Skip to content

Service worker and shared server event connections: TServiceWorkerModule, TServiceWorkerService, TWebManifest, Prado.SharedConnection (#1478) - #1486

Draft
belisoful wants to merge 5 commits into
pradosoft:masterfrom
belisoful:claude/prado-service-worker-cbd00a

Conversation

@belisoful

@belisoful belisoful commented Nov 7, 2026 •

Copy link
Copy Markdown
Member

Closes #1478. Completes the TWebManifest item of #1405. Web Push follows in #1479; #1435 will be rebased and reworked on this PR.

An application-wide browser service worker configured by one module, and one live connection per browser shared by its tabs.

Usage

<modules>
    <module id="serviceworker" class="Prado\Web\Services\ServiceWorker\TServiceWorkerModule"
        CacheAssets="true" OfflinePage="Offline" NavigationPreload="true"
        NetworkFirst="Catalog, Help" NetworkTimeout="3" ClearSiteDataOnLogout="cache, storage"
        Manifest.Name="Orders" Manifest.ShortName="Orders" Manifest.ThemeColor="#2b5797">
        <worker name="admin" Scope="index.php/admin/" OfflinePage="" />
    </module>
</modules>
<!-- protected/pages/Admin/config.xml -->
<configuration><pages ServiceWorker="admin" /></configuration>
document.addEventListener('prado:serviceworkerupdate', (e) => e.detail.activate());
const version = await Prado.ServiceWorker.postMessage('version');

const sub = Prado.SharedConnection.subscribe({
    key: 'sse:' + url,
    open: Prado.SharedConnection.eventSource(url),
    onMessage(message, info) { /* {id, event, data}; info.leader */ },
});

What it adds

  • TServiceWorkerModule, the one configuration point.

    • ServiceID="Auto" adopts any TServiceWorkerService or registers one as sw, like THttpHeadersManager does for TCspReportingService.
    • The module's properties configure the default worker. Each <worker> element starts from those values and overrides them.
    • Modules contribute code through IServiceWorkerContributor and serve requests through IServiceWorkerRequestHandler.
    • AutoRegister adds TServiceWorker and TWebManifest to the pages of TPageService, except for ExcludePages.
    • Enabled="false" serves a worker that removes itself.
    • ClearSiteDataOnLogout hooks TAuthManager::onLogout.
  • A page's worker is chosen by TServiceWorker.Worker, then TPage.ServiceWorker (also settable from <pages>), then TPageService.ServiceWorker, then DefaultWorker. If that worker's scope is not the longest match for the request path (the browser's rule), the page registers nothing and the module logs a warning.

  • TServiceWorkerService serves:

    • ?sw=worker[&w=name], with Service-Worker-Allowed
    • ?sw=manifest, as application/manifest+json
    • contributor requests

    Every response carries Cache-Control: no-cache, an ETag, and a 304 for a matching If-None-Match.

  • TServiceWorkerScript builds the script: the options, the runtime, then each fragment by priority. Its version is a hash of the content. Cache names are prado-<worker>-<version>-<name>, and activate deletes only the worker's own older caches, since workers of one origin share Cache Storage.

  • The worker runtime (worker.js):

    • adds no fetch listener unless a fragment needs one;
    • never caches non-GET requests, other origins, event streams, callbacks, the service's own URLs, or no-store/private responses;
    • answers page messages on a reply port.
  • The fetch strategies fragment covers asset cache-first, network-first with a timeout, the offline page, and navigation preload.

  • Prado.ServiceWorker (package serviceworker) provides register(), postMessage() with replies, activate(), and the prado:serviceworkerready, prado:serviceworkerupdate, and prado:serviceworkermessage events.

  • TServiceWorker registers the worker as an end script. A page without a TForm renders no end scripts, so on such a page the control writes the package files and the registration where it sits, in the head.

  • TWebManifest (Head metadata controls: TJsonLd, TOpenGraph, TWebManifest #1405) renders:

    • the manifest link (CrossOrigin);
    • theme-color, with ThemeColorDark for the dark scheme;
    • application-name and mobile-web-app-capable;
    • the iOS title, status bar style, and touch icon tags.

    With an empty Href it links the page's worker manifest and takes its theme color and short name.

  • TWebAppManifest holds the manifest members as properties, plus a JSON File and Members.

  • Prado.SharedConnection (package sharedconnection) is transport-agnostic.

    • A Web Lock elects one tab per key to hold the connection, and a BroadcastChannel passes its messages to the other tabs.
    • The holder hands over on close, pagehide, and freeze, and the next tab resumes from the last message ID.
    • A tab that misses two heartbeats steals the lock.
    • Without Web Locks or BroadcastChannel, each tab holds its own connection.
    • subscription.send(data) works from any tab. A non-holder posts the data to the holder, which sends it through the transport and confirms. Unconfirmed sends survive a handover (at least once), and closing rejects them.
    • A transport is any open(resumeId, emit) function returning {close()}, plus send(data) for one that sends. A WebSocket transport, such as belisoful/prado-websocket's prado.pubsub.v1 client, plugs in through this seam; the framework carries none.
    • eventSource() is the built-in SSE transport and uses Server push: TServerEventService and TServerEventTriggeredCallback (#1408) #1435's lastEventId parameter. TServerEventTriggeredCallback.SharedConnection comes with the Server push: TServerEventService and TServerEventTriggeredCallback (#1408) #1435 rework.
  • Small additions: TMetaTag.Media, TMediaType::MANIFEST_JSON (.webmanifest), and THttpHeaderName ServiceWorkerAllowed, ServiceWorkerNavigationPreload, and ClearSiteData.

Differences from the issue text

  • ClearSiteDataOnLogout takes a list of Clear-Site-Data types instead of a fixed "cache". The cache type clears only the HTTP cache; clearing the workers' Cache Storage takes storage.
  • The registration renders in place on pages without a form, as described above.

Tests

  • Unit: module, service, script, definition, manifest, TServiceWorker, TWebManifest, plus additions to the TMetaTag, TMediaType, THttpHeaderName, TPage, and TPageService tests. The full unit suite passes with XDEBUG_MODE=off. With local develop-mode Xdebug, TComponentBehaviorTest (2) and TTarFileExtractorUrlTest LZMA (2) fail, with or without this branch.
  • Vitest:
    • tests/js/serviceworker/ runs the runtime, strategies, and removal script as the service renders them, against a fake worker scope, and tests the page client.
    • tests/js/sharedconnection/ simulates several tabs with fake Web Locks and BroadcastChannel, including sends across a handover.
    • The rest of the suite passes except callbackrequest.test.js "disabled fieldsets and options", which also fails on master locally.
  • Playwright, in the new tests/harness/service-worker app, which uses path URLs so the admin worker owns index.php/admin/:
    • Chromium: registration, manifest, messages, the offline page, uncached callbacks, update through activate(), removal, and the admin worker keeping its caches through a default update.
    • Chromium, Firefox, and WebKit: two tabs share one stream and hand it over without a gap.
  • php-cs-fixer, phpstan, and eslint are clean.

@belisoful
belisoful force-pushed the claude/prado-service-worker-cbd00a branch from 5348a04 to 39c8eb2 Compare November 7, 2026 18:29
@belisoful
belisoful force-pushed the claude/prado-service-worker-cbd00a branch 3 times, most recently from 238501f to a343516 Compare November 28, 2026 07:39
@belisoful
belisoful force-pushed the claude/prado-service-worker-cbd00a branch from a343516 to 64b020d Compare November 29, 2026 08:54
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Service worker and shared server event connections: TServiceWorkerModule, TServiceWorkerService, Prado.ServiceWorker

1 participant