Skip to main content

stoat/
context.rs

1use std::sync::Arc;
2
3use stoat_database::events::server::ClientMessage;
4use tokio::sync::mpsc::UnboundedSender;
5
6use crate::{
7    Error, GlobalCache, HttpClient,
8    notifiers::Notifiers,
9    types::StoatConfig,
10    websocket::{EventMessage, ProgramMessage},
11};
12
13
14/// Represents the outgoing websocket connection to Stoat.
15///
16/// This struct is cheaply cloneable using [`Arc`] internally.
17#[derive(Debug, Clone)]
18pub struct Events(pub(crate) Arc<UnboundedSender<EventMessage>>);
19
20impl AsRef<Events> for Events {
21    fn as_ref(&self) -> &Events {
22        self
23    }
24}
25
26impl Events {
27    pub(crate) fn send_message(&self, message: EventMessage) -> Result<(), Error> {
28        self.0.send(message).map_err(|_| Error::BrokenChannel)
29    }
30
31    /// Sends a raw [`ClientMessage`] to Stoat.
32    pub fn send_event(&self, event: ClientMessage) -> Result<(), Error> {
33        self.send_message(EventMessage::Client(event))
34    }
35
36    /// Closes the websocket connection, this will begin to shutdown the client.
37    pub fn close(&self) -> Result<(), Error> {
38        self.send_message(EventMessage::Program(ProgramMessage::Close))
39    }
40}
41
42/// Contains information from the client.
43///
44/// This struct is cheaply cloneable using [`Arc`] internally.
45#[derive(Debug, Clone)]
46pub struct Context {
47    pub cache: GlobalCache,
48    pub http: HttpClient,
49    pub notifiers: Notifiers,
50    pub events: Events,
51}
52
53impl AsRef<GlobalCache> for Context {
54    fn as_ref(&self) -> &GlobalCache {
55        &self.cache
56    }
57}
58
59impl AsRef<HttpClient> for Context {
60    fn as_ref(&self) -> &HttpClient {
61        &self.http
62    }
63}
64
65impl AsRef<Notifiers> for Context {
66    fn as_ref(&self) -> &Notifiers {
67        &self.notifiers
68    }
69}
70
71impl AsRef<Events> for Context {
72    fn as_ref(&self) -> &Events {
73        &self.events
74    }
75}
76
77impl AsRef<StoatConfig> for Context {
78    fn as_ref(&self) -> &StoatConfig {
79        &self.http.api_config
80    }
81}