Documentation
¶
Overview ¶
Package messages renders what Muster sends to messengers (C-12): the markup-neutral Root message of C-12.FR-1 with its default content, the Thread replies, the Storm summary and the notices, in English or Russian per route.language and with absolute times in organization.time_zone; Route templates run in the sandbox of ADR-0012 with a dry run on save and a preview, and the Fallback template stands in for a template that fails at runtime. It never sends: delivery stores what it renders as the Desired state and the adapters lay it out (ADR-0005).
Index ¶
- Constants
- Variables
- func BuiltinSource(kind, lang string) string
- func Cap(s string) string
- func CommandDuration(lang string, seconds int64) string
- func CommandsLine(m Message, mentionsOnly bool) string
- func Done(lang, command string) string
- func Duration(lang string, seconds int64) string
- func EscapeCommonMark(s string) string
- func EscapeHTML(s string) string
- func EscapeMarkdown(s string) string
- func EscapeMrkdwn(s string) string
- func Escaper(m Markup) func(string) string
- func FullTime(t time.Time, tz string) string
- func Layout(m Message, markup Markup) string
- func Length(m Message, markup Markup) int
- func N(lang, key string, count int64, args Args) string
- func Neutralize(s string) string
- func NeutralizeMrkdwnMentions(s string) string
- func NoteTime(t time.Time, tz string) string
- func PresetLabel(lang string, argument int, workdayStart, weekStart string) string
- func SafeData(d templates.Data, markup Markup) templates.Data
- func SafeLine(a templates.Alert, g templates.AlertGroup, markup Markup) templates.LineData
- func SafeURL(u string) string
- func StatusColour(colour string) string
- func StatusEmoji(colour string) string
- func T(lang, key string, args Args) string
- func TestMark(lang string) string
- func Value(s string) string
- type AlertLine
- type AlertList
- type Args
- type Body
- type Button
- type Config
- type DBTX
- type Distinct
- type Failure
- type Heading
- type Kind
- type Label
- type Link
- type Links
- type Markup
- type Message
- type Names
- type PreviewRequest
- type PreviewResult
- type Rendered
- type Renderer
- func (r *Renderer) CheckTemplate(ctx context.Context, routeID int64, kind, source, lang string) error
- func (r *Renderer) Data(src *Source) templates.Data
- func (r *Renderer) GroupURL(publicID string) string
- func (r *Renderer) Load(ctx context.Context, db DBTX, groupID int64) (*Source, error)
- func (r *Renderer) Preview(ctx context.Context, req PreviewRequest) (PreviewResult, error)
- func (r *Renderer) Reply(ctx context.Context, db DBTX, groupID int64, in ReplyInput) (Message, error)
- func (r *Renderer) Root(src *Source, markup Markup) Rendered
- func (r *Renderer) SetRequests(p RequestPreviewer)
- func (r *Renderer) Settle(ctx context.Context, db DBTX, src *Source, failures []Failure, ...) (func(context.Context), error)
- func (r *Renderer) Storm(routePublicID, routeName, lang string, count, urgent int64) Message
- func (r *Renderer) StormOver(routePublicID, lang string, open int64) Message
- func (r *Renderer) TemplateSaved(ctx context.Context, db DBTX, routeID int64, publicID string, kinds []string) error
- func (r *Renderer) TestExample(ctx context.Context) (*Source, error)
- func (r *Renderer) TestRoot(src *Source, markup Markup, destination string) Rendered
- func (r *Renderer) TestSample(ctx context.Context, publicID string) (*Source, error)
- type ReplyInput
- type RequestPreviewer
- type RouteRef
- type Source
- type SourceAlert
Constants ¶
const ( ColourFiring = "firing" ColourAcknowledged = "acknowledged" ColourSnoozed = "snoozed" ColourResolved = "resolved" ColourStorm = "storm" )
The colours of a message: the status of its Alert Group, or a Storm.
const ( LanguageEnglish = "en" LanguageRussian = "ru" )
The languages of messages (route.language); English serves any other.
const ( TemplateRootMessage = "root_message" TemplateLine = "line" TemplateAckTimeoutNotice = "ack_timeout_notice" TemplateLinkRule = "link_rule" TemplateWebhookRequest = "webhook_request" )
The template kinds of the metrics and of the template error state (C-12.FR-13).
const ( SampleStoredSnapshot = "stored_snapshot" SampleAlertGroup = "alert_group" SampleExample = "example" )
The samples a preview renders against.
const ( EventAlertsAdded = "alerts_added" EventAlertReplaced = "alert_replaced" EventReopened = "reopened" EventTakeover = "takeover" EventSnoozeEnded = "snooze_ended" EventUrgencyRaised = "urgency_raised" EventResolved = "resolved" EventUnacknowledged = "unacknowledged" EventAckTimeout = "ack_timeout" EventUnclaimed = "unclaimed" EventReminder = "reminder" EventAutoUnacknowledged = "auto_unacknowledged" EventNoticesMissed = "notices_missed" )
The lifecycle events a Thread reply is about (C-09.FR-22, C-10.FR-15, C-17.FR-11).
const AlertsListed = 10
AlertsListed is message.alerts_listed: one line per Alert up to it; above it, the distinct values of each differing label, at most AlertsListed per label.
const CodeInvalidSample = "invalid_format"
CodeInvalidSample is the code of a Stored Snapshot that cannot serve as a sample.
const DryRunSample = 20
DryRunSample is template.dry_run_sample.
const ReadAlerts = 1000
ReadAlerts is the most Alerts of an Alert Group a message reads; the counts of the Alerts section cover them.
const ValueCap = 4096
ValueCap is message.value_cap: 4 KB per label or annotation value.
Variables ¶
var ( ErrNotFound = errors.New("no such alert group") ErrRouteNotFound = errors.New("no such route") ErrSnapshotNotFound = errors.New("no such stored snapshot") )
The samples and Routes a preview names that do not exist in the Organization, or a Stored Snapshot past retention.stored_snapshots.
var ErrUnsupportedKind = errors.New("the kind of template has no preview yet")
ErrUnsupportedKind is a preview of a kind of template this build does not render.
var Languages = []string{LanguageEnglish, LanguageRussian}
Languages are the languages built-in texts exist in.
var TemplateKinds = []string{TemplateRootMessage, TemplateLine, TemplateAckTimeoutNotice, TemplateLinkRule, TemplateWebhookRequest}
TemplateKinds is the closed set of the label template.
Functions ¶
func BuiltinSource ¶
BuiltinSource is the source of the built-in template of a kind in a language; empty for the kinds without one.
func CommandDuration ¶
CommandDuration is a Snooze duration in lang as a Text command writes it (C-22.FR-14), as the commands line of a Root message shows it: the answer to a Snooze for a duration the Route does not have names the Route's this way.
func CommandsLine ¶
CommandsLine is the line that ends the body of a Root message for a bridge that forwards Thread messages and has no buttons (C-22.FR-5): the Text commands of its buttons in its language, the first Snooze duration only — "Reply in the Thread: ack · resolve · snooze 1h" — or with mentionsOnly, for a bridge that forwards only messages that mention the bot, "Reply in the Thread, mentioning the bot: …". A message without buttons, a resolved one, has none.
func Done ¶
Done is the answer to a press whose Command ran: "Done: {command}", the Command named in lang.
func Duration ¶
Duration is a Snooze duration as a button shows it: hours up to a day, then days; minutes or seconds below an hour.
func EscapeCommonMark ¶
EscapeCommonMark escapes s for CommonMark with strikethrough, a bridge's envelope body (C-22.FR-4): every punctuation that can start markup inside a line, and the marker a line starts with after any spaces and tabs — of a heading, a list item or a setext underline — so that alert data stay literal text. Any indentation, not only up to three spaces: a line of alert data laid out inside a list item is indented relative to it. It drops the lines of only spaces and tabs, the line ending after the last line and the spaces and tabs s starts with: without a blank line every later line continues the paragraph s starts, which an indented code block cannot interrupt, inside its list item or block quote. It does not neutralize `@`: Value does that first.
func EscapeMarkdown ¶
EscapeMarkdown escapes s for Mattermost Markdown.
func EscapeMrkdwn ¶
EscapeMrkdwn escapes s for Slack's mrkdwn (C-24.FR-7): `&`, `<` and `>` become `&`, `<` and `>`, so that nothing in s becomes a link, a Mention, <!channel> or <!here> (F-097); and since mrkdwn has no escape for `*`, `_`, `~` and the backquote, each of them — and `@`, as Neutralize does — is followed by a zero-width space unless one follows it already, so that none pairs into emphasis, strikethrough or code. It is applied once, to neutral text: an entity in s is escaped again and shows as written.
func FullTime ¶
FullTime is t in the time zone tz as messages show a start time: 2026-10-04 14:05 UTC.
func Layout ¶
Layout lays m out as text in a markup, as the preview shows it: one section per line, neutral text escaped for the markup and without Mention tokens, template output as written with its tokens shown as `@` names — in mrkdwn with its literal Mentions neutralized, as a Slack message carries it — and the buttons as a last line of bracketed labels. The adapters lay messages out for their messengers, a Slack message's body section with this layout in mrkdwn. CommonMark has a layout of its own, which a bridge's envelope body takes.
func N ¶
N is the plural form of the text key for count in lang — key_one, key_few, key_many or key_other by the language's rules — with {count} and the other placeholders filled.
func Neutralize ¶
Neutralize puts a zero-width space after every `@` of s that has none yet, so that neutralizing twice changes nothing.
func NeutralizeMrkdwnMentions ¶
NeutralizeMrkdwnMentions keeps template output in mrkdwn from notifying anyone with a literal Mention, as a literal `@all` in a template's text is escaped (C-12.FR-8): only the Destination's Mention settings notify (C-24.FR-6). Its links stay links, and neutralizing twice changes nothing.
func PresetLabel ¶
PresetLabel is the label of the Snooze button of a Snooze preset in lang (C-10.FR-18), by the argument of the button: "Until tomorrow 09:00" for buttons.ArgumentTomorrow and "Until Monday 09:00" — «До понедельника 09:00» — for buttons.ArgumentWeekStart, from workdayStart, organization.workday_start as HH:MM, and weekStart, organization.week_start from monday to sunday; empty for any other argument.
func SafeData ¶
SafeData is the template data d as a template writing markup sees it: every label and annotation value — and the title, summary, Route and Owner of the Alert Group — cut to ValueCap, neutralized and escaped for markup, every generator URL kept only when it is http(s), and in mrkdwn every URL — the generator URLs, ExternalURL and the Alert Group's — escaped for a link.
func StatusColour ¶
StatusColour is the colour of a message as RGB, "#d32f2f" for firing; empty for an unknown one.
func StatusEmoji ¶
StatusEmoji is the colour of a message as an emoji, 🔴 for firing; empty for an unknown one.
func T ¶
T is the built-in text key in lang with its placeholders filled; a key missing in lang falls back to English, and one missing in English is the key itself.
Types ¶
type AlertLine ¶
type AlertLine struct {
Text string `json:"text"`
Resolved bool `json:"resolved,omitempty"`
Markup Markup `json:"markup,omitempty"`
}
AlertLine is the line of one Alert; Markup is set for the output of a Route's line template.
type AlertList ¶
type AlertList struct {
Lines []AlertLine `json:"lines,omitempty"`
Distinct []Distinct `json:"distinct,omitempty"`
FullList *Link `json:"full_list,omitempty"`
}
AlertList is the Alerts section: one line per Alert up to message.alerts_listed, or above it the distinct values of each label that differs between the Alerts and a link to the full list. With lines, the distinct values are kept for shortening and not shown.
type Body ¶
Body is the output of a Route's root_message template, in the markup it was rendered for.
type Button ¶
type Button struct {
Command string `json:"command"`
Argument int `json:"argument,omitempty"`
Label string `json:"label"`
ActionID string `json:"action_id,omitempty"`
KeyID string `json:"key_id,omitempty"`
}
Button is a Command button: the Command, its argument (the index of a Snooze duration), its label and the signed action id with the full id of the key that signed it (C-12.FR-1, internal/buttons).
type Config ¶
type Config struct {
OrgID int64
DB DBTX
PublicURL string
Business clock.Clock
Real clock.Clock
Keys buttons.Keys
Log *logging.Logger
RunbookBase string
Links Links
Names Names
}
Config is what a Renderer needs: the Organization, the main pool that previews and dry runs read, MUSTER_PUBLIC_URL for the links to Muster, the business clock of `now` and of the template error state, the real clock of the sandbox's execution limit and of the render durations, the Keyring that signs the buttons (nil leaves them unsigned), the logger, MUSTER_RUNBOOK_BASE_URL, the links of Alert Groups and the usernames of the users a footer names (nil for none).
type Distinct ¶
type Distinct struct {
Label string `json:"label"`
Values []string `json:"values"`
More int `json:"more,omitempty"`
}
Distinct is the distinct values of a label that differs between the Alerts, at most the per-label limit, and how many more there are.
type Failure ¶
Failure is a Route template that failed while rendering a message: its kind and the error with its position.
type Heading ¶
type Heading struct {
Number int64 `json:"number"`
Title string `json:"title"`
URL string `json:"url"`
}
Heading is #N and the title of the Alert Group, linked to its page.
type Links ¶
type Links interface {
Evaluate(ctx context.Context, db links.DBTX, in links.Input) ([]links.Link, error)
RenderURL(ctx context.Context, db links.DBTX, source string, in links.Input) (string, error)
}
Links are the links of an Alert Group and the preview of a Link rule's URL template (C-12.FR-9), declared by their consumer; *links.Service implements them.
type Markup ¶
type Markup string
Markup is the markup an adapter writes, which template output is written in and alert data are escaped for.
const ( MarkupMarkdown Markup = "markdown" MarkupHTML Markup = "html" MarkupPlain Markup = "plain" // MarkupCommonMark is CommonMark 0.31 with strikethrough, a bridge's envelope body (C-22.FR-4). MarkupCommonMark Markup = "commonmark" // MarkupMrkdwn is Slack's mrkdwn, the text of a Slack message's sections (C-24.FR-4, FR-7). MarkupMrkdwn Markup = "mrkdwn" )
The markups of C-12.FR-7: Mattermost Markdown, Telegram HTML, CommonMark for bridges, Slack's mrkdwn, and plain text for outgoing webhooks and the stored text of a Desired state.
type Message ¶
type Message struct {
Kind Kind `json:"kind"`
Language string `json:"language"`
TimeZone string `json:"time_zone"`
Colour string `json:"colour"`
Heading *Heading `json:"heading,omitempty"`
Environment string `json:"environment,omitempty"`
GroupLabels []Label `json:"group_labels,omitempty"`
CommonLabels []Label `json:"common_labels,omitempty"`
CommonAnnotations []Label `json:"common_annotations,omitempty"`
Summary string `json:"summary,omitempty"`
Body *Body `json:"body,omitempty"`
Alerts *AlertList `json:"alerts,omitempty"`
Lines []string `json:"lines,omitempty"`
Links []Link `json:"links,omitempty"`
Notices []string `json:"notices,omitempty"`
Buttons []Button `json:"buttons"`
SnoozeSeconds []int64 `json:"snooze_seconds,omitempty"`
}
Message is a rendered message, neutral of any markup, in the sections of C-12.FR-1: the colour of its status, the heading with #N and the title linked to the Alert Group page, the environment and start time, the group labels, common labels and common annotations, the summary, the Alerts, the links, the notices, the footer and the buttons. A Route's root_message template replaces the sections from Environment to Alerts with its Body; Lines are the text of a Thread reply, a Storm summary or the Fallback template. Each adapter lays a Message out for its messenger and escapes its neutral text (C-13.FR-8, C-14.FR-13); a Body and the template lines of Alerts are already written in their Markup, where a trusted Mention token of the `mention` function stands for the adapter to render (C-12.FR-8). Footers are the footer per identity space whose username names the user (C-12.FR-12). Language and TimeZone are those it was rendered in, for the notes delivery adds at call time. SnoozeSeconds are the Route's Snooze durations, which its Snooze buttons name by index, set only in CommonMark and mrkdwn: a bridge writes the first in the commands line and drops Snooze buttons from the longest (C-22.FR-5), Slack's Snooze menu names each as its option (C-24.FR-5), and the Desired states of the other markups keep their hashes.
func DeletedNote ¶
DeletedNote adds the note of a Root message published again after it was deleted in the messenger (C-11.FR-13).
func FinalEdit ¶
FinalEdit is the last state of a Root message in a Destination it leaves (C-11.FR-14): what it shows with the note "No longer updated here" and the link to Muster, and no buttons, since nothing there is answered any more.
func LateNote ¶
LateNote adds the note of a late Publication to m (C-11.FR-11): started and resolved in m's time zone.
func Shorten ¶
Shorten shortens m to the limit in a markup and says whether it changed anything; a limit of 0 or less is none.
type Names ¶
type Names interface {
}
Names are the messenger usernames, by identity space, of the user the footer of an Alert Group names (C-12.FR-12), declared by their consumer; *mentions.Service implements them.
type PreviewRequest ¶
type PreviewRequest struct {
Kind string
Template string
Format Markup
RouteID string
SnapshotID string
AlertGroupID string
Language string
LengthLimit int
}
PreviewRequest is previewTemplate: the kind and the template, empty for the built-in one; the markup, Markdown by default; the Route; the sample — a Stored Snapshot or an Alert Group, by default the Route's recent Stored Snapshots or the example; the language, by default the Route's; and a length limit, 0 for none.
type PreviewResult ¶
type PreviewResult struct {
Valid bool
Output string
Truncated bool
Format Markup
Source string
Sample string
Errors []*templates.Error
}
PreviewResult is what a preview shows: whether the template rendered against every sample, the output against the first one in the requested markup, whether it was shortened, the source of the template — the built-in one for an empty template — the sample and the errors with their positions.
type Rendered ¶
Rendered is a Root message, the key that signed its buttons, the Route template that failed, if any — the message is then the Fallback template — and the Route templates that rendered.
type Renderer ¶
type Renderer struct {
// contains filtered or unexported fields
}
Renderer renders the messages of an Organization (C-12): Root messages, with a Route's templates or the default content and the Fallback template when a template fails; Thread replies; Storm summaries; previews and dry runs.
func (*Renderer) CheckTemplate ¶
func (r *Renderer) CheckTemplate(ctx context.Context, routeID int64, kind, source, lang string) error
CheckTemplate is the dry run of a Route template on save (C-12.FR-5), reading the main pool: it parses source and renders it as kind against the most recent Stored Snapshots the Route routeID took — none for a new Route, 0 — or the example; the first failure is the *templates.Error returned.
func (*Renderer) Data ¶
Data is the template data of src with alert data as received, unescaped for any markup: what the request templates of an outgoing webhook read, whose receiver's format Muster does not know (C-15.FR-3).
func (*Renderer) GroupURL ¶
GroupURL is the page of an Alert Group in Muster, under MUSTER_PUBLIC_URL.
func (*Renderer) Preview ¶
func (r *Renderer) Preview(ctx context.Context, req PreviewRequest) (PreviewResult, error)
Preview renders a template against its sample (previewTemplate), reading the main pool. An unknown Route, Stored Snapshot or Alert Group is ErrRouteNotFound, ErrSnapshotNotFound or ErrNotFound; a template that fails is a result with Valid false, never an error.
func (*Renderer) Reply ¶
func (r *Renderer) Reply(ctx context.Context, db DBTX, groupID int64, in ReplyInput) (Message, error)
Reply renders the Thread reply in of the Alert Group groupID, reading through db.
func (*Renderer) Root ¶
Root renders the Root message of src for a markup (C-12.FR-1, FR-2, FR-6): Muster's colour, heading, links, notices, footer and buttons around the body of the Route's root_message template or the default content with the Route's line template; when a Route template fails, the Fallback template. In CommonMark and mrkdwn it also carries the Route's Snooze durations, for a bridge's commands line and Slack's Snooze menu.
func (*Renderer) SetRequests ¶
func (r *Renderer) SetRequests(p RequestPreviewer)
SetRequests sets what previews the request templates of outgoing webhooks, before any preview.
func (*Renderer) Settle ¶
func (r *Renderer) Settle(ctx context.Context, db DBTX, src *Source, failures []Failure, rendered []string) ( func(context.Context), error)
Settle records, in the transaction db of the render, what the Route templates of src came to (C-12.FR-6): a failure sets the Route's template error when none is set and raises MusterTemplateError; a template that rendered again clears the error about it and resolves the Internal alert. It returns what to run once the transaction committed: the counter muster_template_errors_total and the log lines.
func (*Renderer) Storm ¶
Storm is the Storm summary of an active Storm of a Route (C-12.FR-10): "⛈ Storm on {Route}: K Alert Groups, C urgent — open in Muster", with the link to the Route's Alert Groups.
func (*Renderer) StormOver ¶
StormOver is the final state of the Storm summary: "Storm over: M Alert Groups still open".
func (*Renderer) TemplateSaved ¶
func (r *Renderer) TemplateSaved(ctx context.Context, db DBTX, routeID int64, publicID string, kinds []string) error
TemplateSaved clears the template error of the Route routeID and resolves MusterTemplateError, in the transaction db that saved a new template of the kind the error is about (C-12.FR-6).
func (*Renderer) TestExample ¶
TestExample is the built-in example of a Destination test or preview, with the settings of the Default route: three firing Alerts of one rule in a production cluster, ten minutes old.
func (*Renderer) TestRoot ¶
TestRoot renders the Root message of src in markup as a Destination test sends it, without recording anything about its Route's templates: with destination, the public_id of the Destination under test, its buttons carry action ids of the subject test that name that Destination, whose presses change nothing; with an empty one they are unsigned.
type ReplyInput ¶
type ReplyInput struct {
Event string
Seq int64
Fingerprints []string
Listed int
Markup Markup
After func(f func(context.Context))
Fallback func(detail string)
}
ReplyInput is a Thread reply to render: its lifecycle event, the number of the first event it stands for, the fingerprints of the new Alerts it lists and how many it lists at most. An ack timeout notice renders the Route's template for Markup, plain text when empty; a failing template is reported to Fallback with its detail, and what to run once the transaction of the render committed — the counter and the log line of a failure — is handed to After, or run at once when After is nil.
type RequestPreviewer ¶
type RequestPreviewer interface {
PreviewRequest(src string, sample templates.Data) (string, error)
}
RequestPreviewer renders one request template of an outgoing webhook against the template data of a sample, alert data unescaped and its Secrets masked (C-12.FR-4, C-15.FR-10), declared by its consumer; *webhooks.Adapter implements it. A template that fails is a *templates.Error.
type RouteRef ¶
type RouteRef struct {
ID int64
PublicID string
Name string
Language string
SnoozeDurations []int64
RootMessage *string
Line *string
// AckTimeoutNotice is the Route's ack_timeout_notice template, nil for the built-in one.
AckTimeoutNotice *string
ErrorTemplate string
}
RouteRef is the Route of an Alert Group as its messages use it: its templates — nil for the built-in one — and the template its error state is about, empty when there is none.
type Source ¶
type Source struct {
ID int64
PublicID string
Number int64
Title string
Summary string
Status string
SeverityLevel string
Urgent bool
KeyLabels []string
KeyValues map[string]string
CommonLabels map[string]string
CommonAnnotations map[string]string
FiringCount int64
ReopenCount int64
ResolvedByKind string
ResolveReason string
SnoozeUntil *time.Time
SnoozeNoEnd bool
Unclaimed bool
StartedAt time.Time
Route RouteRef
TimeZone string
WorkdayStart string
WeekStart string
Owner string
SnoozedBy string
ResolvedBy string
Alerts []SourceAlert
TotalAlerts int64
// Links are its links after "Open in Muster"; FooterNames the messenger usernames, by identity space, of the
// user its footer names.
Links []links.Link
}
Source is an Alert Group as its messages show it, read through the transaction of the change, with the Organization's time zone, start of the working day (organization.workday_start, HH:MM) and first day of the week (organization.week_start, monday to sunday), which the labels of the Snooze presets name (C-10.FR-18).