Function Compute supports HTTP triggers. After you configure an HTTP trigger for a function, the function can be triggered and executed by using a WebSocket request. Such a function is similar to a web server that receives WebSocket requests and returns responses to the caller. This topic describes how to configure an HTTP trigger for a function that is triggered by WebSocket requests in the Function Compute console.

Prerequisites

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 the parameters, and then click Create.
    Configure the following parameters as described. Keep the default values for other parameters. For more information, see Create a function.
    • Function Name: Enter the name of the function, for example, WEBSOCKET-DEMO.
    • Request Type: Select HTTP Requests.
    • Runtime Environments: 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 to write code in the code editor.
    In the current directory of the web IDE, 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 and cannot be 127.0.0.1 or localhost. By default, if you do not specify a custom listening port, port 9000 is used.
    The following figure shows the directory structure of web IDE.directory1
  2. In the web IDE terminal, run the npm install ws command to install dependencies.
    After the installation, the package-lock.json file is generated. The following figure shows the directory structure.dir2
  3. Click Deploy Code to deploy your 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.
    trigger
  2. Use Postman to test the function.
    Copy the URL to Postman and change the value of the Scheme parameter from HTTPS to WSS. For more information, see Postman.

Billing method

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 longer connection time.

  • 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 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.
    The following figure shows an example of billing for a function whose instance concurrency 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 to T4. The period from T2 to T3 is billed only once. websocket-billing

Additional information

Request timeout

Function Compute does not distinguish between WebSocket requests and HTTP requests when it determines whether a request times out. If the duration of a WebSocket connection exceeds the specified timeout period, the WebSocket connection is terminated and the client receives status code 1006.

Keep-alive mode and reconnection upon timeout

After a WebSocket connection is established, Function Compute does not interfere with the execution logic of the request. When the connection times out, Function Compute terminates the connection. 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 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 verify whether the WebSocket connection is available.

If you want to set a timeout period that is greater than the maximum request timeout period of Function Compute, or you want to maintain a logically stable connection when you run an application, you can add a reconnection mechanism upon timeout in the client code. You can implement this mechanism by using the Reconnecting-WebSocket library or the SocketIO library.

Sticky sessions (session affinity)

Function Compute is stateless. When a large number of concurrent requests are sent to a function, Function Compute cannot ensure that a container can process requests from the same client. 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 a chat room application, Function Compute cannot ensure 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 information to the channel to which the chat room belong in Redis. This way, all users in the chat room can receive the message.

Examples

Custom Runtime Custom Container
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 a few seconds and try again.
  • Check whether the dependencies in the function code are correctly installed. For more information, see Install third-party dependencies on Function Compute.
  • 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. By default, if you do not specify a custom listening port, port 9000 is used.

Troubleshooting

The following errors that may occur before a WebSocket handshake is completed:
  • 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 exceeded the limits on HTTP requests. For more information, see Limits. No
FcCommonError 400 The request for a function that requires identity authentication does not contain the date information or authorization information. No
FcCommonError 403 The signature of the request for a function that requires identity authentication is invalid. As a result, the authorization information is invalid. Date is used to calculate a signature, and the signature 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 Your traffic is throttled. You can reduce the number of concurrent requests or contact the Function Compute team to raise the concurrency limit. No
System error FcCommonError 500 The Function Compute system is abnormal. Try again. No
System throttling FcCommonError 503 The Function Compute system is throttled. You can perform retry in the exponential backoff mode. No

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

References

Aside from the Function Compute console, you can configure triggers in the following ways:

To modify or delete an existing trigger, see Manage triggers.