Skip to content

feat: add Service Worker network interception - #12565

Closed
Ross Wollman (rwoll) wants to merge 27 commits into
microsoft:mainfrom
rwoll:feat/sw-init-interception
Closed

Ross Wollman (rwoll) wants to merge 27 commits into
microsoft:mainfrom
rwoll:feat/sw-init-interception

Conversation

@rwoll

@rwoll Ross Wollman (rwoll) commented Mar 7, 2022 •

Copy link
Copy Markdown
Member

Resolves #1090.

Some known TODOs:

  • Code Organization
    • move SW code into own CRServiceWorker
    • clean up import cycles (and general haphazard importing)
    • Intro NetworkedTarget to try to mitigate all the this._page || this._serviceWorker bits
  • More Tests!
    • CORS
    • Native Service Worker Fetch
    • Service Worker Cache Intercaction
    • Multi-Page Scenarios
    • WebSockets
    • setOffline
    • multiple
  • Toggle Service Worker Interception based on current routeing
  • Review/resolve all FIXME(raw):/TODO(raw):
  • (maybe) Add option to opt-out of SW interception. The current patch may break users who are currently doing interception and don't expect the SW bits to show up (or they assume request.frame() is always valid…it was before!)
  • (maybe) Add worker.on('request',...) etc. events to mirror page events

Comment thread tests/browsercontext-route.spec.ts Resolved
@Mone71

Copy link
Copy Markdown

Thanks

@dgozman Dmitry Gozman (dgozman) left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks nice overall!

const page = this.request().frame()._page;
// FIXME(raw): SW requests do not have an associated frame: we probably want to signal and check it is explicilty SW request
let page = null;
try {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

const page = this.request()._frame?._page;

Comment thread tests/browsercontext-route.spec.ts Resolved
@Meir017

Copy link
Copy Markdown
Contributor

adding a method on the service-worker's request/response that references the page/worker request would be helpful as well here.
puppeteer has a boolean flag for this https://pptr.dev/#?product=Puppeteer&version=v9.0.0&show=api-httpresponsefromserviceworker, playwright does not have any indicator about service worker on the request/response object, this should not be a breaking change

as can be seen in the devtools here https://googlechrome.github.io/samples/service-worker/basic/
image

image
image

@Doug-Bowen

Copy link
Copy Markdown

Is there a general ETA on this work. This is crucial to an issue im solving now. If this is slated for a later release, I'll move in a different direction for the time being.

No pressure, just curious.

@rwoll

Copy link
Copy Markdown
Member Author

Is there a general ETA on this work. This is crucial to an issue im solving now. If this is slated for a later release, I'll move in a different direction for the time being.

No pressure, just curious.

Doug Bowen (@Doug-Bowen) Thanks for your interest! I can't commit to an ETA. Please subscribe to #1090 to be notified of when it lands. Once it's in the main branch, you'll be able to try it out via @next.

@rwoll
Ross Wollman (rwoll) force-pushed the feat/sw-init-interception branch 2 times, most recently from 86aa2d2 to 1baab20 Compare March 12, 2022 00:06
Ross Wollman (rwoll) and others added 12 commits March 12, 2022 13:27
This is the beginning of fixing
microsoft#1090.

There's still quite a bit to be done, but this at least shows an
end-to-end path to accomplish the feature.
There's still lots that needs to be changed and cleaned up. Initial
attempts tried to get too much working at once (and create pretty but
possibly poor abstractions), so this backs off the changes to a minimal
set.

NB: This patchset requires a CR >= r979924 (https://chromium-review.googlesource.com/c/chromium/src/+/3510917).

To use a local copy, be sure to set `CRPATH` like so:

```
$ CRPATH=$HOME/code/google/chromium/src/out/Default/Chromium.app/Contents/MacOS/Chromium npm run ctest -- --reporter=line
```
Comment thread tests/har.spec.ts Resolved
Comment thread tests/chromium/chromium.spec.ts Resolved
if (!event.responseStatusCode && !event.responseErrorReason) {
// Request intercepted, deliver signal to the tracker.
const request = this._requestIdToRequest.get(event.networkId!);
const request = this._requestIdToRequest.get(event.networkId!) || this._maybeAdoptServiceWorkerMainRequest(event.networkId!);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Add a test that 'request' event is dispatched for the main sw script without interception, and is not dispatched on the page.

@rwoll

Copy link
Copy Markdown
Member Author

Addressed the mechanical fixes/improvements. Will address the _maybeAdoptServiceWorkerMainRequest bits of feedback tomorrow!

This is getting near feature complete for an initial land modulo some additional testing. 😄

expect(await worker.evaluate(() => self.toString())).toBe('[object ServiceWorkerGlobalScope]');
});

test('should create a worker from service worker with noop routing', async ({ context, page, server }) => {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we should also verify that page does not report the requests sent from within the service worker, only the request being sent from the page (being intercepted by the service-worker)

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we should also verify that page does not report the requests sent from within the service worker, only the request being sent from the page (being intercepted by the service-worker)

Meir Blachman (@Meir017) Let me make sure I'm following!

So if example.html looks like:

<script>
  navigator.serviceWorker.register('/worker.js');
  navigator.serviceWorker.ready.then(async registration => {
      await fetch('/payload.txt');
  });
</script>

and worker.js looks like:

fetch('/top-level-sw-request.txt');
self.addEventListener('fetch', event => {
  if (!event.request.url.endsWith('/payload.txt')) return;
  event.respondWith(fetch(event.request));
});

On which Playwright object (page or serviceWorker) would you expect to see the request event fire for each of the two requests (/payload.txt and /top-level-sw-request.txt)?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would expect to see two request events fired. one for the page and another for the service worker.
this can be seen in the network tab of the browser.

from your example

  • page request /worker.js
  • sw request /top-level-sw-request.txt
  • page request /payload.txt
  • sw request /payload.txt

see my comment #12565 (comment)

// Service Worker Network.requestWillBeSent event fires on the parent frame session,
// but the Fetch.requestPaused comes in on the Service Worker session.
// We assume these came in the the same session (on the Service Worker), so shuffle things around.
// In the future, this may be resolved; see https://crbug.com/1304536

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Currently fixing this upstream.

@rwoll

Copy link
Copy Markdown
Member Author

Closing this! Will re-open once CR upstream changes are all landed and this code is reworked a bit around some internal refactors and conflicts.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature] support route aka request interception for service workers

6 participants