@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.
Files changed (161) hide show
  1. package/README.md +33 -0
  2. package/lib/_bundle/aws.js +1 -1
  3. package/lib/_bundle/aws.js.map +1 -1
  4. package/lib/_bundle/base.js +2 -2
  5. package/lib/_bundle/base.js.map +1 -1
  6. package/lib/_bundle/graphql.js +2 -2
  7. package/lib/_bundle/graphql.js.map +1 -1
  8. package/lib/_bundle/grpc.js +2 -1
  9. package/lib/_bundle/grpc.js.map +1 -1
  10. package/lib/_bundle/rest.js +1 -1
  11. package/lib/_bundle/rest.js.map +1 -1
  12. package/lib/annotations.d.ts.map +1 -1
  13. package/lib/api.d.ts +71 -58
  14. package/lib/api.d.ts.map +1 -1
  15. package/lib/api.js +1 -1
  16. package/lib/category.d.ts +15 -12
  17. package/lib/category.d.ts.map +1 -1
  18. package/lib/chunks.d.ts.map +1 -1
  19. package/lib/config.d.ts +13 -0
  20. package/lib/config.d.ts.map +1 -1
  21. package/lib/crypto.d.ts.map +1 -1
  22. package/lib/error-category.d.ts.map +1 -1
  23. package/lib/errors.d.ts +35 -2
  24. package/lib/errors.d.ts.map +1 -1
  25. package/lib/errors.js +1 -1
  26. package/lib/graphql.d.ts +21 -4
  27. package/lib/graphql.d.ts.map +1 -1
  28. package/lib/graphql.types.d.ts +0 -1
  29. package/lib/graphql.types.d.ts.map +1 -1
  30. package/lib/grpc-transport-cloudflare-http2.d.ts.map +1 -1
  31. package/lib/grpc-transport-cloudflare-http2.js +2 -2
  32. package/lib/grpc-transport-cloudflare-http2.js.map +1 -1
  33. package/lib/grpc-transport-cloudflare-sockets.d.ts.map +1 -1
  34. package/lib/grpc-transport-cloudflare-sockets.js +4 -4
  35. package/lib/grpc-transport-cloudflare-sockets.js.map +1 -1
  36. package/lib/grpc-transport-node-http2.d.ts.map +1 -1
  37. package/lib/grpc-transport-node-http2.js +1 -1
  38. package/lib/grpc-transport-node-http2.js.map +1 -1
  39. package/lib/grpc-transport.d.ts +53 -18
  40. package/lib/grpc-transport.d.ts.map +1 -1
  41. package/lib/grpc-transport.js +1 -1
  42. package/lib/hpack.d.ts.map +1 -1
  43. package/lib/index.d.ts.map +1 -1
  44. package/lib/max-message-bytes.d.ts +42 -0
  45. package/lib/max-message-bytes.d.ts.map +1 -0
  46. package/lib/max-message-bytes.js +2 -0
  47. package/lib/max-message-bytes.js.map +1 -0
  48. package/lib/ndjson.d.ts +3 -0
  49. package/lib/ndjson.d.ts.map +1 -0
  50. package/lib/ndjson.js +2 -0
  51. package/lib/ndjson.js.map +1 -0
  52. package/lib/pagination.d.ts +4 -1
  53. package/lib/pagination.d.ts.map +1 -1
  54. package/lib/plain-values.d.ts +11 -0
  55. package/lib/plain-values.d.ts.map +1 -1
  56. package/lib/plain-values.js +1 -1
  57. package/lib/plain-values.js.map +1 -1
  58. package/lib/protobuf.d.ts +12 -19
  59. package/lib/protobuf.d.ts.map +1 -1
  60. package/lib/protobuf.js +1 -1
  61. package/lib/protocol-grpc.d.ts +47 -10
  62. package/lib/protocol-grpc.d.ts.map +1 -1
  63. package/lib/protocol-grpc.js +1 -1
  64. package/lib/protocol-http.d.ts +110 -8
  65. package/lib/protocol-http.d.ts.map +1 -1
  66. package/lib/protocol-http.js +1 -1
  67. package/lib/protocol-rest.d.ts +161 -37
  68. package/lib/protocol-rest.d.ts.map +1 -1
  69. package/lib/protocol-rest.js +1 -1
  70. package/lib/protocol.d.ts +113 -0
  71. package/lib/protocol.d.ts.map +1 -0
  72. package/lib/protocol.js +0 -0
  73. package/lib/query.d.ts.map +1 -1
  74. package/lib/response-validation-strict.d.ts.map +1 -1
  75. package/lib/response-validation.d.ts.map +1 -1
  76. package/lib/retry-after.d.ts +1 -1
  77. package/lib/retry-after.d.ts.map +1 -1
  78. package/lib/retry-state.d.ts +26 -0
  79. package/lib/retry-state.d.ts.map +1 -0
  80. package/lib/retry-state.js +2 -0
  81. package/lib/retry-state.js.map +1 -0
  82. package/lib/retry.d.ts +100 -20
  83. package/lib/retry.d.ts.map +1 -1
  84. package/lib/retry.js +1 -1
  85. package/lib/schema-lite-impl.d.ts +25 -4
  86. package/lib/schema-lite-impl.d.ts.map +1 -1
  87. package/lib/schema-lite-impl.js +1 -1
  88. package/lib/schema-lite-typed.d.ts.map +1 -1
  89. package/lib/schema-lite.d.ts +1 -0
  90. package/lib/schema-lite.d.ts.map +1 -1
  91. package/lib/schema-lite.js +1 -1
  92. package/lib/schema.d.ts.map +1 -1
  93. package/lib/sdk-error.d.ts +4 -0
  94. package/lib/sdk-error.d.ts.map +1 -1
  95. package/lib/send.d.ts +37 -0
  96. package/lib/send.d.ts.map +1 -0
  97. package/lib/send.js +2 -0
  98. package/lib/send.js.map +1 -0
  99. package/lib/sensitive.d.ts.map +1 -1
  100. package/lib/sensitive.js +1 -1
  101. package/lib/sensitive.js.map +1 -1
  102. package/lib/telemetry-debug.d.ts.map +1 -1
  103. package/lib/telemetry-debug.js +1 -1
  104. package/lib/telemetry-debug.js.map +1 -1
  105. package/lib/telemetry-hooks.d.ts.map +1 -1
  106. package/lib/telemetry-host-rules.d.ts.map +1 -1
  107. package/lib/telemetry-lambda-context.d.ts.map +1 -1
  108. package/lib/telemetry-message-context.d.ts.map +1 -1
  109. package/lib/telemetry-metrics.d.ts.map +1 -1
  110. package/lib/telemetry-metrics.js +1 -1
  111. package/lib/telemetry-metrics.js.map +1 -1
  112. package/lib/telemetry-name-template.d.ts.map +1 -1
  113. package/lib/telemetry-stream.d.ts.map +1 -1
  114. package/lib/telemetry-stream.js +1 -1
  115. package/lib/telemetry-stream.js.map +1 -1
  116. package/lib/telemetry-xray.d.ts.map +1 -1
  117. package/lib/telemetry.d.ts +29 -0
  118. package/lib/telemetry.d.ts.map +1 -1
  119. package/lib/telemetry.js +2 -2
  120. package/lib/telemetry.js.map +1 -1
  121. package/lib/token-cache.d.ts +31 -0
  122. package/lib/token-cache.d.ts.map +1 -0
  123. package/lib/token-cache.js +2 -0
  124. package/lib/token-cache.js.map +1 -0
  125. package/lib/trait.d.ts +24 -1
  126. package/lib/trait.d.ts.map +1 -1
  127. package/lib/trait.js +1 -1
  128. package/lib/unknown-error.d.ts.map +1 -1
  129. package/lib/xml.d.ts.map +1 -1
  130. package/package.json +3 -3
  131. package/src/api.ts +402 -209
  132. package/src/category.ts +21 -28
  133. package/src/config.ts +17 -1
  134. package/src/errors.ts +24 -2
  135. package/src/graphql.ts +65 -26
  136. package/src/graphql.types.ts +15 -0
  137. package/src/grpc-transport-cloudflare-http2.ts +374 -299
  138. package/src/grpc-transport-cloudflare-sockets.ts +150 -81
  139. package/src/grpc-transport-node-http2.ts +119 -46
  140. package/src/grpc-transport.ts +211 -42
  141. package/src/max-message-bytes.ts +58 -0
  142. package/src/ndjson.ts +55 -0
  143. package/src/pagination.ts +26 -15
  144. package/src/plain-values.ts +30 -1
  145. package/src/protobuf.ts +40 -5
  146. package/src/protocol-grpc.ts +518 -348
  147. package/src/protocol-http.ts +474 -100
  148. package/src/protocol-rest.ts +580 -140
  149. package/src/protocol.ts +150 -0
  150. package/src/response-validation-strict.ts +9 -3
  151. package/src/retry-after.ts +1 -1
  152. package/src/retry-state.ts +105 -0
  153. package/src/retry.ts +176 -47
  154. package/src/schema-lite-impl.ts +81 -10
  155. package/src/schema-lite.ts +1 -0
  156. package/src/sdk-error.ts +4 -0
  157. package/src/send.ts +156 -0
  158. package/src/sensitive.ts +49 -15
  159. package/src/telemetry.ts +2 -34
  160. package/src/token-cache.ts +117 -0
  161. package/src/trait.ts +34 -1
@@ -196,6 +196,29 @@ export const StructWithRest = (struct: Lite, records: ReadonlyArray<Lite>): Lite
196
196
 
197
197
  const resolveObjects = (n: Node): Node => (n._tag === "Suspend" ? resolveObjects(n.thunk!()) : n);
198
198
 
199
+ /**
200
+ * `struct`'s members, then the members of `base` (a struct, possibly
201
+ * suspended) that `struct` does not declare. An operation input that inlines
202
+ * its request body is the body struct extended with the path and query
203
+ * members, without a second copy of every body field. Resolves `base`, so
204
+ * call it inside the input's `suspend`.
205
+ */
206
+ export const Extend = (base: Lite, struct: Lite): Lite => {
207
+ const own = resolveObjects(astOf(struct));
208
+ const names = new Set((own.propertySignatures ?? []).map((p) => p.name));
209
+ const inherited = resolveObjects(astOf(base)).propertySignatures ?? [];
210
+ return make(
211
+ node({
212
+ _tag: "Objects",
213
+ propertySignatures: [
214
+ ...(own.propertySignatures ?? []),
215
+ ...inherited.filter((p) => !names.has(p.name)),
216
+ ],
217
+ indexSignatures: own.indexSignatures ?? [],
218
+ }),
219
+ );
220
+ };
221
+
199
222
  /** A lazily resolved schema; `.ast` is a Suspend node whose thunk resolves the target. */
200
223
  export const suspend = (f: () => Lite): Lite => {
201
224
  let resolved: Node | undefined;
@@ -213,8 +236,22 @@ export const encodeKeysKey = "@distilled.cloud/core/schema-lite/encodeKeys";
213
236
 
214
237
  //#region declarations and errors
215
238
 
239
+ /**
240
+ * Effect Schema's `representation` annotation for its built-in declaration
241
+ * `id` (`effect/schema/Date`, ...). A lite declaration of the same type
242
+ * carries it, so {@link toEffect} rebuilds Effect's own schema for it (and
243
+ * `effect/Arbitrary` can generate values for the result).
244
+ */
245
+ export const representation = (id: string) => ({ id, payload: null });
246
+
216
247
  const declaration = (identifier: string): Lite =>
217
- make(node({ _tag: "Declaration", typeParameters: [], annotations: { identifier } }));
248
+ make(
249
+ node({
250
+ _tag: "Declaration",
251
+ typeParameters: [],
252
+ annotations: { identifier, representation: representation(`effect/schema/${identifier}`) },
253
+ }),
254
+ );
218
255
 
219
256
  export const Date: Lite = /*@__PURE__*/ declaration("Date");
220
257
  export const Duration: Lite = /*@__PURE__*/ declaration("Duration");
@@ -223,7 +260,10 @@ export const Redacted = (value: Lite): Lite =>
223
260
  node({
224
261
  _tag: "Declaration",
225
262
  typeParameters: [astOf(value)],
226
- annotations: { identifier: "Redacted" },
263
+ annotations: {
264
+ identifier: "Redacted",
265
+ representation: representation("effect/schema/Redacted"),
266
+ },
227
267
  }),
228
268
  );
229
269
  export const instanceOf = (cls: Function, annotations?: Annotations): Lite =>
@@ -231,7 +271,13 @@ export const instanceOf = (cls: Function, annotations?: Annotations): Lite =>
231
271
  node({
232
272
  _tag: "Declaration",
233
273
  typeParameters: [],
234
- annotations: { identifier: cls.name, ...annotations },
274
+ annotations: {
275
+ identifier: cls.name,
276
+ ...(cls === globalThis.Uint8Array && {
277
+ representation: representation("effect/schema/Uint8Array"),
278
+ }),
279
+ ...annotations,
280
+ },
235
281
  }),
236
282
  );
237
283
  export const declare = (_is: (u: unknown) => boolean, annotations?: Annotations): Lite =>
@@ -417,12 +463,13 @@ const AtProto: object = /*@__PURE__*/ Object.create(Proto, {
417
463
 
418
464
  //#endregion
419
465
 
420
- //#region Effect Schema bridge (strict validation only)
466
+ //#region Effect Schema bridge
421
467
 
422
468
  /**
423
- * The Effect schema equivalent to a lite node, for strict decoding. Loaded
424
- * on demand so `effect/Schema` is only bundled/imported by callers that
425
- * validate.
469
+ * The Effect schema equivalent to a lite node: the reference for strict
470
+ * decoding, and what `effect/Arbitrary` generates values from
471
+ * (`Arbitrary.schema(toEffect(Schema, op.input.ast))`). Loaded on demand so
472
+ * `effect/Schema` is only bundled/imported by callers that use it.
426
473
  */
427
474
  /** The Effect Schema functions the bridge uses (passed in, so callers import only these). */
428
475
  export type EffectSchemaApi = Pick<
@@ -446,7 +493,9 @@ export type EffectSchemaApi = Pick<
446
493
  | "make"
447
494
  | "optional"
448
495
  | "suspend"
449
- >;
496
+ > &
497
+ /** Built-in declarations; without one, a lite node of that type becomes a plain check. */
498
+ Partial<Pick<typeof import("effect/Schema"), "Date" | "Duration" | "Redacted" | "Uint8Array">>;
450
499
 
451
500
  export const toEffect = (S: EffectSchemaApi, ast: Node): unknown => {
452
501
  const memo = new Map<Node, any>();
@@ -470,6 +519,22 @@ export const toEffect = (S: EffectSchemaApi, ast: Node): unknown => {
470
519
  liteBelow.set(n, r);
471
520
  return r;
472
521
  };
522
+ // Effect's own schema for a declaration whose `representation` names one.
523
+ const builtIn = (n: Node): unknown => {
524
+ switch ((n.annotations?.representation as { id?: unknown } | undefined)?.id) {
525
+ case "effect/schema/Date":
526
+ return S.Date;
527
+ case "effect/schema/Duration":
528
+ return S.Duration;
529
+ case "effect/schema/Uint8Array":
530
+ return S.Uint8Array;
531
+ case "effect/schema/Redacted": {
532
+ const value = n.typeParameters?.[0];
533
+ return value && S.Redacted?.(build(value));
534
+ }
535
+ }
536
+ return undefined;
537
+ };
473
538
  const build = (n: Node): any => {
474
539
  const hit = memo.get(n);
475
540
  if (hit) return hit;
@@ -516,7 +581,12 @@ export const toEffect = (S: EffectSchemaApi, ast: Node): unknown => {
516
581
  case "Objects": {
517
582
  const props = n.propertySignatures ?? [];
518
583
  const records = (n.indexSignatures ?? []).map((i) =>
519
- S.Record(build(i.parameter), build(i.type)),
584
+ S.Record(
585
+ build(i.parameter),
586
+ i.type._tag === "Union" && i.type.context?.isOptional
587
+ ? S.Union([build(i.type.types![0]!), S.Undefined])
588
+ : build(i.type),
589
+ ),
520
590
  );
521
591
  if (props.length === 0 && records.length === 1) {
522
592
  out = records[0];
@@ -532,7 +602,8 @@ export const toEffect = (S: EffectSchemaApi, ast: Node): unknown => {
532
602
  break;
533
603
  }
534
604
  case "Declaration":
535
- out = n.check ? S.declare(n.check as (u: unknown) => u is unknown) : S.Unknown;
605
+ out =
606
+ builtIn(n) ?? (n.check ? S.declare(n.check as (u: unknown) => u is unknown) : S.Unknown);
536
607
  break;
537
608
  case "Unknown":
538
609
  out = S.Unknown;
@@ -12,6 +12,7 @@ export type AnyFn = (...args: any[]) => any;
12
12
  export const optional: AnyFn = L.optional;
13
13
  export const Struct: AnyFn = L.Struct;
14
14
  export const StructWithRest: AnyFn = L.StructWithRest;
15
+ export const Extend: AnyFn = L.Extend;
15
16
  export const suspend: AnyFn = L.suspend;
16
17
  export const Array: AnyFn = L.Array;
17
18
  export const Record: AnyFn = L.Record;
package/src/sdk-error.ts CHANGED
@@ -7,6 +7,10 @@
7
7
  * would. It is typed, so it fails the call instead of crashing the fiber,
8
8
  * and it is never retried.
9
9
  *
10
+ * It is also what a call fails with when something under it threw (the
11
+ * defect boundary, `failed` in `./api.ts`): the message names the operation
12
+ * and what was thrown, and `cause` is the thrown value.
13
+ *
10
14
  * Defined on its own, in core's `base` bundle group, so pagination and
11
15
  * the protocols fail with it without importing the REST modules.
12
16
  */
package/src/send.ts ADDED
@@ -0,0 +1,156 @@
1
+ /**
2
+ * Send one HTTP request for an operation: `Telemetry.execute` (spans, trace
3
+ * headers, debug output), plus the facts the retry layer reads after a
4
+ * failure (see `./retry-state.ts`): which host the request went to, whether
5
+ * it succeeded, and the response's bounded retry hint.
6
+ *
7
+ * Every protocol sends through this, so the retry budget and the
8
+ * `x-amz-retry-after` / `x-distilled-retry-after` headers work for all of
9
+ * them. A protocol that calls `client.execute` directly still retries, on
10
+ * the plain backoff, outside the budget.
11
+ *
12
+ * A body it cannot send twice (the caller's own stream) makes the call
13
+ * `oneShot`: the retry layer then never sends it again. A stream body is
14
+ * one-shot unless the protocol says otherwise (S3 replays a Blob's stream).
15
+ *
16
+ * Redirects are followed here, not by `fetch`. `fetch` removes only
17
+ * `Authorization` and `Cookie` when a redirect goes to another origin, so
18
+ * an API key in `x-api-key`, `DD-API-KEY` or `X-Auth-Token` would reach the
19
+ * new host. A hop to the same origin keeps every header; a hop to another
20
+ * origin keeps only {@link CROSS_ORIGIN_HEADERS}. Every `HttpClient` gets
21
+ * the same rule: the Node clients hand a `3xx` back too.
22
+ */
23
+ import * as Context from "effect/Context";
24
+ import * as Effect from "effect/Effect";
25
+ import * as FetchHttpClient from "effect/http/FetchHttpClient";
26
+ import * as Headers from "effect/http/Headers";
27
+ import * as HttpBody from "effect/http/HttpBody";
28
+ import type * as HttpClient from "effect/http/HttpClient";
29
+ import type * as HttpClientError from "effect/http/HttpClientError";
30
+ import * as HttpClientRequest from "effect/http/HttpClientRequest";
31
+ import type * as HttpClientResponse from "effect/http/HttpClientResponse";
32
+ import * as Url from "effect/http/Url";
33
+ import * as UrlParams from "effect/http/UrlParams";
34
+ import * as Option from "effect/Option";
35
+ import * as Result from "effect/Result";
36
+ import * as RetryState from "./retry-state.ts";
37
+ import * as Telemetry from "./telemetry.ts";
38
+
39
+ /** Redirects followed before the last `3xx` is returned as the response. */
40
+ export const MAX_REDIRECTS = 5;
41
+
42
+ /**
43
+ * The only request headers a redirect to another origin keeps. Credentials,
44
+ * signatures and provider headers are all dropped.
45
+ */
46
+ export const CROSS_ORIGIN_HEADERS: ReadonlySet<string> = new Set([
47
+ "accept",
48
+ "accept-encoding",
49
+ "accept-language",
50
+ "cache-control",
51
+ "content-language",
52
+ "content-length",
53
+ "content-type",
54
+ "if-match",
55
+ "if-modified-since",
56
+ "if-none-match",
57
+ "if-range",
58
+ "if-unmodified-since",
59
+ "range",
60
+ "user-agent",
61
+ ]);
62
+
63
+ // A browser returns an opaque response with no `Location` for
64
+ // `redirect: "manual"`, so there the browser's own redirect rule stays.
65
+ const isBrowser =
66
+ typeof (globalThis as { document?: unknown }).document !== "undefined" ||
67
+ typeof (globalThis as { importScripts?: unknown }).importScripts === "function";
68
+
69
+ /**
70
+ * The caller's `RequestInit` with `redirect: "manual"`, unless the caller
71
+ * chose a redirect mode. Only the fetch client reads it.
72
+ */
73
+ const manualRedirects = (context: Context.Context<any>): globalThis.RequestInit | undefined => {
74
+ if (isBrowser) return undefined;
75
+ const init = Context.getOrUndefined(context, FetchHttpClient.RequestInit);
76
+ return init?.redirect !== undefined ? undefined : { ...init, redirect: "manual" };
77
+ };
78
+
79
+ /**
80
+ * The request for the next hop of a redirect, or `undefined` when the
81
+ * response is not one to follow.
82
+ */
83
+ const nextHop = (
84
+ request: HttpClientRequest.HttpClientRequest,
85
+ response: HttpClientResponse.HttpClientResponse,
86
+ replayable: boolean,
87
+ ): HttpClientRequest.HttpClientRequest | undefined => {
88
+ const status = response.status;
89
+ const location = response.headers.location;
90
+ if (status < 300 || status >= 400 || status === 304 || location === undefined) return undefined;
91
+ const parsed = Url.fromString(location, request.url);
92
+ if (Result.isFailure(parsed)) return undefined;
93
+ const url = parsed.success;
94
+ url.hash = "";
95
+
96
+ let method = request.method;
97
+ let body = request.body;
98
+ let headers = request.headers;
99
+ if (
100
+ ((status === 301 || status === 302) && method === "POST") ||
101
+ (status === 303 && method !== "GET" && method !== "HEAD")
102
+ ) {
103
+ method = "GET";
104
+ body = HttpBody.empty;
105
+ headers = Headers.remove(headers, "content-type");
106
+ headers = Headers.remove(headers, "content-length");
107
+ headers = Headers.remove(headers, "content-encoding");
108
+ } else if (body._tag !== "Empty" && !replayable) {
109
+ // A 307 or 308 sends the body again, and the caller's stream is spent.
110
+ return undefined;
111
+ }
112
+ if (url.origin !== new URL(request.url).origin) {
113
+ headers = Headers.fromInput(
114
+ Object.entries(headers).filter(([name]) => CROSS_ORIGIN_HEADERS.has(name)),
115
+ );
116
+ }
117
+ // The `Location` as sent: a `URL` object would re-encode a signed query.
118
+ return HttpClientRequest.makeWith(
119
+ method,
120
+ url.href,
121
+ UrlParams.empty,
122
+ Option.none(),
123
+ headers,
124
+ body,
125
+ );
126
+ };
127
+
128
+ export const send = (
129
+ context: Context.Context<any>,
130
+ client: HttpClient.HttpClient,
131
+ request: HttpClientRequest.HttpClientRequest,
132
+ oneShot?: boolean,
133
+ ): Effect.Effect<HttpClientResponse.HttpClientResponse, HttpClientError.HttpClientError> => {
134
+ const once = oneShot ?? request.body._tag === "Stream";
135
+ const hop = (
136
+ request: HttpClientRequest.HttpClientRequest,
137
+ redirects: number,
138
+ ): Effect.Effect<HttpClientResponse.HttpClientResponse, HttpClientError.HttpClientError> =>
139
+ // Inside `suspend`: the retry layer runs this same effect again for each
140
+ // attempt, and each attempt must record its own request.
141
+ Effect.suspend(() => {
142
+ RetryState.recordRequest(request.url, once);
143
+ return Effect.flatMap(Telemetry.execute(context, client, request), (response) => {
144
+ const next = redirects < MAX_REDIRECTS ? nextHop(request, response, !once) : undefined;
145
+ if (next !== undefined) return hop(next, redirects + 1);
146
+ RetryState.recordResponse(
147
+ response.status,
148
+ response.headers as Readonly<Record<string, string | undefined>>,
149
+ );
150
+ return Effect.succeed(response);
151
+ });
152
+ });
153
+ const init = manualRedirects(context);
154
+ const sent = hop(request, 0);
155
+ return init === undefined ? sent : Effect.provideService(sent, FetchHttpClient.RequestInit, init);
156
+ };
package/src/sensitive.ts CHANGED
@@ -94,30 +94,64 @@ const isSecretValue = (type: AST.AST, v: unknown, whole: boolean): boolean =>
94
94
  ? v !== null && v !== undefined
95
95
  : typeof v === "string" || (v !== null && resolveNode(type)._tag === "Unknown");
96
96
 
97
+ /** The member names of a union's object arms, once per union. */
98
+ const armNames = /*@__PURE__*/ new WeakMap<AST.AST, ReadonlySet<string>>();
99
+ /** A struct's members by name, once per struct. */
100
+ const membersByName = /*@__PURE__*/ new WeakMap<
101
+ AST.AST,
102
+ ReadonlyMap<string, AST.PropertySignature>
103
+ >();
104
+
105
+ const byNameOf = (
106
+ node: AST.AST,
107
+ props: ReadonlyArray<AST.PropertySignature>,
108
+ ): ReadonlyMap<string, AST.PropertySignature> => {
109
+ const byName = new Map(props.map((p) => [String(p.name), p]));
110
+ membersByName.set(node, byName);
111
+ return byName;
112
+ };
113
+
114
+ /**
115
+ * `wrap`, except that a value whose type holds no sensitive value is
116
+ * returned as is: walking it would only copy it.
117
+ */
118
+ const wrapHolding = (
119
+ ast: AST.AST,
120
+ value: unknown,
121
+ whole: boolean,
122
+ siblingNames?: ReadonlySet<string>,
123
+ ): unknown => (holdsSensitive(ast) ? wrap(ast, value, whole, siblingNames) : value);
124
+
97
125
  const wrap = (
98
126
  ast: AST.AST,
99
127
  value: unknown,
100
128
  whole: boolean,
101
129
  siblingNames?: ReadonlySet<string>,
102
130
  ): unknown => {
103
- if (
104
- value === null ||
105
- typeof value !== "object" ||
106
- isOpaqueValue(value) ||
107
- Redacted.isRedacted(value)
108
- ) {
131
+ if (Redacted.isRedacted(value)) return value;
132
+ // The value's own type is sensitive: a response whose whole body is the
133
+ // secret (a bare-payload root).
134
+ if (isSensitive(ast) && isSecretValue(ast, value, whole)) return Redacted.make(value);
135
+ if (value === null || typeof value !== "object" || isOpaqueValue(value)) {
109
136
  return value;
110
137
  }
111
138
  const node = resolveNode(ast);
112
139
  if (node._tag === "Union") {
113
140
  // Redact every possible sensitive member, including in partial responses.
114
- const named = new Set(
115
- node.types.flatMap((arm) => {
116
- const armNode = resolveNode(arm);
117
- return armNode._tag === "Objects" ? getProps(armNode).map((p) => String(p.name)) : [];
118
- }),
141
+ let named = armNames.get(node);
142
+ if (named === undefined) {
143
+ named = new Set(
144
+ node.types.flatMap((arm) => {
145
+ const armNode = resolveNode(arm);
146
+ return armNode._tag === "Objects" ? getProps(armNode).map((p) => String(p.name)) : [];
147
+ }),
148
+ );
149
+ armNames.set(node, named);
150
+ }
151
+ return node.types.reduce<unknown>(
152
+ (redacted, arm) => wrapHolding(arm, redacted, whole, named),
153
+ value,
119
154
  );
120
- return node.types.reduce<unknown>((redacted, arm) => wrap(arm, redacted, whole, named), value);
121
155
  }
122
156
  if (node._tag === "Arrays") {
123
157
  if (!Array.isArray(value)) return value;
@@ -127,14 +161,14 @@ const wrap = (
127
161
  return value.map((v) =>
128
162
  sensitive && isSecretValue(elem, v, whole) && !Redacted.isRedacted(v)
129
163
  ? Redacted.make(v)
130
- : wrap(elem, v, whole),
164
+ : wrapHolding(elem, v, whole),
131
165
  );
132
166
  }
133
167
  if (node._tag === "Objects" && !Array.isArray(value)) {
134
168
  const props = getProps(node);
135
169
  const mapValue = node.indexSignatures?.[0]?.type;
136
170
  if (props.length === 0 && mapValue === undefined) return value;
137
- const byName = new Map(props.map((p) => [String(p.name), p]));
171
+ const byName = membersByName.get(node) ?? byNameOf(node, props);
138
172
  // fromEntries keeps a `__proto__` key an entry instead of the prototype.
139
173
  return Object.fromEntries(
140
174
  Object.entries(value as Record<string, unknown>).flatMap<[string, unknown]>(([k, v]) => {
@@ -146,7 +180,7 @@ const wrap = (
146
180
  if (isSensitive(type) && isSecretValue(type, v, whole)) {
147
181
  return [[k, Redacted.isRedacted(v) ? v : Redacted.make(v)]];
148
182
  }
149
- return [[k, wrap(type, v, whole)]];
183
+ return [[k, wrapHolding(type, v, whole)]];
150
184
  }),
151
185
  );
152
186
  }
package/src/telemetry.ts CHANGED
@@ -27,7 +27,6 @@
27
27
  *
28
28
  * No span is recorded unless the app installs a tracer (an exporter).
29
29
  */
30
- import * as Cause from "effect/Cause";
31
30
  import * as Context from "effect/Context";
32
31
  import * as Effect from "effect/Effect";
33
32
  import type * as Exit from "effect/Exit";
@@ -37,7 +36,6 @@ import type * as HttpClientError from "effect/http/HttpClientError";
37
36
  import * as HttpClientRequest from "effect/http/HttpClientRequest";
38
37
  import type * as HttpClientResponse from "effect/http/HttpClientResponse";
39
38
  import * as Redacted from "effect/Redacted";
40
- import * as References from "effect/References";
41
39
  import type * as AST from "effect/SchemaAST";
42
40
  import type * as Stream from "effect/Stream";
43
41
  import * as Tracer from "effect/Tracer";
@@ -688,36 +686,6 @@ const exporting = (fiber: Fiber.Fiber<unknown, unknown>): boolean => {
688
686
  return tracer !== undefined && tracer !== Tracer.nativeTracer;
689
687
  };
690
688
 
691
- /**
692
- * On failure only, add the operation as a stack frame at the caller's line,
693
- * so `Cause.pretty` prints `at S3.GetObject (user.ts:12:5)`. Success pays
694
- * one `catchCause`; no stack-frame context is provided per call.
695
- */
696
- const withFailureFrame = <A, E, R>(
697
- body: Effect.Effect<A, E, R>,
698
- name: string,
699
- callSite: (() => string | undefined) | undefined,
700
- ): Effect.Effect<A, E, R> =>
701
- callSite === undefined
702
- ? body
703
- : Effect.catchCause(body, (cause) =>
704
- Effect.withFiber((fiber) =>
705
- Effect.failCause(
706
- Cause.annotate(
707
- cause,
708
- Context.make(Cause.StackTrace, {
709
- name,
710
- stack: callSite,
711
- parent:
712
- Context.getOrUndefined(Cause.annotations(cause), Cause.StackTrace) ??
713
- fiber.getRef(References.CurrentStackFrame),
714
- }),
715
- { overwrite: true },
716
- ),
717
- ),
718
- ),
719
- );
720
-
721
689
  /**
722
690
  * One operation call (every attempt), with or without debug hooks.
723
691
  *
@@ -769,7 +737,7 @@ const traceCall = <A, E, R>(
769
737
  const span = Context.getOrUndefined(fiber.context, Tracer.ParentSpan);
770
738
  if (span !== undefined) body = Effect.provideService(body, Forward, { span, propagate });
771
739
  }
772
- return withFailureFrame(body, info.name, callSite);
740
+ return body;
773
741
  }
774
742
  const attributes: Record<string, unknown> =
775
743
  debug !== undefined
@@ -826,7 +794,7 @@ const traceCall = <A, E, R>(
826
794
  info.hold === undefined
827
795
  ? Effect.useSpan(name, options, inSpan)
828
796
  : info.hold(fiber, name, options, debug, inSpan);
829
- return withFailureFrame(traced, info.name, callSite);
797
+ return traced;
830
798
  };
831
799
 
832
800
  //#endregion
@@ -0,0 +1,117 @@
1
+ /**
2
+ * A token or credentials cache shared by every call on one layer value.
3
+ *
4
+ * The first call mints, later calls reuse the value until it goes stale, and
5
+ * calls that find a cold or stale cache while another call mints wait for
6
+ * that mint instead of starting their own: only one mint runs at a time
7
+ * (request coalescing). A waiting call never waits on the minting call
8
+ * itself: it sleeps on its own timer and checks again. In workerd one
9
+ * request's events never wake another request, and a request that waits on
10
+ * nothing of its own is cancelled as hung, so a lock, `Deferred`,
11
+ * `SynchronizedRef` or `Effect.cachedWithTTL` shared between requests fails
12
+ * there.
13
+ *
14
+ * Every mint has a time limit. A mint that runs past it is interrupted and
15
+ * fails with the caller's timeout error, and so does every call waiting on
16
+ * it. A mint that fails is not cached: the next call mints again.
17
+ *
18
+ * A mint whose owner disappears without finishing (workerd drops the
19
+ * request) can never run again. Once its time limit and
20
+ * {@link TAKEOVER_MARGIN_MS} have passed, the next waiting call mints in its
21
+ * place, and the old mint may no longer write the cache.
22
+ */
23
+ import * as Duration from "effect/Duration";
24
+ import * as Effect from "effect/Effect";
25
+ import * as Exit from "effect/Exit";
26
+
27
+ /** How often a call waiting on another call's mint checks again. */
28
+ export const POLL_MS = 20;
29
+
30
+ /**
31
+ * Default time limit of one mint. A token endpoint answers in well under a
32
+ * second; this is a ceiling for a hung endpoint, not a latency target. A
33
+ * provider whose own retries can take longer passes its own limit.
34
+ */
35
+ export const DEFAULT_MINT_TIMEOUT_MS = 60_000;
36
+
37
+ /**
38
+ * How long after a mint's time limit a waiting call takes its place. The
39
+ * owner's timeout normally ends the mint first; the margin covers a timer
40
+ * that fires late.
41
+ */
42
+ export const TAKEOVER_MARGIN_MS = 1_000;
43
+
44
+ export interface RefreshingOptions<E> {
45
+ /** Time limit of one mint, in milliseconds. @default DEFAULT_MINT_TIMEOUT_MS */
46
+ readonly timeoutMs?: number;
47
+ /** The error a mint fails with when it runs past `timeoutMs`. */
48
+ readonly onTimeout: (timeoutMs: number) => E;
49
+ }
50
+
51
+ /**
52
+ * Cache what `mint` produces. `refreshAt` gives the epoch milliseconds after
53
+ * which a value is stale (`Infinity` for never); `undefined` keeps no copy,
54
+ * so every call mints, with no waiting.
55
+ *
56
+ * Create the cache once per layer value, outside `Layer.effect`, so every
57
+ * build of the layer shares it.
58
+ */
59
+ export const refreshing = <A, E, R>(
60
+ mint: Effect.Effect<A, E, R>,
61
+ refreshAt: (value: A) => number | undefined,
62
+ options: RefreshingOptions<E>,
63
+ ): Effect.Effect<A, E, R> => {
64
+ const timeoutMs = options.timeoutMs ?? DEFAULT_MINT_TIMEOUT_MS;
65
+ const limited = Effect.timeoutOrElse(mint, {
66
+ duration: Duration.millis(timeoutMs),
67
+ orElse: () => Effect.fail(options.onTimeout(timeoutMs)),
68
+ });
69
+
70
+ let cached: { readonly value: A; readonly refreshAt: number } | undefined;
71
+ let keepsNoCopy = false;
72
+ /** The mint in progress; `exit` is set when it succeeds or fails. */
73
+ let minting: { readonly since: number; exit?: Exit.Exit<A, E> } | undefined;
74
+
75
+ const fresh = () => cached !== undefined && Date.now() < cached.refreshAt;
76
+ const takenOver = (mine: NonNullable<typeof minting>) =>
77
+ Date.now() - mine.since >= timeoutMs + TAKEOVER_MARGIN_MS;
78
+
79
+ const store = (value: A) => {
80
+ const at = refreshAt(value);
81
+ keepsNoCopy = at === undefined;
82
+ cached = at === undefined ? undefined : { value, refreshAt: at };
83
+ return value;
84
+ };
85
+
86
+ const mintAndStore = Effect.suspend(() => {
87
+ const mine: NonNullable<typeof minting> = { since: Date.now() };
88
+ minting = mine;
89
+ return limited.pipe(
90
+ // A mint another call has taken over no longer writes the cache.
91
+ Effect.map((value) => (minting === mine ? store(value) : value)),
92
+ Effect.onExit((exit) =>
93
+ Effect.sync(() => {
94
+ if (minting === mine) minting = undefined;
95
+ // An interrupted mint has no result to share: its waiters mint again.
96
+ if (!Exit.hasInterrupts(exit)) mine.exit = exit;
97
+ }),
98
+ ),
99
+ );
100
+ });
101
+
102
+ const waitFor = (mine: NonNullable<typeof minting>): Effect.Effect<A, E, R> =>
103
+ Effect.suspend(() => {
104
+ if (fresh()) return Effect.succeed(cached!.value);
105
+ if (mine.exit !== undefined) return mine.exit;
106
+ if (minting !== mine || takenOver(mine)) return get;
107
+ return Effect.andThen(Effect.sleep(POLL_MS), waitFor(mine));
108
+ });
109
+
110
+ const get: Effect.Effect<A, E, R> = Effect.suspend(() => {
111
+ if (fresh()) return Effect.succeed(cached!.value);
112
+ if (keepsNoCopy) return Effect.map(limited, store);
113
+ if (minting !== undefined && !takenOver(minting)) return waitFor(minting);
114
+ return mintAndStore;
115
+ });
116
+ return get;
117
+ };
package/src/trait.ts CHANGED
@@ -86,6 +86,14 @@ export interface HttpTrait {
86
86
  * 406). Protocols that don't read it fall back to their own default.
87
87
  */
88
88
  readonly accept?: string;
89
+ /**
90
+ * Name of the host the operation runs on, when the API serves it from a
91
+ * host other than the service's main one (DigitalOcean's `"inference"`
92
+ * for `inference.do-ai.run`). It names a host and is never a URL: the
93
+ * protocol maps it to a base URL from its credentials, so the caller's
94
+ * configuration decides where the request and its credentials go.
95
+ */
96
+ readonly server?: string;
89
97
  }
90
98
 
91
99
  export const httpSymbol = /*@__PURE__*/ Symbol.for("@distilled.cloud/core/http");
@@ -125,6 +133,19 @@ export const Body = (name?: string) => makeAnnotation(bodySymbol, name ?? true);
125
133
  export const querySymbol = /*@__PURE__*/ Symbol.for("@distilled.cloud/core/http/query");
126
134
  export const Query = (name?: string) => makeAnnotation(querySymbol, name ?? true);
127
135
 
136
+ export const idempotencyTokenSymbol = /*@__PURE__*/ Symbol.for(
137
+ "@distilled.cloud/core/idempotency-token",
138
+ );
139
+ /**
140
+ * `smithy.api#idempotencyToken`: an input member the API uses to recognize
141
+ * a retried request. When the caller leaves it out, each call fills it with
142
+ * a new UUID, and every automatic retry of that call sends the same one.
143
+ * The UUID is random (v4), or time-ordered (v7, RFC 9562) with `"uuidv7"`
144
+ * for APIs that require it (`distilled.idempotency#format` in the model).
145
+ */
146
+ export const IdempotencyToken = (format?: "uuidv7") =>
147
+ makeAnnotation(idempotencyTokenSymbol, format ?? true);
148
+
128
149
  export const commaDelimitedSymbol = /*@__PURE__*/ Symbol.for(
129
150
  "@distilled.cloud/core/http/comma-delimited",
130
151
  );
@@ -220,11 +241,23 @@ export interface UnionDiscriminator {
220
241
  * kinds of `resource_tagging`, the 34 page-rule actions -- so when the union
221
242
  * has a discriminator the protocol reads the case off it and only falls back
222
243
  * to key-set scoring for a value whose tag is missing or unknown.
244
+ *
245
+ * `dictionaries[i]` holds case `i`'s member-level `T.KeyDictionary`s by TS
246
+ * member name, which the opaque schema cannot carry on the members
247
+ * themselves. An empty one (`{}`) keeps a member's content keys as written:
248
+ * a Worker binding's `json` or `props` is the caller's own JSON. A union
249
+ * with dictionaries is mapped per case in both directions.
223
250
  */
224
251
  export const UnionCases = (
225
252
  cases: ReadonlyArray<ReadonlyArray<string>>,
226
253
  discriminator?: UnionDiscriminator,
227
- ) => makeAnnotation(unionCasesSymbol, discriminator ? { cases, discriminator } : { cases });
254
+ dictionaries?: ReadonlyArray<Readonly<Record<string, KeyDictionaryEntries>>>,
255
+ ) =>
256
+ makeAnnotation(unionCasesSymbol, {
257
+ cases,
258
+ ...(discriminator ? { discriminator } : {}),
259
+ ...(dictionaries ? { dictionaries } : {}),
260
+ });
228
261
  //#endregion
229
262
 
230
263
  //#region Error matcher traits