@baukit/data-contracts 0.7.1 → 0.7.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/dist/erasure.d.ts +1 -1
- package/dist/erasure.d.ts.map +1 -1
- package/package.json +2 -1
- package/src/contracts.ts +160 -0
- package/src/durable-draft.test.ts +1214 -0
- package/src/durable-draft.ts +502 -0
- package/src/erasure.test.ts +229 -0
- package/src/erasure.ts +162 -0
- package/src/export.test.ts +167 -0
- package/src/export.ts +164 -0
- package/src/identity.test.ts +465 -0
- package/src/identity.ts +637 -0
- package/src/import-envelope.test.ts +290 -0
- package/src/import-envelope.ts +264 -0
- package/src/import-envelope.vitest.ts +115 -0
- package/src/index.ts +7 -0
- package/src/limits-policy.test.ts +145 -0
- package/src/limits.test.ts +170 -0
- package/src/limits.ts +329 -0
- package/src/memory.test.ts +49 -0
- package/src/memory.ts +375 -0
- package/src/revisioned-drafts.fixture.test.ts +247 -0
- package/src/revisioned-writes.test.ts +684 -0
- package/src/revisioned-writes.ts +374 -0
- package/src/vitest.ts +614 -0
- package/src/web-storage.test.ts +95 -0
- package/src/web-storage.ts +88 -0
package/src/memory.ts
ADDED
|
@@ -0,0 +1,375 @@
|
|
|
1
|
+
import {
|
|
2
|
+
DEFAULT_PAGE_SIZE,
|
|
3
|
+
MAX_PAGE_SIZE,
|
|
4
|
+
type JsonValue,
|
|
5
|
+
type KeyValueStore,
|
|
6
|
+
type Page,
|
|
7
|
+
type PageOptions,
|
|
8
|
+
type RecordStore,
|
|
9
|
+
type ReentrantStorageTransaction,
|
|
10
|
+
type SchemaMeta,
|
|
11
|
+
type SchemaMetadataStore,
|
|
12
|
+
type SchemaMigrationHook,
|
|
13
|
+
type StoredRecord,
|
|
14
|
+
StorageError,
|
|
15
|
+
type TransactionalStorageStore,
|
|
16
|
+
normalizeStorageError,
|
|
17
|
+
} from './contracts.js';
|
|
18
|
+
|
|
19
|
+
const CURSOR_PREFIX = 'bk1:';
|
|
20
|
+
|
|
21
|
+
function cloneUnknown(value: unknown): unknown {
|
|
22
|
+
if (Array.isArray(value)) {
|
|
23
|
+
return value.map((item: unknown) => cloneUnknown(item));
|
|
24
|
+
}
|
|
25
|
+
if (value !== null && typeof value === 'object') {
|
|
26
|
+
return Object.fromEntries(
|
|
27
|
+
Object.entries(value as Record<string, unknown>).map(([key, item]) => [
|
|
28
|
+
key,
|
|
29
|
+
cloneUnknown(item),
|
|
30
|
+
]),
|
|
31
|
+
);
|
|
32
|
+
}
|
|
33
|
+
return value;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function clone<T>(value: T): T {
|
|
37
|
+
return cloneUnknown(value) as T;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function compareIds(left: string, right: string): number {
|
|
41
|
+
return left < right ? -1 : left > right ? 1 : 0;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function pageLimit(options?: PageOptions): number {
|
|
45
|
+
const limit = options?.limit ?? DEFAULT_PAGE_SIZE;
|
|
46
|
+
if (!Number.isInteger(limit) || limit < 1 || limit > MAX_PAGE_SIZE) {
|
|
47
|
+
throw new RangeError(`Page limit must be an integer from 1 to ${String(MAX_PAGE_SIZE)}.`);
|
|
48
|
+
}
|
|
49
|
+
return limit;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function encodeCursor(id: string): string {
|
|
53
|
+
return `${CURSOR_PREFIX}${encodeURIComponent(id)}`;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function decodeCursor(cursor: string): string {
|
|
57
|
+
if (!cursor.startsWith(CURSOR_PREFIX)) {
|
|
58
|
+
throw new TypeError('Invalid record cursor.');
|
|
59
|
+
}
|
|
60
|
+
try {
|
|
61
|
+
return decodeURIComponent(cursor.slice(CURSOR_PREFIX.length));
|
|
62
|
+
} catch {
|
|
63
|
+
throw new TypeError('Invalid record cursor.');
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
interface KeyValueState {
|
|
68
|
+
values: Map<string, JsonValue>;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
interface RecordState<T extends StoredRecord> {
|
|
72
|
+
values: Map<string, T>;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
interface MetadataState {
|
|
76
|
+
value: SchemaMeta | undefined;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
interface MemoryState<T extends StoredRecord> {
|
|
80
|
+
keyValues: KeyValueState;
|
|
81
|
+
records: RecordState<T>;
|
|
82
|
+
schemaMetadata: MetadataState;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
interface MemoryLifecycle {
|
|
86
|
+
status: 'closed' | 'closing' | 'open';
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
function assertStoreOpen(lifecycle: MemoryLifecycle): void {
|
|
90
|
+
if (lifecycle.status !== 'open') {
|
|
91
|
+
throw new StorageError('storage_closed', 'The storage adapter is closed.');
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function emptyState<T extends StoredRecord>(): MemoryState<T> {
|
|
96
|
+
return {
|
|
97
|
+
keyValues: { values: new Map() },
|
|
98
|
+
records: { values: new Map() },
|
|
99
|
+
schemaMetadata: { value: undefined },
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
function copyState<T extends StoredRecord>(state: MemoryState<T>): MemoryState<T> {
|
|
104
|
+
return {
|
|
105
|
+
keyValues: {
|
|
106
|
+
values: new Map([...state.keyValues.values].map(([key, value]) => [key, clone(value)])),
|
|
107
|
+
},
|
|
108
|
+
records: {
|
|
109
|
+
values: new Map([...state.records.values].map(([key, value]) => [key, clone(value)])),
|
|
110
|
+
},
|
|
111
|
+
schemaMetadata: {
|
|
112
|
+
value:
|
|
113
|
+
state.schemaMetadata.value === undefined ? undefined : clone(state.schemaMetadata.value),
|
|
114
|
+
},
|
|
115
|
+
};
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** Dependency-free reference key/value adapter. */
|
|
119
|
+
export class InMemoryKeyValueStore implements KeyValueStore {
|
|
120
|
+
public constructor(
|
|
121
|
+
private readonly state: KeyValueState = { values: new Map() },
|
|
122
|
+
private readonly assertAvailable: () => void = () => undefined,
|
|
123
|
+
) {}
|
|
124
|
+
|
|
125
|
+
public get(key: string): Promise<JsonValue | undefined> {
|
|
126
|
+
return Promise.resolve().then(() => {
|
|
127
|
+
this.assertAvailable();
|
|
128
|
+
const value = this.state.values.get(key);
|
|
129
|
+
return value === undefined ? undefined : clone(value);
|
|
130
|
+
});
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
public set(key: string, value: JsonValue): Promise<void> {
|
|
134
|
+
return Promise.resolve().then(() => {
|
|
135
|
+
this.assertAvailable();
|
|
136
|
+
this.state.values.set(key, clone(value));
|
|
137
|
+
});
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
public delete(key: string): Promise<void> {
|
|
141
|
+
return Promise.resolve().then(() => {
|
|
142
|
+
this.assertAvailable();
|
|
143
|
+
this.state.values.delete(key);
|
|
144
|
+
});
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
public clear(): Promise<void> {
|
|
148
|
+
return Promise.resolve().then(() => {
|
|
149
|
+
this.assertAvailable();
|
|
150
|
+
this.state.values.clear();
|
|
151
|
+
});
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
public clearPrefix(prefix: string): Promise<void> {
|
|
155
|
+
return Promise.resolve().then(() => {
|
|
156
|
+
this.assertAvailable();
|
|
157
|
+
for (const key of [...this.state.values.keys()]) {
|
|
158
|
+
if (key.startsWith(prefix)) {
|
|
159
|
+
this.state.values.delete(key);
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
});
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/** Dependency-free reference record adapter using ID-based keyset cursors. */
|
|
167
|
+
export class InMemoryRecordStore<T extends StoredRecord> implements RecordStore<T> {
|
|
168
|
+
public constructor(
|
|
169
|
+
private readonly state: RecordState<T> = { values: new Map() },
|
|
170
|
+
private readonly assertAvailable: () => void = () => undefined,
|
|
171
|
+
) {}
|
|
172
|
+
|
|
173
|
+
public put(record: T): Promise<void> {
|
|
174
|
+
return Promise.resolve().then(() => {
|
|
175
|
+
this.assertAvailable();
|
|
176
|
+
if (record.id.length === 0) {
|
|
177
|
+
throw new TypeError('Record id must not be empty.');
|
|
178
|
+
}
|
|
179
|
+
this.state.values.set(record.id, clone(record));
|
|
180
|
+
});
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
public get(id: string): Promise<T | undefined> {
|
|
184
|
+
return Promise.resolve().then(() => {
|
|
185
|
+
this.assertAvailable();
|
|
186
|
+
const record = this.state.values.get(id);
|
|
187
|
+
return record === undefined ? undefined : clone(record);
|
|
188
|
+
});
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
public delete(id: string): Promise<void> {
|
|
192
|
+
return Promise.resolve().then(() => {
|
|
193
|
+
this.assertAvailable();
|
|
194
|
+
this.state.values.delete(id);
|
|
195
|
+
});
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
public list(options?: PageOptions): Promise<Page<T>> {
|
|
199
|
+
return Promise.resolve().then(() => {
|
|
200
|
+
this.assertAvailable();
|
|
201
|
+
const limit = pageLimit(options);
|
|
202
|
+
const afterId =
|
|
203
|
+
options?.cursor === undefined || options.cursor === null
|
|
204
|
+
? undefined
|
|
205
|
+
: decodeCursor(options.cursor);
|
|
206
|
+
const ordered = [...this.state.values.values()]
|
|
207
|
+
.filter((record) => afterId === undefined || compareIds(record.id, afterId) > 0)
|
|
208
|
+
.sort((left, right) => compareIds(left.id, right.id));
|
|
209
|
+
const pageItems = ordered.slice(0, limit);
|
|
210
|
+
const last = pageItems.at(-1);
|
|
211
|
+
|
|
212
|
+
return {
|
|
213
|
+
items: clone(pageItems),
|
|
214
|
+
nextCursor: ordered.length > limit && last !== undefined ? encodeCursor(last.id) : null,
|
|
215
|
+
};
|
|
216
|
+
});
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
/** Dependency-free reference schema metadata adapter. */
|
|
221
|
+
export class InMemorySchemaMetadataStore implements SchemaMetadataStore {
|
|
222
|
+
public constructor(
|
|
223
|
+
private readonly state: MetadataState = { value: undefined },
|
|
224
|
+
private readonly assertAvailable: () => void = () => undefined,
|
|
225
|
+
) {}
|
|
226
|
+
|
|
227
|
+
public getSchemaMeta(): Promise<SchemaMeta | undefined> {
|
|
228
|
+
return Promise.resolve().then(() => {
|
|
229
|
+
this.assertAvailable();
|
|
230
|
+
return this.state.value === undefined ? undefined : clone(this.state.value);
|
|
231
|
+
});
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
public setSchemaMeta(metadata: SchemaMeta): Promise<void> {
|
|
235
|
+
return Promise.resolve().then(() => {
|
|
236
|
+
this.assertAvailable();
|
|
237
|
+
if (metadata.name.length === 0) {
|
|
238
|
+
throw new TypeError('Schema name must not be empty.');
|
|
239
|
+
}
|
|
240
|
+
if (!Number.isInteger(metadata.version) || metadata.version < 0) {
|
|
241
|
+
throw new TypeError('Schema version must be a non-negative integer.');
|
|
242
|
+
}
|
|
243
|
+
this.state.value = clone(metadata);
|
|
244
|
+
});
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
/** A transaction-scoped in-memory view. It must not be retained after the callback. */
|
|
249
|
+
export class InMemoryTransaction<T extends StoredRecord> implements ReentrantStorageTransaction<T> {
|
|
250
|
+
public readonly keyValues: InMemoryKeyValueStore;
|
|
251
|
+
public readonly records: InMemoryRecordStore<T>;
|
|
252
|
+
public readonly schemaMetadata: InMemorySchemaMetadataStore;
|
|
253
|
+
|
|
254
|
+
private active = true;
|
|
255
|
+
|
|
256
|
+
public constructor(
|
|
257
|
+
protected readonly state: MemoryState<T>,
|
|
258
|
+
assertAvailable?: () => void,
|
|
259
|
+
) {
|
|
260
|
+
const assertTransactionActive =
|
|
261
|
+
assertAvailable ??
|
|
262
|
+
(() => {
|
|
263
|
+
if (!this.active) {
|
|
264
|
+
throw new StorageError('storage_closed', 'The transaction context is no longer active.');
|
|
265
|
+
}
|
|
266
|
+
});
|
|
267
|
+
this.keyValues = new InMemoryKeyValueStore(state.keyValues, assertTransactionActive);
|
|
268
|
+
this.records = new InMemoryRecordStore(state.records, assertTransactionActive);
|
|
269
|
+
this.schemaMetadata = new InMemorySchemaMetadataStore(
|
|
270
|
+
state.schemaMetadata,
|
|
271
|
+
assertTransactionActive,
|
|
272
|
+
);
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
public withTransaction<TResult>(
|
|
276
|
+
operation: (context: ReentrantStorageTransaction<T>) => Promise<TResult> | TResult,
|
|
277
|
+
): Promise<TResult> {
|
|
278
|
+
return Promise.resolve().then(() => {
|
|
279
|
+
if (!this.active) {
|
|
280
|
+
throw new StorageError('storage_closed', 'The transaction context is no longer active.');
|
|
281
|
+
}
|
|
282
|
+
return operation(this);
|
|
283
|
+
});
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
public finish(): void {
|
|
287
|
+
this.active = false;
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
/** Composite reference adapter with snapshot-backed atomic transactions. */
|
|
292
|
+
export class InMemoryStore<T extends StoredRecord>
|
|
293
|
+
extends InMemoryTransaction<T>
|
|
294
|
+
implements TransactionalStorageStore<T>, SchemaMigrationHook
|
|
295
|
+
{
|
|
296
|
+
private transactionTail: Promise<void> = Promise.resolve();
|
|
297
|
+
private readonly lifecycle: MemoryLifecycle;
|
|
298
|
+
|
|
299
|
+
public constructor(state: MemoryState<T> = emptyState()) {
|
|
300
|
+
const lifecycle: MemoryLifecycle = { status: 'open' };
|
|
301
|
+
super(state, () => {
|
|
302
|
+
assertStoreOpen(lifecycle);
|
|
303
|
+
});
|
|
304
|
+
this.lifecycle = lifecycle;
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
public override async withTransaction<TResult>(
|
|
308
|
+
operation: (context: ReentrantStorageTransaction<T>) => Promise<TResult> | TResult,
|
|
309
|
+
): Promise<TResult> {
|
|
310
|
+
assertStoreOpen(this.lifecycle);
|
|
311
|
+
const previous = this.transactionTail;
|
|
312
|
+
let release = (): void => undefined;
|
|
313
|
+
this.transactionTail = new Promise<void>((resolve) => {
|
|
314
|
+
release = resolve;
|
|
315
|
+
});
|
|
316
|
+
await previous;
|
|
317
|
+
|
|
318
|
+
let transaction: InMemoryTransaction<T> | undefined;
|
|
319
|
+
try {
|
|
320
|
+
assertStoreOpen(this.lifecycle);
|
|
321
|
+
const pending = copyState(this.state);
|
|
322
|
+
transaction = new InMemoryTransaction(pending);
|
|
323
|
+
const result = await operation(transaction);
|
|
324
|
+
this.state.keyValues.values = pending.keyValues.values;
|
|
325
|
+
this.state.records.values = pending.records.values;
|
|
326
|
+
this.state.schemaMetadata.value = pending.schemaMetadata.value;
|
|
327
|
+
return result;
|
|
328
|
+
} catch (cause) {
|
|
329
|
+
throw normalizeStorageError(cause);
|
|
330
|
+
} finally {
|
|
331
|
+
transaction?.finish();
|
|
332
|
+
release();
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
public async close(): Promise<void> {
|
|
337
|
+
if (this.lifecycle.status === 'closed') {
|
|
338
|
+
return;
|
|
339
|
+
}
|
|
340
|
+
this.lifecycle.status = 'closing';
|
|
341
|
+
await this.transactionTail;
|
|
342
|
+
this.lifecycle.status = 'closed';
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
public async migrate(from: SchemaMeta, to: SchemaMeta): Promise<void> {
|
|
346
|
+
const current = await this.schemaMetadata.getSchemaMeta();
|
|
347
|
+
if (current?.name !== from.name || current.version !== from.version) {
|
|
348
|
+
throw new Error('Current schema metadata does not match the migration source.');
|
|
349
|
+
}
|
|
350
|
+
if (from.name !== to.name) {
|
|
351
|
+
throw new Error('A migration cannot change the schema name.');
|
|
352
|
+
}
|
|
353
|
+
if (to.version <= from.version) {
|
|
354
|
+
throw new Error('A migration target version must be greater than its source.');
|
|
355
|
+
}
|
|
356
|
+
await this.schemaMetadata.setSchemaMeta(to);
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
/** Named persistent backing for exercising close/reopen identity transitions in memory. */
|
|
361
|
+
export class InMemoryStorePool<T extends StoredRecord> {
|
|
362
|
+
private readonly databases = new Map<string, MemoryState<T>>();
|
|
363
|
+
|
|
364
|
+
public open(storeName: string): InMemoryStore<T> {
|
|
365
|
+
if (storeName.trim().length === 0) {
|
|
366
|
+
throw new TypeError('Store name must not be empty.');
|
|
367
|
+
}
|
|
368
|
+
let state = this.databases.get(storeName);
|
|
369
|
+
if (state === undefined) {
|
|
370
|
+
state = emptyState();
|
|
371
|
+
this.databases.set(storeName, state);
|
|
372
|
+
}
|
|
373
|
+
return new InMemoryStore(state);
|
|
374
|
+
}
|
|
375
|
+
}
|
|
@@ -0,0 +1,247 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest';
|
|
2
|
+
|
|
3
|
+
import { InMemoryKeyValueStore, type JsonValue, type KeyValueStore } from '@baukit/data-contracts';
|
|
4
|
+
import {
|
|
5
|
+
type DraftCodec,
|
|
6
|
+
type DurableDraft,
|
|
7
|
+
createDurableDraft,
|
|
8
|
+
} from '@baukit/data-contracts/durable-draft';
|
|
9
|
+
import {
|
|
10
|
+
type RevisionedWriteQueue,
|
|
11
|
+
type RevisionedWriteRequest,
|
|
12
|
+
type RevisionedWriteResult,
|
|
13
|
+
createRevisionedWriteQueue,
|
|
14
|
+
} from '@baukit/data-contracts/revisioned-writes';
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* A plain-object editor that composes both helpers the way a product hook would: the draft keeps a
|
|
18
|
+
* crash-safe local copy, the queue sends revision-checked writes, and the draft is cleared only
|
|
19
|
+
* after the server acknowledged the exact local revision.
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
interface Scope {
|
|
23
|
+
readonly account: string;
|
|
24
|
+
readonly note: string;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
interface NoteDraft {
|
|
28
|
+
readonly body: string;
|
|
29
|
+
/** The server revision the local edits started from, like an ETag kept with the draft. */
|
|
30
|
+
readonly baseRevision: number;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
interface ServerConflict {
|
|
34
|
+
readonly body: string;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
type NoteQueue = RevisionedWriteQueue<string, string, string, number, ServerConflict>;
|
|
38
|
+
|
|
39
|
+
class FakeNoteServer {
|
|
40
|
+
readonly notes = new Map<string, { body: string; revision: number }>();
|
|
41
|
+
loseNextResponse = false;
|
|
42
|
+
|
|
43
|
+
seed(scope: Scope, body: string, revision: number): void {
|
|
44
|
+
this.notes.set(this.#key(scope.account, scope.note), { body, revision });
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
read(scope: Scope): { readonly body: string; readonly revision: number } {
|
|
48
|
+
return this.notes.get(this.#key(scope.account, scope.note)) ?? { body: '', revision: 0 };
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
readonly write = (
|
|
52
|
+
request: RevisionedWriteRequest<string, string, string, number>,
|
|
53
|
+
): Promise<RevisionedWriteResult<number, ServerConflict>> => {
|
|
54
|
+
const key = this.#key(request.scope, request.document);
|
|
55
|
+
const current = this.notes.get(key) ?? { body: '', revision: 0 };
|
|
56
|
+
if (current.revision !== request.expectedRevision) {
|
|
57
|
+
return Promise.resolve({
|
|
58
|
+
kind: 'conflict',
|
|
59
|
+
currentRevision: current.revision,
|
|
60
|
+
conflict: { body: current.body },
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
const next = { body: request.value, revision: current.revision + 1 };
|
|
64
|
+
this.notes.set(key, next);
|
|
65
|
+
if (this.loseNextResponse) {
|
|
66
|
+
this.loseNextResponse = false;
|
|
67
|
+
return Promise.reject(new Error('response lost'));
|
|
68
|
+
}
|
|
69
|
+
return Promise.resolve({ kind: 'accepted', revision: next.revision });
|
|
70
|
+
};
|
|
71
|
+
|
|
72
|
+
#key(account: string, note: string): string {
|
|
73
|
+
return `${account}/${note}`;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
const noteCodec: DraftCodec<NoteDraft> = {
|
|
78
|
+
version: 1,
|
|
79
|
+
encode: (value) => ({ body: value.body, baseRevision: value.baseRevision }),
|
|
80
|
+
decode(value: JsonValue) {
|
|
81
|
+
if (typeof value !== 'object' || value === null || Array.isArray(value)) {
|
|
82
|
+
return { kind: 'corrupt' };
|
|
83
|
+
}
|
|
84
|
+
const body = value['body'];
|
|
85
|
+
const baseRevision = value['baseRevision'];
|
|
86
|
+
if (typeof body !== 'string' || typeof baseRevision !== 'number') {
|
|
87
|
+
return { kind: 'corrupt' };
|
|
88
|
+
}
|
|
89
|
+
return { kind: 'decoded', value: { body, baseRevision } };
|
|
90
|
+
},
|
|
91
|
+
};
|
|
92
|
+
|
|
93
|
+
class NoteEditor {
|
|
94
|
+
readonly draft: DurableDraft<Scope, NoteDraft>;
|
|
95
|
+
readonly queue: NoteQueue;
|
|
96
|
+
|
|
97
|
+
constructor(
|
|
98
|
+
store: KeyValueStore,
|
|
99
|
+
private readonly server: FakeNoteServer,
|
|
100
|
+
private scope: Scope,
|
|
101
|
+
) {
|
|
102
|
+
this.draft = createDurableDraft({
|
|
103
|
+
store,
|
|
104
|
+
key: (next: Scope) => `note-draft:${next.account}:${next.note}`,
|
|
105
|
+
codec: noteCodec,
|
|
106
|
+
});
|
|
107
|
+
const loaded = server.read(scope);
|
|
108
|
+
this.queue = createRevisionedWriteQueue({
|
|
109
|
+
initial: {
|
|
110
|
+
scope: scope.account,
|
|
111
|
+
document: scope.note,
|
|
112
|
+
acknowledgedRevision: loaded.revision,
|
|
113
|
+
},
|
|
114
|
+
write: server.write,
|
|
115
|
+
});
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
get body(): string {
|
|
119
|
+
const snapshot = this.draft.getSnapshot();
|
|
120
|
+
return snapshot.open ? snapshot.value.body : '';
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
async start(): Promise<void> {
|
|
124
|
+
const loaded = this.server.read(this.scope);
|
|
125
|
+
this.queue.reset({
|
|
126
|
+
scope: this.scope.account,
|
|
127
|
+
document: this.scope.note,
|
|
128
|
+
acknowledgedRevision: loaded.revision,
|
|
129
|
+
});
|
|
130
|
+
await this.draft.open(this.scope, { body: loaded.body, baseRevision: loaded.revision });
|
|
131
|
+
const snapshot = this.draft.getSnapshot();
|
|
132
|
+
if (!snapshot.open || snapshot.recovery !== 'restored') {
|
|
133
|
+
return;
|
|
134
|
+
}
|
|
135
|
+
this.queue.reset({
|
|
136
|
+
scope: this.scope.account,
|
|
137
|
+
document: this.scope.note,
|
|
138
|
+
acknowledgedRevision: snapshot.value.baseRevision,
|
|
139
|
+
});
|
|
140
|
+
this.queue.enqueue(snapshot.value.body);
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
edit(body: string): void {
|
|
144
|
+
const baseRevision = this.queue.getSnapshot().acknowledgedRevision;
|
|
145
|
+
this.draft.update({ body, baseRevision });
|
|
146
|
+
this.queue.enqueue(body);
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
async tick(): Promise<void> {
|
|
150
|
+
await this.draft.save();
|
|
151
|
+
const draft = this.draft.getSnapshot();
|
|
152
|
+
if (!draft.open) {
|
|
153
|
+
return;
|
|
154
|
+
}
|
|
155
|
+
const written = await this.queue.flush();
|
|
156
|
+
if (written.status === 'idle' && written.scope === this.scope.account) {
|
|
157
|
+
await this.draft.clear({ reason: 'submitted', localRevision: draft.localRevision });
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
async switchTo(scope: Scope): Promise<void> {
|
|
162
|
+
this.scope = scope;
|
|
163
|
+
await this.start();
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
describe('revisioned drafts fixture', () => {
|
|
168
|
+
it('saves locally, writes to the server, then clears the draft', async () => {
|
|
169
|
+
const store = new InMemoryKeyValueStore();
|
|
170
|
+
const server = new FakeNoteServer();
|
|
171
|
+
server.seed({ account: 'a', note: 'n1' }, 'hello', 3);
|
|
172
|
+
const editor = new NoteEditor(store, server, { account: 'a', note: 'n1' });
|
|
173
|
+
await editor.start();
|
|
174
|
+
|
|
175
|
+
editor.edit('hello world');
|
|
176
|
+
await editor.tick();
|
|
177
|
+
|
|
178
|
+
expect(server.read({ account: 'a', note: 'n1' })).toEqual({ body: 'hello world', revision: 4 });
|
|
179
|
+
expect(editor.queue.getSnapshot()).toMatchObject({ status: 'idle', acknowledgedRevision: 4 });
|
|
180
|
+
expect(editor.draft.getSnapshot()).toMatchObject({ submission: 'confirmed', dirty: false });
|
|
181
|
+
await expect(store.get('note-draft:a:n1')).resolves.toBeUndefined();
|
|
182
|
+
});
|
|
183
|
+
|
|
184
|
+
it('recovers a draft after a lost response and reports the conflict it caused', async () => {
|
|
185
|
+
const store = new InMemoryKeyValueStore();
|
|
186
|
+
const server = new FakeNoteServer();
|
|
187
|
+
server.seed({ account: 'a', note: 'n1' }, 'v1', 1);
|
|
188
|
+
const first = new NoteEditor(store, server, { account: 'a', note: 'n1' });
|
|
189
|
+
await first.start();
|
|
190
|
+
first.edit('v2 local');
|
|
191
|
+
server.loseNextResponse = true;
|
|
192
|
+
await first.tick();
|
|
193
|
+
|
|
194
|
+
expect(first.queue.getSnapshot()).toMatchObject({
|
|
195
|
+
status: 'unknown-outcome',
|
|
196
|
+
uncertain: { value: 'v2 local', expectedRevision: 1 },
|
|
197
|
+
});
|
|
198
|
+
await expect(store.get('note-draft:a:n1')).resolves.toEqual({
|
|
199
|
+
version: 1,
|
|
200
|
+
value: { body: 'v2 local', baseRevision: 1 },
|
|
201
|
+
});
|
|
202
|
+
|
|
203
|
+
const reopened = new NoteEditor(store, server, { account: 'a', note: 'n1' });
|
|
204
|
+
await reopened.start();
|
|
205
|
+
expect(reopened.body).toBe('v2 local');
|
|
206
|
+
await reopened.tick();
|
|
207
|
+
|
|
208
|
+
expect(reopened.queue.getSnapshot()).toMatchObject({
|
|
209
|
+
status: 'conflict',
|
|
210
|
+
acknowledgedRevision: 1,
|
|
211
|
+
conflict: { currentRevision: 2, conflict: { body: 'v2 local' } },
|
|
212
|
+
});
|
|
213
|
+
expect(reopened.draft.getSnapshot()).toMatchObject({ dirty: false, submission: 'none' });
|
|
214
|
+
await expect(store.get('note-draft:a:n1')).resolves.toBeDefined();
|
|
215
|
+
});
|
|
216
|
+
|
|
217
|
+
it('keeps a late acknowledgement for one account out of the next account', async () => {
|
|
218
|
+
const store = new InMemoryKeyValueStore();
|
|
219
|
+
const server = new FakeNoteServer();
|
|
220
|
+
server.seed({ account: 'a', note: 'n1' }, 'a-body', 1);
|
|
221
|
+
server.seed({ account: 'b', note: 'n1' }, 'b-body', 9);
|
|
222
|
+
const editor = new NoteEditor(store, server, { account: 'a', note: 'n1' });
|
|
223
|
+
await editor.start();
|
|
224
|
+
|
|
225
|
+
editor.edit('a-edit');
|
|
226
|
+
await editor.draft.save();
|
|
227
|
+
const lateFlush = editor.queue.flush();
|
|
228
|
+
await editor.switchTo({ account: 'b', note: 'n1' });
|
|
229
|
+
editor.edit('b-edit');
|
|
230
|
+
await editor.draft.save();
|
|
231
|
+
await lateFlush;
|
|
232
|
+
|
|
233
|
+
expect(editor.queue.getSnapshot()).toMatchObject({
|
|
234
|
+
scope: 'b',
|
|
235
|
+
acknowledgedRevision: 9,
|
|
236
|
+
unsent: { value: 'b-edit' },
|
|
237
|
+
});
|
|
238
|
+
await expect(store.get('note-draft:b:n1')).resolves.toEqual({
|
|
239
|
+
version: 1,
|
|
240
|
+
value: { body: 'b-edit', baseRevision: 9 },
|
|
241
|
+
});
|
|
242
|
+
await expect(store.get('note-draft:a:n1')).resolves.toEqual({
|
|
243
|
+
version: 1,
|
|
244
|
+
value: { body: 'a-edit', baseRevision: 1 },
|
|
245
|
+
});
|
|
246
|
+
});
|
|
247
|
+
});
|