-
Notifications
You must be signed in to change notification settings - Fork 0
/
runner.js
105 lines (91 loc) · 2.36 KB
/
runner.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
const sleep = require('await-sleep')
const TaskRequest = require('./task-request')
const TaskResponse = require('./task-response')
class Runner extends require('./discron') {
/**
*
* @param {Array<Task>} taskClasses
*/
constructor({
requestKeyPrefix /** 请求队列名称前缀 */,
responseKey /** 响应队列 */,
backOffDuration /** */,
redisCfg /** redis 配置 */,
taskClasses /** 任务类定义列表 */,
logger,
}) {
super(requestKeyPrefix, taskClasses.length, responseKey, redisCfg, logger)
this.TASK_CLASSES = taskClasses
this.BACK_OFF_DURATION = backOffDuration
}
start() {
this.runEventLoop()
this.logger.debug('执行器启动')
}
stop() {
this.stopped = true
}
async runEventLoop() {
for (;;) {
if (this.stopped) {
break
}
const taskRequest = await this.getTaskRequest()
if (taskRequest) {
await this.onRequest(taskRequest)
}
}
}
async getTaskRequest() {
try {
// 等待多个队列, 从多个队列里顺序选择一个就绪的
return TaskRequest.unpack(await this.dequeRequestQueue())
} catch (err) {
// log
this.logger.error(err, '获取任务请求包时出错')
await sleep(this.BACK_OFF_DURATION)
return null
}
}
async onRequest(taskRequest) {
const taskEntry = this.dispatchTask(taskRequest)
if (!taskEntry) {
return
}
const receipt = await this.execute(taskEntry)
const taskResponse = new TaskResponse(taskRequest, receipt)
await this.respond(taskResponse)
}
dispatchTask(taskRequest) {
try {
if (this.TASK_CLASSES[taskRequest.type]) {
return new this.TASK_CLASSES[taskRequest.type](taskRequest)
} else {
throw new Error(`未找到相关任务: ${taskRequest.type}`)
}
} catch (err) {
// log
this.logger.error(err, '查找任务类时出错')
return null
}
}
async execute(task) {
try {
return await task.run()
} catch (err) {
// log
this.logger.error(err, '执行任务时出错')
return null
}
}
async respond(taskResponse) {
try {
return await this.responseQueue.enque(taskResponse.pack())
} catch (err) {
// log
this.logger.error(err, '发送任务响应时出错')
return null
}
}
}
module.exports = Runner