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

Swoole Bundle Laravel Package

cesurapp/swoole-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require cesurapp/swoole-bundle
    

    Update public/index.php to include the entrypoint:

    require_once dirname(__DIR__).'/vendor/cesurapp/swoole-bundle/src/Runtime/entrypoint.php';
    
  2. Basic Configuration: Add to config/packages/swoole.yaml:

    swoole:
        entrypoint: public/index.php
        watch_dir: /config,/src,/templates
        watch_extension: '*.php,*.yaml,*.yml,*.twig'
    
  3. First Use Case: Start the server in development mode (with file watcher):

    bin/console server:watch
    

    Verify it’s running:

    bin/console server:status
    

Implementation Patterns

1. HTTP Server Integration

  • Replace Symfony HTTP Client: Enable replace_http_client: true in swoole.yaml to leverage Swoole’s async HTTP client for external requests.

    // Example: Async HTTP request in a controller
    $client = $this->container->get('swoole.http_client');
    $response = $client->get('https://api.example.com/data');
    
  • Static File Handling: Enable static file serving via config:

    swoole:
        http_settings:
            enable_static_handler: true
    

2. Background Tasks (Task Workers)

  • Dispatch Tasks: Use TaskHandler in controllers/services:

    $this->taskHandler->dispatch(MyTask::class, ['data' => 'payload']);
    
    • Sync Mode: Set task_sync_mode: true in swoole.yaml for blocking calls (e.g., for critical operations).
  • Task Retries: Configure retries in swoole.yaml:

    swoole:
        failed_task_retry: '@EveryMinute10'
        failed_task_attempt: 3
    

    View failed tasks:

    bin/console task:failed:view
    

3. Scheduled Tasks (Cron Workers)

  • Define Cron Jobs: Extend AbstractCronJob and use predefined expressions:

    class SendDailyReportCron extends AbstractCronJob {
        public string $TIME = '@daily';
        public bool $ENABLE = true;
    
        public function __invoke(): void {
            // Logic here
        }
    }
    

    Register the job in services.yaml:

    services:
        App\Cron\SendDailyReportCron: ~
    
  • Run Manually:

    bin/console cron:run App\Cron\SendDailyReportCron
    

4. Process Workers

  • Long-Running Processes: Use for Redis/Postgres listeners or monitoring:
    class RedisConsumerProcess extends AbstractProcessJob {
        public bool $ENABLE = true;
        public bool $RESTART = true;
        public int $RESTART_DELAY = 5;
    
        public function __invoke(): void {
            $this->redis->subscribe(['queue'], fn($redis, $channel, $msg) => {
                // Process message
            });
        }
    }
    
    Register in services.yaml:
    services:
        App\Process\RedisConsumerProcess: ~
    

5. WebSocket Integration

  • Handler Setup: Implement initServerEvents in your handler:

    class ChatWebSocketHandler {
        public function initServerEvents(Server $server): void {
            $server->on('message', fn($server, Frame $frame) => {
                $server->push($frame->fd, "Echo: {$frame->data}");
            });
        }
    }
    

    Configure in swoole.yaml:

    swoole:
        websocket_handler: App\WebSocket\ChatWebSocketHandler
    
  • Dependency Injection: Use constructor injection for services (e.g., LoggerInterface, ChatService).


Gotchas and Tips

Pitfalls

  1. Serialization Limits:

    • Tasks must serialize data (use serialize()/unserialize()).
    • Avoid passing objects directly; use arrays or DTOs.
    • Fix: Convert objects to arrays before dispatching:
      $this->taskHandler->dispatch(MyTask::class, [
          'user' => $user->toArray(), // Custom method
      ]);
      
  2. Cron Locking:

    • Only one instance of a cron job runs at a time (locking mechanism).
    • Workaround: Use separate cron expressions (e.g., @EveryMinute5 and @EveryMinute10) for parallel jobs.
  3. WebSocket State:

    • Connections are stateless by default. Use external storage (e.g., Redis) for session data.
    • Tip: Store connection IDs ($frame->fd) in Redis for broadcasting.
  4. Process Worker Crashes:

    • If a process crashes, it restarts only if RESTART = true.
    • Debugging: Check logs with:
      bin/console server:status
      
      Or tail Swoole logs:
      tail -f var/log/swoole.log
      
  5. HTTP Client Replacement:

    • Enabling replace_http_client affects all HTTP requests (Symfony HTTP Client, Guzzle, etc.).
    • Test thoroughly in staging before production.

Debugging Tips

  1. Server Status:

    bin/console server:status
    
    • Shows HTTP, cron, task, and process worker states.
  2. Task Debugging:

    • View failed tasks:
      bin/console task:failed:view
      
    • Retry all failed tasks:
      bin/console task:failed:retry
      
  3. Log Levels:

    • Adjust log_level in swoole.yaml (e.g., 4 for SWOOLE_LOG_WARNING).
    • Common levels:
      • 1: SWOOLE_LOG_DEBUG
      • 4: SWOOLE_LOG_WARNING
      • 5: SWOOLE_LOG_ERROR
  4. Development Mode:

    • Use server:watch for auto-reloads during development.
    • Note: File watcher excludes vendor/ and var/ by default.

Extension Points

  1. Custom Task Middleware:

    • Extend TaskHandler to add pre/post-processing:
      class CustomTaskHandler extends TaskHandler {
          public function dispatch(string $task, array $data): void {
              // Pre-process data
              $data['timestamp'] = time();
              parent::dispatch($task, $data);
          }
      }
      
    • Bind in services.yaml:
      services:
          App\Service\CustomTaskHandler: ~
      
  2. WebSocket Authentication:

    • Validate connections in the open event:
      $server->on('open', function($server, $request) {
          if (!$this->authService->validate($request->header)) {
              $server->disconnect($request->fd);
          }
      });
      
  3. Dynamic Cron Jobs:

    • Load cron jobs from a database by implementing a custom CronJobLoader:
      class DatabaseCronJobLoader implements CronJobLoaderInterface {
          public function load(): array {
              return $this->entityManager->getRepository(CronJob::class)->findAll();
          }
      }
      
    • Register as a service with the tag swoole.cron_job_loader.
  4. Task Result Handling:

    • Use task_sync_mode: true for synchronous tasks and capture results:
      $result = $this->taskHandler->dispatchSync(MyTask::class, ['data' => 'payload']);
      

Performance Quirks

  • Worker Count:

    • Default worker_num = CPU cores. Adjust in .env:
      SERVER_HTTP_SETTINGS_WORKER_NUM=4
      
    • Rule of thumb: Start with worker_num = CPU cores * 2 for high-traffic apps.
  • Task Worker Limits:

    • task_worker_num defaults to CPU cores / 2. Increase for heavy async tasks:
      SERVER_HTTP_SETTINGS_TASK_WORKER_NUM=4
      
  • Memory Leaks:

    • Long-running processes (e.g., Redis listeners) may leak memory.
    • Fix: Restart processes periodically or use Swoole\Process::signal() to trigger cleanup.

Environment-Specific Configs

  • Production vs. Development:
    • Disable file watcher in production:
      # config/packages/swoole.yaml (prod)
      swoole:
          watch_dir: null  # Disable in production
      
    • Adjust log levels:
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
andydefer/laravel-cluster
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