Open History to see the last commit
1/**
2 * Redeeming a reset credit is an account-level action: instances that share the
3 * directory holding a provider's login share the credit, so their redemptions
4 * must serialise on that directory, not the instance.
5 */
6import type { ProviderConsumeResetCreditOutcome } from "@t3tools/contracts";
7import * as Context from "effect/Context";
8import * as Crypto from "effect/Crypto";
9import * as Effect from "effect/Effect";
10import * as Layer from "effect/Layer";
11import type * as PlatformError from "effect/PlatformError";
12import * as Ref from "effect/Ref";
13import * as Semaphore from "effect/Semaphore";
14
15interface AccountRedemptionState {
16 readonly lock: Semaphore.Semaphore;
17 readonly pendingKey: Ref.Ref<string | null>;
18}
19
20export class ResetCreditCoordinator extends Context.Service<
21 ResetCreditCoordinator,
22 {
23 /**
24 * The key is cleared when the provider reports an outcome, or when
25 * `isSettled` says a failure was a final answer (such as a cooldown). Any
26 * other failure (timeout included) keeps it so the next attempt is the same
27 * attempt.
28 */
29 readonly redeem: <E, R>(
30 accountKey: string,
31 consume: (idempotencyKey: string) => Effect.Effect<ProviderConsumeResetCreditOutcome, E, R>,
32 isSettled?: (error: E) => boolean,
33 ) => Effect.Effect<ProviderConsumeResetCreditOutcome, E | PlatformError.PlatformError, R>;
34 }
35>()("t3/provider/resetCreditCoordinator") {}
36
37/** @public */
38/** @public Service construction is part of the canonical Effect module API. */
39export const make = Effect.gen(function* () {
40 const crypto = yield* Crypto.Crypto;
41 const statesRef = yield* Ref.make<ReadonlyMap<string, AccountRedemptionState>>(new Map());
42
43 // Get-or-create through one Ref.modify so two first redemptions for the
44 // same account cannot each install their own lock.
45 const stateFor = Effect.fn("ResetCreditCoordinator.stateFor")(function* (accountKey: string) {
46 const existing = (yield* Ref.get(statesRef)).get(accountKey);
47 if (existing) return existing;
48 const candidate = {
49 lock: yield* Semaphore.make(1),
50 pendingKey: yield* Ref.make<string | null>(null),
51 };
52 return yield* Ref.modify(statesRef, (states) => {
53 const current = states.get(accountKey);
54 if (current) return [current, states] as const;
55 const next = new Map(states);
56 next.set(accountKey, candidate);
57 return [candidate, next] as const;
58 });
59 });
60
61 const redeem: ResetCreditCoordinator["Service"]["redeem"] = Effect.fn(
62 "resetCreditCoordinator.redeem",
63 )(function* (accountKey, consume, isSettled) {
64 const state = yield* stateFor(accountKey);
65 return yield* state.lock.withPermits(1)(
66 Effect.gen(function* () {
67 const existing = yield* Ref.get(state.pendingKey);
68 const idempotencyKey = existing ?? (yield* crypto.randomUUIDv4());
69 yield* Ref.set(state.pendingKey, idempotencyKey);
70 const outcome = yield* consume(idempotencyKey).pipe(
71 Effect.tapError((error) =>
72 isSettled?.(error) ? Ref.set(state.pendingKey, null) : Effect.void,
73 ),
74 );
75 yield* Ref.set(state.pendingKey, null);
76 return outcome;
77 }),
78 );
79 });
80
81 return { redeem } satisfies ResetCreditCoordinator["Service"];
82});
83
84export const layer = Layer.effect(ResetCreditCoordinator, make);
85
86export const layerTest = Layer.effect(
87 ResetCreditCoordinator,
88 Effect.gen(function* () {
89 let counter = 0;
90 return yield* make.pipe(
91 Effect.provideService(
92 Crypto.Crypto,
93 Crypto.make({
94 randomBytes: (size) => {
95 counter += 1;
96 return new Uint8Array(size).fill(counter);
97 },
98 digest: (_algorithm, data) => Effect.succeed(data),
99 }),
100 ),
101 );
102 }),
103);