@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,512 @@
|
|
|
1
|
+
import { describe, expect, it, vi } from 'vitest';
|
|
2
|
+
import { RecordId, Uuid } from 'surrealdb';
|
|
3
|
+
import { QueryBuilder } from '@spooky-sync/query-builder';
|
|
4
|
+
import {
|
|
5
|
+
createLiveFeed,
|
|
6
|
+
liveEndpoint,
|
|
7
|
+
liveQueryInput,
|
|
8
|
+
LiveFeedError,
|
|
9
|
+
type LiveSurreal,
|
|
10
|
+
} from './index';
|
|
11
|
+
import { Sp00kyClient } from '../client/sp00ky-client';
|
|
12
|
+
import { Runtime } from '../client/runtime';
|
|
13
|
+
import { fakeAdapters } from '../testing/adapters';
|
|
14
|
+
import { fakeServiceBundle } from '../testing/fake-services';
|
|
15
|
+
import { runPure } from '../testing/run-pure';
|
|
16
|
+
import { defaultEnv } from '../query/env';
|
|
17
|
+
import { registerLocal, registerRemote } from '../query/register.saga';
|
|
18
|
+
import { emptyState } from '../state/client-state';
|
|
19
|
+
import { queryKey } from '../pure';
|
|
20
|
+
import { queryHashInput } from '../query/hash';
|
|
21
|
+
import { sha256Hex } from '../utils/sha256';
|
|
22
|
+
|
|
23
|
+
const schema = {
|
|
24
|
+
tables: [
|
|
25
|
+
{
|
|
26
|
+
name: 'notification',
|
|
27
|
+
columns: { user: { recordId: true }, read: {}, created_at: { dateTime: true } },
|
|
28
|
+
},
|
|
29
|
+
],
|
|
30
|
+
relationships: [],
|
|
31
|
+
} as any;
|
|
32
|
+
|
|
33
|
+
function jwt(claims: Record<string, unknown>): string {
|
|
34
|
+
const b64 = (o: unknown) => Buffer.from(JSON.stringify(o)).toString('base64url');
|
|
35
|
+
return `${b64({ alg: 'HS512', typ: 'JWT' })}.${b64(claims)}.sig`;
|
|
36
|
+
}
|
|
37
|
+
const aliceToken = jwt({
|
|
38
|
+
ID: 'user:alice',
|
|
39
|
+
AC: 'account',
|
|
40
|
+
exp: Math.floor(Date.now() / 1000) + 3600,
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
const n1 = new RecordId('notification', 'n1');
|
|
44
|
+
const n2 = new RecordId('notification', 'n2');
|
|
45
|
+
const n3 = new RecordId('notification', 'n3');
|
|
46
|
+
const body = (rid: RecordId, extra: Record<string, unknown> = {}) => ({
|
|
47
|
+
id: rid,
|
|
48
|
+
user: new RecordId('user', 'alice'),
|
|
49
|
+
read: false,
|
|
50
|
+
title: `t-${rid.id}`,
|
|
51
|
+
...extra,
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
/** A scripted stand-in for the `surrealdb` SDK client. */
|
|
55
|
+
class FakeSurreal {
|
|
56
|
+
calls: Array<{ sql: string; vars?: Record<string, any> }> = [];
|
|
57
|
+
edges: Array<{ out: RecordId; version: number }> = [];
|
|
58
|
+
bodies = new Map<string, Record<string, unknown>>();
|
|
59
|
+
meta: { rowCount: number; state: string } | null = { rowCount: 0, state: 'ready' };
|
|
60
|
+
liveCb: ((m: { action: string; value: unknown }) => void) | null = null;
|
|
61
|
+
killed = false;
|
|
62
|
+
closed = false;
|
|
63
|
+
authError: Error | null = null;
|
|
64
|
+
heartbeatGone = false;
|
|
65
|
+
liveId = new Uuid('018f0000-0000-7000-8000-000000000001');
|
|
66
|
+
connect = vi.fn(async () => true);
|
|
67
|
+
use = vi.fn(async () => true);
|
|
68
|
+
authenticate = vi.fn(async () => {
|
|
69
|
+
if (this.authError) throw this.authError;
|
|
70
|
+
return true;
|
|
71
|
+
});
|
|
72
|
+
close = vi.fn(async () => {
|
|
73
|
+
this.closed = true;
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
query(sql: string, vars?: Record<string, any>): Promise<unknown[]> {
|
|
77
|
+
this.calls.push({ sql, vars });
|
|
78
|
+
return Promise.resolve(this.answer(sql, vars));
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
answer(sql: string, vars?: Record<string, any>): unknown[] {
|
|
82
|
+
const snapshot = () => [this.edges, this.meta, []];
|
|
83
|
+
if (sql.startsWith('fn::query::register')) return [null, ...snapshot()];
|
|
84
|
+
if (sql.startsWith('SELECT out, version FROM')) return snapshot();
|
|
85
|
+
if (sql === 'SELECT * FROM $ids') {
|
|
86
|
+
const rows = (vars!.ids as RecordId[])
|
|
87
|
+
.map((rid) => this.bodies.get(`${rid.table.name}:${rid.id}`))
|
|
88
|
+
.filter(Boolean);
|
|
89
|
+
return [rows];
|
|
90
|
+
}
|
|
91
|
+
if (sql.startsWith('LIVE SELECT')) return [this.liveId];
|
|
92
|
+
if (sql.startsWith('fn::query::heartbeat')) return [this.heartbeatGone ? [] : [{ id: 'q' }]];
|
|
93
|
+
if (sql.startsWith('fn::query::unsubscribe'))
|
|
94
|
+
return sql.split(';').map(() => ({ released: true }));
|
|
95
|
+
if (sql.startsWith('KILL')) return [null];
|
|
96
|
+
if (sql.startsWith('RETURN')) return ['answer'];
|
|
97
|
+
throw new Error(`unscripted: ${sql}`);
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
liveOf(_id: unknown) {
|
|
101
|
+
return Promise.resolve({
|
|
102
|
+
subscribe: (cb: (m: { action: string; value: unknown }) => void) => {
|
|
103
|
+
this.liveCb = cb;
|
|
104
|
+
return () => {
|
|
105
|
+
this.liveCb = null;
|
|
106
|
+
};
|
|
107
|
+
},
|
|
108
|
+
kill: async () => {
|
|
109
|
+
this.killed = true;
|
|
110
|
+
},
|
|
111
|
+
});
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
events = new Map<string, Array<() => void>>();
|
|
115
|
+
subscribe(event: string, cb: () => void): () => void {
|
|
116
|
+
this.events.set(event, [...(this.events.get(event) ?? []), cb]);
|
|
117
|
+
return () =>
|
|
118
|
+
this.events.set(
|
|
119
|
+
event,
|
|
120
|
+
(this.events.get(event) ?? []).filter((x) => x !== cb)
|
|
121
|
+
);
|
|
122
|
+
}
|
|
123
|
+
fire(event: string): void {
|
|
124
|
+
for (const cb of this.events.get(event) ?? []) cb();
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
emit(action: string, value: unknown): void {
|
|
128
|
+
this.liveCb?.({ action, value });
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
put(
|
|
132
|
+
rid: RecordId,
|
|
133
|
+
version: number,
|
|
134
|
+
extra: Record<string, unknown> = {}
|
|
135
|
+
): Record<string, unknown> {
|
|
136
|
+
const row = body(rid, extra);
|
|
137
|
+
this.bodies.set(`${rid.table.name}:${rid.id}`, row);
|
|
138
|
+
this.edges = [
|
|
139
|
+
...this.edges.filter((e) => String(e.out.id) !== String(rid.id)),
|
|
140
|
+
{ out: rid, version },
|
|
141
|
+
];
|
|
142
|
+
return row;
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
const tick = (ms = 0) => new Promise((r) => setTimeout(r, ms));
|
|
147
|
+
|
|
148
|
+
function feedWith(fake: FakeSurreal, over: Partial<Parameters<typeof createLiveFeed>[0]> = {}) {
|
|
149
|
+
return createLiveFeed({
|
|
150
|
+
endpoint: 'https://db.example.com',
|
|
151
|
+
namespace: 'ns',
|
|
152
|
+
database: 'db',
|
|
153
|
+
token: aliceToken,
|
|
154
|
+
sessionId: 'sess',
|
|
155
|
+
surreal: fake as unknown as LiveSurreal,
|
|
156
|
+
...over,
|
|
157
|
+
});
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
describe('createLiveFeed', () => {
|
|
161
|
+
it('registers exactly what the full client sends for the same query and session', async () => {
|
|
162
|
+
const q = new QueryBuilder(schema, 'notification')
|
|
163
|
+
.where({ user: 'user:alice', read: false } as any)
|
|
164
|
+
.build();
|
|
165
|
+
|
|
166
|
+
// The full client: its own registerInput, then the register sagas.
|
|
167
|
+
const services = fakeServiceBundle<any>();
|
|
168
|
+
const a = fakeAdapters({ services: { 'remote.connect': () => new Promise(() => {}) } as any });
|
|
169
|
+
const runtime = new Runtime({
|
|
170
|
+
env: defaultEnv(schema),
|
|
171
|
+
adapters: a.adapters,
|
|
172
|
+
logger: services.logger,
|
|
173
|
+
tabId: 't',
|
|
174
|
+
});
|
|
175
|
+
const client = new Sp00kyClient<any>(
|
|
176
|
+
{
|
|
177
|
+
database: { namespace: 'ns', database: 'db' },
|
|
178
|
+
schema,
|
|
179
|
+
schemaSurql: '',
|
|
180
|
+
logLevel: 'silent',
|
|
181
|
+
} as any,
|
|
182
|
+
{
|
|
183
|
+
services,
|
|
184
|
+
runtime,
|
|
185
|
+
}
|
|
186
|
+
);
|
|
187
|
+
const input = (client as any).registerInput('notification', q.innerQuery, '10m');
|
|
188
|
+
const env = defaultEnv(schema);
|
|
189
|
+
const local = await runPure(registerLocal(env, input), {
|
|
190
|
+
state: {
|
|
191
|
+
...emptyState({ tabId: 't' }),
|
|
192
|
+
sessionId: 'sess',
|
|
193
|
+
userId: 'user:alice',
|
|
194
|
+
ownerSecret: 'owner-k',
|
|
195
|
+
},
|
|
196
|
+
handlers: {
|
|
197
|
+
'local.getById': () => null,
|
|
198
|
+
'ssp.register': () => ({
|
|
199
|
+
localArray: [],
|
|
200
|
+
timings: { parseMs: 0, planMs: 0, snapshotMs: 0, wallMs: 0 },
|
|
201
|
+
}),
|
|
202
|
+
},
|
|
203
|
+
});
|
|
204
|
+
let sent: { sql: string; vars: Record<string, unknown> } | null = null;
|
|
205
|
+
await runPure(registerRemote(env, local.result), {
|
|
206
|
+
state: local.state,
|
|
207
|
+
handlers: {
|
|
208
|
+
'remote.query': (e: any) => {
|
|
209
|
+
sent = { sql: e.sql, vars: e.vars };
|
|
210
|
+
throw new Error('captured');
|
|
211
|
+
},
|
|
212
|
+
},
|
|
213
|
+
});
|
|
214
|
+
|
|
215
|
+
const fake = new FakeSurreal();
|
|
216
|
+
const feed = feedWith(fake, { ownerSecret: 'owner-k' });
|
|
217
|
+
const sub = feed.subscribe(q, { onSet: () => {} });
|
|
218
|
+
await sub.ready;
|
|
219
|
+
const reg = fake.calls.find((c) => c.sql.startsWith('fn::query::register'))!;
|
|
220
|
+
expect(sent).not.toBeNull();
|
|
221
|
+
expect(reg.sql).toBe(sent!.sql);
|
|
222
|
+
expect(reg.vars).toEqual(sent!.vars);
|
|
223
|
+
expect(reg.sql).toContain('FROM $in->_00_list_ref_user_alice');
|
|
224
|
+
expect((reg.vars!.config as any).params.user).toBeInstanceOf(RecordId);
|
|
225
|
+
expect(sub.key).toBe(local.result);
|
|
226
|
+
expect(await queryKey({ surql: input.surql, params: input.params }, 'sess')).toBe(local.result);
|
|
227
|
+
expect(feed.userId).toBe('user:alice');
|
|
228
|
+
expect(fake.connect).toHaveBeenCalledWith('wss://db.example.com/rpc', expect.anything());
|
|
229
|
+
expect(fake.use).toHaveBeenCalledWith({ namespace: 'ns', database: 'db' });
|
|
230
|
+
expect(fake.authenticate).toHaveBeenCalledWith(aliceToken);
|
|
231
|
+
await feed.close();
|
|
232
|
+
await client.close();
|
|
233
|
+
});
|
|
234
|
+
|
|
235
|
+
it('loads the first set, lands FETCH bodies from LIVE, fetches bare ids, drops deletes', async () => {
|
|
236
|
+
const fake = new FakeSurreal();
|
|
237
|
+
const r1 = fake.put(n1, 1);
|
|
238
|
+
const feed = feedWith(fake);
|
|
239
|
+
const sets: unknown[][] = [];
|
|
240
|
+
const changes: any[] = [];
|
|
241
|
+
const sub = feed.subscribe(
|
|
242
|
+
{ surql: 'SELECT * FROM notification WHERE user = $auth.id;' },
|
|
243
|
+
{ onSet: (rows) => sets.push(rows), onChange: (c) => changes.push(c) }
|
|
244
|
+
);
|
|
245
|
+
expect(await sub.ready).toEqual([r1]);
|
|
246
|
+
expect(sets).toEqual([[r1]]);
|
|
247
|
+
expect(
|
|
248
|
+
fake.calls.some((c) => c.sql === 'LIVE SELECT * FROM _00_list_ref_user_alice FETCH out')
|
|
249
|
+
).toBe(true);
|
|
250
|
+
const hash = sub.key!;
|
|
251
|
+
const inRid = new RecordId('_00_query', hash);
|
|
252
|
+
|
|
253
|
+
// Inline body (FETCH out): no extra read.
|
|
254
|
+
const reads = fake.calls.length;
|
|
255
|
+
const r2 = body(n2, { title: 'inline' });
|
|
256
|
+
fake.emit('CREATE', { in: inRid, out: r2, version: 1 });
|
|
257
|
+
await tick(30);
|
|
258
|
+
expect(fake.calls.length).toBe(reads);
|
|
259
|
+
expect(sets.at(-1)).toEqual([r1, r2]);
|
|
260
|
+
expect(changes.at(-1)).toEqual({ added: [r2], updated: [], removed: [] });
|
|
261
|
+
|
|
262
|
+
// An older version of a held row is ignored; a newer one updates.
|
|
263
|
+
fake.emit('UPDATE', { in: inRid, out: body(n2, { title: 'stale' }), version: 1 });
|
|
264
|
+
const r2b = fake.put(n2, 2, { title: 'newer' });
|
|
265
|
+
fake.emit('UPDATE', { in: inRid, out: r2b, version: 2 });
|
|
266
|
+
await tick(30);
|
|
267
|
+
expect(changes.at(-1)).toEqual({ added: [], updated: [r2b], removed: [] });
|
|
268
|
+
|
|
269
|
+
// Bare id (a server that ignored FETCH): the body is read.
|
|
270
|
+
const r3 = fake.put(n3, 4);
|
|
271
|
+
fake.emit('CREATE', { in: inRid, out: n3, version: 4 });
|
|
272
|
+
await tick(60);
|
|
273
|
+
expect(fake.calls.at(-1)!.sql).toBe('SELECT * FROM $ids');
|
|
274
|
+
expect(changes.at(-1)).toEqual({ added: [r3], updated: [], removed: [] });
|
|
275
|
+
|
|
276
|
+
// Another view's edge and subquery children are not ours.
|
|
277
|
+
fake.emit('CREATE', {
|
|
278
|
+
in: new RecordId('_00_query', 'other'),
|
|
279
|
+
out: body(new RecordId('notification', 'x')),
|
|
280
|
+
version: 1,
|
|
281
|
+
});
|
|
282
|
+
fake.emit('CREATE', {
|
|
283
|
+
in: inRid,
|
|
284
|
+
out: body(new RecordId('notification', 'child')),
|
|
285
|
+
version: 1,
|
|
286
|
+
parent: 'notification:n1',
|
|
287
|
+
});
|
|
288
|
+
await tick(30);
|
|
289
|
+
expect(sub.rows()).toHaveLength(3);
|
|
290
|
+
|
|
291
|
+
fake.edges = fake.edges.filter((e) => e.out.id !== 'n1');
|
|
292
|
+
fake.emit('DELETE', { in: inRid, out: n1, version: 1 });
|
|
293
|
+
await tick(30);
|
|
294
|
+
expect(changes.at(-1)).toEqual({ added: [], updated: [], removed: [r1] });
|
|
295
|
+
expect(sub.rows()).toEqual([r2b, r3]);
|
|
296
|
+
|
|
297
|
+
// `out: null` (unreadable or deleted row): membership is re-read and diffed.
|
|
298
|
+
fake.edges = fake.edges.filter((e) => e.out.id !== 'n3');
|
|
299
|
+
fake.emit('DELETE', { in: inRid, out: null, version: 4 });
|
|
300
|
+
await tick(120);
|
|
301
|
+
expect(sub.rows()).toEqual([r2b]);
|
|
302
|
+
expect(await feed.idle({ timeoutMs: 2000, quietMs: 20 })).toBe(true);
|
|
303
|
+
await feed.close();
|
|
304
|
+
});
|
|
305
|
+
|
|
306
|
+
it('shares one view between identical subscriptions and releases it with the last one', async () => {
|
|
307
|
+
const fake = new FakeSurreal();
|
|
308
|
+
fake.put(n1, 1);
|
|
309
|
+
const feed = feedWith(fake);
|
|
310
|
+
const a = feed.subscribe({ surql: 'SELECT * FROM notification;' }, { onSet: () => {} });
|
|
311
|
+
await a.ready;
|
|
312
|
+
const seen: unknown[][] = [];
|
|
313
|
+
const b = feed.subscribe(
|
|
314
|
+
{ surql: 'SELECT * FROM notification;' },
|
|
315
|
+
{ onSet: (rows) => seen.push(rows) }
|
|
316
|
+
);
|
|
317
|
+
await b.ready;
|
|
318
|
+
expect(seen).toHaveLength(1);
|
|
319
|
+
expect(fake.calls.filter((c) => c.sql.startsWith('fn::query::register'))).toHaveLength(1);
|
|
320
|
+
await a.unsubscribe();
|
|
321
|
+
expect(fake.calls.some((c) => c.sql.startsWith('fn::query::unsubscribe'))).toBe(false);
|
|
322
|
+
await b.unsubscribe();
|
|
323
|
+
const release = fake.calls.find((c) => c.sql.startsWith('fn::query::unsubscribe'))!;
|
|
324
|
+
expect(release.vars!.id).toEqual(new RecordId('_00_query', b.key!));
|
|
325
|
+
await feed.close();
|
|
326
|
+
});
|
|
327
|
+
|
|
328
|
+
it('close() kills LIVE, releases every view, closes the socket; idle waits for the first set', async () => {
|
|
329
|
+
const fake = new FakeSurreal();
|
|
330
|
+
fake.put(n1, 1);
|
|
331
|
+
const feed = feedWith(fake, { token: async () => aliceToken });
|
|
332
|
+
const one = feed.subscribe({ surql: 'SELECT * FROM notification;' }, { onSet: () => {} });
|
|
333
|
+
const two = feed.subscribe(
|
|
334
|
+
{ surql: 'SELECT * FROM notification WHERE read = false;' },
|
|
335
|
+
{ onSet: () => {} }
|
|
336
|
+
);
|
|
337
|
+
expect(await feed.idle({ timeoutMs: 3000, quietMs: 20 })).toBe(true);
|
|
338
|
+
expect(one.rows()).toHaveLength(1);
|
|
339
|
+
await feed.close();
|
|
340
|
+
expect(fake.killed).toBe(true);
|
|
341
|
+
const release = fake.calls.find((c) => c.sql.includes('fn::query::unsubscribe($id0)'))!;
|
|
342
|
+
expect(release.sql).toContain('fn::query::unsubscribe($id1)');
|
|
343
|
+
expect([release.vars!.id0, release.vars!.id1]).toEqual(
|
|
344
|
+
expect.arrayContaining([
|
|
345
|
+
new RecordId('_00_query', one.key!),
|
|
346
|
+
new RecordId('_00_query', two.key!),
|
|
347
|
+
])
|
|
348
|
+
);
|
|
349
|
+
expect(fake.closed).toBe(true);
|
|
350
|
+
expect(feed.closed).toBe(true);
|
|
351
|
+
await feed.close();
|
|
352
|
+
await expect(feed.query('RETURN 1')).rejects.toBeInstanceOf(LiveFeedError);
|
|
353
|
+
expect(await feed.idle()).toBe(false);
|
|
354
|
+
});
|
|
355
|
+
|
|
356
|
+
it('a refused token calls onUnauthorized and rejects the subscription', async () => {
|
|
357
|
+
const fake = new FakeSurreal();
|
|
358
|
+
fake.authError = new Error('There was a problem with authentication');
|
|
359
|
+
const onUnauthorized = vi.fn();
|
|
360
|
+
const onError = vi.fn();
|
|
361
|
+
const feed = feedWith(fake, { onUnauthorized });
|
|
362
|
+
const sub = feed.subscribe(
|
|
363
|
+
{ surql: 'SELECT * FROM notification;' },
|
|
364
|
+
{ onSet: () => {}, onError }
|
|
365
|
+
);
|
|
366
|
+
await expect(sub.ready).rejects.toMatchObject({ code: 'unauthorized' });
|
|
367
|
+
expect(onUnauthorized).toHaveBeenCalledTimes(1);
|
|
368
|
+
expect(onError).toHaveBeenCalledTimes(1);
|
|
369
|
+
expect(fake.closed).toBe(true);
|
|
370
|
+
});
|
|
371
|
+
|
|
372
|
+
it('anonymous feeds use the anon list_ref table; query() runs on the feed connection', async () => {
|
|
373
|
+
const fake = new FakeSurreal();
|
|
374
|
+
const feed = feedWith(fake, { token: undefined });
|
|
375
|
+
expect(await feed.query('RETURN fn::push::info()')).toEqual(['answer']);
|
|
376
|
+
expect(fake.authenticate).not.toHaveBeenCalled();
|
|
377
|
+
const sub = feed.subscribe({ surql: 'SELECT * FROM notification;' }, { onSet: () => {} });
|
|
378
|
+
await sub.ready;
|
|
379
|
+
expect(feed.listRefTable).toBe('_00_list_ref_anon');
|
|
380
|
+
await feed.close();
|
|
381
|
+
});
|
|
382
|
+
|
|
383
|
+
it("an anonymous feed's LIVE hears only its own sockets, earlier ones included after a reconnect", async () => {
|
|
384
|
+
const fake = new FakeSurreal();
|
|
385
|
+
let sid = 0;
|
|
386
|
+
const answer = fake.answer.bind(fake);
|
|
387
|
+
fake.answer = (sql, vars) =>
|
|
388
|
+
sql === 'RETURN <string>session::id()' ? [`sid-${++sid}`] : answer(sql, vars);
|
|
389
|
+
const feed = feedWith(fake, { token: undefined });
|
|
390
|
+
const sub = feed.subscribe({ surql: 'SELECT * FROM notification;' }, { onSet: () => {} });
|
|
391
|
+
await sub.ready;
|
|
392
|
+
fake.fire('disconnected');
|
|
393
|
+
fake.fire('connected');
|
|
394
|
+
await tick(60);
|
|
395
|
+
const lives = fake.calls.filter((c) => c.sql.startsWith('LIVE SELECT'));
|
|
396
|
+
expect(lives.map((c) => c.sql)).toEqual([
|
|
397
|
+
'LIVE SELECT * FROM _00_list_ref_anon WHERE clientId = <string>session::id() OR clientId IN $sids FETCH out',
|
|
398
|
+
'LIVE SELECT * FROM _00_list_ref_anon WHERE clientId = <string>session::id() OR clientId IN $sids FETCH out',
|
|
399
|
+
]);
|
|
400
|
+
// The view was registered on the first socket and is not re-registered,
|
|
401
|
+
// so its edges keep naming `sid-1`: the second LIVE must still hear them.
|
|
402
|
+
expect(lives[1].vars).toEqual({ sids: ['sid-1'] });
|
|
403
|
+
await feed.close();
|
|
404
|
+
});
|
|
405
|
+
|
|
406
|
+
it('heartbeats and re-registers a view the server reclaimed', async () => {
|
|
407
|
+
vi.useFakeTimers({ shouldAdvanceTime: true });
|
|
408
|
+
try {
|
|
409
|
+
const fake = new FakeSurreal();
|
|
410
|
+
fake.put(n1, 1);
|
|
411
|
+
const feed = feedWith(fake, { ttl: '20s' });
|
|
412
|
+
const sub = feed.subscribe({ surql: 'SELECT * FROM notification;' }, { onSet: () => {} });
|
|
413
|
+
await sub.ready;
|
|
414
|
+
fake.heartbeatGone = true;
|
|
415
|
+
await vi.advanceTimersByTimeAsync(10_000);
|
|
416
|
+
expect(fake.calls.some((c) => c.sql.startsWith('fn::query::heartbeat($id0)'))).toBe(true);
|
|
417
|
+
const registers = fake.calls.filter((c) => c.sql.startsWith('fn::query::register'));
|
|
418
|
+
expect(registers).toHaveLength(2);
|
|
419
|
+
// The re-registration proves it owns the view with the secret it was
|
|
420
|
+
// registered with (a fresh one per feed, at least 256 bits).
|
|
421
|
+
const owners = registers.map((c) => (c.vars!.config as { owner?: string }).owner);
|
|
422
|
+
expect(owners[0]).toMatch(/^[0-9a-f]{64}$/);
|
|
423
|
+
expect(owners[1]).toBe(owners[0]);
|
|
424
|
+
await feed.close();
|
|
425
|
+
} finally {
|
|
426
|
+
vi.useRealTimers();
|
|
427
|
+
}
|
|
428
|
+
});
|
|
429
|
+
|
|
430
|
+
it('after a reconnect: LIVE again and every view re-read (changes in the gap are not lost)', async () => {
|
|
431
|
+
const fake = new FakeSurreal();
|
|
432
|
+
fake.put(n1, 1);
|
|
433
|
+
const feed = feedWith(fake);
|
|
434
|
+
const changes: any[] = [];
|
|
435
|
+
const sub = feed.subscribe(
|
|
436
|
+
{ surql: 'SELECT * FROM notification;' },
|
|
437
|
+
{ onSet: () => {}, onChange: (c) => changes.push(c) }
|
|
438
|
+
);
|
|
439
|
+
await sub.ready;
|
|
440
|
+
fake.fire('disconnected');
|
|
441
|
+
const r2 = fake.put(n2, 1);
|
|
442
|
+
fake.fire('connected');
|
|
443
|
+
await tick(120);
|
|
444
|
+
expect(fake.calls.filter((c) => c.sql.startsWith('LIVE SELECT'))).toHaveLength(2);
|
|
445
|
+
expect(changes.at(-1)).toEqual({ added: [r2], updated: [], removed: [] });
|
|
446
|
+
await feed.close();
|
|
447
|
+
expect([...fake.events.values()].every((l) => l.length === 0)).toBe(true);
|
|
448
|
+
});
|
|
449
|
+
|
|
450
|
+
it('falls back to a plain LIVE (bodies read per edge) when the server refuses FETCH', async () => {
|
|
451
|
+
const fake = new FakeSurreal();
|
|
452
|
+
fake.put(n1, 1);
|
|
453
|
+
const answer = fake.answer.bind(fake);
|
|
454
|
+
fake.answer = (sql, vars) => {
|
|
455
|
+
if (sql.endsWith('FETCH out')) throw new Error('Parse error: FETCH not supported on LIVE');
|
|
456
|
+
return answer(sql, vars);
|
|
457
|
+
};
|
|
458
|
+
const onError = vi.fn();
|
|
459
|
+
const feed = feedWith(fake, { onError });
|
|
460
|
+
const sub = feed.subscribe({ surql: 'SELECT * FROM notification;' }, { onSet: () => {} });
|
|
461
|
+
await sub.ready;
|
|
462
|
+
expect(onError).toHaveBeenCalledTimes(1);
|
|
463
|
+
expect(fake.calls.filter((c) => c.sql.startsWith('LIVE SELECT')).map((c) => c.sql)).toEqual([
|
|
464
|
+
'LIVE SELECT * FROM _00_list_ref_user_alice FETCH out',
|
|
465
|
+
'LIVE SELECT * FROM _00_list_ref_user_alice',
|
|
466
|
+
]);
|
|
467
|
+
const r2 = fake.put(n2, 1);
|
|
468
|
+
fake.emit('CREATE', { in: new RecordId('_00_query', sub.key!), out: n2, version: 1 });
|
|
469
|
+
await tick(60);
|
|
470
|
+
expect(sub.rows()).toEqual([body(n1), r2]);
|
|
471
|
+
await feed.close();
|
|
472
|
+
});
|
|
473
|
+
|
|
474
|
+
it('waits out a materializing view before delivering the first set', async () => {
|
|
475
|
+
const fake = new FakeSurreal();
|
|
476
|
+
fake.meta = { rowCount: 1, state: 'materializing' };
|
|
477
|
+
const feed = feedWith(fake);
|
|
478
|
+
const sub = feed.subscribe({ surql: 'SELECT * FROM notification;' }, { onSet: () => {} });
|
|
479
|
+
setTimeout(() => {
|
|
480
|
+
fake.put(n1, 1);
|
|
481
|
+
fake.meta = { rowCount: 1, state: 'ready' };
|
|
482
|
+
}, 200);
|
|
483
|
+
expect(await sub.ready).toHaveLength(1);
|
|
484
|
+
await feed.close();
|
|
485
|
+
});
|
|
486
|
+
});
|
|
487
|
+
|
|
488
|
+
describe('live feed helpers', () => {
|
|
489
|
+
it('normalizes endpoints and query inputs', async () => {
|
|
490
|
+
expect(liveEndpoint('https://h.example')).toBe('wss://h.example/rpc');
|
|
491
|
+
expect(liveEndpoint('http://localhost:8000/rpc')).toBe('ws://localhost:8000/rpc');
|
|
492
|
+
expect(liveEndpoint('wss://h/rpc')).toBe('wss://h/rpc');
|
|
493
|
+
expect(liveEndpoint('not a url')).toBe('not a url');
|
|
494
|
+
expect(liveQueryInput({ surql: 'SELECT * FROM thing WHERE a = $a', params: { a: 1 } })).toEqual(
|
|
495
|
+
{
|
|
496
|
+
table: 'thing',
|
|
497
|
+
surql: 'SELECT * FROM thing WHERE a = $a',
|
|
498
|
+
params: { a: 1 },
|
|
499
|
+
}
|
|
500
|
+
);
|
|
501
|
+
const inner = new QueryBuilder(schema, 'notification')
|
|
502
|
+
.where({ user: 'user:bob' } as any)
|
|
503
|
+
.build().innerQuery;
|
|
504
|
+
const fromInner = liveQueryInput(inner as any);
|
|
505
|
+
expect(fromInner.table).toBe('notification');
|
|
506
|
+
expect(fromInner.params.user).toBeInstanceOf(RecordId);
|
|
507
|
+
expect(() => liveQueryInput({} as any)).toThrow(TypeError);
|
|
508
|
+
expect(await queryKey({ surql: 'x', params: {} }, null)).toBe(
|
|
509
|
+
await sha256Hex(queryHashInput({ surql: 'x', params: {} }, null))
|
|
510
|
+
);
|
|
511
|
+
});
|
|
512
|
+
});
|