-
Notifications
You must be signed in to change notification settings - Fork 123
Expand file tree
/
Copy pathenvconfig.rs
More file actions
1731 lines (1530 loc) · 58.2 KB
/
envconfig.rs
File metadata and controls
1731 lines (1530 loc) · 58.2 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
//! Environment and file-based configuration for Temporal clients.
//!
//! This module provides utilities to load Temporal client configuration from TOML files
//! and environment variables. The configuration supports multiple profiles and various
//! connection settings including TLS, authentication, and codec configuration.
//!
//! ## Environment Variables
//!
//! The following environment variables are supported:
//! - `TEMPORAL_CONFIG_FILE`: Path to the TOML configuration file
//! - `TEMPORAL_PROFILE`: Profile name to use from the configuration file
//! - `TEMPORAL_ADDRESS`: Temporal server address
//! - `TEMPORAL_NAMESPACE`: Temporal namespace
//! - `TEMPORAL_API_KEY`: API key for authentication
//! - `TEMPORAL_TLS`: A boolean (`true`/`false`) string to enable/disable TLS.
//! - `TEMPORAL_TLS_CLIENT_CERT_PATH`: Path to a client certificate file. Mutually exclusive with TEMPORAL_TLS_CLIENT_CERT_DATA, only supply one.
//! - `TEMPORAL_TLS_CLIENT_CERT_DATA`: The raw client certificate data. Mutually exclusive with TEMPORAL_TLS_CLIENT_CERT_PATH, only supply one.
//! - `TEMPORAL_TLS_CLIENT_KEY_PATH`: Path to a client key file. Mutually exclusive with TEMPORAL_TLS_CLIENT_KEY_DATA, only supply one.
//! - `TEMPORAL_TLS_CLIENT_KEY_DATA`: The raw client key data. Mutually exclusive with TEMPORAL_TLS_CLIENT_KEY_PATH, only supply one.
//! - `TEMPORAL_TLS_SERVER_CA_CERT_PATH`: Path to a server CA certificate file. Mutually exclusive with TEMPORAL_TLS_SERVER_CA_CERT_DATA, only supply one.
//! - `TEMPORAL_TLS_SERVER_CA_CERT_DATA`: The raw server CA certificate data. Mutually exclusive with TEMPORAL_TLS_SERVER_CA_CERT_PATH, only supply one.
//! - `TEMPORAL_TLS_SERVER_NAME`: The server name to use for SNI.
//! - `TEMPORAL_TLS_DISABLE_HOST_VERIFICATION`: A boolean (`true`/`false`) string to disable host verification.
//! - `TEMPORAL_CODEC_ENDPOINT`: The endpoint for a remote data converter.
//! - `TEMPORAL_CODEC_AUTH`: The authorization header value for a remote data converter.
//! - `TEMPORAL_GRPC_META_*`: gRPC metadata headers. Any variables with this prefix will be
//! converted to gRPC headers. The part of the name after the prefix is converted to the header
//! name by lowercasing it and replacing underscores with hyphens. For example
//! `TEMPORAL_GRPC_META_SOME_KEY` becomes `some-key`.
//!
//! ## TOML Configuration Format
//!
//! ```toml
//! [profile.default]
//! address = "localhost:7233"
//! namespace = "default"
//! api_key = "your-api-key"
//!
//! [profile.default.tls]
//! disabled = false
//! client_cert_path = "/path/to/cert.pem"
//! client_key_path = "/path/to/key.pem"
//!
//! [profile.default.codec]
//! endpoint = "http://localhost:8080"
//! auth = "Bearer token"
//!
//! [profile.default.grpc_meta]
//! custom_header = "value"
//! ```
use serde::{Deserialize, Serialize};
use std::{collections::HashMap, fs, path::Path};
use thiserror::Error;
/// Default profile name when none is specified
pub const DEFAULT_PROFILE: &str = "default";
/// Default configuration file name
pub const DEFAULT_CONFIG_FILE: &str = "temporal.toml";
/// Errors that can occur during configuration loading
#[derive(Debug, Error)]
pub enum ConfigError {
#[error("Profile '{0}' not found")]
ProfileNotFound(String),
#[error("Invalid configuration: {0}")]
InvalidConfig(String),
#[error("Configuration loading error: {0}")]
LoadError(Box<dyn std::error::Error>),
}
impl From<std::env::VarError> for ConfigError {
fn from(e: std::env::VarError) -> Self {
Self::LoadError(e.into())
}
}
impl From<std::str::Utf8Error> for ConfigError {
fn from(e: std::str::Utf8Error) -> Self {
Self::LoadError(e.into())
}
}
impl From<toml::de::Error> for ConfigError {
fn from(e: toml::de::Error) -> Self {
Self::LoadError(e.into())
}
}
impl From<toml::ser::Error> for ConfigError {
fn from(e: toml::ser::Error) -> Self {
Self::LoadError(e.into())
}
}
/// A source for configuration or a TLS certificate/key, from a path or raw data.
#[derive(Debug, Clone, PartialEq)]
pub enum DataSource {
Path(String),
Data(Vec<u8>),
}
/// ClientConfig represents a client config file.
#[derive(Debug, Clone, PartialEq, Default)]
pub struct ClientConfig {
/// Profiles, keyed by profile name
pub profiles: HashMap<String, ClientConfigProfile>,
}
/// ClientConfigProfile is profile-level configuration for a client.
#[derive(Debug, Clone, PartialEq, Default)]
pub struct ClientConfigProfile {
/// Client address
pub address: Option<String>,
/// Client namespace
pub namespace: Option<String>,
/// Client API key. If present and TLS field is None or present and not disabled (i.e. without Disabled as true),
/// TLS is defaulted to enabled.
pub api_key: Option<String>,
/// Optional client TLS config.
pub tls: Option<ClientConfigTLS>,
/// Optional client codec config.
pub codec: Option<ClientConfigCodec>,
/// Client gRPC metadata (aka headers). When loading from TOML and env var, or writing to TOML, the keys are
/// lowercased and underscores are replaced with hyphens. This is used for deduplicating/overriding too, so manually
/// set values that are not normalized may not get overridden with [ClientConfigProfile::apply_env_vars].
pub grpc_meta: HashMap<String, String>,
}
/// ClientConfigTLS is TLS configuration for a client.
#[derive(Debug, Clone, PartialEq, Default)]
pub struct ClientConfigTLS {
/// If Some(true), TLS is explicitly disabled. If Some(false), TLS is explicitly enabled.
/// If None, TLS behavior depends on other factors (API key presence, etc.)
pub disabled: Option<bool>,
/// Client certificate source.
pub client_cert: Option<DataSource>,
/// Client key source.
pub client_key: Option<DataSource>,
/// Server CA certificate source.
pub server_ca_cert: Option<DataSource>,
/// SNI override
pub server_name: Option<String>,
/// True if host verification should be skipped
pub disable_host_verification: bool,
}
/// Codec configuration for a client
#[derive(Debug, Clone, PartialEq, Default)]
pub struct ClientConfigCodec {
/// Remote endpoint for the codec
pub endpoint: Option<String>,
/// Auth for the codec
pub auth: Option<String>,
}
/// Options for loading client configuration
#[derive(Debug, Default)]
pub struct LoadClientConfigOptions {
/// Where to load config from. If unset, will try env vars then default path.
pub config_source: Option<DataSource>,
/// If true, will error if there are unrecognized keys
pub config_file_strict: bool,
}
/// Options for loading a client configuration profile
#[derive(Debug, Default)]
pub struct LoadClientConfigProfileOptions {
/// Where to load config from. If unset, will try env vars then default path.
pub config_source: Option<DataSource>,
/// Specific profile to use
pub config_file_profile: Option<String>,
/// If true, will error if there are unrecognized keys.
pub config_file_strict: bool,
/// Disable loading from file
pub disable_file: bool,
/// Disable loading from environment variables
pub disable_env: bool,
}
/// Options for parsing TOML configuration
#[derive(Debug, Default)]
pub struct ClientConfigFromTOMLOptions {
/// If true, will error if there are unrecognized keys.
pub strict: bool,
}
/// A source for environment variables, which can be either a provided HashMap or the system's
/// environment. This allows for deferred/lazy reading of system env vars.
enum EnvProvider<'a> {
Map(&'a HashMap<String, String>),
System,
}
impl<'a> EnvProvider<'a> {
fn get(&self, key: &str) -> Result<Option<String>, ConfigError> {
match self {
EnvProvider::Map(map) => Ok(map.get(key).cloned()),
EnvProvider::System => match std::env::var(key) {
Ok(v) => Ok(Some(v)),
Err(std::env::VarError::NotPresent) => Ok(None),
Err(e) => Err(e.into()),
},
}
}
fn contains_key(&self, key: &str) -> Result<bool, ConfigError> {
match self {
EnvProvider::Map(map) => Ok(map.contains_key(key)),
EnvProvider::System => Ok(std::env::var(key).is_ok()),
}
}
}
/// Read bytes from a file path, returning Ok(None) if it doesn't exist
fn read_path_bytes(path: &str) -> Result<Option<Vec<u8>>, ConfigError> {
if !Path::new(path).exists() {
return Ok(None);
}
match fs::read(path) {
Ok(data) => Ok(Some(data)),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
Err(e) => Err(ConfigError::LoadError(e.into())),
}
}
/// Load client configuration from TOML. This function uses environment variables (which are
/// taken from the system if not provided) to locate the configuration file. It does not apply
/// other environment variable values; that is handled by [load_client_config_profile]. This will
/// not fail if the file does not exist.
pub fn load_client_config(
options: LoadClientConfigOptions,
env_vars: Option<&HashMap<String, String>>,
) -> Result<ClientConfig, ConfigError> {
let env_provider = match env_vars {
Some(map) => EnvProvider::Map(map),
None => EnvProvider::System,
};
// Get which bytes to load from TOML
let toml_data = match options.config_source {
Some(DataSource::Data(d)) => Some(d),
Some(DataSource::Path(p)) => read_path_bytes(&p)?,
None => {
let file_path = if let Some(path) = env_provider
.get("TEMPORAL_CONFIG_FILE")?
.filter(|p| !p.is_empty())
{
path
} else {
get_default_config_file_path()?
};
read_path_bytes(&file_path)?
}
};
if let Some(data) = toml_data {
ClientConfig::from_toml(
&data,
ClientConfigFromTOMLOptions {
strict: options.config_file_strict,
},
)
} else {
Ok(ClientConfig::default())
}
}
/// Load a specific client configuration profile.
///
/// This function is the primary entry point for loading client configuration. It orchestrates loading
/// from a TOML file (if not disabled) and then applies overrides from environment variables (if not disabled).
///
/// The resolution order is as follows:
/// 1. A profile is loaded from a TOML file. The file is located by checking `options.config_source`,
/// then the `TEMPORAL_CONFIG_FILE` environment variable, then a default path. The profile within
/// the file is determined by `options.config_file_profile`, then the `TEMPORAL_PROFILE`
/// environment variable, then the "default" profile.
/// 2. Environment variables are applied on top of the loaded profile.
///
/// If `env_vars` is provided as a `HashMap`, it will be used as the source for environment
/// variables. If it is `None`, the function will fall back to using the system's environment variables.
pub fn load_client_config_profile(
options: LoadClientConfigProfileOptions,
env_vars: Option<&HashMap<String, String>>,
) -> Result<ClientConfigProfile, ConfigError> {
if options.disable_file && options.disable_env {
return Err(ConfigError::InvalidConfig(
"Cannot disable both file and environment loading".to_string(),
));
}
let env_provider = if options.disable_env {
None
} else {
Some(match env_vars {
Some(map) => EnvProvider::Map(map),
None => EnvProvider::System,
})
};
let mut profile = if options.disable_file {
ClientConfigProfile::default()
} else {
// Load the full config
let config = load_client_config(
LoadClientConfigOptions {
config_source: options.config_source,
config_file_strict: options.config_file_strict,
},
env_vars,
)?;
// Determine profile name
let (profile_name, profile_unset) = if let Some(p) = options.config_file_profile.as_deref()
{
(p.to_string(), false)
} else {
match env_provider.as_ref() {
Some(provider) => match provider.get("TEMPORAL_PROFILE")? {
Some(p) if !p.is_empty() => (p, false),
_ => (DEFAULT_PROFILE.to_string(), true),
},
None => (DEFAULT_PROFILE.to_string(), true),
}
};
if let Some(prof) = config.profiles.get(&profile_name) {
Ok(prof.clone())
} else if !profile_unset {
Err(ConfigError::ProfileNotFound(profile_name))
} else {
Ok(ClientConfigProfile::default())
}?
};
// Apply environment variables if not disabled
if !options.disable_env {
profile.load_from_env(env_vars)?;
}
Ok(profile)
}
impl ClientConfig {
/// Load configuration from a TOML string with options. This will replace all profiles within,
/// it does not do any form of merging.
pub fn from_toml(
toml_bytes: &[u8],
options: ClientConfigFromTOMLOptions,
) -> Result<Self, ConfigError> {
use strict::StrictTomlClientConfig;
let toml_str = std::str::from_utf8(toml_bytes)?;
let mut conf = ClientConfig::default();
if toml_str.trim().is_empty() {
return Ok(conf);
}
if options.strict {
let toml_conf: StrictTomlClientConfig = toml::from_str(toml_str)?;
toml_conf.apply_to_client_config(&mut conf)?;
} else {
let toml_conf: TomlClientConfig = toml::from_str(toml_str)?;
toml_conf.apply_to_client_config(&mut conf)?;
}
Ok(conf)
}
/// Convert configuration to TOML string.
pub fn to_toml(&self) -> Result<Vec<u8>, ConfigError> {
let mut toml_conf = TomlClientConfig::new();
toml_conf.populate_from_client_config(self);
Ok(toml::to_string_pretty(&toml_conf)?.into_bytes())
}
}
impl ClientConfigProfile {
/// Apply environment variable overrides to this profile.
/// If `env_vars` is `None`, the system's environment variables will be used as the source.
pub fn load_from_env(
&mut self,
env_vars: Option<&HashMap<String, String>>,
) -> Result<(), ConfigError> {
let env_provider = match env_vars {
Some(map) => EnvProvider::Map(map),
None => EnvProvider::System,
};
// Apply basic settings
if let Some(address) = env_provider.get("TEMPORAL_ADDRESS")? {
self.address = Some(address);
}
if let Some(namespace) = env_provider.get("TEMPORAL_NAMESPACE")? {
self.namespace = Some(namespace);
}
if let Some(api_key) = env_provider.get("TEMPORAL_API_KEY")? {
self.api_key = Some(api_key);
}
self.apply_tls_env_vars(&env_provider)?;
self.apply_codec_env_vars(&env_provider)?;
self.apply_grpc_meta_env_vars(&env_provider)?;
Ok(())
}
fn apply_tls_env_vars(&mut self, env_provider: &EnvProvider) -> Result<(), ConfigError> {
const TLS_ENV_VARS: &[&str] = &[
"TEMPORAL_TLS",
"TEMPORAL_TLS_CLIENT_CERT_PATH",
"TEMPORAL_TLS_CLIENT_CERT_DATA",
"TEMPORAL_TLS_CLIENT_KEY_PATH",
"TEMPORAL_TLS_CLIENT_KEY_DATA",
"TEMPORAL_TLS_SERVER_CA_CERT_PATH",
"TEMPORAL_TLS_SERVER_CA_CERT_DATA",
"TEMPORAL_TLS_SERVER_NAME",
"TEMPORAL_TLS_DISABLE_HOST_VERIFICATION",
];
if self.tls.is_none() && has_any_env_var(env_provider, TLS_ENV_VARS)? {
self.tls = Some(ClientConfigTLS::default());
}
if let Some(ref mut tls) = self.tls {
if let Some(disabled_str) = env_provider.get("TEMPORAL_TLS")?
&& let Some(disabled) = env_var_to_bool(&disabled_str)
{
tls.disabled = Some(!disabled);
}
apply_data_source_env_var(
env_provider,
"cert",
"TEMPORAL_TLS_CLIENT_CERT_PATH",
"TEMPORAL_TLS_CLIENT_CERT_DATA",
&mut tls.client_cert,
)?;
apply_data_source_env_var(
env_provider,
"key",
"TEMPORAL_TLS_CLIENT_KEY_PATH",
"TEMPORAL_TLS_CLIENT_KEY_DATA",
&mut tls.client_key,
)?;
apply_data_source_env_var(
env_provider,
"server CA cert",
"TEMPORAL_TLS_SERVER_CA_CERT_PATH",
"TEMPORAL_TLS_SERVER_CA_CERT_DATA",
&mut tls.server_ca_cert,
)?;
if let Some(v) = env_provider.get("TEMPORAL_TLS_SERVER_NAME")? {
tls.server_name = Some(v);
}
if let Some(v) = env_provider.get("TEMPORAL_TLS_DISABLE_HOST_VERIFICATION")?
&& let Some(b) = env_var_to_bool(&v)
{
tls.disable_host_verification = b;
}
}
Ok(())
}
fn apply_codec_env_vars(&mut self, env_provider: &EnvProvider) -> Result<(), ConfigError> {
const CODEC_ENV_VARS: &[&str] = &["TEMPORAL_CODEC_ENDPOINT", "TEMPORAL_CODEC_AUTH"];
if self.codec.is_none() && has_any_env_var(env_provider, CODEC_ENV_VARS)? {
self.codec = Some(ClientConfigCodec::default());
}
if let Some(ref mut codec) = self.codec {
if let Some(endpoint) = env_provider.get("TEMPORAL_CODEC_ENDPOINT")? {
codec.endpoint = Some(endpoint);
}
if let Some(auth) = env_provider.get("TEMPORAL_CODEC_AUTH")? {
codec.auth = Some(auth);
}
}
Ok(())
}
fn apply_grpc_meta_env_vars(&mut self, env_provider: &EnvProvider) -> Result<(), ConfigError> {
let mut handle_meta_var = |header_name: &str, value: &str| {
let normalized_name = normalize_grpc_meta_key(header_name);
if value.is_empty() {
self.grpc_meta.remove(&normalized_name);
} else {
self.grpc_meta.insert(normalized_name, value.to_string());
}
};
match env_provider {
EnvProvider::Map(map) => {
for (key, value) in map.iter() {
if let Some(header_name) = key.strip_prefix("TEMPORAL_GRPC_META_") {
handle_meta_var(header_name, value);
}
}
}
EnvProvider::System => {
for (key, value) in std::env::vars() {
if let Some(header_name) = key.strip_prefix("TEMPORAL_GRPC_META_") {
handle_meta_var(header_name, &value);
}
}
}
}
Ok(())
}
}
/// Helper to check if any of the given environment variables are set.
fn has_any_env_var(env_provider: &EnvProvider, keys: &[&str]) -> Result<bool, ConfigError> {
for &key in keys {
if env_provider.contains_key(key)? {
return Ok(true);
}
}
Ok(false)
}
/// Helper for applying env vars to a data source.
fn apply_data_source_env_var(
env_provider: &EnvProvider,
name: &str,
path_var: &str,
data_var: &str,
dest: &mut Option<DataSource>,
) -> Result<(), ConfigError> {
let path_val = env_provider.get(path_var)?;
let data_val = env_provider.get(data_var)?;
match (path_val, data_val) {
(Some(_), Some(_)) => Err(ConfigError::InvalidConfig(format!(
"Cannot specify both {path_var} and {data_var}"
))),
(Some(path), None) => {
if let Some(DataSource::Data(_)) = dest {
return Err(ConfigError::InvalidConfig(format!(
"Cannot specify {name} path via {path_var} when {name} data is already specified"
)));
}
*dest = Some(DataSource::Path(path));
Ok(())
}
(None, Some(data)) => {
if let Some(DataSource::Path(_)) = dest {
return Err(ConfigError::InvalidConfig(format!(
"Cannot specify {name} data via {data_var} when {name} path is already specified"
)));
}
*dest = Some(DataSource::Data(data.into_bytes()));
Ok(())
}
(None, None) => Ok(()),
}
}
/// Parse a boolean value from string (supports "true", "false", "1", "0")
fn env_var_to_bool(s: &str) -> Option<bool> {
match s.to_lowercase().as_str() {
"true" | "1" => Some(true),
"false" | "0" => Some(false),
_ => None,
}
}
/// Normalize gRPC metadata key (lowercase and replace underscores with hyphens)
fn normalize_grpc_meta_key(key: &str) -> String {
key.to_lowercase().replace('_', "-")
}
/// Get the default configuration file path
fn get_default_config_file_path() -> Result<String, ConfigError> {
// Try to get user config directory
let config_dir = dirs::config_dir()
.ok_or_else(|| ConfigError::InvalidConfig("failed getting user config dir".to_string()))?;
let path = config_dir.join("temporalio").join(DEFAULT_CONFIG_FILE);
Ok(path.to_string_lossy().to_string())
}
#[derive(Debug, Clone, Serialize, Deserialize)]
struct TomlClientConfig {
#[serde(default, rename = "profile")]
profiles: HashMap<String, TomlClientConfigProfile>,
}
impl TomlClientConfig {
fn new() -> Self {
Self {
profiles: HashMap::new(),
}
}
fn apply_to_client_config(&self, conf: &mut ClientConfig) -> Result<(), ConfigError> {
conf.profiles = HashMap::with_capacity(self.profiles.len());
for (k, v) in &self.profiles {
conf.profiles.insert(k.clone(), v.to_client_config()?);
}
Ok(())
}
fn populate_from_client_config(&mut self, conf: &ClientConfig) {
self.profiles = HashMap::with_capacity(conf.profiles.len());
for (k, v) in &conf.profiles {
let mut prof = TomlClientConfigProfile::new();
prof.populate_from_client_config(v);
self.profiles.insert(k.clone(), prof);
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
struct TomlClientConfigProfile {
#[serde(skip_serializing_if = "Option::is_none")]
address: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
namespace: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
api_key: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
tls: Option<TomlClientConfigTLS>,
#[serde(skip_serializing_if = "Option::is_none")]
codec: Option<TomlClientConfigCodec>,
#[serde(default, skip_serializing_if = "HashMap::is_empty")]
grpc_meta: HashMap<String, String>,
}
impl TomlClientConfigProfile {
fn new() -> Self {
Self {
address: None,
namespace: None,
api_key: None,
tls: None,
codec: None,
grpc_meta: HashMap::new(),
}
}
fn to_client_config(&self) -> Result<ClientConfigProfile, ConfigError> {
let mut ret = ClientConfigProfile {
address: self.address.clone(),
namespace: self.namespace.clone(),
api_key: self.api_key.clone(),
tls: self
.tls
.as_ref()
.map(|tls| tls.to_client_config())
.transpose()?,
codec: self.codec.as_ref().map(|codec| codec.to_client_config()),
grpc_meta: HashMap::new(),
};
if !self.grpc_meta.is_empty() {
ret.grpc_meta = HashMap::with_capacity(self.grpc_meta.len());
for (k, v) in &self.grpc_meta {
ret.grpc_meta.insert(normalize_grpc_meta_key(k), v.clone());
}
}
Ok(ret)
}
fn populate_from_client_config(&mut self, conf: &ClientConfigProfile) {
self.address = conf.address.clone();
self.namespace = conf.namespace.clone();
self.api_key = conf.api_key.clone();
if let Some(ref tls_conf) = conf.tls {
let mut toml_tls = TomlClientConfigTLS::new();
toml_tls.populate_from_client_config(tls_conf);
self.tls = Some(toml_tls);
} else {
self.tls = None;
}
if let Some(ref codec_conf) = conf.codec {
let mut toml_codec = TomlClientConfigCodec::new();
toml_codec.populate_from_client_config(codec_conf);
self.codec = Some(toml_codec);
} else {
self.codec = None;
}
if !conf.grpc_meta.is_empty() {
self.grpc_meta = HashMap::with_capacity(conf.grpc_meta.len());
for (k, v) in &conf.grpc_meta {
self.grpc_meta.insert(normalize_grpc_meta_key(k), v.clone());
}
} else {
self.grpc_meta.clear();
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
struct TomlClientConfigTLS {
#[serde(default, skip_serializing_if = "Option::is_none")]
disabled: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
client_cert_path: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
client_cert_data: Option<String>, // String in TOML, not Vec<u8>
#[serde(skip_serializing_if = "Option::is_none")]
client_key_path: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
client_key_data: Option<String>, // String in TOML, not Vec<u8>
#[serde(skip_serializing_if = "Option::is_none")]
server_ca_cert_path: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
server_ca_cert_data: Option<String>, // String in TOML, not Vec<u8>
#[serde(skip_serializing_if = "Option::is_none")]
server_name: Option<String>,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
disable_host_verification: bool,
}
impl TomlClientConfigTLS {
fn new() -> Self {
Self {
disabled: None,
client_cert_path: None,
client_cert_data: None,
client_key_path: None,
client_key_data: None,
server_ca_cert_path: None,
server_ca_cert_data: None,
server_name: None,
disable_host_verification: false,
}
}
fn to_client_config(&self) -> Result<ClientConfigTLS, ConfigError> {
if self.client_cert_path.is_some() && self.client_cert_data.is_some() {
return Err(ConfigError::InvalidConfig(
"Cannot specify both client_cert_path and client_cert_data".to_string(),
));
}
if self.client_key_path.is_some() && self.client_key_data.is_some() {
return Err(ConfigError::InvalidConfig(
"Cannot specify both client_key_path and client_key_data".to_string(),
));
}
if self.server_ca_cert_path.is_some() && self.server_ca_cert_data.is_some() {
return Err(ConfigError::InvalidConfig(
"Cannot specify both server_ca_cert_path and server_ca_cert_data".to_string(),
));
}
let string_to_bytes = |s: &Option<String>| {
s.as_ref().and_then(|val| {
if val.is_empty() {
None
} else {
Some(val.as_bytes().to_vec())
}
})
};
Ok(ClientConfigTLS {
disabled: self.disabled,
client_cert: self
.client_cert_path
.clone()
.map(DataSource::Path)
.or_else(|| string_to_bytes(&self.client_cert_data).map(DataSource::Data)),
client_key: self
.client_key_path
.clone()
.map(DataSource::Path)
.or_else(|| string_to_bytes(&self.client_key_data).map(DataSource::Data)),
server_ca_cert: self
.server_ca_cert_path
.clone()
.map(DataSource::Path)
.or_else(|| string_to_bytes(&self.server_ca_cert_data).map(DataSource::Data)),
server_name: self.server_name.clone(),
disable_host_verification: self.disable_host_verification,
})
}
fn populate_from_client_config(&mut self, conf: &ClientConfigTLS) {
self.disabled = conf.disabled;
if let Some(ref cert_source) = conf.client_cert {
match cert_source {
DataSource::Path(p) => self.client_cert_path = Some(p.clone()),
DataSource::Data(d) => {
self.client_cert_data = Some(String::from_utf8_lossy(d).into_owned())
}
}
}
if let Some(ref key_source) = conf.client_key {
match key_source {
DataSource::Path(p) => self.client_key_path = Some(p.clone()),
DataSource::Data(d) => {
self.client_key_data = Some(String::from_utf8_lossy(d).into_owned())
}
}
}
if let Some(ref ca_source) = conf.server_ca_cert {
match ca_source {
DataSource::Path(p) => self.server_ca_cert_path = Some(p.clone()),
DataSource::Data(d) => {
self.server_ca_cert_data = Some(String::from_utf8_lossy(d).into_owned())
}
}
}
self.server_name = conf.server_name.clone();
self.disable_host_verification = conf.disable_host_verification;
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
struct TomlClientConfigCodec {
#[serde(skip_serializing_if = "Option::is_none")]
endpoint: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
auth: Option<String>,
}
impl TomlClientConfigCodec {
fn new() -> Self {
Self {
endpoint: None,
auth: None,
}
}
fn to_client_config(&self) -> ClientConfigCodec {
ClientConfigCodec {
endpoint: self.endpoint.clone(),
auth: self.auth.clone(),
}
}
fn populate_from_client_config(&mut self, conf: &ClientConfigCodec) {
self.endpoint = conf.endpoint.clone();
self.auth = conf.auth.clone();
}
}
mod strict {
use super::{
ClientConfig, ClientConfigCodec, ClientConfigProfile, ClientConfigTLS, ConfigError,
DataSource, normalize_grpc_meta_key,
};
use serde::Deserialize;
use std::collections::HashMap;
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub(crate) struct StrictTomlClientConfig {
#[serde(default, rename = "profile")]
profiles: HashMap<String, StrictTomlClientConfigProfile>,
}
impl StrictTomlClientConfig {
pub(crate) fn apply_to_client_config(
self,
conf: &mut ClientConfig,
) -> Result<(), ConfigError> {
conf.profiles = HashMap::with_capacity(self.profiles.len());
for (k, v) in self.profiles {
conf.profiles.insert(k, v.into_client_config()?);
}
Ok(())
}
}
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct StrictTomlClientConfigProfile {
#[serde(default)]
address: Option<String>,
#[serde(default)]
namespace: Option<String>,
#[serde(default)]
api_key: Option<String>,
#[serde(default)]
tls: Option<StrictTomlClientConfigTLS>,
#[serde(default)]
codec: Option<StrictTomlClientConfigCodec>,
#[serde(default)]
grpc_meta: HashMap<String, String>,
}
impl StrictTomlClientConfigProfile {
fn into_client_config(self) -> Result<ClientConfigProfile, ConfigError> {
let mut ret = ClientConfigProfile {
address: self.address,
namespace: self.namespace,
api_key: self.api_key,
tls: self.tls.map(|tls| tls.into_client_config()).transpose()?,
codec: self.codec.map(|codec| codec.into_client_config()),
grpc_meta: HashMap::new(),
};
if !self.grpc_meta.is_empty() {
ret.grpc_meta = HashMap::with_capacity(self.grpc_meta.len());
for (k, v) in self.grpc_meta {
ret.grpc_meta.insert(normalize_grpc_meta_key(&k), v);
}
}
Ok(ret)
}
}
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct StrictTomlClientConfigTLS {
#[serde(default)]
disabled: Option<bool>,
#[serde(default)]
client_cert_path: Option<String>,
#[serde(default)]
client_cert_data: Option<String>,
#[serde(default)]
client_key_path: Option<String>,
#[serde(default)]
client_key_data: Option<String>,
#[serde(default)]
server_ca_cert_path: Option<String>,
#[serde(default)]
server_ca_cert_data: Option<String>,
#[serde(default)]
server_name: Option<String>,
#[serde(default)]
disable_host_verification: bool,
}
impl StrictTomlClientConfigTLS {
fn into_client_config(self) -> Result<ClientConfigTLS, ConfigError> {
if self.client_cert_path.is_some() && self.client_cert_data.is_some() {
return Err(ConfigError::InvalidConfig(
"Cannot specify both client_cert_path and client_cert_data".to_string(),
));
}
if self.client_key_path.is_some() && self.client_key_data.is_some() {
return Err(ConfigError::InvalidConfig(
"Cannot specify both client_key_path and client_key_data".to_string(),
));
}
if self.server_ca_cert_path.is_some() && self.server_ca_cert_data.is_some() {
return Err(ConfigError::InvalidConfig(
"Cannot specify both server_ca_cert_path and server_ca_cert_data".to_string(),
));
}
let string_to_bytes = |s: Option<String>| {
s.and_then(|val| {
if val.is_empty() {
None
} else {
Some(val.as_bytes().to_vec())
}
})
};
Ok(ClientConfigTLS {
disabled: self.disabled,
client_cert: self
.client_cert_path
.map(DataSource::Path)
.or_else(|| string_to_bytes(self.client_cert_data).map(DataSource::Data)),
client_key: self
.client_key_path
.map(DataSource::Path)
.or_else(|| string_to_bytes(self.client_key_data).map(DataSource::Data)),
server_ca_cert: self