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

10.1 KB
Raw Blame
import { ActivepiecesError, apId, ErrorCode, FlowId, isNil, tryCatch } from '@activepieces/core-utils'
import { FlowVersion, PopulatedTriggerSource, TemplateTelemetryEventType, TriggerSource } from '@activepieces/shared'
import { FastifyBaseLogger } from 'fastify'
import { In } from 'typeorm'
import { repoFactory } from '../../core/db/repo-factory'
import { flowVersionService } from '../../flows/flow-version/flow-version.service'
import { templateTelemetryService } from '../../template/template-telemetry/template-telemetry.service'
import { jobQueue } from '../../workers/job-queue/job-queue'
import { flowTriggerSideEffect } from './flow-trigger-side-effect'
import { TriggerSourceEntity } from './trigger-source-entity'
import { triggerUtils } from './trigger-utils'

export const triggerSourceRepo = repoFactory(TriggerSourceEntity)

export const triggerSourceService = (log: FastifyBaseLogger) => {
    return {
        async enable(params: EnableTriggerParams): Promise<TriggerSource> {
            const { flowVersion, projectId, simulate, templateId, isRepublish, isTriggerUnchanged } = params
            log.info({
                flow: { id: flowVersion.flowId },
                flowVersion: { id: flowVersion.id },
                project: { id: projectId },
                simulate,
            }, '[triggerSourceService#enable] Enabling trigger source')
            const pieceTrigger = await triggerUtils(log).getPieceTriggerOrThrow({ flowVersion, projectId })
            const existingTriggerSource = await triggerSourceRepo().findOne({
                where: {
                    flowId: flowVersion.flowId,
                    projectId,
                    simulate,
                },
                withDeleted: true,
                order: { created: 'DESC' },
            })
            if (!isNil(existingTriggerSource)) {
                await jobQueue(log).removeRepeatingJob({ flowVersionId: existingTriggerSource.flowVersionId })
            }
            await triggerSourceRepo().softDelete({
                flowId: flowVersion.flowId,
                projectId,
                simulate,
            })
            log.info('[triggerSourceService#enable] Soft deleted trigger source')
            const triggerSourceWithouSchedule: Omit<TriggerSource, 'created' | 'updated' | 'schedule'> = {
                id: apId(),
                type: pieceTrigger.type,
                projectId,
                flowId: flowVersion.flowId,
                triggerName: pieceTrigger.name,
                flowVersionId: flowVersion.id,
                pieceName: flowVersion.trigger.settings.pieceName,
                pieceVersion: flowVersion.trigger.settings.pieceVersion,
                simulate,
            }
            const triggerSource = await triggerSourceRepo().save(triggerSourceWithouSchedule)
            const enableResult = await tryCatch(async () => {
                const { scheduleOptions } = await flowTriggerSideEffect(log).enable({
                    flowId: flowVersion.flowId,
                    flowVersionId: flowVersion.id,
                    projectId,
                    pieceName: flowVersion.trigger.settings.pieceName,
                    pieceTrigger,
                    simulate,
                    isRepublish,
                    isTriggerUnchanged,
                    previousSchedule: existingTriggerSource?.schedule ?? undefined,
                })
                return triggerSourceRepo().save({
                    ...triggerSource,
                    schedule: scheduleOptions,
                })
            })
            if (enableResult.error !== null) {
                const { error: rollbackError } = await tryCatch(() => triggerSourceRepo().softDelete({
                    id: triggerSource.id,
                    projectId,
                }))
                log.warn({
                    flow: { id: flowVersion.flowId },
                    flowVersion: { id: flowVersion.id },
                    project: { id: projectId },
                    error: enableResult.error.message,
                    ...(isNil(rollbackError) ? {} : { rollbackError: rollbackError.message }),
                }, '[triggerSourceService#enable] Rolled back trigger source after enable failure')
                throw enableResult.error
            }

            if (templateId) {
                templateTelemetryService(log).sendEvent({
                    event: {
                        eventType: TemplateTelemetryEventType.ACTIVATE,
                        templateId,
                        flowId: flowVersion.flowId,
                    },
                    projectId,
                })
            }

            log.info('[triggerSourceService#enable] Enabled flow trigger side effect')
            return enableResult.data
        },
        async get(params: GetTriggerParams): Promise<TriggerSource | null> {
            const { projectId, id } = params
            return triggerSourceRepo().findOne({
                where: {
                    id,
                    projectId,
                },
            })
        },
        async getByFlowId(params: GetFlowIdParamsWithProjectId): Promise<TriggerSource | null> {
            const { flowId, simulate, projectId } = params
            return triggerSourceRepo().findOne({
                where: {
                    flowId,
                    simulate,
                    ...(projectId ? { projectId } : {}),
                },
            })
        },
        async getByFlowIds(params: GetByFlowIdsParams): Promise<Map<FlowId, TriggerSource>> {
            const { flowIds, projectId } = params
            if (flowIds.length === 0) {
                return new Map()
            }
            const triggerSources = await triggerSourceRepo().find({
                where: {
                    flowId: In(flowIds),
                    projectId,
                },
            })
            const result = new Map<FlowId, TriggerSource>()
            for (const ts of triggerSources) {
                result.set(ts.flowId, ts)
            }
            return result
        },
        async getByFlowIdPopulated(params: GetByFlowIdParams): Promise<PopulatedTriggerSource | null> {
            const { flowId, simulate } = params
            return triggerSourceRepo().findOne({
                where: {
                    flowId,
                    simulate,
                },
                relations: {
                    flow: true,
                },
            })
        },
        async getOrThrow({ projectId, id }: GetTriggerParams): Promise<TriggerSource> {
            const triggerSource = await triggerSourceRepo().findOne({
                where: {
                    id,
                    projectId,
                },
            })
            if (isNil(triggerSource)) {
                throw new ActivepiecesError({
                    code: ErrorCode.ENTITY_NOT_FOUND,
                    params: {
                        entityType: 'trigger',
                        entityId: id,
                    },
                })
            }
            return triggerSource
        },
        async existsByFlowId(params: ExistsByFlowIdParams): Promise<boolean> {
            const { flowId, simulate } = params
            return triggerSourceRepo().existsBy({
                flowId,
                simulate,
            })
        },
        async disable(params: DisableTriggerParams): Promise<void> {
            const { projectId, flowId, simulate, templateId } = params
            log.info({
                flow: { id: flowId },
                project: { id: projectId },
                simulate,
            }, '[triggerSourceService#disable] Disabling trigger source')
            const triggerSource = await triggerSourceRepo().findOneBy({
                flowId,
                projectId,
                simulate,
            })
            if (isNil(triggerSource)) {
                return
            }
            const flowVersion = await flowVersionService(log).getOneOrThrow(triggerSource.flowVersionId)
            const pieceTrigger = await triggerUtils(log).getPieceTrigger({ flowVersion, projectId })
            if (!isNil(pieceTrigger)) {
                await flowTriggerSideEffect(log).disable({
                    flowId: triggerSource.flowId,
                    flowVersionId: triggerSource.flowVersionId,
                    projectId,
                    pieceName: triggerSource.pieceName,
                    pieceTrigger,
                    simulate,
                    ignoreError: params.ignoreError,
                    isRepublish: params.isRepublish,
                    isTriggerUnchanged: params.isTriggerUnchanged,
                })
                log.info('[triggerSourceService#disable] Disabled flow trigger side effect')
            }
            await triggerSourceRepo().softDelete({
                id: triggerSource.id,
                projectId,
            })
            log.info('[triggerSourceService#disable] Soft deleted trigger source')
            if (templateId) {
                templateTelemetryService(log).sendEvent({
                    event: {
                        eventType: TemplateTelemetryEventType.DEACTIVATE,
                        templateId,
                        flowId,
                    },
                    projectId,
                })
            }
        },
    }
}

type ExistsByFlowIdParams = {
    flowId: string
    simulate: boolean
}

type GetByFlowIdParams = {
    flowId: string
    projectId?: string
    simulate: boolean
}

type GetByFlowIdsParams = {
    flowIds: FlowId[]
    projectId: string
}

type GetFlowIdParamsWithProjectId = {
    flowId: string
    projectId: string
    simulate: boolean | undefined
}

type GetTriggerParams = {
    projectId: string
    id: string
}

type DisableTriggerParams = {
    projectId: string
    flowId: string
    simulate: boolean
    ignoreError: boolean
    templateId?: string
    isRepublish?: boolean
    isTriggerUnchanged?: boolean
}

type EnableTriggerParams = {
    flowVersion: FlowVersion
    projectId: string
    simulate: boolean
    templateId?: string
    isRepublish?: boolean
    isTriggerUnchanged?: boolean
}