@powerhousedao/reactor-api 6.2.3-dev.85 → 6.2.3-dev.86

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.
@@ -1,5 +1,5 @@
1
1
 
2
- !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="67ef2060-b4e7-5104-b280-60179cc2bdd7")}catch(e){}}();
2
+ !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="32154524-8414-5e0c-bd0b-eb61f765c647")}catch(e){}}();
3
3
  import path from "node:path";
4
4
  import nodeFs, { promises } from "node:fs";
5
5
  import { protocol } from "@electric-sql/pglite";
@@ -22,6 +22,15 @@ const DEFAULT_VACUUM_FULL_MAX_DEFER_MS = 0;
22
22
  /** The deadline `PH_PGLITE_VACUUM_FULL=forced` sets. */
23
23
  const FORCED_VACUUM_FULL_MAX_DEFER_MS = 18e5;
24
24
  const MAINTENANCE_RETRY_MS = 1e3;
25
+ /**
26
+ * A table rewrite waits for this long a gap between the store's statements.
27
+ * Short, because PGlite syncs after every statement and an idle reactor still
28
+ * reads every 2 s (catch-up, sync polls), so a longer gap never comes.
29
+ */
30
+ const DEFAULT_REWRITE_QUIET_MS = 1e3;
31
+ /** How long a table rewrite waits for that gap before it reports the store busy. */
32
+ const DEFAULT_REWRITE_MAX_WAIT_MS = 9e5;
33
+ const REWRITE_POLL_MS = 250;
25
34
  var PgliteMaintenance = class {
26
35
  intervalMs;
27
36
  vacuumFullAboveBytes;
@@ -30,6 +39,8 @@ var PgliteMaintenance = class {
30
39
  gate;
31
40
  logger;
32
41
  now;
42
+ rewriteQuietMs;
43
+ rewriteMaxWaitMs;
33
44
  pg;
34
45
  label = "";
35
46
  closing = false;
@@ -41,6 +52,7 @@ var PgliteMaintenance = class {
41
52
  deferralLogged = false;
42
53
  lastSyncAt = 0;
43
54
  openedAt = 0;
55
+ rewriting;
44
56
  constructor(options = {}) {
45
57
  this.intervalMs = Math.max(0, options.intervalMs ?? 3e5);
46
58
  this.vacuumFullAboveBytes = Math.max(0, options.vacuumFullAboveBytes ?? 268435456);
@@ -49,6 +61,8 @@ var PgliteMaintenance = class {
49
61
  this.gate = options.gate;
50
62
  this.logger = options.logger;
51
63
  this.now = options.now ?? Date.now;
64
+ this.rewriteQuietMs = options.rewriteQuietMs ?? 1e3;
65
+ this.rewriteMaxWaitMs = options.rewriteMaxWaitMs ?? 9e5;
52
66
  }
53
67
  get scheduled() {
54
68
  return this.timer !== void 0;
@@ -73,11 +87,46 @@ var PgliteMaintenance = class {
73
87
  this.closing = true;
74
88
  this.cancel();
75
89
  if (this.active) await this.inFlight;
90
+ await this.rewriting;
76
91
  }
77
92
  async run() {
78
93
  if (this.gate) return this.gate(() => this.runNow());
79
94
  return this.runNow();
80
95
  }
96
+ /**
97
+ * Rewrites one table with VACUUM FULL and a CHECKPOINT, in the turn of the
98
+ * store's other work, never the whole store. Waits for a gap in the store's
99
+ * statements first; nothing else runs on it while the table is rewritten.
100
+ */
101
+ async rewriteTable(request) {
102
+ const shortOfDisk = await this.diskShortage(request.requiredFreeBytes);
103
+ if (shortOfDisk !== void 0) return {
104
+ outcome: "refused",
105
+ reason: shortOfDisk
106
+ };
107
+ const relation = `${quoteIdentifier(request.schema)}.${quoteIdentifier(request.table)}`;
108
+ const deadline = this.now() + this.rewriteMaxWaitMs;
109
+ for (;;) {
110
+ if (this.closing || !this.pg?.ready) return {
111
+ outcome: "refused",
112
+ reason: "the store is closing"
113
+ };
114
+ if (this.now() - this.lastSyncAt >= this.rewriteQuietMs) {
115
+ const attempt = this.gate ? this.gate(() => this.rewriteNow(relation)) : this.rewriteNow(relation);
116
+ this.rewriting = attempt.catch(() => void 0);
117
+ const result = await attempt;
118
+ this.rewriting = void 0;
119
+ if (result !== void 0) return result;
120
+ }
121
+ if (this.now() >= deadline) return {
122
+ outcome: "busy",
123
+ reason: `The store had no gap of ${this.rewriteQuietMs} ms between statements in ${this.rewriteMaxWaitMs} ms, so ${relation} was not rewritten. Try again in a quieter moment.`
124
+ };
125
+ await new Promise((resolve) => {
126
+ setTimeout(resolve, REWRITE_POLL_MS);
127
+ });
128
+ }
129
+ }
81
130
  async runNow() {
82
131
  this.active = true;
83
132
  try {
@@ -129,6 +178,62 @@ var PgliteMaintenance = class {
129
178
  }
130
179
  return outcome;
131
180
  }
181
+ /** Undefined when a transaction is open, so the caller waits and tries again. */
182
+ async rewriteNow(relation) {
183
+ const pg = this.pg;
184
+ if (this.closing || !pg?.ready) return {
185
+ outcome: "refused",
186
+ reason: "the store is closing"
187
+ };
188
+ const isReady = () => pg.ready && !this.closing;
189
+ const startedAt = this.now();
190
+ const bytesBefore = await dirBytes(path.join(this.label, "base"));
191
+ let completed;
192
+ try {
193
+ completed = await pg._runExclusiveQuery(async () => {
194
+ if (!isReady()) return false;
195
+ const { messages } = await pg.execProtocol(protocol.serialize.query(""), { syncToFs: false });
196
+ if (transactionStatus(messages) !== "I") return void 0;
197
+ this.logger?.warn(`DurableNodeFs: ${this.label}: running VACUUM FULL ${relation}`);
198
+ for (const statement of [`VACUUM FULL ${relation}`, "CHECKPOINT"]) {
199
+ if (!isReady()) return false;
200
+ await pg.execProtocol(protocol.serialize.query(statement), { syncToFs: false });
201
+ }
202
+ return true;
203
+ });
204
+ } catch (err) {
205
+ return {
206
+ outcome: "refused",
207
+ reason: `VACUUM FULL ${relation} failed: ${errorMessage(err)}`
208
+ };
209
+ }
210
+ if (completed === void 0) return void 0;
211
+ if (!completed) return {
212
+ outcome: "refused",
213
+ reason: "the store is closing"
214
+ };
215
+ const durationMs = this.now() - startedAt;
216
+ const bytesAfter = await dirBytes(path.join(this.label, "base"));
217
+ const message = `DurableNodeFs: ${this.label}/base VACUUM FULL ${relation} finished in ${durationMs} ms; ${bytesBefore} -> ${bytesAfter} bytes`;
218
+ if (this.logger?.info) this.logger.info(message);
219
+ else this.logger?.warn(message);
220
+ return {
221
+ outcome: "done",
222
+ durationMs
223
+ };
224
+ }
225
+ /** Why the disk cannot hold the rewrite; undefined when it can or nobody can tell. */
226
+ async diskShortage(requiredFreeBytes) {
227
+ if (requiredFreeBytes <= 0 || !this.label) return void 0;
228
+ let freeBytes;
229
+ try {
230
+ const stats = await promises.statfs(this.label);
231
+ freeBytes = stats.bavail * stats.bsize;
232
+ } catch {
233
+ return;
234
+ }
235
+ return freeBytes < requiredFreeBytes ? `The rewrite needs about ${requiredFreeBytes} bytes of free disk at ${this.label}; ${freeBytes} are free.` : void 0;
236
+ }
132
237
  schedule(delayMs) {
133
238
  if (this.intervalMs === 0 || this.closing) return;
134
239
  this.timer = setTimeout(() => {
@@ -165,6 +270,14 @@ async function dirBytes(dir) {
165
270
  }
166
271
  return total;
167
272
  }
273
+ function quoteIdentifier(name) {
274
+ return `"${name.replaceAll("\"", "\"\"")}"`;
275
+ }
276
+ /** The maintenance of a store opened on DurableNodeFs; undefined for any other. */
277
+ function maintenanceOf(store) {
278
+ const maintenance = store.fs?.maintenance;
279
+ return maintenance instanceof PgliteMaintenance ? maintenance : void 0;
280
+ }
168
281
  function transactionStatus(messages) {
169
282
  for (let i = messages.length - 1; i >= 0; i--) {
170
283
  const m = messages[i];
@@ -309,6 +422,8 @@ function createDurableNodeFs(Base, dataDir, options = {}) {
309
422
  vacuumFullMaxDeferMs: options.vacuumFullMaxDeferMs,
310
423
  gate: options.maintenanceGate,
311
424
  now: options.now,
425
+ rewriteQuietMs: options.rewriteQuietMs,
426
+ rewriteMaxWaitMs: options.rewriteMaxWaitMs,
312
427
  logger
313
428
  });
314
429
  class Durable extends Base {
@@ -480,7 +595,7 @@ function describe(value) {
480
595
  }
481
596
  }
482
597
  //#endregion
483
- export { resolvePgliteMaintenance as a, DEFAULT_MAINTENANCE_INTERVAL_MS as c, DEFAULT_VACUUM_FULL_QUIET_MS as d, FORCED_VACUUM_FULL_MAX_DEFER_MS as f, resolvePgliteFsync as i, DEFAULT_VACUUM_FULL_ABOVE_BYTES as l, PGLITE_UTC_PARSERS as m, toPGliteErrorInfo as n, syncDirectory as o, PgliteMaintenance as p, createDurableNodeFs as r, syncTree as s, fromPGliteErrorInfo as t, DEFAULT_VACUUM_FULL_MAX_DEFER_MS as u };
598
+ export { PGLITE_UTC_PARSERS as _, resolvePgliteMaintenance as a, DEFAULT_MAINTENANCE_INTERVAL_MS as c, DEFAULT_VACUUM_FULL_ABOVE_BYTES as d, DEFAULT_VACUUM_FULL_MAX_DEFER_MS as f, maintenanceOf as g, PgliteMaintenance as h, resolvePgliteFsync as i, DEFAULT_REWRITE_MAX_WAIT_MS as l, FORCED_VACUUM_FULL_MAX_DEFER_MS as m, toPGliteErrorInfo as n, syncDirectory as o, DEFAULT_VACUUM_FULL_QUIET_MS as p, createDurableNodeFs as r, syncTree as s, fromPGliteErrorInfo as t, DEFAULT_REWRITE_QUIET_MS as u };
484
599
 
485
- //# sourceMappingURL=error-info-BaEL50f5.mjs.map
486
- //# debugId=67ef2060-b4e7-5104-b280-60179cc2bdd7
600
+ //# sourceMappingURL=error-info-Cr6oQACe.mjs.map
601
+ //# debugId=32154524-8414-5e0c-bd0b-eb61f765c647
@@ -0,0 +1 @@
1
+ {"version":3,"file":"error-info-Cr6oQACe.mjs","sources":["../src/pglite/parsers.ts","../src/pglite/maintenance.ts","../src/pglite/sync-tree.ts","../src/pglite/durable-node-fs.ts","../src/pglite/worker/error-info.ts"],"sourcesContent":["// PGlite parses `timestamp` (no tz) columns as local time; read-model columns\n// store UTC, so parse them as UTC or values shift by the host's TZ offset.\nexport const PGLITE_UTC_PARSERS = {\n // 1114 = timestamp without time zone\n 1114: (value: string) => new Date(`${value.replace(\" \", \"T\")}Z`),\n} as const;\n","import { protocol, type PGlite } from \"@electric-sql/pglite\";\nimport type {\n IStoreMaintenance,\n TableRewriteRequest,\n TableRewriteResult,\n} from \"@powerhousedao/reactor\";\nimport { promises as fs } from \"node:fs\";\nimport path from \"node:path\";\n\nexport const DEFAULT_MAINTENANCE_INTERVAL_MS = 5 * 60 * 1000;\nexport const DEFAULT_VACUUM_FULL_ABOVE_BYTES = 256 * 1024 * 1024;\nexport const DEFAULT_VACUUM_FULL_QUIET_MS = 60 * 1000;\n/**\n * How long a pending VACUUM FULL waits for a quiet store before it runs\n * anyway: by default it never does (0), because a forced rewrite of a large\n * store under load holds the only connection for minutes, every caller times\n * out, and the dir needs about twice its size in free space meanwhile.\n * `PH_PGLITE_VACUUM_FULL=forced` restores a deadline.\n */\nexport const DEFAULT_VACUUM_FULL_MAX_DEFER_MS = 0;\n/** The deadline `PH_PGLITE_VACUUM_FULL=forced` sets. */\nexport const FORCED_VACUUM_FULL_MAX_DEFER_MS = 30 * 60_000;\nconst MAINTENANCE_RETRY_MS = 1000;\n/**\n * A table rewrite waits for this long a gap between the store's statements.\n * Short, because PGlite syncs after every statement and an idle reactor still\n * reads every 2 s (catch-up, sync polls), so a longer gap never comes.\n */\nexport const DEFAULT_REWRITE_QUIET_MS = 1_000;\n/** How long a table rewrite waits for that gap before it reports the store busy. */\nexport const DEFAULT_REWRITE_MAX_WAIT_MS = 15 * 60_000;\nconst REWRITE_POLL_MS = 250;\n\nexport type MaintenanceOutcome =\n | \"vacuum\"\n | \"vacuum-full\"\n | \"idle\"\n | \"not-ready\"\n | \"in-transaction\"\n | \"failed\";\n\nexport interface MaintenanceLogger {\n warn(message: string): void;\n /** A finished VACUUM FULL is reported here; `warn` when absent. */\n info?(message: string): void;\n}\n\n/** Runs a maintenance pass in the owner's turn; see {@link MaintenanceOptions.gate}. */\nexport type MaintenanceGate = <T>(task: () => Promise<T>) => Promise<T>;\n\nexport interface MaintenanceOptions {\n /** VACUUM + CHECKPOINT cadence; PGlite has no autovacuum. Default 5 min; 0 disables. */\n intervalMs?: number;\n /** First pass runs VACUUM FULL when `base/` exceeds this at open. Default 256 MB; 0 disables. */\n vacuumFullAboveBytes?: number;\n /**\n * VACUUM FULL holds the store for minutes on a large dir, so it waits for a\n * store with no synced statement (no write, no catch-up) for this long,\n * counted from open; until then a pass runs plain VACUUM and keeps the\n * VACUUM FULL pending. Default 60 s; 0 runs it on the first pass.\n */\n vacuumFullQuietMs?: number;\n /**\n * The longest a pending VACUUM FULL waits for that quiet window, counted\n * from open; past it the next pass runs VACUUM FULL anyway. Default 0,\n * which waits for the quiet window however long it takes.\n */\n vacuumFullMaxDeferMs?: number;\n /**\n * Queues each pass with the store's other work, e.g. behind a worker's\n * pending requests, so a pass never starts ahead of a statement already\n * admitted. A pass still waiting here when the store closes is skipped.\n */\n gate?: MaintenanceGate;\n logger?: MaintenanceLogger;\n /** Clock for the quiet window; tests pass their own. */\n now?: () => number;\n /** The gap between statements a table rewrite waits for. Default 1 s. */\n rewriteQuietMs?: number;\n /** How long a table rewrite waits for that gap. Default 15 min. */\n rewriteMaxWaitMs?: number;\n}\n\nexport class PgliteMaintenance implements IStoreMaintenance {\n private readonly intervalMs: number;\n private readonly vacuumFullAboveBytes: number;\n private readonly vacuumFullQuietMs: number;\n private readonly vacuumFullMaxDeferMs: number;\n private readonly gate?: MaintenanceGate;\n private readonly logger?: MaintenanceLogger;\n private readonly now: () => number;\n private readonly rewriteQuietMs: number;\n private readonly rewriteMaxWaitMs: number;\n\n private pg?: PGlite;\n private label = \"\";\n private closing = false;\n private syncsSinceMaintenance = 0;\n private vacuumFullPending = false;\n private timer?: ReturnType<typeof setTimeout>;\n private inFlight?: Promise<MaintenanceOutcome>;\n private active = false;\n private deferralLogged = false;\n private lastSyncAt = 0;\n private openedAt = 0;\n private rewriting?: Promise<TableRewriteResult | undefined>;\n\n constructor(options: MaintenanceOptions = {}) {\n this.intervalMs = Math.max(\n 0,\n options.intervalMs ?? DEFAULT_MAINTENANCE_INTERVAL_MS,\n );\n this.vacuumFullAboveBytes = Math.max(\n 0,\n options.vacuumFullAboveBytes ?? DEFAULT_VACUUM_FULL_ABOVE_BYTES,\n );\n this.vacuumFullQuietMs = Math.max(\n 0,\n options.vacuumFullQuietMs ?? DEFAULT_VACUUM_FULL_QUIET_MS,\n );\n this.vacuumFullMaxDeferMs = Math.max(\n 0,\n options.vacuumFullMaxDeferMs ?? DEFAULT_VACUUM_FULL_MAX_DEFER_MS,\n );\n this.gate = options.gate;\n this.logger = options.logger;\n this.now = options.now ?? Date.now;\n this.rewriteQuietMs = options.rewriteQuietMs ?? DEFAULT_REWRITE_QUIET_MS;\n this.rewriteMaxWaitMs =\n options.rewriteMaxWaitMs ?? DEFAULT_REWRITE_MAX_WAIT_MS;\n }\n\n get scheduled(): boolean {\n return this.timer !== undefined;\n }\n\n get running(): boolean {\n return this.inFlight !== undefined;\n }\n\n start(pg: PGlite, label: string, baseBytes: number): void {\n this.pg = pg;\n this.label = label;\n this.vacuumFullPending =\n this.vacuumFullAboveBytes > 0 && baseBytes > this.vacuumFullAboveBytes;\n this.lastSyncAt = this.now();\n this.openedAt = this.lastSyncAt;\n this.schedule(this.intervalMs);\n }\n\n noteSync(): void {\n this.syncsSinceMaintenance++;\n this.lastSyncAt = this.now();\n }\n\n /** Waits for a pass that has started; one still queued at the gate is left to skip itself. */\n async stop(): Promise<void> {\n this.closing = true;\n this.cancel();\n if (this.active) await this.inFlight;\n await this.rewriting;\n }\n\n async run(): Promise<MaintenanceOutcome> {\n if (this.gate) return this.gate(() => this.runNow());\n return this.runNow();\n }\n\n /**\n * Rewrites one table with VACUUM FULL and a CHECKPOINT, in the turn of the\n * store's other work, never the whole store. Waits for a gap in the store's\n * statements first; nothing else runs on it while the table is rewritten.\n */\n async rewriteTable(\n request: TableRewriteRequest,\n ): Promise<TableRewriteResult> {\n const shortOfDisk = await this.diskShortage(request.requiredFreeBytes);\n if (shortOfDisk !== undefined) {\n return { outcome: \"refused\", reason: shortOfDisk };\n }\n const relation = `${quoteIdentifier(request.schema)}.${quoteIdentifier(request.table)}`;\n const deadline = this.now() + this.rewriteMaxWaitMs;\n for (;;) {\n if (this.closing || !this.pg?.ready) {\n return { outcome: \"refused\", reason: \"the store is closing\" };\n }\n if (this.now() - this.lastSyncAt >= this.rewriteQuietMs) {\n const attempt = this.gate\n ? this.gate(() => this.rewriteNow(relation))\n : this.rewriteNow(relation);\n this.rewriting = attempt.catch(() => undefined);\n const result = await attempt;\n this.rewriting = undefined;\n if (result !== undefined) return result;\n }\n if (this.now() >= deadline) {\n return {\n outcome: \"busy\",\n reason: `The store had no gap of ${this.rewriteQuietMs} ms between statements in ${this.rewriteMaxWaitMs} ms, so ${relation} was not rewritten. Try again in a quieter moment.`,\n };\n }\n await new Promise((resolve) => {\n setTimeout(resolve, REWRITE_POLL_MS);\n });\n }\n }\n\n private async runNow(): Promise<MaintenanceOutcome> {\n this.active = true;\n try {\n return await this.pass();\n } finally {\n this.active = false;\n }\n }\n\n private async pass(): Promise<MaintenanceOutcome> {\n const pg = this.pg;\n if (this.closing || !pg?.ready) return \"not-ready\";\n // pg.close() does not take the query mutex; recheck before each statement.\n const isReady = (): boolean => pg.ready && !this.closing;\n const now = this.now();\n const overdue =\n this.vacuumFullMaxDeferMs > 0 &&\n now - this.openedAt >= this.vacuumFullMaxDeferMs;\n const full =\n this.vacuumFullPending &&\n (now - this.lastSyncAt >= this.vacuumFullQuietMs || overdue);\n if (this.vacuumFullPending && !full && !this.deferralLogged) {\n this.deferralLogged = true;\n this.logger?.warn(\n `DurableNodeFs: ${this.label}/base exceeds ${this.vacuumFullAboveBytes} bytes; VACUUM FULL waits until the store has had no writes for ${this.vacuumFullQuietMs} ms${this.vacuumFullMaxDeferMs > 0 ? `, or at most ${this.vacuumFullMaxDeferMs} ms from open` : \"\"}`,\n );\n }\n if (!full && this.syncsSinceMaintenance === 0) {\n return \"idle\";\n }\n const baseDir = path.join(this.label, \"base\");\n const bytesBefore = full ? await dirBytes(baseDir) : 0;\n const startedAt = this.now();\n let outcome: MaintenanceOutcome;\n try {\n outcome = await pg._runExclusiveQuery(async () => {\n // isInTransaction() misses START TRANSACTION; ReadyForQuery status does not.\n if (!isReady()) return \"not-ready\";\n const { messages } = await pg.execProtocol(\n protocol.serialize.query(\"\"),\n { syncToFs: false },\n );\n if (transactionStatus(messages) !== \"I\") return \"in-transaction\";\n if (full) {\n this.logger?.warn(\n `DurableNodeFs: ${this.label}/base exceeds ${this.vacuumFullAboveBytes} bytes; running VACUUM FULL`,\n );\n }\n for (const statement of [\n full ? \"VACUUM FULL\" : \"VACUUM\",\n \"CHECKPOINT\",\n ]) {\n if (!isReady()) return \"not-ready\";\n await pg.execProtocol(protocol.serialize.query(statement), {\n syncToFs: false,\n });\n }\n return full ? \"vacuum-full\" : \"vacuum\";\n });\n } catch (err) {\n this.logger?.warn(\n `DurableNodeFs maintenance failed: ${errorMessage(err)}`,\n );\n return \"failed\";\n }\n if (outcome !== \"vacuum\" && outcome !== \"vacuum-full\") return outcome;\n this.syncsSinceMaintenance = 0;\n if (full) {\n this.vacuumFullPending = false;\n const bytesAfter = await dirBytes(baseDir);\n const message = `DurableNodeFs: ${this.label}/base VACUUM FULL finished in ${this.now() - startedAt} ms; ${bytesBefore} -> ${bytesAfter} bytes`;\n if (this.logger?.info) this.logger.info(message);\n else this.logger?.warn(message);\n }\n return outcome;\n }\n\n /** Undefined when a transaction is open, so the caller waits and tries again. */\n private async rewriteNow(\n relation: string,\n ): Promise<TableRewriteResult | undefined> {\n const pg = this.pg;\n if (this.closing || !pg?.ready) {\n return { outcome: \"refused\", reason: \"the store is closing\" };\n }\n const isReady = (): boolean => pg.ready && !this.closing;\n const startedAt = this.now();\n const bytesBefore = await dirBytes(path.join(this.label, \"base\"));\n let completed: boolean | undefined;\n try {\n completed = await pg._runExclusiveQuery(async () => {\n if (!isReady()) return false;\n const { messages } = await pg.execProtocol(\n protocol.serialize.query(\"\"),\n { syncToFs: false },\n );\n if (transactionStatus(messages) !== \"I\") return undefined;\n this.logger?.warn(\n `DurableNodeFs: ${this.label}: running VACUUM FULL ${relation}`,\n );\n for (const statement of [`VACUUM FULL ${relation}`, \"CHECKPOINT\"]) {\n if (!isReady()) return false;\n await pg.execProtocol(protocol.serialize.query(statement), {\n syncToFs: false,\n });\n }\n return true;\n });\n } catch (err) {\n return {\n outcome: \"refused\",\n reason: `VACUUM FULL ${relation} failed: ${errorMessage(err)}`,\n };\n }\n if (completed === undefined) return undefined;\n if (!completed) {\n return { outcome: \"refused\", reason: \"the store is closing\" };\n }\n const durationMs = this.now() - startedAt;\n const bytesAfter = await dirBytes(path.join(this.label, \"base\"));\n const message = `DurableNodeFs: ${this.label}/base VACUUM FULL ${relation} finished in ${durationMs} ms; ${bytesBefore} -> ${bytesAfter} bytes`;\n if (this.logger?.info) this.logger.info(message);\n else this.logger?.warn(message);\n return { outcome: \"done\", durationMs };\n }\n\n /** Why the disk cannot hold the rewrite; undefined when it can or nobody can tell. */\n private async diskShortage(\n requiredFreeBytes: number,\n ): Promise<string | undefined> {\n if (requiredFreeBytes <= 0 || !this.label) return undefined;\n let freeBytes: number;\n try {\n const stats = await fs.statfs(this.label);\n freeBytes = stats.bavail * stats.bsize;\n } catch {\n return undefined;\n }\n return freeBytes < requiredFreeBytes\n ? `The rewrite needs about ${requiredFreeBytes} bytes of free disk at ${this.label}; ${freeBytes} are free.`\n : undefined;\n }\n\n private schedule(delayMs: number): void {\n if (this.intervalMs === 0 || this.closing) return;\n this.timer = setTimeout(() => {\n this.timer = undefined;\n this.inFlight = this.run()\n .then((outcome) => {\n this.schedule(\n outcome === \"in-transaction\"\n ? Math.min(MAINTENANCE_RETRY_MS, this.intervalMs)\n : this.intervalMs,\n );\n return outcome;\n })\n .finally(() => {\n this.inFlight = undefined;\n });\n }, delayMs);\n this.timer.unref();\n }\n\n private cancel(): void {\n if (!this.timer) return;\n clearTimeout(this.timer);\n this.timer = undefined;\n }\n}\n\n/** Total size of the regular files under `dir`; 0 when `dir` is missing. */\nexport async function dirBytes(dir: string): Promise<number> {\n let entries;\n try {\n entries = await fs.readdir(dir, { withFileTypes: true });\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") return 0;\n throw err;\n }\n let total = 0;\n for (const entry of entries) {\n const full = path.join(dir, entry.name);\n if (entry.isDirectory()) {\n total += await dirBytes(full);\n } else if (entry.isFile()) {\n total += (await fs.stat(full)).size;\n }\n }\n return total;\n}\n\nfunction quoteIdentifier(name: string): string {\n return `\"${name.replaceAll('\"', '\"\"')}\"`;\n}\n\n/** The maintenance of a store opened on DurableNodeFs; undefined for any other. */\nexport function maintenanceOf(store: {\n fs?: unknown;\n}): PgliteMaintenance | undefined {\n const maintenance = (store.fs as { maintenance?: unknown } | undefined)\n ?.maintenance;\n return maintenance instanceof PgliteMaintenance ? maintenance : undefined;\n}\n\nfunction transactionStatus(messages: readonly { name: string }[]): unknown {\n for (let i = messages.length - 1; i >= 0; i--) {\n const m = messages[i];\n if (m.name === \"readyForQuery\") return (m as { status?: unknown }).status;\n }\n return undefined;\n}\n\nfunction errorMessage(err: unknown): string {\n return err instanceof Error ? err.message : String(err);\n}\n","import nodeFs from \"node:fs\";\nimport path from \"node:path\";\n\nexport interface SyncTreeHostFs {\n fsyncSync(fd: number): void;\n}\n\nexport interface SyncTreeResult {\n files: number;\n dirs: number;\n}\n\n/** One pass over a finished tree; interleaving fsync with writes costs seconds. */\nexport function syncTree(\n root: string,\n hostFs: SyncTreeHostFs = nodeFs,\n): SyncTreeResult {\n const result: SyncTreeResult = { files: 0, dirs: 0 };\n const pending = [path.resolve(root)];\n while (pending.length > 0) {\n const dir = pending.pop()!;\n for (const entry of nodeFs.readdirSync(dir, { withFileTypes: true })) {\n const full = path.join(dir, entry.name);\n if (entry.isDirectory()) {\n pending.push(full);\n } else if (entry.isFile()) {\n syncFile(full, hostFs);\n result.files++;\n }\n }\n syncDirectory(dir, hostFs);\n result.dirs++;\n }\n return result;\n}\n\n// Windows refuses FlushFileBuffers on a read-only handle (EPERM).\nfunction syncFile(file: string, hostFs: SyncTreeHostFs): void {\n const fd = nodeFs.openSync(file, \"r+\");\n try {\n hostFs.fsyncSync(fd);\n } finally {\n nodeFs.closeSync(fd);\n }\n}\n\n/** fsyncs a directory's entries; false where the platform refuses (Windows). */\nexport function syncDirectory(\n dir: string,\n hostFs: SyncTreeHostFs = nodeFs,\n): boolean {\n let fd: number;\n try {\n fd = nodeFs.openSync(dir, \"r\");\n } catch {\n return false;\n }\n try {\n hostFs.fsyncSync(fd);\n return true;\n } catch {\n return false;\n } finally {\n nodeFs.closeSync(fd);\n }\n}\n","import type { PGlite } from \"@electric-sql/pglite\";\nimport { ERRNO_CODES } from \"@electric-sql/pglite/basefs\";\nimport type { NodeFS } from \"@electric-sql/pglite/nodefs\";\nimport nodeFs from \"node:fs\";\nimport path from \"node:path\";\nimport {\n dirBytes,\n FORCED_VACUUM_FULL_MAX_DEFER_MS,\n PgliteMaintenance,\n type MaintenanceGate,\n} from \"./maintenance.js\";\nimport { syncTree } from \"./sync-tree.js\";\n\nexport type NodeFsClass = typeof NodeFS;\n\n// Emscripten/WASI errno; the basefs ERRNO_CODES export lacks it.\nconst EIO = 29;\n\nexport interface DurableNodeFsOptions {\n /** Default true; `PH_PGLITE_FSYNC=0` turns it off (power-loss durability off). */\n fsync?: boolean;\n /** Default 5 min; 0 disables. */\n maintenanceIntervalMs?: number;\n /** `base/` size at open; default 256 MB; 0 disables. */\n vacuumFullAboveBytes?: number;\n /** See `MaintenanceOptions.vacuumFullQuietMs`; default 60 s. */\n vacuumFullQuietMs?: number;\n /** See `MaintenanceOptions.vacuumFullMaxDeferMs`; default 0 (quiet window only). */\n vacuumFullMaxDeferMs?: number;\n /** See `MaintenanceOptions.gate`. */\n maintenanceGate?: MaintenanceGate;\n /** The gap between statements a table rewrite waits for. Default 1 s. */\n rewriteQuietMs?: number;\n /** How long a table rewrite waits for that gap. Default 15 min. */\n rewriteMaxWaitMs?: number;\n /** Clock for the maintenance quiet window; tests pass their own. */\n now?: () => number;\n logger?: { warn(message: string): void; info?(message: string): void };\n /** Emscripten abort (a Postgres PANIC, e.g. ENOSPC on WAL). */\n onAbort?: (what: unknown) => void;\n hostFs?: Pick<typeof nodeFs, \"fsyncSync\" | \"fdatasyncSync\">;\n}\n\nexport type DurableNodeFs = InstanceType<NodeFsClass> & {\n readonly maintenance: PgliteMaintenance;\n};\n\nexport function resolvePgliteFsync(\n env: Record<string, string | undefined>,\n): boolean {\n return env.PH_PGLITE_FSYNC !== \"0\";\n}\n\n/** `PH_PGLITE_VACUUM_FULL`: when an oversized store's one-time VACUUM FULL may run. */\nexport type PgliteVacuumFullMode = \"off\" | \"quiet\" | \"forced\";\n\nconst VACUUM_FULL_MODES: readonly PgliteVacuumFullMode[] = [\n \"off\",\n \"quiet\",\n \"forced\",\n];\n\n/** The VACUUM FULL settings an environment selects; see {@link resolvePgliteMaintenance}. */\nexport type PgliteMaintenanceSettings = Pick<\n DurableNodeFsOptions,\n \"vacuumFullAboveBytes\" | \"vacuumFullQuietMs\" | \"vacuumFullMaxDeferMs\"\n>;\n\n/**\n * Reads the VACUUM FULL knobs. `PH_PGLITE_VACUUM_FULL` is `off` (the\n * default: never), `quiet` (only after the quiet window, however long that\n * takes) or `forced` (a deadline of 30 min from open, after which it runs\n * under load). Off is the default because a full rewrite of a large store\n * needs about twice its size in free disk and holds the only connection for\n * minutes, and on a store that is live data rather than bloat it reclaims\n * nothing; a quiet window of a minute arrives naturally between jobs, so\n * `quiet` is an opt-in for stores known to be small or bloated.\n * `PH_PGLITE_VACUUM_FULL_ABOVE_MB` sets the size that makes a store\n * eligible; `PH_PGLITE_VACUUM_FULL_QUIET_MS` and\n * `PH_PGLITE_VACUUM_FULL_MAX_DEFER_MS` override the mode's timings. A value\n * that is not a non-negative number is left to the default; an unknown mode\n * throws, since silently running a rewrite is what this guards against.\n */\nexport function resolvePgliteMaintenance(\n env: Record<string, string | undefined>,\n): PgliteMaintenanceSettings {\n const rawMode = env.PH_PGLITE_VACUUM_FULL?.trim().toLowerCase() || \"off\";\n if (!isVacuumFullMode(rawMode)) {\n throw new Error(\n `Invalid PH_PGLITE_VACUUM_FULL: ${String(env.PH_PGLITE_VACUUM_FULL)}. Expected \"off\", \"quiet\" or \"forced\".`,\n );\n }\n const mode: PgliteVacuumFullMode = rawMode;\n const settings: PgliteMaintenanceSettings = {};\n if (mode === \"off\") settings.vacuumFullAboveBytes = 0;\n if (mode === \"forced\") {\n settings.vacuumFullMaxDeferMs = FORCED_VACUUM_FULL_MAX_DEFER_MS;\n }\n const aboveMb = nonNegative(env.PH_PGLITE_VACUUM_FULL_ABOVE_MB);\n if (aboveMb !== undefined && mode !== \"off\") {\n settings.vacuumFullAboveBytes = aboveMb * 1024 * 1024;\n }\n const quiet = nonNegative(env.PH_PGLITE_VACUUM_FULL_QUIET_MS);\n if (quiet !== undefined) settings.vacuumFullQuietMs = quiet;\n const maxDefer = nonNegative(env.PH_PGLITE_VACUUM_FULL_MAX_DEFER_MS);\n if (maxDefer !== undefined) settings.vacuumFullMaxDeferMs = maxDefer;\n return settings;\n}\n\nfunction isVacuumFullMode(value: string): value is PgliteVacuumFullMode {\n return (VACUUM_FULL_MODES as readonly string[]).includes(value);\n}\n\nfunction nonNegative(value: string | undefined): number | undefined {\n if (value === undefined || value.trim() === \"\") return undefined;\n const parsed = Number(value);\n return Number.isFinite(parsed) && parsed >= 0 ? parsed : undefined;\n}\n\ninterface NodeFsStream {\n nfd?: number;\n /** Emscripten open flags; NODEFS opens the host fd with the same access mode. */\n flags?: number;\n}\n\n// Only PGlite's pg_flush_data (fsync on pre_sync_fname's O_RDONLY fd) syncs a\n// read-only fd: the result is discarded and an O_RDWR fsync of the same file\n// follows. Skipped, as Windows refuses FlushFileBuffers without write access.\nfunction isReadOnly(stream: NodeFsStream): boolean {\n return stream.flags !== undefined && (stream.flags & 3) === 0;\n}\n\ninterface EmscriptenFs {\n filesystems: { NODEFS: { stream_ops: Record<string, unknown> } };\n getStreamChecked(fd: number): NodeFsStream;\n quit(): void;\n}\n\ninterface EmscriptenMod {\n FS: EmscriptenFs;\n [wasmExport: string]: unknown;\n}\n\n// PGlite re-enters wasm from its own error handler after a query fails; on an\n// aborted runtime that spins forever, so every entry point is cut off first.\nconst WASM_ENTRY_POINTS = [\n \"_interactive_one\",\n \"_interactive_write\",\n \"_pgl_backend\",\n \"_pgl_initdb\",\n \"_pgl_shutdown\",\n];\n\nfunction poisonAfterAbort(mod: EmscriptenMod | undefined, what: unknown): void {\n if (!mod) return;\n const message = `PGlite aborted: ${String(what) || \"wasm runtime abort\"}`;\n for (const name of WASM_ENTRY_POINTS) {\n if (typeof mod[name] !== \"function\") continue;\n mod[name] = () => {\n throw new Error(message);\n };\n }\n // pg.close() rejects before closeFs(), so release the host fds here.\n try {\n mod.FS.quit();\n } catch {\n // already quit by an earlier abort\n }\n}\n\ntype SyscallImport = ((fd: number) => number) & { sig?: string };\n\ninterface WasmImports {\n env: Record<string, unknown> & { __syscall_fdatasync?: SyscallImport };\n}\n\ntype InstantiateWasm = (\n imports: WasmImports,\n done: (instance: WebAssembly.Instance, module: WebAssembly.Module) => void,\n) => unknown;\n\ninterface EmscriptenOpts {\n preRun?: ((mod: EmscriptenMod) => void)[];\n instantiateWasm?: InstantiateWasm;\n onAbort?: (what: unknown) => void;\n}\n\ntype InitOpts = Parameters<InstanceType<NodeFsClass>[\"init\"]>[1];\n\n/** Built over the passed-in class so PG16 dirs on `pglite-legacy-02` get the same behaviour. */\nexport function createDurableNodeFs(\n Base: NodeFsClass,\n dataDir: string,\n options: DurableNodeFsOptions = {},\n): DurableNodeFs {\n const fsync = options.fsync ?? true;\n const hostFs = options.hostFs ?? nodeFs;\n const logger = options.logger;\n const onAbort = options.onAbort;\n const resolvedDir = path.resolve(dataDir);\n const maintenance = new PgliteMaintenance({\n intervalMs: options.maintenanceIntervalMs,\n vacuumFullAboveBytes: options.vacuumFullAboveBytes,\n vacuumFullQuietMs: options.vacuumFullQuietMs,\n vacuumFullMaxDeferMs: options.vacuumFullMaxDeferMs,\n gate: options.maintenanceGate,\n now: options.now,\n rewriteQuietMs: options.rewriteQuietMs,\n rewriteMaxWaitMs: options.rewriteMaxWaitMs,\n logger,\n });\n\n class Durable extends Base {\n readonly maintenance = maintenance;\n private mod?: EmscriptenMod;\n // Off from initialSyncFs of a fresh dir until PGlite's first syncToFs.\n private hostSyncs = fsync;\n private freshInit = false;\n\n override async init(\n pg: PGlite,\n opts: InitOpts,\n ): Promise<{ emscriptenOpts: InitOpts }> {\n const { emscriptenOpts: base } = await super.init(pg, opts);\n const baseOpts = base as EmscriptenOpts;\n const inner = baseOpts.instantiateWasm;\n if (fsync && !inner) {\n throw new Error(\"PGlite did not supply instantiateWasm\");\n }\n const emscriptenOpts: EmscriptenOpts = {\n ...baseOpts,\n onAbort: (what) => {\n poisonAfterAbort(this.mod, what);\n void maintenance.stop();\n onAbort?.(what);\n },\n preRun: [\n ...(baseOpts.preRun ?? []),\n (mod) => {\n this.mod = mod;\n if (!fsync) return;\n mod.FS.filesystems.NODEFS.stream_ops.fsync = (\n stream: NodeFsStream,\n ) => this.fsyncStream(stream);\n },\n ],\n instantiateWasm:\n fsync && inner\n ? (imports, done) => {\n const original = imports.env.__syscall_fdatasync;\n const replacement: SyscallImport = (fd) => this.fdatasync(fd);\n replacement.sig = original?.sig;\n imports.env.__syscall_fdatasync = replacement;\n return inner(imports, done);\n }\n : inner,\n };\n return { emscriptenOpts: emscriptenOpts as InitOpts };\n }\n\n override async initialSyncFs(): Promise<void> {\n await super.initialSyncFs();\n // No PG_VERSION: initdb runs next; PGlite calls syncToFs once before ready.\n this.freshInit =\n fsync && !nodeFs.existsSync(path.join(resolvedDir, \"PG_VERSION\"));\n if (this.freshInit) this.hostSyncs = false;\n const baseBytes = await dirBytes(path.join(resolvedDir, \"base\"));\n maintenance.start(this.pg!, resolvedDir, baseBytes);\n }\n\n override async syncToFs(relaxedDurability?: boolean): Promise<void> {\n maintenance.noteSync();\n await super.syncToFs(relaxedDurability);\n if (!this.freshInit) return;\n this.freshInit = false;\n this.hostSyncs = true;\n syncTree(resolvedDir, hostFs);\n }\n\n override async closeFs(): Promise<void> {\n try {\n await maintenance.stop();\n } finally {\n await super.closeFs();\n }\n }\n\n // WASI fd_sync convention: 0 or a positive errno.\n private fsyncStream(stream: NodeFsStream): number {\n if (!this.hostSyncs) return 0;\n // Directory streams carry no host fd; only regular files do.\n if (typeof stream.nfd !== \"number\" || isReadOnly(stream)) return 0;\n try {\n hostFs.fsyncSync(stream.nfd);\n } catch (err) {\n logger?.warn(`DurableNodeFs fsync failed: ${String(err)}`);\n return EIO;\n }\n return 0;\n }\n\n // Linux syscall convention: 0 or a negative errno.\n private fdatasync(fd: number): number {\n if (!this.hostSyncs) return 0;\n let stream: NodeFsStream;\n try {\n stream = this.mod!.FS.getStreamChecked(fd);\n } catch {\n return -ERRNO_CODES.EBADF;\n }\n if (typeof stream.nfd !== \"number\" || isReadOnly(stream)) return 0;\n try {\n hostFs.fdatasyncSync(stream.nfd);\n } catch (err) {\n logger?.warn(`DurableNodeFs fdatasync failed: ${String(err)}`);\n return -EIO;\n }\n return 0;\n }\n }\n\n return new Durable(dataDir) as DurableNodeFs;\n}\n","import type { PGliteErrorInfo } from \"./protocol.js\";\n\nconst MAX_STACK_LENGTH = 8 * 1024;\nconst MAX_CAUSE_DEPTH = 8;\n\n/** The string fields of PGlite's `DatabaseError`, plus the query PGlite attaches. */\nexport const PG_ERROR_FIELDS = [\n \"code\",\n \"severity\",\n \"detail\",\n \"hint\",\n \"position\",\n \"internalPosition\",\n \"internalQuery\",\n \"where\",\n \"schema\",\n \"table\",\n \"column\",\n \"dataType\",\n \"constraint\",\n \"file\",\n \"line\",\n \"routine\",\n \"query\",\n] as const;\n\n/** Flattens an error and its cause chain into a structured-clonable shape. */\nexport function toPGliteErrorInfo(err: unknown, depth = 0): PGliteErrorInfo {\n if (depth > MAX_CAUSE_DEPTH) {\n return { name: \"Error\", message: \"cause chain truncated\", fields: {} };\n }\n if (!(err instanceof Error)) {\n return { name: \"Error\", message: describe(err), fields: {} };\n }\n const info: PGliteErrorInfo = {\n name: err.name || \"Error\",\n message: err.message,\n fields: pgFieldsOf(err),\n };\n if (typeof err.stack === \"string\") {\n info.stack = err.stack.slice(0, MAX_STACK_LENGTH);\n }\n if (err.cause !== undefined) {\n info.cause = toPGliteErrorInfo(err.cause, depth + 1);\n }\n return info;\n}\n\n/** Rebuilds an `Error` carrying the original name, stack, Postgres fields and cause chain. */\nexport function fromPGliteErrorInfo(info: PGliteErrorInfo): Error {\n const err = new Error(info.message);\n define(err, \"name\", info.name);\n if (info.stack !== undefined) {\n err.stack = info.stack;\n }\n for (const [key, value] of Object.entries(info.fields)) {\n define(err, key, value);\n }\n if (info.cause !== undefined) {\n define(err, \"cause\", fromPGliteErrorInfo(info.cause));\n }\n return err;\n}\n\nfunction pgFieldsOf(err: Error): Record<string, string> {\n const fields: Record<string, string> = {};\n const record = err as unknown as Record<string, unknown>;\n for (const key of PG_ERROR_FIELDS) {\n const value = record[key];\n if (typeof value === \"string\") {\n fields[key] = value;\n }\n }\n return fields;\n}\n\nfunction define(err: Error, key: string, value: unknown): void {\n Object.defineProperty(err, key, {\n value,\n configurable: true,\n writable: true,\n enumerable: key !== \"name\" && key !== \"cause\",\n });\n}\n\nfunction describe(value: unknown): string {\n if (typeof value === \"string\") {\n return value;\n }\n if (value && typeof value === \"object\") {\n const message = (value as { message?: unknown }).message;\n if (typeof message === \"string\") {\n return message;\n }\n }\n if (value === undefined || typeof value === \"function\") {\n return String(value);\n }\n try {\n return JSON.stringify(value);\n } catch {\n return \"[unserializable]\";\n }\n}\n"],"names":["fs"],"mappings":";;;;;;;AAEA,MAAa,qBAAqB,EAEhC,OAAO,0BAAkB,IAAI,KAAK,GAAG,MAAM,QAAQ,KAAK,GAAG,EAAE,EAAE,EACjE;;;ACIA,MAAa,kCAAkC;AAC/C,MAAa,kCAAkC;AAC/C,MAAa,+BAA+B;;;;;;;;AAQ5C,MAAa,mCAAmC;;AAEhD,MAAa,k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AO,QAAQ,CAAC;CAErD,OAAO;AACT;;AAGA,SAAgB,oBAAoB,MAA8B;CAChE,MAAM,MAAM,IAAI,MAAM,KAAK,OAAO;CAClC,OAAO,KAAK,QAAQ,KAAK,IAAI;CAC7B,IAAI,KAAK,UAAU,KAAA,GACjB,IAAI,QAAQ,KAAK;CAEnB,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,KAAK,MAAM,GACnD,OAAO,KAAK,KAAK,KAAK;CAExB,IAAI,KAAK,UAAU,KAAA,GACjB,OAAO,KAAK,SAAS,oBAAoB,KAAK,KAAK,CAAC;CAEtD,OAAO;AACT;AAEA,SAAS,WAAW,KAAoC;CACtD,MAAM,SAAiC,CAAC;CACxC,MAAM,SAAS;CACf,KAAK,MAAM,OAAO,iBAAiB;EACjC,MAAM,QAAQ,OAAO;EACrB,IAAI,OAAO,UAAU,UACnB,OAAO,OAAO;CAElB;CACA,OAAO;AACT;AAEA,SAAS,OAAO,KAAY,KAAa,OAAsB;CAC7D,OAAO,eAAe,KAAK,KAAK;EAC9B;EACA,cAAc;EACd,UAAU;EACV,YAAY,QAAQ,UAAU,QAAQ;CACxC,CAAC;AACH;AAEA,SAAS,SAAS,OAAwB;CACxC,IAAI,OAAO,UAAU,UACnB,OAAO;CAET,IAAI,SAAS,OAAO,UAAU,UAAU;EACtC,MAAM,UAAW,MAAgC;EACjD,IAAI,OAAO,YAAY,UACrB,OAAO;CAEX;CACA,IAAI,UAAU,KAAA,KAAa,OAAO,UAAU,YAC1C,OAAO,OAAO,KAAK;CAErB,IAAI;EACF,OAAO,KAAK,UAAU,KAAK;CAC7B,QAAQ;EACN,OAAO;CACT;AACF","debug_id":"32154524-8414-5e0c-bd0b-eb61f765c647"}
package/dist/index.d.mts CHANGED
@@ -6,7 +6,7 @@ import { ILogger } from "document-model";
6
6
  import { IAnalyticsStore } from "@powerhousedao/analytics-engine-core";
7
7
  import { AnalyticsModel } from "@powerhousedao/analytics-engine-graphql";
8
8
  import { DocumentNode, GraphQLError, GraphQLResolveInfo, GraphQLScalarType, GraphQLScalarTypeConfig, GraphQLSchema } from "graphql";
9
- import { AttachmentRef, CatchUpLoadSample, DocumentModelSource as DocumentModelSource$1, ICatchUpLoadSource, IDocumentModelLoader, IDocumentModelRegistry, IDriveClient, IDriveNodeSource, IInspectableAttachmentStore, IInspector, IInspectorAdmin, IInspectorStorageHealthProvider, INSPECTOR_OPS, IReactorClient, IReactorFactsSink, IReactorProcessorHostModuleBase, IReactorReadClient, IReactorWriteClient, IRelationalDb, ISyncInspector, ISyncManager, InProcessReactorClientModule, InProcessReactorModule, InspectorDocumentReader, InspectorReadOpKey, PagedResults, ParsedDriveUrl, ProcessorFactoryBuilder as ProcessorFactoryBuilder$1, Remote, SYNC_INSPECTION_OPS, SearchFilter, SyncInspectionReadOpKey, SyncScopeGate, ViewFilter, driveIdFromUrl, parseDriveUrl } from "@powerhousedao/reactor";
9
+ import { AttachmentRef, CatchUpLoadSample, DocumentModelSource as DocumentModelSource$1, ICatchUpLoadSource, IDocumentModelLoader, IDocumentModelRegistry, IDriveClient, IDriveNodeSource, IInspectableAttachmentStore, IInspector, IInspectorAdmin, IInspectorStorageHealthProvider, IMemorySampler, IMemoryTelemetrySink, INSPECTOR_OPS, IReactorClient, IReactorFactsSink, IReactorProcessorHostModuleBase, IReactorReadClient, IReactorWriteClient, IRelationalDb, ISyncInspector, ISyncManager, InProcessReactorClientModule, InProcessReactorModule, InspectorDocumentReader, InspectorReadOpKey, MemoryTelemetryConfig, PagedResults, ParsedDriveUrl, ProcessMemorySample, ProcessorFactoryBuilder as ProcessorFactoryBuilder$1, Remote, SYNC_INSPECTION_OPS, SearchFilter, SyncInspectionReadOpKey, SyncScopeGate, ViewFilter, driveIdFromUrl, parseDriveUrl } from "@powerhousedao/reactor";
10
10
  import { AuthSubject, DocumentModelModule, Operation, PHDocument, UpgradeManifest } from "@powerhousedao/shared/document-model";
11
11
  import { AuthorizerResult, IHttpScope, IRelationalDb as IRelationalDb$1, IWebhookEndpoints, IWebhookScope, NodeRouteSpec, ProcessorApp, ProcessorFactory, RouteActor, RouteAuth, RouteAuthorizer, RouteBody, RouteContext, RouteHandler, RouteMethod, RouteOptions, RouteSpec, RouteTransport, RouteUser, RouteUser as RouteUser$1, ScopedRouteHandle, WebhookEndpointInfo, WebhookField, WebhookHashAlgorithm, WebhookPolicy, WebhookReply, WebhookRequest, WebhookScheme, WebhookSignatureEncoding, WebhookSpec, WebhookVerification } from "@powerhousedao/shared/processors";
12
12
  import { Generated, Kysely, RawBuilder } from "kysely";
@@ -18,12 +18,12 @@ import { WebSocketServer } from "ws";
18
18
  import { AttachmentReadGate, IDocumentScopeGate } from "@powerhousedao/reactor-attachments/replication";
19
19
  import { PGlite } from "@electric-sql/pglite";
20
20
  import { Knex } from "knex";
21
+ import { PHReactorRenown } from "@powerhousedao/shared/clis";
21
22
  import http from "node:http";
22
23
  import { CorsOptions } from "cors";
23
24
  import { Context as Context$1, GqlDocument as GqlDocument$1, GqlDriveDocument as GqlDriveDocument$1, GqlOperation as GqlOperation$1, GraphQLManager as GraphQLManager$1, ISubgraph as ISubgraph$1, Processor as Processor$1, SubgraphArgs as SubgraphArgs$1, SubgraphClass as SubgraphClass$1 } from "@powerhousedao/reactor-api";
24
25
  import { IncomingHttpHeaders } from "http";
25
26
  import { Pool } from "pg";
26
- import { PHReactorRenown } from "@powerhousedao/shared/clis";
27
27
  //#region src/graphql/gateway/types.d.ts
28
28
  export type TlsOptions = {
29
29
  keyPath: string;
@@ -5764,6 +5764,81 @@ export declare class PrivacyPermissionAdapter {
5764
5764
  erasePermissions(documentId: string): Promise<Record<string, number>>;
5765
5765
  }
5766
5766
  //#endregion
5767
- export { type AttachmentReadGate, type AuthorizationConfig, type AuthorizerResult, type CanonicalDocumentId, DocumentModelSchema, DocumentModelSchemaCache, type DocumentModelSchemaOptions, DocumentModelSource, GeneratedDocumentModelTypes, type HttpRouteServiceOptions, type IAuthorizationService, type IDocumentScopeGate, type IEventLoopDelaySource, type IHttpScope, type IPackageLoader, type IPackageLoaderOptions, type IPackagePieceSource, type IReactorInspectionSource, type IWebhookEndpoints, type IWebhookScope, type IWebhookStore, type InspectionCallerGate, type InspectionReadField, type InspectionThrottleConfig, type NodeRouteSpec, PGLITE_UTC_PARSERS, type PackagePiece, type PackagePieceEntry, type PackagesSubgraphArgs, type ParsedDriveUrl, type PublicOrigin, type ReactorInspectionOptions, type RegisteredScalar, ReportError, type RequestClients, type RequestLoadRecorderOptions, ReservedTypeNames, ResolvedDocumentModelSchema, type RouteActor, type RouteAuth, type RouteAuthorizer, type RouteBody, type RouteContext, type RouteHandler, type RouteMethod, type RouteOptions, type RouteSpec, type RouteTransport, type RouteUser, RunDetachedOptions, type ScalarExport, type ScalarRegistry, type ScopedRouteHandle, SubgraphSchemaOptions, SubgraphTypeCollisionError, type WebhookEndpointInfo, type WebhookEndpointRow, type WebhookField, type WebhookHashAlgorithm, type WebhookPolicy, type WebhookReply, type WebhookRequest, type WebhookScheme, type WebhookSignatureEncoding, type WebhookSpec, type WebhookVerification, assembleSubgraphTypeDefs, buildDocumentModelSchema, buildSubgraphSchemaModule, createMergedSchema, createSchema, documentModelSubgraphTypes, driveIdFromUrl, findSubgraphTypeCollisions, generateDocumentModelSchema, generatedTypesOf, getDocumentModelSchemaName, getDocumentModelSubgraphName, getDocumentModelTypeDefs, getGeneratedDocumentModelTypes, hasOperationSchemas, parseDriveUrl, reportFailure, reservedTypeNames, reservedTypeNamesTaken, runDetached, typeDefinitionNames };
5767
+ //#region src/telemetry/heap-snapshot.d.ts
5768
+ type HeapSnapshotOptions = {
5769
+ dir: string;
5770
+ now?: () => number;
5771
+ freeMemory?: () => number;
5772
+ heapUsed?: () => number;
5773
+ write?: (file: string) => string;
5774
+ };
5775
+ /**
5776
+ * A guarded writer of main-thread heap snapshots: one at a time, at most one
5777
+ * every two minutes, and refused without room for it unless forced. A snapshot
5778
+ * can hold document state, so it stays on the host. It blocks the event loop
5779
+ * for seconds to minutes; take it at 2-4 GB, not at 10 GB.
5780
+ */
5781
+ export declare function createHeapSnapshotWriter(options: HeapSnapshotOptions): (force: boolean) => Promise<string>;
5782
+ //#endregion
5783
+ //#region src/telemetry/jsonl-sink.d.ts
5784
+ /** An ISO time usable in a Windows file name. */
5785
+ export declare function fileTimestamp(date: Date): string;
5786
+ /** Where telemetry files land: `<phDir>/telemetry`, following `PH_USER_DATA_DIR`. */
5787
+ export declare function telemetryDir(env?: NodeJS.ProcessEnv): string;
5788
+ type JsonlFileOptions = {
5789
+ path: string;
5790
+ maxBytes: number;
5791
+ /** Files kept, the current one included. */
5792
+ keep: number;
5793
+ /** Written as the first line of every file. */
5794
+ header: unknown;
5795
+ logger?: ILogger;
5796
+ };
5797
+ /**
5798
+ * Appends one JSON line at a time and rotates at `maxBytes`: the full file moves
5799
+ * to `<stem>.<n>.jsonl`, and the oldest beyond `keep` is deleted. Each append is
5800
+ * synchronous and small, so a hard kill loses nothing written so far.
5801
+ */
5802
+ export declare class JsonlFile {
5803
+ private readonly options;
5804
+ readonly path: string;
5805
+ private size;
5806
+ private rotation;
5807
+ private failed;
5808
+ private readonly stem;
5809
+ private readonly dir;
5810
+ constructor(options: JsonlFileOptions);
5811
+ writeLine(value: unknown): void;
5812
+ private append;
5813
+ private rotate;
5814
+ private prune;
5815
+ }
5816
+ type MemoryFileSinkOptions = {
5817
+ /** Where a file with no explicit path goes; defaults to `telemetryDir()`. */
5818
+ dir?: string;
5819
+ now?: () => Date;
5820
+ env?: NodeJS.ProcessEnv;
5821
+ logger?: ILogger;
5822
+ };
5823
+ /** Opens the memory telemetry's JSONL file; the header holds no env values. */
5824
+ export declare function memoryFileSink(config: MemoryTelemetryConfig, options?: MemoryFileSinkOptions): IMemoryTelemetrySink;
5825
+ //#endregion
5826
+ //#region src/telemetry/node-memory-sampler.d.ts
5827
+ /**
5828
+ * Reads the process's memory. `heapUsed` alone saw-tooths, so a GC observer
5829
+ * keeps the used heap right after each major collection, which needs no
5830
+ * `--expose-gc`.
5831
+ */
5832
+ export declare class NodeMemorySampler implements IMemorySampler {
5833
+ private observer;
5834
+ private loop;
5835
+ private postGcHeap;
5836
+ private postGcAt;
5837
+ start(): void;
5838
+ stop(): void;
5839
+ sample(): ProcessMemorySample;
5840
+ }
5841
+ //#endregion
5842
+ export { type AttachmentReadGate, type AuthorizationConfig, type AuthorizerResult, type CanonicalDocumentId, DocumentModelSchema, DocumentModelSchemaCache, type DocumentModelSchemaOptions, DocumentModelSource, GeneratedDocumentModelTypes, type HeapSnapshotOptions, type HttpRouteServiceOptions, type IAuthorizationService, type IDocumentScopeGate, type IEventLoopDelaySource, type IHttpScope, type IPackageLoader, type IPackageLoaderOptions, type IPackagePieceSource, type IReactorInspectionSource, type IWebhookEndpoints, type IWebhookScope, type IWebhookStore, type InspectionCallerGate, type InspectionReadField, type InspectionThrottleConfig, type JsonlFileOptions, type MemoryFileSinkOptions, type NodeRouteSpec, PGLITE_UTC_PARSERS, type PackagePiece, type PackagePieceEntry, type PackagesSubgraphArgs, type ParsedDriveUrl, type PublicOrigin, type ReactorInspectionOptions, type RegisteredScalar, ReportError, type RequestClients, type RequestLoadRecorderOptions, ReservedTypeNames, ResolvedDocumentModelSchema, type RouteActor, type RouteAuth, type RouteAuthorizer, type RouteBody, type RouteContext, type RouteHandler, type RouteMethod, type RouteOptions, type RouteSpec, type RouteTransport, type RouteUser, RunDetachedOptions, type ScalarExport, type ScalarRegistry, type ScopedRouteHandle, SubgraphSchemaOptions, SubgraphTypeCollisionError, type WebhookEndpointInfo, type WebhookEndpointRow, type WebhookField, type WebhookHashAlgorithm, type WebhookPolicy, type WebhookReply, type WebhookRequest, type WebhookScheme, type WebhookSignatureEncoding, type WebhookSpec, type WebhookVerification, assembleSubgraphTypeDefs, buildDocumentModelSchema, buildSubgraphSchemaModule, createMergedSchema, createSchema, documentModelSubgraphTypes, driveIdFromUrl, findSubgraphTypeCollisions, generateDocumentModelSchema, generatedTypesOf, getDocumentModelSchemaName, getDocumentModelSubgraphName, getDocumentModelTypeDefs, getGeneratedDocumentModelTypes, hasOperationSchemas, parseDriveUrl, reportFailure, reservedTypeNames, reservedTypeNamesTaken, runDetached, typeDefinitionNames };
5768
5843
  export {};
5769
5844
  //# sourceMappingURL=index.d.mts.map