dsh-workbench-host 0.0.0-stage → 0.6.5

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.
@@ -0,0 +1,56 @@
1
+ import { applyRemoteUpsert, writeConflict } from "../core/index.js";
2
+ /** All inbound paths, including manual resolution, share atomic domain validation. */
3
+ export function incomingTransaction(db, fn) {
4
+ db.exec("SAVEPOINT sync_incoming");
5
+ try {
6
+ const result = fn();
7
+ db.exec("RELEASE sync_incoming");
8
+ return result;
9
+ }
10
+ catch (error) {
11
+ db.exec("ROLLBACK TO sync_incoming; RELEASE sync_incoming");
12
+ throw error;
13
+ }
14
+ }
15
+ export function applyIncoming(db, table, input, serverTs, repair, force = false) {
16
+ return incomingTransaction(db, () => {
17
+ const local = db.prepare("SELECT * FROM " + table.name + " WHERE id=?").get(String(input.id));
18
+ const context = { db, row: input, local: local ?? null };
19
+ const row = table.normalizeIncoming?.(context) ?? input;
20
+ if (row.id !== input.id)
21
+ throw new Error("SYNC_ROW_ID_CHANGED");
22
+ const keys = table.uniqueKeys;
23
+ if (keys?.length && (table.uniquePolicy ?? "lww-tombstone") === "lww-tombstone" && row.deleted_at === null) {
24
+ for (const key of keys) {
25
+ if (!key.length || key.some(c => row[c] == null))
26
+ continue;
27
+ const other = db.prepare("SELECT * FROM " + table.name + " WHERE deleted_at IS NULL AND " + key.map(c => c + "=?").join(" AND ") + " AND id<>? ORDER BY updated_at DESC LIMIT 1")
28
+ .get(...key.map(c => row[c]), String(row.id));
29
+ if (!other)
30
+ continue;
31
+ const localTs = Number(other.updated_at) || 0, remoteTs = Number(row.updated_at) || serverTs;
32
+ if (localTs > remoteTs) {
33
+ writeConflict(db, table.name, row.id, "unique", "local", other, row, remoteTs, localTs);
34
+ return false;
35
+ }
36
+ const ts = Math.max(localTs, remoteTs);
37
+ db.prepare("UPDATE " + table.name + " SET deleted_at=?,updated_at=?,rev=rev+1 WHERE id=?").run(ts, ts, other.id);
38
+ const tomb = db.prepare("SELECT * FROM " + table.name + " WHERE id=?").get(other.id);
39
+ repair?.(tomb);
40
+ writeConflict(db, table.name, row.id, "unique", "server", other, row, remoteTs, localTs);
41
+ }
42
+ }
43
+ let applied;
44
+ if (force) {
45
+ const cols = Object.keys(row);
46
+ db.prepare("DELETE FROM " + table.name + " WHERE id=?").run(row.id);
47
+ db.prepare("INSERT INTO " + table.name + " (" + cols.join(",") + ") VALUES(" + cols.map(() => "?").join(",") + ")").run(...cols.map(c => row[c]));
48
+ applied = true;
49
+ }
50
+ else
51
+ applied = applyRemoteUpsert(db, table.name, row, serverTs);
52
+ if (applied)
53
+ table.afterApply?.({ db, row, local: local ?? null });
54
+ return applied;
55
+ });
56
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,22 @@
1
+ export function stableStringify(value) {
2
+ if (value === null)
3
+ return "null";
4
+ if (Array.isArray(value))
5
+ return "[" + value.map((v) => stableStringify(v)).join(",") + "]";
6
+ if (typeof value === "object") {
7
+ const obj = value;
8
+ return "{" + Object.keys(obj).sort().map((k) => JSON.stringify(k) + ":" + stableStringify(obj[k])).join(",") + "}";
9
+ }
10
+ return JSON.stringify(value);
11
+ }
12
+ export function parseObject(raw) {
13
+ if (typeof raw !== "string" || !raw)
14
+ return null;
15
+ try {
16
+ const v = JSON.parse(raw);
17
+ return v && typeof v === "object" && !Array.isArray(v) ? v : null;
18
+ }
19
+ catch {
20
+ return null;
21
+ }
22
+ }
@@ -0,0 +1,550 @@
1
+ import { applyIncoming } from "./sync-incoming.js";
2
+ import { parseObject, stableStringify } from "./sync-values.js";
3
+ export * from "./sync-types.js";
4
+ export { listConflicts, resolveConflict } from "./sync-conflicts.js";
5
+ import { getSyncState, getSyncStateText, recordDeadLetter, writeConflict, setSyncState, setSyncStateText, tableExists } from "../core/index.js";
6
+ export class SyncHttpError extends Error {
7
+ status;
8
+ code;
9
+ body;
10
+ constructor(status, code, message, body = {}) {
11
+ super(message);
12
+ this.name = "SyncHttpError";
13
+ this.status = status;
14
+ this.code = code;
15
+ this.body = body;
16
+ }
17
+ }
18
+ /** 服务端时钟校准 + 本地单调递增时钟。 */
19
+ export class SyncClock {
20
+ offset = 0;
21
+ last = 0;
22
+ calibrate(serverTime, t1, t2) {
23
+ this.offset = Math.round(serverTime - (t1 + t2) / 2);
24
+ }
25
+ now() {
26
+ const wall = Date.now() + this.offset;
27
+ this.last = Math.max(wall, this.last + 1);
28
+ return this.last;
29
+ }
30
+ getOffset() {
31
+ return this.offset;
32
+ }
33
+ }
34
+ const SESSION_LIMIT = 200;
35
+ const PUSH_BATCH = 200;
36
+ const PULL_BATCH = 300;
37
+ const TREE_RETRY = 3;
38
+ function keyOf(userId, table, kind) {
39
+ return kind + ":" + userId + ":" + table;
40
+ }
41
+ /** 宿主 v2 同步引擎。所有业务差异都在 DomainSyncTable.reconcile 中,引擎只做协议与平台语义。 */
42
+ export class SyncEngine {
43
+ db;
44
+ domains;
45
+ transport;
46
+ clock;
47
+ userId;
48
+ deviceId;
49
+ epoch;
50
+ onEvent;
51
+ running = false;
52
+ sessionId = "";
53
+ constructor(opts) {
54
+ this.db = opts.db;
55
+ this.domains = opts.domains;
56
+ this.transport = opts.transport;
57
+ this.clock = opts.clock;
58
+ this.userId = opts.userId;
59
+ this.deviceId = opts.deviceId;
60
+ this.epoch = opts.epoch;
61
+ this.onEvent = opts.onEvent;
62
+ }
63
+ isRunning() {
64
+ return this.running;
65
+ }
66
+ emit(event, data) {
67
+ try {
68
+ this.onEvent?.(event, data);
69
+ }
70
+ catch {
71
+ /* ignore */
72
+ }
73
+ }
74
+ bindings() {
75
+ const out = new Map();
76
+ for (const domain of this.domains) {
77
+ const declared = domain.sync?.tables;
78
+ if (declared && declared.length) {
79
+ for (const table of declared) {
80
+ if (out.has(table.name))
81
+ continue;
82
+ out.set(table.name, { domainId: domain.id, table });
83
+ }
84
+ continue;
85
+ }
86
+ for (const name of domain.tables ?? []) {
87
+ if (out.has(name))
88
+ continue;
89
+ out.set(name, { domainId: domain.id, table: { name, mode: "row" } });
90
+ }
91
+ }
92
+ return out;
93
+ }
94
+ tableExists(table) {
95
+ return tableExists(this.db, table);
96
+ }
97
+ readRows(table) {
98
+ if (!this.tableExists(table))
99
+ return [];
100
+ return this.db.prepare("SELECT * FROM " + table + " ORDER BY id ASC").all();
101
+ }
102
+ replaceRows(table, rows) {
103
+ if (!this.tableExists(table))
104
+ return;
105
+ this.db.exec("BEGIN IMMEDIATE");
106
+ try {
107
+ this.db.prepare("DELETE FROM " + table).run();
108
+ for (const row of rows) {
109
+ const cols = Object.keys(row);
110
+ if (!cols.length)
111
+ continue;
112
+ const stmt = this.db.prepare("INSERT INTO " + table + " (" + cols.join(",") + ") VALUES(" + cols.map(() => "?").join(",") + ")");
113
+ stmt.run(...cols.map((c) => (row[c] === undefined ? null : row[c])));
114
+ }
115
+ this.db.exec("COMMIT");
116
+ }
117
+ catch (e) {
118
+ try {
119
+ this.db.exec("ROLLBACK");
120
+ }
121
+ catch {
122
+ /* ignore */
123
+ }
124
+ throw e;
125
+ }
126
+ }
127
+ maxSeq(table) {
128
+ const row = this.db
129
+ .prepare("SELECT MAX(seq) AS n FROM sync_change_log WHERE table_name=?")
130
+ .get(table);
131
+ return row?.n ?? 0;
132
+ }
133
+ hasChanges(table, after) {
134
+ return Boolean(this.db
135
+ .prepare("SELECT 1 FROM sync_change_log WHERE table_name=? AND seq>? LIMIT 1")
136
+ .get(table, after));
137
+ }
138
+ enqueueRepair(table, row) {
139
+ if (!this.tableExists(table) || !row || !row.id)
140
+ return;
141
+ const payload = stableStringify(row);
142
+ const op = row.deleted_at !== null && row.deleted_at !== undefined ? "delete" : "upsert";
143
+ this.db
144
+ .prepare("INSERT INTO sync_change_log(table_name,row_id,op,payload,origin,updated_at) VALUES(?,?,?,?,?,?)")
145
+ .run(table, String(row.id), op, payload, "sync-repair", Number(row.updated_at) || this.clock.now());
146
+ }
147
+ localRow(table, rowId) {
148
+ if (!this.tableExists(table))
149
+ return null;
150
+ const row = this.db.prepare("SELECT * FROM " + table + " WHERE id=?").get(rowId);
151
+ return row ?? null;
152
+ }
153
+ applyRemoteRow(table, binding, row, serverTs) {
154
+ return applyIncoming(this.db, binding.table, row, serverTs, tomb => this.enqueueRepair(table, tomb));
155
+ }
156
+ /** 把本地 change log 中的条目补成完整行 payload;旧数据 delete payload=null 时从当前行/墓碑补齐。 */
157
+ changePayload(table, rowId, updatedAt, payload) {
158
+ const parsed = parseObject(payload);
159
+ if (parsed && parsed.id !== undefined)
160
+ return parsed;
161
+ const row = this.localRow(table, rowId);
162
+ if (row)
163
+ return row;
164
+ return { id: rowId, updated_at: updatedAt, deleted_at: updatedAt, rev: 0 };
165
+ }
166
+ report(partial) {
167
+ const now = this.clock.now();
168
+ setSyncStateText(this.db, "last_sync_at", String(now));
169
+ setSyncStateText(this.db, "last_sync_ok", partial.ok ? "1" : "0");
170
+ setSyncStateText(this.db, "last_sync_error", partial.error ?? "");
171
+ setSyncStateText(this.db, "failed_tables", JSON.stringify(partial.failed_tables ?? []));
172
+ }
173
+ status() {
174
+ const failedRaw = getSyncStateText(this.db, "failed_tables");
175
+ let failed = [];
176
+ try {
177
+ const v = JSON.parse(failedRaw);
178
+ if (Array.isArray(v))
179
+ failed = v.map(String);
180
+ }
181
+ catch {
182
+ /* ignore */
183
+ }
184
+ const conflicts = this.db
185
+ .prepare("SELECT COUNT(*) AS n FROM conflict_shadow")
186
+ .get();
187
+ const dead = this.db
188
+ .prepare("SELECT COUNT(*) AS n FROM sync_dead_letter")
189
+ .get();
190
+ return {
191
+ running: this.running,
192
+ user_id: getSyncStateText(this.db, "account_user_id"),
193
+ device_id: this.deviceId,
194
+ epoch: this.epoch,
195
+ clock_offset: Number(getSyncStateText(this.db, "clock_offset")) || 0,
196
+ last_sync_at: Number(getSyncStateText(this.db, "last_sync_at")) || 0,
197
+ last_sync_ok: getSyncStateText(this.db, "last_sync_ok") === "1",
198
+ last_sync_error: getSyncStateText(this.db, "last_sync_error"),
199
+ failed_tables: failed,
200
+ conflicts: conflicts.n,
201
+ dead_letters: dead.n,
202
+ };
203
+ }
204
+ ensureAccount() {
205
+ const cur = getSyncStateText(this.db, "account_user_id");
206
+ if (!cur) {
207
+ setSyncStateText(this.db, "account_user_id", this.userId);
208
+ return;
209
+ }
210
+ if (cur !== this.userId) {
211
+ throw new Error("本地数据已绑定账号 " + cur + ";切换账号请使用新的 WB_HOME 数据目录");
212
+ }
213
+ }
214
+ async run() {
215
+ if (this.running) {
216
+ return {
217
+ ok: false,
218
+ pushed: 0,
219
+ pulled: 0,
220
+ tables: [],
221
+ failed_tables: [],
222
+ error: "sync already running",
223
+ repaired: 0,
224
+ started_at: this.clock.now(),
225
+ finished_at: this.clock.now(),
226
+ };
227
+ }
228
+ this.running = true;
229
+ const startedAt = this.clock.now();
230
+ const tables = this.bindings();
231
+ const report = {
232
+ ok: true,
233
+ pushed: 0,
234
+ pulled: 0,
235
+ tables: [...tables.keys()],
236
+ failed_tables: [],
237
+ repaired: 0,
238
+ started_at: startedAt,
239
+ finished_at: startedAt,
240
+ };
241
+ this.emit("sync-status", { phase: "open", running: true });
242
+ try {
243
+ this.ensureAccount();
244
+ const t1 = Date.now();
245
+ const opened = await this.transport.open(2, this.deviceId);
246
+ this.clock.calibrate(opened.server_time, t1, Date.now());
247
+ setSyncStateText(this.db, "clock_offset", String(this.clock.getOffset()));
248
+ this.sessionId = opened.session_id;
249
+ const versions = opened.tables ?? {};
250
+ const tablesOpen = [];
251
+ for (const [name, binding] of tables) {
252
+ tablesOpen.push({ name, mode: binding.table.mode });
253
+ }
254
+ const treeTables = [...tables.entries()].filter(([, b]) => b.table.mode === "tree");
255
+ const rowTables = [...tables.entries()].filter(([, b]) => b.table.mode !== "tree");
256
+ // B 类先做整表收敛,再处理 A 类行;避免树节点引用尚未同步的行。
257
+ for (const [name, binding] of treeTables) {
258
+ try {
259
+ await this.syncTreeTable(name, binding, versions[name]?.version ?? 0);
260
+ this.emit("sync-status", { phase: "table", table: name, mode: "tree" });
261
+ }
262
+ catch (e) {
263
+ const msg = String((e && e.message) || e);
264
+ report.failed_tables.push(name);
265
+ recordDeadLetter(this.db, name, "*", "table", null, msg);
266
+ this.emit("sync-status", { phase: "table-error", table: name, error: msg });
267
+ }
268
+ }
269
+ for (const [name, binding] of rowTables) {
270
+ try {
271
+ const r = await this.syncRowTable(name, binding);
272
+ report.pushed += r.pushed;
273
+ report.pulled += r.pulled;
274
+ report.repaired += r.repaired;
275
+ this.emit("sync-status", { phase: "table", table: name, mode: "row" });
276
+ }
277
+ catch (e) {
278
+ const msg = String((e && e.message) || e);
279
+ report.failed_tables.push(name);
280
+ recordDeadLetter(this.db, name, "*", "table", null, msg);
281
+ this.emit("sync-status", { phase: "table-error", table: name, error: msg });
282
+ }
283
+ }
284
+ report.ok = report.failed_tables.length === 0;
285
+ if (!report.ok)
286
+ report.error = "部分表同步失败:" + report.failed_tables.join(", ");
287
+ }
288
+ catch (e) {
289
+ report.ok = false;
290
+ report.error = String((e && e.message) || e);
291
+ }
292
+ finally {
293
+ report.finished_at = this.clock.now();
294
+ this.report(report);
295
+ this.emit("sync-status", {
296
+ phase: "done",
297
+ running: false,
298
+ ok: report.ok,
299
+ pushed: report.pushed,
300
+ pulled: report.pulled,
301
+ failed_tables: report.failed_tables,
302
+ error: report.error ?? "",
303
+ });
304
+ this.emit("sync-done", {
305
+ ok: report.ok,
306
+ pushed: report.pushed,
307
+ pulled: report.pulled,
308
+ failed_tables: report.failed_tables,
309
+ error: report.error ?? "",
310
+ });
311
+ this.running = false;
312
+ try {
313
+ await this.transport.close({
314
+ session_id: this.sessionId,
315
+ success: report.ok,
316
+ cursors: this.snapshotCursors([...tables.keys()]),
317
+ });
318
+ }
319
+ catch {
320
+ /* close 幂等;网络失败不影响本轮结果 */
321
+ }
322
+ this.sessionId = "";
323
+ }
324
+ return report;
325
+ }
326
+ snapshotCursors(tables) {
327
+ const out = {};
328
+ for (const table of tables) {
329
+ out[table] = getSyncState(this.db, keyOf(this.userId, table, "pull_cursor"));
330
+ }
331
+ return out;
332
+ }
333
+ async syncRowTable(table, binding) {
334
+ let pushed = 0;
335
+ let pulled = 0;
336
+ let repaired = 0;
337
+ if (!this.tableExists(table)) {
338
+ throw new Error("表不存在:" + table + "(业务插件未初始化?)");
339
+ }
340
+ const backfillKey = keyOf(this.userId, table, "backfill_done");
341
+ const pullKey = keyOf(this.userId, table, "pull_cursor");
342
+ const pushKey = keyOf(this.userId, table, "push_after");
343
+ if (getSyncStateText(this.db, backfillKey) !== "1") {
344
+ const snap = await this.transport.snapshot({ session_id: this.sessionId, table });
345
+ const remoteIds = new Set();
346
+ for (const row of snap.rows ?? []) {
347
+ const id = String(row.id ?? "");
348
+ if (!id)
349
+ continue;
350
+ remoteIds.add(id);
351
+ const applied = this.applyRemoteRow(table, binding, row, Number(row.updated_at) || 0);
352
+ if (!applied) {
353
+ const local = this.localRow(table, String(row.id));
354
+ if (local) {
355
+ this.enqueueRepair(table, local);
356
+ repaired++;
357
+ }
358
+ }
359
+ }
360
+ for (const row of this.readRows(table)) {
361
+ if (!remoteIds.has(String(row.id))) {
362
+ this.enqueueRepair(table, row);
363
+ repaired++;
364
+ }
365
+ }
366
+ setSyncState(this.db, pullKey, snap.cursor ?? 0);
367
+ setSyncStateText(this.db, backfillKey, "1");
368
+ this.emit("sync-status", { phase: "backfill", table, rows: snap.rows?.length ?? 0 });
369
+ }
370
+ // push 本地尾部(包含 backfill 补进来的 repair)
371
+ for (;;) {
372
+ const after = getSyncState(this.db, pushKey);
373
+ const changes = this.db
374
+ .prepare("SELECT * FROM sync_change_log WHERE table_name=? AND seq>? ORDER BY seq ASC LIMIT ?")
375
+ .all(table, after, PUSH_BATCH);
376
+ if (!changes.length)
377
+ break;
378
+ const sent = changes.map((c) => {
379
+ const payload = this.changePayload(table, c.row_id, c.updated_at, c.payload);
380
+ return {
381
+ client_seq: c.seq,
382
+ table_name: c.table_name,
383
+ row_id: c.row_id,
384
+ op: c.op === "delete" ? "delete" : "upsert",
385
+ payload,
386
+ updated_at: Number(payload.updated_at) || c.updated_at,
387
+ };
388
+ });
389
+ const res = await this.transport.push({
390
+ session_id: this.sessionId,
391
+ client_epoch: this.epoch,
392
+ changes: sent,
393
+ });
394
+ let handled = 0;
395
+ for (const r of res.results ?? []) {
396
+ const seq = Number(r.client_seq) || 0;
397
+ if (r.status === "conflict" && r.current) {
398
+ const local = this.localRow(table, r.row_id);
399
+ const serverTs = Number(r.current.updated_at) || 0;
400
+ if (local) {
401
+ writeConflict(this.db, table, r.row_id, "push", "server", local, r.current, serverTs, Number(local.updated_at) || 0);
402
+ }
403
+ this.applyRemoteRow(table, binding, r.current, serverTs);
404
+ }
405
+ else if (r.status === "invalid") {
406
+ recordDeadLetter(this.db, table, r.row_id, "upsert", null, r.error ?? "invalid");
407
+ }
408
+ handled = Math.max(handled, seq);
409
+ }
410
+ const advance = Math.max(after, handled, Math.min(res.accepted_up_to ?? 0, sent[sent.length - 1].client_seq));
411
+ setSyncState(this.db, pushKey, advance);
412
+ pushed += sent.length;
413
+ if (changes.length < PUSH_BATCH)
414
+ break;
415
+ }
416
+ // pull 远端变更(按表游标;不看全局游标)
417
+ let cursor = getSyncState(this.db, pullKey);
418
+ for (;;) {
419
+ const page = await this.transport.pull({
420
+ session_id: this.sessionId,
421
+ cursors: { [table]: cursor },
422
+ limit: PULL_BATCH,
423
+ });
424
+ if (page.min_seq > 0 && cursor + 1 < page.min_seq) {
425
+ // 云端日志已被截断,单表重新 snapshot 重建游标,避免永久缺口。
426
+ const snap = await this.transport.snapshot({ session_id: this.sessionId, table });
427
+ for (const row of snap.rows ?? []) {
428
+ const applied = this.applyRemoteRow(table, binding, row, Number(row.updated_at) || 0);
429
+ if (!applied) {
430
+ const local = this.localRow(table, String(row.id));
431
+ if (local) {
432
+ this.enqueueRepair(table, local);
433
+ repaired++;
434
+ }
435
+ }
436
+ }
437
+ cursor = snap.cursor ?? 0;
438
+ setSyncState(this.db, pullKey, cursor);
439
+ break;
440
+ }
441
+ let pageMax = cursor;
442
+ for (const e of page.entries ?? []) {
443
+ pageMax = Math.max(pageMax, Number(e.server_seq) || 0);
444
+ if (e.op === "reset")
445
+ continue;
446
+ if (e.device_id === this.deviceId)
447
+ continue;
448
+ const applied = this.applyEntry(table, binding, e);
449
+ if (!applied) {
450
+ repaired++;
451
+ const row = this.localRow(table, e.row_id);
452
+ if (row)
453
+ this.enqueueRepair(table, row);
454
+ }
455
+ pulled++;
456
+ }
457
+ cursor = Math.max(cursor, Number(page.next_cursors?.[table] ?? pageMax));
458
+ setSyncState(this.db, pullKey, cursor);
459
+ if (!page.has_more)
460
+ break;
461
+ if (!(page.entries ?? []).length)
462
+ break;
463
+ }
464
+ return { pushed, pulled, repaired };
465
+ }
466
+ applyEntry(table, binding, entry) {
467
+ if (entry.op === "delete") {
468
+ const payload = entry.payload ?? this.localRow(table, entry.row_id);
469
+ if (!payload)
470
+ return false;
471
+ return this.applyRemoteRow(table, binding, { ...payload, id: entry.row_id,
472
+ updated_at: entry.updated_at, deleted_at: payload.deleted_at ?? entry.updated_at }, entry.updated_at);
473
+ }
474
+ if (entry.payload) {
475
+ return this.applyRemoteRow(table, binding, entry.payload, Number(entry.payload.updated_at) || entry.updated_at);
476
+ }
477
+ return false;
478
+ }
479
+ async syncTreeTable(table, binding, remoteVersion) {
480
+ if (!binding.table.reconcile) {
481
+ throw new Error("树表缺少 reconcile:" + table);
482
+ }
483
+ if (!this.tableExists(table))
484
+ throw new Error("表不存在:" + table);
485
+ const versionKey = keyOf(this.userId, table, "table_version");
486
+ const pushKey = keyOf(this.userId, table, "push_after");
487
+ const pullKey = keyOf(this.userId, table, "pull_cursor");
488
+ const backfillKey = keyOf(this.userId, table, "backfill_done");
489
+ const localVersion = Number(getSyncStateText(this.db, versionKey)) || 0;
490
+ const backfilled = getSyncStateText(this.db, backfillKey) === "1";
491
+ const after = getSyncState(this.db, pushKey);
492
+ const dirty = this.hasChanges(table, after);
493
+ if (backfilled && localVersion === remoteVersion && !dirty)
494
+ return;
495
+ // 版本一致但有本地改动:以服务端版本为 base 整表推上去。
496
+ if (backfilled && localVersion === remoteVersion && dirty) {
497
+ const rows = this.readRows(table);
498
+ const maxBefore = this.maxSeq(table);
499
+ try {
500
+ const full = await this.transport.full({
501
+ session_id: this.sessionId,
502
+ table,
503
+ base_version: remoteVersion,
504
+ rows,
505
+ });
506
+ setSyncStateText(this.db, versionKey, String(full.version));
507
+ setSyncState(this.db, pullKey, Math.max(getSyncState(this.db, pullKey), full.cursor));
508
+ setSyncState(this.db, pushKey, maxBefore);
509
+ return;
510
+ }
511
+ catch (e) {
512
+ if (!(e instanceof SyncHttpError) || e.code !== "version_conflict")
513
+ throw e;
514
+ // 版本被别人推进:走 snapshot/reconcile。
515
+ }
516
+ }
517
+ let lastError = null;
518
+ for (let attempt = 0; attempt < TREE_RETRY; attempt++) {
519
+ const snap = await this.transport.snapshot({ session_id: this.sessionId, table });
520
+ const localRows = this.readRows(table);
521
+ const result = await binding.table.reconcile(snap.rows ?? [], localRows);
522
+ const rows = Array.isArray(result?.rows) ? result.rows : localRows;
523
+ this.replaceRows(table, rows);
524
+ for (const dirtyTable of result?.dirtyRowTables ?? []) {
525
+ for (const row of this.readRows(dirtyTable))
526
+ this.enqueueRepair(dirtyTable, row);
527
+ }
528
+ const maxBefore = this.maxSeq(table);
529
+ try {
530
+ const full = await this.transport.full({
531
+ session_id: this.sessionId,
532
+ table,
533
+ base_version: snap.version,
534
+ rows,
535
+ });
536
+ setSyncStateText(this.db, versionKey, String(full.version));
537
+ setSyncState(this.db, pullKey, Math.max(getSyncState(this.db, pullKey), full.cursor));
538
+ setSyncState(this.db, pushKey, maxBefore);
539
+ setSyncStateText(this.db, backfillKey, "1");
540
+ return;
541
+ }
542
+ catch (e) {
543
+ lastError = e;
544
+ if (!(e instanceof SyncHttpError) || e.code !== "version_conflict")
545
+ throw e;
546
+ }
547
+ }
548
+ throw lastError instanceof Error ? lastError : new Error("树表同步失败:" + table);
549
+ }
550
+ }
@@ -0,0 +1 @@
1
+ export {};