@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
@@ -7,7 +7,7 @@
7
7
  */
8
8
  import { AxiosError, HttpStatusCode, isAxiosError } from "axios";
9
9
  import { ResourceError } from "../errors/schema.js";
10
- import { ConsoleLogger } from "../logging/index.js";
10
+ import { isRetryableStatus } from "./retry.js";
11
11
  function isResponseContainer(input) {
12
12
  return typeof input === "object" && input !== null && "data" in input;
13
13
  }
@@ -22,47 +22,173 @@ export function pluckResponseData(input) {
22
22
  return pluckResponseData(body);
23
23
  return body;
24
24
  }
25
- export function checkConnectivity(connectivityURL = "https://connectivitycheck.gstatic.com/generate_204") {
26
- return fetch(connectivityURL, {
27
- method: "HEAD",
28
- })
29
- .then((response) => response.ok)
30
- .catch(() => false);
25
+ /**
26
+ * The `kind` component of a {@linkcode ResourceError}'s `(source, kind, reason)` URN, as produced by
27
+ * {@linkcode delegateAxiosError}. This is the axis {@linkcode isTransientResourceError} branches on, so a caller never
28
+ * has to pattern-match an error message.
29
+ */
30
+ export const ResourceErrorKind = {
31
+ /**
32
+ * The request never reached an HTTP response: a connect failure, a DNS failure, a timeout, or a body read that died
33
+ * mid-transfer.
34
+ */
35
+ Network: "network",
36
+ /**
37
+ * An HTTP response came back and carried a failing status.
38
+ */
39
+ Response: "response",
40
+ /**
41
+ * The request was rejected before (or independently of) the network — a caller-initiated cancel, a malformed config.
42
+ * Never transient: re-issuing the identical request can only fail identically.
43
+ */
44
+ Request: "request",
45
+ /**
46
+ * A response arrived with a SUCCESS status, but its body could not be decoded into the requested type — the classic
47
+ * case being an upstream that serves an HTML error page under a 200.
48
+ *
49
+ * Never transient, deliberately: retrying an unchanged bad body cannot help, and a client that treated this as
50
+ * retryable would spend its whole attempt budget re-downloading the same broken payload.
51
+ */
52
+ Payload: "payload",
53
+ };
54
+ /**
55
+ * The `source` component every URN in this module carries — the machinery that produced the failure.
56
+ */
57
+ const RESOURCE_ERROR_SOURCE = "axios";
58
+ /**
59
+ * The URN component separator {@linkcode ResourceError} joins segments with.
60
+ */
61
+ const URN_SEPARATOR = ":";
62
+ /**
63
+ * The `kind` component of `error`'s URN, or `null` when it isn't a {@linkcode ResourceError} carrying one.
64
+ *
65
+ * Exposed so a caller can assert on the taxonomy directly (`kind === ResourceErrorKind.Network`) instead of splitting
66
+ * the URN — or, worse, matching on `message` prose — at the call site.
67
+ */
68
+ export function resourceErrorKind(error) {
69
+ if (!(error instanceof ResourceError))
70
+ return null;
71
+ const [, kind] = error.name.split(URN_SEPARATOR);
72
+ switch (kind) {
73
+ case ResourceErrorKind.Network:
74
+ case ResourceErrorKind.Response:
75
+ case ResourceErrorKind.Request:
76
+ case ResourceErrorKind.Payload:
77
+ return kind;
78
+ default:
79
+ return null;
80
+ }
81
+ }
82
+ /**
83
+ * Whether `error` is the kind of failure a caller should REQUEUE rather than give up on — every network-class failure
84
+ * (connect, DNS, timeout, mid-transfer drop) and every transient HTTP status (408/429/5xx).
85
+ *
86
+ * This stays `true` even after a client exhausted its OWN bounded attempts: the client's ceiling is a statement about
87
+ * one call, while a caller's requeue is a new, separate attempt budget minutes or hours later. Callers branch on this
88
+ * plus {@linkcode ResourceError.status} — 404 to skip, 403 to abort — and never on message text.
89
+ */
90
+ export function isTransientResourceError(error) {
91
+ if (!(error instanceof ResourceError))
92
+ return false;
93
+ switch (resourceErrorKind(error)) {
94
+ case ResourceErrorKind.Network:
95
+ return true;
96
+ case ResourceErrorKind.Response:
97
+ return isRetryableStatus(error.status);
98
+ default:
99
+ return false;
100
+ }
101
+ }
102
+ /**
103
+ * Build a {@linkcode ResourceError} carrying the `(source, kind, reason)` URN AND the originating `AxiosError` as its
104
+ * `cause`, so a debugger keeps the full Axios context (config, request, response) that the mapped error summarizes.
105
+ */
106
+ function taggedResourceError(cause, status, message, kind, reason) {
107
+ const resourceError = ResourceError.from(status, message, RESOURCE_ERROR_SOURCE, kind, reason);
108
+ resourceError.cause = cause;
109
+ return resourceError;
110
+ }
111
+ /**
112
+ * The `reason` component for a failing HTTP status, chosen so the common branches a caller cares about are nameable
113
+ * without re-deriving them from the number.
114
+ */
115
+ function responseReason(status) {
116
+ switch (status) {
117
+ case HttpStatusCode.Unauthorized:
118
+ return "unauthorized";
119
+ case HttpStatusCode.Forbidden:
120
+ return "forbidden";
121
+ case HttpStatusCode.NotFound:
122
+ return "not-found";
123
+ case HttpStatusCode.TooManyRequests:
124
+ return "rate-limited";
125
+ default:
126
+ return isRetryableStatus(status) ? "server-error" : "status";
127
+ }
31
128
  }
32
129
  /**
33
130
  * Delegate Axios errors to an appropriate error handler.
34
131
  *
132
+ * ALWAYS throws — every failure past this point is a {@linkcode ResourceError} carrying a numeric `status`, a `(source,
133
+ * kind, reason)` URN on `name`, and the originating `AxiosError` on `cause`. A non-Axios error is rethrown untouched.
134
+ *
135
+ * WHAT CHANGED, measured rather than recalled — a differential against `98c4dda1` across 18 failure shapes in the exact
136
+ * `TileAPI` configuration found **16 of them changed**, not the two originally claimed:
137
+ *
138
+ * - Every RESPONSELESS failure (`ERR_NETWORK`, `ECONNREFUSED`, `ECONNRESET`, `ECONNABORTED`, `ETIMEDOUT`, `ERR_CANCELED`)
139
+ * used to collapse into a uniform 500; they now split into 503 / 504 / 400 by cause, and `ERR_CANCELED` flips from
140
+ * transient to terminal, which is the point — a caller who cancelled should not requeue.
141
+ * - Every non-401 HTTP status used to rethrow the raw `AxiosError`, so `status`-based branching (404 → skip, 403 → abort)
142
+ * had to reach into `error.response`. 401's own message and URN changed too.
143
+ *
144
+ * The earlier claim that `ECONNABORTED`/`ETIMEDOUT`/`ERR_CANCELED` RESOLVED the chain with `undefined` was wrong FOR
145
+ * EVERY SHAPE AXIOS ACTUALLY PRODUCES: the old `if (!response) throw` ran BEFORE that `switch`, and axios never
146
+ * attaches a `response` to a timeout or a cancellation, so a real one threw `axios:response:missing` 500 — a
147
+ * misclassified 500, not a `TypeError` at the caller. Note the `return` arms were not unreachable in general, only
148
+ * unreachable via axios: reaching the `switch` required a response to be PRESENT, and an error carrying both a
149
+ * `response` and `ECONNABORTED` did resolve with `undefined`. Stock adapters never pair those, but this repo's own
150
+ * `axiosLikeError(message, code, config, response)` helper builds that shape in one argument. No regression follows
151
+ * from any of this — the sole call site has no `.catch`, and every shape that rejects now also rejected before.
152
+ *
35
153
  * @internal
36
154
  */
37
155
  export async function delegateAxiosError(error) {
38
- {
39
- if (!isAxiosError(error))
40
- throw error;
41
- const { response, code: networkErrorCode } = error;
42
- if (networkErrorCode === "ENOTFOUND") {
43
- const internetReachable = await checkConnectivity();
44
- if (!internetReachable)
45
- throw ResourceError.from(500, "Could not reach host. Are we connected to the internet?", "axios", "network", "unreachable");
46
- }
47
- if (!response)
48
- throw ResourceError.from(500, "Internal Server Error", "axios", "response", "missing");
49
- if (response.status === HttpStatusCode.Unauthorized) {
50
- throw ResourceError.from(401, "Unauthorized");
51
- }
52
- if (!networkErrorCode) {
53
- throw ResourceError.from(500, "Internal Server Error", "axios", "code", "missing");
54
- }
55
- switch (networkErrorCode) {
56
- case AxiosError.ERR_NETWORK:
57
- throw ResourceError.from(503, "Service Unavailable");
58
- case AxiosError.ERR_CANCELED:
59
- case AxiosError.ECONNABORTED:
60
- case AxiosError.ETIMEDOUT:
61
- return;
62
- default:
63
- ConsoleLogger.warn(`Unhandled network error: ${networkErrorCode}`);
64
- }
156
+ if (!isAxiosError(error))
65
157
  throw error;
158
+ const { response, code: networkErrorCode } = error;
159
+ if (response) {
160
+ const { status } = response;
161
+ // A SUCCESS status that still produced an error means the STATUS was fine and the BODY was not —
162
+ // Axios's `transformResponse` rejecting an unparseable JSON payload, most often. That is a
163
+ // different failure from "the server said 500", and a different retry answer.
164
+ if (status >= HttpStatusCode.Ok && status < HttpStatusCode.MultipleChoices) {
165
+ throw taggedResourceError(error, HttpStatusCode.BadGateway, `Response body could not be decoded (${status} from ${error.config?.url ?? "unknown URL"}): ${error.message}`, ResourceErrorKind.Payload, "unreadable");
166
+ }
167
+ throw taggedResourceError(error, status, `${status} ${response.statusText || ""}`.trim() || `HTTP ${status}`, ResourceErrorKind.Response, responseReason(status));
168
+ }
169
+ if (networkErrorCode === AxiosError.ERR_CANCELED) {
170
+ throw taggedResourceError(error, HttpStatusCode.BadRequest, "The request was canceled by its caller.", ResourceErrorKind.Request, "canceled");
171
+ }
172
+ if (networkErrorCode === AxiosError.ECONNABORTED || networkErrorCode === AxiosError.ETIMEDOUT) {
173
+ throw taggedResourceError(error, HttpStatusCode.GatewayTimeout, `The request timed out before a response arrived (${error.config?.url ?? "unknown URL"}).`, ResourceErrorKind.Network, "timeout");
174
+ }
175
+ if (networkErrorCode === "ENOTFOUND") {
176
+ // DELIBERATELY NO CONNECTIVITY PROBE. An earlier version issued a live `HEAD` here to word the
177
+ // message as "are we connected to the internet?" rather than "could not resolve host". It cost
178
+ // one unbounded, un-timed-out request per exhausted DNS failure — with a never-settling `fetch`
179
+ // the client never settled at all — and no test could reach it: deleting the whole branch caused
180
+ // 0 of 269 failures, and the hermetic no-live-network harness could not see it either, because
181
+ // the probe swallowed its own synchronously-throwing `fetch` stub into `false`. Making the probe
182
+ // incapable of throwing is exactly what made it invisible to the guard meant to catch it. The
183
+ // classification is identical either way — network-class, transient — so the whole thing bought
184
+ // one message string.
185
+ throw taggedResourceError(error, HttpStatusCode.ServiceUnavailable, `Could not resolve host (${error.config?.url ?? "unknown URL"}).`, ResourceErrorKind.Network, "unreachable");
186
+ }
187
+ if (!networkErrorCode) {
188
+ throw taggedResourceError(error, HttpStatusCode.InternalServerError, "Internal Server Error", ResourceErrorKind.Response, "missing");
66
189
  }
190
+ // Everything left reached no response and wasn't cancelled: a dropped socket, a refused connection,
191
+ // a TLS failure, a body read that died mid-transfer. All network-class, all worth another attempt.
192
+ throw taggedResourceError(error, HttpStatusCode.ServiceUnavailable, `Service Unavailable (${networkErrorCode}): ${error.message}`, ResourceErrorKind.Network, "unavailable");
67
193
  }
68
194
  //# sourceMappingURL=responses.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"responses.js","sourceRoot":"","sources":["../../api/responses.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,EAAE,UAAU,EAAE,cAAc,EAAE,YAAY,EAAE,MAAM,OAAO,CAAA;AAEhE,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAA;AACnD,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAA;AAuBnD,SAAS,mBAAmB,CAAO,KAAyB;IAC3D,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAI,MAAM,IAAI,KAAK,CAAA;AACtE,CAAC;AAQD,SAAS,iBAAiB,CAAO,KAAqC;IACrE,IAAI,mBAAmB,CAAC,KAAK,CAAC;QAAE,OAAO,KAAK,CAAC,IAAI,CAAA;IAEjD,OAAO,KAAK,CAAA;AACb,CAAC;AAwBD,MAAM,UAAU,iBAAiB,CAAO,KAAqC;IAC5E,MAAM,IAAI,GAAG,iBAAiB,CAAC,KAAK,CAAC,CAAA;IAErC,IAAI,mBAAmB,CAAC,IAAI,CAAC;QAAE,OAAO,iBAAiB,CAAC,IAAI,CAAC,CAAA;IAE7D,OAAO,IAAqC,CAAA;AAC7C,CAAC;AAED,MAAM,UAAU,iBAAiB,CAChC,kBAAgC,oDAAoD;IAEpF,OAAO,KAAK,CAAC,eAAe,EAAE;QAC7B,MAAM,EAAE,MAAM;KACd,CAAC;SACA,IAAI,CAAC,CAAC,QAAQ,EAAE,EAAE,CAAC,QAAQ,CAAC,EAAE,CAAC;SAC/B,KAAK,CAAC,GAAG,EAAE,CAAC,KAAK,CAAC,CAAA;AACrB,CAAC;AAED;;;;GAIG;AACH,MAAM,CAAC,KAAK,UAAU,kBAAkB,CAAC,KA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F,CAAC;IAED,IAAI,gBAAgB,KAAK,UAAU,CAAC,YAAY,IAAI,gBAAgB,KAAK,UAAU,CAAC,SAAS,EAAE,CAAC;QAC/F,MAAM,mBAAmB,CACxB,KAAK,EACL,cAAc,CAAC,cAAc,EAC7B,oDAAoD,KAAK,CAAC,MAAM,EAAE,GAAG,IAAI,aAAa,IAAI,EAC1F,iBAAiB,CAAC,OAAO,EACzB,SAAS,CACT,CAAA;IACF,CAAC;IAED,IAAI,gBAAgB,KAAK,WAAW,EAAE,CAAC;QACtC,+FAA+F;QAC/F,+FAA+F;QAC/F,gGAAgG;QAChG,iGAAiG;QACjG,+FAA+F;QAC/F,iGAAiG;QACjG,8FAA8F;QAC9F,gGAAgG;QAChG,sBAAsB;QACtB,MAAM,mBAAmB,CACxB,KAAK,EACL,cAAc,CAAC,kBAAkB,EACjC,2BAA2B,KAAK,CAAC,MAAM,EAAE,GAAG,IAAI,aAAa,IAAI,EACjE,iBAAiB,CAAC,OAAO,EACzB,aAAa,CACb,CAAA;IACF,CAAC;IAED,IAAI,CAAC,gBAAgB,EAAE,CAAC;QACvB,MAAM,mBAAmB,CACxB,KAAK,EACL,cAAc,CAAC,mBAAmB,EAClC,uBAAuB,EACvB,iBAAiB,CAAC,QAAQ,EAC1B,SAAS,CACT,CAAA;IACF,CAAC;IAED,oGAAoG;IACpG,mGAAmG;IACnG,MAAM,mBAAmB,CACxB,KAAK,EACL,cAAc,CAAC,kBAAkB,EACjC,wBAAwB,gBAAgB,MAAM,KAAK,CAAC,OAAO,EAAE,EAC7D,iBAAiB,CAAC,OAAO,EACzB,aAAa,CACb,CAAA;AACF,CAAC"}
@@ -0,0 +1,119 @@
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
+ * A hard ceiling on how long a single retry wait is ever allowed to be, REGARDLESS of what a server-supplied
15
+ * `Retry-After` asks for. Honoring `Retry-After` is the right side of most fair-access policies, but an unbounded
16
+ * honor-anything policy would let a pathological (or misconfigured) server hang a bulk crawl for hours; 60s is generous
17
+ * for anything a real rate limiter would plausibly ask for. Also the fallback used when `Retry-After` is PRESENT but
18
+ * unparseable — a malformed header is still the server asking us to back off, and guessing LONG is the safe failure
19
+ * mode; guessing short (the exponential default) risks hammering a server that explicitly asked for space.
20
+ */
21
+ export declare const MAX_RETRY_AFTER_MS = 60000;
22
+ /**
23
+ * Attempts a retrying client makes by default (INCLUDING the first) — a stated ceiling, not "until it works."
24
+ */
25
+ export declare const DEFAULT_MAX_ATTEMPTS = 3;
26
+ /**
27
+ * Default base delay for the exponential backoff between attempts, in milliseconds.
28
+ */
29
+ export declare const DEFAULT_BASE_RETRY_DELAY_MS = 500;
30
+ /**
31
+ * How a client should treat one failed attempt.
32
+ */
33
+ export interface RetryDirective {
34
+ /**
35
+ * Whether THIS CLASS of failure is worth another attempt — `true` for 408/429/5xx and every network-class failure
36
+ * (connect, DNS, timeout, mid-body-transfer drop), `false` for 403/404/other non-transient statuses, a
37
+ * caller-initiated cancel, and a body that failed to decode.
38
+ */
39
+ retryable: boolean;
40
+ /**
41
+ * The server-requested wait derived from a `Retry-After` response header, in milliseconds, or `null` when the header
42
+ * was absent (the caller should fall back to its own exponential backoff).
43
+ */
44
+ retryAfterMs: number | null;
45
+ }
46
+ /**
47
+ * Parse a `Retry-After` header value — numeric `delay-seconds` or an HTTP-date, per RFC 9110 — into a clamped wait
48
+ * duration in ms.
49
+ *
50
+ * Returns `null` only when the header is ABSENT. When the header IS present, this always returns a number: the parsed
51
+ * (and {@linkcode MAX_RETRY_AFTER_MS}-clamped) value on success, or `MAX_RETRY_AFTER_MS` itself when the value is
52
+ * present but matches neither valid form — see the constant's docstring for why unparseable fails open toward caution
53
+ * rather than speed.
54
+ *
55
+ * The HTTP-date branch compares against REAL wall-clock time (`Date.now()`), not an injectable clock — an HTTP-date is
56
+ * an absolute calendar timestamp, which only means something relative to the actual current time.
57
+ */
58
+ export declare function parseRetryAfterMs(header: string | null | undefined): number | null;
59
+ /**
60
+ * Whether an HTTP status is worth another attempt: 408 and 429 by name, plus the whole 5xx range. Everything else —
61
+ * every other 4xx, every 2xx/3xx that still produced an error — is terminal.
62
+ *
63
+ * The 4xx exclusion is the load-bearing part, and 403 is why. A 403 from a rate-limited public API means the request
64
+ * failed to identify itself (for SEC EDGAR, a missing or non-descriptive `User-Agent`); it does NOT mean the resource
65
+ * is gone or that this client is banned. Retrying it cannot succeed and burns rate budget on a request that was never
66
+ * going to be served. An earlier revision spelled this out as a redundant `if (status === 403) return false` ahead of
67
+ * the range check — no mutation could kill it, because the range check already excluded 403, so it was removed rather
68
+ * than left as unfalsifiable decoration. The property is proved by mutating this range instead: broadening it to `>=
69
+ * 400` makes the 403 and 404 tests fail.
70
+ */
71
+ export declare function isRetryableStatus(status: number): boolean;
72
+ /**
73
+ * Classify one failed attempt: is this failure class worth retrying, and did the server name its own backoff?
74
+ *
75
+ * A NETWORK-class failure — a dropped socket, a DNS blip, this attempt's own timeout firing, or a body read that died
76
+ * mid-transfer — is retryable. This is the case a bulk crawler hits most: fetching multi-MB documents, a dropped socket
77
+ * is far more common than a 503, and the standalone SEC client shipped a version that treated it as terminal.
78
+ *
79
+ * A caller-initiated cancel (`ERR_CANCELED`, i.e. the caller's own `AbortSignal` fired) is NOT retryable — the caller
80
+ * asked us to stop, and retrying would defy that. Axios reports its own `timeout` config as `ECONNABORTED`/`ETIMEDOUT`,
81
+ * so the two are distinguishable.
82
+ */
83
+ export declare function classifyAxiosFailure(error: unknown): RetryDirective;
84
+ /**
85
+ * Retry configuration for {@linkcode APIClient}. Pass `true` to accept every default.
86
+ *
87
+ * Retry is OPT-IN: an `APIClient` constructed without this option makes exactly one attempt, which is what the existing
88
+ * `TileAPI` consumer has always done. Turning it on repo-wide would silently multiply every caller's failure latency.
89
+ */
90
+ export interface RetryOptions {
91
+ /**
92
+ * Total attempts, INCLUDING the first, before giving up. A stated ceiling, not "until it works". Default
93
+ * {@linkcode DEFAULT_MAX_ATTEMPTS}.
94
+ */
95
+ maxAttempts?: number;
96
+ /**
97
+ * Base delay for the exponential backoff, in milliseconds. Attempt `n`'s wait is `baseDelayMs * 2^(n-1)`, UNLESS the
98
+ * response carried a `Retry-After` header, which is honored instead. Default
99
+ * {@linkcode DEFAULT_BASE_RETRY_DELAY_MS}.
100
+ */
101
+ baseDelayMs?: number;
102
+ }
103
+ /**
104
+ * A fully-resolved retry policy — {@linkcode RetryOptions} with every default filled in.
105
+ */
106
+ export interface ResolvedRetryPolicy {
107
+ maxAttempts: number;
108
+ baseDelayMs: number;
109
+ }
110
+ /**
111
+ * Fill in {@linkcode RetryOptions}' defaults. `undefined` (the absent option) resolves to a single attempt — no retry.
112
+ */
113
+ export declare function resolveRetryPolicy(options: RetryOptions | boolean | undefined): ResolvedRetryPolicy;
114
+ /**
115
+ * The wait before attempt `attempt + 1`, given the directive from attempt `attempt` (1-based). A server-supplied
116
+ * `Retry-After` always wins over the exponential default.
117
+ */
118
+ export declare function retryDelayMs(attempt: number, directive: RetryDirective, policy: ResolvedRetryPolicy): number;
119
+ //# sourceMappingURL=retry.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"retry.d.ts","sourceRoot":"","sources":["../../api/retry.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAwBH;;;;;;;GAOG;AACH,eAAO,MAAM,kBAAkB,QAAS,CAAA;AAExC;;GAEG;AACH,eAAO,MAAM,oBAAoB,IAAI,CAAA;AAErC;;GAEG;AACH,eAAO,MAAM,2BAA2B,MAAM,CAAA;AAmB9C;;GAEG;AACH,MAAM,WAAW,cAAc;IAC9B;;;;OAIG;IACH,SAAS,EAAE,OAAO,CAAA;IAClB;;;OAGG;IACH,YAAY,EAAE,MAAM,GAAG,IAAI,CAAA;CAC3B;AAED;;;;;;;;;;;GAWG;AACH,wBAAgB,iBAAiB,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,GAAG,MAAM,GAAG,IAAI,CAkBlF;AAED;;;;;;;;;;;GAWG;AACH,wBAAgB,iBAAiB,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAIzD;AAiBD;;;;;;;;;;GAUG;AACH,wBAAgB,oBAAoB,CAAC,KAAK,EAAE,OAAO,GAAG,cAAc,CAWnE;AAED;;;;;GAKG;AACH,MAAM,WAAW,YAAY;IAC5B;;;OAGG;IACH,WAAW,CAAC,EAAE,MAAM,CAAA;IACpB;;;;OAIG;IACH,WAAW,CAAC,EAAE,MAAM,CAAA;CACpB;AAED;;GAEG;AACH,MAAM,WAAW,mBAAmB;IACnC,WAAW,EAAE,MAAM,CAAA;IACnB,WAAW,EAAE,MAAM,CAAA;CACnB;AAED;;GAEG;AACH,wBAAgB,kBAAkB,CAAC,OAAO,EAAE,YAAY,GAAG,OAAO,GAAG,SAAS,GAAG,mBAAmB,CASnG;AAED;;;GAGG;AACH,wBAAgB,YAAY,CAAC,OAAO,EAAE,MAAM,EAAE,SAAS,EAAE,cAAc,EAAE,MAAM,EAAE,mBAAmB,GAAG,MAAM,CAE5G"}
@@ -0,0 +1,158 @@
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
+ import { AxiosError, isAxiosError } from "axios";
14
+ /**
15
+ * Rate limited — retryable, the server is asking us to back off.
16
+ */
17
+ const HTTP_TOO_MANY_REQUESTS = 429;
18
+ /**
19
+ * The request took too long at the origin — retryable.
20
+ */
21
+ const HTTP_REQUEST_TIMEOUT = 408;
22
+ /**
23
+ * Lowest 5xx status. Server-side failures are retryable.
24
+ */
25
+ const HTTP_SERVER_ERROR_MIN = 500;
26
+ /**
27
+ * Highest 5xx status.
28
+ */
29
+ const HTTP_SERVER_ERROR_MAX = 599;
30
+ /**
31
+ * A hard ceiling on how long a single retry wait is ever allowed to be, REGARDLESS of what a server-supplied
32
+ * `Retry-After` asks for. Honoring `Retry-After` is the right side of most fair-access policies, but an unbounded
33
+ * honor-anything policy would let a pathological (or misconfigured) server hang a bulk crawl for hours; 60s is generous
34
+ * for anything a real rate limiter would plausibly ask for. Also the fallback used when `Retry-After` is PRESENT but
35
+ * unparseable — a malformed header is still the server asking us to back off, and guessing LONG is the safe failure
36
+ * mode; guessing short (the exponential default) risks hammering a server that explicitly asked for space.
37
+ */
38
+ export const MAX_RETRY_AFTER_MS = 60_000;
39
+ /**
40
+ * Attempts a retrying client makes by default (INCLUDING the first) — a stated ceiling, not "until it works."
41
+ */
42
+ export const DEFAULT_MAX_ATTEMPTS = 3;
43
+ /**
44
+ * Default base delay for the exponential backoff between attempts, in milliseconds.
45
+ */
46
+ export const DEFAULT_BASE_RETRY_DELAY_MS = 500;
47
+ /**
48
+ * RFC 9110 §10.2.3: `Retry-After` is either `delay-seconds` (`1*DIGIT` — one or more ASCII digits, no sign, no decimal
49
+ * point, no hex) or an HTTP-date. `Number("0x10")` and `Number("1.5")` both parse as valid JS numbers but are NOT valid
50
+ * `delay-seconds`, so the numeric branch matches the RFC grammar directly instead of delegating to `Number()`.
51
+ */
52
+ const RETRY_AFTER_DELAY_SECONDS_PATTERN = /^\d+$/;
53
+ /**
54
+ * A necessary (not sufficient) pre-check before trusting `Date.parse` on the HTTP-date branch: `Date.parse` is FAR more
55
+ * lenient than RFC 9110's HTTP-date grammar and will happily parse plausible-looking garbage — `Date.parse("1.5")`
56
+ * returns a valid timestamp (~Jan 2001, some locale-ish `M.D` reading), which very nearly slipped a bare
57
+ * fractional-seconds typo through as an accepted HTTP-date instead of falling back to the long ceiling. Every valid RFC
58
+ * 9110 HTTP-date form (the preferred IMF-fixdate AND the obsolete RFC 850 form) ends in the literal `GMT`; requiring
59
+ * that suffix rejects `Date.parse`'s stray non-date parses without needing a full HTTP-date grammar implementation.
60
+ */
61
+ const HTTP_DATE_SUFFIX_PATTERN = /GMT$/;
62
+ /**
63
+ * Parse a `Retry-After` header value — numeric `delay-seconds` or an HTTP-date, per RFC 9110 — into a clamped wait
64
+ * duration in ms.
65
+ *
66
+ * Returns `null` only when the header is ABSENT. When the header IS present, this always returns a number: the parsed
67
+ * (and {@linkcode MAX_RETRY_AFTER_MS}-clamped) value on success, or `MAX_RETRY_AFTER_MS` itself when the value is
68
+ * present but matches neither valid form — see the constant's docstring for why unparseable fails open toward caution
69
+ * rather than speed.
70
+ *
71
+ * The HTTP-date branch compares against REAL wall-clock time (`Date.now()`), not an injectable clock — an HTTP-date is
72
+ * an absolute calendar timestamp, which only means something relative to the actual current time.
73
+ */
74
+ export function parseRetryAfterMs(header) {
75
+ if (!header)
76
+ return null;
77
+ const trimmed = header.trim();
78
+ if (RETRY_AFTER_DELAY_SECONDS_PATTERN.test(trimmed)) {
79
+ return Math.min(Number(trimmed) * 1000, MAX_RETRY_AFTER_MS);
80
+ }
81
+ if (HTTP_DATE_SUFFIX_PATTERN.test(trimmed)) {
82
+ const dateMs = Date.parse(trimmed);
83
+ if (!Number.isNaN(dateMs)) {
84
+ return Math.min(Math.max(dateMs - Date.now(), 0), MAX_RETRY_AFTER_MS);
85
+ }
86
+ }
87
+ return MAX_RETRY_AFTER_MS;
88
+ }
89
+ /**
90
+ * Whether an HTTP status is worth another attempt: 408 and 429 by name, plus the whole 5xx range. Everything else —
91
+ * every other 4xx, every 2xx/3xx that still produced an error — is terminal.
92
+ *
93
+ * The 4xx exclusion is the load-bearing part, and 403 is why. A 403 from a rate-limited public API means the request
94
+ * failed to identify itself (for SEC EDGAR, a missing or non-descriptive `User-Agent`); it does NOT mean the resource
95
+ * is gone or that this client is banned. Retrying it cannot succeed and burns rate budget on a request that was never
96
+ * going to be served. An earlier revision spelled this out as a redundant `if (status === 403) return false` ahead of
97
+ * the range check — no mutation could kill it, because the range check already excluded 403, so it was removed rather
98
+ * than left as unfalsifiable decoration. The property is proved by mutating this range instead: broadening it to `>=
99
+ * 400` makes the 403 and 404 tests fail.
100
+ */
101
+ export function isRetryableStatus(status) {
102
+ if (status === HTTP_TOO_MANY_REQUESTS || status === HTTP_REQUEST_TIMEOUT)
103
+ return true;
104
+ return status >= HTTP_SERVER_ERROR_MIN && status <= HTTP_SERVER_ERROR_MAX;
105
+ }
106
+ /**
107
+ * Read the `Retry-After` header off an Axios error's response, if it carried one. Axios lower-cases response header
108
+ * names, but `AxiosHeaders` lookups are case-insensitive anyway; the lower-case spelling is used for the plain-object
109
+ * shape a stubbed adapter may return.
110
+ */
111
+ function retryAfterFrom(error) {
112
+ const headers = error.response?.headers;
113
+ if (!headers)
114
+ return null;
115
+ const raw = headers["retry-after"] ?? headers["Retry-After"];
116
+ return typeof raw === "string" || typeof raw === "number" ? parseRetryAfterMs(String(raw)) : null;
117
+ }
118
+ /**
119
+ * Classify one failed attempt: is this failure class worth retrying, and did the server name its own backoff?
120
+ *
121
+ * A NETWORK-class failure — a dropped socket, a DNS blip, this attempt's own timeout firing, or a body read that died
122
+ * mid-transfer — is retryable. This is the case a bulk crawler hits most: fetching multi-MB documents, a dropped socket
123
+ * is far more common than a 503, and the standalone SEC client shipped a version that treated it as terminal.
124
+ *
125
+ * A caller-initiated cancel (`ERR_CANCELED`, i.e. the caller's own `AbortSignal` fired) is NOT retryable — the caller
126
+ * asked us to stop, and retrying would defy that. Axios reports its own `timeout` config as `ECONNABORTED`/`ETIMEDOUT`,
127
+ * so the two are distinguishable.
128
+ */
129
+ export function classifyAxiosFailure(error) {
130
+ if (!isAxiosError(error))
131
+ return { retryable: false, retryAfterMs: null };
132
+ const retryAfterMs = retryAfterFrom(error);
133
+ if (error.response) {
134
+ return { retryable: isRetryableStatus(error.response.status), retryAfterMs };
135
+ }
136
+ // No response at all: a network-class failure, unless the caller cancelled it themselves.
137
+ return { retryable: error.code !== AxiosError.ERR_CANCELED, retryAfterMs };
138
+ }
139
+ /**
140
+ * Fill in {@linkcode RetryOptions}' defaults. `undefined` (the absent option) resolves to a single attempt — no retry.
141
+ */
142
+ export function resolveRetryPolicy(options) {
143
+ if (!options)
144
+ return { maxAttempts: 1, baseDelayMs: DEFAULT_BASE_RETRY_DELAY_MS };
145
+ const provided = options === true ? {} : options;
146
+ return {
147
+ maxAttempts: Math.max(1, provided.maxAttempts ?? DEFAULT_MAX_ATTEMPTS),
148
+ baseDelayMs: provided.baseDelayMs ?? DEFAULT_BASE_RETRY_DELAY_MS,
149
+ };
150
+ }
151
+ /**
152
+ * The wait before attempt `attempt + 1`, given the directive from attempt `attempt` (1-based). A server-supplied
153
+ * `Retry-After` always wins over the exponential default.
154
+ */
155
+ export function retryDelayMs(attempt, directive, policy) {
156
+ return directive.retryAfterMs ?? policy.baseDelayMs * 2 ** (attempt - 1);
157
+ }
158
+ //# sourceMappingURL=retry.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"retry.js","sourceRoot":"","sources":["../../api/retry.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAEH,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,OAAO,CAAA;AAEhD;;GAEG;AACH,MAAM,sBAAsB,GAAG,GAAG,CAAA;AAElC;;GAEG;AACH,MAAM,oBAAoB,GAAG,GAAG,CAAA;AAEhC;;GAEG;AACH,MAAM,qBAAqB,GA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AAI,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,OAAO,CAAA;IAEhD,OAAO;QACN,WAAW,EAAE,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,QAAQ,CAAC,WAAW,IAAI,oBAAoB,CAAC;QACtE,WAAW,EAAE,QAAQ,CAAC,WAAW,IAAI,2BAA2B;KAChE,CAAA;AACF,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,YAAY,CAAC,OAAe,EAAE,SAAyB,EAAE,MAA2B;IACnG,OAAO,SAAS,CAAC,YAAY,IAAI,MAAM,CAAC,WAAW,GAAG,CAAC,IAAI,CAAC,OAAO,GAAG,CAAC,CAAC,CAAA;AACzE,CAAC"}
@@ -0,0 +1,87 @@
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
+ import type { ClockLike } from "./clock.ts";
13
+ /**
14
+ * Run every queued microtask to quiescence. A `setImmediate` is scheduled behind the entire microtask queue, so
15
+ * awaiting one guarantees any in-flight promise chain has settled as far as it can without more real time.
16
+ */
17
+ export declare function drainMicrotasks(): Promise<void>;
18
+ /**
19
+ * A {@linkcode ClockLike} whose `sleep()` bumps `now()` and resolves immediately.
20
+ */
21
+ export interface FakeClock extends ClockLike {
22
+ /**
23
+ * Every `ms` value awaited via `sleep`, in call order.
24
+ */
25
+ sleepCalls: number[];
26
+ /**
27
+ * Advance the clock WITHOUT recording a `sleepCalls` entry — simulates wall-clock time passing between two calls
28
+ * (e.g. "a day later") without the code under test having awaited anything.
29
+ */
30
+ advance(ms: number): void;
31
+ }
32
+ /**
33
+ * A simple, immediately-resolving fake clock. Fine for every SEQUENTIAL assertion (nothing racing the clock), but NOT
34
+ * sufficient for a concurrency test — see {@linkcode VirtualClock}.
35
+ */
36
+ export declare function createFakeClock(startAt?: number): FakeClock;
37
+ /**
38
+ * A virtual-time clock that resolves concurrent `sleep()`s ONE AT A TIME, strictly in deadline order, only when
39
+ * explicitly driven via {@linkcode VirtualClock.advance} — unlike {@linkcode createFakeClock}, which bumps `now()`
40
+ * synchronously the INSTANT `sleep()` is called (fine when nothing else races the clock, but not a faithful model of "N
41
+ * callers all waiting on the same deadline").
42
+ *
43
+ * This fidelity is exactly what a pacing regression needs: a coarser clock that resolves every same-deadline sleeper
44
+ * "at once" cannot distinguish a fixed pacer from a broken one — under such a clock BOTH let a whole cohort through
45
+ * together, because the naive clock's call-time (not wake-time) mutation of `now()` interleaves in a way that masks the
46
+ * bug. Here each pending `sleep()` resolves only when `advance()` reaches its deadline, and the woken continuation
47
+ * (which may register a NEW `sleep()`, pushing its own deadline further out) runs to completion before the next
48
+ * same-deadline sleeper is resolved — reproducing how N real, independent timers settle.
49
+ */
50
+ export declare class VirtualClock implements ClockLike {
51
+ #private;
52
+ readonly sleepCalls: number[];
53
+ now(): number;
54
+ sleep(ms: number): Promise<void>;
55
+ /**
56
+ * Advance virtual time to `now() + ms`, waking every pending `sleep()` due at or before that instant — one at a time,
57
+ * earliest deadline first (ties broken by registration order), draining the microtask queue after each wakeup so the
58
+ * woken continuation runs to quiescence before the next deadline is considered.
59
+ *
60
+ * The drain is a `setImmediate` (a MACROTASK), not a fixed number of `await Promise.resolve()` turns. A woken
61
+ * continuation that runs through a library's own promise chain — Axios's request/response interceptors, say — needs
62
+ * more microtask turns than any hardcoded count, and coming up short lets the clock run ahead of an in-flight
63
+ * dispatch: the request then records a LATER deadline's timestamp, and two dispatches appear to share an instant when
64
+ * they didn't.
65
+ */
66
+ advance(ms: number): Promise<void>;
67
+ /**
68
+ * Drive `work` to completion, jumping virtual time to the next pending deadline whenever the REAL event loop goes
69
+ * idle.
70
+ *
71
+ * {@linkcode advance} alone is not enough once the code under test interleaves virtual sleeps with real asynchrony —
72
+ * a paced client whose gate sits downstream of an on-disk cache spends several real event-loop turns in `readFile`
73
+ * before it ever registers its `sleep()`. A caller that drains once and then advances finds nothing pending, jumps
74
+ * the clock past the deadlines that are registered a moment later, and the test hangs. This polls instead: drain, and
75
+ * if any sleep is pending, advance to the earliest deadline; if none is, yield and look again.
76
+ *
77
+ * Throws rather than hanging when the work neither settles nor schedules anything for {@linkcode MAX_IDLE_TURNS}
78
+ * consecutive turns — a diagnosable failure beats a test-timeout stack trace pointing at the `it()`.
79
+ */
80
+ runUntilSettled<T>(work: Promise<T>): Promise<T>;
81
+ }
82
+ /**
83
+ * The maximum number of `timestamps` falling within any sliding window of `windowMs`, using a trailing half-open window
84
+ * `(anchor - windowMs, anchor]` at each timestamp — the conventional "requests in the last N ms" definition.
85
+ */
86
+ export declare function maxCountInSlidingWindow(timestamps: number[], windowMs: number): number;
87
+ //# sourceMappingURL=test-clocks.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"test-clocks.d.ts","sourceRoot":"","sources":["../../api/test-clocks.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,YAAY,CAAA;AAS3C;;;GAGG;AACH,wBAAgB,eAAe,IAAI,OAAO,CAAC,IAAI,CAAC,CAI/C;AAED;;GAEG;AACH,MAAM,WAAW,SAAU,SAAQ,SAAS;IAC3C;;OAEG;IACH,UAAU,EAAE,MAAM,EAAE,CAAA;IACpB;;;OAGG;IACH,OAAO,CAAC,EAAE,EAAE,MAAM,GAAG,IAAI,CAAA;CACzB;AAED;;;GAGG;AACH,wBAAgB,eAAe,CAAC,OAAO,SAAI,GAAG,SAAS,CAetD;AAED;;;;;;;;;;;;GAYG;AACH,qBAAa,YAAa,YAAW,SAAS;;IAG7C,QAAQ,CAAC,UAAU,EAAE,MAAM,EAAE,CAAK;IAE3B,GAAG,IAAI,MAAM;IAIb,KAAK,CAAC,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAQvC;;;;;;;;;;OAUG;IACU,OAAO,CAAC,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAmB/C;;;;;;;;;;;;OAYG;IACU,eAAe,CAAC,CAAC,EAAE,IAAI,EAAE,OAAO,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC;CA6E7D;AAED;;;GAGG;AACH,wBAAgB,uBAAuB,CAAC,UAAU,EAAE,MAAM,EAAE,EAAE,QAAQ,EAAE,MAAM,GAAG,MAAM,CAUtF"}