-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathconfig.rs
More file actions
1761 lines (1505 loc) · 53.4 KB
/
Copy pathconfig.rs
File metadata and controls
1761 lines (1505 loc) · 53.4 KB
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
use serde::{Deserialize, Serialize};
use std::collections::{HashMap, HashSet};
use std::net::{IpAddr, Ipv4Addr};
use crate::wasm::config::{DestinationUdfConfig, WasmConfig};
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MirrorMakerConfig {
/// Application ID
pub appid: String,
/// Source Kafka bootstrap servers
pub bootstrap: String,
/// Input topic(s) - comma-separated
pub input: String,
/// Output topic (for single destination)
pub output: Option<String>,
/// Target broker (for cross-cluster mirroring)
#[serde(default)]
pub target_broker: Option<String>,
/// Consumer offset reset strategy
#[serde(default = "default_offset")]
pub offset: String,
/// Number of processing threads
#[serde(default = "default_threads")]
pub threads: usize,
/// Runtime batching and Kafka client performance tuning.
#[serde(default)]
pub performance: PerformanceConfig,
/// Compression configuration
#[serde(default)]
pub compression: CompressionConfig,
/// Multi-destination routing configuration
pub routing: Option<RoutingConfig>,
/// Value transform expression for single-destination mode.
///
/// Supports the full transform DSL including `STRING:`, `CACHE_LOOKUP:`,
/// `CACHE_PUT:`, `HASH:`, `CONSTRUCT:`, `ARITHMETIC:`, etc.
/// Ignored when `routing` is set.
#[serde(default)]
pub transform: Option<String>,
/// Consumer properties
#[serde(default)]
pub consumer_properties: HashMap<String, String>,
/// Producer properties
#[serde(default)]
pub producer_properties: HashMap<String, String>,
/// Security configuration
#[serde(default)]
pub security: Option<SecurityConfig>,
/// Commit strategy configuration
#[serde(default)]
pub commit_strategy: CommitStrategyConfig,
/// Cache configuration
#[serde(default)]
pub cache: Option<CacheBackendConfig>,
/// Observability configuration (metrics, monitoring)
#[serde(default)]
pub observability: ObservabilityConfig,
/// Retry configuration for transient failures
#[serde(default)]
pub retry: crate::retry::RetryConfig,
/// Dead letter queue configuration for failed messages
#[serde(default)]
pub dlq: crate::dlq::DlqConfig,
/// Optional registry of stateless WebAssembly UDF components.
///
/// Omitting this field preserves the native-only execution path.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub wasm: Option<WasmConfig>,
/// WebAssembly UDFs for single-destination mode.
///
/// Ignored when `routing` is set.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub udfs: Option<DestinationUdfConfig>,
}
/// Runtime batching and Kafka client performance tuning.
///
/// The in-process batching fields preserve the historical hard-coded defaults.
/// Kafka fields are optional so omitting `performance` preserves librdkafka's
/// existing defaults. Explicit `consumer_properties` and `producer_properties`
/// take precedence over values generated from this section.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct PerformanceConfig {
/// Maximum messages collected before processing a batch.
#[serde(default = "default_consumer_batch_size")]
pub consumer_batch_size: usize,
/// Maximum milliseconds to wait for a partially filled legacy batch. In
/// partition-ordered mode this is also the idle queued-delivery flush delay.
#[serde(default = "default_consumer_batch_timeout_ms")]
pub consumer_batch_timeout_ms: u64,
/// Concurrent processing multiplier applied to `threads`.
#[serde(default = "default_parallelism_factor")]
pub parallelism_factor: usize,
/// In-process scheduling strategy.
///
/// `legacy_batch` preserves the historical batch barrier. `partition_ordered`
/// routes each source partition to one bounded FIFO worker lane.
#[serde(default)]
pub processing_mode: ProcessingMode,
/// Per-worker input queue capacity in `partition_ordered` mode.
#[serde(default = "default_worker_queue_capacity")]
pub worker_queue_capacity: usize,
/// Maps to librdkafka `fetch.min.bytes`.
#[serde(default)]
pub fetch_min_bytes: Option<u32>,
/// Maps to librdkafka `fetch.wait.max.ms`.
#[serde(default)]
pub fetch_max_wait_ms: Option<u32>,
/// Maps to librdkafka `linger.ms`.
#[serde(default)]
pub linger_ms: Option<u64>,
/// Maximum messages per producer batch; maps to librdkafka
/// `batch.num.messages`.
#[serde(default)]
pub batch_size: Option<usize>,
/// Maps to librdkafka `queue.buffering.max.ms`.
#[serde(default)]
pub queue_buffering_max_ms: Option<u64>,
/// Producer delivery completion behavior.
///
/// `acknowledged` preserves the historical behavior by awaiting Kafka's
/// delivery result for every record. `queued` returns after librdkafka
/// accepts the record and tracks delivery completion in the background.
#[serde(default)]
pub producer_delivery_mode: ProducerDeliveryMode,
/// Maximum queued producer deliveries awaiting acknowledgement.
#[serde(default = "default_producer_max_in_flight")]
pub producer_max_in_flight: usize,
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
#[serde(rename_all = "snake_case")]
pub enum ProducerDeliveryMode {
#[default]
Acknowledged,
Queued,
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
#[serde(rename_all = "snake_case")]
pub enum ProcessingMode {
#[default]
LegacyBatch,
PartitionOrdered,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SecurityConfig {
/// Security protocol: PLAINTEXT, SSL, SASL_PLAINTEXT, SASL_SSL
pub protocol: SecurityProtocol,
/// SSL/TLS configuration
#[serde(default)]
pub ssl: Option<SslConfig>,
/// SASL authentication configuration
#[serde(default)]
pub sasl: Option<SaslConfig>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum SecurityProtocol {
Plaintext,
Ssl,
SaslPlaintext,
SaslSsl,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SslConfig {
/// Path to CA certificate file for verifying broker's certificate
pub ca_location: Option<String>,
/// Path to client's certificate file (for mutual TLS)
pub certificate_location: Option<String>,
/// Path to client's private key file (for mutual TLS)
pub key_location: Option<String>,
/// Password for the private key file
pub key_password: Option<String>,
/// Endpoint identification algorithm (default: https)
pub endpoint_identification_algorithm: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SaslConfig {
/// SASL mechanism: PLAIN, SCRAM-SHA-256, SCRAM-SHA-512, GSSAPI, OAUTHBEARER
pub mechanism: SaslMechanism,
/// Username (for PLAIN and SCRAM mechanisms)
pub username: Option<String>,
/// Password (for PLAIN and SCRAM mechanisms)
pub password: Option<String>,
/// Kerberos service name (for GSSAPI)
pub kerberos_service_name: Option<String>,
/// Kerberos principal (for GSSAPI)
pub kerberos_principal: Option<String>,
/// Path to Kerberos keytab (for GSSAPI)
pub kerberos_keytab: Option<String>,
/// OAuth bearer token (for OAUTHBEARER)
pub oauthbearer_token: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum SaslMechanism {
#[serde(rename = "PLAIN")]
Plain,
#[serde(rename = "SCRAM-SHA-256")]
ScramSha256,
#[serde(rename = "SCRAM-SHA-512")]
ScramSha512,
#[serde(rename = "GSSAPI")]
Gssapi,
#[serde(rename = "OAUTHBEARER")]
Oauthbearer,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CompressionConfig {
#[serde(default)]
pub compression_type: CompressionType,
#[serde(default)]
pub compression_algo: CompressionAlgo,
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, Default, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum CompressionType {
#[default]
None,
/// Native Kafka compression (recommended)
Raw,
/// Enveloped compression (custom format)
Enveloped,
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum CompressionAlgo {
#[default]
Gzip,
Snappy,
Zstd,
Lz4,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RoutingConfig {
/// Routing type: content, filter, or hybrid
pub routing_type: String,
/// JSON path for content-based routing
pub path: Option<String>,
/// Destination configurations
pub destinations: Vec<DestinationConfig>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct AggregationConfig {
pub group_by: Vec<AggregationGroupBy>,
pub window: AggregationWindowConfig,
pub metrics: Vec<AggregationMetricConfig>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct AggregationGroupBy {
pub name: String,
pub path: String,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct AggregationWindowConfig {
#[serde(rename = "type")]
pub window_type: AggregationWindowType,
pub size_seconds: u64,
pub emit_interval_seconds: u64,
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum AggregationWindowType {
Tumbling,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct AggregationMetricConfig {
pub name: String,
pub op: AggregationOp,
#[serde(default)]
pub path: Option<String>,
#[serde(default)]
pub percentiles: Option<Vec<f64>>,
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum AggregationOp {
Count,
Sum,
Avg,
ApproxDistinct,
Quantiles,
}
/// Error handling policy for filter/transform failures
#[derive(Debug, Clone, Copy, Serialize, Deserialize, Default, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum ErrorPolicy {
/// Halt pipeline on any error (strictest)
#[default]
Fail,
/// Send failed messages to dead letter queue (recommended)
Dlq,
/// Skip bad messages and log errors (permissive)
SkipAndLog,
/// Continue processing, log but don't DLQ (most permissive)
Continue,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DestinationConfig {
/// Destination topic name
pub output: String,
/// Match value for content-based routing
pub match_value: Option<String>,
/// Filter expression (simple or composite)
/// Simple: "path,operator,value" e.g., "/message/siteId,>,10000"
/// Composite JSON for AND/OR/NOT (parsed separately)
///
/// New envelope filters:
/// - KEY_PREFIX:prefix
/// - KEY_MATCHES:regex
/// - HEADER:name,op,value
/// - TIMESTAMP_AGE:op,seconds
pub filter: Option<String>,
/// Transform expression for message value
/// Simple path: "/message" or "/message/confId"
/// Object construction JSON (parsed separately)
pub transform: Option<String>,
/// Error handling policy for this destination
///
/// Controls what happens when filter/transform evaluation fails:
/// - "fail" - Halt pipeline on any error (default for backward compatibility)
/// - "dlq" - Send failed messages to dead letter queue
/// - "skip_and_log" - Skip bad messages and log errors
/// - "continue" - Continue processing, log errors but don't DLQ
///
/// Choose based on data criticality:
/// - Financial/audit: use "fail" or "dlq"
/// - Analytics: use "skip_and_log"
/// - Enrichment: use "continue" with try() functions
#[serde(default)]
pub error_policy: ErrorPolicy,
/// Key transformation expression (NEW)
///
/// Sets the message key for this destination. Supported formats:
/// - Simple path: "/user/id" - Extract field from value as key
/// - Template: "user-{/user/id}" - Build key from template
/// - Constant: "CONSTANT:my-key" - Set constant key
/// - Hash: "HASH:SHA256,/user/email" - Hash a field
/// - Construct: "CONSTRUCT:tenant=/tenant:user=/user/id" - Build JSON key
///
/// If not specified, the original message key is preserved.
#[serde(default)]
pub key_transform: Option<String>,
/// Headers to set on messages sent to this destination (NEW)
///
/// Static headers with constant values. For dynamic headers from message
/// values, use header_transforms instead.
///
/// Example:
/// ```yaml
/// headers:
/// x-processed-by: "streamforge"
/// x-version: "1.0"
/// ```
#[serde(default)]
pub headers: Option<HashMap<String, String>>,
/// Dynamic header transformations (NEW)
///
/// Extract headers from message values or copy from existing headers.
///
/// Supported operations:
/// - FROM:/path - Extract from value field
/// - COPY:source-header - Copy from existing header
/// - REMOVE - Remove a header
///
/// Example:
/// ```yaml
/// header_transforms:
/// - header: x-user-id
/// operation: FROM:/user/id
/// - header: x-correlation-id
/// operation: COPY:x-request-id
/// ```
#[serde(default)]
pub header_transforms: Option<Vec<HeaderTransformConfig>>,
/// Timestamp handling for messages sent to this destination (NEW)
///
/// Controls how message timestamps are set:
/// - "PRESERVE" - Keep original timestamp (default)
/// - "CURRENT" - Set to current time
/// - "/path/to/field" - Extract from value field
/// - "ADD:seconds" - Add seconds to original timestamp
/// - "SUBTRACT:seconds" - Subtract seconds from original timestamp
///
/// If not specified, the original timestamp is preserved.
#[serde(default)]
pub timestamp: Option<String>,
#[serde(default)]
pub aggregation: Option<AggregationConfig>,
/// Partition field JSON path
pub partition: Option<String>,
/// Broadcast flag for hybrid routing
#[serde(default)]
pub broadcast: bool,
/// Description
pub description: Option<String>,
/// Optional stateless WebAssembly UDFs for this destination.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub udfs: Option<DestinationUdfConfig>,
}
/// Header transformation configuration
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct HeaderTransformConfig {
/// Header name to set/modify
pub header: String,
/// Transformation operation
///
/// Formats:
/// - "FROM:/path" - Extract from message value
/// - "COPY:source-header" - Copy from another header
/// - "REMOVE" - Remove the header
/// - "constant-value" - Set to constant value
pub operation: String,
}
fn default_offset() -> String {
"latest".to_string()
}
fn default_threads() -> usize {
4
}
fn default_consumer_batch_size() -> usize {
100
}
fn default_consumer_batch_timeout_ms() -> u64 {
100
}
fn default_parallelism_factor() -> usize {
10
}
fn default_worker_queue_capacity() -> usize {
1_024
}
fn default_producer_max_in_flight() -> usize {
10_000
}
fn config_error(message: impl Into<String>) -> crate::error::MirrorMakerError {
crate::error::MirrorMakerError::Config(message.into())
}
impl Default for PerformanceConfig {
fn default() -> Self {
Self {
consumer_batch_size: default_consumer_batch_size(),
consumer_batch_timeout_ms: default_consumer_batch_timeout_ms(),
parallelism_factor: default_parallelism_factor(),
processing_mode: ProcessingMode::LegacyBatch,
worker_queue_capacity: default_worker_queue_capacity(),
fetch_min_bytes: None,
fetch_max_wait_ms: None,
linger_ms: None,
batch_size: None,
queue_buffering_max_ms: None,
producer_delivery_mode: ProducerDeliveryMode::Acknowledged,
producer_max_in_flight: default_producer_max_in_flight(),
}
}
}
impl Default for CompressionConfig {
fn default() -> Self {
Self {
compression_type: CompressionType::None,
compression_algo: CompressionAlgo::Gzip,
}
}
}
/// Commit strategy configuration for at-least-once/at-most-once semantics
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CommitStrategyConfig {
/// Enable manual commits (at-least-once) vs auto-commit (at-most-once)
/// Default: false (auto-commit for backward compatibility)
#[serde(default)]
pub manual_commit: bool,
/// Commit mode: Async or Sync
/// Async is faster but may lose commits on crash
/// Sync is slower but guarantees commits
#[serde(default)]
pub commit_mode: CommitMode,
/// Commit interval in milliseconds (for batching)
/// Only applies when manual_commit is true
/// Default: 5000 (5 seconds)
#[serde(default = "default_commit_interval_ms")]
pub commit_interval_ms: u64,
/// Enable dead letter queue for failed messages
#[serde(default)]
pub enable_dlq: bool,
/// Dead letter queue topic name
pub dlq_topic: Option<String>,
/// Maximum retries before sending to DLQ
#[serde(default = "default_max_retries")]
pub max_retries: u32,
/// Retry backoff strategy
#[serde(default)]
pub retry_backoff: RetryBackoffConfig,
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum CommitMode {
/// Async commit (faster, may lose on crash)
#[default]
Async,
/// Sync commit (slower, guaranteed)
Sync,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RetryBackoffConfig {
/// Initial backoff in milliseconds
#[serde(default = "default_initial_backoff_ms")]
pub initial_backoff_ms: u64,
/// Maximum backoff in milliseconds
#[serde(default = "default_max_backoff_ms")]
pub max_backoff_ms: u64,
/// Backoff multiplier
#[serde(default = "default_backoff_multiplier")]
pub multiplier: f64,
}
/// Cache backend configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CacheBackendConfig {
/// Cache backend type: local, redis, kafka
pub backend_type: CacheBackendType,
/// Local cache configuration
pub local: Option<LocalCacheConfig>,
/// Redis cache configuration
pub redis: Option<RedisCacheConfig>,
/// Kafka-backed cache configuration
pub kafka: Option<KafkaCacheConfig>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum CacheBackendType {
/// In-memory cache (Moka)
Local,
/// Redis cache
Redis,
/// Kafka compacted topic as cache
Kafka,
/// Multi-level: local + Redis
Multi,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LocalCacheConfig {
/// Maximum number of cache entries
#[serde(default = "default_cache_capacity")]
pub max_capacity: u64,
/// Time-to-live in seconds
pub ttl_seconds: Option<u64>,
/// Time-to-idle in seconds
pub tti_seconds: Option<u64>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RedisCacheConfig {
/// Redis connection URL
/// Format: redis://[:password@]host[:port][/database]
/// Example: redis://localhost:6379/0
pub url: String,
/// Connection pool size
#[serde(default = "default_redis_pool_size")]
pub pool_size: usize,
/// Key prefix for all cache keys
pub key_prefix: Option<String>,
/// Default TTL in seconds for cache entries
pub default_ttl_seconds: Option<u64>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct KafkaCacheConfig {
/// Kafka bootstrap servers for cache topic
pub bootstrap: String,
/// Compacted topic name to use as cache
pub topic: String,
/// Consumer group for cache consumer
pub group_id: String,
/// Key field in message (JSON path)
pub key_field: String,
/// Value field in message (JSON path, or "." for entire message)
#[serde(default = "default_value_field")]
pub value_field: String,
/// Warm up cache on startup (consume entire topic)
#[serde(default = "default_true")]
pub warmup_on_start: bool,
}
fn default_commit_interval_ms() -> u64 {
5000 // 5 seconds
}
fn default_max_retries() -> u32 {
3
}
fn default_initial_backoff_ms() -> u64 {
100
}
fn default_max_backoff_ms() -> u64 {
30000 // 30 seconds
}
fn default_backoff_multiplier() -> f64 {
2.0
}
fn default_cache_capacity() -> u64 {
10_000
}
fn default_redis_pool_size() -> usize {
10
}
fn default_value_field() -> String {
".".to_string()
}
fn default_true() -> bool {
true
}
impl Default for CommitStrategyConfig {
fn default() -> Self {
Self {
manual_commit: false, // Auto-commit by default for backward compatibility
commit_mode: CommitMode::Async,
commit_interval_ms: default_commit_interval_ms(),
enable_dlq: false,
dlq_topic: None,
max_retries: default_max_retries(),
retry_backoff: RetryBackoffConfig::default(),
}
}
}
impl Default for RetryBackoffConfig {
fn default() -> Self {
Self {
initial_backoff_ms: default_initial_backoff_ms(),
max_backoff_ms: default_max_backoff_ms(),
multiplier: default_backoff_multiplier(),
}
}
}
impl MirrorMakerConfig {
/// Load configuration from file.
///
/// Automatically detects format based on file extension:
/// - .json → JSON format
/// - .yaml, .yml → YAML format
///
/// # Examples
///
/// ```no_run
/// # use streamforge::config::MirrorMakerConfig;
/// let config = MirrorMakerConfig::from_file("config.json").unwrap();
/// let config = MirrorMakerConfig::from_file("config.yaml").unwrap();
/// ```
pub fn from_file(path: &str) -> crate::Result<Self> {
let content = std::fs::read_to_string(path)?;
// Detect format based on file extension
let config: Self = if path.ends_with(".yaml") || path.ends_with(".yml") {
serde_yaml::from_str(&content).map_err(|e| {
crate::error::MirrorMakerError::Config(format!("YAML parse error: {}", e))
})?
} else {
// Default to JSON for backward compatibility
serde_json::from_str(&content).map_err(|e| {
crate::error::MirrorMakerError::Config(format!("JSON parse error: {}", e))
})?
};
config.validate()?;
Ok(config)
}
pub fn validate(&self) -> crate::Result<()> {
if self.threads == 0 {
return Err(config_error("threads must be > 0"));
}
if self.threads > i32::MAX as usize {
return Err(config_error("threads must fit in a signed 32-bit integer"));
}
self.performance.validate()?;
if let Some(wasm) = &self.wasm {
wasm.validate().map_err(config_error)?;
}
if let Some(udfs) = &self.udfs {
if self.routing.is_some() {
return Err(config_error(
"top-level udfs is only valid in single-destination mode",
));
}
if udfs.is_empty() {
return Err(config_error(
"top-level udfs must bind at least one WebAssembly stage",
));
}
let wasm = self
.wasm
.as_ref()
.ok_or_else(|| config_error("top-level udfs requires a top-level wasm registry"))?;
wasm.validate_refs("single destination", udfs)
.map_err(config_error)?;
}
if self.performance.producer_delivery_mode == ProducerDeliveryMode::Queued {
if self.commit_strategy.manual_commit {
return Err(config_error(
"performance.producer_delivery_mode=queued requires \
commit_strategy.manual_commit=false because delivery errors are deferred",
));
}
if self.retry.max_attempts != 1 {
return Err(config_error(
"performance.producer_delivery_mode=queued requires retry.max_attempts=1 \
because deferred delivery errors cannot retry the original envelope",
));
}
if self.dlq.enabled {
return Err(config_error(
"performance.producer_delivery_mode=queued requires dlq.enabled=false \
because deferred delivery errors cannot retain the original envelope",
));
}
}
if self.performance.processing_mode == ProcessingMode::PartitionOrdered
&& self.commit_strategy.manual_commit
{
return Err(config_error(
"performance.processing_mode=partition_ordered currently requires \
commit_strategy.manual_commit=false; explicit rebalance-safe offset \
coordination is not yet implemented",
));
}
if let Some(routing) = &self.routing {
for dest in &routing.destinations {
if let Some(udfs) = &dest.udfs {
if udfs.is_empty() {
return Err(config_error(format!(
"destination {:?} udfs must bind at least one WebAssembly stage",
dest.output
)));
}
let wasm = self.wasm.as_ref().ok_or_else(|| {
config_error(format!(
"destination {:?} udfs requires a top-level wasm registry",
dest.output
))
})?;
wasm.validate_refs(&format!("destination {:?}", dest.output), udfs)
.map_err(config_error)?;
if dest.aggregation.is_some() && udfs.envelope_transform.is_some() {
return Err(config_error(
"aggregation destinations cannot use a wasm envelope_transform",
));
}
}
if let Some(aggregation) = &dest.aggregation {
if self.commit_strategy.manual_commit {
return Err(config_error(
"aggregation destinations do not support commit_strategy.manual_commit=true in v1",
));
}
if dest.key_transform.is_some() {
return Err(config_error(
"aggregation destinations cannot use key_transform",
));
}
if dest.headers.is_some()
|| dest.header_transforms.is_some()
|| dest.timestamp.is_some()
{
return Err(config_error(
"aggregation destinations cannot use header or timestamp transforms in v1",
));
}
aggregation.validate()?;
}
}
}
Ok(())
}
/// Populate Kafka property maps from optional performance settings.
///
/// Existing property-map entries always win. `linger.ms` and
/// `queue.buffering.max.ms` are librdkafka aliases, so an explicit value for
/// either suppresses generation of both.
pub fn apply_performance_property_defaults(&mut self) {
if let Some(value) = self.performance.fetch_min_bytes {
self.consumer_properties
.entry("fetch.min.bytes".to_string())
.or_insert_with(|| value.to_string());
}
if let Some(value) = self.performance.fetch_max_wait_ms {
self.consumer_properties
.entry("fetch.wait.max.ms".to_string())
.or_insert_with(|| value.to_string());
}
if let Some(value) = self.performance.batch_size {
self.producer_properties
.entry("batch.num.messages".to_string())
.or_insert_with(|| value.to_string());
}
let buffering_time_is_explicit = self.producer_properties.contains_key("linger.ms")
|| self
.producer_properties
.contains_key("queue.buffering.max.ms");
if !buffering_time_is_explicit {
// `linger.ms` and `queue.buffering.max.ms` are aliases. Preserve
// documented configs that set both by giving `linger_ms`
// deterministic precedence.
if let Some(value) = self.performance.linger_ms {
self.producer_properties
.insert("linger.ms".to_string(), value.to_string());
} else if let Some(value) = self.performance.queue_buffering_max_ms {
self.producer_properties
.insert("queue.buffering.max.ms".to_string(), value.to_string());
}
}
}
pub fn get_target_broker(&self) -> String {
self.target_broker
.as_ref()
.unwrap_or(&self.bootstrap)
.clone()
}
/// Apply security configuration to a Kafka ClientConfig
pub fn apply_security(&self, client_config: &mut rdkafka::ClientConfig) {
if let Some(security) = &self.security {
// Set security protocol
let protocol = match security.protocol {
SecurityProtocol::Plaintext => "plaintext",
SecurityProtocol::Ssl => "ssl",
SecurityProtocol::SaslPlaintext => "sasl_plaintext",
SecurityProtocol::SaslSsl => "sasl_ssl",
};
client_config.set("security.protocol", protocol);
// Apply SSL configuration
if let Some(ssl) = &security.ssl {
if let Some(ca_location) = &ssl.ca_location {
client_config.set("ssl.ca.location", ca_location);
}
if let Some(cert_location) = &ssl.certificate_location {
client_config.set("ssl.certificate.location", cert_location);
}
if let Some(key_location) = &ssl.key_location {
client_config.set("ssl.key.location", key_location);
}
if let Some(key_password) = &ssl.key_password {
client_config.set("ssl.key.password", key_password);
}
if let Some(endpoint_id) = &ssl.endpoint_identification_algorithm {
client_config.set("ssl.endpoint.identification.algorithm", endpoint_id);
}
}
// Apply SASL configuration
if let Some(sasl) = &security.sasl {
let mechanism = match sasl.mechanism {
SaslMechanism::Plain => "PLAIN",
SaslMechanism::ScramSha256 => "SCRAM-SHA-256",
SaslMechanism::ScramSha512 => "SCRAM-SHA-512",
SaslMechanism::Gssapi => "GSSAPI",
SaslMechanism::Oauthbearer => "OAUTHBEARER",