Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

v3: workbox-range-requests module #1108

Merged
merged 3 commits into from
Dec 6, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions infra/testing/sw-env-mocks/Blob.js
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,12 @@ class Blob {
}
return text;
}

slice(start, end, type) {
const bodyString = this._text;
const slicedBodyString = bodyString.substring(start, end);
return new Blob([slicedBodyString], {type});
}
}

module.exports = Blob;
43 changes: 36 additions & 7 deletions packages/workbox-core/models/messages/messages.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -43,23 +43,22 @@ export default {

'incorrect-type': ({expectedType, paramName, moduleName, className,
funcName}) => {
if (!expectedType || !paramName || !moduleName || !className || !funcName) {
if (!expectedType || !paramName || !moduleName || !funcName) {
throw new Error(`Unexpected input to 'incorrect-type' error.`);
}
return `The parameter '${paramName}' passed into ` +
`'${moduleName}.${className}.${funcName}()' must be of type ` +
`${expectedType}.`;
`'${moduleName}.${className ? (className + '.') : ''}` +
`${funcName}()' must be of type ${expectedType}.`;
},

'incorrect-class': ({expectedClass, paramName, moduleName, className,
funcName}) => {
if (!expectedClass || !paramName || !moduleName || !className ||
!funcName) {
if (!expectedClass || !paramName || !moduleName || !funcName) {
throw new Error(`Unexpected input to 'incorrect-class' error.`);
}
return `The parameter '${paramName}' passed into ` +
`'${moduleName}.${className}.${funcName}()' must be an instance of ` +
`class ${expectedClass.name}.`;
`'${moduleName}.${className ? (className + '.') : ''}.${funcName}()' ` +
`must be an instance of class ${expectedClass.name}.`;
},

'missing-a-method': ({expectedMethod, paramName, moduleName, className,
Expand Down Expand Up @@ -180,4 +179,34 @@ export default {
return `The arguments passed into responsesAreSame() appear to be ` +
`invalid. Please ensure valid Responses are used.`;
},
'unit-must-be-bytes': ({normalizedRangeHeader}) => {
if (!normalizedRangeHeader) {
throw new Error(`Unexpected input to 'unit-must-be-bytes' error.`);
}
return `The 'unit' portion of the Range header must be set to 'bytes'. ` +
`The Range header provided was "${normalizedRangeHeader}"`;
},
'single-range-only': ({normalizedRangeHeader}) => {
if (!normalizedRangeHeader) {
throw new Error(`Unexpected input to 'single-range-only' error.`);
}
return `Multiple ranges are not supported. Please use a single start ` +
`value, and optional end value. The Range header provided was ` +
`"${normalizedRangeHeader}"`;
},
'invalid-range-values': ({normalizedRangeHeader}) => {
if (!normalizedRangeHeader) {
throw new Error(`Unexpected input to 'invalid-range-values' error.`);
}
return `The Range header is missing both start and end values. At least ` +
`one of those values is needed. The Range header provided was ` +
`"${normalizedRangeHeader}"`;
},
'no-range-header': () => {
return `No Range header was found in the Request provided.`;
},
'range-not-satisfiable': ({size, start, end}) => {
return `The start (${start}) and end (${end}) values in the Range are ` +
`not satisfiable by the cached response, which is ${size} bytes.`;
},
};
50 changes: 50 additions & 0 deletions packages/workbox-range-requests/Plugin.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
/*
Copyright 2016 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

import {createPartialResponse} from './createPartialResponse.mjs';

import './_version.mjs';

/**
* The range request plugin makes it easy for a request with a 'Range' header to
* be fulfilled by a cached response.
*
* It does this by intercepting the `cachedResponseWillBeUsed` plugin callback
* and returning the appropriate subset of the cached response body.
*
* @memberof workbox.rangeRequests
*/
class Plugin {
/**
* @param {Object} options
* @param {Request} options.request The original request, which may or may not
* contain a Range: header.
* @param {Response} options.cachedResponse The complete cached response.
* @return {Promise<Response>} If request contains a 'Range' header, then a
* new response with status 206 whose body is a subset of `cachedResponse` is
* returned. Otherwise, `cachedResponse` is returned as-is.
*
* @private
*/
static async cachedResponseWillBeUsed({request, cachedResponse} = {}) {
// Only return a sliced response if there's a Range: header in the request.
if (request.headers.has('range')) {
return await createPartialResponse(request, cachedResponse);
}

// If there was no Range: header, return the original response as-is.
return cachedResponse;
}
}

export {Plugin};
24 changes: 24 additions & 0 deletions packages/workbox-range-requests/_public.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
/*
Copyright 2017 Google Inc.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

https://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

import {createPartialResponse} from './createPartialResponse.mjs';
import {Plugin} from './Plugin.mjs';
import './_version.mjs';

export {
createPartialResponse,
Plugin,
};
1 change: 1 addition & 0 deletions packages/workbox-range-requests/_version.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
try{self.workbox.v['workbox:range-requests:3.0.0-alpha.2']=1;}catch(e){} // eslint-disable-line
19 changes: 19 additions & 0 deletions packages/workbox-range-requests/browser.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
/*
Copyright 2017 Google Inc.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

https://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

import './_version.mjs';

export * from './_public.mjs';
105 changes: 105 additions & 0 deletions packages/workbox-range-requests/createPartialResponse.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
/*
Copyright 2017 Google Inc.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

https://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

import {WorkboxError} from 'workbox-core/_private/WorkboxError.mjs';
import {assert} from 'workbox-core/_private/assert.mjs';
import {logger} from 'workbox-core/_private/logger.mjs';

import {calculateEffectiveBoundaries} from
'./utils/calculateEffectiveBoundaries.mjs';
import {parseRangeHeader} from './utils/parseRangeHeader.mjs';

import './_version.mjs';

/**
* Given a `Request` and `Response` objects as input, this will return a
* promise for a new `Response`.
*
* @param {Request} request A request, which should contain a Range:
* header.
* @param {Response} originalResponse An original response containing the full
* content.
* @return {Promise<Response>} Either a `206 Partial Content` response, with
* the response body set to the slice of content specified by the request's
* `Range:` header, or a `416 Range Not Satisfiable` response if the
* conditions of the `Range:` header can't be met.
*
* @memberof workbox.rangeRequests
*/
async function createPartialResponse(request, originalResponse) {
try {
if (process.env.NODE_ENV !== 'production') {
assert.isInstance(request, Request, {
moduleName: 'workbox-range-requests',
funcName: 'createPartialResponse',
paramName: 'request',
});

assert.isInstance(originalResponse, Response, {
moduleName: 'workbox-range-requests',
funcName: 'createPartialResponse',
paramName: 'originalResponse',
});
}

const rangeHeader = request.headers.get('range');
if (!rangeHeader) {
throw new WorkboxError('no-range-header');
}

const boundaries = parseRangeHeader(rangeHeader);
const originalBlob = await originalResponse.blob();

const effectiveBoundaries = calculateEffectiveBoundaries(
originalBlob, boundaries.start, boundaries.end);

const slicedBlob = originalBlob.slice(effectiveBoundaries.start,
effectiveBoundaries.end);
const slicedBlobSize = slicedBlob.size;

const slicedResponse = new Response(slicedBlob, {
// Status code 206 is for a Partial Content response.
// See https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/206
status: 206,
statusText: 'Partial Content',
headers: originalResponse.headers,
});

slicedResponse.headers.set('Content-Length', slicedBlobSize);
slicedResponse.headers.set('Content-Range',
`bytes ${effectiveBoundaries.start}-${effectiveBoundaries.end - 1}/` +
originalBlob.size);

return slicedResponse;
} catch (error) {
if (process.env.NODE_ENV !== 'production') {
logger.warn(`Unable to construct a partial response; returning a ` +
`416 Range Not Satisfiable response instead.`);
logger.groupCollapsed(`View details here.`);
logger.unprefixed.log(error);
logger.unprefixed.log(request);
logger.unprefixed.log(originalResponse);
logger.groupEnd();
}

return new Response('', {
status: 416,
statusText: 'Range Not Satisfiable',
});
}
}

export {createPartialResponse};
23 changes: 23 additions & 0 deletions packages/workbox-range-requests/index.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
/*
Copyright 2017 Google Inc.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

https://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

/**
* @namespace workbox.rangeRequests
*/

import './_version.mjs';

export * from './_public.mjs';
34 changes: 34 additions & 0 deletions packages/workbox-range-requests/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
{
"name": "workbox-range-requests",
"version": "3.0.0-alpha.2",
"license": "Apache-2.0",
"author": "Google's Web DevRel Team",
"description": "This library creates a new Response, given a source Response and a Range header value.",
"repository": "googlechrome/workbox",
"bugs": "https://github.com/googlechrome/workbox/issues",
"homepage": "https://github.com/GoogleChrome/workbox",
"keywords": [
"workbox",
"workboxjs",
"service worker",
"sw",
"caching",
"cache",
"range",
"media"
],
"scripts": {
"build": "gulp build-packages --package workbox-range-requests",
"version": "npm run build",
"prepare": "npm run build"
},
"workbox": {
"browserNamespace": "workbox.rangeRequests",
"packageType": "browser"
},
"main": "build/workbox-range-requests.prod.js",
"module": "index.mjs",
"dependencies": {
"workbox-core": "^3.0.0-alpha.2"
}
}
Loading