-
Notifications
You must be signed in to change notification settings - Fork 5
/
Scheduler.ts
523 lines (444 loc) · 15.3 KB
/
Scheduler.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
import { Task, TaskStatus, Timestamp } from "./Task"
import { pullAt, findIndex, defaults } from "lodash"
import { performance } from 'perf_hooks'
const PriorityQueue = require("fastpriorityqueue")
/**
* returns the current relative time, since the start of the webpage / script, in ms
* @returns the current relative time in ms
*/
export function getCurrentTimestamp(): number {
return Number(typeof window === 'undefined' ? performance.now() : window.performance.now())
}
export interface SchedulerConfig {
numOfTicksBeforeReschedule: number, // Number of preemption points before task yields
meanTimeToReschedule: number, // Miliseconds before rescheduling is done
meanTimeToYield: number, // Miliseconds before we return to the main loop
debug: boolean,
policy: string, // Fixed Priority (FP) || Earliest Deadline First (EDF)
onRequestAnimationFrame: boolean
}
export const DEFAULT_SCHEDULER_CONFIG: Readonly<SchedulerConfig> = Object.freeze({
numOfTicksBeforeReschedule: 300,
meanTimeToReschedule: 1,
meanTimeToYield: 5,
debug: false,
policy: 'FP',
// If there are no animation frames, it does not make sense to
// request them. This normally means that we do not run in a browser.
onRequestAnimationFrame: !(typeof requestAnimationFrame === 'undefined')
})
export enum SchedulerMessage {
TerminateTask,
Continue
}
export class TaskState {
/**
* the enveloped task structure
*/
task: Task
lastMessage: SchedulerMessage | Promise<any> | undefined
/**
* the generator function of the task
*/
iterator: IterableIterator<SchedulerMessage | Promise<any>>
lastAsyncRespose: any | undefined
/**
* the time at which the task was enqueued, for accouting
*/
enqueuedTime: Timestamp
/**
* the time the task has run, for accounting
*/
elapsedTime: number = 0
/**
* the number of ticks that this task was executed
*/
elapsedTicks: number = 0
/**
* return value of the task after it has finished
*/
retval: any = null
/**
* whether or not the task has finished running
*/
completed = false
parent?: TaskState
/**
* The absolute deadline of this task instance
*/
absoluteDeadline: Timestamp
get status(): TaskStatus {
return this.task.status
}
set status(s: TaskStatus) {
this.task.status = s
}
get priority(): number {
return this.task.priority
}
get isRunnable(): boolean {
return this.task.status === TaskStatus.Runnable
}
get isWaiting(): boolean {
return this.task.status == TaskStatus.Waiting
}
/**
* call the generator function of the task again
*/
next(input: any = undefined): SchedulerMessage | Promise<any> {
if (this.completed) {
return SchedulerMessage.TerminateTask
}
let n = this.iterator.next(input || this.lastAsyncRespose)
if ( n.done == true ) {
this.completed = true;
} else {
this.completed = false;
}
this.lastMessage = n.value
this.lastAsyncRespose = undefined
return this.lastMessage!
}
/**
* set up the structure
* @param task the task to envelop
* @param parent the parent structure
*/
constructor(task: Task, parent?: TaskState) {
this.task = task
this.iterator = task.run()
this.enqueuedTime = getCurrentTimestamp()
this.parent = parent
if (parent) {
this.absoluteDeadline = parent.absoluteDeadline
} else {
this.absoluteDeadline = task.creationTime + task.deadline
}
}
/**
* update the times of the task and call onTermined()
*/
terminate() {
this.task.retval = this.retval
this.task.enqueuedTime = this.enqueuedTime
this.task.elapsedTime = this.elapsedTime
this.task.endTime = getCurrentTimestamp()
this.task.onTerminated()
}
/**
* convert task to a human readable string
*/
toString() {
return `${this.task.name} (priority: ${this.task.priority}, deadline: ${this.absoluteDeadline}): ${this.task.status} (${this.elapsedTime}ms)`
}
}
export class TimeoutState {
/**
* Holds information an alarm state
*/
timeout: number
callback: () => void // Called from scheduler loop
js_timeout: any
js_callback: () => void // called via Javascript event loop
}
/**
* abstract scheduler class, interface for concrete deadline and fixed priority schedulers
*/
export abstract class Scheduler {
/**
* the currently running task
*/
currentTask?: TaskState
/**
* number of pauses of the scheduler, may be used nestedly
*/
private pauses: boolean = true
get paused(): boolean { return this.pauses }
/**
* mostly constant configuration options for the scheduler
*/
config: SchedulerConfig
/**
* How long was the scheduler active on the executor
*/
schedulerTime: number = 0
/**
* Number of preemption points that are visited before thread must actually call yield
*/
RTJS_BUDGET: number
/**
* This flag forces the scheduler to reschedule immediately,
* before finishing the current timeslice.
*/
protected forceReschedule: boolean
printTimes: boolean
/**
* Timeout queue to manage more precise timeouts
*/
private timeoutQueue: PriorityQueue<TimeoutState> = new PriorityQueue((a: TimeoutState, b: TimeoutState) => {
return b.timeout > a.timeout
})
/**
* Flag indicates a non-preemptive critical section
*/
NPCS: boolean
/**
* constructor, setting up a scheduler object
* @param config set to DEFAULT_SCHEDULER_CONFIG, may use any other values
*/
constructor(config: Object = DEFAULT_SCHEDULER_CONFIG) {
this.config = defaults({}, config, DEFAULT_SCHEDULER_CONFIG)
}
/**
* print messages to stdout if the ''debug'' flag was set
*/
protected debug(msg: any, ...optionalParams: any[]) {
if (this.config.debug) {
console.error(msg, ...optionalParams)
}
}
/**
* pauses the scheduler, may be used nestedly
*/
pause() {
this.pauses = true
this.debug("> Pausing Scheduler (pauses %i)", this.pauses)
}
/**
* resumes the scheduler after pausing, may be used nestedly
*/
resume() {
if (this.pauses) {
this.pauses = false
this.debug("> Resuming Scheduler (pauses %i)", this.pauses)
this.repostMe();
}
}
/**
* re-introduces the scheduler itself to the event loop
*/
repostMe() {
//if ( this.config.onRequestAnimationFrame ) {
// requestAnimationFrame ( this.executeRound.bind( this ) )
//} else {
if (!this.pauses) {
setImmediate(this.executeRound.bind(this))
}
//}
}
/**
* Add a single-short or periodic alarm function.
* @param fn - The function to be callled after the delay has passed
* @param delay - The deay in miliseconds
* @param periodic - Whether the alarm is enqueued again
*
*/
addAlarm(fn: () => void, delay: number, periodic: boolean = false) {
let scheduler = this
let ts = new TimeoutState()
ts.timeout = 0
function startTimeout() {
// If we were triggered too late for the next activation,
// we use the current time as the next starting point
let now = getCurrentTimestamp()
if (now > (ts.timeout + delay)) {
ts.timeout = now
}
ts.timeout += delay // trigger at the exact next timeout time
scheduler.timeoutQueue.add(ts)
ts.js_timeout = setTimeout(ts.js_callback, ts.timeout - now)
}
// Setup the Javascript Timeout
ts.js_callback = () => {
scheduler.timeoutQueue.removeOne(t => t == ts)
if (periodic) { startTimeout() }
fn()
}
// Setup the bAUTOSAR timeout. This is called from the scheduler
ts.callback = () => {
clearTimeout(ts.js_timeout)
if (periodic) { startTimeout() }
fn()
}
// Start the timeout for the first time
startTimeout()
return ts
}
/**
* add a task to the queue of the scheduler, sends a scheduler-message to event queue after it is finished, if no task is running atm
* @param task the task object to enqueue
* @param parent optional parameter, scheduler-structure for the parent task if any
*/
addTask(task: Task, parent?: TaskState) {
this.debug("> Adding Task %s with priority %i and deadline %i", task.name, task.priority, task.deadline)
task.scheduler = this
this.enqueueTask(new TaskState(task, parent))
this.resume()
/*if (this.currentTask === undefined && !this.paused) {
this.repostMe()
}*/
}
/**
* Used by tasks to spawn new tasks, sets the currently running one as the parent
* @param task the child task
*/
spawnTask(task: Task) {
if (this.currentTask) {
this.currentTask.status = TaskStatus.Waiting
task.parent = this.currentTask.task
}
this.addTask(task, this.currentTask)
}
/**
* enqueue a task into the queue of the scheduler (implementation dependent)
*/
abstract enqueueTask(task: TaskState): void
/**
* @returns the number of elements in the task queue
*/
abstract get numberOfTasks(): number
/**
* @returns the next task to schedule
*/
protected abstract getNextTask(): TaskState | undefined
/**
* empties the task queue
*/
abstract emptyTaskQueue(): void
/**
* determines whether a reschedule needs to take place
*/
protected abstract needsReschedule(): boolean
/**
* swaps the currently running task with a new one, uses needsReschedule()
*/
protected prepareNextTask() {
if (this.paused) { return }
if (this.NPCS && this.currentTask) { return } // Obey the non-preemptive critical section
// if the currently running task is not runnable or not completed it is re-enqueued for the scheduler to consider
if (this.currentTask && (!this.currentTask.isRunnable || !this.currentTask.completed)) {
this.debug("> Reenqueuing Task %s", this.currentTask.toString())
this.enqueueTask(this.currentTask)
}
// determine next task
this.currentTask = this.getNextTask()
// Rescheduling done, clear flag
this.forceReschedule = false
// all tasks are executed correctly
if (!this.currentTask) {
if (this.numberOfTasks === 0) {
this.debug("> All out of tasks, calling isDone handler")
//this.isDone()
this.pause()
}
return
}
this.debug("> Reschedule to: %s", this.currentTask.toString())
}
/**
* Execute the current thread for a single timelice
*/
protected executeTimelice() {
if (!this.currentTask) { return }
let __step_start: number = getCurrentTimestamp()
let __start: number
let __end: number = __step_start
let taskProgress: number = 0
do {
if (this.paused || this.currentTask.status !== TaskStatus.Runnable) {
break
}
/* If a component requests that we reschedule immediately, we will obey! */
if (this.forceReschedule) {
break;
}
/** We run the current task for one budget (RTJS_BUDGET). The task can hit
* introduced preemption points that often, before it actually calls yield */
if (this.currentTask.task.budget > -1) {
this.RTJS_BUDGET = this.currentTask.task.budget;
} else {
this.RTJS_BUDGET = this.config.numOfTicksBeforeReschedule
}
__start = getCurrentTimestamp()
let msg = this.currentTask.next() /* Execute! */
__end = getCurrentTimestamp()
/* We account for the elapsed time */
taskProgress += __end - __start
this.currentTask.elapsedTime += __end - __start
this.currentTask.elapsedTicks += 1
/* Process the message from the thread. */
if (msg instanceof Promise) {
let taskStatus = this.currentTask
taskStatus.status = TaskStatus.Waiting
msg.then(result => {
taskStatus.lastAsyncRespose = result
taskStatus.status = TaskStatus.Runnable
if (!this.currentTask) {
this.repostMe();
}
})
break
} else if (msg === SchedulerMessage.TerminateTask || this.currentTask.completed) {
if (!(msg === SchedulerMessage.TerminateTask)) {
this.currentTask.retval = msg;
}
this.terminateTask()
break
}
}
while ((__end - __step_start) < this.config.meanTimeToReschedule);
// Poll the timeout queue
do {
let el = this.timeoutQueue.peek()
if (!el) { break }
// Next timeout is more than 1 milisecond away
if ((el.timeout - __end) > 1) { break } // FIXME: Timeout granularity
this.timeoutQueue.poll() // remove el
el.callback()
} while (true)
this.debug("Scheduler Timeslice: %d ms/%d ms", (__end - __step_start), taskProgress)
}
/**
* terminates the currently running task
*/
private terminateTask() {
if (!this.currentTask) return;
this.debug(
"> TerminateTask: Task %s with priority %i (time: %i ms)",
this.currentTask.task.name,
this.currentTask.priority,
this.currentTask.elapsedTime
)
if (this.currentTask.parent) {
this.currentTask.parent.lastAsyncRespose = this.currentTask.lastMessage
this.currentTask.parent.status = TaskStatus.Runnable
}
this.currentTask.terminate()
this.forceReschedule = true
this.NPCS = false
this.currentTask = undefined
}
/**
* if the scheduler is not paused, and there are still tasks left, run
* the scheduler for meanTimeToYield miliseconds
*/
private executeRound() {
let __round_start = getCurrentTimestamp()
let __round_end = __round_start
do {
if (this.paused) { break }
if (this.forceReschedule || this.needsReschedule()) { this.prepareNextTask() }
if (!this.currentTask) { break }
if (this.currentTask.status == TaskStatus.Runnable) {
this.executeTimelice()
} else {
break;
}
__round_end = getCurrentTimestamp()
} while ((__round_end - __round_start) < this.config.meanTimeToYield)
this.debug("Scheduler Round: %d ms");
this.schedulerTime += __round_end - __round_start
// Yield to the mainloop
this.repostMe()
}
}