All files / centro/lib/server_transports http2.js

100% Statements 72/72
100% Branches 33/33
100% Functions 16/16
100% Lines 72/72

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                                    1x 1x 1x   1x           1024x       1964x   1024x 1024x       1024x   8x   1016x 1016x     1x   124x   124x 124x 124x 124x     124x 124x       124x 124x       524x   524x                     140x   140x 140x   140x     140x   556x   556x 556x 556x   4x     552x   4x                     548x   4x                     544x   4x                     540x 540x   540x     540x 540x   540x   476x     540x   8x                     16x     532x   64x               64x     468x               468x       60x       468x           124x 124x       124x       124x 124x   124x   48x 48x     124x   62x     62x 62x               124x   62x     62x    
/*eslint-env node */
 
/**
 * HTTP/2 transport. This allows messages to be sent over HTTP/2 streams.
 *
 * Note that this transport won't work with browser clients. You'll need to use
 * the {@link centro-js/lib/server_transports/http2-duplex|http2-duplex}
 * transport with browsers.
 *
 * @module centro-js/lib/server_transports/http2
 * @param {Object} config - Configuration options. This supports all the options supported by {@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} and {@link https://nodejs.org/api/net.html#net_server_listen_options_callback|net.Server#listen} as well as the following:
 * @param {http2.Http2Server|http2.Http2SecureServer} [config.server] - If you want to supply your own HTTP/2 server object. Otherwise, {@link https://nodejs.org/api/http2.html#http2_http2_createserver_options_onrequesthandler|http2.createServer} or {https://nodejs.org/api/http2.html#http2_http2_createsecureserver_options_onrequesthandler|http2.createSecureServer} will be called to create one.
 * @param {string} [config.pathname=/centro/v2/http2] - Pathname prefix on which to listen for requests.
 * @param {Object} [config.http2] - 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}.
 */
"use strict";
 
var http2 = require('http2'),
    centro = require('../..'),
    access = require('access-control');
 
const common_headers = {
    'Cache-Control': 'max-age=0, no-cache, must-revalidate, proxy-revalidate'
};
 
function on_close(stream, cb)
{
    let called = false;
 
    function cb2()
    {
        if (!called)
        {
            called = true;
            cb();
        }
    }
 
    if (stream.closed)
    {
        return cb2();
    }
    stream.on('close', cb2);
    stream.on('aborted', cb2);
}
 
module.exports = function (config, authorize, connected, ready, error, warning)
{
    config = config.http2 || config;
 
    var certs = config.key && config.cert,
        port = config.port || /* istanbul ignore next */ 443,
        secure = certs || port === 443,
        server = config.server || 
                 (secure ? http2.createSecureServer(config) :
                           http2.createServer(config)),
        pathname = config.pathname || ('/centro/v' + centro.version + '/http2'),
        cors = access(Object.assign(
        {
            methods: ['GET', 'POST', 'OPTIONS']
        }, config.access)),
        sessions = new Set(),
        num_streams = 0;
 
    function destroy(obj)
    {
        try
        {
            obj.destroy();
        }
        catch (ex)
        {
            /* istanbul ignore next */
            warning(ex);
        }
    }
 
    function on_session(session)
    {
        session.on('error', warning);
 
        sessions.add(session);
        session.on('close', function ()
        {
            sessions.delete(this);
        });
 
        session.on('stream', function (stream, headers, flags, rawHeaders)
        {
            stream.on('error', warning);
 
            const req = new http2.Http2ServerRequest(stream, headers, undefined, rawHeaders);
            const res = new http2.Http2ServerResponse(stream);
            if (cors(req, res))
            {
                return;
            }
 
            if (headers[':path'] !== pathname)
            {
                return stream.respond(
                {
                    ':status': 404,
                    ...res.getHeaders(),
                    ...common_headers
                },
                {
                    endStream: true
                });
            }
 
            if (headers[':method'] !== 'POST')
            {
                return stream.respond(
                {
                    ':status': 405,
                    ...res.getHeaders(),
                    ...common_headers
                },
                {
                    endStream: true
                });
            }
 
            if (server.maxConnections && (num_streams >= server.maxConnections))
            {
                return stream.respond(
                {
                    ':status': 503,
                    ...res.getHeaders(),
                    ...common_headers
                },
                {
                    endStream: true
                });
            }
 
            ++num_streams;
            on_close(stream, function ()
            {
                --num_streams;
            });
 
            stream.headers = headers;
            stream.url = headers[':path'];
 
            stream.on('end', function ()
            {
                destroy(this);
            });
 
            authorize(stream, function ()
            {
                stream.respond(
                {
                    ':status': 503,
                    ...res.getHeaders(),
                    ...common_headers
                },
                {
                    endStream: true
                });
            }, function(cb)
            {
                on_close(stream, cb);
            }, function (err, handshakes, unused_tokens)
            {
                if (err)
                {
                    stream.respond(
                    {
                        ':status': err.statusCode,
                        'Content-Type': 'application/json',
                        'WWW-Authenticate': err.authenticate,
                        ...res.getHeaders(),
                        ...common_headers
                    });
                    return stream.end(JSON.stringify({ error: err.message }));
                }
 
                stream.respond(
                {
                    ':status': 200,
                    'Content-Type': 'application/octet-stream',
                    ...res.getHeaders(),
                    ...common_headers
                });
 
                connected(handshakes,
                          stream,
                          function ()
                          {
                              stream.close();
                          },
                          function (cb)
                          {
                              on_close(stream, cb);
                          });
            });
        });
    }
 
    server.on('session', on_session);
    server.on('error', error);
 
    function listening()
    {
        ready(null,
        {
            close: function (cb)
            {
                server.removeListener('session', on_session);
                server.removeListener('error', error);
 
                for (let session of sessions)
                {
                    session.removeAllListeners('stream');
                    destroy(session);
                }
 
                if (config.server)
                {
                    return cb();
                }
 
                server.on('session', destroy);
                server.close(cb);
            },
 
            server: server,
            pathname: pathname
        });
    }
 
    if (config.server)
    {
        return listening();
    }
 
    server.listen(config, listening);
};