redseat-api 0.2.0

Rust client for Redseat media servers
Documentation
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
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
//! HTTP + SSE transport, with reqwest and rustls. Port of `@redseat/api-http`
//! `http-transport.ts` and `client.ts`, with the address choice of `direct.ts`.

use std::sync::PoisonError;
use std::sync::RwLock;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::Duration;

use futures_util::StreamExt;

use crate::cloud::CloudServer;
use crate::direct::{ProbeOptions, probe_candidates_with, server_candidates};
use crate::error::{Error, Result};
use crate::sse::decode_event_stream;
use crate::transport::{Body, EventRequest, Method, RawEventStream, Request, Response, Transport};

/// Default request timeout (TS: 30 s).
pub const DEFAULT_TIMEOUT: Duration = Duration::from_secs(30);

/// How [`HttpTransport::connect`] picks a server address.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ConnectOptions {
    /// The URL that worked last time, cached by the app: tried first.
    pub preferred_url: Option<String>,
    pub probe: ProbeOptions,
    /// Request timeout.
    pub timeout: Duration,
}

impl Default for ConnectOptions {
    fn default() -> Self {
        ConnectOptions {
            preferred_url: None,
            probe: ProbeOptions::default(),
            timeout: DEFAULT_TIMEOUT,
        }
    }
}

/// [`Transport`] over HTTP(S).
pub struct HttpTransport {
    client: reqwest::Client,
    base_url: RwLock<String>,
    timeout: Duration,
    closed: AtomicBool,
}

impl std::fmt::Debug for HttpTransport {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("HttpTransport")
            .field("base_url", &self.base_url())
            .finish_non_exhaustive()
    }
}

fn http_client() -> Result<reqwest::Client> {
    reqwest::Client::builder()
        .build()
        .map_err(|e| Error::transport(format!("HTTP client: {e}")))
}

fn map_reqwest_error(error: reqwest::Error, path: &str) -> Error {
    let path = Some(path.to_owned());
    let message = error.to_string();
    if error.is_timeout() {
        Error::Timeout { message, path }
    } else if error.is_decode() {
        Error::MalformedResponse { message, path }
    } else if error.is_builder() {
        Error::Transport {
            message,
            status: None,
            path,
        }
    } else {
        Error::Network { message, path }
    }
}

fn reqwest_method(method: Method) -> reqwest::Method {
    match method {
        Method::Get => reqwest::Method::GET,
        Method::Head => reqwest::Method::HEAD,
        Method::Post => reqwest::Method::POST,
        Method::Put => reqwest::Method::PUT,
        Method::Patch => reqwest::Method::PATCH,
        Method::Delete => reqwest::Method::DELETE,
    }
}

/// `GET <url>/ping`: true when it answers with a success.
async fn ping(client: &reqwest::Client, url: &str, timeout: Duration) -> bool {
    client
        .get(format!("{url}/ping"))
        .timeout(timeout)
        .send()
        .await
        .is_ok_and(|response| response.status().is_success())
}

/// The base URL to reach `server` at: the first of its direct addresses and custom
/// domain to answer `/ping` (see [`crate::direct`]), else its `url`.
pub async fn resolve_server_url(server: &CloudServer, options: &ConnectOptions) -> Result<String> {
    let candidates = server_candidates(server, options.preferred_url.as_deref());
    if !candidates.is_empty() {
        let client = http_client()?;
        let timeout = options.probe.timeout;
        let winner = probe_candidates_with(&candidates, options.probe, |candidate| {
            let client = client.clone();
            let url = candidate.url.clone();
            async move { ping(&client, &url, timeout).await }
        })
        .await;
        if let Some(winner) = winner {
            return Ok(winner.url);
        }
    }
    if !server.url.is_empty() {
        let port = server.port.map(|p| format!(":{p}")).unwrap_or_default();
        return Ok(format!("https://{}{port}", server.url));
    }
    Err(Error::Network {
        message: format!(
            "server {} is unreachable: none of its addresses answered",
            server.name.as_deref().unwrap_or(&server.id)
        ),
        path: None,
    })
}

impl HttpTransport {
    /// A transport to `base_url` (`https://host:port`).
    pub fn new(base_url: &str) -> Result<Self> {
        Self::with_timeout(base_url, DEFAULT_TIMEOUT)
    }

    pub fn with_timeout(base_url: &str, timeout: Duration) -> Result<Self> {
        Ok(HttpTransport {
            client: http_client()?,
            base_url: RwLock::new(normalize_base(base_url)?),
            timeout,
            closed: AtomicBool::new(false),
        })
    }

    /// A transport to `server`, at the address [`resolve_server_url`] picks.
    pub async fn connect(server: &CloudServer, options: ConnectOptions) -> Result<Self> {
        let base_url = resolve_server_url(server, &options).await?;
        Self::with_timeout(&base_url, options.timeout)
    }

    pub fn base_url(&self) -> String {
        self.base_url
            .read()
            .unwrap_or_else(PoisonError::into_inner)
            .clone()
    }

    /// Switches to another address, for example after the network changed.
    pub fn set_base_url(&self, base_url: &str) -> Result<()> {
        let base_url = normalize_base(base_url)?;
        *self
            .base_url
            .write()
            .unwrap_or_else(PoisonError::into_inner) = base_url;
        Ok(())
    }

    fn url(&self, path: &str, query: &[(String, String)]) -> Result<url::Url> {
        let absolute = if path.starts_with("http://") || path.starts_with("https://") {
            path.to_owned()
        } else {
            let slash = if path.starts_with('/') { "" } else { "/" };
            format!("{}{slash}{path}", self.base_url())
        };
        let mut url = url::Url::parse(&absolute).map_err(|e| Error::Transport {
            message: format!("invalid URL {absolute}: {e}"),
            status: None,
            path: Some(path.to_owned()),
        })?;
        if !query.is_empty() {
            url.query_pairs_mut().extend_pairs(query);
        }
        Ok(url)
    }

    fn check_open(&self, path: &str) -> Result<()> {
        if self.closed.load(Ordering::Relaxed) {
            return Err(Error::Transport {
                message: "HTTP transport is closed".to_owned(),
                status: None,
                path: Some(path.to_owned()),
            });
        }
        Ok(())
    }
}

fn normalize_base(base_url: &str) -> Result<String> {
    let trimmed = base_url.trim_end_matches('/');
    url::Url::parse(trimmed)
        .map_err(|e| Error::transport(format!("invalid URL {base_url}: {e}")))?;
    Ok(trimmed.to_owned())
}

async fn error_of(response: reqwest::Response, path: &str) -> Error {
    let status = response.status().as_u16();
    let body = response
        .bytes()
        .await
        .map(|b| b.to_vec())
        .unwrap_or_default();
    Error::from_status(status, Some(path), &body)
}

#[cfg_attr(not(target_arch = "wasm32"), async_trait::async_trait)]
#[cfg_attr(target_arch = "wasm32", async_trait::async_trait(?Send))]
impl Transport for HttpTransport {
    async fn request(&self, request: Request) -> Result<Response> {
        self.check_open(&request.path)?;
        let path = request.path.clone();
        let url = self.url(&request.path, &request.query)?;
        let mut builder = self
            .client
            .request(reqwest_method(request.method), url)
            .timeout(request.timeout.unwrap_or(self.timeout));
        for (name, value) in &request.headers {
            builder = builder.header(name, value);
        }
        builder = match request.body {
            None => builder,
            Some(Body::Json(value)) => builder
                .header("Content-Type", "application/json")
                .body(value.to_string()),
            Some(Body::Form(fields)) => builder
                .header("Content-Type", "application/x-www-form-urlencoded")
                .body(
                    url::form_urlencoded::Serializer::new(String::new())
                        .extend_pairs(fields)
                        .finish(),
                ),
            Some(Body::Bytes { content_type, data }) => {
                builder.header("Content-Type", content_type).body(data)
            }
        };

        let response = builder
            .send()
            .await
            .map_err(|e| map_reqwest_error(e, &path))?;
        if !response.status().is_success() {
            return Err(error_of(response, &path).await);
        }
        let status = response.status().as_u16();
        let headers = response
            .headers()
            .iter()
            .filter_map(|(name, value)| {
                Some((name.as_str().to_owned(), value.to_str().ok()?.to_owned()))
            })
            .collect();
        let body = response
            .bytes()
            .await
            .map_err(|e| map_reqwest_error(e, &path))?
            .to_vec();
        Ok(Response {
            status,
            headers,
            body,
        })
    }

    async fn subscribe(&self, request: EventRequest) -> Result<RawEventStream> {
        self.check_open(&request.path)?;
        let path = request.path.clone();
        let url = self.url(&request.path, &request.query)?;
        // No timeout: the stream stays open.
        let mut builder = self
            .client
            .get(url)
            .header("Accept", "text/event-stream")
            .header("Cache-Control", "no-cache");
        for (name, value) in &request.headers {
            builder = builder.header(name, value);
        }
        let response = builder
            .send()
            .await
            .map_err(|e| map_reqwest_error(e, &path))?;
        if !response.status().is_success() {
            return Err(error_of(response, &path).await);
        }
        let chunks = response
            .bytes_stream()
            .map(move |chunk| chunk.map_err(|e| map_reqwest_error(e, &path)));
        Ok(Box::pin(decode_event_stream(Box::pin(chunks))))
    }

    fn close(&self) {
        self.closed.store(true, Ordering::Relaxed);
    }

    fn http_base_url(&self) -> Option<String> {
        Some(self.base_url())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::test_support::serve_http as serve;

    #[tokio::test]
    async fn sends_requests_and_maps_statuses() {
        let (address, mut heads) = serve(
            "HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: 7\r\nconnection: close\r\n\r\n[1,2,3]",
        )
        .await;
        let transport = HttpTransport::new(&format!("http://{address}/")).unwrap();
        let response = transport
            .request(
                Request::get("/libraries/x/medias")
                    .query("filter", "{\"a\":1}")
                    .bearer("tok"),
            )
            .await
            .unwrap();
        assert_eq!(response.json::<Vec<u8>>().unwrap(), vec![1, 2, 3]);
        assert_eq!(response.header("Content-Type"), Some("application/json"));
        let head = heads.recv().await.unwrap();
        assert!(head.starts_with("GET /libraries/x/medias?filter=%7B%22a%22%3A1%7D HTTP/1.1"));
        assert!(head.to_lowercase().contains("authorization: bearer tok"));

        let (address, _) =
            serve("HTTP/1.1 401 Unauthorized\r\ncontent-length: 0\r\nconnection: close\r\n\r\n")
                .await;
        let transport = HttpTransport::new(&format!("http://{address}")).unwrap();
        let error = transport.request(Request::get("/x")).await.unwrap_err();
        assert_eq!(error.kind(), crate::ErrorKind::Unauthorized);
        assert_eq!(error.path(), Some("/x"));
    }

    #[tokio::test]
    async fn streams_server_events() {
        let (address, mut heads) = serve(
            "HTTP/1.1 200 OK\r\ncontent-type: text/event-stream\r\nconnection: close\r\n\r\nevent: heartbeat\ndata: {}\n\nevent: medias\ndata: {\"medias\":{\"library\":\"l\",\"medias\":[]}}\n\nevent: tags\ndata: {}",
        )
        .await;
        let transport = HttpTransport::new(&format!("http://{address}")).unwrap();
        let events: Vec<_> = transport
            .subscribe(EventRequest {
                path: "/sse".into(),
                query: vec![("libraries".into(), "l".into())],
                ..Default::default()
            })
            .await
            .unwrap()
            .collect()
            .await;
        let names: Vec<_> = events
            .iter()
            .map(|e| e.as_ref().unwrap().event.as_str())
            .collect();
        assert_eq!(names, vec!["heartbeat", "medias", "tags"]);
        let head = heads.recv().await.unwrap();
        assert!(head.starts_with("GET /sse?libraries=l HTTP/1.1"));
        assert!(head.to_lowercase().contains("accept: text/event-stream"));
    }

    #[tokio::test]
    async fn a_closed_transport_refuses_requests() {
        let transport = HttpTransport::new("http://127.0.0.1:9").unwrap();
        transport.close();
        let error = transport.request(Request::get("/x")).await.unwrap_err();
        assert_eq!(error.kind(), crate::ErrorKind::Transport);
    }

    #[tokio::test]
    async fn falls_back_to_the_server_url_when_no_candidate_answers() {
        let server = CloudServer {
            id: "srv".into(),
            name: None,
            url: "media.example.org".into(),
            port: Some(8443),
            local: None,
            direct: None,
            domain: None,
            member: None,
        };
        let url = resolve_server_url(&server, &ConnectOptions::default())
            .await
            .unwrap();
        assert_eq!(url, "https://media.example.org:8443");

        let unreachable = CloudServer {
            url: String::new(),
            ..server
        };
        let error = resolve_server_url(&unreachable, &ConnectOptions::default())
            .await
            .unwrap_err();
        assert_eq!(error.kind(), crate::ErrorKind::Network);
    }
}