Skip to main content

khive_runtime/operations/
resolve_uuid_or_prefix.rs

1//! Shared UUID-or-prefix resolution for pack handlers.
2
3use uuid::Uuid;
4
5use crate::error::{RuntimeError, RuntimeResult};
6use crate::runtime::{KhiveRuntime, NamespaceToken};
7use crate::secret_gate::{mask_for_redaction_surface, RedactionSurface};
8
9impl KhiveRuntime {
10    /// Parse a full UUID or resolve a compact hexadecimal prefix in the caller's
11    /// primary namespace, using the same lookup policy as [`Self::resolve_prefix`].
12    ///
13    /// A parseable full UUID is returned without a lookup or an existence,
14    /// liveness or authorization check. Otherwise input must contain at least
15    /// eight ASCII hexadecimal characters with no separators or whitespace.
16    /// Missing prefixes and invalid shapes return distinct `InvalidInput` errors;
17    /// lookup storage and ambiguity errors propagate unchanged.
18    pub async fn resolve_uuid_or_prefix(
19        &self,
20        token: &NamespaceToken,
21        s: &str,
22    ) -> RuntimeResult<Uuid> {
23        self.resolve_uuid_or_prefix_inner(token, s, None).await
24    }
25
26    /// Resolve as [`Self::resolve_uuid_or_prefix`], with the comm/schedule
27    /// validation messages prefixed by `verb`. Lookup errors, including
28    /// ambiguous prefixes and storage failures, propagate unchanged.
29    pub async fn resolve_uuid_or_prefix_for_verb(
30        &self,
31        token: &NamespaceToken,
32        s: &str,
33        verb: &str,
34    ) -> RuntimeResult<Uuid> {
35        self.resolve_uuid_or_prefix_inner(token, s, Some(verb))
36            .await
37    }
38
39    async fn resolve_uuid_or_prefix_inner(
40        &self,
41        token: &NamespaceToken,
42        s: &str,
43        verb: Option<&str>,
44    ) -> RuntimeResult<Uuid> {
45        if let Ok(uuid) = s.parse::<Uuid>() {
46            return Ok(uuid);
47        }
48        if s.len() >= 8 && s.chars().all(|c| c.is_ascii_hexdigit()) {
49            return match self.resolve_prefix(token, s).await? {
50                Some(uuid) => Ok(uuid),
51                None => {
52                    let s = mask_for_redaction_surface(RedactionSurface::GateProbe, s);
53                    Err(RuntimeError::InvalidInput(match verb {
54                        Some(verb) => format!("{verb}: no record matches prefix: {s:?}"),
55                        None => format!("no record matches prefix: {s:?}"),
56                    }))
57                }
58            };
59        }
60        let s = mask_for_redaction_surface(RedactionSurface::GateProbe, s);
61        Err(RuntimeError::InvalidInput(match verb {
62            Some(verb) => {
63                format!("{verb}: invalid id {s:?}; expected full UUID or 8-char hex prefix")
64            }
65            None => format!("invalid UUID (expected full UUID or 8+ hex prefix): {s:?}"),
66        }))
67    }
68}