@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
package/api/pacer.ts
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @copyright Sister Software
|
|
3
|
+
* @license AGPL-3.0
|
|
4
|
+
* @author Teffen Ellis, et al.
|
|
5
|
+
* @file Strict minimum-interval request pacing for {@linkcode APIClient}.
|
|
6
|
+
*
|
|
7
|
+
* Lifted verbatim (modulo the SEC-specific rate clamp, which now lives at the SEC client's own call
|
|
8
|
+
* site) from `98c4dda1:filer/sdk/sec-client.ts`, where the design was settled over two review rounds
|
|
9
|
+
* and verified across eight arrival shapes — fan-out, interleaved, serial-plus-fanout, multi-burst,
|
|
10
|
+
* mid-refill, idle-then-burst, and a 60-call run at 50/s — under an injected clock.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import { type ClockLike, systemClock } from "./clock.ts"
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* A strict-interval request pacer: grants are spaced AT LEAST `intervalMs` apart, with NO burst allowance beyond the
|
|
17
|
+
* very first grant. {@linkcode RequestPacer.acquire} resolves immediately for the first call after construction (or
|
|
18
|
+
* after any idle gap), and every call within one interval of the previous grant waits out the remainder of it.
|
|
19
|
+
*
|
|
20
|
+
* WHY NOT A TOKEN BUCKET: a token bucket with capacity C admits up to `C + rate * 1s` requests within any sliding
|
|
21
|
+
* one-second window — there is NO non-zero capacity that honors a FLAT rate cap, only an average one. The bucket this
|
|
22
|
+
* replaced started full (a one-time startup burst, by design) but ALSO refilled to full after any idle gap, so a fresh
|
|
23
|
+
* burst recurred every time a crawl paused and resumed — measured at 20 grants inside one 1000ms window against a 10/s
|
|
24
|
+
* ceiling (2x). Upstreams that publish a flat rate (SEC EDGAR's 10 req/s, verified enforced) and actively police it
|
|
25
|
+
* need the FLAT guarantee, at the cost of the first-call-of-a-burst latency a bucket would have avoided.
|
|
26
|
+
*
|
|
27
|
+
* FAIRNESS (deliberately not addressed): under concurrent contention (N callers racing `acquire()` in the same
|
|
28
|
+
* synchronous turn), grants are issued in whatever order the synchronous reservation happens to run in. This never
|
|
29
|
+
* affects the RATE — every grant is still exactly `intervalMs` after the last — only which specific caller waits how
|
|
30
|
+
* long under backlog. A caller needing FIFO fairness would need a real queue on top of this.
|
|
31
|
+
*/
|
|
32
|
+
export class RequestPacer {
|
|
33
|
+
readonly #intervalMs: number
|
|
34
|
+
readonly #clock: ClockLike
|
|
35
|
+
#nextGrantAt: number
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* @param intervalMs Minimum milliseconds between two grants. Values `<= 0` are rejected — a zero-interval pacer would
|
|
39
|
+
* never actually pace, and silently accepting one would make a misconfigured caller look throttled when it isn't.
|
|
40
|
+
* @param clock Time source. Defaults to {@linkcode systemClock}.
|
|
41
|
+
*/
|
|
42
|
+
constructor(intervalMs: number, clock: ClockLike = systemClock) {
|
|
43
|
+
if (!Number.isFinite(intervalMs) || intervalMs <= 0) {
|
|
44
|
+
throw new RangeError(
|
|
45
|
+
`RequestPacer: intervalMs must be a finite number greater than 0 (received ${intervalMs}). A pacer with a ` +
|
|
46
|
+
"zero or non-finite interval cannot enforce a rate; construct one only when you actually want pacing."
|
|
47
|
+
)
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
this.#intervalMs = intervalMs
|
|
51
|
+
this.#clock = clock
|
|
52
|
+
this.#nextGrantAt = clock.now()
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* The configured minimum spacing between grants, in milliseconds.
|
|
57
|
+
*/
|
|
58
|
+
public get intervalMs(): number {
|
|
59
|
+
return this.#intervalMs
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* Resolve once this call's turn comes up: immediately for the first call (or after any idle gap), or exactly
|
|
64
|
+
* `intervalMs` after the previous grant otherwise.
|
|
65
|
+
*
|
|
66
|
+
* The grant time is reserved SYNCHRONOUSLY, before any `await` — `#nextGrantAt` is read AND bumped in the same
|
|
67
|
+
* synchronous step that computes this call's own wait. This is load-bearing, not cosmetic: moving the `#nextGrantAt`
|
|
68
|
+
* update to after the `await` (i.e. "compute the wait, sleep, then update state") reopens the concurrency bug this
|
|
69
|
+
* pacer exists to close — N callers invoked in the same synchronous turn would all read the SAME stale `#nextGrantAt`
|
|
70
|
+
* before any of them updates it, compute the SAME wait, and all be released together instead of one interval apart.
|
|
71
|
+
*
|
|
72
|
+
* `Math.max(#nextGrantAt, now)` is equally load-bearing: without it, a long idle gap leaves `#nextGrantAt` stuck in
|
|
73
|
+
* the past, and every call after the idle would compute a negative/zero wait forever (the increment-by-one-interval
|
|
74
|
+
* never catches up to a `now` that's run far ahead) — pacing would silently stop working after any idle period.
|
|
75
|
+
*
|
|
76
|
+
* Both are mutation-proved in `pacer.test.ts`.
|
|
77
|
+
*
|
|
78
|
+
* REAL-CLOCK CAVEAT, measured rather than assumed: the guarantee is on the CLOCK's timeline. Grant instants are
|
|
79
|
+
* scheduled exactly `intervalMs` apart, but the continuation that actually issues the request runs whenever the event
|
|
80
|
+
* loop gets to it, which on real timers is 0-2ms after the deadline. A grant that lands 1ms late shifts toward the
|
|
81
|
+
* following window, so a sliding-second count over the OBSERVED dispatch times reads 11 rather than 10 at a 100ms
|
|
82
|
+
* interval (measured 3/3 runs of a 40-call fan-out; the preceding second correspondingly holds 9, and the long-run
|
|
83
|
+
* rate is exactly at the cap). A caller that needs a hard sliding-window ceiling with no jitter headroom should pace
|
|
84
|
+
* fractionally under the published rate rather than exactly at it.
|
|
85
|
+
*/
|
|
86
|
+
public async acquire(): Promise<void> {
|
|
87
|
+
const now = this.#clock.now()
|
|
88
|
+
const grantAt = Math.max(this.#nextGrantAt, now)
|
|
89
|
+
|
|
90
|
+
this.#nextGrantAt = grantAt + this.#intervalMs
|
|
91
|
+
|
|
92
|
+
const waitMs = grantAt - now
|
|
93
|
+
|
|
94
|
+
if (waitMs > 0) {
|
|
95
|
+
await this.#clock.sleep(Math.ceil(waitMs))
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
}
|
package/api/responses.ts
CHANGED
|
@@ -7,9 +7,10 @@
|
|
|
7
7
|
*/
|
|
8
8
|
|
|
9
9
|
import { AxiosError, HttpStatusCode, isAxiosError } from "axios"
|
|
10
|
+
import type { StatusCodes } from "http-status-codes"
|
|
10
11
|
|
|
11
12
|
import { ResourceError } from "../errors/schema.ts"
|
|
12
|
-
import {
|
|
13
|
+
import { isRetryableStatus } from "./retry.ts"
|
|
13
14
|
|
|
14
15
|
/**
|
|
15
16
|
* A response container, wrapping the actual response body.
|
|
@@ -78,61 +79,243 @@ export function pluckResponseData<Body>(input: ResponseContainer<Body> | Body):
|
|
|
78
79
|
return body as ExtractResponseBodyData<Body>
|
|
79
80
|
}
|
|
80
81
|
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
82
|
+
/**
|
|
83
|
+
* The `kind` component of a {@linkcode ResourceError}'s `(source, kind, reason)` URN, as produced by
|
|
84
|
+
* {@linkcode delegateAxiosError}. This is the axis {@linkcode isTransientResourceError} branches on, so a caller never
|
|
85
|
+
* has to pattern-match an error message.
|
|
86
|
+
*/
|
|
87
|
+
export const ResourceErrorKind = {
|
|
88
|
+
/**
|
|
89
|
+
* The request never reached an HTTP response: a connect failure, a DNS failure, a timeout, or a body read that died
|
|
90
|
+
* mid-transfer.
|
|
91
|
+
*/
|
|
92
|
+
Network: "network",
|
|
93
|
+
/**
|
|
94
|
+
* An HTTP response came back and carried a failing status.
|
|
95
|
+
*/
|
|
96
|
+
Response: "response",
|
|
97
|
+
/**
|
|
98
|
+
* The request was rejected before (or independently of) the network — a caller-initiated cancel, a malformed config.
|
|
99
|
+
* Never transient: re-issuing the identical request can only fail identically.
|
|
100
|
+
*/
|
|
101
|
+
Request: "request",
|
|
102
|
+
/**
|
|
103
|
+
* A response arrived with a SUCCESS status, but its body could not be decoded into the requested type — the classic
|
|
104
|
+
* case being an upstream that serves an HTML error page under a 200.
|
|
105
|
+
*
|
|
106
|
+
* Never transient, deliberately: retrying an unchanged bad body cannot help, and a client that treated this as
|
|
107
|
+
* retryable would spend its whole attempt budget re-downloading the same broken payload.
|
|
108
|
+
*/
|
|
109
|
+
Payload: "payload",
|
|
110
|
+
} as const
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* The `kind` component of a {@linkcode ResourceError}'s URN.
|
|
114
|
+
*/
|
|
115
|
+
export type ResourceErrorKind = (typeof ResourceErrorKind)[keyof typeof ResourceErrorKind]
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* The `source` component every URN in this module carries — the machinery that produced the failure.
|
|
119
|
+
*/
|
|
120
|
+
const RESOURCE_ERROR_SOURCE = "axios"
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* The URN component separator {@linkcode ResourceError} joins segments with.
|
|
124
|
+
*/
|
|
125
|
+
const URN_SEPARATOR = ":"
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* The `kind` component of `error`'s URN, or `null` when it isn't a {@linkcode ResourceError} carrying one.
|
|
129
|
+
*
|
|
130
|
+
* Exposed so a caller can assert on the taxonomy directly (`kind === ResourceErrorKind.Network`) instead of splitting
|
|
131
|
+
* the URN — or, worse, matching on `message` prose — at the call site.
|
|
132
|
+
*/
|
|
133
|
+
export function resourceErrorKind(error: unknown): ResourceErrorKind | null {
|
|
134
|
+
if (!(error instanceof ResourceError)) return null
|
|
135
|
+
|
|
136
|
+
const [, kind] = error.name.split(URN_SEPARATOR)
|
|
137
|
+
|
|
138
|
+
switch (kind) {
|
|
139
|
+
case ResourceErrorKind.Network:
|
|
140
|
+
case ResourceErrorKind.Response:
|
|
141
|
+
case ResourceErrorKind.Request:
|
|
142
|
+
case ResourceErrorKind.Payload:
|
|
143
|
+
return kind
|
|
144
|
+
default:
|
|
145
|
+
return null
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/**
|
|
150
|
+
* Whether `error` is the kind of failure a caller should REQUEUE rather than give up on — every network-class failure
|
|
151
|
+
* (connect, DNS, timeout, mid-transfer drop) and every transient HTTP status (408/429/5xx).
|
|
152
|
+
*
|
|
153
|
+
* This stays `true` even after a client exhausted its OWN bounded attempts: the client's ceiling is a statement about
|
|
154
|
+
* one call, while a caller's requeue is a new, separate attempt budget minutes or hours later. Callers branch on this
|
|
155
|
+
* plus {@linkcode ResourceError.status} — 404 to skip, 403 to abort — and never on message text.
|
|
156
|
+
*/
|
|
157
|
+
export function isTransientResourceError(error: unknown): boolean {
|
|
158
|
+
if (!(error instanceof ResourceError)) return false
|
|
159
|
+
|
|
160
|
+
switch (resourceErrorKind(error)) {
|
|
161
|
+
case ResourceErrorKind.Network:
|
|
162
|
+
return true
|
|
163
|
+
case ResourceErrorKind.Response:
|
|
164
|
+
return isRetryableStatus(error.status)
|
|
165
|
+
default:
|
|
166
|
+
return false
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/**
|
|
171
|
+
* Build a {@linkcode ResourceError} carrying the `(source, kind, reason)` URN AND the originating `AxiosError` as its
|
|
172
|
+
* `cause`, so a debugger keeps the full Axios context (config, request, response) that the mapped error summarizes.
|
|
173
|
+
*/
|
|
174
|
+
function taggedResourceError(
|
|
175
|
+
cause: AxiosError,
|
|
176
|
+
status: number,
|
|
177
|
+
message: string,
|
|
178
|
+
kind: ResourceErrorKind,
|
|
179
|
+
reason: string
|
|
180
|
+
): ResourceError {
|
|
181
|
+
const resourceError = ResourceError.from(status as StatusCodes, message, RESOURCE_ERROR_SOURCE, kind, reason)
|
|
182
|
+
|
|
183
|
+
resourceError.cause = cause
|
|
184
|
+
|
|
185
|
+
return resourceError
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/**
|
|
189
|
+
* The `reason` component for a failing HTTP status, chosen so the common branches a caller cares about are nameable
|
|
190
|
+
* without re-deriving them from the number.
|
|
191
|
+
*/
|
|
192
|
+
function responseReason(status: number): string {
|
|
193
|
+
switch (status) {
|
|
194
|
+
case HttpStatusCode.Unauthorized:
|
|
195
|
+
return "unauthorized"
|
|
196
|
+
case HttpStatusCode.Forbidden:
|
|
197
|
+
return "forbidden"
|
|
198
|
+
case HttpStatusCode.NotFound:
|
|
199
|
+
return "not-found"
|
|
200
|
+
case HttpStatusCode.TooManyRequests:
|
|
201
|
+
return "rate-limited"
|
|
202
|
+
default:
|
|
203
|
+
return isRetryableStatus(status) ? "server-error" : "status"
|
|
204
|
+
}
|
|
89
205
|
}
|
|
90
206
|
|
|
91
207
|
/**
|
|
92
208
|
* Delegate Axios errors to an appropriate error handler.
|
|
93
209
|
*
|
|
210
|
+
* ALWAYS throws — every failure past this point is a {@linkcode ResourceError} carrying a numeric `status`, a `(source,
|
|
211
|
+
* kind, reason)` URN on `name`, and the originating `AxiosError` on `cause`. A non-Axios error is rethrown untouched.
|
|
212
|
+
*
|
|
213
|
+
* WHAT CHANGED, measured rather than recalled — a differential against `98c4dda1` across 18 failure shapes in the exact
|
|
214
|
+
* `TileAPI` configuration found **16 of them changed**, not the two originally claimed:
|
|
215
|
+
*
|
|
216
|
+
* - Every RESPONSELESS failure (`ERR_NETWORK`, `ECONNREFUSED`, `ECONNRESET`, `ECONNABORTED`, `ETIMEDOUT`, `ERR_CANCELED`)
|
|
217
|
+
* used to collapse into a uniform 500; they now split into 503 / 504 / 400 by cause, and `ERR_CANCELED` flips from
|
|
218
|
+
* transient to terminal, which is the point — a caller who cancelled should not requeue.
|
|
219
|
+
* - Every non-401 HTTP status used to rethrow the raw `AxiosError`, so `status`-based branching (404 → skip, 403 → abort)
|
|
220
|
+
* had to reach into `error.response`. 401's own message and URN changed too.
|
|
221
|
+
*
|
|
222
|
+
* The earlier claim that `ECONNABORTED`/`ETIMEDOUT`/`ERR_CANCELED` RESOLVED the chain with `undefined` was wrong FOR
|
|
223
|
+
* EVERY SHAPE AXIOS ACTUALLY PRODUCES: the old `if (!response) throw` ran BEFORE that `switch`, and axios never
|
|
224
|
+
* attaches a `response` to a timeout or a cancellation, so a real one threw `axios:response:missing` 500 — a
|
|
225
|
+
* misclassified 500, not a `TypeError` at the caller. Note the `return` arms were not unreachable in general, only
|
|
226
|
+
* unreachable via axios: reaching the `switch` required a response to be PRESENT, and an error carrying both a
|
|
227
|
+
* `response` and `ECONNABORTED` did resolve with `undefined`. Stock adapters never pair those, but this repo's own
|
|
228
|
+
* `axiosLikeError(message, code, config, response)` helper builds that shape in one argument. No regression follows
|
|
229
|
+
* from any of this — the sole call site has no `.catch`, and every shape that rejects now also rejected before.
|
|
230
|
+
*
|
|
94
231
|
* @internal
|
|
95
232
|
*/
|
|
96
|
-
export async function delegateAxiosError(error: unknown): Promise<
|
|
97
|
-
|
|
98
|
-
if (!isAxiosError(error)) throw error
|
|
99
|
-
|
|
100
|
-
const { response, code: networkErrorCode } = error
|
|
101
|
-
|
|
102
|
-
if (networkErrorCode === "ENOTFOUND") {
|
|
103
|
-
const internetReachable = await checkConnectivity()
|
|
104
|
-
|
|
105
|
-
if (!internetReachable)
|
|
106
|
-
throw ResourceError.from(
|
|
107
|
-
500,
|
|
108
|
-
"Could not reach host. Are we connected to the internet?",
|
|
109
|
-
"axios",
|
|
110
|
-
"network",
|
|
111
|
-
"unreachable"
|
|
112
|
-
)
|
|
113
|
-
}
|
|
233
|
+
export async function delegateAxiosError(error: unknown): Promise<never> {
|
|
234
|
+
if (!isAxiosError(error)) throw error
|
|
114
235
|
|
|
115
|
-
|
|
236
|
+
const { response, code: networkErrorCode } = error
|
|
116
237
|
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
}
|
|
238
|
+
if (response) {
|
|
239
|
+
const { status } = response
|
|
120
240
|
|
|
121
|
-
|
|
122
|
-
|
|
241
|
+
// A SUCCESS status that still produced an error means the STATUS was fine and the BODY was not —
|
|
242
|
+
// Axios's `transformResponse` rejecting an unparseable JSON payload, most often. That is a
|
|
243
|
+
// different failure from "the server said 500", and a different retry answer.
|
|
244
|
+
if (status >= HttpStatusCode.Ok && status < HttpStatusCode.MultipleChoices) {
|
|
245
|
+
throw taggedResourceError(
|
|
246
|
+
error,
|
|
247
|
+
HttpStatusCode.BadGateway,
|
|
248
|
+
`Response body could not be decoded (${status} from ${error.config?.url ?? "unknown URL"}): ${error.message}`,
|
|
249
|
+
ResourceErrorKind.Payload,
|
|
250
|
+
"unreadable"
|
|
251
|
+
)
|
|
123
252
|
}
|
|
124
253
|
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
254
|
+
throw taggedResourceError(
|
|
255
|
+
error,
|
|
256
|
+
status,
|
|
257
|
+
`${status} ${response.statusText || ""}`.trim() || `HTTP ${status}`,
|
|
258
|
+
ResourceErrorKind.Response,
|
|
259
|
+
responseReason(status)
|
|
260
|
+
)
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
if (networkErrorCode === AxiosError.ERR_CANCELED) {
|
|
264
|
+
throw taggedResourceError(
|
|
265
|
+
error,
|
|
266
|
+
HttpStatusCode.BadRequest,
|
|
267
|
+
"The request was canceled by its caller.",
|
|
268
|
+
ResourceErrorKind.Request,
|
|
269
|
+
"canceled"
|
|
270
|
+
)
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
if (networkErrorCode === AxiosError.ECONNABORTED || networkErrorCode === AxiosError.ETIMEDOUT) {
|
|
274
|
+
throw taggedResourceError(
|
|
275
|
+
error,
|
|
276
|
+
HttpStatusCode.GatewayTimeout,
|
|
277
|
+
`The request timed out before a response arrived (${error.config?.url ?? "unknown URL"}).`,
|
|
278
|
+
ResourceErrorKind.Network,
|
|
279
|
+
"timeout"
|
|
280
|
+
)
|
|
281
|
+
}
|
|
135
282
|
|
|
136
|
-
|
|
283
|
+
if (networkErrorCode === "ENOTFOUND") {
|
|
284
|
+
// DELIBERATELY NO CONNECTIVITY PROBE. An earlier version issued a live `HEAD` here to word the
|
|
285
|
+
// message as "are we connected to the internet?" rather than "could not resolve host". It cost
|
|
286
|
+
// one unbounded, un-timed-out request per exhausted DNS failure — with a never-settling `fetch`
|
|
287
|
+
// the client never settled at all — and no test could reach it: deleting the whole branch caused
|
|
288
|
+
// 0 of 269 failures, and the hermetic no-live-network harness could not see it either, because
|
|
289
|
+
// the probe swallowed its own synchronously-throwing `fetch` stub into `false`. Making the probe
|
|
290
|
+
// incapable of throwing is exactly what made it invisible to the guard meant to catch it. The
|
|
291
|
+
// classification is identical either way — network-class, transient — so the whole thing bought
|
|
292
|
+
// one message string.
|
|
293
|
+
throw taggedResourceError(
|
|
294
|
+
error,
|
|
295
|
+
HttpStatusCode.ServiceUnavailable,
|
|
296
|
+
`Could not resolve host (${error.config?.url ?? "unknown URL"}).`,
|
|
297
|
+
ResourceErrorKind.Network,
|
|
298
|
+
"unreachable"
|
|
299
|
+
)
|
|
137
300
|
}
|
|
301
|
+
|
|
302
|
+
if (!networkErrorCode) {
|
|
303
|
+
throw taggedResourceError(
|
|
304
|
+
error,
|
|
305
|
+
HttpStatusCode.InternalServerError,
|
|
306
|
+
"Internal Server Error",
|
|
307
|
+
ResourceErrorKind.Response,
|
|
308
|
+
"missing"
|
|
309
|
+
)
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
// Everything left reached no response and wasn't cancelled: a dropped socket, a refused connection,
|
|
313
|
+
// a TLS failure, a body read that died mid-transfer. All network-class, all worth another attempt.
|
|
314
|
+
throw taggedResourceError(
|
|
315
|
+
error,
|
|
316
|
+
HttpStatusCode.ServiceUnavailable,
|
|
317
|
+
`Service Unavailable (${networkErrorCode}): ${error.message}`,
|
|
318
|
+
ResourceErrorKind.Network,
|
|
319
|
+
"unavailable"
|
|
320
|
+
)
|
|
138
321
|
}
|
package/api/retry.ts
ADDED
|
@@ -0,0 +1,227 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @copyright Sister Software
|
|
3
|
+
* @license AGPL-3.0
|
|
4
|
+
* @author Teffen Ellis, et al.
|
|
5
|
+
* @file Bounded retry policy for {@linkcode APIClient} — which failures are worth another attempt, how
|
|
6
|
+
* long to wait, and the hard ceiling on both.
|
|
7
|
+
*
|
|
8
|
+
* Lifted from `98c4dda1:filer/sdk/sec-client.ts`, where the `Retry-After` handling (the HTTP-date
|
|
9
|
+
* form, the long fallback for a present-but-unparseable value, and the RFC 9110 `1*DIGIT`
|
|
10
|
+
* tightening) was settled over two review rounds. The classifier is the same taxonomy that client
|
|
11
|
+
* used, restated against Axios's error shape rather than a raw `Response`.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import { AxiosError, isAxiosError } from "axios"
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Rate limited — retryable, the server is asking us to back off.
|
|
18
|
+
*/
|
|
19
|
+
const HTTP_TOO_MANY_REQUESTS = 429
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* The request took too long at the origin — retryable.
|
|
23
|
+
*/
|
|
24
|
+
const HTTP_REQUEST_TIMEOUT = 408
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Lowest 5xx status. Server-side failures are retryable.
|
|
28
|
+
*/
|
|
29
|
+
const HTTP_SERVER_ERROR_MIN = 500
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Highest 5xx status.
|
|
33
|
+
*/
|
|
34
|
+
const HTTP_SERVER_ERROR_MAX = 599
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* A hard ceiling on how long a single retry wait is ever allowed to be, REGARDLESS of what a server-supplied
|
|
38
|
+
* `Retry-After` asks for. Honoring `Retry-After` is the right side of most fair-access policies, but an unbounded
|
|
39
|
+
* honor-anything policy would let a pathological (or misconfigured) server hang a bulk crawl for hours; 60s is generous
|
|
40
|
+
* for anything a real rate limiter would plausibly ask for. Also the fallback used when `Retry-After` is PRESENT but
|
|
41
|
+
* unparseable — a malformed header is still the server asking us to back off, and guessing LONG is the safe failure
|
|
42
|
+
* mode; guessing short (the exponential default) risks hammering a server that explicitly asked for space.
|
|
43
|
+
*/
|
|
44
|
+
export const MAX_RETRY_AFTER_MS = 60_000
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Attempts a retrying client makes by default (INCLUDING the first) — a stated ceiling, not "until it works."
|
|
48
|
+
*/
|
|
49
|
+
export const DEFAULT_MAX_ATTEMPTS = 3
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Default base delay for the exponential backoff between attempts, in milliseconds.
|
|
53
|
+
*/
|
|
54
|
+
export const DEFAULT_BASE_RETRY_DELAY_MS = 500
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* RFC 9110 §10.2.3: `Retry-After` is either `delay-seconds` (`1*DIGIT` — one or more ASCII digits, no sign, no decimal
|
|
58
|
+
* point, no hex) or an HTTP-date. `Number("0x10")` and `Number("1.5")` both parse as valid JS numbers but are NOT valid
|
|
59
|
+
* `delay-seconds`, so the numeric branch matches the RFC grammar directly instead of delegating to `Number()`.
|
|
60
|
+
*/
|
|
61
|
+
const RETRY_AFTER_DELAY_SECONDS_PATTERN = /^\d+$/
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* A necessary (not sufficient) pre-check before trusting `Date.parse` on the HTTP-date branch: `Date.parse` is FAR more
|
|
65
|
+
* lenient than RFC 9110's HTTP-date grammar and will happily parse plausible-looking garbage — `Date.parse("1.5")`
|
|
66
|
+
* returns a valid timestamp (~Jan 2001, some locale-ish `M.D` reading), which very nearly slipped a bare
|
|
67
|
+
* fractional-seconds typo through as an accepted HTTP-date instead of falling back to the long ceiling. Every valid RFC
|
|
68
|
+
* 9110 HTTP-date form (the preferred IMF-fixdate AND the obsolete RFC 850 form) ends in the literal `GMT`; requiring
|
|
69
|
+
* that suffix rejects `Date.parse`'s stray non-date parses without needing a full HTTP-date grammar implementation.
|
|
70
|
+
*/
|
|
71
|
+
const HTTP_DATE_SUFFIX_PATTERN = /GMT$/
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* How a client should treat one failed attempt.
|
|
75
|
+
*/
|
|
76
|
+
export interface RetryDirective {
|
|
77
|
+
/**
|
|
78
|
+
* Whether THIS CLASS of failure is worth another attempt — `true` for 408/429/5xx and every network-class failure
|
|
79
|
+
* (connect, DNS, timeout, mid-body-transfer drop), `false` for 403/404/other non-transient statuses, a
|
|
80
|
+
* caller-initiated cancel, and a body that failed to decode.
|
|
81
|
+
*/
|
|
82
|
+
retryable: boolean
|
|
83
|
+
/**
|
|
84
|
+
* The server-requested wait derived from a `Retry-After` response header, in milliseconds, or `null` when the header
|
|
85
|
+
* was absent (the caller should fall back to its own exponential backoff).
|
|
86
|
+
*/
|
|
87
|
+
retryAfterMs: number | null
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* Parse a `Retry-After` header value — numeric `delay-seconds` or an HTTP-date, per RFC 9110 — into a clamped wait
|
|
92
|
+
* duration in ms.
|
|
93
|
+
*
|
|
94
|
+
* Returns `null` only when the header is ABSENT. When the header IS present, this always returns a number: the parsed
|
|
95
|
+
* (and {@linkcode MAX_RETRY_AFTER_MS}-clamped) value on success, or `MAX_RETRY_AFTER_MS` itself when the value is
|
|
96
|
+
* present but matches neither valid form — see the constant's docstring for why unparseable fails open toward caution
|
|
97
|
+
* rather than speed.
|
|
98
|
+
*
|
|
99
|
+
* The HTTP-date branch compares against REAL wall-clock time (`Date.now()`), not an injectable clock — an HTTP-date is
|
|
100
|
+
* an absolute calendar timestamp, which only means something relative to the actual current time.
|
|
101
|
+
*/
|
|
102
|
+
export function parseRetryAfterMs(header: string | null | undefined): number | null {
|
|
103
|
+
if (!header) return null
|
|
104
|
+
|
|
105
|
+
const trimmed = header.trim()
|
|
106
|
+
|
|
107
|
+
if (RETRY_AFTER_DELAY_SECONDS_PATTERN.test(trimmed)) {
|
|
108
|
+
return Math.min(Number(trimmed) * 1000, MAX_RETRY_AFTER_MS)
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
if (HTTP_DATE_SUFFIX_PATTERN.test(trimmed)) {
|
|
112
|
+
const dateMs = Date.parse(trimmed)
|
|
113
|
+
|
|
114
|
+
if (!Number.isNaN(dateMs)) {
|
|
115
|
+
return Math.min(Math.max(dateMs - Date.now(), 0), MAX_RETRY_AFTER_MS)
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
return MAX_RETRY_AFTER_MS
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* Whether an HTTP status is worth another attempt: 408 and 429 by name, plus the whole 5xx range. Everything else —
|
|
124
|
+
* every other 4xx, every 2xx/3xx that still produced an error — is terminal.
|
|
125
|
+
*
|
|
126
|
+
* The 4xx exclusion is the load-bearing part, and 403 is why. A 403 from a rate-limited public API means the request
|
|
127
|
+
* failed to identify itself (for SEC EDGAR, a missing or non-descriptive `User-Agent`); it does NOT mean the resource
|
|
128
|
+
* is gone or that this client is banned. Retrying it cannot succeed and burns rate budget on a request that was never
|
|
129
|
+
* going to be served. An earlier revision spelled this out as a redundant `if (status === 403) return false` ahead of
|
|
130
|
+
* the range check — no mutation could kill it, because the range check already excluded 403, so it was removed rather
|
|
131
|
+
* than left as unfalsifiable decoration. The property is proved by mutating this range instead: broadening it to `>=
|
|
132
|
+
* 400` makes the 403 and 404 tests fail.
|
|
133
|
+
*/
|
|
134
|
+
export function isRetryableStatus(status: number): boolean {
|
|
135
|
+
if (status === HTTP_TOO_MANY_REQUESTS || status === HTTP_REQUEST_TIMEOUT) return true
|
|
136
|
+
|
|
137
|
+
return status >= HTTP_SERVER_ERROR_MIN && status <= HTTP_SERVER_ERROR_MAX
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/**
|
|
141
|
+
* Read the `Retry-After` header off an Axios error's response, if it carried one. Axios lower-cases response header
|
|
142
|
+
* names, but `AxiosHeaders` lookups are case-insensitive anyway; the lower-case spelling is used for the plain-object
|
|
143
|
+
* shape a stubbed adapter may return.
|
|
144
|
+
*/
|
|
145
|
+
function retryAfterFrom(error: AxiosError): number | null {
|
|
146
|
+
const headers = error.response?.headers
|
|
147
|
+
|
|
148
|
+
if (!headers) return null
|
|
149
|
+
|
|
150
|
+
const raw = (headers as Record<string, unknown>)["retry-after"] ?? (headers as Record<string, unknown>)["Retry-After"]
|
|
151
|
+
|
|
152
|
+
return typeof raw === "string" || typeof raw === "number" ? parseRetryAfterMs(String(raw)) : null
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/**
|
|
156
|
+
* Classify one failed attempt: is this failure class worth retrying, and did the server name its own backoff?
|
|
157
|
+
*
|
|
158
|
+
* A NETWORK-class failure — a dropped socket, a DNS blip, this attempt's own timeout firing, or a body read that died
|
|
159
|
+
* mid-transfer — is retryable. This is the case a bulk crawler hits most: fetching multi-MB documents, a dropped socket
|
|
160
|
+
* is far more common than a 503, and the standalone SEC client shipped a version that treated it as terminal.
|
|
161
|
+
*
|
|
162
|
+
* A caller-initiated cancel (`ERR_CANCELED`, i.e. the caller's own `AbortSignal` fired) is NOT retryable — the caller
|
|
163
|
+
* asked us to stop, and retrying would defy that. Axios reports its own `timeout` config as `ECONNABORTED`/`ETIMEDOUT`,
|
|
164
|
+
* so the two are distinguishable.
|
|
165
|
+
*/
|
|
166
|
+
export function classifyAxiosFailure(error: unknown): RetryDirective {
|
|
167
|
+
if (!isAxiosError(error)) return { retryable: false, retryAfterMs: null }
|
|
168
|
+
|
|
169
|
+
const retryAfterMs = retryAfterFrom(error)
|
|
170
|
+
|
|
171
|
+
if (error.response) {
|
|
172
|
+
return { retryable: isRetryableStatus(error.response.status), retryAfterMs }
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
// No response at all: a network-class failure, unless the caller cancelled it themselves.
|
|
176
|
+
return { retryable: error.code !== AxiosError.ERR_CANCELED, retryAfterMs }
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/**
|
|
180
|
+
* Retry configuration for {@linkcode APIClient}. Pass `true` to accept every default.
|
|
181
|
+
*
|
|
182
|
+
* Retry is OPT-IN: an `APIClient` constructed without this option makes exactly one attempt, which is what the existing
|
|
183
|
+
* `TileAPI` consumer has always done. Turning it on repo-wide would silently multiply every caller's failure latency.
|
|
184
|
+
*/
|
|
185
|
+
export interface RetryOptions {
|
|
186
|
+
/**
|
|
187
|
+
* Total attempts, INCLUDING the first, before giving up. A stated ceiling, not "until it works". Default
|
|
188
|
+
* {@linkcode DEFAULT_MAX_ATTEMPTS}.
|
|
189
|
+
*/
|
|
190
|
+
maxAttempts?: number
|
|
191
|
+
/**
|
|
192
|
+
* Base delay for the exponential backoff, in milliseconds. Attempt `n`'s wait is `baseDelayMs * 2^(n-1)`, UNLESS the
|
|
193
|
+
* response carried a `Retry-After` header, which is honored instead. Default
|
|
194
|
+
* {@linkcode DEFAULT_BASE_RETRY_DELAY_MS}.
|
|
195
|
+
*/
|
|
196
|
+
baseDelayMs?: number
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/**
|
|
200
|
+
* A fully-resolved retry policy — {@linkcode RetryOptions} with every default filled in.
|
|
201
|
+
*/
|
|
202
|
+
export interface ResolvedRetryPolicy {
|
|
203
|
+
maxAttempts: number
|
|
204
|
+
baseDelayMs: number
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/**
|
|
208
|
+
* Fill in {@linkcode RetryOptions}' defaults. `undefined` (the absent option) resolves to a single attempt — no retry.
|
|
209
|
+
*/
|
|
210
|
+
export function resolveRetryPolicy(options: RetryOptions | boolean | undefined): ResolvedRetryPolicy {
|
|
211
|
+
if (!options) return { maxAttempts: 1, baseDelayMs: DEFAULT_BASE_RETRY_DELAY_MS }
|
|
212
|
+
|
|
213
|
+
const provided = options === true ? {} : options
|
|
214
|
+
|
|
215
|
+
return {
|
|
216
|
+
maxAttempts: Math.max(1, provided.maxAttempts ?? DEFAULT_MAX_ATTEMPTS),
|
|
217
|
+
baseDelayMs: provided.baseDelayMs ?? DEFAULT_BASE_RETRY_DELAY_MS,
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/**
|
|
222
|
+
* The wait before attempt `attempt + 1`, given the directive from attempt `attempt` (1-based). A server-supplied
|
|
223
|
+
* `Retry-After` always wins over the exponential default.
|
|
224
|
+
*/
|
|
225
|
+
export function retryDelayMs(attempt: number, directive: RetryDirective, policy: ResolvedRetryPolicy): number {
|
|
226
|
+
return directive.retryAfterMs ?? policy.baseDelayMs * 2 ** (attempt - 1)
|
|
227
|
+
}
|