routa-core 0.19.0

Routa.js core domain — models, stores, protocols, and JSON-RPC (transport-agnostic)
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
//! Docker availability detection with caching.
//!
//! Mirrors the TypeScript `DockerDetector` in `src/core/acp/docker/detector.ts`.

use super::types::{DockerPullResult, DockerStatus};
use chrono::Utc;
use std::env;
use std::process::Stdio;
use std::sync::{Arc, OnceLock};
use std::time::{Duration, Instant};
use tokio::process::Command;
use tokio::sync::{Mutex, RwLock};

/// Cache TTL in milliseconds (30 seconds).
const CACHE_TTL_MS: u64 = 30_000;

/// Default timeout for Docker commands in milliseconds.
const DEFAULT_TIMEOUT_MS: u64 = 5_000;

/// Docker availability detector with caching.
pub struct DockerDetector {
    cached_status: Arc<RwLock<Option<DockerStatus>>>,
    cached_at: Arc<RwLock<Instant>>,
    refresh_lock: Arc<Mutex<()>>,
}

impl Default for DockerDetector {
    fn default() -> Self {
        Self::new()
    }
}

impl DockerDetector {
    /// Create a new DockerDetector instance.
    pub fn new() -> Self {
        let now = Instant::now();
        let stale_cached_at = stale_cache_instant(now, Duration::from_secs(3600));

        Self {
            cached_status: Arc::new(RwLock::new(None)),
            cached_at: Arc::new(RwLock::new(stale_cached_at)),
            refresh_lock: Arc::new(Mutex::new(())),
        }
    }

    async fn cached_status_if_fresh(&self, now: Instant) -> Option<DockerStatus> {
        let cached = self.cached_status.read().await;
        let cached_time = *self.cached_at.read().await;

        cached.as_ref().and_then(|status| {
            if now.duration_since(cached_time).as_millis() < CACHE_TTL_MS as u128 {
                Some(status.clone())
            } else {
                None
            }
        })
    }

    /// Check Docker availability, using cache if valid.
    pub async fn check_availability(&self, force_refresh: bool) -> DockerStatus {
        self.check_availability_with_runner(force_refresh, |checked_at| async move {
            self.run_docker_info(&checked_at).await
        })
        .await
    }

    async fn check_availability_with_runner<F, Fut>(
        &self,
        force_refresh: bool,
        runner: F,
    ) -> DockerStatus
    where
        F: FnOnce(String) -> Fut,
        Fut: std::future::Future<Output = DockerStatus>,
    {
        let started_at = Instant::now();

        if !force_refresh {
            if let Some(status) = self.cached_status_if_fresh(started_at).await {
                return status;
            }

            let _refresh_guard = self.refresh_lock.lock().await;
            let refreshed_at = Instant::now();
            if let Some(status) = self.cached_status_if_fresh(refreshed_at).await {
                return status;
            }

            let checked_at = Utc::now().to_rfc3339();
            let status = runner(checked_at).await;

            *self.cached_status.write().await = Some(status.clone());
            *self.cached_at.write().await = refreshed_at;

            return status;
        }

        let checked_at = Utc::now().to_rfc3339();
        let status = runner(checked_at).await;

        *self.cached_status.write().await = Some(status.clone());
        *self.cached_at.write().await = started_at;

        status
    }

    /// Run `docker info` and parse the result.
    async fn run_docker_info(&self, checked_at: &str) -> DockerStatus {
        let result = tokio::time::timeout(
            Duration::from_millis(DEFAULT_TIMEOUT_MS),
            docker_command()
                .args(["info", "--format", "{{json .}}"])
                .stdout(Stdio::piped())
                .stderr(Stdio::piped())
                .output(),
        )
        .await;

        match result {
            Ok(Ok(output)) if output.status.success() => {
                let stdout = String::from_utf8_lossy(&output.stdout);
                let (version, api_version) = self.parse_docker_info(&stdout);

                DockerStatus {
                    available: true,
                    daemon_running: true,
                    version,
                    api_version,
                    error: None,
                    checked_at: checked_at.to_string(),
                }
            }
            Ok(Ok(output)) => {
                let stderr = String::from_utf8_lossy(&output.stderr);
                DockerStatus {
                    available: false,
                    daemon_running: false,
                    error: Some(stderr.to_string()),
                    checked_at: checked_at.to_string(),
                    ..Default::default()
                }
            }
            Ok(Err(e)) => DockerStatus {
                available: false,
                daemon_running: false,
                error: Some(format!("Failed to run docker: {e}")),
                checked_at: checked_at.to_string(),
                ..Default::default()
            },
            Err(_) => DockerStatus {
                available: false,
                daemon_running: false,
                error: Some("Docker command timed out".to_string()),
                checked_at: checked_at.to_string(),
                ..Default::default()
            },
        }
    }

    /// Parse Docker info JSON output.
    fn parse_docker_info(&self, stdout: &str) -> (Option<String>, Option<String>) {
        if let Ok(json) = serde_json::from_str::<serde_json::Value>(stdout.trim()) {
            let version = json
                .get("ServerVersion")
                .and_then(|v| v.as_str())
                .map(|s| s.to_string());

            let api_version = json
                .get("ClientInfo")
                .and_then(|c| c.get("ApiVersion"))
                .and_then(|v| v.as_str())
                .or_else(|| json.get("APIVersion").and_then(|v| v.as_str()))
                .map(|s| s.to_string());

            (version, api_version)
        } else {
            (None, None)
        }
    }

    /// Check if a Docker image is available locally.
    pub async fn is_image_available(&self, image: &str) -> bool {
        let result = tokio::time::timeout(
            Duration::from_millis(DEFAULT_TIMEOUT_MS),
            docker_command()
                .args(["images", "-q", image])
                .stdout(Stdio::piped())
                .stderr(Stdio::piped())
                .output(),
        )
        .await;

        match result {
            Ok(Ok(output)) if output.status.success() => {
                !String::from_utf8_lossy(&output.stdout).trim().is_empty()
            }
            _ => false,
        }
    }

    /// Pull a Docker image from the registry.
    pub async fn pull_image(&self, image: &str) -> DockerPullResult {
        // 10 minute timeout for image pull
        let result = tokio::time::timeout(
            Duration::from_secs(10 * 60),
            docker_command()
                .args(["pull", image])
                .stdout(Stdio::piped())
                .stderr(Stdio::piped())
                .output(),
        )
        .await;

        match result {
            Ok(Ok(output)) if output.status.success() => {
                let stdout = String::from_utf8_lossy(&output.stdout);
                let stderr = String::from_utf8_lossy(&output.stderr);
                let combined = format!(
                    "{}{}",
                    stdout,
                    if stderr.is_empty() {
                        "".to_string()
                    } else {
                        format!("\n{stderr}")
                    }
                );

                DockerPullResult {
                    ok: true,
                    image: image.to_string(),
                    output: Some(combined.trim().to_string()),
                    error: None,
                }
            }
            Ok(Ok(output)) => {
                let stderr = String::from_utf8_lossy(&output.stderr);
                DockerPullResult {
                    ok: false,
                    image: image.to_string(),
                    output: None,
                    error: Some(stderr.to_string()),
                }
            }
            Ok(Err(e)) => DockerPullResult {
                ok: false,
                image: image.to_string(),
                output: None,
                error: Some(format!("Failed to run docker pull: {e}")),
            },
            Err(_) => DockerPullResult {
                ok: false,
                image: image.to_string(),
                output: None,
                error: Some("Docker pull timed out".to_string()),
            },
        }
    }
}

/// Resolve the docker binary to an absolute path.
///
/// macOS GUI apps (launched from Dock/Finder) inherit a minimal launchd PATH
/// that typically lacks `/usr/local/bin` where Docker / OrbStack / Colima
/// install their symlinks.  We probe several well-known locations and fall
/// back to `"docker"` so the OS can still resolve it on systems with a
/// proper PATH (Linux, or when launched from a terminal).
pub fn resolve_docker_bin() -> String {
    let candidates: &[&str] = &[
        "/usr/local/bin/docker",    // Docker Desktop, OrbStack (macOS)
        "/opt/homebrew/bin/docker", // Homebrew (Apple Silicon)
        "/usr/bin/docker",          // Linux system install
    ];

    for path in candidates {
        if std::path::Path::new(path).exists() {
            return path.to_string();
        }
    }

    // Fall back to bare name and let the OS resolve via PATH
    "docker".to_string()
}

/// Expanded PATH directories that should be searched for docker.
const EXTRA_PATH_DIRS: &[&str] = &["/usr/local/bin", "/opt/homebrew/bin"];

/// Pre-resolved docker binary path (computed once at first use).
static DOCKER_BIN: OnceLock<String> = OnceLock::new();

fn docker_command() -> Command {
    let bin = DOCKER_BIN.get_or_init(resolve_docker_bin);
    let mut command = Command::new(bin.as_str());
    command.kill_on_drop(true);

    // Inject common Docker paths into the child process PATH so that the
    // docker CLI itself (and any helpers it shells out to) can be found,
    // even when the parent process was launched with a minimal launchd PATH.
    if let Ok(current_path) = env::var("PATH") {
        let extra: String = EXTRA_PATH_DIRS
            .iter()
            .filter(|d| !current_path.contains(*d))
            .cloned()
            .collect::<Vec<_>>()
            .join(":");
        if !extra.is_empty() {
            let expanded = format!("{extra}:{current_path}");
            command.env("PATH", &expanded);
        }
    }

    #[cfg(windows)]
    {
        use std::os::windows::process::CommandExt;

        command.as_std_mut().creation_flags(0x0800_0000);
    }

    command
}

fn stale_cache_instant(now: Instant, stale_by: Duration) -> Instant {
    now.checked_sub(stale_by).unwrap_or(now)
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::atomic::{AtomicUsize, Ordering};
    use tokio::sync::Notify;

    #[test]
    fn stale_cache_instant_saturates_on_underflow() {
        let now = Instant::now();

        assert_eq!(stale_cache_instant(now, Duration::MAX), now);
    }

    #[tokio::test]
    async fn check_availability_coalesces_concurrent_requests() {
        let detector = DockerDetector::new();
        let invocations = Arc::new(AtomicUsize::new(0));

        let first_counter = invocations.clone();
        let second_counter = invocations.clone();

        let first = detector.check_availability_with_runner(false, move |checked_at| {
            let counter = first_counter.clone();
            async move {
                counter.fetch_add(1, Ordering::SeqCst);
                tokio::time::sleep(Duration::from_millis(50)).await;
                DockerStatus {
                    available: true,
                    daemon_running: true,
                    checked_at,
                    ..Default::default()
                }
            }
        });

        let second = detector.check_availability_with_runner(false, move |checked_at| {
            let counter = second_counter.clone();
            async move {
                counter.fetch_add(1, Ordering::SeqCst);
                DockerStatus {
                    available: true,
                    daemon_running: true,
                    checked_at,
                    ..Default::default()
                }
            }
        });

        let (left, right) = tokio::time::timeout(Duration::from_secs(1), async {
            tokio::join!(first, second)
        })
        .await
        .expect("concurrent availability checks should complete");

        assert!(left.available);
        assert!(right.available);
        assert_eq!(invocations.load(Ordering::SeqCst), 1);
    }

    #[tokio::test]
    async fn force_refresh_bypasses_in_flight_probe() {
        let detector = Arc::new(DockerDetector::new());
        let invocations = Arc::new(AtomicUsize::new(0));
        let background_started = Arc::new(Notify::new());
        let background_release = Arc::new(Notify::new());

        let background_detector = detector.clone();
        let background_counter = invocations.clone();
        let background_started_signal = background_started.clone();
        let background_release_signal = background_release.clone();
        let background = tokio::spawn(async move {
            background_detector
                .check_availability_with_runner(false, move |checked_at| {
                    let counter = background_counter.clone();
                    let started = background_started_signal.clone();
                    let release = background_release_signal.clone();
                    async move {
                        counter.fetch_add(1, Ordering::SeqCst);
                        started.notify_waiters();
                        release.notified().await;
                        DockerStatus {
                            available: true,
                            daemon_running: true,
                            checked_at,
                            ..Default::default()
                        }
                    }
                })
                .await
        });

        background_started.notified().await;

        let refresh_detector = detector.clone();
        let refresh_counter = invocations.clone();
        let refresh = tokio::spawn(async move {
            refresh_detector
                .check_availability_with_runner(true, move |checked_at| {
                    let counter = refresh_counter.clone();
                    async move {
                        counter.fetch_add(1, Ordering::SeqCst);
                        DockerStatus {
                            available: true,
                            daemon_running: true,
                            checked_at,
                            ..Default::default()
                        }
                    }
                })
                .await
        });

        let refreshed = tokio::time::timeout(Duration::from_millis(50), refresh)
            .await
            .expect("force refresh should not wait for in-flight background probe")
            .expect("force refresh task should complete");

        assert!(refreshed.available);

        background_release.notify_waiters();
        let background = background.await.expect("background task should complete");

        assert!(background.available);
        assert_eq!(invocations.load(Ordering::SeqCst), 2);
    }
}