All files server.js

100% Statements 148/148
100% Branches 41/41
100% Functions 35/35
100% Lines 145/145

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              86526x 86526x 46196x 6x   46190x 46190x   36x           41915x   41845x               570x 570x 570x 570x 570x 570x       42328x 29x         83792x 83792x 83792x       41241x 41241x   83792x 83792x 83792x 82939x       41241x 41241x       535x 36x   535x       167160x 167160x 83756x 83756x 19755x     64001x         84148x       481x 62x   419x       569x 569x           2x   2x 2x 2x       2x   2x       2x       4x 2x 2x         19x   19x   19x 18x 18x 1x       19x 43014x             43548x 42978x 42978x   42978x 42978x 42978x           43014x 36x   36x     42978x   42978x   42978x   570x   570x       42400x 42400x 42400x 642x           642x     41758x   41758x 41758x 42175x 41758x 41758x 41758x                 41758x 417x 417x 417x   41758x 41758x   41758x 535x 535x 535x     41758x 299x 299x 82x   299x           41459x 236x 236x     41223x 41223x 218x   41005x 41005x 41005x 40997x 40997x 42116x 42116x 40997x           41223x       8x           8x 8x       42978x         570x 570x 570x 570x 570x 570x   570x 570x 569x 569x 569x   570x               570x 570x   570x       2x 2x   2x         4x 2x 2x 2x 2x 2x          
/*eslint-env node */
import EventEmitter from 'events';
import { randomBytes } from 'crypto';
import { Duplex, Writable } from 'stream';
import { constants } from 'http2';
 
function ex_to_err(obj, method, check) {
    const orig_method = obj[method];
    obj[method] = function (...args) {
        if (check && check.call(this)) {
            return;
        }
        try {
            orig_method.apply(this, args);
        } catch (ex) {
            obj.emit('error', ex);
        }
    };
}
 
function ignore_reset_code() {
    Object.defineProperty(this, 'rstCode', {
        get() {
            return constants.NGHTTP2_NO_ERROR;
        },
        configurable: true
    });
}
 
class ServerDuplex extends Duplex {
    constructor(stream, options) {
        super(options);
        this.stream = stream;
        this.options = options;
        this.need_chunk = false;
        this.chunks = [];
        this.forward_errors(stream);
    }
 
    forward_errors(stream) {
        stream.on('error', err => {
            this.emit('error', err);
        });
    }
 
    push_next() {
        const { chunk, cb } = this.chunks.shift();
        process.nextTick(cb);
        return this.push(chunk);
    }
 
    sink(stream) {
        const ths = this;
        const r = new Writable(Object.assign({}, this.options, {
            write(chunk, encoding, cb) {
                ths.chunks.push({ chunk, cb });
                this.emit('written', chunk.length);
                if (ths.need_chunk) {
                    ths._read();
                }
            }
        }));
        stream.pipe(r);
        return r;
    }
 
    drain_and_end() {
        while (this.chunks.length > 0) {
            this.push_next();
        }
        this.push(null);
    }
 
    _read() {
        this.need_chunk = this.chunks.length === 0;
        if (!this.need_chunk) {
            while (this.chunks.length > 0) {
                if (!this.push_next()) {
                    return;
                }
            }
            this.need_chunk = true;
        }
    }
 
    _write(chunk, encoding, cb) {
        this.stream.write(chunk, encoding, cb);
    }
 
    _final(cb) {
        if (this.stream._writableState.ending) {
            return cb();
        }
        this.stream.end(cb);
    }
 
    _destroy(err, cb) {
        this.stream.destroy(err);
        cb(err);
    }
}
 
export class Http2DuplexServer extends EventEmitter {
    constructor(http2_server, path, options) {
        super();
 
        this.http2_server = http2_server;
        this.path = path;
        this.options = Object.assign({
            close_timeout: 1000,
            autoDestroy: true
        }, options);
        this.sessions = new Set();
 
        this.common_headers = {
            'Cache-Control': 'max-age=0, no-cache, must-revalidate, proxy-revalidate'
        };
 
        this.attach();
    }
 
    attach() {
        if (!this.session_listener) {
            this.session_listener = this.process_session.bind(this);
            this.http2_server.on('session', this.session_listener);
        }
    }
 
    async process_session(session) {
        const duplexes = new Map();
 
        this.sessions.add(session);
 
        session.on('close', () => {
            this.sessions.delete(session);
            for (let duplex of duplexes.values()) {
                duplex.push(null);
            }
        });
 
        session.on('stream', async (stream, headers, flags, raw_headers) => {
            await this.process_stream(
                stream, headers, flags, raw_headers,
                duplexes, { ...this.common_headers });
        });
    }
 
    own_stream(stream) {
        if (!stream.http2_duplex_owned) {
            ex_to_err(stream, 'respond', function () {
                return this.closed || this.destroyed;
            });
            ex_to_err(stream, 'close');
            stream.on('aborted', ignore_reset_code);
            stream.http2_duplex_owned = true;
        }
    }
 
    async process_stream(stream, headers, flags, raw_headers,
        duplexes, response_headers) {
        if (headers[':path'] !== this.path) {
            this.emit('unhandled_stream', stream, headers, flags, raw_headers,
                duplexes, response_headers);
            return false;
        }
 
        this.own_stream(stream);
 
        const method = headers[':method'];
 
        switch (method) {
            case 'GET': {
                await this.new_stream(stream, headers, flags, raw_headers,
                    duplexes, response_headers);
                break;
            }
 
            case 'POST': {
                const id = headers['http2-duplex-id'];
                const duplex = duplexes.get(id);
                if (!duplex) {
                    stream.respond({
                        ':status': 404,
                        ...response_headers
                    }, {
                        endStream: true
                    });
                    break;
                }
 
                duplex.forward_errors(stream);
 
                let responded = false;
                const respond = () => {
                    if (!responded) {
                        responded = true;
                        ignore_reset_code.call(stream);
                        stream.respond({
                            ':status': 200,
                            ...response_headers
                        }, {
                            endStream: true
                        });
                    }
                };
 
                const on_close = () => {
                    respond();
                    const timeout = setTimeout(() => stream.close(), this.options.close_timeout);
                    stream.on('close', () => clearTimeout(timeout));
                };
                duplex.on('close', on_close);
                stream.on('close', () => duplex.removeListener('close', on_close));
 
                const end = () => {
                    duplex.drain_and_end();
                    duplexes.delete(id);
                    respond();
                };
 
                if (headers['http2-duplex-end'] === 'true') {
                    end();
                    if (headers['http2-duplex-destroyed'] === 'true') {
                        duplex.stream.close();
                    }
                    break;
                }
 
                // Note: http2 streams always emit 'end' when they close.
                // See onStreamClose() and _destroy() in lib/internal/http2/core.js
 
                if (headers['http2-duplex-single'] === 'true') {
                    duplex.sink(stream).on('finish', end);
                    break;
                }
 
                const content_length = parseInt(headers['content-length'], 10);
                if (content_length === 0) {
                    respond();
                } else {
                    const sink = duplex.sink(stream);
                    sink.on('finish', respond);
                    if (content_length > 0) {
                        let received = 0;
                        sink.on('written', len => {
                            received += len;
                            if (received >= content_length) {
                                stream.push(null);
                            }
                        });
                    }
                }
 
                break;
            }
 
            default: {
                stream.respond({
                    ':status': 405,
                    ...response_headers
                }, {
                    endStream: true
                });
                this.emit('warning', new Error(`unknown method: ${method}`));
                break;
            }
        }
 
        return true;
    }
 
    async new_stream(stream, headers, flags, raw_headers,
        duplexes, response_headers) {
        const duplex = new ServerDuplex(stream, this.options);
        const id = randomBytes(64).toString('base64');
        duplexes.set(id, duplex);
        ex_to_err(duplex, 'end');
        const on_close = () => {
            duplex.end();
        };
        stream.on('close', on_close);
        duplex.on('close', () => {
            stream.removeListener('close', on_close);
            duplexes.delete(id);
            stream.close();
        });
        stream.respond({
            ':status': 200,
            'http2-duplex-id': id,
            'Access-Control-Expose-Headers': 'http2-duplex-id',
            'Content-Type': 'application/octet-stream',
            ...response_headers
        });
        // Sometimes fetch waits for first byte before resolving
        stream.write('a');
        this.emit('duplex', duplex, id, headers, flags, raw_headers,
            duplexes, response_headers);
        return duplex;
    }
 
    destroy(obj) {
        try {
            obj.destroy();
        } catch (ex) {
            this.emit('warning', ex);
        }
    }
 
    detach() {
        if (this.session_listener) {
            this.http2_server.removeListener('session', this.session_listener);
            this.session_listener = null;
            for (let session of this.sessions) {
                session.removeAllListeners('stream');
                this.destroy(session);
            }
        }
    }
}