Skip to content

Commit

Permalink
frankenphp: add frankenphp_loop_max option (#156)
Browse files Browse the repository at this point in the history
  • Loading branch information
dunglas authored Dec 12, 2023
1 parent 5a16ebb commit b3bc258
Show file tree
Hide file tree
Showing 5 changed files with 25 additions and 5 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
### Added

- Add support for Symfony 7
- Add `frankenphp_loop_max` option

## 0.1.0

Expand Down
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,3 +36,7 @@ return function (array $context) {
return new Kernel($context['APP_ENV'], (bool) $context['APP_DEBUG']);
};
```

## Options

* `frankenphp_loop_max`: the number of requests after which the worker must restart, to prevent weird memory leaks (default to `500`, set to `-1` to never restart)
9 changes: 6 additions & 3 deletions src/Runner.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,10 @@
*/
class Runner implements RunnerInterface
{
public function __construct(private HttpKernelInterface $kernel)
{
public function __construct(
private HttpKernelInterface $kernel,
private int $loopMax,
) {
}

public function run(): int
Expand All @@ -38,6 +40,7 @@ public function run(): int
$sfResponse->send();
};

$loops = 0;
do {
$ret = \frankenphp_handle_request($handler);

Expand All @@ -46,7 +49,7 @@ public function run(): int
}

gc_collect_cycles();
} while ($ret);
} while ($ret && (-1 === $this->loopMax || ++$loops <= $this->loopMax));

return 0;
}
Expand Down
14 changes: 13 additions & 1 deletion src/Runtime.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,22 @@
*/
class Runtime extends SymfonyRuntime
{
/**
* @param array{
* frankenphp_loop_max?: int,
* } $options
*/
public function __construct(array $options = [])
{
$options['frankenphp_loop_max'] = (int) ($options['frankenphp_loop_max'] ?? $_SERVER['FRANKENPHP_LOOP_MAX'] ?? $_ENV['FRANKENPHP_LOOP_MAX'] ?? 500);

parent::__construct($options);
}

public function getRunner(?object $application): RunnerInterface
{
if ($application instanceof HttpKernelInterface && ($_SERVER['FRANKENPHP_WORKER'] ?? false)) {
return new Runner($application);
return new Runner($application, $this->options['frankenphp_loop_max']);
}

return parent::getRunner($application);
Expand Down
2 changes: 1 addition & 1 deletion tests/RunnerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ public function testRun(): void

$_SERVER['FOO'] = 'bar';

$runner = new Runner($application);
$runner = new Runner($application, 500);
$this->assertSame(0, $runner->run());
}
}

0 comments on commit b3bc258

Please sign in to comment.