@myfield/sdk 0.9.0 → 0.9.1
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/CHANGELOG.md +5 -0
- package/README.md +2 -2
- package/dist/index.js +230 -60
- package/docs/API.md +2 -1
- package/docs/BUCKET-SPEC.md +28 -13
- package/package.json +1 -1
- package/src/bucket/client.ts +74 -36
- package/src/bucket/format.ts +67 -18
- package/src/bucket/transport.ts +45 -5
- package/src/facade.ts +98 -16
package/src/bucket/client.ts
CHANGED
|
@@ -12,6 +12,7 @@ import {
|
|
|
12
12
|
emptyLwwMapDoc,
|
|
13
13
|
encodePayloadDoc,
|
|
14
14
|
lwwMapDocsEqual,
|
|
15
|
+
lwwMapLatestTs,
|
|
15
16
|
lwwMapValues,
|
|
16
17
|
LwwClock,
|
|
17
18
|
mergeLwwMapDocs,
|
|
@@ -29,6 +30,14 @@ export type BucketTransportLike = {
|
|
|
29
30
|
pullHead(wireObjectId: string): Promise<TransportHeadResult>;
|
|
30
31
|
pullPayload(wireObjectId: string, versionId: string): Promise<TransportPayloadResult>;
|
|
31
32
|
push(wireObjectId: string, plaintext: Uint8Array, expectedHeadVersionId: string | null): Promise<TransportPushResult>;
|
|
33
|
+
listHeads?(): Promise<Map<string, string>>;
|
|
34
|
+
};
|
|
35
|
+
|
|
36
|
+
export type ChangeSource = "local" | "remote";
|
|
37
|
+
|
|
38
|
+
export type SyncPassOptions = {
|
|
39
|
+
skipWireIds?: Iterable<string>;
|
|
40
|
+
resolveUnknown?: (wireObjectId: string, versionId: string) => Promise<string | null>;
|
|
32
41
|
};
|
|
33
42
|
|
|
34
43
|
export type BucketClientOptions = {
|
|
@@ -40,7 +49,9 @@ export type BucketClientOptions = {
|
|
|
40
49
|
mergeStrategyFor?: (appObjectId: string) => MergeStrategy;
|
|
41
50
|
maxCasAttempts?: number;
|
|
42
51
|
pushDebounceMs?: number;
|
|
43
|
-
|
|
52
|
+
localOnlyObjectIds?: Iterable<string>;
|
|
53
|
+
validateRemote?: (appObjectId: string, doc: PayloadDoc) => void;
|
|
54
|
+
onChange?: (appObjectId: string, source: ChangeSource) => void;
|
|
44
55
|
onSyncError?: (appObjectId: string | null, error: unknown) => void;
|
|
45
56
|
};
|
|
46
57
|
|
|
@@ -66,13 +77,17 @@ export class BucketClient {
|
|
|
66
77
|
private readonly maxCasAttempts: number;
|
|
67
78
|
private readonly pushDebounceMs: number;
|
|
68
79
|
private readonly maxEncodedObjectBytes = DEFAULT_MAX_ENCODED_OBJECT_BYTES;
|
|
69
|
-
private readonly
|
|
80
|
+
private readonly localOnly: Set<string>;
|
|
81
|
+
private readonly validateRemote?: (appObjectId: string, doc: PayloadDoc) => void;
|
|
82
|
+
private readonly onChange?: (appObjectId: string, source: ChangeSource) => void;
|
|
70
83
|
private readonly onSyncError?: (appObjectId: string | null, error: unknown) => void;
|
|
71
84
|
private readonly clock = new LwwClock();
|
|
72
85
|
private readonly inFlightSync = new Map<string, Promise<boolean>>();
|
|
73
86
|
private readonly objectLocks = new Map<string, Promise<void>>();
|
|
74
87
|
private readonly pendingPushTimers = new Map<string, ReturnType<typeof setTimeout>>();
|
|
75
88
|
private readonly watched = new Set<string>();
|
|
89
|
+
// Avoids re-downloading an unresolvable object until its head changes.
|
|
90
|
+
private readonly unresolved = new Map<string, string>();
|
|
76
91
|
private triggerCleanup: (() => void) | null = null;
|
|
77
92
|
private disposed = false;
|
|
78
93
|
|
|
@@ -85,6 +100,8 @@ export class BucketClient {
|
|
|
85
100
|
this.mergeStrategyFor = options.mergeStrategyFor || (() => ({ kind: "lww-map" }));
|
|
86
101
|
this.maxCasAttempts = options.maxCasAttempts ?? DEFAULT_MAX_CAS_ATTEMPTS;
|
|
87
102
|
this.pushDebounceMs = options.pushDebounceMs ?? DEFAULT_PUSH_DEBOUNCE_MS;
|
|
103
|
+
this.localOnly = new Set(options.localOnlyObjectIds || []);
|
|
104
|
+
this.validateRemote = options.validateRemote;
|
|
88
105
|
this.onChange = options.onChange;
|
|
89
106
|
this.onSyncError = options.onSyncError;
|
|
90
107
|
}
|
|
@@ -103,6 +120,11 @@ export class BucketClient {
|
|
|
103
120
|
return record.doc.data;
|
|
104
121
|
}
|
|
105
122
|
|
|
123
|
+
async lastModified(appObjectId: string): Promise<number | null> {
|
|
124
|
+
const record = await this.readRecord(appObjectId);
|
|
125
|
+
return record && record.doc.t === "lww-map" ? lwwMapLatestTs(record.doc) : null;
|
|
126
|
+
}
|
|
127
|
+
|
|
106
128
|
async knownObjectIds(): Promise<string[]> {
|
|
107
129
|
const keys = await this.storage.keys(`${this.prefix}:obj:`);
|
|
108
130
|
return keys.map((key) => decodeURIComponent(key.slice(`${this.prefix}:obj:`.length)));
|
|
@@ -142,7 +164,7 @@ export class BucketClient {
|
|
|
142
164
|
dirty: true,
|
|
143
165
|
});
|
|
144
166
|
this.schedulePush(appObjectId);
|
|
145
|
-
this.onChange?.(appObjectId);
|
|
167
|
+
this.onChange?.(appObjectId, "local");
|
|
146
168
|
return lwwMapValues(nextDoc);
|
|
147
169
|
});
|
|
148
170
|
}
|
|
@@ -159,7 +181,7 @@ export class BucketClient {
|
|
|
159
181
|
dirty: true,
|
|
160
182
|
});
|
|
161
183
|
this.schedulePush(appObjectId);
|
|
162
|
-
this.onChange?.(appObjectId);
|
|
184
|
+
this.onChange?.(appObjectId, "local");
|
|
163
185
|
});
|
|
164
186
|
}
|
|
165
187
|
|
|
@@ -186,28 +208,49 @@ export class BucketClient {
|
|
|
186
208
|
await this.syncObjects(ids);
|
|
187
209
|
}
|
|
188
210
|
|
|
189
|
-
async
|
|
190
|
-
|
|
191
|
-
const
|
|
192
|
-
const
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
const
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
if (
|
|
203
|
-
|
|
211
|
+
async syncPass(options: SyncPassOptions = {}): Promise<void> {
|
|
212
|
+
if (!this.transport.listHeads) throw new Error("transport does not list current heads");
|
|
213
|
+
const heads = await this.transport.listHeads();
|
|
214
|
+
for (const wireObjectId of options.skipWireIds || []) heads.delete(wireObjectId);
|
|
215
|
+
const known = new Map<string, string>();
|
|
216
|
+
const ids = new Set([...this.watched].filter((id) => !this.localOnly.has(id)));
|
|
217
|
+
for (const id of await this.knownObjectIds()) {
|
|
218
|
+
if (this.localOnly.has(id)) continue;
|
|
219
|
+
const record = await this.readRecord(id);
|
|
220
|
+
if (!record) continue;
|
|
221
|
+
const wireObjectId = await this.wireId(id);
|
|
222
|
+
known.set(wireObjectId, id);
|
|
223
|
+
const head = heads.get(wireObjectId);
|
|
224
|
+
if (record.dirty || head === undefined || head !== record.remoteVersionId) ids.add(id);
|
|
225
|
+
}
|
|
226
|
+
for (const [wireObjectId, versionId] of heads) {
|
|
227
|
+
if (known.has(wireObjectId) || !options.resolveUnknown || this.unresolved.get(wireObjectId) === versionId) continue;
|
|
228
|
+
try {
|
|
229
|
+
const id = await options.resolveUnknown(wireObjectId, versionId);
|
|
230
|
+
if (id && !this.localOnly.has(id) && (await this.wireId(id)) === wireObjectId) {
|
|
231
|
+
this.unresolved.delete(wireObjectId);
|
|
232
|
+
ids.add(id);
|
|
233
|
+
} else {
|
|
234
|
+
this.unresolved.set(wireObjectId, versionId);
|
|
235
|
+
}
|
|
236
|
+
} catch (error) {
|
|
237
|
+
this.onSyncError?.(null, error);
|
|
204
238
|
}
|
|
205
239
|
}
|
|
206
|
-
const ids = new Set([...this.watched, ...dirtyIdsBefore, ...changedIds]);
|
|
207
|
-
if (indexObjectId) ids.delete(indexObjectId);
|
|
208
240
|
await this.syncObjects(ids);
|
|
209
241
|
}
|
|
210
242
|
|
|
243
|
+
async pullDoc(wireObjectId: string, versionId: string): Promise<PayloadDoc | null> {
|
|
244
|
+
const payload = await this.transport.pullPayload(wireObjectId, versionId);
|
|
245
|
+
return payload.found ? decodePayloadDoc(payload.plaintext) : null;
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
async pullRemoteDoc(appObjectId: string): Promise<PayloadDoc | null> {
|
|
249
|
+
const wireObjectId = await this.wireId(appObjectId);
|
|
250
|
+
const head = await this.transport.pullHead(wireObjectId);
|
|
251
|
+
return head.found ? this.pullDoc(wireObjectId, head.versionId) : null;
|
|
252
|
+
}
|
|
253
|
+
|
|
211
254
|
watch(appObjectIds: Iterable<string>): void {
|
|
212
255
|
for (const id of appObjectIds) this.watched.add(id);
|
|
213
256
|
}
|
|
@@ -215,10 +258,11 @@ export class BucketClient {
|
|
|
215
258
|
// Sync-trigger model: launch (start itself) and a timer fallback.
|
|
216
259
|
// Browser/app lifecycle triggers are owned by the app; post-write pushes
|
|
217
260
|
// are scheduled by setFields/setData.
|
|
218
|
-
start(options
|
|
261
|
+
start(options: { intervalMs?: number; run: () => Promise<void> }): void {
|
|
219
262
|
if (this.triggerCleanup || this.disposed) return;
|
|
220
|
-
const
|
|
221
|
-
const
|
|
263
|
+
const run = options.run;
|
|
264
|
+
const kick = () => void run().catch((error) => this.onSyncError?.(null, error));
|
|
265
|
+
const intervalMs = options.intervalMs ?? DEFAULT_SYNC_INTERVAL_MS;
|
|
222
266
|
const timer = intervalMs > 0 ? setInterval(kick, intervalMs) : null;
|
|
223
267
|
this.triggerCleanup = () => {
|
|
224
268
|
if (timer) clearInterval(timer);
|
|
@@ -253,7 +297,7 @@ export class BucketClient {
|
|
|
253
297
|
// ---- internals ---------------------------------------------------------
|
|
254
298
|
|
|
255
299
|
private schedulePush(appObjectId: string): void {
|
|
256
|
-
if (this.disposed) return;
|
|
300
|
+
if (this.disposed || this.localOnly.has(appObjectId)) return;
|
|
257
301
|
const existing = this.pendingPushTimers.get(appObjectId);
|
|
258
302
|
if (existing) clearTimeout(existing);
|
|
259
303
|
this.pendingPushTimers.set(
|
|
@@ -266,6 +310,7 @@ export class BucketClient {
|
|
|
266
310
|
}
|
|
267
311
|
|
|
268
312
|
private async performSync(appObjectId: string): Promise<boolean> {
|
|
313
|
+
if (this.localOnly.has(appObjectId)) return false;
|
|
269
314
|
const wireObjectId = await this.wireId(appObjectId);
|
|
270
315
|
let remoteChangedLocal = false;
|
|
271
316
|
for (let attempt = 0; attempt < this.maxCasAttempts; attempt += 1) {
|
|
@@ -293,6 +338,7 @@ export class BucketClient {
|
|
|
293
338
|
const payload = await this.transport.pullPayload(wireObjectId, head.versionId);
|
|
294
339
|
if (!payload.found) return "retry";
|
|
295
340
|
const remoteDoc = decodePayloadDoc(payload.plaintext);
|
|
341
|
+
this.validateRemote?.(appObjectId, remoteDoc);
|
|
296
342
|
const merged = record ? this.merge(appObjectId, record.doc, remoteDoc) : remoteDoc;
|
|
297
343
|
const localViewChanged = !record || !docsEqual(merged, record.doc);
|
|
298
344
|
const remoteNeedsUpdate = !docsEqual(merged, remoteDoc);
|
|
@@ -303,7 +349,7 @@ export class BucketClient {
|
|
|
303
349
|
await this.writeRecord(appObjectId, { v: 1, doc: merged, remoteVersionId: head.versionId, dirty: false });
|
|
304
350
|
if (localViewChanged) {
|
|
305
351
|
remoteChangedLocal = true;
|
|
306
|
-
this.onChange?.(appObjectId);
|
|
352
|
+
this.onChange?.(appObjectId, "remote");
|
|
307
353
|
}
|
|
308
354
|
return remoteChangedLocal;
|
|
309
355
|
}
|
|
@@ -313,7 +359,7 @@ export class BucketClient {
|
|
|
313
359
|
await this.writeRecord(appObjectId, { v: 1, doc: merged, remoteVersionId: result.versionId, dirty: false });
|
|
314
360
|
if (localViewChanged) {
|
|
315
361
|
remoteChangedLocal = true;
|
|
316
|
-
this.onChange?.(appObjectId);
|
|
362
|
+
this.onChange?.(appObjectId, "remote");
|
|
317
363
|
}
|
|
318
364
|
return remoteChangedLocal;
|
|
319
365
|
}
|
|
@@ -342,17 +388,13 @@ export class BucketClient {
|
|
|
342
388
|
async dirtyObjectIds(): Promise<string[]> {
|
|
343
389
|
const ids: string[] = [];
|
|
344
390
|
for (const id of await this.knownObjectIds()) {
|
|
391
|
+
if (this.localOnly.has(id)) continue;
|
|
345
392
|
const record = await this.readRecord(id);
|
|
346
393
|
if (record?.dirty) ids.push(id);
|
|
347
394
|
}
|
|
348
395
|
return ids;
|
|
349
396
|
}
|
|
350
397
|
|
|
351
|
-
private async indexFields(indexObjectId: string): Promise<Record<string, unknown>> {
|
|
352
|
-
const record = await this.readRecord(indexObjectId);
|
|
353
|
-
return record?.doc.t === "lww-map" ? lwwMapValues(record.doc) : {};
|
|
354
|
-
}
|
|
355
|
-
|
|
356
398
|
private async readRecord(appObjectId: string): Promise<LocalObjectRecord | null> {
|
|
357
399
|
const record = await this.storage.get<LocalObjectRecord>(this.recordKey(appObjectId));
|
|
358
400
|
if (!record || record.v !== 1 || !record.doc) return null;
|
|
@@ -377,7 +419,3 @@ function docsEqual(a: PayloadDoc, b: PayloadDoc): boolean {
|
|
|
377
419
|
return false;
|
|
378
420
|
}
|
|
379
421
|
|
|
380
|
-
function diffIndexObjectIds(before: Record<string, unknown>, after: Record<string, unknown>): string[] {
|
|
381
|
-
const ids = new Set([...Object.keys(before), ...Object.keys(after)]);
|
|
382
|
-
return [...ids].filter((id) => JSON.stringify(before[id]) !== JSON.stringify(after[id]));
|
|
383
|
-
}
|
package/src/bucket/format.ts
CHANGED
|
@@ -6,6 +6,7 @@
|
|
|
6
6
|
// Document body:
|
|
7
7
|
// { t: "lww-map", fields: { name: { v, ts, actor } }, tombstones: { name: { ts, actor } } }
|
|
8
8
|
// or { t: "opaque", data: <arbitrary JSON> } for custom merge strategies.
|
|
9
|
+
// Unknown top-level and entry keys are kept (BUCKET-SPEC merge steps 4-5).
|
|
9
10
|
// Binary typed field values are represented in the JSON header as part references
|
|
10
11
|
// and carried as raw bytes in the binary parts section.
|
|
11
12
|
|
|
@@ -23,15 +24,18 @@ const HEADER_LENGTH_BYTES = 4;
|
|
|
23
24
|
const PART_LENGTH_BYTES = 4;
|
|
24
25
|
const BINARY_PART_MARKER = "binary-part-v1";
|
|
25
26
|
|
|
26
|
-
export type LwwFieldEntry = { v: unknown; ts: number; actor: string };
|
|
27
|
-
export type LwwTombstone = { ts: number; actor: string };
|
|
27
|
+
export type LwwFieldEntry = { v: unknown; ts: number; actor: string; [extra: string]: unknown };
|
|
28
|
+
export type LwwTombstone = { ts: number; actor: string; [extra: string]: unknown };
|
|
28
29
|
|
|
29
30
|
export type LwwMapDoc = {
|
|
30
31
|
t: "lww-map";
|
|
31
32
|
fields: Record<string, LwwFieldEntry>;
|
|
32
33
|
tombstones: Record<string, LwwTombstone>;
|
|
34
|
+
ext?: Record<string, unknown>;
|
|
33
35
|
};
|
|
34
36
|
|
|
37
|
+
const LWW_MAP_KEYS = new Set(["t", "fields", "tombstones"]);
|
|
38
|
+
|
|
35
39
|
export type OpaqueDoc = { t: "opaque"; data: unknown };
|
|
36
40
|
|
|
37
41
|
export type PayloadDoc = LwwMapDoc | OpaqueDoc;
|
|
@@ -42,7 +46,8 @@ export function emptyLwwMapDoc(): LwwMapDoc {
|
|
|
42
46
|
|
|
43
47
|
export function encodePayloadDoc(doc: PayloadDoc): Uint8Array {
|
|
44
48
|
const parts: Uint8Array[] = [];
|
|
45
|
-
const
|
|
49
|
+
const body = doc.t === "lww-map" ? { ...(doc.ext || {}), t: doc.t, fields: doc.fields, tombstones: doc.tombstones } : doc;
|
|
50
|
+
const header = utf8Encode(JSON.stringify(encodeHeaderValue(body, parts)));
|
|
46
51
|
let totalLength = 1 + HEADER_LENGTH_BYTES + header.byteLength;
|
|
47
52
|
for (const part of parts) totalLength += PART_LENGTH_BYTES + part.byteLength;
|
|
48
53
|
const out = new Uint8Array(totalLength);
|
|
@@ -93,7 +98,13 @@ function parsePayloadDoc(parsed: unknown): PayloadDoc {
|
|
|
93
98
|
for (const entry of Object.values(doc.tombstones)) {
|
|
94
99
|
if (!isLwwTombstone(entry)) throw new Error("invalid lww-map tombstone");
|
|
95
100
|
}
|
|
96
|
-
|
|
101
|
+
const ext = Object.fromEntries(Object.entries(doc).filter(([key]) => !LWW_MAP_KEYS.has(key)));
|
|
102
|
+
return {
|
|
103
|
+
t: "lww-map",
|
|
104
|
+
fields: doc.fields as Record<string, LwwFieldEntry>,
|
|
105
|
+
tombstones: doc.tombstones as Record<string, LwwTombstone>,
|
|
106
|
+
...(Object.keys(ext).length ? { ext } : {}),
|
|
107
|
+
};
|
|
97
108
|
}
|
|
98
109
|
if (docRoot?.t === "opaque") return { t: "opaque", data: (docRoot as OpaqueDoc).data };
|
|
99
110
|
throw new Error("unknown payload doc type");
|
|
@@ -106,13 +117,20 @@ function wins(aTs: number, aActor: string, bTs: number, bActor: string): boolean
|
|
|
106
117
|
return aActor > bActor;
|
|
107
118
|
}
|
|
108
119
|
|
|
109
|
-
//
|
|
110
|
-
//
|
|
111
|
-
// on a full (ts, actor) tie the serialized value breaks the tie.
|
|
120
|
+
// Full (ts, actor) ties (malformed input, or an older SDK that dropped extra
|
|
121
|
+
// keys) fall back to the value, then the whole entry, to stay deterministic.
|
|
112
122
|
function fieldEntryWins(a: LwwFieldEntry, b: LwwFieldEntry): boolean {
|
|
113
123
|
if (a.ts !== b.ts) return a.ts > b.ts;
|
|
114
124
|
if (a.actor !== b.actor) return a.actor > b.actor;
|
|
115
|
-
|
|
125
|
+
const aValue = JSON.stringify(fieldValueToCanonicalJson(a.v));
|
|
126
|
+
const bValue = JSON.stringify(fieldValueToCanonicalJson(b.v));
|
|
127
|
+
if (aValue !== bValue) return aValue > bValue;
|
|
128
|
+
return canonicalJson(a) > canonicalJson(b);
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
function tombstoneWins(a: LwwTombstone, b: LwwTombstone): boolean {
|
|
132
|
+
if (a.ts !== b.ts || a.actor !== b.actor) return wins(a.ts, a.actor, b.ts, b.actor);
|
|
133
|
+
return canonicalJson(a) > canonicalJson(b);
|
|
116
134
|
}
|
|
117
135
|
|
|
118
136
|
// State-based LWW-Map merge: commutative, associative, idempotent. A field
|
|
@@ -124,38 +142,68 @@ export function mergeLwwMapDocs(a: LwwMapDoc, b: LwwMapDoc): LwwMapDoc {
|
|
|
124
142
|
for (const source of [a.tombstones, b.tombstones]) {
|
|
125
143
|
for (const [name, stone] of Object.entries(source)) {
|
|
126
144
|
const existing = tombstones[name];
|
|
127
|
-
if (!existing ||
|
|
145
|
+
if (!existing || tombstoneWins(stone, existing)) tombstones[name] = { ...stone };
|
|
128
146
|
}
|
|
129
147
|
}
|
|
130
148
|
const fields: Record<string, LwwFieldEntry> = {};
|
|
131
149
|
for (const source of [a.fields, b.fields]) {
|
|
132
150
|
for (const [name, entry] of Object.entries(source)) {
|
|
133
151
|
const existing = fields[name];
|
|
134
|
-
if (!existing || fieldEntryWins(entry, existing)) fields[name] = {
|
|
152
|
+
if (!existing || fieldEntryWins(entry, existing)) fields[name] = { ...entry };
|
|
135
153
|
}
|
|
136
154
|
}
|
|
137
155
|
for (const [name, stone] of Object.entries(tombstones)) {
|
|
138
156
|
const entry = fields[name];
|
|
139
157
|
if (entry && !wins(entry.ts, entry.actor, stone.ts, stone.actor)) delete fields[name];
|
|
140
158
|
}
|
|
141
|
-
|
|
159
|
+
const ext = mergeExt(a.ext, b.ext);
|
|
160
|
+
return { t: "lww-map", fields, tombstones, ...(ext ? { ext } : {}) };
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
function mergeExt(a: Record<string, unknown> | undefined, b: Record<string, unknown> | undefined): Record<string, unknown> | undefined {
|
|
164
|
+
if (!a && !b) return undefined;
|
|
165
|
+
const merged: Record<string, unknown> = { ...(a || {}) };
|
|
166
|
+
for (const [key, value] of Object.entries(b || {})) {
|
|
167
|
+
if (!(key in merged) || canonicalJson(value) > canonicalJson(merged[key])) merged[key] = value;
|
|
168
|
+
}
|
|
169
|
+
return Object.keys(merged).length ? merged : undefined;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
function canonicalJson(value: unknown): string {
|
|
173
|
+
return stableStringify(fieldValueToCanonicalJson(value));
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
function stableStringify(value: unknown): string {
|
|
177
|
+
if (Array.isArray(value)) return `[${value.map(stableStringify).join(",")}]`;
|
|
178
|
+
if (value && typeof value === "object") {
|
|
179
|
+
const entries = Object.entries(value as Record<string, unknown>)
|
|
180
|
+
.filter(([, item]) => item !== undefined)
|
|
181
|
+
.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
|
|
182
|
+
return `{${entries.map(([key, item]) => `${JSON.stringify(key)}:${stableStringify(item)}`).join(",")}}`;
|
|
183
|
+
}
|
|
184
|
+
return JSON.stringify(value) ?? "null";
|
|
142
185
|
}
|
|
143
186
|
|
|
144
187
|
export function lwwMapDocsEqual(a: LwwMapDoc, b: LwwMapDoc): boolean {
|
|
145
|
-
return
|
|
188
|
+
return canonicalJson(canonicalLwwMapDoc(a)) === canonicalJson(canonicalLwwMapDoc(b));
|
|
146
189
|
}
|
|
147
190
|
|
|
148
191
|
function canonicalLwwMapDoc(doc: LwwMapDoc): unknown {
|
|
149
192
|
return {
|
|
150
|
-
fields: Object.fromEntries(
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
.map(([name, entry]) => [name, { ...entry, v: fieldValueToCanonicalJson(entry.v) }])
|
|
154
|
-
),
|
|
155
|
-
tombstones: Object.fromEntries(Object.entries(doc.tombstones).sort(([a], [b]) => (a < b ? -1 : 1))),
|
|
193
|
+
fields: Object.fromEntries(Object.entries(doc.fields).map(([name, entry]) => [name, { ...entry, v: fieldValueToCanonicalJson(entry.v) }])),
|
|
194
|
+
tombstones: doc.tombstones,
|
|
195
|
+
ext: doc.ext || {},
|
|
156
196
|
};
|
|
157
197
|
}
|
|
158
198
|
|
|
199
|
+
export function lwwMapLatestTs(doc: LwwMapDoc): number | null {
|
|
200
|
+
let latest: number | null = null;
|
|
201
|
+
for (const entry of [...Object.values(doc.fields), ...Object.values(doc.tombstones)]) {
|
|
202
|
+
if (latest === null || entry.ts > latest) latest = entry.ts;
|
|
203
|
+
}
|
|
204
|
+
return latest;
|
|
205
|
+
}
|
|
206
|
+
|
|
159
207
|
// Plain field view with tombstones and metadata hidden.
|
|
160
208
|
export function lwwMapValues(doc: LwwMapDoc): Record<string, unknown> {
|
|
161
209
|
return Object.fromEntries(Object.entries(doc.fields).map(([name, entry]) => [name, hydrateFieldValue(entry.v)]));
|
|
@@ -189,6 +237,7 @@ export function applyLwwMapUpdates(doc: LwwMapDoc, updates: Record<string, unkno
|
|
|
189
237
|
t: "lww-map",
|
|
190
238
|
fields: { ...doc.fields },
|
|
191
239
|
tombstones: { ...doc.tombstones },
|
|
240
|
+
...(doc.ext ? { ext: { ...doc.ext } } : {}),
|
|
192
241
|
};
|
|
193
242
|
for (const [name, value] of Object.entries(updates)) {
|
|
194
243
|
const ts = clock.next();
|
package/src/bucket/transport.ts
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
// HTTP transport for the open bucket surface: GET current, GET version
|
|
2
|
-
// payload,
|
|
3
|
-
// layer; a 401 triggers one forced session refresh and
|
|
4
|
-
// error escalates (the auth layer decides whether that
|
|
2
|
+
// payload, object CAS write, and current-head listing. Session credentials
|
|
3
|
+
// come from the auth layer; a 401 triggers one forced session refresh and
|
|
4
|
+
// retry before the error escalates (the auth layer decides whether that
|
|
5
|
+
// means disconnected).
|
|
5
6
|
|
|
6
7
|
import { fnv1a32Bytes, utf8Encode } from "../internal/encoding.ts";
|
|
7
8
|
import { decryptEnvelope, encryptEnvelopeFields } from "./crypto.ts";
|
|
@@ -139,9 +140,38 @@ export class BucketTransport {
|
|
|
139
140
|
return { ok: true, versionId };
|
|
140
141
|
}
|
|
141
142
|
|
|
142
|
-
|
|
143
|
+
async listHeads(): Promise<Map<string, string>> {
|
|
144
|
+
const heads = new Map<string, string>();
|
|
145
|
+
const indexRes = await this.request(() => ({ url: `${this.bucketUrl()}/objects:index`, init: { method: "GET" } }));
|
|
146
|
+
if (!indexRes.ok) throw new BucketTransportError(`object index failed: ${indexRes.status}`, indexRes.status);
|
|
147
|
+
const index = await readJsonObject(indexRes, "object index");
|
|
148
|
+
if (!Array.isArray(index.objects)) throw new BucketTransportError("object index returned invalid response", indexRes.status);
|
|
149
|
+
addHeads(heads, index.objects);
|
|
150
|
+
let cursor = typeof index.feedCursor === "string" ? index.feedCursor : null;
|
|
151
|
+
let hasMore = index.hasMoreFeed === true;
|
|
152
|
+
for (let page = 0; hasMore; page += 1) {
|
|
153
|
+
if (page >= MAX_FEED_PAGES) throw new BucketTransportError("feed did not end within page limit", 500);
|
|
154
|
+
const query = new URLSearchParams({ limit: String(FEED_PAGE_LIMIT) });
|
|
155
|
+
if (cursor) query.set("cursor", cursor);
|
|
156
|
+
const feedRes = await this.request(() => ({ url: `${this.bucketUrl()}/feed?${query}`, init: { method: "GET" } }));
|
|
157
|
+
if (!feedRes.ok) throw new BucketTransportError(`feed failed: ${feedRes.status}`, feedRes.status);
|
|
158
|
+
const feed = await readJsonObject(feedRes, "feed");
|
|
159
|
+
if (!Array.isArray(feed.entries)) throw new BucketTransportError("feed returned invalid response", feedRes.status);
|
|
160
|
+
addHeads(heads, feed.entries);
|
|
161
|
+
const next = typeof feed.cursor === "string" ? feed.cursor : null;
|
|
162
|
+
hasMore = feed.hasMore === true && next !== null && next !== cursor;
|
|
163
|
+
cursor = next;
|
|
164
|
+
}
|
|
165
|
+
return heads;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
private bucketUrl(): string {
|
|
143
169
|
const syncRoot = this.apiBase.endsWith("/v1/api/sync") ? this.apiBase : `${this.apiBase}/v1/api/sync`;
|
|
144
|
-
return `${syncRoot}/buckets/${encodeURIComponent(this.keys.bucketId)}
|
|
170
|
+
return `${syncRoot}/buckets/${encodeURIComponent(this.keys.bucketId)}`;
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
private objectUrl(wireObjectId: string): string {
|
|
174
|
+
return `${this.bucketUrl()}/objects/${encodeURIComponent(wireObjectId)}`;
|
|
145
175
|
}
|
|
146
176
|
|
|
147
177
|
private async request(build: () => { url: string; init: RequestInit }): Promise<Response> {
|
|
@@ -170,6 +200,16 @@ export class BucketTransport {
|
|
|
170
200
|
}
|
|
171
201
|
}
|
|
172
202
|
|
|
203
|
+
const FEED_PAGE_LIMIT = 100;
|
|
204
|
+
const MAX_FEED_PAGES = 10_000;
|
|
205
|
+
|
|
206
|
+
function addHeads(heads: Map<string, string>, entries: unknown[]): void {
|
|
207
|
+
for (const entry of entries) {
|
|
208
|
+
const row = entry as { objectId?: unknown; versionId?: unknown } | null;
|
|
209
|
+
if (typeof row?.objectId === "string" && typeof row.versionId === "string") heads.set(row.objectId, row.versionId);
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
|
|
173
213
|
async function readJsonObject(res: Response, label: string): Promise<Record<string, unknown>> {
|
|
174
214
|
const contentType = res.headers.get("content-type") || "";
|
|
175
215
|
if (contentType && !contentType.toLowerCase().includes("application/json")) {
|