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
mod context;
mod handler;

pub use self::{
    context::Context,
    handler::{
        DefaultHandler,
        Handler,
    },
};
use crate::{
    packet::{
        Channel,
        Packet,
    },
    transport::WsTransport,
    CometError,
    CometResult,
};
use std::sync::Arc;
use tungstenite::error::Error as TError;

/// A cometd client
pub struct Client<T> {
    ctx: Context,
    transport: WsTransport,

    /// The event handler
    pub handler: Arc<T>,
}

impl Client<DefaultHandler> {
    /// Connect to the url with the default handler
    pub async fn connect(url: &str) -> CometResult<Self> {
        Self::connect_with_handler(url, DefaultHandler).await
    }
}

impl<T: Handler + 'static> Client<T> {
    /// Connect to the url with the given handler
    pub async fn connect_with_handler(url: &str, handler: T) -> CometResult<Self> {
        let (stream, _response) = tokio_tungstenite::connect_async(url).await?;
        let transport = WsTransport::new(stream);
        let client = Client {
            ctx: Context::new(transport.clone()),
            transport,

            handler: Arc::new(handler),
        };

        client.ctx.send_handshake().await?;

        Ok(client)
    }

    /// Run client
    pub async fn run(&mut self) -> CometResult<()> {
        loop {
            let next_packet = self.transport.next_packet().await;
            match next_packet {
                Ok(packets) => {
                    self.process_packets(packets).await;
                }
                Err(e) => match e {
                    CometError::ClientExited => {
                        return Ok(());
                    }
                    CometError::Ws(TError::Io(_)) => {
                        return Err(e);
                    }
                    e => {
                        self.handler.on_error(self.ctx.clone(), e).await;
                    }
                },
            }
        }
    }

    async fn process_packets(&mut self, packets: Vec<Packet>) {
        for packet in packets {
            match packet.channel {
                Channel::Handshake => {
                    if let (Some(true), Some(client_id)) = (packet.successful, packet.client_id) {
                        {
                            let mut lock = self.ctx.inner.lock().unwrap();
                            lock.client_id = Some(client_id);
                            lock.is_reconnect = true;
                        }

                        if let Err(e) = self.ctx.queue_connect() {
                            let handler = self.handler.clone();
                            let ctx = self.ctx.clone();

                            tokio::spawn(async move {
                                handler.on_error(ctx, e).await;
                            });
                        }
                    } else {
                        self.ctx.queue_handshake();
                    }
                }
                Channel::Connect => {
                    if packet.successful == Some(false) {
                        self.ctx.queue_handshake();
                    } else {
                        let is_reconnect = {
                            let mut lock = self.ctx.inner.lock().unwrap();
                            if lock.is_reconnect {
                                lock.is_reconnect = false;
                                true
                            } else {
                                false
                            }
                        };

                        if is_reconnect {
                            let handler = self.handler.clone();
                            let ctx = self.ctx.clone();

                            tokio::spawn(async move { handler.on_reconnect(ctx).await });
                        }
                    }

                    // TODO: Find out why this has to be here
                    if let Err(e) = self.ctx.queue_connect() {
                        let handler = self.handler.clone();
                        let ctx = self.ctx.clone();

                        tokio::spawn(async move { handler.on_error(ctx, e).await });
                    }
                }
                Channel::Subscribe => {
                    // TODO: Figure out how to handle failed subscriptions
                    assert_eq!(packet.successful, Some(true));
                }
                _ => {
                    let handler = self.handler.clone();
                    let ctx = self.ctx.clone();

                    tokio::spawn(async move {
                        handler.on_message(ctx, packet).await;
                    });
                }
            }
        }

        if let Err(e) = self.ctx.send_buffered_packets().await {
            let handler = self.handler.clone();
            let ctx = self.ctx.clone();

            tokio::spawn(async move { handler.on_error(ctx, e).await });
        }
    }

    pub async fn graceful_shutdown(&self) -> CometResult<()> {
        // TODO: Unsub, disconnect packet
        self.transport.graceful_shutdown().await
    }
}