refactor(scheduling): extract @bitwarden/scheduling Nx leaf library (#19771)

This commit is contained in:
Addison Beck
2026-03-27 07:23:22 -04:00
committed by GitHub
parent cd692bcf5b
commit 02fe70eaeb
25 changed files with 344 additions and 198 deletions

1
.github/CODEOWNERS vendored
View File

@@ -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

View File

@@ -1 +1 @@
scripts
scripts

View File

@@ -63,6 +63,7 @@ module.exports = {
"<rootDir>/libs/subscription/jest.config.js",
"<rootDir>/libs/unlock/jest.config.js",
"<rootDir>/libs/user-crypto-management/jest.config.js",
"<rootDir>/libs/scheduling/jest.config.js",
],
// Workaround for a memory leak that crashes tests in CI:

View File

@@ -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,

View File

@@ -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<void> {
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";

View File

@@ -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";

View File

@@ -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";

View File

@@ -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<T>(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<string, () => 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";

27
libs/scheduling/README.md Normal file
View File

@@ -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`.

View File

@@ -0,0 +1,3 @@
import baseConfig from "../../eslint.config.mjs";
export default [...baseConfig];

View File

@@ -0,0 +1,10 @@
module.exports = {
displayName: "scheduling",
preset: "../../jest.preset.js",
testEnvironment: "node",
transform: {
"^.+\\.[tj]s$": ["ts-jest", { tsconfig: "<rootDir>/tsconfig.spec.json" }],
},
moduleFileExtensions: ["ts", "js", "html"],
coverageDirectory: "../../coverage/libs/scheduling",
};

View File

@@ -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"
}

View File

@@ -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"
}
}
}
}

View File

@@ -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();

View File

@@ -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<void> {
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.`);
}
}
}

View File

@@ -0,0 +1,3 @@
export * from "./scheduled-task-name.enum";
export * from "./task-scheduler.service";
export * from "./default-task-scheduler.service";

View File

@@ -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];

View File

@@ -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();
});
});

View File

@@ -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<T>(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<string, () => 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;
}

View File

@@ -0,0 +1,6 @@
{
"extends": "../../tsconfig.base.json",
"files": [],
"include": ["src/**/*.ts", "src/**/*.js"],
"exclude": ["**/build", "**/dist"]
}

View File

@@ -0,0 +1,13 @@
{
"extends": "../../tsconfig.base.json",
"files": [],
"include": [],
"references": [
{
"path": "./tsconfig.lib.json"
},
{
"path": "./tsconfig.spec.json"
}
]
}

View File

@@ -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"]
}

View File

@@ -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"]
}

9
package-lock.json generated
View File

@@ -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",

View File

@@ -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"],