/
membership-queue.ts
293 lines (272 loc) · 9.96 KB
/
membership-queue.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
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
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
import { Bridge } from "../bridge";
import { get as getLogger } from "./logging";
import PQueue from "p-queue";
import { Counter, Gauge } from "prom-client";
const log = getLogger("MembershipQueue");
export interface ThinRequest {
getId(): string;
}
interface QueueUserItem {
type: "join"|"leave";
kickUser?: string;
reason?: string;
attempts: number;
roomId: string;
userId: string;
retry: boolean;
req: ThinRequest;
ts: number;
ttl: number;
}
export interface MembershipQueueOpts {
/**
* The number of concurrent operations to perform.
*/
concurrentRoomLimit?: number;
/**
* The number of attempts to retry an operation before it is discarded.
*/
maxAttempts?: number;
/**
* @deprecated Use `actionDelayMs`
*/
joinDelayMs?: number;
/**
* How long to delay a request for in milliseconds, multiplied by the number of attempts made
* if a request failed.
*/
actionDelayMs?: number;
/**
* @deprecated Use `maxActionDelayMs`
*/
maxJoinDelayMs?: number;
/**
* The maximum number of milliseconds a request may be delayed for.
*/
maxActionDelayMs?: number;
/**
* How long a request can "live" for before it is discarded in
* milliseconds. This will override `maxAttempts`.
*/
defaultTtlMs?: number;
}
/**
* Default values used by the queue if not specified.
*/
export const DEFAULT_OPTS: MembershipQueueOptsWithDefaults = {
concurrentRoomLimit: 8,
maxAttempts: 10,
actionDelayMs: 500,
maxActionDelayMs: 30 * 60 * 1000, // 30 mins
defaultTtlMs: 2 * 60 * 1000, // 2 mins
};
interface MembershipQueueOptsWithDefaults extends MembershipQueueOpts {
maxActionDelayMs: number;
actionDelayMs: number;
concurrentRoomLimit: number;
defaultTtlMs: number;
maxAttempts: number;
}
/**
* This class sends membership changes for rooms in a linearized queue.
* The queue is lineaized based upon the hash value of the roomId, so that two
* operations for the same roomId may never happen concurrently.
*/
export class MembershipQueue {
private queues: Map<number, PQueue> = new Map();
private pendingGauge?: Gauge<"type"|"instance_id">;
private processedCounter?: Counter<"type"|"instance_id"|"outcome">;
private failureReasonCounter?: Counter<"errcode"|"http_status"|"type">;
private ageOfLastProcessedGauge?: Gauge<string>;
private opts: MembershipQueueOptsWithDefaults;
constructor(private bridge: Bridge, opts: MembershipQueueOpts) {
this.opts = { ...DEFAULT_OPTS, ...opts};
for (let i = 0; i < this.opts.concurrentRoomLimit; i++) {
this.queues.set(i, new PQueue({
autoStart: true,
concurrency: 1,
}));
}
if (opts.actionDelayMs === undefined && opts.joinDelayMs) {
log.warn("MembershipQueue configured with deprecated config option `joinDelayMs`. Use `actionDelayMs`");
this.opts.actionDelayMs = opts.joinDelayMs;
}
if (opts.maxActionDelayMs === undefined && opts.maxJoinDelayMs) {
log.warn(
"MembershipQueue configured with deprecated config option `maxJoinDelayMs`. Use `maxActionDelayMs`"
);
this.opts.maxActionDelayMs = opts.maxJoinDelayMs;
}
}
/**
* This should be called after starting the bridge in order
* to track metrics for the membership queue.
*/
public registerMetrics() {
const metrics = this.bridge.getPrometheusMetrics(false);
this.pendingGauge = metrics.addGauge({
name: "membershipqueue_pending",
help: "Count of membership actions in the queue by type",
labels: ["type"]
});
this.processedCounter = metrics.addCounter({
name: "membershipqueue_processed",
help: "Count of membership actions processed by type and outcome",
labels: ["type", "outcome"],
});
this.failureReasonCounter = metrics.addCounter({
name: "membershipqueue_reason",
help: "Count of failures to process membership by type, matrix errcode and http statuscode",
labels: ["type", "errcode", "http_status"],
});
this.ageOfLastProcessedGauge = metrics.addGauge({
name: "membershipqueue_lastage",
help: "Gauge to measure the age of the last processed event",
});
}
/**
* Join a user to a room
* @param roomId The roomId to join
* @param userId Leave empty to act as the bot user.
* @param req The request entry for logging context
* @param retry Should the request retry if it fails
* @param ttl How long should this request remain queued in milliseconds
* before it's discarded. Defaults to `opts.defaultTtlMs`
* @returns A promise that resolves when the membership has completed
*/
public async join(roomId: string, userId: string|undefined, req: ThinRequest, retry = true, ttl?: number) {
return this.queueMembership({
roomId,
userId: userId || this.bridge.botUserId,
retry,
req,
attempts: 0,
type: "join",
ts: Date.now(),
ttl: ttl || this.opts.defaultTtlMs,
});
}
/**
* Leave OR kick a user from a room
* @param roomId The roomId to leave
* @param userId Leave empty to act as the bot user.
* @param req The request entry for logging context
* @param retry Should the request retry if it fails
* @param reason Reason for leaving/kicking
* @param kickUser The user to be kicked. If left blank, this will be a leave.
* @param ttl How long should this request remain queued in milliseconds
* before it's discarded. Defaults to `opts.defaultTtlMs`
* @returns A promise that resolves when the membership has completed
*/
public async leave(roomId: string, userId: string, req: ThinRequest,
retry = true, reason?: string, kickUser?: string,
ttl?: number) {
return this.queueMembership({
roomId,
userId: userId || this.bridge.botUserId,
retry,
req,
attempts: 0,
reason,
kickUser,
type: "leave",
ts: Date.now(),
ttl: ttl || this.opts.defaultTtlMs,
})
}
public async queueMembership(item: QueueUserItem) {
try {
const queue = this.queues.get(this.hashRoomId(item.roomId));
if (!queue) {
throw Error("Could not find queue for hash");
}
this.pendingGauge?.inc({
type: item.kickUser ? "kick" : item.type
});
return queue.add(() => this.serviceQueue(item));
}
catch (ex) {
log.error(`Failed to handle membership: ${ex}`);
throw ex;
}
}
private hashRoomId(roomId: string) {
return Array.from(roomId).map((s) => s.charCodeAt(0)).reduce((a, b) => a + b, 0)
% this.opts.concurrentRoomLimit;
}
private async serviceQueue(item: QueueUserItem) {
const { req, roomId, userId, reason, kickUser, attempts, type, ttl, ts } = item;
const age = Date.now() - ts;
if (age > ttl) {
this.processedCounter?.inc({
type: kickUser ? "kick" : type,
outcome: "dead",
});
this.pendingGauge?.dec({
type: kickUser ? "kick" : type
});
throw Error('Request failed. TTL exceeded');
}
const reqIdStr = req.getId() ? `[${req.getId()}]`: "";
log.debug(`${reqIdStr} ${userId}@${roomId} -> ${type} (reason: ${reason || "none"}, kicker: ${kickUser})`);
const intent = this.bridge.getIntent(kickUser || userId);
this.ageOfLastProcessedGauge?.set(age);
try {
if (type === "join") {
await intent.join(roomId);
}
else if (kickUser) {
await intent.kick(roomId, userId, reason);
}
else {
await intent.leave(roomId, reason);
}
this.processedCounter?.inc({
type: kickUser ? "kick" : type,
outcome: "success",
});
}
catch (ex) {
if (ex.body.errcode || ex.statusCode) {
this.failureReasonCounter?.inc({
type: kickUser ? "kick" : type,
errcode: ex.body.errcode || "none",
http_status: ex.statusCode || "none"
});
}
if (!this.shouldRetry(ex, attempts)) {
this.processedCounter?.inc({
type: kickUser ? "kick" : type,
outcome: "fail",
});
throw ex;
}
const delay = Math.min(
(this.opts.actionDelayMs * attempts) + (Math.random() * 500),
this.opts.actionDelayMs
);
log.warn(`${reqIdStr} Failed to ${type} ${roomId}, delaying for ${delay}ms`);
log.debug(`${reqIdStr} Failed with: ${ex.body.errcode} ${ex.message}`);
await new Promise((r) => setTimeout(r, delay));
this.queueMembership({...item, attempts: attempts + 1}).catch((innerEx) => {
log.error(`Failed to handle membership change:`, innerEx);
});
}
finally {
this.pendingGauge?.dec({
type: kickUser ? "kick" : type
});
}
}
private shouldRetry(ex: {body: {code: string; errcode: string;}, statusCode: number}, attempts: number): boolean {
const { errcode } = ex.body;
return !(
attempts === this.opts.maxAttempts ||
// Forbidden
errcode === "M_FORBIDDEN" ||
ex.statusCode === 403 ||
// Not found
ex.statusCode === 404
);
}
}