feat: publish standalone worker
Separate worker packaging and service lifecycle from the control plane.
Этот коммит содержится в:
34
internal/notifyrender/count.go
Обычный файл
34
internal/notifyrender/count.go
Обычный файл
@@ -0,0 +1,34 @@
|
||||
// Package notifyrender owns the subject/body templates used by both the
|
||||
// legacy sender (internal/sender) and the worker-driven notification
|
||||
// producer (internal/notifier). It is a leaf package so the notifier package
|
||||
// can pre-render notification content for the worker without importing the
|
||||
// sender package, which would otherwise create an import cycle (sender's
|
||||
// tests already import notifier to drive the legacy loop).
|
||||
package notifyrender
|
||||
|
||||
import (
|
||||
"log"
|
||||
"strconv"
|
||||
|
||||
"rsgit.ru/rsmon/rsmon/config/translator"
|
||||
)
|
||||
|
||||
// GetCount provides functionality.
|
||||
func GetCount(count int, kind string) string {
|
||||
tr, err := translator.Translator.C(kind, float64(count), 0, strconv.Itoa(count))
|
||||
if err != nil {
|
||||
log.Println("translator error", err)
|
||||
return "монитор"
|
||||
}
|
||||
return tr
|
||||
}
|
||||
|
||||
// GetDownMany provides functionality.
|
||||
func GetDownMany(count int) string {
|
||||
return "Не " + GetCount(count, "monitor")
|
||||
}
|
||||
|
||||
// GetUpMany provides functionality.
|
||||
func GetUpMany(count int) string {
|
||||
return "Снова " + GetCount(count, "monitor")
|
||||
}
|
||||
95
internal/notifyrender/event_table.go
Обычный файл
95
internal/notifyrender/event_table.go
Обычный файл
@@ -0,0 +1,95 @@
|
||||
package notifyrender
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/olekukonko/tablewriter"
|
||||
tablewriterTw "github.com/olekukonko/tablewriter/tw"
|
||||
|
||||
"rsgit.ru/rsmon/rsmon/app/models"
|
||||
"rsgit.ru/rsmon/rsmon/internal/util"
|
||||
)
|
||||
|
||||
// RenderEventsTable provides functionality.
|
||||
func RenderEventsTable(message *models.Message, tn time.Time) (string, string) {
|
||||
if message.Kind == stateTest {
|
||||
return "Тестовое сообщение от rsmon.ru", "Тестовое сообщение от rsmon.ru"
|
||||
}
|
||||
|
||||
cols := []string{"Монитор", "Проверка", "Время начала", "Время окончания", "Продолжительность", "Статус", "Ошибка"}
|
||||
|
||||
asciiBuf := bytes.NewBuffer([]byte{})
|
||||
markdownBuf := bytes.NewBuffer([]byte{})
|
||||
|
||||
table := tablewriter.NewTable(asciiBuf,
|
||||
tablewriter.WithHeader(cols),
|
||||
tablewriter.WithBorders(tablewriterTw.Border{Left: tablewriterTw.On, Top: tablewriterTw.Off, Right: tablewriterTw.On, Bottom: tablewriterTw.Off}), //nolint:lll,staticcheck // deprecated API, pending migration
|
||||
)
|
||||
|
||||
markdownBuf.WriteString("|")
|
||||
for _, col := range cols {
|
||||
markdownBuf.WriteString(" " + col + " |")
|
||||
}
|
||||
markdownBuf.WriteString("\n")
|
||||
|
||||
markdownBuf.WriteString("|")
|
||||
for range cols {
|
||||
markdownBuf.WriteString(" --- |")
|
||||
}
|
||||
markdownBuf.WriteString("\n")
|
||||
|
||||
for _, event := range message.Events { //nolint:gocritic // range copy is acceptable here
|
||||
checksDown := []string{}
|
||||
for _, check := range event.Checks { //nolint:gocritic // range copy is acceptable here
|
||||
msg := check.Kind + ":"
|
||||
if check.Name != nil {
|
||||
msg = msg + " " + *check.Name
|
||||
}
|
||||
if check.URL != nil {
|
||||
msg = msg + " " + *check.URL + ""
|
||||
}
|
||||
// msg = msg + "\n"
|
||||
if check.Error != nil {
|
||||
// msg = msg + "<span style='display: inline-block; background-color: red'>Ошибка:" + *check.Error + "</span>"
|
||||
msg = msg + " :warning: Ошибка:" + *check.Error
|
||||
}
|
||||
// msg = msg + "\n"
|
||||
|
||||
checksDown = append(checksDown, msg)
|
||||
}
|
||||
|
||||
startTime := ""
|
||||
if event.StartTime != nil {
|
||||
startTime = event.StartTime.Format("02.01.2006 15:04:05")
|
||||
}
|
||||
|
||||
endTime := ""
|
||||
if event.EndTime != nil {
|
||||
endTime = event.EndTime.Format("02.01.2006 15:04:05")
|
||||
}
|
||||
|
||||
row := []string{
|
||||
event.Monitor.GetLabel(),
|
||||
strings.Join(checksDown, " ; "),
|
||||
startTime,
|
||||
endTime,
|
||||
util.FormatDuration(event.GetDuration(tn)),
|
||||
event.State,
|
||||
event.Reason,
|
||||
}
|
||||
_ = table.Append(row)
|
||||
|
||||
markdownBuf.WriteString("| ")
|
||||
for _, col := range row {
|
||||
markdownBuf.WriteString(" " + col + " |")
|
||||
}
|
||||
markdownBuf.WriteString("\n")
|
||||
}
|
||||
// markdownBuf.WriteString("\n")
|
||||
|
||||
_ = table.Render()
|
||||
|
||||
return asciiBuf.String(), markdownBuf.String()
|
||||
}
|
||||
98
internal/notifyrender/get_content.go
Обычный файл
98
internal/notifyrender/get_content.go
Обычный файл
@@ -0,0 +1,98 @@
|
||||
// Package notifyrender owns the subject/body templates used by both the
|
||||
// legacy sender (internal/sender) and the worker-driven notification
|
||||
// producer (internal/notifier). It is a leaf package so the notifier package
|
||||
// can pre-render notification content for the worker without importing the
|
||||
// sender package, which would otherwise create an import cycle (sender's
|
||||
// tests already import notifier to drive the legacy loop).
|
||||
package notifyrender
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/russross/blackfriday/v2"
|
||||
|
||||
"rsgit.ru/rsmon/rsmon/app/models"
|
||||
)
|
||||
|
||||
const (
|
||||
stateDown = "down"
|
||||
stateUp = "up"
|
||||
stateTest = "test"
|
||||
stateExp = "exp"
|
||||
)
|
||||
|
||||
// GetContent pre-renders subject + bodies for one Message using the same
|
||||
// templates the legacy sender used to apply at delivery time. The result is
|
||||
// what the worker binary consumes directly so it does not need access to
|
||||
// Message/Event rows, workdays, or NotificationDayStart logic on the data plane.
|
||||
//
|
||||
// Returns the four bodies (subject, text, markdown, html). The caller is
|
||||
// responsible for passing them through to the worker task payload.
|
||||
func GetContent(message *models.Message, tn time.Time) (bytes.Buffer, bytes.Buffer, bytes.Buffer, bytes.Buffer) {
|
||||
var subject, textBody, markdownBody, htmlBody bytes.Buffer
|
||||
|
||||
if message.Kind == stateTest {
|
||||
subject.WriteString("тестовое сообщение от rsmon.ru")
|
||||
textBody.WriteString("тестовое сообщение от rsmon.ru")
|
||||
markdownBody.WriteString("#### тестовое сообщение от rsmon.ru")
|
||||
htmlBody.WriteString("<h4>тестовое сообщение от rsmon.ru</h4>")
|
||||
|
||||
return subject, textBody, markdownBody, htmlBody
|
||||
}
|
||||
|
||||
if message.Kind == stateExp {
|
||||
if len(message.Events) > 0 {
|
||||
panic("exp message with events")
|
||||
}
|
||||
if message.Check == nil {
|
||||
panic("exp message with no check")
|
||||
}
|
||||
return TextExpires(message.Check)
|
||||
}
|
||||
|
||||
if message.Check != nil {
|
||||
panic("up/down message with check")
|
||||
}
|
||||
|
||||
if len(message.Events) == 1 {
|
||||
event := message.Events[0]
|
||||
switch message.Kind {
|
||||
case stateDown:
|
||||
return TextDownOne(&event)
|
||||
case stateUp:
|
||||
return TextUpOne(&event)
|
||||
default:
|
||||
panic("bad message kind " + message.Kind)
|
||||
}
|
||||
}
|
||||
switch message.Kind {
|
||||
case stateDown:
|
||||
subject.WriteString(GetDownMany(len(message.Events)))
|
||||
case stateUp:
|
||||
subject.WriteString(GetUpMany(len(message.Events)))
|
||||
default:
|
||||
panic("bad message kind" + message.Kind)
|
||||
}
|
||||
names := []string{}
|
||||
for _, evt := range message.Events { //nolint:gocritic // range copy is acceptable here
|
||||
names = append(names, evt.Monitor.GetLabel())
|
||||
}
|
||||
subject.WriteString(": ")
|
||||
subject.WriteString(strings.Join(names, ", "))
|
||||
|
||||
asciiTable, markdownTable := RenderEventsTable(message, tn)
|
||||
|
||||
textBody.WriteString(subject.String() + "\n")
|
||||
textBody.WriteString(asciiTable)
|
||||
|
||||
markdownBody.WriteString("###### " + subject.String() + "\n\n")
|
||||
markdownBody.WriteString(markdownTable)
|
||||
|
||||
htmlTable := blackfriday.Run([]byte(markdownTable))
|
||||
htmlBody.WriteString("<h4>Изменения статусов по мониторам:</h4>")
|
||||
htmlBody.Write(htmlTable)
|
||||
|
||||
return subject, textBody, markdownBody, htmlBody
|
||||
}
|
||||
53
internal/notifyrender/text_down_one.go
Обычный файл
53
internal/notifyrender/text_down_one.go
Обычный файл
@@ -0,0 +1,53 @@
|
||||
package notifyrender
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"html/template"
|
||||
|
||||
"rsgit.ru/rsmon/rsmon/app/models"
|
||||
)
|
||||
|
||||
var (
|
||||
// DownOneSubject provides functionality.
|
||||
DownOneSubject *template.Template
|
||||
// DownOneBody provides functionality.
|
||||
DownOneBody *template.Template
|
||||
// DownOneHTML provides functionality.
|
||||
DownOneHTML *template.Template
|
||||
)
|
||||
|
||||
func init() {
|
||||
DownOneSubject = template.Must(template.New("down_one_subject").Parse(`Не доступен {{.Monitor.GetLabel}}`))
|
||||
// DownOneBody provides functionality.
|
||||
DownOneBody = template.Must(template.New("down_one_body").Parse(`Монитор {{.Monitor.GetLabel}} не доступен :warning:
|
||||
|
||||
Проверки: {{.ChecksDown}}.
|
||||
Ошибка: {{.Reason}}
|
||||
|
||||
Начало события: {{.StartTime.Format "02.01.2006 15:04:05"}}
|
||||
|
||||
Недоступные проверки:
|
||||
{{range .Checks}}
|
||||
{{.Kind}} - {{if .Name}}{{.Name}}{{else}}Нет имени{{end}} - {{if .URL}}{{.URL}}{{else}}URL не указан{{end}} {{if .Error}}({{.Error}}){{end}}
|
||||
{{end}}`))
|
||||
|
||||
DownOneHTML = template.Must(template.New("down_one_html").Parse(`<h4>Монитор {{.Monitor.GetLabel}} не доступен</h4>
|
||||
|
||||
Проверки: {{.ChecksDown}}.
|
||||
<h5 style='background-color: red;'>Ошибка:</h5>
|
||||
{{.Reason}}
|
||||
|
||||
<div>Начало события: {{.StartTime.Format "02.01.2006 15:04:05"}}</div>
|
||||
|
||||
<h5>Недоступные проверки:<h5>
|
||||
{{range .Checks}}
|
||||
<div>
|
||||
{{.Kind}} - {{if .Name}}{{.Name}}{{else}}Нет имени{{end}} - {{if .URL}}{{.URL}}{{else}}URL не указан{{end}} {{if .Error}}({{.Error}}){{end}}
|
||||
</div>
|
||||
{{end}}`))
|
||||
}
|
||||
|
||||
// TextDownOne provides functionality.
|
||||
func TextDownOne(event *models.Event) (bytes.Buffer, bytes.Buffer, bytes.Buffer, bytes.Buffer) {
|
||||
return executeTemplates(event, DownOneSubject, DownOneBody, DownOneHTML, " :warning:")
|
||||
}
|
||||
48
internal/notifyrender/text_expires.go
Обычный файл
48
internal/notifyrender/text_expires.go
Обычный файл
@@ -0,0 +1,48 @@
|
||||
package notifyrender
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"html/template"
|
||||
|
||||
"rsgit.ru/rsmon/rsmon/app/models"
|
||||
)
|
||||
|
||||
var (
|
||||
// ExpSubject provides functionality.
|
||||
ExpSubject *template.Template
|
||||
// ExpBody provides functionality.
|
||||
ExpBody *template.Template
|
||||
// ExpHTML provides functionality.
|
||||
ExpHTML *template.Template
|
||||
)
|
||||
|
||||
func init() {
|
||||
ExpSubject = template.Must(template.New("exp_subject").Parse(`Скоро истекает {{.GetLabel}} ({{.KindLabel}}) по {{.Monitor.GetLabel}}`))
|
||||
// ExpBody provides functionality.
|
||||
ExpBody = template.Must(template.New("exp_body").Parse(`Монитор {{.Monitor.GetLabel}}
|
||||
{{.Expires.Format "02.01.2006 15:04:05"}} истекает {{.GetLabel}} ({{.KindLabel}})
|
||||
`))
|
||||
ExpHTML = template.Must(template.New("exp_html").Parse(`Монитор {{.Monitor.GetLabel}}
|
||||
{{.Expires.Format "02.01.2006 15:04:05"}} истекает {{.GetLabel}} <strong>({{.KindLabel}})</strong>
|
||||
`))
|
||||
}
|
||||
|
||||
// TextExpires provides functionality.
|
||||
func TextExpires(check *models.Check) (bytes.Buffer, bytes.Buffer, bytes.Buffer, bytes.Buffer) {
|
||||
var err error
|
||||
var subject, textBody, htmlBody bytes.Buffer
|
||||
|
||||
err = ExpSubject.Execute(&subject, check)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
err = ExpBody.Execute(&textBody, check)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
err = ExpHTML.Execute(&htmlBody, check)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return subject, textBody, textBody, htmlBody
|
||||
}
|
||||
76
internal/notifyrender/text_up_one.go
Обычный файл
76
internal/notifyrender/text_up_one.go
Обычный файл
@@ -0,0 +1,76 @@
|
||||
package notifyrender
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"html/template"
|
||||
"strings"
|
||||
|
||||
"rsgit.ru/rsmon/rsmon/app/models"
|
||||
)
|
||||
|
||||
var (
|
||||
// UpOneSubject provides functionality.
|
||||
UpOneSubject *template.Template
|
||||
// UpOneBody provides functionality.
|
||||
UpOneBody *template.Template
|
||||
// UpOneHTML provides functionality.
|
||||
UpOneHTML *template.Template
|
||||
)
|
||||
|
||||
func init() {
|
||||
UpOneSubject = template.Must(template.New("up_one_subject").Parse(`Снова доступен {{.Monitor.GetLabel}}`))
|
||||
// UpOneBody provides functionality.
|
||||
UpOneBody = template.Must(template.New("up_one_body").Parse(`Монитор {{.Monitor.GetLabel}} снова доступен :white_check_mark:
|
||||
|
||||
Проверки:
|
||||
{{range .Checks}}
|
||||
{{.Kind}} - {{if .Name}}{{.Name}}{{else}}Нет имени{{end}} - {{if .URL}}{{.URL}}{{else}}URL не указан{{end}} {{if .Error}}({{.Error}}){{end}}
|
||||
{{end}}
|
||||
|
||||
Он был недоступен {{.FormatDuration}} по причине ошибки {{.Reason}}
|
||||
|
||||
{{if .StartTime}}Начало события: {{.StartTime.Format "02.01.2006 15:04:05"}}{{end}}
|
||||
{{if .EndTime}}Окончание события: {{.EndTime.Format "02.01.2006 15:04:05"}}{{end}}
|
||||
`))
|
||||
UpOneHTML = template.Must(template.New("up_one_html").Parse(`<h4>Монитор {{.Monitor.GetLabel}} снова доступен</h4>.
|
||||
|
||||
<h5>Проверки:<h5>
|
||||
{{range .Checks}}
|
||||
<div>
|
||||
{{.Kind}} - {{if .Name}}{{.Name}}{{else}}Нет имени{{end}} - {{if .URL}}{{.URL}}{{else}}URL не указан{{end}} {{if .Error}}({{.Error}}){{end}}
|
||||
</div>
|
||||
{{end}}
|
||||
|
||||
<div>Он был недоступен {{.FormatDuration}} по причине ошибки <code>{{.Reason}}</code></div>
|
||||
|
||||
{{if .StartTime}}<div>Начало события: {{.StartTime.Format "02.01.2006 15:04:05"}}</div>{{end}}
|
||||
{{if .EndTime}}<div>Окончание события: {{.EndTime.Format "02.01.2006 15:04:05"}}</div>{{end}}
|
||||
`))
|
||||
}
|
||||
|
||||
// executeTemplates is a helper function that executes subject, body, and HTML templates
|
||||
// and removes the specified emoji string from the text body for non-HTML output
|
||||
func executeTemplates(event *models.Event, subject, body, html *template.Template, emojiToRemove string) (bytes.Buffer, bytes.Buffer, bytes.Buffer, bytes.Buffer) { //nolint:lll
|
||||
var err error
|
||||
var subjectBuf, textBodyBuf, htmlBodyBuf bytes.Buffer
|
||||
|
||||
err = subject.Execute(&subjectBuf, event)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
err = body.Execute(&textBodyBuf, event)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
err = html.Execute(&htmlBodyBuf, event)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
txt := bytes.NewBufferString(strings.ReplaceAll(textBodyBuf.String(), emojiToRemove, ""))
|
||||
return subjectBuf, *txt, textBodyBuf, htmlBodyBuf
|
||||
}
|
||||
|
||||
// TextUpOne provides functionality.
|
||||
func TextUpOne(event *models.Event) (bytes.Buffer, bytes.Buffer, bytes.Buffer, bytes.Buffer) {
|
||||
return executeTemplates(event, UpOneSubject, UpOneBody, UpOneHTML, " :white_check_mark:")
|
||||
}
|
||||
Ссылка в новой задаче
Block a user