Skip to content

Commit 2b53d10

Browse files
authored
Support OpenTelemetry (#28)
1 parent 1a9c967 commit 2b53d10

19 files changed

Lines changed: 198 additions & 34 deletions

File tree

Cargo.toml

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,14 @@ futures-util = "0.3"
1919
tokio = "1.43"
2020
tokio-stream = "0.1"
2121

22+
tracing = { version = "0.1", features = ["std"] }
23+
tracing-subscriber = { version = "0.3", features = ["env-filter","registry", "std", "fmt"] }
24+
opentelemetry_sdk = "0.30"
25+
opentelemetry-appender-tracing = "0.30"
26+
tracing-opentelemetry = "0.31"
27+
opentelemetry = { version = "0.30", features = ["trace"] }
28+
opentelemetry-otlp = { version = "0.30", features = ["http-proto", "grpc-tonic"] }
29+
2230
mongodb = "3.2"
2331
redis = { version = "0.29", features = ["aio", "tokio-comp"] }
2432

src/commands/context.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ macro_rules! extract {
2424
};
2525
}
2626

27+
#[derive(Debug, Clone)]
2728
pub struct InteractionContext {
2829
pub command_vec: Vec<String>,
2930
pub command_text: String,

src/database/mongodb.rs

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ use mongodb::{Client, Collection, Database};
55
use mongodb::bson::doc;
66
#[cfg(feature = "tasks")]
77
use mongodb::bson::DateTime;
8+
use tracing::info;
89
use twilight_model::channel::message::Embed;
910
use twilight_model::id::Id;
1011
use twilight_model::id::marker::{ChannelMarker, GuildMarker, UserMarker};
@@ -32,6 +33,7 @@ impl MongoDBConnection {
3233

3334
pub async fn connect(uri: String) -> Result<Self, mongodb::error::Error> {
3435
let client = Client::with_uri_str(uri).await?;
36+
info!("connected to MongoDB");
3537
let db = client.database("custom");
3638
let configs = db.collection::<GuildConfig>("configs");
3739
let cases = db.collection("cases");
@@ -52,7 +54,6 @@ impl MongoDBConnection {
5254
}
5355

5456
pub async fn get_config(&self, guild_id: Id<GuildMarker>) -> Result<GuildConfig, mongodb::error::Error> {
55-
5657
match self.configs_cache.get(&guild_id){
5758
Some(config) => {
5859
Ok(config.to_owned())
@@ -62,9 +63,14 @@ impl MongoDBConnection {
6263
doc! {
6364
"guild_id": guild_id.to_string()
6465
}
65-
).await?.unwrap_or_else(|| GuildConfig::new(guild_id));
66+
).await?.unwrap_or_else(|| GuildConfig::new(guild_id.to_owned()));
6667

6768
self.configs_cache.insert(guild_id, config.to_owned());
69+
info!(
70+
name: "cached guild config",
71+
cache_size = self.configs_cache.len(),
72+
%guild_id,
73+
);
6874

6975
Ok(config)
7076
}

src/database/redis.rs

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ use crate::utils::errors::Error;
1010
use redis::AsyncCommands;
1111
use tokio::sync::mpsc::UnboundedSender;
1212
use tokio::sync::mpsc::error::SendError;
13+
use tracing::info;
1314
use crate::database::mongodb::MongoDBConnection;
1415

1516
#[derive(Serialize, Deserialize, Debug)]
@@ -127,16 +128,20 @@ impl RedisConnection {
127128
&self,
128129
mongodb: &MongoDBConnection
129130
) -> Result<(), RedisError> {
130-
131131
let mut pubsub = self.client.get_async_pubsub().await?;
132132
pubsub.subscribe("configs").await?;
133133

134134
while let Some(message) = pubsub.on_message().next().await {
135135
const ERROR: &str = "Received invalid payload instead of guild id";
136136
let id: String = message.get_payload().expect(ERROR);
137137
let id: Id<GuildMarker> = Id::from_str(id.as_str()).expect(ERROR);
138-
println!("There is a guild config update id={id}");
139138
mongodb.configs_cache.remove(&id);
139+
140+
info!(
141+
name: "removed config from cache due to update",
142+
cache_size = mongodb.configs_cache.len(),
143+
guild_id = %id,
144+
);
140145
}
141146

142147
Ok(())

src/events/automod/mod.rs

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,11 +3,12 @@ mod checks;
33
mod filters;
44

55
use std::sync::Arc;
6+
use tracing::info;
67
use twilight_http::Client;
78
use twilight_model::channel::Message;
89
use crate::context::Context;
910
use crate::events::automod::actions::run_action;
10-
use crate::models::config::automod::TrigerEvent;
11+
use crate::models::config::automod::TriggerEvent;
1112
use crate::models::config::automod::ignore::{Ignore, IgnoreMode};
1213

1314
fn is_ignored(message: &Message, ignore_rule: &Option<Ignore>) -> bool {
@@ -37,7 +38,7 @@ pub async fn run(
3738
message: Message,
3839
discord_http: Arc<Client>,
3940
context: Arc<Context>,
40-
triger: TrigerEvent
41+
trigger: TriggerEvent
4142
) -> Result<(), ()> {
4243
let guild_id = message.guild_id.ok_or(())?;
4344
let guild_config = Arc::new(context.mongodb.get_config(guild_id).await.map_err(|_| ())?);
@@ -52,7 +53,7 @@ pub async fn run(
5253
let message = Arc::new(message);
5354

5455
for automod_rule in &automod_config.rules {
55-
if triger == TrigerEvent::MessageUpdate && !automod_rule.check_on_edit { continue }
56+
if trigger == TriggerEvent::MessageUpdate && !automod_rule.check_on_edit { continue }
5657
if is_ignored(&message, &automod_rule.ignore) { continue }
5758

5859
for filter_meta in &automod_rule.filters {
@@ -64,6 +65,8 @@ pub async fn run(
6465
if !is_allowed { return Ok(()) }
6566
}
6667

68+
info!(name: "automod rule violated", ?message, ?automod_rule, ?trigger);
69+
6770
for action in &automod_rule.actions {
6871
let run = run_action(
6972
action.action.to_owned(),

src/events/mod.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ use twilight_http::Client;
33
use twilight_model::gateway::event::Event;
44
use twilight_model::gateway::payload::incoming::GuildCreate;
55
use crate::context::Context;
6-
use crate::models::config::automod::TrigerEvent;
6+
use crate::models::config::automod::TriggerEvent;
77

88
pub mod automod;
99
mod case;
@@ -27,11 +27,11 @@ pub async fn on_event(
2727
}
2828
Event::MessageCreate(event) => {
2929
let message = event.as_ref().0.to_owned();
30-
self::automod::run(message.to_owned(), discord_http, context.to_owned(), TrigerEvent::MessageCreate).await.ok();
30+
self::automod::run(message.to_owned(), discord_http, context.to_owned(), TriggerEvent::MessageCreate).await.ok();
3131
self::top::run(message, context).await.ok();
3232
}
3333
Event::MessageUpdate(event) => {
34-
self::automod::run(event.0, discord_http, context, TrigerEvent::MessageCreate).await.ok();
34+
self::automod::run(event.0, discord_http, context, TriggerEvent::MessageCreate).await.ok();
3535
}
3636
Event::GuildCreate(event) => {
3737
let guild = if let GuildCreate::Available(guild) = *event { guild } else { return Ok(()) };

src/events/setup.rs

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
use std::sync::Arc;
2+
use tracing::info;
23
use twilight_http::Client;
34
use twilight_model::id::Id;
45
use twilight_model::id::marker::GuildMarker;
@@ -16,6 +17,11 @@ pub async fn run(
1617
}
1718
} else { return Ok(()); };
1819

20+
info!(
21+
name: "registering setup command",
22+
%guild_id
23+
);
24+
1925
let application_id = twilight_http.current_user()
2026
.await.map_err(Error::from)?.model().await.map_err(Error::from)?.id;
2127
twilight_http

src/gateway/shard.rs

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
use std::sync::Arc;
2+
use tracing::error;
23
use twilight_gateway::{EventTypeFlags, Shard, StreamExt};
34
use twilight_model::gateway::{Intents, ShardId};
45
use crate::context::Context;
@@ -10,7 +11,13 @@ pub async fn connect_shards(
1011
context: Arc<Context>
1112
) {
1213
let token = if let Some(token) = http.token() { token.to_string() }
13-
else { eprintln!("Cannot get token of client {id}"); return };
14+
else {
15+
error!(
16+
name: "cannot get token of client",
17+
client_id = %id
18+
);
19+
return
20+
};
1421

1522
let intents = Intents::MESSAGE_CONTENT | Intents::GUILD_MESSAGES | Intents::GUILDS | Intents::GUILD_MODERATION | Intents::GUILD_MEMBERS;
1623

@@ -20,8 +27,10 @@ pub async fn connect_shards(
2027
let event = match event {
2128
Ok(event) => event,
2229
Err(err) => {
23-
eprintln!(
24-
"error while receiving events on shard {shard} with {id} client\n{err}",
30+
error!(
31+
name: "error while receiving events",
32+
error = %err,
33+
client_id = %id,
2534
shard = shard.id().number()
2635
);
2736
continue;

src/main.rs

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ use std::sync::Arc;
22
use crate::context::Context;
33
use dotenv::dotenv;
44
use tokio::task::JoinHandle;
5+
use tracing::info;
56
use twilight_http::Client;
67

78
all_macro!(
@@ -24,11 +25,15 @@ mod database;
2425
mod models;
2526
pub mod utils;
2627
mod server;
28+
mod tracing_init;
2729

2830
#[tokio::main]
2931
async fn main() {
3032
dotenv().ok();
3133

34+
tracing_init::init();
35+
info!("starting app");
36+
3237
let context = Arc::new(Context::new().await);
3338

3439
let cloned_context = context.clone();

src/models/config/automod/mod.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -41,8 +41,8 @@ pub struct AutoModerationRule {
4141
pub name: String,
4242
}
4343

44-
#[derive(PartialEq)]
45-
pub enum TrigerEvent {
44+
#[derive(PartialEq, Debug)]
45+
pub enum TriggerEvent {
4646
MessageCreate,
4747
MessageUpdate
48-
}
48+
}

0 commit comments

Comments
 (0)