aboutsummaryrefslogtreecommitdiffstats
path: root/luz/src/connection/mod.rs
blob: fda2b90c64f5f8925dcc0d3426aa353df746539c (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
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
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
// TODO: consider if this needs to be handled by a supervisor or could be handled by luz directly

use std::{
    collections::HashMap,
    ops::{Deref, DerefMut},
    sync::Arc,
    time::Duration,
};

use jabber::{connection::Tls, jabber_stream::bound_stream::BoundJabberStream};
use jid::JID;
use read::{ReadControl, ReadControlHandle};
use stanza::client::Stanza;
use tokio::{
    sync::{mpsc, oneshot, Mutex},
    task::{JoinHandle, JoinSet},
};
use write::{WriteControl, WriteControlHandle, WriteHandle, WriteMessage};

use crate::{
    db::Db,
    error::{Error, Reason},
    UpdateMessage,
};

mod read;
pub(crate) mod write;

pub struct Supervisor {
    connection_commands: mpsc::Receiver<SupervisorCommand>,
    writer_crash: oneshot::Receiver<(WriteMessage, mpsc::Receiver<WriteMessage>)>,
    reader_crash: oneshot::Receiver<(
        Db,
        mpsc::Sender<UpdateMessage>,
        tokio::task::JoinSet<()>,
        mpsc::Sender<SupervisorCommand>,
        WriteHandle,
        Arc<Mutex<HashMap<String, oneshot::Sender<Result<Stanza, Reason>>>>>,
    )>,
    sender: mpsc::Sender<UpdateMessage>,
    writer_handle: WriteControlHandle,
    reader_handle: ReadControlHandle,
    on_shutdown: oneshot::Sender<()>,
    jid: Arc<Mutex<JID>>,
    password: Arc<String>,
}

pub enum SupervisorCommand {
    Disconnect,
    // for if there was a stream error, require to reconnect
    // couldn't stream errors just cause a crash? lol
    Reconnect(State),
}

pub enum State {
    Write(mpsc::Receiver<WriteMessage>),
    Read(
        (
            Db,
            mpsc::Sender<UpdateMessage>,
            tokio::task::JoinSet<()>,
            mpsc::Sender<SupervisorCommand>,
            WriteHandle,
            Arc<Mutex<HashMap<String, oneshot::Sender<Result<Stanza, Reason>>>>>,
        ),
    ),
}

impl Supervisor {
    fn new(
        connection_commands: mpsc::Receiver<SupervisorCommand>,
        writer_crash: oneshot::Receiver<(WriteMessage, mpsc::Receiver<WriteMessage>)>,
        reader_crash: oneshot::Receiver<(
            Db,
            mpsc::Sender<UpdateMessage>,
            JoinSet<()>,
            mpsc::Sender<SupervisorCommand>,
            WriteHandle,
            Arc<Mutex<HashMap<String, oneshot::Sender<Result<Stanza, Reason>>>>>,
        )>,
        sender: mpsc::Sender<UpdateMessage>,
        writer_handle: WriteControlHandle,
        reader_handle: ReadControlHandle,
        on_shutdown: oneshot::Sender<()>,
        jid: Arc<Mutex<JID>>,
        password: Arc<String>,
    ) -> Self {
        Self {
            connection_commands,
            writer_crash,
            sender,
            writer_handle,
            reader_handle,
            reader_crash,
            on_shutdown,
            jid,
            password,
        }
    }

    async fn run(mut self) {
        loop {
            tokio::select! {
                Some(msg) = self.connection_commands.recv() => {
                    match msg {
                        SupervisorCommand::Disconnect => {
                            let _ = self.writer_handle.send(WriteControl::Disconnect).await;
                            let _ = self.reader_handle.send(ReadControl::Disconnect).await;
                            tokio::select! {
                                _ = async { tokio::join!(
                                    async { let _ = (&mut self.writer_handle.handle).await; },
                                    async { let _ = (&mut self.reader_handle.handle).await; }
                                ) } => {},
                                _ = async { tokio::time::sleep(Duration::from_secs(5)) } => {
                                    (&mut self.reader_handle.handle).abort();
                                    (&mut self.writer_handle.handle).abort();
                                }
                            }
                            break;
                        },
                        SupervisorCommand::Reconnect(state) => {
                            // TODO: please omfg
                            // send abort to read stream, as already done, consider
                            let (read_state, mut write_state);
                            match state {
                                // TODO: proper state things for read and write thread
                                State::Write(receiver) => {
                                    write_state = receiver;
                                    let (send, recv) = oneshot::channel();
                                    let _ = self.reader_handle.send(ReadControl::Abort(send)).await;
                                    if let Ok(state) = recv.await {
                                        read_state = state;
                                    } else {
                                        break
                                    }
                                },
                                State::Read(read) => {
                                    read_state = read;
                                    let (send, recv) = oneshot::channel();
                                    let _ = self.writer_handle.send(WriteControl::Abort(send)).await;
                                    // TODO: need a tokio select, in case the state arrives from somewhere else
                                    if let Ok(state) = recv.await {
                                        write_state = state;
                                    } else {
                                        break
                                    }
                                },
                            }

                            let mut jid = self.jid.lock().await;
                            let mut domain = jid.domainpart.clone();
                            let connection = jabber::connect_and_login(&mut jid, &*self.password, &mut domain).await;
                            match connection {
                                Ok(c) => {

                                    let (read, write) = c.split();
                                    let (send, recv) = oneshot::channel();
                                    self.writer_crash = recv;
                                    self.writer_handle =
                                        WriteControlHandle::reconnect(write, send, write_state);
                                    let (send, recv) = oneshot::channel();
                                    self.reader_crash = recv;
                                    let (db, update_sender, tasks, supervisor_command, write_sender, pending_iqs) = read_state;
                                    self.reader_handle = ReadControlHandle::reconnect(
                                        read,
                                        send,
                                        db,
                                        update_sender,
                                        supervisor_command,
                                        write_sender,
                                        tasks,
                                        pending_iqs,
                                    );
                                },
                                Err(e) => {
                                    // if reconnection failure, respond to all current write messages with lost connection error. the received processes should complete themselves.
                                    write_state.close();
                                    while let Some(msg) = write_state.recv().await {
                                        let _ = msg.respond_to.send(Err(Reason::LostConnection));
                                    }
                                    // TODO: is this the correct error?
                                    let _ = self.sender.send(UpdateMessage::Error(Error::LostConnection)).await;
                                    break;
                                },
                            }
                        },
                    }
                },
                Ok((write_msg, mut write_recv)) = &mut self.writer_crash => {
                    // consider awaiting/aborting the read and write threads
                    let (send, recv) = oneshot::channel();
                    let _ = self.reader_handle.send(ReadControl::Abort(send)).await;
                    let (db, update_sender, tasks, supervisor_command, write_sender, pending_iqs) = tokio::select! {
                        Ok(s) = recv => s,
                        Ok(s) = &mut self.reader_crash => s,
                        // in case, just break as irrecoverable
                        else => break,
                    };

                    let mut jid = self.jid.lock().await;
                    let mut domain = jid.domainpart.clone();
                    let connection = jabber::connect_and_login(&mut jid, &*self.password, &mut domain).await;
                    match connection {
                        Ok(c) => {
                            let (read, write) = c.split();
                            let (send, recv) = oneshot::channel();
                            self.writer_crash = recv;
                            self.writer_handle =
                                WriteControlHandle::reconnect_retry(write, send, write_msg, write_recv);
                            let (send, recv) = oneshot::channel();
                            self.reader_crash = recv;
                            self.reader_handle = ReadControlHandle::reconnect(
                                read,
                                send,
                                db,
                                update_sender,
                                supervisor_command,
                                write_sender,
                                tasks,
                                pending_iqs,
                            );
                        },
                        Err(e) => {
                            // if reconnection failure, respond to all current write messages with lost connection error. the received processes should complete themselves.
                            write_recv.close();
                            let _ = write_msg.respond_to.send(Err(Reason::LostConnection));
                            while let Some(msg) = write_recv.recv().await {
                                let _ = msg.respond_to.send(Err(Reason::LostConnection));
                            }
                            // TODO: is this the correct error to send?
                            let _ = self.sender.send(UpdateMessage::Error(Error::LostConnection)).await;
                            break;
                        },
                    }
                },
                Ok((db, update_sender, tasks, supervisor_control, write_handle, pending_iqs)) = &mut self.reader_crash => {
                    let (send, recv) = oneshot::channel();
                    let _ = self.writer_handle.send(WriteControl::Abort(send)).await;
                    let (retry_msg, mut write_receiver) = tokio::select! {
                        Ok(s) = recv => (None, s),
                        Ok(s) = &mut self.writer_crash => (Some(s.0), s.1),
                        // in case, just break as irrecoverable
                        else => break,
                    };

                    let mut jid = self.jid.lock().await;
                    let mut domain = jid.domainpart.clone();
                    let connection = jabber::connect_and_login(&mut jid, &*self.password, &mut domain).await;
                    match connection {
                        Ok(c) => {
                            let (read, write) = c.split();
                            let (send, recv) = oneshot::channel();
                            self.writer_crash = recv;
                            if let Some(msg) = retry_msg {
                                self.writer_handle =
                                    WriteControlHandle::reconnect_retry(write, send, msg, write_receiver);
                            } else {
                                self.writer_handle = WriteControlHandle::reconnect(write, send, write_receiver)
                            }
                            let (send, recv) = oneshot::channel();
                            self.reader_crash = recv;
                            self.reader_handle = ReadControlHandle::reconnect(
                                read,
                                send,
                                db,
                                update_sender,
                                supervisor_control,
                                write_handle,
                                tasks,
                                pending_iqs,
                            );
                        },
                        Err(e) => {
                            // if reconnection failure, respond to all current messages with lost connection error.
                            write_receiver.close();
                            if let Some(msg) = retry_msg {
                                msg.respond_to.send(Err(Reason::LostConnection));
                            }
                            while let Some(msg) = write_receiver.recv().await {
                                msg.respond_to.send(Err(Reason::LostConnection));
                            }
                            // TODO: is this the correct error?
                            let _ = self.sender.send(UpdateMessage::Error(Error::LostConnection)).await;
                            break;
                        },
                    }
                },
                else => break,
            }
        }
        let _ = self.on_shutdown.send(());
    }
}

pub struct SupervisorHandle {
    sender: SupervisorSender,
    handle: JoinHandle<()>,
}

impl Deref for SupervisorHandle {
    type Target = SupervisorSender;

    fn deref(&self) -> &Self::Target {
        &self.sender
    }
}

impl DerefMut for SupervisorHandle {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.sender
    }
}

#[derive(Clone)]
pub struct SupervisorSender {
    sender: mpsc::Sender<SupervisorCommand>,
}

impl Deref for SupervisorSender {
    type Target = mpsc::Sender<SupervisorCommand>;

    fn deref(&self) -> &Self::Target {
        &self.sender
    }
}

impl DerefMut for SupervisorSender {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.sender
    }
}

impl SupervisorHandle {
    pub fn new(
        streams: BoundJabberStream<Tls>,
        update_sender: mpsc::Sender<UpdateMessage>,
        db: Db,
        on_shutdown: oneshot::Sender<()>,
        jid: Arc<Mutex<JID>>,
        password: Arc<String>,
        pending_iqs: Arc<Mutex<HashMap<String, oneshot::Sender<Result<Stanza, Reason>>>>>,
    ) -> (WriteHandle, Self) {
        let (command_sender, command_receiver) = mpsc::channel(20);
        let (writer_error_sender, writer_error_receiver) = oneshot::channel();
        let (reader_crash_sender, reader_crash_receiver) = oneshot::channel();

        let (reader, writer) = streams.split();
        let (write_handle, write_control_handle) =
            WriteControlHandle::new(writer, writer_error_sender);
        let jabber_reader_control_handle = ReadControlHandle::new(
            reader,
            reader_crash_sender,
            db,
            update_sender.clone(),
            command_sender.clone(),
            write_handle.clone(),
            pending_iqs,
        );

        let actor = Supervisor::new(
            command_receiver,
            writer_error_receiver,
            reader_crash_receiver,
            update_sender,
            write_control_handle,
            jabber_reader_control_handle,
            on_shutdown,
            jid,
            password,
        );

        let handle = tokio::spawn(async move { actor.run().await });

        (
            write_handle,
            Self {
                sender: SupervisorSender {
                    sender: command_sender,
                },
                handle,
            },
        )
    }

    pub fn sender(&self) -> SupervisorSender {
        self.sender.clone()
    }
}