Skip to content

Commit cc30dc0

Browse files
gkalpakthePunderWoman
authored andcommitted
fix(service-worker): ensure obsolete caches are always cleaned up (#42622)
Previously, the SW was only able to clean up caches for app-versions found in the `Driver`'s `versions` map. If (for some reason) the `Driver` failed to load a valid stored state (including app-versions) and ended up with an [empty `versions` map][1], any obsolete versions would remain in the cache storage. This case was rare but possible. This commit makes the cache clean-up logic more robust by ensuring that all app-version caches are removed unless they are currently used by the SW to serve active clients (with the exception of the latest app-version, which is always retained). Fixes #41728 [1]: https://github.com/angular/angular/blob/9de65dbdceac3077881fbc49717f33d0f379e21d/packages/service-worker/worker/src/driver.ts#L515-L529 PR Close #42622
1 parent 01128f5 commit cc30dc0

6 files changed

Lines changed: 125 additions & 71 deletions

File tree

‎packages/service-worker/worker/src/app-version.ts‎

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -284,11 +284,14 @@ export class AppVersion implements UpdateSource {
284284
}
285285

286286
/**
287-
* Erase this application version, by cleaning up all the caches.
287+
* Return a list of the names of all caches used by this version.
288288
*/
289-
async cleanup(): Promise<void> {
290-
await Promise.all(this.assetGroups.map(group => group.cleanup()));
291-
await Promise.all(this.dataGroups.map(group => group.cleanup()));
289+
async getCacheNames(): Promise<string[]> {
290+
const allGroupCacheNames = await Promise.all([
291+
...this.assetGroups.map(group => group.getCacheNames()),
292+
...this.dataGroups.map(group => group.getCacheNames()),
293+
]);
294+
return ([] as string[]).concat(...allGroupCacheNames);
292295
}
293296

294297
/**

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

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
import {Adapter, Context} from './adapter';
1010
import {CacheState, NormalizedUrl, UpdateCacheStatus, UpdateSource, UrlMetadata} from './api';
1111
import {Database, Table} from './database';
12+
import {CacheTable} from './db-cache';
1213
import {errorToString, SwCriticalError, SwUnrecoverableStateError} from './error';
1314
import {IdleScheduler} from './idle';
1415
import {AssetGroupConfig} from './manifest';
@@ -100,13 +101,14 @@ export abstract class AssetGroup {
100101
abstract initializeFully(updateFrom?: UpdateSource): Promise<void>;
101102

102103
/**
103-
* Clean up all the cached data for this group.
104+
* Return a list of the names of all caches used by this group.
104105
*/
105-
async cleanup(): Promise<void> {
106-
await Promise.all([
107-
this.cache.then(cache => this.adapter.caches.delete(cache.name)),
108-
this.metadata.then(metadata => this.db.delete(metadata.name)),
106+
async getCacheNames(): Promise<string[]> {
107+
const [cache, metadata] = await Promise.all([
108+
this.cache,
109+
this.metadata as Promise<CacheTable>,
109110
]);
111+
return [cache.name, metadata.cacheName];
110112
}
111113

112114
/**

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

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88

99
import {Adapter, Context} from './adapter';
1010
import {Database, Table} from './database';
11+
import {CacheTable} from './db-cache';
1112
import {DebugHandler} from './debug';
1213
import {DataGroupConfig} from './manifest';
1314
import {NamedCache} from './named-cache-storage';
@@ -554,6 +555,17 @@ export class DataGroup {
554555
this.lruTable.then(table => this.db.delete(table.name)),
555556
]);
556557
}
558+
/**
559+
* Return a list of the names of all caches used by this group.
560+
*/
561+
async getCacheNames(): Promise<string[]> {
562+
const [cache, ageTable, lruTable] = await Promise.all([
563+
this.cache,
564+
this.ageTable as Promise<CacheTable>,
565+
this.lruTable as Promise<CacheTable>,
566+
]);
567+
return [cache.name, ageTable.cacheName, lruTable.cacheName];
568+
}
557569

558570
/**
559571
* Clear the state of the cache for a particular resource.

‎packages/service-worker/worker/src/db-cache.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88

99
import {Adapter} from './adapter';
1010
import {Database, NotFound, Table} from './database';
11+
import {NamedCache} from './named-cache-storage';
1112

1213

1314
/**
@@ -51,8 +52,10 @@ export class CacheDatabase implements Database {
5152
* A `Table` backed by a `Cache`.
5253
*/
5354
export class CacheTable implements Table {
55+
cacheName = this.cache.name;
56+
5457
constructor(
55-
readonly name: string, private cache: Cache, private adapter: Adapter,
58+
readonly name: string, private cache: NamedCache, private adapter: Adapter,
5659
private cacheQueryOptions?: CacheQueryOptions) {}
5760

5861
private request(key: string): Request {

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

Lines changed: 51 additions & 57 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import {Adapter} from './adapter';
1010
import {CacheState, Debuggable, DebugIdleState, DebugState, DebugVersion, NormalizedUrl, UpdateCacheStatus, UpdateSource} from './api';
1111
import {AppVersion} from './app-version';
1212
import {Database} from './database';
13+
import {CacheTable} from './db-cache';
1314
import {DebugHandler} from './debug';
1415
import {errorToString} from './error';
1516
import {IdleScheduler} from './idle';
@@ -110,6 +111,9 @@ export class Driver implements Debuggable, UpdateSource {
110111

111112
debugger: DebugHandler;
112113

114+
// A promise resolving to the control DB table.
115+
private controlTable = this.db.open('control');
116+
113117
constructor(
114118
private scope: ServiceWorkerGlobalScope, private adapter: Adapter, private db: Database) {
115119
// Set up all the event handlers that the SW needs.
@@ -517,8 +521,7 @@ export class Driver implements Debuggable, UpdateSource {
517521
// the SW has run or the DB state has been wiped or is inconsistent. In that case,
518522
// load a fresh copy of the manifest and reset the state from scratch.
519523

520-
// Open up the DB table.
521-
const table = await this.db.open('control');
524+
const table = await this.controlTable;
522525

523526
// Attempt to load the needed state from the DB. If this fails, the catch {} block
524527
// will populate these variables with freshly constructed values.
@@ -568,12 +571,7 @@ export class Driver implements Debuggable, UpdateSource {
568571

569572
// Schedule cleaning up obsolete caches in the background.
570573
this.idle.schedule('init post-load (cleanup)', async () => {
571-
try {
572-
await this.cleanupCaches();
573-
} catch (err) {
574-
// Nothing to do - cleanup failed. Just log it.
575-
this.debugger.log(err, 'cleanupCaches @ init post-load');
576-
}
574+
await this.cleanupCaches();
577575
});
578576

579577
// Initialize the `versions` map by setting each hash to a new `AppVersion` instance
@@ -901,8 +899,7 @@ export class Driver implements Debuggable, UpdateSource {
901899
* Synchronize the existing state to the underlying database.
902900
*/
903901
private async sync(): Promise<void> {
904-
// Open up the DB table.
905-
const table = await this.db.open('control');
902+
const table = await this.controlTable;
906903

907904
// Construct a serializable map of hashes to manifests.
908905
const manifests: ManifestMap = {};
@@ -931,56 +928,45 @@ export class Driver implements Debuggable, UpdateSource {
931928
}
932929

933930
async cleanupCaches(): Promise<void> {
934-
// Query for all currently active clients, and list the client ids. This may skip
935-
// some clients in the browser back-forward cache, but not much can be done about
936-
// that.
937-
const activeClients: ClientId[] =
938-
(await this.scope.clients.matchAll()).map(client => client.id);
939-
940-
// A simple list of client ids that the SW has kept track of. Subtracting
941-
// activeClients from this list will result in the set of client ids which are
942-
// being tracked but are no longer used in the browser, and thus can be cleaned up.
943-
const knownClients: ClientId[] = Array.from(this.clientVersionMap.keys());
944-
945-
// Remove clients in the clientVersionMap that are no longer active.
946-
knownClients.filter(id => activeClients.indexOf(id) === -1)
947-
.forEach(id => this.clientVersionMap.delete(id));
948-
949-
// Next, determine the set of versions which are still used. All others can be
950-
// removed.
951-
const usedVersions = new Set<string>();
952-
this.clientVersionMap.forEach((version, _) => usedVersions.add(version));
953-
954-
// Collect all obsolete versions by filtering out used versions from the set of all versions.
955-
const obsoleteVersions =
956-
Array.from(this.versions.keys())
957-
.filter(version => !usedVersions.has(version) && version !== this.latestHash);
958-
959-
// Remove all the versions which are no longer used.
960-
await obsoleteVersions.reduce(async (previous, version) => {
961-
// Wait for the other cleanup operations to complete.
962-
await previous;
963-
964-
// Try to get past the failure of one particular version to clean up (this
965-
// shouldn't happen, but handle it just in case).
966-
try {
967-
// Get ahold of the AppVersion for this particular hash.
968-
const instance = this.versions.get(version)!;
931+
try {
932+
// Query for all currently active clients, and list the client IDs. This may skip some clients
933+
// in the browser back-forward cache, but not much can be done about that.
934+
const activeClients =
935+
new Set<ClientId>((await this.scope.clients.matchAll()).map(client => client.id));
969936

970-
// Delete it from the canonical map.
971-
this.versions.delete(version);
937+
// A simple list of client IDs that the SW has kept track of. Subtracting `activeClients` from
938+
// this list will result in the set of client IDs which are being tracked but are no longer
939+
// used in the browser, and thus can be cleaned up.
940+
const knownClients: ClientId[] = Array.from(this.clientVersionMap.keys());
972941

973-
// Clean it up.
974-
await instance.cleanup();
975-
} catch (err) {
976-
// Oh well? Not much that can be done here. These caches will be removed when
977-
// the SW revs its format version, which happens from time to time.
978-
this.debugger.log(err, `cleanupCaches - cleanup ${version}`);
979-
}
980-
}, Promise.resolve());
942+
// Remove clients in the `clientVersionMap` that are no longer active.
943+
const obsoleteClients = knownClients.filter(id => !activeClients.has(id));
944+
obsoleteClients.forEach(id => this.clientVersionMap.delete(id));
981945

982-
// Commit all the changes to the saved state.
983-
await this.sync();
946+
// Next, determine the set of versions which are still used. All others can be removed.
947+
const usedVersions = new Set(this.clientVersionMap.values());
948+
949+
// Collect all obsolete versions by filtering out used versions from the set of all versions.
950+
const obsoleteVersions =
951+
Array.from(this.versions.keys())
952+
.filter(version => !usedVersions.has(version) && version !== this.latestHash);
953+
954+
// Remove all the versions which are no longer used.
955+
obsoleteVersions.forEach(version => this.versions.delete(version));
956+
957+
// Commit all the changes to the saved state.
958+
await this.sync();
959+
960+
// Delete all caches that are no longer needed.
961+
const allCaches = await this.adapter.caches.keys();
962+
const usedCaches = new Set(await this.getCacheNames());
963+
const cachesToDelete = allCaches.filter(name => !usedCaches.has(name));
964+
await Promise.all(cachesToDelete.map(name => this.adapter.caches.delete(name)));
965+
} catch (err) {
966+
// Oh well? Not much that can be done here. These caches will be removed on the next attempt
967+
// or when the SW revs its format version, which happens from time to time.
968+
this.debugger.log(err, 'cleanupCaches');
969+
}
984970
}
985971

986972
/**
@@ -1150,4 +1136,12 @@ export class Driver implements Debuggable, UpdateSource {
11501136
});
11511137
}
11521138
}
1139+
1140+
private async getCacheNames(): Promise<string[]> {
1141+
const controlTable = await this.controlTable as CacheTable;
1142+
const appVersions = Array.from(this.versions.values());
1143+
const appVersionCacheNames =
1144+
await Promise.all(appVersions.map(version => version.getCacheNames()));
1145+
return [controlTable.cacheName].concat(...appVersionCacheNames);
1146+
}
11531147
}

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

Lines changed: 44 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -698,6 +698,42 @@ describe('Driver', () => {
698698
expect(hasOriginalCaches).toEqual(false);
699699
});
700700

701+
it('cleans up properly when failing to load stored state', async () => {
702+
// Initialize the SW and cache the original app-version.
703+
expect(await makeRequest(scope, '/foo.txt')).toBe('this is foo');
704+
await driver.initialized;
705+
706+
// Update and cache the updated app-version.
707+
scope.updateServerState(serverUpdate);
708+
expect(await driver.checkForUpdate()).toBeTrue();
709+
expect(await makeRequest(scope, '/foo.txt', 'newClient')).toBe('this is foo v2');
710+
711+
// Verify both app-versions are stored in the cache.
712+
let cacheNames = await scope.caches.keys();
713+
let hasOriginalVersion = cacheNames.some(name => name.startsWith(`${manifestHash}:`));
714+
let hasUpdatedVersion = cacheNames.some(name => name.startsWith(`${manifestUpdateHash}:`));
715+
expect(hasOriginalVersion).withContext('Has caches for original version').toBeTrue();
716+
expect(hasUpdatedVersion).withContext('Has caches for updated version').toBeTrue();
717+
718+
// Simulate failing to load the stored state (and thus starting from an empty state).
719+
scope.caches.delete('db:control');
720+
driver = new Driver(scope, scope, new CacheDatabase(scope));
721+
722+
expect(await makeRequest(scope, '/foo.txt')).toBe('this is foo v2');
723+
await driver.initialized;
724+
725+
// Verify that the caches for the obsolete original version are cleaned up.
726+
// await driver.cleanupCaches();
727+
scope.advance(6000);
728+
await driver.idle.empty;
729+
730+
cacheNames = await scope.caches.keys();
731+
hasOriginalVersion = cacheNames.some(name => name.startsWith(`${manifestHash}:`));
732+
hasUpdatedVersion = cacheNames.some(name => name.startsWith(`${manifestUpdateHash}:`));
733+
expect(hasOriginalVersion).withContext('Has caches for original version').toBeFalse();
734+
expect(hasUpdatedVersion).withContext('Has caches for updated version').toBeTrue();
735+
});
736+
701737
it('shows notifications for push notifications', async () => {
702738
expect(await makeRequest(scope, '/foo.txt')).toEqual('this is foo');
703739
await driver.initialized;
@@ -1481,6 +1517,7 @@ describe('Driver', () => {
14811517
// Another 6 seconds.
14821518
scope.advance(6000);
14831519
await driver.idle.empty;
1520+
await new Promise(resolve => setTimeout(resolve)); // Wait for async operations to complete.
14841521
serverUpdate.assertSawRequestFor('/unhashed/a.txt');
14851522

14861523
// Now the new version of the resource should be served.
@@ -1817,16 +1854,19 @@ describe('Driver', () => {
18171854
'ngsuu:active',
18181855
'not:ngsw:active',
18191856
'NgSw:StAgEd',
1820-
'ngsw:/:active',
1821-
'ngsw:/foo/:staged',
1857+
'ngsw:/:db:control',
1858+
'ngsw:/foo/:active',
1859+
'ngsw:/bar/:staged',
18221860
];
18231861
const allCacheNames = oldSwCacheNames.concat(otherCacheNames);
18241862

18251863
await Promise.all(allCacheNames.map(name => scope.caches.original.open(name)));
1826-
expect(await scope.caches.original.keys()).toEqual(allCacheNames);
1864+
expect(await scope.caches.original.keys())
1865+
.toEqual(jasmine.arrayWithExactContents(allCacheNames));
18271866

18281867
await driver.cleanupOldSwCaches();
1829-
expect(await scope.caches.original.keys()).toEqual(otherCacheNames);
1868+
expect(await scope.caches.original.keys())
1869+
.toEqual(jasmine.arrayWithExactContents(otherCacheNames));
18301870
});
18311871

18321872
it('should delete other caches even if deleting one of them fails', async () => {

0 commit comments

Comments
 (0)