Skip to content

Commit 4e6b055

Browse files
committed
refactoring code
1 parent 92c1b76 commit 4e6b055

5 files changed

Lines changed: 141 additions & 594 deletions

File tree

src/robusta/core/sinks/slack/slack_sink_params.py

Lines changed: 30 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,46 @@
11
from robusta.core.sinks.sink_base_params import SinkBaseParams
22
from robusta.core.sinks.sink_config import SinkConfigBase
33
from robusta.core.sinks.common import ChannelTransformer
4-
4+
from enum import Enum
55
from typing import Optional, Dict, Literal
66
from pydantic import validator
77

88

9+
class SlackTemplateStyle(str, Enum):
10+
DEFAULT = "default"
11+
LEGACY = "legacy"
12+
13+
914
class SlackSinkParams(SinkBaseParams):
1015
slack_channel: str
1116
api_key: str
1217
channel_override: Optional[str] = None
1318
max_log_file_limit_kb: int = 1000
1419
investigate_link: bool = True
15-
send_svg: bool = True
16-
prefer_redirect_to_platform: bool = True
17-
18-
# Template selection and customization options
19-
template_style: Literal["default", "legacy"] = "default" # Use "legacy" for old-style formatting
20-
custom_templates: Optional[Dict[str, str]] = None # Template name -> custom template content
20+
21+
template_style: SlackTemplateStyle = SlackTemplateStyle.DEFAULT # Use "legacy" for old-style formatting
22+
slack_custom_templates: Optional[Dict[str, str]] = None # Template name -> custom template content
23+
template_name: Optional[str] = None
24+
25+
def get_effective_template_name(self) -> str:
26+
"""
27+
Returns the template name to use for this sink. If template_name is set, use it.
28+
Otherwise, use 'legacy.j2' if template_style is legacy, else 'header.j2'.
29+
"""
30+
if self.template_name:
31+
return self.template_name
32+
if self.template_style == SlackTemplateStyle.LEGACY:
33+
return "legacy.j2"
34+
return "header.j2"
35+
36+
def get_custom_template(self) -> Optional[str]:
37+
"""
38+
Returns the custom template string for the effective template name, if it exists.
39+
"""
40+
template_name = self.get_effective_template_name()
41+
if self.slack_custom_templates and template_name in self.slack_custom_templates:
42+
return self.slack_custom_templates[template_name]
43+
return None
2144

2245
@classmethod
2346
def _supports_grouping(cls):

src/robusta/core/sinks/slack/templates/template_loader.py

Lines changed: 20 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -92,32 +92,33 @@ def render_to_blocks(self, template_name: str, context: Dict[str, Any]) -> List[
9292
logging.error(f"Error rendering template {template_name}: {e}")
9393
return []
9494

95-
def render_custom_or_file_template_to_blocks(self, template_name: str, context: Dict[str, Any], custom_template: str = None) -> List[Dict[str, Any]]:
95+
def render_custom_template_to_blocks(self, custom_template: str, context: Dict[str, Any]) -> List[Dict[str, Any]]:
9696
"""
97-
Render a custom Jinja template string (if provided) or a file-based template to Slack blocks.
97+
Render a custom Jinja template string to Slack blocks.
9898
Args:
99-
template_name: The name of the file-based template (e.g., "header.j2")
99+
custom_template: Jinja template string
100100
context: Dictionary of variables to pass to the template
101-
custom_template: Optional Jinja template string to use instead of file-based template
102101
Returns:
103102
List of Slack block objects (dictionaries)
104103
"""
105-
if custom_template:
106-
try:
107-
template = Template(custom_template)
108-
rendered_blocks = []
109-
for block_str in template.render(**context).strip().split("\n\n"):
110-
if block_str.strip():
111-
block_str_fixed = escape_raw_newlines_in_json_strings(block_str)
112-
block = json.loads(block_str_fixed)
113-
rendered_blocks.append(block)
114-
return rendered_blocks
115-
except Exception as e:
116-
logging.error(f"Error rendering custom template: {e}")
117-
# Fall back to file-based template
104+
try:
105+
template = Template(custom_template)
106+
return self.render_to_blocks(template, context)
107+
except Exception as e:
108+
logging.error(f"Error rendering custom template: {e}")
109+
return []
118110

119-
# Use file-based template
120-
return self.render_to_blocks(template_name, context)
111+
def render_file_template_to_blocks(self, template_name: str, context: Dict[str, Any]) -> List[Dict[str, Any]]:
112+
"""
113+
Render a file-based Jinja template to Slack blocks.
114+
Args:
115+
template_name: The name of the file-based template (e.g., "header.j2")
116+
context: Dictionary of variables to pass to the template
117+
Returns:
118+
List of Slack block objects (dictionaries)
119+
"""
120+
template = self.get_template(template_name)
121+
return self.render_to_blocks(template, context)
121122

122123

123124
# Singleton instance

src/robusta/integrations/slack/sender.py

Lines changed: 12 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -437,17 +437,8 @@ def __create_finding_header(
437437
title, mention = self.extract_mentions(title)
438438

439439
sev = finding.severity
440+
440441

441-
# Select appropriate template based on user preference
442-
template_name = "header.j2" # default template
443-
if sink_params and hasattr(sink_params, "template_style") and sink_params.template_style == "legacy":
444-
template_name = "legacy.j2"
445-
446-
# Check if the user has provided a custom template
447-
custom_template = None
448-
if sink_params and sink_params.custom_templates and template_name in sink_params.custom_templates:
449-
custom_template = sink_params.custom_templates[template_name]
450-
451442
# Prepare data for template
452443
status_text = "Firing" if status == FindingStatus.FIRING else "Resolved"
453444
status_emoji = "⚠️" if status == FindingStatus.FIRING else "✅"
@@ -508,10 +499,17 @@ def __create_finding_header(
508499
"finding": finding
509500
}
510501

511-
# Use the new template loader method for both custom and file-based templates
512-
return template_loader.render_custom_or_file_template_to_blocks(
513-
template_name, template_context, custom_template
514-
)
502+
# Determine the template name to use
503+
template_name = sink_params.get_effective_template_name() if sink_params else "header.j2"
504+
505+
# Get the custom template for this template name, if any
506+
custom_template = sink_params.get_custom_template() if sink_params else None
507+
508+
# Use the new template loader methods for custom or file-based templates
509+
if custom_template:
510+
return template_loader.render_custom_template_to_blocks(custom_template, template_context)
511+
else:
512+
return template_loader.render_file_template_to_blocks(template_name, template_context)
515513

516514
def __create_links(
517515
self,

0 commit comments

Comments
 (0)