@spooky-sync/core 1.0.0-beta.1 → 1.0.0-beta.10
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 +4 -3
- package/dist/index.d.ts +169 -9
- package/dist/index.js +4512 -2338
- package/dist/rows-worker.d.ts +1 -0
- package/dist/rows-worker.js +2639 -0
- package/dist/sqlite-open.js +1 -1
- package/dist/sqlite-worker.js +1 -1
- package/dist/types.d.ts +129 -13
- package/package.json +9 -4
- package/scripts/check-worker-entries.mjs +15 -2
- package/skills/sp00ky-core/SKILL.md +2 -0
- package/src/client/bucket-handle.ts +21 -1
- package/src/client/eager-paint.test.ts +82 -0
- package/src/client/services.ts +4 -1
- package/src/client/sp00ky-client.test.ts +143 -1
- package/src/client/sp00ky-client.ts +157 -19
- package/src/index.ts +9 -0
- package/src/kernel/effects.ts +12 -2
- package/src/kernel/interpreter.test.ts +17 -0
- package/src/kernel/interpreter.ts +5 -2
- package/src/modules/channel/hub.test.ts +223 -0
- package/src/modules/channel/hub.ts +355 -0
- package/src/modules/channel/index.ts +358 -14
- package/src/modules/channel/room.test.ts +340 -0
- package/src/modules/channel/room.ts +367 -0
- package/src/modules/channel/rooms.fixture.ts +383 -0
- package/src/modules/channel/share.test.ts +535 -0
- package/src/modules/channel/webrtc.ts +2 -2
- package/src/modules/devtools/storage-info.ts +4 -3
- package/src/query/materialize.saga.test.ts +16 -0
- package/src/query/materialize.saga.ts +7 -26
- package/src/query/materialize.ts +79 -3
- package/src/query/register.saga.test.ts +61 -0
- package/src/query/register.saga.ts +39 -2
- package/src/services/database/cache-engine.ts +17 -3
- package/src/services/database/engine-factory.ts +7 -0
- package/src/services/database/index.ts +1 -0
- package/src/services/database/rows-cache-engine.test.ts +1014 -0
- package/src/services/database/rows-cache-engine.ts +921 -0
- package/src/services/database/rows-exec.integration.test.ts +589 -0
- package/src/services/database/rows-exec.ts +1027 -0
- package/src/services/database/rows-prewarm.ts +225 -0
- package/src/services/database/rows-store.test.ts +635 -0
- package/src/services/database/rows-store.ts +1208 -0
- package/src/services/database/rows-transport.fixture.ts +151 -0
- package/src/services/database/rows-worker.ts +588 -0
- package/src/services/database/sqlite-cache-engine.test.ts +22 -1
- package/src/services/database/sqlite-cache-engine.ts +55 -34
- package/src/services/database/sqlite-transport.ts +7 -5
- package/src/services/tabs/support.ts +6 -4
- package/src/types.ts +39 -6
- package/tsdown.config.ts +42 -1
- package/vitest.config.ts +4 -0
|
@@ -6,6 +6,7 @@ import { fakeAdapters } from '../testing/adapters';
|
|
|
6
6
|
import { fakeServiceBundle } from '../testing/fake-services';
|
|
7
7
|
import { defaultEnv } from '../query/env';
|
|
8
8
|
import type { StatementResult } from '../kernel/effects';
|
|
9
|
+
import { FakeRelay, settle } from '../modules/channel/rooms.fixture';
|
|
9
10
|
|
|
10
11
|
const schema = { tables: [{ name: 'thing', columns: { a: {} } }], backends: { api: { outboxTable: 'thing', routes: { go: { args: {} } } } } } as any;
|
|
11
12
|
const config = { database: { namespace: 'n', database: 'd' }, schema, schemaSurql: '', logLevel: 'silent' } as any;
|
|
@@ -113,6 +114,85 @@ describe('Sp00kyClient facade', () => {
|
|
|
113
114
|
expect(a.calls.filter(([n]) => n === 'service.local.switchStore').map(([, args]) => args)).toEqual([['anon']]);
|
|
114
115
|
});
|
|
115
116
|
|
|
117
|
+
it('peekQuery hands back what the store kept for a query, with no init and no run', () => {
|
|
118
|
+
const { client, services, a } = makeClient();
|
|
119
|
+
const query = client.query('thing', {}).build();
|
|
120
|
+
const asked: unknown[] = [];
|
|
121
|
+
(services.local as any).peekSelect = (plan: any, _params: unknown, opts: { paintKey: string }) => {
|
|
122
|
+
asked.push([plan.table, opts.paintKey]);
|
|
123
|
+
return [{ id: 'thing:1' }];
|
|
124
|
+
};
|
|
125
|
+
expect(client.peekQuery(query)).toEqual([{ id: 'thing:1' }]);
|
|
126
|
+
// The membership render's copy, named by what a page knows before the client is open.
|
|
127
|
+
expect(asked).toEqual([['thing', JSON.stringify({ surql: query.innerQuery.selectQuery.query, params: {} })]]);
|
|
128
|
+
expect(a.calls).toEqual([]);
|
|
129
|
+
expect(client.isLocalReady()).toBe(false);
|
|
130
|
+
// A store without a paint cache, or one that fails: nothing to paint, never an error.
|
|
131
|
+
(services.local as any).peekSelect = undefined;
|
|
132
|
+
expect(client.peekQuery(query)).toBeNull();
|
|
133
|
+
(services.local as any).peekSelect = () => {
|
|
134
|
+
throw new Error('storage');
|
|
135
|
+
};
|
|
136
|
+
expect(client.peekQuery(query)).toBeNull();
|
|
137
|
+
});
|
|
138
|
+
|
|
139
|
+
it('a query run before init waits for it', async () => {
|
|
140
|
+
const { client } = makeClient();
|
|
141
|
+
const query = client.query('thing', {}).build();
|
|
142
|
+
let hash: string | undefined;
|
|
143
|
+
const running = query.run().then((r) => {
|
|
144
|
+
hash = r.hash;
|
|
145
|
+
});
|
|
146
|
+
let ready = false;
|
|
147
|
+
void client.whenReady().then(() => {
|
|
148
|
+
ready = true;
|
|
149
|
+
});
|
|
150
|
+
await flush();
|
|
151
|
+
expect(hash).toBeUndefined();
|
|
152
|
+
expect(ready).toBe(false);
|
|
153
|
+
await client.init();
|
|
154
|
+
await running;
|
|
155
|
+
expect(ready).toBe(true);
|
|
156
|
+
expect(client.state.queries.has(hash!)).toBe(true);
|
|
157
|
+
});
|
|
158
|
+
|
|
159
|
+
it('CRDT fields and files asked for before init wait for it too', async () => {
|
|
160
|
+
const { client, services } = makeClient();
|
|
161
|
+
const opened: string[] = [];
|
|
162
|
+
(services.crdt as any).open = async (table: string, id: string, field: string) => (opened.push(`${table}/${id}/${field}`), {});
|
|
163
|
+
const field = client.openCrdtField('thing', 'thing:1', 'body');
|
|
164
|
+
// A handle of its own, so the test needs no bucket in the schema.
|
|
165
|
+
const touched: string[] = [];
|
|
166
|
+
const remote = new Proxy({}, { get: (_t, key) => (touched.push(String(key)), () => Promise.reject(new Error('remote')))});
|
|
167
|
+
const { BucketHandle } = await import('./bucket-handle');
|
|
168
|
+
const file = new BucketHandle('files', remote as any, null, undefined, () => (client.isLocalReady() ? undefined : client.whenReady())).exists('a.png');
|
|
169
|
+
file.catch(() => {});
|
|
170
|
+
await flush();
|
|
171
|
+
expect(opened).toEqual([]);
|
|
172
|
+
expect(touched).toEqual([]);
|
|
173
|
+
await client.init();
|
|
174
|
+
await field;
|
|
175
|
+
await file.catch(() => {});
|
|
176
|
+
expect(opened).toEqual(['thing/thing:1/body']);
|
|
177
|
+
expect(touched.length).toBeGreaterThan(0);
|
|
178
|
+
});
|
|
179
|
+
|
|
180
|
+
it('what waited for init fails with it', async () => {
|
|
181
|
+
const { client } = makeClient({
|
|
182
|
+
services: {
|
|
183
|
+
'local.connect': () => {
|
|
184
|
+
throw new Error('no store');
|
|
185
|
+
},
|
|
186
|
+
},
|
|
187
|
+
});
|
|
188
|
+
const running = client.query('thing', {}).build().run();
|
|
189
|
+
const writing = client.create('thing:1', { a: 1 });
|
|
190
|
+
await expect(client.init()).rejects.toThrow('no store');
|
|
191
|
+
await expect(client.whenReady()).rejects.toThrow('no store');
|
|
192
|
+
await expect(running).rejects.toThrow('no store');
|
|
193
|
+
await expect(writing).rejects.toThrow('no store');
|
|
194
|
+
});
|
|
195
|
+
|
|
116
196
|
it('queryRaw registers locally and returns the hash before any remote work; subscribers paint from the local store', async () => {
|
|
117
197
|
// Boot loads the view index: `thing:1` is vouched for, `thing:2` is an orphan and stays hidden.
|
|
118
198
|
const stored = (sql: string) =>
|
|
@@ -365,7 +445,7 @@ describe('Sp00kyClient facade (channels)', () => {
|
|
|
365
445
|
});
|
|
366
446
|
const runtime = new Runtime({ env: defaultEnv(chSchema, { materializeDebounceMs: 1 }), adapters: a.adapters, logger: services.logger, tabId: 'tab-test' });
|
|
367
447
|
const client = new Sp00kyClient<any>({ ...config, schema: chSchema, channels } as any, { services, runtime });
|
|
368
|
-
return { client, runtime };
|
|
448
|
+
return { client, runtime, services };
|
|
369
449
|
}
|
|
370
450
|
|
|
371
451
|
it('opens a channel, keeps ephemeral fields out of writes, scopes its own writes, and wires peer rows to the runtime', async () => {
|
|
@@ -425,4 +505,66 @@ describe('Sp00kyClient facade (channels)', () => {
|
|
|
425
505
|
ch.close();
|
|
426
506
|
await client.close();
|
|
427
507
|
});
|
|
508
|
+
|
|
509
|
+
it('shares writes with the user\'s other devices through the room relay', async () => {
|
|
510
|
+
const relay = new FakeRelay();
|
|
511
|
+
const g = globalThis as { WebSocket?: unknown };
|
|
512
|
+
const before = g.WebSocket;
|
|
513
|
+
g.WebSocket = relay.WebSocket;
|
|
514
|
+
try {
|
|
515
|
+
const channels = { relay: 'ws://relay.test/room', share: { tables: { room: true } } };
|
|
516
|
+
const phone = channelClient(channels);
|
|
517
|
+
const laptop = channelClient({ ...channels, relay: { url: 'ws://relay.test/room', direct: false } });
|
|
518
|
+
for (const device of [phone, laptop]) {
|
|
519
|
+
(device.services.remote as any).getAuthToken = () => 't-a';
|
|
520
|
+
await device.client.init();
|
|
521
|
+
(device.client as any).channels.setUser('user:a');
|
|
522
|
+
}
|
|
523
|
+
const states: string[] = [];
|
|
524
|
+
const stopStates = phone.client.subscribeShareState((s) => states.push(s.status));
|
|
525
|
+
await settle();
|
|
526
|
+
// One socket each, signed in with the session token, in the room of their user.
|
|
527
|
+
expect(relay.sockets.map((sock) => sock.sent[0])).toEqual([
|
|
528
|
+
expect.objectContaining({ t: 'hello', v: 1, token: 't-a' }),
|
|
529
|
+
expect.objectContaining({ t: 'hello', v: 1, token: 't-a' }),
|
|
530
|
+
]);
|
|
531
|
+
expect([...relay.rooms.keys()]).toEqual(['user:a']);
|
|
532
|
+
expect(phone.client.shareState()).toEqual({ status: 'connected', peers: ['user:a'] });
|
|
533
|
+
expect(states).toEqual(['connecting', 'connected']);
|
|
534
|
+
|
|
535
|
+
// The laptop shows nothing of the table yet: the write stays on the phone.
|
|
536
|
+
const ops = () => relay.sockets[0].sent.filter((f) => f.t === 'msg' && (f.d as any)?.m?.m?.t === 'op');
|
|
537
|
+
await phone.client.update('room', 'room:1', { a: 7 });
|
|
538
|
+
await settle();
|
|
539
|
+
expect(ops()).toEqual([]);
|
|
540
|
+
|
|
541
|
+
// Once a query on it is mounted there, the next write goes out.
|
|
542
|
+
const { hash } = await (laptop.client.query('room', {} as any) as any).build().run();
|
|
543
|
+
const stop = await laptop.client.subscribe(hash, () => {}, { immediate: true });
|
|
544
|
+
await settle();
|
|
545
|
+
await phone.client.update('room', 'room:1', { a: 8 });
|
|
546
|
+
await settle();
|
|
547
|
+
expect(ops().map((f) => (f.d as any).m.m)).toEqual([expect.objectContaining({ t: 'op', table: 'room', id: 'room:1', patch: { a: 8 } })]);
|
|
548
|
+
stop();
|
|
549
|
+
stopStates();
|
|
550
|
+
await phone.client.close();
|
|
551
|
+
await laptop.client.close();
|
|
552
|
+
await settle();
|
|
553
|
+
expect(relay.rooms.size).toBe(0);
|
|
554
|
+
} finally {
|
|
555
|
+
g.WebSocket = before;
|
|
556
|
+
}
|
|
557
|
+
});
|
|
558
|
+
|
|
559
|
+
it('says so when sharing is asked for without a relay', async () => {
|
|
560
|
+
const services = fakeServiceBundle<any>();
|
|
561
|
+
const warned: string[] = [];
|
|
562
|
+
(services.logger as any).warn = (_fields: unknown, msg: string) => warned.push(msg);
|
|
563
|
+
const a = fakeAdapters({ services: { 'hint.read': () => 'u1', 'local.usesSurqlSchema': () => false, 'auth.restoreSession': async () => null, 'auth.sessionAuthId': () => null, 'remote.connect': () => new Promise(() => {}) } });
|
|
564
|
+
const runtime = new Runtime({ env: defaultEnv(chSchema, { materializeDebounceMs: 1 }), adapters: a.adapters, logger: services.logger, tabId: 'tab-test' });
|
|
565
|
+
const client = new Sp00kyClient<any>({ ...config, schema: chSchema, channels: { share: { tables: { room: true } } } } as any, { services, runtime });
|
|
566
|
+
expect(warned.filter((m) => m.includes('channels.relay'))).toHaveLength(1);
|
|
567
|
+
expect(client.shareState().status).toBe('idle');
|
|
568
|
+
await client.close();
|
|
569
|
+
});
|
|
428
570
|
});
|
|
@@ -39,8 +39,10 @@ import type { FeatureFlagOptions, FeatureFlagOverride } from '../modules/feature
|
|
|
39
39
|
import { AppReleaseModule, AppReleaseHandle } from '../modules/app-release/index';
|
|
40
40
|
import type { AppReleaseOptions } from '../modules/app-release/index';
|
|
41
41
|
import { WebPushModule } from '../modules/web-push/index';
|
|
42
|
-
import { ChannelManager, type ChannelHandle } from '../modules/channel/index';
|
|
42
|
+
import { ChannelManager, type ChannelHandle, type ChannelState, type ChannelTransportFactory } from '../modules/channel/index';
|
|
43
43
|
import { surrealSignal, webrtcTransport } from '../modules/channel/webrtc';
|
|
44
|
+
import { roomLink, splitTransport } from '../modules/channel/room';
|
|
45
|
+
import { hubTransport } from '../modules/channel/hub';
|
|
44
46
|
import { DevToolsService } from '../modules/devtools/index';
|
|
45
47
|
import type { DevToolsQuerySource } from '../modules/devtools/index';
|
|
46
48
|
import { parseQueryParams, generateId } from '../utils/index';
|
|
@@ -59,7 +61,9 @@ import { boot } from '../boot/boot.saga';
|
|
|
59
61
|
import { preload } from '../boot/preload.saga';
|
|
60
62
|
import { DEGRADE_AFTER_FAILURES, OUTBOX_BATCH_SIZE, PUSH_TIMEOUT_MS } from '../kernel/constants';
|
|
61
63
|
import { Runtime } from './runtime';
|
|
62
|
-
import { createAdapters, createServices, createTabsCoordinator, type ServiceHost, type Services } from './services';
|
|
64
|
+
import { createAdapters, createServices, createTabsCoordinator, readBootBucketHint, type ServiceHost, type Services } from './services';
|
|
65
|
+
import { ANON_USER_ID } from '../modules/ref-tables';
|
|
66
|
+
import { paintKeyOf } from '../query/materialize';
|
|
63
67
|
import { BucketHandle, bucketSettings } from './bucket-handle';
|
|
64
68
|
import { ImpersonationBanner } from '../modules/auth/impersonation-banner';
|
|
65
69
|
import type { LeaderSyncHub, SyncForwarder } from '../services/tabs/coordinator';
|
|
@@ -79,6 +83,17 @@ export interface Sp00kyClientDeps<S extends SchemaStructure> {
|
|
|
79
83
|
* state read, or a subscription on the runtime; the engine's behaviour lives
|
|
80
84
|
* in the sagas.
|
|
81
85
|
*/
|
|
86
|
+
/** A promise and the two ways to settle it; settling twice does nothing. */
|
|
87
|
+
function deferred(): { promise: Promise<void>; resolve: () => void; reject: (error: unknown) => void } {
|
|
88
|
+
let resolve!: () => void;
|
|
89
|
+
let reject!: (error: unknown) => void;
|
|
90
|
+
const promise = new Promise<void>((res, rej) => {
|
|
91
|
+
resolve = res;
|
|
92
|
+
reject = rej;
|
|
93
|
+
});
|
|
94
|
+
return { promise, resolve, reject };
|
|
95
|
+
}
|
|
96
|
+
|
|
82
97
|
export class Sp00kyClient<S extends SchemaStructure> {
|
|
83
98
|
public readonly auth: AuthService<S>;
|
|
84
99
|
public readonly streamProcessor: StreamProcessorService;
|
|
@@ -144,8 +159,14 @@ export class Sp00kyClient<S extends SchemaStructure> {
|
|
|
144
159
|
this.streamProcessor = s.streamProcessor;
|
|
145
160
|
|
|
146
161
|
const liveQueryPort = {
|
|
147
|
-
|
|
148
|
-
|
|
162
|
+
// Feature flags and app releases register here, from boot (which has a
|
|
163
|
+
// session by the time it asks) and from hooks. A hook on a client that
|
|
164
|
+
// is not open yet has no session to register under: it waits, where it
|
|
165
|
+
// used to fail and only be tried again at the next sign-in.
|
|
166
|
+
query: async (table: string, surql: string, params: Record<string, unknown>, ttl: QueryTimeToLive) => {
|
|
167
|
+
if (this.runtime.state.sessionId === null) await this.ready.promise;
|
|
168
|
+
return this.runtime.run(registerLocal(this.env, { tableName: table, surql, params, ttl }));
|
|
169
|
+
},
|
|
149
170
|
subscribe: (hash: string, cb: (records: Record<string, any>[]) => void, options?: { immediate?: boolean }) =>
|
|
150
171
|
this.runtime.subscribe(hash, cb, options),
|
|
151
172
|
};
|
|
@@ -187,6 +208,30 @@ export class Sp00kyClient<S extends SchemaStructure> {
|
|
|
187
208
|
this.disposers.push(this.webPush.attach());
|
|
188
209
|
|
|
189
210
|
const channelsConfig = config.channels;
|
|
211
|
+
const relay = typeof channelsConfig?.relay === 'string' ? { url: channelsConfig.relay } : channelsConfig?.relay;
|
|
212
|
+
// Between users: a WebRTC link per pair of tabs, signaled through the database.
|
|
213
|
+
const mesh: ChannelTransportFactory = (hooks) =>
|
|
214
|
+
webrtcTransport(hooks, {
|
|
215
|
+
signal: surrealSignal(s.remote, s.connectionSupervisor, s.logger),
|
|
216
|
+
iceServers: channelsConfig?.iceServers,
|
|
217
|
+
logger: s.logger,
|
|
218
|
+
});
|
|
219
|
+
// Between the user's own devices: one link per browser to their room on the relay.
|
|
220
|
+
const room: ChannelTransportFactory | null = relay
|
|
221
|
+
? (hooks) =>
|
|
222
|
+
hubTransport(hooks, {
|
|
223
|
+
scope: (user) => `${config.database.namespace}/${config.database.database}/${user}`,
|
|
224
|
+
link: (linkHooks) =>
|
|
225
|
+
roomLink(linkHooks, {
|
|
226
|
+
url: relay.url,
|
|
227
|
+
direct: relay.direct,
|
|
228
|
+
token: () => s.remote.getAuthToken(),
|
|
229
|
+
iceServers: channelsConfig?.iceServers,
|
|
230
|
+
logger: s.logger,
|
|
231
|
+
}),
|
|
232
|
+
logger: s.logger,
|
|
233
|
+
})
|
|
234
|
+
: null;
|
|
190
235
|
this.channels = new ChannelManager(config.schema, {
|
|
191
236
|
config: channelsConfig,
|
|
192
237
|
logger: s.logger,
|
|
@@ -195,15 +240,14 @@ export class Sp00kyClient<S extends SchemaStructure> {
|
|
|
195
240
|
delete: (_table, id, ttlMs) => this.runtime.run(peerDelete(this.env, { recordId: id, ttlMs })),
|
|
196
241
|
read: (id) => this.runtime.run(readRow(id)),
|
|
197
242
|
},
|
|
198
|
-
transport:
|
|
199
|
-
channelsConfig?.transport ??
|
|
200
|
-
((hooks) =>
|
|
201
|
-
webrtcTransport(hooks, {
|
|
202
|
-
signal: surrealSignal(s.remote, s.connectionSupervisor, s.logger),
|
|
203
|
-
iceServers: channelsConfig?.iceServers,
|
|
204
|
-
logger: s.logger,
|
|
205
|
-
})),
|
|
243
|
+
transport: channelsConfig?.transport ?? splitTransport(room, mesh),
|
|
206
244
|
});
|
|
245
|
+
if (this.channels.sharing && !relay && !channelsConfig?.transport) {
|
|
246
|
+
s.logger.warn(
|
|
247
|
+
{ Category: 'sp00ky-client::channel' },
|
|
248
|
+
'channels.share is set without channels.relay: nothing reaches your other devices until a relay address is given'
|
|
249
|
+
);
|
|
250
|
+
}
|
|
207
251
|
if (this.channels.enabled) this.disposers.push(s.auth.subscribe((userId) => this.channels.setUser(userId)));
|
|
208
252
|
|
|
209
253
|
const querySource: DevToolsQuerySource = {
|
|
@@ -243,6 +287,11 @@ export class Sp00kyClient<S extends SchemaStructure> {
|
|
|
243
287
|
});
|
|
244
288
|
}
|
|
245
289
|
this.wireAdapters();
|
|
290
|
+
// Unobserved, a failed boot must not also be an unhandled rejection.
|
|
291
|
+
this.ready.promise.catch(() => {});
|
|
292
|
+
// The bucket `boot` is about to open, so the store can paint from it now
|
|
293
|
+
// (`peekQuery`). Alone in the store only: see `LocalStore.expectBucket`.
|
|
294
|
+
if (!s.tabs) s.local.expectBucket?.(readBootBucketHint() ?? ANON_USER_ID);
|
|
246
295
|
}
|
|
247
296
|
|
|
248
297
|
/** Adapter callbacks become runtime events; runtime events reach the legacy services. */
|
|
@@ -349,11 +398,39 @@ export class Sp00kyClient<S extends SchemaStructure> {
|
|
|
349
398
|
|
|
350
399
|
// ---- lifecycle ---------------------------------------------------------------
|
|
351
400
|
|
|
401
|
+
/** Settled by `init`: what a call made before the client is open waits on. */
|
|
402
|
+
private ready = deferred();
|
|
403
|
+
|
|
352
404
|
async init(): Promise<void> {
|
|
353
|
-
|
|
405
|
+
try {
|
|
406
|
+
await this.runtime.run(boot(this.env, { sharedTabs: this.services.tabs !== null }));
|
|
407
|
+
this.ready.resolve();
|
|
408
|
+
} catch (error) {
|
|
409
|
+
this.ready.reject(error);
|
|
410
|
+
throw error;
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
/**
|
|
415
|
+
* Resolves once `init()` has finished, and rejects with its error if it
|
|
416
|
+
* fails. A page that renders before the client is open (a provider's
|
|
417
|
+
* `eager` mode) awaits this for whatever must not run earlier.
|
|
418
|
+
*/
|
|
419
|
+
whenReady(): Promise<void> {
|
|
420
|
+
return this.ready.promise;
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
/**
|
|
424
|
+
* Queries and writes need the open client: its store, its session. Asked
|
|
425
|
+
* for earlier, they wait for `init()` to finish, so a component may register
|
|
426
|
+
* a query on its first render and need not know whether the client is open.
|
|
427
|
+
*/
|
|
428
|
+
private opened(): Promise<void> | undefined {
|
|
429
|
+
return this.runtime.state.localReady ? undefined : this.ready.promise;
|
|
354
430
|
}
|
|
355
431
|
|
|
356
432
|
async close(): Promise<void> {
|
|
433
|
+
this.ready.reject(new Error('Sp00kyClient: closed before it was ready'));
|
|
357
434
|
const s = this.services;
|
|
358
435
|
s.connectionSupervisor.dispose();
|
|
359
436
|
for (const dispose of this.disposers.splice(0)) dispose();
|
|
@@ -404,10 +481,35 @@ export class Sp00kyClient<S extends SchemaStructure> {
|
|
|
404
481
|
};
|
|
405
482
|
}
|
|
406
483
|
|
|
407
|
-
private initQuery(table: string, q: InnerQuery<any, any, any>, ttl: QueryTimeToLive): Promise<string> {
|
|
484
|
+
private async initQuery(table: string, q: InnerQuery<any, any, any>, ttl: QueryTimeToLive): Promise<string> {
|
|
485
|
+
await this.opened();
|
|
408
486
|
return this.runtime.run(registerLocal(this.env, this.registerInput(table, q, ttl)));
|
|
409
487
|
}
|
|
410
488
|
|
|
489
|
+
/**
|
|
490
|
+
* The rows this query rendered the last time this browser had the app open,
|
|
491
|
+
* handed back at once and with no need for `init()` to have run: something
|
|
492
|
+
* for a component to render on its first pass, where it would have rendered
|
|
493
|
+
* an empty list. `null` when the local store keeps no such copy (only
|
|
494
|
+
* `localEngine: 'rows'` with its paint cache does, and not with shared
|
|
495
|
+
* tabs), or has none for this query.
|
|
496
|
+
*
|
|
497
|
+
* They are rows to paint from, not a result. The query still has to be run
|
|
498
|
+
* and subscribed to; what that delivers is the answer, and it replaces these
|
|
499
|
+
* rows when it differs.
|
|
500
|
+
*/
|
|
501
|
+
peekQuery(finalQuery: FinalQuery<S, any, any, any, any, any>): Record<string, any>[] | null {
|
|
502
|
+
try {
|
|
503
|
+
const q = finalQuery.innerQuery;
|
|
504
|
+
const input = this.registerInput(q.tableName, q, '10m');
|
|
505
|
+
if (!input.plan) return null;
|
|
506
|
+
// The membership render's rows only: a cold scan's are filtered by state the closed client does not have.
|
|
507
|
+
return this.services.local.peekSelect?.(input.plan, input.params, { paintKey: paintKeyOf(input, []) }) ?? null;
|
|
508
|
+
} catch {
|
|
509
|
+
return null;
|
|
510
|
+
}
|
|
511
|
+
}
|
|
512
|
+
|
|
411
513
|
/**
|
|
412
514
|
* The raw remote escape hatches bypass the query builder, so their shapes
|
|
413
515
|
* can never be on the server's query allowlist. When the generated schema
|
|
@@ -424,6 +526,7 @@ export class Sp00kyClient<S extends SchemaStructure> {
|
|
|
424
526
|
|
|
425
527
|
async queryRaw(sql: string, params: Record<string, any>, ttl: QueryTimeToLive): Promise<string> {
|
|
426
528
|
this.assertRawRemoteAllowed('queryRaw');
|
|
529
|
+
await this.opened();
|
|
427
530
|
const tableName = sql.split('FROM ')[1]?.split(' ')[0] ?? '';
|
|
428
531
|
return this.runtime.run(registerLocal(this.env, { tableName, surql: sql, params, ttl }));
|
|
429
532
|
}
|
|
@@ -435,6 +538,7 @@ export class Sp00kyClient<S extends SchemaStructure> {
|
|
|
435
538
|
*/
|
|
436
539
|
async preload(finalQuery: FinalQuery<S, any, any, any, any, any>, options?: PreloadOptions): Promise<void> {
|
|
437
540
|
const q = finalQuery.innerQuery;
|
|
541
|
+
await this.opened();
|
|
438
542
|
await this.runtime.run(preload(this.env, this.registerInput(q.tableName, q, '10m')), { signal: options?.signal });
|
|
439
543
|
}
|
|
440
544
|
|
|
@@ -442,7 +546,10 @@ export class Sp00kyClient<S extends SchemaStructure> {
|
|
|
442
546
|
if (!this.channels.enabled) return this.runtime.subscribe(queryHash, callback, options);
|
|
443
547
|
// Channel values (peer updates, ephemeral fields) are folded into what
|
|
444
548
|
// subscribers see, never into the store.
|
|
445
|
-
|
|
549
|
+
// With `channels.share`, the user's other devices are told what this
|
|
550
|
+
// query can show, and only send what it has a use for.
|
|
551
|
+
const def = this.channels.sharing ? this.runtime.state.queries.get(queryHash)?.def : undefined;
|
|
552
|
+
const tap = this.channels.tap(callback, def ? this.channels.interestOf(def.plan, def.params) : null);
|
|
446
553
|
const stop = this.runtime.subscribe(queryHash, tap.feed, options);
|
|
447
554
|
return () => {
|
|
448
555
|
stop();
|
|
@@ -474,12 +581,38 @@ export class Sp00kyClient<S extends SchemaStructure> {
|
|
|
474
581
|
setPeers: handle.setPeers,
|
|
475
582
|
setQueries: (next) => handle.setScopes(this.channelScopes(next)),
|
|
476
583
|
close: handle.close,
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
584
|
+
// Like every write, these wait for a client that is not open yet. A
|
|
585
|
+
// table the channel does not carry is still refused at once, in the call.
|
|
586
|
+
update: ((table: string, id: string, data: Record<string, unknown>, options?: UpdateOptions) => {
|
|
587
|
+
const scope = scoped(table);
|
|
588
|
+
return Promise.resolve(this.opened()).then(() => this.writeUpdate(table, id, data, options, scope));
|
|
589
|
+
}) as never,
|
|
590
|
+
create: ((id: string, data: Record<string, unknown>) => {
|
|
591
|
+
const scope = scoped(id.slice(0, id.indexOf(':')));
|
|
592
|
+
return Promise.resolve(this.opened()).then(() => this.writeCreate(id, data, scope));
|
|
593
|
+
}) as never,
|
|
594
|
+
delete: (table, id) => {
|
|
595
|
+
const scope = scoped(table);
|
|
596
|
+
return Promise.resolve(this.opened()).then(() => this.writeDelete(table, id, scope));
|
|
597
|
+
},
|
|
480
598
|
};
|
|
481
599
|
}
|
|
482
600
|
|
|
601
|
+
/**
|
|
602
|
+
* The link to this user's other devices (`channels.share`): `connected`
|
|
603
|
+
* with the user's id in `peers` while at least one other tab of theirs, in
|
|
604
|
+
* another browser, is in the room. `idle` when nothing is shared or nobody
|
|
605
|
+
* is signed in.
|
|
606
|
+
*/
|
|
607
|
+
shareState(): ChannelState {
|
|
608
|
+
return this.channels.ownState();
|
|
609
|
+
}
|
|
610
|
+
|
|
611
|
+
/** Called at once with `shareState()`, then on every change. */
|
|
612
|
+
subscribeShareState(callback: (state: ChannelState) => void): () => void {
|
|
613
|
+
return this.channels.subscribeOwn(callback);
|
|
614
|
+
}
|
|
615
|
+
|
|
483
616
|
private channelScopes(queries: ChannelQuery<S, any> | ReadonlyArray<ChannelQuery<S, any>>) {
|
|
484
617
|
const list = (Array.isArray(queries) ? queries : [queries]) as ReadonlyArray<ChannelQuery<S, any>>;
|
|
485
618
|
return list.map((q) => {
|
|
@@ -511,14 +644,17 @@ export class Sp00kyClient<S extends SchemaStructure> {
|
|
|
511
644
|
// ---- mutations ---------------------------------------------------------------
|
|
512
645
|
|
|
513
646
|
async create<T extends Record<string, unknown>>(id: string, data: T): Promise<T> {
|
|
647
|
+
await this.opened();
|
|
514
648
|
return (await this.writeCreate(id, data)) as T;
|
|
515
649
|
}
|
|
516
650
|
|
|
517
651
|
async update<T extends Record<string, unknown>>(table: string, id: string, data: Partial<T>, options?: UpdateOptions): Promise<T> {
|
|
652
|
+
await this.opened();
|
|
518
653
|
return (await this.writeUpdate(table, id, data as Record<string, unknown>, options)) as T;
|
|
519
654
|
}
|
|
520
655
|
|
|
521
656
|
async delete(table: string, id: string): Promise<void> {
|
|
657
|
+
await this.opened();
|
|
522
658
|
await this.writeDelete(table, id);
|
|
523
659
|
}
|
|
524
660
|
|
|
@@ -711,6 +847,8 @@ export class Sp00kyClient<S extends SchemaStructure> {
|
|
|
711
847
|
/** Open a `@crdt` field for editing. `draft` (from {@link createCrdtDraft})
|
|
712
848
|
* hands over edits made before the record existed. */
|
|
713
849
|
async openCrdtField(table: string, recordId: string, field: string, draft?: CrdtField): Promise<CrdtField> {
|
|
850
|
+
// Opening reads this device's unsent edits from the store: it has to be open.
|
|
851
|
+
await this.opened();
|
|
714
852
|
return this.services.crdt.open(table, recordId, field, draft);
|
|
715
853
|
}
|
|
716
854
|
|
|
@@ -727,7 +865,7 @@ export class Sp00kyClient<S extends SchemaStructure> {
|
|
|
727
865
|
}
|
|
728
866
|
|
|
729
867
|
bucket<B extends BucketNames<S>>(name: B): BucketHandle {
|
|
730
|
-
return new BucketHandle(name, this.services.remote, this.services.blobs, bucketSettings(this.config, name, this.services.logger));
|
|
868
|
+
return new BucketHandle(name, this.services.remote, this.services.blobs, bucketSettings(this.config, name, this.services.logger), () => this.opened());
|
|
731
869
|
}
|
|
732
870
|
|
|
733
871
|
getBlobCacheStats() {
|
package/src/index.ts
CHANGED
|
@@ -10,14 +10,21 @@ export {
|
|
|
10
10
|
unusedArgs,
|
|
11
11
|
type ChannelMessage,
|
|
12
12
|
type ChannelOp,
|
|
13
|
+
type ChannelRelayConfig,
|
|
14
|
+
type ChannelShareConfig,
|
|
15
|
+
type ChannelShareRule,
|
|
13
16
|
type ChannelState,
|
|
14
17
|
type ChannelStatus,
|
|
15
18
|
type ChannelTransport,
|
|
16
19
|
type ChannelTransportFactory,
|
|
20
|
+
type ChannelWire,
|
|
17
21
|
type ChannelsConfig,
|
|
22
|
+
type InterestMessage,
|
|
18
23
|
type PeerRef,
|
|
19
24
|
type TransportHooks,
|
|
20
25
|
} from './modules/channel/index';
|
|
26
|
+
export { roomLink, splitTransport, type RoomLink, type RoomLinkHooks, type RoomLinkOptions } from './modules/channel/room';
|
|
27
|
+
export { hubTransport, type HubOptions } from './modules/channel/hub';
|
|
21
28
|
export { webrtcTransport, surrealSignal, type SignalPort, type Signal, type OutgoingSignal } from './modules/channel/webrtc';
|
|
22
29
|
export {
|
|
23
30
|
FeatureFlagModule,
|
|
@@ -75,6 +82,8 @@ export type {
|
|
|
75
82
|
export type { FailedMutationRow as FailedMutation } from './mutation/rows';
|
|
76
83
|
export { semverGt } from './utils/semver';
|
|
77
84
|
export { LocalOpTimeoutError, DEFAULT_LOCAL_OP_TIMEOUT_MS } from './services/database/errors';
|
|
85
|
+
// Start the row store's worker ahead of the app (`localEngine: 'rows'`).
|
|
86
|
+
export { prewarmRows, ROWS_PREWARM_SNIPPET } from './services/database/rows-cache-engine';
|
|
78
87
|
export { fileToUint8Array, textToHtml } from './utils/index';
|
|
79
88
|
export {
|
|
80
89
|
blurhashSidecarPath,
|
package/src/kernel/effects.ts
CHANGED
|
@@ -35,7 +35,8 @@ export type Settled<T = unknown> = { ok: true; value: T } | { ok: false; error:
|
|
|
35
35
|
*/
|
|
36
36
|
export type Effect =
|
|
37
37
|
| { kind: 'local.query'; sql: string; vars?: Vars; epoch?: number }
|
|
38
|
-
| { kind: 'local.select'; plan: QueryPlan; params?: Vars }
|
|
38
|
+
| { kind: 'local.select'; plan: QueryPlan; params?: Vars; paintKey?: string }
|
|
39
|
+
| { kind: 'local.peekSelect'; plan: QueryPlan; params?: Vars; paintKey?: string }
|
|
39
40
|
| { kind: 'local.execute'; query: SealedQuery<unknown>; vars?: Vars; epoch?: number }
|
|
40
41
|
| { kind: 'local.getById'; table: string; id: unknown }
|
|
41
42
|
| { kind: 'local.upsert'; table: string; id: unknown; data: Record<string, unknown>; mode: 'replace' | 'merge' }
|
|
@@ -121,7 +122,16 @@ export type ServiceName = keyof ServiceCalls;
|
|
|
121
122
|
export const fx = {
|
|
122
123
|
local: {
|
|
123
124
|
query: (sql: string, vars?: Vars, epoch?: number): Effect => ({ kind: 'local.query', sql, vars, epoch }),
|
|
124
|
-
|
|
125
|
+
/** `paintKey` names the read for the store's paint cache: the same key peeks at its last answer. */
|
|
126
|
+
select: (plan: QueryPlan, params?: Vars, paintKey?: string): Effect =>
|
|
127
|
+
paintKey === undefined ? { kind: 'local.select', plan, params } : { kind: 'local.select', plan, params, paintKey },
|
|
128
|
+
/** What `select` answered under `paintKey` in an earlier page load, at once, or `null`. Rows to paint from, not a result. */
|
|
129
|
+
peekSelect: (plan: QueryPlan, params: Vars | undefined, paintKey: string): Effect => ({
|
|
130
|
+
kind: 'local.peekSelect',
|
|
131
|
+
plan,
|
|
132
|
+
params,
|
|
133
|
+
paintKey,
|
|
134
|
+
}),
|
|
125
135
|
execute: (query: SealedQuery<unknown>, vars?: Vars, epoch?: number): Effect => ({
|
|
126
136
|
kind: 'local.execute',
|
|
127
137
|
query,
|
|
@@ -40,6 +40,23 @@ describe('interpreter', () => {
|
|
|
40
40
|
expect(a.calls[0]).toEqual(['local.query', ['SELECT 1', { a: 1 }]]);
|
|
41
41
|
});
|
|
42
42
|
|
|
43
|
+
it('local.peekSelect asks a store that keeps a paint cache, and is null for one that does not', async () => {
|
|
44
|
+
const h = fakeHost();
|
|
45
|
+
const plan = { table: 't' } as any;
|
|
46
|
+
// No paint cache (the SurrealDB and SQLite engines): nothing to paint from.
|
|
47
|
+
expect(await createInterpreter(fakeAdapters().adapters, h.host)(fx.local.peekSelect(plan, {}, 'k'))).toBeNull();
|
|
48
|
+
// One that kept the read: its rows, asked for by the paint key.
|
|
49
|
+
const seen: unknown[] = [];
|
|
50
|
+
const kept = fakeAdapters({
|
|
51
|
+
local: { peekSelect: (p, params, options) => (seen.push([p, params, options]), [{ id: 't:1' }]) },
|
|
52
|
+
});
|
|
53
|
+
expect(await createInterpreter(kept.adapters, h.host)(fx.local.peekSelect(plan, { a: 1 }, 'k'))).toEqual([{ id: 't:1' }]);
|
|
54
|
+
expect(seen).toEqual([[plan, { a: 1 }, { paintKey: 'k' }]]);
|
|
55
|
+
// One that has the cache and not this read.
|
|
56
|
+
const missed = fakeAdapters({ local: { peekSelect: () => null } });
|
|
57
|
+
expect(await createInterpreter(missed.adapters, h.host)(fx.local.peekSelect(plan, {}, 'k'))).toBeNull();
|
|
58
|
+
});
|
|
59
|
+
|
|
43
60
|
it('ssp.register without a result throws; ssp.register uses default timings when the SSP reports none', async () => {
|
|
44
61
|
const empty = fakeAdapters({ ssp: { registerQueryPlan: () => undefined } });
|
|
45
62
|
const h = fakeHost();
|
|
@@ -9,7 +9,7 @@ import type { OutEvent, RuntimeEvent } from './events';
|
|
|
9
9
|
|
|
10
10
|
/** The five adapters plus the pure ports, as the interpreter sees them. */
|
|
11
11
|
export interface Adapters {
|
|
12
|
-
local: Pick<LocalStore, 'query' | 'execute' | 'select' | 'getById' | 'upsert' | 'delete'> & { readonly epoch: number };
|
|
12
|
+
local: Pick<LocalStore, 'query' | 'execute' | 'select' | 'peekSelect' | 'getById' | 'upsert' | 'delete'> & { readonly epoch: number };
|
|
13
13
|
remote: {
|
|
14
14
|
queryResponses(sql: string, vars?: Record<string, unknown>): Promise<StatementResult[]>;
|
|
15
15
|
/**
|
|
@@ -63,7 +63,10 @@ export function createInterpreter(adapters: Adapters, host: InterpreterHost): In
|
|
|
63
63
|
case 'local.query':
|
|
64
64
|
return adapters.local.query(effect.sql, effect.vars, effect.epoch === undefined ? undefined : { epoch: effect.epoch });
|
|
65
65
|
case 'local.select':
|
|
66
|
-
return adapters.local.select(effect.plan, effect.params);
|
|
66
|
+
return adapters.local.select(effect.plan, effect.params, effect.paintKey === undefined ? undefined : { paintKey: effect.paintKey });
|
|
67
|
+
case 'local.peekSelect':
|
|
68
|
+
// Synchronous in the store, and optional: only an engine that keeps a paint cache has one.
|
|
69
|
+
return adapters.local.peekSelect?.(effect.plan, effect.params, { paintKey: effect.paintKey }) ?? null;
|
|
67
70
|
case 'local.execute':
|
|
68
71
|
return adapters.local.execute(effect.query, effect.vars, effect.epoch === undefined ? undefined : { epoch: effect.epoch });
|
|
69
72
|
case 'local.getById':
|