Repository navigation
Expand file tree
/
Copy pathclient_connection.rs
More file actions
1586 lines (1413 loc) · 52.8 KB
/
Copy pathclient_connection.rs
File metadata and controls
1586 lines (1413 loc) · 52.8 KB
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
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use std::collections::VecDeque;
use std::future::poll_fn;
use std::ops::Deref;
use std::sync::atomic::Ordering;
use std::sync::atomic::{AtomicBool, Ordering::Relaxed};
use std::sync::Arc;
use std::task::{Context, Poll};
use std::time::{Instant, SystemTime};
use super::{message_handlers, ClientActorId, MessageHandleError, OutboundMessage};
use crate::db::relational_db::RelationalDB;
use crate::error::DBError;
use crate::host::module_host::{ClientConnectedError, ProcedureResultTarget};
use crate::host::{FunctionArgs, ModuleHost, NoSuchModule, ReducerCallError};
use crate::subscription::module_subscription_manager::BroadcastError;
use crate::worker_metrics::{
record_client_rejection, ClientDisconnectCause, ClientDisconnectRecorder, ClientRejectCause, WORKER_METRICS,
};
use bytes::Bytes;
use bytestring::ByteString;
use derive_more::From;
use futures::prelude::*;
use log::warn;
use prometheus::{Histogram, IntCounter, IntGauge};
use scopeguard::ScopeGuard;
use spacetimedb_auth::identity::{ConnectionAuthCtx, SpacetimeIdentityClaims};
use spacetimedb_client_api_messages::websocket::{common as ws_common, v1 as ws_v1, v2 as ws_v2};
use spacetimedb_durability::{DurableOffset, TxOffset};
use spacetimedb_lib::identity::{AuthCtx, RequestId};
use spacetimedb_lib::metrics::ExecutionMetrics;
use spacetimedb_lib::Identity;
use spacetimedb_metrics::utils::IntGaugeExt;
use tokio::sync::mpsc::error::{SendError, TrySendError};
use tokio::sync::{mpsc, oneshot, watch};
use tokio::task::AbortHandle;
use tracing::trace;
#[derive(PartialEq, Eq, Clone, Copy, Hash, Debug)]
pub enum Protocol {
Text,
Binary,
}
#[derive(PartialEq, Eq, Clone, Copy, Hash, Debug)]
pub enum WsVersion {
V1,
V2,
V3,
}
impl Protocol {
pub fn as_str(self) -> &'static str {
match self {
Protocol::Text => "text",
Protocol::Binary => "binary",
}
}
pub(crate) fn assert_matches_format_switch<B, J>(self, fs: &ws_v1::FormatSwitch<B, J>) {
match (self, fs) {
(Protocol::Text, ws_v1::FormatSwitch::Json(_)) | (Protocol::Binary, ws_v1::FormatSwitch::Bsatn(_)) => {}
_ => unreachable!("requested protocol does not match output format"),
}
}
}
#[derive(Clone, Copy, Debug)]
pub struct ClientConfig {
/// The client's desired protocol (format) when the host replies.
pub protocol: Protocol,
/// The websocket protocol version negotiated during the handshake.
pub version: WsVersion,
/// The client's desired (conditional) compression algorithm, if any.
pub compression: ws_common::Compression,
/// Whether the client prefers full [`TransactionUpdate`]s
/// rather than [`TransactionUpdateLight`]s on a successful update.
// TODO(centril): As more knobs are added, make this into a bitfield (when there's time).
pub tx_update_full: bool,
/// If `true`, the client requests to receive updates for transactions
/// confirmed to be durable. If `false`, updates will be delivered
/// immediately.
pub confirmed_reads: bool,
}
impl ClientConfig {
pub fn for_test() -> ClientConfig {
Self {
protocol: Protocol::Binary,
version: WsVersion::V1,
compression: <_>::default(),
tx_update_full: true,
confirmed_reads: false,
}
}
}
/// A message to be sent to the client, along with the transaction offset it
/// was computed at, if available.
///
// TODO: Consider a different name, "ClientUpdate" is used elsewhere already.
#[derive(Debug)]
struct ClientUpdate {
/// Transaction offset at which `message` was computed.
///
/// This is only `Some` if `message` is a query result.
///
/// If `Some` and [`ClientConfig::confirmed_reads`] is `true`,
/// [`ClientConnectionReceiver`] will delay delivery until the durable
/// offset of the database is equal to or greater than `tx_offset`.
pub tx_offset: Option<TxOffset>,
/// Type-erased outgoing message.
pub message: OutboundMessage,
}
/// Types with access to the [`DurableOffset`] of a database.
///
/// Provided implementors are [`watch::Receiver<ModuleHost>`] and [`RelationalDB`].
///
/// The latter is mostly useful for tests, where no managed [`ModuleHost`] is
/// available, while the former supports module hotswapping.
pub trait DurableOffsetSupply: Send {
/// Obtain the current [`DurableOffset`] handle.
///
/// Returns:
///
/// - `Err(NoSuchModule)` if the database was shut down
/// - `Ok(None)` if the database is configured without durability
/// - `Ok(Some(DurableOffset))` otherwise
///
fn durable_offset(&mut self) -> Result<Option<DurableOffset>, NoSuchModule>;
}
impl DurableOffsetSupply for watch::Receiver<ModuleHost> {
fn durable_offset(&mut self) -> Result<Option<DurableOffset>, NoSuchModule> {
let module = if self.has_changed().map_err(|_| NoSuchModule)? {
self.borrow_and_update()
} else {
self.borrow()
};
Ok(module.relational_db().durable_tx_offset())
}
}
impl DurableOffsetSupply for Arc<RelationalDB> {
fn durable_offset(&mut self) -> Result<Option<DurableOffset>, NoSuchModule> {
Ok(self.durable_tx_offset())
}
}
/// Receiving end of [`ClientConnectionSender`].
///
/// The [`ClientConnection`] actor reads messages from this channel and sends
/// them to the client over its websocket connection.
///
/// The [`ClientConnectionReceiver`] takes care of confirmed reads semantics,
/// if requested by the client.
pub struct ClientConnectionReceiver {
confirmed_reads: bool,
channel: MeteredReceiver<ClientUpdate>,
pending: Vec<ClientUpdate>,
offset_supply: Box<dyn DurableOffsetSupply>,
}
impl ClientConnectionReceiver {
pub const DEFAULT_RECV_MANY_LIMIT: usize = 4096;
fn new(
confirmed_reads: bool,
channel: MeteredReceiver<ClientUpdate>,
offset_supply: impl DurableOffsetSupply + 'static,
) -> Self {
Self {
confirmed_reads,
channel,
pending: Vec::new(),
offset_supply: Box::new(offset_supply),
}
}
#[cfg(test)]
pub(crate) async fn recv(&mut self) -> Option<OutboundMessage> {
let mut buf = Vec::with_capacity(1);
(self.recv_many(&mut buf, 1).await != 0).then(|| buf.remove(0))
}
/// Receive multiple messages from this channel.
///
/// Messages are returned immediately if:
///
/// - The [`ClientUpdate`] does not have a `tx_offset`
/// (such as for error messages).
/// - The client hasn't requested confirmed reads
/// (i.e. [`ClientConfig::confirmed_reads`] is `false`).
/// - The database is configured to not persist transactions.
///
/// Otherwise, the last `tx_offset` in the batch is compared against the module's
/// durable offset. If the durable offset is behind the `tx_offset`, the
/// method waits until it catches up before returning the message.
///
/// If the database is shut down while waiting for the durable offset,
/// 0 is returned. In this case, no more messages can ever be received
/// from the channel.
///
/// For non-zero values of `max`, this method will never return `0` unless the
/// input channel has been closed and there are no pending messages, or if the
/// database goes away. This indicates that no further values can ever be received
/// from this `Receiver`.
///
/// # Cancel safety
///
/// This method is cancel safe, as long as `self` is not dropped.
///
/// If `recv_many` is used in a [`tokio::select!`] statement, it may get
/// cancelled while waiting for the durable offset to catch up. At this
/// point, it has already received values from the underlying channel.
/// These values are stored internally, so calling `recv_many` again will
/// not lose data.
pub async fn recv_many(&mut self, buf: &mut Vec<OutboundMessage>, max: usize) -> usize {
// If there are no pending updates and the input channel has been closed,
// no more messages can be received from this receiver.
if max == 0 || (self.pending.is_empty() && self.channel.recv_many(&mut self.pending, max).await == 0) {
return 0;
}
// If we don't have to wait for txns to be made durable,
// drain the pending updates.
if !self.confirmed_reads {
return self.drain_pending(buf, max);
}
// If we do have to wait for txns to be made durable,
// but the next client update doesn't have a tx offset,
// there's no reason to wait - just send it.
if !self.pending_update_has_offset() {
return self.drain_pending(buf, 1);
}
// Otherwise, grab the next offset that we should wait for.
let (n, wait_for_offset) = self.next_confirmed_reads_batch(max);
match self.offset_supply.durable_offset() {
Ok(Some(mut durable)) => {
trace!("waiting for offset {wait_for_offset} to become durable");
if durable.wait_for(wait_for_offset).await.is_err() {
warn!("database went away while waiting for durable offset");
return 0;
}
self.drain_pending(buf, n)
}
// Database shut down or crashed.
Err(NoSuchModule) => 0,
// In-memory database.
Ok(None) => self.drain_pending(buf, max),
}
}
/// Compute the next batch of pending client updates that have a tx offset.
/// What is the size of the batch and what is the max offset?
fn next_confirmed_reads_batch(&self, max: usize) -> (usize, TxOffset) {
self.pending
.iter()
.take(max)
.map_while(|update| update.tx_offset)
.fold((0, 0), |(count, max_offset), tx_offset| {
(count + 1, max_offset.max(tx_offset))
})
}
/// Drain the pending [`ClientUpdate`]s, up to `max, into `buf`.
fn drain_pending(&mut self, buf: &mut Vec<OutboundMessage>, max: usize) -> usize {
let n = self.pending.len().min(max);
buf.reserve(n);
buf.extend(self.pending.drain(..n).map(|u| u.message));
n
}
/// Does the next pending update have a tx offset?
///
/// Assumes that [`Self::pending`] is not empty.
fn pending_update_has_offset(&self) -> bool {
self.pending.first().is_some_and(|update| update.tx_offset.is_some())
}
/// Close the receiver without dropping it.
///
/// This is used to notify the [`ClientConnectionSender`] that the receiver
/// will not consume any more messages from the channel, usually because the
/// connection has been closed or is about to be closed.
///
/// After calling this method, the sender will not be able to send more
/// messages, preventing the internal buffer from filling up.
pub fn close(&mut self) {
self.channel.close();
}
}
#[derive(Debug)]
pub struct ClientConnectionSender {
pub id: ClientActorId,
pub auth: ConnectionAuthCtx,
pub config: ClientConfig,
sendtx: mpsc::Sender<ClientUpdate>,
abort_handle: AbortHandle,
cancelled: AtomicBool,
/// Handles on Prometheus metrics related to connections to this database.
///
/// Will be `None` when constructed by [`ClientConnectionSender::dummy_with_channel`]
/// or [`ClientConnectionSender::dummy`], which are used in tests.
/// Will be `Some` whenever this `ClientConnectionSender` is wired up to an actual client connection.
metrics: Option<ClientConnectionMetrics>,
}
#[derive(Debug)]
pub struct ClientConnectionMetrics {
pub websocket_request_msg_size: Histogram,
pub websocket_requests: IntCounter,
pub outgoing_queue_disconnects: IntCounter,
pub disconnect_recorder: ClientDisconnectRecorder,
/// The `total_outgoing_queue_length` metric labeled with this database's `Identity`,
/// which we'll increment whenever sending a message.
///
/// This metric will be decremented, and cleaned up,
/// by `ws_client_actor_inner` in client-api/src/routes/subscribe.rs.
/// Care must be taken not to increment it after the client has disconnected
/// and performed its clean-up.
pub sendtx_queue_size: IntGauge,
}
impl ClientConnectionMetrics {
fn new(database_identity: Identity, protocol: Protocol) -> Self {
let message_kind = protocol.as_str();
let websocket_request_msg_size = WORKER_METRICS
.websocket_request_msg_size
.with_label_values(&database_identity, message_kind);
let websocket_requests = WORKER_METRICS
.websocket_requests
.with_label_values(&database_identity, message_kind);
let outgoing_queue_disconnects = WORKER_METRICS
.client_outgoing_queue_disconnects
.with_label_values(&database_identity);
let sendtx_queue_size = WORKER_METRICS
.total_outgoing_queue_length
.with_label_values(&database_identity);
let disconnect_recorder = ClientDisconnectRecorder::new(database_identity);
Self {
websocket_request_msg_size,
websocket_requests,
outgoing_queue_disconnects,
disconnect_recorder,
sendtx_queue_size,
}
}
}
#[derive(Debug, thiserror::Error)]
pub enum ClientSendError {
#[error("client disconnected")]
Disconnected,
#[error("client was not responding and has been disconnected")]
Cancelled,
}
impl ClientConnectionSender {
pub fn dummy_with_channel(
id: ClientActorId,
config: ClientConfig,
offset_supply: impl DurableOffsetSupply + 'static,
) -> (Self, ClientConnectionReceiver) {
let (sendtx, rx) = mpsc::channel(CLIENT_CHANNEL_CAPACITY_TEST);
// just make something up, it doesn't need to be attached to a real task
let abort_handle = match tokio::runtime::Handle::try_current() {
Ok(h) => h.spawn(async {}).abort_handle(),
Err(_) => tokio::runtime::Runtime::new().unwrap().spawn(async {}).abort_handle(),
};
let receiver = ClientConnectionReceiver::new(config.confirmed_reads, MeteredReceiver::new(rx), offset_supply);
let cancelled = AtomicBool::new(false);
let dummy_claims = SpacetimeIdentityClaims {
identity: id.identity,
subject: "".into(),
issuer: "".into(),
audience: [].into(),
iat: SystemTime::now(),
exp: None,
extra: None,
};
let sender = Self {
id,
auth: ConnectionAuthCtx::try_from(dummy_claims).expect("dummy claims should always be valid"),
config,
sendtx,
abort_handle,
cancelled,
metrics: None,
};
(sender, receiver)
}
pub fn dummy(id: ClientActorId, config: ClientConfig, offset_supply: impl DurableOffsetSupply + 'static) -> Self {
Self::dummy_with_channel(id, config, offset_supply).0
}
pub fn is_cancelled(&self) -> bool {
self.cancelled.load(Ordering::Relaxed)
}
/// Stop this connection's websocket actor.
///
/// Used when a newer connection arrives for this connection's session
/// (see [`super::ClientSessionIndex`]), and when a client exceeds its
/// outgoing queue capacity. The actor's teardown runs the module-side
/// disconnect.
pub fn kick(&self, cause: ClientDisconnectCause) {
if let Some(metrics) = &self.metrics {
metrics.disconnect_recorder.record(cause);
}
self.abort_handle.abort();
self.cancelled.store(true, Ordering::Relaxed);
}
/// Send a message to the client. For data-related messages, you should probably use
/// `BroadcastQueue::send` to ensure that the client sees data messages in a consistent order.
///
/// If `message` is the result of evaluating a query, then `tx_offset` should be
/// the TX offset of the database state against which the query was evaluated.
/// If `message` is not the result of evaluating a query (e.g. it reports an error),
/// `tx_offset` should be `None`.
/// For clients which have requested only confirmed durable reads,
/// the sender will delay sending `message` until the `tx_offset` is confirmed.
pub fn send_message(
&self,
tx_offset: Option<TxOffset>,
message: impl Into<OutboundMessage>,
) -> Result<(), ClientSendError> {
let message = message.into();
debug_assert!(
matches!(
(&self.config.version, &message),
(WsVersion::V1, OutboundMessage::V1(_)) | (WsVersion::V2 | WsVersion::V3, OutboundMessage::V2(_))
),
"attempted to send message variant that does not match client websocket version"
);
self.send(ClientUpdate { tx_offset, message })
}
fn send(&self, message: ClientUpdate) -> Result<(), ClientSendError> {
if self.cancelled.load(Relaxed) {
return Err(ClientSendError::Cancelled);
}
match self.sendtx.try_send(message) {
Err(mpsc::error::TrySendError::Full(_)) => {
// we've hit CLIENT_CHANNEL_CAPACITY messages backed up in
// the channel, so forcibly kick the client
tracing::warn!(
identity = %self.id.identity,
connection_id = %self.id.connection_id,
confirmed_reads = self.config.confirmed_reads,
"client channel capacity exceeded"
);
log::warn!(
"Client {:?} exceeded channel capacity of {}, kicking",
self.id,
self.sendtx.max_capacity(),
);
if let Some(metrics) = &self.metrics {
metrics.outgoing_queue_disconnects.inc();
}
self.kick(ClientDisconnectCause::OutgoingQueueFull);
return Err(ClientSendError::Cancelled);
}
Err(mpsc::error::TrySendError::Closed(_)) => return Err(ClientSendError::Disconnected),
Ok(()) => {
// If we successfully pushed a message into the queue, increment the queue size metric.
// Don't do this before pushing because, if the client has disconnected,
// it will already have performed its clean-up,
// and so would never perform the corresponding `dec` to this `inc`.
if let Some(metrics) = &self.metrics {
metrics.sendtx_queue_size.inc();
}
}
}
Ok(())
}
pub(crate) fn observe_websocket_request_message(&self, message: &DataMessage) {
if let Some(metrics) = &self.metrics {
metrics.websocket_request_msg_size.observe(message.len() as f64);
metrics.websocket_requests.inc();
}
}
}
#[derive(Clone)]
#[non_exhaustive]
pub struct ClientConnection {
sender: Arc<ClientConnectionSender>,
pub replica_id: u64,
module_rx: watch::Receiver<ModuleHost>,
auth: AuthCtx,
}
impl Deref for ClientConnection {
type Target = ClientConnectionSender;
fn deref(&self) -> &Self::Target {
&self.sender
}
}
#[derive(Debug, From)]
pub enum DataMessage {
Text(ByteString),
Binary(Bytes),
}
impl From<String> for DataMessage {
fn from(value: String) -> Self {
ByteString::from(value).into()
}
}
impl From<Vec<u8>> for DataMessage {
fn from(value: Vec<u8>) -> Self {
Bytes::from(value).into()
}
}
impl DataMessage {
/// Returns the number of bytes this message consists of.
pub fn len(&self) -> usize {
match self {
Self::Text(s) => s.len(),
Self::Binary(b) => b.len(),
}
}
/// Is the message empty?
#[must_use]
pub fn is_empty(&self) -> bool {
self.len() == 0
}
/// Returns a handle to the underlying allocation of the message without consuming it.
pub fn allocation(&self) -> Bytes {
match self {
DataMessage::Text(alloc) => alloc.as_bytes().clone(),
DataMessage::Binary(alloc) => alloc.clone(),
}
}
}
/// Wraps a [VecDeque] with a gauge for tracking its size.
/// We subtract its size from the gauge on drop to avoid leaking the metric.
pub struct MeteredDeque<T> {
inner: VecDeque<T>,
gauge: IntGauge,
}
impl<T> MeteredDeque<T> {
pub fn new(gauge: IntGauge) -> Self {
Self {
inner: VecDeque::new(),
gauge,
}
}
pub fn pop_front(&mut self) -> Option<T> {
self.inner.pop_front().inspect(|_| {
self.gauge.dec();
})
}
pub fn pop_back(&mut self) -> Option<T> {
self.inner.pop_back().inspect(|_| {
self.gauge.dec();
})
}
pub fn push_front(&mut self, value: T) {
self.gauge.inc();
self.inner.push_front(value);
}
pub fn push_back(&mut self, value: T) {
self.gauge.inc();
self.inner.push_back(value);
}
pub fn len(&self) -> usize {
self.inner.len()
}
pub fn is_empty(&self) -> bool {
self.inner.is_empty()
}
}
impl<T> Drop for MeteredDeque<T> {
fn drop(&mut self) {
// Record the number of elements still in the deque on drop
self.gauge.sub(self.inner.len() as _);
}
}
/// Wraps the receiving end of a channel with a gauge for tracking the size of the channel.
/// We subtract the size of the channel from the gauge on drop to avoid leaking the metric.
pub struct MeteredReceiver<T> {
inner: mpsc::Receiver<T>,
gauge: Option<IntGauge>,
}
impl<T> MeteredReceiver<T> {
pub fn new(inner: mpsc::Receiver<T>) -> Self {
Self { inner, gauge: None }
}
pub fn with_gauge(inner: mpsc::Receiver<T>, gauge: IntGauge) -> Self {
Self {
inner,
gauge: Some(gauge),
}
}
pub async fn recv(&mut self) -> Option<T> {
poll_fn(|cx| self.poll_recv(cx)).await
}
pub async fn recv_many(&mut self, buf: &mut Vec<T>, max: usize) -> usize {
poll_fn(|cx| self.poll_recv_many(cx, buf, max)).await
}
pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll<Option<T>> {
self.inner.poll_recv(cx).map(|maybe_item| {
maybe_item.inspect(|_| {
if let Some(gauge) = &self.gauge {
gauge.dec()
}
})
})
}
pub fn poll_recv_many(&mut self, cx: &mut Context<'_>, buf: &mut Vec<T>, max: usize) -> Poll<usize> {
self.inner.poll_recv_many(cx, buf, max).map(|n| {
if let Some(gauge) = &self.gauge {
gauge.sub(n as _);
}
n
})
}
pub fn len(&self) -> usize {
self.inner.len()
}
pub fn is_empty(&self) -> bool {
self.inner.is_empty()
}
pub fn close(&mut self) {
self.inner.close();
}
}
impl<T> Drop for MeteredReceiver<T> {
fn drop(&mut self) {
// Record the number of elements still in the channel on drop
if let Some(gauge) = &self.gauge {
gauge.sub(self.inner.len() as _);
}
}
}
/// Wraps the transmitting end of a channel with a gauge for tracking the size of the channel.
pub struct MeteredSender<T> {
inner: mpsc::Sender<T>,
gauge: Option<IntGauge>,
}
impl<T> MeteredSender<T> {
pub fn new(inner: mpsc::Sender<T>) -> Self {
Self { inner, gauge: None }
}
pub fn with_gauge(inner: mpsc::Sender<T>, gauge: IntGauge) -> Self {
Self {
inner,
gauge: Some(gauge),
}
}
pub async fn send(&mut self, value: T) -> Result<(), SendError<T>> {
self.inner.send(value).await?;
if let Some(gauge) = &self.gauge {
gauge.inc();
}
Ok(())
}
pub fn try_send(&mut self, value: T) -> Result<(), TrySendError<T>> {
self.inner.try_send(value)?;
if let Some(gauge) = &self.gauge {
gauge.inc();
}
Ok(())
}
}
/// Wraps the receiving end of an unbounded channel with a gauge for tracking the size of the channel.
/// We subtract the size of the channel from the gauge on drop to avoid leaking the metric.
pub struct MeteredUnboundedReceiver<T> {
inner: mpsc::UnboundedReceiver<T>,
gauge: Option<IntGauge>,
}
impl<T> MeteredUnboundedReceiver<T> {
pub async fn recv_many(&mut self, buffer: &mut Vec<T>, limit: usize) -> usize {
let count = self.inner.recv_many(buffer, limit).await;
if let Some(gauge) = &self.gauge {
gauge.sub(count as i64);
}
count
}
pub fn try_recv(&mut self) -> Result<T, mpsc::error::TryRecvError> {
self.inner.try_recv().inspect(|_| {
if let Some(gauge) = &self.gauge {
gauge.dec();
}
})
}
pub fn new(inner: mpsc::UnboundedReceiver<T>) -> Self {
Self { inner, gauge: None }
}
pub fn with_gauge(inner: mpsc::UnboundedReceiver<T>, gauge: IntGauge) -> Self {
Self {
inner,
gauge: Some(gauge),
}
}
pub async fn recv(&mut self) -> Option<T> {
poll_fn(|cx| self.poll_recv(cx)).await
}
pub fn blocking_recv(&mut self) -> Option<T> {
self.inner.blocking_recv().inspect(|_| {
if let Some(gauge) = &self.gauge {
gauge.dec();
}
})
}
pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll<Option<T>> {
let poll = self.inner.poll_recv(cx);
if let Poll::Ready(Some(_)) = poll
&& let Some(gauge) = &self.gauge
{
gauge.dec()
}
poll
}
pub fn len(&self) -> usize {
self.inner.len()
}
pub fn is_empty(&self) -> bool {
self.inner.is_empty()
}
pub fn close(&mut self) {
self.inner.close();
}
}
impl<T> Drop for MeteredUnboundedReceiver<T> {
fn drop(&mut self) {
// Record the number of elements still in the channel on drop
self.inner.close();
if let Some(gauge) = &self.gauge {
gauge.sub(self.inner.len() as _);
}
}
}
/// Wraps the transmitting end of an unbounded channel with a gauge for tracking the size of the channel.
pub struct MeteredUnboundedSender<T> {
inner: mpsc::UnboundedSender<T>,
gauge: Option<IntGauge>,
}
impl<T> Clone for MeteredUnboundedSender<T> {
fn clone(&self) -> Self {
Self {
inner: self.inner.clone(),
gauge: self.gauge.clone(),
}
}
}
impl<T> MeteredUnboundedSender<T> {
pub fn new(inner: mpsc::UnboundedSender<T>) -> Self {
Self { inner, gauge: None }
}
pub fn with_gauge(inner: mpsc::UnboundedSender<T>, gauge: IntGauge) -> Self {
Self {
inner,
gauge: Some(gauge),
}
}
pub fn send(&self, value: T) -> Result<(), SendError<T>> {
if let Some(gauge) = &self.gauge {
gauge.inc();
}
if let Err(err) = self.inner.send(value) {
if let Some(gauge) = &self.gauge {
gauge.dec();
}
return Err(err);
}
Ok(())
}
}
// if a client racks up this many messages in the queue without ACK'ing
// anything, we boot 'em.
const CLIENT_CHANNEL_CAPACITY: usize = 16 * KB;
// use a smaller value for tests
const CLIENT_CHANNEL_CAPACITY_TEST: usize = 8;
const KB: usize = 1024;
/// Value returned by [`ClientConnection::call_client_connected_maybe_reject`]
/// and consumed by [`ClientConnection::spawn`] which acts as a proof that the client is authorized.
///
/// Because this struct does not capture the module or database info or the client connection info,
/// a malicious caller could [`ClientConnected::call_client_connected_maybe_reject`] for one client
/// and then use the resulting `Connected` token to [`ClientConnection::spawn`] for a different client.
/// We're not particularly worried about that.
/// This token exists as a sanity check that non-malicious callers don't accidentally [`ClientConnection::spawn`]
/// for an unauthorized client.
#[non_exhaustive]
pub struct Connected {
_private: (),
}
impl ClientConnection {
/// Call the database at `module_rx`'s `client_connection` reducer, if any,
/// and return `Err` if it signals rejecting this client's connection.
///
/// Call this method before [`Self::spawn`]
/// and pass the returned [`Connected`] to [`Self::spawn`] as proof that the client is authorized.
pub async fn call_client_connected_maybe_reject(
module_rx: &mut watch::Receiver<ModuleHost>,
id: ClientActorId,
auth: ConnectionAuthCtx,
) -> Result<Connected, ClientConnectedError> {
let module = module_rx.borrow_and_update().clone();
module.call_identity_connected(auth, id.connection_id).await?;
Ok(Connected { _private: () })
}
/// Spawn a new [`ClientConnection`] for a WebSocket subscriber.
///
/// Callers should first call [`Self::call_client_connected_maybe_reject`]
/// to verify that the database at `module_rx` approves of this connection,
/// and should not invoke this method if that call returns an error,
/// and pass the returned [`Connected`] as `_proof_of_client_connected_call`.
#[allow(clippy::too_many_arguments)]
pub async fn spawn<Fut>(
id: ClientActorId,
auth: ConnectionAuthCtx,
sql_auth: AuthCtx,
config: ClientConfig,
replica_id: u64,
mut module_rx: watch::Receiver<ModuleHost>,
actor: impl FnOnce(ClientConnection, ClientConnectionReceiver) -> Fut,
_proof_of_client_connected_call: Connected,
) -> ClientConnection
where
Fut: Future<Output = ()> + Send + 'static,
{
// Add this client as a subscriber
// TODO: Right now this is connecting clients directly to a replica, but their requests should be
// logically subscribed to the database, not any particular replica. We should handle failover for
// them and stuff. Not right now though.
let module = module_rx.borrow_and_update().clone();
let (sendtx, sendrx) = mpsc::channel::<ClientUpdate>(CLIENT_CHANNEL_CAPACITY);
let (fut_tx, fut_rx) = oneshot::channel::<Fut>();
// weird dance so that we can get an abort_handle into ClientConnection
let module_info = module.info.clone();
let database_identity = module_info.database_identity;
let client_identity = id.identity;
let metrics = ClientConnectionMetrics::new(database_identity, config.protocol);
let actor_disconnect_recorder = metrics.disconnect_recorder.clone();
let abort_handle = tokio::spawn(async move {
let Ok(fut) = fut_rx.await else {
log::warn!("websocket connection aborted for client identity `{client_identity}` and database identity `{database_identity}` before actor startup");
record_client_rejection(database_identity, ClientRejectCause::ActorStartupFailure);
return };
let _gauge_guard = module_info.metrics.connected_clients.inc_scope();
module_info.metrics.ws_clients_spawned.inc();
let abort_guard = scopeguard::guard((), |_| {
let database_identity = module_info.database_identity;
module_info.metrics.ws_clients_aborted.inc();
// This is always called for to make sure `ws_clients_aborted` is incremented, but we only want to log a warning here
// if we haven't already recorded a cause for this disconnection.
if actor_disconnect_recorder.record(ClientDisconnectCause::Unknown) {
log::warn!("websocket connection aborted for client identity `{client_identity}` and database identity `{database_identity}`");
}
});
fut.await;
ScopeGuard::into_inner(abort_guard);
})
.abort_handle();
let receiver = ClientConnectionReceiver::new(
config.confirmed_reads,
MeteredReceiver::with_gauge(sendrx, metrics.sendtx_queue_size.clone()),
module_rx.clone(),
);
let sender = Arc::new(ClientConnectionSender {
id,
auth,
config,
sendtx,
abort_handle,
cancelled: AtomicBool::new(false),
metrics: Some(metrics),
});
let this = Self {
sender,
replica_id,
module_rx,
auth: sql_auth,
};
let actor_fut = actor(this.clone(), receiver);
// if this fails, the actor() function called .abort(), which like... okay, I guess?
let _ = fut_tx.send(actor_fut);
this
}
pub fn dummy(
id: ClientActorId,
config: ClientConfig,
replica_id: u64,
module_rx: watch::Receiver<ModuleHost>,
) -> Self {
Self::dummy_with_receiver(id, config, replica_id, module_rx).0
}
pub fn dummy_with_receiver(
id: ClientActorId,
config: ClientConfig,
replica_id: u64,
module_rx: watch::Receiver<ModuleHost>,
) -> (Self, ClientConnectionReceiver) {
let auth = AuthCtx::new(module_rx.borrow().database_info().database_identity, id.identity);
let (sender, receiver) = ClientConnectionSender::dummy_with_channel(id, config, module_rx.clone());
(
Self {
sender: Arc::new(sender),
replica_id,
module_rx,
auth,
},
receiver,
)
}
pub fn sender(&self) -> Arc<ClientConnectionSender> {
self.sender.clone()
}
pub fn disconnect_recorder(&self) -> Option<ClientDisconnectRecorder> {
self.sender
.metrics
.as_ref()
.map(|metrics| metrics.disconnect_recorder.clone())
}
/// Get the [`ModuleHost`] for this connection.
///
/// Note that modules can be hotswapped, in which case the returned handle