notification-processor
Advanced tools
| "use strict"; | ||
| function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } | ||
| // Generated by CoffeeScript 2.7.0 | ||
| (function () { | ||
| var IgnoredError; | ||
| module.exports = IgnoredError = function () { | ||
| var IgnoredError = function IgnoredError(message, cause) { | ||
| _classCallCheck(this, IgnoredError); | ||
| this.cause = cause; | ||
| this.name = this.constructor.name; | ||
| this.message = message; | ||
| this.stack = new Error().stack; | ||
| }; | ||
| ; | ||
| IgnoredError.prototype = new Error(); | ||
| IgnoredError.prototype.constructor = IgnoredError; | ||
| return IgnoredError; | ||
| }.call(this); | ||
| }).call(undefined); |
| "use strict"; | ||
| function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } | ||
| // Generated by CoffeeScript 2.7.0 | ||
| (function () { | ||
| var NonRetryable; | ||
| module.exports = NonRetryable = function () { | ||
| var NonRetryable = function NonRetryable(message, cause) { | ||
| _classCallCheck(this, NonRetryable); | ||
| this.cause = cause; | ||
| this.name = this.constructor.name; | ||
| this.message = message; | ||
| this.stack = new Error().stack; | ||
| }; | ||
| ; | ||
| NonRetryable.prototype = new Error(); | ||
| NonRetryable.prototype.constructor = NonRetryable; | ||
| return NonRetryable; | ||
| }.call(this); | ||
| }).call(undefined); |
+25
| "use strict"; | ||
| // Generated by CoffeeScript 2.7.0 | ||
| (function () { | ||
| module.exports = { | ||
| Builder: require("./processor.builder"), | ||
| Observers: { | ||
| LoggerObserver: require("./observers/logger.observer"), | ||
| IncidentsApi: require("./observers/incidentsApi.observer"), | ||
| MonitoringCenter: require("./observers/monitoringCenter.observer") | ||
| }, | ||
| Processors: { | ||
| DeadLetterProcessor: require("./processors/deadletter.processor"), | ||
| RequestProcessor: require("./processors/request.processor"), | ||
| RequestAsyncProcessor: require("./processors/requestWithRetries.async.processor"), | ||
| JobProcessor: require("./processors/job"), | ||
| MaxRetriesProcessor: require("./processors/maxRetries.processor") | ||
| }, | ||
| Exceptions: { | ||
| NonRetryable: require("./exceptions/non.retryable") | ||
| }, | ||
| Sources: require("./sources"), | ||
| Senders: require("./senders") | ||
| }; | ||
| }).call(undefined); |
| "use strict"; | ||
| // Generated by CoffeeScript 2.7.0 | ||
| (function () { | ||
| var convert; | ||
| convert = require("convert-units"); | ||
| //delay : { name, value: amount of milliseconds where this delay level is considered to start } | ||
| module.exports = { //milliseconds | ||
| minimal: { | ||
| name: "Minimal", | ||
| value: 0 | ||
| }, | ||
| mild: { | ||
| name: "Mild", | ||
| value: process.env.MILD_DELAY || convert(2).from('s').to('ms') | ||
| }, | ||
| moderate: { | ||
| name: "Moderate", | ||
| value: process.env.MODERATE_DELAY || convert(10).from('s').to('ms') | ||
| }, | ||
| high: { | ||
| name: "High", | ||
| value: process.env.HIGH_DELAY || convert(5).from('min').to('ms') | ||
| }, | ||
| huge: { | ||
| name: "Huge", | ||
| value: process.env.HUGE_DELAY || convert(10).from('min').to('ms') | ||
| } | ||
| }; | ||
| }).call(undefined); |
| "use strict"; | ||
| var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); | ||
| function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } | ||
| // Generated by CoffeeScript 2.7.0 | ||
| (function () { | ||
| var IncidentsApiObserver, Promise, ServiceBusClient, _, debug, encode; | ||
| _ = require("lodash"); | ||
| Promise = require("bluebird"); | ||
| var _require = require("@azure/service-bus"); | ||
| ServiceBusClient = _require.ServiceBusClient; | ||
| var _require2 = require("url-safe-base64"); | ||
| encode = _require2.encode; | ||
| debug = require("debug")("notification-processor:observers:incidents-api"); | ||
| module.exports = IncidentsApiObserver = function () { | ||
| function IncidentsApiObserver(_ref) { | ||
| var sender = _ref.sender, | ||
| clientId = _ref.clientId, | ||
| app = _ref.app, | ||
| job = _ref.job, | ||
| _ref$propertiesToOmit = _ref.propertiesToOmit, | ||
| propertiesToOmit = _ref$propertiesToOmit === undefined ? "auth" : _ref$propertiesToOmit, | ||
| _ref$connection = _ref.connection, | ||
| connectionString = _ref$connection.connectionString, | ||
| topic = _ref$connection.topic; | ||
| _classCallCheck(this, IncidentsApiObserver); | ||
| this.publishToTopic = this.publishToTopic.bind(this); | ||
| this.sender = sender; | ||
| this.clientId = clientId; | ||
| this.app = app; | ||
| this.job = job; | ||
| this.propertiesToOmit = propertiesToOmit; | ||
| this.messageSender = this._buildMessageSender(connectionString, topic); | ||
| } | ||
| _createClass(IncidentsApiObserver, [{ | ||
| key: "listenTo", | ||
| value: function listenTo(observable) { | ||
| return observable.on("unsuccessful_non_retryable", this.publishToTopic); | ||
| } | ||
| }, { | ||
| key: "publishToTopic", | ||
| value: function publishToTopic(_ref2) { | ||
| var _this = this; | ||
| var id = _ref2.id, | ||
| notification = _ref2.notification, | ||
| error = _ref2.error; | ||
| var $message; | ||
| $message = Promise.props({ | ||
| body: this._mapper(id, notification, error.cause) | ||
| }); | ||
| return $message.tap(function (message) { | ||
| return debug("To publish message %o", message); | ||
| }).then(function (message) { | ||
| return _this.messageSender.send(message); | ||
| }); | ||
| } | ||
| }, { | ||
| key: "_mapper", | ||
| value: function _mapper(id, notification, err) { | ||
| var _this2 = this; | ||
| return Promise.props({ | ||
| resource: Promise.method(this.sender.resource)(notification), | ||
| user: Promise.method(this.sender.user)(notification) | ||
| }).then(function (_ref3) { | ||
| var resource = _ref3.resource, | ||
| user = _ref3.user; | ||
| return { | ||
| id: encode([_this2.app, _this2.job, resource].join("_")), | ||
| app: _this2.app, | ||
| job: _this2.job, | ||
| resource: "" + resource, | ||
| notification: notification, | ||
| user: "" + user, | ||
| clientId: _this2.clientId, | ||
| error: _.omit(err, "detail.request"), | ||
| request: _.omit(_.get(err, "detail.request"), _this2.propertiesToOmit), | ||
| type: _.get(err, "type", "unknown_error"), | ||
| tags: _.get(err, "tags", []) | ||
| }; | ||
| }).then(JSON.stringify); | ||
| } | ||
| }, { | ||
| key: "_buildMessageSender", | ||
| value: function _buildMessageSender(connectionString, topic) { | ||
| return ServiceBusClient.createFromConnectionString(connectionString).createQueueClient(topic).createSender(); | ||
| } | ||
| }]); | ||
| return IncidentsApiObserver; | ||
| }(); | ||
| }).call(undefined); |
| "use strict"; | ||
| // Generated by CoffeeScript 2.7.0 | ||
| (function () { | ||
| var errorToJson; | ||
| errorToJson = require("error-to-json"); | ||
| module.exports = { | ||
| listenTo: function listenTo(observable) { | ||
| observable.on("started", function (_ref) { | ||
| var log = _ref.context.log, | ||
| notification = _ref.notification, | ||
| id = _ref.id; | ||
| return log.info("A new message has been received", { | ||
| id: id, | ||
| notification: JSON.stringify(notification) | ||
| }); | ||
| }); | ||
| observable.on("successful", function (_ref2) { | ||
| var log = _ref2.context.log, | ||
| id = _ref2.id; | ||
| return log.info("The process was successful", { id: id }); | ||
| }); | ||
| observable.on("unsuccessful", function (_ref3) { | ||
| var log = _ref3.context.log, | ||
| id = _ref3.id, | ||
| notification = _ref3.notification, | ||
| error = _ref3.error; | ||
| return log.error("The process was unsuccessful", { | ||
| id: id, | ||
| notification: JSON.stringify(notification), | ||
| error: JSON.stringify(errorToJson(error)) | ||
| }); | ||
| }); | ||
| observable.on("unsuccessful_non_retryable", function (_ref4) { | ||
| var log = _ref4.context.log, | ||
| id = _ref4.id, | ||
| notification = _ref4.notification, | ||
| error = _ref4.error; | ||
| return log.error("The process was unsuccessful but it can't be retried", { | ||
| id: id, | ||
| notification: JSON.stringify(notification), | ||
| error: JSON.stringify(errorToJson(error)) | ||
| }); | ||
| }); | ||
| return observable.on("ignored", function (_ref5) { | ||
| var log = _ref5.context.log, | ||
| id = _ref5.id; | ||
| return log.verbose("The message was ignored", { id: id }); | ||
| }); | ||
| } | ||
| }; | ||
| }).call(undefined); |
| "use strict"; | ||
| var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); | ||
| function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } | ||
| // Generated by CoffeeScript 2.7.0 | ||
| (function () { | ||
| var AWS, MESSAGE_PROPERTIES, MonitoringCenterObserver, Promise, TYPE_PROPERTIES, _, debug, moment, retry; | ||
| _ = require("lodash"); | ||
| Promise = require("bluebird"); | ||
| retry = require("bluebird-retry"); | ||
| debug = require("debug")("notification-processor:observers:monitor-center"); | ||
| AWS = require("aws-sdk"); | ||
| moment = require("moment"); | ||
| TYPE_PROPERTIES = ["cause.type", "type"]; | ||
| MESSAGE_PROPERTIES = ["cause.message", "message"]; | ||
| module.exports = MonitoringCenterObserver = function () { | ||
| function MonitoringCenterObserver(_ref) { | ||
| var sender = _ref.sender, | ||
| clientId = _ref.clientId, | ||
| app1 = _ref.app, | ||
| job1 = _ref.job, | ||
| _ref$propertiesToOmit = _ref.propertiesToOmit, | ||
| propertiesToOmit = _ref$propertiesToOmit === undefined ? "auth" : _ref$propertiesToOmit, | ||
| _ref$connection = _ref.connection, | ||
| accessKeyId = _ref$connection.accessKeyId, | ||
| secretAccessKey = _ref$connection.secretAccessKey, | ||
| deliveryStream = _ref$connection.deliveryStream, | ||
| jobsDeliveryStream = _ref$connection.jobsDeliveryStream, | ||
| region = _ref$connection.region; | ||
| _classCallCheck(this, MonitoringCenterObserver); | ||
| this.registerRecord = this.registerRecord.bind(this); | ||
| this._registerJob = this._registerJob.bind(this); | ||
| this._registerExecution = this._registerExecution.bind(this); | ||
| this.sender = sender; | ||
| this.clientId = clientId; | ||
| this.app = app1; | ||
| this.job = job1; | ||
| this.propertiesToOmit = propertiesToOmit; | ||
| this.deliveryStream = deliveryStream; | ||
| this.jobsDeliveryStream = jobsDeliveryStream; | ||
| this.firehose = new AWS.Firehose({ accessKeyId: accessKeyId, secretAccessKey: secretAccessKey, region: region }); | ||
| this.uploadToFirehose = Promise.promisify(this.firehose.putRecord).bind(this.firehose); | ||
| } | ||
| _createClass(MonitoringCenterObserver, [{ | ||
| key: "listenTo", | ||
| value: function listenTo(observable) { | ||
| var _this = this; | ||
| observable.on("unsuccessful_non_retryable", function (payload) { | ||
| return _this.registerRecord(payload, "unsuccessful"); | ||
| }); | ||
| observable.on("unsuccessful", function (payload) { | ||
| return _this.registerRecord(payload, "unsuccessful"); | ||
| }); | ||
| observable.on("started", function (payload) { | ||
| return _this.registerRecord(payload, "pending"); | ||
| }); | ||
| return observable.on("successful", function (payload) { | ||
| return _this.registerRecord(payload, "successful"); | ||
| }); | ||
| } | ||
| }, { | ||
| key: "registerRecord", | ||
| value: function registerRecord(payload, executionStatus) { | ||
| var _this2 = this; | ||
| var deliveryStreamName, jobId; | ||
| jobId = _.get(payload, 'notification.message.JobId'); | ||
| deliveryStreamName = jobId ? this.jobsDeliveryStream : this.deliveryStream; | ||
| return this._mapper(_.merge({ executionStatus: executionStatus, jobId: jobId }, payload)).tap(function (record) { | ||
| return debug("Record to save in firehose %s %j", deliveryStreamName, record); | ||
| }).then(function (record) { | ||
| var __uploadToFirehose, uploadParams; | ||
| if (_.isEmpty(record)) { | ||
| return; | ||
| } | ||
| uploadParams = { | ||
| DeliveryStreamName: deliveryStreamName, | ||
| Record: { | ||
| Data: JSON.stringify(record) | ||
| } | ||
| }; | ||
| debug("Uploading record " + record.event + "/" + record.id + " to firehose delivery stream " + uploadParams.DeliveryStreamName); | ||
| __uploadToFirehose = function __uploadToFirehose() { | ||
| return _this2.uploadToFirehose(uploadParams); | ||
| }; | ||
| return retry(__uploadToFirehose, { | ||
| throw_original: true | ||
| }).tap(function () { | ||
| return debug("Uploaded record " + record.event + "/" + record.id + " to firehose delivery stream " + uploadParams.DeliveryStreamName); | ||
| }).catch(function (e) { | ||
| // We'll do nothing with this error | ||
| return debug("Error uploading record " + record.event + "/" + record.id + " to firehose delivery stream " + uploadParams.DeliveryStreamName + " %o", e); | ||
| }); | ||
| }); | ||
| } | ||
| }, { | ||
| key: "_mapper", | ||
| value: function _mapper(_ref2) { | ||
| var _this3 = this; | ||
| var id = _ref2.id, | ||
| notification = _ref2.notification, | ||
| error = _ref2.error, | ||
| warnings = _ref2.warnings, | ||
| executionStatus = _ref2.executionStatus, | ||
| jobId = _ref2.jobId; | ||
| return Promise.method(this.sender.monitoringCenterFields.bind(this.sender))(notification).then(function (_ref3) { | ||
| var eventType = _ref3.eventType, | ||
| resource = _ref3.resource, | ||
| companyId = _ref3.companyId, | ||
| userId = _ref3.userId, | ||
| externalReference = _ref3.externalReference, | ||
| userExternalReference = _ref3.userExternalReference, | ||
| eventId = _ref3.eventId, | ||
| eventTimestamp = _ref3.eventTimestamp, | ||
| parentEventId = _ref3.parentEventId, | ||
| app = _ref3.app, | ||
| job = _ref3.job, | ||
| partialMessage = _ref3.partialMessage; | ||
| var basicRegister, errorType, executionRegister, now, theRequest; | ||
| if (!eventId) { | ||
| return Promise.resolve({}); | ||
| } | ||
| theRequest = _.get(error, "detail.request") || _.get(error, "cause.detail.request"); | ||
| errorType = _this3._retrieveMessageFromError(error, TYPE_PROPERTIES, "unknown"); | ||
| if (/the operation did not complete within the allocated time/gi.test(errorType)) { | ||
| errorType = "timed_out"; | ||
| } | ||
| now = new Date(); | ||
| basicRegister = { id: id, app: app, companyId: companyId, now: now, executionStatus: executionStatus, errorType: errorType, job: job }; | ||
| executionRegister = { eventType: eventType, userId: userId, eventId: eventId, parentEventId: parentEventId, externalReference: externalReference, userExternalReference: userExternalReference, error: error, theRequest: theRequest, partialMessage: partialMessage, notification: notification, resource: resource, eventTimestamp: eventTimestamp, warnings: warnings }; | ||
| if (jobId) { | ||
| return _this3._registerJob(basicRegister, jobId); | ||
| } else { | ||
| return _this3._registerExecution(basicRegister, executionRegister); | ||
| } | ||
| }); | ||
| } | ||
| }, { | ||
| key: "_registerJob", | ||
| value: function _registerJob(basicRegister, jobId) { | ||
| return { | ||
| id: basicRegister.id, | ||
| app: basicRegister.app || parseInt(this.clientId) || null, | ||
| trigger_id: jobId, | ||
| trigger_mode: "scheduled", | ||
| company: basicRegister.companyId, | ||
| start_time: basicRegister.now.getTime(), | ||
| integration: this.app + "|" + (basicRegister.job || this.job), | ||
| error_type: basicRegister.errorType, | ||
| status: basicRegister.executionStatus | ||
| }; | ||
| } | ||
| }, { | ||
| key: "_registerExecution", | ||
| value: function _registerExecution(basicRegister, executionRegister) { | ||
| var _this4 = this; | ||
| var errorMessage, now, ref; | ||
| now = basicRegister.now; | ||
| errorMessage = this._retrieveMessageFromError(executionRegister.error, MESSAGE_PROPERTIES, ""); | ||
| return { | ||
| id: basicRegister.id, | ||
| executionId: basicRegister.id, | ||
| app: basicRegister.app || parseInt(this.clientId) || null, | ||
| type: executionRegister.eventType || "service-bus", | ||
| company: basicRegister.companyId, | ||
| user: executionRegister.userId, | ||
| event: executionRegister.eventId, | ||
| parent: executionRegister.parentEventId, | ||
| externalreference: executionRegister.externalReference, | ||
| userexternalreference: executionRegister.userExternalReference, | ||
| timestamp: now.getTime(), | ||
| date: now.toISOString(), | ||
| year: moment(now).format('YYYY'), | ||
| month: moment(now).format('MM'), | ||
| day: moment(now).format('DD'), | ||
| hour: moment(now).format('HH'), | ||
| payload: JSON.stringify({ | ||
| clientId: this.clientId, | ||
| job: this.job, | ||
| app: this.app, | ||
| error: _.omit(executionRegister.error, ["detail.request", "cause.detail.request"]), | ||
| request: _.omit(executionRegister.theRequest, _.castArray(this.propertiesToOmit).concat("auth")), | ||
| tags: _.get(executionRegister.error, "tags", []), | ||
| message: executionRegister.partialMessage || executionRegister.notification.message | ||
| }), | ||
| status: basicRegister.executionStatus, | ||
| resource: executionRegister.resource, | ||
| integration: this.app + "|" + (basicRegister.job || this.job), | ||
| // Generic app fields | ||
| event_timestamp: executionRegister.eventTimestamp || now.getTime(), | ||
| error_type: basicRegister.errorType, | ||
| output_message: errorMessage, | ||
| user_settings_version: null, //TODO | ||
| env_version: null, //TODO | ||
| code_version: null, //TODO | ||
| warnings: (ref = executionRegister.warnings) != null ? ref.map(function (warning) { | ||
| return { | ||
| type: _this4._retrieveMessageFromError(warning, TYPE_PROPERTIES, "unknown"), | ||
| message: _this4._retrieveMessageFromError(warning, MESSAGE_PROPERTIES, "") | ||
| }; | ||
| }) : void 0 | ||
| }; | ||
| } | ||
| }, { | ||
| key: "_retrieveMessageFromError", | ||
| value: function _retrieveMessageFromError(error, properties, defaultValue) { | ||
| return error && _(properties).map(function (property) { | ||
| return _.get(error, property); | ||
| }).reject(_.isEmpty).get(0, defaultValue); | ||
| } | ||
| }]); | ||
| return MonitoringCenterObserver; | ||
| }(); | ||
| }).call(undefined); |
| "use strict"; | ||
| var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); | ||
| function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } | ||
| // Generated by CoffeeScript 2.7.0 | ||
| (function () { | ||
| var Promise, Redis, RedisObserver, _; | ||
| _ = require("lodash"); | ||
| Redis = require("../services/redis"); | ||
| Promise = require("bluebird"); | ||
| module.exports = RedisObserver = function () { | ||
| function RedisObserver(_ref) { | ||
| var _ref$redis = _ref.redis, | ||
| redis = _ref$redis === undefined ? {} : _ref$redis; | ||
| _classCallCheck(this, RedisObserver); | ||
| this.publish = this.publish.bind(this); | ||
| this._getChannel = this._getChannel.bind(this); | ||
| this._messagePath_ = this._messagePath_.bind(this); | ||
| this._buildValue_ = this._buildValue_.bind(this); | ||
| this._channelPrefix_ = this._channelPrefix_.bind(this); | ||
| _.defaults(redis, { | ||
| host: process.env.REDIS_HOST, | ||
| port: process.env.REDIS_PORT, | ||
| db: process.env.REDIS_DB, | ||
| auth: process.env.REDIS_AUTH | ||
| }); | ||
| this.redis = Redis.createClient(redis.port, redis.host, { | ||
| db: redis.db | ||
| }); | ||
| if (redis.auth) { | ||
| this.redis.auth(redis.auth); | ||
| } | ||
| } | ||
| _createClass(RedisObserver, [{ | ||
| key: "publish", | ||
| value: function publish(notification, value) { | ||
| var _this = this; | ||
| return Promise.props({ | ||
| channel: this._getChannel(notification), | ||
| value: this._buildValue_(value) | ||
| }).then(function (_ref2) { | ||
| var channel = _ref2.channel, | ||
| value = _ref2.value; | ||
| return _this.redis.publishAsync(channel, value); | ||
| }); | ||
| } | ||
| }, { | ||
| key: "_getChannel", | ||
| value: function _getChannel(notification) { | ||
| return Promise.props({ | ||
| channelPrefix: this._channelPrefix_(notification.type), | ||
| messagePath: this._messagePath_(notification) | ||
| }).then(function (_ref3) { | ||
| var channelPrefix = _ref3.channelPrefix, | ||
| messagePath = _ref3.messagePath; | ||
| return channelPrefix + "/" + messagePath; | ||
| }); | ||
| } | ||
| }, { | ||
| key: "_messagePath_", | ||
| value: function _messagePath_() { | ||
| throw new Error("not supported `_messagePath_`"); | ||
| } | ||
| }, { | ||
| key: "_buildValue_", | ||
| value: function _buildValue_() { | ||
| throw new Error("not supported `_buildValue_`"); | ||
| } | ||
| }, { | ||
| key: "_channelPrefix_", | ||
| value: function _channelPrefix_(type) { | ||
| throw new Error("not supported `_channelPrefix_`"); | ||
| } | ||
| }]); | ||
| return RedisObserver; | ||
| }(); | ||
| }).call(undefined); |
| "use strict"; | ||
| var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); | ||
| function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } | ||
| // Generated by CoffeeScript 2.7.0 | ||
| (function () { | ||
| var AwsSQSSource, MeliSender, Processor, ProcessorBuilder, ProductecaSender, QueueSource, ServiceBusSource, UnknownSource, _, logger; | ||
| _ = require("lodash"); | ||
| Processor = require("./processor"); | ||
| logger = require("./observers/logger.observer"); | ||
| var _require = require("./sources"); | ||
| UnknownSource = _require.UnknownSource; | ||
| ServiceBusSource = _require.ServiceBusSource; | ||
| QueueSource = _require.QueueSource; | ||
| AwsSQSSource = _require.AwsSQSSource; | ||
| var _require2 = require("./senders"); | ||
| MeliSender = _require2.MeliSender; | ||
| ProductecaSender = _require2.ProductecaSender; | ||
| ProcessorBuilder = function () { | ||
| function ProcessorBuilder() { | ||
| _classCallCheck(this, ProcessorBuilder); | ||
| this.source = UnknownSource; | ||
| this.listeners = []; | ||
| } | ||
| _createClass(ProcessorBuilder, [{ | ||
| key: "withSource", | ||
| value: function withSource(source) { | ||
| this.source = source; | ||
| return this; | ||
| } | ||
| }, { | ||
| key: "withSender", | ||
| value: function withSender(sender) { | ||
| this.sender = sender; | ||
| return this; | ||
| } | ||
| }, { | ||
| key: "withTimeout", | ||
| value: function withTimeout(timeout) { | ||
| this.timeout = timeout; | ||
| return this; | ||
| } | ||
| }, { | ||
| key: "withApm", | ||
| value: function withApm(apm) { | ||
| this.apm = apm; | ||
| return this; | ||
| } | ||
| }, { | ||
| key: "fromServiceBus", | ||
| value: function fromServiceBus() { | ||
| return this.withSource(ServiceBusSource); | ||
| } | ||
| }, { | ||
| key: "fromAwsSQS", | ||
| value: function fromAwsSQS() { | ||
| return this.withSource(AwsSQSSource); | ||
| } | ||
| }, { | ||
| key: "fromQueue", | ||
| value: function fromQueue() { | ||
| return this.withSource(QueueSource); | ||
| } | ||
| }, { | ||
| key: "fromMeli", | ||
| value: function fromMeli() { | ||
| return this.withSender(MeliSender); | ||
| } | ||
| }, { | ||
| key: "fromProducteca", | ||
| value: function fromProducteca() { | ||
| return this.withSender(ProductecaSender); | ||
| } | ||
| }, { | ||
| key: "withFunction", | ||
| value: function withFunction(command) { | ||
| this.command = command; | ||
| return this; | ||
| } | ||
| }, { | ||
| key: "withLogging", | ||
| value: function withLogging() { | ||
| return this.withListeners(logger); | ||
| } | ||
| }, { | ||
| key: "withListeners", | ||
| value: function withListeners() { | ||
| for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { | ||
| args[_key] = arguments[_key]; | ||
| } | ||
| this.listeners = _.concat(this.listeners, args); | ||
| return this; | ||
| } | ||
| }, { | ||
| key: "build", | ||
| value: function build() { | ||
| var processor; | ||
| processor = new Processor({ | ||
| source: this.source, | ||
| runner: this.command, | ||
| timeout: this.timeout, | ||
| apm: this.apm | ||
| }); | ||
| _.forEach(this.listeners, function (listener) { | ||
| return listener.listenTo(processor); | ||
| }); | ||
| return processor; | ||
| } | ||
| }], [{ | ||
| key: "create", | ||
| value: function create() { | ||
| return new this(); | ||
| } | ||
| }]); | ||
| return ProcessorBuilder; | ||
| }(); | ||
| module.exports = ProcessorBuilder; | ||
| }).call(undefined); |
+132
| "use strict"; | ||
| var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); | ||
| function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } | ||
| function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } | ||
| function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } | ||
| // Generated by CoffeeScript 2.7.0 | ||
| (function () { | ||
| var ENABLE_EVENTS, | ||
| EventEmitter, | ||
| IgnoredError, | ||
| NonRetryable, | ||
| Processor, | ||
| Promise, | ||
| _, | ||
| newrelic, | ||
| uuid, | ||
| boundMethodCheck = function boundMethodCheck(instance, Constructor) { | ||
| if (!(instance instanceof Constructor)) { | ||
| throw new Error('Bound instance method accessed before binding'); | ||
| } | ||
| }; | ||
| _ = require("lodash"); | ||
| NonRetryable = require("./exceptions/non.retryable"); | ||
| IgnoredError = require("./exceptions/ignored.error"); | ||
| EventEmitter = require("events"); | ||
| Promise = require("bluebird"); | ||
| uuid = require("uuid/v4"); | ||
| newrelic = _.once(function () { | ||
| return require("newrelic"); | ||
| }); | ||
| ENABLE_EVENTS = process.env.ENABLE_EVENTS !== "false"; | ||
| module.exports = Processor = function (_EventEmitter) { | ||
| _inherits(Processor, _EventEmitter); | ||
| function Processor(_ref) { | ||
| var source = _ref.source, | ||
| runner = _ref.runner, | ||
| timeout = _ref.timeout, | ||
| apm = _ref.apm; | ||
| _classCallCheck(this, Processor); | ||
| var _this = _possibleConstructorReturn(this, (Processor.__proto__ || Object.getPrototypeOf(Processor)).call(this)); | ||
| _this.process = _this.process.bind(_this); | ||
| _this._emitEvent = _this._emitEvent.bind(_this); | ||
| _this.source = source; | ||
| _this.runner = runner; | ||
| _this.timeout = timeout; | ||
| _this.apm = apm; | ||
| return _this; | ||
| } | ||
| _createClass(Processor, [{ | ||
| key: "process", | ||
| value: function process(context, raw) { | ||
| var _this2 = this; | ||
| var $promise, _isIgnoredError, execute, id, notification; | ||
| boundMethodCheck(this, Processor); | ||
| id = uuid(); | ||
| notification = this.source.newNotification({ | ||
| context: context, | ||
| id: id, | ||
| message: raw | ||
| }); | ||
| this._emitEvent("started", { context: context, id: id, notification: notification }); | ||
| $promise = Promise.method(this.runner)(notification, context, id); | ||
| if (this.timeout != null) { | ||
| $promise = $promise.timeout(this.timeout, "processor timeout"); | ||
| } | ||
| execute = function execute() { | ||
| var ref; | ||
| if (!((ref = _this2.apm) != null ? ref.active : void 0)) { | ||
| return $promise; | ||
| } | ||
| return newrelic().startBackgroundTransaction(_this2.apm.transactionName, _this2.apm.group, function () { | ||
| return $promise.tapCatch(function (err) { | ||
| return newrelic().noticeError(new Error(JSON.stringify(_.omit(err.detail, "request.auth.pass")))); | ||
| }); | ||
| }); | ||
| }; | ||
| _isIgnoredError = function _isIgnoredError(error) { | ||
| return error instanceof IgnoredError; | ||
| }; | ||
| execute().tap(function () { | ||
| return _this2._emitEvent("successful", { context: context, id: id, notification: notification }); | ||
| }).catch(_isIgnoredError, function (error) { | ||
| return _this2._emitEvent("successful", { | ||
| context: context, | ||
| id: id, | ||
| notification: notification, | ||
| warnings: [error] | ||
| }); | ||
| }).catch(function (error) { | ||
| if (!(error instanceof NonRetryable)) { | ||
| throw error; | ||
| } | ||
| return _this2._emitEvent("unsuccessful_non_retryable", { context: context, id: id, notification: notification, error: error }); | ||
| }).tapCatch(function (error) { | ||
| return _this2._emitEvent("unsuccessful", { context: context, id: id, notification: notification, error: error }); | ||
| }).finally(function () { | ||
| return _this2._emitEvent("finished", { context: context, id: id, notification: notification }); | ||
| }).asCallback(context.done); | ||
| } | ||
| }, { | ||
| key: "_emitEvent", | ||
| value: function _emitEvent(eventName, value) { | ||
| boundMethodCheck(this, Processor); | ||
| if (ENABLE_EVENTS) { | ||
| return this.emit(eventName, value); | ||
| } | ||
| } | ||
| }]); | ||
| return Processor; | ||
| }(EventEmitter); | ||
| }).call(undefined); |
| "use strict"; | ||
| var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); | ||
| function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } | ||
| function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } | ||
| function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } | ||
| // Generated by CoffeeScript 2.7.0 | ||
| (function () { | ||
| var DeadletterProcessor, MaxRetriesProcessor, NonRetryable; | ||
| MaxRetriesProcessor = require("./maxRetries.processor"); | ||
| NonRetryable = require("../exceptions/non.retryable"); | ||
| module.exports = DeadletterProcessor = function (_MaxRetriesProcessor) { | ||
| _inherits(DeadletterProcessor, _MaxRetriesProcessor); | ||
| function DeadletterProcessor() { | ||
| _classCallCheck(this, DeadletterProcessor); | ||
| return _possibleConstructorReturn(this, (DeadletterProcessor.__proto__ || Object.getPrototypeOf(DeadletterProcessor)).apply(this, arguments)); | ||
| } | ||
| _createClass(DeadletterProcessor, [{ | ||
| key: "_onSuccess_", | ||
| value: function _onSuccess_(notification, result) {} | ||
| }, { | ||
| key: "_sanitizeError_", | ||
| value: function _sanitizeError_(err) { | ||
| return err; | ||
| } | ||
| }, { | ||
| key: "_onMaxRetryExceeded_", | ||
| value: function _onMaxRetryExceeded_(notification, err) { | ||
| throw new NonRetryable("Max retry exceeded", err); | ||
| } | ||
| }]); | ||
| return DeadletterProcessor; | ||
| }(MaxRetriesProcessor); | ||
| }).call(undefined); |
| "use strict"; | ||
| // Generated by CoffeeScript 2.7.0 | ||
| (function () { | ||
| var JobProcessor, RequestAsyncProcessor, _; | ||
| _ = require("lodash"); | ||
| JobProcessor = require("./job.processor"); | ||
| RequestAsyncProcessor = require("../request.async.processor"); | ||
| module.exports = function (_ref) { | ||
| var apiUrl = _ref.apiUrl, | ||
| notificationApiUrl = _ref.notificationApiUrl, | ||
| maxRetries = _ref.maxRetries, | ||
| _ref$nonRetryable = _ref.nonRetryable, | ||
| nonRetryable = _ref$nonRetryable === undefined ? [400] : _ref$nonRetryable, | ||
| _ref$silentErrors = _ref.silentErrors, | ||
| silentErrors = _ref$silentErrors === undefined ? [] : _ref$silentErrors; | ||
| var jobProcesor; | ||
| jobProcesor = new JobProcessor({ | ||
| processor: RequestAsyncProcessor({ | ||
| apiUrl: apiUrl, | ||
| fullResponse: true, | ||
| silentErrors: silentErrors | ||
| }), | ||
| maxRetries: maxRetries, | ||
| nonRetryable: nonRetryable, | ||
| silentErrors: silentErrors, | ||
| notificationApiUrl: notificationApiUrl | ||
| }); | ||
| return function (it, context, executionId) { | ||
| return jobProcesor.process(it, context, executionId); | ||
| }; | ||
| }; | ||
| }).call(undefined); |
| "use strict"; | ||
| var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); | ||
| var _get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; | ||
| function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } | ||
| function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } | ||
| function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } | ||
| // Generated by CoffeeScript 2.7.0 | ||
| (function () { | ||
| var JobProcessor, | ||
| MaxRetriesProcessor, | ||
| NonRetryable, | ||
| NotificationsApi, | ||
| _, | ||
| debug, | ||
| request, | ||
| boundMethodCheck = function boundMethodCheck(instance, Constructor) { | ||
| if (!(instance instanceof Constructor)) { | ||
| throw new Error('Bound instance method accessed before binding'); | ||
| } | ||
| }, | ||
| indexOf = [].indexOf; | ||
| _ = require("lodash"); | ||
| request = require("request-promise"); | ||
| MaxRetriesProcessor = require("../maxRetries.processor"); | ||
| NonRetryable = require("../../exceptions/non.retryable"); | ||
| NotificationsApi = require("./notification.api"); | ||
| debug = require("debug")("notification-processor:job-processor"); | ||
| module.exports = JobProcessor = function (_MaxRetriesProcessor) { | ||
| _inherits(JobProcessor, _MaxRetriesProcessor); | ||
| function JobProcessor(args) { | ||
| _classCallCheck(this, JobProcessor); | ||
| var _this = _possibleConstructorReturn(this, (JobProcessor.__proto__ || Object.getPrototypeOf(JobProcessor)).call(this, args)); | ||
| _this.process = _this.process.bind(_this); | ||
| _this._onSuccess_ = _this._onSuccess_.bind(_this); | ||
| _this._shouldRetry_ = _this._shouldRetry_.bind(_this); | ||
| _this._sanitizeError_ = _this._sanitizeError_.bind(_this); | ||
| _this._onMaxRetryExceeded_ = _this._onMaxRetryExceeded_.bind(_this); | ||
| _this._notificationsApi = _this._notificationsApi.bind(_this); | ||
| _this._ifJobIsNotStopped = _this._ifJobIsNotStopped.bind(_this); | ||
| _this.notificationApiUrl = args.notificationApiUrl; | ||
| _this.notificationApiAsyncUrl = args.notificationApiAsyncUrl; | ||
| _this.nonRetryable = args.nonRetryable; | ||
| _this.silentErrors = args.silentErrors; | ||
| return _this; | ||
| } | ||
| _createClass(JobProcessor, [{ | ||
| key: "process", | ||
| value: function process(notification, context, executionId) { | ||
| var _this2 = this; | ||
| boundMethodCheck(this, JobProcessor); | ||
| return this._ifJobIsNotStopped(notification.message, function () { | ||
| return _get(JobProcessor.prototype.__proto__ || Object.getPrototypeOf(JobProcessor.prototype), "process", _this2).call(_this2, notification, context, executionId).thenReturn(); | ||
| }); | ||
| } | ||
| }, { | ||
| key: "_onSuccess_", | ||
| value: function _onSuccess_(_ref, _ref2) { | ||
| var _this3 = this; | ||
| var message = _ref.message; | ||
| var statusCode = _ref2.statusCode; | ||
| boundMethodCheck(this, JobProcessor); | ||
| return this._ifJobIsNotStopped(message, function () { | ||
| return _this3._notificationsApi(message).success({ message: message, statusCode: statusCode }); | ||
| }); | ||
| } | ||
| }, { | ||
| key: "_shouldRetry_", | ||
| value: function _shouldRetry_(notification, err) { | ||
| var ref, ref1, ref2; | ||
| boundMethodCheck(this, JobProcessor); | ||
| return _get(JobProcessor.prototype.__proto__ || Object.getPrototypeOf(JobProcessor.prototype), "_shouldRetry_", this).call(this, notification, err) && (ref = err != null ? (ref1 = err.detail) != null ? (ref2 = ref1.response) != null ? ref2.statusCode : void 0 : void 0 : void 0, indexOf.call(this.nonRetryable, ref) < 0); | ||
| } | ||
| }, { | ||
| key: "_sanitizeError_", | ||
| value: function _sanitizeError_(err) { | ||
| boundMethodCheck(this, JobProcessor); | ||
| return _.pick(err, ["statusCode", "error"]); | ||
| } | ||
| }, { | ||
| key: "_onMaxRetryExceeded_", | ||
| value: function _onMaxRetryExceeded_(_ref3, error) { | ||
| var _this4 = this; | ||
| var message = _ref3.message; | ||
| var errorMessage; | ||
| boundMethodCheck(this, JobProcessor); | ||
| errorMessage = { | ||
| message: message, | ||
| statusCode: error.detail.response.statusCode, | ||
| error: error, | ||
| request: _.omit(error.detail.request, ["resolveWithFullResponse"]) | ||
| }; | ||
| return this._ifJobIsNotStopped(message, function () { | ||
| return _this4._notificationsApi(message).fail(errorMessage).throw(new NonRetryable("Max retry exceeded", error)); | ||
| }); | ||
| } | ||
| }, { | ||
| key: "_notificationsApi", | ||
| value: function _notificationsApi(_ref4) { | ||
| var HeadersForRequest = _ref4.HeadersForRequest, | ||
| JobId = _ref4.JobId; | ||
| boundMethodCheck(this, JobProcessor); | ||
| return new NotificationsApi({ | ||
| token: _.find(HeadersForRequest, { | ||
| Key: "Authorization" | ||
| }).Value, | ||
| jobId: JobId, | ||
| notificationApiUrl: this.notificationApiUrl, | ||
| notificationApiAsyncUrl: this.notificationApiAsyncUrl | ||
| }); | ||
| } | ||
| }, { | ||
| key: "_ifJobIsNotStopped", | ||
| value: function _ifJobIsNotStopped(message, action) { | ||
| boundMethodCheck(this, JobProcessor); | ||
| return this._notificationsApi(message).jobIsStopped().then(function (jobIsStopped) { | ||
| if (jobIsStopped) { | ||
| console.log("job " + message.JobId + " is stopped, ignoring action"); | ||
| return Promise.resolve(); | ||
| } | ||
| return action(); | ||
| }); | ||
| } | ||
| }]); | ||
| return JobProcessor; | ||
| }(MaxRetriesProcessor); | ||
| }).call(undefined); |
| "use strict"; | ||
| var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); | ||
| function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } | ||
| // Generated by CoffeeScript 2.7.0 | ||
| (function () { | ||
| var DEFAULT_NOTIFICATIONS_API_ASYNC_URL, DEFAULT_NOTIFICATIONS_API_URL, HOUR, NOTIFICATIONS_API_JOBS_CACHE_TTL, NOTIFICATIONS_API_MASTER_TOKEN, NOTIFICATIONS_API_STOPPED_JOB_CACHE_TTL, NodeCache, NotificationsApi, Promise, _, jobsCache, requestPromise, retry, stoppedJobsCache; | ||
| _ = require("lodash"); | ||
| requestPromise = require("request-promise"); | ||
| retry = require("bluebird-retry"); | ||
| Promise = require("bluebird"); | ||
| NodeCache = require("node-cache"); | ||
| NOTIFICATIONS_API_JOBS_CACHE_TTL = parseInt(process.env.NOTIFICATIONS_API_JOBS_CACHE_TTL) || 5; | ||
| NOTIFICATIONS_API_STOPPED_JOB_CACHE_TTL = parseInt(process.env.NOTIFICATIONS_API_STOPPED_JOB_CACHE_TTL) || 2; | ||
| NOTIFICATIONS_API_MASTER_TOKEN = process.env.NOTIFICATIONS_API_MASTER_TOKEN; | ||
| DEFAULT_NOTIFICATIONS_API_ASYNC_URL = process.env.DEFAULT_NOTIFICATIONS_API_ASYNC_URL || "https://apps.producteca.com/aws/notifications-api-async"; | ||
| DEFAULT_NOTIFICATIONS_API_URL = process.env.NOTIFICATIONS_API_URL || "https://apps.producteca.com/notifications-api/api"; | ||
| HOUR = 60 * 60; | ||
| //Para minimizar las requests a notifications-api, cachea unos segundos el estado del job | ||
| jobsCache = new NodeCache({ | ||
| stdTTL: NOTIFICATIONS_API_JOBS_CACHE_TTL | ||
| }); | ||
| //A nivel dominio, podria ser cache sin TTL porque un job stoppeado queda asi para siempre. Pero se pone TTL de 2h para que luego libere la memoria | ||
| stoppedJobsCache = new NodeCache({ | ||
| stdTTL: NOTIFICATIONS_API_STOPPED_JOB_CACHE_TTL * HOUR | ||
| }); | ||
| NotificationsApi = function () { | ||
| function NotificationsApi(_ref) { | ||
| var _ref$notificationApiU = _ref.notificationApiUrl, | ||
| notificationApiUrl = _ref$notificationApiU === undefined ? DEFAULT_NOTIFICATIONS_API_URL : _ref$notificationApiU, | ||
| token1 = _ref.token, | ||
| jobId1 = _ref.jobId, | ||
| _ref$notificationApiA = _ref.notificationApiAsyncUrl, | ||
| notificationApiAsyncUrl = _ref$notificationApiA === undefined ? DEFAULT_NOTIFICATIONS_API_ASYNC_URL : _ref$notificationApiA; | ||
| _classCallCheck(this, NotificationsApi); | ||
| var companyId; | ||
| this.success = this.success.bind(this); | ||
| this.fail = this.fail.bind(this); | ||
| this.jobIsStopped = this.jobIsStopped.bind(this); | ||
| this.jobName = this.jobName.bind(this); | ||
| this._jobIsStopped = this._jobIsStopped.bind(this); | ||
| this.fetchJob = this.fetchJob.bind(this); | ||
| this._fetchJob = this._fetchJob.bind(this); | ||
| this._doFetchJob = this._doFetchJob.bind(this); | ||
| this._retryViaAsyncOrIgnore = this._retryViaAsyncOrIgnore.bind(this); | ||
| this._makeRequest = this._makeRequest.bind(this); | ||
| this._shouldUseCachedValue = this._shouldUseCachedValue.bind(this); | ||
| this.notificationApiUrl = notificationApiUrl; | ||
| this.token = token1; | ||
| this.jobId = jobId1; | ||
| this.notificationApiAsyncUrl = notificationApiAsyncUrl; | ||
| if (_.startsWith(this.token, 'Basic') && !_.isEmpty(NOTIFICATIONS_API_MASTER_TOKEN)) { | ||
| companyId = _.first(Buffer.from(_.get(this.token.split(" "), "1"), 'base64').toString().split(":")); | ||
| this.token = "Basic " + new Buffer(companyId + ":" + NOTIFICATIONS_API_MASTER_TOKEN).toString("base64"); | ||
| } | ||
| } | ||
| _createClass(NotificationsApi, [{ | ||
| key: "success", | ||
| value: function success(response, options) { | ||
| var _this = this; | ||
| var __makeRequest, __retryRequest, statusCode; | ||
| statusCode = response.statusCode; | ||
| __makeRequest = function __makeRequest() { | ||
| return _this._makeRequest({ | ||
| statusCode: statusCode, | ||
| success: true | ||
| }, options); | ||
| }; | ||
| __retryRequest = function __retryRequest() { | ||
| return _this.success(response, { | ||
| useAsyncApi: true | ||
| }); | ||
| }; | ||
| return this._retryViaAsyncOrIgnore(__makeRequest, __retryRequest, options); | ||
| } | ||
| }, { | ||
| key: "fail", | ||
| value: function fail(response, options) { | ||
| var _this2 = this; | ||
| var __makeRequest, __retryRequest, error, message, request, statusCode; | ||
| statusCode = response.statusCode; | ||
| error = response.error; | ||
| request = response.request; | ||
| message = _.get(error, "message"); | ||
| error = _.get(error, "type"); | ||
| __makeRequest = function __makeRequest() { | ||
| return _this2._makeRequest({ | ||
| statusCode: statusCode, | ||
| success: false, | ||
| message: message, | ||
| error: error, | ||
| request: request | ||
| }, options); | ||
| }; | ||
| __retryRequest = function __retryRequest() { | ||
| return _this2.fail(response, { | ||
| useAsyncApi: true | ||
| }); | ||
| }; | ||
| return this._retryViaAsyncOrIgnore(__makeRequest, __retryRequest, options); | ||
| } | ||
| }, { | ||
| key: "jobIsStopped", | ||
| value: function jobIsStopped() { | ||
| var _this3 = this; | ||
| var cachedStoppedJob; | ||
| cachedStoppedJob = stoppedJobsCache.get(this.jobId); | ||
| if (this._shouldUseCachedValue(cachedStoppedJob)) { | ||
| return Promise.resolve(cachedStoppedJob); | ||
| } | ||
| return this._jobIsStopped().tap(function (jobIsStopped) { | ||
| if (jobIsStopped) { | ||
| return stoppedJobsCache.set(_this3.jobId, jobIsStopped); | ||
| } | ||
| }); | ||
| } | ||
| }, { | ||
| key: "jobName", | ||
| value: function jobName(jobId, token) { | ||
| return this._fetchJob(jobId, token).then(function (job) { | ||
| return job.name; | ||
| }); | ||
| } | ||
| }, { | ||
| key: "_jobIsStopped", | ||
| value: function _jobIsStopped(jobId, token) { | ||
| return this._fetchJob(jobId, token).then(function (job) { | ||
| return job.stopped; | ||
| }); | ||
| } | ||
| }, { | ||
| key: "fetchJob", | ||
| value: function fetchJob(aJobId, aToken) { | ||
| return this._fetchJob(aJobId, aToken); | ||
| } | ||
| }, { | ||
| key: "_fetchJob", | ||
| value: function _fetchJob(aJobId, aToken) { | ||
| var cachedJob, jobId; | ||
| jobId = aJobId || this.jobId; | ||
| cachedJob = jobsCache.get(jobId); | ||
| if (this._shouldUseCachedValue(cachedJob)) { | ||
| return Promise.resolve(cachedJob); | ||
| } | ||
| return this._doFetchJob(jobId, aToken).tap(function (job) { | ||
| return jobsCache.set(jobId, job); | ||
| }); | ||
| } | ||
| }, { | ||
| key: "_doFetchJob", | ||
| value: function _doFetchJob(jobId, token) { | ||
| var _this4 = this; | ||
| var __fetchJob; | ||
| __fetchJob = function __fetchJob() { | ||
| return requestPromise({ | ||
| url: _this4.notificationApiUrl + "/jobs/" + (jobId || _this4.jobId), | ||
| method: "GET", | ||
| headers: { | ||
| authorization: token || _this4.token | ||
| }, | ||
| json: true | ||
| }).promise(); | ||
| }; | ||
| return retry(__fetchJob, { | ||
| throw_original: true | ||
| }); | ||
| } | ||
| }, { | ||
| key: "_retryViaAsyncOrIgnore", | ||
| value: function _retryViaAsyncOrIgnore(makeRequest, retryRequest) { | ||
| var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; | ||
| return retry(makeRequest, { | ||
| throw_original: true, | ||
| max_tries: 3 | ||
| }).catch(function (e) { | ||
| if (options.useAsyncApi) { | ||
| throw e; | ||
| } | ||
| console.log("Error sending status to notifications-api. Retrying via notifications-api-async"); | ||
| return retryRequest(); | ||
| }).catchReturn(); | ||
| } | ||
| }, { | ||
| key: "_makeRequest", | ||
| value: function _makeRequest(body) { | ||
| var _ref2 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, | ||
| useAsyncApi = _ref2.useAsyncApi; | ||
| var url; | ||
| url = useAsyncApi ? this.notificationApiAsyncUrl : this.notificationApiUrl; | ||
| return requestPromise({ | ||
| url: url + "/jobs/" + this.jobId + "/operations", | ||
| method: "POST", | ||
| headers: { | ||
| authorization: this.token | ||
| }, | ||
| json: body | ||
| }); | ||
| } | ||
| }, { | ||
| key: "_shouldUseCachedValue", | ||
| value: function _shouldUseCachedValue(value) { | ||
| return process.env.NODE_ENV !== "test" && value != null; | ||
| } | ||
| }]); | ||
| return NotificationsApi; | ||
| }(); | ||
| module.exports = NotificationsApi; | ||
| }).call(undefined); |
| "use strict"; | ||
| var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); | ||
| function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } | ||
| // Generated by CoffeeScript 2.7.0 | ||
| (function () { | ||
| var IgnoredError, MaxRetriesProcessor, Promise; | ||
| Promise = require("bluebird"); | ||
| IgnoredError = require("../exceptions/ignored.error"); | ||
| module.exports = MaxRetriesProcessor = function () { | ||
| function MaxRetriesProcessor(_ref) { | ||
| var processor = _ref.processor, | ||
| _ref$maxRetries = _ref.maxRetries, | ||
| maxRetries = _ref$maxRetries === undefined ? 3 : _ref$maxRetries; | ||
| _classCallCheck(this, MaxRetriesProcessor); | ||
| this._onIgnoredError_ = this._onIgnoredError_.bind(this); | ||
| this.processor = processor; | ||
| this.maxRetries = maxRetries; | ||
| } | ||
| _createClass(MaxRetriesProcessor, [{ | ||
| key: "process", | ||
| value: function process(notification, context, executionId) { | ||
| var _this = this; | ||
| return this.processor(notification, context, executionId).tap(function (it) { | ||
| return _this._onSuccess_(notification, it); | ||
| }).catch(function (err) { | ||
| if (_this._isIgnoredError_(err)) { | ||
| return _this._onIgnoredError_(notification, err); | ||
| } | ||
| if (_this._shouldRetry_(notification, err)) { | ||
| throw _this._sanitizeError_(err); | ||
| } | ||
| return _this._onMaxRetryExceeded_(notification, err); | ||
| }); | ||
| } | ||
| }, { | ||
| key: "_shouldRetry_", | ||
| value: function _shouldRetry_(_ref2, err) { | ||
| var _ref2$meta$dequeueCou = _ref2.meta.dequeueCount, | ||
| dequeueCount = _ref2$meta$dequeueCou === undefined ? 0 : _ref2$meta$dequeueCou; | ||
| return dequeueCount < this.maxRetries; | ||
| } | ||
| }, { | ||
| key: "_onSuccess_", | ||
| value: function _onSuccess_(notification, result) { | ||
| throw new Error("subclass responsability"); | ||
| } | ||
| }, { | ||
| key: "_sanitizeError_", | ||
| value: function _sanitizeError_(err) { | ||
| throw new Error("subclass responsability"); | ||
| } | ||
| }, { | ||
| key: "_onMaxRetryExceeded_", | ||
| value: function _onMaxRetryExceeded_(notification, err) { | ||
| throw new Error("subclass responsability"); | ||
| } | ||
| }, { | ||
| key: "_onIgnoredError_", | ||
| value: function _onIgnoredError_(notification, err) { | ||
| var _this2 = this; | ||
| return Promise.try(function () { | ||
| return _this2._onSuccess_(notification, err); | ||
| }).tap(function () { | ||
| throw err; | ||
| }); | ||
| } | ||
| }, { | ||
| key: "_isIgnoredError_", | ||
| value: function _isIgnoredError_(err) { | ||
| return err instanceof IgnoredError; | ||
| } | ||
| }]); | ||
| return MaxRetriesProcessor; | ||
| }(); | ||
| }).call(undefined); |
| "use strict"; | ||
| // Generated by CoffeeScript 2.7.0 | ||
| (function () { | ||
| var RequestProcessor, _, _normalizeHeaders, builderRequest; | ||
| _ = require("lodash"); | ||
| RequestProcessor = require("./request.processor"); | ||
| _normalizeHeaders = function _normalizeHeaders(headers) { | ||
| return _(headers).map(function (_ref) { | ||
| var Key = _ref.Key, | ||
| Value = _ref.Value; | ||
| return [Key, Value]; | ||
| }).fromPairs().value(); | ||
| }; | ||
| builderRequest = function builderRequest(apiUrl, fullResponse) { | ||
| return function (_ref2, context, executionId) { | ||
| var message = _ref2.message; | ||
| var Body, HeadersForRequest, JobId, Method, Resource, headers, json, url; | ||
| Resource = message.Resource; | ||
| Method = message.Method; | ||
| Body = message.Body; | ||
| HeadersForRequest = message.HeadersForRequest; | ||
| JobId = message.JobId; | ||
| json = (Body != null ? Body.length : void 0) > 0 ? JSON.parse(Body) : true; | ||
| headers = _normalizeHeaders(HeadersForRequest); | ||
| if (JobId) { | ||
| headers['x-producteca-event-id'] = JobId + "/" + executionId; | ||
| } | ||
| url = headers.Domain || apiUrl; | ||
| return { | ||
| url: "" + url + Resource, | ||
| method: Method, | ||
| headers: headers, | ||
| json: json, | ||
| resolveWithFullResponse: fullResponse | ||
| }; | ||
| }; | ||
| }; | ||
| module.exports = function (_ref3) { | ||
| var apiUrl = _ref3.apiUrl, | ||
| _ref3$fullResponse = _ref3.fullResponse, | ||
| fullResponse = _ref3$fullResponse === undefined ? false : _ref3$fullResponse, | ||
| silentErrors = _ref3.silentErrors, | ||
| nonRetryable = _ref3.nonRetryable; | ||
| return RequestProcessor(builderRequest(apiUrl, fullResponse), { silentErrors: silentErrors, nonRetryable: nonRetryable }); | ||
| }; | ||
| }).call(undefined); |
| "use strict"; | ||
| // Generated by CoffeeScript 2.7.0 | ||
| (function () { | ||
| var IgnoredError, MESSAGE_PROPERTIES, NonRetryableError, Promise, RequestError, StatusCodeError, _, __isIncludedInStatusesError, _safeParse, _type, errorConditions, httpStatus, request; | ||
| _ = require("lodash"); | ||
| NonRetryableError = require("../exceptions/non.retryable"); | ||
| IgnoredError = require("../exceptions/ignored.error"); | ||
| Promise = require("bluebird"); | ||
| request = require("request-promise"); | ||
| var _require = require("request-promise/errors"); | ||
| StatusCodeError = _require.StatusCodeError; | ||
| RequestError = _require.RequestError; | ||
| httpStatus = require("http").STATUS_CODES; | ||
| MESSAGE_PROPERTIES = ["reason", "error.error", "error.code", "code", "error"]; | ||
| _safeParse = function _safeParse(raw) { | ||
| if (_.isObject(raw)) { | ||
| return raw; | ||
| } else { | ||
| try { | ||
| return JSON.parse(raw); | ||
| } catch (error1) {} | ||
| } | ||
| }; | ||
| _type = function _type(statusCode, error) { | ||
| return _(MESSAGE_PROPERTIES).map(function (key) { | ||
| return _.get(error, key); | ||
| }).concat([_.toLower(httpStatus[statusCode])]).filter(_.isString).compact().head(); | ||
| }; | ||
| errorConditions = { | ||
| client: function client(it) { | ||
| return it >= 400 && it < 500; | ||
| }, | ||
| server: function server(it) { | ||
| return it >= 500; | ||
| } | ||
| }; | ||
| __isIncludedInStatusesError = function __isIncludedInStatusesError(conditions) { | ||
| return function (err) { | ||
| var statusCode; | ||
| statusCode = _.get(err, "detail.response.statusCode"); | ||
| return _(conditions).map(function (it) { | ||
| return _.get(errorConditions, it, _.partial(_.isEqual, it)); | ||
| }).some(function (condition) { | ||
| return condition(statusCode); | ||
| }); | ||
| }; | ||
| }; | ||
| module.exports = function (requestGenerator) { | ||
| var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, | ||
| _ref$silentErrors = _ref.silentErrors, | ||
| silentErrors = _ref$silentErrors === undefined ? [] : _ref$silentErrors, | ||
| _ref$nonRetryable = _ref.nonRetryable, | ||
| nonRetryable = _ref$nonRetryable === undefined ? [] : _ref$nonRetryable; | ||
| return function (notification, context, executionId) { | ||
| return Promise.method(requestGenerator)(notification, context, executionId).then(function (options) { | ||
| return request(options).promise().catch(RequestError, function (_ref2) { | ||
| var cause = _ref2.cause; | ||
| throw { | ||
| type: cause.code, | ||
| detail: cause | ||
| }; | ||
| }).catch(StatusCodeError, function (_ref3) { | ||
| var statusCode = _ref3.statusCode, | ||
| error = _ref3.error; | ||
| var safeError, type; | ||
| safeError = _safeParse(error); | ||
| type = _type(statusCode, safeError); | ||
| throw { | ||
| type: type, | ||
| message: _.get(safeError, "error.message") || _.get(safeError, "message") || type, | ||
| detail: { | ||
| response: { | ||
| statusCode: statusCode, | ||
| body: safeError | ||
| } | ||
| }, | ||
| tags: safeError != null ? safeError.tags : void 0 | ||
| }; | ||
| }).tapCatch(function (err) { | ||
| return _.defaultsDeep(err, { | ||
| type: "unknown", | ||
| message: "unknown", | ||
| detail: { | ||
| request: options | ||
| } | ||
| }); | ||
| }).catch(__isIncludedInStatusesError(silentErrors), function (err) { | ||
| throw new IgnoredError("An error has ocurred in that request but should be ignored", _.omit(err, "response")); | ||
| }).catch(__isIncludedInStatusesError(nonRetryable), function (err) { | ||
| throw new NonRetryableError("An error has ocurred in that request", _.omit(err, "response")); | ||
| }); | ||
| }); | ||
| }; | ||
| }; | ||
| }).call(undefined); |
| "use strict"; | ||
| // Generated by CoffeeScript 2.7.0 | ||
| (function () { | ||
| var MaxRetriesProcessor, RequestAsyncProcessor, _; | ||
| _ = require("lodash"); | ||
| RequestAsyncProcessor = require("./request.async.processor"); | ||
| MaxRetriesProcessor = require("./deadletter.processor"); | ||
| module.exports = function (args) { | ||
| var maxRetries, processor, withMaxRetries; | ||
| var _args$maxRetries = args.maxRetries; | ||
| maxRetries = _args$maxRetries === undefined ? 5 : _args$maxRetries; | ||
| processor = RequestAsyncProcessor(args); | ||
| withMaxRetries = new MaxRetriesProcessor({ processor: processor, maxRetries: maxRetries }); | ||
| return withMaxRetries.process.bind(withMaxRetries); | ||
| }; | ||
| }).call(undefined); |
| "use strict"; | ||
| var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }(); | ||
| // Generated by CoffeeScript 2.7.0 | ||
| (function () { | ||
| var NotificationsApi, OAuthApi, Promise, _, _companyId, _companyIdFromBasicToken, _headerValue, notificationsApi, retry, uuid; | ||
| _ = require("lodash"); | ||
| OAuthApi = require("../services/oAuthApi"); | ||
| NotificationsApi = require("../processors/job/notification.api"); | ||
| Promise = require("bluebird"); | ||
| retry = require("bluebird-retry"); | ||
| uuid = require("uuid/v4"); | ||
| notificationsApi = new NotificationsApi({}); | ||
| _companyIdFromBasicToken = function _companyIdFromBasicToken(token) { | ||
| var decoded; | ||
| decoded = Buffer.from(token, "base64").toString(); | ||
| return _.split(decoded, ":")[0]; | ||
| }; | ||
| _companyId = function _companyId(method, token) { | ||
| if (method !== "Basic") { | ||
| return new OAuthApi(token).scopes().get("companyId"); | ||
| } | ||
| return _companyIdFromBasicToken(token); | ||
| }; | ||
| _headerValue = function _headerValue(headers, key, defaultValue) { | ||
| var header; | ||
| header = _.find(headers, { | ||
| Key: key | ||
| }); | ||
| return _.get(header, "Value", defaultValue); | ||
| }; | ||
| module.exports = { | ||
| user: function user(_ref) { | ||
| var HeadersForRequest = _ref.message.HeadersForRequest; | ||
| var method, token; | ||
| var _headerValue$split = _headerValue(HeadersForRequest, "Authorization", "").split(" "); | ||
| var _headerValue$split2 = _slicedToArray(_headerValue$split, 2); | ||
| method = _headerValue$split2[0]; | ||
| token = _headerValue$split2[1]; | ||
| return _companyId(method, token); | ||
| }, | ||
| resource: function resource(_ref2, resourceGetter) { | ||
| var message = _ref2.message; | ||
| if (_.isFunction(resourceGetter)) { | ||
| return resourceGetter(message); | ||
| } else { | ||
| return _.get(message, "Resource"); | ||
| } | ||
| }, | ||
| monitoringCenterFields: function monitoringCenterFields(notification) { | ||
| var _this = this; | ||
| var __job, __scopes, fullToken, method, token; | ||
| fullToken = _headerValue(notification.message.HeadersForRequest, "Authorization", ""); | ||
| var _fullToken$split = fullToken.split(" "); | ||
| var _fullToken$split2 = _slicedToArray(_fullToken$split, 2); | ||
| method = _fullToken$split2[0]; | ||
| token = _fullToken$split2[1]; | ||
| __scopes = function __scopes() { | ||
| if (_(method.toLowerCase()).includes("bearer")) { | ||
| return retry(function () { | ||
| return new OAuthApi(token).scopes(); | ||
| }); | ||
| } | ||
| return Promise.resolve({ | ||
| id: null, | ||
| appId: null, | ||
| companyId: _companyIdFromBasicToken(token) | ||
| }); | ||
| }; | ||
| __job = function __job() { | ||
| if (notification.message.JobId && fullToken) { | ||
| return notificationsApi.fetchJob(notification.message.JobId, fullToken).catchReturn().then(function (it) { | ||
| return it || {}; | ||
| }); | ||
| } else { | ||
| return Promise.resolve({}); | ||
| } | ||
| }; | ||
| return Promise.props({ | ||
| scopes: __scopes(), | ||
| job: __job() | ||
| }).then(function (_ref3) { | ||
| var _ref3$scopes = _ref3.scopes, | ||
| id = _ref3$scopes.id, | ||
| companyId = _ref3$scopes.companyId, | ||
| appId = _ref3$scopes.appId, | ||
| _ref3$job = _ref3.job, | ||
| name = _ref3$job.name, | ||
| creationDate = _ref3$job.creationDate; | ||
| var eventId, headersWithoutAuth, jobCreationDate, messageInsertionTime, ref, ref1, ref2; | ||
| eventId = notification.message.JobId || _headerValue(notification.message.HeadersForRequest, "x-producteca-event-id", null) || _headerValue(notification.message.HeadersForRequest, "X-producteca-event-id", null) || (notification != null ? (ref = notification.meta) != null ? ref.messageId : void 0 : void 0) || uuid(); | ||
| if (creationDate) { | ||
| jobCreationDate = new Date(creationDate).getTime(); | ||
| } | ||
| if (notification != null ? (ref1 = notification.meta) != null ? ref1.insertionTime : void 0 : void 0) { | ||
| messageInsertionTime = new Date(notification != null ? (ref2 = notification.meta) != null ? ref2.insertionTime : void 0 : void 0).getTime(); | ||
| } | ||
| headersWithoutAuth = _.reject(notification.message.HeadersForRequest, function (_ref4) { | ||
| var Key = _ref4.Key; | ||
| return (Key != null ? Key.toLowerCase() : void 0) === 'authorization'; | ||
| }); | ||
| return Promise.props({ | ||
| eventType: 'http', | ||
| resource: _this.resource(notification), | ||
| companyId: companyId, | ||
| userId: id, | ||
| app: parseInt(appId), | ||
| job: name, | ||
| externalReference: null, | ||
| eventId: eventId, | ||
| eventTimestamp: jobCreationDate || messageInsertionTime, | ||
| parentEventId: null, | ||
| partialMessage: _.assign({}, notification.message, { | ||
| HeadersForRequest: headersWithoutAuth | ||
| }) | ||
| }); | ||
| }); | ||
| } | ||
| }; | ||
| }).call(undefined); |
| "use strict"; | ||
| // Generated by CoffeeScript 2.7.0 | ||
| (function () { | ||
| module.exports = { | ||
| MeliSender: require("./meli.sender"), | ||
| ProductecaSender: require("./producteca.sender"), | ||
| AsyncProductecaSender: require("./async.producteca.sender") | ||
| }; | ||
| }).call(undefined); |
| "use strict"; | ||
| // Generated by CoffeeScript 2.7.0 | ||
| (function () { | ||
| var Promise, UserIdTranslator, uuid; | ||
| uuid = require("uuid/v4"); | ||
| Promise = require("bluebird"); | ||
| UserIdTranslator = require("../services/userIdTranslator"); | ||
| module.exports = { | ||
| user: function user(_ref) { | ||
| var user_id = _ref.message.user_id; | ||
| return user_id; | ||
| }, | ||
| resource: function resource(_ref2) { | ||
| var _resource = _ref2.message.resource; | ||
| return _resource; | ||
| }, | ||
| monitoringCenterFields: function monitoringCenterFields(notification) { | ||
| var _this = this; | ||
| return new UserIdTranslator().translate(this.user(notification)).then(function (_ref3) { | ||
| var app = _ref3.app, | ||
| companyId = _ref3.companyId; | ||
| var ref, ref1, ref2; | ||
| return Promise.props({ | ||
| eventType: 'http', | ||
| resource: null, | ||
| app: app, | ||
| companyId: companyId, | ||
| userId: null, | ||
| externalReference: _this.resource(notification), | ||
| eventId: (notification != null ? (ref = notification.message) != null ? ref._id : void 0 : void 0) || uuid(), | ||
| eventTimestamp: (notification != null ? (ref1 = notification.meta) != null ? ref1.insertionTime : void 0 : void 0) ? new Date(notification != null ? (ref2 = notification.meta) != null ? ref2.insertionTime : void 0 : void 0).getTime() : void 0, | ||
| parentEventId: null | ||
| }); | ||
| }); | ||
| } | ||
| }; | ||
| }).call(undefined); |
| "use strict"; | ||
| // Generated by CoffeeScript 2.7.0 | ||
| (function () { | ||
| var Promise; | ||
| Promise = require("bluebird"); | ||
| module.exports = { | ||
| user: function user(_ref) { | ||
| var CompanyId = _ref.message.CompanyId; | ||
| return CompanyId; | ||
| }, | ||
| resource: function resource(_ref2) { | ||
| var ResourceId = _ref2.message.ResourceId; | ||
| return ResourceId; | ||
| }, | ||
| monitoringCenterFields: function monitoringCenterFields(notification) { | ||
| var ref, ref1, ref2, ref3, ref4, ref5, ref6, ref7; | ||
| return Promise.props({ | ||
| eventType: 'service-bus', | ||
| resource: this.resource(notification), | ||
| companyId: this.user(notification), | ||
| userId: (notification != null ? (ref = notification.message) != null ? ref.UserId : void 0 : void 0) || (notification != null ? (ref1 = notification.message) != null ? ref1.User : void 0 : void 0), | ||
| externalReference: null, | ||
| eventId: notification != null ? (ref2 = notification.message) != null ? ref2.EventId : void 0 : void 0, | ||
| eventTimestamp: (notification != null ? (ref3 = notification.meta) != null ? ref3.insertionTime : void 0 : void 0) || (notification != null ? (ref4 = notification.message) != null ? ref4.Sent : void 0 : void 0) ? new Date((notification != null ? (ref5 = notification.meta) != null ? ref5.insertionTime : void 0 : void 0) || (notification != null ? (ref6 = notification.message) != null ? ref6.Sent : void 0 : void 0)).getTime() : void 0, | ||
| parentEventId: notification != null ? (ref7 = notification.message) != null ? ref7.ParentEventId : void 0 : void 0 | ||
| }); | ||
| } | ||
| }; | ||
| }).call(undefined); |
| "use strict"; | ||
| var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); | ||
| function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } | ||
| // Generated by CoffeeScript 2.7.0 | ||
| (function () { | ||
| var NodeCache, OAUTH_API_URL, OAuthApi, Promise, request, translatedCache; | ||
| request = require("request-promise"); | ||
| Promise = require("bluebird"); | ||
| NodeCache = require("node-cache"); | ||
| translatedCache = new NodeCache({ | ||
| stdTTL: 0, | ||
| checkperiod: 0 | ||
| }); | ||
| OAUTH_API_URL = process.env.OAUTH_API_URL || "https://apps.producteca.com/oauth"; //TODO: Revisar que esta variable este seteada en todos lados con la interna, seguramente no | ||
| module.exports = OAuthApi = function () { | ||
| function OAuthApi(accessToken) { | ||
| _classCallCheck(this, OAuthApi); | ||
| this.scopes = this.scopes.bind(this); | ||
| this._scopes = this._scopes.bind(this); | ||
| this._doRequest = this._doRequest.bind(this); | ||
| this.accessToken = accessToken; | ||
| } | ||
| _createClass(OAuthApi, [{ | ||
| key: "scopes", | ||
| value: function scopes() { | ||
| var _this = this; | ||
| var cachedValue; | ||
| cachedValue = translatedCache.get(this.accessToken); | ||
| if (cachedValue) { | ||
| return Promise.resolve(cachedValue); | ||
| } | ||
| return this._scopes().tap(function (_ref) { | ||
| var id = _ref.id, | ||
| companyId = _ref.companyId, | ||
| appId = _ref.appId; | ||
| return translatedCache.set(_this.accessToken, { id: id, companyId: companyId, appId: appId }); | ||
| }); | ||
| } | ||
| }, { | ||
| key: "_scopes", | ||
| value: function _scopes() { | ||
| return this._doRequest("get", "/scopes", { | ||
| access_token: this.accessToken, | ||
| fromNotificationProcessor: true | ||
| }); | ||
| } | ||
| }, { | ||
| key: "_doRequest", | ||
| value: function _doRequest(verb, path) { | ||
| var qs = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; | ||
| var options; | ||
| options = { | ||
| url: OAUTH_API_URL + path, | ||
| qs: qs, | ||
| json: true | ||
| }; | ||
| return request[verb](options).promise(); | ||
| } | ||
| }]); | ||
| return OAuthApi; | ||
| }(); | ||
| }).call(undefined); |
| "use strict"; | ||
| // Generated by CoffeeScript 2.7.0 | ||
| (function () { | ||
| var Promise, redis; | ||
| Promise = require("bluebird"); | ||
| redis = require("redis"); | ||
| Promise.promisifyAll(redis.RedisClient.prototype); | ||
| Promise.promisifyAll(redis.Multi.prototype); | ||
| module.exports = redis; | ||
| }).call(undefined); |
| "use strict"; | ||
| var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); | ||
| function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } | ||
| // Generated by CoffeeScript 2.7.0 | ||
| (function () { | ||
| var MERCADOLIBRE_API_CORE_URL, MERCADOLIBRE_API_MASTER_TOKEN, NodeCache, Promise, UserIdTranslator, _, request, retry, translatedCache; | ||
| _ = require("lodash"); | ||
| Promise = require("bluebird"); | ||
| request = require("request-promise"); | ||
| retry = require("bluebird-retry"); | ||
| NodeCache = require("node-cache"); | ||
| translatedCache = new NodeCache({ | ||
| stdTTL: 0, | ||
| checkperiod: 0 | ||
| }); | ||
| MERCADOLIBRE_API_CORE_URL = process.env.MERCADOLIBRE_API_CORE_URL || "https://apps.producteca.com/mercadolibre-api"; | ||
| MERCADOLIBRE_API_MASTER_TOKEN = process.env.MERCADOLIBRE_API_MASTER_TOKEN; | ||
| module.exports = UserIdTranslator = function () { | ||
| function UserIdTranslator() { | ||
| _classCallCheck(this, UserIdTranslator); | ||
| this.translate = this.translate.bind(this); | ||
| this.getCompanyId = this.getCompanyId.bind(this); | ||
| this._setInCache = this._setInCache.bind(this); | ||
| this._translateUserId = this._translateUserId.bind(this); | ||
| this.translatedCache = translatedCache; | ||
| this.translate = this.translate.bind(this); | ||
| } | ||
| _createClass(UserIdTranslator, [{ | ||
| key: "translate", | ||
| value: function translate(userId) { | ||
| if (!MERCADOLIBRE_API_MASTER_TOKEN) { | ||
| return Promise.resolve(null); | ||
| } | ||
| return this.getCompanyId(userId); | ||
| } | ||
| }, { | ||
| key: "getCompanyId", | ||
| value: function getCompanyId(userId) { | ||
| var companyId; | ||
| companyId = this.translatedCache.get(userId); | ||
| if (companyId) { | ||
| return Promise.resolve(companyId); | ||
| } else { | ||
| return this._translateUserId(userId); | ||
| } | ||
| } | ||
| }, { | ||
| key: "_setInCache", | ||
| value: function _setInCache(userId, userInfo) { | ||
| var success; | ||
| success = this.translatedCache.set(userId, userInfo); | ||
| if (success) { | ||
| console.log("UserId %s ===> %s was stored in cache successfully", userId, JSON.stringify(userInfo)); | ||
| } | ||
| return Promise.resolve(success); | ||
| } | ||
| }, { | ||
| key: "_translateUserId", | ||
| value: function _translateUserId(userId) { | ||
| var _this = this; | ||
| console.log("Making request to translate", userId); | ||
| return retry(function () { | ||
| return request.get({ | ||
| url: MERCADOLIBRE_API_CORE_URL + "/users/me", | ||
| json: true, | ||
| qs: { | ||
| authenticationType: "mercadolibre" | ||
| }, | ||
| auth: { | ||
| user: "" + userId, | ||
| password: MERCADOLIBRE_API_MASTER_TOKEN | ||
| } | ||
| }).promise(); | ||
| }).then(function (userInformation) { | ||
| return { | ||
| app: userInformation.app, | ||
| companyId: userInformation.tenantId || userInformation.companyId | ||
| }; | ||
| }).tap(function (_ref) { | ||
| var companyId = _ref.companyId; | ||
| return console.log("UserId translated %s ==> %s", userId, companyId); | ||
| }).catch(function (reason) { | ||
| if (_.includes([401, 500], reason.statusCode)) { | ||
| return "Unknown"; | ||
| } | ||
| throw reason; | ||
| }).tap(function (companyId) { | ||
| return _this._setInCache(userId, companyId); | ||
| }); | ||
| } | ||
| }]); | ||
| return UserIdTranslator; | ||
| }(); | ||
| }).call(undefined); |
| "use strict"; | ||
| // Generated by CoffeeScript 2.7.0 | ||
| (function () { | ||
| var _; | ||
| _ = require("lodash"); | ||
| module.exports = { | ||
| newNotification: function newNotification(_ref) { | ||
| var context = _ref.context, | ||
| message = _ref.message; | ||
| return { | ||
| message: !_.isObject(message.Message) ? JSON.parse(message.Message) : message.Message, | ||
| meta: { | ||
| insertionTime: _.get(message, "Timestamp"), | ||
| messageId: _.get(message, "MessageId"), | ||
| properties: _.mapValues(_.get(message, "MessageAttributes"), function (_ref2) { | ||
| var Type = _ref2.Type, | ||
| Value = _ref2.Value; | ||
| if (_.includes(Type, 'Array')) { | ||
| return JSON.parse(Value); | ||
| } else if (Type === 'Number') { | ||
| return Number(Value); | ||
| } else { | ||
| return Value; | ||
| } | ||
| }), | ||
| dequeueCount: _.get(context, "bindingData.approximateReceiveCount") | ||
| }, | ||
| type: "sqs" | ||
| }; | ||
| } | ||
| }; | ||
| }).call(undefined); |
| "use strict"; | ||
| // Generated by CoffeeScript 2.7.0 | ||
| (function () { | ||
| module.exports = { | ||
| AwsSQSSource: require("./aws.sqs.source"), | ||
| ServiceBusSource: require("./service.bus.source"), | ||
| QueueSource: require("./queue.source"), | ||
| TableSource: require("./table.source"), | ||
| UnknownSource: require("./unknown.source") | ||
| }; | ||
| }).call(undefined); |
| "use strict"; | ||
| // Generated by CoffeeScript 2.7.0 | ||
| (function () { | ||
| module.exports = { | ||
| newNotification: function newNotification(_ref) { | ||
| var _ref$context$bindingD = _ref.context.bindingData, | ||
| insertionTime = _ref$context$bindingD.insertionTime, | ||
| dequeueCount = _ref$context$bindingD.dequeueCount, | ||
| messageId = _ref$context$bindingD.messageId, | ||
| Message = _ref$context$bindingD.Message, | ||
| MessageId = _ref$context$bindingD.MessageId, | ||
| message = _ref.message; | ||
| return { | ||
| message: message, | ||
| meta: { | ||
| insertionTime: insertionTime, | ||
| dequeueCount: dequeueCount, | ||
| messageId: messageId || MessageId || Message | ||
| }, | ||
| type: "as" | ||
| }; | ||
| } | ||
| }; | ||
| }).call(undefined); |
| "use strict"; | ||
| // Generated by CoffeeScript 2.7.0 | ||
| (function () { | ||
| var _; | ||
| _ = require("lodash"); | ||
| module.exports = { | ||
| newNotification: function newNotification(_ref) { | ||
| var bindingData = _ref.context.bindingData, | ||
| message = _ref.message; | ||
| return { | ||
| message: _.omit(message, "Sent"), | ||
| meta: { | ||
| messageId: bindingData.messageId, | ||
| insertionTime: bindingData.enqueuedTimeUtc, | ||
| dequeueCount: bindingData.deliveryCount, | ||
| properties: bindingData.userProperties || bindingData.properties | ||
| }, | ||
| type: "sb" | ||
| }; | ||
| } | ||
| }; | ||
| }).call(undefined); |
| "use strict"; | ||
| // Generated by CoffeeScript 2.7.0 | ||
| (function () { | ||
| var _; | ||
| _ = require("lodash"); | ||
| module.exports = function (OtherSource) { | ||
| return { | ||
| newNotification: function newNotification(_ref) { | ||
| var notification = _ref.message.notification; | ||
| return _.merge(notification, { | ||
| type: "table" | ||
| }); | ||
| } | ||
| }; | ||
| }; | ||
| }).call(undefined); |
| "use strict"; | ||
| // Generated by CoffeeScript 2.7.0 | ||
| (function () { | ||
| module.exports = { | ||
| newNotification: function newNotification(_ref) { | ||
| var message = _ref.message; | ||
| return { | ||
| message: message, | ||
| type: "uk" | ||
| }; | ||
| } | ||
| }; | ||
| }).call(undefined); |
| "use strict"; | ||
| // Generated by CoffeeScript 2.7.0 | ||
| (function () { | ||
| var _, notification, redis; | ||
| _ = require("lodash"); | ||
| redis = { | ||
| host: "127.0.0.1", | ||
| port: "1234", | ||
| db: "3", | ||
| auth: "unaCadenaDeAuth" | ||
| }; | ||
| notification = { | ||
| type: "sb", | ||
| dequeueCount: 1, | ||
| message: { | ||
| CompanyId: 123, | ||
| ResourceId: 456 | ||
| }, | ||
| meta: { | ||
| insertionTime: "Sat, 05 Nov 2016 16:44:43 GMT" | ||
| } | ||
| }; | ||
| module.exports = { redis: redis, notification: notification }; | ||
| }).call(undefined); |
| "use strict"; | ||
| var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); | ||
| function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } | ||
| // Generated by CoffeeScript 2.7.0 | ||
| (function () { | ||
| var MockRedis, MockRedisClient, Promise, _, proxyquire, sinon, stub; | ||
| proxyquire = require("proxyquire"); | ||
| Promise = require("bluebird"); | ||
| sinon = require("sinon"); | ||
| _ = require("lodash"); | ||
| MockRedisClient = function () { | ||
| function MockRedisClient() { | ||
| _classCallCheck(this, MockRedisClient); | ||
| this.refreshSpies = this.refreshSpies.bind(this); | ||
| this.refreshSpies(); | ||
| } | ||
| _createClass(MockRedisClient, [{ | ||
| key: "auth", | ||
| value: function auth() {} | ||
| }, { | ||
| key: "refreshSpies", | ||
| value: function refreshSpies() { | ||
| return this.spies = { | ||
| publishAsync: sinon.spy() | ||
| }; | ||
| } | ||
| }, { | ||
| key: "publishAsync", | ||
| value: function publishAsync(key, value) { | ||
| return Promise.resolve(this.spies.publishAsync(key, value)); | ||
| } | ||
| }]); | ||
| return MockRedisClient; | ||
| }(); | ||
| stub = { | ||
| "../services/redis": MockRedis = function () { | ||
| function MockRedis() { | ||
| _classCallCheck(this, MockRedis); | ||
| } | ||
| _createClass(MockRedis, null, [{ | ||
| key: "createClient", | ||
| value: function createClient() { | ||
| return new MockRedisClient(); | ||
| } | ||
| }]); | ||
| return MockRedis; | ||
| }() | ||
| }; | ||
| proxyquire("../observers/redis.observer", stub); | ||
| }).call(undefined); |
+7
-0
@@ -0,1 +1,8 @@ | ||
| ## [5.0.3](https://github.com/Parsimotion/notification-processor/compare/v5.0.2...v5.0.3) (2025-07-24) | ||
| ### Bug Fixes | ||
| * **release:** download build output ([28b6978](https://github.com/Parsimotion/notification-processor/commit/28b69781cef0bbc5983e15d5c184b214f5df6824)) | ||
| ## [5.0.2](https://github.com/Parsimotion/notification-processor/compare/v5.0.1...v5.0.2) (2025-07-24) | ||
@@ -2,0 +9,0 @@ |
+1
-1
| { | ||
| "name": "notification-processor", | ||
| "version": "5.0.2", | ||
| "version": "5.0.3", | ||
| "description": "notification-processor", | ||
@@ -5,0 +5,0 @@ "main": "index.js", |
Major refactor
Supply chain riskPackage has recently undergone a major refactor. It may be unstable or indicate significant internal changes. Use caution when updating to versions that include significant changes.
Found 1 instance in 1 package
Network access
Supply chain riskThis module accesses the network.
Found 1 instance in 1 package
Environment variable access
Supply chain riskPackage accesses environment variables, which may be a sign of credential stuffing or data theft.
Found 18 instances in 1 package
AI-detected potential code anomaly
Supply chain riskAI has identified unusual behaviors that may pose a security risk.
Found 1 instance in 1 package
Long strings
Supply chain riskContains long string literals, which may be a sign of obfuscated or packed code.
Found 1 instance in 1 package
URL strings
Supply chain riskPackage contains fragments of external URLs or IP addresses, which the package may be accessing at runtime.
Found 1 instance in 1 package
Deprecated
MaintenanceThe maintainer of the package marked it as deprecated. This could indicate that a single version should not be used, or that the package is no longer maintained and any new vulnerabilities will not be fixed.
Found 1 instance in 1 package
Empty package
Supply chain riskPackage does not contain any code. It may be removed, is name squatting, or the result of a faulty package publish.
Found 1 instance in 1 package
Major refactor
Supply chain riskPackage has recently undergone a major refactor. It may be unstable or indicate significant internal changes. Use caution when updating to versions that include significant changes.
Found 1 instance in 1 package
88660
1646.65%40
471.43%1919
Infinity%0
-100%21
Infinity%