Skip to content

Commit

Permalink
Merge pull request #282 from fleekxyz/feat/backend-improvements
Browse files Browse the repository at this point in the history
feat: backend improvements
  • Loading branch information
EmperorOrokuSaki authored Jul 12, 2023
2 parents 83f7ee2 + 58631cc commit 2cfb61a
Show file tree
Hide file tree
Showing 8 changed files with 122 additions and 75 deletions.
90 changes: 58 additions & 32 deletions serverless/serverless.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -6,18 +6,26 @@ plugins:
- serverless-offline

provider:
timeout: 150
name: aws
runtime: nodejs18.x
stage: ${opt:stage, 'prd'}
region: ${opt:region, 'us-west-2'}
apiGateway:
minimumCompressionSize: 1024
shouldStartNameWithService: true
environment:
DEBUG: '*'
AWS_STAGE: ${self:provider.stage}
AWS_NODEJS_CONNECTION_REUSE_ENABLED: 1
timeout: 150
name: aws
runtime: nodejs18.x
stage: ${opt:stage, 'prd'}
region: ${opt:region, 'us-west-2'}
apiGateway:
minimumCompressionSize: 1024
shouldStartNameWithService: true
environment:
DEBUG: '*'
AWS_STAGE: ${self:provider.stage}
AWS_NODEJS_CONNECTION_REUSE_ENABLED: 1
httpApi:
cors:
allowedOrigins: '*'
headers: '*'
allowedMethods:
- POST
allowCredentials: false
maxAge: 6000 # In seconds

layers:
TopicAwsNodeModules:
Expand All @@ -27,23 +35,29 @@ layers:
TopicPrismaAwsPrismaClient:
path: lambda-layers-prisma-client

package: {
patterns: ["dist/**/*.prisma", "**/libquery_engine-rhel-openssl-1.0.x.so.node", "dist/serverless/.env", '!node_modules/**'],
}
package:
{
patterns:
[
'dist/**/*.prisma',
'**/libquery_engine-rhel-openssl-1.0.x.so.node',
'dist/serverless/.env',
'!node_modules/**',
],
}

custom:
esbuild:
bundle: true
minify: true
sourcemap: false
exclude:
exclude:
- 'aws-sdk'
target: 'node18'
platform: 'node'
concurrency: 10

functions:

submitBuildInfo:
# Deployment:
handler: ./dist/src/functions/builds/handler.submitBuildInfo # TODO This will not work, need to change to nfa-serverless/dist/serverless/src/functions/builds/handler.submitBuildInfo
Expand All @@ -53,13 +67,12 @@ functions:
- http:
path: build
method: post
cors: true
environment: # TODO They won't be loaded from the shell environment, need to find a way to pass them from the deployment script
cors:
origin: '*'
headers: '*'
allowCredentials: false
environment:
NODE_ENV: production
# DATABASE_URL: ${env:DATABASE_URL}
# CONTRACT_ADDRESS: ${env:CONTRACT_ADDRESS}
# PRIVATE_KEY: ${env:PRIVATE_KEY}
# JSON_RPC: ${env:JSON_RPC}
layers:
- { Ref: TopicAwsNodeModulesLambdaLayer }
- { Ref: TopicAwsLibsLambdaLayer }
Expand All @@ -74,30 +87,43 @@ functions:
- http:
path: mint
method: post
cors: true
environment: # TODO They won't be loaded from the shell environment, need to find a way to pass them from the deployment script
cors:
origin: '*'
headers: '*'
allowCredentials: false
environment:
NODE_ENV: production
# DATABASE_URL: ${env:DATABASE_URL}
# CONTRACT_ADDRESS: ${env:CONTRACT_ADDRESS}
# PRIVATE_KEY: ${env:PRIVATE_KEY}
# JSON_RPC: ${env:JSON_RPC}
layers:
- { Ref: TopicAwsNodeModulesLambdaLayer }
- { Ref: TopicAwsLibsLambdaLayer }
- { Ref: TopicPrismaAwsPrismaClientLambdaLayer }

verifyAccessPoint:
verifyApp:
handler: ./dist/src/functions/apps/handler.verifyApp
events:
- http:
path: verifyApp
method: post
cors: true
cors:
origin: '*'
headers: '*'
allowCredentials: false
layers:
- { Ref: TopicAwsNodeModulesLambdaLayer }
- { Ref: TopicAwsLibsLambdaLayer }
- { Ref: TopicPrismaAwsPrismaClientLambdaLayer }

submitAppInfo:
handler: ./dist/src/functions/apps/handler.submitAppInfo
events:
- http:
path: app
method: post
cors: true
cors:
origin: '*'
headers: '*'
allowCredentials: false
layers:
- { Ref: TopicAwsNodeModulesLambdaLayer }
- { Ref: TopicAwsLibsLambdaLayer }
- { Ref: TopicPrismaAwsPrismaClientLambdaLayer }
45 changes: 22 additions & 23 deletions serverless/src/functions/apps/handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,9 @@ export const verifyApp = async (
// Check the parameters and environment variables
dotenv.config();
if (event.body === null || process.env.BUNNY_CDN_ACCESS_KEY === undefined) {
return formatJSONResponse({
status: 422,
message: 'Required parameters were not passed.',
return formatJSONResponse(422, {
message:
'Required parameters were not passed. Please check the request body and the environment variables.',
});
}

Expand All @@ -38,8 +38,7 @@ export const verifyApp = async (
process.env.FE_SIGNING_KEY
)
) {
return formatJSONResponse({
status: 401,
return formatJSONResponse(401, {
message: 'Unauthorized',
});
}
Expand All @@ -54,12 +53,11 @@ export const verifyApp = async (

await bunnyCdn.loadFreeCertificate(args);

return formatJSONResponse({
status: true,
return formatJSONResponse(200, {
message: 'The hostname was verified successfully.',
});
} catch (e) {
return formatJSONResponse({
status: 500,
return formatJSONResponse(500, {
message: e,
});
}
Expand All @@ -72,9 +70,9 @@ export const submitAppInfo = async (
// Check the parameters and environment variables
dotenv.config();
if (event.body === null || process.env.BUNNY_CDN_ACCESS_KEY === undefined) {
return formatJSONResponse({
status: 422,
message: 'Required parameters were not passed.',
return formatJSONResponse(422, {
message:
'Required parameters were not passed. Please check the request body and the environment variables.',
});
}

Expand All @@ -92,17 +90,16 @@ export const submitAppInfo = async (
process.env.FE_SIGNING_KEY
)
) {
return formatJSONResponse({
status: 401,
message: 'Unauthorized',
return formatJSONResponse(401, {
message: 'Unauthorized.',
});
}

// Set up constants
const bunnyCdn = new BunnyCdn(process.env.BUNNY_CDN_ACCESS_KEY);
const data = JSON.parse(event.body);
const appInfo = {
apId: 'null',
appId: 'null',
createdAt: new Date().toISOString(),
sourceDomain: data.sourceDomain,
hostname: data.targetDomain,
Expand All @@ -116,6 +113,7 @@ export const submitAppInfo = async (
hostname?: string;
};

let errorOccurred = false;
do {
let id = v4();
let requestArgs: CreatePullZoneMethodArgs = {
Expand All @@ -125,8 +123,10 @@ export const submitAppInfo = async (

try {
pullZone = await bunnyCdn.createPullZone(requestArgs);
appInfo.apId = id;
appInfo.appId = id;
break; // Exit the loop since catch block was not triggered
} catch (error) {
errorOccurred = true;
maxTries -= 1;
if (
error instanceof BunnyCdnError &&
Expand All @@ -139,7 +139,7 @@ export const submitAppInfo = async (
throw error;
}
}
} while (maxTries > 0);
} while (maxTries > 0 && errorOccurred);

// Create custom hostname
await bunnyCdn
Expand All @@ -155,7 +155,7 @@ export const submitAppInfo = async (
const zoneRecord = await prisma.zones.findMany({
where: {
zoneId: pullZone!.id,
name: appInfo.apId,
name: appInfo.appId,
sourceDomain: appInfo.sourceDomain,
},
});
Expand All @@ -164,19 +164,18 @@ export const submitAppInfo = async (
await prisma.zones.create({
data: {
zoneId: pullZone!.id,
name: appInfo.apId,
name: appInfo.appId,
hostname: appInfo.hostname,
sourceDomain: appInfo.sourceDomain,
},
});
}

return formatJSONResponse({
return formatJSONResponse(200, {
appInfo,
});
} catch (e) {
return formatJSONResponse({
status: 500,
return formatJSONResponse(500, {
message: e,
});
}
Expand Down
11 changes: 4 additions & 7 deletions serverless/src/functions/builds/handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,8 @@ export const submitBuildInfo = async (
): Promise<APIGatewayProxyResult> => {
try {
if (event.body === null) {
return formatJSONResponse({
status: 422,
message: 'Required parameters were not passed.',
return formatJSONResponse(422, {
message: 'The request body is not configured properly.',
});
}

Expand Down Expand Up @@ -39,7 +38,6 @@ export const submitBuildInfo = async (
});

if (buildRecord.length == 0) {

await prisma.builds.create({
data: {
githubRepository: buildInfo.githubRepository,
Expand Down Expand Up @@ -83,12 +81,11 @@ export const submitBuildInfo = async (
});
}

return formatJSONResponse({
return formatJSONResponse(200, {
buildInfo,
});
} catch (e) {
return formatJSONResponse({
status: 500,
return formatJSONResponse(500, {
message: e,
});
}
Expand Down
11 changes: 4 additions & 7 deletions serverless/src/functions/mints/handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,7 @@ export const submitMintInfo = async (
): Promise<APIGatewayProxyResult> => {
try {
if (event.body === null || event.body === undefined) {
return formatJSONResponse({
status: 422,
return formatJSONResponse(422, {
message: 'Required parameters were not passed.',
});
}
Expand All @@ -36,8 +35,7 @@ export const submitMintInfo = async (
process.env.ALCHEMY_SIGNING_KEY
)
) {
return formatJSONResponse({
status: 401,
return formatJSONResponse(401, {
message: 'Unauthorized',
});
}
Expand Down Expand Up @@ -216,12 +214,11 @@ export const submitMintInfo = async (
});
}

return formatJSONResponse({
return formatJSONResponse(200, {
mintInfo,
});
} catch (e) {
return formatJSONResponse({
status: 500,
return formatJSONResponse(500, {
message: e,
});
}
Expand Down
11 changes: 9 additions & 2 deletions serverless/src/libs/api-gateway.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,15 @@
// QUESTION: should we add back in schema verification?

export const formatJSONResponse = (response: Record<string, unknown>) => {
export const formatJSONResponse = (
code: number,
response: Record<string, unknown>
) => {
return {
statusCode: 200,
statusCode: code,
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Credentials': true,
},
body: JSON.stringify(response),
};
};
7 changes: 4 additions & 3 deletions subgraph/schema.graphql
Original file line number Diff line number Diff line change
Expand Up @@ -81,16 +81,17 @@ type Token @entity {
verifier: Verifier # Address
verified: Boolean!
createdAt: BigInt!
builds: [Build!]!
builds: [Build!]! @derivedFrom(field: "token")
}

type Build @entity {
id: Bytes! # Token ID
id: Bytes! # Build number
number: Int!
gitRepository: GitRepository!
commitHash: String!
ipfsHash: String!
domain: String!
token: Token! @derivedFrom(field: "builds")
token: Token!
}

# Owner entity for collection, access points, and tokens
Expand Down
Loading

0 comments on commit 2cfb61a

Please sign in to comment.