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 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 10x 10x 10x 10x 10x 10x 10x 10x 10x 29x 29x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 8x 8x 6x 10x 4x 4x 4x 4x 4x 6x 6x 10x 1x 1x 1x 1x 1x 1x 5x 10x 5x 5x 5x 5x 5x 5x 5x 10x 1x 1x 1x 1x 1x 4x 4x 4x 4x 4x 4x 10x 1x 1x 1x 1x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 10x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 10x 3x 3x 3x 3x 3x 1x 1x 1x | import {
CloudWatchClient, PutMetricDataCommand
} from '@aws-sdk/client-cloudwatch';
import {
SQSClient,
SendMessageCommand
} from '@aws-sdk/client-sqs';
import {
LambdaApiFunction,
handleResourceApi
} from './_base';
import { validateTwilioRequest } from './_twilio';
import {
validateRequest
} from './_utils';
import {
getTwilioSecret, twilioPhoneNumbers
} from '@/deprecated/utils/general';
import { generateApi400Body } from '@/types/api/_shared';
import {
UpdateTextStatusApi,
createTextQueryValidator, updateTextStatusBodyValidator, updateTextStatusParamsValidator
} from '@/types/api/twilio';
import {
FullUserObject, validDepartments
} from '@/types/api/users';
import { TypedUpdateInput } from '@/types/backend/dynamo';
import { PhoneNumberIssueQueueItem } from '@/types/backend/queue';
import { TwilioQueueEvent } from '@/types/backend/twilioQueue';
import {
TABLE_USER, typedGet, typedUpdate
} from '@/utils/backend/dynamoTyped';
import { getLogger } from '@/utils/common/logger';
const logger = getLogger('twilioStatus');
const sqs = new SQSClient();
const cloudWatch = new CloudWatchClient();
const queueUrl = process.env.SQS_QUEUE;
const twilioQueueUrl = process.env.TWILIO_QUEUE;
const POST: LambdaApiFunction<UpdateTextStatusApi> = async function (event) {
logger.trace('POST', ...arguments);
const eventTime = Date.now();
// Parse the body
const urlParamsBody = new URLSearchParams(event.body || '');
const bodyObj: {
[key: string]: unknown;
} = {};
for (const [
key,
value,
] of urlParamsBody.entries()) {
bodyObj[key] = value;
}
// Validate the request
const {
params,
query,
body,
validationErrors,
} = validateRequest<UpdateTextStatusApi>({
paramsRaw: event.pathParameters,
paramsValidator: updateTextStatusParamsValidator,
bodyRaw: bodyObj,
bodyValidator: updateTextStatusBodyValidator,
queryRaw: event.queryStringParameters || {},
queryValidator: createTextQueryValidator,
});
if (
params === null ||
query === null ||
body === null ||
validationErrors.length > 0
) {
return [
400,
generateApi400Body(validationErrors),
];
}
// Get the information about the phone number
const phoneNumberConfigs = await twilioPhoneNumbers();
const twilioConf = await getTwilioSecret();
if (typeof phoneNumberConfigs[body.From] === 'undefined') {
logger.error(`Invalid phone number - ${body.From}`, body);
return [
400,
generateApi400Body([ 'From', ]),
];
}
const phoneNumberConf = phoneNumberConfigs[body.From];
if (typeof twilioConf[`authToken${phoneNumberConf.account || ''}`] === 'undefined') {
logger.error(`Invalid phone number account - ${phoneNumberConf.account || 'undef'}`, body, phoneNumberConf);
return [
400,
generateApi400Body([ 'From', ]),
];
}
// Validate the Twilio signature
const [ isValid, ] = validateTwilioRequest(
event,
query,
bodyObj,
phoneNumberConf,
twilioConf
);
if (!isValid) {
return [
400,
generateApi400Body([]),
];
}
// Validate the user sent to
const userGet = await typedGet<FullUserObject>({
TableName: TABLE_USER,
Key: {
phone: Number(body.To.slice(2)),
},
});
if (!userGet.Item) {
logger.error(`Invalid user ID - user ${body.To}`, userGet);
return [
204,
'',
];
}
const user = userGet.Item;
const promises: {
[key: string]: Promise<unknown>;
} = {};
// Update the message table
const twilioQueueBody: TwilioQueueEvent = {
datetime: params.id,
status: body.MessageStatus,
phone: user.phone,
eventTime,
};
promises['text-update'] = sqs.send(new SendMessageCommand({
QueueUrl: twilioQueueUrl,
MessageBody: JSON.stringify(twilioQueueBody),
}));
// Update the user for delivered and undelivered messages
if ([
'undelivered',
'delivered',
].includes(body.MessageStatus)) {
const updateValues: TypedUpdateInput<FullUserObject>['ExpressionAttributeValues'] = {
':lastStatus': body.MessageStatus as 'undelivered' | 'delivered',
':lastStatusBase': 0,
};
let updateExpr: string;
if (body.MessageStatus === 'delivered') {
updateExpr = '#lastStatusCount = :lastStatusBase';
} else {
updateValues[':lastStatusIncrement'] = 1;
updateExpr = '#lastStatusCount = if_not_exists(#lastStatusCount, :lastStatusBase) + :lastStatusIncrement';
}
promises['user-update'] = typedUpdate<FullUserObject>({
TableName: TABLE_USER,
Key: {
phone: user.phone,
},
ExpressionAttributeNames: {
'#lastStatus': 'lastStatus',
'#lastStatusCount': 'lastStatusCount',
},
ExpressionAttributeValues: updateValues,
UpdateExpression: `SET #lastStatus = :lastStatus, ${updateExpr}`,
ReturnValues: 'ALL_NEW',
})
.then(result => {
// Check for enough undelivered messages to alert the admins of the department
if (result === null) {
return null;
}
if (
result.Attributes?.lastStatus === 'undelivered' &&
typeof result.Attributes?.lastStatusCount === 'number' &&
result.Attributes.lastStatusCount >= 10 &&
result.Attributes.lastStatusCount % 10 === 0 &&
typeof result.Attributes.phone !== 'undefined'
) {
const queueMessage: PhoneNumberIssueQueueItem = {
action: 'phone-issue',
count: result.Attributes.lastStatusCount,
name: `${result.Attributes.fName} ${result.Attributes.lName}`,
number: result.Attributes.phone,
department: validDepartments
.filter(dep => result.Attributes && result.Attributes[dep]?.active),
};
return sqs.send(new SendMessageCommand({
QueueUrl: queueUrl,
MessageBody: JSON.stringify(queueMessage),
}));
}
return null;
});
}
// Update the metrics for the type of message status
const metricName = body.MessageStatus.slice(0, 1).toUpperCase() +
body.MessageStatus.slice(1) + 'Time';
const messageTime = new Date(params.id);
promises['metrics'] = cloudWatch.send(new PutMetricDataCommand({
Namespace: 'Twilio Health',
MetricData: [ {
MetricName: metricName,
Timestamp: messageTime,
Unit: 'Milliseconds',
Value: eventTime - messageTime.getTime(),
}, ],
}));
let wasError = false;
await Promise.all(Object.keys(promises)
.map(name => promises[name].catch(e => {
wasError = true;
logger.error(`Error on promise ${name}`, e);
})));
if (wasError) {
throw new Error('Error in promises');
}
return [
204,
'',
];
};
export const main = handleResourceApi.bind(null, {
POST,
});
|