diff --git a/couscous.yml b/couscous.yml index 46da09db7..f9fe88622 100644 --- a/couscous.yml +++ b/couscous.yml @@ -114,6 +114,10 @@ menu: text: Databases url: /docs/environment/database.html title: Using a database from AWS Lambda + timeouts: + text: Timeouts + url: /docs/environment/timeouts.html + title: Configure and handle timeouts custom-domains: text: Custom domains url: /docs/environment/custom-domains.html diff --git a/docs/environment/database.md b/docs/environment/database.md index 631a5cb25..476827999 100644 --- a/docs/environment/database.md +++ b/docs/environment/database.md @@ -54,6 +54,8 @@ When possible, an alternative to NAT Gateways is to split the work done by a lam Finally, another free alternative to NAT Gateway is to access AWS services by creating "*private VPC endpoints*": this is possible for S3, API Gateway, [and more](https://docs.aws.amazon.com/en_pv/vpc/latest/userguide/vpc-endpoints-access.html). +Read more in the section about [timeouts](/docs/environment/timeouts.md). + ## Creating a database On the [RDS console](https://console.aws.amazon.com/rds/home): diff --git a/docs/environment/timeouts.md b/docs/environment/timeouts.md new file mode 100644 index 000000000..3bba4032f --- /dev/null +++ b/docs/environment/timeouts.md @@ -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 +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(); +```