@baukit/data-contracts 0.18.2 → 0.19.0

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
@@ -0,0 +1,290 @@
1
+ import type { MaybePromise } from './contracts.js';
2
+ import {
3
+ isPersistenceIdentityMismatchError,
4
+ PersistenceIdentityMismatchError,
5
+ requiredIdentityPart,
6
+ } from './identity-error.js';
7
+ import {
8
+ removeScopedPersistenceRegistryEntry,
9
+ resolveScopedStore,
10
+ type ResolveScopedStoreOptions,
11
+ type ScopedPersistenceResolver,
12
+ } from './identity.js';
13
+
14
+ export interface ClosableScopedPersistence {
15
+ close(): Promise<void>;
16
+ }
17
+
18
+ export interface OpenScopedPersistenceContext {
19
+ readonly subject: string;
20
+ readonly storeName: string;
21
+ }
22
+
23
+ export interface ScopedPersistencePartition<
24
+ TPersistence extends ClosableScopedPersistence,
25
+ > extends OpenScopedPersistenceContext {
26
+ readonly persistence: TPersistence;
27
+ }
28
+
29
+ export type ProfileErasureCleanup = 'pending' | 'complete' | 'failed';
30
+
31
+ export type ScopedPersistenceLifecycleState<TPersistence extends ClosableScopedPersistence> =
32
+ | { readonly status: 'signed-out' }
33
+ | { readonly status: 'initializing'; readonly subject: string }
34
+ | {
35
+ readonly status: 'ready';
36
+ readonly partition: ScopedPersistencePartition<TPersistence>;
37
+ }
38
+ | {
39
+ readonly status: 'blocked';
40
+ readonly reason: 'identity-mismatch' | 'initialization-failed' | 'session-expired';
41
+ readonly error: Error;
42
+ }
43
+ | {
44
+ readonly status: 'blocked';
45
+ readonly reason: 'profile-erased';
46
+ readonly cleanup: ProfileErasureCleanup;
47
+ readonly error: Error;
48
+ };
49
+
50
+ export interface ScopedPersistenceLifecycleOptions<
51
+ TPersistence extends ClosableScopedPersistence,
52
+ > extends Omit<ResolveScopedStoreOptions, 'subject'> {
53
+ /** Overrides registry resolution while retaining lifecycle transition guarantees. */
54
+ readonly resolveStore?: ScopedPersistenceResolver;
55
+ readonly open: (context: OpenScopedPersistenceContext) => Promise<TPersistence>;
56
+ /** Deletes a closed partition. Required by eraseActivePartition and handleProfileErased. */
57
+ readonly erase?: (context: OpenScopedPersistenceContext) => Promise<void>;
58
+ readonly resetUserScopedState: () => MaybePromise<void>;
59
+ }
60
+
61
+ /**
62
+ * Serializes identity transitions, hides stale handles immediately, and only
63
+ * publishes a partition after the product's open/migrate/hydrate hook resolves.
64
+ */
65
+ export class ScopedPersistenceLifecycle<TPersistence extends ClosableScopedPersistence> {
66
+ private activePartition: ScopedPersistencePartition<TPersistence> | undefined;
67
+ private lastSelectedPartition: OpenScopedPersistenceContext | undefined;
68
+ private erasedProfile:
69
+ { readonly subject: string; cleanup: ProfileErasureCleanup; error: Error } | undefined;
70
+ private transitionTail: Promise<void> = Promise.resolve();
71
+ private revision = 0;
72
+ private lifecycleState: ScopedPersistenceLifecycleState<TPersistence> = {
73
+ status: 'signed-out',
74
+ };
75
+
76
+ public constructor(private readonly options: ScopedPersistenceLifecycleOptions<TPersistence>) {}
77
+
78
+ public get state(): ScopedPersistenceLifecycleState<TPersistence> {
79
+ return this.lifecycleState;
80
+ }
81
+
82
+ /** Returns no persistence while a transition is pending or blocked. */
83
+ public current(): ScopedPersistencePartition<TPersistence> | undefined {
84
+ return this.lifecycleState.status === 'ready' ? this.activePartition : undefined;
85
+ }
86
+
87
+ public selectSubject(
88
+ subject: string,
89
+ ): Promise<ScopedPersistencePartition<TPersistence> | undefined> {
90
+ requiredIdentityPart(subject, 'Authenticated subject');
91
+ if (this.lifecycleState.status === 'ready' && this.activePartition?.subject === subject) {
92
+ return Promise.resolve(this.activePartition);
93
+ }
94
+ const revision = ++this.revision;
95
+ this.lifecycleState = { status: 'initializing', subject };
96
+ return this.enqueue(() => this.selectSubjectLocked(subject, revision));
97
+ }
98
+
99
+ public clear(): Promise<void> {
100
+ const revision = ++this.revision;
101
+ this.lifecycleState = { status: 'signed-out' };
102
+ return this.enqueue(async () => {
103
+ await this.closeAndReset();
104
+ if (revision === this.revision) this.lifecycleState = { status: 'signed-out' };
105
+ });
106
+ }
107
+
108
+ /** Closes and deletes the active partition, then removes its registry mapping. */
109
+ public eraseActivePartition(): Promise<boolean> {
110
+ const partition = this.current();
111
+ if (partition === undefined) return Promise.resolve(false);
112
+ const erase = this.options.erase;
113
+ if (erase === undefined) {
114
+ return Promise.reject(
115
+ new Error('Active partition erasure requires a configured persistence erase hook.'),
116
+ );
117
+ }
118
+
119
+ const revision = ++this.revision;
120
+ this.activePartition = undefined;
121
+ this.lifecycleState = { status: 'signed-out' };
122
+ return this.enqueue(async () => {
123
+ await this.closePartitionAndReset(partition);
124
+ await this.erasePartition(partition, erase);
125
+ if (revision === this.revision) this.lifecycleState = { status: 'signed-out' };
126
+ return true;
127
+ });
128
+ }
129
+
130
+ /** Erases the last selected partition, even after session cleanup closed it. */
131
+ public handleProfileErased(): Promise<void> {
132
+ const erase = this.options.erase;
133
+ const revision = ++this.revision;
134
+ let cleanup: ProfileErasureCleanup = 'pending';
135
+ let error = new Error('The server profile was erased; sign in again to continue.');
136
+ this.lifecycleState = { status: 'blocked', reason: 'profile-erased', cleanup, error };
137
+ return this.enqueue(async () => {
138
+ const partition = this.lastSelectedPartition;
139
+ if (partition !== undefined)
140
+ this.erasedProfile = { subject: partition.subject, cleanup, error };
141
+ try {
142
+ if (partition !== undefined) await this.closeAndReset();
143
+ if (erase === undefined) {
144
+ throw new Error('Active partition erasure requires a configured persistence erase hook.');
145
+ }
146
+ if (partition !== undefined) await this.erasePartition(partition, erase);
147
+ cleanup = 'complete';
148
+ } catch (cause) {
149
+ cleanup = 'failed';
150
+ error = cause instanceof Error ? cause : new Error('Local profile erasure failed.');
151
+ throw cause;
152
+ } finally {
153
+ if (this.erasedProfile !== undefined && this.erasedProfile.subject === partition?.subject) {
154
+ this.erasedProfile.cleanup = cleanup;
155
+ this.erasedProfile.error = error;
156
+ }
157
+ if (revision === this.revision) {
158
+ this.lifecycleState = { status: 'blocked', reason: 'profile-erased', cleanup, error };
159
+ }
160
+ }
161
+ });
162
+ }
163
+
164
+ /** Terminal auth expiry closes the current partition and remains blocked. */
165
+ public handleSessionExpired(): Promise<void> {
166
+ const revision = ++this.revision;
167
+ const error = new Error('The authenticated session expired; sign in again to continue.');
168
+ this.lifecycleState = { status: 'blocked', reason: 'session-expired', error };
169
+ return this.enqueue(async () => {
170
+ await this.closeAndReset();
171
+ if (revision === this.revision) {
172
+ this.lifecycleState = { status: 'blocked', reason: 'session-expired', error };
173
+ }
174
+ });
175
+ }
176
+
177
+ /** Blocks an already-open partition after a server subject recheck fails. */
178
+ public blockIdentityMismatch(error: PersistenceIdentityMismatchError): Promise<void> {
179
+ const revision = ++this.revision;
180
+ this.lifecycleState = { status: 'blocked', reason: 'identity-mismatch', error };
181
+ return this.enqueue(async () => {
182
+ await this.closeAndReset();
183
+ if (revision === this.revision) {
184
+ this.lifecycleState = { status: 'blocked', reason: 'identity-mismatch', error };
185
+ }
186
+ });
187
+ }
188
+
189
+ private enqueue<TResult>(operation: () => Promise<TResult>): Promise<TResult> {
190
+ const result = this.transitionTail.then(operation);
191
+ this.transitionTail = result.then(
192
+ () => undefined,
193
+ () => undefined,
194
+ );
195
+ return result;
196
+ }
197
+
198
+ private async selectSubjectLocked(
199
+ subject: string,
200
+ revision: number,
201
+ ): Promise<ScopedPersistencePartition<TPersistence> | undefined> {
202
+ try {
203
+ await this.closeAndReset();
204
+ if (revision !== this.revision) return undefined;
205
+ if (this.erasedProfile?.subject === subject) {
206
+ this.lifecycleState = {
207
+ status: 'blocked',
208
+ reason: 'profile-erased',
209
+ cleanup: this.erasedProfile.cleanup,
210
+ error: this.erasedProfile.error,
211
+ };
212
+ return undefined;
213
+ }
214
+ if (this.lastSelectedPartition?.subject !== subject) this.lastSelectedPartition = undefined;
215
+ const resolved =
216
+ this.options.resolveStore === undefined
217
+ ? await resolveScopedStore({ ...this.options, subject })
218
+ : await this.options.resolveStore(subject);
219
+ requiredIdentityPart(resolved.storeName, 'Resolved persistence store name');
220
+ if (revision !== this.revision) return undefined;
221
+ const context = {
222
+ subject,
223
+ storeName: resolved.storeName,
224
+ };
225
+ this.lastSelectedPartition = context;
226
+ const persistence = await this.options.open(context);
227
+ if (revision !== this.revision) {
228
+ await persistence.close();
229
+ await this.options.resetUserScopedState();
230
+ return undefined;
231
+ }
232
+ const partition = { subject, storeName: resolved.storeName, persistence };
233
+ this.activePartition = partition;
234
+ this.lifecycleState = { status: 'ready', partition };
235
+ return partition;
236
+ } catch (cause) {
237
+ if (revision === this.revision) {
238
+ const error =
239
+ cause instanceof Error ? cause : new Error('Local data initialization failed.');
240
+ this.lifecycleState = {
241
+ status: 'blocked',
242
+ reason: isPersistenceIdentityMismatchError(cause)
243
+ ? 'identity-mismatch'
244
+ : 'initialization-failed',
245
+ error,
246
+ };
247
+ }
248
+ throw cause;
249
+ }
250
+ }
251
+
252
+ private async erasePartition(
253
+ partition: OpenScopedPersistenceContext,
254
+ erase: NonNullable<ScopedPersistenceLifecycleOptions<TPersistence>['erase']>,
255
+ ): Promise<void> {
256
+ await erase({ subject: partition.subject, storeName: partition.storeName });
257
+ await removeScopedPersistenceRegistryEntry({
258
+ namespace: this.options.namespace,
259
+ subject: partition.subject,
260
+ registry: this.options.registry,
261
+ });
262
+ if (this.lastSelectedPartition?.subject === partition.subject) {
263
+ this.lastSelectedPartition = undefined;
264
+ }
265
+ }
266
+
267
+ private async closeAndReset(): Promise<void> {
268
+ const partition = this.activePartition;
269
+ this.activePartition = undefined;
270
+ await this.closePartitionAndReset(partition);
271
+ }
272
+
273
+ private async closePartitionAndReset(
274
+ partition: ScopedPersistencePartition<TPersistence> | undefined,
275
+ ): Promise<void> {
276
+ let closeFailure: unknown;
277
+ try {
278
+ await partition?.persistence.close();
279
+ } catch (cause) {
280
+ closeFailure = cause;
281
+ } finally {
282
+ await this.options.resetUserScopedState();
283
+ }
284
+ if (closeFailure !== undefined) {
285
+ throw closeFailure instanceof Error
286
+ ? closeFailure
287
+ : new Error('Closing the active local-data partition failed.');
288
+ }
289
+ }
290
+ }
@@ -0,0 +1,221 @@
1
+ import { describe, expect, it } from 'vitest';
2
+
3
+ import type { TransactionalStorageStore } from './contracts.js';
4
+ import {
5
+ InMemoryScopedPersistenceRegistryStore,
6
+ recheckServerSubjectBeforeSyncAdoption,
7
+ } from './identity.js';
8
+ import { ScopedPersistenceLifecycle } from './scoped-lifecycle.js';
9
+ import type { ContractStoreFactory, ContractTestRecord } from './vitest.js';
10
+
11
+ /** Adapter seam for identity-transition tests that must reopen named stores. */
12
+ export interface ScopedPersistenceContractAdapter {
13
+ open(storeName: string): Promise<TransactionalStorageStore<ContractTestRecord>>;
14
+ }
15
+
16
+ interface ContractPersistence {
17
+ readonly store: TransactionalStorageStore<ContractTestRecord>;
18
+ close(): Promise<void>;
19
+ }
20
+
21
+ const identityDigest = (value: string): Promise<string> =>
22
+ Promise.resolve(value.endsWith(':account-e') ? 'e'.repeat(64) : 'f'.repeat(64));
23
+
24
+ /**
25
+ * Registers the E -> F -> E ownership suite against an adapter capable of
26
+ * reopening independent named databases.
27
+ */
28
+ export function describeScopedPersistenceContract(
29
+ makeAdapter: ContractStoreFactory<ScopedPersistenceContractAdapter>,
30
+ ): void {
31
+ describe('authenticated scoped persistence contract', () => {
32
+ describeOfflineSwitchIsolation(makeAdapter);
33
+ describeCorruptRegistryBlocking(makeAdapter);
34
+ describeAdoptionRecheck(makeAdapter);
35
+ describeSessionExpiryBlocking(makeAdapter);
36
+ });
37
+ }
38
+
39
+ async function writeSharedWithOutbox(
40
+ store: TransactionalStorageStore<ContractTestRecord> | undefined,
41
+ label: string,
42
+ payload: number,
43
+ operation: string,
44
+ ): Promise<void> {
45
+ await store?.withTransaction(async (transaction) => {
46
+ await transaction.records.put({ id: 'shared', label, payload });
47
+ await transaction.keyValues.set('outbox:pending', { entityId: 'shared', operation });
48
+ });
49
+ }
50
+
51
+ function describeOfflineSwitchIsolation(
52
+ makeAdapter: ContractStoreFactory<ScopedPersistenceContractAdapter>,
53
+ ): void {
54
+ it('isolates records and outbox writes across an offline E -> F -> E switch', async () => {
55
+ const adapter = await makeAdapter();
56
+ const events: string[] = [];
57
+ const memory = {
58
+ syncStatus: 'idle',
59
+ pendingMutationView: 0,
60
+ queryCacheEntries: 0,
61
+ analyticsIdentity: undefined as string | undefined,
62
+ };
63
+ // No server hook is supplied: selecting either retained partition must stay fully local.
64
+ const lifecycle = new ScopedPersistenceLifecycle<ContractPersistence>({
65
+ namespace: 'contract-app',
66
+ registry: new InMemoryScopedPersistenceRegistryStore(),
67
+ digest: identityDigest,
68
+ open: async ({ storeName, subject }) => {
69
+ events.push(`open:${subject}`);
70
+ const store = await adapter.open(storeName);
71
+ return {
72
+ store,
73
+ close: async () => {
74
+ events.push(`close:start:${subject}`);
75
+ await store.close();
76
+ events.push(`close:end:${subject}`);
77
+ },
78
+ };
79
+ },
80
+ resetUserScopedState: () => {
81
+ events.push('reset');
82
+ memory.syncStatus = 'idle';
83
+ memory.pendingMutationView = 0;
84
+ memory.queryCacheEntries = 0;
85
+ memory.analyticsIdentity = undefined;
86
+ },
87
+ });
88
+
89
+ const accountE = await lifecycle.selectSubject('account-e');
90
+ expect(accountE).toBeDefined();
91
+ await writeSharedWithOutbox(accountE?.persistence.store, 'account E', 1, 'put-e');
92
+ memory.syncStatus = 'pending';
93
+ memory.pendingMutationView = 1;
94
+ memory.queryCacheEntries = 2;
95
+ memory.analyticsIdentity = 'account-e';
96
+
97
+ const accountF = await lifecycle.selectSubject('account-f');
98
+ expect(accountF).toBeDefined();
99
+ expect(await accountF?.persistence.store.records.get('shared')).toBeUndefined();
100
+ expect(await accountF?.persistence.store.keyValues.get('outbox:pending')).toBeUndefined();
101
+ expect(memory).toEqual({
102
+ syncStatus: 'idle',
103
+ pendingMutationView: 0,
104
+ queryCacheEntries: 0,
105
+ analyticsIdentity: undefined,
106
+ });
107
+ await writeSharedWithOutbox(accountF?.persistence.store, 'account F', 2, 'put-f');
108
+
109
+ const accountEReturned = await lifecycle.selectSubject('account-e');
110
+ expect(await accountEReturned?.persistence.store.records.get('shared')).toMatchObject({
111
+ label: 'account E',
112
+ });
113
+ expect(await accountEReturned?.persistence.store.keyValues.get('outbox:pending')).toEqual({
114
+ entityId: 'shared',
115
+ operation: 'put-e',
116
+ });
117
+ expect(events.indexOf('close:end:account-e')).toBeLessThan(events.indexOf('open:account-f'));
118
+ expect(events.indexOf('close:end:account-f')).toBeLessThan(
119
+ events.lastIndexOf('open:account-e'),
120
+ );
121
+
122
+ await lifecycle.clear();
123
+ });
124
+ }
125
+
126
+ function describeCorruptRegistryBlocking(
127
+ makeAdapter: ContractStoreFactory<ScopedPersistenceContractAdapter>,
128
+ ): void {
129
+ it('blocks corrupt registry metadata before opening a domain store', async () => {
130
+ const adapter = await makeAdapter();
131
+ let opens = 0;
132
+ const lifecycle = new ScopedPersistenceLifecycle<ContractPersistence>({
133
+ namespace: 'contract-app',
134
+ registry: new InMemoryScopedPersistenceRegistryStore('{truncated'),
135
+ digest: identityDigest,
136
+ open: async ({ storeName }) => {
137
+ opens += 1;
138
+ const store = await adapter.open(storeName);
139
+ return { store, close: () => store.close() };
140
+ },
141
+ resetUserScopedState: () => undefined,
142
+ });
143
+
144
+ await expect(lifecycle.selectSubject('account-e')).rejects.toMatchObject({
145
+ code: 'persistence_identity_mismatch',
146
+ });
147
+ expect(opens).toBe(0);
148
+ expect(lifecycle.current()).toBeUndefined();
149
+ expect(lifecycle.state).toMatchObject({ status: 'blocked', reason: 'identity-mismatch' });
150
+ });
151
+ }
152
+
153
+ function describeAdoptionRecheck(
154
+ makeAdapter: ContractStoreFactory<ScopedPersistenceContractAdapter>,
155
+ ): void {
156
+ it('leaves local data unchanged when the server subject fails the adoption recheck', async () => {
157
+ const adapter = await makeAdapter();
158
+ const lifecycle = new ScopedPersistenceLifecycle<ContractPersistence>({
159
+ namespace: 'contract-app',
160
+ registry: new InMemoryScopedPersistenceRegistryStore(),
161
+ digest: identityDigest,
162
+ open: async ({ storeName }) => {
163
+ const store = await adapter.open(storeName);
164
+ return { store, close: () => store.close() };
165
+ },
166
+ resetUserScopedState: () => undefined,
167
+ });
168
+ const accountE = await lifecycle.selectSubject('account-e');
169
+ await accountE?.persistence.store.records.put({
170
+ id: 'preserved',
171
+ label: 'before adoption',
172
+ payload: true,
173
+ });
174
+ const adopt = async (): Promise<void> => {
175
+ await accountE?.persistence.store.records.put({
176
+ id: 'preserved',
177
+ label: 'after adoption',
178
+ payload: false,
179
+ });
180
+ };
181
+
182
+ await expect(
183
+ recheckServerSubjectBeforeSyncAdoption({
184
+ partitionSubject: 'account-e',
185
+ readServerSubject: () => Promise.resolve('account-f'),
186
+ adopt,
187
+ }),
188
+ ).rejects.toMatchObject({ code: 'persistence_identity_mismatch' });
189
+ expect(await accountE?.persistence.store.records.get('preserved')).toMatchObject({
190
+ label: 'before adoption',
191
+ });
192
+ await lifecycle.clear();
193
+ });
194
+ }
195
+
196
+ function describeSessionExpiryBlocking(
197
+ makeAdapter: ContractStoreFactory<ScopedPersistenceContractAdapter>,
198
+ ): void {
199
+ it('closes and blocks the active partition on terminal session expiry', async () => {
200
+ const adapter = await makeAdapter();
201
+ let opens = 0;
202
+ const lifecycle = new ScopedPersistenceLifecycle<ContractPersistence>({
203
+ namespace: 'contract-app',
204
+ registry: new InMemoryScopedPersistenceRegistryStore(),
205
+ digest: identityDigest,
206
+ open: async ({ storeName }) => {
207
+ opens += 1;
208
+ const store = await adapter.open(storeName);
209
+ return { store, close: () => store.close() };
210
+ },
211
+ resetUserScopedState: () => undefined,
212
+ });
213
+ await lifecycle.selectSubject('account-e');
214
+
215
+ await lifecycle.handleSessionExpired();
216
+
217
+ expect(opens).toBe(1);
218
+ expect(lifecycle.current()).toBeUndefined();
219
+ expect(lifecycle.state).toMatchObject({ status: 'blocked', reason: 'session-expired' });
220
+ });
221
+ }