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

Feat/stagingBuildTimes #1008

Merged
merged 5 commits into from
Nov 2, 2023
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
1 change: 1 addition & 0 deletions kishore-test-dev-emil/kishore-test-dev-emil
Submodule kishore-test-dev-emil added at 3478fc
1 change: 1 addition & 0 deletions pa-corp/pa-corp
Submodule pa-corp added at 1c144c
1 change: 1 addition & 0 deletions src/constants/featureFlags.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
export const FEATURE_FLAGS = {
IS_BUILD_TIMES_REDUCTION_ENABLED: "is_build_times_reduction_enabled",
IS_GGS_ENABLED: "is_ggs_enabled",
IS_SHOW_STAGING_BUILD_STATUS_ENABLED: "is_show_staging_build_status_enabled",
} as const
24 changes: 24 additions & 0 deletions src/routes/v2/authenticated/sites.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import { ProdPermalink, StagingPermalink } from "@root/types/pages"
import { PreviewInfo } from "@root/types/previewInfo"
import { RepositoryData } from "@root/types/repoInfo"
import { SiteInfo, SiteLaunchDto } from "@root/types/siteInfo"
import { StagingBuildStatus } from "@root/types/stagingBuildStatus"
import type SitesService from "@services/identity/SitesService"

type SitesRouterProps = {
Expand Down Expand Up @@ -169,6 +170,23 @@ export class SitesRouter {
.getSitesPreview(req.body.sites, res.locals.userSessionData)
.then((previews) => res.status(200).json(previews))

getUserStagingSiteBuildStatus: RequestHandler<
{ siteName: string },
StagingBuildStatus | ResponseErrorBody,
never,
never,
{ userWithSiteSessionData: UserWithSiteSessionData }
> = async (req, res) => {
const { userWithSiteSessionData } = res.locals
const result = await this.sitesService.getUserStagingSiteBuildStatus(
userWithSiteSessionData
)
if (result.isOk()) {
return res.status(200).json(result.value)
}
return res.status(404).json({ message: "Unable to get staging status" })
}

getRouter() {
const router = express.Router({ mergeParams: true })

Expand Down Expand Up @@ -210,6 +228,12 @@ export class SitesRouter {
this.authorizationMiddleware.verifySiteAdmin,
attachReadRouteHandlerWrapper(this.launchSite)
)
router.get(
"/:siteName/getStagingBuildStatus",
attachSiteHandler,
this.authorizationMiddleware.verifySiteMember,
attachReadRouteHandlerWrapper(this.getUserStagingSiteBuildStatus)
)

// The /sites/preview is a POST endpoint as the frontend sends
// a list of sites to obtain previews for. This is to support
Expand Down
27 changes: 26 additions & 1 deletion src/services/identity/DeploymentClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,11 @@ import {
UpdateBranchCommand,
UpdateBranchCommandOutput,
UpdateBranchCommandInput,
ListJobsCommand,
ListJobsCommandOutput,
JobSummary,
} from "@aws-sdk/client-amplify"
import { ResultAsync } from "neverthrow"
import { ResultAsync, errAsync, fromPromise, okAsync } from "neverthrow"

import { config } from "@config/config"

Expand Down Expand Up @@ -69,6 +72,11 @@ class DeploymentClient {
this.amplifyClient.send(new UpdateBranchCommand(options))
) as ResultAsync<UpdateBranchCommandOutput, AmplifyError>

sendListJobsApp = (appId: string, branchName: string) =>
wrap(
this.amplifyClient.send(new ListJobsCommand({ appId, branchName }))
) as ResultAsync<ListJobsCommandOutput, AmplifyError>

generateCreateAppInput = (
repoName: string,
repoUrl: string
Expand Down Expand Up @@ -113,6 +121,23 @@ class DeploymentClient {
enableBasicAuth: true,
basicAuthCredentials: Buffer.from(`user:${password}`).toString("base64"),
})

getJobSummaries = (
appId: string,
branchName: string
): ResultAsync<JobSummary[], AmplifyError> =>
fromPromise(
this.sendListJobsApp(appId, branchName),
(err) => new AmplifyError(`${err}`)
).andThen((resp) => {
if (resp.isErr()) {
return errAsync(resp.error)
}
if (!resp.value.jobSummaries) {
return errAsync(new AmplifyError("No job summaries"))
}
return okAsync(resp.value.jobSummaries)
})
}

export default DeploymentClient
62 changes: 61 additions & 1 deletion src/services/identity/DeploymentsService.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
import { Result, errAsync, okAsync } from "neverthrow"
import { JobStatus } from "@aws-sdk/client-amplify"
import { Result, ResultAsync, errAsync, fromPromise, okAsync } from "neverthrow"
import { ModelStatic } from "sequelize"

import { config } from "@config/config"

import logger from "@logger/logger"

import { Deployment, Repo, Site } from "@database/models"
import { STAGING_BRANCH, STAGING_LITE_BRANCH } from "@root/constants"
import { NotFoundError } from "@root/errors/NotFoundError"
import { AmplifyError, AmplifyInfo } from "@root/types/index"
import { BuildStatus, StatusStates } from "@root/types/stagingBuildStatus"
import { Brand } from "@root/types/util"
import { decryptPassword, encryptPassword } from "@root/utils/crypto-utils"
import DeploymentClient from "@services/identity/DeploymentClient"
Expand Down Expand Up @@ -259,6 +262,63 @@ class DeploymentsService {
)
return okAsync(deploymentInfo)
}

getStagingSiteBuildStatus = (
siteId: string,
isRepoWhiteListedForBuildRed: boolean
): ResultAsync<BuildStatus, NotFoundError | AmplifyError> =>
fromPromise(
this.deploymentsRepository.findOne({
where: {
siteId,
},
}),
() => new NotFoundError("Site has not been deployed!")
)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: this should be a different error since it means the DB couldn't be queried.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

wait no in this case the deployments row doesnt exist, so it is the case that the site has not been deployed!

.andThen((deploymentInfo) => {
if (!deploymentInfo) {
return errAsync(new NotFoundError("Site has not been deployed!"))
}
return okAsync(deploymentInfo)
})
.andThen((deploymentInfo) => {
let userStagingApp: string
const { hostingId, stagingLiteHostingId } = deploymentInfo
if (isRepoWhiteListedForBuildRed) {
userStagingApp = stagingLiteHostingId
} else {
userStagingApp = hostingId
}

if (!userStagingApp) {
return errAsync(
new NotFoundError("Staging site has not been deployed!")
)
}
return okAsync(userStagingApp)
})
.andThen((userStagingApp) => {
const branchName = isRepoWhiteListedForBuildRed
? STAGING_LITE_BRANCH
: STAGING_BRANCH
return this.deploymentClient.getJobSummaries(userStagingApp, branchName)
})
.andThen((jobSummaries) => {
if (jobSummaries.length === 0) {
return okAsync(StatusStates.pending)
}

const jobSummary = jobSummaries[0]

switch (jobSummary.status) {
case JobStatus.SUCCEED:
return okAsync(StatusStates.ready)
case JobStatus.FAILED:
return okAsync(StatusStates.error)
default:
return okAsync(StatusStates.pending)
}
})
}

export default DeploymentsService
27 changes: 26 additions & 1 deletion src/services/identity/SitesService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,19 @@ import {
getAllRepoData,
SitesCacheService,
} from "@root/services/identity/SitesCacheService"
import { AmplifyError } from "@root/types"
import { GitHubCommitData } from "@root/types/commitData"
import { ConfigYmlData } from "@root/types/configYml"
import { ProdPermalink, StagingPermalink } from "@root/types/pages"
import { PreviewInfo } from "@root/types/previewInfo"
import type { RepositoryData, SiteUrls } from "@root/types/repoInfo"
import { SiteInfo } from "@root/types/siteInfo"
import { StagingBuildStatus } from "@root/types/stagingBuildStatus"
import { Brand } from "@root/types/util"
import { isReduceBuildTimesWhitelistedRepo } from "@root/utils/growthbook-utils"
import {
isReduceBuildTimesWhitelistedRepo,
isShowStagingBuildStatusWhitelistedRepo,
} from "@root/utils/growthbook-utils"
import { safeJsonParse } from "@root/utils/json"
import RepoService from "@services/db/RepoService"
import { ConfigYmlService } from "@services/fileServices/YmlFileServices/ConfigYmlService"
Expand Down Expand Up @@ -536,6 +541,26 @@ class SitesService {
})
)
}

getUserStagingSiteBuildStatus(
userSessionData: UserWithSiteSessionData
): ResultAsync<
StagingBuildStatus,
NotFoundError | MissingSiteError | AmplifyError
> {
const { siteName, growthbook } = userSessionData
if (!isShowStagingBuildStatusWhitelistedRepo(growthbook)) {
return errAsync(new NotFoundError())
}
return this.getBySiteName(siteName)
.andThen((site) =>
this.deploymentsService.getStagingSiteBuildStatus(
site.id.toString(),
isReduceBuildTimesWhitelistedRepo(growthbook)
)
)
.map((status) => ({ status }))
}
}

export default SitesService
1 change: 1 addition & 0 deletions src/types/featureFlags.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
export interface FeatureFlags {
is_build_times_reduction_enabled: boolean
is_ggs_enabled: boolean
is_show_staging_build_status_enabled: boolean
}

// List of attributes we set in GrowthBook Instance in auth middleware
Expand Down
10 changes: 10 additions & 0 deletions src/types/stagingBuildStatus.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
export const StatusStates = {
pending: "PENDING",
ready: "READY",
error: "ERROR",
} as const
export type BuildStatus = typeof StatusStates[keyof typeof StatusStates]

export interface StagingBuildStatus {
status: BuildStatus
}
11 changes: 11 additions & 0 deletions src/utils/growthbook-utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,3 +34,14 @@ export const isReduceBuildTimesWhitelistedRepo = (

return isWhitelistedRedBuildTimesRepo
}

export const isShowStagingBuildStatusWhitelistedRepo = (
growthbook: GrowthBook<FeatureFlags> | undefined
): boolean => {
if (!growthbook) return false

return growthbook.getFeatureValue(
FEATURE_FLAGS.IS_SHOW_STAGING_BUILD_STATUS_ENABLED,
false
)
}
Loading