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(lexical-service): run the lexical service on ECS behind the gateway (#7547)

Wolf Mermelstein96d7f2c625e9
diff --git a/.github/services-config.json b/.github/services-config.json
index 7177182968..800913ccc9 100644
--- a/.github/services-config.json
+++ b/.github/services-config.json
@@ -247,6 +247,14 @@
"image_optimizer"
]
},
+ "lexical-service": {
+ "source_paths": [
+ "services/lexical-service/**",
+ "packages/lexical-core/**",
+ "docker/lexical-service.Dockerfile"
+ ],
+ "stack_path": "infra/stacks/lexical-service/**"
+ },
"unfurl-service": {
"source_paths": [
"services/unfurl_service/**"
diff --git a/.github/workflows/deploy-service-generic.yml b/.github/workflows/deploy-service-generic.yml
index 9b4c2c1f59..dd5da95c4a 100644
--- a/.github/workflows/deploy-service-generic.yml
+++ b/.github/workflows/deploy-service-generic.yml
@@ -25,6 +25,7 @@ on:
- email-suppression
- image-proxy-service
- lambda-aggregate-frecency
+ - lexical-service
- link-sharing
- mcp-server
- notification-service
diff --git a/docker/docker-compose.yml b/docker/docker-compose.yml
index 8cbc66b2ba..e05a5a0bba 100644
--- a/docker/docker-compose.yml
+++ b/docker/docker-compose.yml
@@ -666,16 +666,6 @@ services:
- "8096:8096"
depends_on:
- sync_service
- # Bundle the entry before running. Executing the unbundled TS directly under
- # Bun evaluates the circular @lexical/* ESM imports in an order that triggers
- # a TDZ ("Cannot access 'HeadingNode'/'ElementNode' before initialization");
- # bundling hoists/orders the declarations and resolves it (matching how the
- # worker is run normally — wrangler/esbuild bundles it first). loro-crdt
- # stays external: bundling it emits its .wasm as a second output file
- # (breaking --outfile) and mis-wires the wasm instantiation at runtime.
- # The bundle must live under /app: bun resolves the external loro-crdt
- # import relative to the bundle's path, so it needs /app/node_modules.
- command: ["sh", "-c", "bun build src/server.ts --target=bun --external loro-crdt --outfile=/app/server.bundle.js && exec bun /app/server.bundle.js"]
environment:
- PORT=8096
- INTERNAL_AUTH_KEY=${INTERNAL_API_SECRET_KEY}
diff --git a/docker/lexical-service.Dockerfile b/docker/lexical-service.Dockerfile
index d213ea3233..d94a83eb8e 100644
--- a/docker/lexical-service.Dockerfile
+++ b/docker/lexical-service.Dockerfile
@@ -11,6 +11,16 @@ WORKDIR /app/services/lexical-service
RUN mkdir -p node_modules/@macro-inc \
&& ln -sfn /app/packages/lexical-core node_modules/@macro-inc/lexical-core
+# Run a bundle, not the TS entry. Executing the unbundled TS under Bun
+# evaluates the circular @lexical/* ESM imports in an order that triggers a TDZ
+# ("Cannot access 'HeadingNode'/'ElementNode' before initialization");
+# bundling orders the declarations, as wrangler/esbuild does for the worker.
+# loro-crdt stays external: bundling it emits its .wasm as a second output
+# file (breaking --outfile) and mis-wires the wasm instantiation at runtime.
+# The bundle lives under /app so the external loro-crdt import resolves
+# against /app/node_modules.
+RUN bun build src/server.ts --target=bun --external loro-crdt --outfile=/app/server.bundle.js
+
EXPOSE 8096
-CMD ["bun", "run", "src/server.ts"]
+CMD ["bun", "/app/server.bundle.js"]
diff --git a/infra/bun.lock b/infra/bun.lock
index 7ed1870af7..475c98989a 100644
--- a/infra/bun.lock
+++ b/infra/bun.lock
@@ -159,6 +159,10 @@
"name": "kafka-cluster-stack",
"version": "0.0.0",
},
+ "stacks/lexical-service": {
+ "name": "lexical-service-stack",
+ "version": "0.0.0",
+ },
"stacks/link-sharing": {
"name": "link-sharing-stack",
"version": "0.0.0",
@@ -675,6 +679,8 @@
"lambda": ["lambda@workspace:packages/lambda"],
+ "lexical-service-stack": ["lexical-service-stack@workspace:stacks/lexical-service"],
+
"link-sharing-stack": ["link-sharing-stack@workspace:stacks/link-sharing"],
"lodash.camelcase": ["[email protected]", "", {}, "sha512-TwuEnCnxbc3rAvhf/LbG7tJUDzhqXyFnv3dtzLOPgCG/hODL7WFnsbwktkD7yUV0RrreP/l1PALq/YSg6VvjlA=="],
diff --git a/infra/packages/shared/src/gateway_priorities.ts b/infra/packages/shared/src/gateway_priorities.ts
index c3d6f5c603..c6c3d35e84 100644
--- a/infra/packages/shared/src/gateway_priorities.ts
+++ b/infra/packages/shared/src/gateway_priorities.ts
@@ -20,6 +20,7 @@ export enum GatewayService {
EMAIL_SERVICE = 'EMAIL_SERVICE',
MCP_SERVER = 'MCP_SERVER',
DOCUMENT_COGNITION_SERVICE = 'DOCUMENT_COGNITION_SERVICE',
+ LEXICAL_SERVICE = 'LEXICAL_SERVICE',
}
/**
@@ -48,6 +49,7 @@ export const GATEWAY_PRIORITIES: GatewayPriorityMap = {
[GatewayService.MCP_SERVER]: 130,
[GatewayService.DOCUMENT_COGNITION_SERVICE]: 120,
[GatewayService.CALENDAR_SERVICE]: 140,
+ [GatewayService.LEXICAL_SERVICE]: 160,
[GatewayService.CONVERT_SERVICE]: 3000,
};
diff --git a/infra/packages/shared/src/service_urls.ts b/infra/packages/shared/src/service_urls.ts
index 076bc86cd9..42773c590d 100644
--- a/infra/packages/shared/src/service_urls.ts
+++ b/infra/packages/shared/src/service_urls.ts
@@ -13,6 +13,8 @@ export enum ServiceUrl {
CONNECTION_GATEWAY_URL = 'CONNECTION_GATEWAY_URL',
DOCUMENT_COGNITION_SERVICE_URL = 'DOCUMENT_COGNITION_SERVICE_URL',
LEXICAL_SERVICE_URL = 'LEXICAL_SERVICE_URL',
+ /** The lexical service on ECS, behind the shared gateway. */
+ LEXICAL_GATEWAY_URL = 'LEXICAL_GATEWAY_URL',
UNFURL_SERVICE_URL = 'UNFURL_SERVICE_URL',
AGENT_HARNESS_SERVICE_URL = 'AGENT_HARNESS_SERVICE_URL',
AGENT_HARNESS_EGRESS_URL = 'AGENT_HARNESS_EGRESS_URL',
@@ -46,6 +48,7 @@ const DEV_SERVICE_URLS: ServiceUrlMap = {
'https://dev-gateway.macro.com/cognition',
[ServiceUrl.LEXICAL_SERVICE_URL]:
'https://lexical-service-dev.macroverse.workers.dev',
+ [ServiceUrl.LEXICAL_GATEWAY_URL]: 'https://dev-gateway.macro.com/lexical',
[ServiceUrl.UNFURL_SERVICE_URL]: 'https://dev-gateway.macro.com/unfurl',
[ServiceUrl.AGENT_HARNESS_SERVICE_URL]:
'https://dev-gateway.macro.com/agent-harness',
@@ -72,6 +75,7 @@ const PROD_SERVICE_URLS: ServiceUrlMap = {
'https://gateway.macro.com/cognition',
[ServiceUrl.LEXICAL_SERVICE_URL]:
'https://lexical-service-prod.macroverse.workers.dev',
+ [ServiceUrl.LEXICAL_GATEWAY_URL]: 'https://gateway.macro.com/lexical',
[ServiceUrl.UNFURL_SERVICE_URL]: 'https://gateway.macro.com/unfurl',
[ServiceUrl.AGENT_HARNESS_SERVICE_URL]:
'https://gateway.macro.com/agent-harness',
diff --git a/infra/stacks/doppler-projects/index.ts b/infra/stacks/doppler-projects/index.ts
index 282cc0483e..4dd648d24f 100644
--- a/infra/stacks/doppler-projects/index.ts
+++ b/infra/stacks/doppler-projects/index.ts
@@ -19,6 +19,7 @@ const SERVICE_NAMES = [
'agent-harness-service',
'preview-gateway',
'slack-import-worker',
+ 'lexical-service',
];
for (const service_name of SERVICE_NAMES) {
diff --git a/infra/stacks/lexical-service/Pulumi.dev.yaml b/infra/stacks/lexical-service/Pulumi.dev.yaml
new file mode 100644
index 0000000000..9cfd7a1eb5
--- /dev/null
+++ b/infra/stacks/lexical-service/Pulumi.dev.yaml
@@ -0,0 +1,3 @@
+config:
+ aws-native:region: us-east-1
+ aws:region: us-east-1
diff --git a/infra/stacks/lexical-service/Pulumi.prod.yaml b/infra/stacks/lexical-service/Pulumi.prod.yaml
new file mode 100644
index 0000000000..9cfd7a1eb5
--- /dev/null
+++ b/infra/stacks/lexical-service/Pulumi.prod.yaml
@@ -0,0 +1,3 @@
+config:
+ aws-native:region: us-east-1
+ aws:region: us-east-1
diff --git a/infra/stacks/lexical-service/Pulumi.yaml b/infra/stacks/lexical-service/Pulumi.yaml
new file mode 100644
index 0000000000..628054d024
--- /dev/null
+++ b/infra/stacks/lexical-service/Pulumi.yaml
@@ -0,0 +1,3 @@
+name: lexical-service
+runtime: nodejs
+description: Lexical Service
diff --git a/infra/stacks/lexical-service/index.ts b/infra/stacks/lexical-service/index.ts
new file mode 100644
index 0000000000..68b713846e
--- /dev/null
+++ b/infra/stacks/lexical-service/index.ts
@@ -0,0 +1,47 @@
+import * as pulumi from '@pulumi/pulumi';
+import { getServiceUrl, ServiceUrl, stack } from '../../packages/shared';
+import { get_coparse_api_vpc } from '../../packages/vpc';
+import { LexicalService } from './lexical-service';
+
+const tags = {
+ environment: stack,
+ tech_lead: 'wolf',
+ project: 'lexical-service',
+};
+
+export const coparse_api_vpc = get_coparse_api_vpc();
+
+const cloudStorageStack = new pulumi.StackReference('cloud-storage-stack', {
+ name: `macro-inc/document-storage/${stack}`,
+});
+
+const cloudStorageClusterArn: pulumi.Output<string> = cloudStorageStack
+ .getOutput('cloudStorageClusterArn')
+ .apply((arn) => arn as string);
+
+const cloudStorageClusterName: pulumi.Output<string> = cloudStorageStack
+ .getOutput('cloudStorageClusterName')
+ .apply((arn) => arn as string);
+
+const lexicalService = new LexicalService(`lexical-service-${stack}`, {
+ ecsClusterArn: cloudStorageClusterArn,
+ cloudStorageClusterName: cloudStorageClusterName,
+ vpc: coparse_api_vpc,
+ platform: {
+ family: 'linux',
+ architecture: 'amd64',
+ },
+ serviceContainerPort: 8096,
+ healthCheckPath: '/health',
+ containerEnvVars: [
+ { name: 'PORT', value: '8096' },
+ {
+ name: 'SYNC_SERVICE_URL',
+ value: getServiceUrl(ServiceUrl.SYNC_SERVICE_URL),
+ },
+ ],
+ tags,
+});
+
+export const lexicalServiceSgId = lexicalService.serviceSg.id;
+export const lexicalServiceUrl = getServiceUrl(ServiceUrl.LEXICAL_GATEWAY_URL);
diff --git a/infra/stacks/lexical-service/lexical-service.ts b/infra/stacks/lexical-service/lexical-service.ts
new file mode 100644
index 0000000000..322b751122
--- /dev/null
+++ b/infra/stacks/lexical-service/lexical-service.ts
@@ -0,0 +1,443 @@
+import * as aws from '@pulumi/aws';
+import * as awsx from '@pulumi/awsx';
+import * as pulumi from '@pulumi/pulumi';
+import {
+ DATADOG_API_KEY,
+ DEFAULT_CONTINUE_BEFORE_STEADY_STATE,
+ EcsDeploymentFailureAlarm,
+ datadogAgentContainer,
+ fargateLogRouterSidecarContainer,
+ ServiceTargetGroup,
+} from '../../packages/resources';
+import { EcrImage } from '../../packages/service';
+import {
+ CLOUD_TRAIL_SNS_TOPIC_ARN,
+ DopplerEcsEnvironment,
+ getGatewayAlb,
+ GatewayService,
+ stack,
+} from '../../packages/shared';
+
+const gatewayLoadBalancer = getGatewayAlb();
+
+const BASE_NAME = pulumi.getProject();
+const REPO_ROOT = '../../..';
+
+type CreateLexicalServiceArgs = {
+ cloudStorageClusterName: pulumi.Output<string> | string;
+ ecsClusterArn: pulumi.Output<string> | string;
+ vpc: {
+ vpcId: pulumi.Output<string> | string;
+ privateSubnetIds: pulumi.Output<string[]> | string[];
+ };
+ platform: { family: string; architecture: 'amd64' | 'arm64' };
+ serviceContainerPort: number;
+ containerEnvVars?: { name: string; value: pulumi.Output<string> | string }[];
+ healthCheckPath: string;
+ tags: { [key: string]: string };
+};
+
+export class LexicalService extends pulumi.ComponentResource {
+ public ecr: awsx.ecr.Repository;
+ public serviceSg: aws.ec2.SecurityGroup;
+ public targetGroup: aws.lb.TargetGroup;
+ public service: awsx.ecs.FargateService;
+ public cloudStorageClusterName: pulumi.Output<string> | string;
+ public tags: { [key: string]: string };
+ public role: aws.iam.Role;
+
+ constructor(
+ name: string,
+ {
+ ecsClusterArn,
+ vpc,
+ platform,
+ serviceContainerPort,
+ healthCheckPath,
+ containerEnvVars,
+ cloudStorageClusterName,
+ tags,
+ }: CreateLexicalServiceArgs,
+ opts?: pulumi.ComponentResourceOptions
+ ) {
+ super('my:components:LexicalService', name, {}, opts);
+ this.tags = tags;
+
+ this.cloudStorageClusterName = cloudStorageClusterName;
+
+ // 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: REPO_ROOT,
+ dockerfile: 'docker/lexical-service.Dockerfile',
+ platform,
+ tags: this.tags,
+ },
+ { parent: this }
+ );
+ this.ecr = image.ecr;
+
+ // sg
+ this.serviceSg = this.initializeSecurityGroups({ vpcId: vpc.vpcId });
+
+ const gatewayTargetGroup = new ServiceTargetGroup(
+ `${stack}-${BASE_NAME}`,
+ {
+ tags: this.tags,
+ listenerArn: gatewayLoadBalancer.httpsListenerArn,
+ vpcId: vpc.vpcId,
+ containerPort: serviceContainerPort,
+ service: GatewayService.LEXICAL_SERVICE,
+ healthCheckPath,
+ pathPatterns: ['/lexical', '/lexical/*'],
+ serviceSecurityGroupId: this.serviceSg.id,
+ albSecurityGroupId: gatewayLoadBalancer.albSecurityGroupId,
+ },
+ { parent: this }
+ );
+
+ this.targetGroup = gatewayTargetGroup.target_group;
+
+ 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: '',
+ },
+ ],
+ },
+ managedPolicyArns: [],
+ tags: this.tags,
+ },
+ { parent: this }
+ );
+
+ const dopplerEcsEnvironment = new DopplerEcsEnvironment(
+ BASE_NAME,
+ { tags: this.tags },
+ { parent: this }
+ );
+ // The sync-service key is the one sync-service itself checks, kept in
+ // Secrets Manager; Doppler's SYNC_SERVICE_AUTH_KEY does not authenticate.
+ const syncServiceKeyArn = aws.secretsmanager
+ .getSecretVersionOutput({ secretId: `sync-service-key-${stack}` })
+ .apply((secret) => secret.arn);
+ new aws.iam.RolePolicy(
+ `${BASE_NAME}-sync-service-key-policy`,
+ {
+ role: dopplerEcsEnvironment.executionRole.id,
+ policy: {
+ Version: '2012-10-17',
+ Statement: [
+ {
+ Action: ['secretsmanager:GetSecretValue'],
+ Resource: syncServiceKeyArn,
+ Effect: 'Allow',
+ },
+ ],
+ },
+ },
+ { parent: this }
+ );
+ // The Bun server reads plain env vars, not APP_SECRETS_JSON.
+ const secrets = [
+ {
+ name: 'INTERNAL_AUTH_KEY',
+ valueFrom: pulumi.interpolate`${dopplerEcsEnvironment.containerSecrets[0].valueFrom}:INTERNAL_AUTH_KEY::`,
+ },
+ { name: 'SYNC_SERVICE_AUTH_KEY', valueFrom: syncServiceKeyArn },
+ ];
+
+ // service
+ const service = new awsx.ecs.FargateService(
+ `${BASE_NAME}`,
+ {
+ tags,
+ cluster: ecsClusterArn,
+ networkConfiguration: {
+ subnets: vpc.privateSubnetIds,
+ securityGroups: [this.serviceSg.id],
+ },
+ continueBeforeSteadyState: DEFAULT_CONTINUE_BEFORE_STEADY_STATE,
+ deploymentCircuitBreaker: {
+ enable: true,
+ rollback: true,
+ },
+ loadBalancers: [
+ {
+ targetGroupArn: gatewayTargetGroup.target_group.arn,
+ containerName: 'service',
+ containerPort: serviceContainerPort,
+ },
+ ],
+ taskDefinitionArgs: {
+ taskRole: {
+ roleArn: this.role.arn,
+ },
+ executionRole: {
+ roleArn: dopplerEcsEnvironment.executionRole.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: 256,
+ memory: 512,
+ environment: containerEnvVars,
+ secrets,
+ logConfiguration: {
+ logDriver: 'awsfirelens',
+ options: {
+ Name: 'datadog',
+ Host: 'http-intake.logs.us5.datadoghq.com',
+ apikey: DATADOG_API_KEY,
+ dd_service: 'lexical-service',
+ dd_source: 'fargate',
+ dd_tags: `project:lexical-service, env:${stack}`,
+ provider: 'ecs',
+ },
+ },
+ portMappings: [
+ {
+ appProtocol: 'http',
+ name: `${BASE_NAME}-tcp-${stack}`,
+ hostPort: serviceContainerPort,
+ containerPort: serviceContainerPort,
+ targetGroup: this.targetGroup,
+ },
+ ],
+ },
+ },
+ runtimePlatform: {
+ operatingSystemFamily: `${platform.family.toUpperCase()}`,
+ cpuArchitecture: `${
+ platform.architecture === 'amd64'
+ ? 'X86_64'
+ : platform.architecture.toUpperCase()
+ }`,
+ },
+ },
+ // It sits on the agent prompt path: never a single task.
+ desiredCount: 2,
+ },
+ {
+ parent: this,
+ dependsOn: [gatewayTargetGroup.listener_rule],
+ }
+ );
+
+ this.service = service;
+
+ this.setupAutoScaling();
+
+ this.setupServiceAlarms();
+ }
+
+ initializeSecurityGroups({
+ 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}-service-scalable-target-${stack}`,
+ {
+ maxCapacity: stack === 'prod' ? 10 : 3,
+ minCapacity: 2,
+ resourceId: pulumi.interpolate`service/${this.cloudStorageClusterName}/${this.service.service.name}`,
+ scalableDimension: 'ecs:service:DesiredCount',
+ serviceNamespace: 'ecs',
+ tags: this.tags,
+ },
+ { parent: this }
+ );
+
+ const resourceLabel = pulumi.interpolate`${gatewayLoadBalancer.albArnSuffix}/${this.targetGroup.arnSuffix}`;
+
+ // Create an Auto Scaling policy for request count.
+ new aws.appautoscaling.Policy(
+ `${BASE_NAME}-scaling-policy-request-count-${stack}`,
+ {
+ policyType: 'TargetTrackingScaling',
+ resourceId: serviceScalableTarget.resourceId,
+ scalableDimension: serviceScalableTarget.scalableDimension,
+ serviceNamespace: serviceScalableTarget.serviceNamespace,
+ targetTrackingScalingPolicyConfiguration: {
+ targetValue: 1000,
+ predefinedMetricSpecification: {
+ predefinedMetricType: 'ALBRequestCountPerTarget',
+ resourceLabel,
+ },
+ scaleInCooldown: 60,
+ scaleOutCooldown: 120,
+ },
+ },
+ { 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 EcsDeploymentFailureAlarm(
+ `${BASE_NAME}-deployment-failure-alarm`,
+ {
+ serviceName: BASE_NAME,
+ serviceArn: this.service.service.arn,
+ tags: this.tags,
+ },
+ { parent: this }
+ );
+
+ 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.cloudStorageClusterName,
+ 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.cloudStorageClusterName,
+ 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 }
+ );
+
+ new aws.cloudwatch.MetricAlarm(
+ `${BASE_NAME}-http-5xx-alarm`,
+ {
+ name: `${BASE_NAME}-http-5xx-${stack}`,
+ metricName: 'HTTPCode_Target_5XX_Count',
+ namespace: 'AWS/ApplicationELB',
+ statistic: 'Sum',
+ period: 180,
+ evaluationPeriods: 1,
+ threshold: 25,
+ comparisonOperator: 'GreaterThanOrEqualToThreshold',
+ dimensions: {
+ LoadBalancer: gatewayLoadBalancer.albArnSuffix,
+ TargetGroup: this.targetGroup.arnSuffix,
+ },
+ alarmDescription: `High HTTP 5XX count alarm for ${BASE_NAME} gateway target group.`,
+ actionsEnabled: true,
+ alarmActions: [CLOUD_TRAIL_SNS_TOPIC_ARN],
+ tags: this.tags,
+ },
+ { parent: this }
+ );
+ }
+}
diff --git a/infra/stacks/lexical-service/package.json b/infra/stacks/lexical-service/package.json
new file mode 100644
index 0000000000..8bcff3a17a
--- /dev/null
+++ b/infra/stacks/lexical-service/package.json
@@ -0,0 +1,6 @@
+{
+ "name": "lexical-service-stack",
+ "version": "0.0.0",
+ "private": true,
+ "license": "MIT"
+}
diff --git a/infra/stacks/lexical-service/tsconfig.json b/infra/stacks/lexical-service/tsconfig.json
new file mode 100644
index 0000000000..6f83eb665f
--- /dev/null
+++ b/infra/stacks/lexical-service/tsconfig.json
@@ -0,0 +1,3 @@
+{
+ "extends": "../../tsconfig.json",
+}
diff --git a/services/lexical-service/src/server.ts b/services/lexical-service/src/server.ts
index c6d507996c..c039e193b6 100644
--- a/services/lexical-service/src/server.ts
+++ b/services/lexical-service/src/server.ts
@@ -3,6 +3,22 @@ import app from './index';
const PORT = parseInt(process.env.PORT || '8096', 10);
+// The shared gateway routes `/lexical/*` here without stripping the prefix;
+// the app's routes, and the target group's health check, are at the root.
+const GATEWAY_PREFIX = '/lexical';
+
+function withoutGatewayPrefix(req: Request): Request {
+ const url = new URL(req.url);
+ if (
+ url.pathname !== GATEWAY_PREFIX &&
+ !url.pathname.startsWith(`${GATEWAY_PREFIX}/`)
+ ) {
+ return req;
+ }
+ url.pathname = url.pathname.slice(GATEWAY_PREFIX.length) || '/';
+ return new Request(url, req);
+}
+
const env = {
INTERNAL_AUTH_KEY:
process.env.INTERNAL_AUTH_KEY || process.env.INTERNAL_API_SECRET_KEY,
@@ -26,7 +42,7 @@ for (const varName of requiredVars) {
const server = Bun.serve({
port: PORT,
fetch(req) {
- return app.fetch(req, env);
+ return app.fetch(withoutGatewayPrefix(req), env);
},
});