All files / Nodejs/wrappers fanout2.js

0% Statements 0/198
0% Branches 0/123
0% Functions 0/32
0% Lines 0/186

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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         
const aws = require("aws-sdk");
const eventIdFormat = "[z/]YYYY/MM/DD/HH/mm/";
const moment = require("moment");
const logger = require("leo-logger")("======= [ leo-fanout ] =======");
/**
 * @param {function(BotEvent, LambdaContext, Callback)} handler function to the code handler
 * @param {function(QueueEvent): any} eventPartition function to return the value representing what partition for the event 
 */
const fanoutFactory = (handler, eventPartition, opts = {}) => {
	if (typeof eventPartition !== "function") {
		opts = eventPartition || {};
		eventPartition = opts.eventPartition;
	}
	opts = Object.assign({
		instances: 2,
		allowCheckpoint: false,
		lambdaTimeoutPaddingMillis: 1000 * 3
	}, opts);
 
	eventPartition = eventPartition || (event => event.eid);
	let leo = require("../index.js");
	let leoStreamsFromLeo = leo.streams.fromLeo;
	let cronData;
 
	function fixInstanceForLocal(cronData, event) {
		// Get fanout data from process env if running locally
		if (process.env.FANOUT_data) {
			Object.assign(event, JSON.parse(process.env.FANOUT_data));
			console.log("EVENT", event.__cron.iid, JSON.stringify(event, null, 2));
			//process.exit();
		}
	}
 
	// Override reading from leo to only read up to the max event id send from the master.
	leo.streams.fromLeo = leo.read = (ID, queue, opts = {}) => {
		opts.maxOverride = min(opts.maxOverride, cronData.maxeid);
		logger.log(`Reading Queue Wrapper. Bot: ${ID}, IID: ${cronData.iid}, Queue: ${queue}, Max: ${opts.maxOverride}`);
		let reader = leoStreamsFromLeo.call(leo.streams, ID, queue, opts);
		let lastEvent = {
			id: "UNKNOWN",
			event: queue
		};
		let igroupIndex = 0;
		let instance_groups = cronData.instance_groups || [];
		let stream = leo.streams.pipe(reader, leo.streams.through((obj, done) => {
 
			for (; igroupIndex + 1 < instance_groups.length && obj.eid >= instance_groups[igroupIndex + 1].eid; igroupIndex++) {
				console.log("looking for block", igroupIndex);
			}
 
			let icount = (instance_groups[igroupIndex] || {}).icount || cronData.icount;
			let partition = Math.abs(hashCode(eventPartition(obj))) % icount;
			logger.debug("[partition]", partition, "[iid]", cronData.iid, "[eid]", obj.eid, "[icount]", icount);
			if (partition == cronData.iid) {
				logger.debug(`------ PROCESSING: matched on partition ------ ${obj.eid}`);
				let toEmit = lastEvent;
				lastEvent = obj;
				done(null, toEmit.cp_eid ? toEmit : undefined);
			} else {
				logger.debug(`------ NOT PROCESSING: no match on partition ------ ${obj.eid}`);
				lastEvent.cp_eid = obj.eid;
				done();
			}
		}, function emit(done) {
			let last = lastEvent;
			lastEvent = {
				id: "UNKNOWN",
				event: queue
			};
			done(null, (last.eid || last.cp_eid) ? last : undefined);
		}));
		stream.checkpoint = reader.checkpoint;
		stream.get = reader.get;
		return stream;
	};
 
	return (event, context, callback) => {
		fixInstanceForLocal(cronData, event);
 
		cronData = event.__cron || {};
		cronData.instance_groups = cronData.instance_groups || event.instance_groups;
 
		logger.log("Fanout Handler", cronData.iid || 0);
		logger.debug("Fanout Handler Event", cronData.iid || 0, JSON.stringify(event, null, 2));
		logger.debug("Fanout Handler Context", cronData.iid || 0, JSON.stringify(context, null, 2));
 
		// If this is a worker then report back the checkpoints or error
		if (cronData.iid && cronData.icount) {
			logger.log("Fanout Worker", cronData.iid);
			cronData.cploc = "instances";
			let context_getRemainingTimeInMillis = context.getRemainingTimeInMillis;
			context.getRemainingTimeInMillis = () => {
				return context_getRemainingTimeInMillis.call(context) - (opts.lambdaTimeoutPaddingMillis || (1000 * 3));
			};
			let wasCalled = false;
			const handlerCallback = (err, data) => {
				if (!wasCalled) {
					wasCalled = true;
					let response = {
						error: err,
						data: data,
						iid: cronData.iid
					};
					logger.log("Worker sending data back", cronData.iid);
					logger.debug("Worker sending back response", cronData.iid, JSON.stringify(response, null, 2));
					if (process.send) {
						process.send(response);
					}
					callback(null, response);
				}
			};
			const handlerResponse = handler(event, context, handlerCallback);
			if (handlerResponse && typeof handlerResponse.then === 'function') {
				handlerResponse.then(data => handlerCallback(null, data)).catch(err => handlerCallback(err));
			}
			return handlerResponse;
		} else {
			// This is the master, start the needed workers
			let timestamp = moment.utc();
			cronData.maxeid = cronData.maxeid || event.maxeid || timestamp.format(eventIdFormat) + timestamp.valueOf();
			cronData.iid = 0;
			logger.log("Fanout Master", cronData.iid);
			let instances = opts.instances;
			if (typeof instances === "function") {
				instances = instances(event, cronData);
			}
			instances = Math.max(1, Math.min(instances, opts.maxInstances || 20));
			cronData.icount = instances;
 
			let setupPromise;
			if (!event.instances || !event.checkpoints) {
				setupPromise = new Promise((resolve, reject) => leo.aws.dynamodb.get(leo.configuration.resources.LeoCron, event.botId, (err, data) => err ? reject(err) : resolve(data)))
					.then(bot => {
						event.instances = (bot || {}).instances || {};
						event.checkpoints = (bot || {}).checkpoints || {};
						if (bot == null) {
							return leo.bot.createBot(event.botId, {});
						}
					});
			} else {
				setupPromise = Promise.resolve();
			}
			setupPromise.then(() => {
				// Add any entries that don't exist
				let toAdd = [];
				let command = {
					TableName: leo.configuration.resources.LeoCron,
					Key: {
						id: event.botId
					},
					UpdateExpression: undefined,
					ExpressionAttributeNames: {
						"#instances": "instances"
					},
					ExpressionAttributeValues: {}
				};
				for (let i = 0; i < cronData.icount; i++) {
					if (!event.instances[i]) {
						event.instances[i] = (event.checkpoints || {}).read || {};
						toAdd.push(`#instances.#i${i} = :i${i}`);
						command.ExpressionAttributeNames[`#i${i}`] = `${i}`;
						command.ExpressionAttributeValues[`:i${i}`] = event.instances[i];
					}
				}
				if (toAdd.length > 0) {
					command.UpdateExpression = `set ${toAdd.join(",")}`;
					logger.log("Adding Extra Worker instances", JSON.stringify(command, null, 2));
					return leo.aws.dynamodb.docClient.update(command).promise();
				} else {
					return Promise.resolve();
				}
 
			}).then(() => {
				let workers = [
					new Promise(resolve => {
						setTimeout(() => {
							logger.log(`Invoking 1/${instances}`);
							let wasCalled = false;
							const handlerCallback = (err, data) => {
								if (!wasCalled) {
									wasCalled = true;
									logger.log(`Done with instance 1 / ${instances} `);
									resolve({
										error: err,
										data: data,
										iid: 0
									});
								}
							};
							const handlerResponse = handler(event, context, handlerCallback);
							if (handlerResponse && typeof handlerResponse.then === 'function') {
								handlerResponse.then((data) => handlerCallback(null, data)).catch(err => handlerCallback(err));
							}
							return handlerResponse;
						}, 200);
					})
				];
				for (let i = 1; i < instances; i++) {
					workers.unshift(invokeSelf(event, i, instances, context));
				}
 
				// Wait for all workers to return and figure out what checkpoint to persist
				logger.debug(`Waiting on all Fanout workers: count ${workers.length} `);
				return Promise.all(workers);
			}).then(() => callback()).catch((err) => {
				logger.error("[err]", err);
				return callback(err);
			}).finally(() => {
				logger.log("All Fanout Finished");
			});
		}
	};
};
 
 
 
/**
 * @param {*} event The base event to send to the worker
 * @param {number} iid The instance id of this worker
 * @param {number} count The total number of workers
 * @param {*} context Lambda context object
 * @param {function(BotEvent, LambdaContext, Callback)} handler
 */
function invokeSelf(event, iid, count, context) {
	let newEvent;
	try {
		logger.log(`Invoking ${iid + 1}/${count}`);
		newEvent = JSON.parse(JSON.stringify(event));
		newEvent.__cron.iid = iid;
		newEvent.__cron.icount = count;
		newEvent.__cron.ignoreLock = true;
 
		// Add starting points for all queues.
		// leo-sdk will look to this before the default checkpoints.read[queue]
		let myInstance = (event.instances || {})[iid] || {};
		newEvent.__cron.starteid = Object.keys(myInstance).reduce((all, key) => {
			if (key.match(/^queue:/) && myInstance[key] && myInstance[key].checkpoint) {
				all[key] = myInstance[key].checkpoint;
			}
			return all;
		}, {});
	} catch (err) {
		return Promise.reject(err);
	}
	return new Promise((resolve, reject) => {
		if (process.env.AWS_LAMBDA_FUNCTION_NAME) {
			try {
				let lambdaApi = new aws.Lambda({
					region: process.env.AWS_DEFAULT_REGION,
					httpOptions: {
						timeout: context.getRemainingTimeInMillis() // Default: 120000 // Two minutes
					}
				});
				logger.log("[lambda]", process.env.AWS_LAMBDA_FUNCTION_NAME);
				const lambdaInvocation = lambdaApi.invoke({
					FunctionName: process.env.AWS_LAMBDA_FUNCTION_NAME,
					InvocationType: 'RequestResponse',
					Payload: JSON.stringify(newEvent),
					Qualifier: process.env.AWS_LAMBDA_FUNCTION_VERSION
				}, (err, data) => {
					logger.log(`Done with Lambda instance ${iid + 1}/${count}`);
					try {
						logger.log("[lambda err]", err);
						logger.log("[lambda data]", data);
						if (err) {
							return reject(err);
						} else if (!err && data.FunctionError) {
							err = data.Payload;
							return reject(err);
						} else if (!err && data.Payload != undefined && data.Payload != 'null') {
							data = JSON.parse(data.Payload);
						}
 
						resolve(data);
					} catch (err) {
						reject(err);
					}
				});
				logger.debug("[lambda invoked invocation/payload]", lambdaInvocation, JSON.stringify(newEvent, null, 2));
			} catch (err) {
				reject(err);
			}
		} else {
			try {
				// Fork process with event
				let worker = require("child_process").fork(process.argv[1], process.argv.slice(2), {
					cwd: process.cwd(),
					env: Object.assign({}, process.env, {
						FANOUT_data: JSON.stringify(newEvent),
						runner_keep_cmd: true
					}),
					execArgv: process.execArgv
				});
				let responseData = {};
				worker.once("message", (response) => {
					logger.log(`Got Response with instance ${iid + 1}/${count}`);
					responseData = response;
				});
				worker.once("exit", () => {
					logger.log(`Done with child instance ${iid + 1}/${count}`);
					logger.log("[responseData]", responseData);
					resolve(responseData);
				});
			} catch (err) {
				reject(err);
			}
		}
	});
}
 
 
/**
	 * @param {string|number} str Converts {str} to a hash code value
	 */
function hashCode(str) {
	if (typeof str === "number") {
		return str;
	} else if (Array.isArray(str)) {
		let h = 0;
		for (let a = 0; a < str.length; a++) {
			h += hashCode(str[a]);
		}
		return h;
	}
	let hash = 0,
		i, chr;
	if (str.length === 0) return hash;
	for (i = 0; i < str.length; i++) {
		chr = str.charCodeAt(i);
		hash = ((hash << 5) - hash) + chr;
		hash |= 0; // Convert to 32bit integer
	}
	return hash;
}
 
function min(...args) {
	var current = args[0];
	for (var i = 1; i < args.length; ++i) {
		if (current == undefined) {
			current = args[i];
		} else if (args[i] != null && args[i] != undefined) {
			current = current < args[i] ? current : args[i];
		}
	}
	return current;
}
 
module.exports = fanoutFactory;