1use serde::{Deserialize, Serialize};
47
48use super::{require_schema, validate_id};
49use crate::{UtcTimestamp, ValidationError};
50
51#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
54#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
55pub enum NetworkV1 {
56 Org { channel: String },
57}
58
59impl NetworkV1 {
60 pub fn validate(&self) -> Result<(), ValidationError> {
61 match self {
62 Self::Org { channel } => validate_channel(channel),
63 }
64 }
65}
66
67fn validate_channel(channel: &str) -> Result<(), ValidationError> {
69 let mut parts = channel.splitn(3, '/');
70 let org = parts.next().and_then(|part| part.strip_prefix("org:"));
71 let vault = parts.next().and_then(|part| part.strip_prefix("vault:"));
72 let name = parts.next();
73 match (org, vault, name) {
74 (Some(org), Some(vault), Some(name)) => {
75 validate_id(org, "channel org")?;
76 super::validate_vault_id(vault)?;
77 validate_id(name, "channel name")
78 }
79 _ => Err(ValidationError::new(
80 "channel must be org:<org>/vault:<vault>/<name>",
81 )),
82 }
83}
84
85pub const ENGINE_OPTIN_SCHEMA: &str = "leanctx.cloud.instance-optin/v1";
86pub const ENGINE_OPTIN_STOP_SCHEMA: &str = "leanctx.cloud.instance-optin-stop/v1";
87pub const ENGINE_OPTIN_ON_SCHEMA: &str = "leanctx.cloud.instance-optin-on/v1";
89pub const OPTIN_SIGNING_DOMAIN: &str = "leanctx.cloud.optin.v1\n";
91pub const DEFAULT_DAILY_TASKS: u32 = 5;
92pub const MAX_DAILY_TASKS: u32 = 100;
93pub const MAX_OPTIN_VAULTS: usize = 200;
94pub const MAX_OPTIN_NETWORKS: usize = 200;
95
96#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
99pub struct DailyBudgetV1 {
100 #[serde(default, skip_serializing_if = "Option::is_none")]
102 pub tasks: Option<u32>,
103 #[serde(default, skip_serializing_if = "Option::is_none")]
104 pub tokens: Option<u64>,
105 #[serde(default, skip_serializing_if = "Option::is_none")]
106 pub usd_micros: Option<u64>,
107}
108
109impl DailyBudgetV1 {
110 pub const AUTO: Self = Self {
114 tasks: Some(3),
115 tokens: Some(1_000_000),
116 usd_micros: None,
117 };
118
119 pub fn validate(&self) -> Result<(), ValidationError> {
121 if self
122 .tasks
123 .is_some_and(|t| !(1..=MAX_DAILY_TASKS).contains(&t))
124 || self.tokens == Some(0)
125 {
126 return Err(ValidationError::new(
127 "daily_budget is 1-100 tasks or none, and a non-zero token limit",
128 ));
129 }
130 Ok(())
131 }
132}
133
134impl Default for DailyBudgetV1 {
135 fn default() -> Self {
136 Self {
137 tasks: Some(DEFAULT_DAILY_TASKS),
138 tokens: None,
139 usd_micros: None,
140 }
141 }
142}
143
144#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
146pub struct DailyUsageV1 {
147 pub day: String,
149 pub tasks: u32,
150 pub tokens: u64,
151 pub usd_micros: u64,
152}
153
154#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
156pub struct EngineOptinV1 {
157 pub schema: String,
158 #[serde(default, skip_serializing_if = "Option::is_none")]
161 pub optin_id: Option<String>,
162 pub active: bool,
163 #[serde(default)]
165 pub vaults: Vec<String>,
166 #[serde(default)]
168 pub networks: Vec<NetworkV1>,
169 pub daily_budget: DailyBudgetV1,
170 pub used_today: DailyUsageV1,
171 #[serde(default, skip_serializing_if = "Option::is_none")]
172 pub stopped_at: Option<UtcTimestamp>,
173 #[serde(default, skip_serializing_if = "Option::is_none")]
174 pub updated_at: Option<UtcTimestamp>,
175}
176
177fn day_ok(day: &str) -> bool {
178 let b = day.as_bytes();
179 b.len() == 10
180 && b[4] == b'-'
181 && b[7] == b'-'
182 && [0..4, 5..7, 8..10]
183 .iter()
184 .all(|r| b[r.clone()].iter().all(u8::is_ascii_digit))
185}
186
187impl EngineOptinV1 {
188 pub fn validate(&self) -> Result<(), ValidationError> {
189 require_schema(&self.schema, ENGINE_OPTIN_SCHEMA)?;
190 match &self.optin_id {
191 Some(id) => validate_id(id, "optin_id")?,
192 None if self.active || !self.vaults.is_empty() || !self.networks.is_empty() => {
193 return Err(ValidationError::new(
194 "an engine without opt-in is inactive with empty scope",
195 ));
196 }
197 None => {}
198 }
199 if self.vaults.len() > MAX_OPTIN_VAULTS || self.networks.len() > MAX_OPTIN_NETWORKS {
200 return Err(ValidationError::new(format!(
201 "at most {MAX_OPTIN_VAULTS} vaults and {MAX_OPTIN_NETWORKS} networks"
202 )));
203 }
204 for (i, vault) in self.vaults.iter().enumerate() {
205 super::validate_vault_id(vault)?;
206 if i > 0 && self.vaults[i - 1] >= *vault {
207 return Err(ValidationError::new(
208 "vaults must be sorted without repeats",
209 ));
210 }
211 }
212 self.daily_budget.validate()?;
213 if !day_ok(&self.used_today.day) {
214 return Err(ValidationError::new("used_today.day is YYYY-MM-DD"));
215 }
216 if self.active == self.stopped_at.is_some() && self.optin_id.is_some() {
217 return Err(ValidationError::new(
218 "stopped_at is set exactly while the opt-in is inactive",
219 ));
220 }
221 Ok(())
222 }
223}
224
225#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
227#[serde(deny_unknown_fields)]
228pub struct EngineOptinStopV1 {
229 pub schema: String,
230 pub active: bool,
232}
233
234impl EngineOptinStopV1 {
235 pub fn validate(&self) -> Result<(), ValidationError> {
236 require_schema(&self.schema, ENGINE_OPTIN_STOP_SCHEMA)?;
237 if self.active {
238 return Err(ValidationError::new("an engine can only stop its opt-in"));
239 }
240 Ok(())
241 }
242}
243
244#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
253#[serde(deny_unknown_fields)]
254pub struct EngineOptinOnV1 {
255 pub schema: String,
256 pub active: bool,
258 pub prev_optin_id: Option<String>,
261 #[serde(default, skip_serializing_if = "Option::is_none")]
263 pub vaults: Option<Vec<String>>,
264 pub daily_budget: DailyBudgetV1,
265 #[serde(default, skip_serializing_if = "Option::is_none")]
266 pub presence_signature: Option<String>,
267}
268
269impl EngineOptinOnV1 {
270 pub fn validate(&self) -> Result<(), ValidationError> {
271 require_schema(&self.schema, ENGINE_OPTIN_ON_SCHEMA)?;
272 if !self.active {
273 return Err(ValidationError::new(
274 "a turn-on is active; a stop is the stop schema",
275 ));
276 }
277 if let Some(id) = &self.prev_optin_id {
278 validate_id(id, "prev_optin_id")?;
279 }
280 let vaults = self.vaults.as_deref().unwrap_or_default();
281 if vaults.len() > MAX_OPTIN_VAULTS {
282 return Err(ValidationError::new(format!(
283 "at most {MAX_OPTIN_VAULTS} vaults"
284 )));
285 }
286 for vault in vaults {
287 super::validate_vault_id(vault)?;
288 }
289 self.daily_budget.validate()
290 }
291}
292
293#[cfg(test)]
294mod on_tests {
295 use super::*;
296
297 fn on() -> EngineOptinOnV1 {
298 EngineOptinOnV1 {
299 schema: ENGINE_OPTIN_ON_SCHEMA.into(),
300 active: true,
301 prev_optin_id: None,
302 vaults: Some(vec!["0f3c2b6a8d4e4a7b9c105e2f6a7b8c01".into()]),
303 daily_budget: DailyBudgetV1::AUTO,
304 presence_signature: None,
305 }
306 }
307
308 #[test]
309 fn pickup_turn_on_body_keeps_a_null_prev_optin_id_and_the_auto_budget() {
310 let body = serde_json::to_value(on()).unwrap();
311 assert!(body["prev_optin_id"].is_null());
312 assert!(body.as_object().unwrap().contains_key("prev_optin_id"));
313 assert!(!body.as_object().unwrap().contains_key("presence_signature"));
314 assert_eq!(
315 body["daily_budget"],
316 serde_json::json!({"tasks": 3, "tokens": 1_000_000})
317 );
318 on().validate().unwrap();
319 }
320
321 #[test]
322 fn pickup_turn_on_refuses_a_stop_a_bad_vault_and_a_bad_budget() {
323 let mut stop = on();
324 stop.active = false;
325 assert!(stop.validate().is_err());
326 let mut vault = on();
327 vault.vaults = Some(vec!["notes".into()]);
328 assert!(vault.validate().is_err());
329 let mut budget = on();
330 budget.daily_budget.tasks = Some(0);
331 assert!(budget.validate().is_err());
332 let extra = serde_json::json!({
333 "schema": ENGINE_OPTIN_ON_SCHEMA, "active": true, "prev_optin_id": null,
334 "daily_budget": {"tasks": 3}, "networks": []
335 });
336 assert!(serde_json::from_value::<EngineOptinOnV1>(extra).is_err());
337 }
338}