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
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
use futures::Stream;
use std::collections::HashMap;
use std::net::SocketAddr;
use std::pin::Pin;
use std::sync::{Arc, Mutex};
use std::task::{Context, Poll, Waker};
use url::Url;
use uuid::Uuid;
use async_channel::{unbounded, Receiver, Sender, TryRecvError};
use hyper::service::{make_service_fn, service_fn};
use hyper::{Body, Request, Response};
use thiserror::Error;
const QUERY_PARAM_NAME: &'static str = "_async_webhook_id";
#[derive(Debug, Error)]
enum Error {
#[error("Webhook receiver expected a unique UID but none was found")]
WebhookMissingUid,
}
struct Registry {
drop: Sender<Uuid>,
requests: Arc<Mutex<HashMap<Uuid, (Arc<Mutex<Option<Waker>>>, Sender<Request<Body>>)>>>,
}
impl Clone for Registry {
fn clone(&self) -> Self {
Registry {
drop: self.drop.clone(),
requests: Arc::clone(&self.requests),
}
}
}
impl Registry {
fn new() -> Self {
let (drop, mut handle_drop) = unbounded::<Uuid>();
let requests = Arc::new(Mutex::new(HashMap::new()));
{
let requests = requests.clone();
use tokio::stream::StreamExt;
tokio::task::spawn(async move {
for id in handle_drop.next().await {
requests.lock().unwrap().remove(&id);
}
});
}
Self { drop, requests }
}
fn register(&self, uid: Uuid) -> (Arc<Mutex<Option<Waker>>>, Receiver<Request<Body>>) {
let (sender, receiver) = unbounded();
let mut g = self.requests.lock().unwrap();
let waker = Arc::new(Mutex::new(None));
g.insert(uid, (waker.clone(), sender));
(waker, receiver)
}
fn notify(&self, uid: Uuid, t: Request<Body>) {
let mut g = self.requests.lock().unwrap();
if let Some((waker, sender)) = g.remove(&uid) {
sender.try_send(t).unwrap();
waker.lock().unwrap().as_ref().map(|waker| {
waker.wake_by_ref();
});
}
}
}
impl Drop for Webhook {
fn drop(&mut self) {
self.dropper
.try_send(self.uid.clone())
.expect("Registry should have an open channel to receive dropped requests");
}
}
pub struct Webhook {
url: Url,
uid: Uuid,
value: Option<Receiver<Request<Body>>>,
dropper: Sender<Uuid>,
waker: Arc<Mutex<Option<Waker>>>,
}
impl Webhook {
pub fn url(&self) -> &Url {
&self.url
}
}
impl Stream for Webhook {
type Item = Request<Body>;
fn poll_next(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
let this = Pin::into_inner(self);
*this.waker.lock().unwrap() = Some(_cx.waker().clone());
if let Some(receiver) = this.value.take() {
match receiver.try_recv() {
Ok(l) => Poll::Ready(Some(l)),
Err(TryRecvError::Empty) => Poll::Pending,
Err(_) => Poll::Pending,
}
} else {
panic!("Internal state inconsistent");
}
}
}
#[derive(Clone)]
pub struct Server {
endpoint: url::Url,
addr: SocketAddr,
registry: Registry,
stop: Sender<()>,
}
impl Drop for Server {
fn drop(&mut self) {
self.stop.try_send(()).unwrap();
}
}
impl Server {
pub fn new<A: Into<SocketAddr>>(addr: A) -> Self {
let addr = addr.into();
let endpoint = Url::parse(format!("http://{}", addr).as_str()).unwrap();
let registry = Registry::new();
type BoxError = Box<dyn std::error::Error + Send + Sync>;
async fn handle_request(
registry: Registry,
request: Request<Body>,
) -> Result<Response<Body>, BoxError> {
let registry = registry.clone();
let url = format!("http://localhost{}", request.uri());
let url = Url::parse(url.as_str()).expect("hyper::Uri is url::Url parsable");
let uid = url
.query_pairs()
.find(|(k, _)| k.as_ref() == QUERY_PARAM_NAME)
.map(|(_, uid)| {
Uuid::parse_str(uid.as_ref()).map_err(|_| Error::WebhookMissingUid)
})
.ok_or_else(|| Error::WebhookMissingUid)??;
registry.notify(uid, request);
Ok(Response::new(Body::from("Hello World")))
}
let keep_registry = registry.clone();
let make_service = make_service_fn(move |_conn| {
let registry = registry.clone();
async move {
Ok::<_, Error>(service_fn(move |request| {
let registry = registry.clone();
handle_request(registry, request)
}))
}
});
let (stop, on_stop) = async_channel::bounded::<()>(1);
let server = hyper::Server::bind(&addr)
.serve(make_service)
.with_graceful_shutdown(async move {
on_stop.recv().await.ok();
});
tokio::spawn(server);
Server {
addr,
registry: keep_registry,
stop,
endpoint,
}
}
pub fn set_endpoint(&mut self, url: Url) {
self.endpoint = url;
}
pub fn spawn(&self) -> Webhook {
let uid = Uuid::new_v4();
let url = {
let mut url = self.endpoint.clone();
url.query_pairs_mut()
.append_pair(QUERY_PARAM_NAME, uid.to_string().as_str());
url
};
let (waker, value) = self.registry.register(uid.clone());
let dropper = self.registry.drop.clone();
Webhook {
url,
uid,
value: Some(value),
dropper,
waker,
}
}
}
#[cfg(test)]
mod tests {
use crate::{Server, Webhook};
use futures::{StreamExt, TryStreamExt};
use serde::{Deserialize, Serialize};
#[tokio::test]
async fn test_callback_pattern() {
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize)]
struct Request {
message: String,
callback: String,
}
#[derive(Serialize, Deserialize)]
struct Response {
message: String,
}
eprintln!("Spawning API Server");
let api_server = {
use warp::Filter;
let api_route =
warp::any()
.and(warp::body::json::<Request>())
.and_then(|req: Request| async {
let client = reqwest::Client::new();
eprintln!(
"API received message, sending callback to: {}",
req.callback.as_str()
);
match client
.post(req.callback.as_str())
.json(&Response {
message: req.message,
})
.send()
.await
{
Ok(r) => {
eprintln!("Webhook server responded with status: {}", r.status());
Ok(warp::reply())
}
Err(_) => Err(warp::reject::reject()),
}
});
tokio::spawn(warp::serve(api_route).run(([127, 0, 0, 1], 3032)))
};
eprintln!("Starting callback server");
let server: Server = Server::new(([127, 0, 0, 1], 3031));
eprintln!("Sending API request");
let mut webhook: Webhook = server.spawn();
let client = reqwest::Client::new();
client
.post("http://localhost:3032")
.json(&Request {
callback: webhook.url().to_string(),
message: "hey".to_string(),
})
.send()
.await;
let res: Option<Response> = if let Some(response) = webhook.next().await {
let bytes = response
.into_body()
.try_fold(Vec::new(), |mut data, chunk| async move {
data.extend_from_slice(&chunk);
Ok(data)
})
.await
.unwrap();
serde_json::from_slice(bytes.as_slice()).unwrap()
} else {
None
};
assert_eq!(res.unwrap().message.as_str(), "hey");
}
}