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

fix(triggers): leave an unchanged polling trigger running on republish (#16543)

Amr Elmohamadyc4726775df93
diff --git a/.agents/skills/piece-builder/trigger-patterns.md b/.agents/skills/piece-builder/trigger-patterns.md
index 1b6ac9b73cb..f78d750b4d9 100644
--- a/.agents/skills/piece-builder/trigger-patterns.md
+++ b/.agents/skills/piece-builder/trigger-patterns.md
@@ -14,7 +14,9 @@ Two deduplication strategies:
- **TIMEBASED** -- Each item has a timestamp; only items newer than last poll are returned
- **LAST_ITEM** -- Each item has an ID; items after the last known ID are returned
-**Always pass the whole `context`** to `pollingHelper.onEnable` / `onDisable` / `poll` / `test` -- never a subset like `{ store, auth, propsValue }`. Every field on the helper's param type is optional, so a partial object type-checks and whatever you left out is dropped in silence. The set also grows: `onEnable` now reads `context.isRepublish` to keep the existing `lastPoll`/`lastItem` when a running flow is republished, so a subset call still resets the checkpoint and drops every event since the last poll.
+**Always pass the whole `context`** to `pollingHelper.onEnable` / `onDisable` / `poll` / `test` -- never a subset like `{ store, auth, propsValue }`. Every field on the helper's param type is optional, so a partial object type-checks and whatever you left out is dropped in silence, and the set grows over time.
+
+**Republishing doesn't touch an unchanged polling trigger.** If the piece, its version, the trigger and its inputs are all the same, `onDisable` and `onEnable` are skipped and the store is left as is, so you don't need anything for the common republish. On a piece-version upgrade with the same inputs, both hooks run with `context.isRepublish` set: handle it if your stored state can be kept. See [Polling Trigger → Republishing a running flow](https://www.activepieces.com/docs/build-pieces/piece-reference/triggers/polling-trigger#republishing-a-running-flow).
**Editing an existing polling trigger? Fix every `pollingHelper` call in the piece while you're there.** Most pieces in the repo still pass the subset — the SKILL.md carve-out explains why fix-on-touch beats a repo-wide codemod. Mention the fix in your PR description so it doesn't read as an unrelated change.
diff --git a/brain/knowledge/execution-runtime/workers.md b/brain/knowledge/execution-runtime/workers.md
index a5d63d3730e..82bfc5ca36d 100644
--- a/brain/knowledge/execution-runtime/workers.md
+++ b/brain/knowledge/execution-runtime/workers.md
@@ -21,7 +21,6 @@ The deep `Resolver`/`Runtime` concurrency and bundle-caching model lives on the
- `concurrency === 1` primes the sandbox to the full container RAM (cgroup-aware) via `primeFullContainerMemory()`.
### Gotchas
-- **A local engine edit doesn't reach sandboxes until the worker restarts, unless `AP_ENVIRONMENT` is dev.** `engineInstaller` copies `dist/packages/engine/main.js` into `cache/v<N>/common/main.js` once per worker process (`installedPaths`) and only re-copies on every install in `DEVELOPMENT`. With a prod-like local env, sandboxes keep running whatever engine was built when the worker first ran a job, and killing sandboxes doesn't help. Restart the worker (touching `packages/server/worker/src/bootstrap.ts` makes `tsx watch` do it), then check the cached `main.js` for your change before testing.
- **Piece bundles download over the worker's own `AP_FRONTEND_URL` (`internalApiUrl`), never the app's `PUBLIC_URL` — keep it that way.** Through 0.92.x the sandbox built `GET /v1/engine/pieces/bundle` from the `PUBLIC_URL` the app pushes over the socket, so a standalone worker ignored its own `AP_FRONTEND_URL=http://app` for this one hop. A `localhost` public URL (the docs' default for compose and `docker run -p 8080:80`) failed every uncached install with `fetch failed` (GIT-1838). A public URL that reached a *different* instance sharing the JWT secret returned 404, so custom-piece upload failed with `PIECE_BUNDLE_NOT_AVAILABLE` while the `PACKAGE_ARCHIVE` row sat intact in Postgres. Tell-tale: the bundle GET never shows up in the app's own request log. Fixed by GIT-1718.
- **`AP_CONTAINER_TYPE=WORKER` moves every engine→app call onto `AP_FRONTEND_URL`.** In `WORKER_AND_APP` the engine reaches the app at `http://127.0.0.1:<port>/api/`; in `WORKER` it uses `AP_FRONTEND_URL + '/api/'` (`getApiUrl` in `worker/src/lib/config/configs.ts`), and the worker's Socket.IO connection follows it. If that URL is the public hostname, file uploads, run-log uploads, piece bundle downloads and the worker socket all cross the ingress/WAF/CDN, so WAF rules and websocket idle timeouts start failing runs that worked the day before. Point separated workers at the in-cluster app service instead. Found on Alan's fleet 2026-09-29, the day after being advised to switch to `WORKER`.
- **The piece workspace pins `linker = "isolated"` in its own `bunfig.toml` — do not delete it, the engine's piece resolver depends on the layout bun chooses.** `pieceInstaller` generates a bun workspace at `<cache>/<version>/common` whose members are `pieces/<pieceName>-<pieceVersion>`, and the engine (`piece-loader.ts` → `resolveInstalledPieceEntry`) resolves a piece **only** at `pieces/<alias>/node_modules/<pieceName>`, which just the isolated linker produces. The workspace used to carry no bunfig and inherited whatever ancestor bunfig bun discovered above the cache mount (`/usr/src/app/bunfig.toml`); when bun instead uses the **hoisted** linker it writes the package as a real directory at the workspace root `node_modules/@activepieces/<name>` and leaves the member with no `node_modules` at all, so every run of that piece fails `PieceNotFoundError: Piece not found for package: <name>-<version>` while `bun install` still exits 0. It was silent and self-perpetuating — `markPiecesAsUsed` writes `ready` and `pieceCheckIfAlreadyInstalled` only looks for *a* `node_modules`, so the piece is reinstalled forever and never resolves. Sep 2026 production: 125/125 folders missing `node_modules` were exactly the 125 packages sitting hoisted at the workspace root; 7,400+ `EXECUTE_FLOW` jobs, 15+ platforms, ~60 official pieces, ~300/hr. Two things had to line up — bun 1.4.0 (Aug 31) changed the layout newly-installed members got, and removing the piece-upgrade Redis gate (#15236, deployed 2026-09-03 08:09 UTC) mass-upgraded every platform's flows to newer piece versions so almost every install was suddenly a *first-time* install. Diagnose on a worker with `for d in <cache>/v*/common/pieces/@activepieces/*/; do [ -d "$d/node_modules" ] || basename $d; done`. Fixed by pinning the linker plus a `LATEST_CACHE_VERSION` bump (v14 → v15) so the fleet rebuilds one clean workspace under the pinned layout rather than carrying a mixed one.
diff --git a/brain/knowledge/flows-execution/triggers.md b/brain/knowledge/flows-execution/triggers.md
index ccc03ae0bfb..ac2ffb53916 100644
--- a/brain/knowledge/flows-execution/triggers.md
+++ b/brain/knowledge/flows-execution/triggers.md
@@ -21,8 +21,7 @@ Triggers define how and when a flow starts. The module handles registration, eve
### Gotchas
- **Deduplication** (polling): extracts `__DEDUPE_KEY_PROPERTY`, Redis INCR with 30s TTL — first passes, duplicates filtered; the dedupe key is stripped from returned payloads.
-- **Republish preserves the polling checkpoint** (`isRepublish`): republishing a running flow does `onDisable(old) → onEnable(new)`, which used to reset `lastPoll`/`lastItem` to now and silently drop events created in between. `flowService.isRepublish` decides it once, before anything is disabled: true only when an already-`ENABLED` flow is published to stay `ENABLED` with an unchanged trigger — same piece, **same piece version**, same trigger name, **and deep-equal `settings.input`** (`flowPublishUtils.isSameTrigger`). A piece upgrade counts as a change and starts fresh, because the new version may read its state differently. Both publish paths (direct `LOCK_AND_PUBLISH` and EE approval) pass that one value to the old version's ON_DISABLE job and to the new version's ON_ENABLE job → `ExecuteTriggerOperation` → trigger context (`context.isRepublish`). A fresh enable, a manual off→on toggle, a trigger swap, and any change to the trigger's props all still reset to now. The props check is not cosmetic: a checkpoint kept across a props change points at a resource that is no longer being polled, and `pollingHelper.poll` treats a `LAST_ITEM` id it cannot find in the fetched page (`findIndex → -1`) the same as "no checkpoint", emitting **every** item. A new publish path must call `flowService.isRepublish` with the pre-publish flow snapshot and pass the result to both `triggerSourceService.disable` and `applyStatusChangeForPublishedFlow`; before ENG-938 the approval path skipped it and every approved republish reset the checkpoint.
-- **The engine keeps the checkpoint, not the piece.** On a republish of a `POLLING` trigger, `republishStore.forLifecycleHook` (`packages/server/engine/src/lib/piece-context`) makes the store read-only for both the old version's `onDisable` and the new version's `onEnable`: reads work, writes and deletes do nothing, so the state ends exactly as it was. Per-operation rules were tried and each missed a piece: Twilio clears its checkpoint in `onDisable` with `put(key, null)`, Shopify's `onEnable` deletes `lastItem` and writes new scan keys, ~38 triggers delete their checkpoint in `onDisable`. Pieces don't need to forward the flag. Webhook triggers are excluded because they must remove and re-create their webhook. The cost: a cache that `onEnable` would refresh (Zoho's field list) stays until it expires on its own (6h for Zoho). A plain off toggle or a flow delete sends no flag, so `onDisable` still cleans up there.
+- **Republishing leaves an unchanged polling trigger running** (`isTriggerUnchanged`): a publish runs `onDisable(old) → onEnable(new)`, which reset `lastPoll`/`lastItem` (and every custom checkpoint) to now and silently dropped events created in between. When the flow was already `ENABLED`, stays enabled, and the trigger keeps the same piece, **piece version**, trigger name and deep-equal `settings.input` (`flowPublishUtils.isTriggerUnchanged`), `flowTriggerSideEffect` skips both engine hooks for a POLLING trigger: the store is untouched and only the poll job is re-pointed to the new flow version with the previous trigger source's schedule (no previous schedule → hooks run). The hooks are skipped, not run against a guarded store, because any store-wrapping rule changes what piece code sees mid-hook and broke real pieces (pinterest's mid-pagination bookmark, azure-ad's stale delta link failing the publish); skipping makes the trigger indistinguishable from a flow nobody republished, which is safe for custom pieces too. Skipping both is required — skipping only `onDisable` would let `onEnable` register a second copy of anything external. With the same inputs but a **new piece version** both hooks run with `isRepublish=true` (`flowPublishUtils.isRepublish`, ON_DISABLE and ON_ENABLE jobs → `context.isRepublish`), and `pollingHelper.onEnable` keeps the checkpoint only if the piece passes the whole `context`. A trigger swap, any props change, or an off→on toggle runs the hooks normally and starts fresh; off→on is the way to reset a polling trigger whose state has gone bad (e.g. an expired sync token), since a republish no longer does. The props check is not cosmetic: a checkpoint kept across a props change points at a resource that is no longer being polled, and `pollingHelper.poll` treats a `LAST_ITEM` id it cannot find (`findIndex → -1`) as "no checkpoint", emitting **every** item. Both publish paths — `flowService.updatedPublishedVersionId` and `flowApprovalRequestService.approve` (its own disable→enable) — use these two decisions; any new publish path must too.
- **A missing timestamp permanently kills a TIMEBASED polling trigger** — `pollingHelper.poll` advances the checkpoint with `items.reduce((acc, i) => Math.max(acc, i.epochMilliSeconds), lastPoll)`, and `Math.max(n, NaN)` is `NaN`, so a single item whose date field was never requested (`dayjs(undefined).valueOf()` → `NaN`) writes `NaN` into `lastPoll`; every later poll then filters on `> NaN` → false and the trigger silently never fires again, with no error anywhere. Two guards, both needed: request the date in the API's `fields`/select mask, and drop items with an unusable date before mapping to `epochMilliSeconds`. The filter must check the raw value, not just `.isValid()` — `dayjs(undefined)` is *now* and reports valid.
- **The timestamp you poll on may be client-supplied, and a future one is fatal.** Google Drive sets `modifiedTime` from the *local file mtime* on upload, not the upload moment, so it can be older than `createdTime` — or years ahead if the uploader's clock is fast. A TIMEBASED watermark is `max(epochMilliSeconds)` over the emitted items, so one future-dated row pushes `lastPoll` into the future and the trigger emits nothing until wall-clock catches up. Hold back items timestamped after `Date.now()` — they fire once the clock passes them. Do **not** clamp the watermark instead: a clamped watermark re-emits that same row on every poll forever.
- The **simulate flag** lets a production source and a test source coexist independently.
diff --git a/docs/build-pieces/piece-reference/triggers/polling-trigger.mdx b/docs/build-pieces/piece-reference/triggers/polling-trigger.mdx
index baa78a0fbdf..265b1a1b7ef 100644
--- a/docs/build-pieces/piece-reference/triggers/polling-trigger.mdx
+++ b/docs/build-pieces/piece-reference/triggers/polling-trigger.mdx
@@ -100,3 +100,13 @@ export const newTicketInView = createTrigger({
}
});
```
+
+## Republishing a running flow
+
+When an enabled flow is published again and its polling trigger is unchanged (same piece, same piece version, same trigger, same inputs), Activepieces leaves the trigger running exactly as it was: `onDisable` and `onEnable` are not called, the trigger's store is untouched, and polling continues on the same schedule. Events that arrive around the republish are picked up by the next poll as usual.
+
+Everything else runs the hooks as normal:
+
+- **Upgrading the piece version** with the same inputs runs the old version's `onDisable` and the new version's `onEnable`, with `context.isRepublish` set to `true` in both. Use it to keep your checkpoint when your stored state is still valid.
+- **Changing the trigger or its inputs** runs both hooks without `isRepublish`, so the trigger starts fresh.
+- **Turning the flow off and on** also starts fresh. This is how to reset a polling trigger whose stored state has gone bad, such as an expired sync token.
diff --git a/packages/server/api/src/app/ee/flows/flow-approval/flow-approval-request.service.ts b/packages/server/api/src/app/ee/flows/flow-approval/flow-approval-request.service.ts
index 918eb689b93..ffac1ff5660 100644
--- a/packages/server/api/src/app/ee/flows/flow-approval/flow-approval-request.service.ts
+++ b/packages/server/api/src/app/ee/flows/flow-approval/flow-approval-request.service.ts
@@ -3,6 +3,7 @@ import { FastifyBaseLogger, FastifyRequest } from 'fastify'
import { repoFactory } from '../../../core/db/repo-factory'
import { transaction } from '../../../core/db/transaction'
import { flowExecutionCache } from '../../../flows/flow/flow-execution-cache'
+import { flowPublishUtils } from '../../../flows/flow/flow-publish-utils'
import { flowSideEffects } from '../../../flows/flow/flow-service-side-effects'
import { flowService } from '../../../flows/flow/flow.service'
import { flowVersionRepo, flowVersionService } from '../../../flows/flow-version/flow-version.service'
@@ -84,60 +85,75 @@ export const flowApprovalRequestService = (log: FastifyBaseLogger) => ({
}
assertStateIsPending(approval.state)
- const flow = await flowService(log).getOneOrThrow({ id: approval.flowId, projectId: approval.projectId })
const lockedVersion = await flowVersionService(log).getFlowVersionOrThrow({
- flowId: flow.id,
+ flowId: approval.flowId,
versionId: approval.flowVersionId,
})
- const isRepublish = await flowService(log).isRepublish({ previousFlow: flow, versionToPublish: lockedVersion, newStatus: approval.requestedStatus })
-
const decidedAt = new Date().toISOString()
const approverId = approverPrincipal.type === PrincipalType.SERVICE ? null : approverPrincipal.id
- await transaction(async (entityManager) => {
- const updateResult = await flowApprovalRequestRepo(entityManager)
- .createQueryBuilder()
- .update()
- .set({
- state: FlowApprovalRequestState.APPROVED,
- approverId,
- decidedAt,
+ await flowService(log).withStatusLock({
+ id: approval.flowId,
+ fn: async () => {
+ const flow = await flowService(log).getOneOrThrow({ id: approval.flowId, projectId: approval.projectId })
+ const republishParams = {
+ previouslyPublished: flow.status === FlowStatus.ENABLED && !isNil(flow.publishedVersionId)
+ ? await flowVersionService(log).getFlowVersionOrThrow({ flowId: flow.id, versionId: flow.publishedVersionId })
+ : undefined,
+ toPublish: lockedVersion,
+ requestedStatus: approval.requestedStatus,
+ }
+ const isRepublish = flowPublishUtils.isRepublish(republishParams)
+ const isTriggerUnchanged = flowPublishUtils.isTriggerUnchanged(republishParams)
+
+ await transaction(async (entityManager) => {
+ const updateResult = await flowApprovalRequestRepo(entityManager)
+ .createQueryBuilder()
+ .update()
+ .set({
+ state: FlowApprovalRequestState.APPROVED,
+ approverId,
+ decidedAt,
+ })
+ .where({ id: approval.id, state: FlowApprovalRequestState.PENDING })
+ .returning(['id'])
+ .execute()
+ assertRowsAffected(updateResult.raw?.length)
+ await flowService(log).setPublishedVersion({ flow, lockedVersion, entityManager })
})
- .where({ id: approval.id, state: FlowApprovalRequestState.PENDING })
- .returning(['id'])
- .execute()
- assertRowsAffected(updateResult.raw?.length)
- await flowService(log).setPublishedVersion({ flow, lockedVersion, entityManager })
- })
- if (flow.status === FlowStatus.ENABLED && !isNil(flow.publishedVersionId)) {
- await triggerSourceService(log).disable({
- flowId: flow.id,
- projectId: flow.projectId,
- simulate: false,
- ignoreError: true,
- isRepublish,
- })
- }
- await flowExecutionCache(log).invalidate(flow.id)
- await flowService(log).applyStatusChangeForPublishedFlow({
- id: flow.id,
- projectId: flow.projectId,
- newStatus: approval.requestedStatus,
- isRepublish,
+ if (flow.status === FlowStatus.ENABLED && !isNil(flow.publishedVersionId)) {
+ await triggerSourceService(log).disable({
+ flowId: flow.id,
+ projectId: flow.projectId,
+ simulate: false,
+ ignoreError: true,
+ isRepublish,
+ isTriggerUnchanged,
+ })
+ }
+ await flowExecutionCache(log).invalidate(flow.id)
+ await flowService(log).changeStatusHoldingLock({
+ id: flow.id,
+ projectId: approval.projectId,
+ newStatus: approval.requestedStatus,
+ isRepublish,
+ isTriggerUnchanged,
+ })
+ },
})
rejectedPromiseHandler(telemetry(log).trackProject({
projectId: approval.projectId,
event: {
name: TelemetryEventName.FLOW_PUBLISHED,
- payload: { flowId: flow.id },
+ payload: { flowId: approval.flowId },
},
}), log)
applicationEvents(log).sendUserEvent(request, {
action: ApplicationEventName.FLOW_APPROVAL_GRANTED,
data: {
approvalRequestId: approval.id,
- flowId: flow.id,
+ flowId: approval.flowId,
flowVersionId: approval.flowVersionId,
flowDisplayName: lockedVersion.displayName,
},
diff --git a/packages/server/api/src/app/flows/flow/flow-publish-utils.ts b/packages/server/api/src/app/flows/flow/flow-publish-utils.ts
index 462b93e6c07..633e62d832f 100644
--- a/packages/server/api/src/app/flows/flow/flow-publish-utils.ts
+++ b/packages/server/api/src/app/flows/flow/flow-publish-utils.ts
@@ -1,18 +1,37 @@
-import { FlowTriggerType, FlowVersion } from '@activepieces/shared'
+import { isNil } from '@activepieces/core-utils'
+import { FlowStatus, FlowTriggerType, FlowVersion } from '@activepieces/shared'
import deepEqual from 'deep-equal'
function isSameTrigger({ published, toPublish }: IsSameTriggerParams): boolean {
return published.type === FlowTriggerType.PIECE
&& toPublish.type === FlowTriggerType.PIECE
&& published.settings.pieceName === toPublish.settings.pieceName
- && published.settings.pieceVersion === toPublish.settings.pieceVersion
&& published.settings.triggerName === toPublish.settings.triggerName
&& deepEqual(published.settings.input, toPublish.settings.input)
}
-export const flowPublishUtils = { isSameTrigger }
+function isRepublish({ previouslyPublished, toPublish, requestedStatus }: IsRepublishParams): boolean {
+ return !isNil(previouslyPublished)
+ && requestedStatus === FlowStatus.ENABLED
+ && isSameTrigger({ published: previouslyPublished.trigger, toPublish: toPublish.trigger })
+}
+
+function isTriggerUnchanged({ previouslyPublished, toPublish, requestedStatus }: IsRepublishParams): boolean {
+ return isRepublish({ previouslyPublished, toPublish, requestedStatus })
+ && previouslyPublished?.trigger.type === FlowTriggerType.PIECE
+ && toPublish.trigger.type === FlowTriggerType.PIECE
+ && previouslyPublished.trigger.settings.pieceVersion === toPublish.trigger.settings.pieceVersion
+}
+
+export const flowPublishUtils = { isSameTrigger, isRepublish, isTriggerUnchanged }
type IsSameTriggerParams = {
published: FlowVersion['trigger']
toPublish: FlowVersion['trigger']
}
+
+type IsRepublishParams = {
+ previouslyPublished: FlowVersion | undefined
+ toPublish: FlowVersion
+ requestedStatus: FlowStatus
+}
diff --git a/packages/server/api/src/app/flows/flow/flow-service-side-effects.ts b/packages/server/api/src/app/flows/flow/flow-service-side-effects.ts
index e063a1f0154..ba75759767c 100644
--- a/packages/server/api/src/app/flows/flow/flow-service-side-effects.ts
+++ b/packages/server/api/src/app/flows/flow/flow-service-side-effects.ts
@@ -12,6 +12,7 @@ export const flowSideEffects = (log: FastifyBaseLogger) => ({
publishedFlowVersion,
templateId,
isRepublish,
+ isTriggerUnchanged,
}: PreUpdateStatusParams): Promise<void> {
switch (newStatus) {
case FlowStatus.ENABLED: {
@@ -21,6 +22,7 @@ export const flowSideEffects = (log: FastifyBaseLogger) => ({
simulate: false,
templateId,
isRepublish,
+ isTriggerUnchanged,
})
break
}
@@ -144,6 +146,7 @@ type PreUpdateStatusParams = {
newStatus: FlowStatus
templateId?: string
isRepublish?: boolean
+ isTriggerUnchanged?: boolean
}
diff --git a/packages/server/api/src/app/flows/flow/flow.service.ts b/packages/server/api/src/app/flows/flow/flow.service.ts
index 9a03739ff33..9673b76f4a7 100644
--- a/packages/server/api/src/app/flows/flow/flow.service.ts
+++ b/packages/server/api/src/app/flows/flow/flow.service.ts
@@ -376,16 +376,21 @@ export const flowService = (log: FastifyBaseLogger) => ({
})
break
}
- const isRepublish = await this.isRepublish({ previousFlow: flow, versionToPublish: flowVersionToPublish, newStatus: requestedStatus })
- await this.updatedPublishedVersionId({
+ await withStatusLock({
id,
- userId,
- projectId,
- platformId,
- flowVersionToPublish,
- isRepublish,
+ log,
+ fn: async () => {
+ const { isRepublish, isTriggerUnchanged } = await this.updatedPublishedVersionId({
+ id,
+ userId,
+ projectId,
+ platformId,
+ flowVersionToPublish,
+ requestedStatus,
+ })
+ await changeStatus({ id, projectId, newStatus: requestedStatus, isRepublish, isTriggerUnchanged }, log)
+ },
})
- await this.applyStatusChangeForPublishedFlow({ id, projectId, newStatus: requestedStatus, isRepublish })
break
}
@@ -502,9 +507,15 @@ export const flowService = (log: FastifyBaseLogger) => ({
projectId,
platformId,
flowVersionToPublish,
- isRepublish,
- }: UpdatePublishedVersionIdParams): Promise<PopulatedFlow> {
+ requestedStatus,
+ }: UpdatePublishedVersionIdParams): Promise<UpdatePublishedVersionIdResult> {
const flowToUpdate = await this.getOneOrThrow({ id, projectId })
+ const liveVersion = flowToUpdate.status === FlowStatus.ENABLED && !isNil(flowToUpdate.publishedVersionId)
+ ? await flowVersionService(log).getFlowVersionOrThrow({ flowId: id, versionId: flowToUpdate.publishedVersionId })
+ : undefined
+ const republishParams = { previouslyPublished: liveVersion, toPublish: flowVersionToPublish, requestedStatus }
+ const isRepublish = flowPublishUtils.isRepublish(republishParams)
+ const isTriggerUnchanged = flowPublishUtils.isTriggerUnchanged(republishParams)
if (flowToUpdate.status === FlowStatus.ENABLED && !isNil(flowToUpdate.publishedVersionId)) {
await triggerSourceService(log).disable({
@@ -513,6 +524,7 @@ export const flowService = (log: FastifyBaseLogger) => ({
simulate: false,
ignoreError: true,
isRepublish,
+ isTriggerUnchanged,
})
}
@@ -552,7 +564,7 @@ export const flowService = (log: FastifyBaseLogger) => ({
payload: { flowId: id },
},
}), log)
- return publishedFlow
+ return { publishedFlow, isRepublish, isTriggerUnchanged }
},
async setPublishedVersion({ flow, lockedVersion, entityManager }: SetPublishedVersionParams): Promise<void> {
@@ -567,21 +579,12 @@ export const flowService = (log: FastifyBaseLogger) => ({
})
},
- async isRepublish({ previousFlow, versionToPublish, newStatus }: IsRepublishParams): Promise<boolean> {
- const previousVersionId = previousFlow.publishedVersionId
- const keepsRunning = previousFlow.status === FlowStatus.ENABLED && newStatus === FlowStatus.ENABLED
- if (!keepsRunning || isNil(previousVersionId)) {
- return false
- }
- const previousVersion = await flowVersionService(log).getFlowVersionOrThrow({ flowId: previousFlow.id, versionId: previousVersionId })
- return flowPublishUtils.isSameTrigger({
- published: previousVersion.trigger,
- toPublish: versionToPublish.trigger,
- })
+ async withStatusLock<T>({ id, fn }: { id: FlowId, fn: () => Promise<T> }): Promise<T> {
+ return withStatusLock({ id, log, fn })
},
- async applyStatusChangeForPublishedFlow({ id, projectId, newStatus, isRepublish }: ApplyStatusChangeForPublishedFlowParams): Promise<void> {
- await applyStatusChange({ id, projectId, newStatus, isRepublish }, log)
+ async changeStatusHoldingLock(params: ChangeStatusParams): Promise<void> {
+ await changeStatus(params, log)
},
async delete({ id, projectId, previousFlow, userId, ip, emitEvents = true }: DeleteParams): Promise<void> {
@@ -841,56 +844,58 @@ async function withDraftLock({ flowId, log, fn }: {
})
}
-async function applyStatusChange(params: {
- id: FlowId
- projectId: ProjectId
- newStatus: FlowStatus
- isRepublish?: boolean
-}, log: FastifyBaseLogger): Promise<void> {
+async function applyStatusChange(params: ChangeStatusParams, log: FastifyBaseLogger): Promise<void> {
+ await withStatusLock({ id: params.id, log, fn: () => changeStatus(params, log) })
+}
+
+async function withStatusLock<T>({ id, log, fn }: WithStatusLockParams<T>): Promise<T> {
const triggerTimeout = system.getNumberOrThrow(AppSystemProp.TRIGGER_TIMEOUT_SECONDS)
- await distributedLock(log).runExclusive({
- key: `flow-status-change-${params.id}`,
- timeoutInSeconds: triggerTimeout + 30,
- fn: async () => {
- const flowToUpdate = await flowService(log).getOneOrThrow({
- id: params.id,
- projectId: params.projectId,
- })
- if (flowToUpdate.status === params.newStatus) {
- return
- }
+ return distributedLock(log).runExclusive({
+ key: `flow-status-change-${id}`,
+ timeoutInSeconds: triggerTimeout * 2 + 30,
+ fn,
+ })
+}
- const publishedFlowVersionId = flowToUpdate.publishedVersionId
- if (isNil(publishedFlowVersionId)) {
- throw new ActivepiecesError({
- code: ErrorCode.FLOW_OPERATION_INVALID,
- params: { message: 'Publish the flow before turning it on' },
- })
- }
- const publishedFlowVersion = await flowVersionService(log).getFlowVersionOrThrow({
- flowId: flowToUpdate.id,
- versionId: publishedFlowVersionId,
- })
- if (params.newStatus === FlowStatus.ENABLED) {
- assertTriggerIsSelected({ trigger: publishedFlowVersion.trigger })
- }
+async function changeStatus(params: ChangeStatusParams, log: FastifyBaseLogger): Promise<void> {
+ const flowToUpdate = await flowService(log).getOneOrThrow({
+ id: params.id,
+ projectId: params.projectId,
+ })
+ if (flowToUpdate.status === params.newStatus) {
+ return
+ }
- await flowSideEffects(log).preUpdateStatus({
- flowToUpdate,
- publishedFlowVersion,
- newStatus: params.newStatus,
- templateId: flowToUpdate.templateId ?? undefined,
- isRepublish: params.isRepublish,
- })
+ const publishedFlowVersionId = flowToUpdate.publishedVersionId
+ if (isNil(publishedFlowVersionId)) {
+ throw new ActivepiecesError({
+ code: ErrorCode.FLOW_OPERATION_INVALID,
+ params: { message: 'Publish the flow before turning it on' },
+ })
+ }
+ const publishedFlowVersion = await flowVersionService(log).getFlowVersionOrThrow({
+ flowId: flowToUpdate.id,
+ versionId: publishedFlowVersionId,
+ })
+ if (params.newStatus === FlowStatus.ENABLED) {
+ assertTriggerIsSelected({ trigger: publishedFlowVersion.trigger })
+ }
- await flowRepo().save({
- ...flowToUpdate,
- status: params.newStatus,
- publishedVersionId: publishedFlowVersion.id,
- })
- await flowExecutionCache(log).invalidate(params.id)
- },
+ await flowSideEffects(log).preUpdateStatus({
+ flowToUpdate,
+ publishedFlowVersion,
+ newStatus: params.newStatus,
+ templateId: flowToUpdate.templateId ?? undefined,
+ isRepublish: params.isRepublish,
+ isTriggerUnchanged: params.isTriggerUnchanged,
})
+
+ await flowRepo().save({
+ ...flowToUpdate,
+ status: params.newStatus,
+ publishedVersionId: publishedFlowVersion.id,
+ })
+ await flowExecutionCache(log).invalidate(params.id)
}
export const getFolderIdFromRequest = async ({ projectId, folderId, folderName, log }: { projectId: string, folderId: string | undefined, folderName: string | undefined, log: FastifyBaseLogger }) => {
@@ -1017,26 +1022,33 @@ type UpdatePublishedVersionIdParams = {
platformId: PlatformId
projectId: ProjectId
flowVersionToPublish: FlowVersion
- isRepublish: boolean
-}
-
-type SetPublishedVersionParams = {
- flow: Flow
- lockedVersion: FlowVersion
- entityManager: EntityManager
+ requestedStatus: FlowStatus
}
-type IsRepublishParams = {
- previousFlow: Flow
- versionToPublish: FlowVersion
+type ChangeStatusParams = {
+ id: FlowId
+ projectId: ProjectId
newStatus: FlowStatus
+ isRepublish?: boolean
+ isTriggerUnchanged?: boolean
}
-type ApplyStatusChangeForPublishedFlowParams = {
+type WithStatusLockParams<T> = {
id: FlowId
- projectId: ProjectId
- newStatus: FlowStatus
+ log: FastifyBaseLogger
+ fn: () => Promise<T>
+}
+
+type UpdatePublishedVersionIdResult = {
+ publishedFlow: PopulatedFlow
isRepublish: boolean
+ isTriggerUnchanged: boolean
+}
+
+type SetPublishedVersionParams = {
+ flow: Flow
+ lockedVersion: FlowVersion
+ entityManager: EntityManager
}
type DeleteParams = EventEmissionParams & {
diff --git a/packages/server/api/src/app/trigger/trigger-source/flow-trigger-side-effect.ts b/packages/server/api/src/app/trigger/trigger-source/flow-trigger-side-effect.ts
index 26cf3f3b6d6..ee0cb93a985 100644
--- a/packages/server/api/src/app/trigger/trigger-source/flow-trigger-side-effect.ts
+++ b/packages/server/api/src/app/trigger/trigger-source/flow-trigger-side-effect.ts
@@ -23,7 +23,10 @@ export const flowTriggerSideEffect = (log: FastifyBaseLogger) => {
scheduleOptions: undefined,
}
}
- const { flowId, flowVersionId, projectId, simulate, pieceTrigger, isRepublish } = params
+ const { flowId, flowVersionId, projectId, simulate, pieceTrigger, isRepublish, isTriggerUnchanged, previousSchedule } = params
+ if (pieceTrigger.type === TriggerStrategy.POLLING && isTriggerUnchanged === true && !isNil(previousSchedule)) {
+ return handlePollingTrigger({ flowId, flowVersionId, projectId, scheduleOptions: previousSchedule, log })
+ }
const platformId = await projectService(log).getPlatformId(projectId)
const engineHelperResponse = await userInteractionWatcher.submitAndWaitForResponse<EngineResponse<ExecuteTriggerResponse<TriggerHookType.ON_ENABLE>>>({
@@ -59,9 +62,11 @@ export const flowTriggerSideEffect = (log: FastifyBaseLogger) => {
}
case TriggerStrategy.POLLING: {
return handlePollingTrigger({
- engineHelperResponse,
+ flowId,
+ flowVersionId,
+ projectId,
+ scheduleOptions: engineHelperResponse.response.scheduleOptions,
log,
- ...params,
})
}
case TriggerStrategy.MANUAL: {
@@ -75,31 +80,9 @@ export const flowTriggerSideEffect = (log: FastifyBaseLogger) => {
if (environment === ApEnvironment.TESTING) {
return
}
- const { flowId, flowVersionId, projectId, simulate, pieceTrigger, isRepublish } = params
- const platformId = await projectService(log).getPlatformId(projectId)
- const { error, data: engineHelperResponse } = await tryCatch(
- () => userInteractionWatcher.submitAndWaitForResponse<EngineResponse<ExecuteTriggerResponse<TriggerHookType.ON_DISABLE>>>({
- jobType: WorkerJobType.EXECUTE_TRIGGER_HOOK,
- hookType: TriggerHookType.ON_DISABLE,
- flowId,
- flowVersionId,
- test: simulate,
- projectId,
- platformId,
- isRepublish,
- }, log),
- )
- if (!isNil(error)) {
- if (!params.ignoreError) {
- throw error
- }
- log.warn({ flow: { id: flowId }, error: error.message }, IGNORED_DISABLE_ERROR)
- }
- else if (!params.ignoreError) {
- assertEngineResponseIsOk(engineHelperResponse!, flowId, flowVersionId)
- }
- else if (engineHelperResponse?.status !== EngineResponseStatus.OK) {
- log.warn({ flow: { id: flowId }, error: sanitizeIgnoredError(engineHelperResponse?.error) }, IGNORED_DISABLE_ERROR)
+ const { flowId, flowVersionId, projectId, pieceTrigger, isTriggerUnchanged } = params
+ if (pieceTrigger.type !== TriggerStrategy.POLLING || isTriggerUnchanged !== true) {
+ await runDisableHook({ params, log })
}
switch (pieceTrigger.type) {
case TriggerStrategy.APP_WEBHOOK:
@@ -130,6 +113,35 @@ export const flowTriggerSideEffect = (log: FastifyBaseLogger) => {
}
}
+async function runDisableHook({ params, log }: RunDisableHookParams): Promise<void> {
+ const { flowId, flowVersionId, projectId, simulate, isRepublish, ignoreError } = params
+ const platformId = await projectService(log).getPlatformId(projectId)
+ const { error, data: engineHelperResponse } = await tryCatch(
+ () => userInteractionWatcher.submitAndWaitForResponse<EngineResponse<ExecuteTriggerResponse<TriggerHookType.ON_DISABLE>>>({
+ jobType: WorkerJobType.EXECUTE_TRIGGER_HOOK,
+ hookType: TriggerHookType.ON_DISABLE,
+ flowId,
+ flowVersionId,
+ test: simulate,
+ projectId,
+ platformId,
+ isRepublish,
+ }, log),
+ )
+ if (!isNil(error)) {
+ if (!ignoreError) {
+ throw error
+ }
+ log.warn({ flow: { id: flowId }, error: error.message }, IGNORED_DISABLE_ERROR)
+ }
+ else if (!ignoreError) {
+ assertEngineResponseIsOk(engineHelperResponse!, flowId, flowVersionId)
+ }
+ else if (engineHelperResponse?.status !== EngineResponseStatus.OK) {
+ log.warn({ flow: { id: flowId }, error: sanitizeIgnoredError(engineHelperResponse?.error) }, IGNORED_DISABLE_ERROR)
+ }
+}
+
function sanitizeIgnoredError(error: string | undefined): string {
return tryParseFriendlyPieceError(error)?.message ?? formatPieceError(error).message
}
@@ -181,13 +193,13 @@ async function handleWebhookTrigger({ flowId, flowVersionId, projectId, pieceTri
}
}
-async function handlePollingTrigger({ engineHelperResponse, flowId, flowVersionId, projectId, log }: ActiveTriggerParams): Promise<ActiveTriggerReturn> {
+async function handlePollingTrigger({ flowId, flowVersionId, projectId, scheduleOptions: requestedSchedule, log }: HandlePollingTriggerParams): Promise<ActiveTriggerReturn> {
const pollIntervalMinutes = system.getNumberOrThrow(AppSystemProp.TRIGGER_DEFAULT_POLL_INTERVAL)
const defaultScheduleOptions: ScheduleOptions = {
type: TriggerSourceScheduleType.INTERVAL,
intervalMs: pollIntervalMinutes * 60_000,
}
- const scheduleOptions = engineHelperResponse.response?.scheduleOptions ?? defaultScheduleOptions
+ const scheduleOptions = requestedSchedule ?? defaultScheduleOptions
const platformId = await projectService(log).getPlatformId(projectId)
await jobQueue(log).add({
id: flowVersionId,
@@ -243,12 +255,27 @@ type EnableFlowTriggerParams = {
pieceTrigger: TriggerBase
simulate: boolean
isRepublish?: boolean
+ isTriggerUnchanged?: boolean
+ previousSchedule?: ScheduleOptions
}
-type DisableFlowTriggerParams = EnableFlowTriggerParams & {
+type DisableFlowTriggerParams = Omit<EnableFlowTriggerParams, 'previousSchedule'> & {
ignoreError: boolean
}
+type RunDisableHookParams = {
+ params: DisableFlowTriggerParams
+ log: FastifyBaseLogger
+}
+
+type HandlePollingTriggerParams = {
+ flowId: FlowId
+ flowVersionId: FlowVersionId
+ projectId: string
+ scheduleOptions: ScheduleOptions | undefined
+ log: FastifyBaseLogger
+}
+
type ActiveTriggerParams = EnableFlowTriggerParams & {
log: FastifyBaseLogger
engineHelperResponse: EngineResponse<ExecuteTriggerResponse<TriggerHookType.ON_ENABLE>>
diff --git a/packages/server/api/src/app/trigger/trigger-source/trigger-source-service.ts b/packages/server/api/src/app/trigger/trigger-source/trigger-source-service.ts
index 0b494b404bf..dff77a0e0c5 100644
--- a/packages/server/api/src/app/trigger/trigger-source/trigger-source-service.ts
+++ b/packages/server/api/src/app/trigger/trigger-source/trigger-source-service.ts
@@ -15,7 +15,7 @@ export const triggerSourceRepo = repoFactory(TriggerSourceEntity)
export const triggerSourceService = (log: FastifyBaseLogger) => {
return {
async enable(params: EnableTriggerParams): Promise<TriggerSource> {
- const { flowVersion, projectId, simulate, templateId, isRepublish } = params
+ const { flowVersion, projectId, simulate, templateId, isRepublish, isTriggerUnchanged } = params
log.info({
flow: { id: flowVersion.flowId },
flowVersion: { id: flowVersion.id },
@@ -30,6 +30,7 @@ export const triggerSourceService = (log: FastifyBaseLogger) => {
simulate,
},
withDeleted: true,
+ order: { created: 'DESC' },
})
if (!isNil(existingTriggerSource)) {
await jobQueue(log).removeRepeatingJob({ flowVersionId: existingTriggerSource.flowVersionId })
@@ -61,6 +62,8 @@ export const triggerSourceService = (log: FastifyBaseLogger) => {
pieceTrigger,
simulate,
isRepublish,
+ isTriggerUnchanged,
+ previousSchedule: existingTriggerSource?.schedule ?? undefined,
})
return triggerSourceRepo().save({
...triggerSource,
@@ -196,6 +199,7 @@ export const triggerSourceService = (log: FastifyBaseLogger) => {
simulate,
ignoreError: params.ignoreError,
isRepublish: params.isRepublish,
+ isTriggerUnchanged: params.isTriggerUnchanged,
})
log.info('[triggerSourceService#disable] Disabled flow trigger side effect')
}
@@ -252,6 +256,7 @@ type DisableTriggerParams = {
ignoreError: boolean
templateId?: string
isRepublish?: boolean
+ isTriggerUnchanged?: boolean
}
type EnableTriggerParams = {
@@ -260,4 +265,5 @@ type EnableTriggerParams = {
simulate: boolean
templateId?: string
isRepublish?: boolean
+ isTriggerUnchanged?: boolean
}
diff --git a/packages/server/api/test/integration/ce/flows/flow-run/barrier.test.ts b/packages/server/api/test/integration/ce/flows/flow-run/barrier.test.ts
index 1dcad8365c4..52246f33d93 100644
--- a/packages/server/api/test/integration/ce/flows/flow-run/barrier.test.ts
+++ b/packages/server/api/test/integration/ce/flows/flow-run/barrier.test.ts
@@ -9,8 +9,8 @@ import { transaction } from '../../../../../src/app/core/db/transaction'
import { databaseConnection } from '../../../../../src/app/database/database-connection'
import { distributedStore, redisConnections } from '../../../../../src/app/database/redis-connections'
import { childRunDispatchService } from '../../../../../src/app/flows/flow-run/child-run-dispatch-service'
-import { systemJobIds } from '../../../../../src/app/helper/system-jobs/common'
-import { systemJobsSchedule } from '../../../../../src/app/helper/system-jobs/system-job'
+import { systemJobIds, SystemJobName } from '../../../../../src/app/helper/system-jobs/common'
+import { systemJobsQueue, systemJobsSchedule } from '../../../../../src/app/helper/system-jobs/system-job'
import * as billingProviderModule from '../../../../../src/app/platform/billing-provider'
import { platformConfigurationService } from '../../../../../src/app/platform/platform-configuration.service'
import { barrierQueue } from '../../../../../src/app/waitpoints/barrier-queue'
@@ -776,6 +776,10 @@ describe('signal count limit', () => {
})
describe('barrier deadline', () => {
+ beforeAll(async () => {
+ await systemJobsQueue.removeJobScheduler(SystemJobName.WAITPOINT_DEADLINE_SWEEP)
+ })
+
beforeEach(async () => {
await distributedStore.delete([DEADLINE_SWEEP_CURSOR_KEY, BARRIER_RECOVERY_CURSOR_KEY])
await databaseConnection().query('DELETE FROM "waitpoint"')
diff --git a/packages/server/api/test/integration/ee/flow-approval/approved-republish-keeps-checkpoint.test.ts b/packages/server/api/test/integration/ee/flow-approval/approved-republish-keeps-checkpoint.test.ts
deleted file mode 100644
index 602f2f734bd..00000000000
--- a/packages/server/api/test/integration/ee/flow-approval/approved-republish-keeps-checkpoint.test.ts
+++ /dev/null
@@ -1,244 +0,0 @@
-import {
- apId,
- DefaultProjectRole,
- FlowApprovalRequest,
- FlowApprovalRequestState,
- FlowOperationType,
- FlowStatus,
- FlowTriggerType,
- FlowVersion,
- FlowVersionState,
- PackageType,
- PieceType,
- PropertyExecutionType,
- TriggerStrategy,
- TriggerTestStrategy,
-} from '@activepieces/shared'
-import dayjs from 'dayjs'
-import { FastifyInstance } from 'fastify'
-import { StatusCodes } from 'http-status-codes'
-import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'
-import { db } from '../../../helpers/db'
-import { createMockFlow, createMockFlowVersion, createMockPieceMetadata } from '../../../helpers/mocks'
-import { createMemberContext, createTestContext } from '../../../helpers/test-context'
-import { setupTestEnvironment, teardownTestEnvironment } from '../../../helpers/test-setup'
-
-const triggerCalls = vi.hoisted(() => {
- const calls: TriggerCall[] = []
- return calls
-})
-
-vi.mock('../../../../src/app/trigger/trigger-source/trigger-source-service', async (importOriginal) => {
- const actual = await importOriginal<typeof import('../../../../src/app/trigger/trigger-source/trigger-source-service')>()
- return {
- ...actual,
- triggerSourceService: (log: Parameters<typeof actual.triggerSourceService>[0]) => ({
- ...actual.triggerSourceService(log),
- enable: async (params: { flowVersion: { flowId: string }, simulate: boolean, isRepublish?: boolean }) => {
- if (!params.simulate) {
- triggerCalls.push({ call: 'enable', flowId: params.flowVersion.flowId, isRepublish: params.isRepublish })
- }
- return null
- },
- disable: async (params: { flowId: string, simulate: boolean, isRepublish?: boolean }) => {
- if (!params.simulate) {
- triggerCalls.push({ call: 'disable', flowId: params.flowId, isRepublish: params.isRepublish })
- }
- },
- }),
- }
-})
-
-let app: FastifyInstance | null = null
-
-beforeAll(async () => {
- app = await setupTestEnvironment()
-})
-
-afterAll(async () => {
- await teardownTestEnvironment()
-})
-
-describe('republishing a flow through an approval request', () => {
- it.each([
- {
- name: 'keeps the checkpoint of an enabled flow whose trigger is unchanged',
- flowStatus: FlowStatus.ENABLED,
- requestedStatus: FlowStatus.ENABLED,
- republishedInput: { projectId: 'AP' },
- expected: [{ call: 'disable', isRepublish: true }, { call: 'enable', isRepublish: true }],
- },
- {
- name: 'resets the checkpoint when the trigger input changed',
- flowStatus: FlowStatus.ENABLED,
- requestedStatus: FlowStatus.ENABLED,
- republishedInput: { projectId: 'OTHER' },
- expected: [{ call: 'disable', isRepublish: false }, { call: 'enable', isRepublish: false }],
- },
- {
- name: 'resets the checkpoint when the flow was disabled',
- flowStatus: FlowStatus.DISABLED,
- requestedStatus: FlowStatus.ENABLED,
- republishedInput: { projectId: 'AP' },
- expected: [{ call: 'enable', isRepublish: false }],
- },
- {
- name: 'only disables the old trigger when the approved publish keeps the flow disabled',
- flowStatus: FlowStatus.ENABLED,
- requestedStatus: FlowStatus.DISABLED,
- republishedInput: { projectId: 'AP' },
- expected: [{ call: 'disable', isRepublish: false }],
- },
- ])('$name', async ({ flowStatus, requestedStatus, republishedInput, expected }) => {
- const { statusCode, calls } = await approveRepublish({ flowStatus, requestedStatus, republishedInput })
-
- expect(statusCode).toBe(StatusCodes.OK)
- expect(calls).toEqual(expected)
- })
-})
-
-describe('republishing a flow directly', () => {
- it.each([
- {
- name: 'keeps the checkpoint of an enabled flow whose trigger is unchanged',
- draftInput: { projectId: 'AP' },
- requestedStatus: FlowStatus.ENABLED,
- expected: [{ call: 'disable', isRepublish: true }, { call: 'enable', isRepublish: true }],
- },
- {
- name: 'resets the checkpoint when the trigger input changed',
- draftInput: { projectId: 'OTHER' },
- requestedStatus: FlowStatus.ENABLED,
- expected: [{ call: 'disable', isRepublish: false }, { call: 'enable', isRepublish: false }],
- },
- {
- name: 'clears the old trigger when the publish keeps the flow disabled',
- draftInput: { projectId: 'AP' },
- requestedStatus: FlowStatus.DISABLED,
- expected: [{ call: 'disable', isRepublish: false }],
- },
- {
- name: 'resets the checkpoint when the piece version changed',
- draftInput: { projectId: 'AP' },
- draftPieceVersion: '0.4.2',
- requestedStatus: FlowStatus.ENABLED,
- expected: [{ call: 'disable', isRepublish: false }, { call: 'enable', isRepublish: false }],
- },
- ])('$name', async ({ draftInput, draftPieceVersion, requestedStatus, expected }) => {
- const ctx = await createTestContext(app!)
- await db.save('piece_metadata', jiraPollingPiece({ version: '0.4.1' }))
- await db.save('piece_metadata', jiraPollingPiece({ version: '0.4.2' }))
- const flow = createMockFlow({ projectId: ctx.project.id, status: FlowStatus.ENABLED })
- await db.save('flow', flow)
- const published = createMockFlowVersion({ flowId: flow.id, state: FlowVersionState.LOCKED, valid: true, trigger: pollingTrigger({ input: { projectId: 'AP' } }) })
- await db.save('flow_version', published)
- await db.update('flow', flow.id, { publishedVersionId: published.id })
- const draft = createMockFlowVersion({ flowId: flow.id, state: FlowVersionState.DRAFT, valid: true, created: dayjs().add(1, 'minute').toISOString(), trigger: pollingTrigger({ input: draftInput, pieceVersion: draftPieceVersion }) })
- await db.save('flow_version', draft)
-
- const response = await ctx.post(`/v1/flows/${flow.id}`, { type: FlowOperationType.LOCK_AND_PUBLISH, request: { status: requestedStatus } })
-
- expect(response?.statusCode).toBe(StatusCodes.OK)
- expect(recordedCalls({ flowId: flow.id })).toEqual(expected)
- })
-})
-
-async function approveRepublish({ flowStatus, requestedStatus, republishedInput }: ApproveRepublishParams): Promise<ApproveRepublishResult> {
- const ctx = await createTestContext(app!, { plan: { environmentsEnabled: true } })
- await db.update('project', ctx.project.id, { sensitive: true })
- const memberCtx = await createMemberContext(app!, ctx, { projectRole: DefaultProjectRole.EDITOR })
-
- const flow = createMockFlow({ projectId: ctx.project.id, status: flowStatus })
- await db.save('flow', flow)
- const published = createMockFlowVersion({ flowId: flow.id, state: FlowVersionState.LOCKED, valid: true, trigger: pollingTrigger({ input: { projectId: 'AP' } }) })
- await db.save('flow_version', published)
- await db.update('flow', flow.id, { publishedVersionId: published.id })
- const republished = createMockFlowVersion({ flowId: flow.id, state: FlowVersionState.LOCKED, valid: true, trigger: pollingTrigger({ input: republishedInput }) })
- await db.save('flow_version', republished)
- const now = new Date().toISOString()
- const approval: FlowApprovalRequest = {
- id: apId(),
- created: now,
- updated: now,
- flowId: flow.id,
- flowVersionId: republished.id,
- projectId: ctx.project.id,
- platformId: ctx.platform.id,
- submitterId: memberCtx.user.id,
- submittedAt: now,
- approverId: null,
- decidedAt: null,
- state: FlowApprovalRequestState.PENDING,
- requestedStatus,
- rejectionReason: null,
- }
- await db.save('flow_approval_request', approval)
-
- const response = await ctx.post(`/v1/flow-approval-requests/${approval.id}/approve`, {})
-
- return {
- statusCode: response?.statusCode,
- calls: recordedCalls({ flowId: flow.id }),
- }
-}
-
-function recordedCalls({ flowId }: { flowId: string }): Omit<TriggerCall, 'flowId'>[] {
- return triggerCalls.filter((call) => call.flowId === flowId).map(({ call, isRepublish }) => ({ call, isRepublish }))
-}
-
-function jiraPollingPiece({ version }: { version: string }): ReturnType<typeof createMockPieceMetadata> {
- return createMockPieceMetadata({
- name: '@activepieces/piece-jira-cloud',
- version,
- triggers: {
- new_issue: {
- name: 'new_issue',
- displayName: 'New Issue',
- description: 'New Issue',
- requireAuth: false,
- props: {},
- type: TriggerStrategy.POLLING,
- sampleData: {},
- testStrategy: TriggerTestStrategy.TEST_FUNCTION,
- },
- },
- pieceType: PieceType.OFFICIAL,
- packageType: PackageType.REGISTRY,
- })
-}
-
-function pollingTrigger({ input, pieceVersion = '0.4.1' }: { input: Record<string, unknown>, pieceVersion?: string }): FlowVersion['trigger'] {
- return {
- type: FlowTriggerType.PIECE,
- settings: {
- pieceName: '@activepieces/piece-jira-cloud',
- pieceVersion,
- triggerName: 'new_issue',
- input,
- propertySettings: {
- projectId: { type: PropertyExecutionType.MANUAL },
- },
- },
- valid: true,
- name: 'trigger',
- displayName: 'New Issue',
- lastUpdatedDate: new Date().toISOString(),
- }
-}
-
-type TriggerCall = {
- call: 'enable' | 'disable'
- flowId: string
- isRepublish?: boolean
-}
-
-type ApproveRepublishParams = {
- flowStatus: FlowStatus
- requestedStatus: FlowStatus
- republishedInput: Record<string, unknown>
-}
-
-type ApproveRepublishResult = {
- statusCode: number | undefined
- calls: Omit<TriggerCall, 'flowId'>[]
-}
diff --git a/packages/server/api/test/unit/app/flows/flow/flow-publish-utils.test.ts b/packages/server/api/test/unit/app/flows/flow/flow-publish-utils.test.ts
index 9805cedb7e9..cd3eb67700e 100644
--- a/packages/server/api/test/unit/app/flows/flow/flow-publish-utils.test.ts
+++ b/packages/server/api/test/unit/app/flows/flow/flow-publish-utils.test.ts
@@ -1,13 +1,13 @@
-import { FlowTriggerType, FlowVersion, PropertyExecutionType } from '@activepieces/shared'
+import { FlowStatus, FlowTriggerType, FlowVersion, FlowVersionState, PropertyExecutionType } from '@activepieces/shared'
import { describe, expect, it } from 'vitest'
import { flowPublishUtils } from '../../../../../src/app/flows/flow/flow-publish-utils'
-function pieceTrigger(overrides: { pieceName?: string, triggerName?: string, input?: Record<string, unknown> } = {}): FlowVersion['trigger'] {
+function pieceTrigger(overrides: { pieceName?: string, pieceVersion?: string, triggerName?: string, input?: Record<string, unknown> } = {}): FlowVersion['trigger'] {
return {
type: FlowTriggerType.PIECE,
settings: {
pieceName: overrides.pieceName ?? '@activepieces/piece-jira-cloud',
- pieceVersion: '0.4.1',
+ pieceVersion: overrides.pieceVersion ?? '0.4.1',
triggerName: overrides.triggerName ?? 'new_issue',
input: overrides.input ?? { projectId: 'AP', maxResults: 50 },
propertySettings: {
@@ -80,3 +80,82 @@ describe('flowPublishUtils.isSameTrigger', () => {
})).toBe(false)
})
})
+
+describe('flowPublishUtils.isRepublish', () => {
+ it('is true when the flow was live and is republished enabled with the same trigger', () => {
+ expect(flowPublishUtils.isRepublish({
+ previouslyPublished: versionWith(pieceTrigger()),
+ toPublish: versionWith(pieceTrigger()),
+ requestedStatus: FlowStatus.ENABLED,
+ })).toBe(true)
+ })
+
+ it('is false when there was no live version', () => {
+ expect(flowPublishUtils.isRepublish({
+ previouslyPublished: undefined,
+ toPublish: versionWith(pieceTrigger()),
+ requestedStatus: FlowStatus.ENABLED,
+ })).toBe(false)
+ })
+
+ it('is false when the publish leaves the flow disabled', () => {
+ expect(flowPublishUtils.isRepublish({
+ previouslyPublished: versionWith(pieceTrigger()),
+ toPublish: versionWith(pieceTrigger()),
+ requestedStatus: FlowStatus.DISABLED,
+ })).toBe(false)
+ })
+
+ it('is false when the trigger input changed', () => {
+ expect(flowPublishUtils.isRepublish({
+ previouslyPublished: versionWith(pieceTrigger()),
+ toPublish: versionWith(pieceTrigger({ input: { projectId: 'OPS', maxResults: 50 } })),
+ requestedStatus: FlowStatus.ENABLED,
+ })).toBe(false)
+ })
+})
+
+describe('flowPublishUtils.isTriggerUnchanged', () => {
+ it('is true for a republish that keeps the piece version', () => {
+ expect(flowPublishUtils.isTriggerUnchanged({
+ previouslyPublished: versionWith(pieceTrigger()),
+ toPublish: versionWith(pieceTrigger()),
+ requestedStatus: FlowStatus.ENABLED,
+ })).toBe(true)
+ })
+
+ it('is false when the piece was upgraded, even with the same inputs', () => {
+ expect(flowPublishUtils.isTriggerUnchanged({
+ previouslyPublished: versionWith(pieceTrigger()),
+ toPublish: versionWith(pieceTrigger({ pieceVersion: '0.5.0' })),
+ requestedStatus: FlowStatus.ENABLED,
+ })).toBe(false)
+ })
+
+ it('is false when it is not a republish', () => {
+ expect(flowPublishUtils.isTriggerUnchanged({
+ previouslyPublished: undefined,
+ toPublish: versionWith(pieceTrigger()),
+ requestedStatus: FlowStatus.ENABLED,
+ })).toBe(false)
+ })
+})
+
+function versionWith(trigger: FlowVersion['trigger']): FlowVersion {
+ return {
+ id: 'version-id',
+ created: '2026-08-04T00:00:00.000Z',
+ updated: '2026-08-04T00:00:00.000Z',
+ flowId: 'flow-id',
+ displayName: 'Flow',
+ trigger,
+ updatedBy: null,
+ valid: true,
+ schemaVersion: null,
+ state: FlowVersionState.LOCKED,
+ connectionIds: [],
+ agentIds: [],
+ notes: [],
+ backupFiles: null,
+ }
+}
diff --git a/packages/server/api/test/unit/app/flows/trigger/flow-trigger-side-effect.test.ts b/packages/server/api/test/unit/app/flows/trigger/flow-trigger-side-effect.test.ts
index c9118e98b20..44891eb095b 100644
--- a/packages/server/api/test/unit/app/flows/trigger/flow-trigger-side-effect.test.ts
+++ b/packages/server/api/test/unit/app/flows/trigger/flow-trigger-side-effect.test.ts
@@ -379,4 +379,91 @@ describe('flowTriggerSideEffect', () => {
})
})
})
+
+ describe('republish with an unchanged trigger', () => {
+ const previousSchedule = {
+ type: TriggerSourceScheduleType.CRON_EXPRESSION,
+ cronExpression: '*/15 * * * *',
+ timezone: 'UTC',
+ }
+
+ it('keeps a polling trigger running on the previous schedule without calling onEnable', async () => {
+ const result = await flowTriggerSideEffect(mockLog).enable({
+ ...BASE_PARAMS,
+ pieceTrigger: makePollingTrigger(),
+ isRepublish: true,
+ isTriggerUnchanged: true,
+ previousSchedule,
+ })
+
+ expect(mockSubmitAndWaitForResponse).not.toHaveBeenCalled()
+ expect(result.scheduleOptions).toEqual(previousSchedule)
+ expect(mockAddJob).toHaveBeenCalledWith(expect.objectContaining({
+ id: BASE_PARAMS.flowVersionId,
+ scheduleOptions: previousSchedule,
+ }))
+ })
+
+ it('skips onDisable for a polling trigger but still removes the old poll job', async () => {
+ await flowTriggerSideEffect(mockLog).disable({
+ ...BASE_PARAMS,
+ pieceTrigger: makePollingTrigger(),
+ ignoreError: true,
+ isRepublish: true,
+ isTriggerUnchanged: true,
+ })
+
+ expect(mockSubmitAndWaitForResponse).not.toHaveBeenCalled()
+ expect(mockRemoveRepeatingJob).toHaveBeenCalledWith({ flowVersionId: BASE_PARAMS.flowVersionId })
+ })
+
+ it('runs onEnable when there is no previous schedule to keep', async () => {
+ mockSubmitAndWaitForResponse.mockResolvedValue(okEngineResponse())
+
+ await flowTriggerSideEffect(mockLog).enable({
+ ...BASE_PARAMS,
+ pieceTrigger: makePollingTrigger(),
+ isRepublish: true,
+ isTriggerUnchanged: true,
+ })
+
+ expect(mockSubmitAndWaitForResponse).toHaveBeenCalledOnce()
+ })
+
+ it('runs both hooks with isRepublish when only the inputs match, such as a piece upgrade', async () => {
+ mockSubmitAndWaitForResponse.mockResolvedValue(okEngineResponse())
+
+ await flowTriggerSideEffect(mockLog).disable({
+ ...BASE_PARAMS,
+ pieceTrigger: makePollingTrigger(),
+ ignoreError: true,
+ isRepublish: true,
+ isTriggerUnchanged: false,
+ })
+ await flowTriggerSideEffect(mockLog).enable({
+ ...BASE_PARAMS,
+ pieceTrigger: makePollingTrigger(),
+ isRepublish: true,
+ isTriggerUnchanged: false,
+ previousSchedule,
+ })
+
+ expect(mockSubmitAndWaitForResponse).toHaveBeenCalledTimes(2)
+ expect(mockSubmitAndWaitForResponse).toHaveBeenNthCalledWith(1, expect.objectContaining({ isRepublish: true }), mockLog)
+ expect(mockSubmitAndWaitForResponse).toHaveBeenNthCalledWith(2, expect.objectContaining({ isRepublish: true }), mockLog)
+ })
+
+ it('still runs the hooks for a trigger that is not polling', async () => {
+ mockSubmitAndWaitForResponse.mockResolvedValue(okEngineResponse())
+
+ await flowTriggerSideEffect(mockLog).disable({
+ ...BASE_PARAMS,
+ pieceTrigger: makeManualTrigger(),
+ ignoreError: true,
+ isTriggerUnchanged: true,
+ })
+
+ expect(mockSubmitAndWaitForResponse).toHaveBeenCalledOnce()
+ })
+ })
})
diff --git a/packages/server/engine/src/lib/helper/trigger-helper.ts b/packages/server/engine/src/lib/helper/trigger-helper.ts
index 807141b6808..d87f84a208c 100644
--- a/packages/server/engine/src/lib/helper/trigger-helper.ts
+++ b/packages/server/engine/src/lib/helper/trigger-helper.ts
@@ -6,7 +6,6 @@ import { EngineConstants, ResolvedExecuteTriggerOperation } from '../handler/con
import { FlowExecutorContext } from '../handler/context/flow-execution-context'
import { createFileUploader } from '../piece-context/file-uploader'
import { createFlowsContext } from '../piece-context/flows'
-import { republishStore } from '../piece-context/republish-store'
import { createContextStore } from '../piece-context/store'
import { utils } from '../utils'
import { propsProcessor } from '../variables/props-processor'
@@ -165,17 +164,11 @@ export const triggerHelper = {
}
switch (params.hookType) {
case TriggerHookType.ON_DISABLE: {
- await pieceTrigger.onDisable({
- ...context,
- store: republishStore.forLifecycleHook({ store: context.store, isRepublish: params.isRepublish, triggerType: pieceTrigger.type }),
- })
+ await pieceTrigger.onDisable(context)
return {}
}
case TriggerHookType.ON_ENABLE: {
- await pieceTrigger.onEnable({
- ...context,
- store: republishStore.forLifecycleHook({ store: context.store, isRepublish: params.isRepublish, triggerType: pieceTrigger.type }),
- })
+ await pieceTrigger.onEnable(context)
return {
listeners: appListeners,
scheduleOptions: pieceTrigger.type === TriggerStrategy.POLLING ? scheduleOptions : undefined,
diff --git a/packages/server/engine/src/lib/piece-context/republish-store.ts b/packages/server/engine/src/lib/piece-context/republish-store.ts
deleted file mode 100644
index f9be5800600..00000000000
--- a/packages/server/engine/src/lib/piece-context/republish-store.ts
+++ /dev/null
@@ -1,25 +0,0 @@
-import { Store, TriggerStrategy } from '@activepieces/pieces-framework'
-
-export const republishStore = {
- forLifecycleHook({ store, isRepublish, triggerType }: RepublishStoreParams): Store {
- const keepsPollingState = isRepublish === true && triggerType === TriggerStrategy.POLLING
- return keepsPollingState ? readOnly(store) : store
- },
-}
-
-function readOnly(store: Store): Store {
- return {
- get: (key, scope) => store.get(key, scope),
- async put<T>(_key: string, value: T): Promise<T> {
- return value
- },
- async delete(): Promise<void> {
- },
- }
-}
-
-type RepublishStoreParams = {
- store: Store
- isRepublish: boolean | undefined
- triggerType: TriggerStrategy
-}
diff --git a/packages/server/engine/test/helper/trigger-helper-republish.test.ts b/packages/server/engine/test/helper/trigger-helper-republish.test.ts
deleted file mode 100644
index 1a10de1dd32..00000000000
--- a/packages/server/engine/test/helper/trigger-helper-republish.test.ts
+++ /dev/null
@@ -1,200 +0,0 @@
-import { Store, TriggerStrategy } from '@activepieces/pieces-framework'
-import { ExecuteTriggerResponse, FlowVersionState, TriggerHookType } from '@activepieces/shared'
-import { beforeEach, describe, expect, it, vi } from 'vitest'
-
-const { mockGetPieceAndTriggerOrThrow, storeEntries } = vi.hoisted(() => ({
- mockGetPieceAndTriggerOrThrow: vi.fn(),
- storeEntries: new Map<string, unknown>(),
-}))
-vi.mock('../../src/lib/helper/piece-loader', () => ({
- pieceLoader: {
- getPieceAndTriggerOrThrow: mockGetPieceAndTriggerOrThrow,
- },
-}))
-vi.mock('../../src/lib/piece-context/store', () => ({
- createContextStore: (): Store => ({
- async put<T>(key: string, value: T): Promise<T> {
- storeEntries.set(key, value)
- return value
- },
- async get<T>(key: string): Promise<T | null> {
- return storeEntries.has(key) ? storeEntries.get(key) as T : null
- },
- async delete(key: string): Promise<void> {
- storeEntries.delete(key)
- },
- }),
-}))
-
-import { EngineConstants, ResolvedExecuteTriggerOperation } from '../../src/lib/handler/context/engine-constants'
-import { triggerHelper } from '../../src/lib/helper/trigger-helper'
-
-describe('a republish leaves a polling trigger\'s stored state untouched', () => {
- beforeEach(() => {
- mockGetPieceAndTriggerOrThrow.mockReset()
- storeEntries.clear()
- })
-
- it('keeps the checkpoint onEnable overwrites', async () => {
- storeEntries.set('lastPoll', OLD_CHECKPOINT)
- mockTrigger({ type: TriggerStrategy.POLLING, onEnable: async ({ store }) => {
- await store.put('lastPoll', NEW_CHECKPOINT)
- } })
-
- await executeHook({ hookType: TriggerHookType.ON_ENABLE, isRepublish: true })
-
- expect(storeEntries.get('lastPoll')).toBe(OLD_CHECKPOINT)
- })
-
- it('keeps the checkpoint onDisable deletes', async () => {
- storeEntries.set('_seenVideoIds', ['video-1'])
- mockTrigger({ type: TriggerStrategy.POLLING, onDisable: async ({ store }) => {
- await store.delete('_seenVideoIds')
- } })
-
- await executeHook({ hookType: TriggerHookType.ON_DISABLE, isRepublish: true })
-
- expect(storeEntries.get('_seenVideoIds')).toEqual(['video-1'])
- })
-
- it('keeps the checkpoint onDisable clears by writing null', async () => {
- storeEntries.set('_new_incoming_sms_trigger', { sid: 'message-1' })
- mockTrigger({
- type: TriggerStrategy.POLLING,
- onDisable: async ({ store }) => {
- await store.put('_new_incoming_sms_trigger', null)
- },
- onEnable: async ({ store }) => {
- const last = await store.get('_new_incoming_sms_trigger')
- if (last === null) {
- await store.put('_new_incoming_sms_trigger', { sid: 'message-now' })
- }
- },
- })
-
- await executeHook({ hookType: TriggerHookType.ON_DISABLE, isRepublish: true })
- await executeHook({ hookType: TriggerHookType.ON_ENABLE, isRepublish: true })
-
- expect(storeEntries.get('_new_incoming_sms_trigger')).toEqual({ sid: 'message-1' })
- })
-
- it('does not let onEnable replace the checkpoint with new scan state', async () => {
- storeEntries.set('lastItem', 'checkout-1')
- mockTrigger({ type: TriggerStrategy.POLLING, onEnable: async ({ store }) => {
- await store.put('newestCheckoutScanCursor', 'checkout-99')
- await store.put('newestCheckoutScanEnabledAt', NEW_CHECKPOINT)
- await store.delete('lastItem')
- } })
-
- await executeHook({ hookType: TriggerHookType.ON_ENABLE, isRepublish: true })
-
- expect(Object.fromEntries(storeEntries)).toEqual({ lastItem: 'checkout-1' })
- })
-
- it('still registers the polling schedule', async () => {
- mockTrigger({ type: TriggerStrategy.POLLING, onEnable: async ({ store, setSchedule }) => {
- await store.put('lastPoll', NEW_CHECKPOINT)
- setSchedule({ cronExpression: '*/5 * * * *' })
- } })
-
- const response = await executeHook({ hookType: TriggerHookType.ON_ENABLE, isRepublish: true })
-
- expect(response).toMatchObject({ scheduleOptions: { cronExpression: '*/5 * * * *' } })
- })
-})
-
-describe('outside a republish the store behaves normally', () => {
- beforeEach(() => {
- mockGetPieceAndTriggerOrThrow.mockReset()
- storeEntries.clear()
- })
-
- it('lets onEnable reset the checkpoint on a fresh enable', async () => {
- storeEntries.set('lastPoll', OLD_CHECKPOINT)
- mockTrigger({ type: TriggerStrategy.POLLING, onEnable: async ({ store }) => {
- await store.put('lastPoll', NEW_CHECKPOINT)
- } })
-
- await executeHook({ hookType: TriggerHookType.ON_ENABLE, isRepublish: false })
-
- expect(storeEntries.get('lastPoll')).toBe(NEW_CHECKPOINT)
- })
-
- it('lets onDisable clean up when the flow is turned off', async () => {
- storeEntries.set('_seenVideoIds', ['video-1'])
- mockTrigger({ type: TriggerStrategy.POLLING, onDisable: async ({ store }) => {
- await store.delete('_seenVideoIds')
- } })
-
- await executeHook({ hookType: TriggerHookType.ON_DISABLE, isRepublish: false })
-
- expect(storeEntries.has('_seenVideoIds')).toBe(false)
- })
-
- it('lets a webhook trigger replace its webhook on a republish', async () => {
- storeEntries.set('webhookId', 'old-webhook')
- mockTrigger({
- type: TriggerStrategy.WEBHOOK,
- onDisable: async ({ store }) => {
- await store.delete('webhookId')
- },
- onEnable: async ({ store }) => {
- await store.put('webhookId', 'new-webhook')
- },
- })
-
- await executeHook({ hookType: TriggerHookType.ON_DISABLE, isRepublish: true })
- await executeHook({ hookType: TriggerHookType.ON_ENABLE, isRepublish: true })
-
- expect(storeEntries.get('webhookId')).toBe('new-webhook')
- })
-})
-
-function mockTrigger({ type, onEnable, onDisable }: { type: TriggerStrategy, onEnable?: (context: HookContext) => Promise<void>, onDisable?: (context: HookContext) => Promise<void> }): void {
- mockGetPieceAndTriggerOrThrow.mockResolvedValue({
- piece: { auth: undefined },
- pieceTrigger: { type, props: {}, requireAuth: false, onEnable, onDisable },
- })
-}
-
-async function executeHook({ hookType, isRepublish }: { hookType: TriggerHookType.ON_ENABLE | TriggerHookType.ON_DISABLE, isRepublish: boolean }): Promise<ExecuteTriggerResponse<TriggerHookType>> {
- const params = {
- hookType,
- test: false,
- isRepublish,
- webhookUrl: 'http://127.0.0.1:3000/api/v1/webhooks/flow-1',
- flowVersion: {
- id: 'flow-version-1',
- flowId: 'flow-1',
- state: FlowVersionState.LOCKED,
- trigger: {
- name: 'trigger',
- type: 'PIECE_TRIGGER',
- valid: true,
- displayName: 'Polling trigger',
- settings: {
- pieceName: '@activepieces/piece-under-test',
- pieceVersion: '1.0.0',
- triggerName: 'new_item',
- input: {},
- propertySettings: {},
- },
- },
- },
- projectId: 'project-1',
- platformId: 'platform-1',
- engineToken: 'engine-token',
- internalApiUrl: 'http://127.0.0.1:3000/api/',
- publicApiUrl: 'http://127.0.0.1:4200/api/',
- timeoutInSeconds: 30,
- } as unknown as ResolvedExecuteTriggerOperation<TriggerHookType>
- return triggerHelper.executeTrigger({ params, constants: EngineConstants.fromExecuteTriggerInput(params) })
-}
-
-const OLD_CHECKPOINT = 1000
-const NEW_CHECKPOINT = 2000
-
-type HookContext = {
- store: Store
- setSchedule: (request: { cronExpression: string }) => void
-}