1 use std::collections::HashMap;
5 use crate::{ErrorCode, Request, RequestId, Response, ResponseError};
7 /// Manages the set of pending requests, both incoming and outgoing.
9 pub struct ReqQueue<I, O> {
10 pub incoming: Incoming<I>,
11 pub outgoing: Outgoing<O>,
14 impl<I, O> Default for ReqQueue<I, O> {
15 fn default() -> ReqQueue<I, O> {
17 incoming: Incoming { pending: HashMap::default() },
18 outgoing: Outgoing { next_id: 0, pending: HashMap::default() },
24 pub struct Incoming<I> {
25 pending: HashMap<RequestId, I>,
29 pub struct Outgoing<O> {
31 pending: HashMap<RequestId, O>,
35 pub fn register(&mut self, id: RequestId, data: I) {
36 self.pending.insert(id, data);
38 pub fn cancel(&mut self, id: RequestId) -> Option<Response> {
39 let _data = self.complete(id.clone())?;
40 let error = ResponseError {
41 code: ErrorCode::RequestCanceled as i32,
42 message: "canceled by client".to_string(),
45 Some(Response { id, result: None, error: Some(error) })
47 pub fn complete(&mut self, id: RequestId) -> Option<I> {
48 self.pending.remove(&id)
53 pub fn register<P: Serialize>(&mut self, method: String, params: P, data: O) -> Request {
54 let id = RequestId::from(self.next_id);
55 self.pending.insert(id.clone(), data);
57 Request::new(id, method, params)
59 pub fn complete(&mut self, id: RequestId) -> Option<O> {
60 self.pending.remove(&id)