# Websockets API Date: **08/24/2021** Websockets client API for Matrix. **Websockets is not replace API**, but Websockets uses matrix API to get the data from DB. The main goal is to have a more efficient interface than the REST API: by using a bidirectional protocol such as WebSockets we can avoid Regularly call sync API. # Milestone 1 * How many people/who are going to implement this? * ETA: *6 months ~ 1 year (1 person)* * Programming language: Javascript (nodejs)? Go? Python? Rust? others? Reliability, Speed, Development Process, Human Resources * Limitation: **a single server can handle 65,536 socket connections just because it's the max number of TCP ports available.** ## Handshake Instead of calling `/sync`, the client makes a websocket request to `/_matrix/client/r0/ws/stream`, passing the query parameters `access_token` and `since`. - which have the same meaning as for `/sync`. The server returns the websocket handshake; the socket is then connected. If the server does not return a valid websocket handshake, this indicates that the server or an intermediate proxy does not support WebSockets. Flow : 1. Client send a HTTP request to LALE server for login or sync. 2. Client send a HTTP request to Webscoket server, including the access_token, sync_token. (for handshake) 3. Websocket calls Matrix API (/sync) and return websocket connection & sync data. **HTTP request** url : `GET /_matrix/client/r0/stream?access_token=123456&since=s72594_4483_1934` ## Update Once the socket is connected, the server begins streaming updates over the websocket. The server sends Update about new messages. Update notifications have the same structure as the response to `/sync`. ## Send Send a message event to a room. Implement: `PUT /_matrix/client/r0/rooms/{roomId}/send/{eventType}/{txnId}` [Ref](https://matrix.org/docs/spec/client_server/latest#put-matrix-client-r0-rooms-roomid-send-eventtype-txnid) Flow : 1. Client send a websocket request. 2. Websocket call Matrix API to store to the DB. 3. Websocket gets all related users. 4. If users connected to the Websocket, send sync/stream for all related users. **Websocket request** Client request: ``` { "id": "12345", "method": "send", "params": { "room_id": "!d41d8cd:lalepass.lale.im", "event_type": "m.room.message", "content": { "msgtype": "m.text", "body": "hello" } } } ``` Server response: ``` { "id": "12345", "result": { "event_id": "$66697273743031:matrix.org" } } ``` # Suggestions 1. We need more people to develop websocket API. 2. Technology & programming language. * These affect the Reliability, Speed, Development Process and Human Resources. * Nodejs? Go? Rust? Python? Java? Others? 3. Create a different client app for testing the websocket API. * Start from PC version. (most stable websockets technology is in PC) 4. Please take this document as a reference only. You may consult with other Senior Engineers regarding webscoket technology.