@syncular/server 0.0.1-60

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 (211) hide show
  1. package/dist/blobs/adapters/database.d.ts +83 -0
  2. package/dist/blobs/adapters/database.d.ts.map +1 -0
  3. package/dist/blobs/adapters/database.js +180 -0
  4. package/dist/blobs/adapters/database.js.map +1 -0
  5. package/dist/blobs/adapters/s3.d.ts +82 -0
  6. package/dist/blobs/adapters/s3.d.ts.map +1 -0
  7. package/dist/blobs/adapters/s3.js +170 -0
  8. package/dist/blobs/adapters/s3.js.map +1 -0
  9. package/dist/blobs/index.d.ts +9 -0
  10. package/dist/blobs/index.d.ts.map +1 -0
  11. package/dist/blobs/index.js +9 -0
  12. package/dist/blobs/index.js.map +1 -0
  13. package/dist/blobs/manager.d.ts +195 -0
  14. package/dist/blobs/manager.d.ts.map +1 -0
  15. package/dist/blobs/manager.js +440 -0
  16. package/dist/blobs/manager.js.map +1 -0
  17. package/dist/blobs/migrate.d.ts +27 -0
  18. package/dist/blobs/migrate.d.ts.map +1 -0
  19. package/dist/blobs/migrate.js +119 -0
  20. package/dist/blobs/migrate.js.map +1 -0
  21. package/dist/blobs/types.d.ts +54 -0
  22. package/dist/blobs/types.d.ts.map +1 -0
  23. package/dist/blobs/types.js +5 -0
  24. package/dist/blobs/types.js.map +1 -0
  25. package/dist/clients.d.ts +14 -0
  26. package/dist/clients.d.ts.map +1 -0
  27. package/dist/clients.js +7 -0
  28. package/dist/clients.js.map +1 -0
  29. package/dist/compaction.d.ts +27 -0
  30. package/dist/compaction.d.ts.map +1 -0
  31. package/dist/compaction.js +49 -0
  32. package/dist/compaction.js.map +1 -0
  33. package/dist/dialect/index.d.ts +5 -0
  34. package/dist/dialect/index.d.ts.map +1 -0
  35. package/dist/dialect/index.js +5 -0
  36. package/dist/dialect/index.js.map +1 -0
  37. package/dist/dialect/types.d.ts +170 -0
  38. package/dist/dialect/types.d.ts.map +1 -0
  39. package/dist/dialect/types.js +8 -0
  40. package/dist/dialect/types.js.map +1 -0
  41. package/dist/helpers/conflict.d.ts +52 -0
  42. package/dist/helpers/conflict.d.ts.map +1 -0
  43. package/dist/helpers/conflict.js +49 -0
  44. package/dist/helpers/conflict.js.map +1 -0
  45. package/dist/helpers/emitted-change.d.ts +56 -0
  46. package/dist/helpers/emitted-change.d.ts.map +1 -0
  47. package/dist/helpers/emitted-change.js +46 -0
  48. package/dist/helpers/emitted-change.js.map +1 -0
  49. package/dist/helpers/index.d.ts +10 -0
  50. package/dist/helpers/index.d.ts.map +1 -0
  51. package/dist/helpers/index.js +10 -0
  52. package/dist/helpers/index.js.map +1 -0
  53. package/dist/helpers/paginate.d.ts +49 -0
  54. package/dist/helpers/paginate.d.ts.map +1 -0
  55. package/dist/helpers/paginate.js +54 -0
  56. package/dist/helpers/paginate.js.map +1 -0
  57. package/dist/helpers/scope-strings.d.ts +74 -0
  58. package/dist/helpers/scope-strings.d.ts.map +1 -0
  59. package/dist/helpers/scope-strings.js +82 -0
  60. package/dist/helpers/scope-strings.js.map +1 -0
  61. package/dist/index.d.ts +28 -0
  62. package/dist/index.d.ts.map +1 -0
  63. package/dist/index.js +27 -0
  64. package/dist/index.js.map +1 -0
  65. package/dist/migrate.d.ts +14 -0
  66. package/dist/migrate.d.ts.map +1 -0
  67. package/dist/migrate.js +13 -0
  68. package/dist/migrate.js.map +1 -0
  69. package/dist/proxy/handler.d.ts +42 -0
  70. package/dist/proxy/handler.d.ts.map +1 -0
  71. package/dist/proxy/handler.js +99 -0
  72. package/dist/proxy/handler.js.map +1 -0
  73. package/dist/proxy/index.d.ts +9 -0
  74. package/dist/proxy/index.d.ts.map +1 -0
  75. package/dist/proxy/index.js +14 -0
  76. package/dist/proxy/index.js.map +1 -0
  77. package/dist/proxy/mutation-detector.d.ts +31 -0
  78. package/dist/proxy/mutation-detector.d.ts.map +1 -0
  79. package/dist/proxy/mutation-detector.js +61 -0
  80. package/dist/proxy/mutation-detector.js.map +1 -0
  81. package/dist/proxy/oplog.d.ts +30 -0
  82. package/dist/proxy/oplog.d.ts.map +1 -0
  83. package/dist/proxy/oplog.js +110 -0
  84. package/dist/proxy/oplog.js.map +1 -0
  85. package/dist/proxy/registry.d.ts +35 -0
  86. package/dist/proxy/registry.d.ts.map +1 -0
  87. package/dist/proxy/registry.js +49 -0
  88. package/dist/proxy/registry.js.map +1 -0
  89. package/dist/proxy/types.d.ts +44 -0
  90. package/dist/proxy/types.d.ts.map +1 -0
  91. package/dist/proxy/types.js +7 -0
  92. package/dist/proxy/types.js.map +1 -0
  93. package/dist/prune.d.ts +37 -0
  94. package/dist/prune.d.ts.map +1 -0
  95. package/dist/prune.js +112 -0
  96. package/dist/prune.js.map +1 -0
  97. package/dist/pull.d.ts +31 -0
  98. package/dist/pull.d.ts.map +1 -0
  99. package/dist/pull.js +414 -0
  100. package/dist/pull.js.map +1 -0
  101. package/dist/push.d.ts +33 -0
  102. package/dist/push.d.ts.map +1 -0
  103. package/dist/push.js +329 -0
  104. package/dist/push.js.map +1 -0
  105. package/dist/realtime/in-memory.d.ts +13 -0
  106. package/dist/realtime/in-memory.d.ts.map +1 -0
  107. package/dist/realtime/in-memory.js +28 -0
  108. package/dist/realtime/in-memory.js.map +1 -0
  109. package/dist/realtime/index.d.ts +3 -0
  110. package/dist/realtime/index.d.ts.map +1 -0
  111. package/dist/realtime/index.js +2 -0
  112. package/dist/realtime/index.js.map +1 -0
  113. package/dist/realtime/types.d.ts +50 -0
  114. package/dist/realtime/types.d.ts.map +1 -0
  115. package/dist/realtime/types.js +7 -0
  116. package/dist/realtime/types.js.map +1 -0
  117. package/dist/schema.d.ts +164 -0
  118. package/dist/schema.d.ts.map +1 -0
  119. package/dist/schema.js +10 -0
  120. package/dist/schema.js.map +1 -0
  121. package/dist/shapes/create-handler.d.ts +119 -0
  122. package/dist/shapes/create-handler.d.ts.map +1 -0
  123. package/dist/shapes/create-handler.js +327 -0
  124. package/dist/shapes/create-handler.js.map +1 -0
  125. package/dist/shapes/index.d.ts +4 -0
  126. package/dist/shapes/index.d.ts.map +1 -0
  127. package/dist/shapes/index.js +4 -0
  128. package/dist/shapes/index.js.map +1 -0
  129. package/dist/shapes/registry.d.ts +20 -0
  130. package/dist/shapes/registry.d.ts.map +1 -0
  131. package/dist/shapes/registry.js +88 -0
  132. package/dist/shapes/registry.js.map +1 -0
  133. package/dist/shapes/types.d.ts +204 -0
  134. package/dist/shapes/types.d.ts.map +1 -0
  135. package/dist/shapes/types.js +2 -0
  136. package/dist/shapes/types.js.map +1 -0
  137. package/dist/snapshot-chunks/adapters/s3.d.ts +63 -0
  138. package/dist/snapshot-chunks/adapters/s3.d.ts.map +1 -0
  139. package/dist/snapshot-chunks/adapters/s3.js +50 -0
  140. package/dist/snapshot-chunks/adapters/s3.js.map +1 -0
  141. package/dist/snapshot-chunks/db-metadata.d.ts +33 -0
  142. package/dist/snapshot-chunks/db-metadata.d.ts.map +1 -0
  143. package/dist/snapshot-chunks/db-metadata.js +169 -0
  144. package/dist/snapshot-chunks/db-metadata.js.map +1 -0
  145. package/dist/snapshot-chunks/index.d.ts +9 -0
  146. package/dist/snapshot-chunks/index.d.ts.map +1 -0
  147. package/dist/snapshot-chunks/index.js +9 -0
  148. package/dist/snapshot-chunks/index.js.map +1 -0
  149. package/dist/snapshot-chunks/types.d.ts +65 -0
  150. package/dist/snapshot-chunks/types.d.ts.map +1 -0
  151. package/dist/snapshot-chunks/types.js +8 -0
  152. package/dist/snapshot-chunks/types.js.map +1 -0
  153. package/dist/snapshot-chunks.d.ts +59 -0
  154. package/dist/snapshot-chunks.d.ts.map +1 -0
  155. package/dist/snapshot-chunks.js +202 -0
  156. package/dist/snapshot-chunks.js.map +1 -0
  157. package/dist/stats.d.ts +19 -0
  158. package/dist/stats.d.ts.map +1 -0
  159. package/dist/stats.js +57 -0
  160. package/dist/stats.js.map +1 -0
  161. package/dist/subscriptions/index.d.ts +2 -0
  162. package/dist/subscriptions/index.d.ts.map +1 -0
  163. package/dist/subscriptions/index.js +2 -0
  164. package/dist/subscriptions/index.js.map +1 -0
  165. package/dist/subscriptions/resolve.d.ts +35 -0
  166. package/dist/subscriptions/resolve.d.ts.map +1 -0
  167. package/dist/subscriptions/resolve.js +134 -0
  168. package/dist/subscriptions/resolve.js.map +1 -0
  169. package/package.json +80 -0
  170. package/src/blobs/adapters/database.ts +290 -0
  171. package/src/blobs/adapters/s3.ts +271 -0
  172. package/src/blobs/index.ts +9 -0
  173. package/src/blobs/manager.ts +600 -0
  174. package/src/blobs/migrate.ts +150 -0
  175. package/src/blobs/types.ts +70 -0
  176. package/src/clients.ts +21 -0
  177. package/src/compaction.ts +77 -0
  178. package/src/dialect/index.ts +5 -0
  179. package/src/dialect/types.ts +222 -0
  180. package/src/helpers/conflict.ts +64 -0
  181. package/src/helpers/emitted-change.ts +69 -0
  182. package/src/helpers/index.ts +10 -0
  183. package/src/helpers/paginate.ts +82 -0
  184. package/src/helpers/scope-strings.ts +101 -0
  185. package/src/index.ts +28 -0
  186. package/src/migrate.ts +20 -0
  187. package/src/proxy/handler.ts +152 -0
  188. package/src/proxy/index.ts +18 -0
  189. package/src/proxy/mutation-detector.ts +83 -0
  190. package/src/proxy/oplog.ts +144 -0
  191. package/src/proxy/registry.ts +56 -0
  192. package/src/proxy/types.ts +46 -0
  193. package/src/prune.ts +200 -0
  194. package/src/pull.ts +551 -0
  195. package/src/push.ts +457 -0
  196. package/src/realtime/in-memory.ts +33 -0
  197. package/src/realtime/index.ts +5 -0
  198. package/src/realtime/types.ts +55 -0
  199. package/src/schema.ts +172 -0
  200. package/src/shapes/create-handler.ts +590 -0
  201. package/src/shapes/index.ts +3 -0
  202. package/src/shapes/registry.ts +109 -0
  203. package/src/shapes/types.ts +267 -0
  204. package/src/snapshot-chunks/adapters/s3.ts +68 -0
  205. package/src/snapshot-chunks/db-metadata.ts +238 -0
  206. package/src/snapshot-chunks/index.ts +9 -0
  207. package/src/snapshot-chunks/types.ts +79 -0
  208. package/src/snapshot-chunks.ts +301 -0
  209. package/src/stats.ts +104 -0
  210. package/src/subscriptions/index.ts +1 -0
  211. package/src/subscriptions/resolve.ts +185 -0
package/src/push.ts ADDED
@@ -0,0 +1,457 @@
1
+ import type {
2
+ SyncChange,
3
+ SyncPushRequest,
4
+ SyncPushResponse,
5
+ } from '@syncular/core';
6
+ import type {
7
+ Insertable,
8
+ Kysely,
9
+ SelectQueryBuilder,
10
+ SqlBool,
11
+ Updateable,
12
+ } from 'kysely';
13
+ import { sql } from 'kysely';
14
+ import type { ServerSyncDialect } from './dialect/types';
15
+ import type { SyncCoreDb } from './schema';
16
+ import type { TableRegistry } from './shapes/registry';
17
+
18
+ // biome-ignore lint/complexity/noBannedTypes: Kysely uses `{}` as the initial "no selected columns yet" marker.
19
+ type EmptySelection = {};
20
+
21
+ export interface PushCommitResult {
22
+ response: SyncPushResponse;
23
+ /**
24
+ * Distinct tables affected by this commit.
25
+ * Empty for rejected commits and for commits that emit no changes.
26
+ */
27
+ affectedTables: string[];
28
+ /**
29
+ * Scope keys derived from emitted changes (e.g. "org:abc", "team:xyz").
30
+ * Computed in-transaction so callers don't need an extra DB query.
31
+ * Empty for rejected/cached commits.
32
+ */
33
+ scopeKeys: string[];
34
+ /**
35
+ * Changes emitted by this commit. Available for WS data delivery.
36
+ * Empty for rejected/cached commits.
37
+ */
38
+ emittedChanges: SyncChange[];
39
+ }
40
+
41
+ class RejectCommitError extends Error {
42
+ constructor(public readonly response: SyncPushResponse) {
43
+ super('REJECT_COMMIT');
44
+ this.name = 'RejectCommitError';
45
+ }
46
+ }
47
+
48
+ async function readCommitAffectedTables<DB extends SyncCoreDb>(
49
+ db: Kysely<DB>,
50
+ dialect: ServerSyncDialect,
51
+ commitSeq: number,
52
+ partitionId: string
53
+ ): Promise<string[]> {
54
+ try {
55
+ const commitsQ = db.selectFrom('sync_commits') as SelectQueryBuilder<
56
+ DB,
57
+ 'sync_commits',
58
+ EmptySelection
59
+ >;
60
+
61
+ const row = await commitsQ
62
+ .selectAll()
63
+ .where(sql<SqlBool>`commit_seq = ${commitSeq}`)
64
+ .where(sql<SqlBool>`partition_id = ${partitionId}`)
65
+ .executeTakeFirst();
66
+
67
+ const raw = row?.affected_tables;
68
+ return dialect.dbToArray(raw);
69
+ } catch {
70
+ // ignore and fall back to scanning changes (best-effort)
71
+ }
72
+
73
+ // Fallback: read from changes using dialect-specific implementation
74
+ return dialect.readAffectedTablesFromChanges(db, commitSeq, { partitionId });
75
+ }
76
+
77
+ function scopeKeysFromEmitted(
78
+ emitted: Array<{ scopes: Record<string, string> }>
79
+ ): string[] {
80
+ const keys = new Set<string>();
81
+ for (const c of emitted) {
82
+ for (const [key, value] of Object.entries(c.scopes)) {
83
+ if (!value) continue;
84
+ const prefix = key.replace(/_id$/, '');
85
+ keys.add(`${prefix}:${value}`);
86
+ }
87
+ }
88
+ return Array.from(keys);
89
+ }
90
+
91
+ export async function pushCommit<DB extends SyncCoreDb>(args: {
92
+ db: Kysely<DB>;
93
+ dialect: ServerSyncDialect;
94
+ shapes: TableRegistry<DB>;
95
+ actorId: string;
96
+ partitionId?: string;
97
+ request: SyncPushRequest;
98
+ }): Promise<PushCommitResult> {
99
+ const { request, dialect } = args;
100
+ const db = args.db;
101
+ const partitionId = args.partitionId ?? 'default';
102
+
103
+ if (!request.clientId || !request.clientCommitId) {
104
+ return {
105
+ response: {
106
+ ok: true,
107
+ status: 'rejected',
108
+ results: [
109
+ {
110
+ opIndex: 0,
111
+ status: 'error',
112
+ error: 'INVALID_REQUEST',
113
+ code: 'INVALID_REQUEST',
114
+ retriable: false,
115
+ },
116
+ ],
117
+ },
118
+ affectedTables: [],
119
+ scopeKeys: [],
120
+ emittedChanges: [],
121
+ };
122
+ }
123
+
124
+ const ops = request.operations ?? [];
125
+ if (!Array.isArray(ops) || ops.length === 0) {
126
+ return {
127
+ response: {
128
+ ok: true,
129
+ status: 'rejected',
130
+ results: [
131
+ {
132
+ opIndex: 0,
133
+ status: 'error',
134
+ error: 'EMPTY_COMMIT',
135
+ code: 'EMPTY_COMMIT',
136
+ retriable: false,
137
+ },
138
+ ],
139
+ },
140
+ affectedTables: [],
141
+ scopeKeys: [],
142
+ emittedChanges: [],
143
+ };
144
+ }
145
+
146
+ return dialect.executeInTransaction(db, async (trx) => {
147
+ type SyncTrx = Pick<
148
+ Kysely<SyncCoreDb>,
149
+ 'selectFrom' | 'insertInto' | 'updateTable' | 'deleteFrom'
150
+ >;
151
+
152
+ const syncTrx = trx as SyncTrx;
153
+
154
+ // Clean up any stale commit row with null result_json.
155
+ // This can happen when a previous push inserted the commit row but crashed
156
+ // before writing the result (e.g., on D1 without transaction support).
157
+ await syncTrx
158
+ .deleteFrom('sync_commits')
159
+ .where('partition_id', '=', partitionId)
160
+ .where('client_id', '=', request.clientId)
161
+ .where('client_commit_id', '=', request.clientCommitId)
162
+ .where('result_json', 'is', null)
163
+ .execute();
164
+
165
+ // Insert commit row (idempotency key)
166
+ const commitRow: Insertable<SyncCoreDb['sync_commits']> = {
167
+ partition_id: partitionId,
168
+ actor_id: args.actorId,
169
+ client_id: request.clientId,
170
+ client_commit_id: request.clientCommitId,
171
+ meta: null,
172
+ result_json: null,
173
+ };
174
+
175
+ const insertResult = await syncTrx
176
+ .insertInto('sync_commits')
177
+ .values(commitRow)
178
+ .onConflict((oc) =>
179
+ oc.columns(['partition_id', 'client_id', 'client_commit_id']).doNothing()
180
+ )
181
+ .executeTakeFirstOrThrow();
182
+
183
+ const insertedRows = Number(insertResult.numInsertedOrUpdatedRows ?? 0);
184
+ if (insertedRows === 0) {
185
+ // Existing commit: return cached response (applied or rejected)
186
+ // Use forUpdate() for row locking on databases that support it
187
+ let query = (
188
+ syncTrx.selectFrom('sync_commits') as SelectQueryBuilder<
189
+ SyncCoreDb,
190
+ 'sync_commits',
191
+ EmptySelection
192
+ >
193
+ )
194
+ .selectAll()
195
+ .where('partition_id', '=', partitionId)
196
+ .where('client_id', '=', request.clientId)
197
+ .where('client_commit_id', '=', request.clientCommitId);
198
+
199
+ if (dialect.supportsForUpdate) {
200
+ query = query.forUpdate();
201
+ }
202
+
203
+ const existing = await query.executeTakeFirstOrThrow();
204
+
205
+ const cached = existing.result_json as SyncPushResponse | null;
206
+ if (!cached || cached.ok !== true) {
207
+ return {
208
+ response: {
209
+ ok: true,
210
+ status: 'rejected',
211
+ results: [
212
+ {
213
+ opIndex: 0,
214
+ status: 'error',
215
+ error: 'IDEMPOTENCY_CACHE_MISS',
216
+ code: 'INTERNAL',
217
+ retriable: true,
218
+ },
219
+ ],
220
+ },
221
+ affectedTables: [],
222
+ scopeKeys: [],
223
+ emittedChanges: [],
224
+ };
225
+ }
226
+
227
+ const base: SyncPushResponse = {
228
+ ...cached,
229
+ commitSeq: Number(existing.commit_seq),
230
+ };
231
+
232
+ if (cached.status === 'applied') {
233
+ const tablesFromDb = dialect.dbToArray(existing.affected_tables);
234
+ return {
235
+ response: { ...base, status: 'cached' },
236
+ affectedTables:
237
+ tablesFromDb.length > 0
238
+ ? tablesFromDb
239
+ : await readCommitAffectedTables(
240
+ trx,
241
+ dialect,
242
+ Number(existing.commit_seq),
243
+ partitionId
244
+ ),
245
+ scopeKeys: [],
246
+ emittedChanges: [],
247
+ };
248
+ }
249
+
250
+ return {
251
+ response: base,
252
+ affectedTables: [],
253
+ scopeKeys: [],
254
+ emittedChanges: [],
255
+ };
256
+ }
257
+
258
+ const insertedCommit = await (
259
+ syncTrx.selectFrom('sync_commits') as SelectQueryBuilder<
260
+ SyncCoreDb,
261
+ 'sync_commits',
262
+ EmptySelection
263
+ >
264
+ )
265
+ .selectAll()
266
+ .where('partition_id', '=', partitionId)
267
+ .where('client_id', '=', request.clientId)
268
+ .where('client_commit_id', '=', request.clientCommitId)
269
+ .executeTakeFirstOrThrow();
270
+
271
+ const commitSeq = Number(insertedCommit.commit_seq);
272
+ const commitId = `${request.clientId}:${request.clientCommitId}`;
273
+
274
+ const savepointName = 'sync_apply';
275
+ const useSavepoints = dialect.supportsSavepoints;
276
+ let savepointCreated = false;
277
+
278
+ try {
279
+ // Apply the commit under a savepoint so we can roll back app writes on conflict
280
+ // while still persisting the commit-level cached response.
281
+ if (useSavepoints) {
282
+ await sql.raw(`SAVEPOINT ${savepointName}`).execute(trx);
283
+ savepointCreated = true;
284
+ }
285
+
286
+ const allEmitted = [];
287
+ const results = [];
288
+ const affectedTablesSet = new Set<string>();
289
+
290
+ for (let i = 0; i < ops.length; i++) {
291
+ const op = ops[i]!;
292
+ const handler = args.shapes.getOrThrow(op.table);
293
+ const applied = await handler.applyOperation(
294
+ {
295
+ db: trx,
296
+ trx,
297
+ actorId: args.actorId,
298
+ clientId: request.clientId,
299
+ commitId,
300
+ schemaVersion: request.schemaVersion,
301
+ },
302
+ op,
303
+ i
304
+ );
305
+
306
+ if (applied.result.status !== 'applied') {
307
+ results.push(applied.result);
308
+ throw new RejectCommitError({
309
+ ok: true,
310
+ status: 'rejected',
311
+ commitSeq,
312
+ results,
313
+ });
314
+ }
315
+
316
+ // Framework-level enforcement: emitted changes must have scopes
317
+ for (const c of applied.emittedChanges ?? []) {
318
+ const scopes = c?.scopes;
319
+ if (!scopes || typeof scopes !== 'object') {
320
+ results.push({
321
+ opIndex: i,
322
+ status: 'error' as const,
323
+ error: 'MISSING_SCOPES',
324
+ code: 'INVALID_SCOPE',
325
+ retriable: false,
326
+ });
327
+ throw new RejectCommitError({
328
+ ok: true,
329
+ status: 'rejected',
330
+ commitSeq,
331
+ results,
332
+ });
333
+ }
334
+ }
335
+
336
+ results.push(applied.result);
337
+ allEmitted.push(...applied.emittedChanges);
338
+ for (const c of applied.emittedChanges) {
339
+ affectedTablesSet.add(c.table);
340
+ }
341
+ }
342
+
343
+ if (allEmitted.length > 0) {
344
+ const changeRows: Array<Insertable<SyncCoreDb['sync_changes']>> =
345
+ allEmitted.map((c) => ({
346
+ partition_id: partitionId,
347
+ commit_seq: commitSeq,
348
+ table: c.table,
349
+ row_id: c.row_id,
350
+ op: c.op,
351
+ row_json: c.row_json,
352
+ row_version: c.row_version,
353
+ scopes: dialect.scopesToDb(c.scopes),
354
+ }));
355
+
356
+ await syncTrx.insertInto('sync_changes').values(changeRows).execute();
357
+ }
358
+
359
+ const appliedResponse: SyncPushResponse = {
360
+ ok: true,
361
+ status: 'applied',
362
+ commitSeq,
363
+ results,
364
+ };
365
+
366
+ const affectedTables = Array.from(affectedTablesSet).sort();
367
+
368
+ const appliedCommitUpdate: Updateable<SyncCoreDb['sync_commits']> = {
369
+ result_json: appliedResponse,
370
+ change_count: allEmitted.length,
371
+ affected_tables: affectedTables,
372
+ };
373
+
374
+ await syncTrx
375
+ .updateTable('sync_commits')
376
+ .set(appliedCommitUpdate)
377
+ .where('commit_seq', '=', commitSeq)
378
+ .execute();
379
+
380
+ // Insert table commits for subscription filtering
381
+ if (affectedTables.length > 0) {
382
+ const tableCommits: Array<
383
+ Insertable<SyncCoreDb['sync_table_commits']>
384
+ > = affectedTables.map((table) => ({
385
+ partition_id: partitionId,
386
+ table,
387
+ commit_seq: commitSeq,
388
+ }));
389
+
390
+ await syncTrx
391
+ .insertInto('sync_table_commits')
392
+ .values(tableCommits)
393
+ .onConflict((oc) =>
394
+ oc.columns(['partition_id', 'table', 'commit_seq']).doNothing()
395
+ )
396
+ .execute();
397
+ }
398
+
399
+ if (useSavepoints) {
400
+ await sql.raw(`RELEASE SAVEPOINT ${savepointName}`).execute(trx);
401
+ }
402
+
403
+ return {
404
+ response: appliedResponse,
405
+ affectedTables,
406
+ scopeKeys: scopeKeysFromEmitted(allEmitted),
407
+ emittedChanges: allEmitted.map((c) => ({
408
+ table: c.table,
409
+ row_id: c.row_id,
410
+ op: c.op,
411
+ row_json: c.row_json,
412
+ row_version: c.row_version,
413
+ scopes: c.scopes,
414
+ })),
415
+ };
416
+ } catch (err) {
417
+ // Roll back app writes but keep the commit row.
418
+ if (savepointCreated) {
419
+ try {
420
+ await sql.raw(`ROLLBACK TO SAVEPOINT ${savepointName}`).execute(trx);
421
+ await sql.raw(`RELEASE SAVEPOINT ${savepointName}`).execute(trx);
422
+ } catch (savepointErr) {
423
+ // If savepoint rollback fails, the transaction may be in an
424
+ // inconsistent state. Log and rethrow to fail the entire commit
425
+ // rather than risk data corruption.
426
+ console.error(
427
+ '[pushCommit] Savepoint rollback failed:',
428
+ savepointErr
429
+ );
430
+ throw savepointErr;
431
+ }
432
+ }
433
+
434
+ if (!(err instanceof RejectCommitError)) throw err;
435
+
436
+ const rejectedCommitUpdate: Updateable<SyncCoreDb['sync_commits']> = {
437
+ result_json: err.response,
438
+ change_count: 0,
439
+ affected_tables: [],
440
+ };
441
+
442
+ // Persist the rejected response for commit-level idempotency.
443
+ await syncTrx
444
+ .updateTable('sync_commits')
445
+ .set(rejectedCommitUpdate)
446
+ .where('commit_seq', '=', commitSeq)
447
+ .execute();
448
+
449
+ return {
450
+ response: err.response,
451
+ affectedTables: [],
452
+ scopeKeys: [],
453
+ emittedChanges: [],
454
+ };
455
+ }
456
+ });
457
+ }
@@ -0,0 +1,33 @@
1
+ import type { SyncRealtimeBroadcaster, SyncRealtimeEvent } from './types';
2
+
3
+ /**
4
+ * In-memory broadcaster for tests and single-process setups.
5
+ *
6
+ * This simulates multi-instance fanout when shared across "instances" in a test.
7
+ */
8
+ export class InMemorySyncRealtimeBroadcaster
9
+ implements SyncRealtimeBroadcaster
10
+ {
11
+ private handlers = new Set<(event: SyncRealtimeEvent) => void>();
12
+
13
+ subscribe(handler: (event: SyncRealtimeEvent) => void): () => void {
14
+ this.handlers.add(handler);
15
+ return () => {
16
+ this.handlers.delete(handler);
17
+ };
18
+ }
19
+
20
+ async publish(event: SyncRealtimeEvent): Promise<void> {
21
+ for (const handler of this.handlers) {
22
+ try {
23
+ handler(event);
24
+ } catch {
25
+ // ignore individual handler errors; realtime is best-effort
26
+ }
27
+ }
28
+ }
29
+
30
+ async close(): Promise<void> {
31
+ this.handlers.clear();
32
+ }
33
+ }
@@ -0,0 +1,5 @@
1
+ export { InMemorySyncRealtimeBroadcaster } from './in-memory';
2
+ export type {
3
+ SyncRealtimeBroadcaster,
4
+ SyncRealtimeEvent,
5
+ } from './types';
@@ -0,0 +1,55 @@
1
+ /**
2
+ * @syncular/server - Realtime broadcaster types
3
+ *
4
+ * Realtime is a best-effort "wake up" mechanism. Correctness always comes from pull + cursors.
5
+ */
6
+
7
+ export interface SyncRealtimeCommitEvent {
8
+ type: 'commit';
9
+ commitSeq: number;
10
+ /** Logical partition key (tenant / demo / workspace). */
11
+ partitionId?: string;
12
+ /**
13
+ * Optional scopes affected by the commit.
14
+ * Broadcasters may omit this to keep payloads small (listeners can look up in DB).
15
+ */
16
+ scopeKeys?: string[];
17
+ /** Optional instance id to suppress echo on the originating instance. */
18
+ sourceInstanceId?: string;
19
+ }
20
+
21
+ /**
22
+ * Presence event for tracking which clients are connected to which scopes.
23
+ * Used for collaborative features like "who's online" indicators.
24
+ */
25
+ export interface SyncRealtimePresenceEvent {
26
+ type: 'presence';
27
+ /** The action that occurred */
28
+ action: 'join' | 'leave' | 'update';
29
+ /** The scope key this presence event relates to */
30
+ scopeKey: string;
31
+ /** Client/device identifier */
32
+ clientId: string;
33
+ /** Actor/user identifier */
34
+ actorId: string;
35
+ /** Optional metadata (e.g., entity being viewed/edited) */
36
+ metadata?: Record<string, unknown>;
37
+ /** Optional instance id to suppress echo on the originating instance. */
38
+ sourceInstanceId?: string;
39
+ }
40
+
41
+ export type SyncRealtimeEvent =
42
+ | SyncRealtimeCommitEvent
43
+ | SyncRealtimePresenceEvent;
44
+
45
+ export interface SyncRealtimeBroadcaster {
46
+ /** Publish an event to other app instances. */
47
+ publish(event: SyncRealtimeEvent): Promise<void>;
48
+ /**
49
+ * Subscribe to events from other app instances.
50
+ * Returns an unsubscribe function.
51
+ */
52
+ subscribe(handler: (event: SyncRealtimeEvent) => void): () => void;
53
+ /** Close underlying resources (best-effort). */
54
+ close(): Promise<void>;
55
+ }