-
Notifications
You must be signed in to change notification settings - Fork 12k
/
Copy pathsimple-scheduler.ts
548 lines (491 loc) · 16.3 KB
/
simple-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
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import { JsonValue, schema } from '@angular-devkit/core';
import {
EMPTY,
MonoTypeOperatorFunction,
Observable,
Observer,
Subject,
Subscription,
concat,
concatMap,
filter,
first,
from,
ignoreElements,
map,
merge,
of,
shareReplay,
switchMap,
tap,
} from 'rxjs';
import {
Job,
JobDescription,
JobHandler,
JobInboundMessage,
JobInboundMessageKind,
JobName,
JobOutboundMessage,
JobOutboundMessageKind,
JobOutboundMessageOutput,
JobState,
Registry,
ScheduleJobOptions,
Scheduler,
} from './api';
import { JobDoesNotExistException } from './exception';
export class JobArgumentSchemaValidationError extends schema.SchemaValidationException {
constructor(errors?: schema.SchemaValidatorError[]) {
super(errors, 'Job Argument failed to validate. Errors: ');
}
}
export class JobInboundMessageSchemaValidationError extends schema.SchemaValidationException {
constructor(errors?: schema.SchemaValidatorError[]) {
super(errors, 'Job Inbound Message failed to validate. Errors: ');
}
}
export class JobOutputSchemaValidationError extends schema.SchemaValidationException {
constructor(errors?: schema.SchemaValidatorError[]) {
super(errors, 'Job Output failed to validate. Errors: ');
}
}
interface JobHandlerWithExtra extends JobHandler<JsonValue, JsonValue, JsonValue> {
jobDescription: JobDescription;
argumentV: Promise<schema.SchemaValidator>;
outputV: Promise<schema.SchemaValidator>;
inputV: Promise<schema.SchemaValidator>;
}
function _jobShare<T>(): MonoTypeOperatorFunction<T> {
// This is the same code as a `shareReplay()` operator, but uses a dumber Subject rather than a
// ReplaySubject.
return (source: Observable<T>): Observable<T> => {
let refCount = 0;
let subject: Subject<T>;
let hasError = false;
let isComplete = false;
let subscription: Subscription;
return new Observable<T>((subscriber) => {
let innerSub: Subscription;
refCount++;
if (!subject) {
subject = new Subject<T>();
innerSub = subject.subscribe(subscriber);
subscription = source.subscribe({
next(value) {
subject.next(value);
},
error(err) {
hasError = true;
subject.error(err);
},
complete() {
isComplete = true;
subject.complete();
},
});
} else {
innerSub = subject.subscribe(subscriber);
}
return () => {
refCount--;
innerSub.unsubscribe();
if (subscription && refCount === 0 && (isComplete || hasError)) {
subscription.unsubscribe();
}
};
});
};
}
/**
* Simple scheduler. Should be the base of all registries and schedulers.
*/
export class SimpleScheduler<
MinimumArgumentT extends JsonValue = JsonValue,
MinimumInputT extends JsonValue = JsonValue,
MinimumOutputT extends JsonValue = JsonValue,
> implements Scheduler<MinimumArgumentT, MinimumInputT, MinimumOutputT>
{
private _internalJobDescriptionMap = new Map<JobName, JobHandlerWithExtra>();
private _queue: (() => void)[] = [];
private _pauseCounter = 0;
constructor(
protected _jobRegistry: Registry<MinimumArgumentT, MinimumInputT, MinimumOutputT>,
protected _schemaRegistry: schema.SchemaRegistry = new schema.CoreSchemaRegistry(),
) {}
private _getInternalDescription(name: JobName): Observable<JobHandlerWithExtra | null> {
const maybeHandler = this._internalJobDescriptionMap.get(name);
if (maybeHandler !== undefined) {
return of(maybeHandler);
}
const handler = this._jobRegistry.get<MinimumArgumentT, MinimumInputT, MinimumOutputT>(name);
return handler.pipe(
switchMap((handler) => {
if (handler === null) {
return of(null);
}
const description: JobDescription = {
// Make a copy of it to be sure it's proper JSON.
...(JSON.parse(JSON.stringify(handler.jobDescription)) as JobDescription),
name: handler.jobDescription.name || name,
argument: handler.jobDescription.argument || true,
input: handler.jobDescription.input || true,
output: handler.jobDescription.output || true,
channels: handler.jobDescription.channels || {},
};
const handlerWithExtra = Object.assign(handler.bind(undefined), {
jobDescription: description,
argumentV: this._schemaRegistry.compile(description.argument),
inputV: this._schemaRegistry.compile(description.input),
outputV: this._schemaRegistry.compile(description.output),
}) as JobHandlerWithExtra;
this._internalJobDescriptionMap.set(name, handlerWithExtra);
return of(handlerWithExtra);
}),
);
}
/**
* Get a job description for a named job.
*
* @param name The name of the job.
* @returns A description, or null if the job is not registered.
*/
getDescription(name: JobName) {
return concat(
this._getInternalDescription(name).pipe(map((x) => x && x.jobDescription)),
of(null),
).pipe(first());
}
/**
* Returns true if the job name has been registered.
* @param name The name of the job.
* @returns True if the job exists, false otherwise.
*/
has(name: JobName) {
return this.getDescription(name).pipe(map((x) => x !== null));
}
/**
* Pause the scheduler, temporary queueing _new_ jobs. Returns a resume function that should be
* used to resume execution. If multiple `pause()` were called, all their resume functions must
* be called before the Scheduler actually starts new jobs. Additional calls to the same resume
* function will have no effect.
*
* Jobs already running are NOT paused. This is pausing the scheduler only.
*/
pause() {
let called = false;
this._pauseCounter++;
return () => {
if (!called) {
called = true;
if (--this._pauseCounter == 0) {
// Resume the queue.
const q = this._queue;
this._queue = [];
q.forEach((fn) => fn());
}
}
};
}
/**
* Schedule a job to be run, using its name.
* @param name The name of job to be run.
* @param argument The argument to send to the job when starting it.
* @param options Scheduling options.
* @returns The Job being run.
*/
schedule<A extends MinimumArgumentT, I extends MinimumInputT, O extends MinimumOutputT>(
name: JobName,
argument: A,
options?: ScheduleJobOptions,
): Job<A, I, O> {
if (this._pauseCounter > 0) {
const waitable = new Subject<never>();
this._queue.push(() => waitable.complete());
return this._scheduleJob<A, I, O>(name, argument, options || {}, waitable);
}
return this._scheduleJob<A, I, O>(name, argument, options || {}, EMPTY);
}
/**
* Filter messages.
* @private
*/
private _filterJobOutboundMessages<O extends MinimumOutputT>(
message: JobOutboundMessage<O>,
state: JobState,
) {
switch (message.kind) {
case JobOutboundMessageKind.OnReady:
return state == JobState.Queued;
case JobOutboundMessageKind.Start:
return state == JobState.Ready;
case JobOutboundMessageKind.End:
return state == JobState.Started || state == JobState.Ready;
}
return true;
}
/**
* Return a new state. This is just to simplify the reading of the _createJob method.
* @private
*/
private _updateState<O extends MinimumOutputT>(
message: JobOutboundMessage<O>,
state: JobState,
): JobState {
switch (message.kind) {
case JobOutboundMessageKind.OnReady:
return JobState.Ready;
case JobOutboundMessageKind.Start:
return JobState.Started;
case JobOutboundMessageKind.End:
return JobState.Ended;
}
return state;
}
/**
* Create the job.
* @private
*/
// eslint-disable-next-line max-lines-per-function
private _createJob<A extends MinimumArgumentT, I extends MinimumInputT, O extends MinimumOutputT>(
name: JobName,
argument: A,
handler: Observable<JobHandlerWithExtra | null>,
inboundBus: Observer<JobInboundMessage<I>>,
outboundBus: Observable<JobOutboundMessage<O>>,
): Job<A, I, O> {
const schemaRegistry = this._schemaRegistry;
const channelsSubject = new Map<string, Subject<JsonValue>>();
const channels = new Map<string, Observable<JsonValue>>();
let state = JobState.Queued;
let pingId = 0;
// Create the input channel by having a filter.
const input = new Subject<JsonValue>();
input
.pipe(
concatMap((message) =>
handler.pipe(
switchMap(async (handler) => {
if (handler === null) {
throw new JobDoesNotExistException(name);
}
const validator = await handler.inputV;
return validator(message);
}),
),
),
filter((result) => result.success),
map((result) => result.data as I),
)
.subscribe((value) => inboundBus.next({ kind: JobInboundMessageKind.Input, value }));
outboundBus = concat(
outboundBus,
// Add an End message at completion. This will be filtered out if the job actually send an
// End.
handler.pipe(
switchMap((handler) => {
if (handler) {
return of<JobOutboundMessage<O>>({
kind: JobOutboundMessageKind.End,
description: handler.jobDescription,
});
} else {
return EMPTY as Observable<JobOutboundMessage<O>>;
}
}),
),
).pipe(
filter((message) => this._filterJobOutboundMessages(message, state)),
// Update internal logic and Job<> members.
tap(
(message) => {
// Update the state.
state = this._updateState(message, state);
switch (message.kind) {
case JobOutboundMessageKind.ChannelCreate: {
const maybeSubject = channelsSubject.get(message.name);
// If it doesn't exist or it's closed on the other end.
if (!maybeSubject) {
const s = new Subject<JsonValue>();
channelsSubject.set(message.name, s);
channels.set(message.name, s.asObservable());
}
break;
}
case JobOutboundMessageKind.ChannelMessage: {
const maybeSubject = channelsSubject.get(message.name);
if (maybeSubject) {
maybeSubject.next(message.message);
}
break;
}
case JobOutboundMessageKind.ChannelComplete: {
const maybeSubject = channelsSubject.get(message.name);
if (maybeSubject) {
maybeSubject.complete();
channelsSubject.delete(message.name);
}
break;
}
case JobOutboundMessageKind.ChannelError: {
const maybeSubject = channelsSubject.get(message.name);
if (maybeSubject) {
maybeSubject.error(message.error);
channelsSubject.delete(message.name);
}
break;
}
}
},
() => {
state = JobState.Errored;
},
),
// Do output validation (might include default values so this might have side
// effects). We keep all messages in order.
concatMap((message) => {
if (message.kind !== JobOutboundMessageKind.Output) {
return of(message);
}
return handler.pipe(
switchMap(async (handler) => {
if (handler === null) {
throw new JobDoesNotExistException(name);
}
const validate = await handler.outputV;
const output = await validate(message.value);
if (!output.success) {
throw new JobOutputSchemaValidationError(output.errors);
}
return {
...message,
output: output.data as O,
} as JobOutboundMessageOutput<O>;
}),
) as Observable<JobOutboundMessage<O>>;
}),
_jobShare(),
);
const output = outboundBus.pipe(
filter((x) => x.kind == JobOutboundMessageKind.Output),
map((x) => x.value),
shareReplay(1),
);
// Return the Job.
return {
get state() {
return state;
},
argument,
description: handler.pipe(
switchMap((handler) => {
if (handler === null) {
throw new JobDoesNotExistException(name);
} else {
return of(handler.jobDescription);
}
}),
),
output,
getChannel<T extends JsonValue>(
name: JobName,
schema: schema.JsonSchema = true,
): Observable<T> {
let maybeObservable = channels.get(name);
if (!maybeObservable) {
const s = new Subject<T>();
channelsSubject.set(name, s as unknown as Subject<JsonValue>);
channels.set(name, s.asObservable());
maybeObservable = s.asObservable();
}
return maybeObservable.pipe(
// Keep the order of messages.
concatMap((message) => {
return from(schemaRegistry.compile(schema)).pipe(
switchMap((validate) => validate(message)),
filter((x) => x.success),
map((x) => x.data as T),
);
}),
);
},
ping() {
const id = pingId++;
inboundBus.next({ kind: JobInboundMessageKind.Ping, id });
return outboundBus.pipe(
filter((x) => x.kind === JobOutboundMessageKind.Pong && x.id == id),
first(),
ignoreElements(),
);
},
stop() {
inboundBus.next({ kind: JobInboundMessageKind.Stop });
},
input,
inboundBus,
outboundBus,
};
}
protected _scheduleJob<
A extends MinimumArgumentT,
I extends MinimumInputT,
O extends MinimumOutputT,
>(
name: JobName,
argument: A,
options: ScheduleJobOptions,
waitable: Observable<never>,
): Job<A, I, O> {
// Get handler first, since this can error out if there's no handler for the job name.
const handler = this._getInternalDescription(name);
const optionsDeps = (options && options.dependencies) || [];
const dependencies = Array.isArray(optionsDeps) ? optionsDeps : [optionsDeps];
const inboundBus = new Subject<JobInboundMessage<I>>();
const outboundBus = concat(
// Wait for dependencies, make sure to not report messages from dependencies. Subscribe to
// all dependencies at the same time so they run concurrently.
merge(...dependencies.map((x) => x.outboundBus)).pipe(ignoreElements()),
// Wait for pause() to clear (if necessary).
waitable,
from(handler).pipe(
switchMap(
(handler) =>
new Observable<JobOutboundMessage<O>>((subscriber: Observer<JobOutboundMessage<O>>) => {
if (!handler) {
throw new JobDoesNotExistException(name);
}
// Validate the argument.
return from(handler.argumentV)
.pipe(
switchMap((validate) => validate(argument)),
switchMap((output) => {
if (!output.success) {
throw new JobArgumentSchemaValidationError(output.errors);
}
const argument: A = output.data as A;
const description = handler.jobDescription;
subscriber.next({ kind: JobOutboundMessageKind.OnReady, description });
const context = {
description,
dependencies: [...dependencies],
inboundBus: inboundBus.asObservable(),
scheduler: this as Scheduler<MinimumArgumentT, MinimumInputT, MinimumOutputT>,
};
return handler(argument, context);
}),
)
.subscribe(subscriber as Observer<JobOutboundMessage<JsonValue>>);
}),
),
),
);
return this._createJob(name, argument, handler, inboundBus, outboundBus);
}
}