@spooky-sync/core 0.0.1-canary.240 → 0.0.1-canary.241
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 +34 -15
- package/README.md +56 -16
- package/dist/index.d.ts +1136 -1846
- package/dist/index.js +10168 -11267
- package/dist/types.d.ts +22 -79
- package/package.json +8 -4
- package/skills/sp00ky-core/SKILL.md +18 -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 +151 -0
- package/src/boot/boot.saga.ts +128 -0
- package/src/boot/bucket-switch.saga.test.ts +158 -0
- package/src/boot/bucket-switch.saga.ts +115 -0
- package/src/boot/preload.saga.test.ts +51 -0
- package/src/boot/preload.saga.ts +31 -0
- package/src/client/bucket-handle.test.ts +117 -0
- package/src/client/bucket-handle.ts +227 -0
- package/src/client/router.test.ts +56 -0
- package/src/client/router.ts +94 -0
- package/src/client/runtime.test.ts +192 -0
- package/src/client/runtime.ts +296 -0
- package/src/client/services.ts +349 -0
- package/src/client/sp00ky-client.test.ts +241 -0
- package/src/client/sp00ky-client.ts +482 -0
- package/src/index.ts +1 -0
- package/src/kernel/constants.test.ts +19 -0
- package/src/kernel/constants.ts +54 -0
- package/src/kernel/effects.test.ts +40 -0
- package/src/kernel/effects.ts +159 -0
- package/src/kernel/events.ts +55 -0
- package/src/kernel/interpreter.test.ts +116 -0
- package/src/kernel/interpreter.ts +143 -0
- package/src/kernel/saga.test.ts +89 -0
- package/src/kernel/saga.ts +73 -0
- package/src/modules/app-release/index.ts +13 -5
- package/src/modules/devtools/index.ts +10 -3
- package/src/modules/devtools/state-shape.test.ts +4 -1
- package/src/modules/feature-flag/index.ts +13 -5
- package/src/mutation/jobs.test.ts +25 -0
- package/src/mutation/jobs.ts +41 -0
- package/src/{modules/data → mutation}/mutation-id.test.ts +12 -0
- package/src/mutation/push.saga.test.ts +285 -0
- package/src/mutation/push.saga.ts +215 -0
- package/src/mutation/rows.test.ts +201 -0
- package/src/mutation/rows.ts +377 -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 +163 -0
- package/src/mutation/write.saga.ts +166 -0
- package/src/query/env.test.ts +23 -0
- package/src/query/env.ts +56 -0
- package/src/query/fetch.saga.test.ts +156 -0
- package/src/query/fetch.saga.ts +109 -0
- package/src/query/hash.test.ts +14 -0
- package/src/query/hash.ts +18 -0
- package/src/{modules/data → query}/id-set-plan.test.ts +12 -2
- package/src/query/lifecycle.saga.test.ts +122 -0
- package/src/query/lifecycle.saga.ts +101 -0
- package/src/query/materialize.saga.test.ts +82 -0
- package/src/query/materialize.saga.ts +75 -0
- package/src/query/materialize.test.ts +50 -0
- package/src/query/materialize.ts +44 -0
- package/src/query/membership.saga.test.ts +246 -0
- package/src/query/membership.saga.ts +208 -0
- package/src/query/membership.test.ts +118 -0
- package/src/query/membership.ts +158 -0
- package/src/query/register.saga.test.ts +251 -0
- package/src/query/register.saga.ts +190 -0
- package/src/query/render-set.test.ts +36 -0
- package/src/query/render-set.ts +60 -0
- package/src/query/sql.test.ts +62 -0
- package/src/query/sql.ts +79 -0
- package/src/{modules/data → query}/window-query.test.ts +18 -0
- package/src/{modules/data → query}/window-query.ts +2 -1
- package/src/services/database/connection-supervisor.test.ts +29 -0
- package/src/services/database/connection-supervisor.ts +7 -0
- package/src/services/database/database.responses.test.ts +43 -0
- package/src/services/database/database.ts +25 -10
- package/src/services/database/local-migrator.ts +2 -2
- package/src/services/database/plan-render.test.ts +1 -1
- package/src/services/database/sqlite-cache-engine.test.ts +4 -3
- package/src/services/database/sqlite-cache-engine.ts +2 -11
- package/src/services/database/sqlite-devtools-queries.integration.test.ts +1 -1
- package/src/services/tabs/protocol.ts +7 -3
- package/src/sp00ky.ts +5 -1854
- package/src/state/client-state.ts +184 -0
- package/src/state/lifecycle.test.ts +118 -0
- package/src/state/lifecycle.ts +86 -0
- package/src/state/reducers.test.ts +280 -0
- package/src/state/reducers.ts +476 -0
- package/src/state/selectors.test.ts +149 -0
- package/src/state/selectors.ts +184 -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 +69 -0
- package/src/sync/live.saga.ts +49 -0
- package/src/sync/policy.health.test.ts +56 -0
- package/src/{modules/sync/utils.test.ts → sync/policy.test.ts} +31 -3
- package/src/{modules/sync/utils.ts → sync/policy.ts} +67 -5
- package/src/sync/poll.saga.test.ts +51 -0
- package/src/sync/poll.saga.ts +36 -0
- package/src/sync/tabs.saga.test.ts +74 -0
- package/src/sync/tabs.saga.ts +92 -0
- package/src/testing/adapters.ts +133 -0
- package/src/testing/build.ts +61 -0
- package/src/testing/fake-services.ts +34 -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 +8 -7
- package/src/utils/utils.test.ts +2 -1
- package/vitest.config.ts +48 -0
- package/coverage/lcov-report/base.css +0 -224
- package/coverage/lcov-report/block-navigation.js +0 -87
- package/coverage/lcov-report/favicon.png +0 -0
- package/coverage/lcov-report/index.html +0 -476
- package/coverage/lcov-report/prettify.css +0 -1
- package/coverage/lcov-report/prettify.js +0 -2
- package/coverage/lcov-report/sort-arrow-sprite.png +0 -0
- package/coverage/lcov-report/sorter.js +0 -210
- package/coverage/lcov-report/src/boot/auth-flip.saga.ts.html +0 -271
- package/coverage/lcov-report/src/boot/boot.saga.ts.html +0 -469
- package/coverage/lcov-report/src/boot/bucket-switch.saga.ts.html +0 -430
- package/coverage/lcov-report/src/boot/index.html +0 -161
- package/coverage/lcov-report/src/boot/preload.saga.ts.html +0 -178
- package/coverage/lcov-report/src/client/bucket-handle.ts.html +0 -766
- package/coverage/lcov-report/src/client/index.html +0 -161
- package/coverage/lcov-report/src/client/router.ts.html +0 -367
- package/coverage/lcov-report/src/client/runtime.ts.html +0 -940
- package/coverage/lcov-report/src/client/sp00ky-client.ts.html +0 -1531
- package/coverage/lcov-report/src/events/index.html +0 -116
- package/coverage/lcov-report/src/events/index.ts.html +0 -877
- package/coverage/lcov-report/src/index.html +0 -146
- package/coverage/lcov-report/src/index.ts.html +0 -202
- package/coverage/lcov-report/src/kernel/constants.ts.html +0 -247
- package/coverage/lcov-report/src/kernel/effects.ts.html +0 -562
- package/coverage/lcov-report/src/kernel/events.ts.html +0 -250
- package/coverage/lcov-report/src/kernel/index.html +0 -176
- package/coverage/lcov-report/src/kernel/interpreter.ts.html +0 -514
- package/coverage/lcov-report/src/kernel/saga.ts.html +0 -304
- package/coverage/lcov-report/src/modules/app-release/index.html +0 -116
- package/coverage/lcov-report/src/modules/app-release/index.ts.html +0 -712
- package/coverage/lcov-report/src/modules/auth/events/index.html +0 -116
- package/coverage/lcov-report/src/modules/auth/events/index.ts.html +0 -142
- package/coverage/lcov-report/src/modules/auth/index.html +0 -116
- package/coverage/lcov-report/src/modules/auth/index.ts.html +0 -1225
- package/coverage/lcov-report/src/modules/crdt/crdt-field.ts.html +0 -967
- package/coverage/lcov-report/src/modules/crdt/index.html +0 -146
- package/coverage/lcov-report/src/modules/crdt/index.ts.html +0 -1474
- package/coverage/lcov-report/src/modules/crdt/loro-loader.ts.html +0 -160
- package/coverage/lcov-report/src/modules/devtools/flags.ts.html +0 -1132
- package/coverage/lcov-report/src/modules/devtools/index.html +0 -161
- package/coverage/lcov-report/src/modules/devtools/index.ts.html +0 -2413
- package/coverage/lcov-report/src/modules/devtools/storage-info.ts.html +0 -589
- package/coverage/lcov-report/src/modules/devtools/versions.ts.html +0 -415
- package/coverage/lcov-report/src/modules/feature-flag/index.html +0 -116
- package/coverage/lcov-report/src/modules/feature-flag/index.ts.html +0 -1033
- package/coverage/lcov-report/src/modules/index.html +0 -116
- package/coverage/lcov-report/src/modules/ref-tables.ts.html +0 -349
- package/coverage/lcov-report/src/mutation/index.html +0 -191
- package/coverage/lcov-report/src/mutation/jobs.ts.html +0 -208
- package/coverage/lcov-report/src/mutation/mutation-id.ts.html +0 -190
- package/coverage/lcov-report/src/mutation/push.saga.ts.html +0 -730
- package/coverage/lcov-report/src/mutation/rows.ts.html +0 -1216
- package/coverage/lcov-report/src/mutation/tray.saga.ts.html +0 -229
- package/coverage/lcov-report/src/mutation/write.saga.ts.html +0 -583
- package/coverage/lcov-report/src/otel/index.html +0 -116
- package/coverage/lcov-report/src/otel/index.ts.html +0 -466
- package/coverage/lcov-report/src/query/env.ts.html +0 -253
- package/coverage/lcov-report/src/query/fetch.saga.ts.html +0 -412
- package/coverage/lcov-report/src/query/hash.ts.html +0 -139
- package/coverage/lcov-report/src/query/index.html +0 -281
- package/coverage/lcov-report/src/query/lifecycle.saga.ts.html +0 -388
- package/coverage/lcov-report/src/query/materialize.saga.ts.html +0 -310
- package/coverage/lcov-report/src/query/materialize.ts.html +0 -217
- package/coverage/lcov-report/src/query/membership.saga.ts.html +0 -709
- package/coverage/lcov-report/src/query/membership.ts.html +0 -559
- package/coverage/lcov-report/src/query/register.saga.ts.html +0 -655
- package/coverage/lcov-report/src/query/render-set.ts.html +0 -265
- package/coverage/lcov-report/src/query/sql.ts.html +0 -322
- package/coverage/lcov-report/src/query/window-query.ts.html +0 -670
- package/coverage/lcov-report/src/services/blobs/blob-cache.ts.html +0 -1894
- package/coverage/lcov-report/src/services/blobs/blob-manifest.ts.html +0 -766
- package/coverage/lcov-report/src/services/blobs/blob-store.ts.html +0 -1162
- package/coverage/lcov-report/src/services/blobs/index.html +0 -161
- package/coverage/lcov-report/src/services/blobs/index.ts.html +0 -295
- package/coverage/lcov-report/src/services/database/cache-engine.ts.html +0 -664
- package/coverage/lcov-report/src/services/database/connection-supervisor.ts.html +0 -1330
- package/coverage/lcov-report/src/services/database/database.ts.html +0 -658
- package/coverage/lcov-report/src/services/database/engine-factory.ts.html +0 -184
- package/coverage/lcov-report/src/services/database/errors.ts.html +0 -187
- package/coverage/lcov-report/src/services/database/events/index.html +0 -116
- package/coverage/lcov-report/src/services/database/events/index.ts.html +0 -184
- package/coverage/lcov-report/src/services/database/index.html +0 -386
- package/coverage/lcov-report/src/services/database/index.ts.html +0 -121
- package/coverage/lcov-report/src/services/database/local-migrator.ts.html +0 -703
- package/coverage/lcov-report/src/services/database/local.ts.html +0 -1633
- package/coverage/lcov-report/src/services/database/plan-render.ts.html +0 -409
- package/coverage/lcov-report/src/services/database/relation-resolver.ts.html +0 -682
- package/coverage/lcov-report/src/services/database/remote.ts.html +0 -1036
- package/coverage/lcov-report/src/services/database/sqlite-cache-engine.ts.html +0 -4132
- package/coverage/lcov-report/src/services/database/sqlite-lock-verify.ts.html +0 -220
- package/coverage/lcov-report/src/services/database/sqlite-open.ts.html +0 -577
- package/coverage/lcov-report/src/services/database/sqlite-plan-sql.ts.html +0 -499
- package/coverage/lcov-report/src/services/database/sqlite-select.ts.html +0 -478
- package/coverage/lcov-report/src/services/database/sqlite-transport.ts.html +0 -757
- package/coverage/lcov-report/src/services/database/surql-translate.ts.html +0 -1333
- package/coverage/lcov-report/src/services/database/surreal-cache-engine.ts.html +0 -568
- package/coverage/lcov-report/src/services/logger/index.html +0 -116
- package/coverage/lcov-report/src/services/logger/index.ts.html +0 -154
- package/coverage/lcov-report/src/services/persistence/index.html +0 -146
- package/coverage/lcov-report/src/services/persistence/localstorage.ts.html +0 -163
- package/coverage/lcov-report/src/services/persistence/resilient.ts.html +0 -208
- package/coverage/lcov-report/src/services/persistence/surrealdb.ts.html +0 -271
- package/coverage/lcov-report/src/services/stream-processor/index.html +0 -146
- package/coverage/lcov-report/src/services/stream-processor/index.ts.html +0 -3313
- package/coverage/lcov-report/src/services/stream-processor/permissions.ts.html +0 -244
- package/coverage/lcov-report/src/services/stream-processor/wasm-types.ts.html +0 -346
- package/coverage/lcov-report/src/services/tabs/broker-client.ts.html +0 -934
- package/coverage/lcov-report/src/services/tabs/coordinator.ts.html +0 -1984
- package/coverage/lcov-report/src/services/tabs/index.html +0 -191
- package/coverage/lcov-report/src/services/tabs/leader-locks.ts.html +0 -310
- package/coverage/lcov-report/src/services/tabs/protocol.ts.html +0 -871
- package/coverage/lcov-report/src/services/tabs/support.ts.html +0 -193
- package/coverage/lcov-report/src/services/tabs/tabs-broker-worker.ts.html +0 -2005
- package/coverage/lcov-report/src/sp00ky.ts.html +0 -100
- package/coverage/lcov-report/src/state/client-state.ts.html +0 -637
- package/coverage/lcov-report/src/state/index.html +0 -161
- package/coverage/lcov-report/src/state/lifecycle.ts.html +0 -343
- package/coverage/lcov-report/src/state/reducers.ts.html +0 -1471
- package/coverage/lcov-report/src/state/selectors.ts.html +0 -637
- package/coverage/lcov-report/src/sync/connection.saga.ts.html +0 -343
- package/coverage/lcov-report/src/sync/index.html +0 -176
- package/coverage/lcov-report/src/sync/live.saga.ts.html +0 -232
- package/coverage/lcov-report/src/sync/policy.ts.html +0 -1606
- package/coverage/lcov-report/src/sync/poll.saga.ts.html +0 -193
- package/coverage/lcov-report/src/sync/tabs.saga.ts.html +0 -361
- package/coverage/lcov-report/src/types.ts.html +0 -2419
- package/coverage/lcov-report/src/utils/blurhash.ts.html +0 -355
- package/coverage/lcov-report/src/utils/error-classification.ts.html +0 -244
- package/coverage/lcov-report/src/utils/index.html +0 -191
- package/coverage/lcov-report/src/utils/index.ts.html +0 -820
- package/coverage/lcov-report/src/utils/parser.ts.html +0 -313
- package/coverage/lcov-report/src/utils/semver.ts.html +0 -175
- package/coverage/lcov-report/src/utils/surql.ts.html +0 -667
- package/coverage/lcov.info +0 -19079
- package/src/modules/cache/cache.relay.test.ts +0 -95
- package/src/modules/cache/index.ts +0 -361
- package/src/modules/cache/types.ts +0 -19
- package/src/modules/data/data.activity.test.ts +0 -109
- package/src/modules/data/data.authority.test.ts +0 -122
- package/src/modules/data/data.heartbeat-wake.test.ts +0 -115
- package/src/modules/data/data.hydration.test.ts +0 -142
- package/src/modules/data/data.membership.test.ts +0 -623
- package/src/modules/data/data.notify-table.test.ts +0 -41
- package/src/modules/data/data.pending-ids.test.ts +0 -199
- package/src/modules/data/data.rebind.test.ts +0 -170
- package/src/modules/data/data.rematerialize.test.ts +0 -114
- package/src/modules/data/data.run.test.ts +0 -113
- package/src/modules/data/data.settled-writes.test.ts +0 -235
- package/src/modules/data/data.status.test.ts +0 -249
- package/src/modules/data/data.test.ts +0 -58
- package/src/modules/data/index.ts +0 -2745
- package/src/modules/sync/engine.ts +0 -250
- package/src/modules/sync/events/index.ts +0 -84
- package/src/modules/sync/index.ts +0 -3
- package/src/modules/sync/queue/index.ts +0 -2
- package/src/modules/sync/queue/queue-down.test.ts +0 -228
- package/src/modules/sync/queue/queue-down.ts +0 -184
- package/src/modules/sync/queue/queue-up.forwarded.test.ts +0 -164
- package/src/modules/sync/queue/queue-up.ts +0 -407
- package/src/modules/sync/scheduler.pause.test.ts +0 -109
- package/src/modules/sync/scheduler.retry.test.ts +0 -237
- package/src/modules/sync/scheduler.ts +0 -286
- package/src/modules/sync/sync.cleanup.test.ts +0 -116
- package/src/modules/sync/sync.health.test.ts +0 -167
- package/src/modules/sync/sync.heartbeat.test.ts +0 -80
- package/src/modules/sync/sync.list-ref-meta.test.ts +0 -193
- package/src/modules/sync/sync.live-removal.test.ts +0 -289
- package/src/modules/sync/sync.reconnect.test.ts +0 -145
- package/src/modules/sync/sync.rematerialize-after-fetch.test.ts +0 -93
- package/src/modules/sync/sync.settled-poll.test.ts +0 -58
- package/src/modules/sync/sync.subquery.test.ts +0 -82
- package/src/modules/sync/sync.tabs.test.ts +0 -249
- package/src/modules/sync/sync.ts +0 -2626
- package/src/sp00ky.auth-order.test.ts +0 -112
- package/src/sp00ky.init-query.test.ts +0 -183
- package/src/sp00ky.local-first.test.ts +0 -60
- /package/src/{modules/data → mutation}/mutation-id.ts +0 -0
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
import type { PhaseStat, QueryHash, QueryState, QueryStatus, QueryTimings, RecordVersionArray } from '../types';
|
|
2
|
+
import type { ClientState, QueryEntry } from './client-state';
|
|
3
|
+
import { deriveStatus, hasServerMembership, isAuthoritative } from './lifecycle';
|
|
4
|
+
import { FETCH_CHUNK } from '../kernel/constants';
|
|
5
|
+
|
|
6
|
+
/** Pure reads over `ClientState`. Sagas use them through `state.read`. */
|
|
7
|
+
|
|
8
|
+
export const queryByHash = (s: ClientState, hash: QueryHash): QueryEntry | undefined => s.queries.get(hash);
|
|
9
|
+
|
|
10
|
+
export const activeHashes = (s: ClientState): QueryHash[] => [...s.queries.keys()];
|
|
11
|
+
|
|
12
|
+
export const hashesForTable = (s: ClientState, table: string): QueryHash[] =>
|
|
13
|
+
[...s.queries].filter(([, e]) => e.def.tableName === table).map(([h]) => h);
|
|
14
|
+
|
|
15
|
+
export const queryStatus = (s: ClientState, hash: QueryHash): QueryStatus | undefined => {
|
|
16
|
+
const e = s.queries.get(hash);
|
|
17
|
+
return e ? deriveStatus(e.lifecycle) : undefined;
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
export interface Overlay {
|
|
21
|
+
/** Ids with an unsynced or just-acked create/update. */
|
|
22
|
+
readonly writes: ReadonlySet<string>;
|
|
23
|
+
/** Ids with an unsynced or just-acked delete. */
|
|
24
|
+
readonly deletes: ReadonlySet<string>;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** The optimistic overlay, derived from the outbox (pending AND acked items). */
|
|
28
|
+
export function overlay(s: ClientState): Overlay {
|
|
29
|
+
const writes = new Set<string>();
|
|
30
|
+
const deletes = new Set<string>();
|
|
31
|
+
for (const item of s.outbox) {
|
|
32
|
+
if (item.type === 'delete') deletes.add(item.recordId);
|
|
33
|
+
else writes.add(item.recordId);
|
|
34
|
+
}
|
|
35
|
+
return { writes, deletes };
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export const pendingDeleteIds = (s: ClientState): ReadonlySet<string> =>
|
|
39
|
+
new Set(s.outbox.filter((i) => i.type === 'delete').map((i) => i.recordId));
|
|
40
|
+
|
|
41
|
+
export const hasAckedWrites = (s: ClientState): boolean => s.outbox.some((i) => i.status === 'acked');
|
|
42
|
+
|
|
43
|
+
export const pendingMutationCount = (s: ClientState): number =>
|
|
44
|
+
s.outbox.filter((i) => i.status === 'pending').length;
|
|
45
|
+
|
|
46
|
+
export const fetchingQueryCount = (s: ClientState): number =>
|
|
47
|
+
[...s.queries.values()].filter((e) => e.lifecycle.fetchDepth > 0).length;
|
|
48
|
+
|
|
49
|
+
/** Membership entries whose body is missing or older locally. */
|
|
50
|
+
export function needed(s: ClientState, hash: QueryHash): RecordVersionArray {
|
|
51
|
+
const e = s.queries.get(hash);
|
|
52
|
+
if (!e || !hasServerMembership(e.lifecycle)) return [];
|
|
53
|
+
const deletes = pendingDeleteIds(s);
|
|
54
|
+
return e.remoteArray.filter(([id, v]) => !deletes.has(id) && (s.versions.get(id) ?? -1) < v);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** Subquery child bodies missing or stale locally (never part of `settled`). */
|
|
58
|
+
export function neededChildren(s: ClientState, hash: QueryHash): RecordVersionArray {
|
|
59
|
+
const e = s.queries.get(hash);
|
|
60
|
+
if (!e || e.subqueryRemoteArray.length === 0) return [];
|
|
61
|
+
return e.subqueryRemoteArray.filter(([id, v]) => (s.versions.get(id) ?? -1) < v);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export interface FetchPlan {
|
|
65
|
+
/** Queries whose primary membership needs bodies (they flip to `fetching`). */
|
|
66
|
+
readonly hashes: QueryHash[];
|
|
67
|
+
readonly chunks: string[][];
|
|
68
|
+
/** Highest requested version per id, across every query naming it. */
|
|
69
|
+
readonly versions: ReadonlyMap<string, number>;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** Cross-query, deduped, chunked list of ids to pull from the server. */
|
|
73
|
+
export function planFetch(s: ClientState, chunkSize = FETCH_CHUNK): FetchPlan {
|
|
74
|
+
const versions = new Map<string, number>();
|
|
75
|
+
const hashes: QueryHash[] = [];
|
|
76
|
+
const add = (pairs: RecordVersionArray) => {
|
|
77
|
+
for (const [id, v] of pairs) versions.set(id, Math.max(v, versions.get(id) ?? -1));
|
|
78
|
+
};
|
|
79
|
+
for (const hash of s.queries.keys()) {
|
|
80
|
+
const missing = needed(s, hash);
|
|
81
|
+
if (missing.length > 0) hashes.push(hash);
|
|
82
|
+
add(missing);
|
|
83
|
+
add(neededChildren(s, hash));
|
|
84
|
+
}
|
|
85
|
+
const all = [...versions.keys()];
|
|
86
|
+
const chunks: string[][] = [];
|
|
87
|
+
for (let i = 0; i < all.length; i += chunkSize) chunks.push(all.slice(i, i + chunkSize));
|
|
88
|
+
return { hashes, chunks, versions };
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* "This query's rows are authoritative and complete": server membership
|
|
93
|
+
* accepted, every body present at its version, nothing waiting to be
|
|
94
|
+
* re-rendered, subscribers told at least once.
|
|
95
|
+
*/
|
|
96
|
+
export function settled(s: ClientState, hash: QueryHash): boolean {
|
|
97
|
+
const e = s.queries.get(hash);
|
|
98
|
+
if (!e || e.lifecycle.phase !== 'live') return false;
|
|
99
|
+
return needed(s, hash).length === 0 && !s.dirty.has(hash) && e.lifecycle.notified;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
export const settleFailed = (s: ClientState, hash: QueryHash): boolean => {
|
|
103
|
+
const e = s.queries.get(hash);
|
|
104
|
+
return !e || e.lifecycle.remote === 'failed';
|
|
105
|
+
};
|
|
106
|
+
|
|
107
|
+
export const desiredRegistrations = (s: ClientState): QueryHash[] =>
|
|
108
|
+
[...s.queries].filter(([, e]) => e.lifecycle.remote === 'unregistered').map(([h]) => h);
|
|
109
|
+
|
|
110
|
+
export const evictable = (s: ClientState, now: number): QueryHash[] =>
|
|
111
|
+
[...s.queries]
|
|
112
|
+
.filter(
|
|
113
|
+
([, e]) => e.subscribers === 0 && e.lastSubscriberLeftAt !== null && now - e.lastSubscriberLeftAt >= e.def.ttlMs
|
|
114
|
+
)
|
|
115
|
+
.map(([h]) => h);
|
|
116
|
+
|
|
117
|
+
export const shortestTtlMs = (s: ClientState): number | null => {
|
|
118
|
+
let min: number | null = null;
|
|
119
|
+
for (const e of s.queries.values()) min = min === null ? e.def.ttlMs : Math.min(min, e.def.ttlMs);
|
|
120
|
+
return min;
|
|
121
|
+
};
|
|
122
|
+
|
|
123
|
+
/** Legacy `QueryState` shape for DevTools and the public type surface. */
|
|
124
|
+
export function toQueryState(e: QueryEntry): QueryState {
|
|
125
|
+
const l = e.lifecycle;
|
|
126
|
+
return {
|
|
127
|
+
config: {
|
|
128
|
+
id: e.def.id,
|
|
129
|
+
surql: e.def.surql,
|
|
130
|
+
plan: e.def.plan,
|
|
131
|
+
params: { ...e.def.params },
|
|
132
|
+
localArray: [...e.localArray],
|
|
133
|
+
remoteArray: [...e.remoteArray],
|
|
134
|
+
subqueryRemoteArray: e.subqueryRemoteArray.length ? [...e.subqueryRemoteArray] : undefined,
|
|
135
|
+
membershipKnown: isAuthoritative(l),
|
|
136
|
+
membershipKey: e.def.viewKey,
|
|
137
|
+
ttl: e.def.ttl,
|
|
138
|
+
lastActiveAt: new Date(e.lastHeartbeatAt ?? e.def.createdAt),
|
|
139
|
+
tableName: e.def.tableName,
|
|
140
|
+
},
|
|
141
|
+
records: [...e.records] as Record<string, any>[],
|
|
142
|
+
serverMembership: hasServerMembership(l),
|
|
143
|
+
viewLost: l.phase === 'view-lost',
|
|
144
|
+
serverState: e.serverState,
|
|
145
|
+
syncNotified: l.notified,
|
|
146
|
+
ttlTimer: null,
|
|
147
|
+
ttlDurationMs: e.def.ttlMs,
|
|
148
|
+
lastHeartbeatAt: e.lastHeartbeatAt ?? undefined,
|
|
149
|
+
updateCount: e.telemetry.updateCount,
|
|
150
|
+
lastUpdatedAt: e.telemetry.lastUpdatedAt,
|
|
151
|
+
materializationSamples: [...e.telemetry.materializationSamples],
|
|
152
|
+
lastIngestLatencyMs: e.telemetry.lastIngestLatencyMs,
|
|
153
|
+
errorCount: e.telemetry.errorCount,
|
|
154
|
+
status: deriveStatus(l),
|
|
155
|
+
phaseSamples: Object.fromEntries(Object.entries(e.telemetry.phaseSamples).map(([k, v]) => [k, [...v]])),
|
|
156
|
+
phaseLast: { ...e.telemetry.phaseLast },
|
|
157
|
+
registrationTimings: e.telemetry.registrationTimings,
|
|
158
|
+
};
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
function phaseStatOf(samples: ReadonlyArray<number>, lastMs: number | null): PhaseStat {
|
|
162
|
+
if (samples.length === 0) return { lastMs, p50: null, p90: null, p99: null, count: 0 };
|
|
163
|
+
const sorted = [...samples].sort((a, b) => a - b);
|
|
164
|
+
const pick = (q: number) => sorted[Math.min(sorted.length - 1, Math.floor(q * sorted.length))]!;
|
|
165
|
+
return { lastMs, p50: pick(0.5), p90: pick(0.9), p99: pick(0.99), count: samples.length };
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/** Per-query processing-time breakdown for DevTools and the MCP. */
|
|
169
|
+
export function phaseTimings(e: QueryEntry): QueryTimings {
|
|
170
|
+
const t = e.telemetry;
|
|
171
|
+
const stat = (phase: string) => phaseStatOf(t.phaseSamples[phase] ?? [], t.phaseLast[phase] ?? null);
|
|
172
|
+
return {
|
|
173
|
+
ssp: phaseStatOf(t.materializationSamples, t.lastIngestLatencyMs),
|
|
174
|
+
sspStoreApply: stat('sspStoreApply'),
|
|
175
|
+
sspCircuitStep: stat('sspCircuitStep'),
|
|
176
|
+
sspTransform: stat('sspTransform'),
|
|
177
|
+
localFetch: stat('localFetch'),
|
|
178
|
+
remoteFetch: stat('remoteFetch'),
|
|
179
|
+
frontend: stat('frontend'),
|
|
180
|
+
registration: t.registrationTimings,
|
|
181
|
+
updateCount: t.updateCount,
|
|
182
|
+
errorCount: t.errorCount,
|
|
183
|
+
};
|
|
184
|
+
}
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest';
|
|
2
|
+
import { runPure } from '../testing/run-pure';
|
|
3
|
+
import { buildEntry, buildOutboxItem, buildState } from '../testing/build';
|
|
4
|
+
import * as R from '../state/reducers';
|
|
5
|
+
import { defaultEnv } from '../query/env';
|
|
6
|
+
import { connectionChanged, selfHealTick, syncOutcome } from './connection.saga';
|
|
7
|
+
|
|
8
|
+
const env = defaultEnv({ tables: [] } as any);
|
|
9
|
+
|
|
10
|
+
describe('connectionChanged', () => {
|
|
11
|
+
it('a drop arms resubscribe and invalidates LIVE; the initial connect does nothing else', async () => {
|
|
12
|
+
const s = R.patchSync({ liveUuid: 'u', liveTable: 't' })(buildState());
|
|
13
|
+
const dropped = await runPure(connectionChanged(env, 'reconnecting'), { state: s });
|
|
14
|
+
expect(dropped.state.sync).toMatchObject({ needsResubscribe: true, liveUuid: null, health: { connection: 'reconnecting' } });
|
|
15
|
+
const first = await runPure(connectionChanged(env, 'connected'), { state: buildState() });
|
|
16
|
+
expect(first.dispatched).toEqual([]);
|
|
17
|
+
const connecting = await runPure(connectionChanged(env, 'connecting'), { state: dropped.state });
|
|
18
|
+
expect(connecting.dispatched).toEqual([]);
|
|
19
|
+
});
|
|
20
|
+
it('reconnect after a drop drops every registration and re-drives, once per cooldown window', async () => {
|
|
21
|
+
const s = R.patchSync({ needsResubscribe: true })(
|
|
22
|
+
buildState([
|
|
23
|
+
buildEntry({ def: { hash: 'a' }, lifecycle: { remote: 'registered' } }),
|
|
24
|
+
buildEntry({ def: { hash: 'b' }, lifecycle: { remote: 'failed' } }),
|
|
25
|
+
buildEntry({ def: { hash: 'c' } }),
|
|
26
|
+
])
|
|
27
|
+
);
|
|
28
|
+
const out = await runPure(connectionChanged(env, 'connected'), { state: s, now: 1000 });
|
|
29
|
+
expect([...out.state.queries.values()].map((e) => e.lifecycle.remote)).toEqual(['unregistered', 'unregistered', 'unregistered']);
|
|
30
|
+
expect(out.state.sync).toMatchObject({ needsResubscribe: false, lastReconnectRefetchAt: 1000 });
|
|
31
|
+
expect(out.dispatched).toEqual([{ type: 'EnsureRegistered', requireAuth: true }, { type: 'LiveStart' }, { type: 'Drain' }]);
|
|
32
|
+
const burst = await runPure(connectionChanged(env, 'connected'), { state: R.patchSync({ needsResubscribe: true })(out.state), now: 5000 });
|
|
33
|
+
expect(burst.dispatched).toEqual([]);
|
|
34
|
+
expect(burst.state.sync.needsResubscribe).toBe(false);
|
|
35
|
+
const later = await runPure(connectionChanged(env, 'connected'), { state: R.patchSync({ needsResubscribe: true })(out.state), now: 20_000 });
|
|
36
|
+
expect(later.dispatched).toHaveLength(3);
|
|
37
|
+
});
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
describe('syncOutcome', () => {
|
|
41
|
+
it('degrades after the threshold (arming self-heal), recovers on success (disarming it)', async () => {
|
|
42
|
+
let state = buildState();
|
|
43
|
+
for (let i = 0; i < 2; i++) state = (await runPure(syncOutcome(env, false, new Error('socket')), { state })).state;
|
|
44
|
+
expect(state.sync.health.status).toBe('healthy');
|
|
45
|
+
const third = await runPure(syncOutcome(env, false, new Error('socket')), { state });
|
|
46
|
+
expect(third.state.sync.health.status).toBe('degraded');
|
|
47
|
+
// The saga emits nothing: the runtime notifies `health:changed` off the
|
|
48
|
+
// health object's identity, which `setHealth` only replaces on a real move.
|
|
49
|
+
expect(third.emitted).toEqual([]);
|
|
50
|
+
expect(third.timers.get('heal')).toEqual({ ms: 2000, event: { type: 'SelfHealTick' } });
|
|
51
|
+
expect(third.state.sync.selfHealAttempts).toBe(0);
|
|
52
|
+
const back = await runPure(syncOutcome(env, true), { state: third.state });
|
|
53
|
+
expect(back.state.sync.health.status).toBe('healthy');
|
|
54
|
+
expect(back.state.sync.health).not.toBe(third.state.sync.health);
|
|
55
|
+
expect(back.log.some((e) => e.kind === 'timer.clear' && (e as any).key === 'heal')).toBe(true);
|
|
56
|
+
const quiet = await runPure(syncOutcome(env, true), { state: back.state });
|
|
57
|
+
expect(quiet.state.sync.health).toBe(back.state.sync.health);
|
|
58
|
+
});
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
describe('selfHealTick', () => {
|
|
62
|
+
const degraded = (s: ReturnType<typeof buildState>) =>
|
|
63
|
+
R.compose(R.setHealth({ ...s.sync.health, status: 'degraded' }), R.patchSync({ selfHealAttempts: 1 }))(s);
|
|
64
|
+
it('does nothing when healthy; drains first, then re-registers (failed included), else probes; always re-arms', async () => {
|
|
65
|
+
expect((await runPure(selfHealTick(env), { state: buildState() })).timers.size).toBe(0);
|
|
66
|
+
const withOutbox = await runPure(selfHealTick(env), { state: degraded(buildState([], R.outboxReplace([buildOutboxItem()]))) });
|
|
67
|
+
expect(withOutbox.dispatched).toEqual([{ type: 'Drain' }]);
|
|
68
|
+
expect(withOutbox.timers.get('heal')).toEqual({ ms: 8000, event: { type: 'SelfHealTick' } });
|
|
69
|
+
const withFailed = await runPure(selfHealTick(env), { state: degraded(buildState([buildEntry({ def: { hash: 'a' }, lifecycle: { remote: 'failed' } })])) });
|
|
70
|
+
expect(withFailed.state.queries.get('a')!.lifecycle.remote).toBe('unregistered');
|
|
71
|
+
expect(withFailed.dispatched).toEqual([{ type: 'EnsureRegistered', requireAuth: true }]);
|
|
72
|
+
const withDesired = await runPure(selfHealTick(env), { state: degraded(buildState([buildEntry({ def: { hash: 'a' } })])) });
|
|
73
|
+
expect(withDesired.dispatched).toEqual([{ type: 'EnsureRegistered', requireAuth: true }]);
|
|
74
|
+
const probe = await runPure(selfHealTick(env), { state: degraded(buildState()), handlers: { 'remote.query': () => [{ status: 'OK', result: true }] } });
|
|
75
|
+
expect(probe.dispatched).toEqual([{ type: 'SyncOutcome', ok: true }]);
|
|
76
|
+
const probeFail = await runPure(selfHealTick(env), {
|
|
77
|
+
state: degraded(buildState()),
|
|
78
|
+
handlers: {
|
|
79
|
+
'remote.query': () => {
|
|
80
|
+
throw new Error('offline');
|
|
81
|
+
},
|
|
82
|
+
},
|
|
83
|
+
});
|
|
84
|
+
expect(probeFail.dispatched).toEqual([{ type: 'SyncOutcome', ok: false, error: new Error('offline') }]);
|
|
85
|
+
});
|
|
86
|
+
});
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import type { ConnectionState } from '../types';
|
|
2
|
+
import type { Saga } from '../kernel/saga';
|
|
3
|
+
import { fx } from '../kernel/effects';
|
|
4
|
+
import { RECONNECT_REFETCH_COOLDOWN_MS } from '../kernel/constants';
|
|
5
|
+
import type { ClientState } from '../state/client-state';
|
|
6
|
+
import * as R from '../state/reducers';
|
|
7
|
+
import { desiredRegistrations, pendingMutationCount } from '../state/selectors';
|
|
8
|
+
import type { SagaEnv } from '../query/env';
|
|
9
|
+
import { liveInvalidate } from './live.saga';
|
|
10
|
+
import { nextHealth, selfHealDelayMs } from './policy';
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Transport state changes. A drop invalidates the live query and arms a
|
|
14
|
+
* resubscribe; the next `connected` (outside the burst cooldown) drops every
|
|
15
|
+
* remote registration so `ensureRegistered` rebuilds them behind the
|
|
16
|
+
* `$auth.id` gate, and restarts LIVE.
|
|
17
|
+
*/
|
|
18
|
+
export function* connectionChanged(env: SagaEnv, connection: ConnectionState): Saga<void> {
|
|
19
|
+
const state = (yield fx.state.read((s) => s)) as ClientState;
|
|
20
|
+
yield fx.state.update(R.setConnection(connection));
|
|
21
|
+
if (connection === 'disconnected' || connection === 'reconnecting') {
|
|
22
|
+
yield fx.state.update(R.patchSync({ needsResubscribe: true }));
|
|
23
|
+
yield* liveInvalidate();
|
|
24
|
+
return;
|
|
25
|
+
}
|
|
26
|
+
if (connection !== 'connected' || !state.sync.needsResubscribe) return;
|
|
27
|
+
const now = (yield fx.now()) as number;
|
|
28
|
+
const last = state.sync.lastReconnectRefetchAt;
|
|
29
|
+
if (last !== null && now - last < RECONNECT_REFETCH_COOLDOWN_MS) {
|
|
30
|
+
yield fx.state.update(R.patchSync({ needsResubscribe: false }));
|
|
31
|
+
return;
|
|
32
|
+
}
|
|
33
|
+
yield fx.state.update(
|
|
34
|
+
R.compose(
|
|
35
|
+
R.patchSync({ needsResubscribe: false, lastReconnectRefetchAt: now }),
|
|
36
|
+
...[...state.queries.values()]
|
|
37
|
+
.filter((e) => e.lifecycle.remote !== 'unregistered')
|
|
38
|
+
.map((e) => R.applyLifecycle(e.def.hash, { type: 'remote-dropped' }))
|
|
39
|
+
)
|
|
40
|
+
);
|
|
41
|
+
yield fx.dispatch({ type: 'EnsureRegistered', requireAuth: true });
|
|
42
|
+
yield fx.dispatch({ type: 'LiveStart' });
|
|
43
|
+
yield fx.dispatch({ type: 'Drain' });
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** Fold one sync round's outcome into health; start / stop self-heal. */
|
|
47
|
+
export function* syncOutcome(env: SagaEnv, ok: boolean, error?: unknown): Saga<void> {
|
|
48
|
+
const sync = (yield fx.state.read((s) => s.sync)) as ClientState['sync'];
|
|
49
|
+
const next = nextHealth({ health: sync.health, consecutiveFailures: sync.consecutiveFailures, hasSyncedOnce: sync.hasSyncedOnce }, ok, error, env.degradeAfter);
|
|
50
|
+
yield fx.state.update(
|
|
51
|
+
R.compose(R.setHealth(next.health), R.patchSync({ consecutiveFailures: next.consecutiveFailures, hasSyncedOnce: next.hasSyncedOnce }))
|
|
52
|
+
);
|
|
53
|
+
if (next.degradedNow) {
|
|
54
|
+
yield fx.state.update(R.patchSync({ selfHealAttempts: 0 }));
|
|
55
|
+
yield fx.timer.set('heal', selfHealDelayMs(0), { type: 'SelfHealTick' });
|
|
56
|
+
}
|
|
57
|
+
if (next.recoveredNow) yield fx.timer.clear('heal');
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* While degraded: re-drive whatever can prove the server is back, on a
|
|
62
|
+
* growing backoff. Retry the outbox first, then the registrations (failed
|
|
63
|
+
* ones included, behind the identity gate), else a bare probe.
|
|
64
|
+
*/
|
|
65
|
+
export function* selfHealTick(env: SagaEnv): Saga<void> {
|
|
66
|
+
const state = (yield fx.state.read((s) => s)) as ClientState;
|
|
67
|
+
if (state.sync.health.status !== 'degraded') return;
|
|
68
|
+
const attempt = state.sync.selfHealAttempts + 1;
|
|
69
|
+
yield fx.state.update(R.patchSync({ selfHealAttempts: attempt }));
|
|
70
|
+
const failed = [...state.queries.values()].filter((e) => e.lifecycle.remote === 'failed').map((e) => e.def.hash);
|
|
71
|
+
if (pendingMutationCount(state) > 0) {
|
|
72
|
+
yield fx.dispatch({ type: 'Drain' });
|
|
73
|
+
} else if (desiredRegistrations(state).length > 0 || failed.length > 0) {
|
|
74
|
+
if (failed.length > 0) yield fx.state.update(R.compose(...failed.map((h) => R.applyLifecycle(h, { type: 'remote-dropped' }))));
|
|
75
|
+
yield fx.dispatch({ type: 'EnsureRegistered', requireAuth: true });
|
|
76
|
+
} else {
|
|
77
|
+
try {
|
|
78
|
+
yield fx.remote.query('RETURN true', undefined, env.remoteTimeoutMs);
|
|
79
|
+
yield fx.dispatch({ type: 'SyncOutcome', ok: true });
|
|
80
|
+
} catch (error) {
|
|
81
|
+
yield fx.dispatch({ type: 'SyncOutcome', ok: false, error });
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
yield fx.timer.set('heal', selfHealDelayMs(attempt), { type: 'SelfHealTick' });
|
|
85
|
+
}
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest';
|
|
2
|
+
import { runPure } from '../testing/run-pure';
|
|
3
|
+
import { buildEntry, buildState } from '../testing/build';
|
|
4
|
+
import * as R from '../state/reducers';
|
|
5
|
+
import { defaultEnv } from '../query/env';
|
|
6
|
+
import { liveChange, liveInvalidate, liveStart } from './live.saga';
|
|
7
|
+
|
|
8
|
+
const env = defaultEnv({ tables: [] } as any);
|
|
9
|
+
|
|
10
|
+
describe('liveStart', () => {
|
|
11
|
+
it('subscribes on the session table and records the uuid; no-op when already on it; followers never subscribe', async () => {
|
|
12
|
+
const out = await runPure(liveStart(env), { state: { ...buildState(), userId: 'user:abc' }, handlers: { 'remote.live': (e: any) => `uuid-${e.table}` } });
|
|
13
|
+
expect(out.state.sync).toMatchObject({ liveUuid: 'uuid-_00_list_ref_user_abc', liveTable: '_00_list_ref_user_abc' });
|
|
14
|
+
const same = await runPure(liveStart(env), { state: out.state });
|
|
15
|
+
expect(same.log.filter((e) => e.kind === 'remote.live')).toHaveLength(0);
|
|
16
|
+
const follower = await runPure(liveStart(env), { state: { ...buildState(), tabRole: 'follower' } });
|
|
17
|
+
expect(follower.log.filter((e) => e.kind === 'remote.live')).toHaveLength(0);
|
|
18
|
+
});
|
|
19
|
+
it('kills the previous subscription when connected (ignoring kill errors), tolerates a failing subscribe', async () => {
|
|
20
|
+
const prev = R.compose(R.patchSync({ liveUuid: 'old', liveTable: '_00_list_ref' }), R.setConnection('connected'))({ ...buildState(), userId: 'user:x' });
|
|
21
|
+
const killed: string[] = [];
|
|
22
|
+
const out = await runPure(liveStart(env), {
|
|
23
|
+
state: prev,
|
|
24
|
+
handlers: {
|
|
25
|
+
'remote.kill': (e: any) => {
|
|
26
|
+
killed.push(e.uuid);
|
|
27
|
+
throw new Error('gone');
|
|
28
|
+
},
|
|
29
|
+
'remote.live': () => 'new',
|
|
30
|
+
},
|
|
31
|
+
});
|
|
32
|
+
expect(killed).toEqual(['old']);
|
|
33
|
+
expect(out.state.sync.liveUuid).toBe('new');
|
|
34
|
+
const clean = await runPure(liveStart(env), { state: prev, handlers: { 'remote.kill': () => undefined, 'remote.live': () => 'new2' } });
|
|
35
|
+
expect(clean.state.sync.liveUuid).toBe('new2');
|
|
36
|
+
expect(clean.emitted).toEqual([]);
|
|
37
|
+
const offline = R.patchSync({ liveUuid: 'old', liveTable: '_00_list_ref' })({ ...buildState(), userId: 'user:x' });
|
|
38
|
+
const noKill = await runPure(liveStart(env), {
|
|
39
|
+
state: offline,
|
|
40
|
+
handlers: {
|
|
41
|
+
'remote.live': () => {
|
|
42
|
+
throw new Error('not connected');
|
|
43
|
+
},
|
|
44
|
+
},
|
|
45
|
+
});
|
|
46
|
+
expect(noKill.log.filter((e) => e.kind === 'remote.kill')).toHaveLength(0);
|
|
47
|
+
expect(noKill.state.sync.liveUuid).toBeNull();
|
|
48
|
+
expect(noKill.emitted).toEqual([expect.objectContaining({ level: 'warn' })]);
|
|
49
|
+
});
|
|
50
|
+
it('liveInvalidate clears the bookkeeping', async () => {
|
|
51
|
+
const out = await runPure(liveInvalidate(), { state: R.patchSync({ liveUuid: 'u', liveTable: 't' })(buildState()) });
|
|
52
|
+
expect(out.state.sync).toMatchObject({ liveUuid: null, liveTable: null });
|
|
53
|
+
});
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
describe('liveChange', () => {
|
|
57
|
+
it('marks known hashes dirty, resets the poll streak, relays as leader; ignores unknown hashes', async () => {
|
|
58
|
+
const s = R.patchSync({ pollIdleStreak: 3 })(buildState([buildEntry({ def: { hash: 'a' } })]));
|
|
59
|
+
const out = await runPure(liveChange(['a', 'zz']), { state: { ...s, tabRole: 'leader' } });
|
|
60
|
+
expect([...out.state.membershipDirty]).toEqual(['a']);
|
|
61
|
+
expect(out.state.sync.pollIdleStreak).toBe(0);
|
|
62
|
+
expect(out.timers.get('membership')).toEqual({ ms: 50, event: { type: 'ReadDirtyMembership' } });
|
|
63
|
+
expect(out.emitted).toEqual([{ type: 'tabs:broadcast', message: { type: 'membership-dirty', hashes: ['a'] } }]);
|
|
64
|
+
const solo = await runPure(liveChange(['a']), { state: s });
|
|
65
|
+
expect(solo.emitted).toEqual([]);
|
|
66
|
+
const none = await runPure(liveChange(['zz']), { state: s });
|
|
67
|
+
expect(none.timers.size).toBe(0);
|
|
68
|
+
});
|
|
69
|
+
});
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import type { QueryHash } from '../types';
|
|
2
|
+
import type { Saga } from '../kernel/saga';
|
|
3
|
+
import { fx } from '../kernel/effects';
|
|
4
|
+
import type { ClientState } from '../state/client-state';
|
|
5
|
+
import * as R from '../state/reducers';
|
|
6
|
+
import type { SagaEnv } from '../query/env';
|
|
7
|
+
import { listRefTable } from '../query/env';
|
|
8
|
+
import { markMembershipDirty } from '../query/membership.saga';
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* LIVE on the session's `_00_list_ref` table. Events never carry data into
|
|
12
|
+
* state: every change only marks its query's membership dirty, and the
|
|
13
|
+
* batched re-read decides. Followers get the same dirt relayed by the
|
|
14
|
+
* leader.
|
|
15
|
+
*/
|
|
16
|
+
export function* liveStart(env: SagaEnv): Saga<void> {
|
|
17
|
+
const state = (yield fx.state.read((s) => s)) as ClientState;
|
|
18
|
+
if (state.tabRole === 'follower') return;
|
|
19
|
+
const table = listRefTable(env, state);
|
|
20
|
+
if (state.sync.liveUuid && state.sync.liveTable === table) return;
|
|
21
|
+
if (state.sync.liveUuid && state.sync.health.connection === 'connected') {
|
|
22
|
+
try {
|
|
23
|
+
yield fx.remote.kill(state.sync.liveUuid);
|
|
24
|
+
} catch (error) {
|
|
25
|
+
yield fx.emit({ type: 'log', level: 'debug', message: 'kill of the previous live query failed', data: { error } });
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
yield fx.state.update(R.patchSync({ liveUuid: null, liveTable: null }));
|
|
29
|
+
try {
|
|
30
|
+
const uuid = (yield fx.remote.live(table)) as string;
|
|
31
|
+
yield fx.state.update(R.patchSync({ liveUuid: uuid, liveTable: table }));
|
|
32
|
+
} catch (error) {
|
|
33
|
+
yield fx.emit({ type: 'log', level: 'warn', message: 'live subscription failed; the poll covers membership', data: { table, error } });
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** The socket dropped: the server-side live query is gone with it. */
|
|
38
|
+
export function* liveInvalidate(): Saga<void> {
|
|
39
|
+
yield fx.state.update(R.patchSync({ liveUuid: null, liveTable: null }));
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** One or more edges of these queries changed on the server. */
|
|
43
|
+
export function* liveChange(hashes: QueryHash[]): Saga<void> {
|
|
44
|
+
const [known, role] = (yield fx.state.read((s) => [hashes.filter((h) => s.queries.has(h)), s.tabRole])) as [QueryHash[], ClientState['tabRole']];
|
|
45
|
+
if (known.length === 0) return;
|
|
46
|
+
yield fx.state.update(R.patchSync({ pollIdleStreak: 0 }));
|
|
47
|
+
yield* markMembershipDirty(known);
|
|
48
|
+
if (role === 'leader') yield fx.emit({ type: 'tabs:broadcast', message: { type: 'membership-dirty', hashes: known } });
|
|
49
|
+
}
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest';
|
|
2
|
+
import { nextHealth, selfHealDelayMs } from './policy';
|
|
3
|
+
import { initialHealth } from '../state/client-state';
|
|
4
|
+
import { sameHealth } from '../state/reducers';
|
|
5
|
+
|
|
6
|
+
const start = { health: initialHealth('connected'), consecutiveFailures: 0, hasSyncedOnce: false };
|
|
7
|
+
|
|
8
|
+
describe('nextHealth', () => {
|
|
9
|
+
it('disabled reporting never changes anything', () => {
|
|
10
|
+
const out = nextHealth(start, false, new Error('x'), 0);
|
|
11
|
+
expect(out).toMatchObject({ ...start, degradedNow: false, recoveredNow: false });
|
|
12
|
+
});
|
|
13
|
+
it('first success latches everConnected and hasSyncedOnce', () => {
|
|
14
|
+
const out = nextHealth(start, true, undefined, 3);
|
|
15
|
+
expect(out.health.everConnected).toBe(true);
|
|
16
|
+
expect(out.hasSyncedOnce).toBe(true);
|
|
17
|
+
// A second success moves nothing, so the runtime must not re-notify.
|
|
18
|
+
const again = nextHealth(out, true, undefined, 3);
|
|
19
|
+
expect(sameHealth(again.health, out.health)).toBe(true);
|
|
20
|
+
});
|
|
21
|
+
it('failures accumulate, degrade at the threshold once, recover on success', () => {
|
|
22
|
+
let s = nextHealth(start, false, new Error('socket closed'), 3);
|
|
23
|
+
expect(s.health.status).toBe('healthy');
|
|
24
|
+
expect(s.consecutiveFailures).toBe(1);
|
|
25
|
+
expect(s.health.kind).toBe('network');
|
|
26
|
+
s = nextHealth(s, false, 'permission denied', 3);
|
|
27
|
+
expect(s.health.kind).toBe('application');
|
|
28
|
+
s = nextHealth(s, false, new Error('timeout'), 3);
|
|
29
|
+
expect(s.health.status).toBe('degraded');
|
|
30
|
+
expect(s.degradedNow).toBe(true);
|
|
31
|
+
expect(s.health.consecutiveFailures).toBe(3);
|
|
32
|
+
s = nextHealth(s, false, new Error('timeout'), 3);
|
|
33
|
+
expect(s.degradedNow).toBe(false);
|
|
34
|
+
expect(s.consecutiveFailures).toBe(4);
|
|
35
|
+
const r = nextHealth(s, true, undefined, 3);
|
|
36
|
+
expect(r.health.status).toBe('healthy');
|
|
37
|
+
expect(r.recoveredNow).toBe(true);
|
|
38
|
+
expect(r.health.kind).toBeUndefined();
|
|
39
|
+
expect(r.consecutiveFailures).toBe(0);
|
|
40
|
+
});
|
|
41
|
+
it('a success after sub-threshold failures resets without a recovery flag', () => {
|
|
42
|
+
const s = nextHealth(start, false, new Error('x'), 3);
|
|
43
|
+
const r = nextHealth(s, true, undefined, 3);
|
|
44
|
+
expect(r.recoveredNow).toBe(false);
|
|
45
|
+
expect(r.consecutiveFailures).toBe(0);
|
|
46
|
+
});
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
describe('selfHealDelayMs', () => {
|
|
50
|
+
it('doubles from 2s and caps at 30s', () => {
|
|
51
|
+
expect(selfHealDelayMs(0)).toBe(2000);
|
|
52
|
+
expect(selfHealDelayMs(2)).toBe(8000);
|
|
53
|
+
expect(selfHealDelayMs(10)).toBe(30000);
|
|
54
|
+
expect(selfHealDelayMs(100)).toBe(30000);
|
|
55
|
+
});
|
|
56
|
+
});
|
|
@@ -16,9 +16,37 @@ import {
|
|
|
16
16
|
listRefPollDelayMs,
|
|
17
17
|
LIST_REF_POLL_MAX_INTERVAL_MS,
|
|
18
18
|
recordVersionArraysEqual,
|
|
19
|
-
} from './
|
|
20
|
-
import type { RecordVersionArray, RecordVersionDiff } from '
|
|
21
|
-
import { encodeRecordId } from '
|
|
19
|
+
} from './policy';
|
|
20
|
+
import type { RecordVersionArray, RecordVersionDiff } from '../types';
|
|
21
|
+
import { encodeRecordId } from '../utils/index';
|
|
22
|
+
|
|
23
|
+
describe('ArraySyncer.update', () => {
|
|
24
|
+
it('planListRefPollChunks keeps duplicate hashes with equal ages stable', () => {
|
|
25
|
+
const now = 1000;
|
|
26
|
+
const chunks = planListRefPollChunks(
|
|
27
|
+
[
|
|
28
|
+
{ hash: 'x', rows: 1, lastPolledAt: 0 },
|
|
29
|
+
{ hash: 'x', rows: 1, lastPolledAt: 0 },
|
|
30
|
+
{ hash: 'a', rows: 1, lastPolledAt: 0 },
|
|
31
|
+
],
|
|
32
|
+
{ now }
|
|
33
|
+
);
|
|
34
|
+
expect(chunks).toEqual([['a', 'x', 'x']]);
|
|
35
|
+
});
|
|
36
|
+
it('nextPollDelayMs treats a future live event as no event', () => {
|
|
37
|
+
expect(nextPollDelayMs({ now: 100, lastLiveEventAt: 200, baseIntervalMs: 500 })).toBe(500);
|
|
38
|
+
});
|
|
39
|
+
it('bumps only the matching record and re-sorts on the next diff', () => {
|
|
40
|
+
const syncer = new ArraySyncer([['t:b', 1], ['t:a', 1]], [['t:a', 2], ['t:b', 1]]);
|
|
41
|
+
syncer.update('t:a', 2);
|
|
42
|
+
expect(syncer.nextSet()).toEqual({ added: [], updated: [], removed: [] });
|
|
43
|
+
syncer.insert('t:c', 1);
|
|
44
|
+
syncer.delete('t:b');
|
|
45
|
+
const diff = syncer.nextSet();
|
|
46
|
+
expect(diff!.added.map((a) => encodeRecordId(a.id))).toEqual(['t:b']);
|
|
47
|
+
expect(diff!.removed.map((r) => encodeRecordId(r))).toEqual(['t:c']);
|
|
48
|
+
});
|
|
49
|
+
});
|
|
22
50
|
|
|
23
51
|
function rid(table: string, id: string): RecordId<string> {
|
|
24
52
|
return new RecordId(table, id);
|
|
@@ -1,6 +1,9 @@
|
|
|
1
1
|
import type { RecordId } from 'surrealdb';
|
|
2
|
-
import type { RecordVersionArray, RecordVersionDiff } from '
|
|
3
|
-
import { parseRecordIdString, encodeRecordId } from '
|
|
2
|
+
import type { RecordVersionArray, RecordVersionDiff } from '../types';
|
|
3
|
+
import { parseRecordIdString, encodeRecordId } from '../utils/index';
|
|
4
|
+
import type { SyncHealth } from '../types';
|
|
5
|
+
import { classifySyncError } from '../utils/error-classification';
|
|
6
|
+
import { SELF_HEAL_BASE_MS, SELF_HEAL_MAX_MS } from '../kernel/constants';
|
|
4
7
|
|
|
5
8
|
export class ArraySyncer {
|
|
6
9
|
private localArray: RecordVersionArray;
|
|
@@ -8,8 +11,8 @@ export class ArraySyncer {
|
|
|
8
11
|
private needsSort = false;
|
|
9
12
|
|
|
10
13
|
constructor(localArray: RecordVersionArray, remoteArray: RecordVersionArray) {
|
|
11
|
-
this.remoteArray = remoteArray.toSorted((a, b) => a[0].localeCompare(b[0]));
|
|
12
|
-
this.localArray = localArray.toSorted((a, b) => a[0].localeCompare(b[0]));
|
|
14
|
+
this.remoteArray = remoteArray.toSorted((a: [string, number], b: [string, number]) => a[0].localeCompare(b[0]));
|
|
15
|
+
this.localArray = localArray.toSorted((a: [string, number], b: [string, number]) => a[0].localeCompare(b[0]));
|
|
13
16
|
}
|
|
14
17
|
|
|
15
18
|
/**
|
|
@@ -128,7 +131,7 @@ export function applyRecordVersionDiff(
|
|
|
128
131
|
currentMap.set(encodeRecordId(item.id), item.version);
|
|
129
132
|
}
|
|
130
133
|
|
|
131
|
-
return Array.from(currentMap).toSorted((a, b) => a[0].localeCompare(b[0]));
|
|
134
|
+
return Array.from(currentMap).toSorted((a: [string, number], b: [string, number]) => a[0].localeCompare(b[0]));
|
|
132
135
|
}
|
|
133
136
|
|
|
134
137
|
export function createDiffFromDbOp(
|
|
@@ -438,3 +441,62 @@ export function recordVersionArraysEqual(
|
|
|
438
441
|
}
|
|
439
442
|
return true;
|
|
440
443
|
}
|
|
444
|
+
|
|
445
|
+
// ---- health ------------------------------------------------------------------
|
|
446
|
+
|
|
447
|
+
|
|
448
|
+
export interface HealthInput {
|
|
449
|
+
health: SyncHealth;
|
|
450
|
+
consecutiveFailures: number;
|
|
451
|
+
hasSyncedOnce: boolean;
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
export interface HealthOutput extends HealthInput {
|
|
455
|
+
/** Crossed into degraded on this outcome: start self-heal. */
|
|
456
|
+
degradedNow: boolean;
|
|
457
|
+
/** Left degraded on this outcome: stop self-heal. */
|
|
458
|
+
recoveredNow: boolean;
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
/**
|
|
462
|
+
* Fold one sync round's outcome into health. A single failure is absorbed;
|
|
463
|
+
* `degradeAfter` consecutive ones flip to degraded, the next success flips
|
|
464
|
+
* back. `degradeAfter <= 0` disables reporting.
|
|
465
|
+
*/
|
|
466
|
+
export function nextHealth(input: HealthInput, ok: boolean, error: unknown, degradeAfter: number): HealthOutput {
|
|
467
|
+
const base = { ...input, degradedNow: false, recoveredNow: false };
|
|
468
|
+
if (degradeAfter <= 0) return base;
|
|
469
|
+
if (ok) {
|
|
470
|
+
const everConnected = true;
|
|
471
|
+
if (input.consecutiveFailures === 0) {
|
|
472
|
+
return { ...base, hasSyncedOnce: true, health: { ...input.health, everConnected } };
|
|
473
|
+
}
|
|
474
|
+
const recovered = input.health.status === 'degraded';
|
|
475
|
+
return {
|
|
476
|
+
...base,
|
|
477
|
+
hasSyncedOnce: true,
|
|
478
|
+
consecutiveFailures: 0,
|
|
479
|
+
health: { ...input.health, status: 'healthy', kind: undefined, error: undefined, everConnected },
|
|
480
|
+
recoveredNow: recovered,
|
|
481
|
+
};
|
|
482
|
+
}
|
|
483
|
+
const consecutiveFailures = input.consecutiveFailures + 1;
|
|
484
|
+
const kind = classifySyncError(error);
|
|
485
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
486
|
+
if (input.health.status !== 'degraded' && consecutiveFailures >= degradeAfter) {
|
|
487
|
+
return {
|
|
488
|
+
...base,
|
|
489
|
+
consecutiveFailures,
|
|
490
|
+
health: { ...input.health, status: 'degraded', consecutiveFailures, kind, error: message },
|
|
491
|
+
degradedNow: true,
|
|
492
|
+
};
|
|
493
|
+
}
|
|
494
|
+
return {
|
|
495
|
+
...base,
|
|
496
|
+
consecutiveFailures,
|
|
497
|
+
health: { ...input.health, consecutiveFailures, kind, error: message },
|
|
498
|
+
};
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
export const selfHealDelayMs = (attempt: number): number =>
|
|
502
|
+
Math.min(SELF_HEAL_MAX_MS, SELF_HEAL_BASE_MS * 2 ** Math.min(attempt, 30));
|