phasync
Swerve / draining

Method

Swerve::draining

Whether this worker drains: it is shutting down, reloading or being recycled.

Description#

public static Swerve::draining(): bool

An early hint: it turns true when the drain begins, also for a recycled worker, which then keeps its upgraded connections (and long SSE responses) for up to --linger seconds. What tells that connections must close now is Swerve::onShutdown. Long responses should end soon: see docs/realtime.md. A Subscription ends its loop at that moment, not before.

Return values#

bool

Examples#

Example 1False while serving, true once the drain begins
use Swerve\ClientRequest;
use Swerve\RequestHandler;
use Swerve\Swerve;
use Swerve\WebSocket;

$app = new RequestHandler(function (ClientRequest $request) {
    WebSocket::from($request, function (WebSocket $ws) {
        Swerve::onShutdown(fn () => phasync::shielded(function () use ($ws) {
            $ws->send('draining: ' . var_export(Swerve::draining(), true));
            $ws->end(1001);
        }));
        $ws->send('draining: ' . var_export(Swerve::draining(), true));
        foreach ($ws as $message) {
        }
    });
});

if (debug_backtrace()) {
    return $app;   // swerve loads this file: it is the application's swerve.php
}

// Run directly: serve the application with swerve, and talk to it as a browser would
require __DIR__ . '/../serve.php';
websocket(__FILE__, '/live', [], stop: SIGTERM);   // swerve is stopped after the first message
Output
HTTP/1.1 101 Switching Protocols
upgrade: websocket
connection: Upgrade
sec-websocket-accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
Server: Swerve

< draining: false
< draining: true
< close 1001
Example 2
while (!Swerve::draining()) {
    $out->append(": keep-alive\n\n");
    phasync::sleep(15);
}

See also#

  • Swerve::onShutdownRun $callback when this worker must now close its connections: for an upgraded connection, to say goodbye in its protocol and end it.
  • Swerve::subscribeReceive what is published to $topic from now on.