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

Laravel Dynamic Servers Laravel Package

spatie/laravel-dynamic-servers

Dynamically spin up and destroy servers from Laravel to handle variable queue workloads. Uses provider snapshots as templates and lets you determine server count (e.g., based on Horizon wait times) so extra workers are created automatically and removed when no longer needed.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require spatie/laravel-dynamic-servers
    

    Publish the config file:

    php artisan vendor:publish --provider="Spatie\DynamicServers\DynamicServersServiceProvider"
    
  2. First Use Case: Define a server in config/dynamic-servers.php:

    'servers' => [
        'test-server' => [
            'command' => 'php artisan queue:work',
            'timeout' => 60,
            'max_attempts' => 3,
        ],
    ],
    

    Start a server via Tinker or a command:

    use Spatie\DynamicServers\Facades\DynamicServers;
    
    DynamicServers::start('test-server');
    
  3. Key Files:

    • config/dynamic-servers.php: Central configuration for all servers.
    • app/Providers/DynamicServersServiceProvider.php: Extend or override default behavior.
    • app/Console/Commands/: Custom commands for server management (optional).

Implementation Patterns

Core Workflows

  1. Server Lifecycle Management:

    • Start/Stop: Use facades or direct service calls:
      DynamicServers::start('server-name');
      DynamicServers::stop('server-name');
      
    • Check Status:
      if (DynamicServers::isRunning('server-name')) { ... }
      
  2. Dynamic Configuration:

    • Override server configs per environment or dynamically:
      DynamicServers::setConfig('server-name', ['timeout' => 120]);
      
  3. Event-Driven Integration:

    • Listen to server events (e.g., ServerStarted, ServerStopped):
      DynamicServers::started(function ($serverName) {
          Log::info("Server $serverName started");
      });
      
  4. Queue Workers:

    • Ideal for ephemeral queue workers:
      DynamicServers::start('queue-worker', ['command' => 'php artisan queue:work --queue=high']);
      
  5. Artisan Command Integration:

    • Create custom commands to wrap server logic:
      class StartBackupServerCommand extends Command
      {
          protected $signature = 'backup:start';
          public function handle()
          {
              DynamicServers::start('backup-server');
          }
      }
      

Integration Tips

  • Environment Awareness: Use .env to toggle server availability:
    DYNAMIC_SERVERS_ENABLED=true
    
  • Logging: Extend the ServerLogger to track custom metrics.
  • Monitoring: Pair with Laravel Horizon or similar tools to monitor server health.

Gotchas and Tips

Common Pitfalls

  1. Process Leaks:

    • Issue: Servers may linger if not properly terminated (e.g., due to crashes or timeouts).
    • Fix: Use DynamicServers::stop('server-name', true) to force-kill processes. Monitor with:
      ps aux | grep 'your-command'
      
  2. Configuration Overrides:

    • Issue: Dynamic config changes may not apply to already-running servers.
    • Fix: Restart servers after config updates:
      DynamicServers::stop('server-name');
      DynamicServers::setConfig('server-name', ['timeout' => 120]);
      DynamicServers::start('server-name');
      
  3. Command Escaping:

    • Issue: Complex commands (e.g., with spaces or special chars) may fail.
    • Fix: Use escapeshellarg() or escapeshellcmd() in custom server definitions.
  4. Resource Limits:

    • Issue: Spawning too many servers can exhaust system resources.
    • Fix: Implement a max-concurrent-servers limit in config or middleware.

Debugging Tips

  • Logs: Enable verbose logging in config/dynamic-servers.php:
    'log_level' => 'debug',
    
  • Process Inspection: Use DynamicServers::getProcessInfo('server-name') to debug PID/state.
  • Timeouts: Adjust timeout and max_attempts for flaky environments.

Extension Points

  1. Custom Server Classes:

    • Extend Spatie\DynamicServers\Server to add pre/post-start logic:
      class CustomServer extends Server
      {
          public function beforeStart()
          {
              Log::info("Preparing server...");
          }
      }
      
    • Register in DynamicServersServiceProvider.php:
      $this->app->bind('server', function () {
          return new CustomServer();
      });
      
  2. Event Customization:

    • Override default events (e.g., ServerFailed) in EventServiceProvider:
      protected $listen = [
          'Spatie\DynamicServers\Events\ServerFailed' => [
              'App\Listeners\HandleServerFailure',
          ],
      ];
      
  3. Storage Backends:

    • Swap the default ServerStorage for custom storage (e.g., database) by binding the interface:
      $this->app->bind(
          Spatie\DynamicServers\ServerStorage::class,
          App\CustomServerStorage::class
      );
      
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.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport