scalo 2.10.11

Self-regulating runtime for Rust data-plane services. Backpressure, load shedding and adaptive scaling are on by default.
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
// Project:   scalo
// File:      src/deployment/test_support.rs
// Purpose:   Reusable test helpers for contract-artefact e2e tests
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

//! Test helpers for contract-artefact end-to-end tests, shared by scalo
//! itself and every downstream consumer service (`dfe-loader`, `dfe-receiver`,
//! `dfe-archiver`, `dfe-fetcher`, `dfe-transform-vrl`, `dfe-transform-vector`).
//!
//! # What this module provides
//!
//! * **Tool probes** -- `OnceLock`-cached wrappers (slow probe runs at most
//!   once per test binary): [`docker_available`], [`helm_available`],
//!   [`kubeconform_available`], [`kind_available`], [`kubectl_available`].
//! * **Skip emission** -- [`skip`] writes the canonical
//!   `HYPERCI-SKIP[contract-e2e][<tier>]: <test>: <reason>` line to stderr
//!   AND a side-channel log the CI runner greps + counts for a summary.
//! * **Tier-B gate** -- [`tier_b_enabled`] (true iff `E2E_CLUSTER=1`).
//! * **Kind cluster lifecycle** -- [`KindClusterGuard`] +
//!   [`ensure_kind_cluster`]: per-test uniquely-named cluster, torn down on
//!   Drop so parallel runs never collide on cluster name.
//!
//! # Usage from a consumer's `tests/e2e/`
//!
//! Add `scalo` with the `deployment` feature in dev-dependencies:
//!
//! ```ignore
//! use scalo::deployment::test_support::{
//!     docker_available, ensure_kind_cluster, skip, tier_b_enabled,
//! };
//!
//! #[test]
//! fn my_consumer_dockerfile_actually_starts() {
//!     if !docker_available() {
//!         skip(
//!             "tier-a",
//!             "my_consumer_dockerfile_actually_starts",
//!             "docker daemon not reachable",
//!         );
//!         return;
//!     }
//!     // ... build + run image, etc.
//! }
//! ```
//!
//! # Why no `tempfile` dependency here?
//!
//! scalo `src/` stays std-only; `tempfile` is a dev-dep not pulled into the
//! runtime crate. Callers needing a tempdir pass one in via
//! [`ensure_kind_cluster_in`]. The shorthand [`ensure_kind_cluster`] uses
//! `~/.cache/scalo/contract-test/<cluster>/` and cleans it on Drop.

use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::OnceLock;
use std::time::Duration;

// ============================================================================
// Tool probes -- thin, cached, no panic.
// ============================================================================

/// Returns true iff `docker info` succeeds. Cached for the test-binary
/// lifetime.
#[must_use]
pub fn docker_available() -> bool {
    static OK: OnceLock<bool> = OnceLock::new();
    *OK.get_or_init(|| {
        Command::new("docker")
            .args(["info", "--format", "{{.ServerVersion}}"])
            .output()
            .is_ok_and(|o| o.status.success())
    })
}

/// The daemon endpoint of docker's active context, when one resolves.
///
/// A test that points `DOCKER_CONFIG` at a throwaway directory -- the usual way
/// to stop docker invoking a credential helper the host may not have -- also
/// discards the CONTEXT STORE, which lives in that same directory. Docker then
/// falls back to `unix:///var/run/docker.sock`. That is the right socket on
/// Linux CI and the wrong one anywhere the daemon listens elsewhere: Docker
/// Desktop puts it under the user's home directory, so the build fails to
/// connect on a developer machine while passing in CI.
///
/// Resolve the endpoint from the REAL config up front and hand it back through
/// `DOCKER_HOST`, so the throwaway config strips credentials and nothing else.
/// Returns `None` when no context resolves, leaving docker's own default.
#[must_use]
pub fn docker_host() -> Option<&'static str> {
    static HOST: OnceLock<Option<String>> = OnceLock::new();
    HOST.get_or_init(|| {
        // An explicit DOCKER_HOST already applies to every docker invocation,
        // context store or not, so honour it rather than re-deriving.
        if let Ok(explicit) = std::env::var("DOCKER_HOST")
            && !explicit.is_empty()
        {
            return Some(explicit);
        }
        let out = Command::new("docker")
            .args([
                "context",
                "inspect",
                "--format",
                "{{.Endpoints.docker.Host}}",
            ])
            .output()
            .ok()?;
        if !out.status.success() {
            return None;
        }
        let host = String::from_utf8_lossy(&out.stdout).trim().to_owned();
        (!host.is_empty()).then_some(host)
    })
    .as_deref()
}

/// Returns true iff `helm version` succeeds.
#[must_use]
pub fn helm_available() -> bool {
    static OK: OnceLock<bool> = OnceLock::new();
    *OK.get_or_init(|| {
        Command::new("helm")
            .arg("version")
            .output()
            .is_ok_and(|o| o.status.success())
    })
}

/// Returns true iff `kubeconform -v` succeeds.
#[must_use]
pub fn kubeconform_available() -> bool {
    static OK: OnceLock<bool> = OnceLock::new();
    *OK.get_or_init(|| {
        Command::new("kubeconform")
            .arg("-v")
            .output()
            .is_ok_and(|o| o.status.success())
    })
}

/// Returns true iff `kind version` succeeds.
#[must_use]
pub fn kind_available() -> bool {
    static OK: OnceLock<bool> = OnceLock::new();
    *OK.get_or_init(|| {
        Command::new("kind")
            .arg("version")
            .output()
            .is_ok_and(|o| o.status.success())
    })
}

/// Returns true iff `kubectl version --client=true` succeeds.
#[must_use]
pub fn kubectl_available() -> bool {
    static OK: OnceLock<bool> = OnceLock::new();
    *OK.get_or_init(|| {
        Command::new("kubectl")
            .args(["version", "--client=true"])
            .output()
            .is_ok_and(|o| o.status.success())
    })
}

/// Returns true iff the `E2E_CLUSTER` env var is set to `1` or `true`.
///
/// Cluster-based (Tier B) tests must check this before bringing up kind
/// because cluster spin-up is slow (60-120 s typical) and the harness
/// shouldn't run by default in `cargo test`.
#[must_use]
pub fn tier_b_enabled() -> bool {
    std::env::var("E2E_CLUSTER").is_ok_and(|v| v == "1" || v.eq_ignore_ascii_case("true"))
}

// ============================================================================
// Skip emission with canonical prefix.
// ============================================================================

/// Write a skip notice with the canonical
/// `HYPERCI-SKIP[contract-e2e][<tier>]:` prefix to stderr AND to a
/// side-channel log file the test runner can grep after the test stage.
///
/// `tier` is `"tier-a"` or `"tier-b"`. Anything else works but the test
/// runner's grep won't match.
///
/// # Side-channel path
///
/// Tries `$CARGO_TARGET_TMPDIR/contract-e2e-skips.log` first (cargo's
/// official integration-test scratch dir). Falls back to
/// `$HOME/.cache/scalo/contract-e2e-skips.log` if the env var is
/// unset (e.g. when the test binary is invoked outside `cargo test`).
/// File-write failures are silently ignored -- the test must not fail
/// because the skip-log infrastructure had a hiccup.
pub fn skip(tier: &str, test_name: &str, reason: &str) {
    let line = format!("HYPERCI-SKIP[contract-e2e][{tier}]: {test_name}: {reason}");
    eprintln!("{line}");
    if let Some(path) = skip_log_path() {
        let _ = append_line(&path, &line);
    }
}

fn skip_log_path() -> Option<PathBuf> {
    if let Ok(dir) = std::env::var("CARGO_TARGET_TMPDIR") {
        return Some(Path::new(&dir).join("contract-e2e-skips.log"));
    }
    // Fallback: ~/.cache/scalo/. Never /tmp per AGENT-RULES Rule 4.
    let home = std::env::var("HOME")
        .or_else(|_| std::env::var("USERPROFILE"))
        .ok()?;
    Some(Path::new(&home).join(".cache/scalo/contract-e2e-skips.log"))
}

fn append_line(path: &Path, line: &str) -> std::io::Result<()> {
    use std::io::Write;
    if let Some(parent) = path.parent() {
        std::fs::create_dir_all(parent)?;
    }
    let mut f = std::fs::OpenOptions::new()
        .create(true)
        .append(true)
        .open(path)?;
    writeln!(f, "{line}")
}

// ============================================================================
// Docker config helper -- empty creds JSON to avoid credential-helper lookup.
// ============================================================================

/// Empty-creds JSON suitable for `<docker_config_dir>/config.json`.
///
/// Set `DOCKER_CONFIG=<dir>` and write this to `<dir>/config.json` to
/// prevent docker from invoking credential helpers like
/// `docker-credential-secretservice` that may not be on the host. Public
/// registry pulls (Docker Hub, ghcr.io public images) don't need auth, so
/// the empty config is sufficient for build + run tests.
#[must_use]
pub fn docker_empty_creds_json() -> &'static str {
    r#"{"auths": {}}"#
}

// ============================================================================
// Kind cluster lifecycle -- per-test cluster, dropped on test exit.
// ============================================================================

/// Owns a kind cluster + its kubeconfig path. Dropping the guard deletes
/// the cluster and (if owned) removes the kubeconfig parent directory.
#[derive(Debug)]
pub struct KindClusterGuard {
    /// Kind cluster name (e.g. `hctest-deadbeef`).
    pub name: String,
    /// Path to the kubeconfig file. Tests pass this via `KUBECONFIG` env
    /// var so they don't disturb the user's default context.
    pub kubeconfig: PathBuf,
    /// Directory that holds `kubeconfig`. When the guard owns it (`true`),
    /// the directory is removed on Drop. When `false`, the caller manages
    /// the lifetime (e.g. via their own `tempfile::TempDir`).
    cleanup_dir: bool,
}

impl Drop for KindClusterGuard {
    fn drop(&mut self) {
        // Best-effort: delete the cluster.
        let _ = Command::new("kind")
            .args(["delete", "cluster", "--name", &self.name])
            .output();
        // Best-effort: remove the kubeconfig directory if we own it.
        if self.cleanup_dir
            && let Some(parent) = self.kubeconfig.parent()
        {
            let _ = std::fs::remove_dir_all(parent);
        }
    }
}

/// Bring up a uniquely-named kind cluster for the caller, storing
/// `kubeconfig` under `kubeconfig_dir` (which the caller manages, e.g.
/// via their own `tempfile::TempDir`).
///
/// Returns `None` if any prerequisite is missing (kind/kubectl/docker)
/// or cluster creation fails -- the underlying reason is emitted via
/// [`skip`] so the test runner sees it.
///
/// The cluster name is derived from `test_name` via a small hash so each
/// test in a parallel suite gets its own cluster.
#[must_use]
pub fn ensure_kind_cluster_in(test_name: &str, kubeconfig_dir: &Path) -> Option<KindClusterGuard> {
    let cluster = prepare_cluster_or_skip(test_name)?;
    let kubeconfig = kubeconfig_dir.join("kubeconfig");
    let kc = Command::new("kind")
        .args(["get", "kubeconfig", "--name", &cluster])
        .output()
        .ok()?;
    std::fs::write(&kubeconfig, &kc.stdout).ok()?;
    Some(KindClusterGuard {
        name: cluster,
        kubeconfig,
        cleanup_dir: false,
    })
}

/// Convenience: like [`ensure_kind_cluster_in`] but uses an owned
/// directory under `~/.cache/scalo/contract-test/<cluster>/` so the
/// caller doesn't need `tempfile`. The directory is removed on Drop.
#[must_use]
pub fn ensure_kind_cluster(test_name: &str) -> Option<KindClusterGuard> {
    let cluster = prepare_cluster_or_skip(test_name)?;
    let home = std::env::var("HOME")
        .or_else(|_| std::env::var("USERPROFILE"))
        .ok()?;
    let dir = Path::new(&home)
        .join(".cache/scalo/contract-test")
        .join(&cluster);
    if let Err(e) = std::fs::create_dir_all(&dir) {
        skip(
            "tier-b",
            test_name,
            &format!(
                "could not create cluster scratch dir {}: {e}",
                dir.display()
            ),
        );
        // Best-effort cleanup of the cluster we just created.
        let _ = Command::new("kind")
            .args(["delete", "cluster", "--name", &cluster])
            .output();
        return None;
    }
    let kubeconfig = dir.join("kubeconfig");
    let kc = Command::new("kind")
        .args(["get", "kubeconfig", "--name", &cluster])
        .output()
        .ok()?;
    std::fs::write(&kubeconfig, &kc.stdout).ok()?;
    Some(KindClusterGuard {
        name: cluster,
        kubeconfig,
        cleanup_dir: true,
    })
}

fn prepare_cluster_or_skip(test_name: &str) -> Option<String> {
    if !kind_available() {
        skip(
            "tier-b",
            test_name,
            "kind CLI not on PATH (install: https://kind.sigs.k8s.io/)",
        );
        return None;
    }
    if !kubectl_available() {
        skip("tier-b", test_name, "kubectl not on PATH");
        return None;
    }
    if !docker_available() {
        skip(
            "tier-b",
            test_name,
            "docker daemon not reachable (kind requires docker)",
        );
        return None;
    }

    let suffix = test_name.bytes().fold(0u32, |acc, b| {
        acc.wrapping_mul(31).wrapping_add(u32::from(b))
    });
    let cluster = format!("hctest-{suffix:08x}");

    let create = Command::new("kind")
        .args(["create", "cluster", "--name", &cluster, "--wait", "120s"])
        .output()
        .ok()?;
    if !create.status.success() {
        skip(
            "tier-b",
            test_name,
            &format!(
                "kind create cluster failed: {}",
                String::from_utf8_lossy(&create.stderr).trim()
            ),
        );
        return None;
    }
    Some(cluster)
}

// ============================================================================
// Wait helpers -- usable from cluster tests for "wait until X happens".
// ============================================================================

/// Poll `f` every `interval` until it returns `true` or `deadline` elapses.
/// Returns `true` if `f` returned `true` before deadline, `false` otherwise.
///
/// Used by cluster tests to wait for pods/deployments to become Ready.
pub fn wait_until(deadline: Duration, interval: Duration, mut f: impl FnMut() -> bool) -> bool {
    let start = std::time::Instant::now();
    while start.elapsed() < deadline {
        if f() {
            return true;
        }
        std::thread::sleep(interval);
    }
    f()
}