| 1 | use std::collections::HashMap; |
| 2 | |
| 3 | use crate::{ErrorCode, Request, RequestId, Response, ResponseError}; |
| 4 | |
| 5 | /// Manages the set of pending requests, both incoming and outgoing. |
| 6 | #[derive (Debug)] |
| 7 | pub struct ReqQueue<I, O> { |
| 8 | pub incoming: Incoming<I>, |
| 9 | pub outgoing: Outgoing<O>, |
| 10 | } |
| 11 | |
| 12 | impl<I, O> Default for ReqQueue<I, O> { |
| 13 | fn default() -> ReqQueue<I, O> { |
| 14 | ReqQueue { |
| 15 | incoming: Incoming { pending: HashMap::default() }, |
| 16 | outgoing: Outgoing { next_id: 0, pending: HashMap::default() }, |
| 17 | } |
| 18 | } |
| 19 | } |
| 20 | |
| 21 | #[derive (Debug)] |
| 22 | pub struct Incoming<I> { |
| 23 | pending: HashMap<RequestId, I>, |
| 24 | } |
| 25 | |
| 26 | #[derive (Debug)] |
| 27 | pub struct Outgoing<O> { |
| 28 | next_id: i32, |
| 29 | pending: HashMap<RequestId, O>, |
| 30 | } |
| 31 | |
| 32 | impl<I> Incoming<I> { |
| 33 | pub fn register(&mut self, id: RequestId, data: I) { |
| 34 | self.pending.insert(k:id, v:data); |
| 35 | } |
| 36 | |
| 37 | pub fn cancel(&mut self, id: RequestId) -> Option<Response> { |
| 38 | let _data: I = self.complete(&id)?; |
| 39 | let error: ResponseError = ResponseError { |
| 40 | code: ErrorCode::RequestCanceled as i32, |
| 41 | message: "canceled by client" .to_owned(), |
| 42 | data: None, |
| 43 | }; |
| 44 | Some(Response { id, result: None, error: Some(error) }) |
| 45 | } |
| 46 | |
| 47 | pub fn complete(&mut self, id: &RequestId) -> Option<I> { |
| 48 | self.pending.remove(id) |
| 49 | } |
| 50 | |
| 51 | pub fn is_completed(&self, id: &RequestId) -> bool { |
| 52 | !self.pending.contains_key(id) |
| 53 | } |
| 54 | } |
| 55 | |
| 56 | impl<O> Outgoing<O> { |
| 57 | pub fn register<P: serde::Serialize>(&mut self, method: String, params: P, data: O) -> Request { |
| 58 | let id: RequestId = RequestId::from(self.next_id); |
| 59 | self.pending.insert(k:id.clone(), v:data); |
| 60 | self.next_id += 1; |
| 61 | Request::new(id, method, params) |
| 62 | } |
| 63 | |
| 64 | pub fn complete(&mut self, id: RequestId) -> Option<O> { |
| 65 | self.pending.remove(&id) |
| 66 | } |
| 67 | } |
| 68 | |