Path: blob/main/components/supervisor/frontend/src/ide/heart-beat.ts
2501 views
/**1* Copyright (c) 2020 Gitpod GmbH. All rights reserved.2* Licensed under the GNU Affero General Public License (AGPL).3* See License.AGPL.txt in the project root for license information.4*/56import { DisposableCollection, Disposable } from "@gitpod/gitpod-protocol/lib/util/disposable";7import { FrontendDashboardServiceClient } from "../shared/frontend-dashboard-service";89let lastActivity = 0;10const updateLastActivitiy = () => {11lastActivity = new Date().getTime();12};13export const track = (w: Window) => {14w.document.addEventListener("mousemove", updateLastActivitiy, { capture: true });15w.document.addEventListener("keydown", updateLastActivitiy, { capture: true });16};1718let toCancel: DisposableCollection | undefined;19export function schedule(frontendDashboardServiceClient: FrontendDashboardServiceClient): void {20if (toCancel) {21return;22}23toCancel = new DisposableCollection();24const sendHeartBeat = async (wasClosed?: true) => {25try {26frontendDashboardServiceClient.activeHeartbeat(); // wasClosed27if (wasClosed) {28frontendDashboardServiceClient.trackEvent({29event: "ide_close_signal",30properties: {31clientKind: "supervisor-frontend",32},33});34}35} catch (err) {36console.error("Failed to send hearbeat:", err);37}38};39sendHeartBeat();4041let activityInterval = 30000;42const intervalHandle = setInterval(() => {43// add an additional random value between 5 and 15 seconds44const randomInterval = Math.floor(Math.random() * (15000 - 5000 + 1)) + 5000;45if (lastActivity + activityInterval + randomInterval < new Date().getTime()) {46// no activity, no heartbeat47return;48}49sendHeartBeat();50}, activityInterval);51toCancel.push(Disposable.create(() => clearInterval(intervalHandle)));52}5354export const cancel = () => {55if (toCancel) {56toCancel.dispose();57toCancel = undefined;58}59};606162