import type * as cf from "@cloudflare/workers-types"; import * as Context from "effect/Context"; import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; import * as EffectHttp from "effect/http/HttpEffect"; import { ClientAbort } from "effect/http/HttpServerError"; import * as HttpServerRequest from "effect/http/HttpServerRequest"; import * as HttpServerResponse from "effect/http/HttpServerResponse"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Scope from "effect/Scope"; import * as Http from "../../Http.ts"; import { EventLifetime } from "../EventLifetime.ts"; import { Request } from "./Request.ts"; /** * Run an Effect HTTP handler against a workerd `Request` and resolve the * web `Response` it produces. The handler sees the request both as Effect's * `HttpServerRequest` and as the raw web {@link Request}. */ export const makeRequestEffect = ( webRequest: cf.Request, handler: Http.HttpEffect | Effect.Effect>, /** A Worker fetch's context. With it, a client abort interrupts the handler. */ ctx?: cf.ExecutionContext, ) => { const signal = ctx && (webRequest as any as globalThis.Request).signal; const safeHandler = Http.safeHttpEffect(handler); return Effect.gen(function* () { const request = HttpServerRequest.fromWeb(webRequest as any as globalThis.Request).modify({ remoteAddress: Option.fromUndefinedOr( webRequest.headers.get("cf-connecting-ip") ?? undefined, ), }); Object.defineProperty(request, "raw", { get: () => Object.assign(request.stream, { raw: webRequest.body, }), }); // `toHandled` runs the request uninterruptibly; the handler opts back in, // as `HttpRouter` routes do, so a client abort reaches it. return yield* toHandledWebResponse( signal ? Effect.interruptible(safeHandler) : safeHandler, ).pipe( Effect.provide([ Layer.succeed(HttpServerRequest.HttpServerRequest, request), Layer.succeed(Request, webRequest as any), ]), ); }).pipe(interruptOnClientAbort(signal, ctx)) as any; }; /** * Interrupts the request fiber when the client disconnects, as Effect's * `HttpEffect.toWebHandler` does, annotated with `ClientAbort` so * `causeResponse` answers 499. The signal only fires under the * `enable_request_signal` compatibility flag. * * workerd cancels the event's pending I/O once the client is gone, so the * abort also registers the fiber with `waitUntil`, letting the handler's * finalizers finish. */ const interruptOnClientAbort = (signal: AbortSignal | undefined, ctx: cf.ExecutionContext | undefined) => (self: Effect.Effect) => signal === undefined || ctx === undefined ? self : Effect.withFiber((fiber) => { const onAbort = () => { ctx.waitUntil(new Promise((resolve) => fiber.addObserver(() => resolve()))); fiber.interruptUnsafe(undefined, ClientAbort.annotation); }; if (signal.aborted) { onAbort(); } else { signal.addEventListener("abort", onAbort, { once: true }); fiber.addObserver(() => signal.removeEventListener("abort", onAbort)); } return self; }); const toHandledWebResponse = ( handler: Effect.Effect, ) => Effect.gen(function* () { // `toHandled` exposes the final response through this callback, not its // return value. Keep the assignment isolated here so callers get Response. const context = yield* Effect.context(); const webResponse = yield* Deferred.make(); // Under a Worker or Durable Object bridge the event's scope closes once // the handler, its streamed body and its `waitUntil` work have all // settled. `toHandled` opens a request scope of its own and closes it as // soon as the response is written, so the handler runs on the event's // scope instead and Effect's request scope stays empty. const lifetime = Context.getOption(context, EventLifetime); const eventScope = Context.getOption(context, Scope.Scope); yield* EffectHttp.toHandled( Option.isSome(lifetime) && Option.isSome(eventScope) ? Effect.provideService(handler, Scope.Scope, eventScope.value) : handler, (request, response) => Effect.gen(function* () { const withoutBody = request.method === "HEAD"; if (!HttpServerResponse.omitsBody(response, withoutBody)) { response = Option.isSome(lifetime) ? yield* extendWithBody(response, lifetime.value) : EffectHttp.scopeTransferToStream(response); } return yield* Deferred.succeed( webResponse, HttpServerResponse.toWeb(response, { withoutBody, context }), ); }), ); return yield* Deferred.await(webResponse); }); /** * Keep the event open until a streamed `response` body settles: Effect's * `scopeTransferToStream` closes the fiber's scope when the body exits, so * hand it one whose close only tells the event. */ const extendWithBody = ( response: HttpServerResponse.HttpServerResponse, lifetime: EventLifetime["Service"], ) => { if (response.body._tag !== "Stream") return Effect.succeed(response); const body = Scope.makeUnsafe(); lifetime.extend( new Promise((resolve) => Effect.runSync(Scope.addFinalizer(body, Effect.sync(resolve)))), ); return Effect.sync(() => EffectHttp.scopeTransferToStream(response)).pipe( Effect.provideService(Scope.Scope, body), ); };