summaryrefslogtreecommitdiffstats
path: root/src/client/receive.rs
blob: 3312b1a328941fc7b773d7318c00e9965759de43 (plain)
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
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
//
//   This Source Code Form is subject to the terms of the Mozilla Public
//   License, v. 2.0. If a copy of the MPL was not distributed with this
//   file, You can obtain one at http://mozilla.org/MPL/2.0/.
//

use std::sync::Arc;

use futures::lock::Mutex;
use futures::StreamExt;
use tokio_util::codec::FramedRead;
use tracing::Instrument;
use yoke::Yoke;

use super::InnerClient;
use crate::codecs::MqttPacketCodec;
use crate::packet_identifier::PacketIdentifier;
use crate::packets::MqttPacket;
use crate::packets::MqttWriter;
use crate::packets::StableBytes;
use crate::transport::MqttConnection;

pub(super) async fn handle_background_receiving(
    inner_clone: Arc<Mutex<InnerClient>>,
    mut conn_read: FramedRead<tokio::io::ReadHalf<MqttConnection>, MqttPacketCodec>,
    conn_read_sender: futures::channel::oneshot::Sender<
        FramedRead<tokio::io::ReadHalf<MqttConnection>, MqttPacketCodec>,
    >,
) -> Result<(), ()> {
    tracing::info!("Starting background task");
    let inner: Arc<Mutex<InnerClient>> = inner_clone;

    while let Some(next) = conn_read.next().await {
        let process_span = tracing::debug_span!(
            "Processing packet",
            packet_kind = tracing::field::Empty,
            packet_identifier = tracing::field::Empty
        );
        tracing::debug!(parent: &process_span, valid = next.is_ok(), "Received packet");
        let packet = match next {
            Ok(packet) => packet,
            Err(e) => panic!("Received err: {e}"),
        };
        process_span.record(
            "packet_kind",
            tracing::field::debug(packet.get().get_kind()),
        );

        match packet.get() {
            mqtt_format::v5::packets::MqttPacket::Auth(_) => todo!(),
            mqtt_format::v5::packets::MqttPacket::Disconnect(_) => todo!(),
            mqtt_format::v5::packets::MqttPacket::Pingreq(pingreq) => {
                handle_pingreq(pingreq).instrument(process_span).await?
            }
            mqtt_format::v5::packets::MqttPacket::Pingresp(pingresp) => {
                handle_pingresp(pingresp, &inner)
                    .instrument(process_span)
                    .await?
            }
            mqtt_format::v5::packets::MqttPacket::Puback(mpuback) => {
                handle_puback(mpuback, &inner, &packet)
                    .instrument(process_span)
                    .await?
            }
            mqtt_format::v5::packets::MqttPacket::Pubrec(pubrec) => {
                handle_pubrec(pubrec, &inner, &packet)
                    .instrument(process_span)
                    .await?
            }
            mqtt_format::v5::packets::MqttPacket::Pubcomp(pubcomp) => {
                handle_pubcomp(pubcomp, &inner, &packet)
                    .instrument(process_span)
                    .await?
            }
            mqtt_format::v5::packets::MqttPacket::Publish(_) => todo!(),
            mqtt_format::v5::packets::MqttPacket::Pubrel(_) => todo!(),
            mqtt_format::v5::packets::MqttPacket::Suback(_) => todo!(),
            mqtt_format::v5::packets::MqttPacket::Unsuback(_) => todo!(),

            mqtt_format::v5::packets::MqttPacket::Connack(_)
            | mqtt_format::v5::packets::MqttPacket::Connect(_)
            | mqtt_format::v5::packets::MqttPacket::Subscribe(_)
            | mqtt_format::v5::packets::MqttPacket::Unsubscribe(_) => {
                todo!("Handle invalid packet")
            }
        }
    }

    tracing::debug!("Finished processing, returning reader");
    if let Err(_conn_read) = conn_read_sender.send(conn_read) {
        tracing::error!("Failed to return reader");
        todo!()
    }

    Ok(())
}

async fn handle_pingresp(
    _pingresp: &mqtt_format::v5::packets::pingresp::MPingresp,
    inner: &Arc<Mutex<InnerClient>>,
) -> Result<(), ()> {
    let mut inner = inner.lock().await;
    let inner = &mut *inner;

    if let Some(cb) = inner.outstanding_callbacks.take_ping_req() {
        if cb.send(()).is_err() {
            tracing::debug!("PingReq completion handler was dropped before receiving response")
        }
    } else {
        tracing::warn!("Received an unwarranted PingResp from the server, continuing")
    }

    Ok(())
}

async fn handle_pingreq(_pingreq: &mqtt_format::v5::packets::pingreq::MPingreq) -> Result<(), ()> {
    tracing::warn!("Received an unwarranted PingReq from the server. This is unclear in the spec. Ignoring and continuing...");

    Ok(())
}

async fn handle_pubcomp(
    pubcomp: &mqtt_format::v5::packets::pubcomp::MPubcomp<'_>,
    inner: &Arc<Mutex<InnerClient>>,
    packet: &MqttPacket,
) -> Result<(), ()> {
    match pubcomp.reason {
        mqtt_format::v5::packets::pubcomp::PubcompReasonCode::Success => {
            let mut inner = inner.lock().await;
            let inner = &mut *inner;
            let Some(ref mut session_state) = inner.session_state else {
                tracing::error!("No session state found");
                todo!()
            };
            let pident = PacketIdentifier::from(pubcomp.packet_identifier);
            tracing::Span::current().record("packet_identifier", tracing::field::display(pident));

            if session_state
                .outstanding_packets
                .exists_outstanding_packet(pident)
            {
                session_state.outstanding_packets.remove_by_id(pident);
                tracing::trace!("Removed packet id from outstanding packets");

                if let Some(callback) = inner.outstanding_callbacks.take_qos2_complete(pident) {
                    if let Err(_) = callback.on_complete.send(packet.clone()) {
                        tracing::trace!("Could not send ack, receiver was dropped.")
                    }
                } else {
                    todo!("Invariant broken: Received on_complete for unknown packet")
                }
            }
        }
        _ => todo!("Handle errors"),
    }

    Ok(())
}

async fn handle_puback(
    mpuback: &mqtt_format::v5::packets::puback::MPuback<'_>,
    inner: &Arc<Mutex<InnerClient>>,
    packet: &MqttPacket,
) -> Result<(), ()> {
    match mpuback.reason {
        mqtt_format::v5::packets::puback::PubackReasonCode::Success
        | mqtt_format::v5::packets::puback::PubackReasonCode::NoMatchingSubscribers => {
            let mut inner = inner.lock().await;
            let inner = &mut *inner;
            let Some(ref mut session_state) = inner.session_state else {
                tracing::error!("No session state found");
                todo!()
            };

            let pident = PacketIdentifier::try_from(mpuback.packet_identifier)
                .expect("Zero PacketIdentifier not valid here");
            tracing::Span::current().record("packet_identifier", tracing::field::display(pident));

            if session_state
                .outstanding_packets
                .exists_outstanding_packet(pident)
            {
                session_state.outstanding_packets.remove_by_id(pident);
                tracing::trace!("Removed packet id from outstanding packets");

                if let Some(callback) = inner.outstanding_callbacks.take_qos1(pident) {
                    if let Err(_) = callback.on_acknowledge.send(packet.clone()) {
                        tracing::trace!("Could not send ack, receiver was dropped.")
                    }
                }
            } else {
                tracing::error!("Packet id does not exist in outstanding packets");
                todo!()
            }

            // TODO: Forward mpuback.properties etc to the user
        }

        _ => todo!("Handle errors"),
    }

    Ok(())
}

async fn handle_pubrec(
    pubrec: &mqtt_format::v5::packets::pubrec::MPubrec<'_>,
    inner: &Arc<Mutex<InnerClient>>,
    packet: &MqttPacket,
) -> Result<(), ()> {
    match pubrec.reason {
        mqtt_format::v5::packets::pubrec::PubrecReasonCode::Success => {
            let mut inner = inner.lock().await;
            let inner = &mut *inner;
            let Some(ref mut session_state) = inner.session_state else {
                tracing::error!("No session state found");
                todo!()
            };
            let Some(ref mut conn_state) = inner.connection_state else {
                tracing::error!("No session state found");
                todo!()
            };
            let pident = PacketIdentifier::try_from(pubrec.packet_identifier)
                .expect("zero PacketIdentifier not valid here");
            tracing::Span::current().record("packet_identifier", tracing::field::display(pident));

            if session_state
                .outstanding_packets
                .exists_outstanding_packet(pident)
            {
                let pubrel = mqtt_format::v5::packets::MqttPacket::Pubrel(
                    mqtt_format::v5::packets::pubrel::MPubrel {
                        packet_identifier: pubrec.packet_identifier,
                        reason: mqtt_format::v5::packets::pubr