Skip to content

feat: add Service Worker interception - #14321

Closed
Ross Wollman (rwoll) wants to merge 33 commits into
microsoft:mainfrom
rwoll:feature/service-worker-support
Closed

Ross Wollman (rwoll) wants to merge 33 commits into
microsoft:mainfrom
rwoll:feature/service-worker-support

Conversation

@rwoll

@rwoll Ross Wollman (rwoll) commented May 21, 2022 •

Copy link
Copy Markdown
Member

Adds Service Worker Main Script Interception (CR-only) and Service Worker related utils:

  • (all browsers) Response.fulfilledByServiceWorker
  • (all browsers) serviceWorkers: "allow" | "block" context option (and test.use option)
  • (CR-only) instruments Service Worker Networking (allows for interception/routing, event listening, offline mode, etc.)

Resolves #1090
Resolves #14666
Supercedes #12565

Landed upstream patches:

Pending upstream patches (to resolve the failing test cases in this PR):

Since this Playwright change opts all users in by default, but the upstream pending patch is required to fix some rare failure modes, this Playwright PR should be followed up with a minor change that guards the installation of the new instrumentation based on CR major revision.

@Meir017

Copy link
Copy Markdown
Contributor

Intercepting only requests sent from the service worker is not possible through the first condition argument, I was able to do something like this:

test('should intercept only serviceworker request, not page', async ({ context, page, }) => {
  await context.route('**/sw.js', route =>
    route.fulfill({
      contentType: 'text/javascript',
      status: 200,
      body: `
        self.addEventListener('fetch', event => {
          if (event.request.url.endsWith('/data.json')) {
            event.respondWith(fetch(event.request));
          }
        });
      `,
    })
  );
  await context.route('**/data.json', async route => {
    if (route.request().isServiceWorkerRequest()) {
      return route.fulfill({
        contentType: 'text/plain',
        status: 200,
        body: 'from sw',
      });
    } else {
      return route.continue();
    }
  })

  const [ sw ] = await Promise.all([
    context.waitForEvent('serviceworker'),
    page.goto(server.PREFIX + '/serviceworkers/empty/sw.html'),
  ]);
  const response = await page.evaluate(() => fetch('/data.json').then(r => r.text()));
  expect(response).toBe('from sw');
});

@rwoll

Copy link
Copy Markdown
Member Author

Meir Blachman (@Meir017) See this newly added test: 92e28e0#diff-f48a7787820cb49396256c1234745152eb05ca5a3f43b6d128ce0ee45eb6dff6R253

It aims to cover the intent of your scenario and passes. Notably it: (1) waits for the SW to be active, and (2) asserts the SW actually intercepted the request (according to the SW). Let me know if this covers your case!

tl;dr: I think #14321 (comment) was invalid since it didn't wait for the SW to be active, so SW wasn't yet handling your request (which was still a page req at the time and was reported as such in the context.route).

@rwoll

Copy link
Copy Markdown
Member Author

The following test has different behavior when the context.route line is commented vs. uncommented:

test.only('isServiceWorker() and serviceWorker() work', async ({ context, page, server }) => {
    // context.route('**', (route) => route.continue());
    const [worker] = await Promise.all([
      context.waitForEvent('serviceworker'),
      page.goto(server.PREFIX + '/serviceworkers/fetch/sw.html')
    ]);
    await page.evaluate(() => window['activationPromise']);
    const [swReq, frameReq] = await Promise.all([
      context.waitForEvent('request', r => r.url().endsWith('/inner.txt') && r.isServiceWorkerRequest()),
      context.waitForEvent('request', r => r.url().endsWith('/inner.txt') && !r.isServiceWorkerRequest()),
      page.evaluate(() => fetch('/inner.txt')),
    ]);
    const [ url ] = await worker.evaluate(() => self['intercepted']);
    expect(url).toMatch(/\/inner\.txt$/);
    expect(swReq.frame).toThrow();
    expect(swReq.isServiceWorkerRequest()).toBe(true);
    expect(swReq.serviceWorker()).toBe(worker);

    expect(frameReq.frame()).toBe(page.mainFrame());
    expect(frameReq.isServiceWorkerRequest()).toBe(false);
    expect(frameReq.serviceWorker()).toBe(null);
});

With the following log line:

diff --git a/packages/playwright-core/src/server/chromium/crNetworkManager.ts b/packages/playwright-core/src/server/chromium/crNetworkManager.ts
index fe1716c65..759a6c58d 100644
--- a/packages/playwright-core/src/server/chromium/crNetworkManager.ts
+++ b/packages/playwright-core/src/server/chromium/crNetworkManager.ts
@@ -348,6 +348,7 @@ export class CRNetworkManager {
     this._responseExtraInfoTracker.responseReceived(event);
 
     const request = this._requestIdToRequest.get(event.requestId);
+    console.log('eventLocation', this._serviceWorker ? 'sw' : 'page', 'fromServiceWorker:', event.response.fromServiceWorker, request?.request.url());
     // FileUpload sends a response without a matching request.
     if (!request)
       return;

We see the following with the test run as shown above:

[chromium] › library/chromium/chromium.spec.ts:42:6 › isServiceWorker() and serviceWorker() work
eventLocation page fromServiceWorker: false http://localhost:8907/serviceworkers/fetch/sw.html
eventLocation page fromServiceWorker: false http://localhost:8907/serviceworkers/fetch/style.css
eventLocation sw fromServiceWorker: false http://localhost:8907/serviceworkers/fetch/sw.js
eventLocation sw fromServiceWorker: false http://localhost:8907/request-from-within-worker.txt
eventLocation sw fromServiceWorker: false http://localhost:8907/inner.txt
eventLocation page fromServiceWorker: true http://localhost:8907/inner.txt

and the following when the context.route is added:

[chromium] › library/chromium/chromium.spec.ts:42:6 › isServiceWorker() and serviceWorker() work
eventLocation page fromServiceWorker: false http://localhost:8907/serviceworkers/fetch/sw.html
eventLocation page fromServiceWorker: false http://localhost:8907/serviceworkers/fetch/style.css
eventLocation sw fromServiceWorker: false http://localhost:8907/serviceworkers/fetch/sw.js
eventLocation sw fromServiceWorker: false http://localhost:8907/request-from-within-worker.txt
eventLocation sw fromServiceWorker: false http://localhost:8907/inner.txt
eventLocation page fromServiceWorker: true undefined

The issue likley starts earlier in _onRequestWillBeSent, but it highlights a larger fundamental issue to resolve around this feature: if a SW's fetch event handler handles a frame's request, how do we report the request(s). In the case above, the fetch requests seem "the same", but there's only one request that hits the network. Also, recall the Frame could call fetch('/foo'), and the SW could decide to:

  1. serve from cache
  2. run the fetch request as is (like in the example above)
  3. rewrite it completely and hit the network as /bar, or multiple endpoints that it then merges into one Request, etc.

In our simple example, how many times do we expect to see context.on('request', …) fire for /inner.txt? I think the answer has to be 2 times since there is no guarantee frame and SW requests map 1:1 to eachother. Given this, we have to provide enough info on our Request object:

Request
   isServiceWorkerRequest(): the network was actually engaged within the SW.
   isFromServiceWorker(): this says nothing about if the network was hit or not. It just indicates the request came from the SW (i.e. via [`respondWith`](https://developer.mozilla.org/en-US/docs/Web/API/FetchEvent/respondWith)).  

^ This is a bit of word soup for me to look at on Monday 😄

Anecdotally, it's common for users to want to disable Service Workers
while testing, so this provides a simple context option to do so.

It also prepares us to land microsoft#14321 which requires us to have a point for
folks to enable seeing Service Worker Requests as events (and allow for
routing).
@Meir017

Copy link
Copy Markdown
Contributor

tests for https://developer.mozilla.org/en-US/docs/Web/API/FetchEvent/preloadResponse would be good here, I'm not sure if these scenario will work right now but they can be added later

addEventListener("fetch", (event) => {
  event.respondWith(
    (async function () {
      // Respond from the cache if we can
      const cachedResponse = await caches.match(event.request);
      if (cachedResponse) return cachedResponse;

      // Else, use the preloaded response, if it's there
      const response = await event.preloadResponse;
      if (response) return response;

      // Else try the network.
      return fetch(event.request);
    })()
  );
});

@rwoll

Copy link
Copy Markdown
Member Author

Currently working on some of the opt-(in|out) logic. Once that's in, I'll update the description and open for review as that will be an actual candidate for landing and API review.

@rwoll
Ross Wollman (rwoll) marked this pull request as ready for review May 31, 2022 22:03
Comment thread docs/src/api/class-request.md Resolved
Comment thread utils/generate_types/overrides.d.ts Resolved
Comment thread docs/src/api/params.md Resolved
Comment thread docs/src/api/class-response.md Resolved
Comment thread docs/src/api/params.md Resolved
@rwoll

Copy link
Copy Markdown
Member Author

Closing this to chop it up into a few different PRs

Ross Wollman (rwoll) added a commit that referenced this pull request Jun 8, 2022
Ross Wollman (rwoll) added a commit that referenced this pull request Jun 8, 2022
Adds cross-browser support for easily allowing/blocking Service Workers via a Context option.

Includes plumbing for Playwright Test's `use`.

Resolves #14522.

Relates #1090.
Supercedes #14321.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[internal] Response.fullfilledByServiceWorker for FF [Feature] support route aka request interception for service workers

4 participants