Skip to content
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

add coroutine support #24

Open
wants to merge 2 commits into
base: 2.x.x
Choose a base branch
from
Open
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
2 changes: 1 addition & 1 deletion .github/workflows/coding-standards.yml
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ jobs:
dependencies:
- "locked"
php-version:
- "7.4"
- "8.0"
operating-system:
- "ubuntu-latest"

Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/mutation-tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ jobs:
dependencies:
- "locked"
php-version:
- "7.4"
- "8.0"
operating-system:
- "ubuntu-latest"

Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/phpunit.yml
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ jobs:
dependencies:
- "locked"
php-version:
- "7.4"
- "8.0"
operating-system:
- "ubuntu-latest"

Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/psalm.yml
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ jobs:
dependencies:
- "locked"
php-version:
- "7.4"
- "8.0"
operating-system:
- "ubuntu-latest"

Expand Down
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
}
],
"require": {
"php": "^7.4|^8.0",
"php": "^8.0",
"antidot-fw/framework": "^0.2.0",
"beberlei/assert": "^3.3",
"drift/server": "^0.1.20",
Expand Down
48 changes: 42 additions & 6 deletions docs/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,8 @@ It allows executing promises inside PSR-15 and PSR-7 Middlewares and request han

### PSR-15 Middleware

**Promise Based**

```php
<?php
declare(strict_types = 1);
Expand All @@ -111,21 +113,24 @@ use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
use function React\Promise\resolve;

class SomeMiddleware implements MiddlewareInterface
{
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
return new PromiseResponse(
resolve($request)
->then(static fn(ServerrequestInsterface $request) => $handler->handle($request))
->then(static fn(ServerRequestInterface $request) => $handler->handle($request))
);
}
}
```

### PSR-7 Request Handler

**Promise Based**

```php
<?php
declare(strict_types = 1);
Expand All @@ -136,16 +141,47 @@ use Antidot\React\PromiseResponse;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
use function React\Promise\resolve;

class SomeMiddleware implements RequestHandlerInterface
class SomeRequestHandler implements RequestHandlerInterface
{
public function process(ServerRequestInterface $request): ResponseInterface
public function handle(ServerRequestInterface $request): ResponseInterface
{
return resolve($request)->then(
function(ServerrequestInterface $request): ResponseInterface {
return new PromiseResponse(resolve($request)->then(
function(ServerRequestInterface $request): ResponseInterface {
return new Response('Hello World!!!');
}
);;
));
}
}
```

**Coroutine based**

```php
<?php
declare(strict_types = 1);

namespace App;

use Antidot\React\PromiseResponse;
use Generator;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
use function React\Promise\resolve;

class SomeRequestHandler implements RequestHandlerInterface
{
public function handle(ServerRequestInterface $request): ResponseInterface
{
return PromiseResponse::fromGeneratorCallback(
function(ServerRequestInterface $request): Generator {
$message = yield resolve('Hello World!!!');

return new Response($message);
}
));
}
}
```
Expand Down
11 changes: 6 additions & 5 deletions src/DriftKernelAdapter.php
Original file line number Diff line number Diff line change
Expand Up @@ -68,17 +68,18 @@ public static function create(
}

return resolve(new self($serverContext, $mimeTypeChecker, $rootPath, $filesystem))
->then(fn (KernelAdapter $adapter): KernelAdapter => $adapter);
->then(static fn(KernelAdapter $adapter): KernelAdapter => $adapter);
}

/**
* @psalm-suppress LessSpecificImplementedReturnType
* @param ServerRequestInterface $request
* @return PromiseResponse
* @psalm-suppress LessSpecificImplementedReturnType
*/
public function handle(ServerRequestInterface $request): PromiseResponse
public function handle(ServerRequestInterface $request): PromiseInterface
{
return $this->application->handle($request);
return $this->application
->handle($request)
->then([ResolveGenerator::class, 'toResponse']);
}

public static function getStaticFolder(): ?string
Expand Down
3 changes: 0 additions & 3 deletions src/MiddlewarePipeline.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Ramsey\Uuid\Uuid;
use SplQueue;
use Throwable;
use function React\Promise\reject;
use function React\Promise\resolve;
Expand Down Expand Up @@ -53,7 +52,6 @@ function (ServerRequestInterface $request) {
/** @var string $requestId */
$requestId = $request->getAttribute('request_id');
try {
/** @var MiddlewareInterface $middleware */
$middleware = $this->concurrentPipelines[$requestId]->dequeue();

$response = $middleware->process($request, $this);
Expand Down Expand Up @@ -84,7 +82,6 @@ public function process(ServerRequestInterface $request, RequestHandlerInterface
/** @var string $requestId */
$requestId = $request->getAttribute('request_id');
try {
/** @var MiddlewareQueue $queue */
$queue = $this->concurrentPipelines[$requestId];
$next = new NextHandler($queue, $handler);

Expand Down
23 changes: 22 additions & 1 deletion src/PromiseResponse.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,12 @@

namespace Antidot\React;

use Generator;
use React\Promise\PromiseInterface;
use RingCentral\Psr7\Response;
use function React\Promise\resolve;

class PromiseResponse extends Response implements PromiseInterface
final class PromiseResponse extends Response implements PromiseInterface
{
private PromiseInterface $promise;
protected $stream;
Expand All @@ -28,6 +30,25 @@ public function __construct(
$this->promise = $promise;
}

/**
* @param callable<Generator> $callback
* @return static
*/
public static function fromGeneratorCallback(callable $callback): self
{
return new self(resolve(function () use ($callback): Generator {
/** @var Generator $generator */
$generator = $callback();

return $generator;
}));
}

/**
* @param callable|null $onFulfilled
* @param callable|null $onRejected
* @param callable|null $onProgress
*/
final public function then(
callable $onFulfilled = null,
callable $onRejected = null,
Expand Down
45 changes: 45 additions & 0 deletions src/ResolveGenerator.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
<?php

declare(strict_types=1);

namespace Antidot\React;

use Generator;
use Psr\Http\Message\ResponseInterface;
use React\Promise\Promise;
use React\Promise\PromiseInterface;
use Throwable;

final class ResolveGenerator
{
/**
* @param callable<Generator>|ResponseInterface|PromiseInterface $generator
*/
public static function toResponse(
callable|ResponseInterface|PromiseInterface $callback
): PromiseInterface|ResponseInterface {
if (false === is_callable($callback)) {
return $callback;
}

return new Promise(
static function (callable $resolve, callable $reject) use ($callback): void {
try {
/** @var Generator<PromiseInterface|ResponseInterface> $generator */
$generator = $callback();
while ($generator->valid()) {
$item = $generator->current();
if ($item instanceof PromiseInterface) {
$item->then(static fn($solved) => $generator->send($solved));
continue;
}
$generator->send($item);
}
$resolve($generator->getReturn());
} catch (Throwable $exception) {
$reject($exception);
}
}
);
}
}
8 changes: 4 additions & 4 deletions src/RunServerCommandFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,13 +28,13 @@ public function __invoke(ContainerInterface $container): RunServerCommand
$adapter = $definition->getOption('adapter');
$adapter->setDefault(DriftKernelAdapter::class);
$staticFolder = $definition->getOption('static-folder');
$staticFolder->setDefault($config['static_folder']);
$staticFolder->setDefault((string)$config['static_folder']);
$workers = $definition->getOption('workers');
$workers->setDefault($config['workers']);
$workers->setDefault((string)$config['workers']);
$concurrentRequests = $definition->getOption('concurrent-requests');
$concurrentRequests->setDefault($config['max_concurrency']);
$concurrentRequests->setDefault((string)$config['max_concurrency']);
$bufferSize = $definition->getOption('request-body-buffer');
$bufferSize->setDefault($config['buffer_size']);
$bufferSize->setDefault((string)$config['buffer_size']);

return $command;
}
Expand Down
10 changes: 5 additions & 5 deletions src/ServerFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,6 @@
use React\Http\Middleware\RequestBodyBufferMiddleware;
use React\Http\Middleware\RequestBodyParserMiddleware;
use React\Http\Middleware\StreamingRequestMiddleware;
use React\Promise\PromiseInterface;
use function PHPUnit\Framework\assertArrayHasKey;
use function PHPUnit\Framework\assertIsInt;
use function React\Promise\resolve;

class ServerFactory
{
Expand All @@ -42,7 +38,11 @@ public function __invoke(ContainerInterface $container): Server
new LimitConcurrentRequestsMiddleware($config['max_concurrency']),
new RequestBodyBufferMiddleware($config['buffer_size']),
new RequestBodyParserMiddleware(),
static fn (ServerRequestInterface $request): PromiseInterface => resolve($application->handle($request))
static function (ServerRequestInterface $request) use ($application) {
return $application
->handle($request)
->then([ResolveGenerator::class, 'toResponse']);
}
);

return $server;
Expand Down
6 changes: 3 additions & 3 deletions src/WatchServerCommandFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -31,11 +31,11 @@ public function __invoke(ContainerInterface $container): WatchServerCommand
$definition->setArguments([$path]);

$staticFolder = $definition->getOption('static-folder');
$staticFolder->setDefault($config['static_folder']);
$staticFolder->setDefault((string)$config['static_folder']);
$concurrentRequests = $definition->getOption('concurrent-requests');
$concurrentRequests->setDefault($config['max_concurrency']);
$concurrentRequests->setDefault((string)$config['max_concurrency']);
$bufferSize = $definition->getOption('request-body-buffer');
$bufferSize->setDefault($config['buffer_size']);
$bufferSize->setDefault((string)$config['buffer_size']);

return $command;
}
Expand Down