Skip to content

Commit

Permalink
Use socket server factory package
Browse files Browse the repository at this point in the history
  • Loading branch information
akadlec committed Oct 6, 2021
1 parent cd78d01 commit 2523595
Show file tree
Hide file tree
Showing 7 changed files with 47 additions and 108 deletions.
23 changes: 12 additions & 11 deletions .docs/en/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ After that, you have to register extension in *config.neon*.

```neon
extensions:
fbWebServer: FastyBird\WebServer\DI\WebServerExtension
fbWebServer: FastyBird\WebServer\DI\WebServerExtension(%consoleMode%)
```

This extension is dependent on other extensions, and they have to be registered too
Expand All @@ -24,6 +24,7 @@ extensions:
...
contributteConsole: Contributte\Console\DI\ConsoleExtension(%consoleMode%)
contributteEvents: Contributte\EventDispatcher\DI\EventDispatcherExtension
fbSocketServerFactory: FastyBird\SocketServerFactory\DI\SocketServerFactoryExtension
```

> For information how to configure these extensions please visit their doc pages
Expand All @@ -34,25 +35,28 @@ This extension has some configuration options:

```neon
fbWebServer:
static:
webroot: /path/to/public/folder
enabled: false
fbSocketServerFactory:
server:
address: 127.0.0.1
port: 8000
certificate: /path/to/your/certificate.pa
static:
webroot: /path/to/public/folder
enabled: false
```

Where:

- `static -> webroot` is path to public static files and this files could be served by this webserver
- `static -> enabled` enable or disable serving static files support

And settings for socket server extension:

- `server -> address` is address where is server listening for incoming requests
- `server -> port` is address port where is server listening for incoming requests
- `server -> certificate` is path to your private certificate to enable SSL communication


- `static -> webroot` is path to public static files and this files could be served by this webserver
- `static -> enabled` enable or disable serving static files support

## Application routes

This extension has router collector services which will search for your custom routes providers and register routes to the server service.
Expand Down Expand Up @@ -239,9 +243,6 @@ And as a last step, you have to configure you Apache or Nginx server to load you

If you want to use [{JSON:API}](https://jsonapi.org/) for you api calls, you could use [fastybird/json-api](https://github.com/FastyBird/json-api) package. This package brings you schemas factory for your responses and document to entity hydrator

IF you are using [Doctrine2](https://www.doctrine-project.org), we suggest you to use [fastybird/database](https://github.com/FastyBird/database) package. This package is checking databse connection and in case connection is closed by server, it tries to restore it.
And also this package has middleware which help you solve pagination for you responses.

And last but not least, [fastybird/simple-auth](https://github.com/FastyBird/simple-auth). With this package you could create basic token based authentication and authorization.

***
Expand Down
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@
"php": ">=7.4.0|>=8.0.0",
"contributte/console": "^0.9",
"contributte/event-dispatcher": "^0.8",
"fastybird/socket-server-factory": "^0.1",
"ipub/slim-router": "^0.2",
"nette/bootstrap": "^3.1",
"nette/di": "^3.0",
Expand All @@ -61,7 +62,6 @@

"suggest": {
"fastybird/json-api": "Handle request with {JSON:API} schemas",
"fastybird/database": "For application with Doctrine2 it will help you watch DB connection",
"fastybird/simple-auth": "Handle basic user authentication & authorization"
},

Expand Down
36 changes: 11 additions & 25 deletions src/Commands/HttpServerCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@

namespace FastyBird\WebServer\Commands;

use FastyBird\SocketServerFactory;
use FastyBird\WebServer\Events;
use FastyBird\WebServer\Exceptions;
use FastyBird\WebServer\Middleware;
Expand Down Expand Up @@ -66,44 +67,41 @@ class HttpServerCommand extends Console\Command\Command
/** @var Log\LoggerInterface */
private Log\LoggerInterface $logger;

/** @var SocketServerFactory\SocketServerFactory */
private SocketServerFactory\SocketServerFactory $socketServerFactory;

/** @var EventLoop\LoopInterface */
private EventLoop\LoopInterface $eventLoop;

/**
* @param string $serverAddress
* @param int $serverPort
* @param string|null $serverCertificate
* @param Middleware\CorsMiddleware $corsMiddleware
* @param Middleware\StaticFilesMiddleware $staticFilesMiddleware
* @param Middleware\RouterMiddleware $routerMiddleware
* @param EventLoop\LoopInterface $eventLoop
* @param EventDispatcher\EventDispatcherInterface $dispatcher
* @param SocketServerFactory\SocketServerFactory $socketServerFactory
* @param EventLoop\LoopInterface $eventLoop
* @param Log\LoggerInterface|null $logger
* @param string|null $name
*/
public function __construct(
string $serverAddress,
int $serverPort,
Middleware\CorsMiddleware $corsMiddleware,
Middleware\StaticFilesMiddleware $staticFilesMiddleware,
Middleware\RouterMiddleware $routerMiddleware,
EventLoop\LoopInterface $eventLoop,
EventDispatcher\EventDispatcherInterface $dispatcher,
SocketServerFactory\SocketServerFactory $socketServerFactory,
EventLoop\LoopInterface $eventLoop,
?Log\LoggerInterface $logger = null,
?string $serverCertificate = null,
?string $name = null
) {
parent::__construct($name);

$this->serverAddress = $serverAddress;
$this->serverPort = $serverPort;
$this->serverCertificate = $serverCertificate;

$this->corsMiddleware = $corsMiddleware;
$this->staticFilesMiddleware = $staticFilesMiddleware;
$this->routerMiddleware = $routerMiddleware;

$this->dispatcher = $dispatcher;
$this->socketServerFactory = $socketServerFactory;

$this->logger = $logger ?? new Log\NullLogger();

$this->eventLoop = $eventLoop;
Expand All @@ -130,19 +128,7 @@ protected function execute(
): int {
$this->logger->info('[FB:WEB_SERVER] Starting HTTP server');

$socketServer = new Socket\SocketServer($this->serverAddress . ':' . $this->serverPort, [], $this->eventLoop);

if (
$this->serverCertificate !== null
&& is_file($this->serverCertificate)
&& file_exists($this->serverCertificate)
) {
$socketServer = new Socket\SecureServer($socketServer, $this->eventLoop, [
'local_cert' => $this->serverCertificate,
]);
}

$this->dispatcher->dispatch(new Events\InitializeEvent($socketServer));
$socketServer = $this->socketServerFactory->create();

/**
* HTTP server
Expand Down
17 changes: 1 addition & 16 deletions src/DI/WebServerExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@
use Nette;
use Nette\DI;
use Nette\Schema;
use React\EventLoop;
use stdClass;

/**
Expand Down Expand Up @@ -83,11 +82,6 @@ public static function register(
public function getConfigSchema(): Schema\Schema
{
return Schema\Expect::structure([
'server' => Schema\Expect::structure([
'address' => Schema\Expect::string('127.0.0.1'),
'port' => Schema\Expect::int(8000),
'certificate' => Schema\Expect::string(null)->nullable(),
]),
'static' => Schema\Expect::structure([
'webroot' => Schema\Expect::string(null)->nullable(),
'enabled' => Schema\Expect::bool(false),
Expand Down Expand Up @@ -131,17 +125,8 @@ public function loadConfiguration(): void
$builder->addDefinition($this->prefix('routing.router'), new DI\Definitions\ServiceDefinition())
->setType(Router\Router::class);

$builder->addDefinition('react.eventLoop', new DI\Definitions\ServiceDefinition())
->setType(EventLoop\LoopInterface::class)
->setFactory('React\EventLoop\Factory::create');

$builder->addDefinition($this->prefix('command.server'), new DI\Definitions\ServiceDefinition())
->setType(Commands\HttpServerCommand::class)
->setArguments([
'serverAddress' => $configuration->server->address,
'serverPort' => $configuration->server->port,
'serverCertificate' => $configuration->server->certificate,
]);
->setType(Commands\HttpServerCommand::class);

// Webserver middlewares
$builder->addDefinition($this->prefix('middlewares.cors'), new DI\Definitions\ServiceDefinition())
Expand Down
49 changes: 0 additions & 49 deletions src/Events/InitializeEvent.php

This file was deleted.

23 changes: 19 additions & 4 deletions tests/cases/Unit/Commands/HttpServerCommandTest.phpt
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace Tests\Cases;

use FastyBird\SocketServerFactory;
use FastyBird\WebServer\Commands;
use FastyBird\WebServer\Middleware;
use Mockery;
Expand All @@ -10,6 +11,7 @@ use Psr\EventDispatcher;
use Psr\Log;
use React\EventLoop;
use React\Promise;
use React\Socket;
use Symfony\Component\Console\Application;
use Symfony\Component\Console\Tester\CommandTester;
use Tester\Assert;
Expand Down Expand Up @@ -49,7 +51,21 @@ final class HttpServerCommandTest extends BaseMockeryTestCase
$eventDispatcher = Mockery::mock(EventDispatcher\EventDispatcherInterface::class);
$eventDispatcher
->shouldReceive('dispatch')
->times(2);
->times(1);

$socketServer = Mockery::mock(Socket\ServerInterface::class);
$socketServer
->shouldReceive('getAddress')
->andReturn('http://127.0.0.1:8001')
->times(2)
->getMock()
->shouldReceive('on');

$socketServerFactory = Mockery::mock(SocketServerFactory\SocketServerFactory::class);
$socketServerFactory
->shouldReceive('create')
->andReturn($socketServer)
->times(1);

$corsFilesMiddleware = Mockery::mock(Middleware\CorsMiddleware::class);

Expand All @@ -59,13 +75,12 @@ final class HttpServerCommandTest extends BaseMockeryTestCase

$application = new Application();
$application->add(new Commands\HttpServerCommand(
'127.0.0.1',
8001,
$corsFilesMiddleware,
$staticFilesMiddleware,
$routerMiddleware,
$eventLoop,
$eventDispatcher,
$socketServerFactory,
$eventLoop,
$logger
));

Expand Down
5 changes: 3 additions & 2 deletions tests/common.neon
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,9 @@ php:
date.timezone: Europe/Prague

extensions:
contributteConsole : Contributte\Console\DI\ConsoleExtension(%consoleMode%)
contributteEvents : Contributte\EventDispatcher\DI\EventDispatcherExtension
contributteConsole : Contributte\Console\DI\ConsoleExtension(%consoleMode%)
contributteEvents : Contributte\EventDispatcher\DI\EventDispatcherExtension
fbSocketServerFactory : FastyBird\SocketServerFactory\DI\SocketServerFactoryExtension

contributteConsole:
name: FastyBird:WebServer!
Expand Down

0 comments on commit 2523595

Please sign in to comment.