-
-
Notifications
You must be signed in to change notification settings - Fork 736
/
Copy pathrecorder.js
401 lines (366 loc) · 8.85 KB
/
recorder.js
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
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
const debug = require('debug')('codeceptjs:recorder')
const promiseRetry = require('promise-retry')
const chalk = require('chalk')
const { printObjectProperties } = require('./utils')
const { log } = require('./output')
const { TimeoutError } = require('./timeout')
const MAX_TASKS = 100
let promise
let running = false
let errFn
let queueId = 0
let sessionId = null
let asyncErr = null
let ignoredErrs = []
let tasks = []
let oldPromises = []
const defaultRetryOptions = {
retries: 0,
minTimeout: 150,
maxTimeout: 10000,
}
/**
* Singleton object to record all test steps as promises and run them in chain.
* @alias recorder
* @interface
*/
module.exports = {
/**
* @type {Array<Object<string, *>>}
* @inner
*/
retries: [],
/**
* Start recording promises
*
* @api
* @inner
*/
start() {
debug('Starting recording promises')
running = true
asyncErr = null
errFn = null
this.reset()
},
/**
* @return {boolean}
* @inner
*/
isRunning() {
return running
},
/**
* @return {void}
* @inner
*/
startUnlessRunning() {
if (!this.isRunning()) {
this.start()
}
},
/**
* Add error handler to catch rejected promises
*
* @api
* @param {function} fn
* @inner
*/
errHandler(fn) {
errFn = fn
},
/**
* Stops current promise chain, calls `catch`.
* Resets recorder to initial state.
*
* @api
* @inner
*/
reset() {
if (promise && running) this.catch()
queueId++
sessionId = null
asyncErr = null
log(`${currentQueue()} Starting recording promises`)
promise = Promise.resolve()
oldPromises = []
tasks = []
ignoredErrs = []
this.session.running = false
// reset this retries makes the retryFailedStep plugin won't work if there is Before/BeforeSuit block due to retries is undefined on Scenario
// this.retries = [];
},
/**
* @name CodeceptJS.recorder~session
* @type {CodeceptJS.RecorderSession}
* @inner
*/
/**
* @alias RecorderSession
* @interface
*/
session: {
/**
* @type {boolean}
* @inner
*/
running: false,
/**
* @param {string} name
* @inner
*/
start(name) {
if (sessionId) {
debug(`${currentQueue()}Session already started as ${sessionId}`)
this.restore(sessionId)
}
debug(`${currentQueue()}Starting <${name}> session`)
tasks.push('--->')
oldPromises.push(promise)
this.running = true
sessionId = name
promise = Promise.resolve()
},
/**
* @param {string} [name]
* @inner
*/
restore(name) {
tasks.push('<---')
debug(`${currentQueue()}Finalize <${name}> session`)
this.running = false
sessionId = null
this.catch(errFn)
promise = promise.then(() => oldPromises.pop())
},
/**
* @param {function} fn
* @inner
*/
catch(fn) {
promise = promise.catch(fn)
},
},
/**
* Adds a promise to a chain.
* Promise description should be passed as first parameter.
*
* @param {string|function} taskName
* @param {function} [fn]
* @param {boolean} [force=false]
* @param {boolean} [retry]
* undefined: `add(fn)` -> `false` and `add('step',fn)` -> `true`
* true: it will retries if `retryOpts` set.
* false: ignore `retryOpts` and won't retry.
* @param {number} [timeout]
* @return {Promise<*>}
* @inner
*/
add(taskName, fn = undefined, force = false, retry = undefined, timeout = undefined) {
if (typeof taskName === 'function') {
fn = taskName
taskName = fn.toString()
if (retry === undefined) retry = false
}
if (retry === undefined) retry = true
if (!running && !force) {
return Promise.resolve()
}
tasks.push(taskName)
debug(chalk.gray(`${currentQueue()} Queued | ${taskName}`))
return (promise = Promise.resolve(promise).then(res => {
// prefer options for non-conditional retries
const retryOpts = this.retries
.sort((r1, r2) => r1.when && !r2.when)
.slice(-1)
.pop()
// no retries or unnamed tasks
debug(`${currentQueue()} Running | ${taskName} | Timeout: ${timeout || 'None'}`)
if (retryOpts) debug(`${currentQueue()} Retry opts`, JSON.stringify(retryOpts))
if (!retryOpts || !taskName || !retry) {
const [promise, timer] = getTimeoutPromise(timeout, taskName)
return Promise.race([promise, Promise.resolve(res).then(fn)]).finally(() => clearTimeout(timer))
}
const retryRules = this.retries.slice().reverse()
return promiseRetry(Object.assign(defaultRetryOptions, retryOpts), (retry, number) => {
if (number > 1) log(`${currentQueue()}Retrying... Attempt #${number}`)
const [promise, timer] = getTimeoutPromise(timeout, taskName)
return Promise.race([promise, Promise.resolve(res).then(fn)])
.finally(() => clearTimeout(timer))
.catch(err => {
if (ignoredErrs.includes(err)) return
for (const retryObj of retryRules) {
if (!retryObj.when) return retry(err)
if (retryObj.when && retryObj.when(err)) return retry(err)
}
throw err
})
})
}))
},
/**
* @param {*} opts
* @return {*}
* @inner
*/
retry(opts) {
if (!promise) return
if (opts === null) {
opts = {}
}
if (Number.isInteger(opts)) {
opts = { retries: opts }
}
return this.add(() => this.retries.push(opts))
},
/**
* @param {function} [customErrFn]
* @return {Promise<*>}
* @inner
*/
catch(customErrFn) {
const fnDescription = customErrFn
?.toString()
?.replace(/\s{2,}/g, ' ')
.replace(/\n/g, ' ')
?.slice(0, 50)
debug(chalk.gray(`${currentQueue()} Queued | catch with error handler ${fnDescription || ''}`))
return (promise = promise.catch(err => {
log(`${currentQueue()}Error | ${err} ${fnDescription}...`)
if (!(err instanceof Error)) {
// strange things may happen
err = new Error(`[Wrapped Error] ${printObjectProperties(err)}`) // we should be prepared for them
}
if (customErrFn) {
customErrFn(err)
} else if (errFn) {
errFn(err)
}
this.stop()
}))
},
/**
* @param {function} customErrFn
* @return {Promise<*>}
* @inner
*/
catchWithoutStop(customErrFn) {
const fnDescription = customErrFn
?.toString()
?.replace(/\s{2,}/g, ' ')
.replace(/\n/g, ' ')
?.slice(0, 50)
return (promise = promise.catch(err => {
if (ignoredErrs.includes(err)) return // already caught
log(`${currentQueue()} Error (Non-Terminated) | ${err} | ${fnDescription || ''}...`)
if (!(err instanceof Error)) {
// strange things may happen
err = new Error(`[Wrapped Error] ${JSON.stringify(err)}`) // we should be prepared for them
}
if (customErrFn) {
return customErrFn(err)
}
}))
},
/**
* Adds a promise which throws an error into a chain
*
* @api
* @param {*} err
* @inner
*/
throw(err) {
if (ignoredErrs.includes(err)) return promise // already caught
return this.add(`throw error: ${err.message}`, () => {
if (ignoredErrs.includes(err)) return // already caught
throw err
})
},
ignoreErr(err) {
ignoredErrs.push(err)
},
/**
* @param {*} err
* @inner
*/
saveFirstAsyncError(err) {
if (asyncErr === null) {
asyncErr = err
}
},
/**
* @return {*}
* @inner
*/
getAsyncErr() {
return asyncErr
},
/**
* @return {void}
* @inner
*/
cleanAsyncErr() {
asyncErr = null
},
/**
* Stops recording promises
* @api
* @inner
*/
stop() {
debug(this.toString())
log(`${currentQueue()} Stopping recording promises`)
running = false
},
/**
* Get latest promise in chain.
*
* @api
* @return {Promise<*>}
* @inner
*/
promise() {
return promise
},
/**
* Get a list of all chained tasks
* @return {string}
* @inner
*/
scheduled() {
return tasks.slice(-MAX_TASKS).join('\n')
},
/**
* Get the queue id
* @return {number}
* @inner
*/
getQueueId() {
return queueId
},
/**
* Get a state of current queue and tasks
* @return {string}
* @inner
*/
toString() {
return `Queue: ${currentQueue()}\n\nTasks: ${this.scheduled()}`
},
}
function getTimeoutPromise(timeoutMs, taskName) {
let timer
if (timeoutMs) debug(`Timing out in ${timeoutMs}ms`)
return [
new Promise((done, reject) => {
timer = setTimeout(() => {
reject(new TimeoutError(`Action ${taskName} was interrupted on timeout ${timeoutMs}ms`))
}, timeoutMs || 2e9)
}),
timer,
]
}
function currentQueue() {
let session = ''
if (sessionId) session = `<${sessionId}> `
return `[${queueId}] ${session}`
}