@baukit/data-contracts 0.18.3 → 0.19.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.
Files changed (41) hide show
  1. package/dist/identity-error.d.ts +9 -0
  2. package/dist/identity-error.d.ts.map +1 -0
  3. package/dist/identity-error.js +21 -0
  4. package/dist/identity-error.js.map +1 -0
  5. package/dist/identity.d.ts +2 -76
  6. package/dist/identity.d.ts.map +1 -1
  7. package/dist/identity.js +23 -248
  8. package/dist/identity.js.map +1 -1
  9. package/dist/import-envelope.d.ts.map +1 -1
  10. package/dist/import-envelope.js +6 -2
  11. package/dist/import-envelope.js.map +1 -1
  12. package/dist/index.d.ts +1 -0
  13. package/dist/index.d.ts.map +1 -1
  14. package/dist/index.js +1 -0
  15. package/dist/index.js.map +1 -1
  16. package/dist/limits.js +30 -28
  17. package/dist/limits.js.map +1 -1
  18. package/dist/scoped-lifecycle.d.ts +73 -0
  19. package/dist/scoped-lifecycle.d.ts.map +1 -0
  20. package/dist/scoped-lifecycle.js +216 -0
  21. package/dist/scoped-lifecycle.js.map +1 -0
  22. package/dist/scoped-persistence.vitest.d.ts +12 -0
  23. package/dist/scoped-persistence.vitest.d.ts.map +1 -0
  24. package/dist/scoped-persistence.vitest.js +171 -0
  25. package/dist/scoped-persistence.vitest.js.map +1 -0
  26. package/dist/vitest.d.ts +1 -9
  27. package/dist/vitest.d.ts.map +1 -1
  28. package/dist/vitest.js +111 -266
  29. package/dist/vitest.js.map +1 -1
  30. package/package.json +4 -3
  31. package/src/durable-draft.test.ts +1 -8
  32. package/src/identity-error.ts +30 -0
  33. package/src/identity.test.ts +1 -1
  34. package/src/identity.ts +36 -326
  35. package/src/import-envelope.test.ts +1 -4
  36. package/src/import-envelope.ts +9 -9
  37. package/src/index.ts +1 -0
  38. package/src/limits.ts +39 -32
  39. package/src/scoped-lifecycle.ts +290 -0
  40. package/src/scoped-persistence.vitest.ts +221 -0
  41. package/src/vitest.ts +124 -308
package/src/vitest.ts CHANGED
@@ -11,13 +11,9 @@ import {
11
11
  type Transaction,
12
12
  type TransactionalStorageStore,
13
13
  } from './contracts.js';
14
- import {
15
- InMemoryScopedPersistenceRegistryStore,
16
- ScopedPersistenceLifecycle,
17
- recheckServerSubjectBeforeSyncAdoption,
18
- } from './identity.js';
19
14
 
20
15
  export * from './import-envelope.vitest.js';
16
+ export * from './scoped-persistence.vitest.js';
21
17
 
22
18
  export type ContractStoreFactory<TStore> = () => Promise<TStore> | TStore;
23
19
 
@@ -227,135 +223,146 @@ export function describeTransactionalStorageContract(
227
223
  makeStore: ContractStoreFactory<TransactionalStorageStore<ContractTestRecord>>,
228
224
  ): void {
229
225
  describe('TransactionalStorageStore contract', () => {
230
- it('propagates results and atomically commits a compound write', async () => {
231
- const store = await makeStore();
232
- const result = await store.withTransaction(async (transaction) => {
233
- await transaction.keyValues.set('first', 1);
234
- await transaction.keyValues.set('second', 2);
235
- await transaction.records.put(RECORDS.first);
236
- await transaction.records.put(RECORDS.second);
237
- await transaction.schemaMetadata.setSchemaMeta({ name: 'contract', version: 1 });
238
- return { status: 'committed' } as const;
239
- });
240
- expect(result).toEqual({ status: 'committed' });
241
- expect(await store.keyValues.get('first')).toBe(1);
242
- expect(await store.keyValues.get('second')).toBe(2);
243
- expect((await store.records.list()).items).toEqual([RECORDS.first, RECORDS.second]);
244
- expect(await store.schemaMetadata.getSchemaMeta()).toEqual({
245
- name: 'contract',
246
- version: 1,
247
- });
248
- });
226
+ describeCompoundWriteCases(makeStore);
227
+ describeTransactionFailureCases(makeStore);
228
+ });
229
+ }
249
230
 
250
- it('rolls every compound write back when the callback throws', async () => {
251
- const store = await makeStore();
252
- await store.keyValues.set('preserved', 'before');
253
- await expect(
254
- store.withTransaction(async (transaction) => {
255
- await transaction.keyValues.set('preserved', 'after');
256
- await transaction.records.put(RECORDS.first);
257
- await transaction.schemaMetadata.setSchemaMeta({ name: 'contract', version: 1 });
258
- throw new Error('deliberate rollback');
259
- }),
260
- ).rejects.toThrow('deliberate rollback');
261
- expect(await store.keyValues.get('preserved')).toBe('before');
262
- expect(await store.records.get(RECORDS.first.id)).toBeUndefined();
263
- expect(await store.schemaMetadata.getSchemaMeta()).toBeUndefined();
231
+ function describeCompoundWriteCases(
232
+ makeStore: ContractStoreFactory<TransactionalStorageStore<ContractTestRecord>>,
233
+ ): void {
234
+ it('propagates results and atomically commits a compound write', async () => {
235
+ const store = await makeStore();
236
+ const result = await store.withTransaction(async (transaction) => {
237
+ await transaction.keyValues.set('first', 1);
238
+ await transaction.keyValues.set('second', 2);
239
+ await transaction.records.put(RECORDS.first);
240
+ await transaction.records.put(RECORDS.second);
241
+ await transaction.schemaMetadata.setSchemaMeta({ name: 'contract', version: 1 });
242
+ return { status: 'committed' } as const;
264
243
  });
244
+ expect(result).toEqual({ status: 'committed' });
245
+ expect(await store.keyValues.get('first')).toBe(1);
246
+ expect(await store.keyValues.get('second')).toBe(2);
247
+ expect((await store.records.list()).items).toEqual([RECORDS.first, RECORDS.second]);
248
+ expect(await store.schemaMetadata.getSchemaMeta()).toEqual({
249
+ name: 'contract',
250
+ version: 1,
251
+ });
252
+ });
265
253
 
266
- it('commits a record and outbox-shaped entry together', async () => {
267
- const store = await makeStore();
268
- await store.withTransaction(async (transaction) => {
254
+ it('rolls every compound write back when the callback throws', async () => {
255
+ const store = await makeStore();
256
+ await store.keyValues.set('preserved', 'before');
257
+ await expect(
258
+ store.withTransaction(async (transaction) => {
259
+ await transaction.keyValues.set('preserved', 'after');
269
260
  await transaction.records.put(RECORDS.first);
270
- await transaction.keyValues.set('outbox:mutation-1', {
271
- entityId: RECORDS.first.id,
272
- operation: 'put',
273
- });
274
- });
275
- expect(await store.records.get(RECORDS.first.id)).toEqual(RECORDS.first);
276
- expect(await store.keyValues.get('outbox:mutation-1')).toEqual({
261
+ await transaction.schemaMetadata.setSchemaMeta({ name: 'contract', version: 1 });
262
+ throw new Error('deliberate rollback');
263
+ }),
264
+ ).rejects.toThrow('deliberate rollback');
265
+ expect(await store.keyValues.get('preserved')).toBe('before');
266
+ expect(await store.records.get(RECORDS.first.id)).toBeUndefined();
267
+ expect(await store.schemaMetadata.getSchemaMeta()).toBeUndefined();
268
+ });
269
+
270
+ it('commits a record and outbox-shaped entry together', async () => {
271
+ const store = await makeStore();
272
+ await store.withTransaction(async (transaction) => {
273
+ await transaction.records.put(RECORDS.first);
274
+ await transaction.keyValues.set('outbox:mutation-1', {
277
275
  entityId: RECORDS.first.id,
278
276
  operation: 'put',
279
277
  });
280
278
  });
279
+ expect(await store.records.get(RECORDS.first.id)).toEqual(RECORDS.first);
280
+ expect(await store.keyValues.get('outbox:mutation-1')).toEqual({
281
+ entityId: RECORDS.first.id,
282
+ operation: 'put',
283
+ });
284
+ });
281
285
 
282
- it('joins nested calls made through the ambient transaction context', async () => {
283
- const store = await makeStore();
284
- const result = await store.withTransaction(async (transaction) => {
285
- await transaction.records.put(RECORDS.first);
286
- return transaction.withTransaction(async (nested) => {
287
- expect(nested).toBe(transaction);
288
- await nested.keyValues.set('nested', true);
289
- await nested.schemaMetadata.setSchemaMeta({ name: 'contract', version: 1 });
290
- return 'nested-result';
291
- });
286
+ it('joins nested calls made through the ambient transaction context', async () => {
287
+ const store = await makeStore();
288
+ const result = await store.withTransaction(async (transaction) => {
289
+ await transaction.records.put(RECORDS.first);
290
+ return transaction.withTransaction(async (nested) => {
291
+ expect(nested).toBe(transaction);
292
+ await nested.keyValues.set('nested', true);
293
+ await nested.schemaMetadata.setSchemaMeta({ name: 'contract', version: 1 });
294
+ return 'nested-result';
292
295
  });
293
- expect(result).toBe('nested-result');
294
- expect(await store.records.get(RECORDS.first.id)).toEqual(RECORDS.first);
295
- expect(await store.keyValues.get('nested')).toBe(true);
296
296
  });
297
+ expect(result).toBe('nested-result');
298
+ expect(await store.records.get(RECORDS.first.id)).toEqual(RECORDS.first);
299
+ expect(await store.keyValues.get('nested')).toBe(true);
300
+ });
301
+ }
297
302
 
298
- it('rolls back joined nested writes when the outer callback fails', async () => {
299
- const store = await makeStore();
300
- await expect(
301
- store.withTransaction(async (transaction) => {
302
- await transaction.withTransaction(async (nested) => {
303
- await nested.records.put(RECORDS.first);
304
- await nested.keyValues.set('outbox:mutation-1', true);
305
- });
306
- throw new Error('outer failure');
307
- }),
308
- ).rejects.toThrow('outer failure');
309
- expect(await store.records.get(RECORDS.first.id)).toBeUndefined();
310
- expect(await store.keyValues.get('outbox:mutation-1')).toBeUndefined();
311
- });
303
+ function describeTransactionFailureCases(
304
+ makeStore: ContractStoreFactory<TransactionalStorageStore<ContractTestRecord>>,
305
+ ): void {
306
+ it('rolls back joined nested writes when the outer callback fails', async () => {
307
+ const store = await makeStore();
308
+ await expect(
309
+ store.withTransaction(async (transaction) => {
310
+ await transaction.withTransaction(async (nested) => {
311
+ await nested.records.put(RECORDS.first);
312
+ await nested.keyValues.set('outbox:mutation-1', true);
313
+ });
314
+ throw new Error('outer failure');
315
+ }),
316
+ ).rejects.toThrow('outer failure');
317
+ expect(await store.records.get(RECORDS.first.id)).toBeUndefined();
318
+ expect(await store.keyValues.get('outbox:mutation-1')).toBeUndefined();
319
+ });
312
320
 
313
- it('surfaces quota failures with a stable code and rolls writes back', async () => {
314
- const store = await makeStore();
315
- await expect(
316
- store.withTransaction(async (transaction) => {
317
- await transaction.records.put(RECORDS.first);
318
- throw simulatedQuotaError();
319
- }),
320
- ).rejects.toMatchObject({ code: 'storage_quota_exceeded' });
321
- expect(await store.records.get(RECORDS.first.id)).toBeUndefined();
322
- });
321
+ it('surfaces quota failures with a stable code and rolls writes back', async () => {
322
+ const store = await makeStore();
323
+ await expect(
324
+ store.withTransaction(async (transaction) => {
325
+ await transaction.records.put(RECORDS.first);
326
+ throw simulatedQuotaError();
327
+ }),
328
+ ).rejects.toMatchObject({ code: 'storage_quota_exceeded' });
329
+ expect(await store.records.get(RECORDS.first.id)).toBeUndefined();
330
+ });
323
331
 
324
- it('fails operations after close with a stable code', async () => {
325
- const store = await makeStore();
326
- await store.close();
327
- await expect(store.keyValues.get('closed')).rejects.toMatchObject({
328
- code: 'storage_closed',
329
- });
330
- await expect(store.records.put(RECORDS.first)).rejects.toMatchObject({
331
- code: 'storage_closed',
332
- });
333
- await expect(store.schemaMetadata.getSchemaMeta()).rejects.toMatchObject({
334
- code: 'storage_closed',
335
- });
336
- await expect(store.withTransaction(() => undefined)).rejects.toMatchObject({
337
- code: 'storage_closed',
338
- });
332
+ it('fails operations after close with a stable code', async () => {
333
+ const store = await makeStore();
334
+ await store.close();
335
+ await expect(store.keyValues.get('closed')).rejects.toMatchObject({
336
+ code: 'storage_closed',
337
+ });
338
+ await expect(store.records.put(RECORDS.first)).rejects.toMatchObject({
339
+ code: 'storage_closed',
339
340
  });
341
+ await expect(store.schemaMetadata.getSchemaMeta()).rejects.toMatchObject({
342
+ code: 'storage_closed',
343
+ });
344
+ await expect(store.withTransaction(() => undefined)).rejects.toMatchObject({
345
+ code: 'storage_closed',
346
+ });
347
+ });
340
348
 
341
- it('serializes concurrent root transactions', async () => {
342
- const store = await makeStore();
343
- const events: string[] = [];
344
- const first = store.withTransaction(async (transaction) => {
345
- events.push('first:start');
346
- await transaction.keyValues.set('order', 'first');
347
- events.push('first:end');
348
- });
349
- const second = store.withTransaction(async (transaction) => {
350
- events.push('second:start');
351
- expect(await transaction.keyValues.get('order')).toBe('first');
352
- await transaction.keyValues.set('order', 'second');
353
- events.push('second:end');
354
- });
355
- await Promise.all([first, second]);
356
- expect(events).toEqual(['first:start', 'first:end', 'second:start', 'second:end']);
357
- expect(await store.keyValues.get('order')).toBe('second');
349
+ it('serializes concurrent root transactions', async () => {
350
+ const store = await makeStore();
351
+ const events: string[] = [];
352
+ const first = store.withTransaction(async (transaction) => {
353
+ events.push('first:start');
354
+ await transaction.keyValues.set('order', 'first');
355
+ events.push('first:end');
358
356
  });
357
+ const second = store.withTransaction(async (transaction) => {
358
+ events.push('second:start');
359
+ expect(await transaction.keyValues.get('order')).toBe('first');
360
+ await transaction.keyValues.set('order', 'second');
361
+ events.push('second:end');
362
+ });
363
+ await Promise.all([first, second]);
364
+ expect(events).toEqual(['first:start', 'first:end', 'second:start', 'second:end']);
365
+ expect(await store.keyValues.get('order')).toBe('second');
359
366
  });
360
367
  }
361
368
 
@@ -374,194 +381,3 @@ export function describeSchemaMetadataContract(
374
381
  });
375
382
  });
376
383
  }
377
-
378
- /** Adapter seam for identity-transition tests that must reopen named stores. */
379
- export interface ScopedPersistenceContractAdapter {
380
- open(storeName: string): Promise<TransactionalStorageStore<ContractTestRecord>>;
381
- }
382
-
383
- interface ContractPersistence {
384
- readonly store: TransactionalStorageStore<ContractTestRecord>;
385
- close(): Promise<void>;
386
- }
387
-
388
- const identityDigest = (value: string): Promise<string> =>
389
- Promise.resolve(value.endsWith(':account-e') ? 'e'.repeat(64) : 'f'.repeat(64));
390
-
391
- /**
392
- * Registers the E -> F -> E ownership suite against an adapter capable of
393
- * reopening independent named databases.
394
- */
395
- export function describeScopedPersistenceContract(
396
- makeAdapter: ContractStoreFactory<ScopedPersistenceContractAdapter>,
397
- ): void {
398
- describe('authenticated scoped persistence contract', () => {
399
- it('isolates records and outbox writes across an offline E -> F -> E switch', async () => {
400
- const adapter = await makeAdapter();
401
- const events: string[] = [];
402
- const memory = {
403
- syncStatus: 'idle',
404
- pendingMutationView: 0,
405
- queryCacheEntries: 0,
406
- analyticsIdentity: undefined as string | undefined,
407
- };
408
- // No server hook is supplied: selecting either retained partition must stay fully local.
409
- const lifecycle = new ScopedPersistenceLifecycle<ContractPersistence>({
410
- namespace: 'contract-app',
411
- registry: new InMemoryScopedPersistenceRegistryStore(),
412
- digest: identityDigest,
413
- open: async ({ storeName, subject }) => {
414
- events.push(`open:${subject}`);
415
- const store = await adapter.open(storeName);
416
- return {
417
- store,
418
- close: async () => {
419
- events.push(`close:start:${subject}`);
420
- await store.close();
421
- events.push(`close:end:${subject}`);
422
- },
423
- };
424
- },
425
- resetUserScopedState: () => {
426
- events.push('reset');
427
- memory.syncStatus = 'idle';
428
- memory.pendingMutationView = 0;
429
- memory.queryCacheEntries = 0;
430
- memory.analyticsIdentity = undefined;
431
- },
432
- });
433
-
434
- const accountE = await lifecycle.selectSubject('account-e');
435
- expect(accountE).toBeDefined();
436
- await accountE?.persistence.store.withTransaction(async (transaction) => {
437
- await transaction.records.put({ id: 'shared', label: 'account E', payload: 1 });
438
- await transaction.keyValues.set('outbox:pending', {
439
- entityId: 'shared',
440
- operation: 'put-e',
441
- });
442
- });
443
- memory.syncStatus = 'pending';
444
- memory.pendingMutationView = 1;
445
- memory.queryCacheEntries = 2;
446
- memory.analyticsIdentity = 'account-e';
447
-
448
- const accountF = await lifecycle.selectSubject('account-f');
449
- expect(accountF).toBeDefined();
450
- expect(await accountF?.persistence.store.records.get('shared')).toBeUndefined();
451
- expect(await accountF?.persistence.store.keyValues.get('outbox:pending')).toBeUndefined();
452
- expect(memory).toEqual({
453
- syncStatus: 'idle',
454
- pendingMutationView: 0,
455
- queryCacheEntries: 0,
456
- analyticsIdentity: undefined,
457
- });
458
- await accountF?.persistence.store.withTransaction(async (transaction) => {
459
- await transaction.records.put({ id: 'shared', label: 'account F', payload: 2 });
460
- await transaction.keyValues.set('outbox:pending', {
461
- entityId: 'shared',
462
- operation: 'put-f',
463
- });
464
- });
465
-
466
- const accountEReturned = await lifecycle.selectSubject('account-e');
467
- expect(await accountEReturned?.persistence.store.records.get('shared')).toMatchObject({
468
- label: 'account E',
469
- });
470
- expect(await accountEReturned?.persistence.store.keyValues.get('outbox:pending')).toEqual({
471
- entityId: 'shared',
472
- operation: 'put-e',
473
- });
474
- expect(events.indexOf('close:end:account-e')).toBeLessThan(events.indexOf('open:account-f'));
475
- expect(events.indexOf('close:end:account-f')).toBeLessThan(
476
- events.lastIndexOf('open:account-e'),
477
- );
478
-
479
- await lifecycle.clear();
480
- });
481
-
482
- it('blocks corrupt registry metadata before opening a domain store', async () => {
483
- const adapter = await makeAdapter();
484
- let opens = 0;
485
- const lifecycle = new ScopedPersistenceLifecycle<ContractPersistence>({
486
- namespace: 'contract-app',
487
- registry: new InMemoryScopedPersistenceRegistryStore('{truncated'),
488
- digest: identityDigest,
489
- open: async ({ storeName }) => {
490
- opens += 1;
491
- const store = await adapter.open(storeName);
492
- return { store, close: () => store.close() };
493
- },
494
- resetUserScopedState: () => undefined,
495
- });
496
-
497
- await expect(lifecycle.selectSubject('account-e')).rejects.toMatchObject({
498
- code: 'persistence_identity_mismatch',
499
- });
500
- expect(opens).toBe(0);
501
- expect(lifecycle.current()).toBeUndefined();
502
- expect(lifecycle.state).toMatchObject({ status: 'blocked', reason: 'identity-mismatch' });
503
- });
504
-
505
- it('leaves local data unchanged when the server subject fails the adoption recheck', async () => {
506
- const adapter = await makeAdapter();
507
- const lifecycle = new ScopedPersistenceLifecycle<ContractPersistence>({
508
- namespace: 'contract-app',
509
- registry: new InMemoryScopedPersistenceRegistryStore(),
510
- digest: identityDigest,
511
- open: async ({ storeName }) => {
512
- const store = await adapter.open(storeName);
513
- return { store, close: () => store.close() };
514
- },
515
- resetUserScopedState: () => undefined,
516
- });
517
- const accountE = await lifecycle.selectSubject('account-e');
518
- await accountE?.persistence.store.records.put({
519
- id: 'preserved',
520
- label: 'before adoption',
521
- payload: true,
522
- });
523
- const adopt = async (): Promise<void> => {
524
- await accountE?.persistence.store.records.put({
525
- id: 'preserved',
526
- label: 'after adoption',
527
- payload: false,
528
- });
529
- };
530
-
531
- await expect(
532
- recheckServerSubjectBeforeSyncAdoption({
533
- partitionSubject: 'account-e',
534
- readServerSubject: () => Promise.resolve('account-f'),
535
- adopt,
536
- }),
537
- ).rejects.toMatchObject({ code: 'persistence_identity_mismatch' });
538
- expect(await accountE?.persistence.store.records.get('preserved')).toMatchObject({
539
- label: 'before adoption',
540
- });
541
- await lifecycle.clear();
542
- });
543
-
544
- it('closes and blocks the active partition on terminal session expiry', async () => {
545
- const adapter = await makeAdapter();
546
- let opens = 0;
547
- const lifecycle = new ScopedPersistenceLifecycle<ContractPersistence>({
548
- namespace: 'contract-app',
549
- registry: new InMemoryScopedPersistenceRegistryStore(),
550
- digest: identityDigest,
551
- open: async ({ storeName }) => {
552
- opens += 1;
553
- const store = await adapter.open(storeName);
554
- return { store, close: () => store.close() };
555
- },
556
- resetUserScopedState: () => undefined,
557
- });
558
- await lifecycle.selectSubject('account-e');
559
-
560
- await lifecycle.handleSessionExpired();
561
-
562
- expect(opens).toBe(1);
563
- expect(lifecycle.current()).toBeUndefined();
564
- expect(lifecycle.state).toMatchObject({ status: 'blocked', reason: 'session-expired' });
565
- });
566
- });
567
- }