@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.
Files changed (52) hide show
  1. package/api/APIClient.ts +207 -42
  2. package/api/clock.ts +43 -0
  3. package/api/disk-storage.ts +239 -0
  4. package/api/index.ts +7 -0
  5. package/api/pacer.ts +98 -0
  6. package/api/responses.ts +227 -44
  7. package/api/retry.ts +227 -0
  8. package/api/test-clocks.ts +234 -0
  9. package/env/schema.ts +3 -0
  10. package/out/api/APIClient.d.ts +60 -8
  11. package/out/api/APIClient.d.ts.map +1 -1
  12. package/out/api/APIClient.js +149 -35
  13. package/out/api/APIClient.js.map +1 -1
  14. package/out/api/clock.d.ts +36 -0
  15. package/out/api/clock.d.ts.map +1 -0
  16. package/out/api/clock.js +27 -0
  17. package/out/api/clock.js.map +1 -0
  18. package/out/api/disk-storage.d.ts +64 -0
  19. package/out/api/disk-storage.d.ts.map +1 -0
  20. package/out/api/disk-storage.js +185 -0
  21. package/out/api/disk-storage.js.map +1 -0
  22. package/out/api/index.d.ts +3 -0
  23. package/out/api/index.d.ts.map +1 -1
  24. package/out/api/index.js +6 -0
  25. package/out/api/index.js.map +1 -1
  26. package/out/api/pacer.d.ts +68 -0
  27. package/out/api/pacer.d.ts.map +1 -0
  28. package/out/api/pacer.js +88 -0
  29. package/out/api/pacer.js.map +1 -0
  30. package/out/api/responses.d.ts +71 -2
  31. package/out/api/responses.d.ts.map +1 -1
  32. package/out/api/responses.js +160 -34
  33. package/out/api/responses.js.map +1 -1
  34. package/out/api/retry.d.ts +119 -0
  35. package/out/api/retry.d.ts.map +1 -0
  36. package/out/api/retry.js +158 -0
  37. package/out/api/retry.js.map +1 -0
  38. package/out/api/test-clocks.d.ts +87 -0
  39. package/out/api/test-clocks.d.ts.map +1 -0
  40. package/out/api/test-clocks.js +175 -0
  41. package/out/api/test-clocks.js.map +1 -0
  42. package/out/env/index.d.ts +1 -0
  43. package/out/env/index.d.ts.map +1 -1
  44. package/out/env/schema.d.ts +1 -0
  45. package/out/env/schema.d.ts.map +1 -1
  46. package/out/env/schema.js +2 -0
  47. package/out/env/schema.js.map +1 -1
  48. package/out/vitest.config.d.ts.map +1 -1
  49. package/out/vitest.config.js +2 -0
  50. package/out/vitest.config.js.map +1 -1
  51. package/package.json +18 -2
  52. package/vitest.config.ts +2 -0
package/api/APIClient.ts CHANGED
@@ -2,9 +2,10 @@
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
8
 
7
- import { ConsoleLogger, type IRuntimeLogger } from "@mailwoman/core/logging"
8
9
  import { isAsyncDisposable } from "async-init"
9
10
  import Axios, { type AxiosInstance, type AxiosRequestConfig, type AxiosResponse, type CreateAxiosDefaults } from "axios"
10
11
  import {
@@ -14,9 +15,24 @@ import {
14
15
  setupCache,
15
16
  } from "axios-cache-interceptor"
16
17
 
18
+ import { ConsoleLogger, type IRuntimeLogger } from "../logging/index.ts"
19
+ import { type ClockLike, systemClock } from "./clock.ts"
20
+ import { RequestPacer } from "./pacer.ts"
17
21
  import { delegateAxiosError } from "./responses.ts"
22
+ import {
23
+ classifyAxiosFailure,
24
+ type ResolvedRetryPolicy,
25
+ resolveRetryPolicy,
26
+ retryDelayMs,
27
+ type RetryOptions,
28
+ } from "./retry.ts"
29
+
30
+ export { type IRuntimeLogger } from "../logging/index.ts"
18
31
 
19
- export { type IRuntimeLogger } from "@mailwoman/core/logging"
32
+ /**
33
+ * Milliseconds in a minute — the numerator when turning {@linkcode APIClientConfig.requestsPerMinute} into an interval.
34
+ */
35
+ const MS_PER_MINUTE = 60_000
20
36
 
21
37
  /**
22
38
  * Configuration for an API client.
@@ -33,10 +49,40 @@ export interface APIClientConfig {
33
49
  caching?: CacheOptions
34
50
 
35
51
  /**
36
- * How many requests to make per minute before enforcing a cooldown.
52
+ * How many requests to make per minute before enforcing a cooldown: a BUDGET model — spend `requestsPerMinute`
53
+ * dispatches, then stall until the cooldown lapses.
54
+ *
55
+ * This cannot express a flat per-second rate, which is what most fair-access policies actually publish. For that use
56
+ * {@linkcode minRequestIntervalMs}; the two compose (both gates must clear) but you almost certainly want one.
37
57
  */
38
58
  requestsPerMinute?: number
39
59
 
60
+ /**
61
+ * The minimum spacing between two dispatches, in milliseconds — strict pacing with NO burst allowance.
62
+ *
63
+ * Set this when an upstream publishes a flat rate (SEC EDGAR: 10 requests/second, enforced): `1000 / rate`. Unlike
64
+ * {@linkcode requestsPerMinute}, the guarantee holds under arbitrary concurrency — grants are reserved synchronously,
65
+ * so N callers racing in one turn are still spaced one interval apart. A token bucket cannot do this: capacity C
66
+ * admits `C + rate * 1s` inside a sliding second, so no non-zero capacity honors a flat cap.
67
+ */
68
+ minRequestIntervalMs?: number
69
+
70
+ /**
71
+ * Bounded retry with exponential backoff, honoring a response's `Retry-After`. Pass `true` for the defaults.
72
+ *
73
+ * OPT-IN, and absent by default: an `APIClient` without this makes exactly one attempt, which is what every existing
74
+ * consumer has always done. 429/5xx/408 and network-class failures (dropped socket, DNS, timeout, mid-body-transfer
75
+ * drop) are retried; a 403 never is — it means the request failed to identify itself, so retrying can only fail
76
+ * identically while burning rate budget.
77
+ */
78
+ retry?: RetryOptions | boolean
79
+
80
+ /**
81
+ * Time source powering the pacer, the cooldown timer, and the retry backoff. Defaults to {@linkcode systemClock};
82
+ * tests inject a fake clock so timing behavior is deterministic and instant.
83
+ */
84
+ clock?: ClockLike
85
+
40
86
  /**
41
87
  * Axios configuration.
42
88
  */
@@ -44,16 +90,23 @@ export interface APIClientConfig {
44
90
  }
45
91
 
46
92
  /**
47
- * A base class for API clients used in Mailwoman, providing features like request cooldowns, response caching, and
48
- * integrated logging.
93
+ * A base class for API clients used in Mailwoman, providing request pacing, response caching, bounded retry, mapped
94
+ * errors, and integrated logging.
49
95
  */
50
96
  export class APIClient<C extends APIClientConfig = APIClientConfig> extends EventTarget implements AsyncDisposable {
51
97
  public readonly config: C
52
98
 
53
99
  #cooldownWithResolvers: PromiseWithResolvers<void> | null = null
54
- #requestInterval = 0
55
100
  #requestCountWithinCooldown = 0
56
- #lastRequestTime = 0
101
+ /**
102
+ * When the CURRENT budget window opened — the instant of its first dispatch, not of the last one. The cooldown is
103
+ * measured from here, which is what makes `requestsPerMinute` mean requests per MINUTE.
104
+ */
105
+ #windowStartedAt = 0
106
+
107
+ readonly #clock: ClockLike
108
+ readonly #pacer: RequestPacer | null
109
+ readonly #retryPolicy: ResolvedRetryPolicy
57
110
 
58
111
  public get $cooldown(): Promise<void> {
59
112
  return this.#cooldownWithResolvers?.promise || Promise.resolve()
@@ -73,9 +126,31 @@ export class APIClient<C extends APIClientConfig = APIClientConfig> extends Even
73
126
 
74
127
  this.config = config
75
128
  this.logger = ConsoleLogger.prefix(config.displayName)
129
+ this.#clock = config.clock ?? systemClock
130
+ this.#retryPolicy = resolveRetryPolicy(config.retry)
131
+ this.#pacer = config.minRequestIntervalMs ? new RequestPacer(config.minRequestIntervalMs, this.#clock) : null
132
+
133
+ // THE PACING GATE LIVES IN THE ADAPTER, not in `fetch()`.
134
+ //
135
+ // `axios-cache-interceptor` short-circuits a cache HIT by replacing `config.adapter` with its own
136
+ // `cachedAdapter`, so anything installed here is reached only when the request is actually going
137
+ // to the network. Gating in `fetch()` instead put the cache interceptor DOWNSTREAM of the gate and
138
+ // made every cache hit burn a full pacer sleep: measured 1 dispatch, 5 hits, five 111ms sleeps for
139
+ // zero network traffic. `/Archives/` documents are cached for a century by design, so warm re-runs
140
+ // are the EXPECTED mode for a bulk crawl — at 100k cached documents that is ~3 hours of sleeping
141
+ // against an empty network. The client this replaced also paced only on a miss.
142
+ //
143
+ // Retries are unaffected: each attempt re-enters `this.axios(...)`, so each re-enters this adapter
144
+ // and takes its own grant.
145
+ const delegateAdapter = Axios.getAdapter(config.axios?.adapter ?? Axios.defaults.adapter)
76
146
 
77
147
  const axiosInstance = Axios.create({
78
148
  ...config.axios,
149
+ adapter: async (requestConfig) => {
150
+ await this.acquireDispatchSlot()
151
+
152
+ return delegateAdapter(requestConfig)
153
+ },
79
154
  })
80
155
 
81
156
  // oxlint-disable-next-line unicorn/prefer-ternary -- the branches are multi-line client constructions
@@ -101,65 +176,155 @@ export class APIClient<C extends APIClientConfig = APIClientConfig> extends Even
101
176
  return response
102
177
  })
103
178
 
104
- this.axios.interceptors.response.use(undefined, delegateAxiosError)
179
+ this.#windowStartedAt = this.#clock.now()
180
+ }
105
181
 
106
- this.#requestInterval = typeof config.requestsPerMinute === "number" ? 60_000 / config.requestsPerMinute : 0
182
+ /**
183
+ * Perform a fetch operation using the API's Axios instance: served from cache when possible, paced and cooldown-gated
184
+ * when not, retried within the configured ceiling, and — on the final failure — mapped to a {@linkcode ResourceError}
185
+ * carrying a numeric `status` and a `(source, kind, reason)` URN.
186
+ *
187
+ * Error mapping happens HERE rather than in a response interceptor so the retry loop can see the raw `AxiosError`
188
+ * (status AND `Retry-After`) before it is summarized. The pacing/cooldown gate deliberately does NOT happen here — it
189
+ * sits in the adapter (see the constructor), downstream of the cache, so a hit costs nothing. Every retry attempt
190
+ * re-enters `this.axios(...)` and therefore re-enters that gate; a retry burst cannot outrun the pacer.
191
+ */
192
+ public fetch = async <T>(options: AxiosRequestConfig): Promise<AxiosResponse<T>> => {
193
+ const method = options.method?.toUpperCase() || "GET"
107
194
 
108
- if (this.#requestInterval) {
109
- this.axios.interceptors.response.use(this.updateCooldownAfterResponse)
195
+ // A per-request `adapter` would WIN over the instance default in `mergeConfig`, and the pacing/cooldown gate
196
+ // lives in that instance adapter — so passing one here would dispatch with no grant at all. Reproduced against
197
+ // the un-stripped form: a client at `minRequestIntervalMs: 5000` issuing three concurrent `fetch({ url, adapter })`
198
+ // calls made 3 dispatches, took 0 grants and slept 0 times.
199
+ //
200
+ // The cache interceptor swaps the adapter too, and that one is INTENDED — it is how a cache hit skips the gate
201
+ // without spending a grant. The difference is that it swaps on the merged config from inside the interceptor
202
+ // chain, after this method has already handed the request over. Stripping it here closes the caller-supplied
203
+ // door without touching the interceptor's.
204
+ //
205
+ // Latent when found — no shipped client passes an adapter — which is exactly how the cooldown/pacer composition
206
+ // bug survived too. Closing it before `bdc/sdk/client.ts` is written against this contract.
207
+ const { adapter: _callerAdapter, ...safeOptions } = options
208
+
209
+ for (let attempt = 1; ; attempt++) {
210
+ this.logger.debug(`${method}: ${options.url}`)
211
+
212
+ try {
213
+ return await this.axios(safeOptions)
214
+ } catch (error) {
215
+ const directive = classifyAxiosFailure(error)
216
+
217
+ if (!directive.retryable || attempt >= this.#retryPolicy.maxAttempts) {
218
+ // Always throws — `Promise<never>` is assignable to this method's return type.
219
+ return await delegateAxiosError(error)
220
+ }
221
+
222
+ const waitMs = retryDelayMs(attempt, directive, this.#retryPolicy)
223
+
224
+ this.logger.debug(
225
+ `Retrying ${method} ${options.url} in ${waitMs}ms (attempt ${attempt}/${this.#retryPolicy.maxAttempts}).`
226
+ )
227
+
228
+ await this.#clock.sleep(waitMs)
229
+ }
110
230
  }
111
231
  }
112
232
 
113
233
  /**
114
- * Perform a fetch operation using the API's Axios instance.
234
+ * Acquire permission to dispatch one request, clearing BOTH gates. Each reserves SYNCHRONOUSLY with respect to its
235
+ * own state, so concurrency cannot defeat either of them.
236
+ *
237
+ * The bug this replaced: `fetch()` awaited a single `$cooldown` read and the request was only COUNTED by a response
238
+ * interceptor. N callers invoked in the same turn all cleared the gate before any response came back to set a
239
+ * cooldown — measured at 40 dispatches inside 3ms against a configured budget of 2/minute, and 40 against 10/minute.
240
+ *
241
+ * The pacer is re-acquired on every pass of the loop, NOT taken once up front. A grant is a claim on a specific
242
+ * instant; blocking on a cooldown after taking one leaves it stale, and every caller holding a stale grant spends it
243
+ * the moment the cooldown lifts — measured as four pairs dispatching 0ms apart against a documented 100ms minimum
244
+ * when both gates were configured together. Re-acquiring discards the stale grant (the pacer under-issues by one per
245
+ * cooldown wait, which is the safe direction) and takes a fresh one for the instant we actually dispatch.
115
246
  */
116
- public fetch = async <T>(options: AxiosRequestConfig): Promise<AxiosResponse<T>> => {
117
- await this.$cooldown
247
+ protected acquireDispatchSlot = async (): Promise<void> => {
248
+ for (;;) {
249
+ await this.#pacer?.acquire()
118
250
 
119
- const method = options.method?.toUpperCase() || "GET"
120
- this.logger.debug(`${method}: ${options.url}`)
251
+ const pending = this.#cooldownWithResolvers
252
+
253
+ if (!pending) {
254
+ // Check AND reserve in the same synchronous step. Splitting them — "await the gate, then
255
+ // count" — is the whole bug: every caller queued behind the same microtask turn passes a
256
+ // gate that only closes once one of them has already counted, so the (N-1) callers behind
257
+ // the budget-spending one sail straight through.
258
+ this.#reserveCooldownSlot()
259
+
260
+ return
261
+ }
262
+
263
+ await pending.promise
121
264
 
122
- return this.axios(options)
265
+ // Clear the cooldown we observed, if it's still current — this is what terminates the loop
266
+ // once the timer resolved without opening a replacement.
267
+ if (this.#cooldownWithResolvers === pending) {
268
+ this.#cooldownWithResolvers = null
269
+ }
270
+ }
123
271
  }
124
272
 
125
- protected setCooldown = (nextCooldown: number): void => {
126
- const nextCooldownWithResolvers = Promise.withResolvers<void>()
273
+ /**
274
+ * Count this dispatch against the {@linkcode APIClientConfig.requestsPerMinute} budget, opening a cooldown once the
275
+ * budget is spent. Synchronous by construction: it must run to completion before the next caller can observe the
276
+ * counter, which is precisely what the response-interceptor version could not guarantee.
277
+ */
278
+ #reserveCooldownSlot(): void {
279
+ const { requestsPerMinute } = this.config
127
280
 
128
- setTimeout(() => {
129
- this.#requestCountWithinCooldown = 0
130
- nextCooldownWithResolvers.resolve()
281
+ if (!requestsPerMinute) return
131
282
 
132
- this.dispatchEvent(new Event("cooldown_end"))
133
- }, nextCooldown)
283
+ const now = this.#clock.now()
134
284
 
135
- this.#cooldownWithResolvers = nextCooldownWithResolvers
136
- this.dispatchEvent(new Event("cooldown_start"))
285
+ // The first dispatch after a reset OPENS the window. Everything below measures from that instant.
286
+ if (this.#requestCountWithinCooldown === 0) {
287
+ this.#windowStartedAt = now
288
+ }
289
+
290
+ this.#requestCountWithinCooldown++
291
+
292
+ if (this.#requestCountWithinCooldown >= requestsPerMinute) {
293
+ // Wait out the REMAINDER OF THE MINUTE, not `MS_PER_MINUTE / requestsPerMinute`.
294
+ //
295
+ // The original computed `(60000 / N) - elapsed`, which is the spacing between two requests, not the length
296
+ // of the budget window — so N dispatches went out back to back and the client waited 60/N seconds before
297
+ // releasing another N. Measured on a bare client at `requestsPerMinute: 10`, 20-call fan-out: arrivals
298
+ // `[0 x10, 6000 x10]` — 20 inside one sliding minute against a budget of 10, a sustained 100/minute. A
299
+ // caller trusting the docstring would have hammered an upstream at 10x its stated limit.
300
+ this.setCooldown(MS_PER_MINUTE - (now - this.#windowStartedAt))
301
+ }
137
302
  }
138
303
 
139
- protected updateCooldownAfterResponse = (
140
- response: CacheAxiosResponse | AxiosResponse
141
- ): CacheAxiosResponse | AxiosResponse<unknown, unknown> => {
142
- this.#cooldownWithResolvers?.resolve()
143
- const now = Date.now()
144
- const previousRequestTime = this.#lastRequestTime
145
- this.#lastRequestTime = now
304
+ protected setCooldown = (nextCooldown: number): void => {
305
+ const nextCooldownWithResolvers = Promise.withResolvers<void>()
146
306
 
147
- if (!this.config.requestsPerMinute) return response
307
+ this.#cooldownWithResolvers = nextCooldownWithResolvers
308
+ this.dispatchEvent(new Event("cooldown_start"))
148
309
 
149
- this.#requestCountWithinCooldown++
310
+ void this.#clock.sleep(Math.max(nextCooldown, 0)).then(() => {
311
+ this.#requestCountWithinCooldown = 0
150
312
 
151
- const elapsed = now - previousRequestTime
152
- const cooldown = this.#requestInterval - elapsed
313
+ if (this.#cooldownWithResolvers === nextCooldownWithResolvers) {
314
+ this.#cooldownWithResolvers = null
315
+ }
153
316
 
154
- if (this.#requestCountWithinCooldown >= this.config.requestsPerMinute) {
155
- this.setCooldown(cooldown)
156
- }
317
+ nextCooldownWithResolvers.resolve()
157
318
 
158
- return response
319
+ this.dispatchEvent(new Event("cooldown_end"))
320
+ })
159
321
  }
160
322
 
161
323
  public async [Symbol.asyncDispose](): Promise<void> {
162
- this.#cooldownWithResolvers?.resolve()
324
+ const pending = this.#cooldownWithResolvers
325
+
326
+ this.#cooldownWithResolvers = null
327
+ pending?.resolve()
163
328
 
164
329
  const storedCache = this.config.caching?.storage
165
330
 
package/api/clock.ts ADDED
@@ -0,0 +1,43 @@
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
+ /**
20
+ * A minimal, injectable time source. Anything in this package that would otherwise call `Date.now()` or `setTimeout`
21
+ * directly reads through this instead, so tests can drive time deterministically.
22
+ */
23
+ export interface ClockLike {
24
+ /**
25
+ * The current time, in milliseconds. Same contract as `Date.now()`.
26
+ */
27
+ now(): number
28
+ /**
29
+ * Resolve after at least `ms` milliseconds of this clock's time.
30
+ */
31
+ sleep(ms: number): Promise<void>
32
+ }
33
+
34
+ /**
35
+ * The real-time {@linkcode ClockLike}, used whenever a caller doesn't inject one.
36
+ */
37
+ export const systemClock: ClockLike = {
38
+ now: () => Date.now(),
39
+ sleep: (ms) =>
40
+ new Promise<void>((resolve) => {
41
+ setTimeout(resolve, ms)
42
+ }),
43
+ }
@@ -0,0 +1,239 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ * @file An on-disk `axios-cache-interceptor` storage adapter, so a client gets a durable HTTP cache by
6
+ * CONFIGURATION rather than by hand-rolling one (3b task 5).
7
+ *
8
+ * NODE ONLY, and deliberately NOT re-exported from `./index.ts`: `core/api` reaches a browser bundle
9
+ * (`docs`'s `DashboardMap` → `@mailwoman/cartographer` → `tiles/api.ts` → `@mailwoman/core/api`),
10
+ * and webpack refuses to resolve `node:fs/promises` for the web target. Import this through its own
11
+ * `@mailwoman/core/api/disk-storage` subpath.
12
+ *
13
+ * Two rules here are load-bearing, both carried over from the bespoke cache this replaces
14
+ * (`98c4dda1:filer/sdk/sec-client.ts`), both learned the hard way:
15
+ *
16
+ * 1. VALIDATE BEFORE WRITING. A response that can't be read back — an unparseable body, a
17
+ * non-finite TTL — must never reach disk. A permanently-cached entry has no self-healing path
18
+ * short of hand-deleting a hash-named file.
19
+ * 2. ATOMIC WRITE, UNIQUE TEMP NAME. Write-then-rename, with a temp name unique per write. A
20
+ * DETERMINISTIC temp name (`${final}.building`) made two clients writing one URL collide: the
21
+ * first `rename()` moved the shared temp file away and the second got a raw `ENOENT` for a
22
+ * response that had already succeeded (reproduced 6/6), and at multi-MB bodies the two writers'
23
+ * bytes interleaved into a corrupt-but-parseable entry.
24
+ */
25
+
26
+ import { randomUUID } from "node:crypto"
27
+ import { mkdir, readFile, rename, rm, unlink, writeFile } from "node:fs/promises"
28
+ import { join } from "node:path"
29
+
30
+ import { type AxiosStorage, buildStorage, type NotEmptyStorageValue, type StorageValue } from "axios-cache-interceptor"
31
+
32
+ import { ConsoleLogger, type IRuntimeLogger } from "../logging/index.ts"
33
+ import { sha256Hex } from "../utils/hash.ts"
34
+
35
+ /**
36
+ * Options for {@linkcode buildDiskStorage}.
37
+ */
38
+ export interface DiskStorageOptions {
39
+ /**
40
+ * The directory cache entries live in. Created on first write (recursively).
41
+ */
42
+ directory: string
43
+ /**
44
+ * An additional, domain-specific gate run against every entry BEFORE it is written. Return `false` (or throw) to drop
45
+ * the write; the entry is removed rather than persisted, so the next request re-fetches.
46
+ *
47
+ * This is the seam for "a 200 whose body isn't what this API is supposed to return". Some upstreams (SEC EDGAR among
48
+ * them) serve an HTML error page with a 200 status; persisting one under a permanent TTL poisons that URL forever.
49
+ * The structural checks below (serializable, finite `createdAt`/`ttl`) always run regardless.
50
+ */
51
+ validate?: (value: NotEmptyStorageValue) => boolean
52
+ /**
53
+ * Where rejected writes and unreadable entries are reported. Defaults to a `disk-storage`-prefixed console logger.
54
+ */
55
+ logger?: IRuntimeLogger
56
+ }
57
+
58
+ /**
59
+ * Whether a storage value is one worth persisting. `loading` is an in-flight marker with no reusable body — it belongs
60
+ * in memory (see {@linkcode buildDiskStorage}'s in-process overlay), not in a file that would outlive the process that
61
+ * wrote it and block every later request for that key.
62
+ */
63
+ function isPersistableState(value: NotEmptyStorageValue): boolean {
64
+ return value.state !== "loading"
65
+ }
66
+
67
+ /**
68
+ * The structural half of the validate-before-write rule: an entry must survive a JSON round trip WITH ITS MEANING
69
+ * INTACT.
70
+ *
71
+ * `createdAt` and `ttl` get an explicit finite check because `JSON.stringify(Infinity)` is the string `null`, and
72
+ * `null` reads back as `0` in the interceptor's `createdAt + ttl < Date.now()` expiry test. An `Infinity` TTL — the
73
+ * obvious way to spell "cache this immutable document forever" — would therefore round-trip into an entry that is
74
+ * expired the instant it is read. Rejecting it loudly beats silently caching nothing.
75
+ */
76
+ function hasFiniteTiming(value: NotEmptyStorageValue): boolean {
77
+ if (value.createdAt !== undefined && !Number.isFinite(value.createdAt)) return false
78
+
79
+ return value.ttl === undefined || Number.isFinite(value.ttl)
80
+ }
81
+
82
+ /**
83
+ * Create an on-disk {@linkcode AxiosStorage}, keyed by the SHA-256 of the interceptor's cache key (which already folds
84
+ * in method, URL, params and body), so a filename is always a fixed-length, filesystem-safe hex digest.
85
+ *
86
+ * An in-process overlay Map sits in front of the files, and it is load-bearing for two reasons:
87
+ *
88
+ * 1. `loading` markers live there INSTEAD of on disk. That keeps the interceptor's stampede guard working (a concurrent
89
+ * second request for the same key sees `loading` and waits on the first) without a file write per request, and
90
+ * without an interrupted process leaving a `loading` marker on disk forever.
91
+ * 2. A value being WRITTEN stays there until its `rename` lands. Without that, `set()` clearing the `loading` marker
92
+ * before the file exists opens a window where the key is in neither place, and a concurrent reader gets `empty` for
93
+ * a response that is already in hand — measured as 3 dispatches for 3 concurrent requests to one URL, i.e. the
94
+ * stampede guard fully defeated.
95
+ */
96
+ export function buildDiskStorage(options: DiskStorageOptions): AxiosStorage {
97
+ const { directory, validate } = options
98
+ const logger = options.logger ?? ConsoleLogger.prefix("disk-storage")
99
+
100
+ /**
101
+ * Values visible to this process ahead of (or instead of) the files: `loading` markers, which are never persisted,
102
+ * and entries mid-write, which are dropped once their `rename` lands. See the function docstring.
103
+ */
104
+ const overlay = new Map<string, StorageValue>()
105
+
106
+ function entryPath(key: string): string {
107
+ return join(directory, `${sha256Hex(key)}.json`)
108
+ }
109
+
110
+ async function removeEntry(key: string): Promise<void> {
111
+ overlay.delete(key)
112
+
113
+ try {
114
+ await unlink(entryPath(key))
115
+ } catch {
116
+ // A miss is the expected case for a key that was never persisted (or was already evicted).
117
+ }
118
+ }
119
+
120
+ /**
121
+ * Serialize `value`, or return `null` when it must not reach disk. Every rejection path is logged with the key so a
122
+ * maintainer seeing a cache that never fills has something to grep for.
123
+ */
124
+ function serializeIfValid(key: string, value: NotEmptyStorageValue): string | null {
125
+ if (!hasFiniteTiming(value)) {
126
+ logger.warn(`Refusing to cache ${key}: createdAt/ttl must be finite (received ttl=${String(value.ttl)}).`)
127
+
128
+ return null
129
+ }
130
+
131
+ try {
132
+ if (validate && !validate(value)) {
133
+ logger.warn(`Refusing to cache ${key}: rejected by the configured validate() predicate.`)
134
+
135
+ return null
136
+ }
137
+
138
+ return JSON.stringify(value)
139
+ } catch (error) {
140
+ logger.warn(`Refusing to cache ${key}: ${error instanceof Error ? error.message : String(error)}`)
141
+
142
+ return null
143
+ }
144
+ }
145
+
146
+ return buildStorage({
147
+ find: async (key) => {
148
+ const pending = overlay.get(key)
149
+
150
+ if (pending) return pending
151
+
152
+ let raw: string
153
+
154
+ try {
155
+ raw = await readFile(entryPath(key), "utf8")
156
+ } catch {
157
+ return undefined
158
+ }
159
+
160
+ try {
161
+ return JSON.parse(raw) as StorageValue
162
+ } catch {
163
+ // A truncated or hand-edited entry is a miss, not a crash — re-fetching is always safe.
164
+ logger.warn(`Discarding an unreadable cache entry for ${key}.`)
165
+
166
+ await removeEntry(key)
167
+
168
+ return undefined
169
+ }
170
+ },
171
+
172
+ set: async (key, value) => {
173
+ if (!isPersistableState(value)) {
174
+ overlay.set(key, value)
175
+
176
+ return
177
+ }
178
+
179
+ const serialized = serializeIfValid(key, value)
180
+
181
+ if (serialized === null) {
182
+ // Drop any older entry too: the interceptor is telling us this key's content just changed,
183
+ // and keeping a superseded body would be worse than a miss.
184
+ await removeEntry(key)
185
+
186
+ return
187
+ }
188
+
189
+ // Publish to the overlay BEFORE the write and clear it only once the rename has landed, so the
190
+ // key is continuously visible: the `loading` marker is replaced by the real value in the same
191
+ // synchronous step, never by a gap.
192
+ overlay.set(key, value)
193
+
194
+ const finalPath = entryPath(key)
195
+ // Unique per write — `process.pid` separates processes, `randomUUID()` separates concurrent
196
+ // writes inside one. A deterministic name here is the ENOENT/interleaving bug in the file header.
197
+ const buildingPath = `${finalPath}.${process.pid}.${randomUUID()}.building`
198
+
199
+ try {
200
+ await mkdir(directory, { recursive: true })
201
+ await writeFile(buildingPath, serialized)
202
+ await rename(buildingPath, finalPath)
203
+ } catch (error) {
204
+ // A CACHE WRITE IS A SIDE EFFECT OF A SUCCESSFUL REQUEST, AND A FAILED SIDE EFFECT MUST NOT
205
+ // FAIL THE REQUEST.
206
+ //
207
+ // `axios-cache-interceptor` awaits `set()` inside its response `onFulfilled`, so throwing
208
+ // from here rejects a request whose HTTP response ALREADY SUCCEEDED — the body is discarded.
209
+ // Worse, it escapes as a bare `Error`: no `status`, so `isTransientResourceError` reads it as
210
+ // FALSE and a caller following the documented contract is told never to retry. ANY
211
+ // filesystem failure does this: `EACCES` on a directory whose mode changed (reproduced with
212
+ // a `0o500` parent, which also showed three concurrent gets yielding one rejection and two
213
+ // successes for the SAME response), `EMFILE` under a concurrent crawl, a rename race, a
214
+ // transient I/O error. Not being able to cache is a cache miss.
215
+ logger.warn(
216
+ `Could not persist ${key} (continuing as a cache miss): ${
217
+ error instanceof Error ? error.message : String(error)
218
+ }`
219
+ )
220
+
221
+ // Best-effort cleanup of the temp file, if the failure came after it was created.
222
+ await unlink(buildingPath).catch(() => undefined)
223
+ } finally {
224
+ overlay.delete(key)
225
+ }
226
+ },
227
+
228
+ remove: removeEntry,
229
+
230
+ clear: async () => {
231
+ overlay.clear()
232
+
233
+ // Recreated rather than left absent: "the cache is empty" and "the cache directory vanished"
234
+ // are different states to anything inspecting the data root, and only the first is intended.
235
+ await rm(directory, { recursive: true, force: true })
236
+ await mkdir(directory, { recursive: true })
237
+ },
238
+ })
239
+ }
package/api/index.ts CHANGED
@@ -7,5 +7,12 @@
7
7
  */
8
8
 
9
9
  export * from "./APIClient.ts"
10
+ export * from "./clock.ts"
10
11
  export * from "./headless.ts"
12
+ export * from "./pacer.ts"
11
13
  export * from "./responses.ts"
14
+ export * from "./retry.ts"
15
+
16
+ // NOT `./disk-storage.ts` — it imports `node:fs/promises`, and this barrel reaches a browser bundle
17
+ // (docs' DashboardMap → @mailwoman/cartographer → tiles/api.ts → @mailwoman/core/api). Import it from
18
+ // its own `@mailwoman/core/api/disk-storage` subpath.