Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(contacts): migrate contacts service to gateway (#6140)
Will Hutchinsonfc2efd3c261b
diff --git a/apps/web/scripts/services.ts b/apps/web/scripts/services.tsindex 45420722cd..daed0c089f 100644--- a/apps/web/scripts/services.ts+++ b/apps/web/scripts/services.ts@@ -66,8 +66,8 @@ export const services: Service[] = [},{name: "contacts-service",- dev: "https://contacts-dev.macro.com/api-doc/openapi.json",- prod: "https://contacts.macro.com/api-doc/openapi.json",+ dev: "https://dev-gateway.macro.com/contacts/api-doc/openapi.json",+ prod: "https://gateway.macro.com/contacts/api-doc/openapi.json",local: "http://localhost:8083/api-doc/openapi.json",output: "../src/lib/service-clients/service-contacts/",orvalKey: "contactService",diff --git a/apps/web/src/lib/core/constant/servers.ts b/apps/web/src/lib/core/constant/servers.tsindex b89568b43f..14089b5191 100644--- a/apps/web/src/lib/core/constant/servers.ts+++ b/apps/web/src/lib/core/constant/servers.ts@@ -39,7 +39,7 @@ const serverHostRemote = {'notification-service': `${gatewayHost}/notification`,'static-file': `https://static-file-service${devServerSuffix}.macro.com`,'unfurl-service': `${gatewayHost}/unfurl`,- contacts: `https://contacts${devServerSuffix}.macro.com`,+ contacts: `${gatewayHost}/contacts`,'email-service': `https://email-service${devServerSuffix}.macro.com`,'image-proxy-service': `https://image-proxy${devServerSuffix}.macro.com`,'scheduled-action': `https://agent-schedule${devServerSuffix}.macro.com`,diff --git a/crates/macro_service_urls/src/lib.rs b/crates/macro_service_urls/src/lib.rsindex 3dc891846b..c24066da76 100644--- a/crates/macro_service_urls/src/lib.rs+++ b/crates/macro_service_urls/src/lib.rs@@ -558,8 +558,8 @@ service_url! {/// Contacts service API URL.pub ContactsServiceUrl {local: "http://localhost:8083",- dev: "https://contacts-dev.macro.com",- prod: "https://contacts.macro.com",+ dev: "https://dev-gateway.macro.com/contacts",+ prod: "https://gateway.macro.com/contacts",},/// Email service API URL.pub EmailServiceUrl {diff --git a/crates/macro_service_urls/src/test.rs b/crates/macro_service_urls/src/test.rsindex a05a9debf7..ba4a90a15a 100644--- a/crates/macro_service_urls/src/test.rs+++ b/crates/macro_service_urls/src/test.rs@@ -82,6 +82,18 @@ fn contacts_service_url_parses() {assert_parses_for_all_environments(ContactsServiceUrl::default_for_environment);}+#[test]+fn contacts_service_url_has_no_trailing_slash() {+ for environment in ENVS {+ let url = ContactsServiceUrl::default_for_environment(environment);+ assert!(+ !url.as_ref().ends_with('/'),+ "clients concatenate paths, so {} must not end with /",+ url.as_ref()+ );+ }+}+#[test]fn email_service_url_parses() {assert_parses_for_all_environments(EmailServiceUrl::default_for_environment);@@ -348,7 +360,7 @@ fn exported_service_urls_match_dev_values() {);assert_eq!(service_urls.contacts_service_url.as_ref(),- "https://contacts-dev.macro.com",+ "https://dev-gateway.macro.com/contacts",);assert_eq!(service_urls.email_service_url.as_ref(),@@ -407,7 +419,7 @@ fn exported_service_urls_match_prod_values() {);assert_eq!(service_urls.contacts_service_url.as_ref(),- "https://contacts.macro.com",+ "https://gateway.macro.com/contacts",);assert_eq!(service_urls.email_service_url.as_ref(),diff --git a/infra/packages/shared/src/gateway_priorities.ts b/infra/packages/shared/src/gateway_priorities.tsindex 613b9db884..a7ed43a5eb 100644--- a/infra/packages/shared/src/gateway_priorities.ts+++ b/infra/packages/shared/src/gateway_priorities.ts@@ -7,6 +7,7 @@ export enum GatewayService {UNFURL_SERVICE = 'UNFURL_SERVICE',CONVERT_SERVICE = 'CONVERT_SERVICE',NOTIFICATION_SERVICE = 'NOTIFICATION_SERVICE',+ CONTACTS_SERVICE = 'CONTACTS_SERVICE',}/**@@ -22,6 +23,7 @@ export const GATEWAY_PRIORITIES: GatewayPriorityMap = {[GatewayService.DOCUMENT_STORAGE_SERVICE]: 10,[GatewayService.UNFURL_SERVICE]: 20,[GatewayService.NOTIFICATION_SERVICE]: 30,+ [GatewayService.CONTACTS_SERVICE]: 40,[GatewayService.CONVERT_SERVICE]: 3000,};diff --git a/infra/stacks/contacts-service/index.ts b/infra/stacks/contacts-service/index.tsindex 2e2a2b2618..be98fe97d8 100644--- a/infra/stacks/contacts-service/index.ts+++ b/infra/stacks/contacts-service/index.ts@@ -1,7 +1,12 @@import * as aws from '@pulumi/aws';import * as pulumi from '@pulumi/pulumi';import { Queue } from '../../packages/resources';-import { config, getMacroApiToken, stack } from '../../packages/shared';+import {+ BASE_DOMAIN,+ config,+ getMacroApiToken,+ stack,+} from '../../packages/shared';import { get_coparse_api_vpc } from '../../packages/vpc';import { ContactsService } from './service';@@ -61,7 +66,7 @@ const cloudStorageClusterName: pulumi.Output<string> = cloudStorageStack.getOutput('cloudStorageClusterName').apply((arn) => arn as string);-const contactsService = new ContactsService('contacts-service', {+new ContactsService('contacts-service', {contactsQueueArn,vpc: coparse_api_vpc,tags,@@ -75,4 +80,6 @@ const contactsService = new ContactsService('contacts-service', {secretKeyArns,});-export const contactsServiceUrl = pulumi.interpolate`${contactsService.domain}`;+export const contactsServiceUrl = `https://${+ stack === 'prod' ? '' : `${stack}-`+}gateway.${BASE_DOMAIN}/contacts`;diff --git a/infra/stacks/contacts-service/service.ts b/infra/stacks/contacts-service/service.tsindex 438521723a..c7958eba8b 100644--- a/infra/stacks/contacts-service/service.ts+++ b/infra/stacks/contacts-service/service.ts@@ -8,15 +8,20 @@ import {datadogAgentContainer,fargateLogRouterSidecarContainer,serviceLoadBalancer,+ ServiceTargetGroup,} from '../../packages/resources';import { EcrImage } from '../../packages/service';import {BASE_DOMAIN,CLOUD_TRAIL_SNS_TOPIC_ARN,DopplerEcsEnvironment,+ getGatewayAlb,+ GatewayService,stack,} from '../../packages/shared';+const gatewayLoadBalancer = getGatewayAlb();+const BASE_NAME = pulumi.getProject();const REPO_ROOT = '../../..';export const SERVICE_DOMAIN_NAME = `contacts${@@ -168,6 +173,22 @@ export class ContactsService extends pulumi.ComponentResource {this.serviceAlbSg = sg.serviceAlbSg;this.serviceSg = sg.serviceSg;+ const gatewayTargetGroup = new ServiceTargetGroup(+ `${stack}-${BASE_NAME}`,+ {+ tags: this.tags,+ listenerArn: gatewayLoadBalancer.httpsListenerArn,+ vpcId: vpc.vpcId,+ containerPort: serviceContainerPort,+ service: GatewayService.CONTACTS_SERVICE,+ healthCheckPath,+ pathPatterns: ['/contacts', '/contacts/*'],+ serviceSecurityGroupId: this.serviceSg.id,+ albSecurityGroupId: gatewayLoadBalancer.albSecurityGroupId,+ },+ { parent: this }+ );+// Load balancerconst { targetGroup, lb, listener } = serviceLoadBalancer(this, {serviceName: BASE_NAME, // service name@@ -203,6 +224,23 @@ export class ContactsService extends pulumi.ComponentResource {enable: true,rollback: true,},+ // Register tasks in both the legacy ALB's target group and the gateway+ // target group while we migrate to the gateway. An explicit+ // `loadBalancers` replaces the list awsx derives from+ // `portMappings.targetGroup`, so the legacy entry must be listed here+ // too.+ loadBalancers: [+ {+ targetGroupArn: targetGroup.arn,+ containerName: 'service',+ containerPort: serviceContainerPort,+ },+ {+ targetGroupArn: gatewayTargetGroup.target_group.arn,+ containerName: 'service',+ containerPort: serviceContainerPort,+ },+ ],taskDefinitionArgs: {taskRole: {roleArn: this.role.arn,@@ -267,12 +305,19 @@ export class ContactsService extends pulumi.ComponentResource {},{parent: this,+ // ECS refuses a service whose target group is not yet associated with+ // a load balancer; it is the listener rule that creates that+ // association+ dependsOn: [gatewayTargetGroup.listener_rule],});this.service = service;// auto-scaling and alarm notifications- this.setupAutoScaling();+ this.setupAutoScaling({+ gatewayAlbArnSuffix: gatewayLoadBalancer.albArnSuffix,+ gatewayTargetGroup: gatewayTargetGroup.target_group,+ });this.setupServiceAlarms();// DNS@@ -397,7 +442,13 @@ export class ContactsService extends pulumi.ComponentResource {return { serviceAlbSg, serviceSg };}- setupAutoScaling() {+ setupAutoScaling({+ gatewayAlbArnSuffix,+ gatewayTargetGroup,+ }: {+ gatewayAlbArnSuffix: pulumi.Output<string>;+ gatewayTargetGroup: aws.lb.TargetGroup;+ }) {if (!this.service) return;const serviceScalableTarget = new aws.appautoscaling.Target(@@ -413,19 +464,7 @@ export class ContactsService extends pulumi.ComponentResource {{ parent: this });- const lbPortion: pulumi.Output<string> = this.lb.arn.apply((arn) => {- const parts = arn.split(':loadbalancer/');- return parts[1];- });-- const tgPortion: pulumi.Output<string> = this.targetGroup.arn.apply(- (arn) => {- const parts = arn.split(':');- return parts[parts.length - 1];- }- );-- const resourceLabel = pulumi.interpolate`${lbPortion}/${tgPortion}`;+ const resourceLabel = pulumi.interpolate`${gatewayAlbArnSuffix}/${gatewayTargetGroup.arnSuffix}`;// Create an Auto Scaling policy for request count.new aws.appautoscaling.Policy(diff --git a/packages/sdk/src/config.ts b/packages/sdk/src/config.tsindex 4b048c55e6..9f684cb8ef 100644--- a/packages/sdk/src/config.ts+++ b/packages/sdk/src/config.ts@@ -36,7 +36,7 @@ export const HOSTS: Record<Env, Record<ServiceName, string>> = {'scheduled-action': 'https://agent-schedule-dev.macro.com','static-files': 'https://static-file-service-dev.macro.com',connection: 'https://connection-gateway-dev.macro.com',- contacts: 'https://contacts-dev.macro.com',+ contacts: 'https://dev-gateway.macro.com/contacts',unfurl: 'https://dev-gateway.macro.com/unfurl',},prod: {@@ -51,7 +51,7 @@ export const HOSTS: Record<Env, Record<ServiceName, string>> = {'scheduled-action': 'https://agent-schedule.macro.com','static-files': 'https://static-file-service.macro.com',connection: 'https://connection-gateway.macro.com',- contacts: 'https://contacts.macro.com',+ contacts: 'https://gateway.macro.com/contacts',unfurl: 'https://gateway.macro.com/unfurl',},local: {diff --git a/services/contacts_service/src/main.rs b/services/contacts_service/src/main.rsindex 798ba44d00..b872238701 100644--- a/services/contacts_service/src/main.rs+++ b/services/contacts_service/src/main.rs@@ -4,6 +4,7 @@ mod health;use std::sync::Arc;use anyhow::Context;+use axum::Router;use config::{Config, Environment};use contacts::domain::service::{ContactsDomainService, ContactsOutboxServiceImpl};use contacts::inbound::http::{ApiDoc, ContactsRouterState, contacts_router};@@ -132,14 +133,19 @@ async fn main() -> anyhow::Result<()> {let cors = macro_cors::cors_layer();let port = config.port;- let app = contacts_router(ContactsRouterState {- contacts_service: service,- rate_limit_service,- authorization_state,- })- .layer(cors.clone())- .merge(health::router().layer(cors))- .merge(SwaggerUi::new("/docs").url("/api-doc/openapi.json", ApiDoc::openapi()));+ let app = mount_at_root_and_prefix(+ contacts_router(ContactsRouterState {+ contacts_service: service,+ rate_limit_service,+ authorization_state,+ })+ .layer(cors.clone())+ .merge(health::router().layer(cors)),+ )+ .merge(SwaggerUi::new("/docs").url("/api-doc/openapi.json", ApiDoc::openapi()))+ .merge(+ SwaggerUi::new("/contacts/docs").url("/contacts/api-doc/openapi.json", ApiDoc::openapi()),+ );let listener = tokio::net::TcpListener::bind(format!("0.0.0.0:{}", port)).await@@ -152,3 +158,16 @@ async fn main() -> anyhow::Result<()> {.context("error starting service")?;Ok(())}++/// Path prefix the shared gateway ALB forwards unmodified. Dual-mounted+/// alongside `/` so the dedicated ALB keeps working during cutover.+const GATEWAY_PATH_PREFIX: &str = "/contacts";++fn mount_at_root_and_prefix(inner: Router) -> Router {+ Router::new()+ .merge(inner.clone())+ .nest(GATEWAY_PATH_PREFIX, inner)+}++#[cfg(test)]+mod test;diff --git a/services/contacts_service/src/test.rs b/services/contacts_service/src/test.rsnew file mode 100644index 0000000000..784d11a8ba--- /dev/null+++ b/services/contacts_service/src/test.rs@@ -0,0 +1,40 @@+use super::{health, mount_at_root_and_prefix};+use axum::{+ body::Body,+ http::{Request, StatusCode},+};+use tower::ServiceExt;++#[tokio::test]+async fn health_is_reachable_at_root_and_gateway_prefix() {+ for path in ["/health", "/contacts/health"] {+ let response = mount_at_root_and_prefix(health::router())+ .oneshot(+ Request::builder()+ .uri(path)+ .method("GET")+ .body(Body::empty())+ .unwrap(),+ )+ .await+ .unwrap();++ assert_eq!(response.status(), StatusCode::OK, "{path}");+ }+}++#[tokio::test]+async fn unprefixed_unknown_path_is_not_rewritten_onto_the_prefix() {+ let response = mount_at_root_and_prefix(health::router())+ .oneshot(+ Request::builder()+ .uri("/missing")+ .method("GET")+ .body(Body::empty())+ .unwrap(),+ )+ .await+ .unwrap();++ assert_eq!(response.status(), StatusCode::NOT_FOUND);+}