-
Notifications
You must be signed in to change notification settings - Fork 42
/
worker.js
73 lines (57 loc) · 1.6 KB
/
worker.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
'use strict'
// this worker simulates a background job that uses custom transactions
const apm = require('elastic-apm-node')
let running = false
exports.start = function () {
running = true
queue(processPayment)
queue(processCompletedOrder)
queue(updateShippingStatus)
}
exports.stop = function () {
running = false
}
function processPayment () {
if (!running) return
apm.startTransaction('Process payment', 'Worker')
performSubTasks(['Validate CC', 'Reserve funds'], function () {
apm.endTransaction()
queue(processPayment)
})
}
function processCompletedOrder () {
if (!running) return
apm.startTransaction('Process completed order', 'Worker')
performSubTasks(['Send receipt email', 'Update inventory'], function () {
apm.endTransaction()
queue(processCompletedOrder)
})
}
function updateShippingStatus () {
if (!running) return
apm.startTransaction('Update shipping status', 'Worker')
performSubTasks(['Fetch package status for all orders', 'Send tracking emails'], function () {
apm.endTransaction()
queue(updateShippingStatus)
})
}
function performSubTasks (tasks, cb) {
if (!running) return
performSubTask(tasks.shift(), function () {
if (tasks.length === 0) return cb()
setTimeout(function () {
performSubTasks(tasks, cb)
}, Math.random() * 20).unref()
})
}
function performSubTask (name, cb) {
if (!running) return
const span = apm.startSpan(name)
setTimeout(function () {
if (span) span.end()
cb()
}, Math.random() * 1000).unref()
}
function queue (cb) {
setTimeout(cb, Math.random() * 60000 + 10000).unref()
}