Documentation menu

Lifecycle

php-via provides hooks at every stage, from a worker's start to a tab's last cleanup. Use them to manage timers, presence tracking, background work and resource cleanup.

Worker start and stop

$app->onWorkerStart() runs in every worker process when it starts, and $app->onWorkerStop() when it stops. Both callbacks get the worker's id. With withWorkerNum(4) they run four times, and again for a worker that restarts after a reload, a max_request recycle or a crash. Run work meant for one worker where $workerId === 0: worker 0 always exists and restarts under the same id.

$app->onWorkerStart(function (int $workerId) use ($app): void {
    if ($workerId === 0) {
        $app->setGlobalState('started_at', time());
    }
});

$app->onWorkerStop(function (int $workerId) use ($db): void {
    $db->close(); // end connections and long-lived coroutines here
});

A stopping worker first waits up to half its stop budget for open SSE streams and spawn() tasks, then runs the stop callbacks. A callback cannot tell a reload from a stop.

Connection lifecycle

Here's what happens for each tab:

  1. Page load (GET): the page handler runs, the initial HTML is rendered
  2. SSE connect (GET /_sse): the view renders again and onClientConnect fires
  3. Actions: POST to /_action/{name}, the callback runs, patches stream back
  4. SSE disconnect: onClientDisconnect fires at once
  5. Cleanup (after a timeout): onCleanup callbacks fire, timers are cancelled

If the browser reconnects within the cleanup delay (default: 5 seconds), the context is reused and cleanup is cancelled: you won't see a spurious disconnect/reconnect for normal page refreshes. Configure the delay with Config::withContextTimeouts(cleanupDelayMs: ...). A longer delay tolerates flakier clients at the cost of holding idle contexts (and their in-memory view payloads) in memory longer under concurrent disconnects; pass 0 to clean up immediately with no reconnect grace period:

$config->withContextTimeouts(cleanupDelayMs: 60_000); // 60 seconds

withContextTimeouts() changes only the timers you name and keeps the others as they are.

Contexts without a stream

A context whose SSE stream never connects (a crawler, a prefetch, a tab closed before it connected) is destroyed after the connect timeout, 30 seconds by default, and its onCleanup callbacks run. With several workers the same applies to a copy an action rebuilt on a worker the tab does not stream from; every action on it starts the timeout again. A tab that connects later is rebuilt by revival. Config::withContextTimeouts(connectMs: 0) keeps such contexts until the worker stops.

An action that reaches a tab whose stream is down, because the stream dropped or because the action revived the context after the cleanup delay, keeps the context for the reconnect timeout, 60 seconds by default, counted from the last action. Datastar waits at most 30 seconds between two reconnect attempts (retryMaxWait), so the patches the action queued are sent when the stream comes back. If you raise retryMaxWait, raise the timeout above it:

$config->withContextTimeouts(reconnectMs: 60_000); // default; 0 uses the connect timeout

Which timer frees a context without a stream:

  • Its stream never connected: the connect timeout (30 s).
  • Its stream dropped: the cleanup delay (5 s).
  • An action reached it while it had no stream: the reconnect timeout (60 s) after the last action.
  • An action rebuilt it on a worker the tab does not stream from: the connect timeout after the last action.

Queued patches live in the context. A context freed before its stream returns drops them, together with whatever its actions changed in TAB state. The tab that reconnects later is revived with the signal values it holds and a fresh render of its view, but a one-off patch such as an execScript() is gone.

How a page reconnects

via_head opens the stream with @get('/_sse') as soon as Datastar starts, and again every 15 seconds while no stream is open. When a connection fails, Datastar 1.0.5 retries after 1, 2, 4, 8 and 16 seconds and then every 30 seconds (retryMaxWait), ten times in all (retryMaxCount). Each retry sends the tab's signals as they are at that moment, so a context revived by the retry starts from the current values. A request of your own with retry: 'error' or 'always' also retries after an HTTP error, on the same schedule and within the same ten attempts. The retrying fetch event fires only when a retry is scheduled. Datastar also closes the stream while the tab is hidden and opens it again when the tab is shown.

Once the retries run out, or when a stream ends, the 15-second interval opens a new stream. That wait can outlast the 5-second cleanup delay, and the tab is then revived rather than reconnected to its context. Two kinds of stream end ask the tab to reconnect at once instead: a worker that stops, on a deploy or a reload, so another worker takes the tab, and a login that retired the session cookie the stream was opened with. A page that writes its own bootstrap instead of via_head waits for its own interval.

Each connect renders the view again, and Datastar morphs it into the page. An attribute the browser set by itself, such as the open of a dialog opened with showModal(), goes with it unless the element lists it in data-preserve-attr; see Attributes the browser sets.

How a closed tab is detected

An open SSE stream does nothing between events. It wakes when a patch is queued for it, when its connection closes and when the worker stops, so onClientDisconnect runs about a millisecond after the browser closes the connection, and the tab leaves getClients() on every worker at the same moment. A stream that has sent nothing for 15 seconds writes an SSE comment, which browsers and Datastar ignore, so proxies that close idle connections leave it open:

$config->withSseKeepAliveMs(15_000); // default; 0 sends no comment

A browser that cancels one HTTP/2 stream, as it does for a hidden tab, keeps the connection open, so no close event fires. A server that speaks HTTP/2 checks its streams every 250 ms and ends the ones the browser reset. With dispatch_mode 1, 3 or 7 set through withSwooleSettings(), OpenSwoole has no close event, and a stream notices a closed connection at its next keep-alive interval. A connection that drops without closing, such as a laptop leaving Wi-Fi, stays open until TCP gives up on it.

A tab that reconnects while its old stream is still open stays connected: the old stream ends, onClientConnect fires once, and onClientDisconnect fires only when the tab's last stream ends. A tab restored from the browser's back/forward cache after the cleanup delay is revived, as below, or reloads.

Revival: reconnecting after cleanup, without a reload

When a tab is backgrounded, Datastar closes the /_sse stream (the right thing for battery and data on mobile). If it stays hidden past the cleanup delay, the context is destroyed. Rather than hard-reloading the returning tab, which wipes local (_-prefixed) signals the server never saw, scroll position, and focus, php-via revives it: the server rebuilds an equivalent context with the same context ID (so the already-loaded DOM's bindings and action URLs keep working) and re-seeds the signal values the client still holds and sends on reconnect. Server-owned TAB signals (clientWritable: false, or every TAB signal under Config::withStrictTabSignals()) do not take the client's copy and start from the handler's initial value. The tab's tab state comes back, and $c->input() reads the page's query string again, up to 512 bytes of it.

With withWorkerNum() above 1 the same rebuild happens when a tab's stream reconnects to a worker that does not hold the context, and the worker that held it hands over its TAB signal values while it runs; actions that land on another worker are passed to the one that holds the context. With one worker, the revival records live in the worker's memory, so a tab whose worker restarted reloads.

This is on by default (10-minute window) and needs no application code. Because revival re-runs the page handler, it is not lossless: server-only state such as #[Persist] properties starts over, the handler's timers start again, and onCleanup and connect hooks re-fire, exactly as they would on a reload. Components keep their ids, since each has a namespace. Tune the window, or disable revival entirely (falling back to a reload on reconnect), with:

$config->withContextTimeouts(revivalWindowMs: 600_000); // 10 minutes (default); pass 0 to disable

The page handler of a revived tab runs behind the route's own middleware again, as on a page load, so an auth gate applies and the attributes it sets reach the handler. The middleware gets a GET of the page's URL with the cookies of the request that revives the tab, and the attributes global middleware set on that request: on an action, or SseAwareMiddleware on an SSE reconnect. When it answers instead of calling the handler, the tab is not revived but reloads, from an SSE reconnect or from an action, so the page load gets the middleware's answer, such as its redirect to a login page.

Tab state

$c->setTabState($key, $value) keeps a server-side value of the tab that the page needs to rebuild itself but the browser does not hold, such as the last query result or a cursor. $c->tabState($key, $default) reads it back, also in the handler that runs again on a revival:

$app->page('/search', function (Context $c) use ($search): void {
    $query = $c->signal('', 'query');

    $c->action(function (Context $c) use ($query, $search): void {
        $c->setTabState('results', $search->run($query->string())); // a list of strings
        $c->sync();
    }, 'search');

    $c->view(function () use ($c): string {
        $items = array_map(fn (string $r): string => '<li>' . htmlspecialchars($r) . '</li>', $c->tabState('results', []));

        return '<ul id="results">' . implode('', $items) . '</ul>';
    });
});

Values must be serializable, never reach the browser, and are copies: change one and write it again. A component has keys of its own. Tab state lives as long as the context and then for the revival window. With one worker it stays in memory, and the revival records of destroyed tabs hold up to 64 MiB of it. With more than one worker every worker reads it from the shared context directory, which holds up to 1 024 serialized bytes per tab; raise that with withContextDirectorySize(4096, maxTabStateBytes: ...), where 4096 is the default row count. A write from a spawn() task after the tab's context was destroyed still reaches the revived tab.

onClientConnect (app-level)

Register an app-level callback that fires whenever any client's SSE connection is established. The callback receives the connecting client's Context:

$app->onClientConnect(function (Context $c) use ($app): void {
    // Re-render the route to update presence counters for everyone there
    $app->broadcast(Scope::routeScope($c->getRoute()));
});

onClientDisconnect (app-level)

Fires when an SSE connection closes. The client has already been removed from getClients() when this fires, so any presence count reflects the departure:

$app->onClientDisconnect(function (Context $c) use ($app): void {
    $app->broadcast(Scope::routeScope($c->getRoute()));
});

These two hooks together replace a polling timer for presence features. See Broadcasting.

onCleanup (per-context)

Register cleanup logic per context. It fires when the context is destroyed: after the SSE connection closed and the cleanup delay passed, when the browser sent the close beacon, or when no stream connected within the connect timeout. Use it for resource cleanup specific to that tab:

$c->onCleanup(function (Context $c) use ($room, $app): void {
    unset(Room::$members[$room][$c->getId()]);
    $app->broadcast('room:' . $room);
});

A throw from a cleanup callback, or from onClientConnect and onClientDisconnect, is logged, and the other callbacks still run.

Background tasks

$c->spawn($task) runs per-tab work in a coroutine of its own, such as a long query that reports its progress; see Work that outlasts the action. A task keeps running when its context is destroyed. From then on $c->isDestroyed() is true and its syncs, patches and downloads do nothing. A stopping worker waits for running tasks, and a task that loops checks $app->isShuttingDown() to end in time. A throw from a task reaches onError() as ErrorPhase::Task.

Recurring timers

$c->setInterval() creates an OpenSwoole timer scoped to the context. It fires repeatedly at the given interval (ms) and is automatically cancelled when the context is cleaned up:

$c->setInterval(function () use ($elapsed, $c): void {
    $elapsed->increment();
    $c->syncSignals(); // no action runs here, so send the value
}, 1000); // every 1 second

No need to store the timer ID or cancel it manually: it cleans up with the context. A throw from the callback is logged, reaches onError() as ErrorPhase::Timer, and the timer keeps running.

Server-level timers

For timers that run regardless of who is connected (e.g. a stock price tick), use $app->setInterval(). It runs once for the whole server, on one worker even with withWorkerNum() above 1, and is cleared automatically on shutdown:

$app->setInterval(function () use ($app, $prices): void {
    $app->setGlobalState('price', $prices->latest());
    $app->broadcast(Scope::routeScope('/ticker'));
}, 5000);

Under the hood setInterval() calls Timer::tick() when the leader worker starts and clears it when that worker stops. Pass everyWorker: true to arm it in every worker instead, for work that belongs to each process. Call Timer::tick() from onWorkerStart() yourself when you need the timer ID for conditional logic; onWorkerStart() runs in every worker, so that timer does too. $app->countClients() tells a timer whether anyone is watching; see Counting the tabs in a scope.

Next steps