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

18.0 KB
Raw Blame
import { chunk, spreadIfDefined, tryCatch } from '@activepieces/core-utils'
import { ApEdition, AppInstance, DeploymentConfig, FlowStatus, ProjectType, RunEnvironment, UserStatus, WorkerGroupScope } from '@activepieces/shared'
import dayjs from 'dayjs'
import utc from 'dayjs/plugin/utc'
import { FastifyBaseLogger } from 'fastify'
import { flowRepo } from '../../flows/flow/flow.repo'
import { flowRunRepo } from '../../flows/flow-run/flow-run-service'
import { healthStatusService } from '../../health/health.service'
import { exceptionHandler } from '../../helper/exception-handler'
import { sleep } from '../../helper/sleep'
import { system } from '../../helper/system/system'
import { captureLicenseKeyEvent, flushLicenseKeyPostHogEvents, LICENSE_KEY_EVENTS_FLUSH_BATCH_SIZE, LicenseKeyPostHogEvents, SetupReportApp, SetupReportConfig, SetupReportHealth, SetupReportInfra, SetupReportProperties, SetupReportWorker, TotalRunsPerDayProperties } from '../../helper/telemetry.utils'
import { platformConfigurationService } from '../../platform/platform-configuration.service'
import { projectRepo } from '../../project/project-repo'
import { userRepo } from '../../user/user-service'
import { WorkerMachine, workerMachineCache } from '../../workers/machine/machine-cache'
import { workerLiveness } from '../../workers/machine/worker-liveness'
import { platformPlanRepo } from '../platform/platform-plan/platform-plan.service'

dayjs.extend(utc)

const EXECUTIONS_PROJECT_CHUNK_SIZE = 100
const EXECUTIONS_CHUNK_DELAY_MS = 1000
const SETUP_REPORT_WORKERS_LIMIT = 50

export const licenseKeyUsageReportService = (log: FastifyBaseLogger) => ({
    /**
     * Reports per-platform usage to PostHog (for billing/metering) from a single daily bulk pass — this
     * is NOT product telemetry, so it is intentionally not gated on AP_TELEMETRY_ENABLED. PostHog is the
     * only sink: usage counts are not pushed to Autumn (see brain/decisions/000018). The license key is the gate and
     * the PostHog event identifier: only licensed platforms are reported, keyed by their license key
     * (distinctId), so unlicensed instances bail before the heavy aggregate queries and send nothing.
     * Only the previous *completed* UTC day is reported (the
     * current, in-progress day is excluded), so the count is final on first send. Re-running the same day
     * re-emits the same value. Note: with a single-day window there is no healing margin — if a day's run
     * is missed entirely, the next run won't backfill it, since it only ever looks at yesterday.
     * The setup report that rides alongside the usage event is opt-out per platform, through
     * platform_configuration.isInfraSetupTelemetryEnabled.
     */
    async reportAllPlatforms(): Promise<void> {
        try {
            const licenseKeysByPlatform = await queryLicenseKeysByPlatform()

            if (licenseKeysByPlatform.size === 0) {
                return
            }

            const platformIds = [...licenseKeysByPlatform.keys()]
            const previousDayStartInclusive = utcMidnight(1)
            const previousDayEndExclusive = utcMidnight(0)

            const activeFlowsByPlatform = await countActiveFlowsByPlatform(platformIds)
            const usersByPlatform = await countUsersByPlatform(platformIds)
            const teamProjectsByPlatform = await countTeamProjectsByPlatform(platformIds)
            const dailyExecutionsByPlatform = await countDailyProductionRunsByPlatform({
                platformIds,
                dayStartInclusive: previousDayStartInclusive,
                dayEndExclusive: previousDayEndExclusive,
            })
            const reportedAt = new Date().toISOString()
            const edition = system.getEdition()
            const setupReportPlatformIds = await platformConfigurationService(log).filterPlatformsWithInfraSetupTelemetryEnabled({ platformIds })
            const setupReportPlatforms = new Set(setupReportPlatformIds)
            const setupInfo = setupReportPlatformIds.length === 0
                ? {}
                : await collectSetupInfo({ edition, platformIds: setupReportPlatformIds, log })

            for (const platformBatch of chunk([...licenseKeysByPlatform], LICENSE_KEY_EVENTS_FLUSH_BATCH_SIZE)) {
                for (const [platformId, licenseKey] of platformBatch) {
                    const activeFlows = activeFlowsByPlatform.get(platformId) ?? 0
                    const users = usersByPlatform.get(platformId) ?? 0
                    const teamProjects = teamProjectsByPlatform.get(platformId) ?? 0
                    captureLicenseKeyEvent({
                        licenseKey,
                        event: LicenseKeyPostHogEvents.TOTAL_RUNS_PER_DAY,
                        properties: buildSnapshotBody({
                            platformId,
                            activeFlows,
                            users,
                            projects: teamProjects,
                            dailyExecutions: dailyExecutionsByPlatform.get(platformId) ?? [],
                            reportedAt,
                        }),
                    })
                    if (setupReportPlatforms.has(platformId)) {
                        captureLicenseKeyEvent({
                            licenseKey,
                            event: LicenseKeyPostHogEvents.PLATFORM_SETUP_REPORT,
                            properties: buildSetupReportBody({ platformId, edition, reportedAt, setupInfo }),
                        })
                    }
                }

                const flushResult = await tryCatch(() => flushLicenseKeyPostHogEvents())
                if (flushResult.error !== null) {
                    log.warn({ error: flushResult.error }, '[licenseKeyUsageReport#reportAllPlatforms] Failed to flush license-key events batch')
                }
            }
        }
        catch (error) {
            exceptionHandler.handle(error, log)
        }
    },
})

async function countActiveFlowsByPlatform(platformIds: string[]): Promise<Map<string, number>> {
    const enabledFlowCountPerPlatform = await flowRepo()
        .createQueryBuilder('flow')
        .innerJoin('flow.project', 'project')
        .select('project.platformId', 'platformId')
        .addSelect('COUNT(*)', 'count')
        .where('flow.status = :status', { status: FlowStatus.ENABLED })
        .andWhere('project.platformId IN (:...platformIds)', { platformIds })
        .andWhere('project.deleted IS NULL')
        .groupBy('project.platformId')
        .getRawMany<PlatformCountRow>()

    return toCountByPlatformId(enabledFlowCountPerPlatform)
}

async function countUsersByPlatform(platformIds: string[]): Promise<Map<string, number>> {
    const activeUserCountPerPlatform = await userRepo()
        .createQueryBuilder('user')
        .select('user.platformId', 'platformId')
        .addSelect('COUNT(*)', 'count')
        .where('user.platformId IN (:...platformIds)', { platformIds })
        .andWhere('user.status = :status', { status: UserStatus.ACTIVE })
        .groupBy('user.platformId')
        .getRawMany<PlatformCountRow>()

    return toCountByPlatformId(activeUserCountPerPlatform)
}

async function countTeamProjectsByPlatform(platformIds: string[]): Promise<Map<string, number>> {
    const teamProjectCountPerPlatform = await projectRepo()
        .createQueryBuilder('project')
        .select('project.platformId', 'platformId')
        .addSelect('COUNT(*)', 'count')
        .where('project.type = :type', { type: ProjectType.TEAM })
        .andWhere('project.platformId IN (:...platformIds)', { platformIds })
        .andWhere('project.deleted IS NULL')
        .groupBy('project.platformId')
        .getRawMany<PlatformCountRow>()

    return toCountByPlatformId(teamProjectCountPerPlatform)
}

/**
 * Counts only production runs because test runs (RunEnvironment.TESTING) are not billable. Scopes the
 * scan to the licensed platforms' projects and filters flow_run on projectId — which is what lets
 * PostgreSQL use the flow_run (projectId, environment, created, ...) indexes. A platformId join leaves
 * the index unusable (whole-table scan), and an unscoped created-only scan reads every platform's runs
 * cloud-wide; both trip the DB statement timeout. The projectIds are chunked so each aggregate stays
 * small and bounded. Projects are mapped back to platforms in app code.
 */
async function countDailyProductionRunsByPlatform({ platformIds, dayStartInclusive, dayEndExclusive }: {
    platformIds: string[]
    dayStartInclusive: string
    dayEndExclusive: string
}): Promise<Map<string, DailyExecutionCount[]>> {
    const licensedProjects = await projectRepo()
        .createQueryBuilder('project')
        .select('project.id', 'projectId')
        .addSelect('project.platformId', 'platformId')
        .where('project.platformId IN (:...platformIds)', { platformIds })
        .andWhere('project.deleted IS NULL')
        .getRawMany<{ projectId: string, platformId: string }>()

    const platformIdByProjectId = new Map(licensedProjects.map((project): [string, string] => [project.projectId, project.platformId]))
    const runCountByPlatformIdAndRunDay = new Map<string, Map<string, number>>()

    for (const projectIdChunk of chunk(licensedProjects.map((project) => project.projectId), EXECUTIONS_PROJECT_CHUNK_SIZE)) {
        // Throttle before every chunk so a large report doesn't monopolise the DB connection pool /
        // Postgres, leaving capacity for live request traffic while the (background) report runs.
        await sleep(EXECUTIONS_CHUNK_DELAY_MS)

        const runCountsPerProjectPerRunDay = await flowRunRepo()
            .createQueryBuilder('flow_run')
            .select('flow_run.projectId', 'projectId')
            .addSelect('to_char(flow_run.created AT TIME ZONE \'UTC\', \'YYYY-MM-DD\')', 'runDay')
            .addSelect('COUNT(*)', 'runCount')
            .where('flow_run.projectId IN (:...projectIdChunk)', { projectIdChunk })
            .andWhere('flow_run.environment = :environment', { environment: RunEnvironment.PRODUCTION })
            .andWhere('flow_run.created >= :dayStartInclusive', { dayStartInclusive })
            .andWhere('flow_run.created < :dayEndExclusive', { dayEndExclusive })
            .andWhere('flow_run.parentWaitpointId IS NULL')
            .groupBy('flow_run.projectId')
            .addGroupBy('to_char(flow_run.created AT TIME ZONE \'UTC\', \'YYYY-MM-DD\')')
            .getRawMany<{ projectId: string, runDay: string, runCount: string }>()

        for (const projectRunCount of runCountsPerProjectPerRunDay) {
            const platformId = platformIdByProjectId.get(projectRunCount.projectId)
            if (!platformId) {
                continue
            }
            const runCountByRunDay = runCountByPlatformIdAndRunDay.get(platformId) ?? new Map<string, number>()
            const runCountSoFar = runCountByRunDay.get(projectRunCount.runDay) ?? 0
            runCountByRunDay.set(projectRunCount.runDay, runCountSoFar + Number(projectRunCount.runCount))
            runCountByPlatformIdAndRunDay.set(platformId, runCountByRunDay)
        }
    }

    const dailyExecutionsByPlatformId = new Map<string, DailyExecutionCount[]>()
    for (const [platformId, runCountByRunDay] of runCountByPlatformIdAndRunDay) {
        const dailyExecutions = [...runCountByRunDay.entries()].map(([date, count]): DailyExecutionCount => ({ date, count }))
        dailyExecutionsByPlatformId.set(platformId, dailyExecutions)
    }
    return dailyExecutionsByPlatformId
}

async function queryLicenseKeysByPlatform(): Promise<Map<string, string>> {
    const licensedPlatforms = await platformPlanRepo()
        .createQueryBuilder('platform_plan')
        .select('platform_plan.platformId', 'platformId')
        .addSelect('platform_plan.licenseKey', 'licenseKey')
        .where('platform_plan.licenseKey IS NOT NULL')
        .getRawMany<{ platformId: string, licenseKey: string }>()

    return new Map(licensedPlatforms.map((licensedPlatform): [string, string] => [licensedPlatform.platformId, licensedPlatform.licenseKey]))
}

function toCountByPlatformId(countPerPlatform: PlatformCountRow[]): Map<string, number> {
    return new Map(countPerPlatform.map((platformCount): [string, number] => [platformCount.platformId, Number(platformCount.count)]))
}

function buildSnapshotBody({
    platformId,
    activeFlows,
    users,
    projects,
    dailyExecutions,
    reportedAt,
}: {
    platformId: string
    activeFlows: number
    users: number
    projects: number
    dailyExecutions: DailyExecutionCount[]
    reportedAt: string
}): TotalRunsPerDayProperties {
    return {
        platform_id: platformId,
        active_flows: activeFlows,
        projects,
        users,
        daily_executions: dailyExecutions,
        reported_at: reportedAt,
    }
}

async function collectSetupInfo({ edition, platformIds, log }: {
    edition: ApEdition
    platformIds: string[]
    log: FastifyBaseLogger
}): Promise<SetupInfo> {
    const { data, error } = await tryCatch(async () => {
        const onlineWorkers = await queryOnlineWorkers()
        if (edition === ApEdition.CLOUD) {
            return { workersByPlatform: await groupDedicatedWorkersByPlatform({ platformIds, onlineWorkers }) }
        }
        const deployment = await healthStatusService(log).collectDeploymentDiagnostics()
        return {
            apps: deployment.apps.map(toSetupReportApp),
            deploymentWorkers: toWorkerSetup(onlineWorkers),
            infra: {
                database: deployment.database,
                redis: deployment.redis,
                storage: deployment.storage,
            },
            config: toSetupReportConfig(deployment.config),
            health: {
                database: deployment.database.ok,
                release: healthStatusService(log).getReleaseHealth(onlineWorkers.map((worker) => worker.information.workerProps.version)),
            },
        }
    })
    if (error !== null) {
        log.warn({ error }, '[licenseKeyUsageReport#collectSetupInfo] Failed to collect the deployment setup, reporting edition only')
        return {}
    }
    return data
}

function toSetupReportApp(appInstance: AppInstance): SetupReportApp {
    return {
        cpuCores: appInstance.cpuCores,
        ramTotalBytes: appInstance.ramTotalBytes,
        diskTotalBytes: appInstance.diskTotalBytes,
        diskPercentage: appInstance.diskPercentage,
        version: appInstance.version,
        eventLoopDelayMs: appInstance.eventLoopDelayMs,
    }
}

function toSetupReportConfig(config: DeploymentConfig): SetupReportConfig {
    return {
        executionMode: config.executionMode,
        fileStorageLocation: config.fileStorageLocation,
        sandboxMemoryLimitKb: config.sandboxMemoryLimitKb,
        s3SignedUrls: config.s3SignedUrls,
        s3Region: config.s3Region,
        projectRateLimiterEnabled: config.projectRateLimiterEnabled,
        defaultConcurrentJobsLimit: config.defaultConcurrentJobsLimit,
    }
}

async function queryOnlineWorkers(): Promise<WorkerMachine[]> {
    const allWorkers = await workerMachineCache().find()
    return workerLiveness.partitionByLiveness(allWorkers).online
}

async function groupDedicatedWorkersByPlatform({ platformIds, onlineWorkers }: {
    platformIds: string[]
    onlineWorkers: WorkerMachine[]
}): Promise<Map<string, WorkerSetup>> {
    const workerGroupIdByPlatformId = await queryWorkerGroupsByPlatform(platformIds)
    if (workerGroupIdByPlatformId.size === 0) {
        return new Map()
    }
    const dedicatedWorkers = onlineWorkers.filter((worker) => worker.workerGroupScope === WorkerGroupScope.PLATFORM)
    return new Map([...workerGroupIdByPlatformId].map(([platformId, workerGroupId]): [string, WorkerSetup] => [
        platformId,
        toWorkerSetup(dedicatedWorkers.filter((worker) => worker.workerGroupId === workerGroupId)),
    ]))
}

async function queryWorkerGroupsByPlatform(platformIds: string[]): Promise<Map<string, string>> {
    const workerGroupPerPlatform = await platformPlanRepo()
        .createQueryBuilder('platform_plan')
        .select('platform_plan.platformId', 'platformId')
        .addSelect('platform_plan.workerGroupId', 'workerGroupId')
        .where('platform_plan.platformId IN (:...platformIds)', { platformIds })
        .andWhere('platform_plan.workerGroupId IS NOT NULL')
        .getRawMany<{ platformId: string, workerGroupId: string }>()

    return new Map(workerGroupPerPlatform.map((row): [string, string] => [row.platformId, row.workerGroupId]))
}

function toWorkerSetup(workers: WorkerMachine[]): WorkerSetup {
    return {
        workers: workers.slice(0, SETUP_REPORT_WORKERS_LIMIT).map((worker): SetupReportWorker => ({
            totalCpuCores: worker.information.totalCpuCores,
            totalAvailableRamInBytes: worker.information.totalAvailableRamInBytes,
            diskInfo: worker.information.diskInfo,
            workerProps: worker.information.workerProps,
        })),
        workersTotal: workers.length,
    }
}

function buildSetupReportBody({ platformId, edition, reportedAt, setupInfo }: {
    platformId: string
    edition: ApEdition
    reportedAt: string
    setupInfo: SetupInfo
}): SetupReportProperties {
    const workerSetup = setupInfo.workersByPlatform?.get(platformId) ?? setupInfo.deploymentWorkers
    return {
        platformId,
        edition,
        reportedAt,
        ...spreadIfDefined('apps', setupInfo.apps),
        ...spreadIfDefined('workers', workerSetup?.workers),
        ...spreadIfDefined('workersTotal', workerSetup?.workersTotal),
        ...spreadIfDefined('infra', setupInfo.infra),
        ...spreadIfDefined('config', setupInfo.config),
        ...spreadIfDefined('health', setupInfo.health),
    }
}

function utcMidnight(daysAgo: number): string {
    return dayjs.utc().startOf('day').subtract(daysAgo, 'day').toISOString()
}

type PlatformCountRow = {
    platformId: string
    count: string
}

type DailyExecutionCount = {
    date: string
    count: number
}

type WorkerSetup = {
    workers: SetupReportWorker[]
    workersTotal: number
}

type SetupInfo = {
    apps?: SetupReportApp[]
    infra?: SetupReportInfra
    config?: SetupReportConfig
    health?: SetupReportHealth
    deploymentWorkers?: WorkerSetup
    workersByPlatform?: Map<string, WorkerSetup>
}