-
-
Notifications
You must be signed in to change notification settings - Fork 1k
/
pub-sub-job-queue-strategy.ts
159 lines (135 loc) · 5.01 KB
/
pub-sub-job-queue-strategy.ts
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
import { Message, PubSub, Subscription, Topic } from '@google-cloud/pubsub';
import { JobState } from '@vendure/common/lib/generated-types';
import {
InjectableJobQueueStrategy,
Injector,
Job,
JobData,
JobQueueStrategy,
Logger,
QueueNameProcessStorage,
} from '@vendure/core';
import { loggerCtx, PUB_SUB_OPTIONS } from './constants';
import { PubSubOptions } from './options';
export class PubSubJobQueueStrategy extends InjectableJobQueueStrategy implements JobQueueStrategy {
private concurrency: number;
private queueNamePubSubPair: Map<string, [string, string]>;
private pubSubClient: PubSub;
private topics = new Map<string, Topic>();
private subscriptions = new Map<string, Subscription>();
private listeners = new QueueNameProcessStorage<(message: Message) => void>();
init(injector: Injector) {
this.pubSubClient = injector.get(PubSub);
const options = injector.get<PubSubOptions>(PUB_SUB_OPTIONS);
this.concurrency = options.concurrency ?? 20;
this.queueNamePubSubPair = options.queueNamePubSubPair ?? new Map();
super.init(injector);
}
destroy() {
super.destroy();
for (const subscription of this.subscriptions.values()) {
subscription.removeAllListeners('message');
}
this.subscriptions.clear();
this.topics.clear();
}
async add<Data extends JobData<Data> = object>(job: Job<Data>): Promise<Job<Data>> {
if (!this.hasInitialized) {
throw new Error('Cannot add job before init');
}
const id = await this.topic(job.queueName).publish(Buffer.from(JSON.stringify(job.data)));
Logger.debug(`Sent message ${job.queueName}: ${id}`);
return new Job<Data>({
id,
queueName: job.queueName,
data: job.data,
attempts: 0,
state: JobState.PENDING,
createdAt: new Date(),
});
}
async start<Data extends JobData<Data> = object>(
queueName: string,
process: (job: Job<Data>) => Promise<any>,
) {
if (!this.hasInitialized) {
this.started.set(queueName, process);
return;
}
if (this.listeners.has(queueName, process)) {
return;
}
const subscription = this.subscription(queueName);
const processMessage = async (message: Message) => {
Logger.verbose(`Received message: ${queueName}: ${message.id}`, loggerCtx);
const job = new Job<Data>({
id: message.id,
queueName,
data: JSON.parse(message.data.toString()),
attempts: message.deliveryAttempt,
state: JobState.RUNNING,
startedAt: new Date(),
createdAt: message.publishTime,
});
await process(job);
};
const listener = (message: Message) => {
processMessage(message)
.then(() => {
message.ack();
Logger.verbose(`Finished handling: ${queueName}: ${message.id}`, loggerCtx);
})
.catch(err => {
message.nack();
Logger.error(
`Error handling: ${queueName}: ${message.id}: ${String(err.message)}`,
loggerCtx,
);
});
};
this.listeners.set(queueName, process, listener);
subscription.on('message', listener);
}
async stop<Data extends JobData<Data> = object>(
queueName: string,
process: (job: Job<Data>) => Promise<any>,
) {
const listener = this.listeners.getAndDelete(queueName, process);
if (!listener) {
return;
}
this.subscription(queueName).off('message', listener);
}
private topic(queueName: string): Topic {
let topic = this.topics.get(queueName);
if (topic) {
return topic;
}
const pair = this.queueNamePubSubPair.get(queueName);
if (!pair) {
throw new Error(`Topic name not set for queue: ${queueName}`);
}
const [topicName, subscriptionName] = pair;
topic = this.pubSubClient.topic(topicName);
this.topics.set(queueName, topic);
return topic;
}
private subscription(queueName: string): Subscription {
let subscription = this.subscriptions.get(queueName);
if (subscription) {
return subscription;
}
const pair = this.queueNamePubSubPair.get(queueName);
if (!pair) {
throw new Error(`Subscription name not set for queue: ${queueName}`);
}
const [topicName, subscriptionName] = pair;
subscription = this.topic(queueName).subscription(subscriptionName, {
flowControl: {
maxMessages: this.concurrency,
},
});
this.subscriptions.set(queueName, subscription);
return subscription;
}
}