@spooky-sync/core 0.0.1-canary.97 → 1.0.0-beta.1
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 -21
- package/README.md +59 -16
- package/dist/index.d.ts +2096 -929
- package/dist/index.js +18217 -5019
- package/dist/live.d.ts +149 -0
- package/dist/live.js +739 -0
- package/dist/otel/index.d.ts +1 -1
- package/dist/pure.d.ts +401 -0
- package/dist/pure.js +24 -0
- package/dist/sqlite-open.js +392 -0
- package/dist/sqlite-worker.d.ts +1 -0
- package/dist/sqlite-worker.js +439 -0
- package/dist/sw.d.ts +207 -0
- package/dist/sw.js +393 -0
- package/dist/tabs-broker-worker.d.ts +8 -0
- package/dist/tabs-broker-worker.js +477 -0
- package/dist/types.d.ts +1968 -82
- package/dist/worker-edges.js +498 -0
- package/dist/worker-impersonation.js +60 -0
- package/dist/worker-ref-tables.d.ts +48 -0
- package/dist/worker-types.d.ts +112 -0
- package/dist/worker-types.js +73 -0
- package/package.json +34 -8
- package/scripts/check-broker-bundle.mjs +33 -0
- package/scripts/check-worker-entries.mjs +173 -0
- package/skills/sp00ky-core/SKILL.md +42 -8
- package/skills/sp00ky-core/references/config.md +8 -2
- package/src/boot/auth-flip.saga.test.ts +174 -0
- package/src/boot/auth-flip.saga.ts +77 -0
- package/src/boot/boot.saga.test.ts +203 -0
- package/src/boot/boot.saga.ts +146 -0
- package/src/boot/bucket-switch.saga.test.ts +191 -0
- package/src/boot/bucket-switch.saga.ts +151 -0
- package/src/boot/preload.saga.test.ts +96 -0
- package/src/boot/preload.saga.ts +45 -0
- package/src/bucket-blurhash.test.ts +148 -0
- package/src/client/bucket-handle.test.ts +195 -0
- package/src/client/bucket-handle.ts +352 -0
- package/src/client/router.test.ts +59 -0
- package/src/client/router.ts +104 -0
- package/src/client/runtime.test.ts +319 -0
- package/src/client/runtime.ts +307 -0
- package/src/client/services.test.ts +74 -0
- package/src/client/services.ts +437 -0
- package/src/client/sp00ky-client.test.ts +428 -0
- package/src/client/sp00ky-client.ts +737 -0
- package/src/index.ts +78 -0
- package/src/kernel/constants.test.ts +19 -0
- package/src/kernel/constants.ts +94 -0
- package/src/kernel/effects.test.ts +40 -0
- package/src/kernel/effects.ts +171 -0
- package/src/kernel/events.ts +60 -0
- package/src/kernel/interpreter.test.ts +116 -0
- package/src/kernel/interpreter.ts +148 -0
- package/src/kernel/saga.test.ts +89 -0
- package/src/kernel/saga.ts +73 -0
- package/src/live/index.test.ts +512 -0
- package/src/live/index.ts +1059 -0
- package/src/modules/app-release/index.test.ts +125 -0
- package/src/modules/app-release/index.ts +209 -0
- package/src/modules/auth/auth.local-first.test.ts +228 -0
- package/src/modules/auth/auth.session-recheck.test.ts +140 -0
- package/src/modules/auth/events/index.ts +7 -1
- package/src/modules/auth/impersonation-banner.ts +443 -0
- package/src/modules/auth/impersonation.integration.test.ts +209 -0
- package/src/modules/auth/impersonation.test.ts +377 -0
- package/src/modules/auth/impersonation.ts +179 -0
- package/src/modules/auth/index.ts +516 -34
- package/src/modules/channel/channel.test.ts +752 -0
- package/src/modules/channel/index.ts +1153 -0
- package/src/modules/channel/webrtc.ts +472 -0
- package/src/modules/crdt/acceptance.ts +75 -0
- package/src/modules/crdt/bytes.ts +50 -0
- package/src/modules/crdt/crdt-field.ts +82 -238
- package/src/modules/crdt/crdt.test.ts +546 -0
- package/src/modules/crdt/hash.ts +103 -0
- package/src/modules/crdt/index.ts +740 -271
- package/src/modules/crdt/loro-loader.ts +25 -0
- package/src/modules/crdt/mirror.ts +37 -0
- package/src/modules/devtools/flags.ts +349 -0
- package/src/modules/devtools/index.ts +661 -99
- package/src/modules/devtools/mutations.test.ts +92 -0
- package/src/modules/devtools/mutations.ts +160 -0
- package/src/modules/devtools/notify-throttle.test.ts +166 -0
- package/src/modules/devtools/state-shape.test.ts +263 -0
- package/src/modules/devtools/storage-info.test.ts +79 -0
- package/src/modules/devtools/storage-info.ts +168 -0
- package/src/modules/devtools/versions.ts +29 -0
- package/src/modules/feature-flag/index.test.ts +179 -1
- package/src/modules/feature-flag/index.ts +117 -10
- package/src/modules/ref-tables.test.ts +28 -1
- package/src/modules/ref-tables.ts +23 -1
- package/src/modules/web-push/index.test.ts +824 -0
- package/src/modules/web-push/index.ts +1027 -0
- package/src/mutation/ingest-outage.integration.test.ts +400 -0
- package/src/mutation/jobs.test.ts +25 -0
- package/src/mutation/jobs.ts +41 -0
- package/src/mutation/mutation-id.test.ts +37 -0
- package/src/mutation/mutation-id.ts +35 -0
- package/src/mutation/pending-writes.integration.test.ts +175 -0
- package/src/mutation/push.saga.test.ts +361 -0
- package/src/mutation/push.saga.ts +245 -0
- package/src/mutation/rows.test.ts +278 -0
- package/src/mutation/rows.ts +515 -0
- package/src/mutation/tray.saga.test.ts +63 -0
- package/src/mutation/tray.saga.ts +48 -0
- package/src/mutation/write.saga.test.ts +436 -0
- package/src/mutation/write.saga.ts +384 -0
- package/src/pure.ts +66 -0
- package/src/push/types.ts +174 -0
- package/src/query/anon-query-isolation.integration.test.ts +531 -0
- package/src/query/env.test.ts +23 -0
- package/src/query/env.ts +65 -0
- package/src/query/fetch.saga.test.ts +199 -0
- package/src/query/fetch.saga.ts +120 -0
- package/src/query/hash.test.ts +14 -0
- package/src/query/hash.ts +18 -0
- package/src/query/id-set-plan.test.ts +132 -0
- package/src/query/lifecycle.saga.test.ts +274 -0
- package/src/query/lifecycle.saga.ts +186 -0
- package/src/query/list-ref-live.integration.test.ts +203 -0
- package/src/query/materialize.saga.test.ts +200 -0
- package/src/query/materialize.saga.ts +102 -0
- package/src/query/materialize.test.ts +58 -0
- package/src/query/materialize.ts +57 -0
- package/src/query/membership.saga.test.ts +514 -0
- package/src/query/membership.saga.ts +339 -0
- package/src/query/membership.test.ts +151 -0
- package/src/query/membership.ts +234 -0
- package/src/query/register.saga.test.ts +369 -0
- package/src/query/register.saga.ts +293 -0
- package/src/query/render-set.test.ts +47 -0
- package/src/query/render-set.ts +71 -0
- package/src/query/session-guard.integration.test.ts +304 -0
- package/src/query/sql.test.ts +118 -0
- package/src/query/sql.ts +174 -0
- package/src/{modules/data → query}/window-query.test.ts +22 -4
- package/src/{modules/data → query}/window-query.ts +86 -8
- package/src/services/blobs/blob-cache.test.ts +359 -0
- package/src/services/blobs/blob-cache.ts +603 -0
- package/src/services/blobs/blob-manifest.ts +227 -0
- package/src/services/blobs/blob-store.test.ts +77 -0
- package/src/services/blobs/blob-store.ts +359 -0
- package/src/services/blobs/blob.fixture.ts +90 -0
- package/src/services/blobs/index.ts +70 -0
- package/src/services/database/cache-engine.ts +209 -0
- package/src/services/database/connection-supervisor.test.ts +318 -0
- package/src/services/database/connection-supervisor.ts +422 -0
- package/src/services/database/database.query-timeout.test.ts +140 -0
- package/src/services/database/database.responses.test.ts +43 -0
- package/src/services/database/database.ts +151 -56
- package/src/services/database/engine-factory.ts +33 -0
- package/src/services/database/errors.ts +34 -0
- package/src/services/database/index.ts +7 -0
- package/src/services/database/landed-body-clear.integration.test.ts +236 -0
- package/src/services/database/local-migrator.integration.test.ts +110 -0
- package/src/services/database/local-migrator.ts +54 -9
- package/src/services/database/local.test.ts +117 -0
- package/src/services/database/local.ts +364 -74
- package/src/services/database/plan-render.test.ts +159 -0
- package/src/services/database/plan-render.ts +108 -0
- package/src/services/database/relation-resolver.test.ts +484 -0
- package/src/services/database/relation-resolver.ts +0 -0
- package/src/services/database/remote.ts +283 -4
- package/src/services/database/sqlite-cache-engine.test.ts +628 -0
- package/src/services/database/sqlite-cache-engine.timeout.test.ts +61 -0
- package/src/services/database/sqlite-cache-engine.ts +1401 -0
- package/src/services/database/sqlite-column-reset.integration.test.ts +100 -0
- package/src/services/database/sqlite-column-reset.ts +91 -0
- package/src/services/database/sqlite-devtools-queries.integration.test.ts +143 -0
- package/src/services/database/sqlite-devtools-queries.test.ts +154 -0
- package/src/services/database/sqlite-lock-verify.test.ts +33 -0
- package/src/services/database/sqlite-lock-verify.ts +45 -0
- package/src/services/database/sqlite-open.test.ts +150 -0
- package/src/services/database/sqlite-open.ts +164 -0
- package/src/services/database/sqlite-plan-sql.test.ts +164 -0
- package/src/services/database/sqlite-plan-sql.ts +196 -0
- package/src/services/database/sqlite-projection.test.ts +121 -0
- package/src/services/database/sqlite-select.integration.test.ts +185 -0
- package/src/services/database/sqlite-select.test.ts +261 -0
- package/src/services/database/sqlite-select.ts +131 -0
- package/src/services/database/sqlite-transport.fixture.ts +30 -0
- package/src/services/database/sqlite-transport.ts +229 -0
- package/src/services/database/sqlite-worker.ts +437 -0
- package/src/services/database/surql-translate.ts +417 -0
- package/src/services/database/surreal-cache-engine.ts +163 -0
- package/src/services/logger/index.test.ts +132 -0
- package/src/services/logger/index.ts +187 -6
- package/src/services/persistence/surrealdb.ts +2 -2
- package/src/services/stream-processor/index.ts +621 -93
- package/src/services/stream-processor/stream-processor.batch.test.ts +57 -7
- package/src/services/stream-processor/stream-processor.prime.test.ts +234 -0
- package/src/services/stream-processor/stream-processor.reset.test.ts +226 -0
- package/src/services/stream-processor/wasm-types.ts +41 -1
- package/src/services/tabs/broker-client.ts +284 -0
- package/src/services/tabs/broker.test.ts +381 -0
- package/src/services/tabs/coordinator.test.ts +386 -0
- package/src/services/tabs/coordinator.ts +646 -0
- package/src/services/tabs/fake-ports.fixture.ts +112 -0
- package/src/services/tabs/leader-locks.ts +75 -0
- package/src/services/tabs/protocol.ts +262 -0
- package/src/services/tabs/support.ts +36 -0
- package/src/services/tabs/tabs-broker-worker.ts +652 -0
- package/src/sp00ky.ts +5 -648
- package/src/state/client-state.ts +231 -0
- package/src/state/lifecycle.test.ts +184 -0
- package/src/state/lifecycle.ts +127 -0
- package/src/state/reducers.test.ts +337 -0
- package/src/state/reducers.ts +571 -0
- package/src/state/selectors.test.ts +203 -0
- package/src/state/selectors.ts +264 -0
- package/src/sw/index.test.ts +582 -0
- package/src/sw/index.ts +607 -0
- package/src/sw/store.ts +96 -0
- package/src/sync/connection.saga.test.ts +97 -0
- package/src/sync/connection.saga.ts +89 -0
- package/src/sync/live.saga.test.ts +229 -0
- package/src/sync/live.saga.ts +116 -0
- package/src/sync/policy.health.test.ts +56 -0
- package/src/{modules/sync/utils.test.ts → sync/policy.test.ts} +96 -11
- package/src/{modules/sync/utils.ts → sync/policy.ts} +186 -7
- package/src/sync/poll.saga.test.ts +51 -0
- package/src/sync/poll.saga.ts +36 -0
- package/src/sync/tabs.saga.test.ts +78 -0
- package/src/sync/tabs.saga.ts +96 -0
- package/src/testing/adapters.ts +137 -0
- package/src/testing/build.ts +63 -0
- package/src/testing/fake-services.ts +63 -0
- package/src/testing/run-pure.test.ts +92 -0
- package/src/testing/run-pure.ts +128 -0
- package/src/testing/services.ts +17 -0
- package/src/types.ts +568 -25
- package/src/utils/blurhash.ts +90 -0
- package/src/utils/edges.ts +57 -0
- package/src/utils/error-classification.test.ts +116 -0
- package/src/utils/error-classification.ts +74 -0
- package/src/utils/index.ts +58 -3
- package/src/utils/parser.test.ts +67 -102
- package/src/utils/parser.ts +62 -1
- package/src/utils/semver.test.ts +32 -0
- package/src/utils/semver.ts +30 -0
- package/src/utils/sha256.ts +15 -0
- package/src/utils/surql.ts +17 -15
- package/src/utils/utils.test.ts +3 -2
- package/tsdown.config.ts +64 -4
- package/vitest.config.ts +48 -0
- package/src/modules/cache/index.ts +0 -253
- package/src/modules/cache/types.ts +0 -19
- package/src/modules/crdt/crdt-hydration.test.ts +0 -206
- package/src/modules/data/data.status.test.ts +0 -108
- package/src/modules/data/data.test.ts +0 -58
- package/src/modules/data/index.ts +0 -1491
- package/src/modules/sync/engine.ts +0 -227
- package/src/modules/sync/events/index.ts +0 -84
- package/src/modules/sync/index.ts +0 -3
- package/src/modules/sync/queue/index.ts +0 -2
- package/src/modules/sync/queue/queue-down.ts +0 -90
- package/src/modules/sync/queue/queue-up.ts +0 -224
- package/src/modules/sync/scheduler.ts +0 -121
- package/src/modules/sync/sync.ts +0 -1244
- package/src/sp00ky.auth-order.test.ts +0 -65
package/dist/index.d.ts
CHANGED
|
@@ -1,119 +1,219 @@
|
|
|
1
|
-
import { A as
|
|
1
|
+
import { $ as WebPushInfo, $t as ChannelScope, A as RecordVersionArray, At as AuthEventTypeMap, B as StorageHealthStatus, Bt as ImpersonationTimerHost, C as QueryState, Ct as AuthService, D as QueryTimings, Dt as SignOutContext, E as QueryTimeToLive, Et as SIGN_OUT_HOOK_TIMEOUT_MS, F as Sp00kyChannel, Ft as SealedQuery, G as TimingPhase, Gt as decodeTokenClaims, H as SyncHealth, Ht as ORIGIN_TOKEN_KEY, I as Sp00kyConfig, It as EventDefinition, J as PushDeviceKind, Jt as sameImpersonation, K as UpdateOptions, Kt as impersonationFromToken, L as Sp00kyQueryResult, Lt as EventSystem, M as RegistrationTimings, Mt as createAuthEventSystem, N as RunOptions, Nt as RemoteDatabaseService, O as QueryUpdateCallback, Ot as SignOutHook, P as ServerViewMeta, Pt as LocalStore, Q as WebPushErrorCode, Qt as ChannelOp, R as Sp00kyQueryResultPromise, Rt as IMPERSONATION_ACCESS, S as QueryHash, St as ActiveImpersonation, T as QueryStatusCallback, Tt as REFUSAL_RECHECK_MIN_MS, U as SyncHealthConfig, Ut as SESSION_POLL_MS, V as StoreType, Vt as ImpersonationTimers, W as SyncHealthStatus, Wt as TokenClaims, X as WebPushDevice, Xt as ChannelHandle, Y as WebPushConfig, Yt as ChannelAcceptRule, Z as WebPushError, Zt as ChannelMessage, _ as PreloadOptions, _t as PushPayload, a as EventSubscriptionOptions, an as PeerRef, at as WebPushSyncOptions, b as QueryConfig, bt as WebPushClientMessage, c as LocalWorkers, cn as unusedArgs, ct as WebPushUnsupportedReason, d as MutationCallback, dt as BridgeSignOutMessage, en as ChannelState, et as WebPushMessage, f as MutationEvent, ft as BridgeTokenMessage, g as PinoTransmit, gt as PushOp, h as PhaseStat, ht as PushNotificationAction, i as EdgeDelta, in as ChannelsConfig, it as WebPushSupport, j as RecordVersionDiff, jt as AuthEventTypes, k as ReconnectConfig, kt as AuthEventSystem, l as MATERIALIZATION_SAMPLE_WINDOW, ln as LogTap, lt as WebPushUpdateOptions, m as PersistenceClient, mt as PushNotification, n as ConnectionState, nn as ChannelTransport, nt as WebPushModule, o as InlineRow, on as TransportHooks, ot as WebPushSyncStatus, p as MutationEventType, pt as PUSH_PAYLOAD_VERSION, q as PUSH_ENDPOINT_KEY, qt as renewDelayMs, r as DebounceOptions, rn as ChannelTransportFactory, rt as WebPushSubscribeOptions, s as Level, sn as matchesWhere, st as WebPushUnsubscribeOptions, t as ChannelQuery, tn as ChannelStatus, tt as WebPushMessageInput, u as MembershipOutcome, un as Logger$1, ut as detectWebPushSupport, v as PreloadRefresh, vt as PushPayloadKind, w as QueryStatus, wt as ImpersonationCandidate, x as QueryConfigRecord, xt as isPushPayload, y as QueryAuthorityCallback, yt as PushUrgency, z as StorageHealth, zt as ImpersonationInfo } from "./types.js";
|
|
2
|
+
import { BackendNames, BackendRoutes, BucketNames, ChannelPeer, ChannelTableNames, FinalQuery, GetTable, QueryBuilder, QueryOptions, QueryPlan, RecordId, RoutePayload, SchemaStructure, TableModel, TableNames } from "@spooky-sync/query-builder";
|
|
2
3
|
import * as surrealdb0 from "surrealdb";
|
|
3
|
-
import { Duration, RecordId
|
|
4
|
-
import { AccessDefinition, BackendNames, BackendRoutes, BucketNames, ColumnSchema, GetTable, QueryBuilder, QueryOptions, RoutePayload, SchemaStructure, TableModel, TableNames, TypeNameToTypeMap } from "@spooky-sync/query-builder";
|
|
4
|
+
import { Duration, RecordId as RecordId$1, Surreal } from "surrealdb";
|
|
5
5
|
import { Logger } from "pino";
|
|
6
|
+
import { decode, encode, isBlurhashValid } from "blurhash";
|
|
6
7
|
import { LoroDoc } from "loro-crdt";
|
|
7
8
|
|
|
8
|
-
//#region src/services/
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
9
|
+
//#region src/services/tabs/protocol.d.ts
|
|
10
|
+
|
|
11
|
+
type TabId = string;
|
|
12
|
+
type TabRole$1 = 'solo' | 'leader' | 'follower';
|
|
13
|
+
/** Broker pings every tab at this cadence. */
|
|
14
|
+
|
|
15
|
+
/** Matches `CacheIngestTuple` (modules/cache): exactly what `ingestMany`
|
|
16
|
+
* consumes, so relayed batches feed follower circuits without reshaping. */
|
|
17
|
+
interface IngestTuple {
|
|
18
|
+
table: string;
|
|
19
|
+
op: 'CREATE' | 'UPDATE' | 'DELETE';
|
|
20
|
+
id: string;
|
|
21
|
+
record: Record<string, unknown>;
|
|
22
|
+
}
|
|
23
|
+
type FollowerToLeaderMessage = {
|
|
24
|
+
type: 'sync-hello';
|
|
25
|
+
tabId: TabId;
|
|
26
|
+
}
|
|
27
|
+
/** The follower committed an outbox row (through the shared store) and the
|
|
28
|
+
* leader should drain it. Idempotent; a new leader's loadFromDatabase is
|
|
29
|
+
* the backstop for a notify lost in a failover window. */ | {
|
|
30
|
+
type: 'mutation-enqueued';
|
|
31
|
+
mutationId: string;
|
|
32
|
+
} | {
|
|
33
|
+
type: 'request-poll';
|
|
34
|
+
}
|
|
35
|
+
/** An optimistic write this follower committed to the SHARED store and
|
|
36
|
+
* ingested into its own circuit. The leader ingests it (no DB write, the
|
|
37
|
+
* row is already there) and fans it out to every OTHER follower as
|
|
38
|
+
* `ingest-relay`, so a follower's write lands in every tab in one hop
|
|
39
|
+
* instead of after the server round-trip. */ | {
|
|
40
|
+
type: 'ingest';
|
|
41
|
+
tuples: IngestTuple[];
|
|
24
42
|
};
|
|
25
|
-
type
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
readonly extract: (results: unknown[]) => T;
|
|
43
|
+
type LeaderToFollowerMessage = {
|
|
44
|
+
type: 'db-ready';
|
|
45
|
+
leadershipId: number;
|
|
46
|
+
bucketId: string;
|
|
47
|
+
storageHealth: StorageHealth;
|
|
31
48
|
}
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
protected abstract eventType: typeof DatabaseEventTypes.LocalQuery | typeof DatabaseEventTypes.RemoteQuery;
|
|
39
|
-
constructor(client: Surreal$1, logger: Logger$1, events: DatabaseEventSystem);
|
|
40
|
-
abstract connect(): Promise<void>;
|
|
41
|
-
getClient(): Surreal$1;
|
|
42
|
-
getEvents(): DatabaseEventSystem;
|
|
43
|
-
tx(): Promise<SurrealTransaction>;
|
|
44
|
-
private queryQueue;
|
|
45
|
-
/**
|
|
46
|
-
* Execute a query with serialized execution to prevent WASM transaction issues.
|
|
47
|
-
*/
|
|
48
|
-
query<T extends unknown[]>(query: string, vars?: Record<string, unknown>): Promise<T>;
|
|
49
|
-
execute<T>(query: SealedQuery<T>, vars?: Record<string, unknown>): Promise<T>;
|
|
50
|
-
close(): Promise<void>;
|
|
49
|
+
/** Every ingest the leader's CacheModule committed, so follower circuits
|
|
50
|
+
* stay live without their own fetch. seq detects gaps. */ | {
|
|
51
|
+
type: 'ingest-relay';
|
|
52
|
+
tuples: IngestTuple[];
|
|
53
|
+
leadershipId: number;
|
|
54
|
+
seq: number;
|
|
51
55
|
}
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
56
|
+
/** A `_00_list_ref` LIVE event, relayed verbatim. Each follower resolves the
|
|
57
|
+
* queryId against its own DataModule and ignores foreign queries. */ | {
|
|
58
|
+
type: 'list-ref-change';
|
|
59
|
+
action: 'CREATE' | 'UPDATE' | 'DELETE';
|
|
60
|
+
queryId: string;
|
|
61
|
+
recordId: string;
|
|
62
|
+
version: number;
|
|
63
|
+
parent: boolean;
|
|
64
|
+
}
|
|
65
|
+
/** The leader's drain rolled back a mutation owned by this tab. */ | {
|
|
66
|
+
type: 'mutation-rolled-back';
|
|
67
|
+
mutationId: string;
|
|
68
|
+
recordId: string;
|
|
69
|
+
eventType: 'create' | 'update' | 'delete';
|
|
70
|
+
error: string;
|
|
71
|
+
}
|
|
72
|
+
/** The leader's drain pushed a mutation and deleted its outbox row from the
|
|
73
|
+
* SHARED store. Every follower keeps the row in its overlay until its
|
|
74
|
+
* `_00_list_ref` membership arrives. */ | {
|
|
75
|
+
type: 'mutation-settled';
|
|
76
|
+
mutationId: string;
|
|
77
|
+
recordId: string;
|
|
78
|
+
eventType: 'create' | 'update' | 'delete';
|
|
79
|
+
}
|
|
80
|
+
/** The leader's LIVE saw edges of these queries change; followers re-read
|
|
81
|
+
* membership for the ones they hold. */ | {
|
|
82
|
+
type: 'membership-dirty';
|
|
83
|
+
hashes: string[];
|
|
73
84
|
}
|
|
74
|
-
/**
|
|
75
|
-
|
|
76
|
-
|
|
85
|
+
/** The failed-writes tray changed size on the shared store. */ | {
|
|
86
|
+
type: 'failed-mutations-changed';
|
|
87
|
+
count: number;
|
|
88
|
+
};
|
|
77
89
|
//#endregion
|
|
78
|
-
//#region src/services/database/
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
90
|
+
//#region src/services/database/connection-supervisor.d.ts
|
|
91
|
+
/**
|
|
92
|
+
* Keeps the remote WebSocket alive for the whole life of the page.
|
|
93
|
+
*
|
|
94
|
+
* The SurrealDB SDK reconnects on its own after a socket `close`, but that
|
|
95
|
+
* covers only one of three ways the connection dies:
|
|
96
|
+
*
|
|
97
|
+
* 1. **Socket closes, SDK recovers.** Handled entirely by the SDK. This
|
|
98
|
+
* supervisor only observes it (to report `reconnecting` upward).
|
|
99
|
+
* 2. **Socket closes, SDK gives up.** With `attempts: -1` this shouldn't happen
|
|
100
|
+
* from exhaustion — but the SDK also terminates the engine permanently when
|
|
101
|
+
* its post-reconnect handshake throws (it re-runs `version()`, `use()`,
|
|
102
|
+
* `authenticate()` on every reconnect and closes the engine on any error).
|
|
103
|
+
* One transient hiccup there would otherwise kill the page's connection for
|
|
104
|
+
* good. The revive loop re-opens from scratch.
|
|
105
|
+
* 3. **Socket never closes at all.** A half-open connection: the peer is gone
|
|
106
|
+
* (NAT timeout, wifi switch, laptop sleep) but no FIN ever arrives, so
|
|
107
|
+
* `readyState` stays OPEN and the SDK's own 30s ping — fire-and-forget, no
|
|
108
|
+
* response deadline — never notices. Nothing ever fires a `close` event, so
|
|
109
|
+
* nothing ever triggers a reconnect. The heartbeat detects this and forces
|
|
110
|
+
* the teardown that case 2's loop then repairs.
|
|
111
|
+
*
|
|
112
|
+
* Plus wake triggers: coming back `online` or un-hiding the tab probes
|
|
113
|
+
* immediately rather than waiting out a backoff that was scheduled while the
|
|
114
|
+
* network was known-down.
|
|
115
|
+
*/
|
|
116
|
+
declare class ConnectionSupervisor {
|
|
117
|
+
private readonly remote;
|
|
118
|
+
private readonly logger;
|
|
119
|
+
private readonly config;
|
|
120
|
+
private state;
|
|
121
|
+
private subscribers;
|
|
122
|
+
private started;
|
|
123
|
+
private disposed;
|
|
124
|
+
private heartbeatTimer;
|
|
125
|
+
private heartbeatInFlight;
|
|
126
|
+
/** Consecutive failed probes. See {@link FAILURES_BEFORE_TEARDOWN}. */
|
|
127
|
+
private heartbeatFailures;
|
|
128
|
+
private reviveTimer;
|
|
129
|
+
private reviveAttempts;
|
|
130
|
+
/** Timestamp of the last wake-triggered probe, for rate limiting. */
|
|
131
|
+
private lastWakeProbeAt;
|
|
132
|
+
private reviving;
|
|
133
|
+
/**
|
|
134
|
+
* Set while the browser reports itself offline. Retrying a socket against a
|
|
135
|
+
* down interface only burns backoff, so the loop parks until `online` fires.
|
|
136
|
+
*/
|
|
137
|
+
private suspended;
|
|
138
|
+
private teardown;
|
|
139
|
+
private static readonly REVIVE_BASE_MS;
|
|
140
|
+
/**
|
|
141
|
+
* How many consecutive heartbeat failures it takes to tear the socket down.
|
|
142
|
+
*
|
|
143
|
+
* The probe rides the same serialized queue as every other RPC (deliberately
|
|
144
|
+
* — see {@link beat}), which means it cannot distinguish a WEDGED queue from
|
|
145
|
+
* a merely BUSY one. A single slow window (a large sync burst, one heavy
|
|
146
|
+
* app query) used to be enough to force-close a perfectly healthy socket,
|
|
147
|
+
* and the resulting reconnect re-registered every active query about a
|
|
148
|
+
* second later. That self-inflicted teardown manufactured the very reconnect
|
|
149
|
+
* storms this class exists to survive. A genuinely dead socket still fails
|
|
150
|
+
* every probe, so it is torn down one interval later than before.
|
|
151
|
+
*/
|
|
152
|
+
private static readonly FAILURES_BEFORE_TEARDOWN;
|
|
153
|
+
/** Retry delay after an inconclusive (first) heartbeat failure. */
|
|
154
|
+
private static readonly HEARTBEAT_RETRY_MS;
|
|
155
|
+
/** Floor between probes triggered by wake events (tab focus, pageshow). */
|
|
156
|
+
private static readonly WAKE_PROBE_MIN_INTERVAL_MS;
|
|
157
|
+
constructor(remote: RemoteDatabaseService, logger: Logger$1, config?: Required<ReconnectConfig>);
|
|
158
|
+
/** Latest observed transport state. */
|
|
159
|
+
get connection(): ConnectionState;
|
|
160
|
+
/**
|
|
161
|
+
* Observe transport state. Fires immediately with the current value and again
|
|
162
|
+
* on every change. Returns an unsubscribe.
|
|
163
|
+
*/
|
|
164
|
+
subscribe(cb: (state: ConnectionState) => void): () => void;
|
|
165
|
+
/**
|
|
166
|
+
* Begin supervising. Call once, after the initial {@link
|
|
167
|
+
* RemoteDatabaseService.connect}. Idempotent.
|
|
168
|
+
*/
|
|
169
|
+
start(): void;
|
|
170
|
+
/** Stop all timers and listeners. Safe to call more than once. */
|
|
171
|
+
dispose(): void;
|
|
172
|
+
private setState;
|
|
173
|
+
private clearReviveTimer;
|
|
174
|
+
/**
|
|
175
|
+
* Queue the next `connect()` attempt on exponential backoff, capped at
|
|
176
|
+
* `superviseRetryDelayMaxMs`. Never gives up — the page is expected to
|
|
177
|
+
* outlive any outage.
|
|
178
|
+
*/
|
|
179
|
+
private scheduleRevive;
|
|
180
|
+
private revive;
|
|
181
|
+
private stopHeartbeat;
|
|
182
|
+
private startHeartbeat;
|
|
183
|
+
/**
|
|
184
|
+
* Probe the server end-to-end. Deliberately goes through
|
|
185
|
+
* `remote.query` — the same serialized queue every other remote call uses —
|
|
186
|
+
* so a queue wedged behind a stuck RPC also fails the heartbeat instead of
|
|
187
|
+
* being invisible to it.
|
|
188
|
+
*/
|
|
189
|
+
private beat;
|
|
190
|
+
/**
|
|
191
|
+
* A restored network or an un-hidden tab is the strongest available hint that
|
|
192
|
+
* a reconnect will now succeed, so probe immediately instead of waiting out a
|
|
193
|
+
* backoff scheduled under worse conditions.
|
|
194
|
+
*/
|
|
195
|
+
private installWakeTriggers;
|
|
196
|
+
/**
|
|
197
|
+
* Reset the backoff and act on whichever problem is present: reconnect if the
|
|
198
|
+
* socket is gone, otherwise probe it (it may be half-open — which is exactly
|
|
199
|
+
* what a sleep/wake cycle produces).
|
|
200
|
+
*/
|
|
201
|
+
private wake;
|
|
89
202
|
}
|
|
90
203
|
//#endregion
|
|
91
|
-
//#region src/
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
}
|
|
104
|
-
type HeartbeatEvent = {
|
|
105
|
-
type: 'heartbeat';
|
|
106
|
-
payload: {
|
|
107
|
-
hash: string;
|
|
108
|
-
};
|
|
109
|
-
};
|
|
110
|
-
type CleanupEvent = {
|
|
111
|
-
type: 'cleanup';
|
|
112
|
-
payload: {
|
|
113
|
-
hash: string;
|
|
114
|
-
};
|
|
115
|
-
};
|
|
116
|
-
type DownEvent = RegisterEvent | SyncEvent | HeartbeatEvent | CleanupEvent;
|
|
204
|
+
//#region src/services/database/local-migrator.d.ts
|
|
205
|
+
declare class LocalMigrator {
|
|
206
|
+
private localDb;
|
|
207
|
+
private logger;
|
|
208
|
+
constructor(localDb: LocalStore, logger: Logger$1);
|
|
209
|
+
provision(schemaSurql: string): Promise<void>;
|
|
210
|
+
private readKeptRows;
|
|
211
|
+
private restoreKeptRows;
|
|
212
|
+
private isSchemaUpToDate;
|
|
213
|
+
private recreateDatabase;
|
|
214
|
+
private splitStatements;
|
|
215
|
+
private createHashRecord;
|
|
216
|
+
}
|
|
117
217
|
//#endregion
|
|
118
218
|
//#region src/services/stream-processor/wasm-types.d.ts
|
|
119
219
|
interface WasmStreamUpdate {
|
|
@@ -146,6 +246,14 @@ interface StreamUpdate {
|
|
|
146
246
|
queryHash: string;
|
|
147
247
|
localArray: RecordVersionArray;
|
|
148
248
|
op?: 'CREATE' | 'UPDATE' | 'DELETE';
|
|
249
|
+
/**
|
|
250
|
+
* Client-internal: not from the circuit. A membership-only change that
|
|
251
|
+
* needed no fetch is re-materialized through this same path so it cannot
|
|
252
|
+
* race a real update (DataModule.scheduleRematerialize). Carries the last
|
|
253
|
+
* known `localArray`; consumers that describe an INGEST (persist, metrics,
|
|
254
|
+
* devtools events) skip it.
|
|
255
|
+
*/
|
|
256
|
+
synthetic?: boolean;
|
|
149
257
|
/**
|
|
150
258
|
* End-to-end ingest latency for the WASM call that produced this update,
|
|
151
259
|
* in milliseconds. Populated by StreamProcessorService.ingest. Undefined
|
|
@@ -176,10 +284,38 @@ type StreamProcessorEvents = {
|
|
|
176
284
|
interface StreamUpdateReceiver {
|
|
177
285
|
onStreamUpdate(update: StreamUpdate): void;
|
|
178
286
|
}
|
|
287
|
+
/** One row change in the shape `ingestMany` consumes. */
|
|
288
|
+
interface IngestRecord {
|
|
289
|
+
table: string;
|
|
290
|
+
/** `MERGE` overlays the given fields on the stored row (projection widening). */
|
|
291
|
+
op: 'CREATE' | 'UPDATE' | 'DELETE' | 'MERGE';
|
|
292
|
+
id: string;
|
|
293
|
+
record: any;
|
|
294
|
+
}
|
|
295
|
+
/**
|
|
296
|
+
* What the boot-time prime needs from the client: which tables to walk, how
|
|
297
|
+
* to recognise a snapshot written under a different schema, and which rows'
|
|
298
|
+
* local `_00_rv` must not be reported as the server's.
|
|
299
|
+
*/
|
|
300
|
+
interface CircuitPrimeContext {
|
|
301
|
+
tables: string[];
|
|
302
|
+
schemaHash: string;
|
|
303
|
+
/** Encoded ids with an unsettled local mutation (their `_00_rv` was bumped
|
|
304
|
+
* locally and may exceed the server's next version). */
|
|
305
|
+
pendingIds: Set<string>;
|
|
306
|
+
/** Each table's client column set (`columnFingerprints`). An engine that
|
|
307
|
+
* keeps bodies across schema changes resets the versions of a table whose
|
|
308
|
+
* set changed before they are read, so its rows are fetched again whole. */
|
|
309
|
+
columnFingerprints?: Record<string, string>;
|
|
310
|
+
/** Receives every `(id, rv)` the prime put into the circuit, per table, so
|
|
311
|
+
* the sync layer can skip re-downloading bodies it already has. */
|
|
312
|
+
onVersions?: (table: string, entries: [string, number][]) => void;
|
|
313
|
+
}
|
|
314
|
+
/** Storage key of the circuit snapshot inside the local store. */
|
|
315
|
+
|
|
179
316
|
declare class StreamProcessorService {
|
|
180
317
|
events: EventSystem<StreamProcessorEvents>;
|
|
181
318
|
private db;
|
|
182
|
-
private persistenceClient;
|
|
183
319
|
private logger;
|
|
184
320
|
private processor;
|
|
185
321
|
private isInitialized;
|
|
@@ -187,7 +323,21 @@ declare class StreamProcessorService {
|
|
|
187
323
|
private batching;
|
|
188
324
|
private batchBuffer;
|
|
189
325
|
private sessionAuth;
|
|
190
|
-
|
|
326
|
+
private stateGeneration;
|
|
327
|
+
private persistState;
|
|
328
|
+
private persistCircuit;
|
|
329
|
+
private checkpointMs;
|
|
330
|
+
private checkpointTimer;
|
|
331
|
+
private snapshotDirty;
|
|
332
|
+
private dirtyRows;
|
|
333
|
+
private hideHandler;
|
|
334
|
+
private checkpointInFlight;
|
|
335
|
+
private projection;
|
|
336
|
+
private primed;
|
|
337
|
+
private schemaHash;
|
|
338
|
+
private widenQueue;
|
|
339
|
+
private widenPending;
|
|
340
|
+
constructor(events: EventSystem<StreamProcessorEvents>, db: LocalStore, logger: Logger);
|
|
191
341
|
/**
|
|
192
342
|
* Add a receiver for stream updates.
|
|
193
343
|
* Multiple receivers can be registered (DataManager, DevTools, etc.)
|
|
@@ -196,23 +346,21 @@ declare class StreamProcessorService {
|
|
|
196
346
|
private notifyUpdates;
|
|
197
347
|
private dispatchUpdates;
|
|
198
348
|
/**
|
|
199
|
-
* Ingest a batch of record changes
|
|
200
|
-
*
|
|
201
|
-
*
|
|
202
|
-
*
|
|
203
|
-
*
|
|
204
|
-
*
|
|
349
|
+
* Ingest a batch of record changes, firing one coalesced `StreamUpdate` per
|
|
350
|
+
* affected query once every record has been ingested. Use this whenever
|
|
351
|
+
* multiple records land at once (sync fetching N rows, the boot prime).
|
|
352
|
+
*
|
|
353
|
+
* The batch is fed to the wasm side in chunks of {@link INGEST_CHUNK}: one
|
|
354
|
+
* circuit step per chunk (a step walks every registered view, so per-record
|
|
355
|
+
* ingest paid that fixed cost N times), but never the whole batch at once,
|
|
356
|
+
* because the wasm side has to hold every parsed row of a call at the same
|
|
357
|
+
* time and wasm32 dlmalloc never returns that peak.
|
|
205
358
|
*
|
|
206
|
-
*
|
|
207
|
-
*
|
|
208
|
-
*
|
|
359
|
+
* Returns the records that were ingested. A chunk that fails is reported
|
|
360
|
+
* and skipped, not retried (a retry would double-apply whatever the failed
|
|
361
|
+
* step already committed), and the remaining chunks still run.
|
|
209
362
|
*/
|
|
210
|
-
ingestMany(records:
|
|
211
|
-
table: string;
|
|
212
|
-
op: 'CREATE' | 'UPDATE' | 'DELETE';
|
|
213
|
-
id: string;
|
|
214
|
-
record: any;
|
|
215
|
-
}>): void;
|
|
363
|
+
ingestMany(records: IngestRecord[]): IngestRecord[];
|
|
216
364
|
/**
|
|
217
365
|
* Open a coalescing window. While open, the per-record stream updates
|
|
218
366
|
* emitted by `ingest` are buffered (one entry per queryHash) instead of
|
|
@@ -234,7 +382,87 @@ declare class StreamProcessorService {
|
|
|
234
382
|
* This must be called before using other methods.
|
|
235
383
|
*/
|
|
236
384
|
init(): Promise<void>;
|
|
237
|
-
|
|
385
|
+
/**
|
|
386
|
+
* Drop the current WASM processor and start a fresh, empty circuit. Used on
|
|
387
|
+
* local-bucket switches: the old circuit holds the previous user's rows AND
|
|
388
|
+
* views registered with the previous `$auth` context, so neither may survive.
|
|
389
|
+
* Deliberately loads nothing: the snapshot in the store being swapped away
|
|
390
|
+
* from belongs to the previous bucket; the caller primes the new bucket's
|
|
391
|
+
* circuit (`primeFromLocal`) once its store is open, and the DataModule
|
|
392
|
+
* rebind re-registers every live view against this fresh processor. Caller
|
|
393
|
+
* must re-seed `setPermissions` afterwards (a fresh circuit default-denies
|
|
394
|
+
* every table).
|
|
395
|
+
*/
|
|
396
|
+
reset(): Promise<void>;
|
|
397
|
+
/**
|
|
398
|
+
* Release the wasm circuit and stop checkpointing. Call when the client is
|
|
399
|
+
* torn down; a recreated client (provider remount, HMR) would otherwise stack
|
|
400
|
+
* one full circuit per instance.
|
|
401
|
+
*/
|
|
402
|
+
dispose(): void;
|
|
403
|
+
/**
|
|
404
|
+
* Explicitly run the wasm-bindgen destructor. Guarded: stale wasm builds may
|
|
405
|
+
* not expose `free`, and a double free must not take the app down.
|
|
406
|
+
*/
|
|
407
|
+
private freeProcessor;
|
|
408
|
+
/** Toggle circuit-state persistence (shared-tabs follower/leader role). */
|
|
409
|
+
setPersistenceEnabled(enabled: boolean): void;
|
|
410
|
+
/**
|
|
411
|
+
* Snapshot persistence (`persistCircuit`). When on, the circuit's store is
|
|
412
|
+
* written to the local store on a checkpoint interval and when the page
|
|
413
|
+
* goes hidden, and restored by {@link primeFromLocal} on the next boot.
|
|
414
|
+
*/
|
|
415
|
+
configureCircuitPersistence(enabled: boolean, checkpointMs?: number): void;
|
|
416
|
+
/**
|
|
417
|
+
* Field projection (`circuitProjection`, default on). Takes effect on the
|
|
418
|
+
* next processor (`init`/`reset`) and on rows written after that.
|
|
419
|
+
*/
|
|
420
|
+
configureProjection(enabled: boolean): void;
|
|
421
|
+
private applyProjection;
|
|
422
|
+
/** Resolves once the boot-time prime has finished (or was skipped). */
|
|
423
|
+
whenPrimed(): Promise<void>;
|
|
424
|
+
/**
|
|
425
|
+
* Fill the circuit from the LOCAL store, in the background.
|
|
426
|
+
*
|
|
427
|
+
* With a usable snapshot: install it under whatever views have registered
|
|
428
|
+
* meanwhile (`load_store_state` re-primes them), then `reconcile` each table
|
|
429
|
+
* against the store's `(id, rv)` list so rows deleted since the checkpoint
|
|
430
|
+
* are stepped out and only rows added or changed since are read back and
|
|
431
|
+
* ingested. Without one: read every row and ingest it, chunked.
|
|
432
|
+
*
|
|
433
|
+
* Either way the circuit ends up equal to the local store without touching
|
|
434
|
+
* the network, so the first sync diff is a real delta rather than "fetch
|
|
435
|
+
* everything". The returned promise never rejects; `whenPrimed` gates on it.
|
|
436
|
+
*/
|
|
437
|
+
primeFromLocal(ctx: CircuitPrimeContext): Promise<void>;
|
|
438
|
+
private runPrime;
|
|
439
|
+
/** Publish wasm updates produced outside an ingest (restore, reconcile). */
|
|
440
|
+
private dispatchWasmUpdates;
|
|
441
|
+
/**
|
|
442
|
+
* Record that the circuit changed by `rows` rows. Cheap; the snapshot is
|
|
443
|
+
* deferred to the checkpoint timer and skipped entirely when `persistCircuit`
|
|
444
|
+
* is off.
|
|
445
|
+
*/
|
|
446
|
+
private markSnapshotDirty;
|
|
447
|
+
private startCheckpoints;
|
|
448
|
+
/** Stop checkpointing and drop the visibility listeners. */
|
|
449
|
+
stopCheckpoints(): void;
|
|
450
|
+
/**
|
|
451
|
+
* Write the circuit's store to the local store as a snapshot. Compacts the
|
|
452
|
+
* row arena first when dead bytes outweigh live ones. Serialised: a second
|
|
453
|
+
* call while one is in flight joins it. No-op unless persistence is on, this
|
|
454
|
+
* tab owns the store, and the engine can hold a snapshot.
|
|
455
|
+
*/
|
|
456
|
+
checkpoint(reason?: string): Promise<void>;
|
|
457
|
+
private runCheckpoint;
|
|
458
|
+
/**
|
|
459
|
+
* Projection widening: a newly registered view evaluates fields that rows
|
|
460
|
+
* already in the circuit were stored without. Merge just those fields in,
|
|
461
|
+
* table by table, from the local store. The view registered against what
|
|
462
|
+
* was present and converges as the merges step through.
|
|
463
|
+
*/
|
|
464
|
+
private scheduleWiden;
|
|
465
|
+
private runWiden;
|
|
238
466
|
/**
|
|
239
467
|
* Seed per-table `select` permission predicates ({ [table]: whereText }).
|
|
240
468
|
* Must run after the processor exists and before any `register_view`, else
|
|
@@ -252,13 +480,12 @@ declare class StreamProcessorService {
|
|
|
252
480
|
* "requires $auth but registration params lack it".
|
|
253
481
|
*/
|
|
254
482
|
setSessionAuth(authId: string | null, access: string | null): void;
|
|
255
|
-
saveState(): Promise<void>;
|
|
256
483
|
/**
|
|
257
484
|
* Ingest a record change into the processor.
|
|
258
485
|
* Emits 'stream_update' event if materialized views are affected.
|
|
259
486
|
* @param isOptimistic true = local mutation (increment versions), false = remote sync (keep versions)
|
|
260
487
|
*/
|
|
261
|
-
ingest(table: string, op: '
|
|
488
|
+
ingest(table: string, op: IngestRecord['op'], id: string, record: any): WasmStreamUpdate[];
|
|
262
489
|
/**
|
|
263
490
|
* Register a new query plan.
|
|
264
491
|
* Emits 'stream_update' with the initial result.
|
|
@@ -271,728 +498,240 @@ declare class StreamProcessorService {
|
|
|
271
498
|
private normalizeValue;
|
|
272
499
|
}
|
|
273
500
|
//#endregion
|
|
274
|
-
//#region src/
|
|
275
|
-
|
|
276
|
-
id: RecordId<string>;
|
|
277
|
-
};
|
|
278
|
-
interface QueryConfig$1 {
|
|
279
|
-
queryHash: string;
|
|
280
|
-
surql: string;
|
|
281
|
-
params: Record<string, any>;
|
|
282
|
-
ttl: QueryTimeToLive | Duration;
|
|
283
|
-
lastActiveAt: Date;
|
|
284
|
-
}
|
|
285
|
-
interface CacheRecord {
|
|
286
|
-
table: string;
|
|
287
|
-
op: 'CREATE' | 'UPDATE' | 'DELETE';
|
|
288
|
-
record: RecordWithId;
|
|
289
|
-
version: number;
|
|
290
|
-
}
|
|
291
|
-
//#endregion
|
|
292
|
-
//#region src/modules/cache/index.d.ts
|
|
501
|
+
//#region src/utils/index.d.ts
|
|
502
|
+
declare function fileToUint8Array(file: File | Blob): Promise<Uint8Array>;
|
|
293
503
|
/**
|
|
294
|
-
*
|
|
295
|
-
*
|
|
296
|
-
* Single responsibility: Handle all local storage operations and DBSP ingestion.
|
|
297
|
-
* This module acts as the bridge between data operations and persistence.
|
|
504
|
+
* Convert plain text to simple HTML paragraphs.
|
|
505
|
+
* Useful for seeding a rich-text editor (e.g. TipTap/ProseMirror) with fallback content.
|
|
298
506
|
*/
|
|
299
|
-
declare
|
|
300
|
-
private local;
|
|
301
|
-
private streamProcessor;
|
|
302
|
-
private logger;
|
|
303
|
-
private streamUpdateCallback;
|
|
304
|
-
private versionLookups;
|
|
305
|
-
constructor(local: LocalDatabaseService, streamProcessor: StreamProcessorService, streamUpdateCallback: (update: StreamUpdate) => void, logger: Logger$1);
|
|
306
|
-
/**
|
|
307
|
-
* Implements StreamUpdateReceiver interface
|
|
308
|
-
* Called directly by StreamProcessor when views change
|
|
309
|
-
*/
|
|
310
|
-
onStreamUpdate(update: StreamUpdate): void;
|
|
311
|
-
lookup(recordId: string): number;
|
|
312
|
-
/**
|
|
313
|
-
* Save a single record to local DB and ingest into DBSP
|
|
314
|
-
* Used by mutations (create/update)
|
|
315
|
-
*/
|
|
316
|
-
save(cacheRecord: CacheRecord, skipDbInsert?: boolean): Promise<void>;
|
|
317
|
-
/**
|
|
318
|
-
* Save multiple records in a batch
|
|
319
|
-
* More efficient than calling save() multiple times
|
|
320
|
-
* Used by sync operations
|
|
321
|
-
*/
|
|
322
|
-
saveBatch(records: CacheRecord[], skipDbInsert?: boolean): Promise<void>;
|
|
323
|
-
/**
|
|
324
|
-
* Delete a record from local DB and ingest deletion into DBSP
|
|
325
|
-
*/
|
|
326
|
-
delete(table: string, id: string, skipDbDelete?: boolean, recordData?: Record<string, any>): Promise<void>;
|
|
327
|
-
/**
|
|
328
|
-
* Register a query with DBSP to create a materialized view
|
|
329
|
-
* Returns the initial result array
|
|
330
|
-
*/
|
|
331
|
-
registerQuery(config: QueryConfig$1): {
|
|
332
|
-
localArray: RecordVersionArray;
|
|
333
|
-
registrationTimings?: {
|
|
334
|
-
parseMs: number;
|
|
335
|
-
planMs: number;
|
|
336
|
-
snapshotMs: number;
|
|
337
|
-
};
|
|
338
|
-
};
|
|
339
|
-
/**
|
|
340
|
-
* Unregister a query from DBSP
|
|
341
|
-
*/
|
|
342
|
-
unregisterQuery(queryHash: string): void;
|
|
343
|
-
}
|
|
344
|
-
//#endregion
|
|
345
|
-
//#region src/modules/data/index.d.ts
|
|
507
|
+
declare function textToHtml(text: string): string;
|
|
346
508
|
/**
|
|
347
|
-
*
|
|
348
|
-
*
|
|
349
|
-
* Merges the functionality of QueryManager and MutationManager.
|
|
350
|
-
* Uses CacheModule for all storage operations.
|
|
509
|
+
* Helper for retrying DB operations with exponential backoff
|
|
351
510
|
*/
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
private local;
|
|
355
|
-
private schema;
|
|
356
|
-
private streamDebounceTime;
|
|
357
|
-
private activeQueries;
|
|
358
|
-
private pendingQueries;
|
|
359
|
-
private subscriptions;
|
|
360
|
-
private statusSubscriptions;
|
|
361
|
-
private mutationCallbacks;
|
|
362
|
-
private debounceTimers;
|
|
363
|
-
private logger;
|
|
364
|
-
/**
|
|
365
|
-
* Optional observer notified whenever a query's fetch status changes.
|
|
366
|
-
* Wired by Sp00kyClient to push status changes into DevTools. Kept as a
|
|
367
|
-
* settable field (rather than a constructor arg) because DevTools is
|
|
368
|
-
* constructed after DataModule.
|
|
369
|
-
*/
|
|
370
|
-
onQueryStatusChange?: (hash: QueryHash, status: QueryStatus) => void;
|
|
371
|
-
/**
|
|
372
|
-
* Optional observer invoked when a still-subscribed query's TTL heartbeat
|
|
373
|
-
* fires (~90% of the TTL). Wired by Sp00kyClient to
|
|
374
|
-
* `Sp00kySync.heartbeatQuery`, which refreshes the remote `_00_query`
|
|
375
|
-
* row's `lastActiveAt` so an actively-watched query never expires. Settable
|
|
376
|
-
* field (not a constructor arg) because the sync engine is wired after
|
|
377
|
-
* DataModule is constructed — mirrors `onQueryStatusChange`.
|
|
378
|
-
*/
|
|
379
|
-
onHeartbeat?: (hash: QueryHash) => void;
|
|
380
|
-
/**
|
|
381
|
-
* Optional hook fired by {@link deregisterQuery} when an opt-in query (e.g. a
|
|
382
|
-
* viewport-windowed list cancelling an off-screen window) loses its last
|
|
383
|
-
* subscriber. Wired by Sp00kyClient to enqueue a `cleanup` down-event, which
|
|
384
|
-
* tears the remote `_00_query` view down (releasing its `_00_list_ref` edges)
|
|
385
|
-
* instead of leaving it for the TTL sweep. The local view + state are freed in
|
|
386
|
-
* {@link finalizeDeregister} only after that remote delete, so a fast
|
|
387
|
-
* re-subscribe (scroll back) can abort/heal the teardown — see `cleanupQuery`.
|
|
388
|
-
*/
|
|
389
|
-
onDeregister?: (hash: QueryHash) => void;
|
|
390
|
-
private sessionId;
|
|
391
|
-
private currentUserId;
|
|
392
|
-
constructor(cache: CacheModule, local: LocalDatabaseService, schema: S, logger: Logger$1, streamDebounceTime?: number);
|
|
393
|
-
init(sessionId: string): Promise<void>;
|
|
394
|
-
/**
|
|
395
|
-
* Update the session salt used in query-id hashing. Call this when the
|
|
396
|
-
* SurrealDB session changes (sign-in, sign-out, reconnect). Subsequently
|
|
397
|
-
* registered queries will get fresh, session-scoped IDs.
|
|
398
|
-
*/
|
|
399
|
-
setSessionId(sessionId: string): void;
|
|
400
|
-
/**
|
|
401
|
-
* Update the authenticated user record id. Pass `null` on sign-out.
|
|
402
|
-
* Read by `Sp00kySync.listRefTable()` so the LIVE subscription and
|
|
403
|
-
* the poll route to the same per-user `_00_list_ref_user_<id>` the
|
|
404
|
-
* SSP writes to.
|
|
405
|
-
*/
|
|
406
|
-
setCurrentUserId(userId: string | null): void;
|
|
407
|
-
/** Read-only view of the authenticated user id used for per-user
|
|
408
|
-
* `_00_list_ref` routing. Other modules consult this so they pick the
|
|
409
|
-
* same table name DataModule does. */
|
|
410
|
-
getCurrentUserId(): string | null;
|
|
411
|
-
/**
|
|
412
|
-
* Register a query and return its hash for subscriptions
|
|
413
|
-
*/
|
|
414
|
-
query<T extends TableNames<S>>(tableName: T, surqlString: string, params: Record<string, any>, ttl: QueryTimeToLive): Promise<QueryHash>;
|
|
415
|
-
/**
|
|
416
|
-
* Subscribe to query updates
|
|
417
|
-
*/
|
|
418
|
-
subscribe(queryHash: string, callback: QueryUpdateCallback, options?: {
|
|
419
|
-
immediate?: boolean;
|
|
420
|
-
}): () => void;
|
|
421
|
-
/**
|
|
422
|
-
* Subscribe to a query's fetch-status changes (idle/fetching).
|
|
423
|
-
* With `{ immediate: true }` the callback fires synchronously with the
|
|
424
|
-
* current status (defaults to `idle` if the query isn't registered yet).
|
|
425
|
-
*/
|
|
426
|
-
subscribeStatus(queryHash: string, callback: QueryStatusCallback, options?: {
|
|
427
|
-
immediate?: boolean;
|
|
428
|
-
}): () => void;
|
|
429
|
-
/**
|
|
430
|
-
* Set a query's fetch status and notify status observers (DevTools +
|
|
431
|
-
* `subscribeStatus` listeners). No-op when the status is unchanged or the
|
|
432
|
-
* query is unknown.
|
|
433
|
-
*/
|
|
434
|
-
setQueryStatus(queryHash: string, status: QueryStatus): void;
|
|
435
|
-
/**
|
|
436
|
-
* Subscribe to mutations (for sync)
|
|
437
|
-
*/
|
|
438
|
-
onMutation(callback: MutationCallback): () => void;
|
|
439
|
-
/**
|
|
440
|
-
* Handle stream updates from DBSP (via CacheModule)
|
|
441
|
-
*/
|
|
442
|
-
onStreamUpdate(update: StreamUpdate): Promise<void>;
|
|
443
|
-
private materializeRecords;
|
|
444
|
-
private processStreamUpdate;
|
|
445
|
-
/**
|
|
446
|
-
* Compute p55/p90/p99 from a rolling window of materialization samples.
|
|
447
|
-
* Returns nulls for any percentile that has no samples yet so SurrealDB
|
|
448
|
-
* `option<float>` columns stay NONE rather than 0 before the first ingest.
|
|
449
|
-
*/
|
|
450
|
-
private computeMaterializationPercentiles;
|
|
451
|
-
/** Record a per-phase timing sample (ms) on a query's rolling window. */
|
|
452
|
-
private recordPhase;
|
|
453
|
-
/** Record the remote record-fetch time (ms) for a query. Called by the sync engine. */
|
|
454
|
-
recordRemoteFetch(hash: string, ms: number): void;
|
|
455
|
-
/**
|
|
456
|
-
* Record the frontend reconcile time (ms) for a query. Called from `useQuery`
|
|
457
|
-
* via `Sp00kyClient.reportFrontendTiming` after it applies an update to its store.
|
|
458
|
-
*/
|
|
459
|
-
recordFrontendTiming(hash: string, ms: number): void;
|
|
460
|
-
/**
|
|
461
|
-
* Build the per-query processing-time breakdown surfaced to the DevTools panel
|
|
462
|
-
* and the MCP. `ssp` is the WASM-ingest wall time (from `materializationSamples`);
|
|
463
|
-
* the rest come from the per-phase rolling windows + one-shot registration timings.
|
|
464
|
-
*/
|
|
465
|
-
phaseTimings(q: QueryState): QueryTimings;
|
|
466
|
-
/**
|
|
467
|
-
* Get query state (for sync and devtools)
|
|
468
|
-
*/
|
|
469
|
-
getQueryByHash(hash: string): QueryState | undefined;
|
|
470
|
-
/**
|
|
471
|
-
* Cold-query guard for instant-hydrate: true when the query exists, hasn't been
|
|
472
|
-
* hydrated, and has NOT yet fetched its server result (`remoteArray` empty).
|
|
473
|
-
* We gate on `remoteArray`, not local `records`: a windowed query is often
|
|
474
|
-
* partially pre-seeded from the circuit (e.g. the dashboard's 5-row preview),
|
|
475
|
-
* but it still hasn't loaded its own full window from the server — so it should
|
|
476
|
-
* still hydrate. A warm re-subscribe (remoteArray already populated) is skipped.
|
|
477
|
-
*/
|
|
478
|
-
isCold(hash: string): boolean;
|
|
479
|
-
/**
|
|
480
|
-
* Walk a hydrated record's fields and append any EMBEDDED child records to
|
|
481
|
-
* `batch` (recursing for nested related fields). An embedded child is a
|
|
482
|
-
* value that is itself a record — a non-null object whose `id` is a
|
|
483
|
-
* `RecordId` — or an array of such records (one-to-many vs one-to-one). A
|
|
484
|
-
* bare `RecordId` (a foreign-key reference) or any other value is skipped,
|
|
485
|
-
* so this never mistakes a FK column for an embedded body. Children are
|
|
486
|
-
* keyed by their own `record.id.table`, versioned by `_00_rv`, and cleaned
|
|
487
|
-
* to their table's real columns (which strips the alias/related fields).
|
|
488
|
-
* `seen` dedupes within the batch.
|
|
489
|
-
*/
|
|
490
|
-
private collectEmbeddedChildren;
|
|
491
|
-
/**
|
|
492
|
-
* Instant-hydrate: ingest rows fetched one-shot from the remote (the query's own
|
|
493
|
-
* surql run directly) so the query DISPLAYS immediately, while the full realtime
|
|
494
|
-
* registration proceeds in the background. Ingests with versions (`_00_rv`) so the
|
|
495
|
-
* later `syncRecords` dedup skips re-pulling unchanged bodies, and seeds
|
|
496
|
-
* `remoteArray` so windowed queries materialize the correct window (no sparse
|
|
497
|
-
* local-circuit issue). Runs at most once per query (the `hydrated` flag).
|
|
498
|
-
*/
|
|
499
|
-
applyHydration(hash: string, rows: RecordWithId[]): Promise<void>;
|
|
500
|
-
/** True while ≥1 live subscriber is watching this query (refcount guard). */
|
|
501
|
-
hasSubscribers(hash: string): boolean;
|
|
502
|
-
/**
|
|
503
|
-
* Opt-in eager teardown for a query whose LAST subscriber just left — used by
|
|
504
|
-
* viewport-windowed lists to cancel off-screen windows instead of leaving
|
|
505
|
-
* their remote views to expire on the TTL sweep. No-op while any subscriber
|
|
506
|
-
* remains (refcount). Only enqueues the remote cleanup here; the local WASM
|
|
507
|
-
* view + in-memory state are freed in {@link finalizeDeregister} after the
|
|
508
|
-
* remote delete completes, so a re-subscribe in between aborts/heals it.
|
|
509
|
-
*
|
|
510
|
-
* NOTE: most queries should NOT use this — the default keep-alive on
|
|
511
|
-
* unsubscribe avoids re-registration churn on navigation.
|
|
512
|
-
*/
|
|
513
|
-
deregisterQuery(hash: string): void;
|
|
514
|
-
/**
|
|
515
|
-
* Final local teardown after the remote `_00_query` row was deleted: free the
|
|
516
|
-
* WASM view, heartbeat timer, debounce timer, and in-memory state. Caller
|
|
517
|
-
* (`cleanupQuery`) guarantees no subscriber remains.
|
|
518
|
-
*/
|
|
519
|
-
finalizeDeregister(hash: string): void;
|
|
520
|
-
/**
|
|
521
|
-
* Get query state by id (for sync and devtools)
|
|
522
|
-
*/
|
|
523
|
-
getQueryById(id: RecordId<string>): QueryState | undefined;
|
|
524
|
-
/**
|
|
525
|
-
* Get all active queries (for devtools)
|
|
526
|
-
*/
|
|
527
|
-
getActiveQueries(): QueryState[];
|
|
528
|
-
getActiveQueryHashes(): QueryHash[];
|
|
529
|
-
updateQueryLocalArray(id: string, localArray: RecordVersionArray): Promise<void>;
|
|
530
|
-
updateQueryRemoteArray(hash: string, remoteArray: RecordVersionArray): Promise<void>;
|
|
531
|
-
/**
|
|
532
|
-
* Called after a query's initial sync completes.
|
|
533
|
-
* Ensures subscribers are notified even if no stream updates fired (e.g. empty result set).
|
|
534
|
-
*/
|
|
535
|
-
notifyQuerySynced(queryHash: string): Promise<void>;
|
|
536
|
-
run<B extends BackendNames<S>, R extends BackendRoutes<S, B>>(backend: B, path: R, data: RoutePayload<S, B, R>, options?: RunOptions): Promise<void>;
|
|
537
|
-
/**
|
|
538
|
-
* Create a new record
|
|
539
|
-
*/
|
|
540
|
-
create<T extends Record<string, unknown>>(id: string, data: T): Promise<T>;
|
|
541
|
-
/**
|
|
542
|
-
* Update an existing record
|
|
543
|
-
*/
|
|
544
|
-
update<T extends Record<string, unknown>>(table: string, id: string, data: Partial<T>, options?: UpdateOptions): Promise<T>;
|
|
545
|
-
/**
|
|
546
|
-
* Delete a record
|
|
547
|
-
*/
|
|
548
|
-
delete(table: string, id: string): Promise<void>;
|
|
549
|
-
/**
|
|
550
|
-
* Rollback a failed optimistic create by deleting the record locally
|
|
551
|
-
*/
|
|
552
|
-
rollbackCreate(recordId: RecordId, tableName: string): Promise<void>;
|
|
553
|
-
/**
|
|
554
|
-
* Rollback a failed optimistic update by restoring the previous record state
|
|
555
|
-
*/
|
|
556
|
-
rollbackUpdate(recordId: RecordId, tableName: string, beforeRecord: Record<string, unknown>): Promise<void>;
|
|
557
|
-
/**
|
|
558
|
-
* Remove a record from all active query states and notify subscribers
|
|
559
|
-
*/
|
|
560
|
-
private removeRecordFromQueries;
|
|
561
|
-
private createAndRegisterQuery;
|
|
562
|
-
private createNewQuery;
|
|
563
|
-
private calculateHash;
|
|
564
|
-
private startTTLHeartbeat;
|
|
565
|
-
private replaceRecordInQueries;
|
|
566
|
-
}
|
|
511
|
+
//#endregion
|
|
512
|
+
//#region src/modules/crdt/mirror.d.ts
|
|
567
513
|
/**
|
|
568
|
-
*
|
|
514
|
+
* The plain text a `@crdt` field shows as its column value, rendered the same
|
|
515
|
+
* way the SSP fold renders it (`packages/ssp-node/src/crdt/mirror.rs`).
|
|
569
516
|
*/
|
|
517
|
+
type CrdtKind = 'text' | 'prosemirror';
|
|
570
518
|
//#endregion
|
|
571
|
-
//#region src/modules/
|
|
519
|
+
//#region src/modules/crdt/crdt-field.d.ts
|
|
520
|
+
declare const CURSOR_COLORS: string[];
|
|
521
|
+
declare function cursorColorFromName(name: string): string;
|
|
522
|
+
/** What a field handle needs from the manager that owns its session. */
|
|
523
|
+
interface CrdtFieldHost {
|
|
524
|
+
pushPresence(state: Uint8Array): void;
|
|
525
|
+
}
|
|
572
526
|
/**
|
|
573
|
-
*
|
|
527
|
+
* An open collaborative field: the Loro document an editor binds to. Edits
|
|
528
|
+
* made on it are sent as the client's own edit-log rows; other clients' rows
|
|
529
|
+
* are imported into it as they arrive. Every open of the same field in one tab
|
|
530
|
+
* shares this document.
|
|
574
531
|
*/
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
532
|
+
declare class CrdtField {
|
|
533
|
+
readonly table: string;
|
|
534
|
+
readonly recordId: string;
|
|
535
|
+
readonly fieldName: string;
|
|
536
|
+
readonly kind: CrdtKind;
|
|
537
|
+
readonly cursorsEnabled: boolean;
|
|
538
|
+
private readonly doc;
|
|
539
|
+
private readonly host;
|
|
540
|
+
private _onCursorUpdate;
|
|
541
|
+
private pendingCursorUpdate;
|
|
542
|
+
private loaded;
|
|
543
|
+
private loadedListeners;
|
|
544
|
+
constructor(table: string, recordId: string, fieldName: string, kind: CrdtKind, cursorsEnabled: boolean, doc: LoroDoc, host: CrdtFieldHost);
|
|
545
|
+
getDoc(): LoroDoc;
|
|
546
|
+
/** Whether the document holds anything yet (local state or edits). */
|
|
547
|
+
hasContent(): boolean;
|
|
589
548
|
/**
|
|
590
|
-
*
|
|
591
|
-
*
|
|
592
|
-
*
|
|
593
|
-
|
|
594
|
-
|
|
549
|
+
* Whether the document is known: this device had it, it was handed a draft,
|
|
550
|
+
* or the server answered (with content, or that it has none yet). Until then
|
|
551
|
+
* an empty document means "not loaded", not "empty": show the column's text
|
|
552
|
+
* instead, and do not bind an editor (an editor binding an empty document
|
|
553
|
+
* creates structure that competes with the real one).
|
|
554
|
+
*/
|
|
555
|
+
isLoaded(): boolean;
|
|
556
|
+
/** Runs `cb` once the field is loaded (at once if it already is). Returns
|
|
557
|
+
* an unsubscribe. */
|
|
558
|
+
onLoaded(cb: () => void): () => void;
|
|
559
|
+
/** @internal The manager calls this when the document became known. */
|
|
560
|
+
markLoaded(): void;
|
|
561
|
+
/** Publish this session's presence (an `EphemeralStore` encoding, e.g. the
|
|
562
|
+
* editor's cursor). No-op unless the field is `@cursor`. */
|
|
563
|
+
pushCursorState(encoded: Uint8Array): void;
|
|
564
|
+
/** Called with every other session's presence blob. A blob that arrives
|
|
565
|
+
* before the editor sets this is replayed when it does. */
|
|
566
|
+
set onCursorUpdate(cb: ((data: Uint8Array) => void) | null);
|
|
567
|
+
get onCursorUpdate(): ((data: Uint8Array) => void) | null;
|
|
568
|
+
/** @internal Deliver one remote presence blob. */
|
|
569
|
+
deliverPresence(data: Uint8Array): void;
|
|
595
570
|
}
|
|
571
|
+
//#endregion
|
|
572
|
+
//#region src/modules/crdt/index.d.ts
|
|
596
573
|
/**
|
|
597
|
-
*
|
|
598
|
-
*
|
|
599
|
-
*
|
|
600
|
-
*
|
|
574
|
+
* Collaborative (`@crdt`) fields.
|
|
575
|
+
*
|
|
576
|
+
* Each open field is a Loro document. The client never sends the document,
|
|
577
|
+
* only its own edits: every batch of local edits becomes one row of the
|
|
578
|
+
* generated `<table>__crdt_log` table, written through the ordinary outbox
|
|
579
|
+
* (so it survives offline, reloads and retries), and every client receives
|
|
580
|
+
* the other rows through an ordinary query and merges them. Nobody writes the
|
|
581
|
+
* canonical state but the SSP, which folds the log into `_00_crdt_doc` and the
|
|
582
|
+
* parent field's plain text (see `packages/ssp-node/src/crdt`).
|
|
583
|
+
*
|
|
584
|
+
* A row is imported only if it passes the acceptance rule the fold applies
|
|
585
|
+
* (`./acceptance`), so this tab and the server always hold the same ops.
|
|
586
|
+
*
|
|
587
|
+
* Edits carry this tab's Loro peer id, claimed for the signed-in user in
|
|
588
|
+
* `_00_crdt_peer` before the first row is sent; the database refuses a row
|
|
589
|
+
* whose peer its author does not own. A tab picks a fresh peer per session.
|
|
590
|
+
* Offline, edits stay local (and in the local snapshot) until the claim and
|
|
591
|
+
* the outbox can go through.
|
|
601
592
|
*/
|
|
602
|
-
|
|
593
|
+
/** A followed query: stop following it, and know when the server answered. */
|
|
594
|
+
interface Watch {
|
|
595
|
+
stop: () => void;
|
|
596
|
+
/** Resolves once the server's membership for the query is known and its
|
|
597
|
+
* rows have landed locally (never rejects; may never resolve offline). */
|
|
598
|
+
settled: Promise<void>;
|
|
599
|
+
}
|
|
600
|
+
/** The runtime pieces the manager needs from the client facade. */
|
|
601
|
+
interface CrdtPorts {
|
|
602
|
+
/** Register a query on `table` filtered by `where` and follow its rows. */
|
|
603
|
+
watch(table: string, where: Record<string, unknown>, onRows: (rows: Record<string, unknown>[]) => void): Promise<Watch>;
|
|
604
|
+
/** Optimistic create through the outbox. */
|
|
605
|
+
create(id: string, data: Record<string, unknown>): Promise<unknown>;
|
|
606
|
+
}
|
|
607
|
+
declare class CrdtManager {
|
|
608
|
+
private schema;
|
|
603
609
|
private local;
|
|
604
610
|
private remote;
|
|
605
|
-
|
|
606
|
-
private
|
|
607
|
-
|
|
608
|
-
private
|
|
609
|
-
private
|
|
610
|
-
private
|
|
611
|
+
/** First edit after a quiet spell: wait this long to batch the burst. */
|
|
612
|
+
private debounceMs;
|
|
613
|
+
/** Shortest gap between two sends of one field, while edits keep coming. */
|
|
614
|
+
private sendIntervalMs;
|
|
615
|
+
private sessions;
|
|
616
|
+
private opening;
|
|
617
|
+
/** Closes still saving their field's local state, by session key. */
|
|
618
|
+
private saving;
|
|
619
|
+
private ports;
|
|
611
620
|
private logger;
|
|
612
|
-
private
|
|
613
|
-
/**
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
get liveRetryCount(): number;
|
|
633
|
-
get isSyncing(): boolean;
|
|
634
|
-
get pendingMutationCount(): number;
|
|
635
|
-
subscribeToPendingMutations(cb: (count: number) => void): () => void;
|
|
636
|
-
private readonly degradeAfterFailures;
|
|
637
|
-
private consecutiveSyncFailures;
|
|
638
|
-
private syncHealthStatus;
|
|
639
|
-
private lastSyncErrorKind;
|
|
640
|
-
private lastSyncErrorMessage;
|
|
641
|
-
private selfHealTimer;
|
|
642
|
-
private selfHealAttempts;
|
|
643
|
-
private static readonly SELF_HEAL_BASE_MS;
|
|
644
|
-
private static readonly SELF_HEAL_MAX_MS;
|
|
645
|
-
/** Current sync-health snapshot. */
|
|
646
|
-
get syncHealth(): SyncHealth;
|
|
647
|
-
/**
|
|
648
|
-
* Observe sync health. The callback fires immediately with the current
|
|
649
|
-
* status and again on every healthy↔degraded transition. Returns an
|
|
650
|
-
* unsubscribe. Mirrors {@link subscribeToPendingMutations}.
|
|
651
|
-
*/
|
|
652
|
-
subscribeToSyncHealth(cb: (health: SyncHealth) => void): () => void;
|
|
653
|
-
private emitSyncHealth;
|
|
654
|
-
/**
|
|
655
|
-
* Fed by the scheduler once per drained sync round. Individual failures are
|
|
656
|
-
* absorbed by the queue's retry; only a run of `degradeAfterFailures`
|
|
657
|
-
* consecutive failures flips the status to `degraded`, and the next clean
|
|
658
|
-
* round flips it back. No-op when reporting is disabled (`degradeAfterFailures`
|
|
659
|
-
* is 0).
|
|
660
|
-
*/
|
|
661
|
-
private recordSyncOutcome;
|
|
662
|
-
/**
|
|
663
|
-
* Begin self-heal retries (no-op if already running). Started on the
|
|
664
|
-
* healthy→degraded transition; {@link recordSyncOutcome} stops it on recovery.
|
|
665
|
-
*/
|
|
666
|
-
private startSelfHeal;
|
|
667
|
-
private scheduleSelfHeal;
|
|
668
|
-
private stopSelfHeal;
|
|
669
|
-
constructor(local: LocalDatabaseService, remote: RemoteDatabaseService, cache: CacheModule, dataModule: DataModule<S>, schema: S, logger: Logger$1, options?: Sp00kySyncOptions);
|
|
670
|
-
/**
|
|
671
|
-
* Initializes the synchronization system.
|
|
672
|
-
* Starts the scheduler and initiates the initial sync cycles.
|
|
673
|
-
* @throws Error if already initialized.
|
|
674
|
-
*/
|
|
675
|
-
init(): Promise<void>;
|
|
676
|
-
/**
|
|
677
|
-
* Push the authenticated user's record id from the parent client's
|
|
678
|
-
* auth subscription. Tears down the existing `_00_list_ref` LIVE (if
|
|
679
|
-
* any) and re-registers it under the new user's dedicated table so
|
|
680
|
-
* SurrealDB binds the permission rule under the post-flip auth
|
|
681
|
-
* context. Pass `null` on sign-out.
|
|
682
|
-
*
|
|
683
|
-
* The dedicated `_00_list_ref_user_<id>` table is created lazily by
|
|
684
|
-
* the SSP when the first query registration arrives, which may be
|
|
685
|
-
* concurrent with this call. We retry the LIVE registration with a
|
|
686
|
-
* short backoff so a "table not found" race resolves without
|
|
687
|
-
* surfacing as a permanent auth-loading hang.
|
|
688
|
-
*/
|
|
689
|
-
setCurrentUserId(userId: string | null): Promise<void>;
|
|
690
|
-
private startListRefPoll;
|
|
691
|
-
private stopListRefPoll;
|
|
692
|
-
/**
|
|
693
|
-
* One poll cycle: refetch `_00_list_ref` for every active query. Returns
|
|
694
|
-
* whether ANY query's remoteArray actually changed — the scheduler uses this
|
|
695
|
-
* to drive the adaptive idle backoff.
|
|
696
|
-
*/
|
|
697
|
-
private pollListRefForActiveQueries;
|
|
698
|
-
/**
|
|
699
|
-
* Pull the upstream list_ref entries for `queryHash`, diff them
|
|
700
|
-
* against the local `remoteArray` cache, sync any added/updated rows
|
|
701
|
-
* through the SyncEngine, then persist the new remoteArray. This is
|
|
702
|
-
* the same shape `createRemoteQuery` does for its initial fetch and
|
|
703
|
-
* what `handleRemoteListRefChange` does per-LIVE-event — we reuse
|
|
704
|
-
* it on a timer as a fallback for missed LIVE notifications.
|
|
705
|
-
*/
|
|
706
|
-
private refetchListRefForQuery;
|
|
707
|
-
/**
|
|
708
|
-
* Resolve the current `_00_list_ref` table name for the active auth
|
|
709
|
-
* context. Public so the `createRemoteQuery` initial-fetch path can
|
|
710
|
-
* read from the right per-user table.
|
|
711
|
-
*
|
|
712
|
-
* Reads the user id from `DataModule` rather than the local mirror,
|
|
713
|
-
* because `DataModule.setCurrentUserId` runs synchronously from the
|
|
714
|
-
* auth callback (before any `await`), whereas `sync.setCurrentUserId`
|
|
715
|
-
* is async — the userQuery's initial fetch can fire between those
|
|
716
|
-
* two points and we need the correct table name immediately.
|
|
717
|
-
*/
|
|
718
|
-
listRefTable(): string;
|
|
719
|
-
private killRefLiveQuery;
|
|
720
|
-
private restartRefLiveQuery;
|
|
721
|
-
private subscribeToReconnect;
|
|
722
|
-
private startRefLiveQueries;
|
|
723
|
-
private handleRemoteListRefChange;
|
|
724
|
-
/**
|
|
725
|
-
* Handle a LIVE change to a SUBQUERY child edge (a `_00_list_ref` row with
|
|
726
|
-
* `parent` set) for a `.related()` query. Unlike primary rows, child rows
|
|
727
|
-
* must NOT touch the query's `localArray`/`remoteArray`/`rowCount`; we only
|
|
728
|
-
* keep the child BODY fresh in the local cache so the in-browser SSP's
|
|
729
|
-
* subquery-table dependency re-materializes the parent view.
|
|
730
|
-
*
|
|
731
|
-
* CREATE/UPDATE fetch+upsert the child body. DELETE is intentionally a
|
|
732
|
-
* no-op: a child leaving this query's set must not delete a body another
|
|
733
|
-
* query may still show (see `syncSubqueryChildren` deletion-safety note);
|
|
734
|
-
* a genuine record delete propagates via the normal delete path.
|
|
735
|
-
*/
|
|
736
|
-
private handleRemoteSubqueryChange;
|
|
737
|
-
/**
|
|
738
|
-
* Enqueues a 'down' event (from remote to local) for processing.
|
|
739
|
-
* @param event The DownEvent to enqueue.
|
|
740
|
-
*/
|
|
741
|
-
enqueueDownEvent(event: DownEvent): void;
|
|
742
|
-
private processUpEvent;
|
|
743
|
-
private handleRollback;
|
|
744
|
-
private processDownEvent;
|
|
745
|
-
/**
|
|
746
|
-
* Synchronizes a specific query by hash.
|
|
747
|
-
* Compares local and remote version arrays and fetches differences.
|
|
748
|
-
* @param hash The hash of the query to sync.
|
|
749
|
-
*/
|
|
750
|
-
syncQuery(hash: string): Promise<void>;
|
|
751
|
-
/**
|
|
752
|
-
* Run a sync for a single query while reflecting its fetch status. Marks the
|
|
753
|
-
* query `fetching` for the duration when the diff actually pulls records
|
|
754
|
-
* (added/updated), then resets to `idle` in a `finally` so a failed sync
|
|
755
|
-
* never leaves a query stuck `fetching`. Part A's notification coalescing
|
|
756
|
-
* means the single resulting UI update lands after this completes.
|
|
757
|
-
*/
|
|
758
|
-
private runSyncForQuery;
|
|
759
|
-
/**
|
|
760
|
-
* Record ids with a pending local DELETE in the outbox (`_00_pending_mutations`).
|
|
761
|
-
* Sync must not re-fetch/re-insert these — the remote delete is async, so the
|
|
762
|
-
* server's `_00_list_ref` still lists them until it's processed, and the diff
|
|
763
|
-
* would otherwise resurrect a just-deleted record.
|
|
764
|
-
*/
|
|
765
|
-
private getPendingDeleteIds;
|
|
766
|
-
/**
|
|
767
|
-
* Enqueues a list of mutations (up events) to be sent to the remote.
|
|
768
|
-
* @param mutations Array of UpEvents (create/update/delete) to enqueue.
|
|
769
|
-
*/
|
|
770
|
-
enqueueMutation(mutations: UpEvent[]): Promise<void>;
|
|
771
|
-
private registerQuery;
|
|
772
|
-
private createRemoteQuery;
|
|
773
|
-
/**
|
|
774
|
-
* Sync the BODIES of a `.related()` query's subquery child rows into the
|
|
775
|
-
* local cache, separately from the primary window array. The SSP writes
|
|
776
|
-
* each matched child as a `_00_list_ref` edge tagged `parent`/`parent_rel`;
|
|
777
|
-
* `buildSubqueryListRefSelect` pulls those `out`+`version` pairs (any
|
|
778
|
-
* nesting depth). We diff against the in-memory `subqueryRemoteArray` and
|
|
779
|
-
* fetch added/updated bodies through the SyncEngine — which `saveBatch`s
|
|
780
|
-
* them into the local DB AND the in-browser SSP, whose subquery-table
|
|
781
|
-
* dependency then re-materializes the parent view (no explicit notify).
|
|
621
|
+
private peer;
|
|
622
|
+
/** The current peer's claim: settled once the database holds it for us. */
|
|
623
|
+
private claim;
|
|
624
|
+
private claimRetry;
|
|
625
|
+
private connectionUnsubscribes;
|
|
626
|
+
constructor(schema: SchemaStructure, local: LocalStore, remote: RemoteDatabaseService, logger: Logger$1, /** First edit after a quiet spell: wait this long to batch the burst. */
|
|
627
|
+
debounceMs?: number, /** Shortest gap between two sends of one field, while edits keep coming. */
|
|
628
|
+
sendIntervalMs?: number);
|
|
629
|
+
/** Hand over the runtime ports. Called once by the client facade. */
|
|
630
|
+
attach(ports: CrdtPorts): void;
|
|
631
|
+
/**
|
|
632
|
+
* A new signed-in identity (boot, sign-in, sign-out): edits from here on
|
|
633
|
+
* belong to it, under a peer it claims. Edits already made stay with the
|
|
634
|
+
* peer they were made under.
|
|
635
|
+
*/
|
|
636
|
+
setSessionId(_salt: string): void;
|
|
637
|
+
dispose(): void;
|
|
638
|
+
/**
|
|
639
|
+
* Open a collaborative field. Every open of the same field shares one
|
|
640
|
+
* document; close each open with {@link close}.
|
|
782
641
|
*
|
|
783
|
-
*
|
|
784
|
-
*
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
*
|
|
789
|
-
*
|
|
790
|
-
*
|
|
791
|
-
*/
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
};
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
private
|
|
814
|
-
private
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
*
|
|
822
|
-
*
|
|
823
|
-
*
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
*
|
|
840
|
-
*/
|
|
841
|
-
|
|
842
|
-
/**
|
|
843
|
-
*
|
|
844
|
-
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
private
|
|
850
|
-
|
|
851
|
-
|
|
852
|
-
|
|
853
|
-
|
|
854
|
-
|
|
855
|
-
|
|
856
|
-
|
|
857
|
-
|
|
858
|
-
private
|
|
859
|
-
|
|
860
|
-
private
|
|
861
|
-
private
|
|
862
|
-
private
|
|
863
|
-
private
|
|
864
|
-
private
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
private
|
|
869
|
-
private
|
|
870
|
-
|
|
871
|
-
private
|
|
872
|
-
/**
|
|
873
|
-
*
|
|
874
|
-
|
|
875
|
-
private
|
|
876
|
-
private _onCursorUpdate;
|
|
877
|
-
private pendingCursorUpdate;
|
|
878
|
-
/** Callback set by the editor to receive remote cursor updates.
|
|
879
|
-
* Any cursor data that arrived before this callback was set will be replayed. */
|
|
880
|
-
set onCursorUpdate(cb: ((data: Uint8Array) => void) | null);
|
|
881
|
-
get onCursorUpdate(): ((data: Uint8Array) => void) | null;
|
|
882
|
-
constructor(fieldName: string, cursorsEnabled: boolean, initialState?: Uint8Array, logger?: Logger$1 | null);
|
|
883
|
-
getDoc(): LoroDoc;
|
|
884
|
-
/** Whether the LoroDoc was loaded from saved CRDT state */
|
|
885
|
-
hasContent(): boolean;
|
|
886
|
-
startSync(local: LocalDatabaseService, remote: RemoteDatabaseService, recordId: string, sessionId: string, debounceMs: number): void;
|
|
887
|
-
stopSync(): void;
|
|
888
|
-
importRemote(state: Uint8Array): void;
|
|
889
|
-
exportSnapshot(): Uint8Array;
|
|
890
|
-
/** Push this session's cursor blob into the parent row at
|
|
891
|
-
* `<field>.cursors[$sid]`. No-op when cursors aren't enabled on this
|
|
892
|
-
* field — the editor still calls this method optimistically, but
|
|
893
|
-
* without `@cursor` on the schema there's nowhere to store the blob.
|
|
894
|
-
* The UPDATE itself fires the parent table's LIVE feed, so other
|
|
895
|
-
* browsers receive the cursor change without a separate `_00_rv` bump. */
|
|
896
|
-
pushCursorState(encoded: Uint8Array): Promise<void>;
|
|
897
|
-
/** Import remote cursor state (called by CrdtManager from LIVE SELECT) */
|
|
898
|
-
importRemoteCursor(base64State: string): void;
|
|
899
|
-
private scheduleRemotePush;
|
|
900
|
-
/** SET path inside a parent row for the current snapshot. `@crdt`-only
|
|
901
|
-
* fields hold the snapshot directly (`<field>`); `@crdt @cursor`
|
|
902
|
-
* fields hold a `{ state, cursors }` object so the snapshot lives at
|
|
903
|
-
* `<field>.state` next to per-session cursor blobs. */
|
|
904
|
-
private statePath;
|
|
905
|
-
/** Mirror the LoroDoc snapshot into the parent row locally. Runs on
|
|
906
|
-
* every local update and every remote import so reloads (online or
|
|
907
|
-
* offline) see the freshest content immediately. Failures are
|
|
908
|
-
* swallowed — a stale local write must never block user input. */
|
|
909
|
-
private persistLocal;
|
|
910
|
-
private pushToRemote;
|
|
911
|
-
}
|
|
912
|
-
//#endregion
|
|
913
|
-
//#region src/modules/crdt/index.d.ts
|
|
914
|
-
/**
|
|
915
|
-
* CrdtManager manages active CrdtField instances and their sync channels.
|
|
916
|
-
*
|
|
917
|
-
* Collaborative state lives in two dedicated tables (defined in
|
|
918
|
-
* `apps/cli/src/meta_tables_remote.surql`):
|
|
919
|
-
* - `_00_crdt` { record_id, field, state } — one row per (record, field)
|
|
920
|
-
* - `_00_cursor` { record_id, session_id, field, state } — one row per
|
|
921
|
-
* (record, session, field)
|
|
922
|
-
*
|
|
923
|
-
* Splitting them off the parent row is what makes offline edits mergeable:
|
|
924
|
-
* each (record, field) gets its own row, so concurrent offline writes don't
|
|
925
|
-
* collide on the parent's last-write-wins semantics.
|
|
926
|
-
*
|
|
927
|
-
* Cross-browser delivery still rides the parent table's existing LIVE feed
|
|
928
|
-
* to avoid SurrealDB v3 LIVE bugs around dereference-based permission rules
|
|
929
|
-
* (issues 3602, 4026). On every meta UPSERT the writer also bumps the
|
|
930
|
-
* parent's `_00_rv` (a no-op assignment); that fires the parent's LIVE
|
|
931
|
-
* feed, and the receiver pulls the matching `_00_crdt` / `_00_cursor` rows
|
|
932
|
-
* via subquery. Permission inheritance happens server-side via
|
|
933
|
-
* `record_id.id != NONE` (SELECT) and `fn::can_update_record` (UPDATE).
|
|
934
|
-
*/
|
|
935
|
-
declare class CrdtManager {
|
|
936
|
-
private schema;
|
|
937
|
-
private local;
|
|
938
|
-
private remote;
|
|
939
|
-
private debounceMs;
|
|
940
|
-
private fields;
|
|
941
|
-
private liveByTable;
|
|
942
|
-
private pendingLive;
|
|
943
|
-
private logger;
|
|
944
|
-
private sessionId;
|
|
945
|
-
constructor(schema: SchemaStructure, local: LocalDatabaseService, remote: RemoteDatabaseService, logger: Logger$1, debounceMs?: number);
|
|
946
|
-
/** Set the session id that scopes this client's cursor entries. Must be
|
|
947
|
-
* called before `open()` for cursors to be pushed under a stable key.
|
|
948
|
-
* Passed in from `sp00ky.ts` at boot (it already fetches `session::id()`
|
|
949
|
-
* for the data-module salt). */
|
|
950
|
-
setSessionId(sessionId: string): void;
|
|
951
|
-
/**
|
|
952
|
-
* Open a CRDT field for collaborative editing.
|
|
953
|
-
*
|
|
954
|
-
* @param table - Table name
|
|
955
|
-
* @param recordId - Full record ID (e.g., "thread:abc")
|
|
956
|
-
* @param field - Field name (e.g., "title", "content")
|
|
957
|
-
* @param fallbackText - Current plain text from the record, used to seed the
|
|
958
|
-
* LoroDoc if no CRDT state exists yet (migration path)
|
|
959
|
-
*/
|
|
960
|
-
open(table: string, recordId: string, field: string, fallbackText?: string): Promise<CrdtField>;
|
|
961
|
-
close(table: string, recordId: string, field: string): void;
|
|
962
|
-
closeAll(): void;
|
|
963
|
-
/** Ensure a single `LIVE SELECT * FROM <table>` is running, shared across
|
|
964
|
-
* every open CrdtField on `table`. */
|
|
965
|
-
private ensureTableSubscription;
|
|
966
|
-
/** Apply a parent-row payload from a non-LIVE source (e.g. the
|
|
967
|
-
* list_ref-driven sync engine, when the cross-user LIVE on the
|
|
968
|
-
* parent table is filtered out by the SurrealDB cross-session
|
|
969
|
-
* permission gap). Same semantics as the internal `dispatchRow`. */
|
|
970
|
-
applyRow(table: string, row: Record<string, unknown>): void;
|
|
971
|
-
/** Dispatch a parent-row LIVE event to every open CrdtField on that
|
|
972
|
-
* record. Each open field reads its slice of the row directly — the
|
|
973
|
-
* CRDT snapshot is a column on the parent now, so there is no
|
|
974
|
-
* follow-up subquery. */
|
|
975
|
-
private dispatchRow;
|
|
976
|
-
/** One-shot remote fetch for a row whose CRDT field hasn't synced
|
|
977
|
-
* locally yet (fresh device, memory-backed local DB after reload, …).
|
|
978
|
-
* Used by `open()` when the local read came up empty. Subsequent
|
|
979
|
-
* cross-browser updates ride `dispatchRow` via the parent LIVE feed. */
|
|
980
|
-
private fetchAndDispatchRow;
|
|
981
|
-
/** Schema lookup: does `<table>.<field>` carry a `@cursor` annotation?
|
|
982
|
-
* Determines the on-disk shape (plain snapshot vs. `{ state, cursors }`). */
|
|
983
|
-
private fieldHasCursor;
|
|
984
|
-
/** Pull the LoroDoc snapshot bytes out of a row slice. For `@crdt`-only
|
|
985
|
-
* the slice IS the snapshot (Uint8Array); for `@crdt @cursor` it's
|
|
986
|
-
* `{ state, cursors }` where `state` carries the snapshot bytes. */
|
|
987
|
-
private extractSnapshot;
|
|
988
|
-
private killTableSubscription;
|
|
989
|
-
private makeKey;
|
|
990
|
-
/**
|
|
991
|
-
* Throws if `<table>.<field>` is not annotated `@crdt` in the schema. Catches
|
|
992
|
-
* typos, removed annotations, and stale schema codegen at the call site instead
|
|
993
|
-
* of silently producing a non-CRDT writer.
|
|
994
|
-
*/
|
|
995
|
-
private assertCrdtField;
|
|
642
|
+
* `draft` (from {@link createDraft}) hands over edits made before the record
|
|
643
|
+
* existed: they are merged in and sent like this tab's own.
|
|
644
|
+
*/
|
|
645
|
+
open(table: string, recordId: string, field: string, draft?: CrdtField): Promise<CrdtField>;
|
|
646
|
+
/**
|
|
647
|
+
* A detached document for a field of a record that does not exist yet (a
|
|
648
|
+
* "new thread" form). Nothing is sent; pass it to {@link open} once the
|
|
649
|
+
* record is created and its edits become the record's first ones.
|
|
650
|
+
*/
|
|
651
|
+
createDraft(table: string, field: string): Promise<CrdtField>;
|
|
652
|
+
private adopt;
|
|
653
|
+
/** Close one open. The last close of a field resolves once its unsent
|
|
654
|
+
* edits are in the outbox, or once they are saved on the device when the
|
|
655
|
+
* server does not answer in time (offline: at once). */
|
|
656
|
+
close(table: string, recordId: string, field: string): Promise<void>;
|
|
657
|
+
/** Close every field. `flush: false` (a bucket switch) drops unsent edits
|
|
658
|
+
* from this session's memory; they stay in the local snapshot of the
|
|
659
|
+
* bucket they belong to. */
|
|
660
|
+
closeAll(options?: {
|
|
661
|
+
flush?: boolean;
|
|
662
|
+
}): void;
|
|
663
|
+
private fieldSpec;
|
|
664
|
+
private start;
|
|
665
|
+
private stop;
|
|
666
|
+
/**
|
|
667
|
+
* Wait for server-bound `work`, at most {@link SERVER_WAIT_MS}, and not at
|
|
668
|
+
* all while disconnected: a remote call made then queues behind the
|
|
669
|
+
* reconnect for up to the query timeout, and an offline "new thread" form
|
|
670
|
+
* must not hang on it. The work itself goes on either way.
|
|
671
|
+
*/
|
|
672
|
+
private serverWait;
|
|
673
|
+
private ingest;
|
|
674
|
+
/** Mark the field loaded once its content arrived, or the server answered
|
|
675
|
+
* both reads (the published document and the log) with nothing. */
|
|
676
|
+
private checkLoaded;
|
|
677
|
+
private tryImport;
|
|
678
|
+
private refetchCanonical;
|
|
679
|
+
/**
|
|
680
|
+
* A first open reads the published document and the log at the same time,
|
|
681
|
+
* and a fold landing between the two hides the field from both: it
|
|
682
|
+
* publishes its snapshot, then deletes the rows the log query was about to
|
|
683
|
+
* return, after the published-document read came back empty. Nothing seen
|
|
684
|
+
* means nothing to verify, so the editor stayed empty until the next edit
|
|
685
|
+
* (a second device opening a just-created thread, under e2e load). Once the
|
|
686
|
+
* log has answered, a field that is still empty reads the published
|
|
687
|
+
* document again: the fold that took its rows committed before deleting
|
|
688
|
+
* them. Once per open; `first` is the first read (null with a local copy or
|
|
689
|
+
* a draft, which need none).
|
|
690
|
+
*/
|
|
691
|
+
private recheckCanonical;
|
|
692
|
+
private scheduleVerify;
|
|
693
|
+
/**
|
|
694
|
+
* After a fold: compare this device's document with the one the server
|
|
695
|
+
* published, at the version the server published. Missing ops (rows this
|
|
696
|
+
* device never got before they were folded away) are repaired by merging
|
|
697
|
+
* the published snapshot in. The same ops giving a different state cannot
|
|
698
|
+
* be merged away; that is logged.
|
|
699
|
+
*/
|
|
700
|
+
private verify;
|
|
701
|
+
/**
|
|
702
|
+
* Arm the send. Edits go out on a steady cadence while they keep coming:
|
|
703
|
+
* the first one after a quiet spell waits `debounceMs` (one row for the
|
|
704
|
+
* burst), later ones at least `sendIntervalMs` after the previous send. An
|
|
705
|
+
* armed timer is never pushed back, so continuous typing cannot hold the
|
|
706
|
+
* edits; it is only brought forward (`delay`, e.g. 0 on reconnect).
|
|
707
|
+
*/
|
|
708
|
+
private scheduleFlush;
|
|
709
|
+
/** Send what is unsent. A call while a send runs queues one more after it,
|
|
710
|
+
* so edits made during that send are not left waiting for the next edit. */
|
|
711
|
+
private flush;
|
|
712
|
+
/** Send every own peer's ops that are not in the outbox yet, one row per
|
|
713
|
+
* peer. Only the peer's own ops travel (`updates-in-range`): a plain
|
|
714
|
+
* `from: version` export would carry ops imported from others too, and
|
|
715
|
+
* the acceptance rule refuses such a row. */
|
|
716
|
+
private sendOwnEdits;
|
|
717
|
+
private retryLater;
|
|
718
|
+
/** Claim this session's peer once; a failure (offline, signed out) is retried. */
|
|
719
|
+
private ensureClaimed;
|
|
720
|
+
private claimPeer;
|
|
721
|
+
private localId;
|
|
722
|
+
private readLocal;
|
|
723
|
+
private schedulePersist;
|
|
724
|
+
/** Save the merged document. Another tab may have saved too: merge with
|
|
725
|
+
* its snapshot rather than overwrite it, and keep the further of the two
|
|
726
|
+
* outbox marks per peer. */
|
|
727
|
+
private persist;
|
|
728
|
+
private pushPresence;
|
|
729
|
+
/** Presence is the latest state only: no outbox, no offline queue. */
|
|
730
|
+
private sendPresence;
|
|
731
|
+
/** Remove this session's cursor when the field closes; the server's TTL
|
|
732
|
+
* sweep covers a tab that never gets here. */
|
|
733
|
+
private dropPresence;
|
|
734
|
+
private ingestPresence;
|
|
996
735
|
}
|
|
997
736
|
//#endregion
|
|
998
737
|
//#region src/modules/feature-flag/index.d.ts
|
|
@@ -1004,6 +743,15 @@ interface FeatureFlagOptions {
|
|
|
1004
743
|
fallback?: string;
|
|
1005
744
|
ttl?: QueryTimeToLive;
|
|
1006
745
|
}
|
|
746
|
+
/**
|
|
747
|
+
* A locally forced variant. Applies to THIS browser only and is never sent to
|
|
748
|
+
* the server — the assignment in `_00_user_feature` is untouched, so clearing
|
|
749
|
+
* the override restores whatever the server says.
|
|
750
|
+
*/
|
|
751
|
+
interface FeatureFlagOverride {
|
|
752
|
+
variant: string;
|
|
753
|
+
payload?: unknown;
|
|
754
|
+
}
|
|
1007
755
|
declare class FeatureFlagHandle {
|
|
1008
756
|
readonly key: string;
|
|
1009
757
|
readonly fallback: string | undefined;
|
|
@@ -1023,10 +771,26 @@ declare class FeatureFlagHandle {
|
|
|
1023
771
|
onClose(cb: () => void): void;
|
|
1024
772
|
close(): void;
|
|
1025
773
|
}
|
|
774
|
+
/** The slice of the query engine this module drives: register a live query
|
|
775
|
+
* locally, ask for its remote registration, subscribe to its rows. */
|
|
776
|
+
interface LiveQueryPort$1 {
|
|
777
|
+
query(table: string, surql: string, params: Record<string, unknown>, ttl: QueryTimeToLive): Promise<string>;
|
|
778
|
+
subscribe(hash: string, cb: (records: Record<string, any>[]) => void, options?: {
|
|
779
|
+
immediate?: boolean;
|
|
780
|
+
}): () => void;
|
|
781
|
+
}
|
|
782
|
+
interface RemoteRegisterPort$1 {
|
|
783
|
+
enqueueDownEvent(event: {
|
|
784
|
+
type: 'register';
|
|
785
|
+
payload: {
|
|
786
|
+
hash: string;
|
|
787
|
+
};
|
|
788
|
+
}): void;
|
|
789
|
+
}
|
|
1026
790
|
interface FeatureFlagModuleDeps<S extends SchemaStructure> {
|
|
1027
|
-
dataModule:
|
|
1028
|
-
sync:
|
|
1029
|
-
auth: AuthService<S>;
|
|
791
|
+
dataModule: LiveQueryPort$1;
|
|
792
|
+
sync: RemoteRegisterPort$1;
|
|
793
|
+
auth: Pick<AuthService<S>, 'subscribe'>;
|
|
1030
794
|
logger: Logger$1;
|
|
1031
795
|
}
|
|
1032
796
|
declare class FeatureFlagModule<S extends SchemaStructure> {
|
|
@@ -1040,6 +804,7 @@ declare class FeatureFlagModule<S extends SchemaStructure> {
|
|
|
1040
804
|
private ttl;
|
|
1041
805
|
private snapshots;
|
|
1042
806
|
private loaded;
|
|
807
|
+
private overrides;
|
|
1043
808
|
constructor(deps: FeatureFlagModuleDeps<S>);
|
|
1044
809
|
init(): void;
|
|
1045
810
|
feature(key: string, options?: FeatureFlagOptions): FeatureFlagHandle;
|
|
@@ -1051,15 +816,1296 @@ declare class FeatureFlagModule<S extends SchemaStructure> {
|
|
|
1051
816
|
private ensureStarted;
|
|
1052
817
|
/** Live query result → per-key snapshots → push to every active handle. */
|
|
1053
818
|
private applyRecords;
|
|
819
|
+
/**
|
|
820
|
+
* Force `key` to `variant` in THIS browser. Pass `null` to clear.
|
|
821
|
+
*
|
|
822
|
+
* Nothing is written to the server: the `_00_user_feature` assignment is
|
|
823
|
+
* untouched, so clearing restores whatever the server says. Persisted to
|
|
824
|
+
* localStorage on the page origin, so it survives a reload.
|
|
825
|
+
*/
|
|
826
|
+
setLocalOverride(key: string, variant: string | null, payload?: unknown): void;
|
|
827
|
+
clearLocalOverrides(): void;
|
|
828
|
+
getLocalOverrides(): Record<string, FeatureFlagOverride>;
|
|
829
|
+
/** The assignment for `key`, with any local override taking precedence. */
|
|
830
|
+
private resolve;
|
|
831
|
+
private pushAll;
|
|
832
|
+
private loadOverrides;
|
|
833
|
+
private persistOverrides;
|
|
1054
834
|
}
|
|
1055
835
|
//#endregion
|
|
1056
|
-
//#region src/
|
|
836
|
+
//#region src/modules/app-release/index.d.ts
|
|
837
|
+
interface AppReleaseSnapshot {
|
|
838
|
+
/** Latest announced version for the app, or undefined when no row exists. */
|
|
839
|
+
version: string | undefined;
|
|
840
|
+
/** Clients should clear SW/caches when reloading onto this version. */
|
|
841
|
+
cacheBust: boolean;
|
|
842
|
+
/** Clients should reload/update immediately instead of asking. */
|
|
843
|
+
mandatory: boolean;
|
|
844
|
+
releasedAt: string | undefined;
|
|
845
|
+
}
|
|
846
|
+
interface AppReleaseOptions {
|
|
847
|
+
ttl?: QueryTimeToLive;
|
|
848
|
+
}
|
|
849
|
+
declare class AppReleaseHandle {
|
|
850
|
+
readonly app: string;
|
|
851
|
+
private latest;
|
|
852
|
+
private listeners;
|
|
853
|
+
private onCloseFn;
|
|
854
|
+
private closed;
|
|
855
|
+
constructor(app: string);
|
|
856
|
+
set(snapshot: AppReleaseSnapshot): void;
|
|
857
|
+
snapshot(): AppReleaseSnapshot;
|
|
858
|
+
version(): string | undefined;
|
|
859
|
+
/** True when the announced version is semver-newer than `currentVersion`. */
|
|
860
|
+
updateAvailable(currentVersion: string): boolean;
|
|
861
|
+
subscribe(cb: (s: AppReleaseSnapshot) => void): () => void;
|
|
862
|
+
onClose(cb: () => void): void;
|
|
863
|
+
close(): void;
|
|
864
|
+
}
|
|
865
|
+
/** The slice of the query engine this module drives: register a live query
|
|
866
|
+
* locally, ask for its remote registration, subscribe to its rows. */
|
|
867
|
+
interface LiveQueryPort {
|
|
868
|
+
query(table: string, surql: string, params: Record<string, unknown>, ttl: QueryTimeToLive): Promise<string>;
|
|
869
|
+
subscribe(hash: string, cb: (records: Record<string, any>[]) => void, options?: {
|
|
870
|
+
immediate?: boolean;
|
|
871
|
+
}): () => void;
|
|
872
|
+
}
|
|
873
|
+
interface RemoteRegisterPort {
|
|
874
|
+
enqueueDownEvent(event: {
|
|
875
|
+
type: 'register';
|
|
876
|
+
payload: {
|
|
877
|
+
hash: string;
|
|
878
|
+
};
|
|
879
|
+
}): void;
|
|
880
|
+
}
|
|
881
|
+
interface AppReleaseModuleDeps<S extends SchemaStructure> {
|
|
882
|
+
dataModule: LiveQueryPort;
|
|
883
|
+
sync: RemoteRegisterPort;
|
|
884
|
+
auth: Pick<AuthService<S>, 'subscribe'>;
|
|
885
|
+
logger: Logger$1;
|
|
886
|
+
}
|
|
887
|
+
declare class AppReleaseModule<S extends SchemaStructure> {
|
|
888
|
+
private deps;
|
|
889
|
+
private logger;
|
|
890
|
+
private handles;
|
|
891
|
+
private authUnsubscribe;
|
|
892
|
+
private lastUserId;
|
|
893
|
+
private querySubscription;
|
|
894
|
+
private starting;
|
|
895
|
+
private ttl;
|
|
896
|
+
private snapshots;
|
|
897
|
+
private loaded;
|
|
898
|
+
constructor(deps: AppReleaseModuleDeps<S>);
|
|
899
|
+
init(): void;
|
|
900
|
+
release(app: string, options?: AppReleaseOptions): AppReleaseHandle;
|
|
901
|
+
closeAll(): Promise<void>;
|
|
902
|
+
private refresh;
|
|
903
|
+
private teardownQuery;
|
|
904
|
+
private ensureStarted;
|
|
905
|
+
private applyRecords;
|
|
906
|
+
}
|
|
907
|
+
//#endregion
|
|
908
|
+
//#region src/kernel/events.d.ts
|
|
909
|
+
/**
|
|
910
|
+
* Inbound events. Everything that can start a saga arrives as one of these
|
|
911
|
+
* through the runtime router: public API calls, adapter callbacks, timers,
|
|
912
|
+
* and `dispatch` effects from other sagas.
|
|
913
|
+
*/
|
|
914
|
+
type RuntimeEvent = {
|
|
915
|
+
type: 'EnsureRegistered';
|
|
916
|
+
requireAuth?: boolean;
|
|
917
|
+
attempt?: number;
|
|
918
|
+
} | {
|
|
919
|
+
type: 'RegisterRemote';
|
|
920
|
+
hash: QueryHash;
|
|
921
|
+
retry?: boolean;
|
|
922
|
+
} | {
|
|
923
|
+
type: 'ReleaseSuperseded';
|
|
924
|
+
ids: RecordId$1<string>[];
|
|
925
|
+
} | {
|
|
926
|
+
type: 'SyncOutcome';
|
|
927
|
+
ok: boolean;
|
|
928
|
+
error?: unknown;
|
|
929
|
+
} | {
|
|
930
|
+
type: 'AckPrune';
|
|
931
|
+
} | {
|
|
932
|
+
type: 'ReadDirtyMembership';
|
|
933
|
+
} | {
|
|
934
|
+
type: 'RecoverLostView';
|
|
935
|
+
hash: QueryHash;
|
|
936
|
+
} | {
|
|
937
|
+
type: 'ReadMembership';
|
|
938
|
+
hashes: QueryHash[];
|
|
939
|
+
} | {
|
|
940
|
+
type: 'FetchRows';
|
|
941
|
+
} | {
|
|
942
|
+
type: 'Materialize';
|
|
943
|
+
hash: QueryHash;
|
|
944
|
+
} | {
|
|
945
|
+
type: 'MaterializeDirty';
|
|
946
|
+
} | {
|
|
947
|
+
type: 'LifecycleTick';
|
|
948
|
+
} | {
|
|
949
|
+
type: 'GcTick';
|
|
950
|
+
} | {
|
|
951
|
+
type: 'Drain';
|
|
952
|
+
} | {
|
|
953
|
+
type: 'FlushWrite';
|
|
954
|
+
key: string;
|
|
955
|
+
} | {
|
|
956
|
+
type: 'PeerWriteExpired';
|
|
957
|
+
id: string;
|
|
958
|
+
} | {
|
|
959
|
+
type: 'FlushPendingWrites';
|
|
960
|
+
} | {
|
|
961
|
+
type: 'AdoptPendingWrites';
|
|
962
|
+
} | {
|
|
963
|
+
type: 'PollTick';
|
|
964
|
+
} | {
|
|
965
|
+
type: 'SelfHealTick';
|
|
966
|
+
} | {
|
|
967
|
+
type: 'HeartbeatNow';
|
|
968
|
+
} | {
|
|
969
|
+
type: 'StartRemote';
|
|
970
|
+
} | {
|
|
971
|
+
type: 'PrimeCircuit';
|
|
972
|
+
} | {
|
|
973
|
+
type: 'VersionsPrimed';
|
|
974
|
+
entries: Array<readonly [string, number]>;
|
|
975
|
+
} | {
|
|
976
|
+
type: 'WarmBlobs';
|
|
977
|
+
} | {
|
|
978
|
+
type: 'AuthFlip';
|
|
979
|
+
userId: string | null;
|
|
980
|
+
} | {
|
|
981
|
+
type: 'BucketSwitch';
|
|
982
|
+
target: string;
|
|
983
|
+
} | {
|
|
984
|
+
type: 'PageHide';
|
|
985
|
+
} | {
|
|
986
|
+
type: 'ConnectionChanged';
|
|
987
|
+
state: ConnectionState;
|
|
988
|
+
} | {
|
|
989
|
+
type: 'StreamUpdate';
|
|
990
|
+
update: StreamUpdate;
|
|
991
|
+
} | {
|
|
992
|
+
type: 'LiveStart';
|
|
993
|
+
} | {
|
|
994
|
+
type: 'LiveChange';
|
|
995
|
+
hashes: QueryHash[];
|
|
996
|
+
rows?: InlineRow[];
|
|
997
|
+
deltas?: EdgeDelta[];
|
|
998
|
+
} | {
|
|
999
|
+
type: 'TabRole';
|
|
1000
|
+
role: 'solo' | 'leader' | 'follower';
|
|
1001
|
+
} | {
|
|
1002
|
+
type: 'TabMessage';
|
|
1003
|
+
message: unknown;
|
|
1004
|
+
};
|
|
1005
|
+
type OutEvent = {
|
|
1006
|
+
type: 'query:records';
|
|
1007
|
+
hash: QueryHash;
|
|
1008
|
+
records: ReadonlyArray<Record<string, unknown>>;
|
|
1009
|
+
} | {
|
|
1010
|
+
type: 'query:status';
|
|
1011
|
+
hash: QueryHash;
|
|
1012
|
+
status: QueryStatus;
|
|
1013
|
+
} | {
|
|
1014
|
+
type: 'query:authority';
|
|
1015
|
+
hash: QueryHash;
|
|
1016
|
+
known: boolean;
|
|
1017
|
+
} | {
|
|
1018
|
+
type: 'query:view-lost';
|
|
1019
|
+
hash: QueryHash;
|
|
1020
|
+
} | {
|
|
1021
|
+
type: 'query:evicted';
|
|
1022
|
+
hash: QueryHash;
|
|
1023
|
+
} | {
|
|
1024
|
+
type: 'mutation:event';
|
|
1025
|
+
event: unknown;
|
|
1026
|
+
} | {
|
|
1027
|
+
type: 'mutation:settled';
|
|
1028
|
+
mutationId: string;
|
|
1029
|
+
recordId: string;
|
|
1030
|
+
eventType: string;
|
|
1031
|
+
} | {
|
|
1032
|
+
type: 'mutation:rolled-back';
|
|
1033
|
+
mutationId: string;
|
|
1034
|
+
recordId: string;
|
|
1035
|
+
eventType: string;
|
|
1036
|
+
error: string;
|
|
1037
|
+
} | {
|
|
1038
|
+
type: 'tray:changed';
|
|
1039
|
+
count: number;
|
|
1040
|
+
} | {
|
|
1041
|
+
type: 'health:changed';
|
|
1042
|
+
health: SyncHealth;
|
|
1043
|
+
} | {
|
|
1044
|
+
type: 'activity:changed';
|
|
1045
|
+
fetching: number;
|
|
1046
|
+
pending: number;
|
|
1047
|
+
} | {
|
|
1048
|
+
type: 'tabs:broadcast';
|
|
1049
|
+
message: unknown;
|
|
1050
|
+
} | {
|
|
1051
|
+
type: 'tabs:sendTo';
|
|
1052
|
+
tabId: string;
|
|
1053
|
+
message: unknown;
|
|
1054
|
+
} | {
|
|
1055
|
+
type: 'log';
|
|
1056
|
+
level: 'debug' | 'info' | 'warn' | 'error';
|
|
1057
|
+
message: string;
|
|
1058
|
+
data?: unknown;
|
|
1059
|
+
};
|
|
1060
|
+
//#endregion
|
|
1061
|
+
//#region src/state/lifecycle.d.ts
|
|
1062
|
+
/**
|
|
1063
|
+
* The query lifecycle as one explicit machine.
|
|
1064
|
+
*
|
|
1065
|
+
* `phase` answers "where do this query's rows come from":
|
|
1066
|
+
* - `cold` never resolved on this device: rows come from a local
|
|
1067
|
+
* predicate scan (or the SSP local window), bindings show a loader.
|
|
1068
|
+
* - `cached` a durable `_00_view` row was found: rows come from that id-set.
|
|
1069
|
+
* - `live` a server membership set was accepted this session.
|
|
1070
|
+
* - `view-lost` the server's `_00_query` row vanished while we held
|
|
1071
|
+
* membership; rows are kept, a re-registration is under way.
|
|
1072
|
+
*
|
|
1073
|
+
* `remote` tracks the server-side registration, `fetchDepth` is the refcount
|
|
1074
|
+
* behind `status: 'fetching'`, `notified` says whether subscribers received
|
|
1075
|
+
* at least one materialization this registration.
|
|
1076
|
+
*
|
|
1077
|
+
* `answered` says subscribers have been handed the rows of a known membership
|
|
1078
|
+
* (the server's, or the durable one of an earlier session) at least once:
|
|
1079
|
+
* a materialization ran past `cold`, with no body of a server set still to
|
|
1080
|
+
* download, and the membership it drew was still the one in state when it
|
|
1081
|
+
* committed. Only a re-seed (a new entry, a bucket switch) clears it, so a
|
|
1082
|
+
* reconnect or a lost view does not send a painted query back to loading.
|
|
1083
|
+
* It is what the bindings' `isAuthoritative()` mirrors (see `isAnswered`):
|
|
1084
|
+
* a `cached` seed or a freshly applied server set alone is not enough,
|
|
1085
|
+
* because `records` is still empty (or stale) until `materialize` paints, and
|
|
1086
|
+
* "known and empty" read in that beat made apps create rows that existed.
|
|
1087
|
+
*
|
|
1088
|
+
* `backgroundDepth` is the part of `fetchDepth` that re-verifies rows the
|
|
1089
|
+
* query already shows: a registration of a query that is not `cold`. It still
|
|
1090
|
+
* holds `status: 'fetching'` (results are not yet confirmed), but it is not
|
|
1091
|
+
* traffic the user waits on, so the activity indicator leaves it out.
|
|
1092
|
+
*/
|
|
1093
|
+
type QueryPhase = 'cold' | 'cached' | 'live' | 'view-lost';
|
|
1094
|
+
type RemotePhase = 'unregistered' | 'registering' | 'registered' | 'failed';
|
|
1095
|
+
interface QueryLifecycle {
|
|
1096
|
+
readonly phase: QueryPhase;
|
|
1097
|
+
readonly remote: RemotePhase;
|
|
1098
|
+
readonly fetchDepth: number;
|
|
1099
|
+
readonly backgroundDepth: number;
|
|
1100
|
+
readonly notified: boolean;
|
|
1101
|
+
readonly answered: boolean;
|
|
1102
|
+
}
|
|
1103
|
+
//#endregion
|
|
1104
|
+
//#region src/kernel/effects.d.ts
|
|
1105
|
+
type Vars = Record<string, unknown>;
|
|
1106
|
+
/** What the in-browser SSP needs to build a local view. */
|
|
1107
|
+
interface RegisterPlan {
|
|
1108
|
+
queryHash: string;
|
|
1109
|
+
surql: string;
|
|
1110
|
+
params: Vars;
|
|
1111
|
+
ttl: string;
|
|
1112
|
+
tableName: string;
|
|
1113
|
+
involvedTables?: string[];
|
|
1114
|
+
}
|
|
1115
|
+
/** One statement's outcome of a multi-statement remote request. */
|
|
1116
|
+
type StatementResult = {
|
|
1117
|
+
status: 'OK';
|
|
1118
|
+
result: unknown;
|
|
1119
|
+
} | {
|
|
1120
|
+
status: 'ERR';
|
|
1121
|
+
error: string;
|
|
1122
|
+
};
|
|
1123
|
+
/** One entry of an `all` fan-out result (allSettled semantics). */
|
|
1124
|
+
|
|
1125
|
+
/**
|
|
1126
|
+
* Effects are data. A saga yields one and gets its result back on the next
|
|
1127
|
+
* `next()`; the interpreter (client/runtime) is the only place they execute.
|
|
1128
|
+
*/
|
|
1129
|
+
type Effect = {
|
|
1130
|
+
kind: 'local.query';
|
|
1131
|
+
sql: string;
|
|
1132
|
+
vars?: Vars;
|
|
1133
|
+
epoch?: number;
|
|
1134
|
+
} | {
|
|
1135
|
+
kind: 'local.select';
|
|
1136
|
+
plan: QueryPlan;
|
|
1137
|
+
params?: Vars;
|
|
1138
|
+
} | {
|
|
1139
|
+
kind: 'local.execute';
|
|
1140
|
+
query: SealedQuery<unknown>;
|
|
1141
|
+
vars?: Vars;
|
|
1142
|
+
epoch?: number;
|
|
1143
|
+
} | {
|
|
1144
|
+
kind: 'local.getById';
|
|
1145
|
+
table: string;
|
|
1146
|
+
id: unknown;
|
|
1147
|
+
} | {
|
|
1148
|
+
kind: 'local.upsert';
|
|
1149
|
+
table: string;
|
|
1150
|
+
id: unknown;
|
|
1151
|
+
data: Record<string, unknown>;
|
|
1152
|
+
mode: 'replace' | 'merge';
|
|
1153
|
+
} | {
|
|
1154
|
+
kind: 'local.delete';
|
|
1155
|
+
table: string;
|
|
1156
|
+
id: unknown;
|
|
1157
|
+
} | {
|
|
1158
|
+
kind: 'local.epoch';
|
|
1159
|
+
} | {
|
|
1160
|
+
kind: 'remote.query';
|
|
1161
|
+
sql: string;
|
|
1162
|
+
vars?: Vars;
|
|
1163
|
+
timeoutMs?: number;
|
|
1164
|
+
} | {
|
|
1165
|
+
kind: 'remote.live';
|
|
1166
|
+
table: string;
|
|
1167
|
+
} | {
|
|
1168
|
+
kind: 'remote.kill';
|
|
1169
|
+
uuid: string;
|
|
1170
|
+
} | {
|
|
1171
|
+
kind: 'ssp.register';
|
|
1172
|
+
plan: RegisterPlan;
|
|
1173
|
+
} | {
|
|
1174
|
+
kind: 'ssp.unregister';
|
|
1175
|
+
hash: string;
|
|
1176
|
+
} | {
|
|
1177
|
+
kind: 'ssp.ingest';
|
|
1178
|
+
records: IngestRecord[];
|
|
1179
|
+
} | {
|
|
1180
|
+
kind: 'timer.set';
|
|
1181
|
+
key: string;
|
|
1182
|
+
ms: number;
|
|
1183
|
+
event: RuntimeEvent;
|
|
1184
|
+
} | {
|
|
1185
|
+
kind: 'timer.clear';
|
|
1186
|
+
key: string;
|
|
1187
|
+
} | {
|
|
1188
|
+
kind: 'state.read';
|
|
1189
|
+
select: (s: ClientState) => unknown;
|
|
1190
|
+
} | {
|
|
1191
|
+
kind: 'state.update';
|
|
1192
|
+
fn: (s: ClientState) => ClientState;
|
|
1193
|
+
} | {
|
|
1194
|
+
kind: 'state.wait';
|
|
1195
|
+
until: (s: ClientState) => boolean;
|
|
1196
|
+
} | {
|
|
1197
|
+
kind: 'now';
|
|
1198
|
+
} | {
|
|
1199
|
+
kind: 'id';
|
|
1200
|
+
scope: IdScope;
|
|
1201
|
+
} | {
|
|
1202
|
+
kind: 'hash';
|
|
1203
|
+
input: string;
|
|
1204
|
+
} | {
|
|
1205
|
+
kind: 'emit';
|
|
1206
|
+
event: OutEvent;
|
|
1207
|
+
} | {
|
|
1208
|
+
kind: 'dispatch';
|
|
1209
|
+
event: RuntimeEvent;
|
|
1210
|
+
} | {
|
|
1211
|
+
kind: 'all';
|
|
1212
|
+
effects: Effect[];
|
|
1213
|
+
} | {
|
|
1214
|
+
kind: 'service';
|
|
1215
|
+
name: ServiceName;
|
|
1216
|
+
args: unknown[];
|
|
1217
|
+
};
|
|
1218
|
+
/** `mutation`: an outbox row id. `salt`: a query-key salt. `owner`: a page's anonymous-view owner secret. */
|
|
1219
|
+
type IdScope = 'mutation' | 'salt' | 'owner';
|
|
1220
|
+
/**
|
|
1221
|
+
* Calls into the legacy services that are adapters, not state: auth, tabs,
|
|
1222
|
+
* blobs, migrator, crdt, persistence, the SSP lifecycle, the remote socket.
|
|
1223
|
+
* A saga names the call; the runtime binds it to the real service.
|
|
1224
|
+
*/
|
|
1225
|
+
interface ServiceCalls {
|
|
1226
|
+
'hint.read': () => string | null;
|
|
1227
|
+
'hint.write': (bucketId: string) => void;
|
|
1228
|
+
/** The salt (and owner secret) this tab's previous page left, if minted for `authId`. */
|
|
1229
|
+
'salt.take': (authId: string | null) => {
|
|
1230
|
+
salt: string;
|
|
1231
|
+
owner: string | null;
|
|
1232
|
+
} | null;
|
|
1233
|
+
'salt.leave': (salt: string, authId: string | null, owner: string | null) => void;
|
|
1234
|
+
'local.connect': (bucketId: string) => Promise<void>;
|
|
1235
|
+
'local.switchStore': (bucketId: string) => Promise<void>;
|
|
1236
|
+
'local.beginSwitch': () => () => void;
|
|
1237
|
+
'local.currentBucketId': () => string;
|
|
1238
|
+
'local.usesSurqlSchema': () => boolean;
|
|
1239
|
+
'local.dropBucket': (bucketId: string) => Promise<void>;
|
|
1240
|
+
'migrator.provision': () => Promise<void>;
|
|
1241
|
+
'blobs.start': (bucketId: string) => Promise<void>;
|
|
1242
|
+
'blobs.setNamespace': (bucketId: string) => Promise<void>;
|
|
1243
|
+
'blobs.clear': () => Promise<void>;
|
|
1244
|
+
'ssp.init': () => Promise<void>;
|
|
1245
|
+
'ssp.setPermissions': () => void;
|
|
1246
|
+
'ssp.setSessionAuth': (authId: string | null, access: string | null) => void;
|
|
1247
|
+
'ssp.prime': (pendingIds: string[]) => Promise<void>;
|
|
1248
|
+
'ssp.reset': () => Promise<void>;
|
|
1249
|
+
'ssp.setPersistence': (enabled: boolean) => void;
|
|
1250
|
+
'auth.restoreSession': () => Promise<string | null>;
|
|
1251
|
+
'auth.init': () => Promise<void>;
|
|
1252
|
+
'auth.sessionAuthId': () => string | null;
|
|
1253
|
+
'auth.access': () => string | null;
|
|
1254
|
+
'auth.token': () => string | null;
|
|
1255
|
+
'auth.currentUser': () => Record<string, unknown> | null;
|
|
1256
|
+
'auth.consumeEndedImpersonation': () => string | null;
|
|
1257
|
+
'remote.connect': () => Promise<void>;
|
|
1258
|
+
/** The platform reports no network at all (a browser's `navigator.onLine === false`). */
|
|
1259
|
+
'net.offline': () => boolean;
|
|
1260
|
+
'remote.releaseViews': (ids: unknown[]) => void;
|
|
1261
|
+
/** `session::id()` of every socket this page has had, oldest first. */
|
|
1262
|
+
'remote.sessionIds': () => readonly string[];
|
|
1263
|
+
'supervisor.start': () => void;
|
|
1264
|
+
'tabs.start': (bucketId: string) => Promise<'solo' | 'leader' | 'follower'>;
|
|
1265
|
+
'tabs.moveToBucket': (bucketId: string) => Promise<'solo' | 'leader' | 'follower'>;
|
|
1266
|
+
'crdt.setSessionId': (sessionId: string) => void;
|
|
1267
|
+
'crdt.closeAll': (flush: boolean) => void;
|
|
1268
|
+
'persistence.set': (key: string, value: unknown) => Promise<void>;
|
|
1269
|
+
'features.init': () => void;
|
|
1270
|
+
'releases.init': () => void;
|
|
1271
|
+
'window.attach': () => void;
|
|
1272
|
+
}
|
|
1273
|
+
type ServiceName = keyof ServiceCalls;
|
|
1274
|
+
/** Typed constructors. Each is one line so the saga reads like the plan. */
|
|
1275
|
+
//#endregion
|
|
1276
|
+
//#region src/kernel/saga.d.ts
|
|
1277
|
+
/**
|
|
1278
|
+
* A saga is a generator that yields effects and receives their results. It
|
|
1279
|
+
* holds no references to adapters or state, so it can be driven by the real
|
|
1280
|
+
* interpreter or by `testing/run-pure` with canned results.
|
|
1281
|
+
*/
|
|
1282
|
+
type Saga<R> = Generator<Effect, R, any>;
|
|
1283
|
+
/**
|
|
1284
|
+
* Lanes bound concurrency without a queue object per lane:
|
|
1285
|
+
* - `serial`: runs strictly one at a time per key, in arrival order.
|
|
1286
|
+
* - `dedupe`: a request while one run is active joins that run instead of
|
|
1287
|
+
* starting another.
|
|
1288
|
+
* The bookkeeping is a pure value so the policy is unit-testable; the runtime
|
|
1289
|
+
* owns the promises.
|
|
1290
|
+
*/
|
|
1291
|
+
type Lane = {
|
|
1292
|
+
kind: 'serial';
|
|
1293
|
+
key: string;
|
|
1294
|
+
} | {
|
|
1295
|
+
kind: 'dedupe';
|
|
1296
|
+
key: string;
|
|
1297
|
+
};
|
|
1298
|
+
interface LaneState {
|
|
1299
|
+
readonly running: ReadonlySet<string>;
|
|
1300
|
+
readonly waiting: ReadonlyMap<string, number>;
|
|
1301
|
+
}
|
|
1302
|
+
//#endregion
|
|
1303
|
+
//#region src/state/client-state.d.ts
|
|
1304
|
+
type Row = Record<string, unknown>;
|
|
1305
|
+
/** Everything a query is, minus anything that changes after registration. */
|
|
1306
|
+
interface QueryDefinition {
|
|
1307
|
+
/** Session-salted `_00_query:<hash>` record id: the remote view id. */
|
|
1308
|
+
readonly id: RecordId<string>;
|
|
1309
|
+
readonly hash: QueryHash;
|
|
1310
|
+
/** Unsalted `sha256({surql, params})`: key of the durable `_00_view` row. */
|
|
1311
|
+
readonly viewKey: string;
|
|
1312
|
+
readonly surql: string;
|
|
1313
|
+
readonly params: Readonly<Record<string, unknown>>;
|
|
1314
|
+
readonly plan?: QueryPlan;
|
|
1315
|
+
readonly ttl: QueryTimeToLive;
|
|
1316
|
+
readonly ttlMs: number;
|
|
1317
|
+
readonly tableName: string;
|
|
1318
|
+
readonly createdAt: number;
|
|
1319
|
+
}
|
|
1320
|
+
type ServerViewState = 'materializing' | 'ready' | null;
|
|
1321
|
+
interface QueryTelemetry {
|
|
1322
|
+
readonly updateCount: number;
|
|
1323
|
+
readonly errorCount: number;
|
|
1324
|
+
readonly lastUpdatedAt: number | null;
|
|
1325
|
+
readonly materializationSamples: ReadonlyArray<number>;
|
|
1326
|
+
readonly lastIngestLatencyMs: number | null;
|
|
1327
|
+
readonly phaseSamples: Readonly<Record<string, ReadonlyArray<number>>>;
|
|
1328
|
+
readonly phaseLast: Readonly<Record<string, number | null>>;
|
|
1329
|
+
readonly registrationTimings: RegistrationTimings;
|
|
1330
|
+
}
|
|
1331
|
+
interface QueryEntry {
|
|
1332
|
+
readonly def: QueryDefinition;
|
|
1333
|
+
readonly lifecycle: QueryLifecycle;
|
|
1334
|
+
/** Server membership (ids + versions) or the durable seed. */
|
|
1335
|
+
readonly remoteArray: RecordVersionArray;
|
|
1336
|
+
/** The in-browser SSP view's id-set: local truth for "does this row match". */
|
|
1337
|
+
readonly localArray: RecordVersionArray;
|
|
1338
|
+
readonly subqueryRemoteArray: RecordVersionArray;
|
|
1339
|
+
readonly records: ReadonlyArray<Row>;
|
|
1340
|
+
readonly serverState: ServerViewState;
|
|
1341
|
+
readonly subscribers: number;
|
|
1342
|
+
readonly lastSubscriberLeftAt: number | null;
|
|
1343
|
+
readonly lastHeartbeatAt: number | null;
|
|
1344
|
+
readonly lastPolledAt: number | null;
|
|
1345
|
+
readonly registerAttempts: number;
|
|
1346
|
+
/**
|
|
1347
|
+
* Re-registrations issued because the `_00_query` row read as gone, since
|
|
1348
|
+
* the row was last seen. Paces the next one (see `applyMembership`).
|
|
1349
|
+
*/
|
|
1350
|
+
readonly viewLostCount: number;
|
|
1351
|
+
/** When the paced re-registration is due; null when none is pending. */
|
|
1352
|
+
readonly viewLostRetryAt: number | null;
|
|
1353
|
+
readonly telemetry: QueryTelemetry;
|
|
1354
|
+
}
|
|
1355
|
+
type OutboxStatus = 'pending' | 'acked';
|
|
1356
|
+
/** In-memory mirror of one `_00_pending_mutations` row plus its push progress. */
|
|
1357
|
+
interface OutboxItem {
|
|
1358
|
+
readonly id: string;
|
|
1359
|
+
readonly type: MutationEventType;
|
|
1360
|
+
readonly recordId: string;
|
|
1361
|
+
readonly table: string;
|
|
1362
|
+
readonly status: OutboxStatus;
|
|
1363
|
+
readonly ackedAt: number | null;
|
|
1364
|
+
readonly attempts: number;
|
|
1365
|
+
/**
|
|
1366
|
+
* A request carrying this row may have committed without the answer
|
|
1367
|
+
* reaching this client: it threw a transport error, or the row was loaded
|
|
1368
|
+
* from the store, so a session that died mid-push may have sent it. Its
|
|
1369
|
+
* CREATE then accepts the row already on the server when that row holds
|
|
1370
|
+
* what it would write (see `remoteBatch`). Absent means false.
|
|
1371
|
+
*/
|
|
1372
|
+
readonly inDoubt?: boolean;
|
|
1373
|
+
}
|
|
1374
|
+
type TabRole = 'solo' | 'leader' | 'follower';
|
|
1375
|
+
/** A debounced update accumulating locally until its flush writes the outbox row. */
|
|
1376
|
+
interface PendingWrite {
|
|
1377
|
+
readonly key: string;
|
|
1378
|
+
readonly table: string;
|
|
1379
|
+
readonly recordId: string;
|
|
1380
|
+
readonly data: Readonly<Record<string, unknown>>;
|
|
1381
|
+
readonly before: Readonly<Record<string, unknown>> | null;
|
|
1382
|
+
readonly firstAt: number;
|
|
1383
|
+
/** Its durable copy in `_00_pending_writes`; null when `flushOnHide` is off. */
|
|
1384
|
+
readonly mirrorId: string | null;
|
|
1385
|
+
}
|
|
1386
|
+
/**
|
|
1387
|
+
* A create or delete a channel peer sent, applied here before the server has
|
|
1388
|
+
* it (see `modules/channel`). Shown like an own optimistic write through the
|
|
1389
|
+
* overlay; when `expiresAt` passes it is either confirmed (the server's body
|
|
1390
|
+
* landed) or undone.
|
|
1391
|
+
*/
|
|
1392
|
+
interface PeerWrite {
|
|
1393
|
+
readonly kind: 'create' | 'delete';
|
|
1394
|
+
readonly table: string;
|
|
1395
|
+
readonly expiresAt: number;
|
|
1396
|
+
}
|
|
1397
|
+
interface SyncSlice {
|
|
1398
|
+
readonly health: SyncHealth;
|
|
1399
|
+
readonly consecutiveFailures: number;
|
|
1400
|
+
readonly hasSyncedOnce: boolean;
|
|
1401
|
+
readonly selfHealAttempts: number;
|
|
1402
|
+
readonly pollIdleStreak: number;
|
|
1403
|
+
readonly lastReconnectRefetchAt: number | null;
|
|
1404
|
+
readonly needsResubscribe: boolean;
|
|
1405
|
+
readonly fetchAttempts: number;
|
|
1406
|
+
readonly liveUuid: string | null;
|
|
1407
|
+
readonly liveTable: string | null;
|
|
1408
|
+
readonly lanes: LaneState;
|
|
1409
|
+
}
|
|
1410
|
+
interface ClientState {
|
|
1411
|
+
readonly sessionId: string | null;
|
|
1412
|
+
readonly userId: string | null;
|
|
1413
|
+
/** The principal the current session salt was minted for. */
|
|
1414
|
+
readonly saltUserId: string | null;
|
|
1415
|
+
/**
|
|
1416
|
+
* This page's secret, sent with every registration (`$config.owner`). An
|
|
1417
|
+
* anonymous view answers only to the secret it was registered with, so it
|
|
1418
|
+
* lives as long as the page's views: a reconnect keeps it, and a reload
|
|
1419
|
+
* that keeps the salt keeps it too.
|
|
1420
|
+
*/
|
|
1421
|
+
readonly ownerSecret: string | null;
|
|
1422
|
+
/** Latest bucket-switch target; an older switch that wakes up to a newer target skips. */
|
|
1423
|
+
readonly pendingBucket: string | null;
|
|
1424
|
+
readonly tabId: string;
|
|
1425
|
+
readonly tabRole: TabRole;
|
|
1426
|
+
readonly bucketId: string | null;
|
|
1427
|
+
readonly localReady: boolean;
|
|
1428
|
+
readonly primed: boolean;
|
|
1429
|
+
readonly queries: ReadonlyMap<QueryHash, QueryEntry>;
|
|
1430
|
+
/** Hashes whose local registration is in flight (dedupes concurrent `query()` calls). */
|
|
1431
|
+
readonly registering: ReadonlySet<QueryHash>;
|
|
1432
|
+
/** Re-read attempts per hash while the server reports a view as `materializing`. */
|
|
1433
|
+
readonly membershipReread: ReadonlyMap<QueryHash, number>;
|
|
1434
|
+
/** Local body versions (`_00_rv`) by encoded record id. */
|
|
1435
|
+
readonly versions: ReadonlyMap<string, number>;
|
|
1436
|
+
/**
|
|
1437
|
+
* What each durable `_00_view` row vouches for, by view key: its members
|
|
1438
|
+
* and subquery children. A body no row names is an orphan: it never paints
|
|
1439
|
+
* before the server answers and the GC deletes it.
|
|
1440
|
+
*/
|
|
1441
|
+
readonly views: ReadonlyMap<string, ReadonlyArray<string>>;
|
|
1442
|
+
readonly outbox: ReadonlyArray<OutboxItem>;
|
|
1443
|
+
readonly pendingWrites: ReadonlyMap<string, PendingWrite>;
|
|
1444
|
+
/** Channel peers' unconfirmed creates and deletes, by record id. */
|
|
1445
|
+
readonly peerWrites: ReadonlyMap<string, PeerWrite>;
|
|
1446
|
+
readonly failedCount: number;
|
|
1447
|
+
/** Queries whose render inputs changed since their last materialization. */
|
|
1448
|
+
readonly dirty: ReadonlySet<QueryHash>;
|
|
1449
|
+
/** Queries whose server membership must be re-read. */
|
|
1450
|
+
readonly membershipDirty: ReadonlySet<QueryHash>;
|
|
1451
|
+
readonly sync: SyncSlice;
|
|
1452
|
+
}
|
|
1453
|
+
//#endregion
|
|
1454
|
+
//#region src/modules/ref-tables.d.ts
|
|
1455
|
+
type RefMode = 'single' | 'dedicated';
|
|
1456
|
+
/**
|
|
1457
|
+
* Sentinel user id for unauthenticated clients when anonymous live queries are
|
|
1458
|
+
* enabled. Mirrors `ssp_protocol::ANON_AUTH_ID`. It carries no `user:` prefix
|
|
1459
|
+
* so it can never collide with a real user id (those arrive as `user:<id>`);
|
|
1460
|
+
* both sides resolve it to the shared `_00_list_ref_anon` table.
|
|
1461
|
+
*/
|
|
1462
|
+
//#endregion
|
|
1463
|
+
//#region src/query/env.d.ts
|
|
1464
|
+
/**
|
|
1465
|
+
* Static configuration the sagas read. Plain data, built once by the runtime
|
|
1466
|
+
* from `Sp00kyConfig`; sagas never see the config object itself.
|
|
1467
|
+
*/
|
|
1468
|
+
interface SagaEnv {
|
|
1469
|
+
readonly schema: SchemaStructure;
|
|
1470
|
+
readonly refMode: RefMode;
|
|
1471
|
+
readonly anonLive: boolean;
|
|
1472
|
+
readonly remoteTimeoutMs: number;
|
|
1473
|
+
readonly pushTimeoutMs: number;
|
|
1474
|
+
readonly outboxBatchSize: number;
|
|
1475
|
+
readonly degradeAfter: number;
|
|
1476
|
+
readonly materializeDebounceMs: number;
|
|
1477
|
+
readonly pollBaseMs: number;
|
|
1478
|
+
readonly defaultTtlMs: number;
|
|
1479
|
+
}
|
|
1480
|
+
//#endregion
|
|
1481
|
+
//#region src/mutation/rows.d.ts
|
|
1482
|
+
interface FailedMutationRow {
|
|
1483
|
+
id: string;
|
|
1484
|
+
mutationType: MutationEventType;
|
|
1485
|
+
recordId: string;
|
|
1486
|
+
tableName: string;
|
|
1487
|
+
data?: Record<string, unknown>;
|
|
1488
|
+
beforeRecord?: Record<string, unknown> | null;
|
|
1489
|
+
error: {
|
|
1490
|
+
message: string;
|
|
1491
|
+
kind: 'application' | 'unreplayable';
|
|
1492
|
+
};
|
|
1493
|
+
attempts: number;
|
|
1494
|
+
createdAt: number;
|
|
1495
|
+
failedAt: number;
|
|
1496
|
+
revert: 'full' | 'partial' | 'none';
|
|
1497
|
+
}
|
|
1498
|
+
/**
|
|
1499
|
+
* Parse a record id READ BACK FROM THE STORE, stripping SurrealDB's `⟨⟩`
|
|
1500
|
+
* escaping (outbox ids contain `_`, so they come back escaped).
|
|
1501
|
+
*/
|
|
1502
|
+
//#endregion
|
|
1503
|
+
//#region src/kernel/interpreter.d.ts
|
|
1504
|
+
/** The five adapters plus the pure ports, as the interpreter sees them. */
|
|
1505
|
+
interface Adapters {
|
|
1506
|
+
local: Pick<LocalStore, 'query' | 'execute' | 'select' | 'getById' | 'upsert' | 'delete'> & {
|
|
1507
|
+
readonly epoch: number;
|
|
1508
|
+
};
|
|
1509
|
+
remote: {
|
|
1510
|
+
queryResponses(sql: string, vars?: Record<string, unknown>): Promise<StatementResult[]>;
|
|
1511
|
+
/**
|
|
1512
|
+
* Subscribe to `LIVE SELECT * FROM <table>`; the callback receives the
|
|
1513
|
+
* changed query hashes, plus the changed rows themselves when the
|
|
1514
|
+
* subscription was opened with the body joined on (`liveInlineBodies`).
|
|
1515
|
+
*/
|
|
1516
|
+
live(table: string, onChange: (hashes: string[], rows?: InlineRow[], deltas?: EdgeDelta[]) => void): Promise<string>;
|
|
1517
|
+
kill(uuid: string): Promise<void>;
|
|
1518
|
+
};
|
|
1519
|
+
ssp: {
|
|
1520
|
+
registerQueryPlan(plan: {
|
|
1521
|
+
queryHash: string;
|
|
1522
|
+
surql: string;
|
|
1523
|
+
params: Record<string, unknown>;
|
|
1524
|
+
ttl: Duration;
|
|
1525
|
+
lastActiveAt: Date;
|
|
1526
|
+
localArray: [];
|
|
1527
|
+
remoteArray: [];
|
|
1528
|
+
meta: {
|
|
1529
|
+
tableName: string;
|
|
1530
|
+
involvedTables?: string[];
|
|
1531
|
+
};
|
|
1532
|
+
}): StreamUpdate | undefined;
|
|
1533
|
+
unregisterQueryPlan(hash: string): void;
|
|
1534
|
+
ingestMany(records: IngestRecord[]): unknown;
|
|
1535
|
+
};
|
|
1536
|
+
timers: {
|
|
1537
|
+
set(key: string, ms: number, fire: () => void): void;
|
|
1538
|
+
clear(key: string): void;
|
|
1539
|
+
};
|
|
1540
|
+
clock: {
|
|
1541
|
+
now(): number;
|
|
1542
|
+
};
|
|
1543
|
+
ids: Record<IdScope, () => string>;
|
|
1544
|
+
hash(input: string): Promise<string>;
|
|
1545
|
+
services: ServiceCalls;
|
|
1546
|
+
}
|
|
1547
|
+
/** What the interpreter needs from the runtime: state, waiting, emitting, dispatching. */
|
|
1548
|
+
//#endregion
|
|
1549
|
+
//#region src/client/runtime.d.ts
|
|
1550
|
+
interface RuntimeOptions {
|
|
1551
|
+
env: SagaEnv;
|
|
1552
|
+
adapters: Adapters;
|
|
1553
|
+
logger: Logger$1;
|
|
1554
|
+
tabId: string;
|
|
1555
|
+
initialState?: ClientState;
|
|
1556
|
+
}
|
|
1557
|
+
/**
|
|
1558
|
+
* The one effectful object of the engine: holds the state, runs sagas on
|
|
1559
|
+
* lanes, fires timers, fans events out to subscribers and schedules
|
|
1560
|
+
* materialization for dirty queries. No decision logic lives here.
|
|
1561
|
+
*/
|
|
1562
|
+
declare class Runtime {
|
|
1563
|
+
private stateValue;
|
|
1564
|
+
private readonly interpret;
|
|
1565
|
+
private readonly env;
|
|
1566
|
+
private readonly adapters;
|
|
1567
|
+
private readonly logger;
|
|
1568
|
+
private readonly serialLanes;
|
|
1569
|
+
private readonly dedupeLanes;
|
|
1570
|
+
private readonly waiters;
|
|
1571
|
+
private readonly recordSubs;
|
|
1572
|
+
private readonly statusSubs;
|
|
1573
|
+
private readonly authoritySubs;
|
|
1574
|
+
private readonly lastStatus;
|
|
1575
|
+
private readonly listeners;
|
|
1576
|
+
private readonly scheduledMaterialize;
|
|
1577
|
+
/** When each query last materialized, for the leading-edge throttle in `setState`. */
|
|
1578
|
+
private readonly materializedAt;
|
|
1579
|
+
private readonly timerKeys;
|
|
1580
|
+
private lastActivity;
|
|
1581
|
+
private lastHealth;
|
|
1582
|
+
private disposed;
|
|
1583
|
+
constructor(opts: RuntimeOptions);
|
|
1584
|
+
get state(): ClientState;
|
|
1585
|
+
/** Run a saga, optionally on a lane. Rejections propagate to the caller. */
|
|
1586
|
+
run<R>(saga: Saga<R>, opts?: {
|
|
1587
|
+
lane?: Lane;
|
|
1588
|
+
signal?: AbortSignal;
|
|
1589
|
+
}): Promise<R>;
|
|
1590
|
+
/** Route an event to its saga. Never rejects: failures are logged. */
|
|
1591
|
+
dispatch(event: RuntimeEvent): Promise<void>;
|
|
1592
|
+
private setState;
|
|
1593
|
+
waitFor(until: (s: ClientState) => boolean, signal?: AbortSignal): Promise<void>;
|
|
1594
|
+
/** Deliver an outbound event to its subscribers and listeners. */
|
|
1595
|
+
emit(event: OutEvent): void;
|
|
1596
|
+
private notify;
|
|
1597
|
+
private safely;
|
|
1598
|
+
/** Observe outbound events by type (`'*'` for all). */
|
|
1599
|
+
on(type: OutEvent['type'] | '*', cb: (event: OutEvent) => void): () => void;
|
|
1600
|
+
subscribe(hash: QueryHash, cb: QueryUpdateCallback, options?: {
|
|
1601
|
+
immediate?: boolean;
|
|
1602
|
+
}): () => void;
|
|
1603
|
+
subscribeStatus(hash: QueryHash, cb: QueryStatusCallback, options?: {
|
|
1604
|
+
immediate?: boolean;
|
|
1605
|
+
}): () => void;
|
|
1606
|
+
subscribeAuthority(hash: QueryHash, cb: QueryAuthorityCallback, options?: {
|
|
1607
|
+
immediate?: boolean;
|
|
1608
|
+
}): () => void;
|
|
1609
|
+
/** Apply a reducer outside a saga (facade conveniences such as timing reports). */
|
|
1610
|
+
update(reducer: (s: ClientState) => ClientState): void;
|
|
1611
|
+
dispose(): void;
|
|
1612
|
+
}
|
|
1613
|
+
//#endregion
|
|
1614
|
+
//#region src/services/tabs/coordinator.d.ts
|
|
1615
|
+
interface CoordinatorHooks {
|
|
1616
|
+
/** Become the store owner: spawn the worker, open the pool under the given
|
|
1617
|
+
* per-leadership lock. Returns the resulting health for db-ready relays.
|
|
1618
|
+
* `resumeHeld` = keep the existing live worker (broker-restart path). */
|
|
1619
|
+
adoptOwner(bucketId: string, opts: {
|
|
1620
|
+
workerLockName: string;
|
|
1621
|
+
allowMemoryFallback: boolean;
|
|
1622
|
+
forceTakeover: boolean;
|
|
1623
|
+
resumeHeld: boolean;
|
|
1624
|
+
}): Promise<StorageHealth>;
|
|
1625
|
+
/** Attach to a leader's worker through `dbPort`. */
|
|
1626
|
+
adoptAttached(dbPort: MessagePort, snapshot: {
|
|
1627
|
+
bucketId: string;
|
|
1628
|
+
storageHealth: StorageHealth;
|
|
1629
|
+
leadershipId: number;
|
|
1630
|
+
}): Promise<void>;
|
|
1631
|
+
/** We were leader and got demoted (zombie thaw / stale promotion): tear the
|
|
1632
|
+
* owned worker down so its SAH handles free up. */
|
|
1633
|
+
releaseOwnership(): Promise<void>;
|
|
1634
|
+
/** The leader (or its port) is gone; queue/park ops until a new role lands. */
|
|
1635
|
+
onLeaderLost(reason: string): void;
|
|
1636
|
+
/** Leader side: forward a follower's dbPort into the owned worker. */
|
|
1637
|
+
exposeClientPort(clientId: string, port: MessagePort): Promise<void>;
|
|
1638
|
+
removeClientPort(clientId: string): Promise<void>;
|
|
1639
|
+
/** Sync layer role changes (implemented in the sync module). */
|
|
1640
|
+
/** Synchronous leader WIRING. Must not block: the role is published and
|
|
1641
|
+
* `leader-ready` is sent right after it returns. */
|
|
1642
|
+
becomeSyncLeader(hub: LeaderSyncHub): void;
|
|
1643
|
+
/** The blocking half of the leader handover (outbox drain, LIVE restart),
|
|
1644
|
+
* run in the background once the tab is already a working leader. */
|
|
1645
|
+
resumeSyncLeaderDuties(): Promise<void>;
|
|
1646
|
+
becomeSyncFollower(forwarder: SyncForwarder): void;
|
|
1647
|
+
becomeSyncSolo(): void;
|
|
1648
|
+
/** Current storage health, for db-ready sent to late-joining followers. */
|
|
1649
|
+
currentStorageHealth(): StorageHealth;
|
|
1650
|
+
}
|
|
1651
|
+
/** Leader-side fan-out surface handed to the sync layer. The sync router
|
|
1652
|
+
* (modules/sync/tab-router.ts) registers itself as the message handler. */
|
|
1653
|
+
declare class LeaderSyncHub {
|
|
1654
|
+
readonly leadershipId: number;
|
|
1655
|
+
private logger;
|
|
1656
|
+
private followers;
|
|
1657
|
+
private seq;
|
|
1658
|
+
onFollowerMessage: ((tabId: TabId, msg: FollowerToLeaderMessage) => void) | null;
|
|
1659
|
+
onFollowerDetached: ((tabId: TabId) => void) | null;
|
|
1660
|
+
constructor(leadershipId: number, logger: Logger$1);
|
|
1661
|
+
attach(tabId: TabId, port: MessagePort): void;
|
|
1662
|
+
detach(tabId: TabId): void;
|
|
1663
|
+
detachAll(): void;
|
|
1664
|
+
sendTo(tabId: TabId, msg: LeaderToFollowerMessage): void;
|
|
1665
|
+
broadcast(msg: LeaderToFollowerMessage, exceptTabId?: TabId): void;
|
|
1666
|
+
/** Stamped ingest relay; seq lets followers detect gaps. */
|
|
1667
|
+
relayIngest(tuples: IngestTuple[], exceptTabId?: TabId): void;
|
|
1668
|
+
get followerCount(): number;
|
|
1669
|
+
get relayedBatches(): number;
|
|
1670
|
+
}
|
|
1671
|
+
/** Follower half of the syncPort. Queues while detached (leaderless window)
|
|
1672
|
+
* and flushes on rebind; a lost-in-flight mutation notify is additionally
|
|
1673
|
+
* backstopped by the new leader reloading the shared outbox from the store. */
|
|
1674
|
+
declare class SyncForwarder {
|
|
1675
|
+
private tabId;
|
|
1676
|
+
private port;
|
|
1677
|
+
private queued;
|
|
1678
|
+
onLeaderMessage: ((msg: LeaderToFollowerMessage) => void) | null;
|
|
1679
|
+
constructor(tabId: TabId);
|
|
1680
|
+
rebind(port: MessagePort): void;
|
|
1681
|
+
unbind(): void;
|
|
1682
|
+
private post;
|
|
1683
|
+
mutationEnqueued(mutationId: string): void;
|
|
1684
|
+
/** An optimistic write this tab just ingested. Deliberately NOT queued while
|
|
1685
|
+
* detached: a new leader primes its circuit from the shared store, which
|
|
1686
|
+
* already holds the row, and replaying a stale tuple at it later would put
|
|
1687
|
+
* an older `_00_rv` in its version memo. */
|
|
1688
|
+
ingest(tuples: IngestTuple[]): void;
|
|
1689
|
+
requestPoll(): void;
|
|
1690
|
+
}
|
|
1691
|
+
declare class TabsCoordinator {
|
|
1692
|
+
private deps;
|
|
1693
|
+
role: TabRole$1;
|
|
1694
|
+
leadershipId: number;
|
|
1695
|
+
leaderTabId: TabId | null;
|
|
1696
|
+
brokerRole: 'pending' | TabRole$1;
|
|
1697
|
+
/** Wall time from `become-leader` to `leader-ready` on the last promotion.
|
|
1698
|
+
* Reported in the DevTools role-change event: a slow store adopt (OPFS pool
|
|
1699
|
+
* contention after the previous leader died) shows up here as seconds. */
|
|
1700
|
+
lastPromotionMs: number | null;
|
|
1701
|
+
private fingerprint;
|
|
1702
|
+
private bucketId;
|
|
1703
|
+
private broker;
|
|
1704
|
+
private hub;
|
|
1705
|
+
private forwarder;
|
|
1706
|
+
private roleListeners;
|
|
1707
|
+
private startResolve;
|
|
1708
|
+
private startReject;
|
|
1709
|
+
/** Ports received before start() resolves or between roles. */
|
|
1710
|
+
private promotionChain;
|
|
1711
|
+
private closed;
|
|
1712
|
+
constructor(deps: {
|
|
1713
|
+
tabId: TabId;
|
|
1714
|
+
fingerprint: string;
|
|
1715
|
+
hooks: CoordinatorHooks;
|
|
1716
|
+
logger: Logger$1;
|
|
1717
|
+
/** Fired on pagehide while this tab leads: last-chance OPFS release. */
|
|
1718
|
+
onLeaderPageHide?: () => void;
|
|
1719
|
+
});
|
|
1720
|
+
/** Serialize role transitions; each is small but async (worker opens). */
|
|
1721
|
+
private enqueue;
|
|
1722
|
+
onRoleChange(cb: (role: TabRole$1) => void): () => void;
|
|
1723
|
+
private setRole;
|
|
1724
|
+
/** Connect the broker and resolve once this tab has a usable store role.
|
|
1725
|
+
* Rejects when no role lands in time; the caller then boots solo. */
|
|
1726
|
+
start(bucketId: string): Promise<TabRole$1>;
|
|
1727
|
+
/** Bucket switch: leave the old namespace, join the new one. Resolves when
|
|
1728
|
+
* a role lands in the new namespace. */
|
|
1729
|
+
moveToBucket(bucketId: string): Promise<TabRole$1>;
|
|
1730
|
+
private promote;
|
|
1731
|
+
private demote;
|
|
1732
|
+
private tabLock;
|
|
1733
|
+
private teardownLeader;
|
|
1734
|
+
private teardownFollower;
|
|
1735
|
+
private serveFollower;
|
|
1736
|
+
private attachToLeader;
|
|
1737
|
+
private handleLeaderGone;
|
|
1738
|
+
private fallbackToSolo;
|
|
1739
|
+
get syncHub(): LeaderSyncHub | null;
|
|
1740
|
+
get syncForwarder(): SyncForwarder | null;
|
|
1741
|
+
get tabId(): TabId;
|
|
1742
|
+
stop(): Promise<void>;
|
|
1743
|
+
}
|
|
1744
|
+
//#endregion
|
|
1745
|
+
//#region src/services/blobs/blob-store.d.ts
|
|
1746
|
+
/**
|
|
1747
|
+
* Byte storage for cached bucket files.
|
|
1748
|
+
*
|
|
1749
|
+
* The default implementation is OPFS. Bucket files never arrive over HTTP in
|
|
1750
|
+
* this client — `BucketHandle.get()` is a SurrealQL RPC on the sync socket — so
|
|
1751
|
+
* neither the browser's HTTP cache nor the Cache API can hold them. We persist
|
|
1752
|
+
* the bytes ourselves, and OPFS is the cheapest place to put them: a read is
|
|
1753
|
+
* `getFile()` → a disk-backed lazy `File` that `URL.createObjectURL` can serve
|
|
1754
|
+
* without ever moving the bytes through the JS heap.
|
|
1755
|
+
*
|
|
1756
|
+
* Layout is real nested directories rather than one hashed filename:
|
|
1757
|
+
*
|
|
1758
|
+
* sp00ky-blobs/<namespace>/<bucket>/<...path segments>
|
|
1759
|
+
*
|
|
1760
|
+
* That costs a `getDirectoryHandle` per segment on write, and buys the property
|
|
1761
|
+
* the whole orphan story rests on: the full `(bucket, path)` key is recoverable
|
|
1762
|
+
* from a directory walk alone. The `_00_blob` manifest can therefore be wiped
|
|
1763
|
+
* (memory fallback, SQLite pool wipe, IndexedDB corruption recovery) and be
|
|
1764
|
+
* rebuilt from disk instead of taking the cached bytes down with it.
|
|
1765
|
+
*/
|
|
1766
|
+
/** Identifies one cached file: the bucket it lives in and its path within. */
|
|
1767
|
+
interface BlobKey {
|
|
1768
|
+
bucket: string;
|
|
1769
|
+
path: string;
|
|
1770
|
+
}
|
|
1771
|
+
/** What a directory walk can tell us about a stored file, with no manifest. */
|
|
1772
|
+
interface BlobStat {
|
|
1773
|
+
key: BlobKey;
|
|
1774
|
+
size: number;
|
|
1775
|
+
/** File mtime. Seeds `lastAccess` when a manifest row has to be rebuilt. */
|
|
1776
|
+
mtime: number;
|
|
1777
|
+
}
|
|
1778
|
+
interface BlobStore {
|
|
1779
|
+
/** False for {@link MemoryBlobStore} and for OPFS-less environments: the
|
|
1780
|
+
* cache still dedupes and serves within a tab, but nothing survives reload. */
|
|
1781
|
+
readonly persistent: boolean;
|
|
1782
|
+
/** Namespace (the local bucketId) all keys are resolved under. */
|
|
1783
|
+
readonly namespace: string;
|
|
1784
|
+
read(key: BlobKey): Promise<Blob | null>;
|
|
1785
|
+
/** Returns the number of bytes written. Throws on quota exhaustion. */
|
|
1786
|
+
write(key: BlobKey, bytes: Blob): Promise<number>;
|
|
1787
|
+
remove(key: BlobKey): Promise<void>;
|
|
1788
|
+
/** Every committed file under the current namespace. Sweeps torn writes. */
|
|
1789
|
+
list(): Promise<BlobStat[]>;
|
|
1790
|
+
/** Drop the whole namespace (sign-out with `clearOnSignOut`, or a reset). */
|
|
1791
|
+
clear(): Promise<void>;
|
|
1792
|
+
/** Point at another namespace. Does not touch the bytes of the old one. */
|
|
1793
|
+
setNamespace(namespace: string): void;
|
|
1794
|
+
}
|
|
1795
|
+
//#endregion
|
|
1796
|
+
//#region src/services/blobs/blob-manifest.d.ts
|
|
1797
|
+
interface BlobEntry {
|
|
1798
|
+
/** `${bucket}/${path}` — also the `_00_blob` row id. */
|
|
1799
|
+
id: string;
|
|
1800
|
+
bucket: string;
|
|
1801
|
+
path: string;
|
|
1802
|
+
size: number;
|
|
1803
|
+
contentType: string;
|
|
1804
|
+
createdAt: number;
|
|
1805
|
+
lastAccess: number;
|
|
1806
|
+
hits: number;
|
|
1807
|
+
/** Exempt from pressure eviction. Never expires on its own. */
|
|
1808
|
+
pinned: boolean;
|
|
1809
|
+
}
|
|
1810
|
+
declare class BlobManifest {
|
|
1811
|
+
private local;
|
|
1812
|
+
private entries;
|
|
1813
|
+
/** Ids whose in-memory state has not been written back yet. */
|
|
1814
|
+
private dirty;
|
|
1815
|
+
private removed;
|
|
1816
|
+
private flushing;
|
|
1817
|
+
constructor(local: LocalStore);
|
|
1818
|
+
/**
|
|
1819
|
+
* Hydrate from the rows matching `keys`. Ids come from the OPFS listing, so
|
|
1820
|
+
* this never needs a full-table scan (and therefore never needs a QueryPlan).
|
|
1821
|
+
* Any read failure yields an empty manifest: reconcile then rebuilds every
|
|
1822
|
+
* row from disk, which is exactly the desired degradation.
|
|
1823
|
+
*/
|
|
1824
|
+
load(ids: string[]): Promise<void>;
|
|
1825
|
+
get(key: BlobKey): BlobEntry | undefined;
|
|
1826
|
+
getById(id: string): BlobEntry | undefined;
|
|
1827
|
+
all(): BlobEntry[];
|
|
1828
|
+
totalBytes(): number;
|
|
1829
|
+
pinnedBytes(): number;
|
|
1830
|
+
put(entry: BlobEntry): void;
|
|
1831
|
+
touch(id: string, now: number): void;
|
|
1832
|
+
setPinned(id: string, pinned: boolean): boolean;
|
|
1833
|
+
remove(id: string): void;
|
|
1834
|
+
/** Forget everything without scheduling deletes — for a bucket switch, where
|
|
1835
|
+
* the rows belong to the store we are leaving and must stay put. */
|
|
1836
|
+
reset(): void;
|
|
1837
|
+
hasPendingWrites(): boolean;
|
|
1838
|
+
/**
|
|
1839
|
+
* Write back pending changes. Serialized: a second concurrent flush awaits
|
|
1840
|
+
* the first rather than racing it into the same rows. Failures are swallowed
|
|
1841
|
+
* on purpose — a lost metadata write costs an LRU timestamp, and the entry is
|
|
1842
|
+
* rebuilt from disk on the next reconcile.
|
|
1843
|
+
*/
|
|
1844
|
+
flush(): Promise<void>;
|
|
1845
|
+
private doFlush;
|
|
1846
|
+
}
|
|
1847
|
+
//#endregion
|
|
1848
|
+
//#region src/services/blobs/blob-cache.d.ts
|
|
1849
|
+
interface BlobUrlLease {
|
|
1850
|
+
url: string;
|
|
1851
|
+
release(): void;
|
|
1852
|
+
}
|
|
1853
|
+
interface BlobReadOptions {
|
|
1854
|
+
/** Write through to L1 on a miss. Default true. */
|
|
1855
|
+
persist?: boolean;
|
|
1856
|
+
/** Mark the entry exempt from pressure eviction. */
|
|
1857
|
+
pin?: boolean;
|
|
1858
|
+
/**
|
|
1859
|
+
* Default `'never'`: a bucket path is treated as immutable, which is how the
|
|
1860
|
+
* client writes them (`crypto.randomUUID() + ext`). `'head'` spends a remote
|
|
1861
|
+
* `head()` to compare sizes before trusting L1.
|
|
1862
|
+
*/
|
|
1863
|
+
revalidate?: 'never' | 'head';
|
|
1864
|
+
/** Skip L0/L1 entirely and refill from remote. Backs `refetch()`. */
|
|
1865
|
+
reload?: boolean;
|
|
1866
|
+
}
|
|
1867
|
+
interface BlobCacheStats {
|
|
1868
|
+
entries: number;
|
|
1869
|
+
totalBytes: number;
|
|
1870
|
+
budgetBytes: number;
|
|
1871
|
+
pinnedBytes: number;
|
|
1872
|
+
evictedEntries: number;
|
|
1873
|
+
evictedBytes: number;
|
|
1874
|
+
reconciledEntries: number;
|
|
1875
|
+
hits: number;
|
|
1876
|
+
misses: number;
|
|
1877
|
+
persistent: boolean;
|
|
1878
|
+
/** True when pinned bytes alone exceed the budget: new entries stop being
|
|
1879
|
+
* written rather than pinned ones being thrown away. */
|
|
1880
|
+
persistPaused: boolean;
|
|
1881
|
+
}
|
|
1882
|
+
interface BlobCacheOptions {
|
|
1883
|
+
store: BlobStore;
|
|
1884
|
+
manifest: BlobManifest;
|
|
1885
|
+
/** L2 read. Resolves to null when the file does not exist remotely. */
|
|
1886
|
+
fetchRemote(key: BlobKey): Promise<Blob | null>;
|
|
1887
|
+
/** L2 metadata, for `revalidate: 'head'`. */
|
|
1888
|
+
headRemote?(key: BlobKey): Promise<Record<string, unknown> | null>;
|
|
1889
|
+
logger: Logger$1;
|
|
1890
|
+
maxBytes: number;
|
|
1891
|
+
now?: () => number;
|
|
1892
|
+
/** Injected so the URL layer is exercisable off a DOM (node tests). */
|
|
1893
|
+
urls?: {
|
|
1894
|
+
create(blob: Blob): string;
|
|
1895
|
+
revoke(url: string): void;
|
|
1896
|
+
};
|
|
1897
|
+
}
|
|
1898
|
+
declare class BlobCache {
|
|
1899
|
+
private readonly store;
|
|
1900
|
+
private readonly manifest;
|
|
1901
|
+
private readonly fetchRemote;
|
|
1902
|
+
private readonly headRemote?;
|
|
1903
|
+
private readonly logger;
|
|
1904
|
+
private readonly now;
|
|
1905
|
+
private readonly urlFactory;
|
|
1906
|
+
private maxBytes;
|
|
1907
|
+
private persistPaused;
|
|
1908
|
+
/** Set after a quota failure survives one forced eviction. */
|
|
1909
|
+
private persistDisabled;
|
|
1910
|
+
private readonly urls;
|
|
1911
|
+
/** Ids at zero references, oldest first — the hot-URL window. */
|
|
1912
|
+
private idleUrls;
|
|
1913
|
+
private readonly inflight;
|
|
1914
|
+
private flushTimer;
|
|
1915
|
+
private readonly onPageHide;
|
|
1916
|
+
/**
|
|
1917
|
+
* Resolves once the manifest has been reconciled against disk. Reads await
|
|
1918
|
+
* it, so `start()` does NOT have to be awaited on the boot path — blocking
|
|
1919
|
+
* boot on an OPFS directory walk delayed the WebSocket connect (and with it
|
|
1920
|
+
* the connection supervisor) for no benefit.
|
|
1921
|
+
*/
|
|
1922
|
+
private ready;
|
|
1923
|
+
private hits;
|
|
1924
|
+
private misses;
|
|
1925
|
+
private evictedEntries;
|
|
1926
|
+
private evictedBytes;
|
|
1927
|
+
private reconciledEntries;
|
|
1928
|
+
constructor(opts: BlobCacheOptions);
|
|
1929
|
+
/** Coalesce manifest write-back. Metadata only, so losing the tail costs an
|
|
1930
|
+
* LRU timestamp that reconcile reseeds from the file mtime. */
|
|
1931
|
+
private scheduleFlush;
|
|
1932
|
+
/**
|
|
1933
|
+
* Resolve the bytes for `key`, filling L1 on the way when `persist` is on.
|
|
1934
|
+
* Returns null when the file does not exist remotely and is not cached.
|
|
1935
|
+
*/
|
|
1936
|
+
read(key: BlobKey, options?: BlobReadOptions): Promise<Blob | null>;
|
|
1937
|
+
/**
|
|
1938
|
+
* An object URL for `key`, refcounted. Callers MUST `release()`; the URL is
|
|
1939
|
+
* revoked once the last holder lets go and it falls out of the hot window.
|
|
1940
|
+
*/
|
|
1941
|
+
acquireUrl(key: BlobKey, options?: BlobReadOptions): Promise<BlobUrlLease | null>;
|
|
1942
|
+
private lease;
|
|
1943
|
+
private releaseUrl;
|
|
1944
|
+
private revokeUrl;
|
|
1945
|
+
/** L1 lookup with the size check that catches torn and cross-tab writes. */
|
|
1946
|
+
private readLocal;
|
|
1947
|
+
/** True when the remote agrees with the cached size, or cannot be reached. */
|
|
1948
|
+
private headMatches;
|
|
1949
|
+
private fetchDeduped;
|
|
1950
|
+
private persist;
|
|
1951
|
+
private writeThrough;
|
|
1952
|
+
/** Forget one path everywhere. Called on `bucket.put()`/`bucket.delete()`. */
|
|
1953
|
+
invalidate(key: BlobKey): Promise<void>;
|
|
1954
|
+
private dropLocal;
|
|
1955
|
+
setPinned(key: BlobKey, pinned: boolean): void;
|
|
1956
|
+
/**
|
|
1957
|
+
* Bring total bytes under budget by dropping the least recently used
|
|
1958
|
+
* entries. Pinned entries and anything with a live object URL are skipped —
|
|
1959
|
+
* evicting bytes that a mounted `<img>` is displaying would blank it.
|
|
1960
|
+
*/
|
|
1961
|
+
private enforceBudget;
|
|
1962
|
+
/** Evict LRU-first until at or below `target`. Returns the resulting total. */
|
|
1963
|
+
private evictTo;
|
|
1964
|
+
/**
|
|
1965
|
+
* Rebuild the manifest from what is actually on disk. OPFS wins on existence
|
|
1966
|
+
* in both directions: files with no row get a row (seeded from mtime), rows
|
|
1967
|
+
* are only loaded for files that exist, and torn `.part-` writes are swept by
|
|
1968
|
+
* the walk itself.
|
|
1969
|
+
*
|
|
1970
|
+
* Rows whose file vanished outside our control (a browser origin eviction)
|
|
1971
|
+
* are left in `_00_blob`. They are inert — `load()` only ever asks for ids it
|
|
1972
|
+
* found on disk — and are overwritten if that path is cached again.
|
|
1973
|
+
*/
|
|
1974
|
+
reconcile(): Promise<void>;
|
|
1975
|
+
/** Warm the cache for offline use. Skips anything already cached. */
|
|
1976
|
+
prefetch(keys: BlobKey[]): Promise<void>;
|
|
1977
|
+
/** Bind to the boot bucket and hydrate the manifest from disk. Separate from
|
|
1978
|
+
* {@link setNamespace} because boot must reconcile even when the namespace
|
|
1979
|
+
* it lands on is the one the store was constructed with. */
|
|
1980
|
+
start(namespace: string): Promise<void>;
|
|
1981
|
+
/** Repoint at another local bucket. The bytes of the old one stay on disk so
|
|
1982
|
+
* switching back (or signing back in) is still warm. */
|
|
1983
|
+
setNamespace(namespace: string): Promise<void>;
|
|
1984
|
+
setMaxBytes(maxBytes: number): void;
|
|
1985
|
+
/** Delete every cached byte in the current namespace. */
|
|
1986
|
+
clear(): Promise<void>;
|
|
1987
|
+
flush(): Promise<void>;
|
|
1988
|
+
/** Flush metadata and drop every object URL. Must run before the local store
|
|
1989
|
+
* closes — the flush writes through it. */
|
|
1990
|
+
close(): Promise<void>;
|
|
1991
|
+
stats(): BlobCacheStats;
|
|
1992
|
+
}
|
|
1993
|
+
//#endregion
|
|
1994
|
+
//#region src/client/services.d.ts
|
|
1995
|
+
/** Everything the facade talks to besides the runtime. */
|
|
1996
|
+
interface Services<S extends SchemaStructure> {
|
|
1997
|
+
logger: Logger$1;
|
|
1998
|
+
/** What the logger wrote, for the DevTools Logs tab. Absent in test fakes. */
|
|
1999
|
+
logTap?: LogTap;
|
|
2000
|
+
local: LocalStore;
|
|
2001
|
+
remote: RemoteDatabaseService;
|
|
2002
|
+
connectionSupervisor: ConnectionSupervisor;
|
|
2003
|
+
blobs: BlobCache;
|
|
2004
|
+
persistence: PersistenceClient;
|
|
2005
|
+
streamProcessor: StreamProcessorService;
|
|
2006
|
+
migrator: LocalMigrator;
|
|
2007
|
+
crdt: CrdtManager;
|
|
2008
|
+
auth: AuthService<S>;
|
|
2009
|
+
tabs: TabsCoordinator | null;
|
|
2010
|
+
tabsUnsupportedReason: string | undefined;
|
|
2011
|
+
tabId: string;
|
|
2012
|
+
}
|
|
2013
|
+
/** What the services need back from the runtime once it exists. */
|
|
2014
|
+
//#endregion
|
|
2015
|
+
//#region src/utils/blurhash.d.ts
|
|
2016
|
+
/**
|
|
2017
|
+
* Blurhash generation settings. `true` enables with the defaults below, `false`
|
|
2018
|
+
* disables. Resolution order for a put: per-call option > client config >
|
|
2019
|
+
* default ON. See {@link Sp00kyConfig.blurhash}.
|
|
2020
|
+
*/
|
|
2021
|
+
type BlurhashSetting = boolean | BlurhashEncodeOptions;
|
|
2022
|
+
interface BlurhashEncodeOptions {
|
|
2023
|
+
/** Horizontal detail components, 1-9. Defaults to 4. */
|
|
2024
|
+
componentX?: number;
|
|
2025
|
+
/** Vertical detail components, 1-9. Defaults to 3. */
|
|
2026
|
+
componentY?: number;
|
|
2027
|
+
}
|
|
2028
|
+
/**
|
|
2029
|
+
* Where an image's blurhash lives: a tiny sidecar object in the same bucket.
|
|
2030
|
+
* Buckets have no per-object metadata channel (`put` is just `.put($content)`),
|
|
2031
|
+
* so the hash for `covers/x_t.webp` is the text object `covers/x_t.webp.bh`.
|
|
2032
|
+
*/
|
|
2033
|
+
declare function blurhashSidecarPath(path: string): string;
|
|
2034
|
+
/** Extensions `bucket.put` treats as images worth hashing. */
|
|
2035
|
+
declare const BLURHASH_IMAGE_EXTENSIONS: readonly ["webp", "png", "jpg", "jpeg", "gif", "avif", "bmp"];
|
|
2036
|
+
declare function isImagePath(path: string): boolean;
|
|
2037
|
+
/**
|
|
2038
|
+
* Decode `content` as an image and compute its blurhash. Browser-only: returns
|
|
2039
|
+
* null (never throws) when image decoding is unavailable (node, workers without
|
|
2040
|
+
* canvas), when the bytes are not a decodable image, or on any other failure —
|
|
2041
|
+
* a missing hash must never break the upload that triggered it.
|
|
2042
|
+
*/
|
|
2043
|
+
declare function encodeImageToBlurhash(content: string | Uint8Array | Blob, options?: BlurhashEncodeOptions): Promise<string | null>;
|
|
2044
|
+
//#endregion
|
|
2045
|
+
//#region src/client/bucket-handle.d.ts
|
|
2046
|
+
/** Coerce whatever the `.get()` RPC hands back into a Blob. */
|
|
2047
|
+
declare function bucketContentToBlob(content: unknown): Blob | null;
|
|
2048
|
+
interface BucketPutOptions {
|
|
2049
|
+
/** Override the client-level {@link Sp00kyConfig.blurhash} setting for this put. */
|
|
2050
|
+
blurhash?: BlurhashSetting;
|
|
2051
|
+
}
|
|
2052
|
+
interface BucketPutResult {
|
|
2053
|
+
/** The computed blurhash when the content was a hashable image; else null. */
|
|
2054
|
+
blurhash: string | null;
|
|
2055
|
+
}
|
|
2056
|
+
interface BucketHandleSettings {
|
|
2057
|
+
blurhash?: BlurhashSetting;
|
|
2058
|
+
logger?: {
|
|
2059
|
+
warn: (obj: unknown, msg?: string) => void;
|
|
2060
|
+
};
|
|
2061
|
+
/** The bucket's backend as generated (`'r2'`: files live with the SSP). */
|
|
2062
|
+
backend?: string;
|
|
2063
|
+
/** {@link Sp00kyConfig.files}: where `r2` bucket files are read and written. */
|
|
2064
|
+
files?: {
|
|
2065
|
+
endpoint?: string;
|
|
2066
|
+
};
|
|
2067
|
+
}
|
|
2068
|
+
/** A handle's settings from the client config and the bucket's generated schema. */
|
|
2069
|
+
|
|
1057
2070
|
declare class BucketHandle {
|
|
1058
2071
|
private bucketName;
|
|
1059
|
-
|
|
1060
|
-
|
|
1061
|
-
|
|
2072
|
+
/** Absent on the raw handle the cache itself reads through. */
|
|
2073
|
+
private blobs?;
|
|
2074
|
+
private settings?;
|
|
2075
|
+
private io;
|
|
2076
|
+
constructor(bucketName: string, remote: RemoteDatabaseService, /** Absent on the raw handle the cache itself reads through. */
|
|
2077
|
+
blobs?: (BlobCache | null) | undefined, settings?: BucketHandleSettings | undefined);
|
|
2078
|
+
/** Effective blurhash setting: per-call option > client config > default ON. */
|
|
2079
|
+
private resolveBlurhash;
|
|
2080
|
+
put(path: string, content: string | Uint8Array | Blob, options?: BucketPutOptions): Promise<BucketPutResult>;
|
|
2081
|
+
/**
|
|
2082
|
+
* The blurhash stored alongside an uploaded image (see
|
|
2083
|
+
* {@link blurhashSidecarPath}), or null when there is none. Reads through the
|
|
2084
|
+
* blob cache, so a warm client answers from OPFS without a network hop, and
|
|
2085
|
+
* misses are remembered per tab so a hashless image costs at most one
|
|
2086
|
+
* serialized remote read per session.
|
|
2087
|
+
*/
|
|
2088
|
+
blurhash(path: string): Promise<string | null>;
|
|
1062
2089
|
get(path: string): Promise<unknown>;
|
|
2090
|
+
/**
|
|
2091
|
+
* Read through the local blob cache: OPFS first, the bucket second. Unlike
|
|
2092
|
+
* {@link get} this survives a reload and works offline. Returns null when the
|
|
2093
|
+
* file exists in neither place.
|
|
2094
|
+
*/
|
|
2095
|
+
read(path: string, options?: BlobReadOptions): Promise<Blob | null>;
|
|
2096
|
+
/**
|
|
2097
|
+
* A refcounted object URL for `path`, suitable for `<img src>`. The caller
|
|
2098
|
+
* MUST call `release()` when the URL goes off screen. Returns null when the
|
|
2099
|
+
* file does not exist, or when object URLs are unavailable (non-browser).
|
|
2100
|
+
*/
|
|
2101
|
+
url(path: string, options?: BlobReadOptions): Promise<BlobUrlLease | null>;
|
|
2102
|
+
/** Exempt `path` from pressure eviction. Pinned bytes never expire. */
|
|
2103
|
+
pin(path: string): void;
|
|
2104
|
+
unpin(path: string): void;
|
|
2105
|
+
/** Drop `path` from the local cache without touching the remote file. */
|
|
2106
|
+
evict(path: string): Promise<void>;
|
|
2107
|
+
/** Warm the cache for offline use. Already-cached paths are skipped. */
|
|
2108
|
+
prefetch(paths: string[]): Promise<void>;
|
|
1063
2109
|
delete(path: string): Promise<void>;
|
|
1064
2110
|
exists(path: string): Promise<boolean>;
|
|
1065
2111
|
head(path: string): Promise<Record<string, unknown>>;
|
|
@@ -1067,123 +2113,244 @@ declare class BucketHandle {
|
|
|
1067
2113
|
rename(sourcePath: string, targetPath: string): Promise<void>;
|
|
1068
2114
|
list(prefix?: string): Promise<string[]>;
|
|
1069
2115
|
}
|
|
2116
|
+
//#endregion
|
|
2117
|
+
//#region src/client/sp00ky-client.d.ts
|
|
2118
|
+
interface Sp00kyClientDeps<S extends SchemaStructure> {
|
|
2119
|
+
services?: Services<S>;
|
|
2120
|
+
runtime?: Runtime;
|
|
2121
|
+
env?: Partial<SagaEnv>;
|
|
2122
|
+
}
|
|
2123
|
+
/**
|
|
2124
|
+
* The public client. Every method is a thin translation into a saga run, a
|
|
2125
|
+
* state read, or a subscription on the runtime; the engine's behaviour lives
|
|
2126
|
+
* in the sagas.
|
|
2127
|
+
*/
|
|
1070
2128
|
declare class Sp00kyClient<S extends SchemaStructure> {
|
|
1071
|
-
private config;
|
|
1072
|
-
|
|
1073
|
-
|
|
1074
|
-
|
|
1075
|
-
|
|
1076
|
-
|
|
1077
|
-
private
|
|
1078
|
-
private
|
|
1079
|
-
private
|
|
1080
|
-
private
|
|
1081
|
-
private featureFlags;
|
|
1082
|
-
private
|
|
1083
|
-
|
|
1084
|
-
|
|
1085
|
-
|
|
1086
|
-
|
|
1087
|
-
|
|
1088
|
-
|
|
1089
|
-
|
|
1090
|
-
|
|
1091
|
-
|
|
1092
|
-
|
|
1093
|
-
|
|
1094
|
-
|
|
1095
|
-
/**
|
|
1096
|
-
|
|
1097
|
-
/**
|
|
1098
|
-
* Observe sync health. Fires immediately with the current status and again
|
|
1099
|
-
* on every healthy↔degraded transition. Returns an unsubscribe.
|
|
1100
|
-
*/
|
|
1101
|
-
subscribeToSyncHealth(cb: (health: SyncHealth) => void): () => void;
|
|
1102
|
-
constructor(config: Sp00kyConfig<S>);
|
|
1103
|
-
/**
|
|
1104
|
-
* Setup direct callbacks instead of event subscriptions
|
|
1105
|
-
*/
|
|
1106
|
-
private setupCallbacks;
|
|
2129
|
+
private readonly config;
|
|
2130
|
+
readonly auth: AuthService<S>;
|
|
2131
|
+
readonly streamProcessor: StreamProcessorService;
|
|
2132
|
+
/** Web Push for this browser: subscribe, devices, self-pushes, service worker bridge. */
|
|
2133
|
+
readonly webPush: WebPushModule;
|
|
2134
|
+
/** Peer to peer channels of `-- @channel` tables. */
|
|
2135
|
+
private readonly channels;
|
|
2136
|
+
private readonly services;
|
|
2137
|
+
private readonly env;
|
|
2138
|
+
private readonly runtime;
|
|
2139
|
+
private readonly featureFlags;
|
|
2140
|
+
private readonly appReleases;
|
|
2141
|
+
/** Teardown for subscriptions the client itself owns. */
|
|
2142
|
+
private readonly disposers;
|
|
2143
|
+
/** Assigned in `wireAdapters`, which the constructor always runs. */
|
|
2144
|
+
private impersonationBanner;
|
|
2145
|
+
private readonly devTools;
|
|
2146
|
+
private hub;
|
|
2147
|
+
private forwarder;
|
|
2148
|
+
private detachWindow;
|
|
2149
|
+
private sharedActive;
|
|
2150
|
+
constructor(config: Sp00kyConfig<S>, deps?: Sp00kyClientDeps<S>);
|
|
2151
|
+
/** Adapter callbacks become runtime events; runtime events reach the legacy services. */
|
|
2152
|
+
private wireAdapters;
|
|
2153
|
+
/** Runtime events the DevTools panel follows; query transitions also go to the log. */
|
|
2154
|
+
private forwardToDevTools;
|
|
1107
2155
|
init(): Promise<void>;
|
|
1108
2156
|
close(): Promise<void>;
|
|
2157
|
+
isLocalReady(): boolean;
|
|
2158
|
+
query<Table extends TableNames<S>>(table: Table, options: QueryOptions<TableModel<GetTable<S, Table>>, false>, ttl?: QueryTimeToLive): QueryBuilder<S, Table, Sp00kyQueryResultPromise>;
|
|
2159
|
+
private registerInput;
|
|
2160
|
+
private initQuery;
|
|
1109
2161
|
/**
|
|
1110
|
-
*
|
|
1111
|
-
*
|
|
1112
|
-
*
|
|
1113
|
-
* and whose `subscribe(cb)` fires whenever that assignment changes.
|
|
1114
|
-
*
|
|
1115
|
-
* Permissions are enforced by SurrealDB: a client can only ever see
|
|
1116
|
-
* its own row, and cannot create or modify assignments.
|
|
1117
|
-
*/
|
|
1118
|
-
feature(key: string, options?: FeatureFlagOptions): FeatureFlagHandle;
|
|
1119
|
-
authenticate(token: string): Promise<surrealdb0.Tokens>;
|
|
1120
|
-
/**
|
|
1121
|
-
* Open a CRDT field for collaborative editing.
|
|
1122
|
-
* Returns a CrdtField with a LoroDoc that can be bound to any editor.
|
|
1123
|
-
* Also starts a LIVE SELECT on the parent table for real-time sync;
|
|
1124
|
-
* incoming events trigger a subquery fetch of `_00_crdt` / `_00_cursor`.
|
|
2162
|
+
* The raw remote escape hatches bypass the query builder, so their shapes
|
|
2163
|
+
* can never be on the server's query allowlist. When the generated schema
|
|
2164
|
+
* says the allowlist is on, refuse them unless the app opted in explicitly.
|
|
1125
2165
|
*/
|
|
1126
|
-
|
|
2166
|
+
private assertRawRemoteAllowed;
|
|
2167
|
+
queryRaw(sql: string, params: Record<string, any>, ttl: QueryTimeToLive): Promise<string>;
|
|
1127
2168
|
/**
|
|
1128
|
-
*
|
|
2169
|
+
* Preload = register a query nobody subscribes to. Resolved before on this
|
|
2170
|
+
* device: returns at once. Never resolved: resolves when the server's
|
|
2171
|
+
* membership and every body are local. `signal` aborts the wait.
|
|
1129
2172
|
*/
|
|
1130
|
-
|
|
1131
|
-
deauthenticate(): Promise<void>;
|
|
1132
|
-
query<Table extends TableNames<S>>(table: Table, options: QueryOptions<TableModel<GetTable<S, Table>>, false>, ttl?: QueryTimeToLive): QueryBuilder<S, Table, Sp00kyQueryResultPromise>;
|
|
1133
|
-
private initQuery;
|
|
1134
|
-
queryRaw(sql: string, params: Record<string, any>, ttl: QueryTimeToLive): Promise<string>;
|
|
2173
|
+
preload(finalQuery: FinalQuery<S, any, any, any, any, any>, options?: PreloadOptions): Promise<void>;
|
|
1135
2174
|
subscribe(queryHash: string, callback: (records: Record<string, any>[]) => void, options?: {
|
|
1136
2175
|
immediate?: boolean;
|
|
1137
2176
|
}): Promise<() => void>;
|
|
1138
2177
|
/**
|
|
1139
|
-
*
|
|
1140
|
-
*
|
|
1141
|
-
*
|
|
1142
|
-
*
|
|
1143
|
-
*
|
|
2178
|
+
* Open a peer to peer channel to `peers` (your own id is skipped; a
|
|
2179
|
+
* connection forms only when both sides list each other) for the rows
|
|
2180
|
+
* `queries` match, each a query on a `-- @channel` table. Only its `where`
|
|
2181
|
+
* counts, evaluated against each row; the query is never registered. Writes
|
|
2182
|
+
* to matching rows (plain or the channel's own) reach the peers. Close it
|
|
2183
|
+
* when done.
|
|
1144
2184
|
*/
|
|
2185
|
+
channel<T extends ChannelTableNames<S>>(queries: ChannelQuery<S, T> | ReadonlyArray<ChannelQuery<S, T>>, peers: Iterable<ChannelPeer>): Sp00kyChannel<S, T>;
|
|
2186
|
+
private channelScopes;
|
|
1145
2187
|
deregisterQuery(queryHash: string): void;
|
|
1146
|
-
/**
|
|
1147
|
-
* Subscribe to a query's fetch-status changes (idle/fetching). With
|
|
1148
|
-
* `{ immediate: true }` the callback fires synchronously with the current
|
|
1149
|
-
* status. Powers the `useQuery` hook's `isFetching()` accessor.
|
|
1150
|
-
*/
|
|
1151
2188
|
subscribeQueryStatus(queryHash: string, callback: QueryStatusCallback, options?: {
|
|
1152
2189
|
immediate?: boolean;
|
|
1153
2190
|
}): () => void;
|
|
1154
|
-
|
|
1155
|
-
|
|
1156
|
-
|
|
1157
|
-
* surface the "frontend" phase of the per-query timing breakdown.
|
|
1158
|
-
*/
|
|
2191
|
+
subscribeQueryAuthority(queryHash: string, callback: QueryAuthorityCallback, options?: {
|
|
2192
|
+
immediate?: boolean;
|
|
2193
|
+
}): () => void;
|
|
1159
2194
|
reportFrontendTiming(queryHash: string, ms: number): void;
|
|
1160
|
-
|
|
1161
|
-
|
|
1162
|
-
create(id: string, data: Record<string, unknown>): Promise<Record<string, unknown>>;
|
|
1163
|
-
update(table: string, id: string, data: Record<string, unknown>, options?: UpdateOptions): Promise<{
|
|
1164
|
-
[x: string]: /*elided*/any;
|
|
1165
|
-
}>;
|
|
2195
|
+
create<T extends Record<string, unknown>>(id: string, data: T): Promise<T>;
|
|
2196
|
+
update<T extends Record<string, unknown>>(table: string, id: string, data: Partial<T>, options?: UpdateOptions): Promise<T>;
|
|
1166
2197
|
delete(table: string, id: string): Promise<void>;
|
|
2198
|
+
private writeCreate;
|
|
2199
|
+
private writeUpdate;
|
|
2200
|
+
private writeDelete;
|
|
2201
|
+
run<B extends BackendNames<S>, R extends BackendRoutes<S, B>>(backend: B, path: R, payload: RoutePayload<S, B, R>, options?: RunOptions): Promise<void>;
|
|
2202
|
+
get failedMutationCount(): number;
|
|
2203
|
+
subscribeToFailedMutations(cb: (count: number) => void): () => void;
|
|
2204
|
+
listFailedMutations(): Promise<FailedMutationRow[]>;
|
|
2205
|
+
retryFailedMutation(mutationId: string): Promise<boolean>;
|
|
2206
|
+
discardFailedMutation(mutationId: string): Promise<boolean>;
|
|
2207
|
+
get tabRole(): TabRole$1 | null;
|
|
2208
|
+
get remoteClient(): Surreal;
|
|
2209
|
+
get localClient(): unknown;
|
|
2210
|
+
get pendingMutationCount(): number;
|
|
2211
|
+
/** Kept for the e2e suite; the saga core has no LIVE retry ladder. */
|
|
2212
|
+
get liveRetryCount(): number;
|
|
2213
|
+
subscribeToPendingMutations(cb: (count: number) => void): () => void;
|
|
2214
|
+
get fetchingQueryCount(): number;
|
|
2215
|
+
subscribeToFetchActivity(cb: (fetching: number) => void): () => void;
|
|
2216
|
+
get syncHealth(): SyncHealth;
|
|
2217
|
+
subscribeToSyncHealth(cb: (health: SyncHealth) => void): () => void;
|
|
2218
|
+
get storageHealth(): StorageHealth;
|
|
2219
|
+
subscribeToStorageHealth(cb: (health: StorageHealth) => void): () => void;
|
|
2220
|
+
/** The engine state, read-only. For tests and DevTools. */
|
|
2221
|
+
get state(): ClientState;
|
|
2222
|
+
/** Feed an event into the engine. For adapters, tests and DevTools. */
|
|
2223
|
+
dispatch(event: RuntimeEvent): Promise<void>;
|
|
2224
|
+
authenticate(token: string): Promise<surrealdb0.Tokens>;
|
|
2225
|
+
deauthenticate(): Promise<void>;
|
|
1167
2226
|
useRemote<T>(fn: (client: Surreal) => Promise<T> | T): Promise<T>;
|
|
2227
|
+
remoteQuery<T extends unknown[]>(sql: string, vars?: Record<string, unknown>): Promise<T>;
|
|
1168
2228
|
/**
|
|
1169
|
-
*
|
|
1170
|
-
*
|
|
1171
|
-
*
|
|
1172
|
-
*
|
|
2229
|
+
* Tell the client that the app's own impersonation banner is on screen.
|
|
2230
|
+
* Only meaningful with `impersonationBanner: { mode: 'custom' }`, where it
|
|
2231
|
+
* cancels the fallback that would otherwise show the built-in banner. Call
|
|
2232
|
+
* it while the custom banner is rendered (the Solid `useImpersonation`
|
|
2233
|
+
* hook does it for you with `rendersBanner: true`).
|
|
1173
2234
|
*/
|
|
1174
|
-
|
|
2235
|
+
acknowledgeImpersonationBanner(): void;
|
|
2236
|
+
feature(key: string, options?: FeatureFlagOptions): FeatureFlagHandle;
|
|
2237
|
+
setFeatureOverride(key: string, variant: string | null, payload?: unknown): void;
|
|
2238
|
+
clearFeatureOverrides(): void;
|
|
2239
|
+
getFeatureOverrides(): Record<string, FeatureFlagOverride>;
|
|
2240
|
+
appRelease(app: string, options?: AppReleaseOptions): AppReleaseHandle;
|
|
2241
|
+
/** Open a `@crdt` field for editing. `draft` (from {@link createCrdtDraft})
|
|
2242
|
+
* hands over edits made before the record existed. */
|
|
2243
|
+
openCrdtField(table: string, recordId: string, field: string, draft?: CrdtField): Promise<CrdtField>;
|
|
2244
|
+
/** A detached `@crdt` document for a record not created yet; see
|
|
2245
|
+
* {@link openCrdtField}. */
|
|
2246
|
+
createCrdtDraft(table: string, field: string): Promise<CrdtField>;
|
|
2247
|
+
/** Close a `@crdt` field. The last close resolves once its unsent edits
|
|
2248
|
+
* are queued in the outbox; offline, once they are saved on the device. */
|
|
2249
|
+
closeCrdtField(table: string, recordId: string, field: string): Promise<void>;
|
|
2250
|
+
bucket<B extends BucketNames<S>>(name: B): BucketHandle;
|
|
2251
|
+
getBlobCacheStats(): BlobCacheStats;
|
|
1175
2252
|
}
|
|
1176
2253
|
//#endregion
|
|
1177
|
-
//#region src/
|
|
1178
|
-
declare function fileToUint8Array(file: File | Blob): Promise<Uint8Array>;
|
|
2254
|
+
//#region src/modules/channel/webrtc.d.ts
|
|
1179
2255
|
/**
|
|
1180
|
-
*
|
|
1181
|
-
*
|
|
2256
|
+
* The default channel transport: one WebRTC data channel per pair of tabs,
|
|
2257
|
+
* set up through signaling rows in the database.
|
|
2258
|
+
*
|
|
2259
|
+
* Signaling (all rows of `_00_channel_signal`, read through one raw LIVE):
|
|
2260
|
+
*
|
|
2261
|
+
* 1. A tab that wants user U writes `hello` to U. Every tab of U hears it.
|
|
2262
|
+
* 2. Of each pair of tabs, the one with the lower `user#peer` key offers.
|
|
2263
|
+
* A tab that hears a hello from a higher key offers at once; one that
|
|
2264
|
+
* hears it from a lower key answers with a `hello` addressed back to that
|
|
2265
|
+
* tab, which then offers. So both orders of arrival connect, and nobody
|
|
2266
|
+
* loops.
|
|
2267
|
+
* 3. `offer` / `answer` carry the SDPs, `ice` batches of candidates
|
|
2268
|
+
* (trickled, so nothing waits for gathering to finish).
|
|
2269
|
+
*
|
|
2270
|
+
* A tab only ever reacts to signals from users it wants itself, so a
|
|
2271
|
+
* connection needs both sides to list each other. The database stamps every
|
|
2272
|
+
* row's `sender`, and the offer carries the DTLS fingerprint of the
|
|
2273
|
+
* connection, so the user on the other end of a data channel is proven.
|
|
1182
2274
|
*/
|
|
1183
|
-
|
|
2275
|
+
type SignalKind = 'hello' | 'offer' | 'answer' | 'ice';
|
|
2276
|
+
interface Signal {
|
|
2277
|
+
readonly from: string;
|
|
2278
|
+
readonly fromPeer: string;
|
|
2279
|
+
readonly toPeer: string | null;
|
|
2280
|
+
readonly kind: SignalKind;
|
|
2281
|
+
readonly payload: string | null;
|
|
2282
|
+
}
|
|
2283
|
+
interface OutgoingSignal {
|
|
2284
|
+
readonly to: string;
|
|
2285
|
+
readonly toPeer: string | null;
|
|
2286
|
+
readonly fromPeer: string;
|
|
2287
|
+
readonly kind: SignalKind;
|
|
2288
|
+
readonly payload: string | null;
|
|
2289
|
+
}
|
|
2290
|
+
/** Where signals go and come from. The database by default. */
|
|
2291
|
+
interface SignalPort {
|
|
2292
|
+
send(signal: OutgoingSignal): Promise<void>;
|
|
2293
|
+
listen(self: PeerRef, cb: (signal: Signal) => void): () => void;
|
|
2294
|
+
}
|
|
2295
|
+
interface WebRtcOptions {
|
|
2296
|
+
signal: SignalPort;
|
|
2297
|
+
iceServers?: RTCIceServer[];
|
|
2298
|
+
logger?: Pick<Logger$1, 'debug' | 'warn'>;
|
|
2299
|
+
/** Injectable for tests and non-browser runtimes. */
|
|
2300
|
+
RTCPeerConnection?: typeof RTCPeerConnection;
|
|
2301
|
+
/** Give up on one attempt after this long. Default 15000. */
|
|
2302
|
+
connectTimeoutMs?: number;
|
|
2303
|
+
}
|
|
2304
|
+
declare function webrtcTransport(hooks: TransportHooks, opts: WebRtcOptions): ChannelTransport;
|
|
2305
|
+
/** The bits of the remote service signaling needs. */
|
|
2306
|
+
interface SignalRemote {
|
|
2307
|
+
query<T extends unknown[]>(sql: string, vars?: Record<string, unknown>): Promise<T>;
|
|
2308
|
+
getClient(): Pick<Surreal, 'liveOf'>;
|
|
2309
|
+
}
|
|
2310
|
+
interface SignalConnection {
|
|
2311
|
+
subscribe(cb: (state: ConnectionState) => void): () => void;
|
|
2312
|
+
}
|
|
1184
2313
|
/**
|
|
1185
|
-
*
|
|
2314
|
+
* Signals as rows of `_00_channel_signal` (generated for schemas with a
|
|
2315
|
+
* `@channel` table): a CREATE to send, one raw `LIVE SELECT` on rows
|
|
2316
|
+
* addressed to this user to receive. Not the outbox and not a synced query:
|
|
2317
|
+
* each signal costs one round trip, which is what keeps connection setup
|
|
2318
|
+
* short. The LIVE is re-armed whenever the socket reconnects.
|
|
1186
2319
|
*/
|
|
1187
|
-
|
|
2320
|
+
declare function surrealSignal(remote: SignalRemote, connection: SignalConnection, logger?: Pick<Logger$1, 'debug' | 'warn'>): SignalPort;
|
|
2321
|
+
//#endregion
|
|
2322
|
+
//#region src/utils/semver.d.ts
|
|
2323
|
+
/** True when `a` is a valid version strictly greater than valid version `b`. */
|
|
2324
|
+
declare function semverGt(a: unknown, b: unknown): boolean;
|
|
2325
|
+
//#endregion
|
|
2326
|
+
//#region src/services/database/errors.d.ts
|
|
2327
|
+
/**
|
|
2328
|
+
* A local-store operation that did not answer within its deadline.
|
|
2329
|
+
*
|
|
2330
|
+
* The local write path (`db.create` / `db.update` / `db.delete`, every local
|
|
2331
|
+
* query behind them) used to have no deadline anywhere: the SQLite worker
|
|
2332
|
+
* transport parks a call until the worker replies, the surrealdb engine's
|
|
2333
|
+
* query chain waits on the previous link, and `withRetry` retries without a
|
|
2334
|
+
* clock. One op that never settled (a worker starved behind a long select, a
|
|
2335
|
+
* lock verification awaiting `navigator.locks.query()` forever) left the
|
|
2336
|
+
* caller's promise pending for the tab's lifetime - a chat composer that never
|
|
2337
|
+
* re-enabled, a call that never got past "Connecting".
|
|
2338
|
+
*
|
|
2339
|
+
* The message says "timed out" on purpose: `classifySyncError` keys off it and
|
|
2340
|
+
* treats the failure as transient (re-queue), never as an application error
|
|
2341
|
+
* that rolls the mutation back. `retryable: false` keeps `withRetry` from
|
|
2342
|
+
* spinning on it: the op is still running in the engine, retrying queues a
|
|
2343
|
+
* second copy behind it.
|
|
2344
|
+
*/
|
|
2345
|
+
declare class LocalOpTimeoutError extends Error {
|
|
2346
|
+
readonly name = "LocalOpTimeoutError";
|
|
2347
|
+
readonly retryable = false;
|
|
2348
|
+
readonly op: string;
|
|
2349
|
+
readonly timeoutMs: number;
|
|
2350
|
+
constructor(op: string, timeoutMs: number);
|
|
2351
|
+
}
|
|
2352
|
+
/** Default deadline for one local-store operation. Generous: a cold 4k-row
|
|
2353
|
+
* select on a throttled tab is seconds, not tens of seconds. */
|
|
2354
|
+
declare const DEFAULT_LOCAL_OP_TIMEOUT_MS = 30000;
|
|
1188
2355
|
//#endregion
|
|
1189
|
-
export { AuthEventSystem, AuthEventTypeMap, AuthEventTypes, AuthService, BucketHandle, CURSOR_COLORS, CrdtField, CrdtManager, DebounceOptions, EventSubscriptionOptions, FeatureFlagHandle, FeatureFlagModule, type FeatureFlagOptions, type FeatureFlagSnapshot, Level, MATERIALIZATION_SAMPLE_WINDOW, MutationCallback, MutationEvent, MutationEventType, PersistenceClient, PhaseStat, PinoTransmit, QueryConfig, QueryConfigRecord, QueryHash, QueryState, QueryStatus, QueryStatusCallback, QueryTimeToLive, QueryTimings, QueryUpdateCallback, RecordVersionArray, RecordVersionDiff, RegistrationTimings, RunOptions, Sp00kyClient, Sp00kyConfig, Sp00kyQueryResult, Sp00kyQueryResultPromise, StoreType, SyncHealth, SyncHealthConfig, SyncHealthStatus, TimingPhase, UpdateOptions, createAuthEventSystem, cursorColorFromName, fileToUint8Array, textToHtml };
|
|
2356
|
+
export { ActiveImpersonation, 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, type BridgeSignOutMessage, type BridgeTokenMessage, BucketHandle, BucketPutOptions, BucketPutResult, CURSOR_COLORS, type ChannelAcceptRule, type ChannelHandle, type ChannelMessage, type ChannelOp, ChannelQuery, type ChannelScope, type ChannelState, type ChannelStatus, type ChannelTransport, type ChannelTransportFactory, type ChannelsConfig, ConnectionState, CrdtField, CrdtManager, DEFAULT_LOCAL_OP_TIMEOUT_MS, DebounceOptions, EdgeDelta, EventSubscriptionOptions, type FailedMutationRow as FailedMutation, FeatureFlagHandle, FeatureFlagModule, type FeatureFlagOptions, type FeatureFlagOverride, type FeatureFlagSnapshot, IMPERSONATION_ACCESS, ImpersonationCandidate, ImpersonationInfo, ImpersonationTimerHost, ImpersonationTimers, InlineRow, Level, LocalOpTimeoutError, LocalWorkers, MATERIALIZATION_SAMPLE_WINDOW, MembershipOutcome, MutationCallback, MutationEvent, MutationEventType, ORIGIN_TOKEN_KEY, type OutgoingSignal, PUSH_ENDPOINT_KEY, PUSH_PAYLOAD_VERSION, type PeerRef, PersistenceClient, PhaseStat, PinoTransmit, PreloadOptions, PreloadRefresh, type PushDeviceKind, type PushNotification, type PushNotificationAction, type PushOp, type PushPayload, type PushPayloadKind, type PushUrgency, QueryAuthorityCallback, QueryConfig, QueryConfigRecord, QueryHash, QueryState, QueryStatus, QueryStatusCallback, QueryTimeToLive, QueryTimings, QueryUpdateCallback, REFUSAL_RECHECK_MIN_MS, ReconnectConfig, RecordVersionArray, RecordVersionDiff, RegistrationTimings, RunOptions, SESSION_POLL_MS, SIGN_OUT_HOOK_TIMEOUT_MS, ServerViewMeta, SignOutContext, SignOutHook, type Signal, type SignalPort, Sp00kyChannel, Sp00kyClient, Sp00kyClientDeps, Sp00kyConfig, Sp00kyQueryResult, Sp00kyQueryResultPromise, StorageHealth, StorageHealthStatus, StoreType, SyncHealth, SyncHealthConfig, SyncHealthStatus, TimingPhase, TokenClaims, type TransportHooks, UpdateOptions, type WebPushClientMessage, type WebPushConfig, type WebPushDevice, WebPushError, type WebPushErrorCode, type WebPushInfo, type WebPushMessage, type WebPushMessageInput, WebPushModule, type WebPushSubscribeOptions, type WebPushSupport, type WebPushSyncOptions, type WebPushSyncStatus, type WebPushUnsubscribeOptions, type WebPushUnsupportedReason, type WebPushUpdateOptions, blurhashSidecarPath, bucketContentToBlob, createAuthEventSystem, cursorColorFromName, decode as decodeBlurhash, decodeTokenClaims, detectWebPushSupport, encode as encodeBlurhash, encodeImageToBlurhash, fileToUint8Array, impersonationFromToken, isBlurhashValid, isImagePath, isPushPayload, matchesWhere, renewDelayMs, sameImpersonation, semverGt, surrealSignal, textToHtml, unusedArgs, webrtcTransport };
|