-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathfast_server.js
1432 lines (1280 loc) · 46.8 KB
/
fast_server.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
/*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
/*
* Copyright (c) 2019, Joyent, Inc.
*/
/*
* lib/fast_server.js: public node-fast server interface
*
* The public interface for this module is the FastServer class, which takes a
* server socket and manages connections to clients that connect to the server.
* Callers register RPC method handlers with the server, and their handler
* functions are invoked when RPC requests are received for the registered
* method. RPC handlers are functions that take a single argument, an RPC
* context, through which the handler can access the RPC arguments and send data
* back to the client.
*
*
* Flow control
*
* The implementation of the server is structured primarily into object-mode
* streams to support Node's built-in flow control. This is only of limited
* utility at this time, since the client does not support per-request flow
* control. However, if a client is itself reading slowly, then this mechanism
* allows the server manage backpressure appropriately.
*
* The RPC context argument provided to RPC method handlers is itself an
* object-mode stream. Objects written to the stream are sent to the client.
* When the stream is ended, an "end" message is written to the client, which
* signifies the successful completion of the RPC call. The stream pipeline
* from the RPC context to the client socket fully supports flow control, so the
* stream will used a bounded amount of memory as long as the RPC method
* respects Node's flow-control semantics (e.g., stops writing to the stream
* when write() returns false). The pipeline looks like this:
*
* RPC request context (provided as argument to RPC method handlers)
* |
* | (pipe: objects)
* v
* FastRpcResponseEncoder (wraps objects in Fast "DATA" messages, and
* | terminates the stream with an "END" message)
* | (pipe: objects)
* v
* FastMessageEncoder (serializes logical Fast messages into buffers)
* |
* | (pipe: bytes)
* v
* Client socket (usually a net.Socket object for TCP)
*
* Of course, many of these pipelines may be piped to the same net.Socket
* object. This has an unexpected, unfortunate scaling limitation: the
* completion of a pipe() operation causes Node to remove event listeners, and
* EventEmitter.removeListener() is O(N), where N is the number of listeners for
* the same event. As a result, if a client maintains N concurrent requests,
* then completion of each request will run into this O(N) step. This results
* in an O(N^2) factor in the overall time to complete N requests. The Node API
* does not seem fixable. We could implement a tree of EventEmitters that
* funnel into the socket, but it's not clear at this point that this
* consideration is worthwhile. In practice, Fast servers are more likely to
* see many clients making a small number of requests each rather than a small
* number of clients making a large number of requests each, and this deployment
* model is recommended to avoid this scaling limiter.
*
* Flow control is less well-supported on the receiving side because it's less
* clear what the source of backpressure should be. The pipeline looks like
* this:
*
* +---------------------------------------------------------------------+
* | Per-connection pipeline |
* | ----------------------- |
* | |
* | Client socket (usually a net.Socket object for TCP) |
* | | |
* | | (pipe: bytes) |
* | v |
* | FastMessageDecoder (unmarshals Fast messages from bytes |
* | | received on the socket) |
* | | (pipe: objects) |
* | v |
* | FastRpcConnectionDecoder (tags incoming Fast messages with a |
* | | connection identifier for session |
* | | (pipe: objects) tracking) |
* | | |
* +------- | -----------------------------------------------------------+
* |
* v
* FastMessageHandler (one for the entire server that invokes
* server.onMessage() for each message)
*
* Since there are many connections and one FastMessageHandler for the server,
* the whole picture looks like this:
*
* Connection Connection Connection
* pipeline pipeline pipeline
* | | |
* ... | ... | ... | ...
* | | |
* v v v
* +---------------------------+
* | FastMessageHandler |
* +---------------------------+
* |
* v
* server.onMessage()
*
* The FastMessageHandler currently provides no backpressure. If desired, a
* a simple throttle could flow-control the entire pipeline based on concurrent
* outstanding RPC requests. A more complex governor could look at the the
* count of requests per connection and prioritize some notion of fairness among
* them. As a result of the lack of flow control here, it's possible for any
* client to overwhelm the server by blasting messages to it; however, because
* the intended deployment is not a byzantine environment, this issue is not
* considered a priority for future work.
*/
var mod_assertplus = require('assert-plus');
var mod_dtrace = require('dtrace-provider');
var mod_events = require('events');
var mod_jsprim = require('jsprim');
var mod_microtime = require('microtime');
var mod_stream = require('stream');
var mod_util = require('util');
var VError = require('verror');
var mod_protocol = require('./fast_protocol');
var mod_subr = require('./subr');
exports.FastServer = FastServer;
/*
* Generated via artedi.logLinearBuckets(10, -4, 1, 5). Chosen only because it
* covers the range of observed requests.
*/
var DEFAULT_BUCKETS = [
0.0002, 0.0004, 0.0006, 0.0008, 0.001,
0.002, 0.004, 0.006, 0.008, 0.01,
0.02, 0.04, 0.06, 0.08, 0.1,
0.2, 0.4, 0.6, 0.8, 1,
2, 4, 6, 8, 10,
20, 40, 60, 80, 100
];
/*
* This maximum is chosen pretty arbitrarily.
*/
var FS_MAX_CONNID = (1 << 30);
/*
* There's one DTrace provider for all servers using this copy of this module.
*/
var fastServerProvider = null;
/*
* We have one counter for the number of servers in this process. This is a
* true JavaScript global. See the note in lib/fast_client.js.
*/
/* jsl:declare fastNservers */
fastNservers = 0;
/*
* Instantiate a new server for handling RPC requests made from remote Fast
* clients. This server does not manage the underlying server socket. That's
* the responsibility of the caller.
*
* Named arguments:
*
* log bunyan-style logger
*
* server server object that emits 'connection' events
*
* collector artedi-style metric collector
*
* crc_mode CRC mode. Used to transition off buggy node-crc version.
* See the fast_protocol module documentation for more
* details. The valid values for a FastServer are
* FAST_CHECKSUM_V1, FAST_CHECKSUM_V2, and
* FAST_CHECKSUM_V1_V2.
*
* Use the server by invoking the registerRpcMethod() method to register
* handlers for named RPC methods.
*/
function FastServer(args)
{
var self = this;
var fixed_buckets = false;
mod_assertplus.object(args, 'args');
mod_assertplus.object(args.log, 'args.log');
mod_assertplus.object(args.server, 'args.server');
mod_assertplus.optionalObject(args.collector, 'args.collector');
mod_assertplus.optionalNumber(args.crc_mode, 'args.crc_mode');
if (args.crc_mode && args.crc_mode !== mod_protocol.FAST_CHECKSUM_V1 &&
args.crc_mode !== mod_protocol.FAST_CHECKSUM_V2 &&
args.crc_mode !== mod_protocol.FAST_CHECKSUM_V1_V2) {
mod_assertplus.fail('encountered invalid CRC mode ' +
args.crc_mode);
}
this.fs_log = args.log; /* logger */
this.fs_server = args.server; /* server socket */
this.fs_collector = args.collector; /* metric collector */
this.fs_handlers = {}; /* registered handlers, by name */
this.fs_conns = {}; /* active connections */
/* supported crc mode for joyent/node-fast#23 */
this.fast_crc_mode = args.crc_mode || mod_protocol.FAST_CHECKSUM_V1;
this.fs_msghandler = new FastMessageHandler({
'server': this
});
/*
* A FIFO queue of work functions to be run the next time the number of
* active connections drops to zero. Work functions are individually
* enqueued with the 'onConnsDestroyed' API method, and collectively
* dequeued in 'connDrain' if the server finds that 'fs_conns' is empty.
*/
this.fs_conns_destroyed_callbacks = [];
/*
* See the comments below on use of setMaxListeners().
*/
this.fs_msghandler.setMaxListeners(0);
this.fs_connallocator = new mod_subr.IdAllocator({
'min': 1,
'max': FS_MAX_CONNID,
'isAllocated': function isConnIdAllocated(id) {
return (self.fs_conns.hasOwnProperty(id));
}
});
this.fs_closed = false; /* server is shutting down */
this.fs_server.on('connection',
function onConnection(sock) { self.connCreate(sock); });
this.fs_nignored_noconn = 0; /* count of msgs ignored: no conn */
this.fs_nignored_badconn = 0; /* count of msgs ignored: bad conn */
this.fs_nignored_aborts = 0; /* count of msgs ignored: aborts */
this.fs_nconnections_created = 0; /* count of conns created */
this.fs_nrequests_started = 0; /* count of reqs started */
this.fs_nrequests_completed = 0; /* count of reqs completed */
this.fs_nrequests_failed = 0; /* count of reqs failed */
if (this.fs_collector) {
if (this.fs_collector.FIXED_BUCKETS === true) {
fixed_buckets = true;
}
this.fs_request_counter = this.fs_collector.counter({
name: 'fast_requests_completed',
help: 'count of fast requests completed'
});
this.fs_latency_histogram = this.fs_collector.histogram({
name: 'fast_server_request_time_seconds',
help: 'total time to process fast requests',
buckets: (fixed_buckets === true) ?
DEFAULT_BUCKETS : undefined,
labels: (fixed_buckets === true) ?
{ buckets_version: '1' } : undefined
});
}
if (fastServerProvider === null) {
fastServerProvider = fastServerProviderInit();
}
mod_assertplus.object(fastServerProvider);
this.fs_dtid = fastNservers++;
this.fs_dtp = fastServerProvider;
}
/* public methods */
FastServer.prototype.registerRpcMethod = function (args)
{
var rpcmethod, handler;
mod_assertplus.object(args, 'args');
mod_assertplus.string(args.rpcmethod, 'args.rpcmethod');
mod_assertplus.func(args.rpchandler, 'args.rpchandler');
rpcmethod = args.rpcmethod;
handler = args.rpchandler;
mod_assertplus.ok(!this.fs_handlers.hasOwnProperty(rpcmethod),
'duplicate handler registered for method "' + rpcmethod + '"');
this.fs_log.info({ 'rpcmethod': rpcmethod }, 'registered RPC method');
this.fs_handlers[rpcmethod] = new FastRpcHandler({
'rpcmethod': rpcmethod,
'rpchandler': handler
});
};
FastServer.prototype.close = function ()
{
var error, connid;
mod_assertplus.ok(arguments.length === 0,
'close() accepts no arguments');
if (this.fs_closed) {
this.fs_log.warn('close() called while already shutting down');
return;
}
this.fs_log.info('shutting down');
this.fs_closed = true;
error = new VError('server is shutting down');
for (connid in this.fs_conns) {
this.connTerminate(this.fs_conns[connid], error);
}
};
/*
* Public methods for exposing debugging data over kang.
*
* Over kang, we expose basic statistics about the server (suitable for
* real-time monitoring of basic activity), as well as objects of types:
*
* fastconnection describes a client that's currently connected,
* including local and remote address information
* and basic activity stats
*
* fastrequest describes a request that's currently outstanding,
* including which connection received it, how long it's
* been running, and what state it's in
*/
FastServer.prototype.kangStats = function ()
{
var rv = {};
rv['nConnectionsActive'] = Object.keys(this.fs_conns).length;
rv['nIgnoredMessagesNoConn'] = this.fs_nignored_noconn;
rv['nIgnoredMessagesBadConn'] = this.fs_nignored_badconn;
rv['nIgnoredMessagesAborts'] = this.fs_nignored_aborts;
rv['nConnectionsCreated'] = this.fs_nconnections_created;
rv['nRequestsStarted'] = this.fs_nrequests_started;
rv['nRequestsCompleted'] = this.fs_nrequests_completed;
rv['nRequestsFailed'] = this.fs_nrequests_failed;
rv['fastCRCMode'] = this.fast_crc_mode;
return (rv);
};
FastServer.prototype.kangListTypes = function ()
{
return ([ 'fastconnection', 'fastrequest' ]);
};
FastServer.prototype.kangListObjects = function (type)
{
if (type == 'fastconnection') {
return (Object.keys(this.fs_conns));
}
var rv = [];
mod_assertplus.equal(type, 'fastrequest');
mod_jsprim.forEachKey(this.fs_conns, function (cid, conn) {
Object.keys(conn.fc_pending).map(function (msgid) {
rv.push(cid + '/' + msgid);
});
});
return (rv);
};
FastServer.prototype.kangGetObject = function (type, id)
{
var conn, rv;
var parts, req;
if (type == 'fastconnection') {
conn = this.fs_conns[id];
rv = {
'connid': conn.fc_connid,
'addrinfo': conn.fc_addrinfo,
'nStarted': conn.fc_nstarted,
'nCompleted': conn.fc_ncompleted,
'nFailed': conn.fc_nfailed,
'draining': conn.fc_draining,
'errorSocket': conn.fc_socket_error,
'errorServer': conn.fc_server_error,
'timeAccepted': conn.fc_taccepted.toISOString()
};
return (rv);
}
mod_assertplus.equal(type, 'fastrequest');
parts = id.split('/');
mod_assertplus.equal(parts.length, 2);
conn = this.fs_conns[parts[0]];
req = conn.fc_pending[parts[1]];
rv = {
'connid': parts[0],
'msgid': parts[1],
'rpcmethod': req.fsr_rpcmethod,
'rpcargs': req.fsr_rpcargs,
'state': req.fsr_state,
'error': req.fsr_error,
'blackholed': req.fsr_blackhole !== null,
'timeStarted': req.fsr_tstarted.toISOString()
};
return (rv);
};
/* private methods */
/*
* Connection lifecycle
*
* Connections are created when the underlying Server (usually either a TCP or
* UDS server) emits a 'connection' event. In connCreate(), we set up data
* structures to manage a FastRpcConnection atop the new socket.
*
* Connections remain operational until they are abandoned for one of three
* reasons:
*
* o We read end-of-stream from the socket. This is a graceful termination
* that we might expect when the remote side is shutting down after
* completing all of its RPC requests.
*
* o We see an 'error' event on the socket. This is an ungraceful
* termination of the connection that we might expect in the face of a
* network error.
*
* o We proactively terminate the connection because we've read an invalid
* Fast protocol message or something else that's confused us as to the
* state of the connection, or we're shutting down the server.
*
* This is managed through the following call chain:
*
* connection arrives
* |
* v
* connCreate() sets up the FastRpcConnection
* |
* v
* normal operation
* | | |
* +-----------------+ | +---------------------+
* | | |
* | onConnectionEnd(): | onConnectionError(): | connTerminate():
* | end-of-stream read | socket error | protocol error
* | | | or server
* | | connDisconnectRequests() | shutdown
* | | |
* +---------------------> + <------------------------+
* |
* v
* connDrain():
* wait for pending requests to complete
* |
* v
* connection removed
*/
FastServer.prototype.connCreate = function (sock)
{
var self = this;
var cid, fastconn;
cid = this.allocConnectionId(sock);
mod_assertplus.ok(cid);
mod_assertplus.ok(!this.fs_conns.hasOwnProperty(cid));
fastconn = new FastRpcConnection({
'connId': cid,
'socket': sock,
'log': this.fs_log,
'crc_mode': this.fast_crc_mode
});
this.fs_nconnections_created++;
this.fs_conns[cid] = fastconn;
this.fs_dtp.fire('conn-create', function () {
return ([ self.fs_dtid, cid, fastconn.fc_addrinfo.label ]);
});
fastconn.fc_taccepted = new Date();
fastconn.fc_ckddecoder.pipe(this.fs_msghandler, { 'end': false });
fastconn.fc_log.info('connection received');
sock.on('end', function onConnectionEnd() {
self.onConnectionEnd(cid, fastconn);
});
sock.on('error', function onConnectionError(err) {
self.onConnectionError(cid, fastconn, err);
});
/*
* We shouldn't get here if the server is closing because the caller
* should have shut down the server socket. If we wind up seeing a
* queued connection, terminate it immediately.
*/
if (this.fs_closed) {
this.fs_log.warn('unexpected connection after server shutdown');
this.connTerminate(new VError('server is shutting down'));
}
};
/*
* Remove this connection because we've read end-of-stream. We will wait for
* pending requests to complete before actually removing the connection.
*/
FastServer.prototype.onConnectionEnd = function (cid, conn)
{
mod_assertplus.ok(conn instanceof FastRpcConnection);
mod_assertplus.ok(this.fs_conns.hasOwnProperty(cid));
mod_assertplus.ok(this.fs_conns[cid] == conn);
/*
* Due to Node issue 6083, it's possible to see an "end" event after
* having previously seen an "error" event. Ignore such events.
*/
if (conn.fc_socket_error !== null) {
conn.fc_log.debug('ignoring end-of-stream after error');
} else {
conn.fc_ended = true;
conn.fc_log.debug('end of input');
this.connDrain(conn);
}
};
/*
* Abandon this connection because we've seen a socket error. This can happen
* after the connection has already read end-of-stream or experienced a
* protocol-level error.
*/
FastServer.prototype.onConnectionError = function (cid, conn, err)
{
mod_assertplus.ok(conn instanceof FastRpcConnection);
mod_assertplus.ok(err instanceof Error);
mod_assertplus.ok(this.fs_conns.hasOwnProperty(cid));
mod_assertplus.ok(this.fs_conns[cid] == conn);
mod_assertplus.ok(conn.fc_socket_error === null);
conn.fc_socket_error = err;
conn.fc_log.warn(err, 'socket error');
/*
* If we've already seen a server error, then we're already tearing down
* the connection.
*/
if (conn.fc_server_error === null) {
this.connDisconnectRequests(conn);
this.connDrain(conn);
}
};
/*
* Allocate an internal connection id. Callers will use this as a string (as an
* object property name), and callers assume that it cannot be falsey.
*/
FastServer.prototype.allocConnectionId = function ()
{
return (this.fs_connallocator.alloc());
};
/*
* Terminate this connection because of a protocol error or a server shutdown.
* We do not allow existing requests to complete for this case.
*/
FastServer.prototype.connTerminate = function (conn, err)
{
mod_assertplus.ok(conn instanceof FastRpcConnection);
mod_assertplus.ok(err instanceof Error);
if (conn.fc_server_error === null && conn.fc_socket_error === null) {
conn.fc_log.warn(err, 'gracefully terminating connection');
conn.fc_server_error = err;
this.connDisconnectRequests(conn);
this.connDrain(conn);
} else {
conn.fc_log.warn(err, 'already terminating connection');
}
};
/*
* Disconnect all requests associated with this connection from the connection
* itself, generally as a result of a fatal error on the connection.
*/
FastServer.prototype.connDisconnectRequests = function (conn)
{
var msgid;
for (msgid in conn.fc_pending) {
this.requestDisconnect(conn.fc_pending[msgid]);
}
conn.fc_socket.destroy();
};
/*
* Wait for outstanding requests to complete and then remove this connection
* from the server.
*/
FastServer.prototype.connDrain = function (conn)
{
var self = this;
mod_assertplus.ok(this.fs_conns[conn.fc_connid] == conn);
if (!mod_jsprim.isEmpty(conn.fc_pending)) {
mod_assertplus.ok(conn.fc_nstarted > conn.fc_ncompleted);
conn.fc_log.debug({
'remaining': conn.fc_nstarted - conn.fc_ncompleted
}, 'waiting for request drain');
conn.fc_draining = true;
} else {
mod_assertplus.equal(conn.fc_nstarted, conn.fc_ncompleted);
conn.fc_log.info('removing drained connection');
delete (this.fs_conns[conn.fc_connid]);
this.fs_dtp.fire('conn-destroy', function () {
return ([ self.fs_dtid, conn.fc_connid ]);
});
if (conn.fc_socket_error !== null) {
/*
* If we did see a socket error, then we must explicitly
* tear down the pipeline. Otherwise, these streams
* will maintain references to each other, resulting in
* a leak.
*/
conn.fc_socket.unpipe();
conn.fc_ckddecoder.unpipe();
conn.fc_rawdecoder.unpipe();
} else if (conn.fc_server_error === null) {
/*
* As long as we didn't see a socket error and didn't
* already terminate the socket, destroy the socket. We
* could try to end it gracefully, but we don't actually
* want to wait for the client to shut it down cleanly.
* If we already saw an error, then there's nothing else
* to do.
*/
conn.fc_socket.destroy();
}
if (mod_jsprim.isEmpty(this.fs_conns)) {
while (this.fs_conns_destroyed_callbacks.length > 0) {
setImmediate(this.fs_conns_destroyed_callbacks
.shift());
}
}
}
};
/*
* Calls 'callback' when all the connections in 'fs_conns' have been destroyed.
* The callback is called immediately if the server already has no connections.
* Callbacks are queued and called in FIFO order the next time all client
* connections have been torn down.
*/
FastServer.prototype.onConnsDestroyed = function (callback)
{
mod_assertplus.func(callback, 'callback');
if (mod_jsprim.isEmpty(this.fs_conns)) {
setImmediate(callback);
} else {
this.fs_conns_destroyed_callbacks.push(callback);
}
};
/*
* Message handling
*
* The only message we actually expect from clients is a DATA message, which
* represents an RPC call. This function handles those messages and either
* ignores or issues appropriate errors for other kinds of messages.
*/
FastServer.prototype.onMessage = function (message)
{
var connid, conn;
var msgid, req;
var handler, handlerfunc;
var self = this;
connid = message.connId;
mod_assertplus.ok(connid);
if (!this.fs_conns.hasOwnProperty(connid)) {
/*
* This should only be possible if there were messages queued up
* from a connection that has since been destroyed.
*/
this.fs_log.warn({
'fastMessage': message
}, 'dropping message from unknown connection');
this.fs_nignored_noconn++;
return;
}
conn = this.fs_conns[connid];
if (conn.fc_ended || conn.fc_socket_error !== null) {
this.fs_log.warn({
'fastMessage': message
}, 'dropping message from abandoned connection');
this.fs_nignored_badconn++;
return;
}
if (message.status === mod_protocol.FP_STATUS_END) {
/*
* There's no reason clients should ever send us an "end" event.
*/
this.connTerminate(conn, new VError({
'name': 'FastProtocolError',
'info': {
'fastReason': 'unexpected_status'
}
}, 'unexpected END event from client'));
return;
}
msgid = message.msgid;
if (message.status === mod_protocol.FP_STATUS_ERROR) {
/*
* Intermediate versions of node-fast would send ERROR messages
* to request RPC cancellation. We don't support this. See the
* notes inside lib/fast_client.js for details on why. Such
* clients may expect a response from us in the form of an ERROR
* message, but we just let the RPC complete normally. After
* all, because of the inherent race between receiving the abort
* and completing the RPC, the client has to handle this
* possibility anyway.
*/
this.fs_log.warn({
'msgid': msgid
}, 'ignoring request to abort RPC (not supported)');
this.fs_nignored_aborts++;
return;
}
mod_assertplus.equal(message.status, mod_protocol.FP_STATUS_DATA);
if (conn.fc_pending.hasOwnProperty(msgid)) {
this.connTerminate(conn, new VError({
'name': 'FastProtocolError',
'info': {
'fastReason': 'duplicate_msgid',
'rpcMsgid': msgid
}
}, 'client attempted to re-use msgid'));
return;
}
/*
* The message decoder only validates the Fast message and that the
* payload in the message is a valid, non-null JSON object. Here, we
* validate the details of the payload.
*/
conn.fc_nstarted++;
this.fs_nrequests_started++;
req = new FastRpcServerRequest({
'server': this,
'fastMessage': message,
'fastConn': conn,
'log': conn.fc_log.child({ 'msgid': message.msgid }, true)
});
conn.fc_pending[req.fsr_msgid] = req;
req.fsr_hrtstarted = process.hrtime();
req.fsr_tstarted = new Date();
mod_assertplus.equal(typeof (message.data), 'object');
mod_assertplus.ok(message.data !== null);
if (!message.data.m || !message.data.m.name ||
typeof (message.data.m.name) != 'string' ||
!message.data.d || !Array.isArray(message.data.d)) {
this.requestFail(req, new VError({
'name': 'FastError',
'info': {
'fastReason': 'bad_data',
'rpcMsgid': message.msgid,
'rpcMessage': message
}
}, 'RPC request is not well-formed'));
return;
}
req.fsr_rpcmethod = message.data.m.name;
req.fsr_rpcargs = message.data.d;
if (!this.fs_handlers.hasOwnProperty(req.fsr_rpcmethod)) {
this.requestFail(req, new VError({
'name': 'FastError',
'info': {
'fastReason': 'bad_method',
'rpcMethod': req.fsr_rpcmethod,
'rpcMsgid': message.msgid
}
}, 'unsupported RPC method: "%s"', req.fsr_rpcmethod));
return;
}
handler = this.fs_handlers[req.fsr_rpcmethod];
handler.fh_nstarted++;
handlerfunc = handler.fh_handler;
req.fsr_handler = handler;
/*
* We skip the FR_S_QUEUED state because we do not currently limit
* request concurrency.
*/
req.fsr_state = FR_S_RUNNING;
req.fsr_encoder.pipe(conn.fc_msgencoder, { 'end': false });
req.fsr_docomplete = function () { self.requestComplete(req); };
req.fsr_encoder.on('end', req.fsr_docomplete);
req.fsr_log.debug('request started');
this.fs_dtp.fire('rpc-start', function () {
return ([ self.fs_dtid, conn.fc_connid, req.fsr_msgid,
req.fsr_rpcmethod ]);
});
handlerfunc(req.fsr_context);
};
/*
* Request lifecycle
*
* Requests are created via server.onMessage() and then advance through the
* following state machine:
*
* +------------- FR_S_INIT -------------+
* | |
* | validation okay |
* v | validation failed
* FR_S_QUEUED | (invalid or missing method
* | | name, missing arguments, etc.)
* | request handler invoked |
* v |
* FR_S_RUNNING |
* | |
* | request handler ends stream or |
* | invokes stream.fail(error) |
* | |
* +----------> FR_S_COMPLETE <----------+
*
* There are two paths for reaching FR_S_COMPLETE:
*
* - normal termination (handler ends the stream): server.requestComplete()
*
* - graceful error (handler invokes fail(error)): server.requestFail()
*
* In both cases, server.requestCleanup() is invoked to finish processing the
* request.
*/
var FR_S_INIT = 'INIT';
var FR_S_QUEUED = 'QUEUED';
var FR_S_RUNNING = 'RUNNING';
var FR_S_COMPLETE = 'COMPLETE';
/*
* Fail the given RPC request with the specified error. This entry point is
* invoked by RPC implementors returning an error.
*/
FastServer.prototype.requestFail = function (request, error)
{
mod_assertplus.ok(request instanceof FastRpcServerRequest);
mod_assertplus.ok(error instanceof Error,
'failure must be represented as an Error instance');
request.fsr_error = error;
request.fsr_state = FR_S_COMPLETE;
request.fsr_log.debug(error, 'request failed');
var crc_mode = request.fsr_message.crc_mode;
request.fsr_conn.fc_msgencoder.write(requestMakeMessage(
request, mod_protocol.FP_STATUS_ERROR, error, crc_mode));
/*
* In the case of normal termination, the implementor ends the
* context stream, which tears down the pipeline between that
* stream, the request's encoder, and the connection's encoder.
* In this case, though, that pipeline is still set up, and we
* must explicitly tear it off at the connection end of the
* pipeline so the rest can be garbage collected.
*/
request.fsr_encoder.unpipe(request.fsr_conn.fc_msgencoder);
this.requestCleanup(request);
};
/*
* Mark the given RPC request having completed successfully. This is implicitly
* invoked by RPC implementors when they end their output stream.
*/
FastServer.prototype.requestComplete = function (request)
{
mod_assertplus.equal(request.fsr_state, FR_S_RUNNING);
request.fsr_state = FR_S_COMPLETE;
request.fsr_log.debug('request completed normally');
this.requestCleanup(request);
};
/*
* Disconnect this request from the underlying connection, usually because the
* connection has failed. We do not have a great way to signal cancellation to
* the RPC method handler, so we allow the request to complete and ignore any
* data sent. This should not be a big deal, since Fast RPC requests are
* intended to be very bounded in size anyway.
*/
FastServer.prototype.requestDisconnect = function (request)
{
mod_assertplus.ok(request instanceof FastRpcServerRequest);
if (request.fsr_state != FR_S_RUNNING) {
mod_assertplus.equal(request.fsr_state, FR_S_COMPLETE);
return;
}
mod_assertplus.ok(request.fsr_error === null);
mod_assertplus.ok(request.fsr_blackhole === null);
request.fsr_log.info('disconnecting request');
request.fsr_context.unpipe(request.fsr_encoder);
request.fsr_encoder.unpipe(request.fsr_conn.fc_msgencoder);
request.fsr_encoder.removeListener('end', request.fsr_docomplete);
request.fsr_blackhole = new NullSink();
request.fsr_context.pipe(request.fsr_blackhole);
request.fsr_blackhole.on('finish', request.fsr_docomplete);
};
/*
* Common function for completing execution of the given RPC request.
*/
FastServer.prototype.requestCleanup = function (request)
{
var conn;
var self = this;
var diff;
var latency;
var labels;
mod_assertplus.equal(request.fsr_state, FR_S_COMPLETE);
conn = request.fsr_conn;
mod_assertplus.ok(conn.fc_pending.hasOwnProperty(request.fsr_msgid));
mod_assertplus.ok(conn.fc_pending[request.fsr_msgid] == request);
delete (conn.fc_pending[request.fsr_msgid]);
conn.fc_ncompleted++;
this.fs_nrequests_completed++;
if (this.fs_collector) {
/* Record metrics */
/* Calculate milliseconds since the request began. */
diff = process.hrtime(request.fsr_hrtstarted);
latency = mod_jsprim.hrtimeMillisec(diff);
/* Track the requested RPC methoad. */
labels = { 'rpcMethod': request.fsr_rpcmethod };
this.fs_request_counter.increment(labels);
this.fs_latency_histogram.observe((latency / 1000), labels);
}
if (request.fsr_handler !== null) {
request.fsr_handler.fh_ncompleted++;
/*
* If we never assigned a handler, then we didn't fire the
* rpc-start probe.
*/
this.fs_dtp.fire('rpc-done', function () {
return ([ self.fs_dtid,
conn.fc_connid, request.fsr_msgid ]);
});
}
if (request.fsr_error !== null) {
conn.fc_nfailed++;
this.fs_nrequests_failed++;
if (request.fsr_handler !== null) {
request.fsr_handler.fh_nerrors++;
}
}
if (conn.fc_draining) {
this.connDrain(conn);
}
};
/*
* Helper classes
*
* The classes below generally contain no methods of their own except as needed
* to implement various object-mode streams.
*/
/*
* Each FastRpcHandler instance represents a registered RPC method. Besides the
* user's handler, we keep track of basic stats about this handler's usage.
* Named arguments include:
*
* rpcmethod string name of the RPC method
*
* rpchandler JavaScript function invoked for each outstanding
* request.
*