All files / nodejs/wrappers rstreams-simple.ts

0% Statements 0/48
0% Branches 0/26
0% Functions 0/8
0% Lines 0/48

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                                                                                                                                                                                                                                                                                                                                                                                                                               
 
import { RStreamsSdk } from "leo-sdk";
import { BatchOptions, ReadOptions } from "../lib/lib";
import { Context, Callback, Handler } from "aws-lambda";
import { CredentialProviderChain } from "aws-sdk";
import { ConfigProviderChain, EnvironmentConfiguration } from "../lib/rstreams";
 
export interface RStreamsSimpleOptions {
	readOptions?: ReadOptions;
	batchOptions: BatchOptions;
}
export type RStreamsHandler<T> = Handler<RStreamsEvent<T>, void>;
export type GenericHandler = Handler<any, void>;
 
export interface RStreamsRecordPayload<T> {
	approximateArrivalTimestamp: number;
	data: T;
	rstreamsSchemaVersion: string;
	//partitionKey: string;
	sequenceNumber: string;
}
 
export interface RStreamsEventRecord<T> {
	awsRegion: string;
	eventID: string;
	eventName: string;
	eventSource: string;
	eventSourceARN: string;
	eventVersion: string;
	invokeIdentityArn: string;
	rstreams: RStreamsRecordPayload<T>;
}
 
export interface RStreamsEvent<T> {
	Records: RStreamsEventRecord<T>[];
}
 
 
export default function <T>(options: RStreamsSimpleOptions, functionHandler: RStreamsHandler<T>): GenericHandler {
	// TODO: is this a useful shortcut anymore?  It parse stringified JSON from the ENV 'Resources'
	(process as any).resources = process.env.Resources && JSON.parse(process.env.Resources) || {};
 
	// TODO: How do we get the leo-sdk config
	// Currently it is via the leo-config npm module that needs to be bootstrapped
	// - ENV?
	// - Passed In?
	// - Something like CredentialsProviderChain?
 
	let chain = new ConfigProviderChain();
	let cpc = new CredentialProviderChain();
 
 
	const logger = require('leo-logger')('kinesis-like.wrapper');
	let leosdk: RStreamsSdk = null;
	let ls = null;// = leosdk.streams;
	let busName = null
 
 
	return async function handler(invokeEvent, context: Context) {
 
		// Lazy init because of async
		if (leosdk == null) {
 
			// let d = await cpc.resolvePromise();
			// console.log(d.accessKeyId);
			let config = await chain.resolvePromise();
 
			leosdk = require("../index.js")(
				{
					Region: config.Region,
					LeoStream: config.LeoStream,
					LeoCron: config.LeoCron,
					LeoEvent: config.LeoEvent,
					LeoS3: config.LeoS3,
					LeoKinesisStream: config.LeoKinesisStream,
					LeoFirehoseStream: config.LeoFirehoseStream,
					LeoSettings: config.LeoSettings,
				}
			);
			ls = leosdk.streams;
 
			// Pull the bus name from the sdk config
			busName = leosdk.configuration.resources.LeoKinesisStream.split(/-LeoKinesisStream-/)[0];
 
			console.log(leosdk.configuration);
		}
 
		process.exit();
 
 
		// Keeps lambda from hanging with persistent db connections
		context.callbackWaitsForEmptyEventLoop = false;
 
		// If bot id is not specified try and pull it from a few places
		invokeEvent.botId = invokeEvent.botId || (invokeEvent.__cron || {}).id || process.env.AWS_LAMBDA_FUNCTION_NAME;
 
		const stopTime = Date.now() + context.getRemainingTimeInMillis() * 0.8;
 
		const readSettings: ReadOptions = Object.assign({
			start: undefined, // Defaults to bot's last position
			stopTime: stopTime,
			loops: Number.POSITIVE_INFINITY,
			limit: Number.POSITIVE_INFINITY,
			size: Number.POSITIVE_INFINITY,
			fast_s3_read: true
		}, options.readOptions, invokeEvent.readOptions)
 
		const batchOptions: BatchOptions = Object.assign({
			// TODO: Are there good batching defaults?
		}, options.batchOptions, invokeEvent.batchOptions);
 
		// Counters to keep track of stats
		let counters = {
			batches: 0,
			events: 0
		};
 
		return new Promise((resolve, reject) => {
			ls.pipe(
				leosdk.read(invokeEvent.botId, invokeEvent.queue, readSettings), // Read events from the bus
				ls.batch(batchOptions), // Batch up the events into the requested chunks
				ls.through(async (batchEvent, done) => {
					// If we are after the stopTime skip any read but not processed batches
					if (Date.now() > stopTime) {
						return done();
					}
 
					let handlerError;
					try {
						if (!batchEvent.payload || batchEvent.payload.length == 0) {
							throw new Error("Batch with no events");
						}
 
						// Convert the data into a batch to process
						let recordsEvent: RStreamsEvent<T> = mapEventsToRStreamsEvent<T>(
							batchEvent,
							leosdk.configuration.region,
							"",// TODO: Do we have an identityARN that is useful
							busName
						);
 
						await functionHandler(recordsEvent, context, undefined as unknown as Callback<void>);
					} catch (err) {
						handlerError = err;
					}
 
					if (handlerError == null) {
						// Checkpoint the batch
						// Get the last eid & source_timestamp
						let lastEvent = batchEvent.payload[batchEvent.payload.length - 1];
 
						if (lastEvent == null || !lastEvent.eid) {
							return done(new Error("No eid found to checkpoint"));
						}
 
						leosdk.bot.checkpoint(invokeEvent.botId, invokeEvent.queue, {
							eid: lastEvent.eid,
							source_timestamp: lastEvent.source_timestamp,
							units: batchEvent.payload.length
						}, (checkpointError) => {
 
							// Only add stats for things that processed and checkpointed successfully
							if (checkpointError == null) {
								counters.batches++;
								counters.events += batchEvent.payload.length;
							}
 
							done(checkpointError);
						});
 
					} else {
						done(handlerError)
					}
				}),
				ls.devnull(),
				(err) => {
					logger.log(`Batch Stats: ${JSON.stringify(counters)}`);
					err ? reject(err) : resolve(undefined);
				}
			)
		});
	}
}
 
 
function mapEventsToRStreamsEvent<T>(batchEvent, region: string, identityArn: string, bus: string): RStreamsEvent<T> {
	return {
		Records: batchEvent.payload.map(data => {
			return {
				awsRegion: region,
				eventID: data.eid,
				eventName: "chb:rstreams:record",
				eventSource: "chb:rstreams",
				eventSourceARN: `${bus}:${data.event}:`,
				eventVersion: "2.0",
				invokeIdentityArn: identityArn,
				rstreams: {
					approximateArrivalTimestamp: data.timestamp,
					data: data.payload as T,
					rstreamsSchemaVersion: "2.0",
					//partitionKey: string,
					sequenceNumber: data.eid,
				} as RStreamsRecordPayload<T>
			} as RStreamsEventRecord<T>
		})
	}
}