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

Mercure Laravel Package

symfony/mercure

Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Event-Driven & Real-Time Needs: Mercure excels in architectures requiring real-time updates (e.g., notifications, live dashboards, collaborative editing). It aligns well with Laravel’s event system (e.g., Event facade) and broadcasting capabilities, but introduces a pub/sub layer outside traditional Laravel queues.
  • Decoupling: Mercure decouples producers (Laravel services) from consumers (clients), enabling scalable, distributed updates. This fits microservices or monolithic apps with high real-time demands.
  • Protocol Overhead: Mercure adds HTTP/2 or SSE-based push logic, which may conflict with existing WebSocket (Laravel Echo/Pusher) or polling-based systems. Trade-off: Lower latency than polling but higher complexity than WebSockets for bidirectional communication.

Integration Feasibility

  • Laravel Synergy: Works seamlessly with Laravel’s HTTP layer (via HttpClient) and event system. Example:
    use Symfony\Component\Mercure\HubInterface;
    use Symfony\Component\Mercure\Update;
    
    event(new UserUpdated($user));
    // Listener pushes to Mercure Hub:
    public function handle(UserUpdated $event, HubInterface $hub) {
        $update = new Update(
            '/updates/user/' . $event->user->id,
            json_encode($event->user)
        );
        $hub->publish($update);
    }
    
  • Existing Infrastructure: Requires a Mercure Hub (self-hosted or managed, e.g., Deta, Mercure.rocks). This adds operational complexity if not already in use.
  • Client-Side: Clients subscribe via JavaScript (fetch + EventSource API), which may require frontend updates if not already using SSE.

Technical Risk

  • Hub Dependency: Vendor lock-in risk if using a managed hub (e.g., Deta). Self-hosting requires maintaining a separate service.
  • Security: Mercure updates are signed (JWT) by default, but misconfiguration (e.g., weak keys, CORS) could expose endpoints. Laravel’s auth system won’t directly apply; rely on Mercure’s built-in protections.
  • Performance: High-frequency updates may overwhelm the hub or clients. Mitigation: Rate-limiting, topic scoping (e.g., /updates/{user_id}), or batching.
  • Debugging: Real-time issues (e.g., dropped updates) are harder to diagnose than queued jobs. Tooling: Mercure Hub metrics/logs are critical.

Key Questions

  1. Hub Strategy: Self-hosted (Docker, Kubernetes) vs. managed? What’s the SLA/RTO for the hub?
  2. Topic Design: How will topics (e.g., /updates/{resource}) map to Laravel models/routes? Avoid wildcards (e.g., /updates/*) for scalability.
  3. Fallbacks: What’s the plan for hub downtime? (e.g., fallback to polling or WebSockets.)
  4. Client Compatibility: Are all target clients (mobile, legacy browsers) SSE-capable?
  5. Cost: Managed hubs may have usage limits or costs. Self-hosting adds server resources.
  6. Laravel Ecosystem: How will this interact with existing broadcasting (Echo/Pusher)? Will it replace or augment it?

Integration Approach

Stack Fit

  • Laravel Core: Leverage:
    • Events: Trigger updates via Laravel’s event system.
    • HTTP Client: Publish to Mercure Hub (e.g., HttpClient for self-hosted hubs).
    • Middleware: Add Mercure auth/signing logic (e.g., Mercure\Middleware\JWTMiddleware).
  • Frontend: Replace polling or WebSocket listeners with EventSource:
    const eventSource = new EventSource('https://hub.example.com/.well-known/mercure?topic=/updates/user/123');
    eventSource.onmessage = (e) => console.log(JSON.parse(e.data));
    
  • Database: No direct changes, but consider database triggers or queue listeners to fire events for DB updates.

Migration Path

  1. Pilot Phase:
    • Start with a single high-impact feature (e.g., notifications).
    • Use a managed hub (e.g., Deta) to avoid self-hosting risks.
  2. Incremental Rollout:
    • Replace polling-based updates first (lowest effort).
    • Gradually migrate WebSocket-dependent features if Mercure meets latency needs.
  3. Hub Deployment:
    • Self-hosted: Dockerize the Mercure Hub and integrate with Laravel’s CI/CD.
    • Managed: Configure hub in config/mercure.php with API keys.

Compatibility

  • Laravel Versions: Compatible with Laravel 8+ (PHP 8.0+). Test with:
    • symfony/http-client (for publishing).
    • symfony/mercure-bundle (if using Symfony’s ecosystem).
  • Frontend: Ensure clients support SSE (all modern browsers; polyfills for older ones).
  • Existing Services: Audit:
    • APIs: No changes needed if consumers are HTTP-based.
    • WebSockets: May require dual-stack support during transition.

Sequencing

  1. Backend:
    • Add Mercure Hub URL to .env (MERCURE_HUB_URL).
    • Create a service to publish updates (e.g., MercurePublisher).
    • Update event listeners to use the service.
  2. Frontend:
    • Replace setInterval polling with EventSource.
    • Add error handling for SSE disconnections.
  3. Testing:
    • Unit: Mock HubInterface to test event publishing.
    • Integration: Verify hub receives updates (check hub logs).
    • E2E: Test real-time updates in staging with a managed hub.

Operational Impact

Maintenance

  • Hub Management:
    • Self-hosted: Monitor hub health (CPU, memory, connection drops). Use mercure CLI tools for diagnostics.
    • Managed: Rely on provider metrics (e.g., Deta’s dashboard).
  • Laravel:
    • Add Mercure-related config to config/mercure.php (e.g., JWT secret, allowed topics).
    • Document hub dependencies in README.md or architecture docs.
  • Updates:
    • Mercure Hub updates are independent of Laravel. Pin versions in composer.json to avoid breaking changes.

Support

  • Troubleshooting:
    • Client-side: Check browser console for SSE errors (e.g., EventSource failures).
    • Server-side: Log hub events and Laravel event dispatches. Use stderr logging for Mercure Hub.
    • Common Issues:
      • CORS: Ensure hub allows Laravel’s frontend domains.
      • Authentication: Verify JWT signing/validation.
      • Latency: Use curl -v to test hub responsiveness.
  • SLA:
    • Define RTO/RPO for hub failures (e.g., "fallback to polling within 5 minutes").
    • Document escalation paths for hub provider issues.

Scaling

  • Hub Scaling:
    • Managed hubs auto-scale (e.g., Deta handles traffic spikes).
    • Self-hosted: Scale horizontally (Mercure Hub supports clustering).
  • Laravel:
    • Event Throttling: Use Laravel’s throttle middleware to limit Mercure updates.
    • Topic Granularity: Narrow topics (e.g., /updates/user/{id}) to reduce hub load.
  • Client-Side:
    • Implement exponential backoff for reconnecting EventSource.
    • Use service workers to cache updates offline.

Failure Modes

Failure Impact Mitigation
Mercure Hub downtime Real-time updates fail Fallback to polling or WebSockets
Network partition (client) Stale updates Client-side reconnection + optimistic UI
JWT misconfiguration Unauthorized access Audit hub logs; restrict topics
High update volume Hub/client overload Rate-limiting; topic scoping
Laravel event listener fail Updates not published Retry logic (e.g., Laravel Queue)

Ramp-Up

  • Onboarding:
    • Developers: Provide a mercure.md guide with:
      • Setup steps (hub config, event listeners).
      • Example topics and payloads.
      • Debugging checklist.
    • QA: Test with a staging hub; validate edge cases (e.g., rapid updates, client disconnections).
  • Training:
    • Workshop on Mercure’s pub/sub model vs. traditional HTTP.
    • Demo of client-side SSE integration.
  • Documentation:
    • Architecture Decision Record (ADR): Justify Mercure over alternatives (e.g., WebSockets).
    • Runbook: Steps to recover from hub failures
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.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware