@open-artifact/live-store 0.0.0-stage → 0.2.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/LICENSE +202 -0
- package/NOTICE +5 -0
- package/README.md +5 -2
- package/package.json +53 -4
- package/src/cache.d.ts +8 -0
- package/src/cache.js +40 -0
- package/src/doc-hash.d.ts +13 -0
- package/src/doc-hash.js +67 -0
- package/src/engine.d.ts +260 -0
- package/src/engine.js +1270 -0
- package/src/index.d.ts +10 -0
- package/src/index.js +10 -0
- package/src/json.d.ts +56 -0
- package/src/json.js +221 -0
- package/src/transport.d.ts +88 -0
- package/src/transport.js +35 -0
package/src/engine.d.ts
ADDED
|
@@ -0,0 +1,260 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The live sync engine: keeps a value in step with a document store (a
|
|
3
|
+
* board: one document per element plus a few board records; a dashboard:
|
|
4
|
+
* its datasets, page files and settings).
|
|
5
|
+
*
|
|
6
|
+
* Model, per document path:
|
|
7
|
+
* - `server`: the last value the store reported (by listing, a change event,
|
|
8
|
+
* or our own acknowledged write);
|
|
9
|
+
* - `acked`: our writes acknowledged in the last few seconds, re-applied over
|
|
10
|
+
* `server` so a late event about an older write does not flash old data;
|
|
11
|
+
* - `inflight`: the change being written;
|
|
12
|
+
* - `pending`: the change waiting to be written (debounced, merged).
|
|
13
|
+
*
|
|
14
|
+
* What the viewer sees is `server ⊕ acked ⊕ inflight ⊕ pending`. Changes are
|
|
15
|
+
* JSON merge patches computed against the document as it was before them, so
|
|
16
|
+
* two people editing different fields of one element both win; the same
|
|
17
|
+
* field: the last write wins.
|
|
18
|
+
*
|
|
19
|
+
* Local edits are applied at once ({@link LiveStore.commit}), split into
|
|
20
|
+
* documents on the next tick, and written after {@link LIVE_EDIT_DEBOUNCE_MS}
|
|
21
|
+
* of quiet (at most {@link LIVE_EDIT_MAX_WAIT_MS} after the first edit). Failed
|
|
22
|
+
* writes are retried with backoff; a document the store refuses (too large,
|
|
23
|
+
* invalid) is parked and the rest keep syncing. Losing write access stops
|
|
24
|
+
* syncing and keeps the edits on screen.
|
|
25
|
+
*
|
|
26
|
+
* Saved copy: with a {@link LiveCache}, the engine keeps the documents the
|
|
27
|
+
* store confirmed on the device. When the store does not answer within
|
|
28
|
+
* {@link LIVE_SNAPSHOT_TIMEOUT_MS}, or loading fails for a reason other than
|
|
29
|
+
* access, the saved copy is shown (`cached`): people can keep editing, and
|
|
30
|
+
* their edits wait until the store answers, then sync over what it holds.
|
|
31
|
+
*
|
|
32
|
+
* The engine is framework-agnostic: {@link LiveStore.getSnapshot} and
|
|
33
|
+
* {@link LiveStore.subscribe} fit React's `useSyncExternalStore` or a Zustand
|
|
34
|
+
* store.
|
|
35
|
+
*/
|
|
36
|
+
import { type SyncDocument, type SyncErrorCode, type SyncTimers, type SyncTransport, type SyncWrite } from './transport.ts';
|
|
37
|
+
/** Quiet time after the last edit of a document before it is written. */
|
|
38
|
+
export declare const LIVE_EDIT_DEBOUNCE_MS = 350;
|
|
39
|
+
/** Longest a document waits after its first unsent edit. */
|
|
40
|
+
export declare const LIVE_EDIT_MAX_WAIT_MS = 1500;
|
|
41
|
+
/** After this long loading, the saved copy shows (when there is one), else the status says it is still loading. */
|
|
42
|
+
export declare const LIVE_SNAPSHOT_TIMEOUT_MS = 10000;
|
|
43
|
+
/** After this long loading, the load counts as failed and is retried. */
|
|
44
|
+
export declare const LIVE_EXTENDED_LOAD_TIMEOUT_MS = 35000;
|
|
45
|
+
/** Delays between load retries; the last one repeats. */
|
|
46
|
+
export declare const LIVE_RECONNECT_BACKOFF_MS: readonly number[];
|
|
47
|
+
/** How long an acknowledged write is re-applied over store events. */
|
|
48
|
+
export declare const ACKNOWLEDGED_WRITE_GRACE_MS = 5000;
|
|
49
|
+
/** A write that has not settled after this long is retried. */
|
|
50
|
+
export declare const STUCK_WRITE_TIMEOUT_MS = 60000;
|
|
51
|
+
/** A patch deleting more fields than this is sent as a whole document instead. */
|
|
52
|
+
export declare const MAX_MERGE_PATCH_TOMBSTONES = 64;
|
|
53
|
+
/** The first retry after a failed write waits a random time in this range. */
|
|
54
|
+
export declare const INITIAL_WRITE_RETRY_JITTER_MS: readonly [number, number];
|
|
55
|
+
/** Later retries: `min(MAX, BASE · 2^(failures − 2))`. */
|
|
56
|
+
export declare const WRITE_RETRY_BASE_MS = 2000;
|
|
57
|
+
export declare const WRITE_RETRY_MAX_MS = 30000;
|
|
58
|
+
/** Retries when the store says it is overloaded: `min(MAX, BASE · 2^(failures − 1))`. */
|
|
59
|
+
export declare const BACKPRESSURE_RETRY_BASE_MS = 1000;
|
|
60
|
+
export declare const BACKPRESSURE_RETRY_MAX_MS = 8000;
|
|
61
|
+
/** Overload lasting this long shows as an error. */
|
|
62
|
+
export declare const BACKPRESSURE_ERROR_AFTER_MS = 30000;
|
|
63
|
+
/** Shortest timer the engine sets. */
|
|
64
|
+
export declare const MIN_SYNC_TIMER_DELAY_MS = 16;
|
|
65
|
+
/** Acknowledged writes kept per document, at most. */
|
|
66
|
+
export declare const MAX_UNCOALESCED_ACKNOWLEDGED_WRITES = 8;
|
|
67
|
+
/** Write calls in flight at once, at most. */
|
|
68
|
+
export declare const MAX_CONCURRENT_LIVE_WRITES = 25;
|
|
69
|
+
/** Documents per write call, at most (the store allows 500). */
|
|
70
|
+
export declare const MAX_WRITES_PER_BATCH = 100;
|
|
71
|
+
/** Approximate bytes per write call, at most (one larger document still goes alone). */
|
|
72
|
+
export declare const MAX_BATCH_BYTES = 1048576;
|
|
73
|
+
/** Quiet time before the saved copy is updated after the store's documents change. */
|
|
74
|
+
export declare const LIVE_CACHE_WRITE_DELAY_MS = 2000;
|
|
75
|
+
/** One document's data. */
|
|
76
|
+
export type DocumentValue = Record<string, unknown>;
|
|
77
|
+
/** Documents by path. */
|
|
78
|
+
export type DocumentMap = ReadonlyMap<string, DocumentValue>;
|
|
79
|
+
/**
|
|
80
|
+
* How a value maps to documents. `C` is what composing learns that the next
|
|
81
|
+
* split needs (the board's order slots of missing elements).
|
|
82
|
+
*/
|
|
83
|
+
export interface LiveCodec<T, C = unknown> {
|
|
84
|
+
/** Collections the value lives in, in write order (elements before `board`). */
|
|
85
|
+
readonly collections: readonly string[];
|
|
86
|
+
/** The document that lists the order; written after its collection's documents. */
|
|
87
|
+
readonly metaPath: string;
|
|
88
|
+
/**
|
|
89
|
+
* Documents may hold `null` values. A change that sets one is written
|
|
90
|
+
* whole (`set`), since a merge patch's `null` removes the field.
|
|
91
|
+
*/
|
|
92
|
+
readonly keepsNulls?: boolean;
|
|
93
|
+
/** Splits a value into documents; `previous` lends identity and records the value does not carry. Returns a new map. */
|
|
94
|
+
decompose(value: T, previous: DocumentMap | undefined, carry: C | undefined): Map<string, DocumentValue>;
|
|
95
|
+
/** Builds the value from documents (the map is the engine's: copy what the value keeps). */
|
|
96
|
+
compose(documents: DocumentMap): {
|
|
97
|
+
value: T;
|
|
98
|
+
carry?: C;
|
|
99
|
+
};
|
|
100
|
+
/** Documents always written whole. */
|
|
101
|
+
replaceOnly(path: string): boolean;
|
|
102
|
+
/** Why a document may not be written (too large…), or `undefined`. */
|
|
103
|
+
refuse(path: string, value: unknown, totalBytes: number): string | undefined;
|
|
104
|
+
/** Keeps unchanged parts of `previous` in `next` (identity); returns `previous` when equal. */
|
|
105
|
+
share?(previous: T, next: T): T;
|
|
106
|
+
}
|
|
107
|
+
/**
|
|
108
|
+
* Whether the first snapshot has arrived: `loading`, `cached` (the store
|
|
109
|
+
* has not answered; the saved copy is shown and loading goes on), `live`
|
|
110
|
+
* or `failed`.
|
|
111
|
+
*/
|
|
112
|
+
export type LiveLoadState = 'loading' | 'cached' | 'live' | 'failed';
|
|
113
|
+
/**
|
|
114
|
+
* The sync status: `loading`, `cached` (showing the saved copy while the
|
|
115
|
+
* store is out of reach), `ready` (all synced), `dirty` (edits waiting),
|
|
116
|
+
* `saving` (writes in flight), `offline` (the store is unreachable;
|
|
117
|
+
* retrying), `error` (load failed, access lost or a document parked) or
|
|
118
|
+
* `readonly`.
|
|
119
|
+
*/
|
|
120
|
+
export type LiveStatus = 'loading' | 'cached' | 'ready' | 'dirty' | 'saving' | 'offline' | 'error' | 'readonly';
|
|
121
|
+
/** The last failure. */
|
|
122
|
+
export interface LiveSyncError {
|
|
123
|
+
code: SyncErrorCode | 'refused';
|
|
124
|
+
message: string;
|
|
125
|
+
path?: string;
|
|
126
|
+
}
|
|
127
|
+
/** A one-time message for a toast (a new `id` means a new notice). */
|
|
128
|
+
export interface LiveNotice {
|
|
129
|
+
id: number;
|
|
130
|
+
message: string;
|
|
131
|
+
}
|
|
132
|
+
/** Everything the UI reads. The object is replaced only when something changed. */
|
|
133
|
+
export interface LiveSnapshot<T> {
|
|
134
|
+
readonly value: T;
|
|
135
|
+
readonly loadState: LiveLoadState;
|
|
136
|
+
readonly status: LiveStatus;
|
|
137
|
+
/** Status text in English (the UI may localize from `status` and the counts). */
|
|
138
|
+
readonly message: string;
|
|
139
|
+
/** A second line for the status (what to do). */
|
|
140
|
+
readonly hint?: string;
|
|
141
|
+
/** Clicking the status may help ({@link LiveStore.retry}). */
|
|
142
|
+
readonly retryable: boolean;
|
|
143
|
+
readonly readOnly: boolean;
|
|
144
|
+
/** Documents with unsent or in-flight changes. */
|
|
145
|
+
readonly pending: number;
|
|
146
|
+
/** Write calls in flight. */
|
|
147
|
+
readonly flights: number;
|
|
148
|
+
/** Why a document the codec refused cannot be stored (while it stays unsent). */
|
|
149
|
+
readonly refusal?: string;
|
|
150
|
+
readonly notice?: LiveNotice;
|
|
151
|
+
readonly lastSyncedAt?: number;
|
|
152
|
+
readonly lastError?: LiveSyncError;
|
|
153
|
+
}
|
|
154
|
+
/** What a change notification says. */
|
|
155
|
+
export interface LiveChange<T> {
|
|
156
|
+
/** The value changed because of someone else's edit (or a reload). */
|
|
157
|
+
readonly remote: boolean;
|
|
158
|
+
/** The value changed (otherwise only the status did). */
|
|
159
|
+
readonly valueChanged: boolean;
|
|
160
|
+
/** The value before the change. */
|
|
161
|
+
readonly previous: T;
|
|
162
|
+
}
|
|
163
|
+
/**
|
|
164
|
+
* The saved copy on this device: the documents the store last confirmed.
|
|
165
|
+
* Both calls are synchronous and may fail quietly (storage full or off).
|
|
166
|
+
*/
|
|
167
|
+
export interface LiveCache {
|
|
168
|
+
/** The saved documents, or `undefined` when there is no saved copy. */
|
|
169
|
+
read(): SyncDocument[] | undefined;
|
|
170
|
+
/** Replaces the saved copy. */
|
|
171
|
+
write(documents: SyncDocument[]): void;
|
|
172
|
+
}
|
|
173
|
+
/** Options of {@link createLiveStore}. */
|
|
174
|
+
export interface LiveStoreOptions<T, C = unknown> {
|
|
175
|
+
transport: SyncTransport;
|
|
176
|
+
/** Keeps a saved copy to show when the store is out of reach. */
|
|
177
|
+
cache?: LiveCache;
|
|
178
|
+
codec: LiveCodec<T, C>;
|
|
179
|
+
/** The value shown until the first snapshot arrives. */
|
|
180
|
+
initial: T;
|
|
181
|
+
/** Viewers never write. */
|
|
182
|
+
readOnly?: boolean;
|
|
183
|
+
timers?: SyncTimers;
|
|
184
|
+
/** Formats the "synced at" time of the ready message. */
|
|
185
|
+
formatTime?: (epochMs: number) => string;
|
|
186
|
+
}
|
|
187
|
+
/** A live, synced value. */
|
|
188
|
+
export interface LiveStore<T> {
|
|
189
|
+
/** The current snapshot (same object until something changes). */
|
|
190
|
+
getSnapshot(): LiveSnapshot<T>;
|
|
191
|
+
/** The current value. */
|
|
192
|
+
value(): T;
|
|
193
|
+
/** Listens to changes; returns an unsubscribe function. */
|
|
194
|
+
subscribe(listener: (change: LiveChange<T>) => void): () => void;
|
|
195
|
+
/** Applies a local edit; `false` when editing is not possible (loading, read-only, stopped). */
|
|
196
|
+
commit(next: T): boolean;
|
|
197
|
+
/** True when {@link LiveStore.commit} would be accepted. */
|
|
198
|
+
canEdit(): boolean;
|
|
199
|
+
/** Writes everything now; resolves when nothing more can be sent. */
|
|
200
|
+
flush(): Promise<void>;
|
|
201
|
+
/**
|
|
202
|
+
* Resolves once the local changes of these documents are stored (or were
|
|
203
|
+
* dropped because someone deleted the document); rejects with a
|
|
204
|
+
* {@link LiveWriteError} when one is refused, writing stops (access lost,
|
|
205
|
+
* read-only) or the store is disposed.
|
|
206
|
+
*/
|
|
207
|
+
whenWritten(paths: readonly string[]): Promise<void>;
|
|
208
|
+
/**
|
|
209
|
+
* Writes a batch at once, outside the debounce (a write guarded by
|
|
210
|
+
* `ifMatch`, say), after the local changes of its documents are stored.
|
|
211
|
+
* On success the documents show the result; a failure is not retried and
|
|
212
|
+
* rejects with the store's error.
|
|
213
|
+
*/
|
|
214
|
+
writeNow(writes: readonly SyncWrite[]): Promise<void>;
|
|
215
|
+
/** Retries a failed load, parked documents and backed-off writes now. */
|
|
216
|
+
retry(): void;
|
|
217
|
+
/** Switches viewer mode. */
|
|
218
|
+
setReadOnly(readOnly: boolean): void;
|
|
219
|
+
/** Bytes of every document, as the store counts them. */
|
|
220
|
+
documentBytes(): number;
|
|
221
|
+
/** Stops syncing (call {@link LiveStore.flush} first to send pending edits). */
|
|
222
|
+
dispose(): void;
|
|
223
|
+
}
|
|
224
|
+
/** Why {@link LiveStore.whenWritten} rejected. */
|
|
225
|
+
export declare class LiveWriteError extends Error {
|
|
226
|
+
readonly code: SyncErrorCode | 'refused' | 'readonly' | 'disposed';
|
|
227
|
+
readonly path: string | undefined;
|
|
228
|
+
constructor(code: LiveWriteError['code'], message: string, path?: string);
|
|
229
|
+
}
|
|
230
|
+
/** Status and notice texts (English defaults). */
|
|
231
|
+
export declare const LIVE_MESSAGES: {
|
|
232
|
+
readonly loading: "Loading the latest content…";
|
|
233
|
+
readonly loadingSlow: "Still loading the latest content…";
|
|
234
|
+
readonly loadFailed: "The latest content failed to load. Click to retry.";
|
|
235
|
+
readonly cached: "Showing your saved copy. Reconnecting…";
|
|
236
|
+
readonly cachedEdits: "Showing your saved copy. Your changes will sync when you’re back online.";
|
|
237
|
+
readonly cachedReadOnly: "Showing a saved copy. Reconnecting…";
|
|
238
|
+
readonly readOnly: "Read-only. You’re seeing live changes.";
|
|
239
|
+
readonly accessEnded: "Live sync ended for this view. Reload to continue.";
|
|
240
|
+
readonly parkedSuffix: "Other changes keep syncing.";
|
|
241
|
+
readonly refusedHint: "Shorten it to resume syncing this item.";
|
|
242
|
+
readonly retryHint: "Click to retry.";
|
|
243
|
+
readonly unreachableNow: "The store is unreachable. Retrying now. Your edits are kept on this screen.";
|
|
244
|
+
readonly unreachableLater: "The store is unreachable. Retrying shortly; click to retry now. Your edits are kept on this screen.";
|
|
245
|
+
readonly busy: "The store is busy. Your edits are kept on this screen and will sync when it recovers.";
|
|
246
|
+
readonly saving: "Syncing…";
|
|
247
|
+
readonly syncedHint: "Edits sync as you go; if two people change the same thing, the last change wins.";
|
|
248
|
+
readonly itemGone: "An item you were editing was deleted by someone else.";
|
|
249
|
+
readonly cannotStore: (why: string) => string;
|
|
250
|
+
readonly waiting: (count: number) => string;
|
|
251
|
+
readonly syncedAt: (time: string) => string;
|
|
252
|
+
readonly synced: "Synced.";
|
|
253
|
+
};
|
|
254
|
+
/**
|
|
255
|
+
* Drops the parts of a patch that recurse into an object field the store now
|
|
256
|
+
* holds as a non-object: merging them would build a half object.
|
|
257
|
+
*/
|
|
258
|
+
export declare function dropShapeConflicts(patch: Record<string, unknown>, server: Record<string, unknown> | undefined): Record<string, unknown>;
|
|
259
|
+
/** Creates a live store; loading starts at once. */
|
|
260
|
+
export declare function createLiveStore<T, C = unknown>(options: LiveStoreOptions<T, C>): LiveStore<T>;
|