@spooky-sync/core 0.0.1-canary.33 → 0.0.1-canary.331
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 +84 -0
- package/README.md +56 -16
- package/dist/index.d.ts +2080 -142
- package/dist/index.js +16009 -2480
- package/dist/live.d.ts +149 -0
- package/dist/live.js +739 -0
- package/dist/otel/index.d.ts +1 -1
- package/dist/otel/index.js +3 -3
- package/dist/pure.d.ts +373 -0
- package/dist/pure.js +24 -0
- package/dist/sqlite-open.js +392 -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 +477 -0
- package/dist/types.d.ts +1857 -38
- package/dist/worker-edges.js +480 -0
- package/dist/worker-impersonation.js +60 -0
- package/dist/worker-ref-tables.d.ts +48 -0
- package/dist/worker-types.d.ts +112 -0
- package/dist/worker-types.js +73 -0
- package/package.json +28 -7
- package/scripts/check-broker-bundle.mjs +33 -0
- package/scripts/check-worker-entries.mjs +173 -0
- package/skills/sp00ky-core/SKILL.md +32 -7
- package/skills/sp00ky-core/references/config.md +7 -1
- package/src/boot/auth-flip.saga.test.ts +135 -0
- package/src/boot/auth-flip.saga.ts +77 -0
- package/src/boot/boot.saga.test.ts +203 -0
- package/src/boot/boot.saga.ts +146 -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 +80 -0
- package/src/boot/preload.saga.ts +40 -0
- package/src/bucket-blurhash.test.ts +148 -0
- package/src/build-globals.d.ts +12 -0
- package/src/client/bucket-handle.test.ts +195 -0
- package/src/client/bucket-handle.ts +352 -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.test.ts +74 -0
- package/src/client/services.ts +434 -0
- package/src/client/sp00ky-client.test.ts +341 -0
- package/src/client/sp00ky-client.ts +625 -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 +167 -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 +512 -0
- package/src/live/index.ts +1059 -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 +228 -0
- package/src/modules/auth/events/index.ts +9 -2
- package/src/modules/auth/impersonation-banner.ts +443 -0
- package/src/modules/auth/impersonation.integration.test.ts +205 -0
- package/src/modules/auth/impersonation.test.ts +377 -0
- package/src/modules/auth/impersonation.ts +179 -0
- package/src/modules/auth/index.ts +476 -22
- package/src/modules/crdt/acceptance.ts +75 -0
- package/src/modules/crdt/bytes.ts +50 -0
- package/src/modules/crdt/crdt-field.ts +125 -0
- package/src/modules/crdt/crdt.test.ts +469 -0
- package/src/modules/crdt/hash.ts +103 -0
- package/src/modules/crdt/index.ts +757 -0
- package/src/modules/crdt/loro-loader.ts +25 -0
- package/src/modules/crdt/mirror.ts +37 -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 +298 -0
- package/src/modules/feature-flag/index.ts +316 -0
- package/src/modules/ref-tables.test.ts +93 -0
- package/src/modules/ref-tables.ts +91 -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 +301 -0
- package/src/mutation/push.saga.ts +225 -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 +66 -0
- package/src/push/types.ts +174 -0
- package/src/query/anon-query-isolation.integration.test.ts +527 -0
- package/src/query/env.test.ts +23 -0
- package/src/query/env.ts +65 -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 +186 -0
- package/src/query/list-ref-live.integration.test.ts +203 -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 +407 -0
- package/src/query/membership.saga.ts +282 -0
- package/src/query/membership.test.ts +118 -0
- package/src/query/membership.ts +201 -0
- package/src/query/register.saga.test.ts +311 -0
- package/src/query/register.saga.ts +235 -0
- package/src/query/render-set.test.ts +47 -0
- package/src/query/render-set.ts +71 -0
- package/src/query/sql.test.ts +118 -0
- package/src/query/sql.ts +157 -0
- package/src/query/window-query.test.ts +70 -0
- package/src/query/window-query.ts +208 -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 +209 -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 +156 -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 +61 -16
- package/src/services/database/local.test.ts +150 -0
- package/src/services/database/local.ts +508 -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 +484 -0
- package/src/services/database/relation-resolver.ts +0 -0
- package/src/services/database/remote.ts +285 -6
- package/src/services/database/sqlite-cache-engine.test.ts +628 -0
- package/src/services/database/sqlite-cache-engine.timeout.test.ts +61 -0
- package/src/services/database/sqlite-cache-engine.ts +1401 -0
- package/src/services/database/sqlite-column-reset.integration.test.ts +100 -0
- package/src/services/database/sqlite-column-reset.ts +91 -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 +164 -0
- package/src/services/database/sqlite-plan-sql.ts +196 -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 +261 -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 +417 -0
- package/src/services/database/surreal-cache-engine.ts +163 -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 +806 -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 +234 -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 +284 -0
- package/src/services/tabs/broker.test.ts +381 -0
- package/src/services/tabs/coordinator.test.ts +386 -0
- package/src/services/tabs/coordinator.ts +646 -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 +652 -0
- package/src/sp00ky.ts +5 -395
- package/src/state/client-state.ts +208 -0
- package/src/state/lifecycle.test.ts +141 -0
- package/src/state/lifecycle.ts +99 -0
- package/src/state/reducers.test.ts +306 -0
- package/src/state/reducers.ts +531 -0
- package/src/state/selectors.test.ts +188 -0
- package/src/state/selectors.ts +258 -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 +97 -0
- package/src/sync/connection.saga.ts +89 -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 +663 -0
- package/src/sync/policy.ts +515 -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 +137 -0
- package/src/testing/build.ts +63 -0
- package/src/testing/fake-services.ts +63 -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 +633 -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 +89 -12
- 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 +29 -18
- package/src/utils/utils.test.ts +3 -2
- 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,282 @@
|
|
|
1
|
+
import type { QueryHash, RecordVersionArray, ServerViewMeta } from '../types';
|
|
2
|
+
import type { Saga } from '../kernel/saga';
|
|
3
|
+
import type { Settled, StatementResult } from '../kernel/effects';
|
|
4
|
+
import { fx } from '../kernel/effects';
|
|
5
|
+
import {
|
|
6
|
+
MATERIALIZING_REREAD_LADDER_MS,
|
|
7
|
+
MEMBERSHIP_COALESCE_MS,
|
|
8
|
+
VIEW_LOST_RETRY_BASE_MS,
|
|
9
|
+
VIEW_LOST_RETRY_MAX_MS,
|
|
10
|
+
backoffMs,
|
|
11
|
+
} from '../kernel/constants';
|
|
12
|
+
import type { ClientState, QueryEntry } from '../state/client-state';
|
|
13
|
+
import { isAuthoritative } from '../state/lifecycle';
|
|
14
|
+
import * as R from '../state/reducers';
|
|
15
|
+
import { encodeRecordId } from '../utils/index';
|
|
16
|
+
import { departedIds } from '../state/selectors';
|
|
17
|
+
import { forgetDeparted } from './lifecycle.saga';
|
|
18
|
+
import { planListRefPollChunks, recordVersionArraysEqual } from '../sync/policy';
|
|
19
|
+
import type { SagaEnv } from './env';
|
|
20
|
+
import { listRefTable } from './env';
|
|
21
|
+
import * as sql from './sql';
|
|
22
|
+
import {
|
|
23
|
+
FAILED,
|
|
24
|
+
decideMembershipOutcome,
|
|
25
|
+
snapshotFromSingle,
|
|
26
|
+
snapshotsFromBatch,
|
|
27
|
+
suspectHashes,
|
|
28
|
+
type ListRefSnapshot,
|
|
29
|
+
} from './membership';
|
|
30
|
+
|
|
31
|
+
type MembershipOutcome = 'applied' | 'ignored' | 'view-lost';
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Accept (or refuse) a server id-set for one query. The only writer of
|
|
35
|
+
* `remoteArray`, the `_00_view` row and the cold -> live transition.
|
|
36
|
+
*/
|
|
37
|
+
export function* applyMembership(
|
|
38
|
+
hash: QueryHash,
|
|
39
|
+
remoteArray: RecordVersionArray,
|
|
40
|
+
meta?: ServerViewMeta,
|
|
41
|
+
verifiedRemoval?: boolean
|
|
42
|
+
): Saga<MembershipOutcome> {
|
|
43
|
+
const entry = (yield fx.state.read((s) => s.queries.get(hash))) as QueryEntry | undefined;
|
|
44
|
+
if (!entry) return 'ignored';
|
|
45
|
+
if (meta) yield fx.state.update(R.setServerState(hash, meta.present ? meta.state : null));
|
|
46
|
+
// The row is there: whatever made it read as gone has passed.
|
|
47
|
+
if (meta?.present && (entry.viewLostCount > 0 || entry.viewLostRetryAt !== null)) {
|
|
48
|
+
yield fx.state.update(R.setViewLost(hash, 0, null));
|
|
49
|
+
}
|
|
50
|
+
const outcome = decideMembershipOutcome({
|
|
51
|
+
phase: entry.lifecycle.phase,
|
|
52
|
+
held: entry.remoteArray.length,
|
|
53
|
+
remoteArray,
|
|
54
|
+
meta,
|
|
55
|
+
verifiedRemoval,
|
|
56
|
+
});
|
|
57
|
+
if (outcome === 'ignored') return outcome;
|
|
58
|
+
if (outcome === 'view-lost') {
|
|
59
|
+
if (entry.lifecycle.phase !== 'view-lost') {
|
|
60
|
+
yield fx.state.update(R.applyLifecycle(hash, { type: 'row-missing' }));
|
|
61
|
+
yield fx.emit({ type: 'query:view-lost', hash });
|
|
62
|
+
}
|
|
63
|
+
// A recovery is already scheduled: every read in the meantime would
|
|
64
|
+
// otherwise re-register again.
|
|
65
|
+
if (entry.viewLostRetryAt !== null) return outcome;
|
|
66
|
+
if (entry.viewLostCount === 0) {
|
|
67
|
+
yield fx.state.update(R.setViewLost(hash, 1, null));
|
|
68
|
+
if (entry.lifecycle.remote !== 'unregistered') {
|
|
69
|
+
yield fx.state.update(R.applyLifecycle(hash, { type: 'remote-dropped' }));
|
|
70
|
+
}
|
|
71
|
+
yield fx.dispatch({ type: 'EnsureRegistered' });
|
|
72
|
+
return outcome;
|
|
73
|
+
}
|
|
74
|
+
// Re-registered already and the row still reads as gone. Under load that
|
|
75
|
+
// repeated every read, each one costing the server a registration while it
|
|
76
|
+
// was still publishing the last, so from here on it is paced.
|
|
77
|
+
const delay = backoffMs(entry.viewLostCount - 1, VIEW_LOST_RETRY_BASE_MS, VIEW_LOST_RETRY_MAX_MS);
|
|
78
|
+
const now = (yield fx.now()) as number;
|
|
79
|
+
yield fx.state.update(R.setViewLost(hash, entry.viewLostCount + 1, now + delay));
|
|
80
|
+
yield fx.emit({
|
|
81
|
+
type: 'log',
|
|
82
|
+
level: 'debug',
|
|
83
|
+
message: 'view still lost; re-registering after a delay',
|
|
84
|
+
data: { hash, attempt: entry.viewLostCount + 1, delayMs: delay },
|
|
85
|
+
});
|
|
86
|
+
yield fx.timer.set(`view-lost:${hash}`, delay, { type: 'RecoverLostView', hash });
|
|
87
|
+
return outcome;
|
|
88
|
+
}
|
|
89
|
+
const wasAuthoritative = isAuthoritative(entry.lifecycle);
|
|
90
|
+
yield fx.state.update(R.commitMembership(hash, remoteArray, meta?.present ?? true));
|
|
91
|
+
yield* forgetDeparted(hash, departedIds(entry.remoteArray, remoteArray));
|
|
92
|
+
if (!wasAuthoritative) yield fx.emit({ type: 'query:authority', hash, known: true });
|
|
93
|
+
const now = (yield fx.now()) as number;
|
|
94
|
+
try {
|
|
95
|
+
yield fx.local.upsert(
|
|
96
|
+
sql.VIEW_TABLE,
|
|
97
|
+
sql.viewRecordId(entry.def.viewKey),
|
|
98
|
+
sql.viewRow(remoteArray, entry.subqueryRemoteArray, true, now),
|
|
99
|
+
'replace'
|
|
100
|
+
);
|
|
101
|
+
} catch (err) {
|
|
102
|
+
yield fx.emit({ type: 'log', level: 'debug', message: 'view row write failed', data: { hash, err } });
|
|
103
|
+
}
|
|
104
|
+
yield fx.dispatch({ type: 'FetchRows' });
|
|
105
|
+
return outcome;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* The paced view-lost re-registration. A no-op when the row has been seen
|
|
110
|
+
* since (the pacing was reset) or the query recovered or went away.
|
|
111
|
+
*/
|
|
112
|
+
export function* recoverLostView(hash: QueryHash): Saga<void> {
|
|
113
|
+
const entry = (yield fx.state.read((s) => s.queries.get(hash))) as QueryEntry | undefined;
|
|
114
|
+
if (!entry || entry.viewLostRetryAt === null) return;
|
|
115
|
+
yield fx.state.update(R.setViewLost(hash, entry.viewLostCount, null));
|
|
116
|
+
if (entry.lifecycle.phase !== 'view-lost') return;
|
|
117
|
+
if (entry.lifecycle.remote !== 'unregistered') {
|
|
118
|
+
yield fx.state.update(R.applyLifecycle(hash, { type: 'remote-dropped' }));
|
|
119
|
+
}
|
|
120
|
+
yield fx.dispatch({ type: 'RegisterRemote', hash });
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/**
|
|
124
|
+
* Replace the subquery child set; bodies follow through the fetch plan. A
|
|
125
|
+
* query with a `_00_view` row (past `cold`) records the children there too,
|
|
126
|
+
* so the GC keeps their bodies and a cold scan may paint them.
|
|
127
|
+
*/
|
|
128
|
+
export function* applySubqueryChildren(hash: QueryHash, children: RecordVersionArray): Saga<void> {
|
|
129
|
+
const entry = (yield fx.state.read((s) => s.queries.get(hash))) as QueryEntry | undefined;
|
|
130
|
+
if (!entry || recordVersionArraysEqual(entry.subqueryRemoteArray, children)) return;
|
|
131
|
+
yield fx.state.update(R.setSubqueryRemoteArray(hash, children));
|
|
132
|
+
yield* forgetDeparted(hash, departedIds(entry.subqueryRemoteArray, children));
|
|
133
|
+
if (entry.lifecycle.phase !== 'cold') {
|
|
134
|
+
try {
|
|
135
|
+
yield fx.local.upsert(sql.VIEW_TABLE, sql.viewRecordId(entry.def.viewKey), { children }, 'merge');
|
|
136
|
+
} catch (err) {
|
|
137
|
+
yield fx.emit({ type: 'log', level: 'debug', message: 'view row write failed', data: { hash, err } });
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
yield fx.dispatch({ type: 'FetchRows' });
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
const ok = (r: Settled): r is { ok: true; value: unknown } => r.ok;
|
|
144
|
+
/** One statement's result, or `FAILED` when it did not answer (see `FAILED`). */
|
|
145
|
+
const stmt = (results: unknown, i: number): unknown => {
|
|
146
|
+
if (!Array.isArray(results)) return FAILED;
|
|
147
|
+
const r = (results as StatementResult[])[i];
|
|
148
|
+
return r && r.status === 'OK' ? r.result : FAILED;
|
|
149
|
+
};
|
|
150
|
+
|
|
151
|
+
/**
|
|
152
|
+
* Read the server membership of many queries in as few round trips as the
|
|
153
|
+
* row budget allows, then apply each changed set. This is the ONLY place a
|
|
154
|
+
* server id-set enters state: registration, the poll, LIVE dirt and view-lost
|
|
155
|
+
* recovery all come through here.
|
|
156
|
+
*/
|
|
157
|
+
export function* readMembership(
|
|
158
|
+
env: SagaEnv,
|
|
159
|
+
hashes: QueryHash[],
|
|
160
|
+
opts: { force?: boolean } = {}
|
|
161
|
+
): Saga<{ changed: boolean; failed: boolean }> {
|
|
162
|
+
const state = (yield fx.state.read((s) => s)) as ClientState;
|
|
163
|
+
const entries = hashes.map((h) => state.queries.get(h)).filter((e): e is QueryEntry => !!e);
|
|
164
|
+
if (entries.length === 0) return { changed: false, failed: false };
|
|
165
|
+
const table = listRefTable(env, state);
|
|
166
|
+
const now = (yield fx.now()) as number;
|
|
167
|
+
const chunks = planListRefPollChunks(
|
|
168
|
+
entries.map((e) => ({ hash: e.def.hash, rows: e.remoteArray.length, lastPolledAt: opts.force ? 0 : (e.lastPolledAt ?? 0) })),
|
|
169
|
+
{ now }
|
|
170
|
+
);
|
|
171
|
+
const byHash = new Map(entries.map((e) => [e.def.hash, e]));
|
|
172
|
+
const single = (e: QueryEntry) =>
|
|
173
|
+
fx.remote.query(sql.singleSnapshotSelect(table), { in: e.def.id }, env.remoteTimeoutMs);
|
|
174
|
+
const requests = chunks.map((chunk) =>
|
|
175
|
+
chunk.length === 1
|
|
176
|
+
? single(byHash.get(chunk[0])!)
|
|
177
|
+
: fx.remote.query(sql.batchSnapshotSelect(table), { ins: chunk.map((h) => byHash.get(h)!.def.id) }, env.remoteTimeoutMs)
|
|
178
|
+
);
|
|
179
|
+
const results = (yield fx.all(requests)) as Settled[];
|
|
180
|
+
|
|
181
|
+
const snapshots = new Map<QueryHash, ListRefSnapshot>();
|
|
182
|
+
let failed = false;
|
|
183
|
+
const rereads: QueryEntry[] = [];
|
|
184
|
+
chunks.forEach((chunk, i) => {
|
|
185
|
+
const r = results[i];
|
|
186
|
+
if (!ok(r)) {
|
|
187
|
+
failed = true;
|
|
188
|
+
return;
|
|
189
|
+
}
|
|
190
|
+
if (chunk.length === 1) {
|
|
191
|
+
const snap = snapshotFromSingle(stmt(r.value, 0) as never, stmt(r.value, 1) as never, stmt(r.value, 2) as never);
|
|
192
|
+
if (snap) snapshots.set(chunk[0], snap);
|
|
193
|
+
else failed = true;
|
|
194
|
+
return;
|
|
195
|
+
}
|
|
196
|
+
const hashById = new Map(chunk.map((h) => [encodeRecordId(byHash.get(h)!.def.id), h]));
|
|
197
|
+
const edges = stmt(r.value, 0) as never[] | null;
|
|
198
|
+
const counts = stmt(r.value, 1);
|
|
199
|
+
if (!Array.isArray(edges) || counts === FAILED) {
|
|
200
|
+
failed = true;
|
|
201
|
+
return;
|
|
202
|
+
}
|
|
203
|
+
const batch = snapshotsFromBatch(edges, counts as never, hashById);
|
|
204
|
+
const held = new Map(chunk.map((h) => [h, byHash.get(h)!.remoteArray.length]));
|
|
205
|
+
const suspect = new Set(suspectHashes(batch, held, edges.length));
|
|
206
|
+
for (const [h, snap] of batch) {
|
|
207
|
+
if (suspect.has(h)) rereads.push(byHash.get(h)!);
|
|
208
|
+
else snapshots.set(h, snap);
|
|
209
|
+
}
|
|
210
|
+
});
|
|
211
|
+
if (rereads.length > 0) {
|
|
212
|
+
const again = (yield fx.all(rereads.map(single))) as Settled[];
|
|
213
|
+
again.forEach((r, i) => {
|
|
214
|
+
if (!ok(r)) {
|
|
215
|
+
failed = true;
|
|
216
|
+
return;
|
|
217
|
+
}
|
|
218
|
+
const snap = snapshotFromSingle(stmt(r.value, 0) as never, stmt(r.value, 1) as never, stmt(r.value, 2) as never);
|
|
219
|
+
if (snap) snapshots.set(rereads[i].def.hash, snap);
|
|
220
|
+
else failed = true;
|
|
221
|
+
});
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
let changed = false;
|
|
225
|
+
const stillMaterializing: QueryHash[] = [];
|
|
226
|
+
for (const [hash, snap] of snapshots) {
|
|
227
|
+
const current = (yield fx.state.read((s) => s.queries.get(hash))) as QueryEntry | undefined;
|
|
228
|
+
if (!current) continue;
|
|
229
|
+
const metaChanged = current.serverState !== (snap.meta.present ? snap.meta.state : null);
|
|
230
|
+
if (!recordVersionArraysEqual(snap.primary, current.remoteArray) || metaChanged || current.lifecycle.phase === 'cold' || current.lifecycle.phase === 'cached') {
|
|
231
|
+
const outcome = yield* applyMembership(hash, snap.primary, snap.meta);
|
|
232
|
+
if (outcome === 'applied') changed = true;
|
|
233
|
+
if (outcome === 'ignored' && snap.meta.present && snap.meta.state === 'materializing') stillMaterializing.push(hash);
|
|
234
|
+
}
|
|
235
|
+
yield* applySubqueryChildren(hash, snap.subquery);
|
|
236
|
+
}
|
|
237
|
+
yield fx.state.update(R.compose(R.clearMembershipDirty([...snapshots.keys()]), R.stampPolled(snapshots.keys(), now)));
|
|
238
|
+
|
|
239
|
+
// A view whose edges are still in flight: re-read on a short ladder rather
|
|
240
|
+
// than waiting for a backed-off poll tick.
|
|
241
|
+
for (const hash of stillMaterializing) {
|
|
242
|
+
const attempt = (yield fx.state.read((s) => s.membershipReread.get(hash) ?? 0)) as number;
|
|
243
|
+
if (attempt >= MATERIALIZING_REREAD_LADDER_MS.length) {
|
|
244
|
+
yield fx.state.update(R.setMembershipReread(hash, null));
|
|
245
|
+
continue;
|
|
246
|
+
}
|
|
247
|
+
yield fx.state.update(R.compose(R.setMembershipReread(hash, attempt + 1), R.markMembershipDirty([hash])));
|
|
248
|
+
yield fx.timer.set('membership', MATERIALIZING_REREAD_LADDER_MS[attempt], { type: 'ReadDirtyMembership' });
|
|
249
|
+
}
|
|
250
|
+
for (const hash of snapshots.keys()) {
|
|
251
|
+
if (!stillMaterializing.includes(hash)) yield fx.state.update(R.setMembershipReread(hash, null));
|
|
252
|
+
}
|
|
253
|
+
yield fx.dispatch({ type: 'SyncOutcome', ok: !failed, error: failed ? 'membership read failed' : undefined });
|
|
254
|
+
return { changed, failed };
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/**
|
|
258
|
+
* LIVE handler: mark dirty and coalesce into one batched re-read.
|
|
259
|
+
*
|
|
260
|
+
* The window is armed ONCE per burst, when the dirty set goes from empty to
|
|
261
|
+
* non-empty. `timer.set` replaces a pending timer, so re-arming on every event
|
|
262
|
+
* would push the read out for as long as events keep arriving: on a busy
|
|
263
|
+
* `_00_list_ref` table (registrations, an import, another tab syncing) the
|
|
264
|
+
* events never stop for a whole 50 ms and the read simply never ran, leaving
|
|
265
|
+
* membership frozen until a poll tick happened to cover it.
|
|
266
|
+
*/
|
|
267
|
+
export function* markMembershipDirty(hashes: QueryHash[]): Saga<void> {
|
|
268
|
+
const armed = (yield fx.state.read((s) => s.membershipDirty.size > 0)) as boolean;
|
|
269
|
+
yield fx.state.update(R.markMembershipDirty(hashes));
|
|
270
|
+
if (!armed) yield fx.timer.set('membership', MEMBERSHIP_COALESCE_MS, { type: 'ReadDirtyMembership' });
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
export function* readDirtyMembership(env: SagaEnv): Saga<void> {
|
|
274
|
+
const dirty = (yield fx.state.read((s) => [...s.membershipDirty])) as QueryHash[];
|
|
275
|
+
if (dirty.length === 0) return;
|
|
276
|
+
yield* readMembership(env, dirty, { force: true });
|
|
277
|
+
// Dirt that arrived while the read was in flight, or a hash the read could
|
|
278
|
+
// not answer, holds the set non-empty - and with the window armed only on the
|
|
279
|
+
// empty -> non-empty edge, nothing else would arm it again.
|
|
280
|
+
const left = (yield fx.state.read((s) => s.membershipDirty.size)) as number;
|
|
281
|
+
if (left > 0) yield fx.timer.set('membership', MEMBERSHIP_COALESCE_MS, { type: 'ReadDirtyMembership' });
|
|
282
|
+
}
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest';
|
|
2
|
+
import { RecordId } from 'surrealdb';
|
|
3
|
+
import {
|
|
4
|
+
decideMembershipOutcome,
|
|
5
|
+
dedupeRecordVersions,
|
|
6
|
+
isResolvedBefore,
|
|
7
|
+
metaFromRow,
|
|
8
|
+
parseViewRow,
|
|
9
|
+
snapshotFromSingle,
|
|
10
|
+
snapshotsFromBatch,
|
|
11
|
+
suspectHashes,
|
|
12
|
+
} from './membership';
|
|
13
|
+
|
|
14
|
+
describe('durable view row', () => {
|
|
15
|
+
it('parses and gates resolved-before', () => {
|
|
16
|
+
expect(parseViewRow(null)).toBeNull();
|
|
17
|
+
expect(parseViewRow({ ids: 'nope' })).toBeNull();
|
|
18
|
+
expect(parseViewRow({ ids: [['t:1', 1]], confirmed: true })).toEqual({ ids: [['t:1', 1]], confirmed: true });
|
|
19
|
+
expect(parseViewRow({ ids: [] })).toEqual({ ids: [], confirmed: false });
|
|
20
|
+
expect(isResolvedBefore(null)).toBe(false);
|
|
21
|
+
expect(isResolvedBefore({ ids: [], confirmed: false })).toBe(false);
|
|
22
|
+
expect(isResolvedBefore({ ids: [], confirmed: true })).toBe(true);
|
|
23
|
+
expect(isResolvedBefore({ ids: [['t:1', 1]], confirmed: false })).toBe(true);
|
|
24
|
+
});
|
|
25
|
+
});
|
|
26
|
+
|
|
27
|
+
describe('metaFromRow / dedupe', () => {
|
|
28
|
+
it('folds the row-count select', () => {
|
|
29
|
+
expect(metaFromRow(null)).toEqual({ present: false, rowCount: null, state: null });
|
|
30
|
+
expect(metaFromRow({ rowCount: 3, state: 'ready' })).toEqual({ present: true, rowCount: 3, state: 'ready' });
|
|
31
|
+
expect(metaFromRow({ rowCount: null, state: 'weird' })).toEqual({ present: true, rowCount: null, state: null });
|
|
32
|
+
expect(metaFromRow({ state: 'materializing' })).toEqual({ present: true, rowCount: null, state: 'materializing' });
|
|
33
|
+
});
|
|
34
|
+
it('keeps the highest version per id', () => {
|
|
35
|
+
const single: [string, number][] = [['t:1', 1]];
|
|
36
|
+
expect(dedupeRecordVersions(single)).toBe(single);
|
|
37
|
+
const clean: [string, number][] = [['t:1', 1], ['t:2', 1]];
|
|
38
|
+
expect(dedupeRecordVersions(clean)).toBe(clean);
|
|
39
|
+
expect(dedupeRecordVersions([['t:1', 1], ['t:1', 3], ['t:1', 2]])).toEqual([['t:1', 3]]);
|
|
40
|
+
});
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
describe('decideMembershipOutcome', () => {
|
|
44
|
+
const ready0 = { present: true, rowCount: 0, state: 'ready' as const };
|
|
45
|
+
it('non-empty or verified removal is always applied', () => {
|
|
46
|
+
expect(decideMembershipOutcome({ phase: 'cold', held: 0, remoteArray: [['t:1', 1]] })).toBe('applied');
|
|
47
|
+
expect(decideMembershipOutcome({ phase: 'live', held: 2, remoteArray: [], verifiedRemoval: true })).toBe('applied');
|
|
48
|
+
});
|
|
49
|
+
it('empty with no readable row: view-lost when holding, ignored when cold and empty', () => {
|
|
50
|
+
expect(decideMembershipOutcome({ phase: 'cold', held: 0, remoteArray: [] })).toBe('ignored');
|
|
51
|
+
expect(decideMembershipOutcome({ phase: 'cold', held: 0, remoteArray: [], meta: { present: false, rowCount: null, state: null } })).toBe('ignored');
|
|
52
|
+
expect(decideMembershipOutcome({ phase: 'cold', held: 2, remoteArray: [] })).toBe('view-lost');
|
|
53
|
+
expect(decideMembershipOutcome({ phase: 'cached', held: 0, remoteArray: [] })).toBe('view-lost');
|
|
54
|
+
expect(decideMembershipOutcome({ phase: 'live', held: 1, remoteArray: [], meta: { present: false, rowCount: null, state: null } })).toBe('view-lost');
|
|
55
|
+
});
|
|
56
|
+
it('empty with a present row: applied only when ready and zero rows', () => {
|
|
57
|
+
expect(decideMembershipOutcome({ phase: 'cold', held: 0, remoteArray: [], meta: ready0 })).toBe('applied');
|
|
58
|
+
expect(decideMembershipOutcome({ phase: 'cold', held: 0, remoteArray: [], meta: { present: true, rowCount: 0, state: null } })).toBe('applied');
|
|
59
|
+
expect(decideMembershipOutcome({ phase: 'cold', held: 0, remoteArray: [], meta: { present: true, rowCount: 0, state: 'materializing' } })).toBe('ignored');
|
|
60
|
+
expect(decideMembershipOutcome({ phase: 'live', held: 3, remoteArray: [], meta: { present: true, rowCount: 3, state: 'ready' } })).toBe('ignored');
|
|
61
|
+
expect(decideMembershipOutcome({ phase: 'live', held: 3, remoteArray: [], meta: { present: true, rowCount: null, state: 'ready' } })).toBe('ignored');
|
|
62
|
+
});
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
describe('snapshots', () => {
|
|
66
|
+
const q1 = new RecordId('_00_query', 'a');
|
|
67
|
+
const q2 = new RecordId('_00_query', 'b');
|
|
68
|
+
const out = (id: string) => new RecordId('thing', id);
|
|
69
|
+
it('single: edges, meta, children; null when the primary select is not an array', () => {
|
|
70
|
+
expect(snapshotFromSingle(null, null, null)).toBeNull();
|
|
71
|
+
const snap = snapshotFromSingle(
|
|
72
|
+
[{ out: out('1'), version: 1 }, { out: out('1'), version: 2 }],
|
|
73
|
+
{ rowCount: 1, state: 'ready' },
|
|
74
|
+
[{ out: out('c'), version: 1 }]
|
|
75
|
+
);
|
|
76
|
+
expect(snap).toEqual({
|
|
77
|
+
primary: [['thing:1', 2]],
|
|
78
|
+
subquery: [['thing:c', 1]],
|
|
79
|
+
meta: { present: true, rowCount: 1, state: 'ready' },
|
|
80
|
+
});
|
|
81
|
+
expect(snapshotFromSingle([], null, null)!.subquery).toEqual([]);
|
|
82
|
+
});
|
|
83
|
+
it('batch: splits by hash and parent, fills meta, marks missing rows absent', () => {
|
|
84
|
+
const hashById = new Map([['_00_query:a', 'ha'], ['_00_query:b', 'hb']]);
|
|
85
|
+
expect(snapshotsFromBatch(null, null, hashById).size).toBe(0);
|
|
86
|
+
const snaps = snapshotsFromBatch(
|
|
87
|
+
[
|
|
88
|
+
{ in: q1, out: out('1'), version: 1 },
|
|
89
|
+
{ in: q1, out: out('1'), version: 1 },
|
|
90
|
+
{ in: q1, out: out('c'), version: 1, parent: q1 },
|
|
91
|
+
{ in: new RecordId('_00_query', 'zz'), out: out('9'), version: 1 },
|
|
92
|
+
],
|
|
93
|
+
[{ id: q1, rowCount: 1, state: 'ready' }, null, { rowCount: 5 }, { id: new RecordId('_00_query', 'zz') }],
|
|
94
|
+
hashById
|
|
95
|
+
);
|
|
96
|
+
expect(snaps.get('ha')).toEqual({
|
|
97
|
+
primary: [['thing:1', 1]],
|
|
98
|
+
subquery: [['thing:c', 1]],
|
|
99
|
+
meta: { present: true, rowCount: 1, state: 'ready' },
|
|
100
|
+
});
|
|
101
|
+
expect(snaps.get('hb')).toEqual({ primary: [], subquery: [], meta: { present: false, rowCount: null, state: null } });
|
|
102
|
+
expect(snapshotsFromBatch([], null, hashById).get('ha')!.meta.present).toBe(false);
|
|
103
|
+
});
|
|
104
|
+
it('suspectHashes flags held queries with a missing row or a silently empty batch', () => {
|
|
105
|
+
const snaps = new Map([
|
|
106
|
+
['missing', { primary: [], subquery: [], meta: { present: false, rowCount: null, state: null } }],
|
|
107
|
+
['empty', { primary: [], subquery: [], meta: { present: true, rowCount: 4, state: 'ready' as const } }],
|
|
108
|
+
['fine', { primary: [], subquery: [], meta: { present: true, rowCount: 0, state: 'ready' as const } }],
|
|
109
|
+
['unheld', { primary: [], subquery: [], meta: { present: false, rowCount: null, state: null } }],
|
|
110
|
+
]);
|
|
111
|
+
const held = new Map([['missing', 2], ['empty', 4], ['fine', 1], ['unheld', 0]]);
|
|
112
|
+
expect(suspectHashes(snaps, held, 0)).toEqual(['missing', 'empty']);
|
|
113
|
+
expect(suspectHashes(snaps, held, 1)).toEqual(['missing']);
|
|
114
|
+
const nullCount = new Map([['q', { primary: [], subquery: [], meta: { present: true, rowCount: null, state: 'ready' as const } }]]);
|
|
115
|
+
expect(suspectHashes(nullCount, new Map([['q', 3]]), 0)).toEqual([]);
|
|
116
|
+
expect(suspectHashes(nullCount, new Map(), 0)).toEqual([]);
|
|
117
|
+
});
|
|
118
|
+
});
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
import type { RecordId } from 'surrealdb';
|
|
2
|
+
import type { MembershipOutcome, RecordVersionArray, ServerViewMeta } from '../types';
|
|
3
|
+
import type { QueryPhase } from '../state/lifecycle';
|
|
4
|
+
import { encodeRecordId } from '../utils/index';
|
|
5
|
+
|
|
6
|
+
/** The durable `_00_view` row: the last server-confirmed membership. */
|
|
7
|
+
export interface DurableView {
|
|
8
|
+
ids: RecordVersionArray;
|
|
9
|
+
confirmed: boolean;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export function parseViewRow(row: unknown): DurableView | null {
|
|
13
|
+
if (!row || typeof row !== 'object') return null;
|
|
14
|
+
const ids = (row as { ids?: unknown }).ids;
|
|
15
|
+
if (!Array.isArray(ids)) return null;
|
|
16
|
+
return { ids: ids as RecordVersionArray, confirmed: (row as { confirmed?: unknown }).confirmed === true };
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** One `_00_view` row as the view index and the GC see it. */
|
|
20
|
+
export interface ViewIndexRow {
|
|
21
|
+
key: string;
|
|
22
|
+
/** Members and subquery children: what the row vouches for. */
|
|
23
|
+
ids: string[];
|
|
24
|
+
/** Last time a session resolved the query (0 when the row predates the field). */
|
|
25
|
+
updatedAt: number;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
const pairIds = (pairs: unknown): string[] =>
|
|
29
|
+
Array.isArray(pairs) ? pairs.filter((p): p is [string, number] => Array.isArray(p) && typeof p[0] === 'string').map((p) => p[0]) : [];
|
|
30
|
+
|
|
31
|
+
/** `SELECT * FROM _00_view` rows, keyed by view key; junk rows are skipped. */
|
|
32
|
+
export function parseViewIndex(rows: unknown): ViewIndexRow[] {
|
|
33
|
+
if (!Array.isArray(rows)) return [];
|
|
34
|
+
const out: ViewIndexRow[] = [];
|
|
35
|
+
for (const row of rows as Array<Record<string, unknown> | null>) {
|
|
36
|
+
if (!row || typeof row !== 'object' || !Array.isArray(row.ids)) continue;
|
|
37
|
+
const id = row.id;
|
|
38
|
+
const key = typeof id === 'string' ? id.slice(id.indexOf(':') + 1) : String((id as { id?: unknown } | undefined)?.id ?? '');
|
|
39
|
+
if (!key) continue;
|
|
40
|
+
out.push({
|
|
41
|
+
key,
|
|
42
|
+
ids: [...new Set([...pairIds(row.ids), ...pairIds(row.children)])],
|
|
43
|
+
updatedAt: typeof row.updatedAt === 'number' ? row.updatedAt : 0,
|
|
44
|
+
});
|
|
45
|
+
}
|
|
46
|
+
return out;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* "Resolved before": the server answered this query on this device at some
|
|
51
|
+
* point. An unconfirmed empty row cannot be told apart from one written before
|
|
52
|
+
* the marker existed, so it does not count.
|
|
53
|
+
*/
|
|
54
|
+
export const isResolvedBefore = (view: DurableView | null): boolean =>
|
|
55
|
+
view !== null && (view.ids.length > 0 || view.confirmed);
|
|
56
|
+
|
|
57
|
+
/** The `{ rowCount, state }` object the row-count selects return per row. */
|
|
58
|
+
export interface QueryMetaRow {
|
|
59
|
+
id?: RecordId<string>;
|
|
60
|
+
rowCount?: number | null;
|
|
61
|
+
state?: string | null;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export function metaFromRow(row: QueryMetaRow | null | undefined): ServerViewMeta {
|
|
65
|
+
if (!row || typeof row !== 'object') return { present: false, rowCount: null, state: null };
|
|
66
|
+
const state = row.state === 'materializing' || row.state === 'ready' ? row.state : null;
|
|
67
|
+
return { present: true, rowCount: typeof row.rowCount === 'number' ? row.rowCount : null, state };
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** Collapse duplicate `(id, version)` pairs to one per id, keeping the highest version. */
|
|
71
|
+
export function dedupeRecordVersions(pairs: RecordVersionArray): RecordVersionArray {
|
|
72
|
+
if (pairs.length < 2) return pairs;
|
|
73
|
+
const best = new Map<string, number>();
|
|
74
|
+
for (const [id, version] of pairs) {
|
|
75
|
+
const prev = best.get(id);
|
|
76
|
+
if (prev === undefined || version > prev) best.set(id, version);
|
|
77
|
+
}
|
|
78
|
+
if (best.size === pairs.length) return pairs;
|
|
79
|
+
return Array.from(best.entries());
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export interface MembershipDecisionInput {
|
|
83
|
+
phase: QueryPhase;
|
|
84
|
+
/** Number of ids currently held as membership. */
|
|
85
|
+
held: number;
|
|
86
|
+
remoteArray: RecordVersionArray;
|
|
87
|
+
meta?: ServerViewMeta;
|
|
88
|
+
verifiedRemoval?: boolean;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* Whether a server id-set may be applied. A NON-EMPTY set is always the
|
|
93
|
+
* server's answer. An EMPTY set is believed only when the server stands
|
|
94
|
+
* behind it: the `_00_query` row is present, `ready` (or pre-`state`), and
|
|
95
|
+
* reports zero rows. A missing row while we hold membership is a lost view.
|
|
96
|
+
*/
|
|
97
|
+
export function decideMembershipOutcome(input: MembershipDecisionInput): MembershipOutcome {
|
|
98
|
+
const { phase, held, remoteArray, meta, verifiedRemoval } = input;
|
|
99
|
+
if (remoteArray.length > 0 || verifiedRemoval) return 'applied';
|
|
100
|
+
if (!meta || !meta.present) {
|
|
101
|
+
return held > 0 || phase !== 'cold' ? 'view-lost' : 'ignored';
|
|
102
|
+
}
|
|
103
|
+
const knownEmpty = meta.rowCount === 0 && meta.state !== 'materializing';
|
|
104
|
+
return knownEmpty ? 'applied' : 'ignored';
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
// ---- list_ref snapshots ------------------------------------------------------
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* A statement that did not answer (an ERR, or no result at all). Kept apart
|
|
111
|
+
* from a `null` result, which is the server saying "no such row": reading a
|
|
112
|
+
* failed statement as a missing row turned every timeout under load into a
|
|
113
|
+
* lost view and re-registered it, over and over (whitepawn, 2026-09-16).
|
|
114
|
+
*/
|
|
115
|
+
export const FAILED: unique symbol = Symbol('statement failed');
|
|
116
|
+
export type Answer<T> = T | null | typeof FAILED;
|
|
117
|
+
|
|
118
|
+
export interface ListRefEdgeRow {
|
|
119
|
+
in: RecordId<string>;
|
|
120
|
+
out: RecordId<string>;
|
|
121
|
+
version: number;
|
|
122
|
+
parent?: unknown;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
export interface ListRefSnapshot {
|
|
126
|
+
primary: RecordVersionArray;
|
|
127
|
+
subquery: RecordVersionArray;
|
|
128
|
+
meta: ServerViewMeta;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
const toPairs = (rows: Array<{ out: RecordId<string>; version: number }> | null | undefined): RecordVersionArray =>
|
|
132
|
+
dedupeRecordVersions(Array.isArray(rows) ? rows.map((r) => [encodeRecordId(r.out), r.version]) : []);
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* Fold the single-query statement batch (edges, meta, children) into a
|
|
136
|
+
* snapshot. `null` when any of the three did not answer: half an answer is
|
|
137
|
+
* not one, and a missing meta would read as a lost view.
|
|
138
|
+
*/
|
|
139
|
+
export function snapshotFromSingle(
|
|
140
|
+
items: Answer<Array<{ out: RecordId<string>; version: number }>>,
|
|
141
|
+
metaRow: Answer<QueryMetaRow>,
|
|
142
|
+
children: Answer<Array<{ out: RecordId<string>; version: number }>>
|
|
143
|
+
): ListRefSnapshot | null {
|
|
144
|
+
if (!Array.isArray(items) || metaRow === FAILED || children === FAILED) return null;
|
|
145
|
+
return { primary: toPairs(items), subquery: toPairs(children), meta: metaFromRow(metaRow) };
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/**
|
|
149
|
+
* Fold the many-query statement batch into one snapshot per hash. Every hash
|
|
150
|
+
* in `hashById` gets a snapshot; a query whose row did not come back reads
|
|
151
|
+
* `present: false`. Empty when either statement did not answer.
|
|
152
|
+
*/
|
|
153
|
+
export function snapshotsFromBatch(
|
|
154
|
+
edges: Answer<ListRefEdgeRow[]>,
|
|
155
|
+
counts: Answer<Array<QueryMetaRow | null>>,
|
|
156
|
+
hashById: ReadonlyMap<string, string>
|
|
157
|
+
): Map<string, ListRefSnapshot> {
|
|
158
|
+
const out = new Map<string, ListRefSnapshot>();
|
|
159
|
+
if (!Array.isArray(edges) || counts === FAILED) return out;
|
|
160
|
+
for (const hash of hashById.values()) {
|
|
161
|
+
out.set(hash, { primary: [], subquery: [], meta: { present: false, rowCount: null, state: null } });
|
|
162
|
+
}
|
|
163
|
+
for (const row of edges) {
|
|
164
|
+
const hash = hashById.get(encodeRecordId(row.in));
|
|
165
|
+
if (!hash) continue;
|
|
166
|
+
const snapshot = out.get(hash)!;
|
|
167
|
+
const pair: [string, number] = [encodeRecordId(row.out), row.version];
|
|
168
|
+
if (row.parent == null) snapshot.primary.push(pair);
|
|
169
|
+
else snapshot.subquery.push(pair);
|
|
170
|
+
}
|
|
171
|
+
for (const snapshot of out.values()) {
|
|
172
|
+
snapshot.primary = dedupeRecordVersions(snapshot.primary);
|
|
173
|
+
snapshot.subquery = dedupeRecordVersions(snapshot.subquery);
|
|
174
|
+
}
|
|
175
|
+
for (const count of Array.isArray(counts) ? counts : []) {
|
|
176
|
+
if (!count || !count.id) continue;
|
|
177
|
+
const hash = hashById.get(encodeRecordId(count.id));
|
|
178
|
+
if (!hash) continue;
|
|
179
|
+
out.get(hash)!.meta = metaFromRow(count);
|
|
180
|
+
}
|
|
181
|
+
return out;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/**
|
|
185
|
+
* A batch that must not be believed at face value: a query we hold rows for
|
|
186
|
+
* whose `_00_query` row did not come back, or no edge at all while the server
|
|
187
|
+
* still reports rows for a held query. Such hashes are re-read one at a time.
|
|
188
|
+
*/
|
|
189
|
+
export function suspectHashes(
|
|
190
|
+
snapshots: ReadonlyMap<string, ListRefSnapshot>,
|
|
191
|
+
heldCounts: ReadonlyMap<string, number>,
|
|
192
|
+
edgeCount: number
|
|
193
|
+
): string[] {
|
|
194
|
+
const out: string[] = [];
|
|
195
|
+
for (const [hash, snapshot] of snapshots) {
|
|
196
|
+
const held = heldCounts.get(hash) ?? 0;
|
|
197
|
+
if (held === 0) continue;
|
|
198
|
+
if (!snapshot.meta.present || (edgeCount === 0 && (snapshot.meta.rowCount ?? 0) > 0)) out.push(hash);
|
|
199
|
+
}
|
|
200
|
+
return out;
|
|
201
|
+
}
|