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
use crate::{ImageData, ImageId, SharedString};
use collections::HashMap;
use futures::{
    future::{BoxFuture, Shared},
    AsyncReadExt, FutureExt, TryFutureExt,
};
use image::ImageError;
use parking_lot::Mutex;
use std::sync::Arc;
use thiserror::Error;
use util::http::{self, HttpClient};

#[derive(PartialEq, Eq, Hash, Clone)]
pub struct RenderImageParams {
    pub(crate) image_id: ImageId,
}

#[derive(Debug, Error, Clone)]
pub enum Error {
    #[error("http error: {0}")]
    Client(#[from] http::Error),
    #[error("IO error: {0}")]
    Io(Arc<std::io::Error>),
    #[error("unexpected http status: {status}, body: {body}")]
    BadStatus {
        status: http::StatusCode,
        body: String,
    },
    #[error("image error: {0}")]
    Image(Arc<ImageError>),
}

impl From<std::io::Error> for Error {
    fn from(error: std::io::Error) -> Self {
        Error::Io(Arc::new(error))
    }
}

impl From<ImageError> for Error {
    fn from(error: ImageError) -> Self {
        Error::Image(Arc::new(error))
    }
}

pub struct ImageCache {
    client: Arc<dyn HttpClient>,
    images: Arc<Mutex<HashMap<SharedString, FetchImageFuture>>>,
}

type FetchImageFuture = Shared<BoxFuture<'static, Result<Arc<ImageData>, Error>>>;

impl ImageCache {
    pub fn new(client: Arc<dyn HttpClient>) -> Self {
        ImageCache {
            client,
            images: Default::default(),
        }
    }

    pub fn get(
        &self,
        uri: impl Into<SharedString>,
    ) -> Shared<BoxFuture<'static, Result<Arc<ImageData>, Error>>> {
        let uri = uri.into();
        let mut images = self.images.lock();

        match images.get(&uri) {
            Some(future) => future.clone(),
            None => {
                let client = self.client.clone();
                let future = {
                    let uri = uri.clone();
                    async move {
                        let mut response = client.get(uri.as_ref(), ().into(), true).await?;
                        let mut body = Vec::new();
                        response.body_mut().read_to_end(&mut body).await?;

                        if !response.status().is_success() {
                            return Err(Error::BadStatus {
                                status: response.status(),
                                body: String::from_utf8_lossy(&body).into_owned(),
                            });
                        }

                        let format = image::guess_format(&body)?;
                        let image =
                            image::load_from_memory_with_format(&body, format)?.into_bgra8();
                        Ok(Arc::new(ImageData::new(image)))
                    }
                }
                .map_err({
                    let uri = uri.clone();

                    move |error| {
                        log::log!(log::Level::Error, "{:?} {:?}", &uri, &error);
                        error
                    }
                })
                .boxed()
                .shared();

                images.insert(uri, future.clone());
                future
            }
        }
    }
}