hatchet-client 0.1.0

Rust SDK for Hatchet: run workers and trigger tasks
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
//! Client configuration: explicit settings > `HATCHET_CLIENT_*` environment
//! variables > claims inside the API token.

pub(crate) mod namespace;
mod token;

use std::fmt;
use std::path::{Path, PathBuf};
use std::str::FromStr;

use crate::{Error, Result};

const ENV_TOKEN: &str = "HATCHET_CLIENT_TOKEN";
const ENV_HOST_PORT: &str = "HATCHET_CLIENT_HOST_PORT";
const ENV_SERVER_URL: &str = "HATCHET_CLIENT_SERVER_URL";
const ENV_TENANT_ID: &str = "HATCHET_CLIENT_TENANT_ID";
const ENV_NAMESPACE: &str = "HATCHET_CLIENT_NAMESPACE";
const ENV_TLS_STRATEGY: &str = "HATCHET_CLIENT_TLS_STRATEGY";
const ENV_TLS_CERT_FILE: &str = "HATCHET_CLIENT_TLS_CERT_FILE";
const ENV_TLS_KEY_FILE: &str = "HATCHET_CLIENT_TLS_KEY_FILE";
const ENV_TLS_ROOT_CA_FILE: &str = "HATCHET_CLIENT_TLS_ROOT_CA_FILE";
const ENV_TLS_SERVER_NAME: &str = "HATCHET_CLIENT_TLS_SERVER_NAME";
const ENV_DISABLE_GZIP: &str = "HATCHET_CLIENT_DISABLE_GZIP_COMPRESSION";

/// How the gRPC connection is secured.
///
/// [`Tls`](TlsStrategy::Tls) and [`Mtls`](TlsStrategy::Mtls) need TLS
/// compiled in: a rustls crypto provider (`tls-ring`, on by default, or
/// `tls-aws-lc`) and a root store (`tls-native-roots`, on by default, or
/// `tls-webpki-roots`) — unless `HATCHET_CLIENT_TLS_ROOT_CA_FILE` supplies
/// the roots. A build missing either fails at [`Client::new`](crate::Client::new)
/// with an [`Error::Config`] naming the feature to enable;
/// [`None`](TlsStrategy::None) still works there.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum TlsStrategy {
    /// Plaintext. For local development against `hatchet-lite`, which speaks
    /// plaintext gRPC. Needs no `tls-*` feature.
    None,
    /// TLS with server verification (the default). Needs a crypto provider
    /// feature, and a root store feature or a root CA file.
    #[default]
    Tls,
    /// TLS with a client certificate: [`Tls`](TlsStrategy::Tls) plus
    /// `HATCHET_CLIENT_TLS_CERT_FILE` and `HATCHET_CLIENT_TLS_KEY_FILE`,
    /// without which [`Client::new`](crate::Client::new) fails.
    Mtls,
}

impl FromStr for TlsStrategy {
    type Err = Error;

    fn from_str(value: &str) -> Result<Self> {
        match value.to_ascii_lowercase().as_str() {
            "none" => Ok(Self::None),
            "tls" => Ok(Self::Tls),
            "mtls" => Ok(Self::Mtls),
            _ => Err(Error::Config(format!(
                "unknown TLS strategy {value:?}; expected none, tls, or mtls"
            ))),
        }
    }
}

/// Resolved, immutable client configuration.
#[derive(Clone)]
pub struct ClientConfig {
    token: String,
    tenant_id: String,
    host_port: String,
    server_url: String,
    namespace: String,
    tls_strategy: TlsStrategy,
    tls_cert_file: Option<PathBuf>,
    tls_key_file: Option<PathBuf>,
    tls_root_ca_file: Option<PathBuf>,
    tls_server_name: String,
    gzip: bool,
}

impl fmt::Debug for ClientConfig {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ClientConfig")
            .field("token", &"<redacted>")
            .field("tenant_id", &self.tenant_id)
            .field("host_port", &self.host_port)
            .field("server_url", &self.server_url)
            .field("namespace", &self.namespace)
            .field("tls_strategy", &self.tls_strategy)
            .field("tls_cert_file", &self.tls_cert_file)
            .field("tls_key_file", &self.tls_key_file)
            .field("tls_root_ca_file", &self.tls_root_ca_file)
            .field("tls_server_name", &self.tls_server_name)
            .field("gzip", &self.gzip)
            .finish()
    }
}

impl ClientConfig {
    /// Starts a configuration with nothing set explicitly.
    pub fn builder() -> ClientBuilder {
        ClientBuilder::default()
    }

    /// Resolves the configuration from `HATCHET_CLIENT_*` variables alone.
    ///
    /// # Errors
    ///
    /// The same as [`ClientBuilder::build_config`], which this is the
    /// no-explicit-settings case of.
    pub fn from_env() -> Result<Self> {
        Self::builder().build_config()
    }

    /// The API token. Treat it as a secret.
    pub fn token(&self) -> &str {
        &self.token
    }

    /// The tenant the token belongs to.
    pub fn tenant_id(&self) -> &str {
        &self.tenant_id
    }

    /// The engine's gRPC address, `host:port`.
    pub fn host_port(&self) -> &str {
        &self.host_port
    }

    /// The engine's REST/UI base URL.
    pub fn server_url(&self) -> &str {
        &self.server_url
    }

    /// The normalised namespace prefix (`"dev_"`), or `""` when unset.
    pub fn namespace(&self) -> &str {
        &self.namespace
    }

    /// How the connection is secured.
    pub fn tls_strategy(&self) -> TlsStrategy {
        self.tls_strategy
    }

    /// Client certificate for mTLS.
    pub fn tls_cert_file(&self) -> Option<&Path> {
        self.tls_cert_file.as_deref()
    }

    /// Client key for mTLS.
    pub fn tls_key_file(&self) -> Option<&Path> {
        self.tls_key_file.as_deref()
    }

    /// Root CA to trust instead of the system roots.
    pub fn tls_root_ca_file(&self) -> Option<&Path> {
        self.tls_root_ca_file.as_deref()
    }

    /// The name the server certificate is verified against.
    pub fn tls_server_name(&self) -> &str {
        &self.tls_server_name
    }

    /// Whether requests are sent gzip-compressed. Responses are always
    /// accepted compressed, whatever this says.
    pub fn gzip(&self) -> bool {
        self.gzip
    }

    /// Prefixes a workflow name, event key, or run name with the namespace,
    /// unless it already carries it. Never apply this to cron expressions.
    pub fn apply_namespace(&self, name: &str) -> String {
        namespace::apply(&self.namespace, name)
    }
}

/// Builds a [`ClientConfig`]. Anything not set here falls back to the
/// `HATCHET_CLIENT_*` environment variable, then to the token's claims. An
/// environment variable set to the empty string counts as unset.
///
/// ```no_run
/// # use hatchet_client::{Client, TlsStrategy};
/// # fn example(token: String) -> hatchet_client::Result<()> {
/// // Everything explicit: a local hatchet-lite, which speaks plaintext.
/// let client = Client::builder()
///     .token(token)
///     .host_port("localhost:7077")
///     .namespace("dev")
///     .tls(TlsStrategy::None)
///     .build()?;
/// assert_eq!(client.config().namespace(), "dev_");
/// # Ok(())
/// # }
/// ```
#[derive(Clone, Default)]
#[must_use = "a client builder configures nothing until `build` is called"]
pub struct ClientBuilder {
    token: Option<String>,
    host_port: Option<String>,
    server_url: Option<String>,
    tenant_id: Option<String>,
    namespace: Option<String>,
    tls_strategy: Option<TlsStrategy>,
    tls_cert_file: Option<PathBuf>,
    tls_key_file: Option<PathBuf>,
    tls_root_ca_file: Option<PathBuf>,
    tls_server_name: Option<String>,
    gzip: Option<bool>,
}

impl ClientBuilder {
    /// The API token (`HATCHET_CLIENT_TOKEN`).
    pub fn token(mut self, token: impl Into<String>) -> Self {
        self.token = Some(token.into());
        self
    }

    /// The engine's gRPC `host:port` (`HATCHET_CLIENT_HOST_PORT`).
    pub fn host_port(mut self, host_port: impl Into<String>) -> Self {
        self.host_port = Some(host_port.into());
        self
    }

    /// The engine's REST base URL (`HATCHET_CLIENT_SERVER_URL`).
    pub fn server_url(mut self, server_url: impl Into<String>) -> Self {
        self.server_url = Some(server_url.into());
        self
    }

    /// The tenant ID (`HATCHET_CLIENT_TENANT_ID`).
    pub fn tenant_id(mut self, tenant_id: impl Into<String>) -> Self {
        self.tenant_id = Some(tenant_id.into());
        self
    }

    /// The namespace (`HATCHET_CLIENT_NAMESPACE`); normalised to `lowercase_`.
    pub fn namespace(mut self, namespace: impl Into<String>) -> Self {
        self.namespace = Some(namespace.into());
        self
    }

    /// The TLS strategy (`HATCHET_CLIENT_TLS_STRATEGY`, default `tls`).
    pub fn tls(mut self, strategy: TlsStrategy) -> Self {
        self.tls_strategy = Some(strategy);
        self
    }

    /// Client certificate for mTLS (`HATCHET_CLIENT_TLS_CERT_FILE`).
    pub fn tls_cert_file(mut self, path: impl Into<PathBuf>) -> Self {
        self.tls_cert_file = Some(path.into());
        self
    }

    /// Client key for mTLS (`HATCHET_CLIENT_TLS_KEY_FILE`).
    pub fn tls_key_file(mut self, path: impl Into<PathBuf>) -> Self {
        self.tls_key_file = Some(path.into());
        self
    }

    /// Root CA to trust (`HATCHET_CLIENT_TLS_ROOT_CA_FILE`).
    pub fn tls_root_ca_file(mut self, path: impl Into<PathBuf>) -> Self {
        self.tls_root_ca_file = Some(path.into());
        self
    }

    /// Name to verify the server certificate against
    /// (`HATCHET_CLIENT_TLS_SERVER_NAME`, default: the host of `host_port`).
    pub fn tls_server_name(mut self, name: impl Into<String>) -> Self {
        self.tls_server_name = Some(name.into());
        self
    }

    /// Whether to gzip outgoing requests (`HATCHET_CLIENT_DISABLE_GZIP_COMPRESSION`
    /// — note the negation — default: on).
    ///
    /// Turning it off stops this client *sending* compressed requests; it
    /// still accepts compressed responses, which is exactly what the official
    /// Go SDK's `DisableGzipCompression` does. **The official SDKs have no
    /// environment variable for this at all** — the name above is this SDK's
    /// own, chosen to match Go's configuration field.
    pub fn gzip(mut self, enabled: bool) -> Self {
        self.gzip = Some(enabled);
        self
    }

    /// Resolves the configuration against the process environment.
    ///
    /// # Errors
    ///
    /// [`Error::Config`] when no token was given and `HATCHET_CLIENT_TOKEN` is
    /// unset, or when `HATCHET_CLIENT_TLS_STRATEGY` is not `none`, `tls` or
    /// `mtls`; [`Error::InvalidToken`] when the token is not a JWT whose
    /// payload decodes, or when a setting has neither an explicit value, an
    /// environment variable, nor the claim it falls back to (`host_port` ←
    /// `grpc_broadcast_address`, `server_url` ← `server_url`, `tenant_id` ←
    /// `sub`).
    pub fn build_config(self) -> Result<ClientConfig> {
        self.resolve(&|key| std::env::var(key).ok())
    }

    /// Resolves the configuration and creates a [`Client`](crate::Client).
    ///
    /// # Errors
    ///
    /// Those of [`build_config`](ClientBuilder::build_config) and
    /// [`Client::new`](crate::Client::new).
    ///
    /// # Panics
    ///
    /// Panics if called outside a tokio runtime.
    pub fn build(self) -> Result<crate::Client> {
        crate::Client::new(self.build_config()?)
    }

    /// Resolves with an injected environment lookup (tests pass a map).
    pub(crate) fn resolve(self, env: &dyn Fn(&str) -> Option<String>) -> Result<ClientConfig> {
        let env = |key: &str| env(key).filter(|value| !value.is_empty());

        let token = self.token.or_else(|| env(ENV_TOKEN)).ok_or_else(|| {
            Error::Config(format!(
                "an API token is required; set {ENV_TOKEN} or call `.token(..)`"
            ))
        })?;
        let claims = token::decode_claims(&token)?;

        let missing = |claim: &str, variable: &str| {
            Error::InvalidToken(format!("the token has no `{claim}` claim; set {variable}"))
        };
        let host_port = self
            .host_port
            .or_else(|| env(ENV_HOST_PORT))
            .or(claims.grpc_broadcast_address)
            .ok_or_else(|| missing("grpc_broadcast_address", ENV_HOST_PORT))?;
        let server_url = self
            .server_url
            .or_else(|| env(ENV_SERVER_URL))
            .or(claims.server_url)
            .ok_or_else(|| missing("server_url", ENV_SERVER_URL))?;
        let tenant_id = self
            .tenant_id
            .or_else(|| env(ENV_TENANT_ID))
            .or(claims.sub)
            .ok_or_else(|| missing("sub", ENV_TENANT_ID))?;

        let tls_strategy = match self.tls_strategy {
            Some(strategy) => strategy,
            None => env(ENV_TLS_STRATEGY)
                .map(|s| s.parse())
                .transpose()?
                .unwrap_or_default(),
        };
        let tls_server_name = self
            .tls_server_name
            .or_else(|| env(ENV_TLS_SERVER_NAME))
            .unwrap_or_else(|| host_of(&host_port).to_string());
        let path = |explicit: Option<PathBuf>, variable: &str| {
            explicit.or_else(|| env(variable).map(PathBuf::from))
        };
        let gzip = match self.gzip {
            Some(enabled) => enabled,
            None => match env(ENV_DISABLE_GZIP) {
                Some(value) => !parse_bool(&value, ENV_DISABLE_GZIP)?,
                None => true,
            },
        };

        Ok(ClientConfig {
            namespace: namespace::normalize(
                &self
                    .namespace
                    .or_else(|| env(ENV_NAMESPACE))
                    .unwrap_or_default(),
            ),
            tls_cert_file: path(self.tls_cert_file, ENV_TLS_CERT_FILE),
            tls_key_file: path(self.tls_key_file, ENV_TLS_KEY_FILE),
            tls_root_ca_file: path(self.tls_root_ca_file, ENV_TLS_ROOT_CA_FILE),
            token,
            tenant_id,
            host_port,
            server_url,
            tls_strategy,
            tls_server_name,
            gzip,
        })
    }
}

/// The boolean spellings this SDK accepts in an environment variable.
/// Deliberately narrow: a typo must be an error, not a silent `false`.
fn parse_bool(value: &str, variable: &str) -> Result<bool> {
    match value.trim().to_ascii_lowercase().as_str() {
        "true" | "1" | "yes" | "on" => Ok(true),
        "false" | "0" | "no" | "off" => Ok(false),
        _ => Err(Error::Config(format!(
            "{variable} is {value:?}; expected true or false"
        ))),
    }
}

/// Strips a leading `scheme://`, if any: `"https://engine.example.com:7077"`
/// → `"engine.example.com:7077"`; `"engine.example.com:7077"` unchanged.
pub(crate) fn strip_scheme(host_port: &str) -> &str {
    host_port
        .split_once("://")
        .map_or(host_port, |(_, rest)| rest)
}

/// `"https://engine.example.com:7077"` → `"engine.example.com"`.
/// Bracketed IPv6 literals keep their address without the brackets or port:
/// `"[::1]:7077"` → `"::1"`.
fn host_of(host_port: &str) -> &str {
    let without_scheme = strip_scheme(host_port);
    if let Some(rest) = without_scheme.strip_prefix('[')
        && let Some(end) = rest.find(']')
    {
        return &rest[..end];
    }
    without_scheme
        .rsplit_once(':')
        .map_or(without_scheme, |(host, _)| host)
}

#[cfg(test)]
mod tests {
    use super::token::tests::{full_token, token_with};
    use super::*;
    use std::collections::HashMap;

    fn env_of(pairs: &[(&str, &str)]) -> impl Fn(&str) -> Option<String> + use<> {
        let map: HashMap<String, String> = pairs
            .iter()
            .map(|(k, v)| (k.to_string(), v.to_string()))
            .collect();
        move |key| map.get(key).cloned()
    }

    fn no_env(_: &str) -> Option<String> {
        None
    }

    #[test]
    fn token_claims_fill_tenant_server_url_and_grpc_address() {
        let config = ClientConfig::builder()
            .token(full_token())
            .resolve(&no_env)
            .unwrap();
        assert_eq!(config.tenant_id(), "707d0855-80ab-4e1f-a156-f1c4546cbf52");
        assert_eq!(config.server_url(), "https://hatchet.example.com");
        assert_eq!(config.host_port(), "grpc.example.com:443");
        assert_eq!(config.namespace(), "");
        assert_eq!(config.tls_strategy(), TlsStrategy::Tls);
        assert_eq!(config.tls_server_name(), "grpc.example.com");
    }

    #[test]
    fn token_comes_from_the_environment_when_not_explicit() {
        let token = full_token();
        let env = env_of(&[("HATCHET_CLIENT_TOKEN", &token)]);
        let config = ClientConfig::builder().resolve(&env).unwrap();
        assert_eq!(config.token(), token);
    }

    #[test]
    fn environment_overrides_claims() {
        let env = env_of(&[
            ("HATCHET_CLIENT_HOST_PORT", "localhost:7077"),
            ("HATCHET_CLIENT_SERVER_URL", "http://localhost:8888"),
            ("HATCHET_CLIENT_TENANT_ID", "env-tenant"),
            ("HATCHET_CLIENT_NAMESPACE", "Dev"),
            ("HATCHET_CLIENT_TLS_STRATEGY", "none"),
            ("HATCHET_CLIENT_TLS_SERVER_NAME", "engine.internal"),
        ]);
        let config = ClientConfig::builder()
            .token(full_token())
            .resolve(&env)
            .unwrap();
        assert_eq!(config.host_port(), "localhost:7077");
        assert_eq!(config.server_url(), "http://localhost:8888");
        assert_eq!(config.tenant_id(), "env-tenant");
        assert_eq!(config.namespace(), "dev_");
        assert_eq!(config.tls_strategy(), TlsStrategy::None);
        assert_eq!(config.tls_server_name(), "engine.internal");
    }

    #[test]
    fn explicit_settings_override_the_environment() {
        let env = env_of(&[
            ("HATCHET_CLIENT_TOKEN", "env.token.ignored"),
            ("HATCHET_CLIENT_HOST_PORT", "env-host:1"),
            ("HATCHET_CLIENT_NAMESPACE", "env"),
            ("HATCHET_CLIENT_TLS_STRATEGY", "mtls"),
        ]);
        let config = ClientConfig::builder()
            .token(full_token())
            .host_port("explicit-host:2")
            .namespace("Explicit")
            .tls(TlsStrategy::None)
            .resolve(&env)
            .unwrap();
        assert_eq!(config.host_port(), "explicit-host:2");
        assert_eq!(config.namespace(), "explicit_");
        assert_eq!(config.tls_strategy(), TlsStrategy::None);
        assert_eq!(config.tls_server_name(), "explicit-host");
    }

    #[test]
    fn empty_environment_values_count_as_unset() {
        let env = env_of(&[
            ("HATCHET_CLIENT_HOST_PORT", ""),
            ("HATCHET_CLIENT_NAMESPACE", ""),
        ]);
        let config = ClientConfig::builder()
            .token(full_token())
            .resolve(&env)
            .unwrap();
        assert_eq!(config.host_port(), "grpc.example.com:443");
        assert_eq!(config.namespace(), "");
    }

    #[test]
    fn a_missing_token_is_a_config_error_naming_the_variable() {
        let err = ClientConfig::builder().resolve(&no_env).unwrap_err();
        assert!(matches!(err, Error::Config(_)), "{err:?}");
        assert!(err.to_string().contains("HATCHET_CLIENT_TOKEN"), "{err}");
    }

    #[test]
    fn a_claim_missing_everywhere_is_an_error_naming_it() {
        let token = token_with(serde_json::json!({"sub": "tenant"}));
        let err = ClientConfig::builder()
            .token(token)
            .resolve(&no_env)
            .unwrap_err();
        assert!(matches!(err, Error::InvalidToken(_)), "{err:?}");
        assert!(err.to_string().contains("grpc_broadcast_address"), "{err}");
        assert!(
            err.to_string().contains("HATCHET_CLIENT_HOST_PORT"),
            "{err}"
        );
    }

    #[test]
    fn a_missing_claim_is_fine_when_supplied_another_way() {
        let token = token_with(serde_json::json!({"sub": "tenant"}));
        let config = ClientConfig::builder()
            .token(token)
            .host_port("localhost:7077")
            .server_url("http://localhost:8888")
            .resolve(&no_env)
            .unwrap();
        assert_eq!(config.tenant_id(), "tenant");
    }

    #[test]
    fn unknown_tls_strategy_is_a_config_error() {
        let env = env_of(&[("HATCHET_CLIENT_TLS_STRATEGY", "ssl")]);
        let err = ClientConfig::builder()
            .token(full_token())
            .resolve(&env)
            .unwrap_err();
        assert!(err.to_string().contains("ssl"), "{err}");
    }

    #[test]
    fn tls_files_come_from_the_environment() {
        let env = env_of(&[
            ("HATCHET_CLIENT_TLS_CERT_FILE", "/certs/client.pem"),
            ("HATCHET_CLIENT_TLS_KEY_FILE", "/certs/client.key"),
            ("HATCHET_CLIENT_TLS_ROOT_CA_FILE", "/certs/ca.pem"),
        ]);
        let config = ClientConfig::builder()
            .token(full_token())
            .resolve(&env)
            .unwrap();
        assert_eq!(config.tls_cert_file(), Some(Path::new("/certs/client.pem")));
        assert_eq!(config.tls_key_file(), Some(Path::new("/certs/client.key")));
        assert_eq!(config.tls_root_ca_file(), Some(Path::new("/certs/ca.pem")));
    }

    #[test]
    fn host_of_strips_scheme_port_and_ipv6_brackets() {
        assert_eq!(host_of("engine.example.com:7077"), "engine.example.com");
        assert_eq!(host_of("localhost"), "localhost");
        assert_eq!(host_of("[::1]:7077"), "::1");
        assert_eq!(host_of("https://[2001:db8::1]:443"), "2001:db8::1");
    }

    #[test]
    fn server_name_defaults_to_the_host_without_port_or_scheme() {
        let config = ClientConfig::builder()
            .token(full_token())
            .host_port("https://engine.example.com:7077")
            .resolve(&no_env)
            .unwrap();
        assert_eq!(config.tls_server_name(), "engine.example.com");
    }

    #[test]
    fn apply_namespace_uses_the_configured_namespace() {
        let config = ClientConfig::builder()
            .token(full_token())
            .namespace("Dev")
            .resolve(&no_env)
            .unwrap();
        assert_eq!(config.apply_namespace("agent-run"), "dev_agent-run");
        assert_eq!(config.apply_namespace("dev_agent-run"), "dev_agent-run");
    }

    #[test]
    fn gzip_is_on_by_default() {
        let config = ClientConfig::builder()
            .token(full_token())
            .resolve(&no_env)
            .unwrap();
        assert!(config.gzip());
    }

    #[test]
    fn the_environment_can_turn_gzip_off() {
        for value in ["true", "TRUE", "1", "yes", "on"] {
            let env = env_of(&[("HATCHET_CLIENT_DISABLE_GZIP_COMPRESSION", value)]);
            let config = ClientConfig::builder()
                .token(full_token())
                .resolve(&env)
                .unwrap();
            assert!(!config.gzip(), "{value}");
        }
        for value in ["false", "0", "no", "off"] {
            let env = env_of(&[("HATCHET_CLIENT_DISABLE_GZIP_COMPRESSION", value)]);
            let config = ClientConfig::builder()
                .token(full_token())
                .resolve(&env)
                .unwrap();
            assert!(config.gzip(), "{value}");
        }
    }

    #[test]
    fn an_explicit_gzip_setting_overrides_the_environment() {
        let env = env_of(&[("HATCHET_CLIENT_DISABLE_GZIP_COMPRESSION", "true")]);
        let config = ClientConfig::builder()
            .token(full_token())
            .gzip(true)
            .resolve(&env)
            .unwrap();
        assert!(config.gzip());
    }

    #[test]
    fn an_unparseable_gzip_value_is_a_config_error_naming_the_variable() {
        let env = env_of(&[("HATCHET_CLIENT_DISABLE_GZIP_COMPRESSION", "maybe")]);
        let err = ClientConfig::builder()
            .token(full_token())
            .resolve(&env)
            .unwrap_err();
        assert!(matches!(err, Error::Config(_)), "{err:?}");
        assert!(
            err.to_string()
                .contains("HATCHET_CLIENT_DISABLE_GZIP_COMPRESSION"),
            "{err}"
        );
        assert!(err.to_string().contains("maybe"), "{err}");
    }

    #[test]
    fn debug_output_shows_the_gzip_setting() {
        let config = ClientConfig::builder()
            .token(full_token())
            .gzip(false)
            .resolve(&no_env)
            .unwrap();
        assert!(format!("{config:?}").contains("gzip"), "{config:?}");
    }

    #[test]
    fn debug_output_redacts_the_token() {
        let token = full_token();
        let config = ClientConfig::builder()
            .token(token.clone())
            .resolve(&no_env)
            .unwrap();
        let debug = format!("{config:?}");
        assert!(!debug.contains(&token), "{debug}");
        assert!(debug.contains("redacted"), "{debug}");
    }
}