419adea234
* Create middleware and service for pubsub metrics * Use pubsub middleware for all request * Replace isEnabled with isDisabled to avoid negation * Use new headers names * Add acceptance and unit tests * Remove commented log calls * Remove only filters in tests Remove typo * Refactor service to ease integration test * Fix interaction with query controller * Use middleware at api-router and test all controllers * Rename user middleware function * Use sinon latest version * Create middleware and service for pubsub metrics * Use pubsub middleware for all request * Replace isEnabled with isDisabled to avoid negation * Use new headers names * Add acceptance and unit tests * Remove commented log calls * Remove only filters in tests Remove typo * Refactor service to ease integration test * Fix interaction with query controller * Use middleware at api-router and test all controllers * Rename user middleware function * Use sinon latest version * Fix tests * Fix typos * Checks if pubsub config exists to enable the service * Fix typo * Normalize headers values for pubsub * Trim fields when normalizing * Trim fields when normalizing
67 lines
1.6 KiB
JavaScript
67 lines
1.6 KiB
JavaScript
'use strict';
|
|
|
|
const { PubSub } = require('@google-cloud/pubsub');
|
|
|
|
/**
|
|
* PubSubMetricsService
|
|
*/
|
|
class PubSubMetricsService {
|
|
static build () {
|
|
if (!global.settings.pubSubMetrics || !global.settings.pubSubMetrics.enabled) {
|
|
return new PubSubMetricsService(undefined, false);
|
|
}
|
|
|
|
const pubsub = PubSubMetricsService.createPubSub();
|
|
|
|
return new PubSubMetricsService(pubsub, true);
|
|
}
|
|
|
|
static createPubSub () {
|
|
const projectId = global.settings.pubSubMetrics.project_id;
|
|
const credentials = global.settings.pubSubMetrics.credentials;
|
|
const config = {};
|
|
|
|
if (projectId) {
|
|
config.projectId = projectId;
|
|
}
|
|
if (credentials) {
|
|
config.keyFilename = credentials;
|
|
}
|
|
return new PubSub(config);
|
|
}
|
|
|
|
constructor (pubSub, enabled) {
|
|
this.pubsub = pubSub;
|
|
this.enabled = enabled;
|
|
}
|
|
|
|
isEnabled () {
|
|
return this.enabled;
|
|
}
|
|
|
|
_getTopic () {
|
|
const topicName = global.settings.pubSubMetrics.topic;
|
|
|
|
return this.pubsub.topic(topicName);
|
|
}
|
|
|
|
sendEvent (event, attributes) {
|
|
if (!this.enabled) {
|
|
return;
|
|
}
|
|
|
|
const data = Buffer.from(event);
|
|
const topic = this._getTopic();
|
|
|
|
topic.publish(data, attributes)
|
|
.then(() => {
|
|
console.log(`PubSubTracker: event '${event}' published to '${topic.name}'`);
|
|
})
|
|
.catch((error) => {
|
|
console.error(`ERROR: pubsub middleware failed to publish event '${event}': ${error.message}`);
|
|
});
|
|
}
|
|
}
|
|
|
|
module.exports = PubSubMetricsService;
|