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
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
use crate::{
    client::Client,
    common::{
        authentication::{
            msg::{Authentication, AuthenticationResponse},
            AuthHandler,
        },
        ConnectionId, Destination, Map, Request,
    },
    manager::data::{
        ConnectionInfo, ConnectionList, ManagerCapabilities, ManagerRequest, ManagerResponse,
    },
};
use log::*;
use std::io;

mod channel;
pub use channel::*;

/// Represents a client that can connect to a remote server manager.
pub type ManagerClient = Client<ManagerRequest, ManagerResponse>;

impl ManagerClient {
    /// Request that the manager launches a new server at the given `destination` with `options`
    /// being passed for destination-specific details, returning the new `destination` of the
    /// spawned server.
    ///
    ///  The provided `handler` will be used for any authentication requirements when connecting to
    ///  the remote machine to spawn the server.
    pub async fn launch(
        &mut self,
        destination: impl Into<Destination>,
        options: impl Into<Map>,
        mut handler: impl AuthHandler + Send,
    ) -> io::Result<Destination> {
        let destination = Box::new(destination.into());
        let options = options.into();
        trace!("launch({}, {})", destination, options);

        let mut mailbox = self
            .mail(ManagerRequest::Launch {
                destination: destination.clone(),
                options,
            })
            .await?;

        // Continue to process authentication challenges and other details until we are either
        // launched or fail
        while let Some(res) = mailbox.next().await {
            match res.payload {
                ManagerResponse::Authenticate { id, msg } => match msg {
                    Authentication::Initialization(x) => {
                        if log::log_enabled!(Level::Debug) {
                            debug!(
                                "Initializing authentication, supporting {}",
                                x.methods
                                    .iter()
                                    .map(ToOwned::to_owned)
                                    .collect::<Vec<_>>()
                                    .join(",")
                            );
                        }
                        let msg = AuthenticationResponse::Initialization(
                            handler.on_initialization(x).await?,
                        );
                        self.fire(Request::new(ManagerRequest::Authenticate { id, msg }))
                            .await?;
                    }
                    Authentication::StartMethod(x) => {
                        debug!("Starting authentication method {}", x.method);
                    }
                    Authentication::Challenge(x) => {
                        if log::log_enabled!(Level::Debug) {
                            for question in x.questions.iter() {
                                debug!(
                                    "Received challenge question [{}]: {}",
                                    question.label, question.text
                                );
                            }
                        }
                        let msg = AuthenticationResponse::Challenge(handler.on_challenge(x).await?);
                        self.fire(Request::new(ManagerRequest::Authenticate { id, msg }))
                            .await?;
                    }
                    Authentication::Verification(x) => {
                        debug!("Received verification request {}: {}", x.kind, x.text);
                        let msg =
                            AuthenticationResponse::Verification(handler.on_verification(x).await?);
                        self.fire(Request::new(ManagerRequest::Authenticate { id, msg }))
                            .await?;
                    }
                    Authentication::Info(x) => {
                        info!("{}", x.text);
                    }
                    Authentication::Error(x) => {
                        error!("{}", x.text);
                        if x.is_fatal() {
                            return Err(x.into_io_permission_denied());
                        }
                    }
                    Authentication::Finished => {
                        debug!("Finished authentication for {destination}");
                    }
                },
                ManagerResponse::Launched { destination } => return Ok(destination),
                ManagerResponse::Error { description } => {
                    return Err(io::Error::new(io::ErrorKind::Other, description))
                }
                x => {
                    return Err(io::Error::new(
                        io::ErrorKind::InvalidData,
                        format!("Got unexpected response: {:?}", x),
                    ))
                }
            }
        }

        Err(io::Error::new(
            io::ErrorKind::UnexpectedEof,
            "Missing connection confirmation",
        ))
    }

    /// Request that the manager establishes a new connection at the given `destination`
    /// with `options` being passed for destination-specific details.
    ///
    /// The provided `handler` will be used for any authentication requirements when connecting to
    /// the server.
    pub async fn connect(
        &mut self,
        destination: impl Into<Destination>,
        options: impl Into<Map>,
        mut handler: impl AuthHandler + Send,
    ) -> io::Result<ConnectionId> {
        let destination = Box::new(destination.into());
        let options = options.into();
        trace!("connect({}, {})", destination, options);

        let mut mailbox = self
            .mail(ManagerRequest::Connect {
                destination: destination.clone(),
                options,
            })
            .await?;

        // Continue to process authentication challenges and other details until we are either
        // connected or fail
        while let Some(res) = mailbox.next().await {
            match res.payload {
                ManagerResponse::Authenticate { id, msg } => match msg {
                    Authentication::Initialization(x) => {
                        if log::log_enabled!(Level::Debug) {
                            debug!(
                                "Initializing authentication, supporting {}",
                                x.methods
                                    .iter()
                                    .map(ToOwned::to_owned)
                                    .collect::<Vec<_>>()
                                    .join(",")
                            );
                        }
                        let msg = AuthenticationResponse::Initialization(
                            handler.on_initialization(x).await?,
                        );
                        self.fire(Request::new(ManagerRequest::Authenticate { id, msg }))
                            .await?;
                    }
                    Authentication::StartMethod(x) => {
                        debug!("Starting authentication method {}", x.method);
                    }
                    Authentication::Challenge(x) => {
                        if log::log_enabled!(Level::Debug) {
                            for question in x.questions.iter() {
                                debug!(
                                    "Received challenge question [{}]: {}",
                                    question.label, question.text
                                );
                            }
                        }
                        let msg = AuthenticationResponse::Challenge(handler.on_challenge(x).await?);
                        self.fire(Request::new(ManagerRequest::Authenticate { id, msg }))
                            .await?;
                    }
                    Authentication::Verification(x) => {
                        debug!("Received verification request {}: {}", x.kind, x.text);
                        let msg =
                            AuthenticationResponse::Verification(handler.on_verification(x).await?);
                        self.fire(Request::new(ManagerRequest::Authenticate { id, msg }))
                            .await?;
                    }
                    Authentication::Info(x) => {
                        info!("{}", x.text);
                    }
                    Authentication::Error(x) => {
                        error!("{}", x.text);
                        if x.is_fatal() {
                            return Err(x.into_io_permission_denied());
                        }
                    }
                    Authentication::Finished => {
                        debug!("Finished authentication for {destination}");
                    }
                },
                ManagerResponse::Connected { id } => return Ok(id),
                ManagerResponse::Error { description } => {
                    return Err(io::Error::new(io::ErrorKind::Other, description))
                }
                x => {
                    return Err(io::Error::new(
                        io::ErrorKind::InvalidData,
                        format!("Got unexpected response: {:?}", x),
                    ))
                }
            }
        }

        Err(io::Error::new(
            io::ErrorKind::UnexpectedEof,
            "Missing connection confirmation",
        ))
    }

    /// Establishes a channel with the server represented by the `connection_id`,
    /// returning a [`RawChannel`] acting as the connection.
    ///
    /// ### Note
    ///
    /// Multiple calls to open a channel against the same connection will result in establishing a
    /// duplicate channel to the same server, so take care when using this method.
    pub async fn open_raw_channel(
        &mut self,
        connection_id: ConnectionId,
    ) -> io::Result<RawChannel> {
        trace!("open_raw_channel({})", connection_id);
        RawChannel::spawn(connection_id, self).await
    }

    /// Retrieves a list of supported capabilities
    pub async fn capabilities(&mut self) -> io::Result<ManagerCapabilities> {
        trace!("capabilities()");
        let res = self.send(ManagerRequest::Capabilities).await?;
        match res.payload {
            ManagerResponse::Capabilities { supported } => Ok(supported),
            ManagerResponse::Error { description } => {
                Err(io::Error::new(io::ErrorKind::Other, description))
            }
            x => Err(io::Error::new(
                io::ErrorKind::InvalidData,
                format!("Got unexpected response: {:?}", x),
            )),
        }
    }

    /// Retrieves information about a specific connection
    pub async fn info(&mut self, id: ConnectionId) -> io::Result<ConnectionInfo> {
        trace!("info({})", id);
        let res = self.send(ManagerRequest::Info { id }).await?;
        match res.payload {
            ManagerResponse::Info(info) => Ok(info),
            ManagerResponse::Error { description } => {
                Err(io::Error::new(io::ErrorKind::Other, description))
            }
            x => Err(io::Error::new(
                io::ErrorKind::InvalidData,
                format!("Got unexpected response: {:?}", x),
            )),
        }
    }

    /// Kills the specified connection
    pub async fn kill(&mut self, id: ConnectionId) -> io::Result<()> {
        trace!("kill({})", id);
        let res = self.send(ManagerRequest::Kill { id }).await?;
        match res.payload {
            ManagerResponse::Killed => Ok(()),
            ManagerResponse::Error { description } => {
                Err(io::Error::new(io::ErrorKind::Other, description))
            }
            x => Err(io::Error::new(
                io::ErrorKind::InvalidData,
                format!("Got unexpected response: {:?}", x),
            )),
        }
    }

    /// Retrieves a list of active connections
    pub async fn list(&mut self) -> io::Result<ConnectionList> {
        trace!("list()");
        let res = self.send(ManagerRequest::List).await?;
        match res.payload {
            ManagerResponse::List(list) => Ok(list),
            ManagerResponse::Error { description } => {
                Err(io::Error::new(io::ErrorKind::Other, description))
            }
            x => Err(io::Error::new(
                io::ErrorKind::InvalidData,
                format!("Got unexpected response: {:?}", x),
            )),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::client::{ReconnectStrategy, UntypedClient};
    use crate::common::authentication::DummyAuthHandler;
    use crate::common::{Connection, InmemoryTransport, Request, Response};

    fn setup() -> (ManagerClient, Connection<InmemoryTransport>) {
        let (client, server) = Connection::pair(100);
        let client = UntypedClient::spawn(client, ReconnectStrategy::Fail).into_typed_client();
        (client, server)
    }

    #[inline]
    fn test_error() -> io::Error {
        io::Error::new(io::ErrorKind::Interrupted, "test error")
    }

    #[inline]
    fn test_error_response() -> ManagerResponse {
        ManagerResponse::from(test_error())
    }

    #[tokio::test]
    async fn connect_should_report_error_if_receives_error_response() {
        let (mut client, mut transport) = setup();

        tokio::spawn(async move {
            let request = transport
                .read_frame_as::<Request<ManagerRequest>>()
                .await
                .unwrap()
                .unwrap();

            transport
                .write_frame_for(&Response::new(request.id, test_error_response()))
                .await
                .unwrap();
        });

        let err = client
            .connect(
                "scheme://host".parse::<Destination>().unwrap(),
                "key=value".parse::<Map>().unwrap(),
                DummyAuthHandler,
            )
            .await
            .unwrap_err();
        assert_eq!(err.kind(), io::ErrorKind::Other);
        assert_eq!(err.to_string(), test_error().to_string());
    }

    #[tokio::test]
    async fn connect_should_report_error_if_receives_unexpected_response() {
        let (mut client, mut transport) = setup();

        tokio::spawn(async move {
            let request = transport
                .read_frame_as::<Request<ManagerRequest>>()
                .await
                .unwrap()
                .unwrap();

            transport
                .write_frame_for(&Response::new(request.id, ManagerResponse::Killed))
                .await
                .unwrap();
        });

        let err = client
            .connect(
                "scheme://host".parse::<Destination>().unwrap(),
                "key=value".parse::<Map>().unwrap(),
                DummyAuthHandler,
            )
            .await
            .unwrap_err();
        assert_eq!(err.kind(), io::ErrorKind::InvalidData);
    }

    #[tokio::test]
    async fn connect_should_return_id_from_successful_response() {
        let (mut client, mut transport) = setup();

        let expected_id = 999;
        tokio::spawn(async move {
            let request = transport
                .read_frame_as::<Request<ManagerRequest>>()
                .await
                .unwrap()
                .unwrap();

            transport
                .write_frame_for(&Response::new(
                    request.id,
                    ManagerResponse::Connected { id: expected_id },
                ))
                .await
                .unwrap();
        });

        let id = client
            .connect(
                "scheme://host".parse::<Destination>().unwrap(),
                "key=value".parse::<Map>().unwrap(),
                DummyAuthHandler,
            )
            .await
            .unwrap();
        assert_eq!(id, expected_id);
    }

    #[tokio::test]
    async fn info_should_report_error_if_receives_error_response() {
        let (mut client, mut transport) = setup();

        tokio::spawn(async move {
            let request = transport
                .read_frame_as::<Request<ManagerRequest>>()
                .await
                .unwrap()
                .unwrap();

            transport
                .write_frame_for(&Response::new(request.id, test_error_response()))
                .await
                .unwrap();
        });

        let err = client.info(123).await.unwrap_err();
        assert_eq!(err.kind(), io::ErrorKind::Other);
        assert_eq!(err.to_string(), test_error().to_string());
    }

    #[tokio::test]
    async fn info_should_report_error_if_receives_unexpected_response() {
        let (mut client, mut transport) = setup();

        tokio::spawn(async move {
            let request = transport
                .read_frame_as::<Request<ManagerRequest>>()
                .await
                .unwrap()
                .unwrap();

            transport
                .write_frame_for(&Response::new(request.id, ManagerResponse::Killed))
                .await
                .unwrap();
        });

        let err = client.info(123).await.unwrap_err();
        assert_eq!(err.kind(), io::ErrorKind::InvalidData);
    }

    #[tokio::test]
    async fn info_should_return_connection_info_from_successful_response() {
        let (mut client, mut transport) = setup();

        tokio::spawn(async move {
            let request = transport
                .read_frame_as::<Request<ManagerRequest>>()
                .await
                .unwrap()
                .unwrap();

            let info = ConnectionInfo {
                id: 123,
                destination: "scheme://host".parse::<Destination>().unwrap(),
                options: "key=value".parse::<Map>().unwrap(),
            };

            transport
                .write_frame_for(&Response::new(request.id, ManagerResponse::Info(info)))
                .await
                .unwrap();
        });

        let info = client.info(123).await.unwrap();
        assert_eq!(info.id, 123);
        assert_eq!(
            info.destination,
            "scheme://host".parse::<Destination>().unwrap()
        );
        assert_eq!(info.options, "key=value".parse::<Map>().unwrap());
    }

    #[tokio::test]
    async fn list_should_report_error_if_receives_error_response() {
        let (mut client, mut transport) = setup();

        tokio::spawn(async move {
            let request = transport
                .read_frame_as::<Request<ManagerRequest>>()
                .await
                .unwrap()
                .unwrap();

            transport
                .write_frame_for(&Response::new(request.id, test_error_response()))
                .await
                .unwrap();
        });

        let err = client.list().await.unwrap_err();
        assert_eq!(err.kind(), io::ErrorKind::Other);
        assert_eq!(err.to_string(), test_error().to_string());
    }

    #[tokio::test]
    async fn list_should_report_error_if_receives_unexpected_response() {
        let (mut client, mut transport) = setup();

        tokio::spawn(async move {
            let request = transport
                .read_frame_as::<Request<ManagerRequest>>()
                .await
                .unwrap()
                .unwrap();

            transport
                .write_frame_for(&Response::new(request.id, ManagerResponse::Killed))
                .await
                .unwrap();
        });

        let err = client.list().await.unwrap_err();
        assert_eq!(err.kind(), io::ErrorKind::InvalidData);
    }

    #[tokio::test]
    async fn list_should_return_connection_list_from_successful_response() {
        let (mut client, mut transport) = setup();

        tokio::spawn(async move {
            let request = transport
                .read_frame_as::<Request<ManagerRequest>>()
                .await
                .unwrap()
                .unwrap();

            let mut list = ConnectionList::new();
            list.insert(123, "scheme://host".parse::<Destination>().unwrap());

            transport
                .write_frame_for(&Response::new(request.id, ManagerResponse::List(list)))
                .await
                .unwrap();
        });

        let list = client.list().await.unwrap();
        assert_eq!(list.len(), 1);
        assert_eq!(
            list.get(&123).expect("Connection list missing item"),
            &"scheme://host".parse::<Destination>().unwrap()
        );
    }

    #[tokio::test]
    async fn kill_should_report_error_if_receives_error_response() {
        let (mut client, mut transport) = setup();

        tokio::spawn(async move {
            let request = transport
                .read_frame_as::<Request<ManagerRequest>>()
                .await
                .unwrap()
                .unwrap();

            transport
                .write_frame_for(&Response::new(request.id, test_error_response()))
                .await
                .unwrap();
        });

        let err = client.kill(123).await.unwrap_err();
        assert_eq!(err.kind(), io::ErrorKind::Other);
        assert_eq!(err.to_string(), test_error().to_string());
    }

    #[tokio::test]
    async fn kill_should_report_error_if_receives_unexpected_response() {
        let (mut client, mut transport) = setup();

        tokio::spawn(async move {
            let request = transport
                .read_frame_as::<Request<ManagerRequest>>()
                .await
                .unwrap()
                .unwrap();

            transport
                .write_frame_for(&Response::new(
                    request.id,
                    ManagerResponse::Connected { id: 0 },
                ))
                .await
                .unwrap();
        });

        let err = client.kill(123).await.unwrap_err();
        assert_eq!(err.kind(), io::ErrorKind::InvalidData);
    }

    #[tokio::test]
    async fn kill_should_return_success_from_successful_response() {
        let (mut client, mut transport) = setup();

        tokio::spawn(async move {
            let request = transport
                .read_frame_as::<Request<ManagerRequest>>()
                .await
                .unwrap()
                .unwrap();

            transport
                .write_frame_for(&Response::new(request.id, ManagerResponse::Killed))
                .await
                .unwrap();
        });

        client.kill(123).await.unwrap();
    }
}