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(doppler): email service doppler (#4299)

Will Hutchinson591e2b2733b9
diff --git a/.github/workspace-dep-closures.json b/.github/workspace-dep-closures.json
index 4ccff78433..d9414bd3cf 100644
--- a/.github/workspace-dep-closures.json
+++ b/.github/workspace-dep-closures.json
@@ -1848,6 +1848,8 @@
"last_online_tracker",
"macro_auth",
"macro_aws_config",
+ "macro_config",
+ "macro_config_derive",
"macro_cors",
"macro_db_client",
"macro_entrypoint",
diff --git a/infra/stacks/doppler-projects/index.ts b/infra/stacks/doppler-projects/index.ts
index 983f79ccbf..a62062b6c8 100644
--- a/infra/stacks/doppler-projects/index.ts
+++ b/infra/stacks/doppler-projects/index.ts
@@ -13,6 +13,7 @@ const SERVICE_NAMES = [
'connection-gateway',
'agent-schedule-service',
'mcp-server',
+ 'email-service',
];
for (const service_name of SERVICE_NAMES) {
diff --git a/infra/stacks/email-service/index.ts b/infra/stacks/email-service/index.ts
index a2c9913d80..c5d0eb19c6 100644
--- a/infra/stacks/email-service/index.ts
+++ b/infra/stacks/email-service/index.ts
@@ -8,11 +8,10 @@ import {
} from '../../packages/resources';
import {
config,
+ DopplerEcsEnvironment,
getMacroApiToken,
getMacroNotify,
getSearchEventQueue,
- getServiceUrl,
- ServiceUrl,
stack,
} from '../../packages/shared';
import { get_coparse_api_vpc } from '../../packages/vpc';
@@ -35,56 +34,8 @@ const tags = {
export const coparse_api_vpc = get_coparse_api_vpc();
const JWT_SECRET_KEY = config.require(`jwt_secret_key`);
-const fusionauthClientIdSecretKey = config.require(`fusionauth_client_id`);
-const AUDIENCE = aws.secretsmanager
- .getSecretVersionOutput({
- secretId: fusionauthClientIdSecretKey,
- })
- .apply((secret) => secret.secretString);
-const ISSUER = config.require(`fusionauth_issuer`);
-const NOTIFICATIONS_ENABLED = config.require(`notifications_enabled`);
-const USE_APOLLO_CRM_ENRICHMENT = config.require(`use_apollo_crm_enrichment`);
const APOLLO_API_KEY_SECRET_NAME = config.require(`apollo_api_key_secret_name`);
-const SENT_UNDO_DELAY_SECS = config.require(`sent_undo_delay_secs`);
-const REDIS_RATE_LIMIT_REQS = config.require(`redis_rate_limit_reqs`);
-const REDIS_RATE_LIMIT_REQS_BACKFILL = config.require(
- `redis_rate_limit_reqs_backfill`
-);
-const REDIS_RATE_LIMIT_WINDOW_SECS = config.require(
- `redis_rate_limit_window_secs`
-);
-const PRESIGNED_URL_TTL_SECS = config.require(`presigned_url_ttl_secs`);
-const BACKFILL_QUEUE_WORKERS = config.require(`backfill_queue_workers`);
-const BACKFILL_QUEUE_MAX_MESSAGES = config.require(
- `backfill_queue_max_messages`
-);
-const INBOX_SYNC_QUEUE_WORKERS = config.require(`inbox_sync_queue_workers`);
-const INBOX_SYNC_QUEUE_MAX_MESSAGES = config.require(
- `inbox_sync_queue_max_messages`
-);
-const INBOX_SYNC_RETRY_QUEUE_WORKERS = config.require(
- `inbox_sync_retry_queue_workers`
-);
-const INBOX_SYNC_RETRY_QUEUE_MAX_MESSAGES = config.require(
- `inbox_sync_retry_queue_max_messages`
-);
-const GMAIL_OPS_QUEUE_WORKERS = config.require(`gmail_ops_queue_workers`);
-const GMAIL_OPS_QUEUE_MAX_MESSAGES = config.require(
- `gmail_ops_queue_max_messages`
-);
-const GMAIL_OPS_RETRY_QUEUE_WORKERS = config.require(
- `gmail_ops_retry_queue_workers`
-);
-const GMAIL_OPS_RETRY_QUEUE_MAX_MESSAGES = config.require(
- `gmail_ops_retry_queue_max_messages`
-);
-const SFS_UPLOADER_WORKERS = config.require(`sfs_uploader_workers`);
-const gmailGcpQueue = config.require(`gmail_gcp_queue`);
-const GMAIL_GCP_QUEUE = aws.secretsmanager
- .getSecretVersionOutput({ secretId: gmailGcpQueue })
- .apply((secret) => secret.secretString);
-
const jwtSecretKeyArn: pulumi.Output<string> = aws.secretsmanager
.getSecretVersionOutput({ secretId: JWT_SECRET_KEY })
.apply((secret) => secret.arn);
@@ -102,12 +53,6 @@ const authenticationServiceInternalApiKeyArn: pulumi.Output<string> =
})
.apply((secret) => secret.arn);
-const INTERNAL_AUTH_KEY = aws.secretsmanager
- .getSecretVersionOutput({
- secretId: config.require(`internal_auth_key`),
- })
- .apply((secret) => secret.secretString);
-
const internalAuthKeyArn: pulumi.Output<string> = aws.secretsmanager
.getSecretVersionOutput({ secretId: config.require(`internal_auth_key`) })
.apply((secret) => secret.arn);
@@ -139,8 +84,7 @@ const sfsDeleteQueueName: pulumi.Output<string> = sfsDeleteLambdaStack
.getOutput('sfsDeleteQueueName')
.apply((name) => name as string);
-const { notificationIngressQueueName, notificationIngressQueueArn } =
- getMacroNotify();
+const { notificationIngressQueueArn } = getMacroNotify();
const emailServiceRedis = new Redis('email-service-redis', {
vpc: coparse_api_vpc,
@@ -241,7 +185,7 @@ export const sfsUploaderQueueName = pulumi.interpolate`${sfs_uploader_queue.queu
export { sfsDeleteQueueArn, sfsDeleteQueueName };
-const { searchEventQueueName, searchEventQueueArn } = getSearchEventQueue();
+const { searchEventQueueArn } = getSearchEventQueue();
// Retrieve name of queue used Contacts Service
const contactsServiceStack: pulumi.StackReference = new pulumi.StackReference(
@@ -251,10 +195,6 @@ const contactsServiceStack: pulumi.StackReference = new pulumi.StackReference(
}
);
-const contactsQueueName: pulumi.Output<string> = contactsServiceStack
- .getOutput('contactsQueueName')
- .apply((arn) => arn as string);
-
// Get ARN to allow sending messages to contacts Queue
const contactsQueueArn: pulumi.Output<string> = contactsServiceStack
.getOutput('contactsQueueArn')
@@ -382,210 +322,10 @@ emailAttachmentBucket.attachCloudfrontPolicy({
});
const containerEnvVars = [
- {
- name: 'RUST_LOG',
- value: `email=${stack === 'prod' ? 'debug' : 'debug'},email_service=${stack === 'prod' ? 'debug' : 'debug'},entity_access=${stack === 'prod' ? 'debug' : 'debug'},pubsub_workers=${stack === 'prod' ? 'debug' : 'debug'},email_db_client=${stack === 'prod' ? 'info' : 'debug'},gmail_client=${stack === 'prod' ? 'info' : 'debug'},tower_http=info,crm=${stack === 'prod' ? 'info' : 'debug'},teams=${stack === 'prod' ? 'info' : 'debug'}`,
- },
{
name: 'ENVIRONMENT',
value: stack,
},
- {
- name: 'MACRO_DB_URL',
- value: pulumi.interpolate`${MACRO_DB_URL}`,
- },
- {
- name: 'REDIS_URI',
- value: pulumi.interpolate`redis://${emailServiceRedis.endpoint}`,
- },
- {
- name: 'LINK_MANAGER_QUEUE',
- value: linkManagerQueueName,
- },
- {
- name: 'EMAIL_SCHEDULED_QUEUE',
- value: scheduledQueueName,
- },
- {
- name: 'GMAIL_INBOX_SYNC_QUEUE',
- value: inboxSyncQueueName,
- },
- {
- name: 'GMAIL_INBOX_SYNC_RETRY_QUEUE',
- value: inboxSyncRetryQueueName,
- },
- {
- name: 'GMAIL_OPS_QUEUE',
- value: gmailOpsQueueName,
- },
- {
- name: 'GMAIL_OPS_RETRY_QUEUE',
- value: gmailOpsRetryQueueName,
- },
- {
- name: 'BACKFILL_QUEUE',
- value: backfillQueueName,
- },
- {
- name: 'SFS_UPLOADER_QUEUE',
- value: sfsUploaderQueueName,
- },
- {
- name: 'SFS_DELETE_QUEUE',
- value: sfsDeleteQueueName,
- },
- {
- name: 'GMAIL_GCP_QUEUE',
- value: pulumi.interpolate`${GMAIL_GCP_QUEUE}`,
- },
- {
- name: 'NOTIFICATION_QUEUE',
- value: pulumi.interpolate`${notificationIngressQueueName}`,
- },
- {
- name: 'JWT_SECRET_KEY',
- value: pulumi.interpolate`${JWT_SECRET_KEY}`,
- },
- {
- name: 'AUDIENCE',
- value: pulumi.interpolate`${AUDIENCE}`,
- },
- {
- name: 'ISSUER',
- value: pulumi.interpolate`${ISSUER}`,
- },
- {
- name: 'INTERNAL_API_SECRET_KEY',
- value: pulumi.interpolate`${INTERNAL_AUTH_KEY}`,
- },
- {
- name: ServiceUrl.AUTHENTICATION_SERVICE_URL,
- value: getServiceUrl(ServiceUrl.AUTHENTICATION_SERVICE_URL),
- },
- {
- name: 'AUTHENTICATION_SERVICE_SECRET_KEY',
- value: pulumi.interpolate`${AUTHENTICATION_SERVICE_INTERNAL_API_KEY}`,
- },
- {
- name: ServiceUrl.STATIC_FILE_SERVICE_URL,
- value: getServiceUrl(ServiceUrl.STATIC_FILE_SERVICE_URL),
- },
- {
- name: ServiceUrl.DOCUMENT_STORAGE_SERVICE_URL,
- value: getServiceUrl(ServiceUrl.DOCUMENT_STORAGE_SERVICE_URL),
- },
- {
- name: ServiceUrl.CONNECTION_GATEWAY_URL,
- value: getServiceUrl(ServiceUrl.CONNECTION_GATEWAY_URL),
- },
- {
- name: 'NOTIFICATIONS_ENABLED',
- value: pulumi.interpolate`${NOTIFICATIONS_ENABLED}`,
- },
- {
- name: 'USE_APOLLO_CRM_ENRICHMENT',
- value: pulumi.interpolate`${USE_APOLLO_CRM_ENRICHMENT}`,
- },
- {
- name: 'APOLLO_API_KEY',
- value: pulumi.interpolate`${APOLLO_API_KEY_SECRET_NAME}`,
- },
- {
- name: 'SEARCH_EVENT_QUEUE',
- value: pulumi.interpolate`${searchEventQueueName}`,
- },
- {
- name: 'SENT_UNDO_DELAY_SECS',
- value: pulumi.interpolate`${SENT_UNDO_DELAY_SECS}`,
- },
- {
- name: 'REDIS_RATE_LIMIT_REQS',
- value: pulumi.interpolate`${REDIS_RATE_LIMIT_REQS}`,
- },
- {
- name: 'REDIS_RATE_LIMIT_REQS_BACKFILL',
- value: pulumi.interpolate`${REDIS_RATE_LIMIT_REQS_BACKFILL}`,
- },
- {
- name: 'REDIS_RATE_LIMIT_WINDOW_SECS',
- value: pulumi.interpolate`${REDIS_RATE_LIMIT_WINDOW_SECS}`,
- },
- {
- name: 'BACKFILL_QUEUE_WORKERS',
- value: pulumi.interpolate`${BACKFILL_QUEUE_WORKERS}`,
- },
- {
- name: 'BACKFILL_QUEUE_MAX_MESSAGES',
- value: pulumi.interpolate`${BACKFILL_QUEUE_MAX_MESSAGES}`,
- },
- {
- name: 'INBOX_SYNC_QUEUE_WORKERS',
- value: pulumi.interpolate`${INBOX_SYNC_QUEUE_WORKERS}`,
- },
- {
- name: 'INBOX_SYNC_QUEUE_MAX_MESSAGES',
- value: pulumi.interpolate`${INBOX_SYNC_QUEUE_MAX_MESSAGES}`,
- },
- {
- name: 'INBOX_SYNC_RETRY_QUEUE_WORKERS',
- value: pulumi.interpolate`${INBOX_SYNC_RETRY_QUEUE_WORKERS}`,
- },
- {
- name: 'INBOX_SYNC_RETRY_QUEUE_MAX_MESSAGES',
- value: pulumi.interpolate`${INBOX_SYNC_RETRY_QUEUE_MAX_MESSAGES}`,
- },
- {
- name: 'GMAIL_OPS_QUEUE_WORKERS',
- value: pulumi.interpolate`${GMAIL_OPS_QUEUE_WORKERS}`,
- },
- {
- name: 'GMAIL_OPS_QUEUE_MAX_MESSAGES',
- value: pulumi.interpolate`${GMAIL_OPS_QUEUE_MAX_MESSAGES}`,
- },
- {
- name: 'GMAIL_OPS_RETRY_QUEUE_WORKERS',
- value: pulumi.interpolate`${GMAIL_OPS_RETRY_QUEUE_WORKERS}`,
- },
- {
- name: 'GMAIL_OPS_RETRY_QUEUE_MAX_MESSAGES',
- value: pulumi.interpolate`${GMAIL_OPS_RETRY_QUEUE_MAX_MESSAGES}`,
- },
- {
- name: 'SFS_UPLOADER_WORKERS',
- value: pulumi.interpolate`${SFS_UPLOADER_WORKERS}`,
- },
- {
- name: 'MACRO_API_TOKEN_ISSUER',
- value: pulumi.interpolate`${MACRO_API_TOKENS.macroApiTokenIssuer}`,
- },
- {
- name: 'MACRO_API_TOKEN_PUBLIC_KEY',
- value: pulumi.interpolate`${MACRO_API_TOKENS.macroApiTokenPublicKey}`,
- },
- {
- name: 'EMAIL_SERVICE_PRESIGNED_URL_TTL_SECS',
- value: pulumi.interpolate`${PRESIGNED_URL_TTL_SECS}`,
- },
- {
- name: 'EMAIL_SERVICE_CLOUDFRONT_SIGNER_PRIVATE_KEY',
- value: pulumi.interpolate`${CLOUDFRONT_PRIVATE_KEY}`,
- },
- {
- name: 'CONTACTS_QUEUE',
- value: pulumi.interpolate`${contactsQueueName}`,
- },
- {
- name: 'ATTACHMENT_BUCKET',
- value: emailAttachmentBucket.bucket.id,
- },
- {
- name: 'EMAIL_SERVICE_CLOUDFRONT_DISTRIBUTION_URL',
- value: pulumi.interpolate`${cloudfrontDistribution.domain}`,
- },
- {
- name: 'EMAIL_SERVICE_CLOUDFRONT_SIGNER_PUBLIC_KEY_ID',
- value: pulumi.interpolate`${cloudfrontDistribution.publicKey.id}`,
- },
// OpenTelemetry / Datadog tracing configuration
{
name: 'DD_SERVICE',
@@ -597,6 +337,10 @@ const containerEnvVars = [
},
];
+const dopplerEcsEnvironment = new DopplerEcsEnvironment(pulumi.getProject(), {
+ tags,
+});
+
const emailService = new EmailService('email-service', {
vpc: coparse_api_vpc,
tags,
@@ -608,6 +352,7 @@ const emailService = new EmailService('email-service', {
healthCheckPath: '/health',
platform: { family: 'linux', architecture: 'amd64' },
containerEnvVars,
+ dopplerEcsEnvironment,
});
export const emailServiceUrl = pulumi.interpolate`${emailService.domain}`;
@@ -620,6 +365,7 @@ new EmailPubSubWorkers('email-pubsub-workers', {
role: emailServiceRole,
platform: { family: 'linux', architecture: 'amd64' },
containerEnvVars,
+ dopplerEcsEnvironment,
});
const DELETE_UNUSED_AFTER_DAYS = config.require(`delete_unused_after_days`);
diff --git a/infra/stacks/email-service/pubsub_workers.ts b/infra/stacks/email-service/pubsub_workers.ts
index bea5cf54bd..8641684eb5 100644
--- a/infra/stacks/email-service/pubsub_workers.ts
+++ b/infra/stacks/email-service/pubsub_workers.ts
@@ -9,7 +9,11 @@ import {
fargateLogRouterSidecarContainer,
} from '../../packages/resources';
import { EcrImage } from '../../packages/service';
-import { CLOUD_TRAIL_SNS_TOPIC_ARN, stack } from '../../packages/shared';
+import {
+ CLOUD_TRAIL_SNS_TOPIC_ARN,
+ type DopplerEcsEnvironment,
+ stack,
+} from '../../packages/shared';
const BASE_NAME = 'email-service-pubsub-workers';
const BASE_PATH = '../../../rust/cloud-storage';
@@ -26,6 +30,7 @@ type Args = {
platform: { family: string; architecture: 'amd64' | 'arm64' };
containerEnvVars: { name: string; value: pulumi.Output<string> | string }[];
tags: { [key: string]: string };
+ dopplerEcsEnvironment: DopplerEcsEnvironment;
};
export class EmailPubSubWorkers extends pulumi.ComponentResource {
@@ -45,6 +50,7 @@ export class EmailPubSubWorkers extends pulumi.ComponentResource {
platform,
containerEnvVars,
clusterName,
+ dopplerEcsEnvironment,
tags,
}: Args,
opts?: pulumi.ComponentResourceOptions
@@ -98,6 +104,9 @@ export class EmailPubSubWorkers extends pulumi.ComponentResource {
taskRole: {
roleArn: this.role.arn,
},
+ executionRole: {
+ roleArn: dopplerEcsEnvironment.executionRole.arn,
+ },
containers: {
log_router: fargateLogRouterSidecarContainer,
datadog_agent: datadogAgentContainer,
@@ -108,6 +117,7 @@ export class EmailPubSubWorkers extends pulumi.ComponentResource {
cpu: stack === 'prod' ? 2048 : 1024,
memory: stack === 'prod' ? 3742 : 1742, // 2048 minimum - 256 for datadog - 50 for log_router
environment: [...containerEnvVars],
+ secrets: [...dopplerEcsEnvironment.containerSecrets],
logConfiguration: {
logDriver: 'awsfirelens',
options: {
diff --git a/infra/stacks/email-service/service.ts b/infra/stacks/email-service/service.ts
index 72f4ac9a24..ff97febbbf 100644
--- a/infra/stacks/email-service/service.ts
+++ b/infra/stacks/email-service/service.ts
@@ -13,6 +13,7 @@ import { EcrImage } from '../../packages/service';
import {
BASE_DOMAIN,
CLOUD_TRAIL_SNS_TOPIC_ARN,
+ type DopplerEcsEnvironment,
stack,
} from '../../packages/shared';
@@ -38,6 +39,7 @@ type Args = {
containerEnvVars: { name: string; value: pulumi.Output<string> | string }[];
healthCheckPath: string;
tags: { [key: string]: string };
+ dopplerEcsEnvironment: DopplerEcsEnvironment;
};
export class EmailService extends pulumi.ComponentResource {
@@ -65,6 +67,7 @@ export class EmailService extends pulumi.ComponentResource {
isPrivate,
containerEnvVars,
clusterName,
+ dopplerEcsEnvironment,
tags,
}: Args,
opts?: pulumi.ComponentResourceOptions
@@ -135,6 +138,9 @@ export class EmailService extends pulumi.ComponentResource {
taskRole: {
roleArn: this.role.arn,
},
+ executionRole: {
+ roleArn: dopplerEcsEnvironment.executionRole.arn,
+ },
containers: {
log_router: fargateLogRouterSidecarContainer,
datadog_agent: datadogAgentContainer,
@@ -145,6 +151,7 @@ export class EmailService extends pulumi.ComponentResource {
cpu: stack === 'prod' ? 1024 : 256,
memory: stack === 'prod' ? 4096 : 717,
environment: [...containerEnvVars],
+ secrets: [...dopplerEcsEnvironment.containerSecrets],
logConfiguration: {
logDriver: 'awsfirelens',
options: {
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lock
index d0a6048d16..f53941e833 100644
--- a/rust/cloud-storage/Cargo.lock
+++ b/rust/cloud-storage/Cargo.lock
@@ -4317,6 +4317,7 @@ dependencies = [
"crm",
"document_storage_service_client",
"doppleganger",
+ "doppler-config",
"ego-tree",
"email",
"email_db_client",
@@ -4334,6 +4335,7 @@ dependencies = [
"lol_html",
"macro_auth",
"macro_aws_config",
+ "macro_config",
"macro_cors",
"macro_db_client",
"macro_entrypoint",
diff --git a/rust/cloud-storage/email_service/Cargo.toml b/rust/cloud-storage/email_service/Cargo.toml
index 9ae66bfe86..2ddcff7eb6 100644
--- a/rust/cloud-storage/email_service/Cargo.toml
+++ b/rust/cloud-storage/email_service/Cargo.toml
@@ -45,6 +45,10 @@ path = "src/bin/reverse_sfs_mappings/reverse_sfs_mappings.rs"
name = "email_service_openapi"
path = "src/openapi.rs"
+[[bin]]
+name = "email_service_doppler_config"
+path = "src/doppler_config.rs"
+
[features]
attachment_upload = []
connection_gateway = []
@@ -82,6 +86,7 @@ crm = { path = "../crm" }
unfurl = { path = "../unfurl", features = ["outbound"] }
document_storage_service_client = { path = "../document_storage_service_client" }
doppleganger = { workspace = true }
+doppler-config = { workspace = true }
ego-tree = { workspace = true }
email = { path = "../email", features = ["axum", "gmail_token", "inbound", "outbound"] }
entity_access = { path = "../entity_access", default-features = false, features = ["outbound"] }
@@ -98,6 +103,7 @@ item_filters = { path = "../item_filters" }
lol_html = "2.4.0"
macro_auth = { path = "../macro_auth" }
macro_cors = { path = "../macro_cors" }
+macro_config = { path = "../macro_config" }
macro_db_client = { path = "../macro_db_client" }
macro_entrypoint = { path = "../macro_entrypoint" }
macro_env = { path = "../macro_env" }
diff --git a/rust/cloud-storage/email_service/src/api/email/attachments/get.rs b/rust/cloud-storage/email_service/src/api/email/attachments/get.rs
index 9df516144c..f0c02a9096 100644
--- a/rust/cloud-storage/email_service/src/api/email/attachments/get.rs
+++ b/rust/cloud-storage/email_service/src/api/email/attachments/get.rs
@@ -95,7 +95,7 @@ pub async fn handler(
.into_response()
})?;
- let bucket = &ctx.config.attachment_bucket;
+ let bucket = &ctx.config.attachment_bucket.to_string();
// Create an object key that combines link_id and attachment_id
let object_key =
@@ -275,7 +275,7 @@ async fn get_presigned_url(state: &ApiContext, key: &str) -> anyhow::Result<Stri
let public_key_id = state
.config
.email_service_cloudfront_signer_public_key_id
- .clone();
+ .to_string();
let private_key = state
.config
.email_service_cloudfront_signer_private_key
@@ -283,7 +283,7 @@ async fn get_presigned_url(state: &ApiContext, key: &str) -> anyhow::Result<Stri
let url = state
.config
.email_service_cloudfront_distribution_url
- .clone();
+ .to_string();
let current_unix_timestamp = SystemTime::now()
.duration_since(UNIX_EPOCH)
diff --git a/rust/cloud-storage/email_service/src/api/email/drafts/delete.rs b/rust/cloud-storage/email_service/src/api/email/drafts/delete.rs
index 427a4f3a67..f680cf39c1 100644
--- a/rust/cloud-storage/email_service/src/api/email/drafts/delete.rs
+++ b/rust/cloud-storage/email_service/src/api/email/drafts/delete.rs
@@ -106,7 +106,7 @@ pub async fn handler(
if !draft_attachments.is_empty() {
let db = ctx.db.clone();
let s3_client = ctx.s3_client.clone();
- let bucket = ctx.config.attachment_bucket.clone();
+ let bucket = ctx.config.attachment_bucket.to_string();
let link_id = link.id;
tokio::spawn(async move {
cleanup_draft_attachments(
diff --git a/rust/cloud-storage/email_service/src/bin/pubsub_workers/pubsub_workers.rs b/rust/cloud-storage/email_service/src/bin/pubsub_workers/pubsub_workers.rs
index d19884dcce..23fc99dfed 100644
--- a/rust/cloud-storage/email_service/src/bin/pubsub_workers/pubsub_workers.rs
+++ b/rust/cloud-storage/email_service/src/bin/pubsub_workers/pubsub_workers.rs
@@ -1,14 +1,16 @@
#![recursion_limit = "256"]
use anyhow::Context;
use document_storage_service_client::DocumentStorageServiceClient;
-use email_service::config::{Config, EmailServiceCloudfrontSignerPrivateKey};
+use email_service::config::Config;
use email_service::pubsub::CrmMetadataResolver;
use macro_entrypoint::MacroEntrypoint;
use macro_env::Environment;
use macro_middleware::auth::internal_access::InternalApiSecretKey;
+use macro_service_urls::{
+ AuthServiceUrl, ConnectionGatewayUrl, DocumentStorageServiceUrl, StaticFileServiceUrl,
+};
use notification::domain::service::SqsNotificationIngress;
use notification::outbound::queue::SqsQueue;
-use secretsmanager_client::SecretManager;
use sqlx::postgres::PgPoolOptions;
use static_file_service_client::StaticFileServiceClient;
use std::sync::Arc;
@@ -28,22 +30,12 @@ async fn main() -> anyhow::Result<()> {
aws_sdk_secretsmanager::Client::new(&aws_config),
);
- let cloudfront_signer_private_key = secretsmanager_client
- .get_maybe_secret_value(env, EmailServiceCloudfrontSignerPrivateKey::new()?)
- .await?;
-
- // Parse our configuration from the environment.
- let config = Config::from_env(cloudfront_signer_private_key)
- .context("expected to be able to generate config")?;
-
- let auth_service_secret_key = match config.environment {
- Environment::Local => config.auth_service_secret_key.clone(),
- _ => secretsmanager_client
- .get_secret_value(config.auth_service_secret_key.clone())
- .await
- .context("unable to get secret")?
- .to_string(),
- };
+ // Parse our configuration from the environment, then resolve any secret-manager backed values.
+ let config = Config::from_env()
+ .context("expected to be able to generate config")?
+ .resolve_remote_secrets(env, &secretsmanager_client)
+ .await
+ .context("expected to be able to resolve config secrets")?;
let (min_connections, max_connections): (u32, u32) = match config.environment {
Environment::Production => (3, 15),
@@ -90,20 +82,20 @@ async fn main() -> anyhow::Result<()> {
let contacts_ingress = Arc::new(contacts::domain::service::SqsContactsIngress {
queue: contacts::outbound::ingress::SqsContactsQueue::new(
aws_sdk_sqs::Client::new(&gmail_queue_aws_config),
- config.contacts_queue.clone(),
+ config.contacts_queue.to_string(),
),
});
let link_manager_worker = sqs_worker::SQSWorker::new(
aws_sdk_sqs::Client::new(&gmail_queue_aws_config),
- config.link_manager_queue.clone(),
+ config.link_manager_queue.to_string(),
config.queue_max_messages,
config.queue_wait_time_seconds,
);
let scheduled_worker = sqs_worker::SQSWorker::new(
aws_sdk_sqs::Client::new(&gmail_queue_aws_config),
- config.email_scheduled_queue.clone(),
+ config.email_scheduled_queue.to_string(),
config.queue_max_messages,
config.queue_wait_time_seconds,
);
@@ -112,7 +104,7 @@ async fn main() -> anyhow::Result<()> {
.map(|_| {
sqs_worker::SQSWorker::new(
aws_sdk_sqs::Client::new(&gmail_queue_aws_config),
- config.sfs_uploader_queue.clone(),
+ config.sfs_uploader_queue.to_string(),
config.queue_max_messages,
config.queue_wait_time_seconds,
)
@@ -121,7 +113,7 @@ async fn main() -> anyhow::Result<()> {
let sfs_delete_worker = sqs_worker::SQSWorker::new(
aws_sdk_sqs::Client::new(&gmail_queue_aws_config),
- config.sfs_delete_queue.clone(),
+ config.sfs_delete_queue.to_string(),
config.queue_max_messages,
config.queue_wait_time_seconds,
);
@@ -130,7 +122,7 @@ async fn main() -> anyhow::Result<()> {
.map(|_| {
sqs_worker::SQSWorker::new(
aws_sdk_sqs::Client::new(&gmail_queue_aws_config),
- config.backfill_queue.clone(),
+ config.backfill_queue.to_string(),
config.backfill_queue_max_messages,
config.queue_wait_time_seconds,
)
@@ -141,7 +133,7 @@ async fn main() -> anyhow::Result<()> {
.map(|_| {
sqs_worker::SQSWorker::new(
aws_sdk_sqs::Client::new(&gmail_queue_aws_config),
- config.gmail_ops_queue.clone(),
+ config.gmail_ops_queue.to_string(),
config.gmail_ops_queue_max_messages,
config.queue_wait_time_seconds,
)
@@ -152,7 +144,7 @@ async fn main() -> anyhow::Result<()> {
.map(|_| {
sqs_worker::SQSWorker::new(
aws_sdk_sqs::Client::new(&gmail_queue_aws_config),
- config.gmail_ops_retry_queue.clone(),
+ config.gmail_ops_retry_queue.to_string(),
config.gmail_ops_retry_queue_max_messages,
config.queue_wait_time_seconds,
)
@@ -163,7 +155,7 @@ async fn main() -> anyhow::Result<()> {
.map(|_| {
sqs_worker::SQSWorker::new(
aws_sdk_sqs::Client::new(&gmail_queue_aws_config),
- config.gmail_inbox_sync_queue.clone(),
+ config.gmail_inbox_sync_queue.to_string(),
config.inbox_sync_queue_max_messages,
config.queue_wait_time_seconds,
)
@@ -174,7 +166,7 @@ async fn main() -> anyhow::Result<()> {
.map(|_| {
sqs_worker::SQSWorker::new(
aws_sdk_sqs::Client::new(&gmail_queue_aws_config),
- config.gmail_inbox_sync_retry_queue.clone(),
+ config.gmail_inbox_sync_retry_queue.to_string(),
config.inbox_sync_retry_queue_max_messages,
config.queue_wait_time_seconds,
)
@@ -182,13 +174,16 @@ async fn main() -> anyhow::Result<()> {
.collect::<Vec<_>>();
let auth_service_client = authentication_service_client::AuthServiceClient::new(
- auth_service_secret_key,
- config.auth_service_url.clone(),
+ config
+ .authentication_service_secret_key
+ .as_ref()
+ .to_string(),
+ AuthServiceUrl::new()?.to_string(),
);
- let gmail_client = gmail_client::GmailClient::new(config.gmail_gcp_queue.clone());
+ let gmail_client = gmail_client::GmailClient::new(config.gmail_gcp_queue.to_string());
- let redis_inner_client = redis::Client::open(config.redis_uri.as_str())
+ let redis_inner_client = redis::Client::open(config.redis_uri.as_ref())
.inspect(|client| {
client
.get_connection()
@@ -202,7 +197,7 @@ async fn main() -> anyhow::Result<()> {
let ingress_queue = SqsQueue::new(
aws_sdk_sqs::Client::new(&aws_config),
- config.notification_queue.clone(),
+ config.notification_queue.to_string(),
);
let notification_ingress_service = Arc::new(SqsNotificationIngress {
queue: ingress_queue,
@@ -219,17 +214,17 @@ async fn main() -> anyhow::Result<()> {
let sfs_client = StaticFileServiceClient::new(
internal_auth_key.as_ref().to_string(),
- config.static_file_service_url.clone(),
+ StaticFileServiceUrl::new()?.to_string(),
);
let dss_client = DocumentStorageServiceClient::new(
internal_auth_key.as_ref().to_string(),
- config.document_storage_service_url.clone(),
+ DocumentStorageServiceUrl::new()?.to_string(),
);
let connection_gateway_client = connection_gateway_client::client::ConnectionGatewayClient::new(
internal_auth_key.as_ref().to_string(),
- config.connection_gateway_url.clone(),
+ ConnectionGatewayUrl::new()?.to_string(),
);
let system_properties_service = Arc::new(SystemPropertiesServiceImpl::new(
@@ -254,27 +249,17 @@ async fn main() -> anyhow::Result<()> {
};
let metadata_resolver = if config.use_apollo_crm_enrichment {
- // Apollo key: `config.apollo_api_key` is the key itself locally, or
- // the name of the Secrets Manager secret holding it in deployed envs
- // (resolved here).
- let apollo_api_key = match config.environment {
- Environment::Local => config.apollo_api_key.clone(),
- _ => secretsmanager_client
- .get_secret_value(config.apollo_api_key.clone())
- .await
- .inspect_err(|e| tracing::error!(error=?e, "failed to load apollo api key secret"))
- .map(|k| k.to_string())
- .unwrap_or_default(),
- };
// No usable key (missing/unreadable secret, or unset locally): fall
// back to unfurl rather than running Apollo with an empty key, which
// would no-op and pollute the directory with negative-cache rows.
- if apollo_api_key.is_empty() {
+ if config.apollo_api_key.as_ref().is_empty() {
tracing::warn!("apollo api key unavailable; falling back to unfurl CRM enrichment");
build_unfurl()?
} else {
CrmMetadataResolver::Apollo(
- crm::outbound::apollo_resolver::ApolloCompanyMetadataResolver::new(apollo_api_key),
+ crm::outbound::apollo_resolver::ApolloCompanyMetadataResolver::new(
+ config.apollo_api_key.as_ref().to_string(),
+ ),
)
}
} else {
@@ -492,7 +477,7 @@ async fn main() -> anyhow::Result<()> {
let auth_service_client_scheduled = auth_service_client.clone();
let redis_client_scheduled = redis_client.clone();
let s3_client_scheduled = s3_client.clone();
- let attachment_bucket_scheduled = config.attachment_bucket.clone();
+ let attachment_bucket_scheduled = config.attachment_bucket.to_string();
// send scheduled emails
tokio::spawn(async move {
email_service::pubsub::scheduled::worker::run_worker(
diff --git a/rust/cloud-storage/email_service/src/config.rs b/rust/cloud-storage/email_service/src/config.rs
index 9e95b30ca6..15afd8dd6c 100644
--- a/rust/cloud-storage/email_service/src/config.rs
+++ b/rust/cloud-storage/email_service/src/config.rs
@@ -1,496 +1,200 @@
use anyhow::Context;
pub use macro_env::Environment;
-use macro_env_var::{env_var, env_vars, maybe_env_vars};
-use macro_service_urls::{ConnectionGatewayUrl, DocumentStorageServiceUrl, StaticFileServiceUrl};
+use macro_env_var::env_vars;
use secretsmanager_client::LocalOrRemoteSecret;
+env_vars! {
+ pub struct EmailServiceCloudfrontSignerPrivateKey;
+ pub struct MacroDbUrl;
+ pub struct RedisUri;
+ pub struct LinkManagerQueue;
+ pub struct EmailScheduledQueue;
+ pub struct GmailInboxSyncQueue;
+ pub struct GmailInboxSyncRetryQueue;
+ pub struct GmailOpsQueue;
+ pub struct GmailOpsRetryQueue;
+ pub struct SearchEventQueue;
+ pub struct GmailGcpQueue;
+ pub struct NotificationQueue;
+ pub struct BackfillQueue;
+ pub struct ContactsQueue;
+ pub struct SfsUploaderQueue;
+ pub struct SfsDeleteQueue;
+ #[derive(Debug)]
+ pub struct AttachmentBucket;
+ pub struct NotificationsEnabled;
+ pub struct AuthenticationServiceSecretKey;
+ pub struct EmailServiceCloudfrontDistributionUrl;
+ pub struct EmailServiceCloudfrontSignerPublicKeyId;
+ pub struct ApolloApiKey;
+}
+
+#[derive(macro_config::MacroConfig)]
+#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub struct Config {
/// The connection URL for the macrodb instance this application should use.
/// For deployed applications, this is a secret stored in AWS Secrets Manager.
- pub macro_db_url: String,
+ pub macro_db_url: MacroDbUrl,
/// The port to listen for HTTP requests on.
+ #[macro_config_default(8080)]
pub port: usize,
/// The Redis URI for the Redis this application should use.
- pub redis_uri: String,
+ pub redis_uri: RedisUri,
/// The SQS queue name that email_refresh_handler publishes messages to for refreshing
/// inbox sync subscriptions, and we will publish delete link messages to.
- pub link_manager_queue: String,
+ pub link_manager_queue: LinkManagerQueue,
/// The SQS queue name that email_scheduled_handler publishes messages to for sending
/// scheduled messages.
- pub email_scheduled_queue: String,
+ pub email_scheduled_queue: EmailScheduledQueue,
/// The SQS queue name we process inbox updates from.
- pub gmail_inbox_sync_queue: String,
+ pub gmail_inbox_sync_queue: GmailInboxSyncQueue,
/// The SQS queue name we process inbox update retries from. Separate from the main queue
/// to avoid backups for large inbox update operations
- pub gmail_inbox_sync_retry_queue: String,
+ pub gmail_inbox_sync_retry_queue: GmailInboxSyncRetryQueue,
/// The SQS queue name for async Gmail operations (label changes, block/unblock, etc.)
- pub gmail_ops_queue: String,
+ pub gmail_ops_queue: GmailOpsQueue,
/// The SQS queue name for retrying rate-limited Gmail operations
- pub gmail_ops_retry_queue: String,
+ pub gmail_ops_retry_queue: GmailOpsRetryQueue,
/// The SQS queue name for search event
- pub search_event_queue: String,
+ pub search_event_queue: SearchEventQueue,
/// The GCP queue name that has the subscription that hits our webhook endpoint
- pub gmail_gcp_queue: String,
+ pub gmail_gcp_queue: GmailGcpQueue,
/// The SQS queue name for notification-service
- pub notification_queue: String,
+ pub notification_queue: NotificationQueue,
/// The SQS queue name for the backfill process
- pub backfill_queue: String,
+ pub backfill_queue: BackfillQueue,
/// The SQS queue name for the sfs_uploader process
- pub sfs_uploader_queue: String,
+ pub sfs_uploader_queue: SfsUploaderQueue,
/// The SQS queue name for the sfs_delete process
- pub sfs_delete_queue: String,
+ pub sfs_delete_queue: SfsDeleteQueue,
/// The SQS queue name for contacts service
- pub contacts_queue: String,
+ pub contacts_queue: ContactsQueue,
/// The amount of time to delay processing of a sent message (undo send window) - default 10s
+ #[macro_config_default(10)]
pub sent_undo_delay_secs: u32,
/// The SQS bucket for storing attachments
- pub attachment_bucket: String,
+ pub attachment_bucket: AttachmentBucket,
/// Notification-service functionality
+ #[macro_config_default(true)]
pub notifications_enabled: bool,
/// Use Apollo.io for CRM company enrichment. When `false`, fall back
/// to the unfurl-based resolver.
+ #[macro_config_default(false)]
pub use_apollo_crm_enrichment: bool,
/// Apollo.io API key for CRM enrichment. Locally this is the key
/// itself; in deployed envs it's the name of the Secrets Manager
/// secret holding it (resolved at startup). Empty disables enrichment.
- pub apollo_api_key: String,
+ pub apollo_api_key: LocalOrRemoteSecret<ApolloApiKey>,
/// The queue max messages per poll
+ #[macro_config_default(10)]
pub queue_max_messages: i32,
/// The number of workers we spawn for backfill
+ #[macro_config_default(25)]
pub backfill_queue_workers: i32,
/// The queue max messages per poll for backfill
+ #[macro_config_default(1)]
pub backfill_queue_max_messages: i32,
/// The number of workers we spawn for gmail inbox sync
+ #[macro_config_default(10)]
pub inbox_sync_queue_workers: i32,
/// The queue max messages per poll for gmail inbox sync
+ #[macro_config_default(1)]
pub inbox_sync_queue_max_messages: i32,
/// The number of workers we spawn for gmail retry inbox sync
+ #[macro_config_default(10)]
pub inbox_sync_retry_queue_workers: i32,
/// The queue max messages per poll for gmail retry inbox sync
+ #[macro_config_default(1)]
pub inbox_sync_retry_queue_max_messages: i32,
/// The number of workers we spawn for gmail ops
+ #[macro_config_default(5)]
pub gmail_ops_queue_workers: i32,
/// The queue max messages per poll for gmail ops
+ #[macro_config_default(10)]
pub gmail_ops_queue_max_messages: i32,
/// The number of workers we spawn for gmail ops retry
+ #[macro_config_default(2)]
pub gmail_ops_retry_queue_workers: i32,
/// The queue max messages per poll for gmail ops retry
+ #[macro_config_default(10)]
pub gmail_ops_retry_queue_max_messages: i32,
/// The number of workers we spawn for sfs uploader
+ #[macro_config_default(3)]
pub sfs_uploader_workers: i32,
/// The number of requests we allow per window for backfilling. Less than redis_rate_limit_reqs
/// so we have room for normal gmail operations while backfilling is occurring
+ #[macro_config_default(13000)]
pub redis_rate_limit_reqs_backfill: u32,
/// The number of requests we allow per window.
+ #[macro_config_default(14000)]
pub redis_rate_limit_reqs: u32,
/// The size of the sliding window we use for rate limit.
+ #[macro_config_default(60)]
pub redis_rate_limit_window_secs: u32,
/// 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,
/// Auth service secret key, used for internal access
- pub auth_service_secret_key: String,
-
- /// URL for auth service
- pub auth_service_url: String,
-
- /// The static file service url
- pub static_file_service_url: String,
-
- // The DSS url
- pub document_storage_service_url: String,
-
- /// The connection gateway client url
- pub connection_gateway_url: String,
+ pub authentication_service_secret_key: LocalOrRemoteSecret<AuthenticationServiceSecretKey>,
// The URL for cloudfront
- pub email_service_cloudfront_distribution_url: String,
+ pub email_service_cloudfront_distribution_url: EmailServiceCloudfrontDistributionUrl,
// The secret for the cloudfront private key
pub email_service_cloudfront_signer_private_key:
LocalOrRemoteSecret<EmailServiceCloudfrontSignerPrivateKey>,
// The public key for cloudfront
- pub email_service_cloudfront_signer_public_key_id: String,
+ pub email_service_cloudfront_signer_public_key_id: EmailServiceCloudfrontSignerPublicKeyId,
// How long presigned urls should be valid for attachments
+ #[macro_config_default(3600)]
pub email_service_presigned_url_ttl_secs: u64,
}
-env_var! { pub struct EmailServiceCloudfrontSignerPrivateKey; }
-
-env_vars! {
- struct MacroDbUrl;
- struct RedisUri;
- struct LinkManagerQueue;
- struct EmailScheduledQueue;
- struct GmailInboxSyncQueue;
- struct GmailInboxSyncRetryQueue;
- struct GmailOpsQueue;
- struct GmailOpsRetryQueue;
- struct SearchEventQueue;
- struct GmailGcpQueue;
- struct NotificationQueue;
- struct BackfillQueue;
- struct ContactsQueue;
- struct SfsUploaderQueue;
- struct SfsDeleteQueue;
- struct AttachmentBucket;
- struct NotificationsEnabled;
- struct AuthenticationServiceUrl;
- struct AuthenticationServiceSecretKey;
- struct EmailServiceCloudfrontDistributionUrl;
- struct EmailServiceCloudfrontSignerPublicKeyId;
-}
-
-maybe_env_vars! {
- struct Port;
- struct SentUndoDelaySecs;
- struct UseApolloCrmEnrichment;
- struct ApolloApiKey;
- struct QueueMaxMessages;
- struct BackfillQueueWorkers;
- struct BackfillQueueMaxMessages;
- struct InboxSyncQueueWorkers;
- struct InboxSyncQueueMaxMessages;
- struct InboxSyncRetryQueueWorkers;
- struct InboxSyncRetryQueueMaxMessages;
- struct GmailOpsQueueWorkers;
- struct GmailOpsQueueMaxMessages;
- struct GmailOpsRetryQueueWorkers;
- struct GmailOpsRetryQueueMaxMessages;
- struct SfsUploaderWorkers;
- struct RedisRateLimitReqs;
- struct RedisRateLimitReqsBackfill;
- struct RedisRateLimitWindowSecs;
- struct QueueWaitTimeSeconds;
- struct EmailServicePresignedUrlTtlSecs;
-}
-
-fn parse_optional_env<T, V>(
- value: Option<V>,
- default: T,
- context: &'static str,
-) -> anyhow::Result<T>
-where
- T: std::str::FromStr,
- T::Err: std::error::Error + Send + Sync + 'static,
- V: AsRef<str>,
-{
- value
- .map(|value| value.as_ref().parse::<T>().context(context))
- .transpose()
- .map(|value| value.unwrap_or(default))
-}
-
impl Config {
- pub fn from_env(
- email_service_cloudfront_signer_private_key: LocalOrRemoteSecret<
- EmailServiceCloudfrontSignerPrivateKey,
- >,
- ) -> anyhow::Result<Self> {
- let database_url = MacroDbUrl::new()
- .context("MACRO_DB_URL must be provided")?
- .to_string();
-
- let port = parse_optional_env(Port::new(), 8080usize, "should be valid port number")?;
-
- let redis_uri = RedisUri::new()
- .context("REDIS_URI must be provided")?
- .to_string();
-
- let link_manager_queue = LinkManagerQueue::new()
- .context("LINK_MANAGER_QUEUE must be provided")?
- .to_string();
-
- let email_scheduled_queue = EmailScheduledQueue::new()
- .context("EMAIL_SCHEDULED_QUEUE must be provided")?
- .to_string();
-
- let gmail_inbox_sync_queue = GmailInboxSyncQueue::new()
- .context("GMAIL_INBOX_SYNC_QUEUE must be provided")?
- .to_string();
-
- let gmail_inbox_sync_retry_queue = GmailInboxSyncRetryQueue::new()
- .context("GMAIL_INBOX_SYNC_RETRY_QUEUE must be provided")?
- .to_string();
-
- let gmail_ops_queue = GmailOpsQueue::new()
- .context("GMAIL_OPS_QUEUE must be provided")?
- .to_string();
-
- let gmail_ops_retry_queue = GmailOpsRetryQueue::new()
- .context("GMAIL_OPS_RETRY_QUEUE must be provided")?
- .to_string();
-
- let search_event_queue = SearchEventQueue::new()
- .context("SEARCH_EVENT_QUEUE must be provided")?
- .to_string();
-
- let gmail_gcp_queue = GmailGcpQueue::new()
- .context("GMAIL_GCP_QUEUE must be provided")?
- .to_string();
-
- let notification_queue = NotificationQueue::new()
- .context("NOTIFICATION_QUEUE must be provided")?
- .to_string();
-
- let backfill_queue = BackfillQueue::new()
- .context("BACKFILL_QUEUE must be provided")?
- .to_string();
-
- let contacts_queue = ContactsQueue::new()
- .context("CONTACTS_QUEUE must be provided")?
- .to_string();
-
- let sfs_uploader_queue = SfsUploaderQueue::new()
- .context("SFS_UPLOADER_QUEUE must be provided")?
- .to_string();
-
- let sfs_delete_queue = SfsDeleteQueue::new()
- .context("SFS_DELETE_QUEUE must be provided")?
- .to_string();
-
- let attachment_bucket = AttachmentBucket::new()
- .context("ATTACHMENT_BUCKET must be provided")?
- .to_string();
-
- let sent_undo_delay_secs = parse_optional_env(
- SentUndoDelaySecs::new(),
- 10u32,
- "SENT_UNDO_DELAY_SECS must be a valid u32",
- )?;
-
- let notifications_enabled = NotificationsEnabled::new()
- .context("NOTIFICATIONS_ENABLED must be provided")?
- .parse::<bool>()
- .context("NOTIFICATIONS_ENABLED must be a boolean value")?;
-
- let use_apollo_crm_enrichment = parse_optional_env(
- UseApolloCrmEnrichment::new(),
- false,
- "USE_APOLLO_CRM_ENRICHMENT must be a boolean value",
- )?;
-
- let apollo_api_key = ApolloApiKey::new()
- .map(|api_key| api_key.to_string())
- .unwrap_or_default();
-
- let queue_max_messages = parse_optional_env(
- QueueMaxMessages::new(),
- 10i32,
- "QUEUE_MAX_MESSAGES must be a valid i32",
- )?;
-
- let backfill_queue_workers = parse_optional_env(
- BackfillQueueWorkers::new(),
- 25i32,
- "BACKFILL_QUEUE_WORKERS must be a valid i32",
- )?;
-
- let backfill_queue_max_messages = parse_optional_env(
- BackfillQueueMaxMessages::new(),
- 1i32,
- "BACKFILL_QUEUE_MAX_MESSAGES must be a valid i32",
- )?;
-
- let inbox_sync_queue_workers = parse_optional_env(
- InboxSyncQueueWorkers::new(),
- 10i32,
- "INBOX_SYNC_QUEUE_WORKERS must be a valid i32",
- )?;
-
- let inbox_sync_queue_max_messages = parse_optional_env(
- InboxSyncQueueMaxMessages::new(),
- 1i32,
- "INBOX_SYNC_QUEUE_MAX_MESSAGES must be a valid i32",
- )?;
-
- let inbox_sync_retry_queue_workers = parse_optional_env(
- InboxSyncRetryQueueWorkers::new(),
- 10i32,
- "INBOX_SYNC_RETRY_QUEUE_WORKERS must be a valid i32",
- )?;
-
- let inbox_sync_retry_queue_max_messages = parse_optional_env(
- InboxSyncRetryQueueMaxMessages::new(),
- 1i32,
- "INBOX_SYNC_RETRY_QUEUE_MAX_MESSAGES must be a valid i32",
- )?;
-
- let gmail_ops_queue_workers = parse_optional_env(
- GmailOpsQueueWorkers::new(),
- 5i32,
- "GMAIL_OPS_QUEUE_WORKERS must be a valid i32",
- )?;
-
- let gmail_ops_queue_max_messages = parse_optional_env(
- GmailOpsQueueMaxMessages::new(),
- 10i32,
- "GMAIL_OPS_QUEUE_MAX_MESSAGES must be a valid i32",
- )?;
-
- let gmail_ops_retry_queue_workers = parse_optional_env(
- GmailOpsRetryQueueWorkers::new(),
- 2i32,
- "GMAIL_OPS_RETRY_QUEUE_WORKERS must be a valid i32",
- )?;
-
- let gmail_ops_retry_queue_max_messages = parse_optional_env(
- GmailOpsRetryQueueMaxMessages::new(),
- 10i32,
- "GMAIL_OPS_RETRY_QUEUE_MAX_MESSAGES must be a valid i32",
- )?;
-
- let sfs_uploader_workers = parse_optional_env(
- SfsUploaderWorkers::new(),
- 3i32,
- "SFS_UPLOADER_WORKERS must be a valid i32",
- )?;
-
- let redis_rate_limit_reqs = parse_optional_env(
- RedisRateLimitReqs::new(),
- 14000u32,
- "REDIS_RATE_LIMIT_REQS must be a valid u32",
- )?;
-
- let redis_rate_limit_reqs_backfill = parse_optional_env(
- RedisRateLimitReqsBackfill::new(),
- 13000u32,
- "REDIS_RATE_LIMIT_REQS_BACKFILL must be a valid u32",
- )?;
-
- let redis_rate_limit_window_secs = parse_optional_env(
- RedisRateLimitWindowSecs::new(),
- 60u32,
- "REDIS_RATE_LIMIT_WINDOW_SECS must be a valid u32",
- )?;
-
- let queue_wait_time_seconds = parse_optional_env(
- QueueWaitTimeSeconds::new(),
- 20i32,
- "QUEUE_WAIT_TIME_SECONDS must be a valid i32",
- )?;
-
- let environment = Environment::new_or_prod();
-
- let auth_service_url = AuthenticationServiceUrl::new()
- .context("AUTHENTICATION_SERVICE_URL must be provided")?
- .to_string();
-
- let auth_service_secret_key = AuthenticationServiceSecretKey::new()
- .context("AUTHENTICATION_SERVICE_SECRET_KEY must be provided")?
- .to_string();
-
- let static_file_service_url = StaticFileServiceUrl::new()?.to_string();
-
- let connection_gateway_url = ConnectionGatewayUrl::new()?.to_string();
-
- let document_storage_service_url = DocumentStorageServiceUrl::new()?.to_string();
-
- let email_service_cloudfront_distribution_url =
- EmailServiceCloudfrontDistributionUrl::new()
- .context("EMAIL_SERVICE_CLOUDFRONT_DISTRIBUTION_URL must be provided")?
- .to_string();
-
- let email_service_cloudfront_signer_public_key_id =
- EmailServiceCloudfrontSignerPublicKeyId::new()
- .context("EMAIL_SERVICE_CLOUDFRONT_SIGNER_PUBLIC_KEY_ID must be provided")?
- .to_string();
-
- let email_service_presigned_url_ttl_secs = parse_optional_env(
- EmailServicePresignedUrlTtlSecs::new(),
- 3600u64,
- "EMAIL_SERVICE_PRESIGNED_URL_TTL_SECS must be a valid u64",
- )?;
-
- Ok(Config {
- macro_db_url: database_url,
- port,
- redis_uri,
- link_manager_queue,
- email_scheduled_queue,
- gmail_inbox_sync_queue,
- gmail_inbox_sync_retry_queue,
- gmail_ops_queue,
- gmail_ops_retry_queue,
- search_event_queue,
- gmail_gcp_queue,
- notification_queue,
- backfill_queue,
- sfs_uploader_queue,
- sfs_delete_queue,
- contacts_queue,
- attachment_bucket,
- sent_undo_delay_secs,
- notifications_enabled,
- use_apollo_crm_enrichment,
- apollo_api_key,
- queue_max_messages,
- queue_wait_time_seconds,
- backfill_queue_workers,
- backfill_queue_max_messages,
- inbox_sync_queue_workers,
- inbox_sync_queue_max_messages,
- inbox_sync_retry_queue_workers,
- inbox_sync_retry_queue_max_messages,
- gmail_ops_queue_workers,
- gmail_ops_queue_max_messages,
- gmail_ops_retry_queue_workers,
- gmail_ops_retry_queue_max_messages,
- sfs_uploader_workers,
- redis_rate_limit_reqs,
- redis_rate_limit_reqs_backfill,
- redis_rate_limit_window_secs,
- environment,
- auth_service_secret_key,
- auth_service_url,
- static_file_service_url,
- document_storage_service_url,
- connection_gateway_url,
- email_service_cloudfront_distribution_url,
- email_service_cloudfront_signer_public_key_id,
- email_service_cloudfront_signer_private_key,
- email_service_presigned_url_ttl_secs,
- })
+ pub fn from_env() -> anyhow::Result<Self> {
+ macro_config::ConfigLoader::load::<Config>().context("failed to load config")
}
}
diff --git a/rust/cloud-storage/email_service/src/doppler_config.rs b/rust/cloud-storage/email_service/src/doppler_config.rs
new file mode 100644
index 0000000000..ac63e24a9c
--- /dev/null
+++ b/rust/cloud-storage/email_service/src/doppler_config.rs
@@ -0,0 +1,31 @@
+#![allow(unused)]
+#![recursion_limit = "256"]
+
+use macro_env::Environment;
+
+mod config;
+
+const DOPPLER_PROJECT: &str = "email-service";
+
+#[tokio::main]
+async fn main() -> anyhow::Result<()> {
+ let dev = doppler_config::DopplerConfig::builder()
+ .token_from_env("DOPPLER_TOKEN")
+ .config(Environment::Develop.to_doppler_slug())
+ .project(DOPPLER_PROJECT)
+ .build()
+ .expect("able to grab doppler project");
+
+ dev.load::<config::Config>().await?;
+
+ let prd = doppler_config::DopplerConfig::builder()
+ .token_from_env("DOPPLER_TOKEN")
+ .config(Environment::Production.to_doppler_slug())
+ .project(DOPPLER_PROJECT)
+ .build()
+ .expect("able to grab doppler project");
+
+ prd.load::<config::Config>().await?;
+
+ Ok(())
+}
diff --git a/rust/cloud-storage/email_service/src/main.rs b/rust/cloud-storage/email_service/src/main.rs
index fbed8fe0c4..10e46825b2 100644
--- a/rust/cloud-storage/email_service/src/main.rs
+++ b/rust/cloud-storage/email_service/src/main.rs
@@ -10,14 +10,14 @@ use email::{
},
outbound::{EmailPgRepo, GmailTokenProviderImpl},
};
-use email_service::config::EmailServiceCloudfrontSignerPrivateKey;
use entity_access::{domain::service::EntityAccessServiceImpl, outbound::PgAccessRepository};
use frecency::{domain::services::FrecencyQueryServiceImpl, outbound::postgres::FrecencyPgStorage};
use macro_auth::middleware::decode_jwt::JwtValidationArgs;
use macro_entrypoint::MacroEntrypoint;
use macro_env::Environment;
use macro_middleware::auth::internal_access::InternalApiSecretKey;
-use secretsmanager_client::{LocalOrRemoteSecret, SecretManager};
+use macro_service_urls::{AuthServiceUrl, DocumentStorageServiceUrl, StaticFileServiceUrl};
+use secretsmanager_client::LocalOrRemoteSecret;
use sqlx::postgres::PgPoolOptions;
use static_file_service_client::StaticFileServiceClient;
use std::sync::Arc;
@@ -40,22 +40,12 @@ async fn main() -> anyhow::Result<()> {
aws_sdk_secretsmanager::Client::new(&aws_config),
);
- let cloudfront_signer_private_key = secretsmanager_client
- .get_maybe_secret_value(env, EmailServiceCloudfrontSignerPrivateKey::new()?)
- .await?;
-
- // Parse our configuration from the environment.
- let config = email_service::config::Config::from_env(cloudfront_signer_private_key)
- .context("expected to be able to generate config")?;
-
- let auth_service_secret_key = match config.environment {
- Environment::Local => config.auth_service_secret_key.clone(),
- _ => secretsmanager_client
- .get_secret_value(config.auth_service_secret_key.clone())
- .await
- .context("unable to get secret")?
- .to_string(),
- };
+ // Parse our configuration from the environment, then resolve any secret-manager backed values.
+ let config = email_service::config::Config::from_env()
+ .context("expected to be able to generate config")?
+ .resolve_remote_secrets(env, &secretsmanager_client)
+ .await
+ .context("expected to be able to resolve config secrets")?;
// limiting to max of 200 connections (12.5% of macrodb total) in prod.
let (min_connections, max_connections): (u32, u32) = match config.environment {
@@ -82,13 +72,16 @@ async fn main() -> anyhow::Result<()> {
.email_link_manager_queue(&config.link_manager_queue);
let auth_service_client = authentication_service_client::AuthServiceClient::new(
- auth_service_secret_key,
- config.auth_service_url.clone(),
+ config
+ .authentication_service_secret_key
+ .as_ref()
+ .to_string(),
+ AuthServiceUrl::new()?.to_string(),
);
- let gmail_client = gmail_client::GmailClient::new(config.gmail_gcp_queue.clone());
+ let gmail_client = gmail_client::GmailClient::new(config.gmail_gcp_queue.as_ref().to_string());
- let redis_inner_client = redis::Client::open(config.redis_uri.as_str())
+ let redis_inner_client = redis::Client::open(config.redis_uri.as_ref())
.inspect(|client| {
client
.get_connection()
@@ -111,12 +104,12 @@ async fn main() -> anyhow::Result<()> {
let sfs_client = StaticFileServiceClient::new(
internal_auth_key.as_ref().to_string(),
- config.static_file_service_url.clone(),
+ StaticFileServiceUrl::new()?.to_string(),
);
let dss_client = DocumentStorageServiceClient::new(
internal_auth_key.as_ref().to_string(),
- config.document_storage_service_url.clone(),
+ DocumentStorageServiceUrl::new()?.to_string(),
);
let system_properties_service = Arc::new(SystemPropertiesServiceImpl::new(