Skip to content

Commit fddb50b

Browse files
gkalpakdylhunn
authored andcommitted
fix(service-worker): make ngsw.json generation deterministic and correct (#43679)
Previously, all asset-groups from `ngsw-config.json` were processed in parallel. For each asset-group, we retrieved all files for the current build, filtered out files that were already matched by other asset-groups, determined which of the remaining files belonged to the current asset-group and generated entries for the `ngsw.json` manifest. This process was susceptible to race conditions when there were files that would be matched by multiple asset-groups. This made the generation of the `ngsw.json` manifest non-deterministic and violated the rule that each file would belong to the first asset-group that matched it (based on the asset-groups' order of appearance in `ngsw-config.json`), thus leading to broken ServiceWorker behavior. This commit fixes it by ensuring that the generation process is deterministic and that asset-groups are processed in the proper order. NOTE 1: The generation process has been broken since the beginning, but we have only noticed this recently. This is possibly related to the CLI's switching from a virtual file system host (which has more consistent timing characteristics) to the Node.js built-in `fs.promises` in angular/angular-cli@d3bc530. NOTE 2: This commit also ensures that files in the `ngsw.json` hash-table are in alphabetic order. Previously, the files were added to the hash-table in blocks corresponding to each asset-group. This change is not necessary (i.e. the order of keys in the hash-table makes no difference in behavior), but it makes it easier to scan for a file (for example, for debugging purposes). PR Close #43679
1 parent 0dc4544 commit fddb50b

2 files changed

Lines changed: 123 additions & 19 deletions

File tree

‎packages/service-worker/config/src/generator.ts‎

Lines changed: 27 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
import {parseDurationToMs} from './duration';
1010
import {Filesystem} from './filesystem';
1111
import {globToRegex} from './glob';
12-
import {Config} from './in';
12+
import {AssetGroup, Config} from './in';
1313

1414
const DEFAULT_NAVIGATION_URLS = [
1515
'/**', // Include all URLs.
@@ -45,36 +45,44 @@ export class Generator {
4545

4646
private async processAssetGroups(config: Config, hashTable: {[file: string]: string|undefined}):
4747
Promise<Object[]> {
48+
// Retrieve all files of the build.
49+
const allFiles = await this.fs.list('/');
4850
const seenMap = new Set<string>();
49-
return Promise.all((config.assetGroups || []).map(async (group) => {
51+
const filesPerGroup = new Map<AssetGroup, string[]>();
52+
53+
// Computed which files belong to each asset-group.
54+
for (const group of (config.assetGroups || [])) {
5055
if ((group.resources as any).versionedFiles) {
5156
throw new Error(
5257
`Asset-group '${group.name}' in 'ngsw-config.json' uses the 'versionedFiles' option, ` +
5358
'which is no longer supported. Use \'files\' instead.');
5459
}
5560

5661
const fileMatcher = globListToMatcher(group.resources.files || []);
57-
const allFiles = await this.fs.list('/');
58-
5962
const matchedFiles = allFiles.filter(fileMatcher).filter(file => !seenMap.has(file)).sort();
63+
6064
matchedFiles.forEach(file => seenMap.add(file));
65+
filesPerGroup.set(group, matchedFiles);
66+
}
6167

62-
// Add the hashes.
63-
await matchedFiles.reduce(async (previous, file) => {
64-
await previous;
65-
const hash = await this.fs.hash(file);
66-
hashTable[joinUrls(this.baseHref, file)] = hash;
67-
}, Promise.resolve());
68+
// Compute hashes for all matched files and add them to the hash-table.
69+
const allMatchedFiles = ([] as string[]).concat(...Array.from(filesPerGroup.values())).sort();
70+
const allMatchedHashes = await Promise.all(allMatchedFiles.map(file => this.fs.hash(file)));
71+
allMatchedFiles.forEach((file, idx) => {
72+
hashTable[joinUrls(this.baseHref, file)] = allMatchedHashes[idx];
73+
});
6874

69-
return {
70-
name: group.name,
71-
installMode: group.installMode || 'prefetch',
72-
updateMode: group.updateMode || group.installMode || 'prefetch',
73-
cacheQueryOptions: buildCacheQueryOptions(group.cacheQueryOptions),
74-
urls: matchedFiles.map(url => joinUrls(this.baseHref, url)),
75-
patterns: (group.resources.urls || []).map(url => urlToRegex(url, this.baseHref, true)),
76-
};
77-
}));
75+
// Generate and return the processed asset-groups.
76+
return Array.from(filesPerGroup.entries())
77+
.map(([group, matchedFiles]) => ({
78+
name: group.name,
79+
installMode: group.installMode || 'prefetch',
80+
updateMode: group.updateMode || group.installMode || 'prefetch',
81+
cacheQueryOptions: buildCacheQueryOptions(group.cacheQueryOptions),
82+
urls: matchedFiles.map(url => joinUrls(this.baseHref, url)),
83+
patterns:
84+
(group.resources.urls || []).map(url => urlToRegex(url, this.baseHref, true)),
85+
}));
7886
}
7987

8088
private processDataGroups(config: Config): Object[] {

‎packages/service-worker/config/test/generator_spec.ts‎

Lines changed: 96 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -128,6 +128,102 @@ describe('Generator', () => {
128128
});
129129
});
130130

131+
it('assigns files to the first matching asset-group (unaffected by file-system access delays)',
132+
async () => {
133+
const fs = new MockFilesystem({
134+
'/index.html': 'This is a test',
135+
'/foo/script-1.js': 'This is script 1',
136+
'/foo/script-2.js': 'This is script 2',
137+
'/bar/script-3.js': 'This is script 3',
138+
'/bar/script-4.js': 'This is script 4',
139+
'/qux/script-5.js': 'This is script 5',
140+
});
141+
142+
// Simulate fluctuating file-system access delays.
143+
const allFiles = await fs.list('/');
144+
spyOn(fs, 'list')
145+
.and.returnValues(
146+
new Promise(resolve => setTimeout(resolve, 2000, allFiles.slice())),
147+
new Promise(resolve => setTimeout(resolve, 3000, allFiles.slice())),
148+
new Promise(resolve => setTimeout(resolve, 1000, allFiles.slice())),
149+
);
150+
151+
const gen = new Generator(fs, '');
152+
const config = await gen.process({
153+
index: '/index.html',
154+
assetGroups: [
155+
{
156+
name: 'group-foo',
157+
resources: {files: ['/foo/**/*.js']},
158+
},
159+
{
160+
name: 'group-bar',
161+
resources: {files: ['/bar/**/*.js']},
162+
},
163+
{
164+
name: 'group-fallback',
165+
resources: {files: ['/**/*.js']},
166+
},
167+
],
168+
});
169+
170+
expect(config).toEqual({
171+
configVersion: 1,
172+
timestamp: 1234567890123,
173+
appData: undefined,
174+
index: '/index.html',
175+
assetGroups: [
176+
{
177+
name: 'group-foo',
178+
installMode: 'prefetch',
179+
updateMode: 'prefetch',
180+
cacheQueryOptions: {ignoreVary: true},
181+
urls: [
182+
'/foo/script-1.js',
183+
'/foo/script-2.js',
184+
],
185+
patterns: [],
186+
},
187+
{
188+
name: 'group-bar',
189+
installMode: 'prefetch',
190+
updateMode: 'prefetch',
191+
cacheQueryOptions: {ignoreVary: true},
192+
urls: [
193+
'/bar/script-3.js',
194+
'/bar/script-4.js',
195+
],
196+
patterns: [],
197+
},
198+
{
199+
name: 'group-fallback',
200+
installMode: 'prefetch',
201+
updateMode: 'prefetch',
202+
cacheQueryOptions: {ignoreVary: true},
203+
urls: [
204+
'/qux/script-5.js',
205+
],
206+
patterns: [],
207+
},
208+
],
209+
dataGroups: [],
210+
hashTable: {
211+
'/bar/script-3.js': 'bc0a9b488b5707757c491ddac66f56304310b6b1',
212+
'/bar/script-4.js': 'b7782e97a285f1f6e62feca842384babaa209040',
213+
'/foo/script-1.js': '3cf257d7ef7e991898f8506fd408cab4f0c2de91',
214+
'/foo/script-2.js': '9de2ba54065bb9d610bce51beec62e35bea870a7',
215+
'/qux/script-5.js': '3dceafdc0a1b429718e45fbf8e3005dd767892de'
216+
},
217+
navigationUrls: [
218+
{positive: true, regex: '^\\/.*$'},
219+
{positive: false, regex: '^\\/(?:.+\\/)?[^/]*\\.[^/]*$'},
220+
{positive: false, regex: '^\\/(?:.+\\/)?[^/]*__[^/]*$'},
221+
{positive: false, regex: '^\\/(?:.+\\/)?[^/]*__[^/]*\\/.*$'},
222+
],
223+
navigationRequestStrategy: 'performance',
224+
});
225+
});
226+
131227
it('uses default `navigationUrls` if not provided', async () => {
132228
const fs = new MockFilesystem({
133229
'/index.html': 'This is a test',

0 commit comments

Comments
 (0)