Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add job to load messages in from a csv and fix some crucial bugs in twilio.js #1346

Merged
merged 2 commits into from
Jan 2, 2020
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
"knex": "knex --knexfile ./knexfile.env.js",
"clean": "rm -rf $OUTPUT_DIR",
"lint": "eslint --fix --ext js --ext jsx src",
"process-message-csv": "./dev-tools/babel-run-with-env.js ./src/workers/process-message-csv.js",
"prod-build-client": "webpack --config ./webpack/config.js",
"prod-build-server": "babel ./src -d ./build/server --source-maps --copy-files; babel ./migrations -d ./build/server/migrations/ --source-maps --copy-files",
"prod-build": "npm run clean && npm run prod-build-client && npm run prod-build-server",
Expand Down
15 changes: 7 additions & 8 deletions src/server/api/lib/message-sending.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,16 +18,15 @@ export async function getLastMessage({ contactNumber, service }) {

export async function saveNewIncomingMessage(messageInstance) {
if (messageInstance.service_id) {
const countResult = await r.getCount(
r.knex("message").where("service_id", messageInstance.service_id)
);
const [countResult] = await r
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A theory about the failure was that this was getting a count rather than a single message -- it therefore deadlocked on two of the same messages coming in, because it didn't need to find just one, but get a full count.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This makes sense, though it would be good to rename this variable, since it is no longer the count (unless I'm misunderstanding the change).

.knex("message")
.where("service_id", messageInstance.service_id)
.select("id")
.limit(1);
if (countResult) {
console.error(
"DUPLICATE MESSAGE SAVED",
countResult.count,
messageInstance
);
console.error("DUPLICATE MESSAGE", countResult, messageInstance);
}
return;
strangeways marked this conversation as resolved.
Show resolved Hide resolved
}
await messageInstance.save();

Expand Down
9 changes: 7 additions & 2 deletions src/server/api/lib/twilio.js
Original file line number Diff line number Diff line change
Expand Up @@ -56,13 +56,16 @@ async function convertMessagePartsToMessage(messageParts) {
const lastMessage = await getLastMessage({
contactNumber
});
if (!lastMessage) {
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Often SMS spam comes in. If we failed to find a lastMessage, then this failed rather than returning and completing normally -- leaving a db connection open -- and possibly a transaction.

return;
}
return new Message({
contact_number: contactNumber,
user_number: userNumber,
is_from_contact: true,
text,
error_code: null,
service_id: serviceMessages[0].MessagingServiceSid,
service_id: firstPart.service_id,
assignment_id: lastMessage.assignment_id,
service: "twilio",
send_status: "DELIVERED"
Expand Down Expand Up @@ -345,7 +348,6 @@ async function handleIncomingMessage(message) {
user_number: userNumber,
contact_number: contactNumber
});

if (!process.env.JOBS_SAME_PROCESS) {
// If multiple processes, just insert the message part and let another job handle it
await r.knex("pending_message_part").insert(pendingMessagePart);
Expand All @@ -355,6 +357,9 @@ async function handleIncomingMessage(message) {
pendingMessagePart
]);
if (finalMessage) {
if (message.spokeCreatedAt) {
finalMessage.created_at = message.spokeCreatedAt;
}
await saveNewIncomingMessage(finalMessage);
}
}
Expand Down
39 changes: 39 additions & 0 deletions src/workers/jobs.js
Original file line number Diff line number Diff line change
Expand Up @@ -1251,6 +1251,45 @@ export async function handleIncomingMessageParts() {
}
}

export async function loadMessages(csvFile) {
return new Promise((resolve, reject) => {
Papa.parse(csvFile, {
header: true,
complete: ({ data, meta, errors }, file) => {
const fields = meta.fields;
console.log("FIELDS", fields);
console.log("FIRST LINE", data[0]);
const promises = [];
data.forEach(row => {
if (!row.contact_number) {
return;
}
const twilioMessage = {
From: `+1${row.contact_number}`,
To: `+1${row.user_number}`,
Body: row.text,
MessageSid: row.service_id,
MessagingServiceSid: row.service_id,
FromZip: row.zip, // unused at the moment
spokeCreatedAt: row.created_at
};
promises.push(serviceMap.twilio.handleIncomingMessage(twilioMessage));
});
console.log("Started all promises for CSV");
Promise.all(promises)
.then(doneDid => {
console.log(`Processed ${doneDid.length} rows for CSV`);
resolve(doneDid);
})
.catch(err => {
console.error("Error processing for CSV", err);
reject(err);
});
}
});
});
}

// Temporary fix for orgless users
// See https://github.com/MoveOnOrg/Spoke/issues/934
// and job-processes.js
Expand Down
20 changes: 20 additions & 0 deletions src/workers/process-message-csv.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { loadMessages } from "./jobs";
import fs from "fs";

const csvFilename = process.argv.filter(f => /\.csv/.test(f))[0];

new Promise((resolve, reject) => {
fs.readFile(csvFilename, "utf8", function(err, contents) {
loadMessages(contents)
.then(msgs => {
resolve(msgs);
process.exit();
})
.catch(err => {
console.log(err);
reject(err);
console.log("Error", err);
process.exit();
});
});
});