confers 0.4.1

Production-ready Rust configuration library with zero boilerplate
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
<span id="top"></span>

<div align="center">

<img src="docs/image/confers.png" alt="Confers Logo" width="200" style="margin-bottom: 16px">

<p>
  <!-- CI/CD Status -->
  <a href="https://github.com/Kirky-X/confers/actions/workflows/ci.yml">
    <img src="https://github.com/Kirky-X/confers/actions/workflows/ci.yml/badge.svg" alt="CI Status" style="display:inline; margin:0 4px">
  </a>
  <!-- Version -->
  <a href="https://crates.io/crates/confers">
    <img src="https://img.shields.io/crates/v/confers.svg" alt="Version" style="display:inline; margin:0 4px">
  </a>
  <!-- Documentation -->
  <a href="https://docs.rs/confers">
    <img src="https://docs.rs/confers/badge.svg" alt="Documentation" style="display:inline; margin:0 4px">
  </a>
  <!-- Downloads -->
  <a href="https://crates.io/crates/confers">
    <img src="https://img.shields.io/crates/d/confers.svg" alt="Downloads" style="display:inline; margin:0 4px">
  </a>
  <!-- License -->
  <a href="https://github.com/Kirky-X/confers/blob/main/LICENSE">
    <img src="https://img.shields.io/crates/l/confers.svg" alt="License" style="display:inline; margin:0 4px">
  </a>
  <!-- Rust Version -->
  <a href="https://www.rust-lang.org/">
    <img src="https://img.shields.io/badge/rust-1.88+-orange.svg" alt="Rust 1.88+" style="display:inline; margin:0 4px">
  </a>
  <!-- Coverage -->
  <a href="https://codecov.io/gh/Kirky-X/confers">
    <img src="https://codecov.io/gh/Kirky-X/confers/branch/main/graph/badge.svg" alt="Coverage" style="display:inline; margin:0 4px">
  </a>
</p>

<p align="center">
  <strong>A production-ready Rust configuration library with zero boilerplate</strong>
</p>

<p align="center">
  <a href="#features" style="color:#3B82F6">✨ Features</a><a href="#quick-start" style="color:#3B82F6">🚀 Quick Start</a><a href="#documentation" style="color:#3B82F6">📚 Documentation</a><a href="#examples" style="color:#3B82F6">💻 Examples</a><a href="#contributing" style="color:#3B82F6">🤝 Contributing</a>
</p>

</div>

---

<!-- Hero Section -->

### 🎯 Zero-Boilerplate Configuration Management

Confers provides a **declarative approach** to configuration management with:

|   ✨ Type Safety    |   🔄 Auto Reload   | 🔐 XChaCha20-Poly1305 Encryption | 🌐 Remote Sources  |
| :-----------------: | :----------------: | :------------------------------: | :----------------: |
| Compile-time checks | Hot reload support |    Sensitive data protection     | etcd, Consul, HTTP |

```rust
use confers::Config;
use serde::{Deserialize, Serialize};

#[derive(Debug, Clone, Serialize, Deserialize, Config)]
#[config(validate)]
pub struct AppConfig {
    pub name: String,
    pub port: u16,
    pub debug: bool,
}

// Configuration loads automatically from files, env vars, and CLI args
let config = AppConfig::load_sync()?;
```

---

## 📋 Table of Contents

<details open style="padding:16px">
<summary style="cursor:pointer; font-weight:600; color:#1E293B">📑 Table of Contents (Click to expand)</summary>

- [✨ Features]#features
- [🚀 Quick Start]#quick-start
  - [📦 Installation]#installation
  - [💡 Basic Usage]#basic-usage
- [📚 Documentation]#documentation
- [💻 Examples]#examples
- [🏗️ Architecture]#architecture
- [⚙️ Configuration]#configuration
- [🧪 Testing]#testing
- [📊 Performance]#performance
- [🔒 Security]#security
- [🗺️ Roadmap]#roadmap
- [🤝 Contributing]#contributing
- [📄 License]#license
- [🙏 Acknowledgments]#acknowledgments

</details>

---

## <span id="features">✨ Features</span>

| 🎯 Core Features | ⚡ Optional Features |
| :--------------- | :------------------- |
| Always available | Enable as needed     |

<table style="width:100%; border-collapse: collapse">
<tr>
<td width="50%" style="vertical-align:top; padding: 16px">

### 🎯 Core Features (Always Available)

| Status | Feature                           | Description                                                       |
| :----: | --------------------------------- | ----------------------------------------------------------------- |
|| **Type-safe Configuration**       | Auto-generate config structs via derive macros (`derive` feature) |
|| **Multi-format Support**          | TOML, YAML, JSON, INI configuration files                         |
|| **Environment Variable Override** | Support environment variable overrides                            |
|| **CLI Argument Override**         | Support command-line argument overrides (`cli` feature)           |

</td>
<td width="50%" style="vertical-align:top; padding: 16px">

### ⚡ Optional Features

| Status | Feature                        | Description                                                 |
| :----: | ------------------------------ | ----------------------------------------------------------- |
|   🔍   | **Configuration Validation**   | Built-in validator integration (`validation` feature)       |
|   📊   | **Schema Generation**          | Auto-generate JSON Schema (`schema` feature)                |
|   🚀   | **File Watching & Hot Reload** | Real-time file monitoring (`watch` feature)                 |
|   🔐   | **Configuration Encryption**   | XChaCha20-Poly1305 encrypted storage (`encryption` feature) |
|   🌐   | **Remote Configuration**       | etcd, Consul, HTTP support (`remote` feature)               |
|   📦   | **Audit Logging**              | Record access & change history (`audit` feature)            |
|   🔧   | **Configuration Diff**         | Compare configs with multiple output formats                |
|   🛡️   | **Security Enhancements**      | Nonce reuse detection, SSRF protection                      |
|   🔑   | **Key Management**             | Built-in key generation and rotation                        |

</td>
</tr>
</table>

### 📦 Feature Presets

| Preset                                                          | Features                                                                                                                                                     | Use Case                              |
| --------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------- |
| <span style="color:#166534; padding:4px 8px">minimal</span>     | `env`, `json`                                                                                                                                                | Environment variables + JSON          |
| <span style="color:#1E40AF; padding:4px 8px">recommended</span> | `toml`, `json`, `env`, `validation`                                                                                                                          | **Recommended for most applications** |
| <span style="color:#92400E; padding:4px 8px">dev</span>         | `toml`, `json`, `yaml`, `env`, `cli`, `validation`, `schema`, `audit`, `watch`, `migration`, `snapshot`, `dynamic`                                | Development with all tools            |
| <span style="color:#991B1B; padding:4px 8px">production</span>  | `toml`, `env`, `watch`, `encryption`, `validation`, `audit`, `schema`, `cli`, `migration`, `dynamic`, `progressive-reload`, `snapshot` | Production-ready configuration        |
| <span style="color:#7C3AED; padding:4px 8px">distributed</span> | `toml`, `env`, `watch`, `validation`, `config-bus`, `progressive-reload`, `audit`                                                                 | Distributed systems                   |
| <span style="color:#5B21B6; padding:4px 8px">full</span>        | All features                                                                                                                                                 | Complete feature set                  |

**Note:** Default features include `toml`, `json`, `env`.

### 🎨 Feature Architecture

```mermaid
graph LR
    A["<b>Configuration Sources</b><br/>Files • Env • CLI"] --> B["<b>ConfigLoader</b><br/>Core Engine"]
    B --> C["<b>Validation</b><br/>Type & Business Rules"]
    B --> D["<b>Schema</b><br/>JSON Schema Gen"]
    B --> E["<b>Encryption</b><br/>XChaCha20-Poly1305"]
    B --> F["<b>Audit</b><br/>Access Logs"]
    C --> H["<b>Application Config</b><br/>Ready to Use"]
    D --> H
    E --> H
    F --> H

    style A fill:#DBEAFE,stroke:#1E40AF,stroke-width:2px
    style B fill:#FEF3C7,stroke:#92400E,stroke-width:2px
    style H fill:#DCFCE7,stroke:#166534,stroke-width:2px
```

### 📋 Feature Matrix

| Feature               | Default | Description                                          | Stability |
| :-------------------- | :-----: | :--------------------------------------------------- | :-------- |
| **Format Support**    |         |                                                      |           |
| `toml`                || TOML configuration files                             | Stable    |
| `json`                || JSON configuration files                             | Stable    |
| `yaml`                || YAML configuration files                             | Stable    |
| `ini`                 || INI configuration files                              | Stable    |
| `env`                 || Environment variable support                         | Stable    |
| `dotenv`              || `.env` file support (alias of `env`)                 | Stable    |
| **Core Features**     |         |                                                      |           |
| `validation`          || Configuration validation (garde)                     | Stable    |
| `watch`               || File watching and hot reload                         | Stable    |
| `encryption`          || XChaCha20-Poly1305 encryption                        | Stable    |
| `cli`                 || CLI tool with commands                               | Stable    |
| `schema`              || JSON Schema generation                               | Stable    |
| `typescript-schema`   || TypeScript type generation (alias of `schema`)       | Stable    |
| **Advanced Features** |         |                                                      |           |
| `audit`               || Audit logging                                        | Stable    |
| `dynamic`             || Dynamic fields                                       | Stable    |
| `progressive-reload`  || Canary/linear rollout                                | Stable    |
| `migration`           || Configuration migration                              | Stable    |
| `snapshot`            || Snapshot rollback                                    | Stable    |
| `interpolation`       || Variable interpolation                               | Stable    |
| `hot-reload`          || Hot reload (removed; use `watch` feature)            | Removed   |
| **Remote Sources**    |         |                                                      |           |
| `remote`              || HTTP polling                                         | Beta      |
| `etcd`                || Etcd v3 integration                                  | Beta      |
| `consul`              || Consul integration                                   | Beta      |
| **Message Bus**       |         |                                                      |           |
| `config-bus`          || Config event bus                                     | Stable    |
| `nats-bus`            || NATS integration                                     | Stable    |
| `redis-bus`           || Redis Pub/Sub                                        | Stable    |
| **Security**          |         |                                                      |           |
| `security`            || Security module (env validation, error sanitization) | Stable    |
| `key`                 || Key management and rotation                          | Stable    |
| **Context & Modules** |         |                                                      |           |
| `context-aware`       || Tenant-aware configuration                           | Stable    |
| `modules`             || Modular configuration                                | Stable    |

### 🗂️ Examples Directory

Complete, runnable examples demonstrating all major features. All examples can be found in the [`examples/`](examples/) directory.

| Example                | File                                          | Features             | Description                                                     |
| :--------------------- | :-------------------------------------------- | :------------------- | :-------------------------------------------------------------- |
| **basic_usage**        | `examples/src/examples/basic_usage.rs`        | `toml`, `env`        | Basic configuration loading from TOML and environment variables |
| **hot_reload**         | `examples/src/examples/hot_reload.rs`         | `watch`              | Real-time file monitoring with automatic reload                 |
| **encryption**         | `examples/src/examples/encryption.rs`         | `encryption`         | Sensitive field encryption with XChaCha20-Poly1305              |
| **key_rotation**       | `examples/src/examples/key_rotation.rs`       | `key`                | Key lifecycle management and rotation                           |
| **migration**          | `examples/src/examples/migration.rs`          | `migration`          | Configuration version migration                                 |
| **dynamic_fields**     | `examples/src/examples/dynamic_fields.rs`     | `dynamic`            | Lock-free dynamic field updates with callbacks                  |
| **config_groups**      | `examples/src/examples/config_groups.rs`      | `modules`            | Modular configuration groups                                    |
| **progressive_reload** | `examples/src/examples/progressive_reload.rs` | `progressive-reload` | Canary deployment and health-check-based rollout                |
| **config_bus**         | `examples/src/examples/config_bus.rs`         | `config-bus`         | Multi-instance config broadcast via NATS/Redis                  |
| **snapshot**           | `examples/src/examples/snapshot.rs`           | `snapshot`           | Configuration snapshots with diff and rollback                  |
| **remote_consul**      | `examples/src/examples/remote_consul.rs`      | `consul`             | Remote config from HashiCorp Consul                             |
| **remote_etcd**        | `examples/src/examples/remote_etcd.rs`        | `etcd`               | Remote config from etcd v3                                      |
| **validation**         | `examples/src/examples/validation.rs`         | `validation`         | Configuration validation with garde                             |
| **json_schema**        | `examples/src/examples/json_schema.rs`        | `schema`             | JSON Schema and TypeScript type generation                      |
| **interpolation**      | `examples/src/examples/interpolation.rs`      | `interpolation`      | Configuration string interpolation with ${VAR} syntax           |
| **audit**              | `examples/src/examples/audit.rs`              | `audit`              | Audit logging with AuditWriter and AuditEvent                   |
| **context_aware**      | `examples/src/examples/context_aware.rs`      | `context-aware`      | Context-aware configuration with ContextAwareField              |
| **security**           | `examples/src/examples/security.rs`           | `security`           | Security features: encryption prefix detection, env validation  |
| **modules_demo**       | `examples/src/examples/modules_demo.rs`       | `modules`            | Module registry for feature-based configuration loading         |
| **cli_integration**    | `examples/src/examples/cli_integration.rs`    | `cli`                | CLI tool integration and usage                                  |
| **full_stack**         | `examples/src/examples/full_stack.rs`         | `full`               | Complete feature showcase                                       |

```bash
# Run any example from the examples directory
cd examples && cargo run --bin basic_usage
cd examples && cargo run --bin encryption
cd examples && cargo run --bin full_stack

# Verify all examples compile
cd examples && ./verify_examples.sh
```

---

## <span id="quick-start">🚀 Quick Start</span>

### <span id="installation">📦 Installation</span>

<table style="width:100%; border-collapse: collapse">
<tr>
<td width="100%" style="padding: 16px">

#### 🦀 Rust Installation

| Installation Type  | Configuration                                                                           | Use Case                                          |
| ------------------ | --------------------------------------------------------------------------------------- | ------------------------------------------------- |
| **Default**        | `confers = "0.4.0"`                                                                     | Includes `toml`, `json`, `env` (default features) |
| **Minimal**        | `confers = { version = "0.4.0", default-features = false, features = ["minimal"] }`     | Environment variables + JSON only                 |
| **Recommended**    | `confers = { version = "0.4.0", default-features = false, features = ["recommended"] }` | TOML + Env + validation                           |
| **CLI with Tools** | `confers = { version = "0.4.0", features = ["cli"] }`                                   | CLI tool (no validation/encryption)                |
| **Full**           | `confers = { version = "0.4.0", features = ["full"] }`                                  | All features                                      |

**Individual Features:**

| Feature               | Description                      | Default |
| --------------------- | -------------------------------- | ------- |
| **Format Support**    |                                  |         |
| `toml`                | TOML format support              ||
| `json`                | JSON format support              ||
| `yaml`                | YAML format support              ||
| `ini`                 | INI format support               ||
| `env`                 | Environment variable support     ||
| `dotenv`              | `.env` file support (alias of `env`) ||
| **Core Features**     |                                  |         |
| `validation`          | Configuration validation (garde) ||
| `watch`               | File watching and hot reload     ||
| `encryption`          | XChaCha20-Poly1305 encryption    ||
| `cli`                 | Command-line tool                ||
| `schema`              | JSON Schema generation           ||
| `typescript-schema`   | TypeScript type generation (alias of `schema`) ||
| **Advanced Features** |                                  |         |
| `audit`               | Audit logging                    ||
| `dynamic`             | Dynamic fields                   ||
| `progressive-reload`  | Progressive reload               ||
| `migration`           | Configuration migration          ||
| `snapshot`            | Snapshot rollback                ||
| `interpolation`       | Variable interpolation           ||
| **Remote Sources**    |                                  |         |
| `remote`              | HTTP polling                     ||
| `etcd`                | Etcd integration                 ||
| `consul`              | Consul integration               ||
| **Message Bus**       |                                  |         |
| `config-bus`          | Configuration event bus          ||
| `nats-bus`            | NATS message bus                 ||
| `redis-bus`           | Redis message bus                ||
| **Others**            |                                  |         |
| `security`            | Security module                  ||
| `key`                 | Key management system            ||
| `modules`             | Modular configuration            ||
| `context-aware`       | Context-aware configuration      ||

### 🔧 CLI Command Feature Dependencies

| Command    | Required Features | Optional Features | Description                  |
| ---------- | ----------------- | ----------------- | ---------------------------- |
| `validate` | `cli`             | -                 | Validate configuration files |
| `diff`     | `cli`             | -                 | Compare configuration files  |

**Note**: The `cli` feature provides command-line tools for configuration management.

</td>
</tr>
</table>

### <span id="basic-usage">💡 Basic Usage</span>

#### 🎬 5-Minute Quick Start

**Required Features**: `toml`, `env`, `validation` (use: `features = ["recommended"]`)

<table style="width:100%; border-collapse: collapse">
<tr>
<td width="50%" style="padding: 16px; vertical-align:top">

**Step 1: Define Config Structure**

```rust
use confers::Config;
use serde::{Deserialize, Serialize};

#[derive(Debug, Clone, Serialize, Deserialize, Config)]
#[config(validate)]
#[config(env_prefix = "APP_")]
pub struct AppConfig {
    pub name: String,
    pub port: u16,
    pub debug: bool,
}
```

</td>
<td width="50%" style="padding: 16px; vertical-align:top">

**Step 2: Create Config File**

```toml
# config.toml
name = "my-app"
port = 8080
debug = true
```

</td>
</tr>
<tr>
<td width="50%" style="padding: 16px; vertical-align:top">

**Step 3: Load Config**

```rust
fn main() -> anyhow::Result<()> {
    let config = AppConfig::load_sync()?;
    println!("✅ Loaded: {:?}", config);
    Ok(())
}
```

</td>
<td width="50%" style="padding: 16px; vertical-align:top">

**Step 4: Environment Override**

```bash
# Environment variables automatically override
export APP_PORT=9090
export APP_DEBUG=true
```

</td>
</tr>
</table>

<details style="padding:16px; margin: 16px 0">
<summary style="cursor:pointer; font-weight:600; color:#166534">📖 Complete Working Example</summary>

```rust
use confers::Config;
use serde::{Deserialize, Serialize};

#[derive(Debug, Clone, Serialize, Deserialize, Config)]
#[config(validate)]
#[config(env_prefix = "APP_")]
pub struct AppConfig {
    pub name: String,
    pub port: u16,
    pub debug: bool,
}

fn main() -> anyhow::Result<()> {
    // Create config file
    let config_content = r#"
name = "my-app"
port = 8080
debug = true
"#;
    std::fs::write("config.toml", config_content)?;

    // Load configuration
    let config = AppConfig::load_sync()?;

    // Print configuration
    println!("🎉 Configuration loaded successfully!");
    println!("📋 Name: {}", config.name);
    println!("🔌 Port: {}", config.port);
    println!("🐛 Debug: {}", config.debug);

    Ok(())
}
```

</details>

### 🎨 Three Usage Patterns

Confers provides three flexible usage patterns to suit different needs:

#### 1️⃣ Simple Mode (Recommended)

Perfect for most applications with minimal boilerplate:

```rust
use confers::Config;
use serde::{Deserialize, Serialize};

#[derive(Debug, Clone, Serialize, Deserialize, Config)]
#[config(validate)]
pub struct AppConfig {
    pub name: String,
    pub port: u16,
    pub debug: bool,
}

// One-line configuration loading
let config = AppConfig::load_sync()?;
```

#### 2️⃣ Builder Mode

For more control over configuration sources:

```rust
use confers::{ConfigBuilder, ConfigProviderExt};

let config = ConfigBuilder::<serde_json::Value>::new()
    .file("config.toml")
    .file("local.toml")  // Higher priority
    .env()
    .build()?;

let name = config.get_string("app.name");
let port = config.get_int("app.port");
```

#### 3️⃣ DI Mode (Dependency Injection)

For integration into frameworks and runtime flexibility:

```rust
use std::sync::Arc;
use confers::{ConfigBuilder, ConfigProviderExt};

#[derive(Debug, Clone, serde::Deserialize)]
pub struct MyConfig {
    pub name: String,
    pub port: u16,
}

let config = ConfigBuilder::<MyConfig>::new()
    .file("config.toml")
    .env()
    .build()?;

let shared_config = Arc::new(config);

let service = MyService::new(shared_config);
```

---

## <span id="documentation">📚 Documentation</span>

<table style="width:100%; max-width: 800px">
<tr>
<td align="center" width="33%" style="padding: 16px">
<a href="docs/USER_GUIDE.md" style="text-decoration:none">
<div style="padding: 24px; transition: transform 0.2s">
<img src="https://img.icons8.com/fluency/96/000000/book.png" width="48" height="48"><br>
<b style="color:#1E293B">User Guide</b>
</div>
</a>
<br><span style="color:#64748B">Complete usage guide</span>
</td>
<td align="center" width="33%" style="padding: 16px">
<a href="https://docs.rs/confers" style="text-decoration:none">
<div style="padding: 24px; transition: transform 0.2s">
<img src="https://img.icons8.com/fluency/96/000000/api.png" width="48" height="48"><br>
<b style="color:#1E293B">API Reference</b>
</div>
</a>
<br><span style="color:#64748B">Complete API docs</span>
</td>
<td align="center" width="33%" style="padding: 16px">
<a href="examples/" style="text-decoration:none">
<div style="padding: 24px; transition: transform 0.2s">
<img src="https://img.icons8.com/fluency/96/000000/code.png" width="48" height="48"><br>
<b style="color:#1E293B">Examples</b>
</div>
</a>
<br><span style="color:#64748B">Code examples</span>
</td>
</tr>
</table>

### 📖 Additional Resources

| Resource                                                    | Description                                     |
| ----------------------------------------------------------- | ----------------------------------------------- |
|[FAQ]docs/FAQ.md                                       | Frequently asked questions                      |
| 📖 [Contributing Guide]docs/CONTRIBUTING.md               | Code contribution guidelines                    |
| 📘 [API Reference]docs/API_REFERENCE.md                   | Complete API documentation                      |
| 🏗️ [Architecture Decisions]docs/adr/ | ADR documentation                               |
| 📚 [Library Integration Guide]docs/LIBRARY_INTEGRATION.md | How to integrate confers CLI into your projects |

### 🔄 BrickArchitecture Migration Guide

Confers now follows **BrickArchitecture** error separation patterns:

| Error Type           | Phase         | When It Occurs      | Example                                        |
| -------------------- | ------------- | ------------------- | ---------------------------------------------- |
| `ConfigConfigError` | Configuration | Initialization time | Missing field, parse error, validation failure |
| `ConfersError`       | Runtime       | Use time            | Timeout, remote unavailable, decryption failed |

**Backward Compatibility:** Existing `ConfigError` and `ConfigResult<T>` aliases remain available.

<details style="padding:16px; margin: 16px 0">
<summary style="cursor:pointer; font-weight:600; color:#166534">📖 Migration Example</summary>

```rust
// OLD: ConfigError for all errors
use confers::ConfigError;

// NEW: Use BrickArchitecture error separation
use confers::{ConfigConfigError, ConfersError};

// Configuration phase - use ConfigConfigError
fn init_config() -> Result<impl confers::interface::ConfigConnector, ConfigConfigError> {
    use confers::impl_::memory::InMemoryConfig;
    let config = InMemoryConfig::new_validated(1000)?; // Returns ConfigConfigError
    Ok(config)
}

// Runtime phase - use ConfersError
async fn use_config(config: &impl ConfigReader) -> Result<(), ConfersError> {
    let value = config.get_string("key").await?;  // Returns ConfersError
    Ok(())
}
```

</details>

---

## 🔧 CLI Tool

Confers provides a standalone command-line tool `confers` for configuration management:

### Install CLI Tool

```bash
cargo install confers
```

### Basic Commands

```bash
# View help
confers --help

# Inspect configuration - list all keys with their sources
confers --config config.toml inspect

# Validate configuration file
confers --config config.toml validate

# Compare configuration files
confers diff --base config1.toml --overlay config2.toml

# Export merged configuration
confers --config config.toml export --format json

# Manage configuration snapshots
confers --config config.toml snapshot list
confers --config config.toml snapshot diff --latest 2
```

**Note**: The CLI tool requires the `cli` feature to be enabled.

---

## <span id="examples">💻 Examples</span>

### 💡 Real-World Examples

<table style="width:100%; border-collapse: collapse">
<tr>
<td width="50%" style="padding: 16px; vertical-align:top">

#### 📝 Example 1: Basic Configuration

```rust
use confers::Config;
use serde::{Deserialize, Serialize};

#[derive(Debug, Clone, Serialize, Deserialize, Config)]
#[config(validate)]
pub struct BasicConfig {
    pub name: String,
    pub port: u16,
}

fn basic_example() -> anyhow::Result<()> {
    let config = BasicConfig::load_sync()?;
    println!("✅ Name: {}, Port: {}", config.name, config.port);
    Ok(())
}
```

<details style="margin-top:8px">
<summary style="cursor:pointer; font-weight:600; color:#3B82F6">View Output</summary>

```
✅ Name: my-app, Port: 8080
```

</details>

</td>
<td width="50%" style="padding: 16px; vertical-align:top">

#### 🔥 Example 2: Advanced Configuration

```rust
use confers::Config;
use serde::{Deserialize, Serialize};

#[derive(Debug, Clone, Serialize, Deserialize, Config)]
#[config(validate)]
#[config(env_prefix = "MYAPP_")]
pub struct AdvancedConfig {
    #[config(description = "Server port number")]
    pub port: u16,
    #[config(default = "localhost")]
    pub host: String,
    #[config(sensitive = true)]
    pub api_key: String,
}

fn advanced_example() -> anyhow::Result<()> {
    let config = AdvancedConfig::load_sync()?;
    println!("🚀 Server: {}:{}", config.host, config.port);
    Ok(())
}
```

<details style="margin-top:8px">
<summary style="cursor:pointer; font-weight:600; color:#3B82F6">View Output</summary>

```
🚀 Server: localhost:8080
```

</details>

</td>
</tr>
</table>

**[📂 Explore All Examples →](examples/)**

---

## <span id="architecture">🏗️ Architecture</span>

### 🏗️ System Architecture

```mermaid
graph TB
    subgraph Sources ["Configuration Sources"]
        A["Local Files<br/>TOML, JSON, YAML, INI"]
        B["Environment Variables"]
        C["CLI Arguments"]
        D["Remote Sources<br/>etcd, Consul, HTTP"]
    end

    subgraph Core ["Core Engine"]
        E["ConfigLoader<br/>Multi-source Merge"]
    end

    subgraph Processing ["Processing Layer"]
        F["Validation<br/>Type & Business Rules"]
        G["Schema Generation"]
        H["Encryption<br/>XChaCha20-Poly1305"]
        I["Audit Logging"]
        J["File Watching"]
    end

    subgraph Output ["Application"]
        L["Application Configuration<br/>Type-Safe & Validated"]
    end

    Sources --> Core
    Core --> Processing
    Processing --> Output

    style Sources fill:#DBEAFE,stroke:#1E40AF
    style Core fill:#FEF3C7,stroke:#92400E
    style Processing fill:#EDE9FE,stroke:#5B21B6
    style Output fill:#DCFCE7,stroke:#166534
```

### 📐 Component Status

| Component                    | Description                           | Status    |
| ---------------------------- | ------------------------------------- | --------- |
| **ConfigLoader**             | Core loader with multi-source support | ✅ Stable |
| **Configuration Validation** | Built-in validator integration        | ✅ Stable |
| **Schema Generation**        | Auto-generate JSON Schema             | ✅ Stable |
| **File Watching**            | Real-time monitoring with hot reload  | ✅ Stable |
| **Remote Configuration**     | etcd, Consul, HTTP support            | 🚧 Beta   |
| **Audit Logging**            | Record access and change history      | ✅ Stable |
| **Encrypted Storage**        | XChaCha20-Poly1305 encrypted storage  | ✅ Stable |
| **Configuration Diff**       | Multiple output formats               | ✅ Stable |

---

## <span id="configuration">⚙️ Configuration</span>

### 🎛️ Configuration Options

<table style="width:100%; border-collapse: collapse">
<tr>
<td width="50%" style="padding: 16px">

**Basic Configuration**

```toml
[project]
name = "my-app"
version = "1.0.0"

[server]
host = "localhost"
port = 8080

[features]
debug = true
logging = true
```

</td>
<td width="50%" style="padding: 16px">

**Advanced Configuration**

```toml
[project]
name = "my-app"
version = "1.0.0"

[server]
host = "0.0.0.0"
port = 8080
workers = 4

[database]
url = "postgres://localhost/db"
pool_size = 10

[performance]
cache_size = 1000
```

</td>
</tr>
</table>

<details style="padding:16px; margin: 16px 0">
<summary style="cursor:pointer; font-weight:600; color:#1E293B">🔧 All Configuration Options</summary>

| Option       | Type    | Default     | Description              |
| ------------ | ------- | ----------- | ------------------------ |
| `name`       | String  | -           | Project name             |
| `version`    | String  | "1.0.0"     | Version number           |
| `host`       | String  | "localhost" | Server host              |
| `port`       | u16     | 8080        | Server port              |
| `debug`      | Boolean | false       | Enable debug mode        |
| `workers`    | usize   | 4           | Number of worker threads |
| `cache_size` | usize   | 1000        | Cache size in MB         |

</details>

---

## <span id="testing">🧪 Testing</span>

### 🎯 Test Coverage

```bash
# 🧪 Run all tests
cargo test --features full

# 📊 Generate coverage report
cargo llvm-cov --features full

# ⚡ Run benchmarks
cargo bench

# 🎯 Run specific test
cargo test test_name
```

<details style="padding:16px; margin: 16px 0">
<summary style="cursor:pointer; font-weight:600; color:#166534">📊 Test Statistics</summary>

> Data source: `cargo test --features full` (as of 2026-07). Numbers grow with code evolution; re-run the command to verify.

| Category             | Test Count        | Notes                                  |
| -------------------- | ----------------- | -------------------------------------- |
| 🧪 Unit Tests        | 1700+             | lib tests across all feature gates     |
| 🔗 Integration Tests | multiple suites   | `tests/integration_*.rs` per feature   |
| 📚 Doc Tests         | 32                | rustdoc examples                       |
| ⚡ Performance Tests | 10 bench files    | `benches/*.rs` (criterion)             |
| **📈 Total**         | **1700+**         | Run `cargo test --features full`       |

**Coverage target:** ≥ 80% (enforced in CI via `cargo llvm-cov`).

</details>

---

## <span id="performance">📊 Performance</span>

### ⚡ Benchmark Results

> The following are **reference estimates**. Actual performance depends on configuration complexity and hardware. Run `cargo bench` to obtain measurements for your specific scenario.

<table style="width:100%; border-collapse: collapse">
<tr>
<td width="50%" style="padding: 16px; text-align:center">

**📊 Throughput**

| Operation   | Performance       |
| ----------- | ----------------- |
| Config Load | 1,000,000 ops/sec |
| Validation  | 500,000 ops/sec   |
| Schema Gen  | 2,000,000 ops/sec |

</td>
<td width="50%" style="padding: 16px; text-align:center">

**⏱️ Latency**

| Percentile | Latency |
| ---------- | ------- |
| P50        | 0.5ms   |
| P95        | 1.2ms   |
| P99        | 2.5ms   |

</td>
</tr>
</table>

<details style="padding:16px; margin: 16px 0">
<summary style="cursor:pointer; font-weight:600; color:#92400E">📈 Detailed Benchmarks</summary>

```bash
# Run benchmarks
cargo bench

# Sample output:
test bench_config_load  ... bench: 1,000 ns/iter (+/- 50)
test bench_validate     ... bench: 2,000 ns/iter (+/- 100)
test bench_schema_gen   ... bench: 500 ns/iter (+/- 25)
```

</details>

---

## <span id="security">🔒 Security</span>

### 🛡️ Security Features

<table style="width:100%; border-collapse: collapse">
<tr>
<td align="center" width="25%" style="padding: 16px">
<img src="https://img.icons8.com/fluency/96/000000/lock.png" width="48" height="48"><br>
<b>Memory Safety</b><br>
<span style="color:#166534">Zero-copy & secure cleanup</span>
</td>
<td align="center" width="25%" style="padding: 16px">
<img src="https://img.icons8.com/fluency/96/000000/security-checked.png" width="48" height="48"><br>
<b>Audited</b><br>
<span style="color:#1E40AF">Regular security audits</span>
</td>
<td align="center" width="25%" style="padding: 16px">
<img src="https://img.icons8.com/fluency/96/000000/privacy.png" width="48" height="48"><br>
<b>Privacy</b><br>
<span style="color:#92400E">No data collection</span>
</td>
<td align="center" width="25%" style="padding: 16px">
<img src="https://img.icons8.com/fluency/96/000000/shield.png" width="48" height="48"><br>
<b>Compliance</b><br>
<span style="color:#5B21B6">Industry standards</span>
</td>
</tr>
</table>

<details style="padding:16px; margin: 16px 0">
<summary style="cursor:pointer; font-weight:600; color:#991B1B">🔐 Security Details</summary>

### 🛡️ Security Measures

| Measure                         | Description                                     | API Reference                         |
| ------------------------------- | ----------------------------------------------- | ------------------------------------- |
|**Memory Protection**        | Automatic secure cleanup with zeroization       | `SecretString`, `zeroize` crate       |
|**Side-channel Protection**  | Constant-time cryptographic operations          | XChaCha20-Poly1305 encryption         |
|**Input Validation**         | Comprehensive input sanitization                | `Validate` trait, `garde` crate       |
|**Audit Logging**            | Full operation tracking                         | `AuditConfig`, audit trails           |
|**SSRF Protection**          | Built-in Server-Side Request Forgery prevention | `HttpPolledSource`, `is_ip_blocked()` |
|**Sensitive Data Detection** | Automatic detection of sensitive fields         | `#[config(sensitive = true)]` proc-macro |
|**Error Sanitization**       | Remove sensitive info from error messages       | `ErrorSanitizer`, `SecureLogger`      |
|**Nonce Reuse Detection**    | Prevent cryptographic nonce reuse               | Built into encryption module          |

### 🔐 Security APIs

```rust,ignore
// Secure string handling
use confers::security::{SecureString, SensitivityLevel};
let secure_str = SecureString::new("sensitive_data", SensitivityLevel::High);

// Input validation
use confers::security::ConfigValidator;
let validator = ConfigValidator::builder()
    .max_string_length(1024)
    .strict_mode()
    .build();
let data: std::collections::HashMap<String, String> = std::collections::HashMap::new();
let result = validator.validate(&data);

// Error sanitization
use confers::security::ErrorSanitizer;
let sanitizer = ErrorSanitizer::default();
let safe_error = sanitizer.sanitize(&error_message);

// Audit logging
#[cfg(feature = "audit")]
use confers::audit::AuditConfig;
let audit = AuditConfig::new().enable_sensitive_field_tracking();
```

### 🚨 Security Best Practices

1. **Use SecureString for sensitive data**: Automatically zeroizes memory
2. **Enable audit logging**: Track all configuration access and changes
3. **Validate all inputs**: Use built-in validators for user inputs
4. **Use encryption**: Enable `encryption` feature for sensitive configs
5. **Follow principle of least privilege**: Minimize sensitive data exposure

### 📧 Reporting Security Issues

Please report security vulnerabilities to: **security@confers.dev**

</details>

---

## <span id="roadmap">🗺️ Roadmap</span>

### 🎯 Development Roadmap

```mermaid
gantt
    title Confers Development Roadmap
    dateFormat  YYYY-MM
    section Core Features
    Type-safe Configuration     :done, 2024-01, 2024-06
    Multi-format Support       :done, 2024-02, 2024-06
    Environment Variable Override     :done, 2024-03, 2024-06
    section Validation System
    Basic Validation Integration     :done, 2024-04, 2024-07
    section Advanced Features
    Schema Generation      :active, 2024-06, 2024-09
    File Watching Hot Reload   :done, 2024-07, 2024-09
    Remote Configuration Support     :active, 2024-08, 2024-12
    Audit Logging         :done, 2024-08, 2024-10
```

<table style="width:100%; border-collapse: collapse">
<tr>
<td width="50%" style="padding: 16px">

### ✅ Completed

**Core Features**
- [x] Type-safe Configuration
- [x] Multi-format Support (TOML, YAML, JSON, INI)
- [x] Environment Variable Override
- [x] CLI Argument Override

**Validation System**
- [x] Configuration Validation System (garde)

**Advanced Features**
- [x] Schema Generation (JSON Schema + TypeScript types)
- [x] File Watching & Hot Reload
- [x] Audit Logging
- [x] Encrypted Storage Support (XChaCha20-Poly1305)
- [x] Dynamic Fields (lock-free)
- [x] Modular Configuration (modules)
- [x] Context-aware Configuration (tenant-aware)
- [x] Configuration Migration
- [x] Snapshot & Rollback
- [x] Variable Interpolation
- [x] Progressive Reload (canary rollout)

**Remote & Bus**
- [x] Remote Configuration Support (etcd, Consul, HTTP)
- [x] HTTP Polling
- [x] Configuration Event Bus (NATS / Redis Pub-Sub)

**Security**
- [x] Security Module (env validation, error sanitization, SSRF protection)
- [x] Key Management & Rotation
- [x] Nonce Reuse Detection

</td>
<td width="50%" style="padding: 16px">

### 📋 Planned

**Performance Optimization**
- [ ] Benchmark suite refinement (criterion baselines)
- [ ] Memory footprint optimization for large configs
- [ ] Zero-copy hot path for high-frequency reads

**Cloud-native Integration Enhancements**
- [ ] Kubernetes ConfigMap integration
- [ ] Service mesh support (Istio/Linkerd)
- [ ] Distributed tracing integration

</td>
</tr>
</table>

---

## <span id="contributing">🤝 Contributing</span>

### 💖 Thank You to All Contributors!

<table style="width:100%; border-collapse: collapse">
<tr>
<td width="33%" align="center" style="padding: 16px">

### 🐛 Report Bugs

Found an issue?<br>
<a href="https://github.com/Kirky-X/confers/issues/new">Create Issue</a>

</td>
<td width="33%" align="center" style="padding: 16px">

### 💡 Feature Suggestions

Have a great idea?<br>
<a href="https://github.com/Kirky-X/confers/discussions">Start Discussion</a>

</td>
<td width="33%" align="center" style="padding: 16px">

### 🔧 Submit PR

Want to contribute code?<br>
<a href="https://github.com/Kirky-X/confers/pulls">Fork & PR</a>

</td>
</tr>
</table>

<details style="padding:16px; margin: 16px 0">
<summary style="cursor:pointer; font-weight:600; color:#1E293B">📝 Contribution Guidelines</summary>

### 🚀 How to Contribute

1. **Fork** this repository
2. **Clone** your fork: `git clone https://github.com/yourusername/confers.git`
3. **Create** a branch: `git checkout -b feature/amazing-feature`
4. **Make** your changes
5. **Test** your changes: `cargo test --all-features`
6. **Commit** your changes: `git commit -m 'feat: Add amazing feature'`
7. **Push** to the branch: `git push origin feature/amazing-feature`
8. **Create** a Pull Request

### 📋 Code Standards

- ✅ Follow Rust standard coding conventions
- ✅ Write comprehensive tests
- ✅ Update documentation
- ✅ Add examples for new features
- ✅ Pass `cargo clippy -- -D warnings`

</details>

---

## <span id="license">📄 License</span>

This project is licensed under **MIT License**:

---

## <span id="acknowledgments">🙏 Acknowledgments</span>

### 🌟 Built With Amazing Tools

<table style="width:100%; border-collapse: collapse">
<tr>
<td align="center" width="25%" style="padding: 16px">
<a href="https://www.rust-lang.org/" style="text-decoration:none">
<div style="padding: 16px">
<img src="https://www.rust-lang.org/static/images/rust-logo-blk.svg" width="48" height="48"><br>
<b>Rust</b>
</div>
</a>
</td>
<td align="center" width="25%" style="padding: 16px">
<a href="https://github.com/" style="text-decoration:none">
<div style="padding: 16px">
<img src="https://github.githubassets.com/images/modules/logos_page/GitHub-Mark.png" width="48" height="48"><br>
<b>GitHub</b>
</div>
</a>
</td>
<td align="center" width="25%" style="padding: 16px">
<div style="padding: 16px">
<img src="https://img.icons8.com/fluency/96/000000/code.png" width="48" height="48"><br>
<b>Open Source</b>
</div>
</td>
<td align="center" width="25%" style="padding: 16px">
<div style="padding: 16px">
<img src="https://img.icons8.com/fluency/96/000000/community.png" width="48" height="48"><br>
<b>Community</b>
</div>
</td>
</tr>
</table>

### 💝 Special Thanks

| Category                   | Description                                                                    |
| -------------------------- | ------------------------------------------------------------------------------ |
| 🌟 **Dependency Projects** | [serde]https://github.com/serde-rs/serde - Serialization framework           |
|                            | [figment]https://github.com/SergioBenitez/figment - Configuration management |
|                            | [validator]https://github.com/Keats/validator - Validation library           |
| 👥 **Contributors**        | Thanks to all contributors!                                                    |
| 💬 **Community**           | Special thanks to community members                                            |

---

## 📞 Contact & Support

<table style="width:100%; max-width: 600px">
<tr>
<td align="center" width="33%">
<a href="https://github.com/Kirky-X/confers/issues">
<div style="padding: 16px">
<img src="https://img.icons8.com/fluency/96/000000/bug.png" width="32" height="32"><br>
<b style="color:#991B1B">Issues</b>
</div>
</a>
<br><span style="color:#64748B">Report bugs & issues</span>
</td>
<td align="center" width="33%">
<a href="https://github.com/Kirky-X/confers/discussions">
<div style="padding: 16px">
<img src="https://img.icons8.com/fluency/96/000000/chat.png" width="32" height="32"><br>
<b style="color:#1E40AF">Discussions</b>
</div>
</a>
<br><span style="color:#64748B">Ask questions & share ideas</span>
</td>
<td align="center" width="33%">
<a href="https://github.com/Kirky-X/confers">
<div style="padding: 16px">
<img src="https://img.icons8.com/fluency/96/000000/github.png" width="32" height="32"><br>
<b style="color:#1E293B">GitHub</b>
</div>
</a>
<br><span style="color:#64748B">View source code</span>
</td>
</tr>
</table>

---

## ⭐ Star History

[![Star History Chart](https://api.star-history.com/svg?repos=Kirky-X/confers&type=Date)](https://star-history.com/#Kirky-X/confers&Date)

---

### 💝 Support This Project

If you find this project useful, please consider giving it a ⭐️!

**Built with ❤️ by Kirky.X**

---

**[⬆ Back to Top](#top)**

---

<sub>© 2026 Kirky.X. All rights reserved.</sub>

</div>