All Products
Search
Document Center

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

Last Updated:Feb 03, 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.

Prerequisites

A service is created. For more information, see 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 WebSocket server listens is 0.0.0.0, which indicates that the server listens on 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 the 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 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

More information

Request timeout

Function Compute does not distinguish between WebSocket requests and HTTP requests in terms of the execution timeout period. If the period of an alive WebSocket connection exceeds 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 keeps alive unless the connection duration exceeds the specified timeout period, and Function Compute does not disrupt existing logic. If no data is transmitted within a specific period of time when the WebSocket connection is alive, the connection may be closed by an intermediate node, such as NAT Gateway. In this case, you may need to keep the connection alive by using the ping and pong frames provided by the WebSocket protocol or check whether the WebSocket connection is available.

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.

Sticky sessions (session affinity)

Function Compute are 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 rules

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

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

  • For a function whose instance concurrency is greater than 1, the billing starts at the time when the first WebSocket connection is established and ends at the time when the last WebSocket connection is terminated. If the function has multiple connections that are overlapped within a period of time, the system implements billing for the period of time 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 for several seconds and try again.

  • Check whether dependencies in function code of the function 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. However, the IP address 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. The date information is used to calculate a signature, and the signature is valid only for 15 minutes. If you use an HTTP trigger that requires access authentication, the signature becomes invalid if the date information in the request header is generated for over 15 minutes.

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 throttling

FcCommonError

429

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

No

System error

FcCommonError

500

A system error occurs in Function Compute. Try again.

No

System throttling

FcCommonError

503

System throttling is enabled for 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.

References

  • 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.