Skip to main content

rigspark_runtime/
state.rs

1use rigspark_core::catalog::BACKENDS;
2use serde::{Deserialize, Serialize};
3use serde_json::Value;
4use std::{
5    fs::{self, File, OpenOptions},
6    io::{Read, Write},
7    path::{Path, PathBuf},
8    time::{Duration, Instant},
9};
10use thiserror::Error;
11
12#[derive(Debug, Error)]
13#[error("{kind}: {message}")]
14pub struct StateError {
15    pub kind: &'static str,
16    pub message: String,
17}
18fn error(kind: &'static str, message: impl ToString) -> StateError {
19    StateError {
20        kind,
21        message: message.to_string(),
22    }
23}
24fn io(cause: std::io::Error) -> StateError {
25    error("io", cause)
26}
27fn check(condition: bool, message: &str) -> Result<(), StateError> {
28    if condition {
29        Ok(())
30    } else {
31        Err(error("invalid", message))
32    }
33}
34
35#[derive(Debug, Clone)]
36pub struct Config {
37    pub home: PathBuf,
38    pub state: PathBuf,
39    pub lock: PathBuf,
40    pub staging: PathBuf,
41}
42/// A non-blank `RIGSPARK_HOME` wins; otherwise `~/.rigspark` under the user's home.
43pub fn resolve_home(
44    custom: Option<&str>,
45    user_home: Option<std::ffi::OsString>,
46) -> Result<PathBuf, StateError> {
47    match custom.map(str::trim).filter(|value| !value.is_empty()) {
48        Some(value) => Ok(PathBuf::from(value)),
49        None => user_home
50            .map(|home| PathBuf::from(home).join(".rigspark"))
51            .ok_or_else(|| error("io", "cannot determine home directory")),
52    }
53}
54impl Config {
55    pub fn from_home(home: impl AsRef<Path>) -> Result<Self, StateError> {
56        let home = std::path::absolute(home).map_err(io)?;
57        Ok(Self {
58            state: home.join("state.json"),
59            lock: home.join("lock"),
60            staging: home.join(".staging"),
61            home,
62        })
63    }
64    pub fn load() -> Result<Self, StateError> {
65        Self::from_home(resolve_home(
66            std::env::var("RIGSPARK_HOME").ok().as_deref(),
67            std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE")),
68        )?)
69    }
70    pub fn user_backend(&self) -> Result<Option<String>, StateError> {
71        Ok(self.user_config()?.default_backend)
72    }
73    /// `config.json`: v1 names a default backend; v2 may add a default cache profile.
74    pub fn user_config(&self) -> Result<UserConfig, StateError> {
75        #[derive(Deserialize)]
76        #[serde(rename_all = "camelCase", deny_unknown_fields)]
77        struct Raw {
78            schema_version: u8,
79            default_backend: Option<String>,
80            cache: Option<crate::cache::CacheProfile>,
81        }
82        let raw = match secure_read(&self.home.join("config.json"), 4096, false) {
83            Ok(raw) => raw,
84            Err(cause) if cause.kind == "absent" => return Ok(UserConfig::default()),
85            Err(cause) => return Err(cause),
86        };
87        if raw.trim().is_empty() {
88            return Ok(UserConfig::default());
89        }
90        let parsed: Raw = serde_json::from_str(&raw).map_err(|cause| error("invalid", cause))?;
91        check(
92            match parsed.schema_version {
93                1 => parsed.default_backend.is_some() && parsed.cache.is_none(),
94                2 => true,
95                _ => false,
96            } && parsed
97                .default_backend
98                .as_deref()
99                .is_none_or(|backend| BACKENDS.contains(&backend)),
100            "invalid user config",
101        )?;
102        if let Some(cache) = &parsed.cache {
103            cache
104                .validate()
105                .map_err(|cause| error("invalid", format!("invalid user config: {cause}")))?;
106        }
107        Ok(UserConfig {
108            default_backend: parsed.default_backend,
109            cache: parsed.cache,
110        })
111    }
112}
113
114#[derive(Debug, Clone, Default, PartialEq)]
115pub struct UserConfig {
116    pub default_backend: Option<String>,
117    pub cache: Option<crate::cache::CacheProfile>,
118}
119
120#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
121#[serde(rename_all = "camelCase", deny_unknown_fields)]
122pub struct ServerState {
123    pub backend: String,
124    pub model_id: String,
125    pub endpoint: String,
126    pub port: u16,
127    pub owned_by_us: bool,
128    #[serde(skip_serializing_if = "Option::is_none")]
129    pub pid: Option<u32>,
130    #[serde(skip_serializing_if = "Option::is_none")]
131    pub runtime_model_id: Option<String>,
132    #[serde(skip_serializing_if = "Option::is_none")]
133    pub context: Option<u32>,
134    #[serde(skip_serializing_if = "Option::is_none")]
135    pub integrity: Option<String>,
136    #[serde(skip_serializing_if = "Option::is_none")]
137    pub local_manifest_digest: Option<String>,
138    #[serde(skip_serializing_if = "Option::is_none")]
139    pub model_path: Option<String>,
140    #[serde(skip_serializing_if = "Option::is_none")]
141    pub process_executable: Option<String>,
142    #[serde(skip_serializing_if = "Option::is_none")]
143    pub process_started_at: Option<String>,
144    #[serde(skip_serializing_if = "Option::is_none")]
145    pub auth_token: Option<String>,
146    #[serde(default, skip_serializing_if = "Option::is_none")]
147    pub cache: Option<crate::cache::CacheProfile>,
148}
149pub fn loopback(raw: &str) -> Result<url::Url, StateError> {
150    let url = url::Url::parse(raw).map_err(|cause| error("invalid", cause))?;
151    let local = match url.host() {
152        Some(url::Host::Ipv4(ip)) => ip.is_loopback(),
153        Some(url::Host::Ipv6(ip)) => ip.is_loopback(),
154        Some(url::Host::Domain(domain)) => domain.eq_ignore_ascii_case("localhost"),
155        None => false,
156    };
157    check(
158        url.scheme() == "http" && local && url.username().is_empty() && url.password().is_none(),
159        "endpoint must be unauthenticated loopback HTTP",
160    )?;
161    Ok(url)
162}
163fn hex(value: &str) -> bool {
164    value.len() == 64
165        && value
166            .bytes()
167            .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
168}
169impl ServerState {
170    pub fn validate(&self) -> Result<(), StateError> {
171        check(
172            BACKENDS.contains(&self.backend.as_str()) && !self.model_id.is_empty(),
173            "invalid backend or model id",
174        )?;
175        check(
176            self.port != 0 && loopback(&self.endpoint)?.port_or_known_default() == Some(self.port),
177            "endpoint port mismatch",
178        )?;
179        check(
180            self.pid != Some(0) && (!self.owned_by_us || self.pid.is_some()),
181            "owned process requires positive pid",
182        )?;
183        check(
184            self.context
185                .is_none_or(|context| (1..=10000000).contains(&context)),
186            "invalid context",
187        )?;
188        check(
189            self.integrity
190                .as_deref()
191                .is_none_or(|value| value == "local-manifest"),
192            "invalid integrity kind",
193        )?;
194        for sha in [&self.auth_token, &self.local_manifest_digest]
195            .into_iter()
196            .flatten()
197        {
198            check(hex(sha), "invalid digest or token")?;
199        }
200        for value in [
201            &self.model_path,
202            &self.process_executable,
203            &self.process_started_at,
204        ]
205        .into_iter()
206        .flatten()
207        {
208            check(!value.is_empty(), "empty process metadata")?;
209        }
210        if let Some(id) = &self.runtime_model_id {
211            check(
212                id.starts_with(|ch: char| ch.is_ascii_lowercase() || ch.is_ascii_digit())
213                    && id.bytes().all(|ch| {
214                        ch.is_ascii_lowercase() || ch.is_ascii_digit() || b"._:/-".contains(&ch)
215                    }),
216                "invalid runtime model id",
217            )?;
218        }
219        let complete = self.pid.is_some()
220            && self.process_executable.is_some()
221            && self.process_started_at.is_some();
222        let absent = self.pid.is_none()
223            && self.process_executable.is_none()
224            && self.process_started_at.is_none();
225        match self.backend.as_str() {
226            "mlx" => check(
227                self.owned_by_us && complete && self.auth_token.is_some(),
228                "MLX requires owned process identity and token",
229            )?,
230            "lmstudio" => check(
231                !self.owned_by_us
232                    && complete
233                    && self.model_path.is_some()
234                    && self.auth_token.is_none(),
235                "LM Studio requires attached identity and model path",
236            )?,
237            _ => {
238                check(self.auth_token.is_none(), "token only allowed for MLX")?;
239                check(
240                    self.owned_by_us || complete || absent,
241                    "partial attached identity",
242                )?;
243            }
244        }
245        check(
246            self.cache.is_none_or(|cache| {
247                cache != crate::cache::CacheProfile::default()
248                    && self.owned_by_us
249                    && ["ollama", "llamacpp"].contains(&self.backend.as_str())
250            }),
251            "a cache profile is recorded only for owned Ollama or llama.cpp runtimes",
252        )?;
253        check(
254            self.backend == "lmstudio" || self.model_path.is_none(),
255            "delegated path only allowed for LM Studio",
256        )
257    }
258}
259#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
260#[serde(rename_all = "camelCase", deny_unknown_fields)]
261pub struct RuntimeState {
262    pub schema_version: u8,
263    pub active: Option<ServerState>,
264}
265impl Default for RuntimeState {
266    fn default() -> Self {
267        Self {
268            schema_version: 2,
269            active: None,
270        }
271    }
272}
273impl RuntimeState {
274    /// Schema 3 is written only when a cache profile is recorded, so 1.0.x can still read other state.
275    pub fn for_active(active: ServerState) -> Self {
276        Self {
277            schema_version: if active.cache.is_some() { 3 } else { 2 },
278            active: Some(active),
279        }
280    }
281    pub fn parse(raw: &str) -> Result<Self, StateError> {
282        if raw.is_empty() {
283            return Err(error("empty", "state file is empty"));
284        }
285        check(raw.len() <= 1048576, "state exceeds 1 MiB")?;
286        let mut value: Value =
287            serde_json::from_str(raw).map_err(|cause| error("unparseable", cause))?;
288        check(
289            value.is_object() && value.get("active").is_some(),
290            "missing state fields",
291        )?;
292        if value["schemaVersion"] == 1 {
293            value["schemaVersion"] = Value::from(2);
294            if let Some(active) = value["active"].as_object_mut() {
295                active.entry("backend").or_insert(Value::from("ollama"));
296            }
297        }
298        if let Some(active) = value["active"].as_object_mut() {
299            if active.get("ownedByUs") == Some(&Value::Bool(false))
300                && active.get("pid") == Some(&Value::from(0))
301            {
302                active.remove("pid");
303            }
304            check(
305                !active.values().any(Value::is_null),
306                "null active metadata forbidden",
307            )?;
308        }
309        let state: Self = serde_json::from_value(value).map_err(|cause| error("invalid", cause))?;
310        state.validate()?;
311        Ok(state)
312    }
313    pub fn validate(&self) -> Result<(), StateError> {
314        check(
315            matches!(self.schema_version, 2 | 3),
316            "unsupported state schema",
317        )?;
318        let cached = self
319            .active
320            .as_ref()
321            .is_some_and(|active| active.cache.is_some());
322        check(
323            (self.schema_version == 3) == cached,
324            "state schema 3 is used exactly when a cache profile is applied",
325        )?;
326        if let Some(active) = &self.active {
327            active.validate()?;
328        }
329        Ok(())
330    }
331}
332
333fn nofollow_open(path: &Path) -> Result<File, StateError> {
334    let mut options = OpenOptions::new();
335    options.read(true);
336    #[cfg(unix)]
337    {
338        use std::os::unix::fs::OpenOptionsExt;
339        options.custom_flags(
340            rustix::fs::OFlags::NOFOLLOW.bits() as i32 | rustix::fs::OFlags::NONBLOCK.bits() as i32,
341        );
342    }
343    #[cfg(windows)]
344    {
345        use std::os::windows::fs::OpenOptionsExt;
346        options.custom_flags(0x00200000);
347    }
348    options.open(path).map_err(|cause| {
349        if cause.kind() == std::io::ErrorKind::NotFound {
350            error("absent", cause)
351        } else {
352            io(cause)
353        }
354    })
355}
356pub fn secure_read(path: &Path, maximum: u64, secret: bool) -> Result<String, StateError> {
357    let file = nofollow_open(path)?;
358    let metadata = file.metadata().map_err(io)?;
359    check(
360        metadata.is_file() && !metadata.file_type().is_symlink(),
361        "not a regular file",
362    )?;
363    #[cfg(unix)]
364    {
365        use std::os::unix::fs::MetadataExt;
366        check(
367            metadata.mode() & if secret { 0o077 } else { 0o022 } == 0,
368            "unsafe file permissions",
369        )?;
370    }
371    #[cfg(not(unix))]
372    let _ = secret;
373    check(metadata.len() <= maximum, "file exceeds byte limit")?;
374    let mut bytes = Vec::new();
375    file.take(maximum + 1).read_to_end(&mut bytes).map_err(io)?;
376    check(bytes.len() as u64 <= maximum, "file exceeds byte limit")?;
377    String::from_utf8(bytes).map_err(|cause| error("invalid", cause))
378}
379fn ensure_dir(path: &Path) -> Result<(), StateError> {
380    match fs::symlink_metadata(path) {
381        Ok(meta) => check(
382            meta.is_dir() && !meta.file_type().is_symlink(),
383            "unsafe state directory",
384        )?,
385        Err(cause) if cause.kind() == std::io::ErrorKind::NotFound => {
386            if let Some(parent) = path.parent() {
387                ensure_dir(parent)?;
388            }
389            let builder = fs::DirBuilder::new();
390            #[cfg(unix)]
391            let mut builder = builder;
392            #[cfg(unix)]
393            {
394                use std::os::unix::fs::DirBuilderExt;
395                builder.mode(0o700);
396            }
397            match builder.create(path) {
398                Ok(()) => (),
399                Err(cause) if cause.kind() == std::io::ErrorKind::AlreadyExists => {
400                    return ensure_dir(path);
401                }
402                Err(cause) => return Err(io(cause)),
403            }
404        }
405        Err(cause) => return Err(io(cause)),
406    }
407    Ok(())
408}
409fn private_dir(path: &Path) -> Result<(), StateError> {
410    ensure_dir(path)?;
411    #[cfg(unix)]
412    {
413        use std::os::unix::fs::PermissionsExt;
414        fs::set_permissions(path, fs::Permissions::from_mode(0o700)).map_err(io)?;
415    }
416    Ok(())
417}
418
419struct MutationGuard {
420    path: PathBuf,
421}
422impl MutationGuard {
423    fn acquire(lock: &Path, timeout: Duration) -> Result<Self, StateError> {
424        let mut guard_path = lock.as_os_str().to_owned();
425        guard_path.push(".guard");
426        let path = PathBuf::from(guard_path);
427        let deadline = Instant::now() + timeout;
428        loop {
429            let builder = fs::DirBuilder::new();
430            #[cfg(unix)]
431            let mut builder = builder;
432            #[cfg(unix)]
433            {
434                use std::os::unix::fs::DirBuilderExt;
435                builder.mode(0o700);
436            }
437            match builder.create(&path) {
438                Ok(()) => return Ok(Self { path }),
439                Err(cause) if cause.kind() == std::io::ErrorKind::AlreadyExists => (),
440                Err(cause) => return Err(io(cause)),
441            }
442            if Instant::now() >= deadline {
443                return Err(error(
444                    "locked",
445                    "lock guard busy or abandoned; explicit recovery required",
446                ));
447            }
448            std::thread::sleep(Duration::from_millis(5));
449        }
450    }
451}
452impl Drop for MutationGuard {
453    fn drop(&mut self) {
454        let _ = fs::remove_dir(&self.path);
455    }
456}
457pub struct LockGuard {
458    path: PathBuf,
459    identity: same_file::Handle,
460    released: bool,
461}
462impl LockGuard {
463    pub(crate) fn assert_for(&self, path: &Path) -> Result<(), StateError> {
464        self.assert_owned()?;
465        let expected = same_file::Handle::from_file(nofollow_open(path)?).map_err(io)?;
466        if expected != self.identity {
467            return Err(error("locked", "lock belongs to another store"));
468        }
469        Ok(())
470    }
471    pub fn assert_owned(&self) -> Result<(), StateError> {
472        let file = nofollow_open(&self.path)?;
473        check(file.metadata().map_err(io)?.is_file(), "invalid lock type")?;
474        let current = same_file::Handle::from_file(file).map_err(io)?;
475        if current != self.identity {
476            return Err(error("locked", "lock ownership changed"));
477        }
478        Ok(())
479    }
480    pub fn release(mut self) -> Result<(), StateError> {
481        let result = self.release_inner();
482        self.released = true;
483        result
484    }
485    fn release_inner(&self) -> Result<(), StateError> {
486        let _guard = MutationGuard::acquire(&self.path, Duration::from_secs(10))?;
487        self.assert_owned()?;
488        fs::remove_file(&self.path).map_err(io)
489    }
490}
491impl Drop for LockGuard {
492    fn drop(&mut self) {
493        if !self.released {
494            let _ = self.release_inner();
495        }
496    }
497}
498
499pub struct StateStore {
500    pub config: Config,
501}
502impl StateStore {
503    pub fn new(config: Config) -> Self {
504        Self { config }
505    }
506    pub fn read(&self) -> Result<RuntimeState, StateError> {
507        match secure_read(&self.config.state, 1048576, true) {
508            Ok(raw) => RuntimeState::parse(&raw),
509            // Windows reports "path not found" when home is a file, so absence alone is not proof of empty state.
510            Err(cause)
511                if cause.kind == "absent"
512                    && std::fs::symlink_metadata(&self.config.home)
513                        .map_or(true, |meta| meta.is_dir()) =>
514            {
515                Ok(RuntimeState::default())
516            }
517            Err(cause) if cause.kind == "absent" => {
518                Err(error("invalid", "state home is not a directory"))
519            }
520            Err(cause) => Err(cause),
521        }
522    }
523    pub fn lock(&self, timeout: Duration) -> Result<LockGuard, StateError> {
524        self.lock_with(timeout, process_alive)
525    }
526    pub fn lock_with(
527        &self,
528        timeout: Duration,
529        alive: impl Fn(u32) -> bool,
530    ) -> Result<LockGuard, StateError> {
531        private_dir(&self.config.home)?;
532        let deadline = Instant::now() + timeout;
533        loop {
534            {
535                let _guard = MutationGuard::acquire(
536                    &self.config.lock,
537                    deadline.saturating_duration_since(Instant::now()),
538                )?;
539                let mut options = OpenOptions::new();
540                options.write(true).read(true).create_new(true);
541                #[cfg(unix)]
542                {
543                    use std::os::unix::fs::OpenOptionsExt;
544                    options.mode(0o600);
545                }
546                match options.open(&self.config.lock) {
547                    Ok(mut file) => {
548                        if let Err(cause) =
549                            writeln!(file, "{}", std::process::id()).and_then(|()| file.sync_all())
550                        {
551                            let _ = fs::remove_file(&self.config.lock);
552                            return Err(io(cause));
553                        }
554                        return Ok(LockGuard {
555                            path: self.config.lock.clone(),
556                            identity: same_file::Handle::from_file(file).map_err(io)?,
557                            released: false,
558                        });
559                    }
560                    Err(cause) if cause.kind() == std::io::ErrorKind::AlreadyExists => {
561                        if holder_pid(&self.config.lock).is_some_and(|pid| !alive(pid)) {
562                            fs::remove_file(&self.config.lock).map_err(io)?;
563                            continue;
564                        }
565                    }
566                    Err(cause) => return Err(io(cause)),
567                }
568            }
569            if Instant::now() >= deadline {
570                return Err(error(
571                    "locked",
572                    "state lock busy or stale; explicit recovery required",
573                ));
574            }
575            std::thread::sleep(Duration::from_millis(5));
576        }
577    }
578    pub fn write(&self, guard: &LockGuard, state: &RuntimeState) -> Result<(), StateError> {
579        state.validate()?;
580        check(
581            guard.path == self.config.lock,
582            "guard belongs to another store",
583        )?;
584        let _mutation = MutationGuard::acquire(&self.config.lock, Duration::from_secs(10))?;
585        guard.assert_owned()?;
586        private_dir(&self.config.staging)?;
587        let mut temp = tempfile::NamedTempFile::new_in(&self.config.staging).map_err(io)?;
588        serde_json::to_writer_pretty(&mut temp, state).map_err(|cause| error("io", cause))?;
589        temp.write_all(b"\n").map_err(io)?;
590        temp.as_file().sync_all().map_err(io)?;
591        temp.persist(&self.config.state)
592            .map_err(|cause| io(cause.error))?;
593        #[cfg(unix)]
594        File::open(&self.config.home)
595            .and_then(|file| file.sync_all())
596            .map_err(io)?;
597        Ok(())
598    }
599    pub fn compare_and_write(
600        &self,
601        guard: &LockGuard,
602        expected: &RuntimeState,
603        next: &RuntimeState,
604    ) -> Result<(), StateError> {
605        check(self.read()? == *expected, "state changed since preparation")?;
606        self.write(guard, next)
607    }
608}
609
610fn holder_pid(path: &Path) -> Option<u32> {
611    let raw = secure_read(path, 64, false).ok()?;
612    let raw = raw.trim();
613    if raw.starts_with('0') || !raw.bytes().all(|byte| byte.is_ascii_digit()) {
614        return None;
615    }
616    raw.parse::<u32>()
617        .ok()
618        .filter(|pid| *pid > 0 && *pid <= i32::MAX as u32)
619}
620
621pub(crate) fn process_alive(pid: u32) -> bool {
622    #[cfg(unix)]
623    {
624        let Some(pid) = i32::try_from(pid)
625            .ok()
626            .and_then(rustix::process::Pid::from_raw)
627        else {
628            return true;
629        };
630        !matches!(
631            rustix::process::test_kill_process(pid),
632            Err(rustix::io::Errno::SRCH)
633        )
634    }
635    #[cfg(not(unix))]
636    {
637        let _ = pid;
638        true
639    }
640}