@syncular/server 0.0.1-100

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 (225) 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 +202 -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/base.d.ts +83 -0
  34. package/dist/dialect/base.d.ts.map +1 -0
  35. package/dist/dialect/base.js +144 -0
  36. package/dist/dialect/base.js.map +1 -0
  37. package/dist/dialect/helpers.d.ts +10 -0
  38. package/dist/dialect/helpers.d.ts.map +1 -0
  39. package/dist/dialect/helpers.js +59 -0
  40. package/dist/dialect/helpers.js.map +1 -0
  41. package/dist/dialect/index.d.ts +7 -0
  42. package/dist/dialect/index.d.ts.map +1 -0
  43. package/dist/dialect/index.js +7 -0
  44. package/dist/dialect/index.js.map +1 -0
  45. package/dist/dialect/types.d.ts +149 -0
  46. package/dist/dialect/types.d.ts.map +1 -0
  47. package/dist/dialect/types.js +8 -0
  48. package/dist/dialect/types.js.map +1 -0
  49. package/dist/helpers/conflict.d.ts +52 -0
  50. package/dist/helpers/conflict.d.ts.map +1 -0
  51. package/dist/helpers/conflict.js +49 -0
  52. package/dist/helpers/conflict.js.map +1 -0
  53. package/dist/helpers/emitted-change.d.ts +56 -0
  54. package/dist/helpers/emitted-change.d.ts.map +1 -0
  55. package/dist/helpers/emitted-change.js +46 -0
  56. package/dist/helpers/emitted-change.js.map +1 -0
  57. package/dist/helpers/index.d.ts +10 -0
  58. package/dist/helpers/index.d.ts.map +1 -0
  59. package/dist/helpers/index.js +10 -0
  60. package/dist/helpers/index.js.map +1 -0
  61. package/dist/helpers/paginate.d.ts +49 -0
  62. package/dist/helpers/paginate.d.ts.map +1 -0
  63. package/dist/helpers/paginate.js +54 -0
  64. package/dist/helpers/paginate.js.map +1 -0
  65. package/dist/helpers/scope-strings.d.ts +74 -0
  66. package/dist/helpers/scope-strings.d.ts.map +1 -0
  67. package/dist/helpers/scope-strings.js +82 -0
  68. package/dist/helpers/scope-strings.js.map +1 -0
  69. package/dist/index.d.ts +28 -0
  70. package/dist/index.d.ts.map +1 -0
  71. package/dist/index.js +27 -0
  72. package/dist/index.js.map +1 -0
  73. package/dist/migrate.d.ts +14 -0
  74. package/dist/migrate.d.ts.map +1 -0
  75. package/dist/migrate.js +13 -0
  76. package/dist/migrate.js.map +1 -0
  77. package/dist/proxy/handler.d.ts +42 -0
  78. package/dist/proxy/handler.d.ts.map +1 -0
  79. package/dist/proxy/handler.js +102 -0
  80. package/dist/proxy/handler.js.map +1 -0
  81. package/dist/proxy/index.d.ts +9 -0
  82. package/dist/proxy/index.d.ts.map +1 -0
  83. package/dist/proxy/index.js +14 -0
  84. package/dist/proxy/index.js.map +1 -0
  85. package/dist/proxy/mutation-detector.d.ts +35 -0
  86. package/dist/proxy/mutation-detector.d.ts.map +1 -0
  87. package/dist/proxy/mutation-detector.js +246 -0
  88. package/dist/proxy/mutation-detector.js.map +1 -0
  89. package/dist/proxy/oplog.d.ts +30 -0
  90. package/dist/proxy/oplog.d.ts.map +1 -0
  91. package/dist/proxy/oplog.js +110 -0
  92. package/dist/proxy/oplog.js.map +1 -0
  93. package/dist/proxy/registry.d.ts +35 -0
  94. package/dist/proxy/registry.d.ts.map +1 -0
  95. package/dist/proxy/registry.js +49 -0
  96. package/dist/proxy/registry.js.map +1 -0
  97. package/dist/proxy/types.d.ts +44 -0
  98. package/dist/proxy/types.d.ts.map +1 -0
  99. package/dist/proxy/types.js +7 -0
  100. package/dist/proxy/types.js.map +1 -0
  101. package/dist/prune.d.ts +37 -0
  102. package/dist/prune.d.ts.map +1 -0
  103. package/dist/prune.js +112 -0
  104. package/dist/prune.js.map +1 -0
  105. package/dist/pull.d.ts +31 -0
  106. package/dist/pull.d.ts.map +1 -0
  107. package/dist/pull.js +608 -0
  108. package/dist/pull.js.map +1 -0
  109. package/dist/push.d.ts +33 -0
  110. package/dist/push.d.ts.map +1 -0
  111. package/dist/push.js +412 -0
  112. package/dist/push.js.map +1 -0
  113. package/dist/realtime/in-memory.d.ts +13 -0
  114. package/dist/realtime/in-memory.d.ts.map +1 -0
  115. package/dist/realtime/in-memory.js +28 -0
  116. package/dist/realtime/in-memory.js.map +1 -0
  117. package/dist/realtime/index.d.ts +3 -0
  118. package/dist/realtime/index.d.ts.map +1 -0
  119. package/dist/realtime/index.js +2 -0
  120. package/dist/realtime/index.js.map +1 -0
  121. package/dist/realtime/types.d.ts +50 -0
  122. package/dist/realtime/types.d.ts.map +1 -0
  123. package/dist/realtime/types.js +7 -0
  124. package/dist/realtime/types.js.map +1 -0
  125. package/dist/schema.d.ts +164 -0
  126. package/dist/schema.d.ts.map +1 -0
  127. package/dist/schema.js +10 -0
  128. package/dist/schema.js.map +1 -0
  129. package/dist/shapes/create-handler.d.ts +119 -0
  130. package/dist/shapes/create-handler.d.ts.map +1 -0
  131. package/dist/shapes/create-handler.js +327 -0
  132. package/dist/shapes/create-handler.js.map +1 -0
  133. package/dist/shapes/index.d.ts +4 -0
  134. package/dist/shapes/index.d.ts.map +1 -0
  135. package/dist/shapes/index.js +4 -0
  136. package/dist/shapes/index.js.map +1 -0
  137. package/dist/shapes/registry.d.ts +20 -0
  138. package/dist/shapes/registry.d.ts.map +1 -0
  139. package/dist/shapes/registry.js +88 -0
  140. package/dist/shapes/registry.js.map +1 -0
  141. package/dist/shapes/types.d.ts +204 -0
  142. package/dist/shapes/types.d.ts.map +1 -0
  143. package/dist/shapes/types.js +2 -0
  144. package/dist/shapes/types.js.map +1 -0
  145. package/dist/snapshot-chunks/adapters/s3.d.ts +74 -0
  146. package/dist/snapshot-chunks/adapters/s3.d.ts.map +1 -0
  147. package/dist/snapshot-chunks/adapters/s3.js +50 -0
  148. package/dist/snapshot-chunks/adapters/s3.js.map +1 -0
  149. package/dist/snapshot-chunks/db-metadata.d.ts +38 -0
  150. package/dist/snapshot-chunks/db-metadata.d.ts.map +1 -0
  151. package/dist/snapshot-chunks/db-metadata.js +324 -0
  152. package/dist/snapshot-chunks/db-metadata.js.map +1 -0
  153. package/dist/snapshot-chunks/index.d.ts +9 -0
  154. package/dist/snapshot-chunks/index.d.ts.map +1 -0
  155. package/dist/snapshot-chunks/index.js +9 -0
  156. package/dist/snapshot-chunks/index.js.map +1 -0
  157. package/dist/snapshot-chunks/types.d.ts +78 -0
  158. package/dist/snapshot-chunks/types.d.ts.map +1 -0
  159. package/dist/snapshot-chunks/types.js +8 -0
  160. package/dist/snapshot-chunks/types.js.map +1 -0
  161. package/dist/snapshot-chunks.d.ts +60 -0
  162. package/dist/snapshot-chunks.d.ts.map +1 -0
  163. package/dist/snapshot-chunks.js +223 -0
  164. package/dist/snapshot-chunks.js.map +1 -0
  165. package/dist/stats.d.ts +19 -0
  166. package/dist/stats.d.ts.map +1 -0
  167. package/dist/stats.js +57 -0
  168. package/dist/stats.js.map +1 -0
  169. package/dist/subscriptions/index.d.ts +2 -0
  170. package/dist/subscriptions/index.d.ts.map +1 -0
  171. package/dist/subscriptions/index.js +2 -0
  172. package/dist/subscriptions/index.js.map +1 -0
  173. package/dist/subscriptions/resolve.d.ts +35 -0
  174. package/dist/subscriptions/resolve.d.ts.map +1 -0
  175. package/dist/subscriptions/resolve.js +134 -0
  176. package/dist/subscriptions/resolve.js.map +1 -0
  177. package/package.json +80 -0
  178. package/src/blobs/adapters/database.test.ts +67 -0
  179. package/src/blobs/adapters/database.ts +315 -0
  180. package/src/blobs/adapters/s3.ts +271 -0
  181. package/src/blobs/index.ts +9 -0
  182. package/src/blobs/manager.ts +600 -0
  183. package/src/blobs/migrate.ts +150 -0
  184. package/src/blobs/types.ts +70 -0
  185. package/src/clients.ts +21 -0
  186. package/src/compaction.ts +77 -0
  187. package/src/dialect/base.ts +292 -0
  188. package/src/dialect/helpers.ts +61 -0
  189. package/src/dialect/index.ts +7 -0
  190. package/src/dialect/types.ts +197 -0
  191. package/src/helpers/conflict.ts +64 -0
  192. package/src/helpers/emitted-change.ts +69 -0
  193. package/src/helpers/index.ts +10 -0
  194. package/src/helpers/paginate.ts +82 -0
  195. package/src/helpers/scope-strings.ts +101 -0
  196. package/src/index.ts +28 -0
  197. package/src/migrate.ts +20 -0
  198. package/src/proxy/handler.test.ts +120 -0
  199. package/src/proxy/handler.ts +159 -0
  200. package/src/proxy/index.ts +18 -0
  201. package/src/proxy/mutation-detector.test.ts +71 -0
  202. package/src/proxy/mutation-detector.ts +281 -0
  203. package/src/proxy/oplog.ts +146 -0
  204. package/src/proxy/registry.ts +56 -0
  205. package/src/proxy/types.ts +46 -0
  206. package/src/prune.ts +200 -0
  207. package/src/pull.ts +858 -0
  208. package/src/push.ts +583 -0
  209. package/src/realtime/in-memory.ts +33 -0
  210. package/src/realtime/index.ts +5 -0
  211. package/src/realtime/types.ts +55 -0
  212. package/src/schema.ts +172 -0
  213. package/src/shapes/create-handler.ts +590 -0
  214. package/src/shapes/index.ts +3 -0
  215. package/src/shapes/registry.ts +109 -0
  216. package/src/shapes/types.ts +267 -0
  217. package/src/snapshot-chunks/adapters/s3.ts +68 -0
  218. package/src/snapshot-chunks/db-metadata.test.ts +100 -0
  219. package/src/snapshot-chunks/db-metadata.ts +466 -0
  220. package/src/snapshot-chunks/index.ts +9 -0
  221. package/src/snapshot-chunks/types.ts +103 -0
  222. package/src/snapshot-chunks.ts +329 -0
  223. package/src/stats.ts +104 -0
  224. package/src/subscriptions/index.ts +1 -0
  225. package/src/subscriptions/resolve.ts +185 -0
package/src/push.ts ADDED
@@ -0,0 +1,583 @@
1
+ import {
2
+ captureSyncException,
3
+ countSyncMetric,
4
+ distributionSyncMetric,
5
+ type SyncChange,
6
+ type SyncPushRequest,
7
+ type SyncPushResponse,
8
+ startSyncSpan,
9
+ } from '@syncular/core';
10
+ import type {
11
+ Insertable,
12
+ Kysely,
13
+ SelectQueryBuilder,
14
+ SqlBool,
15
+ Updateable,
16
+ } from 'kysely';
17
+ import { sql } from 'kysely';
18
+ import type { ServerSyncDialect } from './dialect/types';
19
+ import type { SyncCoreDb } from './schema';
20
+ import type { TableRegistry } from './shapes/registry';
21
+
22
+ // biome-ignore lint/complexity/noBannedTypes: Kysely uses `{}` as the initial "no selected columns yet" marker.
23
+ type EmptySelection = {};
24
+
25
+ export interface PushCommitResult {
26
+ response: SyncPushResponse;
27
+ /**
28
+ * Distinct tables affected by this commit.
29
+ * Empty for rejected commits and for commits that emit no changes.
30
+ */
31
+ affectedTables: string[];
32
+ /**
33
+ * Scope keys derived from emitted changes (e.g. "org:abc", "team:xyz").
34
+ * Computed in-transaction so callers don't need an extra DB query.
35
+ * Empty for rejected/cached commits.
36
+ */
37
+ scopeKeys: string[];
38
+ /**
39
+ * Changes emitted by this commit. Available for WS data delivery.
40
+ * Empty for rejected/cached commits.
41
+ */
42
+ emittedChanges: SyncChange[];
43
+ }
44
+
45
+ class RejectCommitError extends Error {
46
+ constructor(public readonly response: SyncPushResponse) {
47
+ super('REJECT_COMMIT');
48
+ this.name = 'RejectCommitError';
49
+ }
50
+ }
51
+
52
+ async function readCommitAffectedTables<DB extends SyncCoreDb>(
53
+ db: Kysely<DB>,
54
+ dialect: ServerSyncDialect,
55
+ commitSeq: number,
56
+ partitionId: string
57
+ ): Promise<string[]> {
58
+ try {
59
+ const commitsQ = db.selectFrom('sync_commits') as SelectQueryBuilder<
60
+ DB,
61
+ 'sync_commits',
62
+ EmptySelection
63
+ >;
64
+
65
+ const row = await commitsQ
66
+ .selectAll()
67
+ .where(sql<SqlBool>`commit_seq = ${commitSeq}`)
68
+ .where(sql<SqlBool>`partition_id = ${partitionId}`)
69
+ .executeTakeFirst();
70
+
71
+ const raw = row?.affected_tables;
72
+ return dialect.dbToArray(raw);
73
+ } catch {
74
+ // ignore and fall back to scanning changes (best-effort)
75
+ }
76
+
77
+ // Fallback: read from changes using dialect-specific implementation
78
+ return dialect.readAffectedTablesFromChanges(db, commitSeq, { partitionId });
79
+ }
80
+
81
+ function scopeKeysFromEmitted(
82
+ emitted: Array<{ scopes: Record<string, string> }>
83
+ ): string[] {
84
+ const keys = new Set<string>();
85
+ for (const c of emitted) {
86
+ for (const [key, value] of Object.entries(c.scopes)) {
87
+ if (!value) continue;
88
+ const prefix = key.replace(/_id$/, '');
89
+ keys.add(`${prefix}:${value}`);
90
+ }
91
+ }
92
+ return Array.from(keys);
93
+ }
94
+
95
+ function recordPushMetrics(args: {
96
+ status: string;
97
+ durationMs: number;
98
+ operationCount: number;
99
+ emittedChangeCount: number;
100
+ affectedTableCount: number;
101
+ }): void {
102
+ const {
103
+ status,
104
+ durationMs,
105
+ operationCount,
106
+ emittedChangeCount,
107
+ affectedTableCount,
108
+ } = args;
109
+
110
+ countSyncMetric('sync.server.push.requests', 1, {
111
+ attributes: { status },
112
+ });
113
+ countSyncMetric('sync.server.push.operations', operationCount, {
114
+ attributes: { status },
115
+ });
116
+ distributionSyncMetric('sync.server.push.duration_ms', durationMs, {
117
+ unit: 'millisecond',
118
+ attributes: { status },
119
+ });
120
+ distributionSyncMetric(
121
+ 'sync.server.push.emitted_changes',
122
+ emittedChangeCount,
123
+ {
124
+ attributes: { status },
125
+ }
126
+ );
127
+ distributionSyncMetric(
128
+ 'sync.server.push.affected_tables',
129
+ affectedTableCount,
130
+ {
131
+ attributes: { status },
132
+ }
133
+ );
134
+ }
135
+
136
+ export async function pushCommit<DB extends SyncCoreDb>(args: {
137
+ db: Kysely<DB>;
138
+ dialect: ServerSyncDialect;
139
+ shapes: TableRegistry<DB>;
140
+ actorId: string;
141
+ partitionId?: string;
142
+ request: SyncPushRequest;
143
+ }): Promise<PushCommitResult> {
144
+ const { request, dialect } = args;
145
+ const db = args.db;
146
+ const partitionId = args.partitionId ?? 'default';
147
+ const requestedOps = Array.isArray(request.operations)
148
+ ? request.operations
149
+ : [];
150
+ const operationCount = requestedOps.length;
151
+ const startedAtMs = Date.now();
152
+
153
+ return startSyncSpan(
154
+ {
155
+ name: 'sync.server.push',
156
+ op: 'sync.push',
157
+ attributes: {
158
+ operation_count: operationCount,
159
+ },
160
+ },
161
+ async (span) => {
162
+ const finalizeResult = (result: PushCommitResult): PushCommitResult => {
163
+ const durationMs = Math.max(0, Date.now() - startedAtMs);
164
+ const status = result.response.status;
165
+
166
+ span.setAttribute('status', status);
167
+ span.setAttribute('duration_ms', durationMs);
168
+ span.setAttribute('emitted_change_count', result.emittedChanges.length);
169
+ span.setAttribute('affected_table_count', result.affectedTables.length);
170
+ span.setStatus('ok');
171
+
172
+ recordPushMetrics({
173
+ status,
174
+ durationMs,
175
+ operationCount,
176
+ emittedChangeCount: result.emittedChanges.length,
177
+ affectedTableCount: result.affectedTables.length,
178
+ });
179
+
180
+ return result;
181
+ };
182
+
183
+ try {
184
+ if (!request.clientId || !request.clientCommitId) {
185
+ return finalizeResult({
186
+ response: {
187
+ ok: true,
188
+ status: 'rejected',
189
+ results: [
190
+ {
191
+ opIndex: 0,
192
+ status: 'error',
193
+ error: 'INVALID_REQUEST',
194
+ code: 'INVALID_REQUEST',
195
+ retriable: false,
196
+ },
197
+ ],
198
+ },
199
+ affectedTables: [],
200
+ scopeKeys: [],
201
+ emittedChanges: [],
202
+ });
203
+ }
204
+
205
+ const ops = request.operations ?? [];
206
+ if (!Array.isArray(ops) || ops.length === 0) {
207
+ return finalizeResult({
208
+ response: {
209
+ ok: true,
210
+ status: 'rejected',
211
+ results: [
212
+ {
213
+ opIndex: 0,
214
+ status: 'error',
215
+ error: 'EMPTY_COMMIT',
216
+ code: 'EMPTY_COMMIT',
217
+ retriable: false,
218
+ },
219
+ ],
220
+ },
221
+ affectedTables: [],
222
+ scopeKeys: [],
223
+ emittedChanges: [],
224
+ });
225
+ }
226
+
227
+ return finalizeResult(
228
+ await dialect.executeInTransaction(db, async (trx) => {
229
+ type SyncTrx = Pick<
230
+ Kysely<SyncCoreDb>,
231
+ 'selectFrom' | 'insertInto' | 'updateTable' | 'deleteFrom'
232
+ >;
233
+
234
+ const syncTrx = trx as SyncTrx;
235
+
236
+ // Clean up any stale commit row with null result_json.
237
+ // This can happen when a previous push inserted the commit row but crashed
238
+ // before writing the result (e.g., on D1 without transaction support).
239
+ await syncTrx
240
+ .deleteFrom('sync_commits')
241
+ .where('partition_id', '=', partitionId)
242
+ .where('client_id', '=', request.clientId)
243
+ .where('client_commit_id', '=', request.clientCommitId)
244
+ .where('result_json', 'is', null)
245
+ .execute();
246
+
247
+ // Insert commit row (idempotency key)
248
+ const commitRow: Insertable<SyncCoreDb['sync_commits']> = {
249
+ partition_id: partitionId,
250
+ actor_id: args.actorId,
251
+ client_id: request.clientId,
252
+ client_commit_id: request.clientCommitId,
253
+ meta: null,
254
+ result_json: null,
255
+ };
256
+
257
+ const insertResult = await syncTrx
258
+ .insertInto('sync_commits')
259
+ .values(commitRow)
260
+ .onConflict((oc) =>
261
+ oc
262
+ .columns(['partition_id', 'client_id', 'client_commit_id'])
263
+ .doNothing()
264
+ )
265
+ .executeTakeFirstOrThrow();
266
+
267
+ const insertedRows = Number(
268
+ insertResult.numInsertedOrUpdatedRows ?? 0
269
+ );
270
+ if (insertedRows === 0) {
271
+ // Existing commit: return cached response (applied or rejected)
272
+ // Use forUpdate() for row locking on databases that support it
273
+ let query = (
274
+ syncTrx.selectFrom('sync_commits') as SelectQueryBuilder<
275
+ SyncCoreDb,
276
+ 'sync_commits',
277
+ EmptySelection
278
+ >
279
+ )
280
+ .selectAll()
281
+ .where('partition_id', '=', partitionId)
282
+ .where('client_id', '=', request.clientId)
283
+ .where('client_commit_id', '=', request.clientCommitId);
284
+
285
+ if (dialect.supportsForUpdate) {
286
+ query = query.forUpdate();
287
+ }
288
+
289
+ const existing = await query.executeTakeFirstOrThrow();
290
+
291
+ const cached = existing.result_json as SyncPushResponse | null;
292
+ if (!cached || cached.ok !== true) {
293
+ return {
294
+ response: {
295
+ ok: true,
296
+ status: 'rejected',
297
+ results: [
298
+ {
299
+ opIndex: 0,
300
+ status: 'error',
301
+ error: 'IDEMPOTENCY_CACHE_MISS',
302
+ code: 'INTERNAL',
303
+ retriable: true,
304
+ },
305
+ ],
306
+ },
307
+ affectedTables: [],
308
+ scopeKeys: [],
309
+ emittedChanges: [],
310
+ };
311
+ }
312
+
313
+ const base: SyncPushResponse = {
314
+ ...cached,
315
+ commitSeq: Number(existing.commit_seq),
316
+ };
317
+
318
+ if (cached.status === 'applied') {
319
+ const tablesFromDb = dialect.dbToArray(
320
+ existing.affected_tables
321
+ );
322
+ return {
323
+ response: { ...base, status: 'cached' },
324
+ affectedTables:
325
+ tablesFromDb.length > 0
326
+ ? tablesFromDb
327
+ : await readCommitAffectedTables(
328
+ trx,
329
+ dialect,
330
+ Number(existing.commit_seq),
331
+ partitionId
332
+ ),
333
+ scopeKeys: [],
334
+ emittedChanges: [],
335
+ };
336
+ }
337
+
338
+ return {
339
+ response: base,
340
+ affectedTables: [],
341
+ scopeKeys: [],
342
+ emittedChanges: [],
343
+ };
344
+ }
345
+
346
+ const insertedCommit = await (
347
+ syncTrx.selectFrom('sync_commits') as SelectQueryBuilder<
348
+ SyncCoreDb,
349
+ 'sync_commits',
350
+ EmptySelection
351
+ >
352
+ )
353
+ .selectAll()
354
+ .where('partition_id', '=', partitionId)
355
+ .where('client_id', '=', request.clientId)
356
+ .where('client_commit_id', '=', request.clientCommitId)
357
+ .executeTakeFirstOrThrow();
358
+
359
+ const commitSeq = Number(insertedCommit.commit_seq);
360
+ const commitId = `${request.clientId}:${request.clientCommitId}`;
361
+
362
+ const savepointName = 'sync_apply';
363
+ const useSavepoints = dialect.supportsSavepoints;
364
+ let savepointCreated = false;
365
+
366
+ try {
367
+ // Apply the commit under a savepoint so we can roll back app writes on conflict
368
+ // while still persisting the commit-level cached response.
369
+ if (useSavepoints) {
370
+ await sql.raw(`SAVEPOINT ${savepointName}`).execute(trx);
371
+ savepointCreated = true;
372
+ }
373
+
374
+ const allEmitted = [];
375
+ const results = [];
376
+ const affectedTablesSet = new Set<string>();
377
+
378
+ for (let i = 0; i < ops.length; i++) {
379
+ const op = ops[i]!;
380
+ const handler = args.shapes.getOrThrow(op.table);
381
+ const applied = await handler.applyOperation(
382
+ {
383
+ db: trx,
384
+ trx,
385
+ actorId: args.actorId,
386
+ clientId: request.clientId,
387
+ commitId,
388
+ schemaVersion: request.schemaVersion,
389
+ },
390
+ op,
391
+ i
392
+ );
393
+
394
+ if (applied.result.status !== 'applied') {
395
+ results.push(applied.result);
396
+ throw new RejectCommitError({
397
+ ok: true,
398
+ status: 'rejected',
399
+ commitSeq,
400
+ results,
401
+ });
402
+ }
403
+
404
+ // Framework-level enforcement: emitted changes must have scopes
405
+ for (const c of applied.emittedChanges ?? []) {
406
+ const scopes = c?.scopes;
407
+ if (!scopes || typeof scopes !== 'object') {
408
+ results.push({
409
+ opIndex: i,
410
+ status: 'error' as const,
411
+ error: 'MISSING_SCOPES',
412
+ code: 'INVALID_SCOPE',
413
+ retriable: false,
414
+ });
415
+ throw new RejectCommitError({
416
+ ok: true,
417
+ status: 'rejected',
418
+ commitSeq,
419
+ results,
420
+ });
421
+ }
422
+ }
423
+
424
+ results.push(applied.result);
425
+ allEmitted.push(...applied.emittedChanges);
426
+ for (const c of applied.emittedChanges) {
427
+ affectedTablesSet.add(c.table);
428
+ }
429
+ }
430
+
431
+ if (allEmitted.length > 0) {
432
+ const changeRows: Array<
433
+ Insertable<SyncCoreDb['sync_changes']>
434
+ > = allEmitted.map((c) => ({
435
+ partition_id: partitionId,
436
+ commit_seq: commitSeq,
437
+ table: c.table,
438
+ row_id: c.row_id,
439
+ op: c.op,
440
+ row_json: c.row_json,
441
+ row_version: c.row_version,
442
+ scopes: dialect.scopesToDb(c.scopes),
443
+ }));
444
+
445
+ await syncTrx
446
+ .insertInto('sync_changes')
447
+ .values(changeRows)
448
+ .execute();
449
+ }
450
+
451
+ const appliedResponse: SyncPushResponse = {
452
+ ok: true,
453
+ status: 'applied',
454
+ commitSeq,
455
+ results,
456
+ };
457
+
458
+ const affectedTables = Array.from(affectedTablesSet).sort();
459
+
460
+ const appliedCommitUpdate: Updateable<
461
+ SyncCoreDb['sync_commits']
462
+ > = {
463
+ result_json: appliedResponse,
464
+ change_count: allEmitted.length,
465
+ affected_tables: affectedTables,
466
+ };
467
+
468
+ await syncTrx
469
+ .updateTable('sync_commits')
470
+ .set(appliedCommitUpdate)
471
+ .where('commit_seq', '=', commitSeq)
472
+ .execute();
473
+
474
+ // Insert table commits for subscription filtering
475
+ if (affectedTables.length > 0) {
476
+ const tableCommits: Array<
477
+ Insertable<SyncCoreDb['sync_table_commits']>
478
+ > = affectedTables.map((table) => ({
479
+ partition_id: partitionId,
480
+ table,
481
+ commit_seq: commitSeq,
482
+ }));
483
+
484
+ await syncTrx
485
+ .insertInto('sync_table_commits')
486
+ .values(tableCommits)
487
+ .onConflict((oc) =>
488
+ oc
489
+ .columns(['partition_id', 'table', 'commit_seq'])
490
+ .doNothing()
491
+ )
492
+ .execute();
493
+ }
494
+
495
+ if (useSavepoints) {
496
+ await sql
497
+ .raw(`RELEASE SAVEPOINT ${savepointName}`)
498
+ .execute(trx);
499
+ }
500
+
501
+ return {
502
+ response: appliedResponse,
503
+ affectedTables,
504
+ scopeKeys: scopeKeysFromEmitted(allEmitted),
505
+ emittedChanges: allEmitted.map((c) => ({
506
+ table: c.table,
507
+ row_id: c.row_id,
508
+ op: c.op,
509
+ row_json: c.row_json,
510
+ row_version: c.row_version,
511
+ scopes: c.scopes,
512
+ })),
513
+ };
514
+ } catch (err) {
515
+ // Roll back app writes but keep the commit row.
516
+ if (savepointCreated) {
517
+ try {
518
+ await sql
519
+ .raw(`ROLLBACK TO SAVEPOINT ${savepointName}`)
520
+ .execute(trx);
521
+ await sql
522
+ .raw(`RELEASE SAVEPOINT ${savepointName}`)
523
+ .execute(trx);
524
+ } catch (savepointErr) {
525
+ // If savepoint rollback fails, the transaction may be in an
526
+ // inconsistent state. Log and rethrow to fail the entire commit
527
+ // rather than risk data corruption.
528
+ console.error(
529
+ '[pushCommit] Savepoint rollback failed:',
530
+ savepointErr
531
+ );
532
+ throw savepointErr;
533
+ }
534
+ }
535
+
536
+ if (!(err instanceof RejectCommitError)) throw err;
537
+
538
+ const rejectedCommitUpdate: Updateable<
539
+ SyncCoreDb['sync_commits']
540
+ > = {
541
+ result_json: err.response,
542
+ change_count: 0,
543
+ affected_tables: [],
544
+ };
545
+
546
+ // Persist the rejected response for commit-level idempotency.
547
+ await syncTrx
548
+ .updateTable('sync_commits')
549
+ .set(rejectedCommitUpdate)
550
+ .where('commit_seq', '=', commitSeq)
551
+ .execute();
552
+
553
+ return {
554
+ response: err.response,
555
+ affectedTables: [],
556
+ scopeKeys: [],
557
+ emittedChanges: [],
558
+ };
559
+ }
560
+ })
561
+ );
562
+ } catch (error) {
563
+ const durationMs = Math.max(0, Date.now() - startedAtMs);
564
+ span.setAttribute('status', 'error');
565
+ span.setAttribute('duration_ms', durationMs);
566
+ span.setStatus('error');
567
+
568
+ recordPushMetrics({
569
+ status: 'error',
570
+ durationMs,
571
+ operationCount,
572
+ emittedChangeCount: 0,
573
+ affectedTableCount: 0,
574
+ });
575
+ captureSyncException(error, {
576
+ event: 'sync.server.push',
577
+ operationCount,
578
+ });
579
+ throw error;
580
+ }
581
+ }
582
+ );
583
+ }
@@ -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
+ }