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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
use std::sync::atomic::{AtomicUsize, Ordering};
use dashmap::DashMap;
use std::collections::{HashMap, HashSet};
/// Wall-clock time in milliseconds since UNIX epoch.
pub(crate) fn epoch_ms() -> u64 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default()
.as_millis() as u64
}
/// Prefix marking a synthetic "remote presence" sentinel connection -- a user
/// present on a peer node with no local socket here.
const REMOTE_PREFIX: &str = "__remote__";
/// Separator between origin and user_id inside a remote sentinel id. The Unit
/// Separator control char (0x1f) never appears in peer addresses or user ids.
const ORIGIN_SEP: char = '\u{1f}';
/// Sentinel connection id for `user_id` reported present by peer `origin`.
///
/// Keyed PER ORIGIN so a leave (or disconnect) from one peer removes only that
/// peer's sentinel and never erases a user still present on another peer. A
/// single global `__remote__{user_id}` sentinel (the old form) made one peer's
/// leave wipe the user cluster-wide and made per-peer ghost cleanup impossible.
fn remote_sentinel(origin: &str, user_id: &str) -> String {
format!("{REMOTE_PREFIX}{origin}{ORIGIN_SEP}{user_id}")
}
/// Prefix matching every sentinel contributed by `origin` (for purge_origin).
fn remote_origin_prefix(origin: &str) -> String {
format!("{REMOTE_PREFIX}{origin}{ORIGIN_SEP}")
}
#[derive(Clone, Debug)]
pub(crate) struct PresenceEntry {
pub user_id: String,
pub data: serde_json::Value,
pub connections: Vec<ConnMeta>,
pub updated_at: u64,
}
#[derive(Clone, Debug)]
pub(crate) struct ConnMeta {
pub conn_id: String,
/// When it joined; for a peer's sentinel, the time of that peer's latest
/// join, which its leaves are compared against.
pub joined_at: u64,
}
pub(crate) struct PresenceStats {
pub num_users: AtomicUsize,
pub num_connections: AtomicUsize,
}
impl PresenceStats {
pub fn new() -> Self {
Self {
num_users: AtomicUsize::new(0),
num_connections: AtomicUsize::new(0),
}
}
}
/// Result of a track operation.
pub(crate) enum TrackResult {
/// First connection for this user in this topic (emit join event).
FirstJoin {
user_id: String,
data: serde_json::Value,
},
/// The user's first connection on this node, while other nodes report
/// the user: peers must hear the join, local subscribers must not (the
/// user was present).
FirstLocalJoin {
user_id: String,
data: serde_json::Value,
},
/// Additional connection for existing user (no event needed).
ExistingUser,
/// Topic at max capacity or data too large, tracking skipped.
AtCapacity,
/// No user_id available for this connection.
NoUserId,
}
/// Result of an untrack operation.
pub(crate) enum UntrackResult {
/// Last connection removed, user is gone (emit leave event).
LastLeave {
user_id: String,
data: serde_json::Value,
},
/// The user's last connection on this node left, but other nodes still
/// report the user: peers must hear the leave, local subscribers must
/// not (the user is still present).
LastLocalLeave {
user_id: String,
data: serde_json::Value,
},
/// Connection removed but user still has other connections (no event).
StillPresent,
/// Connection was not tracked in this topic.
NotTracked,
}
pub(crate) struct PresenceManager {
/// topic -> user_id -> PresenceEntry
topic_presence: DashMap<String, DashMap<String, PresenceEntry>>,
/// topic -> PresenceStats (incremental counters)
topic_presence_stats: DashMap<String, PresenceStats>,
/// conn_id -> user_id (from JWT auth)
conn_user_id: DashMap<String, String>,
/// conn_id -> topics where this conn has presence
conn_presence_topics: DashMap<String, HashSet<String>>,
/// Max bytes for presence data JSON
max_data_size: usize,
/// Max members per topic (0 = unlimited)
max_members: usize,
}
/// A topic's member map. A few shards are plenty for one topic's members; the
/// default shard count (cores x 4) costs several KiB per topic.
fn new_topic_map() -> DashMap<String, PresenceEntry> {
DashMap::with_shard_amount(4)
}
impl PresenceManager {
pub fn new(max_data_size: usize, max_members: usize) -> Self {
Self {
topic_presence: DashMap::new(),
topic_presence_stats: DashMap::new(),
conn_user_id: DashMap::new(),
conn_presence_topics: DashMap::new(),
max_data_size,
max_members,
}
}
/// Register a user_id for a connection (called on JWT auth).
pub fn register_connection(&self, conn_id: &str, user_id: &str) {
self.conn_user_id
.insert(conn_id.to_owned(), user_id.to_owned());
}
/// Clean up all presence state for a connection (called on disconnect).
/// Returns a list of (topic, UntrackResult) for each topic the conn had presence in.
pub fn remove_connection(&self, conn_id: &str) -> Vec<(String, UntrackResult)> {
let mut results = Vec::new();
if let Some((_, topics)) = self.conn_presence_topics.remove(conn_id) {
for topic_ref in topics.iter() {
let topic = topic_ref.clone();
let result = self.untrack_conn_from_topic(conn_id, &topic);
results.push((topic, result));
}
}
self.conn_user_id.remove(conn_id);
results
}
/// Track a connection's presence in a topic.
pub fn track(&self, conn_id: &str, topic: &str, data: &serde_json::Value) -> TrackResult {
// Validate data size
let data_str = serde_json::to_string(data).unwrap_or_default();
if data_str.len() > self.max_data_size {
return TrackResult::AtCapacity;
}
let user_id = match self.conn_user_id.get(conn_id) {
Some(uid) => uid.value().clone(),
None => return TrackResult::NoUserId,
};
let now = epoch_ms();
// Lock order everywhere in this file: topic_presence before
// conn_presence_topics and topic_presence_stats.
let topic_map = self
.topic_presence
.entry(topic.to_owned())
.or_insert_with(new_topic_map);
// Check max members limit
if self.max_members > 0
&& !topic_map.contains_key(&user_id)
&& topic_map.len() >= self.max_members
{
return TrackResult::AtCapacity;
}
let (is_first, actually_inserted, has_remote_sentinel) = {
let mut entry = topic_map
.entry(user_id.clone())
.or_insert_with(|| PresenceEntry {
user_id: user_id.clone(),
data: data.clone(),
connections: Vec::new(),
updated_at: now,
});
// Check for remote sentinel (from cluster sync) while holding the shard lock
let has_remote = entry
.connections
.iter()
.any(|c| c.conn_id.starts_with("__remote__"));
// Check for first LOCAL connection (ignore remote sentinels)
let was_empty = !entry
.connections
.iter()
.any(|c| !c.conn_id.starts_with("__remote__"));
// Add this connection if not already tracked
let inserted = if !entry.connections.iter().any(|c| c.conn_id == conn_id) {
entry.connections.push(ConnMeta {
conn_id: conn_id.to_owned(),
joined_at: now,
});
true
} else {
false
};
if now >= entry.updated_at {
entry.data = data.clone();
entry.updated_at = now;
}
(was_empty, inserted, has_remote)
};
// Track which topics this conn has presence in
self.conn_presence_topics
.entry(conn_id.to_owned())
.or_default()
.insert(topic.to_owned());
// Update stats
let stats = self
.topic_presence_stats
.entry(topic.to_owned())
.or_insert_with(PresenceStats::new);
if actually_inserted {
stats.num_connections.fetch_add(1, Ordering::Relaxed);
}
if is_first && has_remote_sentinel {
// Present on another node already (merge_remote_join counted the
// user): a join for the peers alone.
TrackResult::FirstLocalJoin {
user_id,
data: data.clone(),
}
} else if is_first {
stats.num_users.fetch_add(1, Ordering::Relaxed);
TrackResult::FirstJoin {
user_id,
data: data.clone(),
}
} else {
TrackResult::ExistingUser
}
}
/// Untrack a connection from a specific topic.
fn untrack_conn_from_topic(&self, conn_id: &str, topic: &str) -> UntrackResult {
let user_id = match self.conn_user_id.get(conn_id) {
Some(uid) => uid.value().clone(),
// Connection might already be cleaned up; try to find user_id from the presence entry
None => {
if let Some(topic_map) = self.topic_presence.get(topic) {
let mut found_user = None;
for entry_ref in topic_map.iter() {
if entry_ref.connections.iter().any(|c| c.conn_id == conn_id) {
found_user = Some(entry_ref.user_id.clone());
break;
}
}
match found_user {
Some(uid) => uid,
None => return UntrackResult::NotTracked,
}
} else {
return UntrackResult::NotTracked;
}
}
};
if let Some(topic_map) = self.topic_presence.get(topic) {
// Phase 1: Remove the connection from the entry (get_mut holds shard lock)
let mut removed_conn = false;
if let Some(mut entry) = topic_map.get_mut(&user_id) {
let before = entry.connections.len();
entry.connections.retain(|c| c.conn_id != conn_id);
if entry.connections.len() < before {
removed_conn = true;
if let Some(stats) = self.topic_presence_stats.get(topic) {
stats.num_connections.fetch_sub(1, Ordering::Relaxed);
}
}
}
// Phase 2: Atomically remove entry only if connections is still empty
// (prevents TOCTOU race where track() adds a connection between phases)
if removed_conn
&& let Some((_, removed_entry)) =
topic_map.remove_if(&user_id, |_, entry| entry.connections.is_empty())
{
if let Some(stats) = self.topic_presence_stats.get(topic) {
let _ = stats.num_users.try_update(
Ordering::Relaxed,
Ordering::Relaxed,
|current| Some(current.saturating_sub(1)),
);
}
drop(topic_map);
self.remove_topic_if_empty(topic);
return UntrackResult::LastLeave {
user_id,
data: removed_entry.data,
};
}
// Only other nodes' sentinels left: this node's leave must still
// reach them, or each keeps this node's sentinel for good.
if removed_conn
&& let Some(entry) = topic_map.get(&user_id)
&& entry
.connections
.iter()
.all(|c| c.conn_id.starts_with(REMOTE_PREFIX))
{
return UntrackResult::LastLocalLeave {
user_id,
data: entry.data.clone(),
};
}
}
UntrackResult::StillPresent
}
/// Drop a topic's member map and counters once nobody is present in it;
/// otherwise every topic ever tracked keeps an empty map for the life of
/// the process. The counters go in the same critical section, so a
/// concurrent track() of the topic sees either both or neither. Never call
/// this while holding a guard into `topic_presence`.
fn remove_topic_if_empty(&self, topic: &str) {
self.topic_presence.remove_if(topic, |_, members| {
if members.is_empty() {
self.topic_presence_stats.remove(topic);
true
} else {
false
}
});
}
/// Untrack a connection from specific topics (called on unsubscribe).
pub fn untrack_topics(&self, conn_id: &str, topics: &[String]) -> Vec<(String, UntrackResult)> {
let mut results = Vec::new();
for topic in topics {
// Remove from conn_presence_topics tracking
if let Some(mut conn_topics) = self.conn_presence_topics.get_mut(conn_id) {
conn_topics.remove(topic);
}
let result = self.untrack_conn_from_topic(conn_id, topic);
results.push((topic.clone(), result));
}
results
}
/// Query all members in a topic.
/// Returns: Vec<(user_id, data, connection_count)>
pub fn query(&self, topic: &str) -> Vec<(String, serde_json::Value, usize)> {
let mut members = Vec::new();
if let Some(topic_map) = self.topic_presence.get(topic) {
for entry_ref in topic_map.iter() {
let entry = entry_ref.value();
members.push((
entry.user_id.clone(),
entry.data.clone(),
entry.connections.len(),
));
}
}
members
}
/// Get lightweight stats for a topic (O(1)).
pub fn stats(&self, topic: &str) -> (usize, usize) {
if let Some(stats) = self.topic_presence_stats.get(topic) {
(
stats.num_users.load(Ordering::Relaxed),
stats.num_connections.load(Ordering::Relaxed),
)
} else {
(0, 0)
}
}
/// Update presence data for a connection across all its topics.
/// Returns None on failure, Some((user_id, topics)) on success.
pub fn update_data(
&self,
conn_id: &str,
new_data: &serde_json::Value,
) -> Option<(String, Vec<String>)> {
// Validate size
let data_str = serde_json::to_string(new_data).unwrap_or_default();
if data_str.len() > self.max_data_size {
return None;
}
let user_id = self.conn_user_id.get(conn_id)?.value().clone();
let now = epoch_ms();
let mut updated_topics = Vec::new();
// Copy the topic list out first: holding this connection's entry while
// locking topic maps would take the two maps in the opposite order to
// track(), and on free-threaded Python the two calls can deadlock.
let topics: Vec<String> = match self.conn_presence_topics.get(conn_id) {
Some(topics) => topics.iter().cloned().collect(),
None => Vec::new(),
};
for topic in topics {
if let Some(topic_map) = self.topic_presence.get(&topic)
&& let Some(mut entry) = topic_map.get_mut(&user_id)
{
entry.data = new_data.clone();
entry.updated_at = now;
updated_topics.push(topic);
}
}
Some((user_id, updated_topics))
}
/// Get total presence-tracked topics count.
pub fn total_topics(&self) -> usize {
self.topic_presence.len()
}
/// Get total unique user count across all topics.
pub fn total_users(&self) -> usize {
self.topic_presence
.iter()
.map(|entry| entry.value().len())
.sum()
}
/// TTL sweep: remove presence entries where all connections are dead.
/// Returns list of (topic, user_id, data) for entries that were removed.
pub fn sweep_dead_connections<F>(
&self,
is_conn_alive: F,
) -> Vec<(String, String, serde_json::Value)>
where
F: Fn(&str) -> bool,
{
let mut removed = Vec::new();
let mut thinned_topics: Vec<String> = Vec::new();
for topic_entry in self.topic_presence.iter() {
let topic = topic_entry.key().clone();
let topic_map = topic_entry.value();
let mut dead_users = Vec::new();
for user_entry in topic_map.iter() {
let user_id = user_entry.key().clone();
let entry = user_entry.value();
let alive_count = entry
.connections
.iter()
.filter(|c| is_conn_alive(&c.conn_id))
.count();
if alive_count == 0 {
dead_users.push((user_id, entry.data.clone(), entry.connections.len()));
}
}
for (user_id, data, _dead_conn_count) in dead_users {
// Use remove_if to guard against concurrent track() adding a new conn
let actual_conn_count = if let Some((_, entry)) =
topic_map.remove_if(&user_id, |_, e| {
// Only remove if all connections are still dead
e.connections.iter().all(|c| !is_conn_alive(&c.conn_id))
}) {
// Only count connections whose tracking entry still exists.
// untrack_conn_from_topic may have already removed some and
// decremented num_connections for them -- avoid double-decrement.
let mut count = 0usize;
for conn in &entry.connections {
if self.conn_user_id.remove(&conn.conn_id).is_some() {
count += 1;
}
self.conn_presence_topics.remove(&conn.conn_id);
}
count
} else {
// Entry was either already removed or a live conn was added - skip
// But still clean up any dead local connections from the entry
if let Some(mut entry) = topic_map.get_mut(&user_id) {
let before = entry.connections.len();
entry.connections.retain(|c| {
c.conn_id.starts_with("__remote__") || is_conn_alive(&c.conn_id)
});
let removed_count = before - entry.connections.len();
if removed_count > 0
&& let Some(stats) = self.topic_presence_stats.get(&topic)
{
let _ = stats.num_connections.try_update(
Ordering::Relaxed,
Ordering::Relaxed,
|current| Some(current.saturating_sub(removed_count)),
);
}
}
0
};
// Only decrement stats and emit leave if the entry was actually removed
if actual_conn_count > 0 {
if let Some(stats) = self.topic_presence_stats.get(&topic) {
let _ = stats.num_users.try_update(
Ordering::Relaxed,
Ordering::Relaxed,
|current| Some(current.saturating_sub(1)),
);
let _ = stats.num_connections.try_update(
Ordering::Relaxed,
Ordering::Relaxed,
|current| Some(current.saturating_sub(actual_conn_count)),
);
}
removed.push((topic.clone(), user_id, data));
if thinned_topics.last() != Some(&topic) {
thinned_topics.push(topic.clone());
}
}
}
}
// After the iteration: removing map entries while iterating would wait
// on the iterator's own shard lock.
for topic in &thinned_topics {
self.remove_topic_if_empty(topic);
}
removed
}
// -----------------------------------------------------------------------
// Cluster presence sync: merge remote presence state
// -----------------------------------------------------------------------
/// Merge a remote join from a peer node. Does NOT emit events (caller handles broadcast).
/// `origin` is the reporting peer's address; the sentinel is keyed by it so
/// each peer contributes its own and a leave/disconnect from one peer cannot
/// erase a user still present on another. True when the user was not
/// present before: only then is it a join for local subscribers.
pub fn merge_remote_join(
&self,
topic: &str,
user_id: &str,
data: &serde_json::Value,
updated_at: u64,
origin: &str,
) -> bool {
self.merge_remote(topic, user_id, data, updated_at, updated_at, origin)
}
/// [`merge_remote_join`](Self::merge_remote_join), the user's data as of
/// `updated_at` (whichever node's clock last set it) and `origin`'s own
/// membership as of `joined_at` (its clock: its leaves compare with it).
fn merge_remote(
&self,
topic: &str,
user_id: &str,
data: &serde_json::Value,
updated_at: u64,
joined_at: u64,
origin: &str,
) -> bool {
// Validate remote data size (same limit as local track)
let data_str = data.to_string();
if data_str.len() > self.max_data_size {
tracing::warn!(
"[WSE-Presence] Rejecting oversized remote presence data ({} bytes, max {})",
data_str.len(),
self.max_data_size
);
return false;
}
let topic_map = self
.topic_presence
.entry(topic.to_owned())
.or_insert_with(new_topic_map);
// Enforce max_members limit for remote entries too
if self.max_members > 0
&& !topic_map.contains_key(user_id)
&& topic_map.len() >= self.max_members
{
tracing::warn!(
"[WSE-Presence] Rejecting remote join for {user_id}: topic at capacity ({})",
self.max_members
);
return false;
}
let mut entry = topic_map
.entry(user_id.to_owned())
.or_insert_with(|| PresenceEntry {
user_id: user_id.to_owned(),
data: data.clone(),
connections: Vec::new(),
updated_at,
});
// A user is "new" only if it had no connections at all before this join.
let user_was_new = entry.connections.is_empty();
// Last-write-wins: only update data if newer
if updated_at >= entry.updated_at {
entry.data = data.clone();
entry.updated_at = updated_at;
}
// Add THIS origin's sentinel so the user appears in presence queries.
// One sentinel per (origin, user): if the same peer re-announces, do not
// double-count; if another peer already reported the user, this adds a
// second sentinel so the user survives the first peer leaving.
let sentinel = remote_sentinel(origin, user_id);
match entry.connections.iter_mut().find(|c| c.conn_id == sentinel) {
Some(existing) => existing.joined_at = existing.joined_at.max(joined_at),
None => {
entry.connections.push(ConnMeta {
conn_id: sentinel,
joined_at,
});
let stats = self
.topic_presence_stats
.entry(topic.to_owned())
.or_insert_with(PresenceStats::new);
if user_was_new {
stats.num_users.fetch_add(1, Ordering::Relaxed);
}
stats.num_connections.fetch_add(1, Ordering::Relaxed);
}
}
user_was_new
}
/// Merge a remote leave from a peer node: drop that peer's sentinel, unless
/// the peer joined again after `updated_at` (the peer's own clock, so its
/// joins and leaves compare; a peer's frames arrive in order on its link).
/// Returns the user's data when the user is gone from the topic: only
/// then is it a leave for local subscribers.
pub fn merge_remote_leave(
&self,
topic: &str,
user_id: &str,
updated_at: u64,
origin: &str,
) -> Option<serde_json::Value> {
let topic_map = self.topic_presence.get(topic)?;
let sentinel = remote_sentinel(origin, user_id);
let emptied = {
let mut entry = topic_map.get_mut(user_id)?;
let joined_at = entry
.connections
.iter()
.find(|c| c.conn_id == sentinel)?
.joined_at;
if updated_at < joined_at {
return None;
}
entry.connections.retain(|c| c.conn_id != sentinel);
entry.connections.is_empty()
};
if let Some(stats) = self.topic_presence_stats.get(topic) {
let _ = stats
.num_connections
.try_update(Ordering::Relaxed, Ordering::Relaxed, |c| {
Some(c.saturating_sub(1))
});
}
if !emptied {
return None;
}
// remove_if: track() may have added a local connection meanwhile.
let (_, removed) = topic_map.remove_if(user_id, |_, entry| entry.connections.is_empty())?;
if let Some(stats) = self.topic_presence_stats.get(topic) {
let _ = stats
.num_users
.try_update(Ordering::Relaxed, Ordering::Relaxed, |c| {
Some(c.saturating_sub(1))
});
}
drop(topic_map);
self.remove_topic_if_empty(topic);
Some(removed.data)
}
/// Merge a remote data update (last-write-wins).
/// True when the update was newer and applied.
pub fn merge_remote_update(
&self,
topic: &str,
user_id: &str,
data: &serde_json::Value,
updated_at: u64,
) -> bool {
// Validate remote data size (same limit as local track)
let data_str = data.to_string();
if data_str.len() > self.max_data_size {
tracing::warn!(
"[WSE-Presence] Rejecting oversized remote presence update ({} bytes, max {})",
data_str.len(),
self.max_data_size
);
return false;
}
if let Some(topic_map) = self.topic_presence.get(topic)
&& let Some(mut entry) = topic_map.get_mut(user_id)
&& updated_at >= entry.updated_at
{
entry.data = data.clone();
entry.updated_at = updated_at;
return true;
}
false
}
/// Merge full presence state from a peer, as it comes (older nodes send
/// it so on connect).
/// Expected JSON format: {"topic": {"user_id": {"data": {...}, "updated_at": 123}}}
/// Returns (topic, user_id, data) of the users who were not present before.
pub fn merge_full_state(
&self,
entries_json: &str,
origin: &str,
) -> Vec<(String, String, serde_json::Value)> {
self.merge_entries(entries_json, origin, None)
}
/// Merge one frame of a sync round from `origin` like a full state, and
/// note each user it holds, per topic, in `held` for the round's end
/// (`retain_origin`).
pub fn merge_round_frame(
&self,
entries_json: &str,
origin: &str,
held: &mut HashMap<String, HashSet<String>>,
) -> Vec<(String, String, serde_json::Value)> {
self.merge_entries(entries_json, origin, Some(held))
}
fn merge_entries(
&self,
entries_json: &str,
origin: &str,
mut held: Option<&mut HashMap<String, HashSet<String>>>,
) -> Vec<(String, String, serde_json::Value)> {
let mut joined = Vec::new();
// Cap incoming full state to 10MB to prevent OOM
if entries_json.len() > 10_000_000 {
tracing::error!(
"[Presence] Full state too large ({} bytes, max 10MB), rejecting",
entries_json.len()
);
return joined;
}
let parsed: serde_json::Value = match serde_json::from_str(entries_json) {
Ok(v) => v,
Err(_) => return joined,
};
let topics = match parsed.as_object() {
Some(t) => t,
None => return joined,
};
for (topic, users_val) in topics {
let users = match users_val.as_object() {
Some(u) => u,
None => continue,
};
for (user_id, entry_val) in users {
let data = entry_val
.get("data")
.cloned()
.unwrap_or(serde_json::Value::Null);
let updated_at = entry_val
.get("updated_at")
.and_then(|v| v.as_u64())
.unwrap_or(0);
// The sender's membership on its own clock (a peer of an
// earlier version names none: the data's time).
let joined_at = entry_val
.get("joined_at")
.and_then(|v| v.as_u64())
.unwrap_or(updated_at);
if let Some(held) = held.as_deref_mut() {
held.entry(topic.clone())
.or_default()
.insert(user_id.clone());
}
if self.merge_remote(topic, user_id, &data, updated_at, joined_at, origin) {
joined.push((topic.clone(), user_id.clone(), data));
}
}
}
joined
}
/// Remove every presence sentinel contributed by `origin` -- called when a
/// cluster peer disconnects. Users left with no remaining connections are
/// dropped, so a crashed peer (which sends no per-user leave) cannot leave
/// "ghost" members present forever and drift membership counts upward.
/// Returns (topic, user_id, data) of the users gone with it.
pub fn purge_origin(&self, origin: &str) -> Vec<(String, String, serde_json::Value)> {
self.drop_where(&remote_origin_prefix(origin), |_, _| true)
}
/// Remove every peer's sentinels: this node is in no cluster any more.
/// Returns (topic, user_id, data) of the users gone with them.
pub fn purge_remote(&self) -> Vec<(String, String, serde_json::Value)> {
self.drop_where(REMOTE_PREFIX, |_, _| true)
}
/// The end of a sync round from `origin`: drop its sentinels of every
/// user the round did not hold (`held`, per topic), so a leave lost on
/// the way leaves no ghost. Returns (topic, user_id, data) of the users
/// gone with them.
pub fn retain_origin(
&self,
origin: &str,
held: &HashMap<String, HashSet<String>>,
) -> Vec<(String, String, serde_json::Value)> {
self.drop_where(&remote_origin_prefix(origin), |topic, user| {
!held.get(topic).is_some_and(|users| users.contains(user))
})
}
/// Drop the sentinels of `origin` for the users `gone(topic, user)`
/// names; users left with no connection are removed and returned.
/// Drops the sentinels whose ids start with `prefix`, of the users
/// `gone_user` names.
fn drop_where(
&self,
prefix: &str,
gone_user: impl Fn(&str, &str) -> bool,
) -> Vec<(String, String, serde_json::Value)> {
let mut thinned_topics: Vec<String> = Vec::new();
let mut gone = Vec::new();
for topic_entry in self.topic_presence.iter() {
let topic = topic_entry.key();
let topic_map = topic_entry.value();
let mut conns_removed: usize = 0;
let mut emptied_users: Vec<String> = Vec::new();
for mut user_entry in topic_map.iter_mut() {
if !gone_user(topic, user_entry.key()) {
continue;
}
let before = user_entry.connections.len();
user_entry
.connections
.retain(|c| !c.conn_id.starts_with(prefix));
let removed = before - user_entry.connections.len();
if removed > 0 {
conns_removed += removed;
if user_entry.connections.is_empty() {
emptied_users.push(user_entry.key().clone());
}
}
}
let mut users_removed: usize = 0;
for uid in emptied_users {
// remove_if guards against a concurrent local track() re-adding a
// connection between the iter_mut release and this removal.
if let Some((_, entry)) = topic_map.remove_if(&uid, |_, e| e.connections.is_empty())
{
users_removed += 1;
gone.push((topic.clone(), uid, entry.data));
}
}
if conns_removed > 0
&& let Some(stats) = self.topic_presence_stats.get(topic)
{
let _ =
stats
.num_connections
.try_update(Ordering::Relaxed, Ordering::Relaxed, |c| {
Some(c.saturating_sub(conns_removed))
});
if users_removed > 0 {
let _ = stats
.num_users
.try_update(Ordering::Relaxed, Ordering::Relaxed, |c| {
Some(c.saturating_sub(users_removed))
});
}
}
if users_removed > 0 {
thinned_topics.push(topic.clone());
}
}
for topic in &thinned_topics {
self.remove_topic_if_empty(topic);
}
gone
}
/// Serialize local presence state into one or more JSON chunks, each whose
/// serialized length stays within `max_payload_bytes`. Only entries with a
/// local connection are included (remote sentinels are not re-synced).
///
/// The receiver merges each chunk additively (per-user via merge_remote_join),
/// so several partial chunks reconstruct the same set as a single frame would;
/// sent as a sync round, the round's end also drops what none of its chunks
/// held. One frame for the whole state would be dropped once a busy node's
/// state passed the cluster frame limit, leaving a joining peer blind.
pub fn serialize_full_state_chunked(&self, max_payload_bytes: usize) -> Vec<String> {
let mut chunks: Vec<String> = Vec::new();
let mut current = serde_json::Map::new();
let mut est: usize = 2; // running estimate of current's serialized len ("{}")
for topic_entry in self.topic_presence.iter() {
let topic = topic_entry.key();
let topic_map = topic_entry.value();
for user_entry in topic_map.iter() {
let entry = user_entry.value();
// Only local entries (don't re-sync remote sentinels).
// Their membership on this node's own clock: the data's time
// may be another node's.
let Some(joined_at) = entry
.connections
.iter()
.filter(|c| !c.conn_id.starts_with(REMOTE_PREFIX))
.map(|c| c.joined_at)
.max()
else {
continue;
};
let value = serde_json::json!({
"data": entry.data,
"updated_at": entry.updated_at,
"joined_at": joined_at,
});
// Conservative per-user contribution: topic key + user key + value
// + JSON punctuation/quotes/nested braces.
let add_est = topic.len() + entry.user_id.len() + value.to_string().len() + 24;
// Flush the current chunk before it would exceed the budget (but
// never flush an empty chunk -- a single oversized user still goes
// out alone and is handled by encode_presence_full's own guard).
if est + add_est > max_payload_bytes && !current.is_empty() {
if let Ok(s) = serde_json::to_string(&serde_json::Value::Object(
std::mem::take(&mut current),
)) {
chunks.push(s);
}
est = 2;
}
if let Some(obj) = current
.entry(topic.clone())
.or_insert_with(|| serde_json::Value::Object(serde_json::Map::new()))
.as_object_mut()
{
obj.insert(entry.user_id.clone(), value);
}
est += add_est;
}
}
if !current.is_empty()
&& let Ok(s) = serde_json::to_string(&serde_json::Value::Object(current))
{
chunks.push(s);
}
chunks
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_leave_after_a_snapshot_counts_on_the_clock_of_the_node_that_sent_it() {
let a = PresenceManager::new(4096, 0);
a.register_connection("alice-a", "alice");
a.track("alice-a", "room", &serde_json::json!({"where": "a"}));
let now = epoch_ms();
// B's clock is a minute ahead: its join wins the user's data on A.
a.merge_remote_join(
"room",
"alice",
&serde_json::json!({"where": "b"}),
now + 60_000,
"B",
);
let c = PresenceManager::new(4096, 0);
for frame in a.serialize_full_state_chunked(1_000_000) {
c.merge_full_state(&frame, "A");
}
// A's last local connection leaves, on A's own clock.
a.remove_connection("alice-a");
let left = c.merge_remote_leave("room", "alice", epoch_ms(), "A");
assert!(left.is_some(), "C took A's leave");
assert!(c.query("room").is_empty());
}
#[test]
fn a_first_local_connection_of_a_user_present_elsewhere_is_no_new_join() {
let pm = PresenceManager::new(4096, 0);
pm.merge_remote_join("room", "alice", &serde_json::json!({}), epoch_ms(), "B");
pm.register_connection("alice-a", "alice");
let result = pm.track("alice-a", "room", &serde_json::json!({}));
// Peers hear of it, local subscribers do not: Alice was present.
assert!(matches!(result, TrackResult::FirstLocalJoin { .. }));
assert_eq!(pm.stats("room").0, 1);
}
fn data() -> serde_json::Value {
serde_json::json!({"status": "online"})
}
fn members(mgr: &PresenceManager, topic: &str) -> Vec<String> {
let mut users: Vec<String> = mgr.query(topic).into_iter().map(|m| m.0).collect();
users.sort();
users
}
// The user's last tab on this node closes while another node still has
// one: peers must hear this node's leave, local subscribers must not.
#[test]
fn the_last_local_leave_is_told_to_peers_only() {
let mgr = PresenceManager::new(4096, 0);
mgr.register_connection("c1", "alice");
assert!(matches!(
mgr.track("c1", "room", &data()),
TrackResult::FirstJoin { .. }
));
assert!(!mgr.merge_remote_join("room", "alice", &data(), 100, "peerB"));
let results = mgr.remove_connection("c1");
assert!(matches!(results[0].1, UntrackResult::LastLocalLeave { .. }));
assert_eq!(members(&mgr, "room"), ["alice"]);
// Then peerB's leave: now the user is gone, and that is the event.
assert_eq!(
mgr.merge_remote_leave("room", "alice", 200, "peerB"),
Some(data())
);
assert!(members(&mgr, "room").is_empty());
}
// A peer's leave is compared with that peer's own join, not with the
// newest write from anywhere (another node's clock, a local update).
#[test]
fn a_remote_leave_is_judged_by_its_own_peers_join() {
let mgr = PresenceManager::new(4096, 0);
mgr.merge_remote_join("room", "alice", &data(), 100, "peerB");
// A newer write from elsewhere moves the entry's own timestamp on.
mgr.merge_remote_join("room", "alice", &data(), 500, "peerC");
assert_eq!(mgr.merge_remote_leave("room", "alice", 150, "peerB"), None);
let entry_conns = mgr
.topic_presence
.get("room")
.unwrap()
.get("alice")
.unwrap()
.connections
.len();
assert_eq!(entry_conns, 1, "peerB's sentinel is gone, peerC's stays");
// A leave older than the peer's latest join is stale.
mgr.merge_remote_join("room", "bob", &data(), 300, "peerB");
assert_eq!(mgr.merge_remote_leave("room", "bob", 250, "peerB"), None);
assert_eq!(members(&mgr, "room"), ["alice", "bob"]);
}
#[test]
fn remote_merges_report_what_changed() {
let mgr = PresenceManager::new(4096, 0);
assert!(mgr.merge_remote_join("room", "alice", &data(), 100, "peerB"));
assert!(!mgr.merge_remote_join("room", "alice", &data(), 101, "peerC"));
assert!(mgr.merge_remote_update("room", "alice", &serde_json::json!({"s": 1}), 200));
assert!(!mgr.merge_remote_update("room", "alice", &serde_json::json!({"s": 0}), 150));
let full = r#"{"room": {"alice": {"data": {}, "updated_at": 1}, "carol": {"data": {}, "updated_at": 1}}}"#;
let joined = mgr.merge_full_state(full, "peerD");
assert_eq!(joined.len(), 1);
assert_eq!(joined[0].1, "carol");
let gone = mgr.purge_origin("peerD");
assert_eq!(
gone.iter().map(|g| g.1.as_str()).collect::<Vec<_>>(),
["carol"]
);
assert_eq!(members(&mgr, "room"), ["alice"]);
}
// Per-origin sentinels: a leave from one peer must not erase a user
// still present on another peer.
#[test]
fn per_origin_sentinel_survives_other_peers_leave() {
let mgr = PresenceManager::new(4096, 0);
mgr.merge_remote_join("room", "alice", &data(), 100, "peerA");
mgr.merge_remote_join("room", "alice", &data(), 100, "peerB");
// peerA reports alice leaving; peerB's sentinel must remain.
mgr.merge_remote_leave("room", "alice", 101, "peerA");
let topic_map = mgr.topic_presence.get("room").expect("topic exists");
let entry = topic_map.get("alice").expect("alice still present");
assert_eq!(entry.connections.len(), 1, "only peerB sentinel remains");
assert!(entry.connections[0].conn_id.contains("peerB"));
}
// Last write wins: a stale (reordered) leave must not remove a user
// whose newer re-join already landed.
#[test]
fn lww_ignores_stale_leave() {
let mgr = PresenceManager::new(4096, 0);
// Re-join applied at t=102 before the older leave (t=101) arrives.
mgr.merge_remote_join("room", "bob", &data(), 102, "peerA");
mgr.merge_remote_leave("room", "bob", 101, "peerA");
let topic_map = mgr.topic_presence.get("room").expect("topic exists");
assert!(
topic_map.contains_key("bob"),
"a stale leave must not remove a user that re-joined later"
);
}
// Ghost cleanup: purge_origin removes only the crashed peer's
// sentinels and the users left with no connections.
#[test]
fn purge_origin_removes_only_that_peers_ghosts() {
let mgr = PresenceManager::new(4096, 0);
mgr.merge_remote_join("room", "alice", &data(), 10, "peerA");
mgr.merge_remote_join("room", "bob", &data(), 10, "peerB");
mgr.merge_remote_join("room", "carol", &data(), 10, "peerA");
mgr.purge_origin("peerA");
let topic_map = mgr.topic_presence.get("room").expect("topic exists");
assert!(!topic_map.contains_key("alice"), "peerA ghost removed");
assert!(!topic_map.contains_key("carol"), "peerA ghost removed");
assert!(topic_map.contains_key("bob"), "peerB user retained");
let stats = mgr.topic_presence_stats.get("room").expect("stats exist");
assert_eq!(stats.num_users.load(Ordering::Relaxed), 1);
assert_eq!(stats.num_connections.load(Ordering::Relaxed), 1);
}
#[test]
fn out_of_the_cluster_only_this_nodes_members_stay() {
let mgr = PresenceManager::new(4096, 0);
mgr.merge_remote_join("room", "alice", &data(), 10, "peerA");
mgr.merge_remote_join("room", "bob", &data(), 10, "peerB");
mgr.register_connection("c1", "carol");
mgr.track("c1", "room", &data());
let mut gone: Vec<String> = mgr.purge_remote().into_iter().map(|(_, u, _)| u).collect();
gone.sort();
assert_eq!(gone, ["alice", "bob"]);
let members: Vec<String> = mgr.query("room").into_iter().map(|(u, _, _)| u).collect();
assert_eq!(members, ["carol"]);
let stats = mgr.topic_presence_stats.get("room").expect("stats exist");
assert_eq!(stats.num_users.load(Ordering::Relaxed), 1);
}
// A user present on two peers survives purge of one of them.
#[test]
fn purge_origin_keeps_user_present_on_another_peer() {
let mgr = PresenceManager::new(4096, 0);
mgr.merge_remote_join("room", "dave", &data(), 10, "peerA");
mgr.merge_remote_join("room", "dave", &data(), 10, "peerB");
mgr.purge_origin("peerA");
let topic_map = mgr.topic_presence.get("room").expect("topic exists");
let entry = topic_map.get("dave").expect("dave retained");
assert_eq!(entry.connections.len(), 1, "only peerB sentinel remains");
assert!(entry.connections[0].conn_id.contains("peerB"));
let stats = mgr.topic_presence_stats.get("room").expect("stats exist");
assert_eq!(stats.num_users.load(Ordering::Relaxed), 1);
assert_eq!(stats.num_connections.load(Ordering::Relaxed), 1);
}
// A sync round keeps of its origin exactly what it held: a leave lost on
// the way leaves no ghost, and a user also on another peer stays.
#[test]
fn a_sync_round_drops_what_it_did_not_hold() {
let mgr = PresenceManager::new(4096, 0);
for user in ["alice", "bob", "dave"] {
mgr.merge_remote_join("room", user, &data(), 10, "peerA");
}
mgr.merge_remote_join("lobby", "carol", &data(), 10, "peerA");
mgr.merge_remote_join("room", "dave", &data(), 10, "peerB");
// peerA's round in two frames: alice, and erin who is new.
let mut held = HashMap::new();
let first = r#"{"room": {"alice": {"data": {}, "updated_at": 20}}}"#;
assert!(mgr.merge_round_frame(first, "peerA", &mut held).is_empty());
let last = r#"{"room": {"erin": {"data": {}, "updated_at": 20}}}"#;
let joined = mgr.merge_round_frame(last, "peerA", &mut held);
assert_eq!(
joined.iter().map(|j| j.1.as_str()).collect::<Vec<_>>(),
["erin"]
);
let mut gone: Vec<String> = mgr
.retain_origin("peerA", &held)
.into_iter()
.map(|(topic, user, _)| format!("{topic}/{user}"))
.collect();
gone.sort();
assert_eq!(gone, ["lobby/carol", "room/bob"]);
assert_eq!(members(&mgr, "room"), ["alice", "dave", "erin"]);
let room = mgr.topic_presence.get("room").expect("room");
let dave = room.get("dave").expect("dave stays on peerB");
assert_eq!(dave.connections.len(), 1);
assert!(dave.connections[0].conn_id.contains("peerB"));
assert!(mgr.topic_presence.get("lobby").is_none());
}
// Full-state sync is chunked, so a node with more presence than fits in one
// frame still sends all of it.
#[test]
fn full_state_chunked_covers_all_users_and_splits() {
let mgr = PresenceManager::new(4096, 0);
let d = data();
for i in 0..6 {
let conn = format!("conn{i}");
let uid = format!("user{i}");
mgr.register_connection(&conn, &uid);
mgr.track(&conn, "room", &d);
}
// Huge limit -> a single chunk with all six users.
let one = mgr.serialize_full_state_chunked(1_000_000);
assert_eq!(one.len(), 1, "everything fits in one chunk");
let parsed: serde_json::Value = serde_json::from_str(&one[0]).expect("valid JSON");
assert_eq!(parsed["room"].as_object().expect("room obj").len(), 6);
// Tiny limit -> multiple chunks whose union still covers all six users,
// each chunk independently valid JSON the receiver can merge additively.
let many = mgr.serialize_full_state_chunked(60);
assert!(many.len() > 1, "a small budget splits into multiple chunks");
let mut seen = std::collections::HashSet::new();
for chunk in &many {
let v: serde_json::Value =
serde_json::from_str(chunk).expect("each chunk is valid JSON");
for users in v.as_object().expect("obj").values() {
for uid in users.as_object().expect("users obj").keys() {
seen.insert(uid.clone());
}
}
}
assert_eq!(seen.len(), 6, "every user appears in some chunk");
}
#[test]
fn empty_topics_are_dropped_with_their_counters() {
let mgr = PresenceManager::new(4096, 0);
mgr.register_connection("c1", "u1");
mgr.track("c1", "room:1", &data());
mgr.track("c1", "room:2", &data());
assert_eq!(mgr.total_topics(), 2);
mgr.untrack_topics("c1", &["room:1".to_string()]);
assert_eq!(mgr.total_topics(), 1);
mgr.remove_connection("c1");
assert_eq!(mgr.total_topics(), 0);
assert_eq!(mgr.stats("room:2"), (0, 0));
assert!(mgr.topic_presence_stats.is_empty());
}
#[test]
fn track_and_update_data_do_not_deadlock() {
use std::sync::{Arc, mpsc};
use std::time::Duration;
let mgr = Arc::new(PresenceManager::new(4096, 0));
mgr.register_connection("c1", "u1");
let (done_tx, done_rx) = mpsc::channel();
let workers: Vec<_> = (0..4)
.map(|i| {
let mgr = Arc::clone(&mgr);
let done_tx = done_tx.clone();
std::thread::spawn(move || {
for n in 0..2000 {
if i % 2 == 0 {
mgr.track("c1", &format!("room:{}", n % 8), &data());
} else {
mgr.update_data("c1", &data());
}
}
done_tx.send(()).unwrap();
})
})
.collect();
for _ in 0..4 {
done_rx
.recv_timeout(Duration::from_secs(30))
.expect("track() and update_data() deadlocked");
}
for worker in workers {
worker.join().unwrap();
}
}
}