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.

refactor(search_processing_service): move to macro_config (#4189)

Will Hutchinson84343e57b704
diff --git a/.github/workspace-dep-closures.json b/.github/workspace-dep-closures.json
index 4f8cfae0eb..c95d000f1a 100644
--- a/.github/workspace-dep-closures.json
+++ b/.github/workspace-dep-closures.json
@@ -3377,6 +3377,8 @@
"lexical_client",
"macro_auth",
"macro_aws_config",
+ "macro_config",
+ "macro_config_derive",
"macro_cors",
"macro_db_client",
"macro_entrypoint",
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lock
index a37f576549..94308c3548 100644
--- a/rust/cloud-storage/Cargo.lock
+++ b/rust/cloud-storage/Cargo.lock
@@ -10640,6 +10640,7 @@ dependencies = [
"http-body-util",
"lexical_client",
"macro_aws_config",
+ "macro_config",
"macro_cors",
"macro_db_client",
"macro_entrypoint",
diff --git a/rust/cloud-storage/search_processing_service/Cargo.toml b/rust/cloud-storage/search_processing_service/Cargo.toml
index b8b41a5c93..26138c1527 100644
--- a/rust/cloud-storage/search_processing_service/Cargo.toml
+++ b/rust/cloud-storage/search_processing_service/Cargo.toml
@@ -30,6 +30,7 @@ http-body-util = { workspace = true }
lexical_client = { path = "../lexical_client" }
macro_aws_config = { path = "../macro_aws_config", features = ["s3"] }
macro_cors = { path = "../macro_cors" }
+macro_config = { path = "../macro_config" }
macro_db_client = { path = "../macro_db_client", optional = true } # Make this optional
macro_entrypoint = { path = "../macro_entrypoint" }
macro_env = { path = "../macro_env" }
diff --git a/rust/cloud-storage/search_processing_service/src/config.rs b/rust/cloud-storage/search_processing_service/src/config.rs
index acb12f1c6f..81a0b673fc 100644
--- a/rust/cloud-storage/search_processing_service/src/config.rs
+++ b/rust/cloud-storage/search_processing_service/src/config.rs
@@ -1,30 +1,19 @@
+use std::num::NonZeroUsize;
+
use anyhow::Context;
pub use macro_env::Environment;
-use macro_env_var::{env_vars, maybe_env_vars};
+use macro_env_var::env_vars;
use macro_service_urls::LexicalServiceUrl;
+use secretsmanager_client::LocalOrRemoteSecret;
env_vars! {
- struct DatabaseUrl;
- struct SearchEventQueue;
- struct OpensearchUrl;
- struct OpensearchUsername;
- struct OpensearchPassword;
- struct DocumentStorageBucket;
- struct BackfillJobsTable;
-}
-
-maybe_env_vars! {
- struct DatabaseUrlReadonly;
- struct Port;
- struct QueueMaxMessages;
- struct QueueWaitTimeSeconds;
- struct WorkerCount;
- struct BackfillCallsPageSize;
- struct BackfillChatsPageSize;
- struct BackfillChannelsPageSize;
- struct BackfillDocumentsPageSize;
- struct BackfillEmailsPageSize;
- struct BackfillJobTtlSeconds;
+ pub struct DatabaseUrl;
+ pub struct SearchEventQueue;
+ pub struct OpensearchUrl;
+ pub struct OpensearchUsername;
+ pub struct OpensearchPassword;
+ pub struct DocumentStorageBucket;
+ pub struct BackfillJobsTable;
}
/// Per-entity DB page sizes used by the backfill source adapters. Tunable at
@@ -44,10 +33,17 @@ const DEFAULT_CHANNELS_PAGE: usize = 5000;
const DEFAULT_DOCUMENTS_PAGE: usize = 1000;
const DEFAULT_EMAILS_PAGE: usize = 1000;
+fn nonzero_page_size(value: usize) -> NonZeroUsize {
+ NonZeroUsize::new(value).expect("default backfill page size must be > 0")
+}
+
+/// The configuration parameters for the application.
+#[derive(macro_config::MacroConfig)]
+#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub struct Config {
/// The connection URL for the Postgres database this application should use.
/// For deployed applications, this is a secret stored in AWS Secrets Manager.
- pub database_url: String,
+ pub database_url: LocalOrRemoteSecret<DatabaseUrl>,
/// Optional connection URL (or SM secret id when `environment != Local`)
/// for the macrodb read-replica. When present, backfill reads run against
@@ -58,181 +54,79 @@ pub struct Config {
pub database_url_readonly: Option<String>,
/// The port to listen for HTTP requests on.
+ #[macro_config_default(8080)]
pub port: usize,
/// The search text extractor queue
- pub search_event_queue: String,
+ pub search_event_queue: SearchEventQueue,
/// The queue max messages per poll
+ #[macro_config_default(10)]
pub queue_max_messages: i32,
/// The queue wait time seconds
+ #[macro_config_default(20)]
pub queue_wait_time_seconds: i32,
/// The environment we are in
+ #[macro_config_default(Environment::new_or_prod())]
pub environment: Environment,
/// The URL for the Opensearch instance
- pub opensearch_url: String,
+ pub opensearch_url: OpensearchUrl,
/// The username for the Opensearch instance
- pub opensearch_username: String,
+ pub opensearch_username: OpensearchUsername,
/// The password for the Opensearch instance
- pub opensearch_password: String,
+ pub opensearch_password: LocalOrRemoteSecret<OpensearchPassword>,
/// The bucket where documents are stored
- pub document_storage_bucket: String,
+ pub document_storage_bucket: DocumentStorageBucket,
/// The number of workers to spawn
+ #[macro_config_default(10)]
pub worker_count: u8,
/// The URL for the Lexical service
+ #[macro_config_default(LexicalServiceUrl::unwrap_new().to_string())]
pub lexical_service_url: String,
- /// Per-entity DB page sizes for backfill adapters.
- pub backfill_page_sizes: BackfillPageSizes,
+ /// DB page size used when backfilling call records.
+ #[macro_config_default(nonzero_page_size(DEFAULT_CALLS_PAGE))]
+ pub backfill_calls_page_size: NonZeroUsize,
+ /// DB page size used when backfilling chats.
+ #[macro_config_default(nonzero_page_size(DEFAULT_CHATS_PAGE))]
+ pub backfill_chats_page_size: NonZeroUsize,
+ /// DB page size used when backfilling channels.
+ #[macro_config_default(nonzero_page_size(DEFAULT_CHANNELS_PAGE))]
+ pub backfill_channels_page_size: NonZeroUsize,
+ /// DB page size used when backfilling documents.
+ #[macro_config_default(nonzero_page_size(DEFAULT_DOCUMENTS_PAGE))]
+ pub backfill_documents_page_size: NonZeroUsize,
+ /// DB page size used when backfilling emails.
+ #[macro_config_default(nonzero_page_size(DEFAULT_EMAILS_PAGE))]
+ pub backfill_emails_page_size: NonZeroUsize,
/// DynamoDB table name backing the backfill job registry. Items carry an
/// `expires_at` epoch attribute that DynamoDB's TTL sweeps in the
/// background, so completed jobs vanish on their own.
- pub backfill_jobs_table: String,
+ pub backfill_jobs_table: BackfillJobsTable,
/// TTL applied to the `expires_at` attribute on each job record. Acts as
/// the GC mechanism — DynamoDB removes items shortly after this elapses.
+ #[macro_config_default(24 * 60 * 60)]
pub backfill_job_ttl_seconds: u64,
}
-fn parse_page_size(name: &str, raw_value: Option<String>, default: usize) -> anyhow::Result<usize> {
- match raw_value {
- Some(raw) => raw
- .parse::<usize>()
- .with_context(|| format!("{name} must be a positive integer"))
- .and_then(|n| {
- if n == 0 {
- anyhow::bail!("{name} must be > 0");
- }
- Ok(n)
- }),
- None => Ok(default),
- }
-}
-
impl Config {
pub fn from_env() -> anyhow::Result<Self> {
- let database_url = DatabaseUrl::new()
- .context("DATABASE_URL must be provided")?
- .to_string();
-
- let database_url_readonly = DatabaseUrlReadonly::new().map(|url| url.to_string());
-
- let port = Port::new()
- .map(|port| port.parse::<usize>().context("should be valid port number"))
- .transpose()?
- .unwrap_or(8080);
-
- let environment = Environment::new_or_prod();
-
- let search_event_queue = SearchEventQueue::new()
- .context("SEARCH_EVENT_QUEUE must be provided")?
- .to_string();
-
- let queue_max_messages = QueueMaxMessages::new()
- .map(|queue_max_messages| {
- queue_max_messages
- .parse::<i32>()
- .context("QUEUE_MAX_MESSAGES must be a valid i32")
- })
- .transpose()?
- .unwrap_or(10);
-
- let queue_wait_time_seconds = QueueWaitTimeSeconds::new()
- .map(|queue_wait_time_seconds| {
- queue_wait_time_seconds
- .parse::<i32>()
- .context("QUEUE_WAIT_TIME_SECONDS must be a valid i32")
- })
- .transpose()?
- .unwrap_or(20);
-
- let opensearch_url = OpensearchUrl::new()
- .context("OPENSEARCH_URL must be provided")?
- .to_string();
- let opensearch_username = OpensearchUsername::new()
- .context("OPENSEARCH_USERNAME must be provided")?
- .to_string();
- let opensearch_password = OpensearchPassword::new()
- .context("OPENSEARCH_PASSWORD must be provided")?
- .to_string();
-
- let document_storage_bucket = DocumentStorageBucket::new()
- .context("DOCUMENT_STORAGE_BUCKET must be provided")?
- .to_string();
-
- let worker_count = WorkerCount::new()
- .map(|worker_count| {
- worker_count
- .parse::<u8>()
- .context("WORKER_COUNT must be a valid u8")
- })
- .transpose()?
- .unwrap_or(10);
-
- let lexical_service_url = LexicalServiceUrl::new()?.to_string();
-
- let backfill_page_sizes = BackfillPageSizes {
- calls: parse_page_size(
- "BACKFILL_CALLS_PAGE_SIZE",
- BackfillCallsPageSize::new().map(|value| value.to_string()),
- DEFAULT_CALLS_PAGE,
- )?,
- chats: parse_page_size(
- "BACKFILL_CHATS_PAGE_SIZE",
- BackfillChatsPageSize::new().map(|value| value.to_string()),
- DEFAULT_CHATS_PAGE,
- )?,
- channels: parse_page_size(
- "BACKFILL_CHANNELS_PAGE_SIZE",
- BackfillChannelsPageSize::new().map(|value| value.to_string()),
- DEFAULT_CHANNELS_PAGE,
- )?,
- documents: parse_page_size(
- "BACKFILL_DOCUMENTS_PAGE_SIZE",
- BackfillDocumentsPageSize::new().map(|value| value.to_string()),
- DEFAULT_DOCUMENTS_PAGE,
- )?,
- emails: parse_page_size(
- "BACKFILL_EMAILS_PAGE_SIZE",
- BackfillEmailsPageSize::new().map(|value| value.to_string()),
- DEFAULT_EMAILS_PAGE,
- )?,
- };
-
- let backfill_jobs_table = BackfillJobsTable::new()
- .context("BACKFILL_JOBS_TABLE must be provided")?
- .to_string();
- let backfill_job_ttl_seconds = BackfillJobTtlSeconds::new()
- .map(|backfill_job_ttl_seconds| {
- backfill_job_ttl_seconds
- .parse::<u64>()
- .context("BACKFILL_JOB_TTL_SECONDS must be a positive integer")
- })
- .transpose()?
- .unwrap_or(24 * 60 * 60);
-
- Ok(Config {
- database_url,
- database_url_readonly,
- port,
- search_event_queue,
- queue_max_messages,
- queue_wait_time_seconds,
- environment,
- opensearch_url,
- opensearch_username,
- opensearch_password,
- document_storage_bucket,
- worker_count,
- lexical_service_url,
- backfill_page_sizes,
- backfill_jobs_table,
- backfill_job_ttl_seconds,
- })
+ macro_config::ConfigLoader::load::<Config>().context("failed to load config")
+ }
+
+ pub fn backfill_page_sizes(&self) -> BackfillPageSizes {
+ BackfillPageSizes {
+ calls: self.backfill_calls_page_size.get(),
+ chats: self.backfill_chats_page_size.get(),
+ channels: self.backfill_channels_page_size.get(),
+ documents: self.backfill_documents_page_size.get(),
+ emails: self.backfill_emails_page_size.get(),
+ }
}
}
diff --git a/rust/cloud-storage/search_processing_service/src/main.rs b/rust/cloud-storage/search_processing_service/src/main.rs
index d8f61e2198..5e4ba20203 100644
--- a/rust/cloud-storage/search_processing_service/src/main.rs
+++ b/rust/cloud-storage/search_processing_service/src/main.rs
@@ -14,7 +14,7 @@ use macro_entrypoint::MacroEntrypoint;
use macro_middleware::auth::internal_access::InternalApiSecretKey;
use opensearch_client::OpensearchClient;
use rust_embed::RustEmbed;
-use secretsmanager_client::{LocalOrRemoteSecret, OptionalLocalOrRemoteSecret, SecretManager};
+use secretsmanager_client::{LocalOrRemoteSecret, OptionalLocalOrRemoteSecret};
use sqlx::PgPool;
use sqlx::postgres::PgPoolOptions;
@@ -74,36 +74,24 @@ async fn main() -> anyhow::Result<()> {
// Parse our configuration from the environment.
let config = Config::from_env().context("expected to be able to generate config")?;
- tracing::trace!("initialized config");
let aws_config = macro_aws_config::get_macro_aws_config().await;
- let sqs_client = sqs_client::SQS::new(aws_sdk_sqs::Client::new(&aws_config))
- .search_event_queue(&config.search_event_queue);
-
- let s3_client = s3_client::S3::new(macro_aws_config::s3_client().await);
-
let secretsmanager_client = secretsmanager_client::SecretsManager::new(
aws_sdk_secretsmanager::Client::new(&aws_config),
);
- let database_url = match config.environment {
- Environment::Local => config.database_url.clone(),
- _ => secretsmanager_client
- .get_secret_value(&config.database_url)
- .await
- .context("unable to get secret")?
- .to_string(),
- };
+ let environment = config.environment;
+ let config = config
+ .resolve_remote_secrets(environment, &secretsmanager_client)
+ .await
+ .context("expected to be able to resolve config secrets")?;
+ tracing::trace!("initialized config");
- let opensearch_password = match config.environment {
- Environment::Local => config.opensearch_password.clone(),
- _ => secretsmanager_client
- .get_secret_value(&config.opensearch_password)
- .await
- .context("unable to get secret")?
- .to_string(),
- };
+ let sqs_client = sqs_client::SQS::new(aws_sdk_sqs::Client::new(&aws_config))
+ .search_event_queue(&config.search_event_queue);
+
+ let s3_client = s3_client::S3::new(macro_aws_config::s3_client().await);
let (min_connections, max_connections): (u32, u32) = match config.environment {
Environment::Production => (5, 50),
@@ -114,7 +102,7 @@ async fn main() -> anyhow::Result<()> {
let db = PgPoolOptions::new()
.min_connections(min_connections)
.max_connections(max_connections)
- .connect(&database_url)
+ .connect(config.database_url.as_ref())
.await
.context("could not connect to db")?;
@@ -125,9 +113,9 @@ async fn main() -> anyhow::Result<()> {
);
let opensearch_client = OpensearchClient::new(
- config.opensearch_url.clone(),
- config.opensearch_username.clone(),
- opensearch_password,
+ config.opensearch_url.to_string(),
+ config.opensearch_username.to_string(),
+ config.opensearch_password.as_ref().to_string(),
)
.context("unable to create opensearch client")?;
@@ -159,7 +147,7 @@ async fn main() -> anyhow::Result<()> {
let sqs_client = Arc::new(sqs_client);
let backfill_service = Arc::new(BackfillOrchestrator::new(
- PgBackfillSource::new(backfill_db, config.backfill_page_sizes),
+ PgBackfillSource::new(backfill_db, config.backfill_page_sizes()),
SqsSearchEventPublisher::new(sqs_client.clone()),
));
@@ -181,14 +169,14 @@ async fn main() -> anyhow::Result<()> {
let worker = sqs_worker::SQSWorker::new(
aws_sdk_sqs::Client::new(&aws_config),
- config.search_event_queue.clone(),
+ config.search_event_queue.to_string(),
config.queue_max_messages,
config.queue_wait_time_seconds,
);
let ctx = SearchProcessingContext {
db: db.clone(),
worker: Arc::new(worker.clone()),
- document_storage_bucket: config.document_storage_bucket.clone(),
+ document_storage_bucket: config.document_storage_bucket.to_string(),
s3_client: Arc::new(s3_client),
opensearch_client: Arc::new(opensearch_client.clone()),
lexical_client: Arc::new(lexical_client),
@@ -199,7 +187,7 @@ async fn main() -> anyhow::Result<()> {
let dynamodb_client = aws_sdk_dynamodb::Client::new(&aws_config);
let backfill_jobs = BackfillJobs::new(
dynamodb_client,
- config.backfill_jobs_table.clone(),
+ config.backfill_jobs_table.to_string(),
std::time::Duration::from_secs(config.backfill_job_ttl_seconds),
);
if matches!(config.environment, Environment::Local) {