Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ISOM-1293: Add CodeBuild logic #382

Merged
merged 20 commits into from
Aug 13, 2024
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
5 changes: 3 additions & 2 deletions apps/studio/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,9 @@
"seed": "tsx prisma/seed.ts"
},
"dependencies": {
"@aws-sdk/client-s3": "3.627.0",
"@aws-sdk/s3-request-presigner": "3.627.0",
"@aws-sdk/client-codebuild": "^3.624.0",
"@aws-sdk/client-s3": "3.626.0",
"@aws-sdk/s3-request-presigner": "3.626.0",
"@chakra-ui/anatomy": "^2.2.2",
"@chakra-ui/react": "^2.8.2",
"@chakra-ui/styled-system": "^2.9.2",
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
-- AlterTable
ALTER TABLE "Site" ADD COLUMN "codeBuildId" TEXT;
1 change: 1 addition & 0 deletions apps/studio/prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,7 @@ model Site {
theme Json?
navbar Navbar?
footer Footer?
codeBuildId String?
}

model Navbar {
Expand Down
75 changes: 75 additions & 0 deletions apps/studio/src/server/modules/aws/codebuild.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
import type { StartBuildCommandOutput } from "@aws-sdk/client-codebuild"
import type pino from "pino"
import {
BatchGetBuildsCommand,
CodeBuildClient,
ListBuildsForProjectCommand,
StartBuildCommand,
StopBuildCommand,
} from "@aws-sdk/client-codebuild"

const client = new CodeBuildClient({ region: "ap-southeast-1" })

export const stopRunningBuilds = async (
logger: pino.Logger<string>,
projectId: string,
): Promise<void> => {
try {
// List builds for the given project
const listBuildsCommand = new ListBuildsForProjectCommand({
projectName: projectId,
})
const listBuildsResponse = await client.send(listBuildsCommand)

const buildIds = listBuildsResponse.ids ?? []

if (buildIds.length === 0) {
logger.info({ projectId }, "No running builds found for the project")
return
}

// Get details of the builds
const batchGetBuildsCommand = new BatchGetBuildsCommand({ ids: buildIds })
const batchGetBuildsResponse = await client.send(batchGetBuildsCommand)

// Stop running builds
for (const build of batchGetBuildsResponse.builds ?? []) {
if (build.buildStatus === "IN_PROGRESS") {
logger.info(
{ buildId: build.id },
"Stopping currently running CodeBuild",
)
const stopBuildCommand = new StopBuildCommand({ id: build.id })
await client.send(stopBuildCommand)
logger.info({ buildId: build.id }, "Build stopped successfully")
}
}
} catch (error) {
logger.error(
{ projectId, error },
"Unexpected error while stopping running builds",
)
throw error
}
}

export const startProjectById = async (
logger: pino.Logger<string>,
projectId: string,
): Promise<StartBuildCommandOutput> => {
try {
// Stop any currently running builds
await stopRunningBuilds(logger, projectId)

// Start a new build
const command = new StartBuildCommand({ projectName: projectId })
const response = await client.send(command)
return response
} catch (error) {
logger.error(
{ projectId, error },
"Unexpected error when starting CodeBuild project run",
)
throw error
}
}
22 changes: 19 additions & 3 deletions apps/studio/src/server/modules/page/page.router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { schema } from "@opengovsg/isomer-components"
import { TRPCError } from "@trpc/server"
import Ajv from "ajv"
import isEqual from "lodash/isEqual"
import { z } from "zod"

import {
createPageSchema,
Expand All @@ -15,6 +16,7 @@ import {
} from "~/schemas/page"
import { protectedProcedure, router } from "~/server/trpc"
import { safeJsonParse } from "~/utils/safeJsonParse"
import { startProjectById, stopRunningBuilds } from "../aws/codebuild.service"
import { db, ResourceType } from "../database"
import {
getFooter,
Expand All @@ -24,7 +26,7 @@ import {
updateBlobById,
updatePageById,
} from "../resource/resource.service"
import { getSiteConfig } from "../site/site.service"
import { getSiteConfig, getSiteNameAndCodeBuildId } from "../site/site.service"
import { incrementVersion } from "../version/version.service"
import { createDefaultPage } from "./page.service"

Expand Down Expand Up @@ -254,8 +256,22 @@ export const pageRouter = router({
pageId,
userId: ctx.user.id,
})
return addedVersionResult

/* TODO: Step 2: Use AWS SDK to start a CodeBuild */
/* Step 2: Use AWS SDK to start a CodeBuild */
const site = await getSiteNameAndCodeBuildId(siteId)
const codeBuildId = site.codeBuildId
if (!codeBuildId) {
throw new TRPCError({
harishv7 marked this conversation as resolved.
Show resolved Hide resolved
code: "INTERNAL_SERVER_ERROR",
message: "No CodeBuild project ID found for site",
})
}

// stop any currently running builds for the site
await stopRunningBuilds(ctx.logger, codeBuildId)

// initiate new build
await startProjectById(ctx.logger, codeBuildId)
return addedVersionResult
}),
})
9 changes: 8 additions & 1 deletion apps/studio/src/server/modules/site/site.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,16 @@ export const getSiteTheme = async (siteId: number) => {

return theme
}
export const getSiteNameAndCodeBuildId = async (siteId: number) => {
return await db
.selectFrom("Site")
.where("id", "=", siteId)
.select(["Site.codeBuildId", "Site.name"])
.executeTakeFirstOrThrow()
}

// Note: This overwrites the full site config
// TODO: Should triger immediate re-publish of site
// TODO: Should trigger immediate re-publish of site
export const setSiteConfig = async (
siteId: number,
config: IsomerSiteConfigProps,
Expand Down
4 changes: 1 addition & 3 deletions apps/studio/src/utils/trpc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -201,9 +201,7 @@ export const trpc = createTRPCNext<
},
},
mutations: {
retry: (_, error) => {
return isErrorRetryableOnClient(error)
},
retry: false,
},
},
},
Expand Down
Loading
Loading