orcher-sdk 0.17.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
664
665
666
667
668
669
670
671
672
673
674
//! Builder for configuring and creating a [`Worker`].

use super::runtime::{ExecutionRuntime, RuntimeConfig};
use super::Registry;
use super::{InterceptorChain, Worker, WorkerConfig};
use crate::error::{Error, Result};
use crate::interceptor::InterceptorHook;
use std::sync::Arc;
use std::time::Duration;
use tokio::sync::RwLock;

/// Configures and builds a [`Worker`].
///
/// With the `auto-register` feature, handlers declared with the SDK's macros
/// are collected when the builder is created.
///
/// ## Example
///
/// ```rust,no_run
/// # use orcher_sdk::prelude::*;
/// # async fn example() -> Result<()> {
/// let service = WorkerBuilder::new()
///     .server_url("http://localhost:50051")
///     .namespace("production")
///     .task_queue("orders")
///     .identity("order-service-1")
///     .max_concurrent_workflows(50)
///     .max_concurrent_tasks(100)
///     .build()
///     .await?;
/// # Ok(())
/// # }
/// ```
pub struct WorkerBuilder {
    config: WorkerConfig,
    registry: Registry,
    interceptor_chain: InterceptorChain,
}

impl WorkerBuilder {
    /// Creates a builder with the default configuration.
    ///
    /// # Example
    ///
    /// ```rust
    /// # use orcher_sdk::prelude::*;
    /// let builder = WorkerBuilder::new();
    /// ```
    pub fn new() -> Self {
        let config = WorkerConfig::default();

        let registry = Registry::new();

        #[cfg(feature = "auto-register")]
        let registry = {
            let mut registry = registry;
            registry.collect_from_global_registry();

            tracing::debug!(
                tasks = registry.task_count(),
                workflows = registry.workflow_count(),
                actors = registry.actor_count(),
                "Auto-registered handlers from global registry"
            );
            registry
        };

        Self {
            config,
            registry,
            interceptor_chain: InterceptorChain::new(),
        }
    }

    /// Sets the server URL.
    ///
    /// # Example
    ///
    /// ```rust
    /// # use orcher_sdk::prelude::*;
    /// let builder = WorkerBuilder::new()
    ///     .server_url("http://localhost:50051");
    /// ```
    pub fn server_url(mut self, url: impl Into<String>) -> Self {
        self.config.server_url = url.into();
        self
    }

    /// Sets the namespace.
    ///
    /// # Example
    ///
    /// ```rust
    /// # use orcher_sdk::prelude::*;
    /// let builder = WorkerBuilder::new()
    ///     .namespace("production");
    /// ```
    pub fn namespace(mut self, namespace: impl Into<String>) -> Self {
        self.config.namespace = namespace.into();
        self
    }

    /// Sets the task queue to poll.
    ///
    /// # Example
    ///
    /// ```rust
    /// # use orcher_sdk::prelude::*;
    /// let builder = WorkerBuilder::new()
    ///     .task_queue("orders");
    /// ```
    pub fn task_queue(mut self, queue: impl Into<String>) -> Self {
        self.config.task_queue = queue.into();
        self
    }

    /// Sets the identity reported to the server, for observability.
    ///
    /// Defaults to `orcher-rust-` followed by a random UUID.
    ///
    /// # Example
    ///
    /// ```rust
    /// # use orcher_sdk::prelude::*;
    /// let builder = WorkerBuilder::new()
    ///     .identity("order-service-1");
    /// ```
    pub fn identity(mut self, identity: impl Into<String>) -> Self {
        self.config.identity = identity.into();
        self
    }

    /// Sets how often the worker tells the server it is alive (default: 10 seconds).
    ///
    /// # Example
    ///
    /// ```rust
    /// # use orcher_sdk::prelude::*;
    /// # use std::time::Duration;
    /// let builder = WorkerBuilder::new()
    ///     .heartbeat_interval(Duration::from_secs(5));
    /// ```
    pub fn heartbeat_interval(mut self, interval: Duration) -> Self {
        self.config.heartbeat_interval = interval;
        self
    }

    /// Sets the maximum number of concurrent workflow executions (default: 100).
    ///
    /// # Example
    ///
    /// ```rust
    /// # use orcher_sdk::prelude::*;
    /// let builder = WorkerBuilder::new()
    ///     .max_concurrent_workflows(50);
    /// ```
    pub fn max_concurrent_workflows(mut self, max: usize) -> Self {
        self.config.max_concurrent_workflows = max;
        self
    }

    /// Sets the maximum number of concurrent task executions (default: 200).
    ///
    /// # Example
    ///
    /// ```rust
    /// # use orcher_sdk::prelude::*;
    /// let builder = WorkerBuilder::new()
    ///     .max_concurrent_tasks(100);
    /// ```
    pub fn max_concurrent_tasks(mut self, max: usize) -> Self {
        self.config.max_concurrent_tasks = max;
        self
    }

    /// Sets the interval between polls for work (default: 100 ms).
    ///
    /// # Example
    ///
    /// ```rust
    /// # use orcher_sdk::prelude::*;
    /// # use std::time::Duration;
    /// let builder = WorkerBuilder::new()
    ///     .poll_interval(Duration::from_millis(200));
    /// ```
    pub fn poll_interval(mut self, interval: Duration) -> Self {
        self.config.poll_interval = interval;
        self
    }

    /// Sets the number of concurrent workflow pollers (default: 4, minimum: 1).
    ///
    /// Each poller holds its own long-poll request, so more pollers raise
    /// throughput when many workflows run at once.
    ///
    /// # Example
    ///
    /// ```rust
    /// # use orcher_sdk::prelude::*;
    /// let builder = WorkerBuilder::new()
    ///     .workflow_poller_count(8);
    /// ```
    pub fn workflow_poller_count(mut self, count: usize) -> Self {
        self.config.workflow_poller_count = count.max(1);
        self
    }

    /// Sets the number of concurrent task pollers (default: 4, minimum: 1).
    ///
    /// Each poller holds its own long-poll request, so more pollers raise
    /// throughput when many tasks run at once.
    ///
    /// # Example
    ///
    /// ```rust
    /// # use orcher_sdk::prelude::*;
    /// let builder = WorkerBuilder::new()
    ///     .task_poller_count(8);
    /// ```
    pub fn task_poller_count(mut self, count: usize) -> Self {
        self.config.task_poller_count = count.max(1);
        self
    }

    /// Sets the number of concurrent actor operation pollers (default: 4, minimum: 1).
    ///
    /// Used only when actors are registered.
    pub fn actor_poller_count(mut self, count: usize) -> Self {
        self.config.actor_poller_count = count.max(1);
        self
    }

    /// Sets the maximum number of concurrent actor operations (default: 100).
    pub fn max_concurrent_actor_operations(mut self, max: usize) -> Self {
        self.config.max_concurrent_actor_operations = max;
        self
    }

    /// Sets the maximum number of concurrent worker sessions (default: 10).
    ///
    /// Sessions pin a series of tasks to a single worker. Each session
    /// occupies one slot. When all slots are in use, the worker that picked up
    /// a `create_session()` waits for one of its own slots to be released, up
    /// to the session's creation timeout; it does not pass the creation on to
    /// another worker. If none frees in time, `create_session()` returns
    /// `TaskFailed`.
    ///
    /// # Example
    ///
    /// ```rust
    /// # use orcher_sdk::prelude::*;
    /// let builder = WorkerBuilder::new()
    ///     .max_sessions(20);
    /// ```
    pub fn max_sessions(mut self, max: usize) -> Self {
        self.config.max_sessions = max;
        self
    }

    /// Sets the organization to act for.
    ///
    /// Requests carry it in the `X-Organization-Id` header, which the server
    /// uses for organization-level quotas and billing attribution.
    ///
    /// # Example
    ///
    /// ```rust
    /// # use orcher_sdk::prelude::*;
    /// let builder = WorkerBuilder::new()
    ///     .organization_id("org_abc123");
    /// ```
    pub fn organization_id(mut self, org_id: impl Into<String>) -> Self {
        self.config.organization_id = Some(org_id.into());
        self
    }

    /// Sets the API key that authenticates the worker with the server.
    pub fn api_key(mut self, key: impl Into<String>) -> Self {
        self.config.api_key = Some(key.into());
        self
    }

    /// Sets the TLS settings for every connection the worker opens.
    ///
    /// An `https://` server URL needs none of this: it connects over TLS
    /// verified against the system trust store by default. Supply settings to
    /// trust a private CA, present a client certificate (mTLS) or override the
    /// server name. They take the same [`ClientTlsConfig`] as the client.
    /// TLS is only negotiated for `https://` addresses.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use orcher_sdk::prelude::*;
    /// # use orcher_sdk::client::ClientTlsConfig;
    /// # async fn example() -> std::result::Result<(), Box<dyn std::error::Error>> {
    /// let worker = WorkerBuilder::new()
    ///     .server_url("https://orcher.internal:443")
    ///     .task_queue("orders")
    ///     .tls(
    ///         ClientTlsConfig::new()
    ///             .with_ca_cert_file("ca.pem")?
    ///             .with_client_identity_files("client.pem", "client-key.pem")?,
    ///     )
    ///     .build()
    ///     .await?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// [`ClientTlsConfig`]: crate::client::ClientTlsConfig
    pub fn tls(mut self, tls: crate::client::ClientTlsConfig) -> Self {
        self.config.tls = Some(tls);
        self
    }

    /// Declares the code release this worker is running.
    ///
    /// An opaque label, such as a git SHA, an image digest or a release tag. The
    /// server records it on a workflow execution the first time a worker claims
    /// it, so that the execution keeps running against the code it started on.
    /// The label is never parsed or ordered. A blank value clears it.
    ///
    /// Defaults to the `ORCHER_VERSION_ID` environment variable, since the value
    /// usually comes from the build. Leaving it unset declares nothing and
    /// changes no behavior.
    ///
    /// # Example
    ///
    /// ```rust
    /// # use orcher_sdk::prelude::*;
    /// let builder = WorkerBuilder::new()
    ///     .version_id("v1.2.3-abc123");
    /// ```
    pub fn version_id(mut self, id: impl Into<String>) -> Self {
        let v = id.into();
        self.config.version_id = if v.trim().is_empty() { None } else { Some(v) };
        self
    }

    /// Adds an interceptor that runs around every workflow and task execution.
    ///
    /// Interceptors are called in the order they are added. Use the built-in
    /// ones or implement [`InterceptorHook`].
    ///
    /// # Example
    ///
    /// ```rust
    /// # use orcher_sdk::prelude::*;
    /// # use orcher_sdk::interceptor::{LoggingInterceptor, MetricsInterceptor};
    /// let builder = WorkerBuilder::new()
    ///     .interceptor(LoggingInterceptor::new())
    ///     .interceptor(MetricsInterceptor::new());
    /// ```
    pub fn interceptor(mut self, interceptor: impl InterceptorHook + 'static) -> Self {
        self.interceptor_chain.add(interceptor);
        self
    }

    /// Decrypts incoming payloads with AES-256-GCM.
    ///
    /// The key must match the one used by the client that started the workflow.
    /// Without this, encrypted payloads reach handlers as opaque bytes. Replaces
    /// any codec chain already configured.
    pub fn with_encryption(mut self, key: &[u8; 32]) -> Self {
        use orcher_sdk_core::payload::codec::{CodecChain, EncryptionPayloadCodec};
        let chain = CodecChain::new().with_codec(EncryptionPayloadCodec::new(key));
        self.config.codec_chain = Some(Arc::new(chain));
        self
    }

    /// Decompresses incoming gzip payloads.
    ///
    /// Replaces any codec chain already configured.
    pub fn with_gzip_compression(mut self) -> Self {
        use orcher_sdk_core::payload::codec::{CodecChain, GzipPayloadCodec};
        let chain = CodecChain::new().with_codec(GzipPayloadCodec::default());
        self.config.codec_chain = Some(Arc::new(chain));
        self
    }

    /// Builds the [`Worker`].
    ///
    /// When actor handlers are registered, they are registered with the server
    /// here; nothing else contacts the server until [`Worker::run`].
    ///
    /// # Errors
    ///
    /// Returns [`WorkerError::InvalidConfiguration`] if the server URL or task
    /// queue is empty. Fails if actor handlers are registered and their
    /// registration with the server fails.
    ///
    /// [`WorkerError::InvalidConfiguration`]: crate::error::WorkerError::InvalidConfiguration
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use orcher_sdk::prelude::*;
    /// # async fn example() -> Result<()> {
    /// let service = WorkerBuilder::new()
    ///     .server_url("http://localhost:50051")
    ///     .task_queue("orders")
    ///     .build()
    ///     .await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn build(self) -> Result<Worker> {
        if self.config.server_url.is_empty() {
            return Err(Error::Worker(
                crate::error::WorkerError::InvalidConfiguration(
                    "server_url cannot be empty".to_string(),
                ),
            ));
        }

        if self.config.task_queue.is_empty() {
            return Err(Error::Worker(
                crate::error::WorkerError::InvalidConfiguration(
                    "task_queue cannot be empty".to_string(),
                ),
            ));
        }

        // Reject unusable TLS settings now rather than at the first poll:
        // a certificate without its key, or PEM that does not parse.
        if self.config.tls.is_some() {
            crate::tls::check(&self.config.server_url, self.config.tls.as_ref()).map_err(
                |reason| Error::Worker(crate::error::WorkerError::InvalidConfiguration(reason)),
            )?;
        }

        tracing::info!(
            server_url = %self.config.server_url,
            namespace = %self.config.namespace,
            task_queue = %self.config.task_queue,
            identity = %self.config.identity,
            tasks = self.registry.task_count(),
            workflows = self.registry.workflow_count(),
            actors = {
                #[cfg(feature = "auto-register")]
                { self.registry.actor_count() }
                #[cfg(not(feature = "auto-register"))]
                { 0 }
            },
            "Building ORCHER Worker"
        );

        let runtime_config = RuntimeConfig {
            max_concurrent_workflows: self.config.max_concurrent_workflows,
            max_concurrent_tasks: self.config.max_concurrent_tasks,
            default_task_queue: self.config.task_queue.clone(),
            namespace: self.config.namespace.clone(),
            codec_chain: self.config.codec_chain.clone(),
        };
        let runtime = Arc::new(ExecutionRuntime::new(runtime_config));

        // The executor that runs actor operations; the worker host registers
        // the handlers with the server when the worker runs.
        //
        // Both the gate and the handler list must come from the handler
        // registry, which the `#[operations]` macro populates
        // (`register_actor_handler_direct`). The definitions registry
        // (`actor_count`/`get_actor`) is filled only by the manual definition
        // APIs; gating on it would leave macro-registered actors unserved.
        #[cfg(feature = "auto-register")]
        let actor_executor = {
            if self.registry.actor_handler_count() > 0 {
                let executor = crate::actor::ActorExecutor::new();

                for (actor_name, operations) in self.registry.actor_handlers() {
                    for (operation_name, handler_registration) in operations {
                        executor.register_handler(
                            actor_name,
                            operation_name,
                            handler_registration.handler.clone(),
                        );
                    }
                }

                tracing::info!(
                    handlers = executor.handler_count(),
                    "Actor executor initialized"
                );

                Some(Arc::new(executor))
            } else {
                None
            }
        };

        tracing::info!(
            identity = %self.config.identity,
            "Worker built successfully"
        );

        let (shutdown_tx, _) = tokio::sync::broadcast::channel(1);

        if !self.interceptor_chain.is_empty() {
            tracing::info!(
                interceptors = ?self.interceptor_chain,
                "Interceptor chain configured"
            );
        }

        Ok(Worker {
            config: self.config.clone(),
            runtime,
            registry: Arc::new(RwLock::new(self.registry)),
            #[cfg(feature = "auto-register")]
            actor_executor,
            service_id: self.config.identity.clone(),
            shutdown_tx,
            started_at: std::time::Instant::now(),
            interceptor_chain: Arc::new(self.interceptor_chain),
            host: std::sync::Mutex::new(None),
        })
    }
}

impl Default for WorkerBuilder {
    fn default() -> Self {
        Self::new()
    }
}

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

    #[test]
    fn test_builder_configuration() {
        let builder = WorkerBuilder::new()
            .server_url("http://test:1234")
            .namespace("test-ns")
            .task_queue("test-queue")
            .identity("test-service")
            .max_concurrent_workflows(50)
            .max_concurrent_tasks(100)
            .poll_interval(Duration::from_millis(200));

        assert_eq!(builder.config.server_url, "http://test:1234");
        assert_eq!(builder.config.namespace, "test-ns");
        assert_eq!(builder.config.task_queue, "test-queue");
        assert_eq!(builder.config.identity, "test-service");
        assert_eq!(builder.config.max_concurrent_workflows, 50);
        assert_eq!(builder.config.max_concurrent_tasks, 100);
        assert_eq!(builder.config.poll_interval, Duration::from_millis(200));
    }

    #[tokio::test]
    async fn tls_settings_reach_the_driver_configs() {
        let worker = WorkerBuilder::new()
            .server_url("https://10.0.0.1:443")
            .task_queue("q")
            .tls(crate::client::ClientTlsConfig::new().with_domain_name("orcher.internal"))
            .build()
            .await
            .expect("builds");
        let core = worker.core_tls().expect("TLS configured");
        assert_eq!(core.domain_name.as_deref(), Some("orcher.internal"));
    }

    #[tokio::test]
    async fn a_worker_that_never_ran_has_no_measurements() {
        let worker = WorkerBuilder::new()
            .server_url("http://localhost:50051")
            .task_queue("q")
            .build()
            .await
            .expect("builds");
        assert!(worker.wire_metrics().is_none());
    }

    #[tokio::test]
    async fn pem_that_does_not_parse_fails_the_build() {
        let result = WorkerBuilder::new()
            .server_url("https://orcher.example:443")
            .task_queue("q")
            .tls(
                crate::client::ClientTlsConfig::new()
                    .with_client_identity(b"not a cert".to_vec(), b"not a key".to_vec()),
            )
            .build()
            .await;
        assert!(matches!(
            result,
            Err(Error::Worker(
                crate::error::WorkerError::InvalidConfiguration(_)
            ))
        ));
    }

    /// TLS settings given to the worker reach sdk-core as given; an `https`
    /// address without any is left to core, which verifies it against the
    /// system trust store (the `tls` tests check that on the wire).
    #[tokio::test]
    async fn the_tls_settings_given_reach_core_and_none_are_invented() {
        let https = WorkerBuilder::new()
            .server_url("https://orcher.example:443")
            .task_queue("q")
            .build()
            .await
            .unwrap();
        assert!(https.core_tls().is_none());

        let pinned = WorkerBuilder::new()
            .server_url("https://orcher.example:443")
            .task_queue("q")
            .tls(crate::client::ClientTlsConfig::new().with_domain_name("orcher.internal"))
            .build()
            .await
            .unwrap();
        let core = pinned.core_tls().expect("the settings reach core");
        assert_eq!(core.domain_name.as_deref(), Some("orcher.internal"));
    }

    #[tokio::test]
    async fn a_client_certificate_without_a_key_fails_the_build() {
        let mut tls = crate::client::ClientTlsConfig::new();
        tls.client_cert = Some(b"cert".to_vec());
        let result = WorkerBuilder::new()
            .server_url("https://orcher.example:443")
            .task_queue("q")
            .tls(tls)
            .build()
            .await;
        match result {
            Err(Error::Worker(crate::error::WorkerError::InvalidConfiguration(reason))) => {
                assert!(reason.contains("must be set together"), "{reason}")
            }
            Err(other) => panic!("unexpected error: {other}"),
            Ok(_) => panic!("must fail"),
        }
    }

    #[test]
    fn tls_files_that_do_not_exist_name_the_path() {
        let err = crate::client::ClientTlsConfig::new()
            .with_ca_cert_file("/nonexistent/ca.pem")
            .unwrap_err();
        assert!(err.to_string().contains("/nonexistent/ca.pem"), "{err}");
    }

    #[tokio::test]
    async fn test_builder_validation_empty_url() {
        let result = WorkerBuilder::new()
            .server_url("")
            .task_queue("test-queue")
            .build()
            .await;

        assert!(result.is_err());
        assert!(matches!(result.unwrap_err(), Error::Worker(_)));
    }

    #[tokio::test]
    async fn test_builder_validation_empty_queue() {
        let result = WorkerBuilder::new()
            .server_url("http://localhost:50051")
            .task_queue("")
            .build()
            .await;

        assert!(result.is_err());
        assert!(matches!(result.unwrap_err(), Error::Worker(_)));
    }

    #[test]
    fn test_builder_default() {
        let builder = WorkerBuilder::default();
        assert_eq!(builder.config.server_url, "http://localhost:50051");
    }
}