fix(service-worker): freshness strategy should clone response for cache (#19764)

When Cache.put() is called with a Response, it consumes the response. If
the Response is used for any other purpose (such as satisfying the
original FetchEvent) it must be cloned first.

A bug exists in the mocks used for SW tests, where this condition is not
validated. The bodies of MockResponses can be utilized repeatedly without
erroring in the same way that a real browser would. This bug is fixed by
this commit, which causes tests for the freshness strategy of data caching
to start failing.

The cause of this failure is a second bug in the data caching code, where
the Response is not cloned prior to being passed to Cache.put(). This is
also fixed.

PR Close #19764
This commit is contained in:
Alex Rickabaugh
2017-10-10 12:54:41 -07:00
committed by Tobias Bosch
parent fcfb1544e8
commit 396c2417d9
3 changed files with 20 additions and 8 deletions

View File

@ -12,7 +12,7 @@ export class MockBody implements Body {
constructor(public _body: string|null) {}
async arrayBuffer(): Promise<ArrayBuffer> {
this.bodyUsed = true;
this.markBodyUsed();
if (this._body !== null) {
const buffer = new ArrayBuffer(this._body.length);
const access = new Uint8Array(buffer);
@ -28,7 +28,7 @@ export class MockBody implements Body {
async blob(): Promise<Blob> { throw 'Not implemented'; }
async json(): Promise<any> {
this.bodyUsed = true;
this.markBodyUsed();
if (this._body !== null) {
return JSON.parse(this._body);
} else {
@ -37,7 +37,7 @@ export class MockBody implements Body {
}
async text(): Promise<string> {
this.bodyUsed = true;
this.markBodyUsed();
if (this._body !== null) {
return this._body;
} else {
@ -46,6 +46,13 @@ export class MockBody implements Body {
}
async formData(): Promise<FormData> { throw 'Not implemented'; }
private markBodyUsed(): void {
if (this.bodyUsed === true) {
throw new Error('Cannot reuse body without cloning.');
}
this.bodyUsed = true;
}
}
export class MockHeaders implements Headers {