@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
@@ -10,7 +10,10 @@
10
10
  *
11
11
  * By default `protocol-grpc` sends through the caller's `HttpClient`
12
12
  * (`fetch`), which works where a proxy bridges HTTP/1.1 to gRPC (envoy) and
13
- * puts the status in the headers. Provide a different transport for one
13
+ * puts the status in the headers. A transport built here is Effect code: the
14
+ * body is an Effect `Stream` read in the caller's fiber, and the trailers an
15
+ * `Effect` that fails when the transport can't read them, so no failure
16
+ * turns into an empty value on the way. Provide a different transport for one
14
17
  * scope with {@link layer}:
15
18
  *
16
19
  * - `@distilled.cloud/core/grpc-transport-node-http2` speaks HTTP/2 with
@@ -27,11 +30,22 @@
27
30
  * provides.
28
31
  */
29
32
  import * as Context from "effect/Context";
33
+ import * as Deferred from "effect/Deferred";
30
34
  import * as Effect from "effect/Effect";
35
+ import * as Cookies from "effect/http/Cookies";
36
+ import * as Headers from "effect/http/Headers";
31
37
  import type * as HttpClient from "effect/http/HttpClient";
32
- import type * as HttpClientRequest from "effect/http/HttpClientRequest";
38
+ import * as HttpClientError from "effect/http/HttpClientError";
39
+ import * as HttpClientRequest from "effect/http/HttpClientRequest";
33
40
  import * as HttpClientResponse from "effect/http/HttpClientResponse";
41
+ import * as HttpIncomingMessage from "effect/http/HttpIncomingMessage";
42
+ import * as UrlParams from "effect/http/UrlParams";
43
+ import * as Inspectable from "effect/Inspectable";
34
44
  import * as Layer from "effect/Layer";
45
+ import * as Option from "effect/Option";
46
+ import { pipeArguments } from "effect/Pipeable";
47
+ import type * as Schema from "effect/Schema";
48
+ import * as Stream from "effect/Stream";
35
49
 
36
50
  /**
37
51
  * The `HttpClient` gRPC calls go through. `undefined` (the default) sends
@@ -49,12 +63,29 @@ export const layer = (client: HttpClient.HttpClient): Layer.Layer<never> =>
49
63
  /** Header and trailer names are lowercase; values as received. */
50
64
  export type Trailers = Readonly<Record<string, string>>;
51
65
 
66
+ /** What a transport hands over for a response. */
67
+ export interface Reply {
68
+ readonly status: number;
69
+ readonly headers: Trailers;
70
+ /**
71
+ * The body as it arrives. It runs in the fiber that reads the response, so
72
+ * that fiber's interruption and finalizers reach the connection.
73
+ */
74
+ readonly body: Stream.Stream<Uint8Array, unknown>;
75
+ /** The trailers, once the body has ended. Fails when they can't be read. */
76
+ readonly trailers: Effect.Effect<Trailers, unknown>;
77
+ /**
78
+ * Whether the trailers always arrive. HTTP/2 delivers them end to end;
79
+ * over HTTP/1.1 a bridging proxy may drop them, so the protocol then
80
+ * treats a reply with messages and no status as OK.
81
+ * @default true
82
+ */
83
+ readonly reliableTrailers?: boolean;
84
+ }
85
+
52
86
  // Keyed by the request the transport sent, which a response keeps as
53
87
  // `response.request` through the wrappers `HttpClient` puts around it.
54
- const trailersByRequest = /*@__PURE__*/ new WeakMap<
55
- HttpClientRequest.HttpClientRequest,
56
- { readonly trailers: Promise<Trailers>; readonly reliable: boolean }
57
- >();
88
+ const repliesByRequest = /*@__PURE__*/ new WeakMap<HttpClientRequest.HttpClientRequest, Reply>();
58
89
 
59
90
  /**
60
91
  * Whether `status` is a final HTTP status a response can carry (200 to 599).
@@ -64,55 +95,193 @@ export const isResponseStatus = (status: number): boolean =>
64
95
  Number.isInteger(status) && status >= 200 && status <= 599;
65
96
 
66
97
  /**
67
- * Build a transport's response: the status, the headers, the body as it
68
- * arrives, and the trailers, which settle once the body has ended.
98
+ * Whether a response with `status` has no body (RFC 9110 sections 15.3.5,
99
+ * 15.3.6 and 15.4.5). Its transport lets the connection go at once.
100
+ */
101
+ export const hasNoBody = (status: number): boolean =>
102
+ status === 204 || status === 205 || status === 304;
103
+
104
+ /** HTTP/2 error code (RFC 9113 section 7) -> gRPC status, where it isn't INTERNAL. */
105
+ const RESET_STATUS: ReadonlyMap<number, readonly [status: number, message: string]> =
106
+ /*@__PURE__*/ new Map([
107
+ [0x0, [13, "the server reset the stream without a grpc-status"]],
108
+ [0x7, [14, "the server refused the stream"]],
109
+ [0x8, [1, "the server cancelled the call"]],
110
+ [0xb, [8, "the server asked to slow down"]],
111
+ [0xc, [7, "the connection is not secure enough"]],
112
+ ]);
113
+
114
+ /**
115
+ * The trailers of a stream the server reset with the HTTP/2 error `code`
116
+ * before it sent a status: the gRPC status the gRPC over HTTP/2 spec maps
117
+ * the code to (`PROTOCOL-HTTP2.md`, "Errors"), as grpc-js does. The call
118
+ * fails like any other gRPC error: `REFUSED_STREAM` (the server did no work)
119
+ * as `UNAVAILABLE`, which retries, `NO_ERROR` and unknown codes as
120
+ * `INTERNAL`, which doesn't.
121
+ */
122
+ export const resetTrailers = (code: number): Trailers => {
123
+ const [status, message] = RESET_STATUS.get(code) ?? [13, "the server reset the stream"];
124
+ return { "grpc-status": String(status), "grpc-message": `${message} (HTTP/2 error ${code})` };
125
+ };
126
+
127
+ /**
128
+ * The reply for a stream the server reset with the HTTP/2 error `code`
129
+ * before its response headers: a gRPC reply of trailers alone, carrying
130
+ * {@link resetTrailers}.
131
+ */
132
+ export const resetReply = (code: number): Reply => ({
133
+ status: 200,
134
+ headers: { "content-type": "application/grpc" },
135
+ body: Stream.empty,
136
+ trailers: Effect.succeed(resetTrailers(code)),
137
+ });
138
+
139
+ /**
140
+ * Build a transport's response from its {@link Reply}. Fails with the
141
+ * `TypeError` of a head that is no valid HTTP head (a header name that is no
142
+ * token, a value with a line break), as `fetch` would. A response with
143
+ * {@link hasNoBody} has an empty body and no trailers.
69
144
  */
70
145
  export const respond = (
71
146
  request: HttpClientRequest.HttpClientRequest,
72
- reply: {
73
- readonly status: number;
74
- readonly headers: Trailers;
75
- readonly body: ReadableStream<Uint8Array>;
76
- readonly trailers: Promise<Trailers>;
77
- /**
78
- * Whether the trailers always arrive. HTTP/2 delivers them end to end;
79
- * over HTTP/1.1 a bridging proxy may drop them, so the protocol then
80
- * treats a reply with messages and no status as OK.
81
- * @default true
82
- */
83
- readonly reliableTrailers?: boolean;
84
- },
85
- ): HttpClientResponse.HttpClientResponse => {
86
- // `Response` refuses a body on these, so the transport's is let go.
87
- const bodiless = reply.status === 204 || reply.status === 205 || reply.status === 304;
88
- if (bodiless) void reply.body.cancel().catch(() => undefined);
89
- const response = HttpClientResponse.fromWeb(
90
- request,
91
- new Response(bodiless ? null : reply.body, { status: reply.status, headers: reply.headers }),
147
+ reply: Reply,
148
+ ): Effect.Effect<HttpClientResponse.HttpClientResponse, unknown> =>
149
+ Effect.try({
150
+ try: () => new globalThis.Headers(reply.headers as Record<string, string>),
151
+ catch: (cause) => cause,
152
+ }).pipe(
153
+ Effect.map(() => {
154
+ const kept = hasNoBody(reply.status)
155
+ ? { ...reply, body: Stream.empty, trailers: Effect.succeed({}) }
156
+ : reply;
157
+ repliesByRequest.set(request, kept);
158
+ return new ReplyResponse(request, kept);
159
+ }),
92
160
  );
93
- trailersByRequest.set(request, {
94
- trailers: reply.trailers,
95
- reliable: reply.reliableTrailers ?? true,
96
- });
97
- return response;
98
- };
99
161
 
100
162
  /**
101
163
  * Whether `response` came from a transport whose trailers always arrive
102
- * ({@link respond} with `reliableTrailers`), so a missing status is an error.
164
+ * ({@link Reply.reliableTrailers}), so a missing status is an error.
103
165
  */
104
- export const hasTrailers = (response: HttpClientResponse.HttpClientResponse): boolean =>
105
- trailersByRequest.get(response.request)?.reliable === true;
166
+ export const hasTrailers = (response: HttpClientResponse.HttpClientResponse): boolean => {
167
+ const reply = repliesByRequest.get(response.request);
168
+ return reply !== undefined && (reply.reliableTrailers ?? true);
169
+ };
106
170
 
107
171
  /**
108
172
  * The trailers of a response a transport built with {@link respond}, read
109
- * after its body; empty for any other response (`fetch` exposes none).
173
+ * after its body; empty for any other response (`fetch` exposes none). A
174
+ * transport that can't read them fails with a `DecodeError`.
110
175
  */
111
176
  export const trailersOf = (
112
177
  response: HttpClientResponse.HttpClientResponse,
113
- ): Effect.Effect<Trailers> => {
114
- const entry = trailersByRequest.get(response.request);
115
- return entry === undefined
178
+ ): Effect.Effect<Trailers, HttpClientError.HttpClientError> => {
179
+ const reply = repliesByRequest.get(response.request);
180
+ return reply === undefined
116
181
  ? Effect.succeed({})
117
- : Effect.tryPromise(() => entry.trailers).pipe(Effect.orElseSucceed((): Trailers => ({})));
182
+ : Effect.mapError(reply.trailers, (cause) => decodeError(response, cause));
118
183
  };
184
+
185
+ const decodeError = (response: HttpClientResponse.HttpClientResponse, cause: unknown) =>
186
+ new HttpClientError.HttpClientError({
187
+ reason: new HttpClientError.DecodeError({ request: response.request, response, cause }),
188
+ });
189
+
190
+ /**
191
+ * An `HttpClientResponse` over a {@link Reply}, built like Effect's own web
192
+ * response, with the body read from the transport's stream.
193
+ */
194
+ class ReplyResponse extends Inspectable.Class implements HttpClientResponse.HttpClientResponse {
195
+ readonly [HttpIncomingMessage.TypeId] = HttpIncomingMessage.TypeId;
196
+ readonly [HttpClientResponse.TypeId] = HttpClientResponse.TypeId;
197
+ readonly headers: Headers.Headers;
198
+ readonly cookies: Cookies.Cookies;
199
+ readonly remoteAddress = Option.none<string>();
200
+ /** The body, read once and shared by `arrayBuffer`, `text` and `json`. */
201
+ private bytes?: Deferred.Deferred<Uint8Array, HttpClientError.HttpClientError>;
202
+ readonly request: HttpClientRequest.HttpClientRequest;
203
+ private readonly reply: Reply;
204
+
205
+ constructor(request: HttpClientRequest.HttpClientRequest, reply: Reply) {
206
+ super();
207
+ this.request = request;
208
+ this.reply = reply;
209
+ this.headers = Headers.fromInput(reply.headers);
210
+ const setCookie = reply.headers["set-cookie"];
211
+ this.cookies = setCookie === undefined ? Cookies.empty : Cookies.fromSetCookie(setCookie);
212
+ }
213
+
214
+ get status(): number {
215
+ return this.reply.status;
216
+ }
217
+
218
+ get url(): string {
219
+ const url = HttpClientRequest.toUrl(this.request);
220
+ if (Option.isNone(url)) return "";
221
+ url.value.hash = "";
222
+ return url.value.href;
223
+ }
224
+
225
+ get stream(): Stream.Stream<Uint8Array, HttpClientError.HttpClientError> {
226
+ return Stream.mapError(this.reply.body, (cause) => decodeError(this, cause));
227
+ }
228
+
229
+ private get body(): Effect.Effect<Uint8Array, HttpClientError.HttpClientError> {
230
+ return Effect.suspend(() => {
231
+ if (this.bytes !== undefined) return Deferred.await(this.bytes);
232
+ const bytes = (this.bytes = Deferred.makeUnsafe());
233
+ return Effect.flatMap(Deferred.into(Stream.mkUint8Array(this.stream), bytes), () =>
234
+ Deferred.await(bytes),
235
+ );
236
+ });
237
+ }
238
+
239
+ get arrayBuffer(): Effect.Effect<ArrayBuffer, HttpClientError.HttpClientError> {
240
+ return Effect.map(this.body, (bytes) => bytes.slice().buffer as ArrayBuffer);
241
+ }
242
+
243
+ get text(): Effect.Effect<string, HttpClientError.HttpClientError> {
244
+ return Effect.map(this.body, (bytes) => new TextDecoder().decode(bytes));
245
+ }
246
+
247
+ get json(): Effect.Effect<Schema.Json, HttpClientError.HttpClientError> {
248
+ return Effect.flatMap(this.text, (text) =>
249
+ Effect.try({
250
+ try: () => (text === "" ? null : (JSON.parse(text) as Schema.Json)),
251
+ catch: (cause) => decodeError(this, cause),
252
+ }),
253
+ );
254
+ }
255
+
256
+ get urlParamsBody(): Effect.Effect<UrlParams.UrlParams, HttpClientError.HttpClientError> {
257
+ return Effect.map(this.text, (text) => UrlParams.fromInput(new URLSearchParams(text)));
258
+ }
259
+
260
+ get formData(): Effect.Effect<FormData, HttpClientError.HttpClientError> {
261
+ return Effect.fail(decodeError(this, new Error("a gRPC transport reads no form data")));
262
+ }
263
+
264
+ get upgrade(): Effect.Effect<never, HttpClientError.HttpClientError> {
265
+ return Effect.fail(
266
+ new HttpClientError.HttpClientError({
267
+ reason: new HttpClientError.StatusCodeError({
268
+ request: this.request,
269
+ response: this,
270
+ description: "a gRPC transport cannot hand over the connection of an HTTP upgrade",
271
+ }),
272
+ }),
273
+ );
274
+ }
275
+
276
+ toJSON(): unknown {
277
+ return HttpIncomingMessage.inspect(this, {
278
+ _id: "HttpClientResponse",
279
+ request: this.request.toJSON(),
280
+ status: this.status,
281
+ });
282
+ }
283
+
284
+ pipe() {
285
+ return pipeArguments(this, arguments);
286
+ }
287
+ }
@@ -0,0 +1,58 @@
1
+ /**
2
+ * The largest message a streaming protocol accepts from the server (a gRPC
3
+ * frame, an e2b envd envelope). A message whose header announces more fails
4
+ * the call before the SDK buffers it. The first of these wins:
5
+ *
6
+ * 1. The call's own `maxMessageBytes` ({@link MaxMessageBytesInput}):
7
+ * `Modal.functionGet({ ..., maxMessageBytes: 200 * 1024 * 1024 })`.
8
+ * 2. The {@link MaxMessageBytes} layer, for every call in a scope:
9
+ * `Effect.provide(MaxMessageBytes.of(200 * 1024 * 1024))`.
10
+ * 3. The protocol's own default (e.g. Modal's 100 MiB, as its official
11
+ * client), else {@link DEFAULT_MAX_MESSAGE_BYTES}.
12
+ *
13
+ * `MaxMessageBytes` is an optional service: operations do not list it in
14
+ * their requirements.
15
+ */
16
+ import * as Context from "effect/Context";
17
+ import * as Layer from "effect/Layer";
18
+
19
+ /** 16 MiB. */
20
+ export const DEFAULT_MAX_MESSAGE_BYTES = 16 * 1024 * 1024;
21
+
22
+ export class MaxMessageBytes
23
+ extends /*@__PURE__*/ Context.Service<MaxMessageBytes, number>()(
24
+ "@distilled.cloud/core/MaxMessageBytes",
25
+ ) {}
26
+
27
+ /** Accept messages up to `bytes` in a scope, e.g. `MaxMessageBytes.of(64 * 1024 * 1024)`. */
28
+ export const of = (bytes: number): Layer.Layer<MaxMessageBytes> =>
29
+ Layer.succeed(MaxMessageBytes, bytes);
30
+
31
+ /**
32
+ * The optional `maxMessageBytes` an operation input accepts. It sets the
33
+ * limit for one call, over the {@link MaxMessageBytes} layer. It is not sent
34
+ * on the wire.
35
+ */
36
+ export interface MaxMessageBytesInput {
37
+ readonly maxMessageBytes?: number;
38
+ }
39
+
40
+ /**
41
+ * The limit for one call: the input's `maxMessageBytes`, else the layer in
42
+ * `context`, else `fallback`. A value that is not a positive whole number
43
+ * is returned as an error message.
44
+ */
45
+ export const resolve = <R>(
46
+ context: Context.Context<R>,
47
+ input: unknown,
48
+ fallback: number = DEFAULT_MAX_MESSAGE_BYTES,
49
+ ): number | { readonly invalid: string } => {
50
+ const call =
51
+ input !== null && typeof input === "object"
52
+ ? (input as MaxMessageBytesInput).maxMessageBytes
53
+ : undefined;
54
+ const bytes = call ?? Context.getOrUndefined(context, MaxMessageBytes) ?? fallback;
55
+ return Number.isSafeInteger(bytes) && bytes > 0
56
+ ? bytes
57
+ : { invalid: `maxMessageBytes must be a positive whole number, got ${String(bytes)}` };
58
+ };
package/src/ndjson.ts ADDED
@@ -0,0 +1,55 @@
1
+ /**
2
+ * Newline-delimited JSON (`application/x-ndjson`) framing for REST
3
+ * server-streaming operations: the `framing` config of an
4
+ * `API.makeStreaming` operation (see `StreamFraming` in core/protocol-rest).
5
+ *
6
+ * Each non-empty line is one frame. `.stream(input)` emits each line as the
7
+ * server writes it, decoded as one element of the output's `items`; a plain
8
+ * call reads the whole body and collects the lines. A line that is not JSON
9
+ * fails with the SDK's parse error. Only programs that call such an
10
+ * operation bundle this module and `effect/Stream`.
11
+ */
12
+ import * as Effect from "effect/Effect";
13
+ import * as Stream from "effect/Stream";
14
+ import type { StreamFraming } from "./protocol-rest.ts";
15
+
16
+ const nonEmpty = (line: string): boolean => line.trim().length > 0;
17
+
18
+ /** The line as JSON, or `undefined` when it is not JSON. */
19
+ const parse = (line: string): { readonly json: unknown } | undefined => {
20
+ try {
21
+ return { json: JSON.parse(line) };
22
+ } catch {
23
+ return undefined;
24
+ }
25
+ };
26
+
27
+ export const ndjson: StreamFraming = {
28
+ collect: (text, contentType) => {
29
+ if (contentType?.split(";")[0]!.trim().toLowerCase() !== "application/x-ndjson") {
30
+ return undefined;
31
+ }
32
+ const items: unknown[] = [];
33
+ for (const line of text.split(/\r?\n/)) {
34
+ if (!nonEmpty(line)) continue;
35
+ const parsed = parse(line);
36
+ if (parsed === undefined) return { json: undefined, nonJson: true };
37
+ items.push(parsed.json);
38
+ }
39
+ return { json: { items }, nonJson: false };
40
+ },
41
+ stream: (open) =>
42
+ Stream.unwrap(
43
+ Effect.map(open, ({ body, item, invalid }) =>
44
+ body.pipe(
45
+ Stream.decodeText(),
46
+ Stream.splitLines,
47
+ Stream.filter(nonEmpty),
48
+ Stream.mapEffect((line) => {
49
+ const parsed = parse(line);
50
+ return parsed === undefined ? Effect.fail(invalid(line)) : item(parsed.json, line);
51
+ }),
52
+ ),
53
+ ),
54
+ ),
55
+ };
package/src/pagination.ts CHANGED
@@ -251,7 +251,10 @@ export const paginateCursor = <Input extends Record<string, unknown>, Output, E,
251
251
 
252
252
  /**
253
253
  * Stream of pages using token-based pagination -- pass `outputToken` back as
254
- * `inputToken` until it comes back absent.
254
+ * `inputToken` until it comes back absent or repeats a token already sent.
255
+ * Some APIs never omit the token: CloudWatch Logs `GetLogEvents` marks the end
256
+ * of a stream by echoing the `nextToken` it was sent. Empty pages still
257
+ * advance when they return a new token.
255
258
  */
256
259
  export const paginateToken = <Input extends Record<string, unknown>, Output, E, R>(
257
260
  operation: (input: Input) => Effect.Effect<Output, E, R>,
@@ -266,25 +269,33 @@ export const paginateToken = <Input extends Record<string, unknown>, Output, E,
266
269
  type State = { token: unknown; done: boolean };
267
270
  const startToken = input[inputToken];
268
271
 
269
- return Stream.unfold({ token: startToken, done: false } as State, (state) =>
270
- Effect.gen(function* () {
271
- if (state.done) return undefined;
272
+ return Stream.suspend(() => {
273
+ // Token history belongs to this traversal, not to the reusable stream.
274
+ // Only string tokens are tracked; object tokens (DynamoDB keys) are not.
275
+ const requestedTokens = new Set<string>();
276
+ return Stream.unfold({ token: startToken, done: false } as State, (state) =>
277
+ Effect.gen(function* () {
278
+ if (state.done) return undefined;
279
+ if (typeof state.token === "string") requestedTokens.add(state.token);
272
280
 
273
- const requestPayload =
274
- state.token !== undefined ? ({ ...input, [inputToken]: state.token } as Input) : input;
281
+ const requestPayload =
282
+ state.token !== undefined ? ({ ...input, [inputToken]: state.token } as Input) : input;
275
283
 
276
- const response = yield* operation(requestPayload);
284
+ const response = yield* operation(requestPayload);
277
285
 
278
- const nextToken = getPath(response, outputToken);
286
+ const nextToken = getPath(response, outputToken);
279
287
 
280
- const nextState: State = {
281
- token: nextToken,
282
- done: isTerminalToken(nextToken),
283
- };
288
+ const nextState: State = {
289
+ token: nextToken,
290
+ done:
291
+ isTerminalToken(nextToken) ||
292
+ (typeof nextToken === "string" && requestedTokens.has(nextToken)),
293
+ };
284
294
 
285
- return [response, nextState] as const;
286
- }),
287
- );
295
+ return [response, nextState] as const;
296
+ }),
297
+ );
298
+ });
288
299
  };
289
300
 
290
301
  // ============================================================================
@@ -5,13 +5,24 @@
5
5
  */
6
6
  import * as Redacted from "effect/Redacted";
7
7
 
8
+ /**
9
+ * Whether `v` is an Effect `Stream` (an upload body). Read from the
10
+ * prototype's type id, so this module does not load `effect/Stream`.
11
+ */
12
+ export const isEffectStream = (v: unknown): boolean =>
13
+ v !== null &&
14
+ typeof v === "object" &&
15
+ Object.getPrototypeOf(v) !== null &&
16
+ "~effect/Stream" in Object.getPrototypeOf(v);
17
+
8
18
  /** Binary/opaque values that must never be treated as key-value objects. */
9
19
  export const isOpaqueValue = (v: unknown): boolean =>
10
20
  v instanceof Blob ||
11
21
  v instanceof File ||
12
22
  v instanceof ArrayBuffer ||
13
23
  v instanceof Uint8Array ||
14
- v instanceof Date;
24
+ v instanceof Date ||
25
+ isEffectStream(v);
15
26
 
16
27
  const isPlainObject = (v: unknown): v is Record<string, unknown> =>
17
28
  v !== null &&
@@ -20,6 +31,24 @@ const isPlainObject = (v: unknown): v is Record<string, unknown> =>
20
31
  !isOpaqueValue(v) &&
21
32
  (Object.getPrototypeOf(v) === Object.prototype || Object.getPrototypeOf(v) === null);
22
33
 
34
+ /**
35
+ * Sets `out[key] = value` as an own property. A plain assignment to a
36
+ * `__proto__` key replaces the object's prototype; this keeps it a key, as
37
+ * `JSON.parse` does.
38
+ */
39
+ export const setOwnKey = (out: Record<string, unknown>, key: string, value: unknown): void => {
40
+ if (key === "__proto__") {
41
+ Object.defineProperty(out, key, {
42
+ value,
43
+ enumerable: true,
44
+ writable: true,
45
+ configurable: true,
46
+ });
47
+ } else {
48
+ out[key] = value;
49
+ }
50
+ };
51
+
23
52
  /**
24
53
  * Deep-unwrap `Redacted` values in an input (plain objects/arrays only --
25
54
  * class instances, files, and binary payloads pass through untouched).
package/src/protobuf.ts CHANGED
@@ -16,6 +16,7 @@
16
16
  * `optional`, message fields and `oneof` members) are omitted when absent.
17
17
  * Enum numbers map back to names, and unknown fields are skipped.
18
18
  */
19
+ import { setOwnKey } from "./plain-values.ts";
19
20
 
20
21
  /** A scalar or composite field kind. */
21
22
  export type FieldKind =
@@ -84,6 +85,11 @@ export class ProtobufDecodeError extends Error {
84
85
  readonly _tag: string = "ProtobufDecodeError";
85
86
  }
86
87
 
88
+ /** A frame whose header announces more bytes than the reader accepts. */
89
+ export class FrameTooLargeError extends ProtobufDecodeError {
90
+ override readonly _tag: string = "FrameTooLargeError";
91
+ }
92
+
87
93
  /**
88
94
  * Valid protobuf whose value proto3 JSON can't represent: a Timestamp
89
95
  * outside years 0001 to 9999, or a Duration beyond 10,000 years.
@@ -191,7 +197,9 @@ class Writer {
191
197
  class Reader {
192
198
  pos = 0;
193
199
  readonly view: DataView;
194
- constructor(readonly buf: Uint8Array) {
200
+ readonly buf: Uint8Array;
201
+ constructor(buf: Uint8Array) {
202
+ this.buf = buf;
195
203
  this.view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
196
204
  }
197
205
 
@@ -963,7 +971,7 @@ const readStruct = (bytes: Uint8Array): Record<string, unknown> => {
963
971
  else if (n === 2 && w === 2) value = readStructValue(entry.delimited());
964
972
  else entry.skip(w, n);
965
973
  }
966
- out[key] = value;
974
+ setOwnKey(out, key, value);
967
975
  }
968
976
  return out;
969
977
  };
@@ -1202,7 +1210,7 @@ export const decodeMessage = (d: ProtoDescriptors, name: string, bytes: Uint8Arr
1202
1210
  else entry.skip(w, n);
1203
1211
  }
1204
1212
  const map = (out[json] ??= {}) as Record<string, unknown>;
1205
- map[String(key)] = value;
1213
+ setOwnKey(map, String(key), value);
1206
1214
  continue;
1207
1215
  }
1208
1216
  if (repeated) {
@@ -1288,10 +1296,20 @@ export const frame = (payload: Uint8Array): Uint8Array => {
1288
1296
  * Reads gRPC message frames from a body that arrives in chunks: `push` each
1289
1297
  * chunk and get back the messages it completed. `rest` is the number of
1290
1298
  * bytes held for an incomplete frame (`0` once a body ends cleanly).
1291
- * Compressed frames are rejected; gRPC-Web trailer frames are skipped.
1299
+ * Compressed frames are rejected. A gRPC-Web trailer frame (flag `0x80`) is
1300
+ * not a message: its `name: value` lines are collected in `trailers`.
1292
1301
  */
1293
1302
  export class FrameReader {
1294
1303
  private buf: Uint8Array<ArrayBufferLike> = new Uint8Array(0);
1304
+ private readonly maxBytes: number;
1305
+
1306
+ /** `maxBytes`: the largest frame payload accepted; a larger one throws {@link FrameTooLargeError}. */
1307
+ constructor(maxBytes: number = Infinity) {
1308
+ this.maxBytes = maxBytes;
1309
+ }
1310
+
1311
+ /** The trailers of the gRPC-Web trailer frames read so far, names lowercase. */
1312
+ readonly trailers: Record<string, string> = {};
1295
1313
 
1296
1314
  get rest(): number {
1297
1315
  return this.buf.length;
@@ -1311,18 +1329,35 @@ export class FrameReader {
1311
1329
  while (pos + 5 <= this.buf.length) {
1312
1330
  const flag = this.buf[pos]!;
1313
1331
  const len = view.getUint32(pos + 1, false);
1332
+ // Checked before waiting for the payload, so it is never buffered.
1333
+ if (len > this.maxBytes) {
1334
+ throw new FrameTooLargeError(
1335
+ `a ${len}-byte gRPC message is over the ${this.maxBytes}-byte limit (maxMessageBytes)`,
1336
+ );
1337
+ }
1314
1338
  if (pos + 5 + len > this.buf.length) break;
1315
1339
  if (flag & 1 && !(flag & 0x80)) {
1316
1340
  throw new ProtobufDecodeError("compressed gRPC frames are not supported");
1317
1341
  }
1318
- if (!(flag & 0x80)) out.push(this.buf.slice(pos + 5, pos + 5 + len));
1342
+ if (flag & 0x80) this.readTrailers(this.buf.subarray(pos + 5, pos + 5 + len));
1343
+ else out.push(this.buf.slice(pos + 5, pos + 5 + len));
1319
1344
  pos += 5 + len;
1320
1345
  }
1321
1346
  this.buf = this.buf.subarray(pos);
1322
1347
  return out;
1323
1348
  }
1349
+
1350
+ private readTrailers(payload: Uint8Array): void {
1351
+ for (const line of trailerDecoder.decode(payload).split("\r\n")) {
1352
+ const colon = line.indexOf(":");
1353
+ if (colon > 0)
1354
+ this.trailers[line.slice(0, colon).trim().toLowerCase()] = line.slice(colon + 1).trim();
1355
+ }
1356
+ }
1324
1357
  }
1325
1358
 
1359
+ const trailerDecoder = /*@__PURE__*/ new TextDecoder();
1360
+
1326
1361
  /** Split a whole gRPC body into message payloads. */
1327
1362
  export const unframe = (body: Uint8Array): Uint8Array[] => {
1328
1363
  const reader = new FrameReader();