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
use reqwest::{header, Client};
use serde::{de::DeserializeOwned, Deserialize, Serialize};
use url::Url;

#[async_trait::async_trait]
pub trait Api {
    async fn login(&self, request: LoginRequest) -> anyhow::Result<LoginResponse>;

    async fn create_project(
        &self,
        request: CreateProjectRequest,
        token: String,
    ) -> anyhow::Result<CreateProjectResponse>;

    async fn register_task_version(
        &self,
        request: CreateTaskVersionRequest,
        token: String,
    ) -> anyhow::Result<CreateTaskVersionResponse>;
}

#[derive(Serialize, Deserialize)]
pub struct Error {
    pub message: String,
    pub chain: Vec<String>,
}

impl<'a> From<&'a anyhow::Error> for Error {
    fn from(err: &'a anyhow::Error) -> Self {
        Error {
            message: err.to_string(),
            chain: err.chain().map(|e| e.to_string()).collect::<Vec<_>>(),
        }
    }
}

impl From<Error> for anyhow::Error {
    fn from(value: Error) -> Self {
        match value.chain.as_slice() {
            [] => anyhow::Error::msg(value.message),
            [head @ .., last] => head
                .into_iter()
                .rev()
                .fold(anyhow::Error::msg(last.to_string()), |e, m| {
                    e.context(m.to_string())
                }),
        }
    }
}

#[derive(Serialize, Deserialize)]
pub struct LoginRequest {
    pub email: String,
    pub password: String,
}

#[derive(Serialize, Deserialize)]
pub enum LoginResponse {
    CreatedAccount { email: String, token: String },
    LoggedIn { email: String, token: String },
}

#[derive(Serialize, Deserialize)]
pub struct CreateProjectRequest {
    pub nickname: Option<String>,
}

#[derive(Serialize, Deserialize)]
pub struct CreateProjectResponse {
    pub id: String,
    pub nickname: Option<String>,
}

#[derive(Serialize, Deserialize)]
pub struct CreateTaskVersionRequest {
    pub project_id: String,
    pub task_id: String,
}

#[derive(Serialize, Deserialize, Debug)]
pub struct CreateTaskVersionResponse {
    pub project_id: String,
    pub task_id: String,
    pub hash: String,
    pub created_at: chrono::NaiveDateTime,
}

#[derive(Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum Method {
    Login,
    CreateProject,
    RegisterTaskVersion,
}

pub struct HttpApi {
    client: Client,
    base: Url,
}

impl HttpApi {
    pub fn new(base: &Url) -> anyhow::Result<Self> {
        anyhow::ensure!(base.as_str().ends_with("/"), "API url must end with a /");

        Ok(Self {
            client: Client::new(),
            base: base.clone(),
        })
    }

    async fn call_endpoint<I, O>(
        &self,
        endpoint: Method,
        body: I,
        token: impl Into<Option<String>>,
    ) -> anyhow::Result<O>
    where
        I: Serialize,
        O: DeserializeOwned,
    {
        let url = self.base.join(&serde_json::to_string(&endpoint)?)?;
        let request = self.client.post(url);
        let request = if let Some(token) = token.into() {
            request.header(header::AUTHORIZATION, format!("Bearer {token}"))
        } else {
            request
        };

        let response = request.json(&body).send().await?;

        let status = response.status();
        if status.is_success() {
            Ok(response.json().await?)
        } else if status.is_client_error() || status.is_server_error() {
            Err(response.json::<Error>().await?.into())
        } else {
            anyhow::bail!("Unhandled error code {}", status);
        }
    }
}

#[async_trait::async_trait]
impl Api for HttpApi {
    async fn login(&self, request: LoginRequest) -> anyhow::Result<LoginResponse> {
        self.call_endpoint(Method::Login, request, None).await
    }

    async fn create_project(
        &self,
        request: CreateProjectRequest,
        token: String,
    ) -> anyhow::Result<CreateProjectResponse> {
        self.call_endpoint(Method::CreateProject, request, token)
            .await
    }

    async fn register_task_version(
        &self,
        request: CreateTaskVersionRequest,
        token: String,
    ) -> anyhow::Result<CreateTaskVersionResponse> {
        self.call_endpoint(Method::RegisterTaskVersion, request, token)
            .await
    }
}