@myfield/sdk 0.9.2 → 0.9.3
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 +7 -0
- package/README.md +30 -9
- package/dist/index.js +467 -366
- package/package.json +15 -8
- package/types/index.d.ts +395 -137
- package/docs/API.md +0 -298
- package/docs/BUCKET-SPEC.md +0 -173
- package/src/auth/authorization.ts +0 -254
- package/src/auth/flow.ts +0 -93
- package/src/auth/identifiers.ts +0 -46
- package/src/auth/index.ts +0 -17
- package/src/auth/instance.ts +0 -395
- package/src/auth/keys.ts +0 -73
- package/src/auth/proof.ts +0 -26
- package/src/auth/session.ts +0 -16
- package/src/auth/store.ts +0 -90
- package/src/auth/types.ts +0 -47
- package/src/bucket/binary.ts +0 -253
- package/src/bucket/client.ts +0 -426
- package/src/bucket/crypto.ts +0 -58
- package/src/bucket/format.ts +0 -324
- package/src/bucket/index.ts +0 -40
- package/src/bucket/keys.ts +0 -104
- package/src/bucket/store.ts +0 -190
- package/src/bucket/transport.ts +0 -249
- package/src/errors.ts +0 -40
- package/src/facade.ts +0 -698
- package/src/index.ts +0 -29
- package/src/internal/encoding.ts +0 -95
- package/src/remote/bucket.ts +0 -180
- package/src/remote/client.ts +0 -38
- package/src/remote/connection.ts +0 -529
- package/src/remote/feed.ts +0 -80
- package/src/remote/http.ts +0 -78
- package/src/remote/session.ts +0 -31
package/src/bucket/binary.ts
DELETED
|
@@ -1,253 +0,0 @@
|
|
|
1
|
-
import { bytesToB64url } from "../internal/encoding.ts";
|
|
2
|
-
|
|
3
|
-
export type BinaryInput = Blob | ArrayBuffer | Uint8Array;
|
|
4
|
-
|
|
5
|
-
export type BinaryOptions = {
|
|
6
|
-
mimeType?: string;
|
|
7
|
-
name?: string;
|
|
8
|
-
lastModified?: number;
|
|
9
|
-
};
|
|
10
|
-
|
|
11
|
-
export type BucketBinaryValue = {
|
|
12
|
-
readonly kind: "binary";
|
|
13
|
-
readonly size: number;
|
|
14
|
-
readonly mimeType?: string;
|
|
15
|
-
readonly name?: string;
|
|
16
|
-
readonly lastModified?: number;
|
|
17
|
-
blob(): Promise<Blob>;
|
|
18
|
-
arrayBuffer(): Promise<ArrayBuffer>;
|
|
19
|
-
};
|
|
20
|
-
|
|
21
|
-
export type StoredBinaryValue = {
|
|
22
|
-
__myfieldSdkType: "binary-v1";
|
|
23
|
-
size: number;
|
|
24
|
-
bytes: Uint8Array;
|
|
25
|
-
mimeType?: string;
|
|
26
|
-
name?: string;
|
|
27
|
-
lastModified?: number;
|
|
28
|
-
};
|
|
29
|
-
|
|
30
|
-
const BINARY_HANDLE_MARKER = Symbol("myfield.sdk.binary");
|
|
31
|
-
const STORED_BINARY_TYPE = "binary-v1";
|
|
32
|
-
|
|
33
|
-
type RuntimeBinaryHandle = BucketBinaryValue & {
|
|
34
|
-
readonly [BINARY_HANDLE_MARKER]: true;
|
|
35
|
-
};
|
|
36
|
-
|
|
37
|
-
export function createBucketBinaryValue(input: BinaryInput | BucketBinaryValue, options: BinaryOptions = {}): BucketBinaryValue {
|
|
38
|
-
if (isBucketBinaryValue(input)) {
|
|
39
|
-
return makeBinaryHandle(
|
|
40
|
-
{
|
|
41
|
-
size: input.size,
|
|
42
|
-
...(input.mimeType ? { mimeType: input.mimeType } : {}),
|
|
43
|
-
...(input.name ? { name: input.name } : {}),
|
|
44
|
-
...(typeof input.lastModified === "number" ? { lastModified: input.lastModified } : {}),
|
|
45
|
-
...normalizeBinaryOptions(options),
|
|
46
|
-
},
|
|
47
|
-
() => input.arrayBuffer()
|
|
48
|
-
);
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
if (isBlobLike(input)) {
|
|
52
|
-
const blob = input;
|
|
53
|
-
const fileMeta = blob as Blob & { name?: unknown; lastModified?: unknown };
|
|
54
|
-
return makeBinaryHandle(
|
|
55
|
-
{
|
|
56
|
-
size: blob.size,
|
|
57
|
-
...(blob.type ? { mimeType: blob.type } : {}),
|
|
58
|
-
...(typeof fileMeta.name === "string" && fileMeta.name ? { name: fileMeta.name } : {}),
|
|
59
|
-
...(typeof fileMeta.lastModified === "number" ? { lastModified: fileMeta.lastModified } : {}),
|
|
60
|
-
...normalizeBinaryOptions(options),
|
|
61
|
-
},
|
|
62
|
-
() => blob.arrayBuffer()
|
|
63
|
-
);
|
|
64
|
-
}
|
|
65
|
-
|
|
66
|
-
const bytes = input instanceof Uint8Array ? input : new Uint8Array(input);
|
|
67
|
-
return makeBinaryHandle(
|
|
68
|
-
{
|
|
69
|
-
size: bytes.byteLength,
|
|
70
|
-
...normalizeBinaryOptions(options),
|
|
71
|
-
},
|
|
72
|
-
async () => bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength) as ArrayBuffer
|
|
73
|
-
);
|
|
74
|
-
}
|
|
75
|
-
|
|
76
|
-
export function isBucketBinaryValue(value: unknown): value is BucketBinaryValue {
|
|
77
|
-
return !!value && typeof value === "object" && (value as Partial<RuntimeBinaryHandle>)[BINARY_HANDLE_MARKER] === true;
|
|
78
|
-
}
|
|
79
|
-
|
|
80
|
-
export function isStoredBinaryValue(value: unknown): value is StoredBinaryValue {
|
|
81
|
-
const row = value as Partial<StoredBinaryValue> | null;
|
|
82
|
-
return (
|
|
83
|
-
!!row &&
|
|
84
|
-
row.__myfieldSdkType === STORED_BINARY_TYPE &&
|
|
85
|
-
typeof row.size === "number" &&
|
|
86
|
-
Number.isSafeInteger(row.size) &&
|
|
87
|
-
row.size >= 0 &&
|
|
88
|
-
row.bytes instanceof Uint8Array &&
|
|
89
|
-
row.bytes.byteLength === row.size &&
|
|
90
|
-
optionalString(row.mimeType) &&
|
|
91
|
-
optionalString(row.name) &&
|
|
92
|
-
optionalNumber(row.lastModified)
|
|
93
|
-
);
|
|
94
|
-
}
|
|
95
|
-
|
|
96
|
-
export async function toStoredBinaryValue(value: BucketBinaryValue | StoredBinaryValue): Promise<StoredBinaryValue> {
|
|
97
|
-
if (isStoredBinaryValue(value)) return cloneStoredBinaryValue(value);
|
|
98
|
-
if (!isBucketBinaryValue(value)) throw new Error("binary value must be created with bucket.binary()");
|
|
99
|
-
const bytes = new Uint8Array(await value.arrayBuffer());
|
|
100
|
-
if (bytes.byteLength !== value.size) throw new Error("binary value size changed while reading");
|
|
101
|
-
return {
|
|
102
|
-
__myfieldSdkType: STORED_BINARY_TYPE,
|
|
103
|
-
size: bytes.byteLength,
|
|
104
|
-
bytes,
|
|
105
|
-
...(value.mimeType ? { mimeType: value.mimeType } : {}),
|
|
106
|
-
...(value.name ? { name: value.name } : {}),
|
|
107
|
-
...(typeof value.lastModified === "number" ? { lastModified: value.lastModified } : {}),
|
|
108
|
-
};
|
|
109
|
-
}
|
|
110
|
-
|
|
111
|
-
export function hydrateBinaryValue(value: StoredBinaryValue): BucketBinaryValue {
|
|
112
|
-
const stored = cloneStoredBinaryValue(value);
|
|
113
|
-
return makeBinaryHandle(
|
|
114
|
-
{
|
|
115
|
-
size: stored.size,
|
|
116
|
-
...(stored.mimeType ? { mimeType: stored.mimeType } : {}),
|
|
117
|
-
...(stored.name ? { name: stored.name } : {}),
|
|
118
|
-
...(typeof stored.lastModified === "number" ? { lastModified: stored.lastModified } : {}),
|
|
119
|
-
},
|
|
120
|
-
async () => stored.bytes.buffer.slice(stored.bytes.byteOffset, stored.bytes.byteOffset + stored.bytes.byteLength) as ArrayBuffer
|
|
121
|
-
);
|
|
122
|
-
}
|
|
123
|
-
|
|
124
|
-
export function binaryValueToCanonicalJson(value: StoredBinaryValue): Record<string, unknown> {
|
|
125
|
-
return {
|
|
126
|
-
__myfieldSdkType: STORED_BINARY_TYPE,
|
|
127
|
-
size: value.size,
|
|
128
|
-
data: bytesToB64url(value.bytes),
|
|
129
|
-
...(value.mimeType ? { mimeType: value.mimeType } : {}),
|
|
130
|
-
...(value.name ? { name: value.name } : {}),
|
|
131
|
-
...(typeof value.lastModified === "number" ? { lastModified: value.lastModified } : {}),
|
|
132
|
-
};
|
|
133
|
-
}
|
|
134
|
-
|
|
135
|
-
export function fieldValueToCanonicalJson(value: unknown): unknown {
|
|
136
|
-
if (isStoredBinaryValue(value)) return binaryValueToCanonicalJson(value);
|
|
137
|
-
if (Array.isArray(value)) return value.map(fieldValueToCanonicalJson);
|
|
138
|
-
if (value && typeof value === "object") {
|
|
139
|
-
return Object.fromEntries(
|
|
140
|
-
Object.entries(value as Record<string, unknown>)
|
|
141
|
-
.sort(([a], [b]) => a.localeCompare(b))
|
|
142
|
-
.map(([key, item]) => [key, fieldValueToCanonicalJson(item)])
|
|
143
|
-
);
|
|
144
|
-
}
|
|
145
|
-
return value;
|
|
146
|
-
}
|
|
147
|
-
|
|
148
|
-
export async function canonicalizeFieldValue(value: unknown, seen = new WeakSet<object>()): Promise<unknown> {
|
|
149
|
-
if (value === undefined) return undefined;
|
|
150
|
-
if (value === null) return null;
|
|
151
|
-
if (typeof value === "string" || typeof value === "boolean") return value;
|
|
152
|
-
if (typeof value === "number") {
|
|
153
|
-
if (!Number.isFinite(value)) throw new Error("number field values must be finite");
|
|
154
|
-
return value;
|
|
155
|
-
}
|
|
156
|
-
if (isBucketBinaryValue(value) || isStoredBinaryValue(value)) return toStoredBinaryValue(value);
|
|
157
|
-
if (isRawBinaryInput(value)) throw new Error("binary field values must be created with bucket.binary()");
|
|
158
|
-
if (Array.isArray(value)) {
|
|
159
|
-
if (seen.has(value)) throw new Error("cyclic field values are not supported");
|
|
160
|
-
seen.add(value);
|
|
161
|
-
const out = [];
|
|
162
|
-
for (const item of value) out.push(await canonicalizeFieldValue(item, seen));
|
|
163
|
-
seen.delete(value);
|
|
164
|
-
return out;
|
|
165
|
-
}
|
|
166
|
-
if (typeof value === "object") {
|
|
167
|
-
if (!isPlainObject(value)) throw new Error("field values must be JSON-compatible or created with bucket.binary()");
|
|
168
|
-
if (seen.has(value)) throw new Error("cyclic field values are not supported");
|
|
169
|
-
seen.add(value);
|
|
170
|
-
const out: Record<string, unknown> = {};
|
|
171
|
-
for (const [key, item] of Object.entries(value)) out[key] = await canonicalizeFieldValue(item, seen);
|
|
172
|
-
seen.delete(value);
|
|
173
|
-
return out;
|
|
174
|
-
}
|
|
175
|
-
throw new Error("field values must be JSON-compatible or created with bucket.binary()");
|
|
176
|
-
}
|
|
177
|
-
|
|
178
|
-
export async function canonicalizeFieldMap(fields: Record<string, unknown>): Promise<Record<string, unknown>> {
|
|
179
|
-
const out: Record<string, unknown> = {};
|
|
180
|
-
for (const [name, value] of Object.entries(fields)) out[name] = await canonicalizeFieldValue(value);
|
|
181
|
-
return out;
|
|
182
|
-
}
|
|
183
|
-
|
|
184
|
-
export function hydrateFieldValue(value: unknown): unknown {
|
|
185
|
-
if (isStoredBinaryValue(value)) return hydrateBinaryValue(value);
|
|
186
|
-
if (Array.isArray(value)) return value.map(hydrateFieldValue);
|
|
187
|
-
if (value && typeof value === "object") {
|
|
188
|
-
return Object.fromEntries(Object.entries(value as Record<string, unknown>).map(([key, item]) => [key, hydrateFieldValue(item)]));
|
|
189
|
-
}
|
|
190
|
-
return value;
|
|
191
|
-
}
|
|
192
|
-
|
|
193
|
-
export function cloneStoredBinaryValue(value: StoredBinaryValue): StoredBinaryValue {
|
|
194
|
-
return {
|
|
195
|
-
__myfieldSdkType: STORED_BINARY_TYPE,
|
|
196
|
-
size: value.size,
|
|
197
|
-
bytes: new Uint8Array(value.bytes),
|
|
198
|
-
...(value.mimeType ? { mimeType: value.mimeType } : {}),
|
|
199
|
-
...(value.name ? { name: value.name } : {}),
|
|
200
|
-
...(typeof value.lastModified === "number" ? { lastModified: value.lastModified } : {}),
|
|
201
|
-
};
|
|
202
|
-
}
|
|
203
|
-
|
|
204
|
-
function makeBinaryHandle(
|
|
205
|
-
meta: { size: number; mimeType?: string; name?: string; lastModified?: number },
|
|
206
|
-
load: () => Promise<ArrayBuffer>
|
|
207
|
-
): BucketBinaryValue {
|
|
208
|
-
const handle: BucketBinaryValue = {
|
|
209
|
-
kind: "binary",
|
|
210
|
-
size: meta.size,
|
|
211
|
-
...(meta.mimeType ? { mimeType: meta.mimeType } : {}),
|
|
212
|
-
...(meta.name ? { name: meta.name } : {}),
|
|
213
|
-
...(typeof meta.lastModified === "number" ? { lastModified: meta.lastModified } : {}),
|
|
214
|
-
async blob() {
|
|
215
|
-
return new Blob([await load()], { type: meta.mimeType || "" });
|
|
216
|
-
},
|
|
217
|
-
async arrayBuffer() {
|
|
218
|
-
const buffer = await load();
|
|
219
|
-
return buffer.slice(0);
|
|
220
|
-
},
|
|
221
|
-
};
|
|
222
|
-
Object.defineProperty(handle, BINARY_HANDLE_MARKER, { value: true });
|
|
223
|
-
return handle;
|
|
224
|
-
}
|
|
225
|
-
|
|
226
|
-
function normalizeBinaryOptions(options: BinaryOptions): BinaryOptions {
|
|
227
|
-
return {
|
|
228
|
-
...(typeof options.mimeType === "string" && options.mimeType ? { mimeType: options.mimeType } : {}),
|
|
229
|
-
...(typeof options.name === "string" && options.name ? { name: options.name } : {}),
|
|
230
|
-
...(typeof options.lastModified === "number" && Number.isFinite(options.lastModified) ? { lastModified: options.lastModified } : {}),
|
|
231
|
-
};
|
|
232
|
-
}
|
|
233
|
-
|
|
234
|
-
function isBlobLike(value: unknown): value is Blob {
|
|
235
|
-
return typeof Blob !== "undefined" && value instanceof Blob;
|
|
236
|
-
}
|
|
237
|
-
|
|
238
|
-
function isRawBinaryInput(value: unknown): value is BinaryInput {
|
|
239
|
-
return isBlobLike(value) || value instanceof ArrayBuffer || value instanceof Uint8Array;
|
|
240
|
-
}
|
|
241
|
-
|
|
242
|
-
function isPlainObject(value: object): value is Record<string, unknown> {
|
|
243
|
-
const proto = Object.getPrototypeOf(value);
|
|
244
|
-
return proto === Object.prototype || proto === null;
|
|
245
|
-
}
|
|
246
|
-
|
|
247
|
-
function optionalString(value: unknown): boolean {
|
|
248
|
-
return value === undefined || typeof value === "string";
|
|
249
|
-
}
|
|
250
|
-
|
|
251
|
-
function optionalNumber(value: unknown): boolean {
|
|
252
|
-
return value === undefined || (typeof value === "number" && Number.isFinite(value));
|
|
253
|
-
}
|
package/src/bucket/client.ts
DELETED
|
@@ -1,426 +0,0 @@
|
|
|
1
|
-
// Local-first bucket client. Reads and writes hit the local store first;
|
|
2
|
-
// sync reconciles with the relay through the CAS retry loop
|
|
3
|
-
// (push conflict → pull current → merge → re-push), which converges because
|
|
4
|
-
// every merge strategy is required to be state-based convergent.
|
|
5
|
-
//
|
|
6
|
-
// The relay may have evicted any object. A remote miss with a surviving
|
|
7
|
-
// local record is healed by re-pushing the local state (CAS create).
|
|
8
|
-
|
|
9
|
-
import {
|
|
10
|
-
applyLwwMapUpdates,
|
|
11
|
-
decodePayloadDoc,
|
|
12
|
-
emptyLwwMapDoc,
|
|
13
|
-
encodePayloadDoc,
|
|
14
|
-
lwwMapDocsEqual,
|
|
15
|
-
lwwMapLatestTs,
|
|
16
|
-
lwwMapValues,
|
|
17
|
-
LwwClock,
|
|
18
|
-
mergeLwwMapDocs,
|
|
19
|
-
type LwwMapDoc,
|
|
20
|
-
type OpaqueDoc,
|
|
21
|
-
type PayloadDoc,
|
|
22
|
-
} from "./format.ts";
|
|
23
|
-
import { canonicalizeFieldMap } from "./binary.ts";
|
|
24
|
-
import type { StorageAdapter } from "./store.ts";
|
|
25
|
-
import { BucketTransportError, type TransportHeadResult, type TransportPayloadResult, type TransportPushResult } from "./transport.ts";
|
|
26
|
-
|
|
27
|
-
export type MergeStrategy = { kind: "lww-map" } | { kind: "opaque"; merge: (local: unknown, remote: unknown) => unknown };
|
|
28
|
-
|
|
29
|
-
export type BucketTransportLike = {
|
|
30
|
-
pullHead(wireObjectId: string): Promise<TransportHeadResult>;
|
|
31
|
-
pullPayload(wireObjectId: string, versionId: string): Promise<TransportPayloadResult>;
|
|
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>;
|
|
41
|
-
};
|
|
42
|
-
|
|
43
|
-
export type BucketClientOptions = {
|
|
44
|
-
transport: BucketTransportLike;
|
|
45
|
-
storage: StorageAdapter;
|
|
46
|
-
actorId: string;
|
|
47
|
-
wireObjectId?: (appObjectId: string) => Promise<string>;
|
|
48
|
-
storagePrefix?: string;
|
|
49
|
-
mergeStrategyFor?: (appObjectId: string) => MergeStrategy;
|
|
50
|
-
maxCasAttempts?: number;
|
|
51
|
-
pushDebounceMs?: number;
|
|
52
|
-
autoSync?: boolean;
|
|
53
|
-
localOnlyObjectIds?: Iterable<string>;
|
|
54
|
-
validateRemote?: (appObjectId: string, doc: PayloadDoc) => void;
|
|
55
|
-
onChange?: (appObjectId: string, source: ChangeSource) => void;
|
|
56
|
-
onSyncError?: (appObjectId: string | null, error: unknown) => void;
|
|
57
|
-
};
|
|
58
|
-
|
|
59
|
-
type LocalObjectRecord = {
|
|
60
|
-
v: 1;
|
|
61
|
-
doc: PayloadDoc;
|
|
62
|
-
remoteVersionId: string | null;
|
|
63
|
-
dirty: boolean;
|
|
64
|
-
};
|
|
65
|
-
|
|
66
|
-
const DEFAULT_MAX_CAS_ATTEMPTS = 5;
|
|
67
|
-
const DEFAULT_PUSH_DEBOUNCE_MS = 800;
|
|
68
|
-
const DEFAULT_SYNC_INTERVAL_MS = 5 * 60 * 1000;
|
|
69
|
-
const DEFAULT_MAX_ENCODED_OBJECT_BYTES = 100 * 1024 * 1024;
|
|
70
|
-
|
|
71
|
-
export class BucketClient {
|
|
72
|
-
private readonly transport: BucketTransportLike;
|
|
73
|
-
private readonly storage: StorageAdapter;
|
|
74
|
-
private readonly actorId: string;
|
|
75
|
-
private readonly wireId: (appObjectId: string) => Promise<string>;
|
|
76
|
-
private readonly prefix: string;
|
|
77
|
-
private readonly mergeStrategyFor: (appObjectId: string) => MergeStrategy;
|
|
78
|
-
private readonly maxCasAttempts: number;
|
|
79
|
-
private readonly pushDebounceMs: number;
|
|
80
|
-
private readonly maxEncodedObjectBytes = DEFAULT_MAX_ENCODED_OBJECT_BYTES;
|
|
81
|
-
private readonly localOnly: Set<string>;
|
|
82
|
-
private readonly validateRemote?: (appObjectId: string, doc: PayloadDoc) => void;
|
|
83
|
-
private readonly onChange?: (appObjectId: string, source: ChangeSource) => void;
|
|
84
|
-
private readonly onSyncError?: (appObjectId: string | null, error: unknown) => void;
|
|
85
|
-
private readonly clock = new LwwClock();
|
|
86
|
-
private readonly inFlightSync = new Map<string, Promise<boolean>>();
|
|
87
|
-
private readonly objectLocks = new Map<string, Promise<void>>();
|
|
88
|
-
private readonly pendingPushTimers = new Map<string, ReturnType<typeof setTimeout>>();
|
|
89
|
-
private readonly watched = new Set<string>();
|
|
90
|
-
// Avoids re-downloading an unresolvable object until its head changes.
|
|
91
|
-
private readonly unresolved = new Map<string, string>();
|
|
92
|
-
private triggerCleanup: (() => void) | null = null;
|
|
93
|
-
private disposed = false;
|
|
94
|
-
private autoSync: boolean;
|
|
95
|
-
|
|
96
|
-
constructor(options: BucketClientOptions) {
|
|
97
|
-
this.transport = options.transport;
|
|
98
|
-
this.storage = options.storage;
|
|
99
|
-
this.actorId = options.actorId;
|
|
100
|
-
this.wireId = options.wireObjectId || (async (id) => id);
|
|
101
|
-
this.prefix = options.storagePrefix || "myfield-sdk";
|
|
102
|
-
this.mergeStrategyFor = options.mergeStrategyFor || (() => ({ kind: "lww-map" }));
|
|
103
|
-
this.maxCasAttempts = options.maxCasAttempts ?? DEFAULT_MAX_CAS_ATTEMPTS;
|
|
104
|
-
this.pushDebounceMs = options.pushDebounceMs ?? DEFAULT_PUSH_DEBOUNCE_MS;
|
|
105
|
-
this.localOnly = new Set(options.localOnlyObjectIds || []);
|
|
106
|
-
this.validateRemote = options.validateRemote;
|
|
107
|
-
this.onChange = options.onChange;
|
|
108
|
-
this.onSyncError = options.onSyncError;
|
|
109
|
-
this.autoSync = options.autoSync ?? true;
|
|
110
|
-
}
|
|
111
|
-
|
|
112
|
-
// ---- local reads -------------------------------------------------------
|
|
113
|
-
|
|
114
|
-
async getFields(appObjectId: string): Promise<Record<string, unknown> | null> {
|
|
115
|
-
const record = await this.readRecord(appObjectId);
|
|
116
|
-
if (!record || record.doc.t !== "lww-map") return null;
|
|
117
|
-
return lwwMapValues(record.doc);
|
|
118
|
-
}
|
|
119
|
-
|
|
120
|
-
async getData(appObjectId: string): Promise<unknown> {
|
|
121
|
-
const record = await this.readRecord(appObjectId);
|
|
122
|
-
if (!record || record.doc.t !== "opaque") return null;
|
|
123
|
-
return record.doc.data;
|
|
124
|
-
}
|
|
125
|
-
|
|
126
|
-
async lastModified(appObjectId: string): Promise<number | null> {
|
|
127
|
-
const record = await this.readRecord(appObjectId);
|
|
128
|
-
return record && record.doc.t === "lww-map" ? lwwMapLatestTs(record.doc) : null;
|
|
129
|
-
}
|
|
130
|
-
|
|
131
|
-
async knownObjectIds(): Promise<string[]> {
|
|
132
|
-
const keys = await this.storage.keys(`${this.prefix}:obj:`);
|
|
133
|
-
return keys.map((key) => decodeURIComponent(key.slice(`${this.prefix}:obj:`.length)));
|
|
134
|
-
}
|
|
135
|
-
|
|
136
|
-
// ---- local writes ------------------------------------------------------
|
|
137
|
-
|
|
138
|
-
// Every read-modify-write of a local record runs through a per-object
|
|
139
|
-
// queue: interleaved async writers (concurrent setFields, or a sync merge
|
|
140
|
-
// racing a local write) would otherwise clobber each other's snapshot and
|
|
141
|
-
// silently lose fields.
|
|
142
|
-
private withObjectLock<T>(appObjectId: string, fn: () => Promise<T>): Promise<T> {
|
|
143
|
-
const previous = this.objectLocks.get(appObjectId) ?? Promise.resolve();
|
|
144
|
-
const run = previous.then(fn, fn);
|
|
145
|
-
this.objectLocks.set(
|
|
146
|
-
appObjectId,
|
|
147
|
-
run.then(
|
|
148
|
-
() => undefined,
|
|
149
|
-
() => undefined
|
|
150
|
-
)
|
|
151
|
-
);
|
|
152
|
-
return run;
|
|
153
|
-
}
|
|
154
|
-
|
|
155
|
-
// `undefined` field values delete the field (tombstone).
|
|
156
|
-
setFields(appObjectId: string, updates: Record<string, unknown>): Promise<Record<string, unknown>> {
|
|
157
|
-
return this.withObjectLock(appObjectId, async () => {
|
|
158
|
-
const record = await this.readRecord(appObjectId);
|
|
159
|
-
const baseDoc: LwwMapDoc = record && record.doc.t === "lww-map" ? record.doc : emptyLwwMapDoc();
|
|
160
|
-
this.clock.observeDoc(baseDoc);
|
|
161
|
-
const nextDoc = applyLwwMapUpdates(baseDoc, await canonicalizeFieldMap(updates), this.clock, this.actorId);
|
|
162
|
-
this.assertEncodedObjectSize(nextDoc);
|
|
163
|
-
await this.writeRecord(appObjectId, {
|
|
164
|
-
v: 1,
|
|
165
|
-
doc: nextDoc,
|
|
166
|
-
remoteVersionId: record?.remoteVersionId ?? null,
|
|
167
|
-
dirty: true,
|
|
168
|
-
});
|
|
169
|
-
this.schedulePush(appObjectId);
|
|
170
|
-
this.onChange?.(appObjectId, "local");
|
|
171
|
-
return lwwMapValues(nextDoc);
|
|
172
|
-
});
|
|
173
|
-
}
|
|
174
|
-
|
|
175
|
-
setData(appObjectId: string, data: unknown): Promise<void> {
|
|
176
|
-
return this.withObjectLock(appObjectId, async () => {
|
|
177
|
-
const record = await this.readRecord(appObjectId);
|
|
178
|
-
const nextDoc: OpaqueDoc = { t: "opaque", data };
|
|
179
|
-
this.assertEncodedObjectSize(nextDoc);
|
|
180
|
-
await this.writeRecord(appObjectId, {
|
|
181
|
-
v: 1,
|
|
182
|
-
doc: nextDoc,
|
|
183
|
-
remoteVersionId: record?.remoteVersionId ?? null,
|
|
184
|
-
dirty: true,
|
|
185
|
-
});
|
|
186
|
-
this.schedulePush(appObjectId);
|
|
187
|
-
this.onChange?.(appObjectId, "local");
|
|
188
|
-
});
|
|
189
|
-
}
|
|
190
|
-
|
|
191
|
-
// ---- sync --------------------------------------------------------------
|
|
192
|
-
|
|
193
|
-
// Reconciles one object with the relay. Returns true when the local view
|
|
194
|
-
// changed because of remote data.
|
|
195
|
-
syncObject(appObjectId: string): Promise<boolean> {
|
|
196
|
-
const inFlight = this.inFlightSync.get(appObjectId);
|
|
197
|
-
if (inFlight) return inFlight;
|
|
198
|
-
const promise = this.performSync(appObjectId).finally(() => {
|
|
199
|
-
if (this.inFlightSync.get(appObjectId) === promise) this.inFlightSync.delete(appObjectId);
|
|
200
|
-
});
|
|
201
|
-
this.inFlightSync.set(appObjectId, promise);
|
|
202
|
-
return promise;
|
|
203
|
-
}
|
|
204
|
-
|
|
205
|
-
async syncObjects(appObjectIds: Iterable<string>): Promise<void> {
|
|
206
|
-
await Promise.all(Array.from(appObjectIds, (id) => this.syncObject(id).catch((error) => this.onSyncError?.(id, error))));
|
|
207
|
-
}
|
|
208
|
-
|
|
209
|
-
async syncKnown(): Promise<void> {
|
|
210
|
-
const ids = new Set([...(await this.knownObjectIds()), ...this.watched]);
|
|
211
|
-
await this.syncObjects(ids);
|
|
212
|
-
}
|
|
213
|
-
|
|
214
|
-
async syncPass(options: SyncPassOptions = {}): Promise<void> {
|
|
215
|
-
if (!this.transport.listHeads) throw new Error("transport does not list current heads");
|
|
216
|
-
const heads = await this.transport.listHeads();
|
|
217
|
-
for (const wireObjectId of options.skipWireIds || []) heads.delete(wireObjectId);
|
|
218
|
-
const known = new Map<string, string>();
|
|
219
|
-
const ids = new Set([...this.watched].filter((id) => !this.localOnly.has(id)));
|
|
220
|
-
for (const id of await this.knownObjectIds()) {
|
|
221
|
-
if (this.localOnly.has(id)) continue;
|
|
222
|
-
const record = await this.readRecord(id);
|
|
223
|
-
if (!record) continue;
|
|
224
|
-
const wireObjectId = await this.wireId(id);
|
|
225
|
-
known.set(wireObjectId, id);
|
|
226
|
-
const head = heads.get(wireObjectId);
|
|
227
|
-
if (record.dirty || head === undefined || head !== record.remoteVersionId) ids.add(id);
|
|
228
|
-
}
|
|
229
|
-
for (const [wireObjectId, versionId] of heads) {
|
|
230
|
-
if (known.has(wireObjectId) || !options.resolveUnknown || this.unresolved.get(wireObjectId) === versionId) continue;
|
|
231
|
-
try {
|
|
232
|
-
const id = await options.resolveUnknown(wireObjectId, versionId);
|
|
233
|
-
if (id && !this.localOnly.has(id) && (await this.wireId(id)) === wireObjectId) {
|
|
234
|
-
this.unresolved.delete(wireObjectId);
|
|
235
|
-
ids.add(id);
|
|
236
|
-
} else {
|
|
237
|
-
this.unresolved.set(wireObjectId, versionId);
|
|
238
|
-
}
|
|
239
|
-
} catch (error) {
|
|
240
|
-
this.onSyncError?.(null, error);
|
|
241
|
-
}
|
|
242
|
-
}
|
|
243
|
-
await this.syncObjects(ids);
|
|
244
|
-
}
|
|
245
|
-
|
|
246
|
-
async pullDoc(wireObjectId: string, versionId: string): Promise<PayloadDoc | null> {
|
|
247
|
-
const payload = await this.transport.pullPayload(wireObjectId, versionId);
|
|
248
|
-
return payload.found ? decodePayloadDoc(payload.plaintext) : null;
|
|
249
|
-
}
|
|
250
|
-
|
|
251
|
-
async pullRemoteDoc(appObjectId: string): Promise<PayloadDoc | null> {
|
|
252
|
-
const wireObjectId = await this.wireId(appObjectId);
|
|
253
|
-
const head = await this.transport.pullHead(wireObjectId);
|
|
254
|
-
return head.found ? this.pullDoc(wireObjectId, head.versionId) : null;
|
|
255
|
-
}
|
|
256
|
-
|
|
257
|
-
watch(appObjectIds: Iterable<string>): void {
|
|
258
|
-
for (const id of appObjectIds) this.watched.add(id);
|
|
259
|
-
}
|
|
260
|
-
|
|
261
|
-
// Sync-trigger model: launch (start itself) and a timer fallback.
|
|
262
|
-
// Browser/app lifecycle triggers are owned by the app; post-write pushes
|
|
263
|
-
// are scheduled by setFields/setData.
|
|
264
|
-
start(options: { intervalMs?: number; run: () => Promise<void> }): void {
|
|
265
|
-
if (this.triggerCleanup || this.disposed) return;
|
|
266
|
-
this.autoSync = true;
|
|
267
|
-
const run = options.run;
|
|
268
|
-
const kick = () => void run().catch((error) => this.onSyncError?.(null, error));
|
|
269
|
-
const intervalMs = options.intervalMs ?? DEFAULT_SYNC_INTERVAL_MS;
|
|
270
|
-
const timer = intervalMs > 0 ? setInterval(kick, intervalMs) : null;
|
|
271
|
-
this.triggerCleanup = () => {
|
|
272
|
-
if (timer) clearInterval(timer);
|
|
273
|
-
};
|
|
274
|
-
kick();
|
|
275
|
-
}
|
|
276
|
-
|
|
277
|
-
stop(): void {
|
|
278
|
-
this.autoSync = false;
|
|
279
|
-
this.triggerCleanup?.();
|
|
280
|
-
this.triggerCleanup = null;
|
|
281
|
-
for (const timer of this.pendingPushTimers.values()) clearTimeout(timer);
|
|
282
|
-
this.pendingPushTimers.clear();
|
|
283
|
-
}
|
|
284
|
-
|
|
285
|
-
dispose(): void {
|
|
286
|
-
this.disposed = true;
|
|
287
|
-
this.stop();
|
|
288
|
-
}
|
|
289
|
-
|
|
290
|
-
async flush(appObjectId?: string): Promise<void> {
|
|
291
|
-
const ids = appObjectId ? [appObjectId] : Array.from(this.pendingPushTimers.keys());
|
|
292
|
-
for (const id of ids) {
|
|
293
|
-
const timer = this.pendingPushTimers.get(id);
|
|
294
|
-
if (timer) {
|
|
295
|
-
clearTimeout(timer);
|
|
296
|
-
this.pendingPushTimers.delete(id);
|
|
297
|
-
}
|
|
298
|
-
}
|
|
299
|
-
await this.syncObjects(ids);
|
|
300
|
-
}
|
|
301
|
-
|
|
302
|
-
// ---- internals ---------------------------------------------------------
|
|
303
|
-
|
|
304
|
-
private schedulePush(appObjectId: string): void {
|
|
305
|
-
if (this.disposed || !this.autoSync || this.localOnly.has(appObjectId)) return;
|
|
306
|
-
const existing = this.pendingPushTimers.get(appObjectId);
|
|
307
|
-
if (existing) clearTimeout(existing);
|
|
308
|
-
this.pendingPushTimers.set(
|
|
309
|
-
appObjectId,
|
|
310
|
-
setTimeout(() => {
|
|
311
|
-
this.pendingPushTimers.delete(appObjectId);
|
|
312
|
-
void this.syncObject(appObjectId).catch((error) => this.onSyncError?.(appObjectId, error));
|
|
313
|
-
}, this.pushDebounceMs)
|
|
314
|
-
);
|
|
315
|
-
}
|
|
316
|
-
|
|
317
|
-
private async performSync(appObjectId: string): Promise<boolean> {
|
|
318
|
-
if (this.localOnly.has(appObjectId)) return false;
|
|
319
|
-
const wireObjectId = await this.wireId(appObjectId);
|
|
320
|
-
let remoteChangedLocal = false;
|
|
321
|
-
for (let attempt = 0; attempt < this.maxCasAttempts; attempt += 1) {
|
|
322
|
-
// Each attempt holds the object lock across read → merge → write so a
|
|
323
|
-
// concurrent local setFields cannot land between the snapshot and the
|
|
324
|
-
// record write and get clobbered. Between attempts the lock is
|
|
325
|
-
// released, so local writes slip in and the next attempt re-reads them.
|
|
326
|
-
const outcome = await this.withObjectLock(appObjectId, async (): Promise<"retry" | boolean> => {
|
|
327
|
-
const record = await this.readRecord(appObjectId);
|
|
328
|
-
const head = await this.transport.pullHead(wireObjectId);
|
|
329
|
-
|
|
330
|
-
if (!head.found) {
|
|
331
|
-
if (!record) return false;
|
|
332
|
-
// Relay miss with surviving local state: re-create (self-healing).
|
|
333
|
-
const result = await this.transport.push(wireObjectId, encodePayloadDoc(record.doc), null);
|
|
334
|
-
if (result.ok) {
|
|
335
|
-
await this.writeRecord(appObjectId, { ...record, remoteVersionId: result.versionId, dirty: false });
|
|
336
|
-
return remoteChangedLocal;
|
|
337
|
-
}
|
|
338
|
-
return "retry";
|
|
339
|
-
}
|
|
340
|
-
|
|
341
|
-
if (record && !record.dirty && record.remoteVersionId === head.versionId) return remoteChangedLocal;
|
|
342
|
-
|
|
343
|
-
const payload = await this.transport.pullPayload(wireObjectId, head.versionId);
|
|
344
|
-
if (!payload.found) return "retry";
|
|
345
|
-
const remoteDoc = decodePayloadDoc(payload.plaintext);
|
|
346
|
-
this.validateRemote?.(appObjectId, remoteDoc);
|
|
347
|
-
const merged = record ? this.merge(appObjectId, record.doc, remoteDoc) : remoteDoc;
|
|
348
|
-
const localViewChanged = !record || !docsEqual(merged, record.doc);
|
|
349
|
-
const remoteNeedsUpdate = !docsEqual(merged, remoteDoc);
|
|
350
|
-
|
|
351
|
-
if (merged.t === "lww-map") this.clock.observeDoc(merged);
|
|
352
|
-
|
|
353
|
-
if (!remoteNeedsUpdate) {
|
|
354
|
-
await this.writeRecord(appObjectId, { v: 1, doc: merged, remoteVersionId: head.versionId, dirty: false });
|
|
355
|
-
if (localViewChanged) {
|
|
356
|
-
remoteChangedLocal = true;
|
|
357
|
-
this.onChange?.(appObjectId, "remote");
|
|
358
|
-
}
|
|
359
|
-
return remoteChangedLocal;
|
|
360
|
-
}
|
|
361
|
-
|
|
362
|
-
const result = await this.transport.push(wireObjectId, encodePayloadDoc(merged), head.versionId);
|
|
363
|
-
if (result.ok) {
|
|
364
|
-
await this.writeRecord(appObjectId, { v: 1, doc: merged, remoteVersionId: result.versionId, dirty: false });
|
|
365
|
-
if (localViewChanged) {
|
|
366
|
-
remoteChangedLocal = true;
|
|
367
|
-
this.onChange?.(appObjectId, "remote");
|
|
368
|
-
}
|
|
369
|
-
return remoteChangedLocal;
|
|
370
|
-
}
|
|
371
|
-
// CAS conflict: retry pulls the newer head and merges again.
|
|
372
|
-
return "retry";
|
|
373
|
-
});
|
|
374
|
-
if (outcome !== "retry") return outcome;
|
|
375
|
-
}
|
|
376
|
-
throw new BucketTransportError("sync did not converge within CAS attempt limit", 409);
|
|
377
|
-
}
|
|
378
|
-
|
|
379
|
-
private merge(appObjectId: string, local: PayloadDoc, remote: PayloadDoc): PayloadDoc {
|
|
380
|
-
const strategy = this.mergeStrategyFor(appObjectId);
|
|
381
|
-
if (strategy.kind === "lww-map") {
|
|
382
|
-
if (local.t !== "lww-map" || remote.t !== "lww-map") throw new Error(`object ${appObjectId} is not an lww-map payload`);
|
|
383
|
-
return mergeLwwMapDocs(local, remote);
|
|
384
|
-
}
|
|
385
|
-
if (local.t !== "opaque" || remote.t !== "opaque") throw new Error(`object ${appObjectId} is not an opaque payload`);
|
|
386
|
-
return { t: "opaque", data: strategy.merge(local.data, remote.data) };
|
|
387
|
-
}
|
|
388
|
-
|
|
389
|
-
private recordKey(appObjectId: string): string {
|
|
390
|
-
return `${this.prefix}:obj:${encodeURIComponent(appObjectId)}`;
|
|
391
|
-
}
|
|
392
|
-
|
|
393
|
-
async dirtyObjectIds(): Promise<string[]> {
|
|
394
|
-
const ids: string[] = [];
|
|
395
|
-
for (const id of await this.knownObjectIds()) {
|
|
396
|
-
if (this.localOnly.has(id)) continue;
|
|
397
|
-
const record = await this.readRecord(id);
|
|
398
|
-
if (record?.dirty) ids.push(id);
|
|
399
|
-
}
|
|
400
|
-
return ids;
|
|
401
|
-
}
|
|
402
|
-
|
|
403
|
-
private async readRecord(appObjectId: string): Promise<LocalObjectRecord | null> {
|
|
404
|
-
const record = await this.storage.get<LocalObjectRecord>(this.recordKey(appObjectId));
|
|
405
|
-
if (!record || record.v !== 1 || !record.doc) return null;
|
|
406
|
-
return record;
|
|
407
|
-
}
|
|
408
|
-
|
|
409
|
-
private writeRecord(appObjectId: string, record: LocalObjectRecord): Promise<void> {
|
|
410
|
-
return this.storage.set(this.recordKey(appObjectId), record);
|
|
411
|
-
}
|
|
412
|
-
|
|
413
|
-
private assertEncodedObjectSize(doc: PayloadDoc): void {
|
|
414
|
-
const size = encodePayloadDoc(doc).byteLength;
|
|
415
|
-
if (size > this.maxEncodedObjectBytes) {
|
|
416
|
-
throw new Error(`encoded object payload exceeds ${this.maxEncodedObjectBytes} bytes`);
|
|
417
|
-
}
|
|
418
|
-
}
|
|
419
|
-
}
|
|
420
|
-
|
|
421
|
-
function docsEqual(a: PayloadDoc, b: PayloadDoc): boolean {
|
|
422
|
-
if (a.t === "lww-map" && b.t === "lww-map") return lwwMapDocsEqual(a, b);
|
|
423
|
-
if (a.t === "opaque" && b.t === "opaque") return JSON.stringify(a.data) === JSON.stringify(b.data);
|
|
424
|
-
return false;
|
|
425
|
-
}
|
|
426
|
-
|