@oxidezap/baileyrs 0.3.10 → 0.3.12

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 (55) hide show
  1. package/lib/Bridge/schema.js +42 -16
  2. package/lib/Bridge/types.d.ts +13 -2
  3. package/lib/Compatibility/auth-state.js +2 -11
  4. package/lib/Compatibility/host-auth-state.js +2 -0
  5. package/lib/Compatibility/internal/auth-state.js +6 -0
  6. package/lib/Compatibility/internal/host-auth-state.js +3 -0
  7. package/lib/Compatibility/legacy-store/adapter.js +137 -3
  8. package/lib/Compatibility/legacy-store/codecs/basic.js +5 -8
  9. package/lib/Compatibility/legacy-store/multi-file.d.ts +12 -1
  10. package/lib/Compatibility/legacy-store/multi-file.js +37 -25
  11. package/lib/Compatibility/legacy-store/record-files.d.ts +3 -0
  12. package/lib/Compatibility/legacy-store/record-files.js +5 -0
  13. package/lib/Compatibility/legacy-store/rollback.d.ts +8 -0
  14. package/lib/Compatibility/legacy-store/rollback.js +16 -0
  15. package/lib/Compatibility/legacy-store/snapshot.d.ts +7 -0
  16. package/lib/Compatibility/legacy-store/snapshot.js +53 -0
  17. package/lib/Compatibility/legacy-store/types.d.ts +4 -1
  18. package/lib/Socket/chat-actions.js +1 -1
  19. package/lib/Socket/events-core.js +9 -1
  20. package/lib/Socket/index.d.ts +3 -717
  21. package/lib/Types/Auth.d.ts +5 -0
  22. package/lib/Types/Events.d.ts +6 -1
  23. package/lib/Utils/atomic-store.d.ts +20 -0
  24. package/lib/Utils/atomic-store.js +116 -0
  25. package/lib/Utils/durable-directory.d.ts +3 -0
  26. package/lib/Utils/durable-directory.js +35 -0
  27. package/lib/Utils/flush-deadline.d.ts +19 -0
  28. package/lib/Utils/flush-deadline.js +97 -0
  29. package/lib/Utils/index.d.ts +1 -0
  30. package/lib/Utils/index.js +1 -0
  31. package/lib/Utils/native-auth-rollback.d.ts +14 -0
  32. package/lib/Utils/native-auth-rollback.js +17 -0
  33. package/lib/Utils/process-file-lock.d.ts +6 -0
  34. package/lib/Utils/process-file-lock.js +38 -0
  35. package/lib/Utils/snapshot-rollback-proof.d.ts +9 -0
  36. package/lib/Utils/snapshot-rollback-proof.js +43 -0
  37. package/lib/Utils/snapshot-rollback.d.ts +5 -0
  38. package/lib/Utils/snapshot-rollback.js +69 -0
  39. package/lib/Utils/snapshot-transactions.d.ts +10 -0
  40. package/lib/Utils/snapshot-transactions.js +108 -0
  41. package/lib/Utils/store-migration.d.ts +10 -0
  42. package/lib/Utils/store-migration.js +16 -0
  43. package/lib/Utils/transactional-file-store.d.ts +7 -0
  44. package/lib/Utils/transactional-file-store.js +157 -0
  45. package/lib/Utils/use-bridge-store.d.ts +3 -49
  46. package/lib/Utils/use-bridge-store.js +121 -109
  47. package/lib/Utils/use-memory-store.js +17 -4
  48. package/lib/Utils/use-multi-file-auth-state.d.ts +2 -1
  49. package/lib/Utils/use-multi-file-auth-state.js +2 -2
  50. package/lib/Utils/wrap-legacy-store.d.ts +1 -0
  51. package/lib/Utils/wrap-legacy-store.js +1 -0
  52. package/lib/host-types.d.ts +1 -15
  53. package/lib/node-surface.d.ts +2 -1
  54. package/lib/node-surface.js +2 -1
  55. package/package.json +12 -10
@@ -0,0 +1,108 @@
1
+ import { settleBeforeFlushDeadline, flushDeadlineError, settledFlushError, trackFlushFailures } from './flush-deadline.js';
2
+ import { clearRollbackProof } from './snapshot-rollback-proof.js';
3
+ import { withProcessFileLock } from './process-file-lock.js';
4
+ import { open, readFile, rename, unlink } from 'node:fs/promises';
5
+ import { randomUUID } from 'node:crypto';
6
+ import { join } from 'node:path';
7
+ import { rowKey } from './atomic-store.js';
8
+ const missing = (error) => error?.code === 'ENOENT';
9
+ /** Snapshot publication and backend-wide isolation, independent of row codecs.
10
+ * The OS lock is shared across adapters/processes; there is no stale-owner lease.
11
+ */
12
+ export const createSnapshotTransactions = (folder, snapshotName, namespaces, importRows, syncDir) => {
13
+ const path = join(folder, snapshotName);
14
+ const readRows = async () => {
15
+ try {
16
+ const entries = JSON.parse(await readFile(path, 'utf8'));
17
+ if (!Array.isArray(entries))
18
+ throw new TypeError('invalid atomic store snapshot');
19
+ const rows = new Map();
20
+ for (const entry of entries) {
21
+ if (!Array.isArray(entry) || entry.length !== 2 || typeof entry[0] !== 'string' || typeof entry[1] !== 'string')
22
+ throw new TypeError('invalid atomic store entry');
23
+ const key = JSON.parse(entry[0]);
24
+ if (!Array.isArray(key) || key.length !== 2 || !namespaces.has(key[0]) || typeof key[1] !== 'string')
25
+ throw new TypeError('invalid atomic store key');
26
+ if (rows.has(entry[0]))
27
+ throw new TypeError('duplicate atomic store key');
28
+ if (rowKey(key[0], key[1]) !== entry[0])
29
+ throw new TypeError('noncanonical atomic store key');
30
+ const bytes = Buffer.from(entry[1], 'base64');
31
+ if (bytes.toString('base64') !== entry[1])
32
+ throw new TypeError('invalid atomic store bytes');
33
+ rows.set(entry[0], bytes);
34
+ }
35
+ return rows;
36
+ }
37
+ catch (error) {
38
+ if (!missing(error))
39
+ throw error;
40
+ }
41
+ return importRows();
42
+ };
43
+ const inFlight = new Set();
44
+ let tail = Promise.resolve();
45
+ const exclusive = (work) => {
46
+ const result = tail.then(() => withProcessFileLock(folder, `.${snapshotName}.lock`, work));
47
+ inFlight.add(result);
48
+ void result.then(() => inFlight.delete(result), () => { } // Retain failure until a flush observes it.
49
+ );
50
+ tail = result.catch(() => { });
51
+ return result;
52
+ };
53
+ const persist = async (rows) => {
54
+ const bytes = Buffer.from(JSON.stringify([...rows].map(([key, value]) => [key, Buffer.from(value).toString('base64')])));
55
+ await clearRollbackProof(folder, snapshotName, syncDir);
56
+ const tmp = `${path}.${randomUUID()}.tmp`;
57
+ const handle = await open(tmp, 'wx', 0o600);
58
+ try {
59
+ await handle.writeFile(bytes);
60
+ await handle.sync();
61
+ await handle.close();
62
+ await rename(tmp, path);
63
+ await syncDir(folder);
64
+ }
65
+ finally {
66
+ await handle.close().catch(() => { });
67
+ await unlink(tmp).catch(error => {
68
+ if (!missing(error))
69
+ throw error;
70
+ });
71
+ }
72
+ };
73
+ const transaction = (change, shouldPersist = () => true) => exclusive(async () => {
74
+ const rows = await readRows();
75
+ const result = await change(rows);
76
+ if (shouldPersist())
77
+ await persist(rows);
78
+ return result;
79
+ });
80
+ return {
81
+ read: (read) => exclusive(async () => read(await readRows())),
82
+ transaction,
83
+ flush: () => {
84
+ const errors = new Map();
85
+ const drain = async () => {
86
+ // A finished host callback can admit the next callback in the same
87
+ // engine operation. Drain new admissions too, with a bounded idle turn.
88
+ const deadline = Date.now() + 30000;
89
+ for (;;) {
90
+ const admitted = [...inFlight];
91
+ await settleBeforeFlushDeadline(admitted, deadline, 'snapshot flush', errors);
92
+ for (const operation of admitted)
93
+ inFlight.delete(operation);
94
+ await new Promise(resolve => setImmediate(resolve));
95
+ if (inFlight.size === 0) {
96
+ if (errors.size)
97
+ throw settledFlushError('snapshot flush failed', errors.values());
98
+ return;
99
+ }
100
+ if (Date.now() >= deadline)
101
+ throw flushDeadlineError('snapshot flush', errors);
102
+ }
103
+ };
104
+ return trackFlushFailures(drain(), errors);
105
+ }
106
+ };
107
+ };
108
+ //# sourceMappingURL=snapshot-transactions.js.map
@@ -0,0 +1,10 @@
1
+ export type StoreMigrationOptions = {
2
+ /** Explicit handoff: every adapter/process using the old files has stopped.
3
+ * Back up the whole directory, including hidden completion records and archives. The snapshot becomes authoritative.
4
+ * Older writers cannot share its lock. Before reverting storage formats, stop
5
+ * all writers and run prepareNativeAuthRollback or prepareLegacyAuthRollback
6
+ * with { offline: true }; do not reopen stale per-key backups directly. */
7
+ migrate?: true;
8
+ };
9
+ export declare const requireOfflineMigration: (folder: string, snapshotName: string, isOldRecord: (name: string) => boolean, options: StoreMigrationOptions) => Promise<void>;
10
+ //# sourceMappingURL=store-migration.d.ts.map
@@ -0,0 +1,16 @@
1
+ import { access, readdir } from 'node:fs/promises';
2
+ import { join } from 'node:path';
3
+ export const requireOfflineMigration = async (folder, snapshotName, isOldRecord, options) => {
4
+ try {
5
+ await access(join(folder, snapshotName));
6
+ return;
7
+ }
8
+ catch (error) {
9
+ if (error?.code !== 'ENOENT')
10
+ throw error;
11
+ }
12
+ if (options.migrate !== true && (await readdir(folder)).some(isOldRecord)) {
13
+ throw new Error(`existing auth files require an offline migration: stop every old writer, back up the whole directory, then pass { migrate: true } (${folder})`);
14
+ }
15
+ };
16
+ //# sourceMappingURL=store-migration.js.map
@@ -0,0 +1,7 @@
1
+ import { type StoreMigrationOptions } from './store-migration.js';
2
+ import type { AuthenticationState } from '../Types/index.js';
3
+ import { type OrdinaryStoreCallbacks } from './atomic-store.js';
4
+ type Store = NonNullable<AuthenticationState['store']>;
5
+ export declare const transactionalFileStore: (folder: string, ordinary: OrdinaryStoreCallbacks, syncDir: (path: string) => Promise<void>, options?: StoreMigrationOptions, createOrdinaryDrain?: () => () => Promise<void>) => Promise<Store>;
6
+ export {};
7
+ //# sourceMappingURL=transactional-file-store.d.ts.map
@@ -0,0 +1,157 @@
1
+ import { settleBeforeFlushDeadline, flushDeadlineError, settledFlushError } from './flush-deadline.js';
2
+ import { nativeAtomicNamespaces as namespaces, isNativeAtomicRecordFile } from './native-auth-rollback.js';
3
+ import { requireOfflineMigration } from './store-migration.js';
4
+ import { readFile, readdir } from 'node:fs/promises';
5
+ import { join } from 'node:path';
6
+ import { atomicCallbacks, rowKey } from './atomic-store.js';
7
+ import { createSnapshotTransactions } from './snapshot-transactions.js';
8
+ export const transactionalFileStore = async (folder, ordinary, syncDir, options = {}, createOrdinaryDrain = () => () => {
9
+ try {
10
+ return ordinary.flush?.() ?? Promise.resolve();
11
+ }
12
+ catch (error) {
13
+ return Promise.reject(error);
14
+ }
15
+ }) => {
16
+ await requireOfflineMigration(folder, 'bridge-atomic-v1.json', isNativeAtomicRecordFile, options);
17
+ const snapshot = createSnapshotTransactions(folder, 'bridge-atomic-v1.json', namespaces, async () => {
18
+ await requireOfflineMigration(folder, 'bridge-atomic-v1.json', isNativeAtomicRecordFile, options);
19
+ const rows = new Map();
20
+ for (const file of await readdir(folder)) {
21
+ const separator = file.indexOf('-');
22
+ const store = file.slice(0, separator);
23
+ if (!namespaces.has(store) || !file.endsWith('.bin'))
24
+ continue;
25
+ const encoded = file.slice(separator + 1, -4);
26
+ const key = decodeURIComponent(encoded);
27
+ if (encodeURIComponent(key) !== encoded)
28
+ throw new TypeError(`noncanonical native auth filename: ${file}`);
29
+ const row = rowKey(store, key);
30
+ if (rows.has(row))
31
+ throw new TypeError(`duplicate native auth key: ${file}`);
32
+ rows.set(row, await readFile(join(folder, file)));
33
+ }
34
+ return rows;
35
+ }, syncDir);
36
+ const transaction = snapshot.transaction;
37
+ const list = (rows, store, prefix = '') => [...rows].flatMap(([key, value]) => {
38
+ const [namespace, id] = JSON.parse(key);
39
+ return namespace === store && id.startsWith(prefix) ? [[id, Uint8Array.from(value)]] : [];
40
+ });
41
+ let admissions = 0;
42
+ let activeFlushes = 0;
43
+ const pendingCallbacks = new Set();
44
+ const result = {
45
+ ...ordinary,
46
+ async flush() {
47
+ activeFlushes++;
48
+ try {
49
+ const deadline = Date.now() + 30000;
50
+ const errors = new Map();
51
+ const drainOrdinary = createOrdinaryDrain();
52
+ for (;;) {
53
+ const before = admissions;
54
+ const admitted = [...pendingCallbacks];
55
+ await settleBeforeFlushDeadline([snapshot.flush(), drainOrdinary(), ...admitted], deadline, 'bridge store flush', errors);
56
+ for (const callback of admitted)
57
+ pendingCallbacks.delete(callback);
58
+ await new Promise(resolve => setImmediate(resolve));
59
+ // A callback can reject early after admitting batch children. Join
60
+ // backing queues once more after observing its completion.
61
+ if (admitted.length === 0 && admissions === before && pendingCallbacks.size === 0) {
62
+ if (errors.size)
63
+ throw settledFlushError('bridge store flush failed', errors.values());
64
+ return;
65
+ }
66
+ if (Date.now() >= deadline)
67
+ throw flushDeadlineError('bridge store flush', errors);
68
+ }
69
+ }
70
+ finally {
71
+ activeFlushes--;
72
+ }
73
+ },
74
+ ...atomicCallbacks(transaction),
75
+ get: (store, key) => namespaces.has(store) ? snapshot.read(rows => rows.get(rowKey(store, key)) ?? null) : ordinary.get(store, key),
76
+ set(store, key, value) {
77
+ const bytes = Uint8Array.from(value);
78
+ return namespaces.has(store)
79
+ ? transaction(rows => {
80
+ rows.set(rowKey(store, key), bytes);
81
+ })
82
+ : ordinary.set(store, key, bytes);
83
+ },
84
+ delete: (store, key) => namespaces.has(store)
85
+ ? transaction(rows => {
86
+ rows.delete(rowKey(store, key));
87
+ })
88
+ : ordinary.delete(store, key),
89
+ setMany(store, entries) {
90
+ if (!namespaces.has(store))
91
+ return ordinary.setMany(store, entries);
92
+ const additions = entries.map(([key, value]) => [key, Uint8Array.from(value)]);
93
+ return transaction(rows => {
94
+ for (const [key, value] of additions)
95
+ rows.set(rowKey(store, key), value);
96
+ });
97
+ },
98
+ deleteMany(store, keys) {
99
+ const requested = [...keys];
100
+ return namespaces.has(store)
101
+ ? transaction(rows => {
102
+ for (const key of requested)
103
+ rows.delete(rowKey(store, key));
104
+ })
105
+ : ordinary.deleteMany(store, requested);
106
+ },
107
+ getMany(store, keys) {
108
+ const requested = [...keys];
109
+ return namespaces.has(store)
110
+ ? snapshot.read(rows => requested.flatMap(key => {
111
+ const value = rows.get(rowKey(store, key));
112
+ return value ? [[key, value]] : [];
113
+ }))
114
+ : ordinary.getMany(store, requested);
115
+ },
116
+ listKeys: (store, prefix) => namespaces.has(store)
117
+ ? snapshot.read(rows => list(rows, store, prefix).map(([key]) => key))
118
+ : ordinary.listKeys(store, prefix),
119
+ deletePrefix: (store, prefix) => namespaces.has(store)
120
+ ? transaction(rows => {
121
+ const entries = list(rows, store, prefix);
122
+ for (const [key] of entries)
123
+ rows.delete(rowKey(store, key));
124
+ return entries.length;
125
+ })
126
+ : ordinary.deletePrefix(store, prefix)
127
+ };
128
+ // Every public callback shares the admission counter, so cross-backend
129
+ // completion handlers cannot escape the combined durability barrier.
130
+ const admit = (callback) => (...args) => {
131
+ admissions++;
132
+ const returned = callback(...args);
133
+ const tracked = Promise.resolve(returned);
134
+ pendingCallbacks.add(tracked);
135
+ void tracked.then(() => pendingCallbacks.delete(tracked), () => {
136
+ if (activeFlushes === 0)
137
+ pendingCallbacks.delete(tracked);
138
+ } // Keep failures admitted during a drain.
139
+ );
140
+ return returned;
141
+ };
142
+ return {
143
+ ...result,
144
+ get: admit(result.get),
145
+ set: admit(result.set),
146
+ delete: admit(result.delete),
147
+ getMany: admit(result.getMany),
148
+ setMany: admit(result.setMany),
149
+ deleteMany: admit(result.deleteMany),
150
+ listKeys: admit(result.listKeys),
151
+ deletePrefix: admit(result.deletePrefix),
152
+ commitPatch: admit(result.commitPatch),
153
+ storeReceivedTcToken: admit(result.storeReceivedTcToken),
154
+ touchTcTokenSenderTimestamp: admit(result.touchTcTokenSenderTimestamp)
155
+ };
156
+ };
157
+ //# sourceMappingURL=transactional-file-store.js.map
@@ -1,3 +1,4 @@
1
+ import type { StoreMigrationOptions } from './store-migration.js';
1
2
  import type { AuthenticationState } from '../Types/index.js';
2
3
  /**
3
4
  * Pure classifier for directory-barrier failures: does this error mean
@@ -18,7 +19,7 @@ import type { AuthenticationState } from '../Types/index.js';
18
19
  * `platform` defaults to the running platform; tests pass explicit values
19
20
  * to cover the matrix deterministically on any OS.
20
21
  */
21
- export declare const isUnsupportedDirSync: (e: unknown, platform?: NodeJS.Platform) => boolean;
22
+ export { isUnsupportedDirSync } from './durable-directory.js';
22
23
  type BridgeStoreFileHandle = {
23
24
  writeFile(value: Uint8Array): Promise<void>;
24
25
  sync(): Promise<void>;
@@ -30,55 +31,8 @@ type BridgeStoreFileIO = {
30
31
  syncDir?(dir: string): Promise<void>;
31
32
  openTmp?(tmpPath: string): Promise<BridgeStoreFileHandle>;
32
33
  };
33
- type BridgeStoreOptions = {
34
+ type BridgeStoreOptions = StoreMigrationOptions & {
34
35
  io?: BridgeStoreFileIO;
35
36
  };
36
- /**
37
- * Creates a file-based store for the WASM bridge.
38
- *
39
- * Each (store, key) pair maps to a file: `<folder>/<store>-<key>.bin`
40
- *
41
- * Durability model:
42
- * - Caller buffers are copied synchronously at admission (`set`/`setMany`
43
- * copy before queueing), so mutating a buffer after the call — even
44
- * before awaiting it — can never change what gets persisted.
45
- * - Critical stores write through `durableWrite` before `set`/`setMany`
46
- * resolve. The in-memory map only records bytes AFTER the full barrier
47
- * (write + fsync + atomic rename + directory sync) succeeds, so an
48
- * identical retry following a failure is never skipped and always
49
- * re-attempts the write.
50
- * - If the post-rename barrier fails, the key is marked uncertain: prior
51
- * durable knowledge is discarded, reads serve best-available bytes
52
- * without re-certifying them, and no identical set is skipped until a
53
- * later operation completes the full barrier for that key.
54
- * - Non-critical stores are debounced (50ms coalescing) and readable
55
- * immediately (read-your-write), but such reads are NOT durable until
56
- * `flush()` succeeds. A failed flush keeps the pending entry and throws,
57
- * so the next `flush()` retries the same bytes.
58
- * - `flush()` first waits for every operation admitted before it
59
- * (barrier), then drains the pending writes those operations produced.
60
- * Failures observed by the barrier propagate — a failed admitted write
61
- * fails the flush — but only operations outstanding during that flush
62
- * are reported, so history never poisons later flushes. A drain pass
63
- * with any failure stops at that pass and leaves the failed entries
64
- * for the next explicit flush. `flush()` never reports quiescence
65
- * while prior admitted work is still running.
66
- * - All operations on one key (set, delete, flush, concurrent batches) run
67
- * through a per-key chain, so a stale failure can never erase newer
68
- * state and an in-flight write can never resurrect a deleted key.
69
- * - A failed delete restores the preceding pending/durable state, so an
70
- * acknowledged value stays readable and flushable; only a successful
71
- * delete (unlink + directory barrier) clears it. A delete retried while
72
- * the key is uncertain re-runs the directory barrier instead of
73
- * swallowing the uncertainty as idempotent absence — except that a
74
- * directory removed externally surfaces ENOENT rather than success.
75
- * - Every byte array handed back to callers is a copy.
76
- *
77
- * @param folder Directory to store bridge state files
78
- * @param options Optional per-store file-I/O steps. Test/fault-injection
79
- * seam only: the default implementation is the sole provider of the
80
- * durability contract above.
81
- */
82
37
  export declare function useBridgeStore(folder: string, options?: BridgeStoreOptions): Promise<NonNullable<AuthenticationState['store']>>;
83
- export {};
84
38
  //# sourceMappingURL=use-bridge-store.d.ts.map