generated from MapColonies/jobnik-worker-boilerplate
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtaskPoller.ts
More file actions
142 lines (119 loc) · 4.33 KB
/
taskPoller.ts
File metadata and controls
142 lines (119 loc) · 4.33 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
import { setTimeout as sleep } from 'timers/promises';
import { inject, injectable } from 'tsyringe';
import type { Logger } from '@map-colonies/js-logger';
import type { TaskHandler as QueueClient, ITaskResponse } from '@map-colonies/mc-priority-queue';
import type { IWorker } from '@map-colonies/jobnik-sdk';
import { SERVICES } from '@common/constants';
import type { ConfigType } from '@common/config';
import type { PollingPairConfig } from '../cleaner/types';
import type { StrategyFactory } from '../cleaner/strategies';
import { UnrecoverableError, type ErrorHandler } from '../cleaner/errors';
/**
* TaskPoller - Simple bridge to implement IWorker using the old mc-priority-queue SDK
*/
@injectable()
export class TaskPoller implements IWorker {
private shouldStop = false;
private readonly dequeueIntervalMs: number;
public constructor(
@inject(SERVICES.LOGGER) private readonly logger: Logger,
@inject(SERVICES.CONFIG) config: ConfigType,
@inject(SERVICES.QUEUE_CLIENT) private readonly queueClient: QueueClient,
@inject(SERVICES.STRATEGY_FACTORY) private readonly strategyFactory: StrategyFactory,
@inject(SERVICES.ERROR_HANDLER) private readonly errorHandler: ErrorHandler,
@inject(SERVICES.POLLING_PAIRS) private readonly pollingPairs: PollingPairConfig[]
) {
this.dequeueIntervalMs = config.get('queue.dequeueIntervalMs') as unknown as number; //TODO:when we create worker config schema we can remove the cast
}
public async start(): Promise<void> {
this.shouldStop = false;
await this.poll();
}
public async stop(): Promise<void> {
this.shouldStop = true;
await Promise.resolve();
}
// IWorker event methods - delegated to internal EventEmitter (no-op since nothing listens)
public on(): this {
return this;
}
public off(): this {
return this;
}
public once(): this {
return this;
}
public removeAllListeners(): this {
return this;
}
private async poll(): Promise<void> {
while (!this.shouldStop) {
const result = await this.tryDequeue();
if (!result) {
await sleep(this.dequeueIntervalMs);
continue;
}
await this.processTask(result);
}
}
private async tryDequeue(): Promise<
| {
task: ITaskResponse<unknown>;
pair: PollingPairConfig;
}
| undefined
> {
for (const pair of this.pollingPairs) {
if (this.shouldStop) {
return undefined;
}
try {
const task = await this.queueClient.dequeue<unknown>(pair.jobType, pair.taskType);
if (task) {
this.logger.info({ msg: 'Task dequeued', taskId: task.id, taskType: task.type, jobId: task.jobId });
return { task, pair };
}
} catch (error) {
this.logger.error({ msg: 'Dequeue error', error });
}
}
return undefined;
}
private async processTask(dequeued: { task: ITaskResponse<unknown>; pair: PollingPairConfig }): Promise<void> {
const { task, pair } = dequeued;
const startTime = Date.now();
this.logger.debug({ msg: 'Task started', taskId: task.id, jobId: task.jobId });
try {
if (task.attempts >= pair.maxAttempts) {
throw new UnrecoverableError(`Task exceeded max attempts: ${task.attempts}/${pair.maxAttempts}`);
}
const strategy = this.strategyFactory.resolveWithContext({
jobId: task.jobId,
taskId: task.id,
jobType: pair.jobType,
taskType: pair.taskType,
});
const validated = strategy.validate(task.parameters);
await strategy.execute(validated);
await this.queueClient.ack(task.jobId, task.id);
const durationMs = Date.now() - startTime;
this.logger.info({ msg: 'Task completed', taskId: task.id, durationMs });
} catch (error) {
await this.handleTaskFailure(error, task, pair);
}
}
private async handleTaskFailure(error: unknown, task: ITaskResponse<unknown>, pair: PollingPairConfig): Promise<void> {
const decision = this.errorHandler.handleError({
jobId: task.jobId,
taskId: task.id,
attemptNumber: task.attempts,
maxAttempts: pair.maxAttempts,
error,
});
try {
await this.queueClient.reject(task.jobId, task.id, decision.shouldRetry, decision.reason);
} catch (error) {
this.logger.error({ msg: 'Failed to reject task', taskId: task.id, error });
}
}
}