forked from senecajs/seneca
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathseneca.js
1525 lines (1232 loc) · 38.1 KB
/
seneca.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
/* Copyright © 2010-2018 Richard Rodger and other contributors, MIT License. */
'use strict'
// Node API modules.
var Assert = require('assert')
var Events = require('events')
var Util = require('util')
// External modules.
var _ = require('lodash')
var GateExecutor = require('gate-executor')
var Jsonic = require('jsonic')
var UsePlugin = require('use-plugin')
var Nid = require('nid')
var Norma = require('norma')
var Patrun = require('patrun')
var Stats = require('rolling-stats')
var Ordu = require('ordu')
var Eraro = require('eraro')
// Internal modules.
var API = require('./lib/api')
var Inward = require('./lib/inward')
var Outward = require('./lib/outward')
var Common = require('./lib/common')
var Legacy = require('./lib/legacy')
var Optioner = require('./lib/optioner')
var Package = require('./package.json')
var Plugins = require('./lib/plugins')
var Print = require('./lib/print')
var Actions = require('./lib/actions')
var Transport = require('./lib/transport')
// Shortcuts.
var errlog = Common.make_standard_err_log_entry
var actlog = Common.make_standard_act_log_entry
// Internal data and utilities.
var error = Common.error
var option_defaults = {
// Tag this Seneca instance, will be appended to instance identifier.
tag: '-',
// Standard timeout for actions.
timeout: 22222,
// Standard length of identifiers for actions.
idlen: 12,
didlen: 4,
// Register (true) default plugins. Set false to not register when
// using custom versions.
default_plugins: {
transport: true
},
// Test mode. Use for unit testing.
test: false,
// Wait time for plugins to close gracefully.
death_delay: 11111,
// Wait time for actions to complete before shutdown.
close_delay: 22222,
// Debug settings.
debug: {
// Throw (some) errors from seneca.act.
fragile: false,
// Fatal errors ... aren't fatal. Not for production!
undead: false,
// Print debug info to console
print: {
// Print options. Best used via --seneca.print.options.
options: false,
// Amount of information to print on fatal error: 'summary', 'full'
fatal: 'summary',
// Include environment when printing full crash report.
// Default: false for security.
env: false
},
// Trace action caller and place in args.caller$.
act_caller: false,
// Shorten all identifiers to 2 characters.
short_logs: false,
// Record and log callpoints (calling code locations).
callpoint: false,
// Log deprecation warnings
deprecation: true,
// Set to array to force artificial argv and ignore process.argv
argv: null,
// Length of data description in logs
datalen: 111
},
// Enforce strict behaviours. Relax when backwards compatibility needed.
strict: {
// Action result must be a plain object.
result: true,
// Delegate fixedargs override action args.
fixedargs: true,
// Adding a pattern overrides existing pattern only if matches exactly.
add: false,
// If no action is found and find is false,
// then no error returned along with empty object
find: true,
// Maximum number of times an action can call itself
maxloop: 11,
// Exports must exist
exports: false
},
// Keep a transient time-ordered history of actions submitted
history: {
// History log is active.
active: true,
// Prune the history. Disable only for debugging.
prune: true,
// Prune the history only periodically.
interval: 100
},
// Action executor tracing. See gate-executor module.
trace: {
act: false,
stack: false,
// Messages that do not match a known pattern
unknown: true,
// Messages that have invalid content
invalid: false
},
// Action statistics settings. See rolling-stats module.
stats: {
size: 1024,
interval: 60000,
running: false
},
// Plugin settings
plugin: {},
// Plugins to load (will be passed to .use)
plugins: [],
// System wide functionality.
system: {
exit: process.exit,
// Close instance on these signals, if true.
close_signals: {
SIGHUP: false,
SIGTERM: false,
SIGINT: false,
SIGBREAK: false
},
plugin: {
load_once: false
}
},
// Internal functionality. Reserved for objects and functions only.
internal: {},
// Log status at periodic intervals.
status: {
interval: 60000,
// By default, does not run.
running: false
},
// Shared default transport configuration
transport: {
// Standard port for messages.
port: 10101
},
limits: {
maxparents: 33
},
// Setup event listeners before starting
events: {},
// Backwards compatibility settings.
legacy: {
// Action callback must always have signature callback(error, result).
action_signature: false,
// Logger can be changed by options method.
logging: false,
// Use old error codes. REMOVE in Seneca 4.x
error_codes: false,
// Use old error handling.
error: true,
// Use seneca-transport plugin.
transport: true,
// Add meta$ property to messages.
meta: false,
// Add legacy properties
actdef: false,
// Use old fail method
fail: false
}
}
// Utility functions exposed by Seneca via `seneca.util`.
var seneca_util = {
Eraro: Eraro,
Jsonic: Jsonic,
Nid: Nid,
Patrun: Patrun,
Joi: UsePlugin.Joi,
Optioner: UsePlugin.Optioner,
clean: Common.clean,
pattern: Common.pattern,
print: Common.print,
error: error,
// Legacy
deepextend: Common.deepextend,
recurse: Common.recurse,
copydata: Common.copydata,
nil: Common.nil,
parsepattern: Common.parsePattern,
pincanon: Common.pincanon,
router: function router() {
return Patrun()
},
resolve_option: Common.resolve_option,
flatten: Common.flatten,
argprops: Legacy.argprops
}
// Internal implementations.
var intern = {
util: seneca_util
}
// Seneca is an EventEmitter.
function Seneca() {
Events.EventEmitter.call(this)
this.setMaxListeners(0)
}
Util.inherits(Seneca, Events.EventEmitter)
// Create a Seneca instance.
module.exports = function init(seneca_options, more_options) {
var initial_options = _.isString(seneca_options)
? _.extend({}, { from: seneca_options }, more_options)
: _.extend({}, seneca_options, more_options)
// Legacy options, remove in 4.x
initial_options.deathdelay = initial_options.death_delay
var seneca = make_seneca(initial_options)
var options = seneca.options()
// The 'internal' key of options is reserved for objects and functions
// that provide functionality, and are thus not really printable
seneca.log.debug({ kind: 'notice', options: _.omit(options, ['internal']) })
Print.print_options(seneca, options)
// Register default plugins, unless turned off by options.
if (options.legacy.transport && options.default_plugins.transport) {
seneca.use(require('seneca-transport'))
}
// Register plugins specified in options.
var pluginkeys = Object.keys(options.plugins)
for (var pkI = 0; pkI < pluginkeys.length; pkI++) {
var pluginkey = pluginkeys[pkI]
var plugindesc = options.plugins[pluginkey]
if (false === plugindesc) {
seneca.private$.ignore_plugins[pluginkey] = true
} else {
seneca.use(plugindesc)
}
}
seneca.ready(function() {
this.log.info({ kind: 'notice', notice: 'hello seneca ' + seneca.id })
})
return seneca
}
// Expose Seneca prototype for easier monkey-patching
module.exports.Seneca = Seneca
// To reference builtin loggers when defining logging options.
module.exports.loghandler = Legacy.loghandler
// Makes require('seneca').use(...) work by creating an on-the-fly instance.
module.exports.use = function top_use() {
var argsarr = new Array(arguments.length)
for (var l = 0; l < argsarr.length; ++l) {
argsarr[l] = arguments[l]
}
var instance = module.exports()
return instance.use.apply(instance, argsarr)
}
// Makes require('seneca').test() work.
module.exports.test = function top_test() {
return module.exports().test(arguments[0], arguments[1])
}
module.exports.util = seneca_util
module.exports.test$ = { intern: intern }
// Create a new Seneca instance.
// * _initial_options_ `o` → instance options
function make_seneca(initial_options) {
initial_options = initial_options || {}
// Create a private context.
var private$ = make_private()
private$.error = error
// Create a new root Seneca instance.
var root$ = new Seneca()
// Expose private data to plugins.
root$.private$ = private$
// Resolve initial options.
private$.optioner = Optioner(module, option_defaults, initial_options)
var opts = { $: private$.optioner.get() }
// Setup event handlers, if defined
;['log', 'act_in', 'act_out', 'act_err', 'ready', 'close'].forEach(function(
event_name
) {
if ('function' === typeof opts.$.events[event_name]) {
root$.on(event_name, opts.$.events[event_name])
}
})
// Create internal tools.
private$.actnid = Nid({ length: opts.$.idlen })
private$.didnid = Nid({ length: opts.$.didlen })
var next_action_id = Common.autoincr()
// These need to come from options as required during construction.
opts.$.internal.actrouter = opts.$.internal.actrouter || Patrun({ gex: true })
opts.$.internal.subrouter = opts.$.internal.subrouter || Patrun({ gex: true })
var callpoint = make_callpoint(opts.$.debug.callpoint)
// Define public member variables.
root$.start_time = Date.now()
root$.context = {}
root$.version = Package.version
// TODO: rename in 4.x as "args" terminology is legacy
root$.fixedargs = {}
root$.flags = {
closed: false
}
Object.defineProperty(root$, 'root', { value: root$ })
private$.history = Common.history(opts.$.history)
// Seneca methods. Official API.
root$.has = API.has // True if the given pattern has an action.
root$.find = API.find // Find the action definition for a pattern.
root$.list = API.list // List the patterns added to this instance.
root$.status = API.status // Get the status if this instance.
root$.reply = API.reply // Reply to a submitted message.
root$.sub = API.sub // Subscribe to messages.
root$.list_plugins = API.list_plugins // List the registered plugins.
root$.find_plugin = API.find_plugin // Find the plugin definition.
root$.has_plugin = API.has_plugin // True if the plugin is registered.
root$.ignore_plugin = API.ignore_plugin // Ignore plugin and don't register it.
root$.listen = API.listen(callpoint) // Listen for inbound messages.
root$.client = API.client(callpoint) // Send outbound messages.
root$.gate = API.gate // Create a delegate that executes actions in sequence.
root$.ungate = API.ungate // Execute actions in parallel.
root$.translate = API.translate // Translate message to new pattern.
root$.ping = API.ping // Generate ping response.
root$.use = API.use // Define and load a plugin.
root$.test = API.test // Set test mode.
root$.quiet = API.quiet // Convenience method to set logging level to `warn+`.
root$.export = API.export // Export plain objects from a plugin.
root$.depends = API.depends // Check for plugin dependencies.
root$.delegate = API.delegate // Create an action-specific Seneca instance.
root$.prior = API.prior // Call the previous action definition for message pattern.
root$.inward = API.inward // Add a modifier function for messages inward
root$.outward = API.outward // Add a modifier function for responses outward
root$.error = API.error // Set global error handler, or generate Seneca Error
root$.fail = opts.$.legacy.fail ? Legacy.make_legacy_fail(opts.$) : API.fail // Throw a Seneca error
root$.add = api_add // Add a pattern an associated action.
root$.act = api_act // Submit a message and trigger the associated action.
root$.ready = api_ready // Callback when plugins initialized.
root$.close = api_close // Close and shutdown plugins.
root$.options = api_options // Get and set options.
root$.decorate = api_decorate // Decorate seneca object with functions
// Non-API methods.
root$.register = Plugins.register(opts, callpoint)
root$.wrap = api_wrap
root$.seneca = api_seneca
root$.fix = api_fix
// DEPRECATE IN 4.x
root$.findact = root$.find
root$.plugins = API.list_plugins
root$.findplugin = API.find_plugin
root$.hasplugin = API.has_plugin
root$.hasact = Legacy.hasact
root$.act_if = Legacy.act_if
root$.findpins = Legacy.findpins
root$.pinact = Legacy.findpins
root$.next_act = Legacy.next_act
// Identifier generator.
root$.idgen = Nid({ length: opts.$.idlen })
opts.$.tag = opts.$.tag || option_defaults.tag
opts.$.tag = opts.$.tag === 'undefined' ? option_defaults.tag : opts.$.tag
// Create a unique identifer for this instance.
root$.id =
opts.$.id$ ||
root$.idgen() +
'/' +
root$.start_time +
'/' +
process.pid +
'/' +
root$.version +
'/' +
opts.$.tag
// The instance tag, useful for grouping instances.
root$.tag = opts.$.tag
if (opts.$.debug.short_logs || opts.$.log.short) {
opts.$.idlen = 2
root$.idgen = Nid({ length: opts.$.idlen })
root$.id = root$.idgen() + '/' + opts.$.tag
}
root$.fullname = 'Seneca/' + root$.id
root$.die = Common.makedie(root$, {
type: 'sys',
plugin: 'seneca',
tag: root$.version,
id: root$.id,
callpoint: callpoint
})
root$.util = seneca_util
private$.exports = { options: opts.$ }
private$.decorations = {}
// Configure logging
private$.logger = load_logger(root$, opts.$.internal.logger)
root$.make_log = make_log
root$.log = make_log(root$, make_default_log_modifier(root$))
// Error events are fatal, unless you're undead. These are not the
// same as action errors, these are unexpected internal issues.
root$.on('error', root$.die)
private$.ge = GateExecutor({
timeout: opts.$.timeout
})
.clear(action_queue_clear)
.start()
// TODO: this should be a plugin
// setup status log
if (opts.$.status.interval > 0 && opts.$.status.running) {
private$.stats = private$.stats || {}
private$.status_interval = setInterval(function status() {
root$.log.info({
kind: 'status',
alive: Date.now() - private$.stats.start,
act: private$.stats.act
})
}, opts.$.status.interval)
}
if (opts.$.stats) {
private$.timestats = new Stats.NamedStats(
opts.$.stats.size,
opts.$.stats.interval
)
if (opts.$.stats.running) {
setInterval(function stats() {
private$.timestats.calculate()
}, opts.$.stats.interval)
}
}
// private$.plugins = {}
private$.plugin_order = { byname: [], byref: [] }
private$.use = UsePlugin({
prefix: ['seneca-', '@seneca/'],
module: opts.$.internal.module || module,
msgprefix: false,
builtin: '',
merge_defaults: false
})
private$.actrouter = opts.$.internal.actrouter
private$.subrouter = opts.$.internal.subrouter
root$.toString = api_toString
// TODO: provide an api to add these
private$.action_modifiers = [
function add_rules_from_validate_annotation(actdef) {
actdef.rules = Object.assign(
actdef.rules,
_.clone(actdef.func.validate || {})
)
}
]
private$.sub = { handler: null, tracers: [] }
private$.ready_list = []
private$.inward = Ordu({ name: 'inward' })
.add(Inward.msg_modify)
.add(Inward.closed)
.add(Inward.act_cache)
.add(Inward.act_default)
.add(Inward.act_not_found)
.add(Inward.act_stats)
.add(Inward.validate_msg)
.add(Inward.warnings)
.add(Inward.msg_meta)
.add(Inward.limit_msg)
.add(Inward.prepare_delegate)
.add(Inward.announce)
private$.outward = Ordu({ name: 'outward' })
.add(Outward.make_error)
.add(Outward.act_stats)
.add(Outward.act_cache)
.add(Outward.res_object)
.add(Outward.res_entity)
.add(Outward.msg_meta)
.add(Outward.trace)
.add(Outward.announce)
.add(Outward.act_error)
if (opts.$.test) {
root$.test('string' === typeof opts.$.test ? opts.$.test : 'print')
}
// See [`seneca.add`](#seneca.add)
function api_add() {
var self = this
var args = Common.parsePattern(self, arguments, 'action:f? actdef:o?')
var raw_pattern = args.pattern
var pattern = self.util.clean(raw_pattern)
var action =
args.action ||
function default_action(msg, done, meta) {
done.call(this, null, meta.dflt || null)
}
var actdef = args.actdef || {}
actdef.raw = _.cloneDeep(raw_pattern)
actdef.plugin_name = actdef.plugin_name || 'root$'
actdef.plugin_fullname =
actdef.plugin_fullname ||
actdef.plugin_name +
((actdef.plugin_tag === '-'
? void 0
: actdef.plugin_tag)
? '$' + actdef.plugin_tag
: '')
actdef.plugin = {
name: actdef.plugin_name,
tag: actdef.plugin_tag,
fullname: actdef.plugin_fullname
}
var add_callpoint = callpoint()
if (add_callpoint) {
actdef.callpoint = add_callpoint
}
actdef.sub = !!raw_pattern.sub$
actdef.client = !!raw_pattern.client$
// Deprecate a pattern by providing a string message using deprecate$ key.
actdef.deprecate = raw_pattern.deprecate$
actdef.fixed = Jsonic(raw_pattern.fixed$ || {})
actdef.custom = Jsonic(raw_pattern.custom$ || {})
var strict_add =
raw_pattern.strict$ && raw_pattern.strict$.add !== null
? !!raw_pattern.strict$.add
: !!opts.$.strict.add
var addroute = true
if (opts.$.legacy.actdef) {
actdef.args = _.clone(pattern)
}
actdef.id = action.name + '_' + next_action_id()
actdef.name = action.name
actdef.func = action
// Canonical string form of the action pattern.
actdef.pattern = Common.pattern(pattern)
// Canonical object form of the action pattern.
actdef.msgcanon = Jsonic(actdef.pattern)
var priordef = self.find(pattern)
if (priordef && strict_add && priordef.pattern !== actdef.pattern) {
// only exact action patterns are overridden
// use .wrap for pin-based patterns
priordef = null
}
if (priordef) {
// Clients needs special handling so that the catchall
// pattern does not submit all patterns into the handle
if (
_.isFunction(priordef.handle) &&
((priordef.client && actdef.client) ||
(!priordef.client && !actdef.client))
) {
priordef.handle(args.pattern, action)
addroute = false
} else {
actdef.priordef = priordef
}
actdef.priorpath = priordef.id + ';' + priordef.priorpath
} else {
actdef.priorpath = ''
}
if (action && actdef && _.isFunction(action.handle)) {
actdef.handle = action.handle
}
private$.stats.actmap[actdef.pattern] =
private$.stats.actmap[actdef.pattern] || make_action_stats(actdef)
var pattern_rules = {}
_.each(pattern, function(v, k) {
if (_.isObject(v)) {
pattern_rules[k] = _.clone(v)
delete pattern[k]
}
})
actdef.rules = pattern_rules
if (addroute) {
self.log.debug({
kind: 'add',
case: actdef.sub ? 'SUB' : 'ADD',
id: actdef.id,
pattern: actdef.pattern,
name: action.name,
callpoint: callpoint
})
private$.actrouter.add(pattern, actdef)
}
private$.actdef[actdef.id] = actdef
deferred_modify_action(self, actdef)
return self
}
function make_action_stats(actdef) {
return {
id: actdef.id,
plugin: {
full: actdef.plugin_fullname,
name: actdef.plugin_name,
tag: actdef.plugin_tag
},
prior: actdef.priorpath,
calls: 0,
done: 0,
fails: 0,
time: {}
}
}
// NOTE: use setImmediate so that action annotations (such as .validate)
// can be defined after call to seneca.add (for nicer plugin code order).
function deferred_modify_action(seneca, actdef) {
setImmediate(function() {
_.each(seneca.private$.action_modifiers, function(actmod) {
actmod.call(seneca, actdef)
})
})
}
// Perform an action. The properties of the first argument are matched against
// known patterns, and the most specific one wins.
function api_act() {
var argsarr = new Array(arguments.length)
for (var l = 0; l < argsarr.length; ++l) {
argsarr[l] = arguments[l]
}
var self = this
var spec = Common.build_message(self, argsarr, 'reply:f?', self.fixedargs)
var msg = spec.msg
var reply = spec.reply
if (opts.$.debug.act_caller || opts.$.test) {
msg.caller$ =
'\n Action call arguments and location: ' +
(new Error(Util.inspect(msg).replace(/\n/g, '')).stack + '\n')
.replace(/Error: /, '')
.replace(/.*\/gate-executor\.js:.*\n/g, '')
.replace(/.*\/seneca\.js:.*\n/g, '')
.replace(/.*\/seneca\/lib\/.*\.js:.*\n/g, '')
}
do_act(self, msg, reply)
return self
}
function api_wrap(pin, meta, wrapper) {
var pinthis = this
wrapper = _.isFunction(meta) ? meta : wrapper
meta = _.isFunction(meta) ? {} : meta
pin = _.isArray(pin) ? pin : [pin]
_.each(pin, function(p) {
_.each(pinthis.list(p), function(actpattern) {
pinthis.add(actpattern, meta, wrapper)
})
})
return this
}
private$.handle_close = function() {
root$.close(function(err) {
if (err) {
Print.err(err)
}
opts.$.system.exit(err ? (err.exit === null ? 1 : err.exit) : 0)
})
}
// close seneca instance
// sets public seneca.closed property
function api_close(done) {
var seneca = this
var safe_done = _.once(function(err) {
if (_.isFunction(done)) {
return done.call(seneca, err)
}
})
// don't try to close twice
if (seneca.flags.closed) {
return safe_done()
}
seneca.ready(do_close)
var close_timeout = setTimeout(do_close, opts.$.close_delay)
function do_close() {
clearTimeout(close_timeout)
if (seneca.flags.closed) {
return safe_done()
}
// TODO: remove in 4.x
seneca.closed = true
seneca.flags.closed = true
// cleanup process event listeners
_.each(opts.$.system.close_signals, function(active, signal) {
if (active) {
process.removeListener(signal, private$.handle_close)
}
})
seneca.log.debug({
kind: 'close',
notice: 'start',
callpoint: callpoint()
})
seneca.act('role:seneca,cmd:close,closing$:true', function(err) {
seneca.log.debug(errlog(err, { kind: 'close', notice: 'end' }))
seneca.removeAllListeners('act-in')
seneca.removeAllListeners('act-out')
seneca.removeAllListeners('act-err')
seneca.removeAllListeners('pin')
seneca.removeAllListeners('after-pin')
seneca.removeAllListeners('ready')
seneca.private$.history.close()
if (seneca.private$.status_interval) {
clearInterval(seneca.private$.status_interval)
}
return safe_done(err)
})
}
return seneca
}
// useful when defining services!
// note: has EventEmitter.once semantics
// if using .on('ready',fn) it will be be called for each ready event
function api_ready(ready) {
var self = this
if ('function' === typeof ready) {
setImmediate(function register_ready() {
if (root$.private$.ge.isclear()) {
execute_ready(ready.bind(self))
} else {
root$.private$.ready_list.push(ready.bind(self))
}
})
}
return self
}
// Return self. Mostly useful as a check that this is a Seneca instance.
function api_seneca() {
return this
}
// Describe this instance using the form: Seneca/VERSION/ID
function api_toString() {
return this.fullname
}
function do_act(instance, origmsg, origreply) {
var timedout = false
var actmsg = intern.make_actmsg(origmsg)
var meta = new intern.Meta(instance, opts, origmsg, origreply)
if (meta.gate) {
instance = instance.delegate()
instance.private$.ge = instance.private$.ge.gate()
}
var actctxt = {
seneca: instance,
origmsg: origmsg,
reply: origreply || _.noop,
options: instance.options(),
callpoint: callpoint()
}
var execspec = {
dn: meta.id,
fn: function act_fn(done) {
try {
intern.execute_action(
instance,
opts,
actctxt,
actmsg,
meta,
function action_reply(err, out, reply_meta) {
if (!timedout) {
intern.handle_reply(meta, actctxt, actmsg, err, out, reply_meta)
}
done()
}
)
} catch (e) {
var ex = Util.isError(e) ? e : new Error(Util.inspect(e))
intern.handle_reply(meta, actctxt, actmsg, ex)
done()
}
},
ontm: function act_tm() {
timedout = true
intern.handle_reply(meta, actctxt, actmsg, new Error('[TIMEOUT]'))
},
tm: meta.timeout
}
instance.private$.ge.add(execspec)
}
function api_fix(patargs, msgargs, custom) {
var self = this
// var defargs = Common.parsePattern(self, arguments)
patargs = Jsonic(patargs || {})
var fix_delegate = self.delegate(patargs)
fix_delegate.add = function fix_add() {
var args = Common.parsePattern(this, arguments, 'rest:.*', patargs)
var addargs = [args.pattern]
.concat({
fixed$: Object.assign({}, msgargs, args.pattern.fixed$),
custom$: Object.assign({}, custom, args.pattern.custom$)
})
.concat(args.rest)
return self.add.apply(this, addargs)
}
return fix_delegate
}
function api_options(options, chain) {
var self = this
if (options != null) {
self.log.debug({
kind: 'options',
case: 'SET',
options: options,
callpoint: callpoint()
})
}
opts.$ = private$.exports.options =
options == null ? private$.optioner.get() : private$.optioner.set(options)
if (opts.$.legacy.logging) {
if (options && options.log && _.isArray(options.log.map)) {
for (var i = 0; i < options.log.map.length; ++i) {
self.logroute(options.log.map[i])
}
}
}
// TODO: in 4.x, when given options, it should chain
// Allow chaining with seneca.options({...}, true)
// see https://github.com/rjrodger/seneca/issues/80