-
-
Notifications
You must be signed in to change notification settings - Fork 377
Handle timeouts more gracefully by allowing the application to shutdown #895
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Nyholm
wants to merge
9
commits into
brefphp:master
Choose a base branch
from
Nyholm:timeouts
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 2 commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
e78d2c6
Handle timeouts more gracefully by throwing exception near the hard end
Nyholm 5a57044
Added documentation for Timeouts
Nyholm b89aa04
Adding a note about debugging
Nyholm 52f8d65
Make Timeout::init() private
Nyholm 37a5759
Make this feature opt-in
Nyholm a2e46ca
Make sure the shutdown process has at least 1 second.
Nyholm 0b6d7b2
Always base the timeout duration on the configured Lambda timeout (#3)
mnapoli 9356e4a
Do 2 alarms
Nyholm 2efd449
fixed tests
Nyholm File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,65 @@ | ||
| --- | ||
| title: Timeouts | ||
| current_menu: timeouts | ||
| introduction: Configure and handle timeouts. | ||
| --- | ||
|
|
||
| When a Lambda function times out, it is like the power to the computer is suddenly | ||
| just turned off. This does not give the application a chance to shutdown properly. | ||
| This often leaves you without any logs and the problem could be hard to fix. | ||
|
|
||
| Bref will throw an `LambdaTimeout` exception just before the Lambda actually times | ||
| out. This will allow your application to actually shutdown. | ||
|
|
||
| This feature is enabled automatically for the `php-xx` layer and the `console` layer. | ||
| The `php-xx-fpm` layer needs to opt-in by adding the following to `index.php`. | ||
|
|
||
| ```php | ||
| if (isset($_SERVER['LAMBDA_TASK_ROOT'])) { | ||
| \Bref\Timeout\Timeout::enable(); | ||
| } | ||
| ``` | ||
|
|
||
| ## Configuration | ||
|
|
||
| You may configure this behavior with the `BREF_TIMEOUT` environment variable. To | ||
| always trigger an exception after 10 seconds, set `BREF_TIMEOUT=10`. To disable | ||
| Bref throwing an exception use value `BREF_TIMEOUT=-1`. To automatically set the | ||
| timeout just a hair shorter than the Lambda timeout, use `BREF_TIMEOUT=0`. | ||
|
|
||
| ## Catching the exception | ||
|
|
||
| If you are using a framework, then the framework is probably catching all exceptions | ||
| and displays an error page for the users. You may of course catch the exception | ||
| yourself: | ||
|
|
||
| ```php | ||
| <?php | ||
|
|
||
| require dirname(__DIR__) . '/vendor/autoload.php'; | ||
|
|
||
| use Bref\Context\Context; | ||
| use Bref\Timeout\LambdaTimeout; | ||
|
|
||
| class Handler implements \Bref\Event\Handler | ||
| { | ||
| public function handle($event, Context $context) | ||
| { | ||
| try { | ||
| $this->generateResponse(); | ||
| } catch (LambdaTimeout $e) { | ||
| echo 'Oops, sorry. We spent too much time on this.'; | ||
| } catch (\Throwable $e) { | ||
| echo 'Some unexpected error happened.'; | ||
| } | ||
| } | ||
|
|
||
| private function generateResponse() | ||
| { | ||
| $pi = // ... | ||
| echo 'Pi is '.$pi; | ||
| } | ||
| } | ||
|
|
||
| return new Handler(); | ||
| ``` |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,12 @@ | ||
| <?php declare(strict_types=1); | ||
|
|
||
| namespace Bref\Timeout; | ||
|
|
||
| /** | ||
| * The application took too long to produce a response. This exception is thrown | ||
| * to give the application a chance to flush logs and shut it self down before | ||
| * the power to AWS Lambda is disconnected. | ||
| */ | ||
| class LambdaTimeout extends \RuntimeException | ||
| { | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,92 @@ | ||
| <?php declare(strict_types=1); | ||
|
|
||
| namespace Bref\Timeout; | ||
|
|
||
| /** | ||
| * Helper class to trigger an exception just before the Lamba times out. This | ||
| * will give the application a chance to shut down. | ||
| */ | ||
| final class Timeout | ||
| { | ||
| /** @var bool */ | ||
| private static $initialized = false; | ||
|
|
||
| /** | ||
| * Read environment variables and setup timeout exception. | ||
| */ | ||
| public static function enable(): void | ||
| { | ||
| if (isset($_SERVER['BREF_TIMEOUT'])) { | ||
| $timeout = (int) $_SERVER['BREF_TIMEOUT']; | ||
| if ($timeout === -1) { | ||
| return; | ||
| } | ||
|
|
||
| if ($timeout > 0) { | ||
| self::timeoutAfter($timeout); | ||
|
|
||
| return; | ||
| } | ||
|
|
||
| // else if 0, continue | ||
| } | ||
|
|
||
| if (isset($_SERVER['LAMBDA_INVOCATION_CONTEXT'])) { | ||
| $context = json_decode($_SERVER['LAMBDA_INVOCATION_CONTEXT'], true, 512, JSON_THROW_ON_ERROR); | ||
| $deadlineMs = $context['deadlineMs']; | ||
| $remainingTime = $deadlineMs - intval(microtime(true) * 1000); | ||
|
|
||
| self::timeoutAfter((int) floor($remainingTime / 1000)); | ||
|
|
||
| return; | ||
| } | ||
|
|
||
| throw new \LogicException('Could not find value for bref timeout. Are we running on Lambda?'); | ||
| } | ||
|
|
||
| /** | ||
| * Setup custom handler for SIGTERM. One need to call Timeout::timoutAfter() | ||
| * to make an exception to be thrown. | ||
| * | ||
| * @return bool true if successful. | ||
| */ | ||
| public static function init(): bool | ||
|
Nyholm marked this conversation as resolved.
Outdated
|
||
| { | ||
| if (self::$initialized) { | ||
| return true; | ||
| } | ||
|
|
||
| if (! function_exists('pcntl_async_signals')) { | ||
| trigger_error('Could not enable timeout exceptions because pcntl extension is not enabled.'); | ||
| return false; | ||
| } | ||
|
|
||
| pcntl_async_signals(true); | ||
| pcntl_signal(SIGALRM, function (): void { | ||
| throw new LambdaTimeout('Maximum AWS Lambda execution time reached'); | ||
| }); | ||
|
|
||
| self::$initialized = true; | ||
|
|
||
| return true; | ||
| } | ||
|
|
||
| /** | ||
| * Set a timer to throw an exception. | ||
| */ | ||
| public static function timeoutAfter(int $seconds): void | ||
| { | ||
| self::init(); | ||
| pcntl_alarm($seconds); | ||
| } | ||
|
|
||
| /** | ||
| * Reset timeout. | ||
| */ | ||
| public static function reset(): void | ||
| { | ||
| if (self::$initialized) { | ||
| pcntl_alarm(0); | ||
| } | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.