acton-reactive 9.3.0

Acton Reactive is the main crate of the Acton framework, designed for building reactive, event-driven, and asynchronous systems. It provides intuitive abstractions to make working with distributed actors seamless and efficient.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
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
/*
 * Copyright (c) 2024. Govcraft
 *
 * Licensed under either of
 *   * Apache License, Version 2.0 (the "License");
 *     you may not use this file except in compliance with the License.
 *     You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
 *   * MIT license: http://opensource.org/licenses/MIT
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the applicable License for the specific language governing permissions and
 * limitations under that License.
 */

//! Subscription manager for IPC broker forwarding.
//!
//! This module tracks which IPC connections are subscribed to which message types,
//! allowing the IPC listener to forward broker broadcasts to interested clients.

use std::any::TypeId;
use std::collections::{HashMap, HashSet};
use std::sync::atomic::{AtomicUsize, Ordering};

use parking_lot::RwLock;
use std::sync::Arc;
use tokio::sync::mpsc;
use tracing::{trace, warn};

use super::types::IpcPushNotification;

/// Unique identifier for an IPC connection.
pub type ConnectionId = usize;

/// Channel sender for pushing notifications to a connection.
pub type PushSender = mpsc::Sender<IpcPushNotification>;

/// A case-sensitive IPC name prefix selector ending in exactly one `*`.
///
/// `*` matches every IPC name. All characters before the final star are literal,
/// including separators, question marks, and brackets. Selectors are limited to
/// 256 UTF-8 bytes. Exact subscriptions retain their literal semantics.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct SubscriptionPattern(String);

impl SubscriptionPattern {
    /// Returns the original selector.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// Tests an IPC name against this selector.
    #[must_use]
    pub fn matches(&self, name: &str) -> bool {
        name.starts_with(&self.0[..self.0.len() - 1])
    }
}

impl std::fmt::Display for SubscriptionPattern {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.as_str())
    }
}

impl TryFrom<String> for SubscriptionPattern {
    type Error = PatternSubscriptionError;

    fn try_from(value: String) -> Result<Self, Self::Error> {
        if value.len() > 256 {
            return Err(PatternSubscriptionError::PatternTooLong);
        }
        let Some(prefix) = value.strip_suffix('*') else {
            return Err(PatternSubscriptionError::InvalidPattern);
        };
        if prefix.contains('*') {
            return Err(PatternSubscriptionError::InvalidPattern);
        }
        Ok(Self(value))
    }
}

impl std::str::FromStr for SubscriptionPattern {
    type Err = PatternSubscriptionError;

    fn from_str(value: &str) -> Result<Self, Self::Err> {
        Self::try_from(value.to_owned())
    }
}

/// Failure to validate or apply a pattern subscription batch.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum PatternSubscriptionError {
    /// A selector must end in exactly one wildcard.
    InvalidPattern,
    /// A selector exceeds 256 UTF-8 bytes.
    PatternTooLong,
    /// A request or a connection exceeds the limit of 128 patterns.
    TooManyPatterns,
    /// The connection has not been registered.
    UnknownConnection,
}

impl std::fmt::Display for PatternSubscriptionError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(match self {
            Self::InvalidPattern => "pattern must contain exactly one terminal '*'",
            Self::PatternTooLong => "pattern exceeds 256 UTF-8 bytes",
            Self::TooManyPatterns => "pattern limit of 128 exceeded",
            Self::UnknownConnection => "connection is not registered",
        })
    }
}

impl std::error::Error for PatternSubscriptionError {}

fn validate_patterns(
    values: &[String],
) -> Result<HashSet<SubscriptionPattern>, PatternSubscriptionError> {
    if values.len() > 128 {
        return Err(PatternSubscriptionError::TooManyPatterns);
    }
    values.iter().map(|value| value.parse()).collect()
}

/// Credentials of the process on the other end of a Unix socket connection.
///
/// Supplied by the kernel when the connection is accepted, so they cannot be
/// forged by the peer. Applications can use them to make connection-level
/// authentication and access-control decisions.
///
/// # Choosing between the fields
///
/// Prefer [`uid`](Self::uid) and [`gid`](Self::gid) for authorization. A PID
/// identifies a process only for as long as that process lives: PIDs are
/// recycled, so a check that reads a PID and then acts on it can be defeated by
/// the original process exiting and its number being reused. The user and group
/// ids are fixed for the life of the connection and are the sound basis for a
/// policy decision. [`pid`](Self::pid) is best treated as a diagnostic — it is
/// what lets a log line name the process that connected.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct PeerCredentials {
    /// Process ID of the peer, when the platform reported one.
    pid: Option<u32>,
    /// User ID of the peer.
    uid: u32,
    /// Group ID of the peer.
    gid: u32,
}

impl PeerCredentials {
    /// Build credentials from the raw values the platform reports.
    ///
    /// `pid` is signed at the OS level; a value that cannot be represented as a
    /// `u32` (a negative placeholder) is treated as "no PID reported" rather
    /// than being coerced into a nonsensical number.
    pub(crate) fn from_raw(pid: Option<i32>, uid: u32, gid: u32) -> Self {
        Self {
            pid: pid.and_then(|pid| u32::try_from(pid).ok()),
            uid,
            gid,
        }
    }

    /// Process ID of the peer, if the platform reported one.
    ///
    /// See the type-level note on why this is a diagnostic rather than an
    /// authorization primitive.
    #[must_use]
    pub const fn pid(self) -> Option<u32> {
        self.pid
    }

    /// User ID of the peer.
    #[must_use]
    pub const fn uid(self) -> u32 {
        self.uid
    }

    /// Group ID of the peer.
    #[must_use]
    pub const fn gid(self) -> u32 {
        self.gid
    }
}

impl std::fmt::Display for PeerCredentials {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self.pid {
            Some(pid) => write!(f, "pid={pid} uid={} gid={}", self.uid, self.gid),
            None => write!(f, "pid=unknown uid={} gid={}", self.uid, self.gid),
        }
    }
}

/// Statistics for the subscription manager.
#[derive(Debug, Default)]
pub struct SubscriptionStats {
    /// Total subscriptions added.
    pub subscriptions_added: AtomicUsize,
    /// Total subscriptions removed.
    pub subscriptions_removed: AtomicUsize,
    /// Total push notifications sent.
    pub push_notifications_sent: AtomicUsize,
    /// Total push notifications dropped (channel full or closed).
    pub push_notifications_dropped: AtomicUsize,
}

impl SubscriptionStats {
    /// Get the number of subscriptions added.
    #[must_use]
    pub fn subscriptions_added(&self) -> usize {
        self.subscriptions_added.load(Ordering::Relaxed)
    }

    /// Get the number of subscriptions removed.
    #[must_use]
    pub fn subscriptions_removed(&self) -> usize {
        self.subscriptions_removed.load(Ordering::Relaxed)
    }

    /// Get the number of push notifications sent.
    #[must_use]
    pub fn push_notifications_sent(&self) -> usize {
        self.push_notifications_sent.load(Ordering::Relaxed)
    }

    /// Get the number of push notifications dropped.
    #[must_use]
    pub fn push_notifications_dropped(&self) -> usize {
        self.push_notifications_dropped.load(Ordering::Relaxed)
    }
}

/// Information about a subscribed connection.
struct ConnectionInfo {
    /// Channel for sending push notifications to this connection.
    push_sender: PushSender,
    /// Set of message type names this connection is subscribed to.
    subscribed_types: HashSet<String>,
    subscribed_patterns: HashSet<SubscriptionPattern>,
    /// Credentials of the process behind this connection, when the platform
    /// reported them.
    peer: Option<PeerCredentials>,
}

/// Manages IPC connection subscriptions for broker forwarding.
///
/// This struct tracks which connections are subscribed to which message types
/// and provides methods to efficiently forward broker broadcasts to interested
/// connections.
///
/// # Thread Safety
///
/// This struct is designed to be shared across multiple tasks using `Arc`.
/// All operations are thread-safe.
pub struct SubscriptionManager {
    // Lock order: state, then routes. Keep state locked through cache use and
    // nonblocking delivery so completed mutations cannot leave stale routes.
    state: RwLock<SubscriptionState>,
    routes: RwLock<HashMap<String, Arc<[ConnectionId]>>>,
    type_id_to_name: RwLock<HashMap<TypeId, String>>,
    stats: SubscriptionStats,
}

#[derive(Default)]
struct SubscriptionState {
    connections: HashMap<ConnectionId, ConnectionInfo>,
    exact: HashMap<String, HashSet<ConnectionId>>,
    patterns: HashMap<SubscriptionPattern, HashSet<ConnectionId>>,
}

fn remove_index<K: Eq + std::hash::Hash>(
    index: &mut HashMap<K, HashSet<ConnectionId>>,
    key: &K,
    id: ConnectionId,
) {
    if let Some(ids) = index.get_mut(key) {
        ids.remove(&id);
        if ids.is_empty() {
            index.remove(key);
        }
    }
}

impl SubscriptionState {
    fn remove_connection(&mut self, id: ConnectionId) -> usize {
        let Some(info) = self.connections.remove(&id) else {
            return 0;
        };
        for name in &info.subscribed_types {
            remove_index(&mut self.exact, name, id);
        }
        for pattern in &info.subscribed_patterns {
            remove_index(&mut self.patterns, pattern, id);
        }
        info.subscribed_types.len() + info.subscribed_patterns.len()
    }
}

impl Default for SubscriptionManager {
    fn default() -> Self {
        Self::new()
    }
}

impl std::fmt::Debug for SubscriptionManager {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let state = self.state.read();
        f.debug_struct("SubscriptionManager")
            .field("connection_count", &state.connections.len())
            .field("subscribed_types_count", &state.exact.len())
            .field("subscribed_patterns_count", &state.patterns.len())
            .field("cached_routes", &self.routes.read().len())
            .field("type_id_mappings", &self.type_id_to_name.read().len())
            .field("stats", &self.stats)
            .finish()
    }
}

impl SubscriptionManager {
    /// Creates a new subscription manager.
    #[must_use]
    pub fn new() -> Self {
        Self {
            state: RwLock::new(SubscriptionState::default()),
            routes: RwLock::new(HashMap::new()),
            type_id_to_name: RwLock::new(HashMap::new()),
            stats: SubscriptionStats::default(),
        }
    }

    /// Returns a reference to the statistics, counting exact and pattern selectors.
    #[must_use]
    pub const fn stats(&self) -> &SubscriptionStats {
        &self.stats
    }

    /// Registers a connection and its kernel-reported peer credentials.
    /// Replacing an existing connection removes all its subscriptions.
    pub fn register_connection(
        &self,
        conn_id: ConnectionId,
        push_sender: PushSender,
        peer: Option<PeerCredentials>,
    ) {
        let mut state = self.state.write();
        let removed = state.remove_connection(conn_id);
        self.stats
            .subscriptions_removed
            .fetch_add(removed, Ordering::Relaxed);
        state.connections.insert(
            conn_id,
            ConnectionInfo {
                push_sender,
                peer,
                subscribed_types: HashSet::new(),
                subscribed_patterns: HashSet::new(),
            },
        );
        self.routes.write().clear();
        drop(state);
    }

    /// Returns kernel-reported credentials, or `None` for unknown connections.
    #[must_use]
    pub fn peer_credentials(&self, conn_id: ConnectionId) -> Option<PeerCredentials> {
        self.state
            .read()
            .connections
            .get(&conn_id)
            .and_then(|info| info.peer)
    }

    /// Returns the peer process ID, a diagnostic rather than an authorization primitive.
    #[must_use]
    pub fn peer_pid(&self, conn_id: ConnectionId) -> Option<u32> {
        self.peer_credentials(conn_id)
            .and_then(PeerCredentials::pid)
    }

    /// Unregisters a connection, removing all exact and pattern subscriptions.
    pub fn unregister_connection(&self, conn_id: ConnectionId) {
        let mut state = self.state.write();
        let removed = state.remove_connection(conn_id);
        self.stats
            .subscriptions_removed
            .fetch_add(removed, Ordering::Relaxed);
        self.routes.write().clear();
        drop(state);
    }

    /// Adds literal message type names and returns the current exact subscriptions.
    pub fn subscribe(&self, conn_id: ConnectionId, message_types: &[String]) -> Vec<String> {
        let mut state = self.state.write();
        let SubscriptionState {
            connections, exact, ..
        } = &mut *state;
        let Some(info) = connections.get_mut(&conn_id) else {
            return Vec::new();
        };
        for name in message_types {
            if info.subscribed_types.insert(name.clone()) {
                exact.entry(name.clone()).or_default().insert(conn_id);
                self.stats
                    .subscriptions_added
                    .fetch_add(1, Ordering::Relaxed);
            }
        }
        self.routes.write().clear();
        let subscriptions = info.subscribed_types.iter().cloned().collect();
        drop(state);
        subscriptions
    }

    /// Removes literal subscriptions and returns remaining exact subscriptions.
    /// An empty batch removes both exact and pattern subscriptions.
    pub fn unsubscribe(&self, conn_id: ConnectionId, message_types: &[String]) -> Vec<String> {
        let mut state = self.state.write();
        let SubscriptionState {
            connections,
            exact,
            patterns,
        } = &mut *state;
        let Some(info) = connections.get_mut(&conn_id) else {
            return Vec::new();
        };
        let names = if message_types.is_empty() {
            for pattern in info.subscribed_patterns.drain() {
                remove_index(patterns, &pattern, conn_id);
                self.stats
                    .subscriptions_removed
                    .fetch_add(1, Ordering::Relaxed);
            }
            info.subscribed_types.iter().cloned().collect::<Vec<_>>()
        } else {
            message_types.to_vec()
        };
        for name in names {
            if info.subscribed_types.remove(&name) {
                remove_index(exact, &name, conn_id);
                self.stats
                    .subscriptions_removed
                    .fetch_add(1, Ordering::Relaxed);
            }
        }
        self.routes.write().clear();
        let subscriptions = info.subscribed_types.iter().cloned().collect();
        drop(state);
        subscriptions
    }

    /// Atomically adds validated selectors and returns all current patterns sorted.
    ///
    /// Each request and each connection may contain at most 128 patterns.
    /// Selectors match future IPC names automatically. Overlapping selectors and
    /// exact subscriptions deliver only one notification per broadcast.
    ///
    /// # Errors
    /// Returns an error for invalid selectors, exceeded limits, or unknown connections.
    /// No subscriptions are changed on error.
    pub fn subscribe_patterns(
        &self,
        conn_id: ConnectionId,
        values: &[String],
    ) -> Result<Vec<String>, PatternSubscriptionError> {
        let validated = validate_patterns(values)?;
        let mut state = self.state.write();
        let SubscriptionState {
            connections,
            patterns,
            ..
        } = &mut *state;
        let info = connections
            .get_mut(&conn_id)
            .ok_or(PatternSubscriptionError::UnknownConnection)?;
        if info.subscribed_patterns.union(&validated).count() > 128 {
            return Err(PatternSubscriptionError::TooManyPatterns);
        }
        for pattern in validated {
            if info.subscribed_patterns.insert(pattern.clone()) {
                patterns.entry(pattern).or_default().insert(conn_id);
                self.stats
                    .subscriptions_added
                    .fetch_add(1, Ordering::Relaxed);
            }
        }
        self.routes.write().clear();
        let subscriptions = sorted_patterns(&info.subscribed_patterns);
        drop(state);
        Ok(subscriptions)
    }

    /// Atomically removes the specified pattern selectors, returning remaining patterns sorted.
    /// An empty batch removes all patterns while preserving exact subscriptions.
    ///
    /// # Errors
    /// Returns an error for invalid selectors, exceeded request limits, or unknown connections.
    /// No subscriptions are changed on error.
    pub fn unsubscribe_patterns(
        &self,
        conn_id: ConnectionId,
        values: &[String],
    ) -> Result<Vec<String>, PatternSubscriptionError> {
        let validated = validate_patterns(values)?;
        let mut state = self.state.write();
        let SubscriptionState {
            connections,
            patterns,
            ..
        } = &mut *state;
        let info = connections
            .get_mut(&conn_id)
            .ok_or(PatternSubscriptionError::UnknownConnection)?;
        let selected = if values.is_empty() {
            info.subscribed_patterns.clone()
        } else {
            validated
        };
        for pattern in selected {
            if info.subscribed_patterns.remove(&pattern) {
                remove_index(patterns, &pattern, conn_id);
                self.stats
                    .subscriptions_removed
                    .fetch_add(1, Ordering::Relaxed);
            }
        }
        self.routes.write().clear();
        let subscriptions = sorted_patterns(&info.subscribed_patterns);
        drop(state);
        Ok(subscriptions)
    }

    /// Returns the connection's exact subscriptions.
    #[must_use]
    pub fn get_subscriptions(&self, conn_id: ConnectionId) -> Vec<String> {
        self.state
            .read()
            .connections
            .get(&conn_id)
            .map(|info| info.subscribed_types.iter().cloned().collect())
            .unwrap_or_default()
    }

    /// Returns the connection's pattern selectors in sorted order.
    #[must_use]
    pub fn get_pattern_subscriptions(&self, conn_id: ConnectionId) -> Vec<String> {
        self.state
            .read()
            .connections
            .get(&conn_id)
            .map(|info| sorted_patterns(&info.subscribed_patterns))
            .unwrap_or_default()
    }

    /// Returns whether a connection has any exact or pattern subscriptions.
    #[must_use]
    pub fn has_subscriptions(&self, conn_id: ConnectionId) -> bool {
        self.state
            .read()
            .connections
            .get(&conn_id)
            .is_some_and(|info| {
                !info.subscribed_types.is_empty() || !info.subscribed_patterns.is_empty()
            })
    }

    /// Registers the IPC name used for an internal broker message type.
    pub fn register_type_mapping(&self, type_id: TypeId, type_name: String) {
        self.type_id_to_name.write().insert(type_id, type_name);
    }

    /// Returns the IPC name for an internal message type.
    #[must_use]
    pub fn get_type_name(&self, type_id: &TypeId) -> Option<String> {
        self.type_id_to_name.read().get(type_id).cloned()
    }

    fn recipients(&self, state: &SubscriptionState, name: &str) -> Arc<[ConnectionId]> {
        if let Some(ids) = self.routes.read().get(name) {
            return Arc::clone(ids);
        }
        let mut ids = state.exact.get(name).cloned().unwrap_or_default();
        for (pattern, subscribers) in &state.patterns {
            if pattern.matches(name) {
                ids.extend(subscribers);
            }
        }
        let ids: Arc<[ConnectionId]> = ids.into_iter().collect();
        if name.len() <= 256 {
            let mut routes = self.routes.write();
            if routes.len() >= 1024 && !routes.contains_key(name) {
                if let Some(evicted) = routes.keys().next().cloned() {
                    routes.remove(&evicted);
                }
            }
            routes.insert(name.to_owned(), Arc::clone(&ids));
        }
        ids
    }

    /// Forwards once to each connection matching an exact name or pattern.
    ///
    /// Resolved recipient sets (including empty sets) are memoized for up to
    /// 1024 names of at most 256 bytes, and invalidated atomically on mutation.
    /// Full or closed queues drop notifications rather than blocking delivery.
    pub fn forward_to_subscribers(&self, notification: &IpcPushNotification) {
        let state = self.state.read();
        let ids = self.recipients(&state, &notification.message_type);
        for conn_id in ids.iter() {
            if let Some(info) = state.connections.get(conn_id) {
                match info.push_sender.try_send(notification.clone()) {
                    Ok(()) => {
                        self.stats
                            .push_notifications_sent
                            .fetch_add(1, Ordering::Relaxed);
                    }
                    Err(mpsc::error::TrySendError::Full(_)) => {
                        self.stats
                            .push_notifications_dropped
                            .fetch_add(1, Ordering::Relaxed);
                        warn!(conn_id, message_type = %notification.message_type, "Push channel full, dropping notification");
                    }
                    Err(mpsc::error::TrySendError::Closed(_)) => {
                        self.stats
                            .push_notifications_dropped
                            .fetch_add(1, Ordering::Relaxed);
                        trace!(conn_id, "Push channel closed");
                    }
                }
            }
        }
    }

    /// Returns the number of registered connections.
    #[must_use]
    pub fn connection_count(&self) -> usize {
        self.state.read().connections.len()
    }

    /// Returns the number of distinct exact names with active subscriptions.
    #[must_use]
    pub fn subscribed_types_count(&self) -> usize {
        self.state.read().exact.len()
    }

    /// Returns the number of distinct active pattern selectors.
    #[must_use]
    pub fn subscribed_patterns_count(&self) -> usize {
        self.state.read().patterns.len()
    }

    /// Returns the total number of exact and pattern subscriptions across connections.
    #[must_use]
    pub fn total_subscriptions(&self) -> usize {
        let state = self.state.read();
        state.exact.values().map(HashSet::len).sum::<usize>()
            + state.patterns.values().map(HashSet::len).sum::<usize>()
    }
}

fn sorted_patterns(patterns: &HashSet<SubscriptionPattern>) -> Vec<String> {
    let mut values: Vec<_> = patterns.iter().map(ToString::to_string).collect();
    values.sort();
    values
}

/// A handle for sending push notifications to a specific connection.
///
/// This is given to the push notification forwarding task so it can
/// receive notifications and write them to the connection's stream.
pub struct PushReceiver {
    /// The connection ID, useful for debugging and logging.
    #[allow(dead_code)]
    pub conn_id: ConnectionId,
    /// The receiver for push notifications.
    pub receiver: mpsc::Receiver<IpcPushNotification>,
}

/// Creates a push notification channel for a connection.
///
/// Returns a sender (for the subscription manager) and a receiver (for the connection handler).
#[must_use]
pub fn create_push_channel(
    conn_id: ConnectionId,
    buffer_size: usize,
) -> (PushSender, PushReceiver) {
    let (sender, receiver) = mpsc::channel(buffer_size);
    (sender, PushReceiver { conn_id, receiver })
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::Arc;

    #[test]
    fn test_subscription_manager_new() {
        let manager = SubscriptionManager::new();
        assert_eq!(manager.connection_count(), 0);
        assert_eq!(manager.subscribed_types_count(), 0);
    }

    #[test]
    fn test_register_unregister_connection() {
        let manager = SubscriptionManager::new();
        let (sender, _receiver) = mpsc::channel(10);

        manager.register_connection(1, sender, None);
        assert_eq!(manager.connection_count(), 1);

        manager.unregister_connection(1);
        assert_eq!(manager.connection_count(), 0);
    }

    // ------------------------------------------------------------------
    // Peer credentials (issue #5)
    // ------------------------------------------------------------------

    #[test]
    fn a_reported_pid_is_carried_through() {
        let creds = PeerCredentials::from_raw(Some(4321), 1000, 1000);

        assert_eq!(creds.pid(), Some(4321));
        assert_eq!(creds.uid(), 1000);
        assert_eq!(creds.gid(), 1000);
    }

    /// A negative PID is a placeholder, not a process. Coercing it would invent
    /// a plausible-looking but wrong process id.
    #[test]
    fn a_negative_pid_is_treated_as_unreported() {
        let creds = PeerCredentials::from_raw(Some(-1), 1000, 1000);

        assert_eq!(creds.pid(), None);
        assert_eq!(creds.uid(), 1000, "uid survives an unusable pid");
    }

    #[test]
    fn an_absent_pid_stays_absent() {
        assert_eq!(PeerCredentials::from_raw(None, 0, 0).pid(), None);
    }

    #[test]
    fn root_credentials_are_representable() {
        let creds = PeerCredentials::from_raw(Some(1), 0, 0);

        assert_eq!(creds.pid(), Some(1));
        assert_eq!(creds.uid(), 0);
        assert_eq!(creds.gid(), 0);
    }

    #[test]
    fn credentials_render_for_logs() {
        assert_eq!(
            PeerCredentials::from_raw(Some(7), 1000, 20).to_string(),
            "pid=7 uid=1000 gid=20"
        );
        assert_eq!(
            PeerCredentials::from_raw(None, 1000, 20).to_string(),
            "pid=unknown uid=1000 gid=20"
        );
    }

    #[test]
    fn a_registered_connection_reports_its_peer() {
        let manager = SubscriptionManager::new();
        let (sender, _receiver) = mpsc::channel(10);
        let creds = PeerCredentials::from_raw(Some(4321), 1000, 1000);

        manager.register_connection(1, sender, Some(creds));

        assert_eq!(manager.peer_credentials(1), Some(creds));
        assert_eq!(manager.peer_pid(1), Some(4321));
    }

    #[test]
    fn a_connection_registered_without_credentials_reports_none() {
        let manager = SubscriptionManager::new();
        let (sender, _receiver) = mpsc::channel(10);

        manager.register_connection(1, sender, None);

        assert_eq!(manager.peer_credentials(1), None);
        assert_eq!(manager.peer_pid(1), None);
    }

    #[test]
    fn an_unknown_connection_has_no_peer() {
        let manager = SubscriptionManager::new();

        assert_eq!(manager.peer_credentials(99), None);
        assert_eq!(manager.peer_pid(99), None);
    }

    /// Credentials belong to the connection, so they must outlive subscription
    /// churn and vanish only when the connection does.
    #[test]
    fn credentials_survive_subscription_changes_and_end_with_the_connection() {
        let manager = SubscriptionManager::new();
        let (sender, _receiver) = mpsc::channel(10);
        let creds = PeerCredentials::from_raw(Some(4321), 1000, 1000);

        manager.register_connection(1, sender, Some(creds));
        manager.subscribe(1, &["TypeA".to_string()]);
        assert_eq!(manager.peer_credentials(1), Some(creds));

        manager.unsubscribe(1, &["TypeA".to_string()]);
        assert_eq!(manager.peer_credentials(1), Some(creds));

        manager.unregister_connection(1);
        assert_eq!(manager.peer_credentials(1), None);
    }

    /// Each connection keeps its own peer; they must not bleed into each other.
    #[test]
    fn each_connection_keeps_its_own_peer() {
        let manager = SubscriptionManager::new();
        let (sender1, _r1) = mpsc::channel(10);
        let (sender2, _r2) = mpsc::channel(10);

        manager.register_connection(1, sender1, Some(PeerCredentials::from_raw(Some(11), 1, 1)));
        manager.register_connection(2, sender2, Some(PeerCredentials::from_raw(Some(22), 2, 2)));

        assert_eq!(manager.peer_pid(1), Some(11));
        assert_eq!(manager.peer_pid(2), Some(22));
    }

    #[test]
    fn test_subscribe_unsubscribe() {
        let manager = SubscriptionManager::new();
        let (sender, _receiver) = mpsc::channel(10);

        manager.register_connection(1, sender, None);

        // Subscribe to some types
        let subscribed = manager.subscribe(1, &["TypeA".to_string(), "TypeB".to_string()]);
        assert_eq!(subscribed.len(), 2);
        assert!(subscribed.contains(&"TypeA".to_string()));
        assert!(subscribed.contains(&"TypeB".to_string()));

        assert_eq!(manager.subscribed_types_count(), 2);
        assert_eq!(manager.total_subscriptions(), 2);

        // Unsubscribe from one type
        let subscribed = manager.unsubscribe(1, &["TypeA".to_string()]);
        assert_eq!(subscribed.len(), 1);
        assert!(subscribed.contains(&"TypeB".to_string()));

        assert_eq!(manager.subscribed_types_count(), 1);
        assert_eq!(manager.total_subscriptions(), 1);

        // Unsubscribe from all
        let subscribed = manager.unsubscribe(1, &[]);
        assert!(subscribed.is_empty());
        assert_eq!(manager.subscribed_types_count(), 0);
    }

    #[test]
    fn test_unregister_cleans_subscriptions() {
        let manager = SubscriptionManager::new();
        let (sender, _receiver) = mpsc::channel(10);

        manager.register_connection(1, sender, None);
        manager.subscribe(1, &["TypeA".to_string(), "TypeB".to_string()]);
        assert_eq!(manager.subscribed_types_count(), 2);

        manager.unregister_connection(1);
        assert_eq!(manager.subscribed_types_count(), 0);
    }

    #[test]
    fn test_multiple_connections_same_type() {
        let manager = SubscriptionManager::new();
        let (sender1, _receiver1) = mpsc::channel(10);
        let (sender2, _receiver2) = mpsc::channel(10);

        manager.register_connection(1, sender1, None);
        manager.register_connection(2, sender2, None);

        manager.subscribe(1, &["TypeA".to_string()]);
        manager.subscribe(2, &["TypeA".to_string()]);

        assert_eq!(manager.subscribed_types_count(), 1);
        assert_eq!(manager.total_subscriptions(), 2);

        // Unregister one connection
        manager.unregister_connection(1);
        assert_eq!(manager.subscribed_types_count(), 1);
        assert_eq!(manager.total_subscriptions(), 1);

        // Unregister the other
        manager.unregister_connection(2);
        assert_eq!(manager.subscribed_types_count(), 0);
    }

    #[tokio::test]
    async fn test_forward_to_subscribers() {
        let manager = Arc::new(SubscriptionManager::new());
        let (sender, mut receiver) = mpsc::channel(10);

        manager.register_connection(1, sender, None);
        manager.subscribe(1, &["PriceUpdate".to_string()]);

        let notification = IpcPushNotification::new(
            "PriceUpdate",
            Some("price_service".to_string()),
            serde_json::json!({ "price": 100.0 }),
        );

        manager.forward_to_subscribers(&notification);

        let notification_out = receiver.try_recv().unwrap();
        assert_eq!(notification_out.message_type, "PriceUpdate");
        assert_eq!(manager.stats().push_notifications_sent(), 1);
    }

    #[test]
    fn test_forward_no_subscribers() {
        let manager = Arc::new(SubscriptionManager::new());

        let notification =
            IpcPushNotification::new("UnsubscribedType", None, serde_json::json!({}));

        // Should not panic, just do nothing
        manager.forward_to_subscribers(&notification);
        assert_eq!(manager.stats().push_notifications_sent(), 0);
    }

    #[test]
    fn test_type_mapping() {
        struct TestMessage;

        let manager = SubscriptionManager::new();
        let type_id = TypeId::of::<TestMessage>();

        manager.register_type_mapping(type_id, "TestMessage".to_string());
        assert_eq!(
            manager.get_type_name(&type_id),
            Some("TestMessage".to_string())
        );
    }

    #[tokio::test]
    async fn test_create_push_channel() {
        let conn_id = 42;
        let buffer_size = 10;

        let (sender, receiver) = create_push_channel(conn_id, buffer_size);

        // Verify the receiver has the correct connection ID
        assert_eq!(receiver.conn_id, conn_id);

        // Test that we can send through the channel
        let notification = IpcPushNotification::new(
            "TestMessage",
            Some("test_actor".to_string()),
            serde_json::json!({ "test": true }),
        );

        sender.send(notification.clone()).await.unwrap();

        // Receive the notification
        let mut channel = receiver.receiver;
        let msg = channel.recv().await.unwrap();
        assert_eq!(msg.message_type, "TestMessage");
    }

    #[test]
    fn test_push_receiver_struct() {
        let (_, receiver) = create_push_channel(123, 5);
        assert_eq!(receiver.conn_id, 123);
    }

    fn notification(name: &str) -> IpcPushNotification {
        IpcPushNotification::new(name, None, serde_json::json!({}))
    }

    #[test]
    fn active_subscriptions_are_scoped_to_each_connection() {
        let manager = SubscriptionManager::new();
        let (sender, _receiver) = mpsc::channel(10);
        manager.register_connection(1, sender, None);
        let (sender, _other_receiver) = mpsc::channel(10);
        manager.register_connection(2, sender, None);
        manager.subscribe_patterns(1, &["*".into()]).unwrap();
        assert!(manager.has_subscriptions(1));
        assert!(!manager.has_subscriptions(2));
        assert!(!manager.has_subscriptions(99));
        manager.subscribe(2, &["Exact".into()]);
        assert!(manager.has_subscriptions(2));
        manager.unsubscribe_patterns(1, &[]).unwrap();
        assert!(!manager.has_subscriptions(1));
        assert!(manager.has_subscriptions(2));
    }

    #[test]
    fn patterns_validate_literal_prefixes_and_utf8_limits() {
        for invalid in ["", "Order", "*Order", "Order**", "Or*der*"] {
            assert_eq!(
                invalid.parse::<SubscriptionPattern>(),
                Err(PatternSubscriptionError::InvalidPattern)
            );
        }
        let pattern: SubscriptionPattern = "注文::*".parse().unwrap();
        assert!(pattern.matches("注文::Created"));
        assert!(pattern.matches("注文::"));
        assert!(!pattern.matches("注文Created"));
        assert!("*".parse::<SubscriptionPattern>().unwrap().matches(""));
        assert!(!"Order*"
            .parse::<SubscriptionPattern>()
            .unwrap()
            .matches("orderCreated"));
        assert!("[?]*"
            .parse::<SubscriptionPattern>()
            .unwrap()
            .matches("[?]Created"));
        assert!(format!("{}*", "a".repeat(255))
            .parse::<SubscriptionPattern>()
            .is_ok());
        assert_eq!(
            format!("{}*", "é".repeat(128)).parse::<SubscriptionPattern>(),
            Err(PatternSubscriptionError::PatternTooLong)
        );
    }

    #[test]
    fn overlapping_selectors_deliver_once_and_reuse_cached_routes() {
        let manager = SubscriptionManager::new();
        let (sender, mut receiver) = mpsc::channel(10);
        manager.register_connection(1, sender, None);
        manager.subscribe(1, &["OrderCreated".into()]);
        assert_eq!(
            manager
                .subscribe_patterns(1, &["Order*".into(), "*".into(), "Order*".into()])
                .unwrap(),
            vec!["*", "Order*"]
        );
        let event = notification("OrderCreated");
        manager.forward_to_subscribers(&event);
        let cached = Arc::clone(manager.routes.read().get("OrderCreated").unwrap());
        manager.forward_to_subscribers(&event);
        assert!(Arc::ptr_eq(
            &cached,
            manager.routes.read().get("OrderCreated").unwrap()
        ));
        assert!(receiver.try_recv().is_ok());
        assert!(receiver.try_recv().is_ok());
        assert!(receiver.try_recv().is_err());
        assert_eq!(manager.total_subscriptions(), 3);
        assert_eq!(manager.subscribed_types_count(), 1);
        assert_eq!(manager.subscribed_patterns_count(), 2);
        assert_eq!(manager.stats().subscriptions_added(), 3);
    }

    #[test]
    fn failed_batches_do_not_change_subscriptions_or_cache() {
        let manager = SubscriptionManager::new();
        let (sender, _receiver) = mpsc::channel(10);
        manager.register_connection(1, sender, None);
        manager.subscribe_patterns(1, &["Keep*".into()]).unwrap();
        manager.forward_to_subscribers(&notification("KeepAlive"));
        let cached = Arc::clone(manager.routes.read().get("KeepAlive").unwrap());
        for values in [
            vec!["Valid*".into(), "invalid".into()],
            vec!["*".into(); 129],
        ] {
            assert!(manager.subscribe_patterns(1, &values).is_err());
            assert!(manager.unsubscribe_patterns(1, &values).is_err());
        }
        assert_eq!(manager.get_pattern_subscriptions(1), vec!["Keep*"]);
        assert!(Arc::ptr_eq(
            &cached,
            manager.routes.read().get("KeepAlive").unwrap()
        ));
        let full: Vec<_> = (0..127).map(|i| format!("{i}*")).collect();
        manager.subscribe_patterns(1, &full).unwrap();
        assert_eq!(
            manager.subscribe_patterns(1, &["Extra*".into()]),
            Err(PatternSubscriptionError::TooManyPatterns)
        );
        assert_eq!(manager.get_pattern_subscriptions(1).len(), 128);
        assert_eq!(
            manager.subscribe_patterns(9, &["*".into()]),
            Err(PatternSubscriptionError::UnknownConnection)
        );
    }

    #[test]
    fn negative_routes_invalidate_and_patterns_match_future_names() {
        let manager = SubscriptionManager::new();
        let (sender, mut receiver) = mpsc::channel(10);
        manager.register_connection(1, sender, None);
        manager.forward_to_subscribers(&notification("OrderCreated"));
        assert!(manager
            .routes
            .read()
            .get("OrderCreated")
            .unwrap()
            .is_empty());
        manager.subscribe_patterns(1, &["Order*".into()]).unwrap();
        assert!(manager.routes.read().is_empty());
        manager.forward_to_subscribers(&notification("OrderCreated"));
        manager.forward_to_subscribers(&notification("OrderFuture"));
        assert_eq!(receiver.try_recv().unwrap().message_type, "OrderCreated");
        assert_eq!(receiver.try_recv().unwrap().message_type, "OrderFuture");
        manager.unsubscribe_patterns(1, &["Order*".into()]).unwrap();
        manager.forward_to_subscribers(&notification("OrderCreated"));
        assert!(receiver.try_recv().is_err());
        manager.subscribe(1, &["OrderCreated".into()]);
        manager.forward_to_subscribers(&notification("OrderCreated"));
        assert!(receiver.try_recv().is_ok());
    }

    #[test]
    fn unsubscribe_semantics_preserve_other_selectors() {
        let manager = SubscriptionManager::new();
        let (sender, mut receiver) = mpsc::channel(10);
        manager.register_connection(1, sender, None);
        manager.subscribe(1, &["OrderCreated".into(), "Literal*".into()]);
        manager.subscribe_patterns(1, &["Order*".into()]).unwrap();
        manager.unsubscribe(1, &["OrderCreated".into()]);
        manager.forward_to_subscribers(&notification("OrderCreated"));
        assert!(receiver.try_recv().is_ok());
        manager.unsubscribe_patterns(1, &[]).unwrap();
        manager.forward_to_subscribers(&notification("LiteralOther"));
        assert!(receiver.try_recv().is_err());
        manager.forward_to_subscribers(&notification("Literal*"));
        assert!(receiver.try_recv().is_ok());
        manager.subscribe_patterns(1, &["*".into()]).unwrap();
        manager.unsubscribe(1, &[]);
        assert!(!manager.has_subscriptions(1));
        assert_eq!(manager.total_subscriptions(), 0);
        assert_eq!(
            manager.stats().subscriptions_added(),
            manager.stats().subscriptions_removed()
        );
    }

    #[test]
    fn replacement_and_disconnect_remove_indices_and_cached_recipients() {
        let manager = SubscriptionManager::new();
        let (sender, mut old_receiver) = mpsc::channel(10);
        manager.register_connection(1, sender, None);
        manager.subscribe(1, &["OrderCreated".into()]);
        manager.subscribe_patterns(1, &["*".into()]).unwrap();
        manager.forward_to_subscribers(&notification("OrderCreated"));
        old_receiver.try_recv().unwrap();
        let (sender, mut receiver) = mpsc::channel(10);
        manager.register_connection(1, sender, None);
        manager.forward_to_subscribers(&notification("OrderCreated"));
        assert!(receiver.try_recv().is_err());
        assert!(!manager.has_subscriptions(1));
        assert_eq!(manager.stats().subscriptions_removed(), 2);
        manager.subscribe_patterns(1, &["*".into()]).unwrap();
        manager.forward_to_subscribers(&notification("OrderCreated"));
        receiver.try_recv().unwrap();
        manager.unregister_connection(1);
        assert!(manager.routes.read().is_empty());
        assert!(!manager.has_subscriptions(1));
        assert_eq!(manager.stats().subscriptions_removed(), 3);
    }

    #[test]
    fn route_cache_is_bounded_and_long_names_still_deliver() {
        let manager = SubscriptionManager::new();
        let (sender, mut receiver) = mpsc::channel(1);
        manager.register_connection(1, sender, None);
        manager.subscribe_patterns(1, &["*".into()]).unwrap();
        for i in 0..1025 {
            manager.forward_to_subscribers(&notification(&format!("Event{i}")));
            receiver.try_recv().unwrap();
            assert!(manager.routes.read().len() <= 1024);
        }
        assert_eq!(manager.routes.read().len(), 1024);
        let long_name = "a".repeat(257);
        manager.forward_to_subscribers(&notification(&long_name));
        assert_eq!(receiver.try_recv().unwrap().message_type, long_name);
        assert!(!manager.routes.read().contains_key(&long_name));
    }

    #[test]
    fn overlapping_patterns_count_drops_once_per_recipient() {
        let manager = SubscriptionManager::new();
        let (sender, receiver) = mpsc::channel(1);
        manager.register_connection(1, sender, None);
        manager
            .subscribe_patterns(1, &["*".into(), "Order*".into()])
            .unwrap();
        let event = notification("OrderCreated");
        manager.forward_to_subscribers(&event);
        manager.forward_to_subscribers(&event);
        assert_eq!(manager.stats().push_notifications_sent(), 1);
        assert_eq!(manager.stats().push_notifications_dropped(), 1);
        drop(receiver);
        manager.forward_to_subscribers(&event);
        assert_eq!(manager.stats().push_notifications_dropped(), 2);
    }

    #[test]
    fn concurrent_mutations_leave_no_stale_routes() {
        let manager = SubscriptionManager::new();
        let (sender, mut receiver) = mpsc::channel(1024);
        manager.register_connection(1, sender, None);
        std::thread::scope(|scope| {
            scope.spawn(|| {
                for _ in 0..128 {
                    manager.subscribe_patterns(1, &["*".into()]).unwrap();
                    manager.unsubscribe_patterns(1, &[]).unwrap();
                }
            });
            scope.spawn(|| {
                for _ in 0..128 {
                    manager.subscribe(1, &["Event".into()]);
                    manager.unsubscribe(1, &["Event".into()]);
                }
            });
            for _ in 0..128 {
                manager.forward_to_subscribers(&notification("Event"));
            }
        });
        while receiver.try_recv().is_ok() {}
        manager.forward_to_subscribers(&notification("Event"));
        assert!(receiver.try_recv().is_err());
        assert!(!manager.has_subscriptions(1));
        assert_eq!(
            manager.stats().subscriptions_added(),
            manager.stats().subscriptions_removed()
        );
    }
}