Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
feat: implemented centralized bus service
=52bf4daa9a2e
diff --git a/backend/src/@types/fastify.d.ts b/backend/src/@types/fastify.d.tsindex 5932356ff0..944099e96e 100644--- a/backend/src/@types/fastify.d.ts+++ b/backend/src/@types/fastify.d.ts@@ -17,6 +17,7 @@ import { TDynamicSecretServiceFactory } from "@app/ee/services/dynamic-secret/dyimport { TDynamicSecretLeaseServiceFactory } from "@app/ee/services/dynamic-secret-lease/dynamic-secret-lease-types";import { TEventBusService } from "@app/ee/services/event/event-bus-service";import { TServerSentEventsService } from "@app/ee/services/event/event-sse-service";+import { TEventBusService as TInternalEventBusService } from "@app/ee/services/event-bus";import { TExternalKmsServiceFactory } from "@app/ee/services/external-kms/external-kms-service";import { TGatewayServiceFactory } from "@app/ee/services/gateway/gateway-service";import { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2-service";@@ -352,6 +353,7 @@ declare module "fastify" {pkiTemplate: TPkiTemplatesServiceFactory;reminder: TReminderServiceFactory;bus: TEventBusService;+ eventBus: TInternalEventBusService;sse: TServerSentEventsService;identityAuthTemplate: TIdentityAuthTemplateServiceFactory;notification: TNotificationServiceFactory;diff --git a/backend/src/ee/services/event-bus/event-bus-service.ts b/backend/src/ee/services/event-bus/event-bus-service.tsnew file mode 100644index 0000000000..54a0f0f73b--- /dev/null+++ b/backend/src/ee/services/event-bus/event-bus-service.ts@@ -0,0 +1,105 @@+import { Cluster, Redis } from "ioredis";+import { nanoid } from "nanoid";++import { logger } from "@app/lib/logger";++import {+ EventBusServiceEvents,+ EventBusTopicName,+ TEventBusEvent,+ TEventBusSubscriber,+ TEventBusUnsubscribe+} from "./event-bus-types";+import { createMemoryBus, TMemoryBus } from "./memory-bus";+import { createRedisBus, TRedisBus } from "./redis-bus";++type TEventBusServiceFactoryDep = {+ redis: Redis | Cluster;+};++export const eventBusServiceFactory = ({ redis }: TEventBusServiceFactoryDep) => {+ // Generate unique container ID at startup+ const containerId = `container-${nanoid()}`;++ // Create memory bus for local event delivery+ const memoryBus: TMemoryBus = createMemoryBus();++ // Create Redis bus for inter-container communication+ const redisBus: TRedisBus = createRedisBus(redis, EventBusTopicName.CoreServers);++ /**+ * Initialize the event bus+ * - Sets up Redis subscription+ * - Bridges Redis events to memory bus (excluding events from this container)+ */+ const init = async (): Promise<void> => {+ // Set up handler to bridge Redis events to memory bus+ redisBus.onMessage((event) => {+ // Skip events that originated from this container (already delivered locally)+ if (event.sourceContainer === containerId) {+ return;+ }+ // Forward event to memory bus for local subscribers+ memoryBus.emit(event);+ });++ await redisBus.init();+ logger.info({ containerId }, "Event bus initialized");+ };++ /**+ * Publish an event to all containers+ * - Immediately delivers to local subscribers via memory bus+ * - Broadcasts to other containers via Redis+ */+ const publish = async <T extends Record<string, unknown>>(type: EventBusServiceEvents, payload: T): Promise<void> => {+ const event: TEventBusEvent = {+ type,+ timestamp: new Date().toISOString(),+ sourceContainer: containerId,+ payload+ };++ // Emit locally first for immediate delivery to local subscribers+ memoryBus.emit(event);++ // Then broadcast to other containers via Redis+ await redisBus.publish(event);+ };++ /**+ * Subscribe to events of a specific type+ * Receives events from both local publishers and other containers+ * @returns Unsubscribe function+ */+ const subscribe = (type: EventBusServiceEvents, callback: TEventBusSubscriber): TEventBusUnsubscribe => {+ return memoryBus.subscribe(type, callback);+ };++ /**+ * Subscribe to ALL events (useful for debugging/logging)+ * @returns Unsubscribe function+ */+ const subscribeAll = (callback: TEventBusSubscriber): TEventBusUnsubscribe => {+ return memoryBus.subscribeAll(callback);+ };++ /**+ * Close the event bus and cleanup resources+ */+ const close = async (): Promise<void> => {+ await redisBus.close();+ memoryBus.removeAllListeners();+ logger.info({ containerId }, "Event bus closed");+ };++ return {+ init,+ publish,+ subscribe,+ subscribeAll,+ close+ };+};++export type TEventBusService = ReturnType<typeof eventBusServiceFactory>;diff --git a/backend/src/ee/services/event-bus/event-bus-types.ts b/backend/src/ee/services/event-bus/event-bus-types.tsnew file mode 100644index 0000000000..6c0d662511--- /dev/null+++ b/backend/src/ee/services/event-bus/event-bus-types.ts@@ -0,0 +1,30 @@+import { z } from "zod";++// Topic names for Redis pub/sub channels+export enum EventBusTopicName {+ CoreServers = "infisical::core-servers"+}++// Event types that can be published/subscribed+export enum EventBusServiceEvents {+ SecretCreated = "secret.created",+ SecretUpdated = "secret.updated",+ SecretDeleted = "secret.deleted",+ SecretImportMutation = "secret.import-mutation"+}++// Base event schema - all events must have these fields+export const EventBusSchema = z.object({+ type: z.nativeEnum(EventBusServiceEvents),+ timestamp: z.string().datetime(),+ sourceContainer: z.string(),+ payload: z.record(z.unknown())+});++export type TEventBusEvent = z.infer<typeof EventBusSchema>;++// Subscriber callback type+export type TEventBusSubscriber = (event: TEventBusEvent) => void | Promise<void>;++// Unsubscribe function type+export type TEventBusUnsubscribe = () => void;diff --git a/backend/src/ee/services/event-bus/index.ts b/backend/src/ee/services/event-bus/index.tsnew file mode 100644index 0000000000..e2e14f87d8--- /dev/null+++ b/backend/src/ee/services/event-bus/index.ts@@ -0,0 +1,8 @@+export { eventBusServiceFactory, TEventBusService } from "./event-bus-service";+export {+ EventBusServiceEvents,+ EventBusTopicName,+ TEventBusEvent,+ TEventBusSubscriber,+ TEventBusUnsubscribe+} from "./event-bus-types";diff --git a/backend/src/ee/services/event-bus/memory-bus.ts b/backend/src/ee/services/event-bus/memory-bus.tsnew file mode 100644index 0000000000..c363ce49d1--- /dev/null+++ b/backend/src/ee/services/event-bus/memory-bus.ts@@ -0,0 +1,89 @@+import { EventEmitter } from "events";++import { logger } from "@app/lib/logger";++import { EventBusServiceEvents, TEventBusEvent, TEventBusSubscriber, TEventBusUnsubscribe } from "./event-bus-types";++const ALL_EVENTS_CHANNEL = "__all__";++export const createMemoryBus = () => {+ const emitter = new EventEmitter();+ // Increase max listeners to avoid warnings with many subscribers+ emitter.setMaxListeners(100);++ /**+ * Emit an event to all subscribers of that event type+ * Also emits to the ALL_EVENTS_CHANNEL for global subscribers+ */+ const emit = (event: TEventBusEvent): void => {+ emitter.emit(event.type, event);+ emitter.emit(ALL_EVENTS_CHANNEL, event);+ };++ /**+ * Subscribe to events of a specific type+ * @returns Unsubscribe function+ */+ const subscribe = (type: EventBusServiceEvents, callback: TEventBusSubscriber): TEventBusUnsubscribe => {+ const wrappedCallback = (event: TEventBusEvent) => {+ try {+ const result = callback(event);+ // Handle async callbacks - log errors but don't throw+ if (result instanceof Promise) {+ result.catch((error) => {+ logger.error(error, `Error in event bus subscriber for event type: ${type}`);+ });+ }+ } catch (error) {+ logger.error(error, `Error in event bus subscriber for event type: ${type}`);+ }+ };++ emitter.on(type, wrappedCallback);++ return () => {+ emitter.off(type, wrappedCallback);+ };+ };++ /**+ * Subscribe to ALL events (useful for debugging/logging)+ * @returns Unsubscribe function+ */+ const subscribeAll = (callback: TEventBusSubscriber): TEventBusUnsubscribe => {+ const wrappedCallback = (event: TEventBusEvent) => {+ try {+ const result = callback(event);+ if (result instanceof Promise) {+ result.catch((error) => {+ logger.error(error, "Error in event bus global subscriber");+ });+ }+ } catch (error) {+ logger.error(error, "Error in event bus global subscriber");+ }+ };++ emitter.on(ALL_EVENTS_CHANNEL, wrappedCallback);++ return () => {+ emitter.off(ALL_EVENTS_CHANNEL, wrappedCallback);+ };+ };++ /**+ * Remove all listeners from the memory bus+ */+ const removeAllListeners = (): void => {+ emitter.removeAllListeners();+ };++ return {+ emit,+ subscribe,+ subscribeAll,+ removeAllListeners+ };+};++export type TMemoryBus = ReturnType<typeof createMemoryBus>;diff --git a/backend/src/ee/services/event-bus/redis-bus.ts b/backend/src/ee/services/event-bus/redis-bus.tsnew file mode 100644index 0000000000..7a0e706757--- /dev/null+++ b/backend/src/ee/services/event-bus/redis-bus.ts@@ -0,0 +1,91 @@+import { Cluster, Redis } from "ioredis";++import { logger } from "@app/lib/logger";++import { EventBusSchema, EventBusTopicName, TEventBusEvent } from "./event-bus-types";++export type TRedisBusOnMessage = (event: TEventBusEvent) => void;++export const createRedisBus = (redis: Redis | Cluster, topic: EventBusTopicName) => {+ // Duplicate the redis connection for pub/sub+ // Redis doesn't allow a single connection to both publish and subscribe+ const publisher = redis.duplicate();+ const subscriber = publisher.duplicate();++ let messageHandler: TRedisBusOnMessage | null = null;++ /**+ * Initialize the Redis bus by subscribing to the topic+ */+ const init = async (): Promise<void> => {+ subscriber.on("error", (error) => {+ logger.error(error, "Event bus Redis subscriber error");+ });++ publisher.on("error", (error) => {+ logger.error(error, "Event bus Redis publisher error");+ });++ subscriber.on("message", (channel: string, message: string) => {+ if (channel !== topic || !messageHandler) return;++ try {+ const parsed = JSON.parse(message);+ const validated = EventBusSchema.safeParse(parsed);++ if (!validated.success) {+ logger.error(+ { error: validated.error, message },+ `Invalid event received on channel ${channel}`+ );+ return;+ }++ messageHandler(validated.data);+ } catch (error) {+ logger.error(error, `Error parsing event from channel ${channel}`);+ }+ });++ await subscriber.subscribe(topic);+ logger.info({ topic }, "Event bus subscribed to Redis topic");+ };++ /**+ * Set the message handler for incoming events+ */+ const onMessage = (handler: TRedisBusOnMessage): void => {+ messageHandler = handler;+ };++ /**+ * Publish an event to the Redis channel+ */+ const publish = async (event: TEventBusEvent): Promise<void> => {+ const json = JSON.stringify(event);+ await publisher.publish(topic, json);+ };++ /**+ * Close the Redis connections+ */+ const close = async (): Promise<void> => {+ try {+ await subscriber.unsubscribe(topic);+ await publisher.quit();+ await subscriber.quit();+ logger.info({ topic }, "Event bus Redis connections closed");+ } catch (error) {+ logger.error(error, "Error closing event bus Redis connections");+ }+ };++ return {+ init,+ onMessage,+ publish,+ close+ };+};++export type TRedisBus = ReturnType<typeof createRedisBus>;diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.tsindex 550b9c6374..8d4a18aa5c 100644--- a/backend/src/server/routes/index.ts+++ b/backend/src/server/routes/index.ts@@ -49,6 +49,7 @@ import { dynamicSecretLeaseQueueServiceFactory } from "@app/ee/services/dynamic-import { dynamicSecretLeaseServiceFactory } from "@app/ee/services/dynamic-secret-lease/dynamic-secret-lease-service";import { eventBusFactory } from "@app/ee/services/event/event-bus-service";import { sseServiceFactory } from "@app/ee/services/event/event-sse-service";+import { eventBusServiceFactory } from "@app/ee/services/event-bus";import { externalKmsDALFactory } from "@app/ee/services/external-kms/external-kms-dal";import { externalKmsServiceFactory } from "@app/ee/services/external-kms/external-kms-service";import { gatewayDALFactory } from "@app/ee/services/gateway/gateway-dal";@@ -624,6 +625,9 @@ export const registerRoutes = async (const eventBusService = eventBusFactory(server.redis);const sseService = sseServiceFactory(eventBusService, server.redis);+ // New event bus for inter-container communication+ const internalEventBus = eventBusServiceFactory({ redis: server.redis });+const permissionService = permissionServiceFactory({permissionDAL,serviceTokenDAL,@@ -2679,6 +2683,7 @@ export const registerRoutes = async (await microsoftTeamsService.start();await dynamicSecretQueueService.init();await eventBusService.init();+ await internalEventBus.init();// inject all servicesserver.decorate<FastifyZodProvider["services"]>("services", {@@ -2796,6 +2801,7 @@ export const registerRoutes = async (secretScanningV2: secretScanningV2Service,reminder: reminderService,bus: eventBusService,+ eventBus: internalEventBus,sse: sseService,notification: notificationService,pamFolder: pamFolderService,@@ -2955,6 +2961,7 @@ export const registerRoutes = async (cronJobs.forEach((job) => job.stop());await telemetryService.flushAll();await eventBusService.close();+ await internalEventBus.close();sseService.close();});};