Skip to main content

arks_server/
ops.rs

1//! Serve operations P1 per `.spec/sot/serve-operations.sot.md`:
2//! - O-6: Structured JSON access logs (`ARKS_LOG_FORMAT=json`), `X-Request-Id`, W3C `traceparent`.
3//! - O-7: Persistent atomic file-backed job queue (`arks-forge/jobs/`).
4//! - O-9: Typed TOML config (`--config arks.toml`), `arks serve config check`, `*_FILE` secret loader.
5
6use crate::http::{HttpRequest, HttpResponse};
7use serde::{Deserialize, Serialize};
8use std::collections::BTreeMap;
9use std::fs;
10use std::path::{Path, PathBuf};
11use std::sync::atomic::{AtomicU64, Ordering};
12use std::time::{SystemTime, UNIX_EPOCH};
13
14static TRACE_SEQ: AtomicU64 = AtomicU64::new(1);
15
16fn now_unix_i64() -> i64 {
17    SystemTime::now()
18        .duration_since(UNIX_EPOCH)
19        .map(|d| d.as_secs() as i64)
20        .unwrap_or(0)
21}
22
23fn now_unix_nanos() -> u128 {
24    SystemTime::now()
25        .duration_since(UNIX_EPOCH)
26        .map(|d| d.as_nanos())
27        .unwrap_or(0)
28}
29
30/// Request correlation context (O-6): `X-Request-Id` and W3C `traceparent`.
31#[derive(Clone, Debug, PartialEq, Eq)]
32pub struct RequestTrace {
33    pub request_id: String,
34    pub traceparent: String,
35}
36
37impl RequestTrace {
38    pub fn from_request(req: &HttpRequest) -> Self {
39        let seq = TRACE_SEQ.fetch_add(1, Ordering::Relaxed);
40        let nanos = now_unix_nanos();
41        let request_id = req
42            .header("x-request-id")
43            .map(sanitize_header_val)
44            .filter(|v| !v.is_empty())
45            .unwrap_or_else(|| format!("req_{nanos:016x}_{seq:04x}"));
46        let traceparent = req
47            .header("traceparent")
48            .map(sanitize_header_val)
49            .filter(|v| is_valid_traceparent(v))
50            .unwrap_or_else(|| {
51                let trace_id = format!("{nanos:032x}");
52                let span_id = format!("{seq:016x}");
53                format!("00-{trace_id}-{span_id}-01")
54            });
55        Self {
56            request_id,
57            traceparent,
58        }
59    }
60
61    pub fn attach_headers(&self, resp: &mut HttpResponse) {
62        if !resp
63            .extra_headers
64            .iter()
65            .any(|(k, _)| k.eq_ignore_ascii_case("x-request-id"))
66        {
67            resp.extra_headers
68                .push(("X-Request-Id".into(), self.request_id.clone()));
69        }
70        if !resp
71            .extra_headers
72            .iter()
73            .any(|(k, _)| k.eq_ignore_ascii_case("traceparent"))
74        {
75            resp.extra_headers
76                .push(("traceparent".into(), self.traceparent.clone()));
77        }
78    }
79}
80
81fn sanitize_header_val(raw: &str) -> String {
82    raw.chars()
83        .filter(|&c| c.is_ascii_graphic() || c == ' ')
84        .take(128)
85        .collect::<String>()
86        .trim()
87        .to_string()
88}
89
90fn is_valid_traceparent(s: &str) -> bool {
91    let parts: Vec<&str> = s.split('-').collect();
92    parts.len() == 4
93        && parts[0].len() == 2
94        && parts[1].len() == 32
95        && parts[2].len() == 16
96        && parts[3].len() == 2
97        && parts
98            .iter()
99            .all(|p| p.bytes().all(|b| b.is_ascii_hexdigit()))
100}
101
102/// Emit a single-line JSON access log record when `ARKS_LOG_FORMAT=json` (O-6).
103pub fn maybe_emit_json_access_log(
104    trace: &RequestTrace,
105    req: &HttpRequest,
106    status: u16,
107    duration_ms: u128,
108) {
109    let fmt = std::env::var("ARKS_LOG_FORMAT").unwrap_or_default();
110    if !fmt.eq_ignore_ascii_case("json") {
111        return;
112    }
113    let line = format_json_access_log(trace, req, status, duration_ms);
114    eprintln!("{line}");
115}
116
117pub fn format_json_access_log(
118    trace: &RequestTrace,
119    req: &HttpRequest,
120    status: u16,
121    duration_ms: u128,
122) -> String {
123    serde_json::json!({
124        "ts": now_unix_i64(),
125        "level": if status >= 500 { "error" } else if status >= 400 { "warn" } else { "info" },
126        "request_id": trace.request_id,
127        "traceparent": trace.traceparent,
128        "method": req.method,
129        "path": req.path,
130        "status": status,
131        "duration_ms": duration_ms,
132        "client_ip": req.client_ip().unwrap_or(""),
133    })
134    .to_string()
135}
136
137// ---------------------------------------------------------------------------
138// O-7: Persistent atomic file-backed job queue (`<git_dir>/arks-forge/jobs/`)
139// ---------------------------------------------------------------------------
140
141#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
142#[serde(rename_all = "snake_case")]
143pub enum JobStatus {
144    Pending,
145    Completed,
146    DeadLetter,
147}
148
149#[derive(Clone, Debug, Serialize, Deserialize)]
150pub struct JobRecord {
151    pub id: String,
152    pub kind: String,
153    pub payload: serde_json::Value,
154    pub status: JobStatus,
155    pub attempts: u32,
156    pub max_attempts: u32,
157    pub next_run_at: i64,
158    #[serde(default)]
159    pub last_error: Option<String>,
160    pub created_at: i64,
161}
162
163fn jobs_dir(git_dir: &Path) -> PathBuf {
164    git_dir.join("arks-forge").join("jobs")
165}
166
167/// Atomically persist a new background job into `<git_dir>/arks-forge/jobs/<id>.json`.
168pub fn enqueue_job(
169    git_dir: &Path,
170    kind: &str,
171    payload: serde_json::Value,
172    max_attempts: u32,
173) -> std::io::Result<JobRecord> {
174    let dir = jobs_dir(git_dir);
175    fs::create_dir_all(&dir)?;
176    let seq = TRACE_SEQ.fetch_add(1, Ordering::Relaxed);
177    let now = now_unix_i64();
178    let id = format!("job_{}_{:04x}", now_unix_nanos(), seq);
179    let rec = JobRecord {
180        id: id.clone(),
181        kind: kind.to_string(),
182        payload,
183        status: JobStatus::Pending,
184        attempts: 0,
185        max_attempts: max_attempts.max(1),
186        next_run_at: now,
187        last_error: None,
188        created_at: now,
189    };
190    write_job_atomic(&dir, &rec)?;
191    Ok(rec)
192}
193
194fn write_job_atomic(dir: &Path, rec: &JobRecord) -> std::io::Result<()> {
195    let target = dir.join(format!("{}.json", rec.id));
196    let tmp = dir.join(format!("{}.json.tmp", rec.id));
197    let bytes = serde_json::to_vec_pretty(rec).unwrap_or_else(|_| b"{}".to_vec());
198    fs::write(&tmp, bytes)?;
199    fs::rename(&tmp, &target)?;
200    Ok(())
201}
202
203/// List all persisted jobs in `<git_dir>/arks-forge/jobs/`.
204pub fn list_jobs(git_dir: &Path) -> Vec<JobRecord> {
205    let dir = jobs_dir(git_dir);
206    let Ok(rd) = fs::read_dir(&dir) else {
207        return Vec::new();
208    };
209    let mut out = Vec::new();
210    for entry in rd.flatten() {
211        let p = entry.path();
212        if p.extension().and_then(|e| e.to_str()) != Some("json") {
213            continue;
214        }
215        if let Ok(bytes) = fs::read(&p) {
216            if let Ok(rec) = serde_json::from_slice::<JobRecord>(&bytes) {
217                out.push(rec);
218            }
219        }
220    }
221    out.sort_by_key(|j| j.created_at);
222    out
223}
224
225/// Claim due pending jobs (`next_run_at <= now`) and return them.
226pub fn due_jobs(git_dir: &Path, now: i64) -> Vec<JobRecord> {
227    list_jobs(git_dir)
228        .into_iter()
229        .filter(|j| j.status == JobStatus::Pending && j.next_run_at <= now)
230        .collect()
231}
232
233/// Mark a job completed and persist atomically.
234pub fn complete_job(git_dir: &Path, mut rec: JobRecord) -> std::io::Result<JobRecord> {
235    rec.status = JobStatus::Completed;
236    rec.attempts = rec.attempts.saturating_add(1);
237    rec.last_error = None;
238    let dir = jobs_dir(git_dir);
239    fs::create_dir_all(&dir)?;
240    write_job_atomic(&dir, &rec)?;
241    Ok(rec)
242}
243
244/// Record a failed attempt with capped exponential backoff (`2^attempts * 5s`, max 3600s),
245/// transitioning to `DeadLetter` once `attempts >= max_attempts`.
246pub fn fail_job_with_backoff(
247    git_dir: &Path,
248    mut rec: JobRecord,
249    err: &str,
250    now: i64,
251) -> std::io::Result<JobRecord> {
252    rec.attempts = rec.attempts.saturating_add(1);
253    rec.last_error = Some(err.to_string());
254    if rec.attempts >= rec.max_attempts {
255        rec.status = JobStatus::DeadLetter;
256    } else {
257        let backoff = (5i64.saturating_mul(1i64 << rec.attempts.min(10))).min(3600);
258        rec.next_run_at = now.saturating_add(backoff);
259    }
260    let dir = jobs_dir(git_dir);
261    fs::create_dir_all(&dir)?;
262    write_job_atomic(&dir, &rec)?;
263    Ok(rec)
264}
265
266// ---------------------------------------------------------------------------
267// O-9: Typed config (`--config arks.toml`), `config check`, and `*_FILE` secrets
268// ---------------------------------------------------------------------------
269
270/// Resolve a secret from `<VAR>_FILE` (trimmed file contents) first, falling back to `<VAR>`.
271pub fn resolve_secret_env(var_name: &str) -> Option<String> {
272    let file_var = format!("{var_name}_FILE");
273    if let Ok(path) = std::env::var(&file_var) {
274        let trimmed_path = path.trim();
275        if !trimmed_path.is_empty() {
276            if let Ok(contents) = fs::read_to_string(trimmed_path) {
277                let secret = contents.trim().to_string();
278                if !secret.is_empty() {
279                    return Some(secret);
280                }
281            }
282        }
283    }
284    std::env::var(var_name)
285        .ok()
286        .map(|s| s.trim().to_string())
287        .filter(|s| !s.is_empty())
288}
289
290#[derive(Clone, Debug, PartialEq, Eq)]
291pub struct ServeConfig {
292    pub bind: String,
293    pub shutdown_grace_secs: u64,
294    pub trusted_proxies: Vec<String>,
295    pub log_format: String,
296    pub pwa: bool,
297    pub api_rate_limit_per_min: u32,
298    pub max_body_bytes: usize,
299    pub metrics_token: Option<String>,
300    pub security_contact: Option<String>,
301    pub security_expires: Option<String>,
302}
303
304impl Default for ServeConfig {
305    fn default() -> Self {
306        Self {
307            bind: "127.0.0.1:8080".into(),
308            shutdown_grace_secs: 30,
309            trusted_proxies: vec!["127.0.0.1/32".into(), "::1/128".into()],
310            log_format: "text".into(),
311            pwa: true,
312            api_rate_limit_per_min: crate::web::api::standards::DEFAULT_API_RATE_LIMIT_PER_MIN,
313            max_body_bytes: crate::web::api::standards::DEFAULT_MAX_BODY_BYTES,
314            metrics_token: None,
315            security_contact: None,
316            security_expires: None,
317        }
318    }
319}
320
321impl ServeConfig {
322    /// Parse a minimal TOML config file (zero external TOML crate dependency).
323    pub fn from_toml_str(src: &str) -> Result<Self, String> {
324        let mut cfg = Self::default();
325        let mut section = String::new();
326        let mut unknown_keys: Vec<String> = Vec::new();
327        for (line_no, raw_line) in src.lines().enumerate() {
328            let line = raw_line.split('#').next().unwrap_or("").trim();
329            if line.is_empty() {
330                continue;
331            }
332            if line.starts_with('[') && line.ends_with(']') {
333                section = line[1..line.len() - 1].trim().to_string();
334                continue;
335            }
336            let Some((k, v)) = line.split_once('=') else {
337                return Err(format!("line {}: expected `key = value`", line_no + 1));
338            };
339            let key = k.trim();
340            let val = v.trim();
341            let full = if section.is_empty() {
342                key.to_string()
343            } else {
344                format!("{section}.{key}")
345            };
346            match full.as_str() {
347                "server.bind" => cfg.bind = parse_toml_string(val)?,
348                "server.shutdown_grace_secs" => {
349                    cfg.shutdown_grace_secs = val.parse::<u64>().map_err(|e| {
350                        format!("line {}: invalid shutdown_grace_secs: {e}", line_no + 1)
351                    })?;
352                }
353                "server.trusted_proxies" => {
354                    cfg.trusted_proxies = parse_toml_string_array(val)?;
355                }
356                "ops.log_format" => cfg.log_format = parse_toml_string(val)?,
357                "ops.metrics_token" => cfg.metrics_token = Some(parse_toml_string(val)?),
358                "web.pwa" => {
359                    cfg.pwa = parse_toml_bool(val)
360                        .ok_or_else(|| format!("line {}: invalid bool for web.pwa", line_no + 1))?;
361                }
362                "web.security_contact" => cfg.security_contact = Some(parse_toml_string(val)?),
363                "web.security_expires" => cfg.security_expires = Some(parse_toml_string(val)?),
364                "api.rate_limit_per_min" => {
365                    cfg.api_rate_limit_per_min = val.parse::<u32>().map_err(|e| {
366                        format!("line {}: invalid api.rate_limit_per_min: {e}", line_no + 1)
367                    })?;
368                }
369                "storage.max_body_bytes" => {
370                    cfg.max_body_bytes = val.parse::<usize>().map_err(|e| {
371                        format!("line {}: invalid storage.max_body_bytes: {e}", line_no + 1)
372                    })?;
373                }
374                other => unknown_keys.push(format!("line {}: unknown key `{other}`", line_no + 1)),
375            }
376        }
377        if !unknown_keys.is_empty() {
378            return Err(unknown_keys.join("; "));
379        }
380        cfg.validate()?;
381        Ok(cfg)
382    }
383
384    pub fn from_file(path: &Path) -> Result<Self, String> {
385        let src = fs::read_to_string(path)
386            .map_err(|e| format!("cannot read config {}: {e}", path.display()))?;
387        Self::from_toml_str(&src)
388    }
389
390    pub fn validate(&self) -> Result<(), String> {
391        if self.bind.trim().is_empty() || !self.bind.contains(':') {
392            return Err(format!(
393                "invalid server.bind `{}` (expected host:port)",
394                self.bind
395            ));
396        }
397        if !matches!(self.log_format.as_str(), "text" | "json") {
398            return Err(format!(
399                "invalid ops.log_format `{}` (expected `text` or `json`)",
400                self.log_format
401            ));
402        }
403        for cidr in &self.trusted_proxies {
404            let (ip_str, prefix) = match cidr.split_once('/') {
405                Some((a, b)) => (a.trim(), Some(b.trim())),
406                None => (cidr.trim(), None),
407            };
408            let ip: std::net::IpAddr = ip_str
409                .parse()
410                .map_err(|_| format!("invalid IP in server.trusted_proxies: `{cidr}`"))?;
411            if let Some(p) = prefix {
412                let bits: u8 = p.parse().map_err(|_| {
413                    format!("invalid CIDR prefix in server.trusted_proxies: `{cidr}`")
414                })?;
415                let max_bits = if ip.is_ipv4() { 32 } else { 128 };
416                if bits > max_bits {
417                    return Err(format!(
418                        "CIDR prefix out of range in server.trusted_proxies: `{cidr}`"
419                    ));
420                }
421            }
422        }
423        Ok(())
424    }
425
426    pub fn summary_map(&self) -> BTreeMap<&'static str, String> {
427        let mut m = BTreeMap::new();
428        m.insert("server.bind", self.bind.clone());
429        m.insert(
430            "server.shutdown_grace_secs",
431            self.shutdown_grace_secs.to_string(),
432        );
433        m.insert("ops.log_format", self.log_format.clone());
434        m.insert("web.pwa", self.pwa.to_string());
435        m.insert(
436            "api.rate_limit_per_min",
437            self.api_rate_limit_per_min.to_string(),
438        );
439        m.insert("storage.max_body_bytes", self.max_body_bytes.to_string());
440        m
441    }
442}
443
444fn parse_toml_string(val: &str) -> Result<String, String> {
445    let trimmed = val.trim();
446    if trimmed.len() >= 2
447        && ((trimmed.starts_with('"') && trimmed.ends_with('"'))
448            || (trimmed.starts_with('\'') && trimmed.ends_with('\'')))
449    {
450        Ok(trimmed[1..trimmed.len() - 1].to_string())
451    } else {
452        Err(format!("expected quoted string, got `{trimmed}`"))
453    }
454}
455
456fn parse_toml_bool(val: &str) -> Option<bool> {
457    match val.trim() {
458        "true" => Some(true),
459        "false" => Some(false),
460        _ => None,
461    }
462}
463
464fn parse_toml_string_array(val: &str) -> Result<Vec<String>, String> {
465    let trimmed = val.trim();
466    if !trimmed.starts_with('[') || !trimmed.ends_with(']') {
467        return Err(format!("expected array [...], got `{trimmed}`"));
468    }
469    let inner = trimmed[1..trimmed.len() - 1].trim();
470    if inner.is_empty() {
471        return Ok(Vec::new());
472    }
473    let mut out = Vec::new();
474    for part in inner.split(',') {
475        let item = part.trim();
476        if !item.is_empty() {
477            out.push(parse_toml_string(item)?);
478        }
479    }
480    Ok(out)
481}
482
483#[cfg(test)]
484mod tests {
485    use super::*;
486
487    #[test]
488    fn request_trace_propagates_or_generates_id_and_traceparent() {
489        let req = HttpRequest::new("GET", "/api/v1/issues", "", Vec::new());
490        let tr = RequestTrace::from_request(&req);
491        assert!(tr.request_id.starts_with("req_"));
492        assert!(is_valid_traceparent(&tr.traceparent));
493
494        let custom_tp = "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01";
495        let req2 = HttpRequest::new("GET", "/api/v1/issues", "", Vec::new())
496            .with_header("X-Request-Id", "custom-123")
497            .with_header("traceparent", custom_tp);
498        let tr2 = RequestTrace::from_request(&req2);
499        assert_eq!(tr2.request_id, "custom-123");
500        assert_eq!(tr2.traceparent, custom_tp);
501
502        let log_json: serde_json::Value =
503            serde_json::from_str(&format_json_access_log(&tr2, &req2, 200, 12)).unwrap();
504        assert_eq!(log_json["request_id"], "custom-123");
505        assert_eq!(log_json["status"], 200);
506    }
507
508    #[test]
509    fn persistent_job_queue_enqueue_retry_backoff_and_dead_letter() {
510        let dir = tempfile::TempDir::new().unwrap();
511        let job = enqueue_job(
512            dir.path(),
513            "webhook.deliver",
514            serde_json::json!({"id": 1}),
515            2,
516        )
517        .unwrap();
518        assert_eq!(due_jobs(dir.path(), job.created_at + 1).len(), 1);
519
520        let after_fail = fail_job_with_backoff(dir.path(), job, "502 bad gateway", 1000).unwrap();
521        assert_eq!(after_fail.status, JobStatus::Pending);
522        assert_eq!(after_fail.attempts, 1);
523        assert!(after_fail.next_run_at > 1000);
524        assert!(due_jobs(dir.path(), 1001).is_empty());
525
526        let dead = fail_job_with_backoff(dir.path(), after_fail, "timeout", 2000).unwrap();
527        assert_eq!(dead.status, JobStatus::DeadLetter);
528        assert_eq!(list_jobs(dir.path()).len(), 1);
529    }
530
531    #[test]
532    fn typed_serve_config_parses_and_rejects_unknown_keys() {
533        let cfg = ServeConfig::from_toml_str(
534            r#"
535            [server]
536            bind = "0.0.0.0:8080"
537            shutdown_grace_secs = 45
538            trusted_proxies = ["10.0.0.0/8", "127.0.0.1/32"]
539
540            [ops]
541            log_format = "json"
542
543            [web]
544            pwa = false
545
546            [api]
547            rate_limit_per_min = 600
548            "#,
549        )
550        .unwrap();
551        assert_eq!(cfg.bind, "0.0.0.0:8080");
552        assert_eq!(cfg.shutdown_grace_secs, 45);
553        assert!(!cfg.pwa);
554        assert_eq!(cfg.log_format, "json");
555        assert_eq!(cfg.api_rate_limit_per_min, 600);
556
557        assert!(ServeConfig::from_toml_str("[server]\nunknown_opt = 1\n").is_err());
558        assert!(ServeConfig::from_toml_str("[ops]\nlog_format = \"xml\"\n").is_err());
559    }
560}