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
use std::convert::TryInto;
use std::fmt::{self, Debug};

use crate::broker::{
    channel::{response_channel, ControlSender},
    model::{BrokerControl, SharedBrokerState},
    Broker, ReconnectConfig,
};
use crate::error::{Error, Result};
use crate::model::{ApiRequestId, SubNoteId};

use futures::{
    future::{BoxFuture, FutureExt, TryFutureExt},
    sink::{Sink, SinkExt},
    stream::{BoxStream, Stream, StreamExt},
};
use misskey_core::model::ApiResult;
use misskey_core::{
    streaming::{BoxStreamSink, StreamingClient},
    Client,
};
use serde_json::value;
use url::Url;

pub mod builder;
pub mod stream;

use builder::WebSocketClientBuilder;
use stream::{Broadcast, Channel, SubNote};

/// Asynchronous WebSocket-based client for Misskey.
///
/// [`WebSocketClient`] can be constructed using [`WebSocketClient::connect`] or
/// [`WebSocketClientBuilder`][`builder::WebSocketClientBuilder`].
/// The latter is more flexible and intuitive.
///
/// You do not have to wrap this in [`Arc`][`std::sync::Arc`] and [`Mutex`][`std::sync::Mutex`]
/// to share it because [`WebSocketClient`] is already [`Clone`] and every methods of [`WebSocketClient`] takes `&self`, i.e. they does not require mutability.
#[derive(Clone)]
pub struct WebSocketClient {
    broker_tx: ControlSender,
    state: SharedBrokerState,
}

impl Debug for WebSocketClient {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let mut debug = f.debug_struct("WebSocketClient");

        match self.state.try_read() {
            Some(state) => debug.field("state", &state),
            None => debug.field("state", &"exiting"),
        };

        debug.finish()
    }
}

impl WebSocketClient {
    /// Connects to Misskey using WebSocket, and returns [`WebSocketClient`].
    pub async fn connect(url: Url) -> Result<WebSocketClient> {
        WebSocketClient::connect_with_config(url, ReconnectConfig::default()).await
    }

    /// Connects to Misskey using WebSocket with a given reconnect configuration, and returns [`WebSocketClient`].
    pub async fn connect_with_config(
        url: Url,
        reconnect_config: ReconnectConfig,
    ) -> Result<WebSocketClient> {
        let (broker_tx, state) = Broker::spawn(url, reconnect_config).await?;
        Ok(WebSocketClient { broker_tx, state })
    }

    /// Creates a new builder instance with `url`.
    /// All configurations are set to default.
    ///
    /// This function is identical to [`WebSocketClientBuilder::new`].
    pub fn builder<T>(url: T) -> WebSocketClientBuilder
    where
        T: TryInto<Url>,
        T::Error: Into<Error>,
    {
        WebSocketClientBuilder::new(url)
    }

    /// Captures the note specified by `id`.
    ///
    /// The returned [`SubNote`] implements [`Stream`][stream]
    /// so that note events can be retrieved asynchronously via it.
    ///
    /// [stream]: futures::stream::Stream
    pub fn subnote<E, Id>(&self, note_id: Id) -> BoxFuture<'static, Result<SubNote<E>>>
    where
        E: misskey_core::streaming::SubNoteEvent,
        Id: Into<String>,
    {
        SubNote::subscribe(
            SubNoteId(note_id.into()),
            self.broker_tx.clone(),
            SharedBrokerState::clone(&self.state),
        )
        .boxed()
    }

    /// Connects to the channel using `request`.
    ///
    /// The returned [`Channel`] implements [`Stream`][stream] and [`Sink`][sink]
    /// so that you can exchange messages with channels on it.
    ///
    /// [stream]: futures::stream::Stream
    /// [sink]: futures::sink::Sink
    pub fn channel<R>(
        &self,
        request: R,
    ) -> BoxFuture<'static, Result<Channel<R::Incoming, R::Outgoing>>>
    where
        R: misskey_core::streaming::ConnectChannelRequest,
    {
        Channel::connect(
            request,
            self.broker_tx.clone(),
            SharedBrokerState::clone(&self.state),
        )
    }

    /// Receive messages from the broadcast stream.
    ///
    /// The returned [`Broadcast`] implements [`Stream`][stream]
    /// so that broadcast events can be retrieved asynchronously via it.
    ///
    /// [stream]: futures::stream::Stream
    pub fn broadcast<E>(&self) -> BoxFuture<'static, Result<Broadcast<E>>>
    where
        E: misskey_core::streaming::BroadcastEvent,
    {
        Broadcast::start(
            self.broker_tx.clone(),
            SharedBrokerState::clone(&self.state),
        )
        .boxed()
    }
}

impl Client for WebSocketClient {
    type Error = Error;

    fn request<R: misskey_core::Request>(
        &self,
        request: R,
    ) -> BoxFuture<Result<ApiResult<R::Response>>> {
        let id = ApiRequestId::uuid();

        // limit the use of `R` to the outside of `async`
        // in order not to require `Send` on `R`
        let serialized_request = serde_json::to_value(request);

        Box::pin(async move {
            let (tx, rx) = response_channel(SharedBrokerState::clone(&self.state));
            self.broker_tx
                .clone()
                .send(BrokerControl::Api {
                    id,
                    endpoint: R::ENDPOINT,
                    data: serialized_request?,
                    sender: tx,
                })
                .await?;

            Ok(match rx.recv().await? {
                ApiResult::Ok(x) => ApiResult::Ok(value::from_value(x)?),
                ApiResult::Err { error } => ApiResult::Err { error },
            })
        })
    }
}

fn boxed_stream_sink<'a, I, O, E, S>(s: S) -> BoxStreamSink<'a, I, O, E>
where
    S: Stream<Item = std::result::Result<I, E>> + Sink<O, Error = E> + Send + 'a,
{
    Box::pin(s)
}

impl StreamingClient for WebSocketClient {
    type Error = Error;

    fn subnote<E>(&self, note_id: String) -> BoxFuture<Result<BoxStream<Result<E>>>>
    where
        E: misskey_core::streaming::SubNoteEvent,
    {
        Box::pin(async move {
            Ok(SubNote::subscribe(
                SubNoteId(note_id),
                self.broker_tx.clone(),
                SharedBrokerState::clone(&self.state),
            )
            .await?
            .boxed())
        })
    }

    fn channel<R>(
        &self,
        request: R,
    ) -> BoxFuture<Result<misskey_core::streaming::ChannelStream<R, Error>>>
    where
        R: misskey_core::streaming::ConnectChannelRequest,
    {
        Channel::connect(
            request,
            self.broker_tx.clone(),
            SharedBrokerState::clone(&self.state),
        )
        .map_ok(boxed_stream_sink)
        .boxed()
    }

    fn broadcast<E>(&self) -> BoxFuture<Result<BoxStream<Result<E>>>>
    where
        E: misskey_core::streaming::BroadcastEvent,
    {
        Box::pin(async move {
            Ok(Broadcast::start(
                self.broker_tx.clone(),
                SharedBrokerState::clone(&self.state),
            )
            .await?
            .boxed())
        })
    }
}

#[cfg(test)]
mod tests {
    use super::{builder::WebSocketClientBuilder, WebSocketClient};

    use futures::stream::StreamExt;
    use misskey_core::Client;
    use misskey_test::{self, env};

    #[cfg(feature = "tokio02-runtime")]
    use tokio02 as tokio;

    async fn test_client() -> WebSocketClient {
        misskey_test::init_logger();

        WebSocketClientBuilder::new(env::websocket_url())
            .token(env::token())
            .connect()
            .await
            .unwrap()
    }

    #[test]
    fn test_send() {
        fn assert_send<T: Send>() {}
        assert_send::<WebSocketClient>();
    }

    #[test]
    fn test_sync() {
        fn assert_send<T: Sync>() {}
        assert_send::<WebSocketClient>();
    }

    #[cfg_attr(feature = "tokio-runtime", tokio::test)]
    #[cfg_attr(feature = "tokio02-runtime", tokio02::test)]
    #[cfg_attr(feature = "async-std-runtime", async_std::test)]
    async fn request() {
        let client = test_client().await;

        client
            .request(
                misskey_api::endpoint::notes::create::Request::builder()
                    .text("hi")
                    .build(),
            )
            .await
            .unwrap()
            .unwrap();
    }

    #[cfg_attr(feature = "tokio-runtime", tokio::test)]
    #[cfg_attr(feature = "tokio02-runtime", tokio02::test)]
    #[cfg_attr(feature = "async-std-runtime", async_std::test)]
    async fn subscribe_note() {
        let client = test_client().await;
        let note = client
            .request(
                misskey_api::endpoint::notes::create::Request::builder()
                    .text("hi")
                    .build(),
            )
            .await
            .unwrap()
            .unwrap()
            .created_note;

        let mut stream = client
            .subnote::<misskey_api::streaming::note::NoteUpdateEvent, _>(note.id.to_string())
            .await
            .unwrap();

        futures::future::join(
            async {
                client
                    .request(misskey_api::endpoint::notes::delete::Request { note_id: note.id })
                    .await
                    .unwrap()
                    .unwrap()
            },
            async { stream.next().await.unwrap().unwrap() },
        )
        .await;
    }

    // TODO: test of `Broadcast`
}