Function Compute supports HTTP triggers. After you configure an HTTP trigger for a function, the function can be triggered and executed by using an HTTP request or a WebSocket request. Such a function is similar to a web server that receives HTTP requests or 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.
  2. In the left-side navigation pane, click Services and Functions.
  3. In the top navigation bar, select the region where the service resides.
  4. On the Services page, click the target service.
  5. On the Functions page, click Create Function.
  6. On the Create Function page, select Use Custom Runtime.
  7. In the Basic Settings section, configure the parameters and click Create.
    In this example, the Function Name parameter is set to WEBSOCKET-DEMO, the Runtime Environments parameter is set to Node.js 14, and the Request Type parameter is set to HTTP Requests. For more information about the parameters, see Create a function.

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. If you do not specify a custom listening port, port 9000 is used by default.
    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 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

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. Therefore, when the WebSocket connection is established, the connection may be terminated by an intermediate node, such as a NAT gateway, if no data is transmitted for a period of time. In this case, you may need to keep the connection alive or verify whether the WebSocket connection is active by using the ping frames and pong frames provided by the WebSocket protocol.

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 on the client. 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. If you do not specify a listening port, port 9000 is used by default.

Troubleshooting

The following errors that may occur before the 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 errors FcCommonError 400 Your request exceeded the limits on HTTP requests. For more information, see Usage 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 information is used to calculate a signature, and the signature is valid only for 15 minutes. A common cause of this error is that an HTTP trigger that requires access authentication is used and the timestamp that is included in the date information in the request header is 15 minutes later than the local time. As a result, the signature is invalid. 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. If this method is not configured, the error is reported. 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 try again in 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.

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.