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
#![feature(generators, generator_trait)]
#![feature(custom_attribute)]
#![feature(termination_trait_lib)]

pub extern crate osaka_macros;
pub extern crate mio;
pub extern crate log;

use std::io::Error;
use std::ops::{Generator, GeneratorState};
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use log::{warn, debug};
use std::time::{Duration, Instant};
use std::pin::Pin;

pub use osaka_macros::osaka;

/**
    convenience macro to wait for another future inside an osaka async fn

    if bar is a future that returns a string, for example:

    ```
    let foo : String = sync!(bar);
    printfn!("yo! {}", foo);
    ```

    this is asynchronous and does not block the current thread.
    Instead it will return the Again activation handle of `bar` if its not ready

*/
#[macro_export]
macro_rules! sync {
    ($task:expr) => {{
        use osaka::FutureResult;
        use osaka::Future;
        loop {
            match $task.poll() {
                FutureResult::Done(y) => {
                    break y;
                }
                FutureResult::Again(y) => {
                    yield y;
                }
            }
        }
    };};
}

#[macro_export]
macro_rules! try{
    ($e:expr) => {
        match $e {
            Err(e) => return $crate::FutureResult::Done(Err(e.into())),
            Ok(v) => v,
        }
    }
}
#[macro_export]
macro_rules! _try{
    ($e:expr) => {
        match $e {
            Err(e) => return $crate::FutureResult::Done(Err(e.into())),
            Ok(v) => v,
        }
    }
}

/// an activation token
#[derive(Clone)]
pub struct Token {
    m: mio::Token,
    active: Arc<AtomicUsize>,
}


/** Activation Handle

Again contains tokens that tell the execution engine when to reactivate this task.
*/

#[derive(Clone)]
pub struct Again {
    tokens:     Vec<Token>,
    deadline:   Option<Instant>,
    poll:       Arc<mio::Poll>,
}

impl Again {
    pub fn merge(&mut self, mut other: Again) {
        if let Some(mut t2) = other.deadline {
            let t = if let Some(ref mut t1) = self.deadline {
                if t1 > &mut t2 {
                    true
                } else {
                    false
                }
            } else {
                true
            };
            if t {
                self.deadline = Some(t2);
            }
        }
        self.tokens.append(&mut other.tokens);
    }
}

/// It's either done or we'll try again later
pub enum FutureResult<F> {
    Done(F),
    Again(Again),
}

/// something that can be resumed
pub trait Future<R> {
    fn poll(&mut self) -> FutureResult<R>;
}

/*
impl<R,X> Future<R> for X
where X: FnMut() -> FutureResult<R> {
    fn poll(&mut self) -> FutureResult<R> {
        (self)()
    }
}
*/

impl<R,X> Future<R> for X
where X: std::ops::Generator<Yield = Again, Return = R> + Unpin
{
    fn poll(&mut self) -> FutureResult<R> {
        match Pin::new(self).resume() {
            GeneratorState::Complete(y) => {
                FutureResult::Done(y)
            }
            GeneratorState::Yielded(a) => {
                FutureResult::Again(a)
            }
        }
    }
}

/**
  Task execution engine.

 */
#[derive(Clone)]
pub struct Poll {
    tokens: Arc<AtomicUsize>,
    poll:   Arc<mio::Poll>,
}

impl Poll {
    /// register a mio::Evented as a wake up source
    pub fn register<E: ?Sized>(
        &self,
        handle: &E,
        interest: mio::Ready,
        opts: mio::PollOpt,
    ) -> Result<Token, Error>
    where
        E: mio::Evented,
    {
        let token = mio::Token(self.tokens.fetch_add(1, Ordering::SeqCst));
        self.poll.register(handle, token, interest, opts)?;
        Ok(Token{
            m: token,
            active: Arc::new(AtomicUsize::new(0)),
        })
    }

    /// create an execution engine
    pub fn new() -> Self {
        Self {
            tokens: Arc::new(AtomicUsize::new(0)),
            poll:   Arc::new(mio::Poll::new().unwrap()),
        }
    }

    /// returns an Again that will never be activated because it contains no wakeup sources
    pub fn never(&self) -> Again {
        Again { poll: self.poll.clone(), tokens: Vec::new(), deadline: None }
    }

    /// wake up after the specified time has passed
    pub fn later(&self, deadline: Duration) -> Again {
        Again { poll: self.poll.clone(), tokens: Vec::new(), deadline: Some(Instant::now() + deadline)}
    }

    /// wake up either when the token is ready or after the specified time has passed
    pub fn again(&self, token: Token, deadline: Option<Duration>) -> Again {
        Again { poll: self.poll.clone(), tokens: vec![token], deadline: deadline.map(|v|Instant::now() + v) }
    }

    /// wake up when any of the tokens is ready or after the specified time has passed
    pub fn any(&self, tokens:Vec<Token>, deadline: Option<Duration>) -> Again {
        Again { poll: self.poll.clone(), tokens, deadline: deadline.map(|v|Instant::now() + v) }
    }
}


/**
Something that can be activated

An osaka task is usually constructed by adding the osaka macro to a function, like so:

```
#[osaka]
fn the_answer(poll: osaka::Poll) -> u32 {
    let oracle = Oracle{};
    let token = poll.register(oracle);
    if oracle.is_ready() {
        return 42;
    } else {
        yield poll.again(token);
    }
}
```

*/
pub enum Task<R> {
    Later {
        f: Box<Future<R>>,
        a: Again,
    },
    Immediate {
        r: Option<R>,
    }
}

impl<R> Task<R> {

    /// run a task to completion, blocking the current thread.
    ///
    /// this is not re-entrant, meaning you cannot call this function from some callback.
    /// It is also not thread safe. Basically only ever call this once, prefferably in main.
    pub fn run(&mut self) -> R {
        loop {
            match self {
                Task::Immediate{r} =>  {
                    return r.take().expect("immediate polled after completion");
                }
                Task::Later{f,a} =>  {
                    let mut events = mio::Events::with_capacity(1024);
                    let mut timeout = None;
                    if let Some(deadline) = a.deadline {
                        let now = Instant::now();
                        if now > deadline {
                            warn!("deadline already expired. will loop in 1ms");
                            timeout = Some(Duration::from_millis(1));
                        } else {
                            timeout = Some(deadline - now);
                        }
                    }

                    if a.tokens.len() == 0 {
                        panic!("trying to run() with 0 tokens, this is not going to do anything useful.\n
                       forgot to pass a token with poll.again() ?");
                    }


                    debug!("going to poll with timeout {:?} and {} tokens",
                           timeout,
                           a.tokens.len());

                    a.poll.poll(&mut events, timeout).expect("poll");

                    for token in &a.tokens {
                        token.active.store(0, Ordering::SeqCst);
                    }
                    for event in &events {
                        for token in &a.tokens {
                            if event.token() == token.m {
                                debug!("token {:?} activated", token.m);
                                token.active.store(1, Ordering::SeqCst);
                            }
                        }
                    }

                }
            }
            if let FutureResult::Done(v) = self.poll() {
                return v;
            }
        }
    }

    /// the brave may construct a Task manually from a Future
    ///
    /// the passed Again instance needs to already contain an activation source,
    /// or the task will never be executed
    ///
    ///
    /// for example:
    ///
    /// ```
    /// struct Santa {
    ///     poll: Poll
    /// }
    ///
    /// impl Future for Santa {
    ///     fn poll(&mut self) -> FutureResult<Present> {
    ///         FutureResult::Again(self.poll.never())
    ///     }
    /// }
    ///
    /// fn main() {
    ///     let poll = Poll::new();
    ///     let santa = Santa{poll};
    ///     santa.run().unwrap();
    /// }
    ///
    /// ```
    pub fn new(f: Box<Future<R>>, a: Again) -> Self {
        Task::Later{f,a}
    }



    /// force a wakeup the next time `activate` is called. This is for a poor implementation of
    /// channels and you should probably not use this.
    pub fn wakeup_now(&mut self)  {
        if let Task::Later{f,a} = self {
            a.deadline = Some(Instant::now());
        }
    }


    pub fn immediate(t:R) -> Task<R> {
        Task::Immediate{r:Some(t)}
    }

}

impl<R> Future<R> for Task<R> {
    /// this is called by the execution engine, or a sync macro.
    ///
    /// you can call this by hand, but it won't actually do anything unless the task
    /// contains a token that is ready, or has an expired deadline
    fn poll(&mut self) -> FutureResult<R> {
        match self {
            Task::Immediate{r} =>  {
                return FutureResult::Done(r.take().expect("immediate polled after completion"));
            }
            Task::Later{f,a} =>  {
                let mut ready = false;

                if let Some(deadline) = a.deadline {
                    if Instant::now() >= deadline {
                        debug!("task wakeup caused by deadline");
                        a.deadline = None;
                        ready = true;
                    }
                }

                if !ready {
                    for token in &a.tokens {
                        if token.active.load(Ordering::SeqCst) > 0 {
                            debug!("task wakeup caused by token readyness");
                            ready = true;
                            break;
                        }
                    }
                }

                if ready {
                    match f.poll() {
                        FutureResult::Done(y) => {
                            return FutureResult::Done(y);
                        },
                        FutureResult::Again(a2) => {
                            *a = a2;
                        }
                    }
                }

                FutureResult::Again(a.clone())
            }
        }
    }
}




impl<E:  std::fmt::Debug> std::process::Termination for Task<Result<(), E>> {
    fn report(mut self) -> i32 {
        match self.run() {
            Ok(()) => 0,
            Err(e) => {
                eprintln!("{:?}", e);
                2
            }
        }
    }
}