Skip to content

Commit 3700254

Browse files
authored
[Docs] Fix the fiber context recipe for event loops (#685)
* [Docs] Show a fiber context recipe that survives PHP assertions * [Tests] Cover abandoned streams and a failing wrap in all fiber context modes * [Docs] Build the server in the fiber context example
1 parent 0c184ad commit 3700254

3 files changed

Lines changed: 69 additions & 11 deletions

File tree

‎docs/run/server-builder.md‎

Lines changed: 19 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -347,6 +347,7 @@ A fiber scheduler lets handlers await I/O while the event loop serves other requ
347347
- A [session lock](sessions.md#concurrent-requests) stays held while a handler awaits I/O. Another request of the
348348
same session in the same process waits on the event loop until the lock is free. This wait has no timeout. If
349349
another process holds the lock, the lock backend blocks the event loop while it waits, up to its timeout.
350+
350351
### Fiber Context
351352

352353
Some libraries keep their context per fiber. For example, OpenTelemetry raises a warning when code reads its context
@@ -378,15 +379,30 @@ final class OpenTelemetryFiberContext implements FiberContextInterface
378379
}
379380

380381
$server = Server::builder()
381-
->setFiberContext(new OpenTelemetryFiberContext());
382+
->setFiberContext(new OpenTelemetryFiberContext())
383+
->build();
382384
```
383385

384386
The returned closure must call `$handler` once and return its result. The `finally` block also runs when the server
385387
discards a suspended fiber.
386388

387389
Under an event loop, every request runs in its own fiber, so OpenTelemetry raises the same warning in `wrap()`. Activate
388-
a context in that fiber first, for example with `Context::getRoot()->activate()`. Fibers that a handler starts itself
389-
(e.g. with `Amp\async()`) don't get the context.
390+
a context in that fiber before you run the server, and detach it in a `finally` block:
391+
392+
```php
393+
$scope = Context::getRoot()->activate();
394+
395+
try {
396+
$response = $server->run($transport);
397+
} finally {
398+
$scope->detach();
399+
}
400+
```
401+
402+
Keep the returned scope in a variable. If PHP assertions are enabled, OpenTelemetry raises a notice when a scope is
403+
destroyed before you detach it.
404+
405+
Fibers that a handler starts itself (e.g. with `Amp\async()`) don't get the context.
390406

391407
## Complete Example
392408

‎tests/Unit/Fixtures/RecordingFiberContext.php‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ final class RecordingFiberContext implements FiberContextInterface
2222
public string $parent = 'parent';
2323
public int $created = 0;
2424
public int $released = 0;
25+
public ?\Throwable $wrapFailure = null;
2526

2627
/** @var \WeakMap<object, string> */
2728
private \WeakMap $contexts;
@@ -33,6 +34,10 @@ public function __construct()
3334

3435
public function wrap(\Closure $handler): \Closure
3536
{
37+
if (null !== $this->wrapFailure) {
38+
throw $this->wrapFailure;
39+
}
40+
3641
$context = $this->current();
3742
++$this->created;
3843

‎tests/Unit/Server/Fiber/FiberContextTest.php‎

Lines changed: 45 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -108,23 +108,60 @@ public function testContextIsReleasedWithoutSuspension(string $mode, bool $fail)
108108
$this->assertSame('parent', $context->current());
109109
}
110110

111-
public function testContextIsReleasedWhenAStreamIsAbandoned(): void
111+
#[DataProvider('modes')]
112+
public function testContextIsReleasedWhenAStreamIsAbandoned(string $mode): void
112113
{
113114
$context = new RecordingFiberContext();
114-
$server = $this->builder($context)->addTool(static function (RequestContext $request) use ($context): string {
115+
$builder = $this->builder($context)->addTool(static function (RequestContext $request) use ($context): string {
115116
$request->getClientGateway()->progress(1, 2);
116117

117118
return $context->current();
118-
}, name: 'probe')->buildStateless();
119-
$response = $this->post($server, $this->call(true));
120-
$this->assertSame(1, $context->created);
121-
$this->assertSame(0, $context->released);
119+
}, name: 'probe');
120+
$server = 'standalone' === $mode ? $builder->buildStateless() : $builder->build();
121+
$session = 'legacy' === $mode ? $this->post($server, $this->initialize())->getHeaderLine('Mcp-Session-Id') : null;
122+
$created = $context->created;
123+
$released = $context->released;
124+
125+
$response = $this->post($server, $this->call('legacy' !== $mode), $session);
126+
$this->assertSame($created + 1, $context->created);
127+
$this->assertSame($released, $context->released);
122128
unset($response);
123129

124-
$this->assertSame(1, $context->released);
130+
$this->assertSame($released + 1, $context->released);
125131
$this->assertSame('parent', $context->current());
126132
}
127133

134+
/**
135+
* @return iterable<string, array{string}>
136+
*/
137+
public static function modes(): iterable
138+
{
139+
foreach (['legacy', 'modern', 'standalone'] as $mode) {
140+
yield $mode => [$mode];
141+
}
142+
}
143+
144+
#[DataProvider('modes')]
145+
public function testAFailingWrapAnswersWithAnInternalError(string $mode): void
146+
{
147+
$context = new RecordingFiberContext();
148+
$called = false;
149+
$builder = $this->builder($context)->addTool(static function () use (&$called): string {
150+
$called = true;
151+
152+
return 'unreachable';
153+
}, name: 'probe');
154+
$server = 'standalone' === $mode ? $builder->buildStateless() : $builder->build();
155+
$session = 'legacy' === $mode ? $this->post($server, $this->initialize())->getHeaderLine('Mcp-Session-Id') : null;
156+
$context->wrapFailure = new RuntimeException('wrap failed');
157+
158+
$body = $this->consume($this->post($server, $this->call('legacy' !== $mode), $session));
159+
160+
$this->assertStringContainsString('"code":-32603', $body);
161+
$this->assertStringNotContainsString('wrap failed', $body);
162+
$this->assertFalse($called);
163+
}
164+
128165
public function testContextIsReleasedWhenElicitationDiscardsTheFiber(): void
129166
{
130167
$context = new RecordingFiberContext();
@@ -147,7 +184,7 @@ public function testContextIsReleasedWhenElicitationDiscardsTheFiber(): void
147184
}
148185

149186
#[DataProvider('eras')]
150-
public function testStdioUsesTheFactory(bool $modern): void
187+
public function testStdioUsesTheFiberContext(bool $modern): void
151188
{
152189
$context = new RecordingFiberContext();
153190
$builder = $this->builder($context)->addTool(static function (RequestContext $request) use ($context): string {

0 commit comments

Comments
 (0)