Repository navigation
feat!: 中核を Rosanna に合わせて作り直し、開いている不具合を直す - #118
Conversation
- document をリクエストごとに複製し、worker でページのスクリプトが次の リクエストに残らないようにする - フォームの変換を描画前の木の走査から RenderExtension に移し、Renderable の 子や defer の fallback の中のフォームも変換する - defer エンドポイントに guard が渡した Request を使う Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
manifest の読み直しと Deferred の包み直しをやめ、rosanna の差し替え口を使う。 manifest だけでは決められない引数 (コンテナにないサービスの既定値や nullable) はコンパイル済みのコンポーネントをリフレクションして解決する。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
AppRouter は設定だけを持ち、リクエストごとに RequestDispatch を作る。ページの 読み込み (PageLoader)、描画 (PageRenderer)、エラー応答 (ErrorResponder)、API ルート (ApiRouteDispatcher)、プロファイラの HTTP 部分 (ProfilerBridge)、ページの PSX キャッシュ (PsxCache) に分ける。処理の中身は変えない。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
usePHP の部分更新のための `<div data-rosanna>` を読むものはもうない。 rosanna-defer.js はプレースホルダーを描いたページでだけ出す。すべてのページで 必要なアプリは HtmlDocument::alwaysIncludeClientScript() を呼ぶ。 BREAKING CHANGE: `<div data-rosanna="…">` を削除した。プレースホルダーのない ページでは window.Rosanna が定義されない。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
init や upgrade の後ろのオプションを無視していたので、--help でも雛形を生成して いた。すべてのサブコマンドで先に判定する。 Fixes #102 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
parse_url() が /x/a:80 と //admin をルートページにしていた。パスは自分で切り出し、 先頭の // はルートに届かない (404) ものとして扱う。/admin と同じ扱いにすると、 /admin と比較する middleware を通り抜けるため。フォームの送信先も、//evil.example のように他のホストを指さないようにする。 Fixes #105 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
検証子は誰のリクエストかを含まないので、匿名で表示したブラウザがログイン後も 匿名のコピーを使い続けていた。 Fixes #106 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Go の CGI が /%zz をパースできず 500 になっていた。どのルートにも一致しないパス なので、守るものはなく、そのまま 404 にする。 Fixes #107 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Dotenv の既定値のせいで、APP_ENV のない .env は dev になり、/_profiler と スタックトレースを公開していた。既定を prod にし、雛形も APP_ENV=dev をコミットする .env から gitignore 対象の .env.local に移す。合わせて README に 304 の条件を書く。 BREAKING CHANGE: APP_ENV のない .env は dev ではなく本番になる。clone した直後は echo APP_ENV=dev > .env.local が必要。 Fixes #108 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
FrankenPHP の worker で実際に動かすと、Authenticator と TokenAuthenticator が 最初のユーザーを覚えていて、匿名の訪問者が別人として認証されていた。 - Authenticator は覚えずに毎回セッションから読む - TokenAuthenticator、CachingDatabase、CachingHttpClient の記憶は RequestLifecycle でリクエストとともに消し、AppRouter::run() の最後に必ず呼ぶ - InjectorContainer の exit を StopRequest にする。#[Auth] のリダイレクトと #[Cache] の 304 のたびに worker が再起動していた - 雛形の Caddyfile は worker を起動するだけで、リクエストは index.php に 流れていた。php_server の index で worker に渡す (雛形 v11 に含める) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
There was a problem hiding this comment.
🟡 Changes recommended
Unresolved security regressions can expose production debug pages, bypass routing and authorization guards, leak CSRF tokens, and retain user-specific cached fragments after logout.
12 open issues
Keep defer-cache invalidation available without placeholders · New Force form actions to use origin-relative request paths · New Reject double-slash paths before locale rewriting · New Return framework 404s without invoking application code · New Preserve existing APP_ENV when creating local environment files · New Include Apache authorization fallback in request headers · New Skip cache shortcut for active sessions and cookie-authenticated users · New Preserve service-first component invocation · New Avoid reloading component files to inspect parameters · New Preserve cached page factories when updating loader dependencies · New Render child components before registering form actions · New Migrate APP_ENV=dev when preserving existing local settings · New
What changed in this PR
This PR restructures Relayer’s routing core around Rosanna, separating router configuration from per-request processing while retaining the public AppRouter::create() and run() entrypoints.
Changes:
- Extracts dispatch, rendering, error handling, profiling, and PSX support into focused classes.
- Moves form normalization into rendering, isolates document state between requests, and loads the defer client script conditionally.
- Updates path handling, authenticated cache revalidation, CLI option handling, and production defaults, with regression tests and migration guidance.
| File | Description |
|---|---|
tests/Scaffold/ScaffoldTest.php |
Checks local environment scaffolding and Docker defaults. |
tests/Scaffold/InitCommandTest.php |
Covers subcommand help and unknown options. |
tests/Router/UnusualPathDispatchTest.php |
Covers colon paths, double slashes, and form targets. |
tests/Router/RepeatedDispatchIsolationTest.php |
Checks document isolation across requests. |
tests/Router/NativeHttpServerTest.php |
Tests invalid paths before Go middleware. |
tests/Router/LayoutScriptDispatchTest.php |
Updates script-order expectations. |
tests/Router/Form/FormActionTransformerTest.php |
Removes tests for the retired transformer. |
tests/Router/Form/FormActionRenderExtensionTest.php |
Tests render-time form normalization. |
tests/Router/DeferDispatchTest.php |
Covers guard-substituted defer requests. |
tests/Router/ClientScriptDispatchTest.php |
Tests conditional scripts and wrapper removal. |
tests/Router/AuthRedirectHttpTest.php |
Expects double-slash requests to return 404. |
tests/RelayerBootTest.php |
Tests production defaults and local dev overrides. |
tests/Psx/ContainerPsxArgumentResolverTest.php |
Covers component argument injection and fallbacks. |
tests/Http/RequestTest.php |
Covers unusual and absolute-form request targets. |
tests/Http/CachePolicyTest.php |
Tests credential-aware conditional responses. |
src/Scaffold/Scaffold.php |
Introduces v11 environment and Docker templates. |
src/Scaffold/InitCommand.php |
Handles help and rejects unknown flags before execution. |
src/Scaffold/ContainerCompileCommand.php |
Defaults dotenv loading to production. |
src/Router/Routing/Router.php |
Revises path normalization. |
src/Router/Native/NativeProxy.php |
Skips Go processing for unroutable paths. |
src/Router/Layout/TrackingDeferredRenderer.php |
Tracks whether rendering produces defer placeholders. |
src/Router/Layout/LayoutRenderer.php |
Applies form normalization during rendering. |
src/Router/Form/FormActionTransformer.php |
Removes the pre-render tree transformer. |
src/Router/Form/FormActionRenderExtension.php |
Normalizes form actions and hidden fields at render time. |
src/Router/Document/HtmlDocument.php |
Adds conditional client-script loading and an override. |
src/Router/Dispatch/RequestDispatch.php |
Extracts the per-request processing pipeline. |
src/Router/Dispatch/ProfilerBridge.php |
Extracts profiler endpoints and parent-token handling. |
src/Router/Dispatch/PageRenderer.php |
Extracts page rendering and client-script selection. |
src/Router/Dispatch/PageLoader.php |
Extracts page loading, factory caching, and autowiring. |
src/Router/Dispatch/HttpMessages.php |
Extracts localized HTTP messages. |
src/Router/Dispatch/ErrorResponder.php |
Extracts error responses and exception reporting. |
src/Router/Dispatch/DispatchEnvironment.php |
Groups dispatch configuration and dependencies. |
src/Router/Dispatch/ApiRouteDispatcher.php |
Extracts API handler dispatch and response handling. |
src/Router/Component/FunctionPage.php |
Updates a comment naming the render caller. |
src/Router/AppRouter.php |
Delegates requests and clones configured HTML documents. |
src/Relayer.php |
Defaults environment loading to production. |
src/Psx/PsxComponentRegistrar.php |
Delegates injection to the argument resolver. |
src/Psx/PsxCache.php |
Extracts page and layout compilation caching. |
src/Psx/ContainerPsxArgumentResolver.php |
Resolves component services and fallback arguments. |
src/Http/RequestPath.php |
Rejects leading double slashes. |
src/Http/Request.php |
Separates request-path extraction from URL parsing. |
src/Http/CachePolicy.php |
Disables 304 shortcuts for recognized credentials. |
README.md |
Documents changed defaults and migration steps. |
README.ja.md |
Synchronizes Japanese behavior and migration documentation. |
CLAUDE.md |
Documents the dispatch namespace. |
AGENTS.md |
Documents the dispatch namespace. |
Review effort: Balanced
| if ($this->document instanceof HtmlDocument) { | ||
| $this->document->setClientScriptNeeded($deferred->hasRendered()); |
| return $request; | ||
| } | ||
|
|
||
| $resolved = $resolver->resolve($request); |
| 5 => ['CLAUDE.md'], | ||
| 6 => ['static-build.Dockerfile', 'Caddyfile', 'public/worker.php'], | ||
| // Dev mode moved out of the committed .env (see rewrites()). | ||
| 11 => ['.env.local'], |
| public function setContainer(ContainerInterface $container): self | ||
| { | ||
| $this->container = $container; | ||
| $this->pages = null; |
| // Dev mode moved out of the committed .env (see rewrites()). | ||
| 11 => ['.env.local'], |
プレースホルダーのないページのログアウトフォームには window.Rosanna がなく、 clearDeferCache() が動かない。ユーザー固有の localCache の断片がログアウト後も残り、 共有端末で次のユーザーに表示されるおそれがあった。 既定を main と同じ全ページ読み込みに戻し、プレースホルダーのあるページだけに絞る 挙動は HtmlDocument::loadClientScriptOnlyWithDefer() で明示的に選ぶようにする。 未リリースの alwaysIncludeClientScript() は削除する。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- LocaleResolver: ルートに届かないパスからはロケールの接頭辞を外さない。 `//ja/admin` が `/admin` に、`//ja/_defer/name` が defer の窓口に届いていた。 ロケールは Cookie / ヘッダーなどから決まる - PageLoader: ページのファクトリをプロセス単位で持つ。require_once の記憶は プロセス単位なので、ページを配信したあとの setContainer() / setProfiler() で loader が作り直されると、次のリクエストが 404 になっていた - NativeProxy: ルートに届かないパスにはフレームワークが JSON の 404 を返す。 Go の middleware を通らないまま error ページと root layout が描画されていた Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
v11 で .env.local を migrations() に入れたため、APP_ENV=prod に編集した .env のプロジェクトでも upgrade が .env.local を作り、本番が dev で起動して /_profiler とスタックトレースを公開していた。init の再実行でも同じことが 起きた。逆に、手を入れていない .env と APP_ENV のない .env.local を持つ v10 のプロジェクトは、.env から APP_ENV=dev が消えて黙って本番になっていた。 - upgrade: 手を入れていない .env を書き換えて APP_ENV=dev が消えるときだけ .env.local に移す。なければ作り、APP_ENV がなければ追記し、あれば触らない - 書き込みは .env の書き換えより先に行う。失敗しても dev モードを失わない - 追記は temp + rename を使わず、.env.local のパーミッションを保つ - init: .env.local を書くのは新規プロジェクト(.env も structure_version も ない)だけ。書かなかったときはその旨を出力する - .env.local を migrations() から外し、files() には残す Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
rosanna の PsxArgumentResolver は必ず $props を先頭に渡すので、先頭がサービスのコンポーネントが TypeError になっていた。また引数の解決のためにコンパイル済みファイルを require し直すので、名前付きの関数やクラスを宣言するファイルが Cannot redeclare で落ちていた。 コンテナがあるときは manifest の項目ごとに ContainerPsxComponent を登録し、読み込んだ callable 自身を reflection して引数を決める。読み込みは CompiledPsxFile が内容のハッシュごとにプロセスで保持する。同じプロセスのコンパイルが deferred の宣言を読むときも同じ経路を通すため、deferred manifest は Relayer が書く。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
There was a problem hiding this comment.
🟡 Changes recommended
Unresolved critical issues can leak identities and personalized responses, crash persistent workers, and enable debug mode in existing production applications.
19 open issues
Reset all live instances instead of overwriting same-name callbacks · New Disable shared caching for credential-bearing requests · New Prevent redeclaration fatals when reloading changed artifacts · New Share compiled artifacts with the no-container manifest loader · New Resolve page and layout components as request-local instances · New Avoid enabling development mode for existing manually configured apps · New Preserve existing APP_ENV when creating local environment files Reject double-slash paths before locale rewriting Force form actions to use origin-relative request paths Keep defer-cache invalidation available without placeholders Allow token-only authenticators through the requireAuth gate · New Handle StopRequest before it crosses application middleware · New Write the development override before the base environment file · New Restart development workers when application sources change · New Migrate APP_ENV=dev when preserving existing local settings Render child components before registering form actions Preserve cached page factories when updating loader dependencies Skip cache shortcut for active sessions and cookie-authenticated users Include Apache authorization fallback in request headers
3 resolved since last review
Review effort: Balanced
| index worker.php | ||
| worker { | ||
| file ./public/worker.php |
Bearer 認証のリクエストは 304 にはならなかったが、宣言した `Cache(public: true)` はそのまま送られ、個人向けの 200 を CDN が 他の訪問者に返しうる状態だった。 - `Authorization` のあるリクエストでは、`private` / `noStore` 以外の 方針を `Cache-Control: private, no-store` に置き換える。`emit()` は グローバルから、`isNotModified()` はルーティングされた Request から 判定するので、middleware が `withHeader()` で付けた場合も含む。 クラス型(#[Cache])と関数型($ctx->cache())の両方に効く - セッションがすでに有効なら 304 を返さない。middleware が remember-me の Cookie からログインさせた場合、受け取った Cookie には現れない - `Request::fromGlobals()` は本来のヘッダーがないとき `REDIRECT_HTTP_AUTHORIZATION` を `authorization` として読む (ServerAuthorizationHeader と同じ順序) セッション Cookie だけのリクエストは従来どおり。セッションに触れない ページは宣言どおりの方針で返す。 Fixes #120 Fixes #121 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
TokenAuthenticator・CachingDatabase・CachingHttpClient はクラス名で RequestLifecycle::onReset() に登録していたが、Rosanna は同じ名前の コールバックを置き換えるため、インスタンスが 2 つあると古い方の 認証結果やメモが次のリクエストに残り、後の訪問者が前の利用者として 認証されうる。 RequestScopedInstances に WeakMap で各インスタンスを持たせ、Rosanna には 1 件だけ登録する。リセット関数は static クロージャで受け取る ので、捨てられたインスタンスを生かし続けない。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
PageLoader はコンテナが共有するページ・レイアウト・エラーページの オブジェクトをそのまま描画に使っていたため、worker では render() の addJs() が積み重なり、条件つきのメタデータやパラメータ、フォーム アクションが書いた状態が次の訪問者に残っていた。 コンテナから得たものが Renderable か LayoutInterface なら clone して 使う。注入された依存はそのまま残り、コンテナが持つ元のオブジェクト には一切書き込まない。コンテナにないクラスは従来どおり new する。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
`GET http://other.example/p?q=1` のような絶対形式のリクエストでは、 フォームの action がそのホストを指し、CSRF トークンの送信先も そのホストになっていた。 action はリクエスト URI からスキームとオーソリティを外し、パスと クエリだけにする。ロケールのプレフィックスはブラウザが要求したとおり 残す。先頭の `//` や `/\` は従来どおり 1 本のスラッシュにまとめ、 ブラウザが解釈前に取り除くタブと改行も先に落とす。 Fixes #119 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
`Renderable` の子が `render()` の中で `PageContext::current()->action()` を登録したフォームは、送信しても何も起きなかった。事前描画は描画関数が 返す要素の木を作るだけで、子の `render()` は最終描画まで呼ばれず、 登録がディスパッチに間に合わなかった。 アクションを送信した POST の事前描画で、Renderer と同じように木を たどって子を展開する。配列、入れ子の要素、`resolve()` で展開する子、 defer のフォールバックの中も対象にする。GET とファクトリで登録した アクションへの POST は従来どおり 1 回だけ描画する。README に 子からの登録を書き足した。 Fixes #122 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- CompiledPsxFile: 内容の変わったファイルを読み直す前に、トップレベルで宣言する function / class / interface / trait / enum をトークンで調べる。すでにプロセスに ある名前を宣言するなら実行せず、先に読んだ値を返し続け、ワーカーの再起動を促す メッセージを error_log に一度だけ書く。宣言のないファイルや新しい名前だけを足した ファイルは今までどおり読み直す。最初の実行が宣言の後に例外で止まったファイルは、 再実行の致命的エラーではなく RuntimeException にする - コンテナなしの PsxComponentRegistrar::configure() も、Rosanna 自身のローダーの 代わりに ManifestPsxComponent を登録し、CompiledPsxFile の値を使う。autoCompile の コンパイルで実行したファイルを描画や defer のエンドポイントで再び require しない。 引数は今までどおり manifest の parameters から DefaultPsxArgumentResolver で解決する Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
.env も structure_version もない手作業の本番アプリでも、init が APP_ENV=dev の .env.local を作り、次の起動でプロファイラとスタック トレースを出していた。src/Pages・src/AppConfigurator.php・ public/index.php・public/worker.php のどれかがあれば既存とみなし、 これまでどおり「Did not create .env.local」の案内を出す。 新規判定で見るファイルより先に .env.local を書く。.env を書いた後に 止まると、やり直しの init が既存とみなして開発モードを書かなかった。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
worker はページとコンポーネントをメモリに残すので、編集が再起動まで 反映されない。雛形の開発手段(php -S と compose の dev ターゲット)は どちらもこの Caddyfile を読まない(イメージの CMD は同梱の /etc/frankenphp/Caddyfile を指す)ので、挙動は変えずにコメントと アプリの README で開発の起動方法を案内する。前提が崩れたら落ちる テストも足す。v11 は未リリースなので STRUCTURE_VERSION と v10 の ハッシュはそのまま。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
There was a problem hiding this comment.
🟡 Changes recommended
Component reloads can crash workers, scaffolding can expose the profiler, and session responses can be publicly cached, alongside action-dispatch and request-isolation bugs.
16 open issues
Track closed sessions when deciding response cache policy · New Prevent redeclaration when reloading block-scoped declarations · New Ensure generated .env.local files are excluded from Git · New Preserve existing APP_ENV when creating local environment files Reject double-slash paths before locale rewriting Keep defer-cache invalidation available without placeholders Continue passing props to iterable and mixed component parameters · New Register layout actions before dispatching submissions · New Preserve child instances and action state across rendering · New Validate the original request URI before proxying to Go · New Avoid resetting request lifecycle callbacks twice · New Isolate mutable page state between requests · New Restart development workers when application sources change Migrate APP_ENV=dev when preserving existing local settings Preserve cached page factories when updating loader dependencies Include Apache authorization fallback in request headers
12 resolved since last review
Avoid enabling development mode for existing manually configured apps Resolve page and layout components as request-local instances Share compiled artifacts with the no-container manifest loader Prevent redeclaration fatals when reloading changed artifacts Disable shared caching for credential-bearing requests Reset all live instances instead of overwriting same-name callbacks Force form actions to use origin-relative request paths Write the development override before the base environment file Handle StopRequest before it crosses application middleware Allow token-only authenticators through the requireAuth gate Render child components before registering form actions Skip cache shortcut for active sessions and cookie-authenticated users
Review effort: Balanced
| return (false !== $sessionName && null !== $request->cookie($sessionName)) | ||
| || \PHP_SESSION_ACTIVE === \session_status() | ||
| || self::carriesCredentials($request); |
| if (0 !== $depth) { | ||
| continue; |
| $files = Scaffold::files(); | ||
| $files = ['.env.local' => $files['.env.local']] + $files; |
| if (0 === $parameter->getPosition() && (null === $type || ($isNamed && 'array' === $type->getName()))) { | ||
| return $props; | ||
| } |
| $page->renderToRegisterActions(); | ||
| $page->dispatchActionFromRequest(); |
| $page->renderToRegisterActions(); | ||
| $page->dispatchActionFromRequest(); | ||
| $pageElement = $page->renderAfterDispatch(); |
| // Go's CGI host cannot parse some of these and would answer 500, so | ||
| // the middleware cannot run. Neither may anything behind it: the | ||
| // error page and root layout may rely on what the middleware checks. | ||
| if (null === RequestPath::forMatching($request->path)) { |
| index worker.php | ||
| worker { | ||
| file ./public/worker.php |
| foreach (['RootLayout', 'ItemPage', 'ErrorPage'] as $class) { | ||
| $service = $this->builder->get($this->namespace . '\\' . $class); | ||
| self::assertTrue(\property_exists($service, 'renders')); | ||
| self::assertSame(0, $service->renders, $class . ' rendered on the shared service'); |
プロジェクト自身の .gitignore が .env.local を除外していないと、APP_ENV=dev の .env.local が commit されてデプロイされ、本番で dev になりうる。init と upgrade は 書いたときに /.env.local を .gitignore に足す (なければ作る)。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
AppRouter::run() がリセットした後に、雛形の worker.php が Relayer::endRequest() でもう一度リセットしていた。アプリの onReset() の処理が 2 回走る。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
polidog
left a comment
There was a problem hiding this comment.
レビューしました。v10 からのアップグレード時に .env.local の除外が保証されないケースを2件、再現条件付きでコメントしました。
| } | ||
|
|
||
| if (self::ENV_LOCAL_KEPT !== $moved) { | ||
| $ignore = GitignoreEnvLocal::ensure($root); |
There was a problem hiding this comment.
[P1] 追跡済みの .env.local には ignore が効きません
v10 の未変更 .env と、Git が既に追跡している FEATURE_FLAG=1 だけの .env.local がある状態で upgrade すると、この処理は後者に APP_ENV=dev を追記し、.gitignore を作った上で成功します。しかし Git は追跡済みファイルを ignore しないため、git status は .env.local を変更済みと表示し、そのままコミット・デプロイすると本番が dev になり profiler やスタックトレースが公開されます。一時 Git リポジトリで再現しました。既存ファイルへの追記前に追跡状態を確認し、安全に移行できない場合は変更せず明示的に警告するなどの対応が必要です。
There was a problem hiding this comment.
97a3cbb で直しました。書き込む前に git ls-files --error-unmatch .env.local で追跡されていないかを確かめます。追跡されていれば APP_ENV=dev は書かず、.env も書き換えません。理由と git rm --cached .env.local の手順を表示して、終了コード 1 で止まります。マーカーも進めないので、追跡を外して再実行すると移行が続きます。init はこのファイルだけ作らずに警告します。本物の git init を使う回帰テストで、修正前は失敗することを確認しました。
| return 1; | ||
| } | ||
|
|
||
| if (self::ENV_LOCAL_KEPT !== $moved) { |
There was a problem hiding this comment.
[P1] ignore 設定の失敗後、再実行すると検証を飛ばします
moveDevModeToEnvLocal() は先にファイルを作成・追記するため、続く ensure() が失敗すると APP_ENV=dev だけが残ります。その後原因を解消して再実行すると ENV_LOCAL_KEPT が返り、この条件で ensure() を通らず、除外されていないまま .env を書き換えて成功します。.gitignore をディレクトリにして初回を失敗させ、ディレクトリを除去して再実行すると .gitignore が存在しないまま終了することを確認しました。init にも同様に、失敗後は既存ファイルとして扱われて確認を飛ばす経路があります。再試行でも除外を確認するか、失敗時に作成・追記を巻き戻してください。
There was a problem hiding this comment.
97a3cbb で直しました。順番を「状態を読む → .gitignore を確かめる → 追跡を確かめる → 書き込む」に変え、確認に失敗したら何も書きません。.env.local が既に APP_ENV を持つ場合(前回の失敗で残った場合を含む)も、毎回 .gitignore を確かめます。init は雛形の .gitignore を先に書き、.env.local の直前に確かめます。.gitignore をディレクトリにして失敗させてから再実行する回帰テストで、修正前は失敗することを確認しました。
remember-me の middleware が session_start() のあと $next() の前に session_write_close() で閉じると、セッションはもう有効ではないので、 セッション Cookie を持たずに来たリクエストにも匿名の ETag で 304 を返し、 描画した応答も宣言どおり public のまま出ていた。 セッションを使っているかを「今有効か」に加えて「このレスポンスに セッション名の Set-Cookie が積まれているか」(headers_list())でも判定し、 304 の判定、描画後の方針の差し替え、limiter が残した Expires / Pragma の 除去のすべてに使う。Set-Cookie はそのレスポンスにしか載らないので、 worker でリクエストごとに消す状態を新たに持たない。 Fixes #123 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
CompiledPsxFile は再読み込みの前にトップレベルの宣言だけを調べていたため、
`if (true) { function helper() {} }` や `{ class X {} }` のようにガードのない
ブロックの中で宣言するファイルは、変更後の再読み込みで Cannot redeclare に
なり worker が落ちていた。
ファイルの実行時に宣言されるものを、if / else / try / ループ / switch /
素のブロックの中まで含めて調べるようにした。関数・クロージャ・クラスの
本体の中は実行されないので見ない。宣言の直上が自分の名前を調べる
`if (!function_exists('名前'))`(class_exists などは種類に合うもの)の
ときはガードとして扱い、これまでどおり再読み込みする。判定できない
ときは安全側で再読み込みを断る。波括弧が釣り合わないファイルは PHP が
何も宣言せずにコンパイルを失敗するので、require に構文エラーを報告させる。
Fixes #124
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
アクションを送信した POST の事前描画を、ページをレイアウトに組み込んだ木で行う。 レイアウトの中の Renderable が PageContext::current()->action() で登録した アクションも、ディスパッチの前に登録される。レイアウトの render() は 2 回走るので、 1 回目に addJs() したスクリプトは捨てて 2 重に出さない。 子の描画は RenderableChildren が受け持つ。応答の描画では描画関数をもう一度呼んで 新しい子を作り、1 回目の描画の子でアクションが変えたプロパティだけを、同じ位置に ある同じクラスの子へ描画の前に写す。readonly のプロパティは props として写さない。 アクションが $this に持った入力エラーが応答に出て、描画関数が作り直した props (足されたリストの項目など) もそのまま応答に出る。 あわせて、事前描画の前にファクトリが登録したアクション・スクリプト・メタデータを 覚えておき、応答の描画の前にそこへ戻す。ファクトリで $ctx->metadata() した <title> が POST の応答で既定値に戻らなくなる。 Fixes #125 Fixes #126 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
NativeProxy はルーティングに使うパスだけを検証していたため、guard が
`/%zz` を `withPath('/safe')` に書き換えると検証を通り、CgiRunner が元の
`/%zz` を REQUEST_URI として Go に渡して net/http/cgi が解析できずに 500
になっていた。middleware.go が無い場合も、guard や middleware.php が
書き換えたパスで route.go にマッチすると NativeDispatcher で同じことが
起きていた。
クライアントのリクエストターゲットを CgiRequestUri で検証する。制御文字、
フラグメントの不正なエスケープ、ルーターが受け付けないパス
(RequestPath と同じ規則)を含むものは、Go を起動せずフレームワークの
JSON 404 を返す(NativeProxy は後続のアプリコードも動かさない)。
REQUEST_URI はクライアントの URL、PATH_INFO は書き換え後のパスという
既存の約束は変えない。絶対形式(http://host/path)のターゲットは Go が
Host と連結して解析できないため、オリジン形式に直して渡す。CgiRunner::run
自体も解析できないターゲットでは子プロセスを起動しない。
Fixes #127
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
コンテナに登録したページ・レイアウト・エラーページは共有サービスとして 1 つの オブジェクトになり、ルーターはその浅い複製を描画していた。複製は浅いので、 ページがコンストラクタで作った可変オブジェクト(フォームや DTO など)は worker のリクエスト間で共有され、ある訪問者の状態が次の訪問者に残りえた。 ContainerFactory に NonSharedPagesPass を加え、PageComponent・ ErrorPageComponent を継承するクラスと LayoutInterface を実装するクラスの定義を 共有しないサービスにする。setShared(true) が指定されていても上書きする。 最適化フェーズで動くので、container:compile でダンプしたコンテナも同じ配線に なる。注入されるサービスはこれまでどおり共有される。 PageLoader の clone は残す。ContainerFactory を通らないコンテナや set() で 渡したオブジェクトは同じものを返しうるので、描画の書き込みがそのオブジェクトに 届かないようにするため。README に登録したページの扱いを書いた。 Fixes #128 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- deferred コンポーネントの例外は Rosanna の error_log にしか出ず、Relayer の logger とプロファイラに届かなかった。断片の描画で捕まえて記録し、応答は これまでどおりエンドポイントの 500 に任せる - コンテナなしの経路では RosannaDefer::setArgumentResolver() が効かなかった。 PsxComponentRegistrar::configure() の argumentResolver で渡せるようにする Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
polidog
left a comment
There was a problem hiding this comment.
レビューしました。キャッシュとリクエスト間の状態分離、および clone 不可のページに関する3点をコメントしました。
| */ | ||
| private static function sessionInUse(): bool | ||
| { | ||
| return \PHP_SESSION_ACTIVE === \session_status() || self::sessionCookieQueued(); |
There was a problem hiding this comment.
[P1] 既存セッションを閉じると個人向け応答が共有キャッシュ可能になります
既存の PHPSESSID を受け取ったリクエストでは、session_start() は通常 Set-Cookie を再発行しません。そのため、ミドルウェアが既存セッションを読み、session_write_close() してから $next() を呼ぶと、この判定は false になり、個人向け本文に Cache-Control: public が付きます。実際に既存 Cookie を付けて session を開始・終了した後に CachePolicy::emit(new Cache(public: true, maxAge: 60)) を呼ぶと、本文 alice と Cache-Control: public, max-age=60 が返りました。共有キャッシュから別の訪問者に配信される可能性があります。セッションの使用を閉じた後もリクエスト単位で追跡するか、既存 Cookie を含むケースでも共有キャッシュを無効にしてください。
There was a problem hiding this comment.
3d358cf で直しました。「このリクエストでセッションを開いたか」を isset($_SESSION) でも判定します。$_SESSION は session_start() で定義され、session_write_close() の後も残るので、どこから開いても、新規でも再開でも、閉じた後でも検出できます。worker ではスーパーグローバルが残るため、リクエストの終わりにセッションが開いていなければ $_SESSION を消します。FrankenPHP の worker で、既存のセッションを読んで閉じたリクエストが private, no-store になり、条件付き GET でも 304 を返さないこと、直後の匿名リクエストは public のままであることを確認しました。
| private const array PAGE_TYPES = [ | ||
| PageComponent::class, | ||
| ErrorPageComponent::class, | ||
| LayoutInterface::class, |
There was a problem hiding this comment.
[P1] Renderable のみを実装するページの内部状態が共有されます
PageLoader は PageComponent を継承しない Renderable もページとして受け付けますが、この一覧には含まれないため、コンテナに通常登録した場合は共有サービスのままです。PageLoader の clone は浅いので、ページのコンストラクターが作った可変フォームや DTO は元のサービスと共有され、worker の次の訪問者に前の状態が残ります。対象となるページを非共有で生成し、可変オブジェクトを持つ Renderable 単独実装のページについて2リクエストで確認してください。
There was a problem hiding this comment.
c607b35 で直しました。src/Pages の下にある page、layout、error ファイルに宣言されたクラスも非共有のサービスにします。Renderable を一律に非共有にすると、ページ以外のコンポーネントまで巻き込むためです。live とダンプしたコンテナの両方で、Renderable だけのページがコンストラクタで作った状態を 2 回目のリクエストに持ち越さないことを確かめました。修正前は失敗します。
| \assert(\is_object($instance)); | ||
|
|
||
| return $instance instanceof Renderable || $instance instanceof LayoutInterface | ||
| ? clone $instance |
There was a problem hiding this comment.
[P2] clone 不可のページやレイアウトが 500 になります
コンテナから取得したオブジェクトを常に clone するため、private __clone() を持つページやレイアウトでは Error が発生します。InjectorContainer::has() は未登録クラスにも true を返すため、通常の自動配線で新しく生成されたページにもこの経路が適用されます。clone 不可の Renderable を渡して例外を再現しました。新規生成されたインスタンスはそのまま使えるようにし、共有インスタンスの場合の扱いも明確にできないでしょうか。
There was a problem hiding this comment.
c607b35 で直しました。コンテナが毎回新しく作るもの(非共有の定義と自動配線)は複製しません。build 時に非共有のサービスの id を記録するので、ダンプしたコンテナでも判定できます。複製するのは共有されうるインスタンス(set() で渡したもの、独自の PSR-11 コンテナから来たもの)だけで、複製できない場合は 500 ではなく、クラス名と対処を示す RuntimeException にしました。private __clone() のページとレイアウトが、自動配線、登録 live、登録ダンプのいずれでも 200 になることを確認しました。
init と upgrade は .env.local に APP_ENV=dev を書いてから .gitignore を 確かめていたため、二つの穴があった。 - Git が追跡している .env.local は .gitignore では無視されず、追記した APP_ENV=dev が次のコミットで本番に届いた。git ls-files --error-unmatch で 追跡を確かめ、追跡中なら書かない。upgrade は .env も書き換えずに失敗し (開発モードを失わず、マーカーも進めないので再実行でやり直せる)、 git rm --cached .env.local を案内する。init はこのファイルだけ作らずに 案内する。git がない・作業ツリーでない場合は従来どおり。 - .gitignore の確認に失敗しても APP_ENV=dev は残り、再実行では 「設定済み」として確認を飛ばしていた。確認を書き込みの前に移し、 upgrade は .env.local がすでに APP_ENV を設定している場合も確認する。 init は雛形の .gitignore を .env.local より先に書き、失敗しても再実行で 新規プロジェクトのまま扱われる。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
セッション Cookie を持つリクエストで session_start() は Set-Cookie を 送り直さないため、middleware が既存セッションを読んで session_write_close() してから $next() を呼ぶと、セッションを使った痕跡が 何も残らず、public な Cache 方針がそのまま出ていた。 - session_start() が定義し、閉じても残る $_SESSION を「このリクエストで セッションを開いた」印として、304 の判定と共有キャッシュ可否の両方で 有効なセッションと同じに扱う。誰が session_start() を呼んでも効く - worker では $_SESSION がリクエストをまたいで残るので、 RequestLifecycle::reset() で閉じたセッションの $_SESSION を消す (前の訪問者のデータが次のリクエストから読めることも防ぐ) - ヘッダーは output_buffering により reset の後に送られることが多いので、 共有キャッシュ可能な方針の取り下げは reset の時点で先に判定する - セッションに触れないページはログイン中の訪問者にも public のまま Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
PageLoader は Renderable を実装するクラスならページとして受け付けるが、 NonSharedPagesPass は PageComponent などを継承しないクラスを共有サービスの ままにしていた。浅い複製ではコンストラクタで作ったフォームや DTO が worker の リクエスト間で共有されていた。NonSharedPagesPass は src/Pages の下の page・ layout・error ファイル(.php / .psx)で宣言されたクラスもトークンから読み取って 共有しないサービスにする。ほかの Renderable(コンポーネントなど)は共有のまま。 また、コンテナから取得したページ・レイアウトを常に clone していたため、 private __clone() を持つクラスは新しく作ったものでも Error で 500 になっていた。 NonSharedPagesPass は共有しないサービスの id をパラメータに記録し(ダンプした コンテナにも残る)、InjectorContainer::buildsNewInstance() がそれと未登録クラス の自動配線、ContainerBuilder の定義から、get() が毎回新しいオブジェクトを返すか を答える。PageLoader は新しいオブジェクトをそのまま使い、共有されうるもの (set() で渡したオブジェクトなど)だけを複製する。複製できなければ、クラス名と 共有しないサービスとして登録するよう伝える RuntimeException を投げる。 クラス名の読み取りは PageLoader から RouteFileClasses に移した。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>


Summary
Rosanna への移行後も usePHP 時代の形だった中核を作り直し、開いていた不具合を直します。公開 API(
AppRouter::create()/run()、ページの書き方)は変えません。AppRouterは設定だけを持ち、リクエストごとにRequestDispatchを作ります。フォームの変換は、描画前の木の走査から
RenderExtensionに移しました。破壊的変更(README の移行手順に記載)
APP_ENVのない.envは dev ではなく本番になります。雛形のAPP_ENV=devは gitignore 対象の.env.localに移しました。雛形のバージョンは 11 です。<div data-rosanna="…">を削除しました。rosanna-defer.jsは従来どおり全ページで読み込みます。defer のあるページだけにするならHtmlDocument::loadClientScriptOnlyWithDefer()を呼びます(ログアウト時のキャッシュのリスクがあるので opt-in です)。レビュー指摘への対応: Copilot の 2 回のレビューで出た指摘はすべてこの PR で直しました。主なものは次のとおりです。
Authorization)付きのリクエストへの応答は共有キャッシュに載せない(private, no-store)requireAuth()が動く(以前は 500)Throwableを catch する middleware にStopRequestを渡さないRenderableの子が登録したアクションも実行する(Renderable の子が PageContext::current() で登録したアクションが実行されない #122)relayer initは既存のアプリに dev の.env.localを書かない.env.localを書くときは.gitignoreで除外されていることを確かめるRequestLifecycleを 2 回リセットしないREQUEST_URIを渡さない(絶対形式はpath?queryに直す)、コンテナに登録したページを非共有のサービスにする<title>などが消えていた既存の不具合error_logだけでなくアプリの logger とプロファイラにも記録するPsxComponentRegistrar::configure()を使うコードは、argumentResolver:で独自のリゾルバーを渡せる.env.localにはAPP_ENV=devを書かない(upgradeは止まる)、.gitignoreの確認は書き込みの前に行い再実行でも必ず確認する、middleware が既存のセッションを読んで閉じたリクエストも共有キャッシュさせない、Renderableだけのページも作り直す、新しく作ったページは複製しない(複製できない共有インスタンスは原因を示す設定エラー)worker モードの修正(
mainにもある不具合):AuthenticatorとTokenAuthenticatorが最初のユーザーを覚えていて、匿名の訪問者が別人として認証されていました。リクエストごとの記憶はRequestLifecycleで必ず消します。exitはStopRequestにし、雛形のCaddyfileは実際に worker を使うようにしました。Fixes #102
Fixes #105
Fixes #106
Fixes #107
Fixes #108
Fixes #119
Fixes #120
Fixes #121
Fixes #122
Fixes #123
Fixes #124
Fixes #125
Fixes #126
Fixes #127
Fixes #128
Evidence
修正の前に回帰テストが失敗することを確認し、修正後に通ることを確認しました。
/aの次に/b/bに/aの$ctx->js()が出る。再度/aで 2 重Renderableの中のフォームaction="rosanna-action:…"、CSRF なしaction="/here"、CSRF ありAPP_ENVのない.envdebug=trueGET /x/a:80/x/[id]GET //adminGET //evil.example<form action="//evil.example">middleware.goとGET /%zzrelayer init --helpHi, Admin、/dashboardに入れるSign in、302Caddyfileindex.phpに流れ、worker を使わない#[Cache]の 304.envがAPP_ENV=prodのプロジェクトでupgrade.env.localを作る//ja/admin(パス接頭辞のロケール)/adminに届くTypeErrorCannot redeclarerelayer initで作ったサンプルサイトを Chromium と HTTP で検証しました(153〜154 項目)。php -S)relayer compile済み)Caddyfile)/%zzを PHP の手前で Caddy が 400 で返すので、そのモードに限り 400 も合格としています。static-build.Dockerfile)、worker でのクラス型#[Auth]のリダイレクト、React アイランドと i18n の実ブラウザ確認。Merge Danger
Door: two-way
コードは revert できます。ただし、リリース後に
relayer upgradeを実行したプロジェクトでは雛形が v11 に更新されるので、戻すには利用者側の対応も必要です。Blast Radius: consumers
relayer upgradeで未編集のCaddyfileは更新され、worker が有効になります。アプリ独自のサービスがリクエストの情報を持っていると、次の訪問者に漏れます。.env.localがないと本番モードで動き、PSX の未コンパイルエラーになります。echo APP_ENV=dev >> .env.localが必要です。Authorizationのあるリクエストには 304 を返さないので、その分の描画が増えます。//のパスは 404 になります。middleware.goのあるアプリでは、届かないパスに JSON の 404 を返します。array|string $p = []のような union 型の第 1 引数には$propsが渡らなくなります。autoCompile用に、Relayer 側でも manifest を書き出します(rosanna-defer の処理と重複があります)。残る問題: なし(レビューの指摘と、そこから作った Issue はすべてこの PR で対応済み)。
🤖 Generated with Claude Code