djs_rest/client.rs
1//! The [`Rest`] client and its builder.
2
3use core::{fmt, pin::Pin, time::Duration};
4use std::sync::Arc;
5
6use bytes::Bytes;
7use djs_model::{guild::WidgetStyle, id::GuildId, rest::FileUpload};
8use http::{
9 HeaderName, HeaderValue, StatusCode, Uri,
10 header::{AUTHORIZATION, CONTENT_TYPE, USER_AGENT},
11};
12use serde::{Serialize, de::DeserializeOwned};
13
14use crate::{
15 cdn::{self, Cdn},
16 error::{ApiError, BoxError, Error, ErrorKind, RateLimitedBody},
17 multipart::{Form, PreparedBody},
18 query::{Query, QueryWriter},
19 ratelimit::{InvalidRequests, RateLimitHeaders, RateLimiter},
20 route::{self, Route},
21 transport::{Body, Instant, Transport},
22};
23
24/// The header that carries the [audit log reason](Request::reason).
25const AUDIT_LOG_REASON: HeaderName = HeaderName::from_static("x-audit-log-reason");
26
27/// The default API base URL.
28pub const DEFAULT_API: &str = "https://discord.com/api";
29
30/// Boxes a future built in this crate, so that its body is compiled here once instead of in
31/// every crate that awaits it (D-287): the public async methods return what this returns.
32pub(crate) fn boxed<'a, T>(
33 future: impl Future<Output = T> + Send + 'a,
34) -> Pin<Box<dyn Future<Output = T> + Send + 'a>> {
35 Box::pin(future)
36}
37
38/// Decodes a response body; an empty body (204 No Content) decodes like `null`, which fits
39/// `()` and `Option`.
40fn decode<T: DeserializeOwned>(body: &[u8]) -> Result<T, Error> {
41 let body: &[u8] = if body.is_empty() { b"null" } else { body };
42 serde_json::from_slice(body)
43 .map_err(|source| Error::with_source(ErrorKind::Deserialize, source))
44}
45
46/// A client for the Discord REST API.
47///
48/// `Rest` handles authentication, [rate limits](https://docs.discord.com/developers/topics/rate-limits),
49/// retries and timeouts. It is cheap to [`Clone`] — clones share the same connection pool and
50/// rate-limit state, so create one per bot and pass clones around.
51///
52/// HTTP/2 is negotiated automatically, so concurrent requests share a single connection.
53///
54/// discord.js counterpart: `REST` from `@discordjs/rest`.
55///
56/// # Examples
57///
58/// ```no_run
59/// use djs_model::id::ChannelId;
60/// use djs_rest::Rest;
61///
62/// # async fn example() -> Result<(), djs_rest::Error> {
63/// let rest = Rest::new(std::env::var("DISCORD_TOKEN").unwrap());
64///
65/// let gateway = rest.get_gateway_bot().await?;
66/// println!("recommended shards: {}", gateway.shards);
67///
68/// rest.create_message(ChannelId::new(1_234_567_890_123_456_789), &"Hello!".into())
69/// .await?;
70/// # Ok(())
71/// # }
72/// ```
73#[derive(Clone)]
74pub struct Rest {
75 inner: Arc<Inner>,
76}
77
78struct Inner {
79 transport: Arc<dyn Transport>,
80 token: Token,
81 /// `{api}/v{version}`, without a trailing slash.
82 base: String,
83 user_agent: HeaderValue,
84 timeout: Duration,
85 retries: u8,
86 ratelimiter: RateLimiter,
87 invalid: InvalidRequests,
88 /// `0` = no fail-fast limit.
89 invalid_request_limit: u32,
90 cdn: Cdn,
91}
92
93/// The authorization header, validated once at construction.
94enum Token {
95 None,
96 Valid(HeaderValue),
97 Invalid,
98}
99
100impl fmt::Debug for Rest {
101 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
102 f.debug_struct("Rest")
103 .field("base", &self.inner.base)
104 .field(
105 "token",
106 &match self.inner.token {
107 Token::None => "<none>",
108 Token::Valid(_) => "<redacted>",
109 Token::Invalid => "<invalid>",
110 },
111 )
112 .field("timeout", &self.inner.timeout)
113 .field("retries", &self.inner.retries)
114 .finish_non_exhaustive()
115 }
116}
117
118impl Rest {
119 /// Creates a client authenticated with a bot token, using default options.
120 ///
121 /// Pass the raw token, without the `Bot ` prefix. An invalid token (one containing characters
122 /// that cannot appear in an HTTP header) is reported by the first request as
123 /// [`ErrorKind::BuildRequest`].
124 ///
125 /// discord.js counterpart: `new REST().setToken(token)`.
126 #[cfg(feature = "hyper")]
127 #[cfg_attr(docsrs, doc(cfg(feature = "hyper")))]
128 #[must_use]
129 pub fn new(token: impl Into<String>) -> Self {
130 Self::builder().token(token).build()
131 }
132
133 /// Returns the client's [CDN URL builder](Cdn) (D-137), with the base URLs set on the
134 /// [`RestBuilder`].
135 ///
136 /// discord.js counterpart: `REST#cdn`.
137 ///
138 /// # Examples
139 ///
140 /// ```
141 /// use djs_model::id::EmojiId;
142 /// use djs_rest::cdn::ImageOptions;
143 ///
144 /// let rest = djs_rest::Rest::new("my-token");
145 /// assert_eq!(
146 /// rest.cdn().emoji(EmojiId::new(1), false, ImageOptions::new()),
147 /// "https://cdn.discordapp.com/emojis/1.webp"
148 /// );
149 /// ```
150 #[must_use]
151 pub fn cdn(&self) -> &Cdn {
152 &self.inner.cdn
153 }
154
155 /// The URL of a guild's [widget image](https://docs.discord.com/developers/resources/guild#get-guild-widget-image)
156 /// (a public PNG; the widget must be enabled), in `style` or Discord's default (`shield`)
157 /// (D-116).
158 ///
159 /// discord.js counterpart: `Guild#widgetImageURL`.
160 ///
161 /// # Examples
162 ///
163 /// ```
164 /// use djs_model::{guild::WidgetStyle, id::GuildId};
165 ///
166 /// let rest = djs_rest::Rest::new("my-token");
167 /// assert_eq!(
168 /// rest.guild_widget_image_url(GuildId::new(1), Some(WidgetStyle::Banner2)),
169 /// "https://discord.com/api/v10/guilds/1/widget.png?style=banner2"
170 /// );
171 /// ```
172 #[must_use]
173 pub fn guild_widget_image_url(&self, guild_id: GuildId, style: Option<WidgetStyle>) -> String {
174 let mut url = format!("{}/guilds/{guild_id}/widget.png", self.inner.base);
175 if let Some(style) = style {
176 url.push_str("?style=");
177 route::write_text(&mut url, style.as_str());
178 }
179 url
180 }
181
182 /// Returns a builder to configure a client.
183 ///
184 /// discord.js counterpart: `new REST(options)` (`@discordjs/rest`).
185 ///
186 /// # Examples
187 ///
188 /// ```
189 /// use std::time::Duration;
190 ///
191 /// let rest = djs_rest::Rest::builder()
192 /// .token("my-token")
193 /// .timeout(Duration::from_secs(10))
194 /// .retries(5)
195 /// .build();
196 /// # let _ = rest;
197 /// ```
198 pub fn builder() -> RestBuilder {
199 RestBuilder::default()
200 }
201
202 /// Returns the number of invalid requests (401, 403 and 429 responses, except 429s with the
203 /// `shared` scope) this client made in the last 10 minutes.
204 ///
205 /// Discord temporarily bans the IP (for about an hour) once it sees 10 000 of them in
206 /// 10 minutes. The count is kept in 10-second slots, so it may include requests up to 10 s
207 /// older than the window. A warning is logged at every 1 000; see also
208 /// [`RestBuilder::invalid_request_limit`].
209 ///
210 /// discord.js counterpart: the `invalidRequestWarning` event.
211 #[must_use]
212 pub fn invalid_requests(&self) -> u32 {
213 self.inner.invalid.count(Instant::now())
214 }
215
216 /// Sends a request and deserializes the JSON response into `T`.
217 ///
218 /// This is the low-level entry point for endpoints without a typed method; the typed
219 /// methods send their requests the same way. Use `T = ()` for endpoints that return
220 /// `204 No Content`.
221 ///
222 /// Requests are rate limited and retried automatically:
223 ///
224 /// - `429 Too Many Requests` is retried after the time Discord asks for (it does not count
225 /// towards the retry limit);
226 /// - `5xx` responses, transport errors and timeouts are retried up to
227 /// [`RestBuilder::retries`] times.
228 ///
229 /// discord.js counterpart: `REST#request` / `REST#get` / `REST#post`.
230 ///
231 /// # Errors
232 ///
233 /// Returns an [`Error`] if the request cannot be built or sent, Discord responds with an error
234 /// status, or the response body does not match `T`.
235 pub fn request<'a, T: DeserializeOwned + 'a>(
236 &'a self,
237 request: Request<'a>,
238 ) -> impl Future<Output = Result<T, Error>> + Send + 'a {
239 // Sending is built here, so a caller's crate compiles only the decoding of its `T`.
240 let response = boxed(self.execute(request));
241 async move {
242 let (_, body) = response.await?;
243 decode(&body)
244 }
245 }
246
247 /// [`request`](Self::request) for the typed methods, which are boxed already (D-287).
248 pub(crate) async fn call<T: DeserializeOwned>(&self, request: Request<'_>) -> Result<T, Error> {
249 let (_, body) = self.execute(request).await?;
250 decode(&body)
251 }
252
253 /// Sends a request and returns the raw response body on success.
254 ///
255 /// Log fields name the route template, never the URI: paths can contain tokens.
256 pub(crate) async fn execute(&self, request: Request<'_>) -> Result<(StatusCode, Bytes), Error> {
257 let inner = &*self.inner;
258 let route = request.route;
259 let bucket_route = route.bucket();
260 let limits = bucket_route.limits;
261 let template = bucket_route.template;
262 let uri = inner.uri(route, request.query)?;
263 let reason = request.reason.map(reason_header);
264 let body = request.prepare_body();
265
266 let mut attempt: u8 = 0;
267 loop {
268 inner.check_invalid_requests()?;
269 let bucket = inner.ratelimiter.bucket(bucket_route);
270 // Burst routes (interaction callbacks) do not wait for one another.
271 let mut state = if limits.burst {
272 None
273 } else {
274 let mut state = bucket.state.lock().await;
275 state
276 .wait(inner.ratelimiter.offset(), &*inner.transport)
277 .await;
278 Some(state)
279 };
280 if limits.global {
281 inner.ratelimiter.acquire_global(&*inner.transport).await;
282 }
283
284 let http_request = inner.build_request(route, &uri, reason.as_ref(), &body)?;
285 let started = Instant::now();
286 let response = match timeout(&*inner.transport, inner.timeout, http_request).await {
287 Ok(Ok(response)) => response,
288 failed => {
289 drop(state);
290 let error = match failed {
291 Ok(Err(source)) => Error::with_source(ErrorKind::Transport, source),
292 _ => Error::new(ErrorKind::Timeout),
293 };
294 if attempt < inner.retries {
295 attempt += 1;
296 tracing::warn!(route = template, attempt, %error, "request failed, retrying");
297 continue;
298 }
299 return Err(error);
300 }
301 };
302
303 let now = Instant::now();
304 let (parts, body) = response.into_parts();
305 let headers = RateLimitHeaders::parse(&parts.headers);
306 if let Some(hash) = headers.bucket {
307 inner.ratelimiter.learn_hash(bucket_route.template, hash);
308 }
309 if let Some(state) = &mut state {
310 state.update(&headers, now);
311 }
312 if is_invalid(parts.status, &headers) {
313 inner.invalid.record(now);
314 }
315 tracing::debug!(
316 route = template,
317 status = parts.status.as_u16(),
318 elapsed_ms = millis(started.elapsed()),
319 remaining = headers.remaining,
320 "REST request completed"
321 );
322
323 match parts.status {
324 status if status.is_success() => return Ok((status, body)),
325 StatusCode::TOO_MANY_REQUESTS => {
326 let (retry_after, global) = rate_limited(&body, &headers);
327 tracing::warn!(
328 route = template,
329 global,
330 scope = headers.scope,
331 retry_after_ms = millis(retry_after),
332 "rate limited by Discord, retrying"
333 );
334 match &mut state {
335 _ if global && limits.global => inner.ratelimiter.pause_global(retry_after),
336 Some(state) => state.exhaust_for(retry_after, now),
337 // A burst route only delays the request that was limited.
338 None => {
339 inner
340 .transport
341 .sleep(retry_after + inner.ratelimiter.offset())
342 .await;
343 }
344 }
345 }
346 status if status.is_server_error() && attempt < inner.retries => {
347 attempt += 1;
348 tracing::warn!(
349 route = template,
350 status = status.as_u16(),
351 attempt,
352 "server error, retrying"
353 );
354 }
355 status => {
356 let error = serde_json::from_slice::<ApiError>(&body).ok().map(Box::new);
357 return Err(Error::new(ErrorKind::Response { status, error }));
358 }
359 }
360 }
361 }
362}
363
364impl Inner {
365 /// Fails if the configured invalid-request limit is reached (D-085).
366 fn check_invalid_requests(&self) -> Result<(), Error> {
367 if self.invalid_request_limit == 0 {
368 return Ok(());
369 }
370 let count = self.invalid.count(Instant::now());
371 if count >= self.invalid_request_limit {
372 return Err(Error::new(ErrorKind::InvalidRequestLimit {
373 count,
374 limit: self.invalid_request_limit,
375 }));
376 }
377 Ok(())
378 }
379
380 /// Builds the full URI of a route.
381 fn uri(&self, route: Route<'_>, query: Option<&dyn Query>) -> Result<Uri, Error> {
382 let mut uri = String::with_capacity(self.base.len() + 64);
383 uri.push_str(&self.base);
384 route.write_path(&mut uri);
385 if let Some(query) = query {
386 query.write(&mut QueryWriter::new(&mut uri));
387 }
388 Uri::try_from(uri).map_err(|source| Error::with_source(ErrorKind::BuildRequest, source))
389 }
390
391 /// Builds one HTTP request attempt. Cloning the body is cheap (`Bytes` is reference counted).
392 /// Routes authenticated by a token in their path do not get the client's token (D-121).
393 fn build_request(
394 &self,
395 route: Route<'_>,
396 uri: &Uri,
397 reason: Option<&HeaderValue>,
398 body: &PreparedBody,
399 ) -> Result<http::Request<Body>, Error> {
400 let mut builder = http::Request::builder()
401 .method(route.method())
402 .uri(uri.clone())
403 .header(USER_AGENT, self.user_agent.clone());
404 match &self.token {
405 _ if !route.authenticated() => {}
406 Token::None => {}
407 Token::Valid(token) => builder = builder.header(AUTHORIZATION, token.clone()),
408 Token::Invalid => {
409 return Err(Error::with_source(
410 ErrorKind::BuildRequest,
411 "the token contains characters that are not allowed in an HTTP header",
412 ));
413 }
414 }
415 if let Some(reason) = reason {
416 builder = builder.header(AUDIT_LOG_REASON, reason.clone());
417 }
418 if let Some(content_type) = body.content_type() {
419 builder = builder.header(CONTENT_TYPE, content_type.clone());
420 }
421 builder
422 .body(body.body())
423 .map_err(|source| Error::with_source(ErrorKind::BuildRequest, source))
424 }
425}
426
427/// Encodes an audit log reason for its header: percent-encoded UTF-8, which Discord decodes.
428fn reason_header(reason: &str) -> HeaderValue {
429 let mut encoded = String::with_capacity(reason.len());
430 route::write_text(&mut encoded, reason);
431 // Percent-encoding leaves only visible ASCII, which is always a valid header value.
432 HeaderValue::try_from(encoded).unwrap_or_else(|_| HeaderValue::from_static(""))
433}
434
435/// Whether Discord counts a response towards its invalid-request limit: 401, 403, and 429
436/// unless the limit was a `shared` resource limit.
437fn is_invalid(status: StatusCode, headers: &RateLimitHeaders<'_>) -> bool {
438 match status {
439 StatusCode::UNAUTHORIZED | StatusCode::FORBIDDEN => true,
440 StatusCode::TOO_MANY_REQUESTS => !headers
441 .scope
442 .is_some_and(|scope| scope.eq_ignore_ascii_case("shared")),
443 _ => false,
444 }
445}
446
447/// Extracts how long to wait and whether the limit is global from a 429 response.
448fn rate_limited(body: &[u8], headers: &RateLimitHeaders<'_>) -> (Duration, bool) {
449 let body: Option<RateLimitedBody> = serde_json::from_slice(body).ok();
450 let retry_after = body
451 .as_ref()
452 .map(RateLimitedBody::retry_after)
453 .or(headers.retry_after)
454 .unwrap_or(Duration::from_secs(1));
455 let global = headers.global || body.is_some_and(|body| body.global);
456 (retry_after, global)
457}
458
459/// Whole milliseconds of a duration, saturating, for log fields.
460fn millis(duration: Duration) -> u64 {
461 u64::try_from(duration.as_millis()).unwrap_or(u64::MAX)
462}
463
464/// Sends `request` with `transport`, giving up after `limit` (measured with the transport's
465/// own sleep, so that it works where tokio's timers do not, D-404); `Err(())` on timeout.
466async fn timeout(
467 transport: &dyn Transport,
468 limit: Duration,
469 request: http::Request<Body>,
470) -> Result<Result<http::Response<Bytes>, BoxError>, ()> {
471 let mut send = transport.send(request);
472 let mut expired = transport.sleep(limit);
473 core::future::poll_fn(|cx| {
474 if let core::task::Poll::Ready(response) = send.as_mut().poll(cx) {
475 return core::task::Poll::Ready(Ok(response));
476 }
477 expired.as_mut().poll(cx).map(|()| Err(()))
478 })
479 .await
480}
481
482/// A request to send with [`Rest::request`].
483///
484/// discord.js counterpart: `RequestData` (`@discordjs/rest`).
485///
486/// # Examples
487///
488/// ```
489/// use djs_model::{id::ChannelId, rest::CreateMessage};
490/// use djs_rest::{Request, Route};
491///
492/// let request = Request::new(Route::CreateMessage { channel_id: ChannelId::new(1) })
493/// .json(&CreateMessage::from("hi"))
494/// .unwrap();
495/// assert_eq!(request.route(), Route::CreateMessage { channel_id: ChannelId::new(1) });
496/// ```
497#[derive(Clone)]
498pub struct Request<'a> {
499 route: Route<'a>,
500 reason: Option<&'a str>,
501 query: Option<&'a dyn Query>,
502 body: Option<Bytes>,
503 /// Whether [`body`](Self::body) is `application/x-www-form-urlencoded` instead of JSON.
504 urlencoded: bool,
505 files: &'a [FileUpload],
506 /// A file sent under its own form field name instead of `files[n]` (D-111).
507 form_file: Option<(&'static str, &'a FileUpload)>,
508 /// Text form fields, for endpoints without `payload_json` (Create Guild Sticker).
509 form_text: &'a [(&'static str, &'a str)],
510}
511
512impl<'a> Request<'a> {
513 /// Creates a request without a body.
514 ///
515 /// discord.js counterpart: `RequestData` (`@discordjs/rest`).
516 #[must_use]
517 pub const fn new(route: Route<'a>) -> Self {
518 Self {
519 route,
520 reason: None,
521 query: None,
522 body: None,
523 urlencoded: false,
524 files: &[],
525 form_file: None,
526 form_text: &[],
527 }
528 }
529
530 /// Sets the reason shown in the guild's
531 /// [audit log](https://docs.discord.com/developers/resources/audit-log) for the action
532 /// (the `X-Audit-Log-Reason` header, sent percent-encoded, so any text is allowed). Only
533 /// endpoints whose docs mention the header use it; `None` sends no reason.
534 ///
535 /// discord.js counterpart: the `reason` option of `REST#request`.
536 ///
537 /// # Examples
538 ///
539 /// ```
540 /// use djs_model::id::{ChannelId, MessageId};
541 /// use djs_rest::{Request, Route};
542 ///
543 /// let route = Route::PinMessage {
544 /// channel_id: ChannelId::new(1),
545 /// message_id: MessageId::new(2),
546 /// };
547 /// let request = Request::new(route).reason(Some("Important"));
548 /// assert_eq!(request.audit_log_reason(), Some("Important"));
549 /// ```
550 #[must_use]
551 pub const fn reason(mut self, reason: Option<&'a str>) -> Self {
552 self.reason = reason;
553 self
554 }
555
556 /// Uploads `files` with the request (D-087). The request is then sent as
557 /// `multipart/form-data`: file `n` as the part `files[n]` (with its content type, guessed
558 /// from its name if not given, D-095) and the JSON body as `payload_json`. The file data is
559 /// not copied, not even for retries.
560 ///
561 /// The JSON body must describe the files in its `attachments`; the body structs of
562 /// `djs_model::rest` do that automatically for their own `files` field (D-094), which the
563 /// typed [`Rest`] methods pass here.
564 ///
565 /// discord.js counterpart: the `files` option of `REST#request`.
566 ///
567 /// # Examples
568 ///
569 /// ```
570 /// use djs_model::{
571 /// id::ChannelId,
572 /// rest::{CreateMessage, FileUpload},
573 /// };
574 /// use djs_rest::{Request, Route};
575 ///
576 /// let body = CreateMessage::from("The log:").file(FileUpload::new("log.txt", "everything is fine\n"));
577 /// let request = Request::new(Route::CreateMessage { channel_id: ChannelId::new(1) })
578 /// .json(&body)
579 /// .unwrap()
580 /// .files(&body.files);
581 /// assert_eq!(request.uploads().len(), 1);
582 /// ```
583 #[must_use]
584 pub const fn files(mut self, files: &'a [FileUpload]) -> Self {
585 self.files = files;
586 self
587 }
588
589 /// Returns the files set with [`files`](Self::files).
590 ///
591 /// discord.js counterpart: the `files` of `RequestData` (`@discordjs/rest`).
592 #[must_use]
593 pub const fn uploads(&self) -> &'a [FileUpload] {
594 self.files
595 }
596
597 /// Uploads `file` as the form field `name` (e.g. `target_users_file`, D-111), which
598 /// makes the request `multipart/form-data` like [`files`](Self::files).
599 pub(crate) const fn form_file(mut self, name: &'static str, file: &'a FileUpload) -> Self {
600 self.form_file = Some((name, file));
601 self
602 }
603
604 /// Sets an `application/x-www-form-urlencoded` body (the `OAuth2` token endpoints, D-132).
605 pub(crate) fn form_urlencoded(mut self, body: String) -> Self {
606 self.body = Some(Bytes::from(body));
607 self.urlencoded = true;
608 self
609 }
610
611 /// Builds the body once, for every attempt.
612 fn prepare_body(self) -> PreparedBody {
613 if self.urlencoded {
614 return PreparedBody::urlencoded(self.body.unwrap_or_default());
615 }
616 let form = Form {
617 files: self.files,
618 file: self.form_file,
619 text: self.form_text,
620 };
621 PreparedBody::new(self.body, &form)
622 }
623
624 /// Sends `fields` as text form fields, which makes the request `multipart/form-data`
625 /// (for endpoints that do not read `payload_json`).
626 pub(crate) const fn form_text(mut self, fields: &'a [(&'static str, &'a str)]) -> Self {
627 self.form_text = fields;
628 self
629 }
630
631 /// Sets the query parameters (D-092), written into the URI when the request is sent.
632 pub(crate) const fn query(mut self, query: &'a dyn Query) -> Self {
633 self.query = Some(query);
634 self
635 }
636
637 /// Returns the audit log reason set with [`reason`](Self::reason).
638 ///
639 /// discord.js counterpart: the `reason` of `RequestData` (`@discordjs/rest`).
640 #[must_use]
641 pub const fn audit_log_reason(&self) -> Option<&'a str> {
642 self.reason
643 }
644
645 /// Sets a JSON body. With [files](Self::files), it is sent as the `payload_json` part.
646 ///
647 /// discord.js counterpart: the `body` of `RequestData` (`@discordjs/rest`).
648 ///
649 /// # Errors
650 ///
651 /// Returns [`ErrorKind::BuildRequest`] if `body` cannot be serialized.
652 pub fn json<B: Serialize + ?Sized>(mut self, body: &B) -> Result<Self, Error> {
653 let bytes = serde_json::to_vec(body)
654 .map_err(|source| Error::with_source(ErrorKind::BuildRequest, source))?;
655 self.body = Some(Bytes::from(bytes));
656 Ok(self)
657 }
658
659 /// Returns the route of the request.
660 ///
661 /// discord.js counterpart: the route `REST#request` is given (`@discordjs/rest`).
662 #[must_use]
663 pub const fn route(&self) -> Route<'a> {
664 self.route
665 }
666}
667
668/// Shows the route, the reason and the query, but only the size of the body and the names of
669/// the form parts: bodies can hold secrets (access tokens, client secrets; C-011).
670impl fmt::Debug for Request<'_> {
671 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
672 struct Size(usize);
673 impl fmt::Debug for Size {
674 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
675 write!(f, "<{} bytes>", self.0)
676 }
677 }
678 let files: Vec<&str> = self.files.iter().map(|file| file.name.as_str()).collect();
679 let text: Vec<&str> = self.form_text.iter().map(|(name, _)| *name).collect();
680 f.debug_struct("Request")
681 .field("route", &self.route)
682 .field("reason", &self.reason)
683 .field("query", &self.query)
684 .field("body", &self.body.as_ref().map(|body| Size(body.len())))
685 .field("urlencoded", &self.urlencoded)
686 .field("files", &files)
687 .field("form_file", &self.form_file.map(|(name, _)| name))
688 .field("form_text", &text)
689 .finish()
690 }
691}
692
693/// Configures and builds a [`Rest`] client.
694///
695/// Defaults match `@discordjs/rest`: API `https://discord.com/api`, version 10, 15 s timeout,
696/// 3 retries, 50 requests per second globally, 50 ms rate-limit offset.
697///
698/// discord.js counterpart: `RESTOptions`.
699#[must_use = "a builder does nothing until `build` is called"]
700pub struct RestBuilder {
701 token: Option<(AuthScheme, String)>,
702 api: String,
703 version: u8,
704 timeout: Duration,
705 retries: u8,
706 global_requests_per_second: u32,
707 offset: Duration,
708 user_agent_appendix: Option<String>,
709 invalid_request_limit: u32,
710 cdn: String,
711 media_proxy: String,
712 transport: Option<Arc<dyn Transport>>,
713}
714
715/// How the token authenticates: a bot token or an `OAuth2` access token (D-108).
716#[derive(Clone, Copy, Debug, PartialEq, Eq)]
717enum AuthScheme {
718 Bot,
719 Bearer,
720}
721
722impl AuthScheme {
723 const fn prefix(self) -> &'static str {
724 match self {
725 Self::Bot => "Bot",
726 Self::Bearer => "Bearer",
727 }
728 }
729}
730
731impl fmt::Debug for RestBuilder {
732 /// Never shows the token (C-011).
733 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
734 f.debug_struct("RestBuilder")
735 .field(
736 "token",
737 &match self.token {
738 None => "<none>",
739 Some((AuthScheme::Bot, _)) => "Bot <redacted>",
740 Some((AuthScheme::Bearer, _)) => "Bearer <redacted>",
741 },
742 )
743 .field("api", &self.api)
744 .field("version", &self.version)
745 .field("timeout", &self.timeout)
746 .field("retries", &self.retries)
747 .field(
748 "global_requests_per_second",
749 &self.global_requests_per_second,
750 )
751 .field("offset", &self.offset)
752 .field("user_agent_appendix", &self.user_agent_appendix)
753 .field("invalid_request_limit", &self.invalid_request_limit)
754 .field("cdn", &self.cdn)
755 .field("media_proxy", &self.media_proxy)
756 .field("transport", &self.transport.as_ref().map(|_| "<custom>"))
757 .finish()
758 }
759}
760
761impl Default for RestBuilder {
762 fn default() -> Self {
763 Self {
764 token: None,
765 api: DEFAULT_API.to_owned(),
766 version: djs_model::gateway::API_VERSION,
767 timeout: Duration::from_secs(15),
768 retries: 3,
769 global_requests_per_second: 50,
770 offset: Duration::from_millis(50),
771 user_agent_appendix: None,
772 invalid_request_limit: 0,
773 cdn: cdn::DEFAULT_CDN.to_owned(),
774 media_proxy: cdn::DEFAULT_MEDIA_PROXY.to_owned(),
775 transport: None,
776 }
777 }
778}
779
780impl RestBuilder {
781 /// Sets the bot token (without the `Bot ` prefix).
782 ///
783 /// Without a token, only unauthenticated endpoints (webhooks with tokens, interaction
784 /// callbacks) can be used. Replaces a [`bearer_token`](Self::bearer_token).
785 ///
786 /// discord.js counterpart: `REST#setToken` (`@discordjs/rest`).
787 pub fn token(mut self, token: impl Into<String>) -> Self {
788 self.token = Some((AuthScheme::Bot, token.into()));
789 self
790 }
791
792 /// Authenticates with an `OAuth2` access token (`Authorization: Bearer …`) instead of a
793 /// bot token (D-108), to act for the user who authorized the application — e.g. for
794 /// [Edit Application Command Permissions](crate::Rest::edit_application_command_permissions).
795 /// Replaces a [`token`](Self::token).
796 ///
797 /// Discord limits requests per token, so use one client per access token: its
798 /// rate-limit state is its own.
799 ///
800 /// discord.js counterpart: `RESTOptions#authPrefix` set to `'Bearer'`.
801 ///
802 /// # Examples
803 ///
804 /// ```
805 /// use djs_rest::Rest;
806 ///
807 /// let user_rest = Rest::builder().bearer_token("an-oauth2-access-token").build();
808 /// assert!(!format!("{user_rest:?}").contains("an-oauth2-access-token"));
809 /// ```
810 pub fn bearer_token(mut self, token: impl Into<String>) -> Self {
811 self.token = Some((AuthScheme::Bearer, token.into()));
812 self
813 }
814
815 /// Sets the CDN base URL of [`Rest::cdn`] (default `https://cdn.discordapp.com`, D-137).
816 ///
817 /// discord.js counterpart: the `cdn` option of `RESTOptions` (`@discordjs/rest`).
818 pub fn cdn(mut self, cdn: impl Into<String>) -> Self {
819 self.cdn = cdn.into();
820 self
821 }
822
823 /// Sets the media proxy base URL of [`Rest::cdn`] (default `https://media.discordapp.net`).
824 ///
825 /// discord.js counterpart: the `mediaProxy` option of `RESTOptions` (`@discordjs/rest`).
826 pub fn media_proxy(mut self, media_proxy: impl Into<String>) -> Self {
827 self.media_proxy = media_proxy.into();
828 self
829 }
830
831 /// Sets the API base URL, without the version (default `https://discord.com/api`).
832 ///
833 /// Useful to route requests through a proxy. Plain `http://` URLs are allowed for that
834 /// purpose.
835 ///
836 /// discord.js counterpart: the `api` option of `RESTOptions` (`@discordjs/rest`).
837 pub fn api(mut self, api: impl Into<String>) -> Self {
838 self.api = api.into();
839 self
840 }
841
842 /// Sets the API version (default 10).
843 ///
844 /// discord.js counterpart: the `version` option of `RESTOptions` (`@discordjs/rest`).
845 pub const fn version(mut self, version: u8) -> Self {
846 self.version = version;
847 self
848 }
849
850 /// Sets how long to wait for a complete response before giving up (default 15 s).
851 ///
852 /// discord.js counterpart: the `timeout` option of `RESTOptions` (`@discordjs/rest`).
853 pub const fn timeout(mut self, timeout: Duration) -> Self {
854 self.timeout = timeout;
855 self
856 }
857
858 /// Sets how many times a request is retried after a server error, transport error or timeout
859 /// (default 3). Rate-limited requests are always retried and do not count.
860 ///
861 /// discord.js counterpart: the `retries` option of `RESTOptions` (`@discordjs/rest`).
862 pub const fn retries(mut self, retries: u8) -> Self {
863 self.retries = retries;
864 self
865 }
866
867 /// Sets the maximum number of requests per second across all routes (default 50).
868 ///
869 /// The limit is strict: no sliding second ever contains more requests (the window is
870 /// extended by the [offset](Self::offset)), while a burst of up to `limit` requests is sent
871 /// at once. Unlike discord.js' fixed one-second windows, this never lets twice the limit
872 /// through around a window boundary.
873 ///
874 /// `0` disables the proactive global limit; global rate-limit responses from Discord are
875 /// still honoured.
876 pub const fn global_requests_per_second(mut self, limit: u32) -> Self {
877 self.global_requests_per_second = limit;
878 self
879 }
880
881 /// Sets the extra delay added to every rate-limit wait to absorb clock skew and latency
882 /// (default 50 ms).
883 ///
884 /// discord.js counterpart: the `offset` option of `RESTOptions` (`@discordjs/rest`).
885 pub const fn offset(mut self, offset: Duration) -> Self {
886 self.offset = offset;
887 self
888 }
889
890 /// Makes requests fail immediately with [`ErrorKind::InvalidRequestLimit`] once the client
891 /// made `limit` invalid requests (401, 403, 429) in the last 10 minutes (default `0`: no
892 /// limit). Discord temporarily bans the IP at 10 000, so a limit below that (for example
893 /// 9 000) stops a misbehaving bot before it is locked out (D-085).
894 ///
895 /// The count is shared by every clone of the client; see [`Rest::invalid_requests`].
896 ///
897 /// discord.js counterpart: none (`@discordjs/rest` only warns, with `invalidRequestWarningInterval`).
898 pub const fn invalid_request_limit(mut self, limit: u32) -> Self {
899 self.invalid_request_limit = limit;
900 self
901 }
902
903 /// Appends text to the `User-Agent` header, e.g. your bot's name.
904 ///
905 /// discord.js counterpart: the `userAgentAppendix` option of `RESTOptions` (`@discordjs/rest`).
906 pub fn user_agent_appendix(mut self, appendix: impl Into<String>) -> Self {
907 self.user_agent_appendix = Some(appendix.into());
908 self
909 }
910
911 /// Sets what sends the requests (D-404): needed where the default hyper transport is
912 /// not available (without the `hyper` feature, for example on Cloudflare Workers).
913 /// With a custom transport, the TLS options of this crate (`native-roots`) do not apply.
914 ///
915 /// See [`Transport`] for an example.
916 ///
917 /// discord.js counterpart: the `makeRequest` option of `RESTOptions` (`@discordjs/rest`).
918 pub fn transport(mut self, transport: impl Transport) -> Self {
919 self.transport = Some(Arc::new(transport));
920 self
921 }
922
923 /// Builds the client.
924 ///
925 /// discord.js counterpart: `new REST(options)` (`@discordjs/rest`).
926 ///
927 /// # Panics
928 ///
929 /// Panics if `user_agent_appendix` contains characters that are not allowed in an HTTP
930 /// header, or, without the `hyper` feature, if no [`transport`](Self::transport) was
931 /// set (D-405).
932 #[must_use]
933 pub fn build(self) -> Rest {
934 #[cfg(feature = "hyper")]
935 let transport = self
936 .transport
937 .unwrap_or_else(|| Arc::new(crate::transport::hyper::HyperTransport::new()));
938 #[cfg(not(feature = "hyper"))]
939 let transport = self.transport.expect(
940 "djs-rest is built without the `hyper` feature: set a transport with \
941 `RestBuilder::transport`",
942 );
943
944 let token = match self.token {
945 None => Token::None,
946 Some((scheme, token)) => {
947 match HeaderValue::try_from(format!("{} {token}", scheme.prefix())) {
948 Ok(mut value) => {
949 value.set_sensitive(true);
950 Token::Valid(value)
951 }
952 Err(_) => Token::Invalid,
953 }
954 }
955 };
956
957 let mut user_agent = format!(
958 "DiscordBot (https://github.com/kotoanidev/djs-rs, {})",
959 env!("CARGO_PKG_VERSION")
960 );
961 if let Some(appendix) = &self.user_agent_appendix {
962 user_agent.push(' ');
963 user_agent.push_str(appendix);
964 }
965
966 Rest {
967 inner: Arc::new(Inner {
968 transport,
969 token,
970 base: format!("{}/v{}", self.api.trim_end_matches('/'), self.version),
971 user_agent: HeaderValue::try_from(user_agent)
972 .expect("the user agent appendix contains invalid header characters"),
973 timeout: self.timeout,
974 retries: self.retries,
975 ratelimiter: RateLimiter::new(self.global_requests_per_second, self.offset),
976 invalid: InvalidRequests::new(),
977 invalid_request_limit: self.invalid_request_limit,
978 cdn: Cdn::new(self.cdn, self.media_proxy),
979 }),
980 }
981 }
982}