aws-sam-cli icon indicating copy to clipboard operation
aws-sam-cli copied to clipboard

Bug: sam local invoke on dotnet minimal api throws NullReferenceException in runtime container

Open MengLinMaker opened this issue 10 months ago • 2 comments

Description:

We have a dotnet minimal api demo. sam deploy works, which could be invoked from AWS cloud. sam local start-api also works. However, sam local invoke would throw an error.

Steps to reproduce:

  1. Clone repo - https://github.com/sravimohan/Dotnet6MinApiLambdaSample
  2. Run sam build
  3. Run sam invoke local

Observed result:

sam local invoke output:

{
  "errorType": "NullReferenceException",
  "errorMessage": "Object reference not set to an instance of an object.",
  "stackTrace": [
    "at Amazon.Lambda.AspNetCoreServer.APIGatewayHttpApiV2ProxyFunction.MarshallRequest(InvokeFeatures features, APIGatewayHttpApiV2ProxyRequest apiGatewayRequest, ILambdaContext lambdaContext)",
    "at Amazon.Lambda.AspNetCoreServer.AbstractAspNetCoreFunction`2.FunctionHandlerAsync(TREQUEST request, ILambdaContext lambdaContext)",
    "at Amazon.Lambda.RuntimeSupport.HandlerWrapper.<>c__DisplayClass26_0`2.<<GetHandlerWrapper>b__0>d.MoveNext()",
    "--- End of stack trace from previous location ---",
    "at Amazon.Lambda.RuntimeSupport.LambdaBootstrap.InvokeOnceAsync(CancellationToken cancellationToken)"
  ]
}

sam local invoke --debug output:

2025-02-07 22:51:32,997 | Config file location: /Users/menglinmaker/Downloads/Dotnet6MinApiLambdaSample-main/samconfig.toml  
2025-02-07 22:51:32,998 | Loading configuration values from [default.['local', 'invoke'].parameters]                         
(env.command_name.section) in config file at '/Users/menglinmaker/Downloads/Dotnet6MinApiLambdaSample-main/samconfig.toml'...
2025-02-07 22:51:32,999 | Configuration values successfully loaded.                                                          
2025-02-07 22:51:32,999 | Configuration values are: {}                                                                       
2025-02-07 22:51:33,001 | Using SAM Template at                                                                              
/Users/menglinmaker/Downloads/Dotnet6MinApiLambdaSample-main/.aws-sam/build/template.yaml                                    
2025-02-07 22:51:33,017 | Using config file: samconfig.toml, config environment: default                                     
2025-02-07 22:51:33,018 | Expand command line arguments to:                                                                  
2025-02-07 22:51:33,018 |                                                                                                    
--template_file=/Users/menglinmaker/Downloads/Dotnet6MinApiLambdaSample-main/.aws-sam/build/template.yaml --no_event         
--layer_cache_basedir=/Users/menglinmaker/.aws-sam/layers-pkg --container_host=localhost --container_host_interface=127.0.0.1
2025-02-07 22:51:33,019 | local invoke command is called                                                                     
2025-02-07 22:51:34,480 | No Parameters detected in the template                                                             
2025-02-07 22:51:34,499 | Sam customer defined id is more priority than other IDs. Customer defined id for resource          
Dotnet6MinApiLambda is Dotnet6MinApiLambda                                                                                   
2025-02-07 22:51:34,499 | There is no customer defined id or cdk path defined for resource ServerlessHttpApi, so we will use 
the resource logical id as the resource id                                                                                   
2025-02-07 22:51:34,500 | 0 stacks found in the template                                                                     
2025-02-07 22:51:34,500 | No Parameters detected in the template                                                             
2025-02-07 22:51:34,512 | Sam customer defined id is more priority than other IDs. Customer defined id for resource          
Dotnet6MinApiLambda is Dotnet6MinApiLambda                                                                                   
2025-02-07 22:51:34,512 | There is no customer defined id or cdk path defined for resource ServerlessHttpApi, so we will use 
the resource logical id as the resource id                                                                                   
2025-02-07 22:51:34,513 | 2 resources found in the stack                                                                     
2025-02-07 22:51:34,513 | Found Serverless function with name='Dotnet6MinApiLambda' and CodeUri='Dotnet6MinApiLambda'        
2025-02-07 22:51:34,514 | --base-dir is not presented, adjusting uri Dotnet6MinApiLambda relative to                         
/Users/menglinmaker/Downloads/Dotnet6MinApiLambdaSample-main/.aws-sam/build/template.yaml                                    
2025-02-07 22:51:34,522 | Found one Lambda function with name 'Dotnet6MinApiLambda'                                          
2025-02-07 22:51:34,522 | Invoking Dotnet6MinApiLambdaSample (dotnet8)                                                       
2025-02-07 22:51:34,523 | No environment variables found for function 'Dotnet6MinApiLambda'                                  
2025-02-07 22:51:34,523 | Loading AWS credentials from session with profile 'None'                                           
2025-02-07 22:51:34,529 | Resolving code path.                                                                               
Cwd=/Users/menglinmaker/Downloads/Dotnet6MinApiLambdaSample-main/.aws-sam/build,                                             
CodeUri=/Users/menglinmaker/Downloads/Dotnet6MinApiLambdaSample-main/.aws-sam/build/Dotnet6MinApiLambda                      
2025-02-07 22:51:34,529 | Resolved absolute path to code is                                                                  
/Users/menglinmaker/Downloads/Dotnet6MinApiLambdaSample-main/.aws-sam/build/Dotnet6MinApiLambda                              
2025-02-07 22:51:34,530 | Resolving code path.                                                                               
Cwd=/Users/menglinmaker/Downloads/Dotnet6MinApiLambdaSample-main/.aws-sam/build,                                             
CodeUri=/Users/menglinmaker/Downloads/Dotnet6MinApiLambdaSample-main/.aws-sam/build/Dotnet6MinApiLambda                      
2025-02-07 22:51:34,530 | Resolved real code path to                                                                         
/Users/menglinmaker/Downloads/Dotnet6MinApiLambdaSample-main/.aws-sam/build/Dotnet6MinApiLambda                              
2025-02-07 22:51:34,530 | Code                                                                                               
/Users/menglinmaker/Downloads/Dotnet6MinApiLambdaSample-main/.aws-sam/build/Dotnet6MinApiLambda is not a zip/jar file        
2025-02-07 22:51:38,742 | Local image is up-to-date                                                                          
2025-02-07 22:51:38,764 | Checking free port on 127.0.0.1:6570                                                               
2025-02-07 22:51:38,775 | Using local image: public.ecr.aws/lambda/dotnet:8-rapid-arm64.                                     
                                                                                                                             
2025-02-07 22:51:38,777 | Mounting                                                                                           
/Users/menglinmaker/Downloads/Dotnet6MinApiLambdaSample-main/.aws-sam/build/Dotnet6MinApiLambda as /var/task:ro,delegated,   
inside runtime container                                                                                                     
2025-02-07 22:51:39,130 | Starting a timer for 3 seconds for function 'Dotnet6MinApiLambda'                                  
2025-02-07 22:51:39,131 | Getting lock for the key localhost-6570                                                            
2025-02-07 22:51:39,131 | Waiting to retrieve the lock (localhost-6570) to start invocation                                  
START RequestId: f4fdaaa1-9793-44b4-8719-a54aa161670a Version: $LATEST
END RequestId: a2a7f419-33c4-4485-ae84-a64765ffc646
REPORT RequestId: a2a7f419-33c4-4485-ae84-a64765ffc646  Init Duration: 0.05 ms  Duration: 196.42 ms     Billed Duration: 197 ms      Memory Size: 128 MB     Max Memory Used: 128 MB

2025-02-07 22:51:39,333 | [Container state] OOMKilled False                                                                  
2025-02-07 22:51:39,512 | Cleaning all decompressed code dirs                                                                
2025-02-07 22:51:39,514 | Telemetry endpoint configured to be                                                                
https://aws-serverless-tools-telemetry.us-west-2.amazonaws.com/metrics                                                       
2025-02-07 22:51:39,564 | Telemetry endpoint configured to be                                                                
https://aws-serverless-tools-telemetry.us-west-2.amazonaws.com/metrics                                                       
2025-02-07 22:51:39,564 | Sending Telemetry: {'metrics': [{'commandRun': {'requestId':                                       
'863edf19-4f34-4e60-8a9c-a125ead97020', 'installationId': '7bf6b43e-777b-4524-bcfb-bf5bbd405eb5', 'sessionId':               
'db3ea8ef-f7c4-48e5-a5aa-83f61bd5f408', 'executionEnvironment': 'CLI', 'ci': False, 'pyversion': '3.11.10', 'samcliVersion': 
'1.132.0', 'awsProfileProvided': False, 'debugFlagProvided': True, 'region': '', 'commandName': 'sam local invoke',          
'metricSpecificAttributes': {'projectType': 'CFN', 'gitOrigin': None, 'projectName':                                         
'b07f98a66fa397b0b2457d2cc1e57495ab951c55a89925ca215befe6d303bca5', 'initialCommit': None}, 'duration': 6496, 'exitReason':  
'success', 'exitCode': 0}}]}                                                                                                 
2025-02-07 22:51:39,565 | Unable to find Click Context for getting session_id.                                               
2025-02-07 22:51:39,567 | Sending Telemetry: {'metrics': [{'events': {'requestId': 'f2e2ff0d-cf3a-4cdf-81f5-00b90f198401',   
'installationId': '7bf6b43e-777b-4524-bcfb-bf5bbd405eb5', 'sessionId': 'db3ea8ef-f7c4-48e5-a5aa-83f61bd5f408',               
'executionEnvironment': 'CLI', 'ci': False, 'pyversion': '3.11.10', 'samcliVersion': '1.132.0', 'commandName': 'sam local    
invoke', 'metricSpecificAttributes': {'events': [{'event_name': 'SamConfigFileExtension', 'event_value': '.toml',            
'thread_id': '3579de4bd0cd44ae868d5ef0a2f51b46', 'time_stamp': '2025-02-07 11:51:32.996', 'exception_name': None},           
{'event_name': 'SamConfigFileExtension', 'event_value': '.toml', 'thread_id': '515a9451914949d0b932354e652d04e8',            
'time_stamp': '2025-02-07 11:51:33.017', 'exception_name': None}]}}}]}                                                       
2025-02-07 22:51:40,098 | HTTPSConnectionPool(host='aws-serverless-tools-telemetry.us-west-2.amazonaws.com', port=443): Read 
timed out. (read timeout=0.1)                                                                                                
2025-02-07 22:51:40,100 | HTTPSConnectionPool(host='aws-serverless-tools-telemetry.us-west-2.amazonaws.com', port=443): Read 
timed out. (read timeout=0.1)                                                                                                
2025-02-07 22:51:40,100 | Telemetry endpoint configured to be                                                                
https://aws-serverless-tools-telemetry.us-west-2.amazonaws.com/metrics                                                       
2025-02-07 22:51:40,101 | Sending Telemetry: {'metrics': [{'runtimeMetric': {'requestId':                                    
'f4971668-46f4-4f7a-a0a9-62e21bd51665', 'installationId': '7bf6b43e-777b-4524-bcfb-bf5bbd405eb5', 'sessionId':               
'db3ea8ef-f7c4-48e5-a5aa-83f61bd5f408', 'executionEnvironment': 'CLI', 'ci': False, 'pyversion': '3.11.10', 'samcliVersion': 
'1.132.0', 'runtimes': ['dotnet8']}}]}                                                                                       
2025-02-07 22:51:40,580 | HTTPSConnectionPool(host='aws-serverless-tools-telemetry.us-west-2.amazonaws.com', port=443): Read 
timed out. (read timeout=0.1) 

Expected result:

Should return some json array.

Additional environment details (Ex: Windows, Mac, Amazon Linux etc)

{
  "version": "1.132.0",
  "system": {
    "python": "3.11.10",
    "os": "macOS-15.1.1-arm64-arm-64bit"
  },
  "additional_dependencies": {
    "docker_engine": "27.5.1",
    "aws_cdk": "2.177.0 (build b396961)",
    "terraform": "1.5.7"
  },
  "available_beta_feature_env_vars": [
    "SAM_CLI_BETA_FEATURES",
    "SAM_CLI_BETA_BUILD_PERFORMANCE",
    "SAM_CLI_BETA_TERRAFORM_SUPPORT",
    "SAM_CLI_BETA_RUST_CARGO_LAMBDA"
  ]
}

MengLinMaker avatar Feb 07 '25 11:02 MengLinMaker

Hey there. Thanks for raising this. I was able to reproduce the issue. We will investigate more and will reach out if we need additional information.

mbfreder avatar Feb 19 '25 01:02 mbfreder

The error happens because you are probably local invoking without providing an event. Please try sam local invoke with an APIGatewayHttpApi event. You can follow the steps below:

  1. Create an event.json file in your function's root directory with the following content:
{
    "version": "2.0",
    "routeKey": "GET /",
    "rawPath": "/",
    "rawQueryString": "",
    "headers": {
      "accept": "*/*",
      "content-length": "0",
      "host": "localhost:3000",
      "user-agent": "curl/7.64.1",
      "x-forwarded-proto": "http",
      "x-forwarded-port": "3000"
    },
    "requestContext": {
      "accountId": "123456789012",
      "apiId": "api-id",
      "domainName": "localhost:3000",
      "domainPrefix": "localhost",
      "http": {
        "method": "GET",
        "path": "/",
        "protocol": "HTTP/1.1",
        "sourceIp": "127.0.0.1",
        "userAgent": "curl/7.64.1"
      },
      "requestId": "request-id",
      "routeKey": "GET /",
      "stage": "$default",
      "time": "12/Mar/2020:19:03:58 +0000",
      "timeEpoch": 1583348638390
    },
    "isBase64Encoded": false
  }
  1. Run sam local invoke -e event.json

Please let us know if you need anything else.

mbfreder avatar Mar 23 '25 12:03 mbfreder