Skip to content

Instantly share code, notes, and snippets.

@g105b
Last active December 6, 2019 10:59
Show Gist options
  • Save g105b/1e305bd05c442ec5f32b16bede46eb95 to your computer and use it in GitHub Desktop.
Save g105b/1e305bd05c442ec5f32b16bede46eb95 to your computer and use it in GitHub Desktop.
Lambda runtime entrypoint for PHP.Gt WebEngine
#!/opt/bin/php
<?php
require __DIR__ . "/vendor/autoload.php";
use Gt\Fetch\Http;
use Gt\Fetch\Response\BodyResponse;
while(true) {
$payload = null;
$invocationId = null;
$http = new Http();
$http->fetch(
"http://"
. $_ENV["AWS_LAMBDA_RUNTIME_API"]
. "/2018-06-01/runtime/invocation/next"
)->then(function(BodyResponse $response) use(&$invocationId) {
$invocationId = $response->getHeaderLine("Lambda-Runtime-Aws-Request-Id");
return $response->text();
})->then(function(string $text) use(&$payload) {
$payload = json_decode($text, true);
});
$http->wait();
$handlerFunction = array_slice(explode(".", $_ENV["_HANDLER"]), -1)[0];
require_once($_ENV["LAMBDA_TASK_ROOT"] . "/function/" . $handlerFunction . ".php");
/*
TODO: Once WebEngine is available in the handlerFunction context, the PSR-7 Response
will be returned, which needs to be converted into this object and json_encoded
as the POST body.
{
"isBase64Encoded": true|false,
"statusCode": httpStatusCode,
"headers": { "headerName": "headerValue", ... },
"multiValueHeaders": { "headerName": ["headerValue", "headerValue2", ...], ... },
"body": "..."
}
*/
$response = $handlerFunction($payload);
$http->fetch(
"http://"
. $_ENV["AWS_LAMBDA_RUNTIME_API"]
. "/2018-06-01/runtime/invocation/"
. $invocationId
. "/response",
[
"method" => "POST",
"body" => $response,
]
);
$http->wait();
}
<?php
/*
{
"isBase64Encoded": true|false,
"statusCode": httpStatusCode,
"headers": { "headerName": "headerValue", ... },
"multiValueHeaders": { "headerName": ["headerValue", "headerValue2", ...], ... },
"body": "..."
}
*/
function handler($request) {
$lambdaResponse = (object)[
"isBase64Encoded" => false,
"statusCode" => 200,
"headers" => (object)[
"Content-type" => "text/plain",
"X-Test" => "My name is Greg",
],
"multiValueHeaders" => (object)[
"X-Multi-Test" => [
"First MVH",
"Second MVH",
],
],
"body" => "Mary had a little Lambda",
];
return json_encode($lambdaResponse);
}
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"Service": "lambda.amazonaws.com"
},
"Action": "sts:AssumeRole"
}
]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment