All files / Nodejs/lib/stream/helper chunkEventStream.js

79.34% Statements 73/92
70.73% Branches 58/82
92.3% Functions 12/13
79.34% Lines 73/92

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  1x 1x 1x   1x 5x 5x 5x                         5x 5x     5x                     5x   5x 8x 8x     5x     4x 4x 4x 4x 4x 4x                       4x     4x   4x     5x               9x 9x     9x 5x             9x 9x 9x 9x 9x       8x 2x 2x 1x                 2x 2x 2x 2x 1x   2x 2x     2x       2x               9x           9x 1x     1x 1x 1x   1x 1x     8x             8x     8x 8x   8x 8x   8x                               8x   8x               8x               4x 4x 4x   4x       5x 5x 5x     5x    
'use strict';
const logger = require('leo-logger')('chunkEventStream');
const refUtil = require('../../reference.js');
const zlib = require('zlib');
 
module.exports = function(ls, event, opts) {
	var tenMB = 1024 * 1024 * 10;
	var twoHundredK = 1024 * 200;
	opts = Object.assign({
		records: (opts && opts.records) || (opts && opts.useS3Mode ? Number.POSITIVE_INFINITY : 2000),
		size: (opts && opts.size) || (opts && opts.useS3Mode ? tenMB : twoHundredK),
		time: (opts && opts.time) || {
			seconds: opts && opts.useS3Mode ? tenMB : twoHundredK
		},
		archive: false,
		debug: false,
		gzip: true,
		snapshot: undefined
	}, opts || {});
 
	var item, gzip;
	var totalWrites = 0;
	var totalRecords = 0;
 
	function resetGzip() {
		item = {
			event: event,
			gzip: Buffer.from(''),
			start: opts.archive ? null : 0,
			end: null,
			records: 0,
			size: 0,
			gzipSize: 0,
			stats: {},
			correlations: {}
		};
		gzip = opts.gzip ? zlib.createGzip() : require("stream").PassThrough();
 
		gzip.on('data', function(chunk) {
			item.gzip = Buffer.concat([item.gzip, chunk]);
			item.gzipSize += Buffer.byteLength(chunk);
		});
	}
	resetGzip();
 
	function emitChunk(last, callback) {
		gzip.once('end', () => {
			logger.debug(`Byte ratio  ${Buffer.byteLength(item.gzip)}/${item.size}  ${Buffer.byteLength(item.gzip) / item.size}`);
			logger.debug(`Capacity ratio  ${Math.ceil(Buffer.byteLength(item.gzip) / 1024)}/${item.records}  ${Math.ceil(Buffer.byteLength(item.gzip) / 1024) / item.records}`);
			totalWrites += Math.ceil(Buffer.byteLength(item.gzip) / 1024);
			totalRecords += item.records;
			var i = {
				event: item.event,
				start: item.start,
				end: item.end,
				records: item.records,
				gzip: item.gzip,
				gzipSize: item.gzipSize,
				size: item.size,
				stats: item.stats,
				correlations: item.correlations,
				snapshot: opts.snapshot
			};
			Iif (!last) {
				resetGzip();
			}
			callback(i);
		});
		gzip.end();
	}
 
	var eventStream = ls.buffer({
		label: "chunkEventStream",
		time: opts.time,
		size: opts.size,
		records: opts.records,
		buffer: opts.buffer,
		debug: opts.debug
	}, function write(record, done) {
		let timestamp = record.timestamp = record.timestamp || Date.now();
		let start = record.event_source_timestamp = (record.event_source_timestamp || timestamp);
 
		function updateStats(id, stats) {
			if (!(id in item.stats)) {
				item.stats[id] = {
					start: 0,
					end: 0,
					units: 0,
					checkpoint: null
				};
			}
			let eventData = item.stats[id];
			eventData.units += (stats.units || 1);
			eventData.start = Math.max(start, eventData.start);
			eventData.end = Math.max(timestamp, eventData.end);
			eventData.checkpoint = stats.checkpoint || stats.eid;
		}
 
		function updateCorrelation(c) {
			if (c) {
				var source = c.source;
				if (!(source in item.correlations)) {
					item.correlations[source] = {
						source: source,
						start: null,
						end: null,
						records: 0,
						source_timestamp: start,
						timestamp: timestamp
					};
				}
				let correlation = item.correlations[source];
				correlation.end = c.end || c.start;
				correlation.records += c.units || 1;
				if (!correlation.start) {
					correlation.start = c.start;
				}
				correlation.source_timestamp = start;
				correlation.timestamp = timestamp;
 
				// Allow for partial start and end so we see correlation but don't checkpoint
				Iif (!c.start && c.partial_start) {
					c.start = c.partial_start;
					delete c.partial_start;
				}
				Iif (!c.end && c.partial_end) {
					c.end = c.partial_end;
					delete c.partial_end;
				}
			}
		}
 
		//If there is no payload but there is a correlation_id then we just need to skip this record but store the checkpoint as processed
		Iif ((!record.payload || record.dont_write === true) && record.correlation_id) {
			updateCorrelation(record.correlation_id);
			done(null, {});
			return;
		}
 
		if (record.s3) {
			Iif (opts.snapshot) {
				record.snapshot = opts.snapshot;
			}
			this.flush(() => {
				for (var id in record.stats) {
					updateStats(id, record.stats[id]);
				}
				this.push(record);
				done();
			});
		} else {
			Iif (opts.archive) {
				if (!item.start) {
					item.start = record.eid;
				}
				item.end = record.eid;
				item.records++;
			} else {
				item.end = record.eid = item.records++;
			}
 
			updateStats(record.id, record);
			updateCorrelation(record.correlation_id);
 
			var d = JSON.stringify(record) + "\n";
			var s = Buffer.byteLength(d);
 
			Iif (!opts.useS3Mode && s > opts.size * 3) {
				var newR = Object.assign({}, record, {
					event: refUtil.botRef(record.id).queue("error"),
					payload: {
						size: s,
						maxSize: opts.size * 3,
						error: `Event was too large ${s} > ${opts.size * 3}`,
						preview: d.substr(0, 2000)
					}
				});
				logger.log(newR.payload.error, `skipping`, record.id, record.eid, record.correlation_id, newR.payload.preview);
 
				d = JSON.stringify(newR) + "\n";
				s = Buffer.byteLength(d);
 
			}
			item.size += s;
 
			Iif (!gzip.write(d)) {
				gzip.once('drain', () => {
					done(null, {
						size: s,
						records: 1
					});
				});
			} else {
				done(null, {
					size: s,
					records: 1
				});
			}
		}
	},
		function emit(done, data) {
			emitChunk(data.isLast, (value) => {
				Eif (value && (value.size || (value.correlations && Object.keys(value.correlations).length))) {
					this.push(value);
				}
				done();
			});
		},
		function end(done) {
			logger.debug("done chunking");
			logger.debug("total", totalWrites, totalRecords, totalWrites / totalRecords);
			done();
		});
 
	return eventStream;
};