mammatus / http-server
🐙 Multi vhost HTTP Server
Installs: 7 771
Dependents: 0
Suggesters: 0
Security: 0
Stars: 2
Watchers: 2
Forks: 0
Open Issues: 9
Type:composer-plugin
Requires
- php: ^8.1
- composer-plugin-api: ^2
- ancarda/psr7-string-stream: ^1.3
- chimera/foundation: ^0.4.0
- chimera/mapping: ^0.4.0
- chimera/routing: ^0.4.0
- chimera/routing-mezzio: ^0.4.0
- composer/composer: ^2.4
- doctrine/annotations: ^1.13
- for/http-middleware-psr15-adapter: ^2
- illuminate/collections: ^9.25.1
- laminas/laminas-diactoros: ^2.14
- laminas/laminas-stratigility: ^3.9
- lcobucci/content-negotiation-middleware: ^3.1
- league/tactician: ^1.1
- league/tactician-container: ^3 || ^2
- mammatus/app: dev-master
- mammatus/healthz-vhost: dev-master
- mammatus/http-server-annotations: dev-master
- mammatus/http-server-contracts: dev-master
- mammatus/http-server-webroot: dev-master
- mammatus/http-server-websockets: dev-master
- mammatus/life-cycle-events: ^1
- mammatus/metrics-prometheus-vhost: dev-master
- mezzio/mezzio-fastroute: ^3.5
- mezzio/mezzio-helpers: ^5.6
- mezzio/mezzio-router: ^3.6
- middlewares/access-log: ^2
- middlewares/cache: ^2
- middlewares/client-ip: ^2
- middlewares/filesystem: ^2
- middlewares/https: ^2
- middlewares/negotiation: ^2.1
- middlewares/response-time: ^2
- nikic/fast-route: ^1.2
- nikic/php-parser: ^4.10
- psr/container: ^3 || ^2 || ^1
- psr/http-factory: ^3 || ^2 || ^1
- psr/http-message: ^3 || ^2 || ^1
- psr/http-server-middleware: ^3 || ^2 || ^1
- psr/log: ^3 || ^2 || ^1
- react-inspector/http-middleware: ^2.0
- react/async: ^4
- react/cache: ^1.1
- react/event-loop: ^1.3
- react/http: ^1.7
- react/promise: ^2.9
- react/socket: ^1.12
- roave/better-reflection: ^6 || ^5
- thecodingmachine/safe: ^2 || ^1
- thruway/client: ^0.5.8
- thruway/middleware: ^0.1.1
- voryx/thruway: 0.6.1 as 0.5.13
- wyrihaximus/broadcast: ^2.0.0
- wyrihaximus/broadcast-contracts: ^1.3
- wyrihaximus/doctrine-annotation-autoloader: ^1
- wyrihaximus/get-in-packages-composer.jason: ^2
- wyrihaximus/html-compress: ^4.2
- wyrihaximus/iterator-or-array-to-array: ^1.1
- wyrihaximus/json-psr7: ^1.3
- wyrihaximus/list-classes-in-directory: ^1.3
- wyrihaximus/metrics: ^2 || ^1.0
- wyrihaximus/metrics-tactician: ^1.0
- wyrihaximus/psr-3-callable-throwable-logger: ^2.2
- wyrihaximus/psr-3-context-logger: ^2
- wyrihaximus/react-http-middleware-compress-assets: ^2.0
- wyrihaximus/react-http-middleware-custom-request-body-parsers: ^2.0
- wyrihaximus/react-http-middleware-html-compress: ^2.0
- wyrihaximus/react-http-middleware-resume-response-body: ^3.0
- wyrihaximus/react-http-middleware-webroot-preload: ^2.0
- wyrihaximus/react-stream-json: ^1.2
- wyrihaximus/simple-twig: ^2
- wyrihaximus/string-get-in: ^1
Requires (Dev)
- mammatus/test-utilities: dev-master
- monolog/monolog: ^2
- dev-master
- dev-dependabot/composer/wyrihaximus/metrics-tactician-1.1.1
- dev-dependabot/composer/wyrihaximus/react-http-middleware-custom-request-body-parsers-2.2.1
- dev-dependabot/composer/wyrihaximus/react-http-middleware-webroot-preload-2.3.1
- dev-dependabot/composer/wyrihaximus/react-http-middleware-compress-assets-2.1.1
- dev-dependabot/composer/react-inspector/http-middleware-2.2.1
- dev-dependabot/npm_and_yarn/etc/vhosts/healthz/minimatch-3.1.2
- dev-dependabot/npm_and_yarn/etc/vhosts/healthz/json5-1.0.2
- dev-dependabot/npm_and_yarn/etc/vhosts/healthz/decode-uri-component-0.2.2
- dev-dependabot/npm_and_yarn/etc/vhosts/healthz/loader-utils-1.4.2
- dev-WyriHaximus-patch-1
- dev-use-new-overrides-provider
This package is auto-updated.
Last update: 2024-11-17 00:04:23 UTC
README
time docker run --rm -w `pwd` -v `pwd`:`pwd` -p 9666:9666 -it wyrihaximusnet/php:7.4-zts-alpine3.11 php ./vendor/bin/mammatus
HTTP Server command
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.