Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2466x 4x 4x 4x 1x 192x 192x 192x 192x 192x 192x 192x 192x 192x 192x 192x 192x 192x 1272x 1272x 1144x 1140x 1140x 552x 552x 552x 552x 552x 548x 548x 548x 548x 548x 552x 552x 552x 3804x 3804x 288x 288x 3804x 3804x 3156x 3156x 3804x 2084x 1720x 1720x 460x 460x 1260x 1260x 364x 364x 1260x 48x 1260x 1260x 1256x 4x 4x 4x 1256x 680x 1252x 4x 4x 1272x 1272x 1272x 8x 1840x 1264x 1264x 1264x 1264x 8x 1256x 16x 1240x 8x 32x 16x 16x 1232x 40x 1192x 1192x 1192x 20x 1192x 1192x 1192x 1192x 136x 116x 20x 1192x 1176x 516x 516x 488x 516x 16x 516x 8x 8x 508x 508x 188x 320x 508x 476x 508x 660x 577x 577x 577x 577x 577x 577x 577x 7794x 577x 16x 577x 660x 660x 660x 652x 660x 648x 660x 648x 660x 24x 24x 636x 644x 636x 56x 580x 580x 290x 580x 576x 576x 576x 576x 576x 288x 144x 1192x 540x 540x 1192x 8x 1184x 192x 192x 192x 192x 192x 46x 46x 192x 96x 96x 108x 108x 108x 96x 192x 192x 192x 192x 192x 192x 96x 96x 46x 192x 96x 96x 48x 96x 192x 96x 96x 1x | /*eslint-env node */
/**
* HTTP transport. This allows messages to be published using HTTP POST requests
* and received using HTTP Server-Sent Events.
*
* Publish messages using POST requests of the form:
*
* ```
* /centro/v2/publish?authz_token=XXX&topic=YYY
* ```
*
* - `XXX` is a {@link http://self-issued.info/docs/draft-ietf-oauth-json-web-token.html|JSON Web Token} allowing access to the server. See {@link https://github.com/davedoesdev/centro#authz-tokens|here} for more information about Centro authorization tokens.
* - `YYY` is the message's topic. Topics should be in AMQP format: `.` delimits words.
* - The request body should contain the message's data. The server doesn't
* interpret the data, it just treats it as a binary stream.
*
* Subscribe to messages using GET requests of the form:
*
* ```
* /centro/v2/subscribe?authz_token=XXX&topic=YYY&topic=ZZZ
* ```
*
* - `XXX` is the authorization token allowing access to the server.
* - `YYY` is the message topic to which to subscribe. Topics should be in AMQP format: `.` delimits words, `*` matches exactly one word and `#` matches zero or more words.
* - You can specify more than one topic, e.g. `ZZZ` above.
*
* Messages you've subscribed to are delivered using server-sent events. Each
* message begins with a `start` event, continues with multiple `data` events
* and finishes with an `end` event.
*
* For example, consider a message with topic `foo.bar` and body `wow`. You
* could receive the following events:
*
* ```
* type: start
* data: {"id":0,"single":false,"existing":false,"expires":1498375188,"size":3,"topic":"foo.bar"}
*
* type: data
* data: {"id":0,"data":"wow"}
*
* type: end
* data: {"id":0}
* ```
*
* For larger messages you may receive multiple `data` messages. The event
* data for each event is JSON-encoded and always contains a message `id`
* (in this case `0`). If you're receiving multiple messages at the same time,
* their events may be interleaved so you need to use the `id` to tell which
* event is for which message. The `id` identifies the message for this
* connection only - it isn't globally unique and the same message may have a
* different `id`s on different connections.
*
* In the `start` event, you'll receive whether the messages is being delivered
* to a `single` subscriber, whether it's an `existing` message (i.e. published
* before we subscribed), when it `expires` (in seconds since 1970-01-01),
* the `size` of its body data and its `topic`.
*
* In the `data` event, you'll receive (part of) the message's body (`wow` in
* this case). Since this is JSON-encoded, the data will be a UTF-8 encoded
* string, even for binary data. If you need to get the raw binary data,
* encode the string as latin-1 and use the bytes in the result (the server
* decodes the bytes as latin-1 before JSON encoding the result).
*
* Note that server-sent _event IDs_ and the `Last-Event-ID` header are not
* supported because when a connection drops, the server forgets all about it.
*
* @module centro-js/lib/server_transports/http
* @param {Object} config - Configuration options. This supports all the options supported by {@link https://nodejs.org/api/net.html#net_server_listen_options_callback|net.Server#listen} and {@link https://nodejs.org/api/https.html#https_https_createserver_options_requestlistener|https.createServer} as well as the following:
* @param {http.Server|https.Server} [config.server] - If you want to supply your own HTTP or HTTPS server object. Otherwise, {@link https://nodejs.org/api/http.html#http_http_createserver_requestlistener|http.createServer} or {@link https://nodejs.org/api/https.html#https_https_createserver_options_requestlistener|https.createServer} will be called to create one.
* @param {string} [config.pathname=/centro/v2/] - Pathname prefix on which to listen for requests. Publish requests are made on `/centro/v2/publish` and subscribe requests are made on `/centro/v2/subscribe`.
* @param {integer} [config.sse_keep_alive_interval] - If present, the number of seconds between sending a Server-Sent Event comment in order to keep a connection alive. If you don't specify this, no keep-alive comments will be sent.
* @param {integer} [config.destroy_after_end_delay=500] - Amount of time (in milliseconds) to wait between {@link https://nodejs.org/api/http.html#http_response_end_data_encoding_callback|end}ing a response and {@link https://nodejs.org/api/http.html#http_message_destroy_error|destroy}ing the connection, if an error occurs which means the connection can't be re-used. If you don't want the connection forcibly destroyed, set this to a negative value.
* @param {Object} [config.http] - If present then this is used in preference to `config`.
* @param {Object} [config.access] - Passed to {@link https://github.com/primus/access-control|access-control}.
* @param {boolean} [config.http2] - Whether to use {@link https://tools.ietf.org/html/rfc7540|HTTP/2} ({@link https://nodejs.org/api/http2.html#http2_http2_createserver_options_onrequesthandler|http2.createServer}/{@link https://nodejs.org/api/http2.html#http2_http2_createsecureserver_options_onrequesthandler|http2.createSecureServer}) instead of HTTP. Note this still uses Server-Sent Events to deliver messages. If you want to use HTTP/2 streams to deliver messages, see the {@link centro-js/lib/server_transports/http2|http2} and {@link centro-js/lib/server_transports/http2-duplex|http2-duplex} transports. Defaults to `false`.
*/
"use strict";
var http = require('http'),
https = require('https'),
http2 = require('http2'),
async = require('async'),
Duplex = require('stream').Duplex,
LeftDuplex = require('./in-mem').LeftDuplex,
Transform = require('stream').Transform,
centro = require('../..'),
Ajv = require('ajv'),
ajv = new Ajv(),
access = require('access-control'),
{ get_topic_pattern } = require('../pattern');
function on_connection(warning, conn)
{
conn.on('error', function (err)
{
warning(err);
try
{
this.destroy();
}
catch (ex)
{
/* istanbul ignore next */
warning(ex);
}
});
}
module.exports = function (config, authorize, connected, ready, error, warning)
{
config = config.http || config;
var certs = config.key && config.cert,
port = config.port || /* istanbul ignore next */ 443,
secure = certs || port === 443,
server = config.server ||
(secure ? (config.http2 ? http2.createSecureServer(config) :
https.createServer(config)) :
(config.http2 ? http2.createServer(config) :
http.createServer(config))),
pathname = config.pathname || ('/centro/v' + centro.version + '/'),
pub_pathname = pathname + 'publish',
sub_pathname = pathname + 'subscribe',
cors = access(Object.assign(
{
methods: ['GET', 'POST', 'OPTIONS']
}, config.access)),
destroy_after_end_delay = Object.assign(
{
destroy_after_end_delay: 500
}, config).destroy_after_end_delay,
topic_pattern = get_topic_pattern(config);
var validate_pub = ajv.compile({
type: 'object',
required: ['topic'],
properties: {
topic: {
type: 'string',
pattern: topic_pattern
},
n: {
type: 'integer'
},
single: {
type: 'boolean'
},
ttl: {
type: 'integer'
}
}
});
var validate_sub = ajv.compile({
type: 'object',
required: ['topics'],
properties: {
topics: {
type: ['array'],
minItems: 1,
maxItems: config.max_subscribe_topics,
items: {
type: 'string',
pattern: topic_pattern
}
},
ns: {
type: ['array'],
maxItems: config.max_subscribe_topics,
items: {
type: 'integer',
}
}
}
});
function request(req, res)
{
var closed = false,
headers_written = false,
left,
sse_interval;
function end_response(code, data)
{
res.end(data);
closed = true;
if ((code === 503) && (destroy_after_end_delay >= 0))
{
var cleanup = function ()
{
clearTimeout(timeout);
res.removeListener('close', cleanup);
res.removeListener('finish', destroy);
};
var destroy = function ()
{
cleanup();
try
{
req.destroy();
}
catch (ex)
{
/* istanbul ignore next */
warning(ex);
}
try
{
res.destroy();
}
catch (ex)
{
/* istanbul ignore next */
warning(ex);
}
};
var timeout = setTimeout(destroy, destroy_after_end_delay);
res.on('close', cleanup);
res.on('finish', destroy);
}
}
function done(code, data, err, headers, only_headers)
{
warning(err);
if (sse_interval !== undefined)
{
clearInterval(sse_interval);
sse_interval = undefined;
}
try
{
if (left && (closed || !only_headers))
{
process.nextTick(function ()
{
left.destroy();
});
}
if (closed)
{
return false;
}
code = code || 500;
if (headers_written)
{
end_response(code);
return false;
}
data = typeof data === 'string' ? data : 'server error';
if (data)
{
data = JSON.stringify({ error: data });
res.setHeader('Content-Type', 'application/json');
}
if ((code === 503) && !config.http2)
{
res.setHeader('Connection', 'close');
}
try
{
res.writeHead(code, headers);
headers_written = true;
}
catch (ex)
{
warning(ex);
end_response(code, data);
return false;
}
if (!only_headers)
{
end_response(code, data);
}
return true;
}
catch (ex)
{
warning(ex);
return false;
}
}
req.on('error', warning);
res.on('error', warning);
if (cors(req, res))
{
return;
}
function onclose()
{
closed = true;
}
res.on('prefinish', onclose);
res.on('close', onclose);
var url = require('url').parse(req.url, true);
if ((url.pathname !== pub_pathname) &&
(url.pathname !== sub_pathname))
{
return done(404, 'not found');
}
if (((url.pathname === pub_pathname) && (req.method !== 'POST')) ||
((url.pathname === sub_pathname) && (req.method !== 'GET')))
{
return done(405, 'method not allowed');
}
authorize(req, function ()
{
done(503, 'closed');
}, function (cb)
{
if (req.socket.destroyed)
{
return cb();
}
req.socket.on('close', cb);
}, function (err, handshakes, tokens)
{
if (err)
{
return done(err.statusCode,
err.message,
null,
{
'WWW-Authenticate': err.authenticate
});
}
left = new LeftDuplex(Object.assign(
{
allowHalfOpen: false,
autoDestroy: true,
destroy_wait: 1000
}, config));
left.on('close', function ()
{
done(503, 'closed');
});
function error(err)
{
left.emit('error', err);
}
req.on('error', error);
res.on('error', error);
var mqclient = centro.start(left, Object.assign(
{
token: tokens
}, config));
mqclient.on('error', function (err, obj)
{
if (obj instanceof Duplex)
{
return warning(err);
}
done(null, null, err);
});
mqclient.on('ready', function ()
{
var options, txt;
if (url.pathname === pub_pathname)
{
options = {
topic: url.query.topic,
n: 0,
single: url.query.single === 'true',
};
if (url.query.n !== undefined)
{
options.n = parseInt(url.query.n);
}
if (url.query.ttl !== undefined)
{
options.ttl = parseInt(url.query.ttl);
}
if (!validate_pub(options))
{
txt = ajv.errorsText(validate_pub.errors);
return done(400, txt, new Error(txt));
}
var ps = this.publish(options.n, options.topic, options, function (err)
{
if (err)
{
return done(null, null, err);
}
done(200, '');
});
if (ps)
{
req.pipe(ps);
}
return;
}
var last_msgid = 0;
function handler(s, info, cb)
{
var msgid = last_msgid++,
t = new Transform();
res.write('event: start\ndata: ' +
JSON.stringify(Object.assign(
{
id: msgid
}, info)) + '\n\n');
t.on('end', function ()
{
res.write('event: end\ndata: ' +
JSON.stringify(
{
id: msgid
}) + '\n\n');
cb();
});
t._transform = function (chunk, encoding, cb)
{
cb(null, 'event: data\ndata: ' +
JSON.stringify(
{
id: msgid,
data: chunk.toString('binary')
}) + '\n\n');
};
s.on('error', function ()
{
// Error will be logged via mqclient error event
res.write('event: peer_error\ndata: ' +
JSON.stringify(
{
id: msgid
}) + '\n\n');
});
s.pipe(t).pipe(res, { end: false });
}
options = Object.assign({
n: []
}, url.query);
options = {
topics: options.topic,
ns: options.n
};
if (typeof options.topics === 'string')
{
options.topics = [options.topics];
}
if (typeof options.ns === 'string')
{
options.ns = [options.ns];
}
options.ns = options.ns.map(function (n)
{
return parseInt(n);
});
if (!validate_sub(options))
{
txt = ajv.errorsText(validate_sub.errors);
return done(400, txt, new Error(txt));
}
async.timesSeries(options.topics.length, async.ensureAsync(function (i, next)
{
mqclient.subscribe(options.ns[i] || 0,
options.topics[i],
handler,
next);
}), function (err)
{
if (err)
{
return done(null, null, err);
}
var headers = {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
};
if (!config.http2)
{
headers.Connection = 'keep-alive';
}
if (done(200, '', null, headers, true))
{
res.setTimeout(0);
res.on('prefinish', done);
res.on('close', done);
res.write(':ok\n\n');
if (config.sse_keep_alive_interval)
{
sse_interval = setInterval(function ()
{
res.write(':ka\n\n');
}, config.sse_keep_alive_interval * 1000);
}
}
});
});
connected(handshakes,
left.right,
function (mqserver, now)
{
left.right.destroy(undefined, now);
done(503, 'closed');
},
function (cb)
{
if (left.right.destroyed)
{
return cb();
}
left.right.on('close', cb);
});
});
}
server.on('request', request);
server.on('error', error);
const on_conn = on_connection.bind(server, warning);
server.on('connection', on_conn);
server.on('secureConnection', on_conn);
function destroy_session(session)
{
try
{
session.destroy();
}
catch (ex)
{
/* istanbul ignore next */
warning(ex);
}
}
let sessions;
let on_session;
if (config.http2)
{
sessions = new Set();
on_session = function (session)
{
sessions.add(session);
session.on('close', function ()
{
sessions.delete(this);
});
};
server.on('session', on_session);
}
function listening()
{
ready(null,
{
close: function (cb)
{
server.removeListener('request', request);
server.removeListener('error', error);
server.removeListener('connection', on_conn);
server.removeListener('secureConnection', on_conn);
if (config.http2)
{
server.removeListener('session', on_session);
for (var session of sessions)
{
destroy_session(session);
}
}
if (config.server)
{
return cb();
}
if (config.http2)
{
server.on('session', destroy_session);
}
server.close(cb);
},
server: server,
pub_pathname: pub_pathname,
sub_pathname: sub_pathname
});
}
if (config.server)
{
return listening();
}
server.listen(config, listening);
};
module.exports.on_connection = on_connection;
|