Skip to content

Commit 9490c94

Browse files
committed
refactor: change e2e implementation for workers
1 parent 3310e9c commit 9490c94

File tree

5 files changed

+106
-62
lines changed

5 files changed

+106
-62
lines changed

test/e2e/lib/framework/createTest.ts

Lines changed: 25 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -13,18 +13,13 @@ import { IntakeRegistry } from './intakeRegistry'
1313
import { flushEvents } from './flushEvents'
1414
import type { Servers } from './httpServers'
1515
import { getTestServers, waitForServersIdle } from './httpServers'
16-
import type { SetupFactory, SetupOptions } from './pageSetups'
17-
import { html, DEFAULT_SETUPS, npmSetup, reactSetup } from './pageSetups'
16+
import type { SetupFactory, SetupOptions, WorkerImplementationFactory } from './pageSetups'
17+
import { workerSetup, html, DEFAULT_SETUPS, npmSetup, reactSetup } from './pageSetups'
1818
import { createIntakeServerApp } from './serverApps/intake'
1919
import { createMockServerApp } from './serverApps/mock'
2020
import type { Extension } from './createExtension'
2121
import { isBrowserStack } from './environment'
2222

23-
interface LogsWorkerOptions {
24-
importScript?: boolean
25-
nativeLog?: boolean
26-
}
27-
2823
export function createTest(title: string) {
2924
return new TestBuilder(title)
3025
}
@@ -62,8 +57,8 @@ class TestBuilder {
6257
rumConfiguration?: RumInitConfiguration
6358
logsConfiguration?: LogsInitConfiguration
6459
} = {}
65-
private useServiceWorker: boolean = false
6660
private hostName?: string
61+
private workerImplementationFactory?: (setup: string) => string
6762

6863
constructor(private title: string) {}
6964

@@ -135,37 +130,23 @@ class TestBuilder {
135130
return this
136131
}
137132

138-
withWorker({ importScript = false, nativeLog = false }: LogsWorkerOptions = {}) {
139-
if (!this.useServiceWorker) {
140-
this.useServiceWorker = true
133+
withWorker(implementation: WorkerImplementationFactory, isModule = false) {
134+
implementation.isModule = isModule
135+
this.workerImplementationFactory = implementation
141136

142-
const isModule = !importScript
143-
144-
const params = []
145-
if (importScript) {
146-
params.push('importScripts=true')
147-
}
148-
if (nativeLog) {
149-
params.push('nativeLog=true')
150-
}
137+
const options = isModule ? '{ type: "module" }' : '{}'
151138

152-
const query = params.length > 0 ? `?${params.join('&')}` : ''
153-
const url = `/sw.js${query}`
154-
155-
const options = isModule ? '{ type: "module" }' : '{}'
156-
157-
// Service workers require HTTPS or localhost due to browser security restrictions
158-
this.hostName = 'localhost'
159-
this.withBody(html`
160-
<script>
161-
if (!window.myServiceWorker && 'serviceWorker' in navigator) {
162-
navigator.serviceWorker.register('${url}', ${options}).then((registration) => {
163-
window.myServiceWorker = registration
164-
})
165-
}
166-
</script>
167-
`)
168-
}
139+
// Service workers require HTTPS or localhost due to browser security restrictions
140+
this.withHostName('localhost')
141+
this.withBody(html`
142+
<script>
143+
if (!window.myServiceWorker && 'serviceWorker' in navigator) {
144+
navigator.serviceWorker.register('/sw.js', ${options}).then((registration) => {
145+
window.myServiceWorker = registration
146+
})
147+
}
148+
</script>
149+
`)
169150

170151
return this
171152
}
@@ -194,6 +175,7 @@ class TestBuilder {
194175
testFixture: this.testFixture,
195176
extension: this.extension,
196177
hostName: this.hostName,
178+
workerImplementation: this.workerImplementationFactory,
197179
}
198180

199181
if (this.alsoRunWithRumSlim) {
@@ -270,7 +252,12 @@ function declareTest(title: string, setupOptions: SetupOptions, factory: SetupFa
270252
servers.intake.bindServerApp(createIntakeServerApp(testContext.intakeRegistry))
271253

272254
const setup = factory(setupOptions, servers)
273-
servers.base.bindServerApp(createMockServerApp(servers, setup, setupOptions.remoteConfiguration))
255+
servers.base.bindServerApp(
256+
createMockServerApp(servers, setup, {
257+
remoteConfiguration: setupOptions.remoteConfiguration,
258+
workerImplementation: setupOptions.workerImplementation && workerSetup(setupOptions, servers),
259+
})
260+
)
274261
servers.crossOrigin.bindServerApp(createMockServerApp(servers, setup))
275262

276263
await setUpTest(browserLogs, testContext)

test/e2e/lib/framework/index.ts

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,15 @@
11
export { createTest } from './createTest'
22
export { DEFAULT_RUM_CONFIGURATION, DEFAULT_LOGS_CONFIGURATION } from '../helpers/configuration'
33
export { createExtension } from './createExtension'
4-
export { bundleSetup, html, npmSetup, reactSetup, formatConfiguration, createCrossOriginScriptUrls } from './pageSetups'
4+
export {
5+
bundleSetup,
6+
html,
7+
js,
8+
npmSetup,
9+
reactSetup,
10+
formatConfiguration,
11+
createCrossOriginScriptUrls,
12+
} from './pageSetups'
513
export { IntakeRegistry } from './intakeRegistry'
614
export { getTestServers, waitForServersIdle } from './httpServers'
715
export { flushEvents } from './flushEvents'

test/e2e/lib/framework/pageSetups.ts

Lines changed: 20 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,10 @@ import { DEFAULT_LOGS_CONFIGURATION } from '../helpers/configuration'
66
import { isBrowserStack, isContinuousIntegration } from './environment'
77
import type { Servers } from './httpServers'
88

9+
export interface WorkerImplementationFactory {
10+
(setup: string): string
11+
isModule?: boolean
12+
}
913
export interface SetupOptions {
1014
rum?: RumInitConfiguration
1115
useRumSlim: boolean
@@ -27,6 +31,7 @@ export interface SetupOptions {
2731
logsConfiguration?: LogsInitConfiguration
2832
}
2933
hostName?: string
34+
workerImplementation?: WorkerImplementationFactory
3035
}
3136

3237
export interface WorkerOptions {
@@ -209,20 +214,23 @@ export function reactSetup(options: SetupOptions, servers: Servers, appName: str
209214
})
210215
}
211216

212-
export function workerSetup(options: WorkerOptions, servers: Servers) {
213-
return js`
214-
${options.importScripts ? js`importScripts('/datadog-logs.js');` : js`import '/datadog-logs.js';`}
217+
export function workerSetup(options: SetupOptions, servers: Servers) {
218+
let script = ''
219+
220+
if (!options.workerImplementation) {
221+
return script
222+
}
223+
224+
if (options.logs) {
225+
script += js`
226+
${options.workerImplementation.isModule ? js`import '/datadog-logs.js';` : js`importScripts('/datadog-logs.js');`}
215227
216228
// Initialize DD_LOGS in service worker
217-
DD_LOGS.init(${formatConfiguration({ ...DEFAULT_LOGS_CONFIGURATION, forwardConsoleLogs: 'all', forwardErrorsToLogs: true }, servers)})
218-
219-
// Handle messages from main thread
220-
self.addEventListener('message', (event) => {
221-
const message = event.data;
222-
223-
${options.nativeLog ? js`console.log(message);` : js`DD_LOGS.logger.log(message);`}
224-
});
229+
DD_LOGS.init(${formatConfiguration({ ...DEFAULT_LOGS_CONFIGURATION, ...options.logs }, servers)})
225230
`
231+
}
232+
233+
return options.workerImplementation(script)
226234
}
227235

228236
export function basePage({ header, body }: { header?: string; body?: string }) {
@@ -244,7 +252,7 @@ export function html(parts: readonly string[], ...vars: string[]) {
244252
return parts.reduce((full, part, index) => full + vars[index - 1] + part)
245253
}
246254

247-
function js(parts: readonly string[], ...vars: string[]) {
255+
export function js(parts: readonly string[], ...vars: string[]) {
248256
return parts.reduce((full, part, index) => full + vars[index - 1] + part)
249257
}
250258

test/e2e/lib/framework/serverApps/mock.ts

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -6,14 +6,19 @@ import type { RemoteConfiguration } from '@datadog/browser-rum-core'
66
import { getSdkBundlePath, getTestAppBundlePath } from '../sdkBuilds'
77
import type { MockServerApp, Servers } from '../httpServers'
88
import { DEV_SERVER_BASE_URL } from '../../helpers/playwright'
9-
import { workerSetup } from '../pageSetups'
109

1110
export const LARGE_RESPONSE_MIN_BYTE_SIZE = 100_000
1211

1312
export function createMockServerApp(
1413
servers: Servers,
1514
setup: string,
16-
remoteConfiguration?: RemoteConfiguration
15+
{
16+
remoteConfiguration,
17+
workerImplementation,
18+
}: {
19+
remoteConfiguration?: RemoteConfiguration
20+
workerImplementation?: string
21+
} = {}
1722
): MockServerApp {
1823
const app = express()
1924
let largeResponseBytesWritten = 0
@@ -46,11 +51,7 @@ export function createMockServerApp(
4651
})
4752

4853
app.get('/sw.js', (_req, res) => {
49-
const query = _req.query
50-
51-
res
52-
.contentType('application/javascript')
53-
.send(workerSetup({ importScripts: Boolean(query.importScripts), nativeLog: Boolean(query.nativeLog) }, servers))
54+
res.contentType('application/javascript').send(workerImplementation)
5455
})
5556

5657
function generateLargeResponse(res: ServerResponse, chunkText: string) {

test/e2e/scenario/logs.scenario.ts

Lines changed: 44 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import { DEFAULT_REQUEST_ERROR_RESPONSE_LENGTH_LIMIT } from '@datadog/browser-logs/cjs/domain/configuration'
22
import { test, expect } from '@playwright/test'
3-
import { createTest } from '../lib/framework'
3+
import { createTest, js } from '../lib/framework'
44
import { APPLICATION_ID } from '../lib/helpers/configuration'
55

66
const UNREACHABLE_URL = 'http://localhost:9999/unreachable'
@@ -13,7 +13,21 @@ declare global {
1313

1414
test.describe('logs', () => {
1515
createTest('service worker with worker logs - esm')
16-
.withWorker()
16+
.withLogs()
17+
.withWorker(
18+
(setup) => js`
19+
// Initialize DD_LOGS in service worker
20+
${setup}
21+
22+
// Handle messages from main thread
23+
self.addEventListener('message', (event) => {
24+
const message = event.data;
25+
26+
DD_LOGS.logger.log(message);
27+
});
28+
`,
29+
true
30+
)
1731
.run(async ({ flushEvents, intakeRegistry, browserName, interactWithWorker }) => {
1832
test.skip(browserName !== 'chromium', 'Non-Chromium browsers do not support ES modules in Service Workers')
1933

@@ -28,7 +42,20 @@ test.describe('logs', () => {
2842
})
2943

3044
createTest('service worker with worker logs - importScripts')
31-
.withWorker({ importScript: true })
45+
.withLogs()
46+
.withWorker(
47+
(setup) => js`
48+
// Initialize DD_LOGS in service worker
49+
${setup}
50+
51+
// Handle messages from main thread
52+
self.addEventListener('message', (event) => {
53+
const message = event.data;
54+
55+
DD_LOGS.logger.log(message);
56+
});
57+
`
58+
)
3259
.run(async ({ flushEvents, intakeRegistry, browserName, interactWithWorker }) => {
3360
test.skip(
3461
browserName === 'webkit',
@@ -46,7 +73,20 @@ test.describe('logs', () => {
4673
})
4774

4875
createTest('service worker console forwarding')
49-
.withWorker({ importScript: true, nativeLog: true })
76+
.withLogs({ forwardConsoleLogs: 'all', forwardErrorsToLogs: true })
77+
.withWorker(
78+
(setup) => js`
79+
// Initialize DD_LOGS in service worker
80+
${setup}
81+
82+
// Handle messages from main thread
83+
self.addEventListener('message', (event) => {
84+
const message = event.data;
85+
86+
console.log(message);
87+
});
88+
`
89+
)
5090
.run(async ({ flushEvents, intakeRegistry, interactWithWorker, browserName }) => {
5191
test.skip(
5292
browserName === 'webkit',

0 commit comments

Comments
 (0)