-
Notifications
You must be signed in to change notification settings - Fork 55
Expand file tree
/
Copy pathclient.rs
More file actions
594 lines (520 loc) · 21.3 KB
/
Copy pathclient.rs
File metadata and controls
594 lines (520 loc) · 21.3 KB
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
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
use std::time::Duration;
use hyper::{HeaderMap, header};
use reqwest::{Response, StatusCode};
use serde::Serialize;
use serde::de::DeserializeOwned;
use thiserror::Error;
// Re-export AddKeyForm from the protocol package for backwards compatibility.
pub use torrust_tracker_rest_api_protocol::v1::context::auth_key::forms::add_key_form::AddKeyForm;
use torrust_tracker_rest_api_protocol::v1::context::auth_key::resources::auth_key::AuthKey;
use torrust_tracker_rest_api_protocol::v1::context::stats::resources::stats::Stats;
use torrust_tracker_rest_api_protocol::v1::context::torrent::resources::torrent::{ListItem, Torrent};
use url::Url;
use uuid::Uuid;
use crate::common::http::{Query, QueryParam, ReqwestQuery};
use crate::connection_info::ConnectionInfo;
pub const TOKEN_PARAM_NAME: &str = "token";
pub const AUTH_BEARER_TOKEN_HEADER_PREFIX: &str = "Bearer";
const API_PATH: &str = "api/v1/";
const DEFAULT_REQUEST_TIMEOUT_IN_SECS: u64 = 5;
/// Error type for [`ApiClient`] operations.
#[derive(Debug, Error)]
pub enum ClientError {
/// A transport-level error (connection refused, timeout, DNS failure, etc.).
#[error("transport error: {0}")]
TransportError(#[source] reqwest::Error),
/// The API returned a non-2xx status code.
#[error("API error: {status} - {body}")]
ApiError {
/// The HTTP status code returned by the API.
status: StatusCode,
/// The response body (error message).
body: String,
},
/// Failed to deserialize the API response body into the expected type.
#[error("deserialization error: {0}")]
DeserializationError(#[source] reqwest::Error),
/// An internal error (URL construction failure, etc.).
#[error("internal error: {0}")]
InternalError(String),
}
impl From<reqwest::Error> for ClientError {
fn from(err: reqwest::Error) -> Self {
Self::TransportError(err)
}
}
/// High-level typed client for the Torrust Tracker REST API.
///
/// Wraps [`ApiHttpClient`] and returns protocol DTOs from `rest-api-protocol`.
/// Never panics — all errors are returned as [`ClientError`].
pub struct ApiClient {
inner: ApiHttpClient,
}
impl ApiClient {
/// Creates a new `ApiClient`.
///
/// # Errors
///
/// Returns [`ClientError::TransportError`] if the HTTP client cannot be built.
pub fn new(connection_info: ConnectionInfo) -> Result<Self, ClientError> {
Ok(Self {
inner: ApiHttpClient::new(connection_info).map_err(ClientError::TransportError)?,
})
}
/// Returns a reference to the inner [`ApiHttpClient`] for low-level operations.
#[must_use]
pub fn inner(&self) -> &ApiHttpClient {
&self.inner
}
/// Generates a new random authentication key valid for `seconds_valid`.
///
/// # Errors
///
/// Returns [`ClientError::TransportError`] if the request fails.
/// Returns [`ClientError::ApiError`] if the API returns a non-2xx status.
/// Returns [`ClientError::DeserializationError`] if the response cannot be parsed.
pub async fn generate_auth_key(&self, seconds_valid: i32) -> Result<AuthKey, ClientError> {
let response = self.inner.post_empty_result(&format!("key/{seconds_valid}"), None).await?;
Self::parse_response(response).await
}
/// Adds a new authentication key using the provided form data.
///
/// # Errors
///
/// Returns [`ClientError::TransportError`] if the request fails.
/// Returns [`ClientError::ApiError`] if the API returns a non-2xx status.
/// Returns [`ClientError::DeserializationError`] if the response cannot be parsed.
pub async fn add_auth_key(&self, form: AddKeyForm) -> Result<AuthKey, ClientError> {
let response = self.inner.post_form_result("keys", &form, None).await?;
Self::parse_response(response).await
}
/// Deletes an authentication key.
///
/// # Errors
///
/// Returns [`ClientError::TransportError`] if the request fails.
/// Returns [`ClientError::ApiError`] if the API returns a non-2xx status.
pub async fn delete_auth_key(&self, key: &str) -> Result<(), ClientError> {
let response = self.inner.delete_result(&format!("key/{key}"), None).await?;
Self::check_success(response).await
}
/// Reloads authentication keys from the database.
///
/// # Errors
///
/// Returns [`ClientError::TransportError`] if the request fails.
/// Returns [`ClientError::ApiError`] if the API returns a non-2xx status.
pub async fn reload_keys(&self) -> Result<(), ClientError> {
let response = self.inner.get_result("keys/reload", Query::default(), None).await?;
Self::check_success(response).await
}
/// Whitelists a torrent by info hash.
///
/// # Errors
///
/// Returns [`ClientError::TransportError`] if the request fails.
/// Returns [`ClientError::ApiError`] if the API returns a non-2xx status.
pub async fn whitelist_a_torrent(&self, info_hash: &str) -> Result<(), ClientError> {
let response = self.inner.post_empty_result(&format!("whitelist/{info_hash}"), None).await?;
Self::check_success(response).await
}
/// Removes a torrent from the whitelist.
///
/// # Errors
///
/// Returns [`ClientError::TransportError`] if the request fails.
/// Returns [`ClientError::ApiError`] if the API returns a non-2xx status.
pub async fn remove_torrent_from_whitelist(&self, info_hash: &str) -> Result<(), ClientError> {
let response = self.inner.delete_result(&format!("whitelist/{info_hash}"), None).await?;
Self::check_success(response).await
}
/// Reloads the whitelist from the database.
///
/// # Errors
///
/// Returns [`ClientError::TransportError`] if the request fails.
/// Returns [`ClientError::ApiError`] if the API returns a non-2xx status.
pub async fn reload_whitelist(&self) -> Result<(), ClientError> {
let response = self.inner.get_result("whitelist/reload", Query::default(), None).await?;
Self::check_success(response).await
}
/// Gets a single torrent by info hash.
///
/// # Errors
///
/// Returns [`ClientError::TransportError`] if the request fails.
/// Returns [`ClientError::ApiError`] if the API returns a non-2xx status.
/// Returns [`ClientError::DeserializationError`] if the response cannot be parsed.
pub async fn get_torrent(&self, info_hash: &str) -> Result<Torrent, ClientError> {
let response = self
.inner
.get_result(&format!("torrent/{info_hash}"), Query::default(), None)
.await?;
Self::parse_response(response).await
}
/// Gets a list of torrents matching the query parameters.
///
/// # Errors
///
/// Returns [`ClientError::TransportError`] if the request fails.
/// Returns [`ClientError::ApiError`] if the API returns a non-2xx status.
/// Returns [`ClientError::DeserializationError`] if the response cannot be parsed.
pub async fn get_torrents(&self, params: Query) -> Result<Vec<ListItem>, ClientError> {
let response = self.inner.get_result("torrents", params, None).await?;
Self::parse_response(response).await
}
/// Gets tracker statistics.
///
/// # Errors
///
/// Returns [`ClientError::TransportError`] if the request fails.
/// Returns [`ClientError::ApiError`] if the API returns a non-2xx status.
/// Returns [`ClientError::DeserializationError`] if the response cannot be parsed.
pub async fn get_tracker_statistics(&self) -> Result<Stats, ClientError> {
let response = self.inner.get_result("stats", Query::default(), None).await?;
Self::parse_response(response).await
}
/// Parses a successful response into the expected DTO type.
async fn parse_response<T: DeserializeOwned>(response: Response) -> Result<T, ClientError> {
let status = response.status();
if !status.is_success() {
let body = response.text().await.map_err(ClientError::TransportError)?;
return Err(ClientError::ApiError { status, body });
}
response.json::<T>().await.map_err(ClientError::DeserializationError)
}
/// Checks that the response has a 2xx status code, ignoring the body.
async fn check_success(response: Response) -> Result<(), ClientError> {
let status = response.status();
if !status.is_success() {
let body = response.text().await.map_err(ClientError::TransportError)?;
return Err(ClientError::ApiError { status, body });
}
Ok(())
}
}
/// Low-level HTTP transport for the Torrust Tracker REST API.
///
/// Handles connection info, URL building, auth headers, and raw HTTP requests.
/// Returns [`reqwest::Response`] directly. For a typed high-level API, use
/// [`ApiClient`].
#[allow(clippy::struct_field_names)]
pub struct ApiHttpClient {
connection_info: ConnectionInfo,
base_path: String,
http_client: reqwest::Client,
}
impl ApiHttpClient {
/// # Errors
///
/// Will return an error if the HTTP client can't be created.
pub fn new(connection_info: ConnectionInfo) -> Result<Self, reqwest::Error> {
let client = reqwest::Client::builder()
.timeout(Duration::from_secs(DEFAULT_REQUEST_TIMEOUT_IN_SECS))
.build()?;
Ok(Self {
connection_info,
base_path: API_PATH.to_string(),
http_client: client,
})
}
/// Generates a new random authentication key valid for `seconds_valid`.
///
/// # Errors
///
/// Will return an error if the request can't be sent.
pub async fn generate_auth_key(&self, seconds_valid: i32, headers: Option<HeaderMap>) -> Result<Response, ClientError> {
self.post_empty_result(&format!("key/{seconds_valid}"), headers).await
}
/// Adds a new authentication key using the provided form data.
///
/// # Errors
///
/// Will return an error if the request can't be sent.
pub async fn add_auth_key(&self, add_key_form: AddKeyForm, headers: Option<HeaderMap>) -> Result<Response, ClientError> {
self.post_form_result("keys", &add_key_form, headers).await
}
/// Deletes an authentication key.
///
/// # Errors
///
/// Will return an error if the request can't be sent.
pub async fn delete_auth_key(&self, key: &str, headers: Option<HeaderMap>) -> Result<Response, ClientError> {
self.delete_result(&format!("key/{key}"), headers).await
}
/// Reloads authentication keys from the database.
///
/// # Errors
///
/// Will return an error if the request can't be sent.
pub async fn reload_keys(&self, headers: Option<HeaderMap>) -> Result<Response, ClientError> {
self.get_result("keys/reload", Query::default(), headers).await
}
/// Whitelists a torrent by info hash.
///
/// # Errors
///
/// Will return an error if the request can't be sent.
pub async fn whitelist_a_torrent(&self, info_hash: &str, headers: Option<HeaderMap>) -> Result<Response, ClientError> {
self.post_empty_result(&format!("whitelist/{info_hash}"), headers).await
}
/// Removes a torrent from the whitelist.
///
/// # Errors
///
/// Will return an error if the request can't be sent.
pub async fn remove_torrent_from_whitelist(
&self,
info_hash: &str,
headers: Option<HeaderMap>,
) -> Result<Response, ClientError> {
self.delete_result(&format!("whitelist/{info_hash}"), headers).await
}
/// Reloads the whitelist from the database.
///
/// # Errors
///
/// Will return an error if the request can't be sent.
pub async fn reload_whitelist(&self, headers: Option<HeaderMap>) -> Result<Response, ClientError> {
self.get_result("whitelist/reload", Query::default(), headers).await
}
/// Gets a single torrent by info hash.
///
/// # Errors
///
/// Will return an error if the request can't be sent.
pub async fn get_torrent(&self, info_hash: &str, headers: Option<HeaderMap>) -> Result<Response, ClientError> {
self.get_result(&format!("torrent/{info_hash}"), Query::default(), headers)
.await
}
/// Gets a list of torrents matching the query parameters.
///
/// # Errors
///
/// Will return an error if the request can't be sent.
pub async fn get_torrents(&self, params: Query, headers: Option<HeaderMap>) -> Result<Response, ClientError> {
self.get_result("torrents", params, headers).await
}
/// Gets tracker statistics.
///
/// # Errors
///
/// Will return an error if the request can't be sent.
pub async fn get_tracker_statistics(&self, headers: Option<HeaderMap>) -> Result<Response, ClientError> {
self.get_result("stats", Query::default(), headers).await
}
/// Performs a GET request.
///
/// # Errors
///
/// Will return an error if the request can't be sent.
pub async fn get(&self, path: &str, params: Query, headers: Option<HeaderMap>) -> Result<Response, ClientError> {
self.get_result(path, params, headers).await
}
/// Fallible method that also adds the API token to the query if one is configured.
///
/// Prefer [`Self::get`] for most use cases; use this when you need access to
/// the raw token-injection logic.
pub(crate) async fn get_result(
&self,
path: &str,
params: Query,
headers: Option<HeaderMap>,
) -> Result<Response, ClientError> {
let mut query: Query = params;
if let Some(token) = &self.connection_info.api_token {
query.add_param(QueryParam::new(TOKEN_PARAM_NAME, token));
}
self.get_request_with_query_result(path, query, headers).await
}
/// # Errors
///
/// Will return an error if the request can't be sent.
pub async fn post_empty(&self, path: &str, headers: Option<HeaderMap>) -> Result<Response, ClientError> {
self.post_empty_result(path, headers).await
}
/// Fallible method that also adds the API token header if one is configured.
///
/// Prefer [`Self::post_empty`] for most use cases; use this when you need access
/// to the raw token-injection logic.
pub(crate) async fn post_empty_result(&self, path: &str, headers: Option<HeaderMap>) -> Result<Response, ClientError> {
let builder = self.http_client.post(self.base_url(path)?.clone());
let builder = match headers {
Some(headers) => builder.headers(headers),
None => builder,
};
let builder = match &self.connection_info.api_token {
Some(token) => builder.header(header::AUTHORIZATION, format!("{AUTH_BEARER_TOKEN_HEADER_PREFIX} {token}")),
None => builder,
};
Ok(builder.send().await?)
}
/// # Errors
///
/// Will return an error if the request can't be sent.
pub async fn post_form<T: Serialize + ?Sized>(
&self,
path: &str,
form: &T,
headers: Option<HeaderMap>,
) -> Result<Response, ClientError> {
self.post_form_result(path, form, headers).await
}
/// Fallible method that also adds the API token header if one is configured.
///
/// Prefer [`Self::post_form`] for most use cases; use this when you need access
/// to the raw token-injection logic.
pub(crate) async fn post_form_result<T: Serialize + ?Sized>(
&self,
path: &str,
form: &T,
headers: Option<HeaderMap>,
) -> Result<Response, ClientError> {
let builder = self.http_client.post(self.base_url(path)?.clone()).json(&form);
let builder = match headers {
Some(headers) => builder.headers(headers),
None => builder,
};
let builder = match &self.connection_info.api_token {
Some(token) => builder.header(header::AUTHORIZATION, format!("{AUTH_BEARER_TOKEN_HEADER_PREFIX} {token}")),
None => builder,
};
Ok(builder.send().await?)
}
/// Fallible version of [`Self::delete`] that returns a `Result` instead of panicking.
async fn delete_result(&self, path: &str, headers: Option<HeaderMap>) -> Result<Response, ClientError> {
let builder = self.http_client.delete(self.base_url(path)?.clone());
let builder = match headers {
Some(headers) => builder.headers(headers),
None => builder,
};
let builder = match &self.connection_info.api_token {
Some(token) => builder.header(header::AUTHORIZATION, format!("{AUTH_BEARER_TOKEN_HEADER_PREFIX} {token}")),
None => builder,
};
Ok(builder.send().await?)
}
/// # Errors
///
/// Will return an error if the request can't be sent.
pub async fn get_request_with_query(
&self,
path: &str,
params: Query,
headers: Option<HeaderMap>,
) -> Result<Response, ClientError> {
self.get_request_with_query_result(path, params, headers).await
}
/// Fallible method that also adds the API token to headers or query if one is configured.
///
/// Prefer [`Self::get_request_with_query`] for most use cases; use this when you need
/// access to the raw token-injection logic.
pub(crate) async fn get_request_with_query_result(
&self,
path: &str,
params: Query,
headers: Option<HeaderMap>,
) -> Result<Response, ClientError> {
let url = self.base_url(path)?;
match &self.connection_info.api_token {
Some(token) => {
let headers = if let Some(headers) = headers {
// Headers provided -> add auth token if not already present
if headers.get(header::AUTHORIZATION).is_some() {
// Auth token already present -> use provided
headers
} else {
let mut headers = headers;
headers.insert(
header::AUTHORIZATION,
format!("{AUTH_BEARER_TOKEN_HEADER_PREFIX} {token}")
.parse()
.expect("the auth token is not a valid header value"),
);
headers
}
} else {
// No headers provided -> create headers with auth token
let mut headers = HeaderMap::new();
headers.insert(
header::AUTHORIZATION,
format!("{AUTH_BEARER_TOKEN_HEADER_PREFIX} {token}")
.parse()
.expect("the auth token is not a valid header value"),
);
headers
};
get_result(url, Some(params), Some(headers)).await
}
None => get_result(url, Some(params), headers).await,
}
}
/// # Errors
///
/// Will return an error if the request can't be sent.
pub async fn get_request(&self, path: &str) -> Result<Response, ClientError> {
let url = self.base_url(path)?;
get_result(url, None, None).await
}
fn base_url(&self, path: &str) -> Result<Url, ClientError> {
Url::parse(&format!("{}{}{path}", self.connection_info.origin, self.base_path))
.map_err(|e| ClientError::InternalError(format!("invalid URL: {e}")))
}
}
/// # Errors
///
/// Will return an error if the request can't be sent.
pub async fn get(path: Url, query: Option<Query>, headers: Option<HeaderMap>) -> Result<Response, ClientError> {
get_result(path, query, headers).await
}
/// Fallible free function that builds its own `reqwest::Client`.
///
/// Prefer the methods on [`ApiHttpClient`] when you already have a client instance;
/// use this free function for one-shot requests where creating a full client is
/// unnecessary.
pub(crate) async fn get_result(path: Url, query: Option<Query>, headers: Option<HeaderMap>) -> Result<Response, ClientError> {
let client = reqwest::Client::builder()
.timeout(Duration::from_secs(DEFAULT_REQUEST_TIMEOUT_IN_SECS))
.build()?;
let mut request_builder = client.get(path);
if let Some(params) = query {
request_builder = request_builder.query(&ReqwestQuery::from(params));
}
if let Some(headers) = headers {
request_builder = request_builder.headers(headers);
}
request_builder.send().await.map_err(ClientError::TransportError)
}
/// Returns a `HeaderMap` with a request id header.
///
/// # Panics
///
/// Will panic if the request ID can't be parsed into a `HeaderValue`.
#[must_use]
pub fn headers_with_request_id(request_id: Uuid) -> HeaderMap {
let mut headers = HeaderMap::new();
headers.insert(
"x-request-id",
request_id
.to_string()
.parse()
.expect("the request ID is not a valid header value"),
);
headers
}
/// Returns a `HeaderMap` with an authorization token.
///
/// # Panics
///
/// Will panic if the token can't be parsed into a `HeaderValue`.
#[must_use]
pub fn headers_with_auth_token(token: &str) -> HeaderMap {
let mut headers = HeaderMap::new();
headers.insert(
header::AUTHORIZATION,
format!("{AUTH_BEARER_TOKEN_HEADER_PREFIX} {token}")
.parse()
.expect("the auth token is not a valid header value"),
);
headers
}