1use 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#[derive(Debug)]
23pub(crate) struct Shared {
24 pub(crate) application_id: OnceLock<ApplicationId>,
26 pub(crate) collectors: Arc<Collectors>,
28 pub(crate) sequential: bool,
30 pub(crate) intents: Intents,
32 #[cfg(feature = "gateway")]
34 pub(crate) shards: RwLock<Vec<(u32, MessageSender)>>,
35 pub(crate) total_shards: core::sync::atomic::AtomicU32,
37 pub(crate) shutdown: watch::Sender<bool>,
40 #[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 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#[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
94pub(crate) struct Core {
97 rest: Rest,
98 shard: ShardId,
99 #[cfg(feature = "gateway")]
100 sender: MessageSender,
101 shared: Arc<Shared>,
102 ops: Arc<dyn CacheOps>,
104 #[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 pub(crate) fn collectors(&self) -> &Arc<Collectors> {
122 &self.shared.collectors
123 }
124
125 pub(crate) const fn shard_id(&self) -> ShardId {
127 self.shard
128 }
129
130 pub(crate) fn ops(&self) -> &dyn CacheOps {
132 &*self.ops
133 }
134
135 #[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 #[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 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 #[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 pub(crate) fn core(&self) -> &Core {
219 &self.inner.core
220 }
221
222 pub(crate) fn ops(&self) -> &dyn CacheOps {
224 self.inner.core.ops()
225 }
226
227 pub(crate) fn collectors(&self) -> &Arc<Collectors> {
229 self.inner.core.collectors()
230 }
231
232 pub(crate) fn is_sequential(&self) -> bool {
234 self.inner.core.shared.sequential
235 }
236
237 pub(crate) fn intents(&self) -> Intents {
239 self.inner.core.shared.intents
240 }
241
242 #[must_use]
248 pub fn application_id(&self) -> Option<ApplicationId> {
249 self.inner.core.shared.application_id.get().copied()
250 }
251
252 #[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 #[must_use]
263 pub fn rest(&self) -> &Rest {
264 &self.inner.core.rest
265 }
266
267 #[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 #[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 #[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 pub fn shutdown(&self) {
322 self.inner.core.shared.shutdown.send_replace(true);
323 }
324}