-
Notifications
You must be signed in to change notification settings - Fork 40
fix: use worker to prevent timer throttling #1557
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
1daaa7b
fix: use worker to prevent timer throttling
myandrienko 67148d9
prevent memory leak from setTimeout
myandrienko 790c605
fix: typo
myandrienko 0d49d44
Merge branch 'main' into worker-timers
myandrienko 7cad627
Merge branch 'main' into worker-timers
myandrienko e5d605e
Merge branch 'main' into worker-timers
myandrienko 0aefda0
Merge branch 'main' into worker-timers
myandrienko 1e325db
hide behind feature toggle
myandrienko File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or 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 |
|---|---|---|
| @@ -0,0 +1,16 @@ | ||
| #!/usr/bin/env bash | ||
|
|
||
| npx tsc src/timers/worker.ts \ | ||
| --skipLibCheck \ | ||
| --removeComments \ | ||
| --module preserve \ | ||
| --lib ES2020,WebWorker \ | ||
| --outDir worker-dist | ||
|
|
||
| cat <<EOF >src/timers/worker.build.ts | ||
| export const timerWorker = { | ||
| src: \`$(<worker-dist/worker.js)\`, | ||
| }; | ||
| EOF | ||
|
|
||
| rm -r worker-dist |
This file contains hidden or 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 hidden or 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 hidden or 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 hidden or 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 hidden or 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 hidden or 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 |
|---|---|---|
| @@ -0,0 +1,137 @@ | ||
| import { lazy } from '../helpers/lazy'; | ||
| import { getLogger } from '../logger'; | ||
| import { TimerWorkerEvent, TimerWorkerRequest } from './types'; | ||
| import { timerWorker } from './worker.build'; | ||
|
|
||
| class TimerWorker { | ||
| private currentTimerId = 1; | ||
| private callbacks = new Map<number, () => void>(); | ||
| private worker: Worker | undefined; | ||
| private fallback = false; | ||
|
|
||
| setup({ useTimerWorker = true }: { useTimerWorker?: boolean } = {}): void { | ||
| if (!useTimerWorker) { | ||
| this.fallback = true; | ||
| return; | ||
| } | ||
|
|
||
| try { | ||
| const source = timerWorker.src; | ||
| const blob = new Blob([source], { | ||
| type: 'application/javascript; charset=utf-8', | ||
| }); | ||
| const script = URL.createObjectURL(blob); | ||
| this.worker = new Worker(script, { name: 'str-timer-worker' }); | ||
| this.worker.addEventListener('message', (event) => { | ||
| const { type, id } = event.data as TimerWorkerEvent; | ||
| if (type === 'tick') { | ||
| this.callbacks.get(id)?.(); | ||
| } | ||
| }); | ||
| } catch (err: any) { | ||
| getLogger(['timer-worker'])('error', err); | ||
| this.fallback = true; | ||
| } | ||
| } | ||
|
|
||
| destroy(): void { | ||
| this.callbacks.clear(); | ||
| this.worker?.terminate(); | ||
| this.worker = undefined; | ||
| this.fallback = false; | ||
| } | ||
|
|
||
| get ready() { | ||
| return this.fallback || Boolean(this.worker); | ||
| } | ||
|
|
||
| setInterval(callback: () => void, timeout: number): number { | ||
| return this.setTimer('setInterval', callback, timeout); | ||
| } | ||
|
|
||
| clearInterval(id?: number): void { | ||
| this.clearTimer('clearInterval', id); | ||
| } | ||
|
|
||
| setTimeout(callback: () => void, timeout: number): number { | ||
| return this.setTimer('setTimeout', callback, timeout); | ||
| } | ||
|
|
||
| clearTimeout(id?: number): void { | ||
| this.clearTimer('clearTimeout', id); | ||
| } | ||
|
|
||
| private setTimer( | ||
| type: 'setTimeout' | 'setInterval', | ||
| callback: () => void, | ||
| timeout: number, | ||
| ) { | ||
| if (!this.ready) { | ||
| this.setup(); | ||
| } | ||
|
|
||
| if (this.fallback) { | ||
| return (type === 'setTimeout' ? setTimeout : setInterval)( | ||
| callback, | ||
| timeout, | ||
| ) as unknown as number; | ||
| } | ||
|
|
||
| const id = this.getTimerId(); | ||
|
|
||
| this.callbacks.set(id, () => { | ||
| callback(); | ||
|
|
||
| // Timeouts are one-off operations, so no need to keep callback reference | ||
| // after timer has fired | ||
| if (type === 'setTimeout') { | ||
| this.callbacks.delete(id); | ||
| } | ||
| }); | ||
|
|
||
| this.sendMessage({ type, id, timeout }); | ||
| return id; | ||
| } | ||
|
|
||
| private clearTimer(type: 'clearTimeout' | 'clearInterval', id?: number) { | ||
| if (!id) { | ||
| return; | ||
| } | ||
|
|
||
| if (!this.ready) { | ||
| this.setup(); | ||
| } | ||
|
|
||
| if (this.fallback) { | ||
| (type === 'clearTimeout' ? clearTimeout : clearInterval)(id); | ||
| return; | ||
| } | ||
|
|
||
| this.callbacks.delete(id); | ||
| this.sendMessage({ type, id }); | ||
| } | ||
|
|
||
| private getTimerId() { | ||
| return this.currentTimerId++; | ||
| } | ||
|
|
||
| private sendMessage(message: TimerWorkerRequest) { | ||
| if (!this.worker) { | ||
| throw new Error("Cannot use timer worker before it's set up"); | ||
| } | ||
|
|
||
| this.worker.postMessage(message); | ||
| } | ||
| } | ||
|
|
||
| let timerWorkerEnabled = false; | ||
|
|
||
| export const enableTimerWorker = () => { | ||
| timerWorkerEnabled = true; | ||
| }; | ||
|
|
||
| export const getTimers = lazy(() => { | ||
| const instance = new TimerWorker(); | ||
| instance.setup({ useTimerWorker: timerWorkerEnabled }); | ||
| return instance; | ||
| }); |
This file contains hidden or 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 |
|---|---|---|
| @@ -0,0 +1,15 @@ | ||
| export type TimerWorkerRequest = | ||
| | { | ||
| type: 'setInterval' | 'setTimeout'; | ||
| id: number; | ||
| timeout: number; | ||
| } | ||
| | { | ||
| type: 'clearInterval' | 'clearTimeout'; | ||
| id: number; | ||
| }; | ||
|
|
||
| export type TimerWorkerEvent = { | ||
| type: 'tick'; | ||
| id: number; | ||
| }; |
This file contains hidden or 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 |
|---|---|---|
| @@ -0,0 +1,9 @@ | ||
| // Do not modify this file manually. You can edit worker.ts if necessary | ||
| // and the run ./generate-timer-worker.sh | ||
| export const timerWorker = { | ||
| get src(): string { | ||
| throw new Error( | ||
| 'Timer worker source missing. Did you forget to run generate-timer-worker.sh?', | ||
| ); | ||
| }, | ||
| }; |
This file contains hidden or 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 |
|---|---|---|
| @@ -0,0 +1,40 @@ | ||
| /* eslint-disable */ | ||
|
|
||
| import type { TimerWorkerEvent, TimerWorkerRequest } from './types'; | ||
|
|
||
| const timerIdMapping = new Map<number, NodeJS.Timeout>(); | ||
|
|
||
| self.addEventListener('message', (event: MessageEvent) => { | ||
| const request = event.data as TimerWorkerRequest; | ||
|
|
||
| switch (request.type) { | ||
| case 'setTimeout': | ||
| case 'setInterval': | ||
| timerIdMapping.set( | ||
| request.id, | ||
| (request.type === 'setTimeout' ? setTimeout : setInterval)(() => { | ||
| tick(request.id); | ||
|
|
||
| if (request.type === 'setTimeout') { | ||
| timerIdMapping.delete(request.id); | ||
| } | ||
| }, request.timeout), | ||
| ); | ||
| break; | ||
|
|
||
| case 'clearTimeout': | ||
| case 'clearInterval': | ||
| (request.type === 'clearTimeout' ? clearTimeout : clearInterval)( | ||
| timerIdMapping.get(request.id), | ||
| ); | ||
| timerIdMapping.delete(request.id); | ||
| break; | ||
| } | ||
| }); | ||
|
|
||
| function tick(id: number) { | ||
| const message: TimerWorkerEvent = { type: 'tick', id }; | ||
| self.postMessage(message); | ||
| } | ||
|
|
||
| /* eslint-enable */ |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Feature toggle