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 | import { AthenaClient, GetQueryExecutionCommand, GetQueryResultsCommand, StartQueryExecutionCommand } from '@aws-sdk/client-athena'; import { LambdaApiFunction, handleResourceApi } from './_base'; import { validateRequest } from './_utils'; import { api404Body, api500Body, generateApi400Body } from '@/types/api/_shared'; import { FileEventItem, FullEventItem, GetRadioEventsApi, GetTalkgroupEventsApi, getEventsParamsValidator, getEventsQueryValidator } from '@/types/api/events'; import { TypedQueryInput } from '@/types/backend/dynamo'; import { TABLE_DEVICES, TABLE_FILE, typedQuery } from '@/utils/backend/dynamoTyped'; import { getLogger } from '@/utils/common/logger'; const logger = getLogger('resources/api/v2/eventsList'); const athena = new AthenaClient(); const MAX_RESULTS = 1500; const minDatetime = 1735689600000; // 2025-01-01 00:00 UTC function roundToHour(ts: number, ceil: boolean) { const ONE_HOUR = 60 * 60 * 1000; const divided = ts / ONE_HOUR; if (ceil) { return Math.ceil(divided) * ONE_HOUR; } return Math.floor(divided) * ONE_HOUR; } const GET: LambdaApiFunction<GetRadioEventsApi | GetTalkgroupEventsApi> = async function (event) { logger.trace('GET', ...arguments); // Validate the path is talkgroup or radio if (![ 'talkgroup', 'radioid', ].includes(event.pathParameters?.type || '')) { return [ 404, api404Body, ]; } const queryType = event.pathParameters?.type as 'talkgroup' | 'radioid'; // Validate the ID const { params, query, validationErrors, } = validateRequest<GetTalkgroupEventsApi>({ paramsRaw: event.pathParameters, paramsValidator: getEventsParamsValidator, queryRaw: event.queryStringParameters || {}, queryValidator: getEventsQueryValidator, }); if ( params === null || query === null || validationErrors.length > 0 ) { return [ 400, generateApi400Body(validationErrors), ]; } let endTime: number = Math.ceil(Date.now() / (60 * 60 * 1000)) * 1000 * 60 * 60; if (typeof query.endTime !== 'undefined') { endTime = query.endTime; } let startTime = endTime - (28 * 24 * 60 * 60 * 1000); if (startTime < minDatetime) { startTime = minDatetime; } if (!query.queryId) { const padNum = (num: number) => num.toString().padStart(2, '0'); // Start and end dates const startDateTime = new Date(roundToHour(startTime, false)); const startDatetimeString = `${startDateTime.getUTCFullYear()}-${padNum(startDateTime.getMonth() + 1)}-` + `${padNum(startDateTime.getUTCDate())}-${padNum(startDateTime.getUTCHours())}`; const endDateTime = new Date(roundToHour(endTime, true)); const endDatetimeString = `${endDateTime.getUTCFullYear()}-${padNum(endDateTime.getMonth() + 1)}-` + `${padNum(endDateTime.getUTCDate())}-${padNum(endDateTime.getUTCHours())}`; // Run the Athena query const QueryString = `SELECT * FROM "${process.env.GLUE_TABLE}" WHERE "${queryType}" = '${params.id}' AND "event" != 'call' AND "datetime" >= '${startDatetimeString}' AND "datetime" <= '${endDatetimeString}' AND "timestamp" < ${endTime} AND "timestamp" >= ${startTime} ORDER BY "timestamp" DESC`; const queryId = await athena.send(new StartQueryExecutionCommand({ QueryString, WorkGroup: process.env.ATHENA_WORKGROUP, QueryExecutionContext: { Database: process.env.GLUE_DATABASE, }, ResultReuseConfiguration: { ResultReuseByAgeConfiguration: { Enabled: true, MaxAgeInMinutes: 60, }, }, })); if (!queryId.QueryExecutionId) { logger.error('Failed to produce query execution ID:', queryId); return [ 500, api500Body, ]; } return [ 200, { queryId: queryId.QueryExecutionId, endTime, }, ]; } // 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 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 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] === 'timestamp') { agg.timestamp = Number(agg.timestamp); } return agg as FullEventItem; }, {})) as FullEventItem[] || []; // Get the files const fileQueryConfig: TypedQueryInput<FileEventItem> & Required<Pick< TypedQueryInput<FileEventItem>, 'ExpressionAttributeNames' | 'ExpressionAttributeValues' >> = { ScanIndexForward: false, TableName: TABLE_FILE, ExpressionAttributeNames: { '#StartTime': 'StartTime', }, ExpressionAttributeValues: { ':StartTime': Math.round(startTime / 1000), ':EndTime': Math.round(endTime / 1000), }, }; if (queryType === 'talkgroup') { fileQueryConfig.ExpressionAttributeNames['#Talkgroup'] = 'Talkgroup'; fileQueryConfig.ExpressionAttributeValues[':Talkgroup'] = params.id; fileQueryConfig.IndexName = 'StartTimeTgIndex'; fileQueryConfig.KeyConditionExpression = '#Talkgroup = :Talkgroup AND #StartTime BETWEEN :StartTime AND :EndTime'; } else { fileQueryConfig.TableName = TABLE_DEVICES; fileQueryConfig.ExpressionAttributeNames['#RadioID'] = 'RadioID'; fileQueryConfig.ExpressionAttributeValues[':RadioID'] = params.id.toString(); fileQueryConfig.KeyConditionExpression = '#RadioID = :RadioID AND #StartTime BETWEEN :StartTime AND :EndTime'; } const filesQueryResult = await typedQuery<FileEventItem>(fileQueryConfig); const fileResults = filesQueryResult.Items || []; let endResults = [ ...athenaResults, ...fileResults, ].sort((a, b) => { const aVal = 'StartTime' in a ? a.StartTime * 1000 : a.timestamp; const bVal = 'StartTime' in b ? b.StartTime * 1000 : b.timestamp; return aVal >= bVal ? -1 : 1; }); let firstEvent = startTime; const athenaFirst = athenaResults.length ? athenaResults[athenaResults.length - 1].timestamp : 0; const filesFirst = fileResults.length ? fileResults[fileResults.length - 1].StartTime * 1000 : 0; if (endResults.length >= MAX_RESULTS) { const firstEventItem = endResults[MAX_RESULTS]; firstEvent = 'timestamp' in firstEventItem ? firstEventItem.timestamp : firstEventItem.StartTime * 1000; } else if (athenaResults.length && fileResults.length) { firstEvent = athenaFirst < filesFirst ? athenaFirst : filesFirst; } else if (athenaResults.length) { firstEvent = athenaFirst; } else if (fileResults.length) { firstEvent = filesFirst; } // Filter out older events endResults = endResults.filter(v => { if ('StartTime' in v) { return v.StartTime * 1000 >= firstEvent; } return v.timestamp >= firstEvent; }); return [ 200, { count: endResults.length, events: endResults, startTime: firstEvent, endTime, }, ]; }; export const main = handleResourceApi.bind(null, { GET, }); |