moirai 0.8.2

Async/await job system for game development
Documentation
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
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
use crate::{
    job::{Job, JobContext, JobHandle, JobLocation, JobObject, JobOptions, JobPriority, JobToken},
    jobs::{JobsMeta, JobsRuntime, JobsTags, JobsWaker, JobsWakerCommand},
    queue::JobQueue,
    third_party::time::{Duration, Instant},
};
use intuicio_data::{
    lifetime::LifetimeWeakState,
    managed::{DynamicManagedLazy, ManagedLazy},
};
use std::{
    future::poll_fn,
    hash::Hash,
    pin::{Pin, pin},
    sync::{Arc, Mutex, RwLock, atomic::Ordering, mpsc::Receiver},
    task::Poll,
};
use typid::ID;

#[derive(Default)]
pub struct OnExit {
    job: Option<JobObject>,
    queue: JobQueue,
    closure: Option<Box<dyn FnOnce() + Send + Sync>>,
}

impl Drop for OnExit {
    fn drop(&mut self) {
        if let Some(object) = self.job.take() {
            self.queue.enqueue(object);
        }
        if let Some(closure) = self.closure.take() {
            closure();
        }
    }
}

impl OnExit {
    pub fn invalidate(mut self) {
        self.job = None;
        self.closure = None;
    }
}

/// IMPORTANT: You must assign the result of this function to a named variable,
/// otherwise the future will be executed immediately!
#[must_use]
pub async fn on_exit(future: impl Future<Output = ()> + Send + Sync + 'static) -> OnExit {
    let mut job = Some(Job(Box::pin(future)));
    #[cfg(debug_assertions)]
    let creation_backtrace = std::backtrace::Backtrace::capture().to_string();
    poll_fn(move |cx| {
        let waker = cx.waker();
        let result = if let Some(waker) = JobsWaker::try_cast(waker) {
            if let Some(job) = job.take() {
                OnExit {
                    job: Some(JobObject {
                        id: ID::new(),
                        job,
                        context: Default::default(),
                        location: JobLocation::current_thread(),
                        priority: JobPriority::High,
                        cancel: waker.runtime.cancel.clone(),
                        suspend: waker.runtime.suspend.clone(),
                        meta: waker.runtime.local_meta.clone(),
                        tags: JobsTags::default(),
                        #[cfg(debug_assertions)]
                        creation_backtrace: creation_backtrace.clone(),
                        #[cfg(feature = "tracing")]
                        tracing_span: None,
                    }),
                    queue: waker.runtime.queue.clone(),
                    closure: None,
                }
            } else {
                Default::default()
            }
        } else {
            Default::default()
        };
        waker.wake_by_ref();
        Poll::Ready(result)
    })
    .await
}

/// IMPORTANT: You must assign the result of this function to a named variable,
/// otherwise the future will be executed immediately!
#[must_use]
pub async fn on_exit_closure(f: impl FnOnce() + Send + Sync + 'static) -> OnExit {
    let mut f = Some(f);
    poll_fn(move |cx| {
        let waker = cx.waker();
        let result = if let Some(waker) = JobsWaker::try_cast(waker) {
            if let Some(closure) = f.take() {
                OnExit {
                    job: None,
                    queue: waker.runtime.queue.clone(),
                    closure: Some(Box::new(closure)),
                }
            } else {
                Default::default()
            }
        } else {
            Default::default()
        };
        waker.wake_by_ref();
        Poll::Ready(result)
    })
    .await
}

pub async fn yield_now() {
    wait_polls(1).await
}

pub async fn with_all<T>(
    mut futures: Vec<Pin<Box<dyn Future<Output = T> + Send + Sync>>>,
) -> Vec<T> {
    let mut results = Vec::with_capacity(futures.len());
    let count = futures.len();
    poll_fn(move |cx| {
        futures.retain_mut(|future| match future.as_mut().poll(cx) {
            Poll::Ready(output) => {
                results.push(output);
                false
            }
            Poll::Pending => true,
        });
        if results.len() == count {
            cx.waker().wake_by_ref();
            Poll::Ready(std::mem::take(&mut results))
        } else {
            cx.waker().wake_by_ref();
            Poll::Pending
        }
    })
    .await
}

pub async fn with_any<T>(
    mut futures: Vec<Pin<Box<dyn Future<Output = T> + Send + Sync>>>,
) -> Option<T> {
    poll_fn(move |cx| {
        for future in &mut futures {
            if let Poll::Ready(output) = future.as_mut().poll(cx) {
                cx.waker().wake_by_ref();
                return Poll::Ready(Some(output));
            }
        }
        cx.waker().wake_by_ref();
        Poll::Pending
    })
    .await
}

pub enum CompletionImportance<T> {
    Required(Pin<Box<dyn Future<Output = T> + Send + Sync>>),
    Ignored(Pin<Box<dyn Future<Output = T> + Send + Sync>>),
}

impl<T> CompletionImportance<T> {
    pub fn required(future: impl Future<Output = T> + Send + Sync + 'static) -> Self {
        CompletionImportance::Required(Box::pin(future))
    }

    pub fn ignored(future: impl Future<Output = T> + Send + Sync + 'static) -> Self {
        CompletionImportance::Ignored(Box::pin(future))
    }
}

#[allow(clippy::type_complexity)]
pub async fn with_importance<T>(mut futures: Vec<CompletionImportance<T>>) -> Vec<T> {
    let mut results = Vec::with_capacity(futures.len());
    let count = futures
        .iter()
        .filter(|f| matches!(f, CompletionImportance::Required(_)))
        .count();
    poll_fn(move |cx| {
        futures.retain_mut(|future| match future {
            CompletionImportance::Required(future) => match future.as_mut().poll(cx) {
                Poll::Ready(output) => {
                    results.push(output);
                    false
                }
                Poll::Pending => true,
            },
            CompletionImportance::Ignored(future) => future.as_mut().poll(cx).is_pending(),
        });
        if results.len() == count {
            cx.waker().wake_by_ref();
            Poll::Ready(std::mem::take(&mut results))
        } else {
            cx.waker().wake_by_ref();
            Poll::Pending
        }
    })
    .await
}

pub async fn location() -> JobLocation {
    poll_fn(move |cx| {
        let waker = cx.waker();
        let result = if let Some(waker) = JobsWaker::try_cast(waker) {
            waker.runtime.location.clone()
        } else {
            JobLocation::Unknown
        };
        waker.wake_by_ref();
        Poll::Ready(result)
    })
    .await
}

pub async fn context() -> JobContext {
    poll_fn(move |cx| {
        let waker = cx.waker();
        let result = if let Some(waker) = JobsWaker::try_cast(waker) {
            waker.runtime.context
        } else {
            Default::default()
        };
        waker.wake_by_ref();
        Poll::Ready(result)
    })
    .await
}

pub async fn runtime() -> JobsRuntime {
    poll_fn(move |cx| {
        let waker = cx.waker();
        let result = if let Some(waker) = JobsWaker::try_cast(waker) {
            waker.runtime.clone()
        } else {
            Default::default()
        };
        waker.wake_by_ref();
        Poll::Ready(result)
    })
    .await
}

pub async fn priority() -> JobPriority {
    poll_fn(move |cx| {
        let waker = cx.waker();
        let result = if let Some(waker) = JobsWaker::try_cast(waker) {
            waker.runtime.priority
        } else {
            Default::default()
        };
        waker.wake_by_ref();
        Poll::Ready(result)
    })
    .await
}

pub async fn suspend() {
    let mut executed = false;
    poll_fn(move |cx| {
        let waker = cx.waker();
        if executed {
            waker.wake_by_ref();
            Poll::Ready(())
        } else {
            if let Some(waker) = JobsWaker::try_cast(waker) {
                waker.runtime.suspend.store(true, Ordering::Relaxed);
            }
            executed = true;
            waker.wake_by_ref();
            Poll::Pending
        }
    })
    .await
}

pub async fn acquire_token<T: Hash>(subject: &T) -> JobToken {
    poll_fn(move |cx| {
        let waker = cx.waker();
        let result = if let Some(waker) = JobsWaker::try_cast(waker) {
            waker.runtime.hash_tokens.acquire_token(subject)
        } else {
            Some(JobToken::default())
        };
        waker.wake_by_ref();
        match result {
            Some(token) => Poll::Ready(token),
            None => Poll::Pending,
        }
    })
    .await
}

pub async fn acquire_token_timeout<T: Hash>(subject: &T, timeout: Duration) -> JobToken {
    poll_fn(move |cx| {
        let waker = cx.waker();
        let result = if let Some(waker) = JobsWaker::try_cast(waker) {
            waker
                .runtime
                .hash_tokens
                .acquire_token_timeout(subject, timeout)
        } else {
            Some(JobToken::default())
        };
        waker.wake_by_ref();
        match result {
            Some(token) => Poll::Ready(token),
            None => Poll::Pending,
        }
    })
    .await
}

pub async fn meta_store_local<T>(name: impl ToString, lazy: ManagedLazy<T>) {
    let mut name = Some(name.to_string());
    let mut lazy = Some(lazy.into_dynamic());
    poll_fn(move |cx| {
        let waker = cx.waker();
        if let Some(waker) = JobsWaker::try_cast(waker) {
            waker
                .runtime
                .local_meta
                .set(name.take().unwrap(), lazy.take().unwrap());
        }
        waker.wake_by_ref();
        Poll::Ready(())
    })
    .await
}

pub async fn meta<T>(name: &str) -> Option<ManagedLazy<T>> {
    poll_fn(move |cx| {
        let waker = cx.waker();
        let result = if let Some(waker) = JobsWaker::try_cast(waker) {
            waker
                .runtime
                .get_meta(name)
                .and_then(|lazy| lazy.into_typed::<T>().ok())
        } else {
            None
        };
        waker.wake_by_ref();
        Poll::Ready(result)
    })
    .await
}

pub async fn meta_dynamic(name: &str) -> Option<DynamicManagedLazy> {
    poll_fn(move |cx| {
        let waker = cx.waker();
        let result = if let Some(waker) = JobsWaker::try_cast(waker) {
            waker.runtime.get_meta(name)
        } else {
            None
        };
        waker.wake_by_ref();
        Poll::Ready(result)
    })
    .await
}

pub async fn tags() -> JobsTags {
    poll_fn(move |cx| {
        let waker = cx.waker();
        let result = if let Some(waker) = JobsWaker::try_cast(waker) {
            waker.runtime.tags.clone()
        } else {
            Default::default()
        };
        waker.wake_by_ref();
        Poll::Ready(result)
    })
    .await
}

pub async fn move_to(location: JobLocation) {
    let mut executed = false;
    poll_fn(move |cx| {
        let waker = cx.waker();
        if executed {
            waker.wake_by_ref();
            Poll::Ready(())
        } else {
            if let Some(waker) = JobsWaker::try_cast(waker) {
                waker.command(JobsWakerCommand::MoveTo(location.clone()));
            }
            executed = true;
            waker.wake_by_ref();
            Poll::Pending
        }
    })
    .await
}

pub async fn change_priority(priority: JobPriority) {
    let mut executed = false;
    poll_fn(move |cx| {
        let waker = cx.waker();
        if executed {
            waker.wake_by_ref();
            Poll::Ready(())
        } else {
            if let Some(waker) = JobsWaker::try_cast(waker) {
                waker.command(JobsWakerCommand::ChangePriority(priority));
            }
            executed = true;
            waker.wake_by_ref();
            Poll::Pending
        }
    })
    .await
}

pub async fn spawn<T: Send + 'static>(
    options: impl Into<JobOptions>,
    job: impl Future<Output = T> + Send + Sync + 'static,
) -> JobHandle<T> {
    let options = options.into();
    let handle = JobHandle::default().with_meta(options.meta);
    let handle2 = handle.clone();
    let result = handle.clone();
    let mut job = Some(Job(Box::pin(async move {
        handle.put(job.await);
    })));
    #[cfg(debug_assertions)]
    let creation_backtrace = std::backtrace::Backtrace::capture().to_string();
    poll_fn(move |cx| {
        let waker = cx.waker();
        if let Some(job) = job.take() {
            if let Some(waker) = JobsWaker::try_cast(waker) {
                waker.runtime.queue.enqueue(JobObject {
                    id: ID::new(),
                    job,
                    context: Default::default(),
                    location: options.location.clone(),
                    priority: options.priority,
                    cancel: handle2.cancel.clone(),
                    suspend: handle2.suspend.clone(),
                    meta: waker.runtime.local_meta.clone(),
                    tags: options.tags.clone(),
                    #[cfg(debug_assertions)]
                    creation_backtrace: creation_backtrace.clone(),
                    #[cfg(feature = "tracing")]
                    tracing_span: None,
                });
            }
            waker.wake_by_ref();
            Poll::Pending
        } else {
            waker.wake_by_ref();
            Poll::Ready(())
        }
    })
    .await;
    result
}

pub async fn spawn_closure<T: Send + 'static>(
    options: impl Into<JobOptions>,
    job: impl FnOnce(JobContext) -> T + Send + Sync + 'static,
) -> JobHandle<T> {
    let options = options.into();
    let handle = JobHandle::default().with_meta(options.meta);
    let handle2 = handle.clone();
    let result = handle.clone();
    let mut job = Some(Job(Box::pin(async move {
        handle.put(job(context().await));
    })));
    #[cfg(debug_assertions)]
    let creation_backtrace = std::backtrace::Backtrace::capture().to_string();
    poll_fn(move |cx| {
        let waker = cx.waker();
        if let Some(job) = job.take() {
            if let Some(waker) = JobsWaker::try_cast(waker) {
                waker.runtime.queue.enqueue(JobObject {
                    id: ID::new(),
                    job,
                    context: Default::default(),
                    location: options.location.clone(),
                    priority: options.priority,
                    cancel: handle2.cancel.clone(),
                    suspend: handle2.suspend.clone(),
                    meta: waker.runtime.local_meta.clone(),
                    tags: options.tags.clone(),
                    #[cfg(debug_assertions)]
                    creation_backtrace: creation_backtrace.clone(),
                    #[cfg(feature = "tracing")]
                    tracing_span: None,
                });
            }
            waker.wake_by_ref();
            Poll::Pending
        } else {
            waker.wake_by_ref();
            Poll::Ready(())
        }
    })
    .await;
    result
}

pub async fn queue() -> JobQueue {
    poll_fn(move |cx| {
        let waker = cx.waker();
        let result = if let Some(waker) = JobsWaker::try_cast(waker) {
            waker.runtime.queue.clone()
        } else {
            JobQueue::default()
        };
        waker.wake_by_ref();
        Poll::Ready(result)
    })
    .await
}

pub async fn run_queue(queue: &JobQueue) {
    poll_fn(|cx| {
        let waker = cx.waker();
        if let Some(waker) = JobsWaker::try_cast(waker) {
            waker.runtime.run_queue(queue);
        }
        waker.wake_by_ref();
        Poll::Ready(())
    })
    .await
}

pub async fn run_queue_with_meta(queue: &JobQueue, worker_meta: JobsMeta) {
    let mut worker_meta = Some(worker_meta);
    poll_fn(move |cx| {
        let waker = cx.waker();
        if let Some(waker) = JobsWaker::try_cast(waker) {
            waker
                .runtime
                .run_queue_with_meta(queue, worker_meta.take().unwrap());
        }
        waker.wake_by_ref();
        Poll::Ready(())
    })
    .await
}

pub async fn run_queue_timeout(queue: &JobQueue, timeout: Duration) {
    poll_fn(|cx| {
        let waker = cx.waker();
        if let Some(waker) = JobsWaker::try_cast(waker) {
            waker.runtime.run_queue_timeout(queue, timeout);
        }
        waker.wake_by_ref();
        Poll::Ready(())
    })
    .await
}

pub async fn run_queue_timeout_with_meta(
    queue: &JobQueue,
    timeout: Duration,
    worker_meta: JobsMeta,
) {
    let mut worker_meta = Some(worker_meta);
    poll_fn(move |cx| {
        let waker = cx.waker();
        if let Some(waker) = JobsWaker::try_cast(waker) {
            waker
                .runtime
                .run_queue_timeout_with_meta(queue, timeout, worker_meta.take().unwrap());
        }
        waker.wake_by_ref();
        Poll::Ready(())
    })
    .await
}

pub async fn cancellable<F: Future>(
    mut condition: impl FnMut() -> bool,
    future: F,
) -> Option<F::Output> {
    let mut future = pin!(future);
    poll_fn(move |cx| {
        if condition() {
            cx.waker().wake_by_ref();
            Poll::Ready(None)
        } else {
            match future.as_mut().poll(cx) {
                Poll::Ready(output) => {
                    cx.waker().wake_by_ref();
                    Poll::Ready(Some(output))
                }
                Poll::Pending => {
                    cx.waker().wake_by_ref();
                    Poll::Pending
                }
            }
        }
    })
    .await
}

pub async fn lifetime_bound<F: Future>(
    lifetimes: impl IntoIterator<Item = LifetimeWeakState>,
    future: F,
) -> Option<F::Output> {
    let states = lifetimes.into_iter().collect::<Vec<_>>();
    cancellable(
        || states.iter().any(|state| state.upgrade().is_none()),
        future,
    )
    .await
}

pub async fn duration_bound<F: Future>(duration: Duration, future: F) -> Option<F::Output> {
    let start = Instant::now();
    cancellable(move || start.elapsed() >= duration, future).await
}

pub async fn wait_polls(mut count: usize) {
    poll_fn(move |cx| {
        if count == 0 {
            cx.waker().wake_by_ref();
            Poll::Ready(())
        } else {
            count -= 1;
            cx.waker().wake_by_ref();
            Poll::Pending
        }
    })
    .await
}

pub async fn wait_time(duration: Duration) -> Duration {
    let timer = Instant::now();
    poll_fn(move |cx| {
        let elapsed = timer.elapsed();
        if elapsed >= duration {
            cx.waker().wake_by_ref();
            Poll::Ready(elapsed.saturating_sub(duration))
        } else {
            cx.waker().wake_by_ref();
            Poll::Pending
        }
    })
    .await
}

pub async fn wait_for_mutex<T>(notify: Arc<Mutex<T>>, mut f: impl FnMut(&T) -> bool) {
    poll_fn(move |cx| {
        if let Ok(value) = notify.try_lock() {
            if f(&value) {
                cx.waker().wake_by_ref();
                Poll::Ready(())
            } else {
                cx.waker().wake_by_ref();
                Poll::Pending
            }
        } else {
            cx.waker().wake_by_ref();
            Poll::Ready(())
        }
    })
    .await
}

pub async fn wait_for_rwlock<T>(notify: Arc<RwLock<T>>, mut f: impl FnMut(&T) -> bool) {
    poll_fn(move |cx| {
        if let Ok(notify) = notify.try_read() {
            if f(&notify) {
                cx.waker().wake_by_ref();
                Poll::Ready(())
            } else {
                cx.waker().wake_by_ref();
                Poll::Pending
            }
        } else {
            cx.waker().wake_by_ref();
            Poll::Ready(())
        }
    })
    .await
}

pub async fn wait_for_receiver<T>(notify: Receiver<T>) -> T {
    poll_fn(move |cx| {
        if let Ok(value) = notify.try_recv() {
            cx.waker().wake_by_ref();
            Poll::Ready(value)
        } else {
            cx.waker().wake_by_ref();
            Poll::Pending
        }
    })
    .await
}

pub async fn wait_for_meta<T>(name: &str) -> ManagedLazy<T> {
    poll_fn(move |cx| {
        let waker = cx.waker();
        let result = JobsWaker::try_cast(waker).and_then(|waker| {
            waker
                .runtime
                .get_meta(name)
                .and_then(|lazy| lazy.into_typed::<T>().ok())
        });
        if let Some(result) = result {
            cx.waker().wake_by_ref();
            Poll::Ready(result)
        } else {
            cx.waker().wake_by_ref();
            Poll::Pending
        }
    })
    .await
}

pub async fn wait_for_meta_dynamic(name: &str) -> DynamicManagedLazy {
    poll_fn(move |cx| {
        let waker = cx.waker();
        let result = JobsWaker::try_cast(waker).and_then(|waker| waker.runtime.get_meta(name));
        if let Some(result) = result {
            cx.waker().wake_by_ref();
            Poll::Ready(result)
        } else {
            cx.waker().wake_by_ref();
            Poll::Pending
        }
    })
    .await
}

pub async fn wait_for(condition: impl Fn() -> bool) {
    poll_fn(move |cx| {
        if condition() {
            cx.waker().wake_by_ref();
            Poll::Ready(())
        } else {
            cx.waker().wake_by_ref();
            Poll::Pending
        }
    })
    .await
}

#[derive(Debug, Default, Clone)]
pub struct StrategyDecision {
    pub change_location: Option<JobLocation>,
    pub change_priority: Option<JobPriority>,
    pub cancel: bool,
}

impl StrategyDecision {
    pub fn location(mut self, location: JobLocation) -> Self {
        self.change_location = Some(location);
        self
    }

    pub fn priority(mut self, priority: JobPriority) -> Self {
        self.change_priority = Some(priority);
        self
    }

    pub fn cancel(mut self) -> Self {
        self.cancel = true;
        self
    }
}

pub async fn strategy<F: Future>(
    mut strategy: impl FnMut() -> StrategyDecision,
    future: F,
) -> Option<F::Output> {
    let mut future = pin!(future);
    poll_fn(move |cx| match future.as_mut().poll(cx) {
        Poll::Ready(output) => {
            cx.waker().wake_by_ref();
            Poll::Ready(Some(output))
        }
        Poll::Pending => {
            let waker = cx.waker();
            let StrategyDecision {
                change_location,
                change_priority,
                cancel,
            } = strategy();
            if cancel {
                cx.waker().wake_by_ref();
                return Poll::Ready(None);
            }
            if (change_location.is_some() || change_priority.is_some())
                && let Some(waker) = JobsWaker::try_cast(waker)
            {
                if let Some(location) = change_location {
                    waker.command(JobsWakerCommand::MoveTo(location.clone()));
                }
                if let Some(priority) = change_priority {
                    waker.command(JobsWakerCommand::ChangePriority(priority));
                }
            }
            waker.wake_by_ref();
            Poll::Pending
        }
    })
    .await
}

pub async fn strategy_timeline<F: Future>(
    timeline: impl IntoIterator<Item = (Duration, StrategyDecision)>,
    future: F,
) -> Option<F::Output> {
    let mut timer = Instant::now();
    let mut timeline = timeline.into_iter();
    let mut next = timeline.next();
    strategy(
        move || {
            if let Some((timeout, decision)) = next.clone() {
                if timer.elapsed() >= timeout {
                    next = timeline.next();
                    timer = Instant::now();
                    decision
                } else {
                    Default::default()
                }
            } else {
                Default::default()
            }
        },
        future,
    )
    .await
}