import { getTranslations } from "~/locale/i18next.server"; import { createOwnedTenantWithShkDefaults } from "~/domain/tenant-bootstrap/tenantBootstrapService.server"; import { getUser } from "../../db/users.db.server"; import { getUserInfo } from "../../session.server"; import EventsService from "../../../modules/events/services/.server/EventsService"; import { AccountCreatedDto } from "~/modules/events/dtos/AccountCreatedDto"; import { autosubscribeToTrialOrFreePlan } from "../../services/.server/pricingService"; import { appPath } from "../../app/CanonicalUrlUtils"; import { getRlsExecutionContext, runWithIsolatedUserRlsContext, runWithRlsContext } from "@hivegrid/db/rls-context.server"; import { CatalogError, foundationErrors } from "@hivegrid/foundation"; import { createScopedLogger } from "~/utils/logger.server"; const tenantsApiLogger = createScopedLogger("tenants-api"); type WorkspacePostCommitOperation = "account-created-event" | "trial-autosubscribe"; function runWithPostCommitTenantRlsContext(tenantId: string, userId: string, callback: () => T): T { const current = getRlsExecutionContext(); if (current?.userId === userId && (current.transaction !== undefined || (current.tenantId !== undefined && current.tenantId !== tenantId))) { return runWithIsolatedUserRlsContext(userId, () => runWithRlsContext({ tenantId, userId }, callback)); } return runWithRlsContext({ tenantId, userId }, callback); } async function runWorkspacePostCommitStep({ operation, tenantId, userId, callback, }: { operation: WorkspacePostCommitOperation; tenantId: string; userId: string; callback: () => Promise; }): Promise { try { await callback(); } catch (error) { tenantsApiLogger.warn( { op: `workspace.postcommit.${operation}`, tenantId, userId, err: { name: error instanceof Error ? error.name : "Error" }, }, "Workspace creation committed, but a replayable post-commit step failed." ); throw error; } } export namespace TenantsApi { export async function create({ request, name, slug, creationRequestKey }: { request: Request; name: string; slug?: string; creationRequestKey: string }) { const { t } = await getTranslations(request); const userInfo = await getUserInfo(request); const user = await getUser(userInfo.userId); if (!user) { throw new CatalogError(foundationErrors.notFound, { resource: "workspace-owner" }); } if (!name) { throw new CatalogError(foundationErrors.notFound, { resource: "workspace-creation-input" }); } const { tenant, user: bootstrappedUser, replayed, } = await runWithRlsContext({ userId: user.id }, () => createOwnedTenantWithShkDefaults({ user, name, slug, creationRequestKey, t, }) ); await runWithPostCommitTenantRlsContext(tenant.id, bootstrappedUser.id, async () => { await runWorkspacePostCommitStep({ operation: "trial-autosubscribe", tenantId: tenant.id, userId: bootstrappedUser.id, callback: () => autosubscribeToTrialOrFreePlan({ request, t, tenantId: tenant.id, userId: bootstrappedUser.id, throwOnFailure: true, idempotencyKey: creationRequestKey, }), }); await runWorkspacePostCommitStep({ operation: "account-created-event", tenantId: tenant.id, userId: bootstrappedUser.id, callback: () => EventsService.createIdempotentTenantEvent({ request, event: "account.created", tenantId: tenant.id, userId: bootstrappedUser.id, idempotencyKey: `tenant-bootstrap:${tenant.id}:${creationRequestKey}:account-created`, data: { tenant: { id: tenant.id, name: tenant.name, slug: tenant.slug }, user: { id: bootstrappedUser.id, email: bootstrappedUser.email }, } satisfies AccountCreatedDto, }), }); }); return { redirectTo: appPath({ tenantSlug: tenant.slug, path: "dashboard", mode: "host-aware" }), tenant, user: bootstrappedUser, replayed, }; } }