@citrineos/util
Version:
The OCPP util module which supplies helpful utilities like cache and queue connectors, etc.
133 lines • 5.33 kB
JavaScript
;
// Copyright (c) 2023 S44, LLC
// Copyright Contributors to the CitrineOS Project
//
// SPDX-License-Identifier: Apache 2.0
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.KafkaSender = void 0;
const base_1 = require("@citrineos/base");
const kafkajs_1 = require("kafkajs");
/**
* Implementation of a {@link IMessageSender} using Kafka as the underlying transport.
*/
class KafkaSender extends base_1.AbstractMessageSender {
/**
* Constructor
*
* @param topicPrefix Custom topic prefix, defaults to "ocpp"
*/
constructor(config, logger) {
var _a, _b, _c, _d, _e;
super(config, logger);
this._client = new kafkajs_1.Kafka({
brokers: ((_a = config.util.messageBroker.kafka) === null || _a === void 0 ? void 0 : _a.brokers) || [],
ssl: true,
sasl: {
mechanism: 'plain',
username: ((_b = config.util.messageBroker.kafka) === null || _b === void 0 ? void 0 : _b.sasl.username) || '',
password: ((_c = config.util.messageBroker.kafka) === null || _c === void 0 ? void 0 : _c.sasl.password) || '',
},
});
this._producers = new Array();
this._topicName = `${(_d = this._config.util.messageBroker.kafka) === null || _d === void 0 ? void 0 : _d.topicPrefix}-${(_e = this._config.util.messageBroker.kafka) === null || _e === void 0 ? void 0 : _e.topicName}`;
const admin = this._client.admin();
admin
.connect()
.then(() => admin.listTopics())
.then((topics) => {
if (!topics || topics.filter((topic) => topic === this._topicName).length === 0) {
this._client
.admin()
.createTopics({ topics: [{ topic: this._topicName }] })
.then(() => {
this._logger.debug(`Topic ${this._topicName} created.`);
})
.catch((error) => {
this._logger.error('Failed to create topic', error);
});
}
})
.then(() => admin.disconnect())
.catch((error) => {
this._logger.error('Failed to connect to Kafka', error);
});
}
/**
* Convenience method to send a request message.
*
* @param message The {@link IMessage} to send
* @param payload The payload to send
* @returns
*/
sendRequest(message, payload) {
return this.send(message, payload, base_1.MessageState.Request);
}
/**
* Convenience method to send a confirmation message.
* @param message The {@link IMessage} to send
* @param payload The payload to send
* @returns
*/
sendResponse(message, payload) {
return this.send(message, payload, base_1.MessageState.Response);
}
/**
* Publishes the given message to kafka.
*
* @param message The {@link IMessage} to publish
* @param payload The payload to within the {@link IMessage}
* @param state The {@link MessageState} of the {@link IMessage}
* @returns
*/
send(message, payload, state) {
if (payload) {
message.payload = payload;
}
if (state) {
message.state = state;
}
if (!message.state) {
throw new Error('Message state must be set');
}
if (!message.payload) {
throw new Error('Message payload must be set');
}
this._logger.debug(`Publishing to ${this._topicName}:`, message);
const producer = this._client.producer();
return producer
.connect()
.then(() => producer.send({
topic: this._topicName,
messages: [
{
headers: Object.assign({ origin: message.origin.toString(), eventGroup: message.eventGroup.toString(), action: message.action.toString(), state: message.state.toString() }, message.context),
value: JSON.stringify(message),
},
],
}))
.then(() => this._producers.push(producer))
.then((result) => ({ success: true, result }))
.catch((error) => ({ success: false, error }));
}
/**
* Interface implementation
*/
shutdown() {
return __awaiter(this, void 0, void 0, function* () {
for (const producer of this._producers) {
yield producer.disconnect();
}
});
}
}
exports.KafkaSender = KafkaSender;
//# sourceMappingURL=sender.js.map