Skip to content

Commit 58d155f

Browse files
authored
Service worker: Retry ERR_HTTP2_PROTOCOL_ERROR (#949)
Playground.wordpress.net sometimes returns ERR_HTTP2_PROTOCOL_ERROR for bursts of static assets requests. This commit adds a simple retrying mechanism at the service worker level. ## Testing Instructions Create a new `server.js` file with the following contents: ```js const fs = require('fs'); const http2 = require('http2'); const { HTTP2_HEADER_PATH, HTTP2_HEADER_METHOD } = http2.constants; const server = http2.createSecureServer({ key: fs.readFileSync('./key.pem'), cert: fs.readFileSync('./certificate.pem'), }); server.on('stream', (stream, headers) => { const method = headers[HTTP2_HEADER_METHOD]; const path = headers[HTTP2_HEADER_PATH]; if (method == 'GET' && path == '/error') { // This will terminate the stream and simulate a ERR_HTTP2_PROTOCOL_ERROR stream.destroy(); } else { stream.respond({ 'content-type': 'text/html', ':status': 200, }); stream.end('<h1> This request worked! </h1>'); } }); server.listen(8441); ``` Then update the `service-worker.ts` as follows: ```ts if ( workerResponse.status === 404 && workerResponse.headers.get('x-file-type') === 'static' ) { // If we get a 404 for a static file, try to fetch it from // the from the static assets directory at the remote server. let request = await rewriteRequest( event.request, staticAssetsDirectory ); if ( request.url === 'http://localhost:5400/wp-6.4/wp-includes/js/admin-bar.min.js?ver=6.4.2' ) { request = await cloneRequest(request, { url: 'http://localhost:3000/error', }); } return fetch(request).catch((e) => { ``` Then start a dev server (`npm run dev`), unregister the service worker in devtools > application, restart the browser, and confirm the request to `admin-bar.min.js` failed and was retried once.
1 parent 57b7e7d commit 58d155f

File tree

1 file changed

+15
-1
lines changed

1 file changed

+15
-1
lines changed

packages/playground/remote/service-worker.ts

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,21 @@ initializeServiceWorker({
5454
event.request,
5555
staticAssetsDirectory
5656
);
57-
return fetch(request);
57+
return fetch(request).catch((e) => {
58+
if (e?.name === 'TypeError') {
59+
// This could be an ERR_HTTP2_PROTOCOL_ERROR that sometimes
60+
// happen on playground.wordpress.net. Let's add a randomized
61+
// delay and retry once
62+
return new Promise((resolve) => {
63+
setTimeout(() => {
64+
resolve(fetch(request));
65+
}, Math.random() * 1500);
66+
}) as Promise<Response>;
67+
}
68+
69+
// Otherwise let's just re-throw the error
70+
throw e;
71+
});
5872
}
5973

6074
// Path the block-editor.js file to ensure the site editor's iframe

0 commit comments

Comments
 (0)