@gravityai-dev/gravity-server
Version:
Integration SDK for the Gravity AI orchestration platform - Connect any AI platform in minutes
81 lines • 2.75 kB
JavaScript
/**
* Simple Event Bus for Gravity AI
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.EventBus = void 0;
const RedisManager_1 = require("../RedisManager");
const Publisher_1 = require("./Publisher");
class EventBus {
constructor(options, serviceId) {
this.options = options;
this.serviceId = serviceId;
this.handlers = new Map();
this.publisher = new Publisher_1.Publisher(options, serviceId);
this.subscriber = (0, RedisManager_1.getPubSubConnection)(options);
this.setupSubscriber();
}
static fromRedisConfig(host, port, password, serviceId, username, db) {
const options = {
host,
port,
password,
username,
db: db || 0,
};
return new EventBus(options, serviceId);
}
static fromCredentials(host, port, password, serviceId) {
return EventBus.fromRedisConfig(host, port, password, serviceId);
}
setupSubscriber() {
this.subscriber.on("message", (channel, message) => {
const handlers = this.handlers.get(channel);
if (!handlers || handlers.size === 0)
return;
try {
const event = JSON.parse(message);
handlers.forEach(handler => {
try {
handler(event);
}
catch (error) {
console.error(`[EventBus] Handler error on channel ${channel}:`, error);
}
});
}
catch (error) {
console.error(`[EventBus] Failed to parse message on channel ${channel}:`, error);
}
});
}
async publish(channel, payload) {
// Use the event channel pattern from Publisher
await this.publisher.publishEvent(channel, payload);
}
async subscribe(channel, handler) {
if (!this.handlers.has(channel)) {
this.handlers.set(channel, new Set());
await this.subscriber.subscribe(channel);
}
this.handlers.get(channel).add(handler);
return async () => {
const handlers = this.handlers.get(channel);
if (!handlers)
return;
handlers.delete(handler);
if (handlers.size === 0) {
this.handlers.delete(channel);
await this.subscriber.unsubscribe(channel);
}
};
}
async disconnect() {
await Promise.all([
this.publisher.disconnect(),
this.subscriber.quit()
]);
}
}
exports.EventBus = EventBus;
//# sourceMappingURL=SimpleEventBus.js.map
;