@spooky-sync/core 0.0.1-canary.30 → 0.0.1-canary.301
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/AGENTS.md +81 -0
- package/README.md +56 -16
- package/dist/index.d.ts +2026 -137
- package/dist/index.js +14939 -2432
- package/dist/live.d.ts +141 -0
- package/dist/live.js +709 -0
- package/dist/otel/index.d.ts +1 -1
- package/dist/otel/index.js +3 -3
- package/dist/pure.d.ts +329 -0
- package/dist/pure.js +24 -0
- package/dist/sqlite-open.js +358 -0
- package/dist/sqlite-worker.d.ts +1 -0
- package/dist/sqlite-worker.js +439 -0
- package/dist/sw.d.ts +207 -0
- package/dist/sw.js +393 -0
- package/dist/tabs-broker-worker.d.ts +8 -0
- package/dist/tabs-broker-worker.js +472 -0
- package/dist/types.d.ts +1765 -38
- package/dist/worker-edges.js +423 -0
- package/dist/worker-impersonation.js +60 -0
- package/dist/worker-ref-tables.d.ts +46 -0
- package/dist/worker-types.d.ts +112 -0
- package/dist/worker-types.js +73 -0
- package/package.json +27 -7
- package/scripts/check-broker-bundle.mjs +33 -0
- package/scripts/check-worker-entries.mjs +172 -0
- package/skills/sp00ky-core/SKILL.md +31 -6
- package/skills/sp00ky-core/references/config.md +6 -0
- package/src/boot/auth-flip.saga.test.ts +82 -0
- package/src/boot/auth-flip.saga.ts +62 -0
- package/src/boot/boot.saga.test.ts +158 -0
- package/src/boot/boot.saga.ts +131 -0
- package/src/boot/bucket-switch.saga.test.ts +187 -0
- package/src/boot/bucket-switch.saga.ts +133 -0
- package/src/boot/preload.saga.test.ts +51 -0
- package/src/boot/preload.saga.ts +31 -0
- package/src/bucket-blurhash.test.ts +148 -0
- package/src/build-globals.d.ts +12 -0
- package/src/client/bucket-handle.test.ts +117 -0
- package/src/client/bucket-handle.ts +227 -0
- package/src/client/router.test.ts +58 -0
- package/src/client/router.ts +100 -0
- package/src/client/runtime.test.ts +195 -0
- package/src/client/runtime.ts +296 -0
- package/src/client/services.ts +370 -0
- package/src/client/sp00ky-client.test.ts +303 -0
- package/src/client/sp00ky-client.ts +586 -0
- package/src/events/events.test.ts +2 -1
- package/src/events/index.ts +3 -0
- package/src/index.ts +69 -1
- package/src/kernel/constants.test.ts +19 -0
- package/src/kernel/constants.ts +80 -0
- package/src/kernel/effects.test.ts +40 -0
- package/src/kernel/effects.ts +161 -0
- package/src/kernel/events.ts +57 -0
- package/src/kernel/interpreter.test.ts +116 -0
- package/src/kernel/interpreter.ts +148 -0
- package/src/kernel/saga.test.ts +89 -0
- package/src/kernel/saga.ts +73 -0
- package/src/live/index.test.ts +478 -0
- package/src/live/index.ts +1013 -0
- package/src/modules/app-release/index.test.ts +125 -0
- package/src/modules/app-release/index.ts +209 -0
- package/src/modules/auth/auth.local-first.test.ts +141 -0
- package/src/modules/auth/events/index.ts +9 -2
- package/src/modules/auth/impersonation-banner.ts +443 -0
- package/src/modules/auth/impersonation.test.ts +355 -0
- package/src/modules/auth/impersonation.ts +179 -0
- package/src/modules/auth/index.ts +386 -17
- package/src/modules/crdt/crdt-field.ts +294 -0
- package/src/modules/crdt/crdt-hydration.test.ts +210 -0
- package/src/modules/crdt/crdt-reconnect.test.ts +195 -0
- package/src/modules/crdt/index.ts +463 -0
- package/src/modules/crdt/loro-loader.ts +25 -0
- package/src/modules/devtools/flags.ts +349 -0
- package/src/modules/devtools/index.ts +746 -95
- package/src/modules/devtools/mutations.test.ts +92 -0
- package/src/modules/devtools/mutations.ts +160 -0
- package/src/modules/devtools/notify-throttle.test.ts +166 -0
- package/src/modules/devtools/state-shape.test.ts +263 -0
- package/src/modules/devtools/storage-info.test.ts +79 -0
- package/src/modules/devtools/storage-info.ts +168 -0
- package/src/modules/devtools/versions.test.ts +74 -0
- package/src/modules/devtools/versions.ts +110 -0
- package/src/modules/feature-flag/index.test.ts +251 -0
- package/src/modules/feature-flag/index.ts +316 -0
- package/src/modules/ref-tables.test.ts +91 -0
- package/src/modules/ref-tables.ts +88 -0
- package/src/modules/web-push/index.test.ts +824 -0
- package/src/modules/web-push/index.ts +1027 -0
- package/src/mutation/jobs.test.ts +25 -0
- package/src/mutation/jobs.ts +41 -0
- package/src/mutation/mutation-id.test.ts +37 -0
- package/src/mutation/mutation-id.ts +35 -0
- package/src/mutation/pending-writes.integration.test.ts +175 -0
- package/src/mutation/push.saga.test.ts +285 -0
- package/src/mutation/push.saga.ts +217 -0
- package/src/mutation/rows.test.ts +231 -0
- package/src/mutation/rows.ts +427 -0
- package/src/mutation/tray.saga.test.ts +63 -0
- package/src/mutation/tray.saga.ts +48 -0
- package/src/mutation/write.saga.test.ts +316 -0
- package/src/mutation/write.saga.ts +268 -0
- package/src/otel/index.ts +10 -7
- package/src/pure.ts +65 -0
- package/src/push/types.ts +174 -0
- package/src/query/env.test.ts +23 -0
- package/src/query/env.ts +56 -0
- package/src/query/fetch.saga.test.ts +199 -0
- package/src/query/fetch.saga.ts +120 -0
- package/src/query/hash.test.ts +14 -0
- package/src/query/hash.ts +18 -0
- package/src/query/id-set-plan.test.ts +132 -0
- package/src/query/lifecycle.saga.test.ts +274 -0
- package/src/query/lifecycle.saga.ts +159 -0
- package/src/query/materialize.saga.test.ts +115 -0
- package/src/query/materialize.saga.ts +84 -0
- package/src/query/materialize.test.ts +58 -0
- package/src/query/materialize.ts +57 -0
- package/src/query/membership.saga.test.ts +350 -0
- package/src/query/membership.saga.ts +278 -0
- package/src/query/membership.test.ts +118 -0
- package/src/query/membership.ts +201 -0
- package/src/query/register.saga.test.ts +293 -0
- package/src/query/register.saga.ts +226 -0
- package/src/query/render-set.test.ts +47 -0
- package/src/query/render-set.ts +71 -0
- package/src/query/sql.test.ts +63 -0
- package/src/query/sql.ts +93 -0
- package/src/query/window-query.test.ts +70 -0
- package/src/query/window-query.ts +195 -0
- package/src/services/blobs/blob-cache.test.ts +359 -0
- package/src/services/blobs/blob-cache.ts +603 -0
- package/src/services/blobs/blob-manifest.ts +227 -0
- package/src/services/blobs/blob-store.test.ts +77 -0
- package/src/services/blobs/blob-store.ts +359 -0
- package/src/services/blobs/blob.fixture.ts +90 -0
- package/src/services/blobs/index.ts +70 -0
- package/src/services/database/cache-engine.ts +199 -0
- package/src/services/database/connection-supervisor.test.ts +318 -0
- package/src/services/database/connection-supervisor.ts +422 -0
- package/src/services/database/database.query-timeout.test.ts +140 -0
- package/src/services/database/database.responses.test.ts +43 -0
- package/src/services/database/database.ts +146 -61
- package/src/services/database/engine-factory.ts +33 -0
- package/src/services/database/errors.ts +34 -0
- package/src/services/database/events/index.ts +2 -1
- package/src/services/database/index.ts +7 -0
- package/src/services/database/landed-body-clear.integration.test.ts +236 -0
- package/src/services/database/local-migrator.integration.test.ts +110 -0
- package/src/services/database/local-migrator.ts +59 -16
- package/src/services/database/local.test.ts +64 -0
- package/src/services/database/local.ts +487 -63
- package/src/services/database/plan-render.test.ts +159 -0
- package/src/services/database/plan-render.ts +108 -0
- package/src/services/database/relation-resolver.test.ts +467 -0
- package/src/services/database/relation-resolver.ts +0 -0
- package/src/services/database/remote.ts +213 -6
- package/src/services/database/sqlite-cache-engine.test.ts +617 -0
- package/src/services/database/sqlite-cache-engine.timeout.test.ts +61 -0
- package/src/services/database/sqlite-cache-engine.ts +1372 -0
- package/src/services/database/sqlite-devtools-queries.integration.test.ts +143 -0
- package/src/services/database/sqlite-devtools-queries.test.ts +154 -0
- package/src/services/database/sqlite-lock-verify.test.ts +33 -0
- package/src/services/database/sqlite-lock-verify.ts +45 -0
- package/src/services/database/sqlite-open.test.ts +150 -0
- package/src/services/database/sqlite-open.ts +164 -0
- package/src/services/database/sqlite-plan-sql.test.ts +139 -0
- package/src/services/database/sqlite-plan-sql.ts +179 -0
- package/src/services/database/sqlite-projection.test.ts +121 -0
- package/src/services/database/sqlite-select.integration.test.ts +185 -0
- package/src/services/database/sqlite-select.test.ts +246 -0
- package/src/services/database/sqlite-select.ts +131 -0
- package/src/services/database/sqlite-transport.fixture.ts +30 -0
- package/src/services/database/sqlite-transport.ts +224 -0
- package/src/services/database/sqlite-worker.ts +437 -0
- package/src/services/database/surql-translate.ts +416 -0
- package/src/services/database/surreal-cache-engine.ts +161 -0
- package/src/services/logger/index.test.ts +132 -0
- package/src/services/logger/index.ts +189 -7
- package/src/services/persistence/localstorage.ts +2 -2
- package/src/services/persistence/resilient.ts +10 -3
- package/src/services/persistence/surrealdb.ts +4 -4
- package/src/services/stream-processor/index.ts +779 -67
- package/src/services/stream-processor/permissions.test.ts +47 -0
- package/src/services/stream-processor/permissions.ts +53 -0
- package/src/services/stream-processor/stream-processor.batch.test.ts +186 -0
- package/src/services/stream-processor/stream-processor.prime.test.ts +198 -0
- package/src/services/stream-processor/stream-processor.reset.test.ts +226 -0
- package/src/services/stream-processor/stream-processor.test.ts +1 -1
- package/src/services/stream-processor/wasm-types.ts +58 -2
- package/src/services/tabs/broker-client.ts +283 -0
- package/src/services/tabs/broker.test.ts +327 -0
- package/src/services/tabs/coordinator.test.ts +386 -0
- package/src/services/tabs/coordinator.ts +638 -0
- package/src/services/tabs/fake-ports.fixture.ts +112 -0
- package/src/services/tabs/leader-locks.ts +75 -0
- package/src/services/tabs/protocol.ts +262 -0
- package/src/services/tabs/support.ts +36 -0
- package/src/services/tabs/tabs-broker-worker.ts +640 -0
- package/src/sp00ky.ts +5 -395
- package/src/state/client-state.ts +200 -0
- package/src/state/lifecycle.test.ts +118 -0
- package/src/state/lifecycle.ts +86 -0
- package/src/state/reducers.test.ts +304 -0
- package/src/state/reducers.ts +526 -0
- package/src/state/selectors.test.ts +167 -0
- package/src/state/selectors.ts +216 -0
- package/src/sw/index.test.ts +582 -0
- package/src/sw/index.ts +607 -0
- package/src/sw/store.ts +96 -0
- package/src/sync/connection.saga.test.ts +86 -0
- package/src/sync/connection.saga.ts +85 -0
- package/src/sync/live.saga.test.ts +178 -0
- package/src/sync/live.saga.ts +107 -0
- package/src/sync/policy.health.test.ts +56 -0
- package/src/sync/policy.test.ts +659 -0
- package/src/sync/policy.ts +502 -0
- package/src/sync/poll.saga.test.ts +51 -0
- package/src/sync/poll.saga.ts +36 -0
- package/src/sync/tabs.saga.test.ts +78 -0
- package/src/sync/tabs.saga.ts +96 -0
- package/src/testing/adapters.ts +133 -0
- package/src/testing/build.ts +63 -0
- package/src/testing/fake-services.ts +48 -0
- package/src/testing/run-pure.test.ts +92 -0
- package/src/testing/run-pure.ts +128 -0
- package/src/testing/services.ts +17 -0
- package/src/types.ts +624 -10
- package/src/utils/blurhash.ts +90 -0
- package/src/utils/edges.ts +39 -0
- package/src/utils/error-classification.test.ts +54 -0
- package/src/utils/error-classification.ts +25 -0
- package/src/utils/index.ts +75 -9
- package/src/utils/parser.test.ts +67 -102
- package/src/utils/parser.ts +64 -2
- package/src/utils/semver.test.ts +32 -0
- package/src/utils/semver.ts +30 -0
- package/src/utils/sha256.ts +15 -0
- package/src/utils/surql.ts +30 -18
- package/src/utils/utils.test.ts +2 -1
- package/tsdown.config.ts +117 -3
- package/vitest.config.ts +48 -0
- package/src/modules/cache/index.ts +0 -241
- package/src/modules/cache/types.ts +0 -19
- package/src/modules/data/data.test.ts +0 -58
- package/src/modules/data/index.ts +0 -879
- package/src/modules/sync/engine.ts +0 -173
- package/src/modules/sync/events/index.ts +0 -77
- package/src/modules/sync/index.ts +0 -3
- package/src/modules/sync/queue/index.ts +0 -2
- package/src/modules/sync/queue/queue-down.ts +0 -89
- package/src/modules/sync/queue/queue-up.ts +0 -223
- package/src/modules/sync/scheduler.ts +0 -84
- package/src/modules/sync/sync.ts +0 -421
- package/src/modules/sync/utils.test.ts +0 -311
- package/src/modules/sync/utils.ts +0 -167
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Rewrite a windowed (`LIMIT n START m`, m>0) SELECT so its rows are
|
|
3
|
+
* materialized from an explicit record-id set — the window the SSP already
|
|
4
|
+
* computed — instead of re-running the original query (with its `START m`)
|
|
5
|
+
* against the shared local DB.
|
|
6
|
+
*
|
|
7
|
+
* Why: `DataModule.processStreamUpdate` materializes a query's rows by
|
|
8
|
+
* re-querying the local in-browser SurrealDB with the original surql. For an
|
|
9
|
+
* offset query that re-applies `START m` against the *shared* local store —
|
|
10
|
+
* which, with sparse windowing, may hold only this window's rows — so it skips
|
|
11
|
+
* them all and returns nothing (the "page 2 returns 0 rows" bug). The SSP's
|
|
12
|
+
* materialized view (`StreamUpdate.localArray`) is exactly this window's row
|
|
13
|
+
* ids, so we select those ids directly and re-apply the original `ORDER BY` for
|
|
14
|
+
* stable display order.
|
|
15
|
+
*
|
|
16
|
+
* Returns `null` for non-offset queries (`START` absent or 0) — the caller
|
|
17
|
+
* keeps the normal re-query path, so only the broken case changes behavior.
|
|
18
|
+
*
|
|
19
|
+
* Preserves the `SELECT <projection>` clause and the top-level `ORDER BY`;
|
|
20
|
+
* drops the original `FROM`/`WHERE`/`LIMIT`/`START`. Subqueries inside the
|
|
21
|
+
* projection are preserved verbatim (the scanner is paren/quote aware), with
|
|
22
|
+
* one caveat: SurrealDB v3 drops `*` in the `SELECT *, <subquery> FROM $param`
|
|
23
|
+
* shape — such windowed+subquery queries are rare and were already returning 0,
|
|
24
|
+
* so this is no regression.
|
|
25
|
+
*/
|
|
26
|
+
import type { QueryPlan } from '@spooky-sync/query-builder';
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Plan-level window materialization: restrict a windowed query's base rows to
|
|
30
|
+
* exactly the SSP-computed id-set, dropping `where`/`limit`/`offset` but keeping
|
|
31
|
+
* `orderBy`, `select` and `relations`. The engine-neutral counterpart of
|
|
32
|
+
* {@link buildWindowMaterialization} (which does the same by string surgery for
|
|
33
|
+
* the raw-SurrealQL path). Returns `null` for non-offset queries so the caller
|
|
34
|
+
* keeps the normal re-query path.
|
|
35
|
+
*/
|
|
36
|
+
export function buildWindowMaterializationPlan(
|
|
37
|
+
plan: QueryPlan,
|
|
38
|
+
ids: unknown[]
|
|
39
|
+
): QueryPlan | null {
|
|
40
|
+
if (plan.offset === undefined || plan.offset <= 0) return null;
|
|
41
|
+
return buildIdSetPlan(plan, ids);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Raw-SurrealQL counterpart of {@link buildIdSetPlan}, for queries that arrived
|
|
46
|
+
* without a plan. Same rewrite as {@link buildWindowMaterialization} without the
|
|
47
|
+
* offset guard: keep the projection and top-level `ORDER BY`, replace the source
|
|
48
|
+
* with the bound id-set.
|
|
49
|
+
*/
|
|
50
|
+
export function buildIdSetSurql(
|
|
51
|
+
surql: string,
|
|
52
|
+
idsParam = '__win'
|
|
53
|
+
): { query: string } | null {
|
|
54
|
+
const kw = scanTopLevelClauses(surql);
|
|
55
|
+
if (kw.fromIndex === null) return null;
|
|
56
|
+
return { query: renderIdSetSelect(surql, kw, idsParam) };
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** Shared body of the two id-set surql rewrites: keep the projection and the
|
|
60
|
+
* top-level `ORDER BY`, replace the source with the bound id-set. */
|
|
61
|
+
function renderIdSetSelect(surql: string, kw: TopLevelClauses, idsParam: string): string {
|
|
62
|
+
const selectClause = surql.slice(0, kw.fromIndex!).trimEnd(); // "SELECT <projection>"
|
|
63
|
+
|
|
64
|
+
let orderBy = '';
|
|
65
|
+
const orderByIndex = kw.orderByIndex;
|
|
66
|
+
if (orderByIndex !== null) {
|
|
67
|
+
const ends = [kw.limitIndex, kw.startIndex, kw.semicolonIndex, surql.length].filter(
|
|
68
|
+
(n): n is number => n !== null && n > orderByIndex
|
|
69
|
+
);
|
|
70
|
+
orderBy = ' ' + surql.slice(orderByIndex, Math.min(...ends)).trim();
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
return `${selectClause} FROM $${idsParam}${orderBy}`;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* Restrict any plan's base rows to an explicit id-set, regardless of offset.
|
|
78
|
+
*
|
|
79
|
+
* Same rewrite as {@link buildWindowMaterializationPlan} without the offset
|
|
80
|
+
* guard, for rendering a query from its authoritative membership list rather
|
|
81
|
+
* than by re-running its predicate.
|
|
82
|
+
*
|
|
83
|
+
* `where` is dropped deliberately: the id-set already IS the answer to the
|
|
84
|
+
* predicate as the server evaluated it, and re-applying the `WHERE` locally is
|
|
85
|
+
* exactly the bug — a row that left the window keeps its (stale, never
|
|
86
|
+
* re-fetched) local body, so it keeps matching and keeps rendering.
|
|
87
|
+
* `limit`/`offset` go for the same reason: both are already baked into which ids
|
|
88
|
+
* are in the set, so the set itself is the bound. (Both engines ignore them on
|
|
89
|
+
* the `ids` path regardless — only `select` and `orderBy` are honored there.)
|
|
90
|
+
* `orderBy` is kept so display order stays deterministic.
|
|
91
|
+
*/
|
|
92
|
+
export function buildIdSetPlan(plan: QueryPlan, ids: unknown[]): QueryPlan {
|
|
93
|
+
return {
|
|
94
|
+
...plan,
|
|
95
|
+
ids,
|
|
96
|
+
where: undefined,
|
|
97
|
+
limit: undefined,
|
|
98
|
+
offset: undefined,
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
export function buildWindowMaterialization(
|
|
103
|
+
surql: string,
|
|
104
|
+
idsParam = '__win'
|
|
105
|
+
): { query: string } | null {
|
|
106
|
+
const kw = scanTopLevelClauses(surql);
|
|
107
|
+
// `START` is only recorded once `FROM` was seen, so a positive start value
|
|
108
|
+
// implies a FROM index.
|
|
109
|
+
if (kw.startValue === null || kw.startValue <= 0) return null;
|
|
110
|
+
return { query: renderIdSetSelect(surql, kw, idsParam) };
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
interface TopLevelClauses {
|
|
114
|
+
fromIndex: number | null;
|
|
115
|
+
orderByIndex: number | null;
|
|
116
|
+
limitIndex: number | null;
|
|
117
|
+
startIndex: number | null;
|
|
118
|
+
startValue: number | null;
|
|
119
|
+
semicolonIndex: number | null;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
// Single pass over the query, tracking paren depth and single-quoted strings so
|
|
123
|
+
// that clauses inside subqueries (which live in parens) are ignored — only the
|
|
124
|
+
// outermost (depth-0) clause keywords are recorded.
|
|
125
|
+
function scanTopLevelClauses(sql: string): TopLevelClauses {
|
|
126
|
+
const out: TopLevelClauses = {
|
|
127
|
+
fromIndex: null,
|
|
128
|
+
orderByIndex: null,
|
|
129
|
+
limitIndex: null,
|
|
130
|
+
startIndex: null,
|
|
131
|
+
startValue: null,
|
|
132
|
+
semicolonIndex: null,
|
|
133
|
+
};
|
|
134
|
+
let depth = 0;
|
|
135
|
+
let inStr = false;
|
|
136
|
+
|
|
137
|
+
for (let i = 0; i < sql.length; i++) {
|
|
138
|
+
const ch = sql[i];
|
|
139
|
+
if (inStr) {
|
|
140
|
+
if (ch === '\\') i++; // skip escaped char
|
|
141
|
+
else if (ch === "'") inStr = false;
|
|
142
|
+
continue;
|
|
143
|
+
}
|
|
144
|
+
if (ch === "'") { inStr = true; continue; }
|
|
145
|
+
if (ch === '(') { depth++; continue; }
|
|
146
|
+
if (ch === ')') { depth--; continue; }
|
|
147
|
+
if (depth !== 0) continue;
|
|
148
|
+
if (ch === ';' && out.semicolonIndex === null) { out.semicolonIndex = i; continue; }
|
|
149
|
+
|
|
150
|
+
// Only test keywords at a word boundary.
|
|
151
|
+
if (!isWordBoundary(sql, i)) continue;
|
|
152
|
+
if (out.fromIndex === null && matchKeyword(sql, i, 'FROM')) { out.fromIndex = i; continue; }
|
|
153
|
+
// FROM must come before the trailing clauses; only record them once seen.
|
|
154
|
+
if (out.fromIndex === null) continue;
|
|
155
|
+
if (out.orderByIndex === null && matchKeyword(sql, i, 'ORDER BY')) { out.orderByIndex = i; continue; }
|
|
156
|
+
if (out.limitIndex === null && matchKeyword(sql, i, 'LIMIT')) { out.limitIndex = i; continue; }
|
|
157
|
+
if (out.startIndex === null && matchKeyword(sql, i, 'START')) {
|
|
158
|
+
out.startIndex = i;
|
|
159
|
+
out.startValue = readNumberAfter(sql, i + 'START'.length);
|
|
160
|
+
continue;
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
return out;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
function isWordBoundary(sql: string, i: number): boolean {
|
|
167
|
+
if (i === 0) return true;
|
|
168
|
+
return !/[A-Za-z0-9_]/.test(sql[i - 1]);
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
// Case-insensitive keyword match where internal whitespace (e.g. "ORDER BY")
|
|
172
|
+
// matches any run of whitespace, and the keyword ends on a non-word char.
|
|
173
|
+
function matchKeyword(sql: string, i: number, keyword: string): boolean {
|
|
174
|
+
const parts = keyword.split(' ');
|
|
175
|
+
let pos = i;
|
|
176
|
+
for (let p = 0; p < parts.length; p++) {
|
|
177
|
+
const word = parts[p];
|
|
178
|
+
if (sql.slice(pos, pos + word.length).toUpperCase() !== word) return false;
|
|
179
|
+
pos += word.length;
|
|
180
|
+
if (p < parts.length - 1) {
|
|
181
|
+
const wsStart = pos;
|
|
182
|
+
while (pos < sql.length && /\s/.test(sql[pos])) pos++;
|
|
183
|
+
if (pos === wsStart) return false; // required whitespace
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
// Must end on a non-word char (or end of string).
|
|
187
|
+
return pos >= sql.length || !/[A-Za-z0-9_]/.test(sql[pos]);
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
function readNumberAfter(sql: string, from: number): number | null {
|
|
191
|
+
let pos = from;
|
|
192
|
+
while (pos < sql.length && /\s/.test(sql[pos])) pos++;
|
|
193
|
+
const m = /^\d+/.exec(sql.slice(pos));
|
|
194
|
+
return m ? parseInt(m[0], 10) : null;
|
|
195
|
+
}
|
|
@@ -0,0 +1,359 @@
|
|
|
1
|
+
import { describe, it, expect, vi } from 'vitest';
|
|
2
|
+
import { BlobCache } from './blob-cache';
|
|
3
|
+
import { BlobManifest } from './blob-manifest';
|
|
4
|
+
import { MemoryBlobStore, blobKeyId, type BlobKey } from './blob-store';
|
|
5
|
+
import { bytes, fakeLocalStore, fakeUrls, silentLogger } from './blob.fixture';
|
|
6
|
+
|
|
7
|
+
const KEY: BlobKey = { bucket: 'profile_pictures', path: 'avatar.png' };
|
|
8
|
+
|
|
9
|
+
function setup(opts: { maxBytes?: number; remote?: (key: BlobKey) => Promise<Blob | null> } = {}) {
|
|
10
|
+
const local = fakeLocalStore();
|
|
11
|
+
const store = new MemoryBlobStore('user-1');
|
|
12
|
+
const manifest = new BlobManifest(local.store);
|
|
13
|
+
const urls = fakeUrls();
|
|
14
|
+
let clock = 1000;
|
|
15
|
+
const fetchRemote = vi.fn(opts.remote ?? (async () => bytes(10)));
|
|
16
|
+
const cache = new BlobCache({
|
|
17
|
+
store,
|
|
18
|
+
manifest,
|
|
19
|
+
fetchRemote,
|
|
20
|
+
logger: silentLogger(),
|
|
21
|
+
maxBytes: opts.maxBytes ?? 1_000_000,
|
|
22
|
+
now: () => ++clock,
|
|
23
|
+
urls: urls.factory,
|
|
24
|
+
});
|
|
25
|
+
return { cache, store, manifest, local, urls, fetchRemote };
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
describe('BlobCache reads', () => {
|
|
29
|
+
it('serves the second read from the local store without touching the remote', async () => {
|
|
30
|
+
const { cache, fetchRemote } = setup();
|
|
31
|
+
|
|
32
|
+
const first = await cache.read(KEY);
|
|
33
|
+
const second = await cache.read(KEY);
|
|
34
|
+
|
|
35
|
+
expect(first).not.toBeNull();
|
|
36
|
+
expect(second).not.toBeNull();
|
|
37
|
+
expect(fetchRemote).toHaveBeenCalledTimes(1);
|
|
38
|
+
expect(cache.stats()).toMatchObject({ hits: 1, misses: 1, entries: 1 });
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
it('collapses concurrent misses on the same key into one remote read', async () => {
|
|
42
|
+
let release!: (blob: Blob) => void;
|
|
43
|
+
const pending = new Promise<Blob>((resolve) => {
|
|
44
|
+
release = resolve;
|
|
45
|
+
});
|
|
46
|
+
const { cache, fetchRemote } = setup({ remote: () => pending });
|
|
47
|
+
|
|
48
|
+
const all = Promise.all([cache.read(KEY), cache.read(KEY), cache.read(KEY)]);
|
|
49
|
+
release(bytes(10));
|
|
50
|
+
const results = await all;
|
|
51
|
+
|
|
52
|
+
expect(results.every((r) => r !== null)).toBe(true);
|
|
53
|
+
expect(fetchRemote).toHaveBeenCalledTimes(1);
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
it('refetches when the file vanished from the local store behind our back', async () => {
|
|
57
|
+
const { cache, store, fetchRemote } = setup();
|
|
58
|
+
await cache.read(KEY);
|
|
59
|
+
|
|
60
|
+
await store.remove(KEY);
|
|
61
|
+
await cache.read(KEY);
|
|
62
|
+
|
|
63
|
+
expect(fetchRemote).toHaveBeenCalledTimes(2);
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
it('refetches when the stored size disagrees with the manifest', async () => {
|
|
67
|
+
const { cache, manifest, fetchRemote } = setup();
|
|
68
|
+
await cache.read(KEY);
|
|
69
|
+
|
|
70
|
+
// What a torn write or a racing tab leaves behind.
|
|
71
|
+
const entry = manifest.getById(blobKeyId(KEY))!;
|
|
72
|
+
manifest.put({ ...entry, size: entry.size + 1 });
|
|
73
|
+
await cache.read(KEY);
|
|
74
|
+
|
|
75
|
+
expect(fetchRemote).toHaveBeenCalledTimes(2);
|
|
76
|
+
});
|
|
77
|
+
|
|
78
|
+
it('returns null and keeps no row when the file does not exist remotely', async () => {
|
|
79
|
+
const { cache, manifest } = setup({ remote: async () => null });
|
|
80
|
+
|
|
81
|
+
expect(await cache.read(KEY)).toBeNull();
|
|
82
|
+
expect(manifest.all()).toHaveLength(0);
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
it('reload bypasses the local store', async () => {
|
|
86
|
+
const { cache, fetchRemote } = setup();
|
|
87
|
+
await cache.read(KEY);
|
|
88
|
+
|
|
89
|
+
await cache.read(KEY, { reload: true });
|
|
90
|
+
|
|
91
|
+
expect(fetchRemote).toHaveBeenCalledTimes(2);
|
|
92
|
+
});
|
|
93
|
+
|
|
94
|
+
it('persist:false serves the bytes but writes nothing durable', async () => {
|
|
95
|
+
const { cache, store, manifest } = setup();
|
|
96
|
+
|
|
97
|
+
expect(await cache.read(KEY, { persist: false })).not.toBeNull();
|
|
98
|
+
|
|
99
|
+
expect(await store.list()).toHaveLength(0);
|
|
100
|
+
expect(manifest.all()).toHaveLength(0);
|
|
101
|
+
});
|
|
102
|
+
});
|
|
103
|
+
|
|
104
|
+
describe('BlobCache revalidation', () => {
|
|
105
|
+
it('drops the cached copy when head() reports a different size', async () => {
|
|
106
|
+
const local = fakeLocalStore();
|
|
107
|
+
const fetchRemote = vi.fn(async () => bytes(10));
|
|
108
|
+
const cache = new BlobCache({
|
|
109
|
+
store: new MemoryBlobStore('user-1'),
|
|
110
|
+
manifest: new BlobManifest(local.store),
|
|
111
|
+
fetchRemote,
|
|
112
|
+
headRemote: async () => ({ size: 999 }),
|
|
113
|
+
logger: silentLogger(),
|
|
114
|
+
maxBytes: 1_000_000,
|
|
115
|
+
urls: fakeUrls().factory,
|
|
116
|
+
});
|
|
117
|
+
|
|
118
|
+
await cache.read(KEY);
|
|
119
|
+
await cache.read(KEY, { revalidate: 'head' });
|
|
120
|
+
|
|
121
|
+
expect(fetchRemote).toHaveBeenCalledTimes(2);
|
|
122
|
+
});
|
|
123
|
+
|
|
124
|
+
it('keeps the cached copy when head() fails — offline must not invalidate', async () => {
|
|
125
|
+
const local = fakeLocalStore();
|
|
126
|
+
const fetchRemote = vi.fn(async () => bytes(10));
|
|
127
|
+
const cache = new BlobCache({
|
|
128
|
+
store: new MemoryBlobStore('user-1'),
|
|
129
|
+
manifest: new BlobManifest(local.store),
|
|
130
|
+
fetchRemote,
|
|
131
|
+
headRemote: async () => {
|
|
132
|
+
throw new Error('offline');
|
|
133
|
+
},
|
|
134
|
+
logger: silentLogger(),
|
|
135
|
+
maxBytes: 1_000_000,
|
|
136
|
+
urls: fakeUrls().factory,
|
|
137
|
+
});
|
|
138
|
+
|
|
139
|
+
await cache.read(KEY);
|
|
140
|
+
await cache.read(KEY, { revalidate: 'head' });
|
|
141
|
+
|
|
142
|
+
expect(fetchRemote).toHaveBeenCalledTimes(1);
|
|
143
|
+
});
|
|
144
|
+
});
|
|
145
|
+
|
|
146
|
+
describe('BlobCache invalidation', () => {
|
|
147
|
+
it('invalidate removes the bytes, the row and the object URL', async () => {
|
|
148
|
+
const { cache, store, manifest, urls } = setup();
|
|
149
|
+
const lease = await cache.acquireUrl(KEY);
|
|
150
|
+
expect(lease).not.toBeNull();
|
|
151
|
+
|
|
152
|
+
await cache.invalidate(KEY);
|
|
153
|
+
|
|
154
|
+
expect(await store.list()).toHaveLength(0);
|
|
155
|
+
expect(manifest.all()).toHaveLength(0);
|
|
156
|
+
expect(urls.revoked).toContain(lease!.url);
|
|
157
|
+
});
|
|
158
|
+
});
|
|
159
|
+
|
|
160
|
+
describe('BlobCache eviction', () => {
|
|
161
|
+
const keyN = (n: number): BlobKey => ({ bucket: 'files', path: `f${n}.bin` });
|
|
162
|
+
|
|
163
|
+
it('evicts least-recently-used down to the low-water mark, never on age alone', async () => {
|
|
164
|
+
const { cache, manifest } = setup({ maxBytes: 1000, remote: async () => bytes(200) });
|
|
165
|
+
|
|
166
|
+
// 5 × 200B = 1000B: at budget, so nothing has been dropped yet.
|
|
167
|
+
for (let i = 0; i < 5; i++) await cache.read(keyN(i));
|
|
168
|
+
expect(manifest.all()).toHaveLength(5);
|
|
169
|
+
expect(cache.stats().evictedEntries).toBe(0);
|
|
170
|
+
|
|
171
|
+
// The sixth crosses the budget and triggers a sweep to 80% (800B → 4 files).
|
|
172
|
+
await cache.read(keyN(5));
|
|
173
|
+
|
|
174
|
+
expect(manifest.totalBytes()).toBeLessThanOrEqual(800);
|
|
175
|
+
expect(cache.stats().evictedEntries).toBeGreaterThan(0);
|
|
176
|
+
// Oldest goes first; the one just written stays.
|
|
177
|
+
expect(manifest.get(keyN(0))).toBeUndefined();
|
|
178
|
+
expect(manifest.get(keyN(5))).toBeDefined();
|
|
179
|
+
});
|
|
180
|
+
|
|
181
|
+
it('never evicts a pinned entry', async () => {
|
|
182
|
+
const { cache, manifest } = setup({ maxBytes: 1000, remote: async () => bytes(200) });
|
|
183
|
+
|
|
184
|
+
await cache.read(keyN(0), { pin: true });
|
|
185
|
+
for (let i = 1; i < 6; i++) await cache.read(keyN(i));
|
|
186
|
+
|
|
187
|
+
expect(manifest.get(keyN(0))).toBeDefined();
|
|
188
|
+
expect(manifest.get(keyN(0))!.pinned).toBe(true);
|
|
189
|
+
});
|
|
190
|
+
|
|
191
|
+
it('never evicts an entry whose object URL is still held', async () => {
|
|
192
|
+
const { cache, manifest } = setup({ maxBytes: 1000, remote: async () => bytes(200) });
|
|
193
|
+
|
|
194
|
+
const lease = await cache.acquireUrl(keyN(0));
|
|
195
|
+
for (let i = 1; i < 6; i++) await cache.read(keyN(i));
|
|
196
|
+
|
|
197
|
+
expect(manifest.get(keyN(0))).toBeDefined();
|
|
198
|
+
lease!.release();
|
|
199
|
+
});
|
|
200
|
+
|
|
201
|
+
it('pauses new writes instead of discarding pinned bytes when over budget', async () => {
|
|
202
|
+
const { cache, manifest } = setup({ maxBytes: 500, remote: async () => bytes(200) });
|
|
203
|
+
|
|
204
|
+
for (let i = 0; i < 4; i++) await cache.read(keyN(i), { pin: true });
|
|
205
|
+
|
|
206
|
+
expect(cache.stats().persistPaused).toBe(true);
|
|
207
|
+
// Everything that did land is still there — nothing pinned was thrown away.
|
|
208
|
+
expect(manifest.all().every((e) => e.pinned)).toBe(true);
|
|
209
|
+
});
|
|
210
|
+
});
|
|
211
|
+
|
|
212
|
+
describe('BlobCache reconcile', () => {
|
|
213
|
+
it('rebuilds manifest rows from disk when the local store was wiped', async () => {
|
|
214
|
+
const { cache, manifest, local } = setup();
|
|
215
|
+
await cache.read(KEY);
|
|
216
|
+
await cache.flush();
|
|
217
|
+
expect(local.rows.size).toBe(1);
|
|
218
|
+
|
|
219
|
+
// The SQLite leader wipe-on-pool-open / memory fallback / IndexedDB
|
|
220
|
+
// recovery case: metadata gone, bytes intact.
|
|
221
|
+
local.rows.clear();
|
|
222
|
+
manifest.reset();
|
|
223
|
+
await cache.reconcile();
|
|
224
|
+
|
|
225
|
+
expect(manifest.get(KEY)).toBeDefined();
|
|
226
|
+
expect(cache.stats().reconciledEntries).toBe(1);
|
|
227
|
+
});
|
|
228
|
+
|
|
229
|
+
it('serves reads from disk after a reconcile without going remote', async () => {
|
|
230
|
+
const { cache, manifest, local, fetchRemote } = setup();
|
|
231
|
+
await cache.read(KEY);
|
|
232
|
+
local.rows.clear();
|
|
233
|
+
manifest.reset();
|
|
234
|
+
await cache.reconcile();
|
|
235
|
+
|
|
236
|
+
await cache.read(KEY);
|
|
237
|
+
|
|
238
|
+
expect(fetchRemote).toHaveBeenCalledTimes(1);
|
|
239
|
+
});
|
|
240
|
+
|
|
241
|
+
it('survives a local store whose reads throw', async () => {
|
|
242
|
+
const { cache, manifest, local } = setup();
|
|
243
|
+
await cache.read(KEY);
|
|
244
|
+
manifest.reset();
|
|
245
|
+
local.failReads = true;
|
|
246
|
+
|
|
247
|
+
await cache.reconcile();
|
|
248
|
+
|
|
249
|
+
// Rebuilt purely from disk — a dead manifest must not cost the cached bytes.
|
|
250
|
+
expect(manifest.get(KEY)).toBeDefined();
|
|
251
|
+
});
|
|
252
|
+
});
|
|
253
|
+
|
|
254
|
+
describe('BlobCache object URLs', () => {
|
|
255
|
+
it('shares one URL between holders and revokes it once the hot window ages out', async () => {
|
|
256
|
+
const { cache, urls } = setup({ remote: async () => bytes(10) });
|
|
257
|
+
|
|
258
|
+
const a = await cache.acquireUrl(KEY);
|
|
259
|
+
const b = await cache.acquireUrl(KEY);
|
|
260
|
+
expect(a!.url).toBe(b!.url);
|
|
261
|
+
|
|
262
|
+
a!.release();
|
|
263
|
+
b!.release();
|
|
264
|
+
// Still warm: a re-mount must not pay for a new URL.
|
|
265
|
+
expect(urls.revoked).not.toContain(a!.url);
|
|
266
|
+
|
|
267
|
+
// Push it out of the 32-entry hot window.
|
|
268
|
+
for (let i = 0; i < 33; i++) {
|
|
269
|
+
const lease = await cache.acquireUrl({ bucket: 'files', path: `f${i}.bin` });
|
|
270
|
+
lease!.release();
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
expect(urls.revoked).toContain(a!.url);
|
|
274
|
+
});
|
|
275
|
+
|
|
276
|
+
it('release is idempotent', async () => {
|
|
277
|
+
const { cache, urls } = setup();
|
|
278
|
+
const lease = await cache.acquireUrl(KEY);
|
|
279
|
+
|
|
280
|
+
lease!.release();
|
|
281
|
+
lease!.release();
|
|
282
|
+
lease!.release();
|
|
283
|
+
|
|
284
|
+
// A double release must not push the refcount negative and free a URL that
|
|
285
|
+
// another component still holds.
|
|
286
|
+
const again = await cache.acquireUrl(KEY);
|
|
287
|
+
expect(urls.live.has(again!.url)).toBe(true);
|
|
288
|
+
});
|
|
289
|
+
});
|
|
290
|
+
|
|
291
|
+
describe('BlobCache namespaces', () => {
|
|
292
|
+
it('keeps each local bucket separate and leaves the old bucket warm', async () => {
|
|
293
|
+
const { cache, manifest, fetchRemote } = setup();
|
|
294
|
+
await cache.read(KEY);
|
|
295
|
+
|
|
296
|
+
await cache.setNamespace('user-2');
|
|
297
|
+
expect(manifest.get(KEY)).toBeUndefined();
|
|
298
|
+
await cache.read(KEY);
|
|
299
|
+
expect(fetchRemote).toHaveBeenCalledTimes(2);
|
|
300
|
+
|
|
301
|
+
// Signing back in finds the first user's bytes still there.
|
|
302
|
+
await cache.setNamespace('user-1');
|
|
303
|
+
await cache.read(KEY);
|
|
304
|
+
expect(fetchRemote).toHaveBeenCalledTimes(2);
|
|
305
|
+
});
|
|
306
|
+
|
|
307
|
+
it('a read issued before start() finishes waits for the reconcile', async () => {
|
|
308
|
+
// Boot fires start() without awaiting it (the OPFS walk must not delay the
|
|
309
|
+
// WebSocket connect). A read landing mid-walk must still see the rebuilt
|
|
310
|
+
// manifest rather than refetching a file that is already on disk.
|
|
311
|
+
const { cache, manifest, local, fetchRemote } = setup();
|
|
312
|
+
await cache.read(KEY);
|
|
313
|
+
await cache.flush();
|
|
314
|
+
local.rows.clear();
|
|
315
|
+
manifest.reset();
|
|
316
|
+
|
|
317
|
+
const starting = cache.start('user-1');
|
|
318
|
+
const readDuringStart = cache.read(KEY);
|
|
319
|
+
await Promise.all([starting, readDuringStart]);
|
|
320
|
+
|
|
321
|
+
expect(await readDuringStart).not.toBeNull();
|
|
322
|
+
expect(fetchRemote).toHaveBeenCalledTimes(1);
|
|
323
|
+
});
|
|
324
|
+
|
|
325
|
+
it('clear() drops the current namespace', async () => {
|
|
326
|
+
const { cache, store } = setup();
|
|
327
|
+
await cache.read(KEY);
|
|
328
|
+
|
|
329
|
+
await cache.clear();
|
|
330
|
+
|
|
331
|
+
expect(await store.list()).toHaveLength(0);
|
|
332
|
+
});
|
|
333
|
+
});
|
|
334
|
+
|
|
335
|
+
describe('BlobManifest write-back', () => {
|
|
336
|
+
it('batches access-time updates instead of writing per hit', async () => {
|
|
337
|
+
const { cache, local } = setup();
|
|
338
|
+
await cache.read(KEY);
|
|
339
|
+
await cache.flush();
|
|
340
|
+
const afterFirst = local.upserts;
|
|
341
|
+
|
|
342
|
+
for (let i = 0; i < 10; i++) await cache.read(KEY);
|
|
343
|
+
|
|
344
|
+
// Nothing flushed yet — the debounce has not fired and no one closed.
|
|
345
|
+
expect(local.upserts).toBe(afterFirst);
|
|
346
|
+
await cache.flush();
|
|
347
|
+
// Ten hits collapse into a single row write.
|
|
348
|
+
expect(local.upserts).toBe(afterFirst + 1);
|
|
349
|
+
});
|
|
350
|
+
|
|
351
|
+
it('close() flushes pending metadata', async () => {
|
|
352
|
+
const { cache, local } = setup();
|
|
353
|
+
await cache.read(KEY);
|
|
354
|
+
|
|
355
|
+
await cache.close();
|
|
356
|
+
|
|
357
|
+
expect(local.rows.get(blobKeyId(KEY))).toMatchObject({ bucket: KEY.bucket, path: KEY.path });
|
|
358
|
+
});
|
|
359
|
+
});
|