mirror of
https://github.com/garrytan/gbrain.git
synced 2026-08-17 10:22:34 +00:00
Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6548e5cffc | ||
|
|
0ac3d4da9c |
@@ -151,6 +151,100 @@ export function shouldSpawnAutopilotWorker(args: string[]): boolean {
|
||||
return !args.includes('--no-worker');
|
||||
}
|
||||
|
||||
/**
|
||||
* #1525 — positional subcommand translation.
|
||||
*
|
||||
* Pre-fix, `gbrain autopilot status` silently fell through to "start daemon"
|
||||
* because `runAutopilot()` only branched on flag forms (`--status`, etc.).
|
||||
* `status` was treated as a stray positional and ignored.
|
||||
*
|
||||
* This translator maps known positional subcommands to their flag form so
|
||||
* `autopilot status` is equivalent to `autopilot --status`, then rejects
|
||||
* any unrecognized positional with a fail-loud error before any side
|
||||
* effect (lockfile, daemon spawn, sync dispatch) runs.
|
||||
*
|
||||
* Scope decisions:
|
||||
* - Known aliases: `status` → `--status`, `install` → `--install`,
|
||||
* `uninstall` → `--uninstall`, `start` → (drop; default daemon launch).
|
||||
* - `stop` is intentionally NOT aliased here. Stopping a running daemon
|
||||
* is a new behavior (read PID from lock, SIGTERM, drain) that deserves
|
||||
* its own design and PR. Users typing `gbrain autopilot stop` today get
|
||||
* the unknown-positional error with the canonical alternatives.
|
||||
* - At most one positional allowed; multiple positionals fail loud.
|
||||
*/
|
||||
// Every flag that consumes the NEXT argv token. Missing one here makes the
|
||||
// translator misread the flag's value as a positional subcommand and exit 2
|
||||
// (e.g. `--install --target linux-cron`). Keep in sync with parseArg call sites.
|
||||
const AUTOPILOT_VALUE_FLAGS = new Set(['--repo', '--interval', '--target']);
|
||||
const AUTOPILOT_POSITIONAL_ALIASES: Record<string, string | null> = {
|
||||
status: '--status',
|
||||
install: '--install',
|
||||
uninstall: '--uninstall',
|
||||
start: null, // drop the positional; default behavior is daemon launch
|
||||
};
|
||||
|
||||
export type PositionalTranslation =
|
||||
| { ok: true; args: string[] }
|
||||
| {
|
||||
ok: false;
|
||||
reason: 'unknown_subcommand' | 'multiple_subcommands';
|
||||
message: string;
|
||||
};
|
||||
|
||||
export function translatePositionalSubcommands(args: string[]): PositionalTranslation {
|
||||
const out: string[] = [];
|
||||
let positionalSeen = false;
|
||||
let i = 0;
|
||||
while (i < args.length) {
|
||||
const a = args[i];
|
||||
if (AUTOPILOT_VALUE_FLAGS.has(a)) {
|
||||
// Pass through the flag and its value untouched. If the value is
|
||||
// missing at end-of-argv, fall through so the existing parseArg
|
||||
// path can report the broken usage.
|
||||
out.push(a);
|
||||
if (i + 1 < args.length) {
|
||||
out.push(args[i + 1]);
|
||||
i += 2;
|
||||
} else {
|
||||
i += 1;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (a.startsWith('-')) {
|
||||
out.push(a);
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
// Positional subcommand.
|
||||
if (positionalSeen) {
|
||||
const known = Object.keys(AUTOPILOT_POSITIONAL_ALIASES).join(', ');
|
||||
return {
|
||||
ok: false,
|
||||
reason: 'multiple_subcommands',
|
||||
message: `Multiple subcommands given. Use only one of: ${known}.`,
|
||||
};
|
||||
}
|
||||
positionalSeen = true;
|
||||
if (a in AUTOPILOT_POSITIONAL_ALIASES) {
|
||||
const alias = AUTOPILOT_POSITIONAL_ALIASES[a];
|
||||
if (alias) out.push(alias);
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
const known = Object.keys(AUTOPILOT_POSITIONAL_ALIASES).join(', ');
|
||||
return {
|
||||
ok: false,
|
||||
reason: 'unknown_subcommand',
|
||||
message:
|
||||
`Unknown subcommand: \`${a}\`.\n` +
|
||||
`Allowed subcommands: ${known}.\n` +
|
||||
`Or use the flag form: --status, --install, --uninstall.\n` +
|
||||
`Run \`gbrain autopilot --help\` for full usage.`,
|
||||
};
|
||||
}
|
||||
return { ok: true, args: out };
|
||||
}
|
||||
|
||||
export function isPidAlive(pid: number): boolean {
|
||||
if (!Number.isFinite(pid) || pid <= 0) return false;
|
||||
try {
|
||||
@@ -363,6 +457,11 @@ export async function runAutopilot(engine: BrainEngine, args: string[]) {
|
||||
' gbrain autopilot --install [--repo <path>]\n' +
|
||||
' gbrain autopilot --uninstall\n' +
|
||||
' gbrain autopilot --status [--json]\n\n' +
|
||||
'Subcommand aliases:\n' +
|
||||
' gbrain autopilot status → --status\n' +
|
||||
' gbrain autopilot install → --install\n' +
|
||||
' gbrain autopilot uninstall → --uninstall\n' +
|
||||
' gbrain autopilot start → (default daemon launch)\n\n' +
|
||||
'Self-maintaining brain daemon. Runs the full maintenance cycle\n' +
|
||||
'(lint + backlinks + sync + extract + embed + orphans) on an interval.\n\n' +
|
||||
'For a one-shot cron-triggered cycle, see `gbrain dream`.',
|
||||
@@ -370,6 +469,16 @@ export async function runAutopilot(engine: BrainEngine, args: string[]) {
|
||||
return;
|
||||
}
|
||||
|
||||
// #1525: translate positional subcommands to their flag form BEFORE any
|
||||
// side effect (lockfile, daemon spawn, sync dispatch). Unknown positionals
|
||||
// fail loud here rather than silently starting the daemon.
|
||||
const translated = translatePositionalSubcommands(args);
|
||||
if (!translated.ok) {
|
||||
console.error(translated.message);
|
||||
process.exit(2);
|
||||
}
|
||||
args = translated.args;
|
||||
|
||||
if (args.includes('--install')) {
|
||||
await installDaemon(engine, args);
|
||||
return;
|
||||
|
||||
@@ -5565,78 +5565,30 @@ export class PostgresEngine implements BrainEngine {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* perf (#1694 by @Omerbahari): process-lifetime config cache. A single
|
||||
* search fires ~85 getConfig() reads (loadConfigWithEngine x2, plus
|
||||
* mode/cache/intent/rerank/graph-signals resolvers). On a remote pooler
|
||||
* each read is a round-trip; serial they dominate query latency and can
|
||||
* push the op handler past cli.ts's 10s disconnect force-exit, truncating
|
||||
* stdout. First read batch-loads the whole `config` table into this Map
|
||||
* (inside the same connRetry posture as the per-key read — #1603/#1891);
|
||||
* setConfig/unsetConfig write through. TTL bounds staleness for
|
||||
* multi-writer processes; GBRAIN_CONFIG_CACHE_TTL_MS=0 disables.
|
||||
* Only present keys are stored — Map.has() distinguishes known-absent.
|
||||
*/
|
||||
private _configCache: Map<string, string> | null = null;
|
||||
private _configCacheLoadedAt = 0;
|
||||
private _configCacheLoad: Promise<void> | null = null;
|
||||
private get _configCacheTtlMs(): number {
|
||||
const raw = process.env.GBRAIN_CONFIG_CACHE_TTL_MS;
|
||||
if (raw !== undefined) {
|
||||
const n = parseInt(raw, 10);
|
||||
if (Number.isFinite(n) && n >= 0) return n;
|
||||
}
|
||||
return 30_000;
|
||||
}
|
||||
|
||||
async getConfig(key: string): Promise<string | null> {
|
||||
// #1603: a transient pooler drop on this read used to throw / fall through
|
||||
// to defaults silently — which on remote Postgres surfaces as the wrong
|
||||
// search mode/knobs and empty-stdout queries. Both the batch load and the
|
||||
// cache-off per-key read keep the connRetry reconnect posture.
|
||||
const ttl = this._configCacheTtlMs;
|
||||
if (ttl === 0) {
|
||||
return this.connRetry(async () => {
|
||||
const rows = await this.sql`SELECT value FROM config WHERE key = ${key}`;
|
||||
return rows.length > 0 ? (rows[0].value as string) : null;
|
||||
});
|
||||
}
|
||||
if (this._configCache === null || Date.now() - this._configCacheLoadedAt >= ttl) {
|
||||
// Single-flight: concurrent cold reads share one batch load.
|
||||
this._configCacheLoad ??= this.connRetry(async () => {
|
||||
const rows = await this.sql`SELECT key, value FROM config` as unknown as
|
||||
Array<{ key: string; value: string | null }>;
|
||||
const map = new Map<string, string>();
|
||||
for (const r of rows) if (r.value != null) map.set(r.key, r.value);
|
||||
this._configCache = map;
|
||||
this._configCacheLoadedAt = Date.now();
|
||||
}).finally(() => {
|
||||
this._configCacheLoad = null;
|
||||
});
|
||||
await this._configCacheLoad;
|
||||
}
|
||||
return this._configCache!.has(key) ? this._configCache!.get(key)! : null;
|
||||
// search mode/knobs and empty-stdout queries.
|
||||
return this.connRetry(async () => {
|
||||
const rows = await this.sql`SELECT value FROM config WHERE key = ${key}`;
|
||||
return rows.length > 0 ? (rows[0].value as string) : null;
|
||||
});
|
||||
}
|
||||
|
||||
async setConfig(key: string, value: string): Promise<void> {
|
||||
await this.connRetry(async () => {
|
||||
return this.connRetry(async () => {
|
||||
await this.sql`
|
||||
INSERT INTO config (key, value) VALUES (${key}, ${value})
|
||||
ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value
|
||||
`;
|
||||
});
|
||||
// Write-through so a long-lived process never serves stale config.
|
||||
this._configCache?.set(key, value);
|
||||
}
|
||||
|
||||
async unsetConfig(key: string): Promise<number> {
|
||||
const count = await this.connRetry(async () => {
|
||||
return this.connRetry(async () => {
|
||||
const result = await this.sql`DELETE FROM config WHERE key = ${key}` as unknown as { count: number };
|
||||
return result.count ?? 0;
|
||||
});
|
||||
// Write-through: known-absent, so the cache doesn't serve a stale value.
|
||||
this._configCache?.delete(key);
|
||||
return count;
|
||||
}
|
||||
|
||||
async listConfigKeys(prefix: string): Promise<string[]> {
|
||||
|
||||
@@ -0,0 +1,197 @@
|
||||
/**
|
||||
* Tests for translatePositionalSubcommands() — the v0.41.x #1525 fix that
|
||||
* prevents `gbrain autopilot status` from silently starting the daemon.
|
||||
*
|
||||
* IRON RULE regression guard: the exact ticket repro (`gbrain autopilot
|
||||
* status`) MUST translate to `--status`, not fall through to the default
|
||||
* daemon launch. Verified by the "ticket-exact repro" case below.
|
||||
*/
|
||||
|
||||
import { describe, test, expect } from 'bun:test';
|
||||
import { translatePositionalSubcommands } from '../src/commands/autopilot.ts';
|
||||
|
||||
describe('translatePositionalSubcommands — known aliases', () => {
|
||||
test('IRON RULE — `autopilot status` translates to `--status` (ticket #1525 repro)', () => {
|
||||
const r = translatePositionalSubcommands(['status']);
|
||||
expect(r.ok).toBe(true);
|
||||
if (r.ok) expect(r.args).toEqual(['--status']);
|
||||
});
|
||||
|
||||
test('`install` translates to `--install`', () => {
|
||||
const r = translatePositionalSubcommands(['install']);
|
||||
expect(r.ok).toBe(true);
|
||||
if (r.ok) expect(r.args).toEqual(['--install']);
|
||||
});
|
||||
|
||||
test('`uninstall` translates to `--uninstall`', () => {
|
||||
const r = translatePositionalSubcommands(['uninstall']);
|
||||
expect(r.ok).toBe(true);
|
||||
if (r.ok) expect(r.args).toEqual(['--uninstall']);
|
||||
});
|
||||
|
||||
test('`start` drops the positional (default daemon launch)', () => {
|
||||
const r = translatePositionalSubcommands(['start']);
|
||||
expect(r.ok).toBe(true);
|
||||
if (r.ok) expect(r.args).toEqual([]);
|
||||
});
|
||||
|
||||
test('`start --json` drops only the positional, keeps the flag', () => {
|
||||
const r = translatePositionalSubcommands(['start', '--json']);
|
||||
expect(r.ok).toBe(true);
|
||||
if (r.ok) expect(r.args).toEqual(['--json']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('translatePositionalSubcommands — flag/positional interleaving', () => {
|
||||
test('`status --json` preserves the trailing flag', () => {
|
||||
const r = translatePositionalSubcommands(['status', '--json']);
|
||||
expect(r.ok).toBe(true);
|
||||
if (r.ok) expect(r.args).toEqual(['--status', '--json']);
|
||||
});
|
||||
|
||||
test('`--json status` preserves the leading flag', () => {
|
||||
const r = translatePositionalSubcommands(['--json', 'status']);
|
||||
expect(r.ok).toBe(true);
|
||||
if (r.ok) expect(r.args).toEqual(['--json', '--status']);
|
||||
});
|
||||
|
||||
test('`--repo /foo status` does not mis-classify the path as positional', () => {
|
||||
const r = translatePositionalSubcommands(['--repo', '/foo', 'status']);
|
||||
expect(r.ok).toBe(true);
|
||||
if (r.ok) expect(r.args).toEqual(['--repo', '/foo', '--status']);
|
||||
});
|
||||
|
||||
test('`--interval 300 install` does not mis-classify the number as positional', () => {
|
||||
const r = translatePositionalSubcommands(['--interval', '300', 'install']);
|
||||
expect(r.ok).toBe(true);
|
||||
if (r.ok) expect(r.args).toEqual(['--interval', '300', '--install']);
|
||||
});
|
||||
|
||||
test('`--install --target linux-cron` does not mis-classify the target as positional', () => {
|
||||
// --target is installDaemon's value flag; its value must never be read
|
||||
// as a positional subcommand (regression guard for the review fix).
|
||||
const r = translatePositionalSubcommands(['--install', '--target', 'linux-cron']);
|
||||
expect(r.ok).toBe(true);
|
||||
if (r.ok) expect(r.args).toEqual(['--install', '--target', 'linux-cron']);
|
||||
});
|
||||
|
||||
test('`install --target macos` keeps the alias translation and the target value', () => {
|
||||
const r = translatePositionalSubcommands(['install', '--target', 'macos']);
|
||||
expect(r.ok).toBe(true);
|
||||
if (r.ok) expect(r.args).toEqual(['--install', '--target', 'macos']);
|
||||
});
|
||||
|
||||
test('value-flag at end of argv with missing value passes through (so parseArg can report it)', () => {
|
||||
const r = translatePositionalSubcommands(['--repo']);
|
||||
expect(r.ok).toBe(true);
|
||||
if (r.ok) expect(r.args).toEqual(['--repo']);
|
||||
});
|
||||
|
||||
test('value-flag whose value looks like an alias is NOT translated', () => {
|
||||
// `--repo status` means "use repo path 'status'", not "show status".
|
||||
// Translator must not destructure the value of --repo.
|
||||
const r = translatePositionalSubcommands(['--repo', 'status']);
|
||||
expect(r.ok).toBe(true);
|
||||
if (r.ok) expect(r.args).toEqual(['--repo', 'status']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('translatePositionalSubcommands — pass-through cases', () => {
|
||||
test('empty args returns empty args', () => {
|
||||
const r = translatePositionalSubcommands([]);
|
||||
expect(r.ok).toBe(true);
|
||||
if (r.ok) expect(r.args).toEqual([]);
|
||||
});
|
||||
|
||||
test('flag-only invocation passes through unchanged', () => {
|
||||
const r = translatePositionalSubcommands(['--status', '--json']);
|
||||
expect(r.ok).toBe(true);
|
||||
if (r.ok) expect(r.args).toEqual(['--status', '--json']);
|
||||
});
|
||||
|
||||
test('short flag `-h` passes through unchanged', () => {
|
||||
const r = translatePositionalSubcommands(['-h']);
|
||||
expect(r.ok).toBe(true);
|
||||
if (r.ok) expect(r.args).toEqual(['-h']);
|
||||
});
|
||||
|
||||
test('all known bare flags pass through unchanged', () => {
|
||||
const flags = ['--help', '--install', '--uninstall', '--status', '--json', '--inline', '--no-worker'];
|
||||
const r = translatePositionalSubcommands(flags);
|
||||
expect(r.ok).toBe(true);
|
||||
if (r.ok) expect(r.args).toEqual(flags);
|
||||
});
|
||||
});
|
||||
|
||||
describe('translatePositionalSubcommands — rejection of unknown positionals', () => {
|
||||
test('unknown positional `foo` fails with reason=unknown_subcommand + structured message', () => {
|
||||
const r = translatePositionalSubcommands(['foo']);
|
||||
expect(r.ok).toBe(false);
|
||||
if (!r.ok) {
|
||||
expect(r.reason).toBe('unknown_subcommand');
|
||||
expect(r.message).toContain('Unknown subcommand: `foo`');
|
||||
expect(r.message).toContain('status');
|
||||
expect(r.message).toContain('install');
|
||||
expect(r.message).toContain('uninstall');
|
||||
expect(r.message).toContain('--help');
|
||||
}
|
||||
});
|
||||
|
||||
test('unknown positional `stop` fails with reason=unknown_subcommand (NOT silently aliased)', () => {
|
||||
// Stop is mentioned in the ticket but deliberately NOT aliased in this
|
||||
// PR — stopping a running daemon is a new behavior, not just an alias.
|
||||
// Until that feature lands separately, `stop` must fail loud rather
|
||||
// than starting the daemon (the bug we're fixing).
|
||||
const r = translatePositionalSubcommands(['stop']);
|
||||
expect(r.ok).toBe(false);
|
||||
if (!r.ok) {
|
||||
expect(r.reason).toBe('unknown_subcommand');
|
||||
expect(r.message).toContain('Unknown subcommand: `stop`');
|
||||
}
|
||||
});
|
||||
|
||||
test('unknown positional `status-detail` (close-but-not-matching) fails', () => {
|
||||
const r = translatePositionalSubcommands(['status-detail']);
|
||||
expect(r.ok).toBe(false);
|
||||
if (!r.ok) {
|
||||
expect(r.reason).toBe('unknown_subcommand');
|
||||
expect(r.message).toContain('Unknown subcommand: `status-detail`');
|
||||
}
|
||||
});
|
||||
|
||||
test('multiple positionals fail with reason=multiple_subcommands (`start install`)', () => {
|
||||
const r = translatePositionalSubcommands(['start', 'install']);
|
||||
expect(r.ok).toBe(false);
|
||||
if (!r.ok) {
|
||||
expect(r.reason).toBe('multiple_subcommands');
|
||||
expect(r.message).toContain('Multiple subcommands');
|
||||
}
|
||||
});
|
||||
|
||||
test('multiple positionals fail even when both are known aliases (`status install`)', () => {
|
||||
const r = translatePositionalSubcommands(['status', 'install']);
|
||||
expect(r.ok).toBe(false);
|
||||
if (!r.ok) {
|
||||
expect(r.reason).toBe('multiple_subcommands');
|
||||
expect(r.message).toContain('Multiple subcommands');
|
||||
}
|
||||
});
|
||||
|
||||
test('known-then-unknown rejects with multiple_subcommands (first-positional-wins)', () => {
|
||||
// First positional is known, second is not. Rejection comes from the
|
||||
// multiple-positional rule, which fires before the unknown check; the
|
||||
// intent is "only one subcommand allowed."
|
||||
const r = translatePositionalSubcommands(['status', 'garbage']);
|
||||
expect(r.ok).toBe(false);
|
||||
if (!r.ok) expect(r.reason).toBe('multiple_subcommands');
|
||||
});
|
||||
|
||||
test('unknown-then-known rejects on the unknown (unknown fires before second-positional check)', () => {
|
||||
const r = translatePositionalSubcommands(['garbage', 'status']);
|
||||
expect(r.ok).toBe(false);
|
||||
if (!r.ok) {
|
||||
expect(r.reason).toBe('unknown_subcommand');
|
||||
expect(r.message).toContain('garbage');
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -29,13 +29,6 @@ if (existsSync(envPath)) {
|
||||
}
|
||||
}
|
||||
|
||||
// E2E suites seed/rewrite the config table via raw SQL and expect engine
|
||||
// reads to see it immediately; disable the process-lifetime config cache
|
||||
// (#1694) so read semantics match pre-cache behavior. Spawned CLI
|
||||
// subprocesses inherit this. Cache semantics are pinned by
|
||||
// test/postgres-engine-config-cache.test.ts.
|
||||
process.env.GBRAIN_CONFIG_CACHE_TTL_MS ??= '0';
|
||||
|
||||
const DATABASE_URL = process.env.DATABASE_URL;
|
||||
const FIXTURES_DIR = resolve(import.meta.dir, 'fixtures');
|
||||
|
||||
|
||||
@@ -1,112 +0,0 @@
|
||||
/**
|
||||
* Process-lifetime config cache (#1694 takeover, by @Omerbahari).
|
||||
*
|
||||
* A single search fires ~85 getConfig() reads; on a remote pooler each is a
|
||||
* round-trip. The first read now batch-loads the whole `config` table into a
|
||||
* Map; setConfig/unsetConfig write through; TTL bounds multi-writer
|
||||
* staleness; GBRAIN_CONFIG_CACHE_TTL_MS=0 restores per-key reads.
|
||||
*
|
||||
* Pure: stubs `_sql` with a call-counting fake; no real DB.
|
||||
*/
|
||||
|
||||
import { describe, it, expect } from 'bun:test';
|
||||
import { PostgresEngine } from '../src/core/postgres-engine.ts';
|
||||
import { withEnv } from './helpers/with-env.ts';
|
||||
|
||||
const FAST_RETRY = { maxRetries: 3, delayMs: 1, delayMaxMs: 1, jitter: 'none' as const };
|
||||
|
||||
/** Engine whose `sql` records every query's template strings and returns `rows`. */
|
||||
function makeEngine(rows: unknown[]) {
|
||||
const e = new PostgresEngine();
|
||||
const calls: string[] = [];
|
||||
(e as unknown as { _connectionStyle: string })._connectionStyle = 'instance';
|
||||
(e as unknown as { _bulkRetryOptsCache: unknown })._bulkRetryOptsCache = FAST_RETRY;
|
||||
(e as unknown as { _sql: unknown })._sql = (strings: TemplateStringsArray) => {
|
||||
calls.push(strings.join('?'));
|
||||
return Promise.resolve(rows);
|
||||
};
|
||||
return { engine: e, calls };
|
||||
}
|
||||
|
||||
/** Run `fn` with GBRAIN_CONFIG_CACHE_TTL_MS set (or cleared when undefined). */
|
||||
const withTtl = (ttl: string | undefined, fn: () => Promise<void>) =>
|
||||
withEnv({ GBRAIN_CONFIG_CACHE_TTL_MS: ttl }, fn);
|
||||
|
||||
describe('PostgresEngine config cache (#1694)', () => {
|
||||
it('batch-loads once and serves repeat reads from the cache', () => withTtl(undefined, async () => {
|
||||
const { engine, calls } = makeEngine([
|
||||
{ key: 'search.mode', value: 'balanced' },
|
||||
{ key: 'embedding_multimodal', value: 'true' },
|
||||
]);
|
||||
expect(await engine.getConfig('search.mode')).toBe('balanced');
|
||||
expect(await engine.getConfig('embedding_multimodal')).toBe('true');
|
||||
expect(await engine.getConfig('search.mode')).toBe('balanced');
|
||||
// One SELECT total — this is the whole point of the fix.
|
||||
expect(calls.length).toBe(1);
|
||||
expect(calls[0]).toContain('SELECT key, value FROM config');
|
||||
}));
|
||||
|
||||
it('returns null for a known-absent key without an extra round-trip', () => withTtl(undefined, async () => {
|
||||
const { engine, calls } = makeEngine([{ key: 'a', value: '1' }]);
|
||||
expect(await engine.getConfig('missing.key')).toBeNull();
|
||||
expect(await engine.getConfig('missing.key')).toBeNull();
|
||||
expect(calls.length).toBe(1);
|
||||
}));
|
||||
|
||||
it('setConfig writes through so subsequent reads see the new value', () => withTtl(undefined, async () => {
|
||||
const { engine, calls } = makeEngine([{ key: 'k', value: 'old' }]);
|
||||
expect(await engine.getConfig('k')).toBe('old');
|
||||
await engine.setConfig('k', 'new');
|
||||
expect(await engine.getConfig('k')).toBe('new');
|
||||
expect(calls.length).toBe(2); // batch load + upsert; no re-read
|
||||
}));
|
||||
|
||||
it('unsetConfig writes through so subsequent reads see absence', () => withTtl(undefined, async () => {
|
||||
const { engine } = makeEngine([{ key: 'k', value: 'v' }]);
|
||||
expect(await engine.getConfig('k')).toBe('v');
|
||||
await engine.unsetConfig('k');
|
||||
expect(await engine.getConfig('k')).toBeNull();
|
||||
}));
|
||||
|
||||
it('concurrent cold reads share a single batch load (single-flight)', () => withTtl(undefined, async () => {
|
||||
const { engine, calls } = makeEngine([{ key: 'k', value: 'v' }]);
|
||||
const [a, b, c] = await Promise.all([
|
||||
engine.getConfig('k'),
|
||||
engine.getConfig('k'),
|
||||
engine.getConfig('other'),
|
||||
]);
|
||||
expect([a, b, c]).toEqual(['v', 'v', null]);
|
||||
expect(calls.length).toBe(1);
|
||||
}));
|
||||
|
||||
it('GBRAIN_CONFIG_CACHE_TTL_MS=0 disables the cache (per-key reads)', () => withTtl('0', async () => {
|
||||
const { engine, calls } = makeEngine([{ value: 'v' }]);
|
||||
expect(await engine.getConfig('k')).toBe('v');
|
||||
expect(await engine.getConfig('k')).toBe('v');
|
||||
expect(calls.length).toBe(2);
|
||||
expect(calls[0]).toContain('SELECT value FROM config WHERE key =');
|
||||
}));
|
||||
|
||||
it('an expired TTL reloads from the database', () => withTtl('1', async () => {
|
||||
const { engine, calls } = makeEngine([{ key: 'k', value: 'v' }]);
|
||||
expect(await engine.getConfig('k')).toBe('v');
|
||||
await new Promise((r) => setTimeout(r, 5));
|
||||
expect(await engine.getConfig('k')).toBe('v');
|
||||
expect(calls.length).toBe(2); // two batch loads
|
||||
}));
|
||||
|
||||
it('the batch load keeps the connRetry reconnect posture (#1603/#1891)', () => withTtl(undefined, async () => {
|
||||
const e = new PostgresEngine();
|
||||
(e as unknown as { _connectionStyle: string })._connectionStyle = 'instance';
|
||||
(e as unknown as { _sql: unknown })._sql = null; // torn-down pool → retryable
|
||||
(e as unknown as { _bulkRetryOptsCache: unknown })._bulkRetryOptsCache = FAST_RETRY;
|
||||
let reconnects = 0;
|
||||
(e as unknown as { reconnect: () => Promise<void> }).reconnect = async () => {
|
||||
reconnects++;
|
||||
(e as unknown as { _sql: unknown })._sql = () =>
|
||||
Promise.resolve([{ key: 'k', value: 'v' }]);
|
||||
};
|
||||
expect(await e.getConfig('k')).toBe('v');
|
||||
expect(reconnects).toBe(1);
|
||||
}));
|
||||
});
|
||||
@@ -43,9 +43,7 @@ function makeTornDownEngine(poolResult: unknown): { engine: PostgresEngine; reco
|
||||
|
||||
describe('PostgresEngine non-batch config accessors self-heal (PR #1891 takeover)', () => {
|
||||
it('getConfig reconnects + retries a null instance pool, then returns the value', async () => {
|
||||
// Rows carry `key` too: getConfig's default cached path batch-loads
|
||||
// `SELECT key, value FROM config` (#1694) through the same connRetry.
|
||||
const { engine, reconnects } = makeTornDownEngine([{ key: 'some.key', value: 'live-value' }]);
|
||||
const { engine, reconnects } = makeTornDownEngine([{ value: 'live-value' }]);
|
||||
expect(await engine.getConfig('some.key')).toBe('live-value');
|
||||
expect(reconnects()).toBe(1); // exactly one reconnect closed the gap
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user