keryx 0.41.2 → 0.41.3
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/classes/Action.ts +7 -1
- package/classes/StreamingResponse.ts +13 -4
- package/package.json +1 -1
- package/servers/web.ts +22 -5
- package/util/webCompression.ts +113 -11
- package/util/webStreaming.ts +47 -0
package/classes/Action.ts
CHANGED
|
@@ -160,7 +160,13 @@ export type ActionConstructorInputs = {
|
|
|
160
160
|
route?: RegExp | string;
|
|
161
161
|
/** HTTP method to bind the route to */
|
|
162
162
|
method?: HTTP_METHOD;
|
|
163
|
-
/**
|
|
163
|
+
/**
|
|
164
|
+
* Declares this endpoint as a stream. Swagger documents it as returning
|
|
165
|
+
* `text/event-stream` instead of JSON, and the web server passes the response body
|
|
166
|
+
* through untouched — no compression, no idle timeout — so chunks reach the client as
|
|
167
|
+
* they are produced. Returning a `StreamingResponse` gets that treatment on its own;
|
|
168
|
+
* set this when the action hands back a raw `Response` wrapping a stream.
|
|
169
|
+
*/
|
|
164
170
|
streaming?: boolean;
|
|
165
171
|
};
|
|
166
172
|
|
|
@@ -4,6 +4,8 @@
|
|
|
4
4
|
* WebSocket (incremental messages), or MCP (logging messages + accumulated result).
|
|
5
5
|
*/
|
|
6
6
|
|
|
7
|
+
import { markStreamingResponse } from "../util/webStreaming";
|
|
8
|
+
|
|
7
9
|
const encoder = new TextEncoder();
|
|
8
10
|
|
|
9
11
|
/**
|
|
@@ -71,6 +73,11 @@ export class StreamingResponse {
|
|
|
71
73
|
* the provided base headers (CORS, security, session cookie, etc.) with
|
|
72
74
|
* the streaming-specific headers.
|
|
73
75
|
*
|
|
76
|
+
* The result is marked as a stream (see `markStreamingResponse`) so the web server
|
|
77
|
+
* passes the body through untouched — no compression, no idle timeout — regardless
|
|
78
|
+
* of content type. Without the mark, anything other than `text/event-stream` would
|
|
79
|
+
* be buffered to completion before the first byte reached the client.
|
|
80
|
+
*
|
|
74
81
|
* @param baseHeaders - Headers from `buildHeaders()` to merge in.
|
|
75
82
|
* @returns A native `Response` with the stream as its body.
|
|
76
83
|
*/
|
|
@@ -78,10 +85,12 @@ export class StreamingResponse {
|
|
|
78
85
|
const mergedHeaders = { ...baseHeaders, ...this.headers };
|
|
79
86
|
mergedHeaders["Content-Type"] = this.contentType;
|
|
80
87
|
|
|
81
|
-
return
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
88
|
+
return markStreamingResponse(
|
|
89
|
+
new Response(this.stream, {
|
|
90
|
+
status: 200,
|
|
91
|
+
headers: mergedHeaders,
|
|
92
|
+
}),
|
|
93
|
+
);
|
|
85
94
|
}
|
|
86
95
|
}
|
|
87
96
|
|
package/package.json
CHANGED
package/servers/web.ts
CHANGED
|
@@ -30,6 +30,10 @@ import {
|
|
|
30
30
|
} from "../util/webSocket";
|
|
31
31
|
import { shouldWarnStackLeak } from "../util/webStackLeakWarning";
|
|
32
32
|
import { handleStaticFile } from "../util/webStaticFiles";
|
|
33
|
+
import {
|
|
34
|
+
isStreamingResponse,
|
|
35
|
+
markStreamingResponse,
|
|
36
|
+
} from "../util/webStreaming";
|
|
33
37
|
|
|
34
38
|
/**
|
|
35
39
|
* Per-request context passed to {@link BeforeRequestHook} and {@link AfterRequestHook}.
|
|
@@ -285,8 +289,10 @@ export class WebServer extends Server<ReturnType<typeof Bun.serve>> {
|
|
|
285
289
|
await hook(req, response, ctx, outcome);
|
|
286
290
|
}
|
|
287
291
|
|
|
288
|
-
// SSE
|
|
289
|
-
|
|
292
|
+
// Streaming responses (SSE, chunked downloads, proxied bodies): disable the idle
|
|
293
|
+
// timeout so a stream that goes quiet between chunks is not cut, and skip compression
|
|
294
|
+
// so the body is passed through byte-for-byte as it is produced.
|
|
295
|
+
if (isStreamingResponse(response)) {
|
|
290
296
|
server.timeout(req, 0);
|
|
291
297
|
return response;
|
|
292
298
|
}
|
|
@@ -606,10 +612,21 @@ export class WebServer extends Server<ReturnType<typeof Bun.serve>> {
|
|
|
606
612
|
errorStatusCode = ErrorStatusCodes[error.type];
|
|
607
613
|
}
|
|
608
614
|
|
|
615
|
+
const builtResponse = error
|
|
616
|
+
? buildError(connection, error, errorStatusCode, requestOrigin)
|
|
617
|
+
: buildResponse(connection, response, 200, requestOrigin);
|
|
618
|
+
|
|
619
|
+
// An action that declares `web.streaming` can also hand back a raw `Response` wrapping a
|
|
620
|
+
// stream (a proxied upstream, `Bun.file()`, an LLM relay). Treat the declaration as a
|
|
621
|
+
// transport hint so those bodies get the same pass-through treatment as a
|
|
622
|
+
// `StreamingResponse`. Errors are ordinary JSON, so they stay compressible.
|
|
623
|
+
if (!error && actionName) {
|
|
624
|
+
const action = api.actions.actions.find((a) => a.name === actionName);
|
|
625
|
+
if (action?.web?.streaming) markStreamingResponse(builtResponse);
|
|
626
|
+
}
|
|
627
|
+
|
|
609
628
|
return {
|
|
610
|
-
response:
|
|
611
|
-
? buildError(connection, error, errorStatusCode, requestOrigin)
|
|
612
|
-
: buildResponse(connection, response, 200, requestOrigin),
|
|
629
|
+
response: builtResponse,
|
|
613
630
|
actionName: actionName ?? undefined,
|
|
614
631
|
};
|
|
615
632
|
}
|
package/util/webCompression.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { config } from "../config";
|
|
2
|
+
import { isStreamingResponse } from "./webStreaming";
|
|
2
3
|
|
|
3
4
|
const INCOMPRESSIBLE_TYPES = new Set([
|
|
4
5
|
"image/png",
|
|
@@ -71,13 +72,103 @@ function compressBody(body: ReadableStream, response: Response): Response {
|
|
|
71
72
|
return new Response(stream, { status: response.status, headers });
|
|
72
73
|
}
|
|
73
74
|
|
|
75
|
+
/**
|
|
76
|
+
* Reader/stream shapes described structurally, because Bun's and Node's `ReadableStream`
|
|
77
|
+
* typings disagree over members like `readMany` — a `Response.body` satisfies either.
|
|
78
|
+
*/
|
|
79
|
+
type BodyReader = {
|
|
80
|
+
read(): Promise<{ done: boolean; value?: Uint8Array }>;
|
|
81
|
+
cancel(reason?: unknown): Promise<void>;
|
|
82
|
+
};
|
|
83
|
+
type BodyStream = { getReader(): BodyReader };
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Read from a body stream until at least `limit` bytes are buffered or the stream ends.
|
|
87
|
+
*
|
|
88
|
+
* Used to answer "does this response clear the compression threshold?" for bodies with no
|
|
89
|
+
* `Content-Length`, without draining the whole body. The reader is returned still locked to
|
|
90
|
+
* the stream so the caller can resume from where this stopped.
|
|
91
|
+
*
|
|
92
|
+
* @param body The response body to read from.
|
|
93
|
+
* @param limit Stop reading once this many bytes have been buffered.
|
|
94
|
+
* @returns The buffered chunks, their total size, whether the stream ended, and the reader.
|
|
95
|
+
*/
|
|
96
|
+
async function readUpTo(
|
|
97
|
+
body: BodyStream,
|
|
98
|
+
limit: number,
|
|
99
|
+
): Promise<{
|
|
100
|
+
chunks: Uint8Array[];
|
|
101
|
+
size: number;
|
|
102
|
+
ended: boolean;
|
|
103
|
+
reader: BodyReader;
|
|
104
|
+
}> {
|
|
105
|
+
const reader = body.getReader();
|
|
106
|
+
const chunks: Uint8Array[] = [];
|
|
107
|
+
let size = 0;
|
|
108
|
+
|
|
109
|
+
while (size < limit) {
|
|
110
|
+
const { done, value } = await reader.read();
|
|
111
|
+
if (done) return { chunks, size, ended: true, reader };
|
|
112
|
+
if (value?.byteLength) {
|
|
113
|
+
chunks.push(value);
|
|
114
|
+
size += value.byteLength;
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
return { chunks, size, ended: false, reader };
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* Flatten buffered chunks into a single view over a fresh `ArrayBuffer` of exactly `size`
|
|
123
|
+
* bytes — a concrete `ArrayBuffer` rather than `ArrayBufferLike`, so the result is a valid
|
|
124
|
+
* `BodyInit` under both the Bun and DOM lib typings.
|
|
125
|
+
*/
|
|
126
|
+
function concatChunks(
|
|
127
|
+
chunks: Uint8Array[],
|
|
128
|
+
size: number,
|
|
129
|
+
): Uint8Array<ArrayBuffer> {
|
|
130
|
+
const out = new Uint8Array(new ArrayBuffer(size));
|
|
131
|
+
let offset = 0;
|
|
132
|
+
for (const chunk of chunks) {
|
|
133
|
+
out.set(chunk, offset);
|
|
134
|
+
offset += chunk.byteLength;
|
|
135
|
+
}
|
|
136
|
+
return out;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* Rebuild a body stream from the chunks already read plus the rest of the reader, so a
|
|
141
|
+
* partially-consumed body can be piped onward without buffering what remains.
|
|
142
|
+
*/
|
|
143
|
+
function restoreStream(
|
|
144
|
+
chunks: Uint8Array[],
|
|
145
|
+
reader: BodyReader,
|
|
146
|
+
): ReadableStream<Uint8Array> {
|
|
147
|
+
return new ReadableStream<Uint8Array>({
|
|
148
|
+
start(controller) {
|
|
149
|
+
for (const chunk of chunks) controller.enqueue(chunk);
|
|
150
|
+
},
|
|
151
|
+
async pull(controller) {
|
|
152
|
+
const { done, value } = await reader.read();
|
|
153
|
+
if (done) return controller.close();
|
|
154
|
+
if (value) controller.enqueue(value);
|
|
155
|
+
},
|
|
156
|
+
cancel(reason) {
|
|
157
|
+
return reader.cancel(reason);
|
|
158
|
+
},
|
|
159
|
+
});
|
|
160
|
+
}
|
|
161
|
+
|
|
74
162
|
/**
|
|
75
163
|
* Conditionally compress an HTTP response based on the client's `Accept-Encoding` header,
|
|
76
164
|
* the response content type, and the configured compression threshold.
|
|
77
165
|
*
|
|
78
166
|
* Uses the Web Streams `CompressionStream` API for async, non-blocking compression.
|
|
79
|
-
* Skips compression for empty bodies, already-encoded responses,
|
|
80
|
-
* types, and responses below the size threshold.
|
|
167
|
+
* Skips compression for empty bodies, streaming responses, already-encoded responses,
|
|
168
|
+
* incompressible content types, and responses below the size threshold.
|
|
169
|
+
*
|
|
170
|
+
* Bodies with no `Content-Length` are measured by reading at most `threshold` bytes, never
|
|
171
|
+
* the whole body — memory stays bounded and a large or slow response keeps flowing.
|
|
81
172
|
*
|
|
82
173
|
* @param response The original Response to potentially compress
|
|
83
174
|
* @param req The incoming Request (used to read Accept-Encoding)
|
|
@@ -92,9 +183,10 @@ export async function compressResponse(
|
|
|
92
183
|
// No body to compress
|
|
93
184
|
if (!response.body) return response;
|
|
94
185
|
|
|
95
|
-
// Never
|
|
96
|
-
|
|
97
|
-
|
|
186
|
+
// Never touch a streaming body — SSE, chunked downloads, proxied responses. Compressing
|
|
187
|
+
// one would mean handing it to a CompressionStream that is free to withhold output until
|
|
188
|
+
// it has enough bytes to be worth a gzip block, which defeats incremental delivery.
|
|
189
|
+
if (isStreamingResponse(response)) return response;
|
|
98
190
|
|
|
99
191
|
// Already compressed
|
|
100
192
|
if (response.headers.get("Content-Encoding")) return response;
|
|
@@ -118,18 +210,28 @@ export async function compressResponse(
|
|
|
118
210
|
return response;
|
|
119
211
|
}
|
|
120
212
|
|
|
121
|
-
//
|
|
122
|
-
//
|
|
213
|
+
// Without a Content-Length the size is unknown until the body is read — which covers most
|
|
214
|
+
// of our responses (JSON action responses, error responses). Read only as far as the
|
|
215
|
+
// threshold, which is all it takes to answer "is this worth compressing?", then either
|
|
216
|
+
// return the buffered bytes as-is or stream-compress the buffered prefix plus the rest.
|
|
217
|
+
// Draining the whole body here would hold an arbitrarily large response in memory and
|
|
218
|
+
// stall delivery until the body closed.
|
|
123
219
|
if (!contentLength) {
|
|
124
|
-
const
|
|
125
|
-
|
|
126
|
-
|
|
220
|
+
const threshold = config.server.web.compression.threshold;
|
|
221
|
+
const { chunks, size, ended, reader } = await readUpTo(
|
|
222
|
+
response.body,
|
|
223
|
+
threshold,
|
|
224
|
+
);
|
|
225
|
+
|
|
226
|
+
if (ended) {
|
|
227
|
+
// The whole body fit under the threshold, so send exactly those bytes back.
|
|
228
|
+
return new Response(size > 0 ? concatChunks(chunks, size) : null, {
|
|
127
229
|
status: response.status,
|
|
128
230
|
headers: response.headers,
|
|
129
231
|
});
|
|
130
232
|
}
|
|
131
233
|
|
|
132
|
-
return compressBody(
|
|
234
|
+
return compressBody(restoreStream(chunks, reader), response);
|
|
133
235
|
}
|
|
134
236
|
|
|
135
237
|
// Content-Length is present and above threshold — stream-compress
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Transport-level bookkeeping for streaming HTTP responses.
|
|
3
|
+
*
|
|
4
|
+
* A `Response` whose body is produced incrementally must not be buffered, compressed,
|
|
5
|
+
* or cut short by an idle timeout. There is no way to detect that from the `Response`
|
|
6
|
+
* itself — every `Response` body is a `ReadableStream`, and a streaming body has no
|
|
7
|
+
* `Content-Length` to distinguish it from a small JSON payload. So the code that
|
|
8
|
+
* *creates* the response marks it here, and the web server reads the mark back when
|
|
9
|
+
* deciding whether to compress and whether to disarm Bun's idle timeout.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Responses known to be streams. A `WeakSet` keeps this out of the response's own
|
|
14
|
+
* headers (nothing leaks to the client) and lets the entries be collected with the
|
|
15
|
+
* responses themselves.
|
|
16
|
+
*/
|
|
17
|
+
const streamingResponses = new WeakSet<Response>();
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Mark a response as a stream so the web server skips compression and disables the
|
|
21
|
+
* idle timeout for it.
|
|
22
|
+
*
|
|
23
|
+
* @param response - The response to mark. Returned as-is for call-site chaining.
|
|
24
|
+
* @returns The same response instance that was passed in.
|
|
25
|
+
*/
|
|
26
|
+
export function markStreamingResponse<T extends Response>(response: T): T {
|
|
27
|
+
streamingResponses.add(response);
|
|
28
|
+
return response;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Check whether a response should be treated as a stream.
|
|
33
|
+
*
|
|
34
|
+
* True for responses explicitly marked by {@link markStreamingResponse} (anything from
|
|
35
|
+
* `StreamingResponse.toResponse()`, plus raw `Response` passthrough from actions that
|
|
36
|
+
* declare `web.streaming`), and for any `text/event-stream` response regardless of
|
|
37
|
+
* origin — SSE is always incremental.
|
|
38
|
+
*
|
|
39
|
+
* @param response - The response to inspect.
|
|
40
|
+
* @returns True when the body must be passed through untouched.
|
|
41
|
+
*/
|
|
42
|
+
export function isStreamingResponse(response: Response): boolean {
|
|
43
|
+
if (streamingResponses.has(response)) return true;
|
|
44
|
+
return (
|
|
45
|
+
response.headers.get("Content-Type")?.includes("text/event-stream") ?? false
|
|
46
|
+
);
|
|
47
|
+
}
|