gestalt-sdk 0.0.1-alpha.15

Rust SDK scaffolding and generated protocol bindings for Gestalt executable providers
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
use hyper_util::rt::TokioIo;
use tokio::net::UnixStream;
use tonic::Request;
use tonic::codegen::async_trait;
use tonic::metadata::MetadataValue;
use tonic::service::Interceptor;
use tonic::service::interceptor::InterceptedService;
use tonic::transport::{Channel, ClientTlsConfig, Endpoint, Uri};
use tower::service_fn;

use crate::Subject;
use crate::env::{ENV_HOST_SERVICE_SOCKET, ENV_HOST_SERVICE_TOKEN};
use crate::generated::v1::{
    self as pb, workflow_provider_client::WorkflowProviderClient as ProtoWorkflowProviderClient,
};
use crate::workflow::{
    WorkflowDefinition, WorkflowDefinitionSpec, WorkflowEvent, WorkflowJson, WorkflowRun,
    WorkflowRunStatus, WorkflowSignal, workflow_event_from_proto, workflow_run_from_proto,
    workflow_run_signal_from_proto, workflow_subject_to_proto,
};

type WorkflowTransport = InterceptedService<Channel, RelayTokenInterceptor>;

const WORKFLOW_RELAY_TOKEN_HEADER: &str = "x-gestalt-host-service-relay-token";

#[derive(Debug, thiserror::Error)]
/// Errors returned by [`Workflow`].
pub enum WorkflowError {
    /// The invocation token was empty.
    #[error("workflow: invocation token is not available")]
    MissingInvocationToken,
    /// The host-service transport could not be created.
    #[error("{0}")]
    Transport(#[from] tonic::transport::Error),
    /// The host-service RPC returned a gRPC status.
    #[error("{0}")]
    Status(#[from] tonic::Status),
    /// Plain input could not be converted into the protocol request shape.
    #[error("{0}")]
    Input(#[from] crate::Error),
    /// Required environment or target configuration was invalid.
    #[error("{0}")]
    Env(String),
}

#[derive(Clone, Debug, Default)]
pub struct WorkflowApplyDefinition {
    pub provider_name: String,
    pub spec: Option<WorkflowDefinitionSpec>,
    pub idempotency_key: String,
    pub requested_by_subject_id: String,
}

#[derive(Clone, Debug, Default)]
pub struct WorkflowGetDefinition {
    pub definition_id: String,
}

#[derive(Clone, Debug, Default)]
pub struct WorkflowSetDefinitionPaused {
    pub definition_id: String,
    pub paused: bool,
    pub requested_by_subject_id: String,
}

#[derive(Clone, Debug, Default)]
pub struct WorkflowSetActivationPaused {
    pub definition_id: String,
    pub activation_id: String,
    pub paused: bool,
    pub requested_by_subject_id: String,
}

#[derive(Clone, Debug, Default)]
pub struct WorkflowDeleteDefinition {
    pub definition_id: String,
}

#[derive(Clone, Debug, Default)]
pub struct WorkflowStartRun {
    pub provider_name: String,
    pub workflow_key: String,
    pub definition_id: String,
    pub input: Option<WorkflowJson>,
    pub expected_definition_generation: i64,
    pub idempotency_key: String,
    pub created_by_subject_id: String,
    pub run_as: Option<Subject>,
}

#[derive(Clone, Debug, Default)]
pub struct WorkflowListRuns {
    pub page_size: i32,
    pub page_token: String,
    pub status: WorkflowRunStatus,
    pub target_app: String,
}

#[derive(Clone, Debug, Default)]
pub struct WorkflowGetRun {
    pub run_id: String,
}

#[derive(Clone, Debug, Default)]
pub struct WorkflowGetRunEvents {
    pub run_id: String,
}

#[derive(Clone, Debug, Default)]
pub struct WorkflowGetRunOutput {
    pub run_id: String,
}

#[derive(Clone, Debug, Default)]
pub struct WorkflowCancelRun {
    pub run_id: String,
    pub reason: String,
}

#[derive(Clone, Debug, Default)]
pub struct WorkflowSignalRun {
    pub run_id: String,
    pub signal: Option<WorkflowSignal>,
}

#[derive(Clone, Debug, Default)]
pub struct WorkflowSignalOrStartRun {
    pub provider_name: String,
    pub workflow_key: String,
    pub definition_id: String,
    pub input: Option<WorkflowJson>,
    pub expected_definition_generation: i64,
    pub idempotency_key: String,
    pub created_by_subject_id: String,
    pub signal: Option<WorkflowSignal>,
    pub run_as: Option<Subject>,
}

#[derive(Clone, Debug, Default)]
pub struct WorkflowDeliverEvent {
    pub provider_name: String,
    pub app_name: String,
    pub event: Option<WorkflowEvent>,
    pub delivered_by_subject_id: String,
}

#[async_trait]
/// Fakeable client contract for workflow calls.
pub trait WorkflowContract: Send {
    async fn apply_definition(
        &mut self,
        input: WorkflowApplyDefinition,
    ) -> std::result::Result<WorkflowDefinition, WorkflowError>;
    async fn get_definition(
        &mut self,
        input: WorkflowGetDefinition,
    ) -> std::result::Result<WorkflowDefinition, WorkflowError>;
    async fn list_definitions(
        &mut self,
    ) -> std::result::Result<pb::ListWorkflowProviderDefinitionsResponse, WorkflowError>;
    async fn set_definition_paused(
        &mut self,
        input: WorkflowSetDefinitionPaused,
    ) -> std::result::Result<WorkflowDefinition, WorkflowError>;
    async fn set_activation_paused(
        &mut self,
        input: WorkflowSetActivationPaused,
    ) -> std::result::Result<WorkflowDefinition, WorkflowError>;
    async fn delete_definition(
        &mut self,
        input: WorkflowDeleteDefinition,
    ) -> std::result::Result<(), WorkflowError>;
    async fn start_run(
        &mut self,
        input: WorkflowStartRun,
    ) -> std::result::Result<WorkflowRun, WorkflowError>;
    async fn list_runs(
        &mut self,
        input: WorkflowListRuns,
    ) -> std::result::Result<pb::ListWorkflowProviderRunsResponse, WorkflowError>;
    async fn get_run(
        &mut self,
        input: WorkflowGetRun,
    ) -> std::result::Result<WorkflowRun, WorkflowError>;
    async fn get_run_events(
        &mut self,
        input: WorkflowGetRunEvents,
    ) -> std::result::Result<pb::GetWorkflowProviderRunEventsResponse, WorkflowError>;
    async fn get_run_output(
        &mut self,
        input: WorkflowGetRunOutput,
    ) -> std::result::Result<pb::GetWorkflowProviderRunOutputResponse, WorkflowError>;
    async fn cancel_run(
        &mut self,
        input: WorkflowCancelRun,
    ) -> std::result::Result<WorkflowRun, WorkflowError>;
    async fn signal_run(
        &mut self,
        input: WorkflowSignalRun,
    ) -> std::result::Result<pb::SignalWorkflowRunResponse, WorkflowError>;
    async fn signal_or_start_run(
        &mut self,
        input: WorkflowSignalOrStartRun,
    ) -> std::result::Result<pb::SignalWorkflowRunResponse, WorkflowError>;
    async fn deliver_event(
        &mut self,
        input: WorkflowDeliverEvent,
    ) -> std::result::Result<WorkflowEvent, WorkflowError>;
}

pub(crate) fn new_workflow_apply_definition_request(
    input: WorkflowApplyDefinition,
) -> pb::ApplyWorkflowProviderDefinitionRequest {
    pb::ApplyWorkflowProviderDefinitionRequest {
        provider_name: input.provider_name,
        spec: input.spec,
        invocation_token: String::new(),
        idempotency_key: input.idempotency_key,
        requested_by_subject_id: input.requested_by_subject_id,
    }
}

pub(crate) fn new_workflow_get_definition_request(
    input: WorkflowGetDefinition,
) -> pb::GetWorkflowProviderDefinitionRequest {
    pb::GetWorkflowProviderDefinitionRequest {
        definition_id: input.definition_id,
        invocation_token: String::new(),
    }
}

pub(crate) fn new_workflow_set_definition_paused_request(
    input: WorkflowSetDefinitionPaused,
) -> pb::SetWorkflowProviderDefinitionPausedRequest {
    pb::SetWorkflowProviderDefinitionPausedRequest {
        definition_id: input.definition_id,
        paused: input.paused,
        invocation_token: String::new(),
        requested_by_subject_id: input.requested_by_subject_id,
    }
}

pub(crate) fn new_workflow_set_activation_paused_request(
    input: WorkflowSetActivationPaused,
) -> pb::SetWorkflowProviderActivationPausedRequest {
    pb::SetWorkflowProviderActivationPausedRequest {
        definition_id: input.definition_id,
        activation_id: input.activation_id,
        paused: input.paused,
        invocation_token: String::new(),
        requested_by_subject_id: input.requested_by_subject_id,
    }
}

pub(crate) fn new_workflow_delete_definition_request(
    input: WorkflowDeleteDefinition,
) -> pb::DeleteWorkflowProviderDefinitionRequest {
    pb::DeleteWorkflowProviderDefinitionRequest {
        definition_id: input.definition_id,
        invocation_token: String::new(),
    }
}

pub(crate) fn new_workflow_start_run_request(
    input: WorkflowStartRun,
) -> crate::Result<pb::StartWorkflowProviderRunRequest> {
    Ok(pb::StartWorkflowProviderRunRequest {
        provider_name: input.provider_name,
        idempotency_key: input.idempotency_key,
        created_by_subject_id: input.created_by_subject_id,
        workflow_key: input.workflow_key,
        invocation_token: String::new(),
        definition_id: input.definition_id,
        run_as: input.run_as.map(workflow_subject_to_proto),
        input: input
            .input
            .map(crate::protocol::struct_from_json)
            .transpose()?,
        expected_definition_generation: input.expected_definition_generation,
    })
}

pub(crate) fn new_workflow_list_runs_request(
    input: WorkflowListRuns,
) -> pb::ListWorkflowProviderRunsRequest {
    pb::ListWorkflowProviderRunsRequest {
        page_size: input.page_size,
        page_token: input.page_token,
        status: input.status as i32,
        invocation_token: String::new(),
        target_app: input.target_app,
    }
}

pub(crate) fn new_workflow_get_run_request(
    input: WorkflowGetRun,
) -> pb::GetWorkflowProviderRunRequest {
    pb::GetWorkflowProviderRunRequest {
        run_id: input.run_id,
        invocation_token: String::new(),
    }
}

pub(crate) fn new_workflow_get_run_events_request(
    input: WorkflowGetRunEvents,
) -> pb::GetWorkflowProviderRunEventsRequest {
    pb::GetWorkflowProviderRunEventsRequest {
        run_id: input.run_id,
        invocation_token: String::new(),
    }
}

pub(crate) fn new_workflow_get_run_output_request(
    input: WorkflowGetRunOutput,
) -> pb::GetWorkflowProviderRunOutputRequest {
    pb::GetWorkflowProviderRunOutputRequest {
        run_id: input.run_id,
        invocation_token: String::new(),
    }
}

pub(crate) fn new_workflow_cancel_run_request(
    input: WorkflowCancelRun,
) -> pb::CancelWorkflowProviderRunRequest {
    pb::CancelWorkflowProviderRunRequest {
        run_id: input.run_id,
        reason: input.reason,
        invocation_token: String::new(),
    }
}

pub(crate) fn new_workflow_signal_run_request(
    input: WorkflowSignalRun,
) -> pb::SignalWorkflowProviderRunRequest {
    pb::SignalWorkflowProviderRunRequest {
        run_id: input.run_id,
        signal: input.signal,
        invocation_token: String::new(),
    }
}

pub(crate) fn new_workflow_signal_or_start_run_request(
    input: WorkflowSignalOrStartRun,
) -> crate::Result<pb::SignalOrStartWorkflowProviderRunRequest> {
    Ok(pb::SignalOrStartWorkflowProviderRunRequest {
        provider_name: input.provider_name,
        workflow_key: input.workflow_key,
        idempotency_key: input.idempotency_key,
        created_by_subject_id: input.created_by_subject_id,
        signal: input.signal,
        invocation_token: String::new(),
        definition_id: input.definition_id,
        run_as: input.run_as.map(workflow_subject_to_proto),
        input: input
            .input
            .map(crate::protocol::struct_from_json)
            .transpose()?,
        expected_definition_generation: input.expected_definition_generation,
    })
}

pub(crate) fn new_workflow_deliver_event_request(
    input: WorkflowDeliverEvent,
) -> pb::DeliverWorkflowProviderEventRequest {
    pb::DeliverWorkflowProviderEventRequest {
        app_name: input.app_name,
        event: input.event,
        delivered_by_subject_id: input.delivered_by_subject_id,
        invocation_token: String::new(),
        provider_name: input.provider_name,
    }
}

/// Client for applying workflow definitions, starting runs, signaling, and delivering events.
pub struct Workflow {
    client: ProtoWorkflowProviderClient<WorkflowTransport>,
    invocation_token: String,
    idempotency_key: String,
}

impl Workflow {
    /// Connects to the workflow service with an invocation token from the host.
    pub async fn connect(
        invocation_token: impl AsRef<str>,
    ) -> std::result::Result<Self, WorkflowError> {
        Self::connect_with_idempotency_key(invocation_token, "").await
    }

    /// Connects with a default idempotency key for idempotent create/apply/start requests.
    pub async fn connect_with_idempotency_key(
        invocation_token: impl AsRef<str>,
        idempotency_key: impl AsRef<str>,
    ) -> std::result::Result<Self, WorkflowError> {
        let invocation_token = invocation_token.as_ref().trim().to_owned();
        if invocation_token.is_empty() {
            return Err(WorkflowError::MissingInvocationToken);
        }

        let socket_path = std::env::var(ENV_HOST_SERVICE_SOCKET)
            .map_err(|_| WorkflowError::Env(format!("{ENV_HOST_SERVICE_SOCKET} is not set")))?;
        let relay_token = std::env::var(ENV_HOST_SERVICE_TOKEN).unwrap_or_default();
        let channel = match parse_workflow_target(&socket_path)? {
            WorkflowTarget::Unix(path) => {
                Endpoint::try_from("http://[::]:50051")?
                    .connect_with_connector(service_fn(move |_: Uri| {
                        let path = path.clone();
                        async move { UnixStream::connect(path).await.map(TokioIo::new) }
                    }))
                    .await?
            }
            WorkflowTarget::Tcp(address) => {
                Endpoint::from_shared(format!("http://{address}"))?
                    .connect()
                    .await?
            }
            WorkflowTarget::Tls(address) => {
                Endpoint::from_shared(format!("https://{address}"))?
                    .tls_config(ClientTlsConfig::new().with_native_roots())?
                    .connect()
                    .await?
            }
        };

        Ok(Self {
            client: ProtoWorkflowProviderClient::with_interceptor(
                channel,
                relay_token_interceptor(relay_token.trim())?,
            ),
            invocation_token,
            idempotency_key: idempotency_key.as_ref().trim().to_owned(),
        })
    }

    pub async fn apply_definition(
        &mut self,
        input: WorkflowApplyDefinition,
    ) -> std::result::Result<WorkflowDefinition, WorkflowError> {
        let mut request = new_workflow_apply_definition_request(input);
        request.invocation_token = self.invocation_token.clone();
        if request.idempotency_key.trim().is_empty() {
            request.idempotency_key = self.idempotency_key.clone();
        }
        Ok(self.client.apply_definition(request).await?.into_inner())
    }

    pub async fn get_definition(
        &mut self,
        input: WorkflowGetDefinition,
    ) -> std::result::Result<WorkflowDefinition, WorkflowError> {
        let mut request = new_workflow_get_definition_request(input);
        request.invocation_token = self.invocation_token.clone();
        Ok(self.client.get_definition(request).await?.into_inner())
    }

    pub async fn list_definitions(
        &mut self,
    ) -> std::result::Result<pb::ListWorkflowProviderDefinitionsResponse, WorkflowError> {
        Ok(self
            .client
            .list_definitions(pb::ListWorkflowProviderDefinitionsRequest {
                invocation_token: self.invocation_token.clone(),
            })
            .await?
            .into_inner())
    }

    pub async fn set_definition_paused(
        &mut self,
        input: WorkflowSetDefinitionPaused,
    ) -> std::result::Result<WorkflowDefinition, WorkflowError> {
        let mut request = new_workflow_set_definition_paused_request(input);
        request.invocation_token = self.invocation_token.clone();
        Ok(self
            .client
            .set_definition_paused(request)
            .await?
            .into_inner())
    }

    pub async fn set_activation_paused(
        &mut self,
        input: WorkflowSetActivationPaused,
    ) -> std::result::Result<WorkflowDefinition, WorkflowError> {
        let mut request = new_workflow_set_activation_paused_request(input);
        request.invocation_token = self.invocation_token.clone();
        Ok(self
            .client
            .set_activation_paused(request)
            .await?
            .into_inner())
    }

    pub async fn delete_definition(
        &mut self,
        input: WorkflowDeleteDefinition,
    ) -> std::result::Result<(), WorkflowError> {
        let mut request = new_workflow_delete_definition_request(input);
        request.invocation_token = self.invocation_token.clone();
        self.client.delete_definition(request).await?;
        Ok(())
    }

    pub async fn start_run(
        &mut self,
        input: WorkflowStartRun,
    ) -> std::result::Result<WorkflowRun, WorkflowError> {
        let mut request = new_workflow_start_run_request(input)?;
        request.invocation_token = self.invocation_token.clone();
        if request.idempotency_key.trim().is_empty() {
            request.idempotency_key = self.idempotency_key.clone();
        }
        Ok(workflow_run_from_proto(
            self.client.start_run(request).await?.into_inner(),
        )?)
    }

    pub async fn list_runs(
        &mut self,
        input: WorkflowListRuns,
    ) -> std::result::Result<pb::ListWorkflowProviderRunsResponse, WorkflowError> {
        let mut request = new_workflow_list_runs_request(input);
        request.invocation_token = self.invocation_token.clone();
        Ok(self.client.list_runs(request).await?.into_inner())
    }

    pub async fn get_run(
        &mut self,
        input: WorkflowGetRun,
    ) -> std::result::Result<WorkflowRun, WorkflowError> {
        let mut request = new_workflow_get_run_request(input);
        request.invocation_token = self.invocation_token.clone();
        Ok(workflow_run_from_proto(
            self.client.get_run(request).await?.into_inner(),
        )?)
    }

    pub async fn get_run_events(
        &mut self,
        input: WorkflowGetRunEvents,
    ) -> std::result::Result<pb::GetWorkflowProviderRunEventsResponse, WorkflowError> {
        let mut request = new_workflow_get_run_events_request(input);
        request.invocation_token = self.invocation_token.clone();
        Ok(self.client.get_run_events(request).await?.into_inner())
    }

    pub async fn get_run_output(
        &mut self,
        input: WorkflowGetRunOutput,
    ) -> std::result::Result<pb::GetWorkflowProviderRunOutputResponse, WorkflowError> {
        let mut request = new_workflow_get_run_output_request(input);
        request.invocation_token = self.invocation_token.clone();
        Ok(self.client.get_run_output(request).await?.into_inner())
    }

    pub async fn cancel_run(
        &mut self,
        input: WorkflowCancelRun,
    ) -> std::result::Result<WorkflowRun, WorkflowError> {
        let mut request = new_workflow_cancel_run_request(input);
        request.invocation_token = self.invocation_token.clone();
        Ok(workflow_run_from_proto(
            self.client.cancel_run(request).await?.into_inner(),
        )?)
    }

    pub async fn signal_run(
        &mut self,
        input: WorkflowSignalRun,
    ) -> std::result::Result<pb::SignalWorkflowRunResponse, WorkflowError> {
        let mut request = new_workflow_signal_run_request(input);
        request.invocation_token = self.invocation_token.clone();
        Ok(workflow_run_signal_from_proto(
            self.client.signal_run(request).await?.into_inner(),
        )?)
    }

    pub async fn signal_or_start_run(
        &mut self,
        input: WorkflowSignalOrStartRun,
    ) -> std::result::Result<pb::SignalWorkflowRunResponse, WorkflowError> {
        let mut request = new_workflow_signal_or_start_run_request(input)?;
        request.invocation_token = self.invocation_token.clone();
        if request.idempotency_key.trim().is_empty() {
            request.idempotency_key = self.idempotency_key.clone();
        }
        Ok(workflow_run_signal_from_proto(
            self.client.signal_or_start_run(request).await?.into_inner(),
        )?)
    }

    pub async fn deliver_event(
        &mut self,
        input: WorkflowDeliverEvent,
    ) -> std::result::Result<WorkflowEvent, WorkflowError> {
        let mut request = new_workflow_deliver_event_request(input);
        request.invocation_token = self.invocation_token.clone();
        Ok(workflow_event_from_proto(
            self.client.deliver_event(request).await?.into_inner(),
        )?)
    }
}

#[async_trait]
impl WorkflowContract for Workflow {
    async fn apply_definition(
        &mut self,
        input: WorkflowApplyDefinition,
    ) -> std::result::Result<WorkflowDefinition, WorkflowError> {
        Workflow::apply_definition(self, input).await
    }

    async fn get_definition(
        &mut self,
        input: WorkflowGetDefinition,
    ) -> std::result::Result<WorkflowDefinition, WorkflowError> {
        Workflow::get_definition(self, input).await
    }

    async fn list_definitions(
        &mut self,
    ) -> std::result::Result<pb::ListWorkflowProviderDefinitionsResponse, WorkflowError> {
        Workflow::list_definitions(self).await
    }

    async fn set_definition_paused(
        &mut self,
        input: WorkflowSetDefinitionPaused,
    ) -> std::result::Result<WorkflowDefinition, WorkflowError> {
        Workflow::set_definition_paused(self, input).await
    }

    async fn set_activation_paused(
        &mut self,
        input: WorkflowSetActivationPaused,
    ) -> std::result::Result<WorkflowDefinition, WorkflowError> {
        Workflow::set_activation_paused(self, input).await
    }

    async fn delete_definition(
        &mut self,
        input: WorkflowDeleteDefinition,
    ) -> std::result::Result<(), WorkflowError> {
        Workflow::delete_definition(self, input).await
    }

    async fn start_run(
        &mut self,
        input: WorkflowStartRun,
    ) -> std::result::Result<WorkflowRun, WorkflowError> {
        Workflow::start_run(self, input).await
    }

    async fn list_runs(
        &mut self,
        input: WorkflowListRuns,
    ) -> std::result::Result<pb::ListWorkflowProviderRunsResponse, WorkflowError> {
        Workflow::list_runs(self, input).await
    }

    async fn get_run(
        &mut self,
        input: WorkflowGetRun,
    ) -> std::result::Result<WorkflowRun, WorkflowError> {
        Workflow::get_run(self, input).await
    }

    async fn get_run_events(
        &mut self,
        input: WorkflowGetRunEvents,
    ) -> std::result::Result<pb::GetWorkflowProviderRunEventsResponse, WorkflowError> {
        Workflow::get_run_events(self, input).await
    }

    async fn get_run_output(
        &mut self,
        input: WorkflowGetRunOutput,
    ) -> std::result::Result<pb::GetWorkflowProviderRunOutputResponse, WorkflowError> {
        Workflow::get_run_output(self, input).await
    }

    async fn cancel_run(
        &mut self,
        input: WorkflowCancelRun,
    ) -> std::result::Result<WorkflowRun, WorkflowError> {
        Workflow::cancel_run(self, input).await
    }

    async fn signal_run(
        &mut self,
        input: WorkflowSignalRun,
    ) -> std::result::Result<pb::SignalWorkflowRunResponse, WorkflowError> {
        Workflow::signal_run(self, input).await
    }

    async fn signal_or_start_run(
        &mut self,
        input: WorkflowSignalOrStartRun,
    ) -> std::result::Result<pb::SignalWorkflowRunResponse, WorkflowError> {
        Workflow::signal_or_start_run(self, input).await
    }

    async fn deliver_event(
        &mut self,
        input: WorkflowDeliverEvent,
    ) -> std::result::Result<WorkflowEvent, WorkflowError> {
        Workflow::deliver_event(self, input).await
    }
}

#[derive(Clone)]
struct RelayTokenInterceptor {
    token: Option<MetadataValue<tonic::metadata::Ascii>>,
}

impl Interceptor for RelayTokenInterceptor {
    fn call(
        &mut self,
        mut request: Request<()>,
    ) -> std::result::Result<Request<()>, tonic::Status> {
        if let Some(token) = self.token.clone() {
            request
                .metadata_mut()
                .insert(WORKFLOW_RELAY_TOKEN_HEADER, token);
        }
        Ok(request)
    }
}

fn relay_token_interceptor(
    token: &str,
) -> std::result::Result<RelayTokenInterceptor, WorkflowError> {
    let trimmed = token.trim();
    let token = if trimmed.is_empty() {
        None
    } else {
        Some(MetadataValue::try_from(trimmed).map_err(|err| {
            WorkflowError::Env(format!("workflow: invalid relay token metadata: {err}"))
        })?)
    };
    Ok(RelayTokenInterceptor { token })
}

enum WorkflowTarget {
    Unix(String),
    Tcp(String),
    Tls(String),
}

fn parse_workflow_target(raw: &str) -> std::result::Result<WorkflowTarget, WorkflowError> {
    let target = raw.trim();
    if target.is_empty() {
        return Err(WorkflowError::Env(
            "workflow: transport target is required".to_string(),
        ));
    }
    if let Some(address) = target.strip_prefix("tcp://") {
        let address = address.trim();
        if address.is_empty() {
            return Err(WorkflowError::Env(format!(
                "workflow: tcp target {raw:?} is missing host:port"
            )));
        }
        return Ok(WorkflowTarget::Tcp(address.to_string()));
    }
    if let Some(address) = target.strip_prefix("tls://") {
        let address = address.trim();
        if address.is_empty() {
            return Err(WorkflowError::Env(format!(
                "workflow: tls target {raw:?} is missing host:port"
            )));
        }
        return Ok(WorkflowTarget::Tls(address.to_string()));
    }
    if let Some(path) = target.strip_prefix("unix://") {
        let path = path.trim();
        if path.is_empty() {
            return Err(WorkflowError::Env(format!(
                "workflow: unix target {raw:?} is missing a socket path"
            )));
        }
        return Ok(WorkflowTarget::Unix(path.to_string()));
    }
    if target.contains("://") {
        return Err(WorkflowError::Env(format!(
            "workflow: unsupported target scheme in {raw:?}"
        )));
    }
    Ok(WorkflowTarget::Unix(target.to_string()))
}