forked from misskey-dev/misskey
-
Notifications
You must be signed in to change notification settings - Fork 14
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Perform deferred jobs on shutdown (#729)
- Loading branch information
Showing
3 changed files
with
50 additions
and
20 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,24 +1,43 @@ | ||
/* | ||
* SPDX-FileCopyrightText: syuilo and misskey-project | ||
* SPDX-License-Identifier: AGPL-3.0-only | ||
*/ | ||
|
||
type Job<V> = { | ||
value: V; | ||
timer: NodeJS.Timeout; | ||
}; | ||
|
||
export class CollapsedQueue<K, V> { | ||
private jobs: Map<K, V> = new Map(); | ||
private jobs: Map<K, Job<V>> = new Map(); | ||
|
||
constructor( | ||
private timeout: number, | ||
private collapse: (oldValue: V, newValue: V) => V, | ||
private doJob: (key: K, value: V) => void, | ||
) { } | ||
private perform: (key: K, value: V) => Promise<void>, | ||
) {} | ||
|
||
enqueue(key: K, value: V) { | ||
if (this.jobs.has(key)) { | ||
const old = this.jobs.get(key)!; | ||
const merged = this.collapse(old, value); | ||
this.jobs.set(key, merged); | ||
const merged = this.collapse(old.value, value); | ||
this.jobs.set(key, { ...old, value: merged }); | ||
} else { | ||
this.jobs.set(key, value); | ||
setTimeout(() => { | ||
const value = this.jobs.get(key)!; | ||
const timer = setTimeout(() => { | ||
const job = this.jobs.get(key)!; | ||
this.jobs.delete(key); | ||
this.doJob(key, value); | ||
this.perform(key, job.value); | ||
}, this.timeout); | ||
this.jobs.set(key, { value, timer }); | ||
} | ||
} | ||
|
||
async performAllNow() { | ||
const entries = [...this.jobs.entries()]; | ||
this.jobs.clear(); | ||
for (const [_key, job] of entries) { | ||
clearTimeout(job.timer); | ||
} | ||
await Promise.allSettled(entries.map(([key, job]) => this.perform(key, job.value))); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters