diff --git a/.changeset/http-router-to-http-effect-fresh-router.md b/.changeset/http-router-to-http-effect-fresh-router.md new file mode 100644 index 0000000000..79578c6f82 --- /dev/null +++ b/.changeset/http-router-to-http-effect-fresh-router.md @@ -0,0 +1,9 @@ +--- +"effect": minor +--- + +Build `HttpRouter.toHttpEffect` apps with their own router, so sub-app routes and middleware no longer register on the outer server's router when built inside `HttpRouter.serve` or `HttpRouter.toWebHandler`. The sub-app's router also stands in for `HttpRouter.layer` within the app, so apps that provide it themselves are isolated too. + +`HttpRouter.serve` likewise always builds its own router, instead of reusing an `HttpRouter.layer` already built outside it. Its `routerConfig` option now always applies. + +`Layer.forkMemoMap`, `Layer.forkMemoMapUnsafe` and `Layer.CurrentMemoMap.forkOrCreate` accept a `fresh` option listing layers that the child memo map builds again instead of reusing from its parent. diff --git a/packages/effect/src/Layer.ts b/packages/effect/src/Layer.ts index 2c7c6948fe..a4131916c3 100644 --- a/packages/effect/src/Layer.ts +++ b/packages/effect/src/Layer.ts @@ -421,9 +421,11 @@ class MemoMapImpl implements MemoMap { } readonly parent: MemoMap | undefined + readonly fresh: ReadonlySet> | undefined - constructor(parent?: MemoMap) { + constructor(parent?: MemoMap, fresh?: ReadonlySet>) { this.parent = parent + this.fresh = fresh } readonly map = new Map, MemoMapEntry>() @@ -437,6 +439,7 @@ class MemoMapImpl implements MemoMap { memoMapObserve(local, scope) return local.deferred.effect ?? Deferred.await(local.deferred) } + if (this.fresh?.has(layer)) return undefined return this.parent?.get(layer, scope) } @@ -514,6 +517,12 @@ export const makeMemoMapUnsafe = (): MemoMap => new MemoMapImpl() * builds should see parent memoized layers without writing newly built layers * back to the parent. * + * **Details** + * + * Layers listed in the `fresh` option (since 4.2.0) are never looked up in the + * parent. Each is built again the first time the child uses it, then memoized + * in the child. + * * @see {@link forkMemoMap} for allocating the child memo map inside `Effect` * @see {@link makeMemoMapUnsafe} for creating a root memo map without a parent * @@ -521,7 +530,10 @@ export const makeMemoMapUnsafe = (): MemoMap => new MemoMapImpl() * @category constructors * @since 4.0.0 */ -export const forkMemoMapUnsafe = (parent: MemoMap): MemoMap => new MemoMapImpl(parent) +export const forkMemoMapUnsafe = ( + parent: MemoMap, + options?: { readonly fresh?: Iterable> | undefined } +): MemoMap => new MemoMapImpl(parent, options?.fresh ? new Set(options.fresh) : undefined) /** * Constructs a `MemoMap` effectfully so it can be used to build additional layers. @@ -568,6 +580,12 @@ export const makeMemoMap: Effect = internalEffect.sync(makeMemoMapUnsaf * Use when a layer build should inherit already memoized layers from an * existing `MemoMap` while keeping newly memoized layers out of the parent map. * + * **Details** + * + * Layers listed in the `fresh` option (since 4.2.0) are never looked up in the + * parent. Each is built again the first time the child uses it, then memoized + * in the child. + * * @see {@link makeMemoMap} for creating a root memo map in an `Effect` * @see {@link forkMemoMapUnsafe} for the synchronous constructor variant * @see {@link buildWithMemoMap} for building layers with an explicit memo map @@ -576,7 +594,10 @@ export const makeMemoMap: Effect = internalEffect.sync(makeMemoMapUnsaf * @category constructors * @since 4.0.0 */ -export const forkMemoMap = (parent: MemoMap): Effect => internalEffect.sync(() => forkMemoMapUnsafe(parent)) +export const forkMemoMap = ( + parent: MemoMap, + options?: { readonly fresh?: Iterable> | undefined } +): Effect => internalEffect.sync(() => forkMemoMapUnsafe(parent, options)) /** * Context service for the current `MemoMap` used in layer construction. @@ -598,9 +619,12 @@ export const forkMemoMap = (parent: MemoMap): Effect => internalEffect. * @since 3.13.0 */ export class CurrentMemoMap extends Context.Service()("effect/Layer/CurrentMemoMap") { - static forkOrCreate(self: Context.Context): MemoMap { + static forkOrCreate( + self: Context.Context, + options?: { readonly fresh?: Iterable> | undefined } + ): MemoMap { const current = Context.getOrUndefined(self, CurrentMemoMap) - return current ? forkMemoMapUnsafe(current) : makeMemoMapUnsafe() + return current ? forkMemoMapUnsafe(current, options) : makeMemoMapUnsafe() } } diff --git a/packages/effect/src/http/HttpRouter.ts b/packages/effect/src/http/HttpRouter.ts index 625684cfd5..7135a5406c 100644 --- a/packages/effect/src/http/HttpRouter.ts +++ b/packages/effect/src/http/HttpRouter.ts @@ -653,11 +653,19 @@ export const layer: Layer.Layer = Layer.effect(HttpRouter)(make) * `Scope`; route request markers are converted into the ordinary requirements of * the returned handler. * + * The app is built with its own fresh `HttpRouter`, which also stands in for + * `HttpRouter.layer` if the app provides it. The routes and middleware it + * registers are only reachable through the returned handler, even when it is + * built inside another router app such as `serve` or `toWebHandler`. + * * **Gotchas** * * The layer is built with a forked `MemoMap`, so calling `toHttpEffect` twice * will build the same layer twice. * + * The fresh router reads `RouterConfig` from the context where `toHttpEffect` + * is run, not from the `routerConfig` option of the outer server. + * * @stability unstable * @category converting * @since 4.0.0 @@ -673,14 +681,16 @@ export const toHttpEffect = ( Request.Without, Exclude, HttpRouter> | Scope.Scope > => - Effect.contextWith((context) => { - const scope = Context.get(context, Scope.Scope) - const memoMap = Layer.CurrentMemoMap.forkOrCreate(context) - return Effect.map(Layer.buildWithMemoMap(Layer.provideMerge(appLayer, layer), memoMap, scope), (context) => { - const router = Context.get(context, HttpRouter) - return router.asHttpEffect() - }) - }) as any + Effect.contextWith((context) => + Effect.map( + Layer.buildWithMemoMap( + Layer.provideMerge(appLayer, layer), + Layer.CurrentMemoMap.forkOrCreate(context, { fresh: [layer] }), + Context.get(context, Scope.Scope) + ), + (context) => Context.get(context, HttpRouter).asHttpEffect() + ) + ) as any const RouteTypeId = "~effect/http/HttpRouter/Route" @@ -1332,6 +1342,10 @@ export const provideRequest = * Layers first built inside the app are private to this server. Provide * services that must be shared with sibling layers outside `serve`. * + * The server always builds its own `HttpRouter`, even if `HttpRouter.layer` was + * already built outside `serve`. Within the app, `HttpRouter.layer` resolves to + * the server's router. + * * **Gotchas** * * The layer is built with a forked `MemoMap`, so calling `serve` twice will @@ -1384,7 +1398,7 @@ export const serve = | Request.On : layer ) return Effect.contextWith((context) => { - const memoMap = Layer.CurrentMemoMap.forkOrCreate(context) + const memoMap = Layer.CurrentMemoMap.forkOrCreate(context, { fresh: [layer] }) return Layer.buildWithMemoMap(layerWithRouter, memoMap, Context.get(context, Scope.Scope)) }).pipe( Effect.map((context) => { diff --git a/packages/effect/test/Layer.test.ts b/packages/effect/test/Layer.test.ts index f0d871dbfd..bdbf95d130 100644 --- a/packages/effect/test/Layer.test.ts +++ b/packages/effect/test/Layer.test.ts @@ -733,6 +733,28 @@ describe("Layer", () => { assert.deepStrictEqual(arr, [acquire1, acquire2, acquire2, release2, release2, release1]) })) + + it.effect("forked memo maps build fresh layers again but reuse other parent layers", () => + Effect.gen(function*() { + const arr: Array = [] + const freshLayer = makeLayer1(arr) + const sharedLayer = makeLayer2(arr) + const parent = yield* Layer.makeMemoMap + const child = yield* Layer.forkMemoMap(parent, { fresh: [freshLayer] }) + + const scope1 = yield* Scope.make() + const scope2 = yield* Scope.make() + + yield* Layer.buildWithMemoMap(freshLayer, parent, scope1) + yield* Layer.buildWithMemoMap(sharedLayer, parent, scope1) + yield* Layer.buildWithMemoMap(freshLayer, child, scope2) + yield* Layer.buildWithMemoMap(sharedLayer, child, scope2) + + yield* Scope.close(scope2, Exit.void) + yield* Scope.close(scope1, Exit.void) + + assert.deepStrictEqual(arr, [acquire1, acquire2, acquire1, release1, release2, release1]) + })) }) describe("tracing", () => { diff --git a/packages/effect/test/http/HttpRouter.test.ts b/packages/effect/test/http/HttpRouter.test.ts index ac928ab2ab..24026d7939 100644 --- a/packages/effect/test/http/HttpRouter.test.ts +++ b/packages/effect/test/http/HttpRouter.test.ts @@ -1,6 +1,7 @@ import { assert, describe, it } from "@effect/vitest" import { Effect, Layer, Option } from "effect" -import { HttpRouter, HttpServerError, HttpServerRequest, HttpServerResponse } from "effect/http" +import { HttpRouter, HttpServer, HttpServerError, HttpServerRequest, HttpServerResponse } from "effect/http" +import * as NetAddress from "effect/net/NetAddress" const echoUrl = (request: HttpServerRequest.HttpServerRequest) => Effect.succeed(HttpServerResponse.text(request.url)) @@ -113,6 +114,94 @@ describe("HttpRouter", () => { assert.strictEqual(body, "/?tab=1") })) + describe("toHttpEffect sub-apps", () => { + const Admin = HttpRouter.add("GET", "/admin/stats", HttpServerResponse.text("admin stats")) + + const request = async (app: Layer.Layer, init?: RequestInit) => { + const { dispose, handler } = HttpRouter.toWebHandler(app, { disableLogger: true }) + try { + const response = await handler(new Request("http://localhost/admin/stats", init)) + return { status: response.status, body: await response.text() } + } finally { + await dispose() + } + } + + for ( + const { name, subApp } of [ + { name: "only serves sub-app routes through the mount", subApp: Admin }, + { + name: "only serves routes of a sub-app that provides HttpRouter.layer through the mount", + subApp: Admin.pipe(Layer.provide(HttpRouter.layer)) + } + ] + ) { + it(name, async () => { + const app = HttpRouter.use(Effect.fnUntraced(function*(router) { + const admin = yield* HttpRouter.toHttpEffect(subApp) + yield* router.add( + "*", + "/admin/*", + Effect.gen(function*() { + const request = yield* HttpServerRequest.HttpServerRequest + if (request.headers.authorization !== "Bearer admin") { + return HttpServerResponse.text("unauthorized", { status: 401 }) + } + return yield* Effect.orDie(admin) + }) + ) + })) + + assert.deepStrictEqual(await request(app), { status: 401, body: "unauthorized" }) + assert.deepStrictEqual(await request(app, { headers: { authorization: "Bearer admin" } }), { + status: 200, + body: "admin stats" + }) + }) + } + + it("mounts a sub-app at one of its own routes", async () => { + const app = HttpRouter.use(Effect.fnUntraced(function*(router) { + const admin = yield* HttpRouter.toHttpEffect(Admin) + yield* router.add("GET", "/admin/stats", Effect.orDie(admin)) + })) + + assert.deepStrictEqual(await request(app), { status: 200, body: "admin stats" }) + }) + }) + + it.effect("serve does not reuse an HttpRouter.layer memoized outside it", () => + Effect.gen(function*() { + let serverHandler: Effect.Effect | undefined + const server = HttpServer.make({ + address: NetAddress.inetAddressUnsafe(NetAddress.ipv4Loopback, 0), + serve: (handler) => Effect.sync(() => void (serverHandler = handler)) + }) + const outside = HttpRouter.add("GET", "/outside", HttpServerResponse.text("outside")).pipe( + Layer.provide(HttpRouter.layer) + ) + const app = HttpRouter.serve(HttpRouter.add("GET", "/inside", HttpServerResponse.text("inside")), { + disableLogger: true, + disableListenLog: true + }).pipe( + Layer.provideMerge(outside), + Layer.provide(Layer.succeed(HttpServer.HttpServer)(server)) + ) + yield* Layer.build(app) + const status = (path: string) => + serverHandler!.pipe( + Effect.catchCause((cause) => Effect.map(HttpServerError.causeResponse(cause), ([response]) => response)), + Effect.map((response) => response.status), + Effect.provideService( + HttpServerRequest.HttpServerRequest, + HttpServerRequest.fromWeb(new Request(`http://localhost${path}`)) + ) + ) + + assert.strictEqual(yield* status("/inside"), 200) + assert.strictEqual(yield* status("/outside"), 404) + })) + for (const ignoreDuplicateSlashes of [true, false]) { it.effect(`preserves the local URL with ignoreDuplicateSlashes=${ignoreDuplicateSlashes}`, () => Effect.gen(function*() {