|
| 1 | +/** |
| 2 | + * Keeps the history of every account's quota windows: how the allowance was |
| 3 | + * used over time, and what was left each time a window reset. |
| 4 | + * |
| 5 | + * It listens to the provider registry, so it records whatever the usage |
| 6 | + * probes already read and adds no probing of its own. The history is an |
| 7 | + * append-only file in the state directory, one JSON object per line. |
| 8 | + * |
| 9 | + * @module UsageLimitHistory |
| 10 | + */ |
| 11 | +import { |
| 12 | + UsageLimitHistoryPoint, |
| 13 | + UsageLimitReset, |
| 14 | + type ServerProvider, |
| 15 | + type UsageLimitHistory as UsageLimitHistoryResult, |
| 16 | + type UsageLimitHistoryInput, |
| 17 | +} from "@t3tools/contracts"; |
| 18 | +import * as Clock from "effect/Clock"; |
| 19 | +import * as Context from "effect/Context"; |
| 20 | +import * as Effect from "effect/Effect"; |
| 21 | +import * as FileSystem from "effect/FileSystem"; |
| 22 | +import * as Layer from "effect/Layer"; |
| 23 | +import * as Path from "effect/Path"; |
| 24 | +import * as Schema from "effect/Schema"; |
| 25 | +import * as Semaphore from "effect/Semaphore"; |
| 26 | +import * as Stream from "effect/Stream"; |
| 27 | + |
| 28 | +import * as ServerConfig from "../config.ts"; |
| 29 | +import * as ProviderRegistry from "../provider/ProviderRegistry.ts"; |
| 30 | +import { |
| 31 | + recordUsageLimitReadings, |
| 32 | + usageLimitWindowKey, |
| 33 | + type UsageLimitReadingState, |
| 34 | +} from "./usageLimitReadings.ts"; |
| 35 | + |
| 36 | +export const USAGE_LIMIT_HISTORY_FILE_NAME = "usage-limit-history.jsonl"; |
| 37 | + |
| 38 | +/** Long enough to compare a few monthly windows; older lines are dropped at startup. */ |
| 39 | +const RETENTION_MS = 120 * 24 * 60 * 60_000; |
| 40 | + |
| 41 | +const HistoryLine = Schema.Union([ |
| 42 | + Schema.Struct({ point: UsageLimitHistoryPoint }), |
| 43 | + Schema.Struct({ reset: UsageLimitReset }), |
| 44 | +]); |
| 45 | +type HistoryLine = typeof HistoryLine.Type; |
| 46 | +const decodeLine = Schema.decodeUnknownOption(Schema.fromJsonString(HistoryLine)); |
| 47 | +const encodeLine = Schema.encodeSync(Schema.fromJsonString(HistoryLine)); |
| 48 | + |
| 49 | +export class UsageLimitHistory extends Context.Service< |
| 50 | + UsageLimitHistory, |
| 51 | + { |
| 52 | + /** Points and resets at or after `since`, oldest first. */ |
| 53 | + readonly read: (input: UsageLimitHistoryInput) => Effect.Effect<UsageLimitHistoryResult>; |
| 54 | + } |
| 55 | +>()("t3/usage/UsageLimitHistory") {} |
| 56 | + |
| 57 | +/** What a history file holds, with unreadable and expired lines left out. */ |
| 58 | +export function parseUsageLimitHistory( |
| 59 | + contents: string, |
| 60 | + nowMs: number, |
| 61 | +): { readonly points: UsageLimitHistoryPoint[]; readonly resets: UsageLimitReset[] } { |
| 62 | + const points: UsageLimitHistoryPoint[] = []; |
| 63 | + const resets: UsageLimitReset[] = []; |
| 64 | + for (const raw of contents.split("\n")) { |
| 65 | + if (raw.trim() === "") continue; |
| 66 | + const line = decodeLine(raw); |
| 67 | + if (line._tag === "None") continue; |
| 68 | + const entry = line.value; |
| 69 | + const at = "point" in entry ? entry.point.at : entry.reset.at; |
| 70 | + if (nowMs - Date.parse(at) > RETENTION_MS) continue; |
| 71 | + if ("point" in entry) points.push(entry.point); |
| 72 | + else resets.push(entry.reset); |
| 73 | + } |
| 74 | + return { points, resets }; |
| 75 | +} |
| 76 | + |
| 77 | +function serialize(lines: ReadonlyArray<HistoryLine>): string { |
| 78 | + return lines.map((line) => `${encodeLine(line)}\n`).join(""); |
| 79 | +} |
| 80 | + |
| 81 | +export const make = Effect.gen(function* () { |
| 82 | + const fileSystem = yield* FileSystem.FileSystem; |
| 83 | + const path = yield* Path.Path; |
| 84 | + const config = yield* ServerConfig.ServerConfig; |
| 85 | + const registry = yield* ProviderRegistry.ProviderRegistry; |
| 86 | + const filePath = path.join(config.stateDir, USAGE_LIMIT_HISTORY_FILE_NAME); |
| 87 | + |
| 88 | + const existing = yield* fileSystem.readFileString(filePath).pipe(Effect.orElseSucceed(() => "")); |
| 89 | + const loaded = parseUsageLimitHistory(existing, yield* Clock.currentTimeMillis); |
| 90 | + const points = loaded.points; |
| 91 | + const resets = loaded.resets; |
| 92 | + let state: UsageLimitReadingState = new Map( |
| 93 | + points.map((point) => [usageLimitWindowKey(point), point]), |
| 94 | + ); |
| 95 | + // Rewrite once at startup when lines expired or could not be read, so the |
| 96 | + // file never grows past the retention window. |
| 97 | + const kept = serialize([ |
| 98 | + ...points.map((point) => ({ point })), |
| 99 | + ...resets.map((reset) => ({ reset })), |
| 100 | + ]); |
| 101 | + if (existing !== "" && kept.length < existing.length) { |
| 102 | + yield* fileSystem.writeFileString(filePath, kept).pipe(Effect.ignore); |
| 103 | + } |
| 104 | + |
| 105 | + const lock = yield* Semaphore.make(1); |
| 106 | + const record = (providers: ReadonlyArray<ServerProvider>) => |
| 107 | + lock.withPermits(1)( |
| 108 | + Effect.gen(function* () { |
| 109 | + const delta = recordUsageLimitReadings(state, providers); |
| 110 | + if (delta.points.length === 0) return; |
| 111 | + state = delta.state; |
| 112 | + points.push(...delta.points); |
| 113 | + resets.push(...delta.resets); |
| 114 | + // History is a convenience; a full disk must not take usage limits down with it. |
| 115 | + yield* fileSystem |
| 116 | + .writeFileString( |
| 117 | + filePath, |
| 118 | + serialize([ |
| 119 | + ...delta.points.map((point) => ({ point })), |
| 120 | + ...delta.resets.map((reset) => ({ reset })), |
| 121 | + ]), |
| 122 | + { flag: "a" }, |
| 123 | + ) |
| 124 | + .pipe( |
| 125 | + Effect.catch((cause) => |
| 126 | + Effect.logWarning("Could not append to the usage limit history", cause), |
| 127 | + ), |
| 128 | + ); |
| 129 | + }), |
| 130 | + ); |
| 131 | + |
| 132 | + yield* Stream.runForEach(registry.streamChanges, record).pipe(Effect.forkScoped); |
| 133 | + yield* registry.getProviders.pipe(Effect.flatMap(record)); |
| 134 | + |
| 135 | + return UsageLimitHistory.of({ |
| 136 | + read: (input) => |
| 137 | + Effect.sync(() => { |
| 138 | + const sinceMs = Date.parse(input.since); |
| 139 | + return { |
| 140 | + points: points.filter((point) => Date.parse(point.at) >= sinceMs), |
| 141 | + resets: resets.filter((reset) => Date.parse(reset.at) >= sinceMs), |
| 142 | + }; |
| 143 | + }), |
| 144 | + }); |
| 145 | +}); |
| 146 | + |
| 147 | +export const layer = Layer.effect(UsageLimitHistory, make); |
| 148 | + |
| 149 | +/** Empty history, for suites that only need the RPC surface to resolve. */ |
| 150 | +export const layerTest = Layer.succeed( |
| 151 | + UsageLimitHistory, |
| 152 | + UsageLimitHistory.of({ read: () => Effect.succeed({ points: [], resets: [] }) }), |
| 153 | +); |
0 commit comments