Skip to content

Commit 4dff1de

Browse files
committed
fix(service-worker): do not blow up when caches are unwritable
In some cases, example when the user clears the caches in DevTools but the SW remains active on another tab and keeps references to the deleted caches, trying to write to the cache throws errors (e.g. `Entry was not found`). When this happens, the SW can no longer work correctly and should enter a degraded mode allowing requests to be served from the network. Possibly related: - GoogleChrome/workbox#792 - https://bugs.chromium.org/p/chromium/issues/detail?id=639034 This commits remedies this situation, by ensuring the SW can enter the degraded `EXISTING_CLIENTS_ONLY` mode and forward requests to the network.
1 parent 41ac58a commit 4dff1de

5 files changed

Lines changed: 85 additions & 29 deletions

File tree

‎packages/service-worker/worker/src/assets.ts‎

Lines changed: 25 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
import {Adapter, Context} from './adapter';
1010
import {CacheState, UpdateCacheStatus, UpdateSource, UrlMetadata} from './api';
1111
import {Database, Table} from './database';
12-
import {SwCriticalError} from './error';
12+
import {SwCriticalError, errorToString} from './error';
1313
import {IdleScheduler} from './idle';
1414
import {AssetGroupConfig} from './manifest';
1515
import {sha1Binary} from './sha1';
@@ -317,24 +317,33 @@ export abstract class AssetGroup {
317317
`Response not Ok (fetchAndCacheOnce): request for ${req.url} returned response ${res.status} ${res.statusText}`);
318318
}
319319

320-
// This response is safe to cache (as long as it's cloned). Wait until the cache operation
321-
// is complete.
322-
const cache = await this.scope.caches.open(`${this.prefix}:${this.config.name}:cache`);
323-
await cache.put(req, res.clone());
324-
325-
// If the request is not hashed, update its metadata, especially the timestamp. This is needed
326-
// for future determination of whether this cached response is stale or not.
327-
if (!this.hashes.has(req.url)) {
328-
// Metadata is tracked for requests that are unhashed.
329-
const meta: UrlMetadata = {ts: this.adapter.time, used};
330-
const metaTable = await this.metadata;
331-
await metaTable.write(req.url, meta);
332-
}
320+
try {
321+
// This response is safe to cache (as long as it's cloned). Wait until the cache operation
322+
// is complete.
323+
const cache = await this.scope.caches.open(`${this.prefix}:${this.config.name}:cache`);
324+
await cache.put(req, res.clone());
325+
326+
// If the request is not hashed, update its metadata, especially the timestamp. This is
327+
// needed for future determination of whether this cached response is stale or not.
328+
if (!this.hashes.has(req.url)) {
329+
// Metadata is tracked for requests that are unhashed.
330+
const meta: UrlMetadata = {ts: this.adapter.time, used};
331+
const metaTable = await this.metadata;
332+
await metaTable.write(req.url, meta);
333+
}
333334

334-
return res;
335+
return res;
336+
} catch (err) {
337+
// Among other cases, this can happen when the user clears all data through the DevTools,
338+
// but the SW is still running and serving another tab. In that case, trying to write to the
339+
// caches throws an `Entry was not found` error.
340+
// If this happens the SW can no longer work correctly. This situation is unrecoverable.
341+
throw new SwCriticalError(
342+
`Failed to update the caches for request to '${req.url}' (fetchAndCacheOnce): ${errorToString(err)}`);
343+
}
335344
} finally {
336345
// Finally, it can be removed from `inFlightRequests`. This might result in a double-remove
337-
// if some other chain was already making this request too, but that won't hurt anything.
346+
// if some other chain was already making this request too, but that won't hurt anything.
338347
this.inFlightRequests.delete(req.url);
339348
}
340349
}

‎packages/service-worker/worker/src/driver.ts‎

Lines changed: 12 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -6,12 +6,12 @@
66
* found in the LICENSE file at https://angular.io/license
77
*/
88

9-
import {Adapter, Context} from './adapter';
9+
import {Adapter} from './adapter';
1010
import {CacheState, DebugIdleState, DebugState, DebugVersion, Debuggable, UpdateCacheStatus, UpdateSource} from './api';
1111
import {AppVersion} from './app-version';
12-
import {Database, Table} from './database';
12+
import {Database} from './database';
1313
import {DebugHandler} from './debug';
14-
import {SwCriticalError} from './error';
14+
import {errorToString} from './error';
1515
import {IdleScheduler} from './idle';
1616
import {Manifest, ManifestHash, hashManifest} from './manifest';
1717
import {MsgAny, isMsgActivateUpdate, isMsgCheckForUpdates} from './msg';
@@ -709,7 +709,7 @@ export class Driver implements Debuggable, UpdateSource {
709709
// network, but caches continue to be valid for previous versions. This is
710710
// unfortunate but unavoidable.
711711
this.state = DriverReadyState.EXISTING_CLIENTS_ONLY;
712-
this.stateMessage = `Degraded due to failed initialization: ${errorToString(err)}`;
712+
this.stateMessage = `Degraded due to: ${errorToString(err)}`;
713713

714714
// Cancel the binding for these clients.
715715
Array.from(this.clientVersionMap.keys())
@@ -724,7 +724,14 @@ export class Driver implements Debuggable, UpdateSource {
724724
// Push the affected clients onto the latest version.
725725
affectedClients.forEach(clientId => this.clientVersionMap.set(clientId, this.latestHash !));
726726
}
727-
await this.sync();
727+
728+
try {
729+
await this.sync();
730+
} catch (err2) {
731+
// We are already in a bad state. No need to make things worse.
732+
// Just log the error and move on.
733+
this.debugger.log(err2, `Driver.versionFailed(${err.message || err})`);
734+
}
728735
}
729736

730737
private async setupUpdate(manifest: Manifest, hash: string): Promise<void> {
@@ -999,11 +1006,3 @@ export class Driver implements Debuggable, UpdateSource {
9991006
}
10001007
}
10011008
}
1002-
1003-
function errorToString(error: any): string {
1004-
if (error instanceof Error) {
1005-
return `${error.message}\n${error.stack}`;
1006-
} else {
1007-
return `${error}`;
1008-
}
1009-
}

‎packages/service-worker/worker/src/error.ts‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,3 +7,11 @@
77
*/
88

99
export class SwCriticalError extends Error { readonly isCritical: boolean = true; }
10+
11+
export function errorToString(error: any): string {
12+
if (error instanceof Error) {
13+
return `${error.message}\n${error.stack}`;
14+
} else {
15+
return `${error}`;
16+
}
17+
}

‎packages/service-worker/worker/test/happy_spec.ts‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import {CacheDatabase} from '../src/db-cache';
1111
import {Driver, DriverReadyState} from '../src/driver';
1212
import {Manifest} from '../src/manifest';
1313
import {sha1} from '../src/sha1';
14+
import {MockCache, clearAllCaches} from '../testing/cache';
1415
import {MockRequest} from '../testing/fetch';
1516
import {MockFileSystemBuilder, MockServerStateBuilder, tmpHashTableForFs} from '../testing/mock';
1617
import {SwTestHarness, SwTestHarnessBuilder} from '../testing/scope';
@@ -851,6 +852,28 @@ const manifestUpdateHash = sha1(JSON.stringify(manifestUpdate));
851852
expect(driver.state).toEqual(DriverReadyState.EXISTING_CLIENTS_ONLY);
852853
});
853854

855+
async_it('enters degraded mode when failing to write to cache', async() => {
856+
// Initialize the SW.
857+
await makeRequest(scope, '/foo.txt');
858+
await driver.initialized;
859+
expect(driver.state).toBe(DriverReadyState.NORMAL);
860+
861+
server.clearRequests();
862+
863+
// Operate normally.
864+
expect(await makeRequest(scope, '/foo.txt')).toBe('this is foo');
865+
server.assertNoOtherRequests();
866+
867+
// Clear the caches and make them unwritable.
868+
await clearAllCaches(scope.caches);
869+
spyOn(MockCache.prototype, 'put').and.throwError('Can\'t touch this');
870+
871+
// Enter degraded mode and serve from network.
872+
expect(await makeRequest(scope, '/foo.txt')).toBe('this is foo');
873+
expect(driver.state).toBe(DriverReadyState.EXISTING_CLIENTS_ONLY);
874+
server.assertSawRequestFor('/foo.txt');
875+
});
876+
854877
async_it('ignores invalid `only-if-cached` requests ', async() => {
855878
const requestFoo = (cache: RequestCache | 'only-if-cached', mode: RequestMode) =>
856879
makeRequest(scope, '/foo.txt', undefined, {cache, mode});

‎packages/service-worker/worker/testing/cache.ts‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -164,3 +164,20 @@ export class MockCache {
164164
return dehydrated;
165165
}
166166
}
167+
168+
// This can be used to simulate a situation (bug?), where the user clears the caches from DevTools,
169+
// while the SW is still running (e.g. serving another tab) and keeps references to the deleted
170+
// caches.
171+
export async function clearAllCaches(caches: CacheStorage): Promise<void> {
172+
const cacheNames = await caches.keys();
173+
const cacheInstances = await Promise.all(cacheNames.map(name => caches.open(name)));
174+
175+
// Delete all cache instances from `CacheStorage`.
176+
await Promise.all(cacheNames.map(name => caches.delete(name)));
177+
178+
// Delete all entries from each cache instance.
179+
await Promise.all(cacheInstances.map(async cache => {
180+
const keys = await cache.keys();
181+
await Promise.all(keys.map(key => cache.delete(key)));
182+
}));
183+
}

0 commit comments

Comments
 (0)