1use std::collections::HashMap;
9use std::sync::{Arc, Mutex};
10
11use async_trait::async_trait;
12use futures::io::{AsyncReadExt, AsyncWriteExt};
13use tokio::sync::mpsc;
14use weirdnet_net::member::Membership;
15use weirdnet_net::node::Message;
16use weirdnet_net::user::{Card, NodeCert};
17use weirdnet_net::{AppBody, AppResponse, Incoming, Limits, Multiaddr, NetError, Node, PeerId, Stream};
18
19use crate::codec::{FrameDecoder, MAX_FRAME, encode_frame, from_cbor, to_cbor};
20use crate::feed::AccessFn;
21use crate::{
22 Access, Authorize, Channel, Credentials, Dialer, FeedOptions, FrameRx, FrameTx, Hub, ProtocolId, Service, ServiceError, SessionOptions, State,
23 Topic,
24};
25
26pub fn stream_limits() -> Limits {
29 Limits { idle: None, ..Limits::default() }
30}
31
32impl Credentials {
33 pub fn with_node_cert(self, cert: &NodeCert) -> Self {
35 self.with_cert(to_cbor(cert).unwrap_or_default())
36 }
37
38 pub fn with_user_card(self, card: &Card) -> Self {
40 self.with_card(to_cbor(card).unwrap_or_default())
41 }
42
43 pub fn with_membership_of(self, membership: &Membership) -> Self {
45 self.with_membership(to_cbor(membership).unwrap_or_default())
46 }
47
48 pub fn node_cert(&self) -> Option<Result<NodeCert, ServiceError>> {
50 self.cert().map(from_cbor)
51 }
52
53 pub fn user_card(&self) -> Option<Result<Card, ServiceError>> {
55 self.card().map(from_cbor)
56 }
57}
58
59struct Tx(mpsc::Sender<Vec<u8>>);
60struct Rx(mpsc::Receiver<Result<Vec<u8>, ServiceError>>);
61
62#[async_trait]
63impl FrameTx for Tx {
64 async fn send(&mut self, message: Vec<u8>) -> Result<(), ServiceError> {
65 self.0.send(message).await.map_err(|_| ServiceError::Closed)
66 }
67}
68
69#[async_trait]
70impl FrameRx for Rx {
71 async fn recv(&mut self) -> Result<Option<Vec<u8>>, ServiceError> {
72 match self.0.recv().await {
73 Some(Ok(m)) => Ok(Some(m)),
74 Some(Err(e)) => Err(e),
75 None => Ok(None),
76 }
77 }
78}
79
80pub fn channel(stream: Stream) -> Channel {
84 channel_with(stream, MAX_FRAME)
85}
86
87pub fn channel_with(stream: Stream, max_frame: usize) -> Channel {
89 let (out_tx, mut out_rx) = mpsc::channel::<Vec<u8>>(16);
90 let (in_tx, in_rx) = mpsc::channel::<Result<Vec<u8>, ServiceError>>(64);
91 tokio::spawn(async move {
92 let (mut r, mut w) = stream.split();
93 let mut decoder = FrameDecoder::new(max_frame);
94 let mut buf = vec![0u8; 64 * 1024];
95 let mut writing = true;
96 let mut reader = Some(in_tx);
97 loop {
98 if !writing && reader.as_ref().is_none_or(|t| t.is_closed()) {
99 break;
100 }
101 tokio::select! {
102 m = out_rx.recv(), if writing => match m {
103 Some(message) => {
104 let ok = match encode_frame(&message, max_frame) {
105 Ok(bytes) => w.write_all(&bytes).await.is_ok() && w.flush().await.is_ok(),
106 Err(_) => false,
107 };
108 if !ok {
109 writing = false;
110 if let Some(t) = reader.take() {
111 let _ = t.send(Err(ServiceError::Closed)).await;
112 }
113 }
114 }
115 None => {
116 writing = false;
117 let _ = w.close().await;
118 }
119 },
120 n = r.read(&mut buf), if reader.is_some() => match n {
121 Ok(0) => reader = None,
122 Ok(n) => {
123 decoder.push(&buf[..n]);
124 loop {
125 match decoder.next_frame() {
126 Ok(Some(m)) => {
127 if let Some(t) = &reader && t.send(Ok(m)).await.is_err() {
128 reader = None;
129 break;
130 }
131 }
132 Ok(None) => break,
133 Err(e) => {
134 if let Some(t) = reader.take() {
135 let _ = t.send(Err(e)).await;
136 }
137 break;
138 }
139 }
140 }
141 }
142 Err(e) => {
143 if let Some(t) = reader.take() {
144 let _ = t.send(Err(ServiceError::Unreachable { message: e.to_string() })).await;
145 }
146 }
147 },
148 _ = async { match &reader { Some(t) => t.closed().await, None => std::future::pending().await } }, if !writing => {
149 reader = None;
150 }
151 }
152 }
153 });
154 Channel::new(Box::new(Tx(out_tx)), Box::new(Rx(in_rx)))
155}
156
157pub fn open_error(e: NetError) -> ServiceError {
160 let message = e.to_string();
161 if message.contains("does not accept") { ServiceError::Unsupported { message } } else { ServiceError::Unreachable { message } }
162}
163
164pub struct NetDialer<Q: Message, R: Message> {
167 node: Arc<Node<Q, R>>,
168 hints: Mutex<HashMap<PeerId, Vec<Multiaddr>>>,
169}
170
171impl<Q: Message, R: Message> NetDialer<Q, R> {
172 pub fn new(node: Arc<Node<Q, R>>) -> Self {
173 Self { node, hints: Mutex::new(HashMap::new()) }
174 }
175
176 pub fn hint(&self, peer: PeerId, addrs: Vec<Multiaddr>) {
177 self.hints.lock().unwrap_or_else(|e| e.into_inner()).insert(peer, addrs);
178 }
179}
180
181#[async_trait]
182impl<Q: Message, R: Message> Dialer for NetDialer<Q, R> {
183 async fn open(&self, node: &str, protocol: &str) -> Result<Channel, ServiceError> {
184 let peer: PeerId = node.parse().map_err(|_| ServiceError::Unreachable { message: format!("{node} is not a peer id") })?;
185 let addrs = self.hints.lock().unwrap_or_else(|e| e.into_inner()).get(&peer).cloned().unwrap_or_default();
186 let stream = self.node.open_stream_async(peer, &addrs, protocol, stream_limits()).await.map_err(open_error)?;
187 Ok(channel(stream))
188 }
189}
190
191type Start<Q, R> = Box<dyn FnOnce(&Arc<Node<Q, R>>) -> Result<tokio::task::JoinHandle<()>, ServiceError> + Send>;
192
193pub struct ServerBuilder<Q: Message, R: Message> {
195 node: Arc<Node<Q, R>>,
196 starts: Vec<Start<Q, R>>,
197 protocols: Vec<ProtocolId>,
198 announce: Option<String>,
199}
200
201fn accept_loop(mut incoming: Incoming, serve: impl Fn(Channel, String) + Send + 'static) -> tokio::task::JoinHandle<()> {
202 tokio::spawn(async move {
203 while let Some(stream) = incoming.next().await {
204 let peer = stream.peer().to_string();
205 serve(channel(stream), peer);
206 }
207 })
208}
209
210fn accept<Q: Message, R: Message>(node: &Arc<Node<Q, R>>, protocol: &ProtocolId) -> Result<Incoming, ServiceError> {
211 node.accept_streams(protocol.as_str(), stream_limits()).map_err(|e| ServiceError::failed(e.to_string()))
212}
213
214impl<Q: Message, R: Message> ServerBuilder<Q, R> {
215 pub fn service<S: Service>(mut self, protocol: &ProtocolId, service: Arc<S>, auth: Arc<dyn Authorize>, options: SessionOptions) -> Self {
217 let p = protocol.clone();
218 self.protocols.push(p.clone());
219 self.starts.push(Box::new(move |node| {
220 let incoming = accept(node, &p)?;
221 let options = Arc::new(options);
222 Ok(accept_loop(incoming, move |ch, peer| {
223 let (svc, auth, options) = (service.clone(), auth.clone(), options.clone());
224 tokio::spawn(async move {
225 let _ = crate::serve_session(svc, auth, ch, peer, &options).await;
226 });
227 }))
228 }));
229 self
230 }
231
232 pub fn feed<T: Topic, S: State>(
235 mut self,
236 protocol: &ProtocolId,
237 hub: Arc<Hub<T, S>>,
238 access: impl Fn(&T) -> Access + Send + Sync + 'static,
239 auth: Arc<dyn Authorize>,
240 options: FeedOptions,
241 ) -> Self {
242 let p = protocol.clone();
243 self.protocols.push(p.clone());
244 let access: AccessFn<T> = Arc::new(access);
245 self.starts.push(Box::new(move |node| {
246 let incoming = accept(node, &p)?;
247 let options = Arc::new(options);
248 Ok(accept_loop(incoming, move |ch, peer| {
249 let (hub, access, auth, options) = (hub.clone(), access.clone(), auth.clone(), options.clone());
250 tokio::spawn(async move {
251 let _ = crate::serve_feed(hub, access, auth, ch, peer, &options).await;
252 });
253 }))
254 }));
255 self
256 }
257
258 pub fn announce(mut self, app: &str) -> Self {
260 self.announce = Some(app.to_string());
261 self
262 }
263
264 pub fn start(self) -> Result<Server, ServiceError> {
266 let mut seen = std::collections::HashSet::new();
267 if let Some(dup) = self.protocols.iter().find(|p| !seen.insert(p.as_str())) {
268 return Err(ServiceError::bad_request(format!("{dup} is registered twice")));
269 }
270 let mut server = Server { tasks: Vec::new(), stop: None, protocols: self.protocols.clone() };
271 for s in self.starts {
272 server.tasks.push(s(&self.node)?);
273 }
274 if let Some(app) = self.announce {
275 let ids: Vec<&str> = self.protocols.iter().map(|p| p.as_str()).collect();
276 let body = to_cbor(&ids)?;
277 self.node
278 .serve_app(
279 &app,
280 Arc::new(move |_peer, _req| {
281 let body = body.clone();
282 async move { Ok(AppResponse::new(200).header("content-type", "application/cbor").body(AppBody::bytes(body))) }
283 }),
284 )
285 .map_err(|e| ServiceError::failed(e.to_string()))?;
286 let node = self.node.clone();
287 server.stop = Some(Box::new(move || {
288 node.stop_serving_app(&app);
289 }));
290 }
291 Ok(server)
292 }
293}
294
295pub struct Server {
298 tasks: Vec<tokio::task::JoinHandle<()>>,
299 stop: Option<Box<dyn FnOnce() + Send>>,
300 protocols: Vec<ProtocolId>,
301}
302
303impl Server {
304 pub fn builder<Q: Message, R: Message>(node: &Arc<Node<Q, R>>) -> ServerBuilder<Q, R> {
305 ServerBuilder { node: node.clone(), starts: Vec::new(), protocols: Vec::new(), announce: None }
306 }
307
308 pub fn protocols(&self) -> &[ProtocolId] {
310 &self.protocols
311 }
312}
313
314impl Drop for Server {
315 fn drop(&mut self) {
316 for t in &self.tasks {
317 t.abort();
318 }
319 if let Some(stop) = self.stop.take() {
320 stop();
321 }
322 }
323}