capulus 0.4.4

Shared support helpers for komputation CLI tools.
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
use std::env;
use std::ffi::OsString;
use std::fs::{self, File, OpenOptions};
use std::io::{self, Seek, SeekFrom, Write};
use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::OnceLock;
use std::thread;
use std::time::Duration;

use fs2::FileExt;
use indicatif::ProgressBar;

use crate::ui::{
    Task, TaskOptions, TaskVisibility, Ui, print_notice, spinner, stderr_is_interactive,
};

const BYPASS_ENV_VAR: &str = "CAPULUS_SINGLE_INSTANCE_BYPASS";
const LOCK_WAIT_POLL_INTERVAL: Duration = Duration::from_millis(100);

static ACTIVE_BYPASS_TOKEN: OnceLock<OsString> = OnceLock::new();

#[derive(Debug)]
pub struct InvocationLock {
    _file: Option<File>,
    path: PathBuf,
}

impl InvocationLock {
    pub fn path(&self) -> &Path {
        &self.path
    }
}

#[derive(Debug, thiserror::Error)]
pub enum LockError {
    #[error("another `{tool}` invocation is already running (lockfile: {path})")]
    AlreadyRunning { tool: String, path: String },

    #[error("failed to create lock directory for `{tool}` at {path}: {source}")]
    CreateDir {
        tool: String,
        path: String,
        #[source]
        source: io::Error,
    },

    #[error("failed to open lockfile for `{tool}` at {path}: {source}")]
    Open {
        tool: String,
        path: String,
        #[source]
        source: io::Error,
    },

    #[error("failed to update lockfile for `{tool}` at {path}: {source}")]
    Update {
        tool: String,
        path: String,
        #[source]
        source: io::Error,
    },

    #[error("interrupted while waiting for `{tool}` lock at {path}")]
    Interrupted {
        tool: String,
        path: String,
        #[source]
        source: crate::Cancelled,
    },
}

pub fn acquire_in(
    root: impl AsRef<Path>,
    tool: &str,
    wait: bool,
) -> Result<InvocationLock, LockError> {
    let tool = sanitize_component(tool);
    let token = bypass_token(&tool);
    let _ = ACTIVE_BYPASS_TOKEN.set(token.clone());
    if env::var_os(BYPASS_ENV_VAR).as_ref() == Some(&token) {
        let path = lock_path(root.as_ref(), &tool);
        return Ok(InvocationLock { _file: None, path });
    }
    acquire_sanitized(root.as_ref(), &tool, wait, None)
}

pub fn acquire_in_with_ui(
    root: impl AsRef<Path>,
    tool: &str,
    wait: bool,
    ui: &Ui,
) -> Result<InvocationLock, LockError> {
    let tool = sanitize_component(tool);
    let token = bypass_token(&tool);
    let _ = ACTIVE_BYPASS_TOKEN.set(token.clone());
    if env::var_os(BYPASS_ENV_VAR).as_ref() == Some(&token) {
        let path = lock_path(root.as_ref(), &tool);
        return Ok(InvocationLock { _file: None, path });
    }
    acquire_sanitized(root.as_ref(), &tool, wait, Some(ui))
}

pub fn acquire_named_in(
    root: impl AsRef<Path>,
    name: &str,
    wait: bool,
) -> Result<InvocationLock, LockError> {
    acquire_sanitized(root.as_ref(), &sanitize_component(name), wait, None)
}

pub fn acquire_named_in_with_ui(
    root: impl AsRef<Path>,
    name: &str,
    wait: bool,
    ui: &Ui,
) -> Result<InvocationLock, LockError> {
    acquire_sanitized(root.as_ref(), &sanitize_component(name), wait, Some(ui))
}

pub fn configure_child_command(command: &mut Command) {
    if let Some(token) = ACTIVE_BYPASS_TOKEN.get() {
        command.env(BYPASS_ENV_VAR, token);
    }
}

pub fn configure_privileged_child_command(command: &mut Command, program: &str) {
    if ACTIVE_BYPASS_TOKEN.get().is_none() {
        return;
    }
    match program {
        "doas" => {
            command.arg("-E");
        }
        "sudo" => {
            command.arg(format!("--preserve-env={BYPASS_ENV_VAR}"));
        }
        _ => {}
    }
    configure_child_command(command);
}

fn write_lock_metadata(tool: &str, path: &Path, file: &mut File) -> Result<(), LockError> {
    file.set_len(0).map_err(|source| LockError::Update {
        tool: tool.to_owned(),
        path: path.display().to_string(),
        source,
    })?;
    file.seek(SeekFrom::Start(0))
        .map_err(|source| LockError::Update {
            tool: tool.to_owned(),
            path: path.display().to_string(),
            source,
        })?;
    writeln!(file, "{}", std::process::id()).map_err(|source| LockError::Update {
        tool: tool.to_owned(),
        path: path.display().to_string(),
        source,
    })?;
    file.sync_data().map_err(|source| LockError::Update {
        tool: tool.to_owned(),
        path: path.display().to_string(),
        source,
    })?;
    Ok(())
}

fn acquire_sanitized(
    root: &Path,
    tool: &str,
    wait: bool,
    ui: Option<&Ui>,
) -> Result<InvocationLock, LockError> {
    let path = lock_path(root, tool);
    if let Some(parent) = path.parent() {
        fs::create_dir_all(parent).map_err(|source| LockError::CreateDir {
            tool: tool.to_owned(),
            path: parent.display().to_string(),
            source,
        })?;
    }

    let mut file = OpenOptions::new()
        .create(true)
        .read(true)
        .write(true)
        .truncate(false)
        .open(&path)
        .map_err(|source| LockError::Open {
            tool: tool.to_owned(),
            path: path.display().to_string(),
            source,
        })?;

    let mut wait_ui = LockWaitUi::new(tool, &path, ui.cloned());
    loop {
        match file.try_lock_exclusive() {
            Ok(()) => {
                let result = write_lock_metadata(tool, &path, &mut file);
                wait_ui.clear();
                result?;
                break;
            }
            Err(source) if source.kind() == io::ErrorKind::WouldBlock => {
                if !wait {
                    return Err(LockError::AlreadyRunning {
                        tool: tool.to_owned(),
                        path: path.display().to_string(),
                    });
                }
                wait_ui.show();
                if let Err(error) = wait_ui.sleep() {
                    wait_ui.abandon();
                    return Err(error);
                }
            }
            Err(source) => {
                wait_ui.clear();
                return Err(LockError::Open {
                    tool: tool.to_owned(),
                    path: path.display().to_string(),
                    source,
                });
            }
        }
    }

    Ok(InvocationLock {
        _file: Some(file),
        path,
    })
}

fn lock_path(root: &Path, tool: &str) -> PathBuf {
    root.join(format!("{tool}.lock"))
}

fn bypass_token(tool: &str) -> OsString {
    OsString::from(format!("capulus:{tool}"))
}

fn sanitize_component(value: &str) -> String {
    let mut output = String::with_capacity(value.len());
    for ch in value.chars() {
        if ch.is_ascii_alphanumeric() || matches!(ch, '-' | '_' | '.') {
            output.push(ch.to_ascii_lowercase());
        } else {
            output.push('_');
        }
    }
    if output.is_empty() {
        "tool".to_owned()
    } else {
        output
    }
}

struct LockWaitUi {
    tool: String,
    path: String,
    message: String,
    ui: Option<Ui>,
    task: Option<Task>,
    progress: Option<ProgressBar>,
    notice_printed: bool,
}

impl LockWaitUi {
    fn new(tool: &str, path: &Path, ui: Option<Ui>) -> Self {
        Self {
            tool: tool.to_owned(),
            path: path.display().to_string(),
            message: format!(
                "Waiting for another `{tool}` invocation to finish ({})",
                path.display()
            ),
            ui,
            task: None,
            progress: None,
            notice_printed: false,
        }
    }

    fn show(&mut self) {
        if let Some(ui) = self.ui.as_ref() {
            if self.task.is_none() {
                self.task = Some(
                    ui.task(TaskOptions {
                        label: self.message.clone(),
                        visibility: TaskVisibility::Immediate,
                        ..TaskOptions::default()
                    })
                    .expect("lock wait task is valid"),
                );
            }
            return;
        }
        if let Some(progress) = &self.progress {
            progress.tick();
            return;
        }
        if stderr_is_interactive() {
            self.progress = Some(spinner(&self.message));
            return;
        }
        if !self.notice_printed {
            print_notice(&self.message);
            self.notice_printed = true;
        }
    }

    fn clear(&mut self) {
        if let Some(task) = self.task.take() {
            task.finish_and_clear();
        }
        if let Some(progress) = self.progress.take() {
            progress.finish_and_clear();
        }
    }

    fn abandon(&mut self) {
        if let Some(task) = self.task.take() {
            task.abandon("Lock wait interrupted");
        }
    }

    fn sleep(&self) -> Result<(), LockError> {
        match self.ui.as_ref() {
            Some(ui) => {
                ui.sleep(LOCK_WAIT_POLL_INTERVAL)
                    .map_err(|source| LockError::Interrupted {
                        tool: self.tool.clone(),
                        path: self.path.clone(),
                        source,
                    })
            }
            None => {
                thread::sleep(LOCK_WAIT_POLL_INTERVAL);
                Ok(())
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use std::fs;
    use std::sync::mpsc;
    use std::time::{Duration, SystemTime, UNIX_EPOCH};

    use super::{LockError, acquire_in, acquire_named_in};

    fn unique_tool_name() -> String {
        let now = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .expect("current time after unix epoch")
            .as_nanos();
        format!("capulus-lock-test-{}-{now}", std::process::id())
    }

    #[test]
    fn acquire_without_wait_returns_already_running() {
        let temp = tempfile::TempDir::new().expect("temp lock root");
        let root = temp.path().join("locks");
        let tool = unique_tool_name();
        let first = acquire_in(&root, &tool, false).expect("acquire first lock");
        let first_path = first.path().to_path_buf();
        let second = acquire_in(&root, &tool, false).expect_err("second acquisition should fail");
        assert!(matches!(second, LockError::AlreadyRunning { .. }));
        drop(first);
        fs::remove_file(first_path).ok();
    }

    #[test]
    fn acquire_with_wait_blocks_until_previous_holder_releases() {
        let temp = tempfile::TempDir::new().expect("temp lock root");
        let root = temp.path().join("locks");
        let tool = unique_tool_name();
        let first = acquire_in(&root, &tool, false).expect("acquire first lock");
        let (done_tx, done_rx) = mpsc::channel();
        let waiting_tool = tool.clone();
        let waiting_root = root.clone();

        let handle = std::thread::spawn(move || {
            let second = acquire_in(&waiting_root, &waiting_tool, true)
                .expect("waiting acquisition succeeds");
            done_tx
                .send(second.path().to_path_buf())
                .expect("send path");
            second
        });

        assert!(
            done_rx.recv_timeout(Duration::from_millis(250)).is_err(),
            "waiting acquisition should still be blocked"
        );
        drop(first);

        let second_path = done_rx
            .recv_timeout(Duration::from_secs(3))
            .expect("waiting acquisition completes");
        let second = handle.join().expect("join waiter");
        drop(second);
        fs::remove_file(second_path).ok();
    }

    #[test]
    fn acquire_named_uses_the_same_lock_namespace_without_bypass() {
        let temp = tempfile::TempDir::new().expect("temp lock root");
        let root = temp.path().join("locks");
        let tool = unique_tool_name();
        let first = acquire_named_in(&root, &tool, false).expect("acquire first named lock");
        let second = acquire_named_in(&root, &tool, false)
            .expect_err("second named acquisition should fail");
        assert!(matches!(second, LockError::AlreadyRunning { .. }));
        let first_path = first.path().to_path_buf();
        drop(first);
        fs::remove_file(first_path).ok();
    }
}