use std::sync::Arc;
use std::time::Duration;
use crate::client::ExecutionClient;
use crate::plugin::PluginFactory;
pub(crate) type PluginFactories = Vec<(&'static str, Arc<dyn PluginFactory>)>;
#[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 {}
#[derive(Clone)]
#[non_exhaustive]
pub struct Options {
pub(crate) sdk_config: Option<aws_config::SdkConfig>,
pub(crate) lambda_client: Option<aws_sdk_lambda::Client>,
pub(crate) execution_client: Option<Arc<dyn ExecutionClient>>,
pub(crate) checkpoint_delay: Option<Duration>,
pub(crate) plugins: PluginFactories,
pub(crate) plugin_child_operations_depth: u32,
}
impl Default for Options {
fn default() -> Self {
Self {
sdk_config: None,
lambda_client: None,
execution_client: None,
checkpoint_delay: None,
plugins: Vec::new(),
plugin_child_operations_depth: 0,
}
}
}
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"),
}
}
}
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 {
pub fn builder() -> OptionsBuilder {
OptionsBuilder::default()
}
}
#[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,
}
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 {
pub fn sdk_config(mut self, config: crate::SdkConfig) -> Self {
self.sdk_config = Some(config);
self
}
pub fn lambda_client(mut self, client: crate::LambdaClient) -> Self {
self.lambda_client = Some(client);
self
}
pub fn execution_client(mut self, client: Arc<dyn ExecutionClient>) -> Self {
self.execution_client = Some(client);
self
}
pub fn checkpoint_delay(mut self, delay: Duration) -> Self {
self.checkpoint_delay = Some(delay);
self
}
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
}
pub fn plugin_child_operations_depth(mut self, depth: u32) -> Self {
self.plugin_child_operations_depth = depth;
self
}
pub fn build(self) -> Result<Options, OptionsValidationError> {
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,
})
}
}
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::*;
fn dummy_sdk_config() -> aws_config::SdkConfig {
aws_config::SdkConfig::builder().build()
}
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(),
};
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)));
}
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}"
);
}
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
}
}
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);
}
}