Repository navigation
Refactor internal request handling into a functional core - #17636
Conversation
Replace the App/Pipeline god objects with pure functions drawing static
data from the manifest (the only permitted ambient source of truth):
- All internal handler classes (AstroHandler, PagesHandler, AstroMiddleware,
CacheHandler, ActionHandler, I18n, Rewrites, TrailingSlashHandler, error
handlers, session provider) are now module functions rooted in FetchState.
- FetchState constructs from (manifest, request, options?, hooks?); the
public one-arg new FetchState(request) works from a bare Request by
reaching the manifest module directly (ambient), with no app handle.
- Symbol.for('astro.app') and Symbol.for('astro.pipeline') are deleted;
nothing static rides the request. Render options carry only render()
inputs.
- Environment differences (prod SSR, dev runnable/non-runnable, build,
container) are per-manifest RenderEnvironment records composed at
entrypoint time; production is the zero-setup default.
- Process-lifetime derivations (route table, middleware, actions, session
driver, cache provider, logger, renderers) are WeakMap memos keyed by
the manifest in their owning modules.
- App and NodeApp remain public facades with unchanged signatures; every
method delegates to the functional core. app.pipeline survives as a
stateless compat shim. Pipeline base and all subclasses are deleted.
- Dev HMR route updates are now atomic (fixes stale-router split-brain).
No public API changes. All suites green: unit, full integration,
@astrojs/node, @astrojs/cloudflare (workerd), dev/HMR.
🦋 Changeset detectedLatest commit: f484912 The changes in this PR will be included in the next version bump. This PR includes changesets to release 420 packages
Not sure what this means? Click here to learn what changesets are. Click here if you're a maintainer who wants to add another changeset to this PR |
Merging this PR will degrade performance by 14.8%
Performance Changes
Comparing |
Rewrites the three changesets to describe user-facing behavior instead of internals, removes all references to internal planning documents from code comments, and rewrites comments that described pre-refactor behavior to describe how the code currently works.
Covers the documented advanced pattern from #17591: a custom wrangler entryfile that builds its own state with `new FetchState(request)` from a bare workerd request, serves assets through `cf()`, and renders with `astro(state)`.
The method had no callers — BaseApp.render constructs the FetchState itself and generated builds only use the fetch member. Also rewrites the constructor comment to describe the current contract.
# Conflicts: # pnpm-lock.yaml
|
One thing I wanted to do is access the logger outside the request (and the pipeline), for example within |
There was a problem hiding this comment.
This is a large but well-scoped internal refactor that replaces the monolithic Pipeline and App class hierarchy with a manifest-keyed functional core. The change correctly preserves external API behavior while enabling new FetchState(request) to work inside custom worker entrypoints.
Overall assessment: The implementation is careful and thorough. State is correctly partitioned into per-request (FetchState), per-manifest (createManifestMemo), and per-environment (RenderEnvironment) layers. Backward-compatibility shims (AppPipeline) cover all previously exposed surface area. New unit tests and a Cloudflare integration regression test cover the motivating use case and the new memoization/registry primitives.
Specific notes:
- The functional error dispatch (
renderErrorPage→renderDefaultError/renderDevError/renderBuildError) preserves the old strategy selection. - The
AppPipelineshim reproduces every oldPipelinemember that was reachable fromapp.pipeline, with identical semantics. - Request-reconstruction during rewrites and forwarded-header application correctly drops the removed
appSymbol/pipelineSymbolbecause request-bound state is now captured onFetchStateitself. - Dev HMR wiring now targets the single per-manifest route table atomically, which fixes the stale-route issue described in one of the changesets.
One actionable issue found: BuildApp inadvertently passes streaming = true into the AppPipeline shim instead of the old manifest.serverLike value, making the backward-compatibility app.pipeline.streaming property incorrect for SSG builds.
This review was made by an LLM. The analysis may be wrong, and reports might be incorrect.
|
@florian-lefebvre yes, we can now get a logger keyed by the manifest. I can create a helper for this like we have for actions and some of the other things that hang off of the manifest. |
The last surviving Pipeline: app.pipeline was undocumented, so the stateless compat shim is gone entirely. The node adapter uses the new public app.getLogger() to wait for the configured log destination, and BuildApp carries the routeCache/getComponentByRoute accessors StaticPaths needs across the prerender bundle boundary. The internal PipelineFeatures bit flags are renamed to FetchFeatures, and @astrojs/node now requires the astro version that ships app.getLogger().
Replaces resolveLoggerDestination's hand-rolled WeakMap with a getResolvedLogger accessor built on the shared async manifest memo. The derivation never rejects: a custom log destination that fails to load is reported through the console logger and the request proceeds, instead of failing the first request.
ematipico
left a comment
There was a problem hiding this comment.
Thank you for the explanation!
There was a problem hiding this comment.
Large internal refactor that replaces Pipeline/App god-objects with a manifest-keyed functional core. The refactor preserves public adapter APIs, keeps changesets for all user-facing surfaces, and includes good regression coverage.
I found no required blockers. A few optional notes:
- The dev and container
getModuleForRouteimplementations drift from the production one (no i18n fallback / static redirect-route replacement) despite comments claiming they are identical. vite-plugin-app/environment.tsimportsrouteIsRedirectbut does not use it.BaseApp.setFetchHandlerusesinstanceof DefaultFetchHandler, which would misclassify a user handler that legitimately extends that class.
Validation: strictly static; no project code, tests, builds, or checks were run. git fetch origin main could not be executed because git is not available in this environment, so the review is based on the GitHub-provided PR diff and head files.
Changesets: present and cover astro, @astrojs/node, and the three fix/refactor behaviors.
Additional findings
[optional][design]: setFetchHandler uses instanceof DefaultFetchHandler to detect custom handlers
packages/astro/src/core/app/base.ts:222 RIGHT
BaseApp.setFetchHandler sets #hasCustomFetchHandler based on !(handler instanceof DefaultFetchHandler). A user-defined handler that legitimately extends DefaultFetchHandler would be classified as the default, causing BaseApp.render to take the fast path and bypass the custom fetch method. Consider using the existing isDefaultFetchHandler marker (already emitted by the virtual fetchable module) or an explicit property check instead of instanceof.
This review was made by an LLM. The analysis may be wrong, and reports might be incorrect.
| getDebugInfo: () => Promise<string>; | ||
| } | ||
|
|
||
| // Identical to the production implementation: redirect + i18n-fallback |
There was a problem hiding this comment.
[optional][maintainability]: Dev and container getModuleForRoute duplicate production logic incompletely
The production environment's getModuleForRoute normalizes static redirect routes (route.redirectRoute) and replaces i18n fallback routes (routeIsFallback) before looking them up in pageMap. The runnable dev (vite-plugin-app/environment.ts:54-84), non-runnable dev (core/environment/dev-nonrunnable.ts:41-57), and container (container/environment.ts:29-59) implementations only check route.type === 'redirect' and do not handle fallback replacement, yet their comments claim they are 'identical to the production implementation'. If a dev request matches an i18n fallback route, or a container rewrite lands on one, the pageMap lookup uses the fallback RouteData directly and can throw. Centralize the redirect/fallback normalization in a shared helper, or update the comments to note the intentional divergence.
| import { RedirectComponentInstance, RedirectSinglePageBuiltModule } from '../core/redirects/index.js'; | ||
| import { loadRenderer } from '../core/render/index.js'; | ||
| import { getDefaultRoutes } from '../core/routing/default.js'; | ||
| import { routeIsRedirect } from '../core/routing/helpers.js'; |
There was a problem hiding this comment.
[optional][maintainability]: Unused routeIsRedirect import in runnable dev environment
routeIsRedirect is imported at line 14, but getModuleForRoute at line 68 uses route.type === 'redirect' instead. Removing the unused import avoids confusion and tooling noise.
This PR contains the following updates: | Package | Change | [Age](https://docs.renovatebot.com/merge-confidence/) | [Confidence](https://docs.renovatebot.com/merge-confidence/) | |---|---|---|---| | [@astrojs/markdown-remark](https://astro.build) ([source](https://github.com/withastro/astro/tree/HEAD/packages/markdown/remark)) | [`7.2.2` → `7.2.3`](https://renovatebot.com/diffs/npm/@astrojs%2fmarkdown-remark/7.2.2/7.2.3) |  |  | | [astro](https://astro.build) ([source](https://github.com/withastro/astro/tree/HEAD/packages/astro)) | [`7.2.2` → `7.2.3`](https://renovatebot.com/diffs/npm/astro/7.2.2/7.2.3) |  |  | --- ### Release Notes <details> <summary>withastro/astro (@​astrojs/markdown-remark)</summary> ### [`v7.2.3`](https://github.com/withastro/astro/blob/HEAD/packages/markdown/remark/CHANGELOG.md#723) [Compare Source](https://github.com/withastro/astro/compare/@astrojs/[email protected]...@astrojs/[email protected]) ##### Patch Changes - Updated dependencies \[[`8c193f6`](withastro/astro@8c193f6)]: - [@​astrojs/internal-helpers](https://github.com/astrojs/internal-helpers)@​0.10.3 </details> <details> <summary>withastro/astro (astro)</summary> ### [`v7.2.3`](https://github.com/withastro/astro/blob/HEAD/packages/astro/CHANGELOG.md#723) [Compare Source](https://github.com/withastro/astro/compare/[email protected]@7.2.3) ##### Patch Changes - [#​17724](withastro/astro#17724) [`97140b2`](withastro/astro@97140b2) Thanks [@​ematipico](https://github.com/ematipico)! - Fixes an issue where Astro could run out of memory when `experimental.collectionStorage` is set to `chunked` and there are multiple concurrent updates to the same collection. - [#​17636](withastro/astro#17636) [`51723b1`](withastro/astro@51723b1) Thanks [@​matthewp](https://github.com/matthewp)! - Fixes the dev server sometimes matching against stale routes after pages were added, removed, or renamed, requiring a dev server restart to pick up the change - [#​17636](withastro/astro#17636) [`51723b1`](withastro/astro@51723b1) Thanks [@​matthewp](https://github.com/matthewp)! - Fixes the composable request helpers (`astro/fetch`) throwing an error when used on a request that had been rewritten with `Astro.rewrite()` or `next()` - [#​17636](withastro/astro#17636) [`51723b1`](withastro/astro@51723b1) Thanks [@​matthewp](https://github.com/matthewp)! - Refactors Astro's internal server-side request handling. This is an internal change: all documented public APIs, including `App` and `NodeApp`, keep their existing signatures and behavior. The undocumented internal `app.pipeline` property and the `AppPipeline` export from `astro/app` have been removed. Adapters that used `app.pipeline.getLogger()` to wait for the configured log destination can call the new `app.getLogger()` instead. As a result of this refactor, `new FetchState(request)` from `astro/fetch` now works anywhere inside a built Astro server — including custom `src/fetch.ts` entrypoints — without the request needing to first pass through `app.render()`. Previously this threw an error, breaking patterns like the Cloudflare adapter's advanced custom-worker setup. - [#​17723](withastro/astro#17723) [`c3b9aed`](withastro/astro@c3b9aed) Thanks [@​florian-lefebvre](https://github.com/florian-lefebvre)! - Fixes a link in font providers JSDoc annotations - [#​17699](withastro/astro#17699) [`e28d227`](withastro/astro@e28d227) Thanks [@​ArmandPhilippot](https://github.com/ArmandPhilippot)! - Fixes several documentation issues related to the JSDoc for configuration options. - When hovering over the `server` and `fonts` options, the JSDoc for the nested options was displayed instead of the JSDoc for the top-level property. - Two i18n configuration options were being used incorrectly in the examples. - The indentation of some code blocks was broken on hover. - [#​17572](withastro/astro#17572) [`2066f39`](withastro/astro@2066f39) Thanks [@​matthewp](https://github.com/matthewp)! - Fixes a crash when a request arrives with a malformed port in the `Host` header (for example `example.com:65536` or `example.com:8080:8080`). Such a host made the constructed request URL invalid, and the fallback that was meant to recover reused the same invalid host and threw again. The request URL now degrades to a host the server controls when the incoming host cannot be parsed, so the request is handled instead of erroring. - [#​17685](withastro/astro#17685) [`9f15609`](withastro/astro@9f15609) Thanks [@​astrobot-houston](https://github.com/astrobot-houston)! - Fixes a dev server error where an SSR full reload triggered by a third-party Vite plugin (such as `@tailwindcss/vite`) could fail with `Failed to load url astro:server-app.js` - [#​17636](withastro/astro#17636) [`51723b1`](withastro/astro@51723b1) Thanks [@​matthewp](https://github.com/matthewp)! - Improves error handling for custom log destinations. When the configured logger fails to load, Astro now reports the error and continues with the default console logger instead of failing the first request. - [#​17631](withastro/astro#17631) [`cf29bec`](withastro/astro@cf29bec) Thanks [@​matthewp](https://github.com/matthewp)! - Fixes `getCollection()` and `getEntry()` throwing `DataCloneError` when a collection schema transform returns a `Temporal.PlainDate` or other class instance. - Updated dependencies \[[`8c193f6`](withastro/astro@8c193f6)]: - [@​astrojs/internal-helpers](https://github.com/astrojs/internal-helpers)@​0.10.3 - [@​astrojs/markdown-remark](https://github.com/astrojs/markdown-remark)@​7.2.3 - [@​astrojs/markdown-satteri](https://github.com/astrojs/markdown-satteri)@​0.3.6 </details> --- ### Configuration 📅 **Schedule**: (UTC) - Branch creation - At any time (no schedule defined) - Automerge - At any time (no schedule defined) 🚦 **Automerge**: Disabled by config. Please merge this manually once you are satisfied. ♻ **Rebasing**: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox. 🔕 **Ignore**: Close this PR and you won't be reminded about these updates again. --- - [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check this box --- This PR has been generated by [Mend Renovate CLI](https://github.com/renovatebot/renovate). <!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiI0NC4zMS4wIiwidXBkYXRlZEluVmVyIjoiNDQuMzEuMCIsInRhcmdldEJyYW5jaCI6Im1haW4iLCJsYWJlbHMiOltdfQ==-->
Changes
PipelineandAppclasses as used internally. These were essentially "god objects" that held state related to the server-side app.FetchStatewhen access from outside of theAppclass. For example in Cloudflare you can create a custom worker which is the entrypoint to the application.manifestis the one true god-object in SSR, and we could simply derive all state from that. So this new architecture is much more functional. Derived state is created ascreateManifestMemoandcreateAsyncManifestMemowhich are keyed on themanifest. Anything that needs this state can simply import it now.Appremains as its the external API for adapters, but mostly just defers to the functional approach now.Fixes #17591
Testing
Docs