Ecosyste.ms: Awesome

An open API service indexing awesome lists of open source software.

Awesome Lists | Featured Topics | Projects

https://github.com/scil/LaravelFly

To be an absolutely safe solution to speed up Laravel with Swoole. Preloading + Coroutine and Tinker Online.
https://github.com/scil/LaravelFly

laravel speed swoole tinker

Last synced: about 1 month ago
JSON representation

To be an absolutely safe solution to speed up Laravel with Swoole. Preloading + Coroutine and Tinker Online.

Awesome Lists containing this project

README

        

Please refer to [Swoole handles multiple requests simultaneously per-worker](https://github.com/nextcloud/server/issues/36290#issuecomment-1555965453) and [Hola FrankenPHP! Laravel Octane Servers Comparison](https://medium.com/beyn-technology/hola-frankenphp-laravel-octane-servers-comparison-pushing-the-boundaries-of-performance-d3e7ad8e652c)

====

Would you like php 7.4 Preloading? Would you like php coroutine? Today you can use them with Laravel because of Swoole. With LaravalFly, Laravel will begin like Django 3.0 to be fully async-capable.

LaravelFly is a safe solution to speeds up new or old Laravel 5.5+ projects, with preloading and coroutine, while without data pollution or memory leak. And it makes Tinker available online (use tinker while Laravel is responding requests from browsers).

Thanks to [Laravel](http://laravel.com/), [Swoole](https://github.com/swoole/swoole-src) and [PsySh](https://github.com/bobthecow/psysh).

**Notice**: Great News! [Laravel is supporting Swoole offcially with laravel/octane!](https://github.com/laravel/octane)

## A simple ab test

`ab -k -n 1000 -c 10 http://zc.test` (21 sql statements were executed in single request)

. | fpm | Fly
------------ | ------------ | -------------
Time taken ≈ | 43.5 s | 12.3 s
Requests per second | 23 | 81.5
50% | 303 ms | 117 ms
80% | 360 ms | 153 ms
99% | 1341 ms | 239 ms

Test Env

* env:
- ubuntu 16.04 on VirtualBox ( 1 CPU: i7-7700HQ 2.80GHz ; Memory: 2G )
- php7.2 + opcache + 5 workers for both fpm and laravelfly ( phpfpm : pm=static pm.max_children=5)
- connection pool and coroutine mysql
* Test date : 2018/10

## Version Compatibility

- Laravel 5.5 ~ 6.0
- Swoole >4.2.13

## Quick Start

1.`pecl install swoole`
Make sure `extension=swoole.so` in config file for php cli, not for fpm.
Suggest: `pecl install inotify`

2.`composer require "scil/laravel-fly":"dev-master"`

3.`php vendor/scil/laravel-fly/bin/fly start`
If you enable `eval(tinker())` and see an error about mkdir, you can start LaravelFly with sudo.

Now, your project is flying and listening to port 9501. Enjoy yourself.

## Docker-compose

```
composer require "scil/laravel-fly":"dev-master"

php artisan vendor:publish --tag=fly-server

# 127.0.0.1:8080
# you can edit this docker-compos file and use your own nginx conf
docker-compose -f vendor/scil/laravel-fly-local/docker/docker-compose.yml up -d
```

## Doc

[Configuration](https://github.com/scil/LaravelFly/wiki/Configuration)

[Commands: Start, Reload & Debug](https://github.com/scil/LaravelFly/wiki/Commands)

[Coding Guideline](https://github.com/scil/LaravelFly/wiki/Coding-Requirement)

[Events about LaravelFly](doc/events.md)

[Using tinker when Laravel Working](doc/tinker.md)

[For Dev](doc/dev.md)

## Recommended Packages

- [swlib/saber](https://github.com/swlib/saber/blob/master/README-EN.md) Coroutine HTTP client, based on `Swoole\Coroutine\Http\Client`.
Browser-like cookie managment, multiple requests concurrent, request/response interceptors and so on.
To ensure safety, set `const LARAVELFLY_COROUTINE = true;` in fly.conf.php.

## Features and Behaviors

- Same codes can run on PHP-FPM or LaravelFly. LaravelFly can be installed on your existing projects without affecting nginx/apache server, that's to say, you can run LaravelFly server and nginx/apache server simultaneously to run the same laravel project. The nginx conf [swoole_fallback_to_phpfpm.conf](config/swoole_fallback_to_phpfpm.conf) allow you use LaravelFlyServer as the primary server, and the phpfpm as a backup server which will be passed requests when the LaravelFlyServer is unavailable. Another nginx conf [use_swoole_or_fpm_depending_on_clients](config/use_swoole_or_fpm_depending_on_clients.conf) allows us use query string `?useserver=name = implode('; ',$a);
// $user->save();

});

$a[] = 'outer1';

// go() can use laravel service with closure
$log = app('log');
go(function () use (&$a, $log) {
$a[] = 'coroutine2';
\co::sleep(1.2);
$a[] = 'coroutine2.end';
});

$a[] = 'outer2';

\co::sleep(1);

$a[] = 'outer3';

return implode(';', $a);

});
```

## Similar projects that mix swoole and laravel

The main distinguishing feature of LaravalFly is refactoring Laravel, like what Django 3.0 does.

### 1. [laravel-swoole](https://github.com/swooletw/laravel-swoole)

It is alse a safe sollution. It has supported Lumen and websocket. Its doc is great and also useful for LaravelFly.

The main difference is that in laravel-swoole user's code will be processed by a new `app` cloned from SwooleTW\Http\Server\Application::$application and laravel-swoole updates related container bindings to the new app. However in LaravelFly, the sandbox is not a new app, but an item in the $corDict of the unique application container.
In LaravelFly, most other objects such as `app`, `event`.... always keep one object in a worker process, `clone` is not used at all by default. LaravelFly makes most of laravel objects keep safe on their own. It's about high cohesion & low coupling and the granularity is at the level of app container or services/objects. For users of laravel-swoole, it's a big challenge to handle the relations of multiple packages and objects which to be booted before any requests. Read [Stale Reference](https://github.com/scil/LaravelFly/wiki/clone-and-Stale-Reference).

. | technique | work to maintaining relations of cloned objects to avoid Stale Reference
------------ |------------ | ------------
laravel-swoole | clone app contaniner and objects to make them safe | more work (as app,event...are cloned)
LaravelFly Mode Map | refactor most official objects to make them safe on their own | few work ( nothing is cloned by default)

In LaravelFly, another benefit of non-cloned objects is allowing some improvements, such as event listeners cache, route middlewares cache.

### 2. [laravel-s](https://github.com/hhxsv5/laravel-s)

Many great features!

About data pollution? Same technique and problems as laravel-swoole. And neither support coroutine jumping (from one request to another request).

## Todo About Improvement

- [x] Pre-include. Server configs 'pre_include' and 'pre_files'.
- [x] Server config 'early_laravel'
- [x] Cache for LaravelFly app config. laravelfly_ps_map.php or laravelfly_ps_simple.php located bootstrap/cache
- [x] Cache for Log. Server options 'log_cache'.
- [x] Watching maintenance mode using swoole_event_add. No need to check file storage/framework/down in every request.
- [x] Cache for kernel middlewares objects. Kernel::getParsedKernelMiddlewares, only when LARAVELFLY_SERVICES['kernel'] is true.
- [x] Cache for route middlewares. $cacheByRoute in Router::gatherRouteMiddleware, only useful when all route middleaes are reg on worker.
- [x] Cache for route middlewares objects. config('laravelfly.singleton_route_middlewares') and $cacheForObj in Router::gatherRouteMiddleware, avoid creating instances repeatly.
- [x] Cache for terminateMiddleware objects.
- [x] Cache for event listeners. $listenersStalbe in LaravelFly\Map\IlluminateBase\Dispatcher
- [x] Cache for view compiled path. LARAVELFLY_SERVICES['view.finder'] or App config 'view_compile_1'
- [x] Mysql coroutine. Old code dropped, laravel-s used.
- [x] db connection pool and redis connection pool. In `fly()` or `fly2()`, connections to be used would be fetched from pool, not inherit the same connections from request coroutine. code: `$this->connections[$childId] = [];` in ConnectionsTrait.php
- [x] swoole redis driver
- [ ] swoole redis driver: how to use `errMsg` `errCode`
- [ ] use [hyperf/database](https://github.com/hyperf/database) to replace official version?
- [ ] use [swlib/swpdo](https://github.com/swlib/swpdo) to replace SwoolePDO?
- [ ] Cache for HasRelationships. disable and experimental, not ready
- [x] Cache for RouteDependencyResolverTrait
- [ ] Converting between swoole request/response and Laravel Request/Response
- [ ] safe: auth, remove some props?
- [ ] use: https://github.com/louislivi/smproxy
- [ ] use: https://github.com/kcloze/swoole-jobs or https://github.com/osgochina/Donkey

## Other Todo

- [x] add events
- [x] watch code changes and hot reload
- [x] supply server info. default url is: /laravel-fly/info
- [x] function fly()
- [x] job executed in task process. Related: vendor\scil\laravel-fly-files-local\src\Foundation\Bus\
- [x] event listeners executed in task process. Related: LaravelFly\Map\IlluminateBase\Dispatcher and vendor\scil\laravel-fly-files\src\Foundation\Support\Providers\EventServiceProvider.php
- [ ] use $this->output instead of echo() in Common.php
- [ ] bootstrap all service providers in task process
- [ ] try ocramius/generated-hydrator for laravel-fly/info when its version 3 is ready (it will require nikic/php-parser v4 which is needed by others) // or Zend\Hydrator\Reflection?
- [ ] add tests about auth SessionGuard: Illuminate/Auth/SessionGuard.php with uses Request::createFromGlobals
- [ ] add tests about uploaded file, related symfony/http-foundation files: File/UploadedFile.php and FileBag.php(fixPhpFilesArray)
- [ ] websocket
- [ ] send file
- [ ] travis, static analyze like phan, phpstan or https://github.com/exakat/php-static-analysis-tools
- [ ] cache fly