refactor: lint

This commit is contained in:
Mauricio Siu
2024-12-23 02:28:40 -06:00
parent c6892ba188
commit ed543e5397
37 changed files with 1743 additions and 1745 deletions

View File

@@ -1,11 +1,11 @@
import { relations } from "drizzle-orm";
import {
boolean,
integer,
json,
pgEnum,
pgTable,
text,
boolean,
integer,
json,
pgEnum,
pgTable,
text,
} from "drizzle-orm/pg-core";
import { createInsertSchema } from "drizzle-zod";
import { nanoid } from "nanoid";
@@ -28,493 +28,493 @@ import { sshKeys } from "./ssh-key";
import { generateAppName } from "./utils";
export const sourceType = pgEnum("sourceType", [
"docker",
"git",
"github",
"gitlab",
"bitbucket",
"drop",
"docker",
"git",
"github",
"gitlab",
"bitbucket",
"drop",
]);
export const buildType = pgEnum("buildType", [
"dockerfile",
"heroku_buildpacks",
"paketo_buildpacks",
"nixpacks",
"static",
"dockerfile",
"heroku_buildpacks",
"paketo_buildpacks",
"nixpacks",
"static",
]);
// TODO: refactor this types
export interface HealthCheckSwarm {
Test?: string[] | undefined;
Interval?: number | undefined;
Timeout?: number | undefined;
StartPeriod?: number | undefined;
Retries?: number | undefined;
Test?: string[] | undefined;
Interval?: number | undefined;
Timeout?: number | undefined;
StartPeriod?: number | undefined;
Retries?: number | undefined;
}
export interface RestartPolicySwarm {
Condition?: string | undefined;
Delay?: number | undefined;
MaxAttempts?: number | undefined;
Window?: number | undefined;
Condition?: string | undefined;
Delay?: number | undefined;
MaxAttempts?: number | undefined;
Window?: number | undefined;
}
export interface PlacementSwarm {
Constraints?: string[] | undefined;
Preferences?: Array<{ Spread: { SpreadDescriptor: string } }> | undefined;
MaxReplicas?: number | undefined;
Platforms?:
| Array<{
Architecture: string;
OS: string;
}>
| undefined;
Constraints?: string[] | undefined;
Preferences?: Array<{ Spread: { SpreadDescriptor: string } }> | undefined;
MaxReplicas?: number | undefined;
Platforms?:
| Array<{
Architecture: string;
OS: string;
}>
| undefined;
}
export interface UpdateConfigSwarm {
Parallelism: number;
Delay?: number | undefined;
FailureAction?: string | undefined;
Monitor?: number | undefined;
MaxFailureRatio?: number | undefined;
Order: string;
Parallelism: number;
Delay?: number | undefined;
FailureAction?: string | undefined;
Monitor?: number | undefined;
MaxFailureRatio?: number | undefined;
Order: string;
}
export interface ServiceModeSwarm {
Replicated?: { Replicas?: number | undefined } | undefined;
Global?: {} | undefined;
ReplicatedJob?:
| {
MaxConcurrent?: number | undefined;
TotalCompletions?: number | undefined;
}
| undefined;
GlobalJob?: {} | undefined;
Replicated?: { Replicas?: number | undefined } | undefined;
Global?: {} | undefined;
ReplicatedJob?:
| {
MaxConcurrent?: number | undefined;
TotalCompletions?: number | undefined;
}
| undefined;
GlobalJob?: {} | undefined;
}
export interface NetworkSwarm {
Target?: string | undefined;
Aliases?: string[] | undefined;
DriverOpts?: { [key: string]: string } | undefined;
Target?: string | undefined;
Aliases?: string[] | undefined;
DriverOpts?: { [key: string]: string } | undefined;
}
export interface LabelsSwarm {
[name: string]: string;
[name: string]: string;
}
export const applications = pgTable("application", {
applicationId: text("applicationId")
.notNull()
.primaryKey()
.$defaultFn(() => nanoid()),
name: text("name").notNull(),
appName: text("appName")
.notNull()
.$defaultFn(() => generateAppName("app"))
.unique(),
description: text("description"),
env: text("env"),
previewEnv: text("previewEnv"),
previewBuildArgs: text("previewBuildArgs"),
previewWildcard: text("previewWildcard"),
previewPort: integer("previewPort").default(3000),
previewHttps: boolean("previewHttps").notNull().default(false),
previewPath: text("previewPath").default("/"),
previewCertificateType: certificateType("certificateType")
.notNull()
.default("none"),
previewLimit: integer("previewLimit").default(3),
isPreviewDeploymentsActive: boolean("isPreviewDeploymentsActive").default(
false
),
buildArgs: text("buildArgs"),
memoryReservation: integer("memoryReservation"),
memoryLimit: integer("memoryLimit"),
cpuReservation: integer("cpuReservation"),
cpuLimit: integer("cpuLimit"),
title: text("title"),
enabled: boolean("enabled"),
subtitle: text("subtitle"),
command: text("command"),
refreshToken: text("refreshToken").$defaultFn(() => nanoid()),
sourceType: sourceType("sourceType").notNull().default("github"),
// Github
repository: text("repository"),
owner: text("owner"),
branch: text("branch"),
buildPath: text("buildPath").default("/"),
autoDeploy: boolean("autoDeploy").$defaultFn(() => true),
// Gitlab
gitlabProjectId: integer("gitlabProjectId"),
gitlabRepository: text("gitlabRepository"),
gitlabOwner: text("gitlabOwner"),
gitlabBranch: text("gitlabBranch"),
gitlabBuildPath: text("gitlabBuildPath").default("/"),
gitlabPathNamespace: text("gitlabPathNamespace"),
// Bitbucket
bitbucketRepository: text("bitbucketRepository"),
bitbucketOwner: text("bitbucketOwner"),
bitbucketBranch: text("bitbucketBranch"),
bitbucketBuildPath: text("bitbucketBuildPath").default("/"),
// Docker
username: text("username"),
password: text("password"),
dockerImage: text("dockerImage"),
registryUrl: text("registryUrl"),
// Git
customGitUrl: text("customGitUrl"),
customGitBranch: text("customGitBranch"),
customGitBuildPath: text("customGitBuildPath"),
customGitSSHKeyId: text("customGitSSHKeyId").references(
() => sshKeys.sshKeyId,
{
onDelete: "set null",
}
),
dockerfile: text("dockerfile"),
dockerContextPath: text("dockerContextPath"),
dockerBuildStage: text("dockerBuildStage"),
// Drop
dropBuildPath: text("dropBuildPath"),
// Docker swarm json
healthCheckSwarm: json("healthCheckSwarm").$type<HealthCheckSwarm>(),
restartPolicySwarm: json("restartPolicySwarm").$type<RestartPolicySwarm>(),
placementSwarm: json("placementSwarm").$type<PlacementSwarm>(),
updateConfigSwarm: json("updateConfigSwarm").$type<UpdateConfigSwarm>(),
rollbackConfigSwarm: json("rollbackConfigSwarm").$type<UpdateConfigSwarm>(),
modeSwarm: json("modeSwarm").$type<ServiceModeSwarm>(),
labelsSwarm: json("labelsSwarm").$type<LabelsSwarm>(),
networkSwarm: json("networkSwarm").$type<NetworkSwarm[]>(),
//
replicas: integer("replicas").default(1).notNull(),
applicationStatus: applicationStatus("applicationStatus")
.notNull()
.default("idle"),
buildType: buildType("buildType").notNull().default("nixpacks"),
herokuVersion: text("herokuVersion").default("24"),
publishDirectory: text("publishDirectory"),
createdAt: text("createdAt")
.notNull()
.$defaultFn(() => new Date().toISOString()),
registryId: text("registryId").references(() => registry.registryId, {
onDelete: "set null",
}),
projectId: text("projectId")
.notNull()
.references(() => projects.projectId, { onDelete: "cascade" }),
githubId: text("githubId").references(() => github.githubId, {
onDelete: "set null",
}),
gitlabId: text("gitlabId").references(() => gitlab.gitlabId, {
onDelete: "set null",
}),
bitbucketId: text("bitbucketId").references(() => bitbucket.bitbucketId, {
onDelete: "set null",
}),
serverId: text("serverId").references(() => server.serverId, {
onDelete: "cascade",
}),
applicationId: text("applicationId")
.notNull()
.primaryKey()
.$defaultFn(() => nanoid()),
name: text("name").notNull(),
appName: text("appName")
.notNull()
.$defaultFn(() => generateAppName("app"))
.unique(),
description: text("description"),
env: text("env"),
previewEnv: text("previewEnv"),
previewBuildArgs: text("previewBuildArgs"),
previewWildcard: text("previewWildcard"),
previewPort: integer("previewPort").default(3000),
previewHttps: boolean("previewHttps").notNull().default(false),
previewPath: text("previewPath").default("/"),
previewCertificateType: certificateType("certificateType")
.notNull()
.default("none"),
previewLimit: integer("previewLimit").default(3),
isPreviewDeploymentsActive: boolean("isPreviewDeploymentsActive").default(
false,
),
buildArgs: text("buildArgs"),
memoryReservation: integer("memoryReservation"),
memoryLimit: integer("memoryLimit"),
cpuReservation: integer("cpuReservation"),
cpuLimit: integer("cpuLimit"),
title: text("title"),
enabled: boolean("enabled"),
subtitle: text("subtitle"),
command: text("command"),
refreshToken: text("refreshToken").$defaultFn(() => nanoid()),
sourceType: sourceType("sourceType").notNull().default("github"),
// Github
repository: text("repository"),
owner: text("owner"),
branch: text("branch"),
buildPath: text("buildPath").default("/"),
autoDeploy: boolean("autoDeploy").$defaultFn(() => true),
// Gitlab
gitlabProjectId: integer("gitlabProjectId"),
gitlabRepository: text("gitlabRepository"),
gitlabOwner: text("gitlabOwner"),
gitlabBranch: text("gitlabBranch"),
gitlabBuildPath: text("gitlabBuildPath").default("/"),
gitlabPathNamespace: text("gitlabPathNamespace"),
// Bitbucket
bitbucketRepository: text("bitbucketRepository"),
bitbucketOwner: text("bitbucketOwner"),
bitbucketBranch: text("bitbucketBranch"),
bitbucketBuildPath: text("bitbucketBuildPath").default("/"),
// Docker
username: text("username"),
password: text("password"),
dockerImage: text("dockerImage"),
registryUrl: text("registryUrl"),
// Git
customGitUrl: text("customGitUrl"),
customGitBranch: text("customGitBranch"),
customGitBuildPath: text("customGitBuildPath"),
customGitSSHKeyId: text("customGitSSHKeyId").references(
() => sshKeys.sshKeyId,
{
onDelete: "set null",
},
),
dockerfile: text("dockerfile"),
dockerContextPath: text("dockerContextPath"),
dockerBuildStage: text("dockerBuildStage"),
// Drop
dropBuildPath: text("dropBuildPath"),
// Docker swarm json
healthCheckSwarm: json("healthCheckSwarm").$type<HealthCheckSwarm>(),
restartPolicySwarm: json("restartPolicySwarm").$type<RestartPolicySwarm>(),
placementSwarm: json("placementSwarm").$type<PlacementSwarm>(),
updateConfigSwarm: json("updateConfigSwarm").$type<UpdateConfigSwarm>(),
rollbackConfigSwarm: json("rollbackConfigSwarm").$type<UpdateConfigSwarm>(),
modeSwarm: json("modeSwarm").$type<ServiceModeSwarm>(),
labelsSwarm: json("labelsSwarm").$type<LabelsSwarm>(),
networkSwarm: json("networkSwarm").$type<NetworkSwarm[]>(),
//
replicas: integer("replicas").default(1).notNull(),
applicationStatus: applicationStatus("applicationStatus")
.notNull()
.default("idle"),
buildType: buildType("buildType").notNull().default("nixpacks"),
herokuVersion: text("herokuVersion").default("24"),
publishDirectory: text("publishDirectory"),
createdAt: text("createdAt")
.notNull()
.$defaultFn(() => new Date().toISOString()),
registryId: text("registryId").references(() => registry.registryId, {
onDelete: "set null",
}),
projectId: text("projectId")
.notNull()
.references(() => projects.projectId, { onDelete: "cascade" }),
githubId: text("githubId").references(() => github.githubId, {
onDelete: "set null",
}),
gitlabId: text("gitlabId").references(() => gitlab.gitlabId, {
onDelete: "set null",
}),
bitbucketId: text("bitbucketId").references(() => bitbucket.bitbucketId, {
onDelete: "set null",
}),
serverId: text("serverId").references(() => server.serverId, {
onDelete: "cascade",
}),
});
export const applicationsRelations = relations(
applications,
({ one, many }) => ({
project: one(projects, {
fields: [applications.projectId],
references: [projects.projectId],
}),
deployments: many(deployments),
customGitSSHKey: one(sshKeys, {
fields: [applications.customGitSSHKeyId],
references: [sshKeys.sshKeyId],
}),
domains: many(domains),
mounts: many(mounts),
redirects: many(redirects),
security: many(security),
ports: many(ports),
registry: one(registry, {
fields: [applications.registryId],
references: [registry.registryId],
}),
github: one(github, {
fields: [applications.githubId],
references: [github.githubId],
}),
gitlab: one(gitlab, {
fields: [applications.gitlabId],
references: [gitlab.gitlabId],
}),
bitbucket: one(bitbucket, {
fields: [applications.bitbucketId],
references: [bitbucket.bitbucketId],
}),
server: one(server, {
fields: [applications.serverId],
references: [server.serverId],
}),
previewDeployments: many(previewDeployments),
})
applications,
({ one, many }) => ({
project: one(projects, {
fields: [applications.projectId],
references: [projects.projectId],
}),
deployments: many(deployments),
customGitSSHKey: one(sshKeys, {
fields: [applications.customGitSSHKeyId],
references: [sshKeys.sshKeyId],
}),
domains: many(domains),
mounts: many(mounts),
redirects: many(redirects),
security: many(security),
ports: many(ports),
registry: one(registry, {
fields: [applications.registryId],
references: [registry.registryId],
}),
github: one(github, {
fields: [applications.githubId],
references: [github.githubId],
}),
gitlab: one(gitlab, {
fields: [applications.gitlabId],
references: [gitlab.gitlabId],
}),
bitbucket: one(bitbucket, {
fields: [applications.bitbucketId],
references: [bitbucket.bitbucketId],
}),
server: one(server, {
fields: [applications.serverId],
references: [server.serverId],
}),
previewDeployments: many(previewDeployments),
}),
);
const HealthCheckSwarmSchema = z
.object({
Test: z.array(z.string()).optional(),
Interval: z.number().optional(),
Timeout: z.number().optional(),
StartPeriod: z.number().optional(),
Retries: z.number().optional(),
})
.strict();
.object({
Test: z.array(z.string()).optional(),
Interval: z.number().optional(),
Timeout: z.number().optional(),
StartPeriod: z.number().optional(),
Retries: z.number().optional(),
})
.strict();
const RestartPolicySwarmSchema = z
.object({
Condition: z.string().optional(),
Delay: z.number().optional(),
MaxAttempts: z.number().optional(),
Window: z.number().optional(),
})
.strict();
.object({
Condition: z.string().optional(),
Delay: z.number().optional(),
MaxAttempts: z.number().optional(),
Window: z.number().optional(),
})
.strict();
const PreferenceSchema = z
.object({
Spread: z.object({
SpreadDescriptor: z.string(),
}),
})
.strict();
.object({
Spread: z.object({
SpreadDescriptor: z.string(),
}),
})
.strict();
const PlatformSchema = z
.object({
Architecture: z.string(),
OS: z.string(),
})
.strict();
.object({
Architecture: z.string(),
OS: z.string(),
})
.strict();
const PlacementSwarmSchema = z
.object({
Constraints: z.array(z.string()).optional(),
Preferences: z.array(PreferenceSchema).optional(),
MaxReplicas: z.number().optional(),
Platforms: z.array(PlatformSchema).optional(),
})
.strict();
.object({
Constraints: z.array(z.string()).optional(),
Preferences: z.array(PreferenceSchema).optional(),
MaxReplicas: z.number().optional(),
Platforms: z.array(PlatformSchema).optional(),
})
.strict();
const UpdateConfigSwarmSchema = z
.object({
Parallelism: z.number(),
Delay: z.number().optional(),
FailureAction: z.string().optional(),
Monitor: z.number().optional(),
MaxFailureRatio: z.number().optional(),
Order: z.string(),
})
.strict();
.object({
Parallelism: z.number(),
Delay: z.number().optional(),
FailureAction: z.string().optional(),
Monitor: z.number().optional(),
MaxFailureRatio: z.number().optional(),
Order: z.string(),
})
.strict();
const ReplicatedSchema = z
.object({
Replicas: z.number().optional(),
})
.strict();
.object({
Replicas: z.number().optional(),
})
.strict();
const ReplicatedJobSchema = z
.object({
MaxConcurrent: z.number().optional(),
TotalCompletions: z.number().optional(),
})
.strict();
.object({
MaxConcurrent: z.number().optional(),
TotalCompletions: z.number().optional(),
})
.strict();
const ServiceModeSwarmSchema = z
.object({
Replicated: ReplicatedSchema.optional(),
Global: z.object({}).optional(),
ReplicatedJob: ReplicatedJobSchema.optional(),
GlobalJob: z.object({}).optional(),
})
.strict();
.object({
Replicated: ReplicatedSchema.optional(),
Global: z.object({}).optional(),
ReplicatedJob: ReplicatedJobSchema.optional(),
GlobalJob: z.object({}).optional(),
})
.strict();
const NetworkSwarmSchema = z.array(
z
.object({
Target: z.string().optional(),
Aliases: z.array(z.string()).optional(),
DriverOpts: z.object({}).optional(),
})
.strict()
z
.object({
Target: z.string().optional(),
Aliases: z.array(z.string()).optional(),
DriverOpts: z.object({}).optional(),
})
.strict(),
);
const LabelsSwarmSchema = z.record(z.string());
const createSchema = createInsertSchema(applications, {
appName: z.string(),
createdAt: z.string(),
applicationId: z.string(),
autoDeploy: z.boolean(),
env: z.string().optional(),
buildArgs: z.string().optional(),
name: z.string().min(1),
description: z.string().optional(),
memoryReservation: z.number().optional(),
memoryLimit: z.number().optional(),
cpuReservation: z.number().optional(),
cpuLimit: z.number().optional(),
title: z.string().optional(),
enabled: z.boolean().optional(),
subtitle: z.string().optional(),
dockerImage: z.string().optional(),
username: z.string().optional(),
isPreviewDeploymentsActive: z.boolean().optional(),
password: z.string().optional(),
registryUrl: z.string().optional(),
customGitSSHKeyId: z.string().optional(),
repository: z.string().optional(),
dockerfile: z.string().optional(),
branch: z.string().optional(),
customGitBranch: z.string().optional(),
customGitBuildPath: z.string().optional(),
customGitUrl: z.string().optional(),
buildPath: z.string().optional(),
projectId: z.string(),
sourceType: z.enum(["github", "docker", "git"]).optional(),
applicationStatus: z.enum(["idle", "running", "done", "error"]),
buildType: z.enum([
"dockerfile",
"heroku_buildpacks",
"paketo_buildpacks",
"nixpacks",
"static",
]),
herokuVersion: z.string().optional(),
publishDirectory: z.string().optional(),
owner: z.string(),
healthCheckSwarm: HealthCheckSwarmSchema.nullable(),
restartPolicySwarm: RestartPolicySwarmSchema.nullable(),
placementSwarm: PlacementSwarmSchema.nullable(),
updateConfigSwarm: UpdateConfigSwarmSchema.nullable(),
rollbackConfigSwarm: UpdateConfigSwarmSchema.nullable(),
modeSwarm: ServiceModeSwarmSchema.nullable(),
labelsSwarm: LabelsSwarmSchema.nullable(),
networkSwarm: NetworkSwarmSchema.nullable(),
previewPort: z.number().optional(),
previewEnv: z.string().optional(),
previewBuildArgs: z.string().optional(),
previewWildcard: z.string().optional(),
previewLimit: z.number().optional(),
previewHttps: z.boolean().optional(),
previewPath: z.string().optional(),
previewCertificateType: z.enum(["letsencrypt", "none"]).optional(),
appName: z.string(),
createdAt: z.string(),
applicationId: z.string(),
autoDeploy: z.boolean(),
env: z.string().optional(),
buildArgs: z.string().optional(),
name: z.string().min(1),
description: z.string().optional(),
memoryReservation: z.number().optional(),
memoryLimit: z.number().optional(),
cpuReservation: z.number().optional(),
cpuLimit: z.number().optional(),
title: z.string().optional(),
enabled: z.boolean().optional(),
subtitle: z.string().optional(),
dockerImage: z.string().optional(),
username: z.string().optional(),
isPreviewDeploymentsActive: z.boolean().optional(),
password: z.string().optional(),
registryUrl: z.string().optional(),
customGitSSHKeyId: z.string().optional(),
repository: z.string().optional(),
dockerfile: z.string().optional(),
branch: z.string().optional(),
customGitBranch: z.string().optional(),
customGitBuildPath: z.string().optional(),
customGitUrl: z.string().optional(),
buildPath: z.string().optional(),
projectId: z.string(),
sourceType: z.enum(["github", "docker", "git"]).optional(),
applicationStatus: z.enum(["idle", "running", "done", "error"]),
buildType: z.enum([
"dockerfile",
"heroku_buildpacks",
"paketo_buildpacks",
"nixpacks",
"static",
]),
herokuVersion: z.string().optional(),
publishDirectory: z.string().optional(),
owner: z.string(),
healthCheckSwarm: HealthCheckSwarmSchema.nullable(),
restartPolicySwarm: RestartPolicySwarmSchema.nullable(),
placementSwarm: PlacementSwarmSchema.nullable(),
updateConfigSwarm: UpdateConfigSwarmSchema.nullable(),
rollbackConfigSwarm: UpdateConfigSwarmSchema.nullable(),
modeSwarm: ServiceModeSwarmSchema.nullable(),
labelsSwarm: LabelsSwarmSchema.nullable(),
networkSwarm: NetworkSwarmSchema.nullable(),
previewPort: z.number().optional(),
previewEnv: z.string().optional(),
previewBuildArgs: z.string().optional(),
previewWildcard: z.string().optional(),
previewLimit: z.number().optional(),
previewHttps: z.boolean().optional(),
previewPath: z.string().optional(),
previewCertificateType: z.enum(["letsencrypt", "none"]).optional(),
});
export const apiCreateApplication = createSchema.pick({
name: true,
appName: true,
description: true,
projectId: true,
serverId: true,
name: true,
appName: true,
description: true,
projectId: true,
serverId: true,
});
export const apiFindOneApplication = createSchema
.pick({
applicationId: true,
})
.required();
.pick({
applicationId: true,
})
.required();
export const apiReloadApplication = createSchema
.pick({
appName: true,
applicationId: true,
})
.required();
.pick({
appName: true,
applicationId: true,
})
.required();
export const apiSaveBuildType = createSchema
.pick({
applicationId: true,
buildType: true,
dockerfile: true,
dockerContextPath: true,
dockerBuildStage: true,
herokuVersion: true,
})
.required()
.merge(createSchema.pick({ publishDirectory: true }));
.pick({
applicationId: true,
buildType: true,
dockerfile: true,
dockerContextPath: true,
dockerBuildStage: true,
herokuVersion: true,
})
.required()
.merge(createSchema.pick({ publishDirectory: true }));
export const apiSaveGithubProvider = createSchema
.pick({
applicationId: true,
repository: true,
branch: true,
owner: true,
buildPath: true,
githubId: true,
})
.required();
.pick({
applicationId: true,
repository: true,
branch: true,
owner: true,
buildPath: true,
githubId: true,
})
.required();
export const apiSaveGitlabProvider = createSchema
.pick({
applicationId: true,
gitlabBranch: true,
gitlabBuildPath: true,
gitlabOwner: true,
gitlabRepository: true,
gitlabId: true,
gitlabProjectId: true,
gitlabPathNamespace: true,
})
.required();
.pick({
applicationId: true,
gitlabBranch: true,
gitlabBuildPath: true,
gitlabOwner: true,
gitlabRepository: true,
gitlabId: true,
gitlabProjectId: true,
gitlabPathNamespace: true,
})
.required();
export const apiSaveBitbucketProvider = createSchema
.pick({
bitbucketBranch: true,
bitbucketBuildPath: true,
bitbucketOwner: true,
bitbucketRepository: true,
bitbucketId: true,
applicationId: true,
})
.required();
.pick({
bitbucketBranch: true,
bitbucketBuildPath: true,
bitbucketOwner: true,
bitbucketRepository: true,
bitbucketId: true,
applicationId: true,
})
.required();
export const apiSaveDockerProvider = createSchema
.pick({
dockerImage: true,
applicationId: true,
username: true,
password: true,
registryUrl: true,
})
.required();
.pick({
dockerImage: true,
applicationId: true,
username: true,
password: true,
registryUrl: true,
})
.required();
export const apiSaveGitProvider = createSchema
.pick({
customGitBranch: true,
applicationId: true,
customGitBuildPath: true,
customGitUrl: true,
})
.required()
.merge(
createSchema.pick({
customGitSSHKeyId: true,
})
);
.pick({
customGitBranch: true,
applicationId: true,
customGitBuildPath: true,
customGitUrl: true,
})
.required()
.merge(
createSchema.pick({
customGitSSHKeyId: true,
}),
);
export const apiSaveEnvironmentVariables = createSchema
.pick({
applicationId: true,
env: true,
buildArgs: true,
})
.required();
.pick({
applicationId: true,
env: true,
buildArgs: true,
})
.required();
export const apiFindMonitoringStats = createSchema
.pick({
appName: true,
})
.required();
.pick({
appName: true,
})
.required();
export const apiUpdateApplication = createSchema
.partial()
.extend({
applicationId: z.string().min(1),
})
.omit({ serverId: true });
.partial()
.extend({
applicationId: z.string().min(1),
})
.omit({ serverId: true });

View File

@@ -11,8 +11,8 @@ import { nanoid } from "nanoid";
import { z } from "zod";
import { applications } from "./application";
import { compose } from "./compose";
import { server } from "./server";
import { previewDeployments } from "./preview-deployments";
import { server } from "./server";
export const deploymentStatus = pgEnum("deploymentStatus", [
"running",

View File

@@ -14,8 +14,8 @@ import { z } from "zod";
import { domain } from "../validations/domain";
import { applications } from "./application";
import { compose } from "./compose";
import { certificateType } from "./shared";
import { previewDeployments } from "./preview-deployments";
import { certificateType } from "./shared";
export const domainType = pgEnum("domainType", [
"compose",

View File

@@ -29,4 +29,4 @@ export * from "./github";
export * from "./gitlab";
export * from "./server";
export * from "./utils";
export * from "./preview-deployments";
export * from "./preview-deployments";

View File

@@ -1,13 +1,13 @@
import { relations } from "drizzle-orm";
import { pgTable, text } from "drizzle-orm/pg-core";
import { nanoid } from "nanoid";
import { applications } from "./application";
import { domains } from "./domain";
import { deployments } from "./deployment";
import { createInsertSchema } from "drizzle-zod";
import { nanoid } from "nanoid";
import { z } from "zod";
import { generateAppName } from "./utils";
import { applications } from "./application";
import { deployments } from "./deployment";
import { domains } from "./domain";
import { applicationStatus } from "./shared";
import { generateAppName } from "./utils";
export const previewDeployments = pgTable("preview_deployments", {
previewDeploymentId: text("previewDeploymentId")

View File

@@ -7,12 +7,12 @@ import {
cleanUpSystemPrune,
cleanUpUnusedImages,
} from "../docker/utils";
import { sendDatabaseBackupNotifications } from "../notifications/database-backup";
import { sendDockerCleanupNotifications } from "../notifications/docker-cleanup";
import { runMariadbBackup } from "./mariadb";
import { runMongoBackup } from "./mongo";
import { runMySqlBackup } from "./mysql";
import { runPostgresBackup } from "./postgres";
import { sendDockerCleanupNotifications } from "../notifications/docker-cleanup";
import { sendDatabaseBackupNotifications } from "../notifications/database-backup";
export const initCronJobs = async () => {
console.log("Setting up cron jobs....");

View File

@@ -2,6 +2,7 @@ import { createWriteStream } from "node:fs";
import { join } from "node:path";
import type { InferResultType } from "@dokploy/server/types/with";
import type { CreateServiceOptions } from "dockerode";
import { nanoid } from "nanoid";
import { uploadImage, uploadImageRemoteCommand } from "../cluster/upload";
import {
calculateResources,
@@ -17,7 +18,6 @@ import { buildHeroku, getHerokuCommand } from "./heroku";
import { buildNixpacks, getNixpacksCommand } from "./nixpacks";
import { buildPaketo, getPaketoCommand } from "./paketo";
import { buildStatic, getStaticCommand } from "./static";
import { nanoid } from "nanoid";
// NIXPACKS codeDirectory = where is the path of the code directory
// HEROKU codeDirectory = where is the path of the code directory

View File

@@ -15,528 +15,528 @@ import { spawnAsync } from "../process/spawnAsync";
import { getRemoteDocker } from "../servers/remote-docker";
interface RegistryAuth {
username: string;
password: string;
registryUrl: string;
username: string;
password: string;
registryUrl: string;
}
export const pullImage = async (
dockerImage: string,
onData?: (data: any) => void,
authConfig?: Partial<RegistryAuth>
dockerImage: string,
onData?: (data: any) => void,
authConfig?: Partial<RegistryAuth>,
): Promise<void> => {
try {
if (!dockerImage) {
throw new Error("Docker image not found");
}
try {
if (!dockerImage) {
throw new Error("Docker image not found");
}
if (authConfig?.username && authConfig?.password) {
await spawnAsync(
"docker",
[
"login",
authConfig.registryUrl || "",
"-u",
authConfig.username,
"-p",
authConfig.password,
],
onData
);
}
await spawnAsync("docker", ["pull", dockerImage], onData);
} catch (error) {
throw error;
}
if (authConfig?.username && authConfig?.password) {
await spawnAsync(
"docker",
[
"login",
authConfig.registryUrl || "",
"-u",
authConfig.username,
"-p",
authConfig.password,
],
onData,
);
}
await spawnAsync("docker", ["pull", dockerImage], onData);
} catch (error) {
throw error;
}
};
export const pullRemoteImage = async (
dockerImage: string,
serverId: string,
onData?: (data: any) => void,
authConfig?: Partial<RegistryAuth>
dockerImage: string,
serverId: string,
onData?: (data: any) => void,
authConfig?: Partial<RegistryAuth>,
): Promise<void> => {
try {
if (!dockerImage) {
throw new Error("Docker image not found");
}
try {
if (!dockerImage) {
throw new Error("Docker image not found");
}
const remoteDocker = await getRemoteDocker(serverId);
const remoteDocker = await getRemoteDocker(serverId);
await new Promise((resolve, reject) => {
remoteDocker.pull(
dockerImage,
{ authconfig: authConfig },
(err, stream) => {
if (err) {
reject(err);
return;
}
await new Promise((resolve, reject) => {
remoteDocker.pull(
dockerImage,
{ authconfig: authConfig },
(err, stream) => {
if (err) {
reject(err);
return;
}
remoteDocker.modem.followProgress(
stream as Readable,
(err: Error | null, res) => {
if (!err) {
resolve(res);
}
if (err) {
reject(err);
}
},
(event) => {
onData?.(event);
}
);
}
);
});
} catch (error) {
throw error;
}
remoteDocker.modem.followProgress(
stream as Readable,
(err: Error | null, res) => {
if (!err) {
resolve(res);
}
if (err) {
reject(err);
}
},
(event) => {
onData?.(event);
},
);
},
);
});
} catch (error) {
throw error;
}
};
export const containerExists = async (containerName: string) => {
const container = docker.getContainer(containerName);
try {
await container.inspect();
return true;
} catch (error) {
return false;
}
const container = docker.getContainer(containerName);
try {
await container.inspect();
return true;
} catch (error) {
return false;
}
};
export const stopService = async (appName: string) => {
try {
await execAsync(`docker service scale ${appName}=0 `);
} catch (error) {
console.error(error);
return error;
}
try {
await execAsync(`docker service scale ${appName}=0 `);
} catch (error) {
console.error(error);
return error;
}
};
export const stopServiceRemote = async (serverId: string, appName: string) => {
try {
await execAsyncRemote(serverId, `docker service scale ${appName}=0 `);
} catch (error) {
console.error(error);
return error;
}
try {
await execAsyncRemote(serverId, `docker service scale ${appName}=0 `);
} catch (error) {
console.error(error);
return error;
}
};
export const getContainerByName = (name: string): Promise<ContainerInfo> => {
const opts = {
limit: 1,
filters: {
name: [name],
},
};
return new Promise((resolve, reject) => {
docker.listContainers(opts, (err, containers) => {
if (err) {
reject(err);
} else if (containers?.length === 0) {
reject(new Error(`No container found with name: ${name}`));
} else if (containers && containers?.length > 0 && containers[0]) {
resolve(containers[0]);
}
});
});
const opts = {
limit: 1,
filters: {
name: [name],
},
};
return new Promise((resolve, reject) => {
docker.listContainers(opts, (err, containers) => {
if (err) {
reject(err);
} else if (containers?.length === 0) {
reject(new Error(`No container found with name: ${name}`));
} else if (containers && containers?.length > 0 && containers[0]) {
resolve(containers[0]);
}
});
});
};
export const cleanUpUnusedImages = async (serverId?: string) => {
try {
if (serverId) {
await execAsyncRemote(serverId, "docker image prune --all --force");
} else {
await execAsync("docker image prune --all --force");
}
} catch (error) {
console.error(error);
throw error;
}
try {
if (serverId) {
await execAsyncRemote(serverId, "docker image prune --all --force");
} else {
await execAsync("docker image prune --all --force");
}
} catch (error) {
console.error(error);
throw error;
}
};
export const cleanStoppedContainers = async (serverId?: string) => {
try {
if (serverId) {
await execAsyncRemote(serverId, "docker container prune --force");
} else {
await execAsync("docker container prune --force");
}
} catch (error) {
console.error(error);
throw error;
}
try {
if (serverId) {
await execAsyncRemote(serverId, "docker container prune --force");
} else {
await execAsync("docker container prune --force");
}
} catch (error) {
console.error(error);
throw error;
}
};
export const cleanUpUnusedVolumes = async (serverId?: string) => {
try {
if (serverId) {
await execAsyncRemote(serverId, "docker volume prune --all --force");
} else {
await execAsync("docker volume prune --all --force");
}
} catch (error) {
console.error(error);
throw error;
}
try {
if (serverId) {
await execAsyncRemote(serverId, "docker volume prune --all --force");
} else {
await execAsync("docker volume prune --all --force");
}
} catch (error) {
console.error(error);
throw error;
}
};
export const cleanUpInactiveContainers = async () => {
try {
const containers = await docker.listContainers({ all: true });
const inactiveContainers = containers.filter(
(container) => container.State !== "running"
);
try {
const containers = await docker.listContainers({ all: true });
const inactiveContainers = containers.filter(
(container) => container.State !== "running",
);
for (const container of inactiveContainers) {
await docker.getContainer(container.Id).remove({ force: true });
console.log(`Cleaning up inactive container: ${container.Id}`);
}
} catch (error) {
console.error("Error cleaning up inactive containers:", error);
throw error;
}
for (const container of inactiveContainers) {
await docker.getContainer(container.Id).remove({ force: true });
console.log(`Cleaning up inactive container: ${container.Id}`);
}
} catch (error) {
console.error("Error cleaning up inactive containers:", error);
throw error;
}
};
export const cleanUpDockerBuilder = async (serverId?: string) => {
if (serverId) {
await execAsyncRemote(serverId, "docker builder prune --all --force");
} else {
await execAsync("docker builder prune --all --force");
}
if (serverId) {
await execAsyncRemote(serverId, "docker builder prune --all --force");
} else {
await execAsync("docker builder prune --all --force");
}
};
export const cleanUpSystemPrune = async (serverId?: string) => {
if (serverId) {
await execAsyncRemote(
serverId,
"docker system prune --all --force --volumes"
);
} else {
await execAsync("docker system prune --all --force --volumes");
}
if (serverId) {
await execAsyncRemote(
serverId,
"docker system prune --all --force --volumes",
);
} else {
await execAsync("docker system prune --all --force --volumes");
}
};
export const startService = async (appName: string) => {
try {
await execAsync(`docker service scale ${appName}=1 `);
} catch (error) {
console.error(error);
throw error;
}
try {
await execAsync(`docker service scale ${appName}=1 `);
} catch (error) {
console.error(error);
throw error;
}
};
export const startServiceRemote = async (serverId: string, appName: string) => {
try {
await execAsyncRemote(serverId, `docker service scale ${appName}=1 `);
} catch (error) {
console.error(error);
throw error;
}
try {
await execAsyncRemote(serverId, `docker service scale ${appName}=1 `);
} catch (error) {
console.error(error);
throw error;
}
};
export const removeService = async (
appName: string,
serverId?: string | null,
deleteVolumes = false
appName: string,
serverId?: string | null,
deleteVolumes = false,
) => {
try {
let command: string;
try {
let command: string;
if (deleteVolumes) {
command = `docker service rm --force ${appName}`;
} else {
command = `docker service rm ${appName}`;
}
if (deleteVolumes) {
command = `docker service rm --force ${appName}`;
} else {
command = `docker service rm ${appName}`;
}
if (serverId) {
await execAsyncRemote(serverId, command);
} else {
await execAsync(command);
}
} catch (error) {
return error;
}
if (serverId) {
await execAsyncRemote(serverId, command);
} else {
await execAsync(command);
}
} catch (error) {
return error;
}
};
export const prepareEnvironmentVariables = (
serviceEnv: string | null,
projectEnv?: string | null
serviceEnv: string | null,
projectEnv?: string | null,
) => {
const projectVars = parse(projectEnv ?? "");
const serviceVars = parse(serviceEnv ?? "");
const projectVars = parse(projectEnv ?? "");
const serviceVars = parse(serviceEnv ?? "");
const resolvedVars = Object.entries(serviceVars).map(([key, value]) => {
let resolvedValue = value;
if (projectVars) {
resolvedValue = value.replace(/\$\{\{project\.(.*?)\}\}/g, (_, ref) => {
if (projectVars[ref] !== undefined) {
return projectVars[ref];
}
throw new Error(`Invalid project environment variable: project.${ref}`);
});
}
return `${key}=${resolvedValue}`;
});
const resolvedVars = Object.entries(serviceVars).map(([key, value]) => {
let resolvedValue = value;
if (projectVars) {
resolvedValue = value.replace(/\$\{\{project\.(.*?)\}\}/g, (_, ref) => {
if (projectVars[ref] !== undefined) {
return projectVars[ref];
}
throw new Error(`Invalid project environment variable: project.${ref}`);
});
}
return `${key}=${resolvedValue}`;
});
return resolvedVars;
return resolvedVars;
};
export const prepareBuildArgs = (input: string | null) => {
const pairs = (input ?? "").split("\n");
const pairs = (input ?? "").split("\n");
const jsonObject: Record<string, string> = {};
const jsonObject: Record<string, string> = {};
for (const pair of pairs) {
const [key, value] = pair.split("=");
if (key && value) {
jsonObject[key] = value;
}
}
for (const pair of pairs) {
const [key, value] = pair.split("=");
if (key && value) {
jsonObject[key] = value;
}
}
return jsonObject;
return jsonObject;
};
export const generateVolumeMounts = (mounts: ApplicationNested["mounts"]) => {
if (!mounts || mounts.length === 0) {
return [];
}
if (!mounts || mounts.length === 0) {
return [];
}
return mounts
.filter((mount) => mount.type === "volume")
.map((mount) => ({
Type: "volume" as const,
Source: mount.volumeName || "",
Target: mount.mountPath,
}));
return mounts
.filter((mount) => mount.type === "volume")
.map((mount) => ({
Type: "volume" as const,
Source: mount.volumeName || "",
Target: mount.mountPath,
}));
};
type Resources = {
memoryLimit: number | null;
memoryReservation: number | null;
cpuLimit: number | null;
cpuReservation: number | null;
memoryLimit: number | null;
memoryReservation: number | null;
cpuLimit: number | null;
cpuReservation: number | null;
};
export const calculateResources = ({
memoryLimit,
memoryReservation,
cpuLimit,
cpuReservation,
memoryLimit,
memoryReservation,
cpuLimit,
cpuReservation,
}: Resources): ResourceRequirements => {
return {
Limits: {
MemoryBytes: memoryLimit ?? undefined,
NanoCPUs: cpuLimit ?? undefined,
},
Reservations: {
MemoryBytes: memoryReservation ?? undefined,
NanoCPUs: cpuReservation ?? undefined,
},
};
return {
Limits: {
MemoryBytes: memoryLimit ?? undefined,
NanoCPUs: cpuLimit ?? undefined,
},
Reservations: {
MemoryBytes: memoryReservation ?? undefined,
NanoCPUs: cpuReservation ?? undefined,
},
};
};
export const generateConfigContainer = (application: ApplicationNested) => {
const {
healthCheckSwarm,
restartPolicySwarm,
placementSwarm,
updateConfigSwarm,
rollbackConfigSwarm,
modeSwarm,
labelsSwarm,
replicas,
mounts,
networkSwarm,
} = application;
const {
healthCheckSwarm,
restartPolicySwarm,
placementSwarm,
updateConfigSwarm,
rollbackConfigSwarm,
modeSwarm,
labelsSwarm,
replicas,
mounts,
networkSwarm,
} = application;
const haveMounts = mounts.length > 0;
const haveMounts = mounts.length > 0;
return {
...(healthCheckSwarm && {
HealthCheck: healthCheckSwarm,
}),
...(restartPolicySwarm
? {
RestartPolicy: restartPolicySwarm,
}
: {}),
...(placementSwarm
? {
Placement: placementSwarm,
}
: {
// if app have mounts keep manager as constraint
Placement: {
Constraints: haveMounts ? ["node.role==manager"] : [],
},
}),
...(labelsSwarm && {
Labels: labelsSwarm,
}),
...(modeSwarm
? {
Mode: modeSwarm,
}
: {
// use replicas value if no modeSwarm provided
Mode: {
Replicated: {
Replicas: replicas,
},
},
}),
...(rollbackConfigSwarm && {
RollbackConfig: rollbackConfigSwarm,
}),
...(updateConfigSwarm
? { UpdateConfig: updateConfigSwarm }
: {
// default config if no updateConfigSwarm provided
UpdateConfig: {
Parallelism: 1,
Order: "start-first",
},
}),
...(networkSwarm
? {
Networks: networkSwarm,
}
: {
Networks: [{ Target: "dokploy-network" }],
}),
};
return {
...(healthCheckSwarm && {
HealthCheck: healthCheckSwarm,
}),
...(restartPolicySwarm
? {
RestartPolicy: restartPolicySwarm,
}
: {}),
...(placementSwarm
? {
Placement: placementSwarm,
}
: {
// if app have mounts keep manager as constraint
Placement: {
Constraints: haveMounts ? ["node.role==manager"] : [],
},
}),
...(labelsSwarm && {
Labels: labelsSwarm,
}),
...(modeSwarm
? {
Mode: modeSwarm,
}
: {
// use replicas value if no modeSwarm provided
Mode: {
Replicated: {
Replicas: replicas,
},
},
}),
...(rollbackConfigSwarm && {
RollbackConfig: rollbackConfigSwarm,
}),
...(updateConfigSwarm
? { UpdateConfig: updateConfigSwarm }
: {
// default config if no updateConfigSwarm provided
UpdateConfig: {
Parallelism: 1,
Order: "start-first",
},
}),
...(networkSwarm
? {
Networks: networkSwarm,
}
: {
Networks: [{ Target: "dokploy-network" }],
}),
};
};
export const generateBindMounts = (mounts: ApplicationNested["mounts"]) => {
if (!mounts || mounts.length === 0) {
return [];
}
if (!mounts || mounts.length === 0) {
return [];
}
return mounts
.filter((mount) => mount.type === "bind")
.map((mount) => ({
Type: "bind" as const,
Source: mount.hostPath || "",
Target: mount.mountPath,
}));
return mounts
.filter((mount) => mount.type === "bind")
.map((mount) => ({
Type: "bind" as const,
Source: mount.hostPath || "",
Target: mount.mountPath,
}));
};
export const generateFileMounts = (
appName: string,
service:
| ApplicationNested
| MongoNested
| MariadbNested
| MysqlNested
| PostgresNested
| RedisNested
appName: string,
service:
| ApplicationNested
| MongoNested
| MariadbNested
| MysqlNested
| PostgresNested
| RedisNested,
) => {
const { mounts } = service;
const { APPLICATIONS_PATH } = paths(!!service.serverId);
if (!mounts || mounts.length === 0) {
return [];
}
const { mounts } = service;
const { APPLICATIONS_PATH } = paths(!!service.serverId);
if (!mounts || mounts.length === 0) {
return [];
}
return mounts
.filter((mount) => mount.type === "file")
.map((mount) => {
const fileName = mount.filePath;
const absoluteBasePath = path.resolve(APPLICATIONS_PATH);
const directory = path.join(absoluteBasePath, appName, "files");
const sourcePath = path.join(directory, fileName || "");
return {
Type: "bind" as const,
Source: sourcePath,
Target: mount.mountPath,
};
});
return mounts
.filter((mount) => mount.type === "file")
.map((mount) => {
const fileName = mount.filePath;
const absoluteBasePath = path.resolve(APPLICATIONS_PATH);
const directory = path.join(absoluteBasePath, appName, "files");
const sourcePath = path.join(directory, fileName || "");
return {
Type: "bind" as const,
Source: sourcePath,
Target: mount.mountPath,
};
});
};
export const createFile = async (
outputPath: string,
filePath: string,
content: string
outputPath: string,
filePath: string,
content: string,
) => {
try {
const fullPath = path.join(outputPath, filePath);
if (fullPath.endsWith(path.sep) || filePath.endsWith("/")) {
fs.mkdirSync(fullPath, { recursive: true });
return;
}
try {
const fullPath = path.join(outputPath, filePath);
if (fullPath.endsWith(path.sep) || filePath.endsWith("/")) {
fs.mkdirSync(fullPath, { recursive: true });
return;
}
const directory = path.dirname(fullPath);
fs.mkdirSync(directory, { recursive: true });
fs.writeFileSync(fullPath, content || "");
} catch (error) {
throw error;
}
const directory = path.dirname(fullPath);
fs.mkdirSync(directory, { recursive: true });
fs.writeFileSync(fullPath, content || "");
} catch (error) {
throw error;
}
};
export const encodeBase64 = (content: string) =>
Buffer.from(content, "utf-8").toString("base64");
Buffer.from(content, "utf-8").toString("base64");
export const getCreateFileCommand = (
outputPath: string,
filePath: string,
content: string
outputPath: string,
filePath: string,
content: string,
) => {
const fullPath = path.join(outputPath, filePath);
if (fullPath.endsWith(path.sep) || filePath.endsWith("/")) {
return `mkdir -p ${fullPath};`;
}
const fullPath = path.join(outputPath, filePath);
if (fullPath.endsWith(path.sep) || filePath.endsWith("/")) {
return `mkdir -p ${fullPath};`;
}
const directory = path.dirname(fullPath);
const encodedContent = encodeBase64(content);
return `
const directory = path.dirname(fullPath);
const encodedContent = encodeBase64(content);
return `
mkdir -p ${directory};
echo "${encodedContent}" | base64 -d > "${fullPath}";
`;
};
export const getServiceContainer = async (appName: string) => {
try {
const filter = {
status: ["running"],
label: [`com.docker.swarm.service.name=${appName}`],
};
try {
const filter = {
status: ["running"],
label: [`com.docker.swarm.service.name=${appName}`],
};
const containers = await docker.listContainers({
filters: JSON.stringify(filter),
});
const containers = await docker.listContainers({
filters: JSON.stringify(filter),
});
if (containers.length === 0 || !containers[0]) {
throw new Error(`No container found with name: ${appName}`);
}
if (containers.length === 0 || !containers[0]) {
throw new Error(`No container found with name: ${appName}`);
}
const container = containers[0];
const container = containers[0];
return container;
} catch (error) {
throw error;
}
return container;
} catch (error) {
throw error;
}
};
export const getRemoteServiceContainer = async (
serverId: string,
appName: string
serverId: string,
appName: string,
) => {
try {
const filter = {
status: ["running"],
label: [`com.docker.swarm.service.name=${appName}`],
};
const remoteDocker = await getRemoteDocker(serverId);
const containers = await remoteDocker.listContainers({
filters: JSON.stringify(filter),
});
try {
const filter = {
status: ["running"],
label: [`com.docker.swarm.service.name=${appName}`],
};
const remoteDocker = await getRemoteDocker(serverId);
const containers = await remoteDocker.listContainers({
filters: JSON.stringify(filter),
});
if (containers.length === 0 || !containers[0]) {
throw new Error(`No container found with name: ${appName}`);
}
if (containers.length === 0 || !containers[0]) {
throw new Error(`No container found with name: ${appName}`);
}
const container = containers[0];
const container = containers[0];
return container;
} catch (error) {
throw error;
}
return container;
} catch (error) {
throw error;
}
};