composure 0.1.0

Discord bots over HTTP Interactions, no gateway: slash commands, components, modals and JSX-like views, on Cloudflare Workers (WASM) or any server
Documentation
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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
//! REST and Background Work for handlers, when the Adapter's State provides them (ADR 0006).

use std::{future::Future, pin::Pin, sync::Arc, time::Duration};

use crate::{
    rest::{BotClient, EditMessage, Error, InteractionClient, Transport},
    types::{
        ApplicationCommandInteractionData, DataInteraction, InteractionCommon, InteractionResponse,
        Member, MessageComponentData, MessageFlags, ModalSubmitData, Snowflake, User,
    },
};

use super::{CommandOutput, Ctx, HandlerError, IntoResponse, Theme};
use crate::trace::Instrument;

/// Background Work handed to the Adapter: runs after the response is sent; an `Err` is logged.
/// `Send`, so Adapters can run it on any thread (ADR 0012).
pub type BackgroundWork = Pin<Box<dyn Future<Output = Result<(), HandlerError>> + Send>>;

/// What an Adapter's State offers beyond its own resources: a [`Transport`] for REST, a way to run
/// Background Work, and the bot token when configured. Implemented by each Adapter's State
/// (`composure_adapter_cloudflare::Worker`, `composure_adapter_tokio::Host`); enables
/// [`Ctx::client`], [`Ctx::bot`] and [`Ctx::defer`].
pub trait Platform: Clone + Send + Sync + 'static {
    /// The HTTP client REST calls go through
    type Transport: Transport + Clone + 'static;

    /// A handle to the Transport, for a new client
    fn transport(&self) -> Self::Transport;

    /// Runs `work` after the response is sent (`wait_until` on Cloudflare, `tokio::spawn` on a
    /// hosted server), within the platform's post-response time limit
    fn spawn(&self, work: BackgroundWork);

    /// The bot token (`DISCORD_TOKEN`), without the `Bot ` prefix
    fn bot_token(&self) -> Option<String>;
}

fn interaction_client<S: Platform>(
    state: &S,
    common: &InteractionCommon,
) -> InteractionClient<S::Transport> {
    InteractionClient::new(
        state.transport(),
        common.application_id,
        common.id,
        common.token.clone(),
    )
}

fn bot_client<S: Platform>(
    state: &S,
    common: &InteractionCommon,
) -> Result<BotClient<S::Transport>, HandlerError> {
    let token = state
        .bot_token()
        .ok_or_else(|| HandlerError::new("the bot token (DISCORD_TOKEN) is not configured"))?;
    Ok(BotClient::new(
        state.transport(),
        &token,
        common.application_id,
    ))
}

impl<'a, S: Platform, D: Clone + Send + Sync + 'static> Ctx<'a, S, D> {
    /// Follow-ups and the original response of this Interaction. Before the handler returns,
    /// only Endpoints that do not depend on the initial response work; use [`defer`](Self::defer)
    /// to act after it.
    pub fn client(&self) -> InteractionClient<S::Transport> {
        interaction_client(self.state(), &self.interaction().common)
    }

    /// Client authorized by the bot token; an error when the Adapter has none
    pub fn bot(&self) -> Result<BotClient<S::Transport>, HandlerError> {
        bot_client(self.state(), &self.interaction().common)
    }

    /// Answers with a Deferred Response (the user sees "thinking...") and runs `work` as
    /// Background Work; its output then replaces the original response, like a handler's return
    /// value would have been sent. Wrap in [`Ephemeral`](super::Ephemeral) to make the response
    /// ephemeral; that is decided now, not by `work`'s output.
    ///
    /// ```ignore
    /// #[command]
    /// fn report(ctx: Ctx<Worker>) -> Deferred {
    ///     ctx.defer(async |ctx| {
    ///         let stats = slow_query(ctx.state()).await?;
    ///         Ok::<_, HandlerError>(format!("{stats} rows"))
    ///     })
    /// }
    /// ```
    pub fn defer<F, Fut>(&self, work: F) -> Deferred
    where
        F: FnOnce(DeferredCtx<S, D>) -> Fut,
        Fut: Future<Output: CommandOutput> + Send + 'static,
    {
        self.spawn_completion(work);
        Deferred(())
    }

    /// Runs `work` as Background Work, then edits the original response with its output
    fn spawn_completion<F, Fut>(&self, work: F)
    where
        F: FnOnce(DeferredCtx<S, D>) -> Fut,
        Fut: Future<Output: CommandOutput> + Send + 'static,
    {
        let theme = self.configured_theme();
        let ctx = DeferredCtx {
            interaction: Arc::clone(self.shared_interaction()),
            state: self.state().clone(),
            theme,
        };
        let client = ctx.client();
        let output = work(ctx);
        // A child of the `interaction` span; entered while spawning so Adapters that instrument
        // `spawn` with the current span pick it up too
        let span = info_span!("background_work");
        let work = async move {
            debug!("background work started");
            let result = complete(client, output, theme).await;
            #[cfg(feature = "tracing")]
            match &result {
                Ok(()) => debug!("background work done"),
                Err(error) => error.trace("background work failed"),
            }
            result
        }
        .instrument(span.clone());
        span.in_scope(|| self.state().spawn(Box::pin(work)));
    }
}

/// Background Work's body: awaits the handler's output, then edits the original response with it
/// (an error as its message). A failed edit, else the handler's error, is the result.
async fn complete<T: Transport>(
    client: InteractionClient<T>,
    output: impl Future<Output: CommandOutput> + Send,
    theme: Option<&'static Theme>,
) -> Result<(), HandlerError> {
    let (mut response, error) = match output.await.into_result() {
        Ok(response) => (response, None),
        Err(error) => (error.response_with(theme), Some(error)),
    };
    if let Some(theme) = theme {
        theme.apply(&mut response);
    }
    if let Some(data) = response.into_message_data() {
        // Ephemerality was fixed by the deferred reply; edits cannot change it
        let flags = data
            .flags
            .map(|flags| flags - MessageFlags::Ephemeral)
            .filter(|flags| !flags.is_empty());
        let edit = EditMessage {
            flags,
            ..EditMessage::from(&data)
        };
        edit_original(&client, &edit).await.map_err(|error| {
            HandlerError::new(format_args!(
                "editing the original response failed: {error}"
            ))
        })?;
    }
    error.map_or(Ok(()), Err)
}

/// Interaction data whose original response is a message that can be updated in place
pub trait Updatable: private::Sealed {}

impl Updatable for MessageComponentData {}
impl Updatable for ModalSubmitData {}

mod private {
    pub trait Sealed {}
    impl Sealed for crate::types::MessageComponentData {}
    impl Sealed for crate::types::ModalSubmitData {}
}

impl<'a, S: Platform, D: Updatable + Clone + Send + Sync + 'static> Ctx<'a, S, D> {
    /// Acknowledges without a loading message (Discord type 6) and runs `work` as Background
    /// Work; its output then replaces the message the component is on
    pub fn defer_update<F, Fut>(&self, work: F) -> DeferredUpdate
    where
        F: FnOnce(DeferredCtx<S, D>) -> Fut,
        Fut: Future<Output: CommandOutput> + Send + 'static,
    {
        self.spawn_completion(work);
        DeferredUpdate(())
    }
}

/// Retries while Discord has not yet seen the deferred reply: Background Work can start before
/// the platform finishes sending it
async fn edit_original<T: Transport>(
    client: &InteractionClient<T>,
    message: &EditMessage<'_>,
) -> Result<(), Error> {
    const ATTEMPTS: u32 = 4;
    for attempt in 1.. {
        match client.edit_original(message).await {
            Err(Error::Api(error)) if error.status == 404 && attempt < ATTEMPTS => {
                debug!(attempt, "original response not found yet; retrying");
                client
                    .transport()
                    .sleep(Duration::from_millis(250 * u64::from(attempt)))
                    .await;
            }
            result => return result.map(drop),
        }
    }
    unreachable!()
}

/// Returned by [`Ctx::defer`]: a Deferred Response whose Background Work is already scheduled
#[derive(Debug)]
#[must_use = "return it from the handler, or the user sees no response"]
pub struct Deferred(());

impl IntoResponse for Deferred {
    fn into_response(self) -> InteractionResponse {
        InteractionResponse::DeferredChannelMessageWithSource(None)
    }
}

/// Returned by [`Ctx::defer_update`]: an acknowledgement whose Background Work will update the
/// component's message
#[derive(Debug)]
#[must_use = "return it from the handler, or the user sees no response"]
pub struct DeferredUpdate(());

impl IntoResponse for DeferredUpdate {
    fn into_response(self) -> InteractionResponse {
        InteractionResponse::DeferredUpdateMessage
    }
}

/// What deferred Background Work sees: an owned, `'static` copy of the Interaction and State
pub struct DeferredCtx<S, D = ApplicationCommandInteractionData> {
    interaction: Arc<DataInteraction<D>>,
    state: S,
    theme: Option<&'static Theme>,
}

impl<S: Clone, D> Clone for DeferredCtx<S, D> {
    fn clone(&self) -> Self {
        Self {
            interaction: self.interaction.clone(),
            state: self.state.clone(),
            theme: self.theme,
        }
    }
}

impl<S: Platform, D> DeferredCtx<S, D> {
    /// The Interaction being answered
    pub fn interaction(&self) -> &DataInteraction<D> {
        &self.interaction
    }

    /// The Interaction's data
    pub fn data(&self) -> &D {
        &self.interaction.data
    }

    /// Platform resources passed through by the Adapter
    pub fn state(&self) -> &S {
        &self.state
    }

    /// The App's colors and branding; [`Theme::DEFAULT`] when the App has none
    pub fn theme(&self) -> &'static Theme {
        self.theme.unwrap_or(&Theme::DEFAULT)
    }

    /// The invoking user, in guilds and DMs alike
    pub fn user(&self) -> Option<&User> {
        self.interaction.common.invoking_user()
    }

    /// The invoking member, in guilds only
    pub fn member(&self) -> Option<&Member> {
        self.interaction.common.member.as_ref()
    }

    /// The guild it was invoked in; `None` in DMs
    pub fn guild_id(&self) -> Option<Snowflake> {
        self.interaction.common.guild_id
    }

    /// The channel it was invoked in
    pub fn channel_id(&self) -> Option<Snowflake> {
        self.interaction.common.channel_id
    }

    /// Follow-ups and the original response of this Interaction
    pub fn client(&self) -> InteractionClient<S::Transport> {
        interaction_client(&self.state, &self.interaction.common)
    }

    /// Client authorized by the bot token; an error when the Adapter has none
    pub fn bot(&self) -> Result<BotClient<S::Transport>, HandlerError> {
        bot_client(&self.state, &self.interaction.common)
    }

    /// Waits on the platform's timer (counts toward the Background Work time limit)
    pub async fn sleep(&self, duration: Duration) {
        self.state.transport().sleep(duration).await
    }
}

#[cfg(test)]
mod tests {
    use std::sync::Mutex;

    use futures::executor::block_on;
    use serde_json::json;

    use super::*;
    use crate::{
        command::Ephemeral,
        rest::testing::MockTransport,
        types::{ApplicationCommandInteraction, Interaction},
    };

    #[derive(Clone, Default)]
    struct TestPlatform {
        transport: Arc<MockTransport>,
        work: Arc<Mutex<Vec<BackgroundWork>>>,
    }

    impl Platform for TestPlatform {
        type Transport = Arc<MockTransport>;

        fn transport(&self) -> Self::Transport {
            self.transport.clone()
        }

        fn spawn(&self, work: BackgroundWork) {
            self.work.lock().unwrap().push(work);
        }

        fn bot_token(&self) -> Option<String> {
            None
        }
    }

    impl TestPlatform {
        fn run(&self) -> Result<(), HandlerError> {
            let work = self.work.lock().unwrap().pop().expect("work was spawned");
            block_on(work)
        }

        fn edits(&self) -> Vec<(String, serde_json::Value)> {
            self.transport
                .requests
                .borrow()
                .iter()
                .map(|r| {
                    let body = serde_json::from_slice(r.body.as_deref().unwrap()).unwrap();
                    (r.url.clone(), body)
                })
                .collect()
        }
    }

    fn interaction() -> Arc<ApplicationCommandInteraction> {
        let payload = json!({
            "id": "2", "application_id": "1", "type": 2, "token": "tok", "version": 1,
            "user": { "id": "3", "username": "a", "discriminator": "0", "global_name": null, "avatar": null },
            "data": { "id": "4", "name": "slow", "type": 1 },
        });
        match serde_json::from_value(payload).unwrap() {
            Interaction::ApplicationCommand(interaction) => Arc::new(interaction),
            _ => unreachable!(),
        }
    }

    const ORIGINAL: &str = "https://discord.com/api/v10/webhooks/1/tok/messages/@original";

    #[test]
    fn defer_answers_type_5_and_edits_original_with_the_output() {
        let platform = TestPlatform::default();
        let interaction = interaction();
        let ctx = Ctx::new(&interaction, &platform);
        let response = ctx
            .defer(async |ctx| format!("done for {}", ctx.user().unwrap().username))
            .into_response();
        assert!(matches!(
            response,
            InteractionResponse::DeferredChannelMessageWithSource(None)
        ));
        assert!(platform.transport.requests.borrow().is_empty());

        platform.run().unwrap();
        assert_eq!(
            platform.edits(),
            [(ORIGINAL.to_string(), json!({ "content": "done for a" }))]
        );
    }

    #[test]
    fn ephemeral_defer_sets_the_flag() {
        let platform = TestPlatform::default();
        let interaction = interaction();
        let ctx = Ctx::new(&interaction, &platform);
        let response = Ephemeral(ctx.defer(async |_| "ok")).into_response();
        assert!(matches!(
            response,
            InteractionResponse::DeferredChannelMessageWithSource(Some(MessageFlags::Ephemeral))
        ));
    }

    #[test]
    fn errors_edit_with_the_error_message_and_are_reported() {
        let platform = TestPlatform::default();
        let interaction = interaction();
        let ctx = Ctx::new(&interaction, &platform);
        let _ = ctx.defer(async |_| Err::<String, _>(HandlerError::user("nope")));
        assert_eq!(platform.run().unwrap_err().to_string(), "nope");
        assert_eq!(
            platform.edits(),
            [(ORIGINAL.to_string(), json!({ "content": "nope" }))]
        );
    }

    #[test]
    fn retries_while_the_deferral_is_unknown() {
        let transport = MockTransport::default()
            .respond(404, r#"{"code":10015,"message":"Unknown Webhook"}"#)
            .respond(200, "{}");
        let platform = TestPlatform {
            transport: Arc::new(transport),
            ..Default::default()
        };
        let interaction = interaction();
        let _ = Ctx::new(&interaction, &platform).defer(async |_| "ok");
        platform.run().unwrap();
        assert_eq!(platform.edits().len(), 2);
        assert_eq!(
            *platform.transport.sleeps.borrow(),
            [Duration::from_millis(250)]
        );
    }

    const THEME: Theme = Theme::new().with_primary(0x123456).with_footer("Bot", None);

    #[test]
    fn themed_defer_fills_in_the_edit() {
        let platform = TestPlatform::default();
        let interaction = interaction();
        let ctx = Ctx::new(&interaction, &platform).with_theme(Some(&THEME));
        let _ = ctx.defer(async |ctx| {
            assert_eq!(ctx.theme(), &THEME);
            crate::types::Embed::new().with_title("done")
        });
        platform.run().unwrap();
        let (_, body) = &platform.edits()[0];
        assert_eq!(body["embeds"][0]["color"], 0x123456);
        assert_eq!(body["embeds"][0]["footer"]["text"], "Bot");
    }

    #[test]
    fn themed_defer_fills_container_accents_and_keeps_v2() {
        let platform = TestPlatform::default();
        let interaction = interaction();
        let ctx = Ctx::new(&interaction, &platform).with_theme(Some(&THEME));
        let _ = Ephemeral(ctx.defer(async |_| {
            crate::types::Container::new(vec![crate::types::Component::text("done")])
        }));
        platform.run().unwrap();
        let (_, body) = &platform.edits()[0];
        assert_eq!(body["components"][0]["type"], 17);
        assert_eq!(body["components"][0]["accent_color"], 0x123456);
        assert_eq!(body["flags"], MessageFlags::IsComponentsV2.bits());
        assert_eq!(body.get("content"), None);
    }

    #[test]
    fn themed_defer_errors_are_error_embeds() {
        let platform = TestPlatform::default();
        let interaction = interaction();
        let ctx = Ctx::new(&interaction, &platform).with_theme(Some(&THEME));
        let _ = ctx.defer(async |_| Err::<String, _>(HandlerError::user("nope")));
        assert!(platform.run().is_err());
        let (_, body) = &platform.edits()[0];
        assert_eq!(body["embeds"][0]["color"], Theme::DEFAULT.error);
        assert_eq!(body["embeds"][0]["description"], "nope");
        assert_eq!(body.get("flags"), None);
    }

    #[test]
    fn bot_needs_a_token() {
        let platform = TestPlatform::default();
        let interaction = interaction();
        assert!(Ctx::new(&interaction, &platform).bot().is_err());
    }
}