Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(sps): move to doppler (#4212)
Will Hutchinson00abc713cf61
diff --git a/infra/stacks/search-processing-service/Pulumi.dev.yaml b/infra/stacks/search-processing-service/Pulumi.dev.yamlindex 6147290457..1a38cefb17 100644--- a/infra/stacks/search-processing-service/Pulumi.dev.yaml+++ b/infra/stacks/search-processing-service/Pulumi.dev.yaml@@ -1,6 +1,2 @@config:aws:region: us-east-1- search-processing-service:database_url_key: macro-db-dev- search-processing-service:macro_db_readonly_secret_key: macro-db-readonly-dev- search-processing-service:opensearch_password_key: macro-opensearch-password-dev- search-processing-service:internal_auth_key: document-storage-service-auth-key-devdiff --git a/infra/stacks/search-processing-service/Pulumi.prod.yaml b/infra/stacks/search-processing-service/Pulumi.prod.yamlindex 0bf13c55f1..1a38cefb17 100644--- a/infra/stacks/search-processing-service/Pulumi.prod.yaml+++ b/infra/stacks/search-processing-service/Pulumi.prod.yaml@@ -1,6 +1,2 @@config:aws:region: us-east-1- search-processing-service:database_url_key: macro-db-prod- search-processing-service:macro_db_readonly_secret_key: macro-db-readonly-prod- search-processing-service:opensearch_password_key: macro-opensearch-password-prod- search-processing-service:internal_auth_key: document-storage-service-auth-key-proddiff --git a/infra/stacks/search-processing-service/index.ts b/infra/stacks/search-processing-service/index.tsindex 73cbb7980e..81603d6c3c 100644--- a/infra/stacks/search-processing-service/index.ts+++ b/infra/stacks/search-processing-service/index.ts@@ -1,13 +1,6 @@-import * as aws from '@pulumi/aws';import * as pulumi from '@pulumi/pulumi';import { DynamoDBTable } from '../../packages/resources';-import {- config,- getSearchEventQueue,- getServiceUrl,- ServiceUrl,- stack,-} from '../../packages/shared';+import { getSearchEventQueue, stack } from '../../packages/shared';import { get_coparse_api_vpc } from '../../packages/vpc';import { SearchProcessingService } from './service';@@ -19,7 +12,7 @@ const tags = {const vpc = get_coparse_api_vpc();-const { searchEventQueueName, searchEventQueueArn } = getSearchEventQueue();+const { searchEventQueueArn } = getSearchEventQueue();const cloudStorageStack = new pulumi.StackReference('cloud-storage-stack', {name: `macro-inc/document-storage/${stack}`,@@ -37,14 +30,6 @@ const documentStorageBucketArn: pulumi.Output<string> = cloudStorageStack.getOutput('documentStorageBucketArn').apply((arn) => arn as string);-const documentStorageBucketId: pulumi.Output<string> = cloudStorageStack- .getOutput('documentStorageBucketId')- .apply((id) => id as string);--const opensearchStack = new pulumi.StackReference('opensearch-stack', {- name: `macro-inc/opensearch/${stack}`,-});-const backfillJobsTable = new DynamoDBTable('search-processing-backfill-jobs', {baseName: 'search-processing-backfill-jobs',attributes: [{ name: 'id', type: 'S' }],@@ -53,44 +38,11 @@ const backfillJobsTable = new DynamoDBTable('search-processing-backfill-jobs', {tags,});-const OPENSEARCH_URL: pulumi.Output<string> = opensearchStack- .getOutput('domainEndpoint')- .apply((domainEndpoint) => `https://${domainEndpoint}`);--const OPENSEARCH_USERNAME = 'macrouser';-const OPENSEARCH_PASSWORD = config.require('opensearch_password_key');-const opensearchPasswordArn = aws.secretsmanager- .getSecretVersionOutput({- secretId: OPENSEARCH_PASSWORD,- })- .apply((secret) => secret.arn);-const BASE_NAME = 'search-processing-service';-const DATABASE_URL = config.require('database_url_key');-const databaseUrlArn: pulumi.Output<string> = aws.secretsmanager- .getSecretVersionOutput({ secretId: DATABASE_URL })- .apply((secret) => secret.arn);--const DATABASE_URL_READONLY = config.require('macro_db_readonly_secret_key');-const databaseUrlReadonlyArn: pulumi.Output<string> = aws.secretsmanager- .getSecretVersionOutput({ secretId: DATABASE_URL_READONLY })- .apply((secret) => secret.arn);--const INTERNAL_AUTH_KEY = aws.secretsmanager- .getSecretVersionOutput({- secretId: config.require(`internal_auth_key`),- })- .apply((secret) => secret.secretString);-const searchProcessingService = new SearchProcessingService(`${BASE_NAME}-${stack}`,{- secretKeyArns: [- databaseUrlArn,- databaseUrlReadonlyArn,- opensearchPasswordArn,- ],extraManagedPolicyArns: [backfillJobsTable.policy.arn],searchEventQueueArn,ecsClusterArn: cloudStorageClusterArn,@@ -103,64 +55,6 @@ const searchProcessingService = new SearchProcessingService(healthCheckPath: '/health',containerEnvVars: [{ name: 'ENVIRONMENT', value: stack },- {- name: 'RUST_LOG',- value: `search_processing_service=${- stack === 'prod' ? 'info' : 'trace'- },macro_db_client=info,sqs_worker=info,lexical_client=info`,- },- {- name: 'DATABASE_URL',- value: pulumi.interpolate`${DATABASE_URL}`,- },- {- name: 'DATABASE_URL_READONLY',- value: pulumi.interpolate`${DATABASE_URL_READONLY}`,- },- {- name: 'SEARCH_EVENT_QUEUE',- value: pulumi.interpolate`${searchEventQueueName}`,- },- {- name: 'QUEUE_MAX_MESSAGES',- value: '10', // number of messages a single worker can process at a time- },- {- name: 'QUEUE_WAIT_TIME_SECONDS',- value: '20', // increased polling duration to avoid rate limiting- },- {- name: 'OPENSEARCH_URL',- value: OPENSEARCH_URL,- },- {- name: 'OPENSEARCH_USERNAME',- value: OPENSEARCH_USERNAME,- },- {- name: 'OPENSEARCH_PASSWORD',- value: OPENSEARCH_PASSWORD,- },- {- name: 'DOCUMENT_STORAGE_BUCKET',- value: pulumi.interpolate`${documentStorageBucketId}`,- },- {- name: 'INTERNAL_API_SECRET_KEY',- value: INTERNAL_AUTH_KEY,- },- {- name: 'WORKER_COUNT',- value: '3', // 3 workers per instance- },- {- name: ServiceUrl.LEXICAL_SERVICE_URL,- value: getServiceUrl(ServiceUrl.LEXICAL_SERVICE_URL),- },- {- name: 'BACKFILL_JOBS_TABLE',- value: backfillJobsTable.table.name,- },// OpenTelemetry / Datadog tracing configuration{name: 'DD_SERVICE',diff --git a/infra/stacks/search-processing-service/service.ts b/infra/stacks/search-processing-service/service.tsindex 040e6c5f1b..494496a9b4 100644--- a/infra/stacks/search-processing-service/service.ts+++ b/infra/stacks/search-processing-service/service.ts@@ -14,8 +14,10 @@ import {BASE_DOMAIN,CLOUD_TRAIL_SNS_TOPIC_ARN,stack,+ DopplerEcsEnvironment,} from '../../packages/shared';+// NOTE: the BASE_NAME for sps does not match the pulumi project name so do not changeconst BASE_NAME = 'search-processing';const BASE_PATH = '../../../rust/cloud-storage';@@ -24,7 +26,6 @@ export const SERVICE_DOMAIN_NAME = `search-processing${}.${BASE_DOMAIN}`;type Args = {- secretKeyArns: (pulumi.Output<string> | string)[];clusterName: pulumi.Output<string> | string;ecsClusterArn: pulumi.Output<string> | string;documentStorageBucketArn: pulumi.Output<string> | string;@@ -71,7 +72,6 @@ export class SearchProcessingService extends pulumi.ComponentResource {containerEnvVars,clusterName,tags,- secretKeyArns,searchEventQueueArn,extraManagedPolicyArns = [],}: Args,@@ -82,6 +82,8 @@ export class SearchProcessingService extends pulumi.ComponentResource {this.clusterName = clusterName;+ this.domain = `https://${SERVICE_DOMAIN_NAME}`;+// roleconst docStorageBucketPolicy = new aws.iam.Policy(`${BASE_NAME}-doc-storage-policy`,@@ -104,23 +106,6 @@ export class SearchProcessingService extends pulumi.ComponentResource {},{ parent: this });- const secretsPolicy = new aws.iam.Policy(- `${BASE_NAME}-secrets-policy`,- {- policy: {- Version: '2012-10-17',- Statement: [- {- Action: ['secretsmanager:GetSecretValue'],- Resource: [...secretKeyArns],- Effect: 'Allow',- },- ],- },- tags: this.tags,- },- { parent: this }- );const sqsPolicy = new aws.iam.Policy(`${BASE_NAME}-sqs-policy`,@@ -160,7 +145,6 @@ export class SearchProcessingService extends pulumi.ComponentResource {tags: this.tags,managedPolicyArns: [docStorageBucketPolicy.arn,- secretsPolicy.arn,sqsPolicy.arn,...extraManagedPolicyArns,],@@ -209,6 +193,12 @@ export class SearchProcessingService extends pulumi.ComponentResource {this.lb = lb;this.listener = listener;+ const dopplerEcsEnvironment = new DopplerEcsEnvironment(+ pulumi.getProject(),+ { tags: this.tags },+ { parent: this }+ );+// serviceconst service = new awsx.ecs.FargateService(`${BASE_NAME}`,@@ -228,6 +218,9 @@ export class SearchProcessingService extends pulumi.ComponentResource {taskRole: {roleArn: this.role.arn,},+ executionRole: {+ roleArn: dopplerEcsEnvironment.executionRole.arn,+ },containers: {log_router: fargateLogRouterSidecarContainer,datadog_agent: datadogAgentContainer,@@ -237,7 +230,11 @@ export class SearchProcessingService extends pulumi.ComponentResource {stopTimeout: 10, // 10 seconds to force kill the taskcpu: stack === 'prod' ? 2048 : 512,memory: stack === 'prod' ? 6000 : 1024,- environment: containerEnvVars ?? [],+ environment: [+ { name: 'BASE_URL', value: this.domain },+ ...(containerEnvVars ?? []),+ ],+ secrets: [...dopplerEcsEnvironment.containerSecrets],logConfiguration: {logDriver: 'awsfirelens',options: {@@ -302,8 +299,6 @@ export class SearchProcessingService extends pulumi.ComponentResource {},{ parent: this });-- this.domain = `https://${SERVICE_DOMAIN_NAME}`;}initializeSecurityGroups({diff --git a/rust/cloud-storage/search_processing_service/src/config.rs b/rust/cloud-storage/search_processing_service/src/config.rsindex 61af1a9c08..8aa438e090 100644--- a/rust/cloud-storage/search_processing_service/src/config.rs+++ b/rust/cloud-storage/search_processing_service/src/config.rs@@ -2,7 +2,6 @@ use anyhow::Context;pub use macro_env::Environment;use macro_env_var::{env_vars, maybe_env_vars};use macro_service_urls::LexicalServiceUrl;-use secretsmanager_client::LocalOrRemoteSecret;env_vars! {pub struct DatabaseUrl;@@ -15,6 +14,8 @@ env_vars! {}maybe_env_vars! {+ #[derive(Clone)]+ pub struct DatabaseUrlReadonly;pub struct BackfillCallsPageSize;pub struct BackfillChatsPageSize;pub struct BackfillChannelsPageSize;@@ -72,16 +73,15 @@ fn parse_u64(name: &str, raw_value: Option<&str>, default: u64) -> anyhow::Resul#[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: LocalOrRemoteSecret<DatabaseUrl>,+ pub database_url: DatabaseUrl,- /// Optional connection URL (or SM secret id when `environment != Local`)+ /// Optional connection URL/// for the macrodb read-replica. When present, backfill reads run against/// the replica so they do not contend with writes on the primary; queue/// workers always read from the primary because replica lag would cause/// them to miss rows they are meant to index. When absent, backfills fall/// back to the primary.- pub database_url_readonly: Option<String>,+ pub database_url_readonly: DatabaseUrlReadonly,/// The port to listen for HTTP requests on.#[macro_config_default(8080)]@@ -105,7 +105,7 @@ pub struct Config {/// The username for the Opensearch instancepub opensearch_username: OpensearchUsername,/// The password for the Opensearch instance- pub opensearch_password: LocalOrRemoteSecret<OpensearchPassword>,+ pub opensearch_password: OpensearchPassword,/// The bucket where documents are storedpub document_storage_bucket: DocumentStorageBucket,diff --git a/rust/cloud-storage/search_processing_service/src/main.rs b/rust/cloud-storage/search_processing_service/src/main.rsindex 8049b2f9eb..e71f82635f 100644--- a/rust/cloud-storage/search_processing_service/src/main.rs+++ b/rust/cloud-storage/search_processing_service/src/main.rs@@ -3,6 +3,7 @@ use std::sync::Arc;use crate::{api::context::ApiContext,+ config::DatabaseUrlReadonly,domain::{jobs::BackfillJobs, service::BackfillOrchestrator},outbound::{publisher::SqsSearchEventPublisher, source::PgBackfillSource},process::{context::SearchProcessingContext, worker::run_search_processing_workers},@@ -14,7 +15,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};+use secretsmanager_client::LocalOrRemoteSecret;use sqlx::PgPool;use sqlx::postgres::PgPoolOptions;@@ -30,36 +31,28 @@ mod process;/// agnostic of which adapters back it.pub type BackfillServiceImpl = BackfillOrchestrator<PgBackfillSource, SqsSearchEventPublisher>;-/// Resolve a read-replica macrodb URL via [`OptionalLocalOrRemoteSecret`] and+/// Resolve a read-replica macrodb URL and/// connect a small pool. Returns `None` when the replica URL is missing,-/// blank, fails to fetch from Secrets Manager, or is unreachable. Failures+/// blank. Failures/// are intentionally warning-level rather than fatal: the readonly pool is a/// contention optimisation, not a correctness requirement (e.g. local laptop/// dev cannot reach the VPC-gated read replica).-async fn resolve_readonly_pool(- raw: Option<String>,- secrets: &secretsmanager_client::SecretsManager,-) -> Option<PgPool> {- let raw = raw.filter(|s| !s.is_empty());- let resolved = match OptionalLocalOrRemoteSecret::new_from_secret_manager(raw, secrets).await {- Ok(r) => r,- Err(e) => {- tracing::warn!(error=?e, "unable to fetch readonly db secret; backfills will use primary");- return None;- }- };- let url = resolved.as_str()?;- match PgPoolOptions::new()- .min_connections(1)- .max_connections(10)- .connect(url)- .await- {- Ok(pool) => Some(pool),- Err(e) => {- tracing::warn!(error=?e, "could not connect to readonly macrodb; backfills will use primary");- None+async fn resolve_readonly_pool(read_only_db_url: DatabaseUrlReadonly) -> Option<PgPool> {+ if let Some(url) = read_only_db_url.value() {+ match PgPoolOptions::new()+ .min_connections(1)+ .max_connections(10)+ .connect(url)+ .await+ {+ Ok(pool) => Some(pool),+ Err(e) => {+ tracing::warn!(error=?e, "could not connect to readonly macrodb; backfills will use primary");+ None+ }}+ } else {+ None}}@@ -74,20 +67,10 @@ 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 secretsmanager_client = secretsmanager_client::SecretsManager::new(- aws_sdk_secretsmanager::Client::new(&aws_config),- );-- 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 sqs_client = sqs_client::SQS::new(aws_sdk_sqs::Client::new(&aws_config)).search_event_queue(&config.search_event_queue);@@ -130,19 +113,16 @@ async fn main() -> anyhow::Result<()> {// contend with writes on the primary. Queue workers always read from the// primary because replica lag would cause them to miss rows they are// meant to index.- let backfill_db =- match resolve_readonly_pool(config.database_url_readonly.clone(), &secretsmanager_client)- .await- {- Some(pool) => {- tracing::info!("using read-replica pool for backfill reads");- pool- }- None => {- tracing::info!("backfills will read from the primary pool");- db.clone()- }- };+ let backfill_db = match resolve_readonly_pool(config.database_url_readonly.clone()).await {+ Some(pool) => {+ tracing::info!("using read-replica pool for backfill reads");+ pool+ }+ None => {+ tracing::info!("backfills will read from the primary pool");+ db.clone()+ }+ };let sqs_client = Arc::new(sqs_client);