@pgxsinkit/client 0.1.53 → 0.2.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/README.md +22 -0
- package/dist/adoption.d.ts +118 -0
- package/dist/adoption.d.ts.map +1 -0
- package/dist/boot-report.d.ts +54 -15
- package/dist/boot-report.d.ts.map +1 -1
- package/dist/convergence.d.ts +2 -1
- package/dist/convergence.d.ts.map +1 -1
- package/dist/export-store.d.ts +1 -1
- package/dist/export-store.d.ts.map +1 -1
- package/dist/index.d.ts +270 -52
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +4492 -1511
- package/dist/index.js.map +34 -24
- package/dist/live-rows-sql.d.ts +1 -1
- package/dist/local-store.d.ts +16 -31
- package/dist/local-store.d.ts.map +1 -1
- package/dist/local-tables.d.ts +4 -4
- package/dist/mutation.d.ts +12 -15
- package/dist/mutation.d.ts.map +1 -1
- package/dist/opfs-effects.d.ts +51 -0
- package/dist/opfs-effects.d.ts.map +1 -0
- package/dist/placement-probe.d.ts +75 -0
- package/dist/placement-probe.d.ts.map +1 -0
- package/dist/schema.d.ts +11 -16
- package/dist/schema.d.ts.map +1 -1
- package/dist/store-boot.d.ts +77 -0
- package/dist/store-boot.d.ts.map +1 -0
- package/dist/store-lifecycle.d.ts +153 -0
- package/dist/store-lifecycle.d.ts.map +1 -0
- package/dist/store-meta.d.ts +190 -0
- package/dist/store-meta.d.ts.map +1 -0
- package/dist/store-path.d.ts +77 -7
- package/dist/store-path.d.ts.map +1 -1
- package/dist/sync/apply.d.ts.map +1 -1
- package/dist/sync/shape-inbox.d.ts +1 -1
- package/dist/sync/types.d.ts +3 -3
- package/dist/testing.js.map +3 -3
- package/dist/worker/attach-sync-client.d.ts +235 -12
- package/dist/worker/attach-sync-client.d.ts.map +1 -1
- package/dist/worker/define-sync-worker.d.ts +138 -22
- package/dist/worker/define-sync-worker.d.ts.map +1 -1
- package/dist/worker/election-coordinator.d.ts +95 -0
- package/dist/worker/election-coordinator.d.ts.map +1 -0
- package/dist/worker/engine-control.d.ts +265 -0
- package/dist/worker/engine-control.d.ts.map +1 -0
- package/dist/worker/engine-router.d.ts +75 -0
- package/dist/worker/engine-router.d.ts.map +1 -0
- package/dist/worker/live-query-manager.d.ts.map +1 -1
- package/dist/worker/protocol.d.ts +15 -10
- package/dist/worker/protocol.d.ts.map +1 -1
- package/dist/worker/sw-placement.d.ts +37 -0
- package/dist/worker/sw-placement.d.ts.map +1 -0
- package/package.json +4 -3
- package/skills/core/SKILL.md +15 -12
- package/skills/operating/SKILL.md +103 -46
- package/src/adoption.ts +275 -0
- package/src/boot-report.ts +70 -17
- package/src/convergence.ts +2 -1
- package/src/export-store.ts +1 -1
- package/src/index.ts +1109 -115
- package/src/live-rows-sql.ts +1 -1
- package/src/local-store.ts +18 -40
- package/src/local-tables.ts +2 -2
- package/src/mutation.ts +67 -49
- package/src/mutations-api.ts +3 -3
- package/src/opfs-effects.ts +160 -0
- package/src/placement-probe.ts +168 -0
- package/src/schema.ts +17 -22
- package/src/store-boot.ts +343 -0
- package/src/store-lifecycle.ts +227 -0
- package/src/store-meta.ts +459 -0
- package/src/store-path.ts +197 -22
- package/src/sync/apply.ts +63 -63
- package/src/sync/index.ts +2 -2
- package/src/sync/shape-inbox.ts +1 -1
- package/src/sync/types.ts +3 -3
- package/src/testing.ts +2 -2
- package/src/worker/attach-sync-client.ts +1556 -97
- package/src/worker/define-sync-worker.ts +723 -73
- package/src/worker/election-coordinator.ts +462 -0
- package/src/worker/engine-control.ts +379 -0
- package/src/worker/engine-router.ts +355 -0
- package/src/worker/live-query-manager.ts +4 -1
- package/src/worker/protocol.ts +13 -10
- package/src/worker/sw-placement.ts +64 -0
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
// The REAL OPFS effects for the store-boot wiring (ADR-0049 capability-driven engine placement, plan
|
|
2
|
+
// step 10a). `store-lifecycle.ts` owns the PURE, effect-injected destruction/adoption/fresh-candidate
|
|
3
|
+
// machines; `store-boot.ts` assembles observations and executes their verdicts. This module is the concrete
|
|
4
|
+
// OPFS side those verdicts drive: create/delete the commitment sentinel, delete the store directory, observe
|
|
5
|
+
// the commitment namespace without creating anything, and hand the store directory handle to the
|
|
6
|
+
// opfs-repacked factory.
|
|
7
|
+
//
|
|
8
|
+
// It carries NO DOM lib dependency — the OPFS surface is typed STRUCTURALLY off `globalThis`, exactly as
|
|
9
|
+
// `store-path.ts` and `placement-probe.ts` do. Every path is built ONLY from `store-path.ts`'s namespace
|
|
10
|
+
// builders ({@link opfsCommitmentSentinelPath}, {@link opfsStoreDirectoryPath}) — this module never
|
|
11
|
+
// re-derives an OPFS name. Every effect is IDEMPOTENT per the store-lifecycle contracts it satisfies:
|
|
12
|
+
// create-if-absent (publishSentinel, getStoreDirectoryHandle) and delete-if-present with `NotFoundError`
|
|
13
|
+
// swallowed (deleteSentinel, deleteStoreDirectory). `observeCommitmentNamespace` never creates and never
|
|
14
|
+
// throws — a root/API failure reads as `"unobservable"` (present absence is not historical proof).
|
|
15
|
+
|
|
16
|
+
import { opfsCommitmentSentinelPath, opfsStoreDirectoryPath } from "./store-path";
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* The minimal structural shape of an OPFS `FileSystemDirectoryHandle` this module traverses: the
|
|
20
|
+
* create-or-not `getDirectoryHandle`/`getFileHandle` hops and the recursive `removeEntry`. Declared locally
|
|
21
|
+
* so the module carries no DOM lib dependency (the pattern the rest of the toolkit uses for OPFS handles).
|
|
22
|
+
*/
|
|
23
|
+
export interface DirLike {
|
|
24
|
+
getDirectoryHandle(name: string, options?: { create?: boolean }): Promise<DirLike>;
|
|
25
|
+
getFileHandle(name: string, options?: { create?: boolean }): Promise<unknown>;
|
|
26
|
+
removeEntry(name: string, options?: { recursive?: boolean }): Promise<void>;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** The injectable seam so Bun unit tests fake the OPFS root (there is no real OPFS there). */
|
|
30
|
+
export interface OpfsEffectsDeps {
|
|
31
|
+
/**
|
|
32
|
+
* The OPFS root getter. Omit in production: the default reads `navigator.storage.getDirectory` off
|
|
33
|
+
* `globalThis` (structural, no DOM lib). Absent API → the delete effects are no-ops, `observe` is
|
|
34
|
+
* `"unobservable"`, and the create effects throw (they are only reached in the opfs engine home).
|
|
35
|
+
*/
|
|
36
|
+
getRoot?: () => Promise<DirLike>;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** The effects surface the store-boot wiring drives (create-if-absent / delete-if-present / never-creating observe). */
|
|
40
|
+
export interface OpfsEffects {
|
|
41
|
+
/** Create-if-absent the commitment sentinel file at `pgxsinkit/commitments/<identity>`. */
|
|
42
|
+
publishSentinel(): Promise<void>;
|
|
43
|
+
/** Delete-if-present the commitment sentinel (`NotFoundError` swallowed). */
|
|
44
|
+
deleteSentinel(): Promise<void>;
|
|
45
|
+
/** Recursively delete-if-present the store directory `pgxsinkit/stores/<identity>` (`NotFoundError` swallowed). */
|
|
46
|
+
deleteStoreDirectory(): Promise<void>;
|
|
47
|
+
/**
|
|
48
|
+
* Never-creating walk of the commitment namespace. A root/API failure (or the API being absent) reads as
|
|
49
|
+
* `"unobservable"` — this method NEVER throws.
|
|
50
|
+
*/
|
|
51
|
+
observeCommitmentNamespace(): Promise<{ sentinelPresent: boolean; storeDirectoryPresent: boolean } | "unobservable">;
|
|
52
|
+
/** Create-if-absent chain to the store directory, returning its handle for the opfs-repacked factory. */
|
|
53
|
+
getStoreDirectoryHandle(): Promise<unknown>;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** Is this a `NotFoundError` (a missing OPFS entry) — the delete/observe "absent" signal? */
|
|
57
|
+
function isNotFoundError(error: unknown): boolean {
|
|
58
|
+
return (error as { name?: string } | null)?.name === "NotFoundError";
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** Resolve the default OPFS root getter off `globalThis`, or `null` when the API is absent. */
|
|
62
|
+
function resolveDefaultGetRoot(): (() => Promise<DirLike>) | null {
|
|
63
|
+
const storage = (globalThis as { navigator?: { storage?: { getDirectory?: () => Promise<DirLike> } } }).navigator
|
|
64
|
+
?.storage;
|
|
65
|
+
const getDirectory = storage?.getDirectory;
|
|
66
|
+
if (getDirectory == null) return null;
|
|
67
|
+
return () => getDirectory.call(storage);
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* Construct the real OPFS effects for a store, all under `store-path.ts`'s disjoint namespaces. The returned
|
|
72
|
+
* object's methods satisfy the idempotency contracts the `store-lifecycle.ts` machines require, so a boot that
|
|
73
|
+
* resumes an interrupted destruction/candidate/adoption re-runs them safely.
|
|
74
|
+
*/
|
|
75
|
+
export function createOpfsEffects(storePath: string, deps?: OpfsEffectsDeps): OpfsEffects {
|
|
76
|
+
const getRoot = deps?.getRoot ?? resolveDefaultGetRoot();
|
|
77
|
+
|
|
78
|
+
// Walk (optionally creating) a chain of directory segments, returning the leaf handle. Throws when the OPFS
|
|
79
|
+
// API is absent — only the create paths call it in that state, and they are only reached in the opfs home.
|
|
80
|
+
async function walkDirectories(segments: readonly string[], create: boolean): Promise<DirLike> {
|
|
81
|
+
if (getRoot == null) throw new Error("[pgxsinkit] OPFS root is unavailable in this scope");
|
|
82
|
+
let handle = await getRoot();
|
|
83
|
+
for (const segment of segments) handle = await handle.getDirectoryHandle(segment, { create });
|
|
84
|
+
return handle;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
// Never-creating existence check for one namespace entry; `NotFoundError` anywhere in the chain → absent.
|
|
88
|
+
async function entryExists(path: readonly string[], kind: "file" | "dir"): Promise<boolean> {
|
|
89
|
+
try {
|
|
90
|
+
let handle = await getRoot!();
|
|
91
|
+
const lastIndex = path.length - 1;
|
|
92
|
+
for (let i = 0; i < path.length; i += 1) {
|
|
93
|
+
const segment = path[i]!;
|
|
94
|
+
if (i === lastIndex && kind === "file") {
|
|
95
|
+
await handle.getFileHandle(segment, { create: false });
|
|
96
|
+
return true;
|
|
97
|
+
}
|
|
98
|
+
handle = await handle.getDirectoryHandle(segment, { create: false });
|
|
99
|
+
}
|
|
100
|
+
return true;
|
|
101
|
+
} catch (error) {
|
|
102
|
+
if (isNotFoundError(error)) return false;
|
|
103
|
+
// A non-NotFound failure means we cannot tell — let `observeCommitmentNamespace` map it to "unobservable".
|
|
104
|
+
throw error;
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
return {
|
|
109
|
+
async publishSentinel(): Promise<void> {
|
|
110
|
+
const path = opfsCommitmentSentinelPath(storePath);
|
|
111
|
+
const parent = await walkDirectories(path.slice(0, -1), true);
|
|
112
|
+
// Create-if-absent: the sentinel is a marker file; re-publishing over an existing one is a no-op success.
|
|
113
|
+
await parent.getFileHandle(path[path.length - 1]!, { create: true });
|
|
114
|
+
},
|
|
115
|
+
|
|
116
|
+
async deleteSentinel(): Promise<void> {
|
|
117
|
+
if (getRoot == null) return;
|
|
118
|
+
const path = opfsCommitmentSentinelPath(storePath);
|
|
119
|
+
try {
|
|
120
|
+
const parent = await walkDirectories(path.slice(0, -1), false);
|
|
121
|
+
await parent.removeEntry(path[path.length - 1]!);
|
|
122
|
+
} catch (error) {
|
|
123
|
+
// Delete-if-present: a missing parent dir or a missing sentinel both count as already deleted.
|
|
124
|
+
if (!isNotFoundError(error)) throw error;
|
|
125
|
+
}
|
|
126
|
+
},
|
|
127
|
+
|
|
128
|
+
async deleteStoreDirectory(): Promise<void> {
|
|
129
|
+
if (getRoot == null) return;
|
|
130
|
+
const path = opfsStoreDirectoryPath(storePath);
|
|
131
|
+
try {
|
|
132
|
+
const parent = await walkDirectories(path.slice(0, -1), false);
|
|
133
|
+
// Recursive: the store directory holds the four VFS-owned files; the whole leaf goes.
|
|
134
|
+
await parent.removeEntry(path[path.length - 1]!, { recursive: true });
|
|
135
|
+
} catch (error) {
|
|
136
|
+
if (!isNotFoundError(error)) throw error;
|
|
137
|
+
}
|
|
138
|
+
},
|
|
139
|
+
|
|
140
|
+
async observeCommitmentNamespace(): Promise<
|
|
141
|
+
{ sentinelPresent: boolean; storeDirectoryPresent: boolean } | "unobservable"
|
|
142
|
+
> {
|
|
143
|
+
if (getRoot == null) return "unobservable";
|
|
144
|
+
try {
|
|
145
|
+
const sentinelPresent = await entryExists(opfsCommitmentSentinelPath(storePath), "file");
|
|
146
|
+
const storeDirectoryPresent = await entryExists(opfsStoreDirectoryPath(storePath), "dir");
|
|
147
|
+
return { sentinelPresent, storeDirectoryPresent };
|
|
148
|
+
} catch {
|
|
149
|
+
// Root open failed or an entry check raised something other than NotFound: we cannot observe the
|
|
150
|
+
// namespace honestly, so report "unobservable" (present absence is not proof) — never throw.
|
|
151
|
+
return "unobservable";
|
|
152
|
+
}
|
|
153
|
+
},
|
|
154
|
+
|
|
155
|
+
getStoreDirectoryHandle(): Promise<unknown> {
|
|
156
|
+
// Create-if-absent chain to `pgxsinkit/stores/<identity>`, returning the leaf handle for the factory.
|
|
157
|
+
return walkDirectories(opfsStoreDirectoryPath(storePath), true);
|
|
158
|
+
},
|
|
159
|
+
};
|
|
160
|
+
}
|
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
// The placement probe (ADR-0049 decision 1, plan step 4). The SharedWorker decides its engine home by
|
|
2
|
+
// ACTUALLY opening a sync-access handle in its own scope — the bench phase-0 mechanism
|
|
3
|
+
// (`apps/perf-lab/src/bench/sharedworker-proof.worker.ts`, probe stage) — never by sniffing for the
|
|
4
|
+
// PRESENCE of `createSyncAccessHandle` on a prototype. Presence says nothing: Chromium and Firefox
|
|
5
|
+
// expose the method in a SharedWorker yet REFUSE the open there, while WebKit grants it. Only a real open
|
|
6
|
+
// tells the truth, so the verdict here is a real open on a throwaway scratch file, removed afterwards.
|
|
7
|
+
//
|
|
8
|
+
// NEVER CACHED (invariant 8: "probe per boot"). There is deliberately no module-level memo: engines and
|
|
9
|
+
// modes change across SharedWorker lifetimes, and a stale grant would place the engine in a scope that no
|
|
10
|
+
// longer holds handles. Every call runs the full probe. This module owns no state whatsoever.
|
|
11
|
+
//
|
|
12
|
+
// The probe operates ENTIRELY under the toolkit's `pgxsinkit/probe/` namespace (from
|
|
13
|
+
// `opfsProbeDirectoryPath()` — never re-derived here). It never touches the OPFS root directly and NEVER
|
|
14
|
+
// goes inside or beside any store directory: a store directory is under whole-directory ownership by the
|
|
15
|
+
// opfs-repacked VFS (ADR-0048), which fails CLOSED on any unowned entry it finds, so a scratch file placed
|
|
16
|
+
// there would poison a real store's boot. The probe namespace is disjoint from `pgxsinkit/stores` and
|
|
17
|
+
// `pgxsinkit/commitments` (ADR-0049 D6, invariant 11), so it can never contend with a store.
|
|
18
|
+
|
|
19
|
+
import { opfsProbeDirectoryPath } from "./store-path";
|
|
20
|
+
|
|
21
|
+
/** Monotonic clock (ms) — `performance.now()` where available, else `Date.now()` (matches `boot-report.ts`). */
|
|
22
|
+
const nowMs = (): number => (typeof performance !== "undefined" ? performance.now() : Date.now());
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* The minimal structural shape of the OPFS sync-access handle the probe opens and immediately closes. The
|
|
26
|
+
* open is the whole verdict; `close()` releases it so the scratch file can be removed. Typed locally so this
|
|
27
|
+
* module carries no DOM lib dependency (the pattern `store-path.ts` uses for OPFS handles).
|
|
28
|
+
*/
|
|
29
|
+
export interface OpfsSyncAccessHandle {
|
|
30
|
+
close(): void;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* The minimal structural shape of an OPFS `FileSystemFileHandle` the probe opens a sync-access handle on.
|
|
35
|
+
* `createSyncAccessHandle` is typed as POSSIBLY ABSENT on purpose: the probe never pre-checks it — it calls
|
|
36
|
+
* it, and absence at CALL time surfaces as the thrown `TypeError` we report verbatim, which is itself an
|
|
37
|
+
* honest "no sync access here" verdict rather than a presence sniff.
|
|
38
|
+
*/
|
|
39
|
+
export interface OpfsProbeFileHandle {
|
|
40
|
+
createSyncAccessHandle?: () => Promise<OpfsSyncAccessHandle>;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* The minimal structural shape of the OPFS `FileSystemDirectoryHandle` the probe walks and creates under.
|
|
45
|
+
* All three hops use `{ create: true }`: the probe MAKES its namespace (unlike `store-path.ts`'s
|
|
46
|
+
* never-creating existence walk). Declared locally so this module carries no DOM lib dependency.
|
|
47
|
+
*/
|
|
48
|
+
export interface OpfsProbeDirectoryHandle {
|
|
49
|
+
getDirectoryHandle(name: string, options: { create: true }): Promise<OpfsProbeDirectoryHandle>;
|
|
50
|
+
getFileHandle(name: string, options: { create: true }): Promise<OpfsProbeFileHandle>;
|
|
51
|
+
removeEntry(name: string): Promise<void>;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** The outcome of one placement probe. The probe ANSWERS; it never rejects. */
|
|
55
|
+
export interface PlacementProbeResult {
|
|
56
|
+
/** True only when a REAL `createSyncAccessHandle` open succeeded in this scope. */
|
|
57
|
+
granted: boolean;
|
|
58
|
+
/** Verbatim `Name: message` of the denial/failure when not granted (diagnostics; never parsed). */
|
|
59
|
+
error?: string;
|
|
60
|
+
/** Wall-clock ms the probe took (injectable clock). */
|
|
61
|
+
ms: number;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** Injectable seams so the probe is deterministic in a Bun unit test (no real OPFS there). */
|
|
65
|
+
export interface PlacementProbeDeps {
|
|
66
|
+
/**
|
|
67
|
+
* The OPFS root getter. Omit in production: the default reads `navigator.storage.getDirectory` off
|
|
68
|
+
* `globalThis` (structural, no DOM lib). Absent API → the API-absent verdict below.
|
|
69
|
+
*/
|
|
70
|
+
getRoot?: () => Promise<OpfsProbeDirectoryHandle>;
|
|
71
|
+
/**
|
|
72
|
+
* The scratch file name to open under `pgxsinkit/probe/`. Defaults to `probe-<random>` — UNIQUE per call
|
|
73
|
+
* so concurrent SharedWorkers (different stores, same origin) can probe simultaneously without contending
|
|
74
|
+
* on one file. Injected for deterministic tests.
|
|
75
|
+
*/
|
|
76
|
+
scratchName?: string;
|
|
77
|
+
/** Wall clock. Defaults to `performance.now()`-or-`Date.now()` (the `boot-report.ts` `nowMs` pattern). */
|
|
78
|
+
now?: () => number;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** The API-absent verdict message — no throw occurred, so there is no `Name: message` to report verbatim. */
|
|
82
|
+
const OPFS_API_ABSENT_ERROR = "OPFS API not available: navigator.storage.getDirectory is absent in this scope";
|
|
83
|
+
|
|
84
|
+
/** Verbatim `Name: message` attribution the diagnostics envelope wants (never parsed downstream). */
|
|
85
|
+
function describeProbeError(error: unknown): string {
|
|
86
|
+
if (error instanceof Error) return `${error.name}: ${error.message}`;
|
|
87
|
+
return String(error);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** The default scratch suffix — a short random tail so each probe file is unique per call. */
|
|
91
|
+
function defaultScratchName(): string {
|
|
92
|
+
const uuid = (globalThis as { crypto?: { randomUUID?: () => string } }).crypto?.randomUUID?.();
|
|
93
|
+
// `randomUUID` exists in every scope pgxsinkit runs a probe in (browser SharedWorker, Bun); the fallback
|
|
94
|
+
// only guards exotic embeds and is still unique enough for a per-call scratch name.
|
|
95
|
+
return `probe-${uuid ? uuid.slice(0, 8) : Math.random().toString(36).slice(2, 10)}`;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** Resolve the default OPFS root getter off `globalThis`, or `null` when the API is absent. */
|
|
99
|
+
function resolveDefaultGetRoot(): (() => Promise<OpfsProbeDirectoryHandle>) | null {
|
|
100
|
+
const storage = (
|
|
101
|
+
globalThis as {
|
|
102
|
+
navigator?: { storage?: { getDirectory?: () => Promise<OpfsProbeDirectoryHandle> } };
|
|
103
|
+
}
|
|
104
|
+
).navigator?.storage;
|
|
105
|
+
const getDirectory = storage?.getDirectory;
|
|
106
|
+
if (getDirectory == null) return null;
|
|
107
|
+
return () => getDirectory.call(storage);
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* Probe whether a REAL `createSyncAccessHandle` open succeeds in the executing scope — the ADR-0049 D1
|
|
112
|
+
* verdict that decides the engine home. Granted → the engine boots in this scope (SharedWorker-direct) and
|
|
113
|
+
* election never engages; denied → router-only mode (attach acks carry `electionRequired: true`).
|
|
114
|
+
*
|
|
115
|
+
* Sequence, all under the `pgxsinkit/probe/` namespace ({@link opfsProbeDirectoryPath}):
|
|
116
|
+
* 1. Resolve the OPFS root (`navigator.storage.getDirectory()`); API absent → {@link OPFS_API_ABSENT_ERROR}.
|
|
117
|
+
* 2. Walk/create `pgxsinkit` → `probe` (`{ create: true }`).
|
|
118
|
+
* 3. Create the scratch file (`{ create: true }`).
|
|
119
|
+
* 4. Call `createSyncAccessHandle()` — the verdict. Absence at call time throws a `TypeError` we report.
|
|
120
|
+
* 5. On success: `close()` the handle → granted.
|
|
121
|
+
* 6. ALWAYS (finally): `removeEntry` the scratch file, best-effort.
|
|
122
|
+
*
|
|
123
|
+
* Any throw in steps 1–4 (bar the API-absent early return) → `{ granted: false, error: "Name: message" }`.
|
|
124
|
+
* The probe NEVER rethrows: it answers, it never fails. And it is NEVER cached — every call probes afresh
|
|
125
|
+
* (invariant 8).
|
|
126
|
+
*/
|
|
127
|
+
export async function probeOpfsSyncAccess(deps: PlacementProbeDeps = {}): Promise<PlacementProbeResult> {
|
|
128
|
+
const now = deps.now ?? nowMs;
|
|
129
|
+
const start = now();
|
|
130
|
+
const elapsed = (): number => Math.max(0, now() - start);
|
|
131
|
+
|
|
132
|
+
const getRoot = deps.getRoot ?? resolveDefaultGetRoot();
|
|
133
|
+
if (getRoot == null) {
|
|
134
|
+
// API absent: no handle open was even attempted, so there is no thrown error to attribute verbatim.
|
|
135
|
+
return { granted: false, error: OPFS_API_ABSENT_ERROR, ms: elapsed() };
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
const scratchName = deps.scratchName ?? defaultScratchName();
|
|
139
|
+
const [container, probe] = opfsProbeDirectoryPath();
|
|
140
|
+
|
|
141
|
+
// Held so `finally` can remove the scratch file once the probe directory has been resolved; undefined
|
|
142
|
+
// means the walk never got that far (nothing to clean up).
|
|
143
|
+
let probeDir: OpfsProbeDirectoryHandle | undefined;
|
|
144
|
+
try {
|
|
145
|
+
const root = await getRoot();
|
|
146
|
+
const containerHandle = await root.getDirectoryHandle(container, { create: true });
|
|
147
|
+
probeDir = await containerHandle.getDirectoryHandle(probe, { create: true });
|
|
148
|
+
const fileHandle = await probeDir.getFileHandle(scratchName, { create: true });
|
|
149
|
+
// Call, never pre-check: absence surfaces as the thrown TypeError we report verbatim (a real "no sync
|
|
150
|
+
// access" verdict), not as a method-presence sniff.
|
|
151
|
+
const open = (fileHandle as { createSyncAccessHandle: () => Promise<OpfsSyncAccessHandle> }).createSyncAccessHandle;
|
|
152
|
+
const handle = await open.call(fileHandle);
|
|
153
|
+
handle.close();
|
|
154
|
+
return { granted: true, ms: elapsed() };
|
|
155
|
+
} catch (error) {
|
|
156
|
+
return { granted: false, error: describeProbeError(error), ms: elapsed() };
|
|
157
|
+
} finally {
|
|
158
|
+
if (probeDir != null) {
|
|
159
|
+
try {
|
|
160
|
+
await probeDir.removeEntry(scratchName);
|
|
161
|
+
} catch {
|
|
162
|
+
// Best-effort cleanup: a leftover scratch file in the probe namespace harms nothing (it is not a
|
|
163
|
+
// store, and the next probe uses a fresh unique name), and a cleanup error must NEVER demote a
|
|
164
|
+
// granted verdict — the verdict was already decided by the open above.
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
}
|
package/src/schema.ts
CHANGED
|
@@ -37,25 +37,21 @@ interface ResolvedProjection {
|
|
|
37
37
|
reconcileTrigger: string;
|
|
38
38
|
}
|
|
39
39
|
|
|
40
|
-
/**
|
|
41
|
-
* Local key/value metadata table. Holds the registry fingerprint the local store was
|
|
42
|
-
* provisioned under (ADR-0006), so a registry change is detected on boot and the read
|
|
43
|
-
* cache is rebuilt — rather than relying on a hand-bumped `idb://…-vN` suffix.
|
|
44
|
-
*/
|
|
40
|
+
/** Local key/value metadata table for current-store safety, boot state, and registry identity. */
|
|
45
41
|
export const LOCAL_META_TABLE = "pgxsinkit_local_meta";
|
|
46
42
|
export const REGISTRY_FINGERPRINT_KEY = "registry_fingerprint";
|
|
47
43
|
/**
|
|
48
44
|
* The `pgxsinkit_local_meta` key holding the DURABLE-schema fingerprint the local store was last
|
|
49
|
-
* provisioned under
|
|
45
|
+
* provisioned under for the warm-store schema fast path. Its value is
|
|
50
46
|
* `lsf1:<hash(durable SQL)>` (see {@link computeLocalSchemaFingerprint}); a boot compares it against the
|
|
51
47
|
* freshly-generated durable SQL's hash to SKIP the durable replay when they match.
|
|
52
48
|
*/
|
|
53
49
|
export const LOCAL_SCHEMA_FINGERPRINT_KEY = "local_schema_fingerprint";
|
|
54
|
-
/** The
|
|
50
|
+
/** The fixed namespace for the exact supported local-schema fingerprint. */
|
|
55
51
|
export const LOCAL_SCHEMA_FINGERPRINT_PREFIX = "lsf1:";
|
|
56
52
|
|
|
57
53
|
/**
|
|
58
|
-
* The registry-wide cross-journal mutation view
|
|
54
|
+
* The registry-wide cross-journal mutation view used by the mutation-status API,
|
|
59
55
|
* option 1). A `TEMP` view UNION-ALL-ing every writable table's journal down to the shared fixed columns
|
|
60
56
|
* (plus a `table_key` literal per branch), so a consumer can render one global mutation summary/detail
|
|
61
57
|
* subscription instead of one live query per writable journal. It MUST be `TEMP`: an ephemeral entry's
|
|
@@ -207,11 +203,11 @@ function buildEntryClusterStatements(entry: SyncTableEntry, tableKey: string, lo
|
|
|
207
203
|
`mutation_seq INTEGER NOT NULL UNIQUE DEFAULT nextval(${quoteSqlStringLiteral(qualifiedJournalSequenceName)})::integer`,
|
|
208
204
|
"mutation_kind VARCHAR(24) NOT NULL",
|
|
209
205
|
"status VARCHAR(24) NOT NULL",
|
|
210
|
-
//
|
|
211
|
-
//
|
|
212
|
-
"registry_version TEXT",
|
|
206
|
+
// Registry identity retained with each mutation so a future supported release can reason about
|
|
207
|
+
// mutations authored before a registry transition.
|
|
208
|
+
"registry_version TEXT NOT NULL",
|
|
213
209
|
// ADR-0011 reserved hook: the Server version the entity was observed at when this mutation
|
|
214
|
-
// was authored. The slot lives on the journal
|
|
210
|
+
// was authored. The slot lives on the journal per mutation;
|
|
215
211
|
// the stale-write conflict policy (ADR-0015) decides its exact semantics and stamps it.
|
|
216
212
|
"base_server_version BIGINT",
|
|
217
213
|
// ADR-0022: the dynamic write-unit tag stamped by a `transaction({ mode })` block — the shared
|
|
@@ -236,7 +232,7 @@ function buildEntryClusterStatements(entry: SyncTableEntry, tableKey: string, lo
|
|
|
236
232
|
// Journal indexes render through the SAME core the pgTable-driven renderer uses
|
|
237
233
|
// ({@link renderCreateIndexStatement}), so the two index-emitting paths cannot drift in statement
|
|
238
234
|
// shape. These names/columns are registry-derived bare identifiers, passed verbatim (the pgTable
|
|
239
|
-
// path is the one that quotes)
|
|
235
|
+
// path is the one that quotes), so both index-emitting paths render the same statement text.
|
|
240
236
|
statements.push(
|
|
241
237
|
renderCreateIndexStatement(projection.journalTable, `${journalTableName}_status_idx`, ["status", "enqueued_at_us"]),
|
|
242
238
|
);
|
|
@@ -416,7 +412,7 @@ function ephemeralSchemaStatements<TRegistry extends SyncTableRegistry>(registry
|
|
|
416
412
|
}
|
|
417
413
|
|
|
418
414
|
/**
|
|
419
|
-
* The `CREATE OR REPLACE TEMP VIEW pgxsinkit_all_mutations` statement
|
|
415
|
+
* The `CREATE OR REPLACE TEMP VIEW pgxsinkit_all_mutations` statement for the mutation-status API, or
|
|
420
416
|
* `[]` when the registry has no writable table. Each branch selects a `table_key` literal plus the shared
|
|
421
417
|
* fixed journal columns ({@link ALL_MUTATIONS_JOURNAL_COLUMNS}) from one writable journal, UNION-ALL-ed.
|
|
422
418
|
* Generated DDL (existing generator style): the branch column list is a fixed identifier set and each
|
|
@@ -469,20 +465,19 @@ export function generateEphemeralLocalSchemaSql<TRegistry extends SyncTableRegis
|
|
|
469
465
|
/**
|
|
470
466
|
* The complete local schema — durable statements then ephemeral statements — the single script the
|
|
471
467
|
* wipe/rebuild paths and every external caller keep using. For an all-persistent registry the durable stream
|
|
472
|
-
*
|
|
473
|
-
*
|
|
474
|
-
*
|
|
475
|
-
*
|
|
476
|
-
*
|
|
477
|
-
*
|
|
478
|
-
* by construction (test-covered).
|
|
468
|
+
* is the registry-ordered stream, followed by the always-applied ephemeral portion — which for any registry
|
|
469
|
+
* with a writable table carries the `pgxsinkit_all_mutations` TEMP VIEW as its trailing statement. For a
|
|
470
|
+
* MIXED registry the script is idempotent-equivalent to (not a character-for-character match of) a
|
|
471
|
+
* single-pass interleave: the persistent clusters precede the ephemeral ones and the ephemeral portion
|
|
472
|
+
* re-emits idempotent enum guards — a reordering of independent `IF NOT EXISTS` DDL that executes to the
|
|
473
|
+
* same schema. Equals `durable + ephemeral` by construction (test-covered).
|
|
479
474
|
*/
|
|
480
475
|
export function generateLocalSchemaSql<TRegistry extends SyncTableRegistry>(registry: TRegistry): string {
|
|
481
476
|
return joinSchemaStatements([...durableSchemaStatements(registry), ...ephemeralSchemaStatements(registry)]);
|
|
482
477
|
}
|
|
483
478
|
|
|
484
479
|
/**
|
|
485
|
-
* The durable-schema fingerprint value
|
|
480
|
+
* The durable-schema fingerprint value: `lsf1:<FNV-1a hash of the durable SQL>`. The
|
|
486
481
|
* hash is over the generated durable DDL body itself (no composed inputs, no hand-maintained format-version
|
|
487
482
|
* constant), so it auto-invalidates on ANY generator change, registry change, or projection rename — the
|
|
488
483
|
* ADR-0018 apply-function-fingerprint precedent applied to the local schema. Stamped into
|