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

resetCreditCoordinator.ts

92 lines3.3 KB

1/** Instances sharing a login directory share credits; serialize redemptions on that directory. */
2import type { ProviderConsumeResetCreditOutcome } from "@t3tools/contracts";
3import * as Context from "effect/Context";
4import * as Crypto from "effect/Crypto";
5import * as Effect from "effect/Effect";
6import * as Layer from "effect/Layer";
7import type * as PlatformError from "effect/PlatformError";
8import * as Ref from "effect/Ref";
9import * as Semaphore from "effect/Semaphore";
10​
11interface AccountRedemptionState {
12 readonly lock: Semaphore.Semaphore;
13 readonly pendingKey: Ref.Ref<string | null>;
15​
16export class ResetCreditCoordinator extends Context.Service<
17 ResetCreditCoordinator,
18 {
19 /** Reuse the idempotency key until an outcome or settled failure; timeouts keep it for retry. */
20 readonly redeem: <E, R>(
21 accountKey: string,
22 consume: (idempotencyKey: string) => Effect.Effect<ProviderConsumeResetCreditOutcome, E, R>,
23 isSettled?: (error: E) => boolean,
24 ) => Effect.Effect<ProviderConsumeResetCreditOutcome, E | PlatformError.PlatformError, R>;
25 }
26>()("t3/provider/resetCreditCoordinator") {}
27​
28/** @public */
29export const make = Effect.gen(function* () {
30 const crypto = yield* Crypto.Crypto;
31 const statesRef = yield* Ref.make<ReadonlyMap<string, AccountRedemptionState>>(new Map());
32​
33 // Create account locks atomically so concurrent first redemptions cannot use separate locks.
34 const stateFor = Effect.fn("ResetCreditCoordinator.stateFor")(function* (accountKey: string) {
35 const existing = (yield* Ref.get(statesRef)).get(accountKey);
36 if (existing) return existing;
37 const candidate = {
38 lock: yield* Semaphore.make(1),
39 pendingKey: yield* Ref.make<string | null>(null),
40 };
41 return yield* Ref.modify(statesRef, (states) => {
42 const current = states.get(accountKey);
43 if (current) return [current, states] as const;
44 const next = new Map(states);
45 next.set(accountKey, candidate);
46 return [candidate, next] as const;
47 });
48 });
49​
50 const redeem: ResetCreditCoordinator["Service"]["redeem"] = Effect.fn(
51 "resetCreditCoordinator.redeem",
52 )(function* (accountKey, consume, isSettled) {
53 const state = yield* stateFor(accountKey);
54 return yield* state.lock.withPermits(1)(
55 Effect.gen(function* () {
56 const existing = yield* Ref.get(state.pendingKey);
57 const idempotencyKey = existing ?? (yield* crypto.randomUUIDv4());
58 yield* Ref.set(state.pendingKey, idempotencyKey);
59 const outcome = yield* consume(idempotencyKey).pipe(
60 Effect.tapError((error) =>
61 isSettled?.(error) ? Ref.set(state.pendingKey, null) : Effect.void,
62 ),
63 );
64 yield* Ref.set(state.pendingKey, null);
65 return outcome;
66 }),
67 );
68 });
69​
70 return { redeem } satisfies ResetCreditCoordinator["Service"];
71});
72​
73export const layer = Layer.effect(ResetCreditCoordinator, make);
74​
75export const layerTest = Layer.effect(
76 ResetCreditCoordinator,
77 Effect.gen(function* () {
78 let counter = 0;
79 return yield* make.pipe(
80 Effect.provideService(
81 Crypto.Crypto,
82 Crypto.make({
83 randomBytes: (size) => {
84 counter += 1;
85 return new Uint8Array(size).fill(counter);
86 },
87 digest: (_algorithm, data) => Effect.succeed(data),
88 }),
89 ),
90 );
91 }),
92);