Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Lambda Laravel Package

async-aws/lambda

Async AWS Lambda client for PHP with promise-based async invocations, typed request/response objects, streaming payload support, and credential/region configuration. Lightweight alternative to the AWS SDK for calling and managing Lambda functions.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require async-aws/lambda
    

    Requires PHP 8.2+ and async-aws/core (installed automatically).

  2. Basic Usage:

    use AsyncAws\Lambda\LambdaClient;
    
    $client = new LambdaClient([
        'region' => 'us-east-1',
        'version' => 'latest',
        'credentials' => [
            'key'    => 'YOUR_ACCESS_KEY',
            'secret' => 'YOUR_SECRET_KEY',
        ],
    ]);
    
    // Example: List all Lambda functions
    $result = $client->listFunctions();
    foreach ($result->getFunctions() as $function) {
        echo $function->getFunctionName() . "\n";
    }
    
  3. First Use Case: Invoke a Lambda function with payload:

    $result = $client->invoke([
        'functionName' => 'my-function',
        'payload' => json_encode(['key' => 'value']),
    ]);
    echo $result->getPayload(); // Raw response
    

Key Entry Points

  • Client: LambdaClient (main interface for all operations).
  • Operations: Methods like listFunctions(), getFunction(), invoke(), etc.
  • Value Objects: Strongly-typed responses (e.g., FunctionConfiguration, LayerVersion).

Implementation Patterns

Common Workflows

1. Function Management

  • Create/Update:
    $client->createFunction([
        'functionName' => 'my-function',
        'runtime' => 'nodejs20.x',
        'handler' => 'index.handler',
        'role' => 'arn:aws:iam::123456789012:role/lambda-role',
        'code' => [
            'zipFile' => file_get_contents('function.zip'),
        ],
    ]);
    
  • Configuration:
    $config = $client->getFunctionConfiguration(['functionName' => 'my-function']);
    $config->setMemorySize(1024); // Update memory
    $client->updateFunctionConfiguration($config);
    

2. Invocations

  • Synchronous:
    $result = $client->invoke([
        'functionName' => 'my-function',
        'payload' => json_encode(['event' => 'data']),
    ]);
    
  • Asynchronous:
    $client->invokeAsync([
        'functionName' => 'my-function',
        'payload' => json_encode(['event' => 'data']),
    ]);
    
  • With Response Stream (for large payloads):
    $result = $client->invokeWithResponseStream([
        'functionName' => 'my-function',
        'payload' => json_encode(['event' => 'data']),
    ]);
    

3. Layers and Permissions

  • Publish Layer:
    $client->publishLayerVersion([
        'layerName' => 'my-layer',
        'content' => [
            'zipFile' => file_get_contents('layer.zip'),
        ],
    ]);
    
  • Grant Permission:
    $client->addPermission([
        'functionName' => 'my-function',
        'action' => 'lambda:InvokeFunction',
        'principal' => 'arn:aws:iam::123456789012:user/alice',
    ]);
    

4. Event Source Mappings

  • Create Mapping (e.g., for SQS):
    $client->createEventSourceMapping([
        'eventSourceArn' => 'arn:aws:sqs:us-east-1:123456789012:my-queue',
        'functionName' => 'my-function',
        'batchSize' => 10,
    ]);
    

5. Concurrency Control

  • Set Reserved Concurrency:
    $client->putFunctionConcurrency([
        'functionName' => 'my-function',
        'reservedConcurrentExecutions' => 10,
    ]);
    

Integration Tips

Laravel Service Provider

Register the client in AppServiceProvider:

use AsyncAws\Lambda\LambdaClient;

public function register()
{
    $this->app->singleton(LambdaClient::class, function ($app) {
        return new LambdaClient([
            'region' => config('aws.region'),
            'credentials' => [
                'key'    => config('aws.key'),
                'secret' => config('aws.secret'),
            ],
        ]);
    });
}

Dependency Injection

Inject the client into controllers/services:

use AsyncAws\Lambda\LambdaClient;

class MyService {
    public function __construct(private LambdaClient $lambda) {}

    public function process()
    {
        $this->lambda->invoke([...]);
    }
}

Error Handling

Use try-catch for AWS-specific exceptions:

use AsyncAws\Core\Exception\AwsException;

try {
    $client->invoke([...]);
} catch (AwsException $e) {
    logger()->error('Lambda error: ' . $e->getAwsErrorMessage());
    throw new \RuntimeException('Lambda invocation failed', 0, $e);
}

Async Operations

For non-blocking calls (e.g., in queues), use invokeAsync and handle responses via SQS/SNS or CloudWatch Logs.


Gotchas and Tips

Pitfalls

  1. Region Configuration:

    • Ensure the region matches the Lambda function's region. Use us-isob-west-1 for AWS GovCloud (ISO) regions.
    • Fallback to default region if an unrecognized region is provided (e.g., us-isof-east-1).
  2. Payload Size Limits:

    • Invoke has a 6MB payload limit (use InvokeWithResponseStream for larger payloads).
    • CreateFunction has a 50MB zip limit (use S3 for larger deployments).
  3. Concurrency Quotas:

    • Default account limits: 1,000 concurrent executions (request increases via AWS Support).
    • Use PutFunctionConcurrency to reserve slots for critical functions.
  4. VPC Encryption Controls:

    • If using VPC, ensure DisallowedByVpcEncryptionControl is handled in error responses (e.g., LastUpdateStatusReasonCode).
  5. Runtime Compatibility:

    • Verify runtime support (e.g., nodejs20.x, python3.12). Check changelog for updates.
  6. Special Characters in Names:

    • Lambda function/alias names with # (e.g., my-function#prod) require proper escaping in the functionName parameter.

Debugging Tips

  1. Enable Debug Logging:

    $client = new LambdaClient([
        'debug' => true, // Enable debug logs
        // ... other config
    ]);
    

    Logs appear in storage/logs/laravel.log (Laravel) or stdout.

  2. Validate Inputs:

    • Use json_encode() to validate payloads before invoking:
      $payload = json_encode(['event' => 'data']);
      if (json_last_error() !== JSON_ERROR_NONE) {
          throw new \InvalidArgumentException('Invalid payload');
      }
      
  3. Check Response Metadata:

    $result = $client->invoke([...]);
    $headers = $result->getHeaders(); // Inspect raw headers
    
  4. Retry Transient Errors:

    • Implement exponential backoff for throttling (TooManyRequestsException):
      use AsyncAws\Core\Exception\AwsException;
      
      $attempts = 0;
      $maxAttempts = 3;
      do {
          try {
              return $client->invoke([...]);
          } catch (AwsException $e) {
              if ($e->getAwsErrorCode() === 'TooManyRequestsException' && $attempts < $maxAttempts) {
                  sleep(2 ** $attempts); // Exponential backoff
                  $attempts++;
              } else {
                  throw $e;
              }
          }
      } while (true);
      

Extension Points

  1. Custom Middleware:

    • Extend AsyncAws\Core\Middleware\MiddlewareStack to add logging/auditing:
      use AsyncAws\Core\Middleware\MiddlewareStack;
      use AsyncAws\Core\Request;
      
      $stack = new MiddlewareStack();
      $stack->push(function (Request $request) {
          logger()->info('Lambda request:', ['action' => $request->getAction()]);
      });
      $client = new LambdaClient(['middleware' => $stack]);
      
  2. Event Subscribers:

    • Subscribe to Lambda events (e.g., function:created) using AWS EventBridge or CloudWatch Events.
  3. Local Testing:

    • Use localstack or aws-lambda-ric for local development:
      $client = new
      
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor