-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmetrics.rs
445 lines (398 loc) · 13.8 KB
/
metrics.rs
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
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
//! This module implements the metrics handler and its http server.
use axum::body::Body;
use axum::http::header::CONTENT_TYPE;
use axum::http::StatusCode;
use axum::response::{Html, Response};
use axum::routing::get;
use axum::{Extension, Router};
use prometheus_client::encoding::text::encode;
use prometheus_client::encoding::{EncodeLabelSet, EncodeLabelValue, LabelValueEncoder};
use prometheus_client::metrics::counter::Counter;
use prometheus_client::metrics::family::Family;
use prometheus_client::metrics::gauge::Gauge;
use prometheus_client::registry::Registry;
use serenity::all::{
Activity, ApplicationId, ChannelId, EmojiId, Guild, GuildChannel, GuildId, OnlineStatus,
VoiceState,
};
use std::net::SocketAddr;
use std::sync::Arc;
use tokio_util::sync::CancellationToken;
use tower_http::trace::TraceLayer;
use tracing::{debug, instrument, trace};
/// The prefix ued to all application metrics.
const PREFIX: &str = "dcexport";
/// [Boolean] is a wrapper for [bool] that implements [`EncodeLabelValue`] such that it can be used in
/// metrics labels.
///
/// It encodes [true] as "true" and [false] as "false".
#[derive(Clone, Debug, Hash, PartialEq, Eq)]
pub struct Boolean(bool);
impl From<Boolean> for bool {
fn from(val: Boolean) -> Self {
val.0
}
}
impl From<bool> for Boolean {
fn from(val: bool) -> Self {
Boolean(val)
}
}
impl EncodeLabelValue for Boolean {
fn encode(&self, encoder: &mut LabelValueEncoder) -> Result<(), std::fmt::Error> {
if self.0 {
"true".encode(encoder)
} else {
"false".encode(encoder)
}
}
}
/// [`GuildsLabels`] are the [labels](EncodeLabelSet) for the `guild` metric.
#[derive(Clone, Debug, Hash, PartialEq, Eq, EncodeLabelSet)]
pub struct GuildsLabels {
pub guild_id: u64,
pub guild_name: String,
}
impl GuildsLabels {
/// Creates a new instance of [`GuildsLabels`].
pub fn new(guild: &Guild) -> Self {
Self {
guild_id: guild.id.get(),
guild_name: guild.name.clone(),
}
}
}
/// [`ChannelLabels`] are the [labels](EncodeLabelSet) for the `channel` metric.
#[derive(Clone, Debug, Hash, PartialEq, Eq, EncodeLabelSet)]
pub struct ChannelLabels {
pub guild_id: u64,
pub channel_id: u64,
pub channel_name: String,
pub channel_nsfw: Boolean,
pub channel_type: String,
}
impl ChannelLabels {
/// Creates a new instance of [`ChannelLabels`].
pub fn new(channel: &GuildChannel) -> Self {
Self {
guild_id: channel.guild_id.get(),
channel_id: channel.id.get(),
channel_name: channel.name.clone(),
channel_nsfw: Boolean(channel.nsfw),
channel_type: channel.kind.name().to_string(),
}
}
}
/// [`BoostLabels`] are the [labels](EncodeLabelSet) for the `boost` metric.
#[derive(Clone, Debug, Hash, PartialEq, Eq, EncodeLabelSet)]
pub struct BoostLabels {
pub guild_id: u64,
}
impl BoostLabels {
/// Creates a new instance of [`BoostLabels`].
pub fn new(guild_id: GuildId) -> Self {
Self {
guild_id: guild_id.get(),
}
}
}
/// [`MemberLabels`] are the [labels](EncodeLabelSet) for the `member` metric.
#[derive(Clone, Debug, Hash, PartialEq, Eq, EncodeLabelSet)]
pub struct MemberLabels {
pub guild_id: u64,
}
impl MemberLabels {
/// Creates a new instance of [`MemberLabels`].
pub fn new(guild_id: GuildId) -> Self {
Self {
guild_id: guild_id.get(),
}
}
}
/// [`BotLabels`] are the [labels](EncodeLabelSet) for the `bot` metric.
///
/// This metric is not included in the member metric (using a label) as the user bot status has to
/// be explicitly requested on guild creation. As such, they are separated to ensure that the member
/// metric does not suffer from additional requests (that could potentially fail).
#[derive(Clone, Debug, Hash, PartialEq, Eq, EncodeLabelSet)]
pub struct BotLabels {
pub guild_id: u64,
}
impl BotLabels {
/// Creates a new instance of [`BotLabels`].
pub fn new(guild_id: GuildId) -> Self {
Self {
guild_id: guild_id.get(),
}
}
}
/// [`MemberStatusLabels`] are the [labels](EncodeLabelSet) for the `member_status` metric.
#[derive(Clone, Debug, Hash, PartialEq, Eq, EncodeLabelSet)]
pub struct MemberStatusLabels {
pub guild_id: u64,
pub status: String,
}
impl MemberStatusLabels {
/// Creates a new instance of [`MemberStatusLabels`].
pub fn new(guild_id: GuildId, status: OnlineStatus) -> Self {
Self {
guild_id: guild_id.get(),
status: status.name().to_string(),
}
}
}
/// [`MemberVoiceLabels`] are the [labels](EncodeLabelSet) for the `member_voice` metric.
#[derive(Clone, Debug, Hash, PartialEq, Eq, EncodeLabelSet)]
pub struct MemberVoiceLabels {
pub guild_id: u64,
pub category_id: Option<u64>,
pub channel_id: u64,
pub self_stream: Boolean,
pub self_video: Boolean,
pub self_deaf: Boolean,
pub self_mute: Boolean,
}
impl MemberVoiceLabels {
/// Creates a new instance of [`MemberVoiceLabels`].
pub fn new(
guild_id: GuildId,
category_id: Option<ChannelId>,
channel_id: ChannelId,
voice: &VoiceState,
) -> Self {
Self {
guild_id: guild_id.get(),
category_id: category_id.map(ChannelId::get),
channel_id: channel_id.get(),
self_stream: voice.self_stream.unwrap_or(false).into(),
self_video: voice.self_video.into(),
self_deaf: voice.self_deaf.into(),
self_mute: voice.self_mute.into(),
}
}
}
/// [`MessageSentLabels`] are the [labels](EncodeLabelSet) for the `message_sent` metric.
#[allow(clippy::struct_field_names)]
#[derive(Clone, Debug, Hash, PartialEq, Eq, EncodeLabelSet)]
pub struct MessageSentLabels {
pub guild_id: u64,
pub category_id: Option<u64>,
pub channel_id: u64,
}
impl MessageSentLabels {
/// Creates a new instance of [`MessageSentLabels`].
pub fn new(guild_id: GuildId, category_id: Option<ChannelId>, channel_id: ChannelId) -> Self {
Self {
guild_id: guild_id.get(),
category_id: category_id.map(ChannelId::get),
channel_id: channel_id.get(),
}
}
}
/// [`EmoteUsedLabels`] are the [labels](EncodeLabelSet) for the `emote_used` metric.
#[derive(Clone, Debug, Hash, PartialEq, Eq, EncodeLabelSet)]
pub struct EmoteUsedLabels {
pub guild_id: u64,
pub category_id: Option<u64>,
pub channel_id: u64,
pub reaction: Boolean,
pub emoji_id: u64,
pub emoji_name: Option<String>,
}
impl EmoteUsedLabels {
/// Creates a new instance of [`EmoteUsedLabels`].
pub fn new(
guild_id: GuildId,
category_id: Option<ChannelId>,
channel_id: ChannelId,
reaction: bool,
emoji_id: EmojiId,
emoji_name: Option<String>,
) -> Self {
Self {
guild_id: guild_id.get(),
category_id: category_id.map(ChannelId::get),
channel_id: channel_id.get(),
reaction: Boolean(reaction),
emoji_id: emoji_id.get(),
emoji_name,
}
}
}
/// [`ActivityLabels`] are the [labels](EncodeLabelSet) for the `activity` metric.
#[derive(Clone, Debug, Hash, PartialEq, Eq, EncodeLabelSet)]
pub struct ActivityLabels {
pub guild_id: u64,
pub activity_application_id: Option<u64>,
pub activity_name: String,
}
impl ActivityLabels {
/// Creates a new instance of [`ActivityLabels`].
pub fn new(guild_id: GuildId, activity: &Activity) -> Self {
Self {
guild_id: guild_id.get(),
activity_application_id: activity.application_id.map(ApplicationId::get),
activity_name: activity.name.clone(),
}
}
}
/// Handler is the [servable](serve) bundle of metrics for the exporter.
pub struct Handler {
registry: Registry,
pub guild: Family<GuildsLabels, Gauge>,
pub channel: Family<ChannelLabels, Gauge>,
pub boost: Family<BoostLabels, Gauge>,
pub member: Family<MemberLabels, Gauge>,
pub bot: Family<BotLabels, Gauge>,
pub member_status: Family<MemberStatusLabels, Gauge>,
pub member_voice: Family<MemberVoiceLabels, Gauge>,
pub message_sent: Family<MessageSentLabels, Counter>,
pub emote_used: Family<EmoteUsedLabels, Counter>,
pub activity: Family<ActivityLabels, Gauge>,
}
impl Handler {
/// Creates a new [Handler] metrics bundle with its own [Registry].
///
/// The [Registry] is created using a [PREFIX].
#[instrument]
pub fn new() -> Self {
debug!(prefix = PREFIX, "Building metrics registry");
let mut registry = <Registry>::with_prefix(PREFIX);
debug!(metrics_name = "guild", "Building metric");
let guild = Family::<GuildsLabels, Gauge>::default();
registry.register(
"guild",
"The number of guilds handled by the exporter.",
guild.clone(),
);
debug!(metrics_name = "channel", "Building metric");
let channel = Family::<ChannelLabels, Gauge>::default();
registry.register(
"channel",
"The number of channels on the guild.",
channel.clone(),
);
debug!(metrics_name = "boost", "Building metric");
let boost = Family::<BoostLabels, Gauge>::default();
registry.register(
"boost",
"The number of boosts active on the guild.",
boost.clone(),
);
debug!(metrics_name = "member", "Building metric");
let member = Family::<MemberLabels, Gauge>::default();
registry.register(
"member",
"The number of members (including bots) on the guild.",
member.clone(),
);
debug!(metrics_name = "bot", "Building metric");
let bot = Family::<BotLabels, Gauge>::default();
registry.register(
"bot",
"The number of bot members on the guild.",
bot.clone(),
);
debug!(metrics_name = "member_status", "Building metric");
let member_status = Family::<MemberStatusLabels, Gauge>::default();
registry.register(
"member_status",
"The number of members on the guild per status.",
member_status.clone(),
);
debug!(metrics_name = "member_voice", "Building metric");
let member_voice = Family::<MemberVoiceLabels, Gauge>::default();
registry.register(
"member_voice",
"The number of members in voice channels.",
member_voice.clone(),
);
debug!(metrics_name = "message_sent", "Building metric");
let message_sent = Family::<MessageSentLabels, Counter>::default();
registry.register(
"message_sent",
"The total number of discord messages sent by guild members.",
message_sent.clone(),
);
debug!(metrics_name = "emote_used", "Building metric");
let emote_used = Family::<EmoteUsedLabels, Counter>::default();
registry.register(
"emote_used",
"The total number of discord emotes reacted with by guild members in messages.",
emote_used.clone(),
);
debug!(metrics_name = "activity", "Building metric");
let activity = Family::<ActivityLabels, Gauge>::default();
registry.register(
"activity",
"The number of current activities.",
activity.clone(),
);
Self {
registry,
// metrics
guild,
channel,
boost,
member,
bot,
member_status,
member_voice,
message_sent,
emote_used,
activity,
}
}
}
/// Serves a shared [Handler] using a [webserver](Router).
///
/// Use the [CancellationToken] to cancel and gracefully shutdown the [Handler].
/// The metrics can be accessed using the `/metrics` path. It doesn't enforce any authentication.
#[instrument(skip(handler, shutdown))]
pub async fn serve(
address: &SocketAddr,
handler: Arc<Handler>,
shutdown: CancellationToken,
) -> Result<(), Box<dyn std::error::Error>> {
// Create webserver for metrics
let rest_app = Router::new()
.route("/", get(index))
.route("/metrics", get(metrics))
.layer(Extension(Arc::clone(&handler)))
.layer(TraceLayer::new_for_http())
.with_state(());
// Bind tcp listener
debug!(address = %address, "Starting tcp listener");
let listener = tokio::net::TcpListener::bind(address).await?;
// Serve webserver and wait
debug!("Serving axum router");
axum::serve(listener, rest_app)
.with_graceful_shutdown(shutdown.cancelled_owned())
.await?;
Ok(())
}
/// The index endpoint handler. It shows an index page.
#[instrument]
async fn index() -> Html<&'static str> {
Html("dcexport - <a href=\"/metrics\">Metrics</a>")
}
/// The metrics endpoint handler. It encodes the current registry into the response body.
///
/// The body has the [CONTENT_TYPE] `application/openmetrics-text; version=1.0.0; charset=utf-8`.
#[instrument(skip(handler))]
async fn metrics(Extension(handler): Extension<Arc<Handler>>) -> Response {
debug!("Handling metrics request");
// Encode the metrics content into the buffer
let mut buffer = String::new();
encode(&mut buffer, &handler.registry).expect("failed to encode metrics into the buffer");
trace!(buffer = buffer.to_string(), "Built metrics response");
// Respond with encoded metrics
Response::builder()
.status(StatusCode::OK)
.header(
CONTENT_TYPE,
"application/openmetrics-text; version=1.0.0; charset=utf-8",
)
.body(Body::from(buffer))
.expect("failed to build response")
}