useceleris-client 1.0.2

Client SDK for Celeris realtime channels.
Documentation
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
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
//! Publishes that wait in the command queue across a rate-limit pause or a
//! reconnect, and publishes taken back by dropping their future (catalogue
//! section 10, QUEUE-01).

use std::time::Duration;

use tokio::time::{Instant, sleep};

use crate::channel::Channel;
use crate::client::ClientOptions;
use crate::errors::CelerisError;
use crate::tests::support::{
    DialBehaviour, FakeServer, Peer, PendingPublish, client_with_server, connect,
    connected_channel, poll_once, publish_command, publish_now, receive_rate_limit, record_errors,
    segment_command, start_publish, test_options, wait_until, yield_until,
};
use crate::values::ChannelState;

const HANDSHAKE_FAILED: &str = "WebSocket handshake failed: the server refused the connection or could not be reached. Check the base URL, the credentials and the channel reference.";

/// Drops the connection while every dial hangs until its deadline, which
/// leaves the channel reconnecting.
async fn drop_unreachable(channel: &Channel, server: &FakeServer, peer: Peer) {
    server.set_behaviour(DialBehaviour::Hang);
    drop(peer);
    yield_until("the reconnecting state", || {
        channel.state() == ChannelState::Reconnecting
    })
    .await;
} // end fn drop_unreachable

/// Lets dials through: the hanging attempt times out after 15 s, and the next
/// one, with zero jitter, connects at once.
async fn reconnect_now(channel: &Channel, server: &FakeServer) -> Peer {
    server.set_behaviour(DialBehaviour::Accept);
    let peer = server.accept().await;
    yield_until("the connected state", || {
        channel.state() == ChannelState::Connected
    })
    .await;

    peer
} // end fn reconnect_now

async fn assert_pending(publish: &mut PendingPublish<'_>) {
    let outcome = poll_once(publish).await;
    assert!(outcome.is_none(), "the publish ended early: {outcome:?}");
} // end fn assert_pending

#[tokio::test(start_paused = true)]
async fn cancelling_a_queued_publish_withdraws_it() {
    let (channel, mut peer, _server, _log) = connected_channel().await;
    let chat = channel.segment("chat").unwrap();
    let limited_at = receive_rate_limit(&channel, &mut peer).await;

    drop(start_publish(&chat, "m-1", "x").await);
    let control = start_publish(&chat, "m-2", "y").await;

    // The dropped publish would go first.
    assert_eq!(
        peer.next_command().await,
        publish_command("chat", "m-2", "y")
    );
    assert_eq!(Instant::now() - limited_at, Duration::from_millis(1_000));
    control.await.unwrap();
} // end fn cancelling_a_queued_publish_withdraws_it

#[tokio::test(start_paused = true)]
async fn cancelling_a_publish_queued_while_reconnecting_withdraws_it() {
    let (channel, peer, server, _log) = connected_channel().await;
    let lobby = channel.default_segment();
    drop_unreachable(&channel, &server, peer).await;

    drop(start_publish(&lobby, "m-1", "x").await);
    let control = start_publish(&lobby, "m-2", "y").await;

    let mut next = reconnect_now(&channel, &server).await;
    assert_eq!(
        next.next_command().await,
        publish_command("default", "m-2", "y")
    );
    control.await.unwrap();
} // end fn cancelling_a_publish_queued_while_reconnecting_withdraws_it

#[tokio::test(start_paused = true)]
async fn publish_while_reconnecting_is_sent_after_the_reconnect() {
    let (channel, peer, server, _log) = connected_channel().await;
    let chat = channel.segment("chat").unwrap();
    drop_unreachable(&channel, &server, peer).await;

    let mut pending = start_publish(&chat, "m-1", "x").await;
    sleep(Duration::from_secs(14)).await;
    assert_pending(&mut pending).await;

    let mut next = reconnect_now(&channel, &server).await;
    assert_eq!(
        next.next_command().await,
        publish_command("chat", "m-1", "x")
    );
    pending.await.unwrap();
} // end fn publish_while_reconnecting_is_sent_after_the_reconnect

/// The publishes that the writer never started go back to the front of the
/// queue, so they and those that waited for room behind them are sent after
/// the reconnect, in call order. Only the batch being written may have been
/// sent: its publishes are DeliveryUnknown and never sent again.
#[tokio::test(start_paused = true)]
async fn unwritten_publishes_are_sent_after_the_reconnect_in_order() {
    let (channel, peer, server, _log) = connected_channel().await;
    let lobby = channel.default_segment();
    let message_ids: Vec<String> = (0..66).map(|index| format!("m-{index}")).collect();
    peer.hold_writes();

    // 64 fill the writer, and two more wait for room.
    let mut publishes = Vec::new();

    for message_id in &message_ids {
        publishes.push(start_publish(&lobby, message_id, "x").await);
    }

    yield_until("the held write", || peer.has_held_write()).await;
    drop_unreachable(&channel, &server, peer).await;

    let mut waiting: Vec<PendingPublish<'_>> = Vec::new();
    let mut written = 0;

    for mut publish in publishes {
        match poll_once(&mut publish).await {
            Some(outcome) => {
                assert!(
                    waiting.is_empty(),
                    "a settled publish follows a waiting one"
                );
                assert_eq!(
                    outcome,
                    Err(CelerisError::DeliveryUnknown(
                        "The connection dropped while the socket was writing the publish, so it may or may not have been sent."
                            .to_owned()
                    ))
                );
                written += 1;
            }
            None => waiting.push(publish),
        }
    }

    assert!(
        (1..=16).contains(&written),
        "{written} publishes were being written"
    );

    let mut next = reconnect_now(&channel, &server).await;

    for message_id in &message_ids[written..] {
        assert_eq!(
            next.next_command().await,
            publish_command("default", message_id, "x")
        );
    }

    for publish in waiting {
        publish.await.unwrap();
    }
} // end fn unwritten_publishes_are_sent_after_the_reconnect_in_order

/// Restoration goes first, even ahead of a publish to a restored segment that
/// was queued before the drop; the publishes follow in call order.
#[tokio::test(start_paused = true)]
async fn restoration_precedes_publishes_queued_across_the_reconnect() {
    let (channel, mut peer, server, _log) = connected_channel().await;
    let alpha = channel.segment("alpha").unwrap();
    let beta = channel.segment("beta").unwrap();
    let _messages = alpha.subscribe().unwrap();
    let _presence = alpha.subscribe_presence().unwrap();
    assert_eq!(peer.next_command().await, segment_command("SUB", "alpha"));
    assert_eq!(
        peer.next_command().await,
        segment_command("PRES_SUB", "alpha")
    );

    // The rate-limit pause holds the first publish in the queue.
    receive_rate_limit(&channel, &mut peer).await;
    let early = start_publish(&alpha, "q-1", "x").await;
    drop_unreachable(&channel, &server, peer).await;

    let late = start_publish(&beta, "q-2", "x").await;
    let later = start_publish(&alpha, "q-3", "x").await;

    let mut next = reconnect_now(&channel, &server).await;
    assert_eq!(next.next_command().await, segment_command("SUB", "alpha"));
    assert_eq!(
        next.next_command().await,
        segment_command("PRES_SUB", "alpha")
    );
    assert_eq!(
        next.next_command().await,
        publish_command("alpha", "q-1", "x")
    );
    assert_eq!(
        next.next_command().await,
        publish_command("beta", "q-2", "x")
    );
    assert_eq!(
        next.next_command().await,
        publish_command("alpha", "q-3", "x")
    );

    for publish in [early, late, later] {
        publish.await.unwrap();
    }
} // end fn restoration_precedes_publishes_queued_across_the_reconnect

/// A new socket holds no subscription, and a publish does not make one. Thus
/// a subscription cancelled while reconnecting needs no command on the new
/// socket, also behind a publish to its segment that was queued before it.
#[tokio::test(start_paused = true)]
async fn cancelling_while_reconnecting_sends_no_unsubscribe_on_the_new_socket() {
    let (channel, mut peer, server, _log) = connected_channel().await;
    let gamma = channel.segment("gamma").unwrap();
    let subscription = gamma.subscribe().unwrap();
    let presence = gamma.subscribe_presence().unwrap();
    assert_eq!(peer.next_command().await, segment_command("SUB", "gamma"));
    assert_eq!(
        peer.next_command().await,
        segment_command("PRES_SUB", "gamma")
    );
    drop_unreachable(&channel, &server, peer).await;

    let queued = start_publish(&gamma, "g-1", "x").await;
    subscription.cancel();
    presence.cancel();

    let mut next = reconnect_now(&channel, &server).await;
    assert_eq!(
        next.next_command().await,
        publish_command("gamma", "g-1", "x")
    );
    queued.await.unwrap();

    // An UNSUB or a PRES_UNSUB would go before this subscription.
    let _control = channel.segment("control").unwrap().subscribe().unwrap();
    assert_eq!(next.next_command().await, segment_command("SUB", "control"));
} // end fn cancelling_while_reconnecting_sends_no_unsubscribe_on_the_new_socket

#[tokio::test(start_paused = true)]
async fn publish_while_reconnecting_is_refused_when_the_queue_is_full() {
    let (options, _log) = test_options();

    let options = ClientOptions {
        publish_queue_size: Some(1),
        ..options
    };

    let (client, server) = client_with_server(options, 0.0);
    let (channel, peer) = connect(&client, &server).await;
    let lobby = channel.default_segment();
    drop_unreachable(&channel, &server, peer).await;

    let waiting = start_publish(&lobby, "m-1", "x").await;

    assert_eq!(
        lobby.publish_with_message_id("x", "m-2").await,
        Err(CelerisError::Backpressure(
            "The publish queue is full (size 1). Retry once some publishes have gone out."
                .to_owned()
        ))
    );

    let mut next = reconnect_now(&channel, &server).await;
    assert_eq!(
        next.next_command().await,
        publish_command("default", "m-1", "x")
    );
    waiting.await.unwrap();
} // end fn publish_while_reconnecting_is_refused_when_the_queue_is_full

#[tokio::test(start_paused = true)]
async fn failed_reconnect_attempt_keeps_the_queue() {
    let (options, log) = test_options();
    let (client, server) = client_with_server(options, 0.5);
    let (channel, peer) = connect(&client, &server).await;
    let lobby = channel.default_segment();

    // The attempt at 250 ms is refused; the one 500 ms later connects.
    server.refuse_dials(1);
    let dropped_at = Instant::now();
    drop(peer);
    yield_until("the reconnecting state", || {
        channel.state() == ChannelState::Reconnecting
    })
    .await;

    let mut pending = start_publish(&lobby, "m-1", "x").await;
    sleep(Duration::from_millis(300)).await;

    // The connect, then the refused attempt.
    assert_eq!(log.requests.len(), 2);
    assert_eq!(channel.state(), ChannelState::Reconnecting);
    assert_pending(&mut pending).await;

    let mut next = server.accept().await;
    assert_eq!(Instant::now() - dropped_at, Duration::from_millis(750));
    assert_eq!(
        next.next_command().await,
        publish_command("default", "m-1", "x")
    );
    pending.await.unwrap();
} // end fn failed_reconnect_attempt_keeps_the_queue

/// Recovery that stops in failed refuses each queued publish with the error
/// that on_error reports, and a later connect starts with nothing queued.
#[tokio::test(start_paused = true)]
async fn queued_publishes_fail_with_the_terminal_error() {
    let (options, _log) = test_options();

    let options = ClientOptions {
        maximum_reconnect_attempts: Some(1),
        ..options
    };

    let (client, server) = client_with_server(options, 0.5);
    let (channel, peer) = connect(&client, &server).await;
    let lobby = channel.default_segment();
    let errors = record_errors(&channel).await;
    server.set_behaviour(DialBehaviour::Refuse);
    drop(peer);
    yield_until("the reconnecting state", || {
        channel.state() == ChannelState::Reconnecting
    })
    .await;

    let first = start_publish(&lobby, "m-1", "x").await;
    let second = start_publish(&lobby, "m-2", "x").await;
    wait_until("the failed state", || {
        channel.state() == ChannelState::Failed
    })
    .await;
    wait_until("the reported error", || errors.len() == 1).await;

    let terminal = CelerisError::Transport(HANDSHAKE_FAILED.to_owned());
    assert_eq!(errors.all(), std::slice::from_ref(&terminal));
    assert_eq!(first.await, Err(terminal.clone()));
    assert_eq!(second.await, Err(terminal));

    server.set_behaviour(DialBehaviour::Accept);
    let (connected, mut next) = tokio::join!(channel.connect(), server.accept());
    connected.unwrap();

    // A publish left in the queue would go first.
    publish_now(&lobby, &mut next, "m-3", "x").await;
} // end fn queued_publishes_fail_with_the_terminal_error

#[tokio::test(start_paused = true)]
async fn close_while_reconnecting_cancels_queued_publishes() {
    let (channel, peer, server, _log) = connected_channel().await;
    let lobby = channel.default_segment();
    drop_unreachable(&channel, &server, peer).await;

    let pending = start_publish(&lobby, "m-1", "x").await;
    channel.close().await;

    assert_eq!(
        pending.await,
        Err(CelerisError::Cancelled(
            "Channel closed before the publish was sent.".to_owned()
        ))
    );
} // end fn close_while_reconnecting_cancels_queued_publishes

/// A publish that waits out a rate-limit pause was never handed to the
/// socket, so it waits across the reconnect, which ends the pause.
#[tokio::test(start_paused = true)]
async fn publish_waiting_out_a_pause_is_sent_after_the_reconnect() {
    let (channel, mut peer, server, _log) = connected_channel().await;
    let chat = channel.segment("chat").unwrap();
    receive_rate_limit(&channel, &mut peer).await;
    let pending = start_publish(&chat, "m-1", "x").await;
    drop(peer);

    let mut next = server.accept().await;
    assert_eq!(
        next.next_command().await,
        publish_command("chat", "m-1", "x")
    );
    pending.await.unwrap();
} // end fn publish_waiting_out_a_pause_is_sent_after_the_reconnect

/// A publish handed to a socket is never sent again after a reconnect, not
/// even the copy that a rate limit queued for resending.
#[tokio::test(start_paused = true)]
async fn rate_limit_resend_copy_is_not_sent_after_the_reconnect() {
    let (channel, mut peer, server, _log) = connected_channel().await;
    let chat = channel.segment("chat").unwrap();
    publish_now(&chat, &mut peer, "m-1", "x").await;
    receive_rate_limit(&channel, &mut peer).await;
    drop(peer);

    let mut next = server.accept().await;
    yield_until("the connected state", || {
        channel.state() == ChannelState::Connected
    })
    .await;

    // The copy would go first.
    publish_now(&chat, &mut next, "m-2", "y").await;
} // end fn rate_limit_resend_copy_is_not_sent_after_the_reconnect

/// A publish taken back from the writer is never resent by a later rate
/// limit.
#[tokio::test(start_paused = true)]
async fn publish_taken_back_from_the_writer_is_never_resent() {
    let (channel, mut peer, _server, _log) = connected_channel().await;
    let chat = channel.segment("chat").unwrap();
    peer.hold_writes();
    let writing = start_publish(&chat, "m-1", "x").await;
    yield_until("the held write", || peer.has_held_write()).await;

    drop(start_publish(&chat, "m-2", "y").await);
    peer.release_writes();
    assert_eq!(
        peer.next_command().await,
        publish_command("chat", "m-1", "x")
    );
    writing.await.unwrap();

    receive_rate_limit(&channel, &mut peer).await;
    assert_eq!(
        peer.next_command().await,
        publish_command("chat", "m-1", "x")
    );

    // The taken-back publish would go before this one.
    publish_now(&chat, &mut peer, "m-3", "z").await;
} // end fn publish_taken_back_from_the_writer_is_never_resent

/// A rate limit requeues a publish still waiting in the writer, so it has two
/// copies. Dropping its future takes back both: a cancelled publish never
/// goes out.
#[tokio::test(start_paused = true)]
async fn cancel_takes_back_every_copy_a_rate_limit_left() {
    let (channel, mut peer, _server, _log) = connected_channel().await;
    let chat = channel.segment("chat").unwrap();
    peer.hold_writes();
    let writing = start_publish(&chat, "m-0", "x").await;
    yield_until("the held write", || peer.has_held_write()).await;

    let waiting = start_publish(&chat, "m-1", "y").await;
    let limited_at = receive_rate_limit(&channel, &mut peer).await;
    drop(waiting);
    peer.release_writes();
    assert_eq!(
        peer.next_command().await,
        publish_command("chat", "m-0", "x")
    );
    writing.await.unwrap();

    assert_eq!(
        peer.next_command().await,
        publish_command("chat", "m-0", "x")
    );
    assert_eq!(Instant::now() - limited_at, Duration::from_millis(1_000));
    publish_now(&chat, &mut peer, "m-2", "z").await;
} // end fn cancel_takes_back_every_copy_a_rate_limit_left

/// A publish dropped while the socket writes it may or may not be sent, and
/// is never resent, even by a rate limit that follows.
#[tokio::test(start_paused = true)]
async fn delivery_unknown_publish_is_never_resent() {
    let (channel, mut peer, _server, _log) = connected_channel().await;
    let chat = channel.segment("chat").unwrap();
    peer.hold_writes();
    let writing = start_publish(&chat, "m-1", "x").await;
    yield_until("the held write", || peer.has_held_write()).await;

    drop(writing);
    peer.release_writes();
    assert_eq!(
        peer.next_command().await,
        publish_command("chat", "m-1", "x")
    );

    let limited_at = receive_rate_limit(&channel, &mut peer).await;
    let control = start_publish(&chat, "m-2", "y").await;

    // A resend would go before the control publish.
    assert_eq!(
        peer.next_command().await,
        publish_command("chat", "m-2", "y")
    );
    assert_eq!(Instant::now() - limited_at, Duration::from_millis(1_000));
    control.await.unwrap();
} // end fn delivery_unknown_publish_is_never_resent