Skip to content

Commit

Permalink
Add function return type for Lambda and Step Function code
Browse files Browse the repository at this point in the history
  • Loading branch information
lym953 committed Sep 4, 2024
1 parent 45e67c2 commit f2c1a96
Show file tree
Hide file tree
Showing 11 changed files with 97 additions and 53 deletions.
35 changes: 24 additions & 11 deletions src/commands/lambda/flare.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ export class LambdaFlareCommand extends Command {
* Lambda function and sends them to Datadog support.
* @returns 0 if the command ran successfully, 1 otherwise.
*/
public async execute() {
public async execute(): Promise<0 | 1> {
this.context.stdout.write(helpersRenderer.renderFlareHeader('Lambda', this.isDryRun))

// Validate function name
Expand Down Expand Up @@ -425,7 +425,7 @@ export class LambdaFlareCommand extends Command {
* @param config
* @returns a summarized config
*/
export const summarizeConfig = (config: any) => {
export const summarizeConfig = (config: any): any => {
const summarizedConfig: any = {}
for (const key in config) {
if (SUMMARIZED_FIELDS.has(key)) {
Expand All @@ -450,7 +450,7 @@ export const getLogStreamNames = async (
logGroupName: string,
startMillis?: number,
endMillis?: number
) => {
): Promise<string[]> => {
const config = {
logGroupName,
descending: true,
Expand Down Expand Up @@ -507,7 +507,7 @@ export const getLogEvents = async (
logStreamName: string,
startMillis?: number,
endMillis?: number
) => {
): Promise<OutputLogEvent[]> => {
const config: any = {
logGroupName,
logStreamName,
Expand Down Expand Up @@ -537,7 +537,12 @@ export const getLogEvents = async (
* @param endMillis end time in milliseconds or undefined if no end time is specified
* @returns a map of log stream names to log events or an empty map if no logs are found
*/
export const getAllLogs = async (region: string, functionName: string, startMillis?: number, endMillis?: number) => {
export const getAllLogs = async (
region: string,
functionName: string,
startMillis?: number,
endMillis?: number
): Promise<Map<string, OutputLogEvent[]>> => {
const logs = new Map<string, OutputLogEvent[]>()
const cwlClient = new CloudWatchLogsClient({region, retryStrategy: EXPONENTIAL_BACKOFF_RETRY_STRATEGY})
if (functionName.startsWith('arn:aws')) {
Expand Down Expand Up @@ -574,7 +579,11 @@ export const getAllLogs = async (region: string, functionName: string, startMill
* @returns the tags or an empty object if no tags are found
* @throws Error if the tags cannot be retrieved
*/
export const getTags = async (lambdaClient: LambdaClient, region: string, arn: string) => {
export const getTags = async (
lambdaClient: LambdaClient,
region: string,
arn: string
): Promise<Record<string, string>> => {
if (!arn.startsWith('arn:aws')) {
throw Error(`Invalid function ARN: ${arn}`)
}
Expand All @@ -601,7 +610,7 @@ export const getTags = async (lambdaClient: LambdaClient, region: string, arn: s
* @param filePaths the list of file paths
* @returns a mapping of file paths to new file names
*/
export const getUniqueFileNames = (filePaths: Set<string>) => {
export const getUniqueFileNames = (filePaths: Set<string>): Map<string, string> => {
// Count occurrences of each filename
const fileNameCount: {[fileName: string]: number} = {}
filePaths.forEach((filePath) => {
Expand Down Expand Up @@ -634,7 +643,7 @@ export const getUniqueFileNames = (filePaths: Set<string>) => {
* @param logEvents array of log events
* @returns the CSV string
*/
export const convertToCSV = (logEvents: OutputLogEvent[]) => {
export const convertToCSV = (logEvents: OutputLogEvent[]): string => {
const rows = [['timestamp', 'datetime', 'message']]
for (const logEvent of logEvents) {
const timestamp = `"${logEvent.timestamp ?? ''}"`
Expand All @@ -653,15 +662,15 @@ export const convertToCSV = (logEvents: OutputLogEvent[]) => {
/**
* @param ms number of milliseconds to sleep
*/
export const sleep = async (ms: number) => {
export const sleep = async (ms: number): Promise<void> => {
await new Promise((resolve) => setTimeout(resolve, ms))
}

/**
* Get the framework used based on the files in the directory
* @returns the framework used or undefined if no framework is found
*/
export const getFramework = () => {
export const getFramework = (): string => {
const frameworks = new Set<DeploymentFrameworks>()
const files = fs.readdirSync(process.cwd())
files.forEach((file) => {
Expand All @@ -683,7 +692,11 @@ export const getFramework = () => {
* @param isDryRun whether or not this is a dry run
* @param config Lambda function configuration
*/
export const generateInsightsFile = (insightsFilePath: string, isDryRun: boolean, config: FunctionConfiguration) => {
export const generateInsightsFile = (
insightsFilePath: string,
isDryRun: boolean,
config: FunctionConfiguration
): void => {
const lines: string[] = []
// Header
lines.push('# Flare Insights')
Expand Down
39 changes: 24 additions & 15 deletions src/commands/lambda/functions/commons.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,11 @@ import {applyTagConfig} from '../tags'
* @param layerARNs an array of layer ARNs.
* @returns an array of layer ARNs.
*/
export const addLayerArn = (fullLayerArn: string | undefined, previousLayerName: string, layerARNs: string[]) => {
export const addLayerArn = (
fullLayerArn: string | undefined,
previousLayerName: string,
layerARNs: string[]
): string[] => {
if (fullLayerArn) {
if (!layerARNs.includes(fullLayerArn)) {
// Remove any other versions of the layer
Expand Down Expand Up @@ -137,7 +141,7 @@ export const collectFunctionsByRegion = (
* @param region the region where the layer is stored.
* @returns the latest version of the layer to find.
*/
export const findLatestLayerVersion = async (layer: LayerKey, region: string) => {
export const findLatestLayerVersion = async (layer: LayerKey, region: string): Promise<number> => {
let latestVersion = 0

let searchStep = latestVersion > 0 ? 1 : 100
Expand Down Expand Up @@ -218,7 +222,7 @@ export const getAWSFileCredentialsParams = (profile: string): FromIniInit => {
* @param {string} profile the AWS Credentials profile
* @returns {AwsCredentialIdentity} credentials object.
*/
export const getAWSProfileCredentials = async (profile: string) => {
export const getAWSProfileCredentials = async (profile: string): Promise<AwsCredentialIdentity | undefined> => {
const init = getAWSFileCredentialsParams(profile)

try {
Expand All @@ -233,7 +237,7 @@ export const getAWSProfileCredentials = async (profile: string) => {
}
}

export const getAWSCredentials = async () => {
export const getAWSCredentials = async (): Promise<AwsCredentialIdentity | undefined> => {
const provider = fromNodeProviderChain()

try {
Expand All @@ -250,24 +254,25 @@ export const getAWSCredentials = async () => {
}
}

export const isMissingAnyDatadogApiKeyEnvVar = () =>
export const isMissingAnyDatadogApiKeyEnvVar = (): boolean =>
!(
process.env[CI_API_KEY_ENV_VAR] ||
process.env[API_KEY_ENV_VAR] ||
process.env[CI_KMS_API_KEY_ENV_VAR] ||
process.env[CI_API_KEY_SECRET_ARN_ENV_VAR]
)
export const isMissingDatadogEnvVars = () =>
export const isMissingDatadogEnvVars = (): boolean =>
!isValidDatadogSite(process.env[CI_SITE_ENV_VAR]) || isMissingAnyDatadogApiKeyEnvVar()

export const getAllLambdaFunctionConfigs = async (lambdaClient: LambdaClient) =>
export const getAllLambdaFunctionConfigs = async (lambdaClient: LambdaClient): Promise<LFunctionConfiguration[]> =>
getLambdaFunctionConfigsFromRegex(lambdaClient, '.')

// Returns false if not all runtimes are of the same RuntimeType across multiple functions
export const checkRuntimeTypesAreUniform = (configList: FunctionConfiguration[]) =>
export const checkRuntimeTypesAreUniform = (configList: FunctionConfiguration[]): boolean =>
configList
.map((item) => item.lambdaConfig.Runtime)
.every((runtime) => RUNTIME_LOOKUP[runtime!] === RUNTIME_LOOKUP[configList[0].lambdaConfig.Runtime!])

/**
* Given a Lambda instance and a regular expression,
* returns all the Function Configurations that match.
Expand Down Expand Up @@ -321,6 +326,7 @@ export const getLambdaFunctionConfigs = (
* and settings (optional).
*
* @param config a Lambda FunctionConfiguration.
* @param layer a Lambda layer.
* @param region a region where the layer is hosted.
* @param settings instrumentation settings, mainly used to change the AWS account that contains the Layer.
* @returns the ARN of a **Specific Runtime Layer** with the correct region, account, architecture, and name.
Expand All @@ -330,7 +336,7 @@ export const getLayerArn = (
layer: LayerKey,
region: string,
settings?: InstrumentationSettings
) => {
): string => {
let layerName = LAYER_LOOKUP[layer]
if (ARM_LAYERS.includes(layer) && config.Architectures?.includes(ARM64_ARCHITECTURE)) {
layerName += ARM_LAYER_SUFFIX
Expand All @@ -350,7 +356,7 @@ export const getLayerNameWithVersion = (layerArn: string): string | undefined =>
return name && version ? `${name}:${version}` : undefined
}

export const getLayers = (config: LFunctionConfiguration) => (config.Layers ?? []).map((layer) => layer.Arn!)
export const getLayers = (config: LFunctionConfiguration): string[] => (config.Layers ?? []).map((layer) => layer.Arn!)

/**
* Call the aws-sdk Lambda api to get a Function given
Expand Down Expand Up @@ -406,7 +412,7 @@ export const updateLambdaFunctionConfig = async (
lambdaClient: LambdaClient,
cloudWatchLogsClient: CloudWatchLogsClient,
config: FunctionConfiguration
) => {
): Promise<void> => {
if (config.updateFunctionConfigurationCommandInput !== undefined) {
await updateFunctionConfiguration(lambdaClient, config.updateFunctionConfigurationCommandInput)
}
Expand All @@ -421,12 +427,15 @@ export const updateLambdaFunctionConfig = async (
export const updateFunctionConfiguration = async (
client: LambdaClient,
input: UpdateFunctionConfigurationCommandInput
) => {
): Promise<void> => {
const command = new UpdateFunctionConfigurationCommand(input)
await client.send(command)
}

export const handleLambdaFunctionUpdates = async (configGroups: InstrumentedConfigurationGroup[], stdout: Writable) => {
export const handleLambdaFunctionUpdates = async (
configGroups: InstrumentedConfigurationGroup[],
stdout: Writable
): Promise<void> => {
let totalFunctions = 0
let totalFailedUpdates = 0
for (const group of configGroups) {
Expand Down Expand Up @@ -482,7 +491,7 @@ export const handleLambdaFunctionUpdates = async (configGroups: InstrumentedConf
}
}

export const willUpdateFunctionConfigs = (configs: FunctionConfiguration[]) => {
export const willUpdateFunctionConfigs = (configs: FunctionConfiguration[]): boolean => {
let willUpdate = false
for (const config of configs) {
if (
Expand All @@ -507,7 +516,7 @@ export const willUpdateFunctionConfigs = (configs: FunctionConfiguration[]) => {
* @param config
* @returns masked config
*/
export const maskConfig = (config: any) => {
export const maskConfig = (config: any): any => {
// We stringify and parse again to make a deep copy
const configCopy = JSON.parse(JSON.stringify(config))
const vars = configCopy.Environment?.Variables
Expand Down
2 changes: 1 addition & 1 deletion src/commands/lambda/functions/instrument.ts
Original file line number Diff line number Diff line change
Expand Up @@ -156,7 +156,7 @@ export const calculateUpdateRequest = async (
settings: InstrumentationSettings,
region: string,
runtime: Runtime
) => {
): Promise<UpdateFunctionConfigurationCommandInput | undefined> => {
const oldEnvVars: Record<string, string> = {...config.Environment?.Variables}
const changedEnvVars: Record<string, string> = {}
const functionARN = config.FunctionArn
Expand Down
5 changes: 4 additions & 1 deletion src/commands/lambda/functions/uninstrument.ts
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,10 @@ export const getUninstrumentedFunctionConfigsFromRegEx = async (
return functionsToUpdate
}

export const calculateUpdateRequest = (config: LFunctionConfiguration, runtime: Runtime) => {
export const calculateUpdateRequest = (
config: LFunctionConfiguration,
runtime: Runtime
): UpdateFunctionConfigurationRequest | undefined => {
const oldEnvVars: Record<string, string> = {...config.Environment?.Variables}
const functionARN = config.FunctionArn

Expand Down
8 changes: 4 additions & 4 deletions src/commands/lambda/instrument.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ export class InstrumentCommand extends Command {

private credentials?: AwsCredentialIdentity

public async execute() {
public async execute(): Promise<0 | 1> {
this.context.stdout.write(instrumentRenderer.renderLambdaHeader(Object.getPrototypeOf(this), this.dryRun))

const lambdaConfig = {lambda: this.config}
Expand Down Expand Up @@ -392,7 +392,7 @@ export class InstrumentCommand extends Command {
return {commitSha: currentStatus.hash, gitRemote}
}

private async uploadGitData() {
private async uploadGitData(): Promise<void> {
const cli = new Cli()
cli.register(UploadCommand)
if ((await cli.run(['git-metadata', 'upload'], this.context)) !== 0) {
Expand Down Expand Up @@ -499,7 +499,7 @@ export class InstrumentCommand extends Command {
}
}

private printPlannedActions(configs: FunctionConfiguration[]) {
private printPlannedActions(configs: FunctionConfiguration[]): void {
const willUpdate = willUpdateFunctionConfigs(configs)
if (!willUpdate) {
this.context.stdout.write(instrumentRenderer.renderNoUpdatesApplied(this.dryRun))
Expand Down Expand Up @@ -568,7 +568,7 @@ export class InstrumentCommand extends Command {
}
}

private setEnvServiceVersion() {
private setEnvServiceVersion(): void {
this.environment = process.env[ENVIRONMENT_ENV_VAR] || undefined
this.service = process.env[SERVICE_ENV_VAR] || undefined
this.version = process.env[VERSION_ENV_VAR] || undefined
Expand Down
27 changes: 20 additions & 7 deletions src/commands/lambda/loggroup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import {
DescribeSubscriptionFiltersCommandInput,
PutSubscriptionFilterCommand,
PutSubscriptionFilterCommandInput,
SubscriptionFilter,
} from '@aws-sdk/client-cloudwatch-logs'

import {SUBSCRIPTION_FILTER_NAME} from './constants'
Expand All @@ -24,7 +25,10 @@ export enum SubscriptionState {

const MAX_LOG_GROUP_SUBSCRIPTIONS = 2

export const applyLogGroupConfig = async (client: CloudWatchLogsClient, config: LogGroupConfiguration) => {
export const applyLogGroupConfig = async (
client: CloudWatchLogsClient,
config: LogGroupConfiguration
): Promise<void> => {
const {createLogGroupCommandInput, deleteSubscriptionFilterCommandInput, putSubscriptionFilterCommandInput} = config
if (createLogGroupCommandInput !== undefined) {
await createLogGroup(client, createLogGroupCommandInput)
Expand All @@ -37,7 +41,10 @@ export const applyLogGroupConfig = async (client: CloudWatchLogsClient, config:
}
}

export const createLogGroup = async (client: CloudWatchLogsClient, input: CreateLogGroupCommandInput) => {
export const createLogGroup = async (
client: CloudWatchLogsClient,
input: CreateLogGroupCommandInput
): Promise<void> => {
const command = new CreateLogGroupCommand(input)
await client.send(command)
}
Expand All @@ -50,7 +57,10 @@ export const deleteSubscriptionFilter = async (
await client.send(command)
}

export const putSubscriptionFilter = async (client: CloudWatchLogsClient, input: PutSubscriptionFilterCommandInput) => {
export const putSubscriptionFilter = async (
client: CloudWatchLogsClient,
input: PutSubscriptionFilterCommandInput
): Promise<void> => {
const command = new PutSubscriptionFilterCommand(input)
await client.send(command)
}
Expand All @@ -59,7 +69,7 @@ export const calculateLogGroupUpdateRequest = async (
client: CloudWatchLogsClient,
logGroupName: string,
forwarderARN: string
) => {
): Promise<LogGroupConfiguration | undefined> => {
const config: LogGroupConfiguration = {
logGroupName,
putSubscriptionFilterCommandInput: {
Expand Down Expand Up @@ -99,7 +109,7 @@ export const calculateLogGroupRemoveRequest = async (
client: CloudWatchLogsClient,
logGroupName: string,
forwarderARN: string
) => {
): Promise<LogGroupConfiguration> => {
const config: LogGroupConfiguration = {
logGroupName,
}
Expand Down Expand Up @@ -140,7 +150,7 @@ export const getSubscriptionFilterState = async (
client: CloudWatchLogsClient,
logGroupName: string,
forwarderARN: string
) => {
): Promise<SubscriptionState> => {
const subscriptionFilters = await getSubscriptionFilters(client, logGroupName)
if (subscriptionFilters === undefined || subscriptionFilters.length === 0) {
return SubscriptionState.Empty
Expand All @@ -162,7 +172,10 @@ export const getSubscriptionFilterState = async (
return SubscriptionState.WrongDestinationUnowned
}

export const getSubscriptionFilters = async (client: CloudWatchLogsClient, logGroupName: string) => {
export const getSubscriptionFilters = async (
client: CloudWatchLogsClient,
logGroupName: string
): Promise<SubscriptionFilter[] | undefined> => {
const input: DescribeSubscriptionFiltersCommandInput = {
logGroupName,
}
Expand Down
Loading

0 comments on commit f2c1a96

Please sign in to comment.