@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.
- package/CHANGELOG.md +1067 -28
- package/README.md +15 -0
- package/dist/app/approvals.d.ts +66 -4
- package/dist/app/approvals.js +153 -16
- package/dist/app/authorization.d.ts +1 -1
- package/dist/app/authorization.js +1 -1
- package/dist/app/browser.d.ts +63 -0
- package/dist/app/browser.js +242 -0
- package/dist/app/client.d.ts +114 -13
- package/dist/app/client.js +302 -76
- package/dist/app/identity.js +21 -9
- package/dist/app/index.d.ts +28 -3
- package/dist/app/index.js +16 -1
- package/dist/app/memory-store.d.ts +7 -0
- package/dist/app/memory-store.js +55 -0
- package/dist/app/node.d.ts +34 -6
- package/dist/app/node.js +387 -64
- package/dist/app/paid-allowance.d.ts +325 -0
- package/dist/app/paid-allowance.js +1290 -0
- package/dist/app/paid-approval.d.ts +122 -0
- package/dist/app/paid-approval.js +379 -0
- package/dist/app/paid-journal.d.ts +51 -0
- package/dist/app/paid-journal.js +117 -0
- package/dist/app/paid-keys.d.ts +12 -0
- package/dist/app/paid-keys.js +20 -0
- package/dist/app/paid-operation.d.ts +821 -0
- package/dist/app/paid-operation.js +1720 -0
- package/dist/app/paid-reservation.d.ts +157 -0
- package/dist/app/paid-reservation.js +323 -0
- package/dist/app/paid-session.d.ts +147 -0
- package/dist/app/paid-session.js +578 -0
- package/dist/app/payer-queue.d.ts +11 -0
- package/dist/app/payer-queue.js +27 -0
- package/dist/app/policy-bootstrap.d.ts +342 -0
- package/dist/app/policy-bootstrap.js +365 -0
- package/dist/app/policy-operation.d.ts +47 -0
- package/dist/app/policy-operation.js +101 -0
- package/dist/app/ready-slot.d.ts +12 -0
- package/dist/app/ready-slot.js +5 -2
- package/dist/app/rotation-lock.d.ts +38 -0
- package/dist/app/rotation-lock.js +42 -0
- package/dist/app/session-decrypt.d.ts +135 -0
- package/dist/app/session-decrypt.js +335 -0
- package/dist/app/session-grants.d.ts +349 -0
- package/dist/app/session-grants.js +811 -0
- package/dist/app/signing-intents.d.ts +78 -0
- package/dist/app/signing-intents.js +95 -0
- package/dist/app/store-commit.d.ts +63 -0
- package/dist/app/store-commit.js +126 -0
- package/dist/app/store-errors.d.ts +8 -0
- package/dist/app/store-errors.js +11 -0
- package/dist/app/tasra-client.d.ts +2 -0
- package/dist/app/tasra-client.js +1 -1
- package/dist/app/wallet.js +4 -1
- package/dist/auth/holderProof.d.ts +3 -0
- package/dist/auth/holderProof.js +8 -7
- package/dist/auth/verifier.d.ts +4 -2
- package/dist/auth/verifier.js +5 -2
- package/dist/chain/abis/index.d.ts +6178 -4101
- package/dist/chain/abis/index.js +3 -0
- package/dist/chain/abis/keyRegistry.d.ts +256 -0
- package/dist/chain/abis/keyRegistry.js +333 -0
- package/dist/chain/abis/prepaidFaultOracle.d.ts +321 -0
- package/dist/chain/abis/prepaidFaultOracle.js +413 -0
- package/dist/chain/abis/settlement.d.ts +2203 -703
- package/dist/chain/abis/settlement.js +2685 -764
- package/dist/chain/allowance.d.ts +358 -0
- package/dist/chain/allowance.js +800 -0
- package/dist/chain/billing.d.ts +85 -0
- package/dist/chain/billing.js +197 -0
- package/dist/chain/chainId.d.ts +13 -0
- package/dist/chain/chainId.js +26 -0
- package/dist/chain/client.d.ts +15 -1
- package/dist/chain/client.js +57 -1
- package/dist/chain/commitmentRecovery.d.ts +51 -0
- package/dist/chain/commitmentRecovery.js +38 -0
- package/dist/chain/committeeClient.d.ts +17 -10
- package/dist/chain/committeeClient.js +64 -16
- package/dist/chain/committeeDraw.d.ts +12 -0
- package/dist/chain/committeeDraw.js +56 -0
- package/dist/chain/custodyHealth.d.ts +212 -0
- package/dist/chain/custodyHealth.js +365 -0
- package/dist/chain/deployments.js +2 -0
- package/dist/chain/events.js +2 -0
- package/dist/chain/headFollower.d.ts +77 -0
- package/dist/chain/headFollower.js +219 -0
- package/dist/chain/headPrefetch.d.ts +23 -0
- package/dist/chain/headPrefetch.js +67 -0
- package/dist/chain/index.d.ts +50 -8
- package/dist/chain/index.js +28 -3
- package/dist/chain/keeperExecution.d.ts +44 -0
- package/dist/chain/keeperExecution.js +127 -0
- package/dist/chain/keeperRecovery.d.ts +78 -0
- package/dist/chain/keeperRecovery.js +91 -0
- package/dist/chain/node.d.ts +24 -1
- package/dist/chain/node.js +88 -43
- package/dist/chain/offchain.d.ts +2 -0
- package/dist/chain/paidAgentTransport.d.ts +38 -0
- package/dist/chain/paidAgentTransport.js +1 -0
- package/dist/chain/paidEpoch.d.ts +66 -0
- package/dist/chain/paidEpoch.js +139 -0
- package/dist/chain/paidPacing.d.ts +81 -0
- package/dist/chain/paidPacing.js +136 -0
- package/dist/chain/pinnedReads.d.ts +49 -0
- package/dist/chain/pinnedReads.js +218 -0
- package/dist/chain/prepaid.d.ts +383 -0
- package/dist/chain/prepaid.js +1046 -0
- package/dist/chain/prepaidEscape.d.ts +274 -0
- package/dist/chain/prepaidEscape.js +432 -0
- package/dist/chain/prepaidFault.d.ts +94 -0
- package/dist/chain/prepaidFault.js +148 -0
- package/dist/chain/receipt.d.ts +24 -0
- package/dist/chain/receipt.js +82 -0
- package/dist/chain/registeredAgent.d.ts +68 -3
- package/dist/chain/registeredAgent.js +143 -42
- package/dist/chain/registeredOperation.d.ts +10 -1
- package/dist/chain/registeredOperation.js +18 -3
- package/dist/chain/registeredPaidAgent.d.ts +254 -0
- package/dist/chain/registeredPaidAgent.js +889 -0
- package/dist/chain/registeredRelay.d.ts +31 -1
- package/dist/chain/registeredRelay.js +164 -43
- package/dist/chain/relayVoucher.d.ts +64 -0
- package/dist/chain/relayVoucher.js +69 -0
- package/dist/chain/reservation.d.ts +239 -0
- package/dist/chain/reservation.js +746 -0
- package/dist/chain/reshareRoster.d.ts +64 -0
- package/dist/chain/reshareRoster.js +85 -0
- package/dist/chain/revertReason.d.ts +8 -0
- package/dist/chain/revertReason.js +2 -1
- package/dist/chain/rotationLock.d.ts +130 -0
- package/dist/chain/rotationLock.js +168 -0
- package/dist/chain/serviceRequestPolicy.d.ts +47 -0
- package/dist/chain/serviceRequestPolicy.js +86 -0
- package/dist/chain/services.d.ts +7 -0
- package/dist/chain/services.js +44 -4
- package/dist/chain/slotClient.js +11 -2
- package/dist/chain/slotHandoff.d.ts +81 -0
- package/dist/chain/slotHandoff.js +166 -0
- package/dist/chain/slotSeed.d.ts +47 -5
- package/dist/chain/slotSeed.js +173 -42
- package/dist/chain/verifierSnapshot.d.ts +36 -0
- package/dist/chain/verifierSnapshot.js +197 -0
- package/dist/chain/write.d.ts +111 -21
- package/dist/chain/write.js +378 -146
- package/dist/committee/blsSharing.d.ts +53 -0
- package/dist/committee/blsSharing.js +90 -0
- package/dist/committee/client.d.ts +62 -23
- package/dist/committee/client.js +288 -72
- package/dist/committee/dual-operation.d.ts +165 -0
- package/dist/committee/dual-operation.js +229 -0
- package/dist/committee/dual-sign.d.ts +26 -1
- package/dist/committee/dual-sign.js +85 -7
- package/dist/committee/ecdsa.d.ts +38 -0
- package/dist/committee/ecdsa.js +87 -15
- package/dist/committee/evidence.d.ts +30 -0
- package/dist/committee/evidence.js +65 -0
- package/dist/committee/execution.d.ts +414 -0
- package/dist/committee/execution.js +446 -0
- package/dist/committee/extraction.js +33 -26
- package/dist/committee/index.d.ts +30 -7
- package/dist/committee/index.js +18 -6
- package/dist/committee/keeperExecution.d.ts +37 -0
- package/dist/committee/keeperExecution.js +141 -0
- package/dist/committee/oauth.d.ts +14 -4
- package/dist/committee/oauth.js +17 -5
- package/dist/committee/payment.d.ts +369 -0
- package/dist/committee/payment.js +339 -0
- package/dist/committee/recovery.d.ts +136 -0
- package/dist/committee/recovery.js +204 -0
- package/dist/committee/recoveryJson.d.ts +2 -0
- package/dist/committee/recoveryJson.js +87 -0
- package/dist/committee/request.d.ts +63 -27
- package/dist/committee/request.js +77 -66
- package/dist/committee/session-grant.d.ts +320 -0
- package/dist/committee/session-grant.js +397 -0
- package/dist/committee/status-refresh.d.ts +257 -0
- package/dist/committee/status-refresh.js +619 -0
- package/dist/committee/token.d.ts +163 -15
- package/dist/committee/token.js +247 -10
- package/dist/crypto/bn254.d.ts +70 -0
- package/dist/crypto/bn254.js +222 -0
- package/dist/crypto/ibe.d.ts +32 -0
- package/dist/crypto/ibe.js +56 -8
- package/dist/crypto/index.d.ts +1 -1
- package/dist/crypto/index.js +1 -1
- package/dist/crypto/kem.d.ts +31 -0
- package/dist/crypto/kem.js +113 -7
- package/dist/crypto/recipient.d.ts +75 -0
- package/dist/crypto/recipient.js +107 -0
- package/dist/decryption/client.d.ts +10 -16
- package/dist/decryption/client.js +8 -76
- package/dist/decryption/index.d.ts +2 -0
- package/dist/decryption/index.js +2 -0
- package/dist/decryption/sealed.d.ts +72 -0
- package/dist/decryption/sealed.js +147 -0
- package/dist/decryption/session.d.ts +115 -0
- package/dist/decryption/session.js +358 -0
- package/dist/errors.d.ts +406 -1
- package/dist/errors.js +400 -5
- package/dist/index.d.ts +9 -2
- package/dist/index.js +6 -1
- package/dist/internal/bounded.d.ts +66 -0
- package/dist/internal/bounded.js +126 -0
- package/dist/internal/network.d.ts +4 -0
- package/dist/internal/network.js +40 -0
- package/dist/internal/retryAfter.d.ts +8 -0
- package/dist/internal/retryAfter.js +28 -0
- package/dist/internal/sleep.d.ts +6 -0
- package/dist/internal/sleep.js +15 -0
- package/dist/internal/typedData.d.ts +13 -0
- package/dist/internal/typedData.js +77 -0
- package/dist/internal/viemErrors.d.ts +26 -0
- package/dist/internal/viemErrors.js +49 -0
- package/dist/oid4vp/binding.d.ts +27 -1
- package/dist/oid4vp/binding.js +36 -1
- package/dist/oid4vp/jose.d.ts +4 -2
- package/dist/oid4vp/jose.js +39 -7
- package/dist/oid4vp/request-object.d.ts +61 -4
- package/dist/oid4vp/request-object.js +140 -5
- package/dist/oid4vp/verifier-agent.d.ts +18 -8
- package/dist/oid4vp/verifier-agent.js +48 -6
- package/dist/oid4vp/wallet.d.ts +2 -4
- package/dist/oid4vp/wallet.js +1 -0
- package/dist/retry.d.ts +78 -0
- package/dist/retry.js +137 -0
- package/dist/signing/frost.d.ts +1 -1
- package/dist/verifier-agent/index.d.ts +41 -5
- package/dist/verifier-agent/index.js +124 -9
- package/dist/verifier-agent/payment.d.ts +7 -0
- package/dist/verifier-agent/payment.js +17 -0
- package/docs/api.md +8 -2
- package/docs/application-api.md +25 -2
- package/docs/chain.md +155 -9
- package/docs/consumer-migrations.md +61 -0
- package/docs/encrypted-notes.md +3 -2
- package/docs/encryption.md +4 -2
- package/docs/errors.md +14 -1
- package/docs/flows.md +2 -2
- package/docs/funding.md +902 -0
- package/docs/native-approvals.md +63 -0
- package/docs/reference/README.md +9 -8
- package/docs/reference/app-browser.md +232 -0
- package/docs/reference/app-node.md +38 -8
- package/docs/reference/app.md +4621 -805
- package/docs/reference/chain-node.md +74 -16
- package/docs/reference/chain.md +6740 -1592
- package/docs/reference/committee.md +5630 -987
- package/docs/reference/main.md +1439 -140
- package/docs/reference/oid4vp.md +297 -144
- package/docs/reference/verifier-agent.md +77 -35
- package/docs/signing.md +6 -0
- package/examples/encrypted-notes.ts +21 -6
- package/examples/getting-started.ts +2 -7
- package/examples/live-config.ts +24 -17
- 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
|
+
}
|
package/dist/app/node.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
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
|
-
*
|
|
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
|
|
23
|
-
|
|
24
|
-
|
|
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
|
-
|
|
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
|
-
|
|
74
|
-
|
|
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
|
-
|
|
79
|
-
|
|
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
|
-
|
|
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
|
|
248
|
+
await Promise.all(files.map(file => file.close()));
|
|
85
249
|
}
|
|
86
250
|
}
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
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
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
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
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
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
|
-
|
|
110
|
-
|
|
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
|
|
114
|
-
|
|
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
|
-
|
|
117
|
-
|
|
118
|
-
|
|
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
|
|
121
|
-
|
|
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
|
|
135
|
-
|
|
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
|
|
452
|
+
let file;
|
|
138
453
|
try {
|
|
139
|
-
|
|
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
|
-
|
|
458
|
+
return false;
|
|
144
459
|
throw error;
|
|
145
460
|
}
|
|
146
461
|
try {
|
|
147
|
-
await
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
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
|
|
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
|
}
|