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

codexResetCredit.ts

114 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​
48/** @public Service construction is part of the canonical Effect module API. */
49export const make = Effect.gen(function* () {
50 const crypto = yield* Crypto.Crypto;
51 const statesRef = yield* Ref.make<ReadonlyMap<string, AccountRedemptionState>>(new Map());
52​
53 // Get-or-create through one Ref.modify so two first redemptions for the
54 // same account cannot each install their own lock.
55 const stateFor = Effect.fn("CodexResetCreditCoordinator.stateFor")(function* (
56 accountKey: string,
57 ) {
58 const existing = (yield* Ref.get(statesRef)).get(accountKey);
59 if (existing) return existing;
60 const candidate = {
61 lock: yield* Semaphore.make(1),
62 pendingKey: yield* Ref.make<string | null>(null),
63 };
64 return yield* Ref.modify(statesRef, (states) => {
65 const current = states.get(accountKey);
66 if (current) return [current, states] as const;
67 const next = new Map(states);
68 next.set(accountKey, candidate);
69 return [candidate, next] as const;
70 });
71 });
72​
73 const redeem: CodexResetCreditCoordinator["Service"]["redeem"] = (accountKey, consume) =>
74 Effect.gen(function* () {
75 const state = yield* stateFor(accountKey);
76 return yield* state.lock.withPermits(1)(
77 Effect.gen(function* () {
78 const existing = yield* Ref.get(state.pendingKey);
79 const idempotencyKey = existing ?? (yield* crypto.randomUUIDv4);
80 yield* Ref.set(state.pendingKey, idempotencyKey);
81 const outcome = yield* consume(idempotencyKey);
82 yield* Ref.set(state.pendingKey, null);
83 return outcome;
84 }),
85 );
86 });
87​
88 return { redeem } satisfies CodexResetCreditCoordinator["Service"];
89});
90​
91export const layer = Layer.effect(CodexResetCreditCoordinator, make);
92​
93/**
94 * Self-contained for tests: a counter-backed Crypto so keys are deterministic
95 * and distinct without the platform layer.
96 */
97export const layerTest = Layer.effect(
98 CodexResetCreditCoordinator,
99 Effect.gen(function* () {
100 let counter = 0;
101 return yield* make.pipe(
102 Effect.provideService(
103 Crypto.Crypto,
104 Crypto.make({
105 randomBytes: (size) => {
106 counter += 1;
107 return new Uint8Array(size).fill(counter);
108 },
109 digest: (_algorithm, data) => Effect.succeed(data),
110 }),
111 ),
112 );
113 }),
114);