summaryrefslogtreecommitdiffstats
path: root/src/client/responder.rs
blob: 87cacb8d65c7c7c4cc82ce85cccd1d930e470407 (plain) (blame)
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
use std::{collections::HashMap, sync::Arc, task::Waker};

use super::Client;
use crate::{raw_ptr::TdPtr, Handler};

use super::{JoinStreams, SafeResponse};
use crossbeam::channel::{Receiver, Sender};
use log::{error, trace, warn};
use serde_json::Value as JsonValue;

/// Oneshot means it forgets any information about particular request
/// when receives response:
/// it once stores waker of the future;
/// when response arrives, it stores response and wakes the waker once,
/// dropping waker.
#[derive(Debug)]
pub(crate) struct OneshotResponder<H: Handler> {
    api: Arc<TdPtr>,
    wakers_map: HashMap<u64, SafeResponse>,
    rx: Receiver<JoinStreams>,

    /// sequential id to be used as a unique identifier of request
    /// used to match request with response
    next_id: u64,

    updater: H,
    client: Client,
    rt: tokio::runtime::Handle,
}

#[derive(Debug)]
enum TgResponseType {
    Update,
    Error,
    Response,
}

impl TgResponseType {
    fn from_type<'a>(type_: &'a str) -> Self {
        if type_.starts_with("update") {
            Self::Update
        } else if type_ == "error" {
            Self::Error
        } else {
            Self::Response
        }
    }
}

impl<H: Handler> OneshotResponder<H> {
    pub(crate) fn new(
        rx: Receiver<JoinStreams>,
        api: Arc<TdPtr>,
        updater: H,
        tx: Sender<JoinStreams>,
        rt: tokio::runtime::Handle,
    ) -> Self {
        Self {
            api,
            wakers_map: HashMap::new(),
            rx,
            next_id: 0,
            updater,
            client: Client { sender: tx },
            rt,
        }
    }

    pub(crate) fn run(&mut self) {
        loop {
            match self.rx.recv() {
                Ok(JoinStreams::NewRequest((mut request, fut_ref))) => {
                    let id = self.next_id;
                    self.next_id += 1;
                    if !request["@extra"].is_null() {
                        warn!("overwriting @extra in request");
                    }
                    request["@extra"] = id.into();
                    self.api.send(request.to_string().as_ref()).ok();
                    self.wakers_map.insert(id, fut_ref);
                    trace!("new req:\n{:#}", request);
                }
                Ok(JoinStreams::NewResponse(resp)) => {
                    match serde_json::from_str::<JsonValue>(&resp) {
                        Ok(val) => {
                            use crate::value_ext::ValueExt;
                            let type_ = val.get_type().map(TgResponseType::from_type);
                            match type_ {
                                Ok(TgResponseType::Update) => {
                                    self.rt
                                        .spawn(self.updater.handle_json(self.client.clone(), val));
                                }
                                Ok(TgResponseType::Response) => {
                                    self.handle_response(val);
                                }
                                Ok(TgResponseType::Error) => {
                                    self.handle_error(val);
                                }
                                Err(e) => {
                                    error!("response has invalid @type: {}. Be aware, that this could lock execution flow", e);
                                }
                            }
                        }
                        Err(e) => {
                            warn!("ignoring invalid response. err: {}, resp: {}", e, resp);
                        }
                    }
                }
                Err(e) => {
                    error!("stream closed: {}", e);
                    error!("closing responder thread");
                    // this will return from function and effectively end thread
                    break;
                }
            }
        }
    }

    fn handle_error(&mut self, resp: JsonValue) {
        if let Some(id) = resp["@extra"].as_u64() {
            if let Some(fut) = self.wakers_map.remove(&id) {
                let mut fut_data = fut.lock().unwrap();
                fut_data.resp = Some(resp);
                fut_data.waker.as_ref().map(Waker::wake_by_ref);
            } else {
                warn!(
                    "response received, but request was not issued by any future: {}",
                    resp
                );
            }
        } else {
            warn!("response has invalid @extra: {}", resp);
        }
    }

    fn handle_response(&mut self, resp: JsonValue) {
        if let Some(id) = resp["@extra"].as_u64() {
            if let Some(fut) = self.wakers_map.remove(&id) {
                let mut fut_data = fut.lock().unwrap();
                fut_data.resp = Some(resp);
                fut_data.waker.as_ref().map(Waker::wake_by_ref);
            } else {
                warn!(
                    "response received, but request was not issued by any future: {}",
                    resp
                );
            }
        } else {
            warn!("response has invalid @extra: {}", resp);
        }
    }
}