reactive-apps / command-http-server
HTTP Server command
Installs: 1 777
Dependents: 2
Suggesters: 0
Security: 0
Stars: 4
Watchers: 2
Forks: 0
Open Issues: 8
Requires
- php: ^7.3
- cakephp/collection: ^3.6
- doctrine/annotations: ^1.6
- lcobucci/jwt: ^3.3
- nikic/fast-route: ^1.2
- react/http: ^0.8.0
- reactive-apps/command: dev-master
- reactive-apps/life-cycle-events: dev-master
- roave/better-reflection: ^3.2
- thecodingmachine/safe: ^0.1.16
- thruway/middleware: ^0.0.2
- voryx/thruway: ^0.5.3
- wyrihaximus/broadcast: dev-master
- wyrihaximus/doctrine-annotation-autoloader: ^1.0
- wyrihaximus/get-in-packages-composer.jason: ^1.0
- wyrihaximus/json-psr7: ^1.0
- wyrihaximus/psr-3-callable-throwable-logger: ^2.0
- wyrihaximus/psr-3-context-logger: ^1.0
- wyrihaximus/react-child-process-closure: ^1.0
- wyrihaximus/react-child-process-pool: ^1.4
- wyrihaximus/react-http-middleware-resume-response-body: ^1.0
- wyrihaximus/react-http-middleware-rewrite: ^1.0
- wyrihaximus/react-http-middleware-runner: ^1.0
- wyrihaximus/react-http-middleware-session: ^3.0
- wyrihaximus/react-http-middleware-twig: ^1.0
- wyrihaximus/react-http-middleware-webroot-preload: ^1.0
- wyrihaximus/react-http-psr-15-middleware-group: ^1.2
- wyrihaximus/react-stream-json: ^1.2
- wyrihaximus/recoil-promise-coroutine-wrapper: ^1.0
- wyrihaximus/recoil-queue-caller-pool: ^1.2
- wyrihaximus/string-get-in: ^1.0
- wyrihaximus/to-child-process-or-not-to-child-process: ^1.0
- wyrihaximus/to-coroutine-or-not-to-coroutine: ^1.0
- wyrihaximus/to-thread-or-not-to-thread: dev-master
- zendframework/zend-diactoros: ^2.1
Requires (Dev)
- monolog/monolog: ^2.0
- twig/twig: ^2.8
- wyrihaximus/async-test-utilities: ^1.1
- wyrihaximus/cs-fixer-config: ^1.0
- wyrihaximus/pool-info: ^1.0
- wyrihaximus/react-parallel: dev-master
Suggests
- wyrihaximus/react-parallel: Run request handlers in threads (more performant than child processes)
This package is auto-updated.
Last update: 2024-11-29 05:32:51 UTC
README
Install
To install via Composer, use the command below, it will automatically detect the latest version and bind it with ^
.
composer require reactive-apps/command-http-server
Controllers
Controllers come in two different flavours static and instantiated controllers.
Static Controllers
Static controllers are recommended when your controller doesn't have any dependencies like this ping controller used for
updown.io
health checks. Note: /ping
isn't a updown standard but it's my personal
standard of doing health checks for my apps This controller only has a single method with a single route and no
dependencies:
<?php declare(strict_types=1); namespace App\Controller; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use ReactiveApps\Command\HttpServer\Annotations\Method; use ReactiveApps\Command\HttpServer\Annotations\Routes; use RingCentral\Psr7\Response; final class Ping { /** * @Method("GET") * @Routes("/ping") * * @param ServerRequestInterface $request * @return ResponseInterface */ public static function ping(ServerRequestInterface $request): ResponseInterface { return new Response( 200, ['Content-Type' => 'text/plain'], 'pong' ); } }
Instantiated Controllers
Instantiated Controllers on the other hand will be instantiated and kept around to handle more requests in the future as such they can have dependencies injected. The example below is a controller that has the event loop injected to wait for a random number of seconds before returning the response. It also uses coroutines to make the code more readable:
<?php declare(strict_types=1); namespace App\Controller; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use React\EventLoop\LoopInterface; use ReactiveApps\Command\HttpServer\Annotations\Method; use ReactiveApps\Command\HttpServer\Annotations\Routes; use ReactiveApps\Command\HttpServer\Annotations\Template; use ReactiveApps\Command\HttpServer\TemplateResponse; use WyriHaximus\Annotations\Coroutine; use function WyriHaximus\React\timedPromise; /** * @Coroutine()) */ final class Root { /** @var LoopInterface */ private $loop; /** @var int */ private $time; public function __construct(LoopInterface $loop) { $this->loop = $loop; $this->time = \time(); } /** * @Method("GET") * @Routes("/") * @Template("root") * * @param ServerRequestInterface $request * @return ResponseInterface */ public function root(ServerRequestInterface $request) { $start = \time(); yield timedPromise($this->loop, \random_int(1, 5)); return (new TemplateResponse( 200, ['Content-Type' => 'text/plain'] ))->withTemplateData([ 'uptime' => (\time() - $this->time), 'took' => (\time() - $start), ]); } }
Routing
Routing is done through annotations on the method handling the routes. Each method can handle multiple routes but it's recommended to only map routes that fit the the method.
For example the following annotation will map the current method to /
(note: all routes are required to be
prefixed with /
): @Routes("/")
A multi route annotation has a slightly different syntax, in the following both /old
and /new
will be handled by
the same method:
@Routes({ "/old", "/new" })
The underlying engine for routes is nikic/fast-route
which also makes complex
routes like this one possible:
@Route("/{map:(?:wow_cata_draenor|wow_cata_land|wow_cata_underwater|wow_legion_azeroth|wow_battle_for_azeroth|wow_cata_elemental_plane|wow_cata_twisting_nether|wow_comp_wotlk)}/{zoom:1|2|3|4|5|6|7|8|9|10}/{width:[0-9]{1,5}}/{height:[0-9]{1,5}}/{center:[a-zA-Z0-9\`\-\~\_\@\%]{1,35}}{blips:/blip\_center|/[a-zA-Z0-9\`\-\~\_\@\%\[\]]{3,}.+|}.{quality:png|hq.jpg|lq.jpg}")
The different route components like map
, and center
are available from the request object with:
$request->getAttribute('center');
Templates
A route can render a template upon completion it needs an annotation and return/resolve with a TemplateResponse
holding the data required for that template. For example:
/** * @Template("root") */ public function root(ServerRequestInterface $request) { return (new TemplateResponse( 200, ['Content-Type' => 'text/plain'] ))->withTemplateData([ 'beer' => 'Allmouth', // https://untappd.com/user/WyriHaximus/checkin/745226210 ]); }
Blocking operations in requests
While we aim for building a completely non-blocking application we can't escape the truth that there might always be parts of our application that would block the loop. For those situations there are two ways provided to deal with those situations:
- Child Process (slow, spawns full PHP processes to handle the request)
- Threads (fast, uses threads to do the work, requires ZTS version of PHP)
Child Processes
Works on most if not all systems but requires a full PHP processes per worker. Start up can be slow and communication
with the child process goes over a socket. Add the @ChildProcess
annotation to handle that specific action in a
child process.
Threads
Works only on ZTS PHP builds, but in return starts up almost instantly, communication is directly in memory thus never
leaving the application server. Add the @Thread
annotation to handle that specific action in a thread.
Annotations
@ChildProcess
- Runs controller actions inside a child process@Coroutine
- Runs controller actions inside a coroutine@Method
- Allowed HTTP methods (GET, POST, PATCH, etc)@Routes
- Routes to use the given method for@Template
- Template to use when a TemplateResponse is used@Thread
- Runs controller actions inside a thread (preferred over use child processes)
Options
http-server.address
- The IP + Port to listen on, for example:0.0.0.0:8080
http-server.hsts
- Whether or not to set HSTS headershttp-server.public
- Public webroot to serve, note only put files in here everyone is allowed to seehttp-server.public.preload.cache
- Custom cache to store the preloaded webroot files, stored in memory by defaulthttp-server.middleware.prefix
- An array with react/http middleware added before the accesslog and webroot serving middlewarehttp-server.middleware.suffix
- An array with react/http middleware added after the accesslog and webroot serving middleware and before the route middleware and request handlerhttp-server.pool.ttl
- TTL for a child process to wait for it's next taskhttp-server.pool.min
- Minimum number of child processeshttp-server.pool.max
- maximum number of child processeshttp-server.rewrites
- Rewrites request path internally from one path to the other, invisible for visitors
License
The MIT License (MIT)
Copyright (c) 2019 Cees-Jan Kiewiet
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.