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

2.6 KB
Raw Blame
import { ErrorCode, isNil, ProjectId, spreadIfDefined, tryCatch } from '@activepieces/core-utils'
import { onCallService } from '@activepieces/server-utils'
import { FlowVersion, LATEST_FLOW_SCHEMA_VERSION } from '@activepieces/shared'
import { FastifyBaseLogger } from 'fastify'
import { system } from '../../helper/system/system'
import { AppSystemProp } from '../../helper/system/system-props'
import { projectService } from '../../project/project-service'
import { flowVersionBackupService } from './flow-version-backup.service'
import { flowVersionRepo } from './flow-version.service'
import { flowMigrations } from './migrations'

export const flowVersionMigrationService = (log: FastifyBaseLogger) => ({
    async migrate(flowVersion: FlowVersion, projectId?: ProjectId, platformId?: string): Promise<FlowVersion> {
        // Early exit if already at latest version
        if (flowVersion.schemaVersion === LATEST_FLOW_SCHEMA_VERSION) {
            return flowVersion
        }

        log.info('Starting flow version migration')

        const resolvedPlatformId = platformId ?? (isNil(projectId) ? undefined : await projectService(log).getPlatformId(projectId))
        const { data: migratedFlowVersion, error: migrationError } = await tryCatch(() => flowMigrations.apply(flowVersion, { log, projectId, platformId: resolvedPlatformId }))
        if (migrationError) {
            log.error({ migrationError }, '[flowVersionMigration] Failed to migrate flow version')
            onCallService(log, system.get(AppSystemProp.PAGE_ONCALL_WEBHOOK)).page({
                code: ErrorCode.FLOW_MIGRATION_FAILED,
                message: migrationError.message,
                params: { flowVersionId: flowVersion.id },
            }).catch((pageError) => {
                log.error({ pageError }, '[flowVersionMigration] Failed to send on-call page')
            })
            throw migrationError
        }

        if (migratedFlowVersion.schemaVersion === flowVersion.schemaVersion) {
            return migratedFlowVersion
        }

        const backupFiles = flowVersion.backupFiles ?? {}
        if (!isNil(flowVersion.schemaVersion)) {
            backupFiles[flowVersion.schemaVersion] = await flowVersionBackupService(log).store(flowVersion)
        }

        await flowVersionRepo().update(flowVersion.id, {
            schemaVersion: migratedFlowVersion.schemaVersion,
            ...spreadIfDefined('trigger', migratedFlowVersion.trigger),
            connectionIds: migratedFlowVersion.connectionIds,
            agentIds: migratedFlowVersion.agentIds,
            backupFiles,
        })
        log.info('Flow version migration completed')
        return migratedFlowVersion
    },
})