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            "bitnet" => check(
238                self.owned_by_us
239                    && complete
240                    && self.model_path.is_some()
241                    && self.auth_token.is_none()
242                    && self
243                        .context
244                        .is_some_and(|context| (1..=4096).contains(&context)),
245                "BitNet requires owned identity, model path and bounded context",
246            )?,
247            _ => {
248                check(self.auth_token.is_none(), "token only allowed for MLX")?;
249                check(
250                    self.owned_by_us || complete || absent,
251                    "partial attached identity",
252                )?;
253            }
254        }
255        check(
256            self.cache.is_none_or(|cache| {
257                cache != crate::cache::CacheProfile::default()
258                    && self.owned_by_us
259                    && ["ollama", "llamacpp"].contains(&self.backend.as_str())
260            }),
261            "a cache profile is recorded only for owned Ollama or llama.cpp runtimes",
262        )?;
263        check(
264            ["lmstudio", "bitnet"].contains(&self.backend.as_str()) || self.model_path.is_none(),
265            "model path only allowed for LM Studio or BitNet",
266        )
267    }
268}
269#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
270#[serde(rename_all = "camelCase", deny_unknown_fields)]
271pub struct RuntimeState {
272    pub schema_version: u8,
273    pub active: Option<ServerState>,
274}
275impl Default for RuntimeState {
276    fn default() -> Self {
277        Self {
278            schema_version: 2,
279            active: None,
280        }
281    }
282}
283impl RuntimeState {
284    /// Schema 3 is written only when a cache profile is recorded, so 1.0.x can still read other state.
285    pub fn for_active(active: ServerState) -> Self {
286        Self {
287            schema_version: if active.cache.is_some() { 3 } else { 2 },
288            active: Some(active),
289        }
290    }
291    pub fn parse(raw: &str) -> Result<Self, StateError> {
292        if raw.is_empty() {
293            return Err(error("empty", "state file is empty"));
294        }
295        check(raw.len() <= 1048576, "state exceeds 1 MiB")?;
296        let mut value: Value =
297            serde_json::from_str(raw).map_err(|cause| error("unparseable", cause))?;
298        check(
299            value.is_object() && value.get("active").is_some(),
300            "missing state fields",
301        )?;
302        if value["schemaVersion"] == 1 {
303            value["schemaVersion"] = Value::from(2);
304            if let Some(active) = value["active"].as_object_mut() {
305                active.entry("backend").or_insert(Value::from("ollama"));
306            }
307        }
308        if let Some(active) = value["active"].as_object_mut() {
309            if active.get("ownedByUs") == Some(&Value::Bool(false))
310                && active.get("pid") == Some(&Value::from(0))
311            {
312                active.remove("pid");
313            }
314            check(
315                !active.values().any(Value::is_null),
316                "null active metadata forbidden",
317            )?;
318        }
319        let state: Self = serde_json::from_value(value).map_err(|cause| error("invalid", cause))?;
320        state.validate()?;
321        Ok(state)
322    }
323    pub fn validate(&self) -> Result<(), StateError> {
324        check(
325            matches!(self.schema_version, 2 | 3),
326            "unsupported state schema",
327        )?;
328        let cached = self
329            .active
330            .as_ref()
331            .is_some_and(|active| active.cache.is_some());
332        check(
333            (self.schema_version == 3) == cached,
334            "state schema 3 is used exactly when a cache profile is applied",
335        )?;
336        if let Some(active) = &self.active {
337            active.validate()?;
338        }
339        Ok(())
340    }
341}
342
343fn nofollow_open(path: &Path) -> Result<File, StateError> {
344    let mut options = OpenOptions::new();
345    options.read(true);
346    #[cfg(unix)]
347    {
348        use std::os::unix::fs::OpenOptionsExt;
349        options.custom_flags(
350            rustix::fs::OFlags::NOFOLLOW.bits() as i32 | rustix::fs::OFlags::NONBLOCK.bits() as i32,
351        );
352    }
353    #[cfg(windows)]
354    {
355        use std::os::windows::fs::OpenOptionsExt;
356        options.custom_flags(0x00200000);
357    }
358    options.open(path).map_err(|cause| {
359        if cause.kind() == std::io::ErrorKind::NotFound {
360            error("absent", cause)
361        } else {
362            io(cause)
363        }
364    })
365}
366pub fn secure_read(path: &Path, maximum: u64, secret: bool) -> Result<String, StateError> {
367    let file = nofollow_open(path)?;
368    let metadata = file.metadata().map_err(io)?;
369    check(
370        metadata.is_file() && !metadata.file_type().is_symlink(),
371        "not a regular file",
372    )?;
373    #[cfg(unix)]
374    {
375        use std::os::unix::fs::MetadataExt;
376        check(
377            metadata.mode() & if secret { 0o077 } else { 0o022 } == 0,
378            "unsafe file permissions",
379        )?;
380    }
381    #[cfg(not(unix))]
382    let _ = secret;
383    check(metadata.len() <= maximum, "file exceeds byte limit")?;
384    let mut bytes = Vec::new();
385    file.take(maximum + 1).read_to_end(&mut bytes).map_err(io)?;
386    check(bytes.len() as u64 <= maximum, "file exceeds byte limit")?;
387    String::from_utf8(bytes).map_err(|cause| error("invalid", cause))
388}
389fn ensure_dir(path: &Path) -> Result<(), StateError> {
390    match fs::symlink_metadata(path) {
391        Ok(meta) => check(
392            meta.is_dir() && !meta.file_type().is_symlink(),
393            "unsafe state directory",
394        )?,
395        Err(cause) if cause.kind() == std::io::ErrorKind::NotFound => {
396            if let Some(parent) = path.parent() {
397                ensure_dir(parent)?;
398            }
399            let builder = fs::DirBuilder::new();
400            #[cfg(unix)]
401            let mut builder = builder;
402            #[cfg(unix)]
403            {
404                use std::os::unix::fs::DirBuilderExt;
405                builder.mode(0o700);
406            }
407            match builder.create(path) {
408                Ok(()) => (),
409                Err(cause) if cause.kind() == std::io::ErrorKind::AlreadyExists => {
410                    return ensure_dir(path);
411                }
412                Err(cause) => return Err(io(cause)),
413            }
414        }
415        Err(cause) => return Err(io(cause)),
416    }
417    Ok(())
418}
419fn private_dir(path: &Path) -> Result<(), StateError> {
420    ensure_dir(path)?;
421    #[cfg(unix)]
422    {
423        use std::os::unix::fs::PermissionsExt;
424        fs::set_permissions(path, fs::Permissions::from_mode(0o700)).map_err(io)?;
425    }
426    Ok(())
427}
428
429struct MutationGuard {
430    path: PathBuf,
431}
432impl MutationGuard {
433    fn acquire(lock: &Path, timeout: Duration) -> Result<Self, StateError> {
434        let mut guard_path = lock.as_os_str().to_owned();
435        guard_path.push(".guard");
436        let path = PathBuf::from(guard_path);
437        let deadline = Instant::now() + timeout;
438        loop {
439            let builder = fs::DirBuilder::new();
440            #[cfg(unix)]
441            let mut builder = builder;
442            #[cfg(unix)]
443            {
444                use std::os::unix::fs::DirBuilderExt;
445                builder.mode(0o700);
446            }
447            match builder.create(&path) {
448                Ok(()) => return Ok(Self { path }),
449                Err(cause) if cause.kind() == std::io::ErrorKind::AlreadyExists => (),
450                Err(cause) => return Err(io(cause)),
451            }
452            if Instant::now() >= deadline {
453                return Err(error(
454                    "locked",
455                    "lock guard busy or abandoned; explicit recovery required",
456                ));
457            }
458            std::thread::sleep(Duration::from_millis(5));
459        }
460    }
461}
462impl Drop for MutationGuard {
463    fn drop(&mut self) {
464        let _ = fs::remove_dir(&self.path);
465    }
466}
467pub struct LockGuard {
468    path: PathBuf,
469    identity: same_file::Handle,
470    released: bool,
471}
472impl LockGuard {
473    pub(crate) fn assert_for(&self, path: &Path) -> Result<(), StateError> {
474        self.assert_owned()?;
475        let expected = same_file::Handle::from_file(nofollow_open(path)?).map_err(io)?;
476        if expected != self.identity {
477            return Err(error("locked", "lock belongs to another store"));
478        }
479        Ok(())
480    }
481    pub fn assert_owned(&self) -> Result<(), StateError> {
482        let file = nofollow_open(&self.path)?;
483        check(file.metadata().map_err(io)?.is_file(), "invalid lock type")?;
484        let current = same_file::Handle::from_file(file).map_err(io)?;
485        if current != self.identity {
486            return Err(error("locked", "lock ownership changed"));
487        }
488        Ok(())
489    }
490    pub fn release(mut self) -> Result<(), StateError> {
491        let result = self.release_inner();
492        self.released = true;
493        result
494    }
495    fn release_inner(&self) -> Result<(), StateError> {
496        let _guard = MutationGuard::acquire(&self.path, Duration::from_secs(10))?;
497        self.assert_owned()?;
498        fs::remove_file(&self.path).map_err(io)
499    }
500}
501impl Drop for LockGuard {
502    fn drop(&mut self) {
503        if !self.released {
504            let _ = self.release_inner();
505        }
506    }
507}
508
509pub struct StateStore {
510    pub config: Config,
511}
512impl StateStore {
513    pub fn new(config: Config) -> Self {
514        Self { config }
515    }
516    pub fn read(&self) -> Result<RuntimeState, StateError> {
517        match secure_read(&self.config.state, 1048576, true) {
518            Ok(raw) => RuntimeState::parse(&raw),
519            // Windows reports "path not found" when home is a file, so absence alone is not proof of empty state.
520            Err(cause)
521                if cause.kind == "absent"
522                    && std::fs::symlink_metadata(&self.config.home)
523                        .map_or(true, |meta| meta.is_dir()) =>
524            {
525                Ok(RuntimeState::default())
526            }
527            Err(cause) if cause.kind == "absent" => {
528                Err(error("invalid", "state home is not a directory"))
529            }
530            Err(cause) => Err(cause),
531        }
532    }
533    pub fn lock(&self, timeout: Duration) -> Result<LockGuard, StateError> {
534        self.lock_with(timeout, process_alive)
535    }
536    pub fn lock_with(
537        &self,
538        timeout: Duration,
539        alive: impl Fn(u32) -> bool,
540    ) -> Result<LockGuard, StateError> {
541        private_dir(&self.config.home)?;
542        let deadline = Instant::now() + timeout;
543        loop {
544            {
545                let _guard = MutationGuard::acquire(
546                    &self.config.lock,
547                    deadline.saturating_duration_since(Instant::now()),
548                )?;
549                let mut options = OpenOptions::new();
550                options.write(true).read(true).create_new(true);
551                #[cfg(unix)]
552                {
553                    use std::os::unix::fs::OpenOptionsExt;
554                    options.mode(0o600);
555                }
556                match options.open(&self.config.lock) {
557                    Ok(mut file) => {
558                        if let Err(cause) =
559                            writeln!(file, "{}", std::process::id()).and_then(|()| file.sync_all())
560                        {
561                            let _ = fs::remove_file(&self.config.lock);
562                            return Err(io(cause));
563                        }
564                        return Ok(LockGuard {
565                            path: self.config.lock.clone(),
566                            identity: same_file::Handle::from_file(file).map_err(io)?,
567                            released: false,
568                        });
569                    }
570                    Err(cause) if cause.kind() == std::io::ErrorKind::AlreadyExists => {
571                        if holder_pid(&self.config.lock).is_some_and(|pid| !alive(pid)) {
572                            fs::remove_file(&self.config.lock).map_err(io)?;
573                            continue;
574                        }
575                    }
576                    Err(cause) => return Err(io(cause)),
577                }
578            }
579            if Instant::now() >= deadline {
580                return Err(error(
581                    "locked",
582                    "state lock busy or stale; explicit recovery required",
583                ));
584            }
585            std::thread::sleep(Duration::from_millis(5));
586        }
587    }
588    pub fn write(&self, guard: &LockGuard, state: &RuntimeState) -> Result<(), StateError> {
589        state.validate()?;
590        check(
591            guard.path == self.config.lock,
592            "guard belongs to another store",
593        )?;
594        let _mutation = MutationGuard::acquire(&self.config.lock, Duration::from_secs(10))?;
595        guard.assert_owned()?;
596        private_dir(&self.config.staging)?;
597        let mut temp = tempfile::NamedTempFile::new_in(&self.config.staging).map_err(io)?;
598        serde_json::to_writer_pretty(&mut temp, state).map_err(|cause| error("io", cause))?;
599        temp.write_all(b"\n").map_err(io)?;
600        temp.as_file().sync_all().map_err(io)?;
601        temp.persist(&self.config.state)
602            .map_err(|cause| io(cause.error))?;
603        #[cfg(unix)]
604        File::open(&self.config.home)
605            .and_then(|file| file.sync_all())
606            .map_err(io)?;
607        Ok(())
608    }
609    pub fn compare_and_write(
610        &self,
611        guard: &LockGuard,
612        expected: &RuntimeState,
613        next: &RuntimeState,
614    ) -> Result<(), StateError> {
615        check(self.read()? == *expected, "state changed since preparation")?;
616        self.write(guard, next)
617    }
618}
619
620fn holder_pid(path: &Path) -> Option<u32> {
621    let raw = secure_read(path, 64, false).ok()?;
622    let raw = raw.trim();
623    if raw.starts_with('0') || !raw.bytes().all(|byte| byte.is_ascii_digit()) {
624        return None;
625    }
626    raw.parse::<u32>()
627        .ok()
628        .filter(|pid| *pid > 0 && *pid <= i32::MAX as u32)
629}
630
631pub(crate) fn process_alive(pid: u32) -> bool {
632    #[cfg(unix)]
633    {
634        let Some(pid) = i32::try_from(pid)
635            .ok()
636            .and_then(rustix::process::Pid::from_raw)
637        else {
638            return true;
639        };
640        !matches!(
641            rustix::process::test_kill_process(pid),
642            Err(rustix::io::Errno::SRCH)
643        )
644    }
645    #[cfg(not(unix))]
646    {
647        let _ = pid;
648        true
649    }
650}