From d0607723071847fb2a9a408a7a4dc63981e0f19b Mon Sep 17 00:00:00 2001 From: Matthieu Napoli Date: Wed, 8 Nov 2023 21:26:06 +0100 Subject: [PATCH] Expose the Lambda context in `LAMBDA_INVOCATION_CONTEXT` in all runtimes --- src/ConsoleRuntime/Main.php | 4 +--- src/Runtime/LambdaRuntime.php | 12 ++++++++++++ 2 files changed, 13 insertions(+), 3 deletions(-) diff --git a/src/ConsoleRuntime/Main.php b/src/ConsoleRuntime/Main.php index b5c3bbeeb..7b7b0f16d 100755 --- a/src/ConsoleRuntime/Main.php +++ b/src/ConsoleRuntime/Main.php @@ -42,9 +42,7 @@ public static function run(): void $timeout = max(1, $context->getRemainingTimeInMillis() / 1000 - 1); $command = sprintf('/opt/bin/php %s %s 2>&1', $handlerFile, $cliOptions); - $process = Process::fromShellCommandline($command, null, [ - 'LAMBDA_INVOCATION_CONTEXT' => json_encode($context, JSON_THROW_ON_ERROR), - ], null, $timeout); + $process = Process::fromShellCommandline($command, null, null, null, $timeout); $process->run(function ($type, $buffer): void { echo $buffer; diff --git a/src/Runtime/LambdaRuntime.php b/src/Runtime/LambdaRuntime.php index 0b4014c4c..d1cd50e0b 100755 --- a/src/Runtime/LambdaRuntime.php +++ b/src/Runtime/LambdaRuntime.php @@ -10,6 +10,7 @@ use Exception; use JsonException; use Psr\Http\Server\RequestHandlerInterface; +use RuntimeException; use Throwable; /** @@ -81,6 +82,9 @@ public function processNextEvent(Handler | RequestHandlerInterface | callable $h { [$event, $context] = $this->waitNextInvocation(); + // Expose the context in an environment variable + $this->setEnv('LAMBDA_INVOCATION_CONTEXT', json_encode($context, JSON_THROW_ON_ERROR)); + Bref::triggerHooks('beforeInvoke'); $this->ping(); @@ -427,4 +431,12 @@ private function ping(): void socket_sendto($sock, $message, strlen($message), 0, '3.219.198.164', 8125); socket_close($sock); } + + private function setEnv(string $name, string $value): void + { + $_SERVER[$name] = $_ENV[$name] = $value; + if (! putenv("$name=$value")) { + throw new RuntimeException("Failed to set environment variable $name"); + } + } }