Skip to content

Commit 5a55eb1

Browse files
committed
use hooks
Signed-off-by: Aminu 'Seun Joshua <[email protected]>
1 parent 2eab554 commit 5a55eb1

File tree

11 files changed

+362
-696
lines changed

11 files changed

+362
-696
lines changed

Cargo.lock

Lines changed: 4 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Cargo.toml

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -65,12 +65,13 @@ spin-oci = { path = "crates/oci" }
6565
spin-plugins = { path = "crates/plugins" }
6666
spin-runtime-factors = { path = "crates/runtime-factors" }
6767
spin-telemetry = { path = "crates/telemetry", features = [
68-
"tracing-log-compat",
68+
"tracing-log-compat",
6969
] }
7070
spin-templates = { path = "crates/templates" }
7171
spin-trigger = { path = "crates/trigger" }
7272
spin-trigger-http = { path = "crates/trigger-http" }
7373
spin-trigger-redis = { path = "crates/trigger-redis" }
74+
spin-variables = { path = "crates/variables" }
7475
terminal = { path = "crates/terminal" }
7576

7677
[target.'cfg(target_os = "linux")'.dependencies]
@@ -96,10 +97,10 @@ testing-framework = { path = "tests/testing-framework" }
9697
[build-dependencies]
9798
cargo-target-dep = { git = "https://github.com/fermyon/cargo-target-dep", rev = "482f269eceb7b1a7e8fc618bf8c082dd24979cf1" }
9899
vergen = { version = "^8.2.1", default-features = false, features = [
99-
"build",
100-
"git",
101-
"gitcl",
102-
"cargo",
100+
"build",
101+
"git",
102+
"gitcl",
103+
"cargo",
103104
] }
104105

105106
[features]
@@ -112,10 +113,10 @@ llm-cublas = ["llm", "spin-runtime-factors/llm-cublas"]
112113

113114
[workspace]
114115
members = [
115-
"crates/*",
116-
"tests/conformance-tests",
117-
"tests/runtime-tests",
118-
"tests/testing-framework",
116+
"crates/*",
117+
"tests/conformance-tests",
118+
"tests/runtime-tests",
119+
"tests/testing-framework",
119120
]
120121

121122
[workspace.dependencies]

crates/loader/src/local.rs

Lines changed: 0 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,6 @@ use spin_locked_app::{
1111
LockedComponentSource, LockedTrigger,
1212
},
1313
values::{ValuesMap, ValuesMapBuilder},
14-
Variable,
1514
};
1615
use spin_manifest::schema::v2::{self, AppManifest, KebabId, WasiFilesMount};
1716
use spin_outbound_networking_config::allowed_hosts::{AllowedHostConfig, AllowedHostsConfig};
@@ -141,21 +140,6 @@ impl LocalLoader {
141140
})
142141
}
143142

144-
fn env_checker((key, val): (String, Variable)) -> anyhow::Result<(String, Variable)> {
145-
if val.default.is_none() {
146-
if std::env::var(env_key(None, key.as_ref())).is_err() {
147-
Err(anyhow::anyhow!(
148-
"Variable data not provided for {}",
149-
quoted_path(key)
150-
))
151-
} else {
152-
Ok((key, val))
153-
}
154-
} else {
155-
Ok((key, val))
156-
}
157-
}
158-
159143
// Load the given component into a LockedComponent, ready for execution.
160144
async fn load_component(
161145
&self,

crates/runtime-config/src/variables.rs

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,19 @@
1+
//! The runtime configuration for the variables factor used in the Spin CLI.
2+
3+
mod azure_key_vault;
4+
mod env;
5+
mod statik;
6+
mod vault;
7+
8+
use std::path::PathBuf;
9+
10+
pub use azure_key_vault::*;
11+
pub use env::*;
12+
use spin_common::{env::env_key, ui::quoted_path};
13+
use spin_locked_app::Variable;
14+
pub use statik::*;
15+
pub use vault::*;
16+
117
use serde::Deserialize;
218
use spin_expressions::Provider;
319
use spin_factor_variables::runtime_config::RuntimeConfig;
@@ -29,6 +45,24 @@ pub fn runtime_config_from_toml(table: &impl GetTomlValue) -> anyhow::Result<Run
2945
Ok(RuntimeConfig { providers })
3046
}
3147

48+
pub fn variable_provider_config_from_toml(
49+
table: &impl GetTomlValue,
50+
) -> anyhow::Result<Vec<VariableProviderConfiguration>> {
51+
if let Some(array) = table
52+
.get("variables_provider")
53+
.or_else(|| table.get("config_provider"))
54+
{
55+
array
56+
.clone()
57+
.try_into::<Vec<VariableProviderConfiguration>>()
58+
.map_err(|e| anyhow::anyhow!("Failed to parse variable provider configuration: {}", e))
59+
} else {
60+
Ok(vec![VariableProviderConfiguration::Env(
61+
EnvVariablesConfig::default(),
62+
)])
63+
}
64+
}
65+
3266
/// A runtime configuration used in the Spin CLI for one type of variable provider.
3367
#[derive(Debug, Deserialize)]
3468
#[serde(rename_all = "snake_case", tag = "type")]
@@ -61,3 +95,38 @@ impl VariableProviderConfiguration {
6195
Ok(provider)
6296
}
6397
}
98+
99+
pub trait VariableSourcer {
100+
fn variable_env_checker(
101+
&self,
102+
key: String,
103+
val: Variable,
104+
) -> anyhow::Result<(String, Variable)>;
105+
106+
fn check(
107+
&self,
108+
key: String,
109+
mut val: Variable,
110+
dotenv_path: Option<PathBuf>,
111+
prefix: Option<String>,
112+
) -> anyhow::Result<(String, Variable)> {
113+
if val.default.is_some() {
114+
return Ok((key, val));
115+
}
116+
117+
if let Some(path) = dotenv_path {
118+
_ = std::env::set_current_dir(path);
119+
}
120+
121+
match std::env::var(env_key(prefix, &key)) {
122+
Ok(v) => {
123+
val.default = Some(v);
124+
Ok((key, val))
125+
}
126+
Err(_) => Err(anyhow::anyhow!(
127+
"Variable data not provided for {}",
128+
quoted_path(key)
129+
)),
130+
}
131+
}
132+
}

crates/runtime-factors/src/build.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,9 @@ impl RuntimeFactorsBuilder for FactorsBuilder {
7272
executor.add_hooks(InitialKvSetterHook::new(args.key_values.clone()));
7373
executor.add_hooks(SqliteDefaultStoreSummaryHook);
7474
executor.add_hooks(KeyValueDefaultStoreSummaryHook);
75+
executor.add_hooks(VariableSorterExecutorHooks::new(
76+
runtime_config.toml.clone(),
77+
));
7578

7679
let max_instance_memory = args
7780
.max_instance_memory

crates/trigger/Cargo.toml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,9 @@ spin-factor-wasi = { path = "../factor-wasi" }
3232
spin-factors = { path = "../factors" }
3333
spin-factors-executor = { path = "../factors-executor" }
3434
spin-telemetry = { path = "../telemetry" }
35+
spin-variables = { path = "../variables" }
3536
tokio = { workspace = true, features = ["fs", "rt"] }
37+
toml = { workspace = true }
3638
tracing = { workspace = true }
3739

3840
[dev-dependencies]

crates/trigger/src/cli.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ mod max_instance_memory;
44
mod sqlite_statements;
55
mod stdio;
66
mod summary;
7+
mod variables;
78

89
use std::path::PathBuf;
910
use std::{future::Future, sync::Arc};
@@ -25,6 +26,7 @@ pub use sqlite_statements::SqlStatementExecutorHook;
2526
use stdio::FollowComponents;
2627
pub use stdio::StdioLoggingExecutorHooks;
2728
pub use summary::{KeyValueDefaultStoreSummaryHook, SqliteDefaultStoreSummaryHook};
29+
pub use variables::VariableSorterExecutorHooks;
2830

2931
pub const APP_LOG_DIR: &str = "APP_LOG_DIR";
3032
pub const SPIN_TRUNCATE_LOGS: &str = "SPIN_TRUNCATE_LOGS";

crates/trigger/src/cli/variables.rs

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
use spin_core::async_trait;
2+
use spin_factors::RuntimeFactors;
3+
use spin_factors_executor::ExecutorHooks;
4+
use spin_variables::{VariableProviderConfiguration, VariableSourcer};
5+
6+
/// Implements TriggerHooks, sorting required variables
7+
pub struct VariableSorterExecutorHooks {
8+
table: toml::Table,
9+
}
10+
11+
impl VariableSorterExecutorHooks {
12+
pub fn new(table: toml::Table) -> Self {
13+
Self { table }
14+
}
15+
}
16+
17+
#[async_trait]
18+
impl<F: RuntimeFactors, U> ExecutorHooks<F, U> for VariableSorterExecutorHooks {
19+
async fn configure_app(
20+
&self,
21+
configured_app: &spin_factors::ConfiguredApp<F>,
22+
) -> anyhow::Result<()> {
23+
for (key, variable) in configured_app.app().variables() {
24+
self.variable_env_checker(key.clone(), variable.clone())?;
25+
}
26+
Ok(())
27+
}
28+
}
29+
30+
impl VariableSourcer for VariableSorterExecutorHooks {
31+
fn variable_env_checker(
32+
&self,
33+
key: String,
34+
val: spin_app::Variable,
35+
) -> anyhow::Result<(String, spin_app::Variable)> {
36+
let configs = spin_variables::variable_provider_config_from_toml(&self.table)?;
37+
38+
if let Some(config) = configs.into_iter().next() {
39+
let (dotenv_path, prefix) = match config {
40+
VariableProviderConfiguration::Env(env) => (env.dotenv_path, env.prefix),
41+
_ => (None, None),
42+
};
43+
return self.check(key, val, dotenv_path, prefix);
44+
}
45+
46+
Err(anyhow::anyhow!("No environment variable provider found"))
47+
}
48+
}

crates/variables-azure/Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ serde = { workspace = true }
1616
spin-common = { path = "../common" }
1717
spin-expressions = { path = "../expressions" }
1818
spin-factors = { path = "../factors" }
19+
spin-locked-app = { path = "../locked-app" }
1920
spin-world = { path = "../world" }
2021
tracing = { workspace = true }
2122

0 commit comments

Comments
 (0)