Skip to content

Commit

Permalink
feat: finish deployment function + add zip functionality to adapter +…
Browse files Browse the repository at this point in the history
… start building delete function
  • Loading branch information
Megakuul committed Sep 14, 2024
1 parent 6ff6fe5 commit e361c86
Show file tree
Hide file tree
Showing 26 changed files with 668 additions and 254 deletions.
11 changes: 10 additions & 1 deletion adapter-battleshiper/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { writeFileSync } from 'node:fs';
import esbuild from 'esbuild';
import { fileURLToPath } from 'node:url';
import { posix } from 'node:path';
import AdmZip from "adm-zip";

/** @param {import('./index.js').default} */
export default function (options = {}) {
Expand Down Expand Up @@ -50,7 +51,6 @@ export default function (options = {}) {
bundle: true,
sourcemap: "linked",
})

if (result.warnings.length > 0) {
console.error((await esbuild.formatMessages(result.warnings, {
kind: "warning",
Expand All @@ -66,6 +66,15 @@ export default function (options = {}) {
})).join("\n"))
return
}

try {
const zip = new AdmZip();
zip.addLocalFile(`${dest}/server/index.js`, "", "index.js");
await zip.writeZipPromise(`${dest}/server/handler.zip`);
} catch (err) {
console.error("failed to create zip file:")
console.error(err.message)
}
},
};

Expand Down
214 changes: 112 additions & 102 deletions adapter-battleshiper/package-lock.json

Large diffs are not rendered by default.

5 changes: 3 additions & 2 deletions adapter-battleshiper/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
"sveltekit",
"battleshiper"
],
"version": "0.3.0",
"version": "0.4.0",
"author": "Megakuul",
"license": "MIT",
"private": false,
Expand Down Expand Up @@ -39,6 +39,7 @@
"@types/aws-lambda": "^8.10.140"
},
"dependencies": {
"esbuild": "^0.23.0"
"adm-zip": "^0.5.16",
"esbuild": "^0.23.1"
}
}
28 changes: 11 additions & 17 deletions api/resource/deleteproject/deleteproject.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import (
)

type deleteProjectInput struct {
ProjectId string `json:"project_id"`
ProjectName string `json:"project_name"`
}

type deleteProjectOutput struct {
Expand Down Expand Up @@ -73,25 +73,19 @@ func runHandleDeleteProject(request events.APIGatewayV2HTTPRequest, transportCtx
}

projectCollection := routeCtx.Database.Collection(project.PROJECT_COLLECTION)

deletedProject := &project.Project{}
err = projectCollection.FindOneAndUpdate(transportCtx, bson.M{"id": deleteProjectInput.ProjectId}, bson.M{
result, err := projectCollection.UpdateOne(transportCtx, bson.D{
{Key: "name", Value: deleteProjectInput.ProjectName},
{Key: "owner_id", Value: userToken.Id},
{Key: "deleted", Value: false},
}, bson.M{
"$set": bson.M{
"deleted": bson.M{
"$cond": bson.M{
"if": bson.M{"$eq": bson.A{"$owner_id", userToken.Id}},
"then": true,
"else": false,
},
},
"deleted": true,
},
}).Decode(&deletedProject)
})
if err != nil {
return nil, http.StatusBadRequest, fmt.Errorf("failed to mark project as deleted on database")
}

if !deletedProject.Deleted {
return nil, http.StatusForbidden, fmt.Errorf("user is not the owner of the project")
return nil, http.StatusInternalServerError, fmt.Errorf("failed to mark project as deleted on database")
} else if result.MatchedCount < 1 {
return nil, http.StatusNotFound, fmt.Errorf("project '%s' not found", deleteProjectInput.ProjectName)
}

return &deleteProjectOutput{
Expand Down
7 changes: 4 additions & 3 deletions api/resource/fetchlog/fetchlog.go
Original file line number Diff line number Diff line change
Expand Up @@ -88,9 +88,10 @@ func runHandleFetchLog(request events.APIGatewayV2HTTPRequest, transportCtx cont

specifiedProject := &project.Project{}
err = projectCollection.FindOne(transportCtx,
bson.M{
"owner_id": userToken.Id,
"name": fetchLogInput.ProjectName,
bson.D{
{Key: "owner_id", Value: userToken.Id},
{Key: "name", Value: fetchLogInput.ProjectName},
{Key: "deleted", Value: false},
},
).Decode(&specifiedProject)
if err == mongo.ErrNoDocuments {
Expand Down
1 change: 1 addition & 0 deletions api/resource/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,7 @@ func run() error {
database.SetupIndexes(databaseHandle.Collection(project.PROJECT_COLLECTION), context.TODO(), []database.Index{
{FieldNames: []string{"name"}, SortingOrder: 1, Unique: true},
{FieldNames: []string{"owner_id"}, SortingOrder: 1, Unique: false},
{FieldNames: []string{"deleted"}, SortingOrder: 1, Unique: false},
})

jwtOptions, err := auth.CreateJwtOptions(awsConfig, context.TODO(), JWT_CREDENTIAL_ARN, 0)
Expand Down
1 change: 1 addition & 0 deletions api/resource/updatealias/updatealias.go
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,7 @@ func runHandleUpdateAlias(request events.APIGatewayV2HTTPRequest, transportCtx c
err = projectCollection.FindOne(transportCtx, bson.D{
{Key: "name", Value: updateAliasInput.ProjectName},
{Key: "owner_id", Value: userDoc.Id},
{Key: "deleted", Value: false},
}).Decode(&projectDoc)
if err == mongo.ErrNoDocuments {
return nil, http.StatusNotFound, fmt.Errorf("project does not exist")
Expand Down
1 change: 1 addition & 0 deletions api/resource/updateproject/updateproject.go
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,7 @@ func runHandleUpdateProject(request events.APIGatewayV2HTTPRequest, transportCtx
result, err := projectCollection.UpdateOne(transportCtx, bson.D{
{Key: "name", Value: updateProjectInput.ProjectName},
{Key: "owner_id", Value: userDoc.Id},
{Key: "deleted", Value: false},
}, bson.M{
"$set": updateSpec,
})
Expand Down
110 changes: 110 additions & 0 deletions pipeline/delete/deleteprojects/deleteprojects.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
package deleteprojects

import (
"context"
"fmt"
"log"
"strings"
"time"

"github.com/aws/aws-lambda-go/events"
"github.com/megakuul/battleshiper/lib/model/project"
"github.com/megakuul/battleshiper/pipeline/delete/eventcontext"
"go.mongodb.org/mongo-driver/bson"
)

func HandleDeleteProjects(eventCtx eventcontext.Context) func(context.Context, events.CloudWatchEvent) error {
return func(ctx context.Context, event events.CloudWatchEvent) error {
err := runHandleDeleteProjects(event, ctx, eventCtx)
if err != nil {
log.Printf("ERROR DELETEPROJECTS: %v\n", err)
return err
}
return nil
}
}

func runHandleDeleteProjects(request events.CloudWatchEvent, transportCtx context.Context, eventCtx eventcontext.Context) error {
projectCollection := eventCtx.Database.Collection(project.PROJECT_COLLECTION)

projectDoc := &project.Project{}
err := projectCollection.FindOneAndUpdate(transportCtx, bson.D{
{Key: "name", Value: deployClaims.Project},
{Key: "owner_id", Value: deployClaims.UserID},
}, bson.M{
// Lock the pipeline, this step is used to ensure only one deployment runs at a time.
// running multiple deployments at the same time should not cause major issues,
// however it can cause weird or unintended behavior for the project.
"$set": bson.M{
"pipeline_lock": true,
},
}).Decode(&projectDoc)
if err != nil {
return fmt.Errorf("failed to fetch project from database")
}
if projectDoc.PipelineLock {
return fmt.Errorf("project locked")
}

// Finish build step
buildResult := project.BuildResult{
ExecutionIdentifier: deployRequest.Parameters.ExecutionIdentifier,
Timepoint: time.Now().Unix(),
}
if strings.ToUpper(deployRequest.Status) != "SUCCEEDED" {
buildResult.Successful = false
result, err := projectCollection.UpdateByID(transportCtx, projectDoc.MongoID, bson.M{
"$set": bson.M{
"last_build_result": buildResult,
"status": fmt.Errorf("BUILD FAILED: %v", err),
},
})
if err != nil && result.MatchedCount < 1 {
return fmt.Errorf("failed to update project (last_build_result)")
}
return nil
} else {
buildResult.Successful = true
result, err := projectCollection.UpdateByID(transportCtx, projectDoc.MongoID, bson.M{
"$set": bson.M{
"last_build_result": buildResult,
},
})
if err != nil && result.MatchedCount < 1 {
return fmt.Errorf("failed to update project (last_build_result)")
}
}

// Start actual deployment step
deploymentResult := project.DeploymentResult{
ExecutionIdentifier: deployRequest.Parameters.ExecutionIdentifier,
}
if err := deployProject(transportCtx, eventCtx, projectDoc, deployClaims.UserID, deployRequest.Parameters.ExecutionIdentifier); err != nil {
deploymentResult.Timepoint = time.Now().Unix()
deploymentResult.Successful = false
result, err := projectCollection.UpdateByID(transportCtx, projectDoc.MongoID, bson.M{
"$set": bson.M{
"last_deployment_result": deploymentResult,
"status": fmt.Errorf("DEPLOYMENT FAILED: %v", err),
},
})
if err != nil && result.MatchedCount < 1 {
return fmt.Errorf("failed to update project (last_deployment_result)")
}
return nil
} else {
deploymentResult.Timepoint = time.Now().Unix()
deploymentResult.Successful = true
result, err := projectCollection.UpdateByID(transportCtx, projectDoc.MongoID, bson.M{
"$set": bson.M{
"last_deployment_result": deploymentResult,
"status": "",
},
})
if err != nil && result.MatchedCount < 1 {
return fmt.Errorf("failed to update project (last_deployment_result)")
}
}

return nil
}
26 changes: 26 additions & 0 deletions pipeline/delete/eventcontext/eventcontext.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package eventcontext

import (
"github.com/aws/aws-sdk-go-v2/service/cloudformation"
"github.com/aws/aws-sdk-go-v2/service/cloudfrontkeyvaluestore"
"github.com/aws/aws-sdk-go-v2/service/s3"
"go.mongodb.org/mongo-driver/mongo"
)

type BucketConfiguration struct {
StaticBucketName string
}

type CloudfrontConfiguration struct {
CacheArn string
}

// Context provides data to event handlers.
type Context struct {
Database *mongo.Database
S3Client *s3.Client
CloudformationClient *cloudformation.Client
CloudfrontCacheClient *cloudfrontkeyvaluestore.Client
BucketConfiguration *BucketConfiguration
CloudfrontConfiguration *CloudfrontConfiguration
}
46 changes: 45 additions & 1 deletion pipeline/delete/go.mod
Original file line number Diff line number Diff line change
@@ -1,3 +1,47 @@
module github.com/megakuul/battleshiper/pipeline/deploy
module github.com/megakuul/battleshiper/pipeline/delete

go 1.23.0

require (
github.com/aws/aws-lambda-go v1.47.0
github.com/aws/aws-sdk-go-v2/config v1.27.33
github.com/aws/aws-sdk-go-v2/service/cloudformation v1.53.7
github.com/aws/aws-sdk-go-v2/service/cloudfrontkeyvaluestore v1.6.6
github.com/aws/aws-sdk-go-v2/service/s3 v1.61.2
github.com/megakuul/battleshiper/lib/helper v0.1.12
github.com/megakuul/battleshiper/lib/model v0.2.5
go.mongodb.org/mongo-driver v1.16.1
)

require (
github.com/aws/aws-sdk-go-v2 v1.30.5 // indirect
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.6.4 // indirect
github.com/aws/aws-sdk-go-v2/credentials v1.17.32 // indirect
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.16.13 // indirect
github.com/aws/aws-sdk-go-v2/internal/configsources v1.3.17 // indirect
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.6.17 // indirect
github.com/aws/aws-sdk-go-v2/internal/ini v1.8.1 // indirect
github.com/aws/aws-sdk-go-v2/internal/v4a v1.3.17 // indirect
github.com/aws/aws-sdk-go-v2/service/cloudwatchlogs v1.39.0 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.11.4 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.3.19 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.11.19 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.17.17 // indirect
github.com/aws/aws-sdk-go-v2/service/secretsmanager v1.32.8 // indirect
github.com/aws/aws-sdk-go-v2/service/sso v1.22.7 // indirect
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.26.7 // indirect
github.com/aws/aws-sdk-go-v2/service/sts v1.30.7 // indirect
github.com/aws/smithy-go v1.20.4 // indirect
github.com/golang-jwt/jwt/v5 v5.2.1 // indirect
github.com/golang/snappy v0.0.4 // indirect
github.com/jmespath/go-jmespath v0.4.0 // indirect
github.com/klauspost/compress v1.17.9 // indirect
github.com/montanaflynn/stats v0.7.1 // indirect
github.com/xdg-go/pbkdf2 v1.0.0 // indirect
github.com/xdg-go/scram v1.1.2 // indirect
github.com/xdg-go/stringprep v1.0.4 // indirect
github.com/youmark/pkcs8 v0.0.0-20240726163527-a2c0da244d78 // indirect
golang.org/x/crypto v0.27.0 // indirect
golang.org/x/sync v0.8.0 // indirect
golang.org/x/text v0.18.0 // indirect
)
Loading

0 comments on commit e361c86

Please sign in to comment.