Signal-Desktop/ts/util/StartupQueue.ts

42 lines
954 B
TypeScript
Raw Permalink 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
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
}
}