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.

chore(metering): remove metering service iac (#965)

Will Hutchinsona94f1f696aaa
diff --git a/infra/bun.lock b/infra/bun.lock
index 5461d1ca12..6b18b84a3d 100644
--- a/infra/bun.lock
+++ b/infra/bun.lock
@@ -122,10 +122,6 @@
"name": "link-sharing-stack",
"version": "0.0.0",
},
- "stacks/metering-service": {
- "name": "metering-service-stack",
- "version": "0.0.0",
- },
"stacks/notification-service": {
"name": "notification-service-stack",
"version": "0.0.0",
@@ -752,8 +748,6 @@
"merge-stream": ["[email protected]", "", {}, "sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w=="],
- "metering-service-stack": ["metering-service-stack@workspace:stacks/metering-service"],
-
"mime": ["[email protected]", "", { "bin": { "mime": "cli.js" } }, "sha512-USPkMeET31rOMiarsBNIHZKLGgvKc/LrjofAnBlOttf5ajRvqiRA8QsenbcooctK6d6Ts6aqZXBA+XbkKthiQg=="],
"mimic-fn": ["[email protected]", "", {}, "sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg=="],
diff --git a/infra/stacks/metering-service/Pulumi.dev.yaml b/infra/stacks/metering-service/Pulumi.dev.yaml
deleted file mode 100644
index 270f0f1109..0000000000
--- a/infra/stacks/metering-service/Pulumi.dev.yaml
+++ /dev/null
@@ -1,5 +0,0 @@
-config:
- aws-native:region: us-east-1
- aws:region: us-east-1
- metering-service:db-password-secret-key: metering-db-password-dev
- metering-service:internal_api_key: document-storage-service-auth-key-dev
diff --git a/infra/stacks/metering-service/Pulumi.prod.yaml b/infra/stacks/metering-service/Pulumi.prod.yaml
deleted file mode 100644
index 9ed9dfdca0..0000000000
--- a/infra/stacks/metering-service/Pulumi.prod.yaml
+++ /dev/null
@@ -1,5 +0,0 @@
-config:
- aws-native:region: us-east-1
- aws:region: us-east-1
- metering-service:db-password-secret-key: metering-db-password-prod
- metering-service:internal_api_key: document-storage-service-auth-key-prod
diff --git a/infra/stacks/metering-service/Pulumi.yaml b/infra/stacks/metering-service/Pulumi.yaml
deleted file mode 100644
index 2c28f1d029..0000000000
--- a/infra/stacks/metering-service/Pulumi.yaml
+++ /dev/null
@@ -1,3 +0,0 @@
-name: metering-service
-description: Metering for AI Usage
-runtime: nodejs
diff --git a/infra/stacks/metering-service/index.ts b/infra/stacks/metering-service/index.ts
deleted file mode 100644
index 0be9e6eece..0000000000
--- a/infra/stacks/metering-service/index.ts
+++ /dev/null
@@ -1,103 +0,0 @@
-import * as aws from '@pulumi/aws';
-import * as pulumi from '@pulumi/pulumi';
-import { Database } from '../../packages/resources';
-import { config, stack } from '../../packages/shared';
-import { get_coparse_api_vpc } from '../../packages/vpc';
-import { Service } from './service';
-
-// name of the "project". Usually the thing before "_service" or "_db_client"
-const PROJECT = 'metering';
-// name of who's in charge of this service
-const TECH_LEAD = 'blake';
-
-const SERVICE_NAME = `${PROJECT}_service`;
-const DB_CLIENT_NAME = `${PROJECT}_db_client`;
-const DATABASE_PASSWORD_CONFIG_KEY = `db-password-secret-key`;
-const RDS_INSTANCE_NAME = `${PROJECT}-db`;
-const DATABASE_NAME = PROJECT;
-
-const tags = {
- environment: stack,
- tech_lead: TECH_LEAD,
- project: PROJECT,
-};
-
-export const coparse_api_vpc = get_coparse_api_vpc();
-
-const password = aws.secretsmanager
- .getSecretVersionOutput({
- secretId: config.require(DATABASE_PASSWORD_CONFIG_KEY),
- })
- .apply((secret) => secret.secretString);
-
-const db = new Database(RDS_INSTANCE_NAME, {
- publiclyAccessible: false,
- tags,
- vpc: coparse_api_vpc,
- dbArgs: {
- dbName: DATABASE_NAME,
- instanceClass: stack === 'prod' ? 'db.t4g.large' : 'db.t4g.micro',
- password,
- allocatedStorage: 25,
- },
-});
-
-export const databaseEndpoint = db.endpoint;
-
-const DATABASE_URL = pulumi.all([databaseEndpoint, password]).apply(
- // eslint-disable-next-line @typescript-eslint/no-shadow
- ([endpoint, password]) =>
- `postgresql://macrouser:${password}@${endpoint}/${DATABASE_NAME}`
-);
-
-const INTERNAL_API_SECRET_KEY = config.require(`internal_api_key`);
-const INTERNAL_AUTH_KEY: pulumi.Output<string> = aws.secretsmanager
- .getSecretVersionOutput({
- secretId: pulumi.interpolate`${INTERNAL_API_SECRET_KEY}`,
- })
- .apply((secret) => secret.secretString);
-
-let containerEnvVars = [
- {
- name: 'RUST_LOG',
- value: `${SERVICE_NAME}=${stack === 'prod' ? 'info' : 'debug'},${DB_CLIENT_NAME}=${stack === 'prod' ? 'info' : 'debug'},tower_http=info`,
- },
- {
- name: 'ENVIRONMENT',
- value: stack,
- },
- {
- name: 'DATABASE_URL',
- value: pulumi.interpolate`${DATABASE_URL}`,
- },
- {
- name: 'INTERNAL_API_SECRET_KEY',
- value: pulumi.interpolate`${INTERNAL_AUTH_KEY}`,
- },
-];
-
-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 service = new Service(SERVICE_NAME, {
- vpc: coparse_api_vpc,
- tags,
- containerEnvVars,
- platform: { family: 'linux', architecture: 'amd64' },
- serviceContainerPort: 8080,
- healthCheckPath: '/health',
- isPrivate: stack === 'prod',
- ecsClusterArn: cloudStorageClusterArn,
- cloudStorageClusterName,
-});
-
-export const meteringServiceUrl = pulumi.interpolate`${service.domain}`;
diff --git a/infra/stacks/metering-service/package.json b/infra/stacks/metering-service/package.json
deleted file mode 100644
index 014eae02ec..0000000000
--- a/infra/stacks/metering-service/package.json
+++ /dev/null
@@ -1,7 +0,0 @@
-{
- "name": "metering-service-stack",
- "version": "0.0.0",
- "private": true,
- "license": "MIT",
- "main": "index.ts"
-}
diff --git a/infra/stacks/metering-service/service.ts b/infra/stacks/metering-service/service.ts
deleted file mode 100644
index e490d1f1fa..0000000000
--- a/infra/stacks/metering-service/service.ts
+++ /dev/null
@@ -1,499 +0,0 @@
-import * as aws from '@pulumi/aws';
-import * as awsx from '@pulumi/awsx';
-import * as pulumi from '@pulumi/pulumi';
-import {
- DATADOG_API_KEY,
- datadogAgentContainer,
- fargateLogRouterSidecarContainer,
- serviceLoadBalancer,
-} from '../../packages/resources';
-import { EcrImage } from '../../packages/service';
-import {
- BASE_DOMAIN,
- CLOUD_TRAIL_SNS_TOPIC_ARN,
- stack,
-} from '../../packages/shared';
-
-const toSnakeCase = (...parts: String[]) => parts.join('_');
-//const capitalize = (word: String) => word[0].toUpperCase() + word.slice(1)
-//const toCamelCase = (first: String, ...rest: String[]) => [first, ...rest.map(capitalize)].join('')
-const toKebabCase = (...parts: String[]) => parts.join('-');
-
-// name of of the "project". Usually the thing before "_service".
-const PROJECT = 'metering';
-const KEBAB_BASE_NAME = toKebabCase(PROJECT, 'service');
-// directory name of service
-const SNAKE_BASE_NAME = toSnakeCase(PROJECT, 'service');
-const SERVICE_DIR_NAME = SNAKE_BASE_NAME;
-const BASE_PATH = '../../../rust/cloud-storage';
-
-export const SERVICE_DOMAIN_NAME = `${PROJECT}${stack === 'prod' ? '' : `-${stack}`}.${BASE_DOMAIN}`;
-
-type CreateServiceArgs = {
- vpc: {
- vpcId: pulumi.Output<string> | string;
- publicSubnetIds: pulumi.Output<string[]> | string[];
- privateSubnetIds: pulumi.Output<string[]> | string[];
- };
- tags: { [key: string]: string };
- containerEnvVars: { name: string; value: pulumi.Output<string> | string }[];
- platform: { family: string; architecture: 'amd64' | 'arm64' };
- serviceContainerPort: number;
- healthCheckPath: string;
- isPrivate?: boolean;
- ecsClusterArn: pulumi.Output<string> | string;
- cloudStorageClusterName: pulumi.Output<string> | string;
-};
-
-export class Service extends pulumi.ComponentResource {
- public role: aws.iam.Role;
- public ecr: awsx.ecr.Repository;
- public serviceAlbSg: aws.ec2.SecurityGroup;
- public serviceSg: aws.ec2.SecurityGroup;
- public domain: string;
- public tags: { [key: string]: string };
- public targetGroup: aws.lb.TargetGroup;
- public lb: aws.lb.LoadBalancer;
- public listener: aws.lb.Listener;
- public service: awsx.ecs.FargateService;
- public cloudStorageClusterName: pulumi.Output<string> | string;
-
- constructor(
- name: string,
- {
- vpc,
- tags,
- platform,
- serviceContainerPort,
- healthCheckPath,
- isPrivate,
- ecsClusterArn,
- containerEnvVars,
- cloudStorageClusterName,
- }: CreateServiceArgs,
- opts?: pulumi.ComponentResourceOptions
- ) {
- super(`my:components:${PROJECT}Service`, name, {}, opts);
- this.domain = `https://${SERVICE_DOMAIN_NAME}`;
- this.tags = tags;
- this.cloudStorageClusterName = cloudStorageClusterName;
-
- this.role = new aws.iam.Role(
- `${KEBAB_BASE_NAME}-role`,
- {
- name: `${KEBAB_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: [],
- },
- { parent: this }
- );
-
- // ecr image
- const image = new EcrImage(
- `${KEBAB_BASE_NAME}-ecr-image-${stack}`,
- {
- repositoryId: `${KEBAB_BASE_NAME}-ecr-${stack}`,
- repositoryName: `${KEBAB_BASE_NAME}-${stack}`,
- imageId: `${KEBAB_BASE_NAME}-image-${stack}`,
- imagePath: BASE_PATH,
- dockerfile: 'Dockerfile',
- platform,
- buildArgs: {
- SERVICE_NAME: `${PROJECT}_service`,
- },
- tags: this.tags,
- },
- { parent: this }
- );
- this.ecr = image.ecr;
-
- // Security groups
- const sg = this.initializeSecurityGroups({
- vpcId: vpc.vpcId,
- serviceContainerPort,
- });
- this.serviceAlbSg = sg.serviceAlbSg;
- this.serviceSg = sg.serviceSg;
-
- // Load balancer
- const { targetGroup, lb, listener } = serviceLoadBalancer(this, {
- serviceName: KEBAB_BASE_NAME, // service name
- serviceContainerPort,
- healthCheckPath,
- vpc,
- albSecurityGroupId: this.serviceAlbSg.id,
- isPrivate,
- tags,
- });
- this.targetGroup = targetGroup;
- this.lb = lb;
- this.listener = listener;
-
- // Fargate Service
- const service = new awsx.ecs.FargateService(
- `${KEBAB_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: SERVICE_DIR_NAME,
- image: image.image.imageUri,
- stopTimeout: 10, // 10 seconds to force kill the task
- cpu: stack === 'prod' ? 512 : 256,
- memory: stack === 'prod' ? 1024 : 512,
- environment: [
- ...containerEnvVars,
- {
- name: 'BASE_URL',
- value: this.domain,
- },
- ],
- logConfiguration: {
- logDriver: 'awsfirelens',
- options: {
- Name: 'datadog',
- Host: 'http-intake.logs.us5.datadoghq.com',
- apikey: DATADOG_API_KEY,
- dd_service: `${PROJECT}-service-${stack}`,
- dd_source: 'fargate',
- dd_tags: `project:${PROJECT}, env:${stack}`,
- provider: 'ecs',
- },
- },
- portMappings: [
- {
- appProtocol: 'http',
- name: `${KEBAB_BASE_NAME}-tcp-${stack}`,
- hostPort: serviceContainerPort,
- containerPort: serviceContainerPort,
- targetGroup,
- },
- ],
- },
- },
- runtimePlatform: {
- operatingSystemFamily: `${platform.family.toUpperCase()}`,
- cpuArchitecture: `${
- platform.architecture === 'amd64'
- ? 'X86_64'
- : platform.architecture.toUpperCase()
- }`,
- },
- },
- desiredCount: 1,
- },
- { parent: this }
- );
- this.service = service;
-
- // auto-scaling and alarm notifications
- this.setupAutoScaling();
- this.setupServiceAlarms();
-
- // DNS
- const zone = aws.route53.getZoneOutput({ name: BASE_DOMAIN });
-
- new aws.route53.Record(
- `${KEBAB_BASE_NAME}-domain-record`,
- {
- name: SERVICE_DOMAIN_NAME,
- type: 'A',
- zoneId: zone.zoneId,
- aliases: [
- {
- evaluateTargetHealth: false,
- name: this.lb.dnsName,
- zoneId: this.lb.zoneId,
- },
- ],
- },
- { parent: this }
- );
- }
-
- initializeSecurityGroups({
- vpcId,
- serviceContainerPort,
- }: {
- vpcId: pulumi.Output<string> | string;
- serviceContainerPort: number;
- }) {
- const serviceAlbSg = new aws.ec2.SecurityGroup(
- `${KEBAB_BASE_NAME}-alb-sg-${stack}`,
- {
- name: `${KEBAB_BASE_NAME}-alb-sg-${stack}`,
- description: `${PROJECT} application load balancer security group`,
- vpcId,
- tags: this.tags,
- },
- { parent: this }
- );
-
- const serviceSg = new aws.ec2.SecurityGroup(
- `${KEBAB_BASE_NAME}-sg-${stack}`,
- {
- name: `${KEBAB_BASE_NAME}-sg-${stack}`,
- vpcId,
- description: `${PROJECT} security group that is attached directly to the service`,
- tags: this.tags,
- },
- { parent: this }
- );
-
- new aws.vpc.SecurityGroupIngressRule(
- `${KEBAB_BASE_NAME}-alb-in`,
- {
- securityGroupId: serviceSg.id,
- description: 'Allow inbound traffic from the services ALB',
- referencedSecurityGroupId: serviceAlbSg.id,
- fromPort: serviceContainerPort,
- toPort: serviceContainerPort,
- ipProtocol: 'tcp',
- tags: this.tags,
- },
- { parent: this }
- );
-
- new aws.vpc.SecurityGroupEgressRule(
- `${KEBAB_BASE_NAME}-all-out`,
- {
- securityGroupId: serviceSg.id,
- description: 'Allow all outbound',
- cidrIpv4: '0.0.0.0/0',
- ipProtocol: '-1',
- tags: this.tags,
- },
- { parent: this }
- );
-
- // ALB SG rules
- new aws.vpc.SecurityGroupIngressRule(
- `${KEBAB_BASE_NAME}-http`,
- {
- securityGroupId: serviceAlbSg.id,
- description: 'Allow inbound HTTP traffic',
- cidrIpv4: '0.0.0.0/0',
- fromPort: 80,
- ipProtocol: 'tcp',
- toPort: 80,
- tags: this.tags,
- },
- { parent: this }
- );
-
- new aws.vpc.SecurityGroupIngressRule(
- `${KEBAB_BASE_NAME}-https`,
- {
- securityGroupId: serviceAlbSg.id,
- description: 'Allow inbound HTTPS traffic',
- cidrIpv4: '0.0.0.0/0',
- fromPort: 443,
- ipProtocol: 'tcp',
- toPort: 443,
- tags: this.tags,
- },
- { parent: this }
- );
-
- new aws.vpc.SecurityGroupEgressRule(
- `${KEBAB_BASE_NAME}-out-service`,
- {
- description: 'Allow traffic to the service security group',
- securityGroupId: serviceAlbSg.id,
- referencedSecurityGroupId: serviceSg.id,
- fromPort: serviceContainerPort,
- ipProtocol: 'tcp',
- toPort: serviceContainerPort,
- tags: this.tags,
- },
- { parent: this }
- );
-
- return { serviceAlbSg, serviceSg };
- }
-
- setupAutoScaling() {
- if (!this.service) return;
-
- const serviceScalableTarget = new aws.appautoscaling.Target(
- `${KEBAB_BASE_NAME}-service-scalable-target-${stack}`,
- {
- maxCapacity: stack === 'prod' ? 10 : 3,
- minCapacity: 1,
- resourceId: pulumi.interpolate`service/${this.cloudStorageClusterName}/${this.service.service.name}`,
- scalableDimension: 'ecs:service:DesiredCount',
- serviceNamespace: 'ecs',
- tags: this.tags,
- },
- { 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}`;
-
- // Create an Auto Scaling policy for request count.
- new aws.appautoscaling.Policy(
- `${KEBAB_BASE_NAME}-scaling-policy-request-count-${stack}`,
- {
- policyType: 'TargetTrackingScaling',
- resourceId: serviceScalableTarget.resourceId,
- scalableDimension: serviceScalableTarget.scalableDimension,
- serviceNamespace: serviceScalableTarget.serviceNamespace,
- targetTrackingScalingPolicyConfiguration: {
- targetValue: 1000, // TODO: play with this
- predefinedMetricSpecification: {
- predefinedMetricType: 'ALBRequestCountPerTarget',
- resourceLabel,
- },
- scaleInCooldown: 60,
- scaleOutCooldown: 120,
- },
- },
- { parent: this }
- );
-
- // Create an Auto Scaling policy for CPU utilization.
- new aws.appautoscaling.Policy(
- `${KEBAB_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(
- `${KEBAB_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(
- `${KEBAB_BASE_NAME}-high-cpu-alarm`,
- {
- name: `${KEBAB_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 ${PROJECT} service.`,
- actionsEnabled: true,
- alarmActions: [CLOUD_TRAIL_SNS_TOPIC_ARN],
- tags: this.tags,
- },
- { parent: this }
- );
-
- new aws.cloudwatch.MetricAlarm(
- `${KEBAB_BASE_NAME}-high-mem-alarm`,
- {
- name: `${KEBAB_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 ${PROJECT} service.`,
- actionsEnabled: true,
- alarmActions: [CLOUD_TRAIL_SNS_TOPIC_ARN],
- tags: this.tags,
- },
- { parent: this }
- );
-
- new aws.cloudwatch.MetricAlarm(
- `${KEBAB_BASE_NAME}-http-5xx-alarm`,
- {
- name: `${KEBAB_BASE_NAME}-http-5xx-${stack}`,
- metricName: 'HTTPCode_ELB_5XX_Count',
- namespace: 'AWS/ApplicationELB',
- statistic: 'Sum',
- period: 180,
- evaluationPeriods: 1,
- threshold: 25,
- comparisonOperator: 'GreaterThanOrEqualToThreshold',
- dimensions: {
- LoadBalancer: this.lb.arn,
- },
- alarmDescription: `High HTTP 5XX count alarm for ${PROJECT} Load Balancer.`,
- actionsEnabled: true,
- alarmActions: [CLOUD_TRAIL_SNS_TOPIC_ARN],
- tags: this.tags,
- },
- { parent: this }
- );
- }
-}
diff --git a/infra/stacks/metering-service/tsconfig.json b/infra/stacks/metering-service/tsconfig.json
deleted file mode 100644
index 4082f16a5d..0000000000
--- a/infra/stacks/metering-service/tsconfig.json
+++ /dev/null
@@ -1,3 +0,0 @@
-{
- "extends": "../../tsconfig.json"
-}