Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion README.ja.md
Original file line number Diff line number Diff line change
Expand Up @@ -2776,7 +2776,9 @@ dev 限定のリクエストプロファイラです。各リクエストを `Pr

dev では Traceable デコレータ群が AppRouter / Database / EtagStore /
SessionStorage / Authenticator をラップし、`db.query`・`cache.etag_*`・
`session.*` などのスパンを自動でプロファイルへ流します。`<X defer />`
`session.*` などのスパンを自動でプロファイルへ流します。描画中に Rosanna が出す notice
(属性を捨てたときなど)は `rosanna.notice` / `rosanna.warning` として記録し、そのあと
元のエラーハンドラに渡します。`<X defer />`
によるサブリクエストは `parentToken` で親リクエストに紐づきます。

### Web ビュー
Expand Down Expand Up @@ -2973,6 +2975,12 @@ Relayer は `polidog/rosanna` と `polidog/rosanna-defer` の上で動くよう
クラシック(リクエストごと)モードのままにするには、`Caddyfile` から `index` と
`worker` の行を消してください。

Rosanna は一部の prop を React と違うように描画します。`style` は文字列で渡してください
(`style="color: red"`)。配列は捨てられます。`key` は特別扱いされず、`<li key="1">` は
そのまま出力されます。生 HTML を差し込む手段はなく、`dangerouslySetInnerHTML` もほかの
スカラーでない属性と同じく捨てられます。Rosanna は捨てた属性ごとに `E_USER_NOTICE` を
出し、dev では[プロファイラ](#プロファイラ)が `rosanna` イベントとして記録します。

フィールド名とセッションのキーが変わるので、旧バージョンが描画したフォームは
デプロイの時点で動かなくなります。古い HTML や `usephp.js` が配信されないよう、
デプロイ時に CDN のキャッシュを消してください。
Expand Down
11 changes: 10 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2787,7 +2787,9 @@ A dev-only request profiler. Each request is recorded as a `Profile`

In dev, the Traceable decorators wrap AppRouter / Database / EtagStore /
SessionStorage / Authenticator and feed spans like `db.query`,
`cache.etag_*`, and `session.*` into the profile automatically.
`cache.etag_*`, and `session.*` into the profile automatically. Notices
Rosanna raises while rendering (an attribute it drops) are recorded as
`rosanna.notice` / `rosanna.warning`, then passed on to your error handler.
`<X defer />` sub-requests are linked to their parent via `parentToken`.

### Web view
Expand Down Expand Up @@ -2984,6 +2986,13 @@ island instead. `USEPHP_SNAPSHOT_SECRET` is no longer read, and
To stay in classic (per-request) mode, remove the `index` and `worker` lines
from the `Caddyfile`.

Rosanna renders some props differently from React. Pass `style` as a string
(`style="color: red"`); an array is dropped. `key` is not special: `<li key="1">`
renders as is. There is no raw HTML injection: `dangerouslySetInnerHTML` is
dropped like any other non-scalar attribute. Rosanna reports each dropped
attribute with an `E_USER_NOTICE`, and in dev the [profiler](#profiler) records
it as a `rosanna` event.

Forms rendered by the previous version stop working when you deploy, because
the field names and the session keys changed. Purge your CDN at deploy time so
it does not serve old HTML or the old `usephp.js`.
Expand Down
75 changes: 75 additions & 0 deletions src/Profiler/RosannaNoticeCollector.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
<?php

declare(strict_types=1);

namespace Polidog\Relayer\Profiler;

use Polidog\Rosanna\Runtime\Renderer;
use ReflectionClass;

/**
* Dev-only error handler that records the notices Rosanna raises while
* rendering (an attribute dropped because its value is not scalar, such as
* `style={[...]}` or `dangerouslySetInnerHTML={[...]}`) as `rosanna` profiler
* events, so they show up on `/_profiler` instead of vanishing.
*
* Only `E_USER_NOTICE` / `E_USER_WARNING` raised from Rosanna's own source
* are recorded. Every error, recorded or not, is then handed to the handler
* that was active before {@see install()} (or to PHP's standard handler when
* there was none), so the existing error handling is unchanged.
*/
final class RosannaNoticeCollector
{
private bool $installed = true;

private function __construct() {}

public static function install(Profiler $profiler): self
{
$sourceDir = self::rosannaSourceDir();
$previous = null;
$previous = \set_error_handler(
static function (int $errno, string $errstr, string $errfile = '', int $errline = 0) use ($profiler, $sourceDir, &$previous): bool {
if (null !== $sourceDir && \str_starts_with($errfile, $sourceDir)) {
$profiler->collect('rosanna', \E_USER_WARNING === $errno ? 'warning' : 'notice', [
'message' => $errstr,
'file' => $errfile,
'line' => $errline,
]);
}

if (\is_callable($previous)) {
return false !== $previous($errno, $errstr, $errfile, $errline);
}

return false;
},
\E_USER_NOTICE | \E_USER_WARNING,
);

return new self();
}

/**
* Restore the handler that was active before {@see install()}.
* Idempotent.
*/
public function restore(): void
{
if ($this->installed) {
$this->installed = false;
\restore_error_handler();
}
}

private static function rosannaSourceDir(): ?string
{
$file = new ReflectionClass(Renderer::class)->getFileName();
if (false === $file) {
return null;
}

// Renderer lives in `<rosanna>/src/Runtime/`; match all of `src/`.
return \dirname($file, 2) . \DIRECTORY_SEPARATOR;
}
}
8 changes: 8 additions & 0 deletions src/Router/Dispatch/RequestDispatch.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
use Polidog\Relayer\I18n\LocaleResolver;
use Polidog\Relayer\I18n\Translators;
use Polidog\Relayer\InjectorContainer;
use Polidog\Relayer\Profiler\RosannaNoticeCollector;
use Polidog\Relayer\Router\Component\FunctionPage;
use Polidog\Relayer\Router\Component\PageContext;
use Polidog\Relayer\Router\Document\DocumentInterface;
Expand Down Expand Up @@ -149,6 +150,12 @@ private function dispatchInScope(Request $request, int $outputLevel): void
// LocaleResolver is bound.
$request = $this->request = $this->resolveLocale($request);

// Dev only: record the notices Rosanna raises while rendering
// (attributes it drops) on the profile instead of losing them.
$rosannaNotices = null !== $this->env->recording && null !== $this->env->recording->currentProfile()
? RosannaNoticeCollector::install($this->env->recording)
: null;

try {
// Deferred component GETs (under `/_defer/{name}`) are dispatched
// before route matching: Rosanna owns that URL space, and we
Expand Down Expand Up @@ -208,6 +215,7 @@ private function dispatchInScope(Request $request, int $outputLevel): void
// closure translates them and stops StopRequest itself.
$this->errors->respondToUncaught($exception, $this->request, $outputLevel, true);
} finally {
$rosannaNotices?->restore();
$this->end();
}
}
Expand Down
98 changes: 98 additions & 0 deletions tests/Profiler/RosannaNoticeCollectorTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
<?php

declare(strict_types=1);

namespace Polidog\Relayer\Tests\Profiler;

use PHPUnit\Framework\Attributes\CoversClass;
use PHPUnit\Framework\TestCase;
use Polidog\Relayer\Profiler\RecordingProfiler;
use Polidog\Relayer\Profiler\RosannaNoticeCollector;
use Polidog\Rosanna\Runtime\Element;
use Polidog\Rosanna\Runtime\Renderer;

#[CoversClass(RosannaNoticeCollector::class)]
final class RosannaNoticeCollectorTest extends TestCase
{
/** @var list<string> */
private array $forwarded = [];

protected function setUp(): void
{
$this->forwarded = [];
// Stands in for the app's own handler: the collector must hand
// every error on to it.
\set_error_handler(function (int $errno, string $errstr): bool {
$this->forwarded[] = $errstr;

return true;
});
}

protected function tearDown(): void
{
\restore_error_handler();
}

public function testRecordsDroppedAttributesAndForwardsToThePreviousHandler(): void
{
$profiler = new RecordingProfiler();
$profile = $profiler->beginProfile('/', 'GET');

$collector = RosannaNoticeCollector::install($profiler);

try {
$html = new Renderer()->renderElement(new Element('li', [
'key' => '1',
'style' => ['color' => 'red'],
'dangerouslySetInnerHTML' => ['__html' => '<b>x</b>'],
], ['a']));
} finally {
$collector->restore();
}

// What the README documents: `key` is rendered, the arrays are dropped.
self::assertSame('<li key="1">a</li>', $html);

$events = $profile->getEvents();
self::assertCount(2, $events);
self::assertSame('rosanna', $events[0]->collector);
self::assertSame('notice', $events[0]->label);
self::assertSame('Non-scalar value for attribute "style" (array) was dropped.', $events[0]->payload['message']);
self::assertSame('Non-scalar value for attribute "dangerouslySetInnerHTML" (array) was dropped.', $events[1]->payload['message']);

self::assertCount(2, $this->forwarded);
}

public function testIgnoresNoticesFromOutsideRosannaButStillForwardsThem(): void
{
$profiler = new RecordingProfiler();
$profile = $profiler->beginProfile('/', 'GET');

$collector = RosannaNoticeCollector::install($profiler);

try {
\trigger_error('app notice', \E_USER_NOTICE);
} finally {
$collector->restore();
}

self::assertSame([], $profile->getEvents());
self::assertSame(['app notice'], $this->forwarded);
}

public function testRestoreReinstatesThePreviousHandlerOnce(): void
{
$profiler = new RecordingProfiler();
$profile = $profiler->beginProfile('/', 'GET');

$collector = RosannaNoticeCollector::install($profiler);
$collector->restore();
$collector->restore();

new Renderer()->renderElement(new Element('div', ['style' => ['color' => 'red']]));

self::assertSame([], $profile->getEvents());
self::assertCount(1, $this->forwarded);
}
}
33 changes: 33 additions & 0 deletions tests/Router/AppRouterProfilerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -230,6 +230,39 @@ public function testProfilerExcludedPrefixesNormalizesLeadingSlash(): void
self::assertSame([], $storage->saved);
}

public function testRosannaNoticesDuringDispatchLandOnTheProfile(): void
{
\mkdir($this->workDir . '/styled', 0o777, true);
\file_put_contents(
$this->workDir . '/styled/route.php',
"<?php\n\nuse Polidog\\Relayer\\Http\\Response;\nuse Polidog\\Rosanna\\Runtime\\Element;\nuse Polidog\\Rosanna\\Runtime\\Renderer;\n\n"
. "return ['GET' => static fn (): Response => Response::text(\n"
. " new Renderer()->renderElement(new Element('p', ['style' => ['color' => 'red']], ['hi'])),\n"
. ")];\n",
);
$storage = new InMemoryProfilerStorage();
$router = AppRouter::create($this->workDir)->setProfiler(new RecordingProfiler($storage), $storage);

// The collector forwards to the previous handler; swallow there so
// PHPUnit does not report the notice.
\set_error_handler(static fn (): bool => true);

try {
$output = $this->dispatch($router, '/styled', 'GET');
} finally {
\restore_error_handler();
}

self::assertSame('<p>hi</p>', $output);
$profile = \array_values($storage->saved)[0];
$notices = \array_values(\array_filter(
$profile->getEvents(),
static fn ($event): bool => 'rosanna' === $event->collector,
));
self::assertCount(1, $notices);
self::assertSame('Non-scalar value for attribute "style" (array) was dropped.', $notices[0]->payload['message']);
}

private function dispatch(AppRouter $router, string $path, string $method): string
{
$_SERVER['REQUEST_URI'] = $path;
Expand Down
Loading