Skip to content
Source
Sign inSign up
samwillis/neon-durable-streams
Open History to see the last commit

response-body.ts

52 lines2.0 KB

1import { StreamError } from './errors.js'
2​
3/** Stream an owned, verified page without Fetch's BufferSource body copy. */
4export function ownedResponseBody(bytes: Uint8Array, options: {
5 readonly signal: AbortSignal
6 readonly release: () => void
7 readonly timeoutMs: number
8 readonly expiresAt?: number
9}): ReadableStream<Uint8Array> {
10 let payload: Uint8Array | undefined = bytes
11 let position = 0
12 const deadline = performance.now() + options.timeoutMs
13 let controller: ReadableStreamDefaultController<Uint8Array>
14 const finish = () => {
15 if (!payload) return
16 payload = undefined
17 clearTimeout(timer)
18 options.signal.removeEventListener('abort', abort)
19 options.release()
20 }
21 const abort = () => {
22 if (!payload) return
23 finish()
24 controller.error(options.signal.reason ?? new StreamError(408, 'REQUEST_ABORTED', 'Request aborted'))
25 }
26 const lifetime = options.expiresAt === undefined ? options.timeoutMs : Math.min(options.timeoutMs, Math.max(1, options.expiresAt - Date.now()))
27 const timer = setTimeout(() => {
28 if (!payload) return
29 finish()
30 controller.error(new StreamError(503, 'RESPONSE_DEADLINE', 'Response deadline exceeded; resume from the durable checkpoint'))
31 }, lifetime).unref()
32 return new ReadableStream<Uint8Array>({
33 start(value) {
34 controller = value
35 options.signal.addEventListener('abort', abort, { once: true })
36 if (options.signal.aborted) abort()
37 },
38 pull(value) {
39 if (!payload) return
40 if (performance.now() >= deadline || (options.expiresAt !== undefined && Date.now() >= options.expiresAt)) {
41 finish()
42 value.error(new StreamError(408, 'RESPONSE_EXPIRED', 'Response expired; resume from the durable checkpoint'))
43 return
44 }
45 if (position === payload.byteLength) { finish(); value.close(); return }
46 const end = Math.min(payload.byteLength, position + 65536)
47 value.enqueue(payload.subarray(position, end))
48 position = end
49 },
50 cancel() { finish() },
51 }, { highWaterMark: 0 })