aws-durable-execution-sdk 1.0.0

Rust SDK for AWS Lambda Durable Functions
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
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
//! Configuration types for the durable execution runtime.

use std::sync::Arc;
use std::time::Duration;

use crate::client::ExecutionClient;
use crate::plugin::PluginFactory;

/// The registered plugin factories, in registration order, each with the
/// type name it was registered under.
pub(crate) type PluginFactories = Vec<(&'static str, Arc<dyn PluginFactory>)>;

/// Error returned when [`OptionsBuilder::build()`] detects an invalid
/// configuration combination.
///
/// This error fires at construction time, never mid-execution, matching
/// the spec's construction-time-only validation rule.
///
/// # Examples
///
/// ```no_run
/// use aws_durable_execution_sdk::Options;
///
/// // Attempting to set both sdk_config and lambda_client errors at build():
/// // let opts = Options::builder()
/// //     .sdk_config(config)
/// //     .lambda_client(client)
/// //     .build(); // Err(OptionsValidationError { ... })
/// ```
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct OptionsValidationError {
    message: String,
}

impl std::fmt::Display for OptionsValidationError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "invalid Options configuration: {}", self.message)
    }
}

impl std::error::Error for OptionsValidationError {}

/// Configuration for the durable execution runtime.
///
/// Use [`Options::builder()`] to construct. All settings are optional;
/// defaults are suitable for standard Lambda deployments.
///
/// # Customizing the service client
///
/// The SDK calls the durable execution service through an
/// `aws_sdk_lambda::Client` and relies on that client's own standard,
/// jittered retry for transient failures. To customize transport behavior,
/// retry policy, timeouts, endpoint, credentials, build the client (or an
/// `aws_config::SdkConfig`) yourself and supply it via
/// [`lambda_client`](OptionsBuilder::lambda_client) (or
/// [`sdk_config`](OptionsBuilder::sdk_config)). The SDK uses that client's
/// configuration unchanged, with one addition: it adds the token
/// `aws-durable-execution-sdk-rust/<version>` to the `User-Agent` header of
/// each of its own requests, including requests sent through a client you
/// supply. `<version>` is the crate version.
///
/// To replace the transport itself, supply an
/// [`ExecutionClient`](crate::ExecutionClient) via
/// [`execution_client`](OptionsBuilder::execution_client). The SDK then
/// sends both durable execution service calls through it instead of the
/// Lambda client. [`LambdaExecutionClient::new`](crate::LambdaExecutionClient::new)
/// builds the default transport, so a custom transport can wrap it.
///
/// # Examples
///
/// ```no_run
/// use aws_durable_execution_sdk::Options;
///
/// let options = Options::builder()
///     .build()
///     .expect("valid default config");
/// # drop(options);
/// ```
#[derive(Clone)]
#[non_exhaustive]
pub struct Options {
    /// A user-built AWS SDK config used to construct the Lambda client.
    pub(crate) sdk_config: Option<aws_config::SdkConfig>,
    /// A pre-built Lambda client. When set, it is used directly instead of
    /// building one from [`Self::sdk_config`].
    pub(crate) lambda_client: Option<aws_sdk_lambda::Client>,
    /// A caller-supplied transport. When set, it replaces the Lambda
    /// transport for both service calls.
    pub(crate) execution_client: Option<Arc<dyn ExecutionClient>>,
    /// Coalescing window for checkpoint writes. `None` (the default) adds
    /// no window: writes batch behind the single writer with a zero window.
    pub(crate) checkpoint_delay: Option<Duration>,
    /// The plugin factories, in registration order, each with the type
    /// name it was registered under. Empty by default.
    pub(crate) plugins: PluginFactories,
    /// How many levels of finished child contexts keep their children
    /// visible to later invocations. 0 (the default) keeps none.
    pub(crate) plugin_child_operations_depth: u32,
}

impl Default for Options {
    /// Creates default options suitable for standard Lambda deployments.
    ///
    /// # Examples
    ///
    /// ```
    /// use aws_durable_execution_sdk::Options;
    ///
    /// let opts = Options::default();
    /// # drop(opts);
    /// ```
    fn default() -> Self {
        Self {
            sdk_config: None,
            lambda_client: None,
            execution_client: None,
            checkpoint_delay: None,
            plugins: Vec::new(),
            plugin_child_operations_depth: 0,
        }
    }
}

/// The `Debug` text of an optional transport: `None`, or a placeholder,
/// because [`ExecutionClient`] does not require `Debug`.
struct ExecutionClientDebug<'a>(&'a Option<Arc<dyn ExecutionClient>>);

impl std::fmt::Debug for ExecutionClientDebug<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self.0 {
            Some(_) => f.write_str("<custom execution client>"),
            None => f.write_str("None"),
        }
    }
}

// Written by hand: `Arc<dyn ExecutionClient>` and `Arc<dyn PluginFactory>`
// do not implement `Debug`.
impl std::fmt::Debug for Options {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Options")
            .field("sdk_config", &self.sdk_config)
            .field("lambda_client", &self.lambda_client)
            .field(
                "execution_client",
                &ExecutionClientDebug(&self.execution_client),
            )
            .field("checkpoint_delay", &self.checkpoint_delay)
            .field("plugins", &self.plugins.len())
            .field(
                "plugin_child_operations_depth",
                &self.plugin_child_operations_depth,
            )
            .finish()
    }
}

impl Options {
    /// Creates a new [`OptionsBuilder`].
    ///
    /// # Examples
    ///
    /// ```
    /// use aws_durable_execution_sdk::Options;
    ///
    /// let builder = Options::builder();
    /// let opts = builder.build().expect("valid config");
    /// # drop(opts);
    /// ```
    pub fn builder() -> OptionsBuilder {
        OptionsBuilder::default()
    }
}

/// Builder for [`Options`].
///
/// Follows the Rust API Guidelines C-BUILDER pattern. All methods consume
/// and return `self` for chaining.
///
/// # Examples
///
/// ```no_run
/// use aws_durable_execution_sdk::{Options, OptionsBuilder};
///
/// let options = Options::builder()
///     .build()
///     .expect("valid config");
/// # drop(options);
/// ```
#[derive(Default)]
#[must_use = "builders do nothing unless .build() is called"]
#[non_exhaustive]
pub struct OptionsBuilder {
    sdk_config: Option<aws_config::SdkConfig>,
    lambda_client: Option<aws_sdk_lambda::Client>,
    execution_client: Option<Arc<dyn ExecutionClient>>,
    checkpoint_delay: Option<Duration>,
    plugins: PluginFactories,
    plugin_child_operations_depth: u32,
}

// Written by hand: `Arc<dyn ExecutionClient>` and `Arc<dyn PluginFactory>`
// do not implement `Debug`.
impl std::fmt::Debug for OptionsBuilder {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("OptionsBuilder")
            .field("sdk_config", &self.sdk_config)
            .field("lambda_client", &self.lambda_client)
            .field(
                "execution_client",
                &ExecutionClientDebug(&self.execution_client),
            )
            .field("checkpoint_delay", &self.checkpoint_delay)
            .field("plugins", &self.plugins.len())
            .field(
                "plugin_child_operations_depth",
                &self.plugin_child_operations_depth,
            )
            .finish()
    }
}

impl OptionsBuilder {
    /// Sets the AWS SDK configuration for building service clients.
    ///
    /// Use this to provide custom endpoint configuration, credentials, or
    /// HTTP client settings.
    ///
    /// By default, when neither this nor
    /// [`lambda_client`](Self::lambda_client) is set, the SDK loads the
    /// ambient environment configuration
    /// (`aws_config::load_defaults`) and builds a client from it. That
    /// default client uses a 5 s connect timeout, a 50 s read timeout and
    /// a 55 s attempt timeout. A client built from a config supplied here
    /// keeps the config's own timeouts, and the SDK adds none.
    ///
    /// The SDK adds the token `aws-durable-execution-sdk-rust/<version>` to
    /// the `User-Agent` header of each of its own requests sent through the
    /// client it builds from this config, where `<version>` is the crate
    /// version.
    ///
    /// The parameter type is re-exported at the crate root as
    /// [`SdkConfig`](crate::SdkConfig), so callers can name it without
    /// depending on `aws-config` directly.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use aws_durable_execution_sdk::Options;
    ///
    /// # async fn example() {
    /// let sdk_config = aws_config::load_defaults(aws_config::BehaviorVersion::latest()).await;
    /// let opts = Options::builder()
    ///     .sdk_config(sdk_config)
    ///     .build()
    ///     .expect("valid config");
    /// # drop(opts);
    /// # }
    /// ```
    pub fn sdk_config(mut self, config: crate::SdkConfig) -> Self {
        self.sdk_config = Some(config);
        self
    }

    /// Sets a pre-built Lambda client.
    ///
    /// When provided, the SDK uses this client instead of building one
    /// from the SDK config. By default, when neither this nor
    /// [`sdk_config`](Self::sdk_config) is set, the SDK builds a client
    /// from the ambient environment configuration
    /// (`aws_config::load_defaults`), with a 5 s connect timeout, a 50 s
    /// read timeout and a 55 s attempt timeout. A client supplied here
    /// keeps its own timeouts, and the SDK adds none.
    ///
    /// This is the supported path for customizing how the SDK talks to the
    /// durable execution service: configure retry, timeouts, endpoint, or
    /// credentials on the client (or use
    /// [`sdk_config`](Self::sdk_config)) and the SDK uses its
    /// configuration unchanged. The SDK adds the token
    /// `aws-durable-execution-sdk-rust/<version>` to the `User-Agent` header
    /// of each of its own requests sent through this client, where
    /// `<version>` is the crate version. It adds the token to each request,
    /// so the client itself is not changed.
    /// Transient-failure retry of the service calls is the client's own
    /// standard retry; the SDK adds no retry layer of its own.
    ///
    /// The parameter type is re-exported at the crate root as
    /// [`LambdaClient`](crate::LambdaClient), so callers can name it without
    /// depending on `aws-sdk-lambda` directly.
    ///
    /// # Examples
    ///
    /// The client and its configuration type are both reachable through the
    /// crate root, so this compiles with no direct `aws-config` or
    /// `aws-sdk-lambda` dependency:
    ///
    /// ```no_run
    /// use aws_durable_execution_sdk::{LambdaClient, Options, SdkConfig};
    ///
    /// let config = SdkConfig::builder().build();
    /// let client = LambdaClient::new(&config);
    /// let opts = Options::builder()
    ///     .lambda_client(client)
    ///     .build()
    ///     .expect("valid config");
    /// # drop(opts);
    /// ```
    pub fn lambda_client(mut self, client: crate::LambdaClient) -> Self {
        self.lambda_client = Some(client);
        self
    }

    /// Sets the transport for the two durable execution service calls.
    ///
    /// The SDK sends every checkpoint and every state read through
    /// `client` instead of the Lambda transport. See the
    /// [`ExecutionClient`](crate::ExecutionClient) contract for what a
    /// transport returns and how each error scope ends the invocation or
    /// the execution. [`LambdaExecutionClient::new`](crate::LambdaExecutionClient::new)
    /// builds the default transport, so a custom transport can wrap it.
    ///
    /// The transport replaces the Lambda client, so it cannot be set
    /// together with [`lambda_client`](Self::lambda_client) or
    /// [`sdk_config`](Self::sdk_config): [`build`](Self::build) rejects
    /// that combination.
    ///
    /// The transport owns its own request headers. The SDK adds its
    /// `User-Agent` token only to requests that
    /// [`LambdaExecutionClient`](crate::LambdaExecutionClient) sends, so a
    /// transport that wraps it keeps the token.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use std::sync::Arc;
    /// use aws_durable_execution_sdk::{LambdaClient, LambdaExecutionClient, Options, SdkConfig};
    ///
    /// let client = LambdaClient::new(&SdkConfig::builder().build());
    /// let opts = Options::builder()
    ///     .execution_client(Arc::new(LambdaExecutionClient::new(client)))
    ///     .build()
    ///     .expect("valid config");
    /// # drop(opts);
    /// ```
    pub fn execution_client(mut self, client: Arc<dyn ExecutionClient>) -> Self {
        self.execution_client = Some(client);
        self
    }

    /// Defers checkpoint writes for up to `delay` so that checkpoints from
    /// concurrently running operations coalesce into fewer service calls.
    ///
    /// With a delay configured, a checkpoint written while other operations
    /// are also checkpointing joins a shared batch; the batch is sent as a
    /// single `CheckpointDurableExecution` call when the window elapses.
    /// For high-fan-out executions (large `map`/`parallel` batches) this
    /// trades up to `delay` of extra latency per checkpoint for
    /// substantially fewer API calls. A coalesced batch is split to respect
    /// the service's per-request limits (operation count and payload size),
    /// preserving write order across the splits. Every operation still
    /// awaits its own checkpoint before proceeding, so ordering and replay
    /// semantics are unchanged.
    ///
    /// # Flush contract
    ///
    /// A checkpoint that must land before the execution can make progress
    /// is never held back by the window. Pending checkpoints are flushed
    /// unconditionally at these points:
    ///
    /// - **Suspension**: before an invocation reports `PENDING` to the
    ///   service, every buffered checkpoint is written, so no recorded
    ///   progress is lost across the suspend/resume boundary.
    /// - **Execution completion**: before an invocation reports its
    ///   terminal `SUCCEEDED`/`FAILED` envelope, the buffer is drained.
    /// - **Callback creation**: creating a callback flushes immediately,
    ///   because the service assigns the callback ID in the checkpoint
    ///   response and the handler needs that ID right away.
    ///
    /// When unset (the default), no window is added, and batching never
    /// holds a write back: checkpoint writes go through a single ordered
    /// writer, which sends a write as soon as no earlier request is in
    /// flight, and writes that wait for the same request share it, as in
    /// the JavaScript SDK.
    ///
    /// # Examples
    ///
    /// ```
    /// use aws_durable_execution_sdk::Options;
    /// use std::time::Duration;
    ///
    /// let opts = Options::builder()
    ///     .checkpoint_delay(Duration::from_millis(20))
    ///     .build()
    ///     .expect("valid config");
    /// # drop(opts);
    /// ```
    pub fn checkpoint_delay(mut self, delay: Duration) -> Self {
        self.checkpoint_delay = Some(delay);
        self
    }

    /// Registers a plugin factory.
    ///
    /// Each invocation calls every registered factory once, in
    /// registration order, and the plugin a factory returns observes that
    /// one invocation. The [`plugin`](crate::plugin) module describes the
    /// factory, the plugin and its hooks.
    ///
    /// [`build`](Self::build) rejects two factories whose
    /// [`exclusive_group`](PluginFactory::exclusive_group) returns the same
    /// non-empty group.
    ///
    /// # Examples
    ///
    /// ```
    /// use aws_durable_execution_sdk::plugin::{InvocationInfo, Plugin, PluginFactory};
    /// use aws_durable_execution_sdk::{BoxError, Options};
    ///
    /// struct Quiet;
    /// impl Plugin for Quiet {}
    ///
    /// struct QuietFactory;
    /// impl PluginFactory for QuietFactory {
    ///     fn create_plugin(&self, _info: &InvocationInfo) -> Result<Option<Box<dyn Plugin>>, BoxError> {
    ///         Ok(Some(Box::new(Quiet)))
    ///     }
    /// }
    ///
    /// let opts = Options::builder()
    ///     .plugin(QuietFactory)
    ///     .build()
    ///     .expect("valid config");
    /// # drop(opts);
    /// ```
    pub fn plugin<F: PluginFactory>(mut self, factory: F) -> Self {
        self.plugins.push((
            std::any::type_name::<F>(),
            Arc::new(factory) as Arc<dyn PluginFactory>,
        ));
        self
    }

    /// Keeps the children of finished child contexts visible to plugins
    /// in later invocations, up to `depth` levels. The default is 0.
    ///
    /// When a child context, a `map` or a `parallel` finishes, the service
    /// stops sending its child operations to later invocations, so
    /// [`InvocationInfo::operations`](crate::plugin::InvocationInfo::operations)
    /// holds only the operations above it. Within the depth, the context's
    /// terminal record carries `ReplayChildren`, and the service keeps
    /// sending its children.
    ///
    /// The depth counts context levels below the root. `1` keeps the
    /// children of top-level contexts: the operations of a top-level child
    /// context, and the items and branches of a top-level `map` or
    /// `parallel`. `2` also keeps their children, such as the operations
    /// inside each item. `u32::MAX` keeps the whole tree, and `0` changes
    /// no record. A map item or parallel branch with
    /// [`NestingMode::Flat`](crate::builders::map_parallel::NestingMode::Flat) adds no level. The
    /// setting covers succeeded and failed contexts alike, and it also
    /// flags the record of a `wait_for_callback`, the success of a
    /// `try_join_all` or `join_all`, and every combinator failure. It
    /// applies whether or not a plugin is registered.
    ///
    /// The cost is that a preserved context runs again on every later
    /// replay:
    ///
    /// - A preserved child context, map item or parallel branch re-runs
    ///   its body on each later replay, and its children return recorded
    ///   results.
    /// - A preserved `map` or `parallel` re-runs its items on each later
    ///   replay, and their children return recorded results.
    /// - A preserved `wait_for_callback` re-runs its body the same way.
    /// - A preserved `try_join_all` or `join_all` drives its inputs again
    ///   on each later replay, and each input replays its own record.
    ///
    /// A record whose result is above the size limit does not change: it
    /// already carries `ReplayChildren`.
    ///
    /// # Examples
    ///
    /// ```
    /// use aws_durable_execution_sdk::Options;
    ///
    /// let opts = Options::builder()
    ///     .plugin_child_operations_depth(1)
    ///     .build()
    ///     .expect("valid config");
    /// # drop(opts);
    /// ```
    pub fn plugin_child_operations_depth(mut self, depth: u32) -> Self {
        self.plugin_child_operations_depth = depth;
        self
    }

    /// Builds the [`Options`] from the configured values.
    ///
    /// # Errors
    ///
    /// Returns an error if the configuration contains invalid combinations:
    /// - Setting `execution_client` together with `lambda_client` or
    ///   `sdk_config` is invalid (the execution client replaces the Lambda
    ///   transport: provide one or the other). This check runs first.
    /// - Setting both `sdk_config` and `lambda_client` is invalid (the
    ///   client supersedes the config: provide one or the other).
    /// - Registering two plugin factories whose
    ///   [`exclusive_group`](PluginFactory::exclusive_group) returns the
    ///   same non-empty group is invalid. The message names both factory
    ///   types, the earlier registration first, and the group. `None` and
    ///   `Some("")` are no group.
    ///
    /// # Examples
    ///
    /// ```
    /// use aws_durable_execution_sdk::Options;
    ///
    /// let opts = Options::builder().build();
    /// assert!(opts.is_ok());
    /// # drop(opts);
    /// ```
    pub fn build(self) -> Result<Options, OptionsValidationError> {
        // Construction-time-only validation: invalid combos error here,
        // not mid-execution. Matches the spec's "construction-time only" rule.
        if self.execution_client.is_some()
            && (self.lambda_client.is_some() || self.sdk_config.is_some())
        {
            return Err(OptionsValidationError {
                message: "cannot set `execution_client` together with `lambda_client` or \
                          `sdk_config`: the execution client replaces the Lambda transport; \
                          provide one or the other"
                    .to_owned(),
            });
        }
        if self.sdk_config.is_some() && self.lambda_client.is_some() {
            return Err(OptionsValidationError {
                message: "cannot set both `sdk_config` and `lambda_client`: \
                          the pre-built client supersedes the config; provide one or the other"
                    .to_owned(),
            });
        }

        check_exclusive_groups(&self.plugins)?;

        Ok(Options {
            sdk_config: self.sdk_config,
            lambda_client: self.lambda_client,
            execution_client: self.execution_client,
            checkpoint_delay: self.checkpoint_delay,
            plugins: self.plugins,
            plugin_child_operations_depth: self.plugin_child_operations_depth,
        })
    }
}

/// Rejects two factories in the same non-empty exclusive group.
///
/// Each factory's group is read once, in registration order. A group seen
/// a second time names the factory that claimed it first, so the message
/// lists the earlier registration first.
fn check_exclusive_groups(plugins: &PluginFactories) -> Result<(), OptionsValidationError> {
    let mut claimed: Vec<(&str, &'static str)> = Vec::new();
    for (type_name, factory) in plugins {
        let Some(group) = factory.exclusive_group().filter(|g| !g.is_empty()) else {
            continue;
        };
        if let Some((_, first)) = claimed.iter().find(|(g, _)| *g == group) {
            return Err(OptionsValidationError {
                message: format!(
                    "plugin factories '{first}' and '{type_name}' are mutually exclusive in \
                     group '{group}'; register only one"
                ),
            });
        }
        claimed.push((group, type_name));
    }
    Ok(())
}

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

    /// An offline `SdkConfig` (no network, no credentials probe).
    fn dummy_sdk_config() -> aws_config::SdkConfig {
        aws_config::SdkConfig::builder().build()
    }

    /// An offline Lambda client (built from a static config; never calls AWS).
    fn dummy_lambda_client() -> aws_sdk_lambda::Client {
        let conf = aws_sdk_lambda::config::Config::builder()
            .behavior_version(aws_sdk_lambda::config::BehaviorVersion::latest())
            .region(aws_sdk_lambda::config::Region::new("us-east-1"))
            .build();
        aws_sdk_lambda::Client::from_conf(conf)
    }

    #[test]
    fn plugin_child_operations_depth_defaults_to_zero() {
        assert_eq!(Options::default().plugin_child_operations_depth, 0);
        let built = Options::builder().build().expect("valid config");
        assert_eq!(built.plugin_child_operations_depth, 0);
        let builder = Options::builder().plugin_child_operations_depth(3);
        let builder_debug = format!("{builder:?}");
        let options = builder.build().expect("valid config");
        assert_eq!(options.plugin_child_operations_depth, 3);
        assert!(
            builder_debug.contains("plugin_child_operations_depth: 3"),
            "{builder_debug}"
        );
        let options_debug = format!("{options:?}");
        assert!(
            options_debug.contains("plugin_child_operations_depth: 3"),
            "{options_debug}"
        );
    }

    #[test]
    fn default_options_build_succeeds() {
        let result = Options::builder().build();
        assert!(result.is_ok());
    }

    #[test]
    fn sdk_config_and_lambda_client_conflict() {
        let result = Options::builder()
            .sdk_config(dummy_sdk_config())
            .lambda_client(dummy_lambda_client())
            .build();
        assert_eq!(
            result.unwrap_err().to_string(),
            "invalid Options configuration: cannot set both `sdk_config` and `lambda_client`: \
             the pre-built client supersedes the config; provide one or the other"
        );
    }

    #[test]
    fn sdk_config_alone_is_valid_and_is_stored() {
        let opts = Options::builder().sdk_config(dummy_sdk_config()).build();
        assert!(opts.is_ok());
        assert!(
            opts.expect("valid").sdk_config.is_some(),
            "sdk_config must be preserved, not dropped"
        );
    }

    #[test]
    fn lambda_client_alone_is_valid_and_is_stored() {
        let opts = Options::builder()
            .lambda_client(dummy_lambda_client())
            .build();
        assert!(opts.is_ok());
        assert!(
            opts.expect("valid").lambda_client.is_some(),
            "lambda_client must be preserved, not dropped"
        );
    }

    #[test]
    fn validation_error_implements_std_error() {
        let err = OptionsValidationError {
            message: "test".to_owned(),
        };
        // Verify it implements std::error::Error via trait object coercion.
        let _: &dyn std::error::Error = &err;
        assert!(err.to_string().contains("test"));
    }

    #[test]
    fn default_options_carry_no_execution_tuning() {
        let opts = Options::builder().build().expect("valid");
        assert!(
            opts.checkpoint_delay.is_none(),
            "unset checkpoint delay must stay None so batches flush at once"
        );
    }

    #[test]
    fn checkpoint_delay_is_stored() {
        let opts = Options::builder()
            .checkpoint_delay(Duration::from_millis(20))
            .build()
            .expect("valid");
        assert_eq!(opts.checkpoint_delay, Some(Duration::from_millis(20)));
    }

    /// A transport that implements no `Debug`, as a caller's may not.
    struct NoDebugTransport;

    impl ExecutionClient for NoDebugTransport {
        fn checkpoint(
            &self,
            _execution_arn: &str,
            _checkpoint_token: &str,
            _updates: Vec<crate::lambda_types::OperationUpdate>,
        ) -> std::pin::Pin<
            Box<
                dyn Future<Output = Result<crate::CheckpointOutput, crate::ExecutionClientError>>
                    + Send
                    + '_,
            >,
        > {
            Box::pin(async {
                Ok(crate::CheckpointOutput::new(
                    Some("t".to_owned()),
                    vec![],
                    None,
                ))
            })
        }

        fn get_state(
            &self,
            _execution_arn: &str,
            _checkpoint_token: &str,
            _marker: Option<&str>,
        ) -> std::pin::Pin<
            Box<
                dyn Future<Output = Result<crate::GetStateOutput, crate::ExecutionClientError>>
                    + Send
                    + '_,
            >,
        > {
            Box::pin(async { Ok(crate::GetStateOutput::new(vec![], None)) })
        }
    }

    fn transport() -> Arc<dyn ExecutionClient> {
        Arc::new(NoDebugTransport)
    }

    #[test]
    fn execution_client_alone_is_valid_and_is_stored() {
        let opts = Options::builder()
            .execution_client(transport())
            .build()
            .expect("execution_client alone is valid");
        assert!(
            opts.execution_client.is_some(),
            "execution_client must be preserved, not dropped"
        );
    }

    #[test]
    fn execution_client_and_lambda_client_conflict() {
        let err = Options::builder()
            .execution_client(transport())
            .lambda_client(dummy_lambda_client())
            .build()
            .expect_err("execution_client with lambda_client is rejected");
        let msg = err.to_string();
        assert!(msg.contains("`execution_client`"), "{msg}");
        assert!(msg.contains("`lambda_client`"), "{msg}");
    }

    #[test]
    fn execution_client_and_sdk_config_conflict() {
        let err = Options::builder()
            .execution_client(transport())
            .sdk_config(dummy_sdk_config())
            .build()
            .expect_err("execution_client with sdk_config is rejected");
        let msg = err.to_string();
        assert!(msg.contains("`execution_client`"), "{msg}");
        assert!(msg.contains("`sdk_config`"), "{msg}");
    }

    #[test]
    fn all_three_transports_report_the_execution_client_conflict() {
        let err = Options::builder()
            .execution_client(transport())
            .lambda_client(dummy_lambda_client())
            .sdk_config(dummy_sdk_config())
            .build()
            .expect_err("all three transports are rejected");
        assert_eq!(
            err.message,
            "cannot set `execution_client` together with `lambda_client` or `sdk_config`: \
             the execution client replaces the Lambda transport; provide one or the other"
        );
    }

    #[test]
    fn options_debug_prints_a_placeholder_for_the_execution_client() {
        let builder = Options::builder().execution_client(transport());
        let builder_debug = format!("{builder:?}");
        assert!(
            builder_debug.contains("<custom execution client>"),
            "{builder_debug}"
        );
        let opts = builder.build().expect("valid");
        let opts_debug = format!("{opts:?}");
        assert!(
            opts_debug.contains("<custom execution client>"),
            "{opts_debug}"
        );

        let unset_builder = format!("{:?}", Options::builder());
        assert!(
            unset_builder.contains("execution_client: None"),
            "{unset_builder}"
        );
        let unset_opts = format!("{:?}", Options::builder().build().expect("valid"));
        assert!(
            unset_opts.contains("execution_client: None"),
            "{unset_opts}"
        );
    }

    /// A test factory that implements neither `Debug` nor `Clone`, and
    /// returns a fixed exclusive group.
    struct GroupFactory(Option<&'static str>);

    impl PluginFactory for GroupFactory {
        fn create_plugin(
            &self,
            _info: &crate::plugin::InvocationInfo,
        ) -> Result<Option<Box<dyn crate::plugin::Plugin>>, crate::BoxError> {
            Ok(None)
        }

        fn exclusive_group(&self) -> Option<&str> {
            self.0
        }
    }

    /// A second factory type, so two registrations have distinct names.
    struct OtherFactory(Option<&'static str>);

    impl PluginFactory for OtherFactory {
        fn create_plugin(
            &self,
            _info: &crate::plugin::InvocationInfo,
        ) -> Result<Option<Box<dyn crate::plugin::Plugin>>, crate::BoxError> {
            Ok(None)
        }

        fn exclusive_group(&self) -> Option<&str> {
            self.0
        }
    }

    #[test]
    fn plugin_registers_factories_in_order() {
        let builder = Options::builder()
            .plugin(GroupFactory(None))
            .plugin(OtherFactory(None));
        let builder_debug = format!("{builder:?}");
        assert!(builder_debug.contains("plugins: 2"), "{builder_debug}");
        let opts = builder.build().expect("valid");
        let names: Vec<&str> = opts.plugins.iter().map(|(name, _)| *name).collect();
        assert_eq!(
            names,
            [
                std::any::type_name::<GroupFactory>(),
                std::any::type_name::<OtherFactory>()
            ]
        );
        let opts_debug = format!("{opts:?}");
        assert!(opts_debug.contains("plugins: 2"), "{opts_debug}");
        assert!(
            format!("{:?}", Options::default()).contains("plugins: 0"),
            "the default registers no factory"
        );
    }

    #[test]
    fn conflicting_exclusive_groups_fail_build() {
        let err = Options::builder()
            .plugin(GroupFactory(Some("view")))
            .plugin(OtherFactory(Some("view")))
            .build()
            .expect_err("same group");
        assert_eq!(
            err.message,
            format!(
                "plugin factories '{}' and '{}' are mutually exclusive in group 'view'; \
                 register only one",
                std::any::type_name::<GroupFactory>(),
                std::any::type_name::<OtherFactory>()
            )
        );
    }

    #[test]
    fn distinct_groups_and_none_build() {
        let opts = Options::builder()
            .plugin(GroupFactory(Some("a")))
            .plugin(OtherFactory(Some("b")))
            .plugin(GroupFactory(None))
            .build()
            .expect("distinct groups");
        assert_eq!(opts.plugins.len(), 3);
    }

    #[test]
    fn empty_exclusive_group_is_no_group() {
        let opts = Options::builder()
            .plugin(GroupFactory(Some("")))
            .plugin(OtherFactory(Some("")))
            .build()
            .expect("an empty group is no group");
        assert_eq!(opts.plugins.len(), 2);
    }
}