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
use async_std::io::prelude::BufReadExt;
use async_std::stream::StreamExt;

use bytes::Bytes;

use futures::TryStreamExt;

use serde::de::DeserializeOwned;
use tracing::debug;

use crate::error::{Error, Result};

#[derive(Debug, Clone)]
pub struct LichessApi<HttpClient> {
    pub client: HttpClient,
    bearer_auth: Option<String>,
}

impl<HttpClient> LichessApi<HttpClient> {
    pub fn new(client: HttpClient, auth_token: Option<String>) -> Self {
        let bearer_auth = auth_token.map(|token| format!("Bearer {}", token));
        Self {
            client,
            bearer_auth,
        }
    }

    pub(crate) async fn expect_one_model<Model, G>(&self, stream: &mut G) -> Result<Model>
    where
        G: StreamExt<Item = Result<Model>> + std::marker::Unpin,
    {
        stream
            .next()
            .await
            .ok_or(Error::Response("empty response stream".to_string()))?
    }
}

impl LichessApi<reqwest::Client> {
    pub(crate) async fn send<Model: DeserializeOwned>(
        &self,
        mut http_request: http::Request<Bytes>,
    ) -> Result<impl StreamExt<Item = Result<Model>>> {
        if let Some(auth) = &self.bearer_auth {
            let mut auth_header = http::HeaderValue::from_str(&auth)
                .map_err(|e| Error::HttpRequestBuilder(http::Error::from(e)))?;
            // exclude the auth header from being logged
            auth_header.set_sensitive(true);
            http_request
                .headers_mut()
                .insert(http::header::AUTHORIZATION, auth_header);
        };

        let convert_err = |e: reqwest::Error| Error::Request(e.to_string());
        let mut request = reqwest::Request::try_from(http_request).map_err(convert_err)?;
        *request.timeout_mut() = None;
        debug!(?request, "sending");
        let response = self.client.execute(request).await;
        debug!(?response, "received");
        let stream = response
            .map_err(convert_err)?
            .bytes_stream()
            .map_err(|e| futures::io::Error::new(futures::io::ErrorKind::Other, e))
            .into_async_read()
            .lines()
            .filter(|l| {
                // To avoid trying to serialize blank keep alive lines.
                !l.as_ref().unwrap_or(&"".to_string()).is_empty()
            })
            .map(|l| -> Result<Model> {
                let line = l?;
                debug!(line, "model line");
                if line.starts_with("<!DOCTYPE html>") {
                    return Err(crate::error::Error::PageNotFound());
                }
                serde_json::from_str(&line).map_err(|e| crate::error::Error::Json(e))
            });

        Ok(stream)
    }
}