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

ProviderUsageLimitsIngestion.ts

44 lines1.8 KB

1/**
2 * ProviderUsageLimitsIngestionLive — folds `account.rate-limits.updated`
3 * runtime events into the owning instance's published snapshot.
4 *
5 * Adapters normalise their native payloads before emitting, so this layer
6 * never sees a driver shape: it routes the typed update to the instance and
7 * lets `ServerProviderShape.applyUsageLimits` merge and republish on the
8 * instance's own change stream, which `ProviderRegistry` already aggregates.
9 *
10 * @module provider/Layers/ProviderUsageLimitsIngestion
11 */
12import * as DateTime from "effect/DateTime";
13import * as Effect from "effect/Effect";
14import * as Layer from "effect/Layer";
15import * as Stream from "effect/Stream";
16​
17import { ProviderInstanceRegistry } from "../Services/ProviderInstanceRegistry.ts";
18import { ProviderService } from "../Services/ProviderService.ts";
19​
20export const ProviderUsageLimitsIngestionLive = Layer.effectDiscard(
21 Effect.gen(function* () {
22 const providerService = yield* ProviderService;
23 const instanceRegistry = yield* ProviderInstanceRegistry;
24​
25 yield* providerService.streamEvents.pipe(
26 Stream.filter((event) => event.type === "account.rate-limits.updated"),
27 Stream.runForEach((event) =>
28 Effect.gen(function* () {
29 if (!event.providerInstanceId) {
30 return;
31 }
32 const instance = yield* instanceRegistry.getInstance(event.providerInstanceId);
33 if (!instance) {
34 return;
35 }
36 const checkedAt = DateTime.formatIso(yield* DateTime.now);
37 yield* instance.snapshot.applyUsageLimits({ ...event.payload.limits, checkedAt });
38 // One bad event must not end the subscriber for every later one.
39 }).pipe(Effect.ignoreCause({ log: true })),
40 ),
41 Effect.forkScoped,
42 );
43 }),
44);