Skip to content

Commit

Permalink
Merge pull request #1091 from dl748/master
Browse files Browse the repository at this point in the history
Fix for reloading with shared modules
  • Loading branch information
dherault committed Sep 23, 2020
2 parents 245fe43 + 4eacf7e commit ca3e396
Show file tree
Hide file tree
Showing 3 changed files with 61 additions and 7 deletions.
1 change: 0 additions & 1 deletion package.json
Expand Up @@ -159,7 +159,6 @@
"aws-sdk": "^2.624.0",
"boxen": "^4.2.0",
"chalk": "^3.0.0",
"clear-module": "^4.1.1",
"cuid": "^2.1.8",
"execa": "^4.0.0",
"extend": "^3.0.2",
Expand Down
63 changes: 61 additions & 2 deletions src/lambda/handler-runner/in-process-runner/InProcessRunner.js
@@ -1,5 +1,64 @@
import { performance } from 'perf_hooks'
import clearModule from 'clear-module'
import * as path from 'path'
import * as fs from 'fs'

const clearModule = (fP, opts) => {
const options = opts ?? {}
let filePath = fP
if (!require.cache[filePath]) {
const dirname = path.dirname(filePath)
for (const fn of fs.readdirSync(dirname)) {
const fullPath = path.resolve(dirname, fn)
if (
fullPath.substr(0, filePath.length + 1) === `${filePath}.` &&
require.cache[fullPath]
) {
filePath = fullPath
break
}
}
}
if (require.cache[filePath]) {
// Remove file from parent cache
if (require.cache[filePath].parent) {
let i = require.cache[filePath].parent.children.length
if (i) {
do {
i -= 1
if (require.cache[filePath].parent.children[i].id === filePath) {
require.cache[filePath].parent.children.splice(i, 1)
}
} while (i)
}
}
const cld = require.cache[filePath].children
delete require.cache[filePath]
for (const c of cld) {
// Unload any non node_modules children
if (!c.filename.match(/node_modules/)) {
clearModule(c.id, { ...options, cleanup: false })
}
}
if (opts.cleanup) {
// Cleanup any node_modules that are orphans
let cleanup = false
do {
cleanup = false
for (const fn of Object.keys(require.cache)) {
if (
require.cache[fn].id !== '.' &&
require.cache[fn].parent &&
require.cache[fn].parent.id !== '.' &&
!require.cache[require.cache[fn].parent.id]
) {
delete require.cache[fn]
cleanup = true
}
}
} while (cleanup)
}
}
}

export default class InProcessRunner {
#env = null
Expand Down Expand Up @@ -40,7 +99,7 @@ export default class InProcessRunner {

// lazy load handler with first usage
if (!this.#allowCache) {
clearModule(this.#handlerPath)
clearModule(this.#handlerPath, { cleanup: true })
}
const { [this.#handlerName]: handler } = await import(this.#handlerPath)

Expand Down
4 changes: 0 additions & 4 deletions tests/integration/lambda-invoke/serverless.yml
Expand Up @@ -68,7 +68,3 @@ functions:

invokedAsyncHandler:
handler: lambdaInvokeAsyncHandler.invokedAsyncHandler

custom:
serverless-offline:
allowCache: true

0 comments on commit ca3e396

Please sign in to comment.