Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 54 additions & 0 deletions .github/workflows/infracost.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
name: Generate Infra cost report
on:
pull_request:
types: [opened, synchronize, closed]
push:
branches:
- main

env:
SSH_AUTH_SOCK: /tmp/ssh_agent.sock
jobs:
infracost-pull-request-checks:
name: Infracost Pull Request Checks
if: github.event_name == 'pull_request' && (github.event.action == 'opened' || github.event.action == 'synchronize')
runs-on: ubuntu-latest
permissions:
contents: read
pull-requests: write # Required to post comments
steps:
- name: Setup Infracost
uses: infracost/actions/setup@v3
with:
api-key: ${{ secrets.INFRACOST_API_KEY }}

- name: Checkout base branch
uses: actions/checkout@v4
with:
ref: '${{ github.event.pull_request.base.ref }}'

- name: Generate Infracost cost estimate baseline
run: |
infracost breakdown --path=terraform/ \
--format=json \
--usage-file infracost-usage.yml \
--out-file=/tmp/infracost-base.json

- name: Checkout PR branch
uses: actions/checkout@v4

- name: Generate Infracost diff
run: |
infracost diff --path=terraform/ \
--format=json \
--usage-file infracost-usage.yml \
--compare-to=/tmp/infracost-base.json \
--out-file=/tmp/infracost.json

- name: Post Infracost comment
run: |
infracost comment github --path=/tmp/infracost.json \
--repo=$GITHUB_REPOSITORY \
--github-token=${{ github.token }} \
--pull-request=${{ github.event.pull_request.number }} \
--behavior=update
982 changes: 982 additions & 0 deletions infracost-usage.yml

Large diffs are not rendered by default.

96 changes: 30 additions & 66 deletions src/api/routes/events.ts
Original file line number Diff line number Diff line change
Expand Up @@ -318,7 +318,7 @@ const eventsPlugin: FastifyPluginAsyncZodOpenApi = async (
schema: withRoles(
[AppRoles.EVENTS_MANAGER],
withTags(["Events"], {
body: postRequestSchema.partial(),
body: postRequestSchema,
params: z.object({
id: z.string().min(1).meta({
description: "Event ID to modify.",
Expand All @@ -327,12 +327,7 @@ const eventsPlugin: FastifyPluginAsyncZodOpenApi = async (
}),
response: {
201: {
description: "The event has been modified.",
content: {
"application/json": {
schema: z.null(),
},
},
description: "The event has been modified successfully.",
},
404: notFoundError,
},
Expand All @@ -345,64 +340,29 @@ const eventsPlugin: FastifyPluginAsyncZodOpenApi = async (
if (!request.username) {
throw new UnauthenticatedError({ message: "Username not found." });
}

try {
const updatableFields = Object.keys(postRequestSchema.shape);
const entryUUID = request.params.id;
const requestData = request.body;

const setParts: string[] = [];
const removeParts: string[] = [];
const expressionAttributeNames: Record<string, string> = {};
const expressionAttributeValues: Record<string, any> = {};

setParts.push("#updatedAt = :updatedAt");
expressionAttributeNames["#updatedAt"] = "updatedAt";
expressionAttributeValues[":updatedAt"] = new Date().toISOString();

updatableFields.forEach((key) => {
if (Object.hasOwn(requestData, key)) {
setParts.push(`#${key} = :${key}`);
expressionAttributeNames[`#${key}`] = key;
expressionAttributeValues[`:${key}`] =
requestData[key as keyof typeof requestData];
} else {
removeParts.push(`#${key}`);
expressionAttributeNames[`#${key}`] = key;
}
});

// Construct the final UpdateExpression by combining SET and REMOVE
let updateExpression = `SET ${setParts.join(", ")}`;
if (removeParts.length > 0) {
updateExpression += ` REMOVE ${removeParts.join(", ")}`;
}
const updatedItem = {
...request.body,
id: entryUUID,
updatedAt: new Date().toISOString(),
};

const command = new UpdateItemCommand({
const command = new PutItemCommand({
TableName: genericConfig.EventsDynamoTableName,
Key: { id: { S: entryUUID } },
UpdateExpression: updateExpression,
ExpressionAttributeNames: expressionAttributeNames,
Item: marshall(updatedItem),
ConditionExpression: "attribute_exists(id)",
ExpressionAttributeValues: marshall(expressionAttributeValues),
ReturnValues: "ALL_OLD",
});

let oldAttributes;
let updatedEntry;
try {
oldAttributes = (await fastify.dynamoClient.send(command)).Attributes;

const result = await fastify.dynamoClient.send(command);
oldAttributes = result.Attributes;
if (!oldAttributes) {
throw new DatabaseInsertError({
message: "Item not found or update failed.",
});
throw new NotFoundError({ endpointName: request.url });
}

const oldEntry = oldAttributes ? unmarshall(oldAttributes) : null;
// we know updateData has no undefines because we filtered them out.
updatedEntry = {
...oldEntry,
...requestData,
} as unknown as IUpdateDiscord;
} catch (e: unknown) {
if (
e instanceof Error &&
Expand All @@ -414,16 +374,24 @@ const eventsPlugin: FastifyPluginAsyncZodOpenApi = async (
throw e;
}
request.log.error(e);
throw new DiscordEventError({});
throw new DatabaseInsertError({
message: "Failed to update event in Dynamo table.",
});
}
if (updatedEntry.featured && !updatedEntry.repeats) {

const updatedEntryForDiscord = updatedItem as unknown as IUpdateDiscord;

if (
updatedEntryForDiscord.featured &&
!updatedEntryForDiscord.repeats
) {
try {
await updateDiscord(
{
botToken: fastify.secretConfig.discord_bot_token,
guildId: fastify.environmentConfig.DiscordGuildId,
},
updatedEntry,
updatedEntryForDiscord,
request.username,
false,
request.log,
Expand All @@ -437,10 +405,11 @@ const eventsPlugin: FastifyPluginAsyncZodOpenApi = async (
);

if (e instanceof Error) {
request.log.error(`Failed to publish event to Discord: ${e} `);
request.log.error(`Failed to publish event to Discord: ${e}`);
}
}
}

const postUpdatePromises = [
atomicIncrementCacheCounter(
fastify.dynamoClient,
Expand All @@ -466,14 +435,8 @@ const eventsPlugin: FastifyPluginAsyncZodOpenApi = async (
}),
];
await Promise.all(postUpdatePromises);

reply
.status(201)
.header(
"Location",
`${fastify.environmentConfig.UserFacingUrl}/api/v1/events/${entryUUID}`,
)
.send();
reply.header("location", request.url);
reply.status(201).send();
} catch (e: unknown) {
if (e instanceof Error) {
request.log.error(`Failed to update DynamoDB: ${e.toString()}`);
Expand All @@ -487,6 +450,7 @@ const eventsPlugin: FastifyPluginAsyncZodOpenApi = async (
}
},
);

fastify.withTypeProvider<FastifyZodOpenApiTypeProvider>().post(
"",
{
Expand Down
34 changes: 34 additions & 0 deletions terraform/modules/frontend/main.tf
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,40 @@ resource "aws_s3_bucket" "frontend" {
bucket = "${var.BucketPrefix}-${var.ProjectId}"
}

resource "aws_s3_bucket_lifecycle_configuration" "frontend" {
bucket = aws_s3_bucket.frontend.id

rule {
id = "AbortIncompleteMultipartUploads"
status = "Enabled"

abort_incomplete_multipart_upload {
days_after_initiation = 1
}
}

rule {
id = "ObjectLifecycle"
status = "Enabled"

filter {}

transition {
days = 30
storage_class = "INTELLIGENT_TIERING"
}

noncurrent_version_transition {
noncurrent_days = 30
storage_class = "STANDARD_IA"
}

noncurrent_version_expiration {
noncurrent_days = 60
}
}
}

data "archive_file" "ui" {
type = "zip"
source_dir = "${path.module}/../../../dist_ui/"
Expand Down
4 changes: 2 additions & 2 deletions terraform/modules/lambdas/main.tf
Original file line number Diff line number Diff line change
Expand Up @@ -418,13 +418,13 @@ resource "aws_lambda_function_url" "slow_api_lambda_function_url" {
}

module "lambda_warmer_main" {
source = "github.com/acm-uiuc/terraform-modules/lambda-warmer?ref=b52f22e32c6c07af9b1b4750a226882aaccc769d"
source = "git::https://github.com/acm-uiuc/terraform-modules.git//lambda-warmer?ref=b52f22e32c6c07af9b1b4750a226882aaccc769d"
function_to_warm = local.core_api_lambda_name
is_streaming_lambda = true
}

module "lambda_warmer_slow" {
source = "github.com/acm-uiuc/terraform-modules/lambda-warmer?ref=b52f22e32c6c07af9b1b4750a226882aaccc769d"
source = "git::https://github.com/acm-uiuc/terraform-modules.git//lambda-warmer?ref=b52f22e32c6c07af9b1b4750a226882aaccc769d"
function_to_warm = local.core_api_slow_lambda_name
is_streaming_lambda = true
}
Expand Down
13 changes: 9 additions & 4 deletions tests/live/events.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,14 @@ describe("Event lifecycle tests", async () => {
"Content-Type": "application/json",
},
body: JSON.stringify({
description: "An event of all time THAT HAS BEEN MODIFIED",
title: "Modified Live Testing Event",
description: "An event of all time",
start: "2024-12-31T02:00:00",
end: "2024-12-31T03:30:00",
location: "ACM Room (Siebel 1104)",
host: "ACM",
featured: true,
repeats: "weekly",
}),
},
);
Expand All @@ -154,9 +161,7 @@ describe("Event lifecycle tests", async () => {
expect(response.status).toBe(200);
expect(responseJson).toHaveProperty("id");
expect(responseJson).toHaveProperty("description");
expect(responseJson["description"]).toStrictEqual(
"An event of all time THAT HAS BEEN MODIFIED",
);
expect(responseJson["title"]).toStrictEqual("Modified Live Testing Event");
});

test("deleting a previously-created event", { timeout: 30000 }, async () => {
Expand Down
18 changes: 10 additions & 8 deletions tests/unit/eventPost.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -498,9 +498,9 @@ describe("Event modification tests", async () => {
const ourError = new Error("Nonexistent event.");
ourError.name = "ConditionalCheckFailedException";
ddbMock
.on(UpdateItemCommand, {
.on(PutItemCommand, {
TableName: genericConfig.EventsDynamoTableName,
Key: { id: { S: eventUuid } },
Item: { id: { S: eventUuid } },
})
.rejects(ourError);
const testJwt = createJwt();
Expand All @@ -509,7 +509,12 @@ describe("Event modification tests", async () => {
.patch(`/api/v1/events/${eventUuid}`)
.set("authorization", `Bearer ${testJwt}`)
.send({
paidEventId: "sp24_semiformal_2",
description: "First test event",
host: "Social Committee",
location: "Siebel Center",
start: "2024-09-25T18:00:00",
title: "Event 1",
featured: false,
});

expect(response.statusCode).toBe(404);
Expand All @@ -531,19 +536,16 @@ describe("Event modification tests", async () => {
};
ddbMock.reset();
ddbMock
.on(UpdateItemCommand, {
.on(PutItemCommand, {
TableName: genericConfig.EventsDynamoTableName,
Key: { id: { S: eventUuid } },
})
.resolves({ Attributes: marshall(event) });
const testJwt = createJwt();
await app.ready();
const response = await supertest(app.server)
.patch(`/api/v1/events/${eventUuid}`)
.set("authorization", `Bearer ${testJwt}`)
.send({
paidEventId: "sp24_semiformal_2",
});
.send(event);

expect(response.statusCode).toBe(201);
expect(response.header["location"]).toBeDefined();
Expand Down
Loading