signal-desktop/ts/util/StartupQueue.ts

61 lines
1.4 KiB
TypeScript
Raw Normal View History

2021-03-13 01:22:36 +00:00
// Copyright 2021 Signal Messenger, LLC
// SPDX-License-Identifier: AGPL-3.0-only
2021-08-17 00:16:00 +00:00
import * as Errors from '../types/errors';
import * as log from '../logging/log';
2021-03-13 01:22:36 +00:00
2021-08-17 00:16:00 +00:00
type EntryType = Readonly<{
value: number;
callback(): void;
}>;
2021-03-13 01:22:36 +00:00
2023-01-13 00:24:59 +00:00
let startupProcessingQueue: StartupQueue | undefined;
2021-08-17 00:16:00 +00:00
export class StartupQueue {
private readonly map = new Map<string, EntryType>();
2021-03-13 01:22:36 +00:00
2021-08-17 00:16:00 +00:00
public add(id: string, value: number, f: () => void): void {
const existing = this.map.get(id);
if (existing && existing.value >= value) {
2021-03-13 01:22:36 +00:00
return;
}
2021-08-17 00:16:00 +00:00
this.map.set(id, { value, callback: f });
2021-03-13 01:22:36 +00:00
}
2021-08-17 00:16:00 +00:00
public flush(): void {
log.info('StartupQueue: Processing', this.map.size, 'actions');
2021-08-17 00:16:00 +00:00
const values = Array.from(this.map.values());
this.map.clear();
for (const { callback } of values) {
try {
callback();
} catch (error) {
log.error(
2021-08-17 00:16:00 +00:00
'StartupQueue: Failed to process item due to error',
Errors.toLogFormat(error)
);
}
}
2021-03-13 01:22:36 +00:00
}
2023-01-13 00:24:59 +00:00
static initialize(): void {
startupProcessingQueue = new StartupQueue();
}
static isReady(): boolean {
return Boolean(startupProcessingQueue);
}
static add(id: string, value: number, f: () => void): void {
startupProcessingQueue?.add(id, value, f);
}
static flush(): void {
startupProcessingQueue?.flush();
startupProcessingQueue = undefined;
}
2021-03-13 01:22:36 +00:00
}