Skip to content

Automatically start new fiber for each request on PHP 8.1+ #117

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Feb 17, 2022
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
3 changes: 2 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@
"react/promise": "^2.7"
},
"require-dev": {
"phpunit/phpunit": "^9.5 || ^7.5"
"phpunit/phpunit": "^9.5 || ^7.5",
"react/async": "^4@dev || ^3@dev"
},
"autoload": {
"psr-4": {
Expand Down
16 changes: 16 additions & 0 deletions examples/index.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,22 @@
);
});

$app->get('/sleep/promise', function () {
return React\Promise\Timer\sleep(0.1)->then(function () {
return React\Http\Message\Response::plaintext("OK\n");
});
});
$app->get('/sleep/coroutine', function () {
yield React\Promise\Timer\sleep(0.1);
return React\Http\Message\Response::plaintext("OK\n");
});
if (PHP_VERSION_ID >= 80100 && function_exists('React\Async\async')) { // requires PHP 8.1+ with react/async 4+
$app->get('/sleep/fiber', function () {
React\Async\await(React\Promise\Timer\sleep(0.1));
return React\Http\Message\Response::plaintext("OK\n");
});
}

$app->get('/uri[/{path:.*}]', function (ServerRequestInterface $request) {
return React\Http\Message\Response::plaintext(
(string) $request->getUri() . "\n"
Expand Down
7 changes: 6 additions & 1 deletion src/App.php
Original file line number Diff line number Diff line change
Expand Up @@ -52,14 +52,19 @@ public function __construct(...$middleware)
}
}

// new MiddlewareHandler([$accessLogHandler, $errorHandler, ...$middleware, $routeHandler])
// new MiddlewareHandler([$fiberHandler, $accessLogHandler, $errorHandler, ...$middleware, $routeHandler])
\array_unshift($middleware, $errorHandler);

// only log for built-in webserver and PHP development webserver by default, others have their own access log
if (\PHP_SAPI === 'cli' || \PHP_SAPI === 'cli-server') {
\array_unshift($middleware, new AccessLogHandler());
}

// automatically start new fiber for each request on PHP 8.1+
if (\PHP_VERSION_ID >= 80100) {
\array_unshift($middleware, new FiberHandler()); // @codeCoverageIgnore
}

$this->router = new RouteHandler($container);
$middleware[] = $this->router;
$this->handler = new MiddlewareHandler($middleware);
Expand Down
60 changes: 60 additions & 0 deletions src/FiberHandler.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
<?php

namespace FrameworkX;

use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use React\Promise\Deferred;
use React\Promise\PromiseInterface;

/**
* [Internal] Fibers middleware handler to ensure each request is processed in a separate `Fiber`
*
* The `Fiber` class has been added in PHP 8.1+, so this middleware is only used
* on PHP 8.1+. On supported PHP versions, this middleware is automatically
* added to the list of middleware handlers, so there's no need to reference
* this class in application code.
*
* @internal
* @link https://framework-x.org/docs/async/fibers/
*/
class FiberHandler
{
/**
* @return ResponseInterface|PromiseInterface<ResponseInterface,void>|\Generator
* Returns a `ResponseInterface` from the next request handler in the
* chain. If the next request handler returns immediately, this method
* will return immediately. If the next request handler suspends the
* fiber (see `await()`), this method will return a `PromiseInterface`
* that is fulfilled with a `ResponseInterface` when the fiber is
* terminated successfully. If the next request handler returns a
* promise, this method will return a promise that follows its
* resolution. If the next request handler returns a Generator-based
* coroutine, this method returns a `Generator`. This method never
* throws or resolves a rejected promise. If the handler fails, it will
* be turned into a valid error response before returning.
* @throws void
*/
public function __invoke(ServerRequestInterface $request, callable $next): mixed
{
$deferred = null;
$fiber = new \Fiber(function () use ($request, $next, &$deferred) {
$response = $next($request);
assert($response instanceof ResponseInterface || $response instanceof PromiseInterface || $response instanceof \Generator);

if ($deferred !== null) {
$deferred->resolve($response);
}

return $response;
});

$fiber->start();
if ($fiber->isTerminated()) {
return $fiber->getReturn();
}

$deferred = new Deferred();
return $deferred->promise();
}
}
18 changes: 16 additions & 2 deletions tests/AppMiddlewareTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@

namespace FrameworkX\Tests;

use FrameworkX\AccessLogHandler;
use FrameworkX\App;
use FrameworkX\FiberHandler;
use FrameworkX\RouteHandler;
use PHPUnit\Framework\TestCase;
use Psr\Http\Message\ResponseInterface;
Expand Down Expand Up @@ -788,8 +790,20 @@ private function createAppWithoutLogger(...$middleware): App
$ref->setAccessible(true);
$handlers = $ref->getValue($middleware);

unset($handlers[0]);
$ref->setValue($middleware, array_values($handlers));
if (PHP_VERSION_ID >= 80100) {
$first = array_shift($handlers);
$this->assertInstanceOf(FiberHandler::class, $first);

$next = array_shift($handlers);
$this->assertInstanceOf(AccessLogHandler::class, $next);

array_unshift($handlers, $next, $first);
}

$first = array_shift($handlers);
$this->assertInstanceOf(AccessLogHandler::class, $first);

$ref->setValue($middleware, $handlers);

return $app;
}
Expand Down
137 changes: 135 additions & 2 deletions tests/AppTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
use FrameworkX\App;
use FrameworkX\Container;
use FrameworkX\ErrorHandler;
use FrameworkX\FiberHandler;
use FrameworkX\MiddlewareHandler;
use FrameworkX\RouteHandler;
use FrameworkX\SapiHandler;
Expand All @@ -26,10 +27,12 @@
use React\EventLoop\Loop;
use React\Http\Message\Response;
use React\Http\Message\ServerRequest;
use React\Promise\Deferred;
use React\Promise\Promise;
use React\Promise\PromiseInterface;
use ReflectionMethod;
use ReflectionProperty;
use function React\Async\await;
use function React\Promise\reject;
use function React\Promise\resolve;

Expand Down Expand Up @@ -72,6 +75,11 @@ public function testConstructWithMiddlewareAssignsGivenMiddleware()
$ref->setAccessible(true);
$handlers = $ref->getValue($handler);

if (PHP_VERSION_ID >= 80100) {
$first = array_shift($handlers);
$this->assertInstanceOf(FiberHandler::class, $first);
}

$this->assertCount(4, $handlers);
$this->assertInstanceOf(AccessLogHandler::class, $handlers[0]);
$this->assertInstanceOf(ErrorHandler::class, $handlers[1]);
Expand All @@ -93,6 +101,11 @@ public function testConstructWithContainerAssignsContainerForRouteHandlerOnly()
$ref->setAccessible(true);
$handlers = $ref->getValue($handler);

if (PHP_VERSION_ID >= 80100) {
$first = array_shift($handlers);
$this->assertInstanceOf(FiberHandler::class, $first);
}

$this->assertCount(3, $handlers);
$this->assertInstanceOf(AccessLogHandler::class, $handlers[0]);
$this->assertInstanceOf(ErrorHandler::class, $handlers[1]);
Expand Down Expand Up @@ -122,6 +135,11 @@ public function testConstructWithContainerAndMiddlewareClassNameAssignsCallableF
$ref->setAccessible(true);
$handlers = $ref->getValue($handler);

if (PHP_VERSION_ID >= 80100) {
$first = array_shift($handlers);
$this->assertInstanceOf(FiberHandler::class, $first);
}

$this->assertCount(4, $handlers);
$this->assertInstanceOf(AccessLogHandler::class, $handlers[0]);
$this->assertInstanceOf(ErrorHandler::class, $handlers[1]);
Expand Down Expand Up @@ -820,6 +838,57 @@ public function testHandleRequestWithMatchingRouteReturnsPendingPromiseWhenHandl
$this->assertFalse($resolved);
}

public function testHandleRequestWithMatchingRouteReturnsPromiseResolvingWithResponseWhenHandlerReturnsResponseAfterAwaitingPromiseResolvingWithResponse()
{
if (PHP_VERSION_ID < 80100 || !function_exists('React\Async\async')) {
$this->markTestSkipped('Requires PHP 8.1+ with react/async 4+');
}

$app = $this->createAppWithoutLogger();

$deferred = new Deferred();

$app->get('/users', function () use ($deferred) {
return await($deferred->promise());
});

$request = new ServerRequest('GET', 'http://localhost/users');

// $promise = $app->handleRequest($request);
$ref = new ReflectionMethod($app, 'handleRequest');
$ref->setAccessible(true);
$promise = $ref->invoke($app, $request);

/** @var PromiseInterface $promise */
$this->assertInstanceOf(PromiseInterface::class, $promise);

$response = null;
$promise->then(function ($value) use (&$response) {
$response = $value;
});

$this->assertNull($response);

$deferred->resolve(new Response(
200,
[
'Content-Type' => 'text/html'
],
"OK\n"
));

// await next tick: https://github.com/reactphp/async/issues/27
await(new Promise(function ($resolve) {
Loop::futureTick($resolve);
}));

/** @var ResponseInterface $response */
$this->assertInstanceOf(ResponseInterface::class, $response);
$this->assertEquals(200, $response->getStatusCode());
$this->assertEquals('text/html', $response->getHeaderLine('Content-Type'));
$this->assertEquals("OK\n", (string) $response->getBody());
}

public function testHandleRequestWithMatchingRouteAndRouteVariablesReturnsResponseFromHandlerWithRouteVariablesAssignedAsRequestAttributes()
{
$app = $this->createAppWithoutLogger();
Expand Down Expand Up @@ -1047,6 +1116,58 @@ public function testHandleRequestWithMatchingRouteReturnsPromiseWhichFulfillsWit
$this->assertStringContainsString("<p>Expected request handler to return <code>Psr\Http\Message\ResponseInterface</code> but got uncaught <code>RuntimeException</code> with message <code>Foo</code> in <code title=\"See " . __FILE__ . " line $line\">AppTest.php:$line</code>.</p>\n", (string) $response->getBody());
}

public function testHandleRequestWithMatchingRouteReturnsPromiseWhichFulfillsWithInternalServerErrorResponseWhenHandlerThrowsAfterAwaitingPromiseRejectingWithException()
{
if (PHP_VERSION_ID < 80100 || !function_exists('React\Async\async')) {
$this->markTestSkipped('Requires PHP 8.1+ with react/async 4+');
}

$app = $this->createAppWithoutLogger();

$deferred = new Deferred();

$line = __LINE__ + 1;
$exception = new \RuntimeException('Foo');

$app->get('/users', function () use ($deferred) {
return await($deferred->promise());
});

$request = new ServerRequest('GET', 'http://localhost/users');

// $promise = $app->handleRequest($request);
$ref = new ReflectionMethod($app, 'handleRequest');
$ref->setAccessible(true);
$promise = $ref->invoke($app, $request);

/** @var PromiseInterface $promise */
$this->assertInstanceOf(PromiseInterface::class, $promise);

$response = null;
$promise->then(function ($value) use (&$response) {
$response = $value;
});

$this->assertNull($response);

$deferred->reject($exception);

// await next tick: https://github.com/reactphp/async/issues/27
await(new Promise(function ($resolve) {
Loop::futureTick($resolve);
}));

/** @var ResponseInterface $response */
$this->assertInstanceOf(ResponseInterface::class, $response);
$this->assertEquals(500, $response->getStatusCode());
$this->assertEquals('text/html; charset=utf-8', $response->getHeaderLine('Content-Type'));
$this->assertStringMatchesFormat("<!DOCTYPE html>\n<html>%a</html>\n", (string) $response->getBody());

$this->assertStringContainsString("<title>Error 500: Internal Server Error</title>\n", (string) $response->getBody());
$this->assertStringContainsString("<p>The requested page failed to load, please try again later.</p>\n", (string) $response->getBody());
$this->assertStringContainsString("<p>Expected request handler to return <code>Psr\Http\Message\ResponseInterface</code> but got uncaught <code>RuntimeException</code> with message <code>Foo</code> in <code title=\"See " . __FILE__ . " line $line\">AppTest.php:$line</code>.</p>\n", (string) $response->getBody());
}

public function testHandleRequestWithMatchingRouteReturnsPromiseWhichFulfillsWithInternalServerErrorResponseWhenHandlerReturnsCoroutineWhichReturnsNull()
{
$app = $this->createAppWithoutLogger();
Expand Down Expand Up @@ -1386,8 +1507,20 @@ private function createAppWithoutLogger(): App
$ref->setAccessible(true);
$handlers = $ref->getValue($middleware);

unset($handlers[0]);
$ref->setValue($middleware, array_values($handlers));
if (PHP_VERSION_ID >= 80100) {
$first = array_shift($handlers);
$this->assertInstanceOf(FiberHandler::class, $first);

$next = array_shift($handlers);
$this->assertInstanceOf(AccessLogHandler::class, $next);

array_unshift($handlers, $next, $first);
}

$first = array_shift($handlers);
$this->assertInstanceOf(AccessLogHandler::class, $first);

$ref->setValue($middleware, $handlers);

return $app;
}
Expand Down
Loading