Skip to content

Commit

Permalink
feat: implement router + update concept + update adapter
Browse files Browse the repository at this point in the history
  • Loading branch information
Megakuul committed Sep 13, 2024
1 parent ea74b18 commit 3561958
Show file tree
Hide file tree
Showing 15 changed files with 303 additions and 260 deletions.
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,5 @@
.vscode/**
.aws-sam/**

go.work
go.work.sum
4 changes: 2 additions & 2 deletions adapter-battleshiper/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion adapter-battleshiper/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
"sveltekit",
"battleshiper"
],
"version": "0.1.0",
"version": "0.2.0",
"author": "Megakuul",
"license": "MIT",
"private": false,
Expand Down
45 changes: 21 additions & 24 deletions adapter-battleshiper/src/lambda-handler.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,50 +5,47 @@ import { manifest, prerendered } from 'MANIFEST';
const server = new Server(manifest);

/**
* strips off first http path segments from the left based on the count.
* @param {string} path
* @param {number} count
* @returns {string}
* @typedef {Object} AdapterRequest
* @property {string} method
* @property {string} path
* @property {Object.<string, string>} headers
* @property {string} body
*/
const stripPathSegment = (path, count) => {
const strippedPath = path.split("/").slice(count).join("/");
if (strippedPath.at(0)!="/") {
return "/"
}
return strippedPath
}

/**
* @param {import('aws-lambda').APIGatewayProxyEventV2} event
* @typedef {Object} AdapterResponse
* @property {number} status_code
* @property {string} status_description
* @property {Object.<string, string>} headers
* @property {string} body
*/

/**
* @param {AdapterRequest} event
* @param {import('aws-lambda').Context} context
* @returns {Promise<import('aws-lambda').APIGatewayProxyResultV2>}
* @returns {AdapterResponse}
*/
export const handler = async (event, context) => {
await server.init({ env: process.env });

// Strip off project path segment.
const path = stripPathSegment(event.rawPath, 1);
const url = new URL(`${event.requestContext.http.protocol}://${event.requestContext.domainName}/${path}${event.rawQueryString}`);

/** @type {Request} */
const req = new Request(url, {
method: event.requestContext.http.method,
headers: new Headers(event.headers)
const req = new Request(event.path, {
method: event.method,
headers: event.headers,
body: event.body,
})

/** @type {Response} */
const res = await server.respond(req, {
platform: { context },
getClientAddress: (request) => {
return event.headers["x-forwarded-for"] || event.requestContext.http.sourceIp;
return event.headers["x-forwarded-for"];
}
})

return {
statusCode: res.status,
status_description: res.statusText,
headers: res.headers,
// Object.fromEntries(res.headers.entries())
body: await res.text(),
isBase64Encoded: false,
}
};
246 changes: 128 additions & 118 deletions docs/battleshiper_project.drawio

Large diffs are not rendered by default.

Binary file modified docs/battleshiper_project.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
4 changes: 2 additions & 2 deletions lib/helper/pipeline/subscription.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ func CheckBuildSubscriptionLimit(transportCtx context.Context, database *mongo.D
return fmt.Errorf("failed to update user limit counter on database")
}

if updatedUserDoc.LimitCounter.PipelineBuilds > subscriptionDoc.DailyPipelineBuilds {
if updatedUserDoc.LimitCounter.PipelineBuilds > subscriptionDoc.PipelineSpecs.DailyBuilds {
return fmt.Errorf("subscription limit reached; no further pipeline builds can be performed")
}

Expand Down Expand Up @@ -102,7 +102,7 @@ func CheckDeploySubscriptionLimit(transportCtx context.Context, database *mongo.
return fmt.Errorf("failed to update user limit counter on database")
}

if updatedUserDoc.LimitCounter.PipelineDeployments > subscriptionDoc.DailyPipelineDeployments {
if updatedUserDoc.LimitCounter.PipelineDeployments > subscriptionDoc.PipelineSpecs.DailyDeployments {
return fmt.Errorf("subscription limit reached; no further pipeline deployments can be performed")
}

Expand Down
4 changes: 2 additions & 2 deletions lib/model/user/user.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,9 @@ import "github.com/megakuul/battleshiper/lib/model/rbac"
const USER_COLLECTION = "users"

type ExecutionLimitCounter struct {
PipelineBuilds int `bson:"pipeline_builds"`
PipelineBuilds int64 `bson:"pipeline_builds"`
PipelineBuildsExpiration int64 `bson:"pipeline_builds_exp"`
PipelineDeployments int `bson:"pipeline_deployments"`
PipelineDeployments int64 `bson:"pipeline_deployments"`
PipelineDeploymentsExpiration int64 `bson:"pipeline_deployments_exp"`
}

Expand Down
2 changes: 1 addition & 1 deletion pipeline/deploy/deployproject/analyze.go
Original file line number Diff line number Diff line change
Expand Up @@ -169,7 +169,7 @@ func analyzeServerObject(transportCtx context.Context, s3Client *s3.Client, buck
func extractPageKeys(prerenderObjects []ObjectDescription, projectName string) map[string]string {
pageKeys := map[string]string{}
for _, object := range prerenderObjects {
pageKey := fmt.Sprintf("%s/%s", projectName, object.RelativeKey)
pageKey := fmt.Sprintf("/%s", object.RelativeKey)
pageKeys[strings.TrimSuffix(pageKey, ".html")] = pageKey
}
return pageKeys
Expand Down
2 changes: 2 additions & 0 deletions router/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ require (
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.3.19 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.17.17 // indirect
github.com/golang/snappy v0.0.4 // indirect
github.com/jmespath/go-jmespath v0.4.0 // indirect
github.com/klauspost/compress v1.13.6 // indirect
github.com/montanaflynn/stats v0.7.1 // indirect
github.com/xdg-go/pbkdf2 v1.0.0 // indirect
Expand All @@ -37,6 +38,7 @@ require (
github.com/aws/aws-sdk-go-v2/internal/ini v1.8.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/presigned-url v1.11.19 // indirect
github.com/aws/aws-sdk-go-v2/service/lambda v1.58.3
github.com/aws/aws-sdk-go-v2/service/s3 v1.61.2
github.com/aws/aws-sdk-go-v2/service/secretsmanager v1.32.1 // indirect
github.com/aws/aws-sdk-go-v2/service/sso v1.22.1 // indirect
Expand Down
6 changes: 6 additions & 0 deletions router/go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,8 @@ github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.11.19 h1:rfprUlsd
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.11.19/go.mod h1:SCWkEdRq8/7EK60NcvvQ6NXKuTcchAD4ROAsC37VEZE=
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.17.17 h1:u+EfGmksnJc/x5tq3A+OD7LrMbSSR/5TrKLvkdy/fhY=
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.17.17/go.mod h1:VaMx6302JHax2vHJWgRo+5n9zvbacs3bLU/23DNQrTY=
github.com/aws/aws-sdk-go-v2/service/lambda v1.58.3 h1:jG5WkOpwHICcDQfR+o3r4YYCFeghnHQBQyp5YRmKN9w=
github.com/aws/aws-sdk-go-v2/service/lambda v1.58.3/go.mod h1:Y8hbqj7E9G7kQU3Y5btZNVXedcBQ1WVfLRkDSFXDzXI=
github.com/aws/aws-sdk-go-v2/service/s3 v1.61.2 h1:Kp6PWAlXwP1UvIflkIP6MFZYBNDCa4mFCGtxrpICVOg=
github.com/aws/aws-sdk-go-v2/service/s3 v1.61.2/go.mod h1:5FmD/Dqq57gP+XwaUnd5WFPipAuzrf0HmupX27Gvjvc=
github.com/aws/aws-sdk-go-v2/service/secretsmanager v1.32.1 h1:ZoYRD8IJqPkzjBnpokiMNO6L/DQprtpVpD6k0YSaF5U=
Expand Down Expand Up @@ -67,6 +69,9 @@ github.com/google/go-github/v63 v63.0.0 h1:13xwK/wk9alSokujB9lJkuzdmQuVn2QCPeck7
github.com/google/go-github/v63 v63.0.0/go.mod h1:IqbcrgUmIcEaioWrGYei/09o+ge5vhffGOcxrO0AfmA=
github.com/google/go-querystring v1.1.0 h1:AnCroh3fv4ZBgVIf1Iwtovgjaw/GiKJo8M8yD/fhyJ8=
github.com/google/go-querystring v1.1.0/go.mod h1:Kcdr2DB4koayq7X8pmAG4sNG59So17icRSOU623lUBU=
github.com/jmespath/go-jmespath v0.4.0 h1:BEgLn5cpjn8UN1mAw4NjwDrS35OdebyEtFe+9YPoQUg=
github.com/jmespath/go-jmespath v0.4.0/go.mod h1:T8mJZnbsbmF+m6zOOFylbeCJqk5+pHWvzYPziyZiYoo=
github.com/jmespath/go-jmespath/internal/testify v1.5.1/go.mod h1:L3OGu8Wl2/fWfCI6z80xFu9LTZmf1ZRjMHUOPmWr69U=
github.com/klauspost/compress v1.13.6 h1:P76CopJELS0TiO2mebmnzgWaajssP/EszplttgQxcgc=
github.com/klauspost/compress v1.13.6/go.mod h1:/3/Vjq9QcHkK5uEr5lBEmyoZ1iFhe47etQ6QUkpK6sk=
github.com/megakuul/battleshiper/lib/helper v0.1.8 h1:U2KH5fLlunX1dZtPVAwPgrdo4hcb8IiHJITbddABGj8=
Expand Down Expand Up @@ -132,6 +137,7 @@ golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
67 changes: 14 additions & 53 deletions router/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,29 +5,19 @@ import (
"fmt"
"log"
"os"
"time"

"github.com/aws/aws-lambda-go/lambda"
"github.com/aws/aws-sdk-go-v2/config"
"go.mongodb.org/mongo-driver/mongo"

"github.com/megakuul/battleshiper/lib/helper/auth"
"github.com/megakuul/battleshiper/lib/helper/database"
"github.com/megakuul/battleshiper/lib/model/subscription"
"github.com/megakuul/battleshiper/lib/model/user"
"github.com/megakuul/battleshiper/lib/router"

"github.com/megakuul/battleshiper/api/user/fetchinfo"
"github.com/megakuul/battleshiper/api/user/registeruser"
function "github.com/aws/aws-sdk-go-v2/service/lambda"
"github.com/aws/aws-sdk-go-v2/service/s3"
"github.com/megakuul/battleshiper/api/user/routecontext"
"github.com/megakuul/battleshiper/api/user/routerequest"
)

var (
REGION = os.Getenv("AWS_REGION")
JWT_CREDENTIAL_ARN = os.Getenv("JWT_CREDENTIAL_ARN")
DATABASE_ENDPOINT = os.Getenv("DATABASE_ENDPOINT")
DATABASE_NAME = os.Getenv("DATABASE_NAME")
DATABASE_SECRET_ARN = os.Getenv("DATABASE_SECRET_ARN")
REGION = os.Getenv("AWS_REGION")
STATIC_BUCKET_NAME = os.Getenv("STATIC_BUCKET_NAME")
SERVER_FUNCTION_PREFIX = os.Getenv("SERVER_FUNCTION_PREFIX")
)

func main() {
Expand All @@ -43,45 +33,16 @@ func run() error {
return fmt.Errorf("failed to load aws config: %v", err)
}

databaseOptions, err := database.CreateDatabaseOptions(awsConfig, context.TODO(), DATABASE_SECRET_ARN, DATABASE_ENDPOINT, DATABASE_NAME)
if err != nil {
return err
}
databaseClient, err := mongo.Connect(context.TODO(), databaseOptions)
if err != nil {
return err
}
defer func() {
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
if err = databaseClient.Disconnect(ctx); err != nil {
log.Printf("ERROR CLEANUP: %v\n", err)
}
cancel()
}()
databaseHandle := databaseClient.Database(DATABASE_NAME)

database.SetupIndexes(databaseHandle.Collection(user.USER_COLLECTION), context.TODO(), []database.Index{
{FieldNames: []string{"id"}, SortingOrder: 1, Unique: true},
})

database.SetupIndexes(databaseHandle.Collection(subscription.SUBSCRIPTION_COLLECTION), context.TODO(), []database.Index{
{FieldNames: []string{"id"}, SortingOrder: 1, Unique: true},
})

jwtOptions, err := auth.CreateJwtOptions(awsConfig, context.TODO(), JWT_CREDENTIAL_ARN, 0)
if err != nil {
return err
}

httpRouter := router.NewRouter(routecontext.Context{
JwtOptions: jwtOptions,
Database: databaseHandle,
})
s3Client := s3.NewFromConfig(awsConfig)

httpRouter.AddRoute("GET", "/api/user/fetchinfo", fetchinfo.HandleFetchInfo)
httpRouter.AddRoute("POST", "/api/user/registeruser", registeruser.HandleRegisterUser)
functionClient := function.NewFromConfig(awsConfig)

lambda.Start(httpRouter.Route)
lambda.Start(routerequest.HandleRouteRequest(routecontext.Context{
S3Client: s3Client,
S3Bucket: STATIC_BUCKET_NAME,
FunctionClient: functionClient,
FunctionPrefix: SERVER_FUNCTION_PREFIX,
}))

return nil
}
11 changes: 5 additions & 6 deletions router/routecontext/routecontext.go
Original file line number Diff line number Diff line change
@@ -1,15 +1,14 @@
package routecontext

import (
"net/http"

"github.com/aws/aws-sdk-go-v2/service/lambda"
"github.com/aws/aws-sdk-go-v2/service/s3"
)

// Context provides data to route handlers.
type Context struct {
S3Bucket string
S3Client *s3.Client
HttpSuffix string
HttpClient *http.Client
S3Bucket string
S3Client *s3.Client
FunctionPrefix string
FunctionClient *lambda.Client
}
Loading

0 comments on commit 3561958

Please sign in to comment.