Skip to content

armgit / macro

Public Imported from GitHub
0

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

feat(macro_service_urls): Standardize service urls in rust (#3772)

Will Hutchinson35aa14670036
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lock
index 072263ef2e..44769e2887 100644
--- a/rust/cloud-storage/Cargo.lock
+++ b/rust/cloud-storage/Cargo.lock
@@ -127,6 +127,7 @@ dependencies = [
"macro_db_client",
"macro_env",
"macro_env_var",
+ "macro_service_urls",
"macro_user_id",
"model",
"model-entity",
@@ -2497,6 +2498,7 @@ dependencies = [
"macro_entrypoint",
"macro_env",
"macro_middleware",
+ "macro_service_urls",
"macro_user_id",
"model",
"rate_limit",
@@ -3346,6 +3348,7 @@ dependencies = [
"macro_env",
"macro_env_var",
"macro_middleware",
+ "macro_service_urls",
"macro_user_id",
"macro_uuid",
"mcp_client",
@@ -3573,6 +3576,7 @@ dependencies = [
"lexical_client",
"macro_aws_config",
"macro_entrypoint",
+ "macro_service_urls",
"model",
"s3_key",
"serde",
@@ -3613,6 +3617,7 @@ dependencies = [
"macro_aws_config",
"macro_db_migrator",
"macro_entrypoint",
+ "macro_service_urls",
"macro_user_id",
"macro_uuid",
"mockall",
@@ -4022,6 +4027,7 @@ dependencies = [
"macro_env",
"macro_env_var",
"macro_middleware",
+ "macro_service_urls",
"macro_user_id",
"macro_uuid",
"mailparse",
@@ -6571,6 +6577,8 @@ name = "macro_service_urls"
version = "0.1.0"
dependencies = [
"macro_env",
+ "paste",
+ "thiserror 2.0.18",
"url",
]
@@ -6816,6 +6824,7 @@ dependencies = [
"macro_env",
"macro_env_var",
"macro_middleware",
+ "macro_service_urls",
"macro_user_id",
"mcp_auth_proxy",
"notification",
@@ -7658,6 +7667,7 @@ dependencies = [
"macro_env",
"macro_env_var",
"macro_middleware",
+ "macro_service_urls",
"macro_tower_layers",
"macro_user_id",
"macro_uuid",
@@ -9995,6 +10005,7 @@ dependencies = [
"macro_env",
"macro_env_var",
"macro_middleware",
+ "macro_service_urls",
"macro_user_id",
"macro_uuid",
"memory",
@@ -10114,6 +10125,7 @@ dependencies = [
"macro_entrypoint",
"macro_env",
"macro_middleware",
+ "macro_service_urls",
"macro_user_id",
"macro_uuid",
"mention_utils",
@@ -10213,6 +10225,7 @@ dependencies = [
"lambda_runtime",
"macro_aws_config",
"macro_entrypoint",
+ "macro_service_urls",
"s3_key",
"sqs_client",
"tokio",
@@ -11206,6 +11219,7 @@ dependencies = [
"macro_entrypoint",
"macro_env",
"macro_middleware",
+ "macro_service_urls",
"model",
"models_sfs",
"s3_key",
@@ -11231,6 +11245,7 @@ version = "0.1.0"
dependencies = [
"anyhow",
"bytes",
+ "macro_service_urls",
"models_sfs",
"reqwest 0.13.3",
"serde",
@@ -11463,6 +11478,7 @@ dependencies = [
"macro_env",
"macro_env_var",
"macro_middleware",
+ "macro_service_urls",
"model-entity",
"secretsmanager_client",
"serde",
@@ -12339,6 +12355,7 @@ dependencies = [
"lambda_runtime",
"macro_aws_config",
"macro_entrypoint",
+ "macro_service_urls",
"model",
"model-entity",
"models_bulk_upload",
diff --git a/rust/cloud-storage/ai_tools/Cargo.toml b/rust/cloud-storage/ai_tools/Cargo.toml
index 95e8811ed4..14537b65be 100644
--- a/rust/cloud-storage/ai_tools/Cargo.toml
+++ b/rust/cloud-storage/ai_tools/Cargo.toml
@@ -76,5 +76,7 @@ macro_env = { path = "../macro_env" }
secretsmanager_client = { path = "../secretsmanager_client" }
aws-sdk-secretsmanager = { workspace = true }
+macro_service_urls = { path = "../macro_service_urls" }
+
[dev-dependencies]
cool_asserts = "2"
diff --git a/rust/cloud-storage/ai_tools/src/build_context.rs b/rust/cloud-storage/ai_tools/src/build_context.rs
index 6449d10877..d38e37b5e0 100644
--- a/rust/cloud-storage/ai_tools/src/build_context.rs
+++ b/rust/cloud-storage/ai_tools/src/build_context.rs
@@ -32,6 +32,9 @@ use frecency::outbound::postgres::FrecencyPgStorage;
use lexical_client::LexicalClient;
use macro_env::Environment;
use macro_env_var::{env_var, maybe_env_var};
+use macro_service_urls::{
+ DocumentStorageServiceUrl, EmailServiceUrl, LexicalServiceUrl, SyncServiceUrl,
+};
use notification::domain::service::{NotificationReaderService, PlatformArnConfig};
use notification::outbound::queue::SqsQueue;
use notification::outbound::repository::DbNotificationRepository;
@@ -45,12 +48,8 @@ use sync_service_client::SyncServiceClient;
env_var! {
struct ToolContextEnvVars {
- DocumentStorageServiceUrl,
DocumentStorageServiceAuthKey,
- EmailServiceUrl,
- SyncServiceUrl,
SyncServiceAuthKey,
- StaticFileServiceUrl,
DocumentStorageBucket,
DocxDocumentUploadBucket,
EmailScheduledQueue,
@@ -62,7 +61,6 @@ env_var! {
maybe_env_var! {
struct ToolContextMaybeEnvVars {
- LexicalServiceUrl,
NotificationQueue,
}
}
@@ -75,16 +73,17 @@ maybe_env_var! {
/// are treated as AWS Secrets Manager secret names and resolved through the
/// secrets manager. In `Local`, their values are used directly.
///
-/// Required env vars: `DOCUMENT_STORAGE_SERVICE_URL`, `EMAIL_SERVICE_URL`,
-/// `SYNC_SERVICE_URL`, `SYNC_SERVICE_AUTH_KEY`,
-/// `DOCUMENT_STORAGE_SERVICE_AUTH_KEY`, `STATIC_FILE_SERVICE_URL`,
-/// `DOCUMENT_STORAGE_BUCKET`, `DOCX_DOCUMENT_UPLOAD_BUCKET`, `EMAIL_SCHEDULED_QUEUE`,
+/// Required env vars: `SYNC_SERVICE_AUTH_KEY`,
+/// `DOCUMENT_STORAGE_SERVICE_AUTH_KEY`, `DOCUMENT_STORAGE_BUCKET`,
+/// `DOCX_DOCUMENT_UPLOAD_BUCKET`, `EMAIL_SCHEDULED_QUEUE`,
/// `DOCUMENT_STORAGE_SERVICE_CLOUDFRONT_DISTRIBUTION_URL`,
/// `DOCUMENT_STORAGE_SERVICE_CLOUDFRONT_SIGNER_PUBLIC_KEY_ID`,
/// `DOCUMENT_STORAGE_SERVICE_CLOUDFRONT_SIGNER_PRIVATE_KEY_SECRET_NAME`.
///
-/// Optional env vars (with fallbacks for local dev):
-/// - `LEXICAL_SERVICE_URL` (defaults to `http://localhost:8096`)
+/// Service URLs are resolved through the `macro_service_urls` crate, using optional
+/// `OVERRIDE_*` env vars before environment defaults.
+///
+/// Optional env vars:
/// - `NOTIFICATION_QUEUE` (if omitted, notification status updates skip push clearing)
#[tracing::instrument(skip(pool), err)]
pub async fn build_tool_service_context_from_env(
@@ -93,11 +92,10 @@ pub async fn build_tool_service_context_from_env(
let env = ToolContextEnvVars::new()?;
let maybe_env = ToolContextMaybeEnvVars::new();
let environment = Environment::new_or_prod();
-
- let lexical_service_url: Arc<str> = maybe_env
- .lexical_service_url
- .map(|v| v.as_arc())
- .context("expected LEXICAL_SERVICE_URL")?;
+ let document_storage_service_url = DocumentStorageServiceUrl::new()?.to_string();
+ let sync_service_url = SyncServiceUrl::new()?.to_string();
+ let email_service_url = EmailServiceUrl::new()?.to_string();
+ let lexical_service_url = LexicalServiceUrl::new()?.to_string();
let aws_config = macro_aws_config::get_macro_aws_config().await;
let aws_sqs_client = aws_sdk_sqs::Client::new(&aws_config);
@@ -134,18 +132,16 @@ pub async fn build_tool_service_context_from_env(
let search_client = Arc::new(SearchServiceClient::new(
env.document_storage_service_auth_key.to_string(),
- env.document_storage_service_url.to_string(),
+ document_storage_service_url,
));
let sync_client = Arc::new(SyncServiceClient::new(
sync_service_auth_key.clone(),
- env.sync_service_url.to_string(),
- ));
- let email_ext_client = Arc::new(EmailServiceClientExternal::new(
- env.email_service_url.to_string(),
+ sync_service_url,
));
+ let email_ext_client = Arc::new(EmailServiceClientExternal::new(email_service_url));
let lexical_client = LexicalClient::new(
env.document_storage_service_auth_key.to_string(),
- lexical_service_url.to_string(),
+ lexical_service_url,
);
let frecency_storage = FrecencyPgStorage::new(pool.clone());
diff --git a/rust/cloud-storage/authentication_service/Cargo.toml b/rust/cloud-storage/authentication_service/Cargo.toml
index c5acee8d9d..9c87014073 100644
--- a/rust/cloud-storage/authentication_service/Cargo.toml
+++ b/rust/cloud-storage/authentication_service/Cargo.toml
@@ -128,7 +128,6 @@ utoipa = { workspace = true }
utoipa-swagger-ui = { workspace = true }
uuid = { workspace = true }
-
[dev-dependencies]
cool_asserts = "2"
diff --git a/rust/cloud-storage/authentication_service/src/config.rs b/rust/cloud-storage/authentication_service/src/config.rs
index 197d8c6c36..9df5514809 100644
--- a/rust/cloud-storage/authentication_service/src/config.rs
+++ b/rust/cloud-storage/authentication_service/src/config.rs
@@ -3,6 +3,7 @@ use std::sync::LazyLock;
use anyhow::Context;
pub use macro_env::Environment;
use macro_env_var::env_var;
+use macro_service_urls::DocumentStorageServiceUrl;
// BASE_URL env var. This is validated when creating the config in main.rs
pub static BASE_URL: LazyLock<String> = LazyLock::new(|| std::env::var("BASE_URL").unwrap());
@@ -158,8 +159,7 @@ impl Config {
let environment = Environment::new_or_prod();
- let document_storage_service_url = std::env::var("DOCUMENT_STORAGE_SERVICE_URL")
- .context("DOCUMENT_STORAGE_SERVICE_URL must be provided")?;
+ let document_storage_service_url = DocumentStorageServiceUrl::new()?.to_string();
let notification_queue =
std::env::var("NOTIFICATION_QUEUE").context("NOTIFICATION_QUEUE must be provided")?;
diff --git a/rust/cloud-storage/authentication_service/src/main.rs b/rust/cloud-storage/authentication_service/src/main.rs
index a971fa9a26..4fef6ddc1b 100644
--- a/rust/cloud-storage/authentication_service/src/main.rs
+++ b/rust/cloud-storage/authentication_service/src/main.rs
@@ -20,7 +20,7 @@ use github::{
use macro_auth::middleware::decode_jwt::JwtValidationArgs;
use macro_entrypoint::MacroEntrypoint;
use macro_middleware::auth::internal_access::InternalApiSecretKey;
-use macro_service_urls::EnvExtMacroServiceUrls;
+use macro_service_urls::AppServiceUrl;
use native_app_service::{
domain::{models::PlatformData, service::NativeAppServiceImpl},
outbound::DefaultBundleFetcher,
@@ -326,7 +326,12 @@ async fn main() -> anyhow::Result<()> {
entity_access_service: Arc::new(entity_access_service_impl),
referral_service: Arc::new(referral_service),
native_app_service: Arc::new(NativeAppServiceImpl {
- bundle_fetcher: DefaultBundleFetcher::new(config.environment.app()),
+ bundle_fetcher: DefaultBundleFetcher::new(
+ AppServiceUrl::new_for_environment(config.environment)
+ .context("failed to resolve app service URL")?
+ .parse_url()
+ .context("failed to parse app service URL")?,
+ ),
bundle_policy: native_app_service::domain::models::BundleUpdatePolicy::from_env()
.map_err(|err| {
anyhow!("failed to load bundle update policy: {err}")
diff --git a/rust/cloud-storage/contacts_service/Cargo.toml b/rust/cloud-storage/contacts_service/Cargo.toml
index aecd4e9bd9..be1c3603b2 100644
--- a/rust/cloud-storage/contacts_service/Cargo.toml
+++ b/rust/cloud-storage/contacts_service/Cargo.toml
@@ -40,6 +40,7 @@ tokio = { workspace = true }
tracing = { workspace = true }
utoipa = { workspace = true }
utoipa-swagger-ui = { workspace = true }
+macro_service_urls = { path = "../macro_service_urls" }
[features]
mock = []
diff --git a/rust/cloud-storage/contacts_service/src/config.rs b/rust/cloud-storage/contacts_service/src/config.rs
index 532e4b0a43..e84b7086d2 100644
--- a/rust/cloud-storage/contacts_service/src/config.rs
+++ b/rust/cloud-storage/contacts_service/src/config.rs
@@ -1,5 +1,6 @@
use anyhow::Context;
pub use macro_env::Environment;
+use macro_service_urls::ConnectionGatewayUrl;
pub struct Config {
/// port number of service
@@ -45,7 +46,7 @@ impl Config {
.parse::<i32>()
.unwrap();
- let connection_gateway_url = std::env::var("CONNECTION_GATEWAY_URL").ok();
+ let connection_gateway_url = Some(ConnectionGatewayUrl::new()?.to_string());
let environment = Environment::new_or_prod();
diff --git a/rust/cloud-storage/document_cognition_service/Cargo.toml b/rust/cloud-storage/document_cognition_service/Cargo.toml
index 70c809d7d0..1a1a69490a 100644
--- a/rust/cloud-storage/document_cognition_service/Cargo.toml
+++ b/rust/cloud-storage/document_cognition_service/Cargo.toml
@@ -128,6 +128,8 @@ utoipa = { workspace = true, features = ["axum_extras", "chrono"] }
utoipa-swagger-ui = { workspace = true, features = ["axum"] }
uuid = { workspace = true }
+macro_service_urls = { path = "../macro_service_urls" }
+
[dev-dependencies]
ai_tools = { path = "../ai_tools", features = ["test-support"] }
macro_auth = { path = "../macro_auth", features = ["testing"] }
diff --git a/rust/cloud-storage/document_cognition_service/src/config.rs b/rust/cloud-storage/document_cognition_service/src/config.rs
index 382b839f4a..114c975cea 100644
--- a/rust/cloud-storage/document_cognition_service/src/config.rs
+++ b/rust/cloud-storage/document_cognition_service/src/config.rs
@@ -1,5 +1,9 @@
pub use macro_env::Environment;
use macro_env_var::{env_var, maybe_env_var};
+use macro_service_urls::{
+ DocumentCognitionServiceUrl, DocumentStorageServiceUrl, EmailServiceUrl, LexicalServiceUrl,
+ StaticFileServiceUrl, SyncServiceUrl,
+};
use crate::core::constants::DEFAULT_DOCUMENT_BATCH_LIMIT;
/// The configuration parameters for the application.
@@ -67,14 +71,9 @@ env_var!(
pub ChatDeleteQueue,
pub EmailScheduledQueue,
pub NotificationQueue,
- pub DocumentStorageServiceUrl,
pub DocumentStorageServiceAuthKey,
pub SearchEventQueue,
- pub SyncServiceUrl,
pub SyncServiceAuthKey,
- pub LexicalServiceUrl,
- pub EmailServiceUrl,
- pub StaticFileServiceUrl,
pub AuthenticationServiceUrl,
pub AuthenticationServiceSecretKey,
pub RedisHost,
@@ -83,7 +82,6 @@ env_var!(
pub DocumentStorageServiceCloudfrontSignerPublicKeyId,
pub DocumentStorageServiceCloudfrontSignerPrivateKeySecretName,
pub McpCredentialsKeySecretName,
- pub DocumentCognitionServiceUrl,
}
);
@@ -108,6 +106,13 @@ impl Config {
.and_then(|v| v.parse::<i64>().ok())
.unwrap_or(DEFAULT_DOCUMENT_BATCH_LIMIT);
+ let document_storage_service_url = DocumentStorageServiceUrl::new()?.to_string();
+ let sync_service_url = SyncServiceUrl::new()?.to_string();
+ let lexical_service_url = LexicalServiceUrl::new()?.to_string();
+ let email_service_url = EmailServiceUrl::new()?.to_string();
+ let document_cognition_service_url = DocumentCognitionServiceUrl::new()?.to_string();
+ let static_file_service_url = StaticFileServiceUrl::new()?.to_string();
+
let EnvVars {
database_url,
document_storage_bucket,
@@ -115,14 +120,9 @@ impl Config {
chat_delete_queue,
email_scheduled_queue,
notification_queue,
- document_storage_service_url,
document_storage_service_auth_key,
search_event_queue,
- sync_service_url,
sync_service_auth_key,
- lexical_service_url,
- email_service_url,
- static_file_service_url,
authentication_service_url,
authentication_service_secret_key,
redis_host,
@@ -131,7 +131,6 @@ impl Config {
document_storage_service_cloudfront_signer_public_key_id,
document_storage_service_cloudfront_signer_private_key_secret_name,
mcp_credentials_key_secret_name,
- document_cognition_service_url,
} = env_vars;
Ok(Config {
@@ -140,7 +139,7 @@ impl Config {
environment,
document_batch_limit,
document_storage_bucket: document_storage_bucket.to_string(),
- document_storage_service_url: document_storage_service_url.to_string(),
+ document_storage_service_url,
document_storage_service_auth_key: document_storage_service_auth_key.to_string(),
document_text_extractor_queue: document_text_extractor_queue.to_string(),
chat_delete_queue: chat_delete_queue.to_string(),
@@ -148,11 +147,11 @@ impl Config {
notification_queue: notification_queue.to_string(),
search_event_queue: search_event_queue.to_string(),
sync_service_auth_key: sync_service_auth_key.to_string(),
- sync_service_url: sync_service_url.to_string(),
- lexical_service_url: lexical_service_url.to_string(),
- email_service_url: email_service_url.to_string(),
- document_cognition_service_url: document_cognition_service_url.to_string(),
- static_file_service_url: static_file_service_url.to_string(),
+ sync_service_url,
+ lexical_service_url,
+ email_service_url,
+ document_cognition_service_url,
+ static_file_service_url,
authentication_service_url: authentication_service_url.to_string(),
authentication_service_secret_key: authentication_service_secret_key.to_string(),
redis_host,
diff --git a/rust/cloud-storage/document_storage_service/src/config.rs b/rust/cloud-storage/document_storage_service/src/config.rs
index b7061db526..035b128ae7 100644
--- a/rust/cloud-storage/document_storage_service/src/config.rs
+++ b/rust/cloud-storage/document_storage_service/src/config.rs
@@ -1,5 +1,6 @@
pub use macro_env::Environment;
use macro_env_var::{env_var, maybe_env_var};
+use macro_service_urls::{ConnectionGatewayUrl, LexicalServiceUrl, SyncServiceUrl};
use secretsmanager_client::LocalOrRemoteSecret;
/// The configuration parameters for the application.
@@ -18,6 +19,15 @@ pub struct Config {
/// The environment we are in
pub environment: Environment,
+ /// Connection gateway URL.
+ pub connection_gateway_url: String,
+
+ /// Sync service URL.
+ pub sync_service_url: String,
+
+ /// Lexical service URL.
+ pub lexical_service_url: String,
+
/// Maximum number of SQS messages to receive per poll for the delete document worker
pub queue_max_messages: i32,
/// SQS long-poll wait time in seconds for the delete document worker
@@ -48,12 +58,9 @@ env_var! {
pub RedisUri,
pub NotificationQueue,
pub SearchEventQueue,
- pub ConnectionGatewayUrl,
pub BulkUploadRequestsTable,
pub UploadStagingBucket,
- pub SyncServiceUrl,
pub SyncServiceAuthKey,
- pub LexicalServiceUrl,
pub OpensearchUrl,
pub OpensearchUsername,
pub OpensearchPassword,
@@ -185,11 +192,17 @@ impl Config {
.unwrap_or(4);
let vars = EnvVars::new()?;
+ let connection_gateway_url = ConnectionGatewayUrl::new()?.to_string();
+ let sync_service_url = SyncServiceUrl::new()?.to_string();
+ let lexical_service_url = LexicalServiceUrl::new()?.to_string();
Ok(Config {
vars,
port,
environment,
+ connection_gateway_url,
+ sync_service_url,
+ lexical_service_url,
queue_max_messages,
queue_wait_time_seconds,
document_limit,
diff --git a/rust/cloud-storage/document_storage_service/src/main.rs b/rust/cloud-storage/document_storage_service/src/main.rs
index 1e341172e4..9edacceeda 100644
--- a/rust/cloud-storage/document_storage_service/src/main.rs
+++ b/rust/cloud-storage/document_storage_service/src/main.rs
@@ -216,7 +216,7 @@ async fn main() -> anyhow::Result<()> {
let conn_gateway_client = ConnectionGatewayClient::new(
internal_api_secret.as_ref().to_string(),
- config.vars.connection_gateway_url.as_ref().to_string(),
+ config.connection_gateway_url.clone(),
);
let sync_service_auth_key = match config.environment {
@@ -230,12 +230,12 @@ async fn main() -> anyhow::Result<()> {
let sync_service_client = Arc::new(SyncServiceClient::new(
sync_service_auth_key,
- config.vars.sync_service_url.as_ref().to_string(),
+ config.sync_service_url.clone(),
));
let lexical_client = Arc::new(LexicalClient::new(
internal_api_secret.as_ref().to_string(),
- config.vars.lexical_service_url.as_ref().to_string(),
+ config.lexical_service_url.clone(),
));
let jwt_validation_args =
diff --git a/rust/cloud-storage/document_upload_finalizer_handler/Cargo.toml b/rust/cloud-storage/document_upload_finalizer_handler/Cargo.toml
index e3eabda22d..abc6564b02 100644
--- a/rust/cloud-storage/document_upload_finalizer_handler/Cargo.toml
+++ b/rust/cloud-storage/document_upload_finalizer_handler/Cargo.toml
@@ -20,6 +20,7 @@ macro_aws_config = { path = "../macro_aws_config", features = ["s3"] }
macro_entrypoint = { path = "../macro_entrypoint" }
model = { path = "../model" }
s3_key = { path = "../s3_key" }
+macro_service_urls = { path = "../macro_service_urls" }
serde = { workspace = true }
serde_json = { workspace = true }
sqlx = { workspace = true, features = ["postgres", "runtime-tokio-rustls"] }
@@ -31,4 +32,3 @@ urlencoding = { workspace = true }
[[bin]]
name = "document_upload_finalizer_local_worker"
path = "src/bin/local_worker.rs"
-
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 e06f03780f..737a112048 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_service_urls::{LexicalServiceUrl, SyncServiceUrl};
use sqlx::postgres::PgPoolOptions;
use sync_service_client::SyncServiceClient;
@@ -24,10 +25,8 @@ impl AppContext {
.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 lexical_service_url =
- std::env::var("LEXICAL_SERVICE_URL").context("LEXICAL_SERVICE_URL must be provided")?;
- let sync_service_url =
- std::env::var("SYNC_SERVICE_URL").context("SYNC_SERVICE_URL must be provided")?;
+ let lexical_service_url = LexicalServiceUrl::new()?.to_string();
+ let sync_service_url = SyncServiceUrl::new()?.to_string();
let db_pool = PgPoolOptions::new()
.max_connections(5)
diff --git a/rust/cloud-storage/documents/Cargo.toml b/rust/cloud-storage/documents/Cargo.toml
index af503957f4..76b1791f41 100644
--- a/rust/cloud-storage/documents/Cargo.toml
+++ b/rust/cloud-storage/documents/Cargo.toml
@@ -48,7 +48,14 @@ document_create_adapters = [
"document_create",
"markdown_init",
]
-backfill_binary = ["dep:clap", "dep:macro_entrypoint", "markdown_init", "outbound", "ports"]
+backfill_binary = [
+ "dep:clap",
+ "dep:macro_entrypoint",
+ "dep:macro_service_urls",
+ "markdown_init",
+ "outbound",
+ "ports",
+]
inbound = ["axum", "document_create_adapters", "ports"]
markdown_init = ["dep:lexical_client"]
outbound = [
@@ -96,6 +103,7 @@ model-entity = { path = "../model-entity" }
models_permissions = { path = "../models_permissions" }
models_properties = { path = "../models_properties" }
s3_key = { path = "../s3_key" }
+macro_service_urls = { path = "../macro_service_urls", optional = true }
# Async runtime (for ports)
tokio = { workspace = true, optional = true }
diff --git a/rust/cloud-storage/documents/justfile b/rust/cloud-storage/documents/justfile
index 46e79a7f7c..f007bc5a28 100644
--- a/rust/cloud-storage/documents/justfile
+++ b/rust/cloud-storage/documents/justfile
@@ -18,10 +18,8 @@ backfill_markdown_content_location_dev *FLAGS:
SYNC_SERVICE_AUTH_KEY="$(aws secretsmanager get-secret-value --secret-id sync-service-key-dev --query SecretString --output text)"
INTERNAL_API_SECRET_KEY="$(aws secretsmanager get-secret-value --secret-id document-storage-service-auth-key-dev --query SecretString --output text)"
eval "$(aws configure export-credentials --format env)"
- SYNC_SERVICE_URL="https://sync-service-dev3.macroverse.workers.dev"
- LEXICAL_SERVICE_URL="https://lexical-service-dev.macroverse.workers.dev"
DOCUMENT_STORAGE_BUCKET="doc-storage-dev"
- RUST_LOG="${RUST_LOG:-info}" DATABASE_URL="$DATABASE_URL" SYNC_SERVICE_AUTH_KEY="$SYNC_SERVICE_AUTH_KEY" INTERNAL_API_SECRET_KEY="$INTERNAL_API_SECRET_KEY" SYNC_SERVICE_URL="$SYNC_SERVICE_URL" LEXICAL_SERVICE_URL="$LEXICAL_SERVICE_URL" DOCUMENT_STORAGE_BUCKET="$DOCUMENT_STORAGE_BUCKET" \
+ RUST_LOG="${RUST_LOG:-info}" ENVIRONMENT="dev" DATABASE_URL="$DATABASE_URL" SYNC_SERVICE_AUTH_KEY="$SYNC_SERVICE_AUTH_KEY" INTERNAL_API_SECRET_KEY="$INTERNAL_API_SECRET_KEY" DOCUMENT_STORAGE_BUCKET="$DOCUMENT_STORAGE_BUCKET" \
cargo run -p documents --features backfill_binary --bin backfill_markdown_content_location -- {{ FLAGS }}
# Apply markdown lifecycle backfill against dev DB/sync-service.
@@ -41,10 +39,8 @@ backfill_markdown_content_location_dev_apply *FLAGS:
SYNC_SERVICE_AUTH_KEY="$(aws secretsmanager get-secret-value --secret-id sync-service-key-dev --query SecretString --output text)"
INTERNAL_API_SECRET_KEY="$(aws secretsmanager get-secret-value --secret-id document-storage-service-auth-key-dev --query SecretString --output text)"
eval "$(aws configure export-credentials --format env)"
- SYNC_SERVICE_URL="https://sync-service-dev3.macroverse.workers.dev"
- LEXICAL_SERVICE_URL="https://lexical-service-dev.macroverse.workers.dev"
DOCUMENT_STORAGE_BUCKET="doc-storage-dev"
- RUST_LOG="${RUST_LOG:-info}" DATABASE_URL="$DATABASE_URL" SYNC_SERVICE_AUTH_KEY="$SYNC_SERVICE_AUTH_KEY" INTERNAL_API_SECRET_KEY="$INTERNAL_API_SECRET_KEY" SYNC_SERVICE_URL="$SYNC_SERVICE_URL" LEXICAL_SERVICE_URL="$LEXICAL_SERVICE_URL" DOCUMENT_STORAGE_BUCKET="$DOCUMENT_STORAGE_BUCKET" \
+ RUST_LOG="${RUST_LOG:-info}" ENVIRONMENT="dev" DATABASE_URL="$DATABASE_URL" SYNC_SERVICE_AUTH_KEY="$SYNC_SERVICE_AUTH_KEY" INTERNAL_API_SECRET_KEY="$INTERNAL_API_SECRET_KEY" DOCUMENT_STORAGE_BUCKET="$DOCUMENT_STORAGE_BUCKET" \
cargo run -p documents --features backfill_binary --bin backfill_markdown_content_location -- --apply {{ FLAGS }}
# Dry-run markdown lifecycle backfill against prod DB/sync-service.
@@ -57,10 +53,8 @@ backfill_markdown_content_location_prod *FLAGS:
SYNC_SERVICE_AUTH_KEY="$(aws secretsmanager get-secret-value --secret-id sync-service-key-prod --query SecretString --output text)"
INTERNAL_API_SECRET_KEY="$(aws secretsmanager get-secret-value --secret-id document-storage-service-auth-key-prod --query SecretString --output text)"
eval "$(aws configure export-credentials --format env)"
- SYNC_SERVICE_URL="https://sync-service-prod2.macroverse.workers.dev"
- LEXICAL_SERVICE_URL="https://lexical-service.macroverse.workers.dev"
DOCUMENT_STORAGE_BUCKET="macro-document-storage-prod"
- RUST_LOG="${RUST_LOG:-info}" DATABASE_URL="$DATABASE_URL" SYNC_SERVICE_AUTH_KEY="$SYNC_SERVICE_AUTH_KEY" INTERNAL_API_SECRET_KEY="$INTERNAL_API_SECRET_KEY" SYNC_SERVICE_URL="$SYNC_SERVICE_URL" LEXICAL_SERVICE_URL="$LEXICAL_SERVICE_URL" DOCUMENT_STORAGE_BUCKET="$DOCUMENT_STORAGE_BUCKET" \
+ RUST_LOG="${RUST_LOG:-info}" ENVIRONMENT="prod" DATABASE_URL="$DATABASE_URL" SYNC_SERVICE_AUTH_KEY="$SYNC_SERVICE_AUTH_KEY" INTERNAL_API_SECRET_KEY="$INTERNAL_API_SECRET_KEY" DOCUMENT_STORAGE_BUCKET="$DOCUMENT_STORAGE_BUCKET" \
cargo run -p documents --features backfill_binary --bin backfill_markdown_content_location -- {{ FLAGS }}
# Apply markdown lifecycle backfill against prod DB/sync-service.
@@ -81,8 +75,6 @@ backfill_markdown_content_location_prod_apply *FLAGS:
SYNC_SERVICE_AUTH_KEY="$(aws secretsmanager get-secret-value --secret-id sync-service-key-prod --query SecretString --output text)"
INTERNAL_API_SECRET_KEY="$(aws secretsmanager get-secret-value --secret-id document-storage-service-auth-key-prod --query SecretString --output text)"
eval "$(aws configure export-credentials --format env)"
- SYNC_SERVICE_URL="https://sync-service-prod2.macroverse.workers.dev"
- LEXICAL_SERVICE_URL="https://lexical-service.macroverse.workers.dev"
DOCUMENT_STORAGE_BUCKET="macro-document-storage-prod"
- RUST_LOG="${RUST_LOG:-info}" DATABASE_URL="$DATABASE_URL" SYNC_SERVICE_AUTH_KEY="$SYNC_SERVICE_AUTH_KEY" INTERNAL_API_SECRET_KEY="$INTERNAL_API_SECRET_KEY" SYNC_SERVICE_URL="$SYNC_SERVICE_URL" LEXICAL_SERVICE_URL="$LEXICAL_SERVICE_URL" DOCUMENT_STORAGE_BUCKET="$DOCUMENT_STORAGE_BUCKET" \
+ RUST_LOG="${RUST_LOG:-info}" ENVIRONMENT="prod" DATABASE_URL="$DATABASE_URL" SYNC_SERVICE_AUTH_KEY="$SYNC_SERVICE_AUTH_KEY" INTERNAL_API_SECRET_KEY="$INTERNAL_API_SECRET_KEY" DOCUMENT_STORAGE_BUCKET="$DOCUMENT_STORAGE_BUCKET" \
cargo run -p documents --features backfill_binary --bin backfill_markdown_content_location -- --apply {{ FLAGS }}
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 a8ba636b4b..44c013667e 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
@@ -14,6 +14,7 @@ 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_service_urls::{LexicalServiceUrl, SyncServiceUrl};
use sqlx::postgres::PgPoolOptions;
use sync_service_client::SyncServiceClient;
@@ -89,7 +90,7 @@ async fn main() -> anyhow::Result<()> {
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 sync_service_url = env::var("SYNC_SERVICE_URL").context("SYNC_SERVICE_URL must be set")?;
+ let sync_service_url = SyncServiceUrl::new()?.to_string();
tracing::info!(
apply = options.apply,
@@ -158,8 +159,7 @@ fn build_markdown_initializer(
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 lexical_service_url = env::var("LEXICAL_SERVICE_URL")
- .context("LEXICAL_SERVICE_URL must be set when --initialize-missing is used")?;
+ let lexical_service_url = LexicalServiceUrl::new()?.to_string();
Ok(OptionalMarkdownInitializer::Enabled(
LexicalSyncMarkdownInitializer::new(
diff --git a/rust/cloud-storage/email_formatting/src/lib.rs b/rust/cloud-storage/email_formatting/src/lib.rs
index b7c8e6f149..5444b9ad2f 100644
--- a/rust/cloud-storage/email_formatting/src/lib.rs
+++ b/rust/cloud-storage/email_formatting/src/lib.rs
@@ -2,7 +2,7 @@ use askama::Template;
use chrono::{DateTime, Utc};
use hmac::Hmac;
use macro_env::Environment;
-use macro_service_urls::EnvExtMacroServiceUrls;
+use macro_service_urls::NotificationServiceUrl;
use macro_user_id::cowlike::CowLike;
use model_notifications::NotifEvent;
use notification::domain::models::{
@@ -106,7 +106,7 @@ impl EmailDigestNotification {
}
let num_truncated = input_len - preview_len;
- let mut unsubscribe_url = env.notification_service();
+ let mut unsubscribe_url = NotificationServiceUrl::new_for_environment(env)?.parse_url()?;
unsubscribe_url.set_path(&format!(
"/user_notifications/preferences/{}/disable",
Self::TYPE_NAME
diff --git a/rust/cloud-storage/email_service/Cargo.toml b/rust/cloud-storage/email_service/Cargo.toml
index 368733f39a..1e5bbc9727 100644
--- a/rust/cloud-storage/email_service/Cargo.toml
+++ b/rust/cloud-storage/email_service/Cargo.toml
@@ -161,5 +161,7 @@ utoipa = { workspace = true }
utoipa-swagger-ui = { workspace = true }
uuid = { workspace = true }
+macro_service_urls = { path = "../macro_service_urls" }
+
[dev-dependencies]
macro_auth = { path = "../macro_auth", features = ["testing"] }
diff --git a/rust/cloud-storage/email_service/src/config.rs b/rust/cloud-storage/email_service/src/config.rs
index 8b9e95e776..28becc2b09 100644
--- a/rust/cloud-storage/email_service/src/config.rs
+++ b/rust/cloud-storage/email_service/src/config.rs
@@ -1,6 +1,7 @@
use anyhow::Context;
pub use macro_env::Environment;
use macro_env_var::env_var;
+use macro_service_urls::{ConnectionGatewayUrl, DocumentStorageServiceUrl, StaticFileServiceUrl};
use secretsmanager_client::LocalOrRemoteSecret;
pub struct Config {
@@ -322,14 +323,11 @@ impl Config {
let auth_service_secret_key = std::env::var("AUTHENTICATION_SERVICE_SECRET_KEY")
.context("AUTHENTICATION_SERVICE_SECRET_KEY must be provided")?;
- let static_file_service_url = std::env::var("STATIC_FILE_SERVICE_URL")
- .context("STATIC_FILE_SERVICE_URL must be provided")?;
+ let static_file_service_url = StaticFileServiceUrl::new()?.to_string();
- let connection_gateway_url = std::env::var("CONNECTION_GATEWAY_URL")
- .context("CONNECTION_GATEWAY_URL must be provided")?;
+ let connection_gateway_url = ConnectionGatewayUrl::new()?.to_string();
- let document_storage_service_url = std::env::var("DOCUMENT_STORAGE_SERVICE_URL")
- .context("DOCUMENT_STORAGE_SERVICE_URL must be provided")?;
+ let document_storage_service_url = DocumentStorageServiceUrl::new()?.to_string();
let email_service_cloudfront_distribution_url =
std::env::var("EMAIL_SERVICE_CLOUDFRONT_DISTRIBUTION_URL")
diff --git a/rust/cloud-storage/github/src/inbound/github_sync_router/mod.rs b/rust/cloud-storage/github/src/inbound/github_sync_router/mod.rs
index 241a1767eb..9fdbb4ea4b 100644
--- a/rust/cloud-storage/github/src/inbound/github_sync_router/mod.rs
+++ b/rust/cloud-storage/github/src/inbound/github_sync_router/mod.rs
@@ -13,7 +13,7 @@ use axum::{
extract::{FromRequest, Request, State},
response::Redirect,
};
-use macro_service_urls::EnvExtMacroServiceUrls;
+use macro_service_urls::AppServiceUrl;
use reqwest::StatusCode;
use std::sync::Arc;
@@ -101,7 +101,7 @@ pub struct SyncRedirectParams {
pub async fn sync_redirect_handler<T: GithubSyncService>(
axum::extract::Query(_params): axum::extract::Query<SyncRedirectParams>,
) -> Redirect {
- Redirect::temporary(macro_env::Environment::new_or_prod().app().as_str())
+ Redirect::temporary(AppServiceUrl::unwrap_new().as_str())
}
/// Extractor that validates an incoming GitHub webhook event.
diff --git a/rust/cloud-storage/macro_service_urls/Cargo.toml b/rust/cloud-storage/macro_service_urls/Cargo.toml
index 6e44d65565..f2b9abd3cc 100644
--- a/rust/cloud-storage/macro_service_urls/Cargo.toml
+++ b/rust/cloud-storage/macro_service_urls/Cargo.toml
@@ -6,4 +6,6 @@ version = "0.1.0"
[dependencies]
macro_env = { path = "../macro_env" }
+paste = { workspace = true }
+thiserror = { workspace = true }
url = { workspace = true }
diff --git a/rust/cloud-storage/macro_service_urls/src/lib.rs b/rust/cloud-storage/macro_service_urls/src/lib.rs
index 033f1849d2..b6d2d2b78a 100644
--- a/rust/cloud-storage/macro_service_urls/src/lib.rs
+++ b/rust/cloud-storage/macro_service_urls/src/lib.rs
@@ -1,153 +1,590 @@
#![deny(missing_docs)]
-//! Service URL resolution based on the current environment.
-use macro_env::Environment;
-use url::Url;
+//! Macro service URL values with per-environment defaults and environment
+//! variable overrides.
+//!
+//! Use [`service_url!`] to define a newtype whose default value is selected
+//! from [`macro_env::Environment`]. The generated type also checks an override
+//! environment variable derived from the type name. For example,
+//! `DocumentStorageServiceUrl` checks `OVERRIDE_DOCUMENT_STORAGE_SERVICE_URL`
+//! before falling back to its `local`, `dev`, or `prod` default.
+
+use std::{borrow::Cow, fmt, ops::Deref};
+
+#[doc(hidden)]
+pub use macro_env;
+#[doc(hidden)]
+pub use paste;
+use thiserror::Error;
+pub use url::{ParseError as UrlParseError, Url};
#[cfg(test)]
mod test;
-/// Extension trait that provides service URLs based on the current environment.
-pub trait EnvExtMacroServiceUrls {
- /// The main app URL.
- fn app(&self) -> Url;
- /// Authentication service URL.
- fn auth_service(&self) -> Url;
- /// PDF rendering service URL.
- fn pdf_service(&self) -> Url;
- /// Document storage service URL.
- fn document_storage_service(&self) -> Url;
- /// WebSocket service URL.
- fn websocket_service(&self) -> Url;
- /// Document cognition service URL.
- fn cognition_service(&self) -> Url;
- /// WebSocket connection gateway URL.
- fn connection_gateway(&self) -> Url;
- /// Notification service URL.
- fn notification_service(&self) -> Url;
- /// Static file service URL.
- fn static_file_service(&self) -> Url;
- /// Link unfurl service URL.
- fn unfurl_service(&self) -> Url;
- /// Contacts service URL.
- fn contacts_service(&self) -> Url;
- /// Email service URL.
- fn email_service(&self) -> Url;
- /// Image proxy service URL.
- fn image_proxy_service(&self) -> Url;
-}
+#[cfg(test)]
+mod testing_harness {
+ use super::ServiceUrlVarErr;
+ use std::cell::Cell;
-/// Helper to parse a static URL string. All URLs here are compile-time constants
-/// so parsing can never fail.
-fn url(s: &str) -> Url {
- Url::parse(s).unwrap()
-}
+ type MockValue = Cell<Option<Box<dyn Fn(&'static str) -> Result<String, std::env::VarError>>>>;
-impl EnvExtMacroServiceUrls for Environment {
- fn app(&self) -> Url {
- match self {
- Environment::Production => url("https://macro.com"),
- Environment::Develop => url("https://dev.macro.com"),
- Environment::Local => {
- let port = std::env::var("FRONTEND_PORT").unwrap_or_else(|_| "3000".to_string());
- url(&format!("http://localhost:{port}"))
- }
- }
+ thread_local! {
+ static MOCK_VAR_GETTER: MockValue = const { Cell::new(None) };
}
- fn auth_service(&self) -> Url {
- match self {
- Environment::Production => url("https://auth-service.macro.com"),
- Environment::Develop => url("https://auth-service-dev.macro.com"),
- Environment::Local => url("http://localhost:8080"),
+ struct ResetMockEnv;
+
+ impl Drop for ResetMockEnv {
+ fn drop(&mut self) {
+ MOCK_VAR_GETTER.replace(None);
}
}
- fn pdf_service(&self) -> Url {
- match self {
- Environment::Production => url("https://pdf-service.macro.com"),
- Environment::Develop => url("https://pdf-service-dev.macro.com"),
- Environment::Local => url("http://localhost:4567"),
+ #[doc(hidden)]
+ pub fn read_override_env(var_name: &'static str) -> Result<Option<String>, ServiceUrlVarErr> {
+ let cur_getter = MOCK_VAR_GETTER.replace(None);
+ match cur_getter {
+ Some(mock) => {
+ let out = mock(var_name);
+ MOCK_VAR_GETTER.replace(Some(mock));
+ out
+ }
+ None => std::env::var(var_name),
}
+ .map(Some)
+ .or_else(|err| match err {
+ std::env::VarError::NotPresent => Ok(None),
+ err => Err(ServiceUrlVarErr { var_name, err }),
+ })
}
- fn document_storage_service(&self) -> Url {
- match self {
- Environment::Production => url("https://cloud-storage.macro.com"),
- Environment::Develop => url("https://cloud-storage-dev.macro.com"),
- Environment::Local => url("http://localhost:8086"),
- }
+ pub(crate) fn with_mock_override_env<F, Cb, U>(f: F, cb: Cb) -> U
+ where
+ F: Fn(&'static str) -> Result<String, std::env::VarError> + 'static,
+ Cb: FnOnce() -> U,
+ {
+ MOCK_VAR_GETTER.replace(Some(Box::new(f)));
+ let _guard = ResetMockEnv;
+ cb()
}
+}
- fn websocket_service(&self) -> Url {
- match self {
- Environment::Production => url("wss://services.macro.com"),
- Environment::Develop => url("wss://services-dev.macro.com"),
- Environment::Local => url("ws://localhost:6969"),
- }
+#[cfg(test)]
+#[doc(hidden)]
+pub use testing_harness::read_override_env;
+
+/// Read an override environment variable for a service URL.
+#[cfg(not(test))]
+#[doc(hidden)]
+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),
+ err => Err(ServiceUrlVarErr { var_name, err }),
+ })
+}
+
+/// A service URL string that can either borrow an existing string slice or own
+/// a runtime override value.
+#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
+pub struct ServiceUrl<'a>(Cow<'a, str>);
+
+impl<'a> ServiceUrl<'a> {
+ /// Create a service URL that borrows a string slice.
+ pub const fn borrowed(url: &'a str) -> Self {
+ Self(Cow::Borrowed(url))
}
- fn cognition_service(&self) -> Url {
- match self {
- Environment::Production => url("https://document-cognition.macro.com"),
- Environment::Develop => url("https://document-cognition-dev.macro.com"),
- Environment::Local => url("http://localhost:8085"),
- }
+ /// Create a service URL that owns a runtime string.
+ pub fn owned(url: impl Into<String>) -> ServiceUrl<'static> {
+ ServiceUrl(Cow::Owned(url.into()))
}
- fn connection_gateway(&self) -> Url {
- match self {
- Environment::Production => url("wss://connection-gateway.macro.com"),
- Environment::Develop => url("wss://connection-gateway-dev.macro.com"),
- Environment::Local => url("ws://localhost:8082"),
- }
+ /// Return the URL as a string slice.
+ pub fn as_str(&self) -> &str {
+ self.0.as_ref()
}
- fn notification_service(&self) -> Url {
- match self {
- Environment::Production => url("https://notifications.macro.com"),
- Environment::Develop => url("https://notifications-dev.macro.com"),
- Environment::Local => url("http://localhost:8089"),
- }
+ /// Parse the URL string into a [`Url`].
+ pub fn parse_url(&self) -> Result<Url, UrlParseError> {
+ Url::parse(self.as_str())
}
- fn static_file_service(&self) -> Url {
- match self {
- Environment::Production => url("https://static-file-service.macro.com"),
- Environment::Develop => url("https://static-file-service-dev.macro.com"),
- Environment::Local => url("http://localhost:8100"),
- }
+ /// Return a cheaply copied borrowed view of this URL.
+ pub fn copied(&self) -> ServiceUrl<'_> {
+ ServiceUrl(Cow::Borrowed(self.as_str()))
}
- fn unfurl_service(&self) -> Url {
- match self {
- Environment::Production => url("https://unfurl-service.macro.com"),
- Environment::Develop => url("https://unfurl-service-dev.macro.com"),
- Environment::Local => url("http://localhost:8095"),
- }
+ /// Convert this URL into an owned `'static` value.
+ pub fn into_owned(self) -> ServiceUrl<'static> {
+ ServiceUrl(Cow::Owned(self.0.into_owned()))
+ }
+
+ /// Convert this URL into its internal [`Cow`].
+ pub fn into_cow(self) -> Cow<'a, str> {
+ self.0
}
- fn contacts_service(&self) -> Url {
- match self {
- Environment::Production => url("https://contacts.macro.com"),
- Environment::Develop => url("https://contacts-dev.macro.com"),
- Environment::Local => url("http://localhost:8083"),
+ /// Return the borrowed string if this URL is currently borrowed.
+ pub fn borrowed_inner(&self) -> Option<&'a str> {
+ match &self.0 {
+ Cow::Borrowed(url) => Some(*url),
+ Cow::Owned(_) => None,
}
}
- fn email_service(&self) -> Url {
- match self {
- Environment::Production => url("https://email-service.macro.com"),
- Environment::Develop => url("https://email-service-dev.macro.com"),
- Environment::Local => url("http://localhost:8087"),
+ /// Return the owned string if this URL is currently owned.
+ pub fn owned_inner(&self) -> Option<&String> {
+ match &self.0 {
+ Cow::Borrowed(_) => None,
+ Cow::Owned(url) => Some(url),
}
}
+}
+
+impl<'a> From<&'a str> for ServiceUrl<'a> {
+ fn from(value: &'a str) -> Self {
+ Self::borrowed(value)
+ }
+}
+
+impl From<String> for ServiceUrl<'static> {
+ fn from(value: String) -> Self {
+ Self(Cow::Owned(value))
+ }
+}
+
+impl<'a> From<Cow<'a, str>> for ServiceUrl<'a> {
+ fn from(value: Cow<'a, str>) -> Self {
+ Self(value)
+ }
+}
+
+impl<'a> From<ServiceUrl<'a>> for String {
+ fn from(value: ServiceUrl<'a>) -> Self {
+ value.0.into_owned()
+ }
+}
+
+impl<'a> Deref for ServiceUrl<'a> {
+ type Target = str;
+
+ fn deref(&self) -> &Self::Target {
+ self.as_str()
+ }
+}
- fn image_proxy_service(&self) -> Url {
- match self {
- Environment::Production => url("https://image-proxy.macro.com"),
- Environment::Develop => url("https://image-proxy-dev.macro.com"),
- Environment::Local => url("http://localhost:8097"),
+impl<'a> AsRef<str> for ServiceUrl<'a> {
+ fn as_ref(&self) -> &str {
+ self.as_str()
+ }
+}
+
+impl<'a> fmt::Display for ServiceUrl<'a> {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ f.write_str(self.as_str())
+ }
+}
+
+/// Error returned when a service URL override environment variable cannot be
+/// read.
+#[derive(Debug, Error)]
+#[error("failed to read service URL override env var `{var_name}`: {err}")]
+pub struct ServiceUrlVarErr {
+ var_name: &'static str,
+ #[source]
+ err: std::env::VarError,
+}
+
+impl ServiceUrlVarErr {
+ /// The environment variable name that failed to load.
+ pub const fn var_name(&self) -> &'static str {
+ self.var_name
+ }
+
+ /// The underlying environment-variable error.
+ pub const fn env_var_error(&self) -> &std::env::VarError {
+ &self.err
+ }
+}
+
+/// Define typed service URL values with per-environment defaults and override
+/// environment variables.
+///
+/// The override environment variable name is derived from the struct name:
+/// `DocumentStorageServiceUrl` checks `OVERRIDE_DOCUMENT_STORAGE_SERVICE_URL`.
+/// If that override is not set, [`macro_env::Environment`] selects one of the
+/// provided `local`, `dev`, or `prod` defaults.
+///
+/// # Example
+///
+/// ```
+/// fn document_storage_service_url_example() -> Result<(), macro_service_urls::ServiceUrlVarErr> {
+/// macro_service_urls::service_url! {
+/// #[derive(Debug, Clone)]
+/// pub struct DocumentStorageServiceUrl {
+/// local: "http://localhost:8086",
+/// dev: "https://cloud-storage-dev.macro.com",
+/// prod: "https://cloud-storage.macro.com",
+/// }
+/// }
+///
+/// let url = DocumentStorageServiceUrl::new()?;
+/// assert_eq!(
+/// url.override_env_var_name(),
+/// "OVERRIDE_DOCUMENT_STORAGE_SERVICE_URL",
+/// );
+///
+/// Ok(())
+/// }
+///
+/// document_storage_service_url_example().unwrap();
+/// ```
+#[macro_export]
+macro_rules! service_url {
+ (
+ $(#[$attr:meta])*
+ $v:vis struct $n:ident {
+ local: $local:literal,
+ dev: $dev:literal,
+ prod: $prod:literal $(,)?
}
+ ) => {
+ $crate::paste::paste! {
+ #[doc = "Typed service URL loaded from `OVERRIDE_" $n:snake:upper "` or selected from per-environment defaults."]
+ $(#[$attr])*
+ $v struct $n($crate::ServiceUrl<'static>);
+
+ impl $n {
+ #[doc = "Override environment variable checked before falling back to per-environment defaults."]
+ $v const OVERRIDE_ENV_VAR_NAME: &'static str = concat!("OVERRIDE_", stringify!([<$n:snake:upper>]));
+
+ #[doc = "Default URL for [`macro_env::Environment::Local`]."]
+ $v const LOCAL: &'static str = $local;
+
+ #[doc = "Default URL for [`macro_env::Environment::Develop`]."]
+ $v const DEV: &'static str = $dev;
+
+ #[doc = "Default URL for [`macro_env::Environment::Production`]."]
+ $v const PROD: &'static str = $prod;
+
+ #[doc = "Create a new instance of [`Self`], using the override env var if set and otherwise selecting a default from [`macro_env::Environment::new_or_prod`]."]
+ #[allow(dead_code)]
+ $v fn new() -> Result<Self, $crate::ServiceUrlVarErr> {
+ if let Some(value) = $crate::read_override_env(Self::OVERRIDE_ENV_VAR_NAME)? {
+ return Ok(Self($crate::ServiceUrl::owned(value)));
+ }
+
+ Ok(Self::default_for_environment($crate::macro_env::Environment::new_or_prod()))
+ }
+
+ #[doc = "Create a new instance of [`Self`], panicking if the override env var is set but cannot be read."]
+ #[allow(dead_code)]
+ $v fn unwrap_new() -> Self {
+ Self::new().expect(concat!("Failed to resolve service URL for ", stringify!($n)))
+ }
+
+ #[doc = "Create a new instance of [`Self`] for a specific environment, using the override env var if set."]
+ #[allow(dead_code)]
+ $v fn new_for_environment(environment: $crate::macro_env::Environment) -> Result<Self, $crate::ServiceUrlVarErr> {
+ if let Some(value) = $crate::read_override_env(Self::OVERRIDE_ENV_VAR_NAME)? {
+ return Ok(Self($crate::ServiceUrl::owned(value)));
+ }
+
+ Ok(Self::default_for_environment(environment))
+ }
+
+ #[doc = "Create a new instance of [`Self`] for a specific environment without checking the override env var."]
+ #[allow(dead_code)]
+ $v const fn default_for_environment(environment: $crate::macro_env::Environment) -> Self {
+ match environment {
+ $crate::macro_env::Environment::Local => Self::from_static(Self::LOCAL),
+ $crate::macro_env::Environment::Develop => Self::from_static(Self::DEV),
+ $crate::macro_env::Environment::Production => Self::from_static(Self::PROD),
+ }
+ }
+
+ #[doc = "Create a new instance of [`Self`] from the local default URL."]
+ #[allow(dead_code)]
+ $v const fn local() -> Self {
+ Self::from_static(Self::LOCAL)
+ }
+
+ #[doc = "Create a new instance of [`Self`] from the dev default URL."]
+ #[allow(dead_code)]
+ $v const fn dev() -> Self {
+ Self::from_static(Self::DEV)
+ }
+
+ #[doc = "Create a new instance of [`Self`] from the prod default URL."]
+ #[allow(dead_code)]
+ $v const fn prod() -> Self {
+ Self::from_static(Self::PROD)
+ }
+
+ #[doc = "Create a new instance of [`Self`] from a static URL."]
+ #[allow(dead_code)]
+ $v const fn from_static(url: &'static str) -> Self {
+ Self($crate::ServiceUrl::borrowed(url))
+ }
+
+ #[doc = "Create a new instance of [`Self`] from an owned runtime URL."]
+ #[allow(dead_code)]
+ $v fn from_owned(url: impl Into<String>) -> Self {
+ Self($crate::ServiceUrl::owned(url))
+ }
+
+ #[doc = "Return the override environment variable name checked by [`Self::new`]."]
+ #[allow(dead_code)]
+ $v const fn override_env_var_name(&self) -> &'static str {
+ Self::OVERRIDE_ENV_VAR_NAME
+ }
+
+ #[doc = "Return the contained [`ServiceUrl`]."]
+ #[allow(dead_code)]
+ $v fn into_inner(self) -> $crate::ServiceUrl<'static> {
+ self.0
+ }
+
+ #[doc = "Return a reference to the contained [`ServiceUrl`]."]
+ #[allow(dead_code)]
+ $v fn inner(&self) -> &$crate::ServiceUrl<'static> {
+ &self.0
+ }
+
+ #[doc = "Return the URL as a string slice."]
+ #[allow(dead_code)]
+ $v fn as_str(&self) -> &str {
+ self.0.as_str()
+ }
+
+ #[doc = "Parse the URL string into a URL."]
+ #[allow(dead_code)]
+ $v fn parse_url(&self) -> Result<$crate::Url, $crate::UrlParseError> {
+ self.0.parse_url()
+ }
+
+ #[doc = "Return a cheaply copied borrowed view of this URL."]
+ #[allow(dead_code)]
+ $v fn copied(&self) -> $crate::ServiceUrl<'_> {
+ self.0.copied()
+ }
+ }
+
+ impl std::ops::Deref for $n {
+ type Target = str;
+
+ fn deref(&self) -> &Self::Target {
+ self.as_str()
+ }
+ }
+
+ impl std::convert::AsRef<str> for $n {
+ fn as_ref(&self) -> &str {
+ self.as_str()
+ }
+ }
+
+ impl std::fmt::Display for $n {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.write_str(self.as_str())
+ }
+ }
+
+ impl std::convert::From<$crate::ServiceUrl<'static>> for $n {
+ fn from(value: $crate::ServiceUrl<'static>) -> Self {
+ Self(value)
+ }
+ }
+
+ impl std::convert::From<$n> for $crate::ServiceUrl<'static> {
+ fn from(value: $n) -> Self {
+ value.0
+ }
+ }
+
+ impl std::convert::From<String> for $n {
+ fn from(value: String) -> Self {
+ Self::from_owned(value)
+ }
+ }
+
+ impl std::convert::From<&'static str> for $n {
+ fn from(value: &'static str) -> Self {
+ Self::from_static(value)
+ }
+ }
+ }
+ };
+ (
+ $(#[$attr:meta])*
+ $v:vis struct $n:ident {
+ $(
+ $(#[$field_attr:meta])*
+ $field_vis:vis $field_name:ident {
+ local: $field_local:literal,
+ dev: $field_dev:literal,
+ prod: $field_prod:literal $(,)?
+ }
+ ),* $(,)?
+ }
+ ) => {
+ $crate::paste::paste! {
+ $(
+ $crate::service_url!(
+ $(#[$field_attr])*
+ $field_vis struct $field_name {
+ local: $field_local,
+ dev: $field_dev,
+ prod: $field_prod,
+ }
+ );
+ )*
+
+ #[doc = "A collection of typed service URLs."]
+ $(#[$attr])*
+ $v struct $n {
+ $(
+ #[doc = "Typed service URL loaded from `OVERRIDE_" $field_name:snake:upper "` or selected from per-environment defaults."]
+ $field_vis [<$field_name:snake>]: $field_name,
+ )*
+ }
+
+ impl $n {
+ #[doc = "Create a new instance of [`Self`] with all service URLs resolved for the current macro environment."]
+ #[allow(dead_code)]
+ $v fn new() -> Result<Self, $crate::ServiceUrlVarErr> {
+ let environment = $crate::macro_env::Environment::new_or_prod();
+ Self::new_for_environment(environment)
+ }
+
+ #[doc = "Create a new instance of [`Self`] with all service URLs resolved for the current macro environment, panicking if an override env var is set but cannot be read."]
+ #[allow(dead_code)]
+ $v fn unwrap_new() -> Self {
+ Self::new().expect(concat!("Failed to resolve service URL collection for ", stringify!($n)))
+ }
+
+ #[doc = "Create a new instance of [`Self`] with all service URLs resolved for a specific environment."]
+ #[allow(dead_code)]
+ $v fn new_for_environment(environment: $crate::macro_env::Environment) -> Result<Self, $crate::ServiceUrlVarErr> {
+ Ok(Self {
+ $(
+ [<$field_name:snake>]: $field_name::new_for_environment(environment)?,
+ )*
+ })
+ }
+
+ #[doc = "Create a new instance of [`Self`] with all service URLs set to environment defaults without checking overrides."]
+ #[allow(dead_code)]
+ $v const fn default_for_environment(environment: $crate::macro_env::Environment) -> Self {
+ Self {
+ $(
+ [<$field_name:snake>]: $field_name::default_for_environment(environment),
+ )*
+ }
+ }
+ }
+ }
+ };
+}
+
+service_url! {
+ /// Common service URLs used by Macro services.
+ pub struct ServiceUrls {
+ /// Main app URL.
+ pub AppServiceUrl {
+ local: "http://localhost:3000",
+ dev: "https://dev.macro.com",
+ prod: "https://macro.com",
+ },
+ /// Authentication service API URL.
+ pub AuthServiceUrl {
+ local: "http://localhost:8080",
+ dev: "https://auth-service-dev.macro.com",
+ prod: "https://auth-service.macro.com",
+ },
+ /// PDF rendering service API URL.
+ pub PdfServiceUrl {
+ local: "http://localhost:4567",
+ dev: "https://pdf-service-dev.macro.com",
+ prod: "https://pdf-service.macro.com",
+ },
+ /// Document storage service API URL.
+ pub DocumentStorageServiceUrl {
+ local: "http://localhost:8086",
+ dev: "https://cloud-storage-dev.macro.com",
+ prod: "https://cloud-storage.macro.com",
+ },
+ /// WebSocket service URL.
+ pub WebsocketServiceUrl {
+ local: "ws://localhost:6969",
+ dev: "wss://services-dev.macro.com",
+ prod: "wss://services.macro.com",
+ },
+ /// Connection gateway HTTP API URL.
+ pub ConnectionGatewayUrl {
+ local: "http://localhost:8082",
+ dev: "https://connection-gateway-dev.macro.com",
+ prod: "https://connection-gateway.macro.com",
+ },
+ /// Connection gateway WebSocket URL.
+ pub ConnectionGatewayWebsocketUrl {
+ local: "ws://localhost:8082",
+ dev: "wss://connection-gateway-dev.macro.com",
+ prod: "wss://connection-gateway.macro.com",
+ },
+ /// Document cognition service API URL.
+ pub DocumentCognitionServiceUrl {
+ local: "http://localhost:8085",
+ dev: "https://document-cognition-dev.macro.com",
+ prod: "https://document-cognition.macro.com",
+ },
+ /// Notification service API URL.
+ pub NotificationServiceUrl {
+ local: "http://localhost:8089",
+ dev: "https://notifications-dev.macro.com",
+ prod: "https://notifications.macro.com",
+ },
+ /// Static file service/CDN URL.
+ pub StaticFileServiceUrl {
+ local: "http://localhost:8100",
+ dev: "https://static-file-service-dev.macro.com",
+ prod: "https://static-file-service.macro.com",
+ },
+ /// Link unfurl service API URL.
+ pub UnfurlServiceUrl {
+ local: "http://localhost:8095",
+ dev: "https://unfurl-service-dev.macro.com",
+ prod: "https://unfurl-service.macro.com",
+ },
+ /// Contacts service API URL.
+ pub ContactsServiceUrl {
+ local: "http://localhost:8083",
+ dev: "https://contacts-dev.macro.com",
+ prod: "https://contacts.macro.com",
+ },
+ /// Email service API URL.
+ pub EmailServiceUrl {
+ local: "http://localhost:8087",
+ dev: "https://email-service-dev.macro.com",
+ prod: "https://email-service.macro.com",
+ },
+ /// Image proxy service API URL.
+ pub ImageProxyServiceUrl {
+ local: "http://localhost:8097",
+ dev: "https://image-proxy-dev.macro.com",
+ prod: "https://image-proxy.macro.com",
+ },
+ /// Lexical conversion service API URL.
+ pub LexicalServiceUrl {
+ local: "http://localhost:8096",
+ dev: "https://lexical-service-dev.macroverse.workers.dev",
+ prod: "https://lexical-service.macroverse.workers.dev",
+ },
+ /// Sync service API URL.
+ pub SyncServiceUrl {
+ local: "http://localhost:8787",
+ dev: "https://sync-service-dev3.macroverse.workers.dev",
+ prod: "https://sync-service-prod2.macroverse.workers.dev",
+ },
}
}
diff --git a/rust/cloud-storage/macro_service_urls/src/test.rs b/rust/cloud-storage/macro_service_urls/src/test.rs
index 7d28195788..1df702e146 100644
--- a/rust/cloud-storage/macro_service_urls/src/test.rs
+++ b/rust/cloud-storage/macro_service_urls/src/test.rs
@@ -1,4 +1,6 @@
+use super::testing_harness::with_mock_override_env;
use super::*;
+use macro_env::Environment;
const ENVS: [Environment; 3] = [
Environment::Production,
@@ -6,93 +8,519 @@ const ENVS: [Environment; 3] = [
Environment::Local,
];
-#[test]
-fn app_parses() {
- for env in ENVS {
- let _ = env.app();
+fn assert_parses_for_all_environments<T>(service_url_for_environment: impl Fn(Environment) -> T)
+where
+ T: AsRef<str>,
+{
+ for environment in ENVS {
+ service_url_for_environment(environment)
+ .as_ref()
+ .parse::<Url>()
+ .unwrap();
}
}
#[test]
-fn auth_service_parses() {
- for env in ENVS {
- let _ = env.auth_service();
- }
+fn app_service_url_parses() {
+ assert_parses_for_all_environments(AppServiceUrl::default_for_environment);
}
#[test]
-fn pdf_service_parses() {
- for env in ENVS {
- let _ = env.pdf_service();
- }
+fn auth_service_url_parses() {
+ assert_parses_for_all_environments(AuthServiceUrl::default_for_environment);
}
#[test]
-fn document_storage_service_parses() {
- for env in ENVS {
- let _ = env.document_storage_service();
- }
+fn pdf_service_url_parses() {
+ assert_parses_for_all_environments(PdfServiceUrl::default_for_environment);
}
#[test]
-fn websocket_service_parses() {
- for env in ENVS {
- let _ = env.websocket_service();
- }
+fn document_storage_service_url_parses() {
+ assert_parses_for_all_environments(DocumentStorageServiceUrl::default_for_environment);
}
#[test]
-fn cognition_service_parses() {
- for env in ENVS {
- let _ = env.cognition_service();
- }
+fn websocket_service_url_parses() {
+ assert_parses_for_all_environments(WebsocketServiceUrl::default_for_environment);
}
#[test]
-fn connection_gateway_parses() {
- for env in ENVS {
- let _ = env.connection_gateway();
- }
+fn connection_gateway_url_parses() {
+ assert_parses_for_all_environments(ConnectionGatewayUrl::default_for_environment);
}
#[test]
-fn notification_service_parses() {
- for env in ENVS {
- let _ = env.notification_service();
- }
+fn connection_gateway_websocket_url_parses() {
+ assert_parses_for_all_environments(ConnectionGatewayWebsocketUrl::default_for_environment);
}
#[test]
-fn static_file_service_parses() {
- for env in ENVS {
- let _ = env.static_file_service();
- }
+fn document_cognition_service_url_parses() {
+ assert_parses_for_all_environments(DocumentCognitionServiceUrl::default_for_environment);
}
#[test]
-fn unfurl_service_parses() {
- for env in ENVS {
- let _ = env.unfurl_service();
- }
+fn notification_service_url_parses() {
+ assert_parses_for_all_environments(NotificationServiceUrl::default_for_environment);
}
#[test]
-fn contacts_service_parses() {
- for env in ENVS {
- let _ = env.contacts_service();
- }
+fn static_file_service_url_parses() {
+ assert_parses_for_all_environments(StaticFileServiceUrl::default_for_environment);
+}
+
+#[test]
+fn unfurl_service_url_parses() {
+ assert_parses_for_all_environments(UnfurlServiceUrl::default_for_environment);
+}
+
+#[test]
+fn contacts_service_url_parses() {
+ assert_parses_for_all_environments(ContactsServiceUrl::default_for_environment);
+}
+
+#[test]
+fn email_service_url_parses() {
+ assert_parses_for_all_environments(EmailServiceUrl::default_for_environment);
}
#[test]
-fn email_service_parses() {
- for env in ENVS {
- let _ = env.email_service();
+fn image_proxy_service_url_parses() {
+ assert_parses_for_all_environments(ImageProxyServiceUrl::default_for_environment);
+}
+
+#[test]
+fn lexical_service_url_parses() {
+ assert_parses_for_all_environments(LexicalServiceUrl::default_for_environment);
+}
+
+#[test]
+fn sync_service_url_parses() {
+ assert_parses_for_all_environments(SyncServiceUrl::default_for_environment);
+}
+
+crate::service_url! {
+ #[derive(Debug, Clone)]
+ pub struct TestServiceUrl {
+ local: "http://localhost:8080",
+ dev: "https://test-dev.macro.com",
+ prod: "https://test.macro.com",
}
}
+fn missing_override(_: &'static str) -> Result<String, std::env::VarError> {
+ Err(std::env::VarError::NotPresent)
+}
+
#[test]
-fn image_proxy_service_parses() {
- for env in ENVS {
- let _ = env.image_proxy_service();
+fn defaults_are_selected_by_environment() {
+ with_mock_override_env(missing_override, || {
+ assert_eq!(
+ TestServiceUrl::new_for_environment(macro_env::Environment::Local)
+ .unwrap()
+ .as_ref(),
+ "http://localhost:8080",
+ );
+ assert_eq!(
+ TestServiceUrl::new_for_environment(macro_env::Environment::Develop)
+ .unwrap()
+ .as_ref(),
+ "https://test-dev.macro.com",
+ );
+ assert_eq!(
+ TestServiceUrl::new_for_environment(macro_env::Environment::Production)
+ .unwrap()
+ .as_ref(),
+ "https://test.macro.com",
+ );
+ });
+}
+
+#[test]
+fn default_values_are_borrowed() {
+ let service_url = TestServiceUrl::default_for_environment(macro_env::Environment::Local);
+
+ assert_eq!(service_url.as_ref(), "http://localhost:8080");
+ assert_eq!(
+ service_url.inner().borrowed_inner(),
+ Some("http://localhost:8080"),
+ );
+}
+
+fn mock_test_service_override(var_name: &'static str) -> Result<String, std::env::VarError> {
+ (var_name == "OVERRIDE_TEST_SERVICE_URL")
+ .then(|| "https://override.macro.com".to_string())
+ .ok_or(std::env::VarError::NotPresent)
+}
+
+#[test]
+fn override_env_var_wins_over_environment_default() {
+ let service_url = with_mock_override_env(mock_test_service_override, || {
+ TestServiceUrl::new_for_environment(macro_env::Environment::Local).unwrap()
+ });
+
+ assert_eq!(service_url.as_ref(), "https://override.macro.com");
+ assert_eq!(
+ service_url.override_env_var_name(),
+ "OVERRIDE_TEST_SERVICE_URL",
+ );
+ assert_eq!(
+ service_url.inner().owned_inner().unwrap(),
+ "https://override.macro.com",
+ );
+}
+
+#[test]
+fn helpers_construct_expected_defaults() {
+ assert_eq!(TestServiceUrl::local().as_ref(), "http://localhost:8080");
+ assert_eq!(TestServiceUrl::dev().as_ref(), "https://test-dev.macro.com");
+ assert_eq!(TestServiceUrl::prod().as_ref(), "https://test.macro.com");
+}
+
+#[test]
+fn copied_returns_a_borrowed_view() {
+ let service_url = TestServiceUrl::from_owned("https://runtime.macro.com");
+ let copied = service_url.copied();
+
+ assert_eq!(copied.as_ref(), "https://runtime.macro.com");
+ assert_eq!(copied.borrowed_inner(), Some("https://runtime.macro.com"));
+}
+
+crate::service_url! {
+ #[derive(Debug)]
+ pub struct TestServiceUrls {
+ #[derive(Debug, Clone)]
+ pub TestDocumentStorageServiceUrl {
+ local: "http://localhost:8086",
+ dev: "https://cloud-storage-dev.macro.com",
+ prod: "https://cloud-storage.macro.com",
+ },
+ #[derive(Debug, Clone)]
+ pub TestEmailServiceUrl {
+ local: "http://localhost:8087",
+ dev: "https://email-service-dev.macro.com",
+ prod: "https://email-service.macro.com",
+ },
+ }
+}
+
+fn mock_group_overrides(var_name: &'static str) -> Result<String, std::env::VarError> {
+ match var_name {
+ "OVERRIDE_TEST_EMAIL_SERVICE_URL" => Ok("https://email-override.macro.com".to_string()),
+ _ => Err(std::env::VarError::NotPresent),
}
}
+
+#[test]
+fn grouped_macro_resolves_all_service_urls() {
+ let service_urls = with_mock_override_env(mock_group_overrides, || {
+ TestServiceUrls::new_for_environment(macro_env::Environment::Develop).unwrap()
+ });
+
+ assert_eq!(
+ service_urls.test_document_storage_service_url.as_ref(),
+ "https://cloud-storage-dev.macro.com",
+ );
+ assert_eq!(
+ service_urls.test_email_service_url.as_ref(),
+ "https://email-override.macro.com",
+ );
+}
+
+#[test]
+fn grouped_defaults_do_not_check_overrides() {
+ let service_urls = TestServiceUrls::default_for_environment(macro_env::Environment::Production);
+
+ assert_eq!(
+ service_urls.test_document_storage_service_url.as_ref(),
+ "https://cloud-storage.macro.com",
+ );
+ assert_eq!(
+ service_urls.test_email_service_url.as_ref(),
+ "https://email-service.macro.com",
+ );
+}
+
+#[test]
+fn exported_service_urls_match_local_values() {
+ let service_urls = ServiceUrls::default_for_environment(macro_env::Environment::Local);
+
+ assert_eq!(
+ service_urls.app_service_url.as_ref(),
+ "http://localhost:3000"
+ );
+ assert_eq!(
+ service_urls.auth_service_url.as_ref(),
+ "http://localhost:8080"
+ );
+ assert_eq!(
+ service_urls.pdf_service_url.as_ref(),
+ "http://localhost:4567"
+ );
+ assert_eq!(
+ service_urls.document_storage_service_url.as_ref(),
+ "http://localhost:8086",
+ );
+ assert_eq!(
+ service_urls.websocket_service_url.as_ref(),
+ "ws://localhost:6969"
+ );
+ assert_eq!(
+ service_urls.connection_gateway_url.as_ref(),
+ "http://localhost:8082",
+ );
+ assert_eq!(
+ service_urls.connection_gateway_websocket_url.as_ref(),
+ "ws://localhost:8082",
+ );
+ assert_eq!(
+ service_urls.document_cognition_service_url.as_ref(),
+ "http://localhost:8085",
+ );
+ assert_eq!(
+ service_urls.notification_service_url.as_ref(),
+ "http://localhost:8089",
+ );
+ assert_eq!(
+ service_urls.static_file_service_url.as_ref(),
+ "http://localhost:8100",
+ );
+ assert_eq!(
+ service_urls.unfurl_service_url.as_ref(),
+ "http://localhost:8095"
+ );
+ assert_eq!(
+ service_urls.contacts_service_url.as_ref(),
+ "http://localhost:8083"
+ );
+ assert_eq!(
+ service_urls.email_service_url.as_ref(),
+ "http://localhost:8087"
+ );
+ assert_eq!(
+ service_urls.image_proxy_service_url.as_ref(),
+ "http://localhost:8097",
+ );
+ assert_eq!(
+ service_urls.lexical_service_url.as_ref(),
+ "http://localhost:8096"
+ );
+ assert_eq!(
+ service_urls.sync_service_url.as_ref(),
+ "http://localhost:8787"
+ );
+}
+
+#[test]
+fn exported_service_urls_match_dev_values() {
+ let service_urls = ServiceUrls::default_for_environment(macro_env::Environment::Develop);
+
+ assert_eq!(
+ service_urls.app_service_url.as_ref(),
+ "https://dev.macro.com"
+ );
+ assert_eq!(
+ service_urls.auth_service_url.as_ref(),
+ "https://auth-service-dev.macro.com",
+ );
+ assert_eq!(
+ service_urls.pdf_service_url.as_ref(),
+ "https://pdf-service-dev.macro.com",
+ );
+ assert_eq!(
+ service_urls.document_storage_service_url.as_ref(),
+ "https://cloud-storage-dev.macro.com",
+ );
+ assert_eq!(
+ service_urls.websocket_service_url.as_ref(),
+ "wss://services-dev.macro.com",
+ );
+ assert_eq!(
+ service_urls.connection_gateway_url.as_ref(),
+ "https://connection-gateway-dev.macro.com",
+ );
+ assert_eq!(
+ service_urls.connection_gateway_websocket_url.as_ref(),
+ "wss://connection-gateway-dev.macro.com",
+ );
+ assert_eq!(
+ service_urls.document_cognition_service_url.as_ref(),
+ "https://document-cognition-dev.macro.com",
+ );
+ assert_eq!(
+ service_urls.notification_service_url.as_ref(),
+ "https://notifications-dev.macro.com",
+ );
+ assert_eq!(
+ service_urls.static_file_service_url.as_ref(),
+ "https://static-file-service-dev.macro.com",
+ );
+ assert_eq!(
+ service_urls.unfurl_service_url.as_ref(),
+ "https://unfurl-service-dev.macro.com",
+ );
+ assert_eq!(
+ service_urls.contacts_service_url.as_ref(),
+ "https://contacts-dev.macro.com",
+ );
+ assert_eq!(
+ service_urls.email_service_url.as_ref(),
+ "https://email-service-dev.macro.com",
+ );
+ assert_eq!(
+ service_urls.image_proxy_service_url.as_ref(),
+ "https://image-proxy-dev.macro.com",
+ );
+ assert_eq!(
+ service_urls.lexical_service_url.as_ref(),
+ "https://lexical-service-dev.macroverse.workers.dev",
+ );
+ assert_eq!(
+ service_urls.sync_service_url.as_ref(),
+ "https://sync-service-dev3.macroverse.workers.dev",
+ );
+}
+
+#[test]
+fn exported_service_urls_match_prod_values() {
+ let service_urls = ServiceUrls::default_for_environment(macro_env::Environment::Production);
+
+ assert_eq!(service_urls.app_service_url.as_ref(), "https://macro.com");
+ assert_eq!(
+ service_urls.auth_service_url.as_ref(),
+ "https://auth-service.macro.com",
+ );
+ assert_eq!(
+ service_urls.pdf_service_url.as_ref(),
+ "https://pdf-service.macro.com",
+ );
+ assert_eq!(
+ service_urls.document_storage_service_url.as_ref(),
+ "https://cloud-storage.macro.com",
+ );
+ assert_eq!(
+ service_urls.websocket_service_url.as_ref(),
+ "wss://services.macro.com",
+ );
+ assert_eq!(
+ service_urls.connection_gateway_url.as_ref(),
+ "https://connection-gateway.macro.com",
+ );
+ assert_eq!(
+ service_urls.connection_gateway_websocket_url.as_ref(),
+ "wss://connection-gateway.macro.com",
+ );
+ assert_eq!(
+ service_urls.document_cognition_service_url.as_ref(),
+ "https://document-cognition.macro.com",
+ );
+ assert_eq!(
+ service_urls.notification_service_url.as_ref(),
+ "https://notifications.macro.com",
+ );
+ assert_eq!(
+ service_urls.static_file_service_url.as_ref(),
+ "https://static-file-service.macro.com",
+ );
+ assert_eq!(
+ service_urls.unfurl_service_url.as_ref(),
+ "https://unfurl-service.macro.com",
+ );
+ assert_eq!(
+ service_urls.contacts_service_url.as_ref(),
+ "https://contacts.macro.com",
+ );
+ assert_eq!(
+ service_urls.email_service_url.as_ref(),
+ "https://email-service.macro.com",
+ );
+ assert_eq!(
+ service_urls.image_proxy_service_url.as_ref(),
+ "https://image-proxy.macro.com",
+ );
+ assert_eq!(
+ service_urls.lexical_service_url.as_ref(),
+ "https://lexical-service.macroverse.workers.dev",
+ );
+ assert_eq!(
+ service_urls.sync_service_url.as_ref(),
+ "https://sync-service-prod2.macroverse.workers.dev",
+ );
+}
+
+#[test]
+fn exported_service_url_override_names_are_derived_from_env_var_names() {
+ assert_eq!(
+ AppServiceUrl::local().override_env_var_name(),
+ "OVERRIDE_APP_SERVICE_URL",
+ );
+ assert_eq!(
+ AuthServiceUrl::local().override_env_var_name(),
+ "OVERRIDE_AUTH_SERVICE_URL",
+ );
+ assert_eq!(
+ PdfServiceUrl::local().override_env_var_name(),
+ "OVERRIDE_PDF_SERVICE_URL",
+ );
+ assert_eq!(
+ DocumentStorageServiceUrl::local().override_env_var_name(),
+ "OVERRIDE_DOCUMENT_STORAGE_SERVICE_URL",
+ );
+ assert_eq!(
+ WebsocketServiceUrl::local().override_env_var_name(),
+ "OVERRIDE_WEBSOCKET_SERVICE_URL",
+ );
+ assert_eq!(
+ ConnectionGatewayUrl::local().override_env_var_name(),
+ "OVERRIDE_CONNECTION_GATEWAY_URL",
+ );
+ assert_eq!(
+ ConnectionGatewayWebsocketUrl::local().override_env_var_name(),
+ "OVERRIDE_CONNECTION_GATEWAY_WEBSOCKET_URL",
+ );
+ assert_eq!(
+ DocumentCognitionServiceUrl::local().override_env_var_name(),
+ "OVERRIDE_DOCUMENT_COGNITION_SERVICE_URL",
+ );
+ assert_eq!(
+ NotificationServiceUrl::local().override_env_var_name(),
+ "OVERRIDE_NOTIFICATION_SERVICE_URL",
+ );
+ assert_eq!(
+ StaticFileServiceUrl::local().override_env_var_name(),
+ "OVERRIDE_STATIC_FILE_SERVICE_URL",
+ );
+ assert_eq!(
+ UnfurlServiceUrl::local().override_env_var_name(),
+ "OVERRIDE_UNFURL_SERVICE_URL",
+ );
+ assert_eq!(
+ ContactsServiceUrl::local().override_env_var_name(),
+ "OVERRIDE_CONTACTS_SERVICE_URL",
+ );
+ assert_eq!(
+ EmailServiceUrl::local().override_env_var_name(),
+ "OVERRIDE_EMAIL_SERVICE_URL",
+ );
+ assert_eq!(
+ ImageProxyServiceUrl::local().override_env_var_name(),
+ "OVERRIDE_IMAGE_PROXY_SERVICE_URL",
+ );
+ assert_eq!(
+ LexicalServiceUrl::local().override_env_var_name(),
+ "OVERRIDE_LEXICAL_SERVICE_URL",
+ );
+ assert_eq!(
+ SyncServiceUrl::local().override_env_var_name(),
+ "OVERRIDE_SYNC_SERVICE_URL",
+ );
+}
+
+#[test]
+fn service_url_converts_to_string() {
+ let service_url = ServiceUrl::borrowed("https://borrowed.macro.com");
+ let url_string: String = service_url.into();
+
+ assert_eq!(url_string, "https://borrowed.macro.com");
+}
diff --git a/rust/cloud-storage/mcp_service/Cargo.toml b/rust/cloud-storage/mcp_service/Cargo.toml
index 09c36a8fa4..5826a2cbbf 100644
--- a/rust/cloud-storage/mcp_service/Cargo.toml
+++ b/rust/cloud-storage/mcp_service/Cargo.toml
@@ -60,3 +60,5 @@ sqs_client = { path = "../sqs_client", default-features = false, features = [
sync_service_client = { path = "../sync_service_client" }
tokio = { workspace = true }
tracing = { workspace = true }
+
+macro_service_urls = { path = "../macro_service_urls" }
diff --git a/rust/cloud-storage/mcp_service/src/context.rs b/rust/cloud-storage/mcp_service/src/context.rs
index 033898f917..531031a981 100644
--- a/rust/cloud-storage/mcp_service/src/context.rs
+++ b/rust/cloud-storage/mcp_service/src/context.rs
@@ -27,6 +27,9 @@ use frecency::outbound::postgres::FrecencyPgStorage;
use macro_auth::middleware::decode_jwt::JwtValidationArgs;
use macro_env_var::env_var;
use macro_middleware::auth::internal_access::InternalApiSecretKey;
+use macro_service_urls::{
+ DocumentStorageServiceUrl, EmailServiceUrl, LexicalServiceUrl, SyncServiceUrl,
+};
use mcp_auth_proxy::{
domain::service::McpAuthProxyServiceImpl,
outbound::{fusionauth::FusionAuthOAuthProvider, redis::RedisInflightAuth},
@@ -44,13 +47,8 @@ env_var!(
pub struct McpEnvVars {
DatabaseUrl,
EmailScheduledQueue,
- DocumentStorageServiceUrl,
DocumentStorageServiceAuthKey,
- SyncServiceUrl,
SyncServiceAuthKey,
- LexicalServiceUrl,
- EmailServiceUrl,
- StaticFileServiceUrl,
DocumentStorageBucket,
DocxDocumentUploadBucket,
DocumentStorageServiceCloudfrontDistributionUrl,
@@ -154,20 +152,22 @@ async fn build_tool_context(
document_storage_service_auth_key: String,
sync_service_auth_key: String,
) -> anyhow::Result<ToolServiceContext> {
- let dss_url: String = env_vars.document_storage_service_url.as_ref().to_owned();
- let sync_service_url: String = env_vars.sync_service_url.as_ref().to_owned();
+ let dss_url = DocumentStorageServiceUrl::new()?.to_string();
+ let sync_service_url = SyncServiceUrl::new()?.to_string();
+ let lexical_service_url = LexicalServiceUrl::new()?.to_string();
+ let email_service_url = EmailServiceUrl::new()?.to_string();
let search_service_client =
SearchServiceClient::new(document_storage_service_auth_key, dss_url);
let lexical_client = Arc::new(lexical_client::LexicalClient::new(
internal_auth_key.clone(),
- env_vars.lexical_service_url.as_ref().to_owned(),
+ lexical_service_url,
));
let email_service_client = Arc::new(EmailServiceClient::new(
internal_auth_key.clone(),
- env_vars.email_service_url.as_ref().to_owned(),
+ email_service_url,
));
let frecency_storage = FrecencyPgStorage::new(db.clone());
diff --git a/rust/cloud-storage/memory/src/context.rs b/rust/cloud-storage/memory/src/context.rs
index eaf0fe0c0f..b97d028601 100644
--- a/rust/cloud-storage/memory/src/context.rs
+++ b/rust/cloud-storage/memory/src/context.rs
@@ -31,16 +31,22 @@ use sync_service_client::SyncServiceClient;
use crate::config::Config;
-/// Builds a [`ToolServiceContext`] from environment variables and a database pool.
+/// Builds a [`ToolServiceContext`] from a database pool and caller-provided config.
///
-/// Required env vars: `INTERNAL_API_SECRET_KEY`, `DOCUMENT_STORAGE_SERVICE_URL`,
-/// `EMAIL_SERVICE_URL`, `SYNC_SERVICE_URL`,
-/// `DOCUMENT_COGNITION_SERVICE_URL`, `STATIC_FILE_SERVICE_URL`,
-/// `DOCUMENT_STORAGE_BUCKET`, `DOCX_DOCUMENT_UPLOAD_BUCKET`,
-/// `EMAIL_SCHEDULED_QUEUE`,
+/// This function does not resolve service URLs. The caller must provide a [`Config`]
+/// whose service URL fields have already been resolved, for example with
+/// `macro_service_urls`: `document_storage_service_url`, `sync_service_url`,
+/// `email_service_url`, and `lexical_service_url`.
+///
+/// The provided [`Config`] must also contain values sourced from the required
+/// environment variables: `INTERNAL_API_SECRET_KEY`, `DOCUMENT_STORAGE_BUCKET`,
+/// `DOCX_DOCUMENT_UPLOAD_BUCKET`, `EMAIL_SCHEDULED_QUEUE`,
/// `DOCUMENT_STORAGE_SERVICE_CLOUDFRONT_DISTRIBUTION_URL`,
-/// `DOCUMENT_STORAGE_SERVICE_CLOUDFRONT_SIGNER_PUBLIC_KEY_ID`,
-/// `DOCUMENT_STORAGE_SERVICE_CLOUDFRONT_SIGNER_PRIVATE_KEY_SECRET_NAME`
+/// `DOCUMENT_STORAGE_SERVICE_CLOUDFRONT_SIGNER_PUBLIC_KEY_ID`, and
+/// `DOCUMENT_STORAGE_SERVICE_CLOUDFRONT_SIGNER_PRIVATE_KEY_SECRET_NAME`.
+///
+/// This function reads the provided [`Config`] and initializes the clients needed to
+/// build the [`ToolServiceContext`].
#[tracing::instrument(skip(pool, config), err)]
pub async fn build_tool_service_context(
pool: sqlx::PgPool,
diff --git a/rust/cloud-storage/notification/src/inbound/http/preferences.rs b/rust/cloud-storage/notification/src/inbound/http/preferences.rs
index 80b9706133..7cd02d64d5 100644
--- a/rust/cloud-storage/notification/src/inbound/http/preferences.rs
+++ b/rust/cloud-storage/notification/src/inbound/http/preferences.rs
@@ -8,8 +8,7 @@ use axum::{
};
use cowlike::CowLike;
use decode_jwt::DecodedJwt;
-use macro_env::Environment;
-use macro_service_urls::EnvExtMacroServiceUrls;
+use macro_service_urls::NotificationServiceUrl;
use macro_user_id::user_id::MacroUserIdStr;
use model_error_response::ErrorResponse;
use serde::{Deserialize, Serialize};
@@ -118,8 +117,20 @@ pub async fn presigned_disable_notification_type<S: NotificationReader>(
Query(params): Query<PresignedQueryParams>,
original_uri: OriginalUri,
) -> Result<Html<String>, (StatusCode, Html<String>)> {
- let env = Environment::new_or_prod();
- let notification_service_url = env.notification_service();
+ let notification_service_url = NotificationServiceUrl::new().map_err(|err| {
+ tracing::error!(error=?err, "failed to resolve notification service URL");
+ (
+ StatusCode::INTERNAL_SERVER_ERROR,
+ Html("Invalid link".to_string()),
+ )
+ })?;
+ let notification_service_url = notification_service_url.parse_url().map_err(|err| {
+ tracing::error!(error=?err, "failed to parse notification service URL");
+ (
+ StatusCode::INTERNAL_SERVER_ERROR,
+ Html("Invalid link".to_string()),
+ )
+ })?;
let to_verify = notification_service_url.join(
original_uri
.path_and_query()
diff --git a/rust/cloud-storage/notification_service/Cargo.toml b/rust/cloud-storage/notification_service/Cargo.toml
index 271ee0adcc..4be390bced 100644
--- a/rust/cloud-storage/notification_service/Cargo.toml
+++ b/rust/cloud-storage/notification_service/Cargo.toml
@@ -75,5 +75,7 @@ utoipa = { workspace = true, features = ["chrono"] }
utoipa-swagger-ui = { workspace = true }
uuid = { workspace = true }
+macro_service_urls = { path = "../macro_service_urls" }
+
[dev-dependencies]
macro_auth = { path = "../macro_auth", features = ["testing"] }
diff --git a/rust/cloud-storage/notification_service/src/config.rs b/rust/cloud-storage/notification_service/src/config.rs
index 69a0fc9969..40e8fc8ef2 100644
--- a/rust/cloud-storage/notification_service/src/config.rs
+++ b/rust/cloud-storage/notification_service/src/config.rs
@@ -10,7 +10,6 @@ env_var!(
pub(super) struct Vars {
pub(crate) NotificationQueue,
pub(crate) NotificationIngressQueue,
- pub(crate) ConnectionGatewayUrl,
pub(crate) RedisUri,
pub(crate) AppleBundleId
}
diff --git a/rust/cloud-storage/notification_service/src/main.rs b/rust/cloud-storage/notification_service/src/main.rs
index e27d3abea0..26860de8de 100644
--- a/rust/cloud-storage/notification_service/src/main.rs
+++ b/rust/cloud-storage/notification_service/src/main.rs
@@ -19,6 +19,7 @@ use macro_auth::middleware::decode_jwt::JwtValidationArgs;
use macro_entrypoint::MacroEntrypoint;
use macro_env::Environment;
use macro_middleware::auth::internal_access::InternalApiSecretKey;
+use macro_service_urls::ConnectionGatewayUrl;
use secretsmanager_client::SecretManager;
use sha2::Sha256;
use sqlx::postgres::PgPoolOptions;
@@ -73,6 +74,7 @@ pub async fn main() -> anyhow::Result<()> {
.await?;
let vars = config::Vars::new()?;
+ let connection_gateway_url = ConnectionGatewayUrl::new()?.to_string();
let hmac_key = Hmac::<Sha256>::new_from_slice(unsubscribe_hmac_secret.as_ref().as_bytes())
.expect("HMAC accepts any key size");
@@ -152,12 +154,12 @@ pub async fn main() -> anyhow::Result<()> {
};
let reader_realtime_adapter = WebSocketGatewayAdapter::new(ConnectionGatewayClient::new(
internal_secret_key.as_ref().to_string(),
- vars.connection_gateway_url.as_ref().to_string(),
+ connection_gateway_url.clone(),
));
let notification_events_realtime_adapter =
WebSocketGatewayAdapter::new(ConnectionGatewayClient::new(
internal_secret_key.as_ref().to_string(),
- vars.connection_gateway_url.as_ref().to_string(),
+ connection_gateway_url.clone(),
));
let notification_events_receiver = PgNotificationEventsReceiver::new(db.clone());
let mut notification_events_listener = NotificationEventsListener::new(
@@ -189,7 +191,7 @@ pub async fn main() -> anyhow::Result<()> {
let websocket_adapter = WebSocketGatewayAdapter::new(ConnectionGatewayClient::new(
internal_secret_key.as_ref().to_string(),
- vars.connection_gateway_url.as_ref().to_string(),
+ connection_gateway_url,
));
let mobile_adapter = MobilePushAdapter {
diff --git a/rust/cloud-storage/scheduled_action/Cargo.toml b/rust/cloud-storage/scheduled_action/Cargo.toml
index 7ab0b60082..28f4e122ce 100644
--- a/rust/cloud-storage/scheduled_action/Cargo.toml
+++ b/rust/cloud-storage/scheduled_action/Cargo.toml
@@ -57,3 +57,5 @@ macro_middleware = { path = "../macro_middleware", default-features = false, fea
] }
secretsmanager_client = { path = "../secretsmanager_client" }
aws-sdk-secretsmanager = { workspace = true }
+
+macro_service_urls = { path = "../macro_service_urls" }
diff --git a/rust/cloud-storage/scheduled_action/src/bins/service.rs b/rust/cloud-storage/scheduled_action/src/bins/service.rs
index 2bb52ef422..3f569d2b62 100644
--- a/rust/cloud-storage/scheduled_action/src/bins/service.rs
+++ b/rust/cloud-storage/scheduled_action/src/bins/service.rs
@@ -10,6 +10,7 @@ use macro_entrypoint::MacroEntrypoint;
use macro_env::Environment;
use macro_env_var::env_var;
use macro_middleware::auth::internal_access::InternalApiSecretKey;
+use macro_service_urls::ConnectionGatewayUrl;
use notification::domain::service::SqsNotificationIngress;
use notification::outbound::queue::SqsQueue;
use scheduled_action::domain::ports::ScheduledActionDispatcher;
@@ -31,7 +32,6 @@ env_var! {
Port,
DatabaseUrl,
NotificationQueue,
- ConnectionGatewayUrl,
}
}
@@ -69,7 +69,7 @@ async fn main() -> Result<()> {
let conn_gateway_client = Arc::new(ConnectionGatewayClient::new(
internal_api_secret.as_ref().to_string(),
- env.connection_gateway_url.as_ref().to_string(),
+ ConnectionGatewayUrl::new()?.to_string(),
));
let live_updates = Arc::new(ConnGatewayLiveUpdates::new(Arc::clone(
&conn_gateway_client,
diff --git a/rust/cloud-storage/search_processing_service/Cargo.toml b/rust/cloud-storage/search_processing_service/Cargo.toml
index 38421a31cb..445363f446 100644
--- a/rust/cloud-storage/search_processing_service/Cargo.toml
+++ b/rust/cloud-storage/search_processing_service/Cargo.toml
@@ -70,3 +70,5 @@ tracing = { workspace = true }
utoipa = { workspace = true }
utoipa-swagger-ui = { workspace = true }
uuid = { workspace = true }
+
+macro_service_urls = { path = "../macro_service_urls" }
diff --git a/rust/cloud-storage/search_processing_service/src/config.rs b/rust/cloud-storage/search_processing_service/src/config.rs
index 2867b091ac..8870a362e1 100644
--- a/rust/cloud-storage/search_processing_service/src/config.rs
+++ b/rust/cloud-storage/search_processing_service/src/config.rs
@@ -1,5 +1,6 @@
use anyhow::Context;
pub use macro_env::Environment;
+use macro_service_urls::LexicalServiceUrl;
/// Per-entity DB page sizes used by the backfill source adapters. Tunable at
/// runtime via the corresponding `BACKFILL_*_PAGE_SIZE` env vars.
@@ -130,8 +131,7 @@ impl Config {
.parse::<u8>()
.unwrap();
- let lexical_service_url =
- std::env::var("LEXICAL_SERVICE_URL").context("LEXICAL_SERVICE_URL must be provided")?;
+ let lexical_service_url = LexicalServiceUrl::new()?.to_string();
let backfill_page_sizes = BackfillPageSizes {
calls: parse_page_size("BACKFILL_CALLS_PAGE_SIZE", DEFAULT_CALLS_PAGE)?,
diff --git a/rust/cloud-storage/search_upload_handler/Cargo.toml b/rust/cloud-storage/search_upload_handler/Cargo.toml
index 32646b46b0..43417eb5d9 100644
--- a/rust/cloud-storage/search_upload_handler/Cargo.toml
+++ b/rust/cloud-storage/search_upload_handler/Cargo.toml
@@ -19,3 +19,5 @@ sqs_client = { path = "../sqs_client", default-features = false, features = [
tokio = { workspace = true }
tracing = { workspace = true }
+
+macro_service_urls = { path = "../macro_service_urls" }
diff --git a/rust/cloud-storage/search_upload_handler/src/main.rs b/rust/cloud-storage/search_upload_handler/src/main.rs
index 6d94f582d8..47eb83b2c3 100644
--- a/rust/cloud-storage/search_upload_handler/src/main.rs
+++ b/rust/cloud-storage/search_upload_handler/src/main.rs
@@ -4,6 +4,7 @@ use document_storage_service_client::DocumentStorageServiceClient;
use handler::handler;
use lambda_runtime::{Error, LambdaEvent, run, service_fn, tracing};
use macro_entrypoint::MacroEntrypoint;
+use macro_service_urls::DocumentStorageServiceUrl;
use std::sync::Arc;
mod handler;
@@ -17,8 +18,7 @@ async fn main() -> Result<(), Error> {
let search_event_queue =
std::env::var("SEARCH_EVENT_QUEUE").context("SEARCH_EVENT_QUEUE must be provided")?;
- let dss_url = std::env::var("DOCUMENT_STORAGE_SERVICE_URL")
- .context("DOCUMENT_STORAGE_SERVICE_URL 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")?;
diff --git a/rust/cloud-storage/static_file_service/Cargo.toml b/rust/cloud-storage/static_file_service/Cargo.toml
index 88a363fa89..4f5b7c07d7 100644
--- a/rust/cloud-storage/static_file_service/Cargo.toml
+++ b/rust/cloud-storage/static_file_service/Cargo.toml
@@ -50,3 +50,5 @@ tracing-tree = { workspace = true }
utoipa = { workspace = true }
utoipa-swagger-ui = { workspace = true, features = ["axum"] }
uuid.workspace = true
+
+macro_service_urls = { path = "../macro_service_urls" }
diff --git a/rust/cloud-storage/static_file_service/src/config.rs b/rust/cloud-storage/static_file_service/src/config.rs
index 080bf34d21..900b9daa36 100644
--- a/rust/cloud-storage/static_file_service/src/config.rs
+++ b/rust/cloud-storage/static_file_service/src/config.rs
@@ -1,5 +1,6 @@
use anyhow::Context;
pub use macro_env::Environment;
+use macro_service_urls::StaticFileServiceUrl;
#[derive(Debug, Clone)]
pub struct Config {
@@ -32,8 +33,7 @@ impl Config {
let storage_bucket_name = std::env::var("STATIC_STORAGE_BUCKET")
.context("STATIC_STORAGE_BUCKET must be provided")?;
- let service_url = std::env::var("STATIC_FILE_SERVICE_URL")
- .context("STATIC_FILE_SERVICE_URL must be provided")?;
+ 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")?;
diff --git a/rust/cloud-storage/static_file_service_client/Cargo.toml b/rust/cloud-storage/static_file_service_client/Cargo.toml
index d4959907d3..dfb34cf5f7 100644
--- a/rust/cloud-storage/static_file_service_client/Cargo.toml
+++ b/rust/cloud-storage/static_file_service_client/Cargo.toml
@@ -14,4 +14,5 @@ serde_json = { workspace = true }
tracing = { workspace = true }
[dev-dependencies]
+macro_service_urls = { path = "../macro_service_urls" }
tokio = { workspace = true }
diff --git a/rust/cloud-storage/static_file_service_client/examples/delete_file.rs b/rust/cloud-storage/static_file_service_client/examples/delete_file.rs
index a4c73ba0d0..2a0e4a1913 100644
--- a/rust/cloud-storage/static_file_service_client/examples/delete_file.rs
+++ b/rust/cloud-storage/static_file_service_client/examples/delete_file.rs
@@ -1,3 +1,4 @@
+use macro_service_urls::StaticFileServiceUrl;
use static_file_service_client::StaticFileServiceClient;
use std::env;
@@ -15,7 +16,7 @@ async fn main() -> anyhow::Result<()> {
let internal_auth_key =
env::var("INTERNAL_API_SECRET_KEY").expect("INTERNAL_API_SECRET_KEY must be set");
- let url = env::var("STATIC_FILE_SERVICE_URL").expect("STATIC_FILE_SERVICE_URL must be set");
+ let url = StaticFileServiceUrl::new()?.to_string();
let client = StaticFileServiceClient::new(internal_auth_key, url);
client.delete_file(file_id).await?;
Ok(())
diff --git a/rust/cloud-storage/static_file_service_client/examples/put_file.rs b/rust/cloud-storage/static_file_service_client/examples/put_file.rs
index 4acd13304d..98d0fbd6c0 100644
--- a/rust/cloud-storage/static_file_service_client/examples/put_file.rs
+++ b/rust/cloud-storage/static_file_service_client/examples/put_file.rs
@@ -1,3 +1,4 @@
+use macro_service_urls::StaticFileServiceUrl;
use static_file_service_client::StaticFileServiceClient;
use std::env;
@@ -5,7 +6,7 @@ use std::env;
async fn main() -> anyhow::Result<()> {
let internal_auth_key =
env::var("INTERNAL_API_SECRET_KEY").expect("INTERNAL_API_SECRET_KEY must be set");
- let url = env::var("STATIC_FILE_SERVICE_URL").expect("STATIC_FILE_SERVICE_URL must be set");
+ let url = StaticFileServiceUrl::new()?.to_string();
let client = StaticFileServiceClient::new(internal_auth_key, url);
let res = client
.put_file("http://localhost:8081/some_file.jpg")
diff --git a/rust/cloud-storage/task_dedup/Cargo.toml b/rust/cloud-storage/task_dedup/Cargo.toml
index d8f31000b5..f339556019 100644
--- a/rust/cloud-storage/task_dedup/Cargo.toml
+++ b/rust/cloud-storage/task_dedup/Cargo.toml
@@ -61,6 +61,8 @@ tokio = { workspace = true, features = [
], optional = true }
macro_env_var = { path = "../macro_env_var", optional = true }
+macro_service_urls = { path = "../macro_service_urls" }
+
[dev-dependencies]
macro_db_migrator = { path = "../macro_db_migrator" }
tokio = { workspace = true, features = ["macros", "rt-multi-thread"] }
diff --git a/rust/cloud-storage/task_dedup/src/bin/backfill_task_embeddings.rs b/rust/cloud-storage/task_dedup/src/bin/backfill_task_embeddings.rs
index 2595b1f2a4..5786a7954a 100644
--- a/rust/cloud-storage/task_dedup/src/bin/backfill_task_embeddings.rs
+++ b/rust/cloud-storage/task_dedup/src/bin/backfill_task_embeddings.rs
@@ -12,6 +12,7 @@ use embedding::{EmbeddingModel, VectorStore};
use futures::StreamExt;
use lexical_client::LexicalClient;
use macro_env_var::env_var;
+use macro_service_urls::LexicalServiceUrl;
use secretsmanager_client::{SecretManager, SecretsManager};
use task_dedup::outbound::postgres::PgTaskVectorDb;
@@ -37,13 +38,15 @@ impl Env {
}
}
- /// Hard-coded lexical-service URL for the environment.
- fn lexical_service_url(self) -> &'static str {
- match self {
- Env::Local => "http://localhost:8096",
- Env::Dev => "https://lexical-service-dev.macroverse.workers.dev",
- Env::Prod => "https://lexical-service.macroverse.workers.dev",
- }
+ /// Resolve the lexical-service URL for the environment.
+ fn lexical_service_url(self) -> Result<String> {
+ let environment = match self {
+ Env::Local => macro_service_urls::macro_env::Environment::Local,
+ Env::Dev => macro_service_urls::macro_env::Environment::Develop,
+ Env::Prod => macro_service_urls::macro_env::Environment::Production,
+ };
+
+ Ok(LexicalServiceUrl::new_for_environment(environment)?.to_string())
}
}
@@ -132,7 +135,6 @@ fn confirm(s: &str) -> Result<()> {
env_var! {
struct Vars {
DatabaseUrl,
- LexicalServiceUrl,
InternalApiSecretKey,
OpenaiApiKey,
}
@@ -157,9 +159,8 @@ impl ResolvedConfig {
// which isn't resolvable from the host shell, so hardcode the
// localhost URL for local runs.
database_url: "postgres://user:password@localhost:5432/macrodb".to_string(),
- // The repo `.env` ships the docker-network lexical host
- // (`http://lexical-service:8096`); use the localhost URL for local runs.
- lexical_service_url: Env::Local.lexical_service_url().to_string(),
+ // Resolve through macro_service_urls so local runs use the host-reachable URL.
+ lexical_service_url: Env::Local.lexical_service_url()?,
internal_api_secret_key: vars.internal_api_secret_key.as_ref().to_string(),
openai_api_key: vars.openai_api_key.as_ref().to_string(),
})
@@ -191,7 +192,7 @@ impl ResolvedConfig {
Ok(Self {
database_url,
- lexical_service_url: env.lexical_service_url().to_string(),
+ lexical_service_url: env.lexical_service_url()?,
internal_api_secret_key: internal_api_secret_key.as_ref().to_string(),
openai_api_key: openai_api_key.as_ref().to_string(),
})
@@ -200,7 +201,7 @@ impl ResolvedConfig {
fn print(&self) {
println!("________________________________________");
println!("DATABASE_URL: {}", masked_db_url(&self.database_url));
- println!("LEXICAL_SERVICE_URL: {}", self.lexical_service_url);
+ println!("lexical service URL: {}", self.lexical_service_url);
println!("________________________________________");
}
}
diff --git a/rust/cloud-storage/upload_extractor_lambda_handler/Cargo.toml b/rust/cloud-storage/upload_extractor_lambda_handler/Cargo.toml
index beeaf084ee..ebffcbde60 100644
--- a/rust/cloud-storage/upload_extractor_lambda_handler/Cargo.toml
+++ b/rust/cloud-storage/upload_extractor_lambda_handler/Cargo.toml
@@ -25,6 +25,7 @@ model-entity = { path = "../model-entity" }
models_bulk_upload = { path = "../models_bulk_upload" }
serde = { workspace = true }
serde_json = { workspace = true }
+macro_service_urls = { path = "../macro_service_urls" }
sha2 = { workspace = true }
sqs_client = { path = "../sqs_client" }
tempfile = "3.19.1"
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 44dd11efcf..b6fb9557a1 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_service_urls::ConnectionGatewayUrl;
use model::{
document::{FileType, FileTypeExt},
folder::{FileSystemNodeWithIds, FolderItem, S3Destination, S3DestinationMap},
@@ -581,8 +582,7 @@ async fn main() -> Result<(), Error> {
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 connection_gateway_url =
- std::env::var("CONNECTION_GATEWAY_URL").context("CONNECTION_GATEWAY_URL must be set")?;
+ let connection_gateway_url = ConnectionGatewayUrl::new()?.to_string();
let config = macro_aws_config::get_macro_aws_config().await;
let s3_client = S3Client::new(&config);