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

Sidecar Laravel Package

hammerstone/sidecar

Sidecar lets Laravel package, deploy, and invoke AWS Lambda functions directly from your app. Define a simple PHP class plus the files to ship, choose any supported runtime (Node, Python, Java, .NET, Ruby, or OS-only), and execute from PHP.

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Setup
1. **Installation**
   ```bash
   composer require hammerstone/sidecar
   php artisan sidecar:configure
  • Run the configure command to set up AWS credentials and region.
  1. Define a Lambda Function Create a PHP class extending Hammerstone\Sidecar\LambdaFunction:

    // app/Sidecar/ExampleFunction.php
    namespace App\Sidecar;
    
    use Hammerstone\Sidecar\LambdaFunction;
    
    class ExampleFunction extends LambdaFunction
    {
        public function handler()
        {
            return 'handler.handler'; // Points to `resources/lambda/handler.js`
        }
    
        public function package()
        {
            return ['resources/lambda'];
        }
    }
    
  2. Deploy

    php artisan sidecar:deploy --activate
    
  3. Execute

    // In a route/controller
    $result = ExampleFunction::execute(['key' => 'value']);
    

First Use Case: Image Generation

  • Handler File (resources/lambda/image.js):
    exports.handler = async (event) => {
        return { image: `Generated for: ${event.text}` };
    };
    
  • Execution:
    $response = OgImage::execute(['text' => 'Hello, Sidecar!']);
    

Implementation Patterns

1. Function Organization

  • Grouping: Place all Sidecar functions in app/Sidecar/ for clarity.
  • Naming: Use descriptive names (e.g., PdfGenerator, ImageProcessor).
  • Handler Files: Store runtime-specific code in resources/lambda/ (e.g., pdf-generator.js, image-processor.py).

2. Workflow: Deploy → Execute → Monitor

  1. Deploy:

    php artisan sidecar:deploy --activate  # Deploys and activates all functions
    php artisan sidecar:deploy ExampleFunction  # Deploy a single function
    
    • Use --pre-warm to initialize Lambda instances immediately.
  2. Execute:

    // Sync execution (blocks until response)
    $result = ExampleFunction::execute(['input' => 'data']);
    
    // Async execution (returns a Promise)
    $promise = ExampleFunction::executeAsync(['input' => 'data']);
    $result = $promise->wait();
    
  3. Monitor:

    • Check logs via AWS Console or use sidecar:logs:
      php artisan sidecar:logs ExampleFunction
      

3. Integration with Laravel

  • Service Providers: Bind functions to the container for dependency injection:
    // app/Providers/AppServiceProvider.php
    public function register()
    {
        $this->app->singleton(ExampleFunction::class);
    }
    
  • Jobs: Offload heavy tasks to Lambda:
    use App\Sidecar\ExampleFunction;
    use Illuminate\Bus\Queueable;
    
    class ProcessData implements ShouldQueue
    {
        use Queueable;
    
        public function handle()
        {
            $result = ExampleFunction::execute(['data' => $this->data]);
        }
    }
    

4. Environment Variables

  • Configure Lambda environment variables in your function:
    public function environment()
    {
        return [
            'API_KEY' => env('AWS_API_KEY'),
            'DEBUG' => app()->environment('local'),
        ];
    }
    
  • Access them in your runtime code (e.g., process.env.API_KEY in Node.js).

5. Advanced: Custom Runtimes

  • Specify runtime explicitly:
    public function runtime()
    {
        return 'python3.12';
    }
    
  • Supported runtimes: AWS Lambda Runtimes.

6. Testing

  • Use sidecar:deploy --env=testing to deploy to a separate environment.
  • Mock Lambda responses in PHPUnit:
    $mock = Mockery::mock(ExampleFunction::class);
    $mock->shouldReceive('execute')->andReturn(['mocked' => 'response']);
    

Gotchas and Tips

Pitfalls

  1. Runtime Mismatches:

    • Default runtime changed from Node 14 → Node 20 in v0.6.0. Explicitly declare runtime if using older versions:
      public function runtime() { return 'nodejs14.x'; }
      
    • Deprecated runtimes (e.g., .NET 7, Python 3.8) will fail silently. Use supported versions.
  2. File Path Issues:

    • Windows Paths: Use forward slashes (/) or DIRECTORY_SEPARATOR:
      return ['resources/lambda' . DIRECTORY_SEPARATOR . '*.js'];
      
    • Relative Paths: Ensure paths are relative to the project root (not resources/).
  3. Cold Starts:

    • Lambda functions may have latency on first invocation. Use --pre-warm during deploy or call sidecar:warm:
      php artisan sidecar:warm ExampleFunction
      
  4. Permission Errors:

    • Run php artisan sidecar:configure if you see AccessDenied errors.
    • Ensure IAM roles have lambda:InvokeFunction permissions.
  5. Payload Size Limits:

    • Lambda payloads are limited to 6MB for synchronous invocations. Use S3 for larger data:
      public function execute($payload)
      {
          if (sizeof($payload) > 6_000_000) {
              return $this->uploadToS3AndInvoke($payload);
          }
          return parent::execute($payload);
      }
      
  6. Environment Collisions:

    • Avoid using APP_ENV for Sidecar. Use sidecar.env in .env:
      SIDECAR_ENV=staging
      

Debugging Tips

  1. Logs:

    • Stream logs in real-time:
      php artisan sidecar:logs ExampleFunction --tail
      
    • Check AWS CloudWatch for Lambda logs.
  2. Error Handling:

    • Wrap executions in try-catch:
      try {
          $result = ExampleFunction::execute($data);
      } catch (\Hammerstone\Sidecar\Exceptions\LambdaException $e) {
          report($e);
          return response()->json(['error' => $e->getMessage()], 500);
      }
      
    • Use SettledResult for async operations:
      $result = ExampleFunction::executeAsync($data)->wait();
      if ($result->isError()) {
          throw new \Exception($result->errorAsString());
      }
      
  3. Deployment Issues:

    • Verify AWS credentials in .env:
      AWS_ACCESS_KEY_ID=your_key
      AWS_SECRET_ACCESS_KEY=your_secret
      AWS_DEFAULT_REGION=us-east-1
      
    • Check for existing functions with aws lambda list-functions.
  4. Function Naming:

    • Long or special characters in APP_NAME may cause issues. Use sidecar:configure to adjust naming conventions.

Extension Points

  1. Custom Deployment Logic:

    • Override deploy() in your function class:
      public function deploy()
      {
          $this->package()->include('custom/path');
          parent::deploy();
      }
      
  2. Package Macros:

    • Extend the Package class:
      \Hammerstone\Sidecar\Support\Package::macro('includeNodeModules', function () {
          return $this->include('node_modules');
      });
      
      Usage:
      public function package()
      {
          return (new \Hammerstone\Sidecar\Support\Package)
              ->includeNodeModules()
              ->include('src');
      }
      
  3. Event-Driven Lambdas:

    • Use event() to trigger functions from S3, SQS, etc.:
      public function event()
      {
          return 's3:ObjectCreated:*';
      }
      
    • Configure triggers in aws lambda add-permission.
  4. Container Images:

    • For Docker-based Lambdas, use containerImageUri():
      public function containerImageUri()
      {
          return '123456789012.dkr.ecr.us-east-1.amazonaws.com/my-repo:latest';
      }
      

Performance Tips

  1. Memory/Timeout:

    • Optimize Lambda config:
      public function memory() { return 512; } // MB
      public function timeout() { return 30; } // seconds
      
  2. Ephemeral Storage:

    • Increase storage for large files:
      public function ephemeralStorage() { return 1024; } // MB
      
  3. Concurrency:

    • Limit concurrent executions to avoid throttling:
      public function
      
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.
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope