delivery

package
v0.1.4 Latest Latest
Warning

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

Go to latest
Published: Oct 26, 2026 License: AGPL-3.0 Imports: 35 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 delivery is the delivery engine (C-11, ADR-0005): the Desired state of each Root message per Alert Group and Destination, which the dispatcher's re-render step sets through Enqueue; the delivery worker, which brings the actual message to the latest Desired state with one call per change, Urgent first and within the limiters of the Destination and its Connection; Thread replies with the Thread batching window; the interactive path for calls a person waits for; the delivery events; and the Telegram copy buffer of comment Threads. Only this package writes deliveries, thread_replies, rate_limit_buckets, delivery_events and telegram_post_copies, and only its worker, its Thread replies and its interactive path call the messenger adapters (lint 3).

Index

Constants

View Source
const (
	CodeDNSFailed     = "dns_failed"
	CodeConnectFailed = "connect_failed"
	CodeTLSFailed     = "tls_failed"
	CodeTimeout       = "timeout"
	CodeProxyRefused  = "proxy_refused"
	CodeBlocked       = "blocked"
	CodeRequestFailed = "request_failed"
)

The codes of a request of a Connection or Destination check that failed for a reason its step does not name (ConnectionCheckStep.code, DestinationCheckItem.code): what failed when the request got no answer, an address the outbound address policy refused, and any other failure, such as an error answer, whose text says what answered. Clients translate the code and show the step's English text as its detail where it says more than the code's text.

View Source
const (
	CopyWait          = 60 * time.Second
	PostCopyRetention = 24 * time.Hour
)

The built-in settings of comment Threads (defaults.md): telegram.copy_wait (P-30), and how long a buffered copy is kept before short-lived pruning deletes it.

View Source
const (
	// LearnedFromAutomaticForward is the automatic copy itself (F-005).
	LearnedFromAutomaticForward = "automatic_forward"
	// LearnedFromComment is a person's comment, a reply to the copy (F-007).
	LearnedFromComment = "comment"
)

The ways a copy is learned (telegram_post_copies.learned_from).

View Source
const (
	InteractiveBudget       = 5 * time.Second
	ThreadAlertsListed      = 10
	TransientFirstStep      = 2 * time.Second
	TransientBackoffMax     = 5 * time.Minute
	TransientBudgetAttempts = 10
	TransientBudgetTime     = 30 * time.Minute
	BrokenProbeInterval     = 5 * time.Minute
	StormCalmPeriod         = 5 * time.Minute
	StormWindow             = time.Minute
)

The built-in settings of delivery (defaults.md): delivery.interactive_budget, delivery.thread_alerts_listed, delivery.transient_backoff from its first step up to its longest wait, the attempt and time budgets of delivery.transient_budget, delivery.broken_probe_interval, delivery.storm_calm_period, the minute over which the new Alert Groups of a Route are counted against route.storm_threshold, and the wait before a Thread reply that Telegram refused even without its reply link is attempted again.

View Source
const (
	Lease          = time.Minute
	Batch          = 10
	TokenMargin    = 200 * time.Millisecond
	MaxWait        = 30 * time.Second
	MinWait        = 100 * time.Millisecond
	FailureBackoff = time.Second
	RetentionBatch = 5000
)

The defaults of the worker: the lease of a claimed row, renewed before its call, which it outlasts; the rows one claim takes, few, so that Urgent work that comes due meanwhile waits behind few calls; the margin after the time its tokens are due that a delivery without a token, or after a RetryAfter, waits, so that the interactive path takes the next token first; the longest wait between rounds, which bounds what a missed notification costs; the shortest one; the first wait after a failed round; and the most Thread replies one delete of their retention removes.

View Source
const (
	TypeMattermost = "mattermost"
	TypeTelegram   = "telegram"
	TypeWebhook    = "webhook"
	TypeBridge     = "bridge"
	TypeSlack      = "slack"
)

The Destination types.

View Source
const (
	ClassNone    = "none"
	ClassBlocked = "blocked"
	ClassLimited = "limited"
)

The error classes of a step of a Destination test (DeliveryErrorClass, C-16.FR-2) besides the kinds of outcomes that failed: none for a step that succeeded, blocked for a request the outbound address policy refused, and limited for a step that found no limiter token within delivery.interactive_budget and sent nothing.

View Source
const (
	CodePressNotReached = "press_not_reached"
	CodeBotUnknown      = "bot_unknown"
)

The error codes of a step (TestStep.error_code), where its error class does not tell what failed: the bot's press of a Mattermost test message that did not reach Muster's callback, and the press a bot that no check has learned yet does not make.

View Source
const (
	DeliveryAddedDestination   = "publication_into_added_destination"
	DeliveryStormSummary       = "storm_summary_first_publication"
	DeliveryStormUpdate        = "storm_summary_update"
	DeliveryAfterStorm         = "gradual_publication_after_storm"
	DeliveryLate               = "delivered_late"
	DeliveryAfterRecovery      = "publication_after_recovery"
	DeliveryUpdateRecovery     = "update_after_recovery"
	DeliveryRepliesWhileBroken = "thread_replies_while_broken"
	DeliveryResolvedBroken     = "resolved_while_broken"
	DeliveryRepublication      = "republication_after_deletion"
	DeliveryFinalEdit          = "final_edit"
	DeliveryPastEditWindow     = "republication_past_edit_window"
)

The names of the rows of DeliveryEvents.

View Source
const Channel = "muster_delivery"

Channel is the LISTEN/NOTIFY channel that wakes the delivery workers of every replica when a Desired state changes or a Thread reply is queued.

View Source
const EditWindowMargin = time.Minute

EditWindowMargin is bridge.edit_window_margin: a Root message is past its bridge's edit window this long before edit_max_age_seconds.

View Source
const MaxResponseBody = 4 << 10

MaxResponseBody is how much of a response a test result shows: its first 4 KB.

View Source
const MessageProxyRefused = "The proxy refused the connection (407)"

MessageProxyRefused is the text of a request that the proxy refused: 407 to an HTTP CONNECT, or a SOCKS5 proxy that refused the credentials.

View Source
const RerenderBatch = 50

RerenderBatch is how many Alert Groups one batch of the re-render after a key rotation lists.

View Source
const StateWaitingForBroken = "waiting_for_broken_destination"

StateWaitingForBroken is the delivery state the API shows for a pending delivery whose Destination is Broken; it is derived, never stored (schema.md §4.11).

View Source
const TelegramPressEditDelay = 500 * time.Millisecond

TelegramPressEditDelay is telegram.press_edit_delay (P-51): an edit of a Telegram Root message that comes due while an update of its Connection is being handled — a press not answered yet — is tried again this much later, instead of waiting for the press, so that a slow press never holds the worker and its answer still goes out before the edit (C-14.FR-5, AC-18). The wait is not an attempt, records no error and takes no limiter token.

View Source
const TimerStormCalmCheck = "storm_calm_check"

TimerStormCalmCheck is the timers kind of the calm check of a Storm.

View Source
const VariantSystem groups.Variant = "system"

VariantSystem is resolved by the system (C-09.FR-22), whose row differs from a person's Resolve (C-10.FR-15, the variant groups.VariantCommand); the groups package records both as one event.

Variables

DeliveryEvents is the closed Loud/Quiet table of delivery events (C-11.FR-20, reference.md): every message delivery sends of its own, or decides not to send, reads its loudness and Mentions here.

View Source
var ErrBadCopy = errors.New("the copy names no channel post or no message")

ErrBadCopy is a copy that names no channel post, no discussion group or no message: it can never be learned.

View Source
var ErrButtonKeyNotActive = errors.New("the buttons are not signed with the active key")

ErrButtonKeyNotActive is the re-render's error when the renderer signed the buttons with another key than the active key it was given: this replica's Keyring has not switched to that key, or switched away from it meanwhile.

View Source
var ErrNotBound = errors.New("the post is not a message of the alert group")

ErrNotBound is a button press whose post is not the Root message, or a Reminder, of the Alert Group in a Destination of the Connection.

View Source
var ErrNotFound = errors.New("no such alert group")

ErrNotFound is an Alert Group that does not exist in the Organization.

Outcomes are every outcome an adapter may answer with.

View Source
var Table = []Row{
	{groups.EventCreated, groups.VariantAny, FormPublication, groups.Loud, []groups.Mention{groups.MentionNewAlertGroup},
		false},
	{groups.EventAlertsAdded, groups.VariantFiring, FormReply, groups.Loud, []groups.Mention{groups.MentionNewAlerts},
		false},
	{groups.EventAlertsAdded, groups.VariantAcknowledged, FormReplyAndUpdate, groups.Quiet, nil, false},
	{groups.EventAlertsAdded, groups.VariantSnoozed, FormUpdate, groups.Quiet, nil, false},
	{groups.EventAlertReplaced, groups.VariantAny, FormReply, groups.Quiet, nil, false},
	{groups.EventAlertResolved, groups.VariantAny, FormUpdate, groups.Quiet, nil, false},
	{groups.EventAlertContinued, groups.VariantAny, FormUpdate, groups.Quiet, nil, false},
	{groups.EventAnnotationsChanged, groups.VariantAny, FormUpdate, groups.Quiet, nil, false},
	{groups.EventSeverityRaised, groups.VariantAny, FormUpdate, groups.Quiet, nil, false},
	{groups.EventUrgencyRaised, groups.VariantRemoves, FormReply, groups.Loud,
		[]groups.Mention{groups.MentionOwner, groups.MentionRiseToUrgent}, false},
	{groups.EventUrgencyRaised, groups.VariantRemovesNone, FormUpdate, groups.Quiet, nil, false},
	{groups.EventReopened, groups.VariantFiring, FormReply, groups.Loud, []groups.Mention{groups.MentionReopen}, false},
	{groups.EventReopened, groups.VariantAcknowledged, FormReply, groups.Loud, []groups.Mention{groups.MentionOwner},
		false},
	{groups.EventReopened, groups.VariantSnoozed, FormUpdate, groups.Quiet, nil, false},
	{groups.EventSnoozeEnded, groups.VariantAny, FormReply, groups.Loud, []groups.Mention{groups.MentionSnoozeEnded},
		false},
	{groups.EventResolved, VariantSystem, FormReplyAndUpdate, groups.Quiet, nil, false},
	{groups.EventMovedToDefaultRoute, groups.VariantAny, FormUpdate, groups.Quiet, nil, false},
	{groups.EventUnacknowledged, groups.VariantOwnerReleased, FormReplyAndUpdate, groups.Loud, nil, false},
	{groups.EventAcknowledged, groups.VariantAny, FormUpdate, groups.Quiet, nil, false},
	{groups.EventTakeover, groups.VariantAny, FormReply, groups.Loud, []groups.Mention{groups.MentionPreviousOwner},
		false},
	{groups.EventUnacknowledged, groups.VariantCommand, FormUpdate, groups.Quiet, nil, false},
	{groups.EventResolved, groups.VariantCommand, FormUpdate, groups.Quiet, nil, false},
	{groups.EventUnresolved, groups.VariantAny, FormUpdate, groups.Quiet, nil, false},
	{groups.EventSnoozed, groups.VariantAny, FormUpdate, groups.Quiet, nil, false},
	{groups.EventUnsnoozed, groups.VariantAny, FormUpdate, groups.Quiet, nil, false},
	{groups.EventNoteAdded, groups.VariantAny, FormNothing, groups.Quiet, nil, false},
	{groups.EventAckTimeout, groups.VariantAny, FormReply, groups.Loud, []groups.Mention{groups.MentionAckTimeout},
		false},
	{groups.EventUnclaimed, groups.VariantAny, FormUpdate, groups.Quiet, nil, false},
	{groups.EventReminder, groups.VariantAny, FormReply, groups.Loud, []groups.Mention{groups.MentionOwner}, false},
	{groups.EventReminderAnswered, groups.VariantAny, FormNothing, groups.Quiet, nil, false},
	{groups.EventAutoUnacknowledged, groups.VariantAny, FormReply, groups.Loud,
		[]groups.Mention{groups.MentionOwner}, false},
	{groups.EventNoticesMissed, groups.VariantAny, FormReply, groups.Loud, nil, true},
}

Table is the closed table of the lifecycle events of C-09.FR-22, C-10.FR-15 and C-17.FR-11 that delivery turns into messages (C-11.FR-20), keyed by event and variant: an event whose rows differ by actor or reason has a row per variant. moved_to_default_route changes the Destinations of the Alert Group (C-09.FR-19): the final edit in those it leaves, a Quiet Publication in those it joins, an update in those of both.

Functions

func ErrorClass

func ErrorClass(k OutcomeKind) string

ErrorClass is the error class of a step that ended with an outcome of kind k: none when it succeeded; retry_after, transient, fatal, unknown and template_error as they are; anything else, which a test does not expect, unknown.

func FailureCode

func FailureCode(blocked bool, network string) string

FailureCode is the check code of a failed request: CodeBlocked when the outbound address policy refused its address, the code of what failed (outbound.Network*) when it got no answer, and CodeRequestFailed otherwise.

func FailureMessage

func FailureMessage(network, address, detail string, timeout time.Duration) (message string, ok bool)

FailureMessage is the English text of a request of a check that got no answer, by what failed (outbound.Network*): the host of address, the URL it was sent to, that did not resolve; the TLS failure detail; the timeout of the request; or MessageProxyRefused. ok is false for any other failure, for a TLS failure without its detail, and for a DNS failure without an address, whose own error texts say more: a request through a proxy passes no address, since Muster leaves the name of its URL to the proxy, so the name that did not resolve is the proxy's.

func RecordEvent

func RecordEvent(ctx context.Context, q queries, orgID int64, e Event) error

RecordEvent writes one delivery event through q, in the transaction of what it records. Only delivery writes delivery events, never into the Alert Group tables; the Timeline of an Alert Group merges them in by time.

func ResponseText

func ResponseText(body []byte, mask func(string) string) *string

ResponseText is the start of a response body as a test shows it: masked by mask first, so that a secret cut at the end cannot show in part, then at most MaxResponseBody bytes, cut on a rune boundary, with invalid UTF-8 replaced; nil for an empty body.

Types

type Adapter

type Adapter interface {
	Publish(ctx context.Context, c Call, m Message) Outcome
	Update(ctx context.Context, c Call, messageID string, m Message) Outcome
	Reply(ctx context.Context, c Call, root Root, m Message) Outcome
	LengthLimit() int
}

Adapter is what a Destination type implements, declared here by its consumer (ADR-0016). Publish sends a new Root message, Update edits one, Reply sends into its Thread; LengthLimit is the longest text the messenger takes. Lint 3 allows these calls only in worker.go, threads.go and interactive.go.

type Adapters

type Adapters map[string]Adapter

Adapters are the adapters by Destination type, wired in the runtime.

type Binding

type Binding struct {
	Destination   Destination
	ChannelID     string
	RootMessageID string
	Language      string
	SnoozeSeconds []int64
	// AlertGroup is the internal id of the bound delivery's Alert Group, for the Request log (C-23.FR-2); 0 where the
	// binding does not read it.
	AlertGroup int64
}

Binding is what a button press on a Root message or a Reminder is bound to (C-13.FR-4): the Destination the message was delivered to, its channel, and the language and Snooze durations of the Alert Group's Route. RootMessageID is, for a press on a Reminder in Mattermost, the Root message it replies to, whose Thread the answers go to; empty for a press on a Root message and in Telegram.

type BodyFunc

type BodyFunc func(e EventBody) ([]byte, error)

BodyFunc renders the version 1 body of one event of a change.

type BridgeBinding

type BridgeBinding struct {
	Kind          buttons.Subject
	GroupPublicID string
	Language      string
	SnoozeSeconds []int64
	WeekStart     string
}

BridgeBinding is what a press or a Thread message on a message of a Bridge Connection is bound to (C-22.FR-12, FR-14): the kind of the message — a Root message, buttons.SubjectRoot, or a sent Reminder, buttons.SubjectReply — the Alert Group, by public_id, its Route's language and Snooze durations, and organization.week_start, monday to sunday, which the Snooze presets of Text commands name. An older Root message that a republication past the bridge's edit window replaced (C-22.FR-9) is bound as the current one is: a press or a Text command there acts on the Alert Group as on the current one, and nothing ever edits it again, since the worker reconciles only the current Root message of a delivery.

type Button

type Button = messages.Button

Button is a Command button of a Root message or a Thread reply.

type Call

type Call struct {
	Class       outbound.Class
	Destination Destination
	Loudness    groups.Loudness
	Mentions    []groups.Mention
	Targets     []mentions.Target
	Plain       bool
	Key         string
	// Webhook is what a request of an outgoing webhook in the template mode reads besides the Message, which it does
	// not use; nil for a messenger.
	Webhook *WebhookCall
}

Call is one adapter call: its client class (ADR-0015) — delivery for the worker, interactive for the interactive path — its Destination, and for a new message its loudness, its symbolic Mentions and, for a Loud one, their targets in the Destination (C-12.FR-8), which the adapter renders in its messenger's syntax. An edit is always Quiet and mentions nobody. Plain asks for the same text without markup, after the messenger rejected the markup (C-11.FR-8). Key is the idempotency key of a Publication or a Thread reply to an Idempotent adapter, empty otherwise.

type Checker

type Checker interface {
	Check(ctx context.Context, c Call) Outcome
}

Checker is the Destination check an adapter may offer (C-13.FR-10, C-14.FR-14): whether the bot can still reach and write to its chat, without sending a message. The Broken probe uses it from S-035 on.

type Config

type Config struct {
	OrgID int64
	Store *Store
	// Business is the business clock: due times, windows and the time of delivery events.
	Business clock.Clock
	// Renderer renders Root messages and Storm summaries (C-12).
	Renderer Renderer
	Log      *logging.Logger
	// RunbookBase is MUSTER_RUNBOOK_BASE_URL, the base of the runbook_url of MusterDestinationBroken.
	RunbookBase string
	// Real is the real clock, against which the leases of calls in flight are compared before the secrets of a deleted
	// Destination are wiped; nil is the system's.
	Real clock.Clock
	// Bodies renders the bodies of outgoing webhook events and Mentions resolves their Mentions; without Bodies no
	// event is queued.
	Bodies   EventBodies
	Mentions Mentioner
	// Requests renders the Desired state of outgoing webhooks in the template mode.
	Requests Requests
}

Config is what a Service needs.

type Copy

type Copy struct {
	ConnectionID     int64
	ChannelChatID    int64
	PostID           int64
	DiscussionChatID int64
	CopyID           int64
	LearnedFrom      string
}

Copy is the automatic copy of a channel post, as the update path learns it: the Connection that received it, the channel and the post, the discussion group and the copy's message id there, and how it was learned.

type Destination

type Destination struct {
	ID         int64
	PublicID   string
	Name       string
	Type       string
	Connection *int64
}

Destination is a Destination as delivery calls it: Connection is the internal id of its Connection, nil for an outgoing webhook.

type EditWindowed

type EditWindowed interface {
	EditWindow(ctx context.Context, c Call) (time.Duration, bool)
	PointerKey(d Destination, deliveryID, publication int64) string
	FinalKey(d Destination, deliveryID int64) string
}

EditWindowed is an Adapter whose messenger edits a Root message only for a while after its Publication (C-22.FR-9); *bridge.Adapter implements it. EditWindow is that while for the Destination of c, read outside any transaction from the info of its Connection, again past bridge.info_max_age; ok is false when edits never expire or the info cannot be read, and the messenger's own refusal of an edit then marks the Root message past its window. PointerKey is the idempotency key of the Thread reply that points from Root message number publication of the delivery deliveryID to the one that replaced it; FinalKey that of a final edit sent as a Thread reply.

type Event

type Event struct {
	At            time.Time
	DestinationID int64
	AlertGroupID  *int64
	StormID       *int64
	Kind          EventKind
	Loudness      groups.Loudness
	Mentions      []groups.Mention
	ErrorClass    string
	Error         outbound.Untrusted
	Detail        map[string]any
}

Event is one delivery event: when it happened, its Destination and, when it concerns one, its Alert Group or the Storm of a Storm summary; its loudness and symbolic Mentions; for a failure its error class and the provider's masked error text; and details.

type EventBodies

type EventBodies interface {
	EventBodies(ctx context.Context, tx groups.DBTX, in EventSource) (BodyFunc, error)
}

EventBodies reads, through the transaction of a change, what the bodies of its events carry and returns the function that renders each (C-15.FR-2), declared here by its consumer; *webhooks.Service implements it.

type EventBody

type EventBody struct {
	Event      groups.Recorded
	Notify     bool
	Mentions   []mentions.Target
	OccurredAt time.Time
}

EventBody is one lifecycle event of a change for one events-mode Destination: the event, whether it is Loud, its Mentions in that Destination and when it happened.

type EventCall

type EventCall struct {
	Class       outbound.Class
	Destination Destination
	WebhookID   string
	Body        []byte
}

EventCall is one events-mode request of an outgoing webhook (C-15.FR-2): its client class, its Destination, the webhook-id of its event, kept across retries, and the body rendered when the event was queued.

type EventKind

type EventKind string

EventKind is the kind of a delivery event (C-11.FR-21, DeliveryEventKind): what happened while delivering to a Destination. Delivery events are not lifecycle events: they reach neither messengers nor outgoing webhook events.

const (
	EventPublication          EventKind = "publication"
	EventPossibleDuplicate    EventKind = "possible_duplicate"
	EventNotDelivered         EventKind = "not_delivered"
	EventDeliveredLate        EventKind = "delivered_late"
	EventDeletedInMessenger   EventKind = "deleted_in_messenger"
	EventRepublished          EventKind = "republished"
	EventThreadNotAttached    EventKind = "thread_not_attached"
	EventMarkupRejected       EventKind = "markup_rejected"
	EventDestinationBroken    EventKind = "destination_broken"
	EventDestinationRecovered EventKind = "destination_recovered"
	EventStormSummary         EventKind = "storm_summary"
	EventFinalEdit            EventKind = "final_edit"
	// EventRepublishedPastEditWindow is a Bridge Root message past its edit window published again on a change of
	// status (C-22.FR-9).
	EventRepublishedPastEditWindow EventKind = "republished_past_edit_window"
)

The kinds of delivery events; S-042 records EventThreadNotAttached, delivery the others.

type EventRow

type EventRow struct {
	Name           string
	Form           Form
	Loudness       groups.Loudness
	Mentions       []groups.Mention
	LoudWhenFiring bool
}

EventRow is a row of the Loud/Quiet table of delivery events (reference.md, Loud and Quiet): what delivery itself sends to one Destination, apart from the lifecycle events — a new message, an edit, or nothing — with its loudness and symbolic Mentions. LoudWhenFiring is the row that is Loud only for an Alert Group firing at that moment.

type EventSender

type EventSender interface {
	SendEvent(ctx context.Context, c EventCall) Outcome
}

EventSender sends the events-mode requests of outgoing webhooks (C-15.FR-2, FR-6), declared here by its consumer; *webhooks.Adapter implements it. Only the worker's events path and the Broken probe call it.

type EventSource

type EventSource struct {
	Group         *groups.Group
	RoutePublicID string
	RouteName     string
	Actor         groups.Actor
}

EventSource is a change of an Alert Group as the bodies of its events carry it: the Alert Group after the change, its Route and the actor of the change.

type Form

type Form string

Form is how a lifecycle event appears in a messenger (the last column of the lifecycle event tables): a new Root message, an update of it, a Thread reply, both, or nothing. The Root message follows its Desired state whatever the form; a Loud event is always a new message, and an edit is always Quiet (C-11.FR-7).

const (
	FormPublication    Form = "publication"
	FormUpdate         Form = "update"
	FormReply          Form = "reply"
	FormReplyAndUpdate Form = "reply_and_update"
	FormNothing        Form = "nothing"
)

The messenger forms of the lifecycle events.

type GroupView

type GroupView struct {
	ID       int64
	PublicID string
	Number   int64
	Title    string
	Status   groups.Status
	Urgent   bool
}

GroupView is an Alert Group as delivery renders it.

type Idempotent

type Idempotent interface {
	PublicationKey(d Destination, deliveryID, publication int64) string
	ReplyKey(d Destination, replyID int64) string
}

Idempotent is an Adapter whose messenger keeps idempotency keys (C-22.FR-6): its Publications and Thread replies carry the key of their Call, a retry of a started Publication records no possible duplicate before the call, and its outcome records one unless it was Replayed. *bridge.Adapter implements it. PublicationKey is the key of the Publication number publication of the delivery deliveryID, the same for every retry of it; ReplyKey that of the Thread reply replyID.

type Interactive

type Interactive struct {
	OrgID int64
	Store *Store
	// Clocks: the limiters follow the business clock, the budget the real clock.
	Clocks clock.Clocks
	// Budget is delivery.interactive_budget; zero is InteractiveBudget.
	Budget time.Duration
	// Sleep waits for d unless ctx ends first, and reports whether the whole wait passed; nil sleeps on the real
	// clock.
	Sleep func(ctx context.Context, d time.Duration) bool
}

Interactive is the interactive path (C-11.FR-2, ADR-0005): the one way a call that a person waits for — an answer to a button press, an ephemeral or account-linking message, a check or a test started by a person — reaches a messenger. It takes a token from the same limiters as the delivery worker, polling them during its budget, and since a delivery without a token waits TokenMargin past the time its tokens are due, it takes the next token ahead of waiting deliveries. It never queues and never writes deliveries or Thread replies; it calls in the interactive client class. The Broken probe never uses it (S-035).

func (*Interactive) Do

func (i *Interactive) Do(ctx context.Context, s Subject, op Op) (Outcome, error)

Do makes op once a token of s is taken, in the interactive client class. When no token frees within the budget it returns a *LimitedError and calls nothing. A RetryAfter the call answers holds the bucket of its scope, as for the worker. A Subject with NoLimiter calls op at once: it waits for no token, so never past the budget, and holds no bucket.

type LimitedError

type LimitedError struct {
	RetryAfter time.Duration
}

LimitedError is an interactive call that found no limiter token within the budget: nothing was sent, and a token is due after RetryAfter. The API answers it with 503 interactive-budget-exhausted and Retry-After, a Destination test records the error class limited (S-047).

func (*LimitedError) Error

func (e *LimitedError) Error() string

func (*LimitedError) Seconds

func (e *LimitedError) Seconds() int

Seconds is the wait in whole seconds, rounded up, at least 1, for Retry-After.

type Mentioner

type Mentioner interface {
	Resolve(ctx context.Context, db mentions.DBTX, org int64, r mentions.Request) ([]mentions.Target, error)
}

Mentioner resolves the symbolic Mentions of a Loud message into the targets of its Destination (C-12.FR-8), reading through the transaction of the call's preparation; declared by its consumer, *mentions.Service implements it.

type Message

type Message = messages.Message

Message is a rendered message, neutral of any markup (C-12.FR-1): each adapter lays it out for its messenger and escapes its neutral text (ADR-0005, output safety).

type MessageRenderer

type MessageRenderer struct {
	*messages.Renderer
}

MessageRenderer is the Renderer of messages.Renderer: a Root message is rendered once per markup and the template error state of its Route settled in the same transaction (C-12.FR-6).

func (MessageRenderer) Reply

Reply renders a Thread reply of g.

func (MessageRenderer) Roots

func (r MessageRenderer) Roots(ctx context.Context, db messages.DBTX, g GroupView, markups []messages.Markup) (Roots,
	error)

Roots renders the Root message of g in each markup.

type Op

type Op interface {
	// contains filtered or unexported methods
}

Op is one interactive call. A send or an edit is an adapter call made here, in interactive.go, so that lint 3 allows it nowhere else: PublishOp, UpdateOp and ReplyOp. CheckOp is an adapter's Destination check, and ReadOp a read that changes no message, such as a Connection check or a channel list, whose answer its function keeps. AnswerOp answers a press privately and DirectOp is a bot's message to one person; neither touches a Root message or a Thread reply.

func AnswerOp

func AnswerOp(send func(ctx context.Context, c Call) Outcome) Op

AnswerOp is an answer to the person who pressed a button or wrote a Text command, such as a Mattermost ephemeral post, Telegram's answerCallbackQuery, a bridge's answerEvent, or Slack's chat.postEphemeral and the ephemeral answer to a press's response_url (C-11.FR-2, C-22.FR-13, C-24.FR-11): it changes no Root message and no Thread reply, even where the messenger shows it in the Thread, and send is the adapter's or the client's own call.

func CheckOp

func CheckOp(ch Checker) Op

CheckOp is the Destination check of an adapter (C-13.FR-10, C-14.FR-14).

func DirectOp

func DirectOp(send func(ctx context.Context, c Call) Outcome) Op

DirectOp is a bot's message to one person in a private or direct chat, such as the reply to a Telegram `/start` or the Mattermost direct message with an Account link code (C-18.FR-11): it changes no Root message and no Thread reply, and send is the messenger client's own call.

func PublishOp

func PublishOp(a Adapter, m Message) Op

PublishOp sends m as a new message through a.

func ReadOp

func ReadOp(read func(ctx context.Context, c Call) Outcome) Op

ReadOp is a read that sends and edits nothing; a messenger send or edit inside read is still refused by lint 3.

func ReplyOp

func ReplyOp(a Adapter, root Root, m Message) Op

ReplyOp sends m into the Thread of root through a.

func TestOp

func TestOp(send func(ctx context.Context, c Call) Outcome) Op

TestOp is a request of a Destination test other than the test message, which is a PublishOp (C-16.FR-1, FR-3): the test event or the "create" request of an outgoing webhook, or the bot's own press of a Mattermost test message. It changes no Root message and no Thread reply.

func UpdateOp

func UpdateOp(a Adapter, messageID string, m Message) Op

UpdateOp edits the message messageID to m through a.

func WebhookOp

func WebhookOp(op Op, w *WebhookCall) Op

WebhookOp is op with what a request of an outgoing webhook in the template mode reads in its call (C-15.FR-3).

type Outcome

type Outcome struct {
	Kind         OutcomeKind
	MessageID    string
	MessageURL   string
	RetryAfter   time.Duration
	Scope        Scope
	Error        outbound.Untrusted
	Status       int
	Values       map[string]string
	Missing      []string
	ThreadOpened bool
	Rendered     bool
	Request      string
	ThreadRef    string
	Replayed     bool
	Unanswered   bool
}

Outcome is what an adapter call ended with. An ok Publication or Thread reply names its message; a RetryAfter the exact delay and its scope; a failure carries the provider's error text, masked of secrets and untrusted. Status is the HTTP status of the answer, or the error_code a Telegram answer reports, 0 when the outcome carries no status. An outgoing webhook in the template mode also reports the values the extraction rules of its "create" or "open thread" found (Values), by rule name, and the rules that found nothing (Missing); that "open thread" ran (ThreadOpened), whatever the reply after it came to; that its request templates rendered (Rendered), which ends the Destination's template error; and the request it ended with (Request: create, update, open_thread, reply_in_thread or events) (C-15.FR-3, FR-4, FR-7). A bridge's Publication or Thread reply also reports the Thread its answer named (ThreadRef, the `thread_ref` stored for the next reply), whether the answer was the first result of the call's idempotency key (Replayed), and, when the call failed, whether the request may have reached the messenger without its answer — a timeout, or a connection lost after the request was sent (Unanswered) (C-22.FR-6).

type OutcomeKind

type OutcomeKind string

OutcomeKind classifies what an adapter call ended with (C-11.FR-8).

const (
	// OutcomeOK is a message the messenger accepted; "not modified" is ok too.
	OutcomeOK         OutcomeKind = "ok"
	OutcomeRetryAfter OutcomeKind = "retry_after"
	OutcomeTransient  OutcomeKind = "transient"
	OutcomeFatal      OutcomeKind = "fatal"
	// OutcomeUnknown is an answer the adapter cannot classify.
	OutcomeUnknown        OutcomeKind = "unknown"
	OutcomeMarkupRejected OutcomeKind = "markup_rejected"
	// OutcomeGone is a Root message that no longer exists in the messenger.
	OutcomeGone OutcomeKind = "gone"
	// OutcomeThreadLost is a Thread the messenger refuses replies to.
	OutcomeThreadLost OutcomeKind = "thread_lost"
	// OutcomeTemplateError is a request of an outgoing webhook whose template failed: nothing was sent (C-15.FR-7).
	OutcomeTemplateError OutcomeKind = "template_error"
	// OutcomeEditWindowClosed is an edit a bridge refused only because of the Root message's age: `gone` with the
	// reason `edit_window_closed` (C-22.FR-8, FR-9).
	OutcomeEditWindowClosed OutcomeKind = "edit_window_closed"
)

The outcomes of an adapter call; outcomes.go gives each its rule (C-11.FR-8).

type PreviewItem

type PreviewItem struct {
	Name    string
	Format  string
	Text    *string
	Request *TestRequest
}

PreviewItem is one rendered output of a preview (DestinationPreviewItem): a message with its format and text, or a request.

type Ref

type Ref struct {
	PublicID     string
	Name         string
	Type         string
	Health       string
	BrokenSince  *time.Time
	BrokenReason *string
}

Ref names a Destination with its health.

type Renderer

type Renderer interface {
	Roots(ctx context.Context, db messages.DBTX, g GroupView, markups []messages.Markup) (Roots, error)
	Reply(ctx context.Context, db messages.DBTX, r ReplyView, g GroupView) (Message, error)
	Storm(routePublicID, routeName, language string, count, urgent int64) Message
	StormOver(routePublicID, language string, open int64) Message
}

Renderer renders what delivery stores and sends (C-12), declared here by its consumer: Root messages, read through the transaction of the change, Thread replies when the worker sends them, and the Storm summary. MessageRenderer is the one of the runtime.

type ReplyView

type ReplyView struct {
	Event        groups.Event
	Seq          int64
	Fingerprints []string
	Language     string
	Listed       int
	Markup       messages.Markup
	After        func(f func(context.Context))
	Fallback     func(detail string)
}

ReplyView is a Thread reply as the renderer shows it: its lifecycle event, the number of the first event it stands for, the fingerprints of the new Alerts it lists, the language of the Route and how many Alerts it lists at most, with the markup of its Destination. A Route template that fails for it is reported to Fallback, and what to run once the transaction of the render committed is handed to After.

type RequestState

type RequestState struct {
	Language string          `json:"language"`
	Group    *templates.Data `json:"group,omitempty"`
	Storm    *StormState     `json:"storm,omitempty"`
}

RequestState is the Desired state of an outgoing webhook in the template mode (C-15.FR-3): what its request templates read of an Alert Group (Group, alert data as received) or of a Storm summary (Storm, and no Alert Group), and the language of its final edit. Its hash is that of the rendered "update" request (Requests).

type Requests

type Requests interface {
	Desired(ctx context.Context, db dbgen.DBTX, destinationID int64, st RequestState) ([]byte, error)
}

Requests renders the Desired state of an outgoing webhook in the template mode (C-15.FR-3), declared here by its consumer; *webhooks.Adapter implements it. Desired renders, reading the Destination destinationID through db, its "update" request for st, with its Secrets and the values extracted from responses left out, and returns the hash of the request: a change that leaves the request as it was makes no call, as for a messenger whose text did not change. A request that fails to render has a hash of its own for each state, so that the call that fails is made.

type Root

type Root struct {
	MessageID      string
	ThreadAnchorID string
	ChainLastID    string
}

Root is the Root message a Thread reply goes under: its message id and its Thread anchor — in Telegram, the automatic copy in the discussion group while the Thread is attached to it, or the last reply of a Thread that is not attached, neither for the first reply of an unattached chain; for a bridge, the last `thread_ref` its post or a reply returned, empty without one.

type Roots

type Roots struct {
	Messages map[messages.Markup]messages.Rendered
	Failures []messages.Failure
	After    func(ctx context.Context)
	Data     *templates.Data
	Language string
}

Roots are the Root messages of one Alert Group, one per markup of its Destinations, as one render produced them: the Route templates that failed, whose messages are the Fallback template, and what to run once the transaction committed. Data is the Alert Group as the request templates of outgoing webhooks read it, with alert data as received, and Language the language of its Route.

type Row

type Row struct {
	Event         groups.Event
	Variant       groups.Variant
	Form          Form
	Loudness      groups.Loudness
	Mentions      []groups.Mention
	EventMentions bool
}

Row is one row of the lifecycle event tables as delivery reads it: its event and variant, its messenger form, its loudness and its symbolic Mentions. EventMentions takes the Mentions the event carries instead: those of the notices that notices_missed stands for.

type Scope

type Scope string

Scope is what a RetryAfter holds: the Destination, or every Destination of its Connection.

const (
	ScopeDestination Scope = "destination"
	ScopeConnection  Scope = "connection"
)

The scopes of a RetryAfter.

type Service

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

Service is the delivery of an Organization: Enqueue for the dispatcher, the delivery state of Alert Groups, the delivery events, the end of a Broken state, the calm check of Storms, the hooks of Routes and Destinations that change their Destinations, and the Leader tasks of delivery.

func New

func New(cfg Config) *Service

New returns the Service of the Organization in cfg.

func (*Service) AbandonConnection

func (s *Service) AbandonConnection(ctx context.Context, tx dbgen.DBTX, connectionID int64) (func(context.Context),
	error)

AbandonConnection ends, in the transaction tx that deletes the Connection connectionID, the final edits still pending in its deleted Destinations as Not delivered with the error "the Connection was deleted", each with its not_delivered delivery event, drops their pending Thread replies and wipes their secrets (C-11.FR-14). The caller runs the returned function once tx committed: it logs delivery_not_delivered for each delivery it ended. deleteConnection calls it from S-039.

func (*Service) BridgePressBinding

func (s *Service) BridgePressBinding(ctx context.Context, connectionID int64, messageID string) (BridgeBinding,
	error)

BridgePressBinding reads the binding of a press on the message messageID of the Bridge Connection connectionID (C-22.FR-12): the delivery of an Alert Group to a Bridge Destination of the Connection, not deleted, whose current Root message it is, else whose older Root message it is, else a sent Reminder of such a Destination whose message it is; ErrNotBound when there is none, as for a message Muster did not post through the Connection, a test message or a Storm summary.

func (*Service) BridgeThreadBinding

func (s *Service) BridgeThreadBinding(ctx context.Context, connectionID int64, messageID string) (BridgeBinding,
	error)

BridgeThreadBinding reads the binding of a Thread message in the Thread of the message messageID of the Bridge Connection connectionID (C-22.FR-14): the delivery of an Alert Group to a Bridge Destination of the Connection, not deleted, whose current Root message it is, else whose older Root message it is; ErrNotBound when there is none, as for a Thread reply, a message Muster did not post through the Connection, a test message or a Storm summary.

func (*Service) CheckStormCalm

func (s *Service) CheckStormCalm(ctx context.Context, tx dbgen.DBTX, stormID int64) (func(context.Context), error)

CheckStormCalm is the handler of the timers kind storm_calm_check, in the transaction tx of the timer (C-11.FR-6): the count of the last minute last fell to the Route's Storm threshold one minute after the Alert Group one above the threshold was created, its calm_since; once delivery.storm_calm_period passed since then, the Storm ends; until then the check moves to calm_since plus the period, free of its lease. At the end the summaries get their final state, the held Alert Groups still open are published Quietly within the limiters and the resolved ones are withheld; the function it returns logs storm_ended once tx committed. A Storm that ended already changes nothing.

func (*Service) DestinationRenamed

func (s *Service) DestinationRenamed(ctx context.Context, tx dbgen.DBTX, publicID, name string) error

DestinationRenamed is the rename hook of the Destinations, in the transaction tx that renamed the Destination publicID to name: the Internal alerts about it, MusterDestinationBroken among them, take the new name as the same firing.

func (*Service) EndBroken

func (s *Service) EndBroken(ctx context.Context, destinationID int64) error

EndBroken is MarkHealthy in a transaction of its own, for a successful Destination check started by a person (C-13.FR-10): its log line follows the commit.

func (*Service) Enqueue

func (s *Service) Enqueue(ctx context.Context, tx groups.DBTX, r groups.Rendering) error

Enqueue is the re-render step of the dispatcher (C-11.FR-1, FR-20; groups.Rerender), in the dispatcher's transaction tx. It renders the Root message once per markup of the Route's Destinations, reading through tx, and reports each Route template that failed, whose message is the Fallback template, through r.Fallback (C-12.FR-6). For each Destination of the Alert Group's Route that is not deleted it creates the delivery when it is missing and, when what its Root message shows changed, stores it as the next Desired state, due now; the lifecycle events whose form is a Thread reply queue one, new Alerts within the Thread batching window, or drop it while the Destination is Broken, a Storm holds the delivery or it ended. A delivery created by `created` is a Loud Publication unless a Storm of the Route holds it (C-11.FR-6); the first Publication of an Alert Group that resolves is settled by the rules of late Publications and Broken Destinations; an Alert Group moved to the Default route gets the final edit in the Destinations it leaves and a Quiet Publication in those it joins (C-09.FR-19). An outgoing webhook in the events mode has no Root message: each lifecycle event is queued for it as one event (C-15.FR-2), whether it is Broken or a Storm holds the Alert Group. It wakes the delivery workers once tx commits.

It first takes the Route's membership lock shared (ShareRouteMembership), which a change of the Route's Destinations and the deletion of one of them take exclusively, so that an Enqueue and such a change serialize: neither misses a delivery the other creates or retires. The membership lock closes no cycle: grouping holds the Route's row FOR SHARE and takes this lock after it, and a change of the Destinations takes the row before this lock, so it waits for grouping before it takes the lock; a Command or a timer holds only its Alert Group, FOR NO KEY UPDATE, which a change of the Destinations never locks in a mode that waits for it — the foreign-key checks of its deliveries take FOR KEY SHARE; the move to the Default route holds the Route's row and then the Alert Groups, but never this lock, which an Enqueue takes without the row. While it waits nobody waits for a delivery row it holds: an Enqueue locks the deliveries of its Route only after the lock, and a change of the Destinations locks those of its Route only after it. The deliveries and Thread replies it then locks follow the lock order of worker.go.

func (*Service) ExportBroken

func (s *Service) ExportBroken(ctx context.Context) error

ExportBroken sets muster_destination_broken to 1 for each Broken Destination of the Organization that is not deleted and 0 for the healthy ones, as a Leader task; the series of a Destination that is gone is removed. Running it twice sets the same values.

func (*Service) ExportQueue

func (s *Service) ExportQueue(ctx context.Context) error

ExportQueue sets muster_delivery_queue to the pending deliveries and the due Thread replies of each Destination of the Organization that is not deleted, as a Leader task; the series of a Destination that is gone is removed. Counting twice sets the same values.

func (*Service) ExportStorms

func (s *Service) ExportStorms(ctx context.Context) error

ExportStorms sets muster_storm_active to 1 for each Route of the Organization that is not deleted and has an active Storm and 0 for the others, as a Leader task; the series of a Route that is gone is removed. Running it twice sets the same values.

func (*Service) LearnCopy

func (s *Service) LearnCopy(ctx context.Context, c Copy) error

LearnCopy buffers the copy of a channel post, the first one learned winning, and attaches to it, in the same transaction, the Threads of the Alert Groups whose Root message is that post in a Telegram Destination of the Connection with that channel and discussion group, unless that Thread lost this very copy. Then the Thread replies that wait for the copy come due at once. Learning the same copy again changes nothing.

func (*Service) MarkHealthy

func (s *Service) MarkHealthy(ctx context.Context, tx dbgen.DBTX, destinationID int64) (func(context.Context),
	error)

MarkHealthy ends the Broken state of the Destination destinationID after a successful Destination check started by a person (S-039, S-042) or a successful Destination test (S-047), as a successful probe does: in the caller's transaction tx, whose commit the caller follows with the returned function, which logs; with a nil tx in a transaction of its own, logged once committed. A healthy Destination changes nothing.

func (*Service) PostDestination

func (s *Service) PostDestination(ctx context.Context, connectionID int64, postID, channelID string) (Destination,
	bool, error)

PostDestination reads the Mattermost Destination of the Connection connectionID, not deleted, whose channel is channelID and to which a delivery posted postID, and whether there is one: a press that cannot be verified is answered only on such a post.

func (*Service) PressBinding

func (s *Service) PressBinding(ctx context.Context, connectionID int64, groupPublicID, postID string) (Binding,
	error)

PressBinding reads the binding of a press on the post postID of the Connection connectionID that names the Alert Group groupPublicID: the delivery of that Alert Group to a Mattermost Destination of the Connection, not deleted, whose Root message is postID; ErrNotBound when there is none.

func (*Service) ProbeNow

func (s *Service) ProbeNow(ctx context.Context, destinationID int64) error

ProbeNow makes the probe of the Destination destinationID due at once when it is Broken, and wakes the delivery workers, after a person saved it: a configuration that the save fixed, such as the URL of an outgoing webhook, ends the Broken state with the next probe instead of after delivery.broken_probe_interval. A healthy Destination is left as it is.

func (*Service) PrunePostCopies

func (s *Service) PrunePostCopies(ctx context.Context, now time.Time, limit int32) (int64, error)

PrunePostCopies deletes at most limit buffered copies of the Organization received PostCopyRetention before now, for the short_lived_pruning Leader task, and returns how many it deleted. Running it twice deletes nothing more.

func (*Service) PruneReplies

func (s *Service) PruneReplies(ctx context.Context, now time.Time) (int64, error)

PruneReplies deletes, in batches of at most RetentionBatch, the Thread replies of the Organization that are sent, dropped or not delivered and were created retention.alert_details before now (schema.md §6), until a batch comes back short, and returns how many it deleted. Running it twice deletes nothing more.

func (*Service) PruneWebhookEvents

func (s *Service) PruneWebhookEvents(ctx context.Context, now time.Time) (int64, error)

PruneWebhookEvents deletes, in batches of at most RetentionBatch, the outgoing webhook events of the Organization that are delivered or Not delivered and were created retention.alert_details before now (schema.md §6), until a batch comes back short, and returns how many it deleted. It then wipes the secrets of the deleted Destinations whose last call in flight ended without wiping them, because its replica stopped. Running it twice deletes nothing more.

func (*Service) ReminderReached

func (s *Service) ReminderReached(ctx context.Context, db groups.DBTX, groupID, seq int64) (bool, error)

ReminderReached reports whether the Reminder recorded as the lifecycle event seq of the Alert Group groupID reached at least one Destination, read through db, the transaction of the timer (C-17.FR-5, D298): a Thread reply carrying it was sent, or its reminder event was delivered to an events-mode outgoing webhook. It is the groups.ReminderCheck of the runtime.

func (*Service) ReplyBinding

func (s *Service) ReplyBinding(ctx context.Context, connectionID int64, groupPublicID, postID string) (Binding,
	error)

ReplyBinding reads the binding of a press on the post postID of the Connection connectionID that names the Alert Group groupPublicID in a Reminder's action id (C-13.FR-4): a sent Reminder of that Alert Group whose message id is postID, delivered to a Mattermost Destination of the Connection, not deleted; ErrNotBound when there is none.

func (*Service) RerenderOpen

func (s *Service) RerenderOpen(ctx context.Context, activeKeyID string) (int, error)

RerenderOpen is the work of the Leader task rerender_after_rotation (C-20.FR-7, AC-5; ADR-0007, ADR-0011): in batches, it recomputes the Desired state of every delivery of an open Alert Group whose buttons a key other than activeKeyID signed and that has a Root message to edit or still to publish, so that the renderer, whose Keyring has switched to activeKeyID, signs them with it and the delivery worker edits the Root messages within the limiters. It sends the organization hint after each batch that changed a delivery and returns how many it changed.

Each Alert Group is one transaction in the dispatcher's lock order (worker.go): the Alert Group first, FOR NO KEY UPDATE SKIP LOCKED, then its Route's membership lock shared, then its deliveries in the order Enqueue locks them; it never locks a delivery before its Alert Group, and never a Storm. An Alert Group a Command holds is skipped: that Command's own re-render signs with the active key, and a delivery a replica signed with the old key before it switched is selected again by the next run. A delivery a Storm holds is re-rendered and stays held, as Enqueue renders it: the Storm's release publishes the stored Desired state, now signed with the active key. A second run finds nothing to change, and two overlapping Leaders lock each Alert Group in turn.

An Alert Group that fails is left for the next run and the others go on; the errors are joined and returned at the end. The run stops at once when ctx ends, when a list or a hint fails, or with ErrButtonKeyNotActive, which every other Alert Group would meet too.

func (*Service) RetireDestination

func (s *Service) RetireDestination(ctx context.Context, tx dbgen.DBTX, destinationID int64) error

RetireDestination is the deletion hook of the Destinations (C-11.FR-14), in the transaction tx that deleted the Destination destinationID: the open Root messages there get the final edit, its other pending deliveries end without a call — retired when published, withheld otherwise — its pending Thread replies are dropped, its waiting outgoing webhook events end as Not delivered with no final event sent (C-15.FR-12), MusterDestinationBroken about it is resolved, and its secrets are wiped at once when nothing of it is pending and no call of it is in flight. It wakes the delivery workers once tx commits.

func (*Service) RootDeleted

func (s *Service) RootDeleted(ctx context.Context, connectionID int64, messageID string) error

RootDeleted starts at once the deleted Root message flow (C-11.FR-13) for a message_deleted event of the Bridge Connection connectionID (C-22.FR-10) when messageID is the current Root message of a delivery to a Bridge Destination of the Connection, not deleted: the Root message of an open Alert Group is published again, Quietly, with the deletion note, and the delivery workers are woken; the republished one, or one of a resolved Alert Group, marks the pair deleted in the messenger. Any other message — an older Root message a republication past the edit window replaced, a Thread reply, a message of another Connection, or the Root message of a delivery that retires or ended — changes nothing; a retiring delivery learns of the deletion from the gone answer to its final edit. As after a gone answer, it locks the delivery row only, never the Alert Group before it (D307).

func (*Service) RouteDestinationsChanged

func (s *Service) RouteDestinationsChanged(ctx context.Context, tx dbgen.DBTX, routeID int64, added,
	removed []int64) error

RouteDestinationsChanged is the membership hook of the Routes (C-11.FR-14), in the transaction tx of the Route's change, which holds the Route's membership lock: the Destinations added to the Route routeID publish its open Alert Groups Quietly — during a Storm they get its Storm summary and hold the Alert Groups it holds — and those removed give their open Root messages the final edit and retire the summary of an active Storm, with the alert-group hint of each Alert Group whose delivery that retires or withholds. It wakes the delivery workers once tx commits. The Route's active Storm is locked FOR SHARE before any delivery is written (LockActiveStorm), after the membership lock and before the deliveries, as in the lock order of worker.go: a calm check waits until the deliveries this change holds for the Storm are committed, or ends the Storm before this change reads it.

func (*Service) SlackPressBinding

func (s *Service) SlackPressBinding(ctx context.Context, connectionID int64, channelID, ts string) (SlackBinding,
	error)

SlackPressBinding reads the binding of a press on the message ts of the channel channelID of the Slack Connection connectionID (C-24.FR-10): the delivery of an Alert Group to a Slack Destination of the Connection, not deleted, on that channel, whose Root message it is, else a sent Reminder of such a Destination whose message it is; ErrNotBound when there is none, as for a message of another channel, a test message or a Storm summary. A ts names one message within its channel only, so both are read.

func (*Service) SlackTestDestination

func (s *Service) SlackTestDestination(ctx context.Context, connectionID int64, publicID, channelID string) (
	Destination, bool, error)

SlackTestDestination reads the Slack Destination publicID of the Connection connectionID, not deleted, whose channel is channelID, and whether there is one: the Destination whose test message a person pressed (C-24.FR-13).

func (*Service) States

func (s *Service) States(ctx context.Context, publicID string) ([]State, error)

States reads the delivery state of the Alert Group publicID in each of its Destinations, by Destination name.

func (*Service) TelegramPressBinding

func (s *Service) TelegramPressBinding(ctx context.Context, connectionID int64, groupPublicID string, chatID,
	messageID int64) (Binding, error)

TelegramPressBinding reads the binding of a press on the message messageID of the chat chatID of the Telegram Connection connectionID that names the Alert Group groupPublicID (C-14.FR-4): the delivery of that Alert Group to a Telegram Destination of the Connection, not deleted, whose channel is chatID and whose Root message is the channel post messageID; ErrNotBound when there is none. Its ChannelID is the chat id in decimal.

func (*Service) TelegramReplyBinding

func (s *Service) TelegramReplyBinding(ctx context.Context, connectionID int64, groupPublicID string, chatID,
	messageID int64) (Binding, error)

TelegramReplyBinding reads the binding of a press on the message messageID of the chat chatID of the Telegram Connection connectionID that names the Alert Group groupPublicID in a Reminder's data (C-14.FR-4): a sent Reminder of that Alert Group whose message is messageID in the discussion group chatID of a Telegram Destination of the Connection, not deleted; ErrNotBound when there is none. Its ChannelID is the chat id in decimal.

func (*Service) TestDestination

func (s *Service) TestDestination(ctx context.Context, connectionID int64, publicID, channelID string) (Destination,
	bool, error)

TestDestination reads the Mattermost Destination publicID of the Connection connectionID, not deleted, whose channel is channelID, and whether there is one: the Destination whose test message a person pressed, which limits the private answer (C-16.FR-3).

type SlackBinding

type SlackBinding struct {
	Kind          buttons.Subject
	GroupPublicID string
	AlertGroup    int64
	Destination   Destination
	SnoozeSeconds []int64
	RootTS        string
}

SlackBinding is what a press on a message of a Slack Connection is bound to (C-24.FR-10): the kind of the message — a Root message, buttons.SubjectRoot, or a sent Reminder, buttons.SubjectReply — the Alert Group, by public_id and by its internal id for the Request log, the Destination the message was delivered to, its Route's Snooze durations, and for a Reminder the ts of the Root message it replies to, whose Thread the answers go to. It has no language: a Slack press is answered in the profile language of the person who pressed (C-24.FR-11).

type State

type State struct {
	Destination       Ref
	State             string
	ThreadNotAttached bool
	PossibleDuplicate bool
	PastEditWindow    bool
	MessageURL        *string
	Error             *string
	UpdatedAt         time.Time
}

State is the delivery state of an Alert Group in one Destination (C-11.FR-16). PastEditWindow is a pending or delivered Bridge Root message past its edit window (C-22.FR-9).

type Store

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

Store runs the queries of the package over the main pool, alone or in short transactions, and over the transaction of a change of an Alert Group.

func NewStore

func NewStore(b db.Beginner, d dbgen.DBTX) *Store

NewStore is the Store that begins its transactions with b and runs its other queries on d: the main pool for both.

type StormState

type StormState struct {
	Route           string
	AlertGroupCount int64
	UrgentCount     int64
	Final           bool
	URL             string
}

StormState is a Storm summary as the request templates of an outgoing webhook read it (`.Storm`): the name of the Route, the counts of its new Alert Groups and of the Urgent ones, whether it is the final state after the Storm ended, and the link to the Route's Alert Groups in Muster.

type Subject

type Subject struct {
	Destination *Destination
	Connection  *int64
	NoLimiter   bool
}

Subject is what an interactive call is limited by: a Destination with its Connection, or a Connection alone. NoLimiter says explicitly that the call has no limiter, as the check of a draft of a Connection that is not saved (C-13.FR-14); it names neither, and the zero Subject stays an error.

type TestInput

type TestInput struct {
	Destination Destination
	Source      *messages.Source
	Actor       groups.Actor
}

TestInput is one Destination test or preview: the Destination, the Alert Group it renders — a recent one of the Destination's Routes or the built-in example — and who started it.

type TestRequest

type TestRequest struct {
	Method  string
	URL     string
	Headers [][2]string
	Body    *string
}

TestRequest is a request of a test or a preview as it was or would be sent (RenderedRequest), with every Secret, the Signing secret and the tokens masked as [redacted]; Body is nil without one.

type TestStep

type TestStep struct {
	Name           string
	Request        *TestRequest
	ResponseStatus int
	ResponseBody   *string
	Extracted      map[string]string
	Duration       time.Duration
	ErrorClass     string
	Error          string
	ErrorCode      string
}

TestStep is one step of a test (TestStep): its name, the request, the status and the start of the body of the response (0 and nil without one), the values the extraction rules found, how long it took, its error class and, when it failed, what failed, with its error code where the class does not tell it. Every text is masked.

func Step

func Step(name string, out Outcome, err error, d time.Duration) (TestStep, error)

Step is the step name after its call through the interactive path took d: limited, with nothing sent, when no token was free in time — a *LimitedError, or the end of ctx while waiting for one, before any call — otherwise the class and the error of out. Any other error of the path is returned.

func (TestStep) OK

func (s TestStep) OK() bool

OK reports whether the step succeeded.

type WebhookCall

type WebhookCall struct {
	State        []byte
	Response     map[string]string
	ThreadOpened bool
	Event        string
	Final        string
}

WebhookCall is what a request of an outgoing webhook in the template mode reads (C-15.FR-3): the Desired state its templates render (a RequestState), the values extracted from the responses of its "create" and "open thread", whether "open thread" ran, the lifecycle event a Thread reply carries, and the text of the final edit, empty for another call.

type Worker

type Worker struct {
	Store *Store
	// Lease names this replica in lease_owner and carries the clocks: due times and limiters on the business clock,
	// leases and the duration of calls on the real clock.
	Lease db.Lease
	// Organizations lists the Organizations whose deliveries it makes: one in L1.
	Organizations func(ctx context.Context) ([]int64, error)
	Adapters      Adapters
	// Events sends the events-mode requests of outgoing webhooks.
	Events   EventSender
	Renderer Renderer
	// Mentions resolves the Mentions of Loud calls; nil mentions nobody.
	Mentions Mentioner
	Log      *logging.Logger
	// MaxWait bounds the wait between rounds, and Batch the rows one claim takes; zero is the default.
	MaxWait time.Duration
	Batch   int32
	// Wait waits for d or until a wake arrives; nil waits on the real clock.
	Wait func(ctx context.Context, d time.Duration, wake <-chan struct{})
	// Random is uniform in [0, 1) and jitters delivery.transient_backoff; nil is math/rand/v2.
	Random func() float64
	// RunbookBase is MUSTER_RUNBOOK_BASE_URL, the base of the runbook_url of MusterDestinationBroken.
	RunbookBase string
	// PublicURL is MUSTER_PUBLIC_URL, the base of the link to an Alert Group in a final edit.
	PublicURL string
	// Published marks the first Publication of an Alert Group at a time, (*groups.Service).MarkPublished, once the
	// outcome that recorded it committed; nil marks nothing.
	Published func(ctx context.Context, groupID int64, at time.Time) error
	// contains filtered or unexported fields
}

Worker is the delivery worker of one replica (C-11.FR-1, FR-15; schema.md §5): it probes the Broken Destinations that are due, claims the due deliveries of healthy Destinations, Urgent first, and the due Thread replies with FOR UPDATE SKIP LOCKED and a lease, re-reads each in a short transaction, takes the limiter tokens, calls the adapter outside any transaction in the delivery client class, and records the outcome by its rule (outcomes.go) in another short transaction. It is woken by NOTIFY, by the earliest due time and, in development mode, by a move of the development clock.

func (*Worker) Round

func (w *Worker) Round(ctx context.Context) (time.Duration, error)

Round probes every Broken Destination whose probe is due, then attempts every due delivery, then every due Thread reply, then every due head event of an outgoing webhook, of every Organization, claiming Batch at a time, and returns how long until the next one can be claimed, at most MaxWait. A row that fails is logged and attempted again once its lease runs out; the round goes on.

func (*Worker) Run

func (w *Worker) Run(ctx context.Context)

Run delivers until ctx ends: a round, then a wait until the next row can be claimed — its due time on the business clock or the end of its lease on the real clock — between MinWait and MaxWait, or until woken; after a failed round, a backoff.

func (*Worker) Wake

func (w *Worker) Wake()

Wake makes the worker run a round at once: a Desired state changed, a Thread reply was queued, the development clock moved, or the LISTEN is back.

Directories

Path Synopsis
Package deliverytest is the recording test adapter that the tests of C-11 to C-16 deliver to through the adapter interface (C-11, Acceptance): it records every call with its time, Destination, message, loudness and Mentions, and answers from a script — any outcome, after a delay, with a hook that runs once it accepted the call.
Package deliverytest is the recording test adapter that the tests of C-11 to C-16 deliver to through the adapter interface (C-11, Acceptance): it records every call with its time, Destination, message, loudness and Mentions, and answers from a script — any outcome, after a delay, with a hook that runs once it accepted the call.

Jump to

Keyboard shortcuts

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