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

DO NOT MERGE - poc secondary lambda #269

Closed
wants to merge 6 commits into from
Closed
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
6 changes: 6 additions & 0 deletions bin/stacks/routing-api-stack.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import { RoutingCachingStack } from './routing-caching-stack'
import { RoutingDashboardStack } from './routing-dashboard-stack'
import { RoutingLambdaStack } from './routing-lambda-stack'
import { RoutingDatabaseStack } from './routing-database-stack'
import { SecondaryRoutingLambdaStack } from './secondary-routing-lambda-stack'

export const CHAINS_NOT_MONITORED: ChainId[] = [ChainId.GOERLI, ChainId.POLYGON_MUMBAI]

Expand Down Expand Up @@ -79,6 +80,10 @@ export class RoutingAPIStack extends cdk.Stack {

const { cachedRoutesDynamoDb, cachedV3PoolsDynamoDb } = new RoutingDatabaseStack(this, 'RoutingDatabaseStack', {})

const { secondaryRoutingLambda } = new SecondaryRoutingLambdaStack(this, 'SecondaryRoutingLambdaStack', {
provisionedConcurrency,
})

const { routingLambda, routingLambdaAlias } = new RoutingLambdaStack(this, 'RoutingLambdaStack', {
poolCacheBucket,
poolCacheBucket2,
Expand All @@ -93,6 +98,7 @@ export class RoutingAPIStack extends cdk.Stack {
tenderlyAccessKey,
cachedRoutesDynamoDb,
cachedV3PoolsDynamoDb,
SECONDARY_ROUTING_LAMBDA: secondaryRoutingLambda.functionName,
})

const accessLogGroup = new aws_logs.LogGroup(this, 'RoutingAPIGAccessLogs')
Expand Down
4 changes: 4 additions & 0 deletions bin/stacks/routing-lambda-stack.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ export interface RoutingLambdaStackProps extends cdk.NestedStackProps {
chatbotSNSArn?: string
cachedRoutesDynamoDb?: aws_dynamodb.Table
cachedV3PoolsDynamoDb?: aws_dynamodb.Table
SECONDARY_ROUTING_LAMBDA: string
}
export class RoutingLambdaStack extends cdk.NestedStack {
public readonly routingLambda: aws_lambda_nodejs.NodejsFunction
Expand All @@ -49,12 +50,14 @@ export class RoutingLambdaStack extends cdk.NestedStack {
tenderlyAccessKey,
cachedRoutesDynamoDb,
cachedV3PoolsDynamoDb,
SECONDARY_ROUTING_LAMBDA,
} = props

const lambdaRole = new aws_iam.Role(this, 'RoutingLambdaRole', {
assumedBy: new aws_iam.ServicePrincipal('lambda.amazonaws.com'),
managedPolicies: [
aws_iam.ManagedPolicy.fromAwsManagedPolicyName('service-role/AWSLambdaBasicExecutionRole'),
aws_iam.ManagedPolicy.fromAwsManagedPolicyName('service-role/AWSLambdaRole'),
aws_iam.ManagedPolicy.fromAwsManagedPolicyName('CloudWatchLambdaInsightsExecutionRolePolicy'),
aws_iam.ManagedPolicy.fromAwsManagedPolicyName('AWSXRayDaemonWriteAccess'),
],
Expand All @@ -80,6 +83,7 @@ export class RoutingLambdaStack extends cdk.NestedStack {
},
description: 'Routing Lambda',
environment: {
SECONDARY_ROUTING_LAMBDA,
VERSION: '5',
NODE_OPTIONS: '--enable-source-maps',
POOL_CACHE_BUCKET: poolCacheBucket.bucketName,
Expand Down
85 changes: 85 additions & 0 deletions bin/stacks/secondary-routing-lambda-stack.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
import * as cdk from 'aws-cdk-lib'
import * as asg from 'aws-cdk-lib/aws-applicationautoscaling'
import * as aws_iam from 'aws-cdk-lib/aws-iam'
import * as aws_lambda from 'aws-cdk-lib/aws-lambda'
import * as aws_lambda_nodejs from 'aws-cdk-lib/aws-lambda-nodejs'
import { Construct } from 'constructs'
import * as path from 'path'
import { DynamoDBTableProps } from './routing-database-stack'
import { RetentionDays } from 'aws-cdk-lib/aws-logs'

export interface SecondaryRoutingLambdaStackProps extends cdk.NestedStackProps {
provisionedConcurrency: number
}
export class SecondaryRoutingLambdaStack extends cdk.NestedStack {
public readonly secondaryRoutingLambda: aws_lambda_nodejs.NodejsFunction
public readonly secondaryRoutingLambdaAlias: aws_lambda.Alias

constructor(scope: Construct, name: string, props: SecondaryRoutingLambdaStackProps) {
super(scope, name, props)
const { provisionedConcurrency } = props

const lambdaRole = new aws_iam.Role(this, 'SecondaryRoutingLambdaRole', {
assumedBy: new aws_iam.ServicePrincipal('lambda.amazonaws.com'),
managedPolicies: [
aws_iam.ManagedPolicy.fromAwsManagedPolicyName('service-role/AWSLambdaBasicExecutionRole'),
aws_iam.ManagedPolicy.fromAwsManagedPolicyName('CloudWatchLambdaInsightsExecutionRolePolicy'),
],
})
const region = cdk.Stack.of(this).region

this.secondaryRoutingLambda = new aws_lambda_nodejs.NodejsFunction(this, 'SecondaryRoutingLambda2', {
role: lambdaRole,
runtime: aws_lambda.Runtime.NODEJS_14_X,
entry: path.join(__dirname, '../../lib/handlers/index.ts'),
handler: 'testHandler',
timeout: cdk.Duration.seconds(29),
memorySize: 1024,
bundling: {
minify: true,
sourceMap: true,
},
description: 'Secondary Routing Lambda',
environment: {
VERSION: '5',
NODE_OPTIONS: '--enable-source-maps',
CACHED_ROUTES_TABLE_NAME: DynamoDBTableProps.CacheRouteDynamoDbTable.Name,
CACHED_V3_POOLS_TABLE_NAME: DynamoDBTableProps.V3PoolsDynamoDbTable.Name,
},
layers: [
aws_lambda.LayerVersion.fromLayerVersionArn(
this,
'InsightsLayer',
`arn:aws:lambda:${region}:580247275435:layer:LambdaInsightsExtension:14`
),
],
tracing: aws_lambda.Tracing.ACTIVE,
logRetention: RetentionDays.TWO_WEEKS,
})

const enableProvisionedConcurrency = provisionedConcurrency > 0

this.secondaryRoutingLambdaAlias = new aws_lambda.Alias(this, 'RoutingLiveAlias', {
aliasName: 'live',
version: this.secondaryRoutingLambda.currentVersion,
provisionedConcurrentExecutions: enableProvisionedConcurrency ? provisionedConcurrency : undefined,
})

if (enableProvisionedConcurrency) {
const target = new asg.ScalableTarget(this, 'RoutingProvConcASG', {
serviceNamespace: asg.ServiceNamespace.LAMBDA,
maxCapacity: provisionedConcurrency * 5,
minCapacity: provisionedConcurrency,
resourceId: `function:${this.secondaryRoutingLambdaAlias.lambda.functionName}:${this.secondaryRoutingLambdaAlias.aliasName}`,
scalableDimension: 'lambda:function:ProvisionedConcurrency',
})

target.node.addDependency(this.secondaryRoutingLambdaAlias)

target.scaleToTrackMetric('RoutingProvConcTracking', {
targetValue: 0.8,
predefinedMetric: asg.PredefinedMetric.LAMBDA_PROVISIONED_CONCURRENCY_UTILIZATION,
})
}
}
}
2 changes: 2 additions & 0 deletions lib/handlers/index.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
import { QuoteHandlerInjector } from './quote/injector'
import { QuoteHandler } from './quote/quote'
import { testHandler } from './test/test'

const quoteInjectorPromise = new QuoteHandlerInjector('quoteInjector').build()

const quoteHandler = new QuoteHandler('quote', quoteInjectorPromise)

module.exports = {
quoteHandler: quoteHandler.handler,
testHandler: testHandler,
}
23 changes: 23 additions & 0 deletions lib/handlers/quote/quote.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import Joi from '@hapi/joi'
import { Lambda } from 'aws-sdk'
import { Protocol } from '@uniswap/router-sdk'
import { UNIVERSAL_ROUTER_ADDRESS } from '@uniswap/universal-router-sdk'
import { PermitSingle } from '@uniswap/permit2-sdk'
Expand Down Expand Up @@ -45,9 +46,31 @@ export class QuoteHandler extends APIGLambdaHandler<
): Promise<Response<QuoteResponse> | ErrorResponse> {
const { chainId, metric, log } = params.requestInjected
const startTime = Date.now()
log.warn('quote request started')

let result: Response<QuoteResponse> | ErrorResponse

const invokeAsyncLambda = () => {
const lambda = new Lambda()
log.warn(`secondary_routing_lambda: ${process.env.SECONDARY_ROUTING_LAMBDA}`)
const lambdaParams = {
FunctionName: process.env.SECONDARY_ROUTING_LAMBDA!,
InvocationType: 'Event',
Payload: '',
}
lambda.invoke(lambdaParams, (err, data) => {
log.warn('Invoked secondary routing lambda')
if (err) {
log.warn(`error invoking secondary routing lambda: ${err}`)
} else {
log.warn(`secondary routing lambda invoked: ${data}`)
}
})
}

log.warn('Attempting to invoke secondary routing lambda')
invokeAsyncLambda()

try {
result = await this.handleRequestInternal(params)

Expand Down
13 changes: 13 additions & 0 deletions lib/handlers/test/test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { default as bunyan, default as Logger } from 'bunyan'

Check failure on line 1 in lib/handlers/test/test.ts

View workflow job for this annotation

GitHub Actions / Prettier

lib/handlers/test/test.ts#L1

There are issues with this file's formatting, please run Prettier to fix the errors
import { Context } from 'aws-lambda'

export const testHandler = async (context: Context): Promise<void> => {
const logger: Logger = bunyan.createLogger({
name: 'test',
serializers: bunyan.stdSerializers,
level: bunyan.INFO,
requestId: context.awsRequestId,
})

logger.warn(`SECONDARY ROUTING LAMBDA HAS BEEN FIRED.`)
}
Loading