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
627
628
629
630
631
632
633
634
635
636
637
638
use super::{
    error::{AskError, ExecAskError, FileAskError, TellError},
    file::RemoteFile,
    proc::RemoteProc,
    state::ClientState,
};
use crate::{
    event::{AddrEventManager, EventManager},
    msg::{content::*, Msg},
};
use log::{error, trace};
use over_there_utils::Either;
use std::net::SocketAddr;
use std::sync::Arc;
use std::time::Duration;
use tokio::{
    sync::{oneshot, Mutex},
    task::{JoinError, JoinHandle},
};

/// Represents a client after connecting to an endpoint
pub struct ConnectedClient {
    pub(super) state: Arc<Mutex<ClientState>>,

    /// Represents the event manager used to send and receive data
    pub(super) event_manager: Either<EventManager, AddrEventManager>,

    /// Represents the handle for processing events
    pub(super) event_handle: JoinHandle<()>,

    /// Represents the address the client is connected to
    pub(super) remote_addr: SocketAddr,

    /// Represents maximum to wait on responses before timing out
    pub timeout: Duration,
}

impl ConnectedClient {
    /// Default timeout applied to a new client for any ask made
    pub const DEFAULT_TIMEOUT: Duration = Duration::from_secs(5);

    pub fn remote_addr(&self) -> SocketAddr {
        self.remote_addr
    }

    pub async fn wait(self) -> Result<(), JoinError> {
        match self.event_manager {
            Either::Left(m) => {
                tokio::try_join!(m.wait(), self.event_handle).map(|_| ())
            }
            Either::Right(m) => {
                tokio::try_join!(m.wait(), self.event_handle).map(|_| ())
            }
        }
    }

    /// Generic ask of the server that is expecting a response
    pub async fn ask(&mut self, msg: Msg) -> Result<Msg, AskError> {
        let timeout = self.timeout;
        let (tx, rx) = oneshot::channel::<Result<Msg, AskError>>();

        // Assign a synchronous callback that uses the oneshot channel to
        // get back the result
        self.state.lock().await.callback_manager.add_callback(
            msg.header.id,
            |msg| {
                let result = if let Content::Error(args) = &msg.content {
                    tx.send(Err(AskError::Failure {
                        msg: args.msg.to_string(),
                    }))
                } else {
                    tx.send(Ok(msg.clone()))
                };

                if result.is_err() {
                    error!("Failed to trigger callback: {:?}", msg);
                }
            },
        );

        // Send the msg and report back an error if it occurs
        self.tell(msg).await.map_err(AskError::from)?;

        tokio::time::timeout(timeout, rx)
            .await
            .map_err(|_| AskError::Timeout)?
            .map_err(|_| AskError::CallbackLost)?
    }

    /// Sends a msg to the server, not expecting a response
    pub async fn tell(&mut self, msg: Msg) -> Result<(), TellError> {
        trace!("Sending to {}: {:?}", self.remote_addr, msg);

        let data = msg.to_vec().map_err(|_| TellError::EncodingFailed)?;
        match &mut self.event_manager {
            Either::Left(m) => {
                m.send(data).await.map_err(|_| TellError::SendFailed)
            }
            Either::Right(m) => m
                .send_to(data, self.remote_addr)
                .await
                .map_err(|_| TellError::SendFailed),
        }
    }

    /// Requests the version from the server
    pub async fn ask_version(&mut self) -> Result<VersionArgs, AskError> {
        let msg = self.ask(Msg::from(Content::DoGetVersion)).await?;
        match msg.content {
            Content::Version(args) => Ok(args),
            x => Err(make_ask_error(x)),
        }
    }

    /// Requests the capabilities from the server
    pub async fn ask_capabilities(
        &mut self,
    ) -> Result<CapabilitiesArgs, AskError> {
        let msg = self.ask(Msg::from(Content::DoGetCapabilities)).await?;
        match msg.content {
            Content::Capabilities(args) => Ok(args),
            x => Err(make_ask_error(x)),
        }
    }

    /// Requests to create a new directory
    pub async fn ask_create_dir(
        &mut self,
        path: String,
        include_components: bool,
    ) -> Result<DirCreatedArgs, FileAskError> {
        let result = self
            .ask(Msg::from(Content::DoCreateDir(DoCreateDirArgs {
                path,
                include_components,
            })))
            .await;

        if let Err(x) = result {
            return Err(From::from(x));
        }

        match result.unwrap().content {
            Content::DirCreated(args) => Ok(args),
            x => Err(make_file_ask_error(x)),
        }
    }

    /// Requests to rename an existing directory
    pub async fn ask_rename_dir(
        &mut self,
        from: String,
        to: String,
    ) -> Result<DirRenamedArgs, FileAskError> {
        let result = self
            .ask(Msg::from(Content::DoRenameDir(DoRenameDirArgs {
                from,
                to,
            })))
            .await;

        if let Err(x) = result {
            return Err(From::from(x));
        }

        match result.unwrap().content {
            Content::DirRenamed(args) => Ok(args),
            x => Err(make_file_ask_error(x)),
        }
    }

    /// Requests to remove an existing directory
    pub async fn ask_remove_dir(
        &mut self,
        path: String,
        non_empty: bool,
    ) -> Result<DirRemovedArgs, FileAskError> {
        let result = self
            .ask(Msg::from(Content::DoRemoveDir(DoRemoveDirArgs {
                path,
                non_empty,
            })))
            .await;

        if let Err(x) = result {
            return Err(From::from(x));
        }

        match result.unwrap().content {
            Content::DirRemoved(args) => Ok(args),
            x => Err(make_file_ask_error(x)),
        }
    }

    /// Requests to get a list of the root directory's contents on the server
    pub async fn ask_list_root_dir_contents(
        &mut self,
    ) -> Result<DirContentsListArgs, FileAskError> {
        self.ask_list_dir_contents(String::from(".")).await
    }

    /// Requests to get a list of a directory's contents on the server
    pub async fn ask_list_dir_contents(
        &mut self,
        path: String,
    ) -> Result<DirContentsListArgs, FileAskError> {
        let result = self
            .ask(Msg::from(Content::DoListDirContents(
                DoListDirContentsArgs { path },
            )))
            .await;

        if let Err(x) = result {
            return Err(From::from(x));
        }

        match result.unwrap().content {
            Content::DirContentsList(args) => Ok(args),
            x => Err(make_file_ask_error(x)),
        }
    }

    /// Requests to open a file for reading/writing on the server,
    /// creating the file if it does not exist
    pub async fn ask_open_file(
        &mut self,
        path: String,
    ) -> Result<FileOpenedArgs, FileAskError> {
        self.ask_open_file_with_options(path, true, true, true)
            .await
    }

    /// Requests to open a file on the server, opening using the provided options
    pub async fn ask_open_file_with_options(
        &mut self,
        path: String,
        create: bool,
        write: bool,
        read: bool,
    ) -> Result<FileOpenedArgs, FileAskError> {
        let result = self
            .ask(Msg::from(Content::DoOpenFile(DoOpenFileArgs {
                path: path.clone(),
                create_if_missing: create,
                write_access: write,
                read_access: read,
            })))
            .await;

        if let Err(x) = result {
            return Err(From::from(x));
        }

        match result.unwrap().content {
            Content::FileOpened(args) => Ok(args),
            x => Err(make_file_ask_error(x)),
        }
    }

    /// Requests to close an open file
    pub async fn ask_close_file(
        &mut self,
        file: &RemoteFile,
    ) -> Result<FileClosedArgs, FileAskError> {
        let result = self
            .ask(Msg::from(Content::DoCloseFile(DoCloseFileArgs {
                id: file.id,
                sig: file.sig,
            })))
            .await;

        if let Err(x) = result {
            return Err(From::from(x));
        }

        match result.unwrap().content {
            Content::FileClosed(args) => Ok(args),
            x => Err(make_file_ask_error(x)),
        }
    }

    /// Requests to rename an open file
    pub async fn ask_rename_file(
        &mut self,
        file: &mut RemoteFile,
        to: String,
    ) -> Result<FileRenamedArgs, FileAskError> {
        let result = self
            .ask(Msg::from(Content::DoRenameFile(DoRenameFileArgs {
                id: file.id,
                sig: file.sig,
                to,
            })))
            .await;

        if let Err(x) = result {
            return Err(From::from(x));
        }

        match result.unwrap().content {
            Content::FileRenamed(args) => {
                file.sig = args.sig;
                Ok(args)
            }
            x => Err(make_file_ask_error(x)),
        }
    }

    /// Requests to rename a non-open file
    pub async fn ask_rename_unopened_file(
        &mut self,
        from: String,
        to: String,
    ) -> Result<UnopenedFileRenamedArgs, FileAskError> {
        let result = self
            .ask(Msg::from(Content::DoRenameUnopenedFile(
                DoRenameUnopenedFileArgs { from, to },
            )))
            .await;

        if let Err(x) = result {
            return Err(From::from(x));
        }

        match result.unwrap().content {
            Content::UnopenedFileRenamed(args) => Ok(args),
            x => Err(make_file_ask_error(x)),
        }
    }

    /// Requests to remove an open file
    pub async fn ask_remove_file(
        &mut self,
        file: &mut RemoteFile,
    ) -> Result<FileRemovedArgs, FileAskError> {
        let result = self
            .ask(Msg::from(Content::DoRemoveFile(DoRemoveFileArgs {
                id: file.id,
                sig: file.sig,
            })))
            .await;

        if let Err(x) = result {
            return Err(From::from(x));
        }

        match result.unwrap().content {
            Content::FileRemoved(args) => {
                file.sig = args.sig;
                Ok(args)
            }
            x => Err(make_file_ask_error(x)),
        }
    }

    /// Requests to remove a non-open file
    pub async fn ask_remove_unopened_file(
        &mut self,
        path: String,
    ) -> Result<UnopenedFileRemovedArgs, FileAskError> {
        let result = self
            .ask(Msg::from(Content::DoRemoveUnopenedFile(
                DoRemoveUnopenedFileArgs { path },
            )))
            .await;

        if let Err(x) = result {
            return Err(From::from(x));
        }

        match result.unwrap().content {
            Content::UnopenedFileRemoved(args) => Ok(args),
            x => Err(make_file_ask_error(x)),
        }
    }

    /// Requests the full contents of a file on the server
    pub async fn ask_read_file(
        &mut self,
        file: &RemoteFile,
    ) -> Result<FileContentsArgs, FileAskError> {
        let result = self
            .ask(Msg::from(Content::DoReadFile(DoReadFileArgs {
                id: file.id,
                sig: file.sig,
            })))
            .await;

        if let Err(x) = result {
            return Err(From::from(x));
        }

        match result.unwrap().content {
            Content::FileContents(args) => Ok(args),
            x => Err(make_file_ask_error(x)),
        }
    }

    /// Requests to write the contents of a file on the server
    pub async fn ask_write_file(
        &mut self,
        file: &mut RemoteFile,
        contents: &[u8],
    ) -> Result<FileWrittenArgs, FileAskError> {
        let result = self
            .ask(Msg::from(Content::DoWriteFile(DoWriteFileArgs {
                id: file.id,
                sig: file.sig,
                contents: contents.to_vec(),
            })))
            .await;

        if let Err(x) = result {
            return Err(From::from(x));
        }

        match result.unwrap().content {
            Content::FileWritten(args) => {
                file.sig = args.sig;
                Ok(args)
            }
            x => Err(make_file_ask_error(x)),
        }
    }

    /// Requests to execute a process on the server, providing support to
    /// send lines of text via stdin and reading back lines of text via
    /// stdout and stderr
    pub async fn ask_exec_proc(
        &mut self,
        command: String,
        args: Vec<String>,
    ) -> Result<ProcStartedArgs, ExecAskError> {
        self.ask_exec_proc_with_options(command, args, true, true, true, None)
            .await
    }

    /// Requests to execute a process on the server, providing support to
    /// send lines of text via stdin and reading back lines of text via
    /// stdout and stderr
    pub async fn ask_exec_proc_with_current_dir(
        &mut self,
        command: String,
        args: Vec<String>,
        current_dir: String,
    ) -> Result<ProcStartedArgs, ExecAskError> {
        self.ask_exec_proc_with_options(
            command,
            args,
            true,
            true,
            true,
            Some(current_dir),
        )
        .await
    }

    /// Requests to execute a process on the server, indicating whether to
    /// ignore or use stdin, stdout, and stderr
    pub async fn ask_exec_proc_with_options(
        &mut self,
        command: String,
        args: Vec<String>,
        stdin: bool,
        stdout: bool,
        stderr: bool,
        current_dir: Option<String>,
    ) -> Result<ProcStartedArgs, ExecAskError> {
        let result = self
            .ask(Msg::from(Content::DoExecProc(DoExecProcArgs {
                command,
                args,
                stdin,
                stdout,
                stderr,
                current_dir,
            })))
            .await;

        if let Err(x) = result {
            return Err(From::from(x));
        }

        match result.unwrap().content {
            Content::ProcStarted(args) => Ok(args),
            x => Err(make_exec_ask_error(x)),
        }
    }

    /// Requests to send lines of text to stdin of a remote process on the server
    pub async fn ask_write_stdin(
        &mut self,
        proc: &RemoteProc,
        input: &[u8],
    ) -> Result<StdinWrittenArgs, ExecAskError> {
        let result = self
            .ask(Msg::from(Content::DoWriteStdin(DoWriteStdinArgs {
                id: proc.id,
                input: input.to_vec(),
            })))
            .await;

        if let Err(x) = result {
            return Err(From::from(x));
        }

        match result.unwrap().content {
            Content::StdinWritten(args) => Ok(args),
            x => Err(make_exec_ask_error(x)),
        }
    }

    /// Requests to get all stdout from a remote process on the server since
    /// the last ask was made
    pub async fn ask_get_stdout(
        &mut self,
        proc: &RemoteProc,
    ) -> Result<StdoutContentsArgs, ExecAskError> {
        let result = self
            .ask(Msg::from(Content::DoGetStdout(DoGetStdoutArgs {
                id: proc.id,
            })))
            .await;

        if let Err(x) = result {
            return Err(From::from(x));
        }

        match result.unwrap().content {
            Content::StdoutContents(args) => Ok(args),
            x => Err(make_exec_ask_error(x)),
        }
    }

    /// Requests to get all stderr from a remote process on the server since
    /// the last ask was made
    pub async fn ask_get_stderr(
        &mut self,
        proc: &RemoteProc,
    ) -> Result<StderrContentsArgs, ExecAskError> {
        let result = self
            .ask(Msg::from(Content::DoGetStderr(DoGetStderrArgs {
                id: proc.id,
            })))
            .await;

        if let Err(x) = result {
            return Err(From::from(x));
        }

        match result.unwrap().content {
            Content::StderrContents(args) => Ok(args),
            x => Err(make_exec_ask_error(x)),
        }
    }

    /// Requests to kill a remote process on the server
    pub async fn ask_proc_status(
        &mut self,
        proc: &RemoteProc,
    ) -> Result<ProcStatusArgs, ExecAskError> {
        let result = self
            .ask(Msg::from(Content::DoGetProcStatus(DoGetProcStatusArgs {
                id: proc.id,
            })))
            .await;

        if let Err(x) = result {
            return Err(From::from(x));
        }

        match result.unwrap().content {
            Content::ProcStatus(args) => Ok(args),
            x => Err(make_exec_ask_error(x)),
        }
    }

    /// Requests to kill a remote process on the server
    pub async fn ask_proc_kill(
        &mut self,
        proc: &RemoteProc,
    ) -> Result<ProcStatusArgs, ExecAskError> {
        let result = self
            .ask(Msg::from(Content::DoKillProc(DoKillProcArgs {
                id: proc.id,
            })))
            .await;

        if let Err(x) = result {
            return Err(From::from(x));
        }

        match result.unwrap().content {
            Content::ProcStatus(args) if args.is_alive => {
                Err(ExecAskError::FailedToKill)
            }
            Content::ProcStatus(args) => Ok(args),
            x => Err(make_exec_ask_error(x)),
        }
    }

    /// Requests internal state of server
    pub async fn ask_internal_debug(
        &mut self,
    ) -> Result<InternalDebugArgs, AskError> {
        let result = self
            .ask(Msg::from(Content::InternalDebug(InternalDebugArgs {
                input: vec![],
                output: vec![],
            })))
            .await?;

        match result.content {
            Content::InternalDebug(args) => Ok(args),
            x => Err(make_ask_error(x)),
        }
    }
}

fn make_file_ask_error(x: Content) -> FileAskError {
    match x {
        Content::IoError(args) => FileAskError::IoError(args.into()),
        x => From::from(make_ask_error(x)),
    }
}

fn make_exec_ask_error(x: Content) -> ExecAskError {
    match x {
        Content::IoError(args) => ExecAskError::IoError(args.into()),
        x => From::from(make_ask_error(x)),
    }
}

fn make_ask_error(x: Content) -> AskError {
    match x {
        content => AskError::InvalidResponse { content },
    }
}