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.

chore(clippy): deny std env var (#4156)

Will Hutchinson9907be48f765
diff --git a/.github/workspace-dep-closures.json b/.github/workspace-dep-closures.json
index 553c3bb9cb..692f3f0b37 100644
--- a/.github/workspace-dep-closures.json
+++ b/.github/workspace-dep-closures.json
@@ -2182,6 +2182,7 @@
],
"load-test": [
"document_cognition_service/load-test",
+ "macro_env_var",
"workspace-hack"
],
"local_e2e_integration_tests": [
@@ -2874,11 +2875,13 @@
"workspace-hack"
],
"native_app_server": [
+ "macro_env_var",
"native_app_service",
"tools/native_app_server",
"workspace-hack"
],
"native_app_service": [
+ "macro_env_var",
"native_app_service",
"workspace-hack"
],
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lock
index e982d19374..2453ca922a 100644
--- a/rust/cloud-storage/Cargo.lock
+++ b/rust/cloud-storage/Cargo.lock
@@ -2006,6 +2006,7 @@ dependencies = [
"macro_aws_config",
"macro_db_migrator",
"macro_entrypoint",
+ "macro_env_var",
"sqlx",
"tokio",
"tracing",
@@ -3172,6 +3173,7 @@ dependencies = [
"lambda_runtime",
"macro_aws_config",
"macro_entrypoint",
+ "macro_env_var",
"s3_client",
"sns_client",
"tokio",
@@ -3235,6 +3237,7 @@ dependencies = [
"aws_lambda_events",
"lambda_runtime",
"macro_entrypoint",
+ "macro_env_var",
"macro_uuid",
"sqlx",
"tokio",
@@ -3257,6 +3260,7 @@ dependencies = [
"macro_db_client",
"macro_entrypoint",
"macro_env",
+ "macro_env_var",
"macro_uuid",
"model",
"serde",
@@ -3770,6 +3774,7 @@ dependencies = [
"lexical_client",
"macro_aws_config",
"macro_entrypoint",
+ "macro_env_var",
"macro_service_urls",
"model",
"s3_key",
@@ -3812,6 +3817,7 @@ dependencies = [
"macro_aws_config",
"macro_db_migrator",
"macro_entrypoint",
+ "macro_env_var",
"macro_service_urls",
"macro_user_id",
"macro_uuid",
@@ -3862,6 +3868,7 @@ dependencies = [
"macro_db_client",
"macro_entrypoint",
"macro_env",
+ "macro_env_var",
"macro_sha_count_client",
"macro_uuid",
"model",
@@ -4168,6 +4175,7 @@ dependencies = [
"macro_db_migrator",
"macro_entrypoint",
"macro_env",
+ "macro_env_var",
"model",
"models_email",
"sqlx",
@@ -4191,6 +4199,7 @@ dependencies = [
"macro_db_migrator",
"macro_entrypoint",
"macro_env",
+ "macro_env_var",
"models_email",
"sqlx",
"sqs_client",
@@ -4317,6 +4326,7 @@ dependencies = [
"macro_aws_config",
"macro_entrypoint",
"macro_env",
+ "macro_env_var",
"sqlx",
"sqs_client",
"tokio",
@@ -4334,6 +4344,7 @@ dependencies = [
"lambda_runtime",
"macro_db_client",
"macro_entrypoint",
+ "macro_env_var",
"serde",
"serde_json",
"sqlx",
@@ -5059,6 +5070,7 @@ dependencies = [
"jsonwebtoken 10.3.0",
"macro_db_migrator",
"macro_env",
+ "macro_env_var",
"macro_service_urls",
"macro_user_id",
"macro_uuid",
@@ -5965,6 +5977,7 @@ dependencies = [
"macro_cors",
"macro_entrypoint",
"macro_env",
+ "macro_env_var",
"macro_middleware",
"model",
"reqwest 0.13.4",
@@ -6627,11 +6640,13 @@ dependencies = [
"anyhow",
"futures",
"http 1.4.0",
+ "macro_env_var",
"reqwest 0.13.4",
"serde",
"serde_json",
"tokio",
"tokio-tungstenite 0.28.0",
+ "tracing",
"tungstenite 0.28.0",
"workspace-hack",
]
@@ -6892,6 +6907,7 @@ version = "0.1.0"
dependencies = [
"dotenvy",
"macro_env",
+ "macro_env_var",
"opentelemetry",
"opentelemetry-otlp",
"opentelemetry_sdk",
@@ -7879,6 +7895,7 @@ name = "native_app_server"
version = "0.1.0"
dependencies = [
"axum",
+ "macro_env_var",
"native_app_service",
"rootcause",
"semver",
@@ -7898,6 +7915,7 @@ dependencies = [
"axum",
"cool_asserts",
"futures",
+ "macro_env_var",
"reqwest 0.13.4",
"rootcause",
"semver",
@@ -8616,6 +8634,7 @@ dependencies = [
"lambda_runtime",
"macro_aws_config",
"macro_entrypoint",
+ "macro_env_var",
"sqlx",
"sqs_client",
"tokio",
@@ -8633,6 +8652,7 @@ dependencies = [
"lambda_runtime",
"macro_aws_config",
"macro_entrypoint",
+ "macro_env_var",
"serde_json",
"sqlx",
"sqs_client",
@@ -10670,6 +10690,7 @@ dependencies = [
"macro_db_client",
"macro_entrypoint",
"macro_env",
+ "macro_env_var",
"macro_middleware",
"macro_service_urls",
"macro_user_id",
@@ -10727,6 +10748,7 @@ dependencies = [
"macro_aws_config",
"macro_db_client",
"macro_env",
+ "macro_env_var",
"macro_middleware",
"macro_user_id",
"model",
@@ -10777,6 +10799,7 @@ dependencies = [
"lambda_runtime",
"macro_aws_config",
"macro_entrypoint",
+ "macro_env_var",
"macro_service_urls",
"s3_key",
"sqs_client",
@@ -11213,6 +11236,7 @@ dependencies = [
"macro_aws_config",
"macro_entrypoint",
"macro_env",
+ "macro_env_var",
"mockall",
"redis",
"sqlx",
@@ -11788,6 +11812,7 @@ dependencies = [
"macro_cors",
"macro_entrypoint",
"macro_env",
+ "macro_env_var",
"macro_middleware",
"macro_service_urls",
"model",
@@ -12850,6 +12875,7 @@ dependencies = [
"macro_cors",
"macro_entrypoint",
"macro_env",
+ "macro_env_var",
"reqwest 0.13.4",
"scraper",
"serde",
@@ -12965,6 +12991,7 @@ dependencies = [
"lambda_runtime",
"macro_aws_config",
"macro_entrypoint",
+ "macro_env_var",
"macro_service_urls",
"model",
"model-entity",
@@ -12994,6 +13021,7 @@ dependencies = [
"lambda_runtime",
"macro_aws_config",
"macro_entrypoint",
+ "macro_env_var",
"models_bulk_upload",
"s3_key",
"serde",
@@ -13034,10 +13062,12 @@ dependencies = [
"lambda_runtime",
"macro_db_client",
"macro_entrypoint",
+ "macro_env_var",
"serde",
"serde_json",
"sqlx",
"tokio",
+ "tracing",
"workspace-hack",
]
@@ -13934,6 +13964,7 @@ dependencies = [
"macro_aws_config",
"macro_entrypoint",
"macro_env",
+ "macro_env_var",
"mockall",
"serde_json",
"tokio",
diff --git a/rust/cloud-storage/anthropic/Cargo.toml b/rust/cloud-storage/anthropic/Cargo.toml
index 12dd1d1d55..517415492d 100644
--- a/rust/cloud-storage/anthropic/Cargo.toml
+++ b/rust/cloud-storage/anthropic/Cargo.toml
@@ -17,6 +17,7 @@ rand = { workspace = true }
tokio = { workspace = true, features = ["sync"]}
async-stream = { workspace = true }
futures = { workspace = true }
+macro_env_var = { path = "../macro_env_var" }
reqwest = { workspace = true, features = ["stream"] }
tokio-util = { workspace = true, features = ["io"] }
schemars = { workspace = true }
@@ -33,4 +34,3 @@ ai_toolset = { path = "../ai_toolset", optional = true }
async-trait = { workspace = true, optional = true }
anyhow = { workspace = true, optional = true }
workspace-hack = { version = "0.1", path = "../workspace-hack" }
-macro_env_var = { path = "../macro_env_var" }
diff --git a/rust/cloud-storage/anthropic/src/config.rs b/rust/cloud-storage/anthropic/src/config.rs
index 149c2021fc..eda92e7597 100644
--- a/rust/cloud-storage/anthropic/src/config.rs
+++ b/rust/cloud-storage/anthropic/src/config.rs
@@ -1,18 +1,18 @@
-use macro_env_var::env_var;
+use macro_env_var::env_vars;
use reqwest::header::HeaderMap;
const ANTHROPIC_ROUTER_BASE_URL: &str = "https://api.anthropic.com";
+env_vars! {
+ struct AnthropicApiKey;
+}
+
#[derive(Debug, Clone, Default)]
pub struct Config {
pub api_base: String,
pub headers: HeaderMap,
}
-env_var! {
- pub struct AnthropicApiKey;
-}
-
impl Config {
pub fn dangrously_try_from_env() -> Self {
let api_key = AnthropicApiKey::new().expect("api key");
diff --git a/rust/cloud-storage/authentication_service/src/api/utils.rs b/rust/cloud-storage/authentication_service/src/api/utils.rs
index 9f479925b1..1ef8bb4c2c 100644
--- a/rust/cloud-storage/authentication_service/src/api/utils.rs
+++ b/rust/cloud-storage/authentication_service/src/api/utils.rs
@@ -1,9 +1,14 @@
use cookie::{Cookie, SameSite};
use macro_auth::constant::{MACRO_ACCESS_TOKEN_COOKIE, MACRO_REFRESH_TOKEN_COOKIE};
use macro_env::Environment;
+use macro_env_var::maybe_env_vars;
use rand::{Rng, seq::SliceRandom};
use url::Url;
+maybe_env_vars! {
+ struct FrontendPort;
+}
+
/// Generates a random 25 character session code
pub fn generate_session_code() -> String {
const CHARSET_LOWER: &[u8] = b"abcdefghijklmnopqrstuvwxyz";
@@ -43,7 +48,9 @@ pub fn generate_session_code() -> String {
pub fn default_redirect_url() -> Url {
match Environment::new_or_prod() {
Environment::Local => {
- let port = std::env::var("FRONTEND_PORT").unwrap_or_else(|_| "3000".to_string());
+ let port = FrontendPort::new()
+ .map(|port| port.to_string())
+ .unwrap_or_else(|| "3000".to_string());
format!("http://localhost:{port}").parse().unwrap()
}
Environment::Develop => "https://dev.macro.com/app".parse().unwrap(),
diff --git a/rust/cloud-storage/call_recording_preview_handler/Cargo.toml b/rust/cloud-storage/call_recording_preview_handler/Cargo.toml
index 5995800379..8a0771e0f4 100644
--- a/rust/cloud-storage/call_recording_preview_handler/Cargo.toml
+++ b/rust/cloud-storage/call_recording_preview_handler/Cargo.toml
@@ -17,6 +17,7 @@ tracing = { workspace = true }
urlencoding = { workspace = true }
uuid = { workspace = true }
workspace-hack = { version = "0.1", path = "../workspace-hack" }
+macro_env_var = { path = "../macro_env_var" }
[dev-dependencies]
macro_db_migrator = { path = "../macro_db_migrator" }
diff --git a/rust/cloud-storage/call_recording_preview_handler/src/event.rs b/rust/cloud-storage/call_recording_preview_handler/src/event.rs
index 7b9c71e806..6225c079e6 100644
--- a/rust/cloud-storage/call_recording_preview_handler/src/event.rs
+++ b/rust/cloud-storage/call_recording_preview_handler/src/event.rs
@@ -4,6 +4,7 @@ use anyhow::{Context, bail};
use aws_lambda_events::event::s3::{S3Event, S3EventRecord};
use aws_sdk_s3::{Client as S3Client, primitives::ByteStream};
use lambda_runtime::{Error, LambdaEvent};
+use macro_env_var::env_vars;
use sqlx::{PgPool, Postgres};
use tracing::Instrument;
@@ -21,6 +22,10 @@ pub struct HandlerConfig {
presigned_url_duration: Duration,
}
+env_vars! {
+ pub struct CallRecordingBucketName;
+}
+
impl HandlerConfig {
/// Builds handler configuration from environment variables.
///
@@ -34,9 +39,10 @@ impl HandlerConfig {
let ffprobe_path = std::env::var_os("FFPROBE_PATH")
.map(PathBuf::from)
.unwrap_or_else(|| PathBuf::from("/opt/bin/ffprobe"));
- let default_bucket_name = std::env::var("CALL_RECORDING_BUCKET_NAME")
+ let default_bucket_name = CallRecordingBucketName::new()
.ok()
- .filter(|bucket| !bucket.trim().is_empty());
+ .filter(|bucket| !bucket.trim().is_empty())
+ .map(|d| d.to_string());
Self {
ffmpeg_path,
diff --git a/rust/cloud-storage/call_recording_preview_handler/src/main.rs b/rust/cloud-storage/call_recording_preview_handler/src/main.rs
index 0400884c90..a1c1b9f5e9 100644
--- a/rust/cloud-storage/call_recording_preview_handler/src/main.rs
+++ b/rust/cloud-storage/call_recording_preview_handler/src/main.rs
@@ -5,8 +5,13 @@ use aws_lambda_events::event::s3::S3Event;
use call_recording_preview_handler::{HandlerConfig, HandlerState, handler};
use lambda_runtime::{Error, LambdaEvent, run, service_fn, tracing};
use macro_entrypoint::MacroEntrypoint;
+use macro_env_var::env_vars;
use sqlx::postgres::PgPoolOptions;
+env_vars! {
+ struct DatabaseUrl;
+}
+
#[tokio::main]
async fn main() -> Result<(), Error> {
MacroEntrypoint::default().init();
@@ -14,11 +19,11 @@ async fn main() -> Result<(), Error> {
tracing::trace!("initiating call recording preview lambda");
let config = HandlerConfig::from_env();
- let database_url = std::env::var("DATABASE_URL").context("DATABASE_URL must be provided")?;
+ let database_url = DatabaseUrl::new().context("DATABASE_URL must be provided")?;
let db = PgPoolOptions::new()
.min_connections(1)
.max_connections(1)
- .connect(&database_url)
+ .connect(database_url.as_ref())
.await
.context("could not connect to db")?;
diff --git a/rust/cloud-storage/clippy.toml b/rust/cloud-storage/clippy.toml
index 17c472482d..4d00424fc8 100644
--- a/rust/cloud-storage/clippy.toml
+++ b/rust/cloud-storage/clippy.toml
@@ -1,4 +1,5 @@
disallowed-methods = [
+ { path = "std::env::var", reason = "use macro_env_var so APP_SECRETS_JSON is honored" },
{ path = "sqlx::query", replacement = "sqlx::query!" },
{ path = "sqlx::query_as", replacement = "sqlx::query_as!" },
{ path = "sqlx::query_scalar", replacement = "sqlx::query_scalar!" },
diff --git a/rust/cloud-storage/connection_gateway/scripts/stale_connections.rs b/rust/cloud-storage/connection_gateway/scripts/stale_connections.rs
index e00bce30f7..ed47668fbe 100644
--- a/rust/cloud-storage/connection_gateway/scripts/stale_connections.rs
+++ b/rust/cloud-storage/connection_gateway/scripts/stale_connections.rs
@@ -1,11 +1,17 @@
//! This entrypoint is used to periodically clean up stale connections from the db
use aws_sdk_dynamodb::types::AttributeValue;
use chrono::{DateTime, Utc};
+use macro_env_var::maybe_env_vars;
use std::collections::HashMap;
use std::time::{SystemTime, UNIX_EPOCH};
const DEFAULT_TIMEOUT_THRESHOLD: u64 = 60_000; // 60 seconds in milliseconds
+maybe_env_vars! {
+ struct ConnectionGatewayTable;
+ struct DeleteStale;
+}
+
#[derive(Debug, Clone)]
#[allow(dead_code, unused)]
struct ConnectionInfo {
@@ -114,10 +120,10 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
// Get table name from environment variable or command line argument
let table_name = std::env::args()
.nth(1)
- .or_else(|| std::env::var("CONNECTION_GATEWAY_TABLE").ok())
+ .or_else(|| ConnectionGatewayTable::new().map(|table| table.to_string()))
.expect("Please provide table name as argument or set CONNECTION_GATEWAY_TABLE env var");
- let delete_mode = std::env::var("DELETE_STALE").is_ok();
+ let delete_mode = DeleteStale::new().is_some();
println!("Scanning table: {}", table_name);
println!(
diff --git a/rust/cloud-storage/dataloss_prevention_handler/Cargo.toml b/rust/cloud-storage/dataloss_prevention_handler/Cargo.toml
index 877d3042f3..ae1de01b55 100644
--- a/rust/cloud-storage/dataloss_prevention_handler/Cargo.toml
+++ b/rust/cloud-storage/dataloss_prevention_handler/Cargo.toml
@@ -13,6 +13,7 @@ aws-sdk-sns = { workspace = true }
aws_lambda_events = { workspace = true, features = ["s3"] }
lambda_runtime = { workspace = true }
macro_entrypoint = { path = "../macro_entrypoint" }
+macro_env_var = { path = "../macro_env_var" }
s3_client = { path = "../s3_client" }
sns_client = { path = "../sns_client" }
tokio = { workspace = true }
diff --git a/rust/cloud-storage/dataloss_prevention_handler/src/main.rs b/rust/cloud-storage/dataloss_prevention_handler/src/main.rs
index 167a3f4f24..aad1c7a93b 100644
--- a/rust/cloud-storage/dataloss_prevention_handler/src/main.rs
+++ b/rust/cloud-storage/dataloss_prevention_handler/src/main.rs
@@ -5,9 +5,14 @@ use lambda_runtime::{
tracing::{self},
};
use macro_entrypoint::MacroEntrypoint;
+use macro_env_var::env_vars;
mod handler;
+env_vars! {
+ struct SnsTopicArn;
+}
+
#[tokio::main]
async fn main() -> Result<(), Error> {
MacroEntrypoint::default().init();
@@ -22,7 +27,9 @@ async fn main() -> Result<(), Error> {
let sns_client = sns_client::SNS::new(aws_sdk_sns::Client::new(&aws_config));
tracing::trace!("initialized sns client");
- let topic_arn = std::env::var("SNS_TOPIC_ARN").context("SNS_TOPIC_ARN is required")?;
+ let topic_arn = SnsTopicArn::new()
+ .context("SNS_TOPIC_ARN is required")?
+ .to_string();
let shared_s3_client = &s3_client;
let shared_sns_client = &sns_client;
diff --git a/rust/cloud-storage/decode_jwt/src/lib.rs b/rust/cloud-storage/decode_jwt/src/lib.rs
index 1711385ce2..d07d1940b3 100644
--- a/rust/cloud-storage/decode_jwt/src/lib.rs
+++ b/rust/cloud-storage/decode_jwt/src/lib.rs
@@ -86,6 +86,7 @@ impl DecodedJwt {
query_params: Params,
jwt_validation_args: &JwtValidationArgs,
) -> Result<DecodedJwt, DecodeJwtError> {
+ #[expect(clippy::disallowed_methods, reason = "Only used when running locally")]
if cfg!(feature = "local_auth") && std::env::var("LOCAL_USER_ID").is_ok() {
let user_id =
std::env::var("LOCAL_USER_ID").unwrap_or("macro|[email protected]".to_string());
diff --git a/rust/cloud-storage/delete_chat_handler/Cargo.toml b/rust/cloud-storage/delete_chat_handler/Cargo.toml
index f28672edbb..0954fbe4cd 100644
--- a/rust/cloud-storage/delete_chat_handler/Cargo.toml
+++ b/rust/cloud-storage/delete_chat_handler/Cargo.toml
@@ -9,6 +9,7 @@ anyhow = { workspace = true }
aws_lambda_events = { workspace = true, features = ["sqs"] }
lambda_runtime = { workspace = true }
macro_entrypoint = { path = "../macro_entrypoint" }
+macro_env_var = { path = "../macro_env_var" }
macro_uuid = { path = "../macro_uuid" }
sqlx = { workspace = true }
tokio = { workspace = true }
diff --git a/rust/cloud-storage/delete_chat_handler/src/main.rs b/rust/cloud-storage/delete_chat_handler/src/main.rs
index e33752aad1..03b8b73f96 100644
--- a/rust/cloud-storage/delete_chat_handler/src/main.rs
+++ b/rust/cloud-storage/delete_chat_handler/src/main.rs
@@ -7,20 +7,25 @@ use aws_lambda_events::sqs::SqsEvent;
use handler::handler;
use lambda_runtime::{Error, LambdaEvent, run, service_fn, tracing};
use macro_entrypoint::MacroEntrypoint;
+use macro_env_var::env_vars;
use sqlx::postgres::PgPoolOptions;
+env_vars! {
+ struct DatabaseUrl;
+}
+
#[tokio::main]
async fn main() -> Result<(), Error> {
MacroEntrypoint::default().init();
tracing::trace!("initiating lambda");
- let database_url = std::env::var("DATABASE_URL").context("DATABASE_URL must be provided")?;
+ let database_url = DatabaseUrl::new().context("DATABASE_URL must be provided")?;
let db = service::db::DB::new(
PgPoolOptions::new()
.min_connections(1)
.max_connections(1) // we only ever need one connection per lambda
- .connect(&database_url)
+ .connect(database_url.as_ref())
.await
.context("could not connect to db")?,
);
diff --git a/rust/cloud-storage/deleted_item_poller/Cargo.toml b/rust/cloud-storage/deleted_item_poller/Cargo.toml
index a69f453485..1566e4305f 100644
--- a/rust/cloud-storage/deleted_item_poller/Cargo.toml
+++ b/rust/cloud-storage/deleted_item_poller/Cargo.toml
@@ -16,6 +16,7 @@ lambda_runtime = { workspace = true }
macro_db_client = { path = "../macro_db_client" }
macro_entrypoint = { path = "../macro_entrypoint" }
macro_env = { path = "../macro_env" }
+macro_env_var = { path = "../macro_env_var" }
macro_uuid = { path = "../macro_uuid" }
model = { path = "../model" }
serde = { workspace = true }
diff --git a/rust/cloud-storage/deleted_item_poller/src/config.rs b/rust/cloud-storage/deleted_item_poller/src/config.rs
index 015dc9b148..1471f78471 100644
--- a/rust/cloud-storage/deleted_item_poller/src/config.rs
+++ b/rust/cloud-storage/deleted_item_poller/src/config.rs
@@ -1,5 +1,13 @@
use anyhow::Context;
pub use macro_env::Environment;
+use macro_env_var::env_vars;
+
+env_vars! {
+ struct DatabaseUrl;
+ struct DocumentDeleteQueue;
+ struct ChatDeleteQueue;
+ struct SearchEventQueue;
+}
#[derive(Debug, Clone)]
pub struct Config {
@@ -22,17 +30,21 @@ pub struct Config {
impl Config {
pub fn from_env() -> anyhow::Result<Self> {
- let database_url =
- std::env::var("DATABASE_URL").context("DATABASE_URL must be provided")?;
+ let database_url = DatabaseUrl::new()
+ .context("DATABASE_URL must be provided")?
+ .to_string();
- let document_delete_queue = std::env::var("DOCUMENT_DELETE_QUEUE")
- .context("DOCUMENT_DELETE_QUEUE must be provided")?;
+ let document_delete_queue = DocumentDeleteQueue::new()
+ .context("DOCUMENT_DELETE_QUEUE must be provided")?
+ .to_string();
- let chat_delete_queue =
- std::env::var("CHAT_DELETE_QUEUE").context("CHAT_DELETE_QUEUE must be provided")?;
+ let chat_delete_queue = ChatDeleteQueue::new()
+ .context("CHAT_DELETE_QUEUE must be provided")?
+ .to_string();
- let search_event_queue =
- std::env::var("SEARCH_EVENT_QUEUE").context("SEARCH_EVENT_QUEUE must be provided")?;
+ let search_event_queue = SearchEventQueue::new()
+ .context("SEARCH_EVENT_QUEUE must be provided")?
+ .to_string();
Ok(Config {
database_url,
diff --git a/rust/cloud-storage/document_cognition_service/load-test/Cargo.toml b/rust/cloud-storage/document_cognition_service/load-test/Cargo.toml
index 6566b808a5..75d0ac45d2 100644
--- a/rust/cloud-storage/document_cognition_service/load-test/Cargo.toml
+++ b/rust/cloud-storage/document_cognition_service/load-test/Cargo.toml
@@ -8,10 +8,12 @@ version = "0.1.0"
anyhow = { workspace = true }
futures = { workspace = true }
http = { workspace = true }
+macro_env_var = { path = "../../macro_env_var" }
reqwest = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
tokio = { workspace = true }
tokio-tungstenite = { workspace = true, default-features = false, features = ["connect", "rustls-tls-webpki-roots"] }
+tracing = { workspace = true }
tungstenite = { workspace = true }
workspace-hack = { version = "0.1", path = "../../workspace-hack" }
diff --git a/rust/cloud-storage/document_cognition_service/load-test/src/main.rs b/rust/cloud-storage/document_cognition_service/load-test/src/main.rs
index 770261d435..6cf6b0bedf 100644
--- a/rust/cloud-storage/document_cognition_service/load-test/src/main.rs
+++ b/rust/cloud-storage/document_cognition_service/load-test/src/main.rs
@@ -2,22 +2,25 @@ mod config;
use anyhow::{Context, Result};
use futures::{SinkExt, StreamExt};
use http::uri::Uri;
+use macro_env_var::env_vars;
use serde::{Deserialize, Serialize};
use std::{sync::Arc, time::Duration};
use tokio_tungstenite::{connect_async, tungstenite::Message};
use tungstenite::ClientRequestBuilder;
+env_vars! {
+ struct Token;
+}
+
/// Returns a chat id of a newly created chat
async fn create_chat(config: Arc<config::Config>) -> anyhow::Result<String> {
let client = reqwest::Client::new();
+ let token = Token::new().context("TOKEN must be provided")?;
let response = client
.post(format!("https://{}/chats", config.base_url))
.header(reqwest::header::CONTENT_TYPE, "application/json")
- .header(
- "Authorization",
- format!("Bearer {}", std::env::var("TOKEN").unwrap()),
- )
+ .header("Authorization", format!("Bearer {}", token.as_ref()))
.body(r#"{}"#)
.send()
.await?
@@ -34,14 +37,12 @@ async fn create_chat(config: Arc<config::Config>) -> anyhow::Result<String> {
/// deletes a chat given the chat id
async fn delete_chat(config: &config::Config, chat_id: &str) -> anyhow::Result<()> {
let client = reqwest::Client::new();
+ let token = Token::new().context("TOKEN must be provided")?;
client
.delete(format!("https://{}/chats/{}", config.base_url, chat_id))
.header(reqwest::header::CONTENT_TYPE, "application/json")
- .header(
- "Authorization",
- format!("Bearer {}", std::env::var("TOKEN").unwrap()),
- )
+ .header("Authorization", format!("Bearer {}", token.as_ref()))
.send()
.await?
.json::<serde_json::Value>()
@@ -77,13 +78,11 @@ async fn connection(config: Arc<config::Config>) -> Result<ConnectionReport> {
let mut times_to_acknowledge = Vec::new();
let mut times_to_finish = Vec::new();
let chat_id = create_chat(config.clone()).await?;
+ let token = Token::new().context("TOKEN must be provided")?;
let req =
ClientRequestBuilder::new("wss://document-cognition-dev.macro.com/stream".parse::<Uri>()?)
- .with_header(
- "Authorization",
- format!("Bearer {}", std::env::var("TOKEN").unwrap()),
- );
+ .with_header("Authorization", format!("Bearer {}", token.as_ref()));
let (ws_stream, _) = connect_async(req).await?;
let (mut wx, mut rx) = ws_stream.split();
@@ -266,9 +265,7 @@ async fn main() -> anyhow::Result<()> {
.context("ERROR: expected load config path in args. eg: `cargo run -- config.json`")?
.to_string();
- if std::env::var("TOKEN").is_err() {
- anyhow::bail!("please set `TOKEN` env var with your macro-token");
- }
+ Token::new().context("please set `TOKEN` env var with your macro-token")?;
let config = Arc::new(config::read(&config_path)?);
let chat_id = create_chat(config.clone()).await.unwrap();
diff --git a/rust/cloud-storage/document_cognition_service/src/api/completions.rs b/rust/cloud-storage/document_cognition_service/src/api/completions.rs
index cc29743b78..b2f91861a9 100644
--- a/rust/cloud-storage/document_cognition_service/src/api/completions.rs
+++ b/rust/cloud-storage/document_cognition_service/src/api/completions.rs
@@ -1,7 +1,12 @@
use axum::{extract, response::IntoResponse};
+use macro_env_var::maybe_env_vars;
const OPENAI_CHAT_COMPLETIONS_URL: &str = "https://api.openai.com/v1/chat/completions";
+maybe_env_vars! {
+ struct OpenaiApiKey;
+}
+
/// A non-streaming proxy to the chatgpt api
#[tracing::instrument(err(Debug), skip(body))]
pub async fn handler(
@@ -11,7 +16,9 @@ pub async fn handler(
obj.insert("stream".to_string(), serde_json::Value::Bool(false));
}
- let api_key = std::env::var("OPENAI_API_KEY").unwrap_or_default();
+ let api_key = OpenaiApiKey::new()
+ .map(|api_key| api_key.to_string())
+ .unwrap_or_default();
let response = reqwest::Client::new()
.post(OPENAI_CHAT_COMPLETIONS_URL)
diff --git a/rust/cloud-storage/document_storage_service/src/main.rs b/rust/cloud-storage/document_storage_service/src/main.rs
index 3602142f3d..bc3c27cde7 100644
--- a/rust/cloud-storage/document_storage_service/src/main.rs
+++ b/rust/cloud-storage/document_storage_service/src/main.rs
@@ -70,6 +70,7 @@ use github::outbound::pg_github_sync_repo::PgGithubSyncRepo;
use lexical_client::LexicalClient;
use macro_auth::middleware::decode_jwt::JwtValidationArgs;
use macro_entrypoint::MacroEntrypoint;
+use macro_env_var::maybe_env_vars;
use macro_service_urls::{ConnectionGatewayUrl, LexicalServiceUrl, SyncServiceUrl};
use macro_sha_count_client::Redis;
use notification::domain::service::SqsNotificationIngress;
@@ -102,6 +103,11 @@ mod config;
mod model;
mod service;
+maybe_env_vars! {
+ struct AppleBundleId;
+ struct SnsApnsVoipPlatformArn;
+}
+
#[tokio::main]
async fn main() -> anyhow::Result<()> {
MacroEntrypoint::default().init();
@@ -483,10 +489,9 @@ async fn main() -> anyhow::Result<()> {
//
// Option<VoipPushServiceImpl<...>> is used as the type parameter so the
// type stays stable regardless of whether VoIP push is configured.
- let voip_sender = if let (Ok(bundle_id), Ok(voip_arn)) = (
- std::env::var("APPLE_BUNDLE_ID"),
- std::env::var("SNS_APNS_VOIP_PLATFORM_ARN"),
- ) {
+ let voip_sender = if let (Some(bundle_id), Some(voip_arn)) =
+ (AppleBundleId::new(), SnsApnsVoipPlatformArn::new())
+ {
if voip_arn.is_empty() {
tracing::warn!("voip push disabled: SNS_APNS_VOIP_PLATFORM_ARN is set but empty");
None
@@ -495,10 +500,14 @@ async fn main() -> anyhow::Result<()> {
notification::outbound::repository::DbNotificationRepository::new(db.clone());
let voip_mobile = notification::outbound::mobile::MobilePushAdapter {
push_service: aws_sdk_sns::Client::new(&aws_config),
- apns_bundle_id: bundle_id.clone(),
- voip_bundle_id: Some(format!("{}.voip", bundle_id)),
+ apns_bundle_id: bundle_id.to_string(),
+ voip_bundle_id: Some(format!("{}.voip", bundle_id.as_ref())),
};
- tracing::info!(bundle_id, voip_arn, "voip push enabled");
+ tracing::info!(
+ bundle_id = bundle_id.as_ref(),
+ voip_arn = voip_arn.as_ref(),
+ "voip push enabled"
+ );
Some(notification::domain::service::VoipPushServiceImpl::new(
voip_repo,
voip_mobile,
diff --git a/rust/cloud-storage/document_upload_finalizer_handler/Cargo.toml b/rust/cloud-storage/document_upload_finalizer_handler/Cargo.toml
index 060a205cf4..949fe2eb8a 100644
--- a/rust/cloud-storage/document_upload_finalizer_handler/Cargo.toml
+++ b/rust/cloud-storage/document_upload_finalizer_handler/Cargo.toml
@@ -18,6 +18,7 @@ lambda_runtime = { workspace = true }
lexical_client = { path = "../lexical_client" }
macro_aws_config = { path = "../macro_aws_config", features = ["s3"] }
macro_entrypoint = { path = "../macro_entrypoint" }
+macro_env_var = { path = "../macro_env_var" }
model = { path = "../model" }
s3_key = { path = "../s3_key" }
macro_service_urls = { path = "../macro_service_urls" }
diff --git a/rust/cloud-storage/document_upload_finalizer_handler/src/inbound/local_sqs.rs b/rust/cloud-storage/document_upload_finalizer_handler/src/inbound/local_sqs.rs
index 682da31a75..2c180f6ec9 100644
--- a/rust/cloud-storage/document_upload_finalizer_handler/src/inbound/local_sqs.rs
+++ b/rust/cloud-storage/document_upload_finalizer_handler/src/inbound/local_sqs.rs
@@ -4,6 +4,7 @@ use std::time::Duration;
use anyhow::Context as _;
use aws_sdk_sqs::types::Message;
use lambda_runtime::tracing;
+use macro_env_var::maybe_env_vars;
use crate::AppContext;
use crate::inbound::s3_notification::object_created_events_from_body;
@@ -11,18 +12,25 @@ use crate::inbound::s3_notification::object_created_events_from_body;
const LOCALSTACK_ACCOUNT_ID: &str = "000000000000";
const QUEUE_NAME: &str = "document-upload-finalizer-queue";
+maybe_env_vars! {
+ struct DocumentUploadFinalizerQueueUrl;
+ struct LocalAwsUrl;
+}
+
/// Run the LocalStack SQS polling adapter.
pub async fn run_local_sqs_worker(context: Arc<AppContext>) -> Result<(), anyhow::Error> {
- let queue_url = std::env::var("DOCUMENT_UPLOAD_FINALIZER_QUEUE_URL")
- .unwrap_or_else(|_| default_queue_url());
+ let queue_url = DocumentUploadFinalizerQueueUrl::new()
+ .map(|queue_url| queue_url.to_string())
+ .unwrap_or_else(default_queue_url);
let sqs_client = aws_sdk_sqs::Client::new(&macro_aws_config::get_macro_aws_config().await);
poll_forever(context, sqs_client, queue_url).await
}
fn default_queue_url() -> String {
- let local_aws_url =
- std::env::var("LOCAL_AWS_URL").unwrap_or_else(|_| "http://localstack:4566".to_string());
+ let local_aws_url = LocalAwsUrl::new()
+ .map(|local_aws_url| local_aws_url.to_string())
+ .unwrap_or_else(|| "http://localstack:4566".to_string());
format!(
"{}/{LOCALSTACK_ACCOUNT_ID}/{QUEUE_NAME}",
local_aws_url.trim_end_matches('/')
diff --git a/rust/cloud-storage/document_upload_finalizer_handler/src/runtime.rs b/rust/cloud-storage/document_upload_finalizer_handler/src/runtime.rs
index 737a112048..23e25d73f6 100644
--- a/rust/cloud-storage/document_upload_finalizer_handler/src/runtime.rs
+++ b/rust/cloud-storage/document_upload_finalizer_handler/src/runtime.rs
@@ -2,6 +2,7 @@ use anyhow::Context as _;
use documents::outbound::markdown_init::LexicalSyncMarkdownInitializer;
use documents::outbound::pg_document_repo::PgDocumentRepo;
use lexical_client::LexicalClient;
+use macro_env_var::env_vars;
use macro_service_urls::{LexicalServiceUrl, SyncServiceUrl};
use sqlx::postgres::PgPoolOptions;
use sync_service_client::SyncServiceClient;
@@ -9,6 +10,12 @@ use sync_service_client::SyncServiceClient;
use crate::app::{DocumentUploadFinalizer, ObjectCreated};
use crate::outbound::{PgDocumentUploadPort, S3DocumentObjectReader};
+env_vars! {
+ struct DatabaseUrl;
+ struct InternalApiSecretKey;
+ struct SyncServiceAuthKey;
+}
+
/// Concrete app context used by Lambda and local worker entrypoints.
pub struct AppContext {
finalizer: DocumentUploadFinalizer<PgDocumentUploadPort, S3DocumentObjectReader>,
@@ -19,18 +26,19 @@ pub struct AppContext {
impl AppContext {
/// Build the shared finalizer context from environment variables.
pub async fn from_env() -> Result<Self, anyhow::Error> {
- let database_url =
- std::env::var("DATABASE_URL").context("DATABASE_URL must be provided")?;
- let internal_api_secret = std::env::var("INTERNAL_API_SECRET_KEY")
- .context("INTERNAL_API_SECRET_KEY must be provided")?;
- let sync_service_auth_key = std::env::var("SYNC_SERVICE_AUTH_KEY")
- .context("SYNC_SERVICE_AUTH_KEY must be provided")?;
+ let database_url = DatabaseUrl::new().context("DATABASE_URL must be provided")?;
+ let internal_api_secret = InternalApiSecretKey::new()
+ .context("INTERNAL_API_SECRET_KEY must be provided")?
+ .to_string();
+ let sync_service_auth_key = SyncServiceAuthKey::new()
+ .context("SYNC_SERVICE_AUTH_KEY must be provided")?
+ .to_string();
let lexical_service_url = LexicalServiceUrl::new()?.to_string();
let sync_service_url = SyncServiceUrl::new()?.to_string();
let db_pool = PgPoolOptions::new()
.max_connections(5)
- .connect(&database_url)
+ .connect(database_url.as_ref())
.await
.context("failed to connect to postgres")?;
diff --git a/rust/cloud-storage/documents/Cargo.toml b/rust/cloud-storage/documents/Cargo.toml
index 1d5cb41557..65c77711ed 100644
--- a/rust/cloud-storage/documents/Cargo.toml
+++ b/rust/cloud-storage/documents/Cargo.toml
@@ -97,6 +97,7 @@ foreign_entity = { path = "../foreign_entity", default-features = false, feature
], optional = true }
macro_aws_config = { path = "../macro_aws_config", features = ["s3"] }
macro_entrypoint = { path = "../macro_entrypoint", optional = true }
+macro_env_var = { path = "../macro_env_var" }
macro_user_id = { path = "../macro_user_id" }
macro_uuid = { path = "../macro_uuid" }
model = { path = "../model" }
diff --git a/rust/cloud-storage/documents/src/bin/backfill_markdown_content_location.rs b/rust/cloud-storage/documents/src/bin/backfill_markdown_content_location.rs
index 44c013667e..527efc453e 100644
--- a/rust/cloud-storage/documents/src/bin/backfill_markdown_content_location.rs
+++ b/rust/cloud-storage/documents/src/bin/backfill_markdown_content_location.rs
@@ -1,6 +1,6 @@
//! CLI for markdown document content lifecycle backfill.
-use std::{env, time::Duration};
+use std::time::Duration;
use anyhow::Context as _;
use clap::Parser;
@@ -14,10 +14,18 @@ use documents::outbound::markdown_init::LexicalSyncMarkdownInitializer;
use documents::outbound::pg_document_repo::PgDocumentRepo;
use documents::outbound::s3_markdown_source::S3MarkdownObjectReader;
use lexical_client::LexicalClient;
+use macro_env_var::env_vars;
use macro_service_urls::{LexicalServiceUrl, SyncServiceUrl};
use sqlx::postgres::PgPoolOptions;
use sync_service_client::SyncServiceClient;
+env_vars! {
+ struct DatabaseUrl;
+ struct SyncServiceAuthKey;
+ struct InternalApiSecretKey;
+ struct DocumentStorageBucket;
+}
+
/// Backfill markdown document content lifecycle from sync-service state.
#[derive(Clone, Debug, Parser)]
#[command(version, about)]
@@ -87,9 +95,10 @@ async fn main() -> anyhow::Result<()> {
tracing::warn!("dry-run mode: pass --apply to update Document.contentLocation");
}
- let database_url = env::var("DATABASE_URL").context("DATABASE_URL must be set")?;
- let sync_service_auth_key =
- env::var("SYNC_SERVICE_AUTH_KEY").context("SYNC_SERVICE_AUTH_KEY must be set")?;
+ let database_url = DatabaseUrl::new().context("DATABASE_URL must be set")?;
+ let sync_service_auth_key = SyncServiceAuthKey::new()
+ .context("SYNC_SERVICE_AUTH_KEY must be set")?
+ .to_string();
let sync_service_url = SyncServiceUrl::new()?.to_string();
tracing::info!(
@@ -107,7 +116,7 @@ async fn main() -> anyhow::Result<()> {
let db = PgPoolOptions::new()
.max_connections(5)
- .connect(&database_url)
+ .connect(database_url.as_ref())
.await
.context("failed to connect to postgres")?;
@@ -157,8 +166,9 @@ fn build_markdown_initializer(
return Ok(OptionalMarkdownInitializer::Disabled);
}
- let internal_api_secret_key = env::var("INTERNAL_API_SECRET_KEY")
- .context("INTERNAL_API_SECRET_KEY must be set when --initialize-missing is used")?;
+ let internal_api_secret_key = InternalApiSecretKey::new()
+ .context("INTERNAL_API_SECRET_KEY must be set when --initialize-missing is used")?
+ .to_string();
let lexical_service_url = LexicalServiceUrl::new()?.to_string();
Ok(OptionalMarkdownInitializer::Enabled(
@@ -174,8 +184,9 @@ async fn build_object_reader(enabled: bool) -> anyhow::Result<OptionalMarkdownOb
return Ok(OptionalMarkdownObjectReader::Disabled);
}
- let document_storage_bucket = env::var("DOCUMENT_STORAGE_BUCKET")
- .context("DOCUMENT_STORAGE_BUCKET must be set when --initialize-missing is used")?;
+ let document_storage_bucket = DocumentStorageBucket::new()
+ .context("DOCUMENT_STORAGE_BUCKET must be set when --initialize-missing is used")?
+ .to_string();
Ok(OptionalMarkdownObjectReader::Enabled(
S3MarkdownObjectReader::new(document_storage_bucket, macro_aws_config::s3_client().await),
diff --git a/rust/cloud-storage/docx_unzip_handler/Cargo.toml b/rust/cloud-storage/docx_unzip_handler/Cargo.toml
index 47f5a47042..a324a4241a 100644
--- a/rust/cloud-storage/docx_unzip_handler/Cargo.toml
+++ b/rust/cloud-storage/docx_unzip_handler/Cargo.toml
@@ -41,4 +41,5 @@ tracing = { workspace = true }
urlencoding = { workspace = true }
zip = { workspace = true }
workspace-hack = { version = "0.1", path = "../workspace-hack" }
+macro_env_var = { path = "../macro_env_var" }
diff --git a/rust/cloud-storage/docx_unzip_handler/src/config.rs b/rust/cloud-storage/docx_unzip_handler/src/config.rs
index 6d9cd612e2..43564bf35d 100644
--- a/rust/cloud-storage/docx_unzip_handler/src/config.rs
+++ b/rust/cloud-storage/docx_unzip_handler/src/config.rs
@@ -1,4 +1,13 @@
use anyhow::Context;
+use macro_env_var::env_vars;
+
+env_vars! {
+ pub struct DatabaseUrl;
+ pub struct RedisUri;
+ pub struct DocumentStorageBucket;
+ pub struct WebSocketResponseLambda;
+ pub struct ConvertQueue;
+}
/// The configuration parameters for the application.
///
@@ -27,15 +36,22 @@ pub struct Config {
impl Config {
pub fn from_env() -> anyhow::Result<Self> {
- let database_url =
- std::env::var("DATABASE_URL").context("DATABASE_URL must be provided")?;
- let redis_uri = std::env::var("REDIS_URI").context("REDIS_URI must be provided")?;
- let document_storage_bucket = std::env::var("DOCUMENT_STORAGE_BUCKET")
- .context("DOCUMENT_STORAGE_BUCKET must be provided")?;
- let web_socket_response_lambda = std::env::var("WEB_SOCKET_RESPONSE_LAMBDA")
- .context("WEB_SOCKET_RESPONSE_LAMBDA must be provided")?;
- let convert_queue =
- std::env::var("CONVERT_QUEUE").context("CONVERT_QUEUE must be provided")?;
+ let database_url = DatabaseUrl::new()
+ .context("DATABASE_URL must be provided")?
+ .to_string();
+ let redis_uri = RedisUri::new()
+ .context("REDIS_URI must be provided")?
+ .to_string();
+ let document_storage_bucket = DocumentStorageBucket::new()
+ .context("DOCUMENT_STORAGE_BUCKET must be provided")?
+ .to_string();
+ let web_socket_response_lambda = WebSocketResponseLambda::new()
+ .context("WEB_SOCKET_RESPONSE_LAMBDA must be provided")?
+ .to_string();
+ let convert_queue = ConvertQueue::new()
+ .context("CONVERT_QUEUE must be provided")?
+ .to_string();
+
Ok(Config {
database_url,
redis_uri,
diff --git a/rust/cloud-storage/email_refresh_handler/Cargo.toml b/rust/cloud-storage/email_refresh_handler/Cargo.toml
index a6135edebd..99cc57bade 100644
--- a/rust/cloud-storage/email_refresh_handler/Cargo.toml
+++ b/rust/cloud-storage/email_refresh_handler/Cargo.toml
@@ -13,6 +13,7 @@ chrono = { workspace = true }
lambda_runtime = { workspace = true }
macro_entrypoint = { path = "../macro_entrypoint" }
macro_env = { path = "../macro_env" }
+macro_env_var = { path = "../macro_env_var" }
model = { path = "../model" }
models_email = { path = "../models_email" }
sqlx = { workspace = true }
diff --git a/rust/cloud-storage/email_refresh_handler/src/config.rs b/rust/cloud-storage/email_refresh_handler/src/config.rs
index 6171f64881..4a7de5399a 100644
--- a/rust/cloud-storage/email_refresh_handler/src/config.rs
+++ b/rust/cloud-storage/email_refresh_handler/src/config.rs
@@ -1,5 +1,14 @@
use anyhow::Context;
pub use macro_env::Environment;
+use macro_env_var::env_vars;
+
+env_vars! {
+ struct DatabaseUrl;
+ struct LinkManagerQueue;
+ struct DeleteUnusedAfterDays;
+ struct DeleteInactiveAfterDays;
+ struct InboxHealthPollIntervalHours;
+}
#[derive(Debug, Clone)]
pub struct Config {
@@ -25,25 +34,27 @@ pub struct Config {
impl Config {
pub fn from_env() -> anyhow::Result<Self> {
- let database_url =
- std::env::var("DATABASE_URL").context("DATABASE_URL must be provided")?;
+ let database_url = DatabaseUrl::new()
+ .context("DATABASE_URL must be provided")?
+ .to_string();
- let link_manager_queue =
- std::env::var("LINK_MANAGER_QUEUE").context("LINK_MANAGER_QUEUE must be provided")?;
+ let link_manager_queue = LinkManagerQueue::new()
+ .context("LINK_MANAGER_QUEUE must be provided")?
+ .to_string();
let environment = Environment::new_or_prod();
- let delete_unused_after_days = std::env::var("DELETE_UNUSED_AFTER_DAYS")
+ let delete_unused_after_days = DeleteUnusedAfterDays::new()
.context("DELETE_UNUSED_AFTER_DAYS must be provided")?
.parse()
.context("DELETE_UNUSED_AFTER_DAYS must be a valid u32")?;
- let delete_inactive_after_days = std::env::var("DELETE_INACTIVE_AFTER_DAYS")
+ let delete_inactive_after_days = DeleteInactiveAfterDays::new()
.context("DELETE_INACTIVE_AFTER_DAYS must be provided")?
.parse()
.context("DELETE_INACTIVE_AFTER_DAYS must be a valid u32")?;
- let health_poll_interval_hours = std::env::var("INBOX_HEALTH_POLL_INTERVAL_HOURS")
+ let health_poll_interval_hours = InboxHealthPollIntervalHours::new()
.context("INBOX_HEALTH_POLL_INTERVAL_HOURS must be provided")?
.parse()
.context("INBOX_HEALTH_POLL_INTERVAL_HOURS must be a valid u32")?;
diff --git a/rust/cloud-storage/email_scheduled_handler/Cargo.toml b/rust/cloud-storage/email_scheduled_handler/Cargo.toml
index 04383cabe1..955fa78902 100644
--- a/rust/cloud-storage/email_scheduled_handler/Cargo.toml
+++ b/rust/cloud-storage/email_scheduled_handler/Cargo.toml
@@ -13,6 +13,7 @@ chrono = { workspace = true }
lambda_runtime = { workspace = true }
macro_entrypoint = { path = "../macro_entrypoint" }
macro_env = { path = "../macro_env" }
+macro_env_var = { path = "../macro_env_var" }
models_email = { path = "../models_email" }
sqlx = { workspace = true }
sqs_client = { path = "../sqs_client" }
diff --git a/rust/cloud-storage/email_scheduled_handler/src/config.rs b/rust/cloud-storage/email_scheduled_handler/src/config.rs
index 66bbac7a23..697dcd9c1f 100644
--- a/rust/cloud-storage/email_scheduled_handler/src/config.rs
+++ b/rust/cloud-storage/email_scheduled_handler/src/config.rs
@@ -1,5 +1,11 @@
use anyhow::Context;
pub use macro_env::Environment;
+use macro_env_var::env_vars;
+
+env_vars! {
+ struct DatabaseUrl;
+ struct EmailScheduledQueue;
+}
#[derive(Debug, Clone)]
pub struct Config {
@@ -16,11 +22,13 @@ pub struct Config {
impl Config {
pub fn from_env() -> anyhow::Result<Self> {
- let database_url =
- std::env::var("DATABASE_URL").context("DATABASE_URL must be provided")?;
+ let database_url = DatabaseUrl::new()
+ .context("DATABASE_URL must be provided")?
+ .to_string();
- let email_scheduled_queue = std::env::var("EMAIL_SCHEDULED_QUEUE")
- .context("EMAIL_SCHEDULED_QUEUE must be provided")?;
+ let email_scheduled_queue = EmailScheduledQueue::new()
+ .context("EMAIL_SCHEDULED_QUEUE must be provided")?
+ .to_string();
let environment = Environment::new_or_prod();
diff --git a/rust/cloud-storage/email_service/src/bin/backfill_contacts/config.rs b/rust/cloud-storage/email_service/src/bin/backfill_contacts/config.rs
index 7a61b51741..0845f58c60 100644
--- a/rust/cloud-storage/email_service/src/bin/backfill_contacts/config.rs
+++ b/rust/cloud-storage/email_service/src/bin/backfill_contacts/config.rs
@@ -1,4 +1,5 @@
use anyhow::Context;
+use macro_env_var::env_vars;
/// Holds all configuration loaded from environment variables.
pub struct Config {
@@ -7,14 +8,24 @@ pub struct Config {
pub contacts_queue: String,
}
+env_vars! {
+ struct MacroIds;
+ struct DatabaseUrl;
+ struct ContactsQueue;
+}
+
impl Config {
/// Creates a new `Config` instance by reading from environment variables.
/// Returns an error if any required variable is not set.
pub fn from_env() -> anyhow::Result<Self> {
Ok(Self {
- macro_ids: std::env::var("MACRO_IDS").context("MACRO_IDS not set")?, // Changed
- database_url: std::env::var("DATABASE_URL").context("DATABASE_URL not set")?,
- contacts_queue: std::env::var("CONTACTS_QUEUE").context("CONTACTS_QUEUE not set")?,
+ macro_ids: MacroIds::new().context("MACRO_IDS not set")?.to_string(),
+ database_url: DatabaseUrl::new()
+ .context("DATABASE_URL not set")?
+ .to_string(),
+ contacts_queue: ContactsQueue::new()
+ .context("CONTACTS_QUEUE not set")?
+ .to_string(),
})
}
}
diff --git a/rust/cloud-storage/email_service/src/bin/backfill_gmail_attachments/config.rs b/rust/cloud-storage/email_service/src/bin/backfill_gmail_attachments/config.rs
index 6668a9ab79..30f1c461cb 100644
--- a/rust/cloud-storage/email_service/src/bin/backfill_gmail_attachments/config.rs
+++ b/rust/cloud-storage/email_service/src/bin/backfill_gmail_attachments/config.rs
@@ -1,4 +1,5 @@
use anyhow::Context;
+use macro_env_var::env_vars;
/// Holds all configuration loaded from environment variables.
pub struct Config {
@@ -14,32 +15,53 @@ pub struct Config {
pub gmail_client_secret: String,
}
+env_vars! {
+ struct UploadConcurrency;
+ struct DssUrl;
+ struct InternalAuthKey;
+ struct MacroIds;
+ struct DatabaseUrl;
+ struct FusionauthApiKey;
+ struct FusionauthBaseUrl;
+ struct FusionauthIdentityProviderId;
+ struct GmailClientId;
+ struct GmailClientSecret;
+}
+
impl Config {
/// Creates a new `Config` instance by reading from environment variables.
/// Returns an error if any required variable is not set.
pub fn from_env() -> anyhow::Result<Self> {
- let upload_concurrency =
- std::env::var("UPLOAD_CONCURRENCY").context("UPLOAD_CONCURRENCY not set")?;
- let upload_concurrency = upload_concurrency
+ let upload_concurrency = UploadConcurrency::new()
+ .context("UPLOAD_CONCURRENCY not set")?
.parse::<usize>()
.context("UPLOAD_CONCURRENCY is not a number")?;
Ok(Self {
- dss_url: std::env::var("DSS_URL").context("DSS_URL not set")?,
- internal_auth_key: std::env::var("INTERNAL_AUTH_KEY")
- .context("INTERNAL_AUTH_KEY not set")?,
- macro_ids: std::env::var("MACRO_IDS").context("MACRO_IDS not set")?, // Changed
- database_url: std::env::var("DATABASE_URL").context("DATABASE_URL not set")?,
+ dss_url: DssUrl::new().context("DSS_URL not set")?.to_string(),
+ internal_auth_key: InternalAuthKey::new()
+ .context("INTERNAL_AUTH_KEY not set")?
+ .to_string(),
+ macro_ids: MacroIds::new().context("MACRO_IDS not set")?.to_string(),
+ database_url: DatabaseUrl::new()
+ .context("DATABASE_URL not set")?
+ .to_string(),
upload_concurrency,
- fusionauth_api_key: std::env::var("FUSIONAUTH_API_KEY")
- .context("FUSIONAUTH_API_KEY not set")?,
- fusionauth_base_url: std::env::var("FUSIONAUTH_BASE_URL")
- .context("FUSIONAUTH_BASE_URL not set")?,
- fusionauth_identity_provider_id: std::env::var("FUSIONAUTH_IDENTITY_PROVIDER_ID")
- .context("FUSIONAUTH_IDENTITY_PROVIDER_ID not set")?,
- gmail_client_id: std::env::var("GMAIL_CLIENT_ID").context("GMAIL_CLIENT_ID not set")?,
- gmail_client_secret: std::env::var("GMAIL_CLIENT_SECRET")
- .context("GMAIL_CLIENT_SECRET not set")?,
+ fusionauth_api_key: FusionauthApiKey::new()
+ .context("FUSIONAUTH_API_KEY not set")?
+ .to_string(),
+ fusionauth_base_url: FusionauthBaseUrl::new()
+ .context("FUSIONAUTH_BASE_URL not set")?
+ .to_string(),
+ fusionauth_identity_provider_id: FusionauthIdentityProviderId::new()
+ .context("FUSIONAUTH_IDENTITY_PROVIDER_ID not set")?
+ .to_string(),
+ gmail_client_id: GmailClientId::new()
+ .context("GMAIL_CLIENT_ID not set")?
+ .to_string(),
+ gmail_client_secret: GmailClientSecret::new()
+ .context("GMAIL_CLIENT_SECRET not set")?
+ .to_string(),
})
}
}
diff --git a/rust/cloud-storage/email_service/src/bin/backfill_sfs_attachments/config.rs b/rust/cloud-storage/email_service/src/bin/backfill_sfs_attachments/config.rs
index c37e6265fa..0ffdac517f 100644
--- a/rust/cloud-storage/email_service/src/bin/backfill_sfs_attachments/config.rs
+++ b/rust/cloud-storage/email_service/src/bin/backfill_sfs_attachments/config.rs
@@ -1,4 +1,5 @@
use anyhow::Context;
+use macro_env_var::env_vars;
/// Holds all configuration loaded from environment variables.
pub struct Config {
@@ -14,32 +15,53 @@ pub struct Config {
pub gmail_client_secret: String,
}
+env_vars! {
+ struct UploadConcurrency;
+ struct SfsUrl;
+ struct InternalAuthKey;
+ struct MacroIds;
+ struct DatabaseUrl;
+ struct FusionauthApiKey;
+ struct FusionauthBaseUrl;
+ struct FusionauthIdentityProviderId;
+ struct GmailClientId;
+ struct GmailClientSecret;
+}
+
impl Config {
/// Creates a new `Config` instance by reading from environment variables.
/// Returns an error if any required variable is not set.
pub fn from_env() -> anyhow::Result<Self> {
- let upload_concurrency =
- std::env::var("UPLOAD_CONCURRENCY").context("UPLOAD_CONCURRENCY not set")?;
- let upload_concurrency = upload_concurrency
+ let upload_concurrency = UploadConcurrency::new()
+ .context("UPLOAD_CONCURRENCY not set")?
.parse::<usize>()
.context("UPLOAD_CONCURRENCY is not a number")?;
Ok(Self {
- sfs_url: std::env::var("SFS_URL").context("SFS_URL not set")?,
- internal_auth_key: std::env::var("INTERNAL_AUTH_KEY")
- .context("INTERNAL_AUTH_KEY not set")?,
- macro_ids: std::env::var("MACRO_IDS").context("MACRO_IDS not set")?, // Changed
- database_url: std::env::var("DATABASE_URL").context("DATABASE_URL not set")?,
+ sfs_url: SfsUrl::new().context("SFS_URL not set")?.to_string(),
+ internal_auth_key: InternalAuthKey::new()
+ .context("INTERNAL_AUTH_KEY not set")?
+ .to_string(),
+ macro_ids: MacroIds::new().context("MACRO_IDS not set")?.to_string(),
+ database_url: DatabaseUrl::new()
+ .context("DATABASE_URL not set")?
+ .to_string(),
upload_concurrency,
- fusionauth_api_key: std::env::var("FUSIONAUTH_API_KEY")
- .context("FUSIONAUTH_API_KEY not set")?,
- fusionauth_base_url: std::env::var("FUSIONAUTH_BASE_URL")
- .context("FUSIONAUTH_BASE_URL not set")?,
- fusionauth_identity_provider_id: std::env::var("FUSIONAUTH_IDENTITY_PROVIDER_ID")
- .context("FUSIONAUTH_IDENTITY_PROVIDER_ID not set")?,
- gmail_client_id: std::env::var("GMAIL_CLIENT_ID").context("GMAIL_CLIENT_ID not set")?,
- gmail_client_secret: std::env::var("GMAIL_CLIENT_SECRET")
- .context("GMAIL_CLIENT_SECRET not set")?,
+ fusionauth_api_key: FusionauthApiKey::new()
+ .context("FUSIONAUTH_API_KEY not set")?
+ .to_string(),
+ fusionauth_base_url: FusionauthBaseUrl::new()
+ .context("FUSIONAUTH_BASE_URL not set")?
+ .to_string(),
+ fusionauth_identity_provider_id: FusionauthIdentityProviderId::new()
+ .context("FUSIONAUTH_IDENTITY_PROVIDER_ID not set")?
+ .to_string(),
+ gmail_client_id: GmailClientId::new()
+ .context("GMAIL_CLIENT_ID not set")?
+ .to_string(),
+ gmail_client_secret: GmailClientSecret::new()
+ .context("GMAIL_CLIENT_SECRET not set")?
+ .to_string(),
})
}
}
diff --git a/rust/cloud-storage/email_service/src/bin/cleanup_unused_sfs/config.rs b/rust/cloud-storage/email_service/src/bin/cleanup_unused_sfs/config.rs
index 0a4ebb48bb..8913f042b7 100644
--- a/rust/cloud-storage/email_service/src/bin/cleanup_unused_sfs/config.rs
+++ b/rust/cloud-storage/email_service/src/bin/cleanup_unused_sfs/config.rs
@@ -1,6 +1,7 @@
//! Configuration for the cleanup_unused_sfs binary.
use anyhow::Context;
+use macro_env_var::{env_vars, maybe_env_vars};
/// Holds all configuration loaded from environment variables.
pub struct Config {
@@ -20,29 +21,65 @@ pub struct Config {
pub bulk_concurrency: usize,
}
+env_vars! {
+ struct DatabaseUrl;
+ struct SfsUrl;
+ struct InternalAuthKey;
+ struct DestinationUrlPrefix;
+}
+
+maybe_env_vars! {
+ struct BulkBatchSize;
+ struct BulkConcurrency;
+ struct UnusedUuidsFile;
+}
+
+fn parse_optional_env<T, V>(
+ value: Option<V>,
+ default: T,
+ context: &'static str,
+) -> anyhow::Result<T>
+where
+ T: std::str::FromStr,
+ T::Err: std::error::Error + Send + Sync + 'static,
+ V: AsRef<str>,
+{
+ value
+ .map(|value| value.as_ref().parse::<T>().context(context))
+ .transpose()
+ .map(|value| value.unwrap_or(default))
+}
+
impl Config {
/// Creates a new `Config` instance by reading from environment variables.
/// Returns an error if any required variable is not set.
pub fn from_env() -> anyhow::Result<Self> {
- let bulk_batch_size = std::env::var("BULK_BATCH_SIZE")
- .unwrap_or_else(|_| "50".to_string())
- .parse::<usize>()
- .context("BULK_BATCH_SIZE is not a valid number")?;
+ let bulk_batch_size = parse_optional_env(
+ BulkBatchSize::new(),
+ 50usize,
+ "BULK_BATCH_SIZE is not a valid number",
+ )?;
- let bulk_concurrency = std::env::var("BULK_CONCURRENCY")
- .unwrap_or_else(|_| "5".to_string())
- .parse::<usize>()
- .context("BULK_CONCURRENCY is not a valid number")?;
+ let bulk_concurrency = parse_optional_env(
+ BulkConcurrency::new(),
+ 5usize,
+ "BULK_CONCURRENCY is not a valid number",
+ )?;
Ok(Self {
- database_url: std::env::var("DATABASE_URL").context("DATABASE_URL not set")?,
- sfs_url: std::env::var("SFS_URL").context("SFS_URL not set")?,
- internal_auth_key: std::env::var("INTERNAL_AUTH_KEY")
- .context("INTERNAL_AUTH_KEY not set")?,
- unused_uuids_file: std::env::var("UNUSED_UUIDS_FILE")
- .unwrap_or_else(|_| "unused_sfs_uuids.txt".to_string()),
- destination_url_prefix: std::env::var("DESTINATION_URL_PREFIX")
- .context("DESTINATION_URL_PREFIX not set")?,
+ database_url: DatabaseUrl::new()
+ .context("DATABASE_URL not set")?
+ .to_string(),
+ sfs_url: SfsUrl::new().context("SFS_URL not set")?.to_string(),
+ internal_auth_key: InternalAuthKey::new()
+ .context("INTERNAL_AUTH_KEY not set")?
+ .to_string(),
+ unused_uuids_file: UnusedUuidsFile::new()
+ .map(|value| value.to_string())
+ .unwrap_or_else(|| "unused_sfs_uuids.txt".to_string()),
+ destination_url_prefix: DestinationUrlPrefix::new()
+ .context("DESTINATION_URL_PREFIX not set")?
+ .to_string(),
bulk_batch_size,
bulk_concurrency,
})
diff --git a/rust/cloud-storage/email_service/src/bin/find_unused_sfs_ids/config.rs b/rust/cloud-storage/email_service/src/bin/find_unused_sfs_ids/config.rs
index 46b625480c..f64a3878b5 100644
--- a/rust/cloud-storage/email_service/src/bin/find_unused_sfs_ids/config.rs
+++ b/rust/cloud-storage/email_service/src/bin/find_unused_sfs_ids/config.rs
@@ -1,6 +1,7 @@
//! Configuration for the find_unused_sfs_ids binary.
use anyhow::Context;
+use macro_env_var::{env_vars, maybe_env_vars};
/// Holds all configuration loaded from environment variables.
pub struct Config {
@@ -16,23 +17,56 @@ pub struct Config {
pub extraction_concurrency: usize,
}
+env_vars! {
+ struct DatabaseUrl;
+}
+
+maybe_env_vars! {
+ struct ExtractionConcurrency;
+ struct UsedUuidsFile;
+ struct AllMappingsFile;
+ struct UnusedUuidsFile;
+}
+
+fn parse_optional_env<T, V>(
+ value: Option<V>,
+ default: T,
+ context: &'static str,
+) -> anyhow::Result<T>
+where
+ T: std::str::FromStr,
+ T::Err: std::error::Error + Send + Sync + 'static,
+ V: AsRef<str>,
+{
+ value
+ .map(|value| value.as_ref().parse::<T>().context(context))
+ .transpose()
+ .map(|value| value.unwrap_or(default))
+}
+
impl Config {
/// Creates a new `Config` instance by reading from environment variables.
/// Returns an error if any required variable is not set.
pub fn from_env() -> anyhow::Result<Self> {
- let extraction_concurrency = std::env::var("EXTRACTION_CONCURRENCY")
- .unwrap_or_else(|_| "100".to_string())
- .parse::<usize>()
- .context("EXTRACTION_CONCURRENCY is not a valid number")?;
+ let extraction_concurrency = parse_optional_env(
+ ExtractionConcurrency::new(),
+ 100usize,
+ "EXTRACTION_CONCURRENCY is not a valid number",
+ )?;
Ok(Self {
- database_url: std::env::var("DATABASE_URL").context("DATABASE_URL not set")?,
- used_uuids_file: std::env::var("USED_UUIDS_FILE")
- .unwrap_or_else(|_| "used_sfs_uuids.txt".to_string()),
- all_mappings_file: std::env::var("ALL_MAPPINGS_FILE")
- .unwrap_or_else(|_| "all_sfs_mapping_uuids.txt".to_string()),
- unused_uuids_file: std::env::var("UNUSED_UUIDS_FILE")
- .unwrap_or_else(|_| "unused_sfs_uuids.txt".to_string()),
+ database_url: DatabaseUrl::new()
+ .context("DATABASE_URL not set")?
+ .to_string(),
+ used_uuids_file: UsedUuidsFile::new()
+ .map(|value| value.to_string())
+ .unwrap_or_else(|| "used_sfs_uuids.txt".to_string()),
+ all_mappings_file: AllMappingsFile::new()
+ .map(|value| value.to_string())
+ .unwrap_or_else(|| "all_sfs_mapping_uuids.txt".to_string()),
+ unused_uuids_file: UnusedUuidsFile::new()
+ .map(|value| value.to_string())
+ .unwrap_or_else(|| "unused_sfs_uuids.txt".to_string()),
extraction_concurrency,
})
}
diff --git a/rust/cloud-storage/email_service/src/bin/find_used_sfs_ids/config.rs b/rust/cloud-storage/email_service/src/bin/find_used_sfs_ids/config.rs
index feaa087878..4ed3cd8de7 100644
--- a/rust/cloud-storage/email_service/src/bin/find_used_sfs_ids/config.rs
+++ b/rust/cloud-storage/email_service/src/bin/find_used_sfs_ids/config.rs
@@ -1,6 +1,7 @@
//! Configuration for the find_used_sfs_ids binary.
use anyhow::Context;
+use macro_env_var::{env_vars, maybe_env_vars};
/// Holds all configuration loaded from environment variables.
pub struct Config {
@@ -20,33 +21,70 @@ pub struct Config {
pub prefetch_batches: usize,
}
+env_vars! {
+ struct DatabaseUrl;
+}
+
+maybe_env_vars! {
+ struct FetchBatchSize;
+ struct BatchSize;
+ struct PrefetchBatches;
+ struct SfsDomain;
+ struct MessageIdsFile;
+ struct UsedUuidsFile;
+}
+
+fn parse_optional_env<T, V>(
+ value: Option<V>,
+ default: T,
+ context: &'static str,
+) -> anyhow::Result<T>
+where
+ T: std::str::FromStr,
+ T::Err: std::error::Error + Send + Sync + 'static,
+ V: AsRef<str>,
+{
+ value
+ .map(|value| value.as_ref().parse::<T>().context(context))
+ .transpose()
+ .map(|value| value.unwrap_or(default))
+}
+
impl Config {
/// Creates a new `Config` instance by reading from environment variables.
/// Returns an error if any required variable is not set.
pub fn from_env() -> anyhow::Result<Self> {
- let fetch_batch_size = std::env::var("FETCH_BATCH_SIZE")
- .unwrap_or_else(|_| "1000".to_string())
- .parse::<usize>()
- .context("FETCH_BATCH_SIZE is not a valid number")?;
+ let fetch_batch_size = parse_optional_env(
+ FetchBatchSize::new(),
+ 1000usize,
+ "FETCH_BATCH_SIZE is not a valid number",
+ )?;
- let batch_size = std::env::var("BATCH_SIZE")
- .unwrap_or_else(|_| "1000".to_string())
- .parse::<usize>()
- .context("BATCH_SIZE is not a valid number")?;
+ let batch_size = parse_optional_env(
+ BatchSize::new(),
+ 1000usize,
+ "BATCH_SIZE is not a valid number",
+ )?;
- let prefetch_batches = std::env::var("PREFETCH_BATCHES")
- .unwrap_or_else(|_| "2".to_string())
- .parse::<usize>()
- .context("PREFETCH_BATCHES is not a valid number")?;
+ let prefetch_batches = parse_optional_env(
+ PrefetchBatches::new(),
+ 2usize,
+ "PREFETCH_BATCHES is not a valid number",
+ )?;
Ok(Self {
- database_url: std::env::var("DATABASE_URL").context("DATABASE_URL not set")?,
- sfs_domain: std::env::var("SFS_DOMAIN")
- .unwrap_or_else(|_| "static-file-service.macro.com".to_string()),
- message_ids_file: std::env::var("MESSAGE_IDS_FILE")
- .unwrap_or_else(|_| "message_ids.txt".to_string()),
- used_uuids_file: std::env::var("USED_UUIDS_FILE")
- .unwrap_or_else(|_| "used_sfs_uuids.txt".to_string()),
+ database_url: DatabaseUrl::new()
+ .context("DATABASE_URL not set")?
+ .to_string(),
+ sfs_domain: SfsDomain::new()
+ .map(|value| value.to_string())
+ .unwrap_or_else(|| "static-file-service.macro.com".to_string()),
+ message_ids_file: MessageIdsFile::new()
+ .map(|value| value.to_string())
+ .unwrap_or_else(|| "message_ids.txt".to_string()),
+ used_uuids_file: UsedUuidsFile::new()
+ .map(|value| value.to_string())
+ .unwrap_or_else(|| "used_sfs_uuids.txt".to_string()),
fetch_batch_size,
batch_size,
prefetch_batches,
diff --git a/rust/cloud-storage/email_service/src/bin/reverse_sfs_mappings/config.rs b/rust/cloud-storage/email_service/src/bin/reverse_sfs_mappings/config.rs
index 1126eae73a..5fe378b9cf 100644
--- a/rust/cloud-storage/email_service/src/bin/reverse_sfs_mappings/config.rs
+++ b/rust/cloud-storage/email_service/src/bin/reverse_sfs_mappings/config.rs
@@ -1,6 +1,7 @@
//! Configuration for the reverse_sfs_mappings binary.
use anyhow::Context;
+use macro_env_var::{env_vars, maybe_env_vars};
/// Holds all configuration loaded from environment variables.
pub struct Config {
@@ -14,11 +15,36 @@ pub struct Config {
pub offset: i64,
}
+env_vars! {
+ struct DatabaseUrl;
+}
+
+maybe_env_vars! {
+ struct LinkIds;
+ struct BatchSize;
+ struct Offset;
+}
+
+fn parse_optional_env<T, V>(
+ value: Option<V>,
+ default: T,
+ context: &'static str,
+) -> anyhow::Result<T>
+where
+ T: std::str::FromStr,
+ T::Err: std::error::Error + Send + Sync + 'static,
+ V: AsRef<str>,
+{
+ value
+ .map(|value| value.as_ref().parse::<T>().context(context))
+ .transpose()
+ .map(|value| value.unwrap_or(default))
+}
+
impl Config {
/// Creates a new `Config` instance by reading from environment variables.
pub fn from_env() -> anyhow::Result<Self> {
- let link_ids = std::env::var("LINK_IDS")
- .ok()
+ let link_ids = LinkIds::new()
.map(|s| {
s.split(',')
.map(|id| id.trim().parse::<uuid::Uuid>())
@@ -27,18 +53,15 @@ impl Config {
.transpose()
.context("LINK_IDS contains invalid UUIDs")?;
- let batch_size = std::env::var("BATCH_SIZE")
- .unwrap_or_else(|_| "10".to_string())
- .parse::<i64>()
- .context("BATCH_SIZE is not a valid number")?;
+ let batch_size =
+ parse_optional_env(BatchSize::new(), 10i64, "BATCH_SIZE is not a valid number")?;
- let offset = std::env::var("OFFSET")
- .unwrap_or_else(|_| "0".to_string())
- .parse::<i64>()
- .context("OFFSET is not a valid number")?;
+ let offset = parse_optional_env(Offset::new(), 0i64, "OFFSET is not a valid number")?;
Ok(Self {
- database_url: std::env::var("DATABASE_URL").context("DATABASE_URL not set")?,
+ database_url: DatabaseUrl::new()
+ .context("DATABASE_URL not set")?
+ .to_string(),
link_ids,
batch_size,
offset,
diff --git a/rust/cloud-storage/email_service/src/config.rs b/rust/cloud-storage/email_service/src/config.rs
index 28becc2b09..9e95b30ca6 100644
--- a/rust/cloud-storage/email_service/src/config.rs
+++ b/rust/cloud-storage/email_service/src/config.rs
@@ -1,6 +1,6 @@
use anyhow::Context;
pub use macro_env::Environment;
-use macro_env_var::env_var;
+use macro_env_var::{env_var, env_vars, maybe_env_vars};
use macro_service_urls::{ConnectionGatewayUrl, DocumentStorageServiceUrl, StaticFileServiceUrl};
use secretsmanager_client::LocalOrRemoteSecret;
@@ -158,170 +158,268 @@ pub struct Config {
env_var! { pub struct EmailServiceCloudfrontSignerPrivateKey; }
+env_vars! {
+ struct MacroDbUrl;
+ struct RedisUri;
+ struct LinkManagerQueue;
+ struct EmailScheduledQueue;
+ struct GmailInboxSyncQueue;
+ struct GmailInboxSyncRetryQueue;
+ struct GmailOpsQueue;
+ struct GmailOpsRetryQueue;
+ struct SearchEventQueue;
+ struct GmailGcpQueue;
+ struct NotificationQueue;
+ struct BackfillQueue;
+ struct ContactsQueue;
+ struct SfsUploaderQueue;
+ struct SfsDeleteQueue;
+ struct AttachmentBucket;
+ struct NotificationsEnabled;
+ struct AuthenticationServiceUrl;
+ struct AuthenticationServiceSecretKey;
+ struct EmailServiceCloudfrontDistributionUrl;
+ struct EmailServiceCloudfrontSignerPublicKeyId;
+}
+
+maybe_env_vars! {
+ struct Port;
+ struct SentUndoDelaySecs;
+ struct UseApolloCrmEnrichment;
+ struct ApolloApiKey;
+ struct QueueMaxMessages;
+ struct BackfillQueueWorkers;
+ struct BackfillQueueMaxMessages;
+ struct InboxSyncQueueWorkers;
+ struct InboxSyncQueueMaxMessages;
+ struct InboxSyncRetryQueueWorkers;
+ struct InboxSyncRetryQueueMaxMessages;
+ struct GmailOpsQueueWorkers;
+ struct GmailOpsQueueMaxMessages;
+ struct GmailOpsRetryQueueWorkers;
+ struct GmailOpsRetryQueueMaxMessages;
+ struct SfsUploaderWorkers;
+ struct RedisRateLimitReqs;
+ struct RedisRateLimitReqsBackfill;
+ struct RedisRateLimitWindowSecs;
+ struct QueueWaitTimeSeconds;
+ struct EmailServicePresignedUrlTtlSecs;
+}
+
+fn parse_optional_env<T, V>(
+ value: Option<V>,
+ default: T,
+ context: &'static str,
+) -> anyhow::Result<T>
+where
+ T: std::str::FromStr,
+ T::Err: std::error::Error + Send + Sync + 'static,
+ V: AsRef<str>,
+{
+ value
+ .map(|value| value.as_ref().parse::<T>().context(context))
+ .transpose()
+ .map(|value| value.unwrap_or(default))
+}
+
impl Config {
pub fn from_env(
email_service_cloudfront_signer_private_key: LocalOrRemoteSecret<
EmailServiceCloudfrontSignerPrivateKey,
>,
) -> anyhow::Result<Self> {
- let database_url =
- std::env::var("MACRO_DB_URL").context("MACRO_DB_URL must be provided")?;
+ let database_url = MacroDbUrl::new()
+ .context("MACRO_DB_URL must be provided")?
+ .to_string();
- let port: usize = std::env::var("PORT")
- .unwrap_or("8080".to_string())
- .parse::<usize>()
- .context("should be valid port number")?;
+ let port = parse_optional_env(Port::new(), 8080usize, "should be valid port number")?;
- let redis_uri = std::env::var("REDIS_URI").context("REDIS_URI must be provided")?;
+ let redis_uri = RedisUri::new()
+ .context("REDIS_URI must be provided")?
+ .to_string();
- let link_manager_queue =
- std::env::var("LINK_MANAGER_QUEUE").context("LINK_MANAGER_QUEUE must be provided")?;
+ let link_manager_queue = LinkManagerQueue::new()
+ .context("LINK_MANAGER_QUEUE must be provided")?
+ .to_string();
- let email_scheduled_queue = std::env::var("EMAIL_SCHEDULED_QUEUE")
- .context("EMAIL_SCHEDULED_QUEUE must be provided")?;
+ let email_scheduled_queue = EmailScheduledQueue::new()
+ .context("EMAIL_SCHEDULED_QUEUE must be provided")?
+ .to_string();
- let gmail_inbox_sync_queue = std::env::var("GMAIL_INBOX_SYNC_QUEUE")
- .context("GMAIL_INBOX_SYNC_QUEUE must be provided")?;
+ let gmail_inbox_sync_queue = GmailInboxSyncQueue::new()
+ .context("GMAIL_INBOX_SYNC_QUEUE must be provided")?
+ .to_string();
- let gmail_inbox_sync_retry_queue = std::env::var("GMAIL_INBOX_SYNC_RETRY_QUEUE")
- .context("GMAIL_INBOX_SYNC_RETRY_QUEUE must be provided")?;
+ let gmail_inbox_sync_retry_queue = GmailInboxSyncRetryQueue::new()
+ .context("GMAIL_INBOX_SYNC_RETRY_QUEUE must be provided")?
+ .to_string();
- let gmail_ops_queue =
- std::env::var("GMAIL_OPS_QUEUE").context("GMAIL_OPS_QUEUE must be provided")?;
+ let gmail_ops_queue = GmailOpsQueue::new()
+ .context("GMAIL_OPS_QUEUE must be provided")?
+ .to_string();
- let gmail_ops_retry_queue = std::env::var("GMAIL_OPS_RETRY_QUEUE")
- .context("GMAIL_OPS_RETRY_QUEUE must be provided")?;
+ let gmail_ops_retry_queue = GmailOpsRetryQueue::new()
+ .context("GMAIL_OPS_RETRY_QUEUE must be provided")?
+ .to_string();
- let search_event_queue =
- std::env::var("SEARCH_EVENT_QUEUE").context("SEARCH_EVENT_QUEUE must be provided")?;
+ let search_event_queue = SearchEventQueue::new()
+ .context("SEARCH_EVENT_QUEUE must be provided")?
+ .to_string();
- let gmail_gcp_queue =
- std::env::var("GMAIL_GCP_QUEUE").context("GMAIL_GCP_QUEUE must be provided")?;
+ let gmail_gcp_queue = GmailGcpQueue::new()
+ .context("GMAIL_GCP_QUEUE must be provided")?
+ .to_string();
- let notification_queue =
- std::env::var("NOTIFICATION_QUEUE").context("NOTIFICATION_QUEUE must be provided")?;
+ let notification_queue = NotificationQueue::new()
+ .context("NOTIFICATION_QUEUE must be provided")?
+ .to_string();
- let backfill_queue =
- std::env::var("BACKFILL_QUEUE").context("BACKFILL_QUEUE must be provided")?;
+ let backfill_queue = BackfillQueue::new()
+ .context("BACKFILL_QUEUE must be provided")?
+ .to_string();
- let contacts_queue =
- std::env::var("CONTACTS_QUEUE").context("CONTACTS_QUEUE must be provided")?;
+ let contacts_queue = ContactsQueue::new()
+ .context("CONTACTS_QUEUE must be provided")?
+ .to_string();
- let sfs_uploader_queue =
- std::env::var("SFS_UPLOADER_QUEUE").context("SFS_UPLOADER_QUEUE must be provided")?;
+ let sfs_uploader_queue = SfsUploaderQueue::new()
+ .context("SFS_UPLOADER_QUEUE must be provided")?
+ .to_string();
- let sfs_delete_queue =
- std::env::var("SFS_DELETE_QUEUE").context("SFS_DELETE_QUEUE must be provided")?;
+ let sfs_delete_queue = SfsDeleteQueue::new()
+ .context("SFS_DELETE_QUEUE must be provided")?
+ .to_string();
- let attachment_bucket =
- std::env::var("ATTACHMENT_BUCKET").context("ATTACHMENT_BUCKET must be provided")?;
+ let attachment_bucket = AttachmentBucket::new()
+ .context("ATTACHMENT_BUCKET must be provided")?
+ .to_string();
- let sent_undo_delay_secs: u32 = std::env::var("SENT_UNDO_DELAY_SECS")
- .unwrap_or("10".to_string())
- .parse::<u32>()
- .unwrap();
+ let sent_undo_delay_secs = parse_optional_env(
+ SentUndoDelaySecs::new(),
+ 10u32,
+ "SENT_UNDO_DELAY_SECS must be a valid u32",
+ )?;
- let notifications_enabled = std::env::var("NOTIFICATIONS_ENABLED")
+ let notifications_enabled = NotificationsEnabled::new()
.context("NOTIFICATIONS_ENABLED must be provided")?
.parse::<bool>()
.context("NOTIFICATIONS_ENABLED must be a boolean value")?;
- let use_apollo_crm_enrichment: bool = std::env::var("USE_APOLLO_CRM_ENRICHMENT")
- .unwrap_or("false".to_string())
- .parse::<bool>()
- .context("USE_APOLLO_CRM_ENRICHMENT must be a boolean value")?;
-
- let apollo_api_key = std::env::var("APOLLO_API_KEY").unwrap_or_default();
-
- let queue_max_messages: i32 = std::env::var("QUEUE_MAX_MESSAGES")
- .unwrap_or("10".to_string())
- .parse::<i32>()
- .unwrap();
-
- let backfill_queue_workers: i32 = std::env::var("BACKFILL_QUEUE_WORKERS")
- .unwrap_or("25".to_string())
- .parse::<i32>()
- .unwrap();
-
- let backfill_queue_max_messages: i32 = std::env::var("BACKFILL_QUEUE_MAX_MESSAGES")
- .unwrap_or("1".to_string())
- .parse::<i32>()
- .unwrap();
-
- let inbox_sync_queue_workers: i32 = std::env::var("INBOX_SYNC_QUEUE_WORKERS")
- .unwrap_or("10".to_string())
- .parse::<i32>()
- .unwrap();
-
- let inbox_sync_queue_max_messages: i32 = std::env::var("INBOX_SYNC_QUEUE_MAX_MESSAGES")
- .unwrap_or("1".to_string())
- .parse::<i32>()
- .unwrap();
-
- let inbox_sync_retry_queue_workers: i32 = std::env::var("INBOX_SYNC_RETRY_QUEUE_WORKERS")
- .unwrap_or("10".to_string())
- .parse::<i32>()
- .unwrap();
-
- let inbox_sync_retry_queue_max_messages: i32 =
- std::env::var("INBOX_SYNC_RETRY_QUEUE_MAX_MESSAGES")
- .unwrap_or("1".to_string())
- .parse::<i32>()
- .unwrap();
-
- let gmail_ops_queue_workers: i32 = std::env::var("GMAIL_OPS_QUEUE_WORKERS")
- .unwrap_or("5".to_string())
- .parse::<i32>()
- .unwrap();
-
- let gmail_ops_queue_max_messages: i32 = std::env::var("GMAIL_OPS_QUEUE_MAX_MESSAGES")
- .unwrap_or("10".to_string())
- .parse::<i32>()
- .unwrap();
-
- let gmail_ops_retry_queue_workers: i32 = std::env::var("GMAIL_OPS_RETRY_QUEUE_WORKERS")
- .unwrap_or("2".to_string())
- .parse::<i32>()
- .unwrap();
-
- let gmail_ops_retry_queue_max_messages: i32 =
- std::env::var("GMAIL_OPS_RETRY_QUEUE_MAX_MESSAGES")
- .unwrap_or("10".to_string())
- .parse::<i32>()
- .unwrap();
-
- let sfs_uploader_workers: i32 = std::env::var("SFS_UPLOADER_WORKERS")
- .unwrap_or("3".to_string())
- .parse::<i32>()
- .unwrap();
-
- let redis_rate_limit_reqs: u32 = std::env::var("REDIS_RATE_LIMIT_REQS")
- .unwrap_or("14000".to_string())
- .parse::<u32>()
- .unwrap();
-
- let redis_rate_limit_reqs_backfill: u32 = std::env::var("REDIS_RATE_LIMIT_REQS_BACKFILL")
- .unwrap_or("13000".to_string())
- .parse::<u32>()
- .unwrap();
-
- let redis_rate_limit_window_secs: u32 = std::env::var("REDIS_RATE_LIMIT_WINDOW_SECS")
- .unwrap_or("60".to_string())
- .parse::<u32>()
- .unwrap();
-
- let queue_wait_time_seconds: i32 = std::env::var("QUEUE_WAIT_TIME_SECONDS")
- .unwrap_or("20".to_string())
- .parse::<i32>()
- .unwrap();
+ let use_apollo_crm_enrichment = parse_optional_env(
+ UseApolloCrmEnrichment::new(),
+ false,
+ "USE_APOLLO_CRM_ENRICHMENT must be a boolean value",
+ )?;
+
+ let apollo_api_key = ApolloApiKey::new()
+ .map(|api_key| api_key.to_string())
+ .unwrap_or_default();
+
+ let queue_max_messages = parse_optional_env(
+ QueueMaxMessages::new(),
+ 10i32,
+ "QUEUE_MAX_MESSAGES must be a valid i32",
+ )?;
+
+ let backfill_queue_workers = parse_optional_env(
+ BackfillQueueWorkers::new(),
+ 25i32,
+ "BACKFILL_QUEUE_WORKERS must be a valid i32",
+ )?;
+
+ let backfill_queue_max_messages = parse_optional_env(
+ BackfillQueueMaxMessages::new(),
+ 1i32,
+ "BACKFILL_QUEUE_MAX_MESSAGES must be a valid i32",
+ )?;
+
+ let inbox_sync_queue_workers = parse_optional_env(
+ InboxSyncQueueWorkers::new(),
+ 10i32,
+ "INBOX_SYNC_QUEUE_WORKERS must be a valid i32",
+ )?;
+
+ let inbox_sync_queue_max_messages = parse_optional_env(
+ InboxSyncQueueMaxMessages::new(),
+ 1i32,
+ "INBOX_SYNC_QUEUE_MAX_MESSAGES must be a valid i32",
+ )?;
+
+ let inbox_sync_retry_queue_workers = parse_optional_env(
+ InboxSyncRetryQueueWorkers::new(),
+ 10i32,
+ "INBOX_SYNC_RETRY_QUEUE_WORKERS must be a valid i32",
+ )?;
+
+ let inbox_sync_retry_queue_max_messages = parse_optional_env(
+ InboxSyncRetryQueueMaxMessages::new(),
+ 1i32,
+ "INBOX_SYNC_RETRY_QUEUE_MAX_MESSAGES must be a valid i32",
+ )?;
+
+ let gmail_ops_queue_workers = parse_optional_env(
+ GmailOpsQueueWorkers::new(),
+ 5i32,
+ "GMAIL_OPS_QUEUE_WORKERS must be a valid i32",
+ )?;
+
+ let gmail_ops_queue_max_messages = parse_optional_env(
+ GmailOpsQueueMaxMessages::new(),
+ 10i32,
+ "GMAIL_OPS_QUEUE_MAX_MESSAGES must be a valid i32",
+ )?;
+
+ let gmail_ops_retry_queue_workers = parse_optional_env(
+ GmailOpsRetryQueueWorkers::new(),
+ 2i32,
+ "GMAIL_OPS_RETRY_QUEUE_WORKERS must be a valid i32",
+ )?;
+
+ let gmail_ops_retry_queue_max_messages = parse_optional_env(
+ GmailOpsRetryQueueMaxMessages::new(),
+ 10i32,
+ "GMAIL_OPS_RETRY_QUEUE_MAX_MESSAGES must be a valid i32",
+ )?;
+
+ let sfs_uploader_workers = parse_optional_env(
+ SfsUploaderWorkers::new(),
+ 3i32,
+ "SFS_UPLOADER_WORKERS must be a valid i32",
+ )?;
+
+ let redis_rate_limit_reqs = parse_optional_env(
+ RedisRateLimitReqs::new(),
+ 14000u32,
+ "REDIS_RATE_LIMIT_REQS must be a valid u32",
+ )?;
+
+ let redis_rate_limit_reqs_backfill = parse_optional_env(
+ RedisRateLimitReqsBackfill::new(),
+ 13000u32,
+ "REDIS_RATE_LIMIT_REQS_BACKFILL must be a valid u32",
+ )?;
+
+ let redis_rate_limit_window_secs = parse_optional_env(
+ RedisRateLimitWindowSecs::new(),
+ 60u32,
+ "REDIS_RATE_LIMIT_WINDOW_SECS must be a valid u32",
+ )?;
+
+ let queue_wait_time_seconds = parse_optional_env(
+ QueueWaitTimeSeconds::new(),
+ 20i32,
+ "QUEUE_WAIT_TIME_SECONDS must be a valid i32",
+ )?;
let environment = Environment::new_or_prod();
- let auth_service_url = std::env::var("AUTHENTICATION_SERVICE_URL")
- .context("AUTHENTICATION_SERVICE_URL must be provided")?;
+ let auth_service_url = AuthenticationServiceUrl::new()
+ .context("AUTHENTICATION_SERVICE_URL must be provided")?
+ .to_string();
- let auth_service_secret_key = std::env::var("AUTHENTICATION_SERVICE_SECRET_KEY")
- .context("AUTHENTICATION_SERVICE_SECRET_KEY must be provided")?;
+ let auth_service_secret_key = AuthenticationServiceSecretKey::new()
+ .context("AUTHENTICATION_SERVICE_SECRET_KEY must be provided")?
+ .to_string();
let static_file_service_url = StaticFileServiceUrl::new()?.to_string();
@@ -330,18 +428,20 @@ impl Config {
let document_storage_service_url = DocumentStorageServiceUrl::new()?.to_string();
let email_service_cloudfront_distribution_url =
- std::env::var("EMAIL_SERVICE_CLOUDFRONT_DISTRIBUTION_URL")
- .context("EMAIL_SERVICE_CLOUDFRONT_DISTRIBUTION_URL must be provided")?;
+ EmailServiceCloudfrontDistributionUrl::new()
+ .context("EMAIL_SERVICE_CLOUDFRONT_DISTRIBUTION_URL must be provided")?
+ .to_string();
let email_service_cloudfront_signer_public_key_id =
- std::env::var("EMAIL_SERVICE_CLOUDFRONT_SIGNER_PUBLIC_KEY_ID")
- .context("EMAIL_SERVICE_CLOUDFRONT_SIGNER_PUBLIC_KEY_ID must be provided")?;
-
- let email_service_presigned_url_ttl_secs: u64 =
- std::env::var("EMAIL_SERVICE_PRESIGNED_URL_TTL_SECS")
- .unwrap_or("3600".to_string())
- .parse::<u64>()
- .unwrap();
+ EmailServiceCloudfrontSignerPublicKeyId::new()
+ .context("EMAIL_SERVICE_CLOUDFRONT_SIGNER_PUBLIC_KEY_ID must be provided")?
+ .to_string();
+
+ let email_service_presigned_url_ttl_secs = parse_optional_env(
+ EmailServicePresignedUrlTtlSecs::new(),
+ 3600u64,
+ "EMAIL_SERVICE_PRESIGNED_URL_TTL_SECS must be a valid u64",
+ )?;
Ok(Config {
macro_db_url: database_url,
diff --git a/rust/cloud-storage/email_sfs_delete_handler/Cargo.toml b/rust/cloud-storage/email_sfs_delete_handler/Cargo.toml
index 21d92c6714..e5e287d317 100644
--- a/rust/cloud-storage/email_sfs_delete_handler/Cargo.toml
+++ b/rust/cloud-storage/email_sfs_delete_handler/Cargo.toml
@@ -12,6 +12,7 @@ aws_lambda_events = { workspace = true, features = ["eventbridge"] }
lambda_runtime = { workspace = true }
macro_entrypoint = { path = "../macro_entrypoint" }
macro_env = { path = "../macro_env" }
+macro_env_var = { path = "../macro_env_var" }
sqlx = { workspace = true }
sqs_client = { path = "../sqs_client", default-features = false, features = ["email", "sfs_delete"] }
tokio = { workspace = true }
diff --git a/rust/cloud-storage/email_sfs_delete_handler/src/config.rs b/rust/cloud-storage/email_sfs_delete_handler/src/config.rs
index 54976a7747..1431214b27 100644
--- a/rust/cloud-storage/email_sfs_delete_handler/src/config.rs
+++ b/rust/cloud-storage/email_sfs_delete_handler/src/config.rs
@@ -1,5 +1,11 @@
use anyhow::Context;
pub use macro_env::Environment;
+use macro_env_var::env_vars;
+
+env_vars! {
+ struct DatabaseUrl;
+ struct SfsDeleteQueue;
+}
#[derive(Debug, Clone)]
pub struct Config {
@@ -16,11 +22,13 @@ pub struct Config {
impl Config {
pub fn from_env() -> anyhow::Result<Self> {
- let database_url =
- std::env::var("DATABASE_URL").context("DATABASE_URL must be provided")?;
+ let database_url = DatabaseUrl::new()
+ .context("DATABASE_URL must be provided")?
+ .to_string();
- let email_sfs_delete_queue =
- std::env::var("SFS_DELETE_QUEUE").context("SFS_DELETE_QUEUE must be provided")?;
+ let email_sfs_delete_queue = SfsDeleteQueue::new()
+ .context("SFS_DELETE_QUEUE must be provided")?
+ .to_string();
let environment = Environment::new_or_prod();
diff --git a/rust/cloud-storage/email_suppression_handler/Cargo.toml b/rust/cloud-storage/email_suppression_handler/Cargo.toml
index 7790b4d8de..93617a36bc 100644
--- a/rust/cloud-storage/email_suppression_handler/Cargo.toml
+++ b/rust/cloud-storage/email_suppression_handler/Cargo.toml
@@ -11,6 +11,7 @@ chrono = { workspace = true }
lambda_runtime = { workspace = true }
macro_db_client = { path = "../macro_db_client" }
macro_entrypoint = { path = "../macro_entrypoint" }
+macro_env_var = { path = "../macro_env_var" }
serde = { workspace = true }
serde_json = { workspace = true }
sqlx = { workspace = true }
diff --git a/rust/cloud-storage/email_suppression_handler/src/main.rs b/rust/cloud-storage/email_suppression_handler/src/main.rs
index b26422ae58..ae05959ca3 100644
--- a/rust/cloud-storage/email_suppression_handler/src/main.rs
+++ b/rust/cloud-storage/email_suppression_handler/src/main.rs
@@ -7,8 +7,13 @@ use anyhow::Context;
use aws_lambda_events::sns::SnsEvent;
use lambda_runtime::{Error, LambdaEvent, run, service_fn, tracing};
use macro_entrypoint::MacroEntrypoint;
+use macro_env_var::env_vars;
use sqlx::postgres::PgPoolOptions;
+env_vars! {
+ struct DatabaseUrl;
+}
+
#[tokio::main]
async fn main() -> Result<(), Error> {
MacroEntrypoint::default().init();
@@ -16,12 +21,12 @@ async fn main() -> Result<(), Error> {
tracing::trace!("initiating lambda");
tracing::trace!("initialized config");
- let database_url = std::env::var("DATABASE_URL").context("DATABASE_URL must be provided")?;
+ let database_url = DatabaseUrl::new().context("DATABASE_URL must be provided")?;
let db = PgPoolOptions::new()
.min_connections(1)
.max_connections(1) // we only ever need one connection per lambda
- .connect(&database_url)
+ .connect(database_url.as_ref())
.await
.context("could not connect to db")?;
diff --git a/rust/cloud-storage/foreign_entity/src/domain/models.rs b/rust/cloud-storage/foreign_entity/src/domain/models.rs
index f5b9b4a595..7015328b37 100644
--- a/rust/cloud-storage/foreign_entity/src/domain/models.rs
+++ b/rust/cloud-storage/foreign_entity/src/domain/models.rs
@@ -34,6 +34,7 @@ impl SourceId {
Self::new(id.to_string(), "team")
}
+ #[allow(dead_code)]
pub(crate) fn validate(&self) -> Result<(), ForeignEntityError> {
validate_non_blank("sourceId.id", &self.id)?;
validate_non_blank("sourceId.authEntity", &self.auth_entity)
@@ -113,6 +114,7 @@ pub enum ForeignEntityError {
}
impl CreateForeignEntity {
+ #[allow(dead_code)]
pub(crate) fn validate(&self) -> Result<(), ForeignEntityError> {
validate_non_blank("foreignEntityId", &self.foreign_entity_id)?;
validate_non_blank("foreignEntitySource", &self.foreign_entity_source)?;
@@ -124,6 +126,7 @@ impl CreateForeignEntity {
}
impl PatchForeignEntity {
+ #[allow(dead_code)]
pub(crate) fn validate(&self) -> Result<(), ForeignEntityError> {
if self.is_empty() {
return Err(ForeignEntityError::BadRequest(
@@ -142,6 +145,7 @@ impl PatchForeignEntity {
Ok(())
}
+ #[allow(dead_code)]
fn is_empty(&self) -> bool {
self.foreign_entity_id.is_none()
&& self.foreign_entity_source.is_none()
@@ -151,6 +155,7 @@ impl PatchForeignEntity {
}
}
+#[allow(dead_code)]
pub(crate) fn validate_foreign_entity_lookup(
foreign_entity_id: &str,
foreign_entity_source: Option<&str>,
@@ -163,6 +168,7 @@ fn default_metadata() -> Value {
Value::Object(serde_json::Map::new())
}
+#[allow(dead_code)]
fn validate_optional_non_blank(
field_name: &str,
value: Option<&str>,
@@ -174,6 +180,7 @@ fn validate_optional_non_blank(
Ok(())
}
+#[allow(dead_code)]
fn validate_non_blank(field_name: &str, value: &str) -> Result<(), ForeignEntityError> {
if value.trim().is_empty() {
return Err(ForeignEntityError::BadRequest(format!(
diff --git a/rust/cloud-storage/github/Cargo.toml b/rust/cloud-storage/github/Cargo.toml
index 2166f8c305..5a62998925 100644
--- a/rust/cloud-storage/github/Cargo.toml
+++ b/rust/cloud-storage/github/Cargo.toml
@@ -46,6 +46,7 @@ hex = { workspace = true }
hmac = { workspace = true }
jsonwebtoken = { workspace = true }
macro_env = { path = "../macro_env" }
+macro_env_var = { path = "../macro_env_var" }
macro_service_urls = { path = "../macro_service_urls" }
model-entity = { path = "../model-entity", optional = true }
model_notifications = { path = "../model_notifications", optional = true }
diff --git a/rust/cloud-storage/github/src/domain/service/sync/mod.rs b/rust/cloud-storage/github/src/domain/service/sync/mod.rs
index 6f634edec7..b158d3881e 100644
--- a/rust/cloud-storage/github/src/domain/service/sync/mod.rs
+++ b/rust/cloud-storage/github/src/domain/service/sync/mod.rs
@@ -26,6 +26,7 @@ use foreign_entity::domain::{
ports::ForeignEntityService,
};
use hmac::{Hmac, Mac};
+use macro_env_var::maybe_env_vars;
use notification::domain::service::NotificationIngress;
use sha2::Sha256;
use std::{collections::HashSet, sync::Arc};
@@ -33,6 +34,10 @@ use subtle::ConstantTimeEq;
type HmacSha256 = Hmac<Sha256>;
+maybe_env_vars! {
+ struct FrontendPort;
+}
+
/// Github sync config
#[derive(Debug)]
pub struct GithubSyncConfig {
@@ -998,7 +1003,9 @@ fn create_macro_task_comment_link(name: &str, id: &str) -> String {
macro_env::Environment::Production => "https://macro.com/app/task",
macro_env::Environment::Develop => "https://dev.macro.com/app/task",
macro_env::Environment::Local => {
- let port = std::env::var("FRONTEND_PORT").unwrap_or_else(|_| "3000".to_string());
+ let port = FrontendPort::new()
+ .map(|port| port.to_string())
+ .unwrap_or_else(|| "3000".to_string());
return format!("[{name}](http://localhost:{port}/app/task/{id})");
}
};
diff --git a/rust/cloud-storage/github/src/outbound/pull_request_metadata.rs b/rust/cloud-storage/github/src/outbound/pull_request_metadata.rs
index 78d7b7c61b..e73ee3f4c1 100644
--- a/rust/cloud-storage/github/src/outbound/pull_request_metadata.rs
+++ b/rust/cloud-storage/github/src/outbound/pull_request_metadata.rs
@@ -1,5 +1,7 @@
//! Shared GitHub pull request metadata fetcher.
+#![allow(dead_code)]
+
use std::collections::BTreeSet;
use std::time::Duration;
diff --git a/rust/cloud-storage/image_proxy_service/Cargo.toml b/rust/cloud-storage/image_proxy_service/Cargo.toml
index 170fce3e4a..5d77fef043 100644
--- a/rust/cloud-storage/image_proxy_service/Cargo.toml
+++ b/rust/cloud-storage/image_proxy_service/Cargo.toml
@@ -22,6 +22,7 @@ macro_aws_config = { path = "../macro_aws_config" }
macro_cors = { path = "../macro_cors" }
macro_entrypoint = { path = "../macro_entrypoint" }
macro_env = { path = "../macro_env" }
+macro_env_var = { path = "../macro_env_var" }
macro_middleware = { path = "../macro_middleware", default-features = false, features = [
"auth",
"tracking",
diff --git a/rust/cloud-storage/image_proxy_service/src/config.rs b/rust/cloud-storage/image_proxy_service/src/config.rs
index 8a63fcc0f0..46711eec00 100644
--- a/rust/cloud-storage/image_proxy_service/src/config.rs
+++ b/rust/cloud-storage/image_proxy_service/src/config.rs
@@ -1,4 +1,11 @@
+use anyhow::Context;
+
pub use macro_env::Environment;
+use macro_env_var::maybe_env_vars;
+
+maybe_env_vars! {
+ struct Port;
+}
/// The configuration parameters for the application.
#[derive(Debug)]
@@ -11,10 +18,10 @@ pub struct Config {
impl Config {
pub fn from_env() -> anyhow::Result<Self> {
- let port: usize = std::env::var("PORT")
- .unwrap_or("8080".to_string())
- .parse::<usize>()
- .unwrap();
+ let port = Port::new()
+ .map(|port| port.parse::<usize>().context("PORT must be a valid usize"))
+ .transpose()?
+ .unwrap_or(8080);
let environment = Environment::new_or_prod();
Ok(Config { port, environment })
diff --git a/rust/cloud-storage/invite_email/src/lib.rs b/rust/cloud-storage/invite_email/src/lib.rs
index c8e59e2dc6..3ae4fce79f 100644
--- a/rust/cloud-storage/invite_email/src/lib.rs
+++ b/rust/cloud-storage/invite_email/src/lib.rs
@@ -68,6 +68,7 @@ fn frontend_host(env: Environment) -> Url {
Environment::Production => "https://macro.com".to_string(),
Environment::Develop => "https://dev.macro.com".to_string(),
Environment::Local => {
+ #[expect(clippy::disallowed_methods, reason = "Only used when running locally")]
let port = std::env::var("FRONTEND_PORT").unwrap_or_else(|_| "3000".to_string());
format!("http://localhost:{port}")
}
diff --git a/rust/cloud-storage/macro_config/src/lib.rs b/rust/cloud-storage/macro_config/src/lib.rs
index e13a9c7c3b..58cd1ecdc7 100644
--- a/rust/cloud-storage/macro_config/src/lib.rs
+++ b/rust/cloud-storage/macro_config/src/lib.rs
@@ -103,6 +103,7 @@ where
/// 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> {
+ #[expect(clippy::disallowed_methods, reason = "Needs to read APP_SECRETS_JSON")]
match std::env::var("APP_SECRETS_JSON") {
Ok(raw) => {
let json = serde_json::from_str::<Value>(&raw)
diff --git a/rust/cloud-storage/macro_cors/src/lib.rs b/rust/cloud-storage/macro_cors/src/lib.rs
index 6ef7dd473c..cb9b24ddf3 100644
--- a/rust/cloud-storage/macro_cors/src/lib.rs
+++ b/rust/cloud-storage/macro_cors/src/lib.rs
@@ -28,6 +28,10 @@ static EXTRA_HEADERS: [&str; 4] = [
];
fn get_allowed_origins() -> Vec<Cow<'static, str>> {
+ #[allow(
+ clippy::disallowed_methods,
+ reason = "Used to override ALLOWED_ORIGINS when running locally"
+ )]
match std::env::var("ALLOWED_ORIGINS") {
Ok(origins) => origins
.split(',')
diff --git a/rust/cloud-storage/macro_entrypoint/Cargo.toml b/rust/cloud-storage/macro_entrypoint/Cargo.toml
index cd895a669d..a1fd66ca96 100644
--- a/rust/cloud-storage/macro_entrypoint/Cargo.toml
+++ b/rust/cloud-storage/macro_entrypoint/Cargo.toml
@@ -17,3 +17,4 @@ tracing-panic = "0.1"
tracing-subscriber = { workspace = true }
tracing-tree = { workspace = true }
workspace-hack = { version = "0.1", path = "../workspace-hack" }
+macro_env_var = { path = "../macro_env_var" }
diff --git a/rust/cloud-storage/macro_entrypoint/src/lib.rs b/rust/cloud-storage/macro_entrypoint/src/lib.rs
index 8d9942eccc..ed0ea1bf80 100644
--- a/rust/cloud-storage/macro_entrypoint/src/lib.rs
+++ b/rust/cloud-storage/macro_entrypoint/src/lib.rs
@@ -5,12 +5,18 @@
mod datadog_fmt;
use macro_env::Environment;
+use macro_env_var::env_vars;
use opentelemetry::trace::TracerProvider as _;
use opentelemetry_otlp::WithExportConfig;
use opentelemetry_sdk::trace::SdkTracerProvider;
use tracing_subscriber::{EnvFilter, Registry, layer::SubscriberExt, util::SubscriberInitExt};
use tracing_tree::HierarchicalLayer;
+env_vars! {
+ pub struct DdService;
+ pub struct DdEnv;
+}
+
/// unit struct which defines the behaviour for instantiation
#[derive(Debug)]
pub struct MacroEntrypoint {
@@ -91,8 +97,9 @@ impl MacroEntrypoint {
let tracer_provider = init_opentelemetry();
// Get service name for the tracer
- let service_name =
- std::env::var("DD_SERVICE").unwrap_or_else(|_| "unknown-service".to_string());
+ let service_name = DdService::new()
+ .map(|e| e.to_string())
+ .unwrap_or_else(|_| "unknown-service".to_string());
let tracer = tracer_provider.tracer(service_name);
let otel_layer = tracing_opentelemetry::layer().with_tracer(tracer);
@@ -147,11 +154,14 @@ fn init_opentelemetry() -> SdkTracerProvider {
.expect("failed to create OTLP span exporter");
// Get service name from DD_SERVICE or OTEL_SERVICE_NAME
- let service_name =
- std::env::var("DD_SERVICE").unwrap_or_else(|_| "unknown-service".to_string());
+ let service_name = DdService::new()
+ .map(|e| e.to_string())
+ .unwrap_or_else(|_| "unknown-service".to_string());
// Get environment from DD_ENV
- let env = std::env::var("DD_ENV").unwrap_or_else(|_| "unknown".to_string());
+ let env = DdEnv::new()
+ .map(|e| e.to_string())
+ .unwrap_or_else(|_| "unknown".to_string());
let resource = opentelemetry_sdk::Resource::builder()
.with_service_name(service_name)
diff --git a/rust/cloud-storage/macro_env_var/src/lib.rs b/rust/cloud-storage/macro_env_var/src/lib.rs
index c1d7bf4fa6..981f920ec8 100644
--- a/rust/cloud-storage/macro_env_var/src/lib.rs
+++ b/rust/cloud-storage/macro_env_var/src/lib.rs
@@ -6,6 +6,10 @@ use thiserror::Error;
const APP_SECRETS_JSON_ENV: &str = "APP_SECRETS_JSON";
#[allow(dead_code)]
+#[allow(
+ clippy::disallowed_methods,
+ reason = "macro_env_var is the sanctioned wrapper around std::env::var"
+)]
fn read_std_env(s: &'static str) -> Result<String, std::env::VarError> {
std::env::var(s)
}
@@ -86,6 +90,10 @@ mod testing_harness {
}
}
+ #[allow(
+ clippy::disallowed_methods,
+ reason = "test harness falls back to the same sanctioned std::env::var wrapper behavior"
+ )]
fn get_env(s: &'static str) -> Result<String, std::env::VarError> {
let cur_getter = MOCK_VAR_GETTER.replace(None);
match cur_getter {
diff --git a/rust/cloud-storage/macro_middleware/src/auth/attach_user.rs b/rust/cloud-storage/macro_middleware/src/auth/attach_user.rs
index cac337421e..70bf9a5a16 100644
--- a/rust/cloud-storage/macro_middleware/src/auth/attach_user.rs
+++ b/rust/cloud-storage/macro_middleware/src/auth/attach_user.rs
@@ -13,8 +13,14 @@ use macro_auth::{
middleware::decode_jwt::{JwtToken, JwtValidationArgs},
};
+use macro_env_var::maybe_env_vars;
use model::{response::ErrorResponse, user::UserContext};
+maybe_env_vars! {
+ struct LocalUserId;
+ struct LocalFusionUserId;
+}
+
/// Attempts to decode the JWT and attach user to the request context
/// If there is no JWT to decode, the user context remains empty
pub async fn handler(
@@ -25,8 +31,12 @@ pub async fn handler(
) -> Result<Response, Response> {
if cfg!(feature = "local_auth") {
req.extensions_mut().insert(UserContext {
- user_id: std::env::var("LOCAL_USER_ID").unwrap_or("macro|[email protected]".to_string()),
- fusion_user_id: std::env::var("LOCAL_FUSION_USER_ID").unwrap_or("set me!".to_string()),
+ user_id: LocalUserId::new()
+ .map(|user_id| user_id.to_string())
+ .unwrap_or_else(|| "macro|[email protected]".to_string()),
+ fusion_user_id: LocalFusionUserId::new()
+ .map(|fusion_user_id| fusion_user_id.to_string())
+ .unwrap_or_else(|| "set me!".to_string()),
organization_id: Some(1),
permissions: None,
});
diff --git a/rust/cloud-storage/macro_service_urls/src/lib.rs b/rust/cloud-storage/macro_service_urls/src/lib.rs
index b6d2d2b78a..c52307435d 100644
--- a/rust/cloud-storage/macro_service_urls/src/lib.rs
+++ b/rust/cloud-storage/macro_service_urls/src/lib.rs
@@ -76,6 +76,10 @@ pub use testing_harness::read_override_env;
/// Read an override environment variable for a service URL.
#[cfg(not(test))]
#[doc(hidden)]
+#[allow(
+ clippy::disallowed_methods,
+ reason = "Used when running locally to override service urls"
+)]
pub fn read_override_env(var_name: &'static str) -> Result<Option<String>, ServiceUrlVarErr> {
std::env::var(var_name).map(Some).or_else(|err| match err {
std::env::VarError::NotPresent => Ok(None),
diff --git a/rust/cloud-storage/mcp_service/src/main.rs b/rust/cloud-storage/mcp_service/src/main.rs
index 32c493ec25..4df1bec0d0 100644
--- a/rust/cloud-storage/mcp_service/src/main.rs
+++ b/rust/cloud-storage/mcp_service/src/main.rs
@@ -9,6 +9,7 @@ mod tool_service;
use anyhow::Context;
use context::build_context;
use macro_entrypoint::MacroEntrypoint;
+use macro_env_var::maybe_env_vars;
use mcp_auth_proxy::domain::service::McpAuthProxyService;
use mcp_auth_proxy::inbound::axum_router::mcp_router;
use rmcp::transport::streamable_http_server::{
@@ -20,6 +21,10 @@ use tool_service::AuthenticatedToolService;
const AUTH_PROXY_CLEANUP_INTERVAL: Duration = Duration::from_secs(60);
+maybe_env_vars! {
+ struct Port;
+}
+
#[tokio::main]
#[tracing::instrument(err)]
async fn main() -> anyhow::Result<()> {
@@ -64,7 +69,9 @@ async fn main() -> anyhow::Result<()> {
let app = mcp_router(context.auth_proxy, context.jwt_args, mcp_service);
- let port = std::env::var("PORT").unwrap_or_else(|_| "8090".to_string());
+ let port = Port::new()
+ .map(|port| port.to_string())
+ .unwrap_or_else(|| "8090".to_string());
let addr = format!("0.0.0.0:{port}");
let listener = tokio::net::TcpListener::bind(&addr)
.await
diff --git a/rust/cloud-storage/native_app_service/Cargo.toml b/rust/cloud-storage/native_app_service/Cargo.toml
index cccf5dbf40..0c68c4defe 100644
--- a/rust/cloud-storage/native_app_service/Cargo.toml
+++ b/rust/cloud-storage/native_app_service/Cargo.toml
@@ -18,6 +18,7 @@ tokio = { workspace = true }
tracing = { workspace = true }
url = { workspace = true, features = ["serde"] }
workspace-hack = { version = "0.1", path = "../workspace-hack" }
+macro_env_var = { path = "../macro_env_var" }
[dev-dependencies]
cool_asserts = "2"
diff --git a/rust/cloud-storage/native_app_service/src/outbound.rs b/rust/cloud-storage/native_app_service/src/outbound.rs
index daa52a0e83..5033e569e7 100644
--- a/rust/cloud-storage/native_app_service/src/outbound.rs
+++ b/rust/cloud-storage/native_app_service/src/outbound.rs
@@ -6,11 +6,17 @@ use crate::domain::{
ports::GetJsBundleManifest,
};
use futures::StreamExt;
+use macro_env_var::env_vars;
use rootcause::{Report, prelude::ResultExt};
use sha2::{Digest, Sha256};
use tokio::sync::RwLock;
use url::Url;
+env_vars! {
+ pub struct BundleUpdatePolicyJson;
+ pub struct BundleUpdatePolicyFile;
+}
+
struct BundleChecksumCache {
inner: RwLock<Option<(u64, String)>>,
}
@@ -113,11 +119,11 @@ impl GetJsBundleManifest for DefaultBundleFetcher {
impl BundleUpdatePolicy {
/// Load bundle update policy from `BUNDLE_UPDATE_POLICY_JSON` or `BUNDLE_UPDATE_POLICY_FILE`.
pub fn from_env() -> Result<Self, Report<UpdateErr>> {
- if let Ok(json) = std::env::var("BUNDLE_UPDATE_POLICY_JSON") {
+ if let Ok(json) = BundleUpdatePolicyJson::new() {
return serde_json::from_str(&json).context(UpdateErr::Policy);
}
- if let Ok(path) = std::env::var("BUNDLE_UPDATE_POLICY_FILE") {
- let json = std::fs::read_to_string(path).context(UpdateErr::Policy)?;
+ if let Ok(path) = BundleUpdatePolicyFile::new() {
+ let json = std::fs::read_to_string(path.as_ref()).context(UpdateErr::Policy)?;
return serde_json::from_str(&json).context(UpdateErr::Policy);
}
Ok(Self::default())
diff --git a/rust/cloud-storage/notification_sandbox/src/main.rs b/rust/cloud-storage/notification_sandbox/src/main.rs
index ce9d542d34..cffdf86ec6 100644
--- a/rust/cloud-storage/notification_sandbox/src/main.rs
+++ b/rust/cloud-storage/notification_sandbox/src/main.rs
@@ -70,12 +70,14 @@ async fn main() -> Result<(), Report> {
println!("\n=== Notification Digest Sandbox ===\n");
// --- Phase 1: Connect to persistence ---
+ #[expect(clippy::disallowed_methods, reason = "Only used when running locally")]
let default_db = std::env::var("DATABASE_URL")
.unwrap_or_else(|_| "postgres://user:password@localhost:5432/macrodb".to_string());
let database_url = inquire::Text::new("Postgres URL?")
.with_default(&default_db)
.prompt()?;
+ #[expect(clippy::disallowed_methods, reason = "Only used when running locally")]
let default_redis =
std::env::var("REDIS_URI").unwrap_or_else(|_| "redis://localhost:6379".to_string());
let redis_uri = inquire::Text::new("Redis URL?")
@@ -377,6 +379,7 @@ async fn poll_email_digests(egress: &impl NotificationEgress) -> Result<(), Repo
fn digest_to_sandbox(
batch: notification::domain::models::email_notification_digest::ports::DigestBatch,
) -> Result<SandboxNotification, Report> {
+ #[expect(clippy::disallowed_methods, reason = "Only used when running locally")]
let secret = std::env::var("URL_SIGNING_HMAC")
.unwrap_or_else(|_| "sandbox-default-hmac-secret".to_string());
let hmac_key = Hmac::<sha2::Sha256>::new_from_slice(secret.as_bytes())
diff --git a/rust/cloud-storage/organization_retention_handler/Cargo.toml b/rust/cloud-storage/organization_retention_handler/Cargo.toml
index 5cf18be031..1535257c55 100644
--- a/rust/cloud-storage/organization_retention_handler/Cargo.toml
+++ b/rust/cloud-storage/organization_retention_handler/Cargo.toml
@@ -11,6 +11,7 @@ macro_aws_config = { path = "../macro_aws_config" }
aws_lambda_events = { workspace = true, features = ["sqs"] }
lambda_runtime = { workspace = true }
macro_entrypoint = { path = "../macro_entrypoint" }
+macro_env_var = { path = "../macro_env_var" }
sqlx = { workspace = true }
sqs_client = { path = "../sqs_client" }
tokio = { workspace = true }
diff --git a/rust/cloud-storage/organization_retention_handler/src/main.rs b/rust/cloud-storage/organization_retention_handler/src/main.rs
index 6c3faece5d..416191df5b 100644
--- a/rust/cloud-storage/organization_retention_handler/src/main.rs
+++ b/rust/cloud-storage/organization_retention_handler/src/main.rs
@@ -8,34 +8,40 @@ use aws_lambda_events::sqs::SqsEvent;
use handler::handler;
use lambda_runtime::{Error, LambdaEvent, run, service_fn, tracing};
use macro_entrypoint::MacroEntrypoint;
+use macro_env_var::env_vars;
use sqlx::postgres::PgPoolOptions;
+env_vars! {
+ struct DatabaseUrl;
+ struct DocumentDeleteQueue;
+ struct ChatDeleteQueue;
+}
+
#[tokio::main]
async fn main() -> Result<(), Error> {
MacroEntrypoint::default().init();
tracing::trace!("initiating lambda");
- let database_url = std::env::var("DATABASE_URL").context("DATABASE_URL must be provided")?;
+ let database_url = DatabaseUrl::new().context("DATABASE_URL must be provided")?;
let db = service::db::DB::new(
PgPoolOptions::new()
.min_connections(1)
.max_connections(1) // we only ever need one connection per lambda
- .connect(&database_url)
+ .connect(database_url.as_ref())
.await
.context("could not connect to db")?,
);
let document_delete_queue =
- std::env::var("DOCUMENT_DELETE_QUEUE").context("DOCUMENT_DELETE_QUEUE must be provided")?;
- let chat_delete_queue =
- std::env::var("CHAT_DELETE_QUEUE").context("CHAT_DELETE_QUEUE must be provided")?;
+ DocumentDeleteQueue::new().context("DOCUMENT_DELETE_QUEUE must be provided")?;
+ let chat_delete_queue = ChatDeleteQueue::new().context("CHAT_DELETE_QUEUE must be provided")?;
let sqs_client = sqs_client::SQS::new(aws_sdk_sqs::Client::new(
&macro_aws_config::get_macro_aws_config().await,
))
- .document_delete_queue(&document_delete_queue)
- .chat_delete_queue(&chat_delete_queue);
+ .document_delete_queue(document_delete_queue.as_ref())
+ .chat_delete_queue(chat_delete_queue.as_ref());
let shared_db = Arc::new(db);
let shared_sqs_client = Arc::new(sqs_client);
diff --git a/rust/cloud-storage/organization_retention_trigger/Cargo.toml b/rust/cloud-storage/organization_retention_trigger/Cargo.toml
index 2c98e407f3..f0fbed8ebc 100644
--- a/rust/cloud-storage/organization_retention_trigger/Cargo.toml
+++ b/rust/cloud-storage/organization_retention_trigger/Cargo.toml
@@ -11,6 +11,7 @@ macro_aws_config = { path = "../macro_aws_config" }
aws_lambda_events = { workspace = true, features = ["eventbridge"] }
lambda_runtime = { workspace = true }
macro_entrypoint = { path = "../macro_entrypoint" }
+macro_env_var = { path = "../macro_env_var" }
serde_json = { workspace = true }
sqlx = { workspace = true }
sqs_client = { path = "../sqs_client" }
diff --git a/rust/cloud-storage/organization_retention_trigger/src/main.rs b/rust/cloud-storage/organization_retention_trigger/src/main.rs
index ed31316ff9..1203e24718 100644
--- a/rust/cloud-storage/organization_retention_trigger/src/main.rs
+++ b/rust/cloud-storage/organization_retention_trigger/src/main.rs
@@ -9,8 +9,14 @@ use lambda_runtime::{
tracing::{self},
};
use macro_entrypoint::MacroEntrypoint;
+use macro_env_var::env_vars;
use sqlx::postgres::PgPoolOptions;
+env_vars! {
+ struct DatabaseUrl;
+ struct OrganizationRetentionQueue;
+}
+
#[tracing::instrument(skip(db, sqs_client, event))]
async fn handler(
db: Arc<service::db::DB>,
@@ -34,24 +40,24 @@ async fn main() -> Result<(), Error> {
tracing::info!("initiating lambda");
- let database_url = std::env::var("DATABASE_URL").context("DATABASE_URL must be set")?;
+ let database_url = DatabaseUrl::new().context("DATABASE_URL must be set")?;
let db = service::db::DB::new(
PgPoolOptions::new()
.min_connections(1)
.max_connections(1) // we only ever need one connection per lambda
- .connect(&database_url)
+ .connect(database_url.as_ref())
.await
.context("could not connect to db")?,
);
tracing::trace!("initialized db client");
- let organization_retention_queue = std::env::var("ORGANIZATION_RETENTION_QUEUE")
- .context("ORGANIZATION_RETENTION_QUEUE must be set")?;
+ let organization_retention_queue =
+ OrganizationRetentionQueue::new().context("ORGANIZATION_RETENTION_QUEUE must be set")?;
let sqs_client = sqs_client::SQS::new(aws_sdk_sqs::Client::new(
&macro_aws_config::get_macro_aws_config().await,
))
- .organization_retention_queue(&organization_retention_queue);
+ .organization_retention_queue(organization_retention_queue.as_ref());
tracing::trace!("initialized ecs client");
diff --git a/rust/cloud-storage/search_processing_service/Cargo.toml b/rust/cloud-storage/search_processing_service/Cargo.toml
index 72e2435df0..b8b41a5c93 100644
--- a/rust/cloud-storage/search_processing_service/Cargo.toml
+++ b/rust/cloud-storage/search_processing_service/Cargo.toml
@@ -33,6 +33,7 @@ macro_cors = { path = "../macro_cors" }
macro_db_client = { path = "../macro_db_client", optional = true } # Make this optional
macro_entrypoint = { path = "../macro_entrypoint" }
macro_env = { path = "../macro_env" }
+macro_env_var = { path = "../macro_env_var" }
macro_middleware = { path = "../macro_middleware", default-features = false, features = [
"auth",
] }
diff --git a/rust/cloud-storage/search_processing_service/src/config.rs b/rust/cloud-storage/search_processing_service/src/config.rs
index 8870a362e1..acb12f1c6f 100644
--- a/rust/cloud-storage/search_processing_service/src/config.rs
+++ b/rust/cloud-storage/search_processing_service/src/config.rs
@@ -1,7 +1,32 @@
use anyhow::Context;
pub use macro_env::Environment;
+use macro_env_var::{env_vars, maybe_env_vars};
use macro_service_urls::LexicalServiceUrl;
+env_vars! {
+ struct DatabaseUrl;
+ struct SearchEventQueue;
+ struct OpensearchUrl;
+ struct OpensearchUsername;
+ struct OpensearchPassword;
+ struct DocumentStorageBucket;
+ struct BackfillJobsTable;
+}
+
+maybe_env_vars! {
+ struct DatabaseUrlReadonly;
+ struct Port;
+ struct QueueMaxMessages;
+ struct QueueWaitTimeSeconds;
+ struct WorkerCount;
+ struct BackfillCallsPageSize;
+ struct BackfillChatsPageSize;
+ struct BackfillChannelsPageSize;
+ struct BackfillDocumentsPageSize;
+ struct BackfillEmailsPageSize;
+ struct BackfillJobTtlSeconds;
+}
+
/// Per-entity DB page sizes used by the backfill source adapters. Tunable at
/// runtime via the corresponding `BACKFILL_*_PAGE_SIZE` env vars.
#[derive(Debug, Clone, Copy)]
@@ -74,9 +99,9 @@ pub struct Config {
pub backfill_job_ttl_seconds: u64,
}
-fn parse_page_size(name: &str, default: usize) -> anyhow::Result<usize> {
- match std::env::var(name) {
- Ok(raw) => raw
+fn parse_page_size(name: &str, raw_value: Option<String>, default: usize) -> anyhow::Result<usize> {
+ match raw_value {
+ Some(raw) => raw
.parse::<usize>()
.with_context(|| format!("{name} must be a positive integer"))
.and_then(|n| {
@@ -85,68 +110,111 @@ fn parse_page_size(name: &str, default: usize) -> anyhow::Result<usize> {
}
Ok(n)
}),
- Err(_) => Ok(default),
+ None => Ok(default),
}
}
impl Config {
pub fn from_env() -> anyhow::Result<Self> {
- let database_url =
- std::env::var("DATABASE_URL").context("DATABASE_URL must be provided")?;
+ let database_url = DatabaseUrl::new()
+ .context("DATABASE_URL must be provided")?
+ .to_string();
- let database_url_readonly = std::env::var("DATABASE_URL_READONLY").ok();
+ let database_url_readonly = DatabaseUrlReadonly::new().map(|url| url.to_string());
- let port: usize = std::env::var("PORT")
- .unwrap_or("8080".to_string())
- .parse::<usize>()
- .context("should be valid port number")?;
+ let port = Port::new()
+ .map(|port| port.parse::<usize>().context("should be valid port number"))
+ .transpose()?
+ .unwrap_or(8080);
let environment = Environment::new_or_prod();
- let search_event_queue =
- std::env::var("SEARCH_EVENT_QUEUE").context("SEARCH_EVENT_QUEUE must be provided")?;
-
- let queue_max_messages: i32 = std::env::var("QUEUE_MAX_MESSAGES")
- .unwrap_or("10".to_string())
- .parse::<i32>()
- .unwrap();
-
- let queue_wait_time_seconds: i32 = std::env::var("QUEUE_WAIT_TIME_SECONDS")
- .unwrap_or("20".to_string())
- .parse::<i32>()
- .unwrap();
-
- let opensearch_url =
- std::env::var("OPENSEARCH_URL").context("OPENSEARCH_URL must be provided")?;
- let opensearch_username =
- std::env::var("OPENSEARCH_USERNAME").context("OPENSEARCH_USERNAME must be provided")?;
- let opensearch_password =
- std::env::var("OPENSEARCH_PASSWORD").context("OPENSEARCH_PASSWORD must be provided")?;
-
- let document_storage_bucket = std::env::var("DOCUMENT_STORAGE_BUCKET")
- .context("DOCUMENT_STORAGE_BUCKET must be provided")?;
-
- let worker_count: u8 = std::env::var("WORKER_COUNT")
- .unwrap_or("10".to_string())
- .parse::<u8>()
- .unwrap();
+ let search_event_queue = SearchEventQueue::new()
+ .context("SEARCH_EVENT_QUEUE must be provided")?
+ .to_string();
+
+ let queue_max_messages = QueueMaxMessages::new()
+ .map(|queue_max_messages| {
+ queue_max_messages
+ .parse::<i32>()
+ .context("QUEUE_MAX_MESSAGES must be a valid i32")
+ })
+ .transpose()?
+ .unwrap_or(10);
+
+ let queue_wait_time_seconds = QueueWaitTimeSeconds::new()
+ .map(|queue_wait_time_seconds| {
+ queue_wait_time_seconds
+ .parse::<i32>()
+ .context("QUEUE_WAIT_TIME_SECONDS must be a valid i32")
+ })
+ .transpose()?
+ .unwrap_or(20);
+
+ let opensearch_url = OpensearchUrl::new()
+ .context("OPENSEARCH_URL must be provided")?
+ .to_string();
+ let opensearch_username = OpensearchUsername::new()
+ .context("OPENSEARCH_USERNAME must be provided")?
+ .to_string();
+ let opensearch_password = OpensearchPassword::new()
+ .context("OPENSEARCH_PASSWORD must be provided")?
+ .to_string();
+
+ let document_storage_bucket = DocumentStorageBucket::new()
+ .context("DOCUMENT_STORAGE_BUCKET must be provided")?
+ .to_string();
+
+ let worker_count = WorkerCount::new()
+ .map(|worker_count| {
+ worker_count
+ .parse::<u8>()
+ .context("WORKER_COUNT must be a valid u8")
+ })
+ .transpose()?
+ .unwrap_or(10);
let lexical_service_url = LexicalServiceUrl::new()?.to_string();
let backfill_page_sizes = BackfillPageSizes {
- calls: parse_page_size("BACKFILL_CALLS_PAGE_SIZE", DEFAULT_CALLS_PAGE)?,
- chats: parse_page_size("BACKFILL_CHATS_PAGE_SIZE", DEFAULT_CHATS_PAGE)?,
- channels: parse_page_size("BACKFILL_CHANNELS_PAGE_SIZE", DEFAULT_CHANNELS_PAGE)?,
- documents: parse_page_size("BACKFILL_DOCUMENTS_PAGE_SIZE", DEFAULT_DOCUMENTS_PAGE)?,
- emails: parse_page_size("BACKFILL_EMAILS_PAGE_SIZE", DEFAULT_EMAILS_PAGE)?,
+ calls: parse_page_size(
+ "BACKFILL_CALLS_PAGE_SIZE",
+ BackfillCallsPageSize::new().map(|value| value.to_string()),
+ DEFAULT_CALLS_PAGE,
+ )?,
+ chats: parse_page_size(
+ "BACKFILL_CHATS_PAGE_SIZE",
+ BackfillChatsPageSize::new().map(|value| value.to_string()),
+ DEFAULT_CHATS_PAGE,
+ )?,
+ channels: parse_page_size(
+ "BACKFILL_CHANNELS_PAGE_SIZE",
+ BackfillChannelsPageSize::new().map(|value| value.to_string()),
+ DEFAULT_CHANNELS_PAGE,
+ )?,
+ documents: parse_page_size(
+ "BACKFILL_DOCUMENTS_PAGE_SIZE",
+ BackfillDocumentsPageSize::new().map(|value| value.to_string()),
+ DEFAULT_DOCUMENTS_PAGE,
+ )?,
+ emails: parse_page_size(
+ "BACKFILL_EMAILS_PAGE_SIZE",
+ BackfillEmailsPageSize::new().map(|value| value.to_string()),
+ DEFAULT_EMAILS_PAGE,
+ )?,
};
- let backfill_jobs_table =
- std::env::var("BACKFILL_JOBS_TABLE").context("BACKFILL_JOBS_TABLE must be provided")?;
- let backfill_job_ttl_seconds: u64 = std::env::var("BACKFILL_JOB_TTL_SECONDS")
- .unwrap_or_else(|_| (24 * 60 * 60).to_string())
- .parse()
- .context("BACKFILL_JOB_TTL_SECONDS must be a positive integer")?;
+ let backfill_jobs_table = BackfillJobsTable::new()
+ .context("BACKFILL_JOBS_TABLE must be provided")?
+ .to_string();
+ let backfill_job_ttl_seconds = BackfillJobTtlSeconds::new()
+ .map(|backfill_job_ttl_seconds| {
+ backfill_job_ttl_seconds
+ .parse::<u64>()
+ .context("BACKFILL_JOB_TTL_SECONDS must be a positive integer")
+ })
+ .transpose()?
+ .unwrap_or(24 * 60 * 60);
Ok(Config {
database_url,
diff --git a/rust/cloud-storage/search_service/Cargo.toml b/rust/cloud-storage/search_service/Cargo.toml
index 236583016e..b7381b1dd6 100644
--- a/rust/cloud-storage/search_service/Cargo.toml
+++ b/rust/cloud-storage/search_service/Cargo.toml
@@ -37,6 +37,7 @@ models_soup = { path = "../models_soup" }
properties_db_client = { path = "../properties_db_client" }
readonly_pool = { path = "../readonly_pool" }
macro_env = { path = "../macro_env" }
+macro_env_var = { path = "../macro_env_var" }
macro_middleware = { path = "../macro_middleware", default-features = false, features = [
"auth",
] }
diff --git a/rust/cloud-storage/search_service/src/config.rs b/rust/cloud-storage/search_service/src/config.rs
index 4df66accbe..4e589a2243 100644
--- a/rust/cloud-storage/search_service/src/config.rs
+++ b/rust/cloud-storage/search_service/src/config.rs
@@ -1,8 +1,20 @@
use anyhow::Context;
pub use macro_env::Environment;
+use macro_env_var::{env_vars, maybe_env_vars};
use macro_middleware::auth::internal_access::InternalApiSecretKey;
use secretsmanager_client::LocalOrRemoteSecret;
+env_vars! {
+ struct DatabaseUrl;
+ struct OpensearchUrl;
+ struct OpensearchUsername;
+ struct OpensearchPassword;
+}
+
+maybe_env_vars! {
+ struct Port;
+}
+
pub struct Config {
/// The port to listen for HTTP requests on.
pub port: usize,
@@ -24,22 +36,26 @@ pub struct Config {
impl Config {
pub fn from_env() -> anyhow::Result<Self> {
- let port: usize = std::env::var("PORT")
- .unwrap_or("8080".to_string())
- .parse::<usize>()
- .context("should be valid port number")?;
+ let port = Port::new()
+ .map(|port| port.parse::<usize>().context("should be valid port number"))
+ .transpose()?
+ .unwrap_or(8080);
let environment = Environment::new_or_prod();
- let database_url =
- std::env::var("DATABASE_URL").context("DATABASE_URL must be provided")?;
+ let database_url = DatabaseUrl::new()
+ .context("DATABASE_URL must be provided")?
+ .to_string();
- let opensearch_url =
- std::env::var("OPENSEARCH_URL").context("OPENSEARCH_URL must be provided")?;
- let opensearch_username =
- std::env::var("OPENSEARCH_USERNAME").context("OPENSEARCH_USERNAME must be provided")?;
- let opensearch_password =
- std::env::var("OPENSEARCH_PASSWORD").context("OPENSEARCH_PASSWORD must be provided")?;
+ let opensearch_url = OpensearchUrl::new()
+ .context("OPENSEARCH_URL must be provided")?
+ .to_string();
+ let opensearch_username = OpensearchUsername::new()
+ .context("OPENSEARCH_USERNAME must be provided")?
+ .to_string();
+ let opensearch_password = OpensearchPassword::new()
+ .context("OPENSEARCH_PASSWORD must be provided")?
+ .to_string();
let internal_auth_key = LocalOrRemoteSecret::Local(InternalApiSecretKey::new()?);
diff --git a/rust/cloud-storage/search_upload_handler/Cargo.toml b/rust/cloud-storage/search_upload_handler/Cargo.toml
index 829b49a7ef..907b073fb0 100644
--- a/rust/cloud-storage/search_upload_handler/Cargo.toml
+++ b/rust/cloud-storage/search_upload_handler/Cargo.toml
@@ -12,6 +12,7 @@ macro_aws_config = { path = "../macro_aws_config" }
aws_lambda_events = { workspace = true, features = ["eventbridge"] }
lambda_runtime = { workspace = true }
macro_entrypoint = { path = "../macro_entrypoint" }
+macro_env_var = { path = "../macro_env_var" }
s3_key = { path = "../s3_key" }
sqs_client = { path = "../sqs_client", default-features = false, features = [
"search",
diff --git a/rust/cloud-storage/search_upload_handler/src/main.rs b/rust/cloud-storage/search_upload_handler/src/main.rs
index 47eb83b2c3..a5b34f6d9f 100644
--- a/rust/cloud-storage/search_upload_handler/src/main.rs
+++ b/rust/cloud-storage/search_upload_handler/src/main.rs
@@ -4,11 +4,17 @@ use document_storage_service_client::DocumentStorageServiceClient;
use handler::handler;
use lambda_runtime::{Error, LambdaEvent, run, service_fn, tracing};
use macro_entrypoint::MacroEntrypoint;
+use macro_env_var::env_vars;
use macro_service_urls::DocumentStorageServiceUrl;
use std::sync::Arc;
mod handler;
+env_vars! {
+ struct SearchEventQueue;
+ struct DocumentStorageServiceAuthKey;
+}
+
#[tokio::main]
async fn main() -> Result<(), Error> {
MacroEntrypoint::default().init();
@@ -16,16 +22,17 @@ async fn main() -> Result<(), Error> {
tracing::trace!("initiating lambda");
let search_event_queue =
- std::env::var("SEARCH_EVENT_QUEUE").context("SEARCH_EVENT_QUEUE must be provided")?;
+ SearchEventQueue::new().context("SEARCH_EVENT_QUEUE must be provided")?;
let dss_url = DocumentStorageServiceUrl::new()?.to_string();
- let dss_auth_key = std::env::var("DOCUMENT_STORAGE_SERVICE_AUTH_KEY")
- .context("DOCUMENT_STORAGE_SERVICE_AUTH_KEY must be provided")?;
+ let dss_auth_key = DocumentStorageServiceAuthKey::new()
+ .context("DOCUMENT_STORAGE_SERVICE_AUTH_KEY must be provided")?
+ .to_string();
let sqs_client = sqs_client::SQS::new(aws_sdk_sqs::Client::new(
&macro_aws_config::get_macro_aws_config().await,
))
- .search_event_queue(&search_event_queue);
+ .search_event_queue(search_event_queue.as_ref());
let shared_sqs_client = Arc::new(sqs_client);
let shared_dss_client = Arc::new(DocumentStorageServiceClient::new(dss_auth_key, dss_url));
diff --git a/rust/cloud-storage/seed_cli/src/entity/scenario/mod.rs b/rust/cloud-storage/seed_cli/src/entity/scenario/mod.rs
index 865d7433b4..353c68910f 100644
--- a/rust/cloud-storage/seed_cli/src/entity/scenario/mod.rs
+++ b/rust/cloud-storage/seed_cli/src/entity/scenario/mod.rs
@@ -215,6 +215,7 @@ impl ScenarioArgs {
}
}
+#[allow(clippy::disallowed_methods, reason = "Only used when running locally")]
fn validate_local_e2e_environment(database_url: &str) -> anyhow::Result<()> {
ensure!(
std::env::var("LOCAL_E2E_SEED").as_deref() == Ok("true"),
diff --git a/rust/cloud-storage/sha_cleanup_worker/Cargo.toml b/rust/cloud-storage/sha_cleanup_worker/Cargo.toml
index bcbe90e38d..e45c992d35 100644
--- a/rust/cloud-storage/sha_cleanup_worker/Cargo.toml
+++ b/rust/cloud-storage/sha_cleanup_worker/Cargo.toml
@@ -15,6 +15,7 @@ macro_aws_config = { path = "../macro_aws_config", features = ["s3"] }
futures = { workspace = true }
macro_entrypoint = { path = "../macro_entrypoint" }
macro_env = { path = "../macro_env" }
+macro_env_var = { path = "../macro_env_var" }
mockall = { workspace = true }
redis = { workspace = true, features = [
"aio",
diff --git a/rust/cloud-storage/sha_cleanup_worker/src/config.rs b/rust/cloud-storage/sha_cleanup_worker/src/config.rs
index fdba3a2c11..a0b89ce587 100644
--- a/rust/cloud-storage/sha_cleanup_worker/src/config.rs
+++ b/rust/cloud-storage/sha_cleanup_worker/src/config.rs
@@ -1,4 +1,13 @@
+use anyhow::Context;
+
pub use macro_env::Environment;
+use macro_env_var::env_vars;
+
+env_vars! {
+ struct RedisUri;
+ struct DatabaseUrl;
+ struct DocumentStorageBucket;
+}
/// The configuration parameters for the application.
///
@@ -38,15 +47,15 @@ impl Config {
}
pub fn from_env() -> anyhow::Result<Self> {
- let redis_uri = std::env::var("REDIS_URI").expect("REDIS_URI must be provided");
- let database_url = std::env::var("DATABASE_URL").expect("DATABASE_URL must be provided");
- let document_storage_bucket = std::env::var("DOCUMENT_STORAGE_BUCKET")
- .expect("DOCUMENT_STORAGE_BUCKET must be provided");
+ let redis_uri = RedisUri::new().context("REDIS_URI must be provided")?;
+ let database_url = DatabaseUrl::new().context("DATABASE_URL must be provided")?;
+ let document_storage_bucket =
+ DocumentStorageBucket::new().context("DOCUMENT_STORAGE_BUCKET must be provided")?;
let environment = Environment::new_or_prod();
Ok(Config::new(
- redis_uri.as_str(),
- database_url.as_str(),
- document_storage_bucket.as_str(),
+ redis_uri.as_ref(),
+ database_url.as_ref(),
+ document_storage_bucket.as_ref(),
environment,
))
}
diff --git a/rust/cloud-storage/static_file_service/Cargo.toml b/rust/cloud-storage/static_file_service/Cargo.toml
index df9a7ca367..e3b4f075fb 100644
--- a/rust/cloud-storage/static_file_service/Cargo.toml
+++ b/rust/cloud-storage/static_file_service/Cargo.toml
@@ -30,6 +30,7 @@ macro_aws_config = { path = "../macro_aws_config", features = ["s3"] }
macro_cors = { path = "../macro_cors" }
macro_entrypoint = { path = "../macro_entrypoint" }
macro_env = { path = "../macro_env" }
+macro_env_var = { path = "../macro_env_var" }
macro_middleware = { path = "../macro_middleware", default-features = false, features = [
"auth",
] }
diff --git a/rust/cloud-storage/static_file_service/src/config.rs b/rust/cloud-storage/static_file_service/src/config.rs
index 900b9daa36..030f7ce669 100644
--- a/rust/cloud-storage/static_file_service/src/config.rs
+++ b/rust/cloud-storage/static_file_service/src/config.rs
@@ -1,7 +1,19 @@
use anyhow::Context;
pub use macro_env::Environment;
+use macro_env_var::{env_vars, maybe_env_vars};
use macro_service_urls::StaticFileServiceUrl;
+env_vars! {
+ struct StaticFileServiceDynamodbTableName;
+ struct StaticStorageBucket;
+ struct StaticFileServiceS3EventQueueUrl;
+ struct InternalApiSecretKey;
+}
+
+maybe_env_vars! {
+ struct Port;
+}
+
#[derive(Debug, Clone)]
pub struct Config {
/// self explanatory
@@ -23,23 +35,27 @@ pub struct Config {
impl Config {
pub fn from_env() -> anyhow::Result<Self> {
let environment = Environment::new_or_prod();
- let port: usize = std::env::var("PORT")
- .unwrap_or("8080".to_string())
- .parse::<usize>()
- .unwrap();
- let dynamodb_table = std::env::var("STATIC_FILE_SERVICE_DYNAMODB_TABLE_NAME")
- .context("STATIC_FILE_SERVICE_DYNAMODB_TABLE_NAME must be provided")?;
+ let port = Port::new()
+ .map(|port| port.parse::<usize>().context("PORT must be a valid usize"))
+ .transpose()?
+ .unwrap_or(8080);
+ let dynamodb_table = StaticFileServiceDynamodbTableName::new()
+ .context("STATIC_FILE_SERVICE_DYNAMODB_TABLE_NAME must be provided")?
+ .to_string();
- let storage_bucket_name = std::env::var("STATIC_STORAGE_BUCKET")
- .context("STATIC_STORAGE_BUCKET must be provided")?;
+ let storage_bucket_name = StaticStorageBucket::new()
+ .context("STATIC_STORAGE_BUCKET must be provided")?
+ .to_string();
let service_url = StaticFileServiceUrl::new()?.to_string();
- let s3_event_queue_url = std::env::var("STATIC_FILE_SERVICE_S3_EVENT_QUEUE_URL")
- .context("S3_EVENT_QUEUE_URL must be provided")?;
+ let s3_event_queue_url = StaticFileServiceS3EventQueueUrl::new()
+ .context("S3_EVENT_QUEUE_URL must be provided")?
+ .to_string();
- let internal_api_secret_key = std::env::var("INTERNAL_API_SECRET_KEY")
- .context("INTERNAL_API_SECRET_KEY must be provided")?;
+ let internal_api_secret_key = InternalApiSecretKey::new()
+ .context("INTERNAL_API_SECRET_KEY must be provided")?
+ .to_string();
Ok(Config {
environment,
diff --git a/rust/cloud-storage/stream/src/bin/stream_stdin.rs b/rust/cloud-storage/stream/src/bin/stream_stdin.rs
index 5b4bb65d31..303b1b49ce 100644
--- a/rust/cloud-storage/stream/src/bin/stream_stdin.rs
+++ b/rust/cloud-storage/stream/src/bin/stream_stdin.rs
@@ -8,6 +8,7 @@ const ENTITY_TYPE: EntityType = EntityType::Channel;
const ENTITY_ID: &str = "019467c2-49d0-7d99-b0b9-d535811a337d";
const STREAM_ID: &str = "stdin";
+#[allow(clippy::disallowed_methods, reason = "Only used when running locally")]
fn main() -> anyhow::Result<()> {
let redis_url = std::env::var("DBURL")
.or_else(|_| std::env::var("REDIS_URL"))
diff --git a/rust/cloud-storage/tools/native_app_server/Cargo.toml b/rust/cloud-storage/tools/native_app_server/Cargo.toml
index e8fe8f17e5..a9f57664fa 100644
--- a/rust/cloud-storage/tools/native_app_server/Cargo.toml
+++ b/rust/cloud-storage/tools/native_app_server/Cargo.toml
@@ -6,6 +6,7 @@ version = "0.1.0"
[dependencies]
axum = { workspace = true }
+macro_env_var = { path = "../../macro_env_var" }
native_app_service = { path = "../../native_app_service" }
rootcause = { workspace = true }
semver = { workspace = true }
diff --git a/rust/cloud-storage/tools/native_app_server/src/main.rs b/rust/cloud-storage/tools/native_app_server/src/main.rs
index 2c78799eb6..29418da7e7 100644
--- a/rust/cloud-storage/tools/native_app_server/src/main.rs
+++ b/rust/cloud-storage/tools/native_app_server/src/main.rs
@@ -1,6 +1,7 @@
use std::path::{Path, PathBuf};
use std::sync::Arc;
+use macro_env_var::maybe_env_vars;
use native_app_service::{
domain::{
models::{BundleManifest, BundleUpdatePolicy, PlatformData, UpdateErr},
@@ -66,12 +67,17 @@ async fn sha256_hex(path: &Path) -> std::io::Result<String> {
const ADDR: &str = "0.0.0.0:3001";
const ARCHIVE_PATH: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/app-archive.zip");
+maybe_env_vars! {
+ struct BundleUrl;
+}
+
#[tokio::main]
async fn main() {
tracing_subscriber::fmt::init();
- let bundle_url: Url = std::env::var("BUNDLE_URL")
- .unwrap_or_else(|_| format!("http://{ADDR}/app-archive.zip"))
+ let bundle_url: Url = BundleUrl::new()
+ .map(|url| url.to_string())
+ .unwrap_or_else(|| format!("http://{ADDR}/app-archive.zip"))
.parse()
.expect("BUNDLE_URL must be a valid URL");
diff --git a/rust/cloud-storage/unfurl_service/Cargo.toml b/rust/cloud-storage/unfurl_service/Cargo.toml
index 9f670ecf00..7e01f9c703 100644
--- a/rust/cloud-storage/unfurl_service/Cargo.toml
+++ b/rust/cloud-storage/unfurl_service/Cargo.toml
@@ -25,6 +25,7 @@ http-body-util = { workspace = true }
macro_cors = { path = "../macro_cors" }
macro_entrypoint = { path = "../macro_entrypoint" }
macro_env = { path = "../macro_env" }
+macro_env_var = { path = "../macro_env_var" }
reqwest = { workspace = true, features = ["stream"] }
scraper = { workspace = true }
serde = { workspace = true }
diff --git a/rust/cloud-storage/unfurl_service/src/config.rs b/rust/cloud-storage/unfurl_service/src/config.rs
index 17bf3acca7..eaa134eba4 100644
--- a/rust/cloud-storage/unfurl_service/src/config.rs
+++ b/rust/cloud-storage/unfurl_service/src/config.rs
@@ -1,4 +1,11 @@
+use anyhow::Context;
+
pub use macro_env::Environment;
+use macro_env_var::maybe_env_vars;
+
+maybe_env_vars! {
+ struct Port;
+}
/// The configuration parameters for the application.
///
@@ -16,10 +23,10 @@ pub struct Config {
impl Config {
pub fn from_env() -> anyhow::Result<Self> {
- let port: usize = std::env::var("PORT")
- .unwrap_or("8080".to_string())
- .parse::<usize>()
- .unwrap();
+ let port = Port::new()
+ .map(|port| port.parse::<usize>().context("PORT must be a valid usize"))
+ .transpose()?
+ .unwrap_or(8080);
let environment = Environment::new_or_prod();
Ok(Config { port, environment })
diff --git a/rust/cloud-storage/upload_extractor_lambda_handler/Cargo.toml b/rust/cloud-storage/upload_extractor_lambda_handler/Cargo.toml
index ef64b885cf..a13ebc8f5e 100644
--- a/rust/cloud-storage/upload_extractor_lambda_handler/Cargo.toml
+++ b/rust/cloud-storage/upload_extractor_lambda_handler/Cargo.toml
@@ -20,6 +20,7 @@ futures = { workspace = true }
lambda_runtime = { workspace = true }
macro_aws_config = { path = "../macro_aws_config" }
macro_entrypoint = { path = "../macro_entrypoint" }
+macro_env_var = { path = "../macro_env_var" }
model = { path = "../model" }
model-entity = { path = "../model-entity" }
models_bulk_upload = { path = "../models_bulk_upload" }
diff --git a/rust/cloud-storage/upload_extractor_lambda_handler/src/main.rs b/rust/cloud-storage/upload_extractor_lambda_handler/src/main.rs
index b6fb9557a1..cc9233657b 100644
--- a/rust/cloud-storage/upload_extractor_lambda_handler/src/main.rs
+++ b/rust/cloud-storage/upload_extractor_lambda_handler/src/main.rs
@@ -13,6 +13,7 @@ use lambda_runtime::{
tracing::{self},
};
use macro_entrypoint::MacroEntrypoint;
+use macro_env_var::env_vars;
use macro_service_urls::ConnectionGatewayUrl;
use model::{
document::{FileType, FileTypeExt},
@@ -31,6 +32,14 @@ use tokio_stream::StreamExt;
use tokio_util::io::ReaderStream;
use zip::read::root_dir_common_filter;
+env_vars! {
+ struct LocalZipPath;
+ struct UploadBucketName;
+ struct InternalApiSecretKey;
+ struct DssUrl;
+ struct DynamodbTable;
+}
+
fn get_upload_message_from_sqs_record(record: SqsMessage) -> Result<UploadExtractQueueMessage> {
let body = record.body.as_deref().unwrap_or_default();
let message = serde_json::from_str::<UploadExtractQueueMessage>(body)?;
@@ -208,9 +217,9 @@ async fn process_zipped_s3_object(
if cfg!(feature = "local") {
tracing::info!("using local zip file, remove local feature to download s3 object");
// Update this path to your zip file location
- let file_path = std::env::var("LOCAL_ZIP_PATH").unwrap();
- tracing::info!("Loading local zip file from: {}", file_path);
- let file = File::open(file_path).await?;
+ let file_path = LocalZipPath::new().context("LOCAL_ZIP_PATH must be set")?;
+ tracing::info!("Loading local zip file from: {}", file_path.as_ref());
+ let file = File::open(file_path.as_ref()).await?;
let mut body = tokio::io::BufReader::new(file);
// Write the file to disk
@@ -574,14 +583,16 @@ async fn main() -> Result<(), Error> {
MacroEntrypoint::default().init();
tracing::trace!("initiating lambda");
- let upload_staging_bucket =
- std::env::var("UPLOAD_BUCKET_NAME").context("UPLOAD_STAGING_BUCKET must be set")?;
- let internal_api_secret_key = std::env::var("INTERNAL_API_SECRET_KEY")
- .context("INTERNAL_API_SECRET_KEY must be set")
- .unwrap();
- let dss_url = std::env::var("DSS_URL").context("DSS_URL must be set")?;
- let dynamo_table_name =
- std::env::var("DYNAMODB_TABLE").context("DYNAMODB_TABLE must be set")?;
+ let upload_staging_bucket = UploadBucketName::new()
+ .context("UPLOAD_BUCKET_NAME must be set")?
+ .to_string();
+ let internal_api_secret_key = InternalApiSecretKey::new()
+ .context("INTERNAL_API_SECRET_KEY must be set")?
+ .to_string();
+ let dss_url = DssUrl::new().context("DSS_URL must be set")?.to_string();
+ let dynamo_table_name = DynamodbTable::new()
+ .context("DYNAMODB_TABLE must be set")?
+ .to_string();
let connection_gateway_url = ConnectionGatewayUrl::new()?.to_string();
let config = macro_aws_config::get_macro_aws_config().await;
@@ -589,7 +600,7 @@ async fn main() -> Result<(), Error> {
let dss_client = DocumentStorageServiceClient::new(internal_api_secret_key.clone(), dss_url);
- let dynamodb_client = DynamodbClient::new(&config, Some(dynamo_table_name.clone()));
+ let dynamodb_client = DynamodbClient::new(&config, Some(dynamo_table_name));
let conn_gateway_client =
ConnectionGatewayClient::new(internal_api_secret_key, connection_gateway_url);
diff --git a/rust/cloud-storage/upload_extractor_lambda_trigger/Cargo.toml b/rust/cloud-storage/upload_extractor_lambda_trigger/Cargo.toml
index 1403cc62df..3aa68b6bad 100644
--- a/rust/cloud-storage/upload_extractor_lambda_trigger/Cargo.toml
+++ b/rust/cloud-storage/upload_extractor_lambda_trigger/Cargo.toml
@@ -20,4 +20,4 @@ sqs_client = { path = "../sqs_client" }
tokio = { workspace = true }
tracing = { workspace = true }
workspace-hack = { version = "0.1", path = "../workspace-hack" }
-
+macro_env_var = { path = "../macro_env_var" }
diff --git a/rust/cloud-storage/upload_extractor_lambda_trigger/src/main.rs b/rust/cloud-storage/upload_extractor_lambda_trigger/src/main.rs
index 569e8ebca0..2ef20d91da 100644
--- a/rust/cloud-storage/upload_extractor_lambda_trigger/src/main.rs
+++ b/rust/cloud-storage/upload_extractor_lambda_trigger/src/main.rs
@@ -8,6 +8,7 @@ use lambda_runtime::{
tracing::{self},
};
use macro_entrypoint::MacroEntrypoint;
+use macro_env_var::env_vars;
use models_bulk_upload::UploadFolderStatus;
use serde::{Deserialize, Serialize};
@@ -85,20 +86,24 @@ async fn handler(
Ok(())
}
+env_vars! {
+ pub struct DynamodbTable;
+ pub struct UploadExtractorQueue;
+}
+
#[tokio::main]
async fn main() -> Result<(), Error> {
MacroEntrypoint::default().init();
tracing::info!("initiating lambda");
- let dynamo_table_name =
- std::env::var("DYNAMODB_TABLE").context("DYNAMODB_TABLE must be set")?;
+ let dynamo_table_name = DynamodbTable::new().context("DYNAMODB_TABLE must be set")?;
let upload_extract_queue =
- std::env::var("UPLOAD_EXTRACTOR_QUEUE").context("UPLOAD_EXTRACTOR_QUEUE must be set")?;
+ UploadExtractorQueue::new().context("UPLOAD_EXTRACTOR_QUEUE must be set")?;
tracing::trace!("initialized env vars");
let config = macro_aws_config::get_macro_aws_config().await;
- let dynamodb_client = DynamodbClient::new(&config, Some(dynamo_table_name.clone()));
+ let dynamodb_client = DynamodbClient::new(&config, Some(dynamo_table_name.to_string()));
tracing::trace!("initialized dynamodb client");
diff --git a/rust/cloud-storage/user_link_cleanup_handler/Cargo.toml b/rust/cloud-storage/user_link_cleanup_handler/Cargo.toml
index 3689a36de4..b4d856578d 100644
--- a/rust/cloud-storage/user_link_cleanup_handler/Cargo.toml
+++ b/rust/cloud-storage/user_link_cleanup_handler/Cargo.toml
@@ -12,9 +12,11 @@ futures = { workspace = true }
lambda_runtime = { workspace = true }
macro_db_client = { path = "../macro_db_client" }
macro_entrypoint = { path = "../macro_entrypoint" }
+macro_env_var = { path = "../macro_env_var" }
serde = { workspace = true }
serde_json = { workspace = true }
sqlx = { workspace = true }
tokio = { workspace = true }
+tracing = { workspace = true }
workspace-hack = { version = "0.1", path = "../workspace-hack" }
diff --git a/rust/cloud-storage/user_link_cleanup_handler/src/main.rs b/rust/cloud-storage/user_link_cleanup_handler/src/main.rs
index 04550696e7..9b91539cf1 100644
--- a/rust/cloud-storage/user_link_cleanup_handler/src/main.rs
+++ b/rust/cloud-storage/user_link_cleanup_handler/src/main.rs
@@ -5,21 +5,26 @@ use lambda_runtime::{
tracing::{self},
};
use macro_entrypoint::MacroEntrypoint;
+use macro_env_var::env_vars;
use sqlx::postgres::PgPoolOptions;
+env_vars! {
+ struct DatabaseUrl;
+}
+
#[tokio::main]
async fn main() -> Result<(), Error> {
MacroEntrypoint::default().init();
tracing::trace!("initiating lambda");
- let database_url = std::env::var("DATABASE_URL").context("DATABASE_URL should be set")?;
+ let database_url = DatabaseUrl::new().context("DATABASE_URL should be set")?;
// We should only ever need 1 connection
let db = PgPoolOptions::new()
.min_connections(1)
.max_connections(1) // We want 1 db connection per dss item (document, project, chat)
- .connect(&database_url)
+ .connect(database_url.as_ref())
.await
.context("could not connect to db")?;
diff --git a/rust/cloud-storage/worker_trigger/Cargo.toml b/rust/cloud-storage/worker_trigger/Cargo.toml
index 4c39a9daff..b1ca0e07a5 100644
--- a/rust/cloud-storage/worker_trigger/Cargo.toml
+++ b/rust/cloud-storage/worker_trigger/Cargo.toml
@@ -12,6 +12,7 @@ lambda_runtime = { workspace = true }
macro_aws_config = { path = "../macro_aws_config" }
macro_entrypoint = { path = "../macro_entrypoint" }
macro_env = { path = "../macro_env" }
+macro_env_var = { path = "../macro_env_var" }
serde_json = { workspace = true }
tokio = { workspace = true }
tracing = { workspace = true }
diff --git a/rust/cloud-storage/worker_trigger/src/config.rs b/rust/cloud-storage/worker_trigger/src/config.rs
index a1b7cef443..1f05fa2542 100644
--- a/rust/cloud-storage/worker_trigger/src/config.rs
+++ b/rust/cloud-storage/worker_trigger/src/config.rs
@@ -1,4 +1,13 @@
+use anyhow::Context;
+
pub use macro_env::Environment;
+use macro_env_var::env_vars;
+
+env_vars! {
+ pub struct TaskDefinition;
+ pub struct Cluster;
+ pub struct Subnets;
+}
/// The configuration parameters for the application.
///
@@ -38,19 +47,18 @@ impl Config {
}
pub fn from_env() -> anyhow::Result<Self> {
- let task_definition =
- std::env::var("TASK_DEFINITION").expect("TASK_DEFINITION must be provided");
- let cluster = std::env::var("CLUSTER").expect("CLUSTER must be provided");
- let subnets: Vec<String> = std::env::var("SUBNETS")
- .expect("SUBNETS must be provided")
+ let task_definition = TaskDefinition::new().context("TASK_DEFINITION must be provided")?;
+ let cluster = Cluster::new().context("CLUSTER must be provided")?;
+ let subnets: Vec<String> = Subnets::new()
+ .context("SUBNETS must be provided")?
.split(",")
.map(|s| s.to_string())
.collect::<Vec<String>>();
let environment = Environment::new_or_prod();
Ok(Config::new(
- task_definition.as_str(),
- cluster.as_str(),
+ task_definition.as_ref(),
+ cluster.as_ref(),
subnets,
environment,
))