-
Notifications
You must be signed in to change notification settings - Fork 314
/
seneca.js
1625 lines (1311 loc) · 42.3 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 (c) 2010-2016 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 Eraro = require('eraro')
var Jsonic = require('jsonic')
var Lrucache = require('lru-cache')
var Makeuse = require('use-plugin')
var Nid = require('nid')
var Norma = require('norma')
var Patrun = require('patrun')
var Parambulator = require('parambulator')
var Stats = require('rolling-stats')
var Zig = require('zig')
var DelayedOpenQueue = require('delayed-open-queue')
// Internal modules.
var Actions = require('./lib/actions')
var Common = require('./lib/common')
var Errors = require('./lib/errors')
var Logging = require('./lib/logging')
var Optioner = require('./lib/optioner')
var Package = require('./package.json')
var Plugins = require('./lib/plugins')
var Print = require('./lib/print')
var Store = require('./lib/store')
var Transport = require('./lib/transport')
// Shortcuts
var arrayify = Function.prototype.apply.bind(Array.prototype.slice)
var internals = {
error: Eraro({
package: 'seneca',
msgmap: Errors,
override: true
}),
schema: Parambulator({
tag: { string$: true },
idlen: { integer$: true },
timeout: { integer$: true },
errhandler: { function$: true }
}, {
topname: 'options',
msgprefix: 'seneca({...}): '
}),
defaults: {
// Tag this Seneca instance, will be appended to instance identifier.
tag: '-',
// Standard length of identifiers for actions.
idlen: 12,
// Standard timeout for actions.
timeout: 11111,
// Register (true) default plugins. Set false to not register when
// using custom versions.
default_plugins: {
basic: true,
cluster: true,
'mem-store': true,
repl: true,
transport: true,
web: true
},
// Debug settings.
debug: {
// Throw (some) errors from seneca.act.
fragile: false,
// Print debug info to console
print: {
// Print options. Best used via --seneca.print.options.
options: false
},
// Trace action caller and place in args.caller$.
act_caller: false,
// Shorten all identifiers to 2 characters.
short_logs: false
},
// 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
},
// Action cache. Makes inbound messages idempotent.
actcache: {
active: true,
size: 11111
},
// Action executor tracing. See gate-executor module.
trace: {
act: false,
stack: false,
unknown: 'warn'
},
// Action statistics settings. See rolling-stats module.
stats: {
size: 1024,
interval: 60000,
running: false
},
// Wait time for plugins to close gracefully.
deathdelay: 11111,
// Default seneca-admin settings.
// TODO: move to seneca-admin!
admin: {
local: false,
prefix: '/admin'
},
// Plugin settings
plugin: {},
// Internal settings.
internal: {
// seneca.add uses catchall (pattern='') prior
catchall: false
},
// Log status at periodic intervals.
status: {
interval: 60000,
// By default, does not run.
running: false
},
// zig module settings for seneca.start() chaining.
zig: {},
pin: {
// run pin function without waiting for pin event
immediate: false
}
}
}
// Seneca is an EventEmitter.
function Seneca () {
Events.EventEmitter.call(this)
this.setMaxListeners(0)
}
Util.inherits(Seneca, Events.EventEmitter)
module.exports = function init (seneca_options, more_options) {
// Create instance.
var seneca = make_seneca(_.extend({}, seneca_options, more_options))
var options = seneca.options()
// FIX: plugin decorations do need to be sync
// needs thinking
seneca.decorate('hasplugin', Plugins.api_decorations.hasplugin)
seneca.decorate('findplugin', Plugins.api_decorations.findplugin)
seneca.decorate('plugins', Plugins.api_decorations.plugins)
// HACK: makes this sync
if (options.default_plugins.cluster) {
require('seneca-cluster').call(seneca, {})
}
// HACK: makes this sync
if (options.default_plugins.repl) {
require('seneca-repl').call(seneca, options.repl)
}
// Register default plugins, unless turned off by options.
if (options.default_plugins.basic) { seneca.use(require('seneca-basic')) }
if (options.default_plugins['mem-store']) { seneca.use(require('seneca-mem-store')) }
if (options.default_plugins.transport) { seneca.use(require('seneca-transport')) }
if (options.default_plugins.web) { seneca.use(require('seneca-web')) }
// Register plugins specified in options.
_.each(options.plugins, function (plugindesc) {
seneca.use(plugindesc)
})
return seneca
}
// Expose Seneca prototype for easier monkey-patching
module.exports.Seneca = Seneca
// To reference builtin loggers when defining logging options.
module.exports.loghandler = Logging.handlers
// Makes require('seneca').use(...) work by creating an on-the-fly instance.
module.exports.use = function () {
var instance = module.exports()
return instance.use.apply(instance, arrayify(arguments))
}
// Mostly for testing.
if (require.main === module) {
module.exports()
}
// Create a new Seneca instance.
// * _initial_options_ `o` → instance options
function make_seneca (initial_options) {
initial_options = initial_options || {} // ensure defined
// Create a private context.
var private$ = make_private()
// Create a new root Seneca instance.
var root = new Seneca()
// Create a loading queue to bootstrap safely
// every use, add and act done in the starting
// tick will be queued and executed one at a time
var loadingQueue = DelayedOpenQueue()
// expose private for plugins
root.private$ = private$
// Create option resolver.
private$.optioner = Optioner(
initial_options.module || module.parent || module,
internals.defaults)
// Not needed after this point, and screws up debug printing.
delete initial_options.module
// Define options
var so = private$.optioner.set(initial_options)
internals.schema.validate(so, function (err) {
if (err) {
throw err
}
})
// Create internal tools.
var actnid = Nid({length: so.idlen})
var refnid = function () { return '(' + actnid() + ')' }
// These need to come from options as required during construction.
so.internal.actrouter = so.internal.actrouter || Patrun({ gex: true })
so.internal.subrouter = so.internal.subrouter || Patrun({ gex: true })
// Define public member variables.
root.root = root
root.start_time = Date.now()
root.fixedargs = {}
root.context = {}
root.version = Package.version
// Seneca methods. Official API.
root.add = api_add // Add a message pattern and action.
root.act = api_act // Perform action that matches pattern.
root.sub = api_sub // Subscribe to a message pattern.
root.use = api_use // Define a plugin.
root.listen = Transport.listen() // Listen for inbound messages.
root.client = Transport.client() // Send outbound messages.
root.export = api_export // Export plain objects from a plugin.
root.has = Actions.has // True if action pattern defined.
root.find = Actions.find // Find action by pattern
root.list = Actions.list // List (a subset of) action patterns.
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.start = api_start // Start an action chain.
root.decorate = api_decorate // Decorate seneca object with functions
// Method aliases.
root.hasact = root.has
// Non-API methods.
root.logroute = api_logroute
root.register = Plugins.register(so)
root.depends = api_depends
root.pin = api_pin
root.act_if = api_act_if
root.wrap = api_wrap
root.seneca = api_seneca
root.delegate = api_delegate
// Legacy API; Deprecated.
root.findact = root.find
// Identifier generator.
root.idgen = Nid({length: so.idlen})
so.tag = so.tag || internals.defaults.tag
so.tag = so.tag === 'undefined' ? internals.defaults.tag : so.tag
// Create a unique identifer for this instance.
root.id = root.idgen() + '/' + root.start_time + '/' + process.pid + '/' + so.tag
if (so.debug.short_logs || so.log.short) {
so.idlen = 2
root.idgen = Nid({length: so.idlen})
root.id = root.idgen() + '/' + so.tag
}
root.name = 'Seneca/' + root.version + '/' + root.id
// Configure logging
root.log = Logging.makelog(so.log, {
id: root.id,
start: root.start_time,
short: !!so.debug.short_logs
})
// setup status log
if (so.status.interval > 0 && so.status.running) {
private$.stats = private$.stats || {}
setInterval(function () {
var status = {
alive: (Date.now() - private$.stats.start),
act: private$.stats.act
}
root.log.info('status', status)
}, so.status.interval)
}
if (so.stats) {
private$.timestats = new Stats.NamedStats(so.stats.size, so.stats.interval)
if (so.stats.running) {
setInterval(function () {
private$.timestats.calculate()
}, so.stats.interval)
}
}
private$.plugins = {}
private$.exports = { options: Common.deepextend({}, so) }
private$.plugin_order = { byname: [], byref: [] }
private$.use = Makeuse({
prefix: 'seneca-',
module: module,
msgprefix: false,
builtin: ''
})
private$.actcache = (so.actcache.active
? Lrucache({ max: so.actcache.size })
: { set: _.noop })
private$.actrouter = so.internal.actrouter
private$.subrouter = so.internal.subrouter
root.toString = api_toString
root.util = {
deepextend: Common.deepextend,
recurse: Common.recurse,
clean: Common.clean,
copydata: Common.copydata,
nil: Common.nil,
pattern: Common.pattern,
print: Common.print,
pincanon: Common.pincanon,
router: function () { return Patrun() },
// TODO: deprecate?
argprops: Common.argprops
}
root.store = Store()
// Used for extending seneca with api_decorate
root._decorations = {}
// say hello, printing identifier to log
root.log.info('hello')
// dump options if debugging
root.log.debug('options', function () {
return Util.inspect(so, false, null).replace(/[\r\n]/g, ' ')
})
if (so.debug.print.options) {
console.log('\nSeneca Options (' + root.id + '): before plugins\n' + '===\n')
console.log(Util.inspect(so, { depth: null }))
console.log('')
}
function api_logroute (entry, handler) {
if (arguments.length === 0) {
return root.log.router.toString()
}
entry.handler = handler || entry.handler
Logging.makelogroute(entry, root.log.router)
}
function api_depends () {
var self = this
var args = Norma('{pluginname:s deps:a? moredeps:s*}', arguments)
var deps = args.deps || args.moredeps
_.every(deps, function (depname) {
if (!_.includes(private$.plugin_order.byname, depname) &&
!_.includes(private$.plugin_order.byname, 'seneca-' + depname)) {
self.emit('error', internals.error('plugin_required', { name: args.pluginname, dependency: depname }))
return false
}
else return true
})
}
function api_export (key) {
// Legacy aliases
if (key === 'util') {
key = 'basic'
}
var exportval = private$.exports[key]
if (!exportval) {
throw internals.error('export_not_found', {key: key})
}
return exportval
}
// TODO: DEPRECATE
function api_pin (pattern, pinopts) {
var thispin = this
pattern = _.isString(pattern) ? Jsonic(pattern) : pattern
var methodkeys = []
for (var key in pattern) {
if (/[\*\?]/.exec(pattern[key])) {
methodkeys.push(key)
}
}
function make_pin (pattern) {
var api = {
toString: function () {
return 'pin:' + Common.pattern(pattern) + '/' + thispin
}
}
var calcPin = function () {
var methods = private$.actrouter.list(pattern)
methods.forEach(function (method) {
var mpat = method.match
var methodname = ''
for (var mkI = 0; mkI < methodkeys.length; mkI++) {
methodname += ((mkI > 0 ? '_' : '')) + mpat[methodkeys[mkI]]
}
api[methodname] = function (args, cb) {
var si = this && this.seneca ? this : thispin
var fullargs = _.extend({}, args, mpat)
si.act(fullargs, cb)
}
api[methodname].pattern$ = method.match
api[methodname].name$ = methodname
})
if (pinopts && pinopts.include) {
for (var i = 0; i < pinopts.include.length; i++) {
var methodname = pinopts.include[i]
if (thispin[methodname]) {
api[methodname] = Common.delegate(thispin, thispin[methodname])
}
}
}
}
var opts = {}
_.defaults(opts, pinopts, so.pin)
if (private$._isReady || opts.immediate) {
calcPin()
}
else {
root.once('pin', calcPin)
}
return api
}
return make_pin(pattern)
}
var pm_custom_args = {
rules: {
entity$: function (ctxt, cb) {
var val = ctxt.point
if (val.entity$) {
if (val.canon$({isa: ctxt.rule.spec})) {
return cb()
}
else return ctxt.util.fail(ctxt, cb)
}
else return ctxt.util.fail(ctxt, cb)
}
},
msgs: {
entity$: 'The value <%=value%> is not a data entity of kind <%=rule.spec%>' +
' (property <%=parentpath%>).'
}
}
function api_sub () {
var self = this
var subargs = Common.parsePattern(self, arguments, 'action:f actmeta:o?')
var pattern = subargs.pattern
if (pattern.in$ == null &&
pattern.out$ == null &&
pattern.error$ == null &&
pattern.cache$ == null &&
pattern.default$ == null &&
pattern.client$ == null) {
pattern.in$ = true
}
if (!private$.handle_sub) {
private$.handle_sub = function (args, result) {
args.meta$ = args.meta$ || {}
if (args.meta$.entry !== true) {
return
}
var subfuncs = private$.subrouter.find(args)
if (subfuncs) {
args.meta$.sub = subfuncs.pattern
_.each(subfuncs, function (subfunc) {
subfunc.call(self, args, result)
})
}
}
// TODO: other cases
// Subs are triggered via events
self.on('act-in', annotate('in$', private$.handle_sub))
self.on('act-out', annotate('out$', private$.handle_sub))
}
function annotate (prop, handle_sub) {
return function (args, result) {
args = _.clone(args)
result = _.clone(result)
args[prop] = true
handle_sub(args, result)
}
}
var subs = private$.subrouter.find(pattern)
if (!subs) {
private$.subrouter.add(pattern, subs = [])
subs.pattern = Common.pattern(pattern)
}
subs.push(subargs.action)
return self
}
// ### seneca.add
// Add an message pattern and action function.
//
// `seneca.add(pattern, action)`
// * _pattern_ `o|s` → pattern definition
// * _action_ `f` → pattern action function
//
// `seneca.add(pattern_string, pattern_object, action)`
// * _pattern_string_ `s` → pattern definition as jsonic string
// * _pattern_object_ `o` → pattern definition as object
// * _action_ `f` → pattern action function
//
// The pattern is defined by the top level properties of the
// _pattern_ parameter. In the case where the pattern is a string,
// it is first parsed by
// [jsonic](https://github.com/rjrodger/jsonic)
//
// If the value of a pattern property is a sub-object, this is
// interpreted as a
// [parambulator](https://github.com/rjrodger/parambulator)
// validation check. In this case, the property is not considered
// part of the pattern, but rather an argument to validate when
// _seneca.act_ is called.
function api_add () {
var self = this
var re
if (!loadingQueue.started) {
re = arrayify(arguments)
loadingQueue.push(function (cb) {
api_add.apply(self, re)
process.nextTick(cb)
})
return self
}
var args = Common.parsePattern(self, arguments, 'action:f? actmeta:o?')
var raw_pattern = args.pattern
var action = args.action || function (msg, done) {
done.call(this, null, msg.default$ || null)
}
var actmeta = args.actmeta || {}
// TODO: refactor plugin name, tag and fullname handling.
actmeta.plugin_name = actmeta.plugin_name || 'root$'
actmeta.plugin_fullname = actmeta.plugin_fullname ||
actmeta.plugin_name +
((actmeta.plugin_tag === '-' ? void 0 : actmeta.plugin_tag)
? '/' + actmeta.plugin_tag : '')
actmeta.sub = !!raw_pattern.sub$
actmeta.client = !!raw_pattern.client$
// Deprecate a pattern by providing a string message using deprecate$ key.
actmeta.deprecate = raw_pattern.deprecate$
var strict_add = (raw_pattern.strict$ && raw_pattern.strict$.add !== null)
? !!raw_pattern.strict$.add : !!so.strict.add
var internal_catchall = (raw_pattern.internal$ && raw_pattern.internal$.catchall !== null)
? !!raw_pattern.internal$.catchall : !!so.internal.catchall
var pattern = self.util.clean(raw_pattern)
if (!_.keys(pattern)) {
throw internals.error('add_empty_pattern', {args: Common.clean(args)})
}
var pattern_rules = _.clone(action.validate || {})
_.each(pattern, function (v, k) {
if (_.isObject(v)) {
pattern_rules[k] = v
delete pattern[k]
}
})
if (_.keys(pattern_rules).length) {
actmeta.parambulator = Parambulator(pattern_rules, pm_custom_args)
}
var addroute = true
actmeta.args = _.clone(pattern)
actmeta.pattern = Common.pattern(pattern)
// actmeta.id = self.idgen()
actmeta.id = refnid()
actmeta.func = action
var priormeta = self.find(pattern)
if (priormeta) {
if (!internal_catchall && '' === priormeta.pattern) {
priormeta = null
}
// only exact action patterns are overridden
// use .wrap for pin-based patterns
else if (strict_add && priormeta.pattern !== actmeta.pattern) {
priormeta = null
}
}
if (priormeta) {
if (_.isFunction(priormeta.handle)) {
priormeta.handle(args.pattern, action)
addroute = false
}
else {
actmeta.priormeta = priormeta
}
actmeta.priorpath = priormeta.id + ';' + priormeta.priorpath
}
else {
actmeta.priorpath = ''
}
// FIX: need a much better way to support layered actions
// this ".handle" hack is just to make seneca.close work
if (action && actmeta && _.isFunction(action.handle)) {
actmeta.handle = action.handle
}
var stats = {
id: actmeta.id,
plugin: {
full: actmeta.plugin_fullname,
name: actmeta.plugin_name,
tag: actmeta.plugin_tag
},
prior: actmeta.priorpath,
calls: 0,
done: 0,
fails: 0,
time: {}
}
private$.stats.actmap[actmeta.pattern] =
private$.stats.actmap[actmeta.pattern] || stats
if (addroute) {
var addlog = [ actmeta.sub ? 'SUB' : 'ADD',
actmeta.id, Common.pattern(pattern), action.name]
var logger = self.log.log || self.log
logger.debug.apply(self, addlog)
private$.actrouter.add(pattern, actmeta)
}
return self
}
// TODO: deprecate
root.findpins = root.pinact = function () {
var pins = []
var patterns = _.flatten(arrayify(arguments))
_.each(patterns, function (pattern) {
pattern = _.isString(pattern) ? Jsonic(pattern) : pattern
pins = pins.concat(_.map(private$.actrouter.list(pattern),
function (desc) {
return desc.match
}
))
})
return pins
}
function api_act_if () {
var self = this
var args = Norma('{execute:b actargs:.*}', arguments)
if (args.execute) {
return self.act.apply(self, args.actargs)
}
else return self
}
// Perform an action. The properties of the first argument are matched against
// known patterns, and the most specific one wins.
function api_act () {
var self = this
var spec = Common.parsePattern(self, arrayify(arguments), 'done:f?')
var args = spec.pattern
var actdone = spec.done
args = _.extend(args, self.fixedargs)
if (so.debug.act_caller) {
args.caller$ = '\n Action call arguments and location: ' +
(new Error(Util.inspect(args).replace(/\n/g, '')).stack)
.replace(/.*\/seneca\.js:.*\n/g, '')
.replace(/.*\/seneca\/lib\/.*\.js:.*\n/g, '')
}
do_act(self, null, null, args, actdone)
return self
}
function api_wrap (pin, meta, wrapper) {
var pinthis = this
if (!loadingQueue.started) {
loadingQueue.push(function (cb) {
api_wrap.call(pinthis, pin, meta, wrapper)
process.nextTick(cb)
})
return this
}
wrapper = _.isFunction(meta) ? meta : wrapper
meta = _.isFunction(meta) ? {} : meta
pin = _.isArray(pin) ? pin : [pin]
_.each(pin, function (p) {
_.each(pinthis.findpins(p), function (actpattern) {
pinthis.add(actpattern, meta, wrapper)
})
})
return this
}
// close seneca instance
// sets public seneca.closed property
function api_close (done) {
var seneca = this
seneca.ready(do_close)
function do_close () {
seneca.closed = true
seneca.log.debug('close', 'start')
seneca.act('role:seneca,cmd:close,closing$:true', function (err) {
seneca.log.debug('close', 'end', err)
seneca.removeAllListeners('act-in')
seneca.removeAllListeners('act-out')
seneca.removeAllListeners('act-err')
seneca.removeAllListeners('pin')
seneca.removeAllListeners('after-pin')
seneca.removeAllListeners('ready')
if (_.isFunction(done)) {
return done.call(seneca, err)
}
})
}
}
// 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 (!_.isFunction(ready)) {
// TODO: throw error
return
}
loadingQueue.push(do_ready)
return self
function do_ready (cb) {
private$._isReady = true
root.emit('pin')
root.emit('after-pin')
ready.call(self)
process.nextTick(cb)
}
}
// use('pluginname') - built-in, or provide calling code 'require' as seneca opt
// use(require('pluginname')) - plugin object, init will be called
// if first arg has property senecaplugin
function api_use (arg0, arg1, arg2) {
var self = this
var plugindesc
// Allow chaining with seneca.use('options', {...})
// see https://github.com/rjrodger/seneca/issues/80
if (arg0 === 'options') {
self.options(arg1)
return self
}
plugindesc = private$.use(arg0, arg1, arg2)
loadingQueue.push(function (cb) {
root.register(plugindesc, cb)
}, function (err) {
if (err) {
self.emit('error', err)
return
}
// TODO remove, we probably do not need
// to emit this event for every use
// but it was done in the previous release
// put it behind and option for backward
// compat? - MC
self.emit('ready')
})
return self
}
// TODO: move repl functionality to seneca-repl
root.inrepl = function () {
var self = this
self.on('act-out', function () {
Logging.handlers.print.apply(null, arrayify(arguments))
})
self.on('error', function () {
var args = arrayify(arguments)
args.unshift('ERROR: ')
Logging.handlers.print.apply(null, args)
})
}
// 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.name
}
function do_act (instance, actmeta, prior_ctxt, origargs, actdone) {
var delegate = instance
var args = _.clone(origargs)
var callargs = args
var actstats
var is_sync = _.isFunction(actdone)
var listen_origin = origargs.transport$ && origargs.transport$.origin
var id_tx = (args.id$ || args.actid$ || instance.idgen()).split('/')
var tx =
id_tx[1] ||
origargs.tx$ ||
instance.fixedargs.tx$ ||
instance.idgen()
var actid = (id_tx[0] || instance.idgen()) + '/' + tx
var actstart = Date.now()
args.default$ = args.default$ || (!so.strict.find ? {} : args.default$)
prior_ctxt = prior_ctxt || { chain: [], entry: true, depth: 1 }
actdone = actdone || _.noop
// if previously seen message, provide previous result, and don't process again
if (apply_actcache(instance, args, prior_ctxt, actdone)) {
return
}
var execute_action = function execute_action (action_done) {
var err
actmeta = actmeta || delegate.find(args, {catchall: so.internal.catchall})
if (actmeta) {
if (_.isArray(args.history$) && 0 < args.history$.length) {
var repeat_count = 0
for (var hI = 0; hI < args.history$.length; ++hI) {
if (actmeta.id === args.history$[hI].action) {
++repeat_count
}
}
if (so.strict.maxloop < repeat_count) {
err = internals.error('act_loop', {
pattern: actmeta.pattern,
actmeta: actmeta,
history: args.history$
})
return action_done(err)
}
}
}
// action pattern not found
else {
if (_.isPlainObject(args.default$) || _.isArray(args.default$)) {
delegate.log.debug('act', '-', '-', 'DEFAULT',
delegate.util.clean(args))
return action_done(null, args.default$)
}
var errcode = 'act_not_found'
var errinfo = { args: Util.inspect(Common.clean(args)).replace(/\n/g, '') }
if (!_.isUndefined(args.default$)) {
errcode = 'act_default_bad'
errinfo.xdefault = Util.inspect(args.default$)