/
server.rs
2167 lines (1918 loc) · 72.2 KB
/
server.rs
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::{hash_map::Entry, HashMap, HashSet},
env,
fmt::Debug,
fs,
path::{Path, PathBuf},
sync::{
atomic::{AtomicU64, Ordering},
Arc,
},
time::{SystemTime, UNIX_EPOCH},
};
use jwt::JwtError;
use warp::{
http::{
header::{self, HeaderValue},
StatusCode,
},
ws, Filter, Reply,
};
use common::{
chrono::{Duration, TimeZone, Utc},
eyre::{bail, eyre, Result},
futures::{SinkExt, StreamExt},
itertools::Itertools,
once_cell::sync::{Lazy, OnceCell},
regex::{Captures, Regex},
serde::{Deserialize, Serialize},
serde_json,
tokio::{
self,
sync::{mpsc, RwLock},
task::JoinHandle,
},
tracing,
};
use events::{subscribe, unsubscribe, Subscriber, SubscriptionId};
use http_utils::{http, urlencoding};
use server_next::statics::{get_static_parts, STATIC_VERSION};
use stencila_schema::Node;
use uuids::generate;
use crate::{
config::CONFIG,
documents::DOCUMENTS,
jwt::{self, YEAR_SECONDS},
projects::Projects,
rpc::{self, Error, Response},
utils::urls,
};
/// Main server entry point function
///
/// Used when there is no fancy CLI and all that is wanted is a minimal
/// server process.
///
/// This is currently bare bones and quite useless because it uses an unknown, randomly
/// generated secret key for auth. Instead, it should read options from config file,
/// start accordingly, initialize logging etc and gracefully shutdown on `SIGINT`.
pub async fn main() -> Result<()> {
use tokio::time::{sleep, Duration};
start(None, None, None, false, false, false, None, None, false).await?;
sleep(Duration::MAX).await;
Ok(())
}
/// Start the server
#[allow(clippy::too_many_arguments)]
#[tracing::instrument]
pub async fn start(
home: Option<PathBuf>,
url: Option<String>,
key: Option<String>,
insecure: bool,
traversal: bool,
root: bool,
max_inactivity: Option<u64>,
max_duration: Option<u64>,
log_requests: bool,
) -> Result<JoinHandle<()>> {
if let Some(server) = SERVER.get() {
let server = server.read().await;
if server.running() {
bail!("Server has already been started; perhaps use `stop` first");
}
}
let mut server = Server::new(
home,
url,
key,
insecure,
traversal,
root,
max_inactivity,
max_duration,
log_requests,
)
.await?;
let join_handle = server.start().await?;
match SERVER.get() {
Some(mutex) => {
*(mutex.write().await) = server;
}
None => {
if SERVER.set(RwLock::new(server)).is_err() {
bail!("Unable to set server instance")
}
}
}
Ok(join_handle)
}
/// Stop the server
#[tracing::instrument]
pub async fn stop() -> Result<()> {
if let Some(server) = SERVER.get() {
server.write().await.stop().await?;
} else {
tracing::warn!("Server has not yet been started");
}
Ok(())
}
/// The time that the server was started
static START_TIMESTAMP: AtomicU64 = AtomicU64::new(0);
/// The time that the last request activity was recorded (e.g. a HTTP or RPC request)
static ACTIVITY_TIMESTAMP: AtomicU64 = AtomicU64::new(0);
/// Get the current timestamp in seconds
fn timestamp() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.expect("Time went backwards")
.as_secs()
}
/// Record activity
///
/// Note: this is separate to metric recording because some requests (e.g. to `~metrics` or `~static`
/// routes) should not be recorded as activity
fn record_activity() {
ACTIVITY_TIMESTAMP.fetch_max(timestamp(), Ordering::Relaxed);
}
/// Serve a project or document
///
/// The server will be started (if it has not already been) and a URL is returned
/// containing the server's port, the path, and a token providing access to the
/// path (unless the server has no `key`). The path will be added to the server's
/// list of served paths (only paths withing these paths can be accessed).
///
/// # Arguments
///
/// - `path`: The path to be served
/// - `expiry_seconds`: The number of seconds before the token expires
/// - `single_use`: Whether the token should be single use
pub async fn serve<P: AsRef<Path>>(
path: &P,
expiry_seconds: Option<i64>,
single_use: bool,
) -> Result<String> {
let path = path.as_ref();
// Insert the path into the server's paths to allow access
let project = Projects::project_of_path(path)?;
// Get, or start, the server
let server = match SERVER.get() {
Some(server) => server,
None => {
let mut server = Server::new(
Some(project.clone()),
None,
None,
false,
false,
false,
None,
None,
false,
)
.await?;
server.start().await?;
SERVER.get_or_init(|| RwLock::new(server))
}
};
let server = server.read().await;
// If the path is in the server `home` directory, use a relative path in the URL.
// Strip forward slashes from paths: URL paths beginning with a forward slash cause issues with 301 redirects
// (they are confused with protocol relative URLs by the browser) and percent encoding them causes other issues
// with cookie `Path` matching.
let url_path = if let Ok(path) = path.strip_prefix(&server.home) {
path
} else if let Ok(path) = path.strip_prefix("/") {
path
} else {
path
}
.display()
.to_string();
// Create a URL to path, with a path scoped token (if necessary).
let mut url = format!("http://{}:{}/{}", server.address, server.port, url_path);
if let Some(key) = &server.key {
let token = jwt::encode(key, Some(project), expiry_seconds, single_use)?;
url += &format!("?token={}", token);
}
Ok(url)
}
/// The global, singleton, HTTP/WebSocket server instance
static SERVER: OnceCell<RwLock<Server>> = OnceCell::new();
/// A HTTP/WebSocket server
#[derive(Debug, Serialize)]
#[serde(crate = "common::serde")]
pub struct Server {
/// The IP address that the server is listening on
address: String,
/// The port that the server is listening on
port: u16,
/// The secret key used to sign and verify JSON Web Tokens issued by the server
key: Option<String>,
/// The home project of the server
///
/// This defaults to the directory that the server is started in, or if that directory
/// is nested within a project (i.e. has a `project.json` file), the root directory of the project.
/// Any relative paths that are requested from the server will be resolved to this
/// directory.
home: PathBuf,
/// Whether traversal out of `paths` is permitted
traversal: bool,
/// Maximum number of seconds of inactivity before the server shutsdown
max_inactivity: u64,
/// Maximum number of seconds running before the server shutsdown
max_duration: u64,
/// Whether each request should be logged
log_requests: bool,
/// The set of already used, single-use tokens
used_tokens: HashSet<String>,
/// The `mpsc` channel sender used internally to gracefully shutdown the server
#[serde(skip)]
shutdown_sender: Option<mpsc::Sender<()>>,
}
impl Server {
/// Create a new server
///
/// # Arguments
///
/// - `home`: The root directory for files that are served (defaults to current working directory)
/// - `url`: The URL to listen on
/// - `key`: A secret key for signing and verifying JSON Web Tokens (defaults to random)
/// - `insecure`: Allow unauthenticated access (i.e. no JSON Web Token)
/// - `traversal`: Allow traversal out of the root directory is allowed
/// - `root`: Allow serving as root user
#[allow(clippy::too_many_arguments)]
pub async fn new(
home: Option<PathBuf>,
url: Option<String>,
key: Option<String>,
insecure: bool,
traversal: bool,
root: bool,
max_inactivity: Option<u64>,
max_duration: Option<u64>,
log_requests: bool,
) -> Result<Self> {
let config = &CONFIG.lock().await.server;
let home = match &home {
Some(home) => home.canonicalize()?,
None => Projects::project_of_cwd()?,
};
let url = match url {
Some(url) => Some(url),
None => config.url.clone(),
};
let key = match key {
Some(key) => Some(key),
None => config.key.clone(),
};
let insecure = insecure || config.insecure;
if insecure {
tracing::warn!("Serving in insecure mode is dangerous and discouraged.")
}
let key = if key.is_none() {
match insecure {
true => None,
false => Some(key_utils::generate()),
}
} else {
key
};
if traversal {
tracing::warn!("Allowing traversal out of server home directory.")
}
if root {
tracing::warn!("Serving as root/administrator is dangerous and discouraged.")
}
#[cfg(any(target_os = "linux", target_os = "macos"))]
if let sudo::RunningAs::Root = sudo::check() {
if !root {
bail!("Serving as root/administrator is not permitted by default, use the `--root` option to bypass this safety measure.")
}
}
let (address, port) = match url {
Some(url) => Self::parse_url(&url)?,
None => ("127.0.0.1".to_string(), Self::pick_port(9000, 9011)?),
};
let ten_years = 315360000;
let max_inactivity = max_inactivity.unwrap_or(ten_years);
let max_duration = max_duration.unwrap_or(ten_years);
Ok(Self {
address,
port,
key,
home,
traversal,
max_inactivity,
max_duration,
log_requests,
used_tokens: HashSet::new(),
shutdown_sender: None,
})
}
/// Start the server
pub async fn start(&mut self) -> Result<JoinHandle<()>> {
let home = self.home.clone();
let traversal = self.traversal;
let mut url = format!(
"http://{}:{}",
self.address.replace("0.0.0.0", "127.0.0.1"),
self.port
);
if let Some(key) = &self.key {
// Check the key is not too long
if key.len() > 64 {
bail!("Server key should be 64 bytes or less")
}
// Provide the user with a long-expiring, multiple-use token, scoped to the home project.
let token = jwt::encode(key, Some(home.clone()), None, false)?;
url.push_str("?token=");
url.push_str(&token);
}
tracing::info!("Serving {} at {}", home.display(), url);
// HTTP endpoints without authentication
let statics = warp::get()
.and(warp::path("~static"))
.and(warp::path::tail())
.and_then(get_static);
let metrics = warp::get()
.and(warp::path("~metrics"))
.and_then(get_metrics);
let hooks = warp::post()
.and(warp::path("~hooks"))
.and(warp::query::<HooksParams>())
.and(warp::header::headers_cloned())
.and(warp::body::content_length_limit(10 * 1_048_576)) // 10MB limit
.and(warp::body::json())
.and_then(post_hooks);
// HTTP and WS endpoints requiring authentication
let authenticate = || authentication_filter(self.key.clone(), self.home.clone());
let terminal = warp::get()
.and(warp::path("~terminal"))
.and(authenticate())
.and_then(terminal_handler);
let attach = warp::path("~attach")
.and(warp::ws())
.and(authenticate())
.map(attach_handler);
let rpc_ws = warp::path("~rpc")
.and(warp::ws())
.and(warp::query::<WsParams>())
.and(authenticate())
.map(rpc_ws_handler);
let get = warp::get()
.and(warp::path::full())
.and(warp::query::<GetParams>())
.and(authenticate())
.and(warp::any().map(move || (home.clone(), traversal)))
.and_then(get_handler);
// Custom `server` header
let server_header = warp::reply::with::default_header(
"server",
format!(
"Stencila/{} ({})",
env!("CARGO_PKG_VERSION"),
env::consts::OS
),
);
// CORS headers to allow from any origin
let cors_headers = warp::cors()
.allow_any_origin()
.allow_headers(vec![
"Content-Type",
"Referer", // Note that this is an intentional misspelling!
"Origin",
"Access-Control-Allow-Origin",
])
.allow_methods(&[warp::http::Method::GET, warp::http::Method::POST])
.max_age(24 * 60 * 60);
let log_requests = self.log_requests;
let log = warp::log::custom(move |info| {
if !log_requests {
return;
}
let method = info.method().as_str();
let path = info.path();
let time = info.elapsed();
let status = info.status().as_u16();
macro_rules! event {
($level:expr) => {
tracing::event!(
$level,
method,
path,
status,
time = time.as_micros() as u64,
referer = info.referer(),
user_agent = info.user_agent(),
"{} {} {} {:?}",
method,
path,
status,
time,
);
};
}
use tracing::Level;
if status < 400 {
event!(Level::INFO);
} else if status < 500 {
event!(Level::WARN);
} else {
event!(Level::ERROR);
}
});
let routes = statics
.or(metrics)
.or(hooks)
.or(terminal)
.or(attach)
.or(rpc_ws)
.or(get)
.with(server_header)
.with(cors_headers)
.with(log)
.recover(rejection_handler);
// Spawn the serving task
let (shutdown_sender, mut shutdown_receiver) = mpsc::channel::<()>(1);
let address: std::net::IpAddr = self.address.parse()?;
let (_, future) =
warp::serve(routes).bind_with_graceful_shutdown((address, self.port), async move {
shutdown_receiver.recv().await;
});
let serve_task = tokio::task::spawn(future);
// Initialize timestamps and pawn a timing task to shutdown the server after inactivity,
// or a maximum duration
START_TIMESTAMP.fetch_max(timestamp(), Ordering::SeqCst);
ACTIVITY_TIMESTAMP.fetch_max(timestamp(), Ordering::SeqCst);
let shutdown_sender_clone = shutdown_sender.clone();
let max_duration = self.max_duration;
let max_inactivity = self.max_inactivity;
tokio::task::spawn(async move {
use tokio::time::{sleep, Duration};
loop {
let now = timestamp();
let inactivity_remaining = max_inactivity
.saturating_sub(now.saturating_sub(ACTIVITY_TIMESTAMP.load(Ordering::SeqCst)));
let duration_remaining = max_duration
.saturating_sub(now.saturating_sub(START_TIMESTAMP.load(Ordering::SeqCst)));
if inactivity_remaining == 0 || duration_remaining == 0 {
if inactivity_remaining == 0 {
tracing::info!(
"Server shutting down after maximum period of inactivity of {} seconds",
max_inactivity
);
} else {
tracing::info!(
"Server shutting down after maximum duration of {} seconds",
max_duration
);
}
shutdown_sender_clone.send(()).await.ok();
return;
}
SECONDS_TO_SHUTDOWN.set(
std::cmp::min(inactivity_remaining, duration_remaining)
.try_into()
.unwrap_or(i64::MAX),
);
sleep(Duration::from_secs(1)).await;
}
});
self.shutdown_sender = Some(shutdown_sender);
Ok(serve_task)
}
/// Stop the server
pub async fn stop(&mut self) -> Result<()> {
tracing::debug!("Stopping server");
WEBSOCKET_CLIENTS.clear().await;
if self.shutdown_sender.is_some() {
// It appears to be sufficient to just set the sender to None to shutdown the server
self.shutdown_sender = None;
tracing::info!("Server stopped successfully");
} else {
tracing::info!("Server was already stopped");
}
Ok(())
}
/// Is the server running?
pub fn running(&self) -> bool {
self.shutdown_sender.is_some()
}
/// Parse a URL into address and port components
pub fn parse_url(url: &str) -> Result<(String, u16)> {
let url = urls::parse(url)?;
let address = url.host().unwrap().to_string();
let port = url
.port_or_known_default()
.expect("Should be a default port for the protocol");
Ok((address, port))
}
/// Pick the first available port from a range, falling back to a random port
/// if none of the ports in the range are available
pub fn pick_port(min: u16, max: u16) -> Result<u16> {
for port in min..max {
if portpicker::is_free(port) {
return Ok(port);
}
}
portpicker::pick_unused_port().ok_or_else(|| eyre!("There are no free ports"))
}
}
static HTTP_REQUESTS_COUNT: Lazy<prometheus::IntCounterVec> = Lazy::new(|| {
prometheus::IntCounterVec::new(
prometheus::Opts::new(
"stencila_http_requests_count",
"Count of HTTP requests by method and path",
),
&["method", "path"],
)
.expect("Unable to create metric")
});
static RPC_REQUESTS_COUNT: Lazy<prometheus::IntCounterVec> = Lazy::new(|| {
prometheus::IntCounterVec::new(
prometheus::Opts::new(
"stencila_rpc_requests_count",
"Count of RPC requests by method",
),
&["method"],
)
.expect("Unable to create metric")
});
static WEBSOCKET_CLIENTS_COUNT: Lazy<prometheus::IntGauge> = Lazy::new(|| {
prometheus::IntGauge::new(
"stencila_websocket_clients",
"Count of Websocket clients currently connected",
)
.expect("Unable to create metric")
});
static SECONDS_TO_SHUTDOWN: Lazy<prometheus::IntGauge> = Lazy::new(|| {
prometheus::IntGauge::new(
"stencila_seconds_to_shutdown",
"Number of seconds until the server shutsdown",
)
.expect("Unable to create metric")
});
static METRICS_REGISTRY: Lazy<prometheus::Registry> = Lazy::new(|| {
let registry = prometheus::Registry::new();
registry
.register(Box::new(HTTP_REQUESTS_COUNT.clone()))
.expect("Unable to register metric");
registry
.register(Box::new(RPC_REQUESTS_COUNT.clone()))
.expect("Unable to register metric");
registry
.register(Box::new(WEBSOCKET_CLIENTS_COUNT.clone()))
.expect("Unable to register metric");
registry
.register(Box::new(SECONDS_TO_SHUTDOWN.clone()))
.expect("Unable to register metric");
registry
});
fn record_http_request(method: &str, path: &str) {
HTTP_REQUESTS_COUNT.with_label_values(&[method, path]).inc();
}
fn record_rpc_request(method: &str) {
RPC_REQUESTS_COUNT.with_label_values(&[method]).inc();
}
#[derive(Debug, Serialize)]
#[serde(crate = "common::serde")]
struct WebsocketClient {
/// The client id
id: String,
/// The event topics that this client is subscribed to
subscriptions: HashSet<String>,
/// The current sender for this client
///
/// This is set / reset each time that the client opens
/// a WebSocket connection
#[serde(skip)]
sender: mpsc::UnboundedSender<ws::Message>,
}
impl WebsocketClient {
/// Subscribe the client to an event topic
pub fn subscribe(&mut self, topic: &str) {
self.subscriptions.insert(topic.to_string());
}
/// Unsubscribe the client from an event topic
pub fn unsubscribe(&mut self, topic: &str) {
self.subscriptions.remove(topic);
}
/// Is a client subscribed to a particular topic, or set of topics?
pub fn subscribed(&self, topic: &str) -> bool {
for subscription in &self.subscriptions {
if subscription == "*" || topic.starts_with(subscription) {
return true;
}
}
false
}
/// Send a serializable message to the client
pub fn send(&self, message: impl Serialize) {
match serde_json::to_string(&message) {
Ok(json) => self.send_text(&json),
Err(error) => tracing::error!("Error serializing to JSON `{}`", error),
}
}
/// Send a text message to the client
pub fn send_text(&self, text: &str) {
if let Err(error) = self.sender.send(warp::ws::Message::text(text)) {
tracing::error!("Websocket client send error `{}`", error)
}
}
}
/// The global store of Websocket clients
static WEBSOCKET_CLIENTS: Lazy<WebsocketClients> = Lazy::new(WebsocketClients::new);
/// A store of clients
///
/// Used to manage relaying events to clients.
#[derive(Debug)]
struct WebsocketClients {
/// The clients
inner: Arc<RwLock<HashMap<String, WebsocketClient>>>,
/// The event subscriptions held on behalf of clients
///
/// Used to keep track of the number of clients subscribed to each topic.
/// This ensures that we don't subscribe to the same event more than once (which results in
/// the same event being relayed to each client more than once) and that we can unsubscribe when
/// it becomes zero.
subscriptions: Arc<RwLock<HashMap<String, (SubscriptionId, usize)>>>,
/// The sender used to subscribe to events on behalf of clients
sender: mpsc::UnboundedSender<events::Message>,
}
impl WebsocketClients {
/// Create a new client store and begin task for publishing events to them
pub fn new() -> Self {
let inner = Arc::new(RwLock::new(HashMap::new()));
let subscriptions = Arc::new(RwLock::new(HashMap::new()));
let (sender, receiver) = mpsc::unbounded_channel::<events::Message>();
tokio::spawn(WebsocketClients::relay(inner.clone(), receiver));
Self::ping(inner.clone());
Self {
inner,
subscriptions,
sender,
}
}
/// A client connected
pub async fn connected(&self, client_id: &str, sender: mpsc::UnboundedSender<ws::Message>) {
let mut clients = self.inner.write().await;
match clients.entry(client_id.to_string()) {
Entry::Occupied(mut occupied) => {
tracing::debug!("Re-connection for client `{}`", client_id);
let client = occupied.get_mut();
client.sender = sender;
}
Entry::Vacant(vacant) => {
tracing::debug!("New connection for client `{}`", client_id);
vacant.insert(WebsocketClient {
id: client_id.to_string(),
subscriptions: HashSet::new(),
sender,
});
}
};
}
/// A client disconnected
pub async fn disconnected(&self, client_id: &str, gracefully: bool) {
self.remove(client_id).await;
if gracefully {
tracing::trace!("Graceful disconnect by client `{}`", client_id)
} else {
tracing::warn!("Ungraceful disconnect by client `{}`", client_id)
}
}
/// Subscribe a client to an event topic
pub async fn subscribe(&self, client_id: &str, topic: &str) {
let mut clients = self.inner.write().await;
if let Some(client) = clients.get_mut(client_id) {
tracing::trace!("Subscribing client `{}` to topic `{}`", client_id, topic);
let mut subscriptions = self.subscriptions.write().await;
match subscriptions.entry(topic.to_string()) {
Entry::Occupied(mut occupied) => {
occupied.get_mut().1 += 1;
}
Entry::Vacant(vacant) => {
match subscribe(topic, Subscriber::UnboundedSender(self.sender.clone())) {
Ok(subscription_id) => {
vacant.insert((subscription_id, 1));
}
Err(error) => {
tracing::error!(
"While attempting to subscribe to event topic `{}`:",
error
);
}
}
}
}
client.subscribe(topic);
} else {
tracing::error!("No such client `{}`", client_id);
}
}
/// Unsubscribe a client from an event topic and unsubscribe self if
/// no more clients are subscribed to that topic.
fn unsubscribe_topic(
&self,
client: &mut WebsocketClient,
topic: &str,
subscriptions: &mut HashMap<String, (SubscriptionId, usize)>,
) {
client.unsubscribe(topic);
if let Entry::Occupied(mut occupied) = subscriptions.entry(topic.to_string()) {
let (subscription_id, clients) = occupied.get_mut();
if *clients == 1 {
if let Err(err) = unsubscribe(subscription_id) {
tracing::debug!(
"While unsubscribing from subscription `{}`: {}",
subscription_id,
err,
)
}
occupied.remove();
} else {
*clients -= 1;
}
}
}
/// Unsubscribe a client from an event topic
pub async fn unsubscribe(&self, client_id: &str, topic: &str) {
let mut clients = self.inner.write().await;
if let Some(client) = clients.get_mut(client_id) {
let subscriptions = &mut *self.subscriptions.write().await;
tracing::trace!(
"Unsubscribing client `{}` from topic `{}`",
client_id,
topic
);
self.unsubscribe_topic(client, topic, subscriptions);
} else {
tracing::error!("No such client `{}`", client_id);
}
}
/// Remove a client from the store
///
/// Removes all the client event subscriptions in addition to removing the client
/// from the list of clients.
pub async fn remove(&self, client_id: &str) {
let mut clients = self.inner.write().await;
if let Some(client) = clients.get_mut(client_id) {
let subscriptions = &mut *self.subscriptions.write().await;
for topic in client.subscriptions.clone() {
self.unsubscribe_topic(client, &topic, subscriptions);
}
}
clients.remove(client_id);
}
/// Remove all clients from the store
///
/// Removes all clients and all event subscriptions.
/// This should be done when the server is stopped to avoid keeping a record
/// of clients that have been disconnected.
pub async fn clear(&self) {
let mut subscriptions = self.subscriptions.write().await;
for (subscription_id, ..) in subscriptions.values() {
if let Err(err) = unsubscribe(subscription_id) {
tracing::debug!(
"While unsubscribing from subscription `{}`: {}",
subscription_id,
err,
)
}
}
subscriptions.clear();
let mut clients = self.inner.write().await;
clients.clear();
}
/// Ping all clients periodically
fn ping(clients: Arc<RwLock<HashMap<String, WebsocketClient>>>) {
tokio::spawn(async move {
loop {
let clients = clients.read().await;
for (client_id, client) in clients.iter() {
if let Err(error) = client.sender.send(warp::ws::Message::ping("ping")) {
tracing::debug!("While sending ping to client `{}`: {}", client_id, error)
}
}
// Explicitly drop the read lock so that it is not held while sleeping
drop(clients);
use tokio::time::{sleep, Duration};
sleep(Duration::from_secs(15)).await;
}
});
}
/// Send a message to a client
pub async fn send(&self, client_id: &str, message: impl Serialize) {
let clients = self.inner.read().await;
if let Some(client) = clients.get(client_id) {
client.send(message);
} else {
tracing::error!("No such client `{}`", client_id);
}
}
/// Relay events to clients
///
/// The receiver will receive _all_ events that are published and relay them on to
/// clients based in their subscriptions.
async fn relay(
clients: Arc<RwLock<HashMap<String, WebsocketClient>>>,
receiver: mpsc::UnboundedReceiver<events::Message>,
) {
let mut receiver = tokio_stream::wrappers::UnboundedReceiverStream::new(receiver);
while let Some((topic, event)) = receiver.next().await {
tracing::trace!("Received event for topic `{}`", topic);
// Get a list of clients that are subscribed to this topic
let clients = clients.read().await;
let clients = clients
.values()
.filter(|client| client.subscribed(&topic))
.collect_vec();
// Skip this event if no one is subscribed
if clients.is_empty() {
continue;
}
// Create a JSON-RPC notification for the event and serialize it
// so that does not need to be repeated for each client
let params = if event.is_object() {
serde_json::from_value(event).unwrap()
} else {
let mut params = HashMap::new();
params.insert("event".to_string(), event);
params
};
let notification = rpc::Notification::new(&topic, params);
let json = match serde_json::to_string(¬ification) {
Ok(json) => json,
Err(error) => {
tracing::error!("Error serializing to JSON `{}`", error);
continue;
}
};
tracing::trace!(
"Relaying event to subscribed clients `{}`",
clients
.iter()
.map(|client| client.id.clone())
.collect::<Vec<String>>()
.join(",")
);
// Send it!
for client in clients {
client.send_text(&json)
}
}
}
}
/// Return an error response result
///
/// Used to have a consistent structure to error responses in the
/// handler functions below.
fn error_response(code: StatusCode, message: &str) -> warp::reply::Response {
warp::reply::with_status(
warp::reply::json(&serde_json::json!({ "message": message })),