-
Notifications
You must be signed in to change notification settings - Fork 190
Expand file tree
/
Copy pathmock.ts
More file actions
276 lines (236 loc) · 8.72 KB
/
Copy pathmock.ts
File metadata and controls
276 lines (236 loc) · 8.72 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
import type { ServerResponse } from 'http'
import * as url from 'url'
import cors from 'cors'
import qs from 'qs'
import express from 'express'
import { getSdkBundlePath, getTestAppBundlePath } from '../sdkBuilds'
import type { MockServerApp, Servers } from '../httpServers'
import { DEV_SERVER_BASE_URL } from '../../helpers/playwright'
import type { SetupOptions } from '../pageSetups'
import { workerSetup } from '../pageSetups'
export const LARGE_RESPONSE_MIN_BYTE_SIZE = 100_000
export function createMockServerApp(servers: Servers, setup: string, setupOptions?: SetupOptions): MockServerApp {
const { remoteConfiguration, worker } = setupOptions ?? {}
const app = express()
let largeResponseBytesWritten = 0
app.use(cors())
app.disable('etag') // disable automatic resource caching
app.set('query parser', (str: string) => qs.parse(str))
app.get('/empty', (_req, res) => {
res.end()
})
app.get('/favicon.ico', (_req, res) => {
res.end()
})
app.get('/throw', (_req, res) => {
res.status(500).send('Server error')
})
app.get('/throw-large-response', (_req, res) => {
res.status(500)
const chunkText = 'Server error\n'.repeat(50)
generateLargeResponse(res, chunkText)
})
app.get('/large-response', (_req, res) => {
const chunkText = 'foofoobarbar\n'.repeat(50)
generateLargeResponse(res, chunkText)
})
app.get('/sw.js', (_req, res) => {
res.contentType('application/javascript').send(
workerSetup(
{
...setupOptions!,
worker: { ...worker, importScripts: Boolean(_req.query.importScripts) },
},
servers
)
)
})
function generateLargeResponse(res: ServerResponse, chunkText: string) {
let bytesWritten = 0
let timeoutId: NodeJS.Timeout
res.on('close', () => {
largeResponseBytesWritten = bytesWritten
clearTimeout(timeoutId)
})
function writeMore() {
res.write(chunkText, (error) => {
if (error) {
console.log('Write error', error)
} else {
bytesWritten += chunkText.length
if (bytesWritten < LARGE_RESPONSE_MIN_BYTE_SIZE) {
timeoutId = setTimeout(writeMore, 10)
} else {
res.end()
}
}
})
}
writeMore()
}
app.get('/unknown', (_req, res) => {
res.status(404).send('Not found')
})
app.get('/empty.css', (_req, res) => {
// 50ms delay: WebKit clamps PerformanceResourceTiming timestamps to 1ms. Without a delay,
// a zero-byte response on fast (Linux CI) loopback occasionally completes within a single
// tick, collapsing every timestamp to the same value and making the SDK report duration: 0
// — which made `rum resources › retrieve early requests timings` the top flaky E2E this week.
setTimeout(() => res.header('content-type', 'text/css').end(), 50)
})
app.get('/flush', (_req, res) => {
// The RUM session replay recorder uses a Web Worker to format request data, so it cannot send
// its last segment during the "beforeunload" event — only a few milliseconds after. If the next
// page loads too quickly, the segment may be lost. /flush responds after 200ms to give the
// recorder time to send, and returns HTML with an empty favicon to avoid a spurious favicon request.
setTimeout(() => res.send('<!doctype html><html><head><link rel="icon" href="data:,"/></head></html>'), 200)
})
app.all('/ok', (req, res) => {
// Express will automatically append charset to the Content-Type header
res.header('Content-Type', 'text/plain')
if (req.query['timing-allow-origin'] === 'true') {
res.set('Timing-Allow-Origin', '*')
}
const responseHeaders = req.query['response-headers']
if (responseHeaders) {
for (const [header, value] of Object.entries(responseHeaders)) {
if (typeof value === 'string') {
res.header(header, value)
}
}
}
const timeoutDuration = req.query.duration ? Number(req.query.duration) : 0
setTimeout(() => res.send('ok'), timeoutDuration)
})
app.post('/graphql', (req, res) => {
res.header('Content-Type', 'application/json')
const scenario = req.query.scenario as string | undefined
if (scenario === 'validation-error') {
res.json({
data: null,
errors: [
{
message: 'Field "unknownField" does not exist',
extensions: { code: 'GRAPHQL_VALIDATION_FAILED' },
locations: [{ line: 2, column: 5 }],
path: ['user', 'unknownField'],
},
],
})
} else if (scenario === 'multiple-errors') {
res.json({
data: { user: null },
errors: [
{ message: 'User not found' },
{ message: 'Insufficient permissions', extensions: { code: 'UNAUTHORIZED' } },
],
})
} else {
res.json({ data: { result: 'success' } })
}
})
app.get('/graphql', (_req, res) => {
res.header('Content-Type', 'application/json')
res.json({ data: { result: 'success' } })
})
app.get('/redirect', (req, res) => {
const redirectUri = url.parse(req.originalUrl)
res.redirect(`ok${redirectUri.search!}`)
})
app.get('/headers', (req, res) => {
res.send(JSON.stringify(req.headers))
})
app.get('/', (req, res) => {
res.header(
'Content-Security-Policy',
[
`connect-src ${servers.datadogHttpApi.origin} ${servers.base.origin} ${servers.crossOrigin.origin} https://quota.browser-intake-datadoghq.com`,
`script-src 'self' 'unsafe-inline' ${servers.crossOrigin.origin}`,
"worker-src blob: 'self'",
].join(';')
)
if (req.query['js-profiling'] === 'true') {
res.header('Document-Policy', 'js-profiling')
}
if (req.query['network-efficiency-guardrails'] === 'true') {
res.header('Document-Policy', 'network-efficiency-guardrails')
}
res.send(setup)
res.end()
})
// Serves an uncompressed JavaScript file large enough to trigger a network-efficiency-guardrails
// policy violation (text resources must be HTTP-compressed).
app.get('/uncompressed-script.js', (_req, res) => {
res.removeHeader('Content-Encoding')
res.header('Content-Type', 'application/javascript')
// Explicitly disable compression for this endpoint so the browser detects a violation
res.header('Cache-Control', 'no-store')
res.send(`// uncompressed script\n${'// padding\n'.repeat(500)}`)
})
app.get('/no-blob-worker-csp', (_req, res) => {
res.header(
'Content-Security-Policy',
[
`connect-src ${servers.datadogHttpApi.origin} ${servers.base.origin} ${servers.crossOrigin.origin} https://quota.browser-intake-datadoghq.com`,
`script-src 'self' 'unsafe-inline' ${servers.crossOrigin.origin}`,
].join(';')
)
res.send(setup)
res.end()
})
app.get(/datadog-(?<packageName>[a-z-]*)\.js/, (req, res) => {
const { originalUrl, params } = req
if (process.env.CI) {
res.sendFile(getSdkBundlePath(`browser-${params.packageName}`, originalUrl))
} else {
forwardToDevServer(req.originalUrl, res)
}
})
app.get('/worker.js', (req, res) => {
if (process.env.CI) {
res.sendFile(getSdkBundlePath('browser-worker', req.originalUrl))
} else {
forwardToDevServer(req.originalUrl, res)
}
})
app.get(/(?<appName>app|react-[\w-]+|angular-[\w-]+|tanstack-[\w-]+).js$/, (req, res) => {
const { originalUrl, params } = req
res.sendFile(getTestAppBundlePath(params.appName, originalUrl))
})
app.get(/^\/microfrontend\/.*/, (req, res) => {
const { originalUrl } = req
// Remove the /microfrontend prefix from the URL since getTestAppBundlePath adds the app path
const filePath = originalUrl.replace(/^\/microfrontend/, '')
res.sendFile(getTestAppBundlePath('microfrontend', filePath))
})
app.get('/config', (_req, res) => {
res.send(JSON.stringify(remoteConfiguration))
})
return Object.assign(app, {
getLargeResponseWroteSize() {
return largeResponseBytesWritten
},
})
}
// We fetch and pipe the file content instead of redirecting to avoid creating different behavior between CI and local dev
// This way both environments serve the files from the same origin with the same CSP rules
function forwardToDevServer(originalUrl: string, res: ServerResponse) {
const url = `${DEV_SERVER_BASE_URL}${originalUrl}`
fetch(url)
.then(({ body, headers }) => {
void body?.pipeTo(
new WritableStream({
start() {
headers.forEach((value, key) => res.setHeader(key, value))
},
write(chunk) {
res.write(chunk)
},
close() {
res.end()
},
})
)
})
.catch(() => console.error(`Error fetching ${url}, did you run 'yarn dev'?`))
}