Build HttpRouter.toHttpEffect apps with a fresh router (#10194)

Co-authored-by: Tim <hello@timsmart.co>
This commit is contained in:
effect-bot
2026-11-03 23:39:32 +00:00
committed by effect-bot
co-authored by Tim
parent 8df42b3c9e
commit 245c19edc2
5 changed files with 173 additions and 15 deletions
@@ -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.
+29 -5
View File
@@ -421,9 +421,11 @@ class MemoMapImpl implements MemoMap {
}
readonly parent: MemoMap | undefined
readonly fresh: ReadonlySet<Layer<any, any, any>> | undefined
constructor(parent?: MemoMap) {
constructor(parent?: MemoMap, fresh?: ReadonlySet<Layer<any, any, any>>) {
this.parent = parent
this.fresh = fresh
}
readonly map = new Map<Layer<any, any, any>, 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<Layer<any, any, any>> | 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<MemoMap> = 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<MemoMap> = internalEffect.sync(makeMemoMapUnsaf
* @category constructors
* @since 4.0.0
*/
export const forkMemoMap = (parent: MemoMap): Effect<MemoMap> => internalEffect.sync(() => forkMemoMapUnsafe(parent))
export const forkMemoMap = (
parent: MemoMap,
options?: { readonly fresh?: Iterable<Layer<any, any, any>> | undefined }
): Effect<MemoMap> => 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<MemoMap> => internalEffect.
* @since 3.13.0
*/
export class CurrentMemoMap extends Context.Service<CurrentMemoMap, MemoMap>()("effect/Layer/CurrentMemoMap") {
static forkOrCreate<Services>(self: Context.Context<Services>): MemoMap {
static forkOrCreate<Services>(
self: Context.Context<Services>,
options?: { readonly fresh?: Iterable<Layer<any, any, any>> | undefined }
): MemoMap {
const current = Context.getOrUndefined(self, CurrentMemoMap)
return current ? forkMemoMapUnsafe(current) : makeMemoMapUnsafe()
return current ? forkMemoMapUnsafe(current, options) : makeMemoMapUnsafe()
}
}
+23 -9
View File
@@ -653,11 +653,19 @@ export const layer: Layer.Layer<HttpRouter> = 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 = <A, E, R>(
Request.Without<E>,
Exclude<Request.Without<R>, 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 = <A, E, R, HE, HR = Request.Only<"Requires", R> | 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) => {
+22
View File
@@ -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<string> = []
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", () => {
+90 -1
View File
@@ -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<never, never, HttpRouter.HttpRouter>, 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<HttpServerResponse.HttpServerResponse, unknown, any> | 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*() {