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
refactor(email-service): Separate email api and pubsub workers into separate services (#594)
Evan Hutnikad7f12fed93f
diff --git a/infra/stacks/email-service/index.ts b/infra/stacks/email-service/index.tsindex 2e0d15c690..fdb4352c46 100644--- a/infra/stacks/email-service/index.ts+++ b/infra/stacks/email-service/index.ts@@ -1,7 +1,11 @@import * as aws from '@pulumi/aws';import * as pulumi from '@pulumi/pulumi';import * as tls from '@pulumi/tls';-import { Queue, Redis } from '../../packages/resources';+import {+ createFrecencyTablePolicy,+ Queue,+ Redis,+} from '../../packages/resources';import {config,getMacroApiToken,@@ -10,8 +14,13 @@ import {stack,} from '../../packages/shared';import { get_coparse_api_vpc } from '../../packages/vpc';+import { EmailAttachmentsBucket } from './attachments-bucket';+import { EmailPubSubWorkers } from './pubsub_workers';import { EmailRefreshHandler } from './refresh_lambda';-import { cloudfrontPrivateKeySecret } from './s3-cloudfront-distribution';+import {+ cloudfrontPrivateKeySecret,+ getCloudfrontDistribution,+} from './s3-cloudfront-distribution';import { EmailScheduledHandler } from './scheduled_lambda';import { EmailService } from './service';@@ -241,180 +250,286 @@ const queueArns = [contactsQueueArn,];+const emailServiceSecretsPolicy = new aws.iam.Policy(+ 'email-service-secrets-policy-2',+ {+ policy: {+ Version: '2012-10-17',+ Statement: [+ {+ Action: ['secretsmanager:GetSecretValue'],+ Resource: [...secretKeyArns],+ Effect: 'Allow',+ },+ ],+ },+ tags: tags,+ }+);++const emailServiceSqsPolicy = new aws.iam.Policy('email-service-sqs-policy-2', {+ policy: pulumi.output({+ Version: '2012-10-17',+ Statement: [+ {+ Action: ['sqs:*'],+ Resource: queueArns,+ Effect: 'Allow',+ },+ ],+ }),+ tags: tags,+});++const emailServiceFrecencyPolicy = createFrecencyTablePolicy(+ 'email-service-frecency-policy-2'+);++// Create IAM role for email service+const emailServiceRole = new aws.iam.Role('email-service-role-2', {+ name: `email-service-role-2-${stack}`,+ assumeRolePolicy: {+ Version: '2012-10-17',+ Statement: [+ {+ Action: 'sts:AssumeRole',+ Principal: {+ Service: 'ecs-tasks.amazonaws.com',+ },+ Effect: 'Allow',+ Sid: '',+ },+ ],+ },+ tags: tags,+ managedPolicyArns: [+ emailServiceSecretsPolicy.arn,+ emailServiceSqsPolicy.arn,+ emailServiceFrecencyPolicy.arn,+ ],+});++let emailAttachmentBucket: EmailAttachmentsBucket;+if (stack !== 'local') {+ emailAttachmentBucket = new EmailAttachmentsBucket(+ `email-attachments-bucket-${stack}`,+ {+ emailServiceRoleArn: emailServiceRole.arn,+ }+ );+} else {+ emailAttachmentBucket = new EmailAttachmentsBucket(+ `email-attachments-bucket-${stack}`,+ {}+ );+}++const cloudfrontDistribution = getCloudfrontDistribution({+ bucket: emailAttachmentBucket.bucket,+ keyPair: cfKeyPair,+});++emailAttachmentBucket.attachCloudfrontPolicy({+ cloudfrontDistributionArn: cloudfrontDistribution.distribution.arn,+ emailServiceRoleArn: emailServiceRole.arn,+});++const containerEnvVars = [+ {+ name: 'RUST_LOG',+ value: `email=${stack === 'prod' ? 'debug' : 'debug'},email_service=${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,insight_service_client=${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: 'BACKFILL_QUEUE',+ value: backfillQueueName,+ },+ {+ name: 'SFS_UPLOADER_QUEUE',+ value: sfsUploaderQueueName,+ },+ {+ name: 'GMAIL_GCP_QUEUE',+ value: pulumi.interpolate`${GMAIL_GCP_QUEUE}`,+ },+ {+ name: 'NOTIFICATION_QUEUE',+ value: pulumi.interpolate`${notificationQueueName}`,+ },+ {+ name: 'INSIGHT_CONTEXT_QUEUE',+ value: pulumi.interpolate`${insightContextQueueName}`,+ },+ {+ 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: 'AUTHENTICATION_SERVICE_URL',+ value: pulumi.interpolate`https://auth-service${stack === 'prod' ? '' : `-${stack}`}.macro.com`,+ },+ {+ name: 'AUTHENTICATION_SERVICE_SECRET_KEY',+ value: pulumi.interpolate`${AUTHENTICATION_SERVICE_INTERNAL_API_KEY}`,+ },+ {+ name: 'STATIC_FILE_SERVICE_URL',+ value: `https://static-file-service${stack === 'prod' ? '' : `-${stack}`}.macro.com`,+ },+ {+ name: 'DOCUMENT_STORAGE_SERVICE_URL',+ value: `https://cloud-storage${stack === 'prod' ? '' : `-${stack}`}.macro.com`,+ },+ {+ name: 'CONNECTION_GATEWAY_URL',+ value: `https://connection-gateway${stack === 'prod' ? '' : `-${stack}`}.macro.com`,+ },+ {+ name: 'NOTIFICATIONS_ENABLED',+ value: pulumi.interpolate`${NOTIFICATIONS_ENABLED}`,+ },+ {+ name: 'SEARCH_EVENT_QUEUE',+ value: pulumi.interpolate`${searchEventQueueName}`,+ },+ {+ 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: '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: 'PRESIGNED_URL_TTL_SECS',+ value: pulumi.interpolate`${PRESIGNED_URL_TTL_SECS}`,+ },+ {+ name: '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: 'CLOUDFRONT_DISTRIBUTION_URL',+ value: pulumi.interpolate`${cloudfrontDistribution.domain}`,+ },+ {+ name: 'CLOUDFRONT_SIGNER_PUBLIC_KEY_ID',+ value: pulumi.interpolate`${cloudfrontDistribution.publicKey.id}`,+ },+];+const emailService = new EmailService('email-service', {vpc: coparse_api_vpc,tags,ecsClusterArn: cloudStorageClusterArn,clusterName: cloudStorageClusterName,- secretKeyArns,+ role: emailServiceRole,serviceContainerPort: 8080,isPrivate: false,healthCheckPath: '/health',platform: { family: 'linux', architecture: 'amd64' },- queueArns,- cfKeyPair: cfKeyPair,- containerEnvVars: [- {- name: 'RUST_LOG',- value: `email=${stack === 'prod' ? 'debug' : 'debug'},email_service=${stack === 'prod' ? 'debug' : 'debug'},email_db_client=${stack === 'prod' ? 'info' : 'debug'},gmail_client=${stack === 'prod' ? 'info' : 'debug'},tower_http=info,insight_service_client=${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: 'BACKFILL_QUEUE',- value: backfillQueueName,- },- {- name: 'SFS_UPLOADER_QUEUE',- value: sfsUploaderQueueName,- },- {- name: 'GMAIL_GCP_QUEUE',- value: pulumi.interpolate`${GMAIL_GCP_QUEUE}`,- },- {- name: 'NOTIFICATION_QUEUE',- value: pulumi.interpolate`${notificationQueueName}`,- },- {- name: 'INSIGHT_CONTEXT_QUEUE',- value: pulumi.interpolate`${insightContextQueueName}`,- },- {- 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: 'AUTHENTICATION_SERVICE_URL',- value: pulumi.interpolate`https://auth-service${stack === 'prod' ? '' : `-${stack}`}.macro.com`,- },- {- name: 'AUTHENTICATION_SERVICE_SECRET_KEY',- value: pulumi.interpolate`${AUTHENTICATION_SERVICE_INTERNAL_API_KEY}`,- },- {- name: 'STATIC_FILE_SERVICE_URL',- value: `https://static-file-service${stack === 'prod' ? '' : `-${stack}`}.macro.com`,- },- {- name: 'DOCUMENT_STORAGE_SERVICE_URL',- value: `https://cloud-storage${stack === 'prod' ? '' : `-${stack}`}.macro.com`,- },- {- name: 'CONNECTION_GATEWAY_URL',- value: `https://connection-gateway${stack === 'prod' ? '' : `-${stack}`}.macro.com`,- },- {- name: 'NOTIFICATIONS_ENABLED',- value: pulumi.interpolate`${NOTIFICATIONS_ENABLED}`,- },- {- name: 'SEARCH_EVENT_QUEUE',- value: pulumi.interpolate`${searchEventQueueName}`,- },- {- 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: '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: 'PRESIGNED_URL_TTL_SECS',- value: pulumi.interpolate`${PRESIGNED_URL_TTL_SECS}`,- },- {- name: 'CLOUDFRONT_SIGNER_PRIVATE_KEY',- value: pulumi.interpolate`${CLOUDFRONT_PRIVATE_KEY}`,- },- {- name: 'CONTACTS_QUEUE',- value: pulumi.interpolate`${contactsQueueName}`,- },- ],+ containerEnvVars,});export const emailServiceUrl = pulumi.interpolate`${emailService.domain}`;+new EmailPubSubWorkers('email-pubsub-workers', {+ vpc: coparse_api_vpc,+ tags,+ ecsClusterArn: cloudStorageClusterArn,+ clusterName: cloudStorageClusterName,+ role: emailServiceRole,+ platform: { family: 'linux', architecture: 'amd64' },+ containerEnvVars,+});+const emailRefreshHandler = new EmailRefreshHandler('email-refresh-handler', {queueArns: [linkManagerQueueArn],vpc: coparse_api_vpc,diff --git a/infra/stacks/email-service/pubsub_workers.ts b/infra/stacks/email-service/pubsub_workers.tsnew file mode 100644index 0000000000..44996c2a36--- /dev/null+++ b/infra/stacks/email-service/pubsub_workers.ts@@ -0,0 +1,274 @@+import * as aws from '@pulumi/aws';+import * as awsx from '@pulumi/awsx';+import * as pulumi from '@pulumi/pulumi';+import {+ DATADOG_API_KEY,+ datadogAgentContainer,+ fargateLogRouterSidecarContainer,+} from '../../packages/resources';+import { EcrImage } from '../../packages/service';+import { CLOUD_TRAIL_SNS_TOPIC_ARN, stack } from '../../packages/shared';++const BASE_NAME = 'email-service-pubsub-workers';+const BASE_PATH = '../../../rust/cloud-storage';++type Args = {+ role: aws.iam.Role;+ clusterName: pulumi.Output<string> | string;+ ecsClusterArn: pulumi.Output<string> | string;+ vpc: {+ vpcId: pulumi.Output<string> | string;+ publicSubnetIds: pulumi.Output<string[]> | string[];+ privateSubnetIds: pulumi.Output<string[]> | string[];+ };+ platform: { family: string; architecture: 'amd64' | 'arm64' };+ containerEnvVars: { name: string; value: pulumi.Output<string> | string }[];+ tags: { [key: string]: string };+};++export class EmailPubSubWorkers extends pulumi.ComponentResource {+ public role: aws.iam.Role;+ public ecr: awsx.ecr.Repository;+ public serviceSg: aws.ec2.SecurityGroup;+ public service: awsx.ecs.FargateService;+ public clusterName: pulumi.Output<string> | string;+ public tags: { [key: string]: string };++ constructor(+ name: string,+ {+ role,+ ecsClusterArn,+ vpc,+ platform,+ containerEnvVars,+ clusterName,+ tags,+ }: Args,+ opts?: pulumi.ComponentResourceOptions+ ) {+ super('my:components:PubSubWorkers', name, {}, opts);+ this.tags = tags;++ this.clusterName = clusterName;+ this.role = role;++ // ecr image+ const image = new EcrImage(+ `${BASE_NAME}-ecr-image-${stack}`,+ {+ repositoryId: `${BASE_NAME}-ecr-${stack}`,+ repositoryName: `${BASE_NAME}-${stack}`,+ imageId: `${BASE_NAME}-image-${stack}`,+ imagePath: BASE_PATH,+ dockerfile: 'Dockerfile',+ platform,+ tags: this.tags,+ buildArgs: {+ SERVICE_NAME: 'pubsub_workers',+ },+ },+ { parent: this }+ );+ this.ecr = image.ecr;++ // sg - workers only need egress+ this.serviceSg = this.initializeSecurityGroup({+ vpcId: vpc.vpcId,+ });++ // service+ const service = new awsx.ecs.FargateService(+ `${BASE_NAME}`,+ {+ tags,+ cluster: ecsClusterArn,+ networkConfiguration: {+ subnets: vpc.privateSubnetIds,+ securityGroups: [this.serviceSg.id],+ },+ taskDefinitionArgs: {+ taskRole: {+ roleArn: this.role.arn,+ },+ containers: {+ log_router: fargateLogRouterSidecarContainer,+ datadog_agent: datadogAgentContainer,+ service: {+ name: BASE_NAME,+ image: image.image.imageUri,+ stopTimeout: 10, // 10 seconds to force kill the task+ cpu: stack === 'prod' ? 2048 : 1024,+ memory: stack === 'prod' ? 3742 : 1742, // 2048 minimum - 256 for datadog - 50 for log_router+ environment: [...containerEnvVars],+ logConfiguration: {+ logDriver: 'awsfirelens',+ options: {+ Name: 'datadog',+ Host: 'http-intake.logs.us5.datadoghq.com',+ apikey: DATADOG_API_KEY,+ dd_service: `${BASE_NAME}-${stack}`,+ dd_source: 'fargate',+ dd_tags: `project:cloudstorage, env:${stack}`,+ provider: 'ecs',+ },+ },+ // No portMappings - workers don't expose ports+ },+ },+ runtimePlatform: {+ operatingSystemFamily: `${platform.family.toUpperCase()}`,+ cpuArchitecture: `${+ platform.architecture === 'amd64'+ ? 'X86_64'+ : platform.architecture.toUpperCase()+ }`,+ },+ },+ desiredCount: stack === 'prod' ? 5 : 1,+ },+ { parent: this }+ );++ this.service = service;++ this.setupAutoScaling();++ this.setupServiceAlarms();+ }++ initializeSecurityGroup({+ vpcId,+ }: {+ vpcId: pulumi.Output<string> | string;+ }) {+ const serviceSg = new aws.ec2.SecurityGroup(+ `${BASE_NAME}-sg-${stack}`,+ {+ name: `${BASE_NAME}-sg-${stack}`,+ vpcId,+ description: `${BASE_NAME} security group that is attached directly to the service`,+ tags: this.tags,+ },+ { parent: this }+ );++ new aws.vpc.SecurityGroupEgressRule(+ `${BASE_NAME}-all-out`,+ {+ securityGroupId: serviceSg.id,+ description: 'Allow all outbound',+ cidrIpv4: '0.0.0.0/0',+ ipProtocol: '-1',+ tags: this.tags,+ },+ { parent: this }+ );++ return serviceSg;+ }++ setupAutoScaling() {+ if (!this.service) return;++ const serviceScalableTarget = new aws.appautoscaling.Target(+ `${BASE_NAME}-scalable-target-${stack}`,+ {+ maxCapacity: stack === 'prod' ? 10 : 2,+ minCapacity: stack === 'prod' ? 5 : 1,+ resourceId: pulumi.interpolate`service/${this.clusterName}/${this.service.service.name}`,+ scalableDimension: 'ecs:service:DesiredCount',+ serviceNamespace: 'ecs',+ tags: this.tags,+ },+ { parent: this }+ );++ // Create an Auto Scaling policy for CPU utilization.+ new aws.appautoscaling.Policy(+ `${BASE_NAME}-scaling-policy-cpu-${stack}`,+ {+ policyType: 'TargetTrackingScaling',+ resourceId: serviceScalableTarget.resourceId,+ scalableDimension: serviceScalableTarget.scalableDimension,+ serviceNamespace: serviceScalableTarget.serviceNamespace,+ targetTrackingScalingPolicyConfiguration: {+ targetValue: 70.0,+ predefinedMetricSpecification: {+ predefinedMetricType: 'ECSServiceAverageCPUUtilization',+ },+ scaleInCooldown: 100,+ scaleOutCooldown: 300,+ },+ },+ { parent: this }+ );++ new aws.appautoscaling.Policy(+ `${BASE_NAME}-scaling-policy-memory-${stack}`,+ {+ policyType: 'TargetTrackingScaling',+ resourceId: serviceScalableTarget.resourceId,+ scalableDimension: serviceScalableTarget.scalableDimension,+ serviceNamespace: serviceScalableTarget.serviceNamespace,+ targetTrackingScalingPolicyConfiguration: {+ targetValue: 70.0,+ predefinedMetricSpecification: {+ predefinedMetricType: 'ECSServiceAverageMemoryUtilization',+ },+ scaleInCooldown: 100,+ scaleOutCooldown: 300,+ },+ },+ { parent: this }+ );+ }++ setupServiceAlarms() {+ new aws.cloudwatch.MetricAlarm(+ `${BASE_NAME}-high-cpu-alarm`,+ {+ name: `${BASE_NAME}-high-cpu-alarm-${stack}`,+ metricName: 'CPUUtilization',+ namespace: 'AWS/ECS',+ statistic: 'Average',+ period: 180,+ evaluationPeriods: 1,+ threshold: 80,+ comparisonOperator: 'GreaterThanThreshold',+ dimensions: {+ ClusterName: this.clusterName,+ ServiceName: this.service.service.name,+ },+ alarmDescription: `High CPU usage alarm for ${BASE_NAME} service.`,+ actionsEnabled: true,+ alarmActions: [CLOUD_TRAIL_SNS_TOPIC_ARN],+ tags: this.tags,+ },+ { parent: this }+ );++ new aws.cloudwatch.MetricAlarm(+ `${BASE_NAME}-high-mem-alarm`,+ {+ name: `${BASE_NAME}-high-mem-alarm-${stack}`,+ metricName: 'MemoryUtilization',+ namespace: 'AWS/ECS',+ statistic: 'Average',+ period: 180,+ evaluationPeriods: 1,+ threshold: 80,+ comparisonOperator: 'GreaterThanThreshold',+ dimensions: {+ ClusterName: this.clusterName,+ ServiceName: this.service.service.name,+ },+ alarmDescription: `High Memory usage alarm for ${BASE_NAME} service.`,+ actionsEnabled: true,+ alarmActions: [CLOUD_TRAIL_SNS_TOPIC_ARN],+ tags: this.tags,+ },+ { parent: this }+ );+ }+}diff --git a/infra/stacks/email-service/service.ts b/infra/stacks/email-service/service.tsindex b1962cd850..ed6f841bf5 100644--- a/infra/stacks/email-service/service.ts+++ b/infra/stacks/email-service/service.ts@@ -1,9 +1,7 @@import * as aws from '@pulumi/aws';import * as awsx from '@pulumi/awsx';import * as pulumi from '@pulumi/pulumi';-import type * as tls from '@pulumi/tls';import {- createFrecencyTablePolicy,DATADOG_API_KEY,datadogAgentContainer,fargateLogRouterSidecarContainer,@@ -15,8 +13,6 @@ import {CLOUD_TRAIL_SNS_TOPIC_ARN,stack,} from '../../packages/shared';-import { EmailAttachmentsBucket } from './attachments-bucket';-import { getCloudfrontDistribution } from './s3-cloudfront-distribution';const BASE_NAME = 'email-service';const BASE_PATH = '../../../rust/cloud-storage';@@ -26,7 +22,7 @@ export const SERVICE_DOMAIN_NAME = `email-service${}.${BASE_DOMAIN}`;type Args = {- secretKeyArns: (pulumi.Output<string> | string)[];+ role: aws.iam.Role;clusterName: pulumi.Output<string> | string;ecsClusterArn: pulumi.Output<string> | string;vpc: {@@ -40,8 +36,6 @@ type Args = {containerEnvVars: { name: string; value: pulumi.Output<string> | string }[];healthCheckPath: string;tags: { [key: string]: string };- queueArns: pulumi.Output<string>[];- cfKeyPair: tls.PrivateKey;};export class EmailService extends pulumi.ComponentResource {@@ -60,6 +54,7 @@ export class EmailService extends pulumi.ComponentResource {constructor(name: string,{+ role,ecsClusterArn,vpc,platform,@@ -69,9 +64,6 @@ export class EmailService extends pulumi.ComponentResource {containerEnvVars,clusterName,tags,- secretKeyArns,- queueArns,- cfKeyPair,}: Args,opts?: pulumi.ComponentResourceOptions) {@@ -79,76 +71,7 @@ export class EmailService extends pulumi.ComponentResource {this.tags = tags;this.clusterName = clusterName;-- // role- 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 gmailSqsPolicy = new aws.iam.Policy(- `${BASE_NAME}-gmail-sqs-policy`,- {- policy: pulumi.output({- Version: '2012-10-17',- Statement: [- {- Action: ['sqs:*'],- Resource: queueArns,- Effect: 'Allow',- },- ],- }),- tags: tags,- },- { parent: this }- );-- // Create frecency table policy- const frecencyPolicy = createFrecencyTablePolicy(- `${BASE_NAME}-frecency-policy`,- { parent: this }- );-- this.role = new aws.iam.Role(- `${BASE_NAME}-role`,- {- name: `${BASE_NAME}-role-${stack}`,- assumeRolePolicy: {- Version: '2012-10-17',- Statement: [- {- Action: 'sts:AssumeRole',- Principal: {- Service: 'ecs-tasks.amazonaws.com',- },- Effect: 'Allow',- Sid: '',- },- ],- },- tags: this.tags,- managedPolicyArns: [- secretsPolicy.arn,- gmailSqsPolicy.arn,- frecencyPolicy.arn,- ],- },- { parent: this }- );+ this.role = role;// ecr imageconst image = new EcrImage(@@ -177,46 +100,6 @@ export class EmailService extends pulumi.ComponentResource {this.serviceAlbSg = sg.serviceAlbSg;this.serviceSg = sg.serviceSg;- let emailAttachmentBucket: EmailAttachmentsBucket;- if (stack !== 'local') {- emailAttachmentBucket = new EmailAttachmentsBucket(- `email-attachments-bucket-${stack}`,- {- emailServiceRoleArn: this.role.arn,- }- );- } else {- emailAttachmentBucket = new EmailAttachmentsBucket(- `email-attachments-bucket-${stack}`,- {}- );- }-- const cloudfrontDistribution = getCloudfrontDistribution({- bucket: emailAttachmentBucket.bucket,- keyPair: cfKeyPair,- });-- emailAttachmentBucket.attachCloudfrontPolicy({- cloudfrontDistributionArn: cloudfrontDistribution.distribution.arn,- emailServiceRoleArn: this.role.arn,- });-- containerEnvVars.push(- {- name: 'ATTACHMENT_BUCKET',- value: emailAttachmentBucket.bucket.id,- },- {- name: 'CLOUDFRONT_DISTRIBUTION_URL',- value: pulumi.interpolate`${cloudfrontDistribution.domain}`,- },- {- name: 'CLOUDFRONT_SIGNER_PUBLIC_KEY_ID',- value: pulumi.interpolate`${cloudfrontDistribution.publicKey.id}`,- }- );-// lbconst { targetGroup, lb, listener } = serviceLoadBalancer(this, {serviceName: BASE_NAME, // service name@@ -252,8 +135,8 @@ export class EmailService extends pulumi.ComponentResource {name: BASE_NAME,image: image.image.imageUri,stopTimeout: 10, // 10 seconds to force kill the task- cpu: stack === 'prod' ? 2048 : 1024,- memory: stack === 'prod' ? 3742 : 1742, // 2048 minimum - 256 for datadog - 50 for log_router+ cpu: stack === 'prod' ? 1024 : 256,+ memory: stack === 'prod' ? 1742 : 717, // 2048 minimum - 256 for datadog - 50 for log_routerenvironment: [...containerEnvVars],logConfiguration: {logDriver: 'awsfirelens',diff --git a/rust/cloud-storage/email_service/Cargo.toml b/rust/cloud-storage/email_service/Cargo.tomlindex e5b22b80e3..04e1ab2184 100644--- a/rust/cloud-storage/email_service/Cargo.toml+++ b/rust/cloud-storage/email_service/Cargo.toml@@ -25,6 +25,10 @@ path = "src/bin/backfill_search/backfill_search.rs"name = "backfill_sfs_attachments"path = "src/bin/backfill_sfs_attachments/backfill_sfs_attachments.rs"+[[bin]]+name = "pubsub_workers"+path = "src/bin/pubsub_workers/pubsub_workers.rs"+[features]attachment_upload = []connection_gateway = []@@ -113,7 +117,7 @@ static_file_service_client = { path = "../static_file_service_client" }strum_macros = { workspace = true }system_properties = { path = "../system_properties" }thiserror = { workspace = true }-tokio = { workspace = true }+tokio = { workspace = true, features = ["signal"] }tower = { workspace = true }tower-http = { workspace = true, features = ["compression-br",diff --git a/rust/cloud-storage/email_service/src/api/context.rs b/rust/cloud-storage/email_service/src/api/context.rsindex 5a007a0aef..5f1e3ee016 100644--- a/rust/cloud-storage/email_service/src/api/context.rs+++ b/rust/cloud-storage/email_service/src/api/context.rs@@ -1,7 +1,8 @@-use crate::{config::Config, util::redis::RedisClient};use axum::extract::FromRef;use document_storage_service_client::DocumentStorageServiceClient;use email::{domain::service::EmailServiceImpl, inbound::EmailPreviewState, outbound::EmailPgRepo};+use email_service::config::Config;+use email_service::util::redis::RedisClient;use frecency::{domain::services::FrecencyQueryServiceImpl, outbound::postgres::FrecencyPgStorage};use macro_auth::middleware::decode_jwt::JwtValidationArgs;use macro_middleware::auth::internal_access::InternalApiSecretKey;diff --git a/rust/cloud-storage/email_service/src/api/email/attachments/get_document_id.rs b/rust/cloud-storage/email_service/src/api/email/attachments/get_document_id.rsindex bbda9a956c..f635fd5ab4 100644--- a/rust/cloud-storage/email_service/src/api/email/attachments/get_document_id.rs+++ b/rust/cloud-storage/email_service/src/api/email/attachments/get_document_id.rs@@ -1,11 +1,11 @@use crate::api::context::ApiContext;-use crate::util::upload_attachment::{- UploadAttachmentContext, UploadAttachmentError, upload_attachment,-};use axum::extract::{Path, State};use axum::http::StatusCode;use axum::response::{IntoResponse, Response};use axum::{Extension, Json};+use email_service::util::upload_attachment::{+ UploadAttachmentContext, UploadAttachmentError, upload_attachment,+};use model::response::ErrorResponse;use models_email::db::address::EmailRecipientType;use models_email::email::service::link::Link;diff --git a/rust/cloud-storage/email_service/src/api/email/links/list.rs b/rust/cloud-storage/email_service/src/api/email/links/list.rsindex 0506de113f..67bf6c4978 100644--- a/rust/cloud-storage/email_service/src/api/email/links/list.rs+++ b/rust/cloud-storage/email_service/src/api/email/links/list.rs@@ -1,9 +1,9 @@use crate::api::context::ApiContext;-use crate::util::gmail::auth::fetch_gmail_access_token_from_link;use axum::extract::{Query, State};use axum::http::StatusCode;use axum::response::{IntoResponse, Response};use axum::{Extension, Json};+use email_service::util::gmail::auth::fetch_gmail_access_token_from_link;use futures::future::join_all;use model::response::ErrorResponse;use model::user::UserContext;diff --git a/rust/cloud-storage/email_service/src/api/email/messages/send.rs b/rust/cloud-storage/email_service/src/api/email/messages/send.rsindex 4f75acb30d..e5b91e3f60 100644--- a/rust/cloud-storage/email_service/src/api/email/messages/send.rs+++ b/rust/cloud-storage/email_service/src/api/email/messages/send.rs@@ -1,6 +1,5 @@use crate::api::context::ApiContext;use crate::api::email::validation::{self, ValidationError};-use crate::util::gmail::send;use anyhow::Context;use axum::extract::State;use axum::http::StatusCode;@@ -9,6 +8,7 @@ use axum::{Extension, Json};use base64::Engine;use base64::engine::general_purpose::URL_SAFE_NO_PAD;use email_db_client::messages::insert::insert_message_to_send;+use email_service::util::gmail::send;use model::response::ErrorResponse;use model::user::UserContext;use models_email::email::service::address::ContactInfo;diff --git a/rust/cloud-storage/email_service/src/api/email/sync/enable.rs b/rust/cloud-storage/email_service/src/api/email/sync/enable.rsindex e2950430d0..d006564a38 100644--- a/rust/cloud-storage/email_service/src/api/email/sync/enable.rs+++ b/rust/cloud-storage/email_service/src/api/email/sync/enable.rs@@ -112,7 +112,7 @@ pub async fn enable_gmail_sync() -> Result<Link, EnableSyncError> {let token = match gmail_access_token {Some(token) => token.to_string(),- None => crate::util::gmail::auth::fetch_gmail_token_usercontext_response(+ None => email_service::util::gmail::auth::fetch_gmail_token_usercontext_response(user_context,&ctx.redis_client,&ctx.auth_service_client,diff --git a/rust/cloud-storage/email_service/src/api/gmail/webhook.rs b/rust/cloud-storage/email_service/src/api/gmail/webhook.rsindex c0ff3fe043..85de4153be 100644--- a/rust/cloud-storage/email_service/src/api/gmail/webhook.rs+++ b/rust/cloud-storage/email_service/src/api/gmail/webhook.rs@@ -1,5 +1,4 @@use crate::api::context::ApiContext;-use crate::util;use axum::extract::State;use axum::http::HeaderMap;use axum::{@@ -7,6 +6,7 @@ use axum::{http::StatusCode,response::{IntoResponse, Json, Response},};+use email_service::util;use model::response::ErrorResponse;use models_email::gmail::inbox_sync::{GmailInboxSyncPayload, GmailMessagePayload, InboxSyncOperation, InboxSyncPubsubMessage,diff --git a/rust/cloud-storage/email_service/src/api/internal/backfill.rs b/rust/cloud-storage/email_service/src/api/internal/backfill.rsindex 043fa7c916..96fa2204a0 100644--- a/rust/cloud-storage/email_service/src/api/internal/backfill.rs+++ b/rust/cloud-storage/email_service/src/api/internal/backfill.rs@@ -1,10 +1,11 @@-use crate::{api::ApiContext, util::backfill::backfill_insights::backfill_email_insights};+use crate::api::ApiContext;use axum::{extract::State,http::StatusCode,response::{IntoResponse, Json, Response},};+use email_service::util::backfill::backfill_insights::backfill_email_insights;use model::insight_context::email_insights::BackfillEmailInsightsFilter;/// Internal endpoint to backfill insights from emailsdiff --git a/rust/cloud-storage/email_service/src/api/internal/delete_user.rs b/rust/cloud-storage/email_service/src/api/internal/delete_user.rsindex 9b63722f5e..dfeeec1efb 100644--- a/rust/cloud-storage/email_service/src/api/internal/delete_user.rs+++ b/rust/cloud-storage/email_service/src/api/internal/delete_user.rs@@ -39,19 +39,20 @@ pub async fn handler(tracing::error!(error=?e, link_id=?link.id, "Failed to update backfill job statuses");};- let gmail_access_token = match crate::util::gmail::auth::fetch_gmail_access_token_from_link(- &link,- &ctx.redis_client,- &ctx.auth_service_client,- )- .await- {- Ok(token) => Some(token),- Err(e) => {- tracing::error!(error=?e, link_id=?link.id, "unable to fetch access token - skipping stop watch");- None- }- };+ let gmail_access_token =+ match email_service::util::gmail::auth::fetch_gmail_access_token_from_link(+ &link,+ &ctx.redis_client,+ &ctx.auth_service_client,+ )+ .await+ {+ Ok(token) => Some(token),+ Err(e) => {+ tracing::error!(error=?e, link_id=?link.id, "unable to fetch access token - skipping stop watch");+ None+ }+ };if let Some(token) = gmail_access_token&& let Err(e) = ctx.gmail_client.stop_watch(&token).awaitdiff --git a/rust/cloud-storage/email_service/src/api/middleware/gmail_token.rs b/rust/cloud-storage/email_service/src/api/middleware/gmail_token.rsindex 9ad10aa08c..badc158a88 100644--- a/rust/cloud-storage/email_service/src/api/middleware/gmail_token.rs+++ b/rust/cloud-storage/email_service/src/api/middleware/gmail_token.rs@@ -3,7 +3,7 @@ use axum::{Extension, extract::Request, middleware::Next, response::Response};use model::user::UserContext;use crate::api::context::ApiContext;-use crate::util::gmail::auth::fetch_gmail_token_usercontext_response;+use email_service::util::gmail::auth::fetch_gmail_token_usercontext_response;pub(in crate::api) async fn attach_gmail_token(State(ctx): State<ApiContext>,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.rsnew file mode 100644index 0000000000..a9bbf73bf3--- /dev/null+++ b/rust/cloud-storage/email_service/src/bin/pubsub_workers/pubsub_workers.rs@@ -0,0 +1,388 @@+use anyhow::Context;+use document_storage_service_client::DocumentStorageServiceClient;+use email_service::config::{CloudfrontSignerPrivateKey, Config};+use macro_entrypoint::MacroEntrypoint;+use macro_env::Environment;+use macro_middleware::auth::internal_access::InternalApiSecretKey;+use secretsmanager_client::SecretManager;+use sqlx::postgres::PgPoolOptions;+use static_file_service_client::StaticFileServiceClient;+use std::sync::Arc;+use system_properties::{PgSystemPropertiesRepository, SystemPropertiesServiceImpl};++#[tokio::main]+#[tracing::instrument(err)]+async fn main() -> anyhow::Result<()> {+ MacroEntrypoint::default().init();+ let env = Environment::new_or_prod();++ // new+ let aws_config = aws_config::defaults(aws_config::BehaviorVersion::latest())+ .region("us-east-1")+ .load()+ .await;++ let secretsmanager_client = secretsmanager_client::SecretsManager::new(+ aws_sdk_secretsmanager::Client::new(&aws_config),+ );++ let cloudfront_signer_private_key = secretsmanager_client+ .get_maybe_secret_value(env, CloudfrontSignerPrivateKey::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(),+ };++ let (min_connections, max_connections): (u32, u32) = match config.environment {+ Environment::Production => (3, 15),+ Environment::Develop => (1, 10),+ Environment::Local => (1, 10),+ };++ let (min_connections_backfill, max_connections_backfill): (u32, u32) = match config.environment+ {+ Environment::Production => (3, 25),+ Environment::Develop => (1, 30),+ Environment::Local => (1, 50),+ };++ // all non-backfill workers share a connection pool+ let db = PgPoolOptions::new()+ .min_connections(min_connections)+ .max_connections(max_connections)+ .connect(&config.macro_db_url)+ .await+ .context("could not connect to db")?;++ let db_backfill = PgPoolOptions::new()+ .min_connections(min_connections_backfill)+ .max_connections(max_connections_backfill)+ .connect(&config.macro_db_url)+ .await+ .context("could not connect to backfill db")?;++ let gmail_queue_aws_config = if cfg!(feature = "local_queue") {+ aws_config::defaults(aws_config::BehaviorVersion::latest())+ .region("us-east-1")+ .endpoint_url(&config.gmail_inbox_sync_queue)+ .load()+ .await+ } else {+ aws_config::defaults(aws_config::BehaviorVersion::latest())+ .region("us-east-1")+ .load()+ .await+ };++ let sqs_client = sqs_client::SQS::new(aws_sdk_sqs::Client::new(&gmail_queue_aws_config))+ .gmail_inbox_sync_queue(&config.gmail_inbox_sync_queue)+ .gmail_inbox_sync_retry_queue(&config.gmail_inbox_sync_retry_queue)+ .search_event_queue(&config.search_event_queue)+ .insight_context_queue(&config.insight_context_queue)+ .email_backfill_queue(&config.backfill_queue)+ .email_scheduled_queue(&config.email_scheduled_queue)+ .sfs_uploader_queue(&config.sfs_uploader_queue)+ .contacts_queue(&config.contacts_queue);++ let macro_notify_client = macro_notify::MacroNotify::new(+ config.notification_queue.clone(),+ "email_service".to_string(),+ )+ .await;++ let link_manager_worker = sqs_worker::SQSWorker::new(+ aws_sdk_sqs::Client::new(&gmail_queue_aws_config),+ config.link_manager_queue.clone(),+ 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.queue_max_messages,+ config.queue_wait_time_seconds,+ );++ let sfs_uploader_workers = (0..config.sfs_uploader_workers)+ .map(|_| {+ sqs_worker::SQSWorker::new(+ aws_sdk_sqs::Client::new(&gmail_queue_aws_config),+ config.sfs_uploader_queue.clone(),+ config.queue_max_messages,+ config.queue_wait_time_seconds,+ )+ })+ .collect::<Vec<_>>();++ let backfill_workers = (0..config.backfill_queue_workers)+ .map(|_| {+ sqs_worker::SQSWorker::new(+ aws_sdk_sqs::Client::new(&gmail_queue_aws_config),+ config.backfill_queue.clone(),+ config.backfill_queue_max_messages,+ config.queue_wait_time_seconds,+ )+ })+ .collect::<Vec<_>>();++ let inbox_sync_workers = (0..config.inbox_sync_queue_workers)+ .map(|_| {+ sqs_worker::SQSWorker::new(+ aws_sdk_sqs::Client::new(&gmail_queue_aws_config),+ config.gmail_inbox_sync_queue.clone(),+ config.inbox_sync_queue_max_messages,+ config.queue_wait_time_seconds,+ )+ })+ .collect::<Vec<_>>();++ let inbox_sync_retry_workers = (0..config.inbox_sync_retry_queue_workers)+ .map(|_| {+ sqs_worker::SQSWorker::new(+ aws_sdk_sqs::Client::new(&gmail_queue_aws_config),+ config.gmail_inbox_sync_retry_queue.clone(),+ config.inbox_sync_retry_queue_max_messages,+ config.queue_wait_time_seconds,+ )+ })+ .collect::<Vec<_>>();++ let auth_service_client = authentication_service_client::AuthServiceClient::new(+ auth_service_secret_key,+ config.auth_service_url.clone(),+ );++ let gmail_client = gmail_client::GmailClient::new(config.gmail_gcp_queue.clone());++ let redis_inner_client = redis::Client::open(config.redis_uri.as_str())+ .inspect(|client| {+ client+ .get_connection()+ .map(|_| tracing::info!("initialized redis connection"))+ .inspect_err(|e| {+ tracing::error!(error=?e, "failed to connect to redis");+ })+ .ok();+ })+ .context("failed to connect to redis")?;++ let redis_client = email_service::util::redis::RedisClient::new(+ redis_inner_client,+ config.redis_rate_limit_reqs,+ config.redis_rate_limit_reqs_backfill,+ config.redis_rate_limit_window_secs,+ );++ let internal_auth_key = InternalApiSecretKey::new()?;++ let sfs_client = StaticFileServiceClient::new(+ internal_auth_key.as_ref().to_string(),+ config.static_file_service_url.clone(),+ );++ let dss_client = DocumentStorageServiceClient::new(+ internal_auth_key.as_ref().to_string(),+ config.document_storage_service_url.clone(),+ );++ let connection_gateway_client = connection_gateway_client::client::ConnectionGatewayClient::new(+ internal_auth_key.as_ref().to_string(),+ config.connection_gateway_url.clone(),+ );++ let system_properties_service = Arc::new(SystemPropertiesServiceImpl::new(+ PgSystemPropertiesRepository::new(db.clone()),+ ));++ // process user inbox updates from gmail inbox_sync queue, triggered by update pubsub messages from Google+ for worker in inbox_sync_workers {+ let db_inbox_sync = db.clone();+ let sqs_client_inbox_sync = sqs_client.clone();+ let gmail_client_inbox_sync = gmail_client.clone();+ let auth_service_client_inbox_sync = auth_service_client.clone();+ let redis_client_inbox_sync = redis_client.clone();+ let macro_notify_client_inbox_sync = macro_notify_client.clone();+ let sfs_client_inbox_sync = sfs_client.clone();+ let connection_gateway_client_inbox_sync = connection_gateway_client.clone();+ let dss_client_inbox_sync = dss_client.clone();+ let system_properties_service_inbox_sync = system_properties_service.clone();+ tokio::spawn(async move {+ email_service::pubsub::inbox_sync::worker::run_worker(+ db_inbox_sync,+ worker,+ sqs_client_inbox_sync,+ gmail_client_inbox_sync,+ auth_service_client_inbox_sync,+ redis_client_inbox_sync,+ macro_notify_client_inbox_sync,+ sfs_client_inbox_sync,+ connection_gateway_client_inbox_sync,+ dss_client_inbox_sync,+ system_properties_service_inbox_sync,+ config.notifications_enabled,+ false,+ )+ .await;+ });+ }+ tracing::info!(+ num_workers = config.inbox_sync_queue_workers,+ "inbox_sync workers started"+ );++ // separate queue for retries to avoid backups for large inbox updates that hit gmail api rate limit+ for worker in inbox_sync_retry_workers {+ let db_inbox_sync = db.clone();+ let sqs_client_inbox_sync = sqs_client.clone();+ let gmail_client_inbox_sync = gmail_client.clone();+ let auth_service_client_inbox_sync = auth_service_client.clone();+ let redis_client_inbox_sync = redis_client.clone();+ let macro_notify_client_inbox_sync = macro_notify_client.clone();+ let sfs_client_inbox_sync = sfs_client.clone();+ let connection_gateway_client_inbox_sync = connection_gateway_client.clone();+ let dss_client_inbox_sync = dss_client.clone();+ let system_properties_service_inbox_sync = system_properties_service.clone();+ tokio::spawn(async move {+ email_service::pubsub::inbox_sync::worker::run_worker(+ db_inbox_sync,+ worker,+ sqs_client_inbox_sync,+ gmail_client_inbox_sync,+ auth_service_client_inbox_sync,+ redis_client_inbox_sync,+ macro_notify_client_inbox_sync,+ sfs_client_inbox_sync,+ connection_gateway_client_inbox_sync,+ dss_client_inbox_sync,+ system_properties_service_inbox_sync,+ config.notifications_enabled,+ true,+ )+ .await;+ });+ }+ tracing::info!(+ num_workers = config.inbox_sync_queue_workers,+ "inbox_sync workers started"+ );++ // backfill user emails upon signup+ for worker in backfill_workers {+ let db_backfill = db_backfill.clone();+ let sqs_client_backfill = sqs_client.clone();+ let gmail_client_backfill = gmail_client.clone();+ let auth_service_client_backfill = auth_service_client.clone();+ let redis_client_backfill = redis_client.clone();+ let macro_notify_client_backfill = macro_notify_client.clone();+ let sfs_client_backfill = sfs_client.clone();+ let connection_gateway_client_backfill = connection_gateway_client.clone();+ let dss_client_backfill = dss_client.clone();+ let system_properties_service_backfill = system_properties_service.clone();+ tokio::spawn(async move {+ email_service::pubsub::backfill::worker::run_worker(+ db_backfill,+ worker,+ sqs_client_backfill,+ gmail_client_backfill,+ auth_service_client_backfill,+ redis_client_backfill,+ macro_notify_client_backfill,+ sfs_client_backfill,+ connection_gateway_client_backfill,+ dss_client_backfill,+ system_properties_service_backfill,+ config.notifications_enabled,+ )+ .await;+ });+ }+ tracing::info!(+ num_workers = config.backfill_queue_workers,+ "backfill workers started"+ );++ let db_link_manager = db.clone();+ let gmail_client_link_manager = gmail_client.clone();+ let auth_service_client_link_manager = auth_service_client.clone();+ let redis_client_link_manager = redis_client.clone();+ let sqs_client_link_manager = sqs_client.clone();+ // daily link_manager operations for user contacts and inbox subscriptions+ tokio::spawn(async move {+ email_service::pubsub::link_manager::worker::run_worker(+ link_manager_worker,+ db_link_manager,+ gmail_client_link_manager,+ auth_service_client_link_manager,+ redis_client_link_manager,+ sqs_client_link_manager,+ )+ .await;+ });++ let db_scheduled = db.clone();+ let gmail_client_scheduled = gmail_client.clone();+ let auth_service_client_scheduled = auth_service_client.clone();+ let redis_client_scheduled = redis_client.clone();+ // send scheduled emails+ tokio::spawn(async move {+ email_service::pubsub::scheduled::worker::run_worker(+ scheduled_worker,+ db_scheduled,+ gmail_client_scheduled,+ auth_service_client_scheduled,+ redis_client_scheduled,+ )+ .await;+ });++ if cfg!(feature = "sfs_map") {+ for worker in sfs_uploader_workers {+ let db_sfs_uploader = db.clone();+ let sfs_client_sfs_uploader = sfs_client.clone();+ // upload user contact images to sfs from contact sync+ tokio::spawn(async move {+ email_service::pubsub::sfs_uploader::worker::run_worker(+ worker,+ db_sfs_uploader,+ sfs_client_sfs_uploader,+ )+ .await;+ });+ }+ tracing::info!(+ num_workers = config.sfs_uploader_workers,+ "sfs uploader workers started"+ );+ }++ tracing::info!("All workers started successfully");++ // Wait for shutdown signal (SIGTERM from ECS or SIGINT from Ctrl+C)+ tokio::select! {+ _ = tokio::signal::ctrl_c() => {+ tracing::info!("Received SIGINT (Ctrl+C)");+ }+ _ = async {+ let mut term = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())+ .expect("failed to install SIGTERM handler");+ term.recv().await+ } => {+ tracing::info!("Received SIGTERM");+ }+ }++ tracing::info!("Shutdown signal received, exiting gracefully...");++ Ok(())+}diff --git a/rust/cloud-storage/email_service/src/lib.rs b/rust/cloud-storage/email_service/src/lib.rsnew file mode 100644index 0000000000..fb08291768--- /dev/null+++ b/rust/cloud-storage/email_service/src/lib.rs@@ -0,0 +1,3 @@+pub mod config;+pub mod pubsub;+pub mod util;diff --git a/rust/cloud-storage/email_service/src/main.rs b/rust/cloud-storage/email_service/src/main.rsindex d75f4cda19..38f60712e4 100644--- a/rust/cloud-storage/email_service/src/main.rs+++ b/rust/cloud-storage/email_service/src/main.rs@@ -1,12 +1,12 @@use crate::api::context::ApiContext;-use crate::config::CloudfrontSignerPrivateKey;use anyhow::Context;-use config::{Config, Environment};use document_storage_service_client::DocumentStorageServiceClient;use email::{domain::service::EmailServiceImpl, inbound::EmailPreviewState, outbound::EmailPgRepo};+use email_service::config::CloudfrontSignerPrivateKey;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 sqlx::postgres::PgPoolOptions;@@ -15,9 +15,6 @@ use std::sync::Arc;use system_properties::{PgSystemPropertiesRepository, SystemPropertiesServiceImpl};mod api;-mod config;-mod pubsub;-mod util;mod utils;#[tokio::main]@@ -43,7 +40,7 @@ async fn main() -> anyhow::Result<()> {.await?;// Parse our configuration from the environment.- let config = Config::from_env(cloudfront_signer_private_key)+ 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 {@@ -55,20 +52,13 @@ async fn main() -> anyhow::Result<()> {.to_string(),};- // limiting to max of 400 connections (25% of macrodb total) in prod. (10 service + 30 backfill) * 10 pod max+ // limiting to max of 200 connections (12.5% of macrodb total) in prod.let (min_connections, max_connections): (u32, u32) = match config.environment {- Environment::Production => (3, 30),+ Environment::Production => (3, 20),Environment::Develop => (1, 10),Environment::Local => (1, 10),};- let (min_connections_backfill, max_connections_backfill): (u32, u32) = match config.environment- {- Environment::Production => (3, 30),- Environment::Develop => (1, 30),- Environment::Local => (1, 50),- };-let db = PgPoolOptions::new().min_connections(min_connections).max_connections(max_connections)@@ -76,13 +66,6 @@ async fn main() -> anyhow::Result<()> {.await.context("could not connect to db")?;- let db_backfill = PgPoolOptions::new()- .min_connections(min_connections_backfill)- .max_connections(max_connections_backfill)- .connect(&config.macro_db_url)- .await- .context("could not connect to backfill db")?;-let gmail_queue_aws_config = if cfg!(feature = "local_queue") {aws_config::defaults(aws_config::BehaviorVersion::latest()).region("us-east-1")@@ -106,70 +89,6 @@ async fn main() -> anyhow::Result<()> {.sfs_uploader_queue(&config.sfs_uploader_queue).contacts_queue(&config.contacts_queue);- let macro_notify_client = macro_notify::MacroNotify::new(- config.notification_queue.clone(),- "email_service".to_string(),- )- .await;-- let link_manager_worker = sqs_worker::SQSWorker::new(- aws_sdk_sqs::Client::new(&gmail_queue_aws_config),- config.link_manager_queue.clone(),- 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.queue_max_messages,- config.queue_wait_time_seconds,- );-- let sfs_uploader_workers = (0..config.sfs_uploader_workers)- .map(|_| {- sqs_worker::SQSWorker::new(- aws_sdk_sqs::Client::new(&gmail_queue_aws_config),- config.sfs_uploader_queue.clone(),- config.queue_max_messages,- config.queue_wait_time_seconds,- )- })- .collect::<Vec<_>>();-- let backfill_workers = (0..config.backfill_queue_workers)- .map(|_| {- sqs_worker::SQSWorker::new(- aws_sdk_sqs::Client::new(&gmail_queue_aws_config),- config.backfill_queue.clone(),- config.backfill_queue_max_messages,- config.queue_wait_time_seconds,- )- })- .collect::<Vec<_>>();-- let inbox_sync_workers = (0..config.inbox_sync_queue_workers)- .map(|_| {- sqs_worker::SQSWorker::new(- aws_sdk_sqs::Client::new(&gmail_queue_aws_config),- config.gmail_inbox_sync_queue.clone(),- config.inbox_sync_queue_max_messages,- config.queue_wait_time_seconds,- )- })- .collect::<Vec<_>>();-- let inbox_sync_retry_workers = (0..config.inbox_sync_retry_queue_workers)- .map(|_| {- sqs_worker::SQSWorker::new(- aws_sdk_sqs::Client::new(&gmail_queue_aws_config),- config.gmail_inbox_sync_retry_queue.clone(),- config.inbox_sync_retry_queue_max_messages,- config.queue_wait_time_seconds,- )- })- .collect::<Vec<_>>();-let auth_service_client = authentication_service_client::AuthServiceClient::new(auth_service_secret_key,config.auth_service_url.clone(),@@ -189,7 +108,7 @@ async fn main() -> anyhow::Result<()> {}).context("failed to connect to redis")?;- let redis_client = util::redis::RedisClient::new(+ let redis_client = email_service::util::redis::RedisClient::new(redis_inner_client,config.redis_rate_limit_reqs,config.redis_rate_limit_reqs_backfill,@@ -208,176 +127,10 @@ async fn main() -> anyhow::Result<()> {config.document_storage_service_url.clone(),);- let connection_gateway_client = connection_gateway_client::client::ConnectionGatewayClient::new(- internal_auth_key.as_ref().to_string(),- config.connection_gateway_url.clone(),- );-let system_properties_service = Arc::new(SystemPropertiesServiceImpl::new(PgSystemPropertiesRepository::new(db.clone()),));- // process user inbox updates from gmail inbox_sync queue, triggered by update pubsub messages from Google- for worker in inbox_sync_workers {- let db_inbox_sync = db.clone();- let sqs_client_inbox_sync = sqs_client.clone();- let gmail_client_inbox_sync = gmail_client.clone();- let auth_service_client_inbox_sync = auth_service_client.clone();- let redis_client_inbox_sync = redis_client.clone();- let macro_notify_client_inbox_sync = macro_notify_client.clone();- let sfs_client_inbox_sync = sfs_client.clone();- let connection_gateway_client_inbox_sync = connection_gateway_client.clone();- let dss_client_inbox_sync = dss_client.clone();- let system_properties_service_inbox_sync = system_properties_service.clone();- tokio::spawn(async move {- pubsub::inbox_sync::worker::run_worker(- db_inbox_sync,- worker,- sqs_client_inbox_sync,- gmail_client_inbox_sync,- auth_service_client_inbox_sync,- redis_client_inbox_sync,- macro_notify_client_inbox_sync,- sfs_client_inbox_sync,- connection_gateway_client_inbox_sync,- dss_client_inbox_sync,- system_properties_service_inbox_sync,- config.notifications_enabled,- false,- )- .await;- });- }- tracing::info!(- num_workers = config.inbox_sync_queue_workers,- "inbox_sync workers started"- );-- // separate queue for retries to avoid backups for large inbox updates that hit gmail api rate limit- for worker in inbox_sync_retry_workers {- let db_inbox_sync = db.clone();- let sqs_client_inbox_sync = sqs_client.clone();- let gmail_client_inbox_sync = gmail_client.clone();- let auth_service_client_inbox_sync = auth_service_client.clone();- let redis_client_inbox_sync = redis_client.clone();- let macro_notify_client_inbox_sync = macro_notify_client.clone();- let sfs_client_inbox_sync = sfs_client.clone();- let connection_gateway_client_inbox_sync = connection_gateway_client.clone();- let dss_client_inbox_sync = dss_client.clone();- let system_properties_service_inbox_sync = system_properties_service.clone();- tokio::spawn(async move {- pubsub::inbox_sync::worker::run_worker(- db_inbox_sync,- worker,- sqs_client_inbox_sync,- gmail_client_inbox_sync,- auth_service_client_inbox_sync,- redis_client_inbox_sync,- macro_notify_client_inbox_sync,- sfs_client_inbox_sync,- connection_gateway_client_inbox_sync,- dss_client_inbox_sync,- system_properties_service_inbox_sync,- config.notifications_enabled,- true,- )- .await;- });- }- tracing::info!(- num_workers = config.inbox_sync_queue_workers,- "inbox_sync workers started"- );-- // backfill user emails upon signup- for worker in backfill_workers {- let db_backfill = db_backfill.clone();- let sqs_client_backfill = sqs_client.clone();- let gmail_client_backfill = gmail_client.clone();- let auth_service_client_backfill = auth_service_client.clone();- let redis_client_backfill = redis_client.clone();- let macro_notify_client_backfill = macro_notify_client.clone();- let sfs_client_backfill = sfs_client.clone();- let connection_gateway_client_backfill = connection_gateway_client.clone();- let dss_client_backfill = dss_client.clone();- let system_properties_service_backfill = system_properties_service.clone();- tokio::spawn(async move {- pubsub::backfill::worker::run_worker(- db_backfill,- worker,- sqs_client_backfill,- gmail_client_backfill,- auth_service_client_backfill,- redis_client_backfill,- macro_notify_client_backfill,- sfs_client_backfill,- connection_gateway_client_backfill,- dss_client_backfill,- system_properties_service_backfill,- config.notifications_enabled,- )- .await;- });- }- tracing::info!(- num_workers = config.backfill_queue_workers,- "backfill workers started"- );-- let db_link_manager = db.clone();- let gmail_client_link_manager = gmail_client.clone();- let auth_service_client_link_manager = auth_service_client.clone();- let redis_client_link_manager = redis_client.clone();- let sqs_client_link_manager = sqs_client.clone();- // daily link_manager operations for user contacts and inbox subscriptions- tokio::spawn(async move {- pubsub::link_manager::worker::run_worker(- link_manager_worker,- db_link_manager,- gmail_client_link_manager,- auth_service_client_link_manager,- redis_client_link_manager,- sqs_client_link_manager,- )- .await;- });-- let db_scheduled = db.clone();- let gmail_client_scheduled = gmail_client.clone();- let auth_service_client_scheduled = auth_service_client.clone();- let redis_client_scheduled = redis_client.clone();- // send scheduled emails- tokio::spawn(async move {- pubsub::scheduled::worker::run_worker(- scheduled_worker,- db_scheduled,- gmail_client_scheduled,- auth_service_client_scheduled,- redis_client_scheduled,- )- .await;- });-- if cfg!(feature = "sfs_map") {- for worker in sfs_uploader_workers {- let db_sfs_uploader = db.clone();- let sfs_client_sfs_uploader = sfs_client.clone();- // upload user contact images to sfs from contact sync- tokio::spawn(async move {- pubsub::sfs_uploader::worker::run_worker(- worker,- db_sfs_uploader,- sfs_client_sfs_uploader,- )- .await;- });- }- tracing::info!(- num_workers = config.sfs_uploader_workers,- "sfs uploader workers started"- );- }-let jwt_args =JwtValidationArgs::new_with_secret_manager(config.environment, &secretsmanager_client).await?;diff --git a/rust/cloud-storage/email_service/src/pubsub/backfill/error_handlers.rs b/rust/cloud-storage/email_service/src/pubsub/backfill/error_handlers.rsindex 2a7bdff91c..6ae1d86b8c 100644--- a/rust/cloud-storage/email_service/src/pubsub/backfill/error_handlers.rs+++ b/rust/cloud-storage/email_service/src/pubsub/backfill/error_handlers.rs@@ -53,23 +53,27 @@ pub async fn handle_non_retryable_error(}/// Handles retryable errors by updating status to InProgress and adding the error message-#[tracing::instrument(skip(_e), err)]+#[tracing::instrument(+ skip(data, _e),+ fields(link_id = %data.link_id, error = tracing::field::Empty)+)]pub async fn handle_retryable_error(data: &BackfillPubsubMessage,_e: &DetailedError,) -> anyhow::Result<()> {let error_chain = format!("{:#}", _e.source);+ tracing::Span::current().record("error", &error_chain);+match &data.backfill_operation {BackfillOperation::Init => {- tracing::debug!(error = %error_chain, "Retryable error in Init")+ tracing::debug!("Retryable error in Init")}BackfillOperation::ListThreads(_) => {- tracing::debug!(error = %error_chain, "Retryable error listing threads")+ tracing::debug!("Retryable error listing threads")}BackfillOperation::BackfillThread(p) => {tracing::debug!(thread_id = %p.thread_provider_id,- error = %error_chain,"Retryable error backfilling thread");}@@ -77,21 +81,18 @@ pub async fn handle_retryable_error(tracing::debug!(thread_id = %p.thread_provider_id,message_id = %p.message_provider_id,- error = %error_chain,"Retryable error backfilling message");}BackfillOperation::UpdateThreadMetadata(p) => {tracing::debug!(thread_id = %p.thread_provider_id,- error = %error_chain,"Retryable error updating thread metadata");}BackfillOperation::BackfillAttachment(p) => {tracing::debug!(attachment_db_id = %p.metadata.attachment_metadata.attachment_db_id,- error = %error_chain,"Retryable error backfilling attachment")}diff --git a/rust/cloud-storage/email_service/src/pubsub/backfill/mod.rs b/rust/cloud-storage/email_service/src/pubsub/backfill/mod.rsindex 183c7df440..4762bcc49b 100644--- a/rust/cloud-storage/email_service/src/pubsub/backfill/mod.rs+++ b/rust/cloud-storage/email_service/src/pubsub/backfill/mod.rs@@ -7,4 +7,4 @@ mod init;mod list_threads;mod process;mod update_metadata;-pub(crate) mod worker;+pub mod worker;diff --git a/rust/cloud-storage/email_service/src/pubsub/inbox_sync/mod.rs b/rust/cloud-storage/email_service/src/pubsub/inbox_sync/mod.rsindex fb443e85c6..59b1da2379 100644--- a/rust/cloud-storage/email_service/src/pubsub/inbox_sync/mod.rs+++ b/rust/cloud-storage/email_service/src/pubsub/inbox_sync/mod.rs@@ -1,4 +1,4 @@mod error_handlers;mod operations;pub(crate) mod process;-pub(crate) mod worker;+pub mod worker;diff --git a/rust/cloud-storage/email_service/src/pubsub/link_manager/mod.rs b/rust/cloud-storage/email_service/src/pubsub/link_manager/mod.rsindex bbea3c6492..4ea0718869 100644--- a/rust/cloud-storage/email_service/src/pubsub/link_manager/mod.rs+++ b/rust/cloud-storage/email_service/src/pubsub/link_manager/mod.rs@@ -1,3 +1,3 @@pub(crate) mod context;pub(crate) mod process;-pub(crate) mod worker;+pub mod worker;diff --git a/rust/cloud-storage/email_service/src/pubsub/mod.rs b/rust/cloud-storage/email_service/src/pubsub/mod.rsindex fef4fbc84a..16fdc901e9 100644--- a/rust/cloud-storage/email_service/src/pubsub/mod.rs+++ b/rust/cloud-storage/email_service/src/pubsub/mod.rs@@ -1,7 +1,7 @@-pub(crate) mod backfill;+pub mod backfill;pub(crate) mod context;-pub(crate) mod inbox_sync;-pub(crate) mod link_manager;-pub(crate) mod scheduled;-pub(crate) mod sfs_uploader;+pub mod inbox_sync;+pub mod link_manager;+pub mod scheduled;+pub mod sfs_uploader;pub(crate) mod util;diff --git a/rust/cloud-storage/email_service/src/pubsub/scheduled/mod.rs b/rust/cloud-storage/email_service/src/pubsub/scheduled/mod.rsindex bbea3c6492..4ea0718869 100644--- a/rust/cloud-storage/email_service/src/pubsub/scheduled/mod.rs+++ b/rust/cloud-storage/email_service/src/pubsub/scheduled/mod.rs@@ -1,3 +1,3 @@pub(crate) mod context;pub(crate) mod process;-pub(crate) mod worker;+pub mod worker;diff --git a/rust/cloud-storage/email_service/src/pubsub/sfs_uploader/mod.rs b/rust/cloud-storage/email_service/src/pubsub/sfs_uploader/mod.rsindex bbea3c6492..4ea0718869 100644--- a/rust/cloud-storage/email_service/src/pubsub/sfs_uploader/mod.rs+++ b/rust/cloud-storage/email_service/src/pubsub/sfs_uploader/mod.rs@@ -1,3 +1,3 @@pub(crate) mod context;pub(crate) mod process;-pub(crate) mod worker;+pub mod worker;diff --git a/rust/cloud-storage/email_service/src/util/process_pre_insert/mod.rs b/rust/cloud-storage/email_service/src/util/process_pre_insert/mod.rsindex 9d453187c6..6802e84e8f 100644--- a/rust/cloud-storage/email_service/src/util/process_pre_insert/mod.rs+++ b/rust/cloud-storage/email_service/src/util/process_pre_insert/mod.rs@@ -22,7 +22,8 @@ pub async fn process_threads_pre_insert(}// perform necessary processing on a message before inserting into the database-#[tracing::instrument(skip(db, sfs_client, message), fields(message_id = %message.provider_id.clone().unwrap_or_default()))]+#[tracing::instrument(skip(db, sfs_client, message), fields(message_id = %message.provider_id.clone().unwrap_or_default()+))]pub async fn process_message_pre_insert(db: &sqlx::PgPool,sfs_client: &StaticFileServiceClient,diff --git a/rust/cloud-storage/email_service/src/util/upload_attachment.rs b/rust/cloud-storage/email_service/src/util/upload_attachment.rsindex d10711c2ef..8cd91959e8 100644--- a/rust/cloud-storage/email_service/src/util/upload_attachment.rs+++ b/rust/cloud-storage/email_service/src/util/upload_attachment.rs@@ -74,7 +74,6 @@ pub struct UploadAttachmentContext<'a> {}/// Upload an email attachment to DSS as a document or SFS as media.-#[tracing::instrument(skip(ctx), err)]pub async fn upload_attachment(ctx: UploadAttachmentContext<'_>,args: &AttachmentUploadArgs,