messages

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Nov 29, 2026 License: AGPL-3.0 Imports: 29 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

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

View Source
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.

View Source
const (
	LanguageEnglish = "en"
	LanguageRussian = "ru"
)

The languages of messages (route.language); English serves any other.

View Source
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).

View Source
const (
	PageSourceRoute = "route"
	PageSourceTeam  = "team"
)

The sources of the chain of a Page in a Destination: its Route's, or a Team's.

View Source
const (
	SampleStoredSnapshot = "stored_snapshot"
	SampleAlertGroup     = "alert_group"
	SampleExample        = "example"
)

The samples a preview renders against.

View Source
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).

View Source
const AlertsListed = 10

AlertsListed is message.alerts_listed: the distinct values of each label that differs between the Alerts that the Fallback template keeps for shortening, at most AlertsListed per label, and the Alerts a preview of a line template reads.

View Source
const CodeInvalidSample = "invalid_format"

CodeInvalidSample is the code of a Stored Snapshot that cannot serve as a sample.

View Source
const CompactAlertsListed = 5

CompactAlertsListed is message.compact_alerts_listed (P-83): the values of the distinguishing label a Root message lists before "…and K more" (C-29.FR-3).

View Source
const DryRunSample = 20

DryRunSample is template.dry_run_sample.

View Source
const EventPaged = "paged"

EventPaged is the lifecycle event of a Page by Mention.

View Source
const FooterSep = "\x1f"

FooterSep joins the Mentions and the names of the people of a footer in FooterMention and FooterName.

View Source
const FooterUserToken = "user"

FooterUserToken is the name of the trusted Mention token that stands for the user in the footer of an identity space where they have an Account link (C-12.FR-12). The `mention` function of templates never writes it, and neutral text never carries a token, so only Muster's own footer has one. A footer that names several people has one token per person, the first without a group and the others with their position as the group (FooterToken).

View Source
const ReadAlerts = 1000

ReadAlerts is the most Alerts of an Alert Group a message reads; the counts of the Alerts section cover them.

View Source
const ValueCap = 4096

ValueCap is message.value_cap: 4 KB per label or annotation value.

Variables

View Source
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.

View Source
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.

Languages are the languages built-in texts exist in.

TemplateKinds is the closed set of the label template.

Functions

func AlertsLines

func AlertsLines(m Message, esc func(string) string, output func(AlertLine) string, strike func(string) string,
	bullet string) []string

AlertsLines lays out the Alerts line of m (C-29.FR-3): "pod: a, b, c …and 7 more" as one line, or with a line template one line per listed Alert after bullet and then "…and K more"; esc escapes neutral text, output writes the output of a line template and strike strikes a resolved Alert through. None without an Alerts line.

func BuiltinSource

func BuiltinSource(kind, lang string) string

BuiltinSource is the source of the built-in template of a kind in a language; empty for the kinds without one.

func Cap

func Cap(s string) string

Cap cuts s to at most ValueCap bytes at a character boundary, ending it with "…".

func CommandDuration

func CommandDuration(lang string, seconds int64) string

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

func CommandsLine(m Message, mentionsOnly bool) string

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

func Done(lang, command string) string

Done is the answer to a press whose Command ran: "Done: {command}", the Command named in lang.

func Duration

func Duration(lang string, seconds int64) string

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

func EscapeCommonMark(s string) string

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 EscapeHTML

func EscapeHTML(s string) string

EscapeHTML escapes s for Telegram HTML.

func EscapeMarkdown

func EscapeMarkdown(s string) string

EscapeMarkdown escapes s for Mattermost Markdown.

func EscapeMrkdwn

func EscapeMrkdwn(s string) string

EscapeMrkdwn escapes s for Slack's mrkdwn (C-24.FR-7): `&`, `<` and `>` become `&amp;`, `&lt;` and `&gt;`, 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 Escaper

func Escaper(m Markup) func(string) string

Escaper is the escaper of a markup; plain text is left as it is.

func FooterToken

func FooterToken(i int) string

FooterToken is the token of the i-th person of a footer.

func FullTime

func FullTime(t time.Time, tz string) string

FullTime is t in the time zone tz as messages show a start time: 2026-10-04 14:05 UTC.

func HasLayout

func HasLayout(m Message) bool

HasLayout reports whether the content of the Root message m is wholly Muster's compact default, which a MessageLayout carries (C-29.FR-8): not a Route's root_message template, whose Body renders items 3 to 5 (C-29.FR-5), nor its line template, whose output renders each listed Alert, not the Fallback template, which shows every label, and not a Desired state stored before the compact layout, without the status word. Those have content that only the body holds, so they have no layout.

func HeadingLine

func HeadingLine(m Message, linked string) string

HeadingLine is the heading of m around linked, the number and the title as its markup links them (C-29.FR-1 item 1): "#12 PodDown — 🔴 Firing", the status emoji beside the word; a message without the word, a Desired state stored by an earlier version, keeps the heading of L1, "🔴 #12 PodDown".

func KeyLabelsLine

func KeyLabelsLine(m Message) string

KeyLabelsLine is the line of key labels of m as neutral text, `system=kubernetes · namespace: 2 values`; empty when it has none.

func Layout

func Layout(m Message, markup Markup) string

Layout lays m out as text in a markup, as the preview shows it: one section per line in the order of C-29.FR-1 — the heading with the status word, the fields as "{name}: {value}", the summary, the description, the body, the key labels, the Alerts, then the notices, the footer and the links — 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 Length

func Length(m Message, markup Markup) int

Length is the length of m laid out in a markup, in characters.

func MessengerLength

func MessengerLength(s string, markup Markup) int

MessengerLength is the length of s as the messenger of markup counts it: UTF-16 code units for Telegram's HTML, characters otherwise.

func MessengerLimit

func MessengerLimit(markup Markup) int

MessengerLimit is the length limit of the adapter that writes markup, 0 for a bridge's CommonMark and plain text.

func N

func N(lang, key string, count int64, args Args) string

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

func Neutralize(s string) string

Neutralize puts a zero-width space after every `@` of s that has none yet, so that neutralizing twice changes nothing.

func NeutralizeMrkdwnMentions

func NeutralizeMrkdwnMentions(s string) string

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 NoteTime

func NoteTime(t time.Time, tz string) string

NoteTime is t in the time zone tz as notes show it: 14:05.

func PresetLabel

func PresetLabel(lang string, argument int, workdayStart, weekStart string) string

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

func SafeData(d templates.Data, markup Markup) templates.Data

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 SafeLine

SafeLine is the data of a line template, made safe as SafeData does.

func SafeURL

func SafeURL(u string) string

SafeURL is u when it is an absolute http or https link, and empty otherwise.

func StatusColour

func StatusColour(colour string) string

StatusColour is the colour of a message as RGB, "#d32f2f" for firing; empty for an unknown one.

func StatusEmoji

func StatusEmoji(colour string) string

StatusEmoji is the colour of a message as an emoji, 🔴 for firing; empty for an unknown one.

func T

func T(lang, key string, args Args) string

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.

func TestMark

func TestMark(lang string) string

TestMark is the mark before the heading of a test message in a language: "🧪 Test message".

func Value

func Value(s string) string

Value is an alert value made safe and neutral: without the characters of Mention tokens, cut to ValueCap, with its `@` neutralized.

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 AlertValue

type AlertValue struct {
	Value    string `json:"value"`
	Resolved bool   `json:"resolved,omitempty"`
}

AlertValue is the value of the distinguishing label of a listed Alert.

type AlertsLine

type AlertsLine struct {
	Label  string       `json:"label,omitempty"`
	Values []AlertValue `json:"values,omitempty"`
	Lines  []AlertLine  `json:"lines,omitempty"`
	Total  int64        `json:"total"`
}

AlertsLine is the Alerts of a Root message by their distinguishing label (C-29.FR-3): the label, the values of the Alerts listed with whether each is resolved, firing ones first, the output of the Route's line template for each listed Alert when it has one, and how many Alerts the Alert Group has.

func (AlertsLine) More

func (a AlertsLine) More() int64

More is how many Alerts the line does not list, which "…and K more" counts.

type Args

type Args map[string]string

Args are the values of the placeholders of a text, `{name}`.

type Body

type Body struct {
	Text   string `json:"text"`
	Markup Markup `json:"markup"`
}

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).

func (Button) Style

func (b Button) Style() buttons.Style

Style is the style hint of the button, decided by its Command. It is not a field: the JSON of a Message is the Desired state's payload and the input of its hash, which the style must not change.

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 Account links of the users a footer names (nil for none).

type DBTX

type DBTX = dbgen.DBTX

DBTX is the pool, connection or transaction the Renderer reads and writes through.

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

type Failure struct {
	Template string
	Error    *templates.Error
}

Failure is a Route template that failed while rendering a message: its kind and the error with its position.

func (Failure) Detail

func (f Failure) Detail() string

Detail is the failure as the Timeline and the Route show it: "root_message template failed: line 4, column 7: …".

type FooterUser added in v0.1.3

type FooterUser struct {
	Name        string `json:"name"`
	Username    string `json:"username,omitempty"`
	ExternalID  string `json:"external_id,omitempty"`
	DisplayName string `json:"display_name,omitempty"`
}

FooterUser is the user a footer names in an identity space where they have an Account link, with only what its adapter writes them by, so that the Desired state, whose hash is that of its JSON, changes only with what a messenger shows (C-12.FR-12): their Muster display name, and the username, the messenger's user id and the display name of the link where its messenger's Mention uses them.

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 KeyLabel

type KeyLabel struct {
	Name  string `json:"name"`
	Value string `json:"value,omitempty"`
	Count int    `json:"count,omitempty"`
}

KeyLabel is a label of the line of key labels (C-29.FR-2): its value when every firing Alert has the same one, or with Count above 1 how many values they have.

func (KeyLabel) Text

func (k KeyLabel) Text(lang string) string

Text is the key label as the line shows it in lang: `name=value`, or "name: 2 values".

func (KeyLabel) ValueText

func (k KeyLabel) ValueText(lang string) string

ValueText is the value of the key label in lang: its value, or "2 values" when they differ.

type Kind

type Kind string

Kind is what a message is.

const (
	KindRoot  Kind = "root"
	KindReply Kind = "reply"
	KindStorm Kind = "storm_summary"
)

The kinds of messages.

type Label

type Label struct {
	Name  string `json:"name"`
	Value string `json:"value"`
}

Label is a label or an annotation.

type LayoutAlerts

type LayoutAlerts struct {
	Label  string
	Values []AlertValue
	Total  int64
}

LayoutAlerts are the Alerts of a MessageLayout: the distinguishing label, the values listed and the total.

type LayoutPerson

type LayoutPerson struct {
	Name string
	Team string
}

LayoutPerson is a person of a MessageLayout by their Muster display name and, for an Assignee, the name of the owning Team of their chain, empty for none, both made safe.

type Lead

type Lead struct {
	Before string `json:"before"`
	After  string `json:"after"`
}

Lead is the text before and after the Mentions of a message whose Mentions stand in its text, neutral and in the message's language; an adapter escapes it for its markup.

type Link struct {
	Text string `json:"text"`
	URL  string `json:"url"`
}

Link is a link with its text.

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"`
	StatusWord        string                `json:"status_word,omitempty"`
	Fields            []Label               `json:"fields,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"`
	Description       string                `json:"description,omitempty"`
	Body              *Body                 `json:"body,omitempty"`
	KeyLabels         []KeyLabel            `json:"key_labels,omitempty"`
	AlertsLine        *AlertsLine           `json:"alerts_line,omitempty"`
	Alerts            *AlertList            `json:"alerts,omitempty"`
	Lines             []string              `json:"lines,omitempty"`
	Links             []Link                `json:"links,omitempty"`
	Notices           []string              `json:"notices,omitempty"`
	Footer            string                `json:"footer,omitempty"`
	Footers           map[string]string     `json:"footers,omitempty"`
	FooterUsers       map[string]FooterUser `json:"footer_users,omitempty"`
	Buttons           []Button              `json:"buttons"`
	SnoozeSeconds     []int64               `json:"snooze_seconds,omitempty"`
	Owner             string                `json:"owner,omitempty"`
	// FooterPeople are, for a footer that names several people — the Assignees before an acknowledgement
	// (C-29.FR-1, C-32.FR-12) — the people per identity space where one of them has an Account link, in the order of
	// the footer's tokens, a person without a link there empty; FooterUsers holds the one user of any other footer.
	FooterPeople map[string][]FooterUser `json:"footer_people,omitempty"`
	// Assignees are the Assignees the footer names before an acknowledgement, in its order, each with the owning Team
	// of their chain, made safe, and ChainsStopped marks the footer of an acknowledgement that stopped running chains;
	// both are set only in CommonMark, for a bridge's layout (C-29.FR-8), as Owner is.
	Assignees     []Person `json:"assignees,omitempty"`
	ChainsStopped bool     `json:"chains_stopped,omitempty"`
	// FooterMention is the people of the footer as an adapter writes them in its markup, in the order of the footer's
	// tokens and joined by FooterSep — empty for a person it names by name — and FooterName their Muster display names
	// made safe and joined alike, which a footer cut by shortening keeps instead; WithFooterIn sets both for the layout,
	// and neither is stored.
	FooterMention string `json:"-"`
	FooterName    string `json:"-"`
	// Lead is the text around the Mentions of a Page (C-32.FR-9): an adapter that lays the Mentions out in a line of
	// their own writes Before, the Mentions and After as that line, "Step 1: @ivan, you are needed", and leaves the
	// line out without Mentions.
	Lead *Lead `json:"lead,omitempty"`
}

Message is a rendered message, neutral of any markup. A Root message has the compact layout of C-29.FR-1: the colour of its status, the heading with #N and the title linked to the Alert Group page with the status as a word, the fields, the summary and the description, the key labels of the Route's "Labels in the message", the Alerts by their distinguishing label, the notices, the footer, the buttons and the links. A Route's root_message template replaces the summary, the description, the key labels and the Alerts with its Body (C-29.FR-5); the Fallback template shows every label in the sections of L1 — the group labels, common labels and the Alerts one per line — which a Desired state stored by an earlier version may also have, with its environment and common annotations (C-12.FR-1 of L1); 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 where the user it names has an Account link, with a trusted Mention token where the user stands, and FooterUsers that user per identity space, whom its adapter writes as its messenger's Mention (C-12.FR-12); a Desired state stored before them names the user in Footers as text. 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. Owner is the Muster display name of who acknowledged an acknowledged Alert Group, made safe, set only in CommonMark for the `owner` of a bridge's layout (C-29.FR-8), so that the Desired states of the other markups keep their hashes too.

func DeletedNote

func DeletedNote(m Message, at time.Time) Message

DeletedNote adds the note of a Root message published again after it was deleted in the messenger (C-11.FR-13).

func FinalEdit

func FinalEdit(m Message, link string) Message

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

func LateNote(m Message, started, resolved time.Time) Message

LateNote adds the note of a late Publication to m (C-11.FR-11): started and resolved in m's time zone.

func PageMessage

func PageMessage(lang, route, timeZone, colour string, in PageInput) Message

PageMessage is the Thread reply of a Page in lang, for the Route route, of an Alert Group of the colour.

func Shorten

func Shorten(m Message, limit int, markup Markup) (Message, bool)

Shorten shortens m to the limit in a markup and says whether it changed anything; a limit of 0 or less is none.

func ShownButtons

func ShownButtons(m Message, set *buttons.Set, durations []int64) Message

ShownButtons is the Root message m with only the buttons that set shows on a Route with the Snooze durations given, in seconds, in their order (C-28.FR-8): Unsnooze always; a Thread reply, a Storm summary and a nil set keep every button, and so does a set of every button, which leaves m as it is.

func (Message) FooterIn

func (m Message) FooterIn(space string) string

FooterIn is the footer in an identity space — "telegram", "mattermost:<connection>", "slack:<connection>" or "bridge:<connection>" — with the token of the user it names when they have an Account link there, otherwise the footer that names them by their Muster display name (C-12.FR-12).

func (Message) FooterNamed

func (m Message) FooterNamed() string

FooterNamed is the footer of m with each of its people by their Muster display name, as a footer that mentions nobody shows them: what a footer cut by shortening keeps, and the layout's notice.

func (Message) FooterPeopleIn

func (m Message) FooterPeopleIn(space string) []FooterUser

FooterPeopleIn are the people of the footer in the identity space space, in the order of its tokens: the footer's several people, or its one user, with an Account link there; none in a space where nobody it names has one.

func (Message) FooterText added in v0.1.3

func (m Message) FooterText(esc func(string) string) string

FooterText is the footer of m laid out by esc: its text escaped as a whole, and the token of each of its people — which survives the escaping of every markup — then the Mention that WithFooterIn chose for them, as it is.

func (Message) MentionLine

func (m Message) MentionLine(names []string, sep string, escape func(string) string) string

MentionLine is the line of the Mentions of m that an adapter writes first, joined by sep: the Mentions alone, or, with a Lead, the Lead's text around them, escaped by escape; empty without Mentions.

func (Message) OnlyFooterIn

func (m Message) OnlyFooterIn(space string) Message

OnlyFooterIn is m with the footer and the user of the identity space space alone, from which the hash of the Desired state of a Root message in a Destination of that space is computed: an Account link in another space changes nothing that its messenger shows, so it must change no hash either (C-12.FR-12). WithFooterIn lays it out as it lays out m. A message without footers by identity space, or without one for space, keeps only Footer, which names the user by their Muster display name.

func (Message) Text

func (m Message) Text() string

Text is the message laid out as plain text: the stored text of a Desired state.

func (Message) WithFooterIn added in v0.1.3

func (m Message) WithFooterIn(space string, mention func(mentions.User) string) Message

WithFooterIn is m with the footer of the identity space space as its only footer, for an adapter to lay out (C-12.FR-12): each person with an Account link there is written by mention, the adapter's own Mention of them in its markup — or their name escaped for it where it cannot mention them — in the order of the footer's tokens, and by their Muster display name when mention is nil or writes nothing. A message without footers by identity space is returned as it is, so that calling WithFooterIn again changes nothing.

type MessageLayout

type MessageLayout struct {
	Number      int64
	Title       string
	Status      string
	StatusWord  string
	Fields      []Label
	Summary     string
	Description string
	Labels      []Label
	Alerts      *LayoutAlerts
	Notices     []string
	Assignees   []LayoutPerson
	Owner       *LayoutPerson
	Links       []Link
}

MessageLayout is the content of a Root message as structured, plain-text data (C-29.FR-1, FR-8): the MessageLayout of the API and the `layout` of the Bridge protocol. It has the number and the title apart, the status by its key and word, the fields, the summary and the description, the key labels with their values — "2 values" where they differ — the Alerts by their distinguishing label with the total, the notices with the footer as their last line, the people and the links. The people are the Owner while the Alert Group is acknowledged, named without a Team (P-89), whose footer is then no notice but for "Escalation chains stopped", and before an acknowledgement the Assignees with the owning Team of their chain (C-32.FR-12), whose footer is no notice either; each names a person by their Muster display name, and the Bridge adapter adds the reference to their Mention entry.

func LayoutOf

func LayoutOf(m Message) MessageLayout

LayoutOf is the MessageLayout of the Root message m, its values as neutral text, from the fields the adapters lay out: a message shortened for a limit has the layout of what is left. The footer names its people by their Muster display names, also in a message whose footer an adapter chose (WithFooterIn); with an Owner, the footer of the acknowledgement is the Owner, and "Escalation chains stopped" a line of the notices when it stopped chains; with Assignees, the footer before an acknowledgement is the Assignees, who are never cut.

type Names

type Names interface {
	FooterUsers(ctx context.Context, db mentions.DBTX, groupID int64) (map[string]mentions.User, error)
	AssigneeUsers(ctx context.Context, db mentions.DBTX, groupID int64) (map[int64]map[string]mentions.User, error)
}

Names are the user the footer of an Alert Group names, and its Assignees by id, by the identity spaces where their Account link lets the messenger mention them (C-12.FR-12, C-32.FR-12), declared by their consumer; *mentions.Service implements them.

type PageInput

type PageInput struct {
	Step         int
	Mentioned    bool
	Unlinked     []string
	Messenger    string
	Source       string
	ChainTeam    string
	OnCallTeam   string
	Schedule     string
	People       []string
	Team         string
	Everyone     bool
	Importance   string
	AgainSeconds int
	Again        bool
}

PageInput is a Thread reply of a Page to render: the step, whether the reply mentions anyone, the logins of the people without an Account link in the Destination's Identity space and the messenger's name, the source of the chain in this Destination and the Team of "Chain of the Team", what the step Pages — the On-call of a Schedule of a Team, people by login, a Team by name or everyone in the chat — its importance, the wait until the rule's next Mention, 0 for none, and whether it is a later Mention.

type Person

type Person struct {
	Name string `json:"name"`
	Team string `json:"team,omitempty"`
}

Person is a person a footer names, the Assignees: their Muster display name and the name of the owning Team of their chain, empty for none, both made safe.

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
	Layout         *MessageLayout
	Length         int
	MessengerLimit int
}

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. A Root message also has its Layout, nil when the template failed or when its content is not Muster's compact default (HasLayout), as a bridge then receives none, the Length of its output as its messenger counts it and the MessengerLimit of the adapter of its markup, 0 for none (C-29.FR-7).

type Rendered

type Rendered struct {
	Message  Message
	KeyID    string
	Failure  *Failure
	Rendered []string
}

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 New

func New(cfg Config) *Renderer

New is the Renderer of cfg.

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

func (r *Renderer) Data(src *Source) templates.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

func (r *Renderer) GroupURL(publicID string) string

GroupURL is the page of an Alert Group in Muster, under MUSTER_PUBLIC_URL.

func (*Renderer) Load

func (r *Renderer) Load(ctx context.Context, db DBTX, groupID int64) (*Source, error)

Load reads the Alert Group groupID and its Alerts through db.

func (*Renderer) Page

func (r *Renderer) Page(ctx context.Context, db DBTX, groupID int64, in PageInput) (Message, error)

Page renders the Thread reply of a Page of the Alert Group groupID, reading through db.

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

func (r *Renderer) Root(src *Source, markup Markup) Rendered

Root renders the Root message of src for a markup (C-29.FR-1, FR-5, C-12.FR-6): Muster's colour, heading with the status word, fields, links, notices, footer and buttons around the body of the Route's root_message template or the compact 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, and in CommonMark the Owner of an acknowledged Alert Group with whether its acknowledgement stopped chains, and the Assignees of a firing one, for the `owner`, the notices and the `assignees` of a bridge's layout.

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

func (r *Renderer) Storm(routePublicID, routeName, lang string, count, urgent int64) Message

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

func (r *Renderer) StormOver(routePublicID, lang string, open int64) Message

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

func (r *Renderer) TestExample(ctx context.Context) (*Source, error)

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

func (r *Renderer) TestRoot(src *Source, markup Markup, destination string) Rendered

TestRoot renders the Root message of src in markup as a Destination test sends it, without recording anything about its Route's templates: with the buttons of the Destination's set, src.Buttons (C-16.FR-4, C-28.FR-9); 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.

func (*Renderer) TestSample

func (r *Renderer) TestSample(ctx context.Context, publicID string) (*Source, error)

TestSample reads the Alert Group publicID with its Alerts and links, as the source of a Destination test or preview; an unknown one is ErrNotFound. Its Route is in Source.Route.

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
	MessageLabels    []string
}

RouteRef is the Route of an Alert Group as its messages use it: its templates — nil for the built-in one — the template its error state is about, empty when there is none, and its effective "Labels in the message" (C-29.FR-2).

type Source

type Source struct {
	ID                int64
	PublicID          string
	Number            int64
	Title             string
	Summary           string
	Description       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
	InstanceLabels    []string
	Teams             []string
	Owner             string
	SnoozedBy         string
	ResolvedBy        string
	Alerts            []SourceAlert
	TotalAlerts       int64
	// Links are its links after "Open in Muster"; FooterUsers the user its footer names, by the identity spaces
	// where their Account link lets the messenger mention them.
	Links       []links.Link
	FooterUsers map[string]mentions.User
	Buttons     *buttons.Set
	// Assignees are its Assignees, whom item 7 names before an acknowledgement (C-29.FR-1, C-32.FR-12), and
	// ChainsStopped whether its acknowledgement stopped running chains, which item 7 says after it.
	Assignees     []SourceAssignee
	ChainsStopped bool
	// contains filtered or unexported fields
}

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), and its Instance labels, which name the Alerts first (C-29.FR-3). Teams are the names of the Alert Group's Teams in the order they joined (C-25.FR-6), and Description the description annotation of its first Alert that has one, set once like the summary (C-29.FR-1); an Alert Group created before 0.2.0 has none. Buttons is the button set of the Destination a test message or a preview is for, which TestRoot applies (C-16.FR-4); nil shows every button. Delivery applies each Destination's set to the Root messages it stores (ShownButtons).

type SourceAlert

type SourceAlert struct {
	Fingerprint  string
	Labels       map[string]string
	Annotations  map[string]string
	StartsAt     time.Time
	EndsAt       *time.Time
	GeneratorURL string
	Firing       bool
}

SourceAlert is one Alert of an Alert Group.

type SourceAssignee

type SourceAssignee struct {
	ID    int64
	Name  string
	Team  string
	Links map[string]mentions.User
}

SourceAssignee is an Assignee of an Alert Group: the User by id and display name, the name of the owning Team of their chain, empty for none, and the User by the identity spaces where their Account link lets the messenger mention them.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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