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

perf: support activated service worker that is not handling requests #29349

Merged
merged 41 commits into from
Apr 23, 2024
Merged
Show file tree
Hide file tree
Changes from 24 commits
Commits
Show all changes
41 commits
Select commit Hold shift + click to select a range
c8f3cfa
updating controlledUrls
mschile Apr 7, 2024
fe79da5
updating to start handling requests
mschile Apr 8, 2024
fa9bc30
updating workflow [run ci]
mschile Apr 8, 2024
5e08502
bump cache
mschile Apr 8, 2024
49febb1
commenting out assertion
mschile Apr 8, 2024
4de2375
await clients.claim [run ci]
mschile Apr 8, 2024
67db370
fixing ci build issue [run ci]
mschile Apr 9, 2024
17c15e8
overriding clients.claim
mschile Apr 9, 2024
7958bb8
handling document requests [run ci]
mschile Apr 10, 2024
8b0caab
adding document check [run ci]
mschile Apr 11, 2024
49c29b3
updates
mschile Apr 12, 2024
fa06db9
updates
mschile Apr 12, 2024
446d5ea
updating workflow
mschile Apr 12, 2024
49b6a7d
skip injection for non-chromium browsers
mschile Apr 16, 2024
1b18303
Merge branch 'develop' into mschile/service_worker_uncontrolled
mschile Apr 17, 2024
c25d535
adding driver test
mschile Apr 17, 2024
b2f64ec
Merge branch 'develop' into mschile/service_worker_uncontrolled
mschile Apr 17, 2024
6bbb116
updating failed tests
mschile Apr 17, 2024
2275a4b
Merge branch 'mschile/service_worker_uncontrolled' of https://github.…
mschile Apr 17, 2024
c47a777
unit test updates
mschile Apr 18, 2024
e7962ed
update
mschile Apr 18, 2024
6fea57d
updating changelog
mschile Apr 18, 2024
d278c47
update changelog
mschile Apr 18, 2024
0ee0c45
Merge branch 'develop' into mschile/service_worker_uncontrolled
mschile Apr 18, 2024
b988108
Merge branch 'develop' into mschile/service_worker_uncontrolled
jennifer-shehane Apr 19, 2024
0b7c585
Apply suggestions from code review
mschile Apr 19, 2024
9ee2791
support redirected requests
mschile Apr 20, 2024
1a5bcb9
Apply suggestions from code review
mschile Apr 22, 2024
f73daf5
Update packages/proxy/test/unit/http/util/service-worker-manager.spec.ts
mschile Apr 22, 2024
a9c1c49
fixing type issue
mschile Apr 22, 2024
88474d3
revert stop only change
mschile Apr 22, 2024
328bdd1
Merge branch 'develop' into mschile/service_worker_uncontrolled
mschile Apr 22, 2024
0e80622
Merge branch 'develop' into mschile/service_worker_uncontrolled
jennifer-shehane Apr 22, 2024
1cedbc4
updating cache version
mschile Apr 22, 2024
a276cfc
update
mschile Apr 23, 2024
fc74262
Merge branch 'develop' into mschile/service_worker_uncontrolled
jennifer-shehane Apr 23, 2024
f3e9fbe
reset pendingPreRequestsToRemove
mschile Apr 23, 2024
bc767fd
sweep pendingPreRequestsToRemove
mschile Apr 23, 2024
7c15d36
Merge branch 'develop' into mschile/service_worker_uncontrolled
jennifer-shehane Apr 23, 2024
48d2525
adding timeout
mschile Apr 23, 2024
d13e2e4
Merge branch 'develop' into mschile/service_worker_uncontrolled
mschile Apr 23, 2024
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
26 changes: 9 additions & 17 deletions .circleci/workflows.yml
Original file line number Diff line number Diff line change
Expand Up @@ -29,10 +29,7 @@ mainBuildFilters: &mainBuildFilters
- develop
- /^release\/\d+\.\d+\.\d+$/
# use the following branch as well to ensure that v8 snapshot cache updates are fully tested
- 'cacie/dep/electron-27'
- 'feat/protocol_shadow_dom_support'
- 'publish-binary'
- 'em/circle2'
- 'update-v8-snapshot-cache-on-develop'

# usually we don't build Mac app - it takes a long time
# but sometimes we want to really confirm we are doing the right thing
Expand All @@ -43,9 +40,7 @@ macWorkflowFilters: &darwin-workflow-filters
- equal: [ develop, << pipeline.git.branch >> ]
# use the following branch as well to ensure that v8 snapshot cache updates are fully tested
- equal: [ 'update-v8-snapshot-cache-on-develop', << pipeline.git.branch >> ]
- equal: [ 'cacie/dep/electron-27', << pipeline.git.branch >> ]
- equal: [ 'feat/protocol_shadow_dom_support', << pipeline.git.branch >> ]
- equal: [ 'feat/support_wds5', << pipeline.git.branch >> ]
- equal: [ 'mschile/service_worker_uncontrolled', << pipeline.git.branch >> ]
- matches:
pattern: /^release\/\d+\.\d+\.\d+$/
value: << pipeline.git.branch >>
Expand All @@ -56,9 +51,7 @@ linuxArm64WorkflowFilters: &linux-arm64-workflow-filters
- equal: [ develop, << pipeline.git.branch >> ]
# use the following branch as well to ensure that v8 snapshot cache updates are fully tested
- equal: [ 'update-v8-snapshot-cache-on-develop', << pipeline.git.branch >> ]
- equal: [ 'cacie/dep/electron-27', << pipeline.git.branch >> ]
- equal: [ 'feat/support_wds5', << pipeline.git.branch >> ]
- equal: [ 'em/circle2', << pipeline.git.branch >> ]
- equal: [ 'mschile/service_worker_uncontrolled', << pipeline.git.branch >> ]
- matches:
pattern: /^release\/\d+\.\d+\.\d+$/
value: << pipeline.git.branch >>
Expand All @@ -81,10 +74,7 @@ windowsWorkflowFilters: &windows-workflow-filters
- equal: [ develop, << pipeline.git.branch >> ]
# use the following branch as well to ensure that v8 snapshot cache updates are fully tested
- equal: [ 'update-v8-snapshot-cache-on-develop', << pipeline.git.branch >> ]
- equal: [ 'cacie/dep/electron-27', << pipeline.git.branch >> ]
- equal: [ 'feat/protocol_shadow_dom_support', << pipeline.git.branch >> ]
- equal: [ 'lerna-optimize-tasks', << pipeline.git.branch >> ]
- equal: [ 'feat/support_wds5', << pipeline.git.branch >> ]
- equal: [ 'mschile/service_worker_uncontrolled', << pipeline.git.branch >> ]
- matches:
pattern: /^release\/\d+\.\d+\.\d+$/
value: << pipeline.git.branch >>
Expand Down Expand Up @@ -151,7 +141,7 @@ commands:
name: Set environment variable to determine whether or not to persist artifacts
command: |
echo "Setting SHOULD_PERSIST_ARTIFACTS variable"
echo 'if ! [[ "$CIRCLE_BRANCH" != "develop" && "$CIRCLE_BRANCH" != "release/"* && "$CIRCLE_BRANCH" != "publish-binary" && "$CIRCLE_BRANCH" != "feat/protocol_shadow_dom_support" && "$CIRCLE_BRANCH" != "feat/support_wds5" ]]; then
echo 'if ! [[ "$CIRCLE_BRANCH" != "develop" && "$CIRCLE_BRANCH" != "release/"* && "$CIRCLE_BRANCH" != "mschile/service_worker_uncontrolled" ]]; then
export SHOULD_PERSIST_ARTIFACTS=true
fi' >> "$BASH_ENV"
# You must run `setup_should_persist_artifacts` command and be using bash before running this command
Expand Down Expand Up @@ -453,8 +443,10 @@ commands:
command: yarn versions
- unless:
condition:
# stop-only does not correctly match on windows: https://github.com/bahmutov/stop-only/issues/78
equal: [ *windows-executor, << parameters.executor >> ]
or:
# stop-only does not correctly match on windows: https://github.com/bahmutov/stop-only/issues/78
mschile marked this conversation as resolved.
Show resolved Hide resolved
- equal: [ *windows-executor, << parameters.executor >> ]
- equal: [ *darwin-arm64-executor, << parameters.executor >> ]
steps:
- run:
name: Stop .only
Expand Down
4 changes: 4 additions & 0 deletions cli/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@ _Released 4/23/2024 (PENDING)_

- Added support for `webpack-dev-server` `v5` to `@cypress/webpack-dev-server`. Addresses [#29305](https://github.com/cypress-io/cypress/issues/29305).

**Performance:**

- Fixed a performance issue with activated service workers that aren't controlling clients which could lead to correlation timeouts. Fixes [#29333](https://github.com/cypress-io/cypress/issues/29333) and [#29126](https://github.com/cypress-io/cypress/issues/29126).

**Misc:**

- We now capture the [Semaphore](https://semaphoreci.com/) CI provider's environment variable [`SEMAPHORE_GIT_PR_NUMBER`](https://docs.semaphoreci.com/ci-cd-environment/environment-variables/#semaphore_git_pr_number) to display the linked PR number in the Cloud. Addressed in [#29314](https://github.com/cypress-io/cypress/pull/29314).
Expand Down
18 changes: 18 additions & 0 deletions packages/driver/cypress/e2e/e2e/service-worker.cy.js
Original file line number Diff line number Diff line change
Expand Up @@ -666,4 +666,22 @@ describe('service workers', { defaultCommandTimeout: 1000, pageLoadTimeout: 1000
cy.get('#output').should('have.text', 'done')
validateFetchHandlers({ listenerCount: 1 })
})

it('supports a service worker that is activated but not handling fetch events', () => {
const script = () => {
self.addEventListener('fetch', function (event) {
event.respondWith(fetch(event.request))
})
}

cy.intercept('/fixtures/service-worker.js', (req) => {
req.reply(`(${script})()`,
{ 'Content-Type': 'application/javascript' })
})

cy.visit('fixtures/service-worker.html?skipReload')

cy.get('#output').should('have.text', 'done')
validateFetchHandlers({ listenerCount: 1 })
})
})
13 changes: 10 additions & 3 deletions packages/driver/cypress/fixtures/service-worker.html
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
<title></title>
<script>
const makeRequest = () => {
fetch(`/fixtures/1mb?j=${Math.random()}`).then((response) => {
fetch(`/fixtures/1mb?j=${Math.random()}#hash`).then((response) => {
document.getElementById('output').innerText = 'done'
}).catch(() => {})
}
Expand All @@ -14,15 +14,22 @@
const serviceWorker = registration.installing || registration.waiting
if (serviceWorker) {
let controllerChangeCalled = false
// called when clients.claim() is called in the service worker
navigator.serviceWorker.addEventListener('controllerchange', (e) => {
controllerChangeCalled = true
makeRequest()
})

serviceWorker.addEventListener('statechange', (e) => {
if (e.target.state === 'activated' && !controllerChangeCalled) {
// service worker activated, reload page so it can intercept requests
location.reload()
// service worker activated, either skip reloading the page
// so we can test when an activated service worker is not intercepting requests
// or reload page so it can intercept requests
mschile marked this conversation as resolved.
Show resolved Hide resolved
if (location.search.includes('skipReload')) {
makeRequest()
} else {
location.reload()
}
}
})
} else {
Expand Down
6 changes: 5 additions & 1 deletion packages/proxy/lib/http/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ import type { Request, Response } from 'express'
import type { RemoteStates } from '@packages/server/lib/remote_states'
import type { CookieJar, SerializableAutomationCookie } from '@packages/server/lib/util/cookies'
import type { ResourceTypeAndCredentialManager } from '@packages/server/lib/util/resourceTypeAndCredentialManager'
import type { ProtocolManagerShape } from '@packages/types'
import type { FoundBrowser, ProtocolManagerShape } from '@packages/types'
import type Protocol from 'devtools-protocol'
import type { ServiceWorkerClientEvent } from './util/service-worker-manager'

Expand Down Expand Up @@ -101,6 +101,7 @@ export type ServerCtx = Readonly<{
socket: CyServer.Socket
request: any
serverBus: EventEmitter
getCurrentBrowser: () => FoundBrowser
}>

const READONLY_MIDDLEWARE_KEYS: (keyof HttpMiddlewareThis<{}>)[] = [
Expand Down Expand Up @@ -272,6 +273,7 @@ export class Http {
middleware: HttpMiddlewareStacks
netStubbingState: NetStubbingState
preRequests: PreRequests = new PreRequests()
getCurrentBrowser: () => FoundBrowser
request: any
socket: CyServer.Socket
serverBus: EventEmitter
Expand All @@ -296,6 +298,7 @@ export class Http {
this.serverBus = opts.serverBus
this.resourceTypeAndCredentialManager = opts.resourceTypeAndCredentialManager
this.getCookieJar = opts.getCookieJar
this.getCurrentBrowser = opts.getCurrentBrowser

if (typeof opts.middleware === 'undefined') {
this.middleware = defaultMiddleware
Expand Down Expand Up @@ -361,6 +364,7 @@ export class Http {
this.preRequests.removePendingRequest(pendingRequest)
},
protocolManager: this.protocolManager,
getCurrentBrowser: this.getCurrentBrowser,
}

const onError = (error: Error): Promise<void> => {
Expand Down
3 changes: 2 additions & 1 deletion packages/proxy/lib/http/response-middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -839,7 +839,8 @@ const MaybeInjectServiceWorker: ResponseMiddleware = function () {

span?.setAttributes({ hasServiceWorkerHeader: hasHeader })

if (!hasHeader) {
// skip if we don't have the header or we're not in chromium
if (!hasHeader || this.getCurrentBrowser().family !== 'chromium') {
span?.end()

return this.next()
Expand Down
40 changes: 39 additions & 1 deletion packages/proxy/lib/http/util/prerequests.ts
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,7 @@ export class PreRequests {
pendingPreRequests = new QueueMap<PendingPreRequest>()
pendingRequests = new QueueMap<PendingRequest>()
pendingUrlsWithoutPreRequests = new QueueMap<PendingUrlWithoutPreRequest>()
pendingPreRequestsToRemove: Set<string> = new Set()
sweepIntervalTimer: NodeJS.Timeout
protocolManager?: ProtocolManagerShape

Expand Down Expand Up @@ -144,6 +145,8 @@ export class PreRequests {
debugVerbose('timed out unmatched pre-request: %o', browserPreRequest)
metrics.unmatchedPreRequests++

this.pendingPreRequestsToRemove.delete(browserPreRequest.requestId)

return false
}

Expand All @@ -156,9 +159,23 @@ export class PreRequests {
}, this.sweepInterval)
}

checkAndRemovePendingPreRequest (requestId: string) {
return this.pendingPreRequestsToRemove.delete(requestId)
}

addPending (browserPreRequest: BrowserPreRequest) {
const key = `${browserPreRequest.method}-${tryDecodeURI(browserPreRequest.url)}`

// if we have a pending request to remove, we should remove it now and return
// since we don't want to proceed with this pre-request anymore. In practice,
// this typically happens when we receive a cached response while executing
// the async function to add the pre-request
if (this.checkAndRemovePendingPreRequest(browserPreRequest.requestId)) {
debugVerbose('Received previous request to remove pre-request %s, skipping adding', browserPreRequest.requestId)

return
}

metrics.browserPreRequestsReceived++
const pendingRequest = this.pendingRequests.shift(key)

Expand Down Expand Up @@ -225,9 +242,30 @@ export class PreRequests {
}

removePendingPreRequest (requestId: string) {
let removed = false

this.pendingPreRequests.removeMatching(({ browserPreRequest }) => {
return (browserPreRequest.requestId.includes('-retry-') && !browserPreRequest.requestId.startsWith(`${requestId}-`)) || (!browserPreRequest.requestId.includes('-retry-') && browserPreRequest.requestId !== requestId)
const matches = (browserPreRequest.requestId.includes('-retry-') && browserPreRequest.requestId.startsWith(`${requestId}-`)) ||
(!browserPreRequest.requestId.includes('-retry-') && browserPreRequest.requestId === requestId)

if (matches && !removed) {
removed = true
}

return !matches
})

// if we didn't find a pre-request to remove, add it to the pending list so we can remove it later,
// this typically happens when we receive a cached response while executing
// the async function to add the pre-request
if (!removed) {
debugVerbose('No pre-request found to remove, adding to pending list: %s', requestId)
this.pendingPreRequestsToRemove.add(requestId)
} else {
debugVerbose('Removed pre-request %s', requestId)
}

return removed
}

get (req: CypressIncomingRequest, ctxDebug, callback: GetPreRequestCb) {
Expand Down
Loading
Loading