nextcloud-client-api 0.1.0

implementation of the socket API for the NextCloud client
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
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
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
#![allow(
    clippy::blanket_clippy_restriction_lints,
    reason = "I can't allow this in the cargo.toml for some reason, so I add it here."
)]
//! This crate provides an API to the `NextCloud` linux client.
//! It connects to the socket of the client to interact.
//! The socket is located in the runtime directory, which is defined by the
//! `$XDG_RUNTIME_DIR` environment variable.
//! If this variable is not available, the creation will fail.
//!
//! The API is based on the source code published here: <https://github.com/nextcloud/desktop/blob/master/src/gui/socketapi/socketapi.h>
//!
//! # Examples
//! ```no_run
//! use std::path::Path;
//! use nextcloud_client_api::Api;
//!
//! let mut api = Api::new()
//!     .expect("failed to open API");
//! let version = api.version()
//!     .expect("failed to fetch version");
//! let file_status = api.retrieve_file_status(
//!         &Path::new("/Nextcloud/Documents/About-Storage-Share.pdf")
//!     ).expect("failed to retrieve file status");
//! ```
use core::{result::Result as StdResult, time::Duration};
use std::path::{Path, PathBuf};

use log::trace;
use thiserror::Error as ThisError;

use crate::{
    api_verb::ApiVerb,
    file_status::{Error as FileStatusError, FileStatus},
    menu_item::{Error as MenuItemError, MenuItem},
    message::Message,
    share_status::{Error as ShareStatusError, ShareStatus},
    socket::{Error as NextCloudClientSocketError, NextCloudClientSocket},
};

mod api_verb;
mod file_status;
mod menu_item;
mod message;
mod share_status;
mod socket;

/// Result of API interactions
pub type Result<T> = StdResult<T, Error>;

/// Extensive error codes for drill down
#[derive(Debug, ThisError)]
#[non_exhaustive]
pub enum Error {
    /// Failed to open the socket to `NextCloud` client.
    #[error("failed to open socket: {0}")]
    SocketFail(#[from] NextCloudClientSocketError),

    /// The path to operate with is not registered by the `NextCloud` client
    /// and therefore not shared or synced.
    #[error("requested path/file is not registered in NextCloud: {0}")]
    NotInRegister(PathBuf),

    /// The API did not respond to a request, but was expected to do so.
    #[error("no response")]
    NoResponse,

    /// Unknown file status has been responded.
    #[error("failed to parse file status: {0}")]
    ParsingFailedFileStatus(#[from] FileStatusError),

    /// Unknown share status has been responded.
    #[error("failed to parse share status: {0}")]
    ParsingFailedShareStatus(#[from] ShareStatusError),

    /// Unknown menu item has been responded.
    #[error("failed to parse menu item: {0}")]
    ParsingFailedMenuItem(#[from] MenuItemError),

    /// File can't be shared.
    #[error("file can't be shared due to missing options or the file is not in the correct path")]
    CannotShareFile,

    /// It is not allowed to share the root directory of your `NextCloud` account.
    #[error("you can't share the root of your account")]
    CannotShareRoot,

    /// The client is currently offline.
    #[error("the client is not connected to a backend")]
    NotConnected,

    /// The requested file is not synced yet, and therefore can't be shared with others.
    #[error("the file is not synced yet")]
    NotSynced,
}

/// interface object to interact with `NextCloud` client
pub struct Api {
    socket: NextCloudClientSocket,
    registered_paths: Vec<PathBuf>,
}

impl Api {
    /// `new` opens the socket to the `NextCloud` client.
    /// After the connect, the initial messages are received
    /// and processed. Those contain the registered directories
    /// in the `NextCloud` client.
    ///
    /// # Errors
    /// Will return errors if the socket can't be opened or there is a
    /// parsing issue with the initial messages.
    #[inline]
    pub fn new() -> Result<Self> {
        Api::build(NextCloudClientSocket::new()?)
    }

    #[cfg(test)]
    pub(crate) fn new_test(socket_file: &Path) -> Result<Self> {
        Api::build(NextCloudClientSocket::new_test(socket_file)?)
    }

    #[cfg_attr(
        not(test),
        expect(clippy::single_call_fn, reason = "abstraction for test mocks")
    )]
    fn build(socket: NextCloudClientSocket) -> Result<Self> {
        let mut result = Self {
            socket,
            registered_paths: Vec::new(),
        };

        let initial_messages = result.read_filtered_responses()?;
        for msg in initial_messages {
            trace!("initial: {msg}");
        }

        Ok(result)
    }

    fn read_filtered_responses(&mut self) -> Result<Vec<Message>> {
        let responses = self.socket.read_until_settled(Duration::from_millis(200))?;

        let (registered_paths, other): (Vec<Message>, Vec<Message>) = responses
            .into_iter()
            .inspect(|response| {
                trace!("received response: {response}");
            })
            .partition(|response| matches!(response.verb, ApiVerb::RegisterPath));

        self.registered_paths.extend(
            registered_paths
                .into_iter()
                .map(|path_response| PathBuf::from(path_response.msg)),
        );

        Ok(other)
    }

    /// `version` fetches the current version of the installed nextcloud-client.
    /// The returned value is as reported and not parsed in any format.
    ///
    /// # Errors
    /// Returns error if the request can't be transmitted to the client
    /// or if an unknown response is received.
    #[inline]
    pub fn version(&mut self) -> Result<String> {
        self.socket.write_message(&Message {
            verb: ApiVerb::Version,
            msg: String::default(),
        })?;

        let version = loop {
            let responses = self.read_filtered_responses()?;
            match responses.into_iter().find_map(|response| {
                (matches!(response.verb, ApiVerb::Version)).then_some(response.msg)
            }) {
                None => {}
                Some(version) => break version,
            }
        };

        trace!("version response: {version}");
        Ok(version)
    }

    /// `get_strings` reads the translation strings for context menu
    /// actions.
    /// The result is a vector of strings.
    /// The format is `<ACTION>:<Menu String>`.
    ///
    /// # Errors
    /// Returns error if the request can't be transmitted to the client
    /// or if an unknown response is received.
    #[inline]
    pub fn get_strings(&mut self) -> Result<Vec<String>> {
        self.socket.write_message(&Message {
            verb: ApiVerb::GetStrings,
            msg: String::default(),
        })?;

        Ok(self
            .read_filtered_responses()?
            .into_iter()
            .filter_map(|response| {
                trace!("string response: {}", response.msg);
                if matches!(response.msg.as_str(), "BEGIN" | "END") {
                    None
                } else {
                    Some(response.msg)
                }
            })
            .collect::<Vec<_>>())
    }

    /// `get_menu_items` reads the available actions for the file or folder.
    /// The result is a vector of menu items.
    ///
    /// # Errors
    /// Returns error if the request can't be transmitted to the client
    /// or if an unknown response is received.
    #[inline]
    pub fn get_menu_items(&mut self, path: &Path) -> Result<Vec<MenuItem>> {
        if !self
            .registered_paths
            .iter()
            .any(|registered_path| path.starts_with(registered_path))
        {
            return Err(Error::NotInRegister(path.to_path_buf()));
        }

        self.socket.write_message(&Message {
            verb: ApiVerb::GetMenuItems,
            msg: path.to_string_lossy().to_string(),
        })?;

        let result = self
            .read_filtered_responses()?
            .into_iter()
            .filter_map(|response| {
                trace!("menu item response: {}", response.msg);
                if matches!(response.msg.as_str(), "BEGIN" | "END") {
                    None
                } else {
                    Some(
                        MenuItem::try_from(response.msg.as_str())
                            .map_err(Error::ParsingFailedMenuItem),
                    )
                }
            })
            .collect::<Result<Vec<_>>>()?;

        Ok(result)
    }

    /// `retrieve_folder_status` checks the current state of a folder.
    /// If the folder is not part of the register, an error is returned.
    /// See the documentation of `FileStatus` for details.
    ///
    /// # Errors
    /// Returns error if the request can't be transmitted to the client
    /// or if an unknown response is received.
    #[inline]
    pub fn retrieve_folder_status(&mut self, path: &Path) -> Result<FileStatus> {
        if !self
            .registered_paths
            .iter()
            .any(|registered_path| path.starts_with(registered_path))
        {
            return Err(Error::NotInRegister(path.to_path_buf()));
        }

        self.socket.write_message(&Message {
            verb: ApiVerb::RetrieveFolderStatus,
            msg: path.to_string_lossy().to_string(),
        })?;

        let responses = self.read_filtered_responses()?;

        for response in responses {
            match response.msg.split_once(':') {
                Some((responded_status, responded_path)) if Path::new(responded_path) == path => {
                    let status = FileStatus::try_from(responded_status)?;
                    return Ok(status);
                }
                None | Some((_, _)) => continue,
            }
        }

        Err(Error::NoResponse)
    }

    /// `retrieve_file_status` checks the current state of a folder.
    /// If the folder is not part of the register, an error is returned.
    /// See the documentation of `FileStatus` for details.
    ///
    /// # Errors
    /// Returns error if the request can't be transmitted to the client
    /// or if an unknown response is received.
    #[inline]
    pub fn retrieve_file_status(&mut self, path: &Path) -> Result<FileStatus> {
        if !self
            .registered_paths
            .iter()
            .any(|registered_path| path.starts_with(registered_path))
        {
            return Err(Error::NotInRegister(path.to_path_buf()));
        }

        self.socket.write_message(&Message {
            verb: ApiVerb::RetrieveFileStatus,
            msg: path.to_string_lossy().to_string(),
        })?;

        let responses = self.read_filtered_responses()?;

        for response in responses {
            match response.msg.split_once(':') {
                Some((responded_status, responded_path)) if Path::new(responded_path) == path => {
                    let status = FileStatus::try_from(responded_status)?;
                    return Ok(status);
                }
                None | Some((_, _)) => continue,
            }
        }

        Err(Error::NoResponse)
    }

    /// `activity` displays the file-activity dialog.
    ///
    /// # Errors
    /// Returns error if the request can't be transmitted to the client
    /// or if an unknown response is received.
    #[inline]
    pub fn activity(&mut self, path: &Path) -> Result<()> {
        if !self
            .registered_paths
            .iter()
            .any(|registered_path| path.starts_with(registered_path))
        {
            return Err(Error::NotInRegister(path.to_path_buf()));
        }

        self.socket.write_message(&Message {
            verb: ApiVerb::Activity,
            msg: path.to_string_lossy().to_string(),
        })?;

        _ = self.read_filtered_responses()?;

        Ok(())
    }

    /// `share` opens the sharing dialog of the Nextcloud client
    /// if certain constraints are met.
    /// E.g. you can't share a file, which is not synced to the
    /// backend yet.
    ///
    /// # Errors
    /// Returns error if the request can't be transmitted to the client
    /// or if an unknown response is received.
    #[inline]
    pub fn share(&mut self, path: &Path) -> Result<()> {
        if !self
            .registered_paths
            .iter()
            .any(|registered_path| path.starts_with(registered_path))
        {
            return Err(Error::NotInRegister(path.to_path_buf()));
        }

        self.socket.write_message(&Message {
            verb: ApiVerb::Share,
            msg: path.to_string_lossy().to_string(),
        })?;

        let responses = self.read_filtered_responses()?;

        for response in responses {
            match response.msg.split_once(':') {
                Some((responded_status, responded_path)) if Path::new(responded_path) == path => {
                    let status = ShareStatus::try_from(responded_status)?;
                    return match status {
                        ShareStatus::Nop => Err(Error::CannotShareFile),
                        ShareStatus::NotConnected => Err(Error::NotConnected),
                        ShareStatus::NotSynced => Err(Error::NotSynced),
                        ShareStatus::CannotShareRoot => Err(Error::CannotShareRoot),
                        ShareStatus::Ok => Ok(()),
                    };
                }
                None | Some((_, _)) => continue,
            }
        }

        Err(Error::NoResponse)
    }

    /// `manage_public_links` opens the sharing dialog to manage
    /// active share links.
    ///
    /// # Errors
    /// Returns error if the request can't be transmitted to the client
    /// or if an unknown response is received.
    #[inline]
    pub fn manage_public_links(&mut self, path: &Path) -> Result<()> {
        if !self
            .registered_paths
            .iter()
            .any(|registered_path| path.starts_with(registered_path))
        {
            return Err(Error::NotInRegister(path.to_path_buf()));
        }

        self.socket.write_message(&Message {
            verb: ApiVerb::ManagePublicLinks,
            msg: path.to_string_lossy().to_string(),
        })?;

        let responses = self.read_filtered_responses()?;

        for response in responses {
            match response.msg.split_once(':') {
                Some((responded_status, responded_path)) if Path::new(responded_path) == path => {
                    let status = ShareStatus::try_from(responded_status)?;
                    return match status {
                        ShareStatus::Nop => Err(Error::CannotShareFile),
                        ShareStatus::NotConnected => Err(Error::NotConnected),
                        ShareStatus::NotSynced => Err(Error::NotSynced),
                        ShareStatus::CannotShareRoot => Err(Error::CannotShareRoot),
                        ShareStatus::Ok => Ok(()),
                    };
                }
                None | Some((_, _)) => continue,
            }
        }

        Err(Error::NoResponse)
    }

    /// `copy_securefiledrop_link` creates a link to provide a file drop
    /// location, which can't be read afterwards. In case of an internal
    /// error, the sharing dialog is opened. The created link is placed
    /// in the clipboard.
    ///
    /// # Errors
    /// Returns error if the request can't be transmitted to the client
    /// or if an unknown response is received.
    #[inline]
    pub fn copy_securefiledrop_link(&mut self, path: &Path) -> Result<()> {
        if !self
            .registered_paths
            .iter()
            .any(|registered_path| path.starts_with(registered_path))
        {
            return Err(Error::NotInRegister(path.to_path_buf()));
        }

        self.socket.write_message(&Message {
            verb: ApiVerb::CopySecurefiledropLink,
            msg: path.to_string_lossy().to_string(),
        })?;

        _ = self.read_filtered_responses()?;

        Ok(())
    }

    /// `copy_public_link` creates a link to share publicly.
    /// In case of an internal error, the sharing dialog is opened.
    /// The created link is placed in the clipboard.
    ///
    /// # Errors
    /// Returns error if the request can't be transmitted to the client
    /// or if an unknown response is received.
    #[inline]
    pub fn copy_public_link(&mut self, path: &Path) -> Result<()> {
        if !self
            .registered_paths
            .iter()
            .any(|registered_path| path.starts_with(registered_path))
        {
            return Err(Error::NotInRegister(path.to_path_buf()));
        }

        self.socket.write_message(&Message {
            verb: ApiVerb::CopyPublicLink,
            msg: path.to_string_lossy().to_string(),
        })?;

        _ = self.read_filtered_responses()?;

        Ok(())
    }

    /// `copy_private_link` creates a link to share internally.
    /// In case of an internal error, the sharing dialog is opened.
    /// The created link is placed in the clipboard.
    ///
    /// # Errors
    /// Returns error if the request can't be transmitted to the client
    /// or if an unknown response is received.
    #[inline]
    pub fn copy_private_link(&mut self, path: &Path) -> Result<()> {
        if !self
            .registered_paths
            .iter()
            .any(|registered_path| path.starts_with(registered_path))
        {
            return Err(Error::NotInRegister(path.to_path_buf()));
        }

        self.socket.write_message(&Message {
            verb: ApiVerb::CopyPublicLink,
            msg: path.to_string_lossy().to_string(),
        })?;

        _ = self.read_filtered_responses()?;

        Ok(())
    }

    /// `email_private_link` creates a link to share internally.
    /// In case of an internal error, the sharing dialog is opened.
    /// The default e-mail client is opened with a prepared message.
    ///
    /// # Errors
    /// Returns error if the request can't be transmitted to the client
    /// or if an unknown response is received.
    #[inline]
    pub fn email_private_link(&mut self, path: &Path) -> Result<()> {
        if !self
            .registered_paths
            .iter()
            .any(|registered_path| path.starts_with(registered_path))
        {
            return Err(Error::NotInRegister(path.to_path_buf()));
        }

        self.socket.write_message(&Message {
            verb: ApiVerb::EmailPrivateLink,
            msg: path.to_string_lossy().to_string(),
        })?;

        _ = self.read_filtered_responses()?;

        Ok(())
    }

    /// `open_private_link` creates a link to share internally.
    /// In case of an internal error, the sharing dialog is opened.
    /// The default browser is opened with generated link.
    ///
    /// # Errors
    /// Returns error if the request can't be transmitted to the client
    /// or if an unknown response is received.
    #[inline]
    pub fn open_private_link(&mut self, path: &Path) -> Result<()> {
        if !self
            .registered_paths
            .iter()
            .any(|registered_path| path.starts_with(registered_path))
        {
            return Err(Error::NotInRegister(path.to_path_buf()));
        }

        self.socket.write_message(&Message {
            verb: ApiVerb::OpenPrivateLink,
            msg: path.to_string_lossy().to_string(),
        })?;

        _ = self.read_filtered_responses()?;

        Ok(())
    }

    /// `make_available_locally` configures the file to be synced to
    /// the local FS as soon as possible.
    ///
    /// # Errors
    /// Returns error if the request can't be transmitted to the client
    /// or if an unknown response is received.
    #[inline]
    pub fn make_available_locally(&mut self, path: &Path) -> Result<()> {
        if !self
            .registered_paths
            .iter()
            .any(|registered_path| path.starts_with(registered_path))
        {
            return Err(Error::NotInRegister(path.to_path_buf()));
        }

        self.socket.write_message(&Message {
            verb: ApiVerb::MakeAvailableLocally,
            msg: path.to_string_lossy().to_string(),
        })?;

        _ = self.read_filtered_responses()?;

        Ok(())
    }

    /// `make_online_only` configures the file to be virtually available.
    /// The file or folder will be downloaded on access. So permanent
    /// space occupation is minimized but latency shall be considered.
    ///
    /// # Errors
    /// Returns error if the request can't be transmitted to the client
    /// or if an unknown response is received.
    #[inline]
    pub fn make_online_only(&mut self, path: &Path) -> Result<()> {
        if !self
            .registered_paths
            .iter()
            .any(|registered_path| path.starts_with(registered_path))
        {
            return Err(Error::NotInRegister(path.to_path_buf()));
        }

        self.socket.write_message(&Message {
            verb: ApiVerb::MakeOnlineOnly,
            msg: path.to_string_lossy().to_string(),
        })?;

        _ = self.read_filtered_responses()?;

        Ok(())
    }
}

#[cfg(test)]
#[expect(clippy::unwrap_used, clippy::panic, reason = "for testing we panic")]
mod tests {
    use core::time::Duration;
    use std::{
        io::{prelude::*, BufReader, ErrorKind},
        os::unix::net::UnixListener,
        thread::{sleep, Builder as ThreadBuilder, JoinHandle},
    };

    use tempfile::TempDir;

    use super::*;

    #[test]
    fn test_fetch_version() {
        let temp_dir = TempDir::new().unwrap();
        let temp_path = temp_dir.path().join("nextcloud_socket");

        let server = handle_connection(
            &temp_path,
            "VERSION:".to_owned(),
            "VERSION:v1.3.37\n".to_owned(),
        );

        let mut api = Api::new_test(&temp_path).unwrap();
        let version = api.version().unwrap();

        server.join().unwrap();

        assert_eq!("v1.3.37".to_owned(), version);
    }

    #[test]
    fn test_fetch_menu_items() {
        let temp_dir = TempDir::new().unwrap();
        let temp_path = temp_dir.path().join("nextcloud_socket");

        let server = handle_connection(&temp_path,"GET_MENU_ITEMS:/tmp/NextCloud/test/document.pdf".to_owned(), "GET_MENU_ITEMS:BEGIN\nMENU_ITEM:ACTIVITY::activity\nMENU_ITEM:OPEN_PRIVATE_LINK::open in browser\nMENU_ITEM:SHARE::share\nMENU_ITEM:COPY_PUBLIC_LINK::copy public link\nMENU_ITEM:COPY_PRIVATE_LINK::copy private link\nGET_MENU_ITEMS:END\n".to_owned());

        let mut api = Api::new_test(&temp_path).unwrap();
        let items = api
            .get_menu_items(Path::new("/tmp/NextCloud/test/document.pdf"))
            .unwrap();

        server.join().unwrap();

        assert_eq!(5, items.len(), "wrong number of menu items returned");
    }

    fn handle_connection(temp_path: &Path, request: String, response: String) -> JoinHandle<()> {
        let listener = UnixListener::bind(temp_path).unwrap();

        let server = ThreadBuilder::new()
            .name("socket server".to_owned())
            .spawn(move || {
                trace!("spawned server");
                let (mut unix_stream, _) = listener.accept().unwrap();
                unix_stream
                    .set_read_timeout(Some(Duration::from_millis(100)))
                    .unwrap();

                let mut reader = BufReader::new(unix_stream.try_clone().unwrap());

                trace!("accepted incomming connection");
                unix_stream
                    .write_all("REGISTER_PATH:/tmp/NextCloud\n".to_owned().as_bytes())
                    .unwrap();

                loop {
                    let mut buf = String::new();
                    match reader.read_line(&mut buf) {
                        Ok(0) => continue,
                        Ok(_) => {}
                        Err(err) if err.kind() == ErrorKind::WouldBlock => continue,
                        Err(err) => panic!("failed to read line: {err}"),
                    }

                    let trimmed = buf.trim();
                    trace!("received request: {trimmed}");

                    assert_eq!(request.as_str(), trimmed, "unexpected request: {trimmed}");

                    break;
                }

                unix_stream.write_all(response.as_bytes()).unwrap();

                // sleep to let response handling take action before
                // removing the socket
                sleep(Duration::from_secs(1));

                trace!("shutting down");
            })
            .unwrap();

        server
    }
}