orcher-sdk 0.5.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
//! Handle to a single workflow execution.

use crate::error::{Error, Result};
use orcher_sdk_core::client::WorkflowClient as CoreClient;
use serde::{de::DeserializeOwned, Serialize};
use std::sync::Arc;
use std::time::Duration;

use super::{EventOptions, QueryOptions};

/// Handle to a workflow execution.
///
/// Use it to wait for the result, send events, run queries and updates, and
/// cancel, terminate or reset the workflow. Without a run ID, calls target the
/// latest run. Cloning is cheap.
#[derive(Clone)]
pub struct WorkflowHandle {
    pub(crate) core_client: Arc<CoreClient>,
    pub(crate) workflow_id: String,
    pub(crate) run_id: Option<String>,
    /// Namespace for every call; the client's default when `None`.
    pub(crate) namespace: Option<String>,
}

impl WorkflowHandle {
    pub(crate) fn new_with_namespace(
        core_client: Arc<CoreClient>,
        workflow_id: String,
        run_id: Option<String>,
        namespace: Option<String>,
    ) -> Self {
        Self {
            core_client,
            workflow_id,
            run_id,
            namespace,
        }
    }

    fn get_client(&self) -> CoreClient {
        if let Some(ref namespace) = self.namespace {
            self.core_client.as_ref().clone().with_namespace(namespace)
        } else {
            self.core_client.as_ref().clone()
        }
    }

    /// The workflow ID.
    pub fn id(&self) -> &str {
        &self.workflow_id
    }

    /// The run this handle targets, if it was given one.
    pub fn run_id(&self) -> Option<&str> {
        self.run_id.as_deref()
    }

    // ============================================================================
    // Status
    // ============================================================================

    /// Returns the current status without waiting for completion.
    ///
    /// Use [`WorkflowHandle::describe`] for full metadata.
    pub async fn status(&self) -> Result<orcher_sdk_core::WorkflowStatus> {
        let client = self.get_client();
        client
            .get_workflow_status(&self.workflow_id, self.run_id.clone())
            .await
            .map_err(Error::from)
    }

    // ============================================================================
    // Workflow Results
    // ============================================================================

    /// Waits until the workflow completes and returns its result.
    ///
    /// # Errors
    ///
    /// Fails if the workflow does not complete successfully, or if the result
    /// cannot be deserialized from JSON into `T`.
    pub async fn result<T: DeserializeOwned>(&self) -> Result<T> {
        let run_id = self.run_id.clone();

        tracing::debug!(
            workflow_id = %self.workflow_id,
            run_id = ?run_id,
            "Waiting for workflow result"
        );

        let client = self.get_client();
        let result_bytes = client
            .get_workflow_result_raw(&self.workflow_id, run_id.as_ref().unwrap_or(&String::new()))
            .await
            .map_err(Error::from)?;

        let result: T = serde_json::from_slice(&result_bytes).map_err(|e| {
            Error::Client(crate::error::ClientError::Deserialization(format!(
                "Failed to deserialize workflow result: {}",
                e
            )))
        })?;

        tracing::debug!(
            workflow_id = %self.workflow_id,
            run_id = ?run_id,
            "Workflow completed successfully"
        );

        Ok(result)
    }

    /// Like [`WorkflowHandle::result`], but gives up after `timeout`.
    ///
    /// Giving up only stops the wait; the workflow keeps running.
    ///
    /// # Errors
    ///
    /// Returns [`ClientError::Timeout`] if the workflow has not completed in time,
    /// and otherwise the same errors as [`WorkflowHandle::result`].
    ///
    /// [`ClientError::Timeout`]: crate::error::ClientError::Timeout
    pub async fn result_with_timeout<T: DeserializeOwned>(&self, timeout: Duration) -> Result<T> {
        tokio::time::timeout(timeout, self.result())
            .await
            .map_err(|_| Error::Client(crate::error::ClientError::Timeout { timeout }))?
    }

    // ============================================================================
    // Lifecycle Operations
    // ============================================================================

    /// Requests graceful cancellation.
    ///
    /// The workflow is told to cancel and can clean up before it stops. This
    /// returns once the request is accepted, not when the workflow has stopped.
    pub async fn cancel(&self) -> Result<()> {
        tracing::info!(
            workflow_id = %self.workflow_id,
            "Canceling workflow"
        );

        let client = self.get_client();
        client
            .cancel_workflow(&self.workflow_id, self.run_id.clone())
            .await
            .map_err(Error::from)?;

        tracing::info!(
            workflow_id = %self.workflow_id,
            "Workflow cancellation requested"
        );

        Ok(())
    }

    /// Terminates the workflow immediately, without cleanup.
    ///
    /// Use [`WorkflowHandle::cancel`] to let the workflow clean up.
    pub async fn terminate(&self, reason: impl Into<String>) -> Result<()> {
        let reason = reason.into();
        tracing::warn!(
            workflow_id = %self.workflow_id,
            reason = %reason,
            "Terminating workflow"
        );

        let client = self.get_client();
        client
            .terminate_workflow(&self.workflow_id, self.run_id.clone(), &reason)
            .await
            .map_err(Error::from)?;

        tracing::warn!(
            workflow_id = %self.workflow_id,
            "Workflow terminated"
        );

        Ok(())
    }

    /// Resets the workflow to a journal event and re-executes from there.
    ///
    /// Creates a new execution that replays the journal up to and including
    /// `target_event_id`, then makes fresh decisions from that point. The
    /// current execution ends with the terminal status "reset". `reason` is a
    /// human-readable note recorded with the reset.
    ///
    /// Returns the ID of the new execution.
    pub async fn reset(&self, target_event_id: i64, reason: impl Into<String>) -> Result<String> {
        let reason = reason.into();
        tracing::info!(
            workflow_id = %self.workflow_id,
            target_event_id = target_event_id,
            reason = %reason,
            "Resetting workflow"
        );

        let client = self.get_client();
        let response = client
            .reset_workflow(
                &self.workflow_id,
                self.run_id.clone(),
                target_event_id,
                &reason,
            )
            .await
            .map_err(Error::from)?;

        tracing::info!(
            workflow_id = %self.workflow_id,
            new_execution_id = %response,
            "Workflow reset successfully"
        );

        Ok(response)
    }

    // ============================================================================
    // Events
    // ============================================================================

    /// Sends an event, an asynchronous message, to the workflow.
    ///
    /// Returns once the server has accepted the event, not when the workflow
    /// has handled it.
    pub async fn send_event<E>(&self, event: impl Into<String>, arg: E) -> Result<()>
    where
        E: Serialize,
    {
        self.send_event_with_options(event, arg, EventOptions::default())
            .await
    }

    /// Sends an event with options.
    ///
    /// The options are accepted but not applied: the request uses the client's
    /// timeout.
    pub async fn send_event_with_options<E>(
        &self,
        event: impl Into<String>,
        arg: E,
        _options: EventOptions,
    ) -> Result<()>
    where
        E: Serialize,
    {
        let event = event.into();

        tracing::debug!(
            workflow_id = %self.workflow_id,
            event = %event,
            "Sending event to workflow"
        );

        // sdk-core serializes `arg`.
        let client = self.get_client();
        client
            .send_event(&self.workflow_id, self.run_id.clone(), event.clone(), arg)
            .await
            .map_err(Error::from)?;

        tracing::debug!(
            workflow_id = %self.workflow_id,
            event = %event,
            "Event sent successfully"
        );

        Ok(())
    }

    // ============================================================================
    // Queries
    // ============================================================================

    /// Reads workflow state through a named query, without affecting execution.
    pub async fn query<Q, R>(&self, query: impl Into<String>, args: Q) -> Result<R>
    where
        Q: Serialize,
        R: DeserializeOwned,
    {
        self.query_with_options(query, args, QueryOptions::default())
            .await
    }

    /// Runs a query with options.
    ///
    /// The options are accepted but not applied: the request uses the client's
    /// timeout and no reject condition.
    pub async fn query_with_options<Q, R>(
        &self,
        query: impl Into<String>,
        args: Q,
        _options: QueryOptions,
    ) -> Result<R>
    where
        Q: Serialize,
        R: DeserializeOwned,
    {
        let query = query.into();

        tracing::debug!(
            workflow_id = %self.workflow_id,
            query = %query,
            "Querying workflow"
        );

        // sdk-core serializes `args` and deserializes the result.
        let client = self.get_client();
        let result: R = client
            .query_workflow(&self.workflow_id, self.run_id.clone(), query.clone(), args)
            .await
            .map_err(Error::from)?;

        tracing::debug!(
            workflow_id = %self.workflow_id,
            query = %query,
            "Query completed successfully"
        );

        Ok(result)
    }

    // ============================================================================
    // Description
    // ============================================================================

    /// Returns detailed metadata, such as status, timing and task queue,
    /// without waiting for completion.
    pub async fn describe(&self) -> Result<orcher_sdk_core::WorkflowExecutionDescription> {
        tracing::debug!(
            workflow_id = %self.workflow_id,
            "Describing workflow"
        );

        let client = self.get_client();
        let description = client
            .describe_workflow(&self.workflow_id, self.run_id.clone())
            .await
            .map_err(Error::from)?;

        tracing::debug!(
            workflow_id = %self.workflow_id,
            status = ?description.status,
            "Workflow described successfully"
        );

        Ok(description)
    }

    // ============================================================================
    // Updates
    // ============================================================================

    /// Sends an update to the workflow and waits for its result.
    ///
    /// Unlike a query, an update may change workflow state; its result is
    /// recorded in the journal.
    pub async fn update<A, R>(&self, update_name: impl Into<String>, args: A) -> Result<R>
    where
        A: Serialize,
        R: DeserializeOwned,
    {
        let update_name = update_name.into();

        tracing::debug!(
            workflow_id = %self.workflow_id,
            update_name = %update_name,
            "Updating workflow"
        );

        let client = self.get_client();
        let result: R = client
            .update_workflow(
                &self.workflow_id,
                self.run_id.clone(),
                update_name.clone(),
                args,
            )
            .await
            .map_err(Error::from)?;

        tracing::debug!(
            workflow_id = %self.workflow_id,
            update_name = %update_name,
            "Update completed successfully"
        );

        Ok(result)
    }
}

impl std::fmt::Debug for WorkflowHandle {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("WorkflowHandle")
            .field("workflow_id", &self.workflow_id)
            .field("run_id", &self.run_id)
            .finish()
    }
}

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

    #[test]
    fn test_workflow_handle_debug() {
        // A real handle needs a connected CoreClient, so this only checks the
        // values one would be built from.
        let workflow_id = "test-workflow-123".to_string();
        let run_id = Some("test-run-456".to_string());

        assert_eq!(workflow_id, "test-workflow-123");
        assert_eq!(run_id, Some("test-run-456".to_string()));
    }

    #[test]
    fn test_event_options_defaults() {
        let options = EventOptions::default();
        assert!(options.timeout.is_none());
    }

    #[test]
    fn test_query_options_defaults() {
        let options = QueryOptions::default();
        assert!(options.timeout.is_none());
        assert!(options.reject_condition.is_none());
    }
}

#[cfg(test)]
mod over_the_wire_tests {
    use super::*;

    /// Checks that the handle surfaces a typed error instead of flattening it.
    ///
    /// The unit tests beside `From<CoreError>` prove the mapping is correct, but
    /// not that the handle uses it. If the handle wrapped every failure in
    /// `ClientError::RequestFailed`, which `is_retryable` treats as retryable, a
    /// workflow that will never exist would be retried in a loop. Only a real
    /// call can show the difference.
    ///
    /// Ignored by default because it needs a server:
    ///   cargo test -p orcher-sdk --lib over_the_wire -- --ignored --nocapture
    #[tokio::test]
    #[ignore = "requires a running orcher server on localhost:50051"]
    async fn a_missing_workflow_is_typed_and_not_retryable_over_the_wire() {
        let core_client = Arc::new(
            CoreClient::connect("http://localhost:50051")
                .await
                .expect("connect to server"),
        );
        let handle = WorkflowHandle::new_with_namespace(
            core_client,
            format!("no-such-workflow-{}", uuid::Uuid::new_v4()),
            None,
            Some("default".to_string()),
        );

        let err = handle
            .status()
            .await
            .expect_err("a workflow that does not exist should not return a status");

        println!("handle.status() -> {err:?}");
        println!("is_retryable    -> {}", err.is_retryable());

        assert!(
            !err.is_retryable(),
            "a workflow that will never exist was classified retryable, so a \
             retry loop would hammer the server: {err:?}"
        );
    }
}