All files / Nodejs/wrappers bot.ts

0% Statements 0/83
0% Branches 0/48
0% Functions 0/18
0% Lines 0/83

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                                                                                                                                                                                                                                                                                                                                                                                     
"use strict";
 
import { Context } from "aws-lambda";
import { BotInvocationEvent, RStreamsContext } from "../lib/types";
import { BotHandler } from "./cron";
 
 
function getEmptyContext(): Context {
	return {
		callbackWaitsForEmptyEventLoop: false,
		functionName: process.env.AWS_LAMBDA_FUNCTION_NAME,
		functionVersion: process.env.AWS_LAMBDA_FUNCTION_VERSION,
		invokedFunctionArn: `arn:aws:lambda:${process.env.AWS_REGION}:--:function:${process.env.AWS_LAMBDA_FUNCTION_NAME}`,
		memoryLimitInMB: process.env.AWS_LAMBDA_FUNCTION_MEMORY_SIZE,
		awsRequestId: `awsRequestId-unknown-${Date.now()}`,
		logGroupName: process.env.AWS_LAMBDA_LOG_GROUP_NAME,
		logStreamName: process.env.AWS_LAMBDA_LOG_STREAM_NAME,
		getRemainingTimeInMillis: function (): number {
			throw new Error("Function not implemented.");
		},
		done: function (error?: Error, result?: any): void {
			throw new Error("Function not implemented.");
		},
		fail: function (error: string | Error): void {
			throw new Error("Function not implemented.");
		},
		succeed: function (messageOrObject: any): void {
			throw new Error("Function not implemented.");
		}
	}
}
 
 
 
module.exports = function <T extends BotInvocationEvent, R>(botHandler: BotHandler<T, R>) {
	// Attach any environment resources
	(process as any).resources = process.env.Resources && JSON.parse(process.env.Resources) || {};
 
	let config = require("../leoConfigure.js");
	const logger = require('leo-logger')('bot.wrapper');
	const leosdk = require("../index.js")();
	const refUtil = require("../lib/reference.js");
 
	(process as any).__config = config;
 
	const botId = config.name;
	//const settings = config.cron && config.cron.settings || {};
 
	const moment = require("moment");
 
	const cron = leosdk.bot;
	//const dynamodb = leosdk.aws.dynamodb;
 
	for (let x of process.listeners('uncaughtException')) { //remove lambdas default listener
		process.removeListener('uncaughtException', x);
	}
	let theCallback;
	let theContext: Context = getEmptyContext();
 
	let __theEvent: BotInvocationEvent = {
		botId: "",
		__cron: undefined
	};
	process.on('uncaughtException', function (err) {
		console.log(`[LEOCRON]:end:${config.name}:${theContext.awsRequestId}`);
		logger.error((new Date).toUTCString() + ' uncaughtException:', err.message);
		logger.error(err.stack);
		if (__theEvent.__cron) {
			cron.reportComplete(__theEvent.__cron, theContext.awsRequestId, "error", {
				msg: err.message,
				stack: err.stack
			}, {}, function () {
				console.log("Cron Lock removed");
				if (theCallback) {
					theCallback(null, "Application Error");
				}
			});
		} else {
			cron.removeLock(config.name, theContext.awsRequestId, function () {
				console.log("Lock removed");
				if (theCallback) {
					theCallback(null, "Application Error");
				}
			});
		}
 
	});
 
	function empty(obj) {
		for (let k in obj) {
			delete obj[k];
		}
	}
 
	return function (event, context: RStreamsContext, callback) {
		context.callbackWaitsForEmptyEventLoop = false;
		context.resources = (process as any).resources;
		context.botId = event.botId || botId;
		context.getCheckpoint = async function (queue: string, defaultIfNull: string) {
			let queueRef = refUtil.ref(queue);
			let c = event.start || (
				event.__cron &&
				event.__cron.checkpoints &&
				event.__cron.checkpoints.read &&
				(
					(event.__cron.checkpoints.read[queueRef] && event.__cron.checkpoints.read[queueRef].checkpoint) ||
					(event.__cron.checkpoints.read[queueRef.id] && event.__cron.checkpoints.read[queueRef.id].checkpoint))
			) || defaultIfNull;
 
			return c;
		};
 
		//context.settings = settings;
		context.sdk = leosdk;
 
		theCallback = callback;
		//clear out the registry
		empty(config.registry);
 
		leosdk.configuration.registry = config.registry;
 
		config.registry.context = context;
		config.registry.__cron = event.__cron;
 
		global.cron_run_again = false;
		if (event.__cron && event.__cron.id) { //If it is in cron, use that regardless
			config.registry.id = event.__cron.id;
		} else if (!config.registry.id) { //If they didn't specify it in their config, then let's get it from the function name
			config.registry.id = process.env.AWS_LAMBDA_FUNCTION_NAME;
		}
 
		logger.log("Registry", JSON.stringify(config.registry, null, 2));
		theContext = context;
		__theEvent = event;
		if (event.__cron) {
			let cronkey = event.__cron.id + ":" + event.__cron.iid + ":" + event.__cron.ts + ":" + context.awsRequestId;
			console.log("[LEOCRON]:check:" + cronkey);
			logger.log("Locking on  __cron", event.__cron);
			let startTime = moment.now();
			cron.checkLock(event.__cron, context.awsRequestId, context.getRemainingTimeInMillis(), function (err, data) {
				if (err) {
					if (err && err.code == "ConditionalCheckFailedException") {
						logger.log("LOCK EXISTS, cannot run");
						callback(null, "already running");
					} else {
						logger.error("Failed getting lock, cannot run");
						callback(null, "failed getting lock");
					}
				} else {
					try {
						console.log("[LEOCRON]:start:" + cronkey);
 
						botHandler(event || {}, context)
							.then(data => {
								console.log("[LEOCRON]:complete:" + cronkey);
								cron.reportComplete(event.__cron, context.awsRequestId, err ? "error" : "complete", err ? err : '', {}, function (err2, data2) {
									if (err || err2) {
										logger.log(err || err2);
									}
									callback(null, err || data);
								});
							})
							.catch(err => {
								console.log("[LEOCRON]:complete:" + cronkey);
								cron.reportComplete(event.__cron, context.awsRequestId, "error", err, {}, function () {
									callback(null, err);
								});
							});
					} catch (e) {
						logger.log("error", e);
						cron.reportComplete(event.__cron, context.awsRequestId, "error", {
							msg: e.message,
							stack: e.stack
						}, {}, function () {
							callback(null, e);
						});
					}
 
				}
 
			});
		} else {
			throw new Error("Couldn't obtain lock.  Unknown bot id");
		}
	}
}