omnia_wasi_messaging/host/
resource.rs1use std::any::Any;
2use std::collections::HashMap;
3use std::fmt::Debug;
4use std::ops::{Deref, DerefMut};
5use std::pin::Pin;
6use std::sync::Arc;
7
8use futures::Stream;
9pub use omnia::FutureResult;
10use serde::{Deserialize, Serialize};
11
12use crate::host::generated::wasi::messaging::types;
13pub type Subscriptions = Pin<Box<dyn Stream<Item = MessageProxy> + Send>>;
15
16#[allow(unused_variables)]
18pub trait Client: Debug + Send + Sync + 'static {
19 fn subscribe(&self) -> FutureResult<Subscriptions>;
21
22 fn send(&self, topic: String, message: MessageProxy) -> FutureResult<()>;
24
25 fn request(
27 &self, topic: String, message: MessageProxy, options: Option<RequestOptions>,
28 ) -> FutureResult<MessageProxy>;
29}
30
31#[derive(Clone, Debug)]
33pub struct ClientProxy(pub Arc<dyn Client>);
34
35impl Deref for ClientProxy {
36 type Target = Arc<dyn Client>;
37
38 fn deref(&self) -> &Self::Target {
39 &self.0
40 }
41}
42
43pub trait Message: Debug + Send + Sync + 'static {
46 fn topic(&self) -> String;
48
49 fn payload(&self) -> Vec<u8>;
51
52 fn metadata(&self) -> Option<Metadata>;
54
55 fn description(&self) -> Option<String>;
57
58 fn length(&self) -> usize;
60
61 fn reply(&self) -> Option<Reply>;
63
64 fn as_any(&self) -> &dyn Any;
66}
67
68#[derive(Clone, Debug)]
70pub struct MessageProxy(pub Arc<dyn Message>);
71
72impl Deref for MessageProxy {
73 type Target = Arc<dyn Message>;
74
75 fn deref(&self) -> &Self::Target {
76 &self.0
77 }
78}
79
80impl DerefMut for MessageProxy {
81 fn deref_mut(&mut self) -> &mut Self::Target {
82 &mut self.0
83 }
84}
85
86#[derive(Clone, Debug, Default, Deserialize, Serialize)]
88pub struct Metadata {
89 pub inner: HashMap<String, String>,
91}
92
93impl Metadata {
94 #[must_use]
96 pub fn new() -> Self {
97 Self {
98 inner: HashMap::new(),
99 }
100 }
101}
102
103impl Deref for Metadata {
104 type Target = HashMap<String, String>;
105
106 fn deref(&self) -> &Self::Target {
107 &self.inner
108 }
109}
110
111impl DerefMut for Metadata {
112 fn deref_mut(&mut self) -> &mut Self::Target {
113 &mut self.inner
114 }
115}
116
117impl From<Metadata> for types::Metadata {
118 fn from(meta: Metadata) -> Self {
119 let mut metadata = Self::new();
120 for (k, v) in meta.inner {
121 metadata.push((k, v));
122 }
123 metadata
124 }
125}
126
127impl From<types::Metadata> for Metadata {
128 fn from(meta: types::Metadata) -> Self {
129 let mut map = HashMap::new();
130 for (k, v) in meta {
131 map.insert(k, v);
132 }
133 Self { inner: map }
134 }
135}
136
137#[derive(Clone, Debug, Default, Deserialize, Serialize)]
139pub struct Reply {
140 pub client_name: String,
142 pub topic: String,
144}
145
146#[derive(Default, Clone)]
148pub struct RequestOptions {
149 pub timeout: Option<std::time::Duration>,
151 pub expected_replies: Option<u32>,
153}