AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents
TypeScript ai-agentai-agent-toolsai-agentsai-agents-frameworkmcpmcp-servermcp-toolsmcpsn8n-alternativeno-code-automationworkflowworkflow-automationworkflows
import { isNil, tryCatch } from '@activepieces/core-utils'
import { Mutex } from 'async-mutex'
import Redis from 'ioredis'
import { redisConnections } from '../database/redis-connections'
let redisClientSubscriber: Redis | null = null
let redisClientPublisher: Redis | null = null
const mutexLock = new Mutex()
const channelListeners = new Map<string, Set<(message: string) => void>>()
const redisFactory = redisConnections.create
export const pubsub = {
async subscribe(
channel: string,
listener: (message: string) => void,
): Promise<void> {
const subscriber = await getRedisClientSubscriber()
const existing = channelListeners.get(channel)
if (!isNil(existing)) {
existing.add(listener)
return
}
channelListeners.set(channel, new Set([listener]))
const { error } = await tryCatch(() => subscriber.subscribe(channel))
if (!isNil(error)) {
channelListeners.delete(channel)
throw error
}
},
async publish(channel: string, message: string): Promise<void> {
const publisher = await getRedisClientPublisher()
await publisher.publish(channel, message)
},
async unsubscribe(channel: string, listener?: (message: string) => void): Promise<void> {
const listeners = channelListeners.get(channel)
if (isNil(listeners)) {
return
}
if (!isNil(listener)) {
listeners.delete(listener)
if (listeners.size > 0) {
return
}
}
channelListeners.delete(channel)
const subscriber = await getRedisClientSubscriber()
await subscriber.unsubscribe(channel)
},
async close(): Promise<void> {
channelListeners.clear()
if (!isNil(redisClientSubscriber)) {
await redisClientSubscriber.quit()
redisClientSubscriber = null
}
if (!isNil(redisClientPublisher)) {
await redisClientPublisher.quit()
redisClientPublisher = null
}
},
}
async function getRedisClientSubscriber(): Promise<Redis> {
if (!isNil(redisClientSubscriber)) {
return redisClientSubscriber
}
return mutexLock.runExclusive(async () => {
if (!isNil(redisClientSubscriber)) {
return redisClientSubscriber
}
const connection = await redisFactory()
connection.on('message', (channel: string, message: string) => {
const listeners = channelListeners.get(channel)
if (isNil(listeners)) {
return
}
for (const listener of [...listeners]) {
listener(message)
}
})
redisClientSubscriber = connection
return connection
})
}
async function getRedisClientPublisher(): Promise<Redis> {
if (!isNil(redisClientPublisher)) {
return redisClientPublisher
}
return mutexLock.runExclusive(async () => {
if (!isNil(redisClientPublisher)) {
return redisClientPublisher
}
redisClientPublisher = await redisFactory()
return redisClientPublisher
})
}