1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
|
//! A Mycelium daemon's API as it behaves for the transport, and the transport's tests
//! against it. Its node is behind one lock, which a request for the inbox holds for as long
//! as it waits for a message, and which every other request waits for: Mycelium 0.7's API
//! does so (`mycelium-api`, its long poll holding the node's lock through its wait). Messages
//! come into the inbox beside that lock, as they come from the network. It is served by axum,
//! as Mycelium's API is.
use std::collections::VecDeque;
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::Duration;
use axum::extract::{Query, State};
use axum::http::StatusCode;
use axum::response::{IntoResponse, Response};
use axum::routing::get;
use axum::{Json, Router};
use serde::Deserialize;
use serde_json::{Value, json};
use url::Url;
use super::daemon::MyceliumRuntime;
use super::{MyceliumSetup, MyceliumTransport, encode_message};
use crate::transport::{MessageHandler, ParsedMessage, Transport, is_probe, wire};
/// Our daemon's public key, and a peer's.
const OURS: &str = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
const THEIRS: &str = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb";
/// Long enough for anything the transport does at once, short against Mycelium's long poll.
const SOON: Duration = Duration::from_secs(2);
#[derive(Default)]
struct Daemon {
/// The node, behind its lock.
node: tokio::sync::Mutex<()>,
inbox: std::sync::Mutex<VecDeque<Value>>,
came: tokio::sync::Notify,
/// Requests for the inbox begun, and messages taken to send.
polls: AtomicUsize,
sent: AtomicUsize,
}
impl Daemon {
/// A message from the network, into the inbox.
fn comes(&self, message: Value) {
self.inbox.lock().expect("the inbox").push_back(message);
self.came.notify_waiters();
}
fn polls(&self) -> usize {
self.polls.load(Ordering::SeqCst)
}
}
#[derive(Deserialize)]
struct Asked {
#[serde(default)]
timeout: u64,
#[serde(default)]
peek: bool,
}
async fn admin() -> Json<Value> {
Json(json!({"nodePubkey": OURS}))
}
/// The inbox's next message, popped or peeked at, waiting for one up to `timeout` seconds
/// with the node's lock held.
async fn inbox(State(daemon): State<Arc<Daemon>>, Query(asked): Query<Asked>) -> Response {
daemon.polls.fetch_add(1, Ordering::SeqCst);
let _node = daemon.node.lock().await;
let until = tokio::time::Instant::now() + Duration::from_secs(asked.timeout);
loop {
let came = daemon.came.notified();
tokio::pin!(came);
came.as_mut().enable();
let taken = {
let mut inbox = daemon.inbox.lock().expect("the inbox");
if asked.peek {
inbox.front().cloned()
} else {
inbox.pop_front()
}
};
if let Some(message) = taken {
return Json(message).into_response();
}
if asked.timeout == 0 {
return StatusCode::NO_CONTENT.into_response();
}
tokio::select! {
() = &mut came => {}
() = tokio::time::sleep_until(until) => return StatusCode::NO_CONTENT.into_response(),
}
}
}
async fn push(State(daemon): State<Arc<Daemon>>) -> Response {
let _node = daemon.node.lock().await;
daemon.sent.fetch_add(1, Ordering::SeqCst);
(StatusCode::CREATED, Json(json!({"id": "0123456789abcdef"}))).into_response()
}
/// A daemon serving its API, and where.
async fn started() -> (Arc<Daemon>, Url) {
let daemon = Arc::new(Daemon::default());
let app = Router::new()
.route("/api/v1/admin", get(admin))
.route("/api/v1/messages", get(inbox).post(push))
.with_state(daemon.clone());
let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
.await
.expect("a port");
let url = Url::parse(&format!(
"http://{}/",
listener.local_addr().expect("bound")
))
.expect("a URL");
tokio::spawn(async move {
let _ = axum::serve(listener, app).await;
});
(daemon, url)
}
/// A transport using the daemon at `url`, taking what comes in, and what it took.
async fn taking(
url: Url,
) -> (
Arc<MyceliumTransport>,
tokio::sync::mpsc::UnboundedReceiver<ParsedMessage>,
) {
let transport = Arc::new(
MyceliumTransport::connect(MyceliumSetup {
runtime: MyceliumRuntime::External,
rest_url: url,
})
.await
.expect("connected"),
);
let (tx, rx) = tokio::sync::mpsc::unbounded_channel();
let handler: MessageHandler = Box::new(move |_, message, _| {
let tx = tx.clone();
Box::pin(async move {
let _ = tx.send(message);
Ok(())
})
});
let consuming = transport.clone();
tokio::spawn(async move { consuming.start_consumer(handler).await });
(transport, rx)
}
/// Waits until `daemon` has had a request for its inbox: the transport's first, which
/// waits there while nothing comes in.
async fn polled(daemon: &Daemon) {
tokio::time::timeout(SOON, async {
while daemon.polls() == 0 {
tokio::time::sleep(Duration::from_millis(10)).await;
}
})
.await
.expect("the inbox polled");
}
fn a_message() -> ParsedMessage {
wire::samples()
.into_iter()
.find(|message| !is_probe(message))
.expect("a message other than a probe")
}
/// `message` as the daemon gives it from the inbox, from the peer.
fn inbound(message: &ParsedMessage) -> Value {
let encoded = encode_message(OURS, message, wire::VERSION).expect("encoded");
let outbound: Value = serde_json::from_slice(&encoded.body).expect("JSON");
json!({
"id": "fedcba9876543210",
"srcPk": THEIRS,
"topic": outbound["topic"],
"payload": outbound["payload"],
})
}
/// A node with nothing coming in sends at once: no request for the inbox holds up its
/// messages.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_node_with_nothing_coming_in_sends_at_once() {
let (daemon, url) = started().await;
let (transport, _taken) = taking(url).await;
// The inbox is waited for in the daemon by now.
polled(&daemon).await;
tokio::time::sleep(Duration::from_millis(100)).await;
let message = encode_message(THEIRS, &a_message(), wire::VERSION).expect("encoded");
for n in 1..=3 {
let sent = tokio::time::timeout(SOON, transport.send_encoded(&message)).await;
assert!(
matches!(sent, Ok(Ok(()))),
"send {n} held up while nothing comes in: {sent:?}"
);
assert_eq!(daemon.sent.load(Ordering::SeqCst), n);
}
}
/// A message coming in is taken as it comes.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_message_is_taken_as_it_comes() {
let (daemon, url) = started().await;
let (_transport, mut taken) = taking(url).await;
polled(&daemon).await;
for _ in 0..3 {
tokio::time::sleep(Duration::from_millis(100)).await;
daemon.comes(inbound(&a_message()));
let got = tokio::time::timeout(SOON, taken.recv()).await;
assert!(matches!(got, Ok(Some(_))), "not taken: {got:?}");
}
}
/// A node with nothing coming in, and nothing to send, asks its daemon for nothing again
/// and again: what it asked waits there.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn an_idle_node_asks_its_daemon_nothing_again_and_again() {
let (daemon, url) = started().await;
let (_transport, _taken) = taking(url).await;
let before = daemon.polls();
tokio::time::sleep(Duration::from_secs(1)).await;
let asked = daemon.polls() - before;
assert!(
asked <= 2,
"{asked} requests for the inbox in an idle second"
);
}
/// Messages coming in while the node sends all come in, and every send goes out.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn messages_coming_while_the_node_sends_all_come_in() {
const MESSAGES: usize = 50;
let (daemon, url) = started().await;
let (transport, mut taken) = taking(url).await;
polled(&daemon).await;
let message = encode_message(THEIRS, &a_message(), wire::VERSION).expect("encoded");
let sending = tokio::spawn({
let transport = transport.clone();
async move {
for _ in 0..MESSAGES {
transport.send_encoded(&message).await?;
tokio::time::sleep(Duration::from_millis(3)).await;
}
anyhow::Ok(())
}
});
let coming = tokio::spawn({
let daemon = daemon.clone();
async move {
for _ in 0..MESSAGES {
daemon.comes(inbound(&a_message()));
tokio::time::sleep(Duration::from_millis(2)).await;
}
}
});
let all = Duration::from_secs(10);
let sent = tokio::time::timeout(all, sending).await;
assert!(matches!(sent, Ok(Ok(Ok(())))), "sends held up: {sent:?}");
coming.await.expect("all came");
for n in 0..MESSAGES {
let got = tokio::time::timeout(all, taken.recv()).await;
assert!(
matches!(got, Ok(Some(_))),
"{n} of {MESSAGES} messages taken"
);
}
assert_eq!(daemon.sent.load(Ordering::SeqCst), MESSAGES);
}
|