Skip to content

Commit

Permalink
Rename and document for clarity
Browse files Browse the repository at this point in the history
Signed-off-by: Ryan Levick <[email protected]>
  • Loading branch information
rylev committed Jul 23, 2024
1 parent 53d75ad commit 23b5d12
Show file tree
Hide file tree
Showing 10 changed files with 52 additions and 36 deletions.
5 changes: 4 additions & 1 deletion crates/factor-outbound-networking/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,10 @@ impl Factor for OutboundNetworkingFactor {
.get(ctx.app_component().id())
.cloned()
.context("missing component allowed hosts")?;
let resolver = builders.get_mut::<VariablesFactor>()?.resolver().clone();
let resolver = builders
.get_mut::<VariablesFactor>()?
.expression_resolver()
.clone();
let allowed_hosts_future = async move {
let prepared = resolver.prepare().await?;
AllowedHostsConfig::parse(&hosts, &prepared)
Expand Down
2 changes: 1 addition & 1 deletion crates/factor-outbound-pg/tests/factor_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ async fn disallowed_host_fails() -> anyhow::Result<()> {
networking: OutboundNetworkingFactor,
pg: OutboundPgFactor,
};
factors.variables.add_provider_type(StaticVariables)?;
factors.variables.add_provider_resolver(StaticVariables)?;

let env = test_env();
let mut state = env.build_instance_state(factors).await?;
Expand Down
2 changes: 1 addition & 1 deletion crates/factor-outbound-redis/tests/factor_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ fn get_test_factors() -> TestFactors {
async fn no_outbound_hosts_fails() -> anyhow::Result<()> {
let mut factors = get_test_factors();

factors.variables.add_provider_type(StaticVariables)?;
factors.variables.add_provider_resolver(StaticVariables)?;

let env = TestEnvironment {
manifest: toml! {
Expand Down
48 changes: 28 additions & 20 deletions crates/factor-variables/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,33 +4,40 @@ pub mod spin_cli;
use std::sync::Arc;

use serde::{de::DeserializeOwned, Deserialize};
use spin_expressions::ProviderResolver;
use spin_expressions::ProviderResolver as ExpressionResolver;
use spin_factors::{
anyhow, ConfigureAppContext, Factor, FactorRuntimeConfig, InitContext, InstanceBuilders,
PrepareContext, RuntimeFactors, SelfInstanceBuilder,
};
use spin_world::{async_trait, v1, v2::variables};

pub use provider::MakeVariablesProvider;
pub use provider::ProviderResolver;

/// A factor for providing variables to components.
///
/// The factor is generic over the type of runtime configuration used to configure the providers.
pub struct VariablesFactor<C> {
provider_types: Vec<Box<dyn MakeVariablesProvider<RuntimeConfig = C>>>,
provider_resolvers: Vec<Box<dyn ProviderResolver<RuntimeConfig = C>>>,
}

impl<C> Default for VariablesFactor<C> {
fn default() -> Self {
Self {
provider_types: Default::default(),
provider_resolvers: Default::default(),
}
}
}

impl<C> VariablesFactor<C> {
pub fn add_provider_type<T: MakeVariablesProvider<RuntimeConfig = C>>(
/// Adds a provider resolver to the factor.
///
/// Each added provider will be called in order with the runtime configuration. This order
/// will be the order in which the providers are called to resolve variables.
pub fn add_provider_resolver<T: ProviderResolver<RuntimeConfig = C>>(
&mut self,
provider_type: T,
) -> anyhow::Result<()> {
self.provider_types.push(Box::new(provider_type) as _);
self.provider_resolvers.push(Box::new(provider_type));
Ok(())
}
}
Expand All @@ -51,28 +58,28 @@ impl<C: DeserializeOwned + 'static> Factor for VariablesFactor<C> {
mut ctx: ConfigureAppContext<T, Self>,
) -> anyhow::Result<Self::AppState> {
let app = ctx.app();
let mut resolver =
ProviderResolver::new(app.variables().map(|(key, val)| (key.clone(), val.clone())))?;
let mut expression_resolver =
ExpressionResolver::new(app.variables().map(|(key, val)| (key.clone(), val.clone())))?;

for component in app.components() {
resolver.add_component_variables(
expression_resolver.add_component_variables(
component.id(),
component.config().map(|(k, v)| (k.into(), v.into())),
)?;
}

if let Some(runtime_config) = ctx.take_runtime_config() {
for config in runtime_config.provider_configs {
for make_provider in self.provider_types.iter() {
if let Some(provider) = make_provider.make_provider(&config)? {
resolver.add_provider(provider);
for provider_resolver in self.provider_resolvers.iter() {
if let Some(provider) = provider_resolver.resolve_provider(&config)? {
expression_resolver.add_provider(provider);
}
}
}
}

Ok(AppState {
resolver: Arc::new(resolver),
expression_resolver: Arc::new(expression_resolver),
})
}

Expand All @@ -82,14 +89,15 @@ impl<C: DeserializeOwned + 'static> Factor for VariablesFactor<C> {
_builders: &mut InstanceBuilders<T>,
) -> anyhow::Result<InstanceState> {
let component_id = ctx.app_component().id().to_string();
let resolver = ctx.app_state().resolver.clone();
let expression_resolver = ctx.app_state().expression_resolver.clone();
Ok(InstanceState {
component_id,
resolver,
expression_resolver,
})
}
}

/// The runtime configuration for the variables factor.
#[derive(Deserialize)]
#[serde(transparent)]
pub struct RuntimeConfig<C> {
Expand All @@ -101,17 +109,17 @@ impl<C: DeserializeOwned> FactorRuntimeConfig for RuntimeConfig<C> {
}

pub struct AppState {
resolver: Arc<ProviderResolver>,
expression_resolver: Arc<ExpressionResolver>,
}

pub struct InstanceState {
component_id: String,
resolver: Arc<ProviderResolver>,
expression_resolver: Arc<ExpressionResolver>,
}

impl InstanceState {
pub fn resolver(&self) -> &Arc<ProviderResolver> {
&self.resolver
pub fn expression_resolver(&self) -> &Arc<ExpressionResolver> {
&self.expression_resolver
}
}

Expand All @@ -121,7 +129,7 @@ impl SelfInstanceBuilder for InstanceState {}
impl variables::Host for InstanceState {
async fn get(&mut self, key: String) -> Result<String, variables::Error> {
let key = spin_expressions::Key::new(&key).map_err(expressions_to_variables_err)?;
self.resolver
self.expression_resolver
.resolve(&self.component_id, key)
.await
.map_err(expressions_to_variables_err)
Expand Down
4 changes: 2 additions & 2 deletions crates/factor-variables/src/provider.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,14 @@ use spin_expressions::Provider;
use spin_factors::anyhow;

/// A trait for converting a runtime configuration into a variables provider.
pub trait MakeVariablesProvider: 'static {
pub trait ProviderResolver: 'static {
/// Serialized configuration for the provider.
type RuntimeConfig: DeserializeOwned;

/// Create a variables provider from the given runtime configuration.
///
/// Returns `Ok(None)` if the provider is not applicable to the given configuration.
fn make_provider(
fn resolve_provider(
&self,
runtime_config: &Self::RuntimeConfig,
) -> anyhow::Result<Option<Box<dyn Provider>>>;
Expand Down
6 changes: 3 additions & 3 deletions crates/factor-variables/src/spin_cli/env.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,17 +11,17 @@ use spin_factors::anyhow::{self, Context as _};
use spin_world::async_trait;
use tracing::{instrument, Level};

use crate::MakeVariablesProvider;
use crate::ProviderResolver;

use super::RuntimeConfig;

/// Creator of a environment variables provider.
pub struct EnvVariables;

impl MakeVariablesProvider for EnvVariables {
impl ProviderResolver for EnvVariables {
type RuntimeConfig = RuntimeConfig;

fn make_provider(
fn resolve_provider(
&self,
runtime_config: &Self::RuntimeConfig,
) -> anyhow::Result<Option<Box<dyn Provider>>> {
Expand Down
3 changes: 3 additions & 0 deletions crates/factor-variables/src/spin_cli/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,12 @@ pub use statik::StaticVariables;
use serde::Deserialize;
use statik::StaticVariablesProvider;

/// The runtime configuration for the variables factor used in the Spin CLI.
#[derive(Debug, Deserialize)]
#[serde(rename_all = "snake_case", tag = "type")]
pub enum RuntimeConfig {
/// A static provider of variables.
Static(StaticVariablesProvider),
/// An environment variable provider.
Env(env::EnvVariablesConfig),
}
6 changes: 3 additions & 3 deletions crates/factor-variables/src/spin_cli/statik.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,17 @@ use serde::Deserialize;
use spin_expressions::{async_trait::async_trait, Key, Provider};
use spin_factors::anyhow;

use crate::MakeVariablesProvider;
use crate::ProviderResolver;

use super::RuntimeConfig;

/// Creator of a static variables provider.
pub struct StaticVariables;

impl MakeVariablesProvider for StaticVariables {
impl ProviderResolver for StaticVariables {
type RuntimeConfig = RuntimeConfig;

fn make_provider(
fn resolve_provider(
&self,
runtime_config: &Self::RuntimeConfig,
) -> anyhow::Result<Option<Box<dyn Provider>>> {
Expand Down
8 changes: 5 additions & 3 deletions crates/factor-variables/tests/factor_test.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use spin_factor_variables::spin_cli::{RuntimeConfig, StaticVariables};
use spin_factor_variables::spin_cli::{EnvVariables, RuntimeConfig, StaticVariables};
use spin_factor_variables::VariablesFactor;
use spin_factors::{anyhow, RuntimeFactors};
use spin_factors_test::{toml, TestEnvironment};
Expand Down Expand Up @@ -30,13 +30,15 @@ async fn static_provider_works() -> anyhow::Result<()> {
let mut factors = TestFactors {
variables: VariablesFactor::default(),
};
factors.variables.add_provider_type(StaticVariables)?;
factors.variables.add_provider_resolver(StaticVariables)?;
// The env provider will be ignored since there's no configuration for it.
factors.variables.add_provider_resolver(EnvVariables)?;

let env = test_env();
let state = env.build_instance_state(factors).await?;
let val = state
.variables
.resolver()
.expression_resolver()
.resolve("test-component", "baz".try_into().unwrap())
.await?;
assert_eq!(val, "<bar>");
Expand Down
4 changes: 2 additions & 2 deletions crates/factors/tests/smoke.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ async fn smoke_test_works() -> anyhow::Result<()> {
key_value: KeyValueFactor::new(key_value_resolver),
};

factors.variables.add_provider_type(StaticVariables)?;
factors.variables.add_provider_resolver(StaticVariables)?;

let locked = spin_loader::from_file(
"tests/smoke-app/spin.toml",
Expand All @@ -81,7 +81,7 @@ async fn smoke_test_works() -> anyhow::Result<()> {
assert_eq!(
state
.variables
.resolver()
.expression_resolver()
.resolve("smoke-app", "other".try_into().unwrap())
.await
.unwrap(),
Expand Down

0 comments on commit 23b5d12

Please sign in to comment.