Files
Jyotisha/frontend/tests/database-local-postgres-session-setup.test.ts
T
jesse-uxandGrok (agent loop) 4c3485bc23 服务器长跑不再堆积取消监听,数据库少走几趟。
报告工人的等待到点就摘掉取消监听。本地数据库缓存表结构,并把设置身份合成一条语句,对照通过后默认打开,写成 off 仍走原来的语句。交付、重算和限流的内存表会过期。登录读缓存默认关闭,要开再设 IDENTITY_SESSION_COOKIE_CACHE=on。

自测:tsc 通过,lint 0 error,点名测试 134 通过,test:db 开关关和开都只有已知的 13 条失败,往返 49 降到 32。

Co-Authored-By: Grok (agent loop)
2026-10-14 03:32:39 +08:00

65 lines
2.5 KiB
TypeScript

import assert from "node:assert/strict";
import test from "node:test";
import {
closeLocalPostgresDataPools,
createLocalPostgresDataClient,
localPostgresPoolForTests,
} from "../src/lib/db/local-postgres-client-core.ts";
import { startPostgresFixture } from "./helpers/postgres-fixture.ts";
const probeSql = `
create or replace function public.session_probe()
returns table(db_user text, claim_sub text)
language sql
stable
as $$
select current_user::text, current_setting('request.jwt.claim.sub', true);
$$;
grant usage on schema public to authenticated, service_role;
grant execute on function public.session_probe() to authenticated, service_role;
`;
test("merged session setup applies the role only inside the transaction", async () => {
const previous = {
cache: process.env.JYOTISHA_PG_METADATA_CACHE,
merged: process.env.JYOTISHA_PG_MERGED_SESSION_SETUP,
};
process.env.JYOTISHA_PG_METADATA_CACHE = "on";
process.env.JYOTISHA_PG_MERGED_SESSION_SETUP = "on";
const fixture = startPostgresFixture();
const identity = {
id: "018f4e6d-7a11-7000-8000-0000000000aa",
email: "person@example.com",
};
try {
fixture.psqlScriptAs("postgres", "postgres-test-password", probeSql);
const url = fixture.connectionUrl("app_runtime", "app-runtime-test-password");
const client = createLocalPostgresDataClient(url, identity, "authenticated");
const probe = await client.rpc("session_probe");
assert.equal(probe.error, null, probe.error?.message);
const row = Array.isArray(probe.data) ? probe.data[0] as { db_user?: string; claim_sub?: string } : null;
assert.equal(row?.db_user, "authenticated");
assert.equal(row?.claim_sub, identity.id);
const pool = localPostgresPoolForTests(url);
const borrowed = await pool.connect();
try {
const after = await borrowed.query<{ db_user: string; claim_sub: string | null }>(
"select current_user as db_user, current_setting('request.jwt.claim.sub', true) as claim_sub",
);
assert.equal(after.rows[0]?.db_user, "app_runtime");
assert.equal(after.rows[0]?.claim_sub ?? "", "");
} finally {
borrowed.release();
}
} finally {
await closeLocalPostgresDataPools();
fixture.stop();
if (previous.cache === undefined) delete process.env.JYOTISHA_PG_METADATA_CACHE;
else process.env.JYOTISHA_PG_METADATA_CACHE = previous.cache;
if (previous.merged === undefined) delete process.env.JYOTISHA_PG_MERGED_SESSION_SETUP;
else process.env.JYOTISHA_PG_MERGED_SESSION_SETUP = previous.merged;
}
});