sz-orm-core 1.0.0

Core ORM engine: Model trait, ActiveRecord, QueryBuilder, Pool, Transaction, migration, and SQL dialect abstraction
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
//! Observer + Event Subscriber — 模型生命周期观察者模式
//!
//! 对应文档 6.8 节改进项 32(Observer)+ 33(Event Subscriber)。
//!
//! # 核心概念
//!
//! - **Observer**:观察者接口,订阅模型生命周期事件(INSERT/UPDATE/DELETE/FIND)
//! - **EventSubscriber**:事件订阅者,按事件类型订阅(比 Observer 更细粒度)
//! - **EventDispatcher**:事件分发器,管理 Observer 与 EventSubscriber 的注册和分发
//!
//! # 与 Behaviors 的区别
//!
//! | 特性 | Behaviors (behaviors.rs) | Observer (本模块) |
//! |------|--------------------------|-------------------|
//! | 注册方式 | Model 内部声明 | 外部注册到 Dispatcher |
//! | 解耦程度 | Model 与 Behavior 强耦合 | 完全解耦,Model 无需感知 |
//! | 适用场景 | 字段自动填充(时间戳/操作人) | 审计日志、缓存失效、外部通知 |
//! | 事件粒度 | 4 个生命周期事件 | 可订阅特定事件类型 |
//!
//! # 设计灵感
//!
//! - Doctrine `EventSubscriber` / `LifecycleCallback`
//! - Hibernate `EntityListener` / `@PostPersist`
//! - Laravel Eloquent `Observer` 类
//! - Rails ActiveRecord `Callbacks` + `Observers`
//!
//! # 使用示例
//!
//! ```
//! use sz_orm_core::observer::{
//!     Event, EventDispatcher, EventSubscriber, Observer, SubscriberResult,
//! };
//! use sz_orm_core::hooks::HookContext;
//! use std::collections::HashMap;
//! use std::sync::{Arc, Mutex};
//! use sz_orm_core::Value;
//!
//! // 1. 审计日志订阅者(订阅所有事件)
//! struct AuditLogSubscriber {
//!     logs: Arc<Mutex<Vec<String>>>,
//! }
//!
//! impl EventSubscriber for AuditLogSubscriber {
//!     fn subscribed_events(&self) -> Vec<Event> {
//!         vec![Event::AfterInsert, Event::AfterUpdate, Event::AfterDelete]
//!     }
//!
//!     fn on_event(&self, event: Event, ctx: &HookContext, attrs: &HashMap<String, Value>) -> SubscriberResult<()> {
//!         let mut logs = self.logs.lock().unwrap();
//!         logs.push(format!("{:?} on attrs with {} fields", event, attrs.len()));
//!         Ok(())
//!     }
//! }
//!
//! // 2. 缓存失效订阅者(仅订阅写入事件)
//! struct CacheInvalidationSubscriber;
//!
//! impl EventSubscriber for CacheInvalidationSubscriber {
//!     fn subscribed_events(&self) -> Vec<Event> {
//!         vec![Event::AfterUpdate, Event::AfterDelete]
//!     }
//!
//!     fn on_event(&self, event: Event, _ctx: &HookContext, attrs: &HashMap<String, Value>) -> SubscriberResult<()> {
//!         // 失效缓存逻辑...
//!         let _ = (event, attrs);
//!         Ok(())
//!     }
//! }
//!
//! // 3. 注册并触发事件
//! let logs = Arc::new(Mutex::new(Vec::new()));
//! let mut dispatcher = EventDispatcher::new();
//! dispatcher.subscribe(Box::new(AuditLogSubscriber { logs: logs.clone() }));
//! dispatcher.subscribe(Box::new(CacheInvalidationSubscriber));
//!
//! let ctx = HookContext::default();
//! let attrs = HashMap::new();
//! dispatcher.dispatch(Event::AfterInsert, &ctx, &attrs);
//!
//! assert_eq!(logs.lock().unwrap().len(), 1);
//! ```

use crate::hooks::HookContext;
use crate::Value;
use std::collections::HashMap;
use std::sync::{Arc, RwLock};

// ============================================================================
// Event — 事件类型
// ============================================================================

/// 模型生命周期事件类型
///
/// 与 `hooks::HookEvent` 类似但简化为运行时分发用的事件枚举。
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Event {
    /// 插入前
    BeforeInsert,
    /// 插入后
    AfterInsert,
    /// 更新前
    BeforeUpdate,
    /// 更新后
    AfterUpdate,
    /// 删除前
    BeforeDelete,
    /// 删除后
    AfterDelete,
    /// 单行查询后
    AfterFind,
    /// 软删除恢复前
    BeforeRestore,
    /// 软删除恢复后
    AfterRestore,
}

impl Event {
    /// 是否为 before 事件
    pub fn is_before(&self) -> bool {
        matches!(
            self,
            Event::BeforeInsert | Event::BeforeUpdate | Event::BeforeDelete | Event::BeforeRestore
        )
    }

    /// 是否为 after 事件
    pub fn is_after(&self) -> bool {
        matches!(
            self,
            Event::AfterInsert
                | Event::AfterUpdate
                | Event::AfterDelete
                | Event::AfterFind
                | Event::AfterRestore
        )
    }

    /// 是否为写入事件(INSERT/UPDATE/DELETE)
    pub fn is_write_event(&self) -> bool {
        matches!(
            self,
            Event::BeforeInsert
                | Event::AfterInsert
                | Event::BeforeUpdate
                | Event::AfterUpdate
                | Event::BeforeDelete
                | Event::AfterDelete
        )
    }

    /// 事件名称(用于日志与错误信息)
    pub fn name(&self) -> &'static str {
        match self {
            Event::BeforeInsert => "before_insert",
            Event::AfterInsert => "after_insert",
            Event::BeforeUpdate => "before_update",
            Event::AfterUpdate => "after_update",
            Event::BeforeDelete => "before_delete",
            Event::AfterDelete => "after_delete",
            Event::AfterFind => "after_find",
            Event::BeforeRestore => "before_restore",
            Event::AfterRestore => "after_restore",
        }
    }
}

// ============================================================================
// SubscriberError — 订阅者错误
// ============================================================================

/// 订阅者错误类型
#[derive(Debug)]
pub enum SubscriberError {
    /// 订阅者执行失败(携带错误描述)
    Failed {
        /// 订阅者名称
        subscriber: String,
        /// 错误描述
        reason: String,
    },
    /// 中止后续订阅者执行(用于 veto 模式)
    ///
    /// 例如:before_insert 钩子拒绝该次插入
    Vetoed {
        /// 订阅者名称
        subscriber: String,
        /// 拒绝原因
        reason: String,
    },
}

impl std::fmt::Display for SubscriberError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            SubscriberError::Failed { subscriber, reason } => {
                write!(f, "Subscriber `{}` failed: {}", subscriber, reason)
            }
            SubscriberError::Vetoed { subscriber, reason } => {
                write!(f, "Subscriber `{}` vetoed: {}", subscriber, reason)
            }
        }
    }
}

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

/// 订阅者结果类型
pub type SubscriberResult<T> = Result<T, SubscriberError>;

// ============================================================================
// Observer — 模型观察者 trait
// ============================================================================

/// 模型观察者 trait
///
/// 与 `EventSubscriber` 不同,`Observer` 默认订阅所有事件。
/// 适合需要监控所有生命周期事件的场景(如审计日志)。
///
/// # 实现要点
///
/// - 所有方法默认实现为 no-op,按需 override
/// - 任何方法返回 `Err(SubscriberError::Vetoed)` 会中止 before 事件的后续执行
pub trait Observer: Send + Sync {
    /// 观察者名称(用于日志与错误信息)
    fn name(&self) -> &str {
        "anonymous_observer"
    }

    /// 插入前
    fn before_insert(
        &self,
        _ctx: &HookContext,
        _attrs: &mut HashMap<String, Value>,
    ) -> SubscriberResult<()> {
        Ok(())
    }

    /// 插入后
    fn after_insert(
        &self,
        _ctx: &HookContext,
        _attrs: &HashMap<String, Value>,
    ) -> SubscriberResult<()> {
        Ok(())
    }

    /// 更新前
    fn before_update(
        &self,
        _ctx: &HookContext,
        _attrs: &mut HashMap<String, Value>,
    ) -> SubscriberResult<()> {
        Ok(())
    }

    /// 更新后
    fn after_update(
        &self,
        _ctx: &HookContext,
        _attrs: &HashMap<String, Value>,
    ) -> SubscriberResult<()> {
        Ok(())
    }

    /// 删除前
    fn before_delete(
        &self,
        _ctx: &HookContext,
        _attrs: &HashMap<String, Value>,
    ) -> SubscriberResult<()> {
        Ok(())
    }

    /// 删除后
    fn after_delete(
        &self,
        _ctx: &HookContext,
        _attrs: &HashMap<String, Value>,
    ) -> SubscriberResult<()> {
        Ok(())
    }

    /// 单行查询后
    fn after_find(
        &self,
        _ctx: &HookContext,
        _attrs: &mut HashMap<String, Value>,
    ) -> SubscriberResult<()> {
        Ok(())
    }
}

// ============================================================================
// EventSubscriber — 事件订阅者 trait
// ============================================================================

/// 事件订阅者 trait
///
/// 与 `Observer` 不同,`EventSubscriber` 只接收订阅的特定事件。
/// 适合只关心特定事件的场景(如缓存失效仅关心 UPDATE/DELETE)。
pub trait EventSubscriber: Send + Sync {
    /// 订阅者名称
    fn name(&self) -> &str {
        "anonymous_subscriber"
    }

    /// 返回订阅的事件列表
    ///
    /// 仅当事件在此列表中时,`on_event` 才会被调用。
    fn subscribed_events(&self) -> Vec<Event>;

    /// 事件回调
    ///
    /// # 参数
    /// - `event`:触发的事件
    /// - `ctx`:钩子上下文
    /// - `attrs`:当前属性(before 事件可修改)
    ///
    /// # 返回
    /// - `Ok(())`:继续执行后续订阅者
    /// - `Err(SubscriberError::Vetoed)`:中止 before 事件的后续执行
    /// - `Err(SubscriberError::Failed)`:记录错误,继续执行后续订阅者
    fn on_event(
        &self,
        event: Event,
        ctx: &HookContext,
        attrs: &HashMap<String, Value>,
    ) -> SubscriberResult<()>;
}

// ============================================================================
// EventDispatcher — 事件分发器
// ============================================================================

/// 事件分发器
///
/// 管理 `Observer` 与 `EventSubscriber` 的注册与分发。
///
/// # 分发顺序
///
/// 1. 先按注册顺序调用所有 `Observer` 的对应方法
/// 2. 再按注册顺序调用所有订阅了该事件的 `EventSubscriber`
///
/// # 错误处理
///
/// - `before_*` 事件中任何订阅者返回 `Err(Vetoed)` 会立即中止后续执行
/// - `after_*` 事件中的错误仅记录,不影响后续执行
///
/// # 线程安全
///
/// 内部使用 `RwLock<Vec<Arc<...>>>`,支持多线程并发。
///
/// # 死锁防护(v0.2.1 修复 Critical C-3)
///
/// `dispatch` / `dispatch_before_mut` 在调用用户回调前会先 clone 一份
/// `Vec<Arc<dyn ...>>` 快照并释放读锁,避免持读锁调用用户代码——
/// 否则用户回调中若尝试注册新订阅者(需要写锁)会自我死锁。
pub struct EventDispatcher {
    observers: RwLock<Vec<Arc<dyn Observer>>>,
    subscribers: RwLock<Vec<Arc<dyn EventSubscriber>>>,
    /// 错误收集(非致命错误,不影响流程)
    errors: RwLock<Vec<SubscriberError>>,
    /// 错误缓冲区最大容量(防止内存无限增长)
    ///
    /// 当 errors 长度达到此上限时,新增错误会以 FIFO 方式淘汰最早错误。
    /// 默认 1024,可通过 `with_max_errors` 调整。
    max_errors: usize,
}

/// 默认错误缓冲区容量
const DEFAULT_MAX_ERRORS: usize = 1024;

impl EventDispatcher {
    /// 创建空的事件分发器
    pub fn new() -> Self {
        Self {
            observers: RwLock::new(Vec::new()),
            subscribers: RwLock::new(Vec::new()),
            errors: RwLock::new(Vec::new()),
            max_errors: DEFAULT_MAX_ERRORS,
        }
    }

    /// 设置错误缓冲区最大容量
    ///
    /// 当 errors 达到此容量时,新增错误会淘汰最早错误(FIFO)。
    /// 设置为 0 表示无限制(不推荐,可能导致内存泄漏)。
    pub fn with_max_errors(mut self, max_errors: usize) -> Self {
        self.max_errors = max_errors;
        self
    }

    /// 注册 Observer
    ///
    /// 接收 `Box<dyn Observer>`(向后兼容),内部转 `Arc<dyn Observer>` 存储,
    /// 以便 dispatch 时可以 cheap clone 快照后释放读锁。
    pub fn add_observer(&self, observer: Box<dyn Observer>) {
        let arc: Arc<dyn Observer> = Arc::from(observer);
        self.observers.write().unwrap().push(arc);
    }

    /// 注册 EventSubscriber
    ///
    /// 接收 `Box<dyn EventSubscriber>`(向后兼容),内部转 `Arc<dyn EventSubscriber>` 存储。
    pub fn subscribe(&self, subscriber: Box<dyn EventSubscriber>) {
        let arc: Arc<dyn EventSubscriber> = Arc::from(subscriber);
        self.subscribers.write().unwrap().push(arc);
    }

    /// 清空所有注册
    pub fn clear(&self) {
        self.observers.write().unwrap().clear();
        self.subscribers.write().unwrap().clear();
        self.errors.write().unwrap().clear();
    }

    /// 返回已注册的 Observer 数量
    pub fn observer_count(&self) -> usize {
        self.observers.read().unwrap().len()
    }

    /// 返回已注册的 EventSubscriber 数量
    pub fn subscriber_count(&self) -> usize {
        self.subscribers.read().unwrap().len()
    }

    /// 取出收集到的非致命错误(清空内部缓冲)
    pub fn drain_errors(&self) -> Vec<SubscriberError> {
        std::mem::take(&mut *self.errors.write().unwrap())
    }

    /// 返回当前错误缓冲区中的错误数量
    pub fn error_count(&self) -> usize {
        self.errors.read().unwrap().len()
    }

    /// 将本地错误批量写入 errors 缓冲区,遵循 max_errors 限制(FIFO 淘汰)
    ///
    /// - `max_errors = 0` 表示无限制
    /// - 否则当 errors 达到上限时,淘汰最早错误以腾出空间
    fn push_errors(&self, new_errors: Vec<SubscriberError>) {
        if new_errors.is_empty() {
            return;
        }
        let mut errors = self.errors.write().unwrap();
        if self.max_errors == 0 {
            errors.extend(new_errors);
            return;
        }
        for e in new_errors {
            if errors.len() >= self.max_errors {
                // FIFO 淘汰最早错误
                errors.remove(0);
            }
            errors.push(e);
        }
    }

    /// 分发事件(after_* 事件,attrs 不可变)
    ///
    /// 错误仅记录,不影响后续订阅者执行。
    ///
    /// # 实现要点
    ///
    /// - **v0.2.1 修复 Critical C-3**:调用用户回调前先 clone `Vec<Arc<...>>` 快照
    ///   并释放读锁,避免持读锁调用用户代码(防止死锁)
    /// - 错误先收集到本地 `Vec`,循环结束后一次性批量写入 `self.errors`
    pub fn dispatch(&self, event: Event, ctx: &HookContext, attrs: &HashMap<String, Value>) {
        let mut local_errors: Vec<SubscriberError> = Vec::new();

        // 1. 调用 Observers — 持读锁仅 clone 快照,立即释放
        let observers_snapshot: Vec<Arc<dyn Observer>> = {
            let observers = self.observers.read().unwrap();
            observers.clone()
        };
        // 释放读锁后调用用户代码
        for observer in observers_snapshot.iter() {
            let result = match event {
                Event::AfterInsert => observer.after_insert(ctx, attrs),
                Event::AfterUpdate => observer.after_update(ctx, attrs),
                Event::AfterDelete => observer.after_delete(ctx, attrs),
                _ => Ok(()),
            };
            if let Err(e) = result {
                local_errors.push(e);
            }
        }

        // 2. 调用 EventSubscribers — 持读锁仅 clone 快照,立即释放
        let subscribers_snapshot: Vec<Arc<dyn EventSubscriber>> = {
            let subscribers = self.subscribers.read().unwrap();
            subscribers.clone()
        };
        for subscriber in subscribers_snapshot.iter() {
            if !subscriber.subscribed_events().contains(&event) {
                continue;
            }
            if let Err(e) = subscriber.on_event(event, ctx, attrs) {
                local_errors.push(e);
            }
        }

        if !local_errors.is_empty() {
            self.push_errors(local_errors);
        }
    }

    /// 分发 before 事件(attrs 可变)
    ///
    /// 任何订阅者返回 `Err(Vetoed)` 会立即中止并返回错误。
    ///
    /// # 实现要点
    ///
    /// - Vetoed 时直接返回该错误,**不会再次调用 `on_event`**(避免订阅者副作用翻倍)
    /// - **v0.2.1 修复 Critical C-3**:调用用户回调前先 clone 快照并释放读锁
    /// - 错误先收集到本地 `Vec`,避免持读锁时获取写锁造成死锁
    pub fn dispatch_before_mut(
        &self,
        event: Event,
        ctx: &HookContext,
        attrs: &mut HashMap<String, Value>,
    ) -> SubscriberResult<()> {
        let mut local_errors: Vec<SubscriberError> = Vec::new();
        let mut vetoed: Option<SubscriberError> = None;

        // 1. 调用 Observers — 持读锁仅 clone 快照,立即释放
        let observers_snapshot: Vec<Arc<dyn Observer>> = {
            let observers = self.observers.read().unwrap();
            observers.clone()
        };
        for observer in observers_snapshot.iter() {
            let result = match event {
                Event::BeforeInsert => observer.before_insert(ctx, attrs),
                Event::BeforeUpdate => observer.before_update(ctx, attrs),
                _ => Ok(()),
            };
            match result {
                Ok(()) => {}
                Err(e @ SubscriberError::Vetoed { .. }) => {
                    vetoed = Some(e);
                    break;
                }
                Err(e) => local_errors.push(e),
            }
        }

        // 2. 调用 EventSubscribers(仅当未被 vetoed)— 持读锁仅 clone 快照,立即释放
        if vetoed.is_none() {
            let subscribers_snapshot: Vec<Arc<dyn EventSubscriber>> = {
                let subscribers = self.subscribers.read().unwrap();
                subscribers.clone()
            };
            for subscriber in subscribers_snapshot.iter() {
                if !subscriber.subscribed_events().contains(&event) {
                    continue;
                }
                match subscriber.on_event(event, ctx, attrs) {
                    Ok(()) => {}
                    Err(e @ SubscriberError::Vetoed { .. }) => {
                        vetoed = Some(e);
                        break;
                    }
                    Err(e) => local_errors.push(e),
                }
            }
        }

        if !local_errors.is_empty() {
            self.push_errors(local_errors);
        }

        if let Some(e) = vetoed {
            return Err(e);
        }
        Ok(())
    }

    /// 分发 after_find 事件(attrs 可变,用于修改读出的数据)
    ///
    /// # 实现要点
    ///
    /// - **v0.2.1 修复 Critical C-3**:调用用户回调前先 clone 快照并释放读锁
    /// - 错误先收集到本地 `Vec`,避免持读锁时获取写锁造成死锁
    pub fn dispatch_after_find(
        &self,
        ctx: &HookContext,
        attrs: &mut HashMap<String, Value>,
    ) -> SubscriberResult<()> {
        let mut local_errors: Vec<SubscriberError> = Vec::new();

        let observers_snapshot: Vec<Arc<dyn Observer>> = {
            let observers = self.observers.read().unwrap();
            observers.clone()
        };
        for observer in observers_snapshot.iter() {
            if let Err(e) = observer.after_find(ctx, attrs) {
                local_errors.push(e);
            }
        }

        let subscribers_snapshot: Vec<Arc<dyn EventSubscriber>> = {
            let subscribers = self.subscribers.read().unwrap();
            subscribers.clone()
        };
        for subscriber in subscribers_snapshot.iter() {
            if !subscriber.subscribed_events().contains(&Event::AfterFind) {
                continue;
            }
            if let Err(e) = subscriber.on_event(Event::AfterFind, ctx, attrs) {
                local_errors.push(e);
            }
        }

        if !local_errors.is_empty() {
            self.push_errors(local_errors);
        }

        Ok(())
    }
}

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

// ============================================================================
// 内置订阅者实现
// ============================================================================

// -------------------- AuditLogSubscriber --------------------

/// 审计日志订阅者
///
/// 记录所有写入操作到内部日志缓冲,可用于调试或审计。
///
/// # 示例
///
/// ```
/// use sz_orm_core::observer::{EventDispatcher, AuditLogSubscriber, Event};
/// use sz_orm_core::hooks::HookContext;
/// use std::collections::HashMap;
///
/// let audit = AuditLogSubscriber::new();
/// let mut dispatcher = EventDispatcher::new();
/// dispatcher.subscribe(Box::new(audit.clone()));
///
/// let ctx = HookContext::default();
/// let attrs = HashMap::new();
/// dispatcher.dispatch(Event::AfterInsert, &ctx, &attrs);
///
/// assert_eq!(audit.logs().lock().unwrap().len(), 1);
/// ```
#[derive(Clone)]
pub struct AuditLogSubscriber {
    logs: std::sync::Arc<std::sync::Mutex<Vec<String>>>,
}

impl AuditLogSubscriber {
    /// 创建审计日志订阅者
    pub fn new() -> Self {
        Self {
            logs: std::sync::Arc::new(std::sync::Mutex::new(Vec::new())),
        }
    }

    /// 获取日志列表(用于断言)
    pub fn logs(&self) -> &std::sync::Arc<std::sync::Mutex<Vec<String>>> {
        &self.logs
    }
}

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

impl EventSubscriber for AuditLogSubscriber {
    fn name(&self) -> &str {
        "audit_log"
    }

    fn subscribed_events(&self) -> Vec<Event> {
        vec![Event::AfterInsert, Event::AfterUpdate, Event::AfterDelete]
    }

    fn on_event(
        &self,
        event: Event,
        ctx: &HookContext,
        attrs: &HashMap<String, Value>,
    ) -> SubscriberResult<()> {
        let mut logs = self.logs.lock().unwrap();
        logs.push(format!(
            "event={} operator={:?} field_count={}",
            event.name(),
            ctx.operator_id,
            attrs.len()
        ));
        Ok(())
    }
}

// ============================================================================
// 单元测试
// ============================================================================

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

    // ===== Event 测试 =====

    #[test]
    fn test_event_is_before_after() {
        assert!(Event::BeforeInsert.is_before());
        assert!(!Event::BeforeInsert.is_after());
        assert!(Event::AfterInsert.is_after());
        assert!(!Event::AfterInsert.is_before());
    }

    #[test]
    fn test_event_is_write_event() {
        assert!(Event::BeforeInsert.is_write_event());
        assert!(Event::AfterUpdate.is_write_event());
        assert!(Event::BeforeDelete.is_write_event());
        assert!(!Event::AfterFind.is_write_event());
    }

    #[test]
    fn test_event_name() {
        assert_eq!(Event::BeforeInsert.name(), "before_insert");
        assert_eq!(Event::AfterDelete.name(), "after_delete");
        assert_eq!(Event::AfterFind.name(), "after_find");
    }

    // ===== EventDispatcher 基础测试 =====

    #[test]
    fn test_new_dispatcher_is_empty() {
        let d = EventDispatcher::new();
        assert_eq!(d.observer_count(), 0);
        assert_eq!(d.subscriber_count(), 0);
    }

    #[test]
    fn test_add_observer() {
        struct DummyObserver;
        impl Observer for DummyObserver {}

        let d = EventDispatcher::new();
        d.add_observer(Box::new(DummyObserver));
        assert_eq!(d.observer_count(), 1);
    }

    #[test]
    fn test_subscribe() {
        struct DummySubscriber;
        impl EventSubscriber for DummySubscriber {
            fn subscribed_events(&self) -> Vec<Event> {
                vec![Event::AfterInsert]
            }
            fn on_event(
                &self,
                _event: Event,
                _ctx: &HookContext,
                _attrs: &HashMap<String, Value>,
            ) -> SubscriberResult<()> {
                Ok(())
            }
        }

        let d = EventDispatcher::new();
        d.subscribe(Box::new(DummySubscriber));
        assert_eq!(d.subscriber_count(), 1);
    }

    #[test]
    fn test_clear() {
        struct DummyObserver;
        impl Observer for DummyObserver {}

        let d = EventDispatcher::new();
        d.add_observer(Box::new(DummyObserver));
        d.clear();
        assert_eq!(d.observer_count(), 0);
    }

    // ===== Observer 触发测试 =====

    /// 计数 Observer,用于测试
    struct CountingObserver {
        insert_count: Arc<Mutex<u32>>,
        update_count: Arc<Mutex<u32>>,
        delete_count: Arc<Mutex<u32>>,
    }

    impl Observer for CountingObserver {
        fn name(&self) -> &str {
            "counting"
        }

        fn after_insert(
            &self,
            _ctx: &HookContext,
            _attrs: &HashMap<String, Value>,
        ) -> SubscriberResult<()> {
            *self.insert_count.lock().unwrap() += 1;
            Ok(())
        }

        fn after_update(
            &self,
            _ctx: &HookContext,
            _attrs: &HashMap<String, Value>,
        ) -> SubscriberResult<()> {
            *self.update_count.lock().unwrap() += 1;
            Ok(())
        }

        fn after_delete(
            &self,
            _ctx: &HookContext,
            _attrs: &HashMap<String, Value>,
        ) -> SubscriberResult<()> {
            *self.delete_count.lock().unwrap() += 1;
            Ok(())
        }
    }

    #[test]
    fn test_observer_triggered_on_dispatch() {
        let insert = Arc::new(Mutex::new(0u32));
        let update = Arc::new(Mutex::new(0u32));
        let delete = Arc::new(Mutex::new(0u32));

        let observer = CountingObserver {
            insert_count: insert.clone(),
            update_count: update.clone(),
            delete_count: delete.clone(),
        };

        let d = EventDispatcher::new();
        d.add_observer(Box::new(observer));

        let ctx = HookContext::default();
        let attrs = HashMap::new();

        d.dispatch(Event::AfterInsert, &ctx, &attrs);
        d.dispatch(Event::AfterInsert, &ctx, &attrs);
        d.dispatch(Event::AfterUpdate, &ctx, &attrs);
        d.dispatch(Event::AfterDelete, &ctx, &attrs);

        assert_eq!(*insert.lock().unwrap(), 2);
        assert_eq!(*update.lock().unwrap(), 1);
        assert_eq!(*delete.lock().unwrap(), 1);
    }

    #[test]
    fn test_observer_before_event_can_modify_attrs() {
        struct TimestampInjector;
        impl Observer for TimestampInjector {
            fn before_insert(
                &self,
                _ctx: &HookContext,
                attrs: &mut HashMap<String, Value>,
            ) -> SubscriberResult<()> {
                attrs.insert(
                    "created_at".to_string(),
                    Value::String("2026-07-19".to_string()),
                );
                Ok(())
            }
        }

        let d = EventDispatcher::new();
        d.add_observer(Box::new(TimestampInjector));

        let ctx = HookContext::default();
        let mut attrs = HashMap::new();
        d.dispatch_before_mut(Event::BeforeInsert, &ctx, &mut attrs)
            .unwrap();

        assert_eq!(
            attrs.get("created_at"),
            Some(&Value::String("2026-07-19".to_string()))
        );
    }

    // ===== EventSubscriber 测试 =====

    /// 只订阅 AfterInsert 的订阅者
    struct InsertOnlySubscriber {
        called: Arc<Mutex<u32>>,
    }

    impl EventSubscriber for InsertOnlySubscriber {
        fn name(&self) -> &str {
            "insert_only"
        }

        fn subscribed_events(&self) -> Vec<Event> {
            vec![Event::AfterInsert]
        }

        fn on_event(
            &self,
            _event: Event,
            _ctx: &HookContext,
            _attrs: &HashMap<String, Value>,
        ) -> SubscriberResult<()> {
            *self.called.lock().unwrap() += 1;
            Ok(())
        }
    }

    #[test]
    fn test_subscriber_only_called_for_subscribed_events() {
        let called = Arc::new(Mutex::new(0u32));
        let subscriber = InsertOnlySubscriber {
            called: called.clone(),
        };

        let d = EventDispatcher::new();
        d.subscribe(Box::new(subscriber));

        let ctx = HookContext::default();
        let attrs = HashMap::new();

        // AfterInsert 应触发
        d.dispatch(Event::AfterInsert, &ctx, &attrs);
        // AfterUpdate 不应触发(未订阅)
        d.dispatch(Event::AfterUpdate, &ctx, &attrs);
        // AfterDelete 不应触发
        d.dispatch(Event::AfterDelete, &ctx, &attrs);
        // 再触发一次 AfterInsert
        d.dispatch(Event::AfterInsert, &ctx, &attrs);

        assert_eq!(*called.lock().unwrap(), 2);
    }

    #[test]
    fn test_subscriber_veto_aborts_before_event() {
        struct VetoSubscriber;
        impl EventSubscriber for VetoSubscriber {
            fn name(&self) -> &str {
                "veto"
            }
            fn subscribed_events(&self) -> Vec<Event> {
                vec![Event::BeforeInsert]
            }
            fn on_event(
                &self,
                _event: Event,
                _ctx: &HookContext,
                _attrs: &HashMap<String, Value>,
            ) -> SubscriberResult<()> {
                Err(SubscriberError::Vetoed {
                    subscriber: "veto".to_string(),
                    reason: "Business rule violation".to_string(),
                })
            }
        }

        let d = EventDispatcher::new();
        d.subscribe(Box::new(VetoSubscriber));

        let ctx = HookContext::default();
        let mut attrs = HashMap::new();
        let result = d.dispatch_before_mut(Event::BeforeInsert, &ctx, &mut attrs);

        assert!(matches!(result, Err(SubscriberError::Vetoed { .. })));
    }

    #[test]
    fn test_subscriber_failed_does_not_abort_after_event() {
        struct FailingSubscriber;
        impl EventSubscriber for FailingSubscriber {
            fn name(&self) -> &str {
                "failing"
            }
            fn subscribed_events(&self) -> Vec<Event> {
                vec![Event::AfterInsert]
            }
            fn on_event(
                &self,
                _event: Event,
                _ctx: &HookContext,
                _attrs: &HashMap<String, Value>,
            ) -> SubscriberResult<()> {
                Err(SubscriberError::Failed {
                    subscriber: "failing".to_string(),
                    reason: "Connection lost".to_string(),
                })
            }
        }

        struct CountingSubscriber {
            called: Arc<Mutex<u32>>,
        }
        impl EventSubscriber for CountingSubscriber {
            fn name(&self) -> &str {
                "counting"
            }
            fn subscribed_events(&self) -> Vec<Event> {
                vec![Event::AfterInsert]
            }
            fn on_event(
                &self,
                _event: Event,
                _ctx: &HookContext,
                _attrs: &HashMap<String, Value>,
            ) -> SubscriberResult<()> {
                *self.called.lock().unwrap() += 1;
                Ok(())
            }
        }

        let called = Arc::new(Mutex::new(0u32));
        let d = EventDispatcher::new();
        d.subscribe(Box::new(FailingSubscriber));
        d.subscribe(Box::new(CountingSubscriber {
            called: called.clone(),
        }));

        let ctx = HookContext::default();
        let attrs = HashMap::new();
        d.dispatch(Event::AfterInsert, &ctx, &attrs);

        // 即使 FailingSubscriber 失败,CountingSubscriber 仍应被调用
        assert_eq!(*called.lock().unwrap(), 1);
    }

    // ===== AuditLogSubscriber 测试 =====

    #[test]
    fn test_audit_log_subscriber() {
        let audit = AuditLogSubscriber::new();
        let audit_clone = audit.clone();

        let d = EventDispatcher::new();
        d.subscribe(Box::new(audit_clone));

        let ctx = HookContext {
            operator_id: Some(42),
            ..Default::default()
        };
        let mut attrs = HashMap::new();
        attrs.insert("name".to_string(), Value::String("alice".to_string()));

        d.dispatch(Event::AfterInsert, &ctx, &attrs);
        d.dispatch(Event::AfterUpdate, &ctx, &attrs);
        d.dispatch(Event::AfterDelete, &ctx, &attrs);
        // AfterFind 不在订阅列表,不应记录
        d.dispatch_after_find(&ctx, &mut attrs).unwrap();

        let logs = audit.logs().lock().unwrap();
        assert_eq!(logs.len(), 3);
        assert!(logs[0].contains("event=after_insert"));
        assert!(logs[0].contains("operator=Some(42)"));
        assert!(logs[0].contains("field_count=1"));
    }

    // ===== 多订阅者协同测试 =====

    #[test]
    fn test_multiple_subscribers_and_observers() {
        let sub1_called = Arc::new(Mutex::new(0u32));
        let sub2_called = Arc::new(Mutex::new(0u32));
        let obs_called = Arc::new(Mutex::new(0u32));

        struct Sub1(Arc<Mutex<u32>>);
        impl EventSubscriber for Sub1 {
            fn name(&self) -> &str {
                "sub1"
            }
            fn subscribed_events(&self) -> Vec<Event> {
                vec![Event::AfterInsert]
            }
            fn on_event(
                &self,
                _e: Event,
                _c: &HookContext,
                _a: &HashMap<String, Value>,
            ) -> SubscriberResult<()> {
                *self.0.lock().unwrap() += 1;
                Ok(())
            }
        }

        struct Sub2(Arc<Mutex<u32>>);
        impl EventSubscriber for Sub2 {
            fn name(&self) -> &str {
                "sub2"
            }
            fn subscribed_events(&self) -> Vec<Event> {
                vec![Event::AfterInsert, Event::AfterUpdate]
            }
            fn on_event(
                &self,
                _e: Event,
                _c: &HookContext,
                _a: &HashMap<String, Value>,
            ) -> SubscriberResult<()> {
                *self.0.lock().unwrap() += 1;
                Ok(())
            }
        }

        struct Obs(Arc<Mutex<u32>>);
        impl Observer for Obs {
            fn name(&self) -> &str {
                "obs"
            }
            fn after_insert(
                &self,
                _c: &HookContext,
                _a: &HashMap<String, Value>,
            ) -> SubscriberResult<()> {
                *self.0.lock().unwrap() += 1;
                Ok(())
            }
        }

        let d = EventDispatcher::new();
        d.subscribe(Box::new(Sub1(sub1_called.clone())));
        d.subscribe(Box::new(Sub2(sub2_called.clone())));
        d.add_observer(Box::new(Obs(obs_called.clone())));

        let ctx = HookContext::default();
        let attrs = HashMap::new();

        d.dispatch(Event::AfterInsert, &ctx, &attrs);

        assert_eq!(*sub1_called.lock().unwrap(), 1);
        assert_eq!(*sub2_called.lock().unwrap(), 1);
        assert_eq!(*obs_called.lock().unwrap(), 1);
    }

    // ===== 错误收集测试 =====

    #[test]
    fn test_drain_errors() {
        struct ErrSub;
        impl EventSubscriber for ErrSub {
            fn name(&self) -> &str {
                "err"
            }
            fn subscribed_events(&self) -> Vec<Event> {
                vec![Event::AfterInsert]
            }
            fn on_event(
                &self,
                _e: Event,
                _c: &HookContext,
                _a: &HashMap<String, Value>,
            ) -> SubscriberResult<()> {
                Err(SubscriberError::Failed {
                    subscriber: "err".to_string(),
                    reason: "test".to_string(),
                })
            }
        }

        let d = EventDispatcher::new();
        d.subscribe(Box::new(ErrSub));

        let ctx = HookContext::default();
        let attrs = HashMap::new();
        d.dispatch(Event::AfterInsert, &ctx, &attrs);
        d.dispatch(Event::AfterInsert, &ctx, &attrs);

        let errors = d.drain_errors();
        assert_eq!(errors.len(), 2);
        assert!(matches!(errors[0], SubscriberError::Failed { .. }));

        // drain 后内部应为空
        let errors = d.drain_errors();
        assert!(errors.is_empty());
    }

    // ===== max_errors 限制测试(防内存无限增长) =====

    #[test]
    fn test_max_errors_limits_buffer_size() {
        struct ErrSub;
        impl EventSubscriber for ErrSub {
            fn name(&self) -> &str {
                "err"
            }
            fn subscribed_events(&self) -> Vec<Event> {
                vec![Event::AfterInsert]
            }
            fn on_event(
                &self,
                _e: Event,
                _c: &HookContext,
                _a: &HashMap<String, Value>,
            ) -> SubscriberResult<()> {
                Err(SubscriberError::Failed {
                    subscriber: "err".to_string(),
                    reason: "test".to_string(),
                })
            }
        }

        // 设置 max_errors = 3,触发 5 次错误,应只保留最新 3 个
        let d = EventDispatcher::new().with_max_errors(3);
        d.subscribe(Box::new(ErrSub));

        let ctx = HookContext::default();
        let attrs = HashMap::new();
        for _ in 0..5 {
            d.dispatch(Event::AfterInsert, &ctx, &attrs);
        }

        assert_eq!(d.error_count(), 3);
        let errors = d.drain_errors();
        assert_eq!(errors.len(), 3);
    }

    #[test]
    fn test_max_errors_zero_means_unlimited() {
        struct ErrSub;
        impl EventSubscriber for ErrSub {
            fn name(&self) -> &str {
                "err"
            }
            fn subscribed_events(&self) -> Vec<Event> {
                vec![Event::AfterInsert]
            }
            fn on_event(
                &self,
                _e: Event,
                _c: &HookContext,
                _a: &HashMap<String, Value>,
            ) -> SubscriberResult<()> {
                Err(SubscriberError::Failed {
                    subscriber: "err".to_string(),
                    reason: "test".to_string(),
                })
            }
        }

        let d = EventDispatcher::new().with_max_errors(0);
        d.subscribe(Box::new(ErrSub));

        let ctx = HookContext::default();
        let attrs = HashMap::new();
        for _ in 0..10 {
            d.dispatch(Event::AfterInsert, &ctx, &attrs);
        }

        assert_eq!(d.error_count(), 10);
    }

    #[test]
    fn test_max_errors_fifo_eviction_order() {
        // 验证 FIFO 淘汰:保留的是最新错误
        struct CounterSub(Arc<Mutex<u32>>);
        impl EventSubscriber for CounterSub {
            fn name(&self) -> &str {
                "counter"
            }
            fn subscribed_events(&self) -> Vec<Event> {
                vec![Event::AfterInsert]
            }
            fn on_event(
                &self,
                _e: Event,
                _c: &HookContext,
                _a: &HashMap<String, Value>,
            ) -> SubscriberResult<()> {
                let mut n = self.0.lock().unwrap();
                *n += 1;
                Err(SubscriberError::Failed {
                    subscriber: "counter".to_string(),
                    reason: format!("call-{}", *n),
                })
            }
        }

        let counter = Arc::new(Mutex::new(0u32));
        let d = EventDispatcher::new().with_max_errors(2);
        d.subscribe(Box::new(CounterSub(counter.clone())));

        let ctx = HookContext::default();
        let attrs = HashMap::new();
        for _ in 0..4 {
            d.dispatch(Event::AfterInsert, &ctx, &attrs);
        }

        let errors = d.drain_errors();
        assert_eq!(errors.len(), 2);
        // 应保留最新的两个(call-3, call-4)
        match &errors[0] {
            SubscriberError::Failed { reason, .. } => assert_eq!(reason, "call-3"),
            other => panic!("expected Failed, got {:?}", other),
        }
        match &errors[1] {
            SubscriberError::Failed { reason, .. } => assert_eq!(reason, "call-4"),
            other => panic!("expected Failed, got {:?}", other),
        }
    }

    // ===== before 事件 Veto 测试 =====

    #[test]
    fn test_veto_aborts_subsequent_observers() {
        let second_called = Arc::new(Mutex::new(0u32));

        struct VetoObs;
        impl Observer for VetoObs {
            fn name(&self) -> &str {
                "veto"
            }
            fn before_insert(
                &self,
                _c: &HookContext,
                _a: &mut HashMap<String, Value>,
            ) -> SubscriberResult<()> {
                Err(SubscriberError::Vetoed {
                    subscriber: "veto".to_string(),
                    reason: "no".to_string(),
                })
            }
        }

        struct CountingObs(Arc<Mutex<u32>>);
        impl Observer for CountingObs {
            fn name(&self) -> &str {
                "counting"
            }
            fn before_insert(
                &self,
                _c: &HookContext,
                _a: &mut HashMap<String, Value>,
            ) -> SubscriberResult<()> {
                *self.0.lock().unwrap() += 1;
                Ok(())
            }
        }

        let d = EventDispatcher::new();
        d.add_observer(Box::new(VetoObs));
        d.add_observer(Box::new(CountingObs(second_called.clone())));

        let ctx = HookContext::default();
        let mut attrs = HashMap::new();
        let result = d.dispatch_before_mut(Event::BeforeInsert, &ctx, &mut attrs);

        assert!(result.is_err());
        // 第二个 observer 不应被调用
        assert_eq!(*second_called.lock().unwrap(), 0);
    }

    // ===== Display 测试 =====

    #[test]
    fn test_error_display() {
        let e = SubscriberError::Failed {
            subscriber: "test".to_string(),
            reason: "boom".to_string(),
        };
        assert!(e.to_string().contains("test"));
        assert!(e.to_string().contains("boom"));

        let e = SubscriberError::Vetoed {
            subscriber: "vetoer".to_string(),
            reason: "rejected".to_string(),
        };
        assert!(e.to_string().contains("vetoer"));
        assert!(e.to_string().contains("rejected"));
    }
}