Skip to main content

djs_rs/
context.rs

1//! The [`Context`] passed to event handlers.
2
3use core::fmt;
4use std::sync::{Arc, OnceLock, PoisonError, RwLock};
5
6use djs_cache::{Backend, Cache, DashMapBackend};
7#[cfg(feature = "gateway")]
8use djs_gateway::MessageSender;
9use djs_model::{
10    gateway::{Intents, ShardId},
11    id::{ApplicationId, GuildId},
12};
13use djs_rest::Rest;
14use tokio::sync::watch;
15
16use crate::{
17    cache_ops::{CacheOps, converter},
18    collector::Collectors,
19};
20
21/// What the client and every shard's [`Context`] share.
22#[derive(Debug)]
23pub(crate) struct Shared {
24    /// Set by the client at the first `READY` (D-245).
25    pub(crate) application_id: OnceLock<ApplicationId>,
26    /// The running collectors (D-264).
27    pub(crate) collectors: Arc<Collectors>,
28    /// Whether handlers run one after another (collectors then warn, D-267).
29    pub(crate) sequential: bool,
30    /// The client's intents (collectors warn about missing ones, D-271).
31    pub(crate) intents: Intents,
32    /// The senders of the running shards, by shard number (empty while not running).
33    #[cfg(feature = "gateway")]
34    pub(crate) shards: RwLock<Vec<(u32, MessageSender)>>,
35    /// The bot's total shard count, across processes, of the current `login` (0 before).
36    pub(crate) total_shards: core::sync::atomic::AtomicU32,
37    /// Set to `true` to stop the running client ([`Client::shutdown`](crate::Client::shutdown),
38    /// [`Context::shutdown`], D-293); `login` sets it back to `false`.
39    pub(crate) shutdown: watch::Sender<bool>,
40    /// A cluster process's open connection to its manager, for its outgoing requests
41    /// (D-307).
42    #[cfg(feature = "sharding")]
43    pub(crate) link: std::sync::Mutex<Option<Arc<crate::sharding::Link>>>,
44}
45
46impl Default for Shared {
47    fn default() -> Self {
48        Self {
49            application_id: OnceLock::new(),
50            collectors: Arc::default(),
51            sequential: false,
52            intents: Intents::empty(),
53            #[cfg(feature = "gateway")]
54            shards: RwLock::default(),
55            total_shards: core::sync::atomic::AtomicU32::new(0),
56            shutdown: watch::channel(false).0,
57            #[cfg(feature = "sharding")]
58            link: std::sync::Mutex::new(None),
59        }
60    }
61}
62
63#[cfg(feature = "gateway")]
64impl Shared {
65    /// The sender of shard `number`, if it runs in this client.
66    pub(crate) fn shard(&self, number: u32) -> Option<MessageSender> {
67        self.shards
68            .read()
69            .unwrap_or_else(PoisonError::into_inner)
70            .iter()
71            .find(|(shard, _)| *shard == number)
72            .map(|(_, sender)| sender.clone())
73    }
74}
75
76/// Everything an event handler needs to act: the REST client, the cache and the shard that
77/// received the event.
78///
79/// Cheap to clone (a single reference count increment). `B` is the cache backend of the
80/// [`Client`](crate::Client) (D-172); code that does not name it gets the default.
81///
82/// discord.js counterpart: the `client` reachable from every structure (`message.client`).
83#[derive(Debug)]
84pub struct Context<B: Backend = DashMapBackend> {
85    inner: Arc<Inner<B>>,
86}
87
88#[derive(Debug)]
89struct Inner<B: Backend> {
90    core: Core,
91    cache: Option<Arc<Cache<B>>>,
92}
93
94/// The part of a [`Context`] that does not depend on the cache backend: code that needs
95/// only this is not generic, so it is compiled once, in djs-rs (D-289).
96pub(crate) struct Core {
97    rest: Rest,
98    shard: ShardId,
99    #[cfg(feature = "gateway")]
100    sender: MessageSender,
101    shared: Arc<Shared>,
102    /// The cache's operations, or the converter's without a cache (D-289).
103    ops: Arc<dyn CacheOps>,
104    /// Where an HTTP interaction's initial response goes (D-399); `None` for gateway events.
105    #[cfg(feature = "http-interactions")]
106    inline: Option<crate::http_interactions::Inline>,
107}
108
109impl fmt::Debug for Core {
110    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
111        let mut debug = f.debug_struct("Core");
112        debug.field("rest", &self.rest).field("shard", &self.shard);
113        #[cfg(feature = "gateway")]
114        debug.field("sender", &self.sender);
115        debug.field("shared", &self.shared).finish_non_exhaustive()
116    }
117}
118
119impl Core {
120    /// The running collectors (D-264).
121    pub(crate) fn collectors(&self) -> &Arc<Collectors> {
122        &self.shared.collectors
123    }
124
125    /// The ID of the shard that received the event.
126    pub(crate) const fn shard_id(&self) -> ShardId {
127        self.shard
128    }
129
130    /// The cache operations (D-289): the cache's, or a converter's that keeps nothing.
131    pub(crate) fn ops(&self) -> &dyn CacheOps {
132        &*self.ops
133    }
134
135    /// Takes the slot of `interaction`'s initial response, if the context is that HTTP
136    /// interaction's and nothing has responded yet (D-399).
137    #[cfg(feature = "http-interactions")]
138    pub(crate) fn take_inline(
139        &self,
140        interaction: djs_model::id::InteractionId,
141    ) -> Option<crate::http_interactions::InitialSender> {
142        self.inline.as_ref()?.take(interaction)
143    }
144
145    /// The sender of the shard that receives `guild`'s events, if it runs in this client.
146    #[cfg(feature = "gateway")]
147    pub(crate) fn guild_shard(&self, guild: GuildId) -> Option<MessageSender> {
148        let own = self.shard;
149        let number = ShardId::for_guild(guild, own.total()).number();
150        if number == own.number() {
151            Some(self.sender.clone())
152        } else {
153            self.shared.shard(number)
154        }
155    }
156}
157
158impl<B: Backend> Clone for Context<B> {
159    fn clone(&self) -> Self {
160        Self {
161            inner: Arc::clone(&self.inner),
162        }
163    }
164}
165
166impl<B: Backend> Context<B> {
167    pub(crate) fn new(
168        rest: Rest,
169        shard: ShardId,
170        #[cfg(feature = "gateway")] sender: MessageSender,
171        cache: Option<Arc<Cache<B>>>,
172        state: Arc<Shared>,
173    ) -> Self {
174        // Created here, in the client loop, so that for the default backend the cache
175        // operations are compiled in djs-rs (D-289).
176        let ops = match &cache {
177            Some(cache) => Arc::clone(cache) as Arc<dyn CacheOps>,
178            None => converter(),
179        };
180        Self {
181            inner: Arc::new(Inner {
182                core: Core {
183                    rest,
184                    shard,
185                    #[cfg(feature = "gateway")]
186                    sender,
187                    shared: state,
188                    ops,
189                    #[cfg(feature = "http-interactions")]
190                    inline: None,
191                },
192                cache,
193            }),
194        }
195    }
196
197    /// A context for one HTTP interaction, whose initial response goes to `inline` (D-399).
198    #[cfg(feature = "http-interactions")]
199    pub(crate) fn http(
200        rest: Rest,
201        shard: ShardId,
202        #[cfg(feature = "gateway")] sender: MessageSender,
203        cache: Option<Arc<Cache<B>>>,
204        state: Arc<Shared>,
205        inline: crate::http_interactions::Inline,
206    ) -> Self {
207        #[cfg(feature = "gateway")]
208        let mut ctx = Self::new(rest, shard, sender, cache, state);
209        #[cfg(not(feature = "gateway"))]
210        let mut ctx = Self::new(rest, shard, cache, state);
211        if let Some(inner) = Arc::get_mut(&mut ctx.inner) {
212            inner.core.inline = Some(inline);
213        }
214        ctx
215    }
216
217    /// The part of the context that does not depend on the cache backend (D-289).
218    pub(crate) fn core(&self) -> &Core {
219        &self.inner.core
220    }
221
222    /// The cache operations (D-289): the cache's, or a converter's that keeps nothing.
223    pub(crate) fn ops(&self) -> &dyn CacheOps {
224        self.inner.core.ops()
225    }
226
227    /// The running collectors (D-264).
228    pub(crate) fn collectors(&self) -> &Arc<Collectors> {
229        self.inner.core.collectors()
230    }
231
232    /// Whether handlers run one after another (D-267).
233    pub(crate) fn is_sequential(&self) -> bool {
234        self.inner.core.shared.sequential
235    }
236
237    /// The client's intents.
238    pub(crate) fn intents(&self) -> Intents {
239        self.inner.core.shared.intents
240    }
241
242    /// Returns the bot's application ID, known from the first `READY` (D-245); `None` only in
243    /// handlers that run before it (`ShardError`, `Invalidated`, `ShardDisconnect` while
244    /// logging in).
245    ///
246    /// discord.js counterpart: `client.application.id`.
247    #[must_use]
248    pub fn application_id(&self) -> Option<ApplicationId> {
249        self.inner.core.shared.application_id.get().copied()
250    }
251
252    /// The application ID for the application managers (D-247).
253    #[track_caller]
254    pub(crate) fn expect_application_id(&self) -> ApplicationId {
255        self.application_id()
256            .expect("the application ID is known from the first READY; this handler ran before it")
257    }
258
259    /// Returns the REST client.
260    ///
261    /// discord.js counterpart: `Client#rest`.
262    #[must_use]
263    pub fn rest(&self) -> &Rest {
264        &self.inner.core.rest
265    }
266
267    /// Returns the cache, if the client has one ([`ClientBuilder::cache`](crate::ClientBuilder::cache),
268    /// D-170). The event being handled is already applied to it (D-171).
269    ///
270    /// discord.js counterpart: the managers' `cache` collections (`client.guilds.cache`, …).
271    #[must_use]
272    pub fn cache(&self) -> Option<&Cache<B>> {
273        self.inner.cache.as_deref()
274    }
275
276    #[cfg(feature = "gateway")]
277    #[cfg_attr(docsrs, doc(cfg(feature = "gateway")))]
278    /// Returns the ID of the shard that received the event.
279    ///
280    /// discord.js counterpart: the `shardId` some discord.js events pass; `Guild#shardId`.
281    #[must_use]
282    pub fn shard_id(&self) -> ShardId {
283        self.inner.core.shard
284    }
285
286    #[cfg(feature = "gateway")]
287    #[cfg_attr(docsrs, doc(cfg(feature = "gateway")))]
288    /// Returns a sender for gateway commands on the shard that received the event.
289    ///
290    /// discord.js counterpart: `Guild#shard`.
291    #[must_use]
292    pub fn shard(&self) -> &MessageSender {
293        &self.inner.core.sender
294    }
295
296    #[cfg(feature = "gateway")]
297    #[cfg_attr(docsrs, doc(cfg(feature = "gateway")))]
298    /// Asks the client to disconnect, as [`Client::shutdown`](crate::Client::shutdown) does:
299    /// every shard closes, the session is invalidated (the bot appears offline) and
300    /// [`Client::login`](crate::Client::login) returns `Ok(())`. Has no effect once the client
301    /// has stopped.
302    ///
303    /// discord.js counterpart: `client.destroy()` (through `message.client`).
304    ///
305    /// # Examples
306    ///
307    /// ```no_run
308    /// use djs_rs::{model::id::UserId, prelude::*};
309    ///
310    /// # fn register(client: &Client) {
311    /// const OWNER: UserId = UserId::new(123_456_789_012_345_678);
312    /// client.on(Events::MessageCreate, |ctx, msg| async move {
313    ///     if msg.content == "!stop" && msg.author.id == OWNER {
314    ///         msg.reply(&ctx, "Bye!").await?;
315    ///         ctx.shutdown();
316    ///     }
317    ///     Ok(())
318    /// });
319    /// # }
320    /// ```
321    pub fn shutdown(&self) {
322        self.inner.core.shared.shutdown.send_replace(true);
323    }
324}