Skip to main content

qualia_app_contract/
id.rs

1//! Identifiers and safe numeric types for application contracts.
2
3use crate::error::ContractError;
4use serde::{de, Deserialize, Deserializer, Serialize, Serializer};
5use std::fmt;
6use std::str::FromStr;
7
8/// Maximum integer safely representable in JavaScript IEEE-754 numbers (2^53 - 1).
9pub const JS_MAX_SAFE_INTEGER: u64 = 9_007_199_254_740_991;
10
11/// Application identifier (e.g. `gridcraft`, `wordcraft`, `poet`).
12#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
13#[serde(transparent)]
14pub struct AppId(String);
15
16impl AppId {
17    /// Create and validate a new AppId.
18    pub fn new(id: impl Into<String>) -> Result<Self, ContractError> {
19        let s = id.into();
20        if s.trim().is_empty() {
21            return Err(ContractError::EmptyAppId);
22        }
23        if !s.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_' || c == '.') {
24            return Err(ContractError::InvalidCommandIdFormat(s));
25        }
26        Ok(Self(s))
27    }
28
29    /// `&str` form.
30    pub fn as_str(&self) -> &str {
31        &self.0
32    }
33}
34
35impl fmt::Display for AppId {
36    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
37        write!(f, "{}", self.0)
38    }
39}
40
41impl FromStr for AppId {
42    type Err = ContractError;
43    fn from_str(s: &str) -> Result<Self, Self::Err> {
44        Self::new(s)
45    }
46}
47
48/// Fully-qualified command identifier following the `<app-id>::<upstream-id>` schema.
49#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
50#[serde(transparent)]
51pub struct CommandId(String);
52
53impl CommandId {
54    /// Parse and validate a command identifier.
55    pub fn parse(raw: impl Into<String>) -> Result<Self, ContractError> {
56        let s = raw.into();
57        if s.trim().is_empty() {
58            return Err(ContractError::EmptyCommandId);
59        }
60
61        let parts: Vec<&str> = s.split("::").collect();
62        if parts.len() != 2 {
63            return Err(ContractError::InvalidCommandIdFormat(s));
64        }
65
66        let app_part = parts[0];
67        let cmd_part = parts[1];
68
69        if app_part.is_empty()
70            || cmd_part.is_empty()
71            || !app_part.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_' || c == '.')
72            || !cmd_part.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_' || c == '.')
73        {
74            return Err(ContractError::InvalidCommandIdFormat(s));
75        }
76
77        Ok(Self(s))
78    }
79
80    /// Construct a command identifier from app ID and upstream ID.
81    pub fn from_parts(app_id: &AppId, upstream_id: &str) -> Result<Self, ContractError> {
82        Self::parse(format!("{}::{}", app_id.as_str(), upstream_id))
83    }
84
85    /// `&str` form.
86    pub fn as_str(&self) -> &str {
87        &self.0
88    }
89
90    /// `app` ID.
91    pub fn app_id(&self) -> &str {
92        self.0.split("::").next().unwrap_or("")
93    }
94
95    /// `upstream` ID.
96    pub fn upstream_id(&self) -> &str {
97        self.0.split("::").nth(1).unwrap_or("")
98    }
99}
100
101impl fmt::Display for CommandId {
102    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
103        write!(f, "{}", self.0)
104    }
105}
106
107impl FromStr for CommandId {
108    type Err = ContractError;
109    fn from_str(s: &str) -> Result<Self, Self::Err> {
110        Self::parse(s)
111    }
112}
113
114/// A 64-bit unsigned integer that is serialized as a decimal string in JSON
115/// to prevent precision loss across JavaScript, browser, and JSON boundaries.
116#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
117pub struct DecimalU64(pub u64);
118
119impl DecimalU64 {
120    /// Creates a new instance.
121    pub fn new(val: u64) -> Self {
122        Self(val)
123    }
124
125    /// Gets a value.
126    pub fn get(&self) -> u64 {
127        self.0
128    }
129}
130
131impl fmt::Display for DecimalU64 {
132    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
133        write!(f, "{}", self.0)
134    }
135}
136
137impl From<u64> for DecimalU64 {
138    fn from(val: u64) -> Self {
139        Self(val)
140    }
141}
142
143impl From<DecimalU64> for u64 {
144    fn from(val: DecimalU64) -> Self {
145        val.0
146    }
147}
148
149impl FromStr for DecimalU64 {
150    type Err = ContractError;
151    fn from_str(s: &str) -> Result<Self, Self::Err> {
152        let trimmed = s.trim();
153        trimmed
154            .parse::<u64>()
155            .map(Self)
156            .map_err(|_| ContractError::InvalidDecimalU64(s.to_string()))
157    }
158}
159
160impl Serialize for DecimalU64 {
161    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
162    where
163        S: Serializer,
164    {
165        serializer.serialize_str(&self.0.to_string())
166    }
167}
168
169impl<'de> Deserialize<'de> for DecimalU64 {
170    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
171    where
172        D: Deserializer<'de>,
173    {
174        struct DecimalU64Visitor;
175
176        impl<'de> de::Visitor<'de> for DecimalU64Visitor {
177            type Value = DecimalU64;
178
179            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
180                formatter.write_str("a decimal string representing a u64, or a safe integer <= 2^53 - 1")
181            }
182
183            fn visit_str<E>(self, value: &str) -> Result<DecimalU64, E>
184            where
185                E: de::Error,
186            {
187                DecimalU64::from_str(value).map_err(de::Error::custom)
188            }
189
190            fn visit_u64<E>(self, value: u64) -> Result<DecimalU64, E>
191            where
192                E: de::Error,
193            {
194                if value > JS_MAX_SAFE_INTEGER {
195                    return Err(de::Error::custom(ContractError::JsUnsafeNumericConversion(value)));
196                }
197                Ok(DecimalU64(value))
198            }
199
200            fn visit_i64<E>(self, value: i64) -> Result<DecimalU64, E>
201            where
202                E: de::Error,
203            {
204                if value < 0 {
205                    return Err(de::Error::custom("u64 cannot be negative"));
206                }
207                self.visit_u64(value as u64)
208            }
209        }
210
211        deserializer.deserialize_any(DecimalU64Visitor)
212    }
213}
214
215/// Helper function to validate that a floating point value is strictly finite.
216pub fn validate_finite_f64(val: f64, field_name: &str) -> Result<f64, ContractError> {
217    if !val.is_finite() {
218        return Err(ContractError::NonFiniteCoordinate(format!(
219            "field '{}' has non-finite value {}",
220            field_name, val
221        )));
222    }
223    Ok(val)
224}