twizzler_driver/request/
requester.rs

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
use std::{
    collections::HashMap,
    sync::{
        atomic::{AtomicU32, Ordering},
        Arc, Mutex,
    },
};

use super::{
    async_ids::AsyncIdAllocator,
    inflight::{InFlight, InFlightFuture, InFlightFutureWithResponses},
    response_info::ResponseInfo,
    submit::{SubmitError, SubmitRequest},
    summary::AnySubmitSummary,
    RequestDriver,
};

const OK: u32 = 0;
const SHUTDOWN: u32 = 1;

/// A wrapper for managing requests and responses for a given driver.
pub struct Requester<T: RequestDriver> {
    driver: T,
    inflights: Mutex<HashMap<u64, Arc<InFlight<T::Response>>>>,
    ids: AsyncIdAllocator,
    state: AtomicU32,
}

impl<T: RequestDriver> Requester<T> {
    /// Get a reference to the driver.
    pub fn driver(&self) -> &T {
        &self.driver
    }

    /// Check if the requester is shutdown.
    pub fn is_shutdown(&self) -> bool {
        self.state.load(Ordering::SeqCst) == SHUTDOWN
    }

    /// Construct a new request manager for a given driver.
    pub fn new(driver: T) -> Self {
        Self {
            ids: AsyncIdAllocator::new(T::NUM_IDS),
            driver,
            inflights: Mutex::new(HashMap::new()),
            state: AtomicU32::new(OK),
        }
    }

    async fn allocate_ids(&self, reqs: &mut [SubmitRequest<T::Request>]) -> usize {
        for (num, req) in reqs.iter_mut().enumerate() {
            if num == 0 {
                req.set_id(self.ids.next().await);
            } else {
                if let Some(id) = self.ids.try_next() {
                    req.set_id(id);
                } else {
                    return num;
                }
            }
        }
        reqs.len()
    }

    fn release_id(&self, id: u64) {
        self.ids.release_id(id);
    }

    fn map_inflight(
        &self,
        inflight: Arc<InFlight<T::Response>>,
        reqs: &[SubmitRequest<T::Request>],
        idx_off: usize,
    ) {
        {
            let mut map = self.inflights.lock().unwrap();
            for req in reqs {
                if map.insert(req.id(), inflight.clone()).is_some() {
                    panic!("tried to map existing in-flight request");
                }
            }
        }
        inflight.insert_to_map(reqs, idx_off);
    }

    async fn do_submit(
        &self,
        inflight: Arc<InFlight<T::Response>>,
        reqs: &mut [SubmitRequest<T::Request>],
    ) -> Result<(), SubmitError<T::SubmitError>> {
        let mut idx = 0;
        while idx < reqs.len() {
            let count = self.allocate_ids(&mut reqs[idx..]).await;
            self.map_inflight(inflight.clone(), &reqs[idx..(idx + count)], idx);
            self.driver
                .submit(&mut reqs[idx..(idx + count)])
                .await
                .map_err(|e| SubmitError::DriverError(e))?;
            idx += count;
        }
        Ok(())
    }

    /// Submit a set of requests, for which we are **not** interested in the specific responses from
    /// the device. Returns a future that awaits on an [InFlightFuture], so awaiting on this
    /// function ensures that all requests are submitted, not necessarily handled.
    pub async fn submit(
        &self,
        reqs: &mut [SubmitRequest<T::Request>],
    ) -> Result<InFlightFuture<T::Response>, SubmitError<T::SubmitError>> {
        if self.is_shutdown() {
            return Err(SubmitError::IsShutdown);
        }
        let inflight = Arc::new(InFlight::new(reqs.len(), false));

        self.do_submit(inflight.clone(), reqs).await?;
        Ok(InFlightFuture::new(inflight))
    }

    /// Submit a set of requests, for which we **are** interested in the specific responses from the
    /// device. Returns a future that awaits on an [InFlightFutureWithResponses], so awaiting on
    /// this function ensures that all requests are submitted, not necessarily handled.
    pub async fn submit_for_response(
        &self,
        reqs: &mut [SubmitRequest<T::Request>],
    ) -> Result<InFlightFutureWithResponses<T::Response>, SubmitError<T::SubmitError>> {
        if self.is_shutdown() {
            return Err(SubmitError::IsShutdown);
        }
        let inflight = Arc::new(InFlight::new(reqs.len(), true));
        self.do_submit(inflight.clone(), reqs).await?;
        Ok(InFlightFutureWithResponses::new(inflight))
    }

    /// Shutdown the request manager.
    pub fn shutdown(&self) {
        self.state.store(SHUTDOWN, Ordering::SeqCst);
        let mut inflights = self.inflights.lock().unwrap();
        for (_, inflight) in inflights.drain() {
            inflight.finish(AnySubmitSummary::Shutdown);
        }
    }

    fn take_inflight(&self, id: u64) -> Option<Arc<InFlight<T::Response>>> {
        self.inflights.lock().unwrap().remove(&id)
    }

    /// Send back, from the driver, to the request manager, a set of responses to a previously
    /// submitted set of requests. The responses need not be contiguous in ID, nor do they need all
    /// be from the same set of requests.
    pub fn finish(&self, resps: &[ResponseInfo<T::Response>]) {
        if self.is_shutdown() {
            return;
        }
        for resp in resps {
            let inflight = self.take_inflight(resp.id());
            if let Some(inflight) = inflight {
                inflight.handle_resp(resp);
            }

            self.release_id(resp.id());
        }
    }
}