All Products
Search
Document Center

Function Compute:Configure an HTTP trigger for a function to respond to WebSocket requests

Last Updated:Oct 31, 2024

In Function Compute, you can configure an HTTP trigger for a function to respond to WebSocket requests. After you configure an HTTP trigger for a function, the function works as a web server to handle WebSocket requests and returns responses to callers.

Before you start

Create a service

Step 1: Create a function

  1. Log on to the Function Compute console. In the left-side navigation pane, click Services & Functions.

  2. In the top navigation bar, select a region. On the Services page, click the desired service.

  3. On the Functions page, click Create Function.
  4. On the Create Function page, select Use Custom Runtime, configure parameters, and then click Create.

    The following items describe parameters that you must configure. For other parameters that are not listed, retain the default values. For more information, see Create a function.

    • Function Name: Enter the name of the function. Example: websocket-demo.

    • Handler Type: Select HTTP Handler.

    • Runtime: Select Node.js 14 from the drop-down list.

Step 2: Write and deploy code

  1. On the function details page, click the Code tab and enter function code in the code editor.

    In the current directory of WebIDE in the Function Compute console, copy the following code to the index.js file. Sample code:

    const WebSocket = require('ws');
    
    const WebSocketServer = WebSocket.Server;
    
    const wss = new WebSocketServer({
      host: "0.0.0.0",
      port: 9000,
    });
    
    wss.on('connection', function (ws, req) {
      console.log(`[SERVER] connection()`);
      ws.on('message', function (message) {
        ws.send(`${message}`, (err) => {
          if (err) {
            console.log(`[SERVER] error: ${err}`);
          }
        });
      })
    });
    Note
    • The IP address on which the WebSocket server listens is 0.0.0.0, which indicates all available network ports. Do not specify 127.0.0.1 or localhost as the IP address.

    • The port number on which the WebSocket server listens is an integer that ranges from 0 to 65535. In most cases, the port number is greater than 1024. You must set the port parameter to a value that you specified for your function. By default, the value is 9000.

    The following figure shows the directory structure of WebIDE. directory1

  2. In the WebIDE terminal, run the npm install ws command to install dependencies.

    After the dependencies are installed, the package-lock.json file is automatically generated. The following figure shows the directory structure.dir2

  3. Click Deploy to deploy code to Function Compute.

Step 3: Test the function

  1. On the function details page, click the Triggers tab to view and copy the public endpoint of the trigger.

    image.png

    Note

    After the HTTP trigger is created, the public endpoint remains unchanged.

  2. Use Postman to test the function. For more information, see Postman.

    1. Create a WebSocket request in Postman.

      Copy the public endpoint to Postman and change the value of the Scheme parameter from HTTPS to WebSocket Secure (WSS).

    2. Configure Params and Headers based on your business requirements.

    3. Connect to WebSocket. After the connection is established, you can send messages.

    4. Enter the messages that you want to send and check whether the function receives the messages.

    5. After an execution timeout period elapses, the connection to WebSocket is terminated.

    The following figure shows the test process.

    image.png

    (Optional) If FCCommonError occurs when you use Postman to test the HTTP trigger, check the authentication method of the HTTP trigger. If you do not need to authenticate access, you can set Authentication Method of the HTTP trigger to No Authentication before you perform the test.

    image

More information

Request timeout

Function Compute does not distinguish between WebSocket requests and HTTP requests in terms of execution timeout period. If a WebSocket connection lasts longer than the specified timeout period, the WebSocket connection is forcibly terminated and the client receives status code 1006.

Keep-alive mode and reconnection upon timeout

After a WebSocket connection is established, the connection statys alive unless the connection duration exceeds the specified timeout period, and Function Compute does not disrupt the existing logic. If no data is transmitted within a period of time when the WebSocket connection is alive, the connection may be disabled by an intermediate node, such as a NAT gateway that maps internal IP addresses of clients to public IP addresses, and route configurations. In this case, the connection timeout period is not fixed. If there is no data transmitted within the timeout period, the NAT gateway may disconnect the WebSocket connection. You may need to keep the connection alive or check whether the WebSocket connection is available by using the ping and pong frames provided by the WebSocket protocol.

If you require a longer timeout period that exceeds the maximum timeout period provided by Function Compute or you want to maintain stable logic for running applications, add a re-connection mechanism in client code to handle timeouts. You can implement the preceding mechanism by using the Reconnecting-WebSocket library or the SocketIO library.

Session affinity

Function Compute is stateless. When a function receives numerous concurrent requests at the same time, Function Compute cannot ensure that requests from the same client are processed by the same container. You may need to use external storage services, such as Redis, Memcached, Apache Kafka, and databases, to maintain the status of WebSocket requests between multiple container instances.

For example, for chat-room applications, Function Compute cannot guarantee that all users are connected to the same function instance at the same time. In this case, the Pub/Sub feature of Redis can be used to configure a chat room application. When users join a chat room, they subscribe (Sub) to the channel to which the chat room belongs. When User 1 sends a message to the function, the function publishes (Pub) the message to the channel to which the chat room belongs in Redis. This way, all users in the chat room can receive the message.

Billing methods

The billing methods for WebSocket requests and HTTP requests are the same. A WebSocket request can be regarded as an HTTP request with a longer connection time. For more information about billing, see Billing overview.

  • For a function whose instance concurrency is 1, the billing starts when the WebSocket connection is established and ends when the WebSocket connection is terminated.

  • For a function whose instance concurrency is greater than 1, the billing starts when the first WebSocket connection is established and ends when the last WebSocket connection is terminated. If multiple connections exist within a period of time, the system implements billing only once.

    In the following figure, the instance concurrency of a function is 2. The first request arrives at T1 and ends at T3. The second request arrives at T2 and ends at T4. The billing starts from T1 and ends at T4. From T2 to T3, fees are charged only once.websocket-billing

Examples

Custom runtime

Custom Container runtime

Python

Python

Node.js

Node.js

Golang

Golang

FAQ

Why am I unable to execute a WebSocket function?

  • The time period required to update the cache for a new trigger is approximately 10 seconds. Wait a few seconds and try again.

  • Check whether dependencies in the function code are correctly installed. For more information, see Install third-party dependencies for a function.

  • Check whether the port and IP address on which the function listens are correct. The IP address on which the function listens can be 0.0.0.0 but cannot be 127.0.0.1 or localhost. If you do not specify a custom listening port, port 9000 is used.

Troubleshooting

Before a WebSocket handshake is complete, the following errors may occur:

  • Request error: A request error occurs when a request that does not match specific conditions is sent. If a request error occurs, an HTTP status code 4xx is returned in the response.

  • Function error: A function error occurs when the function code is invalid. If a function error occurs, an HTTP status code 5xx is returned.

Error type

X-Fc-Error-Type

HTTP status code

Cause

Billable

Request error

FcCommonError

400

Your request exceeds the limits on requests. For more information, see Overview.

No

FcCommonError

400

The request for a function that requires identity authentication does not contain date or authorization information.

No

FcCommonError

403

The signature of the request for a function that requires identity authentication is invalid, which indicates that the authorization information is invalid. Date is used to calculate a signature, which is valid only for 15 minutes. When you use the HTTP trigger that requires access authentication, the signature becomes invalid if the date information in the request header times is 15 minutes over the current time.

No

FcCommonError

403

Your request uses a request method that is not configured in the HTTP trigger. For a WebSocket function, the HTTP trigger must support the GET method. The error is reported if the GET method is not configured.

No

FcCommonError

404

A WebSocket request is sent to a function for which no HTTP trigger is configured.

No

User traffic throttling

FcCommonError

429

You can reduce the concurrency or contact the Function Compute team to increase the concurrency limit.

No

A system error occurs.

FcCommonError

500

A system error occurs in Function Compute. Try again.

No

System traffic throttling

FcCommonError

503

A system throttling error occurs in Function Compute. You can retry in exponential backoff mode.

No

The errors that occur after the WebSocket handshake is complete are caused by function code. You can check your code or view the logs generated during code running for troubleshooting. For more information, see View function invocation logs.

Additional information

  • WebSocket has limits on runtimes, timeout periods, and data transmission. For more information, see Limits on WebSocket.

  • HTTP triggers support synchronous and asynchronous invocation. For more information, see Invocation methods.

  • Function Compute allows you to invoke HTTP functions across origins. For information about how to process cross-origin resource sharing (CORS) requests, see CORS request processing.