-
-
Notifications
You must be signed in to change notification settings - Fork 70
/
index.js
1562 lines (1388 loc) · 34.4 KB
/
index.js
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
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'use strict'
/**
* Copyright 2016-present, Dustin Deus (deusdustin@gmail.com)
* All rights reserved.
*
* This source code is licensed under the MIT-style license found in the
* LICENSE file in the root directory of this source tree.
*
*/
/**
* Module Dependencies
*/
const NATS = require('nats')
const EventEmitter = require('events')
const Bloomrun = require('bloomrun')
const Errio = require('errio')
const Heavy = require('heavy')
const Pino = require('pino')
const TinySonic = require('tinysonic')
const SuperError = require('super-error')
const Joi = require('joi')
const Avvio = require('avvio')
const Stream = require('stream').Stream
const runExt = require('./extensionRunner').extRunner
const serverExtIterator = require('./extensionRunner').serverExtIterator
const clientExtIterator = require('./extensionRunner').clientExtIterator
const Errors = require('./errors')
const Symbols = require('./symbols')
const Util = require('./util')
const NatsTransport = require('./transport')
const DefaultExtensions = require('./extensions')
const DefaultEncoder = require('./encoder')
const DefaultDecoder = require('./decoder')
const ServerResponse = require('./serverResponse')
const ServerRequest = require('./serverRequest')
const ClientRequest = require('./clientRequest')
const ClientResponse = require('./clientResponse')
const ConfigScheme = require('./configScheme')
const Reply = require('./reply')
const Add = require('./add')
const ExtensionManager = require('./extensionManager')
const natsConnCodes = [
NATS.CONN_ERR,
NATS.SECURE_CONN_REQ,
NATS.NON_SECURE_CONN_REQ,
NATS.CLIENT_CERT_REQ
]
/**
* @class Hemera
*/
class Hemera extends EventEmitter {
/**
* Creates an instance of Hemera
*
* @param {Nats} transport
* @param {Config} params
*
* @memberOf Hemera
*/
constructor(transport, params) {
super()
const config = Joi.validate(params || {}, ConfigScheme)
if (config.error) {
throw config.error
}
this._root = this
this._isReady = false
this._config = config.value
this._router = Bloomrun(this._config.bloomrun)
this._heavy = new Heavy(this._config.load.process)
this._transport = new NatsTransport({
transport
})
this._topics = new Map()
// special variables for the new execution context
this.context$ = {}
this.meta$ = {}
this.delegate$ = {}
this.auth$ = {}
this.trace$ = {}
this.request$ = {
type: 'request',
id: ''
}
this.sid = 0
// represent the 'Add' instance
this.matchedAction = null
this.request = null
this.response = null
this._topic = ''
this._pattern = null
// represent the 'act' handler
this._execute = null
this._cleanPattern = ''
this._clientEncoder = DefaultEncoder.encode
this._clientDecoder = DefaultDecoder.decode
this._serverEncoder = DefaultEncoder.encode
this._serverDecoder = DefaultDecoder.decode
this._schemaCompiler = null
this._responseSchemaCompiler = null
this._idGenerator = Util.randomId
// errio settings
Errio.setDefaults(this._config.errio)
// Register all default hemera errors
this._registerErrors()
// create load policy
this._loadPolicy = this._heavy.policy(this._config.load.policy)
// start tracking process stats
this._heavy.start()
// when a route for a pattern could not be found
this._notFoundPattern = null
this._onAddHandlers = []
this._extensionManager = new ExtensionManager()
this._extensionManager.add(
'onClientPreRequest',
DefaultExtensions.onClientPreRequest
)
this._extensionManager.add(
'onClientPostRequest',
DefaultExtensions.onClientPostRequest
)
this._extensionManager.add(
'onServerPreRequest',
DefaultExtensions.onServerPreRequest
)
this._extensionManager.add(
'onServerPreResponse',
DefaultExtensions.onServerPreResponse
)
this._configureLogger()
this._avvio = Avvio(this, {
autostart: false,
expose: {
use: 'register',
close: 'shutdown',
onClose: 'onShutdown',
ready: 'bootstrap'
},
timeout: this._config.pluginTimeout
})
this[Symbols.childrenKey] = []
this[Symbols.registeredPlugins] = []
this._avvio.override = (hemera, plugin, opts) => {
const pluginMeta = this.getPluginMeta(plugin)
if (pluginMeta) {
if (pluginMeta.name) {
hemera[Symbols.registeredPlugins].push(pluginMeta.name)
}
hemera.checkPluginDependencies(plugin)
hemera.checkPluginDecorators(plugin)
}
if (plugin[Symbol.for('plugin-scoped')] === false) {
return hemera
}
const instance = Object.create(hemera)
hemera[Symbols.childrenKey].push(instance)
instance[Symbols.childrenKey] = []
if (pluginMeta && pluginMeta.name && hemera._config.childLogger) {
instance.log = hemera.log.child({ plugin: pluginMeta.name })
}
instance[Symbols.registeredPlugins] = Object.create(
hemera[Symbols.registeredPlugins]
)
// inherit all extensions
instance._extensionManager = ExtensionManager.build(
hemera._extensionManager
)
// decorate root instance. All instances will have access
instance.decorate = function() {
hemera.decorate.apply(this._root, arguments)
return instance
}
return instance
}
}
/**
*
*
* @memberof Hemera
*/
_configureLogger() {
const loggerOpts = {
name: this._config.name,
prettyPrint: this._config.prettyLog,
level: this._config.logLevel
}
if (this._config.logger instanceof Stream) {
this.log = Pino(loggerOpts, this._config.logger)
} else if (this._config.logger) {
this.log = this._config.logger
} else {
this.log = Pino(loggerOpts)
}
}
/**
*
*
* @memberof Hemera
*/
_registerErrors() {
for (let error in Hemera.errors) {
Errio.register(Hemera.errors[error])
}
}
/**
*
* @param {*} fn
*/
setIdGenerator(fn) {
if (typeof fn !== 'function') {
throw new Errors.HemeraError(`IdGenerator must be a function`)
}
this._idGenerator = fn
return this
}
/**
*
* @param {*} fn
*/
setServerDecoder(fn) {
if (typeof fn !== 'function') {
throw new Errors.HemeraError(`ServerDecoder must be a function`)
}
this._serverDecoder = fn
return this
}
/**
*
* @param {*} fn
*/
setServerEncoder(fn) {
if (typeof fn !== 'function') {
throw new Errors.HemeraError(`ServerEncoder must be a function`)
}
this._serverEncoder = fn
return this
}
/**
*
* @param {*} fn
*/
setClientDecoder(fn) {
if (typeof fn !== 'function') {
throw new Errors.HemeraError(`ClientDecoder must be a function`)
}
this._clientDecoder = fn
return this
}
/**
*
* @param {*} fn
*/
setClientEncoder(fn) {
if (typeof fn !== 'function') {
throw new Errors.HemeraError(`ClientEncoder must be a function`)
}
this._clientEncoder = fn
return this
}
/**
*
* @param {*} fn
*/
setNotFoundPattern(pattern) {
// check for use quick syntax for JSON objects
if (typeof pattern === 'string') {
pattern = TinySonic(pattern)
}
this._notFoundPattern = pattern
return this
}
/**
* Return the bloomrun instance
*
* @readonly
*
* @memberOf Hemera
*/
get router() {
return this._router
}
/**
* Return the heavy instance
*
* @readonly
*
* @memberOf Hemera
*/
get load() {
return this._heavy.load
}
/**
* Return the underlying NATS driver
*
* @readonly
*
* @memberOf Hemera
*/
get transport() {
return this._transport.driver
}
/**
* Return all registered topics
*
* @readonly
*
* @memberOf Hemera
*/
get topics() {
return this._topics
}
/**
*
* @readonly
*
* @memberOf Hemera
*/
get notFoundPattern() {
return this._notFoundPattern
}
/**
*
*
* @readonly
*
* @memberOf Hemera
*/
get config() {
return this._config
}
/**
*
*
* @readonly
*
* @memberof Hemera
*/
get errorDetails() {
if (this._isServer) {
return {
app: this._config.name,
isServer: this._isServer,
pattern: this.trace$.method
}
} else {
return {
app: this._config.name,
isServer: this._isServer,
pattern: this.trace$.method
}
}
}
/**
* Return all hemera errors
*
* @readonly
* @static
*
* @memberOf Hemera
*/
static get errors() {
return Errors
}
/**
* Create a custom super error object without to start hemera
*
* @readonly
*
* @memberOf Hemera
*/
static createError(name) {
if (typeof name !== 'string') {
throw new Errors.HemeraError(`Error name must be a string`)
}
const ctor = SuperError.subclass(name)
// Register the class with Errio.
Errio.register(ctor)
return ctor
}
/**
* Add an onAdd handler
*
* @param {any} handler
*
* @memberOf Hemera
*/
_addOnAddHandler(handler) {
this._onAddHandlers.push(handler)
}
/**
* Add an extension. Extensions are called in serie
*
* @param {any} type
* @param {any} handler
*
* @memberOf Hemera
*/
ext(type, handler) {
if (typeof handler !== 'function') {
throw new Errors.HemeraError('Extension handler must be a function')
}
if (type === 'onAdd') {
this._addOnAddHandler(handler)
} else if (type === 'onClose') {
this.onShutdown(handler)
} else {
this._extensionManager.add(type, handler)
}
return this
}
/**
*
* @param {*} fn
*/
setSchemaCompiler(fn) {
if (typeof fn !== 'function') {
throw new Errors.HemeraError('SchemaCompiler handler must be a function')
}
this._schemaCompiler = fn
return this
}
/**
*
* @param {*} fn
*/
setResponseSchemaCompiler(fn) {
if (typeof fn !== 'function') {
throw new Errors.HemeraError(
'ResponseSchemaCompiler handler must be a function'
)
}
this._responseSchemaCompiler = fn
return this
}
/**
* Exit the process
*
* @memberOf Hemera
*/
fatal() {
this.close(() => process.exit(1))
}
/**
*
*
* @param {any} prop
* @returns
* @memberof Hemera
*/
hasDecorator(prop) {
return prop in this
}
/**
* Decorate the root instance
* Value is globaly accessible
*
* @param {any} prop
* @param {any} value
*
* @memberOf Hemera
*/
decorate(prop, value, deps) {
if (prop in this) {
throw new Errors.HemeraError('Decoration has been already added')
}
if (deps) {
this._checkMemberDependencies(deps)
}
this[prop] = value
return this
}
/**
* Expose a value to the current instance
*
* @param {any} prop
* @param {any} value
*
* @memberOf Hemera
*/
expose(prop, value, deps) {
if (prop in this) {
throw new Errors.HemeraError('Exposition has been already added')
}
if (deps) {
this._checkMemberDependencies(deps)
}
this[prop] = value
return this
}
/**
*
*
* @param {any} deps
* @memberof Hemera
*/
_checkMemberDependencies(deps) {
for (let i = 0; i < deps.length; i++) {
if (!(deps[i] in this)) {
throw new Errors.HemeraError(`Missing member dependency '${deps[i]}'`)
}
}
}
/**
*
* @param {*} plugin
*/
getPluginMeta(plugin) {
return plugin[Symbol.for('plugin-meta')]
}
/**
*
*
* @param {any} deps
* @memberof Hemera
*/
checkPluginDependencies(plugin) {
const pluginMeta = this.getPluginMeta(plugin)
if (!pluginMeta) {
return
}
const dependencies = pluginMeta.dependencies
if (!dependencies) {
return
}
if (!Array.isArray(dependencies)) {
throw new Errors.HemeraError(
'Plugin dependencies must be an array of strings'
)
}
dependencies.forEach(dependency => {
if (this[Symbols.registeredPlugins].indexOf(dependency) === -1) {
throw new Errors.HemeraError(
`The dependency '${dependency}' is not registered`
)
}
})
}
/**
*
*
* @param {any} deps
* @memberof Hemera
*/
checkPluginDecorators(plugin) {
const pluginMeta = this.getPluginMeta(plugin)
if (!pluginMeta) {
return
}
const decorators = pluginMeta.decorators
if (!decorators) {
return
}
if (!Array.isArray(decorators)) {
throw new Errors.HemeraError(
'Plugin decorators must be an array of strings'
)
}
for (let i = 0; i < decorators.length; i++) {
if (!(decorators[i] in this)) {
throw new Errors.HemeraError(
`The decorator dependency '${decorators[i]}' is not registered`
)
}
}
}
/**
*
*
* @param {any} plugin
* @returns
* @memberof Hemera
*/
use(plugin, opts) {
const pluginMeta = this.getPluginMeta(plugin)
let pluginOpts = pluginMeta ? pluginMeta.options : {}
pluginOpts = Object.assign({}, pluginOpts, opts)
this.register(plugin, pluginOpts)
return this._avvio
}
/**
* Create a custom super error object in a running hemera instance
*
* @param {any} name
* @returns
*
* @memberOf Hemera
*/
createError(name) {
const ctor = SuperError.subclass(name)
// Register the class with Errio
Errio.register(ctor)
return ctor
}
/**
*
*
* @param {Function} cb
*
* @memberOf Hemera
*/
ready(cb) {
if (this._isReady) {
throw new Errors.HemeraError('Hemera was already bootstraped')
}
this._isReady = true
this._transport.driver.on('error', err => {
this.log.error(err, 'Could not connect to NATS!')
this.log.error("NATS Code: '%s', Message: %s", err.code, err.message)
// Exit only on connection issues.
// Authorization and protocol issues don't lead to process termination
if (natsConnCodes.indexOf(err.code) > -1) {
// We have no NATS connection and can only gracefully shutdown hemera
this.close()
}
})
this._transport.driver.on('permission_error', err => {
this.log.error(err, 'NATS permission error')
})
this._transport.driver.on('reconnect', () => {
this.log.info('NATS reconnected!')
})
this._transport.driver.on('reconnecting', () => {
this.log.warn('NATS reconnecting ...')
})
this._transport.driver.on('disconnect', () => {
this.log.warn('NATS disconnected!')
})
// when nats was not able to reconnect or connection was closed due to other reasons
// the process should die and restarted
this._transport.driver.on('close', () => {
const error = new Errors.HemeraError('NATS connection closed!')
this.log.error(error)
// when an 'error' handler was registered no error is thrown
// but you have to handle it by yourself
this.emit('error', error)
})
const ready = cb => {
if (this._transport.driver.connected) {
this.log.info('Connected!')
this.bootstrap(cb)
} else {
this._transport.driver.on('connect', () => {
this.log.info('Connected!')
this.bootstrap(cb)
})
}
}
// callback style
if (typeof cb === 'function') {
ready(err => {
if (err) {
this.log.error(err)
cb(err)
return
}
cb()
})
return
}
// promise style
return new Promise((resolve, reject) => {
ready(err => {
if (err) {
this.log.error(err)
reject(err)
return
}
resolve()
})
})
}
/**
*
*
* @param {any} err
* @returns
* @memberof Hemera
*/
_attachHops(err) {
const self = this
if (err) {
const errorDetails = {
service: self.trace$.service,
method: self.trace$.method,
app: self._config.name,
ts: Util.nowHrTime()
}
// collect hops
if (err.hops) {
err.hops.push(errorDetails)
} else {
err.hops = [errorDetails]
}
}
return err
}
/**
* Attach one handler to the topic subscriber.
* With subToMany and maxMessages you control NATS specific behaviour.
*
* @param {any} addDefinition
* @memberof Hemera
*/
subscribe(addDefinition) {
const self = this
const topic = addDefinition.transport.topic
const maxMessages = addDefinition.transport.maxMessages
const queue = addDefinition.transport.queue || `queue.${topic}`
const pubsub = addDefinition.transport.pubsub
// avoid duplicate subscribers of the emit stream
// we use one subscriber per topic
if (self._topics.has(topic)) {
return 0
}
let handler = (request, replyTo) => {
// create new execution context
let hemera = self.createContext()
hemera._topic = topic
hemera.request = new ServerRequest(request)
hemera.response = new ServerResponse(replyTo)
hemera.reply = new Reply(
hemera.request,
hemera.response,
hemera,
hemera.log
)
hemera._pattern = null
hemera._isServer = true
// represent the matched server action "add"
hemera.matchedAction = null
runExt(
hemera._extensionManager.onServerPreRequest,
serverExtIterator,
hemera,
err => hemera._onServerPreRequestCompleted(err)
)
}
// standard pubsub with optional max messages
if (pubsub) {
return self._transport.subscribe(
topic,
{
max: maxMessages
},
handler
)
} else {
// queue group names allow load balancing of services
return self._transport.subscribe(
topic,
{
queue,
max: maxMessages
},
handler
)
}
}
/**
*
* @param {any} extensionError
* @param {any} value
* @memberof Hemera
*/
_onServerPreRequestCompleted(extensionError) {
const self = this
if (extensionError) {
const internalError = new Errors.HemeraError(
'onServerPreRequest extension',
self.errorDetails
).causedBy(extensionError)
self.log.error(internalError)
self.emit('serverResponseError', extensionError)
self.reply.isError = true
self.reply.send(extensionError)
return
}
// check if a handler is registered with this pattern
if (self.matchedAction) {
self.emit('serverPreHandler', self)
if (self._extensionManager.onServerPreHandler.length) {
runExt(
self._extensionManager.onServerPreHandler,
serverExtIterator,
self,
err => self._onServerPreHandlerCompleted(err)
)
} else {
self._onServerPreHandlerCompleted()
}
} else {
const internalError = new Errors.PatternNotFound(
'No action found for this pattern',
self.errorDetails
)
self.log.error(internalError)
self.emit('serverResponseError', internalError)
self.reply.isError = true
self.reply.send(internalError)
}
}
/**
*
*
* @param {any} extensionError
* @memberof Hemera
*/
_onServerPreHandlerCompleted(extensionError) {
const self = this
if (extensionError) {
const internalError = new Errors.HemeraError(
'onServerPreHandler extension',
self.errorDetails
).causedBy(extensionError)
self.log.error(internalError)
self.emit('serverResponseError', extensionError)
self.reply.isError = true
self.reply.send(extensionError)
return
}
// action middleware
self.matchedAction.run(self.request, self.reply, err =>
self._afterMiddlewareHandler(err)
)
}
/**
*
*
* @param {any} err
* @memberof Hemera
*/
_afterMiddlewareHandler(err) {
const self = this
if (err) {
const internalError = new Errors.HemeraError(
'Action middleware',
self.errorDetails
).causedBy(err)
self.log.error(internalError)
self.emit('serverResponseError', err)
self.reply.isError = true
self.reply.send(err)
return
}
const result = self._processServerAction()
const isPromise = result && typeof result.then === 'function'
if (isPromise) {
// avoid to create a seperate promise
// eslint-disable-next-line promise/catch-or-return
result.then(
payload => self.reply.send(payload),
err => {
self.reply.isError = true
self.reply.send(err)
}
)
}
}
/**
*
*
* @returns
* @memberof Hemera
*/
_processServerAction() {
const self = this
let action = self.matchedAction.action.bind(self)
// if request type is 'pubsub' we don't have to reply back
if (self.request.payload.request.type === 'pubsub') {
action(self.request.payload.pattern)
self.reply.send()
return
}
return action(self.request.payload.pattern, (err, result) => {
if (err) {
self.reply.isError = true
self.reply.send(err)
return
}
self.reply.send(result)
})
}
/**
* Unsubscribe a topic or subscription id from NATS and Hemera
*
* @param {any} topic