forgejo_api/
lib.rs

1#![cfg_attr(docsrs, feature(doc_cfg))]
2
3//! Bindings for Forgejo's web API. See the [`Forgejo`] struct for how to get started.
4//!
5//! Every endpoint that Forgejo exposes under `/api/v1/` is included here as a
6//! method on the [`Forgejo`] struct. They are generated from [Forgejo's OpenAPI
7//! document](https://code.forgejo.org/api/swagger).
8//!
9//! Start by connecting to the API with [`Forgejo::new`]
10//!
11//! ```no_run
12//! # use forgejo_api::{Forgejo, Auth};
13//! # fn foo() -> Result<(), Box<dyn std::error::Error>> {
14//! let api = Forgejo::new(
15//!     Auth::None, // More info on authentication below
16//!     url::Url::parse("https://forgejo.example.local")?,
17//! )?;
18//! # Ok(())
19//! # }
20//! ```
21//!
22//! Then use that to interact with Forgejo!
23//!
24//! ```no_run
25//! # use forgejo_api::{Forgejo, Auth, structs::IssueListIssuesQuery};
26//! # async fn foo() -> Result<(), Box<dyn std::error::Error>> {
27//! # let api = Forgejo::new(
28//! #     Auth::None, // More info on authentication below
29//! #     url::Url::parse("https://forgejo.example.local")?,
30//! # )?;
31//! // Loads every issue made by "someone" on that repo!
32//! let issues = api.issue_list_issues(
33//!         "example-user",
34//!         "example-repo",
35//!         IssueListIssuesQuery {
36//!             created_by: Some("someone".into()),
37//!             ..Default::default()
38//!         }
39//!     )
40//!     .all()
41//!     .await?;
42//! # Ok(())
43//! # }
44//! ```
45//!
46//! ## Authentication
47//!
48//! Credentials are given in the [`Auth`] type when connecting to Forgejo, in
49//! [`Forgejo::new`] or [`Forgejo::with_user_agent`]. Forgejo supports
50//! authenticating via username & password, application tokens, or OAuth, and
51//! those are all available here.
52//!
53//! Provided credentials are always sent in the `Authorization` header. Sending
54//! credentials in a query parameter is deprecated in Forgejo and so is not
55//! supported here.
56//!
57//! ```no_run
58//! # use forgejo_api::{Forgejo, Auth};
59//! # fn foo() -> Result<(), Box<dyn std::error::Error>> {
60//! // No authentication
61//! // No credentials are sent, only public endpoints are available
62//! let api = Forgejo::new(
63//!     Auth::None,
64//!     url::Url::parse("https://forgejo.example.local")?,
65//! )?;
66//!
67//! // Application Token
68//! // Provides access depending on the scopes set when the token is created
69//! let api = Forgejo::new(
70//!     Auth::Token("2a3684d663cd9fdef3a9d759492c21844429e0f9"),
71//!     url::Url::parse("https://forgejo.example.local")?,
72//! )?;
73//!
74//! // OAuth2 Token
75//! // Provides complete access to the user's account
76//! let api = Forgejo::new(
77//!     Auth::OAuth2("Pretend there's a token here (they're really long!)"),
78//!     url::Url::parse("https://forgejo.example.local")?,
79//! )?;
80//!
81//! // Username & password
82//! // Provides complete access to the user's account
83//! //
84//! // I recommended only using this to create a new application token with
85//! // `.user_create_token()`, and to use that token for further operations.
86//! // Storing passwords is tricky!
87//! let api = Forgejo::new(
88//!     Auth::Password {
89//!         username: "ExampleUser",
90//!         password: "password123", // I hope your password is more secure than this...
91//!         mfa: None, // If the user has 2FA enable, it has to be included here.
92//!     },
93//!     url::Url::parse("https://forgejo.example.local")?,
94//! )?;
95//! # Ok(())
96//! # }
97//! ```
98//!
99//! ## Pagination
100//!
101//! Endpoints that return lists of items send them one page of results at a
102//! time. In Forgejo's API spec, the `path` and `limit` parameters are used to
103//! set what page to return and how many items should be included per page
104//! (respectively). Since they're so common, these parameters aren't included
105//! in function args like most parameters. They are instead available as the
106//! `.page(n)` and `.page_size(n)` methods on requests.
107//!
108//! For example:
109//! ```no_run
110//! # use forgejo_api::{Forgejo, Auth};
111//! # async fn foo() -> Result<(), Box<dyn std::error::Error>> {
112//! # let api = Forgejo::new(
113//! #    Auth::None,
114//! #    url::Url::parse("https://unimportant/")?,
115//! # )?;
116//! let following = api.user_current_list_following()
117//!     // The third page (pages are 1-indexed)
118//!     .page(3)
119//!     // Return 30 items per page. It's possible it will return fewer, if
120//!     // there aren't enough to fill the page
121//!     .page_size(30)
122//!     .await?;
123//! # Ok(())
124//! # }
125//! ```
126//!
127//! There are helper functions to make this easier as well:
128//!
129//! - **`.stream()`**:
130//!   
131//!   Returns a `Stream` that yields one item at a time, automatically incrementing
132//!   the page number as needed. (i.e. `.issue_list_issues().stream()` yields `Issue`)
133//! - **`.stream_pages()`**;
134//!   
135//!   Returns a `Stream` that yields one page of items at a
136//!   time. (i.e. `.issue_list_issues().stream_pages()` yields `Vec<Issue>`)
137//!
138//!   Useful for endpoints that return more than just a `Vec<T>` (such as `repo_search`)
139//! - **`.all()`**;
140//!   
141//!   Returns a `Vec` of every item requested. Equivalent to
142//!   `.stream().try_collect()`.
143
144use std::{
145    borrow::Cow, collections::BTreeMap, future::Future, marker::PhantomData, pin::Pin, task::Poll,
146};
147
148use reqwest::{Client, StatusCode};
149use serde::{Deserialize, Deserializer};
150use soft_assert::*;
151use url::Url;
152use zeroize::Zeroize;
153
154/// An `async` client for Forgejo's web API. For a blocking client, see [`sync::Forgejo`]
155///
156/// For more info on how to use this, see the [crate level docs](crate)
157pub struct Forgejo {
158    url: Url,
159    client: Client,
160}
161
162mod generated;
163#[cfg(feature = "sync")]
164pub mod sync;
165
166#[derive(thiserror::Error, Debug)]
167pub enum ForgejoError {
168    #[error("url must have a host")]
169    HostRequired,
170    #[error("scheme must be http or https")]
171    HttpRequired,
172    #[error(transparent)]
173    ReqwestError(#[from] reqwest::Error),
174    #[error("API key should be ascii")]
175    KeyNotAscii,
176    #[error("the response from forgejo was not properly structured")]
177    BadStructure(#[from] StructureError),
178    #[error("unexpected status code {} {}", .0.as_u16(), .0.canonical_reason().unwrap_or(""))]
179    UnexpectedStatusCode(StatusCode),
180    #[error(transparent)]
181    ApiError(#[from] ApiError),
182    #[error("the provided authorization was too long to accept")]
183    AuthTooLong,
184}
185
186#[derive(thiserror::Error, Debug)]
187pub enum StructureError {
188    #[error("{e}")]
189    Serde {
190        e: serde_json::Error,
191        contents: bytes::Bytes,
192    },
193    #[error(transparent)]
194    Utf8(#[from] std::str::Utf8Error),
195    #[error("failed to find header `{0}`")]
196    HeaderMissing(&'static str),
197    #[error("header was not ascii")]
198    HeaderNotAscii,
199    #[error("failed to parse header")]
200    HeaderParseFailed,
201    #[error("nothing was returned when a value was expected")]
202    EmptyResponse,
203}
204
205impl From<std::str::Utf8Error> for ForgejoError {
206    fn from(error: std::str::Utf8Error) -> Self {
207        Self::BadStructure(StructureError::Utf8(error))
208    }
209}
210
211#[derive(thiserror::Error, Debug)]
212pub struct ApiError {
213    pub message: Option<String>,
214    pub kind: ApiErrorKind,
215}
216
217impl ApiError {
218    fn new(message: Option<String>, kind: ApiErrorKind) -> Self {
219        Self { message, kind }
220    }
221
222    pub fn message(&self) -> Option<&str> {
223        self.message.as_deref()
224    }
225
226    pub fn error_kind(&self) -> &ApiErrorKind {
227        &self.kind
228    }
229}
230
231impl From<ApiErrorKind> for ApiError {
232    fn from(kind: ApiErrorKind) -> Self {
233        Self {
234            message: None,
235            kind,
236        }
237    }
238}
239
240impl std::fmt::Display for ApiError {
241    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
242        match &self.message {
243            Some(message) => write!(f, "{}: {message}", self.kind),
244            None => write!(f, "{}", self.kind),
245        }
246    }
247}
248
249#[derive(thiserror::Error, Debug)]
250pub enum ApiErrorKind {
251    #[error("api error")]
252    Generic,
253    #[error("access denied")]
254    Forbidden,
255    #[error("invalid topics")]
256    InvalidTopics { invalid_topics: Option<Vec<String>> },
257    #[error("not found")]
258    NotFound { errors: Option<Vec<String>> },
259    #[error("repo archived")]
260    RepoArchived,
261    #[error("unauthorized")]
262    Unauthorized,
263    #[error("validation failed")]
264    ValidationFailed,
265    #[error("status code {0}")]
266    Other(reqwest::StatusCode),
267}
268
269impl From<structs::APIError> for ApiError {
270    fn from(value: structs::APIError) -> Self {
271        Self::new(value.message, ApiErrorKind::Generic)
272    }
273}
274impl From<structs::APIForbiddenError> for ApiError {
275    fn from(value: structs::APIForbiddenError) -> Self {
276        Self::new(value.message, ApiErrorKind::Forbidden)
277    }
278}
279impl From<structs::APIInvalidTopicsError> for ApiError {
280    fn from(value: structs::APIInvalidTopicsError) -> Self {
281        Self::new(
282            value.message,
283            ApiErrorKind::InvalidTopics {
284                invalid_topics: value.invalid_topics,
285            },
286        )
287    }
288}
289impl From<structs::APINotFound> for ApiError {
290    fn from(value: structs::APINotFound) -> Self {
291        Self::new(
292            value.message,
293            ApiErrorKind::NotFound {
294                errors: value.errors,
295            },
296        )
297    }
298}
299impl From<structs::APIRepoArchivedError> for ApiError {
300    fn from(value: structs::APIRepoArchivedError) -> Self {
301        Self::new(value.message, ApiErrorKind::RepoArchived)
302    }
303}
304impl From<structs::APIUnauthorizedError> for ApiError {
305    fn from(value: structs::APIUnauthorizedError) -> Self {
306        Self::new(value.message, ApiErrorKind::Unauthorized)
307    }
308}
309impl From<structs::APIValidationError> for ApiError {
310    fn from(value: structs::APIValidationError) -> Self {
311        Self::new(value.message, ApiErrorKind::ValidationFailed)
312    }
313}
314impl From<reqwest::StatusCode> for ApiError {
315    fn from(value: reqwest::StatusCode) -> Self {
316        match value {
317            reqwest::StatusCode::NOT_FOUND => ApiErrorKind::NotFound { errors: None },
318            reqwest::StatusCode::FORBIDDEN => ApiErrorKind::Forbidden,
319            reqwest::StatusCode::UNAUTHORIZED => ApiErrorKind::Unauthorized,
320            _ => ApiErrorKind::Other(value),
321        }
322        .into()
323    }
324}
325impl From<OAuthError> for ApiError {
326    fn from(value: OAuthError) -> Self {
327        Self::new(Some(value.error_description), ApiErrorKind::Generic)
328    }
329}
330
331/// Method of authentication to connect to the Forgejo host with.
332pub enum Auth<'a> {
333    /// Application Access Token. Grants access to scope enabled for the
334    /// provided token, which may include full access.
335    ///
336    /// To learn how to create a token, see
337    /// [the Codeberg docs on the subject](https://docs.codeberg.org/advanced/access-token/).
338    ///
339    /// To learn about token scope, see
340    /// [the official Forgejo docs](https://forgejo.org/docs/latest/user/token-scope/).
341    Token(&'a str),
342    /// OAuth2 Token. Grants full access to the user's account, except for
343    /// creating application access tokens.
344    ///
345    /// To learn how to create an OAuth2 token, see
346    /// [the official Forgejo docs on the subject](https://forgejo.org/docs/latest/user/oauth2-provider).
347    OAuth2(&'a str),
348    /// Username, password, and 2-factor auth code (if enabled). Grants full
349    /// access to the user's account.
350    Password {
351        username: &'a str,
352        password: &'a str,
353        mfa: Option<&'a str>,
354    },
355    /// No authentication. Only grants access to access public endpoints.
356    None,
357}
358
359impl Auth<'_> {
360    fn to_headers(&self) -> Result<reqwest::header::HeaderMap, ForgejoError> {
361        let mut headers = reqwest::header::HeaderMap::new();
362        match self {
363            Auth::Token(token) => {
364                let mut header: reqwest::header::HeaderValue = format!("token {token}")
365                    .try_into()
366                    .map_err(|_| ForgejoError::KeyNotAscii)?;
367                header.set_sensitive(true);
368                headers.insert("Authorization", header);
369            }
370            Auth::Password {
371                username,
372                password,
373                mfa,
374            } => {
375                let unencoded_len = username.len() + password.len() + 1;
376                let unpadded_len = unencoded_len
377                    .checked_mul(4)
378                    .ok_or(ForgejoError::AuthTooLong)?
379                    .div_ceil(3);
380                // round up to next multiple of 4, to account for padding
381                let len = unpadded_len.div_ceil(4) * 4;
382                let mut bytes = vec![0; len];
383
384                // panic safety: len cannot be zero
385                let mut encoder = base64ct::Encoder::<base64ct::Base64>::new(&mut bytes).unwrap();
386
387                // panic safety: len will always be enough
388                encoder.encode(username.as_bytes()).unwrap();
389                encoder.encode(b":").unwrap();
390                encoder.encode(password.as_bytes()).unwrap();
391
392                let b64 = encoder.finish().unwrap();
393
394                let mut header: reqwest::header::HeaderValue =
395                    format!("Basic {b64}").try_into().unwrap(); // panic safety: base64 is always ascii
396                header.set_sensitive(true);
397                headers.insert("Authorization", header);
398
399                bytes.zeroize();
400
401                if let Some(mfa) = mfa {
402                    let mut key_header: reqwest::header::HeaderValue =
403                        (*mfa).try_into().map_err(|_| ForgejoError::KeyNotAscii)?;
404                    key_header.set_sensitive(true);
405                    headers.insert("X-FORGEJO-OTP", key_header);
406                }
407            }
408            Auth::OAuth2(token) => {
409                let mut header: reqwest::header::HeaderValue = format!("Bearer {token}")
410                    .try_into()
411                    .map_err(|_| ForgejoError::KeyNotAscii)?;
412                header.set_sensitive(true);
413                headers.insert("Authorization", header);
414            }
415            Auth::None => (),
416        }
417        Ok(headers)
418    }
419}
420
421impl Forgejo {
422    /// Create a new client connect to the API of the specified Forgejo instance.
423    ///
424    /// The default user agent is "forgejo-api-rs". Use
425    /// [`Forgejo::with_user_agent`] to set a custom one.
426    pub fn new(auth: Auth, url: Url) -> Result<Self, ForgejoError> {
427        Self::with_user_agent(auth, url, "forgejo-api-rs")
428    }
429
430    /// Just like [`Forgejo::new`], but includes a custom user agent to be sent
431    /// with each request.
432    pub fn with_user_agent(auth: Auth, url: Url, user_agent: &str) -> Result<Self, ForgejoError> {
433        soft_assert!(
434            matches!(url.scheme(), "http" | "https"),
435            Err(ForgejoError::HttpRequired)
436        );
437
438        let client = Client::builder()
439            .user_agent(user_agent)
440            .default_headers(auth.to_headers()?)
441            .build()?;
442        Ok(Self { url, client })
443    }
444
445    pub async fn download_release_attachment(
446        &self,
447        owner: &str,
448        repo: &str,
449        release: i64,
450        attach: i64,
451    ) -> Result<bytes::Bytes, ForgejoError> {
452        let release = self
453            .repo_get_release_attachment(owner, repo, release, attach)
454            .await?;
455        let mut url = self.url.clone();
456        url.path_segments_mut()
457            .unwrap()
458            .pop_if_empty()
459            .extend(["attachments", &release.uuid.unwrap().to_string()]);
460        let request = self.client.get(url).build()?;
461        Ok(self.client.execute(request).await?.bytes().await?)
462    }
463
464    /// Requests a new OAuth2 access token
465    ///
466    /// More info at [Forgejo's docs](https://forgejo.org/docs/latest/user/oauth2-provider).
467    pub async fn oauth_get_access_token(
468        &self,
469        body: structs::OAuthTokenRequest<'_>,
470    ) -> Result<structs::OAuthToken, ForgejoError> {
471        let url = self.url.join("login/oauth/access_token").unwrap();
472        let request = self.client.post(url).json(&body).build()?;
473        let response = self.client.execute(request).await?;
474        match response.status() {
475            reqwest::StatusCode::OK => Ok(response.json().await?),
476            status if status.is_client_error() => {
477                let err = response.json::<OAuthError>().await?;
478                Err(ApiError::from(err).into())
479            }
480            _ => Err(ForgejoError::UnexpectedStatusCode(response.status())),
481        }
482    }
483
484    pub async fn send_request(&self, request: &RawRequest) -> Result<ApiResponse, ForgejoError> {
485        let mut url = self
486            .url
487            .join(&request.path)
488            .expect("url fail. bug in forgejo-api");
489        let mut query_pairs = url.query_pairs_mut();
490        if let Some(query) = &request.query {
491            query_pairs.extend_pairs(query.iter());
492        }
493        if let Some(page) = request.page {
494            query_pairs.append_pair("page", &format!("{page}"));
495        }
496        if let Some(limit) = request.limit {
497            query_pairs.append_pair("limit", &format!("{limit}"));
498        }
499        drop(query_pairs);
500        let mut reqwest_request = self.client.request(request.method.clone(), url);
501        reqwest_request = match &request.body {
502            RequestBody::Json(bytes) => reqwest_request
503                .body(bytes.clone())
504                .header(reqwest::header::CONTENT_TYPE, "application/json"),
505            RequestBody::Form(list) => {
506                let mut form = reqwest::multipart::Form::new();
507                for (k, v) in list {
508                    form = form.part(
509                        *k,
510                        reqwest::multipart::Part::bytes(v.clone()).file_name("file"),
511                    );
512                }
513                reqwest_request.multipart(form)
514            }
515            RequestBody::None => reqwest_request,
516        };
517        let mut reqwest_response = reqwest_request.send().await?;
518        let response = ApiResponse {
519            status_code: reqwest_response.status(),
520            headers: std::mem::take(reqwest_response.headers_mut()),
521            body: reqwest_response.bytes().await?,
522        };
523        Ok(response)
524    }
525
526    pub async fn hit_endpoint<E: Endpoint, R: FromResponse>(
527        &self,
528        endpoint: E,
529    ) -> Result<R, ForgejoError> {
530        let (response, has_body) =
531            E::handle_error(self.send_request(&endpoint.make_request()).await?)?;
532        Ok(R::from_response(response, has_body)?)
533    }
534}
535
536#[derive(serde::Deserialize)]
537struct OAuthError {
538    error_description: String,
539    // intentionally ignored, no need for now
540    // url: Url
541}
542
543pub mod structs {
544    pub use crate::generated::structs::*;
545
546    /// A Request for a new OAuth2 access token
547    ///
548    /// More info at [Forgejo's docs](https://forgejo.org/docs/latest/user/oauth2-provider).
549    #[derive(serde::Serialize)]
550    #[serde(tag = "grant_type")]
551    pub enum OAuthTokenRequest<'a> {
552        /// Request for getting an access code for a confidential app
553        ///
554        /// The `code` field must have come from sending the user to
555        /// `/login/oauth/authorize` in their browser
556        #[serde(rename = "authorization_code")]
557        Confidential {
558            client_id: &'a str,
559            client_secret: &'a str,
560            code: &'a str,
561            redirect_uri: url::Url,
562        },
563        /// Request for getting an access code for a public app
564        ///
565        /// The `code` field must have come from sending the user to
566        /// `/login/oauth/authorize` in their browser
567        #[serde(rename = "authorization_code")]
568        Public {
569            client_id: &'a str,
570            code_verifier: &'a str,
571            code: &'a str,
572            redirect_uri: url::Url,
573        },
574        /// Request for refreshing an access code
575        #[serde(rename = "refresh_token")]
576        Refresh {
577            refresh_token: &'a str,
578            client_id: &'a str,
579            client_secret: &'a str,
580        },
581    }
582
583    #[derive(serde::Deserialize)]
584    pub struct OAuthToken {
585        pub access_token: String,
586        pub refresh_token: String,
587        pub token_type: String,
588        /// Number of seconds until the access token expires.
589        pub expires_in: u32,
590    }
591}
592
593// Forgejo can return blank strings for URLs. This handles that by deserializing
594// that as `None`
595fn none_if_blank_url<'de, D: serde::Deserializer<'de>>(
596    deserializer: D,
597) -> Result<Option<Url>, D::Error> {
598    use serde::de::{Error, Unexpected, Visitor};
599    use std::fmt;
600
601    struct EmptyUrlVisitor;
602
603    impl<'de> Visitor<'de> for EmptyUrlVisitor {
604        type Value = Option<Url>;
605
606        fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
607            formatter.write_str("option")
608        }
609
610        #[inline]
611        fn visit_unit<E>(self) -> Result<Self::Value, E>
612        where
613            E: Error,
614        {
615            Ok(None)
616        }
617
618        #[inline]
619        fn visit_none<E>(self) -> Result<Self::Value, E>
620        where
621            E: Error,
622        {
623            Ok(None)
624        }
625
626        #[inline]
627        fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
628        where
629            D: serde::Deserializer<'de>,
630        {
631            let s: String = serde::Deserialize::deserialize(deserializer)?;
632            if s.is_empty() {
633                return Ok(None);
634            }
635            Url::parse(&s)
636                .map_err(|err| {
637                    let err_s = format!("{}", err);
638                    Error::invalid_value(Unexpected::Str(&s), &err_s.as_str())
639                })
640                .map(Some)
641        }
642
643        #[inline]
644        fn visit_str<E>(self, s: &str) -> Result<Self::Value, E>
645        where
646            E: Error,
647        {
648            if s.is_empty() {
649                return Ok(None);
650            }
651            Url::parse(s)
652                .map_err(|err| {
653                    let err_s = format!("{err}");
654                    Error::invalid_value(Unexpected::Str(s), &err_s.as_str())
655                })
656                .map(Some)
657        }
658    }
659
660    deserializer.deserialize_option(EmptyUrlVisitor)
661}
662
663#[allow(dead_code)] // not used yet, but it might appear in the future
664fn deserialize_ssh_url<'de, D, DE>(deserializer: D) -> Result<Url, DE>
665where
666    D: Deserializer<'de>,
667    DE: serde::de::Error,
668{
669    let raw_url: String = String::deserialize(deserializer).map_err(DE::custom)?;
670    parse_ssh_url(&raw_url).map_err(DE::custom)
671}
672
673fn deserialize_optional_ssh_url<'de, D, DE>(deserializer: D) -> Result<Option<Url>, DE>
674where
675    D: Deserializer<'de>,
676    DE: serde::de::Error,
677{
678    let raw_url: Option<String> = Option::deserialize(deserializer).map_err(DE::custom)?;
679    raw_url
680        .as_ref()
681        .map(parse_ssh_url)
682        .map(|res| res.map_err(DE::custom))
683        .transpose()
684        .or(Ok(None))
685}
686
687fn requested_reviewers_ignore_null<'de, D, DE>(
688    deserializer: D,
689) -> Result<Option<Vec<structs::User>>, DE>
690where
691    D: Deserializer<'de>,
692    DE: serde::de::Error,
693{
694    let list: Option<Vec<Option<structs::User>>> =
695        Option::deserialize(deserializer).map_err(DE::custom)?;
696    Ok(list.map(|list| list.into_iter().flatten().collect::<Vec<_>>()))
697}
698
699fn parse_ssh_url(raw_url: &String) -> Result<Url, url::ParseError> {
700    // in case of a non-standard ssh-port (not 22), the ssh url coming from the forgejo API
701    // is actually parseable by the url crate, so try to do that first
702    Url::parse(raw_url).or_else(|_| {
703        // otherwise the ssh url is not parseable by the url crate and we try again after some
704        // pre-processing
705        let url = format!("ssh://{url}", url = raw_url.replace(":", "/"));
706        Url::parse(url.as_str())
707    })
708}
709
710#[test]
711fn ssh_url_deserialization() {
712    #[derive(serde::Deserialize)]
713    struct SshUrl {
714        #[serde(deserialize_with = "deserialize_ssh_url")]
715        url: url::Url,
716    }
717    let full_url = r#"{ "url": "ssh://git@codeberg.org/Cyborus/forgejo-api" }"#;
718    let ssh_url = r#"{ "url": "git@codeberg.org:Cyborus/forgejo-api" }"#;
719
720    let full_url_de =
721        serde_json::from_str::<SshUrl>(full_url).expect("failed to deserialize full url");
722    let ssh_url_de =
723        serde_json::from_str::<SshUrl>(ssh_url).expect("failed to deserialize ssh url");
724
725    let expected = "ssh://git@codeberg.org/Cyborus/forgejo-api";
726    assert_eq!(full_url_de.url.as_str(), expected);
727    assert_eq!(ssh_url_de.url.as_str(), expected);
728
729    #[derive(serde::Deserialize)]
730    struct OptSshUrl {
731        #[serde(deserialize_with = "deserialize_optional_ssh_url")]
732        url: Option<url::Url>,
733    }
734    let null_url = r#"{ "url": null }"#;
735
736    let full_url_de = serde_json::from_str::<OptSshUrl>(full_url)
737        .expect("failed to deserialize optional full url");
738    let ssh_url_de =
739        serde_json::from_str::<OptSshUrl>(ssh_url).expect("failed to deserialize optional ssh url");
740    let null_url_de =
741        serde_json::from_str::<OptSshUrl>(null_url).expect("failed to deserialize null url");
742
743    let expected = Some("ssh://git@codeberg.org/Cyborus/forgejo-api");
744    assert_eq!(full_url_de.url.as_ref().map(|u| u.as_ref()), expected);
745    assert_eq!(ssh_url_de.url.as_ref().map(|u| u.as_ref()), expected);
746    assert!(null_url_de.url.is_none());
747}
748
749impl From<structs::DefaultMergeStyle> for structs::MergePullRequestOptionDo {
750    fn from(value: structs::DefaultMergeStyle) -> Self {
751        match value {
752            structs::DefaultMergeStyle::Merge => structs::MergePullRequestOptionDo::Merge,
753            structs::DefaultMergeStyle::Rebase => structs::MergePullRequestOptionDo::Rebase,
754            structs::DefaultMergeStyle::RebaseMerge => {
755                structs::MergePullRequestOptionDo::RebaseMerge
756            }
757            structs::DefaultMergeStyle::Squash => structs::MergePullRequestOptionDo::Squash,
758            structs::DefaultMergeStyle::FastForwardOnly => {
759                structs::MergePullRequestOptionDo::FastForwardOnly
760            }
761        }
762    }
763}
764
765mod sealed {
766    pub trait Sealed {}
767}
768
769pub trait Endpoint: sealed::Sealed {
770    type Response: FromResponse;
771    fn make_request(self) -> RawRequest;
772    fn handle_error(response: ApiResponse) -> Result<(ApiResponse, bool), ForgejoError>;
773}
774
775#[derive(Clone)]
776pub struct RawRequest {
777    method: reqwest::Method,
778    path: Cow<'static, str>,
779    query: Option<Vec<(&'static str, String)>>,
780    body: RequestBody,
781    page: Option<u32>,
782    limit: Option<u32>,
783}
784
785impl RawRequest {
786    pub(crate) fn wrap<E: Endpoint<Response = R>, R>(self, client: &Forgejo) -> Request<'_, E, R> {
787        Request {
788            inner: TypedRequest {
789                inner: self,
790                __endpoint: PhantomData,
791                __response: PhantomData,
792            },
793            client,
794        }
795    }
796
797    #[cfg(feature = "sync")]
798    pub(crate) fn wrap_sync<E: Endpoint<Response = R>, R>(
799        self,
800        client: &sync::Forgejo,
801    ) -> sync::Request<'_, E, R> {
802        sync::Request {
803            inner: TypedRequest {
804                inner: self,
805                __endpoint: PhantomData,
806                __response: PhantomData,
807            },
808            client,
809        }
810    }
811}
812
813pub trait FromResponse {
814    fn from_response(response: ApiResponse, has_body: bool) -> Result<Self, StructureError>
815    where
816        Self: Sized;
817}
818
819#[macro_export]
820macro_rules! impl_from_response {
821    ($t:ty) => {
822        impl $crate::FromResponse for $t {
823            $crate::json_impl!();
824        }
825    };
826}
827#[macro_export]
828#[doc(hidden)]
829macro_rules! json_impl {
830    () => {
831        fn from_response(
832            response: $crate::ApiResponse,
833            has_body: bool,
834        ) -> Result<Self, $crate::StructureError> {
835            soft_assert::soft_assert!(has_body, Err($crate::StructureError::EmptyResponse));
836            serde_json::from_slice(&response.body()).map_err(|e| $crate::StructureError::Serde {
837                e,
838                contents: response.body().clone(),
839            })
840        }
841    };
842}
843
844impl FromResponse for String {
845    fn from_response(
846        response: crate::ApiResponse,
847        has_body: bool,
848    ) -> Result<Self, crate::StructureError> {
849        soft_assert::soft_assert!(has_body, Err(crate::StructureError::EmptyResponse));
850        Ok(std::str::from_utf8(&response.body)?.to_owned())
851    }
852}
853
854impl FromResponse for bytes::Bytes {
855    fn from_response(
856        response: crate::ApiResponse,
857        has_body: bool,
858    ) -> Result<Self, crate::StructureError> {
859        soft_assert::soft_assert!(has_body, Err(crate::StructureError::EmptyResponse));
860        Ok(response.body.clone())
861    }
862}
863
864impl<T: FromResponse + serde::de::DeserializeOwned> FromResponse for Vec<T> {
865    json_impl!();
866}
867
868impl<K, V> FromResponse for BTreeMap<K, V>
869where
870    BTreeMap<K, V>: serde::de::DeserializeOwned,
871{
872    json_impl!();
873}
874
875impl FromResponse for Vec<u8> {
876    fn from_response(
877        response: crate::ApiResponse,
878        has_body: bool,
879    ) -> Result<Self, crate::StructureError> {
880        soft_assert::soft_assert!(has_body, Err(crate::StructureError::EmptyResponse));
881        Ok(response.body.to_vec())
882    }
883}
884
885impl<
886        T: FromResponse,
887        H: for<'a> TryFrom<&'a reqwest::header::HeaderMap, Error = crate::StructureError>,
888    > FromResponse for (H, T)
889{
890    fn from_response(
891        response: crate::ApiResponse,
892        has_body: bool,
893    ) -> Result<Self, crate::StructureError> {
894        let headers = H::try_from(&response.headers)?;
895        let body = T::from_response(response, has_body)?;
896        Ok((headers, body))
897    }
898}
899
900impl<T: FromResponse> FromResponse for Option<T> {
901    fn from_response(
902        response: crate::ApiResponse,
903        has_body: bool,
904    ) -> Result<Self, crate::StructureError> {
905        if has_body {
906            T::from_response(response, true).map(Some)
907        } else {
908            Ok(None)
909        }
910    }
911}
912
913impl_from_response!(bool);
914
915impl FromResponse for () {
916    fn from_response(_: crate::ApiResponse, _: bool) -> Result<Self, crate::StructureError> {
917        Ok(())
918    }
919}
920
921#[derive(Clone)]
922pub enum RequestBody {
923    Json(bytes::Bytes),
924    Form(Vec<(&'static str, Vec<u8>)>),
925    None,
926}
927
928pub struct TypedRequest<E, R> {
929    inner: RawRequest,
930    __endpoint: PhantomData<*const E>,
931    __response: PhantomData<*const R>,
932}
933
934impl<E: Endpoint, R: FromResponse> TypedRequest<E, R> {
935    async fn send(&self, client: &Forgejo) -> Result<R, ForgejoError> {
936        let (response, has_body) = E::handle_error(client.send_request(&self.inner).await?)?;
937        Ok(R::from_response(response, has_body)?)
938    }
939
940    #[cfg(feature = "sync")]
941    fn send_sync(&self, client: &sync::Forgejo) -> Result<R, ForgejoError> {
942        let (response, has_body) = E::handle_error(client.send_request(&self.inner)?)?;
943        Ok(R::from_response(response, has_body)?)
944    }
945}
946
947pub struct ApiResponse {
948    status_code: StatusCode,
949    headers: reqwest::header::HeaderMap,
950    body: bytes::Bytes,
951}
952
953impl ApiResponse {
954    pub fn status_code(&self) -> StatusCode {
955        self.status_code
956    }
957
958    pub fn headers(&self) -> &reqwest::header::HeaderMap {
959        &self.headers
960    }
961
962    pub fn body(&self) -> &bytes::Bytes {
963        &self.body
964    }
965}
966
967pub struct Request<'a, E, R> {
968    inner: TypedRequest<E, R>,
969    client: &'a Forgejo,
970}
971
972impl<'a, E: Endpoint, R: FromResponse> Request<'a, E, R> {
973    pub async fn send(self) -> Result<R, ForgejoError> {
974        self.inner.send(self.client).await
975    }
976
977    pub fn response_type<T: FromResponse>(self) -> Request<'a, E, T> {
978        Request {
979            inner: TypedRequest {
980                inner: self.inner.inner,
981                __endpoint: PhantomData,
982                __response: PhantomData,
983            },
984            client: self.client,
985        }
986    }
987
988    pub fn page(mut self, page: u32) -> Self {
989        self.inner.inner.page = Some(page);
990        self
991    }
992
993    pub fn page_size(mut self, limit: u32) -> Self {
994        self.inner.inner.limit = Some(limit);
995        self
996    }
997}
998
999pub trait CountHeader: sealed::Sealed {
1000    fn count(&self) -> Option<usize>;
1001}
1002
1003pub trait PageSize: sealed::Sealed {
1004    fn page_size(&self) -> usize;
1005}
1006
1007impl<T> sealed::Sealed for Vec<T> {}
1008impl<T> PageSize for Vec<T> {
1009    fn page_size(&self) -> usize {
1010        self.len()
1011    }
1012}
1013
1014impl<'a, E: Endpoint, H: CountHeader, T: PageSize> Request<'a, E, (H, T)>
1015where
1016    (H, T): FromResponse,
1017{
1018    pub fn stream_pages(self) -> PageStream<'a, E, T, H> {
1019        PageStream {
1020            request: self,
1021            total_seen: 0,
1022            finished: false,
1023            fut: None,
1024        }
1025    }
1026}
1027
1028pub struct PageStream<'a, E: Endpoint, T, H> {
1029    request: Request<'a, E, (H, T)>,
1030    total_seen: usize,
1031    finished: bool,
1032    fut: Option<Pin<Box<dyn Future<Output = Result<(H, T), ForgejoError>> + 'a>>>,
1033}
1034
1035impl<'a, E: Endpoint, T: PageSize, H: CountHeader> futures::stream::Stream
1036    for PageStream<'a, E, T, H>
1037where
1038    Self: Unpin + 'a,
1039    (H, T): FromResponse,
1040{
1041    type Item = Result<T, ForgejoError>;
1042
1043    fn poll_next(
1044        mut self: Pin<&mut Self>,
1045        cx: &mut std::task::Context<'_>,
1046    ) -> Poll<Option<Self::Item>> {
1047        if self.finished {
1048            return Poll::Ready(None);
1049        }
1050        match &mut self.fut {
1051            None => {
1052                let request = self.request.inner.inner.clone();
1053                let client = self.request.client;
1054                let fut = Box::pin(async move {
1055                    E::handle_error(client.send_request(&request).await?).and_then(|(res, body)| {
1056                        <(H, T)>::from_response(res, body).map_err(|e| e.into())
1057                    })
1058                });
1059                self.fut = Some(fut);
1060                cx.waker().wake_by_ref();
1061                Poll::Pending
1062            }
1063            Some(fut) => {
1064                let (headers, page_content) = match fut.as_mut().poll(cx) {
1065                    Poll::Ready(Ok(response)) => response,
1066                    Poll::Ready(Err(e)) => {
1067                        self.finished = true;
1068                        return Poll::Ready(Some(Err(e)));
1069                    }
1070                    Poll::Pending => return Poll::Pending,
1071                };
1072                self.total_seen += page_content.page_size();
1073                let total_count = match headers.count() {
1074                    Some(n) => n,
1075                    None => {
1076                        self.finished = true;
1077                        return Poll::Ready(Some(Err(StructureError::HeaderMissing(
1078                            "x-total-count",
1079                        )
1080                        .into())));
1081                    }
1082                };
1083
1084                if self.total_seen >= total_count {
1085                    self.finished = true;
1086                } else {
1087                    self.request.inner.inner.page =
1088                        Some(self.request.inner.inner.page.unwrap_or(1) + 1);
1089                    self.fut = None;
1090                }
1091
1092                Poll::Ready(Some(Ok(page_content)))
1093            }
1094        }
1095    }
1096}
1097
1098impl<'a, E: Endpoint + 'a, T: 'a, H: CountHeader + 'a> Request<'a, E, (H, Vec<T>)>
1099where
1100    (H, Vec<T>): FromResponse,
1101{
1102    pub fn stream(self) -> impl futures::Stream<Item = Result<T, ForgejoError>> + use<'a, E, T, H> {
1103        use futures::TryStreamExt;
1104        self.stream_pages()
1105            .map_ok(|page| futures::stream::iter(page.into_iter().map(Ok)))
1106            .try_flatten()
1107    }
1108
1109    pub async fn all(self) -> Result<Vec<T>, ForgejoError> {
1110        use futures::TryStreamExt;
1111
1112        self.stream().try_collect().await
1113    }
1114}
1115
1116impl<'a, E: Endpoint, R: FromResponse> std::future::IntoFuture for Request<'a, E, R> {
1117    type Output = Result<R, ForgejoError>;
1118
1119    type IntoFuture = Pin<Box<dyn Future<Output = Self::Output> + 'a>>;
1120
1121    fn into_future(self) -> Self::IntoFuture {
1122        Box::pin(async move {
1123            let (response, has_body) =
1124                E::handle_error(self.client.send_request(&self.inner.inner).await?)?;
1125            Ok(R::from_response(response, has_body)?)
1126        })
1127    }
1128}