All files / ipoid import-status-utils.js

15.09% Statements 8/53
0% Branches 0/24
0% Functions 0/8
15.09% Lines 8/53

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    1x 1x 1x   1x             1x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           1x 1x 1x  
'use strict';
 
const mariadb = require( 'mariadb' );
const DATADIR = process.env.DATADIR;
const logger = require( './pipeline-logger.js' ).getPipelineLogger();
 
const jobStates = {
	STARTED: 0,
	COMPLETE: 1,
	ERROR: 2,
	RETRIED: 3
};
 
const options = {
	host: process.env.MYSQL_HOST,
	user: process.env.MYSQL_RW_USER,
	password: process.env.MYSQL_RW_PASS,
	database: process.env.MYSQL_DATABASE,
	port: process.env.MYSQL_PORT
};
 
/**
 * Get the information of any batches that have failed and output it as
 * an object containing the batch recreation information (batch file, feed inputs).
 *
 * @return {Array}
 *
 */
async function getFailedBatches() {
	const connection = await mariadb.createConnection( options );
	let failedBatches = await connection.query( `
		SELECT
			feed_file_yesterday,
			feed_file_today,
			batch_file
		FROM
			import_status
		WHERE
			batch_status = ?;
	`, [ jobStates.ERROR ] );
 
	await connection.end();
 
	failedBatches = convertBufferToString( failedBatches );
	return failedBatches;
}
 
/**
 * Check if any imports are incomplete and return a list of untried batches
 * if any are found.
 * Two kinds of incomplete import can be found:
 * 1. Today's import is incomplete:
 *      This will check the import status from today's and yesterday's feed dates
 * 2. Today's import never completed the first batch or errored out:
 *      This will check the import status of the import before today
 *      as if it never completed a batch then a fresh import can be started
 *      and if it caught on an error, getFailedBatch() would catch it instead
 *
 * @return {Object}
 *
 */
async function getIncompleteImport() {
	const connection = await mariadb.createConnection( options );
 
	// Get the date of the last run import with at least one successful batch
	// If an import started and errored out on the first batch, it would
	// be caught by another check and then otherwise, the import has not been
	// attempted
	let latestImportDates = await connection.query( `
		SELECT
			batch_count,
			feed_file_yesterday,
			feed_file_today
		FROM
			import_status
		WHERE
			batch_status = ?
		ORDER BY timestamp
		DESC
		LIMIT 1;
	`, [ jobStates.COMPLETE ] );
	latestImportDates = convertBufferToString( latestImportDates );
	latestImportDates = latestImportDates[ 0 ];
 
	// Use the date to count how many batches of the import have been completed
	let latestImportBatches = await connection.query( `
		SELECT
			batch_file
		FROM
			import_status
		WHERE
			feed_file_yesterday = ?
		AND
			feed_file_today = ?
		AND
			batch_status = ?;
	`, [
		latestImportDates.feed_file_yesterday ? `${ DATADIR }/${ latestImportDates.feed_file_yesterday }.json.gz` : '',
		latestImportDates.feed_file_today ? `${ DATADIR }/${ latestImportDates.feed_file_today }.json.gz` : '',
		jobStates.COMPLETE
	] );
	latestImportBatches = convertBufferToString( latestImportBatches );
 
	await connection.end();
 
	// Return the status of the latest import
	// If the import ran but is incomplete, pass along a list of
	// completed batches so a continued import can skip them
	return {
		yesterday: latestImportDates.feed_file_yesterday,
		today: latestImportDates.feed_file_today,
		completedBatches: latestImportBatches.length === latestImportDates.batch_count ?
			null : latestImportBatches
	};
}
 
/**
 * Return the status of an import (defined by a yesterday and today feed)
 * The following states are possible:
 *   - if failed batches are found: return ERROR and the array of batches to retry
 *   - if an incomplete import is found: return INCOMPLETE and the array of batches to skip
 *   - if the import is complete: return COMPLETE
 *   - if the import hasn't been attempted: return NOT_STARTED
 * main.sh will use this status to determine what next step to perform,
 * if any, and is expected to only ever pick one step per run.
 *
 * @param {string} yesterday - file name of yesterday's feed
 * @param {string} today -  file name of today's feed
 *
 * @return {Promise<void>}
 *
 */
async function getImportStatus( yesterday, today ) {
	const params = {
		status: null,
		yesterday: null,
		today: null,
		retryBatches: null,
		completedBatches: null
	};
 
	// Check for failed imports
	const failedBatches = await getFailedBatches();
 
	// If there are any failed imports, return the batches and dates
	// that failed so they can be retried
	//
	// Because imports run serially and only after the previous one has been
	// completed successfully, the yesterday and today dates for all
	// batches returned are expected to be the same
	if ( failedBatches.length ) {
		console.log( JSON.stringify( { ...params, ...{
			status: 'ERROR',
			yesterday: failedBatches[ 0 ].feed_file_yesterday,
			today: failedBatches[ 0 ].feed_file_today,
			retryBatches: failedBatches.map( function ( batch ) {
				return batch.batch_file;
			} )
		} } ) );
		return;
	}
 
	// Check for incomplete imports
	const latestKnownImportStatus = await getIncompleteImport();
 
	// If an incomplete import is found, return the dates
	// and the batches that have been completed so they can be skipped
	if ( latestKnownImportStatus.completedBatches ) {
		console.log( JSON.stringify( { ...params, ...{
			status: 'INCOMPLETE',
			yesterday: latestKnownImportStatus.yesterday,
			today: latestKnownImportStatus.today,
			completedBatches: latestKnownImportStatus.completedBatches.map( function ( batch ) {
				return batch.batch_file;
			} )
		} } ) );
		return;
	}
 
	// Otherwise, the import status check returned a complete latest import
	// Compare the dates returned with the dates passed in to see if the import
	// was already run and completed and return if so
	if (
		yesterday === latestKnownImportStatus.yesterday &&
		today === latestKnownImportStatus.today
	) {
		console.log( JSON.stringify( { ...params, ...{
			status: 'COMPLETE',
			yesterday: yesterday,
			today: today
		} } ) );
		return;
	}
 
	// All other cases exhausted; this is an import that hasn't been run yet
	console.log( JSON.stringify( { ...params, ...{
		status: 'NOT_STARTED',
		yesterday: yesterday,
		today: today
	} } ) );
	return;
}
 
/**
 * Update the batch status when it's been retried
 *
 * @param {string} batchFile - filepath to the batch file that's been retried
 * @param {string} yesterday - filepath to the batch's yesterday feed
 * @param {string} today - filepath to batch's today feed
 * @param {string} originalType - type of batch that import corrected (STARTED, ERROR)
 */
async function updateBatchStatus( batchFile, yesterday, today, originalType ) {
	// Mark the processed errored-out batch files as retried
	const connection = await mariadb.createConnection( options );
	await connection.query( `
	UPDATE import_status
		SET
			batch_status = ?
		WHERE
			feed_file_yesterday = ? AND
			feed_file_today = ? AND
			batch_status = ? AND
			batch_file = ?;
	`, [ jobStates.RETRIED, yesterday, today, jobStates[ originalType ], batchFile ] );
	logger.info( `Batch file ${ batchFile } was restarted.` );
	await connection.end();
}
 
/**
 * Batch and feed files come back as filepaths in a buffer
 * Transform every buffer into a string and the feed filepaths into file names
 * Commands later expect the filename, not a path
 *
 * @param {string} arr - Array with objects representing batches that have been run
 *
 * @return {Array}
 *
 */
function convertBufferToString( arr ) {
	arr.map( function ( batch ) {
		const dateGroup = /([1-2][0-9][0-9][0-9])(0[1-9]|1[0-2])(0[1-9]|[1-2][0-9]|3[0-1]).*(?=.json.gz)/g;
		if ( batch.feed_file_yesterday ) {
			batch.feed_file_yesterday = batch.feed_file_yesterday.toString().match( dateGroup );
			batch.feed_file_yesterday = batch.feed_file_yesterday ?
				batch.feed_file_yesterday[ 0 ] : null;
		}
		if ( batch.feed_file_today ) {
			batch.feed_file_today = batch.feed_file_today.toString().match( dateGroup );
			batch.feed_file_today = batch.feed_file_today ?
				batch.feed_file_today[ 0 ] : null;
		}
		if ( batch.batch_file ) {
			batch.batch_file = batch.batch_file.toString();
		}
		return batch;
	} );
	return arr;
}
 
module.exports.jobStates = jobStates;
module.exports.getImportStatus = getImportStatus;
module.exports.updateBatchStatus = updateBatchStatus;