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
// Copyright Materialize, Inc. and contributors. All rights reserved.
//
// Use of this software is governed by the Business Source License
// included in the LICENSE file.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0.

use std::pin::Pin;
use std::time::Duration;

use async_trait::async_trait;
use futures::StreamExt;
use pubnub_hyper::core::data::{channel, message::Type};
use pubnub_hyper::{Builder, DefaultRuntime, DefaultTransport, PubNub};
use timely::scheduling::SyncActivator;
use tracing::info;

use mz_expr::PartitionId;
use mz_repr::{Datum, GlobalId, Row};

use crate::source::{SourceMessage, SourceMessageType, SourceReader, SourceReaderError};
use crate::types::connections::ConnectionContext;
use crate::types::sources::{encoding::SourceDataEncoding, MzOffset, SourceConnection};

/// Information required to sync data from PubNub
pub struct PubNubSourceReader {
    channel: channel::Name,
    pubnub: PubNub,
    stream: Option<Pin<Box<pubnub_hyper::core::Subscription<DefaultRuntime>>>>,
}

#[async_trait(?Send)]
impl SourceReader for PubNubSourceReader {
    type Key = ();
    type Value = Row;
    type Diff = ();

    fn new(
        _source_name: String,
        _source_id: GlobalId,
        _worker_id: usize,
        _worker_count: usize,
        _consumer_activator: SyncActivator,
        connection: SourceConnection,
        _restored_offsets: Vec<(PartitionId, Option<MzOffset>)>,
        _encoding: SourceDataEncoding,
        _: crate::source::metrics::SourceBaseMetrics,
        _: ConnectionContext,
    ) -> Result<Self, anyhow::Error> {
        let pubnub_conn = match connection {
            SourceConnection::PubNub(pubnub_conn) => pubnub_conn,
            _ => {
                panic!("PubNub is the only legitimate SourceConnection for PubNubSourceReader")
            }
        };
        let transport = DefaultTransport::new()
            // we don't need a publish key for subscribing
            .publish_key("")
            .subscribe_key(&pubnub_conn.subscribe_key)
            .build()?;

        let pubnub = Builder::new()
            .transport(transport)
            // TODO(guswynn): figure out if this or hyper spawns tasks
            // here, and if we need to name them
            .runtime(DefaultRuntime)
            .build();

        let channel = pubnub_conn.channel;
        let channel: channel::Name = channel
            .parse()
            .or_else(|_| Err(anyhow::anyhow!("invalid pubnub channel: {}", channel)))?;

        Ok(Self {
            channel,
            pubnub,
            stream: None,
        })
    }

    async fn next(
        &mut self,
        timestamp_frequency: Duration,
    ) -> Option<Result<SourceMessageType<Self::Key, Self::Value, Self::Diff>, SourceReaderError>>
    {
        loop {
            let stream = match &mut self.stream {
                None => {
                    self.stream = Some(Box::pin(self.pubnub.subscribe(self.channel.clone()).await));
                    self.stream.as_mut().expect("we just created the stream")
                }
                Some(stream) => stream,
            };

            match stream.next().await {
                Some(msg) => {
                    if msg.message_type == Type::Publish {
                        let s = msg.json.dump();

                        let row = Row::pack_slice(&[Datum::String(&s)]);

                        return Some(Ok(SourceMessageType::Finalized(SourceMessage {
                            partition: PartitionId::None,
                            offset: MzOffset {
                                // NOTE(guswynn):
                                //
                                // We convert the u64 timetoken that should
                                // 10ns granularity to a u64. Hopefully,
                                // this doesn't overflow, but we may convert
                                // MzOffset to a u64.
                                //
                                // Also, we elect to skip the `region` part of
                                // the timetoken structure, as I can't find
                                // documentation on the pubnub website on
                                // if it is required to produce monotonic
                                // timetokens.
                                offset: msg.timetoken.t,
                            },
                            upstream_time_millis: None,
                            key: (),
                            value: row,
                            headers: None,
                            specific_diff: (),
                        })));
                    }
                }
                None => {
                    info!(
                        "pubnub channel {:?} disconnected. reconnecting",
                        self.channel.to_string()
                    );
                    self.stream.take();
                    tokio::time::sleep(timestamp_frequency).await;
                }
            }
        }
    }
}