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
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
use super::desync::*;
use futures::*;
use futures::executor;
use futures::executor::Spawn;
use std::mem;
use std::sync::*;
use std::ops::Deref;
use std::result::Result;
use std::collections::VecDeque;
lazy_static! {
static ref PIPE_MONITOR: PipeMonitor = PipeMonitor::new();
static ref REFERENCE_CHUTE: Desync<()> = Desync::new(());
}
const PIPE_BACKPRESSURE_COUNT: usize = 5;
struct LazyDrop<Core: 'static+Send> {
reference: Option<Arc<Desync<Core>>>
}
impl<Core: 'static+Send> LazyDrop<Core> {
pub fn new(reference: Arc<Desync<Core>>) -> LazyDrop<Core> {
LazyDrop {
reference: Some(reference)
}
}
}
impl<Core: 'static+Send> Deref for LazyDrop<Core> {
type Target = Desync<Core>;
fn deref(&self) -> &Desync<Core> {
&*(self.reference.as_ref().unwrap())
}
}
impl<Core: 'static+Send> Drop for LazyDrop<Core> {
fn drop(&mut self) {
let reference = self.reference.take();
REFERENCE_CHUTE.desync(move |_| mem::drop(reference));
}
}
pub fn pipe_in<Core, S, ProcessFn>(desync: Arc<Desync<Core>>, stream: S, process: ProcessFn)
where Core: 'static+Send,
S: 'static+Send+Stream,
S::Item: Send,
S::Error: Send,
ProcessFn: 'static+Send+FnMut(&mut Core, Result<S::Item, S::Error>) -> () {
let mut stream = stream;
let desync = Arc::downgrade(&desync);
let process = Arc::new(Mutex::new(process));
PIPE_MONITOR.monitor(move || {
loop {
let desync = desync.upgrade();
if let Some(desync) = desync {
let desync = LazyDrop::new(desync);
let process = Arc::clone(&process);
let next = stream.poll();
match next {
Ok(Async::NotReady) => { return Ok(Async::NotReady); },
Ok(Async::Ready(None)) => { return Ok(Async::Ready(())); }
Ok(Async::Ready(Some(next))) => {
let when_ready = task::current();
desync.desync(move |core| {
{
let mut process = process.lock().unwrap();
let process = &mut *process;
process(core, Ok(next));
}
when_ready.notify();
});
return Ok(Async::NotReady);
},
Err(e) => {
let when_ready = task::current();
desync.desync(move |core| {
{
let mut process = process.lock().unwrap();
let process = &mut *process;
process(core, Err(e));
}
when_ready.notify()
});
},
}
} else {
return Ok(Async::Ready(()));
}
}
});
}
pub fn pipe<Core, S, Output, OutputErr, ProcessFn>(desync: Arc<Desync<Core>>, stream: S, process: ProcessFn) -> PipeStream<Output, OutputErr>
where Core: 'static+Send,
S: 'static+Send+Stream,
S::Item: Send,
S::Error: Send,
Output: 'static+Send,
OutputErr: 'static+Send,
ProcessFn: 'static+Send+FnMut(&mut Core, Result<S::Item, S::Error>) -> Result<Output, OutputErr> {
let mut input_stream = stream;
let process = Arc::new(Mutex::new(process));
let output_stream = PipeStream::new();
let stream_core = Arc::clone(&output_stream.core);
let stream_core = Arc::downgrade(&stream_core);
PIPE_MONITOR.monitor(move || {
loop {
let stream_core = stream_core.upgrade();
if let Some(stream_core) = stream_core {
{
let mut stream_core = stream_core.lock().unwrap();
if stream_core.pending.len() >= stream_core.max_pipe_depth {
stream_core.backpressure_release_notify = Some(task::current());
return Ok(Async::NotReady);
}
if stream_core.closed {
return Ok(Async::Ready(()));
}
}
let process = Arc::clone(&process);
let next = input_stream.poll();
let next_item;
match next {
Ok(Async::NotReady) => { return Ok(Async::NotReady); },
Ok(Async::Ready(None)) => {
let when_closed = task::current();
desync.desync(move |_core| {
let notify = {
let mut stream_core = stream_core.lock().unwrap();
stream_core.closed = true;
stream_core.notify.take()
};
notify.map(|notify| notify.notify());
when_closed.notify();
});
return Ok(Async::NotReady);
}
Ok(Async::Ready(Some(next))) => next_item = Ok(next),
Err(e) => next_item = Err(e),
}
let when_finished = task::current();
desync.desync(move |core| {
let mut process = process.lock().unwrap();
let process = &mut *process;
let next_item = process(core, next_item);
let notify = {
let mut stream_core = stream_core.lock().unwrap();
stream_core.pending.push_back(next_item);
stream_core.notify.take()
};
notify.map(|notify| notify.notify());
when_finished.notify();
});
return Ok(Async::NotReady);
} else {
return Ok(Async::Ready(()));
}
}
});
output_stream
}
struct PipeStreamCore<Item, Error> {
max_pipe_depth: usize,
pending: VecDeque<Result<Item, Error>>,
closed: bool,
notify: Option<task::Task>,
backpressure_release_notify: Option<task::Task>
}
pub struct PipeStream<Item, Error> {
core: Arc<Mutex<PipeStreamCore<Item, Error>>>
}
impl<Item, Error> PipeStream<Item, Error> {
fn new() -> PipeStream<Item, Error> {
PipeStream {
core: Arc::new(Mutex::new(PipeStreamCore {
max_pipe_depth: PIPE_BACKPRESSURE_COUNT,
pending: VecDeque::new(),
closed: false,
notify: None,
backpressure_release_notify: None
}))
}
}
pub fn set_backpressure_depth(&mut self, max_depth: usize) {
self.core.lock().unwrap().max_pipe_depth = max_depth;
}
}
impl<Item, Error> Drop for PipeStream<Item, Error> {
fn drop(&mut self) {
let mut core = self.core.lock().unwrap();
core.pending = VecDeque::new();
}
}
impl<Item, Error> Stream for PipeStream<Item, Error> {
type Item = Item;
type Error = Error;
fn poll(&mut self) -> Poll<Option<Item>, Error> {
let (result, notify) = {
let mut core = self.core.lock().unwrap();
if let Some(item) = core.pending.pop_front() {
let notify_backpressure = core.backpressure_release_notify.take();
match item {
Ok(item) => (Ok(Async::Ready(Some(item))), notify_backpressure),
Err(erm) => (Err(erm), notify_backpressure)
}
} else if core.closed {
(Ok(Async::Ready(None)), None)
} else {
let notify_backpressure = core.backpressure_release_notify.take();
core.notify = Some(task::current());
(Ok(Async::NotReady), notify_backpressure)
}
};
notify.map(|notify| notify.notify());
result
}
}
struct PipeMonitor {
}
struct PipeNotify<PollFn: Send> {
next_poll: Arc<Desync<Option<Spawn<PollFn>>>>
}
impl PipeMonitor {
pub fn new() -> PipeMonitor {
PipeMonitor {
}
}
fn poll<PollFn>(this_poll: &mut Option<Spawn<PollFn>>, next_poll: Arc<Desync<Option<Spawn<PollFn>>>>)
where PollFn: 'static+Send+Future<Item=(), Error=()> {
if let Some(mut poll) = this_poll.take() {
let notify = PipeNotify {
next_poll: next_poll
};
let notify = Arc::new(notify);
let poll_result = poll.poll_future_notify(¬ify, 0);
if poll_result != Ok(Async::Ready(())) {
*this_poll = Some(poll);
}
}
}
pub fn monitor<PollFn>(&self, poll_fn: PollFn)
where PollFn: 'static+Send+FnMut() -> Poll<(), ()> {
let poll_fn = future::poll_fn(poll_fn);
let poll_fn = executor::spawn(poll_fn);
let poll_fn = Arc::new(Desync::new(Some(poll_fn)));
let next_poll = Arc::clone(&poll_fn);
poll_fn.sync(move |poll_fn| Self::poll(poll_fn, next_poll));
}
}
impl<PollFn> executor::Notify for PipeNotify<PollFn>
where PollFn: 'static+Send+Future<Item=(), Error=()> {
fn notify(&self, _id: usize) {
let next_poll = Arc::clone(&self.next_poll);
self.next_poll.sync(move |poll_fn| PipeMonitor::poll(poll_fn, next_poll));
}
}