From 02fe70eaebe4c8601ce1581883330f65a4f220c7 Mon Sep 17 00:00:00 2001 From: Addison Beck Date: Fri, 27 Mar 2026 07:23:22 -0400 Subject: [PATCH] refactor(scheduling): extract @bitwarden/scheduling Nx leaf library (#19771) --- .github/CODEOWNERS | 1 + .nxignore | 2 +- jest.config.js | 1 + .../src/services/jslib-services.module.ts | 5 +- .../default-task-scheduler.service.ts | 98 +------------------ libs/common/src/platform/scheduling/index.ts | 4 +- .../scheduling/scheduled-task-name.enum.ts | 15 +-- .../scheduling/task-scheduler.service.ts | 78 +-------------- libs/scheduling/README.md | 27 +++++ libs/scheduling/eslint.config.mjs | 3 + libs/scheduling/jest.config.js | 10 ++ libs/scheduling/package.json | 11 +++ libs/scheduling/project.json | 34 +++++++ .../default-task-scheduler.service.spec.ts | 4 +- .../src/default-task-scheduler.service.ts | 98 +++++++++++++++++++ libs/scheduling/src/index.ts | 3 + .../src/scheduled-task-name.enum.ts | 14 +++ libs/scheduling/src/scheduling.spec.ts | 8 ++ libs/scheduling/src/task-scheduler.service.ts | 77 +++++++++++++++ libs/scheduling/tsconfig.eslint.json | 6 ++ libs/scheduling/tsconfig.json | 13 +++ libs/scheduling/tsconfig.lib.json | 10 ++ libs/scheduling/tsconfig.spec.json | 10 ++ package-lock.json | 9 ++ tsconfig.base.json | 1 + 25 files changed, 344 insertions(+), 198 deletions(-) create mode 100644 libs/scheduling/README.md create mode 100644 libs/scheduling/eslint.config.mjs create mode 100644 libs/scheduling/jest.config.js create mode 100644 libs/scheduling/package.json create mode 100644 libs/scheduling/project.json rename libs/{common/src/platform/scheduling => scheduling/src}/default-task-scheduler.service.spec.ts (96%) create mode 100644 libs/scheduling/src/default-task-scheduler.service.ts create mode 100644 libs/scheduling/src/index.ts create mode 100644 libs/scheduling/src/scheduled-task-name.enum.ts create mode 100644 libs/scheduling/src/scheduling.spec.ts create mode 100644 libs/scheduling/src/task-scheduler.service.ts create mode 100644 libs/scheduling/tsconfig.eslint.json create mode 100644 libs/scheduling/tsconfig.json create mode 100644 libs/scheduling/tsconfig.lib.json create mode 100644 libs/scheduling/tsconfig.spec.json diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index 321f79f0d5e..5c6adfc0140 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -122,6 +122,7 @@ libs/core-test-utils @bitwarden/team-platform-dev libs/state @bitwarden/team-platform-dev libs/state-internal @bitwarden/team-platform-dev libs/state-test-utils @bitwarden/team-platform-dev +libs/scheduling @bitwarden/team-platform-dev # Web utils used across app and connectors apps/web/src/utils/ @bitwarden/team-platform-dev # Web core and shared files diff --git a/.nxignore b/.nxignore index 528dc4eeda3..b744996d705 100644 --- a/.nxignore +++ b/.nxignore @@ -1 +1 @@ -scripts \ No newline at end of file +scripts diff --git a/jest.config.js b/jest.config.js index b0e4a9f6b13..b3bae138b4c 100644 --- a/jest.config.js +++ b/jest.config.js @@ -63,6 +63,7 @@ module.exports = { "/libs/subscription/jest.config.js", "/libs/unlock/jest.config.js", "/libs/user-crypto-management/jest.config.js", + "/libs/scheduling/jest.config.js", ], // Workaround for a memory leak that crashes tests in CI: diff --git a/libs/angular/src/services/jslib-services.module.ts b/libs/angular/src/services/jslib-services.module.ts index 59d5e43f278..a9c09c1e24c 100644 --- a/libs/angular/src/services/jslib-services.module.ts +++ b/libs/angular/src/services/jslib-services.module.ts @@ -258,10 +258,6 @@ import { Message, MessageListener, MessageSender } from "@bitwarden/common/platf // eslint-disable-next-line no-restricted-imports -- Used for dependency injection import { SubjectMessageSender } from "@bitwarden/common/platform/messaging/internal"; import { devFlagEnabled } from "@bitwarden/common/platform/misc/flags"; -import { - DefaultTaskSchedulerService, - TaskSchedulerService, -} from "@bitwarden/common/platform/scheduling"; import { ServerNotificationsService } from "@bitwarden/common/platform/server-notifications"; // eslint-disable-next-line no-restricted-imports -- Needed for service creation import { @@ -375,6 +371,7 @@ import { UserAsymmetricKeysRegenerationApiService, UserAsymmetricKeysRegenerationService, } from "@bitwarden/key-management"; +import { DefaultTaskSchedulerService, TaskSchedulerService } from "@bitwarden/scheduling"; import { ActiveUserStateProvider, DerivedStateProvider, diff --git a/libs/common/src/platform/scheduling/default-task-scheduler.service.ts b/libs/common/src/platform/scheduling/default-task-scheduler.service.ts index 4de2faec644..be82cbfc0fc 100644 --- a/libs/common/src/platform/scheduling/default-task-scheduler.service.ts +++ b/libs/common/src/platform/scheduling/default-task-scheduler.service.ts @@ -1,97 +1 @@ -import { Subscription } from "rxjs"; - -import { LogService } from "../abstractions/log.service"; -import { ScheduledTaskName } from "../scheduling/scheduled-task-name.enum"; -import { TaskSchedulerService } from "../scheduling/task-scheduler.service"; - -export class DefaultTaskSchedulerService extends TaskSchedulerService { - constructor(protected logService: LogService) { - super(); - - this.taskHandlers = new Map(); - } - - /** - * Sets a timeout and returns the timeout id. - * - * @param taskName - The name of the task. Unused in the base implementation. - * @param delayInMs - The delay in milliseconds. - */ - setTimeout(taskName: ScheduledTaskName, delayInMs: number): Subscription { - this.validateRegisteredTask(taskName); - - const timeoutHandle = globalThis.setTimeout(() => this.triggerTask(taskName), delayInMs); - return new Subscription(() => globalThis.clearTimeout(timeoutHandle)); - } - - /** - * Sets an interval and returns the interval id. - * - * @param taskName - The name of the task. Unused in the base implementation. - * @param intervalInMs - The interval in milliseconds. - * @param _initialDelayInMs - The initial delay in milliseconds. Unused in the base implementation. - */ - setInterval( - taskName: ScheduledTaskName, - intervalInMs: number, - _initialDelayInMs?: number, - ): Subscription { - this.validateRegisteredTask(taskName); - - const intervalHandle = globalThis.setInterval(() => this.triggerTask(taskName), intervalInMs); - - return new Subscription(() => globalThis.clearInterval(intervalHandle)); - } - - /** - * Registers a task handler. - * - * @param taskName - The name of the task. - * @param handler - The task handler. - */ - registerTaskHandler(taskName: ScheduledTaskName, handler: () => void) { - const existingHandler = this.taskHandlers.get(taskName); - if (existingHandler) { - this.logService.warning(`Task handler for ${taskName} already exists. Overwriting.`); - this.unregisterTaskHandler(taskName); - } - - this.taskHandlers.set(taskName, handler); - } - - /** - * Unregisters a task handler. - * - * @param taskName - The name of the task. - */ - unregisterTaskHandler(taskName: ScheduledTaskName) { - this.taskHandlers.delete(taskName); - } - - /** - * Triggers a task. - * - * @param taskName - The name of the task. - * @param _periodInMinutes - The period in minutes. Unused in the base implementation. - */ - protected async triggerTask( - taskName: ScheduledTaskName, - _periodInMinutes?: number, - ): Promise { - const handler = this.taskHandlers.get(taskName); - if (handler) { - handler(); - } - } - - /** - * Validates that a task handler is registered. - * - * @param taskName - The name of the task. - */ - protected validateRegisteredTask(taskName: ScheduledTaskName): void { - if (!this.taskHandlers.has(taskName)) { - throw new Error(`Task handler for ${taskName} not registered. Unable to schedule task.`); - } - } -} +export * from "@bitwarden/scheduling"; diff --git a/libs/common/src/platform/scheduling/index.ts b/libs/common/src/platform/scheduling/index.ts index c9159244ff3..be82cbfc0fc 100644 --- a/libs/common/src/platform/scheduling/index.ts +++ b/libs/common/src/platform/scheduling/index.ts @@ -1,3 +1 @@ -export { TaskSchedulerService, toScheduler } from "./task-scheduler.service"; -export { DefaultTaskSchedulerService } from "./default-task-scheduler.service"; -export { ScheduledTaskNames, ScheduledTaskName } from "./scheduled-task-name.enum"; +export * from "@bitwarden/scheduling"; diff --git a/libs/common/src/platform/scheduling/scheduled-task-name.enum.ts b/libs/common/src/platform/scheduling/scheduled-task-name.enum.ts index 7cc96873748..be82cbfc0fc 100644 --- a/libs/common/src/platform/scheduling/scheduled-task-name.enum.ts +++ b/libs/common/src/platform/scheduling/scheduled-task-name.enum.ts @@ -1,14 +1 @@ -export const ScheduledTaskNames = { - generatePasswordClearClipboardTimeout: "generatePasswordClearClipboardTimeout", - systemClearClipboardTimeout: "systemClearClipboardTimeout", - loginStrategySessionTimeout: "loginStrategySessionTimeout", - notificationsReconnectTimeout: "notificationsReconnectTimeout", - fido2ClientAbortTimeout: "fido2ClientAbortTimeout", - scheduleNextSyncInterval: "scheduleNextSyncInterval", - eventUploadsInterval: "eventUploadsInterval", - vaultTimeoutCheckInterval: "vaultTimeoutCheckInterval", - clearPopupViewCache: "clearPopupViewCache", - phishingDomainUpdate: "phishingDomainUpdate", -} as const; - -export type ScheduledTaskName = (typeof ScheduledTaskNames)[keyof typeof ScheduledTaskNames]; +export * from "@bitwarden/scheduling"; diff --git a/libs/common/src/platform/scheduling/task-scheduler.service.ts b/libs/common/src/platform/scheduling/task-scheduler.service.ts index 3ea80c3ee0a..be82cbfc0fc 100644 --- a/libs/common/src/platform/scheduling/task-scheduler.service.ts +++ b/libs/common/src/platform/scheduling/task-scheduler.service.ts @@ -1,77 +1 @@ -// FIXME: Update this file to be type safe and remove this and next line -// @ts-strict-ignore -import { asyncScheduler, SchedulerLike, Subscription } from "rxjs"; - -import { ScheduledTaskName } from "./scheduled-task-name.enum"; - -/** - * Creates a RXJS scheduler based on a {@link TaskSchedulerService}. - * - * @description This API defers to `TaskSchedulerService` to schedule a task to be ran - * in the future but the task that is ran is NOT the remainder of your RXJS pipeline. The - * task you want ran must instead be registered in a location reachable on a service worker - * startup (on browser). An example of an acceptible location is the constructor of a service - * you know is created in `MainBackground`. Uses of this API in other clients _can_ have the - * `registerTaskHandler` call in more places, but in order to have it work across clients - * it is recommended to register it according to the rules of browser. - * - * @link https://rxjs.dev/guide/scheduler#using-schedulers - * - * @example - * ```ts - * class MyService { - * constructor(messageListener: MessageListener, taskScheduler: TaskSchedulerService) { - * // VERY IMPORTANT! - * this.taskSchedulerService.registerTaskHandler(SchedulerTaskNames.myTaskName, async () => { - * await this.runEvent(); - * }); - * - * messageListener.messages$(MY_MESSAGE).pipe( - * debounceTime( - * 10 * 1000, - * toScheduler(taskScheduler, ShedulerTaskNames.myTaskName), - * ), - * switchMap(() => this.runEvent()), - * ) - * } - * } - * ``` - * - * @param taskScheduler The task scheduler service to use to shedule RXJS work. - * @param taskName The name of the task that the handler should be registered and scheduled based on. - * @returns A SchedulerLike object that can be passed in to RXJS operators like `delay` and `timeout`. - */ -export function toScheduler( - taskScheduler: TaskSchedulerService, - taskName: ScheduledTaskName, -): SchedulerLike { - return new TaskSchedulerSheduler(taskScheduler, taskName); -} - -class TaskSchedulerSheduler implements SchedulerLike { - constructor( - private readonly taskSchedulerService: TaskSchedulerService, - private readonly taskName: ScheduledTaskName, - ) {} - - schedule(work: (state?: T) => void, delay?: number, state?: T): Subscription { - return this.taskSchedulerService.setTimeout(this.taskName, delay ?? 0); - } - - now(): number { - return asyncScheduler.now(); - } -} - -export abstract class TaskSchedulerService { - protected taskHandlers: Map void>; - abstract setTimeout(taskName: ScheduledTaskName, delayInMs: number): Subscription; - abstract setInterval( - taskName: ScheduledTaskName, - intervalInMs: number, - initialDelayInMs?: number, - ): Subscription; - abstract registerTaskHandler(taskName: ScheduledTaskName, handler: () => void): void; - abstract unregisterTaskHandler(taskName: ScheduledTaskName): void; - protected abstract triggerTask(taskName: ScheduledTaskName, periodInMinutes?: number): void; -} +export * from "@bitwarden/scheduling"; diff --git a/libs/scheduling/README.md b/libs/scheduling/README.md new file mode 100644 index 00000000000..c8ba25792b9 --- /dev/null +++ b/libs/scheduling/README.md @@ -0,0 +1,27 @@ +# `@bitwarden/scheduling` + +Owned by: platform + +Background task scheduling infrastructure for Bitwarden clients. + +## Overview + +This library provides the shared abstractions for scheduling recurring and one-shot background tasks across Bitwarden client platforms. It defines a common contract that each platform implements according to its own execution model — for example, browser extensions use `chrome.alarms` because service workers can be killed at any time, while desktop and CLI clients use standard `setTimeout`/`setInterval`. + +## Key Abstractions + +**`TaskSchedulerService`** — The abstract service interface that all scheduling consumers depend on. Platform packages provide their own concrete implementations; nothing in this library should be imported to fulfill this contract at runtime. + +**`DefaultTaskSchedulerService`** — The concrete implementation backed by `globalThis.setTimeout` and `globalThis.setInterval`. This is the scheduler used by the desktop and CLI clients, where a persistent process can be relied upon. + +**`ScheduledTaskName`** — A const object enumerating every named scheduled task in the monorepo (e.g., `loginStrategySessionTimeout`, `vaultTimeoutCheckInterval`, `eventUploadsInterval`). All tasks must be registered here to ensure unique, trackable identifiers across platforms. + +**`toScheduler()`** — A utility that bridges `TaskSchedulerService` to the RxJS `SchedulerLike` interface, enabling use with RxJS operators such as `timer`. + +## Platform Extensions + +Platform-specific scheduler implementations live outside this library in their respective app packages. The browser implementation (`apps/browser/src/_background/services/browser-task-scheduler.service.ts`) is the primary example — it wraps `chrome.alarms` to survive service worker lifecycle events. Adding a new platform scheduler means implementing `TaskSchedulerService` and registering it in that platform's dependency injection setup. + +## Backward Compatibility + +The original source location at `libs/common/src/platform/scheduling/` has been retained as a re-export shim so that existing imports continue to resolve without requiring a bulk migration. New code should import directly from `@bitwarden/scheduling`. diff --git a/libs/scheduling/eslint.config.mjs b/libs/scheduling/eslint.config.mjs new file mode 100644 index 00000000000..9c37d10e3ff --- /dev/null +++ b/libs/scheduling/eslint.config.mjs @@ -0,0 +1,3 @@ +import baseConfig from "../../eslint.config.mjs"; + +export default [...baseConfig]; diff --git a/libs/scheduling/jest.config.js b/libs/scheduling/jest.config.js new file mode 100644 index 00000000000..c2dac1c0ef0 --- /dev/null +++ b/libs/scheduling/jest.config.js @@ -0,0 +1,10 @@ +module.exports = { + displayName: "scheduling", + preset: "../../jest.preset.js", + testEnvironment: "node", + transform: { + "^.+\\.[tj]s$": ["ts-jest", { tsconfig: "/tsconfig.spec.json" }], + }, + moduleFileExtensions: ["ts", "js", "html"], + coverageDirectory: "../../coverage/libs/scheduling", +}; diff --git a/libs/scheduling/package.json b/libs/scheduling/package.json new file mode 100644 index 00000000000..c923601187a --- /dev/null +++ b/libs/scheduling/package.json @@ -0,0 +1,11 @@ +{ + "name": "@bitwarden/scheduling", + "version": "0.0.1", + "description": "Task scheduling domain: enum, abstract service, and default implementation", + "private": true, + "type": "commonjs", + "main": "index.js", + "types": "index.d.ts", + "license": "GPL-3.0", + "author": "platform" +} diff --git a/libs/scheduling/project.json b/libs/scheduling/project.json new file mode 100644 index 00000000000..bb3b8a8194d --- /dev/null +++ b/libs/scheduling/project.json @@ -0,0 +1,34 @@ +{ + "name": "scheduling", + "$schema": "../../node_modules/nx/schemas/project-schema.json", + "sourceRoot": "libs/scheduling/src", + "projectType": "library", + "tags": [], + "targets": { + "build": { + "executor": "@nx/js:tsc", + "outputs": ["{options.outputPath}"], + "options": { + "outputPath": "dist/libs/scheduling", + "main": "libs/scheduling/src/index.ts", + "tsConfig": "libs/scheduling/tsconfig.lib.json", + "assets": ["libs/scheduling/*.md"], + "rootDir": "libs/scheduling/src" + } + }, + "lint": { + "executor": "@nx/eslint:lint", + "outputs": ["{options.outputFile}"], + "options": { + "lintFilePatterns": ["libs/scheduling/**/*.ts"] + } + }, + "test": { + "executor": "@nx/jest:jest", + "outputs": ["{workspaceRoot}/coverage/{projectRoot}"], + "options": { + "jestConfig": "libs/scheduling/jest.config.js" + } + } + } +} diff --git a/libs/common/src/platform/scheduling/default-task-scheduler.service.spec.ts b/libs/scheduling/src/default-task-scheduler.service.spec.ts similarity index 96% rename from libs/common/src/platform/scheduling/default-task-scheduler.service.spec.ts rename to libs/scheduling/src/default-task-scheduler.service.spec.ts index ec66947f0eb..dd5c823cf50 100644 --- a/libs/common/src/platform/scheduling/default-task-scheduler.service.spec.ts +++ b/libs/scheduling/src/default-task-scheduler.service.spec.ts @@ -1,9 +1,9 @@ import { mock, MockProxy } from "jest-mock-extended"; -import { LogService } from "../abstractions/log.service"; -import { ScheduledTaskNames } from "../scheduling/scheduled-task-name.enum"; +import { LogService } from "@bitwarden/logging"; import { DefaultTaskSchedulerService } from "./default-task-scheduler.service"; +import { ScheduledTaskNames } from "./scheduled-task-name.enum"; describe("DefaultTaskSchedulerService", () => { const callback = jest.fn(); diff --git a/libs/scheduling/src/default-task-scheduler.service.ts b/libs/scheduling/src/default-task-scheduler.service.ts new file mode 100644 index 00000000000..6303beb677b --- /dev/null +++ b/libs/scheduling/src/default-task-scheduler.service.ts @@ -0,0 +1,98 @@ +import { Subscription } from "rxjs"; + +import { LogService } from "@bitwarden/logging"; + +import { ScheduledTaskName } from "./scheduled-task-name.enum"; +import { TaskSchedulerService } from "./task-scheduler.service"; + +export class DefaultTaskSchedulerService extends TaskSchedulerService { + constructor(protected logService: LogService) { + super(); + + this.taskHandlers = new Map(); + } + + /** + * Sets a timeout and returns the timeout id. + * + * @param taskName - The name of the task. Unused in the base implementation. + * @param delayInMs - The delay in milliseconds. + */ + setTimeout(taskName: ScheduledTaskName, delayInMs: number): Subscription { + this.validateRegisteredTask(taskName); + + const timeoutHandle = globalThis.setTimeout(() => this.triggerTask(taskName), delayInMs); + return new Subscription(() => globalThis.clearTimeout(timeoutHandle)); + } + + /** + * Sets an interval and returns the interval id. + * + * @param taskName - The name of the task. Unused in the base implementation. + * @param intervalInMs - The interval in milliseconds. + * @param _initialDelayInMs - The initial delay in milliseconds. Unused in the base implementation. + */ + setInterval( + taskName: ScheduledTaskName, + intervalInMs: number, + _initialDelayInMs?: number, + ): Subscription { + this.validateRegisteredTask(taskName); + + const intervalHandle = globalThis.setInterval(() => this.triggerTask(taskName), intervalInMs); + + return new Subscription(() => globalThis.clearInterval(intervalHandle)); + } + + /** + * Registers a task handler. + * + * @param taskName - The name of the task. + * @param handler - The task handler. + */ + registerTaskHandler(taskName: ScheduledTaskName, handler: () => void) { + const existingHandler = this.taskHandlers.get(taskName); + if (existingHandler) { + this.logService.warning(`Task handler for ${taskName} already exists. Overwriting.`); + this.unregisterTaskHandler(taskName); + } + + this.taskHandlers.set(taskName, handler); + } + + /** + * Unregisters a task handler. + * + * @param taskName - The name of the task. + */ + unregisterTaskHandler(taskName: ScheduledTaskName) { + this.taskHandlers.delete(taskName); + } + + /** + * Triggers a task. + * + * @param taskName - The name of the task. + * @param _periodInMinutes - The period in minutes. Unused in the base implementation. + */ + protected async triggerTask( + taskName: ScheduledTaskName, + _periodInMinutes?: number, + ): Promise { + const handler = this.taskHandlers.get(taskName); + if (handler) { + handler(); + } + } + + /** + * Validates that a task handler is registered. + * + * @param taskName - The name of the task. + */ + protected validateRegisteredTask(taskName: ScheduledTaskName): void { + if (!this.taskHandlers.has(taskName)) { + throw new Error(`Task handler for ${taskName} not registered. Unable to schedule task.`); + } + } +} diff --git a/libs/scheduling/src/index.ts b/libs/scheduling/src/index.ts new file mode 100644 index 00000000000..fcdef59e37d --- /dev/null +++ b/libs/scheduling/src/index.ts @@ -0,0 +1,3 @@ +export * from "./scheduled-task-name.enum"; +export * from "./task-scheduler.service"; +export * from "./default-task-scheduler.service"; diff --git a/libs/scheduling/src/scheduled-task-name.enum.ts b/libs/scheduling/src/scheduled-task-name.enum.ts new file mode 100644 index 00000000000..7cc96873748 --- /dev/null +++ b/libs/scheduling/src/scheduled-task-name.enum.ts @@ -0,0 +1,14 @@ +export const ScheduledTaskNames = { + generatePasswordClearClipboardTimeout: "generatePasswordClearClipboardTimeout", + systemClearClipboardTimeout: "systemClearClipboardTimeout", + loginStrategySessionTimeout: "loginStrategySessionTimeout", + notificationsReconnectTimeout: "notificationsReconnectTimeout", + fido2ClientAbortTimeout: "fido2ClientAbortTimeout", + scheduleNextSyncInterval: "scheduleNextSyncInterval", + eventUploadsInterval: "eventUploadsInterval", + vaultTimeoutCheckInterval: "vaultTimeoutCheckInterval", + clearPopupViewCache: "clearPopupViewCache", + phishingDomainUpdate: "phishingDomainUpdate", +} as const; + +export type ScheduledTaskName = (typeof ScheduledTaskNames)[keyof typeof ScheduledTaskNames]; diff --git a/libs/scheduling/src/scheduling.spec.ts b/libs/scheduling/src/scheduling.spec.ts new file mode 100644 index 00000000000..e8681c50c94 --- /dev/null +++ b/libs/scheduling/src/scheduling.spec.ts @@ -0,0 +1,8 @@ +import * as lib from "./index"; + +describe("scheduling", () => { + // This test will fail until something is exported from index.ts + it("should work", () => { + expect(lib).toBeDefined(); + }); +}); diff --git a/libs/scheduling/src/task-scheduler.service.ts b/libs/scheduling/src/task-scheduler.service.ts new file mode 100644 index 00000000000..3ea80c3ee0a --- /dev/null +++ b/libs/scheduling/src/task-scheduler.service.ts @@ -0,0 +1,77 @@ +// FIXME: Update this file to be type safe and remove this and next line +// @ts-strict-ignore +import { asyncScheduler, SchedulerLike, Subscription } from "rxjs"; + +import { ScheduledTaskName } from "./scheduled-task-name.enum"; + +/** + * Creates a RXJS scheduler based on a {@link TaskSchedulerService}. + * + * @description This API defers to `TaskSchedulerService` to schedule a task to be ran + * in the future but the task that is ran is NOT the remainder of your RXJS pipeline. The + * task you want ran must instead be registered in a location reachable on a service worker + * startup (on browser). An example of an acceptible location is the constructor of a service + * you know is created in `MainBackground`. Uses of this API in other clients _can_ have the + * `registerTaskHandler` call in more places, but in order to have it work across clients + * it is recommended to register it according to the rules of browser. + * + * @link https://rxjs.dev/guide/scheduler#using-schedulers + * + * @example + * ```ts + * class MyService { + * constructor(messageListener: MessageListener, taskScheduler: TaskSchedulerService) { + * // VERY IMPORTANT! + * this.taskSchedulerService.registerTaskHandler(SchedulerTaskNames.myTaskName, async () => { + * await this.runEvent(); + * }); + * + * messageListener.messages$(MY_MESSAGE).pipe( + * debounceTime( + * 10 * 1000, + * toScheduler(taskScheduler, ShedulerTaskNames.myTaskName), + * ), + * switchMap(() => this.runEvent()), + * ) + * } + * } + * ``` + * + * @param taskScheduler The task scheduler service to use to shedule RXJS work. + * @param taskName The name of the task that the handler should be registered and scheduled based on. + * @returns A SchedulerLike object that can be passed in to RXJS operators like `delay` and `timeout`. + */ +export function toScheduler( + taskScheduler: TaskSchedulerService, + taskName: ScheduledTaskName, +): SchedulerLike { + return new TaskSchedulerSheduler(taskScheduler, taskName); +} + +class TaskSchedulerSheduler implements SchedulerLike { + constructor( + private readonly taskSchedulerService: TaskSchedulerService, + private readonly taskName: ScheduledTaskName, + ) {} + + schedule(work: (state?: T) => void, delay?: number, state?: T): Subscription { + return this.taskSchedulerService.setTimeout(this.taskName, delay ?? 0); + } + + now(): number { + return asyncScheduler.now(); + } +} + +export abstract class TaskSchedulerService { + protected taskHandlers: Map void>; + abstract setTimeout(taskName: ScheduledTaskName, delayInMs: number): Subscription; + abstract setInterval( + taskName: ScheduledTaskName, + intervalInMs: number, + initialDelayInMs?: number, + ): Subscription; + abstract registerTaskHandler(taskName: ScheduledTaskName, handler: () => void): void; + abstract unregisterTaskHandler(taskName: ScheduledTaskName): void; + protected abstract triggerTask(taskName: ScheduledTaskName, periodInMinutes?: number): void; +} diff --git a/libs/scheduling/tsconfig.eslint.json b/libs/scheduling/tsconfig.eslint.json new file mode 100644 index 00000000000..3daf120441a --- /dev/null +++ b/libs/scheduling/tsconfig.eslint.json @@ -0,0 +1,6 @@ +{ + "extends": "../../tsconfig.base.json", + "files": [], + "include": ["src/**/*.ts", "src/**/*.js"], + "exclude": ["**/build", "**/dist"] +} diff --git a/libs/scheduling/tsconfig.json b/libs/scheduling/tsconfig.json new file mode 100644 index 00000000000..62ebbd94647 --- /dev/null +++ b/libs/scheduling/tsconfig.json @@ -0,0 +1,13 @@ +{ + "extends": "../../tsconfig.base.json", + "files": [], + "include": [], + "references": [ + { + "path": "./tsconfig.lib.json" + }, + { + "path": "./tsconfig.spec.json" + } + ] +} diff --git a/libs/scheduling/tsconfig.lib.json b/libs/scheduling/tsconfig.lib.json new file mode 100644 index 00000000000..9cbf6736007 --- /dev/null +++ b/libs/scheduling/tsconfig.lib.json @@ -0,0 +1,10 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "outDir": "../../dist/out-tsc", + "declaration": true, + "types": ["node"] + }, + "include": ["src/**/*.ts"], + "exclude": ["jest.config.js", "src/**/*.spec.ts"] +} diff --git a/libs/scheduling/tsconfig.spec.json b/libs/scheduling/tsconfig.spec.json new file mode 100644 index 00000000000..1275f148a18 --- /dev/null +++ b/libs/scheduling/tsconfig.spec.json @@ -0,0 +1,10 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "outDir": "../../dist/out-tsc", + "module": "commonjs", + "moduleResolution": "node10", + "types": ["jest", "node"] + }, + "include": ["jest.config.ts", "src/**/*.test.ts", "src/**/*.spec.ts", "src/**/*.d.ts"] +} diff --git a/package-lock.json b/package-lock.json index 260ebd718b0..171ccd0dfcd 100644 --- a/package-lock.json +++ b/package-lock.json @@ -565,6 +565,11 @@ "version": "0.0.0", "license": "GPL-3.0" }, + "libs/scheduling": { + "name": "@bitwarden/scheduling", + "version": "0.0.1", + "license": "GPL-3.0" + }, "libs/serialization": { "name": "@bitwarden/serialization", "version": "0.0.1", @@ -5068,6 +5073,10 @@ "resolved": "libs/pricing", "link": true }, + "node_modules/@bitwarden/scheduling": { + "resolved": "libs/scheduling", + "link": true + }, "node_modules/@bitwarden/sdk-internal": { "version": "0.2.0-main.622", "resolved": "https://registry.npmjs.org/@bitwarden/sdk-internal/-/sdk-internal-0.2.0-main.622.tgz", diff --git a/tsconfig.base.json b/tsconfig.base.json index d310c381304..3aba1a13c7a 100644 --- a/tsconfig.base.json +++ b/tsconfig.base.json @@ -53,6 +53,7 @@ "@bitwarden/platform": ["./libs/platform/src"], "@bitwarden/platform/*": ["./libs/platform/src/*"], "@bitwarden/pricing": ["./libs/pricing/src/index.ts"], + "@bitwarden/scheduling": ["./libs/scheduling/src/index.ts"], "@bitwarden/send-ui": ["./libs/tools/send/send-ui/src"], "@bitwarden/serialization": ["./libs/serialization/src/index.ts"], "@bitwarden/state": ["./libs/state/src/index.ts"],