Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(config): maybe_env_var should deserialize to Option<T> (#4039)
Will Hutchinsondf681725b2b2
diff --git a/rust/cloud-storage/authentication_service/src/config.rs b/rust/cloud-storage/authentication_service/src/config.rsindex 8818e6904a..6f8fc4bbbd 100644--- a/rust/cloud-storage/authentication_service/src/config.rs+++ b/rust/cloud-storage/authentication_service/src/config.rs@@ -104,19 +104,19 @@ pub struct Config {/// The github idp idpub github_idp_id: GithubIdpId,/// GA4 Measurement ID (optional, e.g., "G-XXXXXXXXXX")- pub ga_measurement_id: Option<GaMeasurementId>,+ pub ga_measurement_id: GaMeasurementId,/// GA4 Measurement Protocol API secret (optional)- pub ga_api_secret: Option<GaApiSecret>,+ pub ga_api_secret: GaApiSecret,/// Meta Pixel ID (optional)- pub meta_pixel_id: Option<MetaPixelId>,+ pub meta_pixel_id: MetaPixelId,/// Meta Conversions API access token (optional)- pub meta_access_token: Option<MetaAccessToken>,+ pub meta_access_token: MetaAccessToken,/// Meta test event code for testing (optional)- pub meta_test_event_code: Option<MetaTestEventCode>,+ pub meta_test_event_code: MetaTestEventCode,/// PostHog API key (optional)- pub posthog_api_key: Option<PosthogApiKey>,+ pub posthog_api_key: PosthogApiKey,/// PostHog host (optional)- pub posthog_host: Option<PosthogHost>,+ pub posthog_host: PosthogHost,/// The stripe price idpub stripe_price_id: StripePriceId,}diff --git a/rust/cloud-storage/authentication_service/src/main.rs b/rust/cloud-storage/authentication_service/src/main.rsindex 5d42132e71..42a3fedc05 100644--- a/rust/cloud-storage/authentication_service/src/main.rs+++ b/rust/cloud-storage/authentication_service/src/main.rs@@ -205,34 +205,35 @@ async fn main() -> anyhow::Result<()> {let analytics_client = AnalyticsClient::new(AnalyticsClientConfig {google_analytics: config.ga_measurement_id- .as_ref()- .zip(config.ga_api_secret.as_ref())+ .value()+ .zip(config.ga_api_secret.value()).map(|(measurement_id, api_secret)| {tracing::info!("configuring Google Analytics");GoogleAnalyticsConfig {- measurement_id: measurement_id.to_string().clone(),- api_secret: api_secret.to_string().clone(),+ measurement_id: measurement_id.to_string(),+ api_secret: api_secret.to_string(),}}),meta: config.meta_pixel_id- .as_ref()- .zip(config.meta_access_token.as_ref())+ .value()+ .zip(config.meta_access_token.value()).map(|(pixel_id, access_token)| {tracing::info!("configuring Meta Conversions API");MetaConfig {- pixel_id: pixel_id.to_string().clone(),- access_token: access_token.to_string().clone(),- test_event_code: config.meta_test_event_code.map(|t| t.to_string()),+ pixel_id: pixel_id.to_string(),+ access_token: access_token.to_string(),+ test_event_code: config.meta_test_event_code.value().map(str::to_string),}}),- posthog: config.posthog_api_key.as_ref().map(|api_key| {+ posthog: config.posthog_api_key.value().map(|api_key| {tracing::info!("configuring PostHog");PostHogConfig {- api_key: api_key.to_string().clone(),+ api_key: api_key.to_string(),host: config.posthog_host- .map(|p| p.to_string())+ .value()+ .map(str::to_string).unwrap_or_else(|| "https://us.i.posthog.com".to_string()),}}),diff --git a/rust/cloud-storage/macro_config/src/test.rs b/rust/cloud-storage/macro_config/src/test.rsindex 82bdbe383b..dcd0b51e2e 100644--- a/rust/cloud-storage/macro_config/src/test.rs+++ b/rust/cloud-storage/macro_config/src/test.rs@@ -242,6 +242,59 @@ fn load_deserializes_macro_env_var_fields() {assert!(config.missing_optional_secret.is_none());}+#[derive(Debug, Deserialize)]+#[serde(rename_all = "SCREAMING_SNAKE_CASE")]+struct BareMaybeEnvVarConfig {+ optional_config_secret: OptionalConfigSecret,+ missing_optional_secret: OptionalConfigSecret,+ null_optional_secret: OptionalConfigSecret,+}++#[test]+fn load_deserializes_bare_maybe_env_var_fields_without_option_wrapper() {+ let _lock = ENV_LOCK.lock().expect("env lock poisoned");+ let env = EnvGuard::new(&[+ "APP_SECRETS_JSON",+ "OPTIONAL_CONFIG_SECRET",+ "MISSING_OPTIONAL_SECRET",+ "NULL_OPTIONAL_SECRET",+ ]);+ env.set("OPTIONAL_CONFIG_SECRET", "optional-secret");+ env.set("NULL_OPTIONAL_SECRET", "null");++ let config = ConfigLoader::load::<BareMaybeEnvVarConfig>().expect("config should load");++ assert_eq!(+ config.optional_config_secret.value(),+ Some("optional-secret")+ );+ assert!(config.optional_config_secret.is_set());+ assert_eq!(config.missing_optional_secret.value(), None);+ assert!(!config.missing_optional_secret.is_set());+ assert_eq!(config.null_optional_secret.value(), None);+}++#[test]+fn load_deserializes_bare_maybe_env_var_fields_from_app_secrets_json() {+ let _lock = ENV_LOCK.lock().expect("env lock poisoned");+ let env = EnvGuard::new(&[+ "APP_SECRETS_JSON",+ "OPTIONAL_CONFIG_SECRET",+ "MISSING_OPTIONAL_SECRET",+ "NULL_OPTIONAL_SECRET",+ ]);+ env.set(+ "APP_SECRETS_JSON",+ r#"{"OPTIONAL_CONFIG_SECRET":"from-json","NULL_OPTIONAL_SECRET":null}"#,+ );++ let config = ConfigLoader::load::<BareMaybeEnvVarConfig>().expect("config should load");++ assert_eq!(config.optional_config_secret.value(), Some("from-json"));+ assert_eq!(config.missing_optional_secret.value(), None);+ assert_eq!(config.null_optional_secret.value(), None);+}+#[test]fn load_deserializes_local_or_remote_macro_env_var_fields() {let _lock = ENV_LOCK.lock().expect("env lock poisoned");diff --git a/rust/cloud-storage/macro_env_var/src/lib.rs b/rust/cloud-storage/macro_env_var/src/lib.rsindex b666e5a8ca..afa2868142 100644--- a/rust/cloud-storage/macro_env_var/src/lib.rs+++ b/rust/cloud-storage/macro_env_var/src/lib.rs@@ -378,6 +378,25 @@ macro_rules! maybe_env_vars {/// // Returns None if OPTIONAL_API_KEY is not set/// let _key: Option<OptionalApiKey> = OptionalApiKey::new();/// ```+///+/// # Deserialization+///+/// When deserialized (for example as a field of a `macro_config::MacroConfig` struct), a missing+/// or `null` value produces the `Unset` variant instead of an error, so the generated type can be+/// used directly as a config field without wrapping it in `Option`. Use `value()` to read it:+///+/// ```+/// use macro_env_var::maybe_env_var;+///+/// maybe_env_var! {+/// pub struct OptionalToken;+/// }+///+/// let set: OptionalToken = serde_json::from_str(r#""abc""#).unwrap();+/// let unset: OptionalToken = serde_json::from_str("null").unwrap();+/// assert_eq!(set.value(), Some("abc"));+/// assert_eq!(unset.value(), None);+/// ```#[macro_export]macro_rules! maybe_env_var {(@@ -387,13 +406,18 @@ macro_rules! maybe_env_var {$crate::paste::paste! {#[doc = "struct which represents the optional `" $n:snake:upper "` environment variable.This returns `Option<Self>` when the variable may or may not be present.+ When deserialized (e.g. by `macro_config`), a missing variable produces [`" $n "`::Unset]+ instead of an error, so this type can be used as a bare config field without wrapping it+ in `Option`. Use [`" $n "`::value] to access the value.See [`" $n "`::new] for usage methods"]$(#[$attr])*$v enum $n {#[doc = "This environment var is allocated and read at runtime"]Runtime(std::sync::Arc<str>),#[doc = "This environment var was present at compile time. It may or may not currently exist at runtime."]- Comptime(&'static str)+ Comptime(&'static str),+ #[doc = "This environment var was not set. Produced by deserialization when the variable is absent or `null`."]+ Unset}impl $n {@@ -421,12 +445,34 @@ macro_rules! maybe_env_var {Self::Comptime(s)}+ #[doc = "Create an instance representing an unset `" $n:snake:upper "` variable"]+ #[allow(dead_code)]+ $v const fn new_unset() -> Self {+ Self::Unset+ }++ #[doc = "Get the value as a string slice, or `None` if the variable was not set"]+ #[allow(dead_code)]+ $v fn value(&self) -> Option<&str> {+ match self {+ Self::Runtime(i) => Some(i),+ Self::Comptime(i) => Some(i),+ Self::Unset => None+ }+ }++ #[doc = "Whether the variable was set"]+ #[allow(dead_code)]+ $v fn is_set(&self) -> bool {+ !matches!(self, Self::Unset)+ }+#[allow(dead_code)]#[doc = "Get a reference to the internal [std::sync::Arc] if this is a runtime allocated env var"]$v fn runtime_inner(&self) -> Option<&std::sync::Arc<str>> {match self {Self::Runtime(i) => Some(i),- Self::Comptime(_) => None+ Self::Comptime(_) | Self::Unset => None}}@@ -435,36 +481,51 @@ macro_rules! maybe_env_var {$v fn comptime_inner(&self) -> Option<&'static str> {match self {Self::Comptime(i) => Some(i),- Self::Runtime(_) => None+ Self::Runtime(_) | Self::Unset => None}}#[allow(dead_code)]- #[doc = "Returns an Arc<str> of the contained value"]- $v fn as_arc(&self) -> std::sync::Arc<str> {+ #[doc = "Returns an Arc<str> of the contained value, or `None` if the variable was not set"]+ $v fn as_arc(&self) -> Option<std::sync::Arc<str>> {match self {- Self::Comptime(i) => std::sync::Arc::from(*i),- Self::Runtime(i) => i.clone()+ Self::Comptime(i) => Some(std::sync::Arc::from(*i)),+ Self::Runtime(i) => Some(i.clone()),+ Self::Unset => None}}}+ #[doc = "Panics when the variable is [`" $n "`::Unset]; use [`" $n "`::value] when the+ value may be unset (e.g. when loaded through `macro_config`)."]impl std::ops::Deref for $n {type Target = str;fn deref(&self) -> &Self::Target {match self {Self::Runtime(i) => &*i,- Self::Comptime(i) => i+ Self::Comptime(i) => i,+ Self::Unset => panic!(concat!(+ "dereferenced unset env var `",+ stringify!([<$n:snake:upper>]),+ "`; use `.value()` to handle the unset case"+ ))}}}+ #[doc = "Panics when the variable is [`" $n "`::Unset]; use [`" $n "`::value] when the+ value may be unset (e.g. when loaded through `macro_config`)."]impl std::convert::AsRef<str> for $n {fn as_ref(&self) -> &str {match self {Self::Runtime(i) => &*i,- Self::Comptime(i) => i+ Self::Comptime(i) => i,+ Self::Unset => panic!(concat!(+ "read unset env var `",+ stringify!([<$n:snake:upper>]),+ "` as a str; use `.value()` to handle the unset case"+ ))}}}@@ -474,8 +535,53 @@ macro_rules! maybe_env_var {whereD: $crate::serde::Deserializer<'de>,{- let value = <String as $crate::serde::Deserialize>::deserialize(deserializer)?;- Ok(Self::Runtime(std::sync::Arc::from(value)))+ struct __MaybeEnvVarVisitor;++ impl<'de> $crate::serde::de::Visitor<'de> for __MaybeEnvVarVisitor {+ type Value = $n;++ fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ formatter.write_str("an optional string")+ }++ fn visit_none<E>(self) -> Result<Self::Value, E>+ where+ E: $crate::serde::de::Error,+ {+ Ok($n::Unset)+ }++ fn visit_unit<E>(self) -> Result<Self::Value, E>+ where+ E: $crate::serde::de::Error,+ {+ Ok($n::Unset)+ }++ fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error>+ where+ D: $crate::serde::Deserializer<'de>,+ {+ let value = <String as $crate::serde::Deserialize>::deserialize(deserializer)?;+ Ok($n::Runtime(std::sync::Arc::from(value)))+ }++ fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>+ where+ E: $crate::serde::de::Error,+ {+ Ok($n::Runtime(std::sync::Arc::from(value)))+ }++ fn visit_string<E>(self, value: String) -> Result<Self::Value, E>+ where+ E: $crate::serde::de::Error,+ {+ Ok($n::Runtime(std::sync::Arc::from(value)))+ }+ }++ deserializer.deserialize_option(__MaybeEnvVarVisitor)}}}diff --git a/rust/cloud-storage/macro_env_var/src/tests.rs b/rust/cloud-storage/macro_env_var/src/tests.rsindex eea10bdb5c..780b3ebc89 100644--- a/rust/cloud-storage/macro_env_var/src/tests.rs+++ b/rust/cloud-storage/macro_env_var/src/tests.rs@@ -248,6 +248,34 @@ fn optional_env_var_deserializes_from_string() {assert_eq!(&*v, "optional-from-serde");assert!(v.runtime_inner().is_some());+ assert_eq!(v.value(), Some("optional-from-serde"));+ assert!(v.is_set());+}++#[test]+fn optional_env_var_deserializes_null_as_unset() {+ let v = serde_json::from_str::<MaybeTestVar>("null").expect("null deserializes as unset");++ assert_eq!(v.value(), None);+ assert!(!v.is_set());+ assert!(v.runtime_inner().is_none());+ assert!(v.comptime_inner().is_none());+ assert!(v.as_arc().is_none());+}++#[test]+fn optional_env_var_new_unset_holds_no_value() {+ let v = MaybeTestVar::new_unset();++ assert_eq!(v.value(), None);+ assert!(!v.is_set());+}++#[test]+#[should_panic(expected = "dereferenced unset env var `MAYBE_TEST_VAR`")]+fn optional_env_var_deref_panics_when_unset() {+ let v = MaybeTestVar::new_unset();+ let _ = &*v;}#[test]