Skip to content

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

4.7 KB
Raw Blame
import { apId, ApId } from '@activepieces/core-utils'
import { apDayjsDuration } from '@activepieces/server-utils'
import { FailedStep, FlowRunStatus, RunEnvironment } from '@activepieces/shared'
import { Queue } from 'bullmq'
import Redis from 'ioredis'
import { DistributedStore } from '../../database/redis/distributed-store-factory'
import { QueueName } from './index'

export const redisMetadataKey = ({ projectId, runId }: RedisMetadataKeyParams): string => `runs_metadata:${projectId}:${runId}`

export const legacyRedisMetadataKey = (runId: ApId): string => `runs_metadata:${runId}`

export const runsMetadataDeduplicationId = ({ projectId, runId }: RedisMetadataKeyParams): string => `${projectId}-${runId}`

export const runsMetadataQueueFactory = ({
    createRedisConnection,
    distributedStore,
}: RunsMetadataQueueFactoryParams) => {
    let queueInstance: Queue<RunsMetadataJobData> | undefined = undefined

    return {
        async init(config: RunsMetadataQueueConfig): Promise<void> {
            queueInstance = new Queue<RunsMetadataJobData>(QueueName.RUNS_METADATA, {
                connection: await createRedisConnection(),
                defaultJobOptions: {
                    attempts: 5,
                    backoff: {
                        type: 'exponential',
                        delay: apDayjsDuration(8, 'minute').asMilliseconds(),
                    },
                    removeOnComplete: true,
                    removeOnFail: {
                        age: apDayjsDuration(config.redisFailedJobRetentionDays, 'day').asSeconds(),
                        count: config.redisFailedJobRetentionMaxCount,
                    },
                },
            })
            await queueInstance.waitUntilReady()
        },

        async add(params: RunsMetadataUpsertData): Promise<void> {
            if (!queueInstance) {
                throw new Error('Runs metadata queue not initialized')
            }

            const cleanedParams = stripToRunsMetadataUpsertData(params)

            await distributedStore.merge(redisMetadataKey({ projectId: cleanedParams.projectId, runId: cleanedParams.id }), {
                ...cleanedParams,
                requestId: apId(),
            })

            await queueInstance.add(
                'update-run-metadata',
                { runId: cleanedParams.id, projectId: cleanedParams.projectId },
                { deduplication: { id: runsMetadataDeduplicationId({ projectId: cleanedParams.projectId, runId: cleanedParams.id }) } },
            )
        },

        get(): Queue<RunsMetadataJobData> {
            if (!queueInstance) {
                throw new Error('Runs metadata queue not initialized')
            }
            return queueInstance
        },

        isInitialized(): boolean {
            return queueInstance !== undefined
        },
    }
}

const RUNS_METADATA_UPSERT_KEYS: (keyof RunsMetadataUpsertData)[] = [
    'id', 'projectId', 'created', 'flowId', 'flowVersionId', 'environment',
    'triggeredBy', 'startTime', 'finishTime', 'status', 'tags',
    'failedStep', 'stepNameToTest', 'parentRunId', 'parentWaitpointId', 'failParentOnFailure',
    'logsFileId', 'updated', 'stepsCount', 'requestId',
    'provisionMs', 'bootMs', 'runMs', 'willRetry',
]

function stripToRunsMetadataUpsertData(params: RunsMetadataUpsertData): RunsMetadataUpsertData {
    const result: Record<string, unknown> = {}
    for (const key of RUNS_METADATA_UPSERT_KEYS) {
        if (key in params) {
            result[key] = params[key]
        }
    }
    return result as RunsMetadataUpsertData
}

type RedisMetadataKeyParams = {
    projectId: ApId
    runId: ApId
}

type RunsMetadataQueueFactoryParams = {
    createRedisConnection: () => Promise<Redis>
    distributedStore: DistributedStore
}

export type RunsMetadataJobData = {
    runId: string
    projectId: string
}

export type RunsMetadataQueueConfig = {
    redisFailedJobRetentionDays: number
    redisFailedJobRetentionMaxCount: number
}

export type RunsMetadataUpsertData = {
    id: string
    projectId: string
    created?: string
    flowId?: string
    flowVersionId?: string
    environment?: RunEnvironment
    triggeredBy?: string
    startTime?: string | null
    finishTime?: string | null
    status?: FlowRunStatus
    tags?: string[]
    failedStep?: FailedStep
    stepNameToTest?: string
    parentRunId?: string
    parentWaitpointId?: string
    failParentOnFailure?: boolean
    logsFileId?: string | null
    updated?: string
    stepsCount?: number
    requestId?: string
    // Transient worker-measured phase durations, merged then folded into the `timeline` column. Not persisted directly.
    provisionMs?: number
    bootMs?: number
    runMs?: number
    willRetry?: boolean
}