Skip to content

armgit / dify

Public Imported from GitHub
0

Build Agentic workflows, RAG pipelines, with rich AI model and tool support on one collaborative workspace. Deploy on cloud, VPC, or self-hosted, so teams move from prototype to production without rebuilding the stack.

fix: fix undo delete operation for webhook trigger node lead the url … (#42069)

wangxiaoleiadedbf1f12f9
diff --git a/api/events/event_handlers/sync_webhook_when_app_created.py b/api/events/event_handlers/sync_webhook_when_app_created.py
index 481561faa2f..7fd23a8dfa4 100644
--- a/api/events/event_handlers/sync_webhook_when_app_created.py
+++ b/api/events/event_handlers/sync_webhook_when_app_created.py
@@ -1,6 +1,6 @@
import logging
-from events.app_event import app_draft_workflow_was_synced
+from events.app_event import app_draft_workflow_was_synced, app_published_workflow_was_updated
from models.model import App, AppMode
from models.workflow import Workflow
from services.trigger.webhook_service import WebhookService
@@ -19,4 +19,14 @@ def handle(sender, synced_draft_workflow: Workflow, **kwargs):
# only handle workflow app, chatflow is not supported yet
return
- WebhookService.sync_webhook_relationships(app, synced_draft_workflow)
+ WebhookService.sync_webhook_relationships(app, synced_draft_workflow, remove_stale=False)
+
+
+@app_published_workflow_was_updated.connect
+def handle_published(sender, published_workflow: Workflow, **kwargs):
+ """Remove stale webhook relationships after their node deletion is published."""
+ app: App = sender
+ if app.mode != AppMode.WORKFLOW.value:
+ return
+
+ WebhookService.sync_webhook_relationships(app, published_workflow, remove_stale=True)
diff --git a/api/services/trigger/webhook_service.py b/api/services/trigger/webhook_service.py
index 809693aa415..382fd1ed3d7 100644
--- a/api/services/trigger/webhook_service.py
+++ b/api/services/trigger/webhook_service.py
@@ -887,13 +887,17 @@ class WebhookService:
return response_data, status_code
@classmethod
- def sync_webhook_relationships(cls, app: App, workflow: Workflow):
+ def sync_webhook_relationships(cls, app: App, workflow: Workflow, *, remove_stale: bool = True):
"""
Sync webhook relationships in DB.
1. Check if the workflow has any webhook trigger nodes
2. Fetch the nodes from DB, see if there were any webhook records already
- 3. Diff the nodes and the webhook records, create/update/delete the webhook records as needed
+ 3. Diff the nodes and the webhook records, creating missing records and optionally deleting stale records
+
+ Draft workflow synchronization preserves stale records so undo can restore a
+ webhook node without changing its URL. Published workflow synchronization
+ removes stale records after the deletion becomes effective.
Approach:
Frequent DB operations may cause performance issues, using Redis to cache it instead.
@@ -969,11 +973,12 @@ class WebhookService:
f"{cls.__WEBHOOK_NODE_CACHE_KEY__}:{app.id}:{node_id}", cache.model_dump_json(), ex=60 * 60
)
- # delete the nodes not found in the graph
- for node_id in nodes_id_in_db:
- if node_id not in nodes_id_in_graph:
- session.delete(nodes_id_in_db[node_id])
- redis_client.delete(f"{cls.__WEBHOOK_NODE_CACHE_KEY__}:{app.id}:{node_id}")
+ if remove_stale:
+ # Delete relationships only when reconciling an effective published workflow.
+ for node_id in nodes_id_in_db:
+ if node_id not in nodes_id_in_graph:
+ session.delete(nodes_id_in_db[node_id])
+ redis_client.delete(f"{cls.__WEBHOOK_NODE_CACHE_KEY__}:{app.id}:{node_id}")
except Exception:
logger.exception("Failed to sync webhook relationships for app %s", app.id)
raise
diff --git a/api/tests/unit_tests/events/event_handlers/test_sync_webhook_when_app_created.py b/api/tests/unit_tests/events/event_handlers/test_sync_webhook_when_app_created.py
new file mode 100644
index 00000000000..9f450474ec0
--- /dev/null
+++ b/api/tests/unit_tests/events/event_handlers/test_sync_webhook_when_app_created.py
@@ -0,0 +1,32 @@
+from types import SimpleNamespace
+from typing import cast
+from unittest.mock import patch
+
+from events.event_handlers import sync_webhook_when_app_created
+from events.event_handlers.sync_webhook_when_app_created import handle
+from models.model import App
+from models.workflow import Workflow
+
+
+def test_draft_sync_preserves_stale_webhook_relationships() -> None:
+ app = cast(App, SimpleNamespace(mode="workflow"))
+ workflow = cast(Workflow, SimpleNamespace())
+
+ with patch(
+ "events.event_handlers.sync_webhook_when_app_created.WebhookService.sync_webhook_relationships"
+ ) as sync_webhook_relationships:
+ handle(app, synced_draft_workflow=workflow)
+
+ sync_webhook_relationships.assert_called_once_with(app, workflow, remove_stale=False)
+
+
+def test_published_sync_removes_stale_webhook_relationships() -> None:
+ app = cast(App, SimpleNamespace(mode="workflow"))
+ workflow = cast(Workflow, SimpleNamespace())
+
+ with patch(
+ "events.event_handlers.sync_webhook_when_app_created.WebhookService.sync_webhook_relationships"
+ ) as sync_webhook_relationships:
+ sync_webhook_when_app_created.handle_published(app, published_workflow=workflow)
+
+ sync_webhook_relationships.assert_called_once_with(app, workflow, remove_stale=True)
diff --git a/api/tests/unit_tests/services/test_webhook_service_relationships.py b/api/tests/unit_tests/services/test_webhook_service_relationships.py
new file mode 100644
index 00000000000..ed22c91624a
--- /dev/null
+++ b/api/tests/unit_tests/services/test_webhook_service_relationships.py
@@ -0,0 +1,94 @@
+from types import SimpleNamespace
+from typing import cast
+from unittest.mock import MagicMock
+
+import pytest
+from sqlalchemy import Engine, Table, select
+from sqlalchemy.orm import Session, sessionmaker
+
+from core.trigger.constants import TRIGGER_WEBHOOK_NODE_TYPE
+from models.base import TypeBase
+from models.model import App
+from models.trigger import WorkflowWebhookTrigger
+from models.workflow import Workflow
+from services.trigger import webhook_service
+from services.trigger.webhook_service import WebhookService
+
+
+def test_draft_sync_preserves_webhook_id_when_deleted_node_is_restored(
+ monkeypatch: pytest.MonkeyPatch, sqlite_engine: Engine
+) -> None:
+ webhook_trigger_table = cast(Table, WorkflowWebhookTrigger.__table__)
+ TypeBase.metadata.create_all(sqlite_engine, tables=[webhook_trigger_table])
+ session_maker = sessionmaker(bind=sqlite_engine, expire_on_commit=False)
+ app = cast(
+ App,
+ SimpleNamespace(id="00000000-0000-0000-0000-000000000001", tenant_id="tenant-1", created_by="user-1"),
+ )
+ webhook_trigger = WorkflowWebhookTrigger(
+ app_id=app.id,
+ tenant_id=app.tenant_id,
+ node_id="webhook-node",
+ webhook_id="stable-webhook-id",
+ created_by=app.created_by,
+ )
+ with session_maker.begin() as session:
+ session.add(webhook_trigger)
+ original_record_id = webhook_trigger.id
+
+ redis = MagicMock()
+ redis.get.return_value = None
+ redis.lock.return_value.acquire.return_value = True
+ monkeypatch.setattr(webhook_service, "db", SimpleNamespace(engine=sqlite_engine))
+ monkeypatch.setattr(webhook_service, "redis_client", redis)
+
+ deleted_draft = cast(Workflow, SimpleNamespace(walk_nodes=lambda _node_type: iter(())))
+ WebhookService.sync_webhook_relationships(app, deleted_draft, remove_stale=False)
+
+ restored_draft = cast(
+ Workflow,
+ SimpleNamespace(walk_nodes=lambda _node_type: iter([("webhook-node", {"type": TRIGGER_WEBHOOK_NODE_TYPE})])),
+ )
+ WebhookService.sync_webhook_relationships(app, restored_draft, remove_stale=False)
+
+ with Session(sqlite_engine) as session:
+ records = session.scalars(select(WorkflowWebhookTrigger)).all()
+
+ assert len(records) == 1
+ assert records[0].id == original_record_id
+ assert records[0].webhook_id == "stable-webhook-id"
+
+
+def test_published_sync_removes_stale_webhook_relationships(
+ monkeypatch: pytest.MonkeyPatch, sqlite_engine: Engine
+) -> None:
+ webhook_trigger_table = cast(Table, WorkflowWebhookTrigger.__table__)
+ TypeBase.metadata.create_all(sqlite_engine, tables=[webhook_trigger_table])
+ session_maker = sessionmaker(bind=sqlite_engine, expire_on_commit=False)
+ app = cast(
+ App,
+ SimpleNamespace(id="00000000-0000-0000-0000-000000000001", tenant_id="tenant-1", created_by="user-1"),
+ )
+ webhook_trigger = WorkflowWebhookTrigger(
+ app_id=app.id,
+ tenant_id=app.tenant_id,
+ node_id="deleted-webhook-node",
+ webhook_id="deleted-webhook-id",
+ created_by=app.created_by,
+ )
+ with session_maker.begin() as session:
+ session.add(webhook_trigger)
+
+ redis = MagicMock()
+ redis.get.return_value = None
+ redis.lock.return_value.acquire.return_value = True
+ monkeypatch.setattr(webhook_service, "db", SimpleNamespace(engine=sqlite_engine))
+ monkeypatch.setattr(webhook_service, "redis_client", redis)
+
+ published_workflow = cast(Workflow, SimpleNamespace(walk_nodes=lambda _node_type: iter(())))
+ WebhookService.sync_webhook_relationships(app, published_workflow, remove_stale=True)
+
+ with session_maker() as session:
+ records = session.scalars(select(WorkflowWebhookTrigger)).all()
+ assert records == []
+ redis.delete.assert_called_once_with(f"{WebhookService.__WEBHOOK_NODE_CACHE_KEY__}:{app.id}:deleted-webhook-node")