addons/isl/src/heartbeat.tsblame
View source
b69ab311/**
b69ab312 * Copyright (c) Meta Platforms, Inc. and affiliates.
b69ab313 *
b69ab314 * This source code is licensed under the MIT license found in the
b69ab315 * LICENSE file in the root directory of this source tree.
b69ab316 */
b69ab317
b69ab318import {useEffect, useState} from 'react';
b69ab319import {randomId} from 'shared/utils';
b69ab3110import clientToServerAPI from './ClientToServerAPI';
b69ab3111
b69ab3112export type Heartbeat =
b69ab3113 | {
b69ab3114 type: 'waiting';
b69ab3115 }
b69ab3116 | {
b69ab3117 type: 'timeout';
b69ab3118 }
b69ab3119 | {
b69ab3120 type: 'success' | 'slow';
b69ab3121 /** Round trip time between sending the heartbeat and getting the response */
b69ab3122 rtt: number;
b69ab3123 };
b69ab3124
b69ab3125export const DEFAULT_HEARTBEAT_TIMEOUT_MS = 1500;
b69ab3126
b69ab3127/**
b69ab3128 * Ping the server
b69ab3129 */
b69ab3130export function useHeartbeat(timeoutMs = DEFAULT_HEARTBEAT_TIMEOUT_MS) {
b69ab3131 const [state, setState] = useState<Heartbeat>({type: 'waiting'});
b69ab3132
b69ab3133 useEffect(() => {
b69ab3134 const id = randomId();
b69ab3135 const start = Date.now();
b69ab3136 clientToServerAPI.postMessage({type: 'heartbeat', id});
b69ab3137 clientToServerAPI
b69ab3138 .nextMessageMatching('heartbeat', message => message.id === id)
b69ab3139 .then(() => {
b69ab3140 setState(val => {
b69ab3141 if (val.type === 'waiting') {
b69ab3142 return {type: 'success', rtt: Date.now() - start};
b69ab3143 } else if (val.type === 'timeout') {
b69ab3144 return {type: 'slow', rtt: Date.now() - start};
b69ab3145 }
b69ab3146 return val;
b69ab3147 });
b69ab3148 });
b69ab3149
b69ab3150 const timeout = setTimeout(() => {
b69ab3151 setTimeout(() => {
b69ab3152 setState(val => {
b69ab3153 if (val.type === 'waiting') {
b69ab3154 return {type: 'timeout'};
b69ab3155 }
b69ab3156 return val;
b69ab3157 });
b69ab3158 });
b69ab3159 }, timeoutMs);
b69ab3160
b69ab3161 return () => clearTimeout(timeout);
b69ab3162 }, [setState, timeoutMs]);
b69ab3163
b69ab3164 return state;
b69ab3165}