async-snmp 0.18.1

Modern async-first SNMP client library for Rust
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
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
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
//! Agent notification sending (trap/inform).
//!
//! Provides trap sink configuration and methods for sending notifications
//! from an agent to configured destinations.

use std::fmt;
use std::fmt::Write;
use std::future::Future;
use std::net::SocketAddr;
use std::pin::Pin;
use std::sync::{Arc, RwLock};
use std::task::{Context, Poll};
use std::time::Duration;

use bytes::Bytes;
use futures_core::stream::{FusedStream, Stream};
use futures_util::stream::FuturesUnordered;
use tokio::sync::Mutex as AsyncMutex;

use crate::Community;
use crate::client::{
    Auth, Client, ClientConfig, CommunityVersion, LocalAuthoritativeTimeSource, Retry,
};
use crate::error::{Error, Result};
use crate::handler::SecurityModel;
use crate::message::{CommunityMessage, SecurityLevel};
use crate::oid::Oid;
use crate::pdu::NotificationPdu;
use crate::transport::{UdpHandle, UdpTransport};
use crate::v3::{DerivedKeys, UsmConfig};
use crate::varbind::VarBind;
use crate::version::Version;

const MAX_NOTIFICATION_SINK_ID_LEN: usize = 32;

/// Stable caller-supplied identifier for a notification sink.
///
/// The identifier is operational metadata and is never derived from sink
/// credentials. Keep it stable across agent restarts when retaining sink
/// delivery outcomes outside the library. Configured identifiers
/// contain 1 to 32 octets, matching the `snmpTargetAddrName` size defined by
/// RFC 3413. Identifiers are opaque octets and need not contain UTF-8.
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct NotificationSinkId(Arc<[u8]>);

/// Error returned when a notification sink identifier has an invalid length.
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
#[error("notification sink ID length {length} is outside 1..=32 octets")]
pub struct NotificationSinkIdError {
    length: usize,
}

impl NotificationSinkIdError {
    /// Return the rejected identifier length in octets.
    #[must_use]
    pub const fn length(&self) -> usize {
        self.length
    }
}

impl NotificationSinkId {
    /// Create a notification sink identifier from bytes or text.
    ///
    /// Returns [`NotificationSinkIdError`] unless `id` contains 1 to 32
    /// octets. Text inputs are measured by their UTF-8 encoding.
    pub fn new(id: impl AsRef<[u8]>) -> std::result::Result<Self, NotificationSinkIdError> {
        Self::try_from(id.as_ref())
    }

    /// Return the identifier octets.
    #[must_use]
    pub fn as_bytes(&self) -> &[u8] {
        &self.0
    }

    fn from_arc(id: Arc<[u8]>) -> std::result::Result<Self, NotificationSinkIdError> {
        let length = id.len();
        if !(1..=MAX_NOTIFICATION_SINK_ID_LEN).contains(&length) {
            return Err(NotificationSinkIdError { length });
        }
        Ok(Self(id))
    }
}

fn write_escaped_id(bytes: &[u8], f: &mut fmt::Formatter<'_>) -> fmt::Result {
    for &byte in bytes {
        for escaped in std::ascii::escape_default(byte) {
            f.write_char(char::from(escaped))?;
        }
    }
    Ok(())
}

impl fmt::Debug for NotificationSinkId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("NotificationSinkId(b\"")?;
        write_escaped_id(self.as_bytes(), f)?;
        f.write_str("\")")
    }
}

impl fmt::Display for NotificationSinkId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write_escaped_id(self.as_bytes(), f)
    }
}

impl AsRef<[u8]> for NotificationSinkId {
    fn as_ref(&self) -> &[u8] {
        self.as_bytes()
    }
}

impl TryFrom<&[u8]> for NotificationSinkId {
    type Error = NotificationSinkIdError;

    fn try_from(id: &[u8]) -> std::result::Result<Self, Self::Error> {
        Self::from_arc(Arc::from(id))
    }
}

impl TryFrom<Vec<u8>> for NotificationSinkId {
    type Error = NotificationSinkIdError;

    fn try_from(id: Vec<u8>) -> std::result::Result<Self, Self::Error> {
        Self::from_arc(Arc::from(id))
    }
}

impl<const N: usize> TryFrom<&[u8; N]> for NotificationSinkId {
    type Error = NotificationSinkIdError;

    fn try_from(id: &[u8; N]) -> std::result::Result<Self, Self::Error> {
        Self::try_from(id.as_slice())
    }
}

impl<const N: usize> TryFrom<[u8; N]> for NotificationSinkId {
    type Error = NotificationSinkIdError;

    fn try_from(id: [u8; N]) -> std::result::Result<Self, Self::Error> {
        Self::try_from(Vec::from(id))
    }
}

impl TryFrom<&str> for NotificationSinkId {
    type Error = NotificationSinkIdError;

    fn try_from(id: &str) -> std::result::Result<Self, Self::Error> {
        Self::try_from(id.as_bytes())
    }
}

impl TryFrom<String> for NotificationSinkId {
    type Error = NotificationSinkIdError;

    fn try_from(id: String) -> std::result::Result<Self, Self::Error> {
        Self::try_from(id.into_bytes())
    }
}

/// Credential-free description of a configured notification sink.
///
/// This summary deliberately excludes community identifiers, USM usernames,
/// context names, keys, and the original authentication configuration.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct NotificationSinkSummary {
    index: usize,
    id: NotificationSinkId,
    dest: SocketAddr,
    version: Version,
    security_level: Option<SecurityLevel>,
}

impl NotificationSinkSummary {
    /// Zero-based position in sink configuration order.
    #[must_use]
    pub fn index(&self) -> usize {
        self.index
    }

    /// Stable caller-supplied sink identifier.
    #[must_use]
    pub fn id(&self) -> &NotificationSinkId {
        &self.id
    }

    /// Sink destination address.
    #[must_use]
    pub fn dest(&self) -> SocketAddr {
        self.dest
    }

    /// SNMP version used for this sink.
    #[must_use]
    pub fn version(&self) -> Version {
        self.version
    }

    /// Configured SNMPv3 security level, or `None` for community versions.
    #[must_use]
    pub fn security_level(&self) -> Option<SecurityLevel> {
        self.security_level
    }
}

/// A configured notification destination.
///
/// Stores resolved credentials and cached keys for sending traps and informs
/// to a specific target.
pub(crate) struct TrapSink {
    pub(crate) summary: NotificationSinkSummary,
    auth: Auth,
    pub(crate) community: Community,
    pub(crate) v3_security: Option<UsmConfig>,
    /// Keys derived against the agent's `engine_id` for V3 trap sending.
    /// Lazily populated on first use.
    pub(crate) derived_keys: RwLock<Option<DerivedKeys>>,
    /// Timeout for each unconfirmed trap datagram send.
    trap_send_timeout: Duration,
    /// Inform request timeout and retry policy.
    inform_timeout: Duration,
    inform_retry: Retry,
    /// Cached client for inform sending. Lazily created on first inform.
    inform_client: AsyncMutex<Option<Client<UdpHandle>>>,
}

/// Agent-owned Inform endpoints, shared by every sink in an address family.
pub(crate) struct InformTransportPool {
    ipv4: AsyncMutex<Option<UdpTransport>>,
    ipv6: AsyncMutex<Option<UdpTransport>>,
}

impl InformTransportPool {
    pub(crate) fn new() -> Self {
        Self {
            ipv4: AsyncMutex::new(None),
            ipv6: AsyncMutex::new(None),
        }
    }

    async fn handle(&self, target: SocketAddr) -> Result<UdpHandle> {
        let (slot, bind_addr) = if target.is_ipv6() {
            (&self.ipv6, "[::]:0")
        } else {
            (&self.ipv4, "0.0.0.0:0")
        };
        let mut transport = slot.lock().await;
        if transport.is_none() {
            *transport = Some(UdpTransport::bind(bind_addr).await?);
        }
        transport
            .as_ref()
            .expect("Inform transport was initialized")
            .handle(target)
    }
}

impl TrapSink {
    /// Create from an Auth configuration and resolved destination address.
    pub(crate) fn new(
        index: usize,
        id: NotificationSinkId,
        dest: SocketAddr,
        auth: Auth,
        trap_send_timeout: Duration,
        inform_timeout: Duration,
        inform_retry: Retry,
    ) -> Self {
        let sink_auth = auth.clone();
        let summary = NotificationSinkSummary {
            index,
            id,
            dest,
            version: auth.version(),
            security_level: match &auth {
                Auth::Community { .. } => None,
                Auth::Usm(security) => Some(security.security_level()),
            },
        };
        match auth {
            Auth::Community { community, .. } => TrapSink {
                summary,
                auth: sink_auth,
                community: community.clone(),
                v3_security: None,
                derived_keys: RwLock::new(None),
                trap_send_timeout,
                inform_timeout,
                inform_retry,
                inform_client: AsyncMutex::new(None),
            },
            Auth::Usm(security) => TrapSink {
                summary,
                auth: sink_auth,
                community: Community::default(),
                v3_security: Some(security),
                derived_keys: RwLock::new(None),
                trap_send_timeout,
                inform_timeout,
                inform_retry,
                inform_client: AsyncMutex::new(None),
            },
        }
    }

    /// Ensure keys are derived against the given `engine_id` for V3 trap sending.
    fn ensure_keys_derived(&self, engine_id: &[u8]) -> Result<()> {
        {
            let keys = self.derived_keys.read().map_err(|_| {
                Error::Config("trap sink derived_keys lock poisoned".into()).boxed()
            })?;
            if keys.is_some() {
                return Ok(());
            }
        }

        let security = self.v3_security.as_ref().ok_or_else(|| {
            Error::Config("V3 security not configured for trap sink".into()).boxed()
        })?;

        let keys = security
            .derive_keys_inner(engine_id)
            .map_err(|e| Error::Config(e.to_string().into()).boxed())?;

        let mut derived = self
            .derived_keys
            .write()
            .map_err(|_| Error::Config("trap sink derived_keys lock poisoned".into()).boxed())?;
        *derived = Some(keys);

        Ok(())
    }

    /// Get or create the cached inform client for this sink.
    async fn get_or_create_inform_client(
        &self,
        transports: &InformTransportPool,
        des_salt_state: Option<&crate::v3::DesSaltState>,
        agent_state: Option<&Arc<super::AgentState>>,
    ) -> Result<Client<UdpHandle>> {
        let mut guard = self.inform_client.lock().await;
        if let Some(ref client) = *guard {
            return Ok(client.clone());
        }

        if self.summary.version == Version::V1 {
            unreachable!("v1 does not support informs");
        }
        let local_authoritative_engine =
            agent_state.and_then(|state| state.authoritative_engine.clone());
        let local_authoritative_time_source = agent_state.map(|state| {
            let state = Arc::clone(state);
            Arc::new(move || state.authoritative_boots_time()) as LocalAuthoritativeTimeSource
        });
        let config = ClientConfig {
            auth: self.auth.clone(),
            request_timeout: self.inform_timeout,
            retry: self.inform_retry.clone(),
            des_salt_state: des_salt_state.cloned(),
            local_authoritative_engine,
            local_authoritative_time_source,
            ..ClientConfig::default()
        };

        let handle = transports.handle(self.summary.dest).await?;
        let client = Client::new(handle, config)?;
        *guard = Some(client.clone());
        Ok(client)
    }
}

/// Reason that a configured notification sink was not attempted.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum SinkSkipReason {
    /// SNMPv1 does not support Inform requests.
    InformUnsupportedForV1,
    /// VACM did not resolve a notify view containing the notification.
    NotInNotifyView,
}

impl std::fmt::Display for SinkSkipReason {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::InformUnsupportedForV1 => write!(f, "SNMPv1 does not support informs"),
            Self::NotInNotifyView => write!(f, "notification is not in the sink's notify view"),
        }
    }
}

/// Delivery status for a configured notification sink.
#[derive(Debug)]
pub enum SinkStatus {
    /// Encoding and the local socket write succeeded for a trap, or the Inform
    /// was acknowledged.
    Succeeded,
    /// The delivery attempt failed.
    Failed(Box<Error>),
    /// The configured sink could not be attempted for the stated reason.
    Skipped(SinkSkipReason),
}

/// Delivery outcome for a single configured notification sink.
///
/// For traps, success reflects encoding and the local socket write, not remote
/// receipt. For confirmed informs, success reflects the full request/response
/// exchange, including acknowledgement.
#[derive(Debug)]
pub struct SinkOutcome {
    /// Credential-free configured sink identity and protocol summary.
    pub sink: NotificationSinkSummary,
    /// The delivery status for this sink.
    pub status: SinkStatus,
    /// Accepted response deviations for an Inform exchange. Empty for traps,
    /// skipped sinks, and local failures that consumed no response.
    pub metadata: crate::client::ResponseMetadata,
}

type PendingSinkOutcome<'a> = Pin<Box<dyn Future<Output = SinkOutcome> + Send + 'a>>;

/// Lazy stream of notification sink completions.
///
/// Configured sink operations are driven concurrently as the stream is polled.
/// Each item is yielded as its operation reports completion, so stream order can
/// differ from sink configuration order. Dropping the stream cancels unfinished
/// sink futures, but does not undo network I/O or remote processing that already
/// occurred.
///
/// Use [`into_outcome`](Self::into_outcome) on a newly created stream to run
/// every sink operation and restore sink configuration order in the resulting
/// [`NotificationOutcome`].
#[must_use = "notification streams must be polled to send notifications"]
pub struct NotificationSendStream<'a> {
    agent: &'a super::Agent,
    operation: NotificationOperation,
    next_sink: usize,
    admission_limit: usize,
    pending: FuturesUnordered<PendingSinkOutcome<'a>>,
}

enum NotificationOperation {
    Trap {
        trap_oid: Arc<Oid>,
        uptime: u32,
        varbinds: Arc<[VarBind]>,
    },
    Inform {
        trap_oid: Arc<Oid>,
        uptime: u32,
        varbinds: Arc<[VarBind]>,
    },
}

impl NotificationSendStream<'_> {
    /// Return the next sink outcome in completion order.
    pub async fn next(&mut self) -> Option<SinkOutcome> {
        std::future::poll_fn(|context| Pin::new(&mut *self).poll_next(context)).await
    }

    /// Consume the stream and return its remaining outcomes in configuration order.
    ///
    /// Outcomes already yielded by [`next`](Self::next) are not included.
    pub async fn into_outcome(mut self) -> NotificationOutcome {
        let mut sinks = Vec::with_capacity(self.agent.inner.trap_sinks.len());
        while let Some(outcome) = self.next().await {
            sinks.push(outcome);
        }
        sinks.sort_unstable_by_key(|outcome| outcome.sink.index());
        NotificationOutcome { sinks }
    }
}

impl<'a> NotificationSendStream<'a> {
    fn admit(&mut self) {
        while self.pending.len() < self.admission_limit
            && self.next_sink < self.agent.inner.trap_sinks.len()
        {
            let sink = &self.agent.inner.trap_sinks[self.next_sink];
            let agent = self.agent;
            self.next_sink += 1;
            let future: PendingSinkOutcome<'a> = match &self.operation {
                NotificationOperation::Trap {
                    trap_oid,
                    uptime,
                    varbinds,
                } => {
                    let trap_oid = Arc::clone(trap_oid);
                    let varbinds = Arc::clone(varbinds);
                    let uptime = *uptime;
                    Box::pin(async move {
                        agent
                            .trap_sink_outcome(sink, &trap_oid, uptime, &varbinds)
                            .await
                    })
                }
                NotificationOperation::Inform {
                    trap_oid,
                    uptime,
                    varbinds,
                } => {
                    let trap_oid = Arc::clone(trap_oid);
                    let varbinds = Arc::clone(varbinds);
                    let uptime = *uptime;
                    Box::pin(async move {
                        agent
                            .inform_sink_outcome(sink, &trap_oid, uptime, &varbinds)
                            .await
                    })
                }
            };
            self.pending.push(future);
        }
    }
}

impl Stream for NotificationSendStream<'_> {
    type Item = SinkOutcome;

    fn poll_next(self: Pin<&mut Self>, context: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        let this = self.get_mut();
        this.admit();
        Pin::new(&mut this.pending).poll_next(context)
    }
}

impl FusedStream for NotificationSendStream<'_> {
    fn is_terminated(&self) -> bool {
        self.next_sink == self.agent.inner.trap_sinks.len() && self.pending.is_empty()
    }
}

/// Aggregate outcome of sending a notification to all configured sinks.
///
/// Returned by [`Agent::send_trap`](super::Agent::send_trap) and
/// [`Agent::send_inform`](super::Agent::send_inform) so callers can observe
/// success, failure, or an explicit skip for every configured sink.
#[must_use = "inspect notification outcomes or use the explicit best-effort helper"]
#[derive(Debug)]
pub struct NotificationOutcome {
    sinks: Vec<SinkOutcome>,
}

impl NotificationOutcome {
    /// Per-sink outcomes, in sink configuration order.
    pub fn sinks(&self) -> &[SinkOutcome] {
        &self.sinks
    }

    /// Iterator over the sinks whose delivery failed.
    pub fn failures(&self) -> impl Iterator<Item = &SinkOutcome> {
        self.sinks
            .iter()
            .filter(|s| matches!(s.status, SinkStatus::Failed(_)))
    }

    /// Iterator over configured sinks that were not attempted.
    pub fn skipped(&self) -> impl Iterator<Item = &SinkOutcome> {
        self.sinks
            .iter()
            .filter(|s| matches!(s.status, SinkStatus::Skipped(_)))
    }

    /// `true` if every configured sink succeeded.
    ///
    /// This is also `true` when no sinks are configured, but is `false` when
    /// any configured sink failed or was skipped.
    pub fn all_succeeded(&self) -> bool {
        self.sinks
            .iter()
            .all(|s| matches!(s.status, SinkStatus::Succeeded))
    }

    /// Number of configured sinks represented in this outcome.
    pub fn len(&self) -> usize {
        self.sinks.len()
    }

    /// `true` if no sinks were configured.
    pub fn is_empty(&self) -> bool {
        self.sinks.is_empty()
    }

    /// Consume the outcome, returning the per-sink outcomes.
    pub fn into_sinks(self) -> Vec<SinkOutcome> {
        self.sinks
    }
}

impl super::Agent {
    async fn trap_sink_outcome(
        &self,
        sink: &TrapSink,
        trap_oid: &Oid,
        uptime: u32,
        varbinds: &[VarBind],
    ) -> SinkOutcome {
        let status = if !self.notification_allowed(sink, trap_oid, varbinds) {
            SinkStatus::Skipped(SinkSkipReason::NotInNotifyView)
        } else {
            match NotificationPdu::trap_v2(
                Version::V3,
                self.next_notification_id(),
                uptime,
                trap_oid,
                varbinds.to_vec(),
            ) {
                Ok(pdu) => match self.send_trap_to_sink(sink, &pdu).await {
                    Ok(()) => SinkStatus::Succeeded,
                    Err(error) => SinkStatus::Failed(error),
                },
                Err(error) => SinkStatus::Failed(error),
            }
        };
        SinkOutcome {
            sink: sink.summary.clone(),
            status,
            metadata: crate::client::ResponseMetadata::default(),
        }
    }

    async fn inform_sink_outcome(
        &self,
        sink: &TrapSink,
        trap_oid: &Oid,
        uptime: u32,
        varbinds: &[VarBind],
    ) -> SinkOutcome {
        let (status, metadata) = if sink.summary.version == Version::V1 {
            (
                SinkStatus::Skipped(SinkSkipReason::InformUnsupportedForV1),
                crate::client::ResponseMetadata::default(),
            )
        } else if !self.notification_allowed(sink, trap_oid, varbinds) {
            (
                SinkStatus::Skipped(SinkSkipReason::NotInNotifyView),
                crate::client::ResponseMetadata::default(),
            )
        } else {
            match self
                .send_inform_to_sink(sink, trap_oid, uptime, varbinds)
                .await
            {
                Ok(metadata) => (SinkStatus::Succeeded, metadata),
                Err(error) => {
                    let metadata = error.response_metadata().cloned().unwrap_or_default();
                    (SinkStatus::Failed(error), metadata)
                }
            }
        };
        SinkOutcome {
            sink: sink.summary.clone(),
            status,
            metadata,
        }
    }

    /// Lazily send a trap to all configured sinks.
    ///
    /// No sink operation or request-ID allocation occurs until the returned
    /// stream is polled. Sink operations are then driven concurrently and
    /// outcomes are yielded as they complete. Dropping the stream cancels
    /// unfinished operations but cannot undo a trap write that already occurred.
    /// Use [`NotificationSendStream::into_outcome`] when outcomes are needed in
    /// sink configuration order.
    pub fn send_trap_stream(
        &self,
        trap_oid: &Oid,
        uptime: u32,
        varbinds: Vec<VarBind>,
    ) -> NotificationSendStream<'_> {
        let trap_oid = Arc::new(trap_oid.clone());
        let varbinds: Arc<[VarBind]> = Arc::from(varbinds);
        NotificationSendStream {
            agent: self,
            operation: NotificationOperation::Trap {
                trap_oid,
                uptime,
                varbinds,
            },
            next_sink: 0,
            admission_limit: self.inner.notification_fanout_limit,
            pending: FuturesUnordered::new(),
        }
    }

    /// Send a trap to all configured trap sinks, reporting every outcome.
    ///
    /// Constructs a `TrapV2` PDU with the mandatory sysUpTime.0 and
    /// snmpTrapOID.0 prefix and sends it to each destination. Trap success
    /// means encoding and the local socket write succeeded; traps are
    /// fire-and-forget and remote receipt is not confirmed.
    ///
    /// V1 trap sinks receive a converted v1 trap (RFC 3584 Section 3.2).
    /// For a V3 sink, this Agent is authoritative and sends its persisted
    /// engine ID with the current boots/time tuple.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use async_snmp::agent::Agent;
    /// # use async_snmp::{Auth, NotificationSinkId, oid};
    /// # async fn example() -> Result<(), Box<async_snmp::Error>> {
    /// let agent = Agent::builder()
    ///     .bind("0.0.0.0:1161")
    ///     .community(b"public")
    ///     .trap_sink(NotificationSinkId::new("primary").unwrap(), "192.168.1.100:162", Auth::v2c("public"))
    ///     .allow_all_access()
    ///     .build()
    ///     .await?;
    ///
    /// let outcome = agent
    ///     .send_trap(&oid!(1, 3, 6, 1, 6, 3, 1, 1, 5, 1), 0, vec![])
    ///     .await;
    /// assert!(outcome.all_succeeded());
    /// # Ok(())
    /// # }
    /// ```
    pub async fn send_trap(
        &self,
        trap_oid: &Oid,
        uptime: u32,
        varbinds: Vec<VarBind>,
    ) -> NotificationOutcome {
        self.send_trap_stream(trap_oid, uptime, varbinds)
            .into_outcome()
            .await
    }

    /// Send a trap to all configured sinks, warning and discarding outcomes.
    ///
    /// Use [`send_trap`](Self::send_trap) when the caller needs to observe
    /// per-sink success or failure. Warnings are emitted as each sink operation
    /// completes rather than after every sink has finished.
    pub async fn send_trap_best_effort(&self, trap_oid: &Oid, uptime: u32, varbinds: Vec<VarBind>) {
        let mut stream = self.send_trap_stream(trap_oid, uptime, varbinds);
        while let Some(sink) = stream.next().await {
            match &sink.status {
                SinkStatus::Failed(error) => {
                    tracing::warn!(target: "async_snmp::agent", { snmp.sink_id = %sink.sink.id(), snmp.dest = %sink.sink.dest(), error = %error }, "failed to send trap");
                }
                SinkStatus::Skipped(reason) => {
                    tracing::warn!(target: "async_snmp::agent", { snmp.sink_id = %sink.sink.id(), snmp.dest = %sink.sink.dest(), reason = %reason }, "skipped trap sink");
                }
                SinkStatus::Succeeded => {}
            }
        }
    }

    /// Lazily send an Inform to all configured sinks.
    ///
    /// No sink operation starts until the returned stream is polled. Sink
    /// operations are then driven concurrently and outcomes are yielded as they
    /// complete. Dropping the stream cancels unfinished local exchanges but
    /// cannot undo an Inform already processed by a remote receiver. Use
    /// [`NotificationSendStream::into_outcome`] when outcomes are needed in sink
    /// configuration order.
    pub fn send_inform_stream(
        &self,
        trap_oid: &Oid,
        uptime: u32,
        varbinds: Vec<VarBind>,
    ) -> NotificationSendStream<'_> {
        let trap_oid = Arc::new(trap_oid.clone());
        let varbinds: Arc<[VarBind]> = Arc::from(varbinds);
        NotificationSendStream {
            agent: self,
            operation: NotificationOperation::Inform {
                trap_oid,
                uptime,
                varbinds,
            },
            next_sink: 0,
            admission_limit: self.inner.notification_fanout_limit,
            pending: FuturesUnordered::new(),
        }
    }

    /// Send an inform to all configured trap sinks, reporting every outcome.
    ///
    /// Constructs an `InformRequest` PDU and sends it to each destination,
    /// waiting for acknowledgement from each. Sink exchanges run concurrently,
    /// and outcomes remain in sink configuration order. Reuses a cached client
    /// per sink and one Inform UDP endpoint per destination address family for
    /// request/response exchanges.
    ///
    /// V1 trap sinks are explicitly reported as skipped because v1 does not
    /// support informs. For a V3 sink, the receiver is authoritative; the
    /// cached client discovers and uses the sink's engine identity and trusted
    /// time rather than the Agent's local authoritative state. Each
    /// [`SinkOutcome::metadata`] retains accepted deviations from that sink's
    /// complete Inform exchange.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use async_snmp::agent::Agent;
    /// # use async_snmp::{Auth, NotificationSinkId, oid};
    /// # async fn example() -> Result<(), Box<async_snmp::Error>> {
    /// let agent = Agent::builder()
    ///     .bind("0.0.0.0:1161")
    ///     .community(b"public")
    ///     .trap_sink(NotificationSinkId::new("primary").unwrap(), "192.168.1.100:162", Auth::v2c("public"))
    ///     .allow_all_access()
    ///     .build()
    ///     .await?;
    ///
    /// let outcome = agent
    ///     .send_inform(&oid!(1, 3, 6, 1, 6, 3, 1, 1, 5, 2), 0, vec![])
    ///     .await;
    /// assert!(outcome.all_succeeded());
    /// # Ok(())
    /// # }
    /// ```
    pub async fn send_inform(
        &self,
        trap_oid: &Oid,
        uptime: u32,
        varbinds: Vec<VarBind>,
    ) -> NotificationOutcome {
        self.send_inform_stream(trap_oid, uptime, varbinds)
            .into_outcome()
            .await
    }

    /// Send an inform to all configured sinks, warning and discarding outcomes.
    ///
    /// Use [`send_inform`](Self::send_inform) when the caller needs to observe
    /// per-sink acknowledgement, failure, or skip status. Warnings are emitted
    /// as each sink operation completes rather than after every sink has
    /// finished.
    pub async fn send_inform_best_effort(
        &self,
        trap_oid: &Oid,
        uptime: u32,
        varbinds: Vec<VarBind>,
    ) {
        let mut stream = self.send_inform_stream(trap_oid, uptime, varbinds);
        while let Some(sink) = stream.next().await {
            match &sink.status {
                SinkStatus::Failed(error) => {
                    tracing::warn!(target: "async_snmp::agent", { snmp.sink_id = %sink.sink.id(), snmp.dest = %sink.sink.dest(), error = %error }, "failed to send inform");
                }
                SinkStatus::Skipped(reason) => {
                    tracing::warn!(target: "async_snmp::agent", { snmp.sink_id = %sink.sink.id(), snmp.dest = %sink.sink.dest(), reason = %reason }, "skipped inform sink");
                }
                SinkStatus::Succeeded => {}
            }
        }
    }

    /// Resolve and apply the target sink's VACM notify view.
    fn notification_allowed(&self, sink: &TrapSink, trap_oid: &Oid, varbinds: &[VarBind]) -> bool {
        let Some(vacm) = self.inner.authorization.vacm() else {
            return true;
        };

        let (model, security_name, security_level, context_name) = match &sink.auth {
            Auth::Community { version, community } => {
                let model = match version {
                    CommunityVersion::V1 => SecurityModel::V1,
                    CommunityVersion::V2c => SecurityModel::V2c,
                };
                (
                    model,
                    community.as_bytes(),
                    SecurityLevel::NoAuthNoPriv,
                    &[][..],
                )
            }
            Auth::Usm(security) => (
                SecurityModel::Usm,
                security.username().as_ref(),
                security.security_level(),
                security.configured_context_name().as_ref(),
            ),
        };

        let Some(group) = vacm.get_group(model, security_name) else {
            return false;
        };
        let Some(access) = vacm.get_access(group, context_name, model, security_level) else {
            return false;
        };
        let notify_view = Some(&access.notify_view);

        if !vacm.check_access(notify_view, trap_oid)
            || varbinds
                .iter()
                .any(|varbind| !vacm.check_access(notify_view, &varbind.oid))
        {
            return false;
        }

        // SNMPv2c/v3 notifications carry these mandatory varbind names. In v1
        // they are represented by Trap-PDU fields instead.
        sink.summary.version == Version::V1
            || (vacm.check_access(notify_view, &crate::notification::oids::sys_uptime())
                && vacm.check_access(notify_view, &crate::notification::oids::snmp_trap_oid()))
    }

    /// Send a trap PDU to a single sink.
    async fn send_trap_to_sink(&self, sink: &TrapSink, pdu: &NotificationPdu) -> Result<()> {
        let data = match sink.summary.version {
            Version::V1 => {
                // Convert the v2 PDU to a v1 TrapV1Pdu (RFC 3584 Section 3.2).
                // Use the agent's bound address as agent_addr if available.
                let local_ip = match self.inner.socket.local_addr() {
                    Ok(addr) => match addr.ip() {
                        std::net::IpAddr::V4(v4) => v4.octets(),
                        std::net::IpAddr::V6(_) => [0, 0, 0, 0],
                    },
                    Err(_) => [0, 0, 0, 0],
                };
                let trap = pdu.to_v1_trap(local_ip)?;
                let msg = CommunityMessage::v1_trap(sink.community.clone(), trap.into_raw())?;
                msg.encode()
            }
            Version::V2c => {
                let msg = CommunityMessage::new(
                    CommunityVersion::V2c,
                    sink.community.clone(),
                    pdu.as_raw().clone(),
                )?;
                msg.encode()
            }
            Version::V3 => {
                let security = sink.v3_security.as_ref().ok_or_else(|| {
                    Error::Config("V3 security not configured for trap sink".into()).boxed()
                })?;

                sink.ensure_keys_derived(&self.inner.state.engine_id)?;
                let derived = sink.derived_keys.read().map_err(|_| {
                    Error::Config("trap sink derived_keys lock poisoned".into()).boxed()
                })?;

                let (engine_boots, engine_time) = self.inner.state.authoritative_boots_time()?;

                let msg_id = self.next_notification_id();
                let encoded = crate::v3::encode::encode_v3_message(
                    pdu.as_raw(),
                    msg_id,
                    &self.inner.state.engine_id,
                    engine_boots,
                    engine_time,
                    security,
                    derived.as_ref(),
                    self.inner.salt_counter.as_ref(),
                    self.inner.des_salt_state.as_ref(),
                    Some(engine_boots),
                    false, // reportable=false for traps
                    self.inner.state.local_receive_capacity,
                )?;
                Ok(Bytes::from(encoded))
            }
        }?;

        tracing::debug!(target: "async_snmp::agent", { snmp.sink_id = %sink.summary.id, snmp.dest = %sink.summary.dest, snmp.bytes = data.len() }, "sending trap");
        send_datagram_with_timeout(
            &self.inner.socket,
            &data,
            sink.summary.dest,
            sink.trap_send_timeout,
        )
        .await?;

        Ok(())
    }

    /// Send an inform to a single sink, reusing a cached client.
    async fn send_inform_to_sink(
        &self,
        sink: &TrapSink,
        trap_oid: &Oid,
        uptime: u32,
        varbinds: &[VarBind],
    ) -> Result<crate::client::ResponseMetadata> {
        let client = sink
            .get_or_create_inform_client(
                &self.inner.inform_transports,
                self.inner.des_salt_state.as_ref(),
                Some(&self.inner.state),
            )
            .await?;
        client
            .send_inform_with_metadata(trap_oid, uptime, varbinds.to_vec())
            .await
    }

    /// Generate a notification request/message ID.
    fn next_notification_id(&self) -> i32 {
        use std::sync::atomic::Ordering;
        self.inner
            .notification_id
            .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |v| {
                Some(if v == i32::MAX { 1 } else { v + 1 })
            })
            .unwrap_or(1)
    }
}

async fn send_datagram_with_timeout(
    socket: &tokio::net::UdpSocket,
    data: &[u8],
    target: SocketAddr,
    timeout: Duration,
) -> Result<()> {
    crate::transport::checked_deadline(timeout, "trap send timeout")?;
    let deadline = tokio::time::Instant::now()
        .checked_add(timeout)
        .ok_or_else(|| {
            Error::Config("trap send timeout exceeds the representable deadline".into()).boxed()
        })?;
    if tokio::time::Instant::now() >= deadline {
        return Err(Error::Timeout {
            target,
            elapsed: timeout,
            retries: 0,
        }
        .boxed());
    }

    tokio::time::timeout_at(deadline, socket.send_to(data, target))
        .await
        .map_err(|_| {
            Error::Timeout {
                target,
                elapsed: timeout,
                retries: 0,
            }
            .boxed()
        })?
        .map_err(|source| Error::Network { target, source }.boxed())?;
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::{
        NotificationOperation, NotificationSendStream, NotificationSinkId, PendingSinkOutcome,
        SinkOutcome, SinkSkipReason, SinkStatus, TrapSink,
    };
    use crate::agent::{Agent, SecurityModel, VacmSecurityModel};
    use crate::{Auth, Error, SecurityLevel, Value, VarBind, oid};
    #[cfg(any(feature = "crypto-rustcrypto", feature = "crypto-fips"))]
    use crate::{AuthProtocol, PrivProtocol};
    use bytes::Bytes;
    use futures_util::stream::FuturesUnordered;
    use std::sync::Arc;

    fn test_sink(auth: impl Into<Auth>) -> TrapSink {
        TrapSink::new(
            0,
            NotificationSinkId::new("test-sink").unwrap(),
            "127.0.0.1:9".parse().unwrap(),
            auth.into(),
            crate::client::DEFAULT_SEND_TIMEOUT,
            std::time::Duration::from_millis(10),
            crate::client::Retry::default(),
        )
    }

    #[tokio::test]
    async fn inform_clients_share_one_lazy_endpoint_per_family() {
        let first_receiver = tokio::net::UdpSocket::bind("127.0.0.1:0").await.unwrap();
        let second_receiver = tokio::net::UdpSocket::bind("127.0.0.1:0").await.unwrap();
        let first_target = first_receiver.local_addr().unwrap();
        let second_target = second_receiver.local_addr().unwrap();
        let agent = Agent::builder()
            .bind("127.0.0.1:0")
            .trap_sink(
                NotificationSinkId::new("first").unwrap(),
                first_target.to_string(),
                Auth::v2c("public"),
            )
            .trap_sink(
                NotificationSinkId::new("second").unwrap(),
                second_target.to_string(),
                Auth::v2c("private"),
            )
            .allow_all_access()
            .build()
            .await
            .unwrap();

        assert!(agent.inner.inform_transports.ipv4.lock().await.is_none());
        let (first, second) = tokio::join!(
            agent.inner.trap_sinks[0].get_or_create_inform_client(
                &agent.inner.inform_transports,
                None,
                None
            ),
            agent.inner.trap_sinks[1].get_or_create_inform_client(
                &agent.inner.inform_transports,
                None,
                None
            ),
        );
        let first = first.unwrap();
        let second = second.unwrap();
        assert_eq!(first.peer_addr(), first_target);
        assert_eq!(second.peer_addr(), second_target);

        let transport = agent.inner.inform_transports.ipv4.lock().await;
        let endpoint = transport.as_ref().expect("IPv4 endpoint was not cached");
        assert_ne!(endpoint.local_addr().port(), agent.local_addr().port());
        assert!(agent.inner.inform_transports.ipv6.lock().await.is_none());
    }

    #[cfg(feature = "crypto-rustcrypto")]
    #[tokio::test]
    async fn agent_trap_rejects_des_state_after_authoritative_rollover() {
        let engine = crate::v3::AuthoritativeEngine::for_test(&b"agent-engine"[..], 1);
        engine.set_elapsed_for_test(u64::from(crate::v3::MAX_ENGINE_TIME) + 1);
        let des_state =
            crate::v3::DesSaltState::install(|_| Ok::<(), std::convert::Infallible>(())).unwrap();
        let auth = crate::UsmConfig::new("trapuser")
            .auth_priv(
                crate::v3::AuthProtocol::Sha1,
                b"auth-password",
                crate::v3::PrivProtocol::Des,
                b"priv-password",
            )
            .unwrap();
        let agent = Agent::builder()
            .bind("127.0.0.1:0")
            .authoritative_engine(engine)
            .des_salt_state(des_state.clone())
            .trap_sink(
                NotificationSinkId::new("des-sink").unwrap(),
                "127.0.0.1:9",
                auth,
            )
            .allow_all_access()
            .build()
            .await
            .unwrap();

        let outcome = agent
            .send_trap(&oid!(1, 3, 6, 1, 6, 3, 1, 1, 5, 1), 0, vec![])
            .await;
        let SinkStatus::Failed(error) = &outcome.sinks()[0].status else {
            panic!("stale DES state must fail the trap sink")
        };
        assert!(matches!(
            &**error,
            Error::Privacy(crate::v3::PrivacyError::DesEngineBootsMismatch {
                state_engine_boots: 1,
                generating_engine_boots: 2,
            })
        ));
        assert_eq!(des_state.reserve().unwrap().salt(), 1);
    }

    #[cfg(feature = "crypto-rustcrypto")]
    #[tokio::test]
    async fn agent_des_inform_persistence_updates_health_and_recovers() {
        use std::sync::atomic::{AtomicUsize, Ordering};

        let receiver_engine =
            crate::v3::AuthoritativeEngine::for_test(&b"receiver-inform-health"[..], 5);
        let receiver_des_state = crate::v3::DesSaltState::restart(
            crate::v3::PersistedDesSaltState::new(4).unwrap(),
            |_| Ok::<(), std::convert::Infallible>(()),
        )
        .unwrap();
        let receiver = crate::NotificationReceiver::builder()
            .bind("127.0.0.1:0")
            .authoritative_engine(receiver_engine)
            .des_salt_state(receiver_des_state)
            .usm_user("informuser", |user| {
                user.auth_priv(
                    AuthProtocol::Sha1,
                    b"auth-password",
                    PrivProtocol::Des,
                    b"priv-password",
                )
            })
            .unwrap()
            .accept_all_notifications()
            .build()
            .await
            .unwrap();
        let receiver_addr = receiver.local_addr();
        let receiver_task = tokio::spawn(async move { receiver.recv().await });

        let persistence_calls = std::sync::Arc::new(AtomicUsize::new(0));
        let callback_calls = std::sync::Arc::clone(&persistence_calls);
        let engine =
            crate::v3::AuthoritativeEngine::install(b"agent-inform-health".to_vec(), move |_| {
                match callback_calls.fetch_add(1, Ordering::Relaxed) {
                    0 | 3.. => Ok(()),
                    _ => Err(std::io::Error::other("persistence unavailable")),
                }
            })
            .unwrap();
        let des_state =
            crate::v3::DesSaltState::install(|_| Ok::<(), std::convert::Infallible>(())).unwrap();
        let sink_auth = crate::UsmConfig::new("informuser")
            .auth_priv(
                AuthProtocol::Sha1,
                b"auth-password",
                PrivProtocol::Des,
                b"priv-password",
            )
            .unwrap();
        let agent = Agent::builder()
            .bind("127.0.0.1:0")
            .authoritative_engine(engine.clone())
            .des_salt_state(des_state)
            .trap_sink(
                NotificationSinkId::new("des-inform").unwrap(),
                receiver_addr.to_string(),
                sink_auth,
            )
            .inform_timeout(std::time::Duration::from_secs(1))
            .inform_retry(crate::Retry::none())
            .allow_all_access()
            .build()
            .await
            .unwrap();
        engine.set_elapsed_for_test(u64::from(crate::v3::MAX_ENGINE_TIME) + 1);
        let trap_oid = oid!(1, 3, 6, 1, 6, 3, 1, 1, 5, 1);

        for expected_failures in [1, 2] {
            let outcome = agent.send_inform(&trap_oid, 0, vec![]).await;
            assert!(matches!(
                &outcome.sinks()[0].status,
                SinkStatus::Failed(error)
                    if error.kind() == crate::ErrorKind::AuthoritativeEnginePersistence
            ));
            assert!(matches!(
                agent.health(),
                crate::agent::AgentHealth::AuthoritativePersistenceDegraded {
                    consecutive_failures,
                    ..
                } if consecutive_failures == expected_failures
            ));
        }

        let recovered = agent.send_inform(&trap_oid, 0, vec![]).await;
        assert!(matches!(
            &recovered.sinks()[0].status,
            SinkStatus::Failed(error)
                if matches!(
                    &**error,
                    Error::Privacy(crate::v3::PrivacyError::DesEngineBootsMismatch {
                        state_engine_boots: 1,
                        generating_engine_boots: 2,
                    })
                )
        ));
        assert_eq!(agent.health(), crate::agent::AgentHealth::Healthy);
        assert_eq!(persistence_calls.load(Ordering::Relaxed), 4);

        receiver_task.abort();
        let _ = receiver_task.await;
    }

    #[cfg(any(feature = "crypto-rustcrypto", feature = "crypto-fips"))]
    #[tokio::test]
    async fn notify_view_uses_each_sink_identity_context_and_security_level() {
        let agent = Agent::builder()
            .bind("127.0.0.1:0")
            .vacm(|v| {
                v.group("v1-community", SecurityModel::V1, "v1")
                    .group("v2-community", SecurityModel::V2c, "v2")
                    .group("context-user", SecurityModel::Usm, "context")
                    .group("security-user", SecurityModel::Usm, "security")
                    .access("v1", SecurityModel::V1, SecurityLevel::NoAuthNoPriv, |a| {
                        a.notify_view("all")
                    })
                    .access("v2", SecurityModel::V2c, SecurityLevel::NoAuthNoPriv, |a| {
                        a.notify_view("all")
                    })
                    .access(
                        "context",
                        SecurityModel::Usm,
                        SecurityLevel::NoAuthNoPriv,
                        |a| {
                            a.context_prefix("tenant/")
                                .context_match_prefix()
                                .notify_view("empty")
                        },
                    )
                    .access(
                        "context",
                        SecurityModel::Usm,
                        SecurityLevel::NoAuthNoPriv,
                        |a| a.context_prefix("tenant/blue").notify_view("all"),
                    )
                    .access(
                        "security",
                        SecurityModel::Usm,
                        SecurityLevel::NoAuthNoPriv,
                        |a| a.context_prefix("secure").notify_view("empty"),
                    )
                    .access(
                        "security",
                        SecurityModel::Usm,
                        SecurityLevel::AuthPriv,
                        |a| a.context_prefix("secure").notify_view("all"),
                    )
                    .view("all", |view| view.include(oid!(1, 3, 6)))
                    .view("empty", |view| view)
            })
            .build()
            .await
            .unwrap();
        let trap_oid = oid!(1, 3, 6, 1, 6, 3, 1, 1, 5, 1);

        assert!(agent.notification_allowed(&test_sink(Auth::v1("v1-community")), &trap_oid, &[]));
        assert!(agent.notification_allowed(&test_sink(Auth::v2c("v2-community")), &trap_oid, &[]));
        assert!(agent.notification_allowed(
            &test_sink(crate::UsmConfig::new("context-user").context_name("tenant/blue"),),
            &trap_oid,
            &[]
        ));
        assert!(!agent.notification_allowed(
            &test_sink(crate::UsmConfig::new("context-user").context_name("tenant/red"),),
            &trap_oid,
            &[]
        ));
        assert!(
            !agent.notification_allowed(
                &test_sink(
                    crate::UsmConfig::new("security-user")
                        .auth(AuthProtocol::Sha256, "auth-password")
                        .unwrap()
                        .context_name("secure")
                ),
                &trap_oid,
                &[]
            )
        );
        assert!(
            agent.notification_allowed(
                &test_sink(
                    crate::UsmConfig::new("security-user")
                        .auth_priv(
                            AuthProtocol::Sha256,
                            "auth-password",
                            PrivProtocol::Aes128,
                            "privacy-password",
                        )
                        .unwrap()
                        .context_name("secure")
                ),
                &trap_oid,
                &[]
            )
        );
    }

    #[tokio::test]
    async fn notify_view_denies_trap_oid_extra_varbind_and_missing_views() {
        let denied_trap = oid!(1, 3, 6, 1, 4, 1, 9999, 1);
        let allowed_trap = oid!(1, 3, 6, 1, 4, 1, 9999, 2);
        let denied_extra = oid!(1, 3, 6, 1, 4, 1, 9999, 3);
        let agent = Agent::builder()
            .bind("127.0.0.1:0")
            .vacm(|v| {
                v.group("trap-denied", SecurityModel::V2c, "trap-denied")
                    .group("extra-denied", SecurityModel::V2c, "extra-denied")
                    .group("missing", SecurityModel::V2c, "missing")
                    .group("empty", SecurityModel::V2c, "empty")
                    .group("no-access", SecurityModel::V2c, "no-access")
                    .access(
                        "trap-denied",
                        SecurityModel::V2c,
                        SecurityLevel::NoAuthNoPriv,
                        |a| a.notify_view("trap-view"),
                    )
                    .access(
                        "extra-denied",
                        SecurityModel::V2c,
                        SecurityLevel::NoAuthNoPriv,
                        |a| a.notify_view("extra-view"),
                    )
                    .access(
                        "missing",
                        SecurityModel::V2c,
                        SecurityLevel::NoAuthNoPriv,
                        |a| a.notify_view("not-defined"),
                    )
                    .access(
                        "empty",
                        SecurityModel::V2c,
                        SecurityLevel::NoAuthNoPriv,
                        |a| a,
                    )
                    .view("trap-view", |view| {
                        view.include(oid!(1, 3, 6)).exclude(denied_trap.clone())
                    })
                    .view("extra-view", |view| {
                        view.include(oid!(1, 3, 6)).exclude(denied_extra.clone())
                    })
            })
            .build()
            .await
            .unwrap();
        let extra = VarBind::new(denied_extra, Value::Integer(1));

        assert!(!agent.notification_allowed(
            &test_sink(Auth::v2c("trap-denied")),
            &denied_trap,
            &[]
        ));
        assert!(!agent.notification_allowed(
            &test_sink(Auth::v2c("extra-denied")),
            &allowed_trap,
            &[extra]
        ));
        assert!(!agent.notification_allowed(&test_sink(Auth::v2c("missing")), &allowed_trap, &[]));
        assert!(!agent.notification_allowed(&test_sink(Auth::v2c("empty")), &allowed_trap, &[]));
        assert!(!agent.notification_allowed(
            &test_sink(Auth::v2c("no-access")),
            &allowed_trap,
            &[]
        ));
        assert!(!agent.notification_allowed(&test_sink(Auth::v2c("no-group")), &allowed_trap, &[]));
    }

    #[tokio::test]
    async fn notify_view_checks_v2_mandatory_varbind_names_but_not_v1_fields() {
        let trap_oid = oid!(1, 3, 6, 1, 4, 1, 9999, 1);
        let extra_oid = oid!(1, 3, 6, 1, 4, 1, 9999, 2);
        let agent = Agent::builder()
            .bind("127.0.0.1:0")
            .vacm(|v| {
                v.group("v1", SecurityModel::V1, "group")
                    .group("v2", SecurityModel::V2c, "group")
                    .access(
                        "group",
                        VacmSecurityModel::Any,
                        SecurityLevel::NoAuthNoPriv,
                        |a| a.notify_view("notification-only"),
                    )
                    .view("notification-only", |view| {
                        view.include(trap_oid.clone()).include(extra_oid.clone())
                    })
            })
            .build()
            .await
            .unwrap();
        let extra = VarBind::new(extra_oid, Value::Integer(1));

        assert!(agent.notification_allowed(
            &test_sink(Auth::v1("v1")),
            &trap_oid,
            std::slice::from_ref(&extra)
        ));
        assert!(!agent.notification_allowed(&test_sink(Auth::v2c("v2")), &trap_oid, &[extra]));
    }

    #[tokio::test]
    async fn notification_vacm_is_permissive_when_unconfigured_and_mixed_per_sink() {
        let trap_oid = oid!(1, 3, 6, 1, 6, 3, 1, 1, 5, 1);
        let permissive = Agent::builder().bind("127.0.0.1:0").build().await.unwrap();
        assert!(permissive.notification_allowed(
            &test_sink(Auth::v2c("unmapped")),
            &trap_oid,
            &[VarBind::new(oid!(9, 9), Value::Integer(1))]
        ));

        let mixed = Agent::builder()
            .bind("127.0.0.1:0")
            .trap_sink(
                NotificationSinkId::new("allowed").unwrap(),
                "127.0.0.1:9",
                Auth::v2c("allowed"),
            )
            .trap_sink(
                NotificationSinkId::new("denied").unwrap(),
                "127.0.0.1:9",
                Auth::v2c("denied"),
            )
            .vacm(|v| {
                v.group("allowed", SecurityModel::V2c, "allowed")
                    .group("denied", SecurityModel::V2c, "denied")
                    .access(
                        "allowed",
                        SecurityModel::V2c,
                        SecurityLevel::NoAuthNoPriv,
                        |a| a.notify_view("all"),
                    )
                    .access(
                        "denied",
                        SecurityModel::V2c,
                        SecurityLevel::NoAuthNoPriv,
                        |a| a.notify_view("empty"),
                    )
                    .view("all", |view| view.include(oid!(1, 3, 6)))
                    .view("empty", |view| view)
            })
            .build()
            .await
            .unwrap();
        let outcome = mixed.send_trap(&trap_oid, 0, vec![]).await;
        assert!(matches!(outcome.sinks()[0].status, SinkStatus::Succeeded));
        assert!(matches!(
            outcome.sinks()[1].status,
            SinkStatus::Skipped(SinkSkipReason::NotInNotifyView)
        ));

        let denied_inform = Agent::builder()
            .bind("127.0.0.1:0")
            .trap_sink(
                NotificationSinkId::new("denied").unwrap(),
                "127.0.0.1:9",
                Auth::v2c("denied"),
            )
            .vacm(|v| {
                v.group("denied", SecurityModel::V2c, "denied")
                    .access(
                        "denied",
                        SecurityModel::V2c,
                        SecurityLevel::NoAuthNoPriv,
                        |a| a.notify_view("empty"),
                    )
                    .view("empty", |view| view)
            })
            .build()
            .await
            .unwrap()
            .send_inform(&trap_oid, 0, vec![])
            .await;
        assert!(matches!(
            denied_inform.sinks()[0].status,
            SinkStatus::Skipped(SinkSkipReason::NotInNotifyView)
        ));

        let denied_v1_inform = Agent::builder()
            .bind("127.0.0.1:0")
            .trap_sink(
                NotificationSinkId::new("denied-v1").unwrap(),
                "127.0.0.1:9",
                Auth::v1("denied"),
            )
            .vacm(|v| v)
            .build()
            .await
            .unwrap()
            .send_inform(&trap_oid, 0, vec![])
            .await;
        assert!(matches!(
            denied_v1_inform.sinks()[0].status,
            SinkStatus::Skipped(SinkSkipReason::InformUnsupportedForV1)
        ));
    }

    #[tokio::test]
    async fn public_agent_notification_path_rejects_receive_only_values() {
        let agent = Agent::builder()
            .bind("127.0.0.1:0")
            .community(b"public")
            .trap_sink(
                NotificationSinkId::new("public").unwrap(),
                "127.0.0.1:9",
                Auth::v2c("public"),
            )
            .allow_all_access()
            .build()
            .await
            .unwrap();
        let malformed = VarBind::new(
            oid!(1, 3, 6, 1, 4, 1, 9999, 1),
            Value::Unknown {
                tag: 0x48,
                data: Bytes::from_static(b"raw"),
            },
        );

        let outcome = agent
            .send_trap(&oid!(1, 3, 6, 1, 6, 3, 1, 1, 5, 1), 0, vec![malformed])
            .await;
        assert_eq!(outcome.len(), 1);
        match &outcome.sinks()[0].status {
            SinkStatus::Failed(error) => {
                assert!(matches!(&**error, Error::InvalidMessage(_)));
            }
            status => panic!("expected outbound validation failure, got {status:?}"),
        }
    }

    #[tokio::test]
    async fn unpolled_trap_stream_does_not_allocate_request_id() {
        let agent = Agent::builder()
            .bind("127.0.0.1:0")
            .trap_sink(
                NotificationSinkId::new("lazy").unwrap(),
                "127.0.0.1:9",
                Auth::v1("public"),
            )
            .build()
            .await
            .unwrap();
        let trap_oid = oid!(1, 3, 6, 1, 6, 3, 1, 1, 5, 1);

        let stream = agent.send_trap_stream(&trap_oid, 0, vec![]);
        drop(stream);

        let mut stream = agent.send_trap_stream(&trap_oid, 0, vec![]);
        assert!(matches!(
            stream.next().await.unwrap().status,
            SinkStatus::Succeeded
        ));
        assert_eq!(agent.next_notification_id(), 2);
    }

    #[tokio::test]
    async fn trap_stream_admits_at_most_the_configured_fanout_limit() {
        let mut builder = Agent::builder()
            .bind("127.0.0.1:0")
            .notification_fanout_limit(2);
        for index in 0..5 {
            builder = builder.trap_sink(
                NotificationSinkId::new(format!("sink-{index}")).unwrap(),
                format!("127.0.0.1:{}", 20_000 + index),
                Auth::v2c("public"),
            );
        }
        let agent = builder.build().await.unwrap();
        let trap_oid = oid!(1, 3, 6, 1, 6, 3, 1, 1, 5, 1);
        let mut stream = agent.send_trap_stream(&trap_oid, 0, vec![]);

        assert_eq!(stream.pending.len(), 0);
        stream.admit();
        assert_eq!(stream.pending.len(), 2);
        assert_eq!(stream.next_sink, 2);

        let first = stream.next().await.unwrap();
        assert!(matches!(first.status, SinkStatus::Succeeded));
        assert!(stream.pending.len() <= 2);
        stream.admit();
        assert_eq!(stream.pending.len(), 2);
        assert_eq!(stream.next_sink, 3);

        let outcome = stream.into_outcome().await;
        assert_eq!(outcome.len(), 4);
        assert!(outcome.all_succeeded());
    }

    #[tokio::test(start_paused = true)]
    async fn notification_stream_yields_admitted_futures_in_completion_order() {
        let agent = Agent::builder().bind("127.0.0.1:0").build().await.unwrap();
        let pending = FuturesUnordered::new();
        for (index, delay) in [(0, 20), (1, 1)] {
            let mut sink = test_sink(Auth::v2c("public")).summary;
            sink.index = index;
            pending.push(Box::pin(async move {
                tokio::time::sleep(std::time::Duration::from_millis(delay)).await;
                SinkOutcome {
                    sink,
                    status: SinkStatus::Succeeded,
                    metadata: crate::client::ResponseMetadata::default(),
                }
            }) as PendingSinkOutcome<'_>);
        }
        let trap_oid = Arc::new(oid!(1, 3, 6, 1, 6, 3, 1, 1, 5, 1));
        let mut stream = NotificationSendStream {
            agent: &agent,
            operation: NotificationOperation::Trap {
                trap_oid,
                uptime: 0,
                varbinds: Arc::from([]),
            },
            next_sink: 0,
            admission_limit: 2,
            pending,
        };

        assert_eq!(stream.next().await.unwrap().sink.index(), 1);
        assert_eq!(stream.next().await.unwrap().sink.index(), 0);
    }

    #[tokio::test]
    async fn test_notification_ids_are_per_agent() {
        // Each Agent must own its own notification id sequence; two independent
        // agents must not share a process-global counter.
        let agent_a = Agent::builder()
            .bind("127.0.0.1:0")
            .community(b"public")
            .allow_all_access()
            .build()
            .await
            .unwrap();
        let agent_b = Agent::builder()
            .bind("127.0.0.1:0")
            .community(b"public")
            .allow_all_access()
            .build()
            .await
            .unwrap();

        // Advance agent_a's sequence a few times.
        let a1 = agent_a.next_notification_id();
        let a2 = agent_a.next_notification_id();
        let a3 = agent_a.next_notification_id();
        assert_eq!((a1, a2, a3), (1, 2, 3));

        // agent_b is unaffected by agent_a's advancement and starts fresh.
        let b1 = agent_b.next_notification_id();
        let b2 = agent_b.next_notification_id();
        assert_eq!((b1, b2), (1, 2));

        // agent_a continues its own monotonic sequence.
        assert_eq!(agent_a.next_notification_id(), 4);
    }
}