@spooky-sync/core 0.0.1-canary.20 → 0.0.1-canary.201
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 +57 -0
- package/dist/index.d.ts +2184 -54
- package/dist/index.js +11515 -2399
- package/dist/otel/index.d.ts +2 -2
- package/dist/otel/index.js +6 -6
- package/dist/sqlite-open.js +276 -0
- package/dist/sqlite-worker.d.ts +1 -0
- package/dist/sqlite-worker.js +421 -0
- package/dist/tabs-broker-worker.d.ts +8 -0
- package/dist/tabs-broker-worker.js +434 -0
- package/dist/types.d.ts +688 -11
- package/package.json +11 -7
- package/scripts/check-broker-bundle.mjs +33 -0
- package/skills/{spooky-core → sp00ky-core}/SKILL.md +12 -12
- package/skills/{spooky-core → sp00ky-core}/references/auth.md +1 -1
- package/skills/{spooky-core → sp00ky-core}/references/config.md +2 -2
- package/src/bucket-blurhash.test.ts +148 -0
- package/src/build-globals.d.ts +12 -0
- package/src/events/events.test.ts +2 -1
- package/src/events/index.ts +3 -0
- package/src/index.ts +35 -2
- package/src/modules/app-release/index.test.ts +125 -0
- package/src/modules/app-release/index.ts +201 -0
- package/src/modules/auth/events/index.ts +2 -1
- package/src/modules/auth/index.ts +59 -20
- package/src/modules/cache/index.ts +112 -32
- package/src/modules/cache/types.ts +2 -2
- package/src/modules/crdt/crdt-field.ts +294 -0
- package/src/modules/crdt/crdt-hydration.test.ts +210 -0
- package/src/modules/crdt/crdt-reconnect.test.ts +195 -0
- package/src/modules/crdt/index.ts +463 -0
- package/src/modules/crdt/loro-loader.ts +25 -0
- package/src/modules/data/data.hydration.test.ts +142 -0
- package/src/modules/data/data.membership.test.ts +462 -0
- package/src/modules/data/data.rebind.test.ts +147 -0
- package/src/modules/data/data.run.test.ts +113 -0
- package/src/modules/data/data.settled-writes.test.ts +206 -0
- package/src/modules/data/data.status.test.ts +249 -0
- package/src/modules/data/id-set-plan.test.ts +122 -0
- package/src/modules/data/index.ts +1580 -130
- package/src/modules/data/mutation-id.test.ts +25 -0
- package/src/modules/data/mutation-id.ts +35 -0
- package/src/modules/data/window-query.test.ts +52 -0
- package/src/modules/data/window-query.ts +194 -0
- package/src/modules/devtools/flags.ts +349 -0
- package/src/modules/devtools/index.ts +386 -37
- package/src/modules/devtools/notify-throttle.test.ts +149 -0
- package/src/modules/devtools/storage-info.test.ts +79 -0
- package/src/modules/devtools/storage-info.ts +168 -0
- package/src/modules/devtools/versions.test.ts +74 -0
- package/src/modules/devtools/versions.ts +110 -0
- package/src/modules/feature-flag/index.test.ts +251 -0
- package/src/modules/feature-flag/index.ts +308 -0
- package/src/modules/ref-tables.test.ts +91 -0
- package/src/modules/ref-tables.ts +88 -0
- package/src/modules/sync/engine.ts +101 -37
- package/src/modules/sync/events/index.ts +9 -2
- package/src/modules/sync/queue/queue-down.test.ts +107 -0
- package/src/modules/sync/queue/queue-down.ts +35 -6
- package/src/modules/sync/queue/queue-up.forwarded.test.ts +164 -0
- package/src/modules/sync/queue/queue-up.ts +241 -57
- package/src/modules/sync/scheduler.pause.test.ts +109 -0
- package/src/modules/sync/scheduler.retry.test.ts +156 -0
- package/src/modules/sync/scheduler.ts +158 -11
- package/src/modules/sync/sync.cleanup.test.ts +116 -0
- package/src/modules/sync/sync.health.test.ts +149 -0
- package/src/modules/sync/sync.heartbeat.test.ts +80 -0
- package/src/modules/sync/sync.live-removal.test.ts +134 -0
- package/src/modules/sync/sync.reconnect.test.ts +145 -0
- package/src/modules/sync/sync.subquery.test.ts +82 -0
- package/src/modules/sync/sync.ts +1558 -99
- package/src/modules/sync/utils.test.ts +269 -2
- package/src/modules/sync/utils.ts +201 -17
- package/src/otel/index.ts +13 -10
- 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 +160 -0
- package/src/services/database/connection-supervisor.test.ts +289 -0
- package/src/services/database/connection-supervisor.ts +415 -0
- package/src/services/database/database.query-timeout.test.ts +83 -0
- package/src/services/database/database.ts +32 -12
- package/src/services/database/engine-factory.ts +33 -0
- package/src/services/database/events/index.ts +2 -1
- package/src/services/database/index.ts +7 -0
- package/src/services/database/local-migrator.ts +30 -27
- package/src/services/database/local.test.ts +64 -0
- package/src/services/database/local.ts +478 -67
- 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 +413 -0
- package/src/services/database/relation-resolver.ts +0 -0
- package/src/services/database/remote.ts +110 -14
- package/src/services/database/sqlite-cache-engine.test.ts +558 -0
- package/src/services/database/sqlite-cache-engine.ts +1257 -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-open.test.ts +150 -0
- package/src/services/database/sqlite-open.ts +164 -0
- package/src/services/database/sqlite-plan-sql.test.ts +104 -0
- package/src/services/database/sqlite-plan-sql.ts +106 -0
- package/src/services/database/sqlite-select.integration.test.ts +185 -0
- package/src/services/database/sqlite-select.test.ts +246 -0
- package/src/services/database/sqlite-select.ts +121 -0
- package/src/services/database/sqlite-transport.fixture.ts +30 -0
- package/src/services/database/sqlite-transport.ts +221 -0
- package/src/services/database/sqlite-worker.ts +437 -0
- package/src/services/database/surql-translate.ts +416 -0
- package/src/services/database/surreal-cache-engine.ts +141 -0
- package/src/services/logger/index.ts +3 -2
- package/src/services/persistence/localstorage.ts +2 -2
- package/src/services/persistence/resilient.ts +11 -4
- package/src/services/persistence/surrealdb.ts +10 -10
- package/src/services/stream-processor/index.ts +444 -52
- 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 +136 -0
- package/src/services/stream-processor/stream-processor.reset.test.ts +216 -0
- package/src/services/stream-processor/stream-processor.test.ts +1 -1
- package/src/services/stream-processor/wasm-types.ts +23 -2
- package/src/services/tabs/broker-client.ts +283 -0
- package/src/services/tabs/broker.test.ts +278 -0
- package/src/services/tabs/coordinator.test.ts +244 -0
- package/src/services/tabs/coordinator.ts +576 -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 +242 -0
- package/src/services/tabs/support.ts +36 -0
- package/src/services/tabs/tabs-broker-worker.ts +586 -0
- package/src/sp00ky.auth-order.test.ts +92 -0
- package/src/sp00ky.init-query.test.ts +183 -0
- package/src/sp00ky.ts +1543 -0
- package/src/types.ts +496 -13
- package/src/utils/blurhash.ts +90 -0
- package/src/utils/error-classification.test.ts +44 -0
- package/src/utils/error-classification.ts +7 -0
- package/src/utils/index.ts +73 -13
- package/src/utils/parser.ts +3 -2
- package/src/utils/semver.test.ts +32 -0
- package/src/utils/semver.ts +30 -0
- package/src/utils/surql.ts +30 -18
- package/src/utils/withRetry.test.ts +1 -1
- package/tsdown.config.ts +86 -1
- package/src/spooky.ts +0 -395
package/dist/index.d.ts
CHANGED
|
@@ -1,81 +1,241 @@
|
|
|
1
|
-
import { C as
|
|
1
|
+
import { A as Sp00kyQueryResultPromise, B as LocalStore, C as ReconnectConfig, D as RunOptions, E as RegistrationTimings, F as SyncHealthConfig, G as SyncEventSystem, H as DatabaseEventSystem, I as SyncHealthStatus, K as EventDefinition, L as TimingPhase, M as StorageHealthStatus, N as StoreType, O as Sp00kyConfig, P as SyncHealth, R as UpdateOptions, S as QueryUpdateCallback, T as RecordVersionDiff, U as DatabaseEventTypes, V as SealedQuery, W as Logger$1, _ as QueryState, a as MATERIALIZATION_SAMPLE_WINDOW, b as QueryTimeToLive, c as MutationEventType, d as PinoTransmit, f as PreloadOptions, g as QueryHash, h as QueryConfigRecord, i as Level, j as StorageHealth, k as Sp00kyQueryResult, l as PersistenceClient, m as QueryConfig, n as DebounceOptions, o as MutationCallback, p as PreloadRefresh, q as EventSystem, r as EventSubscriptionOptions, s as MutationEvent, t as ConnectionState, u as PhaseStat, v as QueryStatus, w as RecordVersionArray, x as QueryTimings, y as QueryStatusCallback, z as UpEvent } from "./types.js";
|
|
2
2
|
import * as surrealdb0 from "surrealdb";
|
|
3
|
-
import { Duration, RecordId, Surreal, SurrealTransaction } from "surrealdb";
|
|
4
|
-
import { AccessDefinition, BackendNames, BackendRoutes, BucketNames, ColumnSchema, GetTable, QueryBuilder, QueryOptions, RoutePayload, SchemaStructure, TableModel, TableNames, TypeNameToTypeMap } from "@spooky-sync/query-builder";
|
|
3
|
+
import { Duration, RecordId, Surreal as Surreal$1, SurrealEvents, SurrealTransaction } from "surrealdb";
|
|
4
|
+
import { AccessDefinition, BackendNames, BackendRoutes, BucketNames, ColumnSchema, FinalQuery, GetTable, QueryBuilder, QueryOptions, QueryPlan, RoutePayload, SchemaStructure, TableModel, TableNames, TypeNameToTypeMap } from "@spooky-sync/query-builder";
|
|
5
5
|
import { Logger } from "pino";
|
|
6
|
+
import { decode, encode, isBlurhashValid } from "blurhash";
|
|
7
|
+
import { LoroDoc } from "loro-crdt";
|
|
6
8
|
|
|
7
|
-
//#region src/services/database/events/index.d.ts
|
|
8
|
-
declare const DatabaseEventTypes: {
|
|
9
|
-
readonly LocalQuery: "DATABASE_LOCAL_QUERY";
|
|
10
|
-
readonly RemoteQuery: "DATABASE_REMOTE_QUERY";
|
|
11
|
-
};
|
|
12
|
-
interface DatabaseQueryEventPayload {
|
|
13
|
-
query: string;
|
|
14
|
-
vars?: Record<string, unknown>;
|
|
15
|
-
duration: number;
|
|
16
|
-
success: boolean;
|
|
17
|
-
error?: string;
|
|
18
|
-
timestamp: number;
|
|
19
|
-
}
|
|
20
|
-
type DatabaseEventTypeMap = {
|
|
21
|
-
[DatabaseEventTypes.LocalQuery]: EventDefinition<typeof DatabaseEventTypes.LocalQuery, DatabaseQueryEventPayload>;
|
|
22
|
-
[DatabaseEventTypes.RemoteQuery]: EventDefinition<typeof DatabaseEventTypes.RemoteQuery, DatabaseQueryEventPayload>;
|
|
23
|
-
};
|
|
24
|
-
type DatabaseEventSystem = EventSystem<DatabaseEventTypeMap>;
|
|
25
|
-
//#endregion
|
|
26
|
-
//#region src/utils/surql.d.ts
|
|
27
|
-
interface SealedQuery<T = void> {
|
|
28
|
-
readonly sql: string;
|
|
29
|
-
readonly extract: (results: unknown[]) => T;
|
|
30
|
-
}
|
|
31
|
-
//#endregion
|
|
32
9
|
//#region src/services/database/database.d.ts
|
|
33
10
|
declare abstract class AbstractDatabaseService {
|
|
34
|
-
protected client: Surreal;
|
|
11
|
+
protected client: Surreal$1;
|
|
35
12
|
protected logger: Logger$1;
|
|
36
13
|
protected events: DatabaseEventSystem;
|
|
14
|
+
/**
|
|
15
|
+
* Per-query deadline in ms; `0` disables. Only the remote service sets this
|
|
16
|
+
* (see `RemoteDatabaseService`) — a local query can be legitimately slow and
|
|
17
|
+
* has its own retry ladders, and there is no half-open-socket failure mode
|
|
18
|
+
* for an in-process engine.
|
|
19
|
+
*/
|
|
20
|
+
protected queryTimeoutMs: number;
|
|
37
21
|
protected abstract eventType: typeof DatabaseEventTypes.LocalQuery | typeof DatabaseEventTypes.RemoteQuery;
|
|
38
|
-
constructor(client: Surreal, logger: Logger$1, events: DatabaseEventSystem);
|
|
22
|
+
constructor(client: Surreal$1, logger: Logger$1, events: DatabaseEventSystem);
|
|
39
23
|
abstract connect(): Promise<void>;
|
|
40
|
-
getClient(): Surreal;
|
|
24
|
+
getClient(): Surreal$1;
|
|
41
25
|
getEvents(): DatabaseEventSystem;
|
|
42
26
|
tx(): Promise<SurrealTransaction>;
|
|
43
27
|
private queryQueue;
|
|
44
28
|
/**
|
|
45
29
|
* Execute a query with serialized execution to prevent WASM transaction issues.
|
|
30
|
+
*
|
|
31
|
+
* Serialization means every query waits on the previous one, so a call that
|
|
32
|
+
* never settles blocks the whole chain forever. {@link queryTimeoutMs} bounds
|
|
33
|
+
* each link: on expiry this promise rejects and the chain moves on, even
|
|
34
|
+
* though the underlying RPC is still parked in the SDK's pending map.
|
|
46
35
|
*/
|
|
47
36
|
query<T extends unknown[]>(query: string, vars?: Record<string, unknown>): Promise<T>;
|
|
48
37
|
execute<T>(query: SealedQuery<T>, vars?: Record<string, unknown>): Promise<T>;
|
|
49
38
|
close(): Promise<void>;
|
|
50
39
|
}
|
|
51
40
|
//#endregion
|
|
52
|
-
//#region src/services/database/local.d.ts
|
|
53
|
-
declare class LocalDatabaseService extends AbstractDatabaseService {
|
|
54
|
-
private config;
|
|
55
|
-
protected eventType: "DATABASE_LOCAL_QUERY";
|
|
56
|
-
constructor(config: SpookyConfig<any>['database'], logger: Logger$1);
|
|
57
|
-
getConfig(): SpookyConfig<any>['database'];
|
|
58
|
-
connect(): Promise<void>;
|
|
59
|
-
}
|
|
60
|
-
//#endregion
|
|
61
41
|
//#region src/services/database/remote.d.ts
|
|
42
|
+
/** Transport events the SDK publishes, mapped 1:1 to {@link ConnectionState}. */
|
|
43
|
+
type RemoteConnectionEvent = ConnectionState | 'error';
|
|
62
44
|
declare class RemoteDatabaseService extends AbstractDatabaseService {
|
|
63
45
|
private config;
|
|
64
46
|
protected eventType: "DATABASE_REMOTE_QUERY";
|
|
65
|
-
|
|
66
|
-
|
|
47
|
+
private readonly reconnectConfig;
|
|
48
|
+
/**
|
|
49
|
+
* In-flight `connect()`, so concurrent callers (boot + supervisor revive +
|
|
50
|
+
* an `online` event landing at the same moment) share one attempt instead of
|
|
51
|
+
* racing two sockets. Cleared on settle, so a later call always reconnects.
|
|
52
|
+
*/
|
|
53
|
+
private connecting;
|
|
54
|
+
constructor(config: Sp00kyConfig<any>['database'], logger: Logger$1);
|
|
55
|
+
getConfig(): Sp00kyConfig<any>['database'];
|
|
56
|
+
/** Resolved reconnect tunables; the supervisor reads its own knobs here. */
|
|
57
|
+
getReconnectConfig(): Required<ReconnectConfig>;
|
|
58
|
+
/** Current transport state as reported by the SDK. */
|
|
59
|
+
getStatus(): ConnectionState;
|
|
60
|
+
/**
|
|
61
|
+
* Observe transport events. Thin passthrough so callers (the supervisor,
|
|
62
|
+
* sync, CRDT) don't have to reach through `getClient()`.
|
|
63
|
+
*/
|
|
64
|
+
subscribeConnection<K extends RemoteConnectionEvent>(event: K, cb: (...payload: SurrealEvents[K]) => void): () => void;
|
|
65
|
+
/**
|
|
66
|
+
* Tear the socket down on purpose. Used by the heartbeat watchdog when a
|
|
67
|
+
* socket stops answering but never closes: `close()` makes the SDK publish
|
|
68
|
+
* `disconnected`, which is what drives the supervisor's revive loop.
|
|
69
|
+
*/
|
|
70
|
+
forceClose(): Promise<void>;
|
|
71
|
+
/**
|
|
72
|
+
* Open (or re-open) the remote connection.
|
|
73
|
+
*
|
|
74
|
+
* Safe to call repeatedly: concurrent calls share the in-flight attempt, and
|
|
75
|
+
* a call after a `disconnected` builds a fresh socket. `use()` and
|
|
76
|
+
* `authenticate()` are re-applied here for the cold path; the SDK also
|
|
77
|
+
* replays them itself on its own internal reconnects.
|
|
78
|
+
*/
|
|
67
79
|
connect(): Promise<void>;
|
|
80
|
+
private doConnect;
|
|
68
81
|
signin(params: any): Promise<any>;
|
|
69
82
|
signup(params: any): Promise<any>;
|
|
70
83
|
authenticate(token: string): Promise<any>;
|
|
71
84
|
invalidate(): Promise<void>;
|
|
72
85
|
}
|
|
73
86
|
//#endregion
|
|
87
|
+
//#region src/services/database/connection-supervisor.d.ts
|
|
88
|
+
/**
|
|
89
|
+
* Keeps the remote WebSocket alive for the whole life of the page.
|
|
90
|
+
*
|
|
91
|
+
* The SurrealDB SDK reconnects on its own after a socket `close`, but that
|
|
92
|
+
* covers only one of three ways the connection dies:
|
|
93
|
+
*
|
|
94
|
+
* 1. **Socket closes, SDK recovers.** Handled entirely by the SDK. This
|
|
95
|
+
* supervisor only observes it (to report `reconnecting` upward).
|
|
96
|
+
* 2. **Socket closes, SDK gives up.** With `attempts: -1` this shouldn't happen
|
|
97
|
+
* from exhaustion — but the SDK also terminates the engine permanently when
|
|
98
|
+
* its post-reconnect handshake throws (it re-runs `version()`, `use()`,
|
|
99
|
+
* `authenticate()` on every reconnect and closes the engine on any error).
|
|
100
|
+
* One transient hiccup there would otherwise kill the page's connection for
|
|
101
|
+
* good. The revive loop re-opens from scratch.
|
|
102
|
+
* 3. **Socket never closes at all.** A half-open connection: the peer is gone
|
|
103
|
+
* (NAT timeout, wifi switch, laptop sleep) but no FIN ever arrives, so
|
|
104
|
+
* `readyState` stays OPEN and the SDK's own 30s ping — fire-and-forget, no
|
|
105
|
+
* response deadline — never notices. Nothing ever fires a `close` event, so
|
|
106
|
+
* nothing ever triggers a reconnect. The heartbeat detects this and forces
|
|
107
|
+
* the teardown that case 2's loop then repairs.
|
|
108
|
+
*
|
|
109
|
+
* Plus wake triggers: coming back `online` or un-hiding the tab probes
|
|
110
|
+
* immediately rather than waiting out a backoff that was scheduled while the
|
|
111
|
+
* network was known-down.
|
|
112
|
+
*/
|
|
113
|
+
declare class ConnectionSupervisor {
|
|
114
|
+
private readonly remote;
|
|
115
|
+
private readonly logger;
|
|
116
|
+
private readonly config;
|
|
117
|
+
private state;
|
|
118
|
+
private subscribers;
|
|
119
|
+
private started;
|
|
120
|
+
private disposed;
|
|
121
|
+
private heartbeatTimer;
|
|
122
|
+
private heartbeatInFlight;
|
|
123
|
+
/** Consecutive failed probes. See {@link FAILURES_BEFORE_TEARDOWN}. */
|
|
124
|
+
private heartbeatFailures;
|
|
125
|
+
private reviveTimer;
|
|
126
|
+
private reviveAttempts;
|
|
127
|
+
/** Timestamp of the last wake-triggered probe, for rate limiting. */
|
|
128
|
+
private lastWakeProbeAt;
|
|
129
|
+
private reviving;
|
|
130
|
+
/**
|
|
131
|
+
* Set while the browser reports itself offline. Retrying a socket against a
|
|
132
|
+
* down interface only burns backoff, so the loop parks until `online` fires.
|
|
133
|
+
*/
|
|
134
|
+
private suspended;
|
|
135
|
+
private teardown;
|
|
136
|
+
private static readonly REVIVE_BASE_MS;
|
|
137
|
+
/**
|
|
138
|
+
* How many consecutive heartbeat failures it takes to tear the socket down.
|
|
139
|
+
*
|
|
140
|
+
* The probe rides the same serialized queue as every other RPC (deliberately
|
|
141
|
+
* — see {@link beat}), which means it cannot distinguish a WEDGED queue from
|
|
142
|
+
* a merely BUSY one. A single slow window (a large sync burst, one heavy
|
|
143
|
+
* app query) used to be enough to force-close a perfectly healthy socket,
|
|
144
|
+
* and the resulting reconnect re-registered every active query about a
|
|
145
|
+
* second later. That self-inflicted teardown manufactured the very reconnect
|
|
146
|
+
* storms this class exists to survive. A genuinely dead socket still fails
|
|
147
|
+
* every probe, so it is torn down one interval later than before.
|
|
148
|
+
*/
|
|
149
|
+
private static readonly FAILURES_BEFORE_TEARDOWN;
|
|
150
|
+
/** Retry delay after an inconclusive (first) heartbeat failure. */
|
|
151
|
+
private static readonly HEARTBEAT_RETRY_MS;
|
|
152
|
+
/** Floor between probes triggered by wake events (tab focus, pageshow). */
|
|
153
|
+
private static readonly WAKE_PROBE_MIN_INTERVAL_MS;
|
|
154
|
+
constructor(remote: RemoteDatabaseService, logger: Logger$1, config?: Required<ReconnectConfig>);
|
|
155
|
+
/** Latest observed transport state. */
|
|
156
|
+
get connection(): ConnectionState;
|
|
157
|
+
/**
|
|
158
|
+
* Observe transport state. Fires immediately with the current value and again
|
|
159
|
+
* on every change. Returns an unsubscribe.
|
|
160
|
+
*/
|
|
161
|
+
subscribe(cb: (state: ConnectionState) => void): () => void;
|
|
162
|
+
/**
|
|
163
|
+
* Begin supervising. Call once, after the initial {@link
|
|
164
|
+
* RemoteDatabaseService.connect}. Idempotent.
|
|
165
|
+
*/
|
|
166
|
+
start(): void;
|
|
167
|
+
/** Stop all timers and listeners. Safe to call more than once. */
|
|
168
|
+
dispose(): void;
|
|
169
|
+
private setState;
|
|
170
|
+
private clearReviveTimer;
|
|
171
|
+
/**
|
|
172
|
+
* Queue the next `connect()` attempt on exponential backoff, capped at
|
|
173
|
+
* `superviseRetryDelayMaxMs`. Never gives up — the page is expected to
|
|
174
|
+
* outlive any outage.
|
|
175
|
+
*/
|
|
176
|
+
private scheduleRevive;
|
|
177
|
+
private revive;
|
|
178
|
+
private stopHeartbeat;
|
|
179
|
+
private startHeartbeat;
|
|
180
|
+
/**
|
|
181
|
+
* Probe the server end-to-end. Deliberately goes through
|
|
182
|
+
* `remote.query` — the same serialized queue every other remote call uses —
|
|
183
|
+
* so a queue wedged behind a stuck RPC also fails the heartbeat instead of
|
|
184
|
+
* being invisible to it.
|
|
185
|
+
*/
|
|
186
|
+
private beat;
|
|
187
|
+
/**
|
|
188
|
+
* A restored network or an un-hidden tab is the strongest available hint that
|
|
189
|
+
* a reconnect will now succeed, so probe immediately instead of waiting out a
|
|
190
|
+
* backoff scheduled under worse conditions.
|
|
191
|
+
*/
|
|
192
|
+
private installWakeTriggers;
|
|
193
|
+
/**
|
|
194
|
+
* Reset the backoff and act on whichever problem is present: reconnect if the
|
|
195
|
+
* socket is gone, otherwise probe it (it may be half-open — which is exactly
|
|
196
|
+
* what a sleep/wake cycle produces).
|
|
197
|
+
*/
|
|
198
|
+
private wake;
|
|
199
|
+
}
|
|
200
|
+
//#endregion
|
|
201
|
+
//#region src/modules/sync/queue/queue-down.d.ts
|
|
202
|
+
type RegisterEvent = {
|
|
203
|
+
type: 'register';
|
|
204
|
+
payload: {
|
|
205
|
+
hash: string;
|
|
206
|
+
};
|
|
207
|
+
};
|
|
208
|
+
type SyncEvent = {
|
|
209
|
+
type: 'sync';
|
|
210
|
+
payload: {
|
|
211
|
+
hash: string;
|
|
212
|
+
};
|
|
213
|
+
};
|
|
214
|
+
type HeartbeatEvent = {
|
|
215
|
+
type: 'heartbeat';
|
|
216
|
+
payload: {
|
|
217
|
+
hash: string;
|
|
218
|
+
};
|
|
219
|
+
};
|
|
220
|
+
type CleanupEvent = {
|
|
221
|
+
type: 'cleanup';
|
|
222
|
+
payload: {
|
|
223
|
+
hash: string;
|
|
224
|
+
};
|
|
225
|
+
};
|
|
226
|
+
type DownEvent = RegisterEvent | SyncEvent | HeartbeatEvent | CleanupEvent;
|
|
227
|
+
//#endregion
|
|
74
228
|
//#region src/services/stream-processor/wasm-types.d.ts
|
|
75
229
|
interface WasmStreamUpdate {
|
|
76
230
|
query_id: string;
|
|
77
231
|
result_hash: string;
|
|
78
232
|
result_data: RecordVersionArray;
|
|
233
|
+
timing_store_apply_ms?: number;
|
|
234
|
+
timing_circuit_step_ms?: number;
|
|
235
|
+
timing_transform_ms?: number;
|
|
236
|
+
timing_parse_ms?: number;
|
|
237
|
+
timing_plan_ms?: number;
|
|
238
|
+
timing_snapshot_ms?: number;
|
|
79
239
|
}
|
|
80
240
|
//#endregion
|
|
81
241
|
//#region src/services/stream-processor/index.d.ts
|
|
@@ -96,6 +256,25 @@ interface StreamUpdate {
|
|
|
96
256
|
queryHash: string;
|
|
97
257
|
localArray: RecordVersionArray;
|
|
98
258
|
op?: 'CREATE' | 'UPDATE' | 'DELETE';
|
|
259
|
+
/**
|
|
260
|
+
* End-to-end ingest latency for the WASM call that produced this update,
|
|
261
|
+
* in milliseconds. Populated by StreamProcessorService.ingest. Undefined
|
|
262
|
+
* for the initial register_view snapshot.
|
|
263
|
+
*/
|
|
264
|
+
materializationTimeMs?: number;
|
|
265
|
+
/** SSP internal sub-phase timings (ms) for this ingest, from the WASM binding. */
|
|
266
|
+
storeApplyMs?: number;
|
|
267
|
+
circuitStepMs?: number;
|
|
268
|
+
transformMs?: number;
|
|
269
|
+
/**
|
|
270
|
+
* One-shot registration timings (ms). Only set on the StreamUpdate returned
|
|
271
|
+
* by `registerQueryPlan` (the register_view snapshot), not on ingest updates.
|
|
272
|
+
*/
|
|
273
|
+
registration?: {
|
|
274
|
+
parseMs: number;
|
|
275
|
+
planMs: number;
|
|
276
|
+
snapshotMs: number;
|
|
277
|
+
};
|
|
99
278
|
}
|
|
100
279
|
type StreamProcessorEvents = {
|
|
101
280
|
stream_update: EventDefinition<'stream_update', StreamUpdate[]>;
|
|
@@ -115,19 +294,123 @@ declare class StreamProcessorService {
|
|
|
115
294
|
private processor;
|
|
116
295
|
private isInitialized;
|
|
117
296
|
private receivers;
|
|
118
|
-
|
|
297
|
+
private batching;
|
|
298
|
+
private batchBuffer;
|
|
299
|
+
private sessionAuth;
|
|
300
|
+
private stateKeySuffix;
|
|
301
|
+
private stateGeneration;
|
|
302
|
+
private persistState;
|
|
303
|
+
private persistCircuit;
|
|
304
|
+
private checkpointMs;
|
|
305
|
+
private checkpointTimer;
|
|
306
|
+
private snapshotDirty;
|
|
307
|
+
private pagehideHandler;
|
|
308
|
+
constructor(events: EventSystem<StreamProcessorEvents>, db: LocalStore, persistenceClient: PersistenceClient, logger: Logger);
|
|
119
309
|
/**
|
|
120
310
|
* Add a receiver for stream updates.
|
|
121
311
|
* Multiple receivers can be registered (DataManager, DevTools, etc.)
|
|
122
312
|
*/
|
|
123
313
|
addReceiver(receiver: StreamUpdateReceiver): void;
|
|
124
314
|
private notifyUpdates;
|
|
315
|
+
private dispatchUpdates;
|
|
316
|
+
/**
|
|
317
|
+
* Ingest a batch of record changes as a single bulk operation, firing only
|
|
318
|
+
* one coalesced `StreamUpdate` per affected query once every record has been
|
|
319
|
+
* ingested (instead of one update per record). Use this whenever multiple
|
|
320
|
+
* records land at once — e.g. sync fetching N missing rows — so a list query
|
|
321
|
+
* re-runs and the UI re-renders once for the whole batch rather than
|
|
322
|
+
* row-by-row.
|
|
323
|
+
*
|
|
324
|
+
* Internally opens a coalescing window, ingests each record, then flushes;
|
|
325
|
+
* processor state is persisted once for the whole batch. No-op for an empty
|
|
326
|
+
* batch.
|
|
327
|
+
*/
|
|
328
|
+
ingestMany(records: Array<{
|
|
329
|
+
table: string;
|
|
330
|
+
op: 'CREATE' | 'UPDATE' | 'DELETE';
|
|
331
|
+
id: string;
|
|
332
|
+
record: any;
|
|
333
|
+
}>): void;
|
|
334
|
+
/**
|
|
335
|
+
* Open a coalescing window. While open, the per-record stream updates
|
|
336
|
+
* emitted by `ingest` are buffered (one entry per queryHash) instead of
|
|
337
|
+
* dispatched. Always paired with `flushCoalescing()` in a try/finally by
|
|
338
|
+
* `ingestMany` so the window always closes — otherwise the processor stays
|
|
339
|
+
* stuck buffering forever.
|
|
340
|
+
*
|
|
341
|
+
* No-op if a window is already open (nested batches aren't expected here).
|
|
342
|
+
*/
|
|
343
|
+
private beginCoalescing;
|
|
344
|
+
/**
|
|
345
|
+
* Close the coalescing window and flush: dispatch one coalesced
|
|
346
|
+
* `StreamUpdate` per buffered queryHash, then persist processor state once
|
|
347
|
+
* for the whole batch (instead of once per ingest).
|
|
348
|
+
*/
|
|
349
|
+
private flushCoalescing;
|
|
125
350
|
/**
|
|
126
351
|
* Initialize the WASM module and processor.
|
|
127
352
|
* This must be called before using other methods.
|
|
128
353
|
*/
|
|
129
354
|
init(): Promise<void>;
|
|
355
|
+
/** Route the persisted circuit snapshot to a per-bucket key. */
|
|
356
|
+
setStateKeySuffix(bucketId: string): void;
|
|
357
|
+
private stateKey;
|
|
358
|
+
/**
|
|
359
|
+
* Drop the current WASM processor and start a fresh, empty circuit. Used on
|
|
360
|
+
* local-bucket switches: the old circuit holds the previous user's rows AND
|
|
361
|
+
* views registered with the previous `$auth` context, so neither may survive.
|
|
362
|
+
* Deliberately does NOT `loadState()` — a persisted snapshot references views
|
|
363
|
+
* under a dead sessionId salt; the DataModule rebind re-registers every live
|
|
364
|
+
* view against this fresh processor. Caller must re-seed `setPermissions`
|
|
365
|
+
* afterwards (a fresh circuit default-denies every table).
|
|
366
|
+
*/
|
|
367
|
+
reset(): Promise<void>;
|
|
368
|
+
/**
|
|
369
|
+
* Release the wasm circuit and stop checkpointing. Call when the client is
|
|
370
|
+
* torn down; a recreated client (provider remount, HMR) would otherwise stack
|
|
371
|
+
* one full circuit per instance.
|
|
372
|
+
*/
|
|
373
|
+
dispose(): void;
|
|
374
|
+
/**
|
|
375
|
+
* Explicitly run the wasm-bindgen destructor. Guarded: stale wasm builds may
|
|
376
|
+
* not expose `free`, and a double free must not take the app down.
|
|
377
|
+
*/
|
|
378
|
+
private freeProcessor;
|
|
379
|
+
/** Toggle circuit-state persistence (shared-tabs follower/leader role). */
|
|
380
|
+
setPersistenceEnabled(enabled: boolean): void;
|
|
381
|
+
/**
|
|
382
|
+
* Opt into snapshot persistence (`persistCircuit`). Off by default: see the
|
|
383
|
+
* `persistCircuit` field comment for why per-ingest snapshots were removed.
|
|
384
|
+
* Must be called before `init()` for a snapshot to be restored at boot.
|
|
385
|
+
*/
|
|
386
|
+
configureCircuitPersistence(enabled: boolean, checkpointMs?: number): void;
|
|
387
|
+
/**
|
|
388
|
+
* Record that the circuit changed. Cheap and O(1), the expensive snapshot is
|
|
389
|
+
* deferred to the checkpoint timer, and skipped entirely when
|
|
390
|
+
* `persistCircuit` is off (the default).
|
|
391
|
+
*/
|
|
392
|
+
private markSnapshotDirty;
|
|
393
|
+
private startCheckpoints;
|
|
394
|
+
/** Stop checkpointing and drop the `pagehide` listener. */
|
|
395
|
+
stopCheckpoints(): void;
|
|
130
396
|
loadState(): Promise<void>;
|
|
397
|
+
/**
|
|
398
|
+
* Seed per-table `select` permission predicates ({ [table]: whereText }).
|
|
399
|
+
* Must run after the processor exists and before any `register_view`, else
|
|
400
|
+
* non-`_00_` tables are default-denied and registration fails.
|
|
401
|
+
*/
|
|
402
|
+
setPermissions(permissions: Record<string, string>): void;
|
|
403
|
+
/**
|
|
404
|
+
* Set the current session's auth identity for permission injection,
|
|
405
|
+
* mirroring the server's `fn::query::register`
|
|
406
|
+
* (`object::extend(params, { auth: { id: $auth.id }, access: $access })`).
|
|
407
|
+
* Stored as strings (empty when logged out) and applied to every
|
|
408
|
+
* `register_view` in {@link registerQueryPlan}. Must be set before a
|
|
409
|
+
* `$auth`-gated query registers (and re-set on auth state changes), or the
|
|
410
|
+
* in-browser SSP's `permission_inject` rejects it with
|
|
411
|
+
* "requires $auth but registration params lack it".
|
|
412
|
+
*/
|
|
413
|
+
setSessionAuth(authId: string | null, access: string | null): void;
|
|
131
414
|
saveState(): Promise<void>;
|
|
132
415
|
/**
|
|
133
416
|
* Ingest a record change into the processor.
|
|
@@ -147,6 +430,1006 @@ declare class StreamProcessorService {
|
|
|
147
430
|
private normalizeValue;
|
|
148
431
|
}
|
|
149
432
|
//#endregion
|
|
433
|
+
//#region src/modules/cache/types.d.ts
|
|
434
|
+
type RecordWithId = Record<string, any> & {
|
|
435
|
+
id: RecordId<string>;
|
|
436
|
+
};
|
|
437
|
+
interface QueryConfig$1 {
|
|
438
|
+
queryHash: string;
|
|
439
|
+
surql: string;
|
|
440
|
+
params: Record<string, any>;
|
|
441
|
+
ttl: QueryTimeToLive | Duration;
|
|
442
|
+
lastActiveAt: Date;
|
|
443
|
+
}
|
|
444
|
+
interface CacheRecord {
|
|
445
|
+
table: string;
|
|
446
|
+
op: 'CREATE' | 'UPDATE' | 'DELETE';
|
|
447
|
+
record: RecordWithId;
|
|
448
|
+
version: number;
|
|
449
|
+
}
|
|
450
|
+
//#endregion
|
|
451
|
+
//#region src/modules/cache/index.d.ts
|
|
452
|
+
/**
|
|
453
|
+
* CacheModule - Centralized storage and DBSP ingestion
|
|
454
|
+
*
|
|
455
|
+
* Single responsibility: Handle all local storage operations and DBSP ingestion.
|
|
456
|
+
* This module acts as the bridge between data operations and persistence.
|
|
457
|
+
*/
|
|
458
|
+
/** One ingested change, in exactly the shape `ingestMany` consumes. Shared
|
|
459
|
+
* with the tabs protocol so a leader can relay its ingests to followers. */
|
|
460
|
+
interface CacheIngestTuple {
|
|
461
|
+
table: string;
|
|
462
|
+
op: 'CREATE' | 'UPDATE' | 'DELETE';
|
|
463
|
+
id: string;
|
|
464
|
+
record: Record<string, unknown>;
|
|
465
|
+
}
|
|
466
|
+
declare class CacheModule implements StreamUpdateReceiver {
|
|
467
|
+
private local;
|
|
468
|
+
private streamProcessor;
|
|
469
|
+
private logger;
|
|
470
|
+
private streamUpdateCallback;
|
|
471
|
+
private versionLookups;
|
|
472
|
+
/** Shared-tabs leader: fan every committed ingest out to follower circuits.
|
|
473
|
+
* Fired AFTER the local tx (the rows are already in the shared store, so a
|
|
474
|
+
* follower only needs the circuit feed). Never set on followers. */
|
|
475
|
+
private ingestRelay;
|
|
476
|
+
constructor(local: LocalStore, streamProcessor: StreamProcessorService, streamUpdateCallback: (update: StreamUpdate) => void, logger: Logger$1);
|
|
477
|
+
/**
|
|
478
|
+
* Implements StreamUpdateReceiver interface
|
|
479
|
+
* Called directly by StreamProcessor when views change
|
|
480
|
+
*/
|
|
481
|
+
onStreamUpdate(update: StreamUpdate): void;
|
|
482
|
+
setIngestRelay(cb: ((tuples: CacheIngestTuple[]) => void) | null): void;
|
|
483
|
+
/**
|
|
484
|
+
* Shared-tabs follower: feed relayed tuples into THIS tab's circuit only.
|
|
485
|
+
* The rows are already in the shared store (the leader wrote them), so no
|
|
486
|
+
* local write happens here; the normal chain then runs: SSP -> stream update
|
|
487
|
+
* -> DataModule debounce -> materializeRecords (re-reads via the port
|
|
488
|
+
* transport) -> this tab's subscriptions fire with this tab's hashes.
|
|
489
|
+
*/
|
|
490
|
+
applyRelayedIngest(tuples: CacheIngestTuple[]): void;
|
|
491
|
+
lookup(recordId: string): number;
|
|
492
|
+
/** Drop the version cache on a bucket switch — a stale version would make
|
|
493
|
+
* the sync diff skip fetching a body the new bucket legitimately needs. */
|
|
494
|
+
clearVersionLookups(): void;
|
|
495
|
+
/**
|
|
496
|
+
* Save a single record to local DB and ingest into DBSP
|
|
497
|
+
* Used by mutations (create/update)
|
|
498
|
+
*/
|
|
499
|
+
save(cacheRecord: CacheRecord, skipDbInsert?: boolean): Promise<void>;
|
|
500
|
+
/**
|
|
501
|
+
* Save multiple records in a batch
|
|
502
|
+
* More efficient than calling save() multiple times
|
|
503
|
+
* Used by sync operations
|
|
504
|
+
*/
|
|
505
|
+
saveBatch(records: CacheRecord[], skipDbInsert?: boolean): Promise<void>;
|
|
506
|
+
/**
|
|
507
|
+
* Delete a record from local DB and ingest deletion into DBSP
|
|
508
|
+
*/
|
|
509
|
+
delete(table: string, id: string, skipDbDelete?: boolean, recordData?: Record<string, any>): Promise<void>;
|
|
510
|
+
/**
|
|
511
|
+
* Register a query with DBSP to create a materialized view
|
|
512
|
+
* Returns the initial result array
|
|
513
|
+
*/
|
|
514
|
+
registerQuery(config: QueryConfig$1): {
|
|
515
|
+
localArray: RecordVersionArray;
|
|
516
|
+
registrationTimings?: {
|
|
517
|
+
parseMs: number;
|
|
518
|
+
planMs: number;
|
|
519
|
+
snapshotMs: number;
|
|
520
|
+
};
|
|
521
|
+
};
|
|
522
|
+
/**
|
|
523
|
+
* Unregister a query from DBSP
|
|
524
|
+
*/
|
|
525
|
+
unregisterQuery(queryHash: string): void;
|
|
526
|
+
}
|
|
527
|
+
//#endregion
|
|
528
|
+
//#region src/modules/data/index.d.ts
|
|
529
|
+
/**
|
|
530
|
+
* DataModule - Unified query and mutation management
|
|
531
|
+
*
|
|
532
|
+
* Merges the functionality of QueryManager and MutationManager.
|
|
533
|
+
* Uses CacheModule for all storage operations.
|
|
534
|
+
*/
|
|
535
|
+
declare class DataModule<S extends SchemaStructure> {
|
|
536
|
+
private cache;
|
|
537
|
+
private local;
|
|
538
|
+
private schema;
|
|
539
|
+
private streamDebounceTime;
|
|
540
|
+
/** Tab identity baked into mutation ids (shared-tabs rollback routing);
|
|
541
|
+
* undefined in solo mode, where mutation-id falls back to a session id. */
|
|
542
|
+
private tabId;
|
|
543
|
+
private activeQueries;
|
|
544
|
+
private pendingQueries;
|
|
545
|
+
private subscriptions;
|
|
546
|
+
private statusSubscriptions;
|
|
547
|
+
private mutationCallbacks;
|
|
548
|
+
private debounceTimers;
|
|
549
|
+
private pendingStreamUpdates;
|
|
550
|
+
private fetchDepth;
|
|
551
|
+
private logger;
|
|
552
|
+
/**
|
|
553
|
+
* Optional observer notified whenever a query's fetch status changes.
|
|
554
|
+
* Wired by Sp00kyClient to push status changes into DevTools. Kept as a
|
|
555
|
+
* settable field (rather than a constructor arg) because DevTools is
|
|
556
|
+
* constructed after DataModule.
|
|
557
|
+
*/
|
|
558
|
+
onQueryStatusChange?: (hash: QueryHash, status: QueryStatus) => void;
|
|
559
|
+
/**
|
|
560
|
+
* Optional observer invoked when a still-subscribed query's TTL heartbeat
|
|
561
|
+
* fires (~90% of the TTL). Wired by Sp00kyClient to
|
|
562
|
+
* `Sp00kySync.heartbeatQuery`, which refreshes the remote `_00_query`
|
|
563
|
+
* row's `lastActiveAt` so an actively-watched query never expires. Settable
|
|
564
|
+
* field (not a constructor arg) because the sync engine is wired after
|
|
565
|
+
* DataModule is constructed — mirrors `onQueryStatusChange`.
|
|
566
|
+
*/
|
|
567
|
+
onHeartbeat?: (hash: QueryHash) => void;
|
|
568
|
+
/**
|
|
569
|
+
* Optional hook fired by {@link deregisterQuery} when an opt-in query (e.g. a
|
|
570
|
+
* viewport-windowed list cancelling an off-screen window) loses its last
|
|
571
|
+
* subscriber. Wired by Sp00kyClient to enqueue a `cleanup` down-event, which
|
|
572
|
+
* tears the remote `_00_query` view down (releasing its `_00_list_ref` edges)
|
|
573
|
+
* instead of leaving it for the TTL sweep. The local view + state are freed in
|
|
574
|
+
* {@link finalizeDeregister} only after that remote delete, so a fast
|
|
575
|
+
* re-subscribe (scroll back) can abort/heal the teardown — see `cleanupQuery`.
|
|
576
|
+
*/
|
|
577
|
+
onDeregister?: (hash: QueryHash) => void;
|
|
578
|
+
private sessionId;
|
|
579
|
+
private currentUserId;
|
|
580
|
+
constructor(cache: CacheModule, local: LocalStore, schema: S, logger: Logger$1, streamDebounceTime?: number);
|
|
581
|
+
init(sessionId: string): Promise<void>;
|
|
582
|
+
/**
|
|
583
|
+
* Update the session salt used in query-id hashing. Call this when the
|
|
584
|
+
* SurrealDB session changes (sign-in, sign-out, reconnect). Subsequently
|
|
585
|
+
* registered queries will get fresh, session-scoped IDs.
|
|
586
|
+
*/
|
|
587
|
+
setSessionId(sessionId: string): void;
|
|
588
|
+
/** Shared-tabs: bake this tab's identity into mutation ids so a rollback of
|
|
589
|
+
* a follower's mutation routes back to the tab that made it. */
|
|
590
|
+
setTabId(tabId: string): void;
|
|
591
|
+
/**
|
|
592
|
+
* Update the authenticated user record id. Pass `null` on sign-out.
|
|
593
|
+
* Read by `Sp00kySync.listRefTable()` so the LIVE subscription and
|
|
594
|
+
* the poll route to the same per-user `_00_list_ref_user_<id>` the
|
|
595
|
+
* SSP writes to.
|
|
596
|
+
*/
|
|
597
|
+
setCurrentUserId(userId: string | null): void;
|
|
598
|
+
/** Read-only view of the authenticated user id used for per-user
|
|
599
|
+
* `_00_list_ref` routing. Other modules consult this so they pick the
|
|
600
|
+
* same table name DataModule does. */
|
|
601
|
+
getCurrentUserId(): string | null;
|
|
602
|
+
/**
|
|
603
|
+
* Register a query and return its hash for subscriptions
|
|
604
|
+
*/
|
|
605
|
+
query<T extends TableNames<S>>(tableName: T, surqlString: string, params: Record<string, any>, ttl: QueryTimeToLive, plan?: QueryPlan): Promise<QueryHash>;
|
|
606
|
+
/**
|
|
607
|
+
* Subscribe to query updates
|
|
608
|
+
*/
|
|
609
|
+
subscribe(queryHash: string, callback: QueryUpdateCallback, options?: {
|
|
610
|
+
immediate?: boolean;
|
|
611
|
+
}): () => void;
|
|
612
|
+
/**
|
|
613
|
+
* Subscribe to a query's fetch-status changes (idle/fetching).
|
|
614
|
+
* With `{ immediate: true }` the callback fires synchronously with the
|
|
615
|
+
* current status (defaults to `idle` if the query isn't registered yet).
|
|
616
|
+
*/
|
|
617
|
+
subscribeStatus(queryHash: string, callback: QueryStatusCallback, options?: {
|
|
618
|
+
immediate?: boolean;
|
|
619
|
+
}): () => void;
|
|
620
|
+
/**
|
|
621
|
+
* Set a query's fetch status and notify status observers (DevTools +
|
|
622
|
+
* `subscribeStatus` listeners). No-op when the status is unchanged or the
|
|
623
|
+
* query is unknown.
|
|
624
|
+
*/
|
|
625
|
+
setQueryStatus(queryHash: string, status: QueryStatus): void;
|
|
626
|
+
/**
|
|
627
|
+
* Enter a fetch cycle for a query. Refcounted: registration and concurrent
|
|
628
|
+
* poll/LIVE sync rounds can overlap on the same hash, and only the OUTERMOST
|
|
629
|
+
* cycle may flip the status — 0→1 emits `fetching`, and `endFetching`'s 1→0
|
|
630
|
+
* emits `idle`. Always pair with `endFetching` in a `finally`.
|
|
631
|
+
*/
|
|
632
|
+
beginFetching(queryHash: string): void;
|
|
633
|
+
/** Leave a fetch cycle started with {@link beginFetching}; emits `idle` on the last exit. */
|
|
634
|
+
endFetching(queryHash: string): void;
|
|
635
|
+
/**
|
|
636
|
+
* Subscribe to mutations (for sync)
|
|
637
|
+
*/
|
|
638
|
+
onMutation(callback: MutationCallback): () => void;
|
|
639
|
+
/**
|
|
640
|
+
* Handle stream updates from DBSP (via CacheModule)
|
|
641
|
+
*/
|
|
642
|
+
onStreamUpdate(update: StreamUpdate): Promise<void>;
|
|
643
|
+
/**
|
|
644
|
+
* Process a query's pending (debounced) stream update NOW instead of on the
|
|
645
|
+
* trailing edge. Called by the sync engine before it flips a query back to
|
|
646
|
+
* `idle`, so the status change never races ahead of the rows it fetched.
|
|
647
|
+
* No-op when nothing is pending. The pending entry is removed before the
|
|
648
|
+
* await so a concurrently-firing timer can't process it twice.
|
|
649
|
+
*/
|
|
650
|
+
flushPendingStreamUpdate(queryHash: string): Promise<void>;
|
|
651
|
+
/**
|
|
652
|
+
* Materialize a query's result rows from the local store.
|
|
653
|
+
*
|
|
654
|
+
* A query's rows are its MEMBERSHIP — the id-set the server put in
|
|
655
|
+
* `_00_list_ref` (`remoteArray`) — not "every local body that matches the
|
|
656
|
+
* WHERE". Those two disagree, and the disagreement was the bug: when a row
|
|
657
|
+
* leaves a query's window but still exists upstream, `handleRemovedRecords`
|
|
658
|
+
* keeps its local body and never re-fetches it, so a predicate re-scan finds
|
|
659
|
+
* that stale body still matching and keeps rendering the row. Selecting the
|
|
660
|
+
* id-set directly is also the only correct thing for a windowed query, where
|
|
661
|
+
* re-applying `START m` against the shared local store skips the window's own
|
|
662
|
+
* rows entirely (sparse windowing) and returns nothing.
|
|
663
|
+
*
|
|
664
|
+
* The rendered set is:
|
|
665
|
+
*
|
|
666
|
+
* (membership ∪ (pendingWrites ∩ localArray)) − pendingDeletes
|
|
667
|
+
*
|
|
668
|
+
* The middle term keeps optimistic writes visible without re-admitting stale
|
|
669
|
+
* rows. Every local write is fed to the SSP (`cache.saveBatch` →
|
|
670
|
+
* `ingestMany`), so `localArray` answers "does this row match the predicate
|
|
671
|
+
* per LOCAL truth". A pending write that moves a row into the window is in
|
|
672
|
+
* `localArray` and shows; one that moves a row out is absent and does not; a
|
|
673
|
+
* stale body the server dropped has no pending write at all, so it stays out.
|
|
674
|
+
* `pendingDeletes` covers the reverse lag — the server still lists a row whose
|
|
675
|
+
* DELETE is sitting in our outbox.
|
|
676
|
+
*
|
|
677
|
+
* Falls back to the predicate scan only when membership has never been
|
|
678
|
+
* established (a query first run on this device), so an offline first paint
|
|
679
|
+
* still shows something.
|
|
680
|
+
*/
|
|
681
|
+
private materializeRecords;
|
|
682
|
+
/**
|
|
683
|
+
* The materialization itself, without the DevTools timing wrapper. Split out so
|
|
684
|
+
* cold-start seeding can use it before a `QueryState` exists.
|
|
685
|
+
*/
|
|
686
|
+
private materializeFromConfig;
|
|
687
|
+
/**
|
|
688
|
+
* The authoritative membership list to render from, or `null` when membership
|
|
689
|
+
* has never been established and the caller must fall back to a scan.
|
|
690
|
+
*
|
|
691
|
+
* A windowed query has no usable fallback — re-running its `START m` locally
|
|
692
|
+
* returns the wrong rows — so it renders from whatever id-set is on hand
|
|
693
|
+
* (SSP's included) rather than degrading to a scan. That is the pre-existing
|
|
694
|
+
* behavior for windows and is preserved.
|
|
695
|
+
*/
|
|
696
|
+
private resolveMembership;
|
|
697
|
+
private readonly settledWrites;
|
|
698
|
+
private readonly settledDeletes;
|
|
699
|
+
/**
|
|
700
|
+
* Grace period for a settled write. Long enough to cover an SSP round trip
|
|
701
|
+
* that is running slowly (seconds, not milliseconds, when the edge path is
|
|
702
|
+
* backed up), short enough that a write the server silently dropped cannot
|
|
703
|
+
* linger misleadingly.
|
|
704
|
+
*
|
|
705
|
+
* The rejection case does NOT rely on this expiring: an application error
|
|
706
|
+
* rolls the mutation back and never reports it settled, so it vanishes at
|
|
707
|
+
* once. This deadline only bounds the case where the write succeeded and its
|
|
708
|
+
* membership never arrived at all.
|
|
709
|
+
*/
|
|
710
|
+
private static readonly SETTLED_WRITE_GRACE_MS;
|
|
711
|
+
/**
|
|
712
|
+
* Report that a mutation was accepted by the server and its outbox row
|
|
713
|
+
* removed. Called only on the SUCCESS path — a rolled-back mutation must
|
|
714
|
+
* disappear immediately, which is what makes this safe.
|
|
715
|
+
*/
|
|
716
|
+
noteWriteSettled(recordId: string, mutationType: string): void;
|
|
717
|
+
/** Drop entries past their deadline. */
|
|
718
|
+
private pruneSettled;
|
|
719
|
+
/** Apply the pending-write union and pending-delete subtraction, and map to
|
|
720
|
+
* RecordIds for the engines' id-set path. */
|
|
721
|
+
private buildRenderIds;
|
|
722
|
+
private processStreamUpdate;
|
|
723
|
+
/**
|
|
724
|
+
* Compute p55/p90/p99 from a rolling window of materialization samples.
|
|
725
|
+
* Returns nulls for any percentile that has no samples yet so SurrealDB
|
|
726
|
+
* `option<float>` columns stay NONE rather than 0 before the first ingest.
|
|
727
|
+
*/
|
|
728
|
+
private computeMaterializationPercentiles;
|
|
729
|
+
/** Record a per-phase timing sample (ms) on a query's rolling window. */
|
|
730
|
+
private recordPhase;
|
|
731
|
+
/** Record the remote record-fetch time (ms) for a query. Called by the sync engine. */
|
|
732
|
+
recordRemoteFetch(hash: string, ms: number): void;
|
|
733
|
+
/**
|
|
734
|
+
* Record the frontend reconcile time (ms) for a query. Called from `useQuery`
|
|
735
|
+
* via `Sp00kyClient.reportFrontendTiming` after it applies an update to its store.
|
|
736
|
+
*/
|
|
737
|
+
recordFrontendTiming(hash: string, ms: number): void;
|
|
738
|
+
/**
|
|
739
|
+
* Build the per-query processing-time breakdown surfaced to the DevTools panel
|
|
740
|
+
* and the MCP. `ssp` is the WASM-ingest wall time (from `materializationSamples`);
|
|
741
|
+
* the rest come from the per-phase rolling windows + one-shot registration timings.
|
|
742
|
+
*/
|
|
743
|
+
phaseTimings(q: QueryState): QueryTimings;
|
|
744
|
+
/**
|
|
745
|
+
* Get query state (for sync and devtools)
|
|
746
|
+
*/
|
|
747
|
+
getQueryByHash(hash: string): QueryState | undefined;
|
|
748
|
+
/**
|
|
749
|
+
* Cold-query guard for instant-hydrate: true when the query exists, hasn't been
|
|
750
|
+
* hydrated, and has NOT yet fetched its server result (`remoteArray` empty).
|
|
751
|
+
* We gate on `remoteArray`, not local `records`: a windowed query is often
|
|
752
|
+
* partially pre-seeded from the circuit (e.g. the dashboard's 5-row preview),
|
|
753
|
+
* but it still hasn't loaded its own full window from the server — so it should
|
|
754
|
+
* still hydrate. A warm re-subscribe (remoteArray already populated) is skipped.
|
|
755
|
+
*/
|
|
756
|
+
isCold(hash: string): boolean;
|
|
757
|
+
/**
|
|
758
|
+
* Walk a hydrated record's fields and append any EMBEDDED child records to
|
|
759
|
+
* `batch` (recursing for nested related fields). An embedded child is a
|
|
760
|
+
* value that is itself a record — a non-null object whose `id` is a
|
|
761
|
+
* `RecordId` — or an array of such records (one-to-many vs one-to-one). A
|
|
762
|
+
* bare `RecordId` (a foreign-key reference) or any other value is skipped,
|
|
763
|
+
* so this never mistakes a FK column for an embedded body. Children are
|
|
764
|
+
* keyed by their own `record.id.table`, versioned by `_00_rv`, and cleaned
|
|
765
|
+
* to their table's real columns (which strips the alias/related fields).
|
|
766
|
+
* `seen` dedupes within the batch.
|
|
767
|
+
*/
|
|
768
|
+
private collectEmbeddedChildren;
|
|
769
|
+
/**
|
|
770
|
+
* Prepare a subquery-bearing row (preload / hydration) for the schemafull
|
|
771
|
+
* local store: replace an embedded FORWARD-relation object (`author = { id, … }`)
|
|
772
|
+
* with its RecordId so a `record<…>` field coerces, and DROP reverse-subquery
|
|
773
|
+
* ARRAYS (`comments = [ … ]`) since their rows are cached separately as their
|
|
774
|
+
* own bodies. A flat record — as the live `SELECT * FROM $ids` sync returns,
|
|
775
|
+
* with relations already RecordIds — passes through unchanged.
|
|
776
|
+
*/
|
|
777
|
+
private flattenRelationsForStorage;
|
|
778
|
+
/**
|
|
779
|
+
* Instant-hydrate: ingest rows fetched one-shot from the remote (the query's own
|
|
780
|
+
* surql run directly) so the query DISPLAYS immediately, while the full realtime
|
|
781
|
+
* registration proceeds in the background. Ingests with versions (`_00_rv`) so the
|
|
782
|
+
* later `syncRecords` dedup skips re-pulling unchanged bodies, and seeds
|
|
783
|
+
* `remoteArray` so windowed queries materialize the correct window (no sparse
|
|
784
|
+
* local-circuit issue). Runs at most once per query (the `hydrated` flag).
|
|
785
|
+
*/
|
|
786
|
+
applyHydration(hash: string, rows: RecordWithId[]): Promise<void>;
|
|
787
|
+
/**
|
|
788
|
+
* Build the cache batch for a set of one-shot rows and persist it to the
|
|
789
|
+
* local DB + in-browser SSP. Maps each row to a `CREATE` op on its own table
|
|
790
|
+
* and extracts EMBEDDED related children (any nesting depth) as their own
|
|
791
|
+
* records — a `.related()` query returns its children embedded, and a later
|
|
792
|
+
* correlated re-materialization needs them present as standalone rows.
|
|
793
|
+
* Shared by `applyHydration` (live registration) and `persistSnapshot`
|
|
794
|
+
* (preload).
|
|
795
|
+
*/
|
|
796
|
+
private buildAndSaveCacheBatch;
|
|
797
|
+
/**
|
|
798
|
+
* Preload/prewarm: persist one-shot rows (and their embedded related children)
|
|
799
|
+
* into the local cache WITHOUT registering a query — no `activeQueries` entry,
|
|
800
|
+
* no `_00_query` view, no TTL heartbeat. The rows live in the local DB as
|
|
801
|
+
* ordinary bodies (never GC'd on their own) so a later `useQuery` seeds its
|
|
802
|
+
* first paint from them instantly, then registers a live view to freshen.
|
|
803
|
+
*/
|
|
804
|
+
persistSnapshot(tableName: string, rows: RecordWithId[]): Promise<void>;
|
|
805
|
+
/**
|
|
806
|
+
* Read the durable preload freshness marker for a query hash, or null if this
|
|
807
|
+
* query was never preloaded in the current bucket. Co-located with the cached
|
|
808
|
+
* rows (per-bucket `_00_preload` table) so a bucket switch that clears the
|
|
809
|
+
* data also clears the marker — a stale marker can't claim "warm" when the
|
|
810
|
+
* rows are gone. Any read error is treated as cold.
|
|
811
|
+
*/
|
|
812
|
+
getPreloadMarker(hash: string): Promise<{
|
|
813
|
+
fetchedAt: number;
|
|
814
|
+
rowCount: number;
|
|
815
|
+
} | null>;
|
|
816
|
+
/** Stamp the preload freshness marker after a successful snapshot fetch. */
|
|
817
|
+
writePreloadMarker(hash: string, rowCount: number): Promise<void>;
|
|
818
|
+
/**
|
|
819
|
+
* Read the durable membership row, or `null` if this query has never had
|
|
820
|
+
* authoritative membership on this device. Any read error is treated as
|
|
821
|
+
* "unknown" so a broken row degrades to the predicate scan rather than
|
|
822
|
+
* rendering an empty list.
|
|
823
|
+
*/
|
|
824
|
+
getWindowMembership(key: string): Promise<RecordVersionArray | null>;
|
|
825
|
+
/** Persist the durable membership row. Best-effort: callers must not fail a
|
|
826
|
+
* sync round because the mirror write failed. */
|
|
827
|
+
writeWindowMembership(key: string, ids: RecordVersionArray): Promise<void>;
|
|
828
|
+
/**
|
|
829
|
+
* Record ids with a mutation still in the outbox, split by direction.
|
|
830
|
+
*
|
|
831
|
+
* Both halves feed {@link materializeRecords}: `writes` keeps optimistic
|
|
832
|
+
* creates/updates visible before the server has acknowledged them, and
|
|
833
|
+
* `deletes` suppresses rows the server still lists because our DELETE hasn't
|
|
834
|
+
* been processed yet. Reading `_00_pending_mutations` (rather than tracking
|
|
835
|
+
* ids in memory) is what makes both survive a reload.
|
|
836
|
+
*
|
|
837
|
+
* On failure returns empty sets: membership alone then decides, which can
|
|
838
|
+
* briefly hide an optimistic write but never resurrects a deleted row.
|
|
839
|
+
*/
|
|
840
|
+
getPendingRecordIds(): Promise<{
|
|
841
|
+
writes: Set<string>;
|
|
842
|
+
deletes: Set<string>;
|
|
843
|
+
}>;
|
|
844
|
+
/** True while ≥1 live subscriber is watching this query (refcount guard). */
|
|
845
|
+
hasSubscribers(hash: string): boolean;
|
|
846
|
+
/**
|
|
847
|
+
* Opt-in eager teardown for a query whose LAST subscriber just left — used by
|
|
848
|
+
* viewport-windowed lists to cancel off-screen windows instead of leaving
|
|
849
|
+
* their remote views to expire on the TTL sweep. No-op while any subscriber
|
|
850
|
+
* remains (refcount). Only enqueues the remote cleanup here; the local WASM
|
|
851
|
+
* view + in-memory state are freed in {@link finalizeDeregister} after the
|
|
852
|
+
* remote delete completes, so a re-subscribe in between aborts/heals it.
|
|
853
|
+
*
|
|
854
|
+
* NOTE: most queries should NOT use this — the default keep-alive on
|
|
855
|
+
* unsubscribe avoids re-registration churn on navigation.
|
|
856
|
+
*/
|
|
857
|
+
deregisterQuery(hash: string): void;
|
|
858
|
+
/**
|
|
859
|
+
* Final local teardown after the remote `_00_query` row was deleted: free the
|
|
860
|
+
* WASM view, heartbeat timer, debounce timer, and in-memory state. Caller
|
|
861
|
+
* (`cleanupQuery`) guarantees no subscriber remains.
|
|
862
|
+
*/
|
|
863
|
+
finalizeDeregister(hash: string): void;
|
|
864
|
+
/**
|
|
865
|
+
* Get query state by id (for sync and devtools)
|
|
866
|
+
*/
|
|
867
|
+
getQueryById(id: RecordId<string>): QueryState | undefined;
|
|
868
|
+
/**
|
|
869
|
+
* Get all active queries (for devtools)
|
|
870
|
+
*/
|
|
871
|
+
getActiveQueries(): QueryState[];
|
|
872
|
+
getActiveQueryHashes(): QueryHash[];
|
|
873
|
+
updateQueryLocalArray(id: string, localArray: RecordVersionArray): Promise<void>;
|
|
874
|
+
updateQueryRemoteArray(hash: string, remoteArray: RecordVersionArray, opts?: {
|
|
875
|
+
/** `_00_query.rowCount` read in the same round trip; `null` = unknown. */
|
|
876
|
+
serverRowCount?: number | null;
|
|
877
|
+
}): Promise<void>;
|
|
878
|
+
/**
|
|
879
|
+
* Cancel every armed timer ahead of a local-bucket switch: stream-update
|
|
880
|
+
* debounce timers (their pending updates carry the OLD bucket's id-sets) and
|
|
881
|
+
* per-query TTL heartbeats (they'd refresh the previous user's remote
|
|
882
|
+
* `_00_query` rows under the new session). The rebind re-arms heartbeats.
|
|
883
|
+
*/
|
|
884
|
+
quiesce(): void;
|
|
885
|
+
/**
|
|
886
|
+
* Re-home every active query in a freshly-opened bucket, KEEPING its hash —
|
|
887
|
+
* `useQuery` subscriptions are keyed by hash and don't re-register on auth
|
|
888
|
+
* changes, so the hooks must stay attached. Per query:
|
|
889
|
+
* 1. reset the sync arrays + hydration flag and drop the previous user's
|
|
890
|
+
* records, notifying subscribers with the new-bucket materialization
|
|
891
|
+
* (usually empty) so their rows leave the UI immediately;
|
|
892
|
+
* 2. recreate the `_00_query` row in the new bucket;
|
|
893
|
+
* 3. re-register the SSP view on the (fresh, post-reset) processor — this
|
|
894
|
+
* also rebinds the view to the NEW `$auth` context;
|
|
895
|
+
* 4. restart the TTL heartbeat.
|
|
896
|
+
* Returns the hashes so the caller can enqueue remote re-registration, which
|
|
897
|
+
* refills records from the server via the normal register→sync→notify path.
|
|
898
|
+
*/
|
|
899
|
+
rebindAfterBucketSwitch(): Promise<QueryHash[]>;
|
|
900
|
+
/**
|
|
901
|
+
* Called after a query's initial sync completes.
|
|
902
|
+
* Ensures subscribers are notified even if no stream updates fired (e.g. empty result set).
|
|
903
|
+
*/
|
|
904
|
+
notifyQuerySynced(queryHash: string): Promise<void>;
|
|
905
|
+
run<B extends BackendNames<S>, R extends BackendRoutes<S, B>>(backend: B, path: R, data: RoutePayload<S, B, R>, options?: RunOptions): Promise<void>;
|
|
906
|
+
/**
|
|
907
|
+
* Build the outbox job record + resolve its table for a backend route.
|
|
908
|
+
*
|
|
909
|
+
* Every job is a single execution. Recurring work is declared server-side
|
|
910
|
+
* (`schedules:` in sp00ky.yml) and the scheduler creates a fresh row per cycle,
|
|
911
|
+
* so nothing here needs to know about schedules.
|
|
912
|
+
*/
|
|
913
|
+
private buildJobRecord;
|
|
914
|
+
/**
|
|
915
|
+
* Create a new record
|
|
916
|
+
*/
|
|
917
|
+
create<T extends Record<string, unknown>>(id: string, data: T): Promise<T>;
|
|
918
|
+
/**
|
|
919
|
+
* Update an existing record
|
|
920
|
+
*/
|
|
921
|
+
update<T extends Record<string, unknown>>(table: string, id: string, data: Partial<T>, options?: UpdateOptions): Promise<T>;
|
|
922
|
+
/**
|
|
923
|
+
* Delete a record
|
|
924
|
+
*/
|
|
925
|
+
delete(table: string, id: string): Promise<void>;
|
|
926
|
+
/**
|
|
927
|
+
* Rollback a failed optimistic create by deleting the record locally
|
|
928
|
+
*/
|
|
929
|
+
rollbackCreate(recordId: RecordId, tableName: string): Promise<void>;
|
|
930
|
+
/**
|
|
931
|
+
* Rollback a failed optimistic update by restoring the previous record state
|
|
932
|
+
*/
|
|
933
|
+
rollbackUpdate(recordId: RecordId, tableName: string, beforeRecord: Record<string, unknown>): Promise<void>;
|
|
934
|
+
/**
|
|
935
|
+
* Remove a record from all active query states and notify subscribers
|
|
936
|
+
*/
|
|
937
|
+
private removeRecordFromQueries;
|
|
938
|
+
private createAndRegisterQuery;
|
|
939
|
+
private createNewQuery;
|
|
940
|
+
private calculateHash;
|
|
941
|
+
/**
|
|
942
|
+
* Session-independent counterpart of {@link calculateHash}: the key for a
|
|
943
|
+
* query's durable `_00_window` membership row.
|
|
944
|
+
*
|
|
945
|
+
* Deliberately the SAME inputs minus the `session::id()` salt, so the two keys
|
|
946
|
+
* can never drift apart. The salt is right for `_00_query` (two tabs must not
|
|
947
|
+
* fight over one row) and wrong for membership, which has to be recognizable
|
|
948
|
+
* after a reload — a reload mints a new session id, and offline the salt is
|
|
949
|
+
* `''`, so a salted key can never match what the previous session wrote.
|
|
950
|
+
*/
|
|
951
|
+
private calculateMembershipKey;
|
|
952
|
+
private sha256;
|
|
953
|
+
private startTTLHeartbeat;
|
|
954
|
+
private replaceRecordInQueries;
|
|
955
|
+
}
|
|
956
|
+
/**
|
|
957
|
+
* Parse update options to generate push event options
|
|
958
|
+
*/
|
|
959
|
+
//#endregion
|
|
960
|
+
//#region src/services/tabs/protocol.d.ts
|
|
961
|
+
type TabId = string;
|
|
962
|
+
type TabRole = 'solo' | 'leader' | 'follower';
|
|
963
|
+
/** Broker pings every tab at this cadence. */
|
|
964
|
+
|
|
965
|
+
/** Matches `CacheIngestTuple` (modules/cache): exactly what `ingestMany`
|
|
966
|
+
* consumes, so relayed batches feed follower circuits without reshaping. */
|
|
967
|
+
interface IngestTuple {
|
|
968
|
+
table: string;
|
|
969
|
+
op: 'CREATE' | 'UPDATE' | 'DELETE';
|
|
970
|
+
id: string;
|
|
971
|
+
record: Record<string, unknown>;
|
|
972
|
+
}
|
|
973
|
+
type FollowerToLeaderMessage = {
|
|
974
|
+
type: 'sync-hello';
|
|
975
|
+
tabId: TabId;
|
|
976
|
+
}
|
|
977
|
+
/** The follower committed an outbox row (through the shared store) and the
|
|
978
|
+
* leader should drain it. Idempotent; a new leader's loadFromDatabase is
|
|
979
|
+
* the backstop for a notify lost in a failover window. */ | {
|
|
980
|
+
type: 'mutation-enqueued';
|
|
981
|
+
mutationId: string;
|
|
982
|
+
} | {
|
|
983
|
+
type: 'request-poll';
|
|
984
|
+
};
|
|
985
|
+
type LeaderToFollowerMessage = {
|
|
986
|
+
type: 'db-ready';
|
|
987
|
+
leadershipId: number;
|
|
988
|
+
bucketId: string;
|
|
989
|
+
storageHealth: StorageHealth;
|
|
990
|
+
}
|
|
991
|
+
/** Every ingest the leader's CacheModule committed, so follower circuits
|
|
992
|
+
* stay live without their own fetch. seq detects gaps. */ | {
|
|
993
|
+
type: 'ingest-relay';
|
|
994
|
+
tuples: IngestTuple[];
|
|
995
|
+
leadershipId: number;
|
|
996
|
+
seq: number;
|
|
997
|
+
}
|
|
998
|
+
/** A `_00_list_ref` LIVE event, relayed verbatim. Each follower resolves the
|
|
999
|
+
* queryId against its own DataModule and ignores foreign queries. */ | {
|
|
1000
|
+
type: 'list-ref-change';
|
|
1001
|
+
action: 'CREATE' | 'UPDATE' | 'DELETE';
|
|
1002
|
+
queryId: string;
|
|
1003
|
+
recordId: string;
|
|
1004
|
+
version: number;
|
|
1005
|
+
parent: boolean;
|
|
1006
|
+
}
|
|
1007
|
+
/** The leader's drain rolled back a mutation owned by this tab. */ | {
|
|
1008
|
+
type: 'mutation-rolled-back';
|
|
1009
|
+
mutationId: string;
|
|
1010
|
+
recordId: string;
|
|
1011
|
+
eventType: 'create' | 'update' | 'delete';
|
|
1012
|
+
error: string;
|
|
1013
|
+
};
|
|
1014
|
+
//#endregion
|
|
1015
|
+
//#region src/services/tabs/coordinator.d.ts
|
|
1016
|
+
/** Leader-side fan-out surface handed to the sync layer. The sync router
|
|
1017
|
+
* (modules/sync/tab-router.ts) registers itself as the message handler. */
|
|
1018
|
+
declare class LeaderSyncHub {
|
|
1019
|
+
readonly leadershipId: number;
|
|
1020
|
+
private logger;
|
|
1021
|
+
private followers;
|
|
1022
|
+
private seq;
|
|
1023
|
+
onFollowerMessage: ((tabId: TabId, msg: FollowerToLeaderMessage) => void) | null;
|
|
1024
|
+
onFollowerDetached: ((tabId: TabId) => void) | null;
|
|
1025
|
+
constructor(leadershipId: number, logger: Logger$1);
|
|
1026
|
+
attach(tabId: TabId, port: MessagePort): void;
|
|
1027
|
+
detach(tabId: TabId): void;
|
|
1028
|
+
detachAll(): void;
|
|
1029
|
+
sendTo(tabId: TabId, msg: LeaderToFollowerMessage): void;
|
|
1030
|
+
broadcast(msg: LeaderToFollowerMessage, exceptTabId?: TabId): void;
|
|
1031
|
+
/** Stamped ingest relay; seq lets followers detect gaps. */
|
|
1032
|
+
relayIngest(tuples: IngestTuple[], exceptTabId?: TabId): void;
|
|
1033
|
+
get followerCount(): number;
|
|
1034
|
+
get relayedBatches(): number;
|
|
1035
|
+
}
|
|
1036
|
+
/** Follower half of the syncPort. Queues while detached (leaderless window)
|
|
1037
|
+
* and flushes on rebind; a lost-in-flight mutation notify is additionally
|
|
1038
|
+
* backstopped by the new leader reloading the shared outbox from the store. */
|
|
1039
|
+
declare class SyncForwarder {
|
|
1040
|
+
private tabId;
|
|
1041
|
+
private port;
|
|
1042
|
+
private queued;
|
|
1043
|
+
onLeaderMessage: ((msg: LeaderToFollowerMessage) => void) | null;
|
|
1044
|
+
constructor(tabId: TabId);
|
|
1045
|
+
rebind(port: MessagePort): void;
|
|
1046
|
+
unbind(): void;
|
|
1047
|
+
private post;
|
|
1048
|
+
mutationEnqueued(mutationId: string): void;
|
|
1049
|
+
requestPoll(): void;
|
|
1050
|
+
}
|
|
1051
|
+
//#endregion
|
|
1052
|
+
//#region src/modules/sync/sync.d.ts
|
|
1053
|
+
/**
|
|
1054
|
+
* Tunables for `Sp00kySync` construction.
|
|
1055
|
+
*/
|
|
1056
|
+
interface Sp00kySyncOptions {
|
|
1057
|
+
/**
|
|
1058
|
+
* Cadence (ms) for the `_00_list_ref` poll fallback that catches
|
|
1059
|
+
* cross-session UPDATEs the LIVE-permission gap drops. Non-positive
|
|
1060
|
+
* values fall back to the default; see
|
|
1061
|
+
* {@link resolveListRefPollInterval}.
|
|
1062
|
+
*/
|
|
1063
|
+
refSyncIntervalMs?: number;
|
|
1064
|
+
/**
|
|
1065
|
+
* Enable realtime sync for unauthenticated clients against the shared
|
|
1066
|
+
* `_00_list_ref_anon` table. See {@link Sp00kyConfig.enableAnonymousLiveQueries}.
|
|
1067
|
+
* Defaults to `false`.
|
|
1068
|
+
*/
|
|
1069
|
+
anonymousLiveQueries?: boolean;
|
|
1070
|
+
/**
|
|
1071
|
+
* Consecutive failed sync rounds before sync health flips to `degraded`.
|
|
1072
|
+
* `0` disables degraded reporting. See {@link Sp00kyConfig.syncHealth}.
|
|
1073
|
+
* Defaults to `3`.
|
|
1074
|
+
*/
|
|
1075
|
+
degradeAfterConsecutiveFailures?: number;
|
|
1076
|
+
/**
|
|
1077
|
+
* Max time a single mutation push may take before it is treated as a network
|
|
1078
|
+
* failure and retried. Guards against an RPC that never settles wedging the
|
|
1079
|
+
* up-queue for the session. Defaults to 30000; `0` disables the timeout.
|
|
1080
|
+
*/
|
|
1081
|
+
pushTimeoutMs?: number;
|
|
1082
|
+
/**
|
|
1083
|
+
* Transport supervisor. Sync reads its state to report `connection` in
|
|
1084
|
+
* {@link SyncHealth} so a UI can show "reconnecting…" the instant the socket
|
|
1085
|
+
* drops, without waiting for the degrade threshold. Optional: omitted in
|
|
1086
|
+
* tests, where `connection` then reports `connected`.
|
|
1087
|
+
*/
|
|
1088
|
+
connectionSupervisor?: ConnectionSupervisor;
|
|
1089
|
+
}
|
|
1090
|
+
/**
|
|
1091
|
+
* The main synchronization engine for Sp00ky.
|
|
1092
|
+
* Handles the bidirectional synchronization between the local database and the remote backend.
|
|
1093
|
+
* Uses a queue-based architecture with 'up' (local to remote) and 'down' (remote to local) queues.
|
|
1094
|
+
* @template S The schema structure type.
|
|
1095
|
+
*/
|
|
1096
|
+
declare class Sp00kySync<S extends SchemaStructure> {
|
|
1097
|
+
private local;
|
|
1098
|
+
private remote;
|
|
1099
|
+
private cache;
|
|
1100
|
+
private dataModule;
|
|
1101
|
+
private schema;
|
|
1102
|
+
private upQueue;
|
|
1103
|
+
private downQueue;
|
|
1104
|
+
private isInit;
|
|
1105
|
+
private logger;
|
|
1106
|
+
private syncEngine;
|
|
1107
|
+
/** Engine-level events (e.g. `SYNC_REMOTE_DATA_INGESTED`). Distinct
|
|
1108
|
+
* from `this.events`, which carries Sp00kySync-level events like
|
|
1109
|
+
* `SYNC_QUERY_UPDATED` and `SYNC_MUTATION_ROLLED_BACK`. */
|
|
1110
|
+
get engineEvents(): SyncEventSystem;
|
|
1111
|
+
private scheduler;
|
|
1112
|
+
/**
|
|
1113
|
+
* Set by any event that means the socket we registered on is gone, so the
|
|
1114
|
+
* next `connected` knows it must re-subscribe rather than treat itself as the
|
|
1115
|
+
* initial connect. See {@link subscribeToReconnect}.
|
|
1116
|
+
*/
|
|
1117
|
+
private needsResubscribe;
|
|
1118
|
+
/** When the last reconnect-driven full refetch ran, for burst coalescing. */
|
|
1119
|
+
private lastReconnectRefetchAt;
|
|
1120
|
+
/**
|
|
1121
|
+
* Minimum gap between reconnect-driven full refetches. Long enough to absorb
|
|
1122
|
+
* a flapping socket (the SDK reconnect ladder starts at 1s), short enough
|
|
1123
|
+
* that a genuine drop minutes later still refetches.
|
|
1124
|
+
*/
|
|
1125
|
+
private static readonly RECONNECT_REFETCH_COOLDOWN_MS;
|
|
1126
|
+
events: SyncEventSystem;
|
|
1127
|
+
private currentUserId;
|
|
1128
|
+
private tabRole;
|
|
1129
|
+
private tabId;
|
|
1130
|
+
private hub;
|
|
1131
|
+
private forwarder;
|
|
1132
|
+
private refMode;
|
|
1133
|
+
private readonly anonLiveEnabled;
|
|
1134
|
+
private currentLiveQueryUuid;
|
|
1135
|
+
private liveQueryUnsubscribe;
|
|
1136
|
+
private listRefPollTimer;
|
|
1137
|
+
private listRefPollRunning;
|
|
1138
|
+
private listRefPollInFlight;
|
|
1139
|
+
readonly refSyncIntervalMs: number;
|
|
1140
|
+
private listRefIdleStreak;
|
|
1141
|
+
private stillRemoteStreaks;
|
|
1142
|
+
private lastLiveEventAt;
|
|
1143
|
+
private _liveRetryCount;
|
|
1144
|
+
get liveRetryCount(): number;
|
|
1145
|
+
get isSyncing(): boolean;
|
|
1146
|
+
get pendingMutationCount(): number;
|
|
1147
|
+
subscribeToPendingMutations(cb: (count: number) => void): () => void;
|
|
1148
|
+
private readonly degradeAfterFailures;
|
|
1149
|
+
/** Per-push RPC deadline; see {@link withPushTimeout}. */
|
|
1150
|
+
private readonly pushTimeoutMs;
|
|
1151
|
+
private consecutiveSyncFailures;
|
|
1152
|
+
private syncHealthStatus;
|
|
1153
|
+
private lastSyncErrorKind;
|
|
1154
|
+
private lastSyncErrorMessage;
|
|
1155
|
+
private hasSyncedOnce;
|
|
1156
|
+
private selfHealTimer;
|
|
1157
|
+
private selfHealAttempts;
|
|
1158
|
+
private static readonly SELF_HEAL_BASE_MS;
|
|
1159
|
+
private static readonly SELF_HEAL_MAX_MS;
|
|
1160
|
+
/**
|
|
1161
|
+
* Transport supervisor, when one was supplied. Sync only reads state from it;
|
|
1162
|
+
* it never drives reconnects itself.
|
|
1163
|
+
*/
|
|
1164
|
+
private readonly connectionSupervisor?;
|
|
1165
|
+
/**
|
|
1166
|
+
* Mirror of the supervisor's state. Defaults to `connected` so a client
|
|
1167
|
+
* constructed without a supervisor (tests, embedders) reports the same health
|
|
1168
|
+
* shape it always has rather than a permanent false "disconnected".
|
|
1169
|
+
*/
|
|
1170
|
+
private connectionState;
|
|
1171
|
+
/** Current sync-health snapshot. */
|
|
1172
|
+
get syncHealth(): SyncHealth;
|
|
1173
|
+
/**
|
|
1174
|
+
* Observe sync health. The callback fires immediately with the current
|
|
1175
|
+
* status and again on every healthy↔degraded transition. Returns an
|
|
1176
|
+
* unsubscribe. Mirrors {@link subscribeToPendingMutations}.
|
|
1177
|
+
*/
|
|
1178
|
+
subscribeToSyncHealth(cb: (health: SyncHealth) => void): () => void;
|
|
1179
|
+
private emitSyncHealth;
|
|
1180
|
+
/**
|
|
1181
|
+
* Mirror the supervisor's transport state into {@link SyncHealth} and emit on
|
|
1182
|
+
* every change, so a UI can react to a dropped socket immediately instead of
|
|
1183
|
+
* waiting for `degradeAfterFailures` failed rounds. `status` is untouched:
|
|
1184
|
+
* a brief reconnect is not a degradation.
|
|
1185
|
+
*
|
|
1186
|
+
* No explicit unsubscribe: the supervisor is owned by the same client and
|
|
1187
|
+
* drops all subscribers in its own `dispose()`, which `Sp00kyClient.close()`
|
|
1188
|
+
* calls first.
|
|
1189
|
+
*/
|
|
1190
|
+
private subscribeToConnectionState;
|
|
1191
|
+
/**
|
|
1192
|
+
* Fed by the scheduler once per drained sync round. Individual failures are
|
|
1193
|
+
* absorbed by the queue's retry; only a run of `degradeAfterFailures`
|
|
1194
|
+
* consecutive failures flips the status to `degraded`, and the next clean
|
|
1195
|
+
* round flips it back. No-op when reporting is disabled (`degradeAfterFailures`
|
|
1196
|
+
* is 0).
|
|
1197
|
+
*/
|
|
1198
|
+
private recordSyncOutcome;
|
|
1199
|
+
/**
|
|
1200
|
+
* Begin self-heal retries (no-op if already running). Started on the
|
|
1201
|
+
* healthy→degraded transition; {@link recordSyncOutcome} stops it on recovery.
|
|
1202
|
+
*/
|
|
1203
|
+
private startSelfHeal;
|
|
1204
|
+
private scheduleSelfHeal;
|
|
1205
|
+
private stopSelfHeal;
|
|
1206
|
+
/**
|
|
1207
|
+
* Release a deregistered query's remote view immediately instead of leaving
|
|
1208
|
+
* it to the TTL sweep. Off by default; see the reasoning in
|
|
1209
|
+
* {@link cleanupQuery}. Kept as a field rather than deleted so the eager path
|
|
1210
|
+
* can be re-enabled in a test once the subquery-body repair path exists.
|
|
1211
|
+
*/
|
|
1212
|
+
private readonly releaseQueriesEagerly;
|
|
1213
|
+
constructor(local: LocalStore, remote: RemoteDatabaseService, cache: CacheModule, dataModule: DataModule<S>, schema: S, logger: Logger$1, options?: Sp00kySyncOptions);
|
|
1214
|
+
/**
|
|
1215
|
+
* Initializes the synchronization system.
|
|
1216
|
+
* Starts the scheduler and initiates the initial sync cycles.
|
|
1217
|
+
* @throws Error if already initialized.
|
|
1218
|
+
*/
|
|
1219
|
+
init(): Promise<void>;
|
|
1220
|
+
/** Set BEFORE init(): shapes what init boots (a follower loads no outbox and
|
|
1221
|
+
* never starts LIVE; its own registration/poll paths stay untouched). */
|
|
1222
|
+
setTabContext(role: 'solo' | 'leader' | 'follower', tabId: string | null): void;
|
|
1223
|
+
/** Leader duties: drain the shared outbox, own the single list_ref LIVE,
|
|
1224
|
+
* relay LIVE events and rollbacks to followers via `hub`. Idempotent for a
|
|
1225
|
+
* boot-time leader; a runtime promotion (failover) reloads the outbox,
|
|
1226
|
+
* which now holds EVERY tab's rows, and restarts LIVE under this session. */
|
|
1227
|
+
promoteToLeader(hub: LeaderSyncHub): Promise<void>;
|
|
1228
|
+
/** Follower duties: no outbox drain, no LIVE. Mutations forward to the
|
|
1229
|
+
* leader; everything else (registration, per-query sync, poll) runs
|
|
1230
|
+
* against this tab's own remote session as usual. */
|
|
1231
|
+
demoteToFollower(forwarder: SyncForwarder): void;
|
|
1232
|
+
/**
|
|
1233
|
+
* A pending mutation was discarded because it can never be sent.
|
|
1234
|
+
*
|
|
1235
|
+
* This is a lost write, so it must not stay invisible. Every failure in this
|
|
1236
|
+
* chain used to be a `logger.error` an app running `logLevel: 'fatal'` never
|
|
1237
|
+
* shows, which is how an outbox could sit undrained for hours with the UI
|
|
1238
|
+
* reporting nothing. Surfaces as a rollback event (the mutation will never
|
|
1239
|
+
* apply, which is what a subscriber needs to know) and degrades sync health.
|
|
1240
|
+
*/
|
|
1241
|
+
private onMutationDropped;
|
|
1242
|
+
/** A forwarded outbox row from a follower: load + drain it. Idempotent. */
|
|
1243
|
+
enqueueForwardedMutation(mutationId: string): Promise<void>;
|
|
1244
|
+
/** A relayed `_00_list_ref` LIVE event: resolve against THIS tab's queries
|
|
1245
|
+
* and run the exact same handling the LIVE subscription would have. */
|
|
1246
|
+
private applyRelayedListRefChange;
|
|
1247
|
+
/** One immediate poll cycle (failover convergence). */
|
|
1248
|
+
forcePollRound(): Promise<void>;
|
|
1249
|
+
/**
|
|
1250
|
+
* Quiesce all sync activity ahead of a local-bucket switch. After this
|
|
1251
|
+
* resolves, nothing in the sync module writes to the local store: the poll
|
|
1252
|
+
* loop is stopped AND its in-flight tick awaited, LIVE is killed, debounce
|
|
1253
|
+
* timers are cancelled (their outbox rows are already persisted), and the
|
|
1254
|
+
* scheduler has drained its in-flight queue item — including that item's
|
|
1255
|
+
* outbox-row delete, which must land in the OLD bucket. Queued down-events
|
|
1256
|
+
* are dropped (they reference old-bucket query rows; the post-switch rebind
|
|
1257
|
+
* re-enqueues registrations). The old user's un-pushed outbox is deliberately
|
|
1258
|
+
* NOT drained: the remote session already belongs to the next user.
|
|
1259
|
+
*/
|
|
1260
|
+
prepareBucketSwitch(): Promise<void>;
|
|
1261
|
+
/**
|
|
1262
|
+
* Resume syncing against the freshly-opened bucket: reload the mutation
|
|
1263
|
+
* outbox from ITS `_00_pending_mutations` (the new user's own un-pushed
|
|
1264
|
+
* offline work) and restart the scheduler. LIVE + the list_ref poll restart
|
|
1265
|
+
* via the `setCurrentUserId` call that follows in the auth listener.
|
|
1266
|
+
*/
|
|
1267
|
+
completeBucketSwitch(): Promise<void>;
|
|
1268
|
+
/**
|
|
1269
|
+
* Push the authenticated user's record id from the parent client's
|
|
1270
|
+
* auth subscription. Tears down the existing `_00_list_ref` LIVE (if
|
|
1271
|
+
* any) and re-registers it under the new user's dedicated table so
|
|
1272
|
+
* SurrealDB binds the permission rule under the post-flip auth
|
|
1273
|
+
* context. Pass `null` on sign-out.
|
|
1274
|
+
*
|
|
1275
|
+
* The dedicated `_00_list_ref_user_<id>` table is created lazily by
|
|
1276
|
+
* the SSP when the first query registration arrives, which may be
|
|
1277
|
+
* concurrent with this call. We retry the LIVE registration with a
|
|
1278
|
+
* short backoff so a "table not found" race resolves without
|
|
1279
|
+
* surfacing as a permanent auth-loading hang.
|
|
1280
|
+
*/
|
|
1281
|
+
setCurrentUserId(userId: string | null): Promise<void>;
|
|
1282
|
+
private startListRefPoll;
|
|
1283
|
+
private stopListRefPoll;
|
|
1284
|
+
/**
|
|
1285
|
+
* One poll cycle: refetch `_00_list_ref` for every active query. Returns
|
|
1286
|
+
* whether ANY query's remoteArray actually changed — the scheduler uses this
|
|
1287
|
+
* to drive the adaptive idle backoff.
|
|
1288
|
+
*
|
|
1289
|
+
* Also the ONLY health signal that runs while the page is idle. Sync health is
|
|
1290
|
+
* otherwise activity-driven (mutations/registrations via the scheduler,
|
|
1291
|
+
* reconnect re-registration, self-heal), so on a quiet page a stale `degraded`
|
|
1292
|
+
* would linger until the next mutation and a genuine idle drop would be
|
|
1293
|
+
* invisible. We fold the cycle's aggregate reachability into `recordSyncOutcome`
|
|
1294
|
+
* so idle health self-recovers (and self-degrades) with no user action. A clean
|
|
1295
|
+
* cycle is idempotent when already healthy (`recordSyncOutcome` early-returns at
|
|
1296
|
+
* `consecutiveSyncFailures === 0`), so a healthy idle page pays nothing.
|
|
1297
|
+
*/
|
|
1298
|
+
private pollListRefForActiveQueries;
|
|
1299
|
+
/**
|
|
1300
|
+
* Pull the upstream list_ref entries for `queryHash`, diff them
|
|
1301
|
+
* against the local `remoteArray` cache, sync any added/updated rows
|
|
1302
|
+
* through the SyncEngine, then persist the new remoteArray. This is
|
|
1303
|
+
* the same shape `createRemoteQuery` does for its initial fetch and
|
|
1304
|
+
* what `handleRemoteListRefChange` does per-LIVE-event — we reuse
|
|
1305
|
+
* it on a timer as a fallback for missed LIVE notifications.
|
|
1306
|
+
*/
|
|
1307
|
+
private refetchListRefForQuery;
|
|
1308
|
+
/**
|
|
1309
|
+
* Resolve the current `_00_list_ref` table name for the active auth
|
|
1310
|
+
* context. Public so the `createRemoteQuery` initial-fetch path can
|
|
1311
|
+
* read from the right per-user table.
|
|
1312
|
+
*
|
|
1313
|
+
* Reads the user id from `DataModule` rather than the local mirror,
|
|
1314
|
+
* because `DataModule.setCurrentUserId` runs synchronously from the
|
|
1315
|
+
* auth callback (before any `await`), whereas `sync.setCurrentUserId`
|
|
1316
|
+
* is async — the userQuery's initial fetch can fire between those
|
|
1317
|
+
* two points and we need the correct table name immediately.
|
|
1318
|
+
*/
|
|
1319
|
+
listRefTable(): string;
|
|
1320
|
+
private killRefLiveQuery;
|
|
1321
|
+
private restartRefLiveQuery;
|
|
1322
|
+
/**
|
|
1323
|
+
* Drop local LIVE bookkeeping without issuing a `KILL`.
|
|
1324
|
+
*
|
|
1325
|
+
* Called when the socket dies. The server-side subscription is scoped to that
|
|
1326
|
+
* WebSocket session and died with it, so there is nothing left to kill — and
|
|
1327
|
+
* by the time the reconnect handler runs, the client reports `connected`
|
|
1328
|
+
* again, which would otherwise send a `KILL` for a stale uuid on the *new*
|
|
1329
|
+
* session and hold up the restart queued behind it.
|
|
1330
|
+
*/
|
|
1331
|
+
private invalidateRefLiveQuery;
|
|
1332
|
+
private subscribeToReconnect;
|
|
1333
|
+
private startRefLiveQueries;
|
|
1334
|
+
private handleRemoteListRefChange;
|
|
1335
|
+
/**
|
|
1336
|
+
* Handle a LIVE change to a SUBQUERY child edge (a `_00_list_ref` row with
|
|
1337
|
+
* `parent` set) for a `.related()` query. Unlike primary rows, child rows
|
|
1338
|
+
* must NOT touch the query's `localArray`/`remoteArray`/`rowCount`; we only
|
|
1339
|
+
* keep the child BODY fresh in the local cache so the in-browser SSP's
|
|
1340
|
+
* subquery-table dependency re-materializes the parent view.
|
|
1341
|
+
*
|
|
1342
|
+
* CREATE/UPDATE fetch+upsert the child body. DELETE is intentionally a
|
|
1343
|
+
* no-op: a child leaving this query's set must not delete a body another
|
|
1344
|
+
* query may still show (see `syncSubqueryChildren` deletion-safety note);
|
|
1345
|
+
* a genuine record delete propagates via the normal delete path.
|
|
1346
|
+
*/
|
|
1347
|
+
private handleRemoteSubqueryChange;
|
|
1348
|
+
/**
|
|
1349
|
+
* Enqueues a 'down' event (from remote to local) for processing.
|
|
1350
|
+
* @param event The DownEvent to enqueue.
|
|
1351
|
+
*/
|
|
1352
|
+
enqueueDownEvent(event: DownEvent): void;
|
|
1353
|
+
/**
|
|
1354
|
+
* Bound a mutation push so it always settles.
|
|
1355
|
+
*
|
|
1356
|
+
* `SyncScheduler.syncUp` early-returns while `isSyncingUp` is true, and that
|
|
1357
|
+
* flag only clears in the `finally` of the drain loop. A push whose RPC never
|
|
1358
|
+
* settles (socket dropped mid-flight, response lost) therefore wedges the
|
|
1359
|
+
* up-queue for the rest of the session: no retry, no error, no further
|
|
1360
|
+
* mutation ever sent. A timeout turns that into an ordinary network failure,
|
|
1361
|
+
* which `UpQueue.next` re-queues for the next trigger. The message deliberately
|
|
1362
|
+
* contains "timed out" so `classifySyncError` treats it as `network` and
|
|
1363
|
+
* retries rather than rolling the mutation back.
|
|
1364
|
+
*/
|
|
1365
|
+
private withPushTimeout;
|
|
1366
|
+
private processUpEvent;
|
|
1367
|
+
/**
|
|
1368
|
+
* A mutation the server accepted, reported once its outbox row is gone.
|
|
1369
|
+
*
|
|
1370
|
+
* Keeps the written row in the render set until its membership arrives.
|
|
1371
|
+
* Without this the row is briefly in neither term of
|
|
1372
|
+
* `(membership ∪ pendingWrites) − pendingDeletes` — the outbox delete is
|
|
1373
|
+
* tied to the push, while membership waits on the SSP ingesting the row,
|
|
1374
|
+
* materializing the view, writing the `_00_list_ref` edge and this client
|
|
1375
|
+
* reading it back. The writer therefore watched its own comment appear,
|
|
1376
|
+
* vanish, and return, while every other client showed it throughout.
|
|
1377
|
+
*/
|
|
1378
|
+
private handleMutationSettled;
|
|
1379
|
+
private handleRollback;
|
|
1380
|
+
private processDownEvent;
|
|
1381
|
+
/**
|
|
1382
|
+
* Synchronizes a specific query by hash.
|
|
1383
|
+
* Compares local and remote version arrays and fetches differences.
|
|
1384
|
+
* @param hash The hash of the query to sync.
|
|
1385
|
+
*/
|
|
1386
|
+
syncQuery(hash: string): Promise<void>;
|
|
1387
|
+
/**
|
|
1388
|
+
* Run a sync for a single query while reflecting its fetch status. Marks the
|
|
1389
|
+
* query `fetching` for the duration when the diff actually pulls records
|
|
1390
|
+
* (added/updated), then resets to `idle` in a `finally` so a failed sync
|
|
1391
|
+
* never leaves a query stuck `fetching`. Part A's notification coalescing
|
|
1392
|
+
* means the single resulting UI update lands after this completes.
|
|
1393
|
+
*/
|
|
1394
|
+
private runSyncForQuery;
|
|
1395
|
+
/**
|
|
1396
|
+
* Record ids with a pending local DELETE in the outbox (`_00_pending_mutations`).
|
|
1397
|
+
* Sync must not re-fetch/re-insert these — the remote delete is async, so the
|
|
1398
|
+
* server's `_00_list_ref` still lists them until it's processed, and the diff
|
|
1399
|
+
* would otherwise resurrect a just-deleted record.
|
|
1400
|
+
*/
|
|
1401
|
+
private getPendingDeleteIds;
|
|
1402
|
+
/**
|
|
1403
|
+
* Enqueues a list of mutations (up events) to be sent to the remote.
|
|
1404
|
+
* @param mutations Array of UpEvents (create/update/delete) to enqueue.
|
|
1405
|
+
*/
|
|
1406
|
+
enqueueMutation(mutations: UpEvent[]): Promise<void>;
|
|
1407
|
+
private registerQuery;
|
|
1408
|
+
private createRemoteQuery;
|
|
1409
|
+
/**
|
|
1410
|
+
* Sync the BODIES of a `.related()` query's subquery child rows into the
|
|
1411
|
+
* local cache, separately from the primary window array. The SSP writes
|
|
1412
|
+
* each matched child as a `_00_list_ref` edge tagged `parent`/`parent_rel`;
|
|
1413
|
+
* `buildSubqueryListRefSelect` pulls those `out`+`version` pairs (any
|
|
1414
|
+
* nesting depth). We diff against the in-memory `subqueryRemoteArray` and
|
|
1415
|
+
* fetch added/updated bodies through the SyncEngine — which `saveBatch`s
|
|
1416
|
+
* them into the local DB AND the in-browser SSP, whose subquery-table
|
|
1417
|
+
* dependency then re-materializes the parent view (no explicit notify).
|
|
1418
|
+
*
|
|
1419
|
+
* Deletion safety: we pass `removed: []` deliberately. A child body can be
|
|
1420
|
+
* shared by other queries; letting `handleRemovedRecords` delete one that
|
|
1421
|
+
* merely left THIS query's child set would clobber data another query still
|
|
1422
|
+
* shows. Genuine record deletes flow through the normal delete path; a
|
|
1423
|
+
* lingering orphan body is invisible (the correlated WHERE stops matching).
|
|
1424
|
+
*
|
|
1425
|
+
* Kept off `runSyncForQuery` on purpose so child fetches never flip the
|
|
1426
|
+
* query to `fetching` or skew its DevTools timings.
|
|
1427
|
+
*/
|
|
1428
|
+
private syncSubqueryChildren;
|
|
1429
|
+
heartbeatQuery(queryHash: string): Promise<void>;
|
|
1430
|
+
private cleanupQuery;
|
|
1431
|
+
}
|
|
1432
|
+
//#endregion
|
|
150
1433
|
//#region src/modules/auth/events/index.d.ts
|
|
151
1434
|
declare const AuthEventTypes: {
|
|
152
1435
|
readonly AuthStateChanged: "AUTH_STATE_CHANGED";
|
|
@@ -169,6 +1452,13 @@ declare class AuthService<S extends SchemaStructure> {
|
|
|
169
1452
|
token: string | null;
|
|
170
1453
|
currentUser: any | null;
|
|
171
1454
|
isAuthenticated: boolean;
|
|
1455
|
+
/**
|
|
1456
|
+
* The record-access method name for the current session (e.g. `"account"`),
|
|
1457
|
+
* derived from the token's `AC` claim. Consumed by the in-browser SSP's
|
|
1458
|
+
* permission injection so `$access`-gated table predicates resolve locally,
|
|
1459
|
+
* mirroring the server's `$access`. Null when logged out.
|
|
1460
|
+
*/
|
|
1461
|
+
access: string | null;
|
|
172
1462
|
isLoading: boolean;
|
|
173
1463
|
private events;
|
|
174
1464
|
get eventSystem(): AuthEventSystem;
|
|
@@ -190,17 +1480,672 @@ declare class AuthService<S extends SchemaStructure> {
|
|
|
190
1480
|
*/
|
|
191
1481
|
signOut(): Promise<void>;
|
|
192
1482
|
private setSession;
|
|
1483
|
+
/** Fallback when the token carries no `AC` claim: if the schema defines
|
|
1484
|
+
* exactly one record-access method, assume the session used it. */
|
|
1485
|
+
private defaultAccessName;
|
|
193
1486
|
signUp<Name extends keyof S['access'] & string>(accessName: Name, params: ExtractAccessParams<S, Name, 'signup'>): Promise<void>;
|
|
194
1487
|
signIn<Name extends keyof S['access'] & string>(accessName: Name, params: ExtractAccessParams<S, Name, 'signIn'>): Promise<void>;
|
|
195
1488
|
}
|
|
196
1489
|
//#endregion
|
|
197
|
-
//#region src/
|
|
1490
|
+
//#region src/modules/crdt/crdt-field.d.ts
|
|
1491
|
+
declare const CURSOR_COLORS: string[];
|
|
1492
|
+
declare function cursorColorFromName(name: string): string;
|
|
1493
|
+
declare class CrdtField {
|
|
1494
|
+
private fieldName;
|
|
1495
|
+
private doc;
|
|
1496
|
+
private pushTimer;
|
|
1497
|
+
private local;
|
|
1498
|
+
private remote;
|
|
1499
|
+
private recordId;
|
|
1500
|
+
private sessionId;
|
|
1501
|
+
private unsubscribe;
|
|
1502
|
+
private lastPushTime;
|
|
1503
|
+
private lastCursorPushTime;
|
|
1504
|
+
private loadedFromCrdt;
|
|
1505
|
+
private pushRetryCount;
|
|
1506
|
+
private logger;
|
|
1507
|
+
private cursorsEnabled;
|
|
1508
|
+
/** Remote-push debounce. Local writes happen immediately on every Loro
|
|
1509
|
+
* update; the remote UPSERT is coalesced over this window. Configured
|
|
1510
|
+
* via `Sp00kyConfig.crdtDebounceMs`, default 500. */
|
|
1511
|
+
private remoteDebounceMs;
|
|
1512
|
+
private _onCursorUpdate;
|
|
1513
|
+
private pendingCursorUpdate;
|
|
1514
|
+
/** Callback set by the editor to receive remote cursor updates.
|
|
1515
|
+
* Any cursor data that arrived before this callback was set will be replayed. */
|
|
1516
|
+
set onCursorUpdate(cb: ((data: Uint8Array) => void) | null);
|
|
1517
|
+
get onCursorUpdate(): ((data: Uint8Array) => void) | null;
|
|
1518
|
+
/**
|
|
1519
|
+
* @param LoroDocClass the `LoroDoc` constructor, injected by the caller after
|
|
1520
|
+
* awaiting {@link loadLoro} — keeps `loro-crdt` out of this module's static
|
|
1521
|
+
* import graph so it only ships to apps that use CRDT fields.
|
|
1522
|
+
*/
|
|
1523
|
+
constructor(fieldName: string, cursorsEnabled: boolean, LoroDocClass: typeof LoroDoc, initialState?: Uint8Array, logger?: Logger$1 | null);
|
|
1524
|
+
getDoc(): LoroDoc;
|
|
1525
|
+
/** Whether the LoroDoc was loaded from saved CRDT state */
|
|
1526
|
+
hasContent(): boolean;
|
|
1527
|
+
startSync(local: LocalStore, remote: RemoteDatabaseService, recordId: string, sessionId: string, debounceMs: number): void;
|
|
1528
|
+
/**
|
|
1529
|
+
* Stop syncing this field. Flushes one final remote push by default so the
|
|
1530
|
+
* last keystrokes aren't lost. Pass `{ flush: false }` on a bucket switch —
|
|
1531
|
+
* the remote session already belongs to the NEXT user, and pushing this
|
|
1532
|
+
* (previous user's) snapshot under it would clobber the record remotely.
|
|
1533
|
+
*/
|
|
1534
|
+
stopSync(options?: {
|
|
1535
|
+
flush?: boolean;
|
|
1536
|
+
}): void;
|
|
1537
|
+
importRemote(state: Uint8Array): void;
|
|
1538
|
+
exportSnapshot(): Uint8Array;
|
|
1539
|
+
/** Push this session's cursor blob into the parent row at
|
|
1540
|
+
* `<field>.cursors[$sid]`. No-op when cursors aren't enabled on this
|
|
1541
|
+
* field — the editor still calls this method optimistically, but
|
|
1542
|
+
* without `@cursor` on the schema there's nowhere to store the blob.
|
|
1543
|
+
* The UPDATE itself fires the parent table's LIVE feed, so other
|
|
1544
|
+
* browsers receive the cursor change without a separate `_00_rv` bump. */
|
|
1545
|
+
pushCursorState(encoded: Uint8Array): Promise<void>;
|
|
1546
|
+
/** Import remote cursor state (called by CrdtManager from LIVE SELECT) */
|
|
1547
|
+
importRemoteCursor(base64State: string): void;
|
|
1548
|
+
private scheduleRemotePush;
|
|
1549
|
+
/** SET path inside a parent row for the current snapshot. `@crdt`-only
|
|
1550
|
+
* fields hold the snapshot directly (`<field>`); `@crdt @cursor`
|
|
1551
|
+
* fields hold a `{ state, cursors }` object so the snapshot lives at
|
|
1552
|
+
* `<field>.state` next to per-session cursor blobs. */
|
|
1553
|
+
private statePath;
|
|
1554
|
+
/** Mirror the LoroDoc snapshot into the parent row locally. Runs on
|
|
1555
|
+
* every local update and every remote import so reloads (online or
|
|
1556
|
+
* offline) see the freshest content immediately. Failures are
|
|
1557
|
+
* swallowed — a stale local write must never block user input. */
|
|
1558
|
+
private persistLocal;
|
|
1559
|
+
private pushToRemote;
|
|
1560
|
+
}
|
|
1561
|
+
//#endregion
|
|
1562
|
+
//#region src/modules/crdt/index.d.ts
|
|
1563
|
+
/**
|
|
1564
|
+
* CrdtManager manages active CrdtField instances and their sync channels.
|
|
1565
|
+
*
|
|
1566
|
+
* Collaborative state lives in two dedicated tables (defined in
|
|
1567
|
+
* `apps/cli/src/meta_tables_remote.surql`):
|
|
1568
|
+
* - `_00_crdt` { record_id, field, state } — one row per (record, field)
|
|
1569
|
+
* - `_00_cursor` { record_id, session_id, field, state } — one row per
|
|
1570
|
+
* (record, session, field)
|
|
1571
|
+
*
|
|
1572
|
+
* Splitting them off the parent row is what makes offline edits mergeable:
|
|
1573
|
+
* each (record, field) gets its own row, so concurrent offline writes don't
|
|
1574
|
+
* collide on the parent's last-write-wins semantics.
|
|
1575
|
+
*
|
|
1576
|
+
* Cross-browser delivery still rides the parent table's existing LIVE feed
|
|
1577
|
+
* to avoid SurrealDB v3 LIVE bugs around dereference-based permission rules
|
|
1578
|
+
* (issues 3602, 4026). On every meta UPSERT the writer also bumps the
|
|
1579
|
+
* parent's `_00_rv` (a no-op assignment); that fires the parent's LIVE
|
|
1580
|
+
* feed, and the receiver pulls the matching `_00_crdt` / `_00_cursor` rows
|
|
1581
|
+
* via subquery. Permission inheritance happens server-side via
|
|
1582
|
+
* `record_id.id != NONE` (SELECT) and `fn::can_update_record` (UPDATE).
|
|
1583
|
+
*/
|
|
1584
|
+
declare class CrdtManager {
|
|
1585
|
+
private schema;
|
|
1586
|
+
private local;
|
|
1587
|
+
private remote;
|
|
1588
|
+
private debounceMs;
|
|
1589
|
+
private fields;
|
|
1590
|
+
private liveByTable;
|
|
1591
|
+
private pendingLive;
|
|
1592
|
+
private staleTables;
|
|
1593
|
+
private connectionGeneration;
|
|
1594
|
+
private connectionUnsubscribes;
|
|
1595
|
+
private logger;
|
|
1596
|
+
private sessionId;
|
|
1597
|
+
constructor(schema: SchemaStructure, local: LocalStore, remote: RemoteDatabaseService, logger: Logger$1, debounceMs?: number);
|
|
1598
|
+
/**
|
|
1599
|
+
* Re-establish table LIVEs after a socket drop.
|
|
1600
|
+
*
|
|
1601
|
+
* A LIVE subscription lives and dies with its WebSocket session, and
|
|
1602
|
+
* `ensureTableSubscription` is memoized on `liveByTable` — so without this,
|
|
1603
|
+
* the first reconnect leaves CRDT realtime permanently dead: the map still
|
|
1604
|
+
* holds a uuid for a subscription the server has forgotten, so every later
|
|
1605
|
+
* `open()` short-circuits and no LIVE is ever re-issued.
|
|
1606
|
+
*
|
|
1607
|
+
* Both drop events matter: the SDK publishes `reconnecting` (not
|
|
1608
|
+
* `disconnected`) when it intends to recover on its own, and `disconnected`
|
|
1609
|
+
* only once it has given up.
|
|
1610
|
+
*/
|
|
1611
|
+
private subscribeToReconnect;
|
|
1612
|
+
/** Stop observing transport events. Separate from {@link closeAll}, which also
|
|
1613
|
+
* runs on a bucket switch where the manager keeps being used. */
|
|
1614
|
+
dispose(): void;
|
|
1615
|
+
private hasOpenFieldFor;
|
|
1616
|
+
/** Set the session id that scopes this client's cursor entries. Must be
|
|
1617
|
+
* called before `open()` for cursors to be pushed under a stable key.
|
|
1618
|
+
* Passed in from `sp00ky.ts` at boot (it already fetches `session::id()`
|
|
1619
|
+
* for the data-module salt). */
|
|
1620
|
+
setSessionId(sessionId: string): void;
|
|
1621
|
+
/**
|
|
1622
|
+
* Open a CRDT field for collaborative editing.
|
|
1623
|
+
*
|
|
1624
|
+
* @param table - Table name
|
|
1625
|
+
* @param recordId - Full record ID (e.g., "thread:abc")
|
|
1626
|
+
* @param field - Field name (e.g., "title", "content")
|
|
1627
|
+
* @param fallbackText - Current plain text from the record, used to seed the
|
|
1628
|
+
* LoroDoc if no CRDT state exists yet (migration path)
|
|
1629
|
+
*/
|
|
1630
|
+
open(table: string, recordId: string, field: string, fallbackText?: string): Promise<CrdtField>;
|
|
1631
|
+
close(table: string, recordId: string, field: string): void;
|
|
1632
|
+
/**
|
|
1633
|
+
* Close every open field + table LIVE. Fields flush a final remote push by
|
|
1634
|
+
* default; pass `{ flush: false }` on a bucket switch, where that flush
|
|
1635
|
+
* would push the previous user's snapshot under the next user's session.
|
|
1636
|
+
*/
|
|
1637
|
+
closeAll(options?: {
|
|
1638
|
+
flush?: boolean;
|
|
1639
|
+
}): void;
|
|
1640
|
+
/** Ensure a single `LIVE SELECT * FROM <table>` is running, shared across
|
|
1641
|
+
* every open CrdtField on `table`. */
|
|
1642
|
+
private ensureTableSubscription;
|
|
1643
|
+
/** Apply a parent-row payload from a non-LIVE source (e.g. the
|
|
1644
|
+
* list_ref-driven sync engine, when the cross-user LIVE on the
|
|
1645
|
+
* parent table is filtered out by the SurrealDB cross-session
|
|
1646
|
+
* permission gap). Same semantics as the internal `dispatchRow`. */
|
|
1647
|
+
applyRow(table: string, row: Record<string, unknown>): void;
|
|
1648
|
+
/** Dispatch a parent-row LIVE event to every open CrdtField on that
|
|
1649
|
+
* record. Each open field reads its slice of the row directly — the
|
|
1650
|
+
* CRDT snapshot is a column on the parent now, so there is no
|
|
1651
|
+
* follow-up subquery. */
|
|
1652
|
+
private dispatchRow;
|
|
1653
|
+
/** One-shot remote fetch for a row whose CRDT field hasn't synced
|
|
1654
|
+
* locally yet (fresh device, memory-backed local DB after reload, …).
|
|
1655
|
+
* Used by `open()` when the local read came up empty. Subsequent
|
|
1656
|
+
* cross-browser updates ride `dispatchRow` via the parent LIVE feed. */
|
|
1657
|
+
private fetchAndDispatchRow;
|
|
1658
|
+
/** Schema lookup: does `<table>.<field>` carry a `@cursor` annotation?
|
|
1659
|
+
* Determines the on-disk shape (plain snapshot vs. `{ state, cursors }`). */
|
|
1660
|
+
private fieldHasCursor;
|
|
1661
|
+
/** Pull the LoroDoc snapshot bytes out of a row slice. For `@crdt`-only
|
|
1662
|
+
* the slice IS the snapshot (Uint8Array); for `@crdt @cursor` it's
|
|
1663
|
+
* `{ state, cursors }` where `state` carries the snapshot bytes. */
|
|
1664
|
+
private extractSnapshot;
|
|
1665
|
+
private killTableSubscription;
|
|
1666
|
+
private makeKey;
|
|
1667
|
+
/**
|
|
1668
|
+
* Throws if `<table>.<field>` is not annotated `@crdt` in the schema. Catches
|
|
1669
|
+
* typos, removed annotations, and stale schema codegen at the call site instead
|
|
1670
|
+
* of silently producing a non-CRDT writer.
|
|
1671
|
+
*/
|
|
1672
|
+
private assertCrdtField;
|
|
1673
|
+
}
|
|
1674
|
+
//#endregion
|
|
1675
|
+
//#region src/modules/feature-flag/index.d.ts
|
|
1676
|
+
interface FeatureFlagSnapshot {
|
|
1677
|
+
variant: string | undefined;
|
|
1678
|
+
payload: unknown | undefined;
|
|
1679
|
+
}
|
|
1680
|
+
interface FeatureFlagOptions {
|
|
1681
|
+
fallback?: string;
|
|
1682
|
+
ttl?: QueryTimeToLive;
|
|
1683
|
+
}
|
|
1684
|
+
/**
|
|
1685
|
+
* A locally forced variant. Applies to THIS browser only and is never sent to
|
|
1686
|
+
* the server — the assignment in `_00_user_feature` is untouched, so clearing
|
|
1687
|
+
* the override restores whatever the server says.
|
|
1688
|
+
*/
|
|
1689
|
+
interface FeatureFlagOverride {
|
|
1690
|
+
variant: string;
|
|
1691
|
+
payload?: unknown;
|
|
1692
|
+
}
|
|
1693
|
+
declare class FeatureFlagHandle {
|
|
1694
|
+
readonly key: string;
|
|
1695
|
+
readonly fallback: string | undefined;
|
|
1696
|
+
private latest;
|
|
1697
|
+
private listeners;
|
|
1698
|
+
private unsubscribeFn;
|
|
1699
|
+
private onCloseFn;
|
|
1700
|
+
private closed;
|
|
1701
|
+
constructor(key: string, fallback: string | undefined);
|
|
1702
|
+
attach(unsubscribe: () => void): void;
|
|
1703
|
+
detach(): void;
|
|
1704
|
+
set(snapshot: FeatureFlagSnapshot): void;
|
|
1705
|
+
variant(): string | undefined;
|
|
1706
|
+
payload<T = unknown>(): T | undefined;
|
|
1707
|
+
enabled(): boolean;
|
|
1708
|
+
subscribe(cb: (s: FeatureFlagSnapshot) => void): () => void;
|
|
1709
|
+
onClose(cb: () => void): void;
|
|
1710
|
+
close(): void;
|
|
1711
|
+
}
|
|
1712
|
+
interface FeatureFlagModuleDeps<S extends SchemaStructure> {
|
|
1713
|
+
dataModule: DataModule<S>;
|
|
1714
|
+
sync: Sp00kySync<S>;
|
|
1715
|
+
auth: AuthService<S>;
|
|
1716
|
+
logger: Logger$1;
|
|
1717
|
+
}
|
|
1718
|
+
declare class FeatureFlagModule<S extends SchemaStructure> {
|
|
1719
|
+
private deps;
|
|
1720
|
+
private logger;
|
|
1721
|
+
private handles;
|
|
1722
|
+
private authUnsubscribe;
|
|
1723
|
+
private lastUserId;
|
|
1724
|
+
private querySubscription;
|
|
1725
|
+
private starting;
|
|
1726
|
+
private ttl;
|
|
1727
|
+
private snapshots;
|
|
1728
|
+
private loaded;
|
|
1729
|
+
private overrides;
|
|
1730
|
+
constructor(deps: FeatureFlagModuleDeps<S>);
|
|
1731
|
+
init(): void;
|
|
1732
|
+
feature(key: string, options?: FeatureFlagOptions): FeatureFlagHandle;
|
|
1733
|
+
closeAll(): Promise<void>;
|
|
1734
|
+
/** Auth changed: drop the old user's query/snapshots and re-observe. */
|
|
1735
|
+
private refresh;
|
|
1736
|
+
private teardownQuery;
|
|
1737
|
+
/** Start the single shared live query (idempotent; no-op with no handles). */
|
|
1738
|
+
private ensureStarted;
|
|
1739
|
+
/** Live query result → per-key snapshots → push to every active handle. */
|
|
1740
|
+
private applyRecords;
|
|
1741
|
+
/**
|
|
1742
|
+
* Force `key` to `variant` in THIS browser. Pass `null` to clear.
|
|
1743
|
+
*
|
|
1744
|
+
* Nothing is written to the server: the `_00_user_feature` assignment is
|
|
1745
|
+
* untouched, so clearing restores whatever the server says. Persisted to
|
|
1746
|
+
* localStorage on the page origin, so it survives a reload.
|
|
1747
|
+
*/
|
|
1748
|
+
setLocalOverride(key: string, variant: string | null, payload?: unknown): void;
|
|
1749
|
+
clearLocalOverrides(): void;
|
|
1750
|
+
getLocalOverrides(): Record<string, FeatureFlagOverride>;
|
|
1751
|
+
/** The assignment for `key`, with any local override taking precedence. */
|
|
1752
|
+
private resolve;
|
|
1753
|
+
private pushAll;
|
|
1754
|
+
private loadOverrides;
|
|
1755
|
+
private persistOverrides;
|
|
1756
|
+
}
|
|
1757
|
+
//#endregion
|
|
1758
|
+
//#region src/modules/app-release/index.d.ts
|
|
1759
|
+
interface AppReleaseSnapshot {
|
|
1760
|
+
/** Latest announced version for the app, or undefined when no row exists. */
|
|
1761
|
+
version: string | undefined;
|
|
1762
|
+
/** Clients should clear SW/caches when reloading onto this version. */
|
|
1763
|
+
cacheBust: boolean;
|
|
1764
|
+
/** Clients should reload/update immediately instead of asking. */
|
|
1765
|
+
mandatory: boolean;
|
|
1766
|
+
releasedAt: string | undefined;
|
|
1767
|
+
}
|
|
1768
|
+
interface AppReleaseOptions {
|
|
1769
|
+
ttl?: QueryTimeToLive;
|
|
1770
|
+
}
|
|
1771
|
+
declare class AppReleaseHandle {
|
|
1772
|
+
readonly app: string;
|
|
1773
|
+
private latest;
|
|
1774
|
+
private listeners;
|
|
1775
|
+
private onCloseFn;
|
|
1776
|
+
private closed;
|
|
1777
|
+
constructor(app: string);
|
|
1778
|
+
set(snapshot: AppReleaseSnapshot): void;
|
|
1779
|
+
snapshot(): AppReleaseSnapshot;
|
|
1780
|
+
version(): string | undefined;
|
|
1781
|
+
/** True when the announced version is semver-newer than `currentVersion`. */
|
|
1782
|
+
updateAvailable(currentVersion: string): boolean;
|
|
1783
|
+
subscribe(cb: (s: AppReleaseSnapshot) => void): () => void;
|
|
1784
|
+
onClose(cb: () => void): void;
|
|
1785
|
+
close(): void;
|
|
1786
|
+
}
|
|
1787
|
+
interface AppReleaseModuleDeps<S extends SchemaStructure> {
|
|
1788
|
+
dataModule: DataModule<S>;
|
|
1789
|
+
sync: Sp00kySync<S>;
|
|
1790
|
+
auth: AuthService<S>;
|
|
1791
|
+
logger: Logger$1;
|
|
1792
|
+
}
|
|
1793
|
+
declare class AppReleaseModule<S extends SchemaStructure> {
|
|
1794
|
+
private deps;
|
|
1795
|
+
private logger;
|
|
1796
|
+
private handles;
|
|
1797
|
+
private authUnsubscribe;
|
|
1798
|
+
private lastUserId;
|
|
1799
|
+
private querySubscription;
|
|
1800
|
+
private starting;
|
|
1801
|
+
private ttl;
|
|
1802
|
+
private snapshots;
|
|
1803
|
+
private loaded;
|
|
1804
|
+
constructor(deps: AppReleaseModuleDeps<S>);
|
|
1805
|
+
init(): void;
|
|
1806
|
+
release(app: string, options?: AppReleaseOptions): AppReleaseHandle;
|
|
1807
|
+
closeAll(): Promise<void>;
|
|
1808
|
+
private refresh;
|
|
1809
|
+
private teardownQuery;
|
|
1810
|
+
private ensureStarted;
|
|
1811
|
+
private applyRecords;
|
|
1812
|
+
}
|
|
1813
|
+
//#endregion
|
|
1814
|
+
//#region src/services/blobs/blob-store.d.ts
|
|
1815
|
+
/**
|
|
1816
|
+
* Byte storage for cached bucket files.
|
|
1817
|
+
*
|
|
1818
|
+
* The default implementation is OPFS. Bucket files never arrive over HTTP in
|
|
1819
|
+
* this client — `BucketHandle.get()` is a SurrealQL RPC on the sync socket — so
|
|
1820
|
+
* neither the browser's HTTP cache nor the Cache API can hold them. We persist
|
|
1821
|
+
* the bytes ourselves, and OPFS is the cheapest place to put them: a read is
|
|
1822
|
+
* `getFile()` → a disk-backed lazy `File` that `URL.createObjectURL` can serve
|
|
1823
|
+
* without ever moving the bytes through the JS heap.
|
|
1824
|
+
*
|
|
1825
|
+
* Layout is real nested directories rather than one hashed filename:
|
|
1826
|
+
*
|
|
1827
|
+
* sp00ky-blobs/<namespace>/<bucket>/<...path segments>
|
|
1828
|
+
*
|
|
1829
|
+
* That costs a `getDirectoryHandle` per segment on write, and buys the property
|
|
1830
|
+
* the whole orphan story rests on: the full `(bucket, path)` key is recoverable
|
|
1831
|
+
* from a directory walk alone. The `_00_blob` manifest can therefore be wiped
|
|
1832
|
+
* (memory fallback, SQLite pool wipe, IndexedDB corruption recovery) and be
|
|
1833
|
+
* rebuilt from disk instead of taking the cached bytes down with it.
|
|
1834
|
+
*/
|
|
1835
|
+
/** Identifies one cached file: the bucket it lives in and its path within. */
|
|
1836
|
+
interface BlobKey {
|
|
1837
|
+
bucket: string;
|
|
1838
|
+
path: string;
|
|
1839
|
+
}
|
|
1840
|
+
/** What a directory walk can tell us about a stored file, with no manifest. */
|
|
1841
|
+
interface BlobStat {
|
|
1842
|
+
key: BlobKey;
|
|
1843
|
+
size: number;
|
|
1844
|
+
/** File mtime. Seeds `lastAccess` when a manifest row has to be rebuilt. */
|
|
1845
|
+
mtime: number;
|
|
1846
|
+
}
|
|
1847
|
+
interface BlobStore {
|
|
1848
|
+
/** False for {@link MemoryBlobStore} and for OPFS-less environments: the
|
|
1849
|
+
* cache still dedupes and serves within a tab, but nothing survives reload. */
|
|
1850
|
+
readonly persistent: boolean;
|
|
1851
|
+
/** Namespace (the local bucketId) all keys are resolved under. */
|
|
1852
|
+
readonly namespace: string;
|
|
1853
|
+
read(key: BlobKey): Promise<Blob | null>;
|
|
1854
|
+
/** Returns the number of bytes written. Throws on quota exhaustion. */
|
|
1855
|
+
write(key: BlobKey, bytes: Blob): Promise<number>;
|
|
1856
|
+
remove(key: BlobKey): Promise<void>;
|
|
1857
|
+
/** Every committed file under the current namespace. Sweeps torn writes. */
|
|
1858
|
+
list(): Promise<BlobStat[]>;
|
|
1859
|
+
/** Drop the whole namespace (sign-out with `clearOnSignOut`, or a reset). */
|
|
1860
|
+
clear(): Promise<void>;
|
|
1861
|
+
/** Point at another namespace. Does not touch the bytes of the old one. */
|
|
1862
|
+
setNamespace(namespace: string): void;
|
|
1863
|
+
}
|
|
1864
|
+
//#endregion
|
|
1865
|
+
//#region src/services/blobs/blob-manifest.d.ts
|
|
1866
|
+
interface BlobEntry {
|
|
1867
|
+
/** `${bucket}/${path}` — also the `_00_blob` row id. */
|
|
1868
|
+
id: string;
|
|
1869
|
+
bucket: string;
|
|
1870
|
+
path: string;
|
|
1871
|
+
size: number;
|
|
1872
|
+
contentType: string;
|
|
1873
|
+
createdAt: number;
|
|
1874
|
+
lastAccess: number;
|
|
1875
|
+
hits: number;
|
|
1876
|
+
/** Exempt from pressure eviction. Never expires on its own. */
|
|
1877
|
+
pinned: boolean;
|
|
1878
|
+
}
|
|
1879
|
+
declare class BlobManifest {
|
|
1880
|
+
private local;
|
|
1881
|
+
private entries;
|
|
1882
|
+
/** Ids whose in-memory state has not been written back yet. */
|
|
1883
|
+
private dirty;
|
|
1884
|
+
private removed;
|
|
1885
|
+
private flushing;
|
|
1886
|
+
constructor(local: LocalStore);
|
|
1887
|
+
/**
|
|
1888
|
+
* Hydrate from the rows matching `keys`. Ids come from the OPFS listing, so
|
|
1889
|
+
* this never needs a full-table scan (and therefore never needs a QueryPlan).
|
|
1890
|
+
* Any read failure yields an empty manifest: reconcile then rebuilds every
|
|
1891
|
+
* row from disk, which is exactly the desired degradation.
|
|
1892
|
+
*/
|
|
1893
|
+
load(ids: string[]): Promise<void>;
|
|
1894
|
+
get(key: BlobKey): BlobEntry | undefined;
|
|
1895
|
+
getById(id: string): BlobEntry | undefined;
|
|
1896
|
+
all(): BlobEntry[];
|
|
1897
|
+
totalBytes(): number;
|
|
1898
|
+
pinnedBytes(): number;
|
|
1899
|
+
put(entry: BlobEntry): void;
|
|
1900
|
+
touch(id: string, now: number): void;
|
|
1901
|
+
setPinned(id: string, pinned: boolean): boolean;
|
|
1902
|
+
remove(id: string): void;
|
|
1903
|
+
/** Forget everything without scheduling deletes — for a bucket switch, where
|
|
1904
|
+
* the rows belong to the store we are leaving and must stay put. */
|
|
1905
|
+
reset(): void;
|
|
1906
|
+
hasPendingWrites(): boolean;
|
|
1907
|
+
/**
|
|
1908
|
+
* Write back pending changes. Serialized: a second concurrent flush awaits
|
|
1909
|
+
* the first rather than racing it into the same rows. Failures are swallowed
|
|
1910
|
+
* on purpose — a lost metadata write costs an LRU timestamp, and the entry is
|
|
1911
|
+
* rebuilt from disk on the next reconcile.
|
|
1912
|
+
*/
|
|
1913
|
+
flush(): Promise<void>;
|
|
1914
|
+
private doFlush;
|
|
1915
|
+
}
|
|
1916
|
+
//#endregion
|
|
1917
|
+
//#region src/services/blobs/blob-cache.d.ts
|
|
1918
|
+
interface BlobUrlLease {
|
|
1919
|
+
url: string;
|
|
1920
|
+
release(): void;
|
|
1921
|
+
}
|
|
1922
|
+
interface BlobReadOptions {
|
|
1923
|
+
/** Write through to L1 on a miss. Default true. */
|
|
1924
|
+
persist?: boolean;
|
|
1925
|
+
/** Mark the entry exempt from pressure eviction. */
|
|
1926
|
+
pin?: boolean;
|
|
1927
|
+
/**
|
|
1928
|
+
* Default `'never'`: a bucket path is treated as immutable, which is how the
|
|
1929
|
+
* client writes them (`crypto.randomUUID() + ext`). `'head'` spends a remote
|
|
1930
|
+
* `head()` to compare sizes before trusting L1.
|
|
1931
|
+
*/
|
|
1932
|
+
revalidate?: 'never' | 'head';
|
|
1933
|
+
/** Skip L0/L1 entirely and refill from remote. Backs `refetch()`. */
|
|
1934
|
+
reload?: boolean;
|
|
1935
|
+
}
|
|
1936
|
+
interface BlobCacheStats {
|
|
1937
|
+
entries: number;
|
|
1938
|
+
totalBytes: number;
|
|
1939
|
+
budgetBytes: number;
|
|
1940
|
+
pinnedBytes: number;
|
|
1941
|
+
evictedEntries: number;
|
|
1942
|
+
evictedBytes: number;
|
|
1943
|
+
reconciledEntries: number;
|
|
1944
|
+
hits: number;
|
|
1945
|
+
misses: number;
|
|
1946
|
+
persistent: boolean;
|
|
1947
|
+
/** True when pinned bytes alone exceed the budget: new entries stop being
|
|
1948
|
+
* written rather than pinned ones being thrown away. */
|
|
1949
|
+
persistPaused: boolean;
|
|
1950
|
+
}
|
|
1951
|
+
interface BlobCacheOptions {
|
|
1952
|
+
store: BlobStore;
|
|
1953
|
+
manifest: BlobManifest;
|
|
1954
|
+
/** L2 read. Resolves to null when the file does not exist remotely. */
|
|
1955
|
+
fetchRemote(key: BlobKey): Promise<Blob | null>;
|
|
1956
|
+
/** L2 metadata, for `revalidate: 'head'`. */
|
|
1957
|
+
headRemote?(key: BlobKey): Promise<Record<string, unknown> | null>;
|
|
1958
|
+
logger: Logger$1;
|
|
1959
|
+
maxBytes: number;
|
|
1960
|
+
now?: () => number;
|
|
1961
|
+
/** Injected so the URL layer is exercisable off a DOM (node tests). */
|
|
1962
|
+
urls?: {
|
|
1963
|
+
create(blob: Blob): string;
|
|
1964
|
+
revoke(url: string): void;
|
|
1965
|
+
};
|
|
1966
|
+
}
|
|
1967
|
+
declare class BlobCache {
|
|
1968
|
+
private readonly store;
|
|
1969
|
+
private readonly manifest;
|
|
1970
|
+
private readonly fetchRemote;
|
|
1971
|
+
private readonly headRemote?;
|
|
1972
|
+
private readonly logger;
|
|
1973
|
+
private readonly now;
|
|
1974
|
+
private readonly urlFactory;
|
|
1975
|
+
private maxBytes;
|
|
1976
|
+
private persistPaused;
|
|
1977
|
+
/** Set after a quota failure survives one forced eviction. */
|
|
1978
|
+
private persistDisabled;
|
|
1979
|
+
private readonly urls;
|
|
1980
|
+
/** Ids at zero references, oldest first — the hot-URL window. */
|
|
1981
|
+
private idleUrls;
|
|
1982
|
+
private readonly inflight;
|
|
1983
|
+
private flushTimer;
|
|
1984
|
+
private readonly onPageHide;
|
|
1985
|
+
/**
|
|
1986
|
+
* Resolves once the manifest has been reconciled against disk. Reads await
|
|
1987
|
+
* it, so `start()` does NOT have to be awaited on the boot path — blocking
|
|
1988
|
+
* boot on an OPFS directory walk delayed the WebSocket connect (and with it
|
|
1989
|
+
* the connection supervisor) for no benefit.
|
|
1990
|
+
*/
|
|
1991
|
+
private ready;
|
|
1992
|
+
private hits;
|
|
1993
|
+
private misses;
|
|
1994
|
+
private evictedEntries;
|
|
1995
|
+
private evictedBytes;
|
|
1996
|
+
private reconciledEntries;
|
|
1997
|
+
constructor(opts: BlobCacheOptions);
|
|
1998
|
+
/** Coalesce manifest write-back. Metadata only, so losing the tail costs an
|
|
1999
|
+
* LRU timestamp that reconcile reseeds from the file mtime. */
|
|
2000
|
+
private scheduleFlush;
|
|
2001
|
+
/**
|
|
2002
|
+
* Resolve the bytes for `key`, filling L1 on the way when `persist` is on.
|
|
2003
|
+
* Returns null when the file does not exist remotely and is not cached.
|
|
2004
|
+
*/
|
|
2005
|
+
read(key: BlobKey, options?: BlobReadOptions): Promise<Blob | null>;
|
|
2006
|
+
/**
|
|
2007
|
+
* An object URL for `key`, refcounted. Callers MUST `release()`; the URL is
|
|
2008
|
+
* revoked once the last holder lets go and it falls out of the hot window.
|
|
2009
|
+
*/
|
|
2010
|
+
acquireUrl(key: BlobKey, options?: BlobReadOptions): Promise<BlobUrlLease | null>;
|
|
2011
|
+
private lease;
|
|
2012
|
+
private releaseUrl;
|
|
2013
|
+
private revokeUrl;
|
|
2014
|
+
/** L1 lookup with the size check that catches torn and cross-tab writes. */
|
|
2015
|
+
private readLocal;
|
|
2016
|
+
/** True when the remote agrees with the cached size, or cannot be reached. */
|
|
2017
|
+
private headMatches;
|
|
2018
|
+
private fetchDeduped;
|
|
2019
|
+
private persist;
|
|
2020
|
+
private writeThrough;
|
|
2021
|
+
/** Forget one path everywhere. Called on `bucket.put()`/`bucket.delete()`. */
|
|
2022
|
+
invalidate(key: BlobKey): Promise<void>;
|
|
2023
|
+
private dropLocal;
|
|
2024
|
+
setPinned(key: BlobKey, pinned: boolean): void;
|
|
2025
|
+
/**
|
|
2026
|
+
* Bring total bytes under budget by dropping the least recently used
|
|
2027
|
+
* entries. Pinned entries and anything with a live object URL are skipped —
|
|
2028
|
+
* evicting bytes that a mounted `<img>` is displaying would blank it.
|
|
2029
|
+
*/
|
|
2030
|
+
private enforceBudget;
|
|
2031
|
+
/** Evict LRU-first until at or below `target`. Returns the resulting total. */
|
|
2032
|
+
private evictTo;
|
|
2033
|
+
/**
|
|
2034
|
+
* Rebuild the manifest from what is actually on disk. OPFS wins on existence
|
|
2035
|
+
* in both directions: files with no row get a row (seeded from mtime), rows
|
|
2036
|
+
* are only loaded for files that exist, and torn `.part-` writes are swept by
|
|
2037
|
+
* the walk itself.
|
|
2038
|
+
*
|
|
2039
|
+
* Rows whose file vanished outside our control (a browser origin eviction)
|
|
2040
|
+
* are left in `_00_blob`. They are inert — `load()` only ever asks for ids it
|
|
2041
|
+
* found on disk — and are overwritten if that path is cached again.
|
|
2042
|
+
*/
|
|
2043
|
+
reconcile(): Promise<void>;
|
|
2044
|
+
/** Warm the cache for offline use. Skips anything already cached. */
|
|
2045
|
+
prefetch(keys: BlobKey[]): Promise<void>;
|
|
2046
|
+
/** Bind to the boot bucket and hydrate the manifest from disk. Separate from
|
|
2047
|
+
* {@link setNamespace} because boot must reconcile even when the namespace
|
|
2048
|
+
* it lands on is the one the store was constructed with. */
|
|
2049
|
+
start(namespace: string): Promise<void>;
|
|
2050
|
+
/** Repoint at another local bucket. The bytes of the old one stay on disk so
|
|
2051
|
+
* switching back (or signing back in) is still warm. */
|
|
2052
|
+
setNamespace(namespace: string): Promise<void>;
|
|
2053
|
+
setMaxBytes(maxBytes: number): void;
|
|
2054
|
+
/** Delete every cached byte in the current namespace. */
|
|
2055
|
+
clear(): Promise<void>;
|
|
2056
|
+
flush(): Promise<void>;
|
|
2057
|
+
/** Flush metadata and drop every object URL. Must run before the local store
|
|
2058
|
+
* closes — the flush writes through it. */
|
|
2059
|
+
close(): Promise<void>;
|
|
2060
|
+
stats(): BlobCacheStats;
|
|
2061
|
+
}
|
|
2062
|
+
//#endregion
|
|
2063
|
+
//#region src/utils/blurhash.d.ts
|
|
2064
|
+
/**
|
|
2065
|
+
* Blurhash generation settings. `true` enables with the defaults below, `false`
|
|
2066
|
+
* disables. Resolution order for a put: per-call option > client config >
|
|
2067
|
+
* default ON. See {@link Sp00kyConfig.blurhash}.
|
|
2068
|
+
*/
|
|
2069
|
+
type BlurhashSetting = boolean | BlurhashEncodeOptions;
|
|
2070
|
+
interface BlurhashEncodeOptions {
|
|
2071
|
+
/** Horizontal detail components, 1-9. Defaults to 4. */
|
|
2072
|
+
componentX?: number;
|
|
2073
|
+
/** Vertical detail components, 1-9. Defaults to 3. */
|
|
2074
|
+
componentY?: number;
|
|
2075
|
+
}
|
|
2076
|
+
/**
|
|
2077
|
+
* Where an image's blurhash lives: a tiny sidecar object in the same bucket.
|
|
2078
|
+
* Buckets have no per-object metadata channel (`put` is just `.put($content)`),
|
|
2079
|
+
* so the hash for `covers/x_t.webp` is the text object `covers/x_t.webp.bh`.
|
|
2080
|
+
*/
|
|
2081
|
+
declare function blurhashSidecarPath(path: string): string;
|
|
2082
|
+
/** Extensions `bucket.put` treats as images worth hashing. */
|
|
2083
|
+
declare const BLURHASH_IMAGE_EXTENSIONS: readonly ["webp", "png", "jpg", "jpeg", "gif", "avif", "bmp"];
|
|
2084
|
+
declare function isImagePath(path: string): boolean;
|
|
2085
|
+
/**
|
|
2086
|
+
* Decode `content` as an image and compute its blurhash. Browser-only: returns
|
|
2087
|
+
* null (never throws) when image decoding is unavailable (node, workers without
|
|
2088
|
+
* canvas), when the bytes are not a decodable image, or on any other failure —
|
|
2089
|
+
* a missing hash must never break the upload that triggered it.
|
|
2090
|
+
*/
|
|
2091
|
+
declare function encodeImageToBlurhash(content: string | Uint8Array | Blob, options?: BlurhashEncodeOptions): Promise<string | null>;
|
|
2092
|
+
//#endregion
|
|
2093
|
+
//#region src/sp00ky.d.ts
|
|
2094
|
+
/** Coerce whatever the `.get()` RPC hands back into a Blob. */
|
|
2095
|
+
declare function bucketContentToBlob(content: unknown): Blob | null;
|
|
2096
|
+
interface BucketPutOptions {
|
|
2097
|
+
/** Override the client-level {@link Sp00kyConfig.blurhash} setting for this put. */
|
|
2098
|
+
blurhash?: BlurhashSetting;
|
|
2099
|
+
}
|
|
2100
|
+
interface BucketPutResult {
|
|
2101
|
+
/** The computed blurhash when the content was a hashable image; else null. */
|
|
2102
|
+
blurhash: string | null;
|
|
2103
|
+
}
|
|
2104
|
+
interface BucketHandleSettings {
|
|
2105
|
+
blurhash?: BlurhashSetting;
|
|
2106
|
+
logger?: {
|
|
2107
|
+
warn: (obj: unknown, msg?: string) => void;
|
|
2108
|
+
};
|
|
2109
|
+
}
|
|
198
2110
|
declare class BucketHandle {
|
|
199
2111
|
private bucketName;
|
|
200
2112
|
private remote;
|
|
201
|
-
|
|
202
|
-
|
|
2113
|
+
/** Absent on the raw handle the cache itself reads through. */
|
|
2114
|
+
private blobs?;
|
|
2115
|
+
private settings?;
|
|
2116
|
+
constructor(bucketName: string, remote: RemoteDatabaseService, /** Absent on the raw handle the cache itself reads through. */
|
|
2117
|
+
blobs?: (BlobCache | null) | undefined, settings?: BucketHandleSettings | undefined);
|
|
2118
|
+
/** Effective blurhash setting: per-call option > client config > default ON. */
|
|
2119
|
+
private resolveBlurhash;
|
|
2120
|
+
put(path: string, content: string | Uint8Array | Blob, options?: BucketPutOptions): Promise<BucketPutResult>;
|
|
2121
|
+
/**
|
|
2122
|
+
* The blurhash stored alongside an uploaded image (see
|
|
2123
|
+
* {@link blurhashSidecarPath}), or null when there is none. Reads through the
|
|
2124
|
+
* blob cache, so a warm client answers from OPFS without a network hop, and
|
|
2125
|
+
* misses are remembered per tab so a hashless image costs at most one
|
|
2126
|
+
* serialized remote read per session.
|
|
2127
|
+
*/
|
|
2128
|
+
blurhash(path: string): Promise<string | null>;
|
|
203
2129
|
get(path: string): Promise<unknown>;
|
|
2130
|
+
/**
|
|
2131
|
+
* Read through the local blob cache: OPFS first, the bucket second. Unlike
|
|
2132
|
+
* {@link get} this survives a reload and works offline. Returns null when the
|
|
2133
|
+
* file exists in neither place.
|
|
2134
|
+
*/
|
|
2135
|
+
read(path: string, options?: BlobReadOptions): Promise<Blob | null>;
|
|
2136
|
+
/**
|
|
2137
|
+
* A refcounted object URL for `path`, suitable for `<img src>`. The caller
|
|
2138
|
+
* MUST call `release()` when the URL goes off screen. Returns null when the
|
|
2139
|
+
* file does not exist, or when object URLs are unavailable (non-browser).
|
|
2140
|
+
*/
|
|
2141
|
+
url(path: string, options?: BlobReadOptions): Promise<BlobUrlLease | null>;
|
|
2142
|
+
/** Exempt `path` from pressure eviction. Pinned bytes never expire. */
|
|
2143
|
+
pin(path: string): void;
|
|
2144
|
+
unpin(path: string): void;
|
|
2145
|
+
/** Drop `path` from the local cache without touching the remote file. */
|
|
2146
|
+
evict(path: string): Promise<void>;
|
|
2147
|
+
/** Warm the cache for offline use. Already-cached paths are skipped. */
|
|
2148
|
+
prefetch(paths: string[]): Promise<void>;
|
|
204
2149
|
delete(path: string): Promise<void>;
|
|
205
2150
|
exists(path: string): Promise<boolean>;
|
|
206
2151
|
head(path: string): Promise<Record<string, unknown>>;
|
|
@@ -208,55 +2153,240 @@ declare class BucketHandle {
|
|
|
208
2153
|
rename(sourcePath: string, targetPath: string): Promise<void>;
|
|
209
2154
|
list(prefix?: string): Promise<string[]>;
|
|
210
2155
|
}
|
|
211
|
-
declare class
|
|
2156
|
+
declare class Sp00kyClient<S extends SchemaStructure> {
|
|
212
2157
|
private config;
|
|
213
2158
|
private local;
|
|
214
2159
|
private remote;
|
|
2160
|
+
private blobs;
|
|
2161
|
+
private connectionSupervisor;
|
|
215
2162
|
private persistenceClient;
|
|
216
2163
|
private migrator;
|
|
217
2164
|
private cache;
|
|
218
2165
|
private dataModule;
|
|
219
2166
|
private sync;
|
|
220
2167
|
private devTools;
|
|
2168
|
+
private crdtManager;
|
|
2169
|
+
private featureFlags;
|
|
2170
|
+
private appReleases;
|
|
2171
|
+
private preloadedHashes;
|
|
2172
|
+
private pendingQueryInits;
|
|
221
2173
|
private logger;
|
|
222
2174
|
auth: AuthService<S>;
|
|
223
2175
|
streamProcessor: StreamProcessorService;
|
|
224
|
-
|
|
225
|
-
|
|
2176
|
+
private tabsCoordinator;
|
|
2177
|
+
private sharedActive;
|
|
2178
|
+
/** Current shared-tabs role, or null when the feature is off/fell back. */
|
|
2179
|
+
get tabRole(): TabRole | null;
|
|
2180
|
+
get remoteClient(): surrealdb0.Surreal;
|
|
2181
|
+
get localClient(): unknown;
|
|
226
2182
|
get pendingMutationCount(): number;
|
|
2183
|
+
/** Number of times the initial list_ref LIVE subscription retried on
|
|
2184
|
+
* the most recent `setCurrentUserId` call. 0 when the SSP's
|
|
2185
|
+
* pre-emptive user-table creation got there first; >0 when LIVE
|
|
2186
|
+
* registration hit a "table not found" race. Exposed so the e2e
|
|
2187
|
+
* suite can guard the pre-emptive path against regression. */
|
|
2188
|
+
get liveRetryCount(): number;
|
|
227
2189
|
subscribeToPendingMutations(cb: (count: number) => void): () => void;
|
|
228
|
-
|
|
2190
|
+
/** Current sync-health snapshot. See {@link Sp00kyConfig.syncHealth}. */
|
|
2191
|
+
get syncHealth(): SyncHealth;
|
|
2192
|
+
/**
|
|
2193
|
+
* Observe sync health. Fires immediately with the current status and again
|
|
2194
|
+
* on every healthy↔degraded transition. Returns an unsubscribe.
|
|
2195
|
+
*/
|
|
2196
|
+
subscribeToSyncHealth(cb: (health: SyncHealth) => void): () => void;
|
|
2197
|
+
/** Durability of the local cache. See {@link StorageHealth}. `'unknown'` for
|
|
2198
|
+
* engines that don't report it. */
|
|
2199
|
+
get storageHealth(): StorageHealth;
|
|
2200
|
+
/**
|
|
2201
|
+
* Observe local-store durability. Fires immediately with the current snapshot
|
|
2202
|
+
* and again on every change (at most once per bucket open in practice).
|
|
2203
|
+
* Returns an unsubscribe.
|
|
2204
|
+
*/
|
|
2205
|
+
subscribeToStorageHealth(cb: (health: StorageHealth) => void): () => void;
|
|
2206
|
+
constructor(config: Sp00kyConfig<S>);
|
|
2207
|
+
/** The shared-tabs role machinery, wired to this client's modules. */
|
|
2208
|
+
private buildTabsCoordinator;
|
|
229
2209
|
/**
|
|
230
2210
|
* Setup direct callbacks instead of event subscriptions
|
|
231
2211
|
*/
|
|
232
2212
|
private setupCallbacks;
|
|
233
2213
|
init(): Promise<void>;
|
|
2214
|
+
private bucketSwitchChain;
|
|
2215
|
+
private pendingBucketTarget;
|
|
2216
|
+
/**
|
|
2217
|
+
* Ensure the local store is this user's bucket, switching if needed. Called
|
|
2218
|
+
* from the auth listener on every auth flip; concurrent calls are chained
|
|
2219
|
+
* and superseded intermediates are skipped (latest target wins).
|
|
2220
|
+
*/
|
|
2221
|
+
private ensureLocalBucket;
|
|
2222
|
+
/**
|
|
2223
|
+
* The bucket-switch choreography: drain → swap → rebind.
|
|
2224
|
+
*
|
|
2225
|
+
* Drain: sync quiesced (poll/LIVE stopped, in-flight round awaited so its
|
|
2226
|
+
* outbox delete lands in the OLD bucket, debounce timers cancelled),
|
|
2227
|
+
* DataModule timers cleared, CRDT fields closed WITHOUT their final flush
|
|
2228
|
+
* (the remote session already belongs to the next user).
|
|
2229
|
+
*
|
|
2230
|
+
* Swap: gate closes so any local query issued mid-switch (sibling auth
|
|
2231
|
+
* subscribers, FeatureFlagModule) waits and then runs against the NEW
|
|
2232
|
+
* bucket; store swaps open-new-before-close-old; schema provisions
|
|
2233
|
+
* (no-op for a returning bucket); stale `_00_query` rows are wiped (dead
|
|
2234
|
+
* sessionId-salted hashes with stale arrays — record bodies stay warm);
|
|
2235
|
+
* SSP resets to a fresh circuit with re-seeded permissions.
|
|
2236
|
+
*
|
|
2237
|
+
* Rebind: auth token re-persisted (the surrealdb persistence client wrote it
|
|
2238
|
+
* into the OLD bucket's `_00_kv` before this listener ran), active queries
|
|
2239
|
+
* re-homed keeping their hashes, sync resumed on the new bucket's own
|
|
2240
|
+
* outbox, and every query re-registered remotely to refill from the server.
|
|
2241
|
+
*/
|
|
2242
|
+
private doSwitchBucket;
|
|
234
2243
|
close(): Promise<void>;
|
|
2244
|
+
/**
|
|
2245
|
+
* Subscribe to a feature flag for the current user. Returns a
|
|
2246
|
+
* `FeatureFlagHandle` whose `variant()`, `payload()` and `enabled()`
|
|
2247
|
+
* accessors reflect the latest assignment from `_00_user_feature`,
|
|
2248
|
+
* and whose `subscribe(cb)` fires whenever that assignment changes.
|
|
2249
|
+
*
|
|
2250
|
+
* Permissions are enforced by SurrealDB: a client can only ever see
|
|
2251
|
+
* its own row, and cannot create or modify assignments.
|
|
2252
|
+
*/
|
|
2253
|
+
feature(key: string, options?: FeatureFlagOptions): FeatureFlagHandle;
|
|
2254
|
+
/**
|
|
2255
|
+
* Force a feature flag to `variant` in THIS browser only; `null` clears it.
|
|
2256
|
+
*
|
|
2257
|
+
* Nothing is sent to the server — the `_00_user_feature` assignment is
|
|
2258
|
+
* untouched, so clearing restores whatever the server says. Persisted to
|
|
2259
|
+
* localStorage, survives reloads, and applies while signed out. Backs the
|
|
2260
|
+
* DevTools Access tab, and is a convenient hook for tests.
|
|
2261
|
+
*
|
|
2262
|
+
* To change a flag for OTHER users you need admin rights (`spky admin add`)
|
|
2263
|
+
* and the DevTools Access tab, or `spky flag`.
|
|
2264
|
+
*/
|
|
2265
|
+
setFeatureOverride(key: string, variant: string | null, payload?: unknown): void;
|
|
2266
|
+
/** Drop every local feature flag override set via `setFeatureOverride`. */
|
|
2267
|
+
clearFeatureOverrides(): void;
|
|
2268
|
+
/** The local feature flag overrides currently in effect, keyed by flag. */
|
|
2269
|
+
getFeatureOverrides(): Record<string, FeatureFlagOverride>;
|
|
2270
|
+
/**
|
|
2271
|
+
* Observe the announced release of an app (`_00_app_release:<app>`, written
|
|
2272
|
+
* by `spky deploy` / `spky release`). The handle's `snapshot()` carries the
|
|
2273
|
+
* announced version plus the cache-bust/mandatory flags, and
|
|
2274
|
+
* `updateAvailable(currentVersion)` compares it semver-wise against the
|
|
2275
|
+
* running build. World-readable; writes are root-only.
|
|
2276
|
+
*/
|
|
2277
|
+
appRelease(app: string, options?: AppReleaseOptions): AppReleaseHandle;
|
|
235
2278
|
authenticate(token: string): Promise<surrealdb0.Tokens>;
|
|
2279
|
+
/**
|
|
2280
|
+
* Open a CRDT field for collaborative editing.
|
|
2281
|
+
* Returns a CrdtField with a LoroDoc that can be bound to any editor.
|
|
2282
|
+
* Also starts a LIVE SELECT on the parent table for real-time sync;
|
|
2283
|
+
* incoming events trigger a subquery fetch of `_00_crdt` / `_00_cursor`.
|
|
2284
|
+
*/
|
|
2285
|
+
openCrdtField(table: string, recordId: string, field: string, fallbackText?: string): Promise<CrdtField>;
|
|
2286
|
+
/**
|
|
2287
|
+
* Close a CRDT field when editing is done.
|
|
2288
|
+
*/
|
|
2289
|
+
closeCrdtField(table: string, recordId: string, field: string): void;
|
|
236
2290
|
deauthenticate(): Promise<void>;
|
|
237
|
-
query<Table extends TableNames<S>>(table: Table, options: QueryOptions<TableModel<GetTable<S, Table>>, false>, ttl?: QueryTimeToLive): QueryBuilder<S, Table,
|
|
2291
|
+
query<Table extends TableNames<S>>(table: Table, options: QueryOptions<TableModel<GetTable<S, Table>>, false>, ttl?: QueryTimeToLive): QueryBuilder<S, Table, Sp00kyQueryResultPromise>;
|
|
238
2292
|
private initQuery;
|
|
2293
|
+
/**
|
|
2294
|
+
* Background tail of {@link initQuery}: instant-hydrate (opt-in via
|
|
2295
|
+
* `config.instantHydrate`, and only when the query is cold) followed by
|
|
2296
|
+
* enqueuing the `register` down-event. Never rejects — both halves catch and
|
|
2297
|
+
* log, so `void`-ing the returned promise can't produce an unhandled
|
|
2298
|
+
* rejection. By default (hydrate off) the register lifecycle is the single
|
|
2299
|
+
* freshness path; the one-shot fetch is an optimization apps enable
|
|
2300
|
+
* explicitly, and it runs regardless of preload state — cache-first delivery
|
|
2301
|
+
* never depends on WHY rows are cached.
|
|
2302
|
+
*/
|
|
2303
|
+
private finishQueryInit;
|
|
2304
|
+
/**
|
|
2305
|
+
* Smart, awaitable preload/prewarm into the LOCAL cache — without registering a
|
|
2306
|
+
* live view (NO `_00_query`, NO subscription, NO TTL heartbeat).
|
|
2307
|
+
*
|
|
2308
|
+
* Cache-aware via a durable per-bucket freshness marker (`_00_preload`):
|
|
2309
|
+
* - COLD (never preloaded in this bucket): fetch the query one-shot from the
|
|
2310
|
+
* remote, persist the rows (+ embedded `.related()` children), stamp the
|
|
2311
|
+
* marker — and AWAIT it. This is the "smart waiting" first load: callers can
|
|
2312
|
+
* `await db.preload(...)` to hold the UI until the data is ready.
|
|
2313
|
+
* - WARM (marker present): return instantly — NEVER blocks. `refresh` decides
|
|
2314
|
+
* whether to also kick a one-time silent refetch (see {@link PreloadOptions}).
|
|
2315
|
+
* Default `onUse` does nothing; the data freshens when the real `useQuery`
|
|
2316
|
+
* mounts and registers its live view.
|
|
2317
|
+
*
|
|
2318
|
+
* Best-effort: any fetch failure (offline, etc.) is a no-op warn (no marker
|
|
2319
|
+
* written, so it's retried next load). Deduped per session by query hash.
|
|
2320
|
+
*/
|
|
2321
|
+
preload(finalQuery: FinalQuery<S, any, any, any, any, any>, options?: PreloadOptions): Promise<void>;
|
|
2322
|
+
/**
|
|
2323
|
+
* One-shot remote fetch + local persist for a preload query. Returns the row
|
|
2324
|
+
* count on success, or -1 on failure (best-effort: logged, never thrown) so
|
|
2325
|
+
* the caller skips stamping the freshness marker and retries next load.
|
|
2326
|
+
*/
|
|
2327
|
+
private fetchAndPersist;
|
|
239
2328
|
queryRaw(sql: string, params: Record<string, any>, ttl: QueryTimeToLive): Promise<string>;
|
|
240
2329
|
subscribe(queryHash: string, callback: (records: Record<string, any>[]) => void, options?: {
|
|
241
2330
|
immediate?: boolean;
|
|
242
2331
|
}): Promise<() => void>;
|
|
2332
|
+
/**
|
|
2333
|
+
* Opt-in eager teardown for a query whose last subscriber has gone away
|
|
2334
|
+
* (e.g. a viewport-windowed list cancelling an off-screen window). No-op
|
|
2335
|
+
* while any subscriber remains. Tears down the remote `_00_query` view +
|
|
2336
|
+
* local WASM view instead of waiting for the TTL sweep. Default behavior
|
|
2337
|
+
* (no call here) keeps the view resident for cheap re-subscription.
|
|
2338
|
+
*/
|
|
2339
|
+
deregisterQuery(queryHash: string): void;
|
|
2340
|
+
/**
|
|
2341
|
+
* Subscribe to a query's fetch-status changes (idle/fetching). With
|
|
2342
|
+
* `{ immediate: true }` the callback fires synchronously with the current
|
|
2343
|
+
* status. Powers the `useQuery` hook's `isFetching()` accessor.
|
|
2344
|
+
*/
|
|
2345
|
+
subscribeQueryStatus(queryHash: string, callback: QueryStatusCallback, options?: {
|
|
2346
|
+
immediate?: boolean;
|
|
2347
|
+
}): () => void;
|
|
2348
|
+
/**
|
|
2349
|
+
* Report the frontend processing time (ms) a client framework spent applying
|
|
2350
|
+
* an update for a query (e.g. `useQuery`'s `reconcile()`), so DevTools/MCP can
|
|
2351
|
+
* surface the "frontend" phase of the per-query timing breakdown.
|
|
2352
|
+
*/
|
|
2353
|
+
reportFrontendTiming(queryHash: string, ms: number): void;
|
|
243
2354
|
run<B extends BackendNames<S>, R extends BackendRoutes<S, B>>(backend: B, path: R, payload: RoutePayload<S, B, R>, options?: RunOptions): Promise<void>;
|
|
244
2355
|
bucket<B extends BucketNames<S>>(name: B): BucketHandle;
|
|
2356
|
+
/** Cache-free handle. The blob cache reads the remote through this, so a
|
|
2357
|
+
* cache miss can't loop back into the cache. */
|
|
2358
|
+
private rawBucket;
|
|
2359
|
+
/** Blob cache counters for DevTools. */
|
|
2360
|
+
getBlobCacheStats(): BlobCacheStats;
|
|
245
2361
|
create(id: string, data: Record<string, unknown>): Promise<Record<string, unknown>>;
|
|
246
2362
|
update(table: string, id: string, data: Record<string, unknown>, options?: UpdateOptions): Promise<{
|
|
247
2363
|
[x: string]: /*elided*/any;
|
|
248
2364
|
}>;
|
|
249
2365
|
delete(table: string, id: string): Promise<void>;
|
|
250
2366
|
useRemote<T>(fn: (client: Surreal) => Promise<T> | T): Promise<T>;
|
|
251
|
-
|
|
252
|
-
|
|
2367
|
+
/**
|
|
2368
|
+
* Fetch SurrealDB's `session::id()` as a string. Used as a salt for
|
|
2369
|
+
* query-id hashing so two sessions for the same user get distinct
|
|
2370
|
+
* `_00_query` rows. Returns empty string if the query fails (we still
|
|
2371
|
+
* boot, just without session scoping for IDs).
|
|
2372
|
+
*/
|
|
2373
|
+
private fetchSessionId;
|
|
253
2374
|
}
|
|
254
2375
|
//#endregion
|
|
2376
|
+
//#region src/utils/semver.d.ts
|
|
2377
|
+
/** True when `a` is a valid version strictly greater than valid version `b`. */
|
|
2378
|
+
declare function semverGt(a: unknown, b: unknown): boolean;
|
|
2379
|
+
//#endregion
|
|
255
2380
|
//#region src/utils/index.d.ts
|
|
256
2381
|
declare function fileToUint8Array(file: File | Blob): Promise<Uint8Array>;
|
|
2382
|
+
/**
|
|
2383
|
+
* Convert plain text to simple HTML paragraphs.
|
|
2384
|
+
* Useful for seeding a rich-text editor (e.g. TipTap/ProseMirror) with fallback content.
|
|
2385
|
+
*/
|
|
2386
|
+
declare function textToHtml(text: string): string;
|
|
257
2387
|
/**
|
|
258
2388
|
* Helper for retrying DB operations with exponential backoff
|
|
259
2389
|
*/
|
|
260
2390
|
|
|
261
2391
|
//#endregion
|
|
262
|
-
export { AuthEventSystem, AuthEventTypeMap, AuthEventTypes, AuthService, BucketHandle, DebounceOptions, EventSubscriptionOptions, Level, MutationCallback, MutationEvent, MutationEventType, PersistenceClient, PinoTransmit, QueryConfig, QueryConfigRecord, QueryHash, QueryState, QueryTimeToLive, QueryUpdateCallback, RecordVersionArray, RecordVersionDiff, RunOptions,
|
|
2392
|
+
export { AppReleaseHandle, AppReleaseModule, type AppReleaseOptions, type AppReleaseSnapshot, AuthEventSystem, AuthEventTypeMap, AuthEventTypes, AuthService, BLURHASH_IMAGE_EXTENSIONS, type BlobCacheStats, type BlobEntry, type BlobKey, type BlobReadOptions, type BlobUrlLease, type BlurhashEncodeOptions, type BlurhashSetting, BucketHandle, BucketPutOptions, BucketPutResult, CURSOR_COLORS, ConnectionState, CrdtField, CrdtManager, DebounceOptions, EventSubscriptionOptions, FeatureFlagHandle, FeatureFlagModule, type FeatureFlagOptions, type FeatureFlagOverride, type FeatureFlagSnapshot, Level, MATERIALIZATION_SAMPLE_WINDOW, MutationCallback, MutationEvent, MutationEventType, PersistenceClient, PhaseStat, PinoTransmit, PreloadOptions, PreloadRefresh, QueryConfig, QueryConfigRecord, QueryHash, QueryState, QueryStatus, QueryStatusCallback, QueryTimeToLive, QueryTimings, QueryUpdateCallback, ReconnectConfig, RecordVersionArray, RecordVersionDiff, RegistrationTimings, RunOptions, Sp00kyClient, Sp00kyConfig, Sp00kyQueryResult, Sp00kyQueryResultPromise, StorageHealth, StorageHealthStatus, StoreType, SyncHealth, SyncHealthConfig, SyncHealthStatus, TimingPhase, UpdateOptions, blurhashSidecarPath, bucketContentToBlob, createAuthEventSystem, cursorColorFromName, decode as decodeBlurhash, encode as encodeBlurhash, encodeImageToBlurhash, fileToUint8Array, isBlurhashValid, isImagePath, semverGt, textToHtml };
|