@mailwoman/core 8.4.0 → 8.5.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.
- package/api/APIClient.ts +207 -42
- package/api/clock.ts +43 -0
- package/api/disk-storage.ts +239 -0
- package/api/index.ts +7 -0
- package/api/pacer.ts +98 -0
- package/api/responses.ts +227 -44
- package/api/retry.ts +227 -0
- package/api/test-clocks.ts +234 -0
- package/env/schema.ts +3 -0
- package/out/api/APIClient.d.ts +60 -8
- package/out/api/APIClient.d.ts.map +1 -1
- package/out/api/APIClient.js +149 -35
- package/out/api/APIClient.js.map +1 -1
- package/out/api/clock.d.ts +36 -0
- package/out/api/clock.d.ts.map +1 -0
- package/out/api/clock.js +27 -0
- package/out/api/clock.js.map +1 -0
- package/out/api/disk-storage.d.ts +64 -0
- package/out/api/disk-storage.d.ts.map +1 -0
- package/out/api/disk-storage.js +185 -0
- package/out/api/disk-storage.js.map +1 -0
- package/out/api/index.d.ts +3 -0
- package/out/api/index.d.ts.map +1 -1
- package/out/api/index.js +6 -0
- package/out/api/index.js.map +1 -1
- package/out/api/pacer.d.ts +68 -0
- package/out/api/pacer.d.ts.map +1 -0
- package/out/api/pacer.js +88 -0
- package/out/api/pacer.js.map +1 -0
- package/out/api/responses.d.ts +71 -2
- package/out/api/responses.d.ts.map +1 -1
- package/out/api/responses.js +160 -34
- package/out/api/responses.js.map +1 -1
- package/out/api/retry.d.ts +119 -0
- package/out/api/retry.d.ts.map +1 -0
- package/out/api/retry.js +158 -0
- package/out/api/retry.js.map +1 -0
- package/out/api/test-clocks.d.ts +87 -0
- package/out/api/test-clocks.d.ts.map +1 -0
- package/out/api/test-clocks.js +175 -0
- package/out/api/test-clocks.js.map +1 -0
- package/out/env/index.d.ts +1 -0
- package/out/env/index.d.ts.map +1 -1
- package/out/env/schema.d.ts +1 -0
- package/out/env/schema.d.ts.map +1 -1
- package/out/env/schema.js +2 -0
- package/out/env/schema.js.map +1 -1
- package/out/vitest.config.d.ts.map +1 -1
- package/out/vitest.config.js +2 -0
- package/out/vitest.config.js.map +1 -1
- package/package.json +18 -2
- package/vitest.config.ts +2 -0
|
@@ -0,0 +1,234 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @copyright Sister Software
|
|
3
|
+
* @license AGPL-3.0
|
|
4
|
+
* @author Teffen Ellis, et al.
|
|
5
|
+
* @file Deterministic {@linkcode ClockLike} implementations shared by the `core/api` suites and by
|
|
6
|
+
* downstream clients' tests (`filer/sdk/sec-client.test.ts`).
|
|
7
|
+
*
|
|
8
|
+
* Lifted from `98c4dda1:filer/sdk/sec-client.test.ts`, where the two-clock split was worked out: a
|
|
9
|
+
* naive clock is fine for sequential assertions and actively MASKS concurrency bugs, so anything
|
|
10
|
+
* testing how concurrent waiters interleave needs the deadline-ordered one.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import type { ClockLike } from "./clock.ts"
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* How many consecutive event-loop turns {@linkcode VirtualClock.runUntilSettled} tolerates with nothing pending before
|
|
17
|
+
* declaring the work stuck. Generous — a real `readFile` resolves in a handful of turns — but finite, so a genuinely
|
|
18
|
+
* blocked test reports what happened instead of timing out.
|
|
19
|
+
*/
|
|
20
|
+
const MAX_IDLE_TURNS = 1000
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Run every queued microtask to quiescence. A `setImmediate` is scheduled behind the entire microtask queue, so
|
|
24
|
+
* awaiting one guarantees any in-flight promise chain has settled as far as it can without more real time.
|
|
25
|
+
*/
|
|
26
|
+
export function drainMicrotasks(): Promise<void> {
|
|
27
|
+
return new Promise<void>((resolve) => {
|
|
28
|
+
setImmediate(resolve)
|
|
29
|
+
})
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* A {@linkcode ClockLike} whose `sleep()` bumps `now()` and resolves immediately.
|
|
34
|
+
*/
|
|
35
|
+
export interface FakeClock extends ClockLike {
|
|
36
|
+
/**
|
|
37
|
+
* Every `ms` value awaited via `sleep`, in call order.
|
|
38
|
+
*/
|
|
39
|
+
sleepCalls: number[]
|
|
40
|
+
/**
|
|
41
|
+
* Advance the clock WITHOUT recording a `sleepCalls` entry — simulates wall-clock time passing between two calls
|
|
42
|
+
* (e.g. "a day later") without the code under test having awaited anything.
|
|
43
|
+
*/
|
|
44
|
+
advance(ms: number): void
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* A simple, immediately-resolving fake clock. Fine for every SEQUENTIAL assertion (nothing racing the clock), but NOT
|
|
49
|
+
* sufficient for a concurrency test — see {@linkcode VirtualClock}.
|
|
50
|
+
*/
|
|
51
|
+
export function createFakeClock(startAt = 0): FakeClock {
|
|
52
|
+
let current = startAt
|
|
53
|
+
const sleepCalls: number[] = []
|
|
54
|
+
|
|
55
|
+
return {
|
|
56
|
+
sleepCalls,
|
|
57
|
+
now: () => current,
|
|
58
|
+
sleep: async (ms: number) => {
|
|
59
|
+
sleepCalls.push(ms)
|
|
60
|
+
current += ms
|
|
61
|
+
},
|
|
62
|
+
advance: (ms: number) => {
|
|
63
|
+
current += ms
|
|
64
|
+
},
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* A virtual-time clock that resolves concurrent `sleep()`s ONE AT A TIME, strictly in deadline order, only when
|
|
70
|
+
* explicitly driven via {@linkcode VirtualClock.advance} — unlike {@linkcode createFakeClock}, which bumps `now()`
|
|
71
|
+
* synchronously the INSTANT `sleep()` is called (fine when nothing else races the clock, but not a faithful model of "N
|
|
72
|
+
* callers all waiting on the same deadline").
|
|
73
|
+
*
|
|
74
|
+
* This fidelity is exactly what a pacing regression needs: a coarser clock that resolves every same-deadline sleeper
|
|
75
|
+
* "at once" cannot distinguish a fixed pacer from a broken one — under such a clock BOTH let a whole cohort through
|
|
76
|
+
* together, because the naive clock's call-time (not wake-time) mutation of `now()` interleaves in a way that masks the
|
|
77
|
+
* bug. Here each pending `sleep()` resolves only when `advance()` reaches its deadline, and the woken continuation
|
|
78
|
+
* (which may register a NEW `sleep()`, pushing its own deadline further out) runs to completion before the next
|
|
79
|
+
* same-deadline sleeper is resolved — reproducing how N real, independent timers settle.
|
|
80
|
+
*/
|
|
81
|
+
export class VirtualClock implements ClockLike {
|
|
82
|
+
#now = 0
|
|
83
|
+
#pending: Array<{ deadline: number; resolve: () => void }> = []
|
|
84
|
+
readonly sleepCalls: number[] = []
|
|
85
|
+
|
|
86
|
+
public now(): number {
|
|
87
|
+
return this.#now
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
public sleep(ms: number): Promise<void> {
|
|
91
|
+
this.sleepCalls.push(ms)
|
|
92
|
+
|
|
93
|
+
return new Promise<void>((resolve) => {
|
|
94
|
+
this.#pending.push({ deadline: this.#now + ms, resolve })
|
|
95
|
+
})
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* Advance virtual time to `now() + ms`, waking every pending `sleep()` due at or before that instant — one at a time,
|
|
100
|
+
* earliest deadline first (ties broken by registration order), draining the microtask queue after each wakeup so the
|
|
101
|
+
* woken continuation runs to quiescence before the next deadline is considered.
|
|
102
|
+
*
|
|
103
|
+
* The drain is a `setImmediate` (a MACROTASK), not a fixed number of `await Promise.resolve()` turns. A woken
|
|
104
|
+
* continuation that runs through a library's own promise chain — Axios's request/response interceptors, say — needs
|
|
105
|
+
* more microtask turns than any hardcoded count, and coming up short lets the clock run ahead of an in-flight
|
|
106
|
+
* dispatch: the request then records a LATER deadline's timestamp, and two dispatches appear to share an instant when
|
|
107
|
+
* they didn't.
|
|
108
|
+
*/
|
|
109
|
+
public async advance(ms: number): Promise<void> {
|
|
110
|
+
const target = this.#now + ms
|
|
111
|
+
|
|
112
|
+
for (;;) {
|
|
113
|
+
const earliestIndex = this.#earliestDueIndex(target)
|
|
114
|
+
|
|
115
|
+
if (earliestIndex === -1) break
|
|
116
|
+
|
|
117
|
+
const [due] = this.#pending.splice(earliestIndex, 1)
|
|
118
|
+
|
|
119
|
+
this.#now = due!.deadline
|
|
120
|
+
due!.resolve()
|
|
121
|
+
|
|
122
|
+
await drainMicrotasks()
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
this.#now = target
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* Drive `work` to completion, jumping virtual time to the next pending deadline whenever the REAL event loop goes
|
|
130
|
+
* idle.
|
|
131
|
+
*
|
|
132
|
+
* {@linkcode advance} alone is not enough once the code under test interleaves virtual sleeps with real asynchrony —
|
|
133
|
+
* a paced client whose gate sits downstream of an on-disk cache spends several real event-loop turns in `readFile`
|
|
134
|
+
* before it ever registers its `sleep()`. A caller that drains once and then advances finds nothing pending, jumps
|
|
135
|
+
* the clock past the deadlines that are registered a moment later, and the test hangs. This polls instead: drain, and
|
|
136
|
+
* if any sleep is pending, advance to the earliest deadline; if none is, yield and look again.
|
|
137
|
+
*
|
|
138
|
+
* Throws rather than hanging when the work neither settles nor schedules anything for {@linkcode MAX_IDLE_TURNS}
|
|
139
|
+
* consecutive turns — a diagnosable failure beats a test-timeout stack trace pointing at the `it()`.
|
|
140
|
+
*/
|
|
141
|
+
public async runUntilSettled<T>(work: Promise<T>): Promise<T> {
|
|
142
|
+
let settled = false
|
|
143
|
+
|
|
144
|
+
const observed = work.then(
|
|
145
|
+
(value) => {
|
|
146
|
+
settled = true
|
|
147
|
+
|
|
148
|
+
return value
|
|
149
|
+
},
|
|
150
|
+
(error: unknown) => {
|
|
151
|
+
settled = true
|
|
152
|
+
|
|
153
|
+
throw error
|
|
154
|
+
}
|
|
155
|
+
)
|
|
156
|
+
|
|
157
|
+
// Keep the rejection from surfacing as an unhandled rejection while we drive the clock; the real
|
|
158
|
+
// one is still delivered to whoever awaits the returned promise.
|
|
159
|
+
observed.catch(() => undefined)
|
|
160
|
+
|
|
161
|
+
let idleTurns = 0
|
|
162
|
+
|
|
163
|
+
for (;;) {
|
|
164
|
+
await drainMicrotasks()
|
|
165
|
+
|
|
166
|
+
// `settled` is flipped by the callbacks above, not by this loop body — hence the explicit
|
|
167
|
+
// break rather than a loop condition (which reads as unmodified to a static analyzer).
|
|
168
|
+
if (settled) break
|
|
169
|
+
|
|
170
|
+
const earliest = this.#earliestPendingDeadline()
|
|
171
|
+
|
|
172
|
+
if (earliest === null) {
|
|
173
|
+
idleTurns++
|
|
174
|
+
|
|
175
|
+
if (idleTurns > MAX_IDLE_TURNS) {
|
|
176
|
+
throw new Error(
|
|
177
|
+
`VirtualClock.runUntilSettled: no pending sleep and no progress for ${MAX_IDLE_TURNS} turns at ` +
|
|
178
|
+
`t=${this.#now}. The work is blocked on something this clock does not drive.`
|
|
179
|
+
)
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
continue
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
idleTurns = 0
|
|
186
|
+
|
|
187
|
+
await this.advance(Math.max(earliest - this.#now, 0))
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
return observed
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
#earliestPendingDeadline(): number | null {
|
|
194
|
+
let earliest: number | null = null
|
|
195
|
+
|
|
196
|
+
for (const { deadline } of this.#pending) {
|
|
197
|
+
if (earliest === null || deadline < earliest) {
|
|
198
|
+
earliest = deadline
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
return earliest
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
#earliestDueIndex(target: number): number {
|
|
206
|
+
let earliestIndex = -1
|
|
207
|
+
|
|
208
|
+
for (let i = 0; i < this.#pending.length; i++) {
|
|
209
|
+
if (this.#pending[i]!.deadline > target) continue
|
|
210
|
+
|
|
211
|
+
if (earliestIndex === -1 || this.#pending[i]!.deadline < this.#pending[earliestIndex]!.deadline) {
|
|
212
|
+
earliestIndex = i
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
return earliestIndex
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
/**
|
|
221
|
+
* The maximum number of `timestamps` falling within any sliding window of `windowMs`, using a trailing half-open window
|
|
222
|
+
* `(anchor - windowMs, anchor]` at each timestamp — the conventional "requests in the last N ms" definition.
|
|
223
|
+
*/
|
|
224
|
+
export function maxCountInSlidingWindow(timestamps: number[], windowMs: number): number {
|
|
225
|
+
let max = 0
|
|
226
|
+
|
|
227
|
+
for (const anchor of timestamps) {
|
|
228
|
+
const count = timestamps.filter((t) => t > anchor - windowMs && t <= anchor).length
|
|
229
|
+
|
|
230
|
+
max = Math.max(max, count)
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
return max
|
|
234
|
+
}
|
package/env/schema.ts
CHANGED
|
@@ -137,4 +137,7 @@ export const PrivateEnvSchema = z.object({
|
|
|
137
137
|
// FCC Broadband Map (BDC) public-API credentials (`bdc/sdk/client.ts`) — username + hash_value header auth.
|
|
138
138
|
FCC_MAP_USERNAME: z.string().optional(),
|
|
139
139
|
FCC_MAP_API_KEY: z.string().optional(),
|
|
140
|
+
|
|
141
|
+
// SEC EDGAR fair-access User-Agent (`filer/sdk/sec-client.ts`) — "Company Name AdminContact@domain.com".
|
|
142
|
+
SEC_EDGAR_USER_AGENT: z.string().optional(),
|
|
140
143
|
})
|
package/out/api/APIClient.d.ts
CHANGED
|
@@ -2,11 +2,15 @@
|
|
|
2
2
|
* @copyright Sister Software
|
|
3
3
|
* @license AGPL-3.0
|
|
4
4
|
* @author Teffen Ellis, et al.
|
|
5
|
+
* @file The default base for HTTP clients in this repo. Raw `fetch` duplicates throttling, caching, and
|
|
6
|
+
* error mapping that live here; new clients extend or instantiate this instead (see `AGENTS.md`).
|
|
5
7
|
*/
|
|
6
|
-
import { type IRuntimeLogger } from "@mailwoman/core/logging";
|
|
7
8
|
import { type AxiosInstance, type AxiosRequestConfig, type AxiosResponse, type CreateAxiosDefaults } from "axios";
|
|
8
|
-
import { type AxiosCacheInstance, type
|
|
9
|
-
|
|
9
|
+
import { type AxiosCacheInstance, type CacheOptions } from "axios-cache-interceptor";
|
|
10
|
+
import { type IRuntimeLogger } from "../logging/index.ts";
|
|
11
|
+
import { type ClockLike } from "./clock.ts";
|
|
12
|
+
import { type RetryOptions } from "./retry.ts";
|
|
13
|
+
export { type IRuntimeLogger } from "../logging/index.ts";
|
|
10
14
|
/**
|
|
11
15
|
* Configuration for an API client.
|
|
12
16
|
*/
|
|
@@ -20,17 +24,44 @@ export interface APIClientConfig {
|
|
|
20
24
|
*/
|
|
21
25
|
caching?: CacheOptions;
|
|
22
26
|
/**
|
|
23
|
-
* How many requests to make per minute before enforcing a cooldown
|
|
27
|
+
* How many requests to make per minute before enforcing a cooldown: a BUDGET model — spend `requestsPerMinute`
|
|
28
|
+
* dispatches, then stall until the cooldown lapses.
|
|
29
|
+
*
|
|
30
|
+
* This cannot express a flat per-second rate, which is what most fair-access policies actually publish. For that use
|
|
31
|
+
* {@linkcode minRequestIntervalMs}; the two compose (both gates must clear) but you almost certainly want one.
|
|
24
32
|
*/
|
|
25
33
|
requestsPerMinute?: number;
|
|
34
|
+
/**
|
|
35
|
+
* The minimum spacing between two dispatches, in milliseconds — strict pacing with NO burst allowance.
|
|
36
|
+
*
|
|
37
|
+
* Set this when an upstream publishes a flat rate (SEC EDGAR: 10 requests/second, enforced): `1000 / rate`. Unlike
|
|
38
|
+
* {@linkcode requestsPerMinute}, the guarantee holds under arbitrary concurrency — grants are reserved synchronously,
|
|
39
|
+
* so N callers racing in one turn are still spaced one interval apart. A token bucket cannot do this: capacity C
|
|
40
|
+
* admits `C + rate * 1s` inside a sliding second, so no non-zero capacity honors a flat cap.
|
|
41
|
+
*/
|
|
42
|
+
minRequestIntervalMs?: number;
|
|
43
|
+
/**
|
|
44
|
+
* Bounded retry with exponential backoff, honoring a response's `Retry-After`. Pass `true` for the defaults.
|
|
45
|
+
*
|
|
46
|
+
* OPT-IN, and absent by default: an `APIClient` without this makes exactly one attempt, which is what every existing
|
|
47
|
+
* consumer has always done. 429/5xx/408 and network-class failures (dropped socket, DNS, timeout, mid-body-transfer
|
|
48
|
+
* drop) are retried; a 403 never is — it means the request failed to identify itself, so retrying can only fail
|
|
49
|
+
* identically while burning rate budget.
|
|
50
|
+
*/
|
|
51
|
+
retry?: RetryOptions | boolean;
|
|
52
|
+
/**
|
|
53
|
+
* Time source powering the pacer, the cooldown timer, and the retry backoff. Defaults to {@linkcode systemClock};
|
|
54
|
+
* tests inject a fake clock so timing behavior is deterministic and instant.
|
|
55
|
+
*/
|
|
56
|
+
clock?: ClockLike;
|
|
26
57
|
/**
|
|
27
58
|
* Axios configuration.
|
|
28
59
|
*/
|
|
29
60
|
axios?: CreateAxiosDefaults;
|
|
30
61
|
}
|
|
31
62
|
/**
|
|
32
|
-
* A base class for API clients used in Mailwoman, providing
|
|
33
|
-
* integrated logging.
|
|
63
|
+
* A base class for API clients used in Mailwoman, providing request pacing, response caching, bounded retry, mapped
|
|
64
|
+
* errors, and integrated logging.
|
|
34
65
|
*/
|
|
35
66
|
export declare class APIClient<C extends APIClientConfig = APIClientConfig> extends EventTarget implements AsyncDisposable {
|
|
36
67
|
#private;
|
|
@@ -46,11 +77,32 @@ export declare class APIClient<C extends APIClientConfig = APIClientConfig> exte
|
|
|
46
77
|
readonly axios: AxiosInstance | AxiosCacheInstance;
|
|
47
78
|
constructor(config: C);
|
|
48
79
|
/**
|
|
49
|
-
* Perform a fetch operation using the API's Axios instance
|
|
80
|
+
* Perform a fetch operation using the API's Axios instance: served from cache when possible, paced and cooldown-gated
|
|
81
|
+
* when not, retried within the configured ceiling, and — on the final failure — mapped to a {@linkcode ResourceError}
|
|
82
|
+
* carrying a numeric `status` and a `(source, kind, reason)` URN.
|
|
83
|
+
*
|
|
84
|
+
* Error mapping happens HERE rather than in a response interceptor so the retry loop can see the raw `AxiosError`
|
|
85
|
+
* (status AND `Retry-After`) before it is summarized. The pacing/cooldown gate deliberately does NOT happen here — it
|
|
86
|
+
* sits in the adapter (see the constructor), downstream of the cache, so a hit costs nothing. Every retry attempt
|
|
87
|
+
* re-enters `this.axios(...)` and therefore re-enters that gate; a retry burst cannot outrun the pacer.
|
|
50
88
|
*/
|
|
51
89
|
fetch: <T>(options: AxiosRequestConfig) => Promise<AxiosResponse<T>>;
|
|
90
|
+
/**
|
|
91
|
+
* Acquire permission to dispatch one request, clearing BOTH gates. Each reserves SYNCHRONOUSLY with respect to its
|
|
92
|
+
* own state, so concurrency cannot defeat either of them.
|
|
93
|
+
*
|
|
94
|
+
* The bug this replaced: `fetch()` awaited a single `$cooldown` read and the request was only COUNTED by a response
|
|
95
|
+
* interceptor. N callers invoked in the same turn all cleared the gate before any response came back to set a
|
|
96
|
+
* cooldown — measured at 40 dispatches inside 3ms against a configured budget of 2/minute, and 40 against 10/minute.
|
|
97
|
+
*
|
|
98
|
+
* The pacer is re-acquired on every pass of the loop, NOT taken once up front. A grant is a claim on a specific
|
|
99
|
+
* instant; blocking on a cooldown after taking one leaves it stale, and every caller holding a stale grant spends it
|
|
100
|
+
* the moment the cooldown lifts — measured as four pairs dispatching 0ms apart against a documented 100ms minimum
|
|
101
|
+
* when both gates were configured together. Re-acquiring discards the stale grant (the pacer under-issues by one per
|
|
102
|
+
* cooldown wait, which is the safe direction) and takes a fresh one for the instant we actually dispatch.
|
|
103
|
+
*/
|
|
104
|
+
protected acquireDispatchSlot: () => Promise<void>;
|
|
52
105
|
protected setCooldown: (nextCooldown: number) => void;
|
|
53
|
-
protected updateCooldownAfterResponse: (response: CacheAxiosResponse | AxiosResponse) => CacheAxiosResponse | AxiosResponse<unknown, unknown>;
|
|
54
106
|
[Symbol.asyncDispose](): Promise<void>;
|
|
55
107
|
toString(): string;
|
|
56
108
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"APIClient.d.ts","sourceRoot":"","sources":["../../api/APIClient.ts"],"names":[],"mappings":"AAAA
|
|
1
|
+
{"version":3,"file":"APIClient.d.ts","sourceRoot":"","sources":["../../api/APICl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ACI,KAAK,GAAU,CAAC,EAAE,SAAS,kBAAkB,KAAG,OAAO,CAAC,aAAa,CAAC,CAAC,CAAC,CAAC,CAuC/E;IAED;;;;;;;;;;;;;OAaG;IACH,SAAS,CAAC,mBAAmB,QAAa,OAAO,CAAC,IAAI,CAAC,CAwBtD;IAiCD,SAAS,CAAC,WAAW,GAAI,cAAc,MAAM,KAAG,IAAI,CAiBnD;IAEY,CAAC,MAAM,CAAC,YAAY,CAAC,IAAI,OAAO,CAAC,IAAI,CAAC;IAanC,QAAQ;CAGxB"}
|
package/out/api/APIClient.js
CHANGED
|
@@ -2,23 +2,38 @@
|
|
|
2
2
|
* @copyright Sister Software
|
|
3
3
|
* @license AGPL-3.0
|
|
4
4
|
* @author Teffen Ellis, et al.
|
|
5
|
+
* @file The default base for HTTP clients in this repo. Raw `fetch` duplicates throttling, caching, and
|
|
6
|
+
* error mapping that live here; new clients extend or instantiate this instead (see `AGENTS.md`).
|
|
5
7
|
*/
|
|
6
|
-
import { ConsoleLogger } from "@mailwoman/core/logging";
|
|
7
8
|
import { isAsyncDisposable } from "async-init";
|
|
8
9
|
import Axios, {} from "axios";
|
|
9
10
|
import { setupCache, } from "axios-cache-interceptor";
|
|
11
|
+
import { ConsoleLogger } from "../logging/index.js";
|
|
12
|
+
import { systemClock } from "./clock.js";
|
|
13
|
+
import { RequestPacer } from "./pacer.js";
|
|
10
14
|
import { delegateAxiosError } from "./responses.js";
|
|
11
|
-
|
|
15
|
+
import { classifyAxiosFailure, resolveRetryPolicy, retryDelayMs, } from "./retry.js";
|
|
16
|
+
export {} from "../logging/index.js";
|
|
12
17
|
/**
|
|
13
|
-
*
|
|
14
|
-
|
|
18
|
+
* Milliseconds in a minute — the numerator when turning {@linkcode APIClientConfig.requestsPerMinute} into an interval.
|
|
19
|
+
*/
|
|
20
|
+
const MS_PER_MINUTE = 60_000;
|
|
21
|
+
/**
|
|
22
|
+
* A base class for API clients used in Mailwoman, providing request pacing, response caching, bounded retry, mapped
|
|
23
|
+
* errors, and integrated logging.
|
|
15
24
|
*/
|
|
16
25
|
export class APIClient extends EventTarget {
|
|
17
26
|
config;
|
|
18
27
|
#cooldownWithResolvers = null;
|
|
19
|
-
#requestInterval = 0;
|
|
20
28
|
#requestCountWithinCooldown = 0;
|
|
21
|
-
|
|
29
|
+
/**
|
|
30
|
+
* When the CURRENT budget window opened — the instant of its first dispatch, not of the last one. The cooldown is
|
|
31
|
+
* measured from here, which is what makes `requestsPerMinute` mean requests per MINUTE.
|
|
32
|
+
*/
|
|
33
|
+
#windowStartedAt = 0;
|
|
34
|
+
#clock;
|
|
35
|
+
#pacer;
|
|
36
|
+
#retryPolicy;
|
|
22
37
|
get $cooldown() {
|
|
23
38
|
return this.#cooldownWithResolvers?.promise || Promise.resolve();
|
|
24
39
|
}
|
|
@@ -34,8 +49,28 @@ export class APIClient extends EventTarget {
|
|
|
34
49
|
super();
|
|
35
50
|
this.config = config;
|
|
36
51
|
this.logger = ConsoleLogger.prefix(config.displayName);
|
|
52
|
+
this.#clock = config.clock ?? systemClock;
|
|
53
|
+
this.#retryPolicy = resolveRetryPolicy(config.retry);
|
|
54
|
+
this.#pacer = config.minRequestIntervalMs ? new RequestPacer(config.minRequestIntervalMs, this.#clock) : null;
|
|
55
|
+
// THE PACING GATE LIVES IN THE ADAPTER, not in `fetch()`.
|
|
56
|
+
//
|
|
57
|
+
// `axios-cache-interceptor` short-circuits a cache HIT by replacing `config.adapter` with its own
|
|
58
|
+
// `cachedAdapter`, so anything installed here is reached only when the request is actually going
|
|
59
|
+
// to the network. Gating in `fetch()` instead put the cache interceptor DOWNSTREAM of the gate and
|
|
60
|
+
// made every cache hit burn a full pacer sleep: measured 1 dispatch, 5 hits, five 111ms sleeps for
|
|
61
|
+
// zero network traffic. `/Archives/` documents are cached for a century by design, so warm re-runs
|
|
62
|
+
// are the EXPECTED mode for a bulk crawl — at 100k cached documents that is ~3 hours of sleeping
|
|
63
|
+
// against an empty network. The client this replaced also paced only on a miss.
|
|
64
|
+
//
|
|
65
|
+
// Retries are unaffected: each attempt re-enters `this.axios(...)`, so each re-enters this adapter
|
|
66
|
+
// and takes its own grant.
|
|
67
|
+
const delegateAdapter = Axios.getAdapter(config.axios?.adapter ?? Axios.defaults.adapter);
|
|
37
68
|
const axiosInstance = Axios.create({
|
|
38
69
|
...config.axios,
|
|
70
|
+
adapter: async (requestConfig) => {
|
|
71
|
+
await this.acquireDispatchSlot();
|
|
72
|
+
return delegateAdapter(requestConfig);
|
|
73
|
+
},
|
|
39
74
|
});
|
|
40
75
|
// oxlint-disable-next-line unicorn/prefer-ternary -- the branches are multi-line client constructions
|
|
41
76
|
if (config.caching) {
|
|
@@ -55,48 +90,127 @@ export class APIClient extends EventTarget {
|
|
|
55
90
|
this.logger.debug(`${response.status} ${cachedLabel} ${response.config.method?.toUpperCase()}: ${response.config.url}`);
|
|
56
91
|
return response;
|
|
57
92
|
});
|
|
58
|
-
this.
|
|
59
|
-
this.#requestInterval = typeof config.requestsPerMinute === "number" ? 60_000 / config.requestsPerMinute : 0;
|
|
60
|
-
if (this.#requestInterval) {
|
|
61
|
-
this.axios.interceptors.response.use(this.updateCooldownAfterResponse);
|
|
62
|
-
}
|
|
93
|
+
this.#windowStartedAt = this.#clock.now();
|
|
63
94
|
}
|
|
64
95
|
/**
|
|
65
|
-
* Perform a fetch operation using the API's Axios instance
|
|
96
|
+
* Perform a fetch operation using the API's Axios instance: served from cache when possible, paced and cooldown-gated
|
|
97
|
+
* when not, retried within the configured ceiling, and — on the final failure — mapped to a {@linkcode ResourceError}
|
|
98
|
+
* carrying a numeric `status` and a `(source, kind, reason)` URN.
|
|
99
|
+
*
|
|
100
|
+
* Error mapping happens HERE rather than in a response interceptor so the retry loop can see the raw `AxiosError`
|
|
101
|
+
* (status AND `Retry-After`) before it is summarized. The pacing/cooldown gate deliberately does NOT happen here — it
|
|
102
|
+
* sits in the adapter (see the constructor), downstream of the cache, so a hit costs nothing. Every retry attempt
|
|
103
|
+
* re-enters `this.axios(...)` and therefore re-enters that gate; a retry burst cannot outrun the pacer.
|
|
66
104
|
*/
|
|
67
105
|
fetch = async (options) => {
|
|
68
|
-
await this.$cooldown;
|
|
69
106
|
const method = options.method?.toUpperCase() || "GET";
|
|
70
|
-
|
|
71
|
-
|
|
107
|
+
// A per-request `adapter` would WIN over the instance default in `mergeConfig`, and the pacing/cooldown gate
|
|
108
|
+
// lives in that instance adapter — so passing one here would dispatch with no grant at all. Reproduced against
|
|
109
|
+
// the un-stripped form: a client at `minRequestIntervalMs: 5000` issuing three concurrent `fetch({ url, adapter })`
|
|
110
|
+
// calls made 3 dispatches, took 0 grants and slept 0 times.
|
|
111
|
+
//
|
|
112
|
+
// The cache interceptor swaps the adapter too, and that one is INTENDED — it is how a cache hit skips the gate
|
|
113
|
+
// without spending a grant. The difference is that it swaps on the merged config from inside the interceptor
|
|
114
|
+
// chain, after this method has already handed the request over. Stripping it here closes the caller-supplied
|
|
115
|
+
// door without touching the interceptor's.
|
|
116
|
+
//
|
|
117
|
+
// Latent when found — no shipped client passes an adapter — which is exactly how the cooldown/pacer composition
|
|
118
|
+
// bug survived too. Closing it before `bdc/sdk/client.ts` is written against this contract.
|
|
119
|
+
const { adapter: _callerAdapter, ...safeOptions } = options;
|
|
120
|
+
for (let attempt = 1;; attempt++) {
|
|
121
|
+
this.logger.debug(`${method}: ${options.url}`);
|
|
122
|
+
try {
|
|
123
|
+
return await this.axios(safeOptions);
|
|
124
|
+
}
|
|
125
|
+
catch (error) {
|
|
126
|
+
const directive = classifyAxiosFailure(error);
|
|
127
|
+
if (!directive.retryable || attempt >= this.#retryPolicy.maxAttempts) {
|
|
128
|
+
// Always throws — `Promise<never>` is assignable to this method's return type.
|
|
129
|
+
return await delegateAxiosError(error);
|
|
130
|
+
}
|
|
131
|
+
const waitMs = retryDelayMs(attempt, directive, this.#retryPolicy);
|
|
132
|
+
this.logger.debug(`Retrying ${method} ${options.url} in ${waitMs}ms (attempt ${attempt}/${this.#retryPolicy.maxAttempts}).`);
|
|
133
|
+
await this.#clock.sleep(waitMs);
|
|
134
|
+
}
|
|
135
|
+
}
|
|
72
136
|
};
|
|
137
|
+
/**
|
|
138
|
+
* Acquire permission to dispatch one request, clearing BOTH gates. Each reserves SYNCHRONOUSLY with respect to its
|
|
139
|
+
* own state, so concurrency cannot defeat either of them.
|
|
140
|
+
*
|
|
141
|
+
* The bug this replaced: `fetch()` awaited a single `$cooldown` read and the request was only COUNTED by a response
|
|
142
|
+
* interceptor. N callers invoked in the same turn all cleared the gate before any response came back to set a
|
|
143
|
+
* cooldown — measured at 40 dispatches inside 3ms against a configured budget of 2/minute, and 40 against 10/minute.
|
|
144
|
+
*
|
|
145
|
+
* The pacer is re-acquired on every pass of the loop, NOT taken once up front. A grant is a claim on a specific
|
|
146
|
+
* instant; blocking on a cooldown after taking one leaves it stale, and every caller holding a stale grant spends it
|
|
147
|
+
* the moment the cooldown lifts — measured as four pairs dispatching 0ms apart against a documented 100ms minimum
|
|
148
|
+
* when both gates were configured together. Re-acquiring discards the stale grant (the pacer under-issues by one per
|
|
149
|
+
* cooldown wait, which is the safe direction) and takes a fresh one for the instant we actually dispatch.
|
|
150
|
+
*/
|
|
151
|
+
acquireDispatchSlot = async () => {
|
|
152
|
+
for (;;) {
|
|
153
|
+
await this.#pacer?.acquire();
|
|
154
|
+
const pending = this.#cooldownWithResolvers;
|
|
155
|
+
if (!pending) {
|
|
156
|
+
// Check AND reserve in the same synchronous step. Splitting them — "await the gate, then
|
|
157
|
+
// count" — is the whole bug: every caller queued behind the same microtask turn passes a
|
|
158
|
+
// gate that only closes once one of them has already counted, so the (N-1) callers behind
|
|
159
|
+
// the budget-spending one sail straight through.
|
|
160
|
+
this.#reserveCooldownSlot();
|
|
161
|
+
return;
|
|
162
|
+
}
|
|
163
|
+
await pending.promise;
|
|
164
|
+
// Clear the cooldown we observed, if it's still current — this is what terminates the loop
|
|
165
|
+
// once the timer resolved without opening a replacement.
|
|
166
|
+
if (this.#cooldownWithResolvers === pending) {
|
|
167
|
+
this.#cooldownWithResolvers = null;
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
};
|
|
171
|
+
/**
|
|
172
|
+
* Count this dispatch against the {@linkcode APIClientConfig.requestsPerMinute} budget, opening a cooldown once the
|
|
173
|
+
* budget is spent. Synchronous by construction: it must run to completion before the next caller can observe the
|
|
174
|
+
* counter, which is precisely what the response-interceptor version could not guarantee.
|
|
175
|
+
*/
|
|
176
|
+
#reserveCooldownSlot() {
|
|
177
|
+
const { requestsPerMinute } = this.config;
|
|
178
|
+
if (!requestsPerMinute)
|
|
179
|
+
return;
|
|
180
|
+
const now = this.#clock.now();
|
|
181
|
+
// The first dispatch after a reset OPENS the window. Everything below measures from that instant.
|
|
182
|
+
if (this.#requestCountWithinCooldown === 0) {
|
|
183
|
+
this.#windowStartedAt = now;
|
|
184
|
+
}
|
|
185
|
+
this.#requestCountWithinCooldown++;
|
|
186
|
+
if (this.#requestCountWithinCooldown >= requestsPerMinute) {
|
|
187
|
+
// Wait out the REMAINDER OF THE MINUTE, not `MS_PER_MINUTE / requestsPerMinute`.
|
|
188
|
+
//
|
|
189
|
+
// The original computed `(60000 / N) - elapsed`, which is the spacing between two requests, not the length
|
|
190
|
+
// of the budget window — so N dispatches went out back to back and the client waited 60/N seconds before
|
|
191
|
+
// releasing another N. Measured on a bare client at `requestsPerMinute: 10`, 20-call fan-out: arrivals
|
|
192
|
+
// `[0 x10, 6000 x10]` — 20 inside one sliding minute against a budget of 10, a sustained 100/minute. A
|
|
193
|
+
// caller trusting the docstring would have hammered an upstream at 10x its stated limit.
|
|
194
|
+
this.setCooldown(MS_PER_MINUTE - (now - this.#windowStartedAt));
|
|
195
|
+
}
|
|
196
|
+
}
|
|
73
197
|
setCooldown = (nextCooldown) => {
|
|
74
198
|
const nextCooldownWithResolvers = Promise.withResolvers();
|
|
75
|
-
|
|
199
|
+
this.#cooldownWithResolvers = nextCooldownWithResolvers;
|
|
200
|
+
this.dispatchEvent(new Event("cooldown_start"));
|
|
201
|
+
void this.#clock.sleep(Math.max(nextCooldown, 0)).then(() => {
|
|
76
202
|
this.#requestCountWithinCooldown = 0;
|
|
203
|
+
if (this.#cooldownWithResolvers === nextCooldownWithResolvers) {
|
|
204
|
+
this.#cooldownWithResolvers = null;
|
|
205
|
+
}
|
|
77
206
|
nextCooldownWithResolvers.resolve();
|
|
78
207
|
this.dispatchEvent(new Event("cooldown_end"));
|
|
79
|
-
}
|
|
80
|
-
this.#cooldownWithResolvers = nextCooldownWithResolvers;
|
|
81
|
-
this.dispatchEvent(new Event("cooldown_start"));
|
|
82
|
-
};
|
|
83
|
-
updateCooldownAfterResponse = (response) => {
|
|
84
|
-
this.#cooldownWithResolvers?.resolve();
|
|
85
|
-
const now = Date.now();
|
|
86
|
-
const previousRequestTime = this.#lastRequestTime;
|
|
87
|
-
this.#lastRequestTime = now;
|
|
88
|
-
if (!this.config.requestsPerMinute)
|
|
89
|
-
return response;
|
|
90
|
-
this.#requestCountWithinCooldown++;
|
|
91
|
-
const elapsed = now - previousRequestTime;
|
|
92
|
-
const cooldown = this.#requestInterval - elapsed;
|
|
93
|
-
if (this.#requestCountWithinCooldown >= this.config.requestsPerMinute) {
|
|
94
|
-
this.setCooldown(cooldown);
|
|
95
|
-
}
|
|
96
|
-
return response;
|
|
208
|
+
});
|
|
97
209
|
};
|
|
98
210
|
async [Symbol.asyncDispose]() {
|
|
99
|
-
this.#cooldownWithResolvers
|
|
211
|
+
const pending = this.#cooldownWithResolvers;
|
|
212
|
+
this.#cooldownWithResolvers = null;
|
|
213
|
+
pending?.resolve();
|
|
100
214
|
const storedCache = this.config.caching?.storage;
|
|
101
215
|
if (isAsyncDisposable(storedCache)) {
|
|
102
216
|
await storedCache[Symbol.asyncDispose]();
|
package/out/api/APIClient.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"APIClient.js","sourceRoot":"","sources":["../../api/APIClient.ts"],"names":[],"mappings":"AAAA
|
|
1
|
+
{"version":3,"file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AAY,CAAC;QACjC,MAAM,OAAO,GAAG,IAAI,CAAC,sBAAsB,CAAA;QAE3C,IAAI,CAAC,sBAAsB,GAAG,IAAI,CAAA;QAClC,OAAO,EAAE,OAAO,EAAE,CAAA;QAElB,MAAM,WAAW,GAAG,IAAI,CAAC,MAAM,CAAC,OAAO,EAAE,OAAO,CAAA;QAEhD,IAAI,iBAAiB,CAAC,WAAW,CAAC,EAAE,CAAC;YACpC,MAAM,WAAW,CAAC,MAAM,CAAC,YAAY,CAAC,EAAE,CAAA;QACzC,CAAC;IACF,CAAC;IAEe,QAAQ;QACvB,OAAO,GAAG,IAAI,CAAC,MAAM,CAAC,WAAW,aAAa,CAAA;IAC/C,CAAC;CACD"}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @copyright Sister Software
|
|
3
|
+
* @license AGPL-3.0
|
|
4
|
+
* @author Teffen Ellis, et al.
|
|
5
|
+
* @file The injectable time source every timing-sensitive part of {@linkcode APIClient} reads through.
|
|
6
|
+
*
|
|
7
|
+
* Lifted from `filer/sdk/sec-client.ts` (3b task 5) when the SEC client's bespoke pacing/retry
|
|
8
|
+
* machinery moved down into `@mailwoman/core/api`. Keeping the seam is the whole reason the pacing
|
|
9
|
+
* and backoff suites are deterministic and finish in milliseconds instead of sleeping on the wall
|
|
10
|
+
* clock — a rate-limit test that actually waits 100ms per grant costs 4s for a 40-call fan-out and
|
|
11
|
+
* is flaky under CI load; the same test against an injected clock is exact and instant.
|
|
12
|
+
*
|
|
13
|
+
* Deliberately NOT `node:timers/promises`: `core/api` reaches a browser bundle (`docs`'s
|
|
14
|
+
* `DashboardMap` imports `@mailwoman/cartographer`, which barrels `tiles/api.ts`, which imports
|
|
15
|
+
* `@mailwoman/core/api`), and webpack 5 refuses to resolve a `node:`-prefixed specifier for the
|
|
16
|
+
* web target. The global `setTimeout` is available on every runtime this package ships to.
|
|
17
|
+
*/
|
|
18
|
+
/**
|
|
19
|
+
* A minimal, injectable time source. Anything in this package that would otherwise call `Date.now()` or `setTimeout`
|
|
20
|
+
* directly reads through this instead, so tests can drive time deterministically.
|
|
21
|
+
*/
|
|
22
|
+
export interface ClockLike {
|
|
23
|
+
/**
|
|
24
|
+
* The current time, in milliseconds. Same contract as `Date.now()`.
|
|
25
|
+
*/
|
|
26
|
+
now(): number;
|
|
27
|
+
/**
|
|
28
|
+
* Resolve after at least `ms` milliseconds of this clock's time.
|
|
29
|
+
*/
|
|
30
|
+
sleep(ms: number): Promise<void>;
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* The real-time {@linkcode ClockLike}, used whenever a caller doesn't inject one.
|
|
34
|
+
*/
|
|
35
|
+
export declare const systemClock: ClockLike;
|
|
36
|
+
//# sourceMappingURL=clock.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"clock.d.ts","sourceRoot":"","sources":["../../api/clock.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GAgBG;AAEH;;;GAGG;AACH,MAAM,WAAW,SAAS;IACzB;;OAEG;IACH,GAAG,IAAI,MAAM,CAAA;IACb;;OAEG;IACH,KAAK,CAAC,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAAA;CAChC;AAED;;GAEG;AACH,eAAO,MAAM,WAAW,EAAE,SAMzB,CAAA"}
|