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
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
//! Library for importing assets into treasury.

use std::{
    io::ErrorKind,
    net::Ipv4Addr,
    path::PathBuf,
    process::Command,
    time::{Duration, Instant},
};

use eyre::WrapErr;
use tokio::{io::BufReader, net::TcpStream};
use treasury_api::{
    get_port, recv_message, send_handshake, send_message, FetchUrlResponse, FindResponse,
    OpenRequest, OpenResponse, Request, StoreResponse,
};
use url::Url;

pub use treasury_id::AssetId;

#[derive(Debug, serde::Deserialize)]
enum Treasury {
    // Remote(Url),
    Local(PathBuf),
}

#[derive(Debug)]
pub struct Client {
    #[allow(unused)]
    treasury: Treasury,
    stream: BufReader<TcpStream>,
}

impl Client {
    pub async fn local(treasury: PathBuf, init: bool) -> eyre::Result<Self> {
        let path = treasury
            .to_str()
            .ok_or_else(|| eyre::eyre!("Treasury path must not contain non UTF8 characters"))?;

        let mut stream = BufReader::new(connect_local().await?);

        send_handshake(&mut stream)
            .await
            .wrap_err("Failed to send handshake to treasury server")?;

        send_message(
            &mut stream,
            OpenRequest {
                init,
                path: path.into(),
            },
        )
        .await
        .wrap_err("Failed to send Open message to treasury server")?;

        match recv_message(&mut stream)
            .await
            .wrap_err("Failed to receive response for Open request")?
        {
            None => {
                return Err(eyre::eyre!(
                    "Failed to receive response for Open request. Connection lost."
                ));
            }
            Some(OpenResponse::Success) => {}
            Some(OpenResponse::Failure { description }) => {
                return Err(eyre::eyre!("Open request failure. {}", description));
            }
        }

        Ok(Client {
            stream,
            treasury: Treasury::Local(treasury),
        })
    }

    /// Store asset into treasury from specified URL.
    #[tracing::instrument]
    pub async fn store_asset(
        &mut self,
        source: &Url,
        format: Option<&str>,
        target: &str,
    ) -> eyre::Result<(AssetId, Box<str>)> {
        send_message(
            &mut self.stream,
            Request::Store {
                source: source.as_str().into(),
                format: format.map(|f| f.into()),
                target: target.into(),
            },
        )
        .await
        .wrap_err("Failed to send Store request")?;

        match recv_message(&mut self.stream)
            .await
            .wrap_err("Failed to receive response for Store request")?
        {
            None => Err(eyre::eyre!(
                "Failed to receive response for Store request. Connection lost."
            )),
            Some(StoreResponse::Success { id, path }) => {
                tracing::info!("Store requested succeeded");
                Ok((id, path))
            }
            Some(StoreResponse::Failure { description }) => {
                Err(eyre::eyre!("Store request failure. {}", description))
            }
            Some(StoreResponse::NeedData { url }) => Err(eyre::eyre!(
                "Treasury requires access to '{}' to finish store operation",
                url
            )),
        }
    }

    /// Store asset into treasury from specified URL.
    #[tracing::instrument]
    pub async fn fetch(&mut self, id: AssetId) -> eyre::Result<Option<Url>> {
        send_message(&mut self.stream, Request::FetchUrl { id })
            .await
            .wrap_err("Failed to send Store request")?;

        match recv_message(&mut self.stream)
            .await
            .wrap_err("Failed to receive response for Find request")?
        {
            None => Err(eyre::eyre!(
                "Failed to receive response for Find request. Connection lost."
            )),
            Some(FetchUrlResponse::Success { artifact }) => {
                tracing::info!("Find requested succeeded");
                let url = Url::parse(&artifact).wrap_err_with(|| {
                    format!(
                        "Failed to parse URL from '{}' from server response",
                        artifact
                    )
                })?;

                Ok(Some(url))
            }
            Some(FetchUrlResponse::Failure { description }) => {
                Err(eyre::eyre!("Find request failure. {}", description))
            }
            Some(FetchUrlResponse::NotFound) => Ok(None),
        }
    }

    /// Store asset into treasury from specified URL.
    #[tracing::instrument]
    pub async fn find(
        &mut self,
        source: &Url,
        target: &str,
    ) -> eyre::Result<Option<(AssetId, Box<str>)>> {
        send_message(
            &mut self.stream,
            Request::FindAsset {
                source: source.as_str().into(),
                target: target.into(),
            },
        )
        .await
        .wrap_err("Failed to send Store request")?;

        match recv_message(&mut self.stream)
            .await
            .wrap_err("Failed to receive response for Find request")?
        {
            None => Err(eyre::eyre!(
                "Failed to receive response for Find request. Connection lost."
            )),
            Some(FindResponse::Success { id, path }) => {
                tracing::info!("Find requested succeeded");

                Ok(Some((id, path)))
            }
            Some(FindResponse::Failure { description }) => {
                Err(eyre::eyre!("Find request failure. {}", description))
            }
            Some(FindResponse::NotFound) => Ok(None),
        }
    }
}

async fn connect_local() -> eyre::Result<TcpStream> {
    let port = get_port();

    match TcpStream::connect((Ipv4Addr::LOCALHOST, port)).await {
        Ok(stream) => {
            tracing::info!("Connected to running server");
            Ok(stream)
        }
        Err(err) if err.kind() == ErrorKind::ConnectionRefused => {
            tracing::info!("Failed to connect to treasury server. Run provisional instance");

            match Command::new("treasury-server")
                .env("TREASURY_PENDING_TIMEOUT", "5")
                .spawn()
            {
                Err(err) => {
                    return Err(eyre::eyre!(
                        "Failed to spawn provisional treasury server. {:#}",
                        err
                    ));
                }
                Ok(mut child) => {
                    let ten_ms = Duration::from_millis(10);
                    let second = Duration::from_secs(10);
                    let now = Instant::now();
                    let deadline = now + second;

                    while Instant::now() < deadline {
                        // Dirty, I know.
                        tokio::time::sleep(ten_ms).await;

                        match TcpStream::connect((Ipv4Addr::LOCALHOST, port)).await {
                            Ok(stream) => {
                                // Not recommended for long-running processes to do so on UNIX systems.
                                drop(child);
                                return Ok(stream);
                            }
                            Err(err) if err.kind() == ErrorKind::ConnectionRefused => continue,
                            Err(err) => {
                                let _ = child.kill();
                                return Err(eyre::eyre!(
                                    "Failed to connect to provisional treasury server. {:#}",
                                    err
                                ));
                            }
                        }
                    }

                    // Failed to connect. Kill the bastard.
                    let _ = child.kill();
                    return Err(eyre::eyre!(
                        "Failed to connect to provisional treasury server before timeout"
                    ));
                }
            }
        }
        Err(err) => Err(eyre::eyre!(
            "Failed to connect to treasury server. {:#}",
            err
        )),
    }
}