orcher-sdk 0.17.2

Rust SDK for Orcher, a durable workflow engine: workflows, tasks, actors, workers and a client
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
//! High-level client for the ORCHER orchestrator.

use crate::actor::{ActorInvocationClient, ActorRef};
use crate::error::{Error, Result};
use orcher_sdk_core::client::{
    ActorClient, ConnectOptions, Connection, NamespaceClient, StartWorkflowOpts,
    WorkflowClient as CoreClient,
};
use orcher_sdk_core::payload::codec::PayloadCodec;
use orcher_sdk_core::payload::converter::{
    BinaryPayloadConverter, DataConverter, JsonPayloadConverter,
};
use serde::{de::DeserializeOwned, Serialize};
use std::sync::Arc;

use super::{ClientConfig, StartWorkflowOptions, WorkflowHandle};

/// The workflow retry policy core sends for an SDK [`RetryPolicy`].
///
/// `max_attempts` is sent as given: the first run included, 0 for unlimited. A
/// policy built from [`RetryPolicy::default`](crate::task::RetryPolicy::default)
/// that leaves it alone sends the default of 3.
///
/// [`RetryPolicy`]: crate::task::RetryPolicy
fn workflow_retry_policy(p: &crate::task::RetryPolicy) -> orcher_sdk_core::WorkflowRetryPolicy {
    orcher_sdk_core::WorkflowRetryPolicy {
        max_attempts: p.max_attempts,
        initial_interval: Some(p.initial_interval),
        max_interval: Some(p.max_interval),
        backoff_coefficient: p.backoff_coefficient,
        non_retryable_errors: p.non_retryable_errors.clone(),
    }
}

/// Core's start options for one workflow of `workflow_type` with `input`, as
/// `options` asks.
fn start_opts(
    workflow_id: String,
    workflow_type: &str,
    input: Vec<u8>,
    options: &StartWorkflowOptions,
) -> StartWorkflowOpts {
    let mut opts = StartWorkflowOpts::new(
        workflow_id,
        workflow_type,
        options.task_queue.clone(),
        input,
    );
    opts.execution_timeout = options.workflow_execution_timeout;
    opts.run_timeout = options.workflow_run_timeout;
    opts.task_timeout = options.workflow_task_timeout;
    opts.retry_policy = options.retry_policy.as_ref().map(workflow_retry_policy);
    opts
}

/// Data converter selected by the client.
///
/// An enum rather than a trait object because `DataConverter` has generic
/// methods and so is not object-safe.
#[derive(Clone)]
pub enum DataConverterType {
    /// Encode values as JSON.
    Json(JsonPayloadConverter),
    /// Encode values in the binary payload format.
    Binary(BinaryPayloadConverter),
}

impl DataConverterType {
    /// Encode `value` with this converter.
    // The error type comes from sdk-core. Boxing it would change a public
    // signature for no benefit on a path that is not hot.
    #[allow(clippy::result_large_err)]
    pub fn to_payload<T: Serialize>(
        &self,
        value: &T,
    ) -> orcher_sdk_core::error::Result<orcher_sdk_core::payload::Payload> {
        match self {
            DataConverterType::Json(converter) => converter.to_payload(value),
            DataConverterType::Binary(converter) => converter.to_payload(value),
        }
    }

    /// Name of the encoding this converter produces, such as `json`.
    pub fn encoding(&self) -> &str {
        match self {
            DataConverterType::Json(converter) => converter.encoding(),
            DataConverterType::Binary(converter) => converter.encoding(),
        }
    }
}

impl Default for DataConverterType {
    fn default() -> Self {
        DataConverterType::Json(JsonPayloadConverter)
    }
}

/// Connection to the ORCHER orchestrator for starting and managing workflows.
///
/// Cloning is cheap: clones share the underlying gRPC channel.
///
/// ## Example
///
/// ```rust,no_run
/// # use orcher_sdk::prelude::*;
/// # async fn example() -> Result<()> {
/// let client = Client::connect("http://localhost:50051").await?;
/// let handle = client.start_workflow("MyWorkflow", "input-data").await?;
/// let result: String = handle.result().await?;
/// # Ok(())
/// # }
/// ```
#[derive(Clone)]
pub struct Client {
    pub(crate) core_client: Arc<CoreClient>,
    pub(crate) actor_client: Arc<ActorClient>,
    pub(crate) namespace_client: Arc<NamespaceClient>,
    pub(crate) config: ClientConfig,
    pub(crate) data_converter: DataConverterType,
    /// The connection the clients above share.
    pub(crate) connection: Connection,
}

impl Client {
    /// Connects to the ORCHER server at `url` with the default configuration.
    ///
    /// The URL looks like `http://localhost:50051`. An `https://` URL connects
    /// over TLS verified against the system trust store; for a private CA or
    /// mTLS, use [`Client::with_config`] with [`ClientConfig::with_tls`]. The
    /// channel connects lazily, so an unreachable server surfaces on the first
    /// call, not here.
    ///
    /// # Errors
    ///
    /// Returns [`ClientError::ConnectionFailed`] if the URL is invalid.
    ///
    /// [`ClientError::ConnectionFailed`]: crate::error::ClientError::ConnectionFailed
    pub async fn connect(url: impl Into<String>) -> Result<Self> {
        let url = url.into();
        let config = ClientConfig {
            server_url: url.clone(),
            ..Default::default()
        };

        Self::with_config(config).await
    }

    /// Creates a client from a full [`ClientConfig`].
    ///
    /// The API key and organization ID are bound to every gRPC client here.
    /// TLS follows the URL scheme (`https://` enables it) unless
    /// [`ClientConfig::tls`] is set, which is how a private CA or a client
    /// certificate is supplied.
    ///
    /// # Errors
    ///
    /// Returns [`ClientError::ConnectionFailed`] if the URL is invalid or the TLS
    /// settings are rejected.
    ///
    /// [`ClientError::ConnectionFailed`]: crate::error::ClientError::ConnectionFailed
    pub async fn with_config(config: ClientConfig) -> Result<Self> {
        tracing::info!(
            server_url = %config.server_url,
            namespace = %config.namespace,
            tls = config.tls.is_some() || crate::tls::is_https(&config.server_url),
            "Connecting to ORCHER server via gRPC"
        );

        crate::tls::validate(&config.server_url, config.tls.as_ref()).map_err(|reason| {
            Error::Client(crate::error::ClientError::ConnectionFailed {
                url: config.server_url.clone(),
                reason,
            })
        })?;
        Self::from_config(config)
    }

    /// Builds the clients on one lazy connection made as `config` says: its
    /// address, namespace, credentials and TLS. Every client shares the
    /// connection, so none can go out without the credentials the others
    /// carry.
    fn from_config(config: ClientConfig) -> Result<Self> {
        let connection = Connection::lazy(connect_options(&config)).map_err(|e| {
            Error::Client(crate::error::ClientError::ConnectionFailed {
                url: config.server_url.clone(),
                reason: e.to_string(),
            })
        })?;
        let core_client = connection.workflow_client().with_timeout(config.timeout);
        let data_converter = config.data_converter.clone().unwrap_or_default();
        Ok(Self {
            core_client: Arc::new(core_client),
            actor_client: Arc::new(connection.actor_client()),
            namespace_client: Arc::new(connection.namespace_client()),
            config,
            data_converter,
            connection,
        })
    }

    // ============================================================================
    // Configuration
    // ============================================================================

    /// Compresses workflow inputs and outputs with gzip.
    ///
    /// Replaces any codec chain already configured.
    pub fn with_gzip_compression(mut self) -> Self {
        use orcher_sdk_core::payload::codec::{CodecChain, GzipPayloadCodec};

        let chain = CodecChain::new().with_codec(GzipPayloadCodec::default());

        self.config.codec_chain = Some(Arc::new(chain));
        self
    }

    /// Encrypts workflow inputs and outputs with AES-256-GCM.
    ///
    /// Replaces any codec chain already configured. The server decrypts
    /// payloads and stores plain JSON, so this protects data in transit only;
    /// it is not end-to-end encryption.
    pub fn with_encryption(mut self, key: &[u8; 32]) -> Self {
        use orcher_sdk_core::payload::codec::{CodecChain, EncryptionPayloadCodec};

        let chain = CodecChain::new().with_codec(EncryptionPayloadCodec::new(key));

        self.config.codec_chain = Some(Arc::new(chain));
        self
    }

    /// Has no effect: TLS belongs to the connection, which is already built.
    ///
    /// Set TLS with [`ClientConfig::with_tls`] before
    /// [`Client::with_config`]. An `https://` URL needs no TLS settings at all.
    #[deprecated(
        note = "has no effect on a connected client; set TLS with ClientConfig::with_tls before Client::with_config (https:// URLs use TLS automatically)"
    )]
    pub fn with_tls(mut self, tls: super::ClientTlsConfig) -> Self {
        self.config.tls = Some(tls);
        self
    }

    /// Authenticates every later call with this API key.
    ///
    /// The workflow, actor and namespace clients are rebuilt on a new lazy
    /// connection carrying the key, so it is sent from the next call on.
    /// Clones taken before this call keep their old credentials.
    pub fn with_api_key(mut self, key: impl Into<String>) -> Self {
        self.config.api_key = Some(key.into());
        let data_converter = self.data_converter.clone();
        // The address and TLS settings were accepted when this client was
        // made, so the same connection with a key can be made too.
        let mut rebuilt = match Self::from_config(self.config.clone()) {
            Ok(rebuilt) => rebuilt,
            Err(_) => return self,
        };
        // Keep a converter chosen after connecting (use_binary_serialization).
        rebuilt.data_converter = data_converter;
        rebuilt
    }

    /// The calls this client has made so far, by method: its workflow,
    /// actor and namespace calls alike.
    pub fn wire_metrics(&self) -> orcher_sdk_core::observability::WireMetricsSnapshot {
        self.connection.wire_metrics()
    }

    /// Serializes values in the binary format instead of JSON.
    ///
    /// Binary is more compact but not human-readable.
    pub fn use_binary_serialization(mut self) -> Self {
        self.data_converter = DataConverterType::Binary(BinaryPayloadConverter);
        self
    }

    // ============================================================================
    // Starting Workflows
    // ============================================================================

    /// Starts a workflow with a generated ID on the `default` task queue.
    ///
    /// # Errors
    ///
    /// Fails if the input cannot be serialized or the server rejects the start.
    pub async fn start_workflow<I>(
        &self,
        workflow_type: impl Into<String>,
        input: I,
    ) -> Result<WorkflowHandle>
    where
        I: Serialize,
    {
        let workflow_id = uuid::Uuid::new_v4().to_string();
        let options = StartWorkflowOptions {
            workflow_id: Some(workflow_id.clone()),
            task_queue: "default".to_string(),
            ..Default::default()
        };

        self.start_workflow_with_options(workflow_type, input, options)
            .await
    }

    /// Starts a workflow with explicit options.
    ///
    /// # Errors
    ///
    /// Returns [`ClientError::WorkflowAlreadyExists`] if the workflow ID is held
    /// by an open run and the reuse policy does not allow replacing it. Fails
    /// with [`ClientError::RequestFailed`] if the input cannot be serialized or
    /// encoded, or the server rejects the start.
    ///
    /// [`ClientError::WorkflowAlreadyExists`]: crate::error::ClientError::WorkflowAlreadyExists
    /// [`ClientError::RequestFailed`]: crate::error::ClientError::RequestFailed
    pub async fn start_workflow_with_options<I>(
        &self,
        workflow_type: impl Into<String>,
        input: I,
        options: StartWorkflowOptions,
    ) -> Result<WorkflowHandle>
    where
        I: Serialize,
    {
        let workflow_type = workflow_type.into();
        let workflow_id = options
            .workflow_id
            .clone()
            .unwrap_or_else(|| uuid::Uuid::new_v4().to_string());

        let namespace = options
            .namespace
            .as_ref()
            .unwrap_or(&self.config.namespace)
            .clone();

        tracing::info!(
            workflow_type = %workflow_type,
            workflow_id = %workflow_id,
            task_queue = %options.task_queue,
            namespace = %namespace,
            "Starting workflow"
        );

        let client = self.core_client.as_ref().clone().with_namespace(&namespace);

        let input_data = if self.config.use_payload_format {
            let mut payload = self.data_converter.to_payload(&input).map_err(|e| {
                Error::Client(crate::error::ClientError::RequestFailed(format!(
                    "Failed to serialize input to Payload: {}",
                    e
                )))
            })?;

            if let Some(codec_chain) = &self.config.codec_chain {
                payload = codec_chain.encode(&payload).map_err(|e| {
                    Error::Client(crate::error::ClientError::RequestFailed(format!(
                        "Failed to encode Payload with codec chain: {}",
                        e
                    )))
                })?;
            }

            serde_json::to_vec(&payload).map_err(|e| {
                Error::Client(crate::error::ClientError::RequestFailed(format!(
                    "Failed to serialize Payload envelope: {}",
                    e
                )))
            })?
        } else {
            // Plain JSON, without an envelope.
            serde_json::to_vec(&input).map_err(|e| {
                Error::Client(crate::error::ClientError::RequestFailed(format!(
                    "Failed to serialize input: {}",
                    e
                )))
            })?
        };

        // Every option (retry policy, timeouts, reuse policy) reaches the
        // server through core's start options.
        let mut opts = start_opts(workflow_id.clone(), &workflow_type, input_data, &options);
        opts.cron_schedule = options.cron_schedule.clone();
        opts.id_reuse_policy = options.id_reuse_policy.map(|policy| policy.to_core());
        let handle = client
            .start_workflow_with_options(opts)
            .await
            .map_err(|e| match e {
                // Surface an id conflict as its own error, naming the open run,
                // rather than folding it into a generic failure.
                already @ orcher_sdk_core::error::Error::WorkflowAlreadyExists { .. } => {
                    Error::from(already)
                }
                e => Error::Client(crate::error::ClientError::RequestFailed(format!(
                    "Failed to start workflow: {}",
                    e
                ))),
            })?;

        tracing::debug!(
            workflow_id = %handle.workflow_id(),
            run_id = %handle.run_id(),
            "Workflow started successfully"
        );

        // Keep the namespace on the handle so later calls target the same one.
        Ok(WorkflowHandle::new_with_namespace(
            Arc::clone(&self.core_client),
            handle.workflow_id().to_string(),
            Some(handle.run_id().to_string()),
            Some(namespace),
        ))
    }

    /// Starts several workflows of one type in a single batch request.
    ///
    /// Much faster than calling [`Client::start_workflow`] once per input.
    /// The server generates each workflow ID. Inputs are sent as plain JSON,
    /// without the Payload envelope or codec chain, and the options'
    /// `workflow_id`, `cron_schedule` and `id_reuse_policy` are not applied.
    ///
    /// # Errors
    ///
    /// Fails if an input cannot be serialized or the server rejects the batch.
    pub async fn batch_start_workflows<I: Serialize>(
        &self,
        workflow_type: impl Into<String>,
        inputs: Vec<I>,
        options: StartWorkflowOptions,
    ) -> Result<Vec<WorkflowHandle>> {
        let workflow_type = workflow_type.into();
        let namespace = options
            .namespace
            .as_ref()
            .unwrap_or(&self.config.namespace)
            .clone();

        let mut requests = Vec::with_capacity(inputs.len());
        for input in &inputs {
            let input_bytes = serde_json::to_vec(input).map_err(|e| {
                Error::Client(crate::error::ClientError::RequestFailed(format!(
                    "Failed to serialize input: {}",
                    e
                )))
            })?;

            // The server generates each workflow id.
            requests.push(start_opts(
                String::new(),
                &workflow_type,
                input_bytes,
                &options,
            ));
        }

        let client = self.core_client.as_ref().clone().with_namespace(&namespace);
        let core_handles = client.batch_start_workflows(requests).await.map_err(|e| {
            Error::Client(crate::error::ClientError::RequestFailed(format!(
                "Failed to batch start workflows: {}",
                e
            )))
        })?;

        let handles = core_handles
            .into_iter()
            .map(|h| {
                WorkflowHandle::new_with_namespace(
                    Arc::clone(&self.core_client),
                    h.workflow_id().to_string(),
                    Some(h.run_id().to_string()),
                    Some(namespace.clone()),
                )
            })
            .collect();

        Ok(handles)
    }

    // ============================================================================
    // Getting Workflow Handles
    // ============================================================================

    /// Returns a handle to the latest run of an existing workflow.
    ///
    /// No request is made; an unknown ID surfaces on the first call through
    /// the handle.
    pub async fn get_workflow_handle(
        &self,
        workflow_id: impl Into<String>,
    ) -> Result<WorkflowHandle> {
        self.get_workflow_handle_with_run_id(workflow_id, None)
            .await
    }

    /// Returns a handle to a specific run, or to the latest run if `run_id` is `None`.
    ///
    /// No request is made; the workflow is checked on the first call through
    /// the handle. The handle uses the client's default namespace.
    pub async fn get_workflow_handle_with_run_id(
        &self,
        workflow_id: impl Into<String>,
        run_id: Option<String>,
    ) -> Result<WorkflowHandle> {
        let workflow_id = workflow_id.into();

        tracing::debug!(
            workflow_id = %workflow_id,
            run_id = ?run_id,
            "Getting workflow handle"
        );

        Ok(WorkflowHandle::new_with_namespace(
            Arc::clone(&self.core_client),
            workflow_id,
            run_id,
            None,
        ))
    }

    // ============================================================================
    // Direct Operations
    // ============================================================================

    /// Queries a workflow without first getting a handle.
    pub async fn query_workflow<Q, R>(
        &self,
        workflow_id: impl Into<String>,
        query: impl Into<String>,
        args: Q,
    ) -> Result<R>
    where
        Q: Serialize,
        R: serde::de::DeserializeOwned,
    {
        let handle = self.get_workflow_handle(workflow_id).await?;
        handle.query(query, args).await
    }

    // ============================================================================
    // Actor Operations
    // ============================================================================

    /// Returns a typed client for the actor instance identified by `key`.
    pub fn actor<A: ActorRef>(&self, key: impl Into<String>) -> A::Client {
        let handle = ActorInvocationClient::new(
            self.actor_client.clone(),
            A::actor_name().to_string(),
            key.into(),
        );
        A::client(handle)
    }

    /// Invokes an actor operation by name and waits for its result.
    ///
    /// This is the untyped form; prefer [`Client::actor`] when a typed actor
    /// is available. `input` is the operation's one argument value, sent as it
    /// is; an operation that wants several values takes one struct or tuple.
    pub async fn invoke_actor<I, O>(
        &self,
        actor_name: impl Into<String>,
        key: impl Into<String>,
        operation: impl Into<String>,
        input: I,
    ) -> Result<O>
    where
        I: Serialize,
        O: DeserializeOwned,
    {
        let handle =
            ActorInvocationClient::new(self.actor_client.clone(), actor_name.into(), key.into());
        handle.invoke(&operation.into(), &input, None).await
    }

    /// Sends an actor operation without waiting for it to run.
    ///
    /// The server still executes the operation; only the caller does not wait.
    /// `input` is the operation's one argument value, sent as it is.
    pub async fn send_actor<I>(
        &self,
        actor_name: impl Into<String>,
        key: impl Into<String>,
        operation: impl Into<String>,
        input: I,
    ) -> Result<()>
    where
        I: Serialize,
    {
        let handle =
            ActorInvocationClient::new(self.actor_client.clone(), actor_name.into(), key.into());
        handle.send(&operation.into(), &input, None).await
    }

    // ============================================================================
    // Listing & Searching Workflows
    // ============================================================================

    /// Lists workflow executions, one page at a time, with optional filters.
    pub async fn list_workflows(
        &self,
        options: orcher_sdk_core::ListWorkflowsOptions,
    ) -> Result<orcher_sdk_core::WorkflowListPage> {
        let client = self.core_client.as_ref().clone();
        client.list_workflows(options).await.map_err(|e| {
            Error::Client(crate::error::ClientError::RequestFailed(format!(
                "Failed to list workflows: {}",
                e
            )))
        })
    }

    /// Searches workflow executions with an SQL-like query.
    pub async fn search_workflows(
        &self,
        query: impl Into<String>,
        options: orcher_sdk_core::SearchWorkflowsOptions,
    ) -> Result<orcher_sdk_core::WorkflowListPage> {
        let client = self.core_client.as_ref().clone();
        client.search_workflows(query, options).await.map_err(|e| {
            Error::Client(crate::error::ClientError::RequestFailed(format!(
                "Failed to search workflows: {}",
                e
            )))
        })
    }

    // ============================================================================
    // Namespace Management
    // ============================================================================

    /// Creates a namespace.
    ///
    /// A namespace must exist before workflows can be started in it.
    pub async fn create_namespace(
        &self,
        name: impl Into<String>,
        retention_days: i32,
    ) -> Result<orcher_sdk_core::Namespace> {
        self.namespace_client
            .create_namespace(name, retention_days)
            .await
            .map_err(|e| {
                Error::Client(crate::error::ClientError::RequestFailed(format!(
                    "Failed to create namespace: {}",
                    e
                )))
            })
    }

    /// Fetches a namespace by name.
    pub async fn get_namespace(
        &self,
        name: impl Into<String>,
    ) -> Result<orcher_sdk_core::Namespace> {
        self.namespace_client
            .get_namespace(name)
            .await
            .map_err(|e| {
                Error::Client(crate::error::ClientError::RequestFailed(format!(
                    "Failed to get namespace: {}",
                    e
                )))
            })
    }

    /// Lists namespaces, returning at most the first 100.
    pub async fn list_namespaces(&self) -> Result<Vec<orcher_sdk_core::Namespace>> {
        let (namespaces, _total) = self
            .namespace_client
            .list_namespaces(100, 0)
            .await
            .map_err(|e| {
                Error::Client(crate::error::ClientError::RequestFailed(format!(
                    "Failed to list namespaces: {}",
                    e
                )))
            })?;
        Ok(namespaces)
    }

    /// Updates a namespace's description.
    ///
    /// The request sends the owner as empty and the retention period as zero.
    pub async fn update_namespace(
        &self,
        name: impl Into<String>,
        description: impl Into<String>,
    ) -> Result<orcher_sdk_core::Namespace> {
        self.namespace_client
            .update_namespace(name, description, "", 0)
            .await
            .map_err(|e| {
                Error::Client(crate::error::ClientError::RequestFailed(format!(
                    "Failed to update namespace: {}",
                    e
                )))
            })
    }

    /// Deprecates a namespace, so no new workflows can be started in it.
    pub async fn deprecate_namespace(&self, name: impl Into<String>) -> Result<()> {
        self.namespace_client
            .deprecate_namespace(name)
            .await
            .map(|_| ())
            .map_err(|e| {
                Error::Client(crate::error::ClientError::RequestFailed(format!(
                    "Failed to deprecate namespace: {}",
                    e
                )))
            })
    }

    /// Soft-deletes a namespace.
    pub async fn delete_namespace(&self, name: impl Into<String>) -> Result<()> {
        self.namespace_client
            .delete_namespace(name)
            .await
            .map_err(|e| {
                Error::Client(crate::error::ClientError::RequestFailed(format!(
                    "Failed to delete namespace: {}",
                    e
                )))
            })
    }

    /// The configuration this client was built with.
    pub fn config(&self) -> &ClientConfig {
        &self.config
    }

    /// The underlying sdk-core gRPC client.
    pub fn core_client(&self) -> &CoreClient {
        &self.core_client
    }

    /// The converter that encodes workflow inputs.
    pub fn data_converter(&self) -> &DataConverterType {
        &self.data_converter
    }

    /// Name of the encoding this client's converter produces.
    pub fn encoding(&self) -> &str {
        self.data_converter.encoding()
    }
}

impl std::fmt::Debug for Client {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Client")
            .field("server_url", &self.config.server_url)
            .field("namespace", &self.config.namespace)
            .field("timeout", &self.config.timeout)
            .field("use_payload_format", &self.config.use_payload_format)
            .finish()
    }
}

/// Core's connection options for `config`.
fn connect_options(config: &ClientConfig) -> ConnectOptions {
    let mut options = ConnectOptions::new(&config.server_url).with_namespace(&config.namespace);
    if let Some(ref key) = config.api_key {
        options = options.with_api_key(key);
    }
    if let Some(ref organization_id) = config.organization_id {
        options = options.with_organization_id(organization_id);
    }
    if let Some(ref tls) = config.tls {
        options = options.with_tls(crate::tls::to_core(tls));
    }
    options
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::time::Duration;

    #[test]
    fn a_workflow_retry_policy_left_at_its_count_sends_the_default() {
        let policy =
            crate::task::RetryPolicy::default().with_initial_interval(Duration::from_secs(2));
        assert_eq!(workflow_retry_policy(&policy).max_attempts, 3);
    }

    #[test]
    fn a_workflow_retry_policy_sends_zero_as_unlimited() {
        let policy = crate::task::RetryPolicy::default().with_max_attempts(0);
        assert_eq!(workflow_retry_policy(&policy).max_attempts, 0);
    }

    #[test]
    fn a_workflow_retry_policy_sends_its_count_as_given() {
        let policy = crate::task::RetryPolicy::default().with_max_attempts(5);
        assert_eq!(workflow_retry_policy(&policy).max_attempts, 5);
    }

    #[test]
    fn a_workflow_retry_policy_sends_its_non_retryable_errors() {
        let policy = crate::task::RetryPolicy::default()
            .with_non_retryable_errors(["InvalidInput", "Fraud"]);
        assert_eq!(
            workflow_retry_policy(&policy).non_retryable_errors,
            vec!["InvalidInput".to_string(), "Fraud".to_string()]
        );
    }

    #[test]
    fn test_client_debug() {
        let config = ClientConfig::default();
        // A real client needs a server, so this checks the config it would use.
        assert_eq!(config.server_url, "http://localhost:50051");
        assert_eq!(config.namespace, "default");
    }

    #[test]
    fn test_client_config_access() {
        let config = ClientConfig {
            server_url: "http://test:1234".to_string(),
            namespace: "test-ns".to_string(),
            timeout: Duration::from_secs(10),
            identity: "test-client".to_string(),
            use_payload_format: true,
            data_converter: None,
            codec_chain: None,
            api_key: None,
            organization_id: None,
            tls: None,
        };

        assert_eq!(config.server_url, "http://test:1234");
        assert_eq!(config.namespace, "test-ns");
        assert_eq!(config.timeout, Duration::from_secs(10));
        assert_eq!(config.identity, "test-client");
        assert!(config.use_payload_format);
    }

    #[tokio::test]
    async fn with_api_key_after_connecting_changes_the_credentials_sent() {
        let client = Client::connect("http://127.0.0.1:1").await.unwrap();
        assert_eq!(client.connection.options().api_key, None);

        let client = client.use_binary_serialization().with_api_key("key-123");

        assert_eq!(
            client.connection.options().api_key.as_deref(),
            Some("key-123")
        );
        // The binary converter chosen before survives the rebuild.
        assert_eq!(client.data_converter.encoding(), "binary");
    }

    #[tokio::test]
    async fn an_unusable_client_certificate_is_rejected_at_connect() {
        let mut tls = crate::client::ClientTlsConfig::new();
        tls.client_key = Some(b"key".to_vec());
        let config = ClientConfig::new("https://orcher.example").with_tls(tls);
        let Err(err) = Client::with_config(config).await else {
            panic!("must fail");
        };
        assert!(err.to_string().contains("must be set together"), "{err}");
    }

    #[test]
    fn test_data_converter_type_default() {
        let converter = DataConverterType::default();
        assert_eq!(converter.encoding(), "json");
    }

    #[test]
    fn test_data_converter_type_json() {
        let converter = DataConverterType::Json(JsonPayloadConverter);
        let payload = converter.to_payload(&42).unwrap();
        assert!(payload.is_json());
        assert_eq!(converter.encoding(), "json");
    }

    #[test]
    fn test_data_converter_type_binary() {
        let converter = DataConverterType::Binary(BinaryPayloadConverter);
        assert_eq!(converter.encoding(), "binary");
    }

    #[test]
    fn test_client_config_with_custom_converter() {
        let config = ClientConfig {
            data_converter: Some(DataConverterType::Binary(BinaryPayloadConverter)),
            ..Default::default()
        };
        assert!(config.data_converter.is_some());
    }

    #[test]
    fn test_client_config_payload_format_enabled_by_default() {
        let config = ClientConfig::default();
        assert!(config.use_payload_format);
    }
}