@spooky-sync/core 0.0.1-canary.98 → 1.0.0-beta.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (279) hide show
  1. package/AGENTS.md +58 -21
  2. package/README.md +59 -16
  3. package/dist/index.d.ts +2235 -908
  4. package/dist/index.js +20424 -5052
  5. package/dist/live.d.ts +149 -0
  6. package/dist/live.js +739 -0
  7. package/dist/otel/index.d.ts +1 -1
  8. package/dist/pure.d.ts +401 -0
  9. package/dist/pure.js +24 -0
  10. package/dist/rows-worker.d.ts +1 -0
  11. package/dist/rows-worker.js +2639 -0
  12. package/dist/sqlite-open.js +392 -0
  13. package/dist/sqlite-worker.d.ts +1 -0
  14. package/dist/sqlite-worker.js +439 -0
  15. package/dist/sw.d.ts +207 -0
  16. package/dist/sw.js +393 -0
  17. package/dist/tabs-broker-worker.d.ts +8 -0
  18. package/dist/tabs-broker-worker.js +477 -0
  19. package/dist/types.d.ts +2084 -82
  20. package/dist/worker-edges.js +498 -0
  21. package/dist/worker-impersonation.js +60 -0
  22. package/dist/worker-ref-tables.d.ts +48 -0
  23. package/dist/worker-types.d.ts +112 -0
  24. package/dist/worker-types.js +73 -0
  25. package/package.json +39 -8
  26. package/scripts/check-broker-bundle.mjs +33 -0
  27. package/scripts/check-worker-entries.mjs +186 -0
  28. package/skills/sp00ky-core/SKILL.md +44 -8
  29. package/skills/sp00ky-core/references/config.md +8 -2
  30. package/src/boot/auth-flip.saga.test.ts +174 -0
  31. package/src/boot/auth-flip.saga.ts +77 -0
  32. package/src/boot/boot.saga.test.ts +203 -0
  33. package/src/boot/boot.saga.ts +146 -0
  34. package/src/boot/bucket-switch.saga.test.ts +191 -0
  35. package/src/boot/bucket-switch.saga.ts +151 -0
  36. package/src/boot/preload.saga.test.ts +96 -0
  37. package/src/boot/preload.saga.ts +45 -0
  38. package/src/bucket-blurhash.test.ts +148 -0
  39. package/src/client/bucket-handle.test.ts +195 -0
  40. package/src/client/bucket-handle.ts +372 -0
  41. package/src/client/eager-paint.test.ts +82 -0
  42. package/src/client/router.test.ts +59 -0
  43. package/src/client/router.ts +104 -0
  44. package/src/client/runtime.test.ts +319 -0
  45. package/src/client/runtime.ts +307 -0
  46. package/src/client/services.test.ts +74 -0
  47. package/src/client/services.ts +440 -0
  48. package/src/client/sp00ky-client.test.ts +570 -0
  49. package/src/client/sp00ky-client.ts +875 -0
  50. package/src/index.ts +87 -0
  51. package/src/kernel/constants.test.ts +19 -0
  52. package/src/kernel/constants.ts +94 -0
  53. package/src/kernel/effects.test.ts +40 -0
  54. package/src/kernel/effects.ts +181 -0
  55. package/src/kernel/events.ts +60 -0
  56. package/src/kernel/interpreter.test.ts +133 -0
  57. package/src/kernel/interpreter.ts +151 -0
  58. package/src/kernel/saga.test.ts +89 -0
  59. package/src/kernel/saga.ts +73 -0
  60. package/src/live/index.test.ts +512 -0
  61. package/src/live/index.ts +1059 -0
  62. package/src/modules/app-release/index.test.ts +125 -0
  63. package/src/modules/app-release/index.ts +209 -0
  64. package/src/modules/auth/auth.local-first.test.ts +228 -0
  65. package/src/modules/auth/auth.session-recheck.test.ts +140 -0
  66. package/src/modules/auth/events/index.ts +7 -1
  67. package/src/modules/auth/impersonation-banner.ts +443 -0
  68. package/src/modules/auth/impersonation.integration.test.ts +209 -0
  69. package/src/modules/auth/impersonation.test.ts +377 -0
  70. package/src/modules/auth/impersonation.ts +179 -0
  71. package/src/modules/auth/index.ts +516 -34
  72. package/src/modules/channel/channel.test.ts +752 -0
  73. package/src/modules/channel/hub.test.ts +223 -0
  74. package/src/modules/channel/hub.ts +355 -0
  75. package/src/modules/channel/index.ts +1497 -0
  76. package/src/modules/channel/room.test.ts +340 -0
  77. package/src/modules/channel/room.ts +367 -0
  78. package/src/modules/channel/rooms.fixture.ts +383 -0
  79. package/src/modules/channel/share.test.ts +535 -0
  80. package/src/modules/channel/webrtc.ts +472 -0
  81. package/src/modules/crdt/acceptance.ts +75 -0
  82. package/src/modules/crdt/bytes.ts +50 -0
  83. package/src/modules/crdt/crdt-field.ts +82 -238
  84. package/src/modules/crdt/crdt.test.ts +546 -0
  85. package/src/modules/crdt/hash.ts +103 -0
  86. package/src/modules/crdt/index.ts +740 -271
  87. package/src/modules/crdt/loro-loader.ts +25 -0
  88. package/src/modules/crdt/mirror.ts +37 -0
  89. package/src/modules/devtools/flags.ts +349 -0
  90. package/src/modules/devtools/index.ts +661 -99
  91. package/src/modules/devtools/mutations.test.ts +92 -0
  92. package/src/modules/devtools/mutations.ts +160 -0
  93. package/src/modules/devtools/notify-throttle.test.ts +166 -0
  94. package/src/modules/devtools/state-shape.test.ts +263 -0
  95. package/src/modules/devtools/storage-info.test.ts +79 -0
  96. package/src/modules/devtools/storage-info.ts +169 -0
  97. package/src/modules/devtools/versions.ts +29 -0
  98. package/src/modules/feature-flag/index.test.ts +179 -1
  99. package/src/modules/feature-flag/index.ts +117 -10
  100. package/src/modules/ref-tables.test.ts +28 -1
  101. package/src/modules/ref-tables.ts +23 -1
  102. package/src/modules/web-push/index.test.ts +824 -0
  103. package/src/modules/web-push/index.ts +1027 -0
  104. package/src/mutation/ingest-outage.integration.test.ts +400 -0
  105. package/src/mutation/jobs.test.ts +25 -0
  106. package/src/mutation/jobs.ts +41 -0
  107. package/src/mutation/mutation-id.test.ts +37 -0
  108. package/src/mutation/mutation-id.ts +35 -0
  109. package/src/mutation/pending-writes.integration.test.ts +175 -0
  110. package/src/mutation/push.saga.test.ts +361 -0
  111. package/src/mutation/push.saga.ts +245 -0
  112. package/src/mutation/rows.test.ts +278 -0
  113. package/src/mutation/rows.ts +515 -0
  114. package/src/mutation/tray.saga.test.ts +63 -0
  115. package/src/mutation/tray.saga.ts +48 -0
  116. package/src/mutation/write.saga.test.ts +436 -0
  117. package/src/mutation/write.saga.ts +384 -0
  118. package/src/pure.ts +66 -0
  119. package/src/push/types.ts +174 -0
  120. package/src/query/anon-query-isolation.integration.test.ts +531 -0
  121. package/src/query/env.test.ts +23 -0
  122. package/src/query/env.ts +65 -0
  123. package/src/query/fetch.saga.test.ts +199 -0
  124. package/src/query/fetch.saga.ts +120 -0
  125. package/src/query/hash.test.ts +14 -0
  126. package/src/query/hash.ts +18 -0
  127. package/src/query/id-set-plan.test.ts +132 -0
  128. package/src/query/lifecycle.saga.test.ts +274 -0
  129. package/src/query/lifecycle.saga.ts +186 -0
  130. package/src/query/list-ref-live.integration.test.ts +203 -0
  131. package/src/query/materialize.saga.test.ts +216 -0
  132. package/src/query/materialize.saga.ts +83 -0
  133. package/src/query/materialize.test.ts +58 -0
  134. package/src/query/materialize.ts +133 -0
  135. package/src/query/membership.saga.test.ts +514 -0
  136. package/src/query/membership.saga.ts +339 -0
  137. package/src/query/membership.test.ts +151 -0
  138. package/src/query/membership.ts +234 -0
  139. package/src/query/register.saga.test.ts +430 -0
  140. package/src/query/register.saga.ts +330 -0
  141. package/src/query/render-set.test.ts +47 -0
  142. package/src/query/render-set.ts +71 -0
  143. package/src/query/session-guard.integration.test.ts +304 -0
  144. package/src/query/sql.test.ts +118 -0
  145. package/src/query/sql.ts +174 -0
  146. package/src/{modules/data → query}/window-query.test.ts +22 -4
  147. package/src/{modules/data → query}/window-query.ts +86 -8
  148. package/src/services/blobs/blob-cache.test.ts +359 -0
  149. package/src/services/blobs/blob-cache.ts +603 -0
  150. package/src/services/blobs/blob-manifest.ts +227 -0
  151. package/src/services/blobs/blob-store.test.ts +77 -0
  152. package/src/services/blobs/blob-store.ts +359 -0
  153. package/src/services/blobs/blob.fixture.ts +90 -0
  154. package/src/services/blobs/index.ts +70 -0
  155. package/src/services/database/cache-engine.ts +223 -0
  156. package/src/services/database/connection-supervisor.test.ts +318 -0
  157. package/src/services/database/connection-supervisor.ts +422 -0
  158. package/src/services/database/database.query-timeout.test.ts +140 -0
  159. package/src/services/database/database.responses.test.ts +43 -0
  160. package/src/services/database/database.ts +151 -56
  161. package/src/services/database/engine-factory.ts +40 -0
  162. package/src/services/database/errors.ts +34 -0
  163. package/src/services/database/index.ts +8 -0
  164. package/src/services/database/landed-body-clear.integration.test.ts +236 -0
  165. package/src/services/database/local-migrator.integration.test.ts +110 -0
  166. package/src/services/database/local-migrator.ts +54 -9
  167. package/src/services/database/local.test.ts +117 -0
  168. package/src/services/database/local.ts +364 -74
  169. package/src/services/database/plan-render.test.ts +159 -0
  170. package/src/services/database/plan-render.ts +108 -0
  171. package/src/services/database/relation-resolver.test.ts +484 -0
  172. package/src/services/database/relation-resolver.ts +0 -0
  173. package/src/services/database/remote.ts +283 -4
  174. package/src/services/database/rows-cache-engine.test.ts +1014 -0
  175. package/src/services/database/rows-cache-engine.ts +921 -0
  176. package/src/services/database/rows-exec.integration.test.ts +589 -0
  177. package/src/services/database/rows-exec.ts +1027 -0
  178. package/src/services/database/rows-prewarm.ts +225 -0
  179. package/src/services/database/rows-store.test.ts +635 -0
  180. package/src/services/database/rows-store.ts +1208 -0
  181. package/src/services/database/rows-transport.fixture.ts +151 -0
  182. package/src/services/database/rows-worker.ts +588 -0
  183. package/src/services/database/sqlite-cache-engine.test.ts +649 -0
  184. package/src/services/database/sqlite-cache-engine.timeout.test.ts +61 -0
  185. package/src/services/database/sqlite-cache-engine.ts +1422 -0
  186. package/src/services/database/sqlite-column-reset.integration.test.ts +100 -0
  187. package/src/services/database/sqlite-column-reset.ts +91 -0
  188. package/src/services/database/sqlite-devtools-queries.integration.test.ts +143 -0
  189. package/src/services/database/sqlite-devtools-queries.test.ts +154 -0
  190. package/src/services/database/sqlite-lock-verify.test.ts +33 -0
  191. package/src/services/database/sqlite-lock-verify.ts +45 -0
  192. package/src/services/database/sqlite-open.test.ts +150 -0
  193. package/src/services/database/sqlite-open.ts +164 -0
  194. package/src/services/database/sqlite-plan-sql.test.ts +164 -0
  195. package/src/services/database/sqlite-plan-sql.ts +196 -0
  196. package/src/services/database/sqlite-projection.test.ts +121 -0
  197. package/src/services/database/sqlite-select.integration.test.ts +185 -0
  198. package/src/services/database/sqlite-select.test.ts +261 -0
  199. package/src/services/database/sqlite-select.ts +131 -0
  200. package/src/services/database/sqlite-transport.fixture.ts +30 -0
  201. package/src/services/database/sqlite-transport.ts +231 -0
  202. package/src/services/database/sqlite-worker.ts +437 -0
  203. package/src/services/database/surql-translate.ts +417 -0
  204. package/src/services/database/surreal-cache-engine.ts +163 -0
  205. package/src/services/logger/index.test.ts +132 -0
  206. package/src/services/logger/index.ts +187 -6
  207. package/src/services/persistence/surrealdb.ts +2 -2
  208. package/src/services/stream-processor/index.ts +621 -93
  209. package/src/services/stream-processor/stream-processor.batch.test.ts +57 -7
  210. package/src/services/stream-processor/stream-processor.prime.test.ts +234 -0
  211. package/src/services/stream-processor/stream-processor.reset.test.ts +226 -0
  212. package/src/services/stream-processor/wasm-types.ts +41 -1
  213. package/src/services/tabs/broker-client.ts +284 -0
  214. package/src/services/tabs/broker.test.ts +381 -0
  215. package/src/services/tabs/coordinator.test.ts +386 -0
  216. package/src/services/tabs/coordinator.ts +646 -0
  217. package/src/services/tabs/fake-ports.fixture.ts +112 -0
  218. package/src/services/tabs/leader-locks.ts +75 -0
  219. package/src/services/tabs/protocol.ts +262 -0
  220. package/src/services/tabs/support.ts +38 -0
  221. package/src/services/tabs/tabs-broker-worker.ts +652 -0
  222. package/src/sp00ky.ts +5 -648
  223. package/src/state/client-state.ts +231 -0
  224. package/src/state/lifecycle.test.ts +184 -0
  225. package/src/state/lifecycle.ts +127 -0
  226. package/src/state/reducers.test.ts +337 -0
  227. package/src/state/reducers.ts +571 -0
  228. package/src/state/selectors.test.ts +203 -0
  229. package/src/state/selectors.ts +264 -0
  230. package/src/sw/index.test.ts +582 -0
  231. package/src/sw/index.ts +607 -0
  232. package/src/sw/store.ts +96 -0
  233. package/src/sync/connection.saga.test.ts +97 -0
  234. package/src/sync/connection.saga.ts +89 -0
  235. package/src/sync/live.saga.test.ts +229 -0
  236. package/src/sync/live.saga.ts +116 -0
  237. package/src/sync/policy.health.test.ts +56 -0
  238. package/src/{modules/sync/utils.test.ts → sync/policy.test.ts} +96 -11
  239. package/src/{modules/sync/utils.ts → sync/policy.ts} +186 -7
  240. package/src/sync/poll.saga.test.ts +51 -0
  241. package/src/sync/poll.saga.ts +36 -0
  242. package/src/sync/tabs.saga.test.ts +78 -0
  243. package/src/sync/tabs.saga.ts +96 -0
  244. package/src/testing/adapters.ts +137 -0
  245. package/src/testing/build.ts +63 -0
  246. package/src/testing/fake-services.ts +63 -0
  247. package/src/testing/run-pure.test.ts +92 -0
  248. package/src/testing/run-pure.ts +128 -0
  249. package/src/testing/services.ts +17 -0
  250. package/src/types.ts +601 -25
  251. package/src/utils/blurhash.ts +90 -0
  252. package/src/utils/edges.ts +57 -0
  253. package/src/utils/error-classification.test.ts +116 -0
  254. package/src/utils/error-classification.ts +74 -0
  255. package/src/utils/index.ts +58 -3
  256. package/src/utils/parser.test.ts +67 -102
  257. package/src/utils/parser.ts +62 -1
  258. package/src/utils/semver.test.ts +32 -0
  259. package/src/utils/semver.ts +30 -0
  260. package/src/utils/sha256.ts +15 -0
  261. package/src/utils/surql.ts +17 -15
  262. package/src/utils/utils.test.ts +3 -2
  263. package/tsdown.config.ts +105 -4
  264. package/vitest.config.ts +52 -0
  265. package/src/modules/cache/index.ts +0 -253
  266. package/src/modules/cache/types.ts +0 -19
  267. package/src/modules/crdt/crdt-hydration.test.ts +0 -206
  268. package/src/modules/data/data.status.test.ts +0 -108
  269. package/src/modules/data/data.test.ts +0 -58
  270. package/src/modules/data/index.ts +0 -1491
  271. package/src/modules/sync/engine.ts +0 -227
  272. package/src/modules/sync/events/index.ts +0 -84
  273. package/src/modules/sync/index.ts +0 -3
  274. package/src/modules/sync/queue/index.ts +0 -2
  275. package/src/modules/sync/queue/queue-down.ts +0 -90
  276. package/src/modules/sync/queue/queue-up.ts +0 -224
  277. package/src/modules/sync/scheduler.ts +0 -121
  278. package/src/modules/sync/sync.ts +0 -1244
  279. package/src/sp00ky.auth-order.test.ts +0 -65
@@ -1,227 +0,0 @@
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
- import { SyncEventTypes, createSyncEventSystem } from './events/index';
8
- import { encodeRecordId } from '../../utils/index';
9
- import { cleanRecord } from '../../utils/parser';
10
-
11
- /**
12
- * SyncEngine handles the core sync operations: fetching remote records,
13
- * caching them locally, and ingesting into DBSP.
14
- *
15
- * This is extracted from Sp00kySync to separate "how to sync" from "when to sync".
16
- */
17
- export class SyncEngine {
18
- private logger: Logger;
19
- public events = createSyncEventSystem();
20
-
21
- constructor(
22
- private remote: RemoteDatabaseService,
23
- private cache: CacheModule,
24
- private schema: SchemaStructure,
25
- logger: Logger
26
- ) {
27
- this.logger = logger.child({ service: 'Sp00kySync:SyncEngine' });
28
- }
29
-
30
- /**
31
- * Sync missing/updated/removed records between local and remote.
32
- * Main entry point for sync operations.
33
- * Uses batch processing to minimize events emitted.
34
- */
35
- async syncRecords(
36
- diff: RecordVersionDiff
37
- ): Promise<{ remoteFetchMs: number; stillRemoteIds: string[] }> {
38
- const { added, updated, removed } = diff;
39
-
40
- this.logger.debug(
41
- {
42
- added,
43
- updated,
44
- removed,
45
- Category: 'sp00ky-client::SyncEngine::syncRecords',
46
- },
47
- 'SyncEngine.syncRecords diff'
48
- );
49
-
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[] = [];
54
- if (removed.length > 0) {
55
- stillRemoteIds = await this.handleRemovedRecords(removed);
56
- }
57
-
58
- // Fetch added/updated records from remote
59
- const toFetch = [...added, ...updated];
60
- const idsToFetch = toFetch.map((x) => x.id);
61
- if (idsToFetch.length === 0) {
62
- return { remoteFetchMs: 0, stillRemoteIds };
63
- }
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();
75
- const [remoteResults] = await this.remote.query<[RecordWithId[]]>(
76
- 'SELECT * FROM $idsToFetch',
77
- { idsToFetch }
78
- );
79
- const remoteFetchMs = performance.now() - remoteFetchStart;
80
-
81
- // Prepare batch for cache (which handles both DB and DBSP)
82
- const cacheBatch: CacheRecord[] = [];
83
-
84
- for (const record of remoteResults) {
85
- if (!record?.id) {
86
- this.logger.warn(
87
- {
88
- record,
89
- idsToFetch,
90
- Category: 'sp00ky-client::SyncEngine::syncRecords',
91
- },
92
- 'Remote record has no id (possibly deleted). Skipping record'
93
- );
94
- continue;
95
- }
96
- const fullId = encodeRecordId(record.id);
97
- const table = record.id.table.toString();
98
- const isAdded = added.some((item) => encodeRecordId(item.id) === fullId);
99
- const version = versionMap.get(fullId) ?? 0;
100
-
101
- const localVersion = this.cache.lookup(fullId);
102
- if (localVersion && version <= localVersion) {
103
- this.logger.info(
104
- {
105
- recordId: fullId,
106
- version,
107
- localVersion,
108
- Category: 'sp00ky-client::SyncEngine::syncRecords',
109
- },
110
- 'Local version is higher than remote version. Skipping record'
111
- );
112
- continue;
113
- }
114
- const tableSchema = this.schema.tables.find((t) => t.name === table);
115
- const cleanedRecord = tableSchema
116
- ? cleanRecord(tableSchema.columns, record)
117
- : record;
118
-
119
- cacheBatch.push({
120
- table,
121
- op: isAdded ? 'CREATE' : 'UPDATE',
122
- record: cleanedRecord as RecordWithId,
123
- version,
124
- });
125
- }
126
-
127
- // Use CacheModule to handle both local DB and DBSP ingestion
128
- if (cacheBatch.length > 0) {
129
- await this.cache.saveBatch(cacheBatch);
130
- }
131
-
132
- this.events.emit(SyncEventTypes.RemoteDataIngested, {
133
- records: remoteResults,
134
- });
135
-
136
- return { remoteFetchMs, stillRemoteIds };
137
- }
138
-
139
- /**
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.
152
- */
153
- private async handleRemovedRecords(removed: RecordId[]): Promise<string[]> {
154
- this.logger.debug(
155
- {
156
- removed: removed.map((r) => r.toString()),
157
- Category: 'sp00ky-client::SyncEngine::handleRemovedRecords',
158
- },
159
- 'Checking removed records'
160
- );
161
-
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>;
178
- try {
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))
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 [];
202
- }
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[] = [];
209
- for (const recordId of removed) {
210
- const recordIdStr = encodeRecordId(recordId);
211
- if (!existingRemoteIds.has(recordIdStr)) {
212
- this.logger.debug(
213
- {
214
- recordId: recordIdStr,
215
- Category: 'sp00ky-client::SyncEngine::handleRemovedRecords',
216
- },
217
- 'Deleting confirmed removed record'
218
- );
219
- // Use CacheModule to handle both local DB and DBSP deletion
220
- await this.cache.delete(recordId.table.name, recordIdStr);
221
- } else {
222
- stillRemoteIds.push(recordIdStr);
223
- }
224
- }
225
- return stillRemoteIds;
226
- }
227
- }
@@ -1,84 +0,0 @@
1
- import type { EventDefinition, EventSystem } from '../../../events/index';
2
- import { createEventSystem } from '../../../events/index';
3
- import type { RecordVersionArray, SyncHealth } from '../../../types';
4
-
5
- export const SyncQueueEventTypes = {
6
- MutationEnqueued: 'MUTATION_ENQUEUED',
7
- MutationDequeued: 'MUTATION_DEQUEUED',
8
- QueryItemEnqueued: 'QUERY_ITEM_ENQUEUED',
9
- } as const;
10
-
11
- export type SyncQueueEventTypeMap = {
12
- [SyncQueueEventTypes.MutationEnqueued]: EventDefinition<
13
- typeof SyncQueueEventTypes.MutationEnqueued,
14
- { queueSize: number }
15
- >;
16
- [SyncQueueEventTypes.MutationDequeued]: EventDefinition<
17
- typeof SyncQueueEventTypes.MutationDequeued,
18
- { queueSize: number }
19
- >;
20
- [SyncQueueEventTypes.QueryItemEnqueued]: EventDefinition<
21
- typeof SyncQueueEventTypes.QueryItemEnqueued,
22
- { queueSize: number }
23
- >;
24
- };
25
-
26
- export type SyncQueueEventSystem = EventSystem<SyncQueueEventTypeMap>;
27
-
28
- export function createSyncQueueEventSystem(): SyncQueueEventSystem {
29
- return createEventSystem([
30
- SyncQueueEventTypes.QueryItemEnqueued,
31
- SyncQueueEventTypes.MutationEnqueued,
32
- SyncQueueEventTypes.MutationDequeued,
33
- ]);
34
- }
35
-
36
- export const SyncEventTypes = {
37
- QueryUpdated: 'SYNC_QUERY_UPDATED',
38
- RemoteDataIngested: 'SYNC_REMOTE_DATA_INGESTED',
39
- MutationRolledBack: 'SYNC_MUTATION_ROLLED_BACK',
40
- SyncHealthChanged: 'SYNC_HEALTH_CHANGED',
41
- } as const;
42
-
43
- export type SyncEventTypeMap = {
44
- [SyncEventTypes.QueryUpdated]: EventDefinition<
45
- typeof SyncEventTypes.QueryUpdated,
46
- {
47
- queryId: any; // RecordId<string> but imported
48
- localHash?: string;
49
- localArray?: RecordVersionArray;
50
- remoteHash?: string;
51
- remoteArray?: RecordVersionArray;
52
- records: Record<string, any>[];
53
- }
54
- >;
55
- [SyncEventTypes.RemoteDataIngested]: EventDefinition<
56
- typeof SyncEventTypes.RemoteDataIngested,
57
- {
58
- records: Record<string, any>[];
59
- }
60
- >;
61
- [SyncEventTypes.MutationRolledBack]: EventDefinition<
62
- typeof SyncEventTypes.MutationRolledBack,
63
- {
64
- eventType: string;
65
- recordId: string;
66
- error: string;
67
- }
68
- >;
69
- [SyncEventTypes.SyncHealthChanged]: EventDefinition<
70
- typeof SyncEventTypes.SyncHealthChanged,
71
- SyncHealth
72
- >;
73
- };
74
-
75
- export type SyncEventSystem = EventSystem<SyncEventTypeMap>;
76
-
77
- export function createSyncEventSystem(): SyncEventSystem {
78
- return createEventSystem([
79
- SyncEventTypes.QueryUpdated,
80
- SyncEventTypes.RemoteDataIngested,
81
- SyncEventTypes.MutationRolledBack,
82
- SyncEventTypes.SyncHealthChanged,
83
- ]);
84
- }
@@ -1,3 +0,0 @@
1
- export * from './events/index';
2
- export * from './sync';
3
- export * from './queue/index';
@@ -1,2 +0,0 @@
1
- export * from './queue-up';
2
- export * from './queue-down';
@@ -1,90 +0,0 @@
1
- import type { LocalDatabaseService } from '../../../services/database/index';
2
- import type {
3
- SyncQueueEventSystem} from '../events/index';
4
- import {
5
- createSyncQueueEventSystem,
6
- SyncQueueEventTypes,
7
- } from '../events/index';
8
- import type { Logger } from '../../../services/logger/index';
9
-
10
- export type RegisterEvent = {
11
- type: 'register';
12
- payload: {
13
- hash: string;
14
- };
15
- };
16
-
17
- export type SyncEvent = {
18
- type: 'sync';
19
- payload: {
20
- hash: string;
21
- };
22
- };
23
-
24
- export type HeartbeatEvent = {
25
- type: 'heartbeat';
26
- payload: {
27
- hash: string;
28
- };
29
- };
30
-
31
- export type CleanupEvent = {
32
- type: 'cleanup';
33
- payload: {
34
- hash: string;
35
- };
36
- };
37
-
38
- export type DownEvent = RegisterEvent | SyncEvent | HeartbeatEvent | CleanupEvent;
39
-
40
- export class DownQueue {
41
- private queue: DownEvent[] = [];
42
- private _events: SyncQueueEventSystem;
43
- private logger: Logger;
44
-
45
- get events(): SyncQueueEventSystem {
46
- return this._events;
47
- }
48
-
49
- constructor(
50
- private local: LocalDatabaseService,
51
- logger: Logger
52
- ) {
53
- this._events = createSyncQueueEventSystem();
54
- this.logger = logger.child({ service: 'DownQueue' });
55
- }
56
-
57
- get size(): number {
58
- return this.queue.length;
59
- }
60
-
61
- push(event: DownEvent) {
62
- this.queue.push(event);
63
- this.emitPushEvent();
64
- }
65
-
66
- private emitPushEvent() {
67
- this._events.addEvent({
68
- type: SyncQueueEventTypes.QueryItemEnqueued,
69
- payload: {
70
- queueSize: this.queue.length,
71
- },
72
- });
73
- }
74
-
75
- async next(fn: (event: DownEvent) => Promise<void>): Promise<void> {
76
- const event = this.queue.shift();
77
- if (event) {
78
- try {
79
- await fn(event);
80
- } catch (error) {
81
- this.logger.error(
82
- { error, event, Category: 'sp00ky-client::DownQueue::next' },
83
- 'Failed to process query'
84
- );
85
- this.queue.unshift(event);
86
- throw error;
87
- }
88
- }
89
- }
90
- }
@@ -1,224 +0,0 @@
1
- import type { RecordId } from 'surrealdb';
2
- import type { LocalDatabaseService } from '../../../services/database/index';
3
- import type {
4
- SyncQueueEventSystem} from '../events/index';
5
- import {
6
- createSyncQueueEventSystem,
7
- SyncQueueEventTypes,
8
- } from '../events/index';
9
- import { parseRecordIdString, extractTablePart, classifySyncError } from '../../../utils/index';
10
- import type { Logger } from '../../../services/logger/index';
11
- import type { PushEventOptions } from '../../../events/index';
12
-
13
- export type CreateEvent = {
14
- type: 'create';
15
- mutation_id: RecordId;
16
- record_id: RecordId;
17
- data: Record<string, unknown>;
18
- record?: Record<string, unknown>;
19
- tableName?: string;
20
- options?: PushEventOptions;
21
- };
22
-
23
- export type UpdateEvent = {
24
- type: 'update';
25
- mutation_id: RecordId;
26
- record_id: RecordId;
27
- data: Record<string, unknown>;
28
- record?: Record<string, unknown>;
29
- beforeRecord?: Record<string, unknown>;
30
- options?: PushEventOptions;
31
- };
32
-
33
- export type DeleteEvent = {
34
- type: 'delete';
35
- mutation_id: RecordId;
36
- record_id: RecordId;
37
- options?: PushEventOptions;
38
- };
39
-
40
- export type UpEvent = CreateEvent | UpdateEvent | DeleteEvent;
41
-
42
- export type RollbackCallback = (event: UpEvent, error: Error) => Promise<void>;
43
-
44
- export class UpQueue {
45
- private queue: UpEvent[] = [];
46
- private _events: SyncQueueEventSystem;
47
- private logger: Logger;
48
- private debouncedMutations: Map<string, { timer: any; firstBeforeRecord?: Record<string, unknown> }>;
49
-
50
- get events(): SyncQueueEventSystem {
51
- return this._events;
52
- }
53
-
54
- constructor(
55
- private local: LocalDatabaseService,
56
- logger: Logger
57
- ) {
58
- this._events = createSyncQueueEventSystem();
59
- this.logger = logger.child({ service: 'UpQueue' });
60
- this.debouncedMutations = new Map();
61
- }
62
-
63
- get size(): number {
64
- return this.queue.length;
65
- }
66
-
67
- push(event: UpEvent) {
68
- if (event.options?.debounced) {
69
- const { key, delay } = event.options.debounced;
70
- this.handleDebouncedMutation(event, key, delay);
71
- return;
72
- }
73
- this.addToQueue(event);
74
- }
75
-
76
- private addToQueue(event: UpEvent) {
77
- this.queue.push(event);
78
- this._events.addEvent({
79
- type: SyncQueueEventTypes.MutationEnqueued,
80
- payload: { queueSize: this.queue.length },
81
- });
82
- }
83
-
84
- private handleDebouncedMutation(event: UpEvent, key: string, delay: number) {
85
- const existing = this.debouncedMutations.get(key);
86
- let firstBeforeRecord: Record<string, unknown> | undefined;
87
-
88
- if (existing) {
89
- clearTimeout(existing.timer);
90
- // Preserve the beforeRecord from the first event in the debounce sequence
91
- firstBeforeRecord = existing.firstBeforeRecord;
92
- } else if (event.type === 'update') {
93
- firstBeforeRecord = event.beforeRecord;
94
- }
95
-
96
- const timer = setTimeout(() => {
97
- this.debouncedMutations.delete(key);
98
- // Attach the first beforeRecord to the final debounced event
99
- if (firstBeforeRecord && event.type === 'update') {
100
- event.beforeRecord = firstBeforeRecord;
101
- }
102
- this.addToQueue(event);
103
- }, delay);
104
-
105
- this.debouncedMutations.set(key, { timer, firstBeforeRecord });
106
- }
107
-
108
- async next(fn: (event: UpEvent) => Promise<void>, onRollback?: RollbackCallback): Promise<void> {
109
- const event = this.queue.shift();
110
- if (event) {
111
- try {
112
- await fn(event);
113
- } catch (error) {
114
- const errorType = classifySyncError(error);
115
-
116
- if (errorType === 'network') {
117
- this.logger.error(
118
- { error, event, Category: 'sp00ky-client::UpQueue::next' },
119
- 'Network error processing mutation, re-queuing'
120
- );
121
- this.queue.unshift(event);
122
- throw error;
123
- }
124
-
125
- // Application error — rollback instead of re-queuing
126
- this.logger.error(
127
- { error, event, Category: 'sp00ky-client::UpQueue::next' },
128
- 'Application error processing mutation, rolling back'
129
- );
130
- try {
131
- await this.removeEventFromDatabase(event.mutation_id);
132
- } catch (removeError) {
133
- this.logger.error(
134
- { error: removeError, event, Category: 'sp00ky-client::UpQueue::next' },
135
- 'Failed to remove rolled-back mutation from database'
136
- );
137
- }
138
- if (onRollback) {
139
- try {
140
- await onRollback(event, error instanceof Error ? error : new Error(String(error)));
141
- } catch (rollbackError) {
142
- this.logger.error(
143
- { error: rollbackError, event, Category: 'sp00ky-client::UpQueue::next' },
144
- 'Rollback handler failed'
145
- );
146
- }
147
- }
148
- this._events.addEvent({
149
- type: SyncQueueEventTypes.MutationDequeued,
150
- payload: { queueSize: this.queue.length },
151
- });
152
- return;
153
- }
154
- try {
155
- await this.removeEventFromDatabase(event.mutation_id);
156
- } catch (error) {
157
- this.logger.error(
158
- { error, event, Category: 'sp00ky-client::UpQueue::next' },
159
- 'Failed to remove mutation from database after successful processing'
160
- );
161
- }
162
- this._events.addEvent({
163
- type: SyncQueueEventTypes.MutationDequeued,
164
- payload: { queueSize: this.queue.length },
165
- });
166
- }
167
- }
168
-
169
- async removeEventFromDatabase(mutation_id: RecordId) {
170
- return this.local.query(`DELETE $mutation_id`, { mutation_id });
171
- }
172
-
173
- async loadFromDatabase() {
174
- try {
175
- const [records] = await this.local.query<any>(
176
- `SELECT * FROM _00_pending_mutations ORDER BY created_at ASC`
177
- );
178
-
179
- this.queue = records
180
- .map((r: any): UpEvent | null => {
181
- switch (r.mutationType) {
182
- case 'create':
183
- return {
184
- type: 'create',
185
- mutation_id: parseRecordIdString(r.id),
186
- record_id: parseRecordIdString(r.recordId),
187
- data: r.data,
188
- tableName: extractTablePart(r.recordId),
189
- };
190
- case 'update':
191
- return {
192
- type: 'update',
193
- mutation_id: parseRecordIdString(r.id),
194
- record_id: parseRecordIdString(r.recordId),
195
- data: r.data,
196
- beforeRecord: r.beforeRecord,
197
- };
198
- case 'delete':
199
- return {
200
- type: 'delete',
201
- mutation_id: parseRecordIdString(r.id),
202
- record_id: parseRecordIdString(r.recordId),
203
- };
204
- default:
205
- this.logger.warn(
206
- {
207
- mutationType: r.mutationType,
208
- record: r,
209
- Category: 'sp00ky-client::UpQueue::loadFromDatabase',
210
- },
211
- 'Unknown mutation type'
212
- );
213
- return null;
214
- }
215
- })
216
- .filter((e: UpEvent | null): e is UpEvent => e !== null);
217
- } catch (error) {
218
- this.logger.error(
219
- { error, Category: 'sp00ky-client::UpQueue::loadFromDatabase' },
220
- 'Failed to load pending mutations from database'
221
- );
222
- }
223
- }
224
- }