Repository navigation
Expand file tree
/
Copy pathmonitoring-cluster.ts
More file actions
318 lines (316 loc) · 9.64 KB
/
Copy pathmonitoring-cluster.ts
File metadata and controls
318 lines (316 loc) · 9.64 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
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
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
import { createClient, type RedisClientType } from "redis";
import { z } from "zod";
import { fail } from "@core/shared/errors.js";
import type {
MonitoringBuffer,
MonitoringSnapshot,
} from "./monitoring-buffer.js";
const integer = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);
const finite = z.number().finite();
const histogram = z
.object({
count: integer,
sum: finite,
min: finite,
max: finite,
buckets: z.array(integer).length(13),
})
.strict();
const route = z
.object({
method: z.string().max(20),
route: z.string().max(500),
requests: integer,
clientErrors: integer,
serverErrors: integer,
latency: histogram,
})
.strict();
const snapshotSchema = z
.object({
version: z.literal(1),
instance: z
.object({
instanceId: z.string().min(1).max(200),
epoch: z.string().uuid(),
startedAt: z.string().datetime(),
sampledAt: z.string().datetime(),
stale: z.boolean(),
uptimeSeconds: finite.nonnegative(),
process: z
.object({
rssBytes: integer,
heapUsedBytes: integer,
cpuUserMicros: integer,
cpuSystemMicros: integer,
eventLoopDelayP95Ms: finite.nullable(),
})
.strict(),
logs: z
.object({
oldestSequence: integer,
newestSequence: integer,
dropped: integer,
retained: integer,
})
.strict(),
rejectedMetricSeries: integer,
})
.strict(),
http: z
.array(
z
.object({
second: integer,
requests: integer,
clientErrors: integer,
serverErrors: integer,
aborted: integer,
latency: histogram,
routes: z.array(route).max(100),
})
.strict(),
)
.max(301),
inFlight: integer,
series: z
.array(
z
.object({
instanceId: z.string(),
epoch: z.string().uuid(),
pluginId: z.string(),
name: z.string().max(200),
kind: z.enum(["counter", "gauge", "histogram"]),
labels: z.record(z.string(), z.string()),
updatedAt: z.string().datetime(),
value: finite.nullable(),
histogram: z
.object({
count: integer,
sum: finite,
min: finite.nullable(),
max: finite.nullable(),
buckets: z
.array(
z
.object({ upperBound: finite.nullable(), count: integer })
.strict(),
)
.length(13),
p50: finite.nullable(),
p95: finite.nullable(),
p99: finite.nullable(),
})
.strict()
.nullable(),
})
.strict(),
)
.max(1000),
logs: z
.array(
z
.object({
id: z.string(),
sequence: integer,
instanceId: z.string(),
epoch: z.string().uuid(),
createdAt: z.string().datetime(),
pluginId: z.string().nullable(),
level: z.enum(["trace", "debug", "info", "warn", "error", "fatal"]),
module: z.string().max(200),
message: z.string().max(2000),
requestId: z.string().nullable(),
fields: z.record(z.string(), z.unknown()),
})
.strict(),
)
.max(2000),
})
.strict();
const snapshotLimit = 16 * 1024 * 1024;
export const monitoringStaleMs = 15000;
export const monitoringRetentionMs = 60 * 60 * 1000;
/** Versioned ephemeral host cache, separate from the durable database and realtime protocol. */
export class MonitoringCluster {
readonly #redis: RedisClientType | undefined;
readonly #registry: string;
#timer: ReturnType<typeof setInterval> | undefined;
#publishing: Promise<void> | undefined;
#closed = false;
constructor(
readonly buffer: MonitoringBuffer,
options: { redis?: RedisClientType; prefix?: string } = {},
) {
this.#redis = options.redis;
this.#registry =
(options.prefix?.trim() || "doca") + ":monitoring:v1:instances";
}
get mode() {
return this.#redis ? ("redis" as const) : ("local" as const);
}
isReady() {
return !this.#closed && (!this.#redis || this.#redis.isReady);
}
async start() {
await this.publish();
this.#timer = setInterval(() => {
void this.publish().catch(() => {});
}, 5000);
this.#timer.unref();
}
async publish() {
if (!this.#redis || this.#closed) return;
if (this.#publishing) return this.#publishing;
this.#publishing = (async () => {
if (!this.#redis!.isReady) fail(503, "Monitoring Redis is unavailable");
const snapshot = this.buffer.snapshot(),
raw = JSON.stringify(snapshot),
now = this.buffer.now();
if (Buffer.byteLength(raw) > snapshotLimit)
fail(503, "Monitoring snapshot exceeds the cluster limit");
await this.#redis!.multi()
.set(this.#registry + ":" + snapshot.instance.epoch, raw, {
PX: monitoringRetentionMs,
})
.zAdd(this.#registry, { score: now, value: snapshot.instance.epoch })
.zRemRangeByScore(this.#registry, 0, now - monitoringRetentionMs)
.pExpire(this.#registry, monitoringRetentionMs)
.exec();
})().finally(() => {
this.#publishing = undefined;
});
return this.#publishing;
}
async read(scope: "instance" | "cluster") {
if (this.#closed) fail(503, "Monitoring collector is closed");
if (scope === "instance" || !this.#redis)
return {
scope: "instance" as const,
snapshots: [this.buffer.snapshot()],
unavailable: [] as string[],
};
if (!this.#redis.isReady) fail(503, "Monitoring Redis is unavailable");
await this.publish();
const epochs = await this.#redis.zRangeByScore(
this.#registry,
this.buffer.now() - monitoringRetentionMs,
"+inf",
);
if (epochs.length > 128)
fail(
503,
"Monitoring cluster exceeds 128 instances; query individual instances",
);
if (!epochs.length)
fail(503, "Monitoring cluster inventory is unavailable");
const raw = await this.#redis.mGet(
epochs.map((epoch) => this.#registry + ":" + epoch),
);
const snapshots: MonitoringSnapshot[] = [],
unavailable: string[] = [];
raw.forEach((value, index) => {
try {
if (!value || Buffer.byteLength(value) > snapshotLimit) throw Error();
const snapshot = snapshotSchema.parse(
JSON.parse(value),
) as MonitoringSnapshot;
if (snapshot.instance.epoch !== epochs[index]) throw Error();
if (
snapshot.logs.some(
(log, index, logs) =>
log.epoch !== snapshot.instance.epoch ||
log.instanceId !== snapshot.instance.instanceId ||
log.sequence < snapshot.instance.logs.oldestSequence ||
log.sequence > snapshot.instance.logs.newestSequence ||
(index > 0 && log.sequence !== logs[index - 1]!.sequence + 1),
)
)
throw Error();
if (
snapshot.logs.length !== snapshot.instance.logs.retained ||
snapshot.series.some(
(series) =>
series.epoch !== snapshot.instance.epoch ||
series.instanceId !== snapshot.instance.instanceId,
)
)
throw Error();
if (Date.parse(snapshot.instance.sampledAt) > this.buffer.now() + 5000)
throw Error();
snapshot.instance = {
...snapshot.instance,
stale:
snapshot.instance.stale ||
this.buffer.now() - Date.parse(snapshot.instance.sampledAt) >
monitoringStaleMs,
};
snapshots.push(snapshot);
} catch {
unavailable.push(epochs[index]!);
}
});
return { scope: "cluster" as const, snapshots, unavailable };
}
async close() {
if (this.#closed) return;
if (this.#timer) clearInterval(this.#timer);
await this.#publishing?.catch(() => {});
this.buffer.close();
await this.publish().catch(() => {});
this.#closed = true;
if (this.#redis?.isOpen) {
if (this.#redis.isReady)
await this.#redis.quit().catch(() => this.#redis!.destroy());
else this.#redis.destroy();
}
}
}
export async function createMonitoringCluster(
buffer: MonitoringBuffer,
options: { redisUrl?: string; prefix?: string },
) {
let redis: RedisClientType | undefined;
if (options.redisUrl) {
redis = createClient({
url: options.redisUrl,
disableOfflineQueue: true,
commandOptions: { timeout: 2000 },
socket: {
connectTimeout: 3000,
reconnectStrategy: (retries) => Math.min(100 * 2 ** retries, 2000),
},
});
redis.on("error", () => {});
let timeout: ReturnType<typeof setTimeout> | undefined;
try {
await Promise.race([
redis.connect(),
new Promise<never>((_, reject) => {
timeout = setTimeout(
() => reject(Error("Monitoring Redis startup timed out")),
3000,
);
}),
]);
} catch {
if (redis.isOpen) redis.destroy();
buffer.close();
fail(503, "Monitoring Redis connection failed");
} finally {
if (timeout) clearTimeout(timeout);
}
}
const cluster = new MonitoringCluster(buffer, {
redis,
prefix: options.prefix,
});
try {
await cluster.start();
} catch (error) {
await cluster.close();
throw error;
}
return cluster;
}