temporalio-client 0.6.0

Clients for interacting with Temporal
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
//! Handle for completing activities asynchronously via a client.

use crate::{
    CompleteAsyncActivityInput, FailAsyncActivityInput, HeartbeatAsyncActivityInput,
    NamespacedClient, Next, ReportAsyncActivityCancellationInput, RpcOptions, TemporalClientValue,
    errors::AsyncActivityError, grpc::WorkflowService, interceptors,
};
use futures_util::future::BoxFuture;
use temporalio_common::{
    data_converters::{SerializationContext, SerializationContextData, TemporalSerializable},
    error::{ApplicationFailure, OutgoingActivityError, OutgoingError},
    payload_visitor::encode_payloads,
    protos::{
        TaskToken,
        temporal::api::{
            common::v1::Payloads,
            workflowservice::v1::{
                RecordActivityTaskHeartbeatByIdRequest, RecordActivityTaskHeartbeatByIdResponse,
                RecordActivityTaskHeartbeatRequest, RecordActivityTaskHeartbeatResponse,
                RespondActivityTaskCanceledByIdRequest, RespondActivityTaskCanceledRequest,
                RespondActivityTaskCompletedByIdRequest, RespondActivityTaskCompletedRequest,
                RespondActivityTaskFailedByIdRequest, RespondActivityTaskFailedRequest,
            },
        },
    },
};
use tonic::IntoRequest;

async fn encode_optional_value(
    value: Option<Box<dyn TemporalClientValue>>,
    data_converter: &temporalio_common::data_converters::DataConverter,
) -> Result<Option<Payloads>, AsyncActivityError> {
    let Some(value) = value else {
        return Ok(None);
    };
    let unencoded_payloads = {
        let payload_converter = data_converter.payload_converter();
        let context = SerializationContext {
            data: &SerializationContextData::Activity,
            converter: payload_converter,
        };
        value.serialize_payloads(&context)?
    };
    drop(value);
    let payloads = data_converter
        .codec()
        .encode(&SerializationContextData::Activity, unencoded_payloads)
        .await?;
    Ok(Some(Payloads { payloads }))
}

/// Identifies an async activity for completion outside a worker.
#[derive(Debug, Clone)]
pub enum ActivityIdentifier {
    /// Identify activity by its task token
    TaskToken(TaskToken),
    /// Identify activity by workflow and activity IDs.
    ById {
        /// ID of the workflow that scheduled this activity.
        workflow_id: String,
        /// Run ID of the workflow (optional - if not provided, targets the latest run).
        run_id: String,
        /// ID of the activity to complete.
        activity_id: String,
    },
}

impl ActivityIdentifier {
    /// Create an identifier from a task token.
    pub fn from_task_token(token: TaskToken) -> Self {
        Self::TaskToken(token)
    }

    /// Create an identifier from workflow and activity IDs. Use an empty run id to target the
    /// latest workflow execution.
    pub fn by_id(
        workflow_id: impl Into<String>,
        run_id: impl Into<String>,
        activity_id: impl Into<String>,
    ) -> Self {
        Self::ById {
            workflow_id: workflow_id.into(),
            run_id: run_id.into(),
            activity_id: activity_id.into(),
        }
    }
}

/// Handle for completing activities asynchronously (outside the worker).
pub struct AsyncActivityHandle<CT> {
    client: CT,
    identifier: ActivityIdentifier,
}

impl<CT> AsyncActivityHandle<CT> {
    /// Create a new async activity handle.
    pub fn new(client: CT, identifier: ActivityIdentifier) -> Self {
        Self { client, identifier }
    }

    /// Get the identifier for this activity.
    pub fn identifier(&self) -> &ActivityIdentifier {
        &self.identifier
    }

    /// Get a reference to the underlying client.
    pub fn client(&self) -> &CT {
        &self.client
    }
}

impl<CT: WorkflowService + NamespacedClient + Clone> AsyncActivityHandle<CT> {
    /// Complete the activity with a successful result.
    pub async fn complete<T>(
        &self,
        result: Option<T>,
        rpc_options: RpcOptions,
    ) -> Result<(), AsyncActivityError>
    where
        T: TemporalSerializable + Send + 'static,
    {
        interceptors::call_complete_async_activity(
            self.client.client_interceptors(),
            CompleteAsyncActivityInput::new(self.identifier.clone(), result, rpc_options),
            Next::new({
                let mut client = self.client.clone();
                move |input: CompleteAsyncActivityInput| -> BoxFuture<
                    '_,
                    Result<(), AsyncActivityError>,
                > {
                    Box::pin(async move {
                        let (identifier, result, rpc_options) = input.into_parts();
                        let result = encode_optional_value(result, client.data_converter()).await?;
                        match identifier {
                            ActivityIdentifier::TaskToken(token) => {
                                let mut request = RespondActivityTaskCompletedRequest {
                                    task_token: token.0,
                                    result,
                                    identity: client.identity(),
                                    namespace: client.namespace(),
                                    ..Default::default()
                                }
                                .into_request();
                                rpc_options.apply_to(&mut request);
                                WorkflowService::respond_activity_task_completed(
                                    &mut client,
                                    request,
                                )
                                .await
                                .map_err(AsyncActivityError::from_status)?;
                            }
                            ActivityIdentifier::ById {
                                workflow_id,
                                run_id,
                                activity_id,
                            } => {
                                let mut request = RespondActivityTaskCompletedByIdRequest {
                                    namespace: client.namespace(),
                                    workflow_id,
                                    run_id,
                                    activity_id,
                                    result,
                                    identity: client.identity(),
                                    resource_id: Default::default(),
                                }
                                .into_request();
                                rpc_options.apply_to(&mut request);
                                WorkflowService::respond_activity_task_completed_by_id(
                                    &mut client,
                                    request,
                                )
                                .await
                                .map_err(AsyncActivityError::from_status)?;
                            }
                        }
                        Ok(())
                    })
                }
            }),
        )
        .await
    }

    /// Fail the activity with a failure.
    pub async fn fail<E, T>(
        &self,
        failure: E,
        last_heartbeat_details: Option<T>,
        rpc_options: RpcOptions,
    ) -> Result<(), AsyncActivityError>
    where
        E: Into<ApplicationFailure>,
        T: TemporalSerializable + Send + 'static,
    {
        interceptors::call_fail_async_activity(
            self.client.client_interceptors(),
            FailAsyncActivityInput::new(
                self.identifier.clone(),
                failure.into(),
                last_heartbeat_details,
                rpc_options,
            ),
            Next::new({
                let mut client = self.client.clone();
                move |input: FailAsyncActivityInput| -> BoxFuture<
                    '_,
                    Result<(), AsyncActivityError>,
                > {
                    Box::pin(async move {
                        let (identifier, application_failure, details, rpc_options) =
                            input.into_parts();
                        let data_converter = client.data_converter().clone();
                        let mut failure = data_converter.to_failure(
                            &SerializationContextData::Activity,
                            OutgoingError::Activity(OutgoingActivityError::Application(Box::new(
                                application_failure,
                            ))),
                        );
                        encode_payloads(
                            &mut failure,
                            data_converter.codec(),
                            &SerializationContextData::Activity,
                        )
                        .await?;
                        let last_heartbeat_details =
                            encode_optional_value(details, &data_converter).await?;
                        match identifier {
                            ActivityIdentifier::TaskToken(token) => {
                                let mut request = RespondActivityTaskFailedRequest {
                                    task_token: token.0,
                                    failure: Some(failure),
                                    identity: client.identity(),
                                    namespace: client.namespace(),
                                    last_heartbeat_details,
                                    ..Default::default()
                                }
                                .into_request();
                                rpc_options.apply_to(&mut request);
                                WorkflowService::respond_activity_task_failed(
                                    &mut client,
                                    request,
                                )
                                .await
                                .map_err(AsyncActivityError::from_status)?;
                            }
                            ActivityIdentifier::ById {
                                workflow_id,
                                run_id,
                                activity_id,
                            } => {
                                let mut request = RespondActivityTaskFailedByIdRequest {
                                    namespace: client.namespace(),
                                    workflow_id,
                                    run_id,
                                    activity_id,
                                    failure: Some(failure),
                                    identity: client.identity(),
                                    last_heartbeat_details,
                                    resource_id: Default::default(),
                                }
                                .into_request();
                                rpc_options.apply_to(&mut request);
                                WorkflowService::respond_activity_task_failed_by_id(
                                    &mut client,
                                    request,
                                )
                                .await
                                .map_err(AsyncActivityError::from_status)?;
                            }
                        }
                        Ok(())
                    })
                }
            }),
        )
        .await
    }

    /// Reports the activity as canceled.
    pub async fn report_cancelation<T>(
        &self,
        details: Option<T>,
        rpc_options: RpcOptions,
    ) -> Result<(), AsyncActivityError>
    where
        T: TemporalSerializable + Send + 'static,
    {
        interceptors::call_report_async_activity_cancellation(
            self.client.client_interceptors(),
            ReportAsyncActivityCancellationInput::new(
                self.identifier.clone(),
                details,
                rpc_options,
            ),
            Next::new({
                let mut client = self.client.clone();
                move |input: ReportAsyncActivityCancellationInput| -> BoxFuture<
                    '_,
                    Result<(), AsyncActivityError>,
                > {
                    Box::pin(async move {
                        let (identifier, details, rpc_options) = input.into_parts();
                        let details = encode_optional_value(details, client.data_converter()).await?;
                        match identifier {
                            ActivityIdentifier::TaskToken(token) => {
                                let mut request = RespondActivityTaskCanceledRequest {
                                    task_token: token.0,
                                    details,
                                    identity: client.identity(),
                                    namespace: client.namespace(),
                                    ..Default::default()
                                }
                                .into_request();
                                rpc_options.apply_to(&mut request);
                                WorkflowService::respond_activity_task_canceled(
                                    &mut client,
                                    request,
                                )
                                .await
                                .map_err(AsyncActivityError::from_status)?;
                            }
                            ActivityIdentifier::ById {
                                workflow_id,
                                run_id,
                                activity_id,
                            } => {
                                let mut request = RespondActivityTaskCanceledByIdRequest {
                                    namespace: client.namespace(),
                                    workflow_id,
                                    run_id,
                                    activity_id,
                                    details,
                                    identity: client.identity(),
                                    ..Default::default()
                                }
                                .into_request();
                                rpc_options.apply_to(&mut request);
                                WorkflowService::respond_activity_task_canceled_by_id(
                                    &mut client,
                                    request,
                                )
                                .await
                                .map_err(AsyncActivityError::from_status)?;
                            }
                        }
                        Ok(())
                    })
                }
            }),
        )
        .await
    }

    /// Record a heartbeat for the activity.
    ///
    /// Heartbeats let the server know the activity is still running and can carry
    /// progress information. The response indicates if cancellation has been requested.
    pub async fn heartbeat<T>(
        &self,
        details: Option<T>,
        rpc_options: RpcOptions,
    ) -> Result<ActivityHeartbeatResponse, AsyncActivityError>
    where
        T: TemporalSerializable + Send + 'static,
    {
        interceptors::call_heartbeat_async_activity(
            self.client.client_interceptors(),
            HeartbeatAsyncActivityInput::new(self.identifier.clone(), details, rpc_options),
            Next::new({
                let mut client = self.client.clone();
                move |input: HeartbeatAsyncActivityInput| -> BoxFuture<
                    '_,
                    Result<ActivityHeartbeatResponse, AsyncActivityError>,
                > {
                    Box::pin(async move {
                        let (identifier, details, rpc_options) = input.into_parts();
                        let details = encode_optional_value(details, client.data_converter()).await?;
                        match identifier {
                            ActivityIdentifier::TaskToken(token) => {
                                let mut request = RecordActivityTaskHeartbeatRequest {
                                    task_token: token.0,
                                    details,
                                    identity: client.identity(),
                                    namespace: client.namespace(),
                                    resource_id: Default::default(),
                                }
                                .into_request();
                                rpc_options.apply_to(&mut request);
                                let response = WorkflowService::record_activity_task_heartbeat(
                                    &mut client,
                                    request,
                                )
                                .await
                                .map_err(AsyncActivityError::from_status)?
                                .into_inner();
                                Ok(ActivityHeartbeatResponse::from(response))
                            }
                            ActivityIdentifier::ById {
                                workflow_id,
                                run_id,
                                activity_id,
                            } => {
                                let mut request = RecordActivityTaskHeartbeatByIdRequest {
                                    namespace: client.namespace(),
                                    workflow_id,
                                    run_id,
                                    activity_id,
                                    details,
                                    identity: client.identity(),
                                    resource_id: Default::default(),
                                }
                                .into_request();
                                rpc_options.apply_to(&mut request);
                                let response =
                                    WorkflowService::record_activity_task_heartbeat_by_id(
                                        &mut client,
                                        request,
                                    )
                                    .await
                                    .map_err(AsyncActivityError::from_status)?
                                    .into_inner();
                                Ok(ActivityHeartbeatResponse::from(response))
                            }
                        }
                    })
                }
            }),
        )
        .await
    }
}

/// Response from a heartbeat call.
#[derive(Debug, Clone)]
pub struct ActivityHeartbeatResponse {
    /// True if the activity has been asked to cancel itself.
    pub cancel_requested: bool,
    /// True if the activity is paused.
    pub activity_paused: bool,
    /// True if the activity was reset.
    pub activity_reset: bool,
}

impl From<RecordActivityTaskHeartbeatResponse> for ActivityHeartbeatResponse {
    fn from(resp: RecordActivityTaskHeartbeatResponse) -> Self {
        Self {
            cancel_requested: resp.cancel_requested,
            activity_paused: resp.activity_paused,
            activity_reset: resp.activity_reset,
        }
    }
}

impl From<RecordActivityTaskHeartbeatByIdResponse> for ActivityHeartbeatResponse {
    fn from(resp: RecordActivityTaskHeartbeatByIdResponse) -> Self {
        Self {
            cancel_requested: resp.cancel_requested,
            activity_paused: resp.activity_paused,
            activity_reset: resp.activity_reset,
        }
    }
}