jb_space 0.2.0

Jetbrains Space API wrapper
Documentation
mod deserializers;

use std::collections::HashMap;

use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};

pub struct Client {
    #[allow(clippy::struct_field_names)]
    http_client: reqwest::Client,
    base_url: String,
    auth_token: String,
}

#[derive(Debug, thiserror::Error)]
pub enum Error {
    #[error("Request error: {0}")]
    Request(#[from] reqwest::Error),
    #[error("HTTP code is not successful: {status}, body: {body}")]
    HttpCodeIsNotSuccessful {
        status: reqwest::StatusCode,
        body: String,
    },
    #[error("Response parse error: {source}, body: {body}")]
    ResponseParse {
        source: serde_json::Error,
        body: String,
    },
}

#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct Member {
    pub id: String,
    pub username: String,
}

#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct Issue {
    pub id: String,
    pub title: String,
    pub number: usize,
    #[serde(
        rename(deserialize = "createdBy"),
        deserialize_with = "deserializers::deserialize_created_by"
    )]
    pub created_by: Member,
    #[serde(deserialize_with = "deserializers::deserialize_assignee", default)]
    pub assignee: Option<Member>,
    #[serde(deserialize_with = "deserializers::deserialize_status")]
    pub status: String,
    pub description: Option<String>,
    #[serde(
        rename(deserialize = "creationTime"),
        deserialize_with = "deserializers::deserialize_space_date"
    )]
    pub created_at: DateTime<Utc>,
}

#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct Message {
    pub id: String,
    pub text: String,
    #[serde(deserialize_with = "deserializers::deserialize_created_by")]
    pub author: Member,
    #[serde(
        rename(deserialize = "created"),
        deserialize_with = "deserializers::deserialize_space_date"
    )]
    pub created_at: DateTime<Utc>,
}

#[derive(Serialize, Deserialize, Debug, Clone)]
struct IssuesApiResponse {
    data: Vec<Issue>,
}

#[derive(Serialize, Deserialize, Debug, Clone)]
struct MessagesApiResponse {
    messages: Vec<Message>,
    #[serde(rename(deserialize = "nextStartFromDate"))]
    next_start_from_date: Option<PaginationDate>,
}

#[derive(Serialize, Deserialize, Debug, Clone)]
struct PaginationDate {
    iso: DateTime<Utc>,
}

#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct IssuesQuery {
    #[serde(skip_serializing)]
    pub project_id: String,
    pub sorting: String,
    pub descending: bool,
    #[serde(rename(serialize = "$top"))]
    pub top: usize,
    #[serde(rename(serialize = "$skip"))]
    pub skip: usize,
    #[serde(rename(serialize = "$fields"))]
    pub fields: String,
}

impl IssuesQuery {
    pub fn new(project_id: &str) -> Self {
        Self {
            project_id: project_id.to_string(),
            sorting: "CREATED".to_string(),
            descending: true,
            top: 100000,
            skip: 0,
            fields: "data(assignee(username,id),id,number,status,title,description,createdBy,commentsCount,creationTime),next,totalCount".to_string(),
        }
    }
}

#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct MessagesQuery {
    pub channel: String,
    pub sorting: String,
    #[serde(rename(serialize = "batchSize"))]
    pub batch_size: usize,
    #[serde(rename(serialize = "$fields"))]
    pub fields: String,
    #[serde(rename(serialize = "startFromDate"))]
    pub start_from_date: Option<DateTime<Utc>>,
}

impl MessagesQuery {
    pub fn new(issue_id: &str) -> Self {
        Self {
            channel: format!("issue:id:{issue_id}"),
            sorting: "FromNewestToOldest".to_string(),
            batch_size: 50,
            fields: "nextStartFromDate,orgLimitReached,messages(id,author,created,text)"
                .to_string(),
            start_from_date: None,
        }
    }
}

#[derive(Serialize, Deserialize, Debug)]
pub struct Project {
    pub id: String,
    pub name: String,
    #[serde(deserialize_with = "deserializers::deserialize_project_key")]
    pub key: String,
}

#[derive(Serialize, Deserialize, Debug)]
pub struct ProjectsApiResponse {
    data: Vec<Project>,
}

#[allow(clippy::trivially_copy_pass_by_ref)]
fn serialize_review_id<S>(review_number: &u32, serializer: S) -> Result<S::Ok, S::Error>
where
    S: serde::Serializer,
{
    serializer.serialize_str(&format!("number:{review_number}"))
}

// Space requires the field to always be present in requests, otherwise it
// misbehaves, so None is serialized as an empty string.
fn serialize_filename<S>(filename: &Option<String>, serializer: S) -> Result<S::Ok, S::Error>
where
    S: serde::Serializer,
{
    match filename {
        Some(filename) => serializer.serialize_str(filename),
        None => serializer.serialize_str(""),
    }
}

#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct CodeDiscussionAnchor {
    pub revision: String,
    #[serde(serialize_with = "serialize_filename")]
    pub filename: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub line: Option<u32>,
    #[serde(rename = "oldLine", skip_serializing_if = "Option::is_none")]
    pub old_line: Option<u32>,
}

#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct CreateCodeDiscussionQuery {
    #[serde(skip_serializing)]
    pub project_id: String,
    pub text: String,
    pub repository: String,
    pub anchor: CodeDiscussionAnchor,
    #[serde(rename = "endAnchor", skip_serializing_if = "Option::is_none")]
    pub end_anchor: Option<CodeDiscussionAnchor>,
    pub pending: bool,
    #[serde(rename = "reviewId", serialize_with = "serialize_review_id")]
    pub review_number: u32,
}

impl CreateCodeDiscussionQuery {
    pub fn new(
        project_id: &str,
        repository: &str,
        review_number: u32,
        text: &str,
        revision: &str,
    ) -> Self {
        Self {
            project_id: project_id.to_string(),
            text: text.to_string(),
            repository: repository.to_string(),
            anchor: CodeDiscussionAnchor {
                revision: revision.to_string(),
                filename: None,
                line: None,
                old_line: None,
            },
            end_anchor: None,
            pending: false,
            review_number,
        }
    }
}

#[derive(Serialize, Deserialize, Debug, Clone)]
#[allow(clippy::struct_excessive_bools)]
pub struct CodeDiscussion {
    pub id: String,
    #[serde(rename(deserialize = "projectId"))]
    pub project_id: String,
    pub anchor: CodeDiscussionAnchor,
    #[serde(rename(deserialize = "endAnchor"))]
    pub end_anchor: Option<CodeDiscussionAnchor>,
    #[serde(
        rename(deserialize = "created"),
        deserialize_with = "deserializers::deserialize_space_date"
    )]
    pub created_at: DateTime<Utc>,
    pub resolvable: bool,
    pub resolved: bool,
    pub pending: bool,
    pub archived: bool,
}

impl Client {
    pub fn new(base_url: &str, auth_token: &str, http_client: Option<reqwest::Client>) -> Self {
        Self {
            http_client: http_client.unwrap_or_default(),
            base_url: base_url.to_string(),
            auth_token: auth_token.to_string(),
        }
    }

    pub async fn get_projects(&self) -> Result<Vec<Project>, Error> {
        let url = format!("{}/api/http/projects", self.base_url);

        Ok(self
            .send_request::<_, ProjectsApiResponse>(&url, ())
            .await?
            .data)
    }

    pub async fn get_issues_for_project(&self, query: IssuesQuery) -> Result<Vec<Issue>, Error> {
        let url = format!(
            "{}/api/http/projects/id:{}/planning/issues",
            self.base_url, query.project_id
        );

        Ok(self
            .send_request::<_, IssuesApiResponse>(&url, query)
            .await?
            .data)
    }

    pub async fn get_issue_for_project_by_number(
        &self,
        project_id: &str,
        number: u32,
    ) -> Result<Issue, Error> {
        let url = format!(
            "{}/api/http/projects/id:{project_id}/planning/issues/number:{number}",
            self.base_url
        );

        let query = HashMap::from([(
            "$fields",
            "assignee(username,id),id,number,status,title,description,createdBy,commentsCount,creationTime",
        )]);

        self.send_request::<_, Issue>(&url, query).await
    }

    pub async fn get_issue_messages(&self, query: MessagesQuery) -> Result<Vec<Message>, Error> {
        let url = format!("{}/api/http/chats/messages", self.base_url);

        let mut actual_query = query.clone();
        let mut messages: HashMap<String, Message> = HashMap::new();
        loop {
            let response = self
                .send_request::<_, MessagesApiResponse>(&url, actual_query.clone())
                .await?;

            if response.messages.is_empty() {
                break;
            }

            let messages_more_than_batch_size = response.messages.len() < query.batch_size;

            response.messages.into_iter().for_each(|message| {
                messages.insert(message.id.clone(), message);
            });

            match response.next_start_from_date {
                Some(date) => {
                    actual_query.start_from_date = Some(date.iso);
                }
                None => {
                    break;
                }
            };

            if messages_more_than_batch_size {
                break;
            }
        }

        let mut res = messages.into_values().collect::<Vec<Message>>();
        res.sort_by_key(|message| message.created_at);
        Ok(res)
    }

    pub async fn create_code_discussion(
        &self,
        query: CreateCodeDiscussionQuery,
    ) -> Result<CodeDiscussion, Error> {
        let url = format!(
            "{}/api/http/projects/id:{}/code-reviews/code-discussions",
            self.base_url, query.project_id
        );

        self.send_post_request(&url, query).await
    }

    async fn send_post_request<TBody, TResponse>(
        &self,
        url: &str,
        body: TBody,
    ) -> Result<TResponse, Error>
    where
        TBody: Serialize + Send,
        TResponse: for<'de> Deserialize<'de> + Send,
    {
        let response = self
            .http_client
            .post(url)
            .header("Authorization", format!("Bearer {}", self.auth_token))
            .header("Accept", "application/json")
            .json(&body)
            .send()
            .await?;

        Self::parse_response(response).await
    }

    async fn parse_response<TResponse>(response: reqwest::Response) -> Result<TResponse, Error>
    where
        TResponse: for<'de> Deserialize<'de>,
    {
        let status = response.status();
        let body = response.text().await?;

        if !status.is_success() {
            return Err(Error::HttpCodeIsNotSuccessful { status, body });
        }

        serde_json::from_str(&body).map_err(|source| Error::ResponseParse { source, body })
    }

    async fn send_request<TQuery, TResponse>(
        &self,
        url: &str,
        query: TQuery,
    ) -> Result<TResponse, Error>
    where
        TQuery: Serialize + Send,
        TResponse: for<'de> Deserialize<'de> + Send,
    {
        let response = self
            .http_client
            .get(url)
            .header("Authorization", format!("Bearer {}", self.auth_token))
            .header("Accept", "application/json")
            .query(&query)
            .send()
            .await?;

        Self::parse_response(response).await
    }
}