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
refactor(server): centralize worker groups into workers/worker-groups module (#16456)
Chaker Atallahec2101144872
diff --git a/packages/server/api/src/app/core/canary/canary-routing.middleware.ts b/packages/server/api/src/app/core/canary/canary-routing.middleware.tsindex d03212831cb..b99223221d0 100644--- a/packages/server/api/src/app/core/canary/canary-routing.middleware.ts+++ b/packages/server/api/src/app/core/canary/canary-routing.middleware.ts@@ -2,10 +2,10 @@ import '@fastify/reply-from'import { isNil, tryCatch } from '@activepieces/core-utils'import { PrincipalType } from '@activepieces/shared'import { FastifyBaseLogger, FastifyReply, FastifyRequest } from 'fastify'-import { workerGroupService } from '../../ee/platform/platform-plan/worker-group.service'import { flowExecutionCache } from '../../flows/flow/flow-execution-cache'import { system } from '../../helper/system/system'import { AppSystemProp } from '../../helper/system/system-props'+import { platformWorkerGroupService } from '../../workers/worker-groups/platform-worker-group.service'export const canaryRoutingMiddleware = async (request: FastifyRequest, reply: FastifyReply): Promise<void> => {if (request.headers.upgrade === 'websocket') return@@ -17,7 +17,7 @@ export const canaryRoutingMiddleware = async (request: FastifyRequest, reply: Faif (resolveError || isNil(platformId)) returnconst { data: shouldForward, error: canaryLookupError } = await tryCatch(() =>- workerGroupService(request.log).isCanaryPlatform({ platformId }),+ platformWorkerGroupService(request.log).isCanaryPlatform({ platformId }),)if (canaryLookupError) {request.log.error({ error: canaryLookupError }, '[canaryRoutingMiddleware] failed to fetch canary platform IDs, falling through')diff --git a/packages/server/api/src/app/ee/platform/admin/admin-platform.controller.ts b/packages/server/api/src/app/ee/platform/admin/admin-platform.controller.tsindex a700b520103..448980ead90 100644--- a/packages/server/api/src/app/ee/platform/admin/admin-platform.controller.ts+++ b/packages/server/api/src/app/ee/platform/admin/admin-platform.controller.ts@@ -13,9 +13,9 @@ import { AppSystemProp } from '../../../helper/system/system-props'import { pieceMetadataService } from '../../../pieces/metadata/piece-metadata-service'import { isToolSearchEnabled } from '../../../tool-search/tool-search-flag'import { toolSearchReindexJob } from '../../../tool-search/tool-search-reindex.job'+import { CANARY_WORKER_GROUP_ID, platformWorkerGroupService } from '../../../workers/worker-groups/platform-worker-group.service'import { AgentConversationEntity } from '../../agent/agent-conversation-entity'import { chatAnalyticsBulkSync } from '../../agent/chat-analytics-sync'-import { CANARY_WORKER_GROUP_ID, workerGroupService } from '../platform-plan/worker-group.service'import { adminPlatformService } from './admin-platform.service'const API_KEY_HEADER = 'api-key'@@ -73,15 +73,15 @@ const adminPlatformController: FastifyPluginAsyncZod = async (app.post('/platforms/worker-group', UpdateWorkerGroupRequest, async (req, res) => {const { platformId, workerGroupId } = req.body- await workerGroupService(req.log).moveJobsToTargetQueue({ platformId, workerGroupId })- await workerGroupService(req.log).updateWorkerGroup({ platformId, workerGroupId })+ await platformWorkerGroupService(req.log).moveJobsToTargetQueue({ platformId, workerGroupId })+ await platformWorkerGroupService(req.log).updateWorkerGroup({ platformId, workerGroupId })return res.status(StatusCodes.OK).send()})app.post('/platforms/canary', UpdateCanaryRequest, async (req, res) => {const { platformId, canary } = req.body- await workerGroupService(req.log).moveJobsToTargetQueue({ platformId, workerGroupId: canary ? CANARY_WORKER_GROUP_ID : null })- await workerGroupService(req.log).updateCanary({ platformId, canary })+ await platformWorkerGroupService(req.log).moveJobsToTargetQueue({ platformId, workerGroupId: canary ? CANARY_WORKER_GROUP_ID : null })+ await platformWorkerGroupService(req.log).updateCanary({ platformId, canary })return res.status(StatusCodes.OK).send()})diff --git a/packages/server/api/src/app/ee/projects/platform-project-service.ts b/packages/server/api/src/app/ee/projects/platform-project-service.tsindex 726ff4d70a6..67cfbad47ae 100644--- a/packages/server/api/src/app/ee/projects/platform-project-service.ts+++ b/packages/server/api/src/app/ee/projects/platform-project-service.ts@@ -1,4 +1,4 @@-import { ActivepiecesError, apId, Cursor, ErrorCode, isNil, Metadata, PlatformId, ProjectId, SeekPage, spreadIfDefined, tryCatch, UserId } from '@activepieces/core-utils'+import { ActivepiecesError, apId, Cursor, ErrorCode, isNil, Metadata, PlatformId, ProjectId, SeekPage, spreadIfDefined, UserId } from '@activepieces/core-utils'import { apDayjs } from '@activepieces/server-utils'import { AppConnectionScope, PiecesFilterType, PrincipalType, Project, ProjectType, ProjectWithLimits, UpdateProjectPlatformRequest } from '@activepieces/shared'import { FastifyBaseLogger } from 'fastify'@@ -16,11 +16,9 @@ import { platformService } from '../../platform/platform.service'import { ProjectEntity } from '../../project/project-entity'import { applyProjectsAccessFilters, projectService } from '../../project/project-service'import { userService } from '../../user/user-service'-import { getPlatformGroupQueueName, getProjectGroupQueueName, QueueName } from '../../workers/job'-import { platformQueueMigrationService } from '../../workers/platform-queue-migration.service'+import { projectWorkerGroupService } from '../../workers/worker-groups/project-worker-group.service'import { concurrencyPoolService } from '../platform/concurrency-pool/concurrency-pool.service'import { platformPlanService } from '../platform/platform-plan/platform-plan.service'-import { workerGroupService } from '../platform/platform-plan/worker-group.service'import { projectMemberService } from './project-members/project-member.service'import { ProjectPlanEntity } from './project-plan/project-plan.entity'import { projectLimitsService } from './project-plan/project-plan.service'@@ -199,12 +197,11 @@ export const platformProjectService = (log: FastifyBaseLogger) => ({}const previousGroupId = project.workerGroupId ?? nullif (platformPlan.workerGroupsEnabled && workerGroupId !== undefined && previousGroupId !== workerGroupId) {- await migrateJobsToNewGroupQueue({+ await projectWorkerGroupService(log).migrateProjectToGroup({projectId,platformId: project.platformId,fromGroupId: previousGroupId,toGroupId: workerGroupId,- log,})}return this.getWithPlanAndUsageOrThrow(projectId)@@ -345,31 +342,6 @@ async function resolvePoolId({ platformId, projectId, maxConcurrentJobs, log }:return undefined}-async function migrateJobsToNewGroupQueue({ projectId, platformId, fromGroupId, toGroupId, log }: MigrateJobsToNewGroupQueueParams): Promise<void> {- const ungroupedQueueName = await resolveUngroupedQueueName({ platformId, log })- const { error } = await tryCatch(() => platformQueueMigrationService(log).migrateProjectJobs({- fromQueueName: isNil(fromGroupId) ? ungroupedQueueName : getProjectGroupQueueName(fromGroupId),- toQueueName: isNil(toGroupId) ? ungroupedQueueName : getProjectGroupQueueName(toGroupId),- projectId,- }))- if (error) {- log.error({ project: { id: projectId }, platform: { id: platformId }, error }, '[platformProjectService#update] Failed to migrate waiting jobs to the new worker group queue')- }-}--async function resolveUngroupedQueueName({ platformId, log }: { platformId: string, log: FastifyBaseLogger }): Promise<string> {- const platformGroupId = await workerGroupService(log).getWorkerGroupId({ platformId })- return isNil(platformGroupId) ? QueueName.WORKER_JOBS : getPlatformGroupQueueName(platformGroupId)-}--type MigrateJobsToNewGroupQueueParams = {- projectId: string- platformId: string- fromGroupId: string | null- toGroupId: string | null- log: FastifyBaseLogger-}-type ResolvePoolIdParams = {platformId: stringprojectId: stringdiff --git a/packages/server/api/src/app/flows/pre-warm-workers.ts b/packages/server/api/src/app/flows/pre-warm-workers.tsindex 8ecac101f19..7055e2134da 100644--- a/packages/server/api/src/app/flows/pre-warm-workers.ts+++ b/packages/server/api/src/app/flows/pre-warm-workers.ts@@ -4,7 +4,6 @@ import { ApEdition, FileCompression, FileType, FlowActionType, FlowStatus, flowSimport { FastifyBaseLogger } from 'fastify'import { accessTokenManager } from '../authentication/lib/access-token-manager'import { distributedLock, distributedStore } from '../database/redis-connections'-import { workerGroupService } from '../ee/platform/platform-plan/worker-group.service'import { fileService } from '../file/file.service'import Paginator from '../helper/pagination/paginator'import { system } from '../helper/system/system'@@ -12,7 +11,8 @@ import { AppSystemProp } from '../helper/system/system-props'import { pieceMetadataService } from '../pieces/metadata/piece-metadata-service'import { platformService } from '../platform/platform.service'import { projectService } from '../project/project-service'-import { projectWorkerGroupService } from '../project/project-worker-group.service'+import { platformWorkerGroupService } from '../workers/worker-groups/platform-worker-group.service'+import { projectWorkerGroupService } from '../workers/worker-groups/project-worker-group.service'import { flowService } from './flow/flow.service'@@ -114,7 +114,7 @@ async function computeScope(input: PrewarmDataRequest, log: FastifyBaseLogger):platformId = await projectService(log).getPlatformId(projectIds[0])}else {- platformId = await workerGroupService(log).getWorkerGroupPlatformId({ workerGroupId: input.workerGroupId }) ?? undefined+ platformId = await platformWorkerGroupService(log).getWorkerGroupPlatformId({ workerGroupId: input.workerGroupId }) ?? undefinedif (isNil(platformId)) {return null}diff --git a/packages/server/api/src/app/project/project-service.ts b/packages/server/api/src/app/project/project-service.tsindex cfd313bf1ea..05fe9f4bc59 100644--- a/packages/server/api/src/app/project/project-service.ts+++ b/packages/server/api/src/app/project/project-service.ts@@ -5,9 +5,9 @@ import { Brackets, EntityManager, IsNull, Not, ObjectLiteral, SelectQueryBuilderimport { system } from '../helper/system/system'import { AppSystemProp } from '../helper/system/system-props'import { userService } from '../user/user-service'+import { projectWorkerGroupService } from '../workers/worker-groups/project-worker-group.service'import { projectHooks, ProjectPostCreateContext } from './project-hooks'import { projectRepo } from './project-repo'-import { projectWorkerGroupService } from './project-worker-group.service'export { projectRepo }diff --git a/packages/server/api/src/app/project/project-worker-group.service.ts b/packages/server/api/src/app/project/project-worker-group.service.tsdeleted file mode 100644index 46e24687851..00000000000--- a/packages/server/api/src/app/project/project-worker-group.service.ts+++ /dev/null@@ -1,38 +0,0 @@-import { isNil, spreadIfDefined } from '@activepieces/core-utils'-import { apDayjsDuration } from '@activepieces/server-utils'-import { FastifyBaseLogger } from 'fastify'-import { distributedStore } from '../database/redis-connections'-import { projectRepo } from './project-repo'--const NO_WORKER_GROUP_SENTINEL = '__none__'-const CACHE_TTL_SECONDS = apDayjsDuration(5, 'minute').asSeconds()-const getProjectWorkerGroupCacheKey = (projectId: string): string => `project:${projectId}:worker_group`--export const projectWorkerGroupService = (_log: FastifyBaseLogger) => ({- async getProjectWorkerGroup({ projectId, platformId }: { projectId: string, platformId?: string | null }): Promise<string | null> {- const cached = await distributedStore.get<string>(getProjectWorkerGroupCacheKey(projectId))- if (!isNil(cached)) {- return cached === NO_WORKER_GROUP_SENTINEL ? null : cached- }-- const project = await projectRepo().findOne({- select: ['workerGroupId'],- where: { id: projectId, ...spreadIfDefined('platformId', platformId ?? undefined) },- })-- const workerGroupId = project?.workerGroupId ?? null- await distributedStore.put(getProjectWorkerGroupCacheKey(projectId), workerGroupId ?? NO_WORKER_GROUP_SENTINEL, CACHE_TTL_SECONDS)- return workerGroupId- },- async getWorkerGroupProjects({ workerGroupId }: { workerGroupId: string }): Promise<string[]> {- const projects = await projectRepo().find({- select: ['id'],- where: { workerGroupId },- })- return projects.map((p) => p.id)- },-- async invalidate({ projectId }: { projectId: string }): Promise<void> {- await distributedStore.delete(getProjectWorkerGroupCacheKey(projectId))- },-})diff --git a/packages/server/api/src/app/workers/job-queue/interceptors/rate-limiter-interceptor.ts b/packages/server/api/src/app/workers/job-queue/interceptors/rate-limiter-interceptor.tsindex d00b88f5d21..dd143e5d09b 100644--- a/packages/server/api/src/app/workers/job-queue/interceptors/rate-limiter-interceptor.ts+++ b/packages/server/api/src/app/workers/job-queue/interceptors/rate-limiter-interceptor.ts@@ -7,12 +7,12 @@ import { z } from 'zod'import { getConcurrencyPoolParkedKey, getConcurrencyPoolSetKey, getPlatformPlanNameKey, PLATFORM_PLAN_NAME_TTL_SECONDS } from '../../../database/redis/keys'import { distributedStore, redisConnections } from '../../../database/redis-connections'import { concurrencyPoolService } from '../../../ee/platform/concurrency-pool/concurrency-pool.service'-import { workerGroupService } from '../../../ee/platform/platform-plan/worker-group.service'import { system } from '../../../helper/system/system'import { AppSystemProp } from '../../../helper/system/system-props'import { platformService } from '../../../platform/platform.service'-import { projectWorkerGroupService } from '../../../project/project-worker-group.service'import { workerCapacity } from '../../machine/worker-capacity'+import { platformWorkerGroupService } from '../../worker-groups/platform-worker-group.service'+import { projectWorkerGroupService } from '../../worker-groups/project-worker-group.service'import { InterceptorResult, InterceptorVerdict, JobInterceptor } from '../job-interceptor'import { jobQueue } from '../job-queue'@@ -82,7 +82,7 @@ async function getMaxConcurrentJobs({ poolId, platformId, projectId, log }: { poconst planLimit = await getMaxConcurrentJobsForPlatformPlan({ platformId, log })// When worker groups are enabled, an unassigned-limit project is capped by the physical capacity// of the pool its runs route to (the group pool if the project has one, else shared).- const { data: workerGroupsEnabled } = await tryCatch(() => workerGroupService(log).isWorkerGroupsEnabled({ platformId }))+ const { data: workerGroupsEnabled } = await tryCatch(() => platformWorkerGroupService(log).isWorkerGroupsEnabled({ platformId }))if (workerGroupsEnabled !== true) {return planLimit}diff --git a/packages/server/api/src/app/workers/job-queue/job-queue.ts b/packages/server/api/src/app/workers/job-queue/job-queue.tsindex dabc5a93f98..23f81ba551f 100644--- a/packages/server/api/src/app/workers/job-queue/job-queue.ts+++ b/packages/server/api/src/app/workers/job-queue/job-queue.ts@@ -4,11 +4,10 @@ import { EventDestinationJobData, ExecuteAgentRunJobData, ExecuteAiJobData, Execimport { Job, Queue } from 'bullmq'import { FastifyBaseLogger } from 'fastify'import { redisConnections } from '../../database/redis-connections'-import { workerGroupService } from '../../ee/platform/platform-plan/worker-group.service'import { system } from '../../helper/system/system'import { AppSystemProp } from '../../helper/system/system-props'-import { projectWorkerGroupService } from '../../project/project-worker-group.service'-import { getPlatformGroupQueueName, getProjectGroupQueueName, QueueName } from '../job'+import { QueueName } from '../job'+import { workerGroupRouting } from '../worker-groups/worker-group-routing'const EIGHT_MINUTES_IN_MILLISECONDS = apDayjsDuration(8, 'minute').asMilliseconds()const REDIS_FAILED_JOB_RETENTION_DAYS = apDayjsDuration(system.getNumberOrThrow(AppSystemProp.REDIS_FAILED_JOB_RETENTION_DAYS), 'day').asSeconds()@@ -26,7 +25,7 @@ export const jobQueue = (log: FastifyBaseLogger) => ({const platformId = data.platformIdconst projectId = 'projectId' in data ? data.projectId : null- const queueName = await getQueueName({ platformId, projectId, jobType: data.jobType }, log)+ const queueName = await workerGroupRouting.resolveQueueForJob({ platformId, projectId, jobType: data.jobType, log })const queue = await ensureQueueExists({ log, queueName })switch (type) {@@ -78,7 +77,7 @@ export const jobQueue = (log: FastifyBaseLogger) => ({},async removeOneTimeJob({ jobId, platformId, projectId, jobType }: RemoveOneTimeJobParams): Promise<void> {- const queueName = await getQueueName({ platformId, projectId, jobType }, log)+ const queueName = await workerGroupRouting.resolveQueueForJob({ platformId, projectId, jobType, log })const queue = await ensureQueueExists({ log, queueName })const job = await queue.getJob(jobId)if (!isNil(job)) {@@ -96,7 +95,7 @@ export const jobQueue = (log: FastifyBaseLogger) => ({},async cancelAndReportNeverStarted({ jobId, platformId, projectId, jobType }: RemoveOneTimeJobParams): Promise<boolean> {- const queueName = await getQueueName({ platformId, projectId, jobType }, log)+ const queueName = await workerGroupRouting.resolveQueueForJob({ platformId, projectId, jobType, log })const queue = await ensureQueueExists({ log, queueName })const job = await queue.getJob(jobId)if (isNil(job)) {@@ -130,7 +129,7 @@ export const jobQueue = (log: FastifyBaseLogger) => ({return queue},async removeAllFlowRunJobs({ flowRunId, platformId, projectId }: RemoveAllFlowRunJobsParams): Promise<void> {- const queueName = await getQueueName({ platformId, projectId, jobType: WorkerJobType.EXECUTE_FLOW }, log)+ const queueName = await workerGroupRouting.resolveQueueForJob({ platformId, projectId, jobType: WorkerJobType.EXECUTE_FLOW, log })const queue = await ensureQueueExists({ log, queueName })const allJobs = await queue.getJobs(['waiting', 'delayed'])const matching = allJobs.filter((j) => j.id?.startsWith(flowRunId))@@ -217,43 +216,11 @@ export function callerWaitingForResponse(jobData: JobData): { webserverId: strinreturn null}-export const PROJECT_GROUP_ROUTABLE_JOB_TYPES = new Set<WorkerJobType>([- WorkerJobType.EXECUTE_FLOW,- WorkerJobType.EXECUTE_WEBHOOK,-])--async function getQueueName({ platformId, projectId, jobType }: GetQueueNameParams, log: FastifyBaseLogger): Promise<string> {- if (!isNil(platformId) && !isNil(projectId) && !isNil(jobType) && PROJECT_GROUP_ROUTABLE_JOB_TYPES.has(jobType)) {- const workerGroupsEnabled = await workerGroupService(log).isWorkerGroupsEnabled({ platformId })- if (workerGroupsEnabled) {- const projectGroupId = await projectWorkerGroupService(log).getProjectWorkerGroup({ projectId, platformId })- if (!isNil(projectGroupId)) {- return getProjectGroupQueueName(projectGroupId)- }- }- }- if (!platformId) {- return QueueName.WORKER_JOBS- }- const groupId = await workerGroupService(log).getWorkerGroupId({ platformId })- if (isNil(groupId)) {- return QueueName.WORKER_JOBS- }- return getPlatformGroupQueueName(groupId)-}--export enum JobType {REPEATING = 'repeating',ONE_TIME = 'one_time',}-type GetQueueNameParams = {- platformId: string | null- projectId?: string | null- jobType?: WorkerJobType-}-type RemoveOneTimeJobParams = {jobId: ApIdplatformId: string | nulldiff --git a/packages/server/api/src/app/workers/job/index.ts b/packages/server/api/src/app/workers/job/index.tsindex 78fd58116a8..fc72837bec1 100644--- a/packages/server/api/src/app/workers/job/index.ts+++ b/packages/server/api/src/app/workers/job/index.ts@@ -1,22 +1,10 @@import {- isNil,JobData,RunEnvironment,StreamStepProgress,- WorkerGroupScope,} from '@activepieces/shared'import { z } from 'zod'-export const parseWorkerGroupValue = ({ value, projectWorker }: { value: string | undefined, projectWorker: boolean }): WorkerGroupAssignment | null => {- if (isNil(value) || value.length === 0) {- return null- }- return {- scope: projectWorker ? WorkerGroupScope.PROJECT : WorkerGroupScope.PLATFORM,- id: value,- }-}-export * from './runs-metadata-queue-factory'export enum JobStatus {@@ -30,15 +18,6 @@ export enum QueueName {BARRIER_EVALUATION = 'barrierEvaluation',}-export const getPlatformGroupQueueName = (workerGroupId: string): string => {- // TODO Rename this to workerGroups-workerGroupId-jobs in the future and migrate existings jobs there.- return `platform-${workerGroupId}-jobs`-}--export const getProjectGroupQueueName = (workerGroupId: string): string => {- return `project-${workerGroupId}-jobs`-}-export const ApQueueJob = z.object({id: z.string(),data: z.custom<JobData>(),@@ -74,9 +53,3 @@ export const SubmitPayloadsRequest = z.object({})export type SubmitPayloadsRequest = z.infer<typeof SubmitPayloadsRequest>---export type WorkerGroupAssignment = {- scope: WorkerGroupScope- id: string-}diff --git a/packages/server/api/src/app/workers/machine/machine-controller.ts b/packages/server/api/src/app/workers/machine/machine-controller.tsindex d42ed6fde0c..358296f63b0 100644--- a/packages/server/api/src/app/workers/machine/machine-controller.ts+++ b/packages/server/api/src/app/workers/machine/machine-controller.ts@@ -6,10 +6,11 @@ import { z } from 'zod'import { securityAccess } from '../../core/security/authorization/fastify-security'import { websocketService } from '../../core/websockets.service'import { system } from '../../helper/system/system'-import { parseWorkerGroupValue, QueueName } from '../job'+import { QueueName } from '../job'import { jobBroker } from '../job-queue/job-broker'import { jobQueue } from '../job-queue/job-queue'import { createHandlers } from '../rpc/worker-rpc-service'+import { workerGroupQueues } from '../worker-groups/worker-group-queues'import { machineService } from './machine-service'export const workerMachineController: FastifyPluginAsyncZod = async (app) => {@@ -18,7 +19,7 @@ export const workerMachineController: FastifyPluginAsyncZod = async (app) => {return async (request: WorkerMachineHealthcheckRequest, _principal, _projectId, callback?: (data: unknown) => void) => {const rawWorkerGroupValue = socket.handshake.auth?.workerGroupIdconst projectWorker = socket.handshake.auth?.projectWorker === true- const assignment = parseWorkerGroupValue({ value: typeof rawWorkerGroupValue === 'string' ? rawWorkerGroupValue : undefined, projectWorker })+ const assignment = workerGroupQueues.parseWorkerGroupValue({ value: typeof rawWorkerGroupValue === 'string' ? rawWorkerGroupValue : undefined, projectWorker })const response = await machineService(app.log).onConnection(request, assignment)callback?.(response)createRpcServer<WorkerToApiContract>(socket, createHandlers(app.log, assignment, socket.id), app.log)diff --git a/packages/server/api/src/app/workers/machine/machine-service.ts b/packages/server/api/src/app/workers/machine/machine-service.tsindex 3d91991b0fd..7380a446cbc 100644--- a/packages/server/api/src/app/workers/machine/machine-service.ts+++ b/packages/server/api/src/app/workers/machine/machine-service.ts@@ -3,11 +3,11 @@ import { apVersionUtil } from '@activepieces/server-utils'import { ExecutionMode, NetworkMode, WorkerGroupScope, WorkerMachineHealthcheckRequest, WorkerMachineStatus, WorkerMachineType, WorkerMachineWithStatus, WorkerSettingsResponse } from '@activepieces/shared'import { FastifyBaseLogger } from 'fastify'-import { workerGroupService } from '../../ee/platform/platform-plan/worker-group.service'import { domainHelper } from '../../helper/domain-helper'import { system } from '../../helper/system/system'import { AppSystemProp } from '../../helper/system/system-props'-import { WorkerGroupAssignment } from '../job'+import { platformWorkerGroupService } from '../worker-groups/platform-worker-group.service'+import { WorkerGroupAssignment } from '../worker-groups/worker-group-queues'import { workerMachineCache } from './machine-cache'import { parseWorkerConcurrency, workerCapacity } from './worker-capacity'import { workerLiveness } from './worker-liveness'@@ -95,7 +95,7 @@ export const machineService = (log: FastifyBaseLogger) => {await workerMachineCache().delete(offlineWorkers.map(worker => worker.id))- const platformWorkerGroupId = await workerGroupService(log).getWorkerGroupId({ platformId })+ const platformWorkerGroupId = await platformWorkerGroupService(log).getWorkerGroupId({ platformId })return onlineWorkers.filter(worker => {if (worker.workerGroupScope === WorkerGroupScope.PLATFORM) {diff --git a/packages/server/api/src/app/workers/rpc/worker-rpc-service.ts b/packages/server/api/src/app/workers/rpc/worker-rpc-service.tsindex 63bc70c901f..81e319e1600 100644--- a/packages/server/api/src/app/workers/rpc/worker-rpc-service.ts+++ b/packages/server/api/src/app/workers/rpc/worker-rpc-service.ts@@ -1,6 +1,6 @@import { assertNotNullOrUndefined, isNil, spreadIfDefined } from '@activepieces/core-utils'import { apVersionUtil, onCallService, UNKNOWN_VERSION } from '@activepieces/server-utils'-import { ExecutionType, FileCompression, FileLocation, FileType, FlowOperationType, FlowStatus, WebsocketClientEvent, WorkerGroupScope, WorkerToApiContract } from '@activepieces/shared'+import { ExecutionType, FileCompression, FileLocation, FileType, FlowOperationType, FlowStatus, WebsocketClientEvent, WorkerToApiContract } from '@activepieces/shared'import { FastifyBaseLogger } from 'fastify'import { aiRpcHandlers } from '../../ai/ai-rpc-handlers'import { websocketService } from '../../core/websockets.service'@@ -27,23 +27,15 @@ import { dedupeService } from '../../trigger/dedupe-service'import { triggerEventService } from '../../trigger/trigger-events/trigger-event.service'import { triggerRunStats } from '../../trigger/trigger-run/trigger-run-stats'import { triggerSourceService } from '../../trigger/trigger-source/trigger-source-service'-import { getPlatformGroupQueueName, getProjectGroupQueueName, QueueName, WorkerGroupAssignment } from '../job'import { jobBroker } from '../job-queue/job-broker'import { machineService } from '../machine/machine-service'+import { WorkerGroupAssignment } from '../worker-groups/worker-group-queues'+import { workerGroupRouting } from '../worker-groups/worker-group-routing'const FLOW_BUNDLE_PUBLISH_CLAIM_TTL_SECONDS = 60const getFlowBundlePublishClaimKey = (flowVersionId: string): string => `flow_bundle_publish_claim:${flowVersionId}`-const getPollQueueName = (assignment: WorkerGroupAssignment | null): string => {- if (isNil(assignment)) {- return QueueName.WORKER_JOBS- }- return assignment.scope === WorkerGroupScope.PROJECT- ? getProjectGroupQueueName(assignment.id)- : getPlatformGroupQueueName(assignment.id)-}-let pagedForUnreadableAppVersion = falsefunction pageOnceForUnreadableAppVersion(log: FastifyBaseLogger, appVersion: string): void {@@ -87,7 +79,7 @@ export function createHandlers(log: FastifyBaseLogger, assignment: WorkerGroupAsif (!workerVersionIsCompatible({ log, workerVersion: input.workerProps.version, workerId: input.workerId, rpcMethod: 'poll' })) {return null}- const pollQueueName = getPollQueueName(assignment)+ const pollQueueName = workerGroupRouting.resolveQueueForWorker(assignment)const job = await jobBroker(log).poll(pollQueueName, connectionId)if (job) {log.info({ worker: { id: input.workerId }, job: { id: job.jobId, type: job.jobData.jobType } }, '[workerRpc#poll] Returning job to worker')diff --git a/packages/server/api/src/app/ee/platform/platform-plan/worker-group.service.ts b/packages/server/api/src/app/workers/worker-groups/platform-worker-group.service.tssimilarity index 83%rename from packages/server/api/src/app/ee/platform/platform-plan/worker-group.service.tsrename to packages/server/api/src/app/workers/worker-groups/platform-worker-group.service.tsindex e25761309b6..45374087aac 100644--- a/packages/server/api/src/app/ee/platform/platform-plan/worker-group.service.ts+++ b/packages/server/api/src/app/workers/worker-groups/platform-worker-group.service.ts@@ -1,19 +1,13 @@import { isNil } from '@activepieces/core-utils'import { apDayjsDuration } from '@activepieces/server-utils'import { FastifyBaseLogger } from 'fastify'-import { distributedStore } from '../../../database/redis-connections'-import { getPlatformGroupQueueName, QueueName } from '../../../workers/job'-import { platformQueueMigrationService } from '../../../workers/platform-queue-migration.service'-import { platformPlanRepo } from './platform-plan.service'+import { distributedStore } from '../../database/redis-connections'+import { platformPlanRepo } from '../../ee/platform/platform-plan/platform-plan.service'+import { QueueName } from '../job'+import { platformQueueMigrationService } from './queue-migration.service'+import { workerGroupQueues } from './worker-group-queues'-export const CANARY_WORKER_GROUP_ID = 'canary'--const NO_WORKER_GROUP_SENTINEL = '__none__'-const CACHE_TTL_SECONDS = apDayjsDuration(5, 'minute').asSeconds()-const getWorkerGroupCacheKey = (platformId: string): string => `platform:${platformId}:worker_group_id:v2`-const getWorkerGroupsEnabledCacheKey = (platformId: string): string => `platform:${platformId}:worker_groups_enabled`--export const workerGroupService = (log: FastifyBaseLogger) => ({+export const platformWorkerGroupService = (log: FastifyBaseLogger) => ({async isWorkerGroupsEnabled({ platformId }: { platformId: string }): Promise<boolean> {const cached = await distributedStore.get<string>(getWorkerGroupsEnabledCacheKey(platformId))if (!isNil(cached)) {@@ -70,9 +64,17 @@ export const workerGroupService = (log: FastifyBaseLogger) => ({},async moveJobsToTargetQueue({ platformId, workerGroupId }: { platformId: string, workerGroupId: string | null }): Promise<void> {- const currentGroupId = await workerGroupService(log).getWorkerGroupId({ platformId })- const targetQueue = isNil(workerGroupId) ? QueueName.WORKER_JOBS : getPlatformGroupQueueName(workerGroupId)- const fromQueueName = isNil(currentGroupId) ? QueueName.WORKER_JOBS : getPlatformGroupQueueName(currentGroupId)+ const currentGroupId = await platformWorkerGroupService(log).getWorkerGroupId({ platformId })+ const targetQueue = isNil(workerGroupId) ? QueueName.WORKER_JOBS : workerGroupQueues.getPlatformGroupQueueName(workerGroupId)+ const fromQueueName = isNil(currentGroupId) ? QueueName.WORKER_JOBS : workerGroupQueues.getPlatformGroupQueueName(currentGroupId)await platformQueueMigrationService(log).migrateJobs({ fromQueueName, toQueueName: targetQueue, platformId })},})++const getWorkerGroupCacheKey = (platformId: string): string => `platform:${platformId}:worker_group_id:v2`+const getWorkerGroupsEnabledCacheKey = (platformId: string): string => `platform:${platformId}:worker_groups_enabled`++export const CANARY_WORKER_GROUP_ID = 'canary'++const NO_WORKER_GROUP_SENTINEL = '__none__'+const CACHE_TTL_SECONDS = apDayjsDuration(5, 'minute').asSeconds()diff --git a/packages/server/api/src/app/workers/worker-groups/project-worker-group.service.ts b/packages/server/api/src/app/workers/worker-groups/project-worker-group.service.tsnew file mode 100644index 00000000000..a36ba595eed--- /dev/null+++ b/packages/server/api/src/app/workers/worker-groups/project-worker-group.service.ts@@ -0,0 +1,67 @@+import { isNil, spreadIfDefined, tryCatch } from '@activepieces/core-utils'+import { apDayjsDuration } from '@activepieces/server-utils'+import { FastifyBaseLogger } from 'fastify'+import { distributedStore } from '../../database/redis-connections'+import { projectRepo } from '../../project/project-repo'+import { QueueName } from '../job'+import { platformWorkerGroupService } from './platform-worker-group.service'+import { platformQueueMigrationService } from './queue-migration.service'+import { workerGroupQueues } from './worker-group-queues'++export const projectWorkerGroupService = (log: FastifyBaseLogger) => ({+ async getProjectWorkerGroup({ projectId, platformId }: { projectId: string, platformId?: string | null }): Promise<string | null> {+ const cached = await distributedStore.get<string>(getProjectWorkerGroupCacheKey(projectId))+ if (!isNil(cached)) {+ return cached === NO_WORKER_GROUP_SENTINEL ? null : cached+ }++ const project = await projectRepo().findOne({+ select: ['workerGroupId'],+ where: { id: projectId, ...spreadIfDefined('platformId', platformId ?? undefined) },+ })++ const workerGroupId = project?.workerGroupId ?? null+ await distributedStore.put(getProjectWorkerGroupCacheKey(projectId), workerGroupId ?? NO_WORKER_GROUP_SENTINEL, CACHE_TTL_SECONDS)+ return workerGroupId+ },+ async getWorkerGroupProjects({ workerGroupId }: { workerGroupId: string }): Promise<string[]> {+ const projects = await projectRepo().find({+ select: ['id'],+ where: { workerGroupId },+ })+ return projects.map((p) => p.id)+ },++ async invalidate({ projectId }: { projectId: string }): Promise<void> {+ await distributedStore.delete(getProjectWorkerGroupCacheKey(projectId))+ },++ async migrateProjectToGroup({ projectId, platformId, fromGroupId, toGroupId }: MigrateProjectToGroupParams): Promise<void> {+ const ungroupedQueueName = await resolveUngroupedQueueName({ platformId, log })+ const { error } = await tryCatch(() => platformQueueMigrationService(log).migrateProjectJobs({+ fromQueueName: isNil(fromGroupId) ? ungroupedQueueName : workerGroupQueues.getProjectGroupQueueName(fromGroupId),+ toQueueName: isNil(toGroupId) ? ungroupedQueueName : workerGroupQueues.getProjectGroupQueueName(toGroupId),+ projectId,+ }))+ if (error) {+ log.error({ project: { id: projectId }, platform: { id: platformId }, error }, '[projectWorkerGroupService#migrateProjectToGroup] Failed to migrate waiting jobs to the new worker group queue')+ }+ },+})++async function resolveUngroupedQueueName({ platformId, log }: { platformId: string, log: FastifyBaseLogger }): Promise<string> {+ const platformGroupId = await platformWorkerGroupService(log).getWorkerGroupId({ platformId })+ return isNil(platformGroupId) ? QueueName.WORKER_JOBS : workerGroupQueues.getPlatformGroupQueueName(platformGroupId)+}++const getProjectWorkerGroupCacheKey = (projectId: string): string => `project:${projectId}:worker_group`++const NO_WORKER_GROUP_SENTINEL = '__none__'+const CACHE_TTL_SECONDS = apDayjsDuration(5, 'minute').asSeconds()++type MigrateProjectToGroupParams = {+ projectId: string+ platformId: string+ fromGroupId: string | null+ toGroupId: string | null+}diff --git a/packages/server/api/src/app/workers/platform-queue-migration.service.ts b/packages/server/api/src/app/workers/worker-groups/queue-migration.service.tssimilarity index 98%rename from packages/server/api/src/app/workers/platform-queue-migration.service.tsrename to packages/server/api/src/app/workers/worker-groups/queue-migration.service.tsindex ee2a40669f9..010ca77f7e7 100644--- a/packages/server/api/src/app/workers/platform-queue-migration.service.ts+++ b/packages/server/api/src/app/workers/worker-groups/queue-migration.service.ts@@ -1,7 +1,8 @@import { isNil } from '@activepieces/core-utils'import { Job, Queue } from 'bullmq'import { FastifyBaseLogger } from 'fastify'-import { jobQueue, PROJECT_GROUP_ROUTABLE_JOB_TYPES } from './job-queue/job-queue'+import { jobQueue } from '../job-queue/job-queue'+import { PROJECT_GROUP_ROUTABLE_JOB_TYPES } from './worker-group-queues'export const platformQueueMigrationService = (log: FastifyBaseLogger) => ({async migrateJobs({ fromQueueName, toQueueName, platformId, batchSize = 200 }: MigrateJobsParams): Promise<void> {@@ -110,7 +111,7 @@ async function migrateSchedulers({ sourceQueue, targetQueue, platformId, batchSimigrationFailed = true}})-+}offset += skippeddiff --git a/packages/server/api/src/app/workers/worker-groups/worker-group-queues.ts b/packages/server/api/src/app/workers/worker-groups/worker-group-queues.tsnew file mode 100644index 00000000000..3248d23f444--- /dev/null+++ b/packages/server/api/src/app/workers/worker-groups/worker-group-queues.ts@@ -0,0 +1,37 @@+import { isNil } from '@activepieces/core-utils'+import { WorkerGroupScope, WorkerJobType } from '@activepieces/shared'++const parseWorkerGroupValue = ({ value, projectWorker }: { value: string | undefined, projectWorker: boolean }): WorkerGroupAssignment | null => {+ if (isNil(value) || value.length === 0) {+ return null+ }+ return {+ scope: projectWorker ? WorkerGroupScope.PROJECT : WorkerGroupScope.PLATFORM,+ id: value,+ }+}++const getPlatformGroupQueueName = (workerGroupId: string): string => {+ // TODO Rename this to workerGroups-workerGroupId-jobs in the future and migrate existings jobs there.+ return `platform-${workerGroupId}-jobs`+}++const getProjectGroupQueueName = (workerGroupId: string): string => {+ return `project-${workerGroupId}-jobs`+}++export const workerGroupQueues = {+ parseWorkerGroupValue,+ getPlatformGroupQueueName,+ getProjectGroupQueueName,+}++export const PROJECT_GROUP_ROUTABLE_JOB_TYPES = new Set<WorkerJobType>([+ WorkerJobType.EXECUTE_FLOW,+ WorkerJobType.EXECUTE_WEBHOOK,+])++export type WorkerGroupAssignment = {+ scope: WorkerGroupScope+ id: string+}diff --git a/packages/server/api/src/app/workers/worker-groups/worker-group-routing.ts b/packages/server/api/src/app/workers/worker-groups/worker-group-routing.tsnew file mode 100644index 00000000000..9e64928d669--- /dev/null+++ b/packages/server/api/src/app/workers/worker-groups/worker-group-routing.ts@@ -0,0 +1,48 @@+import { isNil } from '@activepieces/core-utils'+import { WorkerGroupScope, WorkerJobType } from '@activepieces/shared'+import { FastifyBaseLogger } from 'fastify'+import { QueueName } from '../job'+import { platformWorkerGroupService } from './platform-worker-group.service'+import { projectWorkerGroupService } from './project-worker-group.service'+import { PROJECT_GROUP_ROUTABLE_JOB_TYPES, WorkerGroupAssignment, workerGroupQueues } from './worker-group-queues'++const resolveQueueForJob = async ({ platformId, projectId, jobType, log }: ResolveQueueForJobParams): Promise<string> => {+ if (!isNil(platformId) && !isNil(projectId) && !isNil(jobType) && PROJECT_GROUP_ROUTABLE_JOB_TYPES.has(jobType)) {+ const workerGroupsEnabled = await platformWorkerGroupService(log).isWorkerGroupsEnabled({ platformId })+ if (workerGroupsEnabled) {+ const projectGroupId = await projectWorkerGroupService(log).getProjectWorkerGroup({ projectId, platformId })+ if (!isNil(projectGroupId)) {+ return workerGroupQueues.getProjectGroupQueueName(projectGroupId)+ }+ }+ }+ if (!platformId) {+ return QueueName.WORKER_JOBS+ }+ const groupId = await platformWorkerGroupService(log).getWorkerGroupId({ platformId })+ if (isNil(groupId)) {+ return QueueName.WORKER_JOBS+ }+ return workerGroupQueues.getPlatformGroupQueueName(groupId)+}++const resolveQueueForWorker = (assignment: WorkerGroupAssignment | null): string => {+ if (isNil(assignment)) {+ return QueueName.WORKER_JOBS+ }+ return assignment.scope === WorkerGroupScope.PROJECT+ ? workerGroupQueues.getProjectGroupQueueName(assignment.id)+ : workerGroupQueues.getPlatformGroupQueueName(assignment.id)+}++export const workerGroupRouting = {+ resolveQueueForJob,+ resolveQueueForWorker,+}++type ResolveQueueForJobParams = {+ platformId: string | null+ projectId?: string | null+ jobType?: WorkerJobType+ log: FastifyBaseLogger+}diff --git a/packages/server/api/test/integration/ce/workers/platform-queue-migration.test.ts b/packages/server/api/test/integration/ce/workers/platform-queue-migration.test.tsindex a09924488fb..44455828cea 100644--- a/packages/server/api/test/integration/ce/workers/platform-queue-migration.test.ts+++ b/packages/server/api/test/integration/ce/workers/platform-queue-migration.test.ts@@ -1,9 +1,9 @@import { apId } from '@activepieces/core-utils'import { FlowTriggerType, LATEST_JOB_DATA_SCHEMA_VERSION, WorkerJobType } from '@activepieces/shared'import { FastifyInstance } from 'fastify'-import { getPlatformGroupQueueName } from '../../../../src/app/workers/job'+import { workerGroupQueues } from '../../../../src/app/workers/worker-groups/worker-group-queues'import { jobQueue } from '../../../../src/app/workers/job-queue/job-queue'-import { platformQueueMigrationService } from '../../../../src/app/workers/platform-queue-migration.service'+import { platformQueueMigrationService } from '../../../../src/app/workers/worker-groups/queue-migration.service'import { setupTestEnvironment, teardownTestEnvironment } from '../../../helpers/test-setup'let app: FastifyInstance@@ -21,8 +21,8 @@ describe('platformQueueMigrationService', () => {let toQueueName: stringbeforeEach(() => {- fromQueueName = getPlatformGroupQueueName(apId())- toQueueName = getPlatformGroupQueueName(apId())+ fromQueueName = workerGroupQueues.getPlatformGroupQueueName(apId())+ toQueueName = workerGroupQueues.getPlatformGroupQueueName(apId())})afterEach(async () => {@@ -35,7 +35,7 @@ describe('platformQueueMigrationService', () => {it('returns early without touching queues when fromQueueName equals toQueueName', async () => {const platformId = apId()const flowVersionId = apId()- const sameQueue = getPlatformGroupQueueName(apId())+ const sameQueue = workerGroupQueues.getPlatformGroupQueueName(apId())const queue = await jobQueue(app.log).getOrCreateQueue({ queueName: sameQueue })await queue.upsertJobScheduler(diff --git a/packages/server/api/test/unit/app/core/canary/canary-proxy.integration.test.ts b/packages/server/api/test/unit/app/core/canary/canary-proxy.integration.test.tsindex fdb98067faa..66be0f74dbf 100644--- a/packages/server/api/test/unit/app/core/canary/canary-proxy.integration.test.ts+++ b/packages/server/api/test/unit/app/core/canary/canary-proxy.integration.test.ts@@ -33,8 +33,8 @@ vi.mock('../../../../../src/app/helper/system/system', () => ({},}))-vi.mock('../../../../../src/app/ee/platform/platform-plan/worker-group.service', () => ({- workerGroupService: () => ({+vi.mock('../../../../../src/app/workers/worker-groups/platform-worker-group.service', () => ({+ platformWorkerGroupService: () => ({isCanaryPlatform: mockIsCanaryPlatform,}),}))diff --git a/packages/server/api/test/unit/app/core/canary/canary-routing.middleware.test.ts b/packages/server/api/test/unit/app/core/canary/canary-routing.middleware.test.tsindex 724e1a3c52f..38076f7f7bc 100644--- a/packages/server/api/test/unit/app/core/canary/canary-routing.middleware.test.ts+++ b/packages/server/api/test/unit/app/core/canary/canary-routing.middleware.test.ts@@ -16,8 +16,8 @@ vi.mock('../../../../../src/app/helper/system/system', () => ({},}))-vi.mock('../../../../../src/app/ee/platform/platform-plan/worker-group.service', () => ({- workerGroupService: () => ({+vi.mock('../../../../../src/app/workers/worker-groups/platform-worker-group.service', () => ({+ platformWorkerGroupService: () => ({isCanaryPlatform: mockIsCanaryPlatform,}),}))diff --git a/packages/server/api/test/unit/app/core/canary/worker-group.service.test.ts b/packages/server/api/test/unit/app/core/canary/platform-worker-group.service.test.tssimilarity index 95%rename from packages/server/api/test/unit/app/core/canary/worker-group.service.test.tsrename to packages/server/api/test/unit/app/core/canary/platform-worker-group.service.test.tsindex 9bc80a48d9e..4ba22f76152 100644--- a/packages/server/api/test/unit/app/core/canary/worker-group.service.test.ts+++ b/packages/server/api/test/unit/app/core/canary/platform-worker-group.service.test.ts@@ -41,16 +41,16 @@ const mockLog: FastifyBaseLogger = {level: 'info',} as unknown as FastifyBaseLogger-type WorkerGroupService = ReturnType<typeof import('../../../../../src/app/ee/platform/platform-plan/worker-group.service').workerGroupService>+type WorkerGroupService = ReturnType<typeof import('../../../../../src/app/workers/worker-groups/platform-worker-group.service').platformWorkerGroupService>const CANARY_WORKER_GROUP_ID = 'canary'async function loadService(): Promise<WorkerGroupService> {- const mod = await import('../../../../../src/app/ee/platform/platform-plan/worker-group.service')- return mod.workerGroupService(mockLog)+ const mod = await import('../../../../../src/app/workers/worker-groups/platform-worker-group.service')+ return mod.platformWorkerGroupService(mockLog)}-describe('workerGroupService', () => {+describe('platformWorkerGroupService', () => {let service: WorkerGroupServicebeforeEach(async () => {diff --git a/packages/server/api/test/unit/app/workers/machine/machine-list-filter.test.ts b/packages/server/api/test/unit/app/workers/machine/machine-list-filter.test.tsindex 00e0bbbed5c..39e2f7efb9f 100644--- a/packages/server/api/test/unit/app/workers/machine/machine-list-filter.test.ts+++ b/packages/server/api/test/unit/app/workers/machine/machine-list-filter.test.ts@@ -30,8 +30,8 @@ vi.mock('../../../../../src/app/workers/machine/machine-cache', () => ({const mockGetWorkerGroupId = vi.fn()-vi.mock('../../../../../src/app/ee/platform/platform-plan/worker-group.service', () => ({- workerGroupService: () => ({+vi.mock('../../../../../src/app/workers/worker-groups/platform-worker-group.service', () => ({+ platformWorkerGroupService: () => ({getWorkerGroupId: (...args: unknown[]) => mockGetWorkerGroupId(...args),}),}))