dapr-durabletask 0.0.1

Dapr Durable Task Framework
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
use tonic::transport::{Certificate, Channel, ClientTlsConfig, Identity};

use crate::api::{DurableTaskError, OrchestrationState, PurgeInstanceFilter, Result};
use crate::internal;
use crate::proto;
use crate::proto::task_hub_sidecar_service_client::TaskHubSidecarServiceClient;

use super::options::ClientOptions;

/// Client for managing orchestrations via a gRPC connection to a sidecar.
pub struct TaskHubGrpcClient {
    inner: TaskHubSidecarServiceClient<Channel>,
    options: ClientOptions,
}

// ─── Channel construction ────────────────────────────────────────────────────

/// Build a tonic [`Channel`] from the host address and client options,
/// applying TLS, keepalive, connect timeout, and message-size limits.
async fn build_channel(host_address: &str, options: &ClientOptions) -> Result<Channel> {
    let mut builder = Channel::from_shared(host_address.to_string())
        .map_err(|e| DurableTaskError::Other(e.to_string()))?;

    if let Some(tls) = &options.tls {
        if tls.skip_verify {
            return Err(DurableTaskError::Other(
                "skip_verify is not supported; connect without TLS for development".into(),
            ));
        }

        let mut tls_config = ClientTlsConfig::new();

        if let Some(ca_pem) = &tls.ca_cert_pem {
            tls_config = tls_config.ca_certificate(Certificate::from_pem(ca_pem));
        }

        match (&tls.client_cert_pem, &tls.client_key_pem) {
            (Some(cert), Some(key)) => {
                tls_config = tls_config.identity(Identity::from_pem(cert, key));
            }
            (None, None) => {}
            _ => {
                return Err(DurableTaskError::Other(
                    "client_cert_pem and client_key_pem must both be set for mutual TLS".into(),
                ));
            }
        }

        if let Some(domain) = &tls.domain_name {
            tls_config = tls_config.domain_name(domain.clone());
        }

        builder = builder
            .tls_config(tls_config)
            .map_err(|e| DurableTaskError::Other(e.to_string()))?;
    }

    if let Some(timeout) = options.connect_timeout {
        builder = builder.connect_timeout(timeout);
    }

    if let Some(interval) = options.keepalive_interval {
        builder = builder.tcp_keepalive(Some(interval));
    }

    builder
        .connect()
        .await
        .map_err(|e| DurableTaskError::Other(e.to_string()))
}

/// Wrap a channel in the gRPC client stub, applying the max-message-size limit.
fn make_stub(channel: Channel, options: &ClientOptions) -> TaskHubSidecarServiceClient<Channel> {
    let mut stub = TaskHubSidecarServiceClient::new(channel);
    if let Some(size) = options.max_grpc_message_size {
        stub = stub.max_decoding_message_size(size);
    }
    stub
}

// ─── TaskHubGrpcClient ───────────────────────────────────────────────────────

impl TaskHubGrpcClient {
    /// Create a new client connected to the given host address.
    ///
    /// The default address is `http://localhost:4001`.
    pub async fn new(host_address: &str) -> Result<Self> {
        Self::with_options(host_address, ClientOptions::default()).await
    }

    /// Create a new client connected to the given host address with custom options.
    pub async fn with_options(host_address: &str, options: ClientOptions) -> Result<Self> {
        tracing::info!(address = %host_address, "Connecting to sidecar");
        let channel = build_channel(host_address, &options).await?;
        tracing::info!(address = %host_address, "Client connected");
        let inner = make_stub(channel, &options);
        Ok(Self { inner, options })
    }

    /// Create a client from an existing tonic [`Channel`].
    pub fn from_channel(channel: Channel) -> Self {
        let options = ClientOptions::default();
        let inner = make_stub(channel, &options);
        Self { inner, options }
    }

    /// Create a client from an existing tonic [`Channel`] with custom options.
    pub fn from_channel_with_options(channel: Channel, options: ClientOptions) -> Self {
        let inner = make_stub(channel, &options);
        Self { inner, options }
    }

    /// Close the client, releasing the underlying gRPC channel.
    ///
    /// The channel is also released when the client is dropped. This method
    /// provides an explicit, named alternative.
    pub fn close(self) {
        drop(self);
    }

    /// Schedule a new orchestration instance and return its instance ID.
    pub async fn schedule_new_orchestration(
        &mut self,
        orchestrator_name: &str,
        input: Option<String>,
        instance_id: Option<String>,
        start_at: Option<chrono::DateTime<chrono::Utc>>,
    ) -> Result<String> {
        internal::validate_identifier(
            orchestrator_name,
            "orchestrator name",
            self.options.max_identifier_length,
        )?;
        let instance_id = instance_id.unwrap_or_else(|| uuid::Uuid::new_v4().to_string());
        internal::validate_identifier(
            &instance_id,
            "instance ID",
            self.options.max_identifier_length,
        )?;

        tracing::info!(
            instance_id = %instance_id,
            orchestrator = %orchestrator_name,
            "Scheduling new orchestration"
        );

        #[cfg(feature = "opentelemetry")]
        let (parent_trace_context, _otel_ctx) = {
            let parent_ctx = opentelemetry::Context::current();
            let ctx = internal::otel::start_create_orchestration_span(
                &parent_ctx,
                orchestrator_name,
                &instance_id,
            );
            let sc = opentelemetry::trace::TraceContextExt::span(&ctx)
                .span_context()
                .clone();
            let tc = internal::otel::trace_context_from_span_context(&sc);
            (tc, ctx)
        };
        #[cfg(not(feature = "opentelemetry"))]
        let parent_trace_context: Option<proto::TraceContext> = None;

        let request = proto::CreateInstanceRequest {
            instance_id: instance_id.clone(),
            name: orchestrator_name.to_string(),
            input,
            scheduled_start_timestamp: start_at.map(internal::to_timestamp),
            version: None,
            execution_id: None,
            tags: std::collections::HashMap::new(),
            parent_trace_context,
        };

        let response = self.inner.start_instance(request).await?;
        let result_id = response.into_inner().instance_id;

        #[cfg(feature = "opentelemetry")]
        internal::otel::end_span(&_otel_ctx);

        tracing::debug!(instance_id = %result_id, "Orchestration scheduled");
        Ok(result_id)
    }

    /// Get the current state of an orchestration.
    pub async fn get_orchestration_state(
        &mut self,
        instance_id: &str,
        fetch_payloads: bool,
    ) -> Result<Option<OrchestrationState>> {
        internal::validate_identifier(
            instance_id,
            "instance ID",
            self.options.max_identifier_length,
        )?;
        let request = proto::GetInstanceRequest {
            instance_id: instance_id.to_string(),
            get_inputs_and_outputs: fetch_payloads,
        };
        let response = self.inner.get_instance(request).await?;
        Ok(OrchestrationState::try_from(&response.into_inner()).ok())
    }

    /// Wait for an orchestration to start running.
    pub async fn wait_for_orchestration_start(
        &mut self,
        instance_id: &str,
        fetch_payloads: bool,
        timeout: Option<std::time::Duration>,
    ) -> Result<Option<OrchestrationState>> {
        internal::validate_identifier(
            instance_id,
            "instance ID",
            self.options.max_identifier_length,
        )?;
        tracing::debug!(instance_id = %instance_id, "Waiting for orchestration to start");

        let request = proto::GetInstanceRequest {
            instance_id: instance_id.to_string(),
            get_inputs_and_outputs: fetch_payloads,
        };

        let fut = self.inner.wait_for_instance_start(request);

        let response = if let Some(timeout_dur) = timeout {
            tokio::time::timeout(timeout_dur, fut)
                .await
                .map_err(|_| DurableTaskError::Timeout)??
        } else {
            fut.await?
        };

        let state = OrchestrationState::try_from(&response.into_inner()).ok();
        tracing::debug!(
            instance_id = %instance_id,
            status = ?state.as_ref().map(|s| &s.runtime_status),
            "Orchestration started"
        );
        Ok(state)
    }

    /// Wait for an orchestration to reach a terminal state.
    pub async fn wait_for_orchestration_completion(
        &mut self,
        instance_id: &str,
        fetch_payloads: bool,
        timeout: Option<std::time::Duration>,
    ) -> Result<Option<OrchestrationState>> {
        internal::validate_identifier(
            instance_id,
            "instance ID",
            self.options.max_identifier_length,
        )?;
        tracing::debug!(instance_id = %instance_id, "Waiting for orchestration completion");

        let request = proto::GetInstanceRequest {
            instance_id: instance_id.to_string(),
            get_inputs_and_outputs: fetch_payloads,
        };

        let fut = self.inner.wait_for_instance_completion(request);

        let response = if let Some(timeout_dur) = timeout {
            tokio::time::timeout(timeout_dur, fut)
                .await
                .map_err(|_| DurableTaskError::Timeout)??
        } else {
            fut.await?
        };

        let state = OrchestrationState::try_from(&response.into_inner()).ok();
        tracing::debug!(
            instance_id = %instance_id,
            status = ?state.as_ref().map(|s| &s.runtime_status),
            "Orchestration completed"
        );
        Ok(state)
    }

    /// Raise an event to an orchestration instance.
    pub async fn raise_orchestration_event(
        &mut self,
        instance_id: &str,
        event_name: &str,
        data: Option<String>,
    ) -> Result<()> {
        internal::validate_identifier(
            instance_id,
            "instance ID",
            self.options.max_identifier_length,
        )?;
        internal::validate_identifier(
            event_name,
            "event name",
            self.options.max_identifier_length,
        )?;
        tracing::info!(
            instance_id = %instance_id,
            event_name = %event_name,
            "Raising orchestration event"
        );
        let request = proto::RaiseEventRequest {
            instance_id: instance_id.to_string(),
            name: event_name.to_string(),
            input: data,
        };
        self.inner.raise_event(request).await?;
        Ok(())
    }

    /// Terminate a running orchestration.
    pub async fn terminate_orchestration(
        &mut self,
        instance_id: &str,
        output: Option<String>,
        recursive: bool,
    ) -> Result<()> {
        internal::validate_identifier(
            instance_id,
            "instance ID",
            self.options.max_identifier_length,
        )?;
        tracing::info!(
            instance_id = %instance_id,
            recursive = recursive,
            "Terminating orchestration"
        );
        let request = proto::TerminateRequest {
            instance_id: instance_id.to_string(),
            output,
            recursive,
        };
        self.inner.terminate_instance(request).await?;
        Ok(())
    }

    /// Suspend a running orchestration.
    pub async fn suspend_orchestration(
        &mut self,
        instance_id: &str,
        reason: Option<String>,
    ) -> Result<()> {
        internal::validate_identifier(
            instance_id,
            "instance ID",
            self.options.max_identifier_length,
        )?;
        tracing::info!(instance_id = %instance_id, "Suspending orchestration");
        let request = proto::SuspendRequest {
            instance_id: instance_id.to_string(),
            reason,
        };
        self.inner.suspend_instance(request).await?;
        Ok(())
    }

    /// Resume a suspended orchestration.
    pub async fn resume_orchestration(
        &mut self,
        instance_id: &str,
        reason: Option<String>,
    ) -> Result<()> {
        internal::validate_identifier(
            instance_id,
            "instance ID",
            self.options.max_identifier_length,
        )?;
        tracing::info!(instance_id = %instance_id, "Resuming orchestration");
        let request = proto::ResumeRequest {
            instance_id: instance_id.to_string(),
            reason,
        };
        self.inner.resume_instance(request).await?;
        Ok(())
    }

    /// Purge an orchestration's history and state by instance ID.
    ///
    /// Returns the number of deleted instances.
    pub async fn purge_orchestration(&mut self, instance_id: &str, recursive: bool) -> Result<i32> {
        internal::validate_identifier(
            instance_id,
            "instance ID",
            self.options.max_identifier_length,
        )?;
        tracing::info!(instance_id = %instance_id, "Purging orchestration");
        let request = proto::PurgeInstancesRequest {
            request: Some(proto::purge_instances_request::Request::InstanceId(
                instance_id.to_string(),
            )),
            recursive,
            force: None,
        };
        let response = self.inner.purge_instances(request).await?;
        let count = response.into_inner().deleted_instance_count;
        tracing::debug!(instance_id = %instance_id, deleted = count, "Purge complete");
        Ok(count)
    }

    /// Purge orchestrations matching the given filter criteria.
    ///
    /// Returns the number of deleted instances.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use dapr_durabletask::api::{OrchestrationStatus, PurgeInstanceFilter};
    ///
    /// # async fn example(mut client: dapr_durabletask::client::TaskHubGrpcClient) {
    /// let filter = PurgeInstanceFilter::new()
    ///     .with_created_time_from(chrono::Utc::now() - chrono::Duration::hours(24))
    ///     .with_runtime_status([OrchestrationStatus::Completed, OrchestrationStatus::Failed]);
    ///
    /// let deleted = client.purge_orchestrations_by_filter(filter, false).await.unwrap();
    /// println!("Deleted {deleted} orchestrations");
    /// # }
    /// ```
    pub async fn purge_orchestrations_by_filter(
        &mut self,
        filter: PurgeInstanceFilter,
        recursive: bool,
    ) -> Result<i32> {
        tracing::info!(?filter, "Purging orchestrations by filter");
        let request = proto::PurgeInstancesRequest {
            request: Some(
                proto::purge_instances_request::Request::PurgeInstanceFilter(filter.into_proto()),
            ),
            recursive,
            force: None,
        };
        let response = self.inner.purge_instances(request).await?;
        let count = response.into_inner().deleted_instance_count;
        tracing::debug!(deleted = count, "Purge by filter complete");
        Ok(count)
    }
}