1use std::collections::{BTreeMap, HashMap};
2
3use crate::cbor;
4
5#[derive(Debug, Clone)]
12pub enum LocalizedString {
13 Plain(String),
15 Localized(HashMap<String, String>),
17}
18
19impl Default for LocalizedString {
20 fn default() -> Self {
21 Self::Plain(String::new())
22 }
23}
24
25impl LocalizedString {
26 pub fn plain(text: impl Into<String>) -> Self {
28 Self::Plain(text.into())
29 }
30
31 pub fn new(lang: impl Into<String>, text: impl Into<String>) -> Self {
33 let mut map = HashMap::new();
34 map.insert(lang.into(), text.into());
35 Self::Localized(map)
36 }
37
38 pub fn get(&self, lang: &str) -> Option<&str> {
43 match self {
44 Self::Plain(text) => Some(text.as_str()),
45 Self::Localized(map) => map.get(lang).map(|s| s.as_str()),
46 }
47 }
48
49 pub fn resolve(&self, lang: &str) -> &str {
54 match self {
55 Self::Plain(text) => text.as_str(),
56 Self::Localized(map) => {
57 if let Some(text) = map.get(lang) {
59 return text.as_str();
60 }
61 if let Some(text) = map
63 .iter()
64 .find(|(tag, _)| tag.starts_with(lang) || lang.starts_with(tag.as_str()))
65 .map(|(_, text)| text.as_str())
66 {
67 return text;
68 }
69 map.values().next().map(|s| s.as_str()).unwrap_or("")
71 }
72 }
73 }
74
75 pub fn any_text(&self) -> &str {
78 match self {
79 Self::Plain(text) => text.as_str(),
80 Self::Localized(map) => map.values().next().map(|s| s.as_str()).unwrap_or(""),
81 }
82 }
83}
84
85impl From<String> for LocalizedString {
86 fn from(s: String) -> Self {
87 Self::Plain(s)
88 }
89}
90
91impl From<&str> for LocalizedString {
92 fn from(s: &str) -> Self {
93 Self::Plain(s.to_string())
94 }
95}
96
97impl From<Vec<(String, String)>> for LocalizedString {
98 fn from(v: Vec<(String, String)>) -> Self {
99 Self::Localized(v.into_iter().collect())
100 }
101}
102
103impl From<HashMap<String, String>> for LocalizedString {
104 fn from(map: HashMap<String, String>) -> Self {
105 Self::Localized(map)
106 }
107}
108
109#[derive(Debug, Clone, Default)]
115pub struct Metadata(HashMap<String, serde_json::Value>);
116
117impl Metadata {
118 pub fn new() -> Self {
119 Self(HashMap::new())
120 }
121
122 pub fn insert(&mut self, key: impl Into<String>, value: impl Into<serde_json::Value>) {
124 self.0.insert(key.into(), value.into());
125 }
126
127 pub fn get(&self, key: &str) -> Option<&serde_json::Value> {
129 self.0.get(key)
130 }
131
132 pub fn get_as<T: serde::de::DeserializeOwned>(&self, key: &str) -> Option<T> {
134 self.0
135 .get(key)
136 .and_then(|v| serde_json::from_value(v.clone()).ok())
137 }
138
139 pub fn contains_key(&self, key: &str) -> bool {
141 self.0.contains_key(key)
142 }
143
144 pub fn is_empty(&self) -> bool {
146 self.0.is_empty()
147 }
148
149 pub fn iter(&self) -> impl Iterator<Item = (&String, &serde_json::Value)> {
151 self.0.iter()
152 }
153
154 pub fn len(&self) -> usize {
156 self.0.len()
157 }
158
159 pub fn extend(&mut self, other: Metadata) {
161 self.0.extend(other.0);
162 }
163}
164
165impl From<serde_json::Value> for Metadata {
167 fn from(value: serde_json::Value) -> Self {
168 match value {
169 serde_json::Value::Object(map) => Self(map.into_iter().collect()),
170 _ => Self::new(),
171 }
172 }
173}
174
175impl From<Metadata> for serde_json::Value {
177 fn from(m: Metadata) -> Self {
178 serde_json::Value::Object(m.0.into_iter().collect())
179 }
180}
181
182impl From<Vec<(String, Vec<u8>)>> for Metadata {
184 fn from(v: Vec<(String, Vec<u8>)>) -> Self {
185 Self(
186 v.into_iter()
187 .filter_map(|(k, cbor_bytes)| {
188 let val = cbor::cbor_to_json(&cbor_bytes).ok()?;
189 Some((k, val))
190 })
191 .collect(),
192 )
193 }
194}
195
196impl From<Metadata> for Vec<(String, Vec<u8>)> {
198 fn from(m: Metadata) -> Self {
199 m.0.into_iter()
200 .map(|(k, v)| (k, cbor::to_cbor(&v)))
201 .collect()
202 }
203}
204
205use crate::constants::*;
206
207#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
211pub struct FilesystemCap {
212 #[serde(
214 rename = "mount-root",
215 default,
216 skip_serializing_if = "Option::is_none"
217 )]
218 pub mount_root: Option<String>,
219
220 #[serde(default, skip_serializing_if = "Vec::is_empty")]
224 pub allow: Vec<FilesystemAllow>,
225}
226
227#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
230pub struct FilesystemAllow {
231 pub path: String,
233 pub mode: FsMode,
235}
236
237#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
239#[serde(rename_all = "lowercase")]
240pub enum FsMode {
241 Ro,
243 Rw,
245}
246
247#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
249pub struct HttpCap {
250 #[serde(default, skip_serializing_if = "Vec::is_empty")]
254 pub allow: Vec<HttpAllow>,
255}
256
257#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
263pub struct HttpAllow {
264 pub host: String,
265 #[serde(default, skip_serializing_if = "Option::is_none")]
266 pub scheme: Option<String>,
267 #[serde(default, skip_serializing_if = "Option::is_none")]
268 pub methods: Option<Vec<String>>,
269 #[serde(default, skip_serializing_if = "Option::is_none")]
270 pub ports: Option<Vec<u16>>,
271}
272
273#[derive(Debug, Clone, Copy, Default, serde::Serialize, serde::Deserialize)]
275pub struct SocketsCap {}
276
277#[serde_with::skip_serializing_none]
282#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
283#[serde(default)]
284pub struct Capabilities {
285 #[serde(rename = "wasi:filesystem")]
287 pub filesystem: Option<FilesystemCap>,
288 #[serde(rename = "wasi:http")]
290 pub http: Option<HttpCap>,
291 #[serde(rename = "wasi:sockets")]
293 pub sockets: Option<SocketsCap>,
294 #[serde(flatten)]
296 pub other: BTreeMap<String, serde_json::Value>,
297}
298
299impl Capabilities {
300 pub fn is_empty(&self) -> bool {
302 self.http.is_none()
303 && self.filesystem.is_none()
304 && self.sockets.is_none()
305 && self.other.is_empty()
306 }
307
308 pub fn has(&self, id: &str) -> bool {
310 match id {
311 CAP_HTTP => self.http.is_some(),
312 CAP_FILESYSTEM => self.filesystem.is_some(),
313 CAP_SOCKETS => self.sockets.is_some(),
314 other => self.other.contains_key(other),
315 }
316 }
317
318 pub fn fs_mount_root(&self) -> Option<&str> {
320 self.filesystem.as_ref()?.mount_root.as_deref()
321 }
322}
323
324#[non_exhaustive]
331#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
332pub struct ComponentInfo {
333 #[serde(default)]
335 pub std: StdComponentInfo,
336 #[serde(flatten, default, skip_serializing_if = "HashMap::is_empty")]
338 pub extra: HashMap<String, serde_json::Value>,
339}
340
341#[non_exhaustive]
343#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
344pub struct StdComponentInfo {
345 #[serde(default)]
346 pub name: String,
347 #[serde(default)]
348 pub version: String,
349 #[serde(default)]
350 pub description: String,
351 #[serde(
352 rename = "default-language",
353 default,
354 skip_serializing_if = "Option::is_none"
355 )]
356 pub default_language: Option<String>,
357 #[serde(default, skip_serializing_if = "Capabilities::is_empty")]
358 pub capabilities: Capabilities,
359}
360
361impl ComponentInfo {
362 pub fn new(
363 name: impl Into<String>,
364 version: impl Into<String>,
365 description: impl Into<String>,
366 ) -> Self {
367 Self {
368 std: StdComponentInfo {
369 name: name.into(),
370 version: version.into(),
371 description: description.into(),
372 ..Default::default()
373 },
374 ..Default::default()
375 }
376 }
377
378 pub fn name(&self) -> &str {
380 &self.std.name
381 }
382 pub fn version(&self) -> &str {
383 &self.std.version
384 }
385 pub fn description(&self) -> &str {
386 &self.std.description
387 }
388}
389
390#[derive(Debug, Clone)]
394pub struct ActError {
395 pub kind: String,
396 pub message: String,
397}
398
399impl ActError {
400 pub fn new(kind: impl Into<String>, message: impl Into<String>) -> Self {
401 Self {
402 kind: kind.into(),
403 message: message.into(),
404 }
405 }
406
407 pub fn not_found(message: impl Into<String>) -> Self {
408 Self::new(ERR_NOT_FOUND, message)
409 }
410
411 pub fn invalid_args(message: impl Into<String>) -> Self {
412 Self::new(ERR_INVALID_ARGS, message)
413 }
414
415 pub fn internal(message: impl Into<String>) -> Self {
416 Self::new(ERR_INTERNAL, message)
417 }
418
419 pub fn timeout(message: impl Into<String>) -> Self {
420 Self::new(ERR_TIMEOUT, message)
421 }
422
423 pub fn capability_denied(message: impl Into<String>) -> Self {
424 Self::new(ERR_CAPABILITY_DENIED, message)
425 }
426}
427
428impl std::fmt::Display for ActError {
429 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
430 write!(f, "{}: {}", self.kind, self.message)
431 }
432}
433
434impl std::error::Error for ActError {}
435
436pub type ActResult<T> = Result<T, ActError>;
438
439#[cfg(test)]
440mod tests {
441 use super::*;
442 use serde_json::json;
443
444 #[test]
445 fn localized_string_plain() {
446 let ls = LocalizedString::plain("hello");
447 assert_eq!(ls.resolve("en"), "hello");
448 assert_eq!(ls.any_text(), "hello");
449 }
450
451 #[test]
452 fn localized_string_from_str() {
453 let ls = LocalizedString::from("hello");
454 assert_eq!(ls.any_text(), "hello");
455 }
456
457 #[test]
458 fn localized_string_default() {
459 let ls = LocalizedString::default();
460 assert_eq!(ls.any_text(), "");
461 }
462
463 #[test]
464 fn localized_string_resolve_by_lang() {
465 let mut map = std::collections::HashMap::new();
466 map.insert("en".to_string(), "hello".to_string());
467 map.insert("ru".to_string(), "привет".to_string());
468 let ls = LocalizedString::Localized(map);
469 assert_eq!(ls.resolve("ru"), "привет");
470 assert_eq!(ls.resolve("en"), "hello");
471 assert!(!ls.resolve("fr").is_empty());
473 }
474
475 #[test]
476 fn localized_string_resolve_prefix() {
477 let mut map = HashMap::new();
478 map.insert("zh-Hans".to_string(), "你好".to_string());
479 map.insert("en".to_string(), "hello".to_string());
480 let ls = LocalizedString::Localized(map);
481 assert_eq!(ls.resolve("zh"), "你好");
482 }
483
484 #[test]
485 fn localized_string_get() {
486 let ls = LocalizedString::new("en", "hello");
487 assert_eq!(ls.get("en"), Some("hello"));
488 assert_eq!(ls.get("ru"), None);
489 }
490
491 #[test]
492 fn localized_string_from_vec() {
493 let v = vec![("en".to_string(), "hi".to_string())];
494 let ls = LocalizedString::from(v);
495 assert_eq!(ls.resolve("en"), "hi");
496 }
497
498 #[test]
499 fn metadata_insert_and_get() {
500 let mut m = Metadata::new();
501 m.insert("std:read-only", true);
502 assert_eq!(m.get("std:read-only"), Some(&json!(true)));
503 assert_eq!(m.get_as::<bool>("std:read-only"), Some(true));
504 }
505
506 #[test]
507 fn metadata_to_json_empty() {
508 let json: serde_json::Value = Metadata::new().into();
509 assert_eq!(json, json!({}));
510 }
511
512 #[test]
513 fn metadata_to_json_with_values() {
514 let mut m = Metadata::new();
515 m.insert("std:read-only", true);
516 let json: serde_json::Value = m.into();
517 assert_eq!(json["std:read-only"], json!(true));
518 }
519
520 #[test]
521 fn metadata_from_vec() {
522 let v = vec![("key".to_string(), cbor::to_cbor(&42u32))];
523 let m = Metadata::from(v);
524 assert_eq!(m.get("key"), Some(&json!(42)));
525 assert_eq!(m.get_as::<u32>("key"), Some(42));
526 }
527
528 #[test]
529 fn capabilities_cbor_roundtrip() {
530 let mut info = ComponentInfo::new("test", "0.1.0", "test component");
531 info.std.capabilities.http = Some(HttpCap::default());
532 info.std.capabilities.filesystem = Some(FilesystemCap {
533 mount_root: Some("/data".to_string()),
534 ..Default::default()
535 });
536
537 let mut buf = Vec::new();
538 ciborium::into_writer(&info, &mut buf).unwrap();
539
540 let decoded: ComponentInfo = ciborium::from_reader(&buf[..]).unwrap();
541 assert!(decoded.std.capabilities.http.is_some());
542 assert!(decoded.std.capabilities.filesystem.is_some());
543 assert!(decoded.std.capabilities.sockets.is_none());
544 assert_eq!(decoded.std.capabilities.fs_mount_root(), Some("/data"));
545 }
546
547 #[test]
548 fn capabilities_empty_roundtrip() {
549 let info = ComponentInfo::new("test", "0.1.0", "test");
550
551 let mut buf = Vec::new();
552 ciborium::into_writer(&info, &mut buf).unwrap();
553
554 let decoded: ComponentInfo = ciborium::from_reader(&buf[..]).unwrap();
555 assert!(decoded.std.capabilities.is_empty());
556 }
557
558 #[test]
559 fn capabilities_fs_no_params_roundtrip() {
560 let mut info = ComponentInfo::new("test", "0.1.0", "test");
561 info.std.capabilities.filesystem = Some(FilesystemCap::default());
562
563 let mut buf = Vec::new();
564 ciborium::into_writer(&info, &mut buf).unwrap();
565
566 let decoded: ComponentInfo = ciborium::from_reader(&buf[..]).unwrap();
567 assert!(decoded.std.capabilities.filesystem.is_some());
568 assert_eq!(decoded.std.capabilities.fs_mount_root(), None);
569 }
570
571 #[test]
572 fn capabilities_unknown_preserved() {
573 let mut info = ComponentInfo::new("test", "0.1.0", "test");
574 info.std
575 .capabilities
576 .other
577 .insert("acme:gpu".to_string(), json!({"cores": 8}));
578
579 let mut buf = Vec::new();
580 ciborium::into_writer(&info, &mut buf).unwrap();
581
582 let decoded: ComponentInfo = ciborium::from_reader(&buf[..]).unwrap();
583 assert!(decoded.std.capabilities.has("acme:gpu"));
584 assert_eq!(decoded.std.capabilities.other["acme:gpu"]["cores"], 8);
585 }
586
587 #[test]
588 fn filesystem_cap_with_allow_roundtrips() {
589 let toml_input = r#"
590[std.capabilities."wasi:filesystem"]
591description = "test"
592
593[[std.capabilities."wasi:filesystem".allow]]
594path = "/etc/**"
595mode = "ro"
596
597[[std.capabilities."wasi:filesystem".allow]]
598path = "/tmp/**"
599mode = "rw"
600"#;
601 #[derive(serde::Deserialize)]
602 struct Wrap {
603 std: Std,
604 }
605 #[derive(serde::Deserialize)]
606 struct Std {
607 capabilities: Capabilities,
608 }
609 let w: Wrap = toml::from_str(toml_input).expect("parses");
610 let fs = w.std.capabilities.filesystem.expect("fs declared");
611 assert_eq!(fs.allow.len(), 2);
612 assert_eq!(fs.allow[0].path, "/etc/**");
613 assert!(matches!(fs.allow[0].mode, FsMode::Ro));
614 assert_eq!(fs.allow[1].path, "/tmp/**");
615 assert!(matches!(fs.allow[1].mode, FsMode::Rw));
616 }
617
618 #[test]
619 fn filesystem_cap_requires_path_and_mode_on_each_entry() {
620 let bad = r#"
622[[std.capabilities."wasi:filesystem".allow]]
623path = "/tmp/**"
624"#;
625 #[derive(serde::Deserialize)]
626 struct Wrap {
627 std: Std,
628 }
629 #[derive(serde::Deserialize)]
630 struct Std {
631 capabilities: Capabilities,
632 }
633 assert!(
634 toml::from_str::<Wrap>(bad).is_err(),
635 "missing mode must fail"
636 );
637 }
638
639 #[test]
640 fn http_cap_with_allow_roundtrips() {
641 let toml_input = r#"
642[std.capabilities."wasi:http"]
643description = "Calls OpenAI + GitHub"
644
645[[std.capabilities."wasi:http".allow]]
646host = "api.openai.com"
647scheme = "https"
648methods = ["GET", "POST"]
649
650[[std.capabilities."wasi:http".allow]]
651host = "*.github.com"
652scheme = "https"
653"#;
654 #[derive(serde::Deserialize)]
655 struct Wrap {
656 std: Std,
657 }
658 #[derive(serde::Deserialize)]
659 struct Std {
660 capabilities: Capabilities,
661 }
662 let w: Wrap = toml::from_str(toml_input).expect("parses");
663 let http = w.std.capabilities.http.expect("http declared");
664 assert_eq!(http.allow.len(), 2);
665 assert_eq!(http.allow[0].host, "api.openai.com");
666 assert_eq!(http.allow[0].scheme.as_deref(), Some("https"));
667 assert_eq!(
668 http.allow[0].methods.as_deref(),
669 Some(&["GET".to_string(), "POST".to_string()][..])
670 );
671 assert_eq!(http.allow[1].host, "*.github.com");
672 }
673
674 #[test]
675 fn http_cap_requires_host_on_each_entry() {
676 let bad = r#"
678[[std.capabilities."wasi:http".allow]]
679scheme = "https"
680"#;
681 #[derive(serde::Deserialize)]
682 struct Wrap {
683 std: Std,
684 }
685 #[derive(serde::Deserialize)]
686 struct Std {
687 capabilities: Capabilities,
688 }
689 assert!(
690 toml::from_str::<Wrap>(bad).is_err(),
691 "missing host must fail"
692 );
693 }
694
695 #[test]
696 fn http_cap_wildcard_host() {
697 let toml_input = r#"
699[[std.capabilities."wasi:http".allow]]
700host = "*"
701"#;
702 #[derive(serde::Deserialize)]
703 struct Wrap {
704 std: Std,
705 }
706 #[derive(serde::Deserialize)]
707 struct Std {
708 capabilities: Capabilities,
709 }
710 let w: Wrap = toml::from_str(toml_input).expect("parses");
711 assert_eq!(w.std.capabilities.http.unwrap().allow[0].host, "*");
712 }
713}