1use std::collections::BTreeSet;
13use std::fmt;
14use std::future::{poll_fn, Future};
15use std::sync::{Arc, Mutex, PoisonError};
16use std::task::{Context, Poll, Waker};
17
18use futures_core::Stream;
19use serde::de::DeserializeOwned;
20use serde::Serialize;
21use serde_json::Value;
22use xmachines_runtime::{EventType, Machine};
23
24use crate::input::{is_event, Chunk, Control, Input, Outcome};
25use crate::journal::{ChunkEntry, HostedCheckpoint, JournalEntry, SnapshotEntry, StartEntry};
26use crate::record::{Checkpoint, Fault, FaultCode, Record};
27use crate::step::{Applied, Checkpoints, Options, Run, Stepper};
28use crate::work::{Action, Invoke, Work, WorkId};
29
30pub trait Clock {
34 fn now(&self) -> u64;
36 fn sleep_until(&self, at: u64) -> impl Future<Output = ()>;
39}
40
41pub trait Journal {
45 type Error: fmt::Display;
47 fn code(error: &Self::Error) -> FaultCode {
52 let _ = error;
53 FaultCode::WorkflowJournalFailed
54 }
55 fn keeps(&self) -> bool {
58 true
59 }
60 fn read(&mut self) -> impl Future<Output = Result<Vec<JournalEntry>, Self::Error>>;
62 fn append(&mut self, entries: &[JournalEntry]) -> impl Future<Output = Result<(), Self::Error>>;
64}
65
66#[derive(Debug, Clone, Default, PartialEq)]
70pub struct MemoryJournal {
71 pub entries: Vec<JournalEntry>,
73}
74
75impl Journal for MemoryJournal {
76 type Error = std::convert::Infallible;
77
78 fn read(&mut self) -> impl Future<Output = Result<Vec<JournalEntry>, Self::Error>> {
79 std::future::ready(Ok(self.entries.clone()))
80 }
81
82 fn append(&mut self, entries: &[JournalEntry]) -> impl Future<Output = Result<(), Self::Error>> {
83 self.entries.extend_from_slice(entries);
84 std::future::ready(Ok(()))
85 }
86}
87
88#[derive(Debug, Clone, Copy, Default)]
90pub struct NoJournal;
91
92impl Journal for NoJournal {
93 type Error = std::convert::Infallible;
94
95 fn keeps(&self) -> bool {
96 false
97 }
98
99 fn read(&mut self) -> impl Future<Output = Result<Vec<JournalEntry>, Self::Error>> {
100 std::future::ready(Ok(Vec::new()))
101 }
102
103 fn append(&mut self, _: &[JournalEntry]) -> impl Future<Output = Result<(), Self::Error>> {
104 std::future::ready(Ok(()))
105 }
106}
107
108#[derive(Debug, Clone, PartialEq, Eq)]
112pub struct HandlerContext {
113 pub id: String,
115 pub actor: String,
117 pub run: String,
119}
120
121pub trait Handlers {
125 fn invoke(&self, work: Invoke, context: HandlerContext) -> impl Future<Output = Result<Value, Value>>;
128 fn action(&self, work: Action, context: HandlerContext) -> impl Future<Output = Result<(), String>>;
133}
134
135#[derive(Debug, Clone, Copy, Default)]
137pub struct NoHandlers;
138
139impl Handlers for NoHandlers {
140 fn invoke(&self, _: Invoke, _: HandlerContext) -> impl Future<Output = Result<Value, Value>> {
141 std::future::pending()
142 }
143
144 fn action(&self, _: Action, _: HandlerContext) -> impl Future<Output = Result<(), String>> {
145 std::future::pending()
146 }
147}
148
149pub trait Sink {
151 fn record(&mut self, record: &Record);
153 fn fault(&mut self, fault: &Fault) {
156 let _ = fault;
157 }
158}
159
160impl<F: FnMut(&Record)> Sink for F {
161 fn record(&mut self, record: &Record) {
162 self(record);
163 }
164}
165
166#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
169pub enum Order {
170 #[default]
174 ApplyFirst,
175 JournalFirst,
178 JournalSync,
181}
182
183#[derive(Debug, Clone, Default)]
185pub struct HostOptions {
186 pub order: Order,
188 pub run: Option<String>,
190 pub version: Option<String>,
193 pub options: Options,
198 pub checkpoint: Option<Checkpoints>,
202 pub from: Option<HostedCheckpoint>,
208 pub breathe: Option<u64>,
211}
212
213#[derive(Debug, Clone, PartialEq)]
216pub struct Hosted {
217 pub seq: u64,
219 pub checkpoint: HostedCheckpoint,
221}
222
223const CHECKPOINT: u64 = 64;
225const BREATHE: u64 = 128;
227
228#[derive(Debug, Clone, Copy, PartialEq, Eq)]
231enum Origin {
232 User,
233 Feedback,
234}
235
236enum Settled {
238 Work { id: String, outcome: Outcome, data: Option<Value> },
239 Failed { id: String, message: String },
240}
241
242const RETRY: u64 = 100;
245const RETRY_MAX: u64 = 30_000;
247
248fn journal_failed<J: Journal>(error: &J::Error, seq: u64) -> Fault {
250 Fault::new(J::code(error), format!("The journal failed: {error}"), seq)
251}
252
253async fn settle<H: Handlers>(handlers: &H, work: Work, run: String) -> Settled {
257 match work {
258 Work::Invoke(invoke) => {
259 let id = invoke.id.clone();
260 let context = HandlerContext { id: id.clone(), actor: invoke.actor.clone(), run };
261 match handlers.invoke(invoke, context).await {
262 Ok(output) => Settled::Work { id, outcome: Outcome::Resolved, data: Some(output) },
263 Err(error) => Settled::Work { id, outcome: Outcome::Rejected, data: Some(error) },
264 }
265 }
266 Work::Action(action) => {
267 let id = action.id.clone();
268 let context = HandlerContext { id: id.clone(), actor: action.actor.clone(), run };
269 match handlers.action(action, context).await {
270 Ok(()) => Settled::Work { id, outcome: Outcome::Done, data: None },
271 Err(message) => Settled::Failed { id, message },
272 }
273 }
274 }
275}
276
277fn to_start<C, E>(run: &Run<C, E>, started: &mut BTreeSet<String>) -> (BTreeSet<String>, Vec<Work>)
280where
281 C: Serialize + DeserializeOwned + Clone + Send + Sync + 'static,
282 E: EventType + Send + Sync,
283{
284 let work = &run.last().work;
285 let waiting: BTreeSet<String> = work.iter().map(|w| w.id().to_owned()).collect();
286 started.retain(|id| waiting.contains(id));
287 let new = work.iter().cloned().map(Work::from).filter(|w| started.insert(w.id().to_owned())).collect();
288 (waiting, new)
289}
290
291fn now_or_never<F: Future>(future: F) -> Option<F::Output> {
294 let mut future = std::pin::pin!(future);
295 match future.as_mut().poll(&mut Context::from_waker(Waker::noop())) {
296 Poll::Ready(output) => Some(output),
297 Poll::Pending => None,
298 }
299}
300
301pub async fn hosted<C, E, S, K, J, H, O>(
331 machine: Arc<Machine<C, E>>,
332 options: HostOptions,
333 inputs: S,
334 clock: &K,
335 journal: &mut J,
336 handlers: &H,
337 sink: &mut O,
338) -> Result<Hosted, Fault>
339where
340 C: Serialize + DeserializeOwned + Clone + Send + Sync + 'static,
341 E: EventType + Send + Sync,
342 S: Stream<Item = Chunk<Value>>,
343 K: Clock,
344 J: Journal,
345 H: Handlers,
346 O: Sink,
347{
348 let order = options.order;
349 let run_id = options.run.clone().unwrap_or_else(|| "root".to_owned());
350 let breathe = options.breathe.unwrap_or(BREATHE).max(1);
351 let fallback = if journal.keeps() { Checkpoints::Every(CHECKPOINT) } else { Checkpoints::Never };
352 let checkpoints = options.checkpoint.unwrap_or(fallback);
353 let entries = journal.read().await.map_err(|e| journal_failed::<J>(&e, 0))?;
354 if let Some(from) = &options.from {
355 check_start(&from.start, &run_id, options.version.as_deref(), FaultCode::WorkflowInvalidSnapshot)?;
357 if options.options.input.is_some() {
358 return Err(Fault::new(
359 FaultCode::WorkflowInvalidSnapshot,
360 "A checkpoint carries the input its run started of: give from or input, not both.",
361 from.seq,
362 ));
363 }
364 if !entries.is_empty() {
365 sink.fault(&Fault::new(
366 FaultCode::WorkflowInvalidSnapshot,
367 "The journal holds the run: the checkpoint given as from is not read, and the run reopens of the journal.",
368 0,
369 ));
370 }
371 }
372 let mut last_stamp = 0u64;
373 let mut stamp = |clock: &K| {
374 last_stamp = last_stamp.max(clock.now());
375 last_stamp
376 };
377
378 let (mut run, start, opening) = if entries.is_empty() {
380 let (start, run_options) = match &options.from {
381 None => {
382 let time = stamp(clock);
383 let o = &options.options;
384 let max_timers = o.max_timers.unwrap_or(xmachines_runtime::work::DEFAULT_MAX_TIMERS as u64);
385 let start = StartEntry {
386 run: run_id.clone(),
387 actor: o.actor.clone().unwrap_or_else(|| "root".to_owned()),
388 version: options.version.clone(),
389 input: o.input.clone(),
390 time: time as i64,
391 max_timers,
392 };
393 let run_options = Options {
394 actor: Some(start.actor.clone()),
395 time: Some(time as i64),
396 input: o.input.clone(),
397 checkpoint: Some(checkpoints),
398 max_timers: Some(max_timers),
399 max_steps: o.max_steps,
400 from: None,
401 };
402 (start, run_options)
403 }
404 Some(from) => {
405 let run_options = Options {
406 actor: Some(from.start.actor.clone()),
407 checkpoint: Some(checkpoints),
408 max_timers: Some(from.start.max_timers),
409 max_steps: options.options.max_steps,
410 from: Some(Checkpoint { seq: from.seq, snapshot: from.snapshot.clone() }),
411 ..Options::default()
412 };
413 (from.start.clone(), run_options)
414 }
415 };
416 let (run, opening) = Run::open(machine, run_options)?;
417 let mut first = vec![JournalEntry::Start(start.clone())];
418 if let Some(from) = &options.from {
419 first.push(JournalEntry::Snapshot(SnapshotEntry {
420 epoch: None,
421 positions: None,
422 published: None,
423 seq: from.seq,
424 snapshot: from.snapshot.clone(),
425 }));
426 }
427 journal.append(&first).await.map_err(|e| journal_failed::<J>(&e, 0))?;
428 (run, start, opening)
429 } else {
430 let (run, start) = replay(machine, &entries, &run_id, options.version.as_deref(), checkpoints, &options)?;
431 let opening = vec![run.record()];
432 (run, start, opening)
433 };
434 for record in &opening {
435 sink.record(record);
436 }
437
438 let mut inputs = std::pin::pin!(inputs);
439 let mut started: BTreeSet<String> = BTreeSet::new();
440 let mut pending = Vec::new();
443 let mut retries = none_of(|| (String::new(), Box::pin(clock.sleep_until(0))));
445 let mut attempts: std::collections::BTreeMap<String, u32> = std::collections::BTreeMap::new();
446 let mut timer = None;
447 let mut stuck: Option<u64> = None;
449 let mut in_a_row = 0u64;
450 macro_rules! reconcile {
453 () => {{
454 let (waiting, new) = to_start(&run, &mut started);
455 pending.retain(|(id, _)| waiting.contains(id));
456 retries.retain(|(id, _)| waiting.contains(id));
457 attempts.retain(|id, _| waiting.contains(id));
458 for work in new {
459 let id = work.id().to_owned();
460 pending.push((id, Box::pin(settle(handlers, work, run_id.clone()))));
461 }
462 }};
463 }
464 reconcile!();
465
466 loop {
467 let deadline = run.last().deadline.filter(|d| Some(*d) != stuck);
469 if timer.as_ref().map(|(at, _)| *at) != deadline {
470 timer = deadline.map(|at| (at, Box::pin(clock.sleep_until(at))));
471 }
472 let next = poll_fn(|cx| {
473 for at in 0..pending.len() {
475 if let Poll::Ready(settled) = pending[at].1.as_mut().poll(cx) {
476 drop(pending.swap_remove(at));
477 return Poll::Ready(Some(Next::Settled(settled)));
478 }
479 }
480 for at in 0..retries.len() {
481 if retries[at].1.as_mut().poll(cx).is_ready() {
482 let (id, _) = retries.swap_remove(at);
483 return Poll::Ready(Some(Next::Retry(id)));
484 }
485 }
486 if let Some((_, sleep)) = timer.as_mut() {
487 if sleep.as_mut().poll(cx).is_ready() {
488 timer = None;
489 return Poll::Ready(Some(Next::Time));
490 }
491 }
492 match inputs.as_mut().poll_next(cx) {
493 Poll::Ready(Some(chunk)) => Poll::Ready(Some(Next::Chunk(chunk))),
494 Poll::Ready(None) => Poll::Ready(None),
495 Poll::Pending => Poll::Pending,
496 }
497 })
498 .await;
499 let Some(next) = next else { break };
500 let fired = matches!(next, Next::Time).then(|| run.last().deadline).flatten();
501 let (inputs_of, origin) = match next {
502 Next::Chunk(chunk) => {
503 let batch = chunk.into_batch();
504 if !batch.iter().all(is_event) {
505 sink.fault(&Fault::new(
506 FaultCode::WorkflowInvalidInput,
507 "A caller writes events alone: time and work results are the host's.",
508 0,
509 ));
510 continue;
511 }
512 (batch, Origin::User)
513 }
514 Next::Time => (Vec::new(), Origin::Feedback),
515 Next::Settled(Settled::Work { id, outcome, data }) => {
516 started.remove(&id);
517 attempts.remove(&id);
518 let control = Control::Work { id, outcome, data, extra: serde_json::Map::new() };
519 (vec![serde_json::to_value(control).unwrap_or_default()], Origin::Feedback)
520 }
521 Next::Settled(Settled::Failed { id, message }) => {
522 let attempt = attempts.entry(id.clone()).or_insert(0);
525 let wait = RETRY.saturating_mul(1 << (*attempt).min(16)).min(RETRY_MAX);
526 *attempt += 1;
527 retries.push((id.clone(), Box::pin(clock.sleep_until(clock.now().saturating_add(wait)))));
528 sink.fault(&Fault::new(
529 FaultCode::WorkflowHostActionFailed,
530 format!("The host action {id} failed, and is tried again in {wait} ms: {message}"),
531 0,
532 ));
533 continue;
534 }
535 Next::Retry(id) => {
536 started.remove(&id);
537 reconcile!();
538 continue;
539 }
540 };
541 let now = stamp(clock);
542 let mut chunk = Vec::with_capacity(inputs_of.len() + 1);
543 chunk.push(serde_json::to_value(Control::<Value>::time(now as i64)).unwrap_or_default());
544 chunk.extend(inputs_of);
545 if stale(&run, &chunk, origin) {
546 continue;
547 }
548 if chunk.iter().any(is_event) {
550 let mut caught = None;
551 while let Some(deadline) = run.last().deadline {
552 if deadline > now || caught.is_some_and(|last| deadline <= last) {
553 break;
554 }
555 caught = Some(deadline);
556 let time = vec![chunk[0].clone()];
557 apply_one(&mut run, time, order, journal, sink).await?;
558 }
559 }
560 apply_one(&mut run, chunk, order, journal, sink).await?;
561 stuck = match (fired, run.last().deadline) {
563 (Some(was), Some(is)) if was == is => Some(is),
564 _ => None,
565 };
566 reconcile!();
567 in_a_row += 1;
568 if in_a_row.is_multiple_of(breathe) {
569 yield_now().await;
570 }
571 }
572 Ok(Hosted {
573 seq: run.seq(),
574 checkpoint: HostedCheckpoint { seq: run.seq(), snapshot: run.checkpoint().snapshot, start },
575 })
576}
577
578enum Next {
580 Chunk(Chunk<Value>),
581 Time,
582 Settled(Settled),
583 Retry(String),
585}
586
587async fn write<J: Journal>(journal: &mut J, entries: &[JournalEntry], sync: bool, seq: u64) -> Result<(), Fault> {
590 if sync {
591 return match now_or_never(journal.append(entries)) {
592 Some(appended) => appended.map_err(|e| journal_failed::<J>(&e, seq)),
593 None => Err(Fault::new(
594 FaultCode::WorkflowJournalFailed,
595 "The order journal-sync takes a journal that appends at once.",
596 seq,
597 )),
598 };
599 }
600 journal.append(entries).await.map_err(|e| journal_failed::<J>(&e, seq))
601}
602
603fn none_of<T>(_make: impl FnOnce() -> T) -> Vec<T> {
606 Vec::new()
607}
608
609fn check_start(start: &StartEntry, run: &str, version: Option<&str>, code: FaultCode) -> Result<(), Fault> {
612 if start.max_timers < 1 {
613 return Err(Fault::new(code, "The start has no bound of timers.", 0));
614 }
615 if start.time < 0 {
616 return Err(Fault::new(code, format!("The start is at {}: a time is 0 or more.", start.time), 0));
617 }
618 if start.version.as_deref() != version {
619 return Err(Fault::new(
620 code,
621 format!("The run is of version {:?} of the machine, not {version:?}.", start.version),
622 0,
623 ));
624 }
625 if start.run != run {
626 return Err(Fault::new(code, format!("The run is {}, not {run}.", start.run), 0));
627 }
628 Ok(())
629}
630
631fn replay<C, E>(
635 machine: Arc<Machine<C, E>>,
636 entries: &[JournalEntry],
637 run_id: &str,
638 version: Option<&str>,
639 checkpoints: Checkpoints,
640 options: &HostOptions,
641) -> Result<(Run<C, E>, StartEntry), Fault>
642where
643 C: Serialize + DeserializeOwned + Clone + Send + Sync + 'static,
644 E: EventType + Send + Sync,
645{
646 let invalid = |message: String, seq: u64| Fault::new(FaultCode::WorkflowInvalidJournal, message, seq);
647 let Some(JournalEntry::Start(start)) = entries.first() else {
648 return Err(invalid(
649 "The journal does not start with its start: a store that drops its oldest entries is no journal.".into(),
650 0,
651 ));
652 };
653 check_start(start, run_id, version, FaultCode::WorkflowInvalidJournal)?;
654 let from = entries.iter().rev().find_map(|entry| match entry {
655 JournalEntry::Snapshot(snapshot) => Some(Checkpoint { seq: snapshot.seq, snapshot: snapshot.snapshot.clone() }),
656 _ => None,
657 });
658 let reopened = from.is_some();
659 let run_options = Options {
660 actor: Some(start.actor.clone()),
661 time: (!reopened).then_some(start.time),
662 input: if reopened { None } else { start.input.clone() },
663 checkpoint: Some(checkpoints),
664 max_timers: Some(start.max_timers),
665 max_steps: options.options.max_steps,
666 from,
667 };
668 let (mut run, _) = Run::open(machine, run_options)?;
669 let mut seen = BTreeSet::new();
670 for entry in entries {
671 let JournalEntry::Chunk(chunk) = entry else { continue };
672 if !seen.insert(chunk.seq) {
674 return Err(invalid(
675 format!("The journal holds chunk {} twice: two writers wrote the run.", chunk.seq),
676 chunk.seq,
677 ));
678 }
679 if chunk.seq <= run.seq() {
680 continue;
681 }
682 if chunk.seq != run.seq() + 1 {
683 return Err(invalid(format!("The journal skips from chunk {} to {}.", run.seq(), chunk.seq), chunk.seq));
684 }
685 let batch = chunk.chunk.iter().map(|input| serde_json::to_value(input).unwrap_or_default()).collect();
686 match run.step(&Chunk::Batch(batch)) {
687 Ok(Applied::Applied { .. } | Applied::Rejected { .. }) => {}
688 Err(fault) if fault.code.is_recoverable() => {}
689 Err(fault) => return Err(fault),
690 }
691 }
692 Ok((run, start.clone()))
693}
694
695fn stale<C, E>(run: &Run<C, E>, chunk: &[Value], origin: Origin) -> bool
700where
701 C: Serialize + DeserializeOwned + Clone + Send + Sync + 'static,
702 E: EventType + Send + Sync,
703{
704 if origin != Origin::Feedback {
705 return false;
706 }
707 let last = run.last();
708 let work: Vec<&str> = chunk.iter().filter(|i| i["kind"] == "work").filter_map(|i| i["id"].as_str()).collect();
709 if work.is_empty() {
710 let now = chunk[0]["now"].as_u64().unwrap_or_default();
711 return last.deadline.is_none_or(|deadline| deadline > now);
712 }
713 work.len() == chunk.len() - 1 && work.iter().all(|id| !last.work.iter().any(|w| w.id() == *id))
714}
715
716async fn apply_one<C, E, J: Journal, O: Sink>(
721 run: &mut Run<C, E>,
722 chunk: Vec<Value>,
723 order: Order,
724 journal: &mut J,
725 sink: &mut O,
726) -> Result<(), Fault>
727where
728 C: Serialize + DeserializeOwned + Clone + Send + Sync + 'static,
729 E: EventType + Send + Sync,
730{
731 let seq = run.seq() + 1;
732 let inputs = chunk
733 .iter()
734 .map(|input| Input::from_value(input.clone()))
735 .collect::<Result<_, _>>()
736 .map_err(|e| Fault::new(FaultCode::WorkflowInvalidInput, format!("Chunk {seq}: {e}."), seq))?;
737 let entry = JournalEntry::Chunk(ChunkEntry { seq, chunk: inputs, source: None, epoch: None });
738 if order != Order::ApplyFirst {
739 write(journal, std::slice::from_ref(&entry), order == Order::JournalSync, seq).await?;
740 }
741 let mut records = Vec::new();
742 let applied = run.apply(Chunk::Batch(chunk), &mut records);
743 if order == Order::ApplyFirst {
744 records.iter().for_each(|record| sink.record(record));
745 write(journal, std::slice::from_ref(&entry), false, seq).await?;
746 }
747 if let Some(Record::Snapshot { seq, snapshot }) = records.last() {
748 if snapshot.state.is_some() {
749 let checkpoint = JournalEntry::Snapshot(SnapshotEntry {
750 epoch: None,
751 positions: None,
752 published: None,
753 seq: *seq,
754 snapshot: (**snapshot).clone(),
755 });
756 write(journal, std::slice::from_ref(&checkpoint), order == Order::JournalSync, *seq).await?;
757 }
758 }
759 if order != Order::ApplyFirst {
760 records.iter().for_each(|record| sink.record(record));
761 }
762 match applied {
763 Ok(_) => Ok(()),
764 Err(fault) if fault.code.is_recoverable() => {
765 sink.fault(&fault);
766 Ok(())
767 }
768 Err(fault) => Err(fault),
769 }
770}
771
772async fn yield_now() {
775 let mut yielded = false;
776 poll_fn(|cx| {
777 if yielded {
778 Poll::Ready(())
779 } else {
780 yielded = true;
781 cx.waker().wake_by_ref();
782 Poll::Pending
783 }
784 })
785 .await;
786}
787
788#[derive(Debug, Clone, Default)]
792pub struct ManualClock {
793 state: Arc<Mutex<ManualState>>,
794}
795
796#[derive(Debug, Default)]
797struct ManualState {
798 now: u64,
799 next: u64,
801 waiting: std::collections::BTreeMap<u64, (u64, Waker)>,
803}
804
805impl ManualClock {
806 pub fn new(now: u64) -> Self {
808 Self { state: Arc::new(Mutex::new(ManualState { now, ..ManualState::default() })) }
809 }
810
811 pub fn set(&self, now: u64) {
814 let due: Vec<Waker> = {
815 let mut state = self.state.lock().unwrap_or_else(PoisonError::into_inner);
816 state.now = state.now.max(now);
817 let now = state.now;
818 let (due, waiting) = std::mem::take(&mut state.waiting).into_iter().partition(|(_, (at, _))| *at <= now);
819 state.waiting = waiting;
820 due.into_values().map(|(_, waker)| waker).collect()
821 };
822 due.into_iter().for_each(Waker::wake);
823 }
824
825 pub fn advance(&self, ms: u64) {
827 let now = self.now();
828 self.set(now + ms);
829 }
830
831 pub fn waiting(&self) -> usize {
834 self.state.lock().unwrap_or_else(PoisonError::into_inner).waiting.len()
835 }
836}
837
838impl Clock for ManualClock {
839 fn now(&self) -> u64 {
840 self.state.lock().unwrap_or_else(PoisonError::into_inner).now
841 }
842
843 fn sleep_until(&self, at: u64) -> impl Future<Output = ()> {
844 let id = {
845 let mut state = self.state.lock().unwrap_or_else(PoisonError::into_inner);
846 state.next += 1;
847 state.next
848 };
849 ManualSleep { state: Arc::clone(&self.state), at, id }
850 }
851}
852
853#[derive(Debug)]
857struct ManualSleep {
858 state: Arc<Mutex<ManualState>>,
859 at: u64,
860 id: u64,
861}
862
863impl Future for ManualSleep {
864 type Output = ();
865
866 fn poll(self: std::pin::Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
867 let mut state = self.state.lock().unwrap_or_else(PoisonError::into_inner);
868 if state.now >= self.at {
869 state.waiting.remove(&self.id);
870 return Poll::Ready(());
871 }
872 match state.waiting.get_mut(&self.id) {
873 Some((_, waker)) => waker.clone_from(cx.waker()),
874 None => {
875 state.waiting.insert(self.id, (self.at, cx.waker().clone()));
876 }
877 }
878 Poll::Pending
879 }
880}
881
882impl Drop for ManualSleep {
883 fn drop(&mut self) {
884 self.state.lock().unwrap_or_else(PoisonError::into_inner).waiting.remove(&self.id);
885 }
886}