passalong-core 0.1.2

Core library for passalong: configuration, item model, storage traits, and telemetry
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
//! `passalong serve`: send every new clipboard text and every file dropped
//! into the drop folder, until told to stop.
//!
//! Three tasks cooperate:
//!
//! - the clipboard watcher polls the clipboard and queues new text, or a
//!   new image when it holds no text;
//! - the drop watcher scans the drop folder whenever the operating system
//!   reports a change, and at least every `rescan_interval` in case events
//!   are missed, queueing each file once it has stopped changing;
//! - with pull mode on, the pull loop applies items from other devices:
//!   files into the download directory, text and images through the
//!   clipboard task;
//! - the uploader, running in [`run`]'s own task, sends queued jobs one at a
//!   time, retrying each with a freshly opened store until it succeeds.

pub mod clipboard_watcher;
pub mod drop_watcher;
pub mod pull;
pub mod retry;
pub mod upload;

use std::path::PathBuf;
use std::sync::Arc;
use std::time::Duration;

use tokio::sync::{mpsc, oneshot, watch};
use tokio::time::{Instant, MissedTickBehavior};

use crate::clipboard::{Clipboard, ClipboardError, RgbaImage};
use crate::config::{AfterSend, Config};
use crate::store::{BackendFuture, StoreError};

use self::clipboard_watcher::ClipboardWatcher;
use self::drop_watcher::DropTracker;
use self::pull::{ClipboardWrite, Puller};
use self::upload::{JobOutcome, Uploader};

/// Folder inside the drop folder that sent files move to.
pub const SENT_DIR: &str = "sent";
const DEFAULT_RESCAN_INTERVAL: Duration = Duration::from_secs(5);
const QUEUE_DEPTH: usize = 64;

/// Opens a fresh store. `serve` calls it at start-up and again before every
/// retry, so a dropped SSH connection is re-established.
pub type StoreOpener = Arc<dyn Fn() -> BackendFuture<'static> + Send + Sync>;

/// One thing to send.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Job {
    /// Clipboard text.
    Text(String),
    /// A file in the drop folder.
    File(PathBuf),
    /// A clipboard image.
    Image(RgbaImage),
}

/// How `serve` behaves; normally built with [`ServeOptions::from_config`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ServeOptions {
    /// Folder watched for files to send.
    pub drop_folder: PathBuf,
    /// How often the clipboard is read.
    pub clipboard_poll_interval: Duration,
    /// How long a file must stay unchanged before it is sent.
    pub file_stable_wait: Duration,
    /// Longest time between two scans of the drop folder.
    pub rescan_interval: Duration,
    /// What happens to a file once it is sent.
    pub after_send: AfterSend,
    /// Device name recorded on sent items.
    pub device: String,
    /// Whether clipboard images are sent too.
    pub clipboard_images: bool,
    /// Whether items from other devices are applied here.
    pub pull: bool,
    /// How often pull mode checks for new items.
    pub pull_interval: Duration,
    /// Where pull mode puts files; used only when it exists.
    pub download_dir: PathBuf,
}

impl ServeOptions {
    /// Options from `[serve]` and `client.device_name`, rescanning the drop
    /// folder at least every 5 seconds.
    pub fn from_config(config: &Config) -> Self {
        Self {
            drop_folder: config.serve.drop_folder.clone(),
            clipboard_poll_interval: Duration::from_millis(config.serve.clipboard_poll_interval_ms),
            file_stable_wait: Duration::from_millis(config.serve.file_stable_wait_ms),
            rescan_interval: DEFAULT_RESCAN_INTERVAL,
            after_send: config.serve.after_send,
            device: config.client.device_name.clone(),
            clipboard_images: config.serve.clipboard_images,
            pull: config.serve.pull,
            pull_interval: Duration::from_millis(config.serve.pull_interval_ms),
            download_dir: config.client.download_dir.clone(),
        }
    }
}

/// Reasons `serve` cannot start. Once running, it never stops because of a
/// single failed item.
#[derive(Debug, thiserror::Error)]
pub enum ServeError {
    /// The store could not be opened at start-up.
    #[error("cannot open the store: {0}")]
    Store(#[from] StoreError),
    /// The drop folder or its `sent` folder could not be created.
    #[error("cannot prepare the drop folder {path}: {message}")]
    DropFolder {
        /// The drop folder.
        path: String,
        /// Underlying error.
        message: String,
    },
    /// The operating system refused to watch the drop folder.
    #[error("cannot watch the drop folder {path}: {message}")]
    Watch {
        /// The drop folder.
        path: String,
        /// Underlying error.
        message: String,
    },
}

/// Runs until `shutdown` becomes `true` or its sender is dropped. The store
/// is opened first so configuration and connection problems fail fast.
///
/// # Errors
///
/// A [`ServeError`] when start-up fails; after that, failures are logged
/// and retried.
pub async fn run(
    options: ServeOptions,
    clipboard: Option<Box<dyn Clipboard>>,
    open_store: StoreOpener,
    shutdown: watch::Receiver<bool>,
) -> Result<(), ServeError> {
    let (ready, _) = oneshot::channel();
    run_with_ready(options, clipboard, open_store, shutdown, ready).await
}

/// Like [`run`], and sends on `ready` once start-up has succeeded: the store
/// is open, the drop folder exists and is watched, and the watchers run.
/// `serve --daemon` uses it to report a successful start.
///
/// # Errors
///
/// As [`run`].
pub async fn run_with_ready(
    options: ServeOptions,
    clipboard: Option<Box<dyn Clipboard>>,
    open_store: StoreOpener,
    mut shutdown: watch::Receiver<bool>,
    ready: oneshot::Sender<()>,
) -> Result<(), ServeError> {
    let store = open_store().await?;
    let folder = options.drop_folder.clone();
    let shown = folder.display().to_string();
    let sent_dir = folder.join(SENT_DIR);
    tokio::fs::create_dir_all(&sent_dir)
        .await
        .map_err(|err| ServeError::DropFolder {
            path: shown.clone(),
            message: err.to_string(),
        })?;
    let (changed_tx, changed_rx) = mpsc::channel(1);
    let _watcher =
        drop_watcher::watch_folder(&folder, changed_tx).map_err(|err| ServeError::Watch {
            path: shown.clone(),
            message: err.to_string(),
        })?;

    // Pulled text and images reach the clipboard through the clipboard
    // task. The puller starts before anything is spawned, so a store
    // failure leaves nothing running, and before `ready`, so an item sent
    // right after start-up counts as new.
    let (writes_tx, writes_rx) = mpsc::channel(4);
    let puller = if options.pull {
        let pull_store = open_store().await?;
        let puller = Puller::start(
            pull_store.as_ref(),
            options.device.clone(),
            options.download_dir.clone(),
            clipboard.is_some().then(|| writes_tx.clone()),
        )
        .await?;
        Some((puller, pull_store))
    } else {
        None
    };
    drop(writes_tx);

    let (jobs_tx, mut jobs_rx) = mpsc::channel(QUEUE_DEPTH);
    let mut tasks = Vec::new();
    match clipboard {
        Some(clipboard) => tasks.push(tokio::spawn(clipboard_loop(
            clipboard,
            options.clipboard_poll_interval,
            options.clipboard_images,
            writes_rx,
            jobs_tx.clone(),
            shutdown.clone(),
        ))),
        None => tracing::warn!("no clipboard available; only the drop folder is watched"),
    }
    if let Some((puller, pull_store)) = puller {
        tracing::info!(
            interval_ms = options.pull_interval.as_millis() as u64,
            "pull mode: applying items from other devices"
        );
        tasks.push(tokio::spawn(pull::pull_loop(
            puller,
            pull_store,
            open_store.clone(),
            options.pull_interval,
            shutdown.clone(),
        )));
    }
    let (skipped_tx, skipped_rx) = mpsc::unbounded_channel();
    tasks.push(tokio::spawn(drop_loop(
        folder,
        options.file_stable_wait,
        options.rescan_interval,
        jobs_tx,
        changed_rx,
        skipped_rx,
        shutdown.clone(),
    )));
    tracing::info!(
        path = shown.as_str(),
        "serving: watching the clipboard and the drop folder"
    );

    // Nobody may be waiting for readiness; that is fine.
    let _ = ready.send(());
    let mut uploader = Uploader::new(
        store,
        open_store,
        options.device,
        options.after_send,
        sent_dir,
    );
    loop {
        tokio::select! {
            () = stopped(&mut shutdown) => break,
            job = jobs_rx.recv() => match job {
                Some(job) => {
                    let file = match &job {
                        Job::File(path) => Some(path.clone()),
                        Job::Text(_) | Job::Image(_) => None,
                    };
                    if uploader.handle(job, &mut shutdown).await == JobOutcome::Skipped
                        && let Some(path) = file
                    {
                        // The drop watcher offers it again once it changes.
                        let _ = skipped_tx.send(path);
                    }
                }
                None => break,
            },
        }
    }
    for task in tasks {
        task.abort();
    }
    tracing::info!("serve stopped");
    Ok(())
}

/// Resolves once a stop is requested: the flag turns `true`, or its sender
/// is dropped.
pub(crate) async fn stopped(shutdown: &mut watch::Receiver<bool>) {
    // `wait_for` fails only when the sender is gone, which also means stop.
    let _ = shutdown.wait_for(|stop| *stop).await;
}

async fn clipboard_loop(
    mut clipboard: Box<dyn Clipboard>,
    interval: Duration,
    images: bool,
    mut writes: mpsc::Receiver<ClipboardWrite>,
    jobs: mpsc::Sender<Job>,
    mut shutdown: watch::Receiver<bool>,
) {
    let mut watcher = ClipboardWatcher::new();
    let mut ticker = tokio::time::interval(interval);
    ticker.set_missed_tick_behavior(MissedTickBehavior::Delay);
    // Log a failing clipboard once per distinct error, not on every poll.
    let mut last_error: Option<String> = None;
    loop {
        tokio::select! {
            () = stopped(&mut shutdown) => return,
            Some(write) = writes.recv() => {
                let task = tokio::task::spawn_blocking(move || {
                    let result = write_clipboard(clipboard.as_mut(), &write);
                    (clipboard, write, result)
                });
                match task.await {
                    Ok((back, write, result)) => {
                        clipboard = back;
                        match (result, &write) {
                            // Seen, so the next read does not send it back.
                            (Ok(()), ClipboardWrite::Text(text)) => watcher.mark_text(text),
                            (Ok(()), ClipboardWrite::Image(image)) => watcher.mark_image(image),
                            (Err(err), _) => {
                                tracing::warn!(error = %err, "cannot put pulled content on the clipboard");
                            }
                        }
                    }
                    Err(err) => {
                        tracing::warn!(error = %err, "the clipboard writer stopped");
                        return;
                    }
                }
                continue;
            }
            _ = ticker.tick() => {}
        }
        // Clipboard access can block, and images can be large, so it runs
        // on a blocking thread.
        let read = tokio::task::spawn_blocking(move || {
            let result = read_clipboard(clipboard.as_mut(), images);
            (clipboard, result)
        });
        let result = match read.await {
            Ok((back, result)) => {
                clipboard = back;
                result
            }
            Err(err) => {
                tracing::warn!(error = %err, "the clipboard reader stopped");
                return;
            }
        };
        match result {
            Ok((text, image)) => {
                last_error = None;
                if let Some(text) = watcher.observe(text) {
                    tracing::debug!(size = text.len() as u64, "new clipboard text");
                    if jobs.send(Job::Text(text)).await.is_err() {
                        return;
                    }
                } else if let Some(image) = watcher.observe_image(image) {
                    tracing::debug!(
                        width = image.width(),
                        height = image.height(),
                        "new clipboard image"
                    );
                    if jobs.send(Job::Image(image)).await.is_err() {
                        return;
                    }
                }
            }
            Err(err) => {
                let message = err.to_string();
                if last_error.as_deref() != Some(message.as_str()) {
                    tracing::warn!(error = message.as_str(), "cannot read the clipboard");
                    last_error = Some(message);
                }
            }
        }
    }
}

fn write_clipboard(
    clipboard: &mut dyn Clipboard,
    write: &ClipboardWrite,
) -> Result<(), ClipboardError> {
    match write {
        ClipboardWrite::Text(text) => clipboard.write_text(text),
        ClipboardWrite::Image(image) => clipboard.write_image(image),
    }
}

/// Reads the clipboard's text and, when it holds no text and `images` is
/// on, its image.
fn read_clipboard(
    clipboard: &mut dyn Clipboard,
    images: bool,
) -> Result<(Option<String>, Option<RgbaImage>), ClipboardError> {
    let text = clipboard.read_text()?;
    let has_text = text.as_deref().is_some_and(|text| !text.trim().is_empty());
    let image = if images && !has_text {
        clipboard.read_image()?
    } else {
        None
    };
    Ok((text, image))
}

async fn drop_loop(
    folder: PathBuf,
    stable_wait: Duration,
    rescan: Duration,
    jobs: mpsc::Sender<Job>,
    mut changed: mpsc::Receiver<()>,
    mut skipped: mpsc::UnboundedReceiver<PathBuf>,
    mut shutdown: watch::Receiver<bool>,
) {
    let mut tracker = DropTracker::new(stable_wait);
    // While files are settling, look again often enough to notice promptly.
    let settle_tick = (stable_wait / 2).clamp(Duration::from_millis(50), Duration::from_secs(1));
    let mut watching = true;
    loop {
        match drop_watcher::scan(&folder).await {
            Ok(files) => {
                for path in tracker.observe(files, Instant::now()) {
                    if jobs.send(Job::File(path)).await.is_err() {
                        return;
                    }
                }
            }
            Err(err) => {
                tracing::warn!(path = %folder.display(), error = %err, "cannot scan the drop folder")
            }
        }
        let wait = if tracker.has_pending() {
            settle_tick
        } else {
            rescan
        };
        tokio::select! {
            () = stopped(&mut shutdown) => return,
            event = changed.recv(), if watching => {
                // The watcher is gone; keep going on periodic scans alone.
                if event.is_none() {
                    watching = false;
                }
            }
            Some(path) = skipped.recv() => tracker.mark_skipped(&path),
            () = tokio::time::sleep(wait) => {}
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::testing::MapEnv;

    #[test]
    fn options_come_from_the_config() {
        let text = "[client]\ndevice_name = \"lap\"\ndownload_dir = \"/dl\"\n[server]\nkind = \"local\"\n[server.local]\npath = \"/s\"\n[serve]\ndrop_folder = \"/drop\"\nclipboard_poll_interval_ms = 300\nfile_stable_wait_ms = 0\nafter_send = \"delete\"\n";
        let config =
            crate::config::parse(text, std::path::Path::new("/c.toml"), &MapEnv::new()).unwrap();
        assert_eq!(
            ServeOptions::from_config(&config),
            ServeOptions {
                drop_folder: PathBuf::from("/drop"),
                clipboard_poll_interval: Duration::from_millis(300),
                file_stable_wait: Duration::ZERO,
                rescan_interval: Duration::from_secs(5),
                after_send: AfterSend::Delete,
                device: "lap".into(),
                clipboard_images: true,
                pull: false,
                pull_interval: Duration::from_millis(5000),
                download_dir: PathBuf::from("/dl"),
            }
        );
    }
}