Giter Club home page Giter Club logo

mezzio-swoole's Introduction

mezzio

Build Status Type Coverage

Develop PSR-7 middleware applications in minutes!

mezzio builds on laminas-stratigility to provide a minimalist PSR-7 middleware framework for PHP, with the following features:

Installation

We provide two ways to install Mezzio, both using Composer: via our skeleton project and installer, or manually.

Using the skeleton + installer

The simplest way to install and get started is using the skeleton project, which includes installer scripts for choosing a router, dependency injection container, and optionally a template renderer and/or error handler. The skeleton also provides configuration for officially supported dependencies.

To use the skeleton, use Composer's create-project command:

composer create-project mezzio/mezzio-skeleton <project dir>

This will prompt you through choosing your dependencies, and then create and install the project in the <project dir> (omitting the <project dir> will create and install in a mezzio-skeleton/ directory).

Manual Composer installation

You can install Mezzio standalone using Composer:

composer require mezzio/mezzio

However, at this point, Mezzio is not usable, as you need to supply minimally:

  • a router.
  • a dependency injection container.

We currently support and provide the following routing integrations:

We recommend using a dependency injection container, and typehint against PSR-11 Container. We can recommend the following implementations:

  • laminas-servicemanager: composer require laminas/laminas-servicemanager
  • Pimple (see docs for more details): composer require laminas/laminas-pimple-config
  • Aura.Di (see docs for more details): composer require laminas/laminas-auradi-config

Additionally, you may optionally want to install a template renderer implementation, and/or an error handling integration. These are covered in the documentation.

Documentation

Documentation is in the doc tree, and can be compiled using mkdocs:

mkdocs build

Additionally, public-facing, browseable documentation is available at https://docs.mezzio.dev/mezzio/

mezzio-swoole's People

Contributors

acelaya avatar achevillard avatar babarinde avatar basz avatar byan avatar codeliner avatar codercms avatar doubaokun avatar eranoitulover avatar ezimuel avatar fezfez avatar froschdesign avatar ghostwriter avatar gsteel avatar huangzhhui avatar ishanvyas22 avatar laminas-bot avatar linuxd3v avatar massiathg avatar michalbundyra avatar moln avatar mrvralex avatar ocramius avatar pauci avatar renovate[bot] avatar samsonasik avatar taylorsasser avatar thomasvargiu avatar weierophinney avatar xerkus avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

mezzio-swoole's Issues

ext-openswoole

When mezzio-swoole will be integrated with package ext-openswoole rather than ext-swoole?

Support swoole onWorkerExit

Feature Request

Q A
New Feature yes
RFC not sure
BC Break no

Summary

At the momen mezzio/swoole supports some swoole events - however not all.
Specifically workerstop is supported, but not workerexit for example.

Per docs - workerstop is not triggering for task processes: https://github.com/deminy/swoole-by-examples/blob/master/examples/servers/server-events.php.

Event "onWorkerStop" happens in worker processes only. It won't happen in task worker processes.
Event "onWorkerExit" happens only when option \Swoole\Constant::OPTION_RELOAD_ASYNC is turned on.

this could be problematic if one needs to do some work on task worker exit - like shutdown connection pool for example.

Could probably be easily addressed in Mezzio\Swoole\SwooleRequestHandlerRunner:

    public function run(): void
    {
        if ($this->httpServer->mode === SWOOLE_PROCESS) {
            $this->httpServer->on('start', [$this, 'onStart']);
            $this->httpServer->on('shutdown', [$this, 'onShutdown']);
        }

        $this->httpServer->on('managerstart', [$this, 'onManagerStart']);
        $this->httpServer->on('managerstop', [$this, 'onManagerStop']);
        $this->httpServer->on('workerstart', [$this, 'onWorkerStart']);
        $this->httpServer->on('workerstop', [$this, 'onWorkerStop']);

       //lets add this!
        $this->httpServer->on('workerexit', [$this, 'onWorkerExit']);

        $this->httpServer->on('workererror', [$this, 'onWorkerError']);
        $this->httpServer->on('request', [$this, 'onRequest']);
        $this->httpServer->on('beforereload', [$this, 'onBeforeReload']);
        $this->httpServer->on('afterreload', [$this, 'onAfterReload']);
        $this->httpServer->on('task', [$this, 'onTask']);
        $this->httpServer->on('finish', [$this, 'onTaskFinish']);

        $this->httpServer->start();
    }

Dependency Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

Repository problems

These problems occurred while renovating this repository. View logs.

  • WARN: Use matchDepNames instead of matchPackageNames

Warning

Renovate failed to look up the following dependencies: Failed to look up packagist package psr/http-message-implementation.

Files affected: composer.json


Open

These updates have all been created already. Click a checkbox below to force a retry/rebase of any.

Detected dependencies

composer
composer.json
  • php ~8.1.0 || ~8.2.0 || ~8.3.0
  • dflydev/fig-cookies ^2.0.1 || ^3.0
  • laminas/laminas-cli ^1.8
  • laminas/laminas-diactoros ^2.25.2 || ^3.0
  • laminas/laminas-httphandlerrunner ^2.5
  • mezzio/mezzio ^3.15
  • psr/container ^1.1.2 || ^2.0.2
  • psr/event-dispatcher ^1.0
  • psr/http-message ^1.1 || ^2.0
  • psr/http-message-implementation ^1.0 || ^2.0
  • psr/http-server-handler ^1.0.2
  • psr/log ^1.0 || ^2.0 || ^3.0
  • symfony/console ^5.0 || ^6.0.19
  • webmozart/assert ^1.11
  • filp/whoops ^2.15.2
  • laminas/laminas-coding-standard ~2.5.0
  • laminas/laminas-servicemanager ^3.20
  • phpunit/phpunit ^10.5
  • psalm/plugin-phpunit ^0.18.4
  • swoole/ide-helper ^5.0.3
  • vimeo/psalm ^5.19
github-actions
.github/workflows/continuous-integration.yml
.github/workflows/docs-build.yml
.github/workflows/release-on-milestone-closed.yml

  • Check this box to trigger a request for Renovate to run again on this repository

Unused configuration property "enable" and misleading documentation about static resources

Not really a bug, but I noticed that the ConfigProvider has the key static-files which inside of it has the key enable - but that one is not used anywhere.

'static-files' => [
'enable' => true,
],

I checked the history of this package and noticed that at some point there was such a parameter, but it was removed as part of the "feat: event-driven handler runner" commit, check the references:

As a matter of fact, I think the lines from the documentation for disabling static resources are not relevant at all:

But the cookbook seems to be up to date with the correct information, though:

4.7.0 is not compatible with psr/http-messages:^2.0

Bug Report

Q A
Version(s) 4.7.0

Summary

Upgrading to 4.7.0 with psr/http-message:^2.0 gives compatibility errors in Mezzio\Swoole\SwooleStream.

Fatal error: Declaration of Mezzio\Swoole\SwooleStream::close() must be compatible with Psr\Http\Message\StreamInterface::close(): void in /app/vendor/mezzio/mezzio-swoole/src/SwooleStream.php on line 242

Current behavior

How to reproduce

Expected behavior

Update properties to use typehints

Feature Request

Q A
New Feature yes
RFC no
BC Break yes

Summary

For version 3.0, since it targets PHP 7.4+, we should update all properties to use typehints.

Add support for laminas-httphandlerrunner v2.1

Feature Request

Q A
New Feature yes
RFC no
BC Break unsure

Summary

laminas/laminas-httphandlerrunner v2 was released earlier this year. The base mezzio/mezzio package can already utiliize it, and it is the version installed by default with a new Mezzio installation. This package should provide compatibility with it.

However, the new version makes a few changes that may make this difficult:

  • It adds a RequestHandlerRunnerInterface.
  • It marks the base RequestHandlerRunner implementation as final.

The problems are thus:

  • In v1, there was no interface, so applications would pull the Laminas\HttpHandlerRunner\RequestHandlerRunner service from the container and use that. This package essentially overwrote that definition in order to provide an implementation.
  • Also, because in v1 there was no interface, inheritance was the only way to provide a compatible implementation. Since v2 marks the default implementation as final, we cannot inherit in a version that supports v2.

I propose a minor + major release strategy:

  • In the minor release, we provide multiple implementations:
    • A trait will define the full internals of each.
    • One implementation will target laminas-httphandlerrunner v1, extending the v1 version and using the trait; it will have the trait methods take precedence over inherited methods.
    • Another implementation will target laminas-httphandlerrunner v2, implementing the v2 interface and using the trait.
    • An autoloader will determine which one to use, and alias Mezzio\Swoole\SwooleRequestHandlerRunner to the implementation.
    • The ConfigProvider aliases the interface to the implementation.
  • In the major release, one implementation:
    • The v2 implementation becomes the only implementation.

One other idea I've considered: vary what the ConfigProvider maps based on the laminas-httphandlerrunner version. Since we know the RequestHandlerRunnerInterface only exists in v2, we could simply define an additional v2-compatible implementation, and have the ConfigProvider map to its factory when detected, instead of the existing implementation. The main downside to this is if anybody was previously extending our implementation (which shouldn't be necessary anymore, due to the changes made to have it trigger events). We would still likely need a trait with the common functionality (required due to inheritance in v1), but it wouldn't require usage of class_alias().

WhoopsPrettyPageHandlerDelegator leads to undefined index error

Bug Report

Q A
Version(s) 3.1

Summary

vendor/mezzio/mezzio-swoole/src/ConfigProvider.php has delegator defined as

Mezzio\WhoopsPageHandler' => [
                    WhoopsPrettyPageHandlerDelegator::class,
],

Current behavior

This leads to
Notice: Undefined index: Mezzio\WhoopsPageHandler in vendor/elie29/zend-phpdi-config/src/Config.php on line 137

How to reproduce

Expected behaviour

Whoops should not be tied to the application

SameSite=None in SwooleEmitter.php

Hi,
emitCookies() in SwooleEmitter.php is missing the SameSite attribute, $cookie->getSameSite(). Chrome 80 which will be released on the 4th of february won't send cookies to a thirdparty without SameSite=None anymore. Also $cookie->getSameSite() returns a string like "SameSite= $value" which is also a problem. It should only return the value.

Add BeforeServerStartEvent

Feature Request

Q A
New Feature yes
RFC not sure
BC Break no

Summary

With swoole certain operations could only happen before the server start. (one example is - one can only add swoole processes to swoole server before server starts.)
For this reason I think it would be worthwhile to add BeforeServerStartEvent.

Could probably be easily addressed in Mezzio\Swoole\SwooleRequestHandlerRunner:

    public function run(): void
    {
        if ($this->httpServer->mode === SWOOLE_PROCESS) {
            $this->httpServer->on('start', [$this, 'onStart']);
            $this->httpServer->on('shutdown', [$this, 'onShutdown']);
        }

        $this->httpServer->on('managerstart', [$this, 'onManagerStart']);
        $this->httpServer->on('managerstop', [$this, 'onManagerStop']);
        $this->httpServer->on('workerstart', [$this, 'onWorkerStart']);
        $this->httpServer->on('workerstop', [$this, 'onWorkerStop']);
        $this->httpServer->on('workererror', [$this, 'onWorkerError']);
        $this->httpServer->on('request', [$this, 'onRequest']);
        $this->httpServer->on('beforereload', [$this, 'onBeforeReload']);
        $this->httpServer->on('afterreload', [$this, 'onAfterReload']);
        $this->httpServer->on('task', [$this, 'onTask']);
        $this->httpServer->on('finish', [$this, 'onTaskFinish']);

       //lets add this!
        $this->dispatcher->dispatch(new Event\BeforeServerStartEvent($server));

        $this->httpServer->start();
    }

Add 'swoole/ide-helper' to "require-dev"

Feature Request

Q A
New Feature yes
RFC no
BC Break no

Summary

Please add 'swoole/ide-helper' component to Composer's 'dev' dependencies in order to help IDEs resolving Swoole engine entities (classes, functions, constants, etc...).

Reload command does not work

Bug Report

Q A
Version(s) 3.1.0

Summary

Executing Reload command from CLI throw errors.

Current behavior

Reloading server ...
PHP Notice:  Undefined index: stop in /usr/src/project/vendor/laminas/laminas-cli/src/AbstractContainerCommandLoader.php on line 64
Notice: Undefined index: stop in /usr/src/project/vendor/laminas/laminas-cli/src/AbstractContainerCommandLoader.php on line 64

Command "stop" is not defined.

Did you mean this?
      mezzio:swoole:stop

How to reproduce

./vendor/bin/laminas mezzio:swoole:start -d
./vendor/bin/laminas mezzio:swoole:reload

Expected behavior

Callling Reload command from CLI should reload Swoole server.

Fix

I think Symfony Console (method find() of Application class) can not find command when using short name (stop vs. mezzio:swoole:stop)?

This line from ReloadCommand
https://github.com/mezzio/mezzio-swoole/blob/3.1.0/src/Command/ReloadCommand.php#L78
should be replaced with:

$stop   = $application->find('mezzio:swoole:stop');

and this line:
https://github.com/mezzio/mezzio-swoole/blob/3.1.0/src/Command/ReloadCommand.php#L95
should be replaced with:

$stop   = $application->find('mezzio:swoole:start');

Update to dflydev/fig-cookies 3.0

Feature Request

Q A
New Feature no
RFC no
BC Break no

Summary

A new major version of dflydev/fig-cookies has been released, which adds support for PHP 8 (among other things).

Would you be open to update on this project? If so I can take care of it, I just need to know if you want to support both v2 and v3 at the same time.

Compatibility with openswoole 22

Feature Request

Q A
New Feature yes
RFC no
BC Break ideally, no

Summary

I have tried a project where I use this library with openswoole, and using openswoole 22.0.0, there seems to be calls to now removed functions (So far I have identified Fatal error: Uncaught Error: Call to undefined function swoole_set_process_name() in mezzio/mezzio-swoole/src/Event/ProcessNameTrait.php:33).

I believe this is the first version that trully deviates from swoole and might require considering how hard would be to continue supporting both.

The changelog does not mention the removal of this particular function, so I wonder how many other undocumented changes there are.

Replace ocramius/package-versions with composer/package-versions-deprecated

Feature Request

Q A
New Feature yes
RFC no
BC Break no

Summary

To support Composer 2 for all of the laminas packages, we have to replace ocramius/package-versions with composers fork composer/package-versions-deprecated.
The fork removed the PHP 7.4 limitation and thus provides Composer 2 support for PHP <7.4.

composer/package-versions-deprecated is replacing ocramius/package-versions and thus can be used as a 1:1 replacement.

Psalm integration

Feature Request

Q A
QA yes

Summary

As decided during the Technical-Steering-Committee Meeting on August 3rd, 2020, Laminas wants to implement vimeo/psalm in all packages.

Implementing psalm is quite easy.

Required

  • Create a psalm.xml in the project root
  • Copy and paste the contents from this psalm.xml.dist
  • Run $ composer require --dev vimeo/psalm
  • Run $ vendor/bin/psalm --set-baseline=psalm-baseline.xml
  • Add a composer script static-analysis with the command psalm --shepherd --stats
  • Add a new line to script: in .travis.yml: - if [[ $TEST_COVERAGE == 'true' ]]; then composer static-analysis ; fi
  • Remove phpstan from the project (phpstan.neon.dist, .travis.yml entry, composer.json require-dev and scripts)
Optional
  • Fix as many psalm errors as possible.

Migrate commands to laminas-cli

Feature Request

Q A
New Feature no
RFC yes (laminas-cli)
BC Break yes

Summary

Currently, the component provides its own binary for launching/controlling the Swoole web server, based on symfony console. This functionality should be migrated to laminas-cli.

"file not found in package" error notice when using composer

When updating mezzio-swoole package with composer (composer update) there is notice in console:

Skipped installation of bin bin/mezzio-swoole for package mezzio/mezzio-swoole: file not found in package

mezzio-swoole command was replaced by laminas command so "bin" section should be removed from composer.json:

"bin": [
        "bin/mezzio-swoole"
    ],

Swoole project exposed by whistleblower as potentially untrustworthy

Yesterday, one of the main Swoole devs blew the whistle on a gaping security flaw that was planned for Swoole v4.8.0. After his concerns were initially unaddressed, he forked the project (Openswoole). In response, the core Swoole team immediately removed the flaw and then booted the whistleblower from the project.

Given that Swoole is controlled by a team of devs based in the PRC, who are demonstrably operating either with at least bad judgement and poor accountability, or at most nefarious intent, I'm asking that you consider taking one of the following actions:

  • Add a warning label to the documentation for mezzio/mezzio-swoole, with a link to swoole/swoole-src#4434, or
  • Abandon and archive mezzio/mezzo-swoole.

Read the discussion above for yourself, and decide whether you are comfortable trusting upstream Swoole, or the Openswoole fork in the foreseeable future.

Server not loading when 'HotCodeReload' is enabled

Bug Report

Q A
PHP 7.4.5
Swoole 4.5.1

Summary

When starting, within a Docker container, a Mezzio based project according to the 'mezzio-swoole' documentation the Swoole server cannot start.

Current behavior

With a 'mezzio-swoole' configuration like the following:

<?php

declare(strict_types=1);

use Laminas\ServiceManager\Factory\InvokableFactory;
use Mezzio\Swoole\HotCodeReload\FileWatcher\InotifyFileWatcher;
use Psr\Log\LoggerInterface;
use \App\Swoole\Log\LoggerFactory;

return [
    'dependencies' => [
        'factories' => [
            LoggerInterface::class => LoggerFactory::class,
            //InotifyFileWatcher::class => InvokableFactory::class
        ],
        'delegators' => [
            \Swoole\Http\Server::class => [
                \App\Swoole\Task\TaskControllerDelegator::class
            ],
        ],
    ],
    'mezzio-swoole' => [
        'enable_coroutine' => true,
        'hot-code-reload' => [
            'enable' => true,
            'interval' => 500,
        ],
        'swoole-http-server' => [
            'host' => '*',
            'port' => 9501,
            'process-name' => 'mezzio',
            'mode' => SWOOLE_PROCESS,
            'options' => [
                'worker_num'      => 8,
                'task_worker_num' => 4,
                'task_enable_coroutine' => true
            ]
        ]
    ]
];

a ServiceManager related error is generated on server start:

In ServiceManager.php line 688:
                                                                               
  Unable to resolve service "Mezzio\Swoole\HotCodeReload\FileWatcher\InotifyF  
  ileWatcher" to a factory; are you certain you provided it during configurat  
  ion?  

How to reproduce

Follow 'mezzio-swoole' installation instruction, enable 'hot-code-reload'.

Reason for the issue

The module's 'ConfigProvider' specifies an 'alias' for related to the failing class (specified in above error) but the actual factory for that class is not defined in the dependencies manager.

Using the 'Laminas Service Manager' the solution is as easy as adding 'InotifyFileWatcher::class => InvokableFactory::class' in the 'factories' configuration.

Expected behavior

The Swoole server starts correctly as configured.

Add flag to "start" command to allow specifying number of task workers

Feature Request

Q A
New Feature yes
RFC no
BC Break no

Summary

Once #28 is merged, there is no longer any reason that the start command cannot expose an option for specifying the number of task workers to spawn, as there is now always a task listener present. I suggest --task-workers|-t as the option name.

ISO 8601 log format

  • I was not able to find an open or closed issue matching what I'm seeing.
  • This is not a question. (Questions should be asked on chat (Signup here) or our forums.)

Currently it's impossible to define an own date format in the logger.
The problem goes down to the usage of strftime which uses % for formating times as well as the other non common date formats.

Code to reproduce the issue

To log times in ISO 8601 format, according to the documentation this would look like the following.
But as % is used already to parse the log format the formatter just generates useless output.

 'zend-expressive-swoole' => [
        'swoole-http-server' => [
            'logger' => [
                'format' => '%{%FT%T%z}t',
            ],
    ]
]

Suggestion 1

My recommended suggestion would to to use the more common date format instead of strftime because, yea it's more common in PHP as it's the same as in DateTime and it does not use % to it's much more readable and much simpler to parse.

Suggestion 2

Another suggestion would be to "fix" the log formatter and combine replaceConstantDirectives and replaceVariableDirectives on parsing to make sure %{format}t gets used by the variable directives no matter how the format looks like.


Originally posted by @marc-mabe at zendframework/zend-expressive-swoole#62

PHP 8.0 support

Feature Request

Q A
New Feature yes

Summary

To be prepared for the december release of PHP 8.0, this repository has some additional TODOs to be tested against the new major version.

In order to make this repository compatible, one has to follow these steps:

  • Modify composer.json to provide support for PHP 8.0 by adding the constraint ~8.0.0
  • Modify composer.json to drop support for PHP less than 7.3
  • Modify composer.json to implement phpunit 9.3 which supports PHP 7.3+
  • Modify .travis.yml to ignore platform requirements when installing composer dependencies (simply add --ignore-platform-reqs to COMPOSER_ARGS env variable)
  • Modify .travis.yml to add PHP 8.0 to the matrix (NOTE: Do not allow failures as PHP 8.0 has a feature freeze since 2020-08-04!)
  • Modify source code in case there are incompatibilities with PHP 8.0

Support XDebug step debugging

Feature Request

Q A
New Feature yes
RFC no
BC Break no

Summary

Debugging swoole applications is much harder as 1. XDebug step debugging does not work out-of-the box and 2. because printing debug messages get send into nirvana.

Both are not related a mezzio swoole but to the nature how the swoole webserver works.

I think I found a good way to support xdebug step debugging requests by manually reproducing what xdebug does normally to start a debug session on http request and would like to get your thoughts about this.

PS: Currently this is a prov-of-concept for step debugging only but it should also be possible for profiling and other debugging sessions.

Requirements to make it work:

  • xdebug installed and debug mode enabled
  • coroutines turned off (Actually didn't test with coroutines turned on yet)
  • Add XDebugSessionRequestListener as first RequestEvent listener ín development.config.php
class XDebugSessionRequestListener
{
    private bool $isAvailable = false;

    private string $startWithRequest = 'trigger';

    private string $triggerValue = '';

    public function __construct()
    {
        if (!\extension_loaded('xdebug')) {
            return;
        }

        $mode = (string)(\getenv('XDEBUG_MODE') ?: \ini_get('xdebug.mode') ?? '');
        if (!\in_array('debug', \explode(',', $mode), true)) {
            return;
        }

        // env XDEBUG_CONFIG
        $envConfig        = [];
        $envConfigEntries = \explode(' ', (string)\getenv('XDEBUG_CONFIG'));
        foreach ($envConfigEntries as $envConfigEntry) {
            $envConfigSplit                = \explode('=', $envConfigEntry);
            $envConfig[$envConfigSplit[0]] = $envConfigSplit[1] ?? null;
        }

        $startWithRequest = $envConfig['start_with_request'] ?? (string)\ini_get('xdebug.start_with_request');
        if ($startWithRequest === 'no') {
            return;
        }

        // Normalize "xdebug.start_with_request" setting
        // as the value "default" depends on "xdebug.mode":
        //    debug: trigger
        //    gcstats: no
        //    profile: yes
        //    trace: trigger
        // -> We already expect "xdebug.mode" to include "debug"
        if ($startWithRequest === 'default') {
            $startWithRequest = 'trigger';
        }

        $this->startWithRequest = $startWithRequest;
        $this->triggerValue     = $envConfig['trigger_value'] ?? (string)\ini_get('xdebug.trigger_value');
        $this->isAvailable      = true;
    }

    public function __invoke(RequestEvent $event): void
    {
        if (!$this->isAvailable) {
            return;
        }

        // XDebug is configured to auto start on each request
        if ($this->startWithRequest === 'yes') {
            $this->start();
            return;
        }

        if ($this->startWithRequest !== 'trigger') {
            return;
        }

        $request = $event->getRequest();

        $requestValue = $request->cookie['XDEBUG_TRIGGER']
            ?? $request->get['XDEBUG_TRIGGER']
            ?? $request->post['XDEBUG_TRIGGER']
            ?? null;

        // legacy triggers
        $requestValue ??= $request->cookie['XDEBUG_SESSION']
            ?? $request->get['XDEBUG_SESSION']
            ?? $request->post['XDEBUG_SESSION']
            ?? null;

        if ($requestValue === $this->triggerValue || ($requestValue !== null && !$this->triggerValue)) {
            $this->start();
        }
    }

    private function start(): void
    {
        if (\function_exists('xdebug_connect_to_client')) {
            // XDebug >= 3.1
            \xdebug_connect_to_client();
        } else {
            // XDebug < 3.1 we have to set a breakpoint
            \xdebug_break();
        }
    }
}

SwooleStream is cutting down response

Bug Report

SwooleStream is cutting down response when there is one character left in the stream.

Branch: master

Summary

// add this test case to the SwooleStreamTest

public function testCrossCase(): void
{
    $len = strlen(self::DEFAULT_CONTENT);

    $this->assertSame('This is a test', $this->stream->read($len - 1));
    $this->assertFalse($this->stream->eof()); // it fails here
}

Current behavior

Test fails

How to reproduce

Just run provided test case

Expected behavior

$this->stream->eof() shoud return false, because there is one character left in the stream

Support for PHP 8.2

Feature Request

Q A
New Feature yes
RFC no
BC Break no

Summary

I'm creating this as I don't see a ticket to add support for php 8.2

I'm willing to contribute the change if needed.

App specific listeners for swoole events

  • I was not able to find an open or closed issue matching what I'm seeing.
  • This is not a question. (Questions should be asked on chat (Signup here) or our forums.)

Use swoole tick timer on the worker process to be able to use it as the event loop for guzzle.

PS: By default guzzle uses PHP shutdown handler but this does not work in a swoole environment. To be able to use async Guzzle callbacks within an swoole worker you have to run the task queue of Guzzle manually. This can simply be done using the SwooleServer::tick function of the worker process.

Code to reproduce the issue

// This does not work as "SwooleServer::on()" supports only one listener
// and there is already a listener in SwooleRequestHandlerRunner
$masterServer = $container->get(SwooleHttpServer::class);
$masterServer->on('workerstart', function (SwooleHttpServer $workerServer) {
    $queue = \GuzzleHttp\Promise\queue();
    $workerServer->tick(100, function () use ($queue) {
        $queue->run();
    });
});

// I had to extend SwooleRequestHandlerRunner
// and copy-past SwooleRequestHandlerRunnerFactory
// to use an own event manager to add application specific listeners to these events
$em = $container->get(EventManagerInterface::class);
$em->attach(WorkerStartEvent::class, function (WorkerStartEvent $event) {
    $queue = \GuzzleHttp\Promise\queue();
    $workerServer = $event->getServer();
    $workerServer->tick(1000, function () use ($queue) {
        $queue->run();
    });
});

Expected results

There should already be a way in zend-expressive-swoole to add application specific listeners to such events

Actual results

It's not possible without extending SwooleRequestHandlerRunner and copy-pasting SwooleRequestHandlerRunnerFactory.


Originally posted by @marc-mabe at zendframework/zend-expressive-swoole#69

SwooleEmitter.php - SameSite=null

Bug Report

Q A
Version(s) 2.6

Summary

If there's a cookie in the response and the Cookie is missing the 'SameSite' directive then a fatal error will be thrown.

PHP Fatal error: Uncaught TypeError: Swoole\Http\Response::cookie() expects parameter 8 to be string, null given in /var/www/mezzio-test/vendor/mezzio/mezzio-swoole/src/SwooleEmitter.php:106

Current behavior

If there's a response with a cookie and no SameSite directive then the swoole process will just die

How to reproduce

I installed a clean and fresh instance of mezzio, configured the project to use swoole with these instructions, modified the HomePageHandler.php like this:

$response = new HtmlResponse($this->template->render('app::home-page', $data));
$cookie = 'CookieName=CookieValue; Expires=Wed, 01-Jul-2020 13:43:42 GMT; Path=/; Secure; HttpOnly;';
$response = $response->withHeader('Set-Cookie', $cookie);

return $response;

and started it using php7.3
/usr/bin/php7.3 /mezzio-test/public/index.php

i've fixed it by setting sameSite to an empty string instead of null:
$sameSite = $cookie->getSameSite() ? substr($cookie->getSameSite()->asString(), 9) : '';

As for the SwooleEmitter.php tests: i don't know why phpunit doesn't have the same error. any hints for learning purposes would be nice.

Expected behavior

I'd expected to get a normal response with a Cookie

Stream response with unknown size uses getContents

Bug Report

Q A
Version(s) 3.3.1

Summary

I want to stream a response with unknown size.

Current behavior

SwooleEmitter calls SteamInterface::getContents() when StreamInterface::getSize() returns null

How to reproduce

Adding a failing test and fix in #69

Expected behavior

SwooleEmitter calls StreamInterface::read() when StreamInterface::getSize() returns null

Code highlighter doesnt work on website.

Bug Report

syntax highlighter doesnt work on website.

Summary

Code highlighting on website is illegible, its dark gray on slightly less darker gray - hard to read.

Current behavior

Hard to read code examples

How to reproduce

Visit this page https://docs.mezzio.dev/mezzio-swoole/v4/logging/ see this code block:
gray

Expected behavior

we should be seeing nice and fancy syntax highlights in multiple colors that are other then gray

Access logger does not log correct remote addresses when serving behind a proxy or load balancer

Bug Report

Q A
Version(s) 2.6.3 (probably any version since the access logger exists)

Summary

I have a mezzio app using mezzio-swoole, which is hosted behind a nginx configured as a reverse proxy.

I have configured the access logger like this:

return [
    
    'mezzio-swoole' => [
        'swoole-http-server' => [
            'logger' => [
                'format' => '%h %l %u "%r" %>s %b',
            ],
        ],
    ],

];

However, I have noticed that the %h part is being replaced by the proxy IP address, instead of the real client address.

I have digged in the code and it looks like it's always using the REMOTE_ADDR server param, when it should be first checking the HTTP_X_FORWARDED_FOR one, and if not found, then fall back to REMOTE_ADDR (I think).

It should potentially check HTTP_X_REAL_IP and HTTP_CLIENT_IP first too, as those are common ways to forward real IP addresses from reverse proxies.

Current behavior

When using the %h or %a modifiers for the access logging format, if the app is served behind a reverse proxy, the proxy IP address is logged.

How to reproduce

Set up a mezzio skeleton app, install swoole and mezzio-swoole and add the logger config provided above.

Then put a reverse proxy in front of the app and try accessing it.

Expected behavior

When using the %h or %a modifiers for the access logging format, if the app is served behind a reverse proxy, the real client IP address is logged.


I can provide a fix for this if you think that would be proper solution.

Routing not working because of wrong URI

Bug Report

Summary

I have set up Swoole with Mezzio using the mezzio/mezzio-swoole package. I'm running the application with Docker, based on the phpswoole/swoole:4.6-php7.4-alpine image. I have set up 2 routes in the config/routes.php, one is /foo another is /bar. However, when I try to open /foo or /bar in the browser, it matches the / route instead, which is non-existent in my case and it falls back to the NotFoundHandler.

Current behavior

I tried to intercept the request by placing a middleware before the RouteMiddleware to see what does the request contain and I tried printing out the $request->getUri()->getPath(). Regardless of what URL I use to make the request to, the resulting URI path is always /.

How to reproduce

  1. Setup a mezzio application
  2. Add swoole
  3. Configure this in a Docker environment with an entrypoint or cmd to run ./vendor/bin/laminas mezzio:swoole:start
  4. Create a route which is not the root, e.g. /foo with a FooHandler
  5. Try to visit the /foo URL

Expected behavior

The expected behavior would be for the application to match the request to the specified route. For some reason it seems that Swoole/Mezzio does not recognize the URI path and always shows and matches the root / instead.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.