@aliou/pi-synthetic 0.15.0 → 0.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,211 @@
1
+ import {
2
+ afterEach,
3
+ assert,
4
+ beforeEach,
5
+ describe,
6
+ expect,
7
+ it,
8
+ vi,
9
+ } from "vitest";
10
+ import type { QuotasResponse } from "../types/quotas";
11
+ import { QuotaStore } from "./quota-store";
12
+
13
+ beforeEach(() => {
14
+ vi.useFakeTimers();
15
+ });
16
+
17
+ afterEach(() => {
18
+ vi.useRealTimers();
19
+ });
20
+
21
+ describe("QuotaStore", () => {
22
+ const sampleQuotas: QuotasResponse = {
23
+ subscription: { limit: 100, requests: 5, renewsAt: "2026-01-01T00:00:00Z" },
24
+ };
25
+
26
+ describe("ingest", () => {
27
+ it("stores and emits API-sourced data", () => {
28
+ const store = new QuotaStore();
29
+ const received: QuotasResponse[] = [];
30
+ store.subscribe((snap) => received.push(snap.quotas));
31
+
32
+ const result = store.ingest(sampleQuotas, "api");
33
+
34
+ expect(result).toBe(true);
35
+ expect(store.getSnapshot()?.quotas).toBe(sampleQuotas);
36
+ expect(store.getSnapshot()?.source).toBe("api");
37
+ expect(received).toHaveLength(1);
38
+ });
39
+
40
+ it("stores and emits header-sourced data", () => {
41
+ const store = new QuotaStore();
42
+ const result = store.ingest(sampleQuotas, "header");
43
+
44
+ expect(result).toBe(true);
45
+ expect(store.getSnapshot()?.source).toBe("header");
46
+ });
47
+
48
+ it("throttles header ingestion within throttle window", () => {
49
+ const store = new QuotaStore();
50
+ store.ingest(sampleQuotas, "header");
51
+
52
+ // Within throttle window — should be dropped
53
+ const result = store.ingest(sampleQuotas, "header");
54
+ expect(result).toBe(false);
55
+
56
+ // Advance past throttle
57
+ vi.advanceTimersByTime(store.headerThrottleMs + 1);
58
+ const result2 = store.ingest(sampleQuotas, "header");
59
+ expect(result2).toBe(true);
60
+ });
61
+
62
+ it("does NOT throttle API ingestion", () => {
63
+ const store = new QuotaStore();
64
+ store.ingest(sampleQuotas, "api");
65
+
66
+ // API is never throttled
67
+ const result = store.ingest(sampleQuotas, "api");
68
+ expect(result).toBe(true);
69
+ });
70
+
71
+ it("header after API emit always goes through", () => {
72
+ const store = new QuotaStore();
73
+ store.ingest(sampleQuotas, "api");
74
+
75
+ // Header 1ms after API should not be blocked
76
+ vi.advanceTimersByTime(1);
77
+ const result = store.ingest(sampleQuotas, "header");
78
+ expect(result).toBe(true);
79
+ });
80
+
81
+ it("updates timestamp on each successful ingest", () => {
82
+ const store = new QuotaStore();
83
+ store.ingest(sampleQuotas, "api");
84
+ const snap1 = store.getSnapshot();
85
+ assert(snap1);
86
+ const t1 = snap1.updatedAt;
87
+
88
+ vi.advanceTimersByTime(10_000);
89
+ store.ingest(sampleQuotas, "api");
90
+ const snap2 = store.getSnapshot();
91
+ assert(snap2);
92
+ const t2 = snap2.updatedAt;
93
+
94
+ expect(t2).toBeGreaterThan(t1);
95
+ });
96
+ });
97
+
98
+ describe("subscribe", () => {
99
+ it("notifies subscribers on ingest", () => {
100
+ const store = new QuotaStore();
101
+ const calls: QuotasResponse[] = [];
102
+ store.subscribe((snap) => calls.push(snap.quotas));
103
+
104
+ store.ingest(sampleQuotas, "api");
105
+ expect(calls).toHaveLength(1);
106
+ expect(calls[0]).toBe(sampleQuotas);
107
+ });
108
+
109
+ it("does not notify on throttled ingest", () => {
110
+ const store = new QuotaStore();
111
+ const calls: QuotasResponse[] = [];
112
+ store.subscribe((snap) => calls.push(snap.quotas));
113
+
114
+ store.ingest(sampleQuotas, "header");
115
+ store.ingest(sampleQuotas, "header"); // throttled
116
+
117
+ expect(calls).toHaveLength(1);
118
+ });
119
+
120
+ it("unsubscribes when unsubscribe function is called", () => {
121
+ const store = new QuotaStore();
122
+ const calls: QuotasResponse[] = [];
123
+ const unsub = store.subscribe((snap) => calls.push(snap.quotas));
124
+
125
+ unsub();
126
+ store.ingest(sampleQuotas, "api");
127
+
128
+ expect(calls).toHaveLength(0);
129
+ });
130
+
131
+ it("supports multiple subscribers", () => {
132
+ const store = new QuotaStore();
133
+ const calls1: QuotasResponse[] = [];
134
+ const calls2: QuotasResponse[] = [];
135
+ store.subscribe((snap) => calls1.push(snap.quotas));
136
+ store.subscribe((snap) => calls2.push(snap.quotas));
137
+
138
+ store.ingest(sampleQuotas, "api");
139
+
140
+ expect(calls1).toHaveLength(1);
141
+ expect(calls2).toHaveLength(1);
142
+ });
143
+ });
144
+
145
+ describe("refreshFromApi", () => {
146
+ it("calls the fetcher and ingests the result", async () => {
147
+ const store = new QuotaStore();
148
+ const fetcher = vi.fn().mockResolvedValue(sampleQuotas);
149
+
150
+ const result = await store.refreshFromApi(fetcher);
151
+
152
+ assert(result);
153
+ expect(result.quotas).toBe(sampleQuotas);
154
+ expect(result.source).toBe("api");
155
+ expect(fetcher).toHaveBeenCalledOnce();
156
+ });
157
+
158
+ it("deduplicates concurrent calls", async () => {
159
+ const store = new QuotaStore();
160
+ let resolveFirst!: (v: QuotasResponse) => void;
161
+ const first = new Promise<QuotasResponse>((r) => (resolveFirst = r));
162
+ const fetcher = vi.fn().mockImplementation(() => first);
163
+
164
+ // Start two concurrent refreshes
165
+ const p1 = store.refreshFromApi(fetcher);
166
+ const p2 = store.refreshFromApi(fetcher);
167
+
168
+ // Only one fetcher call
169
+ expect(fetcher).toHaveBeenCalledOnce();
170
+ expect(store.isRefreshing).toBe(true);
171
+
172
+ // Resolve the fetch
173
+ resolveFirst(sampleQuotas);
174
+ await p1;
175
+ await p2;
176
+
177
+ expect(store.isRefreshing).toBe(false);
178
+ });
179
+
180
+ it("handles fetcher returning undefined", async () => {
181
+ const store = new QuotaStore();
182
+ const fetcher = vi.fn().mockResolvedValue(undefined);
183
+
184
+ const result = await store.refreshFromApi(fetcher);
185
+
186
+ expect(result).toBeUndefined();
187
+ expect(store.getSnapshot()).toBeUndefined();
188
+ });
189
+ });
190
+
191
+ describe("clear", () => {
192
+ it("resets all state", () => {
193
+ const store = new QuotaStore();
194
+ store.ingest(sampleQuotas, "api");
195
+
196
+ store.clear();
197
+
198
+ expect(store.getSnapshot()).toBeUndefined();
199
+ });
200
+
201
+ it("resets header throttle after clear", () => {
202
+ const store = new QuotaStore();
203
+ store.ingest(sampleQuotas, "header");
204
+ expect(store.ingest(sampleQuotas, "header")).toBe(false);
205
+
206
+ store.clear();
207
+
208
+ expect(store.ingest(sampleQuotas, "header")).toBe(true);
209
+ });
210
+ });
211
+ });
@@ -0,0 +1,112 @@
1
+ import type { QuotaSource, QuotasResponse } from "../types/quotas";
2
+
3
+ export interface QuotaSnapshot {
4
+ quotas: QuotasResponse;
5
+ source: QuotaSource;
6
+ updatedAt: number; // epoch ms
7
+ }
8
+
9
+ type Listener = (snapshot: QuotaSnapshot) => void;
10
+
11
+ /**
12
+ * Pi-agnostic in-memory quota store.
13
+ *
14
+ * Ingests quota data from headers or API, handles throttling of
15
+ * header-sourced updates, and notifies subscribers on change.
16
+ *
17
+ * Usage:
18
+ * const store = new QuotaStore();
19
+ * store.subscribe((snap) => { ... });
20
+ * store.ingest(quotas, "header");
21
+ * store.ingest(quotas, "api");
22
+ */
23
+ export class QuotaStore {
24
+ private snapshot: QuotaSnapshot | undefined;
25
+ private listeners = new Set<Listener>();
26
+ private lastHeaderIngestAt = 0;
27
+ private inFlightRefresh: Promise<QuotaSnapshot | undefined> | undefined;
28
+ private inFlightId = 0;
29
+
30
+ /** Throttle header ingestion: skip if last header ingest was within this window. */
31
+ headerThrottleMs = 5_000;
32
+
33
+ /** Current snapshot (may be undefined if no data has been ingested yet). */
34
+ getSnapshot(): QuotaSnapshot | undefined {
35
+ return this.snapshot;
36
+ }
37
+
38
+ /** Subscribe to snapshot updates. Returns unsubscribe function. */
39
+ subscribe(listener: Listener): () => void {
40
+ this.listeners.add(listener);
41
+ return () => {
42
+ this.listeners.delete(listener);
43
+ };
44
+ }
45
+
46
+ private emit(snapshot: QuotaSnapshot): void {
47
+ for (const l of this.listeners) l(snapshot);
48
+ }
49
+
50
+ /**
51
+ * Ingest quota data. Returns true if the snapshot was updated
52
+ * (i.e. not throttled).
53
+ *
54
+ * Header-sourced data is throttled: if the last header ingest was
55
+ * within `headerThrottleMs`, it is silently dropped.
56
+ * API-sourced data always goes through.
57
+ */
58
+ ingest(quotas: QuotasResponse, source: QuotaSource): boolean {
59
+ const now = Date.now();
60
+
61
+ if (source === "header") {
62
+ if (now - this.lastHeaderIngestAt < this.headerThrottleMs) return false;
63
+ this.lastHeaderIngestAt = now;
64
+ }
65
+
66
+ this.snapshot = { quotas, source, updatedAt: now };
67
+ this.emit(this.snapshot);
68
+ return true;
69
+ }
70
+
71
+ /**
72
+ * Refresh quotas by calling the provided fetcher.
73
+ * Deduplicates concurrent calls — only one fetch runs at a time.
74
+ */
75
+ async refreshFromApi(
76
+ fetcher: () => Promise<QuotasResponse | undefined>,
77
+ ): Promise<QuotaSnapshot | undefined> {
78
+ if (this.inFlightRefresh) return this.inFlightRefresh;
79
+
80
+ this.inFlightId++;
81
+ const id = this.inFlightId;
82
+
83
+ this.inFlightRefresh = (async () => {
84
+ try {
85
+ const quotas = await fetcher();
86
+ if (quotas && id === this.inFlightId) {
87
+ this.ingest(quotas, "api");
88
+ }
89
+ return this.snapshot;
90
+ } finally {
91
+ if (id === this.inFlightId) {
92
+ this.inFlightRefresh = undefined;
93
+ }
94
+ }
95
+ })();
96
+
97
+ return this.inFlightRefresh;
98
+ }
99
+
100
+ /** Returns true if a refresh is currently in flight. */
101
+ get isRefreshing(): boolean {
102
+ return !!this.inFlightRefresh;
103
+ }
104
+
105
+ /** Clear all state. Call on session shutdown or reset. */
106
+ clear(): void {
107
+ this.inFlightId++; // Invalidates in-flight refresh
108
+ this.snapshot = undefined;
109
+ this.lastHeaderIngestAt = 0;
110
+ this.inFlightRefresh = undefined;
111
+ }
112
+ }