bootstrap 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. #! /opt/bin/php -c /opt/etc/php.ini
  2. <?php
  3. // This invokes Composer's autoloader so that we'll be able to use Guzzle and any other 3rd party libraries we need.
  4. require __DIR__ . '/vendor/autoload.php';
  5. function getNextRequest()
  6. {
  7. $client = new \GuzzleHttp\Client();
  8. $response = $client->get('http://' . $_ENV['AWS_LAMBDA_RUNTIME_API'] . '/2018-06-01/runtime/invocation/next');
  9. return [
  10. 'invocationId' => $response->getHeader('Lambda-Runtime-Aws-Request-Id')[0],
  11. 'payload' => json_decode((string)$response->getBody(), true)
  12. ];
  13. }
  14. function sendResponse($invocationId, $response)
  15. {
  16. $client = new \GuzzleHttp\Client();
  17. $client->post(
  18. 'http://' . $_ENV['AWS_LAMBDA_RUNTIME_API'] . '/2018-06-01/runtime/invocation/' . $invocationId . '/response',
  19. ['body' => $response]
  20. );
  21. }
  22. function sendError($invocationId, $error)
  23. {
  24. $client = new \GuzzleHttp\Client();
  25. $client->post(
  26. 'http://' . $_ENV['AWS_LAMBDA_RUNTIME_API'] . '/2018-06-01/runtime/invocation/' . $invocationId . '/error',
  27. ['body' => $error]
  28. );
  29. }
  30. // This is the request processing loop. Barring unrecoverable failure, this loop runs until the environment shuts down.
  31. do {
  32. // Ask the runtime API for a request to handle.
  33. $request = getNextRequest();
  34. try {
  35. // Obtain the function name from the _HANDLER environment variable and ensure the function's code is available.
  36. $handlerFunction = array_slice(explode('.', $_ENV['_HANDLER']), -1)[0];
  37. require_once $_ENV['LAMBDA_TASK_ROOT'] . '/src/' . $handlerFunction . '.php';
  38. // Execute the desired function and obtain the response.
  39. $response = $handlerFunction($request['payload']);
  40. // Submit the response back to the runtime API.
  41. sendResponse($request['invocationId'], $response);
  42. } catch (Throwable $e) {
  43. sendError($request['invocationId'], (string)$e);
  44. }
  45. } while (true);