Skip to content

Upgrade tc-email-service and logs #65

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

Merged
merged 40 commits into from
Oct 21, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
40 commits
Select commit Hold shift + click to select a range
4171c43
add attachments
eisbilir Aug 31, 2022
e1744cb
upgrade node version
eisbilir Sep 1, 2022
60f419e
WIP-upgrade node and coding style
hamidre13 Sep 6, 2022
7dfa2fc
Branch change
hamidre13 Sep 7, 2022
02e1caf
pulling from origin
hamidre13 Sep 7, 2022
5afa11b
feat:Adding sednAt and personalization fields
hamidre13 Sep 7, 2022
5e87a2b
Merge conflicts
hamidre13 Sep 7, 2022
343eb29
Move the email msg to if statement
hamidre13 Sep 7, 2022
c10184b
Merge pull request #53 from topcoder-platform/ptc/email
eisbilir Sep 7, 2022
073333d
Change from null to undefined
hamidre13 Sep 7, 2022
6bafd39
Merge pull request #54 from topcoder-platform/ptc/email
eisbilir Sep 7, 2022
0727f99
Merge conflicts
hamidre13 Sep 13, 2022
aca56bc
Updating with db
Sep 19, 2022
4992dd7
WIP- Branch change
Sep 20, 2022
043abd8
Add log to sendgrid email
Sep 20, 2022
7cbf3a8
Merge pull request #55 from topcoder-platform/sendGridLogging
Sep 20, 2022
58398fa
proper logger import
Sep 20, 2022
ca8c497
Merge pull request #56 from topcoder-platform/sendGridLogging
Sep 20, 2022
9b645b5
Changed logging and add schedule
Sep 23, 2022
d003c0e
Added more logging
Sep 23, 2022
3c402ce
Merge pull request #52 from topcoder-platform/feature/PLAT-1484
Sep 23, 2022
3230d80
Format kafka url
Sep 23, 2022
fa01ae0
Merge pull request #57 from topcoder-platform/feature/PLAT-1484
Sep 23, 2022
7c4dee6
Clean up
Sep 23, 2022
0dae3c0
Merge pull request #58 from topcoder-platform/feature/PLAT-1484
Sep 23, 2022
6ce7897
More logging
Sep 24, 2022
4a73617
Merge pull request #59 from topcoder-platform/feature/PLAT-1484
Sep 24, 2022
4806873
Added tracing
Oct 14, 2022
bc01189
Added tracing config
Oct 14, 2022
fc48b90
Merge pull request #60 from topcoder-platform/tracing
Oct 14, 2022
ec80e9b
Import function wrapper
Oct 15, 2022
06c1e02
Merge pull request #61 from topcoder-platform/tracing
Oct 15, 2022
c1707bf
Proper improt
Oct 17, 2022
06d2e09
Merge pull request #62 from topcoder-platform/tracing
Oct 17, 2022
7a99f86
Added tracing again
Oct 18, 2022
5d54523
More tracing
Oct 18, 2022
dfb04df
Merge pull request #63 from topcoder-platform/tracing
Oct 18, 2022
8c624da
Change tracing name
Oct 18, 2022
6f5d7ea
add more email logging and fix model.save
Oct 19, 2022
3056459
Merge branch 'master' into merge-master-conflicts
Oct 20, 2022
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
3 changes: 0 additions & 3 deletions .eslintrc

This file was deleted.

9 changes: 9 additions & 0 deletions .eslintrc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
module.exports = {
"parserOptions": {
"ecmaVersion": 12,
"env": {
"node": true,
"es2021": true
}
}
}
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
node_modules
.env
log.txt
3 changes: 2 additions & 1 deletion Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@
# and runs it against the specified Topcoder backend (development or
# production) when container is executed.

FROM node:8.2.1

FROM node:16.17
LABEL app="tc email" version="1.1"

WORKDIR /opt/app
Expand Down
11 changes: 8 additions & 3 deletions config/default.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
/**
* The configuration file.
*/
require('dotenv').config()
module.exports = {
LOG_LEVEL: process.env.LOG_LEVEL,
PORT: process.env.PORT,
AUTH_SECRET: process.env.AUTH_SECRET,
DATABASE_URL: process.env.DATABASE_URL,
DATABASE_OPTIONS: {
dialect: 'postgres',
logging: false,
dialectOptions: {
ssl: process.env.DATABASE_SSL != null,
},
Expand All @@ -34,18 +36,21 @@ module.exports = {
TEMPLATE_MAP: process.env.TEMPLATE_MAP,
SENDGRID_API_KEY: process.env.SENDGRID_API_KEY || '',
EMAIL_FROM: process.env.EMAIL_FROM || 'no-reply@topcoder.com',

// temporary not in use feature
EMAIL_MAX_ERRORS: process.env.EMAIL_MAX_ERRORS || 2,
EMAIL_PAUSE_TIME: process.env.EMAIL_PAUSE_TIME || 30,

//in every 2 minutes will retry for failed status
EMAIL_RETRY_SCHEDULE: process.env.EMAIL_RETRY_SCHEDULE || '0 */2 * * * *',
//wont't retry failed emails older than this time (msec)
EMAIL_RETRY_MAX_AGE: process.env.EMAIL_RETRY_MAX_AGE || 1000*60*60*24,
EMAIL_RETRY_MAX_AGE: process.env.EMAIL_RETRY_MAX_AGE || 1000 * 60 * 60 * 24,

API_CONTEXT_PATH: process.env.API_CONTEXT_PATH || '/v5/email',

PAYLOAD_SENDGRID_TEMPLATE_KEY: process.env.PAYLOAD_SENDGRID_TEMPLATE_KEY || 'sendgrid_template_id',

//Tracing information
APM_OTLP_TRACE_EXPORTER_URL: process.env.APM_OTLP_TRACE_EXPORTER_URL || '',
APM_SERVICE_NAME: process.env.APM_SERVICE_NAME || 'tc-email-service-svc',
APM_TRACER_NAME: process.env.APM_TRACER_NAME || 'tc-email-service-svc',
};
39 changes: 21 additions & 18 deletions connect/connectEmailServer.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,6 @@
/**
* This is TopCoder connect email server.
*/
'use strict';

global.Promise = require('bluebird');

const _ = require('lodash');
const config = require('config');
const emailServer = require('../index');
Expand All @@ -13,27 +9,27 @@ const logger = require('../src/common/logger');

// set configuration for the server, see ../config/default.js for available config parameters
// setConfig should be called before initDatabase and start functions
emailServer.setConfig({ LOG_LEVEL: 'debug' });
emailServer.setConfig({ LOG_LEVEL: config.LOG_LEVEL });

// add topic handlers,
// handler is used build a notification list for a message of a topic,
// it is defined as: function(topic, message, callback),
// it is defined as: function(topic, message),
// the topic is topic name,
// the message is JSON event message,
// the callback is function(error, templateId), where templateId is the used SendGrid template id
const handler = (topic, message, callback) => {
const handler = async (topic, message) => {
let templateId = config.TEMPLATE_MAP[topic];
templateId = _.get(message, config.PAYLOAD_SENDGRID_TEMPLATE_KEY, templateId);
if (!templateId) {
return callback(null, { success: false, error: `Template not found for topic ${topic}` });
return { success: false, error: `Template not found for topic ${topic}` };
}

service.sendEmail(templateId, message).then(() => {
callback(null, { success: true });
}).catch((err) => {
logger.error("Error occurred in sendgrid api calling:", err);
callback(null, { success: false, error: err });
});
try {
await service.sendEmail(templateId, message)
return { success: true };
} catch (err) {
logger.error("Error occurred in sendgrid api calling:", err);
return { success: false, error: err };
}

};

Expand All @@ -45,8 +41,15 @@ _.keys(config.TEMPLATE_MAP).forEach((eventType) => {
// init database, it will clear and re-create all tables
emailServer
.initDatabase()
.then(() => emailServer.start())
.catch((e) => console.log(e)); // eslint-disable-line no-console
.then(() => {
logger.info('Database initialized successfully.')

emailServer.start()
})
.catch((e) => {
logger.error('Error occurred in starting email server:', e);
process.exit(1);
}); // eslint-disable-line no-console

// if no need to init database, then directly start the server:
// emailServer.start();
// emailServer.start()
46 changes: 33 additions & 13 deletions connect/service.js
Original file line number Diff line number Diff line change
@@ -1,37 +1,44 @@
/**
* This is TopCoder connect email service.
*/
'use strict';

const sgMail = require('@sendgrid/mail');
const config = require('config');
const logger = require('../src/common/logger');

// set api key for SendGrid email client
sgMail.setApiKey(config.SENDGRID_API_KEY);

const sendEmail = (templateId, message) => { // send email

const sendEmail = async (templateId, message) => { // send email
const span = await logger.startSpan('sendEmail');
let msg = {}
const from = message.from ? message.from : config.EMAIL_FROM;
const replyTo = message.replyTo ? message.replyTo : config.EMAIL_FROM;
const substitutions = message.data ;
const categories = message.categories ? message.categories: [];
const substitutions = message.data;
const categories = message.categories ? message.categories : [];
const to = message.recipients;
const cc = message.cc ? message.cc : [];
const cc = message.cc ? message.cc : [];
const bcc = message.bcc ? message.bcc : [];

if (message.version && message.version=="v3"){
return sgMail.send({
const sendAt = message.sendAt ? message.sendAt : undefined;
const personalizations = message.personalizations ? message.personalizations : undefined
const attachments = message.attachments ? message.attachments : [];

if (message.version && message.version == "v3") {
msg = {
to,
templateId,
dynamicTemplateData: substitutions,
personalizations,
from,
replyTo,
categories,
cc,
bcc,
});
} else{
return sgMail.send({
attachments,
sendAt
};
} else {
msg = {
to,
templateId,
substitutions,
Expand All @@ -41,9 +48,22 @@ const sendEmail = (templateId, message) => { // send email
categories,
cc,
bcc,
});
};
}
logger.info(`Sending email with templateId: ${templateId} and message: ${JSON.stringify(msg)}`);
try {
await logger.endSpan(span);
const sgSpan = await logger.startSpan('sendgrid');
const result = await sgMail.send(msg)
await logger.endSpan(sgSpan);
logger.info(`Email sent successfully with result: ${JSON.stringify(result)} \n ${JSON.stringify(msg)}`);
return result
} catch (err) {
logger.error(`Error occurred in sendgrid api calling: ${err}`);
throw err
}
}
module.exports = {
sendEmail,
}
logger.buildService(module.exports)
7 changes: 3 additions & 4 deletions docs/swagger_api.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@ info:
description: "TOPCODER EMAIL SERIES - EMAIL SERVER"
version: "1.0.0"
host: "localhost:6100"
basePath : "/v5/email"
basePath: "/v5/email"
schemes:
- "https"
- "https"
securityDefinitions:
jwt:
type: apiKey
Expand All @@ -17,8 +17,7 @@ securityDefinitions:
paths:
/health:
get:
description:
health check endpoint
description: health check endpoint
produces:
- application/json
responses:
Expand Down
Loading