All files / Nodejs/lib event-trace.ts

42.1% Statements 88/209
38.02% Branches 54/142
25% Functions 15/60
42.71% Lines 88/206

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 5761x   1x 1x     1x                                 1x 3x 3x 3x 3x   3x                                                                                                                             3x 3x   3x 3x 3x             3x 3x 237x 237x 237x     237x 138x 138x 54x         138x 138x 99x         138x   237x 243x 243x 180x         243x 243x 105x         243x         3x 3x       3x   3x 3x 7x 7x 7x           4x 4x 4x 4x           4x 4x 3x   4x           4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x             4x   7x 3x   7x     7x   3x       3x     8x     8x 8x 8x 27x 27x 27x 27x                   27x 14x 5x                       8x   3x                         14x                                                                                                                                                                                                                               1x                                                                                                                                                                                                                                                                                     1x                                                                                                         1x        
import async from "async";
import { RStreamsSdk } from "../index";
import moment from "moment";
import util from "./reference";
import { ReadEvent } from "./types";
 
const logger = require('leo-logger')('event-trace');
 
 
export interface EventTraceOptions {
	queue: string;
	eid: string;
	children?: string[];
}
 
export interface TraceReadEvent extends ReadEvent<any> {
	kinesis_number: any;
	lag: number;
	label: any;
	type: string;
	server_id: string;
}
 
export async function trace(sdk: RStreamsSdk, statsTableName: string, options: EventTraceOptions) {
	let ls = sdk.streams;
	let dynamodb = sdk.aws.dynamodb;
	let queue = util.ref(options.queue).toString();
	let id = options.eid;
 
	Iif (options.children) {
		let children = options.children;//.split(/,/);
 
		let results = {};
		logger.debug("With children", queue, prevId(id))
		return await new Promise((resolve, reject) => {
			ls.pipe(
				ls.fromLeo("test", queue, {
					start: prevId(id),
					limit: 1,
				}),
				ls.write(function (readEvent, done) {
					let event = readEvent as TraceReadEvent;
					let correlation = {
						start: event.eid || event.kinesis_number,
						timestamp: moment(event.timestamp),
						source: util.ref(event.event).id
					};
 
					async.doWhilst((done) => {
						let [bot_id, queue_id] = children.splice(0, 2).map((n, i) => util.ref(n, i == 0 && "bot"));
						searchCorrelationId(sdk, statsTableName, queue_id, bot_id, correlation, (err, event) => {
							if (err) {
								logger.log("Error Searching for Correlation Id", err);
								return done(err);
							}
							if (event) {
								results[bot_id.toString()] = {
									checkpoint: event.eid || event.kinesis_number,
									lag: event.timestamp - event.event_source_timestamp,
								};
								results[queue_id.toString()] = {
									payload: event.payload,
									lag: event.timestamp - event.event_source_timestamp,
									checkpoint: event.eid || event.kinesis_number
								};
								correlation = {
									start: event.eid || event.kinesis_number,
									timestamp: moment(event.timestamp),
									source: util.ref(event.event).id
								};
							} else {
								results[bot_id.toString()] = results[bot_id.toString()] || {};
								results[queue_id.toString()] = results[queue_id.toString()] || {};
							}
							done();
						});
					}, () => {
						return children.length > 0;
					}, (err) => {
						done(err);
					});
 
				}), function (err) {
					if (err) {
						reject(err);
					} else {
						resolve(results);
					}
				}
			);
		});
	} else {
		let bots = {};
		let queues = {};
 
		let botLookup = {};
		return new Promise((resolve, reject) => {
			dynamodb.query({
				TableName: sdk.configuration.resources.LeoCron,
				"ReturnConsumedCapacity": 'TOTAL'
			}, {
				method: "scan",
				mb: 10
			}).then((data) => {
				let crons = data.Items;
				crons.forEach((cron) => {
					let botId = util.refId(cron.id, "bot");
					Eif (cron.checkpoints) {
						botLookup[botId] = util.fixBotReferences(cron, {
							checkpoints: true
						});
						Object.keys(cron?.checkpoints?.read || {}).forEach((key) => {
							let queue = util.refId(key);
							if (!(queue in queues)) {
								queues[queue] = {
									parents: [],
									children: []
								};
							}
							queues[queue].children.push(botId);
							if (!(botId in bots)) {
								bots[botId] = {
									parents: [],
									children: []
								}
							}
							bots[botId].parents.push(queue);
						});
						Object.keys(cron?.checkpoints?.write || {}).forEach((key) => {
							let queue = util.refId(key);
							if (!(queue in queues)) {
								queues[queue] = {
									parents: [],
									children: []
								}
							}
							queues[queue].parents.push(botId);
							if (!(botId in bots)) {
								bots[botId] = {
									parents: [],
									children: []
								}
							}
							bots[botId].children.push(queue);
						});
					}
				});
 
				let parents = [];
				let current = {
					queue: queue,
					id: id
				};
				let seen = {};
 
				let targetEvent = null;
				async.doWhilst((done) => {
					logger.debug("doWhilst", current.queue, current.id, prevId(current.id));
					let gotEvent = false;
					ls.pipe(
						ls.fromLeo("test", current.queue, {
							start: prevId(current.id),
							limit: 1,
						}),
						ls.write(function (readEvent, done) {
							let event = readEvent as TraceReadEvent;
							gotEvent = true;
							let botId = util.refId(event.id, "bot");
							Iif (seen[botId]) {
								current = null;
								done();
								return;
							}
 
							seen[botId] = 1;
							if (!targetEvent) {
								targetEvent = event;
							}
							let b = {
								id: botId,
								server_id: botId,
								type: "bot",
								label: botLookup[botId].name
							};
							let eRef = util.ref(event.event);
							event.id = eRef.refId(); //util.botRefId(event.id);
							event.event = eRef.refId();
							event.server_id = event.id;
							event.type = "queue";
							event.label = eRef.id;
							event.lag = moment(event.timestamp).diff(event.event_source_timestamp);
							event.kinesis_number = event.eid || event.kinesis_number;
							parents.unshift(event);
							parents.unshift(b);
							Eif (event.correlation_id && event.correlation_id.start != undefined) {
								current = {
									id: event.correlation_id.start,
									queue: util.ref(event.correlation_id.source).toString()
								};
							} else {
								current = null;
							}
							done();
						}), function (err) {
							if (!gotEvent) {
								current = null;
							}
							done(err);
						});
				}, () => {
					return current !== null;
				}, (err) => {
					Iif (err) {
						reject(err);
						return;
					}
					let seen = {};
 
					function children(queue, id, force = false) {
						Iif (seen[queue]) {
							return {};
						}
						seen[queue] = 1;
						let kids = {};
						queues[queue].children.forEach((bot) => {
							let checkpoint = (botLookup[bot].checkpoints && botLookup[bot].checkpoints.read[queue]) || {};
							let lag = checkpoint.source_timestamp ? moment(checkpoint.source_timestamp).diff(targetEvent.event_source_timestamp) : null;
							let has_processed = checkpoint.checkpoint > id || false;
							kids[bot] = {
								id: bot,
								server_id: bot,
								type: 'bot',
								label: botLookup[bot].name,
								has_processed: has_processed,
								lag: !has_processed ? lag : 0,
								checkpoint: checkpoint,
								children: {}
							};
							if (force || has_processed) {
								bots[bot].children.map((q_id) => {
									kids[bot].children[q_id] = {
										id: q_id,
										label: q_id,
										server_id: q_id,
										lag: null,
										type: 'queue',
										event: null,
										children: children(q_id, id, force || has_processed)
									};
								});
							}
						});
						return kids;
					}
					resolve({
						parents: parents.slice(0, -1),
						event: targetEvent,
						children: children(queue, id)
					});
				});
 
			}).catch(reject);
		})
	}
}
 
function prevId(id) {
	return id.slice(0, -1) + (id.slice(-1) == "0" ? ' ' : id.slice(-1) - 1);
}
 
function searchCorrelationId(sdk: RStreamsSdk, statsTableName: string, queue_id, bot_id, correlation, callback) {
 
	let dynamodb = sdk.aws.dynamodb;
	let ls = sdk.streams;
 
	logger.debug("Search Correlation Id:", bot_id.refId())
	dynamodb.docClient.query({
		TableName: statsTableName,
		KeyConditionExpression: "#id = :id and #bucket >= :bucket",
		ExpressionAttributeNames: {
			"#bucket": "bucket",
			"#id": "id"
		},
		Limit: 14 * 24,
		ExpressionAttributeValues: {
			":bucket": statsBuckets.data.hour.transform(correlation.timestamp.clone()),
			":id": bot_id.refId()
		},
		"ReturnConsumedCapacity": 'TOTAL'
	}, (err, result) => {
		if (err) {
			callback(err);
			return;
		}
		let found = null;
		let source = util.ref(correlation.source).queue().refId();
		for (let i = 0; i < result.Items.length; i++) {
			let stat = result.Items[i];
			logger.debug(stat.bucket, stat.current.read[source] && stat.current.read[source].checkpoint, correlation.start)
			if (stat.current.read[source] && stat.current.read[source].checkpoint >= correlation.start) {
				found = stat;
				break;
			}
		}
		if (!found) {
			return callback();
		}
		let timestamp = moment(found.time);
		dynamodb.docClient.query({
			TableName: statsTableName,
			KeyConditionExpression: "#id = :id and #bucket >= :bucket",
			ExpressionAttributeNames: {
				"#bucket": "bucket",
				"#id": "id"
			},
			Limit: 60,
			ExpressionAttributeValues: {
				":bucket": statsBuckets.data.minute_1.transform(timestamp),
				":id": bot_id.refId()
			},
			"ReturnConsumedCapacity": 'TOTAL'
		}, (err, result) => {
			if (err) {
				return callback(err);
			}
			let found = null;
			for (let i = 0; i < result.Items.length; i++) {
				let stat = result.Items[i];
				logger.debug(stat.bucket, stat.current.read[source] && stat.current.read[source].checkpoint, correlation.start)
				if (stat.current.read[source] && stat.current.read[source].checkpoint >= correlation.start) {
					found = stat;
					break;
				}
			}
			if (!found) {
				//return callback();
			}
			let timestamp = moment(found.time);
			if (correlation.timestamp > timestamp) {
				timestamp = correlation.timestamp;
			}
			found = null;
			let start = timestamp.format("[z/]YYYY/MM/DD/HH/mm/ss");
			let shouldContinue = true;
			logger.debug("Searching Events", queue_id.refId(), start)
			ls.pipe(
				ls.fromLeo("test", queue_id, {
					start: start,
					maxOverride: timestamp.clone().add(1, "m").format("[z/]YYYY/MM/DD/HH/mm/ss"),
					fast_s3_read: true
				}),
				ls.write(function (readEvent, done) {
					let e = readEvent as TraceReadEvent;
					if (!shouldContinue) {
						logger.debug("Should stop")
						return done();
					}
					e.kinesis_number = e.eid || e.kinesis_number;
					if (
						(e.correlation_id.end && correlation.start <= e.correlation_id.end && correlation.start >= e.correlation_id.start) ||
						e.correlation_id.start == correlation.start
					) {
						found = e;
						shouldContinue = false;
						done();
					} else {
						done();
					}
				}), (err) => {
					callback(err, found);
				});
		});
	});
 
}
 
 
 
 
const bucketsData = {
	"minute_1": {
		period: "minute",
		prefix: "minute_",
		transform: function (timestamp) {
			return "minute_" + timestamp.clone().utc().startOf("minute").format("YYYY-MM-DD HH:mm");
		},
		value: function (timestamp) {
			return timestamp.clone().utc().startOf("minute");
		},
		prev: function (timestamp, amount) {
			return moment(timestamp).utc().subtract((amount || 1), "minutes");
		},
		next: function (timestamp, amount) {
			return moment(timestamp).utc().add((amount || 1), "minutes");
		},
		parent: "minute_5",
		duration: {
			m: 1
		},
		defaultContainer: "minute",
		defaultContainerInterval: 6 * 5
	},
	"minute_5": {
		period: "minute_5",
		prefix: "minute_5_",
		transform: function (timestamp) {
			let offset = (timestamp.utc().minute() + 5) % 5;
			return "minute_5_" + timestamp.clone().utc().subtract(offset, "minutes").startOf("minute").format("YYYY-MM-DD HH:mm");
		},
		value: function (timestamp) {
			let offset = (timestamp.utc().minute() + 5) % 5;
			return timestamp.clone().utc().subtract(offset, "minutes").startOf("minute");
		},
		prev: function (timestamp, amount) {
			return moment(timestamp).utc().subtract(5 * (amount || 1), "minutes");
		},
		next: function (timestamp, amount) {
			return moment(timestamp).utc().add(5 * (amount || 1), "minutes");
		},
		parent: "minute_15",
		duration: {
			m: 5
		},
		defaultContainer: "minute",
		defaultContainerInterval: 6 * 15
	},
	"minute_15": {
		period: "minute_15",
		prefix: "minute_15_",
		transform: function (timestamp) {
			let offset = (timestamp.utc().minute() + 15) % 15;
			return "minute_15_" + timestamp.clone().utc().subtract(offset, "minutes").startOf("minute").format("YYYY-MM-DD HH:mm");
		},
		value: function (timestamp) {
			let offset = (timestamp.utc().minute() + 15) % 15;
			return timestamp.clone().utc().subtract(offset, "minutes").startOf("minute");
		},
		prev: function (timestamp, amount) {
			return moment(timestamp).utc().subtract(15 * (amount || 1), "minutes");
		},
		next: function (timestamp, amount) {
			return moment(timestamp).utc().add(15 * (amount || 1), "minutes");
		},
		parent: "hour",
		duration: {
			m: 15
		},
		defaultContainer: "hour",
		defaultContainerInterval: 6
	},
	"hour": {
		period: "hour",
		prefix: "hour_",
		transform: function (timestamp) {
			return "hour_" + timestamp.clone().utc().startOf("hour").format("YYYY-MM-DD HH");
		},
		value: function (timestamp) {
			return timestamp.clone().utc().startOf("hour");
		},
		prev: function (timestamp, amount) {
			return moment(timestamp).utc().subtract((amount || 1), "hour");
		},
		next: function (timestamp, amount) {
			return moment(timestamp).utc().add((amount || 1), "hour");
		},
		parent: "day",
		duration: {
			h: 1
		},
		defaultContainer: "hour",
		defaultContainerInterval: 30
	},
	"day": {
		period: "day",
		prefix: "day_",
		transform: function (timestamp) {
			return "day_" + timestamp.clone().utc().startOf("day").format("YYYY-MM-DD");
		},
		value: function (timestamp) {
			return timestamp.clone().utc().startOf("day");
		},
		prev: function (timestamp, amount) {
			return moment(timestamp).utc().subtract((amount || 1), "day");
		},
		next: function (timestamp, amount) {
			return moment(timestamp).utc().add((amount || 1), "day");
		},
		parent: "week",
		duration: {
			d: 1
		},
		defaultContainer: "day",
		defaultContainerInterval: 30
	},
	"week": {
		period: "week",
		prefix: "week_",
		transform: function (timestamp) {
			return "week_" + timestamp.clone().utc().startOf("week").format("YYYY-MM-DD");
		},
		value: function (timestamp) {
			return timestamp.clone().utc().startOf("week");
		},
		prev: function (timestamp, amount) {
			return moment(timestamp).utc().subtract((amount || 1), "week");
		},
		next: function (timestamp, amount) {
			return moment(timestamp).utc().add((amount || 1), "week");
		},
		parent: null,
		duration: {
			w: 1
		},
		defaultContainer: "week",
		defaultContainerInterval: 30
	}
};
 
const ranges = {
	"minute": {
		period: "minute_1",
		count: 1,
		startOf: (timestamp) => timestamp.clone().startOf("minute")
	},
	"minute_1": {
		period: "minute_1",
		count: 1,
		startOf: (timestamp) => timestamp.clone().startOf("minute")
	},
	"minute_5": {
		period: "minute_1",
		count: 5,
		startOf: (timestamp) => {
			let offset = (timestamp.utc().minute() + 5) % 5;
			return timestamp.clone().subtract(offset, "minutes").startOf("minute");
		}
	},
	"minute_15": {
		period: "minute_1",
		count: 15,
		startOf: (timestamp) => {
			let offset = (timestamp.minute() + 15) % 15;
			return timestamp.clone().subtract(offset, "minutes").startOf("minute");
		}
	},
	"hour": {
		period: "hour",
		count: 1,
		startOf: (timestamp) => timestamp.clone().startOf("hour"),
		rolling: {
			period: "minute_15",
			count: 4
		}
	},
	"hour_6": {
		period: "hour",
		count: 6,
		startOf: (timestamp) => timestamp.clone().startOf("hour"),
	},
	"day": {
		period: "hour",
		count: 24,
		startOf: (timestamp) => timestamp.clone().startOf("day")
	},
	"week": {
		period: "hour",
		count: 168,
		startOf: (timestamp) => timestamp.clone().startOf("week")
	}
};
 
const statsBuckets = {
	data: bucketsData,
	ranges: ranges
};