Skip to content

Commit

Permalink
add logic to wait for job completion
Browse files Browse the repository at this point in the history
  • Loading branch information
taraspos committed Dec 16, 2024
1 parent 8790c1f commit b1f7d99
Show file tree
Hide file tree
Showing 5 changed files with 86 additions and 150 deletions.
138 changes: 0 additions & 138 deletions .github/actions/amplify-preview/action.yaml

This file was deleted.

4 changes: 4 additions & 0 deletions tools/amplify-preview/action.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,9 @@ inputs:
github_token:
required: true
description: "Github token with permissions to read/write comments in pull request"
wait:
default: "false"
description: "If Amplify deployment is pending/running state wait for it's completion"
runs:
using: composite
steps:
Expand All @@ -30,6 +33,7 @@ runs:
GIT_BRANCH_NAME: ${{ steps.extract_branch.outputs.branch }}
CREATE_BRANCHES: ${{ inputs.create_branches }}
GITHUB_TOKEN: ${{ inputs.github_token }}
WAIT: ${{ inputs.wait }}
shell: bash
run: |
pushd ./tools/amplify-preview/; go run ./; popd
47 changes: 38 additions & 9 deletions tools/amplify-preview/amplify.go
Original file line number Diff line number Diff line change
@@ -1,3 +1,19 @@
/*
Copyright 2024 Gravitational, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package main

import (
Expand All @@ -15,8 +31,13 @@ import (
)

var (
errBranchNotFound = errors.New("Branch not found")
errNoJobForBranch = errors.New("Current branch has no jobs")
errBranchNotFound = errors.New("Branch not found")
errNoJobForBranch = errors.New("Current branch has no jobs")
amplifyJobCompletedStatuses = map[types.JobStatus]struct{}{
types.JobStatusFailed: {},
types.JobStatusCancelled: {},
types.JobStatusSucceed: {},
}
)

const (
Expand Down Expand Up @@ -147,7 +168,7 @@ func (amp *AmplifyPreview) StartJob(ctx context.Context, branch *types.Branch) (

}

func (amp *AmplifyPreview) GetJob(ctx context.Context, branch *types.Branch, jobID *string) (*types.JobSummary, error) {
func (amp *AmplifyPreview) GetLatestJob(ctx context.Context, branch *types.Branch, jobID *string) (*types.JobSummary, error) {
appID, err := appIDFromBranchARN(*branch.BranchArn)
if err != nil {
return nil, err
Expand All @@ -158,16 +179,17 @@ func (amp *AmplifyPreview) GetJob(ctx context.Context, branch *types.Branch, job
}

if jobID != nil {
resp, err := amp.client.GetJob(ctx, &amplify.GetJobInput{
resp, err := amp.client.ListJobs(ctx, &amplify.ListJobsInput{
AppId: aws.String(appID),
BranchName: branch.BranchName,
JobId: jobID,
MaxResults: 1,
})
if err != nil {
return nil, err
}

return resp.Job.Summary, nil
if len(resp.JobSummaries) > 0 {
return &resp.JobSummaries[0], nil
}
}

return nil, errNoJobForBranch
Expand All @@ -186,6 +208,11 @@ func appIDFromBranchARN(branchArn string) (string, error) {
return "", fmt.Errorf("Invalid branch ARN")
}

func isAmplifyJobCompleted(job *types.JobSummary) bool {
_, ok := amplifyJobCompletedStatuses[job.Status]
return ok
}

func (err aggregatedError) Error() error {
if len(err.perAppErr) == 0 {
return nil
Expand All @@ -200,7 +227,7 @@ func (err aggregatedError) Error() error {
}

func amplifyJobToMarkdown(job *types.JobSummary, branch *types.Branch) string {
var mdTableHeader = [...]string{"Branch", "Commit", "Status", "Preview", "Updated (UTC)"}
var mdTableHeader = [...]string{"Branch", "Commit", "Job ID", "Status", "Preview", "Updated (UTC)"}
var commentBody strings.Builder
var jobStatusToEmoji = map[types.JobStatus]rune{
types.JobStatusFailed: '❌',
Expand Down Expand Up @@ -233,9 +260,11 @@ func amplifyJobToMarkdown(job *types.JobSummary, branch *types.Branch) string {
commentBody.WriteString(" | ")
commentBody.WriteString(*job.CommitId)
commentBody.WriteString(" | ")
commentBody.WriteString(*job.JobId)
commentBody.WriteString(" | ")
commentBody.WriteString(fmt.Sprintf("%c%s", jobStatusToEmoji[job.Status], job.Status))
commentBody.WriteString(" | ")
commentBody.WriteString(fmt.Sprintf("https://%s.%s.%s", *branch.DisplayName, appID, amplifyDefaultDomain))
commentBody.WriteString(fmt.Sprintf("[%[1]s](https://%[1]s.%s.%s)", *branch.DisplayName, appID, amplifyDefaultDomain))
commentBody.WriteString(" | ")
commentBody.WriteString(updateTime.Format(time.DateTime))
commentBody.WriteByte('\n')
Expand Down
16 changes: 16 additions & 0 deletions tools/amplify-preview/github.go
Original file line number Diff line number Diff line change
@@ -1,3 +1,19 @@
/*
Copyright 2024 Gravitational, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package main

import (
Expand Down
31 changes: 28 additions & 3 deletions tools/amplify-preview/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import (
"log/slog"
"os"
"strings"
"time"

"github.com/alecthomas/kingpin/v2"
"github.com/aws/aws-sdk-go-v2/aws"
Expand All @@ -38,6 +39,13 @@ var (
gitBranchName = kingpin.Flag("git-branch-name", "Git branch name").Envar("GIT_BRANCH_NAME").Required().String()
createBranches = kingpin.Flag("crate-branches",
"Defines whether Amplify branches should be created if missing, or just lookup existing ones").Envar("CREATE_BRANCHES").Default("false").Bool()
wait = kingpin.Flag("wait",
"Wait for pending/running job to complete").Envar("wait").Default("false").Bool()
)

const (
jobWaitSleepTime = 30 * time.Second
jobWaitTimeAttempts = 40
)

func main() {
Expand Down Expand Up @@ -81,7 +89,7 @@ func main() {
}

// check if existing branch was/being deployed already
job, err := amp.GetJob(ctx, branch, nil)
job, err := amp.GetLatestJob(ctx, branch, nil)
if err != nil {
if !*createBranches && !errors.Is(err, errNoJobForBranch) {
logger.Error("failed to get amplify job", logKeyBranchName, *gitBranchName, "error", err)
Expand All @@ -100,11 +108,28 @@ func main() {
logger.Error("failed to post preview URL", "error", err)
os.Exit(1)
}

logger.Info("Successfully posted PR comment")

if *wait {
for i := 0; !isAmplifyJobCompleted(job) && i < jobWaitTimeAttempts; i++ {
job, err := amp.GetLatestJob(ctx, branch, nil)
if err != nil {
logger.Error("failed to get amplify job", logKeyBranchName, *gitBranchName, "error", err)
os.Exit(1)
}

logger.Info("Job is not in a completed state yet. Sleeping...", logKeyBranchName, *gitBranchName, "job_status", job.Status, "job_id", job.JobId)
time.Sleep(jobWaitSleepTime)
}

if err := postPreviewURL(ctx, amplifyJobToMarkdown(job, branch)); err != nil {
logger.Error("failed to post preview URL", "error", err)
os.Exit(1)
}
}

if job.Status == types.JobStatusFailed {
logger.Error("amplify job is in failed state", "job_status", job.Status, "job_id", job.JobId)
logger.Error("amplify job is in failed state", logKeyBranchName, *gitBranchName, "job_status", job.Status, "job_id", job.JobId)
os.Exit(1)
}
}

0 comments on commit b1f7d99

Please sign in to comment.