@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
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import { RecordId } from 'surrealdb';
|
|
2
|
-
import { SchemaStructure } from '@spooky-sync/query-builder';
|
|
3
|
-
import { RemoteDatabaseService } from '../../services/database/index';
|
|
4
|
-
import { CacheModule, CacheRecord, RecordWithId } from '../cache/index';
|
|
5
|
-
import { RecordVersionDiff } from '../../types';
|
|
6
|
-
import { Logger } from '../../services/logger/index';
|
|
1
|
+
import type { RecordId } from 'surrealdb';
|
|
2
|
+
import type { SchemaStructure } from '@spooky-sync/query-builder';
|
|
3
|
+
import type { RemoteDatabaseService } from '../../services/database/index';
|
|
4
|
+
import type { CacheModule, CacheRecord, RecordWithId } from '../cache/index';
|
|
5
|
+
import type { RecordVersionDiff } from '../../types';
|
|
6
|
+
import type { Logger } from '../../services/logger/index';
|
|
7
7
|
import { SyncEventTypes, createSyncEventSystem } from './events/index';
|
|
8
8
|
import { encodeRecordId } from '../../utils/index';
|
|
9
9
|
import { cleanRecord } from '../../utils/parser';
|
|
@@ -12,7 +12,7 @@ import { cleanRecord } from '../../utils/parser';
|
|
|
12
12
|
* SyncEngine handles the core sync operations: fetching remote records,
|
|
13
13
|
* caching them locally, and ingesting into DBSP.
|
|
14
14
|
*
|
|
15
|
-
* This is extracted from
|
|
15
|
+
* This is extracted from Sp00kySync to separate "how to sync" from "when to sync".
|
|
16
16
|
*/
|
|
17
17
|
export class SyncEngine {
|
|
18
18
|
private logger: Logger;
|
|
@@ -24,7 +24,7 @@ export class SyncEngine {
|
|
|
24
24
|
private schema: SchemaStructure,
|
|
25
25
|
logger: Logger
|
|
26
26
|
) {
|
|
27
|
-
this.logger = logger.child({ service: '
|
|
27
|
+
this.logger = logger.child({ service: 'Sp00kySync:SyncEngine' });
|
|
28
28
|
}
|
|
29
29
|
|
|
30
30
|
/**
|
|
@@ -32,7 +32,9 @@ export class SyncEngine {
|
|
|
32
32
|
* Main entry point for sync operations.
|
|
33
33
|
* Uses batch processing to minimize events emitted.
|
|
34
34
|
*/
|
|
35
|
-
async syncRecords(
|
|
35
|
+
async syncRecords(
|
|
36
|
+
diff: RecordVersionDiff
|
|
37
|
+
): Promise<{ remoteFetchMs: number; stillRemoteIds: string[] }> {
|
|
36
38
|
const { added, updated, removed } = diff;
|
|
37
39
|
|
|
38
40
|
this.logger.debug(
|
|
@@ -40,55 +42,70 @@ export class SyncEngine {
|
|
|
40
42
|
added,
|
|
41
43
|
updated,
|
|
42
44
|
removed,
|
|
43
|
-
Category: '
|
|
45
|
+
Category: 'sp00ky-client::SyncEngine::syncRecords',
|
|
44
46
|
},
|
|
45
47
|
'SyncEngine.syncRecords diff'
|
|
46
48
|
);
|
|
47
49
|
|
|
48
|
-
// Handle removed records: verify they don't exist remotely before deleting
|
|
50
|
+
// Handle removed records: verify they don't exist remotely before deleting
|
|
51
|
+
// locally. Returns ids that LEFT the view's list_ref but still exist upstream
|
|
52
|
+
// (so they weren't deleted) — the caller converges localArray to drop them.
|
|
53
|
+
let stillRemoteIds: string[] = [];
|
|
49
54
|
if (removed.length > 0) {
|
|
50
|
-
await this.handleRemovedRecords(removed);
|
|
55
|
+
stillRemoteIds = await this.handleRemovedRecords(removed);
|
|
51
56
|
}
|
|
52
57
|
|
|
53
58
|
// Fetch added/updated records from remote
|
|
54
59
|
const toFetch = [...added, ...updated];
|
|
55
60
|
const idsToFetch = toFetch.map((x) => x.id);
|
|
56
61
|
if (idsToFetch.length === 0) {
|
|
57
|
-
return;
|
|
62
|
+
return { remoteFetchMs: 0, stillRemoteIds };
|
|
58
63
|
}
|
|
59
64
|
|
|
65
|
+
// Build a version map from the diff (versions come from _00_list_ref)
|
|
66
|
+
const versionMap = new Map<string, number>();
|
|
67
|
+
for (const item of toFetch) {
|
|
68
|
+
versionMap.set(encodeRecordId(item.id), item.version);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
// Fetch records from remote — avoid SELECT *, <subquery> FROM $param
|
|
72
|
+
// pattern which drops the * fields in SurrealDB v3 (known bug).
|
|
73
|
+
// Versions are already known from the diff's list_ref data.
|
|
74
|
+
const remoteFetchStart = performance.now();
|
|
60
75
|
const [remoteResults] = await this.remote.query<[RecordWithId[]]>(
|
|
61
|
-
|
|
76
|
+
'SELECT * FROM $idsToFetch',
|
|
62
77
|
{ idsToFetch }
|
|
63
78
|
);
|
|
64
|
-
|
|
79
|
+
const remoteFetchMs = performance.now() - remoteFetchStart;
|
|
80
|
+
|
|
65
81
|
// Prepare batch for cache (which handles both DB and DBSP)
|
|
66
82
|
const cacheBatch: CacheRecord[] = [];
|
|
67
83
|
|
|
68
|
-
for (const
|
|
84
|
+
for (const record of remoteResults) {
|
|
69
85
|
if (!record?.id) {
|
|
70
86
|
this.logger.warn(
|
|
71
87
|
{
|
|
72
88
|
record,
|
|
73
89
|
idsToFetch,
|
|
74
|
-
Category: '
|
|
90
|
+
Category: 'sp00ky-client::SyncEngine::syncRecords',
|
|
75
91
|
},
|
|
76
|
-
'Remote record has no id. Skipping record'
|
|
92
|
+
'Remote record has no id (possibly deleted). Skipping record'
|
|
77
93
|
);
|
|
78
94
|
continue;
|
|
79
95
|
}
|
|
80
96
|
const fullId = encodeRecordId(record.id);
|
|
81
97
|
const table = record.id.table.toString();
|
|
82
98
|
const isAdded = added.some((item) => encodeRecordId(item.id) === fullId);
|
|
99
|
+
const version = versionMap.get(fullId) ?? 0;
|
|
83
100
|
|
|
84
101
|
const localVersion = this.cache.lookup(fullId);
|
|
85
|
-
if (localVersion &&
|
|
102
|
+
if (localVersion && version <= localVersion) {
|
|
86
103
|
this.logger.info(
|
|
87
104
|
{
|
|
88
105
|
recordId: fullId,
|
|
89
|
-
version
|
|
106
|
+
version,
|
|
90
107
|
localVersion,
|
|
91
|
-
Category: '
|
|
108
|
+
Category: 'sp00ky-client::SyncEngine::syncRecords',
|
|
92
109
|
},
|
|
93
110
|
'Local version is higher than remote version. Skipping record'
|
|
94
111
|
);
|
|
@@ -103,7 +120,7 @@ export class SyncEngine {
|
|
|
103
120
|
table,
|
|
104
121
|
op: isAdded ? 'CREATE' : 'UPDATE',
|
|
105
122
|
record: cleanedRecord as RecordWithId,
|
|
106
|
-
version
|
|
123
|
+
version,
|
|
107
124
|
});
|
|
108
125
|
}
|
|
109
126
|
|
|
@@ -115,49 +132,96 @@ export class SyncEngine {
|
|
|
115
132
|
this.events.emit(SyncEventTypes.RemoteDataIngested, {
|
|
116
133
|
records: remoteResults,
|
|
117
134
|
});
|
|
135
|
+
|
|
136
|
+
return { remoteFetchMs, stillRemoteIds };
|
|
118
137
|
}
|
|
119
138
|
|
|
120
139
|
/**
|
|
121
140
|
* Handle records that exist locally but not in remote array.
|
|
141
|
+
*
|
|
142
|
+
* "Removed" here is a derived signal: the SSP's `_00_list_ref` array no
|
|
143
|
+
* longer references a record that exists locally. That can mean the row
|
|
144
|
+
* was genuinely deleted upstream — but it can also be a benign race
|
|
145
|
+
* (e.g. a record we just created hasn't propagated into the SSP's
|
|
146
|
+
* incantation list yet). Before deleting locally we verify against
|
|
147
|
+
* upstream SurrealDB: if the row still exists there, skip the delete.
|
|
148
|
+
*
|
|
149
|
+
* On verification failure we skip deletion too. Losing a stale local
|
|
150
|
+
* row to a later sync round is recoverable; deleting a fresh row that
|
|
151
|
+
* upstream still has is not.
|
|
122
152
|
*/
|
|
123
|
-
private async handleRemovedRecords(removed: RecordId[]): Promise<
|
|
153
|
+
private async handleRemovedRecords(removed: RecordId[]): Promise<string[]> {
|
|
124
154
|
this.logger.debug(
|
|
125
155
|
{
|
|
126
156
|
removed: removed.map((r) => r.toString()),
|
|
127
|
-
Category: '
|
|
157
|
+
Category: 'sp00ky-client::SyncEngine::handleRemovedRecords',
|
|
128
158
|
},
|
|
129
159
|
'Checking removed records'
|
|
130
160
|
);
|
|
131
161
|
|
|
132
|
-
|
|
162
|
+
// Confirm which of the "removed" ids still exist remotely by selecting the
|
|
163
|
+
// records directly from the id array (the records ARE the FROM target).
|
|
164
|
+
//
|
|
165
|
+
// The exact query form matters on SurrealDB v3.x:
|
|
166
|
+
// - `WHERE id IN $ids` is broken: record-id `IN` matches nothing, so every
|
|
167
|
+
// removed id looked gone and live local records got deleted (a fresh
|
|
168
|
+
// collection vanished mid-session). Do NOT use `IN`.
|
|
169
|
+
// - `SELECT id FROM $ids` — a FIELD projection over a record-id ARRAY —
|
|
170
|
+
// errors "Specify a database to use" on the deployed engine. The catch
|
|
171
|
+
// below then swallowed it and skipped EVERY deletion, so nothing could be
|
|
172
|
+
// deleted anywhere (games, comments, …). Do NOT project a field over the
|
|
173
|
+
// array. (`SELECT * FROM $ids` works but pulls full records — wasteful.)
|
|
174
|
+
// - `SELECT VALUE id FROM $ids` works: a flat array of ids with a NONE entry
|
|
175
|
+
// for each id that no longer exists. We filter the NONE entries out; the
|
|
176
|
+
// survivors are the ids still present upstream.
|
|
177
|
+
let existingRemoteIds: Set<string>;
|
|
133
178
|
try {
|
|
134
|
-
const [
|
|
135
|
-
ids
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
{ Category: 'spooky-client::SyncEngine::handleRemovedRecords' },
|
|
143
|
-
'Remote existence check failed, proceeding with deletion'
|
|
179
|
+
const [existing] = await this.remote.query<[(RecordId | null | undefined)[]]>(
|
|
180
|
+
'SELECT VALUE id FROM $ids',
|
|
181
|
+
{ ids: removed }
|
|
182
|
+
);
|
|
183
|
+
existingRemoteIds = new Set(
|
|
184
|
+
(existing ?? [])
|
|
185
|
+
.filter((id): id is RecordId => id != null)
|
|
186
|
+
.map((id) => encodeRecordId(id))
|
|
144
187
|
);
|
|
188
|
+
} catch (err) {
|
|
189
|
+
// Verification failed. Skip deletion entirely — the next sync
|
|
190
|
+
// round re-derives the diff and we get another shot. The
|
|
191
|
+
// alternative (delete on uncertainty) destroys freshly-created
|
|
192
|
+
// rows when the SSP hasn't yet refreshed `_00_list_ref`.
|
|
193
|
+
this.logger.warn(
|
|
194
|
+
{
|
|
195
|
+
err,
|
|
196
|
+
removed: removed.map((r) => r.toString()),
|
|
197
|
+
Category: 'sp00ky-client::SyncEngine::handleRemovedRecords',
|
|
198
|
+
},
|
|
199
|
+
'Remote existence check failed, skipping deletion to avoid clobbering fresh data'
|
|
200
|
+
);
|
|
201
|
+
return [];
|
|
145
202
|
}
|
|
146
203
|
|
|
204
|
+
// Ids that left the view's list_ref but STILL exist upstream — not deletions,
|
|
205
|
+
// just a view-membership change (e.g. a record whose field changed so it no
|
|
206
|
+
// longer matches the query). The caller drops these from `localArray` so the
|
|
207
|
+
// poll's diff stops re-flagging them every tick (the `job:` churn).
|
|
208
|
+
const stillRemoteIds: string[] = [];
|
|
147
209
|
for (const recordId of removed) {
|
|
148
210
|
const recordIdStr = encodeRecordId(recordId);
|
|
149
211
|
if (!existingRemoteIds.has(recordIdStr)) {
|
|
150
212
|
this.logger.debug(
|
|
151
213
|
{
|
|
152
214
|
recordId: recordIdStr,
|
|
153
|
-
Category: '
|
|
215
|
+
Category: 'sp00ky-client::SyncEngine::handleRemovedRecords',
|
|
154
216
|
},
|
|
155
217
|
'Deleting confirmed removed record'
|
|
156
218
|
);
|
|
157
|
-
|
|
158
219
|
// Use CacheModule to handle both local DB and DBSP deletion
|
|
159
220
|
await this.cache.delete(recordId.table.name, recordIdStr);
|
|
221
|
+
} else {
|
|
222
|
+
stillRemoteIds.push(recordIdStr);
|
|
160
223
|
}
|
|
161
224
|
}
|
|
225
|
+
return stillRemoteIds;
|
|
162
226
|
}
|
|
163
227
|
}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
1
|
+
import type { EventDefinition, EventSystem } from '../../../events/index';
|
|
2
|
+
import { createEventSystem } from '../../../events/index';
|
|
3
|
+
import type { RecordVersionArray, SyncHealth } from '../../../types';
|
|
3
4
|
|
|
4
5
|
export const SyncQueueEventTypes = {
|
|
5
6
|
MutationEnqueued: 'MUTATION_ENQUEUED',
|
|
@@ -36,6 +37,7 @@ export const SyncEventTypes = {
|
|
|
36
37
|
QueryUpdated: 'SYNC_QUERY_UPDATED',
|
|
37
38
|
RemoteDataIngested: 'SYNC_REMOTE_DATA_INGESTED',
|
|
38
39
|
MutationRolledBack: 'SYNC_MUTATION_ROLLED_BACK',
|
|
40
|
+
SyncHealthChanged: 'SYNC_HEALTH_CHANGED',
|
|
39
41
|
} as const;
|
|
40
42
|
|
|
41
43
|
export type SyncEventTypeMap = {
|
|
@@ -64,6 +66,10 @@ export type SyncEventTypeMap = {
|
|
|
64
66
|
error: string;
|
|
65
67
|
}
|
|
66
68
|
>;
|
|
69
|
+
[SyncEventTypes.SyncHealthChanged]: EventDefinition<
|
|
70
|
+
typeof SyncEventTypes.SyncHealthChanged,
|
|
71
|
+
SyncHealth
|
|
72
|
+
>;
|
|
67
73
|
};
|
|
68
74
|
|
|
69
75
|
export type SyncEventSystem = EventSystem<SyncEventTypeMap>;
|
|
@@ -73,5 +79,6 @@ export function createSyncEventSystem(): SyncEventSystem {
|
|
|
73
79
|
SyncEventTypes.QueryUpdated,
|
|
74
80
|
SyncEventTypes.RemoteDataIngested,
|
|
75
81
|
SyncEventTypes.MutationRolledBack,
|
|
82
|
+
SyncEventTypes.SyncHealthChanged,
|
|
76
83
|
]);
|
|
77
84
|
}
|
|
@@ -1,10 +1,11 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import type { LocalStore } from '../../../services/database/index';
|
|
2
|
+
import type {
|
|
3
|
+
SyncQueueEventSystem} from '../events/index';
|
|
2
4
|
import {
|
|
3
5
|
createSyncQueueEventSystem,
|
|
4
|
-
SyncQueueEventSystem,
|
|
5
6
|
SyncQueueEventTypes,
|
|
6
7
|
} from '../events/index';
|
|
7
|
-
import { Logger } from '../../../services/logger/index';
|
|
8
|
+
import type { Logger } from '../../../services/logger/index';
|
|
8
9
|
|
|
9
10
|
export type RegisterEvent = {
|
|
10
11
|
type: 'register';
|
|
@@ -46,7 +47,7 @@ export class DownQueue {
|
|
|
46
47
|
}
|
|
47
48
|
|
|
48
49
|
constructor(
|
|
49
|
-
private local:
|
|
50
|
+
private local: LocalStore,
|
|
50
51
|
logger: Logger
|
|
51
52
|
) {
|
|
52
53
|
this._events = createSyncQueueEventSystem();
|
|
@@ -71,6 +72,12 @@ export class DownQueue {
|
|
|
71
72
|
});
|
|
72
73
|
}
|
|
73
74
|
|
|
75
|
+
/** Drop all queued events (bucket switch: old-bucket register/sync work is
|
|
76
|
+
* re-derived after the switch; replaying it would target dead query rows). */
|
|
77
|
+
clear(): void {
|
|
78
|
+
this.queue = [];
|
|
79
|
+
}
|
|
80
|
+
|
|
74
81
|
async next(fn: (event: DownEvent) => Promise<void>): Promise<void> {
|
|
75
82
|
const event = this.queue.shift();
|
|
76
83
|
if (event) {
|
|
@@ -78,7 +85,7 @@ export class DownQueue {
|
|
|
78
85
|
await fn(event);
|
|
79
86
|
} catch (error) {
|
|
80
87
|
this.logger.error(
|
|
81
|
-
{ error, event, Category: '
|
|
88
|
+
{ error, event, Category: 'sp00ky-client::DownQueue::next' },
|
|
82
89
|
'Failed to process query'
|
|
83
90
|
);
|
|
84
91
|
this.queue.unshift(event);
|
|
@@ -1,13 +1,14 @@
|
|
|
1
|
-
import { RecordId } from 'surrealdb';
|
|
2
|
-
import {
|
|
1
|
+
import type { RecordId } from 'surrealdb';
|
|
2
|
+
import type { LocalStore } from '../../../services/database/index';
|
|
3
|
+
import type {
|
|
4
|
+
SyncQueueEventSystem} from '../events/index';
|
|
3
5
|
import {
|
|
4
6
|
createSyncQueueEventSystem,
|
|
5
|
-
SyncQueueEventSystem,
|
|
6
7
|
SyncQueueEventTypes,
|
|
7
8
|
} from '../events/index';
|
|
8
9
|
import { parseRecordIdString, extractTablePart, classifySyncError } from '../../../utils/index';
|
|
9
|
-
import { Logger } from '../../../services/logger/index';
|
|
10
|
-
import { PushEventOptions } from '../../../events/index';
|
|
10
|
+
import type { Logger } from '../../../services/logger/index';
|
|
11
|
+
import type { PushEventOptions } from '../../../events/index';
|
|
11
12
|
|
|
12
13
|
export type CreateEvent = {
|
|
13
14
|
type: 'create';
|
|
@@ -51,7 +52,7 @@ export class UpQueue {
|
|
|
51
52
|
}
|
|
52
53
|
|
|
53
54
|
constructor(
|
|
54
|
-
private local:
|
|
55
|
+
private local: LocalStore,
|
|
55
56
|
logger: Logger
|
|
56
57
|
) {
|
|
57
58
|
this._events = createSyncQueueEventSystem();
|
|
@@ -104,6 +105,20 @@ export class UpQueue {
|
|
|
104
105
|
this.debouncedMutations.set(key, { timer, firstBeforeRecord });
|
|
105
106
|
}
|
|
106
107
|
|
|
108
|
+
/**
|
|
109
|
+
* Cancel all pending debounce timers WITHOUT enqueueing their events. Used
|
|
110
|
+
* on local-bucket switches: the mutation's `_00_pending_mutations` row was
|
|
111
|
+
* already persisted at mutation time, so dropping the in-memory push only
|
|
112
|
+
* defers it to that bucket's next `loadFromDatabase` — it must NOT be pushed
|
|
113
|
+
* now, the remote session already belongs to the next user.
|
|
114
|
+
*/
|
|
115
|
+
clearDebounceTimers(): void {
|
|
116
|
+
for (const { timer } of this.debouncedMutations.values()) {
|
|
117
|
+
clearTimeout(timer);
|
|
118
|
+
}
|
|
119
|
+
this.debouncedMutations.clear();
|
|
120
|
+
}
|
|
121
|
+
|
|
107
122
|
async next(fn: (event: UpEvent) => Promise<void>, onRollback?: RollbackCallback): Promise<void> {
|
|
108
123
|
const event = this.queue.shift();
|
|
109
124
|
if (event) {
|
|
@@ -114,7 +129,7 @@ export class UpQueue {
|
|
|
114
129
|
|
|
115
130
|
if (errorType === 'network') {
|
|
116
131
|
this.logger.error(
|
|
117
|
-
{ error, event, Category: '
|
|
132
|
+
{ error, event, Category: 'sp00ky-client::UpQueue::next' },
|
|
118
133
|
'Network error processing mutation, re-queuing'
|
|
119
134
|
);
|
|
120
135
|
this.queue.unshift(event);
|
|
@@ -123,14 +138,14 @@ export class UpQueue {
|
|
|
123
138
|
|
|
124
139
|
// Application error — rollback instead of re-queuing
|
|
125
140
|
this.logger.error(
|
|
126
|
-
{ error, event, Category: '
|
|
141
|
+
{ error, event, Category: 'sp00ky-client::UpQueue::next' },
|
|
127
142
|
'Application error processing mutation, rolling back'
|
|
128
143
|
);
|
|
129
144
|
try {
|
|
130
145
|
await this.removeEventFromDatabase(event.mutation_id);
|
|
131
146
|
} catch (removeError) {
|
|
132
147
|
this.logger.error(
|
|
133
|
-
{ error: removeError, event, Category: '
|
|
148
|
+
{ error: removeError, event, Category: 'sp00ky-client::UpQueue::next' },
|
|
134
149
|
'Failed to remove rolled-back mutation from database'
|
|
135
150
|
);
|
|
136
151
|
}
|
|
@@ -139,7 +154,7 @@ export class UpQueue {
|
|
|
139
154
|
await onRollback(event, error instanceof Error ? error : new Error(String(error)));
|
|
140
155
|
} catch (rollbackError) {
|
|
141
156
|
this.logger.error(
|
|
142
|
-
{ error: rollbackError, event, Category: '
|
|
157
|
+
{ error: rollbackError, event, Category: 'sp00ky-client::UpQueue::next' },
|
|
143
158
|
'Rollback handler failed'
|
|
144
159
|
);
|
|
145
160
|
}
|
|
@@ -154,7 +169,7 @@ export class UpQueue {
|
|
|
154
169
|
await this.removeEventFromDatabase(event.mutation_id);
|
|
155
170
|
} catch (error) {
|
|
156
171
|
this.logger.error(
|
|
157
|
-
{ error, event, Category: '
|
|
172
|
+
{ error, event, Category: 'sp00ky-client::UpQueue::next' },
|
|
158
173
|
'Failed to remove mutation from database after successful processing'
|
|
159
174
|
);
|
|
160
175
|
}
|
|
@@ -172,7 +187,7 @@ export class UpQueue {
|
|
|
172
187
|
async loadFromDatabase() {
|
|
173
188
|
try {
|
|
174
189
|
const [records] = await this.local.query<any>(
|
|
175
|
-
`SELECT * FROM
|
|
190
|
+
`SELECT * FROM _00_pending_mutations ORDER BY created_at ASC`
|
|
176
191
|
);
|
|
177
192
|
|
|
178
193
|
this.queue = records
|
|
@@ -205,7 +220,7 @@ export class UpQueue {
|
|
|
205
220
|
{
|
|
206
221
|
mutationType: r.mutationType,
|
|
207
222
|
record: r,
|
|
208
|
-
Category: '
|
|
223
|
+
Category: 'sp00ky-client::UpQueue::loadFromDatabase',
|
|
209
224
|
},
|
|
210
225
|
'Unknown mutation type'
|
|
211
226
|
);
|
|
@@ -215,7 +230,7 @@ export class UpQueue {
|
|
|
215
230
|
.filter((e: UpEvent | null): e is UpEvent => e !== null);
|
|
216
231
|
} catch (error) {
|
|
217
232
|
this.logger.error(
|
|
218
|
-
{ error, Category: '
|
|
233
|
+
{ error, Category: 'sp00ky-client::UpQueue::loadFromDatabase' },
|
|
219
234
|
'Failed to load pending mutations from database'
|
|
220
235
|
);
|
|
221
236
|
}
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
import { describe, it, expect, vi } from 'vitest';
|
|
2
|
+
import { SyncScheduler } from './scheduler';
|
|
3
|
+
import type { UpQueue, DownQueue, UpEvent } from './queue/index';
|
|
4
|
+
|
|
5
|
+
// `SyncScheduler.pause()` is the drain step of a local-bucket switch: it must
|
|
6
|
+
// (a) let an IN-FLIGHT queue item finish — including its outbox-row delete,
|
|
7
|
+
// which has to land in the old bucket — and only then resolve, and (b) refuse
|
|
8
|
+
// to start new rounds until `resume()`. The pause point is between items.
|
|
9
|
+
|
|
10
|
+
const silentLogger = {
|
|
11
|
+
child: () => silentLogger,
|
|
12
|
+
debug: () => {},
|
|
13
|
+
info: () => {},
|
|
14
|
+
warn: () => {},
|
|
15
|
+
error: () => {},
|
|
16
|
+
} as any;
|
|
17
|
+
|
|
18
|
+
function makeQueues(items: UpEvent[]) {
|
|
19
|
+
const upQueue = {
|
|
20
|
+
queue: [...items],
|
|
21
|
+
get size() {
|
|
22
|
+
return this.queue.length;
|
|
23
|
+
},
|
|
24
|
+
events: { subscribe: () => {} },
|
|
25
|
+
loadFromDatabase: async () => {},
|
|
26
|
+
async next(fn: (event: UpEvent) => Promise<void>) {
|
|
27
|
+
const event = this.queue.shift();
|
|
28
|
+
if (event) await fn(event);
|
|
29
|
+
},
|
|
30
|
+
} as unknown as UpQueue & { queue: UpEvent[] };
|
|
31
|
+
|
|
32
|
+
const downQueue = {
|
|
33
|
+
queue: [] as unknown[],
|
|
34
|
+
get size() {
|
|
35
|
+
return this.queue.length;
|
|
36
|
+
},
|
|
37
|
+
events: { subscribe: () => {} },
|
|
38
|
+
async next() {},
|
|
39
|
+
clear() {
|
|
40
|
+
this.queue = [];
|
|
41
|
+
},
|
|
42
|
+
} as unknown as DownQueue;
|
|
43
|
+
|
|
44
|
+
return { upQueue, downQueue };
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
const upEvent = (n: number) => ({ type: 'delete', mutation_id: n, record_id: n }) as unknown as UpEvent;
|
|
48
|
+
|
|
49
|
+
describe('SyncScheduler.pause', () => {
|
|
50
|
+
it('waits for the in-flight item (push + outbox delete) before resolving', async () => {
|
|
51
|
+
const { upQueue, downQueue } = makeQueues([upEvent(1), upEvent(2)]);
|
|
52
|
+
let release!: () => void;
|
|
53
|
+
const gate = new Promise<void>((r) => (release = r));
|
|
54
|
+
const processed: unknown[] = [];
|
|
55
|
+
const scheduler = new SyncScheduler(
|
|
56
|
+
upQueue,
|
|
57
|
+
downQueue,
|
|
58
|
+
async (event) => {
|
|
59
|
+
await gate; // simulate a slow remote push
|
|
60
|
+
processed.push(event);
|
|
61
|
+
},
|
|
62
|
+
async () => {},
|
|
63
|
+
silentLogger
|
|
64
|
+
);
|
|
65
|
+
|
|
66
|
+
const round = scheduler.syncUp();
|
|
67
|
+
const pauseDone = vi.fn();
|
|
68
|
+
const pause = scheduler.pause().then(pauseDone);
|
|
69
|
+
|
|
70
|
+
// The in-flight item hasn't finished — pause must not have resolved.
|
|
71
|
+
await Promise.resolve();
|
|
72
|
+
expect(pauseDone).not.toHaveBeenCalled();
|
|
73
|
+
|
|
74
|
+
release();
|
|
75
|
+
await pause;
|
|
76
|
+
await round;
|
|
77
|
+
// Exactly the in-flight item completed; the second stayed queued.
|
|
78
|
+
expect(processed).toHaveLength(1);
|
|
79
|
+
expect(upQueue.size).toBe(1);
|
|
80
|
+
});
|
|
81
|
+
|
|
82
|
+
it('refuses new rounds while paused and drains them on resume', async () => {
|
|
83
|
+
const { upQueue, downQueue } = makeQueues([upEvent(1)]);
|
|
84
|
+
const processed: unknown[] = [];
|
|
85
|
+
const scheduler = new SyncScheduler(
|
|
86
|
+
upQueue,
|
|
87
|
+
downQueue,
|
|
88
|
+
async (event) => {
|
|
89
|
+
processed.push(event);
|
|
90
|
+
},
|
|
91
|
+
async () => {},
|
|
92
|
+
silentLogger
|
|
93
|
+
);
|
|
94
|
+
|
|
95
|
+
await scheduler.pause();
|
|
96
|
+
await scheduler.syncUp();
|
|
97
|
+
expect(processed).toHaveLength(0);
|
|
98
|
+
|
|
99
|
+
scheduler.resume();
|
|
100
|
+
await vi.waitFor(() => expect(processed).toHaveLength(1));
|
|
101
|
+
expect(upQueue.size).toBe(0);
|
|
102
|
+
});
|
|
103
|
+
|
|
104
|
+
it('resolves immediately when nothing is in flight', async () => {
|
|
105
|
+
const { upQueue, downQueue } = makeQueues([]);
|
|
106
|
+
const scheduler = new SyncScheduler(upQueue, downQueue, async () => {}, async () => {}, silentLogger);
|
|
107
|
+
await expect(scheduler.pause()).resolves.toBeUndefined();
|
|
108
|
+
});
|
|
109
|
+
});
|