fix(service-worker): several misc fixes for corner cases
This commit fixes several issues discovered through use in real apps. * The sha1() function operated on text content, causing issues for binary-format files. A sha1Binary() function which operates on unparsed data now avoids any encoding issues. * The characters '?' and '+' were not escaped in Glob-to-regex conversion previously, but are now. * URLs from the browser contain the full origin, but were checked against the table of hashes from the manifest which only has the path for URLs from the same origin. Now the origin is checked and URLs are relativized to the domain root before comparison if appropriate. * ngsw: prefix was missing from data groups, is now added. * Occasionally servers will return a redirected response for an asset, and caching it could cause errors for navigation requests. The SW now handles this by detecting such responses and following the redirect manually, to avoid caching a redirected response. * The request for known assets is now created from scratch from the URL before fetching from the network, in order to sanitize it and avoid carrying any special modes or headers that might result in opaque responses. * Debugging log for troubleshooting. * Avoid creating errors by returning 504 responses on error. * Fix bug where idle queue doesn't run in some circumstances. * Add tests for the above.
This commit is contained in:
@ -25,7 +25,7 @@ type ClientAssignments = {
|
||||
[id: string]: ManifestHash
|
||||
};
|
||||
|
||||
const SYNC_THRESHOLD = 5000;
|
||||
const IDLE_THRESHOLD = 5000;
|
||||
|
||||
const SUPPORTED_CONFIG_VERSION = 1;
|
||||
|
||||
@ -42,36 +42,33 @@ enum DriverReadyState {
|
||||
// The SW is operating in a normal mode, responding to all traffic.
|
||||
NORMAL,
|
||||
|
||||
// The SW does not have a clean installation of the latest version of the app, but older cached
|
||||
// versions
|
||||
// are safe to use so long as they don't try to fetch new dependencies. This is a degraded state.
|
||||
// The SW does not have a clean installation of the latest version of the app, but older
|
||||
// cached versions are safe to use so long as they don't try to fetch new dependencies.
|
||||
// This is a degraded state.
|
||||
EXISTING_CLIENTS_ONLY,
|
||||
|
||||
// The SW has decided that caching is completely unreliable, and is forgoing request handling
|
||||
// until the
|
||||
// next restart.
|
||||
// The SW has decided that caching is completely unreliable, and is forgoing request
|
||||
// handling until the next restart.
|
||||
SAFE_MODE,
|
||||
}
|
||||
|
||||
export class Driver implements Debuggable, UpdateSource {
|
||||
/**
|
||||
* Tracks the current readiness condition under which the SW is operating. This controls whether
|
||||
* the SW
|
||||
* attempts to respond to some or all requests.
|
||||
* Tracks the current readiness condition under which the SW is operating. This controls
|
||||
* whether the SW attempts to respond to some or all requests.
|
||||
*/
|
||||
private state: DriverReadyState = DriverReadyState.NORMAL;
|
||||
private stateMessage: string = '(nominal)';
|
||||
|
||||
/**
|
||||
* Tracks whether the SW is in an initialized state or not. Before initialization, it's not legal
|
||||
* to
|
||||
* respond to requests.
|
||||
* Tracks whether the SW is in an initialized state or not. Before initialization,
|
||||
* it's not legal to respond to requests.
|
||||
*/
|
||||
initialized: Promise<void>|null = null;
|
||||
|
||||
/**
|
||||
* Maps client IDs to the manifest hash of the application version being used to serve them. If a
|
||||
* client ID is not present here, it has not yet been assigned a version.
|
||||
* Maps client IDs to the manifest hash of the application version being used to serve
|
||||
* them. If a client ID is not present here, it has not yet been assigned a version.
|
||||
*
|
||||
* If a ManifestHash appears here, it is also present in the `versions` map below.
|
||||
*/
|
||||
@ -92,8 +89,8 @@ export class Driver implements Debuggable, UpdateSource {
|
||||
private lastUpdateCheck: number|null = null;
|
||||
|
||||
/**
|
||||
* A scheduler which manages a queue of tasks that need to be executed when the SW is not doing
|
||||
* any other work (not processing any other requests).
|
||||
* A scheduler which manages a queue of tasks that need to be executed when the SW is
|
||||
* not doing any other work (not processing any other requests).
|
||||
*/
|
||||
idle: IdleScheduler;
|
||||
|
||||
@ -101,75 +98,132 @@ export class Driver implements Debuggable, UpdateSource {
|
||||
|
||||
constructor(
|
||||
private scope: ServiceWorkerGlobalScope, private adapter: Adapter, private db: Database) {
|
||||
// Listen to fetch events.
|
||||
this.scope.addEventListener(
|
||||
'install', (event) => { event !.waitUntil(this.scope.skipWaiting()); });
|
||||
// Set up all the event handlers that the SW needs.
|
||||
|
||||
// The install event is triggered when the service worker is first installed.
|
||||
this.scope.addEventListener('install', (event) => {
|
||||
// SW code updates are separate from application updates, so code updates are
|
||||
// almost as straightforward as restarting the SW. Because of this, it's always
|
||||
// safe to skip waiting until application tabs are closed, and activate the new
|
||||
// SW version immediately.
|
||||
event !.waitUntil(this.scope.skipWaiting());
|
||||
});
|
||||
|
||||
// The activate event is triggered when this version of the service worker is
|
||||
// first activated.
|
||||
this.scope.addEventListener('activate', (event) => {
|
||||
// As above, it's safe to take over from existing clients immediately, since
|
||||
// the new SW version will continue to serve the old application.
|
||||
event !.waitUntil(this.scope.clients.claim());
|
||||
|
||||
// Rather than wait for the first fetch event, which may not arrive until
|
||||
// the next time the application is loaded, the SW takes advantage of the
|
||||
// activation event to schedule initialization. However, if this were run
|
||||
// in the context of the 'activate' event, waitUntil() here would cause fetch
|
||||
// events to block until initialization completed. Thus, the SW does a
|
||||
// postMessage() to itself, to schedule a new event loop iteration with an
|
||||
// entirely separate event context. The SW will be kept alive by waitUntil()
|
||||
// within that separate context while initialization proceeds, while at the
|
||||
// same time the activation event is allowed to resolve and traffic starts
|
||||
// being served.
|
||||
if (this.scope.registration.active !== null) {
|
||||
this.scope.registration.active.postMessage({action: 'INITIALIZE'});
|
||||
}
|
||||
});
|
||||
|
||||
// Handle the fetch, message, and push events.
|
||||
this.scope.addEventListener('fetch', (event) => this.onFetch(event !));
|
||||
this.scope.addEventListener('message', (event) => this.onMessage(event !));
|
||||
this.scope.addEventListener('push', (event) => this.onPush(event !));
|
||||
|
||||
this.idle = new IdleScheduler(this.adapter, SYNC_THRESHOLD);
|
||||
// The debugger generates debug pages in response to debugging requests.
|
||||
this.debugger = new DebugHandler(this, this.adapter);
|
||||
|
||||
// The IdleScheduler will execute idle tasks after a given delay.
|
||||
this.idle = new IdleScheduler(this.adapter, IDLE_THRESHOLD, this.debugger);
|
||||
}
|
||||
|
||||
/**
|
||||
* The handler for fetch events.
|
||||
*
|
||||
* This is the transition point between the synchronous event handler and the
|
||||
* asynchronous execution that eventually resolves for respondWith() and waitUntil().
|
||||
*/
|
||||
private onFetch(event: FetchEvent): void {
|
||||
// The only thing that is served unconditionally is the debug page.
|
||||
if (this.adapter.getPath(event.request.url) === '/ngsw/state') {
|
||||
if (this.adapter.parseUrl(event.request.url, this.scope.registration.scope).path ===
|
||||
'/ngsw/state') {
|
||||
// Allow the debugger to handle the request, but don't affect SW state in any
|
||||
// other way.
|
||||
event.respondWith(this.debugger.handleFetch(event.request));
|
||||
return;
|
||||
}
|
||||
|
||||
// If the SW is in a broken state where it's not safe to handle requests at all, returning
|
||||
// causes the request to fall back on the network. This is preferred over
|
||||
// `respondWith(fetch(req))` because the latter still shows in DevTools that the request
|
||||
// was handled by the SW.
|
||||
// If the SW is in a broken state where it's not safe to handle requests at all,
|
||||
// returning causes the request to fall back on the network. This is preferred over
|
||||
// `respondWith(fetch(req))` because the latter still shows in DevTools that the
|
||||
// request was handled by the SW.
|
||||
// TODO: try to handle DriverReadyState.EXISTING_CLIENTS_ONLY here.
|
||||
if (this.state === DriverReadyState.SAFE_MODE) {
|
||||
// Even though the worker is in safe mode, idle tasks still need to happen so things
|
||||
// like update checks, etc. can take place.
|
||||
// Even though the worker is in safe mode, idle tasks still need to happen so
|
||||
// things like update checks, etc. can take place.
|
||||
event.waitUntil(this.idle.trigger());
|
||||
return;
|
||||
}
|
||||
|
||||
// Past this point, the SW commits to handling the request itself. This could still fail (and
|
||||
// result in `state` being set to `SAFE_MODE`), but even in that case the SW will still deliver
|
||||
// a response.
|
||||
// Past this point, the SW commits to handling the request itself. This could still
|
||||
// fail (and result in `state` being set to `SAFE_MODE`), but even in that case the
|
||||
// SW will still deliver a response.
|
||||
event.respondWith(this.handleFetch(event));
|
||||
}
|
||||
|
||||
/**
|
||||
* The handler for message events.
|
||||
*/
|
||||
private onMessage(event: ExtendableMessageEvent): void {
|
||||
// Ignore message events when the SW is in safe mode, for now.
|
||||
if (this.state === DriverReadyState.SAFE_MODE) {
|
||||
return;
|
||||
}
|
||||
|
||||
// If the message doesn't have the expected signature, ignore it.
|
||||
const data = event.data;
|
||||
if (!data || !data.action) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Initialization is the only event which is sent directly from the SW to itself,
|
||||
// and thus `event.source` is not a Client. Handle it here, before the check
|
||||
// for Client sources.
|
||||
if (data.action === 'INITIALIZE' && this.initialized === null) {
|
||||
// Initialize the SW.
|
||||
this.initialized = this.initialize();
|
||||
event.waitUntil(this.initialized);
|
||||
event.waitUntil(this.idle.trigger());
|
||||
return;
|
||||
|
||||
// Wait until initialization is properly scheduled, then trigger idle
|
||||
// events to allow it to complete (assuming the SW is idle).
|
||||
event.waitUntil((async() => {
|
||||
await this.initialized;
|
||||
await this.idle.trigger();
|
||||
})());
|
||||
}
|
||||
|
||||
// Only messages from true clients are accepted past this point (this is essentially
|
||||
// a typecast).
|
||||
if (!this.adapter.isClient(event.source)) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Handle the message and keep the SW alive until it's handled.
|
||||
event.waitUntil(this.handleMessage(data, event.source));
|
||||
}
|
||||
|
||||
private onPush(msg: PushEvent): void {
|
||||
// Push notifications without data have no effect.
|
||||
if (!msg.data) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Handle the push and keep the SW alive until it's handled.
|
||||
msg.waitUntil(this.handlePush(msg.data));
|
||||
}
|
||||
|
||||
@ -212,7 +266,8 @@ export class Driver implements Debuggable, UpdateSource {
|
||||
}
|
||||
|
||||
async updateClient(client: Client): Promise<void> {
|
||||
// Figure out which version the client is on. If it's not on the latest, it needs to be moved.
|
||||
// Figure out which version the client is on. If it's not on the latest,
|
||||
// it needs to be moved.
|
||||
const existing = this.clientVersionMap.get(client.id);
|
||||
if (existing === this.latestHash) {
|
||||
// Nothing to do, this client is already on the latest version.
|
||||
@ -222,14 +277,14 @@ export class Driver implements Debuggable, UpdateSource {
|
||||
// Switch the client over.
|
||||
let previous: Object|undefined = undefined;
|
||||
|
||||
// Look up the application data associated with the existing version. If there isn't any,
|
||||
// fall back on using the hash.
|
||||
// Look up the application data associated with the existing version. If there
|
||||
// isn't any, fall back on using the hash.
|
||||
if (existing !== undefined) {
|
||||
const existingVersion = this.versions.get(existing) !;
|
||||
previous = this.mergeHashWithAppData(existingVersion.manifest, existing);
|
||||
}
|
||||
|
||||
// Set the current version used by the client, and
|
||||
// Set the current version used by the client, and sync the mapping to disk.
|
||||
this.clientVersionMap.set(client.id, this.latestHash !);
|
||||
await this.sync();
|
||||
|
||||
@ -269,7 +324,7 @@ export class Driver implements Debuggable, UpdateSource {
|
||||
|
||||
// Since the SW is already committed to responding to the currently active request,
|
||||
// respond with a network fetch.
|
||||
return this.scope.fetch(event.request);
|
||||
return this.safeFetch(event.request);
|
||||
}
|
||||
|
||||
// Decide which version of the app to use to serve this request. This is asynchronous as in
|
||||
@ -279,7 +334,7 @@ export class Driver implements Debuggable, UpdateSource {
|
||||
// Bail out
|
||||
if (appVersion === null) {
|
||||
event.waitUntil(this.idle.trigger());
|
||||
return this.scope.fetch(event.request);
|
||||
return this.safeFetch(event.request);
|
||||
}
|
||||
|
||||
// Handle the request. First try the AppVersion. If that doesn't work, fall back on the network.
|
||||
@ -289,7 +344,7 @@ export class Driver implements Debuggable, UpdateSource {
|
||||
// request. In that case, just fall back on the network.
|
||||
if (res === null) {
|
||||
event.waitUntil(this.idle.trigger());
|
||||
return this.scope.fetch(event.request);
|
||||
return this.safeFetch(event.request);
|
||||
}
|
||||
|
||||
// Trigger the idle scheduling system. The Promise returned by trigger() will resolve after
|
||||
@ -306,23 +361,21 @@ export class Driver implements Debuggable, UpdateSource {
|
||||
* Attempt to quickly reach a state where it's safe to serve responses.
|
||||
*/
|
||||
private async initialize(): Promise<void> {
|
||||
// On initialization, all of the serialized state is read out of the 'control' table. This
|
||||
// includes:
|
||||
// On initialization, all of the serialized state is read out of the 'control'
|
||||
// table. This includes:
|
||||
// - map of hashes to manifests of currently loaded application versions
|
||||
// - map of client IDs to their pinned versions
|
||||
// - record of the most recently fetched manifest hash
|
||||
//
|
||||
// If these values don't exist in the DB, then this is the either the first time the SW has run
|
||||
// or
|
||||
// the DB state has been wiped or is inconsistent. In that case, load a fresh copy of the
|
||||
// manifest
|
||||
// and reset the state from scratch.
|
||||
// If these values don't exist in the DB, then this is the either the first time
|
||||
// the SW has run or the DB state has been wiped or is inconsistent. In that case,
|
||||
// load a fresh copy of the manifest and reset the state from scratch.
|
||||
|
||||
// Open up the DB table.
|
||||
const table = await this.db.open('control');
|
||||
|
||||
// Attempt to load the needed state from the DB. If this fails, the catch {} block will populate
|
||||
// these variables with freshly constructed values.
|
||||
// Attempt to load the needed state from the DB. If this fails, the catch {} block
|
||||
// will populate these variables with freshly constructed values.
|
||||
let manifests: ManifestMap, assignments: ClientAssignments, latest: LatestEntry;
|
||||
try {
|
||||
// Read them from the DB simultaneously.
|
||||
@ -332,16 +385,20 @@ export class Driver implements Debuggable, UpdateSource {
|
||||
table.read<LatestEntry>('latest'),
|
||||
]);
|
||||
|
||||
// Successfully loaded from saved state. This implies a manifest exists, so the update check
|
||||
// needs to happen in the background.
|
||||
// Successfully loaded from saved state. This implies a manifest exists, so
|
||||
// the update check needs to happen in the background.
|
||||
this.idle.schedule('init post-load (update, cleanup)', async() => {
|
||||
await this.checkForUpdate();
|
||||
await this.cleanupCaches();
|
||||
try {
|
||||
await this.cleanupCaches();
|
||||
} catch (err) {
|
||||
// Nothing to do - cleanup failed. Just log it.
|
||||
this.debugger.log(err, 'cleanupCaches @ init post-load');
|
||||
}
|
||||
});
|
||||
} catch (_) {
|
||||
// Something went wrong. Try to start over by fetching a new manifest from the server and
|
||||
// building
|
||||
// up an empty initial state.
|
||||
// Something went wrong. Try to start over by fetching a new manifest from the
|
||||
// server and building up an empty initial state.
|
||||
const manifest = await this.fetchLatestManifest();
|
||||
const hash = hashManifest(manifest);
|
||||
manifests = {};
|
||||
@ -357,49 +414,36 @@ export class Driver implements Debuggable, UpdateSource {
|
||||
]);
|
||||
}
|
||||
|
||||
// At this point, either the state has been loaded successfully, or fresh state with a new copy
|
||||
// of
|
||||
// the manifest has been produced. At this point, the `Driver` can have its internals hydrated
|
||||
// from
|
||||
// the state.
|
||||
// At this point, either the state has been loaded successfully, or fresh state
|
||||
// with a new copy of the manifest has been produced. At this point, the `Driver`
|
||||
// can have its internals hydrated from the state.
|
||||
|
||||
// Initialize the `versions` map by setting each hash to a new `AppVersion` instance for that
|
||||
// manifest.
|
||||
// Initialize the `versions` map by setting each hash to a new `AppVersion` instance
|
||||
// for that manifest.
|
||||
Object.keys(manifests).forEach((hash: ManifestHash) => {
|
||||
const manifest = manifests[hash];
|
||||
|
||||
// If the manifest is newly initialized, an AppVersion may have already been created for it.
|
||||
// If the manifest is newly initialized, an AppVersion may have already been
|
||||
// created for it.
|
||||
if (!this.versions.has(hash)) {
|
||||
this.versions.set(
|
||||
hash, new AppVersion(this.scope, this.adapter, this.db, this.idle, manifest, hash));
|
||||
}
|
||||
});
|
||||
|
||||
// Wait for the scheduling of initialization of all versions in the manifest. Ordinarily this
|
||||
// just
|
||||
// schedules the initializations to happen during the next idle period, but in development mode
|
||||
// this might actually wait for the full initialization.
|
||||
await Promise.all(Object.keys(manifests).map(async(hash: ManifestHash) => {
|
||||
try {
|
||||
// Attempt to schedule or initialize this version. If this operation is successful, then
|
||||
// initialization either succeeded or was scheduled. If it fails, then full initialization
|
||||
// was attempted and failed.
|
||||
await this.scheduleInitialization(this.versions.get(hash) !);
|
||||
} catch (err) {
|
||||
return false;
|
||||
}
|
||||
}));
|
||||
|
||||
// Map each client ID to its associated hash. Along the way, verify that the hash is still valid
|
||||
// for that clinet ID. It should not be possible for a client to still be associated with a hash
|
||||
// that was since removed from the state.
|
||||
// Map each client ID to its associated hash. Along the way, verify that the hash
|
||||
// is still valid for that client ID. It should not be possible for a client to
|
||||
// still be associated with a hash that was since removed from the state.
|
||||
Object.keys(assignments).forEach((clientId: ClientId) => {
|
||||
const hash = assignments[clientId];
|
||||
if (!this.versions.has(hash)) {
|
||||
throw new Error(
|
||||
`Invariant violated (initialize): no manifest known for hash ${hash} active for client ${clientId}`);
|
||||
if (this.versions.has(hash)) {
|
||||
this.clientVersionMap.set(clientId, hash);
|
||||
} else {
|
||||
this.clientVersionMap.set(clientId, latest.latest);
|
||||
this.debugger.log(
|
||||
`Unknown version ${hash} mapped for client ${clientId}, using latest instead`,
|
||||
`initialize: map assignments`);
|
||||
}
|
||||
this.clientVersionMap.set(clientId, hash);
|
||||
});
|
||||
|
||||
// Set the latest version.
|
||||
@ -410,6 +454,26 @@ export class Driver implements Debuggable, UpdateSource {
|
||||
throw new Error(
|
||||
`Invariant violated (initialize): latest hash ${latest.latest} has no known manifest`);
|
||||
}
|
||||
|
||||
|
||||
|
||||
// Finally, wait for the scheduling of initialization of all versions in the
|
||||
// manifest. Ordinarily this just schedules the initializations to happen during
|
||||
// the next idle period, but in development mode this might actually wait for the
|
||||
// full initialization.
|
||||
// If any of these initializations fail, versionFailed() will be called either
|
||||
// synchronously or asynchronously to handle the failure and re-map clients.
|
||||
await Promise.all(Object.keys(manifests).map(async(hash: ManifestHash) => {
|
||||
try {
|
||||
// Attempt to schedule or initialize this version. If this operation is
|
||||
// successful, then initialization either succeeded or was scheduled. If
|
||||
// it fails, then full initialization was attempted and failed.
|
||||
await this.scheduleInitialization(this.versions.get(hash) !);
|
||||
} catch (err) {
|
||||
this.debugger.log(err, `initialize: schedule init of ${hash}`);
|
||||
return false;
|
||||
}
|
||||
}));
|
||||
}
|
||||
|
||||
private lookupVersionByHash(hash: ManifestHash, debugName: string = 'lookupVersionByHash'):
|
||||
@ -426,8 +490,8 @@ export class Driver implements Debuggable, UpdateSource {
|
||||
* Decide which version of the manifest to use for the event.
|
||||
*/
|
||||
private async assignVersion(event: FetchEvent): Promise<AppVersion|null> {
|
||||
// First, check whether the event has a client ID. If it does, the version may already be
|
||||
// associated.
|
||||
// First, check whether the event has a client ID. If it does, the version may
|
||||
// already be associated.
|
||||
const clientId = event.clientId;
|
||||
if (clientId !== null) {
|
||||
// Check if there is an assigned client id.
|
||||
@ -436,10 +500,10 @@ export class Driver implements Debuggable, UpdateSource {
|
||||
let hash = this.clientVersionMap.get(clientId) !;
|
||||
|
||||
// Ordinarily, this client would be served from its assigned version. But, if this
|
||||
// request is a navigation request, this client can be updated to the latest version
|
||||
// immediately.
|
||||
// request is a navigation request, this client can be updated to the latest
|
||||
// version immediately.
|
||||
if (this.state === DriverReadyState.NORMAL && hash !== this.latestHash &&
|
||||
isNavigationRequest(event.request, this.adapter)) {
|
||||
isNavigationRequest(event.request, this.scope.registration.scope, this.adapter)) {
|
||||
// Update this client to the latest version immediately.
|
||||
if (this.latestHash === null) {
|
||||
throw new Error(`Invariant violated (assignVersion): latestHash was null`);
|
||||
@ -454,14 +518,16 @@ export class Driver implements Debuggable, UpdateSource {
|
||||
// TODO: make sure the version is valid.
|
||||
return this.lookupVersionByHash(hash, 'assignVersion');
|
||||
} else {
|
||||
// This is the first time this client ID has been seen. Whether the SW is in a state
|
||||
// to handle new clients depends on the current readiness state, so check that first.
|
||||
// This is the first time this client ID has been seen. Whether the SW is in a
|
||||
// state to handle new clients depends on the current readiness state, so check
|
||||
// that first.
|
||||
if (this.state !== DriverReadyState.NORMAL) {
|
||||
// It's not safe to serve new clients in the current state. It's possible that this
|
||||
// is an existing client which has not been mapped yet (see below) but even if that
|
||||
// is the case, it's invalid to make an assignment to a known invalid version, even
|
||||
// if that assignment was previously implicit. Return undefined here to let the
|
||||
// caller know that no assignment is possible at this time.
|
||||
// It's not safe to serve new clients in the current state. It's possible that
|
||||
// this is an existing client which has not been mapped yet (see below) but
|
||||
// even if that is the case, it's invalid to make an assignment to a known
|
||||
// invalid version, even if that assignment was previously implicit. Return
|
||||
// undefined here to let the caller know that no assignment is possible at
|
||||
// this time.
|
||||
return null;
|
||||
}
|
||||
|
||||
@ -514,7 +580,8 @@ export class Driver implements Debuggable, UpdateSource {
|
||||
* Retrieve a copy of the latest manifest from the server.
|
||||
*/
|
||||
private async fetchLatestManifest(): Promise<Manifest> {
|
||||
const res = await this.scope.fetch('/ngsw.json?ngsw-cache-bust=' + Math.random());
|
||||
const res = await this.safeFetch(
|
||||
this.adapter.newRequest('/ngsw.json?ngsw-cache-bust=' + Math.random()));
|
||||
if (!res.ok) {
|
||||
if (res.status === 404) {
|
||||
await this.deleteAllCaches();
|
||||
@ -547,7 +614,8 @@ export class Driver implements Debuggable, UpdateSource {
|
||||
try {
|
||||
await appVersion.initializeFully();
|
||||
} catch (err) {
|
||||
this.versionFailed(appVersion, err);
|
||||
this.debugger.log(err, `initializeFully for ${appVersion.manifestHash}`);
|
||||
await this.versionFailed(appVersion, err);
|
||||
}
|
||||
};
|
||||
// TODO: better logic for detecting localhost.
|
||||
@ -557,7 +625,7 @@ export class Driver implements Debuggable, UpdateSource {
|
||||
this.idle.schedule(`initialization(${appVersion.manifestHash})`, initialize);
|
||||
}
|
||||
|
||||
private versionFailed(appVersion: AppVersion, err: Error): void {
|
||||
private async versionFailed(appVersion: AppVersion, err: Error): Promise<void> {
|
||||
// This particular AppVersion is broken. First, find the manifest hash.
|
||||
const broken =
|
||||
Array.from(this.versions.entries()).find(([hash, version]) => version === appVersion);
|
||||
@ -573,8 +641,8 @@ export class Driver implements Debuggable, UpdateSource {
|
||||
// If so, the SW cannot accept new clients, but can continue to service old ones.
|
||||
if (this.latestHash === brokenHash) {
|
||||
// The latest manifest is broken. This means that new clients are at the mercy of the
|
||||
// network, but caches continue to be valid for previous versions. This is unfortunate
|
||||
// but unavoidable.
|
||||
// network, but caches continue to be valid for previous versions. This is
|
||||
// unfortunate but unavoidable.
|
||||
this.state = DriverReadyState.EXISTING_CLIENTS_ONLY;
|
||||
this.stateMessage = `Degraded due to failed initialization: ${errorToString(err)}`;
|
||||
|
||||
@ -582,15 +650,16 @@ export class Driver implements Debuggable, UpdateSource {
|
||||
Array.from(this.clientVersionMap.keys())
|
||||
.forEach(clientId => this.clientVersionMap.delete(clientId));
|
||||
} else {
|
||||
// The current version is viable, but this older version isn't. The only possible remedy
|
||||
// is to stop serving the older version and go to the network. Figure out which clients
|
||||
// are affected and put them on the latest.
|
||||
// The current version is viable, but this older version isn't. The only
|
||||
// possible remedy is to stop serving the older version and go to the network.
|
||||
// Figure out which clients are affected and put them on the latest.
|
||||
const affectedClients =
|
||||
Array.from(this.clientVersionMap.keys())
|
||||
.filter(clientId => this.clientVersionMap.get(clientId) ! === brokenHash);
|
||||
// Push the affected clients onto the latest version.
|
||||
affectedClients.forEach(clientId => this.clientVersionMap.set(clientId, this.latestHash !));
|
||||
}
|
||||
await this.sync();
|
||||
}
|
||||
|
||||
private async setupUpdate(manifest: Manifest, hash: string): Promise<void> {
|
||||
@ -599,9 +668,9 @@ export class Driver implements Debuggable, UpdateSource {
|
||||
// Try to determine a version that's safe to update from.
|
||||
let updateFrom: AppVersion|undefined = undefined;
|
||||
|
||||
// It's always safe to update from a version, even a broken one, as it will still only have
|
||||
// valid resources cached. If there is no latest version, though, this update will have to
|
||||
// install as a fresh version.
|
||||
// It's always safe to update from a version, even a broken one, as it will still
|
||||
// only have valid resources cached. If there is no latest version, though, this
|
||||
// update will have to install as a fresh version.
|
||||
if (this.latestHash !== null) {
|
||||
updateFrom = this.versions.get(this.latestHash);
|
||||
}
|
||||
@ -614,8 +683,8 @@ export class Driver implements Debuggable, UpdateSource {
|
||||
`Invalid config version: expected ${SUPPORTED_CONFIG_VERSION}, got ${manifest.configVersion}.`);
|
||||
}
|
||||
|
||||
// Cause the new version to become fully initialized. If this fails, then the version will
|
||||
// not be available for use.
|
||||
// Cause the new version to become fully initialized. If this fails, then the
|
||||
// version will not be available for use.
|
||||
await newVersion.initializeFully(this);
|
||||
|
||||
// Install this as an active version of the app.
|
||||
@ -636,6 +705,7 @@ export class Driver implements Debuggable, UpdateSource {
|
||||
if (this.versions.has(hash)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
await this.setupUpdate(manifest, hash);
|
||||
|
||||
return true;
|
||||
@ -674,24 +744,23 @@ export class Driver implements Debuggable, UpdateSource {
|
||||
}
|
||||
|
||||
async cleanupCaches(): Promise<void> {
|
||||
// Make sure internal state has been initialized before attempting to clean up caches.
|
||||
await this.initialized;
|
||||
|
||||
// Query for all currently active clients, and list the client ids. This may skip some
|
||||
// clients in the browser back-forward cache, but not much can be done about that.
|
||||
// Query for all currently active clients, and list the client ids. This may skip
|
||||
// some clients in the browser back-forward cache, but not much can be done about
|
||||
// that.
|
||||
const activeClients: ClientId[] =
|
||||
(await this.scope.clients.matchAll()).map(client => client.id);
|
||||
|
||||
// A simple list of client ids that the SW has kept track of. Subtracting activeClients
|
||||
// from this list will result in the set of client ids which are being tracked but are no
|
||||
// longer used in the browser, and thus can be cleaned up.
|
||||
// A simple list of client ids that the SW has kept track of. Subtracting
|
||||
// activeClients from this list will result in the set of client ids which are
|
||||
// being tracked but are no longer used in the browser, and thus can be cleaned up.
|
||||
const knownClients: ClientId[] = Array.from(this.clientVersionMap.keys());
|
||||
|
||||
// Remove clients in the clientVersionMap that are no longer active.
|
||||
knownClients.filter(id => activeClients.indexOf(id) === -1)
|
||||
.forEach(id => this.clientVersionMap.delete(id));
|
||||
|
||||
// Next, determine the set of versions which are still used. All others can be removed.
|
||||
// Next, determine the set of versions which are still used. All others can be
|
||||
// removed.
|
||||
const usedVersions = new Set<string>();
|
||||
this.clientVersionMap.forEach((version, _) => usedVersions.add(version));
|
||||
|
||||
@ -705,8 +774,8 @@ export class Driver implements Debuggable, UpdateSource {
|
||||
// Wait for the other cleanup operations to complete.
|
||||
await previous;
|
||||
|
||||
// Try to get past the failure of one particular version to clean up (this shouldn't happen,
|
||||
// but handle it just in case).
|
||||
// Try to get past the failure of one particular version to clean up (this
|
||||
// shouldn't happen, but handle it just in case).
|
||||
try {
|
||||
// Get ahold of the AppVersion for this particular hash.
|
||||
const instance = this.versions.get(version) !;
|
||||
@ -716,9 +785,10 @@ export class Driver implements Debuggable, UpdateSource {
|
||||
|
||||
// Clean it up.
|
||||
await instance.cleanup();
|
||||
} catch (e) {
|
||||
// Oh well? Not much that can be done here. These caches will be removed when the SW revs
|
||||
// its format version, which happens from time to time.
|
||||
} catch (err) {
|
||||
// Oh well? Not much that can be done here. These caches will be removed when
|
||||
// the SW revs its format version, which happens from time to time.
|
||||
this.debugger.log(err, `cleanupCaches - cleanup ${version}`);
|
||||
}
|
||||
}, Promise.resolve());
|
||||
|
||||
@ -847,6 +917,18 @@ export class Driver implements Debuggable, UpdateSource {
|
||||
lastRun: this.idle.lastRun,
|
||||
};
|
||||
}
|
||||
|
||||
async safeFetch(req: Request): Promise<Response> {
|
||||
try {
|
||||
return await this.scope.fetch(req);
|
||||
} catch (err) {
|
||||
this.debugger.log(err, `Driver.fetch(${req.url})`);
|
||||
return this.adapter.newResponse(null, {
|
||||
status: 504,
|
||||
statusText: 'Gateway Timeout',
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function errorToString(error: any): string {
|
||||
|
Reference in New Issue
Block a user