import { Pool, PoolClient, QueryResult, QueryResultRow, QueryConfig } from 'pg'; import { config } from './config'; import { getTenantDbStore } from './services/tenantDbContext'; import { allowRlsFailOpen, rlsRoleMissingMessage } from './services/rlsFailOpen'; export { allowRlsFailOpen } from './services/rlsFailOpen'; export const pool = new Pool({ connectionString: config.databaseUrl, max: Number(process.env.PG_POOL_MAX || 30), idleTimeoutMillis: Number(process.env.PG_IDLE_TIMEOUT_MS || 30_000), connectionTimeoutMillis: Number(process.env.PG_CONNECT_TIMEOUT_MS || 10_000), }); /** 未包装的原始方法,供 instrumentation / 元数据查询避免递归 */ const rawPoolQuery = pool.query.bind(pool) as Pool['query']; const rawPoolConnect = pool.connect.bind(pool) as Pool['connect']; export async function query(text: string, params: unknown[] = []) { return pool.query(text, params); } const RLS_APP_ROLE = 'canteen_app_rls'; let rlsRoleAvailable: boolean | null = null; /** 不可用的具体原因(角色不存在 / 当前用户无权切换 / 探测失败),供启动自检与 503 文案 */ let rlsRoleUnavailableReason: string | null = null; type SimpleQuery = (text: string, params?: unknown[]) => Promise; /** * 实试一次 `SET LOCAL ROLE`:**角色存在 ≠ 当前连接用户有权切换**。 * * catalog 判定不可靠:生产实测 `pg_auth_members` 里没有 hermes→canteen_app_rls 行, * 但 `pg_has_role(...,'MEMBER')` 为真且实际能切;本地 canteen 是超管、成员表同样为空。 * 故以「真试一次」的行为为准。 * * 事务内用 SAVEPOINT 包裹:实测 SET LOCAL ROLE 成功与失败都能被 * `ROLLBACK TO SAVEPOINT` 干净还原,不污染调用方事务的角色与后续查询。 */ async function probeRlsRoleSwitch(queryFn: SimpleQuery, inTransaction: boolean): Promise { const savepoint = 'sp_rls_role_probe'; try { await queryFn(inTransaction ? `SAVEPOINT ${savepoint}` : 'BEGIN'); } catch (error) { rlsRoleUnavailableReason = `探测事务无法开始:${(error as Error)?.message || error}`; return false; } let ok = true; try { await queryFn(`SET LOCAL ROLE ${RLS_APP_ROLE}`); } catch (error) { ok = false; rlsRoleUnavailableReason = (error as Error)?.message || String(error); } try { if (inTransaction) { await queryFn(`ROLLBACK TO SAVEPOINT ${savepoint}`); await queryFn(`RELEASE SAVEPOINT ${savepoint}`); } else { await queryFn('ROLLBACK'); } } catch (error) { // 还原失败会破坏调用方事务状态,必须显式暴露而不是静默 console.error('[rls] 角色探测后回滚失败:', (error as Error)?.message || error); rlsRoleUnavailableReason = `探测后回滚失败:${(error as Error)?.message || error}`; return false; } if (ok) rlsRoleUnavailableReason = null; return ok; } /** 已持有连接时探测并缓存 RLS 角色(禁止再借 pool,避免死锁) */ async function detectRlsRoleOnConnection(queryFn: SimpleQuery): Promise { if (rlsRoleAvailable !== null) return rlsRoleAvailable; rlsRoleAvailable = await probeRlsRoleSwitch(queryFn, true); return rlsRoleAvailable; } /** * canteen_app_rls 是否**真的可用**:已由迁移 20260736 创建 **且** 当前连接用户可切换(结果缓存)。 * 未持有连接时借一条连接探测(缓存预热后不会走到这里)。 */ export async function isRlsRoleAvailable(): Promise { if (rlsRoleAvailable !== null) return rlsRoleAvailable; const client = await rawPoolConnect(); try { rlsRoleAvailable = await probeRlsRoleSwitch(client.query.bind(client) as SimpleQuery, false); } finally { client.release(); } return rlsRoleAvailable; } /** * 进程启动预热 + 明确自检结论:避免首请求持连接时再借 pool, * 也避免「配置漂移」只表现为请求期的脏 500 / 200 带错。 * * 刻意**不退出进程**:不可用时生产禁止降级,需要 RLS 的三条路径会返回 rls_required(503), * 其余功能仍可用;直接拒启会把局部降级放大成全站宕机。 */ export async function warmRlsRoleCache(): Promise { try { if (await isRlsRoleAvailable()) { console.log(`[rls] ${RLS_APP_ROLE} 可用(已实试 SET LOCAL ROLE)`); return; } const reason = rlsRoleUnavailableReason || '未知原因'; if (allowRlsFailOpen()) { console.warn( `[rls] ${RLS_APP_ROLE} 不可用(${reason});RLS_FAIL_OPEN 已开启,降级 owner 连接(仅非生产)` ); return; } console.error( `[rls] ${RLS_APP_ROLE} 不可用(${reason})。生产禁止应急降级:需要 RLS 的路径` + '(/api/data 批量、备货批量完成、租户数据访问)将返回 rls_required(503)。' + '请确认该角色存在,并把当前数据库用户设为它的成员(或改用超管连接);此处不退出进程以免全站宕机。' ); } catch (error) { console.warn('[rls] warmRlsRoleCache failed:', (error as Error)?.message || error); } } function assertTenantSchemaName(schemaName: string): void { if (!/^tenant_[a-z0-9_-]{2,30}$/.test(schemaName)) { throw new Error(`拒绝非法 search_path schema: ${schemaName}`); } } /** 会话级 search_path + app.branch_code(跨事务保持,连接归还前须复位;FORCE RLS 下 owner 也依赖 branch_code) */ async function applyTenantSearchPathSession( queryFn: SimpleQuery, schemaName: string, branchCode?: string ): Promise { assertTenantSchemaName(schemaName); await queryFn(`SELECT set_config('search_path', $1, false)`, [`${schemaName}, public`]); const code = String(branchCode || '').trim(); if (code) { await queryFn(`SELECT set_config('app.branch_code', $1, false)`, [code]); } } async function resetSearchPathSession(queryFn: SimpleQuery): Promise { await queryFn(`SELECT set_config('search_path', 'public', false)`); await queryFn(`SELECT set_config('app.branch_code', '', false)`); } function rlsRoleMissingError(): Error { return Object.assign(new Error(rlsRoleMissingMessage()), { status: 503, code: 'rls_required', }); } type RequestScopedClient = PoolClient & { __tenantOriginalRelease?: PoolClient['release']; __tenantRequestOwned?: boolean; __tenantRawQuery?: PoolClient['query']; __tenantQueryTail?: Promise; }; /** * 单连接串行化 query:请求级复用 client 时,业务侧 Promise.all(pool.query) * 不可并发写同一条 PG 连接,否则协议错乱 → 上游断连 / ERR_HTTP2_PROTOCOL_ERROR。 */ export function attachSerializedQuery(client: PoolClient): PoolClient { const owned = client as RequestScopedClient; if (owned.__tenantRawQuery) return owned; const rawQuery = client.query.bind(client) as PoolClient['query']; owned.__tenantRawQuery = rawQuery; owned.__tenantQueryTail = Promise.resolve(); const serializedQuery = ((...args: unknown[]) => { const prev = owned.__tenantQueryTail || Promise.resolve(); const resultPromise = prev.then( () => (rawQuery as (...a: unknown[]) => Promise | QueryResult)(...args), () => (rawQuery as (...a: unknown[]) => Promise | QueryResult)(...args) ) as Promise; owned.__tenantQueryTail = resultPromise.then( () => undefined, () => undefined ); return resultPromise; }) as PoolClient['query']; owned.query = serializedQuery; return owned; } /** 供 tenantDbContext:请求级复用连接 */ export async function acquireTenantSessionClient( schemaName: string, branchCode?: string ): Promise { assertTenantSchemaName(schemaName); const client = await rawPoolConnect(); try { await applyTenantSearchPathSession( client.query.bind(client) as SimpleQuery, schemaName, branchCode ); const owned = attachSerializedQuery(client) as RequestScopedClient; owned.__tenantOriginalRelease = client.release.bind(client); owned.__tenantRequestOwned = true; return owned; } catch (error) { client.release(); throw error; } } export async function releaseTenantSessionClient(client: PoolClient): Promise { const owned = client as RequestScopedClient; const rawQuery = owned.__tenantRawQuery || client.query.bind(client); try { await resetSearchPathSession(rawQuery as unknown as SimpleQuery); } catch { // ignore reset failures; still release } const release = owned.__tenantOriginalRelease || client.release.bind(client); owned.__tenantRequestOwned = false; release(); } /** pool.connect 复用请求连接时:release 为空操作,避免提前归还 */ function asRequestScopedConnectFacade(shared: PoolClient): PoolClient { return new Proxy(shared, { get(target, prop, receiver) { if (prop === 'release') { return () => { /* owned by runWithTenantDbContext finally */ }; } const value = Reflect.get(target, prop, receiver); if (typeof value === 'function') { return value.bind(target); } return value; }, }) as PoolClient; } /** 事务内 LOCAL path(显式 BEGIN 后由 wrap 注入) */ async function applyTenantLocals( queryFn: PoolClient['query'], branchCode: string, schemaName: string ): Promise { const q = queryFn as SimpleQuery; assertTenantSchemaName(schemaName); await q(`SELECT set_config('search_path', $1, true)`, [`${schemaName}, public`]); const code = String(branchCode || '').trim(); if (code) { await q(`SELECT set_config('app.branch_code', $1, true)`, [code]); } } function sqlText(configOrText: string | QueryConfig | { text?: string }): string { if (typeof configOrText === 'string') return configOrText; return String(configOrText?.text || ''); } /** * 显式 pool.connect():会话级切 path,不再对每条 SQL 自动 BEGIN/COMMIT。 */ function wrapClientForTenant( client: PoolClient, branchCode: string, schemaName: string ): PoolClient { const rawQuery = client.query.bind(client) as PoolClient['query']; let pathReady: Promise | null = null; const ensureSessionPath = () => { if (!pathReady) { pathReady = applyTenantSearchPathSession( rawQuery as unknown as SimpleQuery, schemaName, branchCode ); } return pathReady; }; const wrappedQuery = async (...args: unknown[]) => { const text = sqlText(args[0] as string | QueryConfig).trim(); const upper = text.toUpperCase(); if (/^BEGIN\b/.test(upper)) { await ensureSessionPath(); const result = await (rawQuery as (...a: unknown[]) => Promise)(...args); await applyTenantLocals(rawQuery, branchCode, schemaName); return result; } if (/^(COMMIT|ROLLBACK)\b/.test(upper)) { return (rawQuery as (...a: unknown[]) => Promise)(...args); } await ensureSessionPath(); return (rawQuery as (...a: unknown[]) => Promise)(...args); }; const patched = client as PoolClient & { query: typeof wrappedQuery; __tenantRawQuery?: PoolClient['query']; }; patched.__tenantRawQuery = rawQuery; patched.query = wrappedQuery as PoolClient['query']; return patched; } function instrumentPool(): void { pool.query = ((...args: unknown[]) => { const store = getTenantDbStore(); if (!store?.schemaName) { return (rawPoolQuery as (...a: unknown[]) => ReturnType)(...args); } // 请求级复用连接:零额外往返 if (store.client) { return (store.client.query as (...a: unknown[]) => ReturnType)( ...(args as Parameters) ); } // 无请求 client:短借 + 会话级 path(不再 BEGIN/COMMIT) return (async () => { const client = await rawPoolConnect(); try { await applyTenantSearchPathSession( client.query.bind(client) as SimpleQuery, store.schemaName!, store.branchCode ); return await (client.query as (...a: unknown[]) => Promise)(...args); } finally { try { await resetSearchPathSession(client.query.bind(client) as SimpleQuery); } catch { // ignore } client.release(); } })(); }) as Pool['query']; pool.connect = ((callback?: (err: Error | undefined, client: PoolClient | undefined, done: (release?: unknown) => void) => void) => { const store = getTenantDbStore(); // 请求已占用 client:复用同一连接,避免池耗尽;release 为空操作(由 ALS finally 归还) if (store?.client && store.schemaName) { const facade = asRequestScopedConnectFacade(store.client); if (callback) { callback(undefined, facade, () => undefined); return; } return Promise.resolve(facade); } if (callback) { return rawPoolConnect((err, client, done) => { if (err || !client) { callback(err, client, done); return; } if (!store?.schemaName) { callback(undefined, client, done); return; } const wrapped = wrapClientForTenant(client, store.branchCode, store.schemaName); const rawQuery = (client as PoolClient & { __tenantRawQuery?: PoolClient['query'] }).__tenantRawQuery || client.query.bind(client); callback(undefined, wrapped, (releaseErr?: unknown) => { void resetSearchPathSession(rawQuery as unknown as SimpleQuery) .catch(() => undefined) .finally(() => done(releaseErr)); }); }); } return (async () => { const client = await rawPoolConnect(); const current = getTenantDbStore(); if (!current?.schemaName) { return client; } const wrapped = wrapClientForTenant(client, current.branchCode, current.schemaName); const rawQuery = (client as PoolClient & { __tenantRawQuery?: PoolClient['query'] }).__tenantRawQuery || client.query.bind(client); const originalRelease = client.release.bind(client); (client as PoolClient).release = ((err?: Error | boolean) => { void resetSearchPathSession(rawQuery as unknown as SimpleQuery) .catch(() => undefined) .finally(() => originalRelease(err as Error | undefined)); }) as PoolClient['release']; return wrapped; })(); }) as Pool['connect']; } instrumentPool(); /** * 以数据库层 RLS 强制的分公司身份执行回调: * 事务内 SET LOCAL ROLE 到非 owner 角色并注入 app.branch_code, * tenant_isolation_* 策略在此连接上真正生效(越权访问在 DB 层被拒绝)。 * * 默认角色缺失时拒绝(关 fail-open)。应急:RLS_FAIL_OPEN=1 降级 owner。 */ export async function runWithBranchRls( branchCode: string, fn: (client: PoolClient) => Promise ): Promise { if (!(await isRlsRoleAvailable())) { if (!allowRlsFailOpen()) { throw rlsRoleMissingError(); } console.warn( '[rls] canteen_app_rls 角色不存在,RLS_FAIL_OPEN=1,降级为 owner 连接' ); const client = await rawPoolConnect(); try { return await fn(client); } finally { client.release(); } } const client = await rawPoolConnect(); try { await client.query('BEGIN'); await client.query(`SET LOCAL ROLE ${RLS_APP_ROLE}`); await client.query(`SELECT set_config('app.branch_code', $1, true)`, [branchCode]); const result = await fn(client); await client.query('COMMIT'); return result; } catch (error) { await client.query('ROLLBACK').catch(() => undefined); throw error; } finally { client.release(); } } /** * 在事务内已持有 client 时注入 RLS 身份(用于 /api/data batch)。 * 调用方负责 BEGIN/COMMIT;本函数只 SET LOCAL ROLE + app.branch_code。 */ export async function applyBranchRlsToClient(client: PoolClient, branchCode: string): Promise { if (!(await detectRlsRoleOnConnection(client.query.bind(client) as SimpleQuery))) { if (!allowRlsFailOpen()) { throw rlsRoleMissingError(); } console.warn( '[rls] canteen_app_rls 角色不存在,RLS_FAIL_OPEN=1,batch 保持 owner' ); return false; } await client.query(`SET LOCAL ROLE ${RLS_APP_ROLE}`); await client.query(`SELECT set_config('app.branch_code', $1, true)`, [branchCode]); return true; } /** 测试/锁内核:绕过 ALS 的原始 connect(查 public.orders 找 branch 等) */ export function getRawPoolConnect(): Pool['connect'] { return rawPoolConnect; } export function getRawPoolQuery(): Pool['query'] { return rawPoolQuery; }