-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
application.ts
504 lines (472 loc) · 14.7 KB
/
application.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
// Copyright IBM Corp. 2017,2018. All Rights Reserved.
// Node module: @loopback/core
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT
import {
Binding,
BindingScope,
Constructor,
Context,
createBindingFromClass,
Provider,
} from '@loopback/context';
import * as assert from 'assert';
import * as debugFactory from 'debug';
import pEvent from 'p-event';
import {Component, mountComponent} from './component';
import {CoreBindings, CoreTags} from './keys';
import {
asLifeCycleObserver,
isLifeCycleObserverClass,
LifeCycleObserver,
} from './lifecycle';
import {LifeCycleObserverRegistry} from './lifecycle-registry';
import {Server} from './server';
import {createServiceBinding, ServiceOptions} from './service';
const debug = debugFactory('loopback:core:application');
/**
* Application is the container for various types of artifacts, such as
* components, servers, controllers, repositories, datasources, connectors,
* and models.
*/
export class Application extends Context implements LifeCycleObserver {
public readonly options: ApplicationConfig;
/**
* A flag to indicate that the application is being shut down
*/
private _isShuttingDown = false;
/**
* State of the application
*/
private _state = 'created';
/**
* Get the state of the application. The initial state is `created` and it can
* transition as follows by `start` and `stop`:
*
* 1. start
* - !started -> starting -> started
* - started -> started (no-op)
* 2. stop
* - started -> stopping -> stopped
* - !started -> stopped (no-op)
*
* Two types of states are expected:
* - stable, such as `started` and `stopped`
* - in process, such as `booting` and `starting`
*
* Operations such as `start` and `stop` can only be called at a stable state.
* The logic should immediately set the state to a new one indicating work in
* process, such as `starting` and `stopping`.
*/
public get state() {
return this._state;
}
/**
* Create an application with the given parent context
* @param parent - Parent context
*/
constructor(parent: Context);
/**
* Create an application with the given configuration and parent context
* @param config - Application configuration
* @param parent - Parent context
*/
constructor(config?: ApplicationConfig, parent?: Context);
constructor(configOrParent?: ApplicationConfig | Context, parent?: Context) {
super(
configOrParent instanceof Context ? configOrParent : parent,
'application',
);
if (configOrParent instanceof Context) configOrParent = {};
this.options = configOrParent ?? {};
// Bind the life cycle observer registry
this.bind(CoreBindings.LIFE_CYCLE_OBSERVER_REGISTRY)
.toClass(LifeCycleObserverRegistry)
.inScope(BindingScope.SINGLETON);
// Bind to self to allow injection of application context in other modules.
this.bind(CoreBindings.APPLICATION_INSTANCE).to(this);
// Make options available to other modules as well.
this.bind(CoreBindings.APPLICATION_CONFIG).to(this.options);
const shutdownConfig = this.options.shutdown || {};
this.setupShutdown(
shutdownConfig.signals || ['SIGTERM'],
shutdownConfig.gracePeriod,
);
}
/**
* Register a controller class with this application.
*
* @param controllerCtor - The controller class
* (constructor function).
* @param name - Optional controller name, default to the class name
* @returns The newly created binding, you can use the reference to
* further modify the binding, e.g. lock the value to prevent further
* modifications.
*
* @example
* ```ts
* class MyController {
* }
* app.controller(MyController).lock();
* ```
*/
controller(controllerCtor: ControllerClass, name?: string): Binding {
debug('Adding controller %s', name ?? controllerCtor.name);
const binding = createBindingFromClass(controllerCtor, {
name,
namespace: CoreBindings.CONTROLLERS,
type: CoreTags.CONTROLLER,
defaultScope: BindingScope.TRANSIENT,
});
this.add(binding);
return binding;
}
/**
* Bind a Server constructor to the Application's master context.
* Each server constructor added in this way must provide a unique prefix
* to prevent binding overlap.
*
* @example
* ```ts
* app.server(RestServer);
* // This server constructor will be bound under "servers.RestServer".
* app.server(RestServer, "v1API");
* // This server instance will be bound under "servers.v1API".
* ```
*
* @param server - The server constructor.
* @param name - Optional override for key name.
* @returns Binding for the server class
*
*/
public server<T extends Server>(
ctor: Constructor<T>,
name?: string,
): Binding<T> {
debug('Adding server %s', name ?? ctor.name);
const binding = createBindingFromClass(ctor, {
name,
namespace: CoreBindings.SERVERS,
type: CoreTags.SERVER,
defaultScope: BindingScope.SINGLETON,
}).apply(asLifeCycleObserver);
this.add(binding);
return binding;
}
/**
* Bind an array of Server constructors to the Application's master
* context.
* Each server added in this way will automatically be named based on the
* class constructor name with the "servers." prefix.
*
* @remarks
* If you wish to control the binding keys for particular server instances,
* use the app.server function instead.
* ```ts
* app.servers([
* RestServer,
* GRPCServer,
* ]);
* // Creates a binding for "servers.RestServer" and a binding for
* // "servers.GRPCServer";
* ```
*
* @param ctors - An array of Server constructors.
* @returns An array of bindings for the registered server classes
*
*/
public servers<T extends Server>(ctors: Constructor<T>[]): Binding[] {
return ctors.map(ctor => this.server(ctor));
}
/**
* Retrieve the singleton instance for a bound server.
*
* @typeParam T - Server type
* @param ctor - The constructor that was used to make the
* binding.
* @returns A Promise of server instance
*
*/
public async getServer<T extends Server>(
target: Constructor<T> | string,
): Promise<T> {
let key: string;
// instanceof check not reliable for string.
if (typeof target === 'string') {
key = `${CoreBindings.SERVERS}.${target}`;
} else {
const ctor = target as Constructor<T>;
key = `${CoreBindings.SERVERS}.${ctor.name}`;
}
return this.get<T>(key);
}
/**
* Assert there is no other operation is in progress, i.e., the state is not
* `*ing`, such as `starting` or `stopping`.
*
* @param op - The operation name, such as 'boot', 'start', or 'stop'
*/
protected assertNotInProcess(op: string) {
assert(
!this._state.endsWith('ing'),
`Cannot ${op} the application as it is ${this._state}.`,
);
}
/**
* Assert current state of the application to be one of the expected values
* @param op - The operation name, such as 'boot', 'start', or 'stop'
* @param states - Valid states
*/
protected assertInStates(op: string, ...states: string[]) {
assert(
states.includes(this._state),
`Cannot ${op} the application as it is ${this._state}. Valid states are ${states}.`,
);
}
/**
* Transition the application to a new state and emit an event
* @param state - The new state
*/
protected setState(state: string) {
const oldState = this._state;
this._state = state;
if (oldState !== state) {
this.emit('stateChanged', {from: oldState, to: this._state});
this.emit(state);
}
}
protected async awaitState(state: string) {
await pEvent(this, state);
}
/**
* Start the application, and all of its registered observers. The application
* state is checked to ensure the integrity of `start`.
*
* If the application is already started, no operation is performed.
*/
public async start(): Promise<void> {
if (this._state === 'starting') return this.awaitState('started');
this.assertNotInProcess('start');
// No-op if it's started
if (this._state === 'started') return;
this.setState('starting');
const registry = await this.getLifeCycleObserverRegistry();
await registry.start();
this.setState('started');
}
/**
* Stop the application instance and all of its registered observers. The
* application state is checked to ensure the integrity of `stop`.
*
* If the application is already stopped or not started, no operation is
* performed.
*/
public async stop(): Promise<void> {
if (this._state === 'stopping') return this.awaitState('stopped');
this.assertNotInProcess('stop');
// No-op if it's created or stopped
if (this._state !== 'started') return;
this.setState('stopping');
const registry = await this.getLifeCycleObserverRegistry();
await registry.stop();
this.setState('stopped');
}
private async getLifeCycleObserverRegistry() {
return this.get(CoreBindings.LIFE_CYCLE_OBSERVER_REGISTRY);
}
/**
* Add a component to this application and register extensions such as
* controllers, providers, and servers from the component.
*
* @param componentCtor - The component class to add.
* @param name - Optional component name, default to the class name
*
* @example
* ```ts
*
* export class ProductComponent {
* controllers = [ProductController];
* repositories = [ProductRepo, UserRepo];
* providers = {
* [AUTHENTICATION_STRATEGY]: AuthStrategy,
* [AUTHORIZATION_ROLE]: Role,
* };
* };
*
* app.component(ProductComponent);
* ```
*/
public component(componentCtor: Constructor<Component>, name?: string) {
debug('Adding component: %s', name ?? componentCtor.name);
const binding = createBindingFromClass(componentCtor, {
name,
namespace: CoreBindings.COMPONENTS,
type: CoreTags.COMPONENT,
defaultScope: BindingScope.SINGLETON,
});
if (isLifeCycleObserverClass(componentCtor)) {
binding.apply(asLifeCycleObserver);
}
this.add(binding);
// Assuming components can be synchronously instantiated
const instance = this.getSync<Component>(binding.key);
mountComponent(this, instance);
return binding;
}
/**
* Set application metadata. `@loopback/boot` calls this method to populate
* the metadata from `package.json`.
*
* @param metadata - Application metadata
*/
public setMetadata(metadata: ApplicationMetadata) {
this.bind(CoreBindings.APPLICATION_METADATA).to(metadata);
}
/**
* Register a life cycle observer class
* @param ctor - A class implements LifeCycleObserver
* @param name - Optional name for the life cycle observer
*/
public lifeCycleObserver<T extends LifeCycleObserver>(
ctor: Constructor<T>,
name?: string,
): Binding<T> {
debug('Adding life cycle observer %s', name ?? ctor.name);
const binding = createBindingFromClass(ctor, {
name,
namespace: CoreBindings.LIFE_CYCLE_OBSERVERS,
type: CoreTags.LIFE_CYCLE_OBSERVER,
defaultScope: BindingScope.SINGLETON,
}).apply(asLifeCycleObserver);
this.add(binding);
return binding;
}
/**
* Add a service to this application.
*
* @param cls - The service or provider class
*
* @example
*
* ```ts
* // Define a class to be bound via ctx.toClass()
* @bind({scope: BindingScope.SINGLETON})
* export class LogService {
* log(msg: string) {
* console.log(msg);
* }
* }
*
* // Define a class to be bound via ctx.toProvider()
* const uuidv4 = require('uuid/v4');
* export class UuidProvider implements Provider<string> {
* value() {
* return uuidv4();
* }
* }
*
* // Register the local services
* app.service(LogService);
* app.service(UuidProvider, 'uuid');
*
* export class MyController {
* constructor(
* @inject('services.uuid') private uuid: string,
* @inject('services.LogService') private log: LogService,
* ) {
* }
*
* greet(name: string) {
* this.log(`Greet request ${this.uuid} received: ${name}`);
* return `${this.uuid}: ${name}`;
* }
* }
* ```
*/
public service<S>(
cls: Constructor<S> | Constructor<Provider<S>>,
name?: string | ServiceOptions,
): Binding<S> {
const options = typeof name === 'string' ? {name} : name;
const binding = createServiceBinding(cls, options);
this.add(binding);
return binding;
}
/**
* Set up signals that are captured to shutdown the application
* @param signals - An array of signals to be trapped
* @param gracePeriod - A grace period in ms before forced exit
*/
protected setupShutdown(signals: NodeJS.Signals[], gracePeriod?: number) {
const cleanup = async (signal: string) => {
const kill = () => {
// eslint-disable-next-line @typescript-eslint/no-misused-promises
signals.forEach(sig => process.removeListener(sig, cleanup));
process.kill(process.pid, signal);
};
debug('Signal %s received for process %d', signal, process.pid);
if (!this._isShuttingDown) {
this._isShuttingDown = true;
let timer;
if (typeof gracePeriod === 'number' && !isNaN(gracePeriod)) {
timer = setTimeout(kill, gracePeriod);
}
try {
await this.stop();
} finally {
if (timer != null) clearTimeout(timer);
kill();
}
}
};
// eslint-disable-next-line @typescript-eslint/no-misused-promises
signals.forEach(sig => process.on(sig, cleanup));
}
}
/**
* Options to set up application shutdown
*/
export type ShutdownOptions = {
/**
* An array of signals to be trapped for graceful shutdown
*/
signals?: NodeJS.Signals[];
/**
* Period in milliseconds to wait for the grace shutdown to finish before
* exiting the process
*/
gracePeriod?: number;
};
/**
* Configuration for application
*/
export interface ApplicationConfig {
/**
* Configuration for signals that shut down the application
*/
shutdown?: ShutdownOptions;
/**
* Other properties
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
[prop: string]: any;
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export type ControllerClass = Constructor<any>;
/**
* Type definition for JSON
*/
export type JSONPrimitive = string | number | boolean | null;
export type JSONValue = JSONPrimitive | JSONObject | JSONArray;
export interface JSONObject {
[property: string]: JSONValue;
}
export interface JSONArray extends Array<JSONValue> {}
/**
* Type description for `package.json`
*/
export interface ApplicationMetadata extends JSONObject {
name: string;
version: string;
description: string;
}