router-build.ts
This file
Path
apps/platform/src/router-build.ts
120 lines · 4.1 KiB · TypeScript
Last changed by
Merge observability into mainoscabrielbefore adoption1985111
History of this fileTake it
Merge build/comments-platform into mainoscabrielbefore adoptionddf09e8
lines 1–5why, one step back1// effect's `HttpRouter.toWebHandler` has every request await one layer build. On2// Workers a request whose client leaves is cancelled without resuming its fibers, so3// a build that awaited a request's I/O would hang every later request for the4// isolate's life. Here the build runs synchronously, and a layer that awaits a5// promise or a timer while built throws where the handler is made.Merge build/1007oscabrielbefore adoption77fa97a
lines 6–15why, one step back6import {7 Cause,8 Context,9 Data,10 Effect,11 Exit,12 Layer,13 Scheduler,14 Scope,15} from "effect";Merge observability into mainoscabrielbefore adoption1985111
line 16why, one step back16import { constTrue } from "effect/Function";Merge build/1007oscabrielbefore adoption77fa97a
line 17why, one step back17import type { HttpServerRequest } from "effect/http";Merge observability into mainoscabrielbefore adoption1985111
line 18why, one step back18import { HttpEffect, HttpMiddleware, HttpRouter } from "effect/http";Merge build/1007oscabrielbefore adoption77fa97a
lines 19–23why, one step back1920export class RouterBuildAwaited extends Data.TaggedError("RouterBuildAwaited")<{21 readonly message: string;22}> {}23Merge observability into mainoscabrielbefore adoption1985111
lines 24–31why, one step back24// The runtime traces each request itself, with its URL; effect's own25// `http.server` span would be a second, carrying the query and the client's26// address.27const UntracedRequests = Layer.succeed(28 HttpMiddleware.TracerDisabledWhen,29 constTrue30);31Merge build/1007oscabrielbefore adoption77fa97a
lines 32–46why, one step back32type RequestNeeds<A, R> = Exclude<33 | HttpRouter.Request.Only<"Requires", R>34 | HttpRouter.Request.Only<"GlobalRequires", R>,35 A | Scope.Scope | HttpServerRequest.HttpServerRequest36>;3738export const buildHandler = <39 A,40 E,41 R extends42 | HttpRouter.HttpRouter43 | HttpRouter.Request<"Requires", unknown>44 | HttpRouter.Request<"GlobalRequires", unknown>45 | HttpRouter.Request<"Error", unknown>46 | HttpRouter.Request<"GlobalError", unknown>,Merge observability into mainoscabrielbefore adoption1985111
line 47why, one step back47 TE = never,Merge build/1007oscabrielbefore adoption77fa97a
line 48why, one step back48>(Merge observability into mainoscabrielbefore adoption1985111
lines 49–51why, one step back49 appLayer: Layer.Layer<A, E, R>,50 // Every request runs with it, and a request's defect is reported through it.51 telemetry: Layer.Layer<never, TE> = Layer.emptyMerge build/1007oscabrielbefore adoption77fa97a
lines 52–66why, one step back52) => {53 const scope = Scope.makeUnsafe();5455 // SAFETY: what `R` adds to `HttpRouter` are `HttpRouter.Request` markers,56 // which name what each request is given (its context) or may fail with,57 // never a service the build needs; effect's `toWebHandler` drops them the58 // same way.59 /* oxlint-disable typescript/no-unsafe-type-assertion -- the markers are phantom types with no service behind them; see SAFETY. */60 // @effect-diagnostics-next-line unsafeEffectTypeAssertion:off -- the markers are phantom types with no service behind them; see SAFETY.61 const routed = Layer.provideMerge(appLayer, HttpRouter.layer) as Layer.Layer<62 A | HttpRouter.HttpRouter,63 E64 >;65 /* oxlint-enable typescript/no-unsafe-type-assertion */66Merge observability into mainoscabrielbefore adoption1985111
lines 67–71why, one step back67 const observed = Layer.provideMerge(68 routed,69 Layer.merge(telemetry, UntracedRequests)70 );71Merge build/comments-platform into mainoscabrielbefore adoptionddf09e8
lines 72–74why, one step back72 // `runSyncExit`'s own scheduler would ride along in any context a layer captures73 // while built, so the build runs on the default one; `runSyncExit` still drains what74 // it schedules before it returns.Merge build/1007oscabrielbefore adoption77fa97a
line 75why, one step back75 const built = Effect.runSyncExit(Merge observability into mainoscabrielbefore adoption1985111
line 76why, one step back76 Layer.buildWithScope(observed, scope).pipe(Merge build/1007oscabrielbefore adoption77fa97a
lines 77–120why, one step back77 Effect.provideService(78 Scheduler.Scheduler,79 Scheduler.Scheduler.defaultValue()80 )81 )82 );8384 const awaited =85 Exit.isFailure(built) &&86 built.cause.reasons.some(87 (reason) =>88 Cause.isDieReason(reason) && Cause.isAsyncFiberError(reason.defect)89 );9091 if (awaited) {92 throw new RouterBuildAwaited({93 message:94 "The router's build awaited a promise or a timer: move that work into the request path.",95 });96 }9798 const serveRequest = Exit.match(built, {99 onFailure: (cause) => () => Effect.runPromise(Effect.failCause(cause)),100 onSuccess: (context) =>101 HttpEffect.toWebHandlerWith<102 A | HttpRouter.HttpRouter,103 HttpServerRequest.HttpServerRequest | Scope.Scope,104 never105 >(context)(106 // @effect-diagnostics-next-line anyUnknownInErrorContext:off -- the router's own effect fails with whatever a route left unhandled, which `toWebHandlerWith` turns into a response (404 for no route), as effect's `toWebHandler` does with the same effect.107 Context.get(context, HttpRouter.HttpRouter).asHttpEffect()108 ),109 });110111 const handler = (112 request: Request,113 context?: Context.Context<RequestNeeds<A, R>>114 ): Promise<Response> => serveRequest(request, context);115116 return {117 dispose: () => Effect.runPromise(Scope.close(scope, Exit.void)),118 handler,119 };120};