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