@distilled.cloud/core 1.0.0-rc.20 → 1.0.0-rc.21
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/README.md +33 -0
- package/lib/_bundle/aws.js +1 -1
- package/lib/_bundle/aws.js.map +1 -1
- package/lib/_bundle/base.js +2 -2
- package/lib/_bundle/base.js.map +1 -1
- package/lib/_bundle/graphql.js +2 -2
- package/lib/_bundle/graphql.js.map +1 -1
- package/lib/_bundle/grpc.js +2 -1
- package/lib/_bundle/grpc.js.map +1 -1
- package/lib/_bundle/rest.js +1 -1
- package/lib/_bundle/rest.js.map +1 -1
- package/lib/annotations.d.ts.map +1 -1
- package/lib/api.d.ts +71 -58
- package/lib/api.d.ts.map +1 -1
- package/lib/api.js +1 -1
- package/lib/category.d.ts +15 -12
- package/lib/category.d.ts.map +1 -1
- package/lib/chunks.d.ts.map +1 -1
- package/lib/config.d.ts +13 -0
- package/lib/config.d.ts.map +1 -1
- package/lib/crypto.d.ts.map +1 -1
- package/lib/error-category.d.ts.map +1 -1
- package/lib/errors.d.ts +35 -2
- package/lib/errors.d.ts.map +1 -1
- package/lib/errors.js +1 -1
- package/lib/graphql.d.ts +21 -4
- package/lib/graphql.d.ts.map +1 -1
- package/lib/graphql.types.d.ts +0 -1
- package/lib/graphql.types.d.ts.map +1 -1
- package/lib/grpc-transport-cloudflare-http2.d.ts.map +1 -1
- package/lib/grpc-transport-cloudflare-http2.js +2 -2
- package/lib/grpc-transport-cloudflare-http2.js.map +1 -1
- package/lib/grpc-transport-cloudflare-sockets.d.ts.map +1 -1
- package/lib/grpc-transport-cloudflare-sockets.js +4 -4
- package/lib/grpc-transport-cloudflare-sockets.js.map +1 -1
- package/lib/grpc-transport-node-http2.d.ts.map +1 -1
- package/lib/grpc-transport-node-http2.js +1 -1
- package/lib/grpc-transport-node-http2.js.map +1 -1
- package/lib/grpc-transport.d.ts +53 -18
- package/lib/grpc-transport.d.ts.map +1 -1
- package/lib/grpc-transport.js +1 -1
- package/lib/hpack.d.ts.map +1 -1
- package/lib/index.d.ts.map +1 -1
- package/lib/max-message-bytes.d.ts +42 -0
- package/lib/max-message-bytes.d.ts.map +1 -0
- package/lib/max-message-bytes.js +2 -0
- package/lib/max-message-bytes.js.map +1 -0
- package/lib/ndjson.d.ts +3 -0
- package/lib/ndjson.d.ts.map +1 -0
- package/lib/ndjson.js +2 -0
- package/lib/ndjson.js.map +1 -0
- package/lib/pagination.d.ts +4 -1
- package/lib/pagination.d.ts.map +1 -1
- package/lib/plain-values.d.ts +11 -0
- package/lib/plain-values.d.ts.map +1 -1
- package/lib/plain-values.js +1 -1
- package/lib/plain-values.js.map +1 -1
- package/lib/protobuf.d.ts +12 -19
- package/lib/protobuf.d.ts.map +1 -1
- package/lib/protobuf.js +1 -1
- package/lib/protocol-grpc.d.ts +47 -10
- package/lib/protocol-grpc.d.ts.map +1 -1
- package/lib/protocol-grpc.js +1 -1
- package/lib/protocol-http.d.ts +110 -8
- package/lib/protocol-http.d.ts.map +1 -1
- package/lib/protocol-http.js +1 -1
- package/lib/protocol-rest.d.ts +161 -37
- package/lib/protocol-rest.d.ts.map +1 -1
- package/lib/protocol-rest.js +1 -1
- package/lib/protocol.d.ts +113 -0
- package/lib/protocol.d.ts.map +1 -0
- package/lib/protocol.js +0 -0
- package/lib/query.d.ts.map +1 -1
- package/lib/response-validation-strict.d.ts.map +1 -1
- package/lib/response-validation.d.ts.map +1 -1
- package/lib/retry-after.d.ts +1 -1
- package/lib/retry-after.d.ts.map +1 -1
- package/lib/retry-state.d.ts +26 -0
- package/lib/retry-state.d.ts.map +1 -0
- package/lib/retry-state.js +2 -0
- package/lib/retry-state.js.map +1 -0
- package/lib/retry.d.ts +100 -20
- package/lib/retry.d.ts.map +1 -1
- package/lib/retry.js +1 -1
- package/lib/schema-lite-impl.d.ts +25 -4
- package/lib/schema-lite-impl.d.ts.map +1 -1
- package/lib/schema-lite-impl.js +1 -1
- package/lib/schema-lite-typed.d.ts.map +1 -1
- package/lib/schema-lite.d.ts +1 -0
- package/lib/schema-lite.d.ts.map +1 -1
- package/lib/schema-lite.js +1 -1
- package/lib/schema.d.ts.map +1 -1
- package/lib/sdk-error.d.ts +4 -0
- package/lib/sdk-error.d.ts.map +1 -1
- package/lib/send.d.ts +37 -0
- package/lib/send.d.ts.map +1 -0
- package/lib/send.js +2 -0
- package/lib/send.js.map +1 -0
- package/lib/sensitive.d.ts.map +1 -1
- package/lib/sensitive.js +1 -1
- package/lib/sensitive.js.map +1 -1
- package/lib/telemetry-debug.d.ts.map +1 -1
- package/lib/telemetry-debug.js +1 -1
- package/lib/telemetry-debug.js.map +1 -1
- package/lib/telemetry-hooks.d.ts.map +1 -1
- package/lib/telemetry-host-rules.d.ts.map +1 -1
- package/lib/telemetry-lambda-context.d.ts.map +1 -1
- package/lib/telemetry-message-context.d.ts.map +1 -1
- package/lib/telemetry-metrics.d.ts.map +1 -1
- package/lib/telemetry-metrics.js +1 -1
- package/lib/telemetry-metrics.js.map +1 -1
- package/lib/telemetry-name-template.d.ts.map +1 -1
- package/lib/telemetry-stream.d.ts.map +1 -1
- package/lib/telemetry-stream.js +1 -1
- package/lib/telemetry-stream.js.map +1 -1
- package/lib/telemetry-xray.d.ts.map +1 -1
- package/lib/telemetry.d.ts +29 -0
- package/lib/telemetry.d.ts.map +1 -1
- package/lib/telemetry.js +2 -2
- package/lib/telemetry.js.map +1 -1
- package/lib/token-cache.d.ts +31 -0
- package/lib/token-cache.d.ts.map +1 -0
- package/lib/token-cache.js +2 -0
- package/lib/token-cache.js.map +1 -0
- package/lib/trait.d.ts +24 -1
- package/lib/trait.d.ts.map +1 -1
- package/lib/trait.js +1 -1
- package/lib/unknown-error.d.ts.map +1 -1
- package/lib/xml.d.ts.map +1 -1
- package/package.json +3 -3
- package/src/api.ts +402 -209
- package/src/category.ts +21 -28
- package/src/config.ts +17 -1
- package/src/errors.ts +24 -2
- package/src/graphql.ts +65 -26
- package/src/graphql.types.ts +15 -0
- package/src/grpc-transport-cloudflare-http2.ts +374 -299
- package/src/grpc-transport-cloudflare-sockets.ts +150 -81
- package/src/grpc-transport-node-http2.ts +119 -46
- package/src/grpc-transport.ts +211 -42
- package/src/max-message-bytes.ts +58 -0
- package/src/ndjson.ts +55 -0
- package/src/pagination.ts +26 -15
- package/src/plain-values.ts +30 -1
- package/src/protobuf.ts +40 -5
- package/src/protocol-grpc.ts +518 -348
- package/src/protocol-http.ts +474 -100
- package/src/protocol-rest.ts +580 -140
- package/src/protocol.ts +150 -0
- package/src/response-validation-strict.ts +9 -3
- package/src/retry-after.ts +1 -1
- package/src/retry-state.ts +105 -0
- package/src/retry.ts +176 -47
- package/src/schema-lite-impl.ts +81 -10
- package/src/schema-lite.ts +1 -0
- package/src/sdk-error.ts +4 -0
- package/src/send.ts +156 -0
- package/src/sensitive.ts +49 -15
- package/src/telemetry.ts +2 -34
- package/src/token-cache.ts +117 -0
- package/src/trait.ts +34 -1
package/src/protocol.ts
ADDED
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What a protocol is, typed by the errors it declares.
|
|
3
|
+
*
|
|
4
|
+
* An operation fails with three groups of errors, each named for where it
|
|
5
|
+
* is declared:
|
|
6
|
+
*
|
|
7
|
+
* 1. on the operation its `errors` list
|
|
8
|
+
* 2. on the service its `serviceErrors` list, the same for every
|
|
9
|
+
* operation of the service
|
|
10
|
+
* 3. on the protocol the {@link Protocol}'s own error type: what the
|
|
11
|
+
* code that builds requests and reads responses
|
|
12
|
+
* fails with (a response it can't parse, mostly)
|
|
13
|
+
*
|
|
14
|
+
* `API.make` adds the three together. A protocol never names an error of
|
|
15
|
+
* groups 1 and 2: it receives their classes, matches a failed response
|
|
16
|
+
* against them, and fails with the instance as a {@link DeclaredError}.
|
|
17
|
+
* Everything else it fails with is in its own type, and passes through to
|
|
18
|
+
* every operation that names the protocol. Nobody writes that list: the
|
|
19
|
+
* compiler reads it from the protocol's code ({@link ErrorOf}, and
|
|
20
|
+
* {@link ProtocolOf} for a protocol written by hand).
|
|
21
|
+
*
|
|
22
|
+
* export const NeonProtocol = restProtocol({ ... });
|
|
23
|
+
* export type NeonOpError = NeonServiceError | ErrorOf<typeof NeonProtocol>;
|
|
24
|
+
*
|
|
25
|
+
* Types only: this module has no runtime code.
|
|
26
|
+
*/
|
|
27
|
+
import type * as Effect from "effect/Effect";
|
|
28
|
+
import type * as HttpClientRequest from "effect/http/HttpClientRequest";
|
|
29
|
+
import type * as HttpClientResponse from "effect/http/HttpClientResponse";
|
|
30
|
+
import type * as AST from "effect/SchemaAST";
|
|
31
|
+
import type * as Stream from "effect/Stream";
|
|
32
|
+
import type { PreparedOperation, ProtocolOperationConfig } from "./api.ts";
|
|
33
|
+
|
|
34
|
+
declare const declaredError: unique symbol;
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* An error of group 1 or 2 as a protocol sees it: an instance of a class
|
|
38
|
+
* that the operation or its service declares. A protocol can construct one
|
|
39
|
+
* from a {@link DeclaredErrorClass} and fail with it; `API.make` puts the
|
|
40
|
+
* real classes in the operation's error type.
|
|
41
|
+
*/
|
|
42
|
+
export interface DeclaredError {
|
|
43
|
+
readonly [declaredError]: true;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** A class that the operation or its service declares, as a protocol receives it. */
|
|
47
|
+
export type DeclaredErrorClass = new (props: any) => DeclaredError;
|
|
48
|
+
|
|
49
|
+
/** What {@link Protocol.encode} receives. */
|
|
50
|
+
export interface EncodeArgs {
|
|
51
|
+
readonly input: unknown;
|
|
52
|
+
readonly inputAst: AST.AST;
|
|
53
|
+
/** The operation's config (the same object on every call of the operation). */
|
|
54
|
+
readonly config: ProtocolOperationConfig;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** What {@link Protocol.decode} receives. */
|
|
58
|
+
export interface DecodeArgs {
|
|
59
|
+
readonly response: HttpClientResponse.HttpClientResponse;
|
|
60
|
+
readonly outputAst: AST.AST;
|
|
61
|
+
/** The operation's declared classes, then its service's. */
|
|
62
|
+
readonly errors: ReadonlyArray<DeclaredErrorClass>;
|
|
63
|
+
/** The operation's config (the same object on every call of the operation). */
|
|
64
|
+
readonly config: ProtocolOperationConfig;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** One operation as {@link Protocol.call} and {@link Protocol.stream} see it. */
|
|
68
|
+
export interface Operation extends Omit<PreparedOperation, "errors"> {
|
|
69
|
+
/** The operation's declared classes, then its service's. */
|
|
70
|
+
readonly errors: ReadonlyArray<DeclaredErrorClass>;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* How an SDK turns an input into an HTTP request and a response into an
|
|
75
|
+
* output. `ProtocolError` is what the protocol declares (group 3), and
|
|
76
|
+
* `Requirements` is what its methods read from the calling fiber
|
|
77
|
+
* (credentials, a region).
|
|
78
|
+
*
|
|
79
|
+
* A request that was not sent has no response to match, so `encode` fails
|
|
80
|
+
* with the protocol's errors only.
|
|
81
|
+
*/
|
|
82
|
+
export interface Protocol<ProtocolError, Requirements = never> {
|
|
83
|
+
readonly encode: (
|
|
84
|
+
args: EncodeArgs,
|
|
85
|
+
) => Effect.Effect<HttpClientRequest.HttpClientRequest, ProtocolError, Requirements>;
|
|
86
|
+
readonly decode: (
|
|
87
|
+
args: DecodeArgs,
|
|
88
|
+
) => Effect.Effect<unknown, DeclaredError | ProtocolError, Requirements>;
|
|
89
|
+
/**
|
|
90
|
+
* Optional whole call. When present, `API.make` runs a call as
|
|
91
|
+
* `call(operation, input)` in place of encode, send, decode. It reads the
|
|
92
|
+
* `HttpClient` from the calling fiber and produces the same request,
|
|
93
|
+
* result and errors as `encode` and `decode`.
|
|
94
|
+
*/
|
|
95
|
+
readonly call?: (
|
|
96
|
+
operation: Operation,
|
|
97
|
+
input: unknown,
|
|
98
|
+
) => Effect.Effect<unknown, DeclaredError | ProtocolError, Requirements>;
|
|
99
|
+
/**
|
|
100
|
+
* Server streaming (see `API.makeStreaming`): each response message as it
|
|
101
|
+
* arrives, decoded as one element of the output's `items`. Ending the
|
|
102
|
+
* stream early cancels the call. A protocol that can't stream leaves it
|
|
103
|
+
* out; one that streams only some operations fails the others with
|
|
104
|
+
* `API.cannotStream`.
|
|
105
|
+
*/
|
|
106
|
+
readonly stream?: (
|
|
107
|
+
operation: Operation,
|
|
108
|
+
input: unknown,
|
|
109
|
+
) => Stream.Stream<unknown, DeclaredError | ProtocolError, Requirements>;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** What the methods of `P` return: its effects and its stream. */
|
|
113
|
+
type Outcome<P> = P[Extract<keyof P, keyof Protocol<unknown>>] extends infer Method
|
|
114
|
+
? Method extends (...args: any) => infer Result
|
|
115
|
+
? Result
|
|
116
|
+
: never
|
|
117
|
+
: never;
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* The errors a protocol declares (group 3), read from what its methods fail
|
|
121
|
+
* with. An SDK uses it to name what every operation fails with besides its
|
|
122
|
+
* own errors: `<Sdk>ServiceError | ErrorOf<typeof <Sdk>Protocol>`.
|
|
123
|
+
*/
|
|
124
|
+
export type ErrorOf<P> =
|
|
125
|
+
Outcome<P> extends infer Result
|
|
126
|
+
? Result extends Effect.Effect<any, infer Failure, any>
|
|
127
|
+
? Exclude<Failure, DeclaredError>
|
|
128
|
+
: Result extends Stream.Stream<any, infer Failure, any>
|
|
129
|
+
? Exclude<Failure, DeclaredError>
|
|
130
|
+
: never
|
|
131
|
+
: never;
|
|
132
|
+
|
|
133
|
+
/** What a protocol's methods read from the calling fiber. */
|
|
134
|
+
export type RequirementsOf<P> =
|
|
135
|
+
Outcome<P> extends infer Result
|
|
136
|
+
? Result extends Effect.Effect<any, any, infer Requirements>
|
|
137
|
+
? Requirements
|
|
138
|
+
: Result extends Stream.Stream<any, any, infer Requirements>
|
|
139
|
+
? Requirements
|
|
140
|
+
: never
|
|
141
|
+
: never;
|
|
142
|
+
|
|
143
|
+
/**
|
|
144
|
+
* The type of a protocol written by hand, read from its methods, so that
|
|
145
|
+
* nobody lists its errors:
|
|
146
|
+
*
|
|
147
|
+
* const methods = { encode, decode } satisfies Protocol<unknown, unknown>;
|
|
148
|
+
* export const GcpProtocol: ProtocolOf<typeof methods> = methods;
|
|
149
|
+
*/
|
|
150
|
+
export type ProtocolOf<Methods> = Protocol<ErrorOf<Methods>, RequirementsOf<Methods>>;
|
|
@@ -77,6 +77,12 @@ const MISSING: unique symbol = Symbol("missing");
|
|
|
77
77
|
const makeCompile = (exact: boolean): ((n: Node) => Check) => {
|
|
78
78
|
const fail = (expected: string, actual: unknown): Fail => ({ path: [], expected, actual });
|
|
79
79
|
const ok: Check = () => undefined;
|
|
80
|
+
// Effect's rule (SchemaAST.requiresOwnProperty, since 4.1.3): a field named
|
|
81
|
+
// after an `Object.prototype` member is present only as an own property,
|
|
82
|
+
// so `{}` has no `constructor`.
|
|
83
|
+
const prototypeKeys = new Set<PropertyKey>(Reflect.ownKeys(Object.prototype)).add("__proto__");
|
|
84
|
+
const ownOnly = (name: PropertyKey) =>
|
|
85
|
+
prototypeKeys.has(typeof name === "number" ? String(name) : name);
|
|
80
86
|
const typeOf =
|
|
81
87
|
(t: string): Check =>
|
|
82
88
|
(u) =>
|
|
@@ -253,7 +259,7 @@ const makeCompile = (exact: boolean): ((n: Node) => Check) => {
|
|
|
253
259
|
|
|
254
260
|
const objects = (n: Node): Check => {
|
|
255
261
|
const props = (n.propertySignatures ?? []).map(
|
|
256
|
-
(p) => [p.name, compile(p.type), isOptional(p.type)] as const,
|
|
262
|
+
(p) => [p.name, compile(p.type), isOptional(p.type), ownOnly(p.name)] as const,
|
|
257
263
|
);
|
|
258
264
|
const index = (n.indexSignatures ?? []).map(
|
|
259
265
|
(s) => [compile(s.parameter), compile(s.type)] as const,
|
|
@@ -269,8 +275,8 @@ const makeCompile = (exact: boolean): ((n: Node) => Check) => {
|
|
|
269
275
|
if (typeof u !== "object" || u === null || Array.isArray(u)) return fail("object", u);
|
|
270
276
|
const o = u as Record<PropertyKey, unknown>;
|
|
271
277
|
for (let i = 0; i < props.length; i++) {
|
|
272
|
-
const [name, check, optional] = props[i]!;
|
|
273
|
-
if (!(
|
|
278
|
+
const [name, check, optional, own] = props[i]!;
|
|
279
|
+
if (!(Object.hasOwn(o, name) || (!own && name in o))) {
|
|
274
280
|
if (optional) continue;
|
|
275
281
|
return at(fail("a value", MISSING), name);
|
|
276
282
|
}
|
package/src/retry-after.ts
CHANGED
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
*
|
|
9
9
|
* Each SDK's `matchError` calls these helpers and attaches the resulting
|
|
10
10
|
* `Duration` to retryable errors via the optional `retryAfter` field, where
|
|
11
|
-
* the retry policy
|
|
11
|
+
* the retry policy waits at least that long (RFC 9110).
|
|
12
12
|
*
|
|
13
13
|
* Services that use bespoke headers or body fields are expected to do their
|
|
14
14
|
* own parsing in the SDK's `matchError`, optionally falling back to these
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What the retry layer learns from the wire, kept outside the error values:
|
|
3
|
+
*
|
|
4
|
+
* - the host of the last request each fiber sent, which keys the retry
|
|
5
|
+
* budget ({@link Budget}), and the bounded server hint its response
|
|
6
|
+
* carried (`x-amz-retry-after` / `x-distilled-retry-after`);
|
|
7
|
+
* - whether that request's body could be read only once, so a retry
|
|
8
|
+
* would send it empty;
|
|
9
|
+
* - a count of successful responses per host, which refills the budget.
|
|
10
|
+
*
|
|
11
|
+
* `send` (`./send.ts`) writes them for every protocol that sends through it.
|
|
12
|
+
* The module imports nothing heavy: every bundle that sends a request loads
|
|
13
|
+
* it.
|
|
14
|
+
*/
|
|
15
|
+
import * as Fiber from "effect/Fiber";
|
|
16
|
+
|
|
17
|
+
interface LastRequest {
|
|
18
|
+
readonly host: string;
|
|
19
|
+
/** The body can be read only once: the call must not be sent again. */
|
|
20
|
+
readonly oneShot: boolean;
|
|
21
|
+
/** Bounded server hint of the response, in milliseconds. */
|
|
22
|
+
hintMs: number | undefined;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
const lastByFiber = /*@__PURE__*/ new WeakMap<object, LastRequest>();
|
|
26
|
+
const successesByHost = /*@__PURE__*/ new Map<string, number>();
|
|
27
|
+
|
|
28
|
+
/** The host of `url` (no port); `""` when it has none. */
|
|
29
|
+
export const hostOf = (url: string): string => {
|
|
30
|
+
const schemeEnd = url.indexOf("://");
|
|
31
|
+
if (schemeEnd === -1) return "";
|
|
32
|
+
const start = schemeEnd + 3;
|
|
33
|
+
let end = start;
|
|
34
|
+
while (end < url.length && !"/?#".includes(url[end]!)) end++;
|
|
35
|
+
const authority = url.slice(url.lastIndexOf("@", end) + 1 || start, end);
|
|
36
|
+
const colon = authority.lastIndexOf(":");
|
|
37
|
+
return colon !== -1 && !authority.endsWith("]") ? authority.slice(0, colon) : authority;
|
|
38
|
+
};
|
|
39
|
+
|
|
40
|
+
/** A whole, non-negative number of milliseconds; anything else is no hint. */
|
|
41
|
+
const parseMs = (value: string | undefined): number | undefined => {
|
|
42
|
+
if (value === undefined) return undefined;
|
|
43
|
+
const trimmed = value.trim();
|
|
44
|
+
if (!/^\d+$/.test(trimmed)) return undefined;
|
|
45
|
+
const ms = Number(trimmed);
|
|
46
|
+
return Number.isSafeInteger(ms) ? ms : undefined;
|
|
47
|
+
};
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* The bounded server hint of a response: `x-amz-retry-after` or
|
|
51
|
+
* `x-distilled-retry-after` in milliseconds, the larger when both are set.
|
|
52
|
+
*/
|
|
53
|
+
export const boundedHintOf = (
|
|
54
|
+
headers: Readonly<Record<string, string | undefined>>,
|
|
55
|
+
): number | undefined => {
|
|
56
|
+
const amz = parseMs(headers["x-amz-retry-after"]);
|
|
57
|
+
const distilled = parseMs(headers["x-distilled-retry-after"]);
|
|
58
|
+
if (amz === undefined) return distilled;
|
|
59
|
+
return distilled === undefined ? amz : Math.max(amz, distilled);
|
|
60
|
+
};
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* Record that the current fiber is sending a request to `url`; `oneShot`
|
|
64
|
+
* when its body can be read only once.
|
|
65
|
+
*/
|
|
66
|
+
export const recordRequest = (url: string, oneShot = false): void => {
|
|
67
|
+
const fiber = Fiber.getCurrent();
|
|
68
|
+
if (fiber !== undefined) {
|
|
69
|
+
lastByFiber.set(fiber, { host: hostOf(url), oneShot, hintMs: undefined });
|
|
70
|
+
}
|
|
71
|
+
};
|
|
72
|
+
|
|
73
|
+
/** Record the response to the current fiber's last request. */
|
|
74
|
+
export const recordResponse = (
|
|
75
|
+
status: number,
|
|
76
|
+
headers: Readonly<Record<string, string | undefined>>,
|
|
77
|
+
): void => {
|
|
78
|
+
const fiber = Fiber.getCurrent();
|
|
79
|
+
const last = fiber === undefined ? undefined : lastByFiber.get(fiber);
|
|
80
|
+
if (last === undefined) return;
|
|
81
|
+
if (status < 300) {
|
|
82
|
+
successesByHost.set(last.host, (successesByHost.get(last.host) ?? 0) + 1);
|
|
83
|
+
} else {
|
|
84
|
+
last.hintMs = boundedHintOf(headers);
|
|
85
|
+
}
|
|
86
|
+
};
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* The current fiber's last request, removed so that a later failure that
|
|
90
|
+
* sent nothing cannot reuse its hint.
|
|
91
|
+
*/
|
|
92
|
+
export const takeLastRequest = (): {
|
|
93
|
+
readonly host: string;
|
|
94
|
+
readonly oneShot: boolean;
|
|
95
|
+
readonly hintMs?: number;
|
|
96
|
+
} => {
|
|
97
|
+
const fiber = Fiber.getCurrent();
|
|
98
|
+
const last = fiber === undefined ? undefined : lastByFiber.get(fiber);
|
|
99
|
+
if (last === undefined) return { host: "", oneShot: false };
|
|
100
|
+
lastByFiber.delete(fiber!);
|
|
101
|
+
return last.hintMs === undefined ? { host: last.host, oneShot: last.oneShot } : last;
|
|
102
|
+
};
|
|
103
|
+
|
|
104
|
+
/** Successful responses from `host` so far in this process. */
|
|
105
|
+
export const successesOf = (host: string): number => successesByHost.get(host) ?? 0;
|
package/src/retry.ts
CHANGED
|
@@ -10,12 +10,12 @@
|
|
|
10
10
|
import * as Context from "effect/Context";
|
|
11
11
|
import * as Duration from "effect/Duration";
|
|
12
12
|
import * as Effect from "effect/Effect";
|
|
13
|
-
import { pipe } from "effect/Function";
|
|
14
13
|
import * as Layer from "effect/Layer";
|
|
15
14
|
import * as Option from "effect/Option";
|
|
16
15
|
import * as Ref from "effect/Ref";
|
|
17
16
|
import * as Schedule from "effect/Schedule";
|
|
18
17
|
import { isThrottling, isTransientError } from "./category.ts";
|
|
18
|
+
import { successesOf } from "./retry-state.ts";
|
|
19
19
|
|
|
20
20
|
// ============================================================================
|
|
21
21
|
// Retry Policy Types
|
|
@@ -29,10 +29,22 @@ import { isThrottling, isTransientError } from "./category.ts";
|
|
|
29
29
|
* instead of an Effect `Schedule`, so bundles do not carry the Schedule
|
|
30
30
|
* machinery unless a caller supplies a schedule of their own.
|
|
31
31
|
*
|
|
32
|
-
* Delay before retry `n` (0-based)
|
|
33
|
-
*
|
|
34
|
-
*
|
|
35
|
-
*
|
|
32
|
+
* Delay before retry `n` (0-based), `t`:
|
|
33
|
+
*
|
|
34
|
+
* - with `fullJitter`: `random(0, 1) × min(capMs, base × factor^n)`, where
|
|
35
|
+
* `base` is `throttlingBaseMs` for throttling errors and `baseMs` otherwise;
|
|
36
|
+
* - without it: `min(baseMs × factor^n, capMs)`, at least `minThrottleMs` for
|
|
37
|
+
* throttling errors, plus up to `jitterMs` of random jitter.
|
|
38
|
+
*
|
|
39
|
+
* With `serverHint`, the server can lengthen `t`:
|
|
40
|
+
*
|
|
41
|
+
* - a bounded hint (`x-amz-retry-after` or `x-distilled-retry-after`, in
|
|
42
|
+
* milliseconds) is clamped to `[t, t + 5s]` and used as is;
|
|
43
|
+
* - otherwise `error.retryAfter` (`Retry-After` / `RateLimit`) is a minimum,
|
|
44
|
+
* as RFC 9110 defines it; a hint over the cap ({@link ServerRetryHintCapMs})
|
|
45
|
+
* stops retrying, because retrying earlier than the server asked fails again.
|
|
46
|
+
*
|
|
47
|
+
* With a `budget`, each retry withdraws from it and stops when it is empty.
|
|
36
48
|
*/
|
|
37
49
|
export interface Backoff {
|
|
38
50
|
readonly baseMs: number;
|
|
@@ -43,8 +55,109 @@ export interface Backoff {
|
|
|
43
55
|
readonly jitterMs?: number;
|
|
44
56
|
readonly minThrottleMs?: number;
|
|
45
57
|
readonly serverHint?: boolean;
|
|
58
|
+
/** Base delay for throttling errors under `fullJitter`; `baseMs` when absent. */
|
|
59
|
+
readonly throttlingBaseMs?: number;
|
|
60
|
+
readonly fullJitter?: boolean;
|
|
61
|
+
readonly budget?: Budget;
|
|
62
|
+
/**
|
|
63
|
+
* When the budget cannot pay for a retry, wait the delay before failing
|
|
64
|
+
* anyway, so a polling loop around the call cannot spin (AWS Retry
|
|
65
|
+
* Behavior 2.1 for long-polling operations such as SQS `ReceiveMessage`).
|
|
66
|
+
*/
|
|
67
|
+
readonly longPoll?: boolean;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** How far a bounded server hint may lengthen the computed delay. */
|
|
71
|
+
export const BOUNDED_HINT_MAX_EXTRA_MS = 5_000;
|
|
72
|
+
|
|
73
|
+
// ============================================================================
|
|
74
|
+
// Retry Budget
|
|
75
|
+
// ============================================================================
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* A retry budget: one token bucket per key (the request's host). A retry
|
|
79
|
+
* withdraws its cost; a successful response from that host adds one token,
|
|
80
|
+
* up to `max`; a retry that succeeds gets its cost back. When a bucket
|
|
81
|
+
* cannot pay, the call fails instead of retrying, so a failing dependency
|
|
82
|
+
* sees about `1 / cost` extra load instead of `maxRetries` times its load.
|
|
83
|
+
*
|
|
84
|
+
* The bucket lives as long as the budget value. A policy defined at module
|
|
85
|
+
* scope shares one budget across calls (and across Lambda invocations); a
|
|
86
|
+
* policy built per call starts a fresh one each time.
|
|
87
|
+
*/
|
|
88
|
+
export interface Budget {
|
|
89
|
+
/** Withdraw a retry's cost from `key`'s bucket; the cost, or `undefined` when it cannot pay. */
|
|
90
|
+
readonly withdraw: (key: string, throttling: boolean) => number | undefined;
|
|
91
|
+
/** Give back what a retry that succeeded withdrew. */
|
|
92
|
+
readonly refund: (key: string, cost: number) => void;
|
|
93
|
+
/** Tokens left in `key`'s bucket. */
|
|
94
|
+
readonly tokens: (key: string) => number;
|
|
95
|
+
/** Return every bucket to its initial tokens. */
|
|
96
|
+
readonly reset: () => void;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
export interface BudgetOptions {
|
|
100
|
+
/** Tokens a new bucket starts with. Default 100: 7 transient or 20 throttling retries. */
|
|
101
|
+
readonly initial?: number;
|
|
102
|
+
/** Most tokens a bucket holds. Default 500. */
|
|
103
|
+
readonly max?: number;
|
|
104
|
+
/** Cost of retrying a non-throttling error. Default 14. */
|
|
105
|
+
readonly transientCost?: number;
|
|
106
|
+
/** Cost of retrying a throttling error. Default 5. */
|
|
107
|
+
readonly throttlingCost?: number;
|
|
46
108
|
}
|
|
47
109
|
|
|
110
|
+
/**
|
|
111
|
+
* The AWS SDKs' retry quota (Retry Behavior 2.1: 500 tokens, a transient
|
|
112
|
+
* retry costs 14, a throttling retry 5, a success adds 1), except that a
|
|
113
|
+
* bucket starts with 100 tokens instead of full: many short-lived clients,
|
|
114
|
+
* each starting full, would together retry a failing service at nearly
|
|
115
|
+
* `maxRetries` times its load.
|
|
116
|
+
*/
|
|
117
|
+
export const makeBudget = (options: BudgetOptions = {}): Budget => {
|
|
118
|
+
const initial = options.initial ?? 100;
|
|
119
|
+
const max = options.max ?? 500;
|
|
120
|
+
const transientCost = options.transientCost ?? 14;
|
|
121
|
+
const throttlingCost = options.throttlingCost ?? 5;
|
|
122
|
+
const buckets = new Map<string, { tokens: number; seen: number }>();
|
|
123
|
+
const bucket = (key: string) => {
|
|
124
|
+
const seen = successesOf(key);
|
|
125
|
+
let b = buckets.get(key);
|
|
126
|
+
if (b === undefined) {
|
|
127
|
+
b = { tokens: initial, seen };
|
|
128
|
+
buckets.set(key, b);
|
|
129
|
+
} else if (seen !== b.seen) {
|
|
130
|
+
// Successes since the last look, one token each.
|
|
131
|
+
b.tokens = Math.min(max, b.tokens + (seen - b.seen));
|
|
132
|
+
b.seen = seen;
|
|
133
|
+
}
|
|
134
|
+
return b;
|
|
135
|
+
};
|
|
136
|
+
return {
|
|
137
|
+
withdraw: (key, throttling) => {
|
|
138
|
+
const b = bucket(key);
|
|
139
|
+
const cost = throttling ? throttlingCost : transientCost;
|
|
140
|
+
if (b.tokens < cost) return undefined;
|
|
141
|
+
b.tokens -= cost;
|
|
142
|
+
return cost;
|
|
143
|
+
},
|
|
144
|
+
refund: (key, cost) => {
|
|
145
|
+
const b = bucket(key);
|
|
146
|
+
// The success itself already added a token.
|
|
147
|
+
b.tokens = Math.min(max, b.tokens + cost - 1);
|
|
148
|
+
},
|
|
149
|
+
tokens: (key) => bucket(key).tokens,
|
|
150
|
+
reset: () => buckets.clear(),
|
|
151
|
+
};
|
|
152
|
+
};
|
|
153
|
+
|
|
154
|
+
/**
|
|
155
|
+
* The budget of the default policy, shared by every SDK in this process.
|
|
156
|
+
* Its buckets are keyed by host, so one failing service does not use up the
|
|
157
|
+
* retries of another.
|
|
158
|
+
*/
|
|
159
|
+
export const defaultBudget: Budget = /*@__PURE__*/ makeBudget();
|
|
160
|
+
|
|
48
161
|
export interface Options {
|
|
49
162
|
/**
|
|
50
163
|
* Predicate to determine if an error should trigger a retry.
|
|
@@ -189,6 +302,7 @@ export const resolveServerRetryHintCapMs = (): Effect.Effect<number, never, neve
|
|
|
189
302
|
| ProvidedConfigProvider
|
|
190
303
|
| undefined;
|
|
191
304
|
if (!provider) return readServerRetryHintCapMsFromEnv();
|
|
305
|
+
// An unset or unreadable cap is the default cap.
|
|
192
306
|
const node = yield* provider
|
|
193
307
|
.load([ENV_SERVER_RETRY_HINT_CAP_MS])
|
|
194
308
|
.pipe(Effect.orElseSucceed(() => undefined));
|
|
@@ -208,66 +322,81 @@ export const serverHintMillis = (error: unknown, capMs: number): number | undefi
|
|
|
208
322
|
return Math.min(Duration.toMillis(hint), capMs);
|
|
209
323
|
};
|
|
210
324
|
|
|
211
|
-
/**
|
|
212
|
-
* Schedule modifier that honors `error.retryAfter` (set by the SDK's
|
|
213
|
-
* `matchError` from `Retry-After` / `RateLimit` headers) with precedence
|
|
214
|
-
* over the input delay. Falls back to the original delay when no hint is
|
|
215
|
-
* present.
|
|
216
|
-
*/
|
|
217
|
-
const honorServerHint = (
|
|
218
|
-
lastError: Ref.Ref<unknown>,
|
|
219
|
-
baseline?: (duration: Duration.Duration, error: unknown) => Duration.Duration,
|
|
220
|
-
) =>
|
|
221
|
-
Schedule.modifyDelay(
|
|
222
|
-
Effect.fnUntraced(function* ({ duration }) {
|
|
223
|
-
const capMs = yield* resolveServerRetryHintCapMs();
|
|
224
|
-
const error = yield* Ref.get(lastError);
|
|
225
|
-
const hint = serverHintMillis(error, capMs);
|
|
226
|
-
if (hint !== undefined) return hint;
|
|
227
|
-
const adjusted = baseline ? baseline(duration, error) : duration;
|
|
228
|
-
return Duration.toMillis(adjusted);
|
|
229
|
-
}),
|
|
230
|
-
);
|
|
231
|
-
|
|
232
325
|
// ============================================================================
|
|
233
326
|
// Default Retry Policies
|
|
234
327
|
// ============================================================================
|
|
235
328
|
|
|
236
329
|
/**
|
|
237
|
-
*
|
|
330
|
+
* The policy used when the context provides none, tuned for calls at
|
|
331
|
+
* runtime (a request handler, a Lambda) after AWS's Retry Behavior 2.1:
|
|
238
332
|
*
|
|
239
|
-
*
|
|
240
|
-
* -
|
|
241
|
-
* -
|
|
242
|
-
*
|
|
243
|
-
*
|
|
244
|
-
* -
|
|
245
|
-
* capped at 5s per delay
|
|
246
|
-
* - Ensures at least 500ms delay for throttling errors
|
|
247
|
-
* - Limits to 8 retry attempts
|
|
248
|
-
* - Applies jitter to avoid thundering herd
|
|
333
|
+
* - retries only errors marked retryable (see `isTransientError`);
|
|
334
|
+
* - at most 2 retries (3 attempts);
|
|
335
|
+
* - full jitter: `random(0, 1) × min(20s, base × 2^n)`, base 50ms, or 1s
|
|
336
|
+
* for throttling errors;
|
|
337
|
+
* - honors server hints (see {@link Backoff});
|
|
338
|
+
* - draws from {@link defaultBudget}.
|
|
249
339
|
*
|
|
250
|
-
*
|
|
251
|
-
*
|
|
252
|
-
* high request concurrency routinely outlast a short 5-attempt/3s policy
|
|
253
|
-
* while a genuinely broken credential still fails within seconds.
|
|
340
|
+
* Deploy tools that should wait out longer outages install their own
|
|
341
|
+
* policy, for example {@link transientFactory}.
|
|
254
342
|
*/
|
|
255
|
-
/** The policy used when the context provides none. */
|
|
256
343
|
export const defaultOptions: Options = {
|
|
257
344
|
while: (error) => isTransientError(error),
|
|
258
345
|
backoff: {
|
|
259
|
-
baseMs:
|
|
346
|
+
baseMs: 50,
|
|
347
|
+
throttlingBaseMs: 1000,
|
|
260
348
|
factor: 2,
|
|
261
|
-
capMs:
|
|
262
|
-
maxRetries:
|
|
263
|
-
|
|
264
|
-
minThrottleMs: 500,
|
|
349
|
+
capMs: 20_000,
|
|
350
|
+
maxRetries: 2,
|
|
351
|
+
fullJitter: true,
|
|
265
352
|
serverHint: true,
|
|
353
|
+
budget: defaultBudget,
|
|
266
354
|
},
|
|
267
355
|
};
|
|
268
356
|
|
|
269
357
|
export const makeDefault: Factory = () => defaultOptions;
|
|
270
358
|
|
|
359
|
+
/**
|
|
360
|
+
* A model's `distilled.retry#policy` trait: numbers that replace the default
|
|
361
|
+
* policy's for a service or an operation. What retries still comes from the
|
|
362
|
+
* error's marks.
|
|
363
|
+
*/
|
|
364
|
+
export interface RetryOverride {
|
|
365
|
+
/** Attempts in total, the first included. */
|
|
366
|
+
readonly maxAttempts?: number;
|
|
367
|
+
readonly baseMs?: number;
|
|
368
|
+
readonly throttlingBaseMs?: number;
|
|
369
|
+
readonly capMs?: number;
|
|
370
|
+
/** Multiplier between delays (2 by default). */
|
|
371
|
+
readonly factor?: number;
|
|
372
|
+
readonly longPoll?: boolean;
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
const overridden = new WeakMap<RetryOverride, Options>();
|
|
376
|
+
|
|
377
|
+
/** {@link defaultOptions} with `override`'s numbers, memoized per override object. */
|
|
378
|
+
export const defaultWith = (override: RetryOverride): Options => {
|
|
379
|
+
const cached = overridden.get(override);
|
|
380
|
+
if (cached !== undefined) return cached;
|
|
381
|
+
const backoff = defaultOptions.backoff!;
|
|
382
|
+
const result: Options = {
|
|
383
|
+
...defaultOptions,
|
|
384
|
+
backoff: {
|
|
385
|
+
...backoff,
|
|
386
|
+
...(override.maxAttempts !== undefined ? { maxRetries: override.maxAttempts - 1 } : {}),
|
|
387
|
+
...(override.baseMs !== undefined ? { baseMs: override.baseMs } : {}),
|
|
388
|
+
...(override.throttlingBaseMs !== undefined
|
|
389
|
+
? { throttlingBaseMs: override.throttlingBaseMs }
|
|
390
|
+
: {}),
|
|
391
|
+
...(override.capMs !== undefined ? { capMs: override.capMs } : {}),
|
|
392
|
+
...(override.factor !== undefined ? { factor: override.factor } : {}),
|
|
393
|
+
...(override.longPoll !== undefined ? { longPoll: override.longPoll } : {}),
|
|
394
|
+
},
|
|
395
|
+
};
|
|
396
|
+
overridden.set(override, result);
|
|
397
|
+
return result;
|
|
398
|
+
};
|
|
399
|
+
|
|
271
400
|
const slowBackoff: Backoff = {
|
|
272
401
|
baseMs: 1000,
|
|
273
402
|
factor: 2,
|