@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 817 lines 28.5 KB
Raw
1 /**
2 * Bun implementation of the Effect `HttpServer`.
3 *
4 * `make` creates a scoped HTTP server from `Bun.serve`, converting Bun
5 * `Request` values into `HttpServerRequest` values and Effect
6 * `HttpServerResponse` values back into Web `Response` values. The server
7 * supports streaming bodies, multipart requests, file responses through
8 * `BunHttpPlatform`, and WebSocket upgrades. `Bun.serve` cannot hand over the
9 * connection for other protocols, so other upgrades fail. This module also
10 * provides layers for the server alone, the Bun HTTP support services, the
11 * combined server, configurable server options, and a test server with an
12 * HTTP client.
13 *
14 * @stability unstable
15 * @since 4.0.0
16 */
17 import type { Server as BunServer, ServerWebSocket } from "bun"
18 import type * as Arr from "effect/Array"
19 import * as Cause from "effect/Cause"
20 import * as Channel from "effect/Channel"
21 import * as Config from "effect/Config"
22 import type { ConfigError } from "effect/Config"
23 import * as Context from "effect/Context"
24 import * as Deferred from "effect/Deferred"
25 import * as Duration from "effect/Duration"
26 import * as Effect from "effect/Effect"
27 import * as Exit from "effect/Exit"
28 import * as Fiber from "effect/Fiber"
29 import type * as FileSystem from "effect/FileSystem"
30 import { constVoid, flow } from "effect/Function"
31 import * as Cookies from "effect/http/Cookies"
32 import * as Etag from "effect/http/Etag"
33 import * as FetchHttpClient from "effect/http/FetchHttpClient"
34 import * as Headers from "effect/http/Headers"
35 import type { HttpClient } from "effect/http/HttpClient"
36 import * as HttpEffect from "effect/http/HttpEffect"
37 import * as IncomingMessage from "effect/http/HttpIncomingMessage"
38 import type { HttpMethod } from "effect/http/HttpMethod"
39 import type { HttpPlatform } from "effect/http/HttpPlatform"
40 import * as Server from "effect/http/HttpServer"
41 import * as Error from "effect/http/HttpServerError"
42 import * as ServerRequest from "effect/http/HttpServerRequest"
43 import * as ServerResponse from "effect/http/HttpServerResponse"
44 import type * as Multipart from "effect/http/Multipart"
45 import * as UrlParams from "effect/http/UrlParams"
46 import * as Inspectable from "effect/Inspectable"
47 import * as Layer from "effect/Layer"
48 import * as NetAddress from "effect/net/NetAddress"
49 import * as Option from "effect/Option"
50 import type * as Path from "effect/Path"
51 import type * as Record from "effect/Record"
52 import * as Result from "effect/Result"
53 import * as Scheduler from "effect/Scheduler"
54 import type * as Schema from "effect/Schema"
55 import * as Scope from "effect/Scope"
56 import * as Semaphore from "effect/Semaphore"
57 import * as Socket from "effect/socket/Socket"
58 import * as Stream from "effect/Stream"
59 import * as Platform from "./BunHttpPlatform.ts"
60 import * as BunMultipart from "./BunMultipart.ts"
61 import * as BunServices from "./BunServices.ts"
62 import * as BunStream from "./BunStream.ts"
63
64 /**
65 * Bun serve options accepted by the HTTP server, extended with typed route definitions.
66 *
67 * @stability unstable
68 * @category options
69 * @since 4.0.0
70 */
71 export type ServeOptions<R extends string> =
72 & (
73 | Bun.Serve.UnixServeOptions<WebSocketContext>
74 | Bun.Serve.HostnamePortServeOptions<WebSocketContext>
75 )
76 & { readonly routes?: Bun.Serve.Routes<WebSocketContext, R> }
77
78 /**
79 * WebSocket tuning options forwarded to `Bun.serve`'s `websocket` handler.
80 *
81 * **Details**
82 *
83 * The lifecycle handlers (`open`, `message`, `close`, ...) are managed by the
84 * server and cannot be overridden; everything else — such as
85 * `perMessageDeflate` compression, payload limits, and idle timeouts — passes
86 * through, e.g.
87 * `BunHttpServer.layer({ port: 3000, websocket: { perMessageDeflate: true } })`.
88 *
89 * The `compressionThreshold` option controls the minimum message size in bytes
90 * that is compressed when per-message deflate is negotiated. It defaults to
91 * 1024, matching the default threshold of Node's `ws` server.
92 *
93 * @stability unstable
94 * @category options
95 * @since 4.0.0
96 */
97 export type WebSocketOptions =
98 & Omit<
99 Bun.WebSocketHandler<WebSocketContext>,
100 "open" | "message" | "close" | "drain" | "ping" | "pong" | "data" | "binaryType"
101 >
102 & {
103 /**
104 * The minimum message size in bytes that is compressed when per-message
105 * deflate is negotiated.
106 *
107 * @default 1024
108 */
109 readonly compressionThreshold?: number | undefined
110 }
111
112 /**
113 * Creates a scoped Bun `HttpServer` from `Bun.serve` options, stopping the server on scope finalization with optional graceful shutdown settings.
114 *
115 * **Details**
116 *
117 * `idleTimeout` defaults to `0`, disabling Bun's 10 second idle timeout, so
118 * quiet response streams and slow uploads are bounded only by the `Stream`
119 * and `Effect` timeouts in your handlers or middleware. An explicit value is
120 * passed to Bun unchanged.
121 *
122 * **Gotchas**
123 *
124 * Without an idle timeout, Bun also keeps idle keep-alive connections and
125 * clients that stopped reading a response open, and handler timeouts cannot
126 * catch either. Directly exposed servers should set `idleTimeout` (seconds,
127 * at most 255) or sit behind a proxy with its own idle timeout.
128 *
129 * @stability unstable
130 * @category constructors
131 * @since 4.0.0
132 */
133 export const make = Effect.fnUntraced(
134 function*<R extends string>(
135 options: ServeOptions<R> & {
136 readonly disablePreemptiveShutdown?: boolean | undefined
137 readonly gracefulShutdownTimeout?: Duration.Input | undefined
138 readonly websocket?: WebSocketOptions | undefined
139 }
140 ) {
141 const scope = yield* Effect.scope
142 let listenOptions = options
143 if (!("unix" in options) || options.unix === undefined) {
144 const internetOptions = options as Bun.Serve.HostnamePortServeOptions<WebSocketContext>
145 let hostname = internetOptions.hostname ?? "::"
146 if (Result.isFailure(NetAddress.ipFromString(hostname))) {
147 hostname = yield* Effect.tryPromise({
148 try: async () => {
149 const result = await Bun.dns.lookup(hostname, { socketType: "tcp" })
150 if (result.length === 0) throw new globalThis.Error(`Could not resolve hostname: ${hostname}`)
151 return result[0].address
152 },
153 catch: (cause) => new Error.ServeError({ cause })
154 })
155 }
156 listenOptions = { ...options, hostname }
157 }
158 const { compressionThreshold = MIN_COMPRESSIBLE_SIZE, ...websocket } = options.websocket ?? {}
159 const handlerStack: Array<(request: Request, server: BunServer<WebSocketContext>) => Response | Promise<Response>> =
160 [
161 function(_request, _server) {
162 return new Response("not found", { status: 404 })
163 }
164 ]
165 const server = Bun.serve<WebSocketContext, R>({
166 // Opt-in; Effect timeouts bound requests and responses instead. Bun
167 // applies idleTimeout to Unix sockets too, although its types omit it.
168 ...{
169 ...listenOptions,
170 idleTimeout: (options as { readonly idleTimeout?: number | undefined }).idleTimeout ?? 0
171 } as ServeOptions<R>,
172 fetch: handlerStack[0],
173 websocket: {
174 ...websocket,
175 open(ws) {
176 Deferred.doneUnsafe(ws.data.deferred, Exit.succeed(ws))
177 },
178 message(ws, message) {
179 ws.data.run(message)
180 },
181 close(ws, code, closeReason) {
182 code = typeof code === "number" ? code : 1001
183 const error = new Socket.SocketError({
184 reason: new Socket.SocketCloseError({ code, closeReason })
185 })
186 ws.data.closeError = error
187 ws.data.onClose(error)
188 }
189 }
190 })
191
192 const shutdown = yield* Effect.promise(() => server.stop()).pipe(
193 Effect.cached
194 )
195 const preemptiveShutdown = options.disablePreemptiveShutdown ? Effect.void : Effect.timeoutOrElse(shutdown, {
196 duration: options.gracefulShutdownTimeout ?? Duration.seconds(20),
197 orElse: () => Effect.void
198 })
199
200 yield* Scope.addFinalizer(scope, shutdown)
201
202 const address = "unix" in options && options.unix !== undefined
203 ? NetAddress.unixPathAddress(options.unix)
204 : yield* Effect.fromResult(NetAddress.inetAddressFromIpString(server.hostname!, server.port!)).pipe(
205 Effect.mapError((cause) => new Error.ServeError({ cause }))
206 )
207
208 return Server.make({
209 address,
210 serve: Effect.fnUntraced(function*(httpApp, middleware) {
211 const parent = yield* Effect.fiber
212 const services = parent.context
213 const serveScope = Context.getUnsafe(services, Scope.Scope)
214 const scope = Scope.forkUnsafe(serveScope, "parallel")
215
216 const httpEffect = HttpEffect.toHandled(httpApp, (request, response) =>
217 Effect.sync(() => {
218 const bunRequest = request as BunServerRequest
219 bunRequest.resolve(makeResponse(bunRequest, response, services, scope))
220 if (upgradedSources.has(bunRequest.source)) return upgradedResponse
221 }), middleware)
222
223 function handler(request: Request, server: BunServer<WebSocketContext>) {
224 if (request.method === "CONNECT") {
225 return Promise.resolve(new Response(null, { status: 501 }))
226 }
227 return new Promise<Response>((resolve, _reject) => {
228 const context = Context.add(
229 services,
230 ServerRequest.HttpServerRequest,
231 new BunServerRequest(request, resolve, removeHost(request.url), server, compressionThreshold)
232 )
233 const fiber = Fiber.runIn(Effect.runForkWith(context)(httpEffect), scope)
234 request.signal.addEventListener("abort", () => {
235 // Bun aborts the signal when an upgraded WebSocket closes, which is not a client abort.
236 if (upgradedSources.has(request)) return
237 fiber.interruptUnsafe(parent.id, Error.ClientAbort.annotation)
238 }, { once: true })
239 })
240 }
241
242 yield* Scope.addFinalizerExit(serveScope, () => {
243 const index = handlerStack.indexOf(handler)
244 if (index !== -1) handlerStack.splice(index, 1)
245 server.reload({
246 fetch: handlerStack[handlerStack.length - 1],
247 ...(options.routes === undefined ? undefined : { routes: options.routes })
248 })
249 return handlerStack.length === 1 ? preemptiveShutdown : Effect.void
250 })
251 handlerStack.push(handler)
252 server.reload({
253 fetch: handler,
254 ...(options.routes === undefined ? undefined : { routes: options.routes })
255 })
256 })
257 })
258 }
259 )
260
261 const MIN_COMPRESSIBLE_SIZE = 1024
262
263 // Reported to middleware in place of the handler's discarded response.
264 const upgradedResponse = ServerResponse.empty({ status: 101 })
265
266 // Keyed by source so request copies from `modify` share the upgrade state.
267 const upgradedSources = new WeakSet<Request>()
268
269 const isRawUpgrade = (request: Request): boolean => {
270 const protocol = request.headers.get("upgrade")
271 return protocol !== null && protocol.toLowerCase() !== "websocket"
272 }
273
274 const makeResponse = (
275 request: BunServerRequest,
276 response: ServerResponse.HttpServerResponse,
277 context: Context.Context<never>,
278 scope: Scope.Scope
279 ): Response => {
280 if (ServerResponse.omitsBody(response, request.method === "HEAD")) {
281 return ServerResponse.toWeb(response, { withoutBody: true })
282 }
283 const fields: {
284 headers: globalThis.Headers
285 status?: number
286 statusText?: string
287 } = {
288 headers: new globalThis.Headers(response.headers),
289 status: response.status
290 }
291
292 if (!Cookies.isEmpty(response.cookies)) {
293 for (const header of Cookies.toSetCookieHeaders(response.cookies)) {
294 fields.headers.append("set-cookie", header)
295 }
296 }
297
298 if (response.statusText !== undefined) {
299 fields.statusText = response.statusText
300 }
301
302 response = HttpEffect.scopeTransferToStream(response)
303 const body = response.body
304 switch (body._tag) {
305 case "Empty": {
306 return new Response(undefined, fields)
307 }
308 case "Uint8Array": {
309 return new Response(body.text ?? body.body as any, fields)
310 }
311 case "Raw": {
312 if (body.body instanceof Response) {
313 return ServerResponse.toWeb(response)
314 }
315 return new Response(body.body as any, fields)
316 }
317 case "FormData": {
318 return new Response(body.formData as any, fields)
319 }
320 case "Stream": {
321 return new Response(
322 Stream.toReadableStreamWith(
323 // Attach before transforming: startup can suspend. Register the request finalizer before the first pull.
324 Stream.fromChannel(Channel.fromTransform((upstream, streamScope) =>
325 Effect.withFiber((fiber) => {
326 Fiber.runIn(fiber, scope)
327 return Channel.toTransform(body.stream.channel)(upstream, streamScope)
328 })
329 )),
330 context,
331 { signal: request.source.signal }
332 ),
333 fields
334 )
335 }
336 }
337 }
338
339 /**
340 * Layer that provides only `HttpServer` by constructing a scoped Bun server from the supplied serve options.
341 *
342 * @stability unstable
343 * @category layers
344 * @since 4.0.0
345 */
346 export const layerServer: <R extends string>(
347 options: ServeOptions<R> & {
348 readonly disablePreemptiveShutdown?: boolean | undefined
349 readonly gracefulShutdownTimeout?: Duration.Input | undefined
350 readonly websocket?: WebSocketOptions | undefined
351 }
352 ) => Layer.Layer<Server.HttpServer, Error.ServeError> = flow(make, Layer.effect(Server.HttpServer)) as any
353
354 /**
355 * Layer that provides Bun HTTP support services: `HttpPlatform`, weak ETag generation, and `BunServices`.
356 *
357 * @stability unstable
358 * @category layers
359 * @since 4.0.0
360 */
361 export const layerHttpServices: Layer.Layer<
362 | HttpPlatform
363 | Etag.Generator
364 | BunServices.BunServices
365 > = Layer.mergeAll(
366 Platform.layer,
367 Etag.layerWeak,
368 BunServices.layer
369 )
370
371 /**
372 * Layer that provides a Bun `HttpServer` together with the Bun HTTP platform, ETag generator, and Bun services.
373 *
374 * **Details**
375 *
376 * `idleTimeout` defaults to `0` (disabled); see `make`.
377 *
378 * @stability unstable
379 * @category layers
380 * @since 4.0.0
381 */
382 export const layer = <R extends string>(
383 options: ServeOptions<R> & {
384 readonly disablePreemptiveShutdown?: boolean | undefined
385 readonly gracefulShutdownTimeout?: Duration.Input | undefined
386 readonly websocket?: WebSocketOptions | undefined
387 }
388 ): Layer.Layer<
389 | Server.HttpServer
390 | HttpPlatform
391 | Etag.Generator
392 | BunServices.BunServices,
393 Error.ServeError
394 > => Layer.mergeAll(layerServer(options), layerHttpServices)
395
396 /**
397 * Layer that starts a Bun HTTP server on an ephemeral port for tests.
398 *
399 * @stability unstable
400 * @category testing
401 * @since 4.0.0
402 */
403 export const layerTest: Layer.Layer<
404 Server.HttpServer | HttpPlatform | FileSystem.FileSystem | Etag.Generator | Path.Path | HttpClient
405 > = Server.layerTestClient.pipe(
406 Layer.provide(FetchHttpClient.layer.pipe(
407 Layer.provide(Layer.succeed(FetchHttpClient.RequestInit)({ keepalive: false }))
408 )),
409 Layer.provideMerge(Layer.orDie(layer({ hostname: "127.0.0.1", port: 0 })))
410 )
411
412 /**
413 * Creates the Bun HTTP server and support-services layer from configurable serve options.
414 *
415 * @stability unstable
416 * @category layers
417 * @since 4.0.0
418 */
419 export const layerConfig = <R extends string>(
420 options: Config.Wrap<
421 ServeOptions<R> & {
422 readonly disablePreemptiveShutdown?: boolean | undefined
423 readonly gracefulShutdownTimeout?: Duration.Input | undefined
424 readonly websocket?: WebSocketOptions | undefined
425 }
426 >
427 ): Layer.Layer<
428 Server.HttpServer | HttpPlatform | FileSystem.FileSystem | Etag.Generator | Path.Path,
429 ConfigError | Error.ServeError
430 > =>
431 Layer.mergeAll(
432 Layer.effect(Server.HttpServer)(Effect.flatMap(Config.unwrap(options), make)),
433 layerHttpServices
434 )
435
436 // -----------------------------------------------------------------------------
437 // Internal
438 // -----------------------------------------------------------------------------
439
440 interface WebSocketContext {
441 readonly deferred: Deferred.Deferred<ServerWebSocket<WebSocketContext>>
442 readonly buffer: Array<Uint8Array | string>
443 closeError: Socket.SocketError | undefined
444 run: (_: Uint8Array | string) => void
445 onClose: (error: Socket.SocketError) => void
446 }
447
448 function wsDefaultRun(this: WebSocketContext, _: Uint8Array | string) {
449 this.buffer.push(_)
450 }
451
452 const formDecoder = new TextDecoder("utf-8", { ignoreBOM: true })
453
454 class BunServerRequest extends Inspectable.Class implements ServerRequest.HttpServerRequest {
455 readonly [ServerRequest.TypeId]: typeof ServerRequest.TypeId
456 readonly [IncomingMessage.TypeId]: typeof IncomingMessage.TypeId
457 readonly source: Request
458 public resolve: (response: Response) => void
459 readonly url: string
460 private bunServer: BunServer<WebSocketContext>
461 private compressionThreshold: number
462 public headersOverride?: Headers.Headers | undefined
463 private remoteAddressOverride?: Option.Option<string> | undefined
464 private peerAddressOverride?: Option.Option<string> | undefined
465 readonly protocol: "http" | "https" | undefined
466
467 constructor(
468 source: Request,
469 resolve: (response: Response) => void,
470 url: string,
471 bunServer: BunServer<WebSocketContext>,
472 compressionThreshold: number,
473 headersOverride?: Headers.Headers,
474 remoteAddressOverride?: Option.Option<string>,
475 peerAddressOverride?: Option.Option<string>,
476 protocol?: "http" | "https"
477 ) {
478 super()
479 this[ServerRequest.TypeId] = ServerRequest.TypeId
480 this[IncomingMessage.TypeId] = IncomingMessage.TypeId
481 this.source = source
482 this.resolve = resolve
483 this.url = url
484 this.bunServer = bunServer
485 this.compressionThreshold = compressionThreshold
486 this.headersOverride = headersOverride
487 this.remoteAddressOverride = remoteAddressOverride
488 this.peerAddressOverride = peerAddressOverride
489 this.protocol = protocol
490 }
491 toJSON(): unknown {
492 return IncomingMessage.inspect(this, {
493 _id: "HttpServerRequest",
494 method: this.method,
495 url: UrlParams.redactUrl(this.originalUrl)
496 })
497 }
498 modify(
499 options: {
500 readonly url?: string | undefined
501 readonly headers?: Headers.Headers | undefined
502 readonly remoteAddress?: Option.Option<string> | undefined
503 readonly peerAddress?: Option.Option<string> | undefined
504 readonly protocol?: "http" | "https" | undefined
505 }
506 ) {
507 return new BunServerRequest(
508 this.source,
509 this.resolve,
510 options.url ?? this.url,
511 this.bunServer,
512 this.compressionThreshold,
513 options.headers ?? this.headersOverride,
514 "remoteAddress" in options ? options.remoteAddress : this.remoteAddressOverride,
515 options.peerAddress ?? this.peerAddressOverride,
516 options.protocol ?? this.protocol
517 )
518 }
519 get method(): HttpMethod {
520 return this.source.method.toUpperCase() as HttpMethod
521 }
522 get originalUrl() {
523 return this.source.url
524 }
525 get remoteAddress(): Option.Option<string> {
526 return this.remoteAddressOverride ?? Option.fromNullishOr(this.bunServer.requestIP(this.source)?.address)
527 }
528 get peerAddress(): Option.Option<string> {
529 return this.peerAddressOverride ?? this.remoteAddress
530 }
531 get headers(): Headers.Headers {
532 this.headersOverride ??= Headers.fromInput(this.source.headers)
533 return this.headersOverride
534 }
535
536 private cachedCookies: Record.ReadonlyRecord<string, string> | undefined
537 get cookies() {
538 if (this.cachedCookies) {
539 return this.cachedCookies
540 }
541 return this.cachedCookies = Cookies.parseHeader(this.headers.cookie ?? "")
542 }
543
544 get stream(): Stream.Stream<Uint8Array, Error.HttpServerError> {
545 return this.source.body
546 ? BunStream.fromReadableStream({
547 evaluate: () => this.source.body ?? emptyReadbleStream,
548 onError: (cause) =>
549 new Error.HttpServerError({
550 reason: new Error.RequestParseError({
551 request: this,
552 cause
553 })
554 })
555 })
556 : Stream.fail(
557 new Error.HttpServerError({
558 reason: new Error.RequestParseError({
559 request: this,
560 description: "can not create stream from empty body"
561 })
562 })
563 )
564 }
565
566 private textEffect: Effect.Effect<string, Error.HttpServerError> | undefined
567 get text(): Effect.Effect<string, Error.HttpServerError> {
568 return this.textEffect ??= Effect.map(this.arrayBuffer, (buffer) => new TextDecoder().decode(buffer))
569 }
570
571 get json(): Effect.Effect<Schema.Json, Error.HttpServerError> {
572 return Effect.flatMap(this.text, (_) =>
573 Effect.try({
574 try: () => JSON.parse(_) as Schema.Json,
575 catch: (cause) =>
576 new Error.HttpServerError({
577 reason: new Error.RequestParseError({
578 request: this,
579 cause
580 })
581 })
582 }))
583 }
584
585 get urlParamsBody(): Effect.Effect<UrlParams.UrlParams, Error.HttpServerError> {
586 return Effect.flatMap(this.arrayBuffer, (bytes) =>
587 Effect.try({
588 // A leading "?" is form data; URLSearchParams would drop it as a query prefix.
589 try: () => UrlParams.fromInput(new URLSearchParams(formDecoder.decode(bytes).replace(/^\?/, "%3F"))),
590 catch: (cause) =>
591 new Error.HttpServerError({
592 reason: new Error.RequestParseError({
593 request: this,
594 cause
595 })
596 })
597 }))
598 }
599
600 private multipartEffect:
601 | Effect.Effect<
602 Multipart.Persisted,
603 Multipart.MultipartError,
604 Scope.Scope | FileSystem.FileSystem | Path.Path
605 >
606 | undefined
607 get multipart(): Effect.Effect<
608 Multipart.Persisted,
609 Multipart.MultipartError,
610 Scope.Scope | FileSystem.FileSystem | Path.Path
611 > {
612 if (this.multipartEffect) {
613 return this.multipartEffect
614 }
615 this.multipartEffect = Effect.runSync(Effect.cached(
616 BunMultipart.persisted(this.source)
617 ))
618 return this.multipartEffect
619 }
620
621 get multipartStream(): Stream.Stream<Multipart.Part, Multipart.MultipartError> {
622 return BunMultipart.stream(this.source)
623 }
624
625 private arrayBufferEffect: Effect.Effect<ArrayBuffer, Error.HttpServerError> | undefined
626 get arrayBuffer(): Effect.Effect<ArrayBuffer, Error.HttpServerError> {
627 if (this.arrayBufferEffect) {
628 return this.arrayBufferEffect
629 }
630 this.arrayBufferEffect = Effect.runSync(Effect.cached(
631 // Reuse the Web reader so that MaxBodySize is enforced.
632 Effect.mapError(ServerRequest.fromWeb(this.source).arrayBuffer, (error) => {
633 if (error.reason._tag !== "RequestParseError") return error
634 const { cause, reason } = error.reason
635 return new Error.HttpServerError({
636 reason: new Error.RequestParseError({ request: this, cause, ...(reason && { reason }) })
637 })
638 })
639 ))
640 return this.arrayBufferEffect
641 }
642
643 upgradeWith(
644 options: { readonly headers?: Headers.Input | undefined }
645 ): Effect.Effect<Socket.Socket, Error.HttpServerError> {
646 if (Object.keys(Headers.fromInput(options.headers)).length === 0) return this.upgrade
647 return Effect.fail(
648 new Error.HttpServerError({
649 reason: new Error.InternalError({
650 request: this,
651 description: "WebSocket upgrades do not support custom response headers"
652 })
653 })
654 )
655 }
656
657 get upgrade(): Effect.Effect<Socket.Socket, Error.HttpServerError> {
658 return Effect.callback<Socket.Socket, Error.HttpServerError>((resume) => {
659 const deferred = Deferred.makeUnsafe<ServerWebSocket<WebSocketContext>>()
660 const semaphore = Semaphore.makeUnsafe(1)
661
662 const success = this.bunServer.upgrade(this.source, {
663 data: {
664 deferred,
665 buffer: [],
666 closeError: undefined,
667 run: wsDefaultRun,
668 onClose: constVoid
669 }
670 })
671 if (!success) {
672 resume(Effect.fail(
673 new Error.HttpServerError({
674 reason: new Error.RequestParseError({
675 request: this,
676 description: isRawUpgrade(this.source)
677 ? "Bun.serve only supports WebSocket upgrades"
678 : "Not an upgradeable ServerRequest"
679 })
680 })
681 ))
682 return
683 }
684 upgradedSources.add(this.source)
685 const compressionThreshold = this.compressionThreshold
686 resume(Effect.map(Deferred.await(deferred), (ws) => {
687 const write = (chunk: Uint8Array | string | Socket.CloseEvent) =>
688 Effect.sync(() => {
689 if (typeof chunk === "string") {
690 ws.sendText(chunk, chunk.length >= compressionThreshold)
691 } else if (Socket.isCloseEvent(chunk)) {
692 ws.close(chunk.code, chunk.reason)
693 } else {
694 ws.sendBinary(chunk, chunk.byteLength >= compressionThreshold)
695 }
696 })
697 const writeAll = (chunks: ReadonlyArray<Uint8Array | string>) =>
698 Effect.sync(() => {
699 for (let i = 0; i < chunks.length; i++) {
700 const chunk = chunks[i]
701 if (typeof chunk === "string") {
702 ws.sendText(chunk, chunk.length >= compressionThreshold)
703 } else {
704 ws.sendBinary(chunk, chunk.byteLength >= compressionThreshold)
705 }
706 }
707 })
708 const writer: Socket.Socket["writer"] = Effect.succeed({ write, writeAll })
709
710 const reader: Socket.Socket["reader"] = Effect.gen(function*() {
711 const dispatcher = (yield* Scheduler.Scheduler).makeDispatcher()
712 yield* Effect.acquireRelease(semaphore.take(1), () => semaphore.release(1))
713 const closeError = ws.data.closeError ?? (ws.readyState >= 2
714 ? new Socket.SocketError({
715 reason: new Socket.SocketCloseError({ code: 1006 })
716 })
717 : undefined)
718 if (closeError !== undefined && ws.data.buffer.length === 0) {
719 return yield* closeError
720 }
721 const scope = yield* Effect.scope
722
723 type ReadResume = (
724 effect: Effect.Effect<Arr.NonEmptyReadonlyArray<Uint8Array | string>, Socket.SocketError>
725 ) => void
726
727 let buffer: Array<Uint8Array | string> = ws.data.buffer.splice(0)
728 let error: Socket.SocketError | undefined = closeError
729 let waiter: ReadResume | undefined
730 let flushScheduled = false
731
732 function takeBuffer(): Arr.NonEmptyReadonlyArray<Uint8Array | string> {
733 const chunk = buffer
734 buffer = []
735 return chunk as unknown as Arr.NonEmptyReadonlyArray<Uint8Array | string>
736 }
737 function deliver() {
738 flushScheduled = false
739 if (waiter === undefined || buffer.length === 0) return
740 const resumeRead = waiter
741 waiter = undefined
742 resumeRead(Effect.succeed(takeBuffer()))
743 }
744 function push(data: Uint8Array | string) {
745 buffer.push(data)
746 if (waiter !== undefined && !flushScheduled) {
747 flushScheduled = true
748 dispatcher.scheduleTask(deliver, 0)
749 }
750 }
751 function fail(err: Socket.SocketError) {
752 if (error === undefined) error = err
753 if (waiter !== undefined) {
754 const resumeRead = waiter
755 waiter = undefined
756 resumeRead(buffer.length > 0 ? Effect.succeed(takeBuffer()) : Effect.fail(error))
757 }
758 }
759
760 ws.data.run = push
761 ws.data.onClose = fail
762 yield* Scope.addFinalizerExit(
763 scope,
764 (exit) =>
765 Effect.suspend(() => {
766 // resume a pull blocked in another fiber before detaching
767 fail(
768 new Socket.SocketError({
769 reason: new Socket.SocketCloseError({ code: 1006 })
770 })
771 )
772 ws.data.run = wsDefaultRun
773 ws.data.onClose = constVoid
774 ws.close(closeCode(exit))
775 return Effect.void
776 })
777 )
778
779 return {
780 pull: Effect.callback<
781 Arr.NonEmptyReadonlyArray<Uint8Array | string>,
782 Socket.SocketError
783 >((resumeRead) => {
784 if (buffer.length > 0) return resumeRead(Effect.succeed(takeBuffer()))
785 if (error !== undefined) return resumeRead(Effect.fail(error))
786 waiter = resumeRead
787 return Effect.sync(() => {
788 if (waiter === resumeRead) waiter = undefined
789 })
790 }),
791 upgrade: Socket.SocketUpgradeError.unsupported
792 }
793 })
794
795 return Socket.make({ reader, writer })
796 }))
797 })
798 }
799 }
800
801 const closeCode = (exit: Exit.Exit<unknown, unknown>): number =>
802 Exit.isSuccess(exit) ? 1000 : Cause.hasInterruptsOnly(exit.cause) ? 1001 : 1011
803
804 const emptyReadbleStream = new ReadableStream({
805 start(controller) {
806 controller.enqueue(new Uint8Array())
807 controller.close()
808 }
809 })
810
811 const removeHost = (url: string) => {
812 if (url[0] === "/") {
813 return url
814 }
815 const index = url.indexOf("/", url.indexOf("//") + 2)
816 return index === -1 ? "/" : url.slice(index)
817 }