From 9af8d7fdb1610c7b11040d8fd9c9d6c00c4d8f13 Mon Sep 17 00:00:00 2001 From: Ryan Lee Date: Mon, 29 Jul 2024 15:48:21 -0400 Subject: [PATCH] chore: add heartbeat --- packages/extension/src/background.ts | 20 ++++++++++++++ packages/extension/src/heartbeat.ts | 39 ++++++++++++++++++++++++++++ 2 files changed, 59 insertions(+) create mode 100644 packages/extension/src/heartbeat.ts diff --git a/packages/extension/src/background.ts b/packages/extension/src/background.ts index 962afcda2b2..9546fc73351 100644 --- a/packages/extension/src/background.ts +++ b/packages/extension/src/background.ts @@ -77,6 +77,26 @@ chrome.tabs.onRemoved.addListener(() => { getActiveTabs(); }); +// add heartbeat using alarms to prevent the service worker from being killed as +// much as possible. +chrome.alarms.onAlarm.addListener(async () => { + await chrome.storage.local.set({ 'last-heartbeat': new Date().getTime() }); +}) + +chrome.runtime.onInstalled.addListener(({ reason }) => { + if ( + reason !== chrome.runtime.OnInstalledReason.INSTALL && + reason !== chrome.runtime.OnInstalledReason.UPDATE + ) + return + + chrome.alarms.create("heartbeat", { + periodInMinutes: 0.5, + }) +}) + +startHeartbeat() + // initial setup cryptoWaitReady() .then((): void => { diff --git a/packages/extension/src/heartbeat.ts b/packages/extension/src/heartbeat.ts new file mode 100644 index 00000000000..25bba909a69 --- /dev/null +++ b/packages/extension/src/heartbeat.ts @@ -0,0 +1,39 @@ +// Copyright 2019-2024 @polkadot/extension authors & contributors +// SPDX-License-Identifier: Apache-2.0 + +/** + * Heartbeat functions as described by google. + * + * @see https://developer.chrome.com/docs/extensions/develop/migrate/to-service-workers#keep_a_service_worker_alive_continuously + */ + +let heartbeatInterval: string | number | NodeJS.Timeout | undefined; + +async function runHeartbeat() { + await chrome.storage.local.set({ 'last-heartbeat': new Date().getTime() }); +} + +/** + * Starts the heartbeat interval which keeps the service worker alive. Call + * this sparingly when you are doing work which requires persistence, and call + * stopHeartbeat once that work is complete. + */ +async function startHeartbeat() { + // Run the heartbeat once at service worker startup. + runHeartbeat().then(() => { + // Then again every 20 seconds. + heartbeatInterval = setInterval(runHeartbeat, 20 * 1000); + }); +} + +async function stopHeartbeat() { + clearInterval(heartbeatInterval); +} + +/** + * Returns the last heartbeat stored in extension storage, or undefined if + * the heartbeat has never run before. + */ +async function getLastHeartbeat() { + return (await chrome.storage.local.get('last-heartbeat'))['last-heartbeat']; +}