Skip to content

Commit 1748e45

Browse files
committed
Refactor branch defined triggers
1 parent 76ac0fb commit 1748e45

File tree

2 files changed

+43
-29
lines changed

2 files changed

+43
-29
lines changed

backend/infrahub/trigger/models.py

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
from __future__ import annotations
22

33
from datetime import timedelta
4-
from enum import Enum
4+
from enum import Enum, StrEnum
55
from typing import TYPE_CHECKING, Any
66

77
from prefect.events.actions import RunDeployment
@@ -19,6 +19,16 @@
1919
from uuid import UUID
2020

2121

22+
class TriggerComparison(StrEnum):
23+
MATCH = "match" # Expected trigger and actual trigger is identical
24+
REFRESH = "refresh" # The branch parameters doesn't match, the hash does, refresh in Prefect but don't run triggers
25+
UPDATE = "update" # Neither branch or other data points match, update in Prefect and run triggers
26+
27+
@property
28+
def update_prefect(self) -> bool:
29+
return self in {TriggerComparison.REFRESH, TriggerComparison.UPDATE}
30+
31+
2232
class TriggerSetupReport(BaseModel):
2333
created: list[TriggerDefinition] = Field(default_factory=list)
2434
updated: list[TriggerDefinition] = Field(default_factory=list)
@@ -29,6 +39,12 @@ class TriggerSetupReport(BaseModel):
2939
def in_use_count(self) -> int:
3040
return len(self.created + self.updated + self.unchanged)
3141

42+
def add_with_comparison(self, trigger: TriggerDefinition, comparison: TriggerComparison) -> None:
43+
if comparison == TriggerComparison.MATCH:
44+
self.unchanged.append(trigger)
45+
elif comparison in {TriggerComparison.UPDATE, TriggerComparison.REFRESH}:
46+
self.updated.append(trigger)
47+
3248

3349
class TriggerType(str, Enum):
3450
ACTION_TRIGGER_RULE = "action_trigger_rule"

backend/infrahub/trigger/setup.py

Lines changed: 26 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -10,15 +10,17 @@
1010

1111
from infrahub import lock
1212
from infrahub.database import InfrahubDatabase
13-
from infrahub.trigger.models import TriggerDefinition
13+
from infrahub.trigger.models import TriggerBranchDefinition, TriggerDefinition
1414

15-
from .models import TriggerSetupReport, TriggerType
15+
from .models import TriggerComparison, TriggerSetupReport, TriggerType
1616

1717
if TYPE_CHECKING:
1818
from uuid import UUID
1919

2020

21-
def compare_automations(target: AutomationCore, existing: Automation) -> bool:
21+
def compare_automations(
22+
target: AutomationCore, existing: Automation, trigger_type: TriggerType | None
23+
) -> TriggerComparison:
2224
"""Compare an AutomationCore with an existing Automation object to identify if they are identical or not
2325
2426
Return True if the target is identical to the existing automation
@@ -27,6 +29,11 @@ def compare_automations(target: AutomationCore, existing: Automation) -> bool:
2729
target_dump = target.model_dump(exclude_defaults=True, exclude_none=True)
2830
existing_dump = existing.model_dump(exclude_defaults=True, exclude_none=True, exclude={"id"})
2931

32+
if not trigger_type or (trigger_type and not isinstance(trigger_type, TriggerBranchDefinition)):
33+
if target_dump == existing_dump:
34+
return TriggerComparison.MATCH
35+
return TriggerComparison.UPDATE
36+
3037
return target_dump == existing_dump
3138

3239

@@ -63,10 +70,8 @@ async def setup_triggers(
6370

6471
report = TriggerSetupReport()
6572

66-
if trigger_type:
67-
log.debug(f"Setting up triggers of type {trigger_type.value}")
68-
else:
69-
log.debug("Setting up all triggers")
73+
trigger_log_message = f"triggers of type {trigger_type.value}" if trigger_type else "all triggers"
74+
log.debug(f"Setting up {trigger_log_message}")
7075

7176
# -------------------------------------------------------------
7277
# Retrieve existing Deployments and Automation from the server
@@ -80,16 +85,14 @@ async def setup_triggers(
8085
}
8186
deployments_mapping: dict[str, UUID] = {name: item.id for name, item in deployments.items()}
8287

83-
# If a trigger type is provided, narrow down the list of existing triggers to know which one to delete
84-
existing_automations: dict[str, Automation] = {}
88+
existing_automations = {item.name: item for item in await client.read_automations()}
8589
if trigger_type:
90+
# If a trigger type is provided, narrow down the list of existing triggers to know which one to delete
8691
existing_automations = {
87-
item.name: item
88-
for item in await client.read_automations()
89-
if item.name.startswith(f"{trigger_type.value}::")
92+
automation_name: automation
93+
for automation_name, automation in existing_automations.items()
94+
if automation_name.startswith(f"{trigger_type.value}::")
9095
}
91-
else:
92-
existing_automations = {item.name: item for item in await client.read_automations()}
9396

9497
trigger_names = [trigger.generate_name() for trigger in triggers]
9598
automation_names = list(existing_automations.keys())
@@ -115,12 +118,13 @@ async def setup_triggers(
115118
existing_automation = existing_automations.get(trigger.generate_name(), None)
116119

117120
if existing_automation:
118-
if force_update or not compare_automations(target=automation, existing=existing_automation):
121+
trigger_comparison = compare_automations(
122+
target=automation, existing=existing_automation, trigger_type=trigger_type
123+
)
124+
if force_update or trigger_comparison.update_prefect:
119125
await client.update_automation(automation_id=existing_automation.id, automation=automation)
120126
log.info(f"{trigger.generate_name()} Updated")
121-
report.updated.append(trigger)
122-
else:
123-
report.unchanged.append(trigger)
127+
report.add_with_comparison(trigger, trigger_comparison)
124128
else:
125129
await client.create_automation(automation=automation)
126130
log.info(f"{trigger.generate_name()} Created")
@@ -145,15 +149,9 @@ async def setup_triggers(
145149
else:
146150
raise
147151

148-
if trigger_type:
149-
log.info(
150-
f"Processed triggers of type {trigger_type.value}: "
151-
f"{len(report.created)} created, {len(report.updated)} updated, {len(report.unchanged)} unchanged, {len(report.deleted)} deleted"
152-
)
153-
else:
154-
log.info(
155-
f"Processed all triggers: "
156-
f"{len(report.created)} created, {len(report.updated)} updated, {len(report.unchanged)} unchanged, {len(report.deleted)} deleted"
157-
)
152+
log.info(
153+
f"Processed {trigger_log_message}: "
154+
f"{len(report.created)} created, {len(report.updated)} updated, {len(report.unchanged)} unchanged, {len(report.deleted)} deleted"
155+
)
158156

159157
return report

0 commit comments

Comments
 (0)