Skip to content

Commit

Permalink
Merge pull request #1010 from appwrite/feat-implement-heartbeat
Browse files Browse the repository at this point in the history
feat: implement heartbeat
  • Loading branch information
christyjacob4 authored Dec 16, 2024
2 parents 675362c + ae553cc commit 27d8ecd
Showing 1 changed file with 29 additions and 4 deletions.
33 changes: 29 additions & 4 deletions templates/web/src/client.ts.twig
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,9 @@ type Headers = {
*/
type RealtimeResponse = {
/**
* Type of the response: 'error', 'event', 'connected', or 'response'.
* Type of the response: 'error', 'event', 'connected', 'pong', or 'response'.
*/
type: 'error' | 'event' | 'connected' | 'response';
type: 'error' | 'event' | 'connected' | 'response' | 'pong';

/**
* Data associated with the response based on the response type.
Expand Down Expand Up @@ -129,6 +129,8 @@ type RealtimeRequestAuthenticate = {
session: string;
}

type TimeoutHandle = ReturnType<typeof setTimeout> | number;

/**
* Realtime interface representing the structure of a realtime communication object.
*/
Expand All @@ -139,9 +141,14 @@ type Realtime = {
socket?: WebSocket;

/**
* Timeout duration for communication operations.
* Timeout for reconnect operations.
*/
timeout?: number;
timeout?: TimeoutHandle;

/**
* Heartbeat interval for the realtime connection.
*/
heartbeat?: TimeoutHandle;

/**
* URL for establishing the WebSocket connection.
Expand Down Expand Up @@ -196,6 +203,11 @@ type Realtime = {
*/
createSocket: () => void;

/**
* Function to create a new heartbeat interval.
*/
createHeartbeat: () => void;

/**
* Function to clean up resources associated with specified channels.
*
Expand Down Expand Up @@ -359,6 +371,7 @@ class Client {
private realtime: Realtime = {
socket: undefined,
timeout: undefined,
heartbeat: undefined,
url: '',
channels: new Set(),
subscriptions: new Map(),
Expand All @@ -384,6 +397,17 @@ class Client {
return 60_000;
}
},
createHeartbeat: () => {
if (this.realtime.heartbeat) {
clearTimeout(this.realtime.heartbeat);
}

this.realtime.heartbeat = window?.setInterval(() => {
this.realtime.socket?.send(JSON.stringify({
type: 'ping'
}));
}, 20_000);
},
createSocket: () => {
if (this.realtime.channels.size < 1) {
this.realtime.reconnect = false;
Expand Down Expand Up @@ -417,6 +441,7 @@ class Client {
this.realtime.socket.addEventListener('message', this.realtime.onMessage);
this.realtime.socket.addEventListener('open', _event => {
this.realtime.reconnectAttempts = 0;
this.realtime.createHeartbeat();
});
this.realtime.socket.addEventListener('close', event => {
if (
Expand Down

0 comments on commit 27d8ecd

Please sign in to comment.