Skip to content

Commit

Permalink
fix: timeout terminating process (#1593)
Browse files Browse the repository at this point in the history
  • Loading branch information
dnalborczyk authored Oct 5, 2022
1 parent ae1c8b3 commit 552081c
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 16 deletions.
1 change: 1 addition & 0 deletions src/errors/LambdaTimeoutError.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export default class LambdaTimeoutError extends Error {}
2 changes: 2 additions & 0 deletions src/errors/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
// eslint-disable-next-line import/prefer-default-export
export { default as LambdaTimeoutError } from './LambdaTimeoutError.js'
31 changes: 15 additions & 16 deletions src/lambda/LambdaFunction.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import {
DEFAULT_LAMBDA_TIMEOUT,
supportedRuntimes,
} from '../config/index.js'
import { LambdaTimeoutError } from '../errors/index.js'
import { createUniqueId } from '../utils/index.js'

const { ceil } = Math
Expand All @@ -40,8 +41,6 @@ export default class LambdaFunction {

#handler = null

#handlerRunDone = false

#handlerRunner = null

#idleTimeStarted = null
Expand Down Expand Up @@ -281,14 +280,7 @@ export default class LambdaFunction {
async #timeoutAndTerminate() {
await setTimeoutPromise(this.#timeout)

// if the handler has finished before the timeout don't terminate
if (this.#handlerRunDone) {
return
}

await this.#handlerRunner.cleanup()

throw new Error('Lambda timeout.')
throw new LambdaTimeoutError('Lambda timeout.')
}

async runHandler() {
Expand All @@ -307,14 +299,20 @@ export default class LambdaFunction {

this.#startExecutionTimer()

this.#handlerRunDone = false
let result

const result = await Promise.race([
this.#handlerRunner.run(this.#event, context),
...(this.#noTimeout ? [] : [this.#timeoutAndTerminate()]),
])
try {
result = await Promise.race([
this.#handlerRunner.run(this.#event, context),
...(this.#noTimeout ? [] : [this.#timeoutAndTerminate()]),
])
} catch (err) {
if (err instanceof LambdaTimeoutError) {
await this.#handlerRunner.cleanup()
}

this.#handlerRunDone = true
throw err
}

this.#stopExecutionTimer()

Expand All @@ -330,6 +328,7 @@ export default class LambdaFunction {
}

this.#status = 'IDLE'

this.#startIdleTimer()

return result
Expand Down

0 comments on commit 552081c

Please sign in to comment.