Skip to main content

aws_durable_execution_sdk/
options.rs

1//! Configuration types for the durable execution runtime.
2
3use std::sync::Arc;
4use std::time::Duration;
5
6use crate::client::ExecutionClient;
7use crate::plugin::PluginFactory;
8
9/// The registered plugin factories, in registration order, each with the
10/// type name it was registered under.
11pub(crate) type PluginFactories = Vec<(&'static str, Arc<dyn PluginFactory>)>;
12
13/// Error returned when [`OptionsBuilder::build()`] detects an invalid
14/// configuration combination.
15///
16/// This error fires at construction time, never mid-execution, matching
17/// the spec's construction-time-only validation rule.
18///
19/// # Examples
20///
21/// ```no_run
22/// use aws_durable_execution_sdk::Options;
23///
24/// // Attempting to set both sdk_config and lambda_client errors at build():
25/// // let opts = Options::builder()
26/// //     .sdk_config(config)
27/// //     .lambda_client(client)
28/// //     .build(); // Err(OptionsValidationError { ... })
29/// ```
30#[derive(Debug, Clone)]
31#[non_exhaustive]
32pub struct OptionsValidationError {
33    message: String,
34}
35
36impl std::fmt::Display for OptionsValidationError {
37    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
38        write!(f, "invalid Options configuration: {}", self.message)
39    }
40}
41
42impl std::error::Error for OptionsValidationError {}
43
44/// Configuration for the durable execution runtime.
45///
46/// Use [`Options::builder()`] to construct. All settings are optional;
47/// defaults are suitable for standard Lambda deployments.
48///
49/// # Customizing the service client
50///
51/// The SDK calls the durable execution service through an
52/// `aws_sdk_lambda::Client` and relies on that client's own standard,
53/// jittered retry for transient failures. To customize transport behavior,
54/// retry policy, timeouts, endpoint, credentials, build the client (or an
55/// `aws_config::SdkConfig`) yourself and supply it via
56/// [`lambda_client`](OptionsBuilder::lambda_client) (or
57/// [`sdk_config`](OptionsBuilder::sdk_config)). The SDK uses that client's
58/// configuration unchanged, with one addition: it adds the token
59/// `aws-durable-execution-sdk-rust/<version>` to the `User-Agent` header of
60/// each of its own requests, including requests sent through a client you
61/// supply. `<version>` is the crate version.
62///
63/// To replace the transport itself, supply an
64/// [`ExecutionClient`](crate::ExecutionClient) via
65/// [`execution_client`](OptionsBuilder::execution_client). The SDK then
66/// sends both durable execution service calls through it instead of the
67/// Lambda client. [`LambdaExecutionClient::new`](crate::LambdaExecutionClient::new)
68/// builds the default transport, so a custom transport can wrap it.
69///
70/// # Examples
71///
72/// ```no_run
73/// use aws_durable_execution_sdk::Options;
74///
75/// let options = Options::builder()
76///     .build()
77///     .expect("valid default config");
78/// # drop(options);
79/// ```
80#[derive(Clone)]
81#[non_exhaustive]
82pub struct Options {
83    /// A user-built AWS SDK config used to construct the Lambda client.
84    pub(crate) sdk_config: Option<aws_config::SdkConfig>,
85    /// A pre-built Lambda client. When set, it is used directly instead of
86    /// building one from [`Self::sdk_config`].
87    pub(crate) lambda_client: Option<aws_sdk_lambda::Client>,
88    /// A caller-supplied transport. When set, it replaces the Lambda
89    /// transport for both service calls.
90    pub(crate) execution_client: Option<Arc<dyn ExecutionClient>>,
91    /// Coalescing window for checkpoint writes. `None` (the default) adds
92    /// no window: writes batch behind the single writer with a zero window.
93    pub(crate) checkpoint_delay: Option<Duration>,
94    /// The plugin factories, in registration order, each with the type
95    /// name it was registered under. Empty by default.
96    pub(crate) plugins: PluginFactories,
97    /// How many levels of finished child contexts keep their children
98    /// visible to later invocations. 0 (the default) keeps none.
99    pub(crate) plugin_child_operations_depth: u32,
100}
101
102impl Default for Options {
103    /// Creates default options suitable for standard Lambda deployments.
104    ///
105    /// # Examples
106    ///
107    /// ```
108    /// use aws_durable_execution_sdk::Options;
109    ///
110    /// let opts = Options::default();
111    /// # drop(opts);
112    /// ```
113    fn default() -> Self {
114        Self {
115            sdk_config: None,
116            lambda_client: None,
117            execution_client: None,
118            checkpoint_delay: None,
119            plugins: Vec::new(),
120            plugin_child_operations_depth: 0,
121        }
122    }
123}
124
125/// The `Debug` text of an optional transport: `None`, or a placeholder,
126/// because [`ExecutionClient`] does not require `Debug`.
127struct ExecutionClientDebug<'a>(&'a Option<Arc<dyn ExecutionClient>>);
128
129impl std::fmt::Debug for ExecutionClientDebug<'_> {
130    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
131        match self.0 {
132            Some(_) => f.write_str("<custom execution client>"),
133            None => f.write_str("None"),
134        }
135    }
136}
137
138// Written by hand: `Arc<dyn ExecutionClient>` and `Arc<dyn PluginFactory>`
139// do not implement `Debug`.
140impl std::fmt::Debug for Options {
141    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
142        f.debug_struct("Options")
143            .field("sdk_config", &self.sdk_config)
144            .field("lambda_client", &self.lambda_client)
145            .field(
146                "execution_client",
147                &ExecutionClientDebug(&self.execution_client),
148            )
149            .field("checkpoint_delay", &self.checkpoint_delay)
150            .field("plugins", &self.plugins.len())
151            .field(
152                "plugin_child_operations_depth",
153                &self.plugin_child_operations_depth,
154            )
155            .finish()
156    }
157}
158
159impl Options {
160    /// Creates a new [`OptionsBuilder`].
161    ///
162    /// # Examples
163    ///
164    /// ```
165    /// use aws_durable_execution_sdk::Options;
166    ///
167    /// let builder = Options::builder();
168    /// let opts = builder.build().expect("valid config");
169    /// # drop(opts);
170    /// ```
171    pub fn builder() -> OptionsBuilder {
172        OptionsBuilder::default()
173    }
174}
175
176/// Builder for [`Options`].
177///
178/// Follows the Rust API Guidelines C-BUILDER pattern. All methods consume
179/// and return `self` for chaining.
180///
181/// # Examples
182///
183/// ```no_run
184/// use aws_durable_execution_sdk::{Options, OptionsBuilder};
185///
186/// let options = Options::builder()
187///     .build()
188///     .expect("valid config");
189/// # drop(options);
190/// ```
191#[derive(Default)]
192#[must_use = "builders do nothing unless .build() is called"]
193#[non_exhaustive]
194pub struct OptionsBuilder {
195    sdk_config: Option<aws_config::SdkConfig>,
196    lambda_client: Option<aws_sdk_lambda::Client>,
197    execution_client: Option<Arc<dyn ExecutionClient>>,
198    checkpoint_delay: Option<Duration>,
199    plugins: PluginFactories,
200    plugin_child_operations_depth: u32,
201}
202
203// Written by hand: `Arc<dyn ExecutionClient>` and `Arc<dyn PluginFactory>`
204// do not implement `Debug`.
205impl std::fmt::Debug for OptionsBuilder {
206    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
207        f.debug_struct("OptionsBuilder")
208            .field("sdk_config", &self.sdk_config)
209            .field("lambda_client", &self.lambda_client)
210            .field(
211                "execution_client",
212                &ExecutionClientDebug(&self.execution_client),
213            )
214            .field("checkpoint_delay", &self.checkpoint_delay)
215            .field("plugins", &self.plugins.len())
216            .field(
217                "plugin_child_operations_depth",
218                &self.plugin_child_operations_depth,
219            )
220            .finish()
221    }
222}
223
224impl OptionsBuilder {
225    /// Sets the AWS SDK configuration for building service clients.
226    ///
227    /// Use this to provide custom endpoint configuration, credentials, or
228    /// HTTP client settings.
229    ///
230    /// By default, when neither this nor
231    /// [`lambda_client`](Self::lambda_client) is set, the SDK loads the
232    /// ambient environment configuration
233    /// (`aws_config::load_defaults`) and builds a client from it. That
234    /// default client uses a 5 s connect timeout, a 50 s read timeout and
235    /// a 55 s attempt timeout. A client built from a config supplied here
236    /// keeps the config's own timeouts, and the SDK adds none.
237    ///
238    /// The SDK adds the token `aws-durable-execution-sdk-rust/<version>` to
239    /// the `User-Agent` header of each of its own requests sent through the
240    /// client it builds from this config, where `<version>` is the crate
241    /// version.
242    ///
243    /// The parameter type is re-exported at the crate root as
244    /// [`SdkConfig`](crate::SdkConfig), so callers can name it without
245    /// depending on `aws-config` directly.
246    ///
247    /// # Examples
248    ///
249    /// ```no_run
250    /// use aws_durable_execution_sdk::Options;
251    ///
252    /// # async fn example() {
253    /// let sdk_config = aws_config::load_defaults(aws_config::BehaviorVersion::latest()).await;
254    /// let opts = Options::builder()
255    ///     .sdk_config(sdk_config)
256    ///     .build()
257    ///     .expect("valid config");
258    /// # drop(opts);
259    /// # }
260    /// ```
261    pub fn sdk_config(mut self, config: crate::SdkConfig) -> Self {
262        self.sdk_config = Some(config);
263        self
264    }
265
266    /// Sets a pre-built Lambda client.
267    ///
268    /// When provided, the SDK uses this client instead of building one
269    /// from the SDK config. By default, when neither this nor
270    /// [`sdk_config`](Self::sdk_config) is set, the SDK builds a client
271    /// from the ambient environment configuration
272    /// (`aws_config::load_defaults`), with a 5 s connect timeout, a 50 s
273    /// read timeout and a 55 s attempt timeout. A client supplied here
274    /// keeps its own timeouts, and the SDK adds none.
275    ///
276    /// This is the supported path for customizing how the SDK talks to the
277    /// durable execution service: configure retry, timeouts, endpoint, or
278    /// credentials on the client (or use
279    /// [`sdk_config`](Self::sdk_config)) and the SDK uses its
280    /// configuration unchanged. The SDK adds the token
281    /// `aws-durable-execution-sdk-rust/<version>` to the `User-Agent` header
282    /// of each of its own requests sent through this client, where
283    /// `<version>` is the crate version. It adds the token to each request,
284    /// so the client itself is not changed.
285    /// Transient-failure retry of the service calls is the client's own
286    /// standard retry; the SDK adds no retry layer of its own.
287    ///
288    /// The parameter type is re-exported at the crate root as
289    /// [`LambdaClient`](crate::LambdaClient), so callers can name it without
290    /// depending on `aws-sdk-lambda` directly.
291    ///
292    /// # Examples
293    ///
294    /// The client and its configuration type are both reachable through the
295    /// crate root, so this compiles with no direct `aws-config` or
296    /// `aws-sdk-lambda` dependency:
297    ///
298    /// ```no_run
299    /// use aws_durable_execution_sdk::{LambdaClient, Options, SdkConfig};
300    ///
301    /// let config = SdkConfig::builder().build();
302    /// let client = LambdaClient::new(&config);
303    /// let opts = Options::builder()
304    ///     .lambda_client(client)
305    ///     .build()
306    ///     .expect("valid config");
307    /// # drop(opts);
308    /// ```
309    pub fn lambda_client(mut self, client: crate::LambdaClient) -> Self {
310        self.lambda_client = Some(client);
311        self
312    }
313
314    /// Sets the transport for the two durable execution service calls.
315    ///
316    /// The SDK sends every checkpoint and every state read through
317    /// `client` instead of the Lambda transport. See the
318    /// [`ExecutionClient`](crate::ExecutionClient) contract for what a
319    /// transport returns and how each error scope ends the invocation or
320    /// the execution. [`LambdaExecutionClient::new`](crate::LambdaExecutionClient::new)
321    /// builds the default transport, so a custom transport can wrap it.
322    ///
323    /// The transport replaces the Lambda client, so it cannot be set
324    /// together with [`lambda_client`](Self::lambda_client) or
325    /// [`sdk_config`](Self::sdk_config): [`build`](Self::build) rejects
326    /// that combination.
327    ///
328    /// The transport owns its own request headers. The SDK adds its
329    /// `User-Agent` token only to requests that
330    /// [`LambdaExecutionClient`](crate::LambdaExecutionClient) sends, so a
331    /// transport that wraps it keeps the token.
332    ///
333    /// # Examples
334    ///
335    /// ```no_run
336    /// use std::sync::Arc;
337    /// use aws_durable_execution_sdk::{LambdaClient, LambdaExecutionClient, Options, SdkConfig};
338    ///
339    /// let client = LambdaClient::new(&SdkConfig::builder().build());
340    /// let opts = Options::builder()
341    ///     .execution_client(Arc::new(LambdaExecutionClient::new(client)))
342    ///     .build()
343    ///     .expect("valid config");
344    /// # drop(opts);
345    /// ```
346    pub fn execution_client(mut self, client: Arc<dyn ExecutionClient>) -> Self {
347        self.execution_client = Some(client);
348        self
349    }
350
351    /// Defers checkpoint writes for up to `delay` so that checkpoints from
352    /// concurrently running operations coalesce into fewer service calls.
353    ///
354    /// With a delay configured, a checkpoint written while other operations
355    /// are also checkpointing joins a shared batch; the batch is sent as a
356    /// single `CheckpointDurableExecution` call when the window elapses.
357    /// For high-fan-out executions (large `map`/`parallel` batches) this
358    /// trades up to `delay` of extra latency per checkpoint for
359    /// substantially fewer API calls. A coalesced batch is split to respect
360    /// the service's per-request limits (operation count and payload size),
361    /// preserving write order across the splits. Every operation still
362    /// awaits its own checkpoint before proceeding, so ordering and replay
363    /// semantics are unchanged.
364    ///
365    /// # Flush contract
366    ///
367    /// A checkpoint that must land before the execution can make progress
368    /// is never held back by the window. Pending checkpoints are flushed
369    /// unconditionally at these points:
370    ///
371    /// - **Suspension**: before an invocation reports `PENDING` to the
372    ///   service, every buffered checkpoint is written, so no recorded
373    ///   progress is lost across the suspend/resume boundary.
374    /// - **Execution completion**: before an invocation reports its
375    ///   terminal `SUCCEEDED`/`FAILED` envelope, the buffer is drained.
376    /// - **Callback creation**: creating a callback flushes immediately,
377    ///   because the service assigns the callback ID in the checkpoint
378    ///   response and the handler needs that ID right away.
379    ///
380    /// When unset (the default), no window is added, and batching never
381    /// holds a write back: checkpoint writes go through a single ordered
382    /// writer, which sends a write as soon as no earlier request is in
383    /// flight, and writes that wait for the same request share it, as in
384    /// the JavaScript SDK.
385    ///
386    /// # Examples
387    ///
388    /// ```
389    /// use aws_durable_execution_sdk::Options;
390    /// use std::time::Duration;
391    ///
392    /// let opts = Options::builder()
393    ///     .checkpoint_delay(Duration::from_millis(20))
394    ///     .build()
395    ///     .expect("valid config");
396    /// # drop(opts);
397    /// ```
398    pub fn checkpoint_delay(mut self, delay: Duration) -> Self {
399        self.checkpoint_delay = Some(delay);
400        self
401    }
402
403    /// Registers a plugin factory.
404    ///
405    /// Each invocation calls every registered factory once, in
406    /// registration order, and the plugin a factory returns observes that
407    /// one invocation. The [`plugin`](crate::plugin) module describes the
408    /// factory, the plugin and its hooks.
409    ///
410    /// [`build`](Self::build) rejects two factories whose
411    /// [`exclusive_group`](PluginFactory::exclusive_group) returns the same
412    /// non-empty group.
413    ///
414    /// # Examples
415    ///
416    /// ```
417    /// use aws_durable_execution_sdk::plugin::{InvocationInfo, Plugin, PluginFactory};
418    /// use aws_durable_execution_sdk::{BoxError, Options};
419    ///
420    /// struct Quiet;
421    /// impl Plugin for Quiet {}
422    ///
423    /// struct QuietFactory;
424    /// impl PluginFactory for QuietFactory {
425    ///     fn create_plugin(&self, _info: &InvocationInfo) -> Result<Option<Box<dyn Plugin>>, BoxError> {
426    ///         Ok(Some(Box::new(Quiet)))
427    ///     }
428    /// }
429    ///
430    /// let opts = Options::builder()
431    ///     .plugin(QuietFactory)
432    ///     .build()
433    ///     .expect("valid config");
434    /// # drop(opts);
435    /// ```
436    pub fn plugin<F: PluginFactory>(mut self, factory: F) -> Self {
437        self.plugins.push((
438            std::any::type_name::<F>(),
439            Arc::new(factory) as Arc<dyn PluginFactory>,
440        ));
441        self
442    }
443
444    /// Keeps the children of finished child contexts visible to plugins
445    /// in later invocations, up to `depth` levels. The default is 0.
446    ///
447    /// When a child context, a `map` or a `parallel` finishes, the service
448    /// stops sending its child operations to later invocations, so
449    /// [`InvocationInfo::operations`](crate::plugin::InvocationInfo::operations)
450    /// holds only the operations above it. Within the depth, the context's
451    /// terminal record carries `ReplayChildren`, and the service keeps
452    /// sending its children.
453    ///
454    /// The depth counts context levels below the root. `1` keeps the
455    /// children of top-level contexts: the operations of a top-level child
456    /// context, and the items and branches of a top-level `map` or
457    /// `parallel`. `2` also keeps their children, such as the operations
458    /// inside each item. `u32::MAX` keeps the whole tree, and `0` changes
459    /// no record. A map item or parallel branch with
460    /// [`NestingMode::Flat`](crate::builders::map_parallel::NestingMode::Flat) adds no level. The
461    /// setting covers succeeded and failed contexts alike, and it also
462    /// flags the record of a `wait_for_callback`, the success of a
463    /// `try_join_all` or `join_all`, and every combinator failure. It
464    /// applies whether or not a plugin is registered.
465    ///
466    /// The cost is that a preserved context runs again on every later
467    /// replay:
468    ///
469    /// - A preserved child context, map item or parallel branch re-runs
470    ///   its body on each later replay, and its children return recorded
471    ///   results.
472    /// - A preserved `map` or `parallel` re-runs its items on each later
473    ///   replay, and their children return recorded results.
474    /// - A preserved `wait_for_callback` re-runs its body the same way.
475    /// - A preserved `try_join_all` or `join_all` drives its inputs again
476    ///   on each later replay, and each input replays its own record.
477    ///
478    /// A record whose result is above the size limit does not change: it
479    /// already carries `ReplayChildren`.
480    ///
481    /// # Examples
482    ///
483    /// ```
484    /// use aws_durable_execution_sdk::Options;
485    ///
486    /// let opts = Options::builder()
487    ///     .plugin_child_operations_depth(1)
488    ///     .build()
489    ///     .expect("valid config");
490    /// # drop(opts);
491    /// ```
492    pub fn plugin_child_operations_depth(mut self, depth: u32) -> Self {
493        self.plugin_child_operations_depth = depth;
494        self
495    }
496
497    /// Builds the [`Options`] from the configured values.
498    ///
499    /// # Errors
500    ///
501    /// Returns an error if the configuration contains invalid combinations:
502    /// - Setting `execution_client` together with `lambda_client` or
503    ///   `sdk_config` is invalid (the execution client replaces the Lambda
504    ///   transport: provide one or the other). This check runs first.
505    /// - Setting both `sdk_config` and `lambda_client` is invalid (the
506    ///   client supersedes the config: provide one or the other).
507    /// - Registering two plugin factories whose
508    ///   [`exclusive_group`](PluginFactory::exclusive_group) returns the
509    ///   same non-empty group is invalid. The message names both factory
510    ///   types, the earlier registration first, and the group. `None` and
511    ///   `Some("")` are no group.
512    ///
513    /// # Examples
514    ///
515    /// ```
516    /// use aws_durable_execution_sdk::Options;
517    ///
518    /// let opts = Options::builder().build();
519    /// assert!(opts.is_ok());
520    /// # drop(opts);
521    /// ```
522    pub fn build(self) -> Result<Options, OptionsValidationError> {
523        // Construction-time-only validation: invalid combos error here,
524        // not mid-execution. Matches the spec's "construction-time only" rule.
525        if self.execution_client.is_some()
526            && (self.lambda_client.is_some() || self.sdk_config.is_some())
527        {
528            return Err(OptionsValidationError {
529                message: "cannot set `execution_client` together with `lambda_client` or \
530                          `sdk_config`: the execution client replaces the Lambda transport; \
531                          provide one or the other"
532                    .to_owned(),
533            });
534        }
535        if self.sdk_config.is_some() && self.lambda_client.is_some() {
536            return Err(OptionsValidationError {
537                message: "cannot set both `sdk_config` and `lambda_client`: \
538                          the pre-built client supersedes the config; provide one or the other"
539                    .to_owned(),
540            });
541        }
542
543        check_exclusive_groups(&self.plugins)?;
544
545        Ok(Options {
546            sdk_config: self.sdk_config,
547            lambda_client: self.lambda_client,
548            execution_client: self.execution_client,
549            checkpoint_delay: self.checkpoint_delay,
550            plugins: self.plugins,
551            plugin_child_operations_depth: self.plugin_child_operations_depth,
552        })
553    }
554}
555
556/// Rejects two factories in the same non-empty exclusive group.
557///
558/// Each factory's group is read once, in registration order. A group seen
559/// a second time names the factory that claimed it first, so the message
560/// lists the earlier registration first.
561fn check_exclusive_groups(plugins: &PluginFactories) -> Result<(), OptionsValidationError> {
562    let mut claimed: Vec<(&str, &'static str)> = Vec::new();
563    for (type_name, factory) in plugins {
564        let Some(group) = factory.exclusive_group().filter(|g| !g.is_empty()) else {
565            continue;
566        };
567        if let Some((_, first)) = claimed.iter().find(|(g, _)| *g == group) {
568            return Err(OptionsValidationError {
569                message: format!(
570                    "plugin factories '{first}' and '{type_name}' are mutually exclusive in \
571                     group '{group}'; register only one"
572                ),
573            });
574        }
575        claimed.push((group, type_name));
576    }
577    Ok(())
578}
579
580#[cfg(test)]
581mod tests {
582    use super::*;
583
584    /// An offline `SdkConfig` (no network, no credentials probe).
585    fn dummy_sdk_config() -> aws_config::SdkConfig {
586        aws_config::SdkConfig::builder().build()
587    }
588
589    /// An offline Lambda client (built from a static config; never calls AWS).
590    fn dummy_lambda_client() -> aws_sdk_lambda::Client {
591        let conf = aws_sdk_lambda::config::Config::builder()
592            .behavior_version(aws_sdk_lambda::config::BehaviorVersion::latest())
593            .region(aws_sdk_lambda::config::Region::new("us-east-1"))
594            .build();
595        aws_sdk_lambda::Client::from_conf(conf)
596    }
597
598    #[test]
599    fn plugin_child_operations_depth_defaults_to_zero() {
600        assert_eq!(Options::default().plugin_child_operations_depth, 0);
601        let built = Options::builder().build().expect("valid config");
602        assert_eq!(built.plugin_child_operations_depth, 0);
603        let builder = Options::builder().plugin_child_operations_depth(3);
604        let builder_debug = format!("{builder:?}");
605        let options = builder.build().expect("valid config");
606        assert_eq!(options.plugin_child_operations_depth, 3);
607        assert!(
608            builder_debug.contains("plugin_child_operations_depth: 3"),
609            "{builder_debug}"
610        );
611        let options_debug = format!("{options:?}");
612        assert!(
613            options_debug.contains("plugin_child_operations_depth: 3"),
614            "{options_debug}"
615        );
616    }
617
618    #[test]
619    fn default_options_build_succeeds() {
620        let result = Options::builder().build();
621        assert!(result.is_ok());
622    }
623
624    #[test]
625    fn sdk_config_and_lambda_client_conflict() {
626        let result = Options::builder()
627            .sdk_config(dummy_sdk_config())
628            .lambda_client(dummy_lambda_client())
629            .build();
630        assert_eq!(
631            result.unwrap_err().to_string(),
632            "invalid Options configuration: cannot set both `sdk_config` and `lambda_client`: \
633             the pre-built client supersedes the config; provide one or the other"
634        );
635    }
636
637    #[test]
638    fn sdk_config_alone_is_valid_and_is_stored() {
639        let opts = Options::builder().sdk_config(dummy_sdk_config()).build();
640        assert!(opts.is_ok());
641        assert!(
642            opts.expect("valid").sdk_config.is_some(),
643            "sdk_config must be preserved, not dropped"
644        );
645    }
646
647    #[test]
648    fn lambda_client_alone_is_valid_and_is_stored() {
649        let opts = Options::builder()
650            .lambda_client(dummy_lambda_client())
651            .build();
652        assert!(opts.is_ok());
653        assert!(
654            opts.expect("valid").lambda_client.is_some(),
655            "lambda_client must be preserved, not dropped"
656        );
657    }
658
659    #[test]
660    fn validation_error_implements_std_error() {
661        let err = OptionsValidationError {
662            message: "test".to_owned(),
663        };
664        // Verify it implements std::error::Error via trait object coercion.
665        let _: &dyn std::error::Error = &err;
666        assert!(err.to_string().contains("test"));
667    }
668
669    #[test]
670    fn default_options_carry_no_execution_tuning() {
671        let opts = Options::builder().build().expect("valid");
672        assert!(
673            opts.checkpoint_delay.is_none(),
674            "unset checkpoint delay must stay None so batches flush at once"
675        );
676    }
677
678    #[test]
679    fn checkpoint_delay_is_stored() {
680        let opts = Options::builder()
681            .checkpoint_delay(Duration::from_millis(20))
682            .build()
683            .expect("valid");
684        assert_eq!(opts.checkpoint_delay, Some(Duration::from_millis(20)));
685    }
686
687    /// A transport that implements no `Debug`, as a caller's may not.
688    struct NoDebugTransport;
689
690    impl ExecutionClient for NoDebugTransport {
691        fn checkpoint(
692            &self,
693            _execution_arn: &str,
694            _checkpoint_token: &str,
695            _updates: Vec<crate::lambda_types::OperationUpdate>,
696        ) -> std::pin::Pin<
697            Box<
698                dyn Future<Output = Result<crate::CheckpointOutput, crate::ExecutionClientError>>
699                    + Send
700                    + '_,
701            >,
702        > {
703            Box::pin(async {
704                Ok(crate::CheckpointOutput::new(
705                    Some("t".to_owned()),
706                    vec![],
707                    None,
708                ))
709            })
710        }
711
712        fn get_state(
713            &self,
714            _execution_arn: &str,
715            _checkpoint_token: &str,
716            _marker: Option<&str>,
717        ) -> std::pin::Pin<
718            Box<
719                dyn Future<Output = Result<crate::GetStateOutput, crate::ExecutionClientError>>
720                    + Send
721                    + '_,
722            >,
723        > {
724            Box::pin(async { Ok(crate::GetStateOutput::new(vec![], None)) })
725        }
726    }
727
728    fn transport() -> Arc<dyn ExecutionClient> {
729        Arc::new(NoDebugTransport)
730    }
731
732    #[test]
733    fn execution_client_alone_is_valid_and_is_stored() {
734        let opts = Options::builder()
735            .execution_client(transport())
736            .build()
737            .expect("execution_client alone is valid");
738        assert!(
739            opts.execution_client.is_some(),
740            "execution_client must be preserved, not dropped"
741        );
742    }
743
744    #[test]
745    fn execution_client_and_lambda_client_conflict() {
746        let err = Options::builder()
747            .execution_client(transport())
748            .lambda_client(dummy_lambda_client())
749            .build()
750            .expect_err("execution_client with lambda_client is rejected");
751        let msg = err.to_string();
752        assert!(msg.contains("`execution_client`"), "{msg}");
753        assert!(msg.contains("`lambda_client`"), "{msg}");
754    }
755
756    #[test]
757    fn execution_client_and_sdk_config_conflict() {
758        let err = Options::builder()
759            .execution_client(transport())
760            .sdk_config(dummy_sdk_config())
761            .build()
762            .expect_err("execution_client with sdk_config is rejected");
763        let msg = err.to_string();
764        assert!(msg.contains("`execution_client`"), "{msg}");
765        assert!(msg.contains("`sdk_config`"), "{msg}");
766    }
767
768    #[test]
769    fn all_three_transports_report_the_execution_client_conflict() {
770        let err = Options::builder()
771            .execution_client(transport())
772            .lambda_client(dummy_lambda_client())
773            .sdk_config(dummy_sdk_config())
774            .build()
775            .expect_err("all three transports are rejected");
776        assert_eq!(
777            err.message,
778            "cannot set `execution_client` together with `lambda_client` or `sdk_config`: \
779             the execution client replaces the Lambda transport; provide one or the other"
780        );
781    }
782
783    #[test]
784    fn options_debug_prints_a_placeholder_for_the_execution_client() {
785        let builder = Options::builder().execution_client(transport());
786        let builder_debug = format!("{builder:?}");
787        assert!(
788            builder_debug.contains("<custom execution client>"),
789            "{builder_debug}"
790        );
791        let opts = builder.build().expect("valid");
792        let opts_debug = format!("{opts:?}");
793        assert!(
794            opts_debug.contains("<custom execution client>"),
795            "{opts_debug}"
796        );
797
798        let unset_builder = format!("{:?}", Options::builder());
799        assert!(
800            unset_builder.contains("execution_client: None"),
801            "{unset_builder}"
802        );
803        let unset_opts = format!("{:?}", Options::builder().build().expect("valid"));
804        assert!(
805            unset_opts.contains("execution_client: None"),
806            "{unset_opts}"
807        );
808    }
809
810    /// A test factory that implements neither `Debug` nor `Clone`, and
811    /// returns a fixed exclusive group.
812    struct GroupFactory(Option<&'static str>);
813
814    impl PluginFactory for GroupFactory {
815        fn create_plugin(
816            &self,
817            _info: &crate::plugin::InvocationInfo,
818        ) -> Result<Option<Box<dyn crate::plugin::Plugin>>, crate::BoxError> {
819            Ok(None)
820        }
821
822        fn exclusive_group(&self) -> Option<&str> {
823            self.0
824        }
825    }
826
827    /// A second factory type, so two registrations have distinct names.
828    struct OtherFactory(Option<&'static str>);
829
830    impl PluginFactory for OtherFactory {
831        fn create_plugin(
832            &self,
833            _info: &crate::plugin::InvocationInfo,
834        ) -> Result<Option<Box<dyn crate::plugin::Plugin>>, crate::BoxError> {
835            Ok(None)
836        }
837
838        fn exclusive_group(&self) -> Option<&str> {
839            self.0
840        }
841    }
842
843    #[test]
844    fn plugin_registers_factories_in_order() {
845        let builder = Options::builder()
846            .plugin(GroupFactory(None))
847            .plugin(OtherFactory(None));
848        let builder_debug = format!("{builder:?}");
849        assert!(builder_debug.contains("plugins: 2"), "{builder_debug}");
850        let opts = builder.build().expect("valid");
851        let names: Vec<&str> = opts.plugins.iter().map(|(name, _)| *name).collect();
852        assert_eq!(
853            names,
854            [
855                std::any::type_name::<GroupFactory>(),
856                std::any::type_name::<OtherFactory>()
857            ]
858        );
859        let opts_debug = format!("{opts:?}");
860        assert!(opts_debug.contains("plugins: 2"), "{opts_debug}");
861        assert!(
862            format!("{:?}", Options::default()).contains("plugins: 0"),
863            "the default registers no factory"
864        );
865    }
866
867    #[test]
868    fn conflicting_exclusive_groups_fail_build() {
869        let err = Options::builder()
870            .plugin(GroupFactory(Some("view")))
871            .plugin(OtherFactory(Some("view")))
872            .build()
873            .expect_err("same group");
874        assert_eq!(
875            err.message,
876            format!(
877                "plugin factories '{}' and '{}' are mutually exclusive in group 'view'; \
878                 register only one",
879                std::any::type_name::<GroupFactory>(),
880                std::any::type_name::<OtherFactory>()
881            )
882        );
883    }
884
885    #[test]
886    fn distinct_groups_and_none_build() {
887        let opts = Options::builder()
888            .plugin(GroupFactory(Some("a")))
889            .plugin(OtherFactory(Some("b")))
890            .plugin(GroupFactory(None))
891            .build()
892            .expect("distinct groups");
893        assert_eq!(opts.plugins.len(), 3);
894    }
895
896    #[test]
897    fn empty_exclusive_group_is_no_group() {
898        let opts = Options::builder()
899            .plugin(GroupFactory(Some("")))
900            .plugin(OtherFactory(Some("")))
901            .build()
902            .expect("an empty group is no group");
903        assert_eq!(opts.plugins.len(), 2);
904    }
905}