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
//  CLIENT.rs
//    by Lut99
//
//  Created:
//    25 Nov 2022, 15:09:17
//  Last edited:
//    15 Jan 2024, 15:16:14
//  Auto updated?
//    Yes
//
//  Description:
//!   Provides client code for the `brane-prx` service. In particular,
//!   offers functionality for generating new paths.
//

use std::collections::HashMap;
use std::str::FromStr;
use std::sync::{RwLock, RwLockReadGuard, RwLockWriteGuard};

use log::{debug, info};
use reqwest::{Client, Request, Response};
use serde::Serialize;
use specifications::address::Address;
use specifications::package::PackageIndex;
use specifications::working::{Error as JobServiceError, JobServiceClient};
use url::Url;

pub use crate::errors::ClientError as Error;
use crate::spec::{NewPathRequest, NewPathRequestTlsOptions};


/***** HELPER FUNCTIONS *****/
/// Declares a new path in the proxy services.
///
/// # Arguments
/// - `endpoint`: The proxy service to connect to (hostname + address).
/// - `remote_address`: The remote address to connect to through the proxy.
/// - `tls`: If given, whether to use TLS and for what location.
///
/// # Returns
/// The port of the new path that is created.
///
/// # Errors
/// This function errors if we failed to create the port for whatever reason.
async fn create_path(endpoint: &Url, remote: impl Into<String>, tls: &Option<NewPathRequestTlsOptions>) -> Result<u16, Error> {
    let remote: String = remote.into();
    debug!("Creating path to '{}' on proxy service '{}'...", remote, endpoint);

    // Prepare the request
    let request: NewPathRequest = NewPathRequest { address: remote.clone(), tls: tls.clone() };

    // Send it with reqwest
    let address: String = format!("{endpoint}outgoing/new");
    let client: Client = Client::new();
    let req: Request = match client.post(&address).json(&request).build() {
        Ok(req) => req,
        Err(err) => {
            return Err(Error::RequestBuildError { address, err });
        },
    };
    debug!("Sending request '{}'...", req.url());
    let res: Response = match client.execute(req).await {
        Ok(res) => res,
        Err(err) => {
            return Err(Error::RequestError { address, err });
        },
    };
    if !res.status().is_success() {
        return Err(Error::RequestFailure { address, code: res.status(), err: res.text().await.ok() });
    }

    // Extract the port
    let port: String = match res.text().await {
        Ok(port) => port,
        Err(err) => {
            return Err(Error::RequestTextError { address, err });
        },
    };
    let port: u16 = match u16::from_str(&port) {
        Ok(port) => port,
        Err(err) => {
            return Err(Error::RequestPortParseError { address, raw: port, err });
        },
    };

    // Done
    Ok(port)
}





/***** LIBRARY *****/
/// Defines a ProxyClient, which remembers the paths stored and seamlessly translates between them.
#[derive(Debug)]
pub struct ProxyClient {
    /// The remote address of the endpoint.
    endpoint: Url,

    /// The map of remote addresses / paths that we have already used.
    paths: RwLock<HashMap<(String, Option<NewPathRequestTlsOptions>), u16>>,
}

impl ProxyClient {
    /// Constructor for the ProxyClient.
    ///
    /// Note that no connection is made yet; this is done lazily.
    ///
    /// # Arguments
    /// - `endpoint`: The remote proxy endpoint to connect to.
    ///
    /// # Returns
    /// A new ProxyClient instance.
    pub fn new(endpoint: impl AsRef<Address>) -> Self {
        let endpoint: &Address = endpoint.as_ref();

        // Parse the address as an endpoint
        let endpoint: Url =
            Url::from_str(&endpoint.to_string()).unwrap_or_else(|err| panic!("Cannot parse given address '{endpoint}' as a URL: {err}"));
        if endpoint.domain().is_none() {
            panic!("Given address '{endpoint}' does not have a domain");
        }

        // Return us
        Self { endpoint, paths: RwLock::new(HashMap::new()) }
    }

    /// Sends a GET-request to the given address/path.
    ///
    /// # Arguments
    /// - `address`: The address to send the request to.
    /// - `tls`: The TLS settings of the remote proxy to use for this request.
    ///
    /// # Returns
    /// The result of the request, as a `Result<reqwest::Response, reqwest::Error>`.
    ///
    /// # Errors
    /// This function errors if we fail to reserve any new paths if necessary.
    pub async fn get(&self, address: impl AsRef<str>, tls: Option<NewPathRequestTlsOptions>) -> Result<Result<Response, reqwest::Error>, Error> {
        let address: &str = address.as_ref();

        // Create a client
        let client: Client = Client::new();

        // Create a new GET-request with that client
        let request: Request = match client.get(address).build() {
            Ok(request) => request,
            Err(err) => {
                return Err(Error::RequestBuildError { address: address.into(), err });
            },
        };

        // Pass it onto `ProxyClient::execute()`
        self.execute(client, request, tls).await
    }

    /// Sends a GET-request with a JSON body to the given address/path.
    ///
    /// # Arguments
    /// - `address`: The address to send the request to.
    /// - `tls`: The TLS settings of the remote proxy to use for this request.
    /// - `body`: A [`Serialize`]able body to send along.
    ///
    /// # Returns
    /// The result of the request, as a `Result<reqwest::Response, reqwest::Error>`.
    ///
    /// # Errors
    /// This function errors if we fail to reserve any new paths if necessary.
    pub async fn get_with_body(
        &self,
        address: impl AsRef<str>,
        tls: Option<NewPathRequestTlsOptions>,
        body: &(impl ?Sized + Serialize),
    ) -> Result<Result<Response, reqwest::Error>, Error> {
        let address: &str = address.as_ref();

        // Create a client
        let client: Client = Client::new();

        // Create a new GET-request with that client
        let request: Request = match client.get(address).json(body).build() {
            Ok(request) => request,
            Err(err) => {
                return Err(Error::RequestBuildError { address: address.into(), err });
            },
        };

        // Pass it onto `ProxyClient::execute()`
        self.execute(client, request, tls).await
    }

    /// Sends the given `reqwest` request to the given address/path using the given client.
    ///
    /// # Arguments
    /// - `client`: The client to perform the actual request itself.
    /// - `request`: The request to send. Already carries the address to which we send it.
    /// - `tls`: The TLS settings to use for this request.
    ///
    /// # Returns
    /// The result of the request, as a `Result<reqwest::Response, reqwest::Error>`.
    ///
    /// # Errors
    /// This function errors if we fail to reserve any new paths if necessary.
    pub async fn execute(
        &self,
        client: Client,
        request: impl Into<Request>,
        tls: Option<NewPathRequestTlsOptions>,
    ) -> Result<Result<Response, reqwest::Error>, Error> {
        let mut request: Request = request.into();
        info!("Sending HTTP request to '{}' through proxy service at '{}'", request.url(), self.endpoint);

        // Assert it has the appropriate fields
        let url: &Url = request.url_mut();
        if url.domain().is_none() {
            panic!("URL {url} does not have a domain defined");
        }
        if url.port().is_none() {
            panic!("URL {url} does not have a port defined");
        }

        // Check if we already have a path for this
        let remote: String = format!("{}://{}:{}", url.scheme(), url.domain().unwrap(), url.port().unwrap());
        let port: Option<u16> = {
            let lock: RwLockReadGuard<HashMap<(String, Option<NewPathRequestTlsOptions>), u16>> = self.paths.read().unwrap();
            lock.get(&(remote.clone(), tls.clone())).cloned()
        };

        // If not, request one
        let port: u16 = match port {
            Some(port) => port,
            None => {
                // Create the path
                let port: u16 = create_path(&self.endpoint, &remote, &tls).await?;

                // Store it in the internal map for next time
                let mut lock: RwLockWriteGuard<HashMap<(String, Option<NewPathRequestTlsOptions>), u16>> = self.paths.write().unwrap();
                lock.insert((remote.clone(), tls.clone()), port);

                // And return the port
                port
            },
        };

        // Inject the new address into the request
        let url: Url = url.clone();
        if url.scheme() == "https" {
            // Replace with http, since the proxy will take care of TLS
            if request.url_mut().set_scheme("http").is_err() {
                return Err(Error::UrlSchemeUpdateError { url: request.url().clone(), scheme: "http".into() });
            }
        }
        if let Err(err) = request.url_mut().set_host(Some(self.endpoint.domain().unwrap())) {
            return Err(Error::UrlHostUpdateError { url: request.url().clone(), host: self.endpoint.domain().unwrap().into(), err });
        }
        if request.url_mut().set_port(Some(port)).is_err() {
            return Err(Error::UrlPortUpdateError { url: request.url().clone(), port });
        }

        // We can now perform the request
        debug!("Performing request to '{}' (secretly '{}')...", url, request.url());
        Ok(match client.execute(request).await {
            Ok(res) => Ok(res),
            Err(err) => {
                // If it fails, remove the mapping so we are forced to ask a new one next time
                let mut lock: RwLockWriteGuard<HashMap<(String, Option<NewPathRequestTlsOptions>), u16>> = self.paths.write().unwrap();
                lock.remove(&(remote, tls));
                Err(err)
            },
        })
    }

    /// Requests the package index from the `brane-api` service at the given endpoint.
    ///
    /// # Arguments
    /// - `address`: The endpoint (including path) to fetch the package index from.
    ///
    /// # Returns
    /// The result of the request, as a `Result<PackageIndex, brane_tsk::api::Error>`.
    ///
    /// # Errors
    /// This function errors if we fail to reserve any new paths if necessary.
    pub async fn get_package_index(&self, address: impl AsRef<str>) -> Result<Result<PackageIndex, brane_tsk::api::Error>, Error> {
        let address: &str = address.as_ref();

        // Parse the address as a URL
        let mut address: Url = match Url::from_str(address) {
            Ok(address) => address,
            Err(err) => {
                return Err(Error::IllegalUrl { raw: address.into(), err });
            },
        };
        // Assert it has the appropriate fields
        if address.domain().is_none() {
            panic!("URL {address} does not have a domain defined");
        }
        if address.port().is_none() {
            panic!("URL {address} does not have a port defined");
        }

        // Check if we already have a path for this
        let remote: String = format!("{}://{}:{}", address.scheme(), address.domain().unwrap(), address.port().unwrap());
        let port: Option<u16> = {
            let lock: RwLockReadGuard<HashMap<(String, Option<NewPathRequestTlsOptions>), u16>> = self.paths.read().unwrap();
            lock.get(&(remote.clone(), None)).cloned()
        };

        // If not, request one
        let port: u16 = match port {
            Some(port) => port,
            None => {
                // Create the path
                let port: u16 = create_path(&self.endpoint, &remote, &None).await?;

                // Store it in the internal map for next time
                let mut lock: RwLockWriteGuard<HashMap<(String, Option<NewPathRequestTlsOptions>), u16>> = self.paths.write().unwrap();
                lock.insert((remote.clone(), None), port);

                // And return the port
                port
            },
        };

        // Inject the new target in the URL
        let original: Url = address.clone();
        if let Err(err) = address.set_host(Some(self.endpoint.domain().unwrap())) {
            return Err(Error::UrlHostUpdateError { url: address, host: self.endpoint.domain().unwrap().into(), err });
        }
        if address.set_port(Some(port)).is_err() {
            return Err(Error::UrlPortUpdateError { url: address, port });
        }

        // Run the normal function
        debug!("Performing request to '{}' (secretly '{}')...", original, address);
        Ok(match brane_tsk::api::get_package_index(address).await {
            Ok(res) => Ok(res),
            Err(err) => {
                // If it fails, remove the mapping so we are forced to ask a new one next time
                let mut lock: RwLockWriteGuard<HashMap<(String, Option<NewPathRequestTlsOptions>), u16>> = self.paths.write().unwrap();
                lock.remove(&(remote, None));
                Err(err)
            },
        })
    }

    /// Connects to the given `brane-job` service using gRPC.
    ///
    /// This effectively creates a JobServiceClient, but through the proxy node.
    ///
    /// # Arguments
    /// - `address`: The address of the remote to connect to.
    ///
    /// # Returns
    /// The result of the connection, as a `Result<JobServiceClient, tonic::transport::Error>`.
    ///
    /// # Errors
    /// This function errors if we fail to reserve any new paths if necessary.
    pub async fn connect_to_job(&self, address: impl AsRef<str>) -> Result<Result<JobServiceClient, JobServiceError>, Error> {
        let address: &str = address.as_ref();

        // Parse the address as a URL
        let mut address: Url = match Url::from_str(address) {
            Ok(address) => address,
            Err(err) => {
                return Err(Error::IllegalUrl { raw: address.into(), err });
            },
        };
        // Assert it has the appropriate fields
        if address.domain().is_none() {
            panic!("URL {address} does not have a domain defined");
        }
        if address.port().is_none() {
            panic!("URL {address} does not have a port defined");
        }

        // Check if we already have a path for this
        let remote: String = format!("{}://{}:{}", address.scheme(), address.domain().unwrap(), address.port().unwrap());
        let port: Option<u16> = {
            let lock: RwLockReadGuard<HashMap<(String, Option<NewPathRequestTlsOptions>), u16>> = self.paths.read().unwrap();
            lock.get(&(remote.clone(), None)).cloned()
        };

        // If not, request one
        let port: u16 = match port {
            Some(port) => port,
            None => {
                // Create the path
                let port: u16 = create_path(&self.endpoint, &remote, &None).await?;

                // Store it in the internal map for next time
                let mut lock: RwLockWriteGuard<HashMap<(String, Option<NewPathRequestTlsOptions>), u16>> = self.paths.write().unwrap();
                lock.insert((remote.clone(), None), port);

                // And return the port
                port
            },
        };

        // Inject the new target in the URL
        let original: Url = address.clone();
        if let Err(err) = address.set_host(Some(self.endpoint.domain().unwrap())) {
            return Err(Error::UrlHostUpdateError { url: address, host: self.endpoint.domain().unwrap().into(), err });
        }
        if address.set_port(Some(port)).is_err() {
            return Err(Error::UrlPortUpdateError { url: address, port });
        }

        // We can now perform the request
        debug!("Connecting to '{}' (secretly '{}')...", original, address);
        Ok(match JobServiceClient::connect(address.to_string()).await {
            Ok(res) => Ok(res),
            Err(err) => {
                // If it fails, remove the mapping so we are forced to ask a new one next time
                let mut lock: RwLockWriteGuard<HashMap<(String, Option<NewPathRequestTlsOptions>), u16>> = self.paths.write().unwrap();
                lock.remove(&(remote, None));
                Err(err)
            },
        })
    }
}