// AK-P4a — worker-side tenant RLS adoption, mirroring R-P2b's web helper // (apps/web/app/utils/db/.server/tenantRls.server.ts). The worker cannot import // the web helper (it is bound to the web `db` singleton), so it gets its own thin // wrapper that takes the Prisma client as a parameter (the worker uses // getDbClient() from @toolctrl/db/client.server). // // Sets the tenant context TRANSACTION-LOCALLY (set_config(..., true) == SET LOCAL, // PgBouncer transaction-pooling safe) and runs the queries inside that same // transaction, so the RLS policies (USING/WITH CHECK on // current_setting('app.tenant_id')) bind. Without the context an RLS-enabled // table returns no rows for the restricted app role. // // The helper is generic over the transaction client so callers can keep narrow, // string-typed seam interfaces (decoupled from the generated Prisma enum types, // which keeps the dynamic-import jobs building before native libs are installed). // The only requirement is that the tx exposes `$executeRaw` (a real Prisma // TransactionClient does). /** Minimal surface the helper needs on the transaction client to set the GUC. */ export interface RlsTransactionExecutor { $executeRaw(query: TemplateStringsArray, ...values: unknown[]): Promise; } /** A client whose `$transaction` yields a tx of type `Tx`. */ export interface TransactionCapableClient { $transaction(fn: (tx: Tx) => Promise): Promise; } export async function withTenantRLS( client: TransactionCapableClient, tenantId: string, callback: (tx: Tx) => Promise, ): Promise { if (!tenantId) { throw new Error("withTenantRLS requires a non-empty tenantId"); } return client.$transaction(async (tx) => { await tx.$executeRaw`SELECT set_config('app.tenant_id', ${tenantId}, true)`; return callback(tx); }); }