Skip to content

The open alternative to Salesforce, designed for AI.

Let application workflows run on a schedule (#27699)

Thomas Trompette024c8b86476d
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-manifest/application-manifest-migration.service.ts b/packages/twenty-server/src/engine/core-modules/application/application-manifest/application-manifest-migration.service.ts
index e6c3dd0d658..64eda7d2681 100644
--- a/packages/twenty-server/src/engine/core-modules/application/application-manifest/application-manifest-migration.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/application-manifest/application-manifest-migration.service.ts
@@ -6,6 +6,7 @@ import { FeatureFlagKey } from 'twenty-shared/types';
import { isDefined } from 'twenty-shared/utils';
import { ComputeApplicationManifestAllUniversalFlatEntityMapsService } from 'src/engine/core-modules/application/application-manifest/services/compute-application-manifest-all-universal-flat-entity-maps.service';
+import { buildApplicationWorkflowCronTriggerCacheEntries } from 'src/engine/core-modules/application/application-manifest/utils/build-application-workflow-cron-trigger-cache-entries.util';
import { addWorkflowManifestsToFlatEntityMapsOrThrow } from 'src/engine/core-modules/application/application-manifest/utils/add-workflow-manifests-to-flat-entity-maps-or-throw.util';
import { preallocateWorkflowReferenceIds } from 'src/engine/core-modules/application/application-manifest/utils/preallocate-workflow-reference-ids.util';
import { buildAllFlatEntityOperationRecordByMetadataNameFromFromTo } from 'src/engine/core-modules/application/application-manifest/utils/build-all-flat-entity-operation-record-by-metadata-name-from-from-to.util';
@@ -19,6 +20,7 @@ import {
import { ApplicationService } from 'src/engine/core-modules/application/application.service';
import { type FlatApplication } from 'src/engine/core-modules/application/types/flat-application.type';
import { LoggerService } from 'src/engine/core-modules/logger/logger.service';
+import { WorkflowVersionCoreSyncService } from 'src/engine/core-modules/workflow/services/workflow-version-core-sync.service';
import { getMetadataFlatEntityMapsKey } from 'src/engine/metadata-modules/flat-entity/utils/get-metadata-flat-entity-maps-key.util';
import { WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';
import { TWENTY_STANDARD_APPLICATION } from 'src/engine/workspace-manager/twenty-standard-application/constants/twenty-standard-applications';
@@ -34,6 +36,7 @@ export class ApplicationManifestMigrationService {
private readonly applicationService: ApplicationService,
private readonly computeManifestFlatEntityMapsService: ComputeApplicationManifestAllUniversalFlatEntityMapsService,
private readonly logger: LoggerService,
+ private readonly workflowVersionCoreSyncService: WorkflowVersionCoreSyncService,
) {}
async syncPreInstallLogicFunctionFromManifest({
@@ -216,7 +219,7 @@ export class ApplicationManifestMigrationService {
})
: {};
- addWorkflowManifestsToFlatEntityMapsOrThrow({
+ const applicationWorkflows = addWorkflowManifestsToFlatEntityMapsOrThrow({
workflows: manifest.workflows ?? [],
ownerFlatApplication,
fromAllFlatEntityMaps,
@@ -281,6 +284,13 @@ export class ApplicationManifestMigrationService {
ownerFlatApplication,
inferDeletionFromMissingEntities,
});
+
+ await this.workflowVersionCoreSyncService.publishCronTriggerCacheEntries(
+ buildApplicationWorkflowCronTriggerCacheEntries({
+ workspaceId,
+ workflows: applicationWorkflows,
+ }),
+ );
}
return {
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-manifest/application-manifest.module.ts b/packages/twenty-server/src/engine/core-modules/application/application-manifest/application-manifest.module.ts
index be88a9d53b3..6bac36669aa 100644
--- a/packages/twenty-server/src/engine/core-modules/application/application-manifest/application-manifest.module.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/application-manifest/application-manifest.module.ts
@@ -17,6 +17,7 @@ import { ApplicationTranslationModule } from 'src/engine/core-modules/applicatio
import { SecretEncryptionModule } from 'src/engine/core-modules/secret-encryption/secret-encryption.module';
import { SdkClientModule } from 'src/engine/core-modules/sdk-client/sdk-client.module';
import { FrontComponentEntity } from 'src/engine/metadata-modules/front-component/entities/front-component.entity';
+import { WorkflowVersionCoreModule } from 'src/engine/core-modules/workflow/workflow-version-core.module';
import { WorkspaceCacheModule } from 'src/engine/workspace-cache/workspace-cache.module';
import { WorkspaceMigrationModule } from 'src/engine/workspace-manager/workspace-migration/workspace-migration.module';
import { provideWorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/provide-workspace-scoped-repository';
@@ -32,6 +33,7 @@ import { provideWorkspaceScopedRepository } from 'src/engine/twenty-orm/workspac
ApplicationTranslationModule,
SecretEncryptionModule,
SdkClientModule,
+ WorkflowVersionCoreModule,
WorkspaceCacheModule,
WorkspaceMigrationModule,
],
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/__tests__/from-workflow-manifest-to-universal-flat-workflow-or-throw.util.spec.ts b/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/__tests__/from-workflow-manifest-to-universal-flat-workflow-or-throw.util.spec.ts
index c1d8be2c6f4..c147504149d 100644
--- a/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/__tests__/from-workflow-manifest-to-universal-flat-workflow-or-throw.util.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/__tests__/from-workflow-manifest-to-universal-flat-workflow-or-throw.util.spec.ts
@@ -208,6 +208,49 @@ describe('application workflow definitions', () => {
).toThrow('Workflow trigger: missing object');
});
+ it('keeps the cron schedule of a scheduled workflow', () => {
+ const { version } = convert({
+ ...options,
+ manifest: {
+ ...manifest,
+ version: {
+ ...manifest.version,
+ trigger: {
+ universalIdentifier: TRIGGER_ID,
+ type: 'CRON',
+ nextStepIds: [STEP_ID],
+ settings: { type: 'HOURS', schedule: { hour: 2, minute: 30 } },
+ },
+ },
+ },
+ });
+
+ expect(version.triggers?.[0]).toMatchObject({
+ type: 'CRON',
+ settings: { type: 'HOURS', schedule: { hour: 2, minute: 30 } },
+ });
+ });
+
+ it('refuses a custom cron pattern the scheduler cannot parse', () => {
+ expect(() =>
+ convert({
+ ...options,
+ manifest: {
+ ...manifest,
+ version: {
+ ...manifest.version,
+ trigger: {
+ universalIdentifier: TRIGGER_ID,
+ type: 'CRON',
+ nextStepIds: [STEP_ID],
+ settings: { type: 'CUSTOM', pattern: 'every monday' },
+ },
+ },
+ },
+ }),
+ ).toThrow("Workflow trigger: Cron pattern 'every monday' is invalid");
+ });
+
it('rejects an unsupported trigger on the server too', () => {
const invalid = structuredClone(manifest);
Object.assign(invalid.version.trigger, { type: 'WEBHOOK' });
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/from-workflow-trigger-manifest-to-trigger-or-throw.util.ts b/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/from-workflow-trigger-manifest-to-trigger-or-throw.util.ts
index 499da4b8f1d..4331c7eedd0 100644
--- a/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/from-workflow-trigger-manifest-to-trigger-or-throw.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/from-workflow-trigger-manifest-to-trigger-or-throw.util.ts
@@ -1,13 +1,21 @@
+import { msg } from '@lingui/core/macro';
import { type WorkflowTriggerManifest } from 'twenty-shared/application';
import { isDefined } from 'twenty-shared/utils';
import { type WorkflowManifestReferences } from 'src/engine/core-modules/application/application-manifest/types/workflow-manifest-references.type';
import { buildWorkflowManifestReferenceResolvers } from 'src/engine/core-modules/application/application-manifest/utils/build-workflow-manifest-reference-resolvers.util';
import {
+ ApplicationException,
+ ApplicationExceptionCode,
+} from 'src/engine/core-modules/application/application.exception';
+import {
+ type WorkflowCronTrigger,
type WorkflowManualTrigger,
type WorkflowTrigger,
WorkflowTriggerType,
} from 'src/modules/workflow/workflow-trigger/types/workflow-trigger.type';
+import { computeCronPatternFromSchedule } from 'src/modules/workflow/workflow-trigger/utils/compute-cron-pattern-from-schedule';
+import { assertNever } from 'src/utils/assert';
type WorkflowManifestReferenceResolvers = ReturnType<
typeof buildWorkflowManifestReferenceResolvers
@@ -18,6 +26,8 @@ type ManualTriggerManifest = Extract<
{ type: 'MANUAL' }
>;
+type CronTriggerManifest = Extract<WorkflowTriggerManifest, { type: 'CRON' }>;
+
const fromManualTriggerManifest = ({
trigger,
resolvers,
@@ -56,6 +66,33 @@ const fromManualTriggerManifest = ({
} satisfies WorkflowManualTrigger;
};
+const fromCronTriggerManifestOrThrow = (
+ trigger: CronTriggerManifest,
+): WorkflowCronTrigger => {
+ const { settings, ...identity } = trigger;
+ const cronTrigger = {
+ ...identity,
+ name: 'On a schedule',
+ type: WorkflowTriggerType.CRON,
+ position: { x: 0, y: 0 },
+ settings: { ...settings, outputSchema: {} },
+ } satisfies WorkflowCronTrigger;
+
+ try {
+ computeCronPatternFromSchedule(cronTrigger);
+ } catch (error) {
+ throw new ApplicationException(
+ `Workflow trigger: ${error instanceof Error ? error.message : String(error)}`,
+ ApplicationExceptionCode.INVALID_INPUT,
+ {
+ userFriendlyMessage: msg`The workflow schedule is invalid.`,
+ },
+ );
+ }
+
+ return cronTrigger;
+};
+
export const fromWorkflowTriggerManifestToTriggerOrThrow = ({
trigger,
references,
@@ -68,5 +105,12 @@ export const fromWorkflowTriggerManifestToTriggerOrThrow = ({
subject: 'Workflow trigger',
});
- return fromManualTriggerManifest({ trigger, resolvers });
+ switch (trigger.type) {
+ case 'MANUAL':
+ return fromManualTriggerManifest({ trigger, resolvers });
+ case 'CRON':
+ return fromCronTriggerManifestOrThrow(trigger);
+ default:
+ return assertNever(trigger);
+ }
};
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/__tests__/build-application-workflow-cron-trigger-cache-entries.util.spec.ts b/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/__tests__/build-application-workflow-cron-trigger-cache-entries.util.spec.ts
new file mode 100644
index 00000000000..7ed4109c6d8
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/__tests__/build-application-workflow-cron-trigger-cache-entries.util.spec.ts
@@ -0,0 +1,48 @@
+import { buildApplicationWorkflowCronTriggerCacheEntries } from 'src/engine/core-modules/application/application-manifest/utils/build-application-workflow-cron-trigger-cache-entries.util';
+import {
+ type WorkflowTrigger,
+ WorkflowTriggerType,
+} from 'src/modules/workflow/workflow-trigger/types/workflow-trigger.type';
+
+const WORKSPACE_ID = '20202020-1c25-4d02-bf25-6aeccf7ea419';
+
+const applicationWorkflow = (id: string, trigger: WorkflowTrigger) => ({
+ id,
+ flatUniversalWorkflowVersion: {
+ id: `${id.slice(0, -1)}9`,
+ triggers: [trigger],
+ },
+});
+
+describe('buildApplicationWorkflowCronTriggerCacheEntries', () => {
+ it('publishes only the scheduled workflows with their cron pattern', () => {
+ const entries = buildApplicationWorkflowCronTriggerCacheEntries({
+ workspaceId: WORKSPACE_ID,
+ workflows: [
+ applicationWorkflow('11111111-1111-4111-8111-111111111111', {
+ name: 'On a schedule',
+ type: WorkflowTriggerType.CRON,
+ settings: {
+ type: 'HOURS',
+ schedule: { hour: 2, minute: 30 },
+ outputSchema: {},
+ },
+ }),
+ applicationWorkflow('22222222-2222-4222-8222-222222222222', {
+ name: 'Manual trigger',
+ type: WorkflowTriggerType.MANUAL,
+ settings: { outputSchema: {} },
+ }),
+ ],
+ });
+
+ expect(entries).toEqual([
+ {
+ workspaceId: WORKSPACE_ID,
+ workflowId: '11111111-1111-4111-8111-111111111111',
+ coreWorkflowVersionId: '11111111-1111-4111-8111-111111111119',
+ pattern: '30 */2 * * *',
+ },
+ ]);
+ });
+});
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/add-workflow-manifests-to-flat-entity-maps-or-throw.util.ts b/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/add-workflow-manifests-to-flat-entity-maps-or-throw.util.ts
index c34472c6424..929ee12c606 100644
--- a/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/add-workflow-manifests-to-flat-entity-maps-or-throw.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/add-workflow-manifests-to-flat-entity-maps-or-throw.util.ts
@@ -14,6 +14,7 @@ import {
} from 'src/engine/core-modules/application/application.exception';
import { type FlatApplication } from 'src/engine/core-modules/application/types/flat-application.type';
import { type AllFlatEntityMaps } from 'src/engine/metadata-modules/flat-entity/types/all-flat-entity-maps.type';
+import { type UniversalFlatWorkflow } from 'src/engine/workspace-manager/workspace-migration/universal-flat-entity/types/universal-flat-workflow.type';
import { type IdByUniversalIdentifierByMetadataName } from 'src/engine/workspace-manager/workspace-migration/services/utils/enrich-create-workspace-migration-action-with-ids.util';
import { addUniversalFlatEntityToUniversalFlatEntityMapsThroughMutationOrThrow } from 'src/engine/workspace-manager/workspace-migration/universal-flat-entity/utils/add-universal-flat-entity-to-universal-flat-entity-maps-through-mutation-or-throw.util';
@@ -35,7 +36,7 @@ export const addWorkflowManifestsToFlatEntityMapsOrThrow = ({
idByUniversalIdentifierByMetadataName: IdByUniversalIdentifierByMetadataName;
isApplicationWorkflowsEnabled: boolean | undefined;
now: string;
-}): void => {
+}): (UniversalFlatWorkflow & { id: string })[] => {
if (workflows.length > 0 && !isApplicationWorkflowsEnabled) {
throw new ApplicationException(
'Application workflows are not enabled for this workspace',
@@ -48,6 +49,7 @@ export const addWorkflowManifestsToFlatEntityMapsOrThrow = ({
const applicationUniversalIdentifier =
ownerFlatApplication.universalIdentifier;
+ const applicationWorkflows: (UniversalFlatWorkflow & { id: string })[] = [];
if (workflows.length > 0) {
const references = prepareWorkflowManifestReferences({
@@ -89,6 +91,7 @@ export const addWorkflowManifestsToFlatEntityMapsOrThrow = ({
universalFlatEntityMapsToMutate:
toAllUniversalFlatEntityMaps.flatWorkflowMaps,
});
+ applicationWorkflows.push(workflow);
}
if (recordFieldErrors.length > 0) {
throw new ApplicationException(
@@ -100,4 +103,6 @@ export const addWorkflowManifestsToFlatEntityMapsOrThrow = ({
);
}
}
+
+ return applicationWorkflows;
};
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/build-application-workflow-cron-trigger-cache-entries.util.ts b/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/build-application-workflow-cron-trigger-cache-entries.util.ts
new file mode 100644
index 00000000000..6839d036cbc
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/build-application-workflow-cron-trigger-cache-entries.util.ts
@@ -0,0 +1,38 @@
+import { isDefined } from 'twenty-shared/utils';
+
+import { buildCoreDispatchIds } from 'src/engine/core-modules/workflow/utils/build-core-dispatch-ids.util';
+import { type CachedCronTrigger } from 'src/modules/workflow/workflow-trigger/automated-trigger/crons/types/cached-cron-trigger.type';
+import { WorkflowTriggerType } from 'src/modules/workflow/workflow-trigger/types/workflow-trigger.type';
+import { computeCronPatternFromSchedule } from 'src/modules/workflow/workflow-trigger/utils/compute-cron-pattern-from-schedule';
+import { type UniversalFlatWorkflowVersion } from 'src/engine/workspace-manager/workspace-migration/universal-flat-entity/types/universal-flat-workflow-version.type';
+
+export const buildApplicationWorkflowCronTriggerCacheEntries = ({
+ workspaceId,
+ workflows,
+}: {
+ workspaceId: string;
+ workflows: {
+ id: string;
+ flatUniversalWorkflowVersion?: Pick<
+ UniversalFlatWorkflowVersion,
+ 'triggers'
+ > & { id: string };
+ }[];
+}): CachedCronTrigger[] =>
+ workflows.flatMap((workflow) => {
+ const version = workflow.flatUniversalWorkflowVersion;
+ const trigger = version?.triggers?.[0];
+
+ if (!isDefined(version) || trigger?.type !== WorkflowTriggerType.CRON) {
+ return [];
+ }
+
+ return [
+ {
+ workspaceId,
+ workflowId: workflow.id,
+ pattern: computeCronPatternFromSchedule(trigger),
+ ...buildCoreDispatchIds({ coreWorkflowVersionId: version.id }),
+ },
+ ];
+ });
diff --git a/packages/twenty-server/src/engine/core-modules/workflow/services/core-workflow-lifecycle.workspace-service.ts b/packages/twenty-server/src/engine/core-modules/workflow/services/core-workflow-lifecycle.workspace-service.ts
index 3d1a1c2900a..92fc9d42210 100644
--- a/packages/twenty-server/src/engine/core-modules/workflow/services/core-workflow-lifecycle.workspace-service.ts
+++ b/packages/twenty-server/src/engine/core-modules/workflow/services/core-workflow-lifecycle.workspace-service.ts
@@ -58,6 +58,7 @@ import { AutomatedTriggerWorkspaceService } from 'src/modules/workflow/workflow-
import { type DatabaseEventTriggerSettings } from 'src/modules/workflow/workflow-trigger/automated-trigger/constants/automated-trigger-settings';
import { WORKFLOW_CRON_TRIGGER_CACHE_KEY } from 'src/modules/workflow/workflow-trigger/automated-trigger/crons/constants/workflow-cron-trigger-cache-key.constant';
import { type CachedCronTrigger } from 'src/modules/workflow/workflow-trigger/automated-trigger/crons/types/cached-cron-trigger.type';
+import { publishCronTriggerCacheEntry } from 'src/modules/workflow/workflow-trigger/automated-trigger/crons/utils/publish-cron-trigger-cache-entry.util';
import {
WorkflowTriggerException,
WorkflowTriggerExceptionCode,
@@ -921,24 +922,11 @@ export class CoreWorkflowLifecycleWorkspaceService {
}),
};
- try {
- await this.cacheStorageService.hashSetIfExists({
- key: WORKFLOW_CRON_TRIGGER_CACHE_KEY,
- field: resolved.coreWorkflow.id,
- value: JSON.stringify(cachedTrigger),
- });
- } catch (error) {
- this.logger.error(
- `Cron trigger cache entry not published for workflow ${workspaceWorkflowId}, dropping the cron cache so the next tick rebuilds it from the database`,
- error,
- );
-
- try {
- await this.cacheStorageService.del(WORKFLOW_CRON_TRIGGER_CACHE_KEY);
- } catch (invalidationError) {
- this.logger.error(invalidationError);
- }
- }
+ await publishCronTriggerCacheEntry({
+ cacheStorageService: this.cacheStorageService,
+ cachedTrigger,
+ logger: this.logger,
+ });
}
private async disableAutomatedTrigger({
diff --git a/packages/twenty-server/src/engine/core-modules/workflow/services/workflow-version-core-sync.service.ts b/packages/twenty-server/src/engine/core-modules/workflow/services/workflow-version-core-sync.service.ts
index 4b928baf81c..2bc6cde0467 100644
--- a/packages/twenty-server/src/engine/core-modules/workflow/services/workflow-version-core-sync.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/workflow/services/workflow-version-core-sync.service.ts
@@ -39,6 +39,8 @@ import { InjectCacheStorage } from 'src/engine/core-modules/cache-storage/decora
import { CacheStorageService } from 'src/engine/core-modules/cache-storage/services/cache-storage.service';
import { CacheStorageNamespace } from 'src/engine/core-modules/cache-storage/types/cache-storage-namespace.enum';
import { WORKFLOW_CRON_TRIGGER_CACHE_KEY } from 'src/modules/workflow/workflow-trigger/automated-trigger/crons/constants/workflow-cron-trigger-cache-key.constant';
+import { type CachedCronTrigger } from 'src/modules/workflow/workflow-trigger/automated-trigger/crons/types/cached-cron-trigger.type';
+import { publishCronTriggerCacheEntry } from 'src/modules/workflow/workflow-trigger/automated-trigger/crons/utils/publish-cron-trigger-cache-entry.util';
import { WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';
import { type WorkflowVersionWorkspaceEntity } from 'src/modules/workflow/common/standard-objects/workflow-version.workspace-entity';
import { type WorkflowWorkspaceEntity } from 'src/modules/workflow/common/standard-objects/workflow.workspace-entity';
@@ -306,6 +308,18 @@ export class WorkflowVersionCoreSyncService {
await this.evictCronTriggerCacheEntries(deletedVersions);
}
+ async publishCronTriggerCacheEntries(
+ cachedTriggers: CachedCronTrigger[],
+ ): Promise<void> {
+ for (const cachedTrigger of cachedTriggers) {
+ await publishCronTriggerCacheEntry({
+ cacheStorageService: this.cacheStorageService,
+ cachedTrigger,
+ logger: this.logger,
+ });
+ }
+ }
+
private async evictCronTriggerCacheEntries(
deletedVersions: Pick<WorkflowVersionEntity, 'coreWorkflowId' | 'status'>[],
): Promise<void> {
diff --git a/packages/twenty-server/src/modules/workflow/workflow-trigger/automated-trigger/crons/jobs/__tests__/workflow-cron-trigger-cron.job.spec.ts b/packages/twenty-server/src/modules/workflow/workflow-trigger/automated-trigger/crons/jobs/__tests__/workflow-cron-trigger-cron.job.spec.ts
index 4241fcb5b59..1571a499f48 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-trigger/automated-trigger/crons/jobs/__tests__/workflow-cron-trigger-cron.job.spec.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-trigger/automated-trigger/crons/jobs/__tests__/workflow-cron-trigger-cron.job.spec.ts
@@ -51,6 +51,40 @@ const mockWorkflowVersionCoreSyncService = {
findCoreVersionById: jest.fn(),
};
+const buildCronTrigger = (index: number) => ({
+ workflowId: `workflow-${index}`,
+ coreWorkflowVersionId: `core-version-${index}`,
+ workspaceWorkflowVersionId: `workspace-version-${index}`,
+ type: 'CRON',
+ settings: { pattern: '* * * * *' },
+});
+
+const mockWorkspaceCaches = (
+ triggersByWorkspaceId: Record<string, Record<string, unknown> | Error>,
+ applicationVersion: string | null = '1.0.1',
+) =>
+ mockWorkspaceCacheService.getOrRecompute.mockImplementation((async (
+ workspaceId: string,
+ keys: string[],
+ ) => {
+ if (keys.includes('flatApplicationMaps')) {
+ return {
+ flatApplicationMaps: {
+ byId: { 'application-id': { version: applicationVersion } },
+ idByUniversalIdentifier: {},
+ },
+ };
+ }
+
+ const triggers = triggersByWorkspaceId[workspaceId];
+
+ if (triggers instanceof Error) {
+ throw triggers;
+ }
+
+ return { workflowAutomatedTriggerMaps: { byWorkflowId: triggers ?? {} } };
+ }) as never);
+
describe('WorkflowCronTriggerCronJob', () => {
let job: WorkflowCronTriggerCronJob;
@@ -59,9 +93,11 @@ describe('WorkflowCronTriggerCronJob', () => {
jest.useFakeTimers();
jest.setSystemTime(new Date('2026-04-02T15:00:30.000Z'));
mockCronTriggerDeduplicationService.shouldDispatch.mockResolvedValue(true);
+ mockWorkspaceCaches({});
mockWorkflowCoreSyncService.findCoreWorkflowByIdOrWorkspaceWorkflowId.mockImplementation(
async (_workspaceId: string, workflowId: string) => ({
id: workflowId,
+ applicationId: 'application-id',
workspaceWorkflowId: workflowId,
lastPublishedCoreWorkflowVersionId: workflowId.replace(
'workflow-',
@@ -200,6 +236,21 @@ describe('WorkflowCronTriggerCronJob', () => {
);
});
+ it('should not enqueue jobs while the application of the workflow is still installing', async () => {
+ mockWorkspaceCaches({}, null);
+ mockCacheStorageService.hashGetValues.mockResolvedValue([
+ JSON.stringify({
+ workspaceId: WORKSPACE_1,
+ workflowId: 'workflow-1',
+ pattern: '* * * * *',
+ }),
+ ]);
+
+ await job.handle();
+
+ expect(mockMessageQueueService.add).not.toHaveBeenCalled();
+ });
+
it('should not enqueue jobs when the trigger is not due', async () => {
mockCronTriggerDeduplicationService.shouldDispatch.mockResolvedValue(
false,
@@ -260,10 +311,6 @@ describe('WorkflowCronTriggerCronJob', () => {
{ id: WORKSPACE_2 },
{ id: WORKSPACE_3 },
]);
- mockWorkspaceCacheService.getOrRecompute.mockResolvedValue({
- workflowAutomatedTriggerMaps: { byWorkflowId: {} },
- } as never);
-
await job.handle();
expect(mockWorkspaceRepository.find).toHaveBeenCalled();
@@ -278,36 +325,14 @@ describe('WorkflowCronTriggerCronJob', () => {
{ id: WORKSPACE_3 },
]);
- mockWorkspaceCacheService.getOrRecompute
- .mockResolvedValueOnce({
- workflowAutomatedTriggerMaps: {
- byWorkflowId: {
- 'workflow-1': {
- workflowId: 'workflow-1',
- coreWorkflowVersionId: 'core-version-1',
- workspaceWorkflowVersionId: 'workspace-version-1',
- type: 'CRON',
- settings: { pattern: '* * * * *' },
- },
- },
- },
- } as never)
- .mockResolvedValueOnce({
- workflowAutomatedTriggerMaps: { byWorkflowId: {} },
- } as never)
- .mockResolvedValueOnce({
- workflowAutomatedTriggerMaps: {
- byWorkflowId: {
- 'workflow-2': {
- workflowId: 'workflow-2',
- coreWorkflowVersionId: 'core-version-2',
- workspaceWorkflowVersionId: 'workspace-version-2',
- type: 'CRON',
- settings: { pattern: '* * * * *' },
- },
- },
- },
- } as never);
+ mockWorkspaceCaches({
+ [WORKSPACE_1]: {
+ 'workflow-1': buildCronTrigger(1),
+ },
+ [WORKSPACE_3]: {
+ 'workflow-2': buildCronTrigger(2),
+ },
+ });
await job.handle();
@@ -353,6 +378,29 @@ describe('WorkflowCronTriggerCronJob', () => {
);
});
+ it('should keep a workflow cached without dispatching it while its application is still installing', async () => {
+ mockCacheStorageService.hashGetValues.mockResolvedValue([]);
+ mockWorkspaceRepository.find.mockResolvedValue([{ id: WORKSPACE_1 }]);
+ mockWorkspaceCaches(
+ {
+ [WORKSPACE_1]: {
+ 'workflow-1': buildCronTrigger(1),
+ },
+ },
+ null,
+ );
+
+ await job.handle();
+
+ expect(mockCacheStorageService.hashSetWithExpire).toHaveBeenCalledWith(
+ expect.objectContaining({
+ key: WORKFLOW_CRON_TRIGGER_CACHE_KEY,
+ field: 'workflow-1',
+ }),
+ );
+ expect(mockMessageQueueService.add).not.toHaveBeenCalled();
+ });
+
it('should not write to cache when no workspaces have cron triggers', async () => {
mockCacheStorageService.hashGetValues.mockResolvedValue([]);
mockWorkspaceRepository.find.mockResolvedValue([{ id: WORKSPACE_1 }]);
@@ -402,21 +450,12 @@ describe('WorkflowCronTriggerCronJob', () => {
{ id: WORKSPACE_1 },
{ id: WORKSPACE_2 },
]);
- mockWorkspaceCacheService.getOrRecompute
- .mockRejectedValueOnce(new Error('Cache unavailable'))
- .mockResolvedValueOnce({
- workflowAutomatedTriggerMaps: {
- byWorkflowId: {
- 'workflow-1': {
- workflowId: 'workflow-1',
- coreWorkflowVersionId: 'core-version-1',
- workspaceWorkflowVersionId: 'workspace-version-1',
- type: 'CRON',
- settings: { pattern: '* * * * *' },
- },
- },
- },
- } as never);
+ mockWorkspaceCaches({
+ [WORKSPACE_1]: new Error('Cache unavailable'),
+ [WORKSPACE_2]: {
+ 'workflow-1': buildCronTrigger(1),
+ },
+ });
await job.handle();
diff --git a/packages/twenty-server/src/modules/workflow/workflow-trigger/automated-trigger/crons/jobs/workflow-cron-trigger-cron.job.ts b/packages/twenty-server/src/modules/workflow/workflow-trigger/automated-trigger/crons/jobs/workflow-cron-trigger-cron.job.ts
index 2a64cedbb37..3ef1a9eb367 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-trigger/automated-trigger/crons/jobs/workflow-cron-trigger-cron.job.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-trigger/automated-trigger/crons/jobs/workflow-cron-trigger-cron.job.ts
@@ -84,14 +84,19 @@ export class WorkflowCronTriggerCronJob {
private async getAndRunTriggersFromCache(cachedValues: string[], now: Date) {
for (const serialized of cachedValues) {
try {
- const trigger = await this.normalizeCachedTrigger(
+ const normalizedTrigger = await this.normalizeCachedTrigger(
JSON.parse(serialized) as CachedCronTrigger,
);
- if (!isDefined(trigger)) {
+ if (
+ !isDefined(normalizedTrigger) ||
+ !normalizedTrigger.isApplicationInstalled
+ ) {
continue;
}
+ const { trigger } = normalizedTrigger;
+
const shouldDispatch = await this.shouldDispatch({ trigger, now });
if (!shouldDispatch) {
@@ -179,7 +184,7 @@ export class WorkflowCronTriggerCronJob {
continue;
}
- const cachedTrigger = await this.normalizeCachedTrigger({
+ const normalizedTrigger = await this.normalizeCachedTrigger({
workspaceId,
workflowId,
legacyWorkflowId: cronTrigger.legacyWorkflowId,
@@ -187,12 +192,19 @@ export class WorkflowCronTriggerCronJob {
pattern,
});
- if (!isDefined(cachedTrigger)) {
+ if (!isDefined(normalizedTrigger)) {
continue;
}
+ const { trigger: cachedTrigger, isApplicationInstalled } =
+ normalizedTrigger;
+
triggersToCache.push(cachedTrigger);
+ if (!isApplicationInstalled) {
+ continue;
+ }
+
const shouldDispatch = await this.shouldDispatch({
trigger: cachedTrigger,
now,
@@ -252,9 +264,10 @@ export class WorkflowCronTriggerCronJob {
}));
}
- private async normalizeCachedTrigger(
- trigger: CachedCronTrigger,
- ): Promise<CachedCronTrigger | null> {
+ private async normalizeCachedTrigger(trigger: CachedCronTrigger): Promise<{
+ trigger: CachedCronTrigger;
+ isApplicationInstalled: boolean;
+ } | null> {
const workflow =
await this.workflowCoreSyncService.findCoreWorkflowByIdOrWorkspaceWorkflowId(
trigger.workspaceId,
@@ -265,6 +278,12 @@ export class WorkflowCronTriggerCronJob {
return null;
}
+ const { flatApplicationMaps } =
+ await this.workspaceCacheService.getOrRecompute(trigger.workspaceId, [
+ 'flatApplicationMaps',
+ ]);
+ const application = flatApplicationMaps.byId[workflow.applicationId];
+
const version =
await this.workflowVersionCoreSyncService.findCoreVersionById(
trigger.workspaceId,
@@ -282,14 +301,18 @@ export class WorkflowCronTriggerCronJob {
}
return {
- workspaceId: trigger.workspaceId,
- workflowId: workflow.id,
- legacyWorkflowId: workflow.workspaceWorkflowId ?? undefined,
- ...buildCoreDispatchIds({
- coreWorkflowVersionId: version.id,
- workspaceWorkflowVersionId: version.workspaceWorkflowVersionId,
- }),
- pattern: computeCronPatternFromSchedule(definition),
+ trigger: {
+ workspaceId: trigger.workspaceId,
+ workflowId: workflow.id,
+ legacyWorkflowId: workflow.workspaceWorkflowId ?? undefined,
+ ...buildCoreDispatchIds({
+ coreWorkflowVersionId: version.id,
+ workspaceWorkflowVersionId: version.workspaceWorkflowVersionId,
+ }),
+ pattern: computeCronPatternFromSchedule(definition),
+ },
+ isApplicationInstalled:
+ !isDefined(application) || isDefined(application.version),
};
}
diff --git a/packages/twenty-server/src/modules/workflow/workflow-trigger/automated-trigger/crons/utils/publish-cron-trigger-cache-entry.util.ts b/packages/twenty-server/src/modules/workflow/workflow-trigger/automated-trigger/crons/utils/publish-cron-trigger-cache-entry.util.ts
new file mode 100644
index 00000000000..06590a7ef6c
--- /dev/null
+++ b/packages/twenty-server/src/modules/workflow/workflow-trigger/automated-trigger/crons/utils/publish-cron-trigger-cache-entry.util.ts
@@ -0,0 +1,32 @@
+import { type CacheStorageService } from 'src/engine/core-modules/cache-storage/services/cache-storage.service';
+import { WORKFLOW_CRON_TRIGGER_CACHE_KEY } from 'src/modules/workflow/workflow-trigger/automated-trigger/crons/constants/workflow-cron-trigger-cache-key.constant';
+import { type CachedCronTrigger } from 'src/modules/workflow/workflow-trigger/automated-trigger/crons/types/cached-cron-trigger.type';
+
+export const publishCronTriggerCacheEntry = async ({
+ cacheStorageService,
+ cachedTrigger,
+ logger,
+}: {
+ cacheStorageService: CacheStorageService;
+ cachedTrigger: CachedCronTrigger;
+ logger: { error: (message: unknown, ...optionalParams: unknown[]) => void };
+}): Promise<void> => {
+ try {
+ await cacheStorageService.hashSetIfExists({
+ key: WORKFLOW_CRON_TRIGGER_CACHE_KEY,
+ field: cachedTrigger.workflowId,
+ value: JSON.stringify(cachedTrigger),
+ });
+ } catch (error) {
+ logger.error(
+ `Cron trigger cache entry not published for workflow ${cachedTrigger.workflowId}, dropping the cron cache so the next tick rebuilds it from the database`,
+ error,
+ );
+
+ try {
+ await cacheStorageService.del(WORKFLOW_CRON_TRIGGER_CACHE_KEY);
+ } catch (invalidationError) {
+ logger.error(invalidationError);
+ }
+ }
+};
diff --git a/packages/twenty-server/src/modules/workflow/workflow-trigger/workspace-services/workflow-trigger.workspace-service.ts b/packages/twenty-server/src/modules/workflow/workflow-trigger/workspace-services/workflow-trigger.workspace-service.ts
index f3188c184d0..ef955e3d517 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-trigger/workspace-services/workflow-trigger.workspace-service.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-trigger/workspace-services/workflow-trigger.workspace-service.ts
@@ -41,6 +41,7 @@ import { type WorkflowVersionStatusUpdate } from 'src/modules/workflow/workflow-
import { AutomatedTriggerWorkspaceService } from 'src/modules/workflow/workflow-trigger/automated-trigger/automated-trigger.workspace-service';
import { type DatabaseEventTriggerSettings } from 'src/modules/workflow/workflow-trigger/automated-trigger/constants/automated-trigger-settings';
import { WORKFLOW_CRON_TRIGGER_CACHE_KEY } from 'src/modules/workflow/workflow-trigger/automated-trigger/crons/constants/workflow-cron-trigger-cache-key.constant';
+import { publishCronTriggerCacheEntry } from 'src/modules/workflow/workflow-trigger/automated-trigger/crons/utils/publish-cron-trigger-cache-entry.util';
import { type CachedCronTrigger } from 'src/modules/workflow/workflow-trigger/automated-trigger/crons/types/cached-cron-trigger.type';
import {
WorkflowTriggerException,
@@ -682,28 +683,12 @@ export class WorkflowTriggerWorkspaceService {
}),
};
- const publishCronCache = async () => {
- try {
- await this.cacheStorageService.hashSetIfExists({
- key: WORKFLOW_CRON_TRIGGER_CACHE_KEY,
- field: workflowVersion.workflowId,
- value: JSON.stringify(cachedTrigger),
- });
- } catch (error) {
- this.logger.error(
- `Cron trigger cache entry not published for workflow ${workflowVersion.workflowId}, dropping the cron cache so the next tick rebuilds it from the database`,
- error,
- );
-
- try {
- await this.cacheStorageService.del(
- WORKFLOW_CRON_TRIGGER_CACHE_KEY,
- );
- } catch (invalidationError) {
- this.logger.error(invalidationError);
- }
- }
- };
+ const publishCronCache = () =>
+ publishCronTriggerCacheEntry({
+ cacheStorageService: this.cacheStorageService,
+ cachedTrigger,
+ logger: this.logger,
+ });
if (isDefined(transactionContext)) {
transactionContext.transactionScope.afterCommit(publishCronCache);
diff --git a/packages/twenty-shared/src/application/__tests__/workflowManifestType.spec.ts b/packages/twenty-shared/src/application/__tests__/workflowManifestType.spec.ts
index 3e5600728df..0a1fd0590af 100644
--- a/packages/twenty-shared/src/application/__tests__/workflowManifestType.spec.ts
+++ b/packages/twenty-shared/src/application/__tests__/workflowManifestType.spec.ts
@@ -199,7 +199,62 @@ describe('workflow manifest manual trigger', () => {
);
expect(result.success).toBe(false);
expect(result.error?.issues[0]?.message).toBe(
- 'Unsupported trigger type. Application workflows support: MANUAL',
+ 'Unsupported trigger type. Application workflows support: MANUAL, CRON',
);
});
});
+
+describe('workflow manifest cron trigger', () => {
+ const withCron = (settings: Record<string, unknown>) => ({
+ ...workflow,
+ version: {
+ ...workflow.version,
+ trigger: {
+ universalIdentifier: workflow.version.trigger.universalIdentifier,
+ type: 'CRON',
+ nextStepIds: workflow.version.trigger.nextStepIds,
+ settings,
+ },
+ },
+ });
+
+ it('accepts every schedule type', () => {
+ for (const settings of [
+ { type: 'DAYS', schedule: { day: 1, hour: 9, minute: 0 } },
+ { type: 'HOURS', schedule: { hour: 2, minute: 30 } },
+ { type: 'MINUTES', schedule: { minute: 15 } },
+ { type: 'CUSTOM', pattern: '0 9 * * 1-5' },
+ ]) {
+ expect(workflowManifestSchema.safeParse(withCron(settings)).success).toBe(
+ true,
+ );
+ }
+ });
+
+ it('rejects a schedule outside the clock', () => {
+ const result = workflowManifestSchema.safeParse(
+ withCron({ type: 'DAYS', schedule: { day: 1, hour: 24, minute: 0 } }),
+ );
+ expect(result.success).toBe(false);
+ expect(result.error?.issues[0]?.path).toEqual([
+ 'version',
+ 'trigger',
+ 'settings',
+ 'schedule',
+ 'hour',
+ ]);
+ });
+
+ it('rejects a schedule key the schedule type does not use', () => {
+ const result = workflowManifestSchema.safeParse(
+ withCron({ type: 'MINUTES', schedule: { minute: 15, hour: 2 } }),
+ );
+ expect(result.success).toBe(false);
+ expect(result.error?.issues[0]?.path).toEqual([
+ 'version',
+ 'trigger',
+ 'settings',
+ 'schedule',
+ ]);
+ });
+});
diff --git a/packages/twenty-shared/src/application/workflowTriggerManifestType.ts b/packages/twenty-shared/src/application/workflowTriggerManifestType.ts
index aab4450d4c8..340b60fc508 100644
--- a/packages/twenty-shared/src/application/workflowTriggerManifestType.ts
+++ b/packages/twenty-shared/src/application/workflowTriggerManifestType.ts
@@ -1,6 +1,7 @@
import { z } from 'zod';
import { isDefined } from '@/utils/validation/isDefined';
+import { workflowCronTriggerSchema } from '@/workflow/schemas/cron-trigger-schema';
const manualTriggerAvailabilityManifestSchema = z.discriminatedUnion('type', [
z.strictObject({ type: z.literal('GLOBAL') }),
@@ -14,6 +15,29 @@ const manualTriggerAvailabilityManifestSchema = z.discriminatedUnion('type', [
}),
]);
+const [
+ dailyCronSettingsSchema,
+ hourlyCronSettingsSchema,
+ minutelyCronSettingsSchema,
+ customCronSettingsSchema,
+] = workflowCronTriggerSchema.shape.settings.options;
+
+const cronTriggerSettingsManifestSchema = z.discriminatedUnion('type', [
+ dailyCronSettingsSchema
+ .omit({ outputSchema: true })
+ .extend({ schedule: dailyCronSettingsSchema.shape.schedule.strict() })
+ .strict(),
+ hourlyCronSettingsSchema
+ .omit({ outputSchema: true })
+ .extend({ schedule: hourlyCronSettingsSchema.shape.schedule.strict() })
+ .strict(),
+ minutelyCronSettingsSchema
+ .omit({ outputSchema: true })
+ .extend({ schedule: minutelyCronSettingsSchema.shape.schedule.strict() })
+ .strict(),
+ customCronSettingsSchema.omit({ outputSchema: true }).strict(),
+]);
+
const workflowTriggerManifestOptions = [
z.strictObject({
universalIdentifier: z.uuid(),
@@ -40,6 +64,12 @@ const workflowTriggerManifestOptions = [
})
.optional(),
}),
+ z.strictObject({
+ universalIdentifier: z.uuid(),
+ type: z.literal('CRON'),
+ nextStepIds: z.array(z.uuid()).min(1),
+ settings: cronTriggerSettingsManifestSchema,
+ }),
] as const;
export const APPLICATION_WORKFLOW_TRIGGER_TYPES: readonly string[] =