@t3foundry/tasra-sdk 0.3.1 → 0.4.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 (255) hide show
  1. package/CHANGELOG.md +1067 -28
  2. package/README.md +15 -0
  3. package/dist/app/approvals.d.ts +66 -4
  4. package/dist/app/approvals.js +153 -16
  5. package/dist/app/authorization.d.ts +1 -1
  6. package/dist/app/authorization.js +1 -1
  7. package/dist/app/browser.d.ts +63 -0
  8. package/dist/app/browser.js +242 -0
  9. package/dist/app/client.d.ts +114 -13
  10. package/dist/app/client.js +302 -76
  11. package/dist/app/identity.js +21 -9
  12. package/dist/app/index.d.ts +28 -3
  13. package/dist/app/index.js +16 -1
  14. package/dist/app/memory-store.d.ts +7 -0
  15. package/dist/app/memory-store.js +55 -0
  16. package/dist/app/node.d.ts +34 -6
  17. package/dist/app/node.js +387 -64
  18. package/dist/app/paid-allowance.d.ts +325 -0
  19. package/dist/app/paid-allowance.js +1290 -0
  20. package/dist/app/paid-approval.d.ts +122 -0
  21. package/dist/app/paid-approval.js +379 -0
  22. package/dist/app/paid-journal.d.ts +51 -0
  23. package/dist/app/paid-journal.js +117 -0
  24. package/dist/app/paid-keys.d.ts +12 -0
  25. package/dist/app/paid-keys.js +20 -0
  26. package/dist/app/paid-operation.d.ts +821 -0
  27. package/dist/app/paid-operation.js +1720 -0
  28. package/dist/app/paid-reservation.d.ts +157 -0
  29. package/dist/app/paid-reservation.js +323 -0
  30. package/dist/app/paid-session.d.ts +147 -0
  31. package/dist/app/paid-session.js +578 -0
  32. package/dist/app/payer-queue.d.ts +11 -0
  33. package/dist/app/payer-queue.js +27 -0
  34. package/dist/app/policy-bootstrap.d.ts +342 -0
  35. package/dist/app/policy-bootstrap.js +365 -0
  36. package/dist/app/policy-operation.d.ts +47 -0
  37. package/dist/app/policy-operation.js +101 -0
  38. package/dist/app/ready-slot.d.ts +12 -0
  39. package/dist/app/ready-slot.js +5 -2
  40. package/dist/app/rotation-lock.d.ts +38 -0
  41. package/dist/app/rotation-lock.js +42 -0
  42. package/dist/app/session-decrypt.d.ts +135 -0
  43. package/dist/app/session-decrypt.js +335 -0
  44. package/dist/app/session-grants.d.ts +349 -0
  45. package/dist/app/session-grants.js +811 -0
  46. package/dist/app/signing-intents.d.ts +78 -0
  47. package/dist/app/signing-intents.js +95 -0
  48. package/dist/app/store-commit.d.ts +63 -0
  49. package/dist/app/store-commit.js +126 -0
  50. package/dist/app/store-errors.d.ts +8 -0
  51. package/dist/app/store-errors.js +11 -0
  52. package/dist/app/tasra-client.d.ts +2 -0
  53. package/dist/app/tasra-client.js +1 -1
  54. package/dist/app/wallet.js +4 -1
  55. package/dist/auth/holderProof.d.ts +3 -0
  56. package/dist/auth/holderProof.js +8 -7
  57. package/dist/auth/verifier.d.ts +4 -2
  58. package/dist/auth/verifier.js +5 -2
  59. package/dist/chain/abis/index.d.ts +6178 -4101
  60. package/dist/chain/abis/index.js +3 -0
  61. package/dist/chain/abis/keyRegistry.d.ts +256 -0
  62. package/dist/chain/abis/keyRegistry.js +333 -0
  63. package/dist/chain/abis/prepaidFaultOracle.d.ts +321 -0
  64. package/dist/chain/abis/prepaidFaultOracle.js +413 -0
  65. package/dist/chain/abis/settlement.d.ts +2203 -703
  66. package/dist/chain/abis/settlement.js +2685 -764
  67. package/dist/chain/allowance.d.ts +358 -0
  68. package/dist/chain/allowance.js +800 -0
  69. package/dist/chain/billing.d.ts +85 -0
  70. package/dist/chain/billing.js +197 -0
  71. package/dist/chain/chainId.d.ts +13 -0
  72. package/dist/chain/chainId.js +26 -0
  73. package/dist/chain/client.d.ts +15 -1
  74. package/dist/chain/client.js +57 -1
  75. package/dist/chain/commitmentRecovery.d.ts +51 -0
  76. package/dist/chain/commitmentRecovery.js +38 -0
  77. package/dist/chain/committeeClient.d.ts +17 -10
  78. package/dist/chain/committeeClient.js +64 -16
  79. package/dist/chain/committeeDraw.d.ts +12 -0
  80. package/dist/chain/committeeDraw.js +56 -0
  81. package/dist/chain/custodyHealth.d.ts +212 -0
  82. package/dist/chain/custodyHealth.js +365 -0
  83. package/dist/chain/deployments.js +2 -0
  84. package/dist/chain/events.js +2 -0
  85. package/dist/chain/headFollower.d.ts +77 -0
  86. package/dist/chain/headFollower.js +219 -0
  87. package/dist/chain/headPrefetch.d.ts +23 -0
  88. package/dist/chain/headPrefetch.js +67 -0
  89. package/dist/chain/index.d.ts +50 -8
  90. package/dist/chain/index.js +28 -3
  91. package/dist/chain/keeperExecution.d.ts +44 -0
  92. package/dist/chain/keeperExecution.js +127 -0
  93. package/dist/chain/keeperRecovery.d.ts +78 -0
  94. package/dist/chain/keeperRecovery.js +91 -0
  95. package/dist/chain/node.d.ts +24 -1
  96. package/dist/chain/node.js +88 -43
  97. package/dist/chain/offchain.d.ts +2 -0
  98. package/dist/chain/paidAgentTransport.d.ts +38 -0
  99. package/dist/chain/paidAgentTransport.js +1 -0
  100. package/dist/chain/paidEpoch.d.ts +66 -0
  101. package/dist/chain/paidEpoch.js +139 -0
  102. package/dist/chain/paidPacing.d.ts +81 -0
  103. package/dist/chain/paidPacing.js +136 -0
  104. package/dist/chain/pinnedReads.d.ts +49 -0
  105. package/dist/chain/pinnedReads.js +218 -0
  106. package/dist/chain/prepaid.d.ts +383 -0
  107. package/dist/chain/prepaid.js +1046 -0
  108. package/dist/chain/prepaidEscape.d.ts +274 -0
  109. package/dist/chain/prepaidEscape.js +432 -0
  110. package/dist/chain/prepaidFault.d.ts +94 -0
  111. package/dist/chain/prepaidFault.js +148 -0
  112. package/dist/chain/receipt.d.ts +24 -0
  113. package/dist/chain/receipt.js +82 -0
  114. package/dist/chain/registeredAgent.d.ts +68 -3
  115. package/dist/chain/registeredAgent.js +143 -42
  116. package/dist/chain/registeredOperation.d.ts +10 -1
  117. package/dist/chain/registeredOperation.js +18 -3
  118. package/dist/chain/registeredPaidAgent.d.ts +254 -0
  119. package/dist/chain/registeredPaidAgent.js +889 -0
  120. package/dist/chain/registeredRelay.d.ts +31 -1
  121. package/dist/chain/registeredRelay.js +164 -43
  122. package/dist/chain/relayVoucher.d.ts +64 -0
  123. package/dist/chain/relayVoucher.js +69 -0
  124. package/dist/chain/reservation.d.ts +239 -0
  125. package/dist/chain/reservation.js +746 -0
  126. package/dist/chain/reshareRoster.d.ts +64 -0
  127. package/dist/chain/reshareRoster.js +85 -0
  128. package/dist/chain/revertReason.d.ts +8 -0
  129. package/dist/chain/revertReason.js +2 -1
  130. package/dist/chain/rotationLock.d.ts +130 -0
  131. package/dist/chain/rotationLock.js +168 -0
  132. package/dist/chain/serviceRequestPolicy.d.ts +47 -0
  133. package/dist/chain/serviceRequestPolicy.js +86 -0
  134. package/dist/chain/services.d.ts +7 -0
  135. package/dist/chain/services.js +44 -4
  136. package/dist/chain/slotClient.js +11 -2
  137. package/dist/chain/slotHandoff.d.ts +81 -0
  138. package/dist/chain/slotHandoff.js +166 -0
  139. package/dist/chain/slotSeed.d.ts +47 -5
  140. package/dist/chain/slotSeed.js +173 -42
  141. package/dist/chain/verifierSnapshot.d.ts +36 -0
  142. package/dist/chain/verifierSnapshot.js +197 -0
  143. package/dist/chain/write.d.ts +111 -21
  144. package/dist/chain/write.js +378 -146
  145. package/dist/committee/blsSharing.d.ts +53 -0
  146. package/dist/committee/blsSharing.js +90 -0
  147. package/dist/committee/client.d.ts +62 -23
  148. package/dist/committee/client.js +288 -72
  149. package/dist/committee/dual-operation.d.ts +165 -0
  150. package/dist/committee/dual-operation.js +229 -0
  151. package/dist/committee/dual-sign.d.ts +26 -1
  152. package/dist/committee/dual-sign.js +85 -7
  153. package/dist/committee/ecdsa.d.ts +38 -0
  154. package/dist/committee/ecdsa.js +87 -15
  155. package/dist/committee/evidence.d.ts +30 -0
  156. package/dist/committee/evidence.js +65 -0
  157. package/dist/committee/execution.d.ts +414 -0
  158. package/dist/committee/execution.js +446 -0
  159. package/dist/committee/extraction.js +33 -26
  160. package/dist/committee/index.d.ts +30 -7
  161. package/dist/committee/index.js +18 -6
  162. package/dist/committee/keeperExecution.d.ts +37 -0
  163. package/dist/committee/keeperExecution.js +141 -0
  164. package/dist/committee/oauth.d.ts +14 -4
  165. package/dist/committee/oauth.js +17 -5
  166. package/dist/committee/payment.d.ts +369 -0
  167. package/dist/committee/payment.js +339 -0
  168. package/dist/committee/recovery.d.ts +136 -0
  169. package/dist/committee/recovery.js +204 -0
  170. package/dist/committee/recoveryJson.d.ts +2 -0
  171. package/dist/committee/recoveryJson.js +87 -0
  172. package/dist/committee/request.d.ts +63 -27
  173. package/dist/committee/request.js +77 -66
  174. package/dist/committee/session-grant.d.ts +320 -0
  175. package/dist/committee/session-grant.js +397 -0
  176. package/dist/committee/status-refresh.d.ts +257 -0
  177. package/dist/committee/status-refresh.js +619 -0
  178. package/dist/committee/token.d.ts +163 -15
  179. package/dist/committee/token.js +247 -10
  180. package/dist/crypto/bn254.d.ts +70 -0
  181. package/dist/crypto/bn254.js +222 -0
  182. package/dist/crypto/ibe.d.ts +32 -0
  183. package/dist/crypto/ibe.js +56 -8
  184. package/dist/crypto/index.d.ts +1 -1
  185. package/dist/crypto/index.js +1 -1
  186. package/dist/crypto/kem.d.ts +31 -0
  187. package/dist/crypto/kem.js +113 -7
  188. package/dist/crypto/recipient.d.ts +75 -0
  189. package/dist/crypto/recipient.js +107 -0
  190. package/dist/decryption/client.d.ts +10 -16
  191. package/dist/decryption/client.js +8 -76
  192. package/dist/decryption/index.d.ts +2 -0
  193. package/dist/decryption/index.js +2 -0
  194. package/dist/decryption/sealed.d.ts +72 -0
  195. package/dist/decryption/sealed.js +147 -0
  196. package/dist/decryption/session.d.ts +115 -0
  197. package/dist/decryption/session.js +358 -0
  198. package/dist/errors.d.ts +406 -1
  199. package/dist/errors.js +400 -5
  200. package/dist/index.d.ts +9 -2
  201. package/dist/index.js +6 -1
  202. package/dist/internal/bounded.d.ts +66 -0
  203. package/dist/internal/bounded.js +126 -0
  204. package/dist/internal/network.d.ts +4 -0
  205. package/dist/internal/network.js +40 -0
  206. package/dist/internal/retryAfter.d.ts +8 -0
  207. package/dist/internal/retryAfter.js +28 -0
  208. package/dist/internal/sleep.d.ts +6 -0
  209. package/dist/internal/sleep.js +15 -0
  210. package/dist/internal/typedData.d.ts +13 -0
  211. package/dist/internal/typedData.js +77 -0
  212. package/dist/internal/viemErrors.d.ts +26 -0
  213. package/dist/internal/viemErrors.js +49 -0
  214. package/dist/oid4vp/binding.d.ts +27 -1
  215. package/dist/oid4vp/binding.js +36 -1
  216. package/dist/oid4vp/jose.d.ts +4 -2
  217. package/dist/oid4vp/jose.js +39 -7
  218. package/dist/oid4vp/request-object.d.ts +61 -4
  219. package/dist/oid4vp/request-object.js +140 -5
  220. package/dist/oid4vp/verifier-agent.d.ts +18 -8
  221. package/dist/oid4vp/verifier-agent.js +48 -6
  222. package/dist/oid4vp/wallet.d.ts +2 -4
  223. package/dist/oid4vp/wallet.js +1 -0
  224. package/dist/retry.d.ts +78 -0
  225. package/dist/retry.js +137 -0
  226. package/dist/signing/frost.d.ts +1 -1
  227. package/dist/verifier-agent/index.d.ts +41 -5
  228. package/dist/verifier-agent/index.js +124 -9
  229. package/dist/verifier-agent/payment.d.ts +7 -0
  230. package/dist/verifier-agent/payment.js +17 -0
  231. package/docs/api.md +8 -2
  232. package/docs/application-api.md +25 -2
  233. package/docs/chain.md +155 -9
  234. package/docs/consumer-migrations.md +61 -0
  235. package/docs/encrypted-notes.md +3 -2
  236. package/docs/encryption.md +4 -2
  237. package/docs/errors.md +14 -1
  238. package/docs/flows.md +2 -2
  239. package/docs/funding.md +902 -0
  240. package/docs/native-approvals.md +63 -0
  241. package/docs/reference/README.md +9 -8
  242. package/docs/reference/app-browser.md +232 -0
  243. package/docs/reference/app-node.md +38 -8
  244. package/docs/reference/app.md +4621 -805
  245. package/docs/reference/chain-node.md +74 -16
  246. package/docs/reference/chain.md +6740 -1592
  247. package/docs/reference/committee.md +5630 -987
  248. package/docs/reference/main.md +1439 -140
  249. package/docs/reference/oid4vp.md +297 -144
  250. package/docs/reference/verifier-agent.md +77 -35
  251. package/docs/signing.md +6 -0
  252. package/examples/encrypted-notes.ts +21 -6
  253. package/examples/getting-started.ts +2 -7
  254. package/examples/live-config.ts +24 -17
  255. package/package.json +17 -5
package/dist/app/index.js CHANGED
@@ -9,4 +9,19 @@ export { resolveApplicationManifest, loadApplicationManifest } from './manifest.
9
9
  export { createApplicationSlot, ApplicationSlotRecoveryError } from './ready-slot.js';
10
10
  export { createLocalWallet, connectWallet, createSlotWallet } from './wallet.js';
11
11
  export { createIdentity, issueCredential, verifyCredential, credentialPolicy, credentialAuthorization, presentCredentials } from './identity.js';
12
- export { setApprovalPolicy, identityApprover, approveWithCredential } from './approvals.js';
12
+ export { setApprovalPolicy, readApprovalPolicy, prepareOperationApproval, assembleOperationApproval, identityApprover, approveWithCredential } from './approvals.js';
13
+ export { lockKeyRotation } from './rotation-lock.js';
14
+ // Operation approval builders (the statement each approver signs and the bundle), re-exported beside the app helpers.
15
+ export { approveDualOperation, requireDualOperationProof } from '../committee/dual-operation.js';
16
+ export { createPaidReservationJournal, loadPaidReservationJournal } from './paid-journal.js';
17
+ export { reserveApplicationPayment, reconcileApplicationPayment, reconcileApplicationReservation, selectApplicationGasPayer, ApplicationPayerRecoveryError } from './paid-reservation.js';
18
+ // ADR-0090 allowance lanes (PaidOperationConfig.allowances, default off).
19
+ export { AllowanceRefusedError, AllowanceUnavailableError, AllowanceCapacityError, inspectAllowanceLanes, journaledAllowanceVoucher, allowanceLaneCount } from './paid-allowance.js';
20
+ export { paidOperation, prepareAllowances, paidFinalSign, resumePaidFinalSign, paidSessionDecrypt, resumePaidSessionDecrypt, resumePaidOperation, reconcilePaidOperation, recoverPaidOperation, abandonPaidOperation, paidOperationPhase, listPaidOperations, PaidOperationRecoveryError, PaidOperationAbandonRefusedError, NewerVerifierEpoch } from './paid-operation.js';
21
+ export { SLOT_POLICY_DOMAIN_NAME, SLOT_POLICY_REQUEST_DOMAIN_NAME, SLOT_POLICY_MAX_LIFETIME_SECS, SLOT_POLICY_REQUEST_MAX_AGE_SECS, SlotPolicyError, PolicyOperationError, slotPolicyTypedData, slotPolicyHash, verifySlotPolicyBootstrap, issueSlotPolicyBootstrap, slotPolicyRequestTypedData, createSlotPolicyRequest, verifySlotPolicyRequest } from './policy-bootstrap.js';
22
+ export { paidPolicyOperation, readPolicyOperation } from './policy-operation.js';
23
+ export { drivePaidSession, waitForPaidSnapshot, PaidSessionRecoveryError } from './paid-session.js';
24
+ export { createMemoryStore } from './memory-store.js';
25
+ export { createSessionKey, sessionGrantCreateFragment, acceptSessionGrant, loadGrantedSession, GrantedSession, SessionEndedError, SessionRefreshError, SESSION_REFUSAL_CODES, SESSION_RETRYABLE_CODES, SESSION_VERIFIER_BEHIND_RETRY_MS, SessionRevokeIncompleteError, SessionRevokeUnconfirmedError } from './session-grants.js';
26
+ export { decryptInSession, SessionMessageError, MAX_MESSAGE_DEBITS } from './session-decrypt.js';
27
+ export { signingIntentDigest, signingIntentCurve, requireIntentPayment, approveSigningIntent, SIGNING_INTENT_MAX_BYTES } from './signing-intents.js';
@@ -0,0 +1,7 @@
1
+ import type { ApplicationStore } from './ready-slot.js';
2
+ /**
3
+ * Create a process-local store. Values are deep-copied on save and load (like a durable store,
4
+ * a caller mutating its object never changes saved state), and `withLock` serializes work per
5
+ * key by waiting, in call order.
6
+ */
7
+ export declare function createMemoryStore(): ApplicationStore;
@@ -0,0 +1,55 @@
1
+ // In-memory ApplicationStore: for tests, examples and short-lived processes only.
2
+ //
3
+ // ⚠ Nothing here survives the process. A paid reservation journaled only in memory cannot be
4
+ // reconciled after a crash, so production applications use createFileStore
5
+ // (tasra-sdk/app/node) or createIndexedDbStore (tasra-sdk/app/browser).
6
+ import { TasraError } from '../errors.js';
7
+ const KEY = /^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/;
8
+ /**
9
+ * Create a process-local store. Values are deep-copied on save and load (like a durable store,
10
+ * a caller mutating its object never changes saved state), and `withLock` serializes work per
11
+ * key by waiting, in call order.
12
+ */
13
+ export function createMemoryStore() {
14
+ const values = new Map();
15
+ const tails = new Map();
16
+ const check = (key) => { if (typeof key !== 'string' || !KEY.test(key))
17
+ throw new TasraError('Invalid state key'); };
18
+ return {
19
+ async load(key) {
20
+ check(key);
21
+ return values.has(key) ? structuredClone(values.get(key)) : undefined;
22
+ },
23
+ async save(key, value) {
24
+ check(key);
25
+ values.set(key, structuredClone(value));
26
+ },
27
+ async claim(key) {
28
+ check(key);
29
+ if (values.has(key))
30
+ return false;
31
+ values.set(key, { claimed: true });
32
+ return true;
33
+ },
34
+ async list(prefix) {
35
+ return [...values.keys()].filter(key => key.startsWith(prefix));
36
+ },
37
+ async withLock(key, operation) {
38
+ check(key);
39
+ const previous = tails.get(key) ?? Promise.resolve();
40
+ let release;
41
+ const tail = new Promise(resolve => { release = resolve; });
42
+ const chained = previous.then(() => tail);
43
+ tails.set(key, chained);
44
+ await previous;
45
+ try {
46
+ return await operation();
47
+ }
48
+ finally {
49
+ release();
50
+ if (tails.get(key) === chained)
51
+ tails.delete(key);
52
+ }
53
+ },
54
+ };
55
+ }
@@ -1,4 +1,4 @@
1
- import { TasraError } from '../errors.js';
1
+ import { StoreLockedError } from './store-errors.js';
2
2
  /**
3
3
  * Durable private state storage with exclusive locking for each named operation.
4
4
  */
@@ -15,16 +15,44 @@ export interface ApplicationStore {
15
15
  * Exclusively serialize work for the key across all participating processes or tabs.
16
16
  */
17
17
  withLock<T>(key: string, action: () => Promise<T>): Promise<T>;
18
+ /**
19
+ * Optional: keys starting with `prefix`, in any order. Used only for one-time maintenance
20
+ * such as backfilling the paid operation index; stores without it still work everywhere else.
21
+ */
22
+ list?(prefix: string): Promise<string[]>;
23
+ /**
24
+ * Optional: atomically and durably create the record `key` only if it does not exist, across all
25
+ * participating processes or tabs. Resolves true for exactly one caller, false when the key
26
+ * already exists. Paid approvals use it as a one-use, generation-bound send claim; without it a
27
+ * retained approval is sent once and never resent.
28
+ */
29
+ claim?(key: string): Promise<boolean>;
18
30
  }
31
+ export { StoreLockedError };
19
32
  /**
20
- * A state lock is already held and requires reconciliation before manual removal.
33
+ * Durable-write steps the store counts (for tests and measurement); never part of the stored state.
34
+ * `flushes`: device flushes of a state directory (each one F_FULLFSYNC on macOS), whatever they
35
+ * served; `shared`: those that served a data barrier and a directory sync at once; `fileSyncs`:
36
+ * per-file syncs (only without O_DSYNC).
21
37
  */
22
- export declare class StoreLockedError extends TasraError {
23
- readonly key: string;
24
- constructor(/** Store entry whose exclusive lock could not be acquired. */ key: string);
38
+ export declare const fileStoreSyncCounters: {
39
+ flushes: number;
40
+ shared: number;
41
+ fileSyncs: number;
42
+ };
43
+ /** Options for {@link createFileStore}. */
44
+ export interface FileStoreOptions {
45
+ /**
46
+ * Longest wait, in ms, for a lock held by ANOTHER process before `withLock` refuses with
47
+ * StoreLockedError (default 10000; 0 refuses at once; at most 600000). A lock left by a crashed
48
+ * process is never removed or taken over: after the wait it still needs reconciliation. Calls in
49
+ * this process never refuse each other; they queue in call order.
50
+ */
51
+ lockWaitMs?: number;
25
52
  }
26
53
  /**
27
54
  * The directory is private, trusted application state, not an untrusted shared folder.
28
55
  * @param directory Private application state directory owned by the current operating-system user.
56
+ * @param options Bounded wait for a lock held by another process.
29
57
  */
30
- export declare function createFileStore(directory: string): ApplicationStore;
58
+ export declare function createFileStore(directory: string, options?: FileStoreOptions): ApplicationStore;
package/dist/app/node.js CHANGED
@@ -1,19 +1,13 @@
1
1
  /** Node-only durable private state. Import from @t3foundry/tasra-sdk/app/node. */
2
2
  import { constants } from 'node:fs';
3
- import { mkdir, lstat, open, rename, unlink } from 'node:fs/promises';
3
+ import { mkdir, lstat, open, readdir, rename, unlink } from 'node:fs/promises';
4
4
  import { resolve, join } from 'node:path';
5
5
  import { randomUUID } from 'node:crypto';
6
+ import { AsyncLocalStorage } from 'node:async_hooks';
6
7
  import { TasraError } from '../errors.js';
7
- /**
8
- * A state lock is already held and requires reconciliation before manual removal.
9
- */
10
- export class StoreLockedError extends TasraError {
11
- key;
12
- constructor(/** Store entry whose exclusive lock could not be acquired. */ key) {
13
- super(`State ${key} is locked; reconcile any interrupted operation before removing its lock`);
14
- this.key = key;
15
- }
16
- }
8
+ import { StoreLockedError } from './store-errors.js';
9
+ import { STORE_COMMIT } from './store-commit.js';
10
+ export { StoreLockedError };
17
11
  function encode(value, seen = new Set()) {
18
12
  if (value === null)
19
13
  return ['null'];
@@ -58,102 +52,431 @@ function decode(value) {
58
52
  }
59
53
  }
60
54
  const missing = (error) => error.code === 'ENOENT';
55
+ /** How often one load re-opens a value replaced (renamed over) between its open and its fstat
56
+ * before it reads the superseded value it opened (see `load`). */
57
+ const LOAD_REPLACED_RETRIES = 64;
58
+ // In-process lock queue. Every file store in this process (one directory may have several store
59
+ // objects) queues on the lock FILE's path, in call order, so callers in one process never refuse
60
+ // each other; only a lock file held by ANOTHER process (or left by a crashed one) is waited for,
61
+ // boundedly, and then refused. One entry per path with a waiter or holder; the last one leaving
62
+ // removes it.
63
+ const queues = new Map();
64
+ /** Locks held by the current async call chain: a nested `withLock` on one of them would wait on itself. */
65
+ const holding = new AsyncLocalStorage();
66
+ const sleep = (ms) => new Promise(done => setTimeout(done, ms));
67
+ // Group commit. Every durable write keeps the crash model it always had: a file's data is on
68
+ // stable storage BEFORE the rename (or lock/claim entry) that publishes it can become durable,
69
+ // and a caller is acknowledged only after the directory entry itself is synced. What changes is
70
+ // who pays for the device flush:
71
+ // 1. each file's data is written with O_DSYNC, so write() returns only once the data reached
72
+ // the device (synchronized data integrity, as fdatasync; on Linux this is already a FUA or
73
+ // flush, so durable on its own);
74
+ // 2. ONE device flush, issued after the write returned - on macOS libuv issues
75
+ // `FileHandle.sync()` as `F_FULLFSYNC`, which flushes the drive's whole write cache, so
76
+ // every O_DSYNC write that completed before it is now on stable storage;
77
+ // 3. only then the rename / entry, and ONE more device flush, of the directory, before anyone
78
+ // is told.
79
+ // Both flushes are the SAME step: an `F_FULLFSYNC` of the directory (`fsync` of the directory
80
+ // on Linux, where O_DSYNC data is already stable when write() returns). It makes every entry
81
+ // created, renamed or removed in the directory before it durable AND empties the drive cache, so
82
+ // it is at once the data barrier of every writer whose data is written and the directory sync of
83
+ // every writer whose renames are done. Concurrent commits in different stages therefore share a
84
+ // flush: one commit's directory sync is the next one's data barrier, and a directory has at most
85
+ // one flush in flight. Before this, each write paid its own F_FULLFSYNC and directory sync; macOS
86
+ // serializes those device-wide (about 5 ms each), which capped a process at a few hundred durable
87
+ // writes per second however many callers were waiting.
88
+ // What this relies on, stated plainly: the state directory is on a local APFS (or ext4/xfs)
89
+ // volume, where an O_DSYNC write has reached the device when it returns and a directory flush
90
+ // commits the temporary file's size and extents with the rename (APFS commits the container in
91
+ // ordered transactions). On a network or FAT volume libuv silently falls back from F_FULLFSYNC,
92
+ // and that ordering is not guaranteed; keep the state directory off such volumes. Without
93
+ // O_DSYNC every file is synced on its own and only the directory flush is shared (Windows never
94
+ // gets here: without `process.getuid` `ready()` refuses the directory).
95
+ const DSYNC = constants.O_DSYNC ?? 0;
96
+ /**
97
+ * Coalesce one asynchronous step among concurrent callers. A caller joins the next step that has
98
+ * NOT started yet, so the step always begins after that caller's own preceding work completed;
99
+ * while a step runs, new callers queue for the following one. A failed step rejects exactly the
100
+ * callers that joined it.
101
+ */
102
+ function coalescer(step) {
103
+ let running = Promise.resolve();
104
+ let waiting;
105
+ return (arg) => {
106
+ if (waiting) {
107
+ waiting.args.push(arg);
108
+ return waiting.done;
109
+ }
110
+ const batch = { args: [arg], done: Promise.resolve() };
111
+ batch.done = running.catch(() => { }).then(() => {
112
+ if (waiting === batch)
113
+ waiting = undefined;
114
+ return step(batch.args);
115
+ });
116
+ waiting = batch;
117
+ running = batch.done;
118
+ return batch.done;
119
+ };
120
+ }
121
+ // One flush per directory path, shared by every store object on it in this process.
122
+ const committers = new Map();
123
+ /**
124
+ * Durable-write steps the store counts (for tests and measurement); never part of the stored state.
125
+ * `flushes`: device flushes of a state directory (each one F_FULLFSYNC on macOS), whatever they
126
+ * served; `shared`: those that served a data barrier and a directory sync at once; `fileSyncs`:
127
+ * per-file syncs (only without O_DSYNC).
128
+ */
129
+ export const fileStoreSyncCounters = { flushes: 0, shared: 0, fileSyncs: 0 };
130
+ function committer(root) {
131
+ const found = committers.get(root);
132
+ if (found)
133
+ return found;
134
+ const flush = coalescer(async (purposes) => {
135
+ fileStoreSyncCounters.flushes++;
136
+ if (purposes.includes('data') && purposes.includes('entries'))
137
+ fileStoreSyncCounters.shared++;
138
+ const dir = await open(root, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW);
139
+ try {
140
+ await dir.sync();
141
+ }
142
+ finally {
143
+ await dir.close();
144
+ }
145
+ });
146
+ committers.set(root, flush);
147
+ return flush;
148
+ }
61
149
  /**
62
150
  * The directory is private, trusted application state, not an untrusted shared folder.
63
151
  * @param directory Private application state directory owned by the current operating-system user.
152
+ * @param options Bounded wait for a lock held by another process.
64
153
  */
65
- export function createFileStore(directory) {
154
+ export function createFileStore(directory, options = {}) {
66
155
  const root = resolve(directory);
156
+ const lockWaitMs = options.lockWaitMs ?? 10_000;
157
+ if (!Number.isSafeInteger(lockWaitMs) || lockWaitMs < 0 || lockWaitMs > 600_000)
158
+ throw new TasraError('Invalid file store lock wait');
67
159
  const path = (key, suffix = '.json') => {
68
160
  if (!/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/.test(key))
69
161
  throw new TasraError('Invalid state key');
70
162
  return join(root, key + suffix);
71
163
  };
164
+ /**
165
+ * Check the directory before every operation (created first when absent). One `lstat` when it
166
+ * exists: a recursive `mkdir` of an existing directory is two more metadata calls per operation,
167
+ * and under concurrent device flushes (macOS F_FULLFSYNC) every metadata call waits its turn.
168
+ */
72
169
  async function ready() {
73
- await mkdir(root, { recursive: true, mode: 0o700 });
74
- const stat = await lstat(root);
170
+ let stat;
171
+ try {
172
+ stat = await lstat(root);
173
+ }
174
+ catch (error) {
175
+ if (!missing(error))
176
+ throw error;
177
+ await mkdir(root, { recursive: true, mode: 0o700 });
178
+ stat = await lstat(root);
179
+ }
75
180
  if (!stat.isDirectory() || stat.isSymbolicLink() || (stat.mode & 0o077) !== 0 || stat.uid !== process.getuid?.())
76
181
  throw new TasraError('State directory must be owned by this user with mode 0700');
77
182
  }
78
- async function syncDirectory() {
79
- const dir = await open(root, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW);
183
+ const flush = committer(root);
184
+ const syncDirectory = () => flush('entries');
185
+ /**
186
+ * Create the lock file exclusively. At the head of this process's queue an existing file belongs
187
+ * to another process (or a crashed one): wait for it to go, at most `lockWaitMs`, then refuse.
188
+ * The file is never removed or overwritten here.
189
+ */
190
+ async function acquire(key, target, durableLock) {
191
+ const deadline = Date.now() + lockWaitMs;
192
+ for (let delay = 5;; delay = Math.min(delay * 2, 100)) {
193
+ try {
194
+ return await open(target, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | constants.O_NOFOLLOW | (durableLock ? DSYNC : 0), 0o600);
195
+ }
196
+ catch (error) {
197
+ if (error.code !== 'EEXIST')
198
+ throw error;
199
+ const left = deadline - Date.now();
200
+ if (left <= 0)
201
+ throw new StoreLockedError(key);
202
+ await sleep(Math.min(delay, left));
203
+ }
204
+ }
205
+ }
206
+ /**
207
+ * Write every value to its own temporary file (O_DSYNC), then make all of their data durable
208
+ * together: one coalesced directory flush issued after the last write returned (or each file's
209
+ * own sync without O_DSYNC). Nothing is renamed
210
+ * here, so nothing is published before its data is on stable storage. The temporaries are
211
+ * independent files, so they are created and written concurrently: under concurrent device
212
+ * flushes each metadata call and O_DSYNC write waits its turn, and one commit stages up to
213
+ * eight of them (C20: ~90 ms in a row on the 32-stream bench).
214
+ */
215
+ async function stageFiles(entries) {
216
+ const encoded = entries.map(([key, value]) => ({ target: path(key), contents: JSON.stringify({ schemaVersion: 1, value }) + "\n" }));
217
+ await ready();
218
+ const written = [];
219
+ const files = [];
80
220
  try {
81
- await dir.sync();
221
+ // `written` keeps entry order (publish renames by it); every opened handle is recorded before
222
+ // any await can fail, so a failure closes and removes all of them.
223
+ const slots = encoded.map(({ target }) => ({ temporary: join(root, `.${randomUUID()}.tmp`), target }));
224
+ const outcomes = await Promise.allSettled(slots.map(async ({ temporary }, i) => {
225
+ const file = await open(temporary, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | constants.O_NOFOLLOW | DSYNC, 0o600);
226
+ files.push(file);
227
+ written.push(slots[i]);
228
+ await file.writeFile(encoded[i].contents, 'utf8');
229
+ }));
230
+ const failed = outcomes.find(o => o.status === 'rejected');
231
+ if (failed)
232
+ throw failed.reason;
233
+ written.sort((a, b) => slots.indexOf(a) - slots.indexOf(b));
234
+ if (DSYNC === 0)
235
+ for (const file of files) {
236
+ fileStoreSyncCounters.fileSyncs++;
237
+ await file.sync();
238
+ }
239
+ else if (files.length > 0)
240
+ await flush('data');
241
+ return written;
242
+ }
243
+ catch (error) {
244
+ await discard(written);
245
+ throw error;
82
246
  }
83
247
  finally {
84
- await dir.close();
248
+ await Promise.all(files.map(file => file.close()));
85
249
  }
86
250
  }
87
- return {
88
- async load(key) {
89
- const target = path(key);
90
- await ready();
91
- let file;
92
- try {
93
- file = await open(target, constants.O_RDONLY | constants.O_NOFOLLOW);
251
+ async function discard(written) {
252
+ for (const { temporary } of written)
253
+ await unlink(temporary).catch(error => { if (!missing(error))
254
+ throw error; });
255
+ }
256
+ /** Rename durable temporaries into place, in order; a temporary left by a failure is removed. */
257
+ async function publish(written) {
258
+ try {
259
+ for (const { temporary, target } of written)
260
+ await rename(temporary, target);
261
+ }
262
+ catch (error) {
263
+ await discard(written);
264
+ throw error;
265
+ }
266
+ }
267
+ /**
268
+ * Take the locks of `keys` (distinct, in sorted order, so two callers never wait on each other),
269
+ * each in call order within this process (another process's lock is waited for, boundedly), run
270
+ * `action`, and always remove every lock. `durableLock` syncs the lock entries before the
271
+ * action runs; otherwise they become durable with the first directory sync after them.
272
+ * `release` runs after a successful action with the locks still held, and returns whether their
273
+ * removal still needs its own directory sync.
274
+ */
275
+ async function locked(keys, durableLock, action, release) {
276
+ const targets = [...new Set(keys)].sort().map(key => ({ key, target: path(key, '.lock') }));
277
+ // A nested lock on a key this call chain already holds can never be granted: refuse at once,
278
+ // exactly as before, instead of queueing behind itself.
279
+ const current = holding.getStore() ?? [];
280
+ for (const { key, target } of targets)
281
+ if (current.some(held => held.path === target && !held.released))
282
+ throw new StoreLockedError(key);
283
+ const turns = [];
284
+ const held = [];
285
+ // Distinct lock files, all removed before the caller's one directory sync: concurrently.
286
+ // Every lock is marked closed before any removal settles, so after a failure no caller runs
287
+ // its sync (nothing is left open): the removals that DID succeed are synced here, once every
288
+ // removal has settled, and the first failure is reported.
289
+ const unlock = async () => {
290
+ const outcomes = await Promise.allSettled(held.map(async (h) => {
291
+ h.released = true;
292
+ if (!h.open)
293
+ return false;
294
+ h.open = false;
295
+ await h.lock.close();
296
+ await unlink(h.path);
297
+ return true;
298
+ }));
299
+ const failed = outcomes.find(o => o.status === 'rejected');
300
+ if (!failed)
301
+ return;
302
+ if (outcomes.some(o => o.status === 'fulfilled' && o.value))
303
+ await syncDirectory().catch(() => { });
304
+ throw failed.reason;
305
+ };
306
+ try {
307
+ // The directory is checked once per lock set (before the first lock), not once per key.
308
+ let checked = false;
309
+ for (const { key, target } of targets) {
310
+ // Join the queue synchronously, so callers are served in call order.
311
+ const previous = queues.get(target) ?? Promise.resolve();
312
+ let done;
313
+ const turn = new Promise(resolve => { done = resolve; });
314
+ const tail = previous.then(() => turn);
315
+ queues.set(target, tail);
316
+ turns.push({ target, tail, done });
317
+ await previous;
318
+ if (!checked) {
319
+ await ready();
320
+ checked = true;
321
+ }
322
+ const lock = await acquire(key, target, durableLock);
323
+ held.push({ path: target, released: false, lock, open: true });
324
+ await lock.writeFile(JSON.stringify({ pid: process.pid, createdAt: new Date().toISOString() }));
94
325
  }
95
- catch (error) {
96
- if (missing(error))
97
- return undefined;
98
- throw error;
326
+ if (durableLock) {
327
+ // The lock's content is a diagnostic nothing reads; only its entry must be durable. With
328
+ // O_DSYNC its data reached the device during the write (Linux: on stable storage; macOS:
329
+ // the directory's F_FULLFSYNC empties the drive cache), so the directory flush suffices.
330
+ if (DSYNC === 0)
331
+ for (const h of held) {
332
+ fileStoreSyncCounters.fileSyncs++;
333
+ await h.lock.sync();
334
+ }
335
+ await syncDirectory();
99
336
  }
100
- try {
101
- const stat = await file.stat();
102
- if (!stat.isFile() || stat.nlink !== 1 || (stat.mode & 0o077) !== 0 || stat.uid !== process.getuid?.())
103
- throw new TasraError('State file must be a private regular file');
104
- const envelope = JSON.parse(await file.readFile('utf8'));
105
- if (envelope.schemaVersion !== 1)
106
- throw new TasraError('Unsupported state schema');
107
- return decode(envelope.value);
337
+ const result = await holding.run([...current, ...held], action);
338
+ if (release && !await release(unlock))
339
+ return result;
340
+ await unlock();
341
+ await syncDirectory();
342
+ return result;
343
+ }
344
+ catch (error) {
345
+ if (held.some(h => h.open)) {
346
+ await unlock();
347
+ await syncDirectory();
108
348
  }
109
- finally {
110
- await file.close();
349
+ throw error;
350
+ }
351
+ finally {
352
+ for (const h of held)
353
+ h.released = true;
354
+ for (const { target, tail, done } of turns) {
355
+ done();
356
+ if (queues.get(target) === tail)
357
+ queues.delete(target);
111
358
  }
359
+ }
360
+ }
361
+ const steps = {
362
+ // Every store object on this directory with this lock wait reads and writes the same files
363
+ // under the same in-process lock queues and committer: one state.
364
+ identity: `file:${lockWaitMs}:${root}`,
365
+ async withCommit(keys, action) {
366
+ const staged = new Map();
367
+ return locked(typeof keys === 'string' ? [keys] : keys, false, () => action({ stage: (k, v) => { path(k); staged.delete(k); staged.set(k, encode(v)); } }), async (unlock) => {
368
+ if (staged.size === 0)
369
+ return true;
370
+ const written = await stageFiles([...staged]);
371
+ await publish(written);
372
+ // One directory sync publishes every rename AND the removed lock.
373
+ await unlock();
374
+ await syncDirectory();
375
+ return false;
376
+ });
112
377
  },
113
- async save(key, value) {
114
- const target = path(key), contents = JSON.stringify({ schemaVersion: 1, value: encode(value) }) + '\n';
378
+ async saveAll(entries) {
379
+ if (entries.length === 0)
380
+ return;
381
+ await publish(await stageFiles(entries.map(([key, value]) => [key, encode(value)])));
382
+ await syncDirectory();
383
+ },
384
+ async saveRederivable(key, value) {
385
+ await publish(await stageFiles([[key, encode(value)]]));
386
+ },
387
+ };
388
+ const store = {
389
+ async load(key) {
390
+ const target = path(key);
115
391
  await ready();
116
- const temporary = join(root, `.${randomUUID()}.tmp`);
117
- const file = await open(temporary, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | constants.O_NOFOLLOW, 0o600);
118
- try {
392
+ // Every save publishes by renaming a new file OVER the old one, so a load that opened the old
393
+ // value an instant before holds an inode no name refers to any more: fstat reports nlink 0.
394
+ // That inode is a superseded value, not the file at `target`; read the one that replaced it
395
+ // (whose every property is checked again), a bounded number of times.
396
+ //
397
+ // If every attempt lost that race, read the superseded inode itself: it WAS the value at
398
+ // `target` when it was opened (O_NOFOLLOW, by name), so returning it is an ordinary read
399
+ // ordered just before the commit that replaced it. It still must be a private regular file
400
+ // of ours; only the link count differs, and nlink 0 cannot be a planted hard link (that has
401
+ // a second name, so nlink >= 2, which stays refused). Refusing it instead turned writer
402
+ // contention into a load FAILURE (tasra-sdk 4e67a60, release cert 44454169835 on EC2):
403
+ // open and fstat both queue in libuv's 4-thread pool behind the committers' O_DSYNC writes
404
+ // and directory syncs, so on a slow-fsync host a rename lands in that window attempt after
405
+ // attempt and all 64 retries lose.
406
+ for (let attempt = 0;; attempt++) {
407
+ let file;
119
408
  try {
120
- await file.writeFile(contents, 'utf8');
121
- await file.sync();
409
+ file = await open(target, constants.O_RDONLY | constants.O_NOFOLLOW);
410
+ }
411
+ catch (error) {
412
+ if (missing(error))
413
+ return undefined;
414
+ throw error;
415
+ }
416
+ try {
417
+ const stat = await file.stat();
418
+ if (stat.nlink === 0 && stat.isFile() && attempt < LOAD_REPLACED_RETRIES)
419
+ continue;
420
+ const superseded = stat.nlink === 0;
421
+ if (!stat.isFile() || (stat.nlink !== 1 && !superseded) || (stat.mode & 0o077) !== 0 || stat.uid !== process.getuid?.())
422
+ throw new TasraError('State file must be a private regular file');
423
+ const envelope = JSON.parse(await file.readFile('utf8'));
424
+ if (envelope.schemaVersion !== 1)
425
+ throw new TasraError('Unsupported state schema');
426
+ return decode(envelope.value);
122
427
  }
123
428
  finally {
124
429
  await file.close();
125
430
  }
126
- await rename(temporary, target);
127
- await syncDirectory();
128
- }
129
- finally {
130
- await unlink(temporary).catch(error => { if (!missing(error))
131
- throw error; });
132
431
  }
133
432
  },
134
- async withLock(key, action) {
135
- const target = path(key, '.lock');
433
+ async save(key, value) {
434
+ await publish(await stageFiles([[key, encode(value)]]));
435
+ await syncDirectory();
436
+ },
437
+ async list(prefix) {
438
+ await ready();
439
+ // Saved values are `<key>.json`; temporaries start with a dot and locks end in `.lock`.
440
+ return (await readdir(root)).filter(name => name.endsWith('.json') && /^[a-zA-Z0-9]/.test(name))
441
+ .map(name => name.slice(0, -'.json'.length)).filter(key => key.startsWith(prefix));
442
+ },
443
+ async claim(key) {
444
+ // `O_CREAT | O_EXCL` on the record itself is the exclusive claim, across threads and
445
+ // processes: exactly one creator wins, every other gets EEXIST. The entry exists before the
446
+ // write, so ONE directory flush issued after the write returns makes both durable before
447
+ // this resolves (without O_DSYNC the file is synced on its own first). A crash before that
448
+ // flush may leave the entry without its content, exactly as a crash mid-write always could:
449
+ // the key stays claimed (its content is only a diagnostic), which is the safe direction.
450
+ const target = path(key), contents = JSON.stringify({ schemaVersion: 1, value: encode({ claimed: true }) }) + '\n';
136
451
  await ready();
137
- let lock;
452
+ let file;
138
453
  try {
139
- lock = await open(target, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | constants.O_NOFOLLOW, 0o600);
454
+ file = await open(target, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | constants.O_NOFOLLOW | DSYNC, 0o600);
140
455
  }
141
456
  catch (error) {
142
457
  if (error.code === 'EEXIST')
143
- throw new StoreLockedError(key);
458
+ return false;
144
459
  throw error;
145
460
  }
146
461
  try {
147
- await lock.writeFile(JSON.stringify({ pid: process.pid, createdAt: new Date().toISOString() }));
148
- await lock.sync();
149
- await syncDirectory();
150
- return await action();
462
+ await file.writeFile(contents, 'utf8');
463
+ if (DSYNC === 0) {
464
+ fileStoreSyncCounters.fileSyncs++;
465
+ await file.sync();
466
+ }
151
467
  }
152
468
  finally {
153
- await lock.close();
154
- await unlink(target);
155
- await syncDirectory();
469
+ await file.close();
156
470
  }
471
+ await syncDirectory();
472
+ return true;
157
473
  },
474
+ withLock(key, action) { return locked([key], true, action); },
158
475
  };
476
+ // Not enumerable: an application wrapper `{...store, load: wrapped}` must not copy the native
477
+ // steps, or it would share this store's identity (and its journal commit batches, whose duplicate
478
+ // check reads through the first caller's `load`) while behaving differently. A copy is an
479
+ // ordinary application store: it gets the generic one-save-at-a-time path.
480
+ Object.defineProperty(store, STORE_COMMIT, { value: steps, enumerable: false, writable: false, configurable: false });
481
+ return store;
159
482
  }