1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 | import {
|
7 | Binding,
|
8 | BindingFromClassOptions,
|
9 | BindingScope,
|
10 | Constructor,
|
11 | Context,
|
12 | createBindingFromClass,
|
13 | DynamicValueProviderClass,
|
14 | generateUniqueId,
|
15 | Interceptor,
|
16 | InterceptorBindingOptions,
|
17 | JSONObject,
|
18 | Provider,
|
19 | registerInterceptor,
|
20 | ValueOrPromise,
|
21 | } from '@loopback/context';
|
22 | import assert from 'assert';
|
23 | import debugFactory from 'debug';
|
24 | import {once} from 'events';
|
25 | import {Component, mountComponent} from './component';
|
26 | import {CoreBindings, CoreTags} from './keys';
|
27 | import {
|
28 | asLifeCycleObserver,
|
29 | isLifeCycleObserverClass,
|
30 | LifeCycleObserver,
|
31 | } from './lifecycle';
|
32 | import {LifeCycleObserverRegistry} from './lifecycle-registry';
|
33 | import {Server} from './server';
|
34 | import {createServiceBinding, ServiceOptions} from './service';
|
35 | const debug = debugFactory('loopback:core:application');
|
36 | const debugShutdown = debugFactory('loopback:core:application:shutdown');
|
37 | const debugWarning = debugFactory('loopback:core:application:warning');
|
38 |
|
39 |
|
40 |
|
41 |
|
42 |
|
43 |
|
44 | function buildConstructorArgs(
|
45 | configOrParent?: ApplicationConfig | Context,
|
46 | parent?: Context,
|
47 | ) {
|
48 | let name: string | undefined;
|
49 | let parentCtx: Context | undefined;
|
50 |
|
51 | if (configOrParent instanceof Context) {
|
52 | parentCtx = configOrParent;
|
53 | name = undefined;
|
54 | } else {
|
55 | parentCtx = parent;
|
56 | name = configOrParent?.name;
|
57 | }
|
58 | return [parentCtx, name];
|
59 | }
|
60 |
|
61 |
|
62 |
|
63 |
|
64 |
|
65 |
|
66 | export class Application extends Context implements LifeCycleObserver {
|
67 | public readonly options: ApplicationConfig;
|
68 |
|
69 | |
70 |
|
71 |
|
72 | private _isShuttingDown = false;
|
73 | private _shutdownOptions: ShutdownOptions;
|
74 | private _signalListener: (signal: string) => Promise<void>;
|
75 |
|
76 | private _initialized = false;
|
77 |
|
78 | |
79 |
|
80 |
|
81 | private _state = 'created';
|
82 |
|
83 | |
84 |
|
85 |
|
86 |
|
87 |
|
88 |
|
89 |
|
90 |
|
91 |
|
92 |
|
93 |
|
94 |
|
95 |
|
96 |
|
97 |
|
98 |
|
99 |
|
100 |
|
101 |
|
102 | public get state() {
|
103 | return this._state;
|
104 | }
|
105 |
|
106 | |
107 |
|
108 |
|
109 |
|
110 | constructor(parent: Context);
|
111 | /**
|
112 | * Create an application with the given configuration and parent context
|
113 | * @param config - Application configuration
|
114 | * @param parent - Parent context
|
115 | */
|
116 | constructor(config?: ApplicationConfig, parent?: Context);
|
117 |
|
118 | constructor(configOrParent?: ApplicationConfig | Context, parent?: Context) {
|
119 | // super() has to be first statement for a constructor
|
120 | super(...buildConstructorArgs(configOrParent, parent));
|
121 | this.scope = BindingScope.APPLICATION;
|
122 |
|
123 | this.options =
|
124 | configOrParent instanceof Context ? {} : configOrParent ?? {};
|
125 |
|
126 | // Configure debug
|
127 | this._debug = debug;
|
128 |
|
129 | // Bind the life cycle observer registry
|
130 | this.bind(CoreBindings.LIFE_CYCLE_OBSERVER_REGISTRY)
|
131 | .toClass(LifeCycleObserverRegistry)
|
132 | .inScope(BindingScope.SINGLETON);
|
133 | // Bind to self to allow injection of application context in other modules.
|
134 | this.bind(CoreBindings.APPLICATION_INSTANCE).to(this);
|
135 | // Make options available to other modules as well.
|
136 | this.bind(CoreBindings.APPLICATION_CONFIG).to(this.options);
|
137 |
|
138 | // Also configure the application instance to allow `@config`
|
139 | this.configure(CoreBindings.APPLICATION_INSTANCE).toAlias(
|
140 | CoreBindings.APPLICATION_CONFIG,
|
141 | );
|
142 |
|
143 | this._shutdownOptions = {signals: ['SIGTERM'], ...this.options.shutdown};
|
144 | }
|
145 |
|
146 | |
147 |
|
148 |
|
149 |
|
150 |
|
151 |
|
152 |
|
153 |
|
154 |
|
155 |
|
156 |
|
157 |
|
158 |
|
159 |
|
160 |
|
161 |
|
162 |
|
163 | controller<T>(
|
164 | controllerCtor: ControllerClass<T>,
|
165 | nameOrOptions?: string | BindingFromClassOptions,
|
166 | ): Binding<T> {
|
167 | this.debug('Adding controller %s', nameOrOptions ?? controllerCtor.name);
|
168 | const binding = createBindingFromClass(controllerCtor, {
|
169 | namespace: CoreBindings.CONTROLLERS,
|
170 | type: CoreTags.CONTROLLER,
|
171 | defaultScope: BindingScope.TRANSIENT,
|
172 | ...toOptions(nameOrOptions),
|
173 | });
|
174 | this.add(binding);
|
175 | return binding;
|
176 | }
|
177 |
|
178 | |
179 |
|
180 |
|
181 |
|
182 |
|
183 |
|
184 |
|
185 |
|
186 |
|
187 |
|
188 |
|
189 |
|
190 |
|
191 |
|
192 |
|
193 |
|
194 |
|
195 |
|
196 | public server<T extends Server>(
|
197 | ctor: Constructor<T>,
|
198 | nameOrOptions?: string | BindingFromClassOptions,
|
199 | ): Binding<T> {
|
200 | this.debug('Adding server %s', nameOrOptions ?? ctor.name);
|
201 | const binding = createBindingFromClass(ctor, {
|
202 | namespace: CoreBindings.SERVERS,
|
203 | type: CoreTags.SERVER,
|
204 | defaultScope: BindingScope.SINGLETON,
|
205 | ...toOptions(nameOrOptions),
|
206 | }).apply(asLifeCycleObserver);
|
207 | this.add(binding);
|
208 | return binding;
|
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 | public servers<T extends Server>(ctors: Constructor<T>[]): Binding[] {
|
234 | return ctors.map(ctor => this.server(ctor));
|
235 | }
|
236 |
|
237 | |
238 |
|
239 |
|
240 |
|
241 |
|
242 |
|
243 |
|
244 |
|
245 |
|
246 | public async getServer<T extends Server>(
|
247 | target: Constructor<T> | string,
|
248 | ): Promise<T> {
|
249 | let key: string;
|
250 |
|
251 | if (typeof target === 'string') {
|
252 | key = `${CoreBindings.SERVERS}.${target}`;
|
253 | } else {
|
254 | const ctor = target as Constructor<T>;
|
255 | key = `${CoreBindings.SERVERS}.${ctor.name}`;
|
256 | }
|
257 | return this.get<T>(key);
|
258 | }
|
259 |
|
260 | |
261 |
|
262 |
|
263 |
|
264 |
|
265 |
|
266 | protected assertNotInProcess(op: string) {
|
267 | assert(
|
268 | !this._state.endsWith('ing'),
|
269 | `Cannot ${op} the application as it is ${this._state}.`,
|
270 | );
|
271 | }
|
272 |
|
273 | |
274 |
|
275 |
|
276 |
|
277 |
|
278 | protected assertInStates(op: string, ...states: string[]) {
|
279 | assert(
|
280 | states.includes(this._state),
|
281 | `Cannot ${op} the application as it is ${this._state}. Valid states are ${states}.`,
|
282 | );
|
283 | }
|
284 |
|
285 | |
286 |
|
287 |
|
288 |
|
289 | protected setState(state: string) {
|
290 | const oldState = this._state;
|
291 | this._state = state;
|
292 | if (oldState !== state) {
|
293 | this.emit('stateChanged', {from: oldState, to: this._state});
|
294 | this.emit(state);
|
295 | }
|
296 | }
|
297 |
|
298 | protected async awaitState(state: string) {
|
299 | await once(this, state);
|
300 | }
|
301 |
|
302 | |
303 |
|
304 |
|
305 |
|
306 |
|
307 |
|
308 |
|
309 |
|
310 |
|
311 | public async init(): Promise<void> {
|
312 | if (this._initialized) return;
|
313 | if (this._state === 'initializing') return this.awaitState('initialized');
|
314 | this.assertNotInProcess('initialize');
|
315 | this.setState('initializing');
|
316 |
|
317 | const registry = await this.getLifeCycleObserverRegistry();
|
318 | await registry.init();
|
319 | this._initialized = true;
|
320 | this.setState('initialized');
|
321 | }
|
322 |
|
323 | |
324 |
|
325 |
|
326 |
|
327 |
|
328 |
|
329 |
|
330 |
|
331 |
|
332 |
|
333 | public onInit(fn: () => ValueOrPromise<void>): Binding<LifeCycleObserver> {
|
334 | const key = [
|
335 | CoreBindings.LIFE_CYCLE_OBSERVERS,
|
336 | fn.name || '<onInit>',
|
337 | generateUniqueId(),
|
338 | ].join('.');
|
339 |
|
340 | return this.bind<LifeCycleObserver>(key)
|
341 | .to({init: fn})
|
342 | .apply(asLifeCycleObserver);
|
343 | }
|
344 |
|
345 | |
346 |
|
347 |
|
348 |
|
349 |
|
350 |
|
351 |
|
352 |
|
353 |
|
354 |
|
355 | public async start(): Promise<void> {
|
356 | if (!this._initialized) await this.init();
|
357 | if (this._state === 'starting') return this.awaitState('started');
|
358 | this.assertNotInProcess('start');
|
359 |
|
360 | if (this._state === 'started') return;
|
361 | this.setState('starting');
|
362 | this.setupShutdown();
|
363 |
|
364 | const registry = await this.getLifeCycleObserverRegistry();
|
365 | await registry.start();
|
366 | this.setState('started');
|
367 | }
|
368 |
|
369 | |
370 |
|
371 |
|
372 |
|
373 |
|
374 |
|
375 |
|
376 |
|
377 |
|
378 |
|
379 | public onStart(fn: () => ValueOrPromise<void>): Binding<LifeCycleObserver> {
|
380 | const key = [
|
381 | CoreBindings.LIFE_CYCLE_OBSERVERS,
|
382 | fn.name || '<onStart>',
|
383 | generateUniqueId(),
|
384 | ].join('.');
|
385 |
|
386 | return this.bind<LifeCycleObserver>(key)
|
387 | .to({start: fn})
|
388 | .apply(asLifeCycleObserver);
|
389 | }
|
390 |
|
391 | |
392 |
|
393 |
|
394 |
|
395 |
|
396 |
|
397 |
|
398 | public async stop(): Promise<void> {
|
399 | if (this._state === 'stopping') return this.awaitState('stopped');
|
400 | this.assertNotInProcess('stop');
|
401 |
|
402 | if (this._state !== 'started' && this._state !== 'initialized') return;
|
403 | this.setState('stopping');
|
404 | if (!this._isShuttingDown) {
|
405 |
|
406 |
|
407 | this.removeSignalListener();
|
408 | }
|
409 | const registry = await this.getLifeCycleObserverRegistry();
|
410 | await registry.stop();
|
411 | this.setState('stopped');
|
412 | }
|
413 |
|
414 | |
415 |
|
416 |
|
417 |
|
418 |
|
419 |
|
420 |
|
421 |
|
422 |
|
423 |
|
424 | public onStop(fn: () => ValueOrPromise<void>): Binding<LifeCycleObserver> {
|
425 | const key = [
|
426 | CoreBindings.LIFE_CYCLE_OBSERVERS,
|
427 | fn.name || '<onStop>',
|
428 | generateUniqueId(),
|
429 | ].join('.');
|
430 | return this.bind<LifeCycleObserver>(key)
|
431 | .to({stop: fn})
|
432 | .apply(asLifeCycleObserver);
|
433 | }
|
434 |
|
435 | private async getLifeCycleObserverRegistry() {
|
436 | return this.get(CoreBindings.LIFE_CYCLE_OBSERVER_REGISTRY);
|
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 | public component<T extends Component = Component>(
|
463 | componentCtor: Constructor<T>,
|
464 | nameOrOptions?: string | BindingFromClassOptions,
|
465 | ) {
|
466 | this.debug('Adding component: %s', nameOrOptions ?? componentCtor.name);
|
467 | const binding = createBindingFromClass(componentCtor, {
|
468 | namespace: CoreBindings.COMPONENTS,
|
469 | type: CoreTags.COMPONENT,
|
470 | defaultScope: BindingScope.SINGLETON,
|
471 | ...toOptions(nameOrOptions),
|
472 | });
|
473 | if (isLifeCycleObserverClass(componentCtor)) {
|
474 | binding.apply(asLifeCycleObserver);
|
475 | }
|
476 | this.add(binding);
|
477 |
|
478 | const instance = this.getSync<Component>(binding.key);
|
479 | mountComponent(this, instance);
|
480 | return binding;
|
481 | }
|
482 |
|
483 | |
484 |
|
485 |
|
486 |
|
487 |
|
488 |
|
489 | public setMetadata(metadata: ApplicationMetadata) {
|
490 | this.bind(CoreBindings.APPLICATION_METADATA).to(metadata);
|
491 | }
|
492 |
|
493 | |
494 |
|
495 |
|
496 |
|
497 |
|
498 | public lifeCycleObserver<T extends LifeCycleObserver>(
|
499 | ctor: Constructor<T>,
|
500 | nameOrOptions?: string | BindingFromClassOptions,
|
501 | ): Binding<T> {
|
502 | this.debug('Adding life cycle observer %s', nameOrOptions ?? ctor.name);
|
503 | const binding = createBindingFromClass(ctor, {
|
504 | namespace: CoreBindings.LIFE_CYCLE_OBSERVERS,
|
505 | type: CoreTags.LIFE_CYCLE_OBSERVER,
|
506 | defaultScope: BindingScope.SINGLETON,
|
507 | ...toOptions(nameOrOptions),
|
508 | }).apply(asLifeCycleObserver);
|
509 | this.add(binding);
|
510 | return binding;
|
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 |
|
549 |
|
550 |
|
551 |
|
552 |
|
553 |
|
554 |
|
555 | public service<S>(
|
556 | cls: ServiceOrProviderClass<S>,
|
557 | nameOrOptions?: string | ServiceOptions,
|
558 | ): Binding<S> {
|
559 | const options = toOptions(nameOrOptions);
|
560 | const binding = createServiceBinding(cls, options);
|
561 | this.add(binding);
|
562 | return binding;
|
563 | }
|
564 |
|
565 | |
566 |
|
567 |
|
568 |
|
569 |
|
570 | public interceptor(
|
571 | interceptor: Interceptor | Constructor<Provider<Interceptor>>,
|
572 | nameOrOptions?: string | InterceptorBindingOptions,
|
573 | ) {
|
574 | const options = toOptions(nameOrOptions);
|
575 | return registerInterceptor(this, interceptor, options);
|
576 | }
|
577 |
|
578 | |
579 |
|
580 |
|
581 | protected setupShutdown() {
|
582 | if (this._signalListener != null) {
|
583 | this.registerSignalListener();
|
584 | return this._signalListener;
|
585 | }
|
586 | const gracePeriod = this._shutdownOptions.gracePeriod;
|
587 | this._signalListener = async (signal: string) => {
|
588 | const kill = () => {
|
589 | this.removeSignalListener();
|
590 | process.kill(process.pid, signal);
|
591 | };
|
592 | debugShutdown(
|
593 | '[%s] Signal %s received for process %d',
|
594 | this.name,
|
595 | signal,
|
596 | process.pid,
|
597 | );
|
598 | if (!this._isShuttingDown) {
|
599 | this._isShuttingDown = true;
|
600 | let timer;
|
601 | if (typeof gracePeriod === 'number' && !isNaN(gracePeriod)) {
|
602 | timer = setTimeout(kill, gracePeriod);
|
603 | }
|
604 | try {
|
605 | await this.stop();
|
606 | } finally {
|
607 | if (timer != null) clearTimeout(timer);
|
608 | kill();
|
609 | }
|
610 | }
|
611 | };
|
612 | this.registerSignalListener();
|
613 | return this._signalListener;
|
614 | }
|
615 |
|
616 | private registerSignalListener() {
|
617 | const {signals = []} = this._shutdownOptions;
|
618 | debugShutdown(
|
619 | '[%s] Registering signal listeners on the process %d',
|
620 | this.name,
|
621 | process.pid,
|
622 | signals,
|
623 | );
|
624 | signals.forEach(sig => {
|
625 | if (process.getMaxListeners() <= process.listenerCount(sig)) {
|
626 | if (debugWarning.enabled) {
|
627 | debugWarning(
|
628 | '[%s] %d %s listeners are added to process %d',
|
629 | this.name,
|
630 | process.listenerCount(sig),
|
631 | sig,
|
632 | process.pid,
|
633 | new Error('MaxListenersExceededWarning'),
|
634 | );
|
635 | }
|
636 | }
|
637 |
|
638 | process.on(sig, this._signalListener);
|
639 | });
|
640 | }
|
641 |
|
642 | private removeSignalListener() {
|
643 | if (this._signalListener == null) return;
|
644 | const {signals = []} = this._shutdownOptions;
|
645 | debugShutdown(
|
646 | '[%s] Removing signal listeners on the process %d',
|
647 | this.name,
|
648 | process.pid,
|
649 | signals,
|
650 | );
|
651 | signals.forEach(sig =>
|
652 |
|
653 | process.removeListener(sig, this._signalListener),
|
654 | );
|
655 | }
|
656 | }
|
657 |
|
658 |
|
659 |
|
660 |
|
661 |
|
662 | function toOptions(nameOrOptions?: string | BindingFromClassOptions) {
|
663 | if (typeof nameOrOptions === 'string') {
|
664 | return {name: nameOrOptions};
|
665 | }
|
666 | return nameOrOptions ?? {};
|
667 | }
|
668 |
|
669 |
|
670 |
|
671 |
|
672 | export type ShutdownOptions = {
|
673 | |
674 |
|
675 |
|
676 | signals?: NodeJS.Signals[];
|
677 | |
678 |
|
679 |
|
680 |
|
681 | gracePeriod?: number;
|
682 | };
|
683 |
|
684 |
|
685 |
|
686 |
|
687 | export interface ApplicationConfig {
|
688 | |
689 |
|
690 |
|
691 | name?: string;
|
692 | |
693 |
|
694 |
|
695 | shutdown?: ShutdownOptions;
|
696 |
|
697 | |
698 |
|
699 |
|
700 |
|
701 | [prop: string]: any;
|
702 | }
|
703 |
|
704 |
|
705 | export type ControllerClass<T = any> = Constructor<T>;
|
706 |
|
707 |
|
708 | export type ServiceOrProviderClass<T = any> =
|
709 | | Constructor<T | Provider<T>>
|
710 | | DynamicValueProviderClass<T>;
|
711 |
|
712 |
|
713 |
|
714 |
|
715 | export interface ApplicationMetadata extends JSONObject {
|
716 | name: string;
|
717 | version: string;
|
718 | description: string;
|
719 | }
|