utils

package
v1.4.24 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 27, 2026 License: MIT Imports: 19 Imported by: 0

Documentation

Overview

Package utils provides utility functions for the application

Package utils provides utility functions for the application

Index

Constants

View Source
const (
	AgentSlackTemplatePath    = "config/agent_slack.tmpl"
	AgentTelegramTemplatePath = "config/agent_telegram.tmpl"
	AgentMSTeamsTemplatePath  = "config/agent_msteams.tmpl"
	AgentLarkTemplatePath     = "config/agent_lark.tmpl"
	AgentViberTemplatePath    = "config/agent_viber.tmpl"
	AgentEmailTemplatePath    = "config/agent_email.tmpl"
)

Hardcoded per-channel template paths used for incidents emitted by the AI SRE Agent (detect mode). Each channel has its own file because the markup syntax differs per channel (mrkdwn, HTML, Markdown, plain text). Providers render agent-emitted incidents through these files instead of their per-channel default templates.

Variables

This section is empty.

Functions

func ContainsMarkdownSyntax

func ContainsMarkdownSyntax(text string) bool

ContainsMarkdownSyntax checks if the message contains any Markdown formatting

func ConvertMarkdownToPlainText

func ConvertMarkdownToPlainText(markdown string) string

ConvertMarkdownToPlainText converts markdown to plain text for fallback

func ConvertToTeamsPayload

func ConvertToTeamsPayload(powerAutomateURL, messageText string, incident *m.Incident) ([]byte, error)

ConvertToTeamsPayload takes the rendered template message and converts it to the appropriate payload format for Power Automate.

func CreateHTTPClient added in v1.3.7

func CreateHTTPClient(proxyConfig config.ProxyConfig, useProxy bool) *http.Client

CreateHTTPClient creates an HTTP client with optional proxy support

func ExtractJSONObject added in v1.4.0

func ExtractJSONObject(s string) string

ExtractJSONObject pulls the first balanced {...} block out of s. Returns "" when no balanced object is present.

This is intentionally simpler than a full JSON tokenizer — it is designed for tolerating LLM-style output that may wrap a single JSON object in code fences or preamble. A depth counter with string-escape handling is enough for the degraded-output cases we care about; nested objects inside string literals do not throw it off.

func ExtractPatternID added in v1.4.22

func ExtractPatternID(content map[string]interface{}) string

ExtractPatternID resolves the pattern identity of a free-form alert payload in priority order (PatternID, pattern_id, key). Same determinism guarantee as ExtractSource: it feeds the dedup fingerprint.

func ExtractService added in v1.4.22

func ExtractService(content map[string]interface{}) string

ExtractService resolves the service a free-form alert payload is about. It is the ONE implementation every caller (the durable IncidentRecord.Service column, the incidents list, the service detail aggregation, the report and the emit fingerprint) routes through, so they can never disagree. Lookup order: top-level keys, then nested Alertmanager labels, then CloudWatch alarm trigger dimensions. Matching is case-insensitive and fail-soft: an unrecognised payload yields "".

func ExtractSeverity added in v1.4.22

func ExtractSeverity(content map[string]interface{}) string

ExtractSeverity resolves the best-effort severity of a free-form alert payload, using the same lookup order as ExtractService: top-level severity keys, then the nested Alertmanager label maps, then the CloudWatch alarm's Trigger.Dimensions[]. Raw — callers band or normalize it. Returns "" when the payload carries no severity.

Only real severity fields are read. An agent verdict is deliberately NOT a severity here: it is operator-set free text (POST /agent/patterns/:id), and this value feeds the priority floor and the dedup fingerprint, which must never be steerable by a typed-in label. A cosmetic verdict fallback lives in the report's own banding instead.

func ExtractSource added in v1.4.22

func ExtractSource(content map[string]interface{}) string

ExtractSource resolves the ingress/source label a free-form alert payload names itself with. Like the other extractors it is case-insensitive, trimmed, and fail-soft, and it resolves a payload carrying two spellings of the key ("Source" and "source") the same way on every read — the value feeds the dedup fingerprint, so two reads of one payload must never land in two buckets.

func ExtractTitle added in v1.4.22

func ExtractTitle(content map[string]interface{}) string

ExtractTitle resolves the human-facing title of a free-form alert payload: top-level keys first, then the nested Alertmanager label maps (labels.alertname / commonLabels.alertname). It is the ONE implementation behind the durable IncidentRecord.Title, the report's title fallback and the emit fingerprint's title fallback, so an alert can never be titled one way and fingerprinted another. Matching is case-insensitive and fail-soft: a payload that names no title yields "" rather than a title invented from unrelated fields.

Operator note: recognising AlarmName re-keys CloudWatch alerts once. Their title used to resolve empty, so every alarm on one service+severity hashed to the same fingerprint and deduped against its neighbours; distinct alarms now hash distinctly. Fatigue rows written under the old key no longer match and new rows are created — a one-time re-key, after which the stale rows age out on their normal retention.

func GetIncludeFunc added in v1.3.2

func GetIncludeFunc(tmplName string) func(string, interface{}) (string, error)

GetIncludeFunc returns an include function that uses the specified template

func GetTemplateFuncMaps

func GetTemplateFuncMaps() template.FuncMap

GetTemplateFuncMaps returns a map of template functions that can be used in templates

func IsAgentIncident added in v1.4.0

func IsAgentIncident(content map[string]interface{}) bool

IsAgentIncident returns true when the incident content map was built by services.CreateIncidentFromFinding, i.e. originated from the AI SRE Agent. Detection is based on stable fields stamped by the agent path: a non-empty PatternID OR a Source that begins with "agent:".

func NormalizeSeverity added in v1.4.0

func NormalizeSeverity(s string) string

NormalizeSeverity coerces a free-form severity string into one of the canonical alert severities (`critical`, `high`, `medium`, `low`). Unknown / empty values fall back to "medium".

func OneLine added in v1.4.0

func OneLine(s string, maxLen int) string

OneLine collapses newlines into spaces and truncates to maxLen runes (well, bytes — callers pass log lines that are ASCII-dominant). A trailing ellipsis "…" is appended on truncation. maxLen <= 0 disables truncation.

func PayloadString added in v1.4.22

func PayloadString(content map[string]interface{}, keys ...string) string

PayloadString returns the first non-empty string value found at any of the given keys: exact match first, then case-insensitive. It is the shared content accessor behind the extractors, exported so callers that need one extra key of their own (the report's verdict fallback) read a payload the same trimmed, case-insensitive way instead of hand-rolling a map lookup.

func RegisterTemplate added in v1.3.2

func RegisterTemplate(name string, tmpl *template.Template)

RegisterTemplate registers a template for use with the include function

func SeverityRank added in v1.4.4

func SeverityRank(s string) int

SeverityRank maps a canonical severity to an orderable rank (critical highest). Unknown / empty severities rank lowest (0) so they never act as a floor over a real AI-assigned severity.

func StripMarkdown

func StripMarkdown(text string) string

StripMarkdown removes common markdown syntax from text

Types

type AdaptiveCard

type AdaptiveCard struct {
	Type    string        `json:"type"`
	Body    []interface{} `json:"body"`
	Schema  string        `json:"$schema"`
	Version string        `json:"version"`
	// Required MS Teams fields
	Text    string `json:"text,omitempty"`    // Fallback text for clients that don't support cards
	Summary string `json:"summary,omitempty"` // Required by MS Teams for notification
}

AdaptiveCard represents a basic Adaptive Card structure for MS Teams

func ConvertMarkdownToAdaptiveCard

func ConvertMarkdownToAdaptiveCard(markdown string) AdaptiveCard

ConvertMarkdownToAdaptiveCard converts Markdown-like text to an Adaptive Card

type FoldedPayload added in v1.4.22

type FoldedPayload struct {
	// contains filtered or unexported fields
}

FoldedPayload is a reusable, case-folded view of ONE alert payload.

Every extractor below resolves its keys case-insensitively, and a single alert runs several of them. Resolving one candidate key by ranging the payload costs O(len(payload)), so a wide payload used to pay that scan once per candidate key per extractor — dozens of full scans per alert. FoldedPayload pays it once instead: the fold map, each nested label map and the parsed CloudWatch dimension set are built on first use and reused by every later lookup on the same payload.

It is a pure read-side cache — the payload itself is never written to — and it resolves exactly the values the one-shot Extract* functions resolve, duplicate-spelling tie-break included. A FoldedPayload is not safe for concurrent use; build one per payload on the goroutine that reads it.

Build ONE per payload and read every field off it — Service, Severity, Title, Source, PatternID, and String for a caller's own key set. The Extract* / PayloadString functions are one-shot wrappers that build a throwaway index, so a caller that needs several fields should hold the FoldedPayload instead of calling them in sequence.

func NewFoldedPayload added in v1.4.22

func NewFoldedPayload(content map[string]interface{}) *FoldedPayload

NewFoldedPayload wraps a content map. The fold index is built lazily, so a caller whose keys all hit their exact spelling never pays for it.

func (*FoldedPayload) PatternID added in v1.4.22

func (p *FoldedPayload) PatternID() string

PatternID resolves the pattern identity the payload carries, in priority order: PatternID, then pattern_id, then the generic key.

func (*FoldedPayload) Service added in v1.4.22

func (p *FoldedPayload) Service() string

Service resolves the service this payload is about: top-level keys, then nested Alertmanager labels, then CloudWatch alarm trigger dimensions.

func (*FoldedPayload) Severity added in v1.4.22

func (p *FoldedPayload) Severity() string

Severity resolves the payload's raw severity in the same lookup order as Service. Callers band or normalize it.

func (*FoldedPayload) Source added in v1.4.22

func (p *FoldedPayload) Source() string

Source resolves the ingress/source label the payload names itself with.

func (*FoldedPayload) String added in v1.4.22

func (p *FoldedPayload) String(keys ...string) string

String returns the first non-empty string value found at any of the given keys: exact match across all keys first, then case-insensitive.

func (*FoldedPayload) Title added in v1.4.22

func (p *FoldedPayload) Title() string

Title resolves the payload's human-facing title: top-level keys first, then the nested Alertmanager label maps.

type LarkCard added in v1.3.1

type LarkCard struct {
	Header   LarkCardHeader    `json:"header"`
	Elements []LarkCardElement `json:"elements"`
}

LarkCard represents an interactive card in Lark

type LarkCardElement added in v1.3.1

type LarkCardElement struct {
	Tag     string `json:"tag"`
	Content string `json:"content"`
}

LarkCardElement represents an element in a Lark card

type LarkCardHeader added in v1.3.1

type LarkCardHeader struct {
	Title LarkCardTitle `json:"title"`
}

LarkCardHeader represents the header of a Lark card

type LarkCardTitle added in v1.3.1

type LarkCardTitle struct {
	Tag     string `json:"tag"`
	Content string `json:"content"`
}

LarkCardTitle represents the title component of a Lark card header

type LarkMessage added in v1.3.1

type LarkMessage struct {
	MsgType string    `json:"msg_type"`
	Card    *LarkCard `json:"card"`
}

LarkMessage represents the structure of a Lark message

func CreateLarkMessage added in v1.3.1

func CreateLarkMessage(content string, isResolved bool) *LarkMessage

CreateLarkMessage creates a Lark message with interactive card format This format uses "msg_type": "interactive" with a card structure

type MSTeamsMessage

type MSTeamsMessage struct {
	Text string `json:"text"`
}

MSTeamsMessage represents a basic message for MS Teams

type TemplateDict added in v1.3.2

type TemplateDict map[string]interface{}

TemplateDict is a custom dictionary type that supports the Set method

func (TemplateDict) Set added in v1.3.2

func (d TemplateDict) Set(key string, value interface{}) TemplateDict

Set adds or updates a key-value pair in the dictionary

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL