retina_fetch/
promise.rs

1// Copyright (C) 2023 Tristan Gerritsen <tristan@thewoosh.org>
2// All Rights Reserved.
3
4use std::{
5    future::Future,
6    sync::Arc,
7    task::{Poll, Context},
8};
9
10use tokio::sync::mpsc::Receiver;
11
12use crate::{Request, FetchResponse, InternalError};
13
14/// An async-library agnostic awaitable.
15#[derive(Debug)]
16pub struct FetchPromise {
17    pub(crate) request: Arc<Request>,
18    pub(crate) receiver: Receiver<FetchResponse>,
19}
20
21impl FetchPromise {
22    /// Get the [`Request`] associated with this `fetch`.
23    pub fn request(&self) -> &Request {
24        &self.request
25    }
26}
27
28impl Future for FetchPromise {
29    type Output = FetchResponse;
30
31    fn poll(self: std::pin::Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
32        match self.get_mut().receiver.poll_recv(cx) {
33            Poll::Pending => Poll::Pending,
34            Poll::Ready(None) => Poll::Ready(InternalError::SynchronizationFault.into()),
35            Poll::Ready(Some(response)) => Poll::Ready(response),
36        }
37    }
38}