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 | import { AthenaClient, GetQueryExecutionCommand, GetQueryResultsCommand, StartQueryExecutionCommand } from '@aws-sdk/client-athena'; import { FirehoseClient, PutRecordBatchCommand } from '@aws-sdk/client-firehose'; import { LambdaApiFunction, handleResourceApi } from './_base'; import { api200Body, api401Body, api500Body, generateApi400Body } from '@/types/api/_shared'; import { AddEventsApi, EventQueryResultRow, QueryEventsApi, addEventsQueryValidator, eventItemValidator, queryEventsQueryValidator } from '@/types/api/events'; import { validateObject } from '@/utils/backend/validation'; import { getLogger } from '@/utils/common/logger'; const logger = getLogger('resources/api/v2/events'); const firehose = new FirehoseClient(); const FIREHOSE_NAME = process.env.FIREHOSE_NAME; const queryTimeframes = { day: 24 * 60 * 60 * 1000, week: 7 * 24 * 60 * 60 * 1000, month: 28 * 24 * 60 * 60 * 1000, } as const; const padNum = (num: number) => num.toString().padStart(2, '0'); const dateToQueryDate = (date: Date) => `${date.getUTCFullYear()}-${padNum(date.getMonth() + 1)}-` + `${padNum(date.getUTCDate())}-${padNum(date.getUTCHours())}`; const GET: LambdaApiFunction<QueryEventsApi> = async function (event, user, userPerms) { logger.trace('GET', ...arguments); const athena = new AthenaClient(); // Authorize the user if (user === null || !userPerms.isUser) { return [ 401, api401Body, ]; } // Validate the request const [ query, validationErrors, ] = validateObject<QueryEventsApi['query']>( event.multiValueQueryStringParameters || {}, queryEventsQueryValidator, true ); if (query !== null && typeof query.groupBy === 'undefined' && typeof query.queryId === 'undefined') { validationErrors.push('Must provide either groupBy or queryId'); } if ( query === null || validationErrors.length > 0 ) { return [ 400, generateApi400Body(validationErrors), ]; } if (typeof query.groupBy !== 'undefined') { // Build the query time const timeframe = query.timeframe || 'month'; const endTime = new Date(Date.now() - (2 * 60 * 60 * 1000)); endTime.setUTCMinutes(0); endTime.setUTCSeconds(0); endTime.setUTCMilliseconds(0); const startTime = new Date(endTime.getTime() - queryTimeframes[timeframe]); const queryString = `SELECT ${query.groupBy.map(v => `"${v}"`).join(', ')}, COUNT(*) as num FROM "${process.env.GLUE_TABLE}" WHERE "datetime" >= '${dateToQueryDate(startTime)}' AND "datetime" < '${dateToQueryDate(endTime)}'` + (query.events ? `AND "event" IN (${query.events.map(e => `'${e}'`).join(',')})` : '') + `GROUP BY ${query.groupBy.map(v => `"${v}"`).join(', ')}`; const queryId = await athena.send(new StartQueryExecutionCommand({ QueryString: queryString, WorkGroup: process.env.ATHENA_WORKGROUP, QueryExecutionContext: { Database: process.env.GLUE_DATABASE, }, ResultReuseConfiguration: { ResultReuseByAgeConfiguration: { Enabled: true, MaxAgeInMinutes: 180, }, }, })); if (!queryId.QueryExecutionId) { logger.error('Failed to produce query execution ID:', queryId, queryString); return [ 500, api500Body, ]; } return [ 200, { queryId: queryId.QueryExecutionId, startTime: startTime.getTime(), endTime: endTime.getTime(), }, ]; } if (typeof query.queryId === 'undefined') { return [ 500, api500Body, ]; } // Look for the result const queryStatus = await athena.send(new GetQueryExecutionCommand({ QueryExecutionId: query.queryId, })); const queryState = queryStatus.QueryExecution?.Status?.State || 'UNKNOWN'; // Handle failed states if ([ 'CANCELLED', 'FAILED', ].includes(queryState)) { logger.error(`Query ID ${query.queryId} in state ${queryState}`); return [ 500, api500Body, ]; } // Handle in progress states if ([ 'QUEUED', 'RUNNING', 'UNKNOWN', ].includes(queryState)) { return [ 200, { status: queryState, }, ]; } // Get the results let nextToken: string | undefined; const results = await athena.send(new GetQueryResultsCommand({ QueryExecutionId: query.queryId, })); if (!results.ResultSet?.Rows) { logger.error(`No results returned from query ID ${query.queryId}`); } // Parse the results const names = results.ResultSet?.Rows?.[0].Data?.map(c => c.VarCharValue) || []; const rows: EventQueryResultRow[] = results.ResultSet?.Rows?.slice(1) .map(r => r.Data?.map(c => c.VarCharValue) || []) .map(r => r.reduce((agg: { [key: string]: string | undefined | number }, v, i) => { agg[names[i] || 'UNK'] = v; if (names[i] === 'num') { agg.num = Number(agg.num); } return agg as EventQueryResultRow; }, {})) as EventQueryResultRow[] || []; nextToken = results.NextToken; while (nextToken) { const results = await athena.send(new GetQueryResultsCommand({ QueryExecutionId: query.queryId, NextToken: nextToken, })); if (!results.ResultSet?.Rows) { logger.error(`No results returned from query ID ${query.queryId}`); } const athenaResults = results.ResultSet?.Rows?.slice(1) .map(r => r.Data?.map(c => c.VarCharValue) || []) .map(r => r.reduce((agg: { [key: string]: string | undefined | number }, v, i) => { agg[names[i] || 'UNK'] = v; if (names[i] === 'num') { agg.num = Number(agg.num); } return agg as EventQueryResultRow; }, {})) as EventQueryResultRow[] || []; rows.push(...athenaResults); nextToken = results.NextToken; } return [ 200, { count: rows.length, rows, }, ]; }; const POST: LambdaApiFunction<AddEventsApi> = async function (event) { logger.trace('POST', ...arguments); const eventTime = Date.now(); // Parse the query const [ query, queryErrors, ] = validateObject(event.queryStringParameters, addEventsQueryValidator); if (query === null || queryErrors.length > 0) { logger.error('Missing auhtentication token'); } // Parse the body const body = JSON.parse(event.body || ''); if ( !body || !Array.isArray(body) ) { return [ 400, generateApi400Body([]), ]; } // Get the valid items from the body const validItems: AddEventsApi['body'] = []; const allItemErrors: string[] = []; body.forEach((item, idx) => { const [ parsedItem, itemErrors, ] = validateObject(item, eventItemValidator); if (itemErrors.length > 0) { allItemErrors.push(...itemErrors.map(v => `${idx}-${v}`)); } else if (!parsedItem) { allItemErrors.push(`${idx}-null`); } else { validItems.push(parsedItem); } }); // Send the valid items to the firehose if (validItems.length > 0) { const encoder = new TextEncoder(); await firehose.send(new PutRecordBatchCommand({ DeliveryStreamName: FIREHOSE_NAME, Records: validItems.map(item => { const timestamp = typeof item.timestamp !== 'undefined' ? item.timestamp : eventTime; const dateTime = new Date(timestamp); const datePartition = `${dateTime.getUTCFullYear()}-` + `${(dateTime.getUTCMonth() + 1).toString().padStart(2, '0')}-` + `${dateTime.getUTCDate().toString() .padStart(2, '0')}-` + `${dateTime.getUTCHours().toString() .padStart(2, '0')}`; return { Data: encoder.encode(JSON.stringify({ ...item, timestamp, datePartition, })), }; }), })); } // Return either the errors or a 200 if (allItemErrors.length > 0) { return [ 400, generateApi400Body(allItemErrors), ]; } return [ 200, api200Body, ]; }; export const main = handleResourceApi.bind(null, { GET, POST, }); |