Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat: macro config (#3801)

Will Hutchinsonf651428bcd50
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lock
index 4d8a72bf6c..2c3e298a45 100644
--- a/rust/cloud-storage/Cargo.lock
+++ b/rust/cloud-storage/Cargo.lock
@@ -666,6 +666,7 @@ dependencies = [
"macro_auth",
"macro_aws_config",
"macro_cache_client",
+ "macro_config",
"macro_cors",
"macro_db_client",
"macro_entrypoint",
@@ -6475,6 +6476,28 @@ dependencies = [
"redis",
]
+[[package]]
+name = "macro_config"
+version = "0.1.0"
+dependencies = [
+ "macro_config_derive",
+ "macro_env_var",
+ "remote_env_var",
+ "serde",
+ "serde_json",
+ "thiserror 2.0.18",
+ "tracing",
+]
+
+[[package]]
+name = "macro_config_derive"
+version = "0.1.0"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.117",
+]
+
[[package]]
name = "macro_cors"
version = "0.1.0"
@@ -6560,6 +6583,7 @@ name = "macro_env_var"
version = "0.1.0"
dependencies = [
"paste",
+ "serde",
"serde_json",
"thiserror 2.0.18",
"tracing",
@@ -9519,6 +9543,9 @@ name = "remote_env_var"
version = "0.1.0"
dependencies = [
"macro_env",
+ "macro_env_var",
+ "serde",
+ "serde_json",
"thiserror 2.0.18",
"tracing",
]
diff --git a/rust/cloud-storage/Cargo.toml b/rust/cloud-storage/Cargo.toml
index fcce49b391..2a16e91730 100644
--- a/rust/cloud-storage/Cargo.toml
+++ b/rust/cloud-storage/Cargo.toml
@@ -55,6 +55,7 @@ members = [
"upload_extractor_lambda_trigger",
"user_link_cleanup_handler",
"worker_trigger",
+ "macro_config"
]
[workspace.dependencies]
diff --git a/rust/cloud-storage/authentication_service/Cargo.toml b/rust/cloud-storage/authentication_service/Cargo.toml
index 64d8b1b261..edda33fb6a 100644
--- a/rust/cloud-storage/authentication_service/Cargo.toml
+++ b/rust/cloud-storage/authentication_service/Cargo.toml
@@ -65,6 +65,7 @@ macro_cache_client = { path = "../macro_cache_client", default-features = false,
"verify_email_rate_limit",
] }
macro_cors = { path = "../macro_cors" }
+macro_config = { path = "../macro_config" }
macro_db_client = { path = "../macro_db_client", default-features = false, features = [
"account_merge_request",
"team",
diff --git a/rust/cloud-storage/authentication_service/src/config.rs b/rust/cloud-storage/authentication_service/src/config.rs
index e8356f6a9c..dc19a6d468 100644
--- a/rust/cloud-storage/authentication_service/src/config.rs
+++ b/rust/cloud-storage/authentication_service/src/config.rs
@@ -2,33 +2,11 @@ use std::sync::LazyLock;
use anyhow::Context;
pub use macro_env::Environment;
-use macro_service_urls::DocumentStorageServiceUrl;
-
-use serde_json::Value;
-
-fn read_config_value(key: &'static str) -> Option<String> {
- std::env::var("APP_SECRETS_JSON")
- .ok()
- .and_then(|raw| serde_json::from_str::<Value>(&raw).ok())
- .and_then(|json| json.get(key).cloned())
- .map(|value| match value {
- Value::String(s) => s,
- other => other.to_string(),
- })
- .or_else(|| std::env::var(key).ok())
-}
-
-fn required_config_value(key: &'static str) -> anyhow::Result<String> {
- read_config_value(key).with_context(|| format!("{key} must be provided"))
-}
-
-fn optional_config_value(key: &'static str) -> Option<String> {
- read_config_value(key)
-}
// BASE_URL config value. This is validated when creating the config in main.rs
pub static BASE_URL: LazyLock<String> = LazyLock::new(|| {
- read_config_value("BASE_URL").expect("BASE_URL must be provided via APP_SECRETS_JSON or env")
+ macro_config::required_config_value("BASE_URL")
+ .expect("BASE_URL must be provided via APP_SECRETS_JSON or env")
});
/// The configuration parameters for the application.
@@ -38,6 +16,8 @@ pub static BASE_URL: LazyLock<String> = LazyLock::new(|| {
/// populate the Docker container
///
/// See `.env.sample` in document-storage-service root for details.
+#[derive(macro_config::MacroConfig)]
+#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub struct Config {
#[allow(dead_code)]
pub base_url: String,
@@ -67,17 +47,16 @@ pub struct Config {
pub stripe_secret_key: String,
/// The port to listen for HTTP requests on.
+ #[macro_config_default(8080)]
pub port: usize,
/// The environment we are in
+ #[macro_config_default(Environment::new_or_prod())]
pub environment: Environment,
/// The internal auth key used by other services
pub service_internal_auth_key: String,
- /// The document storage service url
- pub document_storage_service_url: String,
-
/// The notification queue
pub notification_queue: String,
@@ -122,86 +101,7 @@ pub struct Config {
impl Config {
pub fn from_env() -> anyhow::Result<Self> {
- let base_url = required_config_value("BASE_URL")?;
- let database_url = required_config_value("DATABASE_URL")?;
- let redis_uri = required_config_value("REDIS_URI")?;
-
- let fusionauth_tenant_id = required_config_value("FUSIONAUTH_TENANT_ID")?;
- let fusionauth_api_key_secret_key = required_config_value("FUSIONAUTH_API_KEY_SECRET_KEY")?;
- let fusionauth_client_id = required_config_value("FUSIONAUTH_CLIENT_ID")?;
- let fusionauth_client_secret_key = required_config_value("FUSIONAUTH_CLIENT_SECRET_KEY")?;
- let fusionauth_base_url = required_config_value("FUSIONAUTH_BASE_URL")?;
- let fusionauth_oauth_redirect_uri = required_config_value("FUSIONAUTH_OAUTH_REDIRECT_URI")?;
-
- let google_client_id = required_config_value("GOOGLE_CLIENT_ID")?;
- let google_client_secret_key = required_config_value("GOOGLE_CLIENT_SECRET_KEY")?;
-
- let stripe_secret_key = required_config_value("STRIPE_SECRET_KEY")?;
-
- let service_internal_auth_key = required_config_value("SERVICE_INTERNAL_AUTH_KEY")?;
-
- let port: usize = read_config_value("PORT")
- .unwrap_or_else(|| "8080".to_string())
- .parse::<usize>()
- .context("should be valid port number")?;
-
- let environment = Environment::new_or_prod();
-
- let document_storage_service_url = DocumentStorageServiceUrl::new()?.to_string();
-
- let notification_queue = required_config_value("NOTIFICATION_QUEUE")?;
- let search_event_queue = required_config_value("SEARCH_EVENT_QUEUE")?;
- let link_manager_queue = required_config_value("LINK_MANAGER_QUEUE")?;
- let email_backfill_queue = required_config_value("EMAIL_BACKFILL_QUEUE")?;
-
- let github_client_id = required_config_value("GITHUB_CLIENT_ID")?;
- let github_client_secret = required_config_value("GITHUB_CLIENT_SECRET")?;
- let github_idp_id = required_config_value("GITHUB_IDP_ID")?;
-
- let ga_measurement_id = optional_config_value("GA_MEASUREMENT_ID");
- let ga_api_secret = optional_config_value("GA_API_SECRET");
-
- let meta_pixel_id = optional_config_value("META_PIXEL_ID");
- let meta_access_token = optional_config_value("META_ACCESS_TOKEN");
- let meta_test_event_code = optional_config_value("META_TEST_EVENT_CODE");
-
- let posthog_api_key = optional_config_value("POSTHOG_API_KEY");
- let posthog_host = optional_config_value("POSTHOG_HOST");
-
- let stripe_price_id = required_config_value("STRIPE_PRICE_ID")?;
-
- Ok(Config {
- base_url,
- database_url,
- redis_uri,
- fusionauth_tenant_id,
- fusionauth_api_key_secret_key,
- fusionauth_client_id,
- fusionauth_client_secret_key,
- fusionauth_base_url,
- fusionauth_oauth_redirect_uri,
- google_client_id,
- google_client_secret_key,
- stripe_secret_key,
- port,
- service_internal_auth_key,
- document_storage_service_url,
- notification_queue,
- search_event_queue,
- link_manager_queue,
- email_backfill_queue,
- environment,
- github_client_id,
- github_client_secret,
- github_idp_id,
- ga_measurement_id,
- ga_api_secret,
- meta_pixel_id,
- meta_access_token,
- meta_test_event_code,
- posthog_api_key,
- posthog_host,
- stripe_price_id,
- })
+ macro_config::ConfigLoader::load::<Config>()
+ .context("failed to load authentication service config")
}
}
diff --git a/rust/cloud-storage/authentication_service/src/main.rs b/rust/cloud-storage/authentication_service/src/main.rs
index 22ba2c4d4e..88f4b3ff44 100644
--- a/rust/cloud-storage/authentication_service/src/main.rs
+++ b/rust/cloud-storage/authentication_service/src/main.rs
@@ -21,6 +21,7 @@ use macro_auth::middleware::decode_jwt::JwtValidationArgs;
use macro_entrypoint::MacroEntrypoint;
use macro_middleware::auth::internal_access::InternalApiSecretKey;
use macro_service_urls::AppServiceUrl;
+use macro_service_urls::DocumentStorageServiceUrl;
use native_app_service::{
domain::{models::PlatformData, service::NativeAppServiceImpl},
outbound::DefaultBundleFetcher,
@@ -155,7 +156,7 @@ async fn main() -> anyhow::Result<()> {
let document_storage_service_client = DocumentStorageServiceClient::new(
config.service_internal_auth_key.clone(),
- config.document_storage_service_url.clone(),
+ DocumentStorageServiceUrl::new()?.to_string(),
);
tracing::trace!("initialized document storage service client");
diff --git a/rust/cloud-storage/macro_config/Cargo.toml b/rust/cloud-storage/macro_config/Cargo.toml
new file mode 100644
index 0000000000..168cd6e427
--- /dev/null
+++ b/rust/cloud-storage/macro_config/Cargo.toml
@@ -0,0 +1,16 @@
+[package]
+edition = "2024"
+name = "macro_config"
+publish = false
+version = "0.1.0"
+
+[dependencies]
+macro_config_derive = { path = "../macro_config_derive" }
+serde = { workspace = true }
+serde_json = { workspace = true }
+tracing = { workspace = true }
+thiserror = { workspace = true }
+
+[dev-dependencies]
+macro_env_var = { path = "../macro_env_var" }
+remote_env_var = { path = "../remote_env_var" }
diff --git a/rust/cloud-storage/macro_config/src/lib.rs b/rust/cloud-storage/macro_config/src/lib.rs
new file mode 100644
index 0000000000..c05bbf0e3a
--- /dev/null
+++ b/rust/cloud-storage/macro_config/src/lib.rs
@@ -0,0 +1,772 @@
+#![deny(missing_docs)]
+
+//! This crate creates a standardized way to load a service config from environment variables.
+
+extern crate self as macro_config;
+
+pub use macro_config_derive::MacroConfig;
+
+use serde::de::{
+ self, DeserializeOwned, DeserializeSeed, Error as _, IntoDeserializer, MapAccess, Visitor,
+};
+use serde_json::Value;
+use std::fmt::Display;
+
+#[doc(hidden)]
+pub use serde as __serde;
+use std::str::FromStr;
+
+#[cfg(test)]
+mod test;
+
+/// Typed result
+pub type MacroConfigResult<T> = Result<T, MacroConfigError>;
+
+/// Macro config errors
+#[derive(Debug, thiserror::Error)]
+pub enum MacroConfigError {
+ /// Missing required value
+ #[error("missing required value: {0}")]
+ MissingRequiredValue(&'static str),
+ /// Failed to deserialize a config value
+ #[error("failed to deserialize config value: {0}")]
+ Deserialize(String),
+}
+
+impl MacroConfigError {
+ fn invalid_value(
+ key: &'static str,
+ expected: &'static str,
+ error: impl Display,
+ ) -> MacroConfigError {
+ MacroConfigError::Deserialize(format!(
+ "failed to deserialize config key `{key}` as {expected}: {error}"
+ ))
+ }
+}
+
+impl de::Error for MacroConfigError {
+ fn custom<T>(msg: T) -> Self
+ where
+ T: Display,
+ {
+ MacroConfigError::Deserialize(msg.to_string())
+ }
+}
+
+/// Loads strongly typed config structs from config values.
+///
+/// Field names come from Serde, so attributes like `rename` and `rename_all` are respected when
+/// looking up environment keys.
+#[derive(Debug, Default, Clone, Copy)]
+pub struct ConfigLoader;
+
+impl ConfigLoader {
+ /// Loads a config struct from `APP_SECRETS_JSON` or environment variables.
+ ///
+ /// Non-`Option` fields are loaded with [`required_config_value`]. `Option` fields are loaded
+ /// with [`optional_config_value`].
+ pub fn load<T>() -> MacroConfigResult<T>
+ where
+ T: DeserializeOwned,
+ {
+ serde::Deserialize::deserialize(ConfigDeserializer)
+ }
+}
+
+/// Loads a config struct from `APP_SECRETS_JSON` or environment variables.
+///
+/// This is a convenience wrapper around [`ConfigLoader::load`].
+pub fn load<T>() -> MacroConfigResult<T>
+where
+ T: DeserializeOwned,
+{
+ ConfigLoader::load()
+}
+
+/// Reads the value from app secrets json env var.
+/// If `APP_SECRETS_JSON` is not present, tries to read from standard env var.
+fn read_config_value(key: &'static str) -> Option<String> {
+ match std::env::var("APP_SECRETS_JSON") {
+ Ok(raw) => {
+ let json = serde_json::from_str::<Value>(&raw)
+ .unwrap_or_else(|error| panic!("APP_SECRETS_JSON contains invalid JSON: {error}"));
+
+ json.get(key).cloned().map(|value| match value {
+ Value::String(s) => s,
+ other => other.to_string(),
+ })
+ }
+ Err(std::env::VarError::NotPresent) => std::env::var(key).ok(),
+ Err(error) => panic!("failed to read APP_SECRETS_JSON: {error}"),
+ }
+}
+
+/// Get a required value
+pub fn required_config_value(key: &'static str) -> MacroConfigResult<String> {
+ read_config_value(key).ok_or(MacroConfigError::MissingRequiredValue(key))
+}
+
+/// Get an optional value
+pub fn optional_config_value(key: &'static str) -> Option<String> {
+ read_config_value(key)
+}
+
+struct ConfigDeserializer;
+
+impl<'de> de::Deserializer<'de> for ConfigDeserializer {
+ type Error = MacroConfigError;
+
+ fn deserialize_any<V>(self, _visitor: V) -> MacroConfigResult<V::Value>
+ where
+ V: Visitor<'de>,
+ {
+ Err(MacroConfigError::Deserialize(
+ "ConfigLoader can only load struct types".to_string(),
+ ))
+ }
+
+ fn deserialize_struct<V>(
+ self,
+ _name: &'static str,
+ fields: &'static [&'static str],
+ visitor: V,
+ ) -> MacroConfigResult<V::Value>
+ where
+ V: Visitor<'de>,
+ {
+ visitor.visit_map(ConfigMapAccess {
+ fields,
+ next_field: 0,
+ current_key: None,
+ })
+ }
+
+ serde::forward_to_deserialize_any! {
+ bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string bytes
+ byte_buf option unit unit_struct newtype_struct seq tuple tuple_struct map enum
+ identifier ignored_any
+ }
+}
+
+struct ConfigMapAccess {
+ fields: &'static [&'static str],
+ next_field: usize,
+ current_key: Option<&'static str>,
+}
+
+impl<'de> MapAccess<'de> for ConfigMapAccess {
+ type Error = MacroConfigError;
+
+ fn next_key_seed<K>(&mut self, seed: K) -> MacroConfigResult<Option<K::Value>>
+ where
+ K: DeserializeSeed<'de>,
+ {
+ let Some(key) = self.fields.get(self.next_field).copied() else {
+ return Ok(None);
+ };
+
+ self.next_field += 1;
+ self.current_key = Some(key);
+ seed.deserialize(key.into_deserializer()).map(Some)
+ }
+
+ fn next_value_seed<V>(&mut self, seed: V) -> MacroConfigResult<V::Value>
+ where
+ V: DeserializeSeed<'de>,
+ {
+ let key = self.current_key.take().ok_or_else(|| {
+ MacroConfigError::Deserialize("config value requested before config key".to_string())
+ })?;
+
+ seed.deserialize(ConfigValueDeserializer { key })
+ }
+
+ fn size_hint(&self) -> Option<usize> {
+ Some(self.fields.len().saturating_sub(self.next_field))
+ }
+}
+
+struct ConfigValueDeserializer {
+ key: &'static str,
+}
+
+impl ConfigValueDeserializer {
+ fn required_value(self) -> MacroConfigResult<ConfigRawValueDeserializer> {
+ required_config_value(self.key).map(|value| ConfigRawValueDeserializer {
+ key: self.key,
+ value,
+ })
+ }
+}
+
+impl<'de> de::Deserializer<'de> for ConfigValueDeserializer {
+ type Error = MacroConfigError;
+
+ fn deserialize_any<V>(self, visitor: V) -> MacroConfigResult<V::Value>
+ where
+ V: Visitor<'de>,
+ {
+ self.required_value()?.deserialize_any(visitor)
+ }
+
+ fn deserialize_bool<V>(self, visitor: V) -> MacroConfigResult<V::Value>
+ where
+ V: Visitor<'de>,
+ {
+ self.required_value()?.deserialize_bool(visitor)
+ }
+
+ fn deserialize_i8<V>(self, visitor: V) -> MacroConfigResult<V::Value>
+ where
+ V: Visitor<'de>,
+ {
+ self.required_value()?.deserialize_i8(visitor)
+ }
+
+ fn deserialize_i16<V>(self, visitor: V) -> MacroConfigResult<V::Value>
+ where
+ V: Visitor<'de>,
+ {
+ self.required_value()?.deserialize_i16(visitor)
+ }
+
+ fn deserialize_i32<V>(self, visitor: V) -> MacroConfigResult<V::Value>
+ where
+ V: Visitor<'de>,
+ {
+ self.required_value()?.deserialize_i32(visitor)
+ }
+
+ fn deserialize_i64<V>(self, visitor: V) -> MacroConfigResult<V::Value>
+ where
+ V: Visitor<'de>,
+ {
+ self.required_value()?.deserialize_i64(visitor)
+ }
+
+ fn deserialize_i128<V>(self, visitor: V) -> MacroConfigResult<V::Value>
+ where
+ V: Visitor<'de>,
+ {
+ self.required_value()?.deserialize_i128(visitor)
+ }
+
+ fn deserialize_u8<V>(self, visitor: V) -> MacroConfigResult<V::Value>
+ where
+ V: Visitor<'de>,
+ {
+ self.required_value()?.deserialize_u8(visitor)
+ }
+
+ fn deserialize_u16<V>(self, visitor: V) -> MacroConfigResult<V::Value>
+ where
+ V: Visitor<'de>,
+ {
+ self.required_value()?.deserialize_u16(visitor)
+ }
+
+ fn deserialize_u32<V>(self, visitor: V) -> MacroConfigResult<V::Value>
+ where
+ V: Visitor<'de>,
+ {
+ self.required_value()?.deserialize_u32(visitor)
+ }
+
+ fn deserialize_u64<V>(self, visitor: V) -> MacroConfigResult<V::Value>
+ where
+ V: Visitor<'de>,
+ {
+ self.required_value()?.deserialize_u64(visitor)
+ }
+
+ fn deserialize_u128<V>(self, visitor: V) -> MacroConfigResult<V::Value>
+ where
+ V: Visitor<'de>,
+ {
+ self.required_value()?.deserialize_u128(visitor)
+ }
+
+ fn deserialize_f32<V>(self, visitor: V) -> MacroConfigResult<V::Value>
+ where
+ V: Visitor<'de>,
+ {
+ self.required_value()?.deserialize_f32(visitor)
+ }
+
+ fn deserialize_f64<V>(self, visitor: V) -> MacroConfigResult<V::Value>
+ where
+ V: Visitor<'de>,
+ {
+ self.required_value()?.deserialize_f64(visitor)
+ }
+
+ fn deserialize_char<V>(self, visitor: V) -> MacroConfigResult<V::Value>
+ where
+ V: Visitor<'de>,
+ {
+ self.required_value()?.deserialize_char(visitor)
+ }
+
+ fn deserialize_str<V>(self, visitor: V) -> MacroConfigResult<V::Value>
+ where
+ V: Visitor<'de>,
+ {
+ self.required_value()?.deserialize_str(visitor)
+ }
+
+ fn deserialize_string<V>(self, visitor: V) -> MacroConfigResult<V::Value>
+ where
+ V: Visitor<'de>,
+ {
+ self.required_value()?.deserialize_string(visitor)
+ }
+
+ fn deserialize_bytes<V>(self, visitor: V) -> MacroConfigResult<V::Value>
+ where
+ V: Visitor<'de>,
+ {
+ self.required_value()?.deserialize_bytes(visitor)
+ }
+
+ fn deserialize_byte_buf<V>(self, visitor: V) -> MacroConfigResult<V::Value>
+ where
+ V: Visitor<'de>,
+ {
+ self.required_value()?.deserialize_byte_buf(visitor)
+ }
+
+ fn deserialize_option<V>(self, visitor: V) -> MacroConfigResult<V::Value>
+ where
+ V: Visitor<'de>,
+ {
+ match optional_config_value(self.key) {
+ Some(value) if value == "null" => visitor.visit_none(),
+ Some(value) => visitor.visit_some(ConfigRawValueDeserializer {
+ key: self.key,
+ value,
+ }),
+ None => visitor.visit_none(),
+ }
+ }
+
+ fn deserialize_unit<V>(self, visitor: V) -> MacroConfigResult<V::Value>
+ where
+ V: Visitor<'de>,
+ {
+ self.required_value()?.deserialize_unit(visitor)
+ }
+
+ fn deserialize_unit_struct<V>(
+ self,
+ name: &'static str,
+ visitor: V,
+ ) -> MacroConfigResult<V::Value>
+ where
+ V: Visitor<'de>,
+ {
+ self.required_value()?
+ .deserialize_unit_struct(name, visitor)
+ }
+
+ fn deserialize_newtype_struct<V>(
+ self,
+ name: &'static str,
+ visitor: V,
+ ) -> MacroConfigResult<V::Value>
+ where
+ V: Visitor<'de>,
+ {
+ self.required_value()?
+ .deserialize_newtype_struct(name, visitor)
+ }
+
+ fn deserialize_seq<V>(self, visitor: V) -> MacroConfigResult<V::Value>
+ where
+ V: Visitor<'de>,
+ {
+ self.required_value()?.deserialize_seq(visitor)
+ }
+
+ fn deserialize_tuple<V>(self, len: usize, visitor: V) -> MacroConfigResult<V::Value>
+ where
+ V: Visitor<'de>,
+ {
+ self.required_value()?.deserialize_tuple(len, visitor)
+ }
+
+ fn deserialize_tuple_struct<V>(
+ self,
+ name: &'static str,
+ len: usize,
+ visitor: V,
+ ) -> MacroConfigResult<V::Value>
+ where
+ V: Visitor<'de>,
+ {
+ self.required_value()?
+ .deserialize_tuple_struct(name, len, visitor)
+ }
+
+ fn deserialize_map<V>(self, visitor: V) -> MacroConfigResult<V::Value>
+ where
+ V: Visitor<'de>,
+ {
+ self.required_value()?.deserialize_map(visitor)
+ }
+
+ fn deserialize_struct<V>(
+ self,
+ name: &'static str,
+ fields: &'static [&'static str],
+ visitor: V,
+ ) -> MacroConfigResult<V::Value>
+ where
+ V: Visitor<'de>,
+ {
+ self.required_value()?
+ .deserialize_struct(name, fields, visitor)
+ }
+
+ fn deserialize_enum<V>(
+ self,
+ name: &'static str,
+ variants: &'static [&'static str],
+ visitor: V,
+ ) -> MacroConfigResult<V::Value>
+ where
+ V: Visitor<'de>,
+ {
+ self.required_value()?
+ .deserialize_enum(name, variants, visitor)
+ }
+
+ fn deserialize_identifier<V>(self, visitor: V) -> MacroConfigResult<V::Value>
+ where
+ V: Visitor<'de>,
+ {
+ self.required_value()?.deserialize_identifier(visitor)
+ }
+
+ fn deserialize_ignored_any<V>(self, visitor: V) -> MacroConfigResult<V::Value>
+ where
+ V: Visitor<'de>,
+ {
+ self.required_value()?.deserialize_ignored_any(visitor)
+ }
+}
+
+struct ConfigRawValueDeserializer {
+ key: &'static str,
+ value: String,
+}
+
+impl ConfigRawValueDeserializer {
+ fn parse<T>(self, expected: &'static str) -> MacroConfigResult<T>
+ where
+ T: FromStr,
+ T::Err: Display,
+ {
+ self.value
+ .parse()
+ .map_err(|error| MacroConfigError::invalid_value(self.key, expected, error))
+ }
+
+ fn parse_json(self, expected: &'static str) -> MacroConfigResult<Value> {
+ serde_json::from_str(&self.value)
+ .map_err(|error| MacroConfigError::invalid_value(self.key, expected, error))
+ }
+}
+
+impl<'de> de::Deserializer<'de> for ConfigRawValueDeserializer {
+ type Error = MacroConfigError;
+
+ fn deserialize_any<V>(self, visitor: V) -> MacroConfigResult<V::Value>
+ where
+ V: Visitor<'de>,
+ {
+ match serde_json::from_str::<Value>(&self.value) {
+ Ok(value) => value
+ .deserialize_any(visitor)
+ .map_err(MacroConfigError::custom),
+ Err(_) => visitor.visit_string(self.value),
+ }
+ }
+
+ fn deserialize_bool<V>(self, visitor: V) -> MacroConfigResult<V::Value>
+ where
+ V: Visitor<'de>,
+ {
+ visitor.visit_bool(self.parse("bool")?)
+ }
+
+ fn deserialize_i8<V>(self, visitor: V) -> MacroConfigResult<V::Value>
+ where
+ V: Visitor<'de>,
+ {
+ visitor.visit_i8(self.parse("i8")?)
+ }
+
+ fn deserialize_i16<V>(self, visitor: V) -> MacroConfigResult<V::Value>
+ where
+ V: Visitor<'de>,
+ {
+ visitor.visit_i16(self.parse("i16")?)
+ }
+
+ fn deserialize_i32<V>(self, visitor: V) -> MacroConfigResult<V::Value>
+ where
+ V: Visitor<'de>,
+ {
+ visitor.visit_i32(self.parse("i32")?)
+ }
+
+ fn deserialize_i64<V>(self, visitor: V) -> MacroConfigResult<V::Value>
+ where
+ V: Visitor<'de>,
+ {
+ visitor.visit_i64(self.parse("i64")?)
+ }
+
+ fn deserialize_i128<V>(self, visitor: V) -> MacroConfigResult<V::Value>
+ where
+ V: Visitor<'de>,
+ {
+ visitor.visit_i128(self.parse("i128")?)
+ }
+
+ fn deserialize_u8<V>(self, visitor: V) -> MacroConfigResult<V::Value>
+ where
+ V: Visitor<'de>,
+ {
+ visitor.visit_u8(self.parse("u8")?)
+ }
+
+ fn deserialize_u16<V>(self, visitor: V) -> MacroConfigResult<V::Value>
+ where
+ V: Visitor<'de>,
+ {
+ visitor.visit_u16(self.parse("u16")?)
+ }
+
+ fn deserialize_u32<V>(self, visitor: V) -> MacroConfigResult<V::Value>
+ where
+ V: Visitor<'de>,
+ {
+ visitor.visit_u32(self.parse("u32")?)
+ }
+
+ fn deserialize_u64<V>(self, visitor: V) -> MacroConfigResult<V::Value>
+ where
+ V: Visitor<'de>,
+ {
+ visitor.visit_u64(self.parse("u64")?)
+ }
+
+ fn deserialize_u128<V>(self, visitor: V) -> MacroConfigResult<V::Value>
+ where
+ V: Visitor<'de>,
+ {
+ visitor.visit_u128(self.parse("u128")?)
+ }
+
+ fn deserialize_f32<V>(self, visitor: V) -> MacroConfigResult<V::Value>
+ where
+ V: Visitor<'de>,
+ {
+ visitor.visit_f32(self.parse("f32")?)
+ }
+
+ fn deserialize_f64<V>(self, visitor: V) -> MacroConfigResult<V::Value>
+ where
+ V: Visitor<'de>,
+ {
+ visitor.visit_f64(self.parse("f64")?)
+ }
+
+ fn deserialize_char<V>(self, visitor: V) -> MacroConfigResult<V::Value>
+ where
+ V: Visitor<'de>,
+ {
+ let mut chars = self.value.chars();
+ let Some(char_value) = chars.next() else {
+ return Err(MacroConfigError::invalid_value(
+ self.key,
+ "char",
+ "expected a single character",
+ ));
+ };
+
+ if chars.next().is_some() {
+ return Err(MacroConfigError::invalid_value(
+ self.key,
+ "char",
+ "expected a single character",
+ ));
+ }
+
+ visitor.visit_char(char_value)
+ }
+
+ fn deserialize_str<V>(self, visitor: V) -> MacroConfigResult<V::Value>
+ where
+ V: Visitor<'de>,
+ {
+ visitor.visit_string(self.value)
+ }
+
+ fn deserialize_string<V>(self, visitor: V) -> MacroConfigResult<V::Value>
+ where
+ V: Visitor<'de>,
+ {
+ visitor.visit_string(self.value)
+ }
+
+ fn deserialize_bytes<V>(self, visitor: V) -> MacroConfigResult<V::Value>
+ where
+ V: Visitor<'de>,
+ {
+ visitor.visit_byte_buf(self.value.into_bytes())
+ }
+
+ fn deserialize_byte_buf<V>(self, visitor: V) -> MacroConfigResult<V::Value>
+ where
+ V: Visitor<'de>,
+ {
+ visitor.visit_byte_buf(self.value.into_bytes())
+ }
+
+ fn deserialize_option<V>(self, visitor: V) -> MacroConfigResult<V::Value>
+ where
+ V: Visitor<'de>,
+ {
+ if self.value == "null" {
+ visitor.visit_none()
+ } else {
+ visitor.visit_some(self)
+ }
+ }
+
+ fn deserialize_unit<V>(self, visitor: V) -> MacroConfigResult<V::Value>
+ where
+ V: Visitor<'de>,
+ {
+ if self.value.is_empty() || self.value == "null" {
+ visitor.visit_unit()
+ } else {
+ Err(MacroConfigError::invalid_value(
+ self.key,
+ "unit",
+ "expected empty string or null",
+ ))
+ }
+ }
+
+ fn deserialize_unit_struct<V>(
+ self,
+ _name: &'static str,
+ visitor: V,
+ ) -> MacroConfigResult<V::Value>
+ where
+ V: Visitor<'de>,
+ {
+ self.deserialize_unit(visitor)
+ }
+
+ fn deserialize_newtype_struct<V>(
+ self,
+ _name: &'static str,
+ visitor: V,
+ ) -> MacroConfigResult<V::Value>
+ where
+ V: Visitor<'de>,
+ {
+ visitor.visit_newtype_struct(self)
+ }
+
+ fn deserialize_seq<V>(self, visitor: V) -> MacroConfigResult<V::Value>
+ where
+ V: Visitor<'de>,
+ {
+ self.parse_json("JSON array")?
+ .deserialize_seq(visitor)
+ .map_err(MacroConfigError::custom)
+ }
+
+ fn deserialize_tuple<V>(self, len: usize, visitor: V) -> MacroConfigResult<V::Value>
+ where
+ V: Visitor<'de>,
+ {
+ self.parse_json("JSON array")?
+ .deserialize_tuple(len, visitor)
+ .map_err(MacroConfigError::custom)
+ }
+
+ fn deserialize_tuple_struct<V>(
+ self,
+ name: &'static str,
+ len: usize,
+ visitor: V,
+ ) -> MacroConfigResult<V::Value>
+ where
+ V: Visitor<'de>,
+ {
+ self.parse_json("JSON array")?
+ .deserialize_tuple_struct(name, len, visitor)
+ .map_err(MacroConfigError::custom)
+ }
+
+ fn deserialize_map<V>(self, visitor: V) -> MacroConfigResult<V::Value>
+ where
+ V: Visitor<'de>,
+ {
+ self.parse_json("JSON object")?
+ .deserialize_map(visitor)
+ .map_err(MacroConfigError::custom)
+ }
+
+ fn deserialize_struct<V>(
+ self,
+ name: &'static str,
+ fields: &'static [&'static str],
+ visitor: V,
+ ) -> MacroConfigResult<V::Value>
+ where
+ V: Visitor<'de>,
+ {
+ self.parse_json("JSON object")?
+ .deserialize_struct(name, fields, visitor)
+ .map_err(MacroConfigError::custom)
+ }
+
+ fn deserialize_enum<V>(
+ self,
+ name: &'static str,
+ variants: &'static [&'static str],
+ visitor: V,
+ ) -> MacroConfigResult<V::Value>
+ where
+ V: Visitor<'de>,
+ {
+ match serde_json::from_str::<Value>(&self.value) {
+ Ok(value) => value
+ .deserialize_enum(name, variants, visitor)
+ .map_err(MacroConfigError::custom),
+ Err(_) => visitor.visit_enum(self.value.into_deserializer()),
+ }
+ }
+
+ fn deserialize_identifier<V>(self, visitor: V) -> MacroConfigResult<V::Value>
+ where
+ V: Visitor<'de>,
+ {
+ visitor.visit_string(self.value)
+ }
+
+ fn deserialize_ignored_any<V>(self, visitor: V) -> MacroConfigResult<V::Value>
+ where
+ V: Visitor<'de>,
+ {
+ visitor.visit_unit()
+ }
+}
diff --git a/rust/cloud-storage/macro_config/src/test.rs b/rust/cloud-storage/macro_config/src/test.rs
new file mode 100644
index 0000000000..ed7b86541e
--- /dev/null
+++ b/rust/cloud-storage/macro_config/src/test.rs
@@ -0,0 +1,295 @@
+use super::*;
+use serde::Deserialize;
+use std::sync::Mutex;
+
+static ENV_LOCK: Mutex<()> = Mutex::new(());
+
+struct EnvGuard {
+ saved: Vec<(&'static str, Option<String>)>,
+}
+
+impl EnvGuard {
+ fn new(keys: &[&'static str]) -> EnvGuard {
+ let saved = keys
+ .iter()
+ .copied()
+ .map(|key| {
+ let value = std::env::var(key).ok();
+ unsafe {
+ std::env::remove_var(key);
+ }
+ (key, value)
+ })
+ .collect();
+
+ EnvGuard { saved }
+ }
+
+ fn set(&self, key: &'static str, value: &str) {
+ unsafe {
+ std::env::set_var(key, value);
+ }
+ }
+}
+
+impl Drop for EnvGuard {
+ fn drop(&mut self) {
+ for (key, value) in self.saved.drain(..) {
+ match value {
+ Some(value) => unsafe {
+ std::env::set_var(key, value);
+ },
+ None => unsafe {
+ std::env::remove_var(key);
+ },
+ }
+ }
+ }
+}
+
+macro_env_var::env_var! {
+ #[derive(Debug)]
+ struct ConfigSecret;
+}
+
+macro_env_var::maybe_env_var! {
+ #[derive(Debug)]
+ struct OptionalConfigSecret;
+}
+
+#[derive(Debug, Deserialize, PartialEq)]
+#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
+struct ScreamingSnakeConfig {
+ required_value: String,
+ optional_value: Option<u16>,
+ missing_optional: Option<String>,
+}
+
+#[test]
+fn load_uses_serde_renamed_field_names() {
+ let _lock = ENV_LOCK.lock().expect("env lock poisoned");
+ let env = EnvGuard::new(&[
+ "APP_SECRETS_JSON",
+ "REQUIRED_VALUE",
+ "OPTIONAL_VALUE",
+ "MISSING_OPTIONAL",
+ ]);
+ env.set("REQUIRED_VALUE", "required");
+ env.set("OPTIONAL_VALUE", "42");
+
+ let config = ConfigLoader::load::<ScreamingSnakeConfig>().expect("config should load");
+
+ assert_eq!(
+ config,
+ ScreamingSnakeConfig {
+ required_value: "required".to_string(),
+ optional_value: Some(42),
+ missing_optional: None,
+ }
+ );
+}
+
+#[derive(Debug, Deserialize, PartialEq)]
+struct LowercaseConfig {
+ lowercase: String,
+}
+
+#[derive(Debug, MacroConfig, PartialEq)]
+struct DefaultValueConfig {
+ #[macro_config_default(8080)]
+ port: usize,
+}
+
+#[test]
+fn load_uses_default_field_names() {
+ let _lock = ENV_LOCK.lock().expect("env lock poisoned");
+ let env = EnvGuard::new(&["APP_SECRETS_JSON", "lowercase"]);
+ env.set("lowercase", "lowercase value");
+
+ let config = load::<LowercaseConfig>().expect("config should load");
+
+ assert_eq!(
+ config,
+ LowercaseConfig {
+ lowercase: "lowercase value".to_string(),
+ }
+ );
+}
+
+#[test]
+fn load_uses_macro_config_default_value_when_key_is_missing() {
+ let _lock = ENV_LOCK.lock().expect("env lock poisoned");
+ let _env = EnvGuard::new(&["APP_SECRETS_JSON", "port"]);
+
+ let config = load::<DefaultValueConfig>().expect("config should load");
+
+ assert_eq!(config, DefaultValueConfig { port: 8080 });
+}
+
+#[test]
+fn load_uses_config_value_over_macro_config_default_value() {
+ let _lock = ENV_LOCK.lock().expect("env lock poisoned");
+ let env = EnvGuard::new(&["APP_SECRETS_JSON", "port"]);
+ env.set("port", "3000");
+
+ let config = load::<DefaultValueConfig>().expect("config should load");
+
+ assert_eq!(config, DefaultValueConfig { port: 3000 });
+}
+
+#[derive(Debug, Deserialize, PartialEq)]
+#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
+struct JsonConfig {
+ required_value: String,
+ count: u32,
+ items: Vec<String>,
+}
+
+#[test]
+fn load_reads_values_from_app_secrets_json() {
+ let _lock = ENV_LOCK.lock().expect("env lock poisoned");
+ let env = EnvGuard::new(&["APP_SECRETS_JSON", "REQUIRED_VALUE", "COUNT", "ITEMS"]);
+ env.set(
+ "APP_SECRETS_JSON",
+ r#"{"REQUIRED_VALUE":"from json","COUNT":7,"ITEMS":["first","second"]}"#,
+ );
+ env.set("REQUIRED_VALUE", "from env");
+
+ let config = ConfigLoader::load::<JsonConfig>().expect("config should load");
+
+ assert_eq!(
+ config,
+ JsonConfig {
+ required_value: "from json".to_string(),
+ count: 7,
+ items: vec!["first".to_string(), "second".to_string()],
+ }
+ );
+}
+
+#[test]
+fn load_panics_when_app_secrets_json_is_invalid() {
+ let _lock = ENV_LOCK.lock().expect("env lock poisoned");
+ let env = EnvGuard::new(&["APP_SECRETS_JSON", "lowercase"]);
+ env.set("APP_SECRETS_JSON", "not json");
+ env.set("lowercase", "fallback value");
+
+ let panic = std::panic::catch_unwind(ConfigLoader::load::<LowercaseConfig>)
+ .expect_err("config load should panic");
+ let message = panic
+ .downcast_ref::<String>()
+ .map(String::as_str)
+ .or_else(|| panic.downcast_ref::<&str>().copied())
+ .expect("panic should have a string message");
+
+ assert!(message.contains("APP_SECRETS_JSON contains invalid JSON"));
+}
+
+#[test]
+fn load_does_not_fallback_to_env_when_app_secrets_json_is_present_without_key() {
+ let _lock = ENV_LOCK.lock().expect("env lock poisoned");
+ let env = EnvGuard::new(&["APP_SECRETS_JSON", "lowercase"]);
+ env.set("APP_SECRETS_JSON", r#"{}"#);
+ env.set("lowercase", "fallback value");
+
+ let error = ConfigLoader::load::<LowercaseConfig>().expect_err("config should fail");
+
+ assert!(matches!(
+ error,
+ MacroConfigError::MissingRequiredValue("lowercase")
+ ));
+}
+
+#[derive(Debug, Deserialize)]
+#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
+struct EnvVarFieldConfig {
+ config_secret: ConfigSecret,
+ optional_config_secret: Option<OptionalConfigSecret>,
+ missing_optional_secret: Option<OptionalConfigSecret>,
+}
+
+#[derive(Deserialize)]
+#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
+struct RemoteSecretFieldConfig {
+ remote_config_secret: remote_env_var::LocalOrRemoteSecret<ConfigSecret>,
+ optional_remote_config_secret:
+ remote_env_var::OptionalLocalOrRemoteSecret<OptionalConfigSecret>,
+ missing_remote_config_secret: remote_env_var::OptionalLocalOrRemoteSecret<OptionalConfigSecret>,
+}
+
+#[test]
+fn load_deserializes_macro_env_var_fields() {
+ let _lock = ENV_LOCK.lock().expect("env lock poisoned");
+ let env = EnvGuard::new(&[
+ "APP_SECRETS_JSON",
+ "CONFIG_SECRET",
+ "OPTIONAL_CONFIG_SECRET",
+ "MISSING_OPTIONAL_SECRET",
+ ]);
+ env.set("CONFIG_SECRET", "secret");
+ env.set("OPTIONAL_CONFIG_SECRET", "optional-secret");
+
+ let config = ConfigLoader::load::<EnvVarFieldConfig>().expect("config should load");
+
+ assert_eq!(&*config.config_secret, "secret");
+ assert_eq!(
+ config
+ .optional_config_secret
+ .as_ref()
+ .map(|value| value.as_ref()),
+ Some("optional-secret")
+ );
+ assert!(config.missing_optional_secret.is_none());
+}
+
+#[test]
+fn load_deserializes_local_or_remote_macro_env_var_fields() {
+ let _lock = ENV_LOCK.lock().expect("env lock poisoned");
+ let env = EnvGuard::new(&[
+ "APP_SECRETS_JSON",
+ "REMOTE_CONFIG_SECRET",
+ "OPTIONAL_REMOTE_CONFIG_SECRET",
+ "MISSING_REMOTE_CONFIG_SECRET",
+ ]);
+ env.set("REMOTE_CONFIG_SECRET", "remote-secret-name");
+ env.set(
+ "OPTIONAL_REMOTE_CONFIG_SECRET",
+ "optional-remote-secret-name",
+ );
+
+ let config = ConfigLoader::load::<RemoteSecretFieldConfig>().expect("config should load");
+
+ match config.remote_config_secret {
+ remote_env_var::LocalOrRemoteSecret::Local(value) => {
+ assert_eq!(value.as_ref(), "remote-secret-name");
+ }
+ remote_env_var::LocalOrRemoteSecret::Remote(_) => {
+ panic!("deserialized secret should be local until resolved")
+ }
+ }
+
+ assert_eq!(
+ config.optional_remote_config_secret.as_str(),
+ Some("optional-remote-secret-name")
+ );
+ assert_eq!(config.missing_remote_config_secret.as_str(), None);
+}
+
+#[allow(dead_code)]
+#[derive(Debug, Deserialize)]
+struct MissingRequiredConfig {
+ missing: String,
+}
+
+#[test]
+fn load_errors_when_required_value_is_missing() {
+ let _lock = ENV_LOCK.lock().expect("env lock poisoned");
+ let _env = EnvGuard::new(&["APP_SECRETS_JSON", "missing"]);
+
+ let error = ConfigLoader::load::<MissingRequiredConfig>().expect_err("config should fail");
+
+ assert!(matches!(
+ error,
+ MacroConfigError::MissingRequiredValue("missing")
+ ));
+}
diff --git a/rust/cloud-storage/macro_config_derive/Cargo.toml b/rust/cloud-storage/macro_config_derive/Cargo.toml
new file mode 100644
index 0000000000..7f74155a29
--- /dev/null
+++ b/rust/cloud-storage/macro_config_derive/Cargo.toml
@@ -0,0 +1,13 @@
+[package]
+edition = "2024"
+name = "macro_config_derive"
+publish = false
+version = "0.1.0"
+
+[lib]
+proc-macro = true
+
+[dependencies]
+proc-macro2 = "1"
+quote = { workspace = true }
+syn = { version = "2", features = ["full"] }
diff --git a/rust/cloud-storage/macro_config_derive/src/lib.rs b/rust/cloud-storage/macro_config_derive/src/lib.rs
new file mode 100644
index 0000000000..d17d327067
--- /dev/null
+++ b/rust/cloud-storage/macro_config_derive/src/lib.rs
@@ -0,0 +1,332 @@
+use proc_macro::TokenStream;
+use proc_macro2::TokenStream as TokenStream2;
+use quote::{format_ident, quote};
+use syn::{
+ Data, DeriveInput, Fields, GenericArgument, LitStr, PathArguments, Type, parse_macro_input,
+ parse_quote,
+};
+
+#[proc_macro_derive(MacroConfig, attributes(macro_config_default, serde))]
+pub fn derive_macro_config(input: TokenStream) -> TokenStream {
+ let input = parse_macro_input!(input as DeriveInput);
+
+ match expand_macro_config(input) {
+ Ok(tokens) => tokens.into(),
+ Err(error) => error.to_compile_error().into(),
+ }
+}
+
+fn expand_macro_config(input: DeriveInput) -> syn::Result<TokenStream2> {
+ let struct_name = input.ident;
+ let struct_name_string = struct_name.to_string();
+ let rename_all = serde_rename_all(&input.attrs)?;
+
+ let fields = match input.data {
+ Data::Struct(data) => match data.fields {
+ Fields::Named(fields) => fields.named,
+ _ => {
+ return Err(syn::Error::new_spanned(
+ struct_name,
+ "MacroConfig only supports structs with named fields",
+ ));
+ }
+ },
+ _ => {
+ return Err(syn::Error::new_spanned(
+ struct_name,
+ "MacroConfig only supports structs",
+ ));
+ }
+ };
+
+ let mut field_data = Vec::new();
+ for (index, field) in fields.into_iter().enumerate() {
+ let ident = field.ident.ok_or_else(|| {
+ syn::Error::new_spanned(&field.ty, "MacroConfig only supports named fields")
+ })?;
+ let ty = field.ty;
+ let key = serde_rename(&field.attrs)?.unwrap_or_else(|| {
+ let field_name = ident.to_string();
+ apply_rename_all(&field_name, rename_all.as_deref())
+ });
+ let default = macro_config_default(&field.attrs)?;
+ let is_option = default.is_none() && is_option_type(&ty);
+ let variant = format_ident!("Field{index}");
+
+ field_data.push(FieldData {
+ ident,
+ ty,
+ key,
+ default,
+ is_option,
+ variant,
+ });
+ }
+
+ let field_keys = field_data.iter().map(|field| field.key.as_str());
+ let variants = field_data.iter().map(|field| &field.variant);
+ let field_matches = field_data.iter().map(|field| {
+ let key = field.key.as_str();
+ let variant = &field.variant;
+ quote! { #key => Ok(__MacroConfigField::#variant), }
+ });
+ let initializers = field_data.iter().map(|field| {
+ let ident = &field.ident;
+ quote! { let mut #ident = None; }
+ });
+ let value_matches = field_data.iter().map(|field| {
+ let FieldData {
+ ident,
+ ty,
+ key,
+ default,
+ variant,
+ ..
+ } = field;
+
+ match default {
+ Some(default) => quote! {
+ __MacroConfigField::#variant => {
+ if #ident.is_some() {
+ return Err(<V::Error as ::macro_config::__serde::de::Error>::duplicate_field(#key));
+ }
+ #ident = Some(
+ map.next_value::<Option<#ty>>()?
+ .unwrap_or_else(|| #default)
+ );
+ }
+ },
+ None => quote! {
+ __MacroConfigField::#variant => {
+ if #ident.is_some() {
+ return Err(<V::Error as ::macro_config::__serde::de::Error>::duplicate_field(#key));
+ }
+ #ident = Some(map.next_value::<#ty>()?);
+ }
+ },
+ }
+ });
+ let finalizers = field_data.iter().map(|field| {
+ let FieldData {
+ ident,
+ key,
+ default,
+ is_option,
+ ..
+ } = field;
+
+ match default {
+ Some(default) => quote! {
+ let #ident = #ident.unwrap_or_else(|| #default);
+ },
+ None if *is_option => quote! {
+ let #ident = #ident.unwrap_or(None);
+ },
+ None => quote! {
+ let #ident = #ident.ok_or_else(|| {
+ <V::Error as ::macro_config::__serde::de::Error>::missing_field(#key)
+ })?;
+ },
+ }
+ });
+ let struct_fields = field_data.iter().map(|field| &field.ident);
+
+ let mut impl_generics_with_de = input.generics.clone();
+ impl_generics_with_de.params.insert(0, parse_quote!('de));
+ let (impl_generics, _, where_clause) = impl_generics_with_de.split_for_impl();
+ let (_, ty_generics, _) = input.generics.split_for_impl();
+
+ Ok(quote! {
+ impl #impl_generics ::macro_config::__serde::Deserialize<'de> for #struct_name #ty_generics #where_clause {
+ fn deserialize<__D>(deserializer: __D) -> Result<Self, __D::Error>
+ where
+ __D: ::macro_config::__serde::Deserializer<'de>,
+ {
+ const FIELDS: &[&str] = &[#(#field_keys),*];
+
+ enum __MacroConfigField {
+ #(#variants),*
+ }
+
+ impl<'de> ::macro_config::__serde::Deserialize<'de> for __MacroConfigField {
+ fn deserialize<__D>(deserializer: __D) -> Result<Self, __D::Error>
+ where
+ __D: ::macro_config::__serde::Deserializer<'de>,
+ {
+ struct __MacroConfigFieldVisitor;
+
+ impl<'de> ::macro_config::__serde::de::Visitor<'de> for __MacroConfigFieldVisitor {
+ type Value = __MacroConfigField;
+
+ fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ formatter.write_str("a config field")
+ }
+
+ fn visit_str<__E>(self, value: &str) -> Result<Self::Value, __E>
+ where
+ __E: ::macro_config::__serde::de::Error,
+ {
+ match value {
+ #(#field_matches)*
+ _ => Err(__E::unknown_field(value, FIELDS)),
+ }
+ }
+ }
+
+ deserializer.deserialize_identifier(__MacroConfigFieldVisitor)
+ }
+ }
+
+ struct __MacroConfigVisitor;
+
+ impl<'de> ::macro_config::__serde::de::Visitor<'de> for __MacroConfigVisitor {
+ type Value = #struct_name #ty_generics;
+
+ fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ formatter.write_str(concat!("struct ", #struct_name_string))
+ }
+
+ fn visit_map<V>(self, mut map: V) -> Result<Self::Value, V::Error>
+ where
+ V: ::macro_config::__serde::de::MapAccess<'de>,
+ {
+ #(#initializers)*
+
+ while let Some(key) = map.next_key::<__MacroConfigField>()? {
+ match key {
+ #(#value_matches)*
+ }
+ }
+
+ #(#finalizers)*
+
+ Ok(#struct_name {
+ #(#struct_fields),*
+ })
+ }
+ }
+
+ deserializer.deserialize_struct(#struct_name_string, FIELDS, __MacroConfigVisitor)
+ }
+ }
+ })
+}
+
+struct FieldData {
+ ident: syn::Ident,
+ ty: Type,
+ key: String,
+ default: Option<TokenStream2>,
+ is_option: bool,
+ variant: syn::Ident,
+}
+
+fn macro_config_default(attrs: &[syn::Attribute]) -> syn::Result<Option<TokenStream2>> {
+ let mut default = None;
+
+ for attr in attrs {
+ if attr.path().is_ident("macro_config_default") {
+ if default.is_some() {
+ return Err(syn::Error::new_spanned(
+ attr,
+ "duplicate macro_config_default attribute",
+ ));
+ }
+ default = Some(attr.parse_args::<TokenStream2>()?);
+ }
+ }
+
+ Ok(default)
+}
+
+fn serde_rename_all(attrs: &[syn::Attribute]) -> syn::Result<Option<String>> {
+ let mut rename_all = None;
+
+ for attr in attrs {
+ if attr.path().is_ident("serde") {
+ attr.parse_nested_meta(|meta| {
+ if meta.path.is_ident("rename_all") {
+ let value = meta.value()?;
+ let value = value.parse::<LitStr>()?;
+ rename_all = Some(value.value());
+ }
+ Ok(())
+ })?;
+ }
+ }
+
+ Ok(rename_all)
+}
+
+fn serde_rename(attrs: &[syn::Attribute]) -> syn::Result<Option<String>> {
+ let mut rename = None;
+
+ for attr in attrs {
+ if attr.path().is_ident("serde") {
+ attr.parse_nested_meta(|meta| {
+ if meta.path.is_ident("rename") {
+ let value = meta.value()?;
+ let value = value.parse::<LitStr>()?;
+ rename = Some(value.value());
+ }
+ Ok(())
+ })?;
+ }
+ }
+
+ Ok(rename)
+}
+
+fn apply_rename_all(field_name: &str, rename_all: Option<&str>) -> String {
+ match rename_all {
+ Some("SCREAMING_SNAKE_CASE") => to_screaming_snake_case(field_name),
+ Some("lowercase") => field_name.to_ascii_lowercase(),
+ Some("snake_case") | None => field_name.to_string(),
+ _ => field_name.to_string(),
+ }
+}
+
+fn to_screaming_snake_case(value: &str) -> String {
+ let mut out = String::new();
+ let mut previous_was_lowercase_or_digit = false;
+
+ for ch in value.chars() {
+ if ch == '-' || ch == ' ' {
+ if !out.ends_with('_') {
+ out.push('_');
+ }
+ previous_was_lowercase_or_digit = false;
+ } else if ch.is_ascii_uppercase() {
+ if previous_was_lowercase_or_digit && !out.ends_with('_') {
+ out.push('_');
+ }
+ out.push(ch);
+ previous_was_lowercase_or_digit = false;
+ } else {
+ out.push(ch.to_ascii_uppercase());
+ previous_was_lowercase_or_digit = ch.is_ascii_lowercase() || ch.is_ascii_digit();
+ }
+ }
+
+ out
+}
+
+fn is_option_type(ty: &Type) -> bool {
+ let Type::Path(path) = ty else {
+ return false;
+ };
+
+ let Some(segment) = path.path.segments.last() else {
+ return false;
+ };
+
+ if segment.ident != "Option" {
+ return false;
+ }
+
+ matches!(
+ &segment.arguments,
+ PathArguments::AngleBracketed(args)
+ if args.args.iter().any(|arg| matches!(arg, GenericArgument::Type(_)))
+ )
+}
diff --git a/rust/cloud-storage/macro_env_var/Cargo.toml b/rust/cloud-storage/macro_env_var/Cargo.toml
index 644dd01593..222f3133df 100644
--- a/rust/cloud-storage/macro_env_var/Cargo.toml
+++ b/rust/cloud-storage/macro_env_var/Cargo.toml
@@ -9,6 +9,7 @@ test-comptime = []
[dependencies]
paste = { workspace = true }
+serde = { workspace = true }
serde_json = { workspace = true }
thiserror = { workspace = true }
diff --git a/rust/cloud-storage/macro_env_var/src/lib.rs b/rust/cloud-storage/macro_env_var/src/lib.rs
index 2cb5f29369..29c383263f 100644
--- a/rust/cloud-storage/macro_env_var/src/lib.rs
+++ b/rust/cloud-storage/macro_env_var/src/lib.rs
@@ -1,5 +1,6 @@
-// Re-export paste so users don't need to depend on it directly
+// Re-export paste and serde so users don't need to depend on them directly
pub use paste;
+pub use serde;
use thiserror::Error;
const APP_SECRETS_JSON_ENV: &str = "APP_SECRETS_JSON";
@@ -220,6 +221,16 @@ macro_rules! env_var {
}
}
}
+
+ impl<'de> $crate::serde::Deserialize<'de> for $n {
+ fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
+ where
+ D: $crate::serde::Deserializer<'de>,
+ {
+ let value = <String as $crate::serde::Deserialize>::deserialize(deserializer)?;
+ Ok(Self::Runtime(std::sync::Arc::from(value)))
+ }
+ }
}
};
(
@@ -389,6 +400,16 @@ macro_rules! maybe_env_var {
}
}
}
+
+ impl<'de> $crate::serde::Deserialize<'de> for $n {
+ fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
+ where
+ D: $crate::serde::Deserializer<'de>,
+ {
+ let value = <String as $crate::serde::Deserialize>::deserialize(deserializer)?;
+ Ok(Self::Runtime(std::sync::Arc::from(value)))
+ }
+ }
}
};
(
diff --git a/rust/cloud-storage/macro_env_var/src/tests.rs b/rust/cloud-storage/macro_env_var/src/tests.rs
index c20a73e51a..a4b59d0512 100644
--- a/rust/cloud-storage/macro_env_var/src/tests.rs
+++ b/rust/cloud-storage/macro_env_var/src/tests.rs
@@ -46,6 +46,14 @@ fn it_should_be_arced() {
assert_eq!(Arc::strong_count(&third), 3);
}
+#[test]
+fn required_env_var_deserializes_from_string() {
+ let v = serde_json::from_str::<TestVar>(r#""from-serde""#).expect("env var deserializes");
+
+ assert_eq!(&*v, "from-serde");
+ assert!(v.runtime_inner().is_some());
+}
+
#[test]
fn required_env_reads_from_app_secrets_json_when_key_exists() {
let value = with_mock_env(
@@ -201,6 +209,15 @@ fn maybe_env_var_can_be_arced() {
assert_eq!(Arc::strong_count(&third), 3);
}
+#[test]
+fn optional_env_var_deserializes_from_string() {
+ let v = serde_json::from_str::<MaybeTestVar>(r#""optional-from-serde""#)
+ .expect("optional env var deserializes");
+
+ assert_eq!(&*v, "optional-from-serde");
+ assert!(v.runtime_inner().is_some());
+}
+
#[test]
fn optional_env_returns_some_from_app_secrets_json_when_key_exists() {
let value = with_mock_env(
diff --git a/rust/cloud-storage/remote_env_var/Cargo.toml b/rust/cloud-storage/remote_env_var/Cargo.toml
index ebf8ab078c..cf07466bfd 100644
--- a/rust/cloud-storage/remote_env_var/Cargo.toml
+++ b/rust/cloud-storage/remote_env_var/Cargo.toml
@@ -6,5 +6,10 @@ version = "0.1.0"
[dependencies]
macro_env = { path = "../macro_env" }
+serde = { workspace = true }
thiserror = { workspace = true }
tracing = { workspace = true }
+
+[dev-dependencies]
+macro_env_var = { path = "../macro_env_var" }
+serde_json = { workspace = true }
diff --git a/rust/cloud-storage/remote_env_var/src/lib.rs b/rust/cloud-storage/remote_env_var/src/lib.rs
index 50967f50ba..525af847ca 100644
--- a/rust/cloud-storage/remote_env_var/src/lib.rs
+++ b/rust/cloud-storage/remote_env_var/src/lib.rs
@@ -6,6 +6,9 @@ use std::sync::Arc;
use macro_env::Environment;
use thiserror::Error;
+#[cfg(test)]
+mod test;
+
/// a trait to abstract away the expected interface for fetching a secret from a remote server
pub trait SecretManager: Send + Sync {
/// The error that can be returned from the server
@@ -76,6 +79,18 @@ where
}
}
+impl<'de, T> serde::Deserialize<'de> for LocalOrRemoteSecret<T>
+where
+ T: serde::Deserialize<'de>,
+{
+ fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
+ where
+ D: serde::Deserializer<'de>,
+ {
+ T::deserialize(deserializer).map(LocalOrRemoteSecret::Local)
+ }
+}
+
impl<T> LocalOrRemoteSecret<T>
where
T: AsRef<str> + Send,
@@ -90,6 +105,29 @@ where
{
secret_manager.get_maybe_secret_value(Environment::new_or_prod(), val)
}
+
+ /// Resolve a locally deserialized secret through a secret manager for the provided environment.
+ ///
+ /// This is useful for values produced by Serde-based config loading: deserialization can only
+ /// construct the local env-var wrapper, while remote secret lookup requires an async secret
+ /// manager.
+ pub async fn resolve_from_secret_manager<S>(
+ self,
+ environment: Environment,
+ secret_manager: &S,
+ ) -> Result<Self, S::Err>
+ where
+ S: SecretManager,
+ {
+ match self {
+ LocalOrRemoteSecret::Local(var) => {
+ secret_manager
+ .get_maybe_secret_value(environment, var)
+ .await
+ }
+ LocalOrRemoteSecret::Remote(secret) => Ok(LocalOrRemoteSecret::Remote(secret)),
+ }
+ }
}
/// Optional variant of [`LocalOrRemoteSecret`]. `None` represents an env var
@@ -99,6 +137,18 @@ where
#[derive(Clone)]
pub struct OptionalLocalOrRemoteSecret<T>(pub Option<LocalOrRemoteSecret<T>>);
+impl<'de, T> serde::Deserialize<'de> for OptionalLocalOrRemoteSecret<T>
+where
+ LocalOrRemoteSecret<T>: serde::Deserialize<'de>,
+{
+ fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
+ where
+ D: serde::Deserializer<'de>,
+ {
+ Option::<LocalOrRemoteSecret<T>>::deserialize(deserializer).map(OptionalLocalOrRemoteSecret)
+ }
+}
+
impl<T> OptionalLocalOrRemoteSecret<T>
where
T: AsRef<str> + Send,
@@ -121,6 +171,26 @@ where
}
}
+ /// Resolve a locally deserialized optional secret through a secret manager for the provided
+ /// environment.
+ pub async fn resolve_from_secret_manager<S>(
+ self,
+ environment: Environment,
+ secret_manager: &S,
+ ) -> Result<Self, S::Err>
+ where
+ S: SecretManager,
+ {
+ match self.0 {
+ Some(secret) => Ok(Self(Some(
+ secret
+ .resolve_from_secret_manager(environment, secret_manager)
+ .await?,
+ ))),
+ None => Ok(Self(None)),
+ }
+ }
+
/// View the resolved secret as `&str`, or `None` when unset.
pub fn as_str(&self) -> Option<&str>
where
diff --git a/rust/cloud-storage/remote_env_var/src/test.rs b/rust/cloud-storage/remote_env_var/src/test.rs
new file mode 100644
index 0000000000..334b5e5621
--- /dev/null
+++ b/rust/cloud-storage/remote_env_var/src/test.rs
@@ -0,0 +1,38 @@
+use super::*;
+
+macro_env_var::env_var! {
+ #[derive(Debug)]
+ struct TestSecretName;
+}
+
+#[test]
+fn local_or_remote_secret_deserializes_macro_env_var_as_local() {
+ let secret = serde_json::from_str::<LocalOrRemoteSecret<TestSecretName>>(r#""secret-name""#)
+ .expect("secret should deserialize");
+
+ match secret {
+ LocalOrRemoteSecret::Local(value) => assert_eq!(value.as_ref(), "secret-name"),
+ LocalOrRemoteSecret::Remote(_) => panic!("deserialized value should be local"),
+ }
+}
+
+#[test]
+fn optional_local_or_remote_secret_deserializes_some_macro_env_var_as_local() {
+ let secret =
+ serde_json::from_str::<OptionalLocalOrRemoteSecret<TestSecretName>>(r#""secret-name""#)
+ .expect("secret should deserialize");
+
+ let Some(LocalOrRemoteSecret::Local(value)) = secret.0 else {
+ panic!("deserialized value should be some local secret");
+ };
+
+ assert_eq!(value.as_ref(), "secret-name");
+}
+
+#[test]
+fn optional_local_or_remote_secret_deserializes_null_as_none() {
+ let secret = serde_json::from_str::<OptionalLocalOrRemoteSecret<TestSecretName>>("null")
+ .expect("secret should deserialize");
+
+ assert!(secret.0.is_none());
+}