Skip to content

Commit

Permalink
Merge pull request #1686 from brefphp/lambda-context
Browse files Browse the repository at this point in the history
Expose the Lambda context in `LAMBDA_INVOCATION_CONTEXT` in all runtimes
  • Loading branch information
mnapoli committed Jan 1, 2024
2 parents 9670734 + 7d1cab3 commit 65b318a
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 3 deletions.
4 changes: 1 addition & 3 deletions src/ConsoleRuntime/Main.php
Original file line number Diff line number Diff line change
Expand Up @@ -45,9 +45,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;
Expand Down
12 changes: 12 additions & 0 deletions src/Runtime/LambdaRuntime.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
use Exception;
use JsonException;
use Psr\Http\Server\RequestHandlerInterface;
use RuntimeException;
use Throwable;

/**
Expand Down Expand Up @@ -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');
Bref::events()->beforeInvoke($handler, $event, $context);

Expand Down Expand Up @@ -432,4 +436,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");
}
}
}

0 comments on commit 65b318a

Please sign in to comment.