forked from strongloop-community/loopback-example-pubsub
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pubsub-primus.js
17116 lines (15014 loc) · 419 KB
/
pubsub-primus.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
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.PrimusTransport = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
'use strict';
var util = require('util');
/**
* Generic Primus error.
*
* @constructor
* @param {String} message The reason for the error
* @param {EventEmitter} logger Optional EventEmitter to emit a `log` event on.
* @api public
*/
function PrimusError(message, logger) {
Error.call(this);
Error.captureStackTrace(this, this.constructor);
this.message = message;
this.name = this.constructor.name;
if (logger) {
logger.emit('log', 'error', this);
}
}
util.inherits(PrimusError, Error);
/**
* There was an error while parsing incoming or outgoing data.
*
* @param {String} message The reason for the error.
* @param {Spark} spark The spark that caused the error.
* @api public
*/
function ParserError(message, spark) {
Error.call(this);
Error.captureStackTrace(this, this.constructor);
this.message = message;
this.name = this.constructor.name;
if (spark) {
if (spark.listeners('error').length) spark.emit('error', this);
spark.primus.emit('log', 'error', this);
}
}
util.inherits(ParserError, Error);
//
// Expose our custom events.
//
exports.PrimusError = PrimusError;
exports.ParserError = ParserError;
},{"util":82}],2:[function(require,module,exports){
(function (process,__dirname){
'use strict';
var PrimusError = require('./errors').PrimusError
, EventEmitter = require('eventemitter3')
, Transformer = require('./transformer')
, log = require('diagnostics')('primus')
, Spark = require('./spark')
, fuse = require('fusing')
, fs = require('fs');
/**
* Primus is a universal wrapper for real-time frameworks that provides a common
* interface for server and client interaction.
*
* @constructor
* @param {HTTP.Server} server HTTP or HTTPS server instance.
* @param {Object} options Configuration
* @api public
*/
function Primus(server, options) {
if (!(this instanceof Primus)) return new Primus(server, options);
if ('object' !== typeof server) {
var message = 'The first argument of the constructor must be ' +
'an HTTP or HTTPS server instance';
throw new PrimusError(message, this);
}
options = options || {};
this.fuse();
var primus = this
, key;
this.auth = options.authorization || null; // Do we have an authorization handler.
this.connections = Object.create(null); // Connection storage.
this.ark = Object.create(null); // Plugin storage.
this.layers = []; // Middleware layers.
this.transformer = null; // Reference to the real-time engine instance.
this.encoder = null; // Shorthand to the parser's encoder.
this.decoder = null; // Shorthand to the parser's decoder.
this.connected = 0; // Connection counter.
this.sparks = 0; // Increment id for connection ids.
this.timeout = 'timeout' in options // The timeout used to detect zombie sparks.
? options.timeout
: 35000;
this.whitelist = []; // Forwarded-for white listing.
this.options = options; // The configuration.
this.transformers = { // Message transformers.
outgoing: [],
incoming: []
};
this.server = server;
this.pathname = 'string' === typeof options.pathname
? options.pathname.charAt(0) !== '/'
? '/'+ options.pathname
: options.pathname
: '/primus';
//
// Create a specification file with the information that people might need to
// connect to the server.
//
this.spec = {
version: this.version,
pathname: this.pathname,
timeout: this.timeout
};
//
// Create a pre-bound Spark constructor. Doing a Spark.bind(Spark, this) doesn't
// work as we cannot extend the constructor of it anymore. The added benefit of
// approach listed below is that the prototype extensions are only applied to
// the Spark of this Primus instance.
//
this.Spark = function Sparky(headers, address, query, id, request) {
Spark.call(this, primus, headers, address, query, id, request);
};
this.Spark.prototype = Object.create(Spark.prototype, {
constructor: {
value: this.Spark,
writable: true,
enumerable: false,
configurable: true
}
});
//
// Copy over the original Spark static properties and methods so readable and
// writable can also be used.
//
for (key in Spark) {
this.Spark[key] = Spark[key];
}
this.parsers(options.parser);
this.initialise(options.transformer || options.transport, options);
//
// If the plugins are supplied through the options, also initialise them. This
// allows us to do `primus.createSocket({})` to also use plugins.
//
if ('string' === typeof options.plugin) {
options.plugin.split(/[\s|,]+/).forEach(function register(name) {
primus.use(name, name);
});
return;
}
if ('object' === typeof options.plugin) {
for (key in options.plugin) {
this.use(key, options.plugin[key]);
}
}
//
// - Cluster node 0.10 lets the Operating System decide to which worker a request
// goes. This can result in a not even distribution where some workers are
// used at 10% while others at 90%. In addition to that the load balancing
// isn't sticky.
//
// - Cluster node 0.12 implements a custom round robin algorithm. This solves the
// not even distribution of work but it does not address our sticky session
// requirement.
//
// Projects like `sticky-session` attempt to implement sticky sessions but they
// are using `net` server instead of a HTTP server in combination with the
// remoteAddress of the connection to load balance. This does not work when you
// address your servers behind a load balancer as the IP is set to the load
// balancer, not the connecting clients. All in all, it only causes more
// scalability problems. So we've opted-in to warn users about the
// risks of using Primus in a cluster.
//
if (!options.iknowclusterwillbreakconnections && require('cluster').isWorker) [
'',
'The `cluster` module does not implement sticky sessions. Learn more about',
'this issue at:',
'',
'http://github.com/primus/primus#can-i-use-cluster',
'',
].forEach(function warn(line) {
console.error('Primus: '+ line);
});
}
//
// Fuse and spice-up the Primus prototype with EventEmitter and predefine
// awesomeness.
//
fuse(Primus, EventEmitter);
//
// Lazy read the primus.js JavaScript client.
//
Object.defineProperty(Primus.prototype, 'client', {
get: function read() {
if (!read.primus) {
read.primus = fs.readFileSync(__dirname + '/primus.js', 'utf-8');
}
return this.customGlobal(read.primus);
}
});
//
// Lazy compile the primus.js JavaScript client for Node.js
//
Object.defineProperty(Primus.prototype, 'Socket', {
get: function () {
return require('load').compiler(this.library(true), 'primus.js', {
__filename: 'primus.js',
__dirname: process.cwd()
}).Primus;
}
});
/**
* Change the default Primus global which we use in client code to something
* custom. This makes it easier for people to integrate libraries in to their
* own custom code bases.
*
* @param {String} input The library code.
* @returns {String} The updated library code with the global replacements.
* @api private
*/
Primus.prototype.customGlobal = function customGlobal(input) {
var libraryNameLength = 'Primus'.length
, global = this.options.global;
if (!global) return input;
input.match(/Primus[^\ ]/g).filter(function filter(e, i, values) {
return values.lastIndexOf(e) === i;
}).forEach(function each(match) {
//
// Doing a split then join prevents us needing to escape for RegExp
//
input = input.split(match).join(global + match.substr(libraryNameLength, 1));
});
return input;
};
//
// Expose the current version number.
//
Primus.prototype.version = require('./package.json').version;
//
// A list of supported transformers and the required Node.js modules.
//
Primus.transformers = require('./transformers.json');
Primus.parsers = require('./parsers.json');
/**
* Simple function to output common errors.
*
* @param {String} what What is missing.
* @param {Object} where Either Primus.parsers or Primus.transformers.
* @returns {Object}
* @api private
*/
Primus.readable('is', function is(what, where) {
var missing = Primus.parsers !== where
? 'transformer'
: 'parser'
, dependency = where[what];
return {
missing: function write() {
console.error('Primus:');
console.error('Primus: Missing required npm dependency for '+ what);
console.error('Primus: Please run the following command and try again:');
console.error('Primus:');
console.error('Primus: npm install --save %s', dependency.server);
console.error('Primus:');
return 'Missing dependencies for '+ missing +': "'+ what + '"';
},
unknown: function write() {
console.error('Primus:');
console.error('Primus: Unsupported %s: "%s"', missing, what);
console.error('Primus: We only support the following %ss:', missing);
console.error('Primus:');
console.error('Primus: %s', Object.keys(where).join(', '));
console.error('Primus:');
return 'Unsupported '+ missing +': "'+ what +'"';
}
};
});
/**
* Initialise the real-time transport that was chosen.
*
* @param {Mixed} Transformer The name of the transformer or a constructor;
* @param {Object} options Options.
* @api private
*/
Primus.readable('initialise', function initialise(Transformer, options) {
Transformer = Transformer || 'websockets';
var primus = this
, transformer;
if ('string' === typeof Transformer) {
log('transformer `%s` is a string, attempting to resolve location', Transformer);
Transformer = transformer = Transformer.toLowerCase();
this.spec.transformer = transformer;
//
// This is a unknown transporter, it could be people made a typo.
//
if (!(Transformer in Primus.transformers)) {
log('the supplied transformer %s is not supported, please use %s', transformer, Primus.transformers);
throw new PrimusError(this.is(Transformer, Primus.transformers).unknown(), this);
}
try {
Transformer = require('./transformers/'+ transformer);
this.transformer = new Transformer(this);
} catch (e) {
if (e.code === 'MODULE_NOT_FOUND') {
log('the supplied transformer `%s` is missing', transformer);
throw new PrimusError(this.is(transformer, Primus.transformers).missing(), this);
} else {
log(e);
throw e;
}
}
} else {
log('received a custom transformer');
this.spec.transformer = 'custom';
}
if ('function' !== typeof Transformer) {
throw new PrimusError('The given transformer is not a constructor', this);
}
this.transformer = this.transformer || new Transformer(this);
this.on('connection', function connection(stream) {
this.connected++;
this.connections[stream.id] = stream;
log('connection: %s currently serving %d concurrent', stream.id, this.connected);
});
this.on('disconnection', function disconnected(stream) {
this.connected--;
delete this.connections[stream.id];
log('disconnection: %s currently serving %d concurrent', stream.id, this.connected);
});
//
// Add our default middleware layers.
//
this.before('forwarded', require('./middleware/forwarded'));
this.before('cors', require('./middleware/access-control'));
this.before('primus.js', require('./middleware/primus'));
this.before('spec', require('./middleware/spec'));
this.before('x-xss', require('./middleware/xss'));
this.before('no-cache', require('./middleware/no-cache'));
this.before('authorization', require('./middleware/authorization'));
//
// Emit the initialised event after the next tick so we have some time to
// attach listeners.
//
process.nextTick(function tock() {
primus.emit('initialised', primus.transformer, primus.parser, options);
});
});
/**
* Add a new authorization handler.
*
* @param {Function} auth The authorization handler.
* @returns {Primus}
* @api public
*/
Primus.readable('authorize', function authorize(auth) {
if ('function' !== typeof auth) {
throw new PrimusError('Authorize only accepts functions', this);
}
if (auth.length < 2) {
throw new PrimusError('Authorize function requires more arguments', this);
}
log('setting an authorization function');
this.auth = auth;
return this;
});
/**
* Iterate over the connections.
*
* @param {Function} fn The function that is called every iteration.
* @param {Function} done Optional callback, if you want to iterate asynchronously.
* @returns {Primus}
* @api public
*/
Primus.readable('forEach', function forEach(fn, done) {
if (!done) {
for (var id in this.connections) {
if (fn(this.connections[id], id, this.connections) === false) break;
}
return this;
}
var ids = Object.keys(this.connections)
, primus = this;
log('iterating over %d connections', ids.length);
function pushId(spark) {
ids.push(spark.id);
}
//
// We are going to iterate through the connections asynchronously so
// we should handle new connections as they come in.
//
primus.on('connection', pushId);
(function iterate() {
var id = ids.shift()
, spark;
if (!id) {
primus.removeListener('connection', pushId);
return done();
}
spark = primus.connections[id];
//
// The connection may have already been closed.
//
if (!spark) return iterate();
fn(spark, function next(err, forward) {
if (err || forward === false) {
primus.removeListener('connection', pushId);
return done(err);
}
iterate();
});
}());
return this;
});
/**
* Broadcast the message to all connections.
*
* @param {Mixed} data The data you want to send.
* @returns {Primus}
* @api public
*/
Primus.readable('write', function write(data) {
this.forEach(function forEach(spark) {
spark.write(data);
});
return this;
});
/**
* Install message parsers.
*
* @param {Mixed} parser Parse name or parser Object.
* @returns {Primus}
* @api private
*/
Primus.readable('parsers', function parsers(parser) {
parser = parser || 'json';
if ('string' === typeof parser) {
log('transformer `%s` is a string, attempting to resolve location', parser);
parser = parser.toLowerCase();
this.spec.parser = parser;
//
// This is a unknown parser, it could be people made a typo.
//
if (!(parser in Primus.parsers)) {
log('the supplied parser `%s` is not supported please use %s', parser, Primus.parsers);
throw new PrimusError(this.is(parser, Primus.parsers).unknown(), this);
}
try { parser = require('./parsers/'+ parser); }
catch (e) {
if (e.code === 'MODULE_NOT_FOUND') {
log('the supplied parser `%s` is missing', parser);
throw new PrimusError(this.is(parser, Primus.parsers).missing(), this);
} else {
log(e);
throw e;
}
}
} else {
this.spec.parser = 'custom';
}
if ('object' !== typeof parser) {
throw new PrimusError('The given parser is not an Object', this);
}
this.encoder = parser.encoder;
this.decoder = parser.decoder;
this.parser = parser;
return this;
});
/**
* Register a new message transformer. This allows you to easily manipulate incoming
* and outgoing data which is particularity handy for plugins that want to send
* meta data together with the messages.
*
* @param {String} type Incoming or outgoing
* @param {Function} fn A new message transformer.
* @returns {Primus}
* @api public
*/
Primus.readable('transform', function transform(type, fn) {
if (!(type in this.transformers)) {
throw new PrimusError('Invalid transformer type', this);
}
if (~this.transformers[type].indexOf(fn)) {
log('the %s message transformer already exists, not adding it', type);
return this;
}
this.transformers[type].push(fn);
return this;
});
/**
* Gets a spark by its id.
*
* @param {String} id The spark's id.
* @returns {Spark}
* @api private
*/
Primus.prototype.spark = function spark(id) {
return this.connections[id];
};
/**
* Generate a client library.
*
* @param {Boolean} nodejs Don't include the library, as we're running on Node.js.
* @returns {String} The client library.
* @api public
*/
Primus.readable('library', function compile(nodejs) {
var encoder = this.encoder.client || this.encoder
, decoder = this.decoder.client || this.decoder
, library = [ !nodejs ? this.transformer.library : null ]
, global = this.options.global || 'Primus'
, transport = this.transformer.client
, parser = this.parser.library || '';
//
// Add a simple export wrapper so it can be used as Node.js, AMD or browser
// client.
//
var client = '(function UMDish(name, context, definition) {'
+ ' context[name] = definition.call(context);'
+ ' if (typeof module !== "undefined" && module.exports) {'
+ ' module.exports = context[name];'
+ ' } else if (typeof define == "function" && define.amd) {'
+ ' define(function reference() { return context[name]; });'
+ ' }'
+ '})("'+ global +'", this, function '+ global +'() {'
+ this.client;
//
// Replace some basic content.
//
client = client
.replace('null; // @import {primus::pathname}', '"'+ this.pathname.toString() +'"')
.replace('null; // @import {primus::version}', '"'+ this.version +'"')
.replace('null; // @import {primus::transport}', transport.toString())
.replace('null; // @import {primus::auth}', (!!this.auth).toString())
.replace('null; // @import {primus::encoder}', encoder.toString())
.replace('null; // @import {primus::decoder}', decoder.toString());
//
// As we're given a timeout value on the server side, we need to update the
// `ping` interval of the client to ensure that we've sent the server
// a message before the timeout gets triggered and we get disconnected.
//
if ('number' === typeof this.timeout) {
var timeout = this.timeout - 10000;
log('adding a custom timeout to the client');
client = client.replace('options.ping : 25e3;', 'options.ping : '+ timeout +';');
}
//
// Add the parser inside the closure, to prevent global leaking.
//
if (parser && parser.length) {
log('adding parser to the client file');
client += parser;
}
//
// Iterate over the parsers, and register the client side plugins. If there's
// a library bundled, add it the library array as there were some issues with
// frameworks that get included in module wrapper as it forces strict mode.
//
var name, plugin;
for (name in this.ark) {
plugin = this.ark[name];
name = JSON.stringify(name);
if (plugin.library) {
log('adding the library of the %s plugin to the client file', name);
library.push(this.customGlobal(plugin.library));
}
if (!plugin.client) continue;
log('adding the client code of the %s plugin to the client file', name);
client += global +'.prototype.ark['+ name +'] = '+ plugin.client.toString() +';\n';
}
//
// Close the export wrapper and return the client. If we need to add
// a library, we should add them after we've created our closure and module
// exports. Some libraries seem to fail hard once they are wrapped in our
// closure so I'll rather expose a global variable instead of having to monkey
// patch to much code.
//
return client +' return '+ global +'; });'
+ library.filter(Boolean).map(function expose(library) {
return '(function '+ global +'LibraryWrap('+ global +') {'
+ library
+ '})(this["'+ global +'"]);';
}).join('\n');
});
/**
* Save the library to disk.
*
* @param {String} dir The location that we need to save the library.
* @param {function} fn Optional callback, if you want an async save.
* @returns {Primus}
* @api public
*/
Primus.readable('save', function save(path, fn) {
if (!fn) fs.writeFileSync(path, this.library(), 'utf-8');
else fs.writeFile(path, this.library(), 'utf-8', fn);
return this;
});
/**
* Register a new Primus plugin.
*
* ```js
* primus.use('ack', {
* //
* // Only ran on the server.
* //
* server: function (primus, options) {
* // do stuff
* },
*
* //
* // Runs on the client, it's automatically bundled.
* //
* client: function (primus, options) {
* // do client stuff
* },
*
* //
* // Optional library that needs to be bundled on the client (should be a string)
* //
* library: ''
* });
* ```
*
* @param {String} name The name of the plugin.
* @param {Object} energon The plugin that contains client and server extensions.
* @returns {Primus}
* @api public
*/
Primus.readable('use', function use(name, energon) {
if ('object' === typeof name && !energon) {
energon = name;
name = energon.name;
}
if (!name) {
throw new PrimusError('Plugin should be specified with a name', this);
}
if ('string' !== typeof name) {
throw new PrimusError('Plugin names should be a string', this);
}
if ('string' === typeof energon) {
log('plugin was passed as a string, attempting to require %s', energon);
energon = require(energon);
}
//
// Plugin accepts an object or a function only.
//
if (!/^(object|function)$/.test(typeof energon)) {
throw new PrimusError('Plugin should be an object or function', this);
}
//
// Plugin require a client, server or both to be specified in the object.
//
if (!energon.server && !energon.client) {
throw new PrimusError('The plugin is missing a client or server function', this);
}
//
// Don't allow duplicate plugins or plugin override as this is most likely
// unintentional.
//
if (name in this.ark) {
throw new PrimusError('The plugin name was already defined', this);
}
log('adding %s as new plugin', name);
this.ark[name] = energon;
this.emit('plugin', name, energon);
if (!energon.server) return this;
log('calling the %s plugin\'s server code', name);
energon.server.call(this, this, this.options);
return this;
});
/**
* Return the given plugin.
*
* @param {String} name The name of the plugin.
* @returns {Mixed}
* @api public
*/
Primus.readable('plugin', function plugin(name) {
if (name) return this.ark[name];
var plugins = {};
for (name in this.ark) {
plugins[name] = this.ark[name];
}
return plugins;
});
/**
* Remove plugin from the ark.
*
* @param {String} name Name of the plugin we need to remove from the ark.
* @returns {Boolean} Successful removal of the plugin.
* @api public
*/
Primus.readable('plugout', function plugout(name) {
if (!(name in this.ark)) return false;
this.emit('plugout', name, this.ark[name]);
delete this.ark[name];
return true;
});
/**
* Add a new middleware layer. If no middleware name has been provided we will
* attempt to take the name of the supplied function. If that fails, well fuck,
* just random id it.
*
* @param {String} name The name of the middleware.
* @param {Function} fn The middleware that's called each time.
* @param {Object} options Middleware configuration.
* @param {Number} level 0 based optional index for the middleware.
* @returns {Primus}
* @api public
*/
Primus.readable('before', function before(name, fn, options, level) {
if ('function' === typeof name) {
level = options;
options = fn;
fn = name;
name = fn.name || 'pid_'+ Date.now();
}
if (!level && 'number' === typeof options) {
level = options;
options = {};
}
options = options || {};
//
// No or only 1 argument means that we need to initialise the middleware, this
// is a special initialisation process where we pass in a reference to the
// initialised Primus instance so a pre-compiling process can be done.
//
if (fn.length < 2) {
log('automatically configuring middleware `%s`', name);
fn = fn.call(this, options);
}
//
// Make sure that we have a function that takes at least 2 arguments.
//
if ('function' !== typeof fn || fn.length < 2) {
throw new PrimusError('Middleware should be a function that accepts at least 2 args');
}
var layer = {
length: fn.length, // Amount of arguments indicates if it's async.
enabled: true, // Middleware is enabled by default.
name: name, // Used for lookups.
fn: fn // The actual middleware.
}, index = this.indexOfLayer(name);
//
// Override middleware layer if we already have a middleware layer with
// exactly the same name.
//
if (!~index) {
if (level >= 0 && level < this.layers.length) {
log('adding middleware `%s` to the supplied index at %d', name, level);
this.layers.splice(level, 0, layer);
} else {
this.layers.push(layer);
}
} else {
this.layers[index] = layer;
}
return this;
});
/**
* Remove a middleware layer from the stack.
*
* @param {String} name The name of the middleware.
* @returns {Primus}
* @api public
*/
Primus.readable('remove', function remove(name) {
var index = this.indexOfLayer(name);
if (~index) {
log('removing middleware `%s`', name);
this.layers.splice(index, 1);
}
return this;
});
/**
* Enable a given middleware layer.
*
* @param {String} name The name of the middleware.
* @returns {Primus}
* @api public
*/
Primus.readable('enable', function enable(name) {
var index = this.indexOfLayer(name);
if (~index) {
log('enabling middleware `%s`', name);
this.layers[index].enabled = true;
}
return this;
});
/**
* Disable a given middleware layer.
*
* @param {String} name The name of the middleware.
* @returns {Primus}
* @api public
*/
Primus.readable('disable', function disable(name) {
var index = this.indexOfLayer(name);
if (~index) {
log('disabling middleware `%s`', name);
this.layers[index].enabled = false;
}
return this;
});
/**
* Find the index of a given middleware layer by name.
*
* @param {String} name The name of the layer.
* @returns {Number}
* @api private
*/
Primus.readable('indexOfLayer', function indexOfLayer(name) {
for (var i = 0, length = this.layers.length; i < length; i++) {
if (this.layers[i].name === name) return i;
}
return -1;
});
/**
* Destroy the created Primus instance.
*
* Options:
* - close (boolean) Close the given server.
* - end (boolean) Shut down all active connections.
* - timeout (number) Forcefully close all connections after a given x MS.
*
* @param {Object} options Destruction instructions.
* @param {Function} fn Callback.
* @returns {Primus}
* @api public
*/
Primus.readable('destroy', function destroy(options, fn) {
if ('function' === typeof options) {
fn = options;
options = null;
}
options = options || {};
var primus = this;
setTimeout(function cleanup() {
//
// Optionally close the server.
//
if (options.close !== false && primus.server) {
//
// Closing a server that isn't started yet would throw an error.
//
try { primus.server.close(); }
catch (e) {}
}
//
// Optionally close connections that are left open.
//
if (options.end !== false) {
primus.forEach(function shutdown(spark) {
spark.end();
});
} else {
[
'',
'We\'ve detected that you are using the `destroy` method with the',
'`end` option set to `false`. This is deprecated and the ability to',
'leave the connections open will be removed in future releases.',
''
].forEach(function each(line) {
console.error('Primus: '+ line);
});
}
//
// Emit some final closing events right before we remove all listener
// references from all the event emitters.
//