Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

codexResetCredit.ts

113 lines4.2 KB

1/**
2 * Redeeming a Codex reset credit is an account-level action: instances that
3 * share the directory holding `auth.json` share the credit, so their
4 * redemptions must serialise on that directory, not the instance. This
5 * service keeps one lock and one pending idempotency key per account key so
6 * overlapping confirmations from any instance queue rather than spending two
7 * credits, and a retry after a timeout re-sends the same attempt.
8 *
9 * @module provider/Layers/codexResetCredit
10 */
11import type { ProviderConsumeResetCreditOutcome } from "@t3tools/contracts";
12import * as Context from "effect/Context";
13import * as Crypto from "effect/Crypto";
14import * as Duration from "effect/Duration";
15import * as Effect from "effect/Effect";
16import * as Layer from "effect/Layer";
17import type * as PlatformError from "effect/PlatformError";
18import * as Ref from "effect/Ref";
19import * as Semaphore from "effect/Semaphore";
20​
21/**
22 * Bounded so a hung app-server cannot hold the account lock forever; the
23 * timeout interrupts the scoped request, which kills the process, and the
24 * kept idempotency key makes the user's retry safe.
25 */
26export const CODEX_RESET_CREDIT_TIMEOUT = Duration.seconds(20);
27​
28interface AccountRedemptionState {
29 readonly lock: Semaphore.Semaphore;
30 readonly pendingKey: Ref.Ref<string | null>;
32​
33export class CodexResetCreditCoordinator extends Context.Service<
34 CodexResetCreditCoordinator,
35 {
36 /**
37 * Run `consume` under the account's lock with a stable idempotency key.
38 * The key is cleared only when Codex reports an outcome; a failure
39 * (timeout included) keeps it so the next attempt is the same attempt.
40 */
41 readonly redeem: <E, R>(
42 accountKey: string,
43 consume: (idempotencyKey: string) => Effect.Effect<ProviderConsumeResetCreditOutcome, E, R>,
44 ) => Effect.Effect<ProviderConsumeResetCreditOutcome, E | PlatformError.PlatformError, R>;
45 }
46>()("t3/provider/Layers/codexResetCredit/CodexResetCreditCoordinator") {}
47​
48export const make = Effect.gen(function* () {
49 const crypto = yield* Crypto.Crypto;
50 const statesRef = yield* Ref.make<ReadonlyMap<string, AccountRedemptionState>>(new Map());
51​
52 // Get-or-create through one Ref.modify so two first redemptions for the
53 // same account cannot each install their own lock.
54 const stateFor = Effect.fn("CodexResetCreditCoordinator.stateFor")(function* (
55 accountKey: string,
56 ) {
57 const existing = (yield* Ref.get(statesRef)).get(accountKey);
58 if (existing) return existing;
59 const candidate = {
60 lock: yield* Semaphore.make(1),
61 pendingKey: yield* Ref.make<string | null>(null),
62 };
63 return yield* Ref.modify(statesRef, (states) => {
64 const current = states.get(accountKey);
65 if (current) return [current, states] as const;
66 const next = new Map(states);
67 next.set(accountKey, candidate);
68 return [candidate, next] as const;
69 });
70 });
71​
72 const redeem: CodexResetCreditCoordinator["Service"]["redeem"] = (accountKey, consume) =>
73 Effect.gen(function* () {
74 const state = yield* stateFor(accountKey);
75 return yield* state.lock.withPermits(1)(
76 Effect.gen(function* () {
77 const existing = yield* Ref.get(state.pendingKey);
78 const idempotencyKey = existing ?? (yield* crypto.randomUUIDv4);
79 yield* Ref.set(state.pendingKey, idempotencyKey);
80 const outcome = yield* consume(idempotencyKey);
81 yield* Ref.set(state.pendingKey, null);
82 return outcome;
83 }),
84 );
85 });
86​
87 return { redeem } satisfies CodexResetCreditCoordinator["Service"];
88});
89​
90export const layer = Layer.effect(CodexResetCreditCoordinator, make);
91​
92/**
93 * Self-contained for tests: a counter-backed Crypto so keys are deterministic
94 * and distinct without the platform layer.
95 */
96export const layerTest = Layer.effect(
97 CodexResetCreditCoordinator,
98 Effect.gen(function* () {
99 let counter = 0;
100 return yield* make.pipe(
101 Effect.provideService(
102 Crypto.Crypto,
103 Crypto.make({
104 randomBytes: (size) => {
105 counter += 1;
106 return new Uint8Array(size).fill(counter);
107 },
108 digest: (_algorithm, data) => Effect.succeed(data),
109 }),
110 ),
111 );
112 }),
113);