@rotorsoft/act-sqlite 1.9.1 → 1.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/.tsbuildinfo +1 -1
- package/dist/@types/sqlite-store.d.ts +1 -0
- package/dist/@types/sqlite-store.d.ts.map +1 -1
- package/dist/index.cjs +47 -7
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +47 -7
- package/dist/index.js.map +1 -1
- package/package.json +4 -4
package/dist/index.cjs
CHANGED
|
@@ -141,7 +141,8 @@ var SqliteStore = class {
|
|
|
141
141
|
leased_by TEXT,
|
|
142
142
|
leased_until TEXT,
|
|
143
143
|
priority INTEGER NOT NULL DEFAULT 0,
|
|
144
|
-
lane TEXT NOT NULL DEFAULT 'default'
|
|
144
|
+
lane TEXT NOT NULL DEFAULT 'default',
|
|
145
|
+
deferred_at TEXT
|
|
145
146
|
)
|
|
146
147
|
`);
|
|
147
148
|
try {
|
|
@@ -150,6 +151,12 @@ var SqliteStore = class {
|
|
|
150
151
|
);
|
|
151
152
|
} catch {
|
|
152
153
|
}
|
|
154
|
+
try {
|
|
155
|
+
await this.client.execute(
|
|
156
|
+
"ALTER TABLE streams ADD COLUMN deferred_at TEXT"
|
|
157
|
+
);
|
|
158
|
+
} catch {
|
|
159
|
+
}
|
|
153
160
|
try {
|
|
154
161
|
await this.client.execute(
|
|
155
162
|
"ALTER TABLE streams ADD COLUMN lane TEXT NOT NULL DEFAULT 'default'"
|
|
@@ -346,9 +353,10 @@ var SqliteStore = class {
|
|
|
346
353
|
const lane_clause = lane !== void 0 ? " AND lane = ?" : "";
|
|
347
354
|
const result = await tx.execute({
|
|
348
355
|
sql: `SELECT stream, source, at, priority, lane FROM streams
|
|
349
|
-
WHERE blocked = 0 AND (leased_until IS NULL OR leased_until <= ?)
|
|
356
|
+
WHERE blocked = 0 AND (leased_until IS NULL OR leased_until <= ?)
|
|
357
|
+
AND (deferred_at IS NULL OR deferred_at <= ?)${lane_clause}
|
|
350
358
|
ORDER BY priority DESC, at ASC`,
|
|
351
|
-
args: lane !== void 0 ? [now, lane] : [now]
|
|
359
|
+
args: lane !== void 0 ? [now, now, lane] : [now, now]
|
|
352
360
|
});
|
|
353
361
|
const candidates = [];
|
|
354
362
|
for (const row of result.rows) {
|
|
@@ -418,7 +426,7 @@ var SqliteStore = class {
|
|
|
418
426
|
const result = [];
|
|
419
427
|
for (const l of leases) {
|
|
420
428
|
const r = await tx.execute({
|
|
421
|
-
sql: `UPDATE streams SET at = ?, leased_by = NULL, leased_until = NULL, retry = -1
|
|
429
|
+
sql: `UPDATE streams SET at = ?, leased_by = NULL, leased_until = NULL, retry = -1, deferred_at = NULL
|
|
422
430
|
WHERE stream = ? AND leased_by = ?`,
|
|
423
431
|
args: [l.at, l.stream, l.by]
|
|
424
432
|
});
|
|
@@ -438,7 +446,7 @@ var SqliteStore = class {
|
|
|
438
446
|
const result = [];
|
|
439
447
|
for (const l of leases) {
|
|
440
448
|
const r = await tx.execute({
|
|
441
|
-
sql: `UPDATE streams SET blocked = 1, error =
|
|
449
|
+
sql: `UPDATE streams SET blocked = 1, error = ?, deferred_at = NULL
|
|
442
450
|
WHERE stream = ? AND leased_by = ? AND blocked = 0`,
|
|
443
451
|
args: [l.error, l.stream, l.by]
|
|
444
452
|
});
|
|
@@ -451,6 +459,38 @@ var SqliteStore = class {
|
|
|
451
459
|
throw new import_act.StoreError("block", { cause: e });
|
|
452
460
|
}
|
|
453
461
|
}
|
|
462
|
+
// --- defer: hold streams out of claim until deferred_at (#1090) ---
|
|
463
|
+
// Persisted as an ISO string (like leased_until) so claim's
|
|
464
|
+
// `deferred_at <= now` comparison is a lexicographic string compare.
|
|
465
|
+
// Cleared by ack/block/reset/unblock. See {@link Store.defer}.
|
|
466
|
+
async defer(input, deferred_at) {
|
|
467
|
+
const at_iso = new Date(deferred_at).toISOString();
|
|
468
|
+
const tx = await this.client.transaction("write");
|
|
469
|
+
try {
|
|
470
|
+
let count = 0;
|
|
471
|
+
if (Array.isArray(input)) {
|
|
472
|
+
for (const stream of input) {
|
|
473
|
+
const r = await tx.execute({
|
|
474
|
+
sql: `UPDATE streams SET deferred_at = ?, retry = -1 WHERE stream = ?`,
|
|
475
|
+
args: [at_iso, stream]
|
|
476
|
+
});
|
|
477
|
+
count += r.rowsAffected;
|
|
478
|
+
}
|
|
479
|
+
} else {
|
|
480
|
+
const { clause, args } = this._filter_clause(input);
|
|
481
|
+
const r = await tx.execute({
|
|
482
|
+
sql: `UPDATE streams SET deferred_at = ?, retry = -1 WHERE ${clause}`,
|
|
483
|
+
args: [at_iso, ...args]
|
|
484
|
+
});
|
|
485
|
+
count = r.rowsAffected;
|
|
486
|
+
}
|
|
487
|
+
await tx.commit();
|
|
488
|
+
return count;
|
|
489
|
+
} catch (e) {
|
|
490
|
+
await tx.rollback();
|
|
491
|
+
throw new import_act.StoreError("defer", { cause: e });
|
|
492
|
+
}
|
|
493
|
+
}
|
|
454
494
|
/**
|
|
455
495
|
* Translate a {@link StreamFilter} to a SQLite `WHERE` clause fragment
|
|
456
496
|
* plus positional args. Returns `"1"` (always true) when empty so
|
|
@@ -491,7 +531,7 @@ var SqliteStore = class {
|
|
|
491
531
|
// --- reset: transactional, accepts names or filter ---
|
|
492
532
|
async reset(input) {
|
|
493
533
|
const set_clause = `SET at = -1, retry = -1, blocked = 0, error = '',
|
|
494
|
-
leased_by = NULL, leased_until = NULL`;
|
|
534
|
+
leased_by = NULL, leased_until = NULL, deferred_at = NULL`;
|
|
495
535
|
const tx = await this.client.transaction("write");
|
|
496
536
|
try {
|
|
497
537
|
let count = 0;
|
|
@@ -523,7 +563,7 @@ var SqliteStore = class {
|
|
|
523
563
|
// matching the InMemoryStore convention.
|
|
524
564
|
async unblock(input) {
|
|
525
565
|
const set_clause = `SET retry = -1, blocked = 0, error = '',
|
|
526
|
-
leased_by = NULL, leased_until = NULL`;
|
|
566
|
+
leased_by = NULL, leased_until = NULL, deferred_at = NULL`;
|
|
527
567
|
const tx = await this.client.transaction("write");
|
|
528
568
|
try {
|
|
529
569
|
let count = 0;
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/sqlite-store.ts"],"sourcesContent":["/**\n * @packageDocumentation\n * @module act-sqlite\n * Main entry point for the Act-SQLite adapter. Re-exports all core APIs\n */\nexport * from \"./sqlite-store.js\";\n","import { type Client, createClient } from \"@libsql/client\";\nimport type {\n BlockedLease,\n Committed,\n EventMeta,\n Lease,\n Message,\n Query,\n QueryStatsOptions,\n QueryStreams,\n QueryStreamsResult,\n Schemas,\n Store,\n StreamFilter,\n StreamPosition,\n StreamStats,\n} from \"@rotorsoft/act\";\nimport { StoreError } from \"@rotorsoft/act\";\nimport {\n decrypt,\n type Encryption,\n encrypt,\n makeKeyResolver,\n} from \"@rotorsoft/act-crypto\";\n\n/**\n * SQLite store configuration\n */\nexport interface SqliteConfig {\n /** Path to the SQLite database file (default: \":memory:\") */\n url: string;\n /** Auth token for libSQL server connections (optional) */\n authToken?: string;\n /**\n * Adapter-layer envelope encryption for the `events.pii` column.\n * Optional — when present, every non-null PII payload is encrypted\n * before INSERT and decrypted on every read; when absent, the\n * column is stored and read as plaintext (the framework's default\n * behavior).\n *\n * Cipher and wire format come from `@rotorsoft/act-crypto`:\n * AES-256-GCM with a versioned base64-framed envelope. The TEXT\n * column stores `JSON.stringify(...)`-ed values either way, so\n * encrypted writes land as a JSON-stringified base64 string and\n * plaintext writes as a JSON-stringified object. The read path\n * discriminates by `typeof` after `JSON.parse` — strings get\n * decrypted, objects pass through — which makes mixed-data\n * rollouts transparent.\n *\n * `forget_pii` semantics are unchanged: the column is set to\n * `NULL` regardless of whether the prior value was plaintext or\n * ciphertext.\n *\n * Encryption at rest at the **storage** layer (SQLite SEE, an\n * encrypted volume, OS-level FDE) composes orthogonally with\n * adapter-layer encryption. See\n * `docs/docs/guides/pii-encryption-at-rest.md` for the decision\n * matrix.\n */\n pii_encryption?: Encryption;\n}\n\nconst DEFAULT_CONFIG: SqliteConfig = {\n url: \"file::memory:\",\n};\n\n/** Translate a stream filter (regex-shaped or plain substring) into a\n * SQL LIKE pattern. Honors `^` / `$` anchors and converts `.*` → `%`,\n * `.` → `_`. Unanchored input gets `%` wildcards on both sides.\n *\n * Examples:\n * - `^abc$` → `abc` (exact)\n * - `^abc.*` → `abc%` (starts-with)\n * - `.*abc$` → `%abc` (ends-with)\n * - `abc` → `%abc%` (contains)\n * - `a.c` → `%a_c%` (single-char wildcard, contains)\n *\n * @internal exported for testing\n */\nexport function streamPatternToLike(input: string): string {\n let s = input;\n const start = s.startsWith(\"^\");\n const end = s.endsWith(\"$\");\n if (start) s = s.slice(1);\n if (end) s = s.slice(0, -1);\n s = s.replace(/\\.\\*/g, \"%\").replace(/\\./g, \"_\");\n const out = (start ? \"\" : \"%\") + s + (end ? \"\" : \"%\");\n // Collapse adjacent `%` — e.g. `^a.*` would otherwise yield `a%%`.\n // Same matching semantics, cleaner output.\n return out.replace(/%+/g, \"%\");\n}\n\n/**\n * SQLite event store adapter for [@rotorsoft/act](https://www.npmjs.com/package/@rotorsoft/act).\n *\n * Provides persistent event storage using SQLite via `@libsql/client`.\n * All write operations use transactions for ACID guarantees.\n *\n * SQLite is a single-writer store: concurrent write transactions raise\n * `SQLITE_BUSY` rather than serializing transparently, so it does not\n * support competing consumers the way PostgreSQL's `FOR UPDATE SKIP LOCKED`\n * does (the TCK leaves `concurrent_claim` off for this reason). The intended\n * model is a single drain worker per database file.\n *\n * **`Store.notify` is intentionally not implemented.** The notify hook is\n * a cross-process wake-up signal that lets a horizontally-scaled Act\n * deployment wake `settle()` immediately on remote commits. SQLite is\n * single-node by design — there is no remote writer to be notified of —\n * so the {@link Act} orchestrator falls back to the existing\n * debounce/poll path, which is correct for this topology.\n *\n * @example\n * ```typescript\n * import { store } from \"@rotorsoft/act\";\n * import { SqliteStore } from \"@rotorsoft/act-sqlite\";\n *\n * store(new SqliteStore({ url: \"file:myapp.db\" }));\n * await store().seed();\n * ```\n */\nexport class SqliteStore implements Store {\n private client: Client;\n /**\n * Memoized key resolver for the optional `pii_encryption` envelope.\n * Initialized in the constructor when encryption is configured;\n * `undefined` otherwise. The resolver caches the operator's key on\n * first use — rotation means restarting the store with a fresh\n * provider.\n */\n private readonly _resolve_pii_key: (() => Promise<Buffer>) | undefined;\n\n constructor(config: Partial<SqliteConfig> = {}) {\n const cfg = { ...DEFAULT_CONFIG, ...config };\n this.client = createClient({\n url: cfg.url,\n authToken: cfg.authToken,\n });\n this._resolve_pii_key = cfg.pii_encryption\n ? makeKeyResolver(cfg.pii_encryption)\n : undefined;\n }\n\n /**\n * Write-side pii encoder: encrypts when `pii_encryption` is configured,\n * stringifies for the TEXT column either way. `null` passes through so\n * `forget_pii` semantics survive intact (the row format skips the\n * column entirely on a `NULL` write).\n *\n * @internal\n */\n private async _stringify_pii_for_write(\n pii: Readonly<Record<string, unknown>> | null | undefined\n ): Promise<string | null> {\n if (pii == null) return null;\n if (this._resolve_pii_key) {\n return JSON.stringify(await encrypt(pii, this._resolve_pii_key));\n }\n return JSON.stringify(pii);\n }\n\n /**\n * Read-side pii decoder: parses the TEXT column, and when\n * `pii_encryption` is configured, transparently decrypts any value\n * that came back as a JSON string. Plaintext writes deserialize to\n * objects and pass through — which is what makes mixed-data\n * rollouts (some pre-encryption rows, some post-) read cleanly.\n *\n * @internal\n */\n private async _parse_pii_from_read(\n raw: unknown\n ): Promise<Record<string, unknown> | null> {\n if (raw == null) return null;\n const parsed = JSON.parse(raw as string);\n if (this._resolve_pii_key && typeof parsed === \"string\") {\n return (await decrypt(parsed, this._resolve_pii_key)) as Record<\n string,\n unknown\n >;\n }\n return parsed;\n }\n\n async seed() {\n await this.client.execute(\"PRAGMA journal_mode=WAL\");\n await this.client.execute(`\n CREATE TABLE IF NOT EXISTS events (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n stream TEXT NOT NULL,\n version INTEGER NOT NULL,\n name TEXT NOT NULL,\n data TEXT NOT NULL,\n meta TEXT NOT NULL,\n created TEXT NOT NULL,\n pii TEXT,\n UNIQUE(stream, version)\n )\n `);\n // Migration for tables created before pii_isolation (#871).\n // libSQL surfaces \"duplicate column\" as an error, hence the\n // try/swallow — mirrors PG's `ADD COLUMN IF NOT EXISTS`. SQLite's\n // row format skips NULL columns, so events without sensitive\n // declarations pay zero extra bytes.\n try {\n await this.client.execute(\"ALTER TABLE events ADD COLUMN pii TEXT\");\n } catch {\n // already present\n }\n await this.client.execute(\n \"CREATE INDEX IF NOT EXISTS idx_events_stream ON events(stream)\"\n );\n await this.client.execute(\n \"CREATE INDEX IF NOT EXISTS idx_events_name ON events(name)\"\n );\n // Partial index over snapshot rows only, so the with_snaps \"resume at\n // the latest snapshot\" floor (MAX(id) WHERE stream=? AND\n // name='__snapshot__') is an O(log) lookup and costs nothing for\n // streams with no snapshot (the index has no rows for them).\n await this.client.execute(\n \"CREATE INDEX IF NOT EXISTS idx_events_snapshot ON events(stream, id) WHERE name = '__snapshot__'\"\n );\n await this.client.execute(`\n CREATE TABLE IF NOT EXISTS streams (\n stream TEXT PRIMARY KEY,\n source TEXT,\n at INTEGER NOT NULL DEFAULT -1,\n retry INTEGER NOT NULL DEFAULT -1,\n blocked INTEGER NOT NULL DEFAULT 0,\n error TEXT NOT NULL DEFAULT '',\n leased_by TEXT,\n leased_until TEXT,\n priority INTEGER NOT NULL DEFAULT 0,\n lane TEXT NOT NULL DEFAULT 'default'\n )\n `);\n // Migration for tables created before priority lanes (ACT-102).\n // libSQL surfaces \"duplicate column\" as an error, hence the\n // try/swallow — this mirrors PG's `ADD COLUMN IF NOT EXISTS`.\n try {\n await this.client.execute(\n \"ALTER TABLE streams ADD COLUMN priority INTEGER NOT NULL DEFAULT 0\"\n );\n } catch {\n // already present\n }\n // Migration for tables created before drain lanes (ACT-1103).\n try {\n await this.client.execute(\n \"ALTER TABLE streams ADD COLUMN lane TEXT NOT NULL DEFAULT 'default'\"\n );\n } catch {\n // already present\n }\n await this.client.execute(\n \"CREATE INDEX IF NOT EXISTS idx_streams_claim ON streams(blocked, priority DESC, at)\"\n );\n // Lane filter index (ACT-1103).\n await this.client.execute(\n \"CREATE INDEX IF NOT EXISTS idx_streams_lane ON streams(lane)\"\n );\n }\n\n async drop() {\n await this.client.execute(\"DROP TABLE IF EXISTS events\");\n await this.client.execute(\"DROP TABLE IF EXISTS streams\");\n }\n\n async dispose() {\n await Promise.resolve();\n this.client.close();\n }\n\n // --- commit: transaction + optimistic concurrency ---\n async commit<E extends Schemas>(\n stream: string,\n msgs: Message<E, keyof E>[],\n meta: EventMeta,\n expectedVersion?: number\n ): Promise<Committed<E, keyof E>[]> {\n const tx = await this.client.transaction(\"write\");\n try {\n const version_row = await tx.execute({\n sql: \"SELECT COALESCE(MAX(version), -1) as v FROM events WHERE stream = ?\",\n args: [stream],\n });\n const current_version = Number(version_row.rows[0].v);\n\n if (\n typeof expectedVersion === \"number\" &&\n current_version !== expectedVersion\n ) {\n const { ConcurrencyError } = await import(\"@rotorsoft/act\");\n throw new ConcurrencyError(\n stream,\n current_version,\n msgs as Message<Schemas, keyof Schemas>[],\n expectedVersion\n );\n }\n\n const now = new Date().toISOString();\n const committed: Committed<E, keyof E>[] = [];\n let version = current_version + 1;\n\n for (const { name, data, pii } of msgs) {\n const pii_for_write = await this._stringify_pii_for_write(pii);\n const result = await tx.execute({\n sql: \"INSERT INTO events (stream, version, name, data, meta, created, pii) VALUES (?, ?, ?, ?, ?, ?, ?)\",\n args: [\n stream,\n version,\n name as string,\n JSON.stringify(data),\n JSON.stringify(meta),\n now,\n pii_for_write,\n ],\n });\n committed.push({\n id: Number(result.lastInsertRowid),\n stream,\n version,\n created: new Date(now),\n name,\n data,\n meta,\n ...(pii == null ? {} : { pii }),\n });\n version++;\n }\n\n await tx.commit();\n return committed;\n } catch (e) {\n await tx.rollback();\n throw e;\n }\n }\n\n // --- query: read-only, no transaction needed ---\n async query<E extends Schemas>(\n callback: (event: Committed<E, keyof E>) => void,\n query?: Query\n ): Promise<number> {\n let sql = \"SELECT * FROM events WHERE 1=1\";\n const args: unknown[] = [];\n\n if (query?.stream) {\n if (query.stream_exact) {\n sql += \" AND stream = ?\";\n args.push(query.stream);\n } else {\n sql += \" AND stream LIKE ?\";\n args.push(streamPatternToLike(query.stream));\n }\n }\n if (query?.names) {\n sql += ` AND name IN (${query.names.map(() => \"?\").join(\",\")})`;\n args.push(...query.names);\n }\n if ((query as any)?.correlation) {\n sql += \" AND json_extract(meta, '$.correlation') = ?\";\n args.push((query as any).correlation);\n }\n if (query?.after !== undefined) {\n sql += \" AND id > ?\";\n args.push(query.after);\n } else if (query?.with_snaps && query.stream_exact && query.stream) {\n // Resume at the latest snapshot for this stream so pre-snapshot\n // events aren't scanned. No snapshot → MAX is NULL → -1 → full\n // stream. An explicit `after` (above) wins.\n sql +=\n \" AND id >= (SELECT COALESCE(MAX(id), -1) FROM events WHERE stream = ? AND name = '__snapshot__')\";\n args.push(query.stream);\n }\n if (query?.before !== undefined) {\n sql += \" AND id < ?\";\n args.push(query.before);\n }\n if (query?.created_after) {\n sql += \" AND created > ?\";\n args.push(query.created_after.toISOString());\n }\n if (query?.created_before) {\n sql += \" AND created < ?\";\n args.push(query.created_before.toISOString());\n }\n if (!query?.with_snaps) {\n sql += \" AND name != '__snapshot__'\";\n }\n\n sql += query?.backward ? \" ORDER BY id DESC\" : \" ORDER BY id ASC\";\n\n if (query?.limit) {\n sql += \" LIMIT ?\";\n args.push(query.limit);\n }\n\n const result = await this.client.execute({ sql, args: args as any[] });\n let count = 0;\n\n for (const row of result.rows) {\n const pii_value = await this._parse_pii_from_read(row.pii);\n await Promise.resolve(\n callback({\n id: Number(row.id),\n stream: row.stream as string,\n version: Number(row.version),\n created: new Date(row.created as string),\n name: row.name as string,\n data: JSON.parse(row.data as string),\n meta: JSON.parse(row.meta as string),\n pii: pii_value,\n })\n );\n count++;\n }\n\n return count;\n }\n\n // --- subscribe: idempotent INSERT OR IGNORE (= PG ON CONFLICT DO NOTHING)\n // plus a UPDATE pass to keep the *max* priority across reactions\n // targeting the same stream (ACT-102). Operator overrides go\n // through `prioritize()` instead.\n async subscribe(\n streams: Array<{\n stream: string;\n source?: string;\n priority?: number;\n lane?: string;\n }>\n ) {\n const tx = await this.client.transaction(\"write\");\n try {\n let subscribed = 0;\n for (const {\n stream,\n source,\n priority = 0,\n lane = \"default\",\n } of streams) {\n const inserted = await tx.execute({\n sql: \"INSERT OR IGNORE INTO streams (stream, source, priority, lane, retry) VALUES (?, ?, ?, ?, -1)\",\n args: [stream, source ?? null, priority, lane],\n });\n if (inserted.rowsAffected > 0) {\n subscribed++;\n } else {\n if (priority > 0) {\n await tx.execute({\n sql: \"UPDATE streams SET priority = ? WHERE stream = ? AND priority < ?\",\n args: [priority, stream, priority],\n });\n }\n // ACT-1103: current subscribe wins on lane.\n await tx.execute({\n sql: \"UPDATE streams SET lane = ? WHERE stream = ? AND lane <> ?\",\n args: [lane, stream, lane],\n });\n }\n }\n const wm = await tx.execute(\n \"SELECT COALESCE(MAX(at), -1) as w FROM streams\"\n );\n await tx.commit();\n return { subscribed, watermark: Number(wm.rows[0].w) };\n } catch (e) {\n await tx.rollback();\n throw new StoreError(\"subscribe\", { cause: e });\n }\n }\n\n // --- claim: write transaction. Single-writer: concurrent claims from\n // separate connections raise SQLITE_BUSY, so this assumes one drain\n // worker per database file (see class doc; TCK `concurrent_claim` off).\n async claim(\n lagging: number,\n leading: number,\n by: string,\n millis: number,\n lane?: string\n ) {\n const tx = await this.client.transaction(\"write\");\n try {\n const now = new Date().toISOString();\n\n const lane_clause = lane !== undefined ? \" AND lane = ?\" : \"\";\n const result = await tx.execute({\n sql: `SELECT stream, source, at, priority, lane FROM streams\n WHERE blocked = 0 AND (leased_until IS NULL OR leased_until <= ?)${lane_clause}\n ORDER BY priority DESC, at ASC`,\n args: lane !== undefined ? [now, lane] : [now],\n });\n\n const candidates: {\n stream: string;\n source: string | undefined;\n at: number;\n priority: number;\n lane: string;\n }[] = [];\n for (const row of result.rows) {\n const stream = row.stream as string;\n const source = row.source as string | null;\n const at = Number(row.at);\n\n let has_events: boolean;\n if (source) {\n const check = await tx.execute({\n sql: `SELECT 1 FROM events WHERE id > ? AND name != '__snapshot__' AND stream LIKE ? LIMIT 1`,\n args: [at, streamPatternToLike(source)],\n });\n has_events = check.rows.length > 0;\n } else {\n const check = await tx.execute({\n sql: `SELECT 1 FROM events WHERE id > ? AND name != '__snapshot__' LIMIT 1`,\n args: [at],\n });\n has_events = check.rows.length > 0;\n }\n\n if (has_events) {\n candidates.push({\n stream,\n source: source ?? undefined,\n at,\n priority: Number(row.priority),\n lane: row.lane as string,\n });\n }\n }\n\n // Dual frontier: lagging (priority DESC, watermark ASC — ACT-102)\n // + leading (newest first). The candidates list arrives sorted\n // by `priority DESC, at ASC` from the SELECT above, so the\n // `slice(0, lagging)` already does the right thing.\n const lag = candidates\n .slice(0, lagging)\n .map((c) => ({ ...c, lagging: true }));\n const lead = [...candidates]\n .sort((a, b) => b.at - a.at)\n .slice(0, leading)\n .map((c) => ({ ...c, lagging: false }));\n const seen = new Set<string>();\n const combined = [...lag, ...lead].filter((p) => {\n if (seen.has(p.stream)) return false;\n seen.add(p.stream);\n return true;\n });\n\n const leases: Lease[] = [];\n const until = new Date(Date.now() + millis).toISOString();\n for (const row of combined) {\n const updated = await tx.execute({\n sql: \"UPDATE streams SET leased_by = ?, leased_until = ?, retry = retry + 1 WHERE stream = ? RETURNING retry\",\n args: [by, until, row.stream],\n });\n leases.push({\n stream: row.stream,\n source: row.source,\n at: row.at,\n by,\n retry: Number(updated.rows[0].retry),\n lagging: row.lagging,\n lane: row.lane,\n });\n }\n\n await tx.commit();\n return leases;\n } catch (e) {\n await tx.rollback();\n throw new StoreError(\"claim\", { cause: e });\n }\n }\n\n // --- ack: transaction + ownership check (= PG WHERE leased_by) ---\n async ack(leases: Lease[]) {\n const tx = await this.client.transaction(\"write\");\n try {\n const result: Lease[] = [];\n for (const l of leases) {\n const r = await tx.execute({\n sql: `UPDATE streams SET at = ?, leased_by = NULL, leased_until = NULL, retry = -1\n WHERE stream = ? AND leased_by = ?`,\n args: [l.at, l.stream, l.by],\n });\n if (r.rowsAffected > 0) result.push(l);\n }\n await tx.commit();\n return result;\n } catch (e) {\n await tx.rollback();\n throw new StoreError(\"ack\", { cause: e });\n }\n }\n\n // --- block: transaction + ownership + idempotent (= PG) ---\n async block(leases: BlockedLease[]) {\n const tx = await this.client.transaction(\"write\");\n try {\n const result: BlockedLease[] = [];\n for (const l of leases) {\n const r = await tx.execute({\n sql: `UPDATE streams SET blocked = 1, error = ?\n WHERE stream = ? AND leased_by = ? AND blocked = 0`,\n args: [l.error, l.stream, l.by],\n });\n if (r.rowsAffected > 0) result.push(l);\n }\n await tx.commit();\n return result;\n } catch (e) {\n await tx.rollback();\n throw new StoreError(\"block\", { cause: e });\n }\n }\n\n /**\n * Translate a {@link StreamFilter} to a SQLite `WHERE` clause fragment\n * plus positional args. Returns `\"1\"` (always true) when empty so\n * callers can compose it unconditionally.\n */\n private _filter_clause(filter: StreamFilter): {\n clause: string;\n args: unknown[];\n } {\n const conditions: string[] = [];\n const args: unknown[] = [];\n if (filter.stream !== undefined) {\n if (filter.stream_exact) {\n conditions.push(\"stream = ?\");\n args.push(filter.stream);\n } else {\n conditions.push(\"stream LIKE ?\");\n args.push(streamPatternToLike(filter.stream));\n }\n }\n if (filter.source !== undefined) {\n conditions.push(\"source IS NOT NULL\");\n if (filter.source_exact) {\n conditions.push(\"source = ?\");\n args.push(filter.source);\n } else {\n conditions.push(\"source LIKE ?\");\n args.push(streamPatternToLike(filter.source));\n }\n }\n if (filter.blocked !== undefined) {\n conditions.push(\"blocked = ?\");\n args.push(filter.blocked ? 1 : 0);\n }\n if (filter.lane !== undefined) {\n conditions.push(\"lane = ?\");\n args.push(filter.lane);\n }\n return { clause: conditions.length ? conditions.join(\" AND \") : \"1\", args };\n }\n\n // --- reset: transactional, accepts names or filter ---\n async reset(input: string[] | StreamFilter) {\n const set_clause = `SET at = -1, retry = -1, blocked = 0, error = '',\n leased_by = NULL, leased_until = NULL`;\n const tx = await this.client.transaction(\"write\");\n try {\n let count = 0;\n if (Array.isArray(input)) {\n for (const stream of input) {\n const r = await tx.execute({\n sql: `UPDATE streams ${set_clause} WHERE stream = ?`,\n args: [stream],\n });\n count += r.rowsAffected;\n }\n } else {\n const { clause, args } = this._filter_clause(input);\n const r = await tx.execute({\n sql: `UPDATE streams ${set_clause} WHERE ${clause}`,\n args: args as any[],\n });\n count = r.rowsAffected;\n }\n await tx.commit();\n return count;\n } catch (e) {\n await tx.rollback();\n throw e;\n }\n }\n\n // --- unblock: clear blocked + retry + lease without touching watermark ---\n // `retry = -1` so claim's post-bump returns retry=0 (first attempt),\n // matching the InMemoryStore convention.\n async unblock(input: string[] | StreamFilter) {\n const set_clause = `SET retry = -1, blocked = 0, error = '',\n leased_by = NULL, leased_until = NULL`;\n const tx = await this.client.transaction(\"write\");\n try {\n let count = 0;\n if (Array.isArray(input)) {\n for (const stream of input) {\n const r = await tx.execute({\n sql: `UPDATE streams ${set_clause}\n WHERE stream = ? AND blocked = 1`,\n args: [stream],\n });\n count += r.rowsAffected;\n }\n } else {\n // Filter form: force blocked = true regardless of what the\n // caller passed.\n const { clause, args } = this._filter_clause({\n ...input,\n blocked: true,\n });\n const r = await tx.execute({\n sql: `UPDATE streams ${set_clause} WHERE ${clause}`,\n args: args as any[],\n });\n count = r.rowsAffected;\n }\n await tx.commit();\n return count;\n } catch (e) {\n await tx.rollback();\n throw e;\n }\n }\n\n // --- query_streams: read-only introspection with filters ---\n async query_streams(\n callback: (position: StreamPosition) => void,\n query?: QueryStreams\n ): Promise<QueryStreamsResult> {\n const limit = query?.limit ?? 100;\n let sql =\n \"SELECT stream, source, at, retry, blocked, error, leased_by, leased_until, priority, lane FROM streams WHERE 1=1\";\n const args: unknown[] = [];\n\n if (query?.stream !== undefined) {\n if (query.stream_exact) {\n sql += \" AND stream = ?\";\n args.push(query.stream);\n } else {\n sql += \" AND stream LIKE ?\";\n args.push(streamPatternToLike(query.stream));\n }\n }\n if (query?.source !== undefined) {\n sql += \" AND source IS NOT NULL\";\n if (query.source_exact) {\n sql += \" AND source = ?\";\n args.push(query.source);\n } else {\n sql += \" AND source LIKE ?\";\n args.push(streamPatternToLike(query.source));\n }\n }\n if (query?.blocked !== undefined) {\n sql += \" AND blocked = ?\";\n args.push(query.blocked ? 1 : 0);\n }\n if (query?.lane !== undefined) {\n sql += \" AND lane = ?\";\n args.push(query.lane);\n }\n if (query?.after !== undefined) {\n sql += \" AND stream > ?\";\n args.push(query.after);\n }\n sql += \" ORDER BY stream LIMIT ?\";\n args.push(limit);\n\n const [streamsResult, maxResult] = await Promise.all([\n this.client.execute({ sql, args: args as any[] }),\n this.client.execute(\"SELECT COALESCE(MAX(id), -1) AS m FROM events\"),\n ]);\n\n let count = 0;\n for (const row of streamsResult.rows) {\n const leased_until = row.leased_until as string | null;\n callback({\n stream: row.stream as string,\n source: (row.source as string | null) ?? undefined,\n at: Number(row.at),\n retry: Number(row.retry),\n blocked: Number(row.blocked) === 1,\n error: row.error as string,\n priority: Number(row.priority),\n leased_by: (row.leased_by as string | null) ?? undefined,\n leased_until: leased_until ? new Date(leased_until) : undefined,\n lane: row.lane as string,\n });\n count++;\n }\n\n return { maxEventId: Number(maxResult.rows[0].m), count };\n }\n\n /**\n * Per-stream aggregated stats — see {@link Store.query_stats}.\n *\n * Two code paths (mirrors the PostgresStore strategy):\n *\n * - **Heads-only path** (no `count`, no `names`): one or two queries\n * using `ROW_NUMBER() OVER (PARTITION BY stream ORDER BY version\n * DESC|ASC)` (SQLite lacks PG's `DISTINCT ON`). Window function +\n * `WHERE rn = 1` materializes the head (or tail) per stream from\n * the `(stream, version)` unique index. Parallel `Promise.all` when\n * tail is requested.\n *\n * - **Full-scan path** (`count` or `names` set): one CTE materializes\n * the filtered events, then `GROUP BY stream, name` →\n * `json_group_object(name, n)` for the names map plus `SUM(n)` for\n * count. Heads (and tails when requested) come from the same scan.\n *\n * SQLite specifics:\n * - `data` and `meta` are stored as TEXT (JSON-encoded); the reader\n * JSON-parses them when materializing the {@link Committed} rows.\n * - `blocked` is stored as 0/1 integer; the filter converts.\n * - Array input expands to a placeholder list (`IN (?, ?, ...)`)\n * since SQLite has no native array type.\n */\n async query_stats<E extends Schemas>(\n input: string[] | Pick<StreamFilter, \"stream\" | \"stream_exact\">,\n options?: QueryStatsOptions<E>\n ): Promise<Map<string, StreamStats<E>>> {\n const exclude = options?.exclude ?? [];\n const want_tail = options?.tail ?? false;\n const want_count = options?.count ?? false;\n const want_names = options?.names ?? false;\n const before = options?.before;\n const after = options?.after;\n const limit = options?.limit;\n const full_scan = want_count || want_names;\n\n if (Array.isArray(input) && input.length === 0) {\n return new Map<string, StreamStats<E>>();\n }\n\n // Build WHERE clause + positional args. Subscription-level filters\n // (source, blocked) are intentionally not accepted — events live in\n // the events table; subscription state in the streams table. For\n // \"stats for blocked subscriptions\" callers compose with\n // query_streams. So no JOIN here.\n const where: string[] = [];\n const args: unknown[] = [];\n\n if (Array.isArray(input)) {\n const placeholders = input.map(() => \"?\").join(\",\");\n where.push(`e.stream IN (${placeholders})`);\n args.push(...input);\n } else if (input.stream !== undefined) {\n if (input.stream_exact) {\n where.push(`e.stream = ?`);\n args.push(input.stream);\n } else {\n where.push(`e.stream LIKE ?`);\n args.push(streamPatternToLike(input.stream));\n }\n }\n if (exclude.length) {\n const placeholders = exclude.map(() => \"?\").join(\",\");\n where.push(`e.name NOT IN (${placeholders})`);\n args.push(...exclude);\n }\n if (before !== undefined) {\n where.push(`e.id < ?`);\n args.push(before);\n }\n // Keyset pagination cursor (#1010): exclusive — return only streams\n // whose name sorts strictly after `after`. Applied at the event level\n // so the per-stream head/agg rows downstream only cover the page.\n if (after !== undefined) {\n where.push(`e.stream > ?`);\n args.push(after);\n }\n\n const from_clause = `events e`;\n // Always emit a WHERE clause — `WHERE 1=1` short-circuits the\n // empty-filter case without a conditional branch on the generation\n // side. SQLite optimizes the trivial predicate out.\n const where_clause = `WHERE ${where.length ? where.join(\" AND \") : \"1=1\"}`;\n\n return full_scan\n ? this._query_stats_full_scan<E>(\n from_clause,\n where_clause,\n args,\n want_tail,\n want_count,\n want_names,\n limit\n )\n : this._query_stats_heads_only<E>(\n from_clause,\n where_clause,\n args,\n want_tail,\n limit\n );\n }\n\n /**\n * Cheap path — head (and optional tail) via ROW_NUMBER() over the\n * `(stream, version)` unique index. Parallel queries when tail set.\n */\n private async _query_stats_heads_only<E extends Schemas>(\n from_clause: string,\n where_clause: string,\n args: unknown[],\n want_tail: boolean,\n limit?: number\n ): Promise<Map<string, StreamStats<E>>> {\n const cols = `e.id, e.stream, e.version, e.name, e.data, e.created, e.meta, e.pii`;\n // Keyset pagination (#1010): order heads by stream ascending so the\n // caller can use the last key as the next `after` cursor; cap with\n // LIMIT when set (unbounded otherwise).\n const limit_clause = limit !== undefined ? \" LIMIT ?\" : \"\";\n const head_sql = `SELECT * FROM (\n SELECT ${cols}, ROW_NUMBER() OVER (PARTITION BY e.stream ORDER BY e.version DESC) AS rn\n FROM ${from_clause}\n ${where_clause}\n ) WHERE rn = 1 ORDER BY stream${limit_clause}`;\n const head_args = limit !== undefined ? [...args, limit] : args;\n // The tail query shares the same WHERE; when paginating it must cover\n // exactly the limited head stream set, so it joins against the same\n // ordered+limited heads subquery rather than re-scanning all streams.\n const tail_sql = want_tail\n ? `SELECT t.* FROM (\n SELECT ${cols}, ROW_NUMBER() OVER (PARTITION BY e.stream ORDER BY e.version ASC) AS rn\n FROM ${from_clause}\n ${where_clause}\n ) t\n WHERE t.rn = 1 AND t.stream IN (\n SELECT stream FROM (\n SELECT e.stream, ROW_NUMBER() OVER (PARTITION BY e.stream ORDER BY e.version DESC) AS rn\n FROM ${from_clause}\n ${where_clause}\n ) WHERE rn = 1 ORDER BY stream${limit_clause}\n )`\n : null;\n const tail_args =\n limit !== undefined ? [...args, ...args, limit] : [...args, ...args];\n\n const [headRes, tailRes] = await Promise.all([\n this.client.execute({ sql: head_sql, args: head_args as any[] }),\n tail_sql\n ? this.client.execute({ sql: tail_sql, args: tail_args as any[] })\n : null,\n ]);\n\n const to_committed = async (\n row: Record<string, unknown>\n ): Promise<Committed<E, keyof E>> =>\n ({\n id: Number(row.id),\n stream: row.stream as string,\n version: Number(row.version),\n name: row.name as string,\n data: JSON.parse(row.data as string),\n meta: JSON.parse(row.meta as string),\n created: new Date(row.created as string),\n pii: await this._parse_pii_from_read(row.pii),\n }) as Committed<E, keyof E>;\n\n const out = new Map<string, StreamStats<E>>();\n for (const row of headRes.rows) {\n out.set(row.stream as string, {\n head: await to_committed(row as Record<string, unknown>),\n });\n }\n if (tailRes) {\n for (const row of tailRes.rows) {\n // Head and tail share the same WHERE, so any stream returning\n // a tail must also have returned a head — no null check needed.\n (\n out.get(row.stream as string) as {\n head: Committed<E, keyof E>;\n tail?: Committed<E, keyof E>;\n }\n ).tail = await to_committed(row as Record<string, unknown>);\n }\n }\n return out;\n }\n\n /**\n * Full-scan path — one CTE-based query with per-stream `COUNT(*)` and\n * `json_group_object(name, n)`. Heads (and optional tails) ride free\n * on the same scan.\n */\n private async _query_stats_full_scan<E extends Schemas>(\n from_clause: string,\n where_clause: string,\n args: unknown[],\n want_tail: boolean,\n want_count: boolean,\n want_names: boolean,\n limit?: number\n ): Promise<Map<string, StreamStats<E>>> {\n const tail_cte = want_tail\n ? `, tails AS (\n SELECT * FROM (\n SELECT *, ROW_NUMBER() OVER (PARTITION BY stream ORDER BY version ASC) AS rn FROM ef\n ) WHERE rn = 1\n )`\n : \"\";\n const tail_join = want_tail\n ? `LEFT JOIN tails t ON t.stream = h.stream`\n : \"\";\n const tail_cols = want_tail\n ? `, t.id AS t_id, t.stream AS t_stream, t.version AS t_version,\n t.name AS t_name, t.data AS t_data, t.created AS t_created, t.meta AS t_meta, t.pii AS t_pii`\n : \"\";\n\n const sql = `\n WITH ef AS (\n SELECT e.id, e.stream, e.version, e.name, e.data, e.created, e.meta, e.pii\n FROM ${from_clause}\n ${where_clause}\n ),\n agg AS (\n SELECT stream,\n SUM(n) AS cnt,\n json_group_object(name, n) AS names\n FROM (\n SELECT stream, name, COUNT(*) AS n\n FROM ef\n GROUP BY stream, name\n )\n GROUP BY stream\n ),\n heads AS (\n SELECT * FROM (\n SELECT *, ROW_NUMBER() OVER (PARTITION BY stream ORDER BY version DESC) AS rn FROM ef\n ) WHERE rn = 1\n ORDER BY stream${limit !== undefined ? \" LIMIT ?\" : \"\"}\n )\n ${tail_cte}\n SELECT\n h.id, h.stream, h.version, h.name, h.data, h.created, h.meta, h.pii,\n a.cnt AS agg_count,\n a.names AS agg_names\n ${tail_cols}\n FROM heads h\n LEFT JOIN agg a ON a.stream = h.stream\n ${tail_join}\n ORDER BY h.stream\n `;\n\n // Keyset pagination (#1010): the `heads` CTE is ordered by stream and\n // capped with LIMIT (when set); the final SELECT re-asserts stream\n // order so the returned Map's key order is the next cursor. The LIMIT\n // arg binds last when present (unbounded otherwise).\n const full_args = limit !== undefined ? [...args, limit] : args;\n const res = await this.client.execute({ sql, args: full_args as any[] });\n\n const to_committed = async (\n id: unknown,\n stream: unknown,\n version: unknown,\n name: unknown,\n data: unknown,\n meta: unknown,\n created: unknown,\n pii: unknown\n ): Promise<Committed<E, keyof E>> =>\n ({\n id: Number(id),\n stream: stream as string,\n version: Number(version),\n name: name as string,\n data: JSON.parse(data as string),\n meta: JSON.parse(meta as string),\n created: new Date(created as string),\n pii: await this._parse_pii_from_read(pii),\n }) as Committed<E, keyof E>;\n\n const out = new Map<string, StreamStats<E>>();\n for (const row of res.rows) {\n const r = row as unknown as Record<string, unknown>;\n const stats: {\n head: Committed<E, keyof E>;\n tail?: Committed<E, keyof E>;\n count?: number;\n names?: Record<string, number>;\n } = {\n head: await to_committed(\n r.id,\n r.stream,\n r.version,\n r.name,\n r.data,\n r.meta,\n r.created,\n r.pii\n ),\n };\n if (want_tail && r.t_id !== null && r.t_id !== undefined) {\n stats.tail = await to_committed(\n r.t_id,\n r.t_stream,\n r.t_version,\n r.t_name,\n r.t_data,\n r.t_meta,\n r.t_created,\n r.t_pii\n );\n }\n if (want_count) stats.count = Number(r.agg_count);\n // `agg_names` is non-null when this row exists: heads and agg are\n // both built from the same `ef` CTE, so any stream in heads has\n // at least one matching event and `json_group_object` returns a\n // JSON string (never null) for that group.\n if (want_names) stats.names = JSON.parse(r.agg_names as string);\n out.set(r.stream as string, stats as StreamStats<E>);\n }\n return out;\n }\n\n // --- prioritize: bulk priority update with filter (ACT-102) ---\n async prioritize(filter: StreamFilter, priority: number): Promise<number> {\n const { clause, args: filterArgs } = this._filter_clause(filter);\n // libSQL `?` placeholders are positional and NOT reusable, so we\n // bind `priority` twice: once for SET, once for the no-op skip\n // in WHERE.\n const sql = `UPDATE streams SET priority = ?\n WHERE priority <> ? AND ${clause}`;\n const result = await this.client.execute({\n sql,\n args: [priority, priority, ...filterArgs] as any[],\n });\n return result.rowsAffected;\n }\n\n // --- truncate: transactional delete + seed ---\n async truncate(\n targets: Array<{\n stream: string;\n snapshot?: Record<string, unknown>;\n meta?: EventMeta;\n }>\n ) {\n const result = new Map<\n string,\n { deleted: number; committed: Committed<Schemas, keyof Schemas> }\n >();\n\n const tx = await this.client.transaction(\"write\");\n try {\n for (const { stream, snapshot, meta } of targets) {\n const count_row = await tx.execute({\n sql: \"SELECT COUNT(*) as c FROM events WHERE stream = ?\",\n args: [stream],\n });\n const deleted = Number(count_row.rows[0].c);\n await tx.execute({\n sql: \"DELETE FROM events WHERE stream = ?\",\n args: [stream],\n });\n await tx.execute({\n sql: \"DELETE FROM streams WHERE stream = ?\",\n args: [stream],\n });\n\n const event_name =\n snapshot !== undefined ? \"__snapshot__\" : \"__tombstone__\";\n const event_meta = meta ?? { correlation: \"\", causation: {} };\n const now = new Date().toISOString();\n const ins = await tx.execute({\n sql: \"INSERT INTO events (stream, version, name, data, meta, created) VALUES (?, 0, ?, ?, ?, ?)\",\n args: [\n stream,\n event_name,\n JSON.stringify(snapshot ?? {}),\n JSON.stringify(event_meta),\n now,\n ],\n });\n\n result.set(stream, {\n deleted,\n committed: {\n id: Number(ins.lastInsertRowid),\n stream,\n version: 0,\n created: new Date(now),\n name: event_name,\n data: snapshot ?? {},\n meta: event_meta,\n },\n });\n }\n await tx.commit();\n } catch (e) {\n await tx.rollback();\n throw e;\n }\n\n return result;\n }\n\n /**\n * Atomically wipe-and-rebuild the store inside a single libsql\n * `write` transaction.\n *\n * On any throw inside the driver the transaction rolls back and the\n * store is byte-for-byte unchanged. `DELETE FROM events` + `DELETE\n * FROM streams` wipe both tables; `DELETE FROM sqlite_sequence\n * WHERE name = 'events'` resets the autoincrement counter so the\n * new sequence is dense from 1. `created` is preserved verbatim\n * from the source.\n */\n async restore(\n driver: (\n callback: (event: Committed<Schemas, keyof Schemas>) => Promise<number>\n ) => Promise<void>\n ): Promise<void> {\n const tx = await this.client.transaction(\"write\");\n try {\n await tx.execute(\"DELETE FROM events\");\n await tx.execute(\"DELETE FROM streams\");\n // Reset the autoincrement counter so the new sequence is dense\n // from 1. `DELETE FROM sqlite_sequence WHERE name = '?'` is the\n // canonical SQLite reset; safe even if the row doesn't exist.\n await tx.execute(\"DELETE FROM sqlite_sequence WHERE name = 'events'\");\n await driver(async (event) => {\n const pii_for_write = await this._stringify_pii_for_write(event.pii);\n const ins = await tx.execute({\n sql: \"INSERT INTO events (stream, version, name, data, meta, created, pii) VALUES (?, ?, ?, ?, ?, ?, ?)\",\n args: [\n event.stream,\n event.version,\n event.name,\n JSON.stringify(event.data),\n JSON.stringify(event.meta),\n event.created.toISOString(),\n pii_for_write,\n ],\n });\n return Number(ins.lastInsertRowid);\n });\n await tx.commit();\n } catch (error) {\n await tx.rollback();\n throw error;\n }\n }\n\n /**\n * Wipe the sensitive-data payload for every event on the stream — the\n * physical-erasure side of the sensitive-data epic (#566). Sets\n * `events.pii` to `NULL` for the stream's events; `events.data` and\n * the rest of the row are never touched.\n *\n * Single `UPDATE` under SQLite's writer lock, bounded by events-per-\n * stream. Idempotent — the `pii IS NOT NULL` predicate filters out\n * already-wiped rows so a second call returns `0`.\n *\n * SQLite doesn't auto-reclaim space; freed pages stay in the file\n * until an operator-scheduled `PRAGMA incremental_vacuum` or a full\n * `VACUUM`. The production checklist documents the cadence.\n *\n * @param stream Target stream\n * @returns Count of events whose `pii` was set to `NULL`\n */\n async forget_pii(stream: string): Promise<number> {\n const r = await this.client.execute({\n sql: \"UPDATE events SET pii = NULL WHERE stream = ? AND pii IS NOT NULL\",\n args: [stream],\n });\n return r.rowsAffected ?? 0;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,oBAA0C;AAiB1C,iBAA2B;AAC3B,wBAKO;AAuCP,IAAM,iBAA+B;AAAA,EACnC,KAAK;AACP;AAeO,SAAS,oBAAoB,OAAuB;AACzD,MAAI,IAAI;AACR,QAAM,QAAQ,EAAE,WAAW,GAAG;AAC9B,QAAM,MAAM,EAAE,SAAS,GAAG;AAC1B,MAAI,MAAO,KAAI,EAAE,MAAM,CAAC;AACxB,MAAI,IAAK,KAAI,EAAE,MAAM,GAAG,EAAE;AAC1B,MAAI,EAAE,QAAQ,SAAS,GAAG,EAAE,QAAQ,OAAO,GAAG;AAC9C,QAAM,OAAO,QAAQ,KAAK,OAAO,KAAK,MAAM,KAAK;AAGjD,SAAO,IAAI,QAAQ,OAAO,GAAG;AAC/B;AA8BO,IAAM,cAAN,MAAmC;AAAA,EAChC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQS;AAAA,EAEjB,YAAY,SAAgC,CAAC,GAAG;AAC9C,UAAM,MAAM,EAAE,GAAG,gBAAgB,GAAG,OAAO;AAC3C,SAAK,aAAS,4BAAa;AAAA,MACzB,KAAK,IAAI;AAAA,MACT,WAAW,IAAI;AAAA,IACjB,CAAC;AACD,SAAK,mBAAmB,IAAI,qBACxB,mCAAgB,IAAI,cAAc,IAClC;AAAA,EACN;AAAA;AAAA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M;AAAA,IACR;AAEA,WAAO;AAAA,EACT;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAaA,MAAM,QACJ,QAGe;AACf,UAAM,KAAK,MAAM,KAAK,OAAO,YAAY,OAAO;AAChD,QAAI;AACF,YAAM,GAAG,QAAQ,oBAAoB;AACrC,YAAM,GAAG,QAAQ,qBAAqB;AAItC,YAAM,GAAG,QAAQ,mDAAmD;AACpE,YAAM,OAAO,OAAO,UAAU;AAC5B,cAAM,gBAAgB,MAAM,KAAK,yBAAyB,MAAM,GAAG;AACnE,cAAM,MAAM,MAAM,GAAG,QAAQ;AAAA,UAC3B,KAAK;AAAA,UACL,MAAM;AAAA,YACJ,MAAM;AAAA,YACN,MAAM;AAAA,YACN,MAAM;AAAA,YACN,KAAK,UAAU,MAAM,IAAI;AAAA,YACzB,KAAK,UAAU,MAAM,IAAI;AAAA,YACzB,MAAM,QAAQ,YAAY;AAAA,YAC1B;AAAA,UACF;AAAA,QACF,CAAC;AACD,eAAO,OAAO,IAAI,eAAe;AAAA,MACnC,CAAC;AACD,YAAM,GAAG,OAAO;AAAA,IAClB,SAAS,OAAO;AACd,YAAM,GAAG,SAAS;AAClB,YAAM;AAAA,IACR;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAmBA,MAAM,WAAW,QAAiC;AAChD,UAAM,IAAI,MAAM,KAAK,OAAO,QAAQ;AAAA,MAClC,KAAK;AAAA,MACL,MAAM,CAAC,MAAM;AAAA,IACf,CAAC;AACD,WAAO,EAAE,gBAAgB;AAAA,EAC3B;AACF;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/sqlite-store.ts"],"sourcesContent":["/**\n * @packageDocumentation\n * @module act-sqlite\n * Main entry point for the Act-SQLite adapter. Re-exports all core APIs\n */\nexport * from \"./sqlite-store.js\";\n","import { type Client, createClient } from \"@libsql/client\";\nimport type {\n BlockedLease,\n Committed,\n EventMeta,\n Lease,\n Message,\n Query,\n QueryStatsOptions,\n QueryStreams,\n QueryStreamsResult,\n Schemas,\n Store,\n StreamFilter,\n StreamPosition,\n StreamStats,\n} from \"@rotorsoft/act\";\nimport { StoreError } from \"@rotorsoft/act\";\nimport {\n decrypt,\n type Encryption,\n encrypt,\n makeKeyResolver,\n} from \"@rotorsoft/act-crypto\";\n\n/**\n * SQLite store configuration\n */\nexport interface SqliteConfig {\n /** Path to the SQLite database file (default: \":memory:\") */\n url: string;\n /** Auth token for libSQL server connections (optional) */\n authToken?: string;\n /**\n * Adapter-layer envelope encryption for the `events.pii` column.\n * Optional — when present, every non-null PII payload is encrypted\n * before INSERT and decrypted on every read; when absent, the\n * column is stored and read as plaintext (the framework's default\n * behavior).\n *\n * Cipher and wire format come from `@rotorsoft/act-crypto`:\n * AES-256-GCM with a versioned base64-framed envelope. The TEXT\n * column stores `JSON.stringify(...)`-ed values either way, so\n * encrypted writes land as a JSON-stringified base64 string and\n * plaintext writes as a JSON-stringified object. The read path\n * discriminates by `typeof` after `JSON.parse` — strings get\n * decrypted, objects pass through — which makes mixed-data\n * rollouts transparent.\n *\n * `forget_pii` semantics are unchanged: the column is set to\n * `NULL` regardless of whether the prior value was plaintext or\n * ciphertext.\n *\n * Encryption at rest at the **storage** layer (SQLite SEE, an\n * encrypted volume, OS-level FDE) composes orthogonally with\n * adapter-layer encryption. See\n * `docs/docs/guides/pii-encryption-at-rest.md` for the decision\n * matrix.\n */\n pii_encryption?: Encryption;\n}\n\nconst DEFAULT_CONFIG: SqliteConfig = {\n url: \"file::memory:\",\n};\n\n/** Translate a stream filter (regex-shaped or plain substring) into a\n * SQL LIKE pattern. Honors `^` / `$` anchors and converts `.*` → `%`,\n * `.` → `_`. Unanchored input gets `%` wildcards on both sides.\n *\n * Examples:\n * - `^abc$` → `abc` (exact)\n * - `^abc.*` → `abc%` (starts-with)\n * - `.*abc$` → `%abc` (ends-with)\n * - `abc` → `%abc%` (contains)\n * - `a.c` → `%a_c%` (single-char wildcard, contains)\n *\n * @internal exported for testing\n */\nexport function streamPatternToLike(input: string): string {\n let s = input;\n const start = s.startsWith(\"^\");\n const end = s.endsWith(\"$\");\n if (start) s = s.slice(1);\n if (end) s = s.slice(0, -1);\n s = s.replace(/\\.\\*/g, \"%\").replace(/\\./g, \"_\");\n const out = (start ? \"\" : \"%\") + s + (end ? \"\" : \"%\");\n // Collapse adjacent `%` — e.g. `^a.*` would otherwise yield `a%%`.\n // Same matching semantics, cleaner output.\n return out.replace(/%+/g, \"%\");\n}\n\n/**\n * SQLite event store adapter for [@rotorsoft/act](https://www.npmjs.com/package/@rotorsoft/act).\n *\n * Provides persistent event storage using SQLite via `@libsql/client`.\n * All write operations use transactions for ACID guarantees.\n *\n * SQLite is a single-writer store: concurrent write transactions raise\n * `SQLITE_BUSY` rather than serializing transparently, so it does not\n * support competing consumers the way PostgreSQL's `FOR UPDATE SKIP LOCKED`\n * does (the TCK leaves `concurrent_claim` off for this reason). The intended\n * model is a single drain worker per database file.\n *\n * **`Store.notify` is intentionally not implemented.** The notify hook is\n * a cross-process wake-up signal that lets a horizontally-scaled Act\n * deployment wake `settle()` immediately on remote commits. SQLite is\n * single-node by design — there is no remote writer to be notified of —\n * so the {@link Act} orchestrator falls back to the existing\n * debounce/poll path, which is correct for this topology.\n *\n * @example\n * ```typescript\n * import { store } from \"@rotorsoft/act\";\n * import { SqliteStore } from \"@rotorsoft/act-sqlite\";\n *\n * store(new SqliteStore({ url: \"file:myapp.db\" }));\n * await store().seed();\n * ```\n */\nexport class SqliteStore implements Store {\n private client: Client;\n /**\n * Memoized key resolver for the optional `pii_encryption` envelope.\n * Initialized in the constructor when encryption is configured;\n * `undefined` otherwise. The resolver caches the operator's key on\n * first use — rotation means restarting the store with a fresh\n * provider.\n */\n private readonly _resolve_pii_key: (() => Promise<Buffer>) | undefined;\n\n constructor(config: Partial<SqliteConfig> = {}) {\n const cfg = { ...DEFAULT_CONFIG, ...config };\n this.client = createClient({\n url: cfg.url,\n authToken: cfg.authToken,\n });\n this._resolve_pii_key = cfg.pii_encryption\n ? makeKeyResolver(cfg.pii_encryption)\n : undefined;\n }\n\n /**\n * Write-side pii encoder: encrypts when `pii_encryption` is configured,\n * stringifies for the TEXT column either way. `null` passes through so\n * `forget_pii` semantics survive intact (the row format skips the\n * column entirely on a `NULL` write).\n *\n * @internal\n */\n private async _stringify_pii_for_write(\n pii: Readonly<Record<string, unknown>> | null | undefined\n ): Promise<string | null> {\n if (pii == null) return null;\n if (this._resolve_pii_key) {\n return JSON.stringify(await encrypt(pii, this._resolve_pii_key));\n }\n return JSON.stringify(pii);\n }\n\n /**\n * Read-side pii decoder: parses the TEXT column, and when\n * `pii_encryption` is configured, transparently decrypts any value\n * that came back as a JSON string. Plaintext writes deserialize to\n * objects and pass through — which is what makes mixed-data\n * rollouts (some pre-encryption rows, some post-) read cleanly.\n *\n * @internal\n */\n private async _parse_pii_from_read(\n raw: unknown\n ): Promise<Record<string, unknown> | null> {\n if (raw == null) return null;\n const parsed = JSON.parse(raw as string);\n if (this._resolve_pii_key && typeof parsed === \"string\") {\n return (await decrypt(parsed, this._resolve_pii_key)) as Record<\n string,\n unknown\n >;\n }\n return parsed;\n }\n\n async seed() {\n await this.client.execute(\"PRAGMA journal_mode=WAL\");\n await this.client.execute(`\n CREATE TABLE IF NOT EXISTS events (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n stream TEXT NOT NULL,\n version INTEGER NOT NULL,\n name TEXT NOT NULL,\n data TEXT NOT NULL,\n meta TEXT NOT NULL,\n created TEXT NOT NULL,\n pii TEXT,\n UNIQUE(stream, version)\n )\n `);\n // Migration for tables created before pii_isolation (#871).\n // libSQL surfaces \"duplicate column\" as an error, hence the\n // try/swallow — mirrors PG's `ADD COLUMN IF NOT EXISTS`. SQLite's\n // row format skips NULL columns, so events without sensitive\n // declarations pay zero extra bytes.\n try {\n await this.client.execute(\"ALTER TABLE events ADD COLUMN pii TEXT\");\n } catch {\n // already present\n }\n await this.client.execute(\n \"CREATE INDEX IF NOT EXISTS idx_events_stream ON events(stream)\"\n );\n await this.client.execute(\n \"CREATE INDEX IF NOT EXISTS idx_events_name ON events(name)\"\n );\n // Partial index over snapshot rows only, so the with_snaps \"resume at\n // the latest snapshot\" floor (MAX(id) WHERE stream=? AND\n // name='__snapshot__') is an O(log) lookup and costs nothing for\n // streams with no snapshot (the index has no rows for them).\n await this.client.execute(\n \"CREATE INDEX IF NOT EXISTS idx_events_snapshot ON events(stream, id) WHERE name = '__snapshot__'\"\n );\n await this.client.execute(`\n CREATE TABLE IF NOT EXISTS streams (\n stream TEXT PRIMARY KEY,\n source TEXT,\n at INTEGER NOT NULL DEFAULT -1,\n retry INTEGER NOT NULL DEFAULT -1,\n blocked INTEGER NOT NULL DEFAULT 0,\n error TEXT NOT NULL DEFAULT '',\n leased_by TEXT,\n leased_until TEXT,\n priority INTEGER NOT NULL DEFAULT 0,\n lane TEXT NOT NULL DEFAULT 'default',\n deferred_at TEXT\n )\n `);\n // Migration for tables created before priority lanes (ACT-102).\n // libSQL surfaces \"duplicate column\" as an error, hence the\n // try/swallow — this mirrors PG's `ADD COLUMN IF NOT EXISTS`.\n try {\n await this.client.execute(\n \"ALTER TABLE streams ADD COLUMN priority INTEGER NOT NULL DEFAULT 0\"\n );\n } catch {\n // already present\n }\n // Migration for tables created before deferred reactions (#1090).\n try {\n await this.client.execute(\n \"ALTER TABLE streams ADD COLUMN deferred_at TEXT\"\n );\n } catch {\n // already present\n }\n // Migration for tables created before drain lanes (ACT-1103).\n try {\n await this.client.execute(\n \"ALTER TABLE streams ADD COLUMN lane TEXT NOT NULL DEFAULT 'default'\"\n );\n } catch {\n // already present\n }\n await this.client.execute(\n \"CREATE INDEX IF NOT EXISTS idx_streams_claim ON streams(blocked, priority DESC, at)\"\n );\n // Lane filter index (ACT-1103).\n await this.client.execute(\n \"CREATE INDEX IF NOT EXISTS idx_streams_lane ON streams(lane)\"\n );\n }\n\n async drop() {\n await this.client.execute(\"DROP TABLE IF EXISTS events\");\n await this.client.execute(\"DROP TABLE IF EXISTS streams\");\n }\n\n async dispose() {\n await Promise.resolve();\n this.client.close();\n }\n\n // --- commit: transaction + optimistic concurrency ---\n async commit<E extends Schemas>(\n stream: string,\n msgs: Message<E, keyof E>[],\n meta: EventMeta,\n expectedVersion?: number\n ): Promise<Committed<E, keyof E>[]> {\n const tx = await this.client.transaction(\"write\");\n try {\n const version_row = await tx.execute({\n sql: \"SELECT COALESCE(MAX(version), -1) as v FROM events WHERE stream = ?\",\n args: [stream],\n });\n const current_version = Number(version_row.rows[0].v);\n\n if (\n typeof expectedVersion === \"number\" &&\n current_version !== expectedVersion\n ) {\n const { ConcurrencyError } = await import(\"@rotorsoft/act\");\n throw new ConcurrencyError(\n stream,\n current_version,\n msgs as Message<Schemas, keyof Schemas>[],\n expectedVersion\n );\n }\n\n const now = new Date().toISOString();\n const committed: Committed<E, keyof E>[] = [];\n let version = current_version + 1;\n\n for (const { name, data, pii } of msgs) {\n const pii_for_write = await this._stringify_pii_for_write(pii);\n const result = await tx.execute({\n sql: \"INSERT INTO events (stream, version, name, data, meta, created, pii) VALUES (?, ?, ?, ?, ?, ?, ?)\",\n args: [\n stream,\n version,\n name as string,\n JSON.stringify(data),\n JSON.stringify(meta),\n now,\n pii_for_write,\n ],\n });\n committed.push({\n id: Number(result.lastInsertRowid),\n stream,\n version,\n created: new Date(now),\n name,\n data,\n meta,\n ...(pii == null ? {} : { pii }),\n });\n version++;\n }\n\n await tx.commit();\n return committed;\n } catch (e) {\n await tx.rollback();\n throw e;\n }\n }\n\n // --- query: read-only, no transaction needed ---\n async query<E extends Schemas>(\n callback: (event: Committed<E, keyof E>) => void,\n query?: Query\n ): Promise<number> {\n let sql = \"SELECT * FROM events WHERE 1=1\";\n const args: unknown[] = [];\n\n if (query?.stream) {\n if (query.stream_exact) {\n sql += \" AND stream = ?\";\n args.push(query.stream);\n } else {\n sql += \" AND stream LIKE ?\";\n args.push(streamPatternToLike(query.stream));\n }\n }\n if (query?.names) {\n sql += ` AND name IN (${query.names.map(() => \"?\").join(\",\")})`;\n args.push(...query.names);\n }\n if ((query as any)?.correlation) {\n sql += \" AND json_extract(meta, '$.correlation') = ?\";\n args.push((query as any).correlation);\n }\n if (query?.after !== undefined) {\n sql += \" AND id > ?\";\n args.push(query.after);\n } else if (query?.with_snaps && query.stream_exact && query.stream) {\n // Resume at the latest snapshot for this stream so pre-snapshot\n // events aren't scanned. No snapshot → MAX is NULL → -1 → full\n // stream. An explicit `after` (above) wins.\n sql +=\n \" AND id >= (SELECT COALESCE(MAX(id), -1) FROM events WHERE stream = ? AND name = '__snapshot__')\";\n args.push(query.stream);\n }\n if (query?.before !== undefined) {\n sql += \" AND id < ?\";\n args.push(query.before);\n }\n if (query?.created_after) {\n sql += \" AND created > ?\";\n args.push(query.created_after.toISOString());\n }\n if (query?.created_before) {\n sql += \" AND created < ?\";\n args.push(query.created_before.toISOString());\n }\n if (!query?.with_snaps) {\n sql += \" AND name != '__snapshot__'\";\n }\n\n sql += query?.backward ? \" ORDER BY id DESC\" : \" ORDER BY id ASC\";\n\n if (query?.limit) {\n sql += \" LIMIT ?\";\n args.push(query.limit);\n }\n\n const result = await this.client.execute({ sql, args: args as any[] });\n let count = 0;\n\n for (const row of result.rows) {\n const pii_value = await this._parse_pii_from_read(row.pii);\n await Promise.resolve(\n callback({\n id: Number(row.id),\n stream: row.stream as string,\n version: Number(row.version),\n created: new Date(row.created as string),\n name: row.name as string,\n data: JSON.parse(row.data as string),\n meta: JSON.parse(row.meta as string),\n pii: pii_value,\n })\n );\n count++;\n }\n\n return count;\n }\n\n // --- subscribe: idempotent INSERT OR IGNORE (= PG ON CONFLICT DO NOTHING)\n // plus a UPDATE pass to keep the *max* priority across reactions\n // targeting the same stream (ACT-102). Operator overrides go\n // through `prioritize()` instead.\n async subscribe(\n streams: Array<{\n stream: string;\n source?: string;\n priority?: number;\n lane?: string;\n }>\n ) {\n const tx = await this.client.transaction(\"write\");\n try {\n let subscribed = 0;\n for (const {\n stream,\n source,\n priority = 0,\n lane = \"default\",\n } of streams) {\n const inserted = await tx.execute({\n sql: \"INSERT OR IGNORE INTO streams (stream, source, priority, lane, retry) VALUES (?, ?, ?, ?, -1)\",\n args: [stream, source ?? null, priority, lane],\n });\n if (inserted.rowsAffected > 0) {\n subscribed++;\n } else {\n if (priority > 0) {\n await tx.execute({\n sql: \"UPDATE streams SET priority = ? WHERE stream = ? AND priority < ?\",\n args: [priority, stream, priority],\n });\n }\n // ACT-1103: current subscribe wins on lane.\n await tx.execute({\n sql: \"UPDATE streams SET lane = ? WHERE stream = ? AND lane <> ?\",\n args: [lane, stream, lane],\n });\n }\n }\n const wm = await tx.execute(\n \"SELECT COALESCE(MAX(at), -1) as w FROM streams\"\n );\n await tx.commit();\n return { subscribed, watermark: Number(wm.rows[0].w) };\n } catch (e) {\n await tx.rollback();\n throw new StoreError(\"subscribe\", { cause: e });\n }\n }\n\n // --- claim: write transaction. Single-writer: concurrent claims from\n // separate connections raise SQLITE_BUSY, so this assumes one drain\n // worker per database file (see class doc; TCK `concurrent_claim` off).\n async claim(\n lagging: number,\n leading: number,\n by: string,\n millis: number,\n lane?: string\n ) {\n const tx = await this.client.transaction(\"write\");\n try {\n const now = new Date().toISOString();\n\n const lane_clause = lane !== undefined ? \" AND lane = ?\" : \"\";\n const result = await tx.execute({\n sql: `SELECT stream, source, at, priority, lane FROM streams\n WHERE blocked = 0 AND (leased_until IS NULL OR leased_until <= ?)\n AND (deferred_at IS NULL OR deferred_at <= ?)${lane_clause}\n ORDER BY priority DESC, at ASC`,\n args: lane !== undefined ? [now, now, lane] : [now, now],\n });\n\n const candidates: {\n stream: string;\n source: string | undefined;\n at: number;\n priority: number;\n lane: string;\n }[] = [];\n for (const row of result.rows) {\n const stream = row.stream as string;\n const source = row.source as string | null;\n const at = Number(row.at);\n\n let has_events: boolean;\n if (source) {\n const check = await tx.execute({\n sql: `SELECT 1 FROM events WHERE id > ? AND name != '__snapshot__' AND stream LIKE ? LIMIT 1`,\n args: [at, streamPatternToLike(source)],\n });\n has_events = check.rows.length > 0;\n } else {\n const check = await tx.execute({\n sql: `SELECT 1 FROM events WHERE id > ? AND name != '__snapshot__' LIMIT 1`,\n args: [at],\n });\n has_events = check.rows.length > 0;\n }\n\n if (has_events) {\n candidates.push({\n stream,\n source: source ?? undefined,\n at,\n priority: Number(row.priority),\n lane: row.lane as string,\n });\n }\n }\n\n // Dual frontier: lagging (priority DESC, watermark ASC — ACT-102)\n // + leading (newest first). The candidates list arrives sorted\n // by `priority DESC, at ASC` from the SELECT above, so the\n // `slice(0, lagging)` already does the right thing.\n const lag = candidates\n .slice(0, lagging)\n .map((c) => ({ ...c, lagging: true }));\n const lead = [...candidates]\n .sort((a, b) => b.at - a.at)\n .slice(0, leading)\n .map((c) => ({ ...c, lagging: false }));\n const seen = new Set<string>();\n const combined = [...lag, ...lead].filter((p) => {\n if (seen.has(p.stream)) return false;\n seen.add(p.stream);\n return true;\n });\n\n const leases: Lease[] = [];\n const until = new Date(Date.now() + millis).toISOString();\n for (const row of combined) {\n const updated = await tx.execute({\n sql: \"UPDATE streams SET leased_by = ?, leased_until = ?, retry = retry + 1 WHERE stream = ? RETURNING retry\",\n args: [by, until, row.stream],\n });\n leases.push({\n stream: row.stream,\n source: row.source,\n at: row.at,\n by,\n retry: Number(updated.rows[0].retry),\n lagging: row.lagging,\n lane: row.lane,\n });\n }\n\n await tx.commit();\n return leases;\n } catch (e) {\n await tx.rollback();\n throw new StoreError(\"claim\", { cause: e });\n }\n }\n\n // --- ack: transaction + ownership check (= PG WHERE leased_by) ---\n async ack(leases: Lease[]) {\n const tx = await this.client.transaction(\"write\");\n try {\n const result: Lease[] = [];\n for (const l of leases) {\n const r = await tx.execute({\n sql: `UPDATE streams SET at = ?, leased_by = NULL, leased_until = NULL, retry = -1, deferred_at = NULL\n WHERE stream = ? AND leased_by = ?`,\n args: [l.at, l.stream, l.by],\n });\n if (r.rowsAffected > 0) result.push(l);\n }\n await tx.commit();\n return result;\n } catch (e) {\n await tx.rollback();\n throw new StoreError(\"ack\", { cause: e });\n }\n }\n\n // --- block: transaction + ownership + idempotent (= PG) ---\n async block(leases: BlockedLease[]) {\n const tx = await this.client.transaction(\"write\");\n try {\n const result: BlockedLease[] = [];\n for (const l of leases) {\n const r = await tx.execute({\n sql: `UPDATE streams SET blocked = 1, error = ?, deferred_at = NULL\n WHERE stream = ? AND leased_by = ? AND blocked = 0`,\n args: [l.error, l.stream, l.by],\n });\n if (r.rowsAffected > 0) result.push(l);\n }\n await tx.commit();\n return result;\n } catch (e) {\n await tx.rollback();\n throw new StoreError(\"block\", { cause: e });\n }\n }\n\n // --- defer: hold streams out of claim until deferred_at (#1090) ---\n // Persisted as an ISO string (like leased_until) so claim's\n // `deferred_at <= now` comparison is a lexicographic string compare.\n // Cleared by ack/block/reset/unblock. See {@link Store.defer}.\n async defer(input: string[] | StreamFilter, deferred_at: number) {\n const at_iso = new Date(deferred_at).toISOString();\n const tx = await this.client.transaction(\"write\");\n try {\n let count = 0;\n if (Array.isArray(input)) {\n for (const stream of input) {\n const r = await tx.execute({\n sql: `UPDATE streams SET deferred_at = ?, retry = -1 WHERE stream = ?`,\n args: [at_iso, stream],\n });\n count += r.rowsAffected;\n }\n } else {\n const { clause, args } = this._filter_clause(input);\n const r = await tx.execute({\n sql: `UPDATE streams SET deferred_at = ?, retry = -1 WHERE ${clause}`,\n args: [at_iso, ...args] as any[],\n });\n count = r.rowsAffected;\n }\n await tx.commit();\n return count;\n } catch (e) {\n await tx.rollback();\n throw new StoreError(\"defer\", { cause: e });\n }\n }\n\n /**\n * Translate a {@link StreamFilter} to a SQLite `WHERE` clause fragment\n * plus positional args. Returns `\"1\"` (always true) when empty so\n * callers can compose it unconditionally.\n */\n private _filter_clause(filter: StreamFilter): {\n clause: string;\n args: unknown[];\n } {\n const conditions: string[] = [];\n const args: unknown[] = [];\n if (filter.stream !== undefined) {\n if (filter.stream_exact) {\n conditions.push(\"stream = ?\");\n args.push(filter.stream);\n } else {\n conditions.push(\"stream LIKE ?\");\n args.push(streamPatternToLike(filter.stream));\n }\n }\n if (filter.source !== undefined) {\n conditions.push(\"source IS NOT NULL\");\n if (filter.source_exact) {\n conditions.push(\"source = ?\");\n args.push(filter.source);\n } else {\n conditions.push(\"source LIKE ?\");\n args.push(streamPatternToLike(filter.source));\n }\n }\n if (filter.blocked !== undefined) {\n conditions.push(\"blocked = ?\");\n args.push(filter.blocked ? 1 : 0);\n }\n if (filter.lane !== undefined) {\n conditions.push(\"lane = ?\");\n args.push(filter.lane);\n }\n return { clause: conditions.length ? conditions.join(\" AND \") : \"1\", args };\n }\n\n // --- reset: transactional, accepts names or filter ---\n async reset(input: string[] | StreamFilter) {\n const set_clause = `SET at = -1, retry = -1, blocked = 0, error = '',\n leased_by = NULL, leased_until = NULL, deferred_at = NULL`;\n const tx = await this.client.transaction(\"write\");\n try {\n let count = 0;\n if (Array.isArray(input)) {\n for (const stream of input) {\n const r = await tx.execute({\n sql: `UPDATE streams ${set_clause} WHERE stream = ?`,\n args: [stream],\n });\n count += r.rowsAffected;\n }\n } else {\n const { clause, args } = this._filter_clause(input);\n const r = await tx.execute({\n sql: `UPDATE streams ${set_clause} WHERE ${clause}`,\n args: args as any[],\n });\n count = r.rowsAffected;\n }\n await tx.commit();\n return count;\n } catch (e) {\n await tx.rollback();\n throw e;\n }\n }\n\n // --- unblock: clear blocked + retry + lease without touching watermark ---\n // `retry = -1` so claim's post-bump returns retry=0 (first attempt),\n // matching the InMemoryStore convention.\n async unblock(input: string[] | StreamFilter) {\n const set_clause = `SET retry = -1, blocked = 0, error = '',\n leased_by = NULL, leased_until = NULL, deferred_at = NULL`;\n const tx = await this.client.transaction(\"write\");\n try {\n let count = 0;\n if (Array.isArray(input)) {\n for (const stream of input) {\n const r = await tx.execute({\n sql: `UPDATE streams ${set_clause}\n WHERE stream = ? AND blocked = 1`,\n args: [stream],\n });\n count += r.rowsAffected;\n }\n } else {\n // Filter form: force blocked = true regardless of what the\n // caller passed.\n const { clause, args } = this._filter_clause({\n ...input,\n blocked: true,\n });\n const r = await tx.execute({\n sql: `UPDATE streams ${set_clause} WHERE ${clause}`,\n args: args as any[],\n });\n count = r.rowsAffected;\n }\n await tx.commit();\n return count;\n } catch (e) {\n await tx.rollback();\n throw e;\n }\n }\n\n // --- query_streams: read-only introspection with filters ---\n async query_streams(\n callback: (position: StreamPosition) => void,\n query?: QueryStreams\n ): Promise<QueryStreamsResult> {\n const limit = query?.limit ?? 100;\n let sql =\n \"SELECT stream, source, at, retry, blocked, error, leased_by, leased_until, priority, lane FROM streams WHERE 1=1\";\n const args: unknown[] = [];\n\n if (query?.stream !== undefined) {\n if (query.stream_exact) {\n sql += \" AND stream = ?\";\n args.push(query.stream);\n } else {\n sql += \" AND stream LIKE ?\";\n args.push(streamPatternToLike(query.stream));\n }\n }\n if (query?.source !== undefined) {\n sql += \" AND source IS NOT NULL\";\n if (query.source_exact) {\n sql += \" AND source = ?\";\n args.push(query.source);\n } else {\n sql += \" AND source LIKE ?\";\n args.push(streamPatternToLike(query.source));\n }\n }\n if (query?.blocked !== undefined) {\n sql += \" AND blocked = ?\";\n args.push(query.blocked ? 1 : 0);\n }\n if (query?.lane !== undefined) {\n sql += \" AND lane = ?\";\n args.push(query.lane);\n }\n if (query?.after !== undefined) {\n sql += \" AND stream > ?\";\n args.push(query.after);\n }\n sql += \" ORDER BY stream LIMIT ?\";\n args.push(limit);\n\n const [streamsResult, maxResult] = await Promise.all([\n this.client.execute({ sql, args: args as any[] }),\n this.client.execute(\"SELECT COALESCE(MAX(id), -1) AS m FROM events\"),\n ]);\n\n let count = 0;\n for (const row of streamsResult.rows) {\n const leased_until = row.leased_until as string | null;\n callback({\n stream: row.stream as string,\n source: (row.source as string | null) ?? undefined,\n at: Number(row.at),\n retry: Number(row.retry),\n blocked: Number(row.blocked) === 1,\n error: row.error as string,\n priority: Number(row.priority),\n leased_by: (row.leased_by as string | null) ?? undefined,\n leased_until: leased_until ? new Date(leased_until) : undefined,\n lane: row.lane as string,\n });\n count++;\n }\n\n return { maxEventId: Number(maxResult.rows[0].m), count };\n }\n\n /**\n * Per-stream aggregated stats — see {@link Store.query_stats}.\n *\n * Two code paths (mirrors the PostgresStore strategy):\n *\n * - **Heads-only path** (no `count`, no `names`): one or two queries\n * using `ROW_NUMBER() OVER (PARTITION BY stream ORDER BY version\n * DESC|ASC)` (SQLite lacks PG's `DISTINCT ON`). Window function +\n * `WHERE rn = 1` materializes the head (or tail) per stream from\n * the `(stream, version)` unique index. Parallel `Promise.all` when\n * tail is requested.\n *\n * - **Full-scan path** (`count` or `names` set): one CTE materializes\n * the filtered events, then `GROUP BY stream, name` →\n * `json_group_object(name, n)` for the names map plus `SUM(n)` for\n * count. Heads (and tails when requested) come from the same scan.\n *\n * SQLite specifics:\n * - `data` and `meta` are stored as TEXT (JSON-encoded); the reader\n * JSON-parses them when materializing the {@link Committed} rows.\n * - `blocked` is stored as 0/1 integer; the filter converts.\n * - Array input expands to a placeholder list (`IN (?, ?, ...)`)\n * since SQLite has no native array type.\n */\n async query_stats<E extends Schemas>(\n input: string[] | Pick<StreamFilter, \"stream\" | \"stream_exact\">,\n options?: QueryStatsOptions<E>\n ): Promise<Map<string, StreamStats<E>>> {\n const exclude = options?.exclude ?? [];\n const want_tail = options?.tail ?? false;\n const want_count = options?.count ?? false;\n const want_names = options?.names ?? false;\n const before = options?.before;\n const after = options?.after;\n const limit = options?.limit;\n const full_scan = want_count || want_names;\n\n if (Array.isArray(input) && input.length === 0) {\n return new Map<string, StreamStats<E>>();\n }\n\n // Build WHERE clause + positional args. Subscription-level filters\n // (source, blocked) are intentionally not accepted — events live in\n // the events table; subscription state in the streams table. For\n // \"stats for blocked subscriptions\" callers compose with\n // query_streams. So no JOIN here.\n const where: string[] = [];\n const args: unknown[] = [];\n\n if (Array.isArray(input)) {\n const placeholders = input.map(() => \"?\").join(\",\");\n where.push(`e.stream IN (${placeholders})`);\n args.push(...input);\n } else if (input.stream !== undefined) {\n if (input.stream_exact) {\n where.push(`e.stream = ?`);\n args.push(input.stream);\n } else {\n where.push(`e.stream LIKE ?`);\n args.push(streamPatternToLike(input.stream));\n }\n }\n if (exclude.length) {\n const placeholders = exclude.map(() => \"?\").join(\",\");\n where.push(`e.name NOT IN (${placeholders})`);\n args.push(...exclude);\n }\n if (before !== undefined) {\n where.push(`e.id < ?`);\n args.push(before);\n }\n // Keyset pagination cursor (#1010): exclusive — return only streams\n // whose name sorts strictly after `after`. Applied at the event level\n // so the per-stream head/agg rows downstream only cover the page.\n if (after !== undefined) {\n where.push(`e.stream > ?`);\n args.push(after);\n }\n\n const from_clause = `events e`;\n // Always emit a WHERE clause — `WHERE 1=1` short-circuits the\n // empty-filter case without a conditional branch on the generation\n // side. SQLite optimizes the trivial predicate out.\n const where_clause = `WHERE ${where.length ? where.join(\" AND \") : \"1=1\"}`;\n\n return full_scan\n ? this._query_stats_full_scan<E>(\n from_clause,\n where_clause,\n args,\n want_tail,\n want_count,\n want_names,\n limit\n )\n : this._query_stats_heads_only<E>(\n from_clause,\n where_clause,\n args,\n want_tail,\n limit\n );\n }\n\n /**\n * Cheap path — head (and optional tail) via ROW_NUMBER() over the\n * `(stream, version)` unique index. Parallel queries when tail set.\n */\n private async _query_stats_heads_only<E extends Schemas>(\n from_clause: string,\n where_clause: string,\n args: unknown[],\n want_tail: boolean,\n limit?: number\n ): Promise<Map<string, StreamStats<E>>> {\n const cols = `e.id, e.stream, e.version, e.name, e.data, e.created, e.meta, e.pii`;\n // Keyset pagination (#1010): order heads by stream ascending so the\n // caller can use the last key as the next `after` cursor; cap with\n // LIMIT when set (unbounded otherwise).\n const limit_clause = limit !== undefined ? \" LIMIT ?\" : \"\";\n const head_sql = `SELECT * FROM (\n SELECT ${cols}, ROW_NUMBER() OVER (PARTITION BY e.stream ORDER BY e.version DESC) AS rn\n FROM ${from_clause}\n ${where_clause}\n ) WHERE rn = 1 ORDER BY stream${limit_clause}`;\n const head_args = limit !== undefined ? [...args, limit] : args;\n // The tail query shares the same WHERE; when paginating it must cover\n // exactly the limited head stream set, so it joins against the same\n // ordered+limited heads subquery rather than re-scanning all streams.\n const tail_sql = want_tail\n ? `SELECT t.* FROM (\n SELECT ${cols}, ROW_NUMBER() OVER (PARTITION BY e.stream ORDER BY e.version ASC) AS rn\n FROM ${from_clause}\n ${where_clause}\n ) t\n WHERE t.rn = 1 AND t.stream IN (\n SELECT stream FROM (\n SELECT e.stream, ROW_NUMBER() OVER (PARTITION BY e.stream ORDER BY e.version DESC) AS rn\n FROM ${from_clause}\n ${where_clause}\n ) WHERE rn = 1 ORDER BY stream${limit_clause}\n )`\n : null;\n const tail_args =\n limit !== undefined ? [...args, ...args, limit] : [...args, ...args];\n\n const [headRes, tailRes] = await Promise.all([\n this.client.execute({ sql: head_sql, args: head_args as any[] }),\n tail_sql\n ? this.client.execute({ sql: tail_sql, args: tail_args as any[] })\n : null,\n ]);\n\n const to_committed = async (\n row: Record<string, unknown>\n ): Promise<Committed<E, keyof E>> =>\n ({\n id: Number(row.id),\n stream: row.stream as string,\n version: Number(row.version),\n name: row.name as string,\n data: JSON.parse(row.data as string),\n meta: JSON.parse(row.meta as string),\n created: new Date(row.created as string),\n pii: await this._parse_pii_from_read(row.pii),\n }) as Committed<E, keyof E>;\n\n const out = new Map<string, StreamStats<E>>();\n for (const row of headRes.rows) {\n out.set(row.stream as string, {\n head: await to_committed(row as Record<string, unknown>),\n });\n }\n if (tailRes) {\n for (const row of tailRes.rows) {\n // Head and tail share the same WHERE, so any stream returning\n // a tail must also have returned a head — no null check needed.\n (\n out.get(row.stream as string) as {\n head: Committed<E, keyof E>;\n tail?: Committed<E, keyof E>;\n }\n ).tail = await to_committed(row as Record<string, unknown>);\n }\n }\n return out;\n }\n\n /**\n * Full-scan path — one CTE-based query with per-stream `COUNT(*)` and\n * `json_group_object(name, n)`. Heads (and optional tails) ride free\n * on the same scan.\n */\n private async _query_stats_full_scan<E extends Schemas>(\n from_clause: string,\n where_clause: string,\n args: unknown[],\n want_tail: boolean,\n want_count: boolean,\n want_names: boolean,\n limit?: number\n ): Promise<Map<string, StreamStats<E>>> {\n const tail_cte = want_tail\n ? `, tails AS (\n SELECT * FROM (\n SELECT *, ROW_NUMBER() OVER (PARTITION BY stream ORDER BY version ASC) AS rn FROM ef\n ) WHERE rn = 1\n )`\n : \"\";\n const tail_join = want_tail\n ? `LEFT JOIN tails t ON t.stream = h.stream`\n : \"\";\n const tail_cols = want_tail\n ? `, t.id AS t_id, t.stream AS t_stream, t.version AS t_version,\n t.name AS t_name, t.data AS t_data, t.created AS t_created, t.meta AS t_meta, t.pii AS t_pii`\n : \"\";\n\n const sql = `\n WITH ef AS (\n SELECT e.id, e.stream, e.version, e.name, e.data, e.created, e.meta, e.pii\n FROM ${from_clause}\n ${where_clause}\n ),\n agg AS (\n SELECT stream,\n SUM(n) AS cnt,\n json_group_object(name, n) AS names\n FROM (\n SELECT stream, name, COUNT(*) AS n\n FROM ef\n GROUP BY stream, name\n )\n GROUP BY stream\n ),\n heads AS (\n SELECT * FROM (\n SELECT *, ROW_NUMBER() OVER (PARTITION BY stream ORDER BY version DESC) AS rn FROM ef\n ) WHERE rn = 1\n ORDER BY stream${limit !== undefined ? \" LIMIT ?\" : \"\"}\n )\n ${tail_cte}\n SELECT\n h.id, h.stream, h.version, h.name, h.data, h.created, h.meta, h.pii,\n a.cnt AS agg_count,\n a.names AS agg_names\n ${tail_cols}\n FROM heads h\n LEFT JOIN agg a ON a.stream = h.stream\n ${tail_join}\n ORDER BY h.stream\n `;\n\n // Keyset pagination (#1010): the `heads` CTE is ordered by stream and\n // capped with LIMIT (when set); the final SELECT re-asserts stream\n // order so the returned Map's key order is the next cursor. The LIMIT\n // arg binds last when present (unbounded otherwise).\n const full_args = limit !== undefined ? [...args, limit] : args;\n const res = await this.client.execute({ sql, args: full_args as any[] });\n\n const to_committed = async (\n id: unknown,\n stream: unknown,\n version: unknown,\n name: unknown,\n data: unknown,\n meta: unknown,\n created: unknown,\n pii: unknown\n ): Promise<Committed<E, keyof E>> =>\n ({\n id: Number(id),\n stream: stream as string,\n version: Number(version),\n name: name as string,\n data: JSON.parse(data as string),\n meta: JSON.parse(meta as string),\n created: new Date(created as string),\n pii: await this._parse_pii_from_read(pii),\n }) as Committed<E, keyof E>;\n\n const out = new Map<string, StreamStats<E>>();\n for (const row of res.rows) {\n const r = row as unknown as Record<string, unknown>;\n const stats: {\n head: Committed<E, keyof E>;\n tail?: Committed<E, keyof E>;\n count?: number;\n names?: Record<string, number>;\n } = {\n head: await to_committed(\n r.id,\n r.stream,\n r.version,\n r.name,\n r.data,\n r.meta,\n r.created,\n r.pii\n ),\n };\n if (want_tail && r.t_id !== null && r.t_id !== undefined) {\n stats.tail = await to_committed(\n r.t_id,\n r.t_stream,\n r.t_version,\n r.t_name,\n r.t_data,\n r.t_meta,\n r.t_created,\n r.t_pii\n );\n }\n if (want_count) stats.count = Number(r.agg_count);\n // `agg_names` is non-null when this row exists: heads and agg are\n // both built from the same `ef` CTE, so any stream in heads has\n // at least one matching event and `json_group_object` returns a\n // JSON string (never null) for that group.\n if (want_names) stats.names = JSON.parse(r.agg_names as string);\n out.set(r.stream as string, stats as StreamStats<E>);\n }\n return out;\n }\n\n // --- prioritize: bulk priority update with filter (ACT-102) ---\n async prioritize(filter: StreamFilter, priority: number): Promise<number> {\n const { clause, args: filterArgs } = this._filter_clause(filter);\n // libSQL `?` placeholders are positional and NOT reusable, so we\n // bind `priority` twice: once for SET, once for the no-op skip\n // in WHERE.\n const sql = `UPDATE streams SET priority = ?\n WHERE priority <> ? AND ${clause}`;\n const result = await this.client.execute({\n sql,\n args: [priority, priority, ...filterArgs] as any[],\n });\n return result.rowsAffected;\n }\n\n // --- truncate: transactional delete + seed ---\n async truncate(\n targets: Array<{\n stream: string;\n snapshot?: Record<string, unknown>;\n meta?: EventMeta;\n }>\n ) {\n const result = new Map<\n string,\n { deleted: number; committed: Committed<Schemas, keyof Schemas> }\n >();\n\n const tx = await this.client.transaction(\"write\");\n try {\n for (const { stream, snapshot, meta } of targets) {\n const count_row = await tx.execute({\n sql: \"SELECT COUNT(*) as c FROM events WHERE stream = ?\",\n args: [stream],\n });\n const deleted = Number(count_row.rows[0].c);\n await tx.execute({\n sql: \"DELETE FROM events WHERE stream = ?\",\n args: [stream],\n });\n await tx.execute({\n sql: \"DELETE FROM streams WHERE stream = ?\",\n args: [stream],\n });\n\n const event_name =\n snapshot !== undefined ? \"__snapshot__\" : \"__tombstone__\";\n const event_meta = meta ?? { correlation: \"\", causation: {} };\n const now = new Date().toISOString();\n const ins = await tx.execute({\n sql: \"INSERT INTO events (stream, version, name, data, meta, created) VALUES (?, 0, ?, ?, ?, ?)\",\n args: [\n stream,\n event_name,\n JSON.stringify(snapshot ?? {}),\n JSON.stringify(event_meta),\n now,\n ],\n });\n\n result.set(stream, {\n deleted,\n committed: {\n id: Number(ins.lastInsertRowid),\n stream,\n version: 0,\n created: new Date(now),\n name: event_name,\n data: snapshot ?? {},\n meta: event_meta,\n },\n });\n }\n await tx.commit();\n } catch (e) {\n await tx.rollback();\n throw e;\n }\n\n return result;\n }\n\n /**\n * Atomically wipe-and-rebuild the store inside a single libsql\n * `write` transaction.\n *\n * On any throw inside the driver the transaction rolls back and the\n * store is byte-for-byte unchanged. `DELETE FROM events` + `DELETE\n * FROM streams` wipe both tables; `DELETE FROM sqlite_sequence\n * WHERE name = 'events'` resets the autoincrement counter so the\n * new sequence is dense from 1. `created` is preserved verbatim\n * from the source.\n */\n async restore(\n driver: (\n callback: (event: Committed<Schemas, keyof Schemas>) => Promise<number>\n ) => Promise<void>\n ): Promise<void> {\n const tx = await this.client.transaction(\"write\");\n try {\n await tx.execute(\"DELETE FROM events\");\n await tx.execute(\"DELETE FROM streams\");\n // Reset the autoincrement counter so the new sequence is dense\n // from 1. `DELETE FROM sqlite_sequence WHERE name = '?'` is the\n // canonical SQLite reset; safe even if the row doesn't exist.\n await tx.execute(\"DELETE FROM sqlite_sequence WHERE name = 'events'\");\n await driver(async (event) => {\n const pii_for_write = await this._stringify_pii_for_write(event.pii);\n const ins = await tx.execute({\n sql: \"INSERT INTO events (stream, version, name, data, meta, created, pii) VALUES (?, ?, ?, ?, ?, ?, ?)\",\n args: [\n event.stream,\n event.version,\n event.name,\n JSON.stringify(event.data),\n JSON.stringify(event.meta),\n event.created.toISOString(),\n pii_for_write,\n ],\n });\n return Number(ins.lastInsertRowid);\n });\n await tx.commit();\n } catch (error) {\n await tx.rollback();\n throw error;\n }\n }\n\n /**\n * Wipe the sensitive-data payload for every event on the stream — the\n * physical-erasure side of the sensitive-data epic (#566). Sets\n * `events.pii` to `NULL` for the stream's events; `events.data` and\n * the rest of the row are never touched.\n *\n * Single `UPDATE` under SQLite's writer lock, bounded by events-per-\n * stream. Idempotent — the `pii IS NOT NULL` predicate filters out\n * already-wiped rows so a second call returns `0`.\n *\n * SQLite doesn't auto-reclaim space; freed pages stay in the file\n * until an operator-scheduled `PRAGMA incremental_vacuum` or a full\n * `VACUUM`. The production checklist documents the cadence.\n *\n * @param stream Target stream\n * @returns Count of events whose `pii` was set to `NULL`\n */\n async forget_pii(stream: string): Promise<number> {\n const r = await this.client.execute({\n sql: \"UPDATE events SET pii = NULL WHERE stream = ? AND pii IS NOT NULL\",\n args: [stream],\n });\n return r.rowsAffected ?? 0;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,oBAA0C;AAiB1C,iBAA2B;AAC3B,wBAKO;AAuCP,IAAM,iBAA+B;AAAA,EACnC,KAAK;AACP;AAeO,SAAS,oBAAoB,OAAuB;AACzD,MAAI,IAAI;AACR,QAAM,QAAQ,EAAE,WAAW,GAAG;AAC9B,QAAM,MAAM,EAAE,SAAS,GAAG;AAC1B,MAAI,MAAO,KAAI,EAAE,MAAM,CAAC;AACxB,MAAI,IAAK,KAAI,EAAE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f,CAAC;AACD,WAAO,EAAE,gBAAgB;AAAA,EAC3B;AACF;","names":[]}
|
package/dist/index.js
CHANGED
|
@@ -108,7 +108,8 @@ var SqliteStore = class {
|
|
|
108
108
|
leased_by TEXT,
|
|
109
109
|
leased_until TEXT,
|
|
110
110
|
priority INTEGER NOT NULL DEFAULT 0,
|
|
111
|
-
lane TEXT NOT NULL DEFAULT 'default'
|
|
111
|
+
lane TEXT NOT NULL DEFAULT 'default',
|
|
112
|
+
deferred_at TEXT
|
|
112
113
|
)
|
|
113
114
|
`);
|
|
114
115
|
try {
|
|
@@ -117,6 +118,12 @@ var SqliteStore = class {
|
|
|
117
118
|
);
|
|
118
119
|
} catch {
|
|
119
120
|
}
|
|
121
|
+
try {
|
|
122
|
+
await this.client.execute(
|
|
123
|
+
"ALTER TABLE streams ADD COLUMN deferred_at TEXT"
|
|
124
|
+
);
|
|
125
|
+
} catch {
|
|
126
|
+
}
|
|
120
127
|
try {
|
|
121
128
|
await this.client.execute(
|
|
122
129
|
"ALTER TABLE streams ADD COLUMN lane TEXT NOT NULL DEFAULT 'default'"
|
|
@@ -313,9 +320,10 @@ var SqliteStore = class {
|
|
|
313
320
|
const lane_clause = lane !== void 0 ? " AND lane = ?" : "";
|
|
314
321
|
const result = await tx.execute({
|
|
315
322
|
sql: `SELECT stream, source, at, priority, lane FROM streams
|
|
316
|
-
WHERE blocked = 0 AND (leased_until IS NULL OR leased_until <= ?)
|
|
323
|
+
WHERE blocked = 0 AND (leased_until IS NULL OR leased_until <= ?)
|
|
324
|
+
AND (deferred_at IS NULL OR deferred_at <= ?)${lane_clause}
|
|
317
325
|
ORDER BY priority DESC, at ASC`,
|
|
318
|
-
args: lane !== void 0 ? [now, lane] : [now]
|
|
326
|
+
args: lane !== void 0 ? [now, now, lane] : [now, now]
|
|
319
327
|
});
|
|
320
328
|
const candidates = [];
|
|
321
329
|
for (const row of result.rows) {
|
|
@@ -385,7 +393,7 @@ var SqliteStore = class {
|
|
|
385
393
|
const result = [];
|
|
386
394
|
for (const l of leases) {
|
|
387
395
|
const r = await tx.execute({
|
|
388
|
-
sql: `UPDATE streams SET at = ?, leased_by = NULL, leased_until = NULL, retry = -1
|
|
396
|
+
sql: `UPDATE streams SET at = ?, leased_by = NULL, leased_until = NULL, retry = -1, deferred_at = NULL
|
|
389
397
|
WHERE stream = ? AND leased_by = ?`,
|
|
390
398
|
args: [l.at, l.stream, l.by]
|
|
391
399
|
});
|
|
@@ -405,7 +413,7 @@ var SqliteStore = class {
|
|
|
405
413
|
const result = [];
|
|
406
414
|
for (const l of leases) {
|
|
407
415
|
const r = await tx.execute({
|
|
408
|
-
sql: `UPDATE streams SET blocked = 1, error =
|
|
416
|
+
sql: `UPDATE streams SET blocked = 1, error = ?, deferred_at = NULL
|
|
409
417
|
WHERE stream = ? AND leased_by = ? AND blocked = 0`,
|
|
410
418
|
args: [l.error, l.stream, l.by]
|
|
411
419
|
});
|
|
@@ -418,6 +426,38 @@ var SqliteStore = class {
|
|
|
418
426
|
throw new StoreError("block", { cause: e });
|
|
419
427
|
}
|
|
420
428
|
}
|
|
429
|
+
// --- defer: hold streams out of claim until deferred_at (#1090) ---
|
|
430
|
+
// Persisted as an ISO string (like leased_until) so claim's
|
|
431
|
+
// `deferred_at <= now` comparison is a lexicographic string compare.
|
|
432
|
+
// Cleared by ack/block/reset/unblock. See {@link Store.defer}.
|
|
433
|
+
async defer(input, deferred_at) {
|
|
434
|
+
const at_iso = new Date(deferred_at).toISOString();
|
|
435
|
+
const tx = await this.client.transaction("write");
|
|
436
|
+
try {
|
|
437
|
+
let count = 0;
|
|
438
|
+
if (Array.isArray(input)) {
|
|
439
|
+
for (const stream of input) {
|
|
440
|
+
const r = await tx.execute({
|
|
441
|
+
sql: `UPDATE streams SET deferred_at = ?, retry = -1 WHERE stream = ?`,
|
|
442
|
+
args: [at_iso, stream]
|
|
443
|
+
});
|
|
444
|
+
count += r.rowsAffected;
|
|
445
|
+
}
|
|
446
|
+
} else {
|
|
447
|
+
const { clause, args } = this._filter_clause(input);
|
|
448
|
+
const r = await tx.execute({
|
|
449
|
+
sql: `UPDATE streams SET deferred_at = ?, retry = -1 WHERE ${clause}`,
|
|
450
|
+
args: [at_iso, ...args]
|
|
451
|
+
});
|
|
452
|
+
count = r.rowsAffected;
|
|
453
|
+
}
|
|
454
|
+
await tx.commit();
|
|
455
|
+
return count;
|
|
456
|
+
} catch (e) {
|
|
457
|
+
await tx.rollback();
|
|
458
|
+
throw new StoreError("defer", { cause: e });
|
|
459
|
+
}
|
|
460
|
+
}
|
|
421
461
|
/**
|
|
422
462
|
* Translate a {@link StreamFilter} to a SQLite `WHERE` clause fragment
|
|
423
463
|
* plus positional args. Returns `"1"` (always true) when empty so
|
|
@@ -458,7 +498,7 @@ var SqliteStore = class {
|
|
|
458
498
|
// --- reset: transactional, accepts names or filter ---
|
|
459
499
|
async reset(input) {
|
|
460
500
|
const set_clause = `SET at = -1, retry = -1, blocked = 0, error = '',
|
|
461
|
-
leased_by = NULL, leased_until = NULL`;
|
|
501
|
+
leased_by = NULL, leased_until = NULL, deferred_at = NULL`;
|
|
462
502
|
const tx = await this.client.transaction("write");
|
|
463
503
|
try {
|
|
464
504
|
let count = 0;
|
|
@@ -490,7 +530,7 @@ var SqliteStore = class {
|
|
|
490
530
|
// matching the InMemoryStore convention.
|
|
491
531
|
async unblock(input) {
|
|
492
532
|
const set_clause = `SET retry = -1, blocked = 0, error = '',
|
|
493
|
-
leased_by = NULL, leased_until = NULL`;
|
|
533
|
+
leased_by = NULL, leased_until = NULL, deferred_at = NULL`;
|
|
494
534
|
const tx = await this.client.transaction("write");
|
|
495
535
|
try {
|
|
496
536
|
let count = 0;
|