1use std::collections::BTreeMap;
9
10use ed25519_dalek::{Signature, Verifier as _, VerifyingKey};
11use serde::{Deserialize, Serialize};
12use serde_json::{Map, Value};
13
14use super::address::{is_wire_address, is_worker_id};
15
16pub const BUS_SCHEMA: &str = "leanctx.cloud.bus/v2";
17pub const CONTROL_DOMAIN: &str = "leanctx.cloud.control.v1\n";
18pub const TEXT_MAX: usize = 4000;
20pub const SHORT_TEXT_MAX: usize = 1000;
22const REFS_MAX: usize = 10;
23
24pub fn text_max(kind: MessageType) -> Option<usize> {
28 match kind {
29 MessageType::Question | MessageType::Answer => Some(TEXT_MAX),
30 MessageType::Offer | MessageType::Handoff => Some(SHORT_TEXT_MAX),
31 MessageType::Finding | MessageType::Progress => None,
32 }
33}
34pub(crate) const PERSON_VALIDATION_WORKER: &str = "wkr_personpublishpending";
38
39#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
42#[serde(rename_all = "snake_case")]
43pub enum MessageType {
44 Question,
45 Offer,
46 Handoff,
47 Finding,
48 Answer,
49 Progress,
50}
51
52impl MessageType {
53 pub fn parse(s: &str) -> Option<Self> {
54 serde_json::from_value(Value::String(s.to_string())).ok()
55 }
56}
57
58#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
59#[serde(deny_unknown_fields)]
60pub struct Ref {
61 pub kind: RefKind,
62 #[serde(rename = "ref")]
63 pub target: String,
64}
65
66#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
67#[serde(rename_all = "snake_case")]
68pub enum RefKind {
69 Node,
70 Msg,
71 File,
72 Commit,
73 Url,
74 Test,
75}
76
77#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
79pub struct Publish {
80 pub schema: String,
81 pub client_msg_id: String,
82 pub to: String,
83 #[serde(rename = "type")]
84 pub kind: MessageType,
85 pub worker_id: String,
86 #[serde(default, skip_serializing_if = "Option::is_none")]
87 pub thread_id: Option<String>,
88 #[serde(default, skip_serializing_if = "Option::is_none")]
89 pub reply_to: Option<String>,
90 #[serde(default, skip_serializing_if = "Vec::is_empty")]
91 pub refs: Vec<Ref>,
92 pub body: Value,
93 #[serde(default, skip_serializing_if = "Option::is_none")]
96 pub ck_wrapped: Option<String>,
97 #[serde(default, skip_serializing_if = "Option::is_none")]
98 pub epoch: Option<u32>,
99 #[serde(default, skip_serializing_if = "Option::is_none")]
102 pub about: Option<About>,
103 #[serde(default, skip_serializing_if = "Option::is_none")]
104 pub counts: Option<CollabCounts>,
105 #[serde(default, skip_serializing_if = "Option::is_none")]
106 pub window: Option<Window>,
107}
108
109#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
110#[serde(rename_all = "snake_case")]
111pub enum About {
112 Collaboration,
113}
114
115#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
118#[serde(deny_unknown_fields)]
119pub struct CollabCounts {
120 #[serde(default, skip_serializing_if = "Option::is_none")]
121 pub registration_renewed: Option<u32>,
122 #[serde(default, skip_serializing_if = "Option::is_none")]
123 pub wait_timeout: Option<u32>,
124 #[serde(default, skip_serializing_if = "Option::is_none")]
125 pub merge_conflict: Option<u32>,
126 #[serde(default, skip_serializing_if = "Option::is_none")]
127 pub claim_refused: Option<u32>,
128 #[serde(default, skip_serializing_if = "Option::is_none")]
129 pub claim_expired: Option<u32>,
130 #[serde(default, skip_serializing_if = "Option::is_none")]
131 pub gate_reruns: Option<u32>,
132 #[serde(default, skip_serializing_if = "Option::is_none")]
133 pub agent_seconds: Option<u32>,
134 #[serde(default, skip_serializing_if = "Option::is_none")]
135 pub idle_seconds: Option<u32>,
136}
137
138#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
139#[serde(deny_unknown_fields)]
140pub struct Window {
141 pub from_ms: u64,
142 pub to_ms: u64,
143}
144
145#[derive(Debug, Clone, PartialEq, Eq)]
147pub struct Invalid(pub String);
148
149impl Invalid {
150 pub fn rule(&self) -> Option<&str> {
153 let rest = self.0.split_once("reason: ")?.1;
154 rest.split(':').next()
155 }
156}
157
158impl std::fmt::Display for Invalid {
159 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
160 write!(f, "invalid_message: {}", self.0)
161 }
162}
163
164#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
168#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
169pub enum Sender {
170 Worker {
171 worker_id: String,
172 name: String,
173 owner_handle: String,
174 host_app: String,
175 },
176 Person {
177 handle: String,
178 },
179 System,
180}
181
182pub fn sender_of(message: &Value) -> Result<Sender, Invalid> {
184 let sender = message.get("sender").ok_or(Invalid("sender".into()))?;
185 let parsed: Sender =
186 serde_json::from_value(sender.clone()).map_err(|e| Invalid(format!("sender: {e}")))?;
187 if let Sender::Worker { worker_id, .. } = &parsed
188 && !is_worker_id(worker_id)
189 {
190 return Err(Invalid("sender.worker_id".into()));
191 }
192 if !matches!(parsed, Sender::Worker { .. }) && message.get("worker_id").is_some() {
194 return Err(Invalid("worker_id on a message no worker sent".into()));
195 }
196 Ok(parsed)
197}
198
199fn bad(why: impl Into<String>) -> Invalid {
200 Invalid(why.into())
201}
202
203fn chars(value: &Value, field: &str, min: usize, max: usize) -> Result<(), Invalid> {
204 let n = value[field]
205 .as_str()
206 .ok_or_else(|| bad(format!("{field} is required")))?
207 .chars()
208 .count();
209 if (min..=max).contains(&n) {
210 Ok(())
211 } else {
212 Err(bad(format!("{field} must be {min} to {max} characters")))
213 }
214}
215
216fn opt_chars(value: &Value, field: &str, min: usize, max: usize) -> Result<(), Invalid> {
217 if value.get(field).is_some() {
218 chars(value, field, min, max)
219 } else {
220 Ok(())
221 }
222}
223
224fn int(value: &Value, field: &str, min: u64, max: u64, required: bool) -> Result<(), Invalid> {
225 match value.get(field) {
226 None if !required => Ok(()),
227 None => Err(bad(format!("{field} is required"))),
228 Some(v) => v
229 .as_u64()
230 .filter(|n| (min..=max).contains(n))
231 .map(|_| ())
232 .ok_or_else(|| bad(format!("{field} must be an integer {min} to {max}"))),
233 }
234}
235
236fn worker(value: &Value, field: &str, required: bool) -> Result<(), Invalid> {
237 match value.get(field) {
238 None if !required => Ok(()),
239 Some(Value::String(id)) if is_worker_id(id) => Ok(()),
240 _ => Err(bad(format!("{field} must be a worker id"))),
241 }
242}
243
244fn only(body: &Map<String, Value>, allowed: &[&str]) -> Result<(), Invalid> {
245 match body.keys().find(|k| !allowed.contains(&k.as_str())) {
246 Some(extra) => Err(bad(format!("unknown body field {extra}"))),
247 None => Ok(()),
248 }
249}
250
251fn check_body(kind: MessageType, body: &Value) -> Result<(), Invalid> {
253 let map = body
254 .as_object()
255 .ok_or_else(|| bad("body must be an object"))?;
256 match kind {
257 MessageType::Question => {
258 only(map, &["text", "to_worker", "deadline"])?;
259 chars(body, "text", 1, TEXT_MAX)?;
260 worker(body, "to_worker", false)?;
261 int(body, "deadline", 0, u64::MAX, false)
262 }
263 MessageType::Offer => {
264 only(map, &["what", "capability", "eta_minutes", "withdraw"])?;
265 chars(body, "what", 1, SHORT_TEXT_MAX)?;
266 chars(body, "capability", 1, 64)?;
267 int(body, "eta_minutes", 1, 10_080, true)?;
268 match body.get("withdraw") {
269 None | Some(Value::Bool(_)) => Ok(()),
270 _ => Err(bad("withdraw must be true or false")),
271 }
272 }
273 MessageType::Handoff => {
274 only(map, &["to_worker", "resource", "note", "lease_id"])?;
275 worker(body, "to_worker", true)?;
276 chars(body, "resource", 1, 200)?;
277 opt_chars(body, "note", 1, SHORT_TEXT_MAX)?;
278 lease(body, false)
279 }
280 MessageType::Finding => {
281 only(map, &["statement", "evidence"])?;
282 chars(body, "statement", 24, 300)?;
283 match body["evidence"].as_str() {
284 Some("observed" | "stated" | "imported") => Ok(()),
285 _ => Err(bad("evidence must be observed, stated or imported")),
286 }
287 }
288 MessageType::Answer => {
289 only(map, &["text", "accept"])?;
290 chars(body, "text", 1, TEXT_MAX)?;
291 match body.get("accept") {
292 None | Some(Value::Bool(_)) => Ok(()),
293 _ => Err(bad("accept must be true or false")),
294 }
295 }
296 MessageType::Progress => {
297 only(map, &["percentage", "step", "usage"])?;
298 if map.get("percentage").is_none() && map.get("step").is_none() {
299 return Err(bad("progress needs percentage or step"));
300 }
301 int(body, "percentage", 0, 100, false)?;
302 opt_chars(body, "step", 1, 300)
303 }
304 }
305}
306
307fn lease(body: &Value, required: bool) -> Result<(), Invalid> {
308 match body.get("lease_id") {
309 None if !required => Ok(()),
310 Some(Value::String(id))
311 if id.strip_prefix("bl_").is_some_and(|r| {
312 (1..=40).contains(&r.len())
313 && r.bytes()
314 .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit())
315 }) =>
316 {
317 Ok(())
318 }
319 _ => Err(bad("lease_id must be bl_<id>")),
320 }
321}
322
323fn is_msg_id(s: &str) -> bool {
324 s.strip_prefix("msg_").is_some_and(|r| {
325 r.len() == 16
326 && r.bytes()
327 .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
328 })
329}
330
331impl Publish {
332 pub fn validate(&self) -> Result<(), Invalid> {
334 if self.schema != BUS_SCHEMA {
335 return Err(bad("schema"));
336 }
337 if !is_ulid(&self.client_msg_id) {
338 return Err(bad("client_msg_id must be a ULID"));
339 }
340 if !is_wire_address(&self.to) {
341 return Err(bad("to must be #<ws>/<vault>, ~<slug> or @wkr_<id>"));
342 }
343 if !is_worker_id(&self.worker_id) {
344 return Err(bad("worker_id"));
345 }
346 for id in [&self.thread_id, &self.reply_to].into_iter().flatten() {
347 if !is_msg_id(id) {
348 return Err(bad("thread_id and reply_to must be msg_ ids"));
349 }
350 }
351 if self.refs.len() > REFS_MAX
352 || self
353 .refs
354 .iter()
355 .any(|r| r.target.is_empty() || r.target.chars().count() > 500)
356 {
357 return Err(bad("refs: at most 10, each 1 to 500 characters"));
358 }
359 if self.body.get("sealed").is_some() {
360 return Err(bad("sealed bodies are not supported"));
361 }
362 let collaboration = self.about.is_some();
363 if collaboration {
364 if self.kind != MessageType::Finding {
365 return Err(bad("about: collaboration is for findings only"));
366 }
367 if self.counts.is_none() || self.window.is_none() {
368 return Err(bad("a collaboration finding needs counts and window"));
369 }
370 } else if self.counts.is_some() || self.window.is_some() {
371 return Err(bad("counts and window need about: collaboration"));
372 }
373 if self.kind == MessageType::Finding && self.refs.is_empty() && !collaboration {
374 return Err(bad("a finding needs at least one ref"));
375 }
376 if self.kind == MessageType::Answer && self.reply_to.is_none() {
377 return Err(bad("an answer needs reply_to"));
378 }
379 if self.ck_wrapped.is_some() || self.epoch.is_some() {
380 return Err(bad("key material on a plain place"));
381 }
382 if self.worker_id != PERSON_VALIDATION_WORKER {
385 super::person_rules::check_agent_body(self.kind, &self.body)?;
386 }
387 check_body(self.kind, &self.body)
388 }
389}
390
391pub fn is_ulid(s: &str) -> bool {
393 s.len() == 26
394 && s.bytes().all(|b| {
395 b.is_ascii_digit()
396 || (b.is_ascii_uppercase() && !matches!(b, b'I' | b'L' | b'O' | b'U'))
397 })
398}
399
400pub fn new_ulid(now_ms: u64) -> String {
402 let mut random = [0u8; 10];
403 let _ = getrandom::fill(&mut random);
404 ulid_of(now_ms, random)
405}
406
407pub fn ulid_for(at_ms: u64, seed: &str) -> String {
411 let digest = blake3::hash(seed.as_bytes());
412 let mut bits = [0u8; 10];
413 bits.copy_from_slice(&digest.as_bytes()[..10]);
414 ulid_of(at_ms, bits)
415}
416
417fn ulid_of(ms: u64, low: [u8; 10]) -> String {
418 const ALPHABET: &[u8; 32] = b"0123456789ABCDEFGHJKMNPQRSTVWXYZ";
419 let mut value: u128 = u128::from(ms & 0xFFFF_FFFF_FFFF) << 80;
420 for (i, byte) in low.iter().enumerate() {
421 value |= u128::from(*byte) << (8 * (9 - i));
422 }
423 (0..26)
424 .rev()
425 .map(|i| ALPHABET[((value >> (5 * i)) & 31) as usize] as char)
426 .collect()
427}
428
429#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
431#[serde(deny_unknown_fields)]
432pub struct Control {
433 pub id: String,
434 pub place: String,
435 pub target: ControlTarget,
436 #[serde(default, skip_serializing_if = "Option::is_none")]
437 pub worker_id: Option<String>,
438 #[serde(default, rename = "ref", skip_serializing_if = "Option::is_none")]
439 pub target_ref: Option<ControlRef>,
440 pub action: ControlAction,
441 pub reason: String,
442 pub issued_by: IssuedBy,
443 pub created_at: u64,
444 #[serde(default, skip_serializing_if = "Option::is_none")]
445 pub lifted_at: Option<u64>,
446 pub key_id: String,
447 pub signature: String,
448}
449
450#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
451#[serde(rename_all = "snake_case")]
452pub enum ControlTarget {
453 Worker,
454 Bus,
455}
456
457#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
458#[serde(rename_all = "snake_case")]
459pub enum ControlAction {
460 Hold,
461 Stop,
462 Resume,
463 Veto,
464}
465
466#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
467#[serde(deny_unknown_fields)]
468pub struct ControlRef {
469 pub kind: String,
470 pub id: String,
471}
472
473#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
474#[serde(deny_unknown_fields)]
475pub struct IssuedBy {
476 pub kind: String,
477 pub user_id: String,
478 #[serde(default, skip_serializing_if = "Option::is_none")]
481 pub label: Option<String>,
482}
483
484#[derive(Debug, Clone, Copy, PartialEq, Eq)]
486pub enum ControlRejection {
487 Invalid,
490 SigInvalid,
492}
493
494pub type ControlKeys = BTreeMap<String, VerifyingKey>;
497
498impl Control {
499 pub fn verify(&self, lifted: bool, keys: &ControlKeys) -> Result<(), ControlRejection> {
503 let shape_ok = (self.target == ControlTarget::Worker) == self.worker_id.is_some()
504 && (self.action != ControlAction::Veto || self.target_ref.is_some())
505 && lifted == self.lifted_at.is_some()
506 && (2..=500).contains(&self.reason.chars().count())
507 && self.issued_by.kind == "person";
508 if !shape_ok {
509 return Err(ControlRejection::Invalid);
510 }
511 let key = keys.get(&self.key_id).ok_or(ControlRejection::SigInvalid)?;
512 let value = serde_json::to_value(self).map_err(|_| ControlRejection::Invalid)?;
513 let input =
514 lean_ctx_protocol::cloud::signing_input_without_signature(CONTROL_DOMAIN, &value)
515 .map_err(|_| ControlRejection::Invalid)?;
516 let mut sig = [0u8; 64];
517 hex::decode_to_slice(&self.signature, &mut sig)
518 .map_err(|_| ControlRejection::SigInvalid)?;
519 key.verify(&input, &Signature::from_bytes(&sig))
520 .map_err(|_| ControlRejection::SigInvalid)
521 }
522}
523
524#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
526#[serde(rename_all = "snake_case")]
527pub enum PresenceState {
528 Active,
529 Idle,
530 Held,
531}
532
533#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
534#[serde(deny_unknown_fields)]
535pub struct PresenceEntry {
536 pub worker_id: String,
537 pub role: String,
538 pub state: PresenceState,
539 #[serde(default, skip_serializing_if = "Option::is_none")]
542 pub display_name: Option<String>,
543 #[serde(default, skip_serializing_if = "Option::is_none")]
544 pub instance_id: Option<String>,
545 #[serde(default, skip_serializing_if = "Option::is_none")]
546 pub instance_name: Option<String>,
547}
548
549#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
553pub struct PresenceNames {
554 #[serde(default, skip_serializing_if = "Option::is_none")]
556 pub kind: Option<String>,
557 #[serde(default, skip_serializing_if = "Option::is_none")]
558 pub display_name: Option<String>,
559 #[serde(default, skip_serializing_if = "Option::is_none")]
560 pub session_name: Option<String>,
561 #[serde(default, skip_serializing_if = "Option::is_none")]
562 pub instance_id: Option<String>,
563 #[serde(default, skip_serializing_if = "Option::is_none")]
564 pub instance_name: Option<String>,
565 #[serde(default, skip_serializing_if = "Option::is_none")]
570 pub person_name: Option<String>,
571 #[serde(default, skip_serializing_if = "Option::is_none")]
572 pub machine_name: Option<String>,
573 #[serde(default, skip_serializing_if = "Option::is_none")]
574 pub working_on: Option<String>,
575}
576
577#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
583pub struct PresenceIdentity {
584 #[serde(default)]
585 pub machine_name: Option<String>,
586 #[serde(default)]
587 pub working_on: Option<String>,
588}
589
590pub fn machine_name(label: &str) -> Option<String> {
598 let label = label.trim();
599 let short =
600 if label.chars().any(char::is_whitespace) || label.parse::<std::net::IpAddr>().is_ok() {
601 label
602 } else {
603 label.split('.').next().unwrap_or_default()
604 };
605 bounded_line(short, PRESENCE_NAME_CHARS).map(str::to_owned)
606}
607
608pub fn bounded_line(value: &str, max: usize) -> Option<&str> {
611 let value = value.trim();
612 (!value.is_empty() && value.chars().count() <= max && !value.chars().any(char::is_control))
613 .then_some(value)
614}
615
616pub fn working_on(status: &str) -> Option<String> {
624 let first = status.lines().map(str::trim).find(|l| !l.is_empty())?;
625 let redacted = lean_ctx::core::redaction::redact_text(&without_paths(first));
626 let cut: String = redacted.chars().take(PRESENCE_NAME_CHARS).collect();
627 bounded_line(&cut, PRESENCE_NAME_CHARS).map(str::to_owned)
628}
629
630fn without_paths(line: &str) -> String {
647 let words: Vec<&str> = line.split_whitespace().collect();
648 let mut out = Vec::with_capacity(words.len());
649 let mut next = 0;
650 while let Some(&word) = words.get(next) {
651 next += 1;
652 let Some((prefix, start)) = path_start(word) else {
653 out.push(word.to_owned());
654 continue;
655 };
656 let segment_end = words[next..]
657 .iter()
658 .position(|more| ends_segment(more))
659 .map_or(words.len(), |at| next + at);
660 let through = words[next..segment_end]
661 .iter()
662 .rposition(|more| more.contains(['/', '\\']))
663 .map_or(next, |at| next + at + 1);
664 let mut path = word[start..].to_owned();
665 for more in &words[next..through] {
666 path.push(' ');
667 path.push_str(more);
668 }
669 next = through;
670 out.push(format!("{prefix}{}", last_part(&path)));
671 }
672 out.join(" ")
673}
674
675fn path_start(word: &str) -> Option<(&str, usize)> {
680 if let Some(scheme) = word.find("://") {
681 let name = &word[..scheme];
682 if !name.to_ascii_lowercase().ends_with("file") {
683 return None;
684 }
685 let path = scheme + "://".len();
686 return (path < word.len()).then_some((&word[..scheme - "file".len()], path));
687 }
688 let mut before: Option<char> = None;
689 for (at, c) in word.char_indices() {
690 let free = before.is_none_or(|b| !is_name_char(b) || is_short_flag(&word[..at]));
691 if free && starts_path(&word[at..]) {
692 return Some((&word[..at], at));
693 }
694 before = Some(c);
695 }
696 None
697}
698
699fn starts_path(rest: &str) -> bool {
702 let bytes = rest.as_bytes();
703 if matches!(bytes.first(), Some(b'/' | b'\\')) {
704 return bytes.len() > 1;
705 }
706 if let Some(var) = rest.strip_prefix('$') {
707 let name = var
708 .find(|c: char| !(c.is_ascii_alphanumeric() || c == '_'))
709 .unwrap_or(var.len());
710 return name > 0 && matches!(var.as_bytes().get(name), Some(b'/' | b'\\'));
711 }
712 if let Some(home) = rest.strip_prefix('~') {
713 return home
714 .find('/')
715 .is_some_and(|slash| home[..slash].chars().all(is_name_char));
716 }
717 bytes.len() > 2
718 && bytes[0].is_ascii_alphabetic()
719 && bytes[1] == b':'
720 && matches!(bytes[2], b'\\' | b'/')
721}
722
723fn is_name_char(c: char) -> bool {
726 c.is_alphanumeric() || matches!(c, '.' | '_' | '-' | '~')
727}
728
729fn is_short_flag(prefix: &str) -> bool {
731 prefix
732 .strip_prefix('-')
733 .is_some_and(|name| !name.is_empty() && name.chars().all(|c| c.is_ascii_alphabetic()))
734}
735
736fn ends_segment(word: &str) -> bool {
739 let flag = word
740 .strip_prefix('-')
741 .and_then(|rest| rest.chars().next())
742 .is_some_and(|c| c == '-' || c.is_alphanumeric());
743 flag || word.contains("://")
744 || matches!(word, "|" | "||" | "&&" | ";" | ">" | ">>")
745 || path_start(word).is_some()
746}
747
748fn last_part(path: &str) -> String {
752 let closes = |c: char| {
753 matches!(
754 c,
755 '"' | '\'' | '`' | ')' | ']' | '>' | '}' | ',' | '.' | ';' | ':' | '!' | '?'
756 )
757 };
758 let mut parts = path.rsplit(['/', '\\']);
759 let last = parts.next().unwrap_or_default();
760 if !last.trim_matches(closes).is_empty() {
761 return last.to_owned();
762 }
763 let name = parts
764 .find(|part| !part.trim_matches(closes).is_empty())
765 .unwrap_or("…");
766 format!("{name}{last}")
767}
768
769const PRESENCE_NAME_CHARS: usize = 128;
771
772pub fn presence_names(value: &Value) -> PresenceNames {
775 let line = |field: &str| {
776 value[field]
777 .as_str()
778 .map(str::trim)
779 .filter(|v| {
780 !v.is_empty()
781 && v.chars().count() <= PRESENCE_NAME_CHARS
782 && !v.chars().any(char::is_control)
783 })
784 .map(str::to_owned)
785 };
786 PresenceNames {
787 kind: line("kind").filter(|k| matches!(k.as_str(), "agent" | "person")),
788 display_name: line("display_name"),
789 session_name: line("session_name"),
790 instance_id: line("instance_id"),
791 instance_name: line("instance_name"),
792 person_name: line("person_name"),
793 machine_name: line("machine_name"),
794 working_on: line("working_on"),
795 }
796}
797
798#[derive(Debug, Clone, PartialEq)]
800pub enum Inbound {
801 HelloAck(Value),
802 Stored {
803 client_msg_id: String,
804 id: String,
805 seq: u64,
806 thread_id: String,
807 },
808 Deliver(Value),
809 Presence {
810 address: String,
811 worker_id: String,
812 role: String,
813 state: PresenceState,
814 at: u64,
815 names: PresenceNames,
817 },
818 Control {
819 lifted: bool,
820 control: Box<Control>,
821 },
822 PlaceDenied {
823 place: String,
824 code: String,
825 },
826 Resync {
827 place: String,
828 },
829 Error {
830 client_msg_id: Option<String>,
831 code: String,
832 reason: Option<String>,
833 quota: Option<Box<Value>>,
837 },
838 Ping,
839 ConsentAnswered {
841 consent_id: String,
842 },
843 TaskEvent(Box<super::task_events::TaskEvent>),
845 PlanAdvanced(Box<super::plan_events::PlanAdvanced>),
849 DecisionChanged(Box<super::plan_events::DecisionChanged>),
851 LogAdvanced {
854 place: String,
855 purge: bool,
856 },
857 TrustAdvanced {
859 place: String,
860 },
861 PolicyAdvanced {
865 version: u64,
866 },
867 Other(String),
868}
869
870fn quota_fields(frame: &Value) -> Option<Box<Value>> {
874 let mut out = serde_json::Map::new();
875 for (field, string) in [
876 ("resource", true),
877 ("reset_at", true),
878 ("limit", false),
879 ("used", false),
880 ("retry_after_s", false),
881 ] {
882 let value = &frame[field];
883 if field == "retry_after_s" {
884 if let Some(s) = value.as_u64() {
886 let capped = s.min(crate::error::RETRY_AFTER_CAP_S);
887 out.insert(field.to_string(), Value::from(capped));
888 }
889 } else if (string && value.is_string()) || (!string && value.is_u64()) {
890 out.insert(field.to_string(), value.clone());
891 }
892 }
893 (!out.is_empty()).then(|| Box::new(Value::Object(out)))
894}
895
896pub fn parse_frame(text: &str) -> Result<Inbound, Invalid> {
898 let value: Value = serde_json::from_str(text).map_err(|e| bad(format!("frame: {e}")))?;
899 let t = value["t"]
900 .as_str()
901 .ok_or_else(|| bad("frame without t"))?
902 .to_string();
903 let s = |field: &str| -> Result<String, Invalid> {
904 value[field]
905 .as_str()
906 .map(str::to_string)
907 .ok_or_else(|| bad(format!("{t}: {field}")))
908 };
909 let n = |field: &str| -> Result<u64, Invalid> {
910 value[field]
911 .as_u64()
912 .ok_or_else(|| bad(format!("{t}: {field}")))
913 };
914 Ok(match t.as_str() {
915 "hello.ack" => Inbound::HelloAck(value),
916 "message.stored" => Inbound::Stored {
917 client_msg_id: s("client_msg_id")?,
918 id: s("id")?,
919 seq: n("seq")?,
920 thread_id: s("thread_id")?,
921 },
922 "message.deliver" => Inbound::Deliver(value),
923 "presence.update" => Inbound::Presence {
924 address: s("address")?,
925 worker_id: s("worker_id")?,
926 role: s("role")?,
927 state: serde_json::from_value(value["state"].clone())
928 .map_err(|_| bad("presence.update: state"))?,
929 at: n("at")?,
930 names: presence_names(&value),
931 },
932 "control" => {
933 let lifted = match value["state"].as_str() {
934 Some("issued") => false,
935 Some("lifted") => true,
936 _ => return Err(bad("control: state")),
937 };
938 let control = serde_json::from_value(value["control"].clone())
939 .map_err(|e| bad(format!("control: {e}")))?;
940 Inbound::Control { lifted, control }
941 }
942 "place.denied" => Inbound::PlaceDenied {
943 place: s("place")?,
944 code: s("code")?,
945 },
946 "resync" => Inbound::Resync { place: s("place")? },
947 "error" => Inbound::Error {
948 client_msg_id: value["client_msg_id"].as_str().map(str::to_string),
949 code: s("code")?,
950 reason: value["reason"].as_str().map(str::to_string),
951 quota: quota_fields(&value),
952 },
953 "ping" => Inbound::Ping,
954 "consent.answered" => Inbound::ConsentAnswered {
955 consent_id: s("consent_id")?,
956 },
957 "task.event" => Inbound::TaskEvent(Box::new(
958 super::task_events::TaskEvent::parse(&value).ok_or_else(|| bad("task.event"))?,
959 )),
960 "plan.advanced" => Inbound::PlanAdvanced(Box::new(
961 super::plan_events::PlanAdvanced::parse(&value).ok_or_else(|| bad("plan.advanced"))?,
962 )),
963 "decision.changed" => Inbound::DecisionChanged(Box::new(
964 super::plan_events::DecisionChanged::parse(&value)
965 .ok_or_else(|| bad("decision.changed"))?,
966 )),
967 "log.advanced" => Inbound::LogAdvanced {
968 place: s("place")?,
969 purge: value["priority"].as_str() == Some("purge"),
970 },
971 "trust.advanced" => Inbound::TrustAdvanced { place: s("place")? },
972 "policy.advanced" => Inbound::PolicyAdvanced {
973 version: n("version")?,
974 },
975 _ => Inbound::Other(t),
976 })
977}
978
979#[cfg(test)]
980#[path = "v2_tests.rs"]
981mod tests;