Merge pull request #4777 from Dokploy/perf/dedupe-module-singletons

perf: share db, docker and auth singletons across duplicated bundles
This commit is contained in:
Mauricio Siu
2026-07-09 02:18:42 -06:00
committed by GitHub
4 changed files with 400 additions and 388 deletions
+2 -1
View File
@@ -69,4 +69,5 @@ EXPOSE 3000
HEALTHCHECK --interval=30s --timeout=5s --start-period=60s --retries=5 \ HEALTHCHECK --interval=30s --timeout=5s --start-period=60s --retries=5 \
CMD curl -fs http://localhost:3000/api/trpc/settings.health || exit 1 CMD curl -fs http://localhost:3000/api/trpc/settings.health || exit 1
CMD ["sh", "-c", "pnpm run wait-for-postgres && exec pnpm start"] # Ejecutar node directamente: pnpm como wrapper queda residente (~100MB RSS)
CMD ["sh", "-c", "node -r dotenv/config dist/wait-for-postgres.mjs && node -r dotenv/config dist/migration.mjs && exec node -r dotenv/config dist/server.mjs"]
+11 -1
View File
@@ -81,7 +81,17 @@ const getDockerConfig = (): Docker => {
return new Docker({ ...versionOption }); return new Docker({ ...versionOption });
}; };
export const docker = getDockerConfig(); // Igual que db: el módulo se evalúa una vez por copia bundleada, el cache
// evita crear un cliente (y loguear la detección del socket) por cada una.
const globalForDocker = globalThis as unknown as {
docker?: Docker;
};
if (!globalForDocker.docker) {
globalForDocker.docker = getDockerConfig();
}
export const docker = globalForDocker.docker;
export const paths = (isServer = false) => { export const paths = (isServer = false) => {
const BASE_PATH = const BASE_PATH =
+6 -19
View File
@@ -9,32 +9,19 @@ export * from "./schema";
type Database = PostgresJsDatabase<typeof schema>; type Database = PostgresJsDatabase<typeof schema>;
/** // Este módulo se evalúa varias veces por proceso (copias duplicadas por
* Evita problemas de redeclaración global en monorepos. // esbuild y los chunks de Next); el cache en globalThis garantiza un solo
* No usamos `declare global`. // pool de conexiones por proceso.
*/
const globalForDb = globalThis as unknown as { const globalForDb = globalThis as unknown as {
db?: Database; db?: Database;
}; };
let dbConnection: Database; if (!globalForDb.db) {
globalForDb.db = drizzle(postgres(dbUrl), {
if (process.env.NODE_ENV === "production") {
// En producción no usamos global cache
dbConnection = drizzle(postgres(dbUrl), {
schema, schema,
}); });
} else {
// En desarrollo reutilizamos conexión para evitar múltiples conexiones
if (!globalForDb.db) {
globalForDb.db = drizzle(postgres(dbUrl), {
schema,
});
}
dbConnection = globalForDb.db;
} }
export const db: Database = dbConnection; export const db: Database = globalForDb.db;
export { dbUrl }; export { dbUrl };
+381 -367
View File
@@ -61,404 +61,418 @@ const resolveTrustedOrigins = async () => {
} }
}; };
const { handler, api } = betterAuth({ const createBetterAuth = () =>
database: drizzleAdapter(db, { betterAuth({
provider: "pg", database: drizzleAdapter(db, {
schema: schema, provider: "pg",
}), schema: schema,
disabledPaths: [
"/sso/register",
"/organization/create",
"/organization/update",
"/organization/delete",
...(!IS_CLOUD ? ["/verify-email"] : []),
],
secret: betterAuthSecret,
...(!IS_CLOUD
? {
advanced: {
useSecureCookies: false,
defaultCookieAttributes: {
sameSite: "lax",
secure: false,
httpOnly: true,
path: "/",
},
},
}
: {}),
account: {
accountLinking: {
enabled: true,
async trustedProviders() {
const fromDb = await getTrustedProviders();
return ["github", "google", ...fromDb];
},
allowDifferentEmails: true,
},
},
appName: "Dokploy",
socialProviders: {
github: {
clientId: process.env.GITHUB_CLIENT_ID as string,
clientSecret: process.env.GITHUB_CLIENT_SECRET as string,
},
google: {
clientId: process.env.GOOGLE_CLIENT_ID as string,
clientSecret: process.env.GOOGLE_CLIENT_SECRET as string,
},
},
logger: {
disabled: process.env.NODE_ENV === "production",
},
trustedOrigins: resolveTrustedOrigins,
hooks: {
before: createAuthMiddleware(async (ctx) => {
ctx.context.trustedOrigins = [
...(ctx.context.baseURL ? [new URL(ctx.context.baseURL).origin] : []),
...(await resolveTrustedOrigins()),
].filter(Boolean);
}), }),
}, disabledPaths: [
emailVerification: { "/sso/register",
sendOnSignUp: true, "/organization/create",
autoSignInAfterVerification: true, "/organization/update",
sendOnSignIn: true, "/organization/delete",
sendVerificationEmail: async ({ user, url }) => { ...(!IS_CLOUD ? ["/verify-email"] : []),
if (IS_CLOUD) { ],
await sendVerificationEmail({ secret: betterAuthSecret,
userName: user.name || "User", ...(!IS_CLOUD
? {
advanced: {
useSecureCookies: false,
defaultCookieAttributes: {
sameSite: "lax",
secure: false,
httpOnly: true,
path: "/",
},
},
}
: {}),
account: {
accountLinking: {
enabled: true,
async trustedProviders() {
const fromDb = await getTrustedProviders();
return ["github", "google", ...fromDb];
},
allowDifferentEmails: true,
},
},
appName: "Dokploy",
socialProviders: {
github: {
clientId: process.env.GITHUB_CLIENT_ID as string,
clientSecret: process.env.GITHUB_CLIENT_SECRET as string,
},
google: {
clientId: process.env.GOOGLE_CLIENT_ID as string,
clientSecret: process.env.GOOGLE_CLIENT_SECRET as string,
},
},
logger: {
disabled: process.env.NODE_ENV === "production",
},
trustedOrigins: resolveTrustedOrigins,
hooks: {
before: createAuthMiddleware(async (ctx) => {
ctx.context.trustedOrigins = [
...(ctx.context.baseURL ? [new URL(ctx.context.baseURL).origin] : []),
...(await resolveTrustedOrigins()),
].filter(Boolean);
}),
},
emailVerification: {
sendOnSignUp: true,
autoSignInAfterVerification: true,
sendOnSignIn: true,
sendVerificationEmail: async ({ user, url }) => {
if (IS_CLOUD) {
await sendVerificationEmail({
userName: user.name || "User",
email: user.email,
verificationUrl: url,
});
}
},
},
emailAndPassword: {
enabled: true,
autoSignIn: !IS_CLOUD,
requireEmailVerification:
IS_CLOUD && process.env.NODE_ENV === "production",
password: {
async hash(password) {
return bcrypt.hashSync(password, 10);
},
async verify({ hash, password }) {
return bcrypt.compareSync(password, hash);
},
},
sendResetPassword: async ({ user, url }) => {
await sendEmail({
email: user.email, email: user.email,
verificationUrl: url, subject: "Reset your password",
}); text: `
}
},
},
emailAndPassword: {
enabled: true,
autoSignIn: !IS_CLOUD,
requireEmailVerification: IS_CLOUD && process.env.NODE_ENV === "production",
password: {
async hash(password) {
return bcrypt.hashSync(password, 10);
},
async verify({ hash, password }) {
return bcrypt.compareSync(password, hash);
},
},
sendResetPassword: async ({ user, url }) => {
await sendEmail({
email: user.email,
subject: "Reset your password",
text: `
<p>Click the link to reset your password: <a href="${url}">Reset Password</a></p> <p>Click the link to reset your password: <a href="${url}">Reset Password</a></p>
`, `,
}); });
},
}, },
}, databaseHooks: {
databaseHooks: { user: {
user: { create: {
create: { before: async (_user, context) => {
before: async (_user, context) => { if (!IS_CLOUD) {
if (!IS_CLOUD) { const xDokployToken =
const xDokployToken = context?.request?.headers?.get("x-dokploy-token");
context?.request?.headers?.get("x-dokploy-token"); if (xDokployToken) {
if (xDokployToken) { let invitation: Awaited<ReturnType<typeof getUserByToken>>;
let invitation: Awaited<ReturnType<typeof getUserByToken>>; try {
invitation = await getUserByToken(xDokployToken);
} catch {
throw new APIError("BAD_REQUEST", {
message: "Invalid invitation token",
});
}
if (invitation.isExpired) {
throw new APIError("BAD_REQUEST", {
message: "Invitation has expired",
});
}
if (invitation.status !== "pending") {
throw new APIError("BAD_REQUEST", {
message: "Invitation has already been used",
});
}
if (
_user.email.toLowerCase().trim() !==
invitation.email.toLowerCase().trim()
) {
throw new APIError("BAD_REQUEST", {
message: "Email does not match invitation",
});
}
} else {
const isSSORequest = context?.path.includes("/sso");
const isSCIMRequest = context?.path.includes("/scim");
if (isSSORequest || isSCIMRequest) {
return;
}
const isAdminPresent = await db.query.member.findFirst({
where: eq(schema.member.role, "owner"),
});
if (isAdminPresent) {
throw new APIError("BAD_REQUEST", {
message: "Admin is already created",
});
}
}
}
},
after: async (user, context) => {
const isSSORequest = context?.path.includes("/sso");
const isSCIMRequest = context?.path.includes("/scim");
const isAdminPresent = await db.query.member.findFirst({
where: eq(schema.member.role, "owner"),
});
if (!IS_CLOUD && !isAdminPresent) {
await updateWebServerSettings({
serverIp: await getPublicIpWithFallback(),
});
}
if (IS_CLOUD) {
try { try {
invitation = await getUserByToken(xDokployToken); const hutk = getHubSpotUTK(
} catch { context?.request?.headers?.get("cookie") || undefined,
throw new APIError("BAD_REQUEST", { );
message: "Invalid invitation token", // Cast to include additional fields
}); const userWithFields = user as typeof user & {
} lastName?: string;
if (invitation.isExpired) { };
throw new APIError("BAD_REQUEST", { const hubspotSuccess = await submitToHubSpot(
message: "Invitation has expired", {
}); email: user.email,
} firstName: user.name || "", // name is mapped to firstName column
if (invitation.status !== "pending") { lastName: userWithFields.lastName || "",
throw new APIError("BAD_REQUEST", { },
message: "Invitation has already been used", hutk,
}); );
} if (!hubspotSuccess) {
if ( console.error("Failed to submit to HubSpot");
_user.email.toLowerCase().trim() !== }
invitation.email.toLowerCase().trim() } catch (error) {
) { console.error("Error submitting to HubSpot", error);
throw new APIError("BAD_REQUEST", {
message: "Email does not match invitation",
});
}
} else {
const isSSORequest = context?.path.includes("/sso");
const isSCIMRequest = context?.path.includes("/scim");
if (isSSORequest || isSCIMRequest) {
return;
}
const isAdminPresent = await db.query.member.findFirst({
where: eq(schema.member.role, "owner"),
});
if (isAdminPresent) {
throw new APIError("BAD_REQUEST", {
message: "Admin is already created",
});
} }
} }
}
},
after: async (user, context) => {
const isSSORequest = context?.path.includes("/sso");
const isSCIMRequest = context?.path.includes("/scim");
const isAdminPresent = await db.query.member.findFirst({
where: eq(schema.member.role, "owner"),
});
if (!IS_CLOUD && !isAdminPresent) { if (isSCIMRequest) {
await updateWebServerSettings({ return;
serverIp: await getPublicIpWithFallback(),
});
}
if (IS_CLOUD) {
try {
const hutk = getHubSpotUTK(
context?.request?.headers?.get("cookie") || undefined,
);
// Cast to include additional fields
const userWithFields = user as typeof user & {
lastName?: string;
};
const hubspotSuccess = await submitToHubSpot(
{
email: user.email,
firstName: user.name || "", // name is mapped to firstName column
lastName: userWithFields.lastName || "",
},
hutk,
);
if (!hubspotSuccess) {
console.error("Failed to submit to HubSpot");
}
} catch (error) {
console.error("Error submitting to HubSpot", error);
} }
}
if (isSCIMRequest) { if (IS_CLOUD || !isAdminPresent) {
return; await db.transaction(async (tx) => {
} const organization = await tx
.insert(schema.organization)
.values({
name: "My Organization",
ownerId: user.id,
createdAt: new Date(),
})
.returning()
.then((res) => res[0]);
if (IS_CLOUD || !isAdminPresent) { await tx.insert(schema.member).values({
await db.transaction(async (tx) => { userId: user.id,
const organization = await tx organizationId: organization?.id || "",
.insert(schema.organization) role: "owner",
.values({
name: "My Organization",
ownerId: user.id,
createdAt: new Date(), createdAt: new Date(),
}) isDefault: true, // Mark first organization as default
.returning() });
.then((res) => res[0]); });
} else if (isSSORequest) {
const providerId = context?.params?.providerId;
if (!providerId) {
throw new APIError("BAD_REQUEST", {
message: "Provider ID is required",
});
}
const provider = await db.query.ssoProvider.findFirst({
where: eq(schema.ssoProvider.providerId, providerId),
});
await tx.insert(schema.member).values({ if (!provider) {
throw new APIError("BAD_REQUEST", {
message: "Provider not found",
});
}
await db.insert(schema.member).values({
userId: user.id, userId: user.id,
organizationId: organization?.id || "", organizationId: provider?.organizationId || "",
role: "owner", role: "member",
createdAt: new Date(), createdAt: new Date(),
isDefault: true, // Mark first organization as default isDefault: true,
});
});
} else if (isSSORequest) {
const providerId = context?.params?.providerId;
if (!providerId) {
throw new APIError("BAD_REQUEST", {
message: "Provider ID is required",
}); });
} }
const provider = await db.query.ssoProvider.findFirst({ },
where: eq(schema.ssoProvider.providerId, providerId), },
},
session: {
create: {
before: async (session) => {
// Find the default organization for this user
// Priority: 1) isDefault=true, 2) most recently created
const member = await db.query.member.findFirst({
where: eq(schema.member.userId, session.userId),
orderBy: [
desc(schema.member.isDefault),
desc(schema.member.createdAt),
],
with: {
organization: true,
},
}); });
if (!provider) { return {
throw new APIError("BAD_REQUEST", { data: {
message: "Provider not found", ...session,
}); activeOrganizationId: member?.organization.id,
} },
await db.insert(schema.member).values({ };
userId: user.id, },
organizationId: provider?.organizationId || "", after: async (session) => {
role: "member", const orgId = (
createdAt: new Date(), session as typeof session & { activeOrganizationId?: string }
isDefault: true, ).activeOrganizationId;
if (!orgId) return;
const memberRecord = await db.query.member.findFirst({
where: and(
eq(schema.member.userId, session.userId),
eq(schema.member.organizationId, orgId),
),
with: { user: true },
}); });
} if (!memberRecord) return;
await createAuditLog({
organizationId: orgId,
userId: session.userId,
userEmail: memberRecord.user.email,
userRole: memberRecord.role,
action: "login",
resourceType: "session",
});
},
},
delete: {
after: async (session) => {
const orgId = (
session as typeof session & { activeOrganizationId?: string }
).activeOrganizationId;
if (!orgId) return;
const memberRecord = await db.query.member.findFirst({
where: and(
eq(schema.member.userId, session.userId),
eq(schema.member.organizationId, orgId),
),
with: { user: true },
});
if (!memberRecord) return;
await createAuditLog({
organizationId: orgId,
userId: session.userId,
userEmail: memberRecord.user.email,
userRole: memberRecord.role,
action: "logout",
resourceType: "session",
});
},
}, },
}, },
}, },
session: { session: {
create: { expiresIn: 60 * 60 * 24 * 3,
before: async (session) => { updateAge: 60 * 60 * 24,
// Find the default organization for this user },
// Priority: 1) isDefault=true, 2) most recently created user: {
const member = await db.query.member.findFirst({ modelName: "user",
where: eq(schema.member.userId, session.userId), fields: {
orderBy: [ name: "firstName", // Map better-auth's default 'name' field to 'firstName' column
desc(schema.member.isDefault), },
desc(schema.member.createdAt), additionalFields: {
], role: {
with: { type: "string",
organization: true, // required: true,
}, input: false,
},
ownerId: {
type: "string",
// required: true,
input: false,
},
allowImpersonation: {
fieldName: "allowImpersonation",
type: "boolean",
defaultValue: false,
},
lastName: {
type: "string",
required: false,
input: true,
defaultValue: "",
},
enableEnterpriseFeatures: {
type: "boolean",
required: false,
input: false,
},
isValidEnterpriseLicense: {
type: "boolean",
required: false,
input: false,
},
},
},
plugins: [
apiKey({
enableMetadata: true,
references: "user",
}),
sso({
saml: {
enableInResponseToValidation: false,
},
}),
scim({
beforeSCIMTokenGenerated: async ({ user }) => {
const dbUser = await db.query.user.findFirst({
where: eq(schema.user.id, user.id),
columns: { enableEnterpriseFeatures: true },
}); });
return { if (!dbUser?.enableEnterpriseFeatures) {
data: { throw new APIError("FORBIDDEN", {
...session, message: "SCIM provisioning requires an enterprise license",
activeOrganizationId: member?.organization.id, });
}, }
};
}, },
after: async (session) => { }),
const orgId = ( twoFactor(),
session as typeof session & { activeOrganizationId?: string } organization({
).activeOrganizationId; ac,
if (!orgId) return; roles: {
const memberRecord = await db.query.member.findFirst({ owner: ownerRole,
where: and( admin: adminRole,
eq(schema.member.userId, session.userId), member: memberRole,
eq(schema.member.organizationId, orgId),
),
with: { user: true },
});
if (!memberRecord) return;
await createAuditLog({
organizationId: orgId,
userId: session.userId,
userEmail: memberRecord.user.email,
userRole: memberRecord.role,
action: "login",
resourceType: "session",
});
}, },
}, dynamicAccessControl: {
delete: { enabled: true,
after: async (session) => { maximumRolesPerOrganization: 10,
const orgId = (
session as typeof session & { activeOrganizationId?: string }
).activeOrganizationId;
if (!orgId) return;
const memberRecord = await db.query.member.findFirst({
where: and(
eq(schema.member.userId, session.userId),
eq(schema.member.organizationId, orgId),
),
with: { user: true },
});
if (!memberRecord) return;
await createAuditLog({
organizationId: orgId,
userId: session.userId,
userEmail: memberRecord.user.email,
userRole: memberRecord.role,
action: "logout",
resourceType: "session",
});
}, },
}, }),
}, // Self-hosted needs the admin plugin too: SCIM deactivation (active: false)
}, // maps to the admin plugin's `banned` field and is rejected without it.
session: { // adminRoles: [] keeps every /admin/* endpoint locked on self-hosted.
expiresIn: 60 * 60 * 24 * 3, admin(
updateAge: 60 * 60 * 24, IS_CLOUD
}, ? { adminUserIds: [process.env.USER_ADMIN_ID as string] }
user: { : { adminRoles: [] },
modelName: "user", ),
fields: { ],
name: "firstName", // Map better-auth's default 'name' field to 'firstName' column });
},
additionalFields: {
role: {
type: "string",
// required: true,
input: false,
},
ownerId: {
type: "string",
// required: true,
input: false,
},
allowImpersonation: {
fieldName: "allowImpersonation",
type: "boolean",
defaultValue: false,
},
lastName: {
type: "string",
required: false,
input: true,
defaultValue: "",
},
enableEnterpriseFeatures: {
type: "boolean",
required: false,
input: false,
},
isValidEnterpriseLicense: {
type: "boolean",
required: false,
input: false,
},
},
},
plugins: [
apiKey({
enableMetadata: true,
references: "user",
}),
sso({
saml: {
enableInResponseToValidation: false,
},
}),
scim({
beforeSCIMTokenGenerated: async ({ user }) => {
const dbUser = await db.query.user.findFirst({
where: eq(schema.user.id, user.id),
columns: { enableEnterpriseFeatures: true },
});
if (!dbUser?.enableEnterpriseFeatures) { // Una sola instancia de better-auth por proceso aunque el módulo esté
throw new APIError("FORBIDDEN", { // duplicado en varios bundles.
message: "SCIM provisioning requires an enterprise license", const globalForAuth = globalThis as unknown as {
}); betterAuthInstance?: ReturnType<typeof createBetterAuth>;
} };
},
}), if (!globalForAuth.betterAuthInstance) {
twoFactor(), globalForAuth.betterAuthInstance = createBetterAuth();
organization({ }
ac,
roles: { const { handler, api } = globalForAuth.betterAuthInstance;
owner: ownerRole,
admin: adminRole,
member: memberRole,
},
dynamicAccessControl: {
enabled: true,
maximumRolesPerOrganization: 10,
},
}),
// Self-hosted needs the admin plugin too: SCIM deactivation (active: false)
// maps to the admin plugin's `banned` field and is rejected without it.
// adminRoles: [] keeps every /admin/* endpoint locked on self-hosted.
admin(
IS_CLOUD
? { adminUserIds: [process.env.USER_ADMIN_ID as string] }
: { adminRoles: [] },
),
],
});
const _auth = { const _auth = {
handler, handler,