Websocket API returing "Unexpected server response: 502" on connection attempt.

0

I've been working on creating my first web socket API gateway. Everything was initially working. I was able to connect to the API and send and receive data within postman without issue even routing requests to my custom 'sendCommand' action. Now for some reason i'm not even able to initiate a connection to the web socket API or any new APis I create.

When i attempt to connect, postman is showing: Error: Unexpected server response: 502

While the associated error in cloudwatch is:
"errorMessage": "Error: Cannot find module 'index'\nRequire stack:\n- /var/runtime/index.mjs", "stack": [ "Runtime.ImportModuleError: Error: Cannot find module 'index'", "Require stack:", "- /var/runtime/index.mjs", " at _loadUserApp (file:///var/runtime/index.mjs:997:17)", " at async UserFunction.js.module.exports.load (file:///var/runtime/index.mjs:1032:21)", " at async start (file:///var/runtime/index.mjs:1195:23)", " at async file:///var/runtime/index.mjs:1201:1" ]

I'm not sure if this is related but the issue seems to have started shortly after I updated my lambda function for the API using the following bash script. The script successfully updates the lambda and I can see the updated change when viewing the lambda within the aws console via a browser.

#!/bin/bash
lambda_name=$1
zip_file="${lambda_name}.zip"
files="${lambda_name}.js"
chmod -R 755 ${files}
zip -r "${zip_file}" $files
aws lambda update-function-code --function-name "${lambda_name}" --zip-file "fileb://${zip_file}" --no-cli-pager

Lambda the API is pointing to: import { ApiGatewayManagementApiClient, PostToConnectionCommand, } from "@aws-sdk/client-apigatewaymanagementapi";

export const handler = async(event) => {
    console.log(event)
    
    const route = event.requestContext.routeKey
    const domain = event.requestContext.domainName;
    const stage = event.requestContext.stage;
    const connectionId = event.requestContext.connectionId;
    const callbackUrl = `https://${domain}/${stage}`;
      
    const client = new ApiGatewayManagementApiClient({endpoint: callbackUrl})

    const sendToOne = async(connectionId,body) => {
      const requestParams = {
        ConnectionId: connectionId,
        Data: body
      };

      const command = new PostToConnectionCommand(requestParams);
      
      try {
        await client.send(command);
      } catch (error) {
        console.log(error);
      }

      return {
        statusCode: 200,
      };
    }

    switch(route) {
        case '$connect':
            console.log("Connect")        
            break

        case '$disconnect':
            console.log('Disconnect')
            break

        case 'sendCommand':
            console.log('Command received', event)
            return sendToOne(connectionId, JSON.stringify(event))
            break

        case '$default':
          console.log('Unknown route', route)
          return sendToOne(connectionId, JSON.stringify(event))   
    }

    return {
        statusCode: 200
    }
};

Thanks in advance for any help!

1 Answer
0

It seems your Lambda function is not configured correctly and you will get the same error if you will try to test the Lambda function from the Lambda console. I think it has something to do with the name of the handler as it is configured in the function.

profile pictureAWS
EXPERT
Uri
answered 10 months ago
  • I was not able to figure out any issues with the Lambda.

    I have since created a brand new websocket api gateway and associated lambda(all from the aws console in a browser) and everything was working correctly(I could connect, send requests, and receive replies).

    I then save an identical copy of the lambda code locally and updated the lambda with the script i referenced earlier and am having the same issue again.

    Although the lambda code is identical and the update-function-code script successfully updates the lambda, this is what is causing the issue.

    Steps to reproduce the issue:

    1. I created and new websocket api gateway with a lambda function named 'ws'. The api works fine at this point.
    2. I copied the working lambda code from the aws console lambda editor into a text editor, added a single comment of //test to the top of the file (to confirm the lambda is being updated by my script and saved the file as ws.js
    3. I then executed the script below with the command './update-lambda.sh ws'
    4. I confirmed the lambda is updated with the identical code with the addition of the //test comment.

    Update script: #!/bin/bash lambda_name=$1 zip_file="${lambda_name}.zip" files="${lambda_name}.js" chmod -R 755 ${files} zip -r "${zip_file}" $files aws lambda update-function-code --function-name "${lambda_name}" --zip-file "fileb://${zip_file}" --no-cli-pager

  • Output from './update-lambda.sh ws':

        updating: ws.js (deflated 63%)
        {
            "FunctionName": "ws",
            "FunctionArn": "arn:aws:lambda:us-east-2:752196647762:function:ws",
            "Runtime": "nodejs18.x",
            "Role": "arn:aws:iam::752196647762:role/service-role/ws-role-tokldkvc",
            "Handler": "index.handler",
            "CodeSize": 400,
            "Description": "",
            "Timeout": 3,
            "MemorySize": 128,
            "LastModified": "2023-07-12T19:46:54.000+0000",
            "CodeSha256": "c6jN2TdrYC79bxH4RtX8vF7MHQPXjVcGVHc4GQMujZ4=",
            "Version": "$LATEST",
            "TracingConfig": {
                "Mode": "PassThrough"
            },
            "RevisionId": "62297b7a-0b79-4453-b892-9b578f271270",
            "State": "Active",
            "LastUpdateStatus": "InProgress",
            "LastUpdateStatusReason": "The function is being created.",
            "LastUpdateStatusReasonCode": "Creating",
            "PackageType": "Zip",
            "Architectures": [
                "x86_64"
            ],
            "EphemeralStorage": {
                "Size": 512
            },
            "SnapStart": {
                "ApplyOn": "None",
                "OptimizationStatus": "Off"
            },
            "RuntimeVersionConfig": {
                "RuntimeVersionArn": "arn:aws:lambda:us-east-2::runtime:2755dc322c8dbb64760145d6403d14432af527bf4dd3cf03713aae10e0f8b552"
            }
    

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.

Guidelines for Answering Questions