phasync
Production / WorkerStoppingException

Exception

WorkerStoppingException

Thrown into the coroutines still running when a worker stops, once its requests have finished (or its drain time is over): clean up at once, then let it end; the worker exits shortly after, whether or not they have. A phasync ShutdownException, so a CancelledException: code that only needs to stop catches nothing. $reason says why, for telling a client what happens next.

Class synopsis#

final class WorkerStoppingException extends ShutdownException implements \Throwable, \Stringable, RethrowExceptionInterface {
    /* Methods */
    public WorkerStoppingException::__construct(StopReason $reason)
}

Properties#

NameTypeDescription
$reasonreadonly StopReason

Methods#

MethodDescription
__constructAn exception for a worker that stops for $reason; its message names the reason.

Examples#

Example 1Clean up when the worker stops
use Swerve\ClientRequest;
use Swerve\RequestHandler;
use Swerve\WorkerStoppingException;

$app = new RequestHandler(function (ClientRequest $request) {
    $request->write("export started\n");
    try {
        phasync::sleep(30);                      // a long job; the worker stops meanwhile
        $request->write("export done\n");
    } catch (WorkerStoppingException $e) {
        // Clean up at once; a write waits, so it goes inside shielded()
        phasync::shielded(fn () => $request->write("stopped: {$e->reason->name}, try again\n"));
    }
});

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

// Run directly: serve the application with swerve, and send it requests
require __DIR__ . '/../serve.php';
serve(__FILE__, ["GET /export HTTP/1.1\r\nHost: example\r\n\r\n"], stop: SIGTERM);   // stop swerve once it answers
Output
HTTP/1.1 200 OK
Server: Swerve
Transfer-Encoding: chunked
Connection: close

f
export started

1d
stopped: Shutdown, try again

0