@spooky-sync/core 0.0.1-canary.13 → 0.0.1-canary.130
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 +56 -0
- package/dist/index.d.ts +1171 -372
- package/dist/index.js +5716 -1278
- package/dist/otel/index.d.ts +21 -0
- package/dist/otel/index.js +86 -0
- package/dist/sqlite-worker.d.ts +1 -0
- package/dist/sqlite-worker.js +107 -0
- package/dist/types.d.ts +746 -0
- package/package.json +39 -8
- package/skills/sp00ky-core/SKILL.md +258 -0
- package/skills/sp00ky-core/references/auth.md +98 -0
- package/skills/sp00ky-core/references/config.md +76 -0
- package/src/build-globals.d.ts +12 -0
- package/src/events/events.test.ts +2 -1
- package/src/events/index.ts +3 -0
- package/src/index.ts +9 -2
- package/src/modules/auth/events/index.ts +2 -1
- package/src/modules/auth/index.ts +59 -20
- package/src/modules/cache/index.ts +77 -32
- package/src/modules/cache/types.ts +2 -2
- package/src/modules/crdt/crdt-field.ts +288 -0
- package/src/modules/crdt/crdt-hydration.test.ts +206 -0
- package/src/modules/crdt/index.ts +357 -0
- package/src/modules/data/data.hydration.test.ts +150 -0
- package/src/modules/data/data.rebind.test.ts +147 -0
- package/src/modules/data/data.recurring.test.ts +137 -0
- package/src/modules/data/data.status.test.ts +249 -0
- package/src/modules/data/index.ts +1228 -127
- package/src/modules/data/window-query.test.ts +52 -0
- package/src/modules/data/window-query.ts +154 -0
- package/src/modules/devtools/index.ts +191 -30
- package/src/modules/devtools/versions.test.ts +74 -0
- package/src/modules/devtools/versions.ts +81 -0
- package/src/modules/feature-flag/index.test.ts +120 -0
- package/src/modules/feature-flag/index.ts +209 -0
- package/src/modules/ref-tables.test.ts +91 -0
- package/src/modules/ref-tables.ts +88 -0
- package/src/modules/sync/engine.ts +101 -37
- package/src/modules/sync/events/index.ts +9 -2
- package/src/modules/sync/queue/queue-down.ts +12 -5
- package/src/modules/sync/queue/queue-up.ts +29 -14
- package/src/modules/sync/scheduler.pause.test.ts +109 -0
- package/src/modules/sync/scheduler.ts +73 -7
- package/src/modules/sync/sync.health.test.ts +149 -0
- package/src/modules/sync/sync.subquery.test.ts +82 -0
- package/src/modules/sync/sync.ts +1017 -62
- package/src/modules/sync/utils.test.ts +269 -2
- package/src/modules/sync/utils.ts +182 -17
- package/src/otel/index.ts +127 -0
- package/src/services/database/cache-engine.ts +143 -0
- package/src/services/database/database.ts +11 -11
- package/src/services/database/engine-factory.ts +32 -0
- package/src/services/database/events/index.ts +2 -1
- package/src/services/database/index.ts +6 -0
- package/src/services/database/local-migrator.ts +28 -27
- package/src/services/database/local.test.ts +64 -0
- package/src/services/database/local.ts +452 -66
- package/src/services/database/plan-render.test.ts +133 -0
- package/src/services/database/plan-render.ts +100 -0
- package/src/services/database/relation-resolver.test.ts +413 -0
- package/src/services/database/relation-resolver.ts +0 -0
- package/src/services/database/remote.ts +13 -13
- package/src/services/database/sqlite-cache-engine.test.ts +85 -0
- package/src/services/database/sqlite-cache-engine.ts +699 -0
- package/src/services/database/sqlite-worker.ts +116 -0
- package/src/services/database/surql-translate.ts +291 -0
- package/src/services/database/surreal-cache-engine.ts +122 -0
- package/src/services/logger/index.ts +6 -101
- package/src/services/persistence/localstorage.ts +2 -2
- package/src/services/persistence/resilient.ts +41 -0
- package/src/services/persistence/surrealdb.ts +10 -10
- package/src/services/stream-processor/index.ts +295 -38
- package/src/services/stream-processor/permissions.test.ts +47 -0
- package/src/services/stream-processor/permissions.ts +53 -0
- package/src/services/stream-processor/stream-processor.batch.test.ts +136 -0
- package/src/services/stream-processor/stream-processor.reset.test.ts +104 -0
- package/src/services/stream-processor/stream-processor.test.ts +1 -1
- package/src/services/stream-processor/wasm-types.ts +18 -2
- package/src/sp00ky.auth-order.test.ts +92 -0
- package/src/sp00ky.init-query.test.ts +185 -0
- package/src/sp00ky.ts +1016 -0
- package/src/types.ts +258 -15
- package/src/utils/error-classification.test.ts +44 -0
- package/src/utils/error-classification.ts +7 -0
- package/src/utils/index.ts +35 -13
- package/src/utils/parser.ts +3 -2
- package/src/utils/surql.ts +24 -15
- package/src/utils/withRetry.test.ts +1 -1
- package/tsdown.config.ts +77 -1
- package/src/spooky.ts +0 -392
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Backend versions of the stack components, derived from the entity list the
|
|
3
|
+
* backend `/info` endpoint exposes (read via the `fn::spooky::info()` SurrealQL
|
|
4
|
+
* function). Any component that isn't reported degrades to `'unavailable'`.
|
|
5
|
+
*/
|
|
6
|
+
export interface BackendVersions {
|
|
7
|
+
ssp: string;
|
|
8
|
+
scheduler: string;
|
|
9
|
+
surrealdb: string;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export const UNAVAILABLE = 'unavailable';
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* A single stack entity as reported by `/info` (one per ssp / scheduler /
|
|
16
|
+
* backend). Carries far more than versions — status, uptime, ip, views — so the
|
|
17
|
+
* DevTools can render the whole stack. Extra fields are preserved verbatim.
|
|
18
|
+
*/
|
|
19
|
+
export interface BackendEntity {
|
|
20
|
+
entity: string;
|
|
21
|
+
id?: string;
|
|
22
|
+
ip?: string | null;
|
|
23
|
+
status?: string;
|
|
24
|
+
version?: string;
|
|
25
|
+
surrealdb_version?: string;
|
|
26
|
+
uptime_seconds?: number;
|
|
27
|
+
views?: number;
|
|
28
|
+
[key: string]: unknown;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export interface BackendInfo {
|
|
32
|
+
versions: BackendVersions;
|
|
33
|
+
entities: BackendEntity[];
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export function emptyBackendVersions(): BackendVersions {
|
|
37
|
+
return { ssp: UNAVAILABLE, scheduler: UNAVAILABLE, surrealdb: UNAVAILABLE };
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export function emptyBackendInfo(): BackendInfo {
|
|
41
|
+
return { versions: emptyBackendVersions(), entities: [] };
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** Strip a leading `surrealdb-` so versions read as bare semver (e.g. `2.0.3`). */
|
|
45
|
+
function normalizeServerVersion(v: string): string {
|
|
46
|
+
return String(v).replace(/^surrealdb-/i, '').trim();
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Normalize whatever `RETURN fn::spooky::info()` resolves to into the entity
|
|
51
|
+
* array. The SurrealQL function returns the parsed `/info` array; depending on
|
|
52
|
+
* how the result is unwrapped it may arrive as the array itself, a single
|
|
53
|
+
* object, or `null`. Tolerant of all three.
|
|
54
|
+
*/
|
|
55
|
+
export function toEntityArray(raw: unknown): BackendEntity[] {
|
|
56
|
+
if (Array.isArray(raw)) return raw.filter((e): e is BackendEntity => !!e && typeof e === 'object');
|
|
57
|
+
if (raw && typeof raw === 'object') return [raw as BackendEntity];
|
|
58
|
+
return [];
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Derive component versions + the full entity list from a `/info` entity array.
|
|
63
|
+
* `surrealdb` is taken from whichever entity reports `surrealdb_version` (ssp or
|
|
64
|
+
* scheduler). Never throws; missing pieces stay `'unavailable'`.
|
|
65
|
+
*/
|
|
66
|
+
export function parseBackendInfo(raw: unknown): BackendInfo {
|
|
67
|
+
const entities = toEntityArray(raw);
|
|
68
|
+
const versions = emptyBackendVersions();
|
|
69
|
+
|
|
70
|
+
for (const entity of entities) {
|
|
71
|
+
const version = entity.version ? String(entity.version) : undefined;
|
|
72
|
+
if (entity.entity === 'ssp' && version) versions.ssp = version;
|
|
73
|
+
else if (entity.entity === 'scheduler' && version) versions.scheduler = version;
|
|
74
|
+
|
|
75
|
+
if (versions.surrealdb === UNAVAILABLE && entity.surrealdb_version) {
|
|
76
|
+
versions.surrealdb = normalizeServerVersion(String(entity.surrealdb_version));
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
return { versions, entities };
|
|
81
|
+
}
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
import { describe, it, expect, beforeEach } from 'vitest';
|
|
2
|
+
import { FeatureFlagModule } from './index';
|
|
3
|
+
|
|
4
|
+
// Minimal mocks for the three deps the module touches. The DataModule mock
|
|
5
|
+
// captures the single subscribe callback so a test can push live results, and
|
|
6
|
+
// counts query() calls to assert the query is SHARED (one registration for all
|
|
7
|
+
// flags), not per-key.
|
|
8
|
+
function makeDeps() {
|
|
9
|
+
let subCb: ((records: unknown[]) => void) | null = null;
|
|
10
|
+
const calls: Array<{ sql: string; params: unknown }> = [];
|
|
11
|
+
let authCb: ((userId: string | null) => void) | null = null;
|
|
12
|
+
|
|
13
|
+
const dataModule = {
|
|
14
|
+
query: async (_table: string, sql: string, params: unknown) => {
|
|
15
|
+
calls.push({ sql, params });
|
|
16
|
+
return `hash:${calls.length}`;
|
|
17
|
+
},
|
|
18
|
+
subscribe: (_hash: string, cb: (records: unknown[]) => void) => {
|
|
19
|
+
subCb = cb;
|
|
20
|
+
return () => {
|
|
21
|
+
subCb = null;
|
|
22
|
+
};
|
|
23
|
+
},
|
|
24
|
+
};
|
|
25
|
+
const sync = { enqueueDownEvent: () => {} };
|
|
26
|
+
const auth = {
|
|
27
|
+
subscribe: (cb: (userId: string | null) => void) => {
|
|
28
|
+
authCb = cb;
|
|
29
|
+
return () => {
|
|
30
|
+
authCb = null;
|
|
31
|
+
};
|
|
32
|
+
},
|
|
33
|
+
};
|
|
34
|
+
const logger = { child: () => ({ warn: () => {} }) };
|
|
35
|
+
|
|
36
|
+
const deps = { dataModule, sync, auth, logger } as any;
|
|
37
|
+
return {
|
|
38
|
+
deps,
|
|
39
|
+
calls,
|
|
40
|
+
push: (records: unknown[]) => subCb?.(records),
|
|
41
|
+
setUser: (id: string | null) => authCb?.(id),
|
|
42
|
+
hasSub: () => subCb !== null,
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
const tick = () => new Promise((r) => setTimeout(r, 0));
|
|
47
|
+
|
|
48
|
+
describe('FeatureFlagModule', () => {
|
|
49
|
+
let env: ReturnType<typeof makeDeps>;
|
|
50
|
+
let mod: FeatureFlagModule<any>;
|
|
51
|
+
|
|
52
|
+
beforeEach(() => {
|
|
53
|
+
env = makeDeps();
|
|
54
|
+
mod = new FeatureFlagModule(env.deps);
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
it('registers ONE shared, unfiltered query for many flags', async () => {
|
|
58
|
+
mod.feature('alpha');
|
|
59
|
+
mod.feature('beta');
|
|
60
|
+
mod.feature('gamma');
|
|
61
|
+
await tick();
|
|
62
|
+
|
|
63
|
+
expect(env.calls.length).toBe(1);
|
|
64
|
+
expect(env.calls[0].sql).not.toContain('WHERE');
|
|
65
|
+
expect(env.calls[0].sql).toContain('FROM _00_user_feature');
|
|
66
|
+
expect(env.calls[0].params).toEqual({});
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
it('fans the shared result out to each handle by key', async () => {
|
|
70
|
+
const alpha = mod.feature('alpha', { fallback: 'off' });
|
|
71
|
+
const beta = mod.feature('beta', { fallback: 'off' });
|
|
72
|
+
const missing = mod.feature('missing', { fallback: 'off' });
|
|
73
|
+
await tick();
|
|
74
|
+
|
|
75
|
+
env.push([
|
|
76
|
+
{ key: 'alpha', variant: 'on' },
|
|
77
|
+
{ key: 'beta', variant: 'off' },
|
|
78
|
+
]);
|
|
79
|
+
|
|
80
|
+
expect(alpha.enabled()).toBe(true);
|
|
81
|
+
expect(alpha.variant()).toBe('on');
|
|
82
|
+
expect(beta.enabled()).toBe(false); // assigned 'off'
|
|
83
|
+
expect(missing.enabled()).toBe(false); // no row → fallback 'off'
|
|
84
|
+
});
|
|
85
|
+
|
|
86
|
+
it('observes NEW assignments live without re-registering', async () => {
|
|
87
|
+
const flag = mod.feature('live', { fallback: 'off' });
|
|
88
|
+
await tick();
|
|
89
|
+
|
|
90
|
+
env.push([]); // user starts with no assignment
|
|
91
|
+
expect(flag.enabled()).toBe(false);
|
|
92
|
+
|
|
93
|
+
env.push([{ key: 'live', variant: 'on' }]); // assigned while observing
|
|
94
|
+
expect(flag.enabled()).toBe(true);
|
|
95
|
+
|
|
96
|
+
expect(env.calls.length).toBe(1); // still the same single query
|
|
97
|
+
});
|
|
98
|
+
|
|
99
|
+
it('seeds a late-created handle from the already-loaded snapshot', async () => {
|
|
100
|
+
mod.feature('alpha', { fallback: 'off' });
|
|
101
|
+
await tick();
|
|
102
|
+
env.push([{ key: 'alpha', variant: 'on' }]);
|
|
103
|
+
|
|
104
|
+
const late = mod.feature('alpha', { fallback: 'off' });
|
|
105
|
+
expect(late.enabled()).toBe(true); // no fallback flash
|
|
106
|
+
});
|
|
107
|
+
|
|
108
|
+
it('clears flags and re-observes on user change', async () => {
|
|
109
|
+
mod.init();
|
|
110
|
+
const flag = mod.feature('alpha', { fallback: 'off' });
|
|
111
|
+
await tick();
|
|
112
|
+
env.push([{ key: 'alpha', variant: 'on' }]);
|
|
113
|
+
expect(flag.enabled()).toBe(true);
|
|
114
|
+
|
|
115
|
+
env.setUser('user:other'); // sign-in as a different user
|
|
116
|
+
await tick();
|
|
117
|
+
expect(flag.enabled()).toBe(false); // cleared until the new query resolves
|
|
118
|
+
expect(env.hasSub()).toBe(true); // re-registered for the new user
|
|
119
|
+
});
|
|
120
|
+
});
|
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
import type { SchemaStructure } from '@spooky-sync/query-builder';
|
|
2
|
+
import type { DataModule } from '../data/index';
|
|
3
|
+
import type { Sp00kySync } from '../sync/index';
|
|
4
|
+
import type { AuthService } from '../auth/index';
|
|
5
|
+
import type { Logger } from '../../services/logger/index';
|
|
6
|
+
import type { QueryTimeToLive } from '../../types';
|
|
7
|
+
|
|
8
|
+
// One shared LIVE query over ALL of the signed-in user's assignments — the
|
|
9
|
+
// `_00_user_feature` select permission scopes it to `user = $auth.id`, so no
|
|
10
|
+
// per-key `WHERE key = $key` param is needed. A single registration means every
|
|
11
|
+
// flag the user is (or becomes) assigned is observed at once: new assignments
|
|
12
|
+
// stream in live, and a handle for an unassigned key simply resolves to its
|
|
13
|
+
// fallback. Avoids one-registration-per-flag and the param-filtered live query.
|
|
14
|
+
const FEATURE_QUERY = 'SELECT key, variant, payload FROM _00_user_feature';
|
|
15
|
+
|
|
16
|
+
interface FeatureRow {
|
|
17
|
+
key?: string;
|
|
18
|
+
variant?: string;
|
|
19
|
+
payload?: unknown;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export interface FeatureFlagSnapshot {
|
|
23
|
+
variant: string | undefined;
|
|
24
|
+
payload: unknown | undefined;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export interface FeatureFlagOptions {
|
|
28
|
+
fallback?: string;
|
|
29
|
+
ttl?: QueryTimeToLive;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export class FeatureFlagHandle {
|
|
33
|
+
private latest: FeatureFlagSnapshot = { variant: undefined, payload: undefined };
|
|
34
|
+
private listeners = new Set<(s: FeatureFlagSnapshot) => void>();
|
|
35
|
+
private unsubscribeFn: (() => void) | null = null;
|
|
36
|
+
private onCloseFn: (() => void) | null = null;
|
|
37
|
+
private closed = false;
|
|
38
|
+
|
|
39
|
+
constructor(
|
|
40
|
+
public readonly key: string,
|
|
41
|
+
public readonly fallback: string | undefined,
|
|
42
|
+
) {}
|
|
43
|
+
|
|
44
|
+
attach(unsubscribe: () => void): void {
|
|
45
|
+
this.unsubscribeFn?.();
|
|
46
|
+
this.unsubscribeFn = unsubscribe;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
detach(): void {
|
|
50
|
+
this.unsubscribeFn?.();
|
|
51
|
+
this.unsubscribeFn = null;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
set(snapshot: FeatureFlagSnapshot): void {
|
|
55
|
+
if (this.closed) return;
|
|
56
|
+
this.latest = snapshot;
|
|
57
|
+
for (const cb of this.listeners) cb(snapshot);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
variant(): string | undefined {
|
|
61
|
+
return this.latest.variant ?? this.fallback;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
payload<T = unknown>(): T | undefined {
|
|
65
|
+
return this.latest.payload as T | undefined;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
enabled(): boolean {
|
|
69
|
+
const v = this.variant();
|
|
70
|
+
return v !== undefined && v !== 'off';
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
subscribe(cb: (s: FeatureFlagSnapshot) => void): () => void {
|
|
74
|
+
this.listeners.add(cb);
|
|
75
|
+
cb({ variant: this.variant(), payload: this.latest.payload });
|
|
76
|
+
return () => {
|
|
77
|
+
this.listeners.delete(cb);
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
onClose(cb: () => void): void {
|
|
82
|
+
this.onCloseFn = cb;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
close(): void {
|
|
86
|
+
if (this.closed) return;
|
|
87
|
+
this.closed = true;
|
|
88
|
+
this.listeners.clear();
|
|
89
|
+
this.detach();
|
|
90
|
+
this.onCloseFn?.();
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
export interface FeatureFlagModuleDeps<S extends SchemaStructure> {
|
|
95
|
+
dataModule: DataModule<S>;
|
|
96
|
+
sync: Sp00kySync<S>;
|
|
97
|
+
auth: AuthService<S>;
|
|
98
|
+
logger: Logger;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
export class FeatureFlagModule<S extends SchemaStructure> {
|
|
102
|
+
private logger: Logger;
|
|
103
|
+
private handles = new Set<FeatureFlagHandle>();
|
|
104
|
+
private authUnsubscribe: (() => void) | null = null;
|
|
105
|
+
private lastUserId: string | null = null;
|
|
106
|
+
|
|
107
|
+
// The single shared live query over the user's assignments.
|
|
108
|
+
private querySubscription: (() => void) | null = null;
|
|
109
|
+
private starting = false;
|
|
110
|
+
// Longest TTL any caller asked for (the query is shared across all flags).
|
|
111
|
+
private ttl: QueryTimeToLive = '10m';
|
|
112
|
+
// Latest assignment per key, plus whether the query has resolved at least
|
|
113
|
+
// once (so a handle created before the first result knows to wait vs. fall
|
|
114
|
+
// back). `snapshots` only holds ASSIGNED keys; an absent key → fallback.
|
|
115
|
+
private snapshots = new Map<string, FeatureFlagSnapshot>();
|
|
116
|
+
private loaded = false;
|
|
117
|
+
|
|
118
|
+
constructor(private deps: FeatureFlagModuleDeps<S>) {
|
|
119
|
+
this.logger = deps.logger.child({ service: 'FeatureFlagModule' });
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
init(): void {
|
|
123
|
+
if (this.authUnsubscribe) return;
|
|
124
|
+
this.authUnsubscribe = this.deps.auth.subscribe((userId) => {
|
|
125
|
+
if (userId === this.lastUserId) return;
|
|
126
|
+
this.lastUserId = userId;
|
|
127
|
+
void this.refresh();
|
|
128
|
+
});
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
feature(key: string, options: FeatureFlagOptions = {}): FeatureFlagHandle {
|
|
132
|
+
const handle = new FeatureFlagHandle(key, options.fallback);
|
|
133
|
+
this.handles.add(handle);
|
|
134
|
+
handle.onClose(() => this.handles.delete(handle));
|
|
135
|
+
if (options.ttl) this.ttl = options.ttl;
|
|
136
|
+
// If the shared query already resolved, seed this handle immediately so a
|
|
137
|
+
// late `feature()` call doesn't flash the fallback for an assigned key.
|
|
138
|
+
if (this.loaded) {
|
|
139
|
+
handle.set(this.snapshots.get(key) ?? { variant: undefined, payload: undefined });
|
|
140
|
+
}
|
|
141
|
+
void this.ensureStarted();
|
|
142
|
+
return handle;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
async closeAll(): Promise<void> {
|
|
146
|
+
this.authUnsubscribe?.();
|
|
147
|
+
this.authUnsubscribe = null;
|
|
148
|
+
this.teardownQuery();
|
|
149
|
+
for (const handle of [...this.handles]) handle.close();
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/** Auth changed: drop the old user's query/snapshots and re-observe. */
|
|
153
|
+
private async refresh(): Promise<void> {
|
|
154
|
+
this.teardownQuery();
|
|
155
|
+
this.loaded = false;
|
|
156
|
+
this.snapshots.clear();
|
|
157
|
+
// Clear handles immediately so a sign-out hides flag-gated UI without lag.
|
|
158
|
+
for (const handle of this.handles) {
|
|
159
|
+
handle.set({ variant: undefined, payload: undefined });
|
|
160
|
+
}
|
|
161
|
+
await this.ensureStarted();
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
private teardownQuery(): void {
|
|
165
|
+
this.querySubscription?.();
|
|
166
|
+
this.querySubscription = null;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/** Start the single shared live query (idempotent; no-op with no handles). */
|
|
170
|
+
private async ensureStarted(): Promise<void> {
|
|
171
|
+
if (this.querySubscription || this.starting || this.handles.size === 0) return;
|
|
172
|
+
this.starting = true;
|
|
173
|
+
try {
|
|
174
|
+
const hash = await this.deps.dataModule.query(
|
|
175
|
+
'_00_user_feature' as any,
|
|
176
|
+
FEATURE_QUERY,
|
|
177
|
+
{},
|
|
178
|
+
this.ttl,
|
|
179
|
+
);
|
|
180
|
+
this.deps.sync.enqueueDownEvent({ type: 'register', payload: { hash } });
|
|
181
|
+
this.querySubscription = this.deps.dataModule.subscribe(
|
|
182
|
+
hash,
|
|
183
|
+
(records) => this.applyRecords(records as FeatureRow[]),
|
|
184
|
+
{ immediate: true },
|
|
185
|
+
);
|
|
186
|
+
} catch (err) {
|
|
187
|
+
this.logger.warn(
|
|
188
|
+
{ err, Category: 'sp00ky-client::FeatureFlagModule::register' },
|
|
189
|
+
'Failed to register feature flag query',
|
|
190
|
+
);
|
|
191
|
+
} finally {
|
|
192
|
+
this.starting = false;
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/** Live query result → per-key snapshots → push to every active handle. */
|
|
197
|
+
private applyRecords(records: FeatureRow[]): void {
|
|
198
|
+
this.snapshots.clear();
|
|
199
|
+
for (const row of records ?? []) {
|
|
200
|
+
if (row && typeof row.key === 'string') {
|
|
201
|
+
this.snapshots.set(row.key, { variant: row.variant, payload: row.payload });
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
this.loaded = true;
|
|
205
|
+
for (const handle of this.handles) {
|
|
206
|
+
handle.set(this.snapshots.get(handle.key) ?? { variant: undefined, payload: undefined });
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
}
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import { describe, it, expect } from 'vitest';
|
|
2
|
+
import { RecordId } from 'surrealdb';
|
|
3
|
+
import { ANON_USER_ID, bucketIdForUser, listRefTableFor, sanitizeUserId } from './ref-tables';
|
|
4
|
+
|
|
5
|
+
describe('listRefTableFor', () => {
|
|
6
|
+
it('returns global table in single mode regardless of user', () => {
|
|
7
|
+
expect(listRefTableFor('single', 'user:abc')).toBe('_00_list_ref');
|
|
8
|
+
expect(listRefTableFor('single', null)).toBe('_00_list_ref');
|
|
9
|
+
expect(listRefTableFor('single', undefined)).toBe('_00_list_ref');
|
|
10
|
+
});
|
|
11
|
+
|
|
12
|
+
it('returns per-user table in dedicated mode with valid user id', () => {
|
|
13
|
+
expect(listRefTableFor('dedicated', 'user:abc')).toBe(
|
|
14
|
+
'_00_list_ref_user_abc'
|
|
15
|
+
);
|
|
16
|
+
});
|
|
17
|
+
|
|
18
|
+
it('accepts a RecordId object in dedicated mode', () => {
|
|
19
|
+
const rid = new RecordId('user', 'def');
|
|
20
|
+
expect(listRefTableFor('dedicated', rid)).toBe('_00_list_ref_user_def');
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
it('falls back to global in dedicated mode when user id is missing', () => {
|
|
24
|
+
expect(listRefTableFor('dedicated', null)).toBe('_00_list_ref');
|
|
25
|
+
expect(listRefTableFor('dedicated', undefined)).toBe('_00_list_ref');
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
it('falls back to global in dedicated mode when user id has invalid chars', () => {
|
|
29
|
+
// SurrealDB table identifiers only accept alphanumerics + underscore.
|
|
30
|
+
expect(listRefTableFor('dedicated', 'user:abc-with-dash')).toBe(
|
|
31
|
+
'_00_list_ref'
|
|
32
|
+
);
|
|
33
|
+
expect(listRefTableFor('dedicated', 'user:abc.dot')).toBe('_00_list_ref');
|
|
34
|
+
});
|
|
35
|
+
|
|
36
|
+
it('routes the anon sentinel to the shared anon table in both modes', () => {
|
|
37
|
+
expect(listRefTableFor('dedicated', ANON_USER_ID)).toBe('_00_list_ref_anon');
|
|
38
|
+
expect(listRefTableFor('single', ANON_USER_ID)).toBe('_00_list_ref_anon');
|
|
39
|
+
// A real user whose id sanitizes to "anon" still carries the user: prefix,
|
|
40
|
+
// so it never collides with the bare sentinel.
|
|
41
|
+
expect(listRefTableFor('dedicated', 'user:anon')).toBe(
|
|
42
|
+
'_00_list_ref_user_anon'
|
|
43
|
+
);
|
|
44
|
+
});
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
describe('sanitizeUserId', () => {
|
|
48
|
+
it('strips the user: prefix', () => {
|
|
49
|
+
expect(sanitizeUserId('user:abc123')).toBe('abc123');
|
|
50
|
+
});
|
|
51
|
+
|
|
52
|
+
it('accepts plain ids without the user: prefix', () => {
|
|
53
|
+
expect(sanitizeUserId('abc123')).toBe('abc123');
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
it('accepts RecordId objects', () => {
|
|
57
|
+
expect(sanitizeUserId(new RecordId('user', 'xyz'))).toBe('xyz');
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
it('returns null for invalid id shapes', () => {
|
|
61
|
+
expect(sanitizeUserId(null)).toBeNull();
|
|
62
|
+
expect(sanitizeUserId(undefined)).toBeNull();
|
|
63
|
+
expect(sanitizeUserId('user:')).toBeNull();
|
|
64
|
+
expect(sanitizeUserId('user:has-dash')).toBeNull();
|
|
65
|
+
});
|
|
66
|
+
});
|
|
67
|
+
|
|
68
|
+
describe('bucketIdForUser', () => {
|
|
69
|
+
it('routes signed-out sessions to the anon bucket', () => {
|
|
70
|
+
expect(bucketIdForUser(null)).toBe(ANON_USER_ID);
|
|
71
|
+
expect(bucketIdForUser(undefined)).toBe(ANON_USER_ID);
|
|
72
|
+
expect(bucketIdForUser(ANON_USER_ID)).toBe(ANON_USER_ID);
|
|
73
|
+
});
|
|
74
|
+
|
|
75
|
+
it('uses the sanitized id for valid users', () => {
|
|
76
|
+
expect(bucketIdForUser('user:abc123')).toBe('abc123');
|
|
77
|
+
expect(bucketIdForUser(new RecordId('user', 'xyz'))).toBe('xyz');
|
|
78
|
+
});
|
|
79
|
+
|
|
80
|
+
it('gives unsanitizable ids a deterministic per-user bucket, never anon', () => {
|
|
81
|
+
const a = bucketIdForUser('user:has-dash');
|
|
82
|
+
const b = bucketIdForUser('user:has-dash');
|
|
83
|
+
const c = bucketIdForUser('user:other-dash');
|
|
84
|
+
// Falling back to the shared anon bucket here would recreate the
|
|
85
|
+
// cross-user local-cache leak this helper exists to prevent.
|
|
86
|
+
expect(a).not.toBe(ANON_USER_ID);
|
|
87
|
+
expect(a).toBe(b);
|
|
88
|
+
expect(a).not.toBe(c);
|
|
89
|
+
expect(a).toMatch(/^u[0-9a-f]+$/);
|
|
90
|
+
});
|
|
91
|
+
});
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
// Client-side mirror of `packages/ssp-protocol/src/lib.rs`'s
|
|
2
|
+
// `query_table_for` / `list_ref_table_for`. Same naming convention so
|
|
3
|
+
// the LIVE subscription, the initial-fetch read, and the SSP's writes
|
|
4
|
+
// all land on the same table.
|
|
5
|
+
//
|
|
6
|
+
// The mode is currently hardcoded to `dedicated` because that's the
|
|
7
|
+
// only mode the e2e suite exercises and threading the value through
|
|
8
|
+
// codegen wasn't necessary to land the cross-session fix. If single
|
|
9
|
+
// mode ever needs to be exposed from the TS client too, the SSP server
|
|
10
|
+
// already reads it from `SPKY_SSP_REF_MODE`; add a matching codegen
|
|
11
|
+
// export then.
|
|
12
|
+
|
|
13
|
+
import { cyrb53 } from '@spooky-sync/query-builder';
|
|
14
|
+
|
|
15
|
+
export type RefMode = 'single' | 'dedicated';
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Sentinel user id for unauthenticated clients when anonymous live queries are
|
|
19
|
+
* enabled. Mirrors `ssp_protocol::ANON_AUTH_ID`. It carries no `user:` prefix
|
|
20
|
+
* so it can never collide with a real user id (those arrive as `user:<id>`);
|
|
21
|
+
* both sides resolve it to the shared `_00_list_ref_anon` table.
|
|
22
|
+
*/
|
|
23
|
+
export const ANON_USER_ID = 'anon';
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Default ref-storage mode for this client build. Mirrors the SSP's
|
|
27
|
+
* default (`RefMode::Dedicated`) so cross-session sync works out of the
|
|
28
|
+
* box.
|
|
29
|
+
*/
|
|
30
|
+
export const DEFAULT_REF_MODE: RefMode = 'dedicated';
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Sanitize a user record id (e.g. `"user:abc"`) into the segment that
|
|
34
|
+
* goes into a dedicated table name (e.g. `"abc"`). Returns `null` if
|
|
35
|
+
* the id is missing the `user:` prefix or contains characters that
|
|
36
|
+
* aren't valid in a SurrealDB table identifier — the server-side
|
|
37
|
+
* `ssp_protocol::sanitize_user_id` uses the same predicate.
|
|
38
|
+
*
|
|
39
|
+
* Accepts both string ids (`"user:abc"`) and SurrealDB `RecordId`
|
|
40
|
+
* objects (which only stringify cleanly via `.toString()`), since
|
|
41
|
+
* `AuthService` passes the record-id object as-is to its subscribers.
|
|
42
|
+
*/
|
|
43
|
+
export function sanitizeUserId(userId: unknown): string | null {
|
|
44
|
+
if (userId === null || userId === undefined) return null;
|
|
45
|
+
const asString =
|
|
46
|
+
typeof userId === 'string'
|
|
47
|
+
? userId
|
|
48
|
+
: typeof (userId as { toString?: unknown }).toString === 'function'
|
|
49
|
+
? (userId as { toString: () => string }).toString()
|
|
50
|
+
: null;
|
|
51
|
+
if (!asString) return null;
|
|
52
|
+
const raw = asString.startsWith('user:') ? asString.slice('user:'.length) : asString;
|
|
53
|
+
if (raw.length === 0) return null;
|
|
54
|
+
if (!/^[A-Za-z0-9_]+$/.test(raw)) return null;
|
|
55
|
+
return raw;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Resolve the LOCAL storage bucket id for a user. Every user gets their own
|
|
60
|
+
* IndexedDB-backed local store (`indxdb://sp00ky-<bucketId>`) so cached rows,
|
|
61
|
+
* query state, and the mutation outbox never leak across accounts on a shared
|
|
62
|
+
* device. Signed-out sessions share the `anon` bucket.
|
|
63
|
+
*
|
|
64
|
+
* An id that fails sanitization still gets a DETERMINISTIC per-user bucket
|
|
65
|
+
* (cyrb53 hex of the raw id) — falling back to `anon` here would put an
|
|
66
|
+
* authenticated user in the shared bucket and recreate the cross-user leak.
|
|
67
|
+
*/
|
|
68
|
+
export function bucketIdForUser(userId: unknown): string {
|
|
69
|
+
if (userId === null || userId === undefined || userId === ANON_USER_ID) return ANON_USER_ID;
|
|
70
|
+
const uid = sanitizeUserId(userId);
|
|
71
|
+
if (uid) return uid;
|
|
72
|
+
return `u${cyrb53(String(userId)).toString(16)}`;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* Returns the `_00_list_ref` table name for `(mode, userId)`. Falls
|
|
77
|
+
* back to the global `_00_list_ref` when sanitization fails or in
|
|
78
|
+
* single mode.
|
|
79
|
+
*/
|
|
80
|
+
export function listRefTableFor(mode: RefMode, userId: unknown): string {
|
|
81
|
+
// Anonymous clients (flag-enabled) share one dedicated table in both modes —
|
|
82
|
+
// checked before the mode split so it never lands on the per-user or the
|
|
83
|
+
// auth-gated global table. Matches `ssp_protocol::list_ref_table_for`.
|
|
84
|
+
if (userId === ANON_USER_ID) return '_00_list_ref_anon';
|
|
85
|
+
if (mode === 'single') return '_00_list_ref';
|
|
86
|
+
const uid = sanitizeUserId(userId);
|
|
87
|
+
return uid ? `_00_list_ref_user_${uid}` : '_00_list_ref';
|
|
88
|
+
}
|