aws sam local invoke command returns Error: Cannot find module error

aws sam local invoke command returns Error: Cannot find module error

我在尝试使用 sam local invoke 命令测试我的 lambda 时收到 Error: Cannot find module(最后共享完整堆栈跟踪)错误。基本上,我创建了一个打字稿项目并使用 AWS CDK 创建了我的 lambda 资源。

这是我的项目目录结构

├── bin
│   └── app.ts
├── cdk.json
├── env.json
├── events
│   └── createCostEvent.json
├── lib
│   ├── cost-api-stack.ts
│   └── entity.ts
├── package-lock.json
├── package.json
├── src
│   └── lambda
│       └── create-cost-lambda.ts
├── template.yml
├── tsconfig.eslint.json
└── tsconfig.json

创建成本-lambda.ts

import { APIGatewayProxyEventV2, APIGatewayProxyHandlerV2, APIGatewayProxyResultV2 } from 'aws-lambda';

export const handler: APIGatewayProxyHandlerV2 = async (event: APIGatewayProxyEventV2) : Promise<APIGatewayProxyResultV2> => {
    console.log(event);
    return {
        body: 'success',
        statusCode: 200,
    };
};

此外,您可以从here and template.yml here

看到我的堆栈代码

我 运行 sam local invoke costPostV1Function0C3CA513 --event events/createCostEvent.json --env-vars env.json --debug 在本地调用我的 lambda 生成堆栈跟踪;

2021-03-18 20:13:00,735 | Telemetry endpoint configured to be https://aws-serverless-tools-telemetry.us-west-2.amazonaws.com/metrics
2021-03-18 20:13:00,736 | Using config file: samconfig.toml, config environment: default
2021-03-18 20:13:00,736 | Expand command line arguments to:
2021-03-18 20:13:00,736 | --template_file=/Users/baktas/workspace/cost-api/template.yml --event=events/createCostEvent.json --env_vars=env.json --function_logical_id=costPostV1Function0C3CA513 --no_event --layer_cache_basedir=/Users/baktas/.aws-sam/layers-pkg
2021-03-18 20:13:00,736 | local invoke command is called
2021-03-18 20:13:00,771 | Collected default values for parameters: {}
2021-03-18 20:13:00,803 | 14 stacks found in the template
2021-03-18 20:13:00,803 | Collected default values for parameters: {}
2021-03-18 20:13:00,829 | 14 resources found in the stack
2021-03-18 20:13:00,830 | Collected default values for parameters: {}
2021-03-18 20:13:00,854 | Found Lambda function with name='costPostV1Function0C3CA513' and CodeUri='/Users/baktas/workspace/cost-api/src'
2021-03-18 20:13:00,854 | --base-dir is presented not, adjusting uri /Users/baktas/workspace/cost-api/src relative to /Users/baktas/workspace/cost-api/template.yml
2021-03-18 20:13:00,869 | Found one Lambda function with name 'costPostV1Function0C3CA513'
2021-03-18 20:13:00,869 | Invoking lambda/create-cost-lambda.handler (nodejs12.x)
2021-03-18 20:13:00,869 | No environment variables found for function 'costPostV1Function0C3CA513'
2021-03-18 20:13:00,870 | Environment variables overrides data is standard format
2021-03-18 20:13:00,870 | Loading AWS credentials from session with profile 'None'
2021-03-18 20:13:00,881 | Resolving code path. Cwd=/Users/baktas/workspace/cost-api, CodeUri=/Users/baktas/workspace/cost-api/src
2021-03-18 20:13:00,881 | Resolved absolute path to code is /Users/baktas/workspace/cost-api/src
2021-03-18 20:13:00,882 | Code /Users/baktas/workspace/cost-api/src is not a zip/jar file
2021-03-18 20:13:00,901 | Skip pulling image and use local one: amazon/aws-sam-cli-emulation-image-nodejs12.x:rapid-1.21.1.

2021-03-18 20:13:00,901 | Mounting /Users/baktas/workspace/cost-api/src as /var/task:ro,delegated inside runtime container
2021-03-18 20:13:01,246 | Starting a timer for 3 seconds for function 'costPostV1Function0C3CA513'
START RequestId: 01bcac5a-fc5a-4fd5-b508-9e057689e554 Version: $LATEST
2021-03-18T17:13:01.351Z    undefined   ERROR   Uncaught Exception  {"errorType":"Runtime.ImportModuleError","errorMessage":"Error: Cannot find module 'create-cost-lambda'\nRequire stack:\n- /var/runtime/UserFunction.js\n- /var/runtime/index.js","stack":["Runtime.ImportModuleError: Error: Cannot find module 'create-cost-lambda'","Require stack:","- /var/runtime/UserFunction.js","- /var/runtime/index.js","    at _loadUserApp (/var/runtime/UserFunction.js:100:13)","    at Object.module.exports.load (/var/runtime/UserFunction.js:140:17)","    at Object.<anonymous> (/var/runtime/index.js:43:30)","    at Module._compile (internal/modules/cjs/loader.js:999:30)","    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10)","    at Module.load (internal/modules/cjs/loader.js:863:32)","    at Function.Module._load (internal/modules/cjs/loader.js:708:14)","    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:60:12)","    at internal/main/run_main_module.js:17:47"]}
time="2021-03-18T17:13:01.359" level=panic msg="ReplyStream not available"
2021/03/18 17:13:01 http: panic serving 127.0.0.1:55970: &{0xc000132000 map[] 2021-03-18 17:13:01.35917884 +0000 UTC m=+0.118457205 panic <nil> ReplyStream not available <nil> <nil> }
goroutine 54 [running]:
net/http.(*conn).serve.func1(0xc0002081e0)
    /usr/local/go/src/net/http/server.go:1800 +0x139
panic(0x866640, 0xc0002460e0)
    /usr/local/go/src/runtime/panic.go:975 +0x3e3
github.com/sirupsen/logrus.Entry.log(0xc000132000, 0xc000204300, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, ...)
    /go/pkg/mod/github.com/sirupsen/logrus@v1.6.0/entry.go:259 +0x335
github.com/sirupsen/logrus.(*Entry).Log(0xc000246000, 0xc000000000, 0xc00008f588, 0x1, 0x1)
    /go/pkg/mod/github.com/sirupsen/logrus@v1.6.0/entry.go:287 +0xeb
github.com/sirupsen/logrus.(*Logger).Log(0xc000132000, 0xc000000000, 0xc00008f588, 0x1, 0x1)
    /go/pkg/mod/github.com/sirupsen/logrus@v1.6.0/logger.go:193 +0x7d
github.com/sirupsen/logrus.(*Logger).Panic(...)
    /go/pkg/mod/github.com/sirupsen/logrus@v1.6.0/logger.go:234
github.com/sirupsen/logrus.Panic(...)
    /go/pkg/mod/github.com/sirupsen/logrus@v1.6.0/exported.go:129
go.amzn.com/lambda/rapi/rendering.RenderInteropError(0x9097c0, 0xc00023a0e0, 0xc00022e500, 0x902b60, 0xc00021a160)
    /LambdaRuntimeLocal/lambda/rapi/rendering/rendering.go:292 +0x9a
go.amzn.com/lambda/rapi/handler.(*initErrorHandler).ServeHTTP(0xc000051000, 0x9097c0, 0xc00023a0e0, 0xc00022e500)
    /LambdaRuntimeLocal/lambda/rapi/handler/initerror.go:52 +0x519
net/http.HandlerFunc.ServeHTTP(0xc00000c680, 0x9097c0, 0xc00023a0e0, 0xc00022e500)
    /usr/local/go/src/net/http/server.go:2041 +0x44
github.com/go-chi/chi.(*Mux).routeHTTP(0xc00007c600, 0x9097c0, 0xc00023a0e0, 0xc00022e500)
    /go/pkg/mod/github.com/go-chi/chi@v4.1.2+incompatible/mux.go:431 +0x278
net/http.HandlerFunc.ServeHTTP(0xc000050f90, 0x9097c0, 0xc00023a0e0, 0xc00022e500)
    /usr/local/go/src/net/http/server.go:2041 +0x44
go.amzn.com/lambda/rapi/middleware.RuntimeReleaseMiddleware.func1.1(0x9097c0, 0xc00023a0e0, 0xc00022e500)
    /LambdaRuntimeLocal/lambda/rapi/middleware/middleware.go:100 +0xea
net/http.HandlerFunc.ServeHTTP(0xc00000c480, 0x9097c0, 0xc00023a0e0, 0xc00022e500)
    /usr/local/go/src/net/http/server.go:2041 +0x44
go.amzn.com/lambda/rapi/middleware.AccessLogMiddleware.func1.1(0x9097c0, 0xc00023a0e0, 0xc00022e500)
    /LambdaRuntimeLocal/lambda/rapi/middleware/middleware.go:77 +0x170
net/http.HandlerFunc.ServeHTTP(0xc00000c4a0, 0x9097c0, 0xc00023a0e0, 0xc00022e500)
    /usr/local/go/src/net/http/server.go:2041 +0x44
go.amzn.com/lambda/rapi/middleware.AppCtxMiddleware.func1.1(0x9097c0, 0xc00023a0e0, 0xc00022e400)
    /LambdaRuntimeLocal/lambda/rapi/middleware/middleware.go:66 +0x77
net/http.HandlerFunc.ServeHTTP(0xc00001f4a0, 0x9097c0, 0xc00023a0e0, 0xc00022e400)
    /usr/local/go/src/net/http/server.go:2041 +0x44
github.com/go-chi/chi.(*Mux).ServeHTTP(0xc00007c600, 0x9097c0, 0xc00023a0e0, 0xc00022e400)
    /go/pkg/mod/github.com/go-chi/chi@v4.1.2+incompatible/mux.go:70 +0x513
github.com/go-chi/chi.(*Mux).Mount.func1(0x9097c0, 0xc00023a0e0, 0xc00022e400)
    /go/pkg/mod/github.com/go-chi/chi@v4.1.2+incompatible/mux.go:298 +0x118
net/http.HandlerFunc.ServeHTTP(0xc00000c6e0, 0x9097c0, 0xc00023a0e0, 0xc00022e400)
    /usr/local/go/src/net/http/server.go:2041 +0x44
github.com/go-chi/chi.(*Mux).routeHTTP(0xc00007c5a0, 0x9097c0, 0xc00023a0e0, 0xc00022e400)
    /go/pkg/mod/github.com/go-chi/chi@v4.1.2+incompatible/mux.go:431 +0x278
net/http.HandlerFunc.ServeHTTP(0xc000051020, 0x9097c0, 0xc00023a0e0, 0xc00022e400)
    /usr/local/go/src/net/http/server.go:2041 +0x44
github.com/go-chi/chi.(*Mux).ServeHTTP(0xc00007c5a0, 0x9097c0, 0xc00023a0e0, 0xc00022e300)
    /go/pkg/mod/github.com/go-chi/chi@v4.1.2+incompatible/mux.go:86 +0x2b2
net/http.serverHandler.ServeHTTP(0xc00014e0e0, 0x9097c0, 0xc00023a0e0, 0xc00022e300)
    /usr/local/go/src/net/http/server.go:2836 +0xa3
net/http.(*conn).serve(0xc0002081e0, 0x90a800, 0xc000218240)
    /usr/local/go/src/net/http/server.go:1924 +0x86c
created by net/http.(*Server).Serve
    /usr/local/go/src/net/http/server.go:2962 +0x35c
2021-03-18T17:13:01.361Z    undefined   ERROR   Uncaught Exception  {"errorType":"Error","errorMessage":"socket hang up","code":"ECONNRESET","stack":["Error: socket hang up","    at connResetException (internal/errors.js:609:14)","    at Socket.socketOnEnd (_http_client.js:458:23)","    at Socket.emit (events.js:326:22)","    at endReadableNT (_stream_readable.js:1241:12)","    at processTicksAndRejections (internal/process/task_queues.js:84:21)"]}
time="2021-03-18T17:13:01.368" level=error msg="Init failed" InvokeID= error="Runtime exited with error: exit status 129"
time="2021-03-18T17:13:01.369" level=error msg="INIT DONE failed: Runtime.ExitError"
2021-03-18 20:13:01,544 | Cleaning all decompressed code dirs
2021-03-18 20:13:01,545 | Sending Telemetry: {'metrics': [{'commandRun': {'requestId': 'e407eafe-1097-4da6-91e8-4cbf325ba359', 'installationId': 'a6304821-17c2-4514-8297-7782df26a31d', 'sessionId': '571947cc-f1dc-4d82-b295-cfd7f43ee404', 'executionEnvironment': 'CLI', 'pyversion': '3.8.8', 'samcliVersion': '1.21.1', 'awsProfileProvided': False, 'debugFlagProvided': True, 'region': '', 'commandName': 'sam local invoke', 'duration': 809, 'exitReason': 'success', 'exitCode': 0}}]}
2021-03-18 20:13:02,449 | HTTPSConnectionPool(host='aws-serverless-tools-telemetry.us-west-2.amazonaws.com', port=443): Read timed out. (read timeout=0.1)
2021-03-18 20:13:02,449 | Telemetry endpoint configured to be https://aws-serverless-tools-telemetry.us-west-2.amazonaws.com/metrics
2021-03-18 20:13:02,450 | Sending Telemetry: {'metrics': [{'runtimeMetric': {'requestId': '4d5cfff5-2c70-4bb9-9fa5-052bc7126a16', 'installationId': 'a6304821-17c2-4514-8297-7782df26a31d', 'sessionId': '571947cc-f1dc-4d82-b295-cfd7f43ee404', 'executionEnvironment': 'CLI', 'pyversion': '3.8.8', 'samcliVersion': '1.21.1', 'runtimes': ['nodejs12.x']}}]}
2021-03-18 20:13:03,214 | HTTPSConnectionPool(host='aws-serverless-tools-telemetry.us-west-2.amazonaws.com', port=443): Read timed out. (read timeout=0.1)

我引用的是我实际的 src 目录,在我的例子中应该用 dist/src 替换。所以,code 参数应该是 code: lambda.Code.fromAsset('dist/src') 而不是 code: lambda.Code.fromAsset('src').