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(notification): migrate notification service to gateway (#6135)

Will Hutchinson7884b0026037
diff --git a/apps/web/scripts/services.ts b/apps/web/scripts/services.ts
index 26bd757c97..45420722cd 100644
--- a/apps/web/scripts/services.ts
+++ b/apps/web/scripts/services.ts
@@ -42,8 +42,8 @@ export const services: Service[] = [
},
{
name: "notification-service",
- dev: "https://notifications-dev.macro.com/api-doc/openapi.json",
- prod: "https://notifications.macro.com/api-doc/openapi.json",
+ dev: "https://dev-gateway.macro.com/notification/api-doc/openapi.json",
+ prod: "https://gateway.macro.com/notification/api-doc/openapi.json",
local: "http://localhost:8089/api-doc/openapi.json",
output: "../src/lib/service-clients/service-notification/",
orvalKey: "notificationService",
diff --git a/apps/web/src/lib/core/constant/servers.ts b/apps/web/src/lib/core/constant/servers.ts
index 7a830a7eee..b89568b43f 100644
--- a/apps/web/src/lib/core/constant/servers.ts
+++ b/apps/web/src/lib/core/constant/servers.ts
@@ -18,9 +18,6 @@ const serverHostLocal: Servers = {
const devServerSuffix = import.meta.env.MODE === 'development' ? '-dev' : '';
-// The shared gateway ALB fronts DSS (`/dss`) and unfurl (`/unfurl`). Unlike
-// the other services it is named with a `dev-` prefix rather than a `-dev`
-// suffix, so it cannot reuse `devServerSuffix`.
const gatewayHost =
import.meta.env.MODE === 'development'
? 'https://dev-gateway.macro.com'
@@ -39,7 +36,7 @@ const serverHostRemote = {
'websocket-service': `wss://services${devServerSuffix}.macro.com`,
'cognition-service': `https://document-cognition${devServerSuffix}.macro.com`,
'connection-gateway': `wss://connection-gateway${devServerSuffix}.macro.com`,
- 'notification-service': `https://notifications${devServerSuffix}.macro.com`,
+ 'notification-service': `${gatewayHost}/notification`,
'static-file': `https://static-file-service${devServerSuffix}.macro.com`,
'unfurl-service': `${gatewayHost}/unfurl`,
contacts: `https://contacts${devServerSuffix}.macro.com`,
diff --git a/crates/email_formatting/src/lib.rs b/crates/email_formatting/src/lib.rs
index 5444b9ad2f..1e4e3a6856 100644
--- a/crates/email_formatting/src/lib.rs
+++ b/crates/email_formatting/src/lib.rs
@@ -7,14 +7,19 @@ use macro_user_id::cowlike::CowLike;
use model_notifications::NotifEvent;
use notification::domain::models::{
Notification, NotificationExtEmail, NotificationTitle, RateLimitConfig, RateLimitKey,
- UserNotificationRow, email_notification_digest::ports::DigestBatch,
- queue_message::EmailContent, signing::SignedUrl,
+ UserNotificationRow,
+ email_notification_digest::ports::DigestBatch,
+ queue_message::EmailContent,
+ signing::{self, SignedUrl},
};
use rootcause::{Report, report};
use serde::{Deserialize, Serialize};
use sha2::Sha256;
use std::time::Duration;
+#[cfg(test)]
+mod test;
+
#[derive(Template)]
#[template(path = "digest.html")]
struct DigestTemplate {
@@ -106,11 +111,13 @@ impl EmailDigestNotification {
}
let num_truncated = input_len - preview_len;
- let mut unsubscribe_url = NotificationServiceUrl::new_for_environment(env)?.parse_url()?;
- unsubscribe_url.set_path(&format!(
- "/user_notifications/preferences/{}/disable",
- Self::TYPE_NAME
- ));
+ let mut unsubscribe_url = signing::append_path(
+ NotificationServiceUrl::new_for_environment(env)?.parse_url()?,
+ &format!(
+ "/user_notifications/preferences/{}/disable",
+ Self::TYPE_NAME
+ ),
+ );
unsubscribe_url
.query_pairs_mut()
.append_pair("id", digest.user_id.as_ref())
diff --git a/crates/email_formatting/src/test.rs b/crates/email_formatting/src/test.rs
new file mode 100644
index 0000000000..93547bf7df
--- /dev/null
+++ b/crates/email_formatting/src/test.rs
@@ -0,0 +1,45 @@
+use super::*;
+use hmac::Mac;
+use sha2::Sha256;
+
+#[test]
+fn unsubscribe_url_keeps_gateway_prefix() {
+ let url = signing::append_path(
+ NotificationServiceUrl::default_for_environment(Environment::Production)
+ .parse_url()
+ .unwrap(),
+ "/user_notifications/preferences/email-digest-notification/disable",
+ );
+ assert_eq!(
+ url.as_str(),
+ "https://gateway.macro.com/notification/user_notifications/preferences/email-digest-notification/disable"
+ );
+}
+
+#[test]
+fn signed_unsubscribe_roundtrips_against_request_url() {
+ let secret = Hmac::<Sha256>::new_from_slice(b"test-secret").unwrap();
+ let mut unsigned = signing::append_path(
+ NotificationServiceUrl::default_for_environment(Environment::Production)
+ .parse_url()
+ .unwrap(),
+ "/user_notifications/preferences/email-digest-notification/disable",
+ );
+ unsigned
+ .query_pairs_mut()
+ .append_pair("id", "macro|[email protected]");
+ let signed = SignedUrl::new(unsigned, secret.clone());
+
+ let reconstructed =
+ signing::public_request_url("https", "gateway.macro.com", signed.as_ref().path()).unwrap();
+ let mut to_verify = reconstructed;
+ to_verify.set_query(signed.as_ref().query());
+
+ assert!(SignedUrl::verify(to_verify, secret).is_some());
+ assert!(
+ signed
+ .as_ref()
+ .as_str()
+ .contains("/notification/user_notifications/")
+ );
+}
diff --git a/crates/macro_service_urls/src/lib.rs b/crates/macro_service_urls/src/lib.rs
index f0534e9923..3dc891846b 100644
--- a/crates/macro_service_urls/src/lib.rs
+++ b/crates/macro_service_urls/src/lib.rs
@@ -533,8 +533,8 @@ service_url! {
/// Notification service API URL.
pub NotificationServiceUrl {
local: "http://localhost:8089",
- dev: "https://notifications-dev.macro.com",
- prod: "https://notifications.macro.com",
+ dev: "https://dev-gateway.macro.com/notification",
+ prod: "https://gateway.macro.com/notification",
},
/// Static file service/CDN URL.
pub StaticFileServiceUrl {
diff --git a/crates/macro_service_urls/src/test.rs b/crates/macro_service_urls/src/test.rs
index ec5c346236..a05a9debf7 100644
--- a/crates/macro_service_urls/src/test.rs
+++ b/crates/macro_service_urls/src/test.rs
@@ -336,7 +336,7 @@ fn exported_service_urls_match_dev_values() {
);
assert_eq!(
service_urls.notification_service_url.as_ref(),
- "https://notifications-dev.macro.com",
+ "https://dev-gateway.macro.com/notification",
);
assert_eq!(
service_urls.static_file_service_url.as_ref(),
@@ -395,7 +395,7 @@ fn exported_service_urls_match_prod_values() {
);
assert_eq!(
service_urls.notification_service_url.as_ref(),
- "https://notifications.macro.com",
+ "https://gateway.macro.com/notification",
);
assert_eq!(
service_urls.static_file_service_url.as_ref(),
diff --git a/crates/notification/src/domain/models/signing.rs b/crates/notification/src/domain/models/signing.rs
index 970ea2d9b2..bd8f2009bc 100644
--- a/crates/notification/src/domain/models/signing.rs
+++ b/crates/notification/src/domain/models/signing.rs
@@ -1,7 +1,7 @@
use hmac::{Hmac, Mac};
use sha2::Sha256;
use std::borrow::Cow;
-use url::Url;
+use url::{ParseError, Url};
#[cfg(test)]
mod test;
@@ -9,6 +9,28 @@ mod test;
/// The query parameter name used to store the HMAC signature.
const SIG_PARAM: &str = "sig";
+/// Append `path` onto `base` without discarding `base`'s existing path.
+pub fn append_path(mut base: Url, path: &str) -> Url {
+ let prefix = base.path().trim_end_matches('/');
+ let suffix = path.trim_start_matches('/');
+ base.set_path(&format!("{prefix}/{suffix}"));
+ base
+}
+
+/// Rebuild the public URL the client requested.
+pub fn public_request_url(
+ scheme: &str,
+ host: &str,
+ path_and_query: &str,
+) -> Result<Url, ParseError> {
+ let path_and_query = if path_and_query.starts_with('/') {
+ Cow::Borrowed(path_and_query)
+ } else {
+ Cow::Owned(format!("/{path_and_query}"))
+ };
+ Url::parse(&format!("{scheme}://{host}{path_and_query}"))
+}
+
/// A wrapper over url which is guaranteed to be a cryptographically signed url.
/// The signature exists as a query param under "sig".
pub struct SignedUrl(Url);
diff --git a/crates/notification/src/domain/models/signing/test.rs b/crates/notification/src/domain/models/signing/test.rs
index 8323a0a517..221a6dedfa 100644
--- a/crates/notification/src/domain/models/signing/test.rs
+++ b/crates/notification/src/domain/models/signing/test.rs
@@ -45,3 +45,85 @@ fn verify_returns_none_when_no_sig_param() {
let url = Url::parse("https://example.com/path").unwrap();
assert!(SignedUrl::verify(url, secret).is_none());
}
+
+#[test]
+fn append_path_keeps_gateway_prefix() {
+ let base = Url::parse("https://gateway.macro.com/notification").unwrap();
+ let joined = append_path(
+ base,
+ "/user_notifications/preferences/email-digest-notification/disable",
+ );
+ assert_eq!(
+ joined.as_str(),
+ "https://gateway.macro.com/notification/user_notifications/preferences/email-digest-notification/disable"
+ );
+}
+
+#[test]
+fn append_path_on_host_only_base_matches_legacy_route() {
+ let base = Url::parse("https://notifications.macro.com").unwrap();
+ let joined = append_path(
+ base,
+ "/user_notifications/preferences/email-digest-notification/disable",
+ );
+ assert_eq!(
+ joined.as_str(),
+ "https://notifications.macro.com/user_notifications/preferences/email-digest-notification/disable"
+ );
+}
+
+#[test]
+fn set_path_and_join_drop_gateway_prefix() {
+ let mut set_path_url = Url::parse("https://gateway.macro.com/notification").unwrap();
+ set_path_url.set_path("/user_notifications/preferences/x/disable");
+ assert_eq!(
+ set_path_url.as_str(),
+ "https://gateway.macro.com/user_notifications/preferences/x/disable"
+ );
+
+ let joined = Url::parse("https://gateway.macro.com/notification")
+ .unwrap()
+ .join("/user_notifications/preferences/x/disable")
+ .unwrap();
+ assert_eq!(
+ joined.as_str(),
+ "https://gateway.macro.com/user_notifications/preferences/x/disable"
+ );
+}
+
+#[test]
+fn public_request_url_uses_request_host_and_full_path() {
+ let legacy = public_request_url(
+ "https",
+ "notifications.macro.com",
+ "/user_notifications/preferences/x/disable?id=macro%7Cuser",
+ )
+ .unwrap();
+ assert_eq!(
+ legacy.as_str(),
+ "https://notifications.macro.com/user_notifications/preferences/x/disable?id=macro%7Cuser"
+ );
+
+ let gateway = public_request_url(
+ "https",
+ "gateway.macro.com",
+ "/notification/user_notifications/preferences/x/disable?id=macro%7Cuser",
+ )
+ .unwrap();
+ assert_eq!(
+ gateway.as_str(),
+ "https://gateway.macro.com/notification/user_notifications/preferences/x/disable?id=macro%7Cuser"
+ );
+}
+
+#[test]
+fn signed_url_roundtrips_on_both_public_hosts() {
+ let secret = make_secret(b"test-secret");
+ for raw in [
+ "https://notifications.macro.com/user_notifications/preferences/x/disable?id=u",
+ "https://gateway.macro.com/notification/user_notifications/preferences/x/disable?id=u",
+ ] {
+ let signed = SignedUrl::new(Url::parse(raw).unwrap(), secret.clone());
+ assert!(SignedUrl::verify(signed.as_ref().clone(), secret.clone()).is_some());
+ }
+}
diff --git a/crates/notification/src/inbound/http/preferences.rs b/crates/notification/src/inbound/http/preferences.rs
index 33cb21c501..c8b6b34669 100644
--- a/crates/notification/src/inbound/http/preferences.rs
+++ b/crates/notification/src/inbound/http/preferences.rs
@@ -3,7 +3,7 @@
use axum::{
Json,
extract::{OriginalUri, Path, Query, State},
- http::{StatusCode, uri::PathAndQuery},
+ http::{HeaderMap, StatusCode, header, uri::PathAndQuery},
response::Html,
};
use macro_authorization::{MacroAuthorizationExtractor, MacroAuthorizationService, UserOrInternal};
@@ -13,7 +13,10 @@ use model_error_response::ErrorResponse;
use serde::{Deserialize, Serialize};
use utoipa::ToSchema;
-use crate::domain::{models::signing::SignedUrl, service::NotificationReader};
+use crate::domain::{
+ models::signing::{self, SignedUrl},
+ service::NotificationReader,
+};
use super::NotificationRouterState;
@@ -120,6 +123,7 @@ pub async fn presigned_disable_notification_type<
notification_event_type,
}): Path<NotificationEventTypePath>,
Query(params): Query<PresignedQueryParams>,
+ headers: HeaderMap,
original_uri: OriginalUri,
) -> Result<Html<String>, (StatusCode, Html<String>)> {
let notification_service_url = NotificationServiceUrl::new().map_err(|err| {
@@ -136,16 +140,20 @@ pub async fn presigned_disable_notification_type<
Html("Invalid link".to_string()),
)
})?;
- let to_verify = notification_service_url.join(
+ let host = headers
+ .get(header::HOST)
+ .and_then(|value| value.to_str().ok())
+ .or_else(|| notification_service_url.host_str())
+ .ok_or_else(|| (StatusCode::BAD_REQUEST, Html("Invalid link".to_string())))?;
+ let to_verify = signing::public_request_url(
+ notification_service_url.scheme(),
+ host,
original_uri
.path_and_query()
.map(PathAndQuery::as_str)
.unwrap_or("/"),
- );
-
- let Ok(to_verify) = to_verify else {
- return Err((StatusCode::BAD_REQUEST, Html("Invalid link".to_string())));
- };
+ )
+ .map_err(|_| (StatusCode::BAD_REQUEST, Html("Invalid link".to_string())))?;
let Some(_verified) = SignedUrl::verify(to_verify, state.hmac_signing_key.clone()) else {
return Err((
diff --git a/crates/notification/src/inbound/http/test.rs b/crates/notification/src/inbound/http/test.rs
index 6ca074fc2b..b5a529449e 100644
--- a/crates/notification/src/inbound/http/test.rs
+++ b/crates/notification/src/inbound/http/test.rs
@@ -686,8 +686,7 @@ impl NotificationReader for PresignedTestService {
const HMAC_KEY: &[u8] = b"test-key";
-/// The base URL that `Environment::new_or_prod()` (Production) resolves to.
-const NOTIFICATION_BASE_URL: &str = "https://notifications.macro.com";
+const LEGACY_NOTIFICATION_ORIGIN: &str = "https://notifications.macro.com";
fn presigned_router() -> Router {
let hmac_key = Hmac::<Sha256>::new_from_slice(HMAC_KEY).unwrap();
@@ -699,44 +698,51 @@ fn presigned_router() -> Router {
authorization_state,
);
- Router::new()
+ let inner = Router::new()
.nest(
"/user_notifications",
super::router::<PresignedTestService, FakeAuthorizationService, serde_json::Value>(),
)
- .with_state(state)
+ .with_state(state);
+ Router::new()
+ .merge(inner.clone())
+ .nest("/notification", inner)
}
-/// Build a presigned disable URL path+query for use as a request URI.
-///
-/// Signs the full absolute URL (`https://notifications.macro.com/...`) and
-/// returns only the path+query portion (e.g. `/user_notifications/preferences/...?id=...&sig=...`).
-fn signed_disable_uri(notification_type: &str, user_id: &str) -> String {
+fn signed_disable_uri_at(origin: &str, notification_type: &str, user_id: &str) -> String {
let hmac_key = Hmac::<Sha256>::new_from_slice(HMAC_KEY).unwrap();
- let mut unsigned = url::Url::parse(&format!(
- "{NOTIFICATION_BASE_URL}/user_notifications/preferences/{notification_type}/disable"
- ))
- .unwrap();
- // Use query_pairs_mut so the encoding matches what SignedUrl::verify expects
- // (application/x-www-form-urlencoded round-trip).
+ let mut unsigned = crate::domain::models::signing::append_path(
+ url::Url::parse(origin).unwrap(),
+ &format!("/user_notifications/preferences/{notification_type}/disable"),
+ );
unsigned.query_pairs_mut().append_pair("id", user_id);
let signed = SignedUrl::new(unsigned, hmac_key);
let signed_url = signed.as_ref();
- // Return path + query for use as request URI
format!("{}?{}", signed_url.path(), signed_url.query().unwrap())
}
+fn signed_disable_uri(notification_type: &str, user_id: &str) -> String {
+ signed_disable_uri_at(LEGACY_NOTIFICATION_ORIGIN, notification_type, user_id)
+}
+
+fn presigned_get(uri: &str, host: &str) -> Request<axum::body::Body> {
+ Request::builder()
+ .uri(uri)
+ .method("GET")
+ .header("host", host)
+ .body(axum::body::Body::empty())
+ .unwrap()
+}
+
#[tokio::test]
async fn presigned_disable_succeeds_without_jwt() {
let router = presigned_router();
let uri = signed_disable_uri("test_type", "macro|[email protected]");
- let req = Request::builder()
- .uri(&uri)
- .method("GET")
- .body(axum::body::Body::empty())
+ let resp = router
+ .oneshot(presigned_get(&uri, "notifications.macro.com"))
+ .await
.unwrap();
- let resp = router.oneshot(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let body = resp.into_body().collect().await.unwrap().to_bytes();
@@ -753,13 +759,24 @@ async fn presigned_disable_succeeds_with_valid_hmac() {
let uri = signed_disable_uri("test_type", "macro|[email protected]");
let resp = router
- .oneshot(
- Request::builder()
- .uri(&uri)
- .method("GET")
- .body(axum::body::Body::empty())
- .unwrap(),
- )
+ .oneshot(presigned_get(&uri, "notifications.macro.com"))
+ .await
+ .unwrap();
+
+ assert_eq!(resp.status(), StatusCode::OK);
+}
+
+#[tokio::test]
+async fn presigned_disable_succeeds_on_gateway_prefix() {
+ let router = presigned_router();
+ let uri = signed_disable_uri_at(
+ "https://gateway.macro.com/notification",
+ "test_type",
+ );
+
+ let resp = router
+ .oneshot(presigned_get(&uri, "gateway.macro.com"))
.await
.unwrap();
diff --git a/infra/packages/shared/src/gateway_priorities.ts b/infra/packages/shared/src/gateway_priorities.ts
index 393b25b59a..613b9db884 100644
--- a/infra/packages/shared/src/gateway_priorities.ts
+++ b/infra/packages/shared/src/gateway_priorities.ts
@@ -6,6 +6,7 @@ export enum GatewayService {
DOCUMENT_STORAGE_SERVICE = 'DOCUMENT_STORAGE_SERVICE',
UNFURL_SERVICE = 'UNFURL_SERVICE',
CONVERT_SERVICE = 'CONVERT_SERVICE',
+ NOTIFICATION_SERVICE = 'NOTIFICATION_SERVICE',
}
/**
@@ -20,6 +21,7 @@ type GatewayPriorityMap = { [K in GatewayService]: number };
export const GATEWAY_PRIORITIES: GatewayPriorityMap = {
[GatewayService.DOCUMENT_STORAGE_SERVICE]: 10,
[GatewayService.UNFURL_SERVICE]: 20,
+ [GatewayService.NOTIFICATION_SERVICE]: 30,
[GatewayService.CONVERT_SERVICE]: 3000,
};
diff --git a/infra/packages/shared/src/service_urls.ts b/infra/packages/shared/src/service_urls.ts
index d2c4ed0fca..8fcc0e740c 100644
--- a/infra/packages/shared/src/service_urls.ts
+++ b/infra/packages/shared/src/service_urls.ts
@@ -32,7 +32,8 @@ const DEV_SERVICE_URLS: ServiceUrlMap = {
[ServiceUrl.EMAIL_SERVICE_URL]: 'https://email-service-dev.macro.com',
[ServiceUrl.STATIC_FILE_SERVICE_URL]:
'https://static-file-service-dev.macro.com',
- [ServiceUrl.NOTIFICATION_SERVICE_URL]: 'https://notifications-dev.macro.com',
+ [ServiceUrl.NOTIFICATION_SERVICE_URL]:
+ 'https://dev-gateway.macro.com/notification',
[ServiceUrl.AUTHENTICATION_SERVICE_URL]: 'https://auth-service-dev.macro.com',
[ServiceUrl.DOCUMENT_STORAGE_SERVICE_URL]:
'https://dev-gateway.macro.com/dss',
@@ -53,7 +54,8 @@ const PROD_SERVICE_URLS: ServiceUrlMap = {
'https://sync-service-prod2.macroverse.workers.dev',
[ServiceUrl.EMAIL_SERVICE_URL]: 'https://email-service.macro.com',
[ServiceUrl.STATIC_FILE_SERVICE_URL]: 'https://static-file-service.macro.com',
- [ServiceUrl.NOTIFICATION_SERVICE_URL]: 'https://notifications.macro.com',
+ [ServiceUrl.NOTIFICATION_SERVICE_URL]:
+ 'https://gateway.macro.com/notification',
[ServiceUrl.AUTHENTICATION_SERVICE_URL]: 'https://auth-service.macro.com',
[ServiceUrl.DOCUMENT_STORAGE_SERVICE_URL]: 'https://gateway.macro.com/dss',
[ServiceUrl.CONNECTION_GATEWAY_URL]: 'https://connection-gateway.macro.com',
diff --git a/infra/stacks/notification-service/service.ts b/infra/stacks/notification-service/service.ts
index 6d70af8613..65f7b8d398 100644
--- a/infra/stacks/notification-service/service.ts
+++ b/infra/stacks/notification-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,
+ GatewayService,
+ getGatewayAlb,
stack,
} from '../../packages/shared';
+const gatewayLoadBalancer = getGatewayAlb();
+
const BASE_NAME = pulumi.getProject();
const REPO_ROOT = '../../..';
@@ -230,6 +235,22 @@ export class NotificationService 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.NOTIFICATION_SERVICE,
+ healthCheckPath,
+ pathPatterns: ['/notification', '/notification/*'],
+ serviceSecurityGroupId: this.serviceSg.id,
+ albSecurityGroupId: gatewayLoadBalancer.albSecurityGroupId,
+ },
+ { parent: this }
+ );
+
// lb
const { targetGroup, lb, listener } = serviceLoadBalancer(this, {
serviceName: BASE_NAME, // service name
@@ -265,6 +286,21 @@ export class NotificationService extends pulumi.ComponentResource {
enable: true,
rollback: true,
},
+ // 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,
@@ -325,12 +361,19 @@ export class NotificationService 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;
- this.setupAutoScaling();
+ this.setupAutoScaling({
+ gatewayAlbArnSuffix: gatewayLoadBalancer.albArnSuffix,
+ gatewayTargetGroup: gatewayTargetGroup.target_group,
+ });
this.setupServiceAlarms();
@@ -456,7 +499,13 @@ export class NotificationService 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(
@@ -472,19 +521,7 @@ export class NotificationService 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.ts
index 5660fb9542..4b048c55e6 100644
--- a/packages/sdk/src/config.ts
+++ b/packages/sdk/src/config.ts
@@ -30,7 +30,7 @@ export const HOSTS: Record<Env, Record<ServiceName, string>> = {
auth: 'https://auth-service-dev.macro.com',
email: 'https://email-service-dev.macro.com',
cognition: 'https://document-cognition-dev.macro.com',
- notification: 'https://notifications-dev.macro.com',
+ notification: 'https://dev-gateway.macro.com/notification',
properties: 'https://dev-gateway.macro.com/dss',
search: 'https://dev-gateway.macro.com/dss',
'scheduled-action': 'https://agent-schedule-dev.macro.com',
@@ -45,7 +45,7 @@ export const HOSTS: Record<Env, Record<ServiceName, string>> = {
auth: 'https://auth-service.macro.com',
email: 'https://email-service.macro.com',
cognition: 'https://document-cognition.macro.com',
- notification: 'https://notifications.macro.com',
+ notification: 'https://gateway.macro.com/notification',
properties: 'https://gateway.macro.com/dss',
search: 'https://gateway.macro.com/dss',
'scheduled-action': 'https://agent-schedule.macro.com',
diff --git a/services/notification_service/src/api.rs b/services/notification_service/src/api.rs
index 9ae492c4f5..ca92aceb64 100644
--- a/services/notification_service/src/api.rs
+++ b/services/notification_service/src/api.rs
@@ -40,9 +40,11 @@ pub async fn setup_and_serve<S: ::notification::domain::service::NotificationRea
))
.layer(macro_cors::cors_layer())
.layer(CompressionLayer::new().gzip(true)),
- )
- // The health router is attached here so we don't attach the logging middleware to it
- .merge(SwaggerUi::new("/docs").url("/api-doc/openapi.json", swagger::ApiDoc::openapi()));
+ );
+ let app = Router::new()
+ .merge(app.clone())
+ .nest("/notification", app)
+ .merge(swagger_ui());
let listener = tokio::net::TcpListener::bind(format!("0.0.0.0:{}", port))
.await
@@ -57,6 +59,15 @@ pub async fn setup_and_serve<S: ::notification::domain::service::NotificationRea
.context("error starting service")
}
+fn swagger_ui() -> Router {
+ Router::new()
+ .merge(SwaggerUi::new("/docs").url("/api-doc/openapi.json", swagger::ApiDoc::openapi()))
+ .merge(SwaggerUi::new("/notification/docs").url(
+ "/notification/api-doc/openapi.json",
+ swagger::ApiDoc::openapi(),
+ ))
+}
+
fn api_router<S: ::notification::domain::service::NotificationReader>(
_state: ApiContext,
ingress_state: NotificationRouterState<S, AuthorizationService>,
@@ -80,3 +91,41 @@ fn api_router<S: ::notification::domain::service::NotificationReader>(
.nest("/{version}", internal_router.clone())
.merge(internal_router)
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use axum::{
+ body::Body,
+ http::{Request, StatusCode},
+ };
+ use tower::ServiceExt;
+
+ #[tokio::test]
+ async fn openapi_is_served_at_root_and_gateway_prefix() {
+ let api = swagger_ui();
+
+ for uri in [
+ "/api-doc/openapi.json",
+ "/notification/api-doc/openapi.json",
+ ] {
+ let response = api
+ .clone()
+ .oneshot(
+ Request::builder()
+ .uri(uri)
+ .method("GET")
+ .body(Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(
+ response.status(),
+ StatusCode::OK,
+ "openapi at {uri} should be 200"
+ );
+ }
+ }
+}
diff --git a/services/notification_service/src/api/health.rs b/services/notification_service/src/api/health.rs
index 09e4867acc..ee39b30f87 100644
--- a/services/notification_service/src/api/health.rs
+++ b/services/notification_service/src/api/health.rs
@@ -28,21 +28,35 @@ mod tests {
use http_body_util::BodyExt; // for `collect`
use tower::ServiceExt;
+ fn dual_mounted_health() -> Router {
+ let health = router();
+ Router::new()
+ .merge(health.clone())
+ .nest("/notification", health)
+ }
+
#[tokio::test]
async fn test_health_check() {
- let api = router();
+ let api = dual_mounted_health();
- let response = api
- .oneshot(
- Request::builder()
- .uri("/health")
- .method("GET")
- .body(Body::empty())
- .unwrap(),
- )
- .await
- .unwrap();
+ for uri in ["/health", "/notification/health"] {
+ let response = api
+ .clone()
+ .oneshot(
+ Request::builder()
+ .uri(uri)
+ .method("GET")
+ .body(Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
- assert_eq!(response.status(), StatusCode::OK);
+ assert_eq!(
+ response.status(),
+ StatusCode::OK,
+ "health at {uri} should be 200"
+ );
+ }
}
}