Repository navigation
Expand file tree
/
Copy pathqueue.ts
More file actions
186 lines (154 loc) · 4.75 KB
/
Copy pathqueue.ts
File metadata and controls
186 lines (154 loc) · 4.75 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
import PgBoss, { Job, JobWithMetadata } from 'pg-boss'
import { getConfig } from '../config'
import { registerWorkers } from './workers'
import { BaseEvent, BasePayload } from './events'
import { QueueJobRetryFailed, QueueJobCompleted, QueueJobError } from '../monitoring/metrics'
import { logger, logSchema } from '../monitoring'
//eslint-disable-next-line @typescript-eslint/no-explicit-any
type SubclassOfBaseClass = (new (payload: any) => BaseEvent<any>) & {
[K in keyof typeof BaseEvent]: (typeof BaseEvent)[K]
}
export abstract class Queue {
protected static events: SubclassOfBaseClass[] = []
private static pgBoss?: PgBoss
static async init() {
if (Queue.pgBoss) {
return Queue.pgBoss
}
const {
isMultitenant,
databaseURL,
multitenantDatabaseUrl,
pgQueueConnectionURL,
pgQueueDeleteAfterDays,
pgQueueArchiveCompletedAfterSeconds,
pgQueueRetentionDays,
} = getConfig()
let url = pgQueueConnectionURL ?? databaseURL
if (isMultitenant && !pgQueueConnectionURL) {
if (!multitenantDatabaseUrl) {
throw new Error(
'running storage in multi-tenant but DB_MULTITENANT_DATABASE_URL is not set'
)
}
url = multitenantDatabaseUrl
}
Queue.pgBoss = new PgBoss({
connectionString: url,
max: 4,
application_name: 'storage-pgboss',
deleteAfterDays: pgQueueDeleteAfterDays,
archiveCompletedAfterSeconds: pgQueueArchiveCompletedAfterSeconds,
retentionDays: pgQueueRetentionDays,
retryBackoff: true,
retryLimit: 20,
expireInHours: 48,
})
registerWorkers()
Queue.pgBoss.on('error', (error) => {
logSchema.error(logger, '[Queue] error', {
type: 'queue',
error,
})
})
await Queue.pgBoss.start()
await Queue.startWorkers()
return Queue.pgBoss
}
static getInstance() {
if (!this.pgBoss) {
throw new Error('pg boss not initialised')
}
return this.pgBoss
}
static register<T extends SubclassOfBaseClass>(event: T) {
Queue.events.push(event)
}
static async stop() {
if (!this.pgBoss) {
return
}
const boss = this.pgBoss
await boss.stop({
timeout: 20 * 1000,
})
await new Promise((resolve) => {
boss.once('stopped', () => resolve(null))
})
Queue.pgBoss = undefined
}
protected static startWorkers() {
const workers: Promise<string>[] = []
Queue.events.forEach((event) => {
workers.push(Queue.registerTask(event.getQueueName(), event, true))
const slowRetryQueue = event.withSlowRetryQueue()
if (slowRetryQueue) {
workers.push(Queue.registerTask(event.getSlowRetryQueueName(), event, false))
}
})
return Promise.all(workers)
}
protected static registerTask(
queueName: string,
event: SubclassOfBaseClass,
slowRetryQueueOnFail?: boolean
) {
const hasSlowRetryQueue = event.withSlowRetryQueue()
return Queue.getInstance().work(
queueName,
event.getWorkerOptions(),
async (job: Job<BasePayload>) => {
try {
const res = await event.handle(job)
QueueJobCompleted.inc({
name: event.getQueueName(),
})
return res
} catch (e) {
QueueJobRetryFailed.inc({
name: event.getQueueName(),
})
try {
const dbJob: JobWithMetadata | null =
(job as JobWithMetadata).priority !== undefined
? (job as JobWithMetadata)
: await Queue.getInstance().getJobById(job.id)
if (!dbJob) {
return
}
if (dbJob.retrycount >= dbJob.retrylimit) {
QueueJobError.inc({
name: event.getQueueName(),
})
if (hasSlowRetryQueue && slowRetryQueueOnFail) {
event.sendSlowRetryQueue(job.data).catch(() => {
logSchema.error(
logger,
`[Queue Handler] Error while sending job to slow retry queue`,
{
type: 'queue-task',
error: e,
metadata: JSON.stringify(job),
}
)
})
}
}
} catch (e) {
logSchema.error(logger, `[Queue Handler] fetching job ${event.name}`, {
type: 'queue-task',
error: e,
metadata: JSON.stringify(job),
})
}
logSchema.error(logger, `[Queue Handler] Error while processing job ${event.name}`, {
type: 'queue-task',
error: e,
metadata: JSON.stringify(job),
})
throw e
}
}
)
}
}