@syncular/client 0.85.0 → 0.90.0
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/README.md +13 -4
- package/dist/apply.d.ts +1 -1
- package/dist/apply.js +25 -26
- package/dist/blob.d.ts +0 -4
- package/dist/blob.js +7 -22
- package/dist/client.d.ts +31 -10
- package/dist/client.js +501 -465
- package/dist/diagnostics.d.ts +2 -4
- package/dist/diagnostics.js +3 -17
- package/dist/encryption.js +5 -30
- package/dist/errors.d.ts +2 -0
- package/dist/errors.js +4 -0
- package/dist/failed-overlay.d.ts +8 -2
- package/dist/failed-overlay.js +33 -22
- package/dist/local-purge.d.ts +1 -0
- package/dist/local-purge.js +1 -1
- package/dist/local-rebootstrap-receipt.js +2 -2
- package/dist/local-rebootstrap.js +1 -1
- package/dist/native-bridge.d.ts +8 -3
- package/dist/native-bridge.js +29 -12
- package/dist/outcomes.d.ts +13 -1
- package/dist/outcomes.js +21 -20
- package/dist/previous-version.js +23 -35
- package/dist/progress.d.ts +4 -0
- package/dist/progress.js +14 -2
- package/dist/realtime-supervisor.d.ts +4 -1
- package/dist/realtime-supervisor.js +2 -2
- package/dist/schema.js +14 -13
- package/dist/state.d.ts +16 -4
- package/dist/state.js +83 -44
- package/dist/sync-scheduler.d.ts +8 -2
- package/dist/sync-scheduler.js +11 -3
- package/dist/worker-core.js +14 -10
- package/dist/worker-host.d.ts +10 -2
- package/dist/worker-host.js +15 -0
- package/dist/worker-protocol.d.ts +4 -1
- package/package.json +3 -3
- package/src/apply.ts +34 -47
- package/src/blob.ts +7 -24
- package/src/client.ts +699 -553
- package/src/diagnostics.ts +3 -19
- package/src/encryption.ts +15 -40
- package/src/errors.ts +5 -0
- package/src/failed-overlay.ts +39 -29
- package/src/local-purge.ts +1 -1
- package/src/local-rebootstrap-receipt.ts +2 -5
- package/src/local-rebootstrap.ts +1 -2
- package/src/native-bridge.ts +40 -14
- package/src/outcomes.ts +36 -31
- package/src/previous-version.ts +31 -40
- package/src/progress.ts +18 -2
- package/src/realtime-supervisor.ts +7 -3
- package/src/schema.ts +13 -13
- package/src/state.ts +107 -64
- package/src/sync-scheduler.ts +17 -5
- package/src/worker-core.ts +14 -18
- package/src/worker-host.ts +30 -1
- package/src/worker-protocol.ts +4 -0
package/src/diagnostics.ts
CHANGED
|
@@ -6,6 +6,7 @@
|
|
|
6
6
|
* diagnostic prose.
|
|
7
7
|
*/
|
|
8
8
|
import type { SecurityLifecycle } from './client';
|
|
9
|
+
import { ChangeEmitter } from './invalidation';
|
|
9
10
|
|
|
10
11
|
export const CLIENT_DIAGNOSTICS_VERSION = 2 as const;
|
|
11
12
|
export const MAX_DIAGNOSTIC_DOMAINS = 256;
|
|
@@ -198,26 +199,9 @@ export type ClientDiagnosticsListener = (
|
|
|
198
199
|
snapshot: ClientDiagnosticsSnapshot,
|
|
199
200
|
) => void;
|
|
200
201
|
|
|
201
|
-
export class ClientDiagnosticsEmitter {
|
|
202
|
-
readonly #listeners = new Set<ClientDiagnosticsListener>();
|
|
203
|
-
|
|
202
|
+
export class ClientDiagnosticsEmitter extends ChangeEmitter<ClientDiagnosticsSnapshot> {
|
|
204
203
|
get observed(): boolean {
|
|
205
|
-
return this
|
|
206
|
-
}
|
|
207
|
-
|
|
208
|
-
on(listener: ClientDiagnosticsListener): () => void {
|
|
209
|
-
this.#listeners.add(listener);
|
|
210
|
-
return () => this.#listeners.delete(listener);
|
|
211
|
-
}
|
|
212
|
-
|
|
213
|
-
emit(snapshot: ClientDiagnosticsSnapshot): void {
|
|
214
|
-
for (const listener of this.#listeners) {
|
|
215
|
-
try {
|
|
216
|
-
listener(snapshot);
|
|
217
|
-
} catch {
|
|
218
|
-
// Diagnostics observers cannot alter sync correctness.
|
|
219
|
-
}
|
|
220
|
-
}
|
|
204
|
+
return this.size > 0;
|
|
221
205
|
}
|
|
222
206
|
}
|
|
223
207
|
|
package/src/encryption.ts
CHANGED
|
@@ -116,23 +116,16 @@ function encryptionKeyId(
|
|
|
116
116
|
}
|
|
117
117
|
const selectorColumn = config.keyIdColumns?.[table.name];
|
|
118
118
|
if (selectorColumn === undefined) return table.name;
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
}
|
|
127
|
-
if (table.columns[index]?.encrypted === true) {
|
|
128
|
-
throw new EncryptError(
|
|
129
|
-
`encryption key-id column ${JSON.stringify(selectorColumn)} on table ${JSON.stringify(table.name)} must not be encrypted`,
|
|
130
|
-
);
|
|
131
|
-
}
|
|
132
|
-
const selected = values[index];
|
|
119
|
+
// The column must exist, stay plaintext, and hold a non-empty string.
|
|
120
|
+
const selected =
|
|
121
|
+
values[
|
|
122
|
+
table.columns.findIndex(
|
|
123
|
+
(column) => column.name === selectorColumn && column.encrypted !== true,
|
|
124
|
+
)
|
|
125
|
+
];
|
|
133
126
|
if (typeof selected !== 'string' || selected.length === 0) {
|
|
134
127
|
throw new EncryptError(
|
|
135
|
-
`encryption key-id column ${JSON.stringify(selectorColumn)} on table ${JSON.stringify(table.name)} must
|
|
128
|
+
`encryption key-id column ${JSON.stringify(selectorColumn)} on table ${JSON.stringify(table.name)} must be a plaintext column holding a non-empty string`,
|
|
136
129
|
);
|
|
137
130
|
}
|
|
138
131
|
return selected;
|
|
@@ -158,20 +151,11 @@ export async function encryptRowValues<T extends RowValue | undefined>(
|
|
|
158
151
|
values: readonly T[],
|
|
159
152
|
storedKeyId?: string,
|
|
160
153
|
): Promise<T[]> {
|
|
161
|
-
if (!table.hasEncryptedColumns) return values.slice();
|
|
162
154
|
const out = values.slice();
|
|
163
155
|
// Sparse semantics: absent (undefined) and NULL columns are never
|
|
164
156
|
// re-encrypted, so a patch that presents no encrypted value needs no key.
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
if (table.columns[i]?.encrypted !== true) continue;
|
|
168
|
-
const value = out[i];
|
|
169
|
-
if (value !== undefined && value !== null) {
|
|
170
|
-
hasPresentEncrypted = true;
|
|
171
|
-
break;
|
|
172
|
-
}
|
|
173
|
-
}
|
|
174
|
-
if (!hasPresentEncrypted) return out;
|
|
157
|
+
if (!table.columns.some((column, i) => column.encrypted && out[i] != null))
|
|
158
|
+
return out;
|
|
175
159
|
if (config === undefined) {
|
|
176
160
|
throw new EncryptError('encrypted columns need an encryption config');
|
|
177
161
|
}
|
|
@@ -279,7 +263,6 @@ export async function decryptRowValues(
|
|
|
279
263
|
table: CompiledClientTable,
|
|
280
264
|
values: readonly RowValue[],
|
|
281
265
|
): Promise<RowValue[]> {
|
|
282
|
-
if (!table.hasEncryptedColumns) return values.slice();
|
|
283
266
|
const out = values.slice();
|
|
284
267
|
for (let i = 0; i < table.columns.length; i++) {
|
|
285
268
|
const column = table.columns[i];
|
|
@@ -294,20 +277,12 @@ export async function decryptRowValues(
|
|
|
294
277
|
if (config === undefined) {
|
|
295
278
|
throw new DecryptError('encrypted columns need an encryption config');
|
|
296
279
|
}
|
|
297
|
-
out[i] =
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
table.name,
|
|
303
|
-
),
|
|
280
|
+
out[i] = await decryptValue(
|
|
281
|
+
declaredTypeOf(column),
|
|
282
|
+
value,
|
|
283
|
+
config.keyProvider,
|
|
284
|
+
table.name,
|
|
304
285
|
);
|
|
305
286
|
}
|
|
306
287
|
return out;
|
|
307
288
|
}
|
|
308
|
-
|
|
309
|
-
// decryptValue already returns a PlainValue; RowValue is a superset, so this
|
|
310
|
-
// is just the type widening (kept explicit for clarity at the seam).
|
|
311
|
-
function deserializeGuard(value: PlainValue): RowValue {
|
|
312
|
-
return value;
|
|
313
|
-
}
|
package/src/errors.ts
CHANGED
|
@@ -57,6 +57,11 @@ export class ClientSyncError extends Error {
|
|
|
57
57
|
}
|
|
58
58
|
}
|
|
59
59
|
|
|
60
|
+
/** `sync.local_corrupt`: persisted local state this client cannot read. */
|
|
61
|
+
export function localStateCorrupt(message: string): ClientSyncError {
|
|
62
|
+
return new ClientSyncError('sync.local_corrupt', message);
|
|
63
|
+
}
|
|
64
|
+
|
|
60
65
|
/** Shared invalid-request construction for client validators and transport guards. */
|
|
61
66
|
export function invalidRequest(
|
|
62
67
|
message: string,
|
package/src/failed-overlay.ts
CHANGED
|
@@ -2,7 +2,7 @@ import { hasUniqueIndex } from './schema';
|
|
|
2
2
|
import { OUTCOMES_TABLE } from './outcomes';
|
|
3
3
|
import { OUTBOX_IMAGES } from './outbox';
|
|
4
4
|
export const RETAINED_ROWS = '_syncular_failed_rows';
|
|
5
|
-
import {
|
|
5
|
+
import { localStateCorrupt } from './errors';
|
|
6
6
|
import type { ClientDatabase } from './database';
|
|
7
7
|
import type {
|
|
8
8
|
CompiledClientSchema,
|
|
@@ -29,7 +29,7 @@ import type {
|
|
|
29
29
|
import { deleteLocalRow, upsertLocalRow } from './apply';
|
|
30
30
|
|
|
31
31
|
/** Protected failure state. The server base advances independently of intent. */
|
|
32
|
-
const SET_UNIQUE_CONFLICTS = `UPDATE ${RETAINED_ROWS} SET unique_conflicts=? WHERE
|
|
32
|
+
const SET_UNIQUE_CONFLICTS = `UPDATE ${RETAINED_ROWS} SET unique_conflicts=? WHERE rowid=?`;
|
|
33
33
|
|
|
34
34
|
export function ensureFailedOverlaySchema(db: ClientDatabase): void {
|
|
35
35
|
db.exec(
|
|
@@ -44,24 +44,42 @@ export function ensureFailedOverlaySchema(db: ClientDatabase): void {
|
|
|
44
44
|
);
|
|
45
45
|
}
|
|
46
46
|
|
|
47
|
+
/**
|
|
48
|
+
* Server writes, after they are stored: each `written` row replaces the base
|
|
49
|
+
* of its key's retained rows (`undefined`: deleted), and the table's retained
|
|
50
|
+
* intents re-read their unique conflicts with the written keys. A written row
|
|
51
|
+
* without a retained row costs no statement.
|
|
52
|
+
*/
|
|
47
53
|
export function retainedBaseWrite(
|
|
48
54
|
db: ClientDatabase,
|
|
49
55
|
table: CompiledClientTable,
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
56
|
+
written: ReadonlyMap<
|
|
57
|
+
string,
|
|
58
|
+
readonly [readonly RowValue[], number] | undefined
|
|
59
|
+
>,
|
|
53
60
|
): void {
|
|
54
|
-
|
|
55
|
-
values === undefined ? null : JSON.stringify(values),
|
|
56
|
-
version ?? null,
|
|
57
|
-
table.name,
|
|
58
|
-
rowId,
|
|
59
|
-
]);
|
|
60
|
-
if (!hasUniqueIndex(table)) return;
|
|
61
|
+
if (!written.size) return;
|
|
61
62
|
for (const retained of db.query(
|
|
62
|
-
`SELECT
|
|
63
|
+
`SELECT rowid AS r,* FROM ${RETAINED_ROWS} WHERE tbl=?`,
|
|
63
64
|
[table.name],
|
|
64
65
|
)) {
|
|
66
|
+
const base = written.get(retained.id as string);
|
|
67
|
+
if (written.has(retained.id as string))
|
|
68
|
+
db.exec(`UPDATE ${RETAINED_ROWS} SET base=?,version=? WHERE rowid=?`, [
|
|
69
|
+
base
|
|
70
|
+
? JSON.stringify(
|
|
71
|
+
Object.fromEntries(
|
|
72
|
+
table.columns.map((column, index) => [
|
|
73
|
+
column.name,
|
|
74
|
+
rowValueToJson(base[0][index] ?? null),
|
|
75
|
+
]),
|
|
76
|
+
),
|
|
77
|
+
)
|
|
78
|
+
: null,
|
|
79
|
+
base?.[1] ?? null,
|
|
80
|
+
retained.r as number,
|
|
81
|
+
]);
|
|
82
|
+
if (!hasUniqueIndex(table) || retained.commit_seq !== null) continue;
|
|
65
83
|
const prior: readonly (Omit<
|
|
66
84
|
NonNullable<RetainedCommitRow['uniqueConflicts']>[number],
|
|
67
85
|
'serverRow'
|
|
@@ -69,14 +87,14 @@ export function retainedBaseWrite(
|
|
|
69
87
|
retained.unique_conflicts === null
|
|
70
88
|
? []
|
|
71
89
|
: JSON.parse(retained.unique_conflicts as string);
|
|
72
|
-
const conflicts = prior.filter((conflict) => conflict.rowId
|
|
73
|
-
if (
|
|
90
|
+
const conflicts = prior.filter((conflict) => !written.has(conflict.rowId));
|
|
91
|
+
if (retained.intent !== null) {
|
|
74
92
|
const intent: Record<string, JsonRowValue> = JSON.parse(
|
|
75
93
|
retained.intent as string,
|
|
76
94
|
);
|
|
77
95
|
conflicts.push(
|
|
78
96
|
...uniqueConflicts(db, table, mapRowValues(intent, jsonToRowValue))
|
|
79
|
-
.filter((conflict) => conflict.rowId
|
|
97
|
+
.filter((conflict) => written.has(conflict.rowId))
|
|
80
98
|
.map((conflict) => ({
|
|
81
99
|
...conflict,
|
|
82
100
|
serverRow: mapRowValues(conflict.serverRow, rowValueToJson),
|
|
@@ -93,8 +111,7 @@ export function retainedBaseWrite(
|
|
|
93
111
|
),
|
|
94
112
|
)
|
|
95
113
|
: null,
|
|
96
|
-
retained.
|
|
97
|
-
Number(retained.idx),
|
|
114
|
+
retained.r as number,
|
|
98
115
|
]);
|
|
99
116
|
}
|
|
100
117
|
}
|
|
@@ -113,11 +130,7 @@ export function retainFailedRows(
|
|
|
113
130
|
operation.op === 'upsert'
|
|
114
131
|
? { ...image?.values, ...operation.values }
|
|
115
132
|
: undefined;
|
|
116
|
-
if (!image)
|
|
117
|
-
throw new ClientSyncError(
|
|
118
|
-
'sync.local_corrupt',
|
|
119
|
-
'missing intent before-image',
|
|
120
|
-
);
|
|
133
|
+
if (!image) throw localStateCorrupt('missing intent before-image');
|
|
121
134
|
db.exec(
|
|
122
135
|
`INSERT INTO ${RETAINED_ROWS}(commit_id,idx,tbl,id,at,op,intent,base,version,commit_seq)VALUES(?,?,?,?,?,?,?,?,?,?)`,
|
|
123
136
|
[
|
|
@@ -181,7 +194,7 @@ function retainedRows(
|
|
|
181
194
|
// A scope joins through the (tbl, id) index; a scan per applied commit
|
|
182
195
|
// would make a drained batch quadratic.
|
|
183
196
|
return db.query(
|
|
184
|
-
`SELECT
|
|
197
|
+
`SELECT rowid AS r,* FROM ${RETAINED_ROWS} WHERE (?1 IS NULL OR rowid IN(SELECT r.rowid FROM json_each(?1) k JOIN ${RETAINED_ROWS} r ON r.tbl=json_extract(k.value,'$[0]') AND r.id=json_extract(k.value,'$[1]') UNION SELECT r.rowid FROM json_each(?1) k JOIN ${RETAINED_ROWS} r ON json_array_length(k.value)=1 AND r.tbl=json_extract(k.value,'$[0]')))${acknowledged === undefined ? '' : ` AND commit_seq IS${acknowledged ? ' NOT' : ''} NULL`} ORDER BY commit_seq,at,commit_id,idx`,
|
|
185
198
|
[scope ? JSON.stringify(scope) : null],
|
|
186
199
|
);
|
|
187
200
|
}
|
|
@@ -190,7 +203,7 @@ export function restoreFailedBases(
|
|
|
190
203
|
db: ClientDatabase,
|
|
191
204
|
schema: CompiledClientSchema,
|
|
192
205
|
scope?: OverlayScope,
|
|
193
|
-
):
|
|
206
|
+
): void {
|
|
194
207
|
const seen = new Set<string>();
|
|
195
208
|
for (const row of retainedRows(db, scope)) {
|
|
196
209
|
const key = JSON.stringify([row.tbl, row.id]);
|
|
@@ -211,11 +224,9 @@ export function restoreFailedBases(
|
|
|
211
224
|
jsonToRowValue(values[column.name] ?? null),
|
|
212
225
|
),
|
|
213
226
|
(row.version ?? -1) as number,
|
|
214
|
-
false,
|
|
215
227
|
);
|
|
216
228
|
}
|
|
217
229
|
}
|
|
218
|
-
return seen.size > 0;
|
|
219
230
|
}
|
|
220
231
|
|
|
221
232
|
export function failedOverlayCommits(
|
|
@@ -278,8 +289,7 @@ export function failedOverlayCommits(
|
|
|
278
289
|
serverRow: mapRowValues(conflict.serverRow, rowValueToJson),
|
|
279
290
|
})),
|
|
280
291
|
),
|
|
281
|
-
row.
|
|
282
|
-
row.idx as number,
|
|
292
|
+
row.r as number,
|
|
283
293
|
]);
|
|
284
294
|
}
|
|
285
295
|
}
|
package/src/local-purge.ts
CHANGED
|
@@ -15,7 +15,7 @@ const MAX_TARGETS = 64;
|
|
|
15
15
|
const MAX_SELECTORS_PER_TARGET = 8;
|
|
16
16
|
const MAX_VALUES_PER_SELECTOR = 128;
|
|
17
17
|
const MAX_ROUTING_VALUE_LENGTH = 256;
|
|
18
|
-
const CODE_LIKE_VALUE = /^[A-Za-z0-9][A-Za-z0-9._:-]*$/;
|
|
18
|
+
export const CODE_LIKE_VALUE = /^[A-Za-z0-9][A-Za-z0-9._:-]*$/;
|
|
19
19
|
|
|
20
20
|
function compareCodeLike(left: string, right: string): number {
|
|
21
21
|
return left < right ? -1 : left > right ? 1 : 0;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { localStateCorrupt } from './errors';
|
|
2
2
|
|
|
3
3
|
const LEGACY_MARKER = 'v1';
|
|
4
4
|
const RECEIPT_VERSION = 2;
|
|
@@ -14,10 +14,7 @@ export interface LocalDataRebootstrapReceipt {
|
|
|
14
14
|
}
|
|
15
15
|
|
|
16
16
|
function invalidReceipt(): never {
|
|
17
|
-
throw
|
|
18
|
-
'sync.local_corrupt',
|
|
19
|
-
'persisted local rebootstrap receipt is invalid',
|
|
20
|
-
);
|
|
17
|
+
throw localStateCorrupt('persisted local rebootstrap receipt is invalid');
|
|
21
18
|
}
|
|
22
19
|
|
|
23
20
|
function isCount(value: unknown): value is number {
|
package/src/local-rebootstrap.ts
CHANGED
package/src/native-bridge.ts
CHANGED
|
@@ -13,8 +13,10 @@
|
|
|
13
13
|
*/
|
|
14
14
|
import {
|
|
15
15
|
type ClientSnapshotMethods,
|
|
16
|
+
type CommitDelivery,
|
|
16
17
|
type CurrentBaseProof,
|
|
17
18
|
type MutationInput,
|
|
19
|
+
type ReplaceCommitOutcomeInput,
|
|
18
20
|
type PresencePeer,
|
|
19
21
|
type PromiseMethods,
|
|
20
22
|
type QueryReadSpec,
|
|
@@ -25,6 +27,7 @@ import {
|
|
|
25
27
|
type SnapshotReadRequest,
|
|
26
28
|
type SyncClient,
|
|
27
29
|
type SyncClientConfig,
|
|
30
|
+
type SyncIdleOptions,
|
|
28
31
|
type UnitCatchup,
|
|
29
32
|
type WindowState,
|
|
30
33
|
} from './client';
|
|
@@ -72,6 +75,7 @@ import {
|
|
|
72
75
|
type SyncProgressListener,
|
|
73
76
|
} from './progress';
|
|
74
77
|
import type { UnitRecord } from './state';
|
|
78
|
+
import type { OutboxCommit } from './outbox';
|
|
75
79
|
import type { WindowBase } from './window';
|
|
76
80
|
|
|
77
81
|
/** A driver-protocol reply: `{result}` on success or `{error}` on failure. */
|
|
@@ -739,7 +743,7 @@ export abstract class NativeBridgeClient implements PromiseMethods<
|
|
|
739
743
|
sql: spec.sql,
|
|
740
744
|
params: encodeValue(spec.params ?? []),
|
|
741
745
|
coverage: spec.coverage ?? [],
|
|
742
|
-
|
|
746
|
+
owner: spec.owner,
|
|
743
747
|
}),
|
|
744
748
|
)) as {
|
|
745
749
|
revision: string;
|
|
@@ -766,7 +770,7 @@ export abstract class NativeBridgeClient implements PromiseMethods<
|
|
|
766
770
|
coverage: request.coverage ?? [],
|
|
767
771
|
units: request.units ?? [],
|
|
768
772
|
commitIds: request.commitIds ?? [],
|
|
769
|
-
|
|
773
|
+
owner: request.owner,
|
|
770
774
|
})) as {
|
|
771
775
|
revision: string;
|
|
772
776
|
queries: readonly (readonly Record<string, unknown>[])[];
|
|
@@ -995,10 +999,8 @@ export abstract class NativeBridgeClient implements PromiseMethods<
|
|
|
995
999
|
): Promise<string> {
|
|
996
1000
|
const result = (await this.command('uploadBlob', {
|
|
997
1001
|
bytes: encodeValue(bytes),
|
|
998
|
-
|
|
999
|
-
|
|
1000
|
-
: {}),
|
|
1001
|
-
...(options?.name !== undefined ? { name: options.name } : {}),
|
|
1002
|
+
mediaType: options?.mediaType,
|
|
1003
|
+
name: options?.name,
|
|
1002
1004
|
})) as { ref: string };
|
|
1003
1005
|
return result.ref;
|
|
1004
1006
|
}
|
|
@@ -1071,6 +1073,12 @@ export abstract class NativeBridgeClient implements PromiseMethods<
|
|
|
1071
1073
|
return (await this.snapshotRead({ statements: [], units: [id] })).units[0]!;
|
|
1072
1074
|
}
|
|
1073
1075
|
|
|
1076
|
+
/** §7.5: one client commit's delivery status, from the same snapshot read. */
|
|
1077
|
+
async commitDelivery(id: string): Promise<CommitDelivery> {
|
|
1078
|
+
return (await this.snapshotRead({ statements: [], commitIds: [id] }))
|
|
1079
|
+
.deliveries[0]!;
|
|
1080
|
+
}
|
|
1081
|
+
|
|
1074
1082
|
async setWindow(base: WindowBase, units: readonly string[]): Promise<void> {
|
|
1075
1083
|
await this.command('setWindow', { base, units });
|
|
1076
1084
|
}
|
|
@@ -1087,13 +1095,16 @@ export abstract class NativeBridgeClient implements PromiseMethods<
|
|
|
1087
1095
|
return this.command('sync', {});
|
|
1088
1096
|
}
|
|
1089
1097
|
|
|
1098
|
+
/** The Rust core has no §8.4 empty-replica gate: `skipEmpty` is not sent. */
|
|
1090
1099
|
async syncUntilIdle(
|
|
1091
|
-
|
|
1100
|
+
options?: number | SyncIdleOptions,
|
|
1092
1101
|
timeoutMs?: number,
|
|
1093
1102
|
): Promise<unknown> {
|
|
1103
|
+
const maxRounds = typeof options === 'object' ? options.maxRounds : options;
|
|
1104
|
+
if (typeof options === 'object') timeoutMs = options.timeoutMs;
|
|
1094
1105
|
return this.command('syncUntilIdle', {
|
|
1095
|
-
|
|
1096
|
-
|
|
1106
|
+
maxRounds,
|
|
1107
|
+
timeoutMs,
|
|
1097
1108
|
});
|
|
1098
1109
|
}
|
|
1099
1110
|
|
|
@@ -1114,7 +1125,7 @@ export abstract class NativeBridgeClient implements PromiseMethods<
|
|
|
1114
1125
|
clientCommitId: outcome.clientCommitId,
|
|
1115
1126
|
sequence: outcome.sequence,
|
|
1116
1127
|
},
|
|
1117
|
-
|
|
1128
|
+
maxRounds,
|
|
1118
1129
|
})) as CurrentBaseProof;
|
|
1119
1130
|
return proof.proven
|
|
1120
1131
|
? { proven: true, rows: this.#retainedRows(proof.rows) }
|
|
@@ -1164,11 +1175,26 @@ export abstract class NativeBridgeClient implements PromiseMethods<
|
|
|
1164
1175
|
return this.#commitOutcome(result.outcome);
|
|
1165
1176
|
}
|
|
1166
1177
|
|
|
1167
|
-
async
|
|
1168
|
-
|
|
1169
|
-
|
|
1178
|
+
async replaceCommitOutcome({
|
|
1179
|
+
clientCommitId,
|
|
1180
|
+
sequence,
|
|
1181
|
+
replacement,
|
|
1182
|
+
}: ReplaceCommitOutcomeInput): Promise<string> {
|
|
1183
|
+
const result = (await this.command('replaceCommitOutcome', {
|
|
1184
|
+
clientCommitId,
|
|
1185
|
+
sequence,
|
|
1186
|
+
...(replacement === undefined
|
|
1187
|
+
? {}
|
|
1188
|
+
: { replacement: encodeValue(replacement) }),
|
|
1189
|
+
})) as { clientCommitId: string };
|
|
1190
|
+
return result.clientCommitId;
|
|
1191
|
+
}
|
|
1192
|
+
|
|
1193
|
+
async pendingCommits(): Promise<OutboxCommit[]> {
|
|
1194
|
+
const result = (await this.command('pendingCommits', {})) as {
|
|
1195
|
+
commits: OutboxCommit[];
|
|
1170
1196
|
};
|
|
1171
|
-
return result.
|
|
1197
|
+
return result.commits;
|
|
1172
1198
|
}
|
|
1173
1199
|
|
|
1174
1200
|
async presence(scopeKey: string): Promise<readonly PresencePeer[]> {
|
package/src/outcomes.ts
CHANGED
|
@@ -15,7 +15,7 @@ import {
|
|
|
15
15
|
type RowValue,
|
|
16
16
|
} from '@syncular/core';
|
|
17
17
|
import type { ClientDatabase } from './database';
|
|
18
|
-
import {
|
|
18
|
+
import { invalidRequest, localStateCorrupt } from './errors';
|
|
19
19
|
import type { OutboxOperation } from './outbox';
|
|
20
20
|
import {
|
|
21
21
|
isBytesEnvelope,
|
|
@@ -116,9 +116,32 @@ export interface CommitOutcome {
|
|
|
116
116
|
readonly retainedRows?: readonly RetainedCommitRow[];
|
|
117
117
|
readonly resolution: CommitOutcomeResolution;
|
|
118
118
|
readonly resolvedAtMs?: number;
|
|
119
|
+
/**
|
|
120
|
+
* The replacement commit of a `superseded` outcome; on an `active`
|
|
121
|
+
* outcome, the replacement of a pending decision (§7.2.2).
|
|
122
|
+
*/
|
|
119
123
|
readonly replacementClientCommitId?: string;
|
|
120
124
|
}
|
|
121
125
|
|
|
126
|
+
export interface PendingDecision {
|
|
127
|
+
readonly clientCommitId: string;
|
|
128
|
+
readonly sequence: number;
|
|
129
|
+
readonly replacementClientCommitId: string;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** §7.2.2: active outcomes whose replacement waits for a proven base. */
|
|
133
|
+
export function pendingDecisions(db: ClientDatabase): PendingDecision[] {
|
|
134
|
+
return db
|
|
135
|
+
.query(
|
|
136
|
+
`SELECT seq,client_commit_id,replacement_client_commit_id FROM ${OUTCOMES_TABLE} WHERE resolution='active' AND replacement_client_commit_id IS NOT NULL`,
|
|
137
|
+
)
|
|
138
|
+
.map((row) => ({
|
|
139
|
+
clientCommitId: row.client_commit_id as string,
|
|
140
|
+
sequence: row.seq as number,
|
|
141
|
+
replacementClientCommitId: row.replacement_client_commit_id as string,
|
|
142
|
+
}));
|
|
143
|
+
}
|
|
144
|
+
|
|
122
145
|
export interface CommitOutcomeQuery {
|
|
123
146
|
/** Newest-first result cap. Defaults to all retained entries. */
|
|
124
147
|
readonly limit?: number;
|
|
@@ -195,24 +218,20 @@ export function isStoredOperation(value: unknown): value is OutboxOperation {
|
|
|
195
218
|
);
|
|
196
219
|
}
|
|
197
220
|
|
|
221
|
+
function corrupt(): never {
|
|
222
|
+
throw localStateCorrupt('persisted commit outcome is invalid');
|
|
223
|
+
}
|
|
224
|
+
|
|
198
225
|
function decodeResults(raw: string): CommitOperationOutcome[] {
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
'persisted commit outcome is invalid',
|
|
203
|
-
);
|
|
204
|
-
}
|
|
226
|
+
// §6.1 op indexes are i32.
|
|
227
|
+
const badIndex = (index: number) =>
|
|
228
|
+
!Number.isInteger(index) || index < -2147483648 || index > 2147483647;
|
|
205
229
|
const stored = JSON.parse(raw) as StoredCommitOperationOutcome[];
|
|
206
230
|
if (!Array.isArray(stored)) corrupt();
|
|
207
231
|
return stored.map((result) => {
|
|
208
232
|
if (!isRecord(result)) corrupt();
|
|
209
233
|
if (result.status === 'applied') {
|
|
210
|
-
if (
|
|
211
|
-
!Number.isInteger(result.opIndex) ||
|
|
212
|
-
result.opIndex < -2147483648 ||
|
|
213
|
-
result.opIndex > 2147483647
|
|
214
|
-
)
|
|
215
|
-
corrupt();
|
|
234
|
+
if (badIndex(result.opIndex)) corrupt();
|
|
216
235
|
return result;
|
|
217
236
|
}
|
|
218
237
|
if (result.status === 'conflict') {
|
|
@@ -221,9 +240,7 @@ function decodeResults(raw: string): CommitOperationOutcome[] {
|
|
|
221
240
|
!isRecord(conflict) ||
|
|
222
241
|
!isStoredRow(conflict.serverRow) ||
|
|
223
242
|
typeof conflict.clientCommitId !== 'string' ||
|
|
224
|
-
|
|
225
|
-
conflict.opIndex < -2147483648 ||
|
|
226
|
-
conflict.opIndex > 2147483647 ||
|
|
243
|
+
badIndex(conflict.opIndex) ||
|
|
227
244
|
typeof conflict.table !== 'string' ||
|
|
228
245
|
typeof conflict.rowId !== 'string' ||
|
|
229
246
|
typeof conflict.code !== 'string' ||
|
|
@@ -254,9 +271,7 @@ function decodeResults(raw: string): CommitOperationOutcome[] {
|
|
|
254
271
|
if (
|
|
255
272
|
!isRecord(rejection) ||
|
|
256
273
|
typeof rejection.clientCommitId !== 'string' ||
|
|
257
|
-
|
|
258
|
-
rejection.opIndex < -2147483648 ||
|
|
259
|
-
rejection.opIndex > 2147483647 ||
|
|
274
|
+
badIndex(rejection.opIndex) ||
|
|
260
275
|
typeof rejection.code !== 'string' ||
|
|
261
276
|
typeof rejection.message !== 'string' ||
|
|
262
277
|
typeof rejection.retryable !== 'boolean' ||
|
|
@@ -391,12 +406,6 @@ export function persistedCommitOutcome(
|
|
|
391
406
|
): CommitOutcome | undefined {
|
|
392
407
|
const row = outcomeRow(db, clientCommitId);
|
|
393
408
|
if (row === undefined) return undefined;
|
|
394
|
-
function corrupt(): never {
|
|
395
|
-
throw new ClientSyncError(
|
|
396
|
-
'sync.local_corrupt',
|
|
397
|
-
'persisted commit outcome is invalid',
|
|
398
|
-
);
|
|
399
|
-
}
|
|
400
409
|
const status = row.status;
|
|
401
410
|
const resolution = row.resolution;
|
|
402
411
|
if (
|
|
@@ -488,17 +497,13 @@ export function persistCommitOutcomeResolution(
|
|
|
488
497
|
|
|
489
498
|
/**
|
|
490
499
|
* Bound journal growth without deleting active failures. If active failures
|
|
491
|
-
* alone exceed the cap the journal intentionally remains over-capacity.
|
|
500
|
+
* alone exceed the cap the journal intentionally remains over-capacity. The
|
|
501
|
+
* client constructor validates `maxEntries`.
|
|
492
502
|
*/
|
|
493
503
|
export function pruneCommitOutcomes(
|
|
494
504
|
db: ClientDatabase,
|
|
495
505
|
maxEntries: number,
|
|
496
506
|
): number {
|
|
497
|
-
if (!Number.isSafeInteger(maxEntries) || maxEntries < 1) {
|
|
498
|
-
throw invalidRequest(
|
|
499
|
-
'outcome retention maxEntries must be a positive safe integer',
|
|
500
|
-
);
|
|
501
|
-
}
|
|
502
507
|
const count = db.query(`SELECT COUNT(*) AS count FROM ${OUTCOMES_TABLE}`)[0]
|
|
503
508
|
?.count as number | undefined;
|
|
504
509
|
const excess = Math.max(0, (count ?? 0) - maxEntries);
|