From 2a178a90a4d6265e193074b9e980326267fb8e5e Mon Sep 17 00:00:00 2001 From: Damien Garros Date: Wed, 30 Oct 2024 15:54:50 +0100 Subject: [PATCH] Convert BranchDelete task and event to Prefect --- .github/workflows/ci.yml | 1 + backend/infrahub/core/branch/tasks.py | 19 +++++- backend/infrahub/events/branch_action.py | 35 ++++++++++ backend/infrahub/events/models.py | 2 +- backend/infrahub/events/node_action.py | 21 +++--- backend/infrahub/graphql/mutations/branch.py | 22 ++---- .../infrahub/message_bus/messages/__init__.py | 4 -- .../request_proposed_change_cancel.py | 9 --- .../trigger_proposed_change_cancel.py | 9 --- .../message_bus/operations/__init__.py | 3 - .../message_bus/operations/event/branch.py | 14 ---- .../operations/requests/proposed_change.py | 21 ++---- .../operations/trigger/__init__.py | 4 +- .../operations/trigger/proposed_change.py | 27 -------- backend/infrahub/proposed_change/__init__.py | 0 backend/infrahub/proposed_change/tasks.py | 41 +++++++++++ .../services/adapters/event/__init__.py | 4 +- backend/infrahub/workflows/catalogue.py | 17 +++++ backend/infrahub/workflows/utils.py | 3 +- .../request/test_proposed_change.py | 32 +-------- .../unit/graphql/mutations/test_branch.py | 34 ---------- .../operations/event/test_branch.py | 21 +----- .../tests/unit/message_bus/test_mappings.py | 10 ++- docs/docs/reference/message-bus-events.mdx | 68 ------------------- 24 files changed, 149 insertions(+), 272 deletions(-) create mode 100644 backend/infrahub/events/branch_action.py delete mode 100644 backend/infrahub/message_bus/messages/request_proposed_change_cancel.py delete mode 100644 backend/infrahub/message_bus/messages/trigger_proposed_change_cancel.py delete mode 100644 backend/infrahub/message_bus/operations/trigger/proposed_change.py create mode 100644 backend/infrahub/proposed_change/__init__.py create mode 100644 backend/infrahub/proposed_change/tasks.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 71727c034a..efbd5f94a8 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -6,6 +6,7 @@ on: push: branches: - develop + - develop-* - stable - release-* diff --git a/backend/infrahub/core/branch/tasks.py b/backend/infrahub/core/branch/tasks.py index 145e966ade..a7971c6f37 100644 --- a/backend/infrahub/core/branch/tasks.py +++ b/backend/infrahub/core/branch/tasks.py @@ -11,12 +11,13 @@ from infrahub.core.migrations.schema.tasks import schema_apply_migrations from infrahub.core.validators.models.validate_migration import SchemaValidateMigrationData from infrahub.core.validators.tasks import schema_validate_migrations +from infrahub.events.branch_action import BranchDeleteEvent from infrahub.exceptions import ValidationError from infrahub.log import get_log_data from infrahub.message_bus import Meta, messages from infrahub.services import services from infrahub.worker import WORKER_IDENTITY -from infrahub.workflows.catalogue import IPAM_RECONCILIATION +from infrahub.workflows.catalogue import BRANCH_CANCEL_PROPOSED_CHANGES, IPAM_RECONCILIATION from infrahub.workflows.utils import add_branch_tag @@ -165,3 +166,19 @@ async def merge_branch(branch: str, conflict_resolution: dict[str, bool] | None meta=Meta(initiator_id=WORKER_IDENTITY, request_id=request_id), ) await service.send(message=message) + + +@flow(name="branch-delete") +async def delete_branch(branch: str) -> None: + service = services.service + + await add_branch_tag(branch_name=branch) + + obj = await Branch.get_by_name(db=service.database, name=str(branch)) + assert obj.id + event = BranchDeleteEvent(branch=branch, branch_id=obj.id, sync_with_git=obj.sync_with_git) + await obj.delete(db=service.database) + + await service.workflow.submit_workflow(workflow=BRANCH_CANCEL_PROPOSED_CHANGES, parameters={"branch_name": branch}) + + await service.event.send(event=event) diff --git a/backend/infrahub/events/branch_action.py b/backend/infrahub/events/branch_action.py new file mode 100644 index 0000000000..88bb6aa064 --- /dev/null +++ b/backend/infrahub/events/branch_action.py @@ -0,0 +1,35 @@ +from pydantic import Field + +from infrahub.message_bus import InfrahubMessage +from infrahub.message_bus.messages.event_branch_delete import EventBranchDelete +from infrahub.message_bus.messages.refresh_registry_branches import RefreshRegistryBranches + +from .models import InfrahubBranchEvent + + +class BranchDeleteEvent(InfrahubBranchEvent): + """Event generated when a branch has been deleted""" + + branch_id: str = Field(..., description="The ID of the mutated node") + sync_with_git: bool = Field(..., description="Indicates if the branch was extended to Git") + + def get_name(self) -> str: + return f"{self.get_event_namespace()}.branch.deleted" + + def get_resource(self) -> dict[str, str]: + return { + "prefect.resource.id": f"infrahub.branch.{self.branch}", + "infrahub.branch.id": self.branch_id, + } + + def get_messages(self) -> list[InfrahubMessage]: + events = [ + EventBranchDelete( + branch=self.branch, + branch_id=self.branch_id, + sync_with_git=self.sync_with_git, + meta=self.get_message_meta(), + ), + RefreshRegistryBranches(), + ] + return events diff --git a/backend/infrahub/events/models.py b/backend/infrahub/events/models.py index 1717fc97b8..29ea3f523e 100644 --- a/backend/infrahub/events/models.py +++ b/backend/infrahub/events/models.py @@ -27,7 +27,7 @@ def get_name(self) -> str: def get_resource(self) -> dict[str, str]: raise NotImplementedError - def get_message(self) -> InfrahubMessage: + def get_messages(self) -> list[InfrahubMessage]: raise NotImplementedError def get_related(self) -> list[dict[str, str]]: diff --git a/backend/infrahub/events/node_action.py b/backend/infrahub/events/node_action.py index ad40f664d9..e8fb95c413 100644 --- a/backend/infrahub/events/node_action.py +++ b/backend/infrahub/events/node_action.py @@ -3,6 +3,7 @@ from pydantic import Field from infrahub.core.constants import MutationAction +from infrahub.message_bus import InfrahubMessage from infrahub.message_bus.messages.event_node_mutated import EventNodeMutated from .models import InfrahubBranchEvent @@ -29,12 +30,14 @@ def get_resource(self) -> dict[str, str]: def get_payload(self) -> dict[str, Any]: return self.data - def get_message(self) -> EventNodeMutated: - return EventNodeMutated( - branch=self.branch, - kind=self.kind, - node_id=self.node_id, - action=self.action.value, - data=self.data, - meta=self.get_message_meta(), - ) + def get_messages(self) -> list[InfrahubMessage]: + return [ + EventNodeMutated( + branch=self.branch, + kind=self.kind, + node_id=self.node_id, + action=self.action.value, + data=self.data, + meta=self.get_message_meta(), + ) + ] diff --git a/backend/infrahub/graphql/mutations/branch.py b/backend/infrahub/graphql/mutations/branch.py index 15407160a4..7d140568b9 100644 --- a/backend/infrahub/graphql/mutations/branch.py +++ b/backend/infrahub/graphql/mutations/branch.py @@ -18,7 +18,7 @@ from infrahub.log import get_log_data, get_logger from infrahub.message_bus import Meta, messages from infrahub.worker import WORKER_IDENTITY -from infrahub.workflows.catalogue import BRANCH_MERGE, BRANCH_REBASE +from infrahub.workflows.catalogue import BRANCH_DELETE, BRANCH_MERGE, BRANCH_REBASE from ..types import BranchType @@ -129,22 +129,10 @@ class Arguments: async def mutate(cls, root: dict, info: GraphQLResolveInfo, data: BranchNameInput) -> Self: context: GraphqlContext = info.context - async with UserTask.from_graphql_context(title=f"Delete branch: {data['name']}", context=context): - obj = await Branch.get_by_name(db=context.db, name=str(data.name)) - await obj.delete(db=context.db) - - if context.service: - log_data = get_log_data() - request_id = log_data.get("request_id", "") - message = messages.EventBranchDelete( - branch=obj.name, - branch_id=str(obj.id), - sync_with_git=obj.sync_with_git, - meta=Meta(request_id=request_id), - ) - await context.service.send(message=message) - - return cls(ok=True) + obj = await Branch.get_by_name(db=context.db, name=str(data.name)) + assert context.service + await context.service.workflow.execute_workflow(workflow=BRANCH_DELETE, parameters={"branch": obj.name}) + return cls(ok=True) class BranchUpdate(Mutation): diff --git a/backend/infrahub/message_bus/messages/__init__.py b/backend/infrahub/message_bus/messages/__init__.py index 7c4c9159e6..cbda08556b 100644 --- a/backend/infrahub/message_bus/messages/__init__.py +++ b/backend/infrahub/message_bus/messages/__init__.py @@ -34,7 +34,6 @@ from .request_generatordefinition_check import RequestGeneratorDefinitionCheck from .request_generatordefinition_run import RequestGeneratorDefinitionRun from .request_graphqlquerygroup_update import RequestGraphQLQueryGroupUpdate -from .request_proposed_change_cancel import RequestProposedChangeCancel from .request_proposedchange_pipeline import RequestProposedChangePipeline from .request_repository_checks import RequestRepositoryChecks from .request_repository_userchecks import RequestRepositoryUserChecks @@ -42,7 +41,6 @@ from .schema_validator_path import SchemaValidatorPath, SchemaValidatorPathResponse from .send_echo_request import SendEchoRequest, SendEchoRequestResponse from .trigger_generatordefinition_run import TriggerGeneratorDefinitionRun -from .trigger_proposed_change_cancel import TriggerProposedChangeCancel from .trigger_webhook_actions import TriggerWebhookActions MESSAGE_MAP: dict[str, type[InfrahubMessage]] = { @@ -76,7 +74,6 @@ "request.generator_definition.check": RequestGeneratorDefinitionCheck, "request.generator_definition.run": RequestGeneratorDefinitionRun, "request.graphql_query_group.update": RequestGraphQLQueryGroupUpdate, - "request.proposed_change.cancel": RequestProposedChangeCancel, "request.proposed_change.data_integrity": RequestProposedChangeDataIntegrity, "request.proposed_change.pipeline": RequestProposedChangePipeline, "request.proposed_change.refresh_artifacts": RequestProposedChangeRefreshArtifacts, @@ -88,7 +85,6 @@ "request.repository.user_checks": RequestRepositoryUserChecks, "send.echo.request": SendEchoRequest, "trigger.generator_definition.run": TriggerGeneratorDefinitionRun, - "trigger.proposed_change.cancel": TriggerProposedChangeCancel, "trigger.webhook.actions": TriggerWebhookActions, } diff --git a/backend/infrahub/message_bus/messages/request_proposed_change_cancel.py b/backend/infrahub/message_bus/messages/request_proposed_change_cancel.py deleted file mode 100644 index bb54444cfd..0000000000 --- a/backend/infrahub/message_bus/messages/request_proposed_change_cancel.py +++ /dev/null @@ -1,9 +0,0 @@ -from pydantic import Field - -from infrahub.message_bus import InfrahubMessage - - -class RequestProposedChangeCancel(InfrahubMessage): - """Cancel the proposed change""" - - proposed_change: str = Field(..., description="The unique ID of the Proposed Change") diff --git a/backend/infrahub/message_bus/messages/trigger_proposed_change_cancel.py b/backend/infrahub/message_bus/messages/trigger_proposed_change_cancel.py deleted file mode 100644 index 3ce54d2b7d..0000000000 --- a/backend/infrahub/message_bus/messages/trigger_proposed_change_cancel.py +++ /dev/null @@ -1,9 +0,0 @@ -from pydantic import Field - -from infrahub.message_bus import InfrahubMessage - - -class TriggerProposedChangeCancel(InfrahubMessage): - """Triggers request to cancel any open or closed proposed changes for a given branch""" - - branch: str = Field(..., description="The impacted branch") diff --git a/backend/infrahub/message_bus/operations/__init__.py b/backend/infrahub/message_bus/operations/__init__.py index 28fefe17e9..bb434a1251 100644 --- a/backend/infrahub/message_bus/operations/__init__.py +++ b/backend/infrahub/message_bus/operations/__init__.py @@ -26,7 +26,6 @@ "check.repository.merge_conflicts": check.repository.merge_conflicts, "check.repository.user_check": check.repository.user_check, "event.branch.create": event.branch.create, - "event.branch.delete": event.branch.delete, "event.branch.merge": event.branch.merge, "event.branch.rebased": event.branch.rebased, "event.node.mutated": event.node.mutated, @@ -48,7 +47,6 @@ "request.generator_definition.run": requests.generator_definition.run, "request.graphql_query_group.update": requests.graphql_query_group.update, "request.artifact_definition.check": requests.artifact_definition.check, - "request.proposed_change.cancel": requests.proposed_change.cancel, "request.proposed_change.data_integrity": requests.proposed_change.data_integrity, "request.proposed_change.pipeline": requests.proposed_change.pipeline, "request.proposed_change.refresh_artifacts": requests.proposed_change.refresh_artifacts, @@ -62,7 +60,6 @@ "schema.migration.path": schema.migration.path, "schema.validator.path": schema.validator.path, "trigger.generator_definition.run": trigger.generator_definition.run, - "trigger.proposed_change.cancel": trigger.proposed_change.cancel, "trigger.webhook.actions": trigger.webhook.actions, } diff --git a/backend/infrahub/message_bus/operations/event/branch.py b/backend/infrahub/message_bus/operations/event/branch.py index 976c9d70b0..3786b66712 100644 --- a/backend/infrahub/message_bus/operations/event/branch.py +++ b/backend/infrahub/message_bus/operations/event/branch.py @@ -36,20 +36,6 @@ async def create(message: messages.EventBranchCreate, service: InfrahubServices) await service.send(message=event) -@flow(name="event-branch-delete") -async def delete(message: messages.EventBranchDelete, service: InfrahubServices) -> None: - log.info("Branch was deleted", branch=message.branch) - - events: List[InfrahubMessage] = [ - messages.RefreshRegistryBranches(), - messages.TriggerProposedChangeCancel(branch=message.branch), - ] - - for event in events: - event.assign_meta(parent=message) - await service.send(message=event) - - @flow(name="branch-event-merge") async def merge(message: messages.EventBranchMerge, service: InfrahubServices) -> None: log.info("Branch merged", source_branch=message.source_branch, target_branch=message.target_branch) diff --git a/backend/infrahub/message_bus/operations/requests/proposed_change.py b/backend/infrahub/message_bus/operations/requests/proposed_change.py index 122f8e703d..2ad50a8c8a 100644 --- a/backend/infrahub/message_bus/operations/requests/proposed_change.py +++ b/backend/infrahub/message_bus/operations/requests/proposed_change.py @@ -8,12 +8,12 @@ from typing import TYPE_CHECKING, Union import pytest -from infrahub_sdk.protocols import CoreGeneratorDefinition, CoreProposedChange +from infrahub_sdk.protocols import CoreGeneratorDefinition from prefect import flow from pydantic import BaseModel from infrahub import config, lock -from infrahub.core.constants import CheckType, InfrahubKind, ProposedChangeState, RepositoryInternalStatus +from infrahub.core.constants import CheckType, InfrahubKind, RepositoryInternalStatus from infrahub.core.diff.coordinator import DiffCoordinator from infrahub.core.diff.model.diff import SchemaConflict from infrahub.core.integrity.object_conflict.conflict_recorder import ObjectConflictValidatorRecorder @@ -70,19 +70,6 @@ def log_line(self) -> str: return "Doesn't require changes due to no relevant modified kinds or file changes in Git" -@flow(name="proposed-changed-cancel") -async def cancel(message: messages.RequestProposedChangeCancel, service: InfrahubServices) -> None: - """Cancel a proposed change.""" - async with service.task_report( - related_node=message.proposed_change, - title="Canceling proposed change", - ) as task_report: - await task_report.info("Canceling proposed change as the source branch was deleted", id=message.proposed_change) - proposed_change = await service.client.get(kind=CoreProposedChange, id=message.proposed_change) - proposed_change.state.value = ProposedChangeState.CANCELED.value - await proposed_change.save() - - @flow(name="proposed-changed-data-integrity") async def data_integrity(message: messages.RequestProposedChangeDataIntegrity, service: InfrahubServices) -> None: """Triggers a data integrity validation check on the provided proposed change to start.""" @@ -408,8 +395,8 @@ async def run_generators(message: messages.RequestProposedChangeRunGenerators, s related_node=message.proposed_change, title="Evaluating Generators", ) as task_report: - generators: list[CoreGeneratorDefinition] = await service.client.filters( - kind=InfrahubKind.GENERATORDEFINITION, + generators = await service.client.filters( + kind=CoreGeneratorDefinition, prefetch_relationships=True, populate_store=True, branch=message.source_branch, diff --git a/backend/infrahub/message_bus/operations/trigger/__init__.py b/backend/infrahub/message_bus/operations/trigger/__init__.py index f9c9de4ead..d35e89a2d2 100644 --- a/backend/infrahub/message_bus/operations/trigger/__init__.py +++ b/backend/infrahub/message_bus/operations/trigger/__init__.py @@ -1,3 +1,3 @@ -from . import generator_definition, proposed_change, webhook +from . import generator_definition, webhook -__all__ = ["generator_definition", "proposed_change", "webhook"] +__all__ = ["generator_definition", "webhook"] diff --git a/backend/infrahub/message_bus/operations/trigger/proposed_change.py b/backend/infrahub/message_bus/operations/trigger/proposed_change.py deleted file mode 100644 index 1f2f2d2f68..0000000000 --- a/backend/infrahub/message_bus/operations/trigger/proposed_change.py +++ /dev/null @@ -1,27 +0,0 @@ -from prefect import flow - -from infrahub.core.constants import InfrahubKind, ProposedChangeState -from infrahub.log import get_logger -from infrahub.message_bus import messages -from infrahub.services import InfrahubServices - -log = get_logger() - - -@flow(name="proposed-change-cancel") -async def cancel(message: messages.TriggerProposedChangeCancel, service: InfrahubServices) -> None: - proposed_changed_opened = await service.client.filters( - kind=InfrahubKind.PROPOSEDCHANGE, include=["id", "source_branch"], state__value=ProposedChangeState.OPEN.value - ) - proposed_changed_closed = await service.client.filters( - kind=InfrahubKind.PROPOSEDCHANGE, include=["id", "source_branch"], state__value=ProposedChangeState.CLOSED.value - ) - - events = [] - for proposed_change in proposed_changed_opened + proposed_changed_closed: - if proposed_change.source_branch.value == message.branch: - events.append(messages.RequestProposedChangeCancel(proposed_change=proposed_change.id)) - - for event in events: - event.assign_meta(parent=message) - await service.send(message=event) diff --git a/backend/infrahub/proposed_change/__init__.py b/backend/infrahub/proposed_change/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/backend/infrahub/proposed_change/tasks.py b/backend/infrahub/proposed_change/tasks.py new file mode 100644 index 0000000000..a4c819551c --- /dev/null +++ b/backend/infrahub/proposed_change/tasks.py @@ -0,0 +1,41 @@ +from __future__ import annotations + +from infrahub_sdk.protocols import CoreProposedChange +from prefect import flow, task +from prefect.logging import get_run_logger + +from infrahub.core.constants import ProposedChangeState +from infrahub.services import ( + services, +) + + +@flow(name="proposed-changes-cancel-branch", description="Cancel all Proposed change associated with a branch.") +async def cancel_proposed_changes_branch(branch_name: str) -> None: + service = services.service + proposed_changed_opened = await service.client.filters( + kind=CoreProposedChange, + include=["id", "source_branch"], + state__value=ProposedChangeState.OPEN.value, + source_branch__value=branch_name, + ) + proposed_changed_closed = await service.client.filters( + kind=CoreProposedChange, + include=["id", "source_branch"], + state__value=ProposedChangeState.CLOSED.value, + source_branch__value=branch_name, + ) + + for proposed_change in proposed_changed_opened + proposed_changed_closed: + await cancel_proposed_change(proposed_change=proposed_change) + + +@task(description="Cancel a propose change") +async def cancel_proposed_change(proposed_change: CoreProposedChange) -> None: + service = services.service + log = get_run_logger() + + log.info("Canceling proposed change as the source branch was deleted") + proposed_change = await service.client.get(kind=CoreProposedChange, id=proposed_change.id) + proposed_change.state.value = ProposedChangeState.CANCELED.value + await proposed_change.save() diff --git a/backend/infrahub/services/adapters/event/__init__.py b/backend/infrahub/services/adapters/event/__init__.py index 865778ce08..2d147ee87f 100644 --- a/backend/infrahub/services/adapters/event/__init__.py +++ b/backend/infrahub/services/adapters/event/__init__.py @@ -34,8 +34,8 @@ async def send(self, event: InfrahubEvent) -> None: await asyncio.gather(*tasks) async def _send_bus(self, event: InfrahubEvent) -> None: - message = event.get_message() - await self.service.send(message=message) + for message in event.get_messages(): + await self.service.send(message=message) async def _send_prefect(self, event: InfrahubEvent) -> None: emit_event( diff --git a/backend/infrahub/workflows/catalogue.py b/backend/infrahub/workflows/catalogue.py index 856f89a5f4..870a7fec01 100644 --- a/backend/infrahub/workflows/catalogue.py +++ b/backend/infrahub/workflows/catalogue.py @@ -140,6 +140,21 @@ tags=[WorkflowTag.DATABASE_CHANGE], ) +BRANCH_DELETE = WorkflowDefinition( + name="branch-delete", + type=WorkflowType.INTERNAL, + module="infrahub.core.branch.tasks", + function="delete_branch", + branch_support=BranchSupportType.AWARE, +) + +BRANCH_CANCEL_PROPOSED_CHANGES = WorkflowDefinition( + name="proposed-change-cancel", + type=WorkflowType.INTERNAL, + module="infrahub.proposed_change.tasks", + function="cancel_proposed_changes_branch", +) + worker_pools = [INFRAHUB_WORKER_POOL] workflows = [ @@ -156,8 +171,10 @@ REQUEST_ARTIFACT_GENERATE, BRANCH_REBASE, BRANCH_MERGE, + BRANCH_DELETE, REQUEST_ARTIFACT_DEFINITION_GENERATE, REQUEST_GENERATOR_RUN, REQUEST_DIFF_UPDATE, REQUEST_DIFF_REFRESH, + BRANCH_CANCEL_PROPOSED_CHANGES, ] diff --git a/backend/infrahub/workflows/utils.py b/backend/infrahub/workflows/utils.py index b32e0676fc..2820159f7f 100644 --- a/backend/infrahub/workflows/utils.py +++ b/backend/infrahub/workflows/utils.py @@ -1,10 +1,9 @@ -from prefect import get_client, task +from prefect import get_client from prefect.runtime import flow_run from .constants import WorkflowTag -@task(name="add-branch-tag") async def add_branch_tag(branch_name: str) -> None: client = get_client(sync_client=False) current_flow_run_id = flow_run.id diff --git a/backend/tests/integration/message_bus/operations/request/test_proposed_change.py b/backend/tests/integration/message_bus/operations/request/test_proposed_change.py index 05d8a39841..545d1e443e 100644 --- a/backend/tests/integration/message_bus/operations/request/test_proposed_change.py +++ b/backend/tests/integration/message_bus/operations/request/test_proposed_change.py @@ -5,12 +5,11 @@ import pytest from infrahub_sdk import Config, InfrahubClient -from infrahub.core.constants import InfrahubKind, ProposedChangeState -from infrahub.core.manager import NodeManager +from infrahub.core.constants import InfrahubKind from infrahub.core.node import Node from infrahub.git import InfrahubRepository from infrahub.message_bus import messages -from infrahub.message_bus.operations.requests.proposed_change import cancel, pipeline, run_generators +from infrahub.message_bus.operations.requests.proposed_change import pipeline, run_generators from infrahub.message_bus.types import ProposedChangeBranchDiff from infrahub.server import app, app_initialization from infrahub.services import InfrahubServices, services @@ -24,7 +23,6 @@ if TYPE_CHECKING: from pathlib import Path - from infrahub.core.protocols import CoreProposedChange from infrahub.database import InfrahubDatabase BRANCH_CREATE = """ @@ -193,29 +191,3 @@ async def test_run_generators_validate_requested_jobs( "request.proposed_change.refresh_artifacts", "request.proposed_change.repository_checks", ] - - -async def test_cancel( - prepare_proposed_change: str, - db: InfrahubDatabase, - test_client: InfrahubTestClient, -): - message = messages.RequestProposedChangeCancel( - proposed_change=prepare_proposed_change, - ) - integration_helper = IntegrationHelper(db=db) - bus_pre_data_changes = BusRecorder() - admin_token = await integration_helper.create_token() - config = Config(api_token=admin_token, requester=test_client.async_request) - client = InfrahubClient(config=config) - fake_log = FakeLogger() - services.service._client = client - services.service.log = fake_log - services.service.message_bus = bus_pre_data_changes - services.prepare(service=services.service) - await cancel(message=message, service=services.service) - assert fake_log.info_logs == ["Canceling proposed change as the source branch was deleted"] - proposed_change: CoreProposedChange = await NodeManager.get_one_by_id_or_default_filter( - db=db, id=prepare_proposed_change, kind=InfrahubKind.PROPOSEDCHANGE - ) - assert proposed_change.state.value.value == ProposedChangeState.CANCELED.value diff --git a/backend/tests/unit/graphql/mutations/test_branch.py b/backend/tests/unit/graphql/mutations/test_branch.py index ab26b2d730..cef0b26691 100644 --- a/backend/tests/unit/graphql/mutations/test_branch.py +++ b/backend/tests/unit/graphql/mutations/test_branch.py @@ -151,20 +151,6 @@ async def test_branch_create( async def test_branch_delete( db: InfrahubDatabase, default_branch: Branch, car_person_schema, register_core_models_schema, session_admin ): - create_query = """ - mutation { - BranchCreate(data: { name: "branch3", description: "my description", sync_with_git: false }) { - ok - object { - id - name - description - sync_with_git - } - } - } - """ - delete_query = """ mutation { BranchDelete(data: { name: "branch3" }) { @@ -176,29 +162,9 @@ async def test_branch_delete( delete_before_create = await graphql_mutation( query=delete_query, db=db, branch=default_branch, account_session=session_admin ) - recorder = BusRecorder() - service = InfrahubServices(message_bus=recorder) - - create = await graphql_mutation( - query=create_query, db=db, branch=default_branch, service=service, account_session=session_admin - ) - recorder = BusRecorder() - service = InfrahubServices(message_bus=recorder) - - delete_after_create = await graphql_mutation( - query=delete_query, db=db, branch=default_branch, service=service, account_session=session_admin - ) - delete_after_delete = await graphql_mutation( - query=delete_query, db=db, branch=default_branch, account_session=session_admin - ) assert delete_before_create.errors assert delete_before_create.errors[0].message == "Branch: branch3 not found." - assert not create.errors - assert not delete_after_create.errors - assert delete_after_delete.errors - assert delete_after_delete.errors[0].message == "Branch: branch3 not found." - assert recorder.seen_routing_keys == ["event.branch.delete"] async def test_branch_create_registry( diff --git a/backend/tests/unit/message_bus/operations/event/test_branch.py b/backend/tests/unit/message_bus/operations/event/test_branch.py index 7644008caa..fc90a14785 100644 --- a/backend/tests/unit/message_bus/operations/event/test_branch.py +++ b/backend/tests/unit/message_bus/operations/event/test_branch.py @@ -10,7 +10,7 @@ from infrahub.core.timestamp import Timestamp from infrahub.dependencies.component.registry import ComponentDependencyRegistry from infrahub.message_bus import messages -from infrahub.message_bus.operations.event.branch import delete, merge, rebased +from infrahub.message_bus.operations.event.branch import merge, rebased from infrahub.services import InfrahubServices, services from infrahub.services.adapters.workflow.local import WorkflowLocalExecution from infrahub.workflows.catalogue import REQUEST_DIFF_REFRESH, REQUEST_DIFF_UPDATE, TRIGGER_ARTIFACT_DEFINITION_GENERATE @@ -29,25 +29,6 @@ def init_service(): services.service = original -async def test_delete(prefect_test_fixture): - """Validate that a deleted branch triggers a registry refresh and cancels open proposed changes""" - - message = messages.EventBranchDelete( - branch_id="40fb612f-eaaa-422b-9480-df269080c103", branch="cr1234", sync_with_git=True - ) - - recorder = BusRecorder() - service = InfrahubServices(message_bus=recorder) - - await delete(message=message, service=service) - - assert len(recorder.messages) == 2 - assert isinstance(recorder.messages[0], messages.RefreshRegistryBranches) - assert isinstance(recorder.messages[1], messages.TriggerProposedChangeCancel) - trigger_cancel: messages.TriggerProposedChangeCancel = recorder.messages[1] - assert trigger_cancel.branch == "cr1234" - - async def test_merged(default_branch: Branch, init_service: InfrahubServices, prefect_test_fixture): """ Test that merge flow triggers corrects events/workflows. It does not actually test these events/workflows behaviors diff --git a/backend/tests/unit/message_bus/test_mappings.py b/backend/tests/unit/message_bus/test_mappings.py index 7624b3ba7b..f4e60a62d8 100644 --- a/backend/tests/unit/message_bus/test_mappings.py +++ b/backend/tests/unit/message_bus/test_mappings.py @@ -10,9 +10,13 @@ def test_message_command_overlap(): - """Verify that a command is defined for each message.""" - messages = sorted(list(MESSAGE_MAP.keys())) - commands = sorted(list(COMMAND_MAP.keys())) + """ + Verify that a command is defined for each message + except events that don't need to be associated with a command + """ + messages = sorted([key for key in MESSAGE_MAP.keys() if not key.startswith("event.")]) + commands = sorted([key for key in COMMAND_MAP.keys() if not key.startswith("event.")]) + assert messages == commands diff --git a/docs/docs/reference/message-bus-events.mdx b/docs/docs/reference/message-bus-events.mdx index 41cf8bd9ca..9b1012bdd8 100644 --- a/docs/docs/reference/message-bus-events.mdx +++ b/docs/docs/reference/message-bus-events.mdx @@ -653,20 +653,6 @@ For more detailed explanations on how to use these events within Infrahub, see t ### Request Proposed Change - -#### Event request.proposed_change.cancel - - -**Description**: Cancel the proposed change - -**Priority**: 3 - - -| Key | Description | Type | Default Value | -|-----|-------------|------|---------------| -| **meta** | Meta properties for the message | N/A | None | -| **proposed_change** | The unique ID of the Proposed Change | string | None | - #### Event request.proposed_change.data_integrity @@ -877,25 +863,6 @@ For more detailed explanations on how to use these events within Infrahub, see t | **branch** | The branch to run the Generators in | string | None | - -### Trigger Proposed Change - - - -#### Event trigger.proposed_change.cancel - - -**Description**: Triggers request to cancel any open or closed proposed changes for a given branch - -**Priority**: 3 - - -| Key | Description | Type | Default Value | -|-----|-------------|------|---------------| -| **meta** | Meta properties for the message | N/A | None | -| **branch** | The impacted branch | string | None | - - ### Trigger Webhook @@ -1590,21 +1557,6 @@ For more detailed explanations on how to use these events within Infrahub, see t ### Request Proposed Change - -#### Event request.proposed_change.cancel - - -**Description**: Cancel the proposed change - -**Priority**: 3 - - - -| Key | Description | Type | Default Value | -|-----|-------------|------|---------------| -| **meta** | Meta properties for the message | N/A | None | -| **proposed_change** | The unique ID of the Proposed Change | string | None | - #### Event request.proposed_change.data_integrity @@ -1826,26 +1778,6 @@ For more detailed explanations on how to use these events within Infrahub, see t | **branch** | The branch to run the Generators in | string | None | - -### Trigger Proposed Change - - - -#### Event trigger.proposed_change.cancel - - -**Description**: Triggers request to cancel any open or closed proposed changes for a given branch - -**Priority**: 3 - - - -| Key | Description | Type | Default Value | -|-----|-------------|------|---------------| -| **meta** | Meta properties for the message | N/A | None | -| **branch** | The impacted branch | string | None | - - ### Trigger Webhook