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
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
//! Registry of workflow, task, update and actor handlers.
//!
//! Handlers are registered manually or, with the `auto-register` feature,
//! collected from the SDK's macros.
//!
//! ## Usage
//!
//! ### Auto-registration (recommended)
//!
//! ```rust,no_run
//! use orcher_sdk::prelude::*;
//!
//! #[task] // Submits a registration entry to `inventory`.
//! async fn greet(_ctx: TaskContext, name: String) -> Result<String> {
//!     Ok(format!("Hello, {name}"))
//! }
//!
//! #[tokio::main]
//! async fn main() -> Result<()> {
//!     // The builder collects every submitted entry.
//!     let worker = Worker::builder()
//!         .server_url("http://localhost:50051")
//!         .build()
//!         .await?;
//!     worker.run().await
//! }
//! ```
//!
//! ### Manual registration
//!
//! ```rust
//! use orcher_sdk::worker::registry::{Registry, TaskHandler, WorkflowHandler};
//! use std::sync::Arc;
//!
//! let mut registry = Registry::new();
//!
//! // Handlers take and return payloads; this task echoes its input.
//! registry.register_task("echo", TaskHandler {
//!     name: "echo".to_string(),
//!     handler: Some(Arc::new(|_ctx, input| Box::pin(async move { Ok(input) }))),
//! });
//! registry.register_workflow("my_workflow", WorkflowHandler {
//!     name: "my_workflow".to_string(),
//!     handler: Some(Arc::new(|_ctx, input| Box::pin(async move { Ok(input) }))),
//! });
//!
//! assert!(registry.has_task("echo"));
//! assert!(registry.has_workflow("my_workflow"));
//! ```

use std::collections::HashMap;
use std::sync::RwLock;

#[cfg(feature = "auto-register")]
use crate::worker::registration::{
    ActorHandlerRegistration, TaskRegistration, WorkflowRegistration,
};

#[cfg(feature = "auto-register")]
use once_cell::sync::Lazy;

/// Process-wide registry of auto-registered actor operation handlers.
///
/// The `#[operations]` macro generates constructor functions that add each
/// operation's handler here at program startup. Tasks, workflows and updates
/// are collected through `inventory` instead. The
/// [`WorkerBuilder`](crate::worker::WorkerBuilder) copies these entries into
/// the worker's [`Registry`] when it is created.
///
/// The `RwLock` makes access thread-safe. Registration runs in `#[ctor::ctor]`
/// functions before `main`, so in practice there is no contention.
///
/// # Example
///
/// ```text
/// // Shape of a constructor function generated by `#[operations]`:
/// #[::orcher_sdk::ctor::ctor]
/// fn __orcher_register_actor_handler_Counter_increment() {
///     ::orcher_sdk::worker::registry::GLOBAL_REGISTRY
///         .write()
///         .unwrap()
///         .register_actor_handler_direct(ActorHandlerRegistration { ... });
/// }
/// ```
#[cfg(feature = "auto-register")]
pub static GLOBAL_REGISTRY: Lazy<RwLock<GlobalRegistry>> = Lazy::new(|| {
    tracing::debug!("Initializing global auto-registration registry");
    RwLock::new(GlobalRegistry::new())
});

/// Storage behind [`GLOBAL_REGISTRY`].
///
/// Kept separate from [`Registry`] to avoid circular dependencies and to give
/// generated registration code a smaller interface.
#[cfg(feature = "auto-register")]
#[derive(Debug, Default)]
pub struct GlobalRegistry {
    /// Always empty: tasks are collected through `inventory`.
    tasks: Vec<TaskRegistration>,

    /// Always empty: workflows are collected through `inventory`.
    workflows: Vec<WorkflowRegistration>,

    actor_handlers: Vec<ActorHandlerRegistration>,
}

#[cfg(feature = "auto-register")]
impl GlobalRegistry {
    /// Creates an empty registry.
    pub fn new() -> Self {
        Self {
            tasks: Vec::new(),
            workflows: Vec::new(),
            actor_handlers: Vec::new(),
        }
    }

    /// Does nothing; tasks are registered through `inventory`.
    ///
    /// Kept so that code calling it still compiles.
    #[deprecated(note = "Tasks are now registered via inventory")]
    pub fn register_task_direct(&mut self, _registration: TaskRegistration) {
        tracing::debug!("Task registration via GlobalRegistry is deprecated - use inventory");
    }

    /// Does nothing; workflows are registered through `inventory`.
    ///
    /// Kept so that code calling it still compiles.
    #[deprecated(note = "Workflows are now registered via inventory")]
    pub fn register_workflow_direct(&mut self, _registration: WorkflowRegistration) {
        tracing::debug!("Workflow registration via GlobalRegistry is deprecated - use inventory");
    }

    /// Adds an actor operation handler.
    ///
    /// Called by the `#[ctor::ctor]` functions that the `#[operations]` macro
    /// generates.
    pub fn register_actor_handler_direct(&mut self, registration: ActorHandlerRegistration) {
        tracing::debug!(
            actor = registration.actor_name,
            operation = registration.operation_name,
            "Auto-registering actor handler to global registry"
        );
        self.actor_handlers.push(registration);
    }

    /// Task registrations; always empty, see [`GlobalRegistry::register_task_direct`].
    pub fn tasks(&self) -> &[TaskRegistration] {
        &self.tasks
    }

    /// Workflow registrations; always empty, see
    /// [`GlobalRegistry::register_workflow_direct`].
    pub fn workflows(&self) -> &[WorkflowRegistration] {
        &self.workflows
    }

    /// Number of task registrations; always zero.
    pub fn task_count(&self) -> usize {
        self.tasks.len()
    }

    /// Number of workflow registrations; always zero.
    pub fn workflow_count(&self) -> usize {
        self.workflows.len()
    }

    /// All registered actor operation handlers.
    pub fn actor_handlers(&self) -> &[ActorHandlerRegistration] {
        &self.actor_handlers
    }

    /// Number of registered actor operation handlers.
    pub fn actor_handler_count(&self) -> usize {
        self.actor_handlers.len()
    }
}

/// A worker's handlers, looked up by name.
///
/// Holds workflow, task and update handlers and, with the `auto-register`
/// feature, actor definitions and actor operation handlers.
#[derive(Debug, Default)]
pub struct Registry {
    /// Workflow handlers by workflow name.
    pub workflows: HashMap<String, WorkflowHandler>,

    /// Task handlers by task name.
    pub tasks: HashMap<String, TaskHandler>,

    /// Update handlers by update name.
    pub updates: HashMap<String, UpdateHandler>,

    /// Actor definitions by actor name. Filled only from definitions submitted
    /// by hand; macro-declared actors appear only in `actor_handlers`.
    #[cfg(feature = "auto-register")]
    pub actors: HashMap<String, crate::actor::definition::ActorDefinition>,

    /// Actor operation handlers by actor name, then operation name.
    #[cfg(feature = "auto-register")]
    pub actor_handlers: HashMap<String, HashMap<String, ActorHandlerRegistration>>,
}

/// A registered workflow: its name and, when available, its handler.
#[derive(Clone)]
pub struct WorkflowHandler {
    /// Workflow name.
    pub name: String,

    /// The handler, if one was supplied.
    #[cfg(feature = "auto-register")]
    pub handler: Option<crate::worker::registration::WorkflowHandlerFn>,
}

/// A registered task: its name and, when available, its handler.
#[derive(Clone)]
pub struct TaskHandler {
    /// Task name.
    pub name: String,

    /// The handler, if one was supplied.
    #[cfg(feature = "auto-register")]
    pub handler: Option<crate::worker::registration::TaskHandlerFn>,
}

/// A registered update handler: its name and, when available, its function.
#[derive(Clone)]
pub struct UpdateHandler {
    /// Update name.
    pub name: String,

    /// The handler, if one was supplied.
    #[cfg(feature = "auto-register")]
    pub handler: Option<crate::worker::registration::UpdateHandlerFn>,
}

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

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

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

impl Registry {
    /// Creates an empty registry.
    pub fn new() -> Self {
        Self {
            workflows: HashMap::new(),
            tasks: HashMap::new(),
            updates: HashMap::new(),
            #[cfg(feature = "auto-register")]
            actors: HashMap::new(),
            #[cfg(feature = "auto-register")]
            actor_handlers: HashMap::new(),
        }
    }

    /// Registers a workflow handler under `name`, replacing any previous one.
    ///
    /// # Example
    ///
    /// ```rust
    /// use orcher_sdk::worker::registry::{Registry, WorkflowHandler};
    /// use std::sync::Arc;
    ///
    /// let mut registry = Registry::new();
    /// registry.register_workflow("order_workflow", WorkflowHandler {
    ///     name: "order_workflow".to_string(),
    ///     handler: Some(Arc::new(|_ctx, input| Box::pin(async move { Ok(input) }))),
    /// });
    /// assert_eq!(registry.workflow_names(), ["order_workflow"]);
    /// ```
    pub fn register_workflow(&mut self, name: impl Into<String>, handler: WorkflowHandler) {
        let name = name.into();
        tracing::debug!(workflow = %name, "Registering workflow handler");
        self.workflows.insert(name, handler);
    }

    /// Registers a task handler under `name`, replacing any previous one.
    ///
    /// # Example
    ///
    /// ```rust
    /// use orcher_sdk::worker::registry::{Registry, TaskHandler};
    /// use std::sync::Arc;
    ///
    /// let mut registry = Registry::new();
    /// registry.register_task("process_payment", TaskHandler {
    ///     name: "process_payment".to_string(),
    ///     handler: Some(Arc::new(|_ctx, input| Box::pin(async move { Ok(input) }))),
    /// });
    /// assert_eq!(registry.task_names(), ["process_payment"]);
    /// ```
    pub fn register_task(&mut self, name: impl Into<String>, handler: TaskHandler) {
        let name = name.into();
        tracing::debug!(task = %name, "Registering task handler");
        self.tasks.insert(name, handler);
    }

    /// Returns the workflow handler registered under `name`.
    pub fn get_workflow(&self, name: &str) -> Option<&WorkflowHandler> {
        self.workflows.get(name)
    }

    /// Returns the task handler registered under `name`.
    pub fn get_task(&self, name: &str) -> Option<&TaskHandler> {
        self.tasks.get(name)
    }

    /// Names of all registered workflows, in no particular order.
    pub fn workflow_names(&self) -> Vec<&str> {
        self.workflows.keys().map(|s| s.as_str()).collect()
    }

    /// Names of all registered tasks, in no particular order.
    pub fn task_names(&self) -> Vec<&str> {
        self.tasks.keys().map(|s| s.as_str()).collect()
    }

    /// Whether a workflow is registered under `name`.
    pub fn has_workflow(&self, name: &str) -> bool {
        self.workflows.contains_key(name)
    }

    /// Whether a task is registered under `name`.
    pub fn has_task(&self, name: &str) -> bool {
        self.tasks.contains_key(name)
    }

    /// Registers an update handler under `name`, replacing any previous one.
    pub fn register_update(&mut self, name: impl Into<String>, handler: UpdateHandler) {
        let name = name.into();
        tracing::debug!(update = %name, "Registering update handler");
        self.updates.insert(name, handler);
    }

    /// Returns the update handler registered under `name`.
    pub fn get_update(&self, name: &str) -> Option<&UpdateHandler> {
        self.updates.get(name)
    }

    /// Names of all registered update handlers, in no particular order.
    pub fn update_names(&self) -> Vec<&str> {
        self.updates.keys().map(|s| s.as_str()).collect()
    }

    /// Whether an update handler is registered under `name`.
    pub fn has_update(&self, name: &str) -> bool {
        self.updates.contains_key(name)
    }

    /// Number of registered workflows.
    pub fn workflow_count(&self) -> usize {
        self.workflows.len()
    }

    /// Number of registered tasks.
    pub fn task_count(&self) -> usize {
        self.tasks.len()
    }

    /// Number of registered update handlers.
    pub fn update_count(&self) -> usize {
        self.updates.len()
    }

    /// Number of actor definitions.
    ///
    /// Counts only definitions submitted by hand; use
    /// [`Registry::actor_handler_count`] for macro-declared actors.
    #[cfg(feature = "auto-register")]
    pub fn actor_count(&self) -> usize {
        self.actors.len()
    }

    /// Names of all actor definitions, in no particular order.
    #[cfg(feature = "auto-register")]
    pub fn actor_names(&self) -> Vec<&str> {
        self.actors.keys().map(|s| s.as_str()).collect()
    }

    /// Returns the actor definition registered under `name`.
    #[cfg(feature = "auto-register")]
    pub fn get_actor(&self, name: &str) -> Option<&crate::actor::definition::ActorDefinition> {
        self.actors.get(name)
    }

    /// Whether an actor definition is registered under `name`.
    #[cfg(feature = "auto-register")]
    pub fn has_actor(&self, name: &str) -> bool {
        self.actors.contains_key(name)
    }

    /// Actor operation handlers, by actor name and then operation name.
    #[cfg(feature = "auto-register")]
    pub fn actor_handlers(&self) -> &HashMap<String, HashMap<String, ActorHandlerRegistration>> {
        &self.actor_handlers
    }

    /// Number of actor operation handlers, across all actors.
    #[cfg(feature = "auto-register")]
    pub fn actor_handler_count(&self) -> usize {
        self.actor_handlers.values().map(|ops| ops.len()).sum()
    }

    /// Collects every auto-registered handler into this registry.
    ///
    /// Runs the task, workflow and update registration functions submitted to
    /// `inventory`, copies the actor operation handlers from [`GLOBAL_REGISTRY`],
    /// and collects actor definitions from `inventory`.
    ///
    /// [`WorkerBuilder::new`](crate::worker::WorkerBuilder::new) calls this.
    ///
    /// # Example
    ///
    /// ```rust
    /// use orcher_sdk::prelude::*;
    /// use orcher_sdk::worker::Registry;
    ///
    /// #[task]
    /// async fn greet(_ctx: TaskContext, name: String) -> Result<String> {
    ///     Ok(format!("Hello, {name}"))
    /// }
    ///
    /// let mut registry = Registry::new();
    /// registry.collect_from_global_registry();
    ///
    /// assert!(registry.has_task("greet"));
    /// println!("Auto-registered {} workflows", registry.workflow_count());
    /// ```
    #[cfg(feature = "auto-register")]
    pub fn collect_from_global_registry(&mut self) {
        let task_registrations: Vec<_> =
            inventory::iter::<crate::worker::registration::TaskRegistration>()
                .copied()
                .collect();

        let task_count = task_registrations.len();
        for registration in task_registrations {
            tracing::debug!("Invoking task registration function");
            registration.register(self);
        }

        let workflow_registrations: Vec<_> =
            inventory::iter::<crate::worker::registration::WorkflowRegistration>()
                .copied()
                .collect();

        let workflow_count = workflow_registrations.len();
        for registration in workflow_registrations {
            tracing::debug!("Invoking workflow registration function");
            registration.register(self);
        }

        let update_registrations: Vec<_> =
            inventory::iter::<crate::worker::registration::UpdateRegistration>()
                .copied()
                .collect();

        let update_count = update_registrations.len();
        for registration in update_registrations {
            tracing::debug!("Invoking update handler registration function");
            registration.register(self);
        }

        // Actor operation handlers come from GLOBAL_REGISTRY, not `inventory`.
        #[cfg(feature = "auto-register")]
        {
            let global = GLOBAL_REGISTRY
                .read()
                .expect("Failed to acquire read lock on GLOBAL_REGISTRY");

            let _actor_handler_count = global.actor_handlers().len();
            for handler_registration in global.actor_handlers() {
                tracing::debug!(
                    actor = handler_registration.actor_name,
                    operation = handler_registration.operation_name,
                    "Collecting actor handler from global registry"
                );

                self.actor_handlers
                    .entry(handler_registration.actor_name.to_string())
                    .or_default()
                    .insert(
                        handler_registration.operation_name.to_string(),
                        handler_registration.clone(),
                    );
            }
        }

        // Actor definitions are collected through `inventory`.
        let actors: Vec<_> = inventory::iter::<crate::actor::definition::ActorDefinition>()
            .cloned()
            .collect();

        let actor_count = actors.len();
        for actor_def in actors {
            tracing::debug!(
                actor = actor_def.actor_name(),
                operations = actor_def.operation_count(),
                "Collecting actor from inventory"
            );

            self.actors
                .insert(actor_def.actor_name().to_string(), actor_def);
        }

        tracing::info!(
            tasks = task_count,
            workflows = workflow_count,
            updates = update_count,
            actors = actor_count,
            "Collected and registered handlers from inventory"
        );
    }
}

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

    #[test]
    fn test_registry_new() {
        let registry = Registry::new();
        assert_eq!(registry.workflow_count(), 0);
        assert_eq!(registry.task_count(), 0);
    }

    #[test]
    fn test_register_workflow() {
        let mut registry = Registry::new();
        let handler = WorkflowHandler {
            name: "test_workflow".to_string(),
            #[cfg(feature = "auto-register")]
            handler: None,
        };

        registry.register_workflow("test_workflow", handler);

        assert_eq!(registry.workflow_count(), 1);
        assert!(registry.has_workflow("test_workflow"));
        assert!(!registry.has_workflow("unknown"));
    }

    #[test]
    fn test_register_task() {
        let mut registry = Registry::new();
        let handler = TaskHandler {
            name: "test_task".to_string(),
            #[cfg(feature = "auto-register")]
            handler: None,
        };

        registry.register_task("test_task", handler);

        assert_eq!(registry.task_count(), 1);
        assert!(registry.has_task("test_task"));
        assert!(!registry.has_task("unknown"));
    }

    #[test]
    fn test_get_handlers() {
        let mut registry = Registry::new();

        let wf_handler = WorkflowHandler {
            name: "my_workflow".to_string(),
            #[cfg(feature = "auto-register")]
            handler: None,
        };
        let task_handler = TaskHandler {
            name: "my_task".to_string(),
            #[cfg(feature = "auto-register")]
            handler: None,
        };

        registry.register_workflow("my_workflow", wf_handler);
        registry.register_task("my_task", task_handler);

        assert!(registry.get_workflow("my_workflow").is_some());
        assert!(registry.get_task("my_task").is_some());
        assert!(registry.get_workflow("unknown").is_none());
        assert!(registry.get_task("unknown").is_none());
    }

    #[test]
    fn test_list_names() {
        let mut registry = Registry::new();

        registry.register_workflow(
            "workflow1",
            WorkflowHandler {
                name: "workflow1".to_string(),
                #[cfg(feature = "auto-register")]
                handler: None,
            },
        );
        registry.register_workflow(
            "workflow2",
            WorkflowHandler {
                name: "workflow2".to_string(),
                #[cfg(feature = "auto-register")]
                handler: None,
            },
        );
        registry.register_task(
            "task1",
            TaskHandler {
                name: "task1".to_string(),
                #[cfg(feature = "auto-register")]
                handler: None,
            },
        );

        let workflow_names = registry.workflow_names();
        let task_names = registry.task_names();

        assert_eq!(workflow_names.len(), 2);
        assert_eq!(task_names.len(), 1);
        assert!(workflow_names.contains(&"workflow1"));
        assert!(workflow_names.contains(&"workflow2"));
        assert!(task_names.contains(&"task1"));
    }

    #[cfg(feature = "auto-register")]
    #[test]
    fn test_collect_from_global_registry() {
        let mut registry = Registry::new();

        // What gets collected depends on the test binary; this only checks
        // that collection does not panic.
        registry.collect_from_global_registry();

        println!(
            "Collected {} tasks and {} workflows from global registry",
            registry.task_count(),
            registry.workflow_count()
        );
    }

    #[test]
    fn test_registry_default() {
        let registry = Registry::default();
        assert_eq!(registry.workflow_count(), 0);
        assert_eq!(registry.task_count(), 0);
    }
}