@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.
- package/dist/blobs/adapters/database.d.ts +83 -0
- package/dist/blobs/adapters/database.d.ts.map +1 -0
- package/dist/blobs/adapters/database.js +180 -0
- package/dist/blobs/adapters/database.js.map +1 -0
- package/dist/blobs/adapters/s3.d.ts +82 -0
- package/dist/blobs/adapters/s3.d.ts.map +1 -0
- package/dist/blobs/adapters/s3.js +170 -0
- package/dist/blobs/adapters/s3.js.map +1 -0
- package/dist/blobs/index.d.ts +9 -0
- package/dist/blobs/index.d.ts.map +1 -0
- package/dist/blobs/index.js +9 -0
- package/dist/blobs/index.js.map +1 -0
- package/dist/blobs/manager.d.ts +195 -0
- package/dist/blobs/manager.d.ts.map +1 -0
- package/dist/blobs/manager.js +440 -0
- package/dist/blobs/manager.js.map +1 -0
- package/dist/blobs/migrate.d.ts +27 -0
- package/dist/blobs/migrate.d.ts.map +1 -0
- package/dist/blobs/migrate.js +119 -0
- package/dist/blobs/migrate.js.map +1 -0
- package/dist/blobs/types.d.ts +54 -0
- package/dist/blobs/types.d.ts.map +1 -0
- package/dist/blobs/types.js +5 -0
- package/dist/blobs/types.js.map +1 -0
- package/dist/clients.d.ts +14 -0
- package/dist/clients.d.ts.map +1 -0
- package/dist/clients.js +7 -0
- package/dist/clients.js.map +1 -0
- package/dist/compaction.d.ts +27 -0
- package/dist/compaction.d.ts.map +1 -0
- package/dist/compaction.js +49 -0
- package/dist/compaction.js.map +1 -0
- package/dist/dialect/index.d.ts +5 -0
- package/dist/dialect/index.d.ts.map +1 -0
- package/dist/dialect/index.js +5 -0
- package/dist/dialect/index.js.map +1 -0
- package/dist/dialect/types.d.ts +170 -0
- package/dist/dialect/types.d.ts.map +1 -0
- package/dist/dialect/types.js +8 -0
- package/dist/dialect/types.js.map +1 -0
- package/dist/helpers/conflict.d.ts +52 -0
- package/dist/helpers/conflict.d.ts.map +1 -0
- package/dist/helpers/conflict.js +49 -0
- package/dist/helpers/conflict.js.map +1 -0
- package/dist/helpers/emitted-change.d.ts +56 -0
- package/dist/helpers/emitted-change.d.ts.map +1 -0
- package/dist/helpers/emitted-change.js +46 -0
- package/dist/helpers/emitted-change.js.map +1 -0
- package/dist/helpers/index.d.ts +10 -0
- package/dist/helpers/index.d.ts.map +1 -0
- package/dist/helpers/index.js +10 -0
- package/dist/helpers/index.js.map +1 -0
- package/dist/helpers/paginate.d.ts +49 -0
- package/dist/helpers/paginate.d.ts.map +1 -0
- package/dist/helpers/paginate.js +54 -0
- package/dist/helpers/paginate.js.map +1 -0
- package/dist/helpers/scope-strings.d.ts +74 -0
- package/dist/helpers/scope-strings.d.ts.map +1 -0
- package/dist/helpers/scope-strings.js +82 -0
- package/dist/helpers/scope-strings.js.map +1 -0
- package/dist/index.d.ts +28 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +27 -0
- package/dist/index.js.map +1 -0
- package/dist/migrate.d.ts +14 -0
- package/dist/migrate.d.ts.map +1 -0
- package/dist/migrate.js +13 -0
- package/dist/migrate.js.map +1 -0
- package/dist/proxy/handler.d.ts +42 -0
- package/dist/proxy/handler.d.ts.map +1 -0
- package/dist/proxy/handler.js +99 -0
- package/dist/proxy/handler.js.map +1 -0
- package/dist/proxy/index.d.ts +9 -0
- package/dist/proxy/index.d.ts.map +1 -0
- package/dist/proxy/index.js +14 -0
- package/dist/proxy/index.js.map +1 -0
- package/dist/proxy/mutation-detector.d.ts +31 -0
- package/dist/proxy/mutation-detector.d.ts.map +1 -0
- package/dist/proxy/mutation-detector.js +61 -0
- package/dist/proxy/mutation-detector.js.map +1 -0
- package/dist/proxy/oplog.d.ts +30 -0
- package/dist/proxy/oplog.d.ts.map +1 -0
- package/dist/proxy/oplog.js +110 -0
- package/dist/proxy/oplog.js.map +1 -0
- package/dist/proxy/registry.d.ts +35 -0
- package/dist/proxy/registry.d.ts.map +1 -0
- package/dist/proxy/registry.js +49 -0
- package/dist/proxy/registry.js.map +1 -0
- package/dist/proxy/types.d.ts +44 -0
- package/dist/proxy/types.d.ts.map +1 -0
- package/dist/proxy/types.js +7 -0
- package/dist/proxy/types.js.map +1 -0
- package/dist/prune.d.ts +37 -0
- package/dist/prune.d.ts.map +1 -0
- package/dist/prune.js +112 -0
- package/dist/prune.js.map +1 -0
- package/dist/pull.d.ts +31 -0
- package/dist/pull.d.ts.map +1 -0
- package/dist/pull.js +414 -0
- package/dist/pull.js.map +1 -0
- package/dist/push.d.ts +33 -0
- package/dist/push.d.ts.map +1 -0
- package/dist/push.js +329 -0
- package/dist/push.js.map +1 -0
- package/dist/realtime/in-memory.d.ts +13 -0
- package/dist/realtime/in-memory.d.ts.map +1 -0
- package/dist/realtime/in-memory.js +28 -0
- package/dist/realtime/in-memory.js.map +1 -0
- package/dist/realtime/index.d.ts +3 -0
- package/dist/realtime/index.d.ts.map +1 -0
- package/dist/realtime/index.js +2 -0
- package/dist/realtime/index.js.map +1 -0
- package/dist/realtime/types.d.ts +50 -0
- package/dist/realtime/types.d.ts.map +1 -0
- package/dist/realtime/types.js +7 -0
- package/dist/realtime/types.js.map +1 -0
- package/dist/schema.d.ts +164 -0
- package/dist/schema.d.ts.map +1 -0
- package/dist/schema.js +10 -0
- package/dist/schema.js.map +1 -0
- package/dist/shapes/create-handler.d.ts +119 -0
- package/dist/shapes/create-handler.d.ts.map +1 -0
- package/dist/shapes/create-handler.js +327 -0
- package/dist/shapes/create-handler.js.map +1 -0
- package/dist/shapes/index.d.ts +4 -0
- package/dist/shapes/index.d.ts.map +1 -0
- package/dist/shapes/index.js +4 -0
- package/dist/shapes/index.js.map +1 -0
- package/dist/shapes/registry.d.ts +20 -0
- package/dist/shapes/registry.d.ts.map +1 -0
- package/dist/shapes/registry.js +88 -0
- package/dist/shapes/registry.js.map +1 -0
- package/dist/shapes/types.d.ts +204 -0
- package/dist/shapes/types.d.ts.map +1 -0
- package/dist/shapes/types.js +2 -0
- package/dist/shapes/types.js.map +1 -0
- package/dist/snapshot-chunks/adapters/s3.d.ts +63 -0
- package/dist/snapshot-chunks/adapters/s3.d.ts.map +1 -0
- package/dist/snapshot-chunks/adapters/s3.js +50 -0
- package/dist/snapshot-chunks/adapters/s3.js.map +1 -0
- package/dist/snapshot-chunks/db-metadata.d.ts +33 -0
- package/dist/snapshot-chunks/db-metadata.d.ts.map +1 -0
- package/dist/snapshot-chunks/db-metadata.js +169 -0
- package/dist/snapshot-chunks/db-metadata.js.map +1 -0
- package/dist/snapshot-chunks/index.d.ts +9 -0
- package/dist/snapshot-chunks/index.d.ts.map +1 -0
- package/dist/snapshot-chunks/index.js +9 -0
- package/dist/snapshot-chunks/index.js.map +1 -0
- package/dist/snapshot-chunks/types.d.ts +65 -0
- package/dist/snapshot-chunks/types.d.ts.map +1 -0
- package/dist/snapshot-chunks/types.js +8 -0
- package/dist/snapshot-chunks/types.js.map +1 -0
- package/dist/snapshot-chunks.d.ts +59 -0
- package/dist/snapshot-chunks.d.ts.map +1 -0
- package/dist/snapshot-chunks.js +202 -0
- package/dist/snapshot-chunks.js.map +1 -0
- package/dist/stats.d.ts +19 -0
- package/dist/stats.d.ts.map +1 -0
- package/dist/stats.js +57 -0
- package/dist/stats.js.map +1 -0
- package/dist/subscriptions/index.d.ts +2 -0
- package/dist/subscriptions/index.d.ts.map +1 -0
- package/dist/subscriptions/index.js +2 -0
- package/dist/subscriptions/index.js.map +1 -0
- package/dist/subscriptions/resolve.d.ts +35 -0
- package/dist/subscriptions/resolve.d.ts.map +1 -0
- package/dist/subscriptions/resolve.js +134 -0
- package/dist/subscriptions/resolve.js.map +1 -0
- package/package.json +80 -0
- package/src/blobs/adapters/database.ts +290 -0
- package/src/blobs/adapters/s3.ts +271 -0
- package/src/blobs/index.ts +9 -0
- package/src/blobs/manager.ts +600 -0
- package/src/blobs/migrate.ts +150 -0
- package/src/blobs/types.ts +70 -0
- package/src/clients.ts +21 -0
- package/src/compaction.ts +77 -0
- package/src/dialect/index.ts +5 -0
- package/src/dialect/types.ts +222 -0
- package/src/helpers/conflict.ts +64 -0
- package/src/helpers/emitted-change.ts +69 -0
- package/src/helpers/index.ts +10 -0
- package/src/helpers/paginate.ts +82 -0
- package/src/helpers/scope-strings.ts +101 -0
- package/src/index.ts +28 -0
- package/src/migrate.ts +20 -0
- package/src/proxy/handler.ts +152 -0
- package/src/proxy/index.ts +18 -0
- package/src/proxy/mutation-detector.ts +83 -0
- package/src/proxy/oplog.ts +144 -0
- package/src/proxy/registry.ts +56 -0
- package/src/proxy/types.ts +46 -0
- package/src/prune.ts +200 -0
- package/src/pull.ts +551 -0
- package/src/push.ts +457 -0
- package/src/realtime/in-memory.ts +33 -0
- package/src/realtime/index.ts +5 -0
- package/src/realtime/types.ts +55 -0
- package/src/schema.ts +172 -0
- package/src/shapes/create-handler.ts +590 -0
- package/src/shapes/index.ts +3 -0
- package/src/shapes/registry.ts +109 -0
- package/src/shapes/types.ts +267 -0
- package/src/snapshot-chunks/adapters/s3.ts +68 -0
- package/src/snapshot-chunks/db-metadata.ts +238 -0
- package/src/snapshot-chunks/index.ts +9 -0
- package/src/snapshot-chunks/types.ts +79 -0
- package/src/snapshot-chunks.ts +301 -0
- package/src/stats.ts +104 -0
- package/src/subscriptions/index.ts +1 -0
- 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,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
|
+
}
|