-
Notifications
You must be signed in to change notification settings - Fork 1k
Expand file tree
/
Copy pathclient_connection.rs
More file actions
492 lines (439 loc) · 15.7 KB
/
client_connection.rs
File metadata and controls
492 lines (439 loc) · 15.7 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
use std::ops::Deref;
use std::sync::atomic::{AtomicBool, Ordering::Relaxed};
use std::sync::Arc;
use std::time::Instant;
use super::messages::{OneOffQueryResponseMessage, SerializableMessage};
use super::{message_handlers, ClientActorId, MessageHandleError};
use crate::error::DBError;
use crate::host::module_host::ClientConnectedError;
use crate::host::{ModuleHost, NoSuchModule, ReducerArgs, ReducerCallError, ReducerCallResult};
use crate::messages::websocket::Subscribe;
use crate::util::asyncify;
use crate::util::prometheus_handle::IntGaugeExt;
use crate::worker_metrics::WORKER_METRICS;
use bytes::Bytes;
use bytestring::ByteString;
use derive_more::From;
use futures::prelude::*;
use prometheus::{Histogram, IntCounter, IntGauge};
use spacetimedb_client_api_messages::websocket::{
BsatnFormat, CallReducerFlags, Compression, FormatSwitch, JsonFormat, SubscribeMulti, SubscribeSingle, Unsubscribe,
UnsubscribeMulti,
};
use spacetimedb_lib::identity::RequestId;
use spacetimedb_lib::metrics::ExecutionMetrics;
use spacetimedb_lib::Identity;
use tokio::sync::{mpsc, oneshot, watch};
use tokio::task::AbortHandle;
#[derive(PartialEq, Eq, Clone, Copy, Hash, Debug)]
pub enum Protocol {
Text,
Binary,
}
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: &FormatSwitch<B, J>) {
match (self, fs) {
(Protocol::Text, FormatSwitch::Json(_)) | (Protocol::Binary, 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 client's desired (conditional) compression algorithm, if any.
pub compression: 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,
}
impl ClientConfig {
pub fn for_test() -> ClientConfig {
Self {
protocol: Protocol::Binary,
compression: <_>::default(),
tx_update_full: true,
}
}
}
#[derive(Debug)]
pub struct ClientConnectionSender {
pub id: ClientActorId,
pub config: ClientConfig,
sendtx: mpsc::Sender<SerializableMessage>,
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,
/// 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 sendtx_queue_size = WORKER_METRICS
.total_outgoing_queue_length
.with_label_values(&database_identity);
Self {
websocket_request_msg_size,
websocket_requests,
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) -> (Self, mpsc::Receiver<SerializableMessage>) {
let (sendtx, rx) = mpsc::channel(1);
// 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 cancelled = AtomicBool::new(false);
let sender = Self {
id,
config,
sendtx,
abort_handle,
cancelled,
metrics: None,
};
(sender, rx)
}
pub fn dummy(id: ClientActorId, config: ClientConfig) -> Self {
Self::dummy_with_channel(id, config).0
}
/// 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.
pub fn send_message(&self, message: impl Into<SerializableMessage>) -> Result<(), ClientSendError> {
self.send(message.into())
}
fn send(&self, message: SerializableMessage) -> 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, "client channel capacity exceeded");
self.abort_handle.abort();
self.cancelled.store(true, Relaxed);
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,
pub module: ModuleHost,
module_rx: watch::Receiver<ModuleHost>,
}
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(),
}
}
}
// 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;
const KB: usize = 1024;
impl ClientConnection {
/// Returns an error if ModuleHost closed
pub async fn spawn<Fut>(
id: ClientActorId,
config: ClientConfig,
replica_id: u64,
mut module_rx: watch::Receiver<ModuleHost>,
actor: impl FnOnce(ClientConnection, mpsc::Receiver<SerializableMessage>) -> Fut,
) -> Result<ClientConnection, ClientConnectedError>
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();
module.call_identity_connected(id.identity, id.connection_id).await?;
let (sendtx, sendrx) = mpsc::channel::<SerializableMessage>(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 abort_handle = tokio::spawn(async move {
let Ok(fut) = fut_rx.await else { return };
let _gauge_guard = module_info.metrics.connected_clients.inc_scope();
module_info.metrics.ws_clients_spawned.inc();
scopeguard::defer!(module_info.metrics.ws_clients_aborted.inc());
fut.await
})
.abort_handle();
let metrics = ClientConnectionMetrics::new(database_identity, config.protocol);
let sender = Arc::new(ClientConnectionSender {
id,
config,
sendtx,
abort_handle,
cancelled: AtomicBool::new(false),
metrics: Some(metrics),
});
let this = Self {
sender,
replica_id,
module,
module_rx,
};
let actor_fut = actor(this.clone(), sendrx);
// if this fails, the actor() function called .abort(), which like... okay, I guess?
let _ = fut_tx.send(actor_fut);
Ok(this)
}
pub fn dummy(
id: ClientActorId,
config: ClientConfig,
replica_id: u64,
mut module_rx: watch::Receiver<ModuleHost>,
) -> Self {
let module = module_rx.borrow_and_update().clone();
Self {
sender: Arc::new(ClientConnectionSender::dummy(id, config)),
replica_id,
module,
module_rx,
}
}
pub fn sender(&self) -> Arc<ClientConnectionSender> {
self.sender.clone()
}
#[inline]
pub fn handle_message(
&self,
message: impl Into<DataMessage>,
timer: Instant,
) -> impl Future<Output = Result<(), MessageHandleError>> + '_ {
message_handlers::handle(self, message.into(), timer)
}
pub async fn watch_module_host(&mut self) -> Result<(), NoSuchModule> {
match self.module_rx.changed().await {
Ok(()) => {
self.module = self.module_rx.borrow_and_update().clone();
Ok(())
}
Err(_) => Err(NoSuchModule),
}
}
pub async fn call_reducer(
&self,
reducer: &str,
args: ReducerArgs,
request_id: RequestId,
timer: Instant,
flags: CallReducerFlags,
) -> Result<ReducerCallResult, ReducerCallError> {
let caller = match flags {
CallReducerFlags::FullUpdate => Some(self.sender()),
// Setting `sender = None` causes `eval_updates` to skip sending to the caller
// as it has no access to the caller other than by id/connection id.
CallReducerFlags::NoSuccessNotify => None,
};
self.module
.call_reducer(
self.id.identity,
Some(self.id.connection_id),
caller,
Some(request_id),
Some(timer),
reducer,
args,
)
.await
}
pub async fn subscribe_single(
&self,
subscription: SubscribeSingle,
timer: Instant,
) -> Result<Option<ExecutionMetrics>, DBError> {
let me = self.clone();
asyncify(move || {
me.module
.subscriptions()
.add_single_subscription(me.sender, subscription, timer, None)
})
.await
}
pub async fn unsubscribe(&self, request: Unsubscribe, timer: Instant) -> Result<Option<ExecutionMetrics>, DBError> {
let me = self.clone();
asyncify(move || {
me.module
.subscriptions()
.remove_single_subscription(me.sender, request, timer)
})
.await
}
pub async fn subscribe_multi(
&self,
request: SubscribeMulti,
timer: Instant,
) -> Result<Option<ExecutionMetrics>, DBError> {
let me = self.clone();
asyncify(move || {
me.module
.subscriptions()
.add_multi_subscription(me.sender, request, timer, None)
})
.await
}
pub async fn unsubscribe_multi(
&self,
request: UnsubscribeMulti,
timer: Instant,
) -> Result<Option<ExecutionMetrics>, DBError> {
let me = self.clone();
asyncify(move || {
me.module
.subscriptions()
.remove_multi_subscription(me.sender, request, timer)
})
.await
}
pub async fn subscribe(&self, subscription: Subscribe, timer: Instant) -> Result<ExecutionMetrics, DBError> {
let me = self.clone();
asyncify(move || {
me.module
.subscriptions()
.add_legacy_subscriber(me.sender, subscription, timer, None)
})
.await
}
pub async fn one_off_query_json(
&self,
query: &str,
message_id: &[u8],
timer: Instant,
) -> Result<(), anyhow::Error> {
self.module
.one_off_query::<JsonFormat>(
self.id.identity,
query.to_owned(),
self.sender.clone(),
message_id.to_owned(),
timer,
|msg: OneOffQueryResponseMessage<JsonFormat>| msg.into(),
)
.await
}
pub async fn one_off_query_bsatn(
&self,
query: &str,
message_id: &[u8],
timer: Instant,
) -> Result<(), anyhow::Error> {
self.module
.one_off_query::<BsatnFormat>(
self.id.identity,
query.to_owned(),
self.sender.clone(),
message_id.to_owned(),
timer,
|msg: OneOffQueryResponseMessage<BsatnFormat>| msg.into(),
)
.await
}
pub async fn disconnect(self) {
self.module.disconnect_client(self.id).await
}
}