summaryrefslogtreecommitdiff
path: root/exes/gateway/src/lib.rs
blob: 44fcce19cb5fbd620e4d4d428bed3e50495f60b6 (plain)
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
#![deny(
    clippy::all,
    clippy::correctness,
    clippy::suspicious,
    clippy::style,
    clippy::complexity,
    clippy::perf,
    clippy::pedantic,
    clippy::nursery,
    unsafe_code
)]
#![allow(clippy::redundant_pub_crate)]
use async_nats::{Client, HeaderMap, HeaderValue};
use config::Gateway;
use leash::{AnyhowResultFuture, Component};
use opentelemetry::{global, propagation::Injector};
use shared::{
    config::Settings,
    payloads::{CachePayload, DispatchEventTagged},
};
use std::{convert::TryFrom, future::Future, pin::Pin, str::FromStr};
use tokio::{select, sync::oneshot};
use tracing_opentelemetry::OpenTelemetrySpanExt;
use twilight_gateway::{Event, Shard, ShardId};
pub mod config;
use tracing::{debug, error, info, info_span, instrument, Instrument};
use twilight_model::gateway::event::DispatchEvent;

struct MetadataMap<'a>(&'a mut HeaderMap);

impl<'a> Injector for MetadataMap<'a> {
    fn set(&mut self, key: &str, value: String) {
        self.0.insert(key, HeaderValue::from_str(&value).unwrap());
    }
}

pub struct GatewayServer {}

impl Component for GatewayServer {
    type Config = Gateway;
    const SERVICE_NAME: &'static str = "gateway";

    fn start(
        &self,
        settings: Settings<Self::Config>,
        mut stop: oneshot::Receiver<()>,
    ) -> AnyhowResultFuture<()> {
        Box::pin(async move {
            let mut shard = Shard::new(
                ShardId::new(settings.shard, settings.shard_total),
                settings.token.clone(),
                settings.intents,
            );

            let nats = Into::<Pin<Box<dyn Future<Output = anyhow::Result<Client>> + Send>>>::into(
                settings.nats,
            )
            .await?;

            loop {
                select! {
                    event = shard.next_event() => {
                        match event {
                            Ok(event) => {
                                let _ = handle_event(event, &nats)
                                    .await
                                    .map_err(|err| error!(error = ?err, "event publish failed"));
                            },
                            Err(source) => {
                                if source.is_fatal() {
                                    break;
                                }
                                continue;
                            }
                        }
                    },
                    _ = (&mut stop) => break
                };
            }

            info!("stopping shard...");
            Ok(())
        })
    }

    fn new() -> Self {
        Self {}
    }
}

#[instrument]
async fn handle_event(event: Event, nats: &Client) -> anyhow::Result<()> {
    if let Event::Ready(ready) = event {
        info!(username = ready.user.name, "logged in");
    } else {
        let name = event.kind().name();
        if let Ok(dispatch_event) = DispatchEvent::try_from(event) {
            let name = name.unwrap();
            debug!(event_name = name, "handling dispatch event");

            let data = CachePayload {
                data: DispatchEventTagged(dispatch_event),
            };
            let value = serde_json::to_string(&data)?;
            let bytes = bytes::Bytes::from(value);

            let span = info_span!("nats send");

            let mut header_map = HeaderMap::new();
            let context = span.context();
            global::get_text_map_propagator(|propagator| {
                propagator.inject_context(&context, &mut MetadataMap(&mut header_map));
            });

            nats.publish_with_headers(format!("nova.cache.dispatch.{name}"), header_map, bytes)
                .instrument(info_span!("sending to nats"))
                .await?;
        }
    }

    Ok(())
}