bridge

package
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Oct 22, 2026 License: AGPL-3.0 Imports: 42 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 bridge is Muster's client of the Bridge protocol (ADR-0017, C-22): requests to `<base>/v1/…` with the Connection's token as a bearer token, through internal/outbound with the Connection's proxy, in the client class of the caller (ADR-0015), with the token registered for redaction; the classification of every answer by the problem's class or the protocol's status mapping (classify.go); `info` with Muster's copy of it (info.go); the Destination check and the dry probe of a check without a token (check.go); the Bridge delivery, which posts, edits and replies to messages as envelopes (delivery.go, envelope.go); the events of the Connections, polled by the Leader or pushed to the ingest listener, handled once per id and answered through answerEvent (events.go, poller.go, push.go, presses.go, commands.go); the Account links by a token sent to the bot or a code sent by direct message (links.go); and the conformance check `muster bridge check`, which runs the protocol against a bridge outside any installation and also deletes its message (conformance.go). The models are generated from api/bridge.yaml into internal/bridge/gen.

Index

Constants

View Source
const (
	StepDryProbe = "dry_probe"

	MessageWrongPrefix = "Wrong path prefix: the server answered 404."
)

The step of the dry probe of a Bridge Connection (C-22.FR-2) and the messages of what answered it.

View Source
const (
	CodeNotBridge        = "not_bridge"
	CodeWrongPrefix      = "wrong_path_prefix"
	CodeUnexpectedStatus = "unexpected_status"
)

The codes of the dry probe that reached no bridge (ConnectionCheckStep.code); a probe without an answer has the code of delivery.FailureCode.

View Source
const (
	ViaDirect = "direct"
	ViaProxy  = "proxy"
)

The paths of a Connection's requests (ConnectionPath).

View Source
const (
	TypePress          = "press"
	TypeThreadMessage  = "thread_message"
	TypeAccountLink    = "account_link"
	TypeMessageDeleted = "message_deleted"
)

The types of the events of the Bridge protocol (C-22.FR-11).

View Source
const (
	EventDeliveryPoll = string(gen.Poll)
	EventDeliveryPush = string(gen.Push)
)

The event delivery modes of a Bridge Connection (connection.bridge.event_delivery).

View Source
const (
	CodeTokenInvalid            = "token_invalid"
	CodeProtocolVersionUnknown  = "protocol_version_unknown"
	CodeProtocolMismatch        = "protocol_mismatch"
	CodeEventDeliveryNotOffered = "event_delivery_not_offered"
)

The check codes of a Bridge Connection check (ConnectionCheckStep.code) that the protocol names.

View Source
const CallbackPath = "/api/v1/callbacks/bridge/"

CallbackPath is the path below MUSTER_INGEST_URL where a bridge in push mode posts the events of a Connection, followed by its public_id (C-22.FR-11).

View Source
const CodeChannelForbidden = "channel_forbidden"

CodeChannelForbidden is the check code of a channel the bridge answered forbidden for: it does not exist, or the bot cannot use it (DestinationCheckItem.code).

View Source
const ConformanceWait = 5 * time.Minute

ConformanceWait is how long the press step waits for a person.

View Source
const DefaultInfoMaxAge = 10 * time.Minute

DefaultInfoMaxAge is bridge.info_max_age: a call that depends on info reads it again first when Muster's copy is older.

View Source
const DefaultPushListen = "127.0.0.1:0"

DefaultPushListen is where the push listener of the conformance check listens unless it is told otherwise.

View Source
const DefaultRetryAfterMax = 15 * time.Minute

DefaultRetryAfterMax is bridge.retry_after_max: a rate_limited answer that asks for a longer wait counts as Transient.

View Source
const EventDedupWindow = 24 * time.Hour

EventDedupWindow is bridge.event_dedup_window: an event id of a Connection is handled once within it, on the business clock.

View Source
const EventMaxAge = time.Hour

EventMaxAge is bridge.event_max_age: a press or a Text command older than this after its occurred_at, by the real clock, is dropped, unanswered, and logged.

View Source
const FormatJSON = "json"

FormatJSON is the format of the preview item of a Bridge Destination: the envelope as JSON.

View Source
const InfoMaxBytes = 64 << 10

InfoMaxBytes is the largest info Muster reads (C-22.FR-2); a larger one does not match the protocol.

View Source
const ItemChannel = "channel"

ItemChannel is the one item of the Destination check of a Bridge Destination (DestinationCheckItem.name): whether the bot can post, edit and reply in the channel.

View Source
const MaxAnswerLength = 500

MaxAnswerLength is the longest text of an answer to an event, in characters (C-22.FR-13).

View Source
const MaxDirectMessageLength = 2000

MaxDirectMessageLength is the longest body of a direct message, in characters (api/bridge.yaml).

View Source
const MaxEventBytes = 64 << 10

MaxEventBytes bounds the body of a pushed event: an event is a few kilobytes at most, a Thread message of 4,000 characters included.

View Source
const MessageChannelForbidden = "The bridge refused the channel."

MessageChannelForbidden is the message of a forbidden answer that carries no text of the bridge's.

View Source
const MessageProxyRefused = delivery.MessageProxyRefused

MessageProxyRefused is the message of a request that the Connection's proxy refused with 407 (D338), as every check says it.

View Source
const MessageTokenInvalid = "The bridge refused the token." //nolint:gosec // G101: a message, not a credential

MessageTokenInvalid is the message of an info the bridge refused with 401.

View Source
const MinBodyLength = 500

MinBodyLength is the protocol's floor of limits.max_body_length, in code points: the body limit when info has none.

View Source
const ParallelEvents = 2

ParallelEvents is bridge.parallel_events: the most Bridge events one process handles at a time, over all its Bridge Connections and both event delivery modes; the others wait for a slot. An event being handled holds a connection of the main pool for its claim while its Command takes one more, as telegram.ParallelUpdates bounds Telegram updates.

View Source
const PollMargin = 15 * time.Second

PollMargin is how much longer than its wait Muster waits for the answer of a pollEvents call, so that a long poll is never cut short as a timeout.

View Source
const PollWait = 25 * time.Second

PollWait is bridge.poll_wait: the wait of each pollEvents call, how long the bridge holds the call open while no event comes.

View Source
const ProtocolVersion = "1"

ProtocolVersion is the version of the Bridge protocol this Muster speaks.

View Source
const PushPattern = "POST " + CallbackPath + "{connection_id}"

PushPattern is the route of bridgeEvent on the callback mux of the ingest listener: a bridge in push mode posts the events of a Connection to CallbackPath followed by its public_id (C-22.FR-11).

View Source
const PushTolerance = 5 * time.Minute

PushTolerance is bridge.push_tolerance: the longest a pushed event's webhook-timestamp may be from Muster's real clock, either way, as Standard Webhooks recommends.

View Source
const (
	// ReadInterval is how often the poller reads the Bridge Connections again when no change woke it.
	ReadInterval = 30 * time.Second
)
View Source
const ReasonEditWindowClosed = "edit_window_closed"

ReasonEditWindowClosed is the reason of a gone answer to an edit refused only because of the message's age.

View Source
const StepMessage = "message"

StepMessage is the step of a test and the item of a preview that is the test message.

Variables

View Source
var ErrBaseURL = errors.New("the base URL is not an absolute http or https URL without user information, query or " +
	"fragment")

ErrBaseURL is a base URL that breaks the rules of C-22.FR-1.

View Source
var ErrNoConnection = errors.New("no such bridge connection")

ErrNoConnection is a Bridge Connection that is unknown, deleted or not a Bridge Connection.

View Source
var ErrNoTarget = errors.New("the destination has no bridge connection")

ErrNoTarget is a Destination that has no Bridge Connection to post through: its Connection no longer exists, or it is not a Bridge Destination.

View Source
var ErrNotAnEvent = errors.New("the body is not an event of the bridge protocol")

ErrNotAnEvent is a body that is no event of the Bridge protocol: not a JSON object, of a type the protocol does not define, or without a member its type requires or with one out of its bounds. The wrapped text names what is wrong, never a value of the body.

Functions

func EventDeliveryStep

func EventDeliveryStep(i Info, mode string) (ok bool, code, message string)

EventDeliveryStep checks that the bridge offers the event delivery mode of a Connection (C-22.FR-2); a failure has its code and message.

func LogInfoRead

func LogInfoRead(ctx context.Context, log *logging.Logger, publicID string, i Info)

LogInfoRead logs bridge_info_read for the Connection publicID (C-22.FR-24).

func NewPush

func NewPush(cfg PushConfig) http.Handler

NewPush is the push callback of Bridge Connections, bridgeEvent (C-22.FR-11, AC-14), which answers every request itself. Nothing changes before a request is authenticated: an unknown or deleted Connection, one in poll mode, a missing Standard Webhooks header, a webhook-signature without a v1 signature of webhook-id, webhook-timestamp and the body under the Connection's push secret, compared in constant time, and a webhook-timestamp further than Tolerance from the real clock are all answered 401 with one body, so that the endpoint reveals nothing about which Connections exist; the signature is checked before the timestamp, so that an unsigned request does not learn whether its timestamp was in range. A body larger than BodyLimit, one that is no event of the Bridge protocol and an event whose id is not webhook-id are answered 400, and the bridge drops them. Otherwise the event goes to Events, which waits for a free slot, handles it once by its id and answers the person before the 204; an event whose handling failed is answered 500 and is not recorded, so that the bridge sends it again. Each refusal logs bridge_event_rejected with its reason, never the signature, the secret, the headers or the body. Every request for a known Connection is in its Request log, refused ones included, through the annotation of requestlog.Inbound (C-23.FR-1).

func ParseBaseURL

func ParseBaseURL(raw string) (string, error)

ParseBaseURL checks the base URL of a bridge (C-22.FR-1) and returns it normalized: an absolute http or https URL with a host and without user information, query or fragment, whose path prefix is kept without its trailing slashes, so that requests go to `<base>/v1/…`.

func RunConformance

func RunConformance(ctx context.Context, cfg ConformanceConfig) (failed bool, err error)

RunConformance runs the conformance check of cfg and prints each line to cfg.Out as soon as its step ends. failed is whether a step failed. err is the end of ctx, which interrupted the run, or a client that cannot be built, after which nothing ran.

func Segment

func Segment(id string) string

Segment is id percent-encoded as one path segment, as the protocol sends a message_id or a channel_id; a segment of dots only is encoded too, so that no client or server takes `.` or `..` for a step in the path.

func ValidPushSecret

func ValidPushSecret(s logging.Secret) bool

ValidPushSecret reports whether s is a push secret in the Standard Webhooks form, whsec_ followed by base64 of at least one byte, as a Connection's push secret is checked.

Types

type Adapter

type Adapter struct {
	Targets Targets
}

Adapter is the Bridge delivery (C-22.FR-4 to FR-8, ADR-0017): Publish, Update and Reply post, edit and reply as envelopes, called by the delivery worker and the interactive path only, in the client class of their Call, with the idempotency key of the Call; and Check, the Destination check of C-22.FR-3, for the Broken probe. Each body is fitted to the limit of the Destination's Connection, which its info gives.

func (*Adapter) Check

func (a *Adapter) Check(ctx context.Context, c delivery.Call) delivery.Outcome

Check runs the Destination check of C-22.FR-3 — one checkChannel, which posts nothing — at once in the client class of c: the Broken probe calls it in the delivery class (C-11.FR-9).

func (*Adapter) EditWindow

func (a *Adapter) EditWindow(ctx context.Context, c delivery.Call) (time.Duration, bool)

EditWindow is limits.edit_max_age_seconds of the info of the Connection of c's Destination, read again past bridge.info_max_age (C-22.FR-9): false when the info declares none (null: edits never expire) or cannot be read, so that the bridge's own refusal of an edit as edit_window_closed is what marks a Root message past its window.

func (*Adapter) FinalKey

func (a *Adapter) FinalKey(d delivery.Destination, deliveryID int64) string

FinalKey is the idempotency key of the final edit of a Root message past its edit window, sent as a Thread reply (C-22.FR-9): final-<Destination public_id>-<delivery id>.

func (*Adapter) LengthLimit

func (a *Adapter) LengthLimit() int

LengthLimit is the protocol's floor of limits.max_body_length. Delivery never shortens for a bridge: the adapter fits each body to its Connection's limit itself.

func (*Adapter) PointerKey

func (a *Adapter) PointerKey(d delivery.Destination, deliveryID, publication int64) string

PointerKey is the idempotency key of the pointer reply under Root message number publication, which a republication past the edit window replaced (C-22.FR-9): pointer-<Destination public_id>-<delivery id>-<publication>.

func (*Adapter) PublicationKey

func (a *Adapter) PublicationKey(d delivery.Destination, deliveryID, publication int64) string

PublicationKey is the idempotency key of a Publication (C-22.FR-6): pub-<Destination public_id>-<delivery id>-<publication>, the same for every retry of it.

func (*Adapter) Publish

Publish posts m as a Root message, or a Storm summary, with the Mentions of a Loud call — their line before its body and their entries in `mentions` (C-22.FR-16) — and its footer in the Connection's identity space. Its outcome names the message, its link when the bridge sent a safe one, the Thread the answer named and whether the answer was replayed; a truncated body is delivered.

func (*Adapter) Reply

Reply posts m into the Thread of root under its last thread_ref, null without one, with the Mentions of a Loud call as Publish sends them; its outcome names the reply, the thread_ref the answer returned and whether it was replayed. A Reminder carries its buttons when the bridge has them.

func (*Adapter) ReplyKey

func (a *Adapter) ReplyKey(d delivery.Destination, replyID int64) string

ReplyKey is the idempotency key of a Thread reply (C-22.FR-6): reply-<Destination public_id>-<thread reply id>.

func (*Adapter) Update

func (a *Adapter) Update(ctx context.Context, c delivery.Call, messageID string, m delivery.Message) delivery.Outcome

Update replaces the message messageID with the whole envelope of m, Quiet and without Mentions, its footer in the Connection's identity space. An edit refused as gone only because of the message's age, with the reason edit_window_closed, is OutcomeEditWindowClosed, not a deleted Root message (C-22.FR-8).

type Batch

type Batch struct {
	Events     []json.RawMessage
	NextCursor string
}

Batch is the answer of pollEvents: the events after the cursor sent, oldest first, each as the bridge sent it, and the cursor of the next call.

type Bindings

type Bindings interface {
	BridgePressBinding(ctx context.Context, connectionID int64, messageID string) (delivery.BridgeBinding, error)
	BridgeThreadBinding(ctx context.Context, connectionID int64, messageID string) (delivery.BridgeBinding, error)
	RootDeleted(ctx context.Context, connectionID int64, messageID string) error
}

Bindings are what delivery does for an event about a message of a Bridge Connection, declared by their consumer: the reads of what a press or a Thread message is bound to, and the deleted Root message flow of a message_deleted event; *delivery.Service implements them.

type ChannelCheck

type ChannelCheck struct {
	Name    string
	Message string
	Code    string
	Outcome delivery.Outcome
}

ChannelCheck is the result of the Destination check of a channel: the channel's name when it passed; otherwise the message, in English, with its code; and the outcome for delivery — ok, or the failure as Result.Outcome classifies it, with the message as its error — which the Broken probe keeps.

func CheckDestination

func CheckDestination(ctx context.Context, c *Client, run Runner, channelID string) (ChannelCheck, error)

CheckDestination runs the Destination check of the channel channelID through run (C-22.FR-3): one checkChannel, which posts nothing. A token the bridge refuses with 401 is token_invalid; any other forbidden answer is channel_forbidden, with the bridge's detail as the message; a request without an answer, or one the outbound address policy refuses, has the code of delivery.FailureCode; any other error class is request_failed, with the class named in the message. Its error is the runner's own.

func (ChannelCheck) OK

func (c ChannelCheck) OK() bool

OK reports whether the check passed.

type Class

type Class string

Class is the error class of a failed call (ADR-0017 Errors): what the bridge says in the problem's class, or what the protocol's mapping of the status gives.

const (
	ClassTransient   Class = "transient"
	ClassRateLimited Class = "rate_limited"
	ClassGone        Class = "gone"
	ClassForbidden   Class = "forbidden"
	ClassInvalid     Class = "invalid"
)

The error classes.

type Classification

type Classification struct {
	Class         Class
	RetryAfter    time.Duration
	HasRetryAfter bool
	Scope         Scope
	Reason        string
}

Classification is how a failed call is classified: its class; for rate_limited the Retry-After of the answer, when it has one, and its scope; for gone the problem's reason. The zero value is a call that succeeded.

func Classify

func Classify(status int, retryAfter time.Duration, hasRetryAfter bool, p *gen.Problem) Classification

Classify classifies an answer (C-22.FR-8, ADR-0017 Errors): by the class of its problem p when it has a known one, otherwise by its status — 0, a call without an answer, transient; 401 and 403 forbidden; 408 transient; 429, and 503 with Retry-After, rate_limited; other 5xx transient; a 2xx no failure; 3xx, 404, 410 and everything else invalid. No status is ever gone: only the bridge decides that a message is gone.

type Client

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

Client calls the bridge of one Connection, in the interactive, delivery and background client classes; the outbound client of a class is built on its first call.

func NewClient

func NewClient(n Network, s Settings) (*Client, error)

NewClient builds the client of the Connection s, checking its settings with the interactive class. Its requests go to the base URL, or to what s.Route answers for it and the token when it answers. The token, the push secret and the proxy password are registered for redaction.

func (*Client) AnswerEvent

func (c *Client) AnswerEvent(ctx context.Context, class outbound.Class, eventID, text string) (gen.AnswerShown,
	Result)

AnswerEvent calls answerEvent (C-22.FR-13): it shows text, a plain text cut to MaxAnswerLength characters, to the person behind the event eventID, with the Idempotency-Key answer-<event id>, and returns where the bridge showed it. A successful answer without a shown_as of the protocol is invalid.

func (*Client) CheckChannel

func (c *Client) CheckChannel(ctx context.Context, class outbound.Class, channelID string) (string, Result)

CheckChannel calls checkChannel for channelID in class (C-22.FR-3), which posts nothing: the channel's name, masked of the token and the push secret, when the bridge answers 200 with a name of 1 to 200 characters without NUL. Any other answer is a failed Result; a 200 without such a name is invalid.

func (*Client) DeleteMessage

func (c *Client) DeleteMessage(ctx context.Context, class outbound.Class, messageID string) Result

DeleteMessage calls deleteMessage in class: it deletes the message messageID of the bot, and a message that no longer exists is a success too. Only the conformance check calls it (C-22.FR-21); Muster L1 never deletes a message.

func (*Client) EditMessage

func (c *Client) EditMessage(ctx context.Context, class outbound.Class, messageID string, in gen.MessageContent) (
	gen.MessageEdited, Result)

EditMessage calls editMessage (C-22.FR-6): it replaces the message messageID with the envelope in, which has no Mentions and is always Quiet.

func (*Client) FindUsers

func (c *Client) FindUsers(ctx context.Context, class outbound.Class, handle string) (gen.Person, bool, Result)

FindUsers calls findUsers (C-22.FR-15) in class for the account with handle: the one person the bridge found, and false for none. A successful answer without a list of at most one person within the protocol's bounds is invalid. The handle travels in the query, which the texts of a failure leave out.

func (*Client) GetInfo

func (c *Client) GetInfo(ctx context.Context, class outbound.Class) (Info, Result)

GetInfo calls getInfo (C-22.FR-2). A 401 is the code token_invalid with MessageTokenInvalid; an info that Muster cannot use is invalid, with the code and the message of its *InfoError.

func (*Client) PollEvents

func (c *Client) PollEvents(ctx context.Context, cursor *string, wait time.Duration) (Batch, Result)

PollEvents calls pollEvents (C-22.FR-11): the events after cursor, all the bridge keeps when cursor is nil, which the bridge holds open for wait while there are none. It runs in the background client class through the client that makes long polls, whose timeout is PollWait plus PollMargin, and the caller's context bounds the call with the retries of the class. A successful answer without an array of events and a next_cursor of at most 1024 characters is invalid.

func (*Client) PostMessage

func (c *Client) PostMessage(ctx context.Context, class outbound.Class, key string, in gen.MessageInput) (
	gen.MessagePosted, Result)

PostMessage calls postMessage (C-22.FR-4, FR-6): it posts the envelope in to its channel with the idempotency key, sent as Idempotency-Key unless it is empty. A successful answer without a message_id of 1 to 512 characters, or with a longer thread_ref, is invalid.

func (*Client) ReplyInThread

func (c *Client) ReplyInThread(ctx context.Context, class outbound.Class, messageID, key string,
	in gen.ThreadReplyInput) (gen.ThreadReplyPosted, Result)

ReplyInThread calls replyInThread (C-22.FR-6): it posts the reply in into the Thread of the message messageID with the idempotency key, sent as Idempotency-Key unless it is empty. A successful answer without a message_id and a thread_ref of 1 to 512 characters each is invalid.

func (*Client) SendDirectMessage

func (c *Client) SendDirectMessage(ctx context.Context, class outbound.Class, key, externalID, body string) (
	gen.DirectMessageSent, Result)

SendDirectMessage calls sendDirectMessage (C-22.FR-15) in class with the Idempotency-Key key: body, CommonMark cut to MaxDirectMessageLength characters, to the account externalID, in the direct chat the bridge opens if needed. A successful answer without a message_id is invalid.

func (*Client) Via

func (c *Client) Via() string

Via is how the requests of the client travel: ViaDirect or ViaProxy.

type Commands

type Commands interface {
	Acknowledge(ctx context.Context, c groups.Caller, publicID string) (groups.Result, error)
	Unacknowledge(ctx context.Context, c groups.Caller, publicID string) (groups.Result, error)
	Resolve(ctx context.Context, c groups.Caller, publicID string, note *string) (groups.Result, error)
	Snooze(ctx context.Context, c groups.Caller, publicID string, end groups.SnoozeEnd) (groups.Result, error)
	Unsnooze(ctx context.Context, c groups.Caller, publicID string) (groups.Result, error)
	AnswerReminder(ctx context.Context, c groups.Caller, publicID string) (groups.Result, error)
}

Commands are the Commands a press or a Text command runs; *groups.Service implements them.

type ConformanceConfig

type ConformanceConfig struct {
	BaseURL          string
	Token            logging.Secret
	PushSecret       logging.Secret
	Channel          string
	ForbiddenChannel string
	Handle           string
	PushListen       string
	PushURL          string
	Interactive      bool
	Wait             time.Duration
	Out              io.Writer
	Log              *logging.Logger
	Real             clock.Clock
	// contains filtered or unexported fields
}

ConformanceConfig is a run of the conformance check: the bridge's base URL and token; the push secret, generated when it is empty; the channel the bot posts to, the channel it cannot use and the handle of a person, the last two skipping their steps when empty; where the push listener listens (DefaultPushListen when empty) and the URL the bridge reaches it at (the listener's own when empty); whether a person takes part; how long press waits for them (ConformanceWait when zero); where the lines go; the logger of the outbound client (nothing logged when nil); and the real clock (the system clock when nil).

type Conn

type Conn struct {
	ID       int64
	PublicID string
	Version  int64
	Client   *Client
}

Conn is a Bridge Connection as InfoCache needs it: its id, its public_id for the log, the version of its configuration that its client was built from, and its client.

type Connections

type Connections interface {
	// PushConnection is the Bridge Connection publicID with its event delivery mode, and in push mode its client,
	// whose settings hold the push secret; a Connection in poll mode has no client, since its secrets are never opened
	// for a push. A Connection that is unknown, deleted or not a Bridge Connection is ErrNoConnection.
	PushConnection(ctx context.Context, publicID string) (Conn, string, error)
	// PollingConnections lists the Bridge Connections that are not deleted and receive their events by polling, each
	// with its client, kept until the Connection changes, and its stored cursor; one whose client cannot be built has
	// Err instead of a client.
	PollingConnections(ctx context.Context) ([]Polled, error)
	// StoreEventsCursor stores the cursor of the events of c, or drops it when cursor is nil, unless the Connection
	// changed since c was read.
	StoreEventsCursor(ctx context.Context, c Conn, cursor *string) error
	// HandleEventOnce runs f for the event eventID of the Connection connectionID unless its id was recorded within
	// EventDedupWindow, under the transaction advisory lock of the event's claim, so that a second copy of the event
	// waits for the first and then finds the id recorded; once f succeeded it records the id and commits. It reports
	// whether f ran. An error of f records nothing, so that the event comes again.
	HandleEventOnce(ctx context.Context, connectionID int64, eventID string, f func(context.Context) error) (bool,
		error)
}

Connections are the Bridge Connections as the event paths need them, declared by their consumer; *connections.Service implements them and internal/runtime wires it, since internal/connections imports this package.

type Event

type Event struct {
	ID         string
	Type       string
	OccurredAt time.Time
	MessageID  string
	User       gen.Person
	Data       string
	Text       string
	ThreadRef  *string
	Token      string
}

Event is one event of the Bridge protocol, checked against api/bridge.yaml, since the generated models check nothing. MessageID is a press's, a Thread message's and a message_deleted event's; User a press's, a Thread message's and an account_link event's; Data a press's; Text and ThreadRef a Thread message's; Token an account_link event's.

func DecodeEvent

func DecodeEvent(raw []byte) (Event, error)

DecodeEvent decodes one event of the Bridge protocol (C-22.FR-11) with the generated models and checks it against api/bridge.yaml: a JSON object of one of the four types, with its id, occurred_at and every member its type requires, within their bounds; members it does not know are ignored. Anything else is ErrNotAnEvent.

type Events

type Events struct {
	Store Connections
	// Bindings find the message an event names among the Connection's deliveries, and start the deleted Root message
	// flow.
	Bindings Bindings
	// Links map the account behind an event to its User.
	Links Links
	// Linker links the accounts of account_link events (C-22.FR-15).
	Linker Linker
	// Commands run the Commands of presses and Text commands through the dispatcher.
	Commands Commands
	// Roles are the Permissions of each Role, which a linked User acts with.
	Roles auth.Roles
	// Keys verify the signed data of a press: the Keyring.
	Keys buttons.Keys
	// Path is the interactive path, which the answers take.
	Path Path
	// Budget is delivery.interactive_budget, within which an answer is made or fails; zero is
	// delivery.InteractiveBudget.
	Budget time.Duration
	// PublicURL is MUSTER_PUBLIC_URL, the base of the profile link of an account without an Account link.
	PublicURL string
	// Clocks: the real clock dates the age of a press or a Text command against bridge.event_max_age, and a Snooze
	// lasts its duration from the business clock.
	Clocks clock.Clocks
	// MaxAge is bridge.event_max_age; zero is EventMaxAge.
	MaxAge time.Duration
	// Parallel is bridge.parallel_events; zero is ParallelEvents.
	Parallel int
	Log      *logging.Logger
	// contains filtered or unexported fields
}

Events is the one handler of Bridge events for both event delivery modes (C-22.FR-11, ADR-0017): the poller and the push callback hand it every event they decoded. It handles at most Parallel events at a time, claims each event id of a Connection through Store, dispatches the event inside the claim — a Command runs through the dispatcher in its own transaction — and, once the claim committed, answers the person behind it and logs what it did, all before the event is acknowledged. Every event type of the protocol is handled, whatever the Connection's info declares.

func (*Events) Handle

func (e *Events) Handle(ctx context.Context, c Conn, ev Event) error

Handle handles the event ev of the Connection c once a slot is free (C-22.FR-11). An event whose id the Connection handled before is acknowledged without handling it. An error — no slot before ctx ended, or a claim or a handling that failed, logged as bridge_event_failed unless ctx ended, as when the Leader stops polling — records nothing: the poller keeps its cursor and the push callback answers 500, so that the event comes again. Once the claim committed, the person behind the event is answered, when there is something to say (C-22.FR-13), before Handle returns and so before the poller stores the next cursor or the push callback answers 204; a crash or a failure of the answer leaves the person without one, which is logged with the event's line and never retried.

type Info

type Info struct {
	gen.Info
	Raw json.RawMessage `json:"-"`
}

Info is the info of a bridge: the fields Muster reads, and Raw, the whole answer as the bridge sent it, unknown fields included, which is what Muster stores.

func DecodeInfo

func DecodeInfo(raw []byte) (Info, error)

DecodeInfo reads a stored copy of info, which ParseInfo accepted when it was read.

func ParseInfo

func ParseInfo(body []byte) (Info, error)

ParseInfo reads the answer of getInfo (C-22.FR-2). It refuses an answer larger than InfoMaxBytes before it parses it, and one that Muster could not store: not UTF-8, or with an escape that PostgreSQL's jsonb refuses. It reads protocol_version before it validates the rest, so that a bridge of another version fails with its version named rather than with a schema error. The error is an *InfoError.

func (Info) Features

func (i Info) Features() []string

Features are the names of the optional features the info declares, sorted.

type InfoCache

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

InfoCache keeps the info of each Bridge Connection for the calls that depend on it (C-22.FR-2): in memory, else from the store, read again through the bridge when it is older than its maximum age on the business clock. A copy belongs to a version of its Connection, so that a new base URL or token never serves the info of the old one.

func NewInfoCache

func NewInfoCache(store InfoStore, business clock.Clock, maxAge time.Duration, log *logging.Logger) *InfoCache

NewInfoCache returns an InfoCache over store; a maxAge of 0 is DefaultInfoMaxAge.

func (*InfoCache) Forget

func (ic *InfoCache) Forget(id int64)

Forget drops the copy kept in memory of the Connection id, which was deleted.

func (*InfoCache) Info

func (ic *InfoCache) Info(ctx context.Context, conn Conn, class outbound.Class) (Info, Result)

Info is Muster's copy of the info of conn. When there is none, or it is older than the maximum age, it is read again through conn's client in class; a fresh read is stored, kept and logged. A failed read returns the stale copy, if there is one, with the failed Result; a failure of the store is a transient Result.

func (*InfoCache) Refresh

func (ic *InfoCache) Refresh(ctx context.Context, conn Conn, class outbound.Class) (Info, Result, error)

Refresh reads the info of conn again through its client in class, whatever Muster's copy, as a Connection check does: a fresh read is stored, kept and logged, and a failed one changes nothing. The error is a failure of the store, which leaves the fresh read kept in memory.

type InfoError

type InfoError struct {
	Code    string
	Message string
	// contains filtered or unexported fields
}

InfoError is an info that Muster cannot use: its check code and its message, in English. version is the unknown protocol_version the message shows, so that a client masks it before it is cut.

func (*InfoError) Error

func (e *InfoError) Error() string

type InfoStore

type InfoStore interface {
	StoredInfo(ctx context.Context, conn Conn) (Stored, bool, error)
	StoreInfo(ctx context.Context, conn Conn, i Info, at time.Time) error
}

InfoStore keeps the copy of info of each Bridge Connection; internal/connections implements it. StoredInfo has no copy for a Connection whose version is no longer conn's, and StoreInfo stores nothing for one.

type LinkBots

type LinkBots struct {
	Conns LinkConnections
	Path  Path
}

LinkBots run the calls of an Account link by code through the bot of a Bridge Connection (C-22.FR-15, C-18.FR-11): the lookup of the account by its handle and the direct message with the code, on the interactive path, never as a delivery. They implement accountlinks.BridgeBots.

func (LinkBots) Session

func (l LinkBots) Session(ctx context.Context, publicID string,
	f func(ctx context.Context, b accountlinks.BridgeBot) error) error

Session takes one limiter token of the Connection publicID on the interactive path and runs f with its bot, whose offer comes from the Connection's info, read again first when Muster's copy is older than bridge.info_max_age (C-22.FR-2), the stale copy when that read fails; a RetryAfter that the read or a call of f gets holds the Connection. A Connection that is unknown, deleted or not a Bridge one is accountlinks.ErrNoConnection; no token within the budget is a *delivery.LimitedError and runs nothing.

type LinkConnections

type LinkConnections interface {
	// BridgeConn is the Bridge Connection publicID with its client, kept until the Connection changes; one that is
	// unknown, deleted or not a Bridge Connection is ErrNoConnection.
	BridgeConn(ctx context.Context, publicID string) (Conn, error)
	// BridgeInfo is Muster's copy of the info of conn, read again through its client in class when it is older than
	// bridge.info_max_age; a failed read returns the stale copy, if there is one, with the failed Result.
	BridgeInfo(ctx context.Context, conn Conn, class outbound.Class) (Info, Result)
}

LinkConnections find the Bridge Connection of an Account link by code and read its info, declared by their consumer; *connections.Service implements them.

type Linker

type Linker interface {
	LinkBridge(ctx context.Context, conn accountlinks.BridgeConnection, token string, from accountlinks.BridgeAccount) (
		accountlinks.BridgeLinked, error)
}

Linker links the account behind an account_link event; *accountlinks.Service implements it.

type Links interface {
	Lookup(ctx context.Context, identitySpace, externalID string) (accountlinks.User, error)
}

Links map an account of a Bridge Connection to its User; *accountlinks.Service implements them.

type Network

type Network struct {
	Policy   outbound.PolicySource
	Log      *logging.Logger
	Real     clock.Clock
	Resolver outbound.Resolver
	Recorder outbound.Recorder
}

Network is what a Client needs besides its Connection: the outbound address policy, the logger, the real clock of the outbound metrics and of Retry-After dates, a resolver (nil: the system resolver) and the Request log, nil for none (C-23.FR-1). Its fields are those of mattermost.Network, so that one converts into the other.

type Path

type Path interface {
	Do(ctx context.Context, s delivery.Subject, op delivery.Op) (delivery.Outcome, error)
}

Path is the interactive path, declared by its consumer; *delivery.Interactive implements it.

type Polled

type Polled struct {
	Conn   Conn
	Cursor *string
	Err    error
}

Polled is a Bridge Connection that receives its events by polling, with the stored cursor of its events, nil for none. Err is why its client could not be built, such as a token that cannot be opened: the Connection then has no client and is not polled.

type Poller

type Poller struct {
	Source Connections
	Events *Events
	Log    *logging.Logger
	// Wait is bridge.poll_wait; zero, or longer, is PollWait, so that the long-poll client's timeout is never shorter
	// than a call's deadline.
	Wait time.Duration
	// Every is how often the Connections are read again without a wake; zero is ReadInterval.
	Every time.Duration
	// contains filtered or unexported fields
}

Poller polls the events of an Organization's Bridge Connections in poll mode (C-22.FR-11), the Leader task bridge_polling (ADR-0007): one loop per Connection calls pollEvents with the stored cursor and Wait, gives each call Wait plus PollMargin, hands the events of the batch to Events one at a time, in order, and then stores next_cursor, so that a new Leader goes on where the old one stopped. A cursor the bridge refuses as invalid is dropped, and the next poll starts without one. A failed call backs off from 1 s to 1 min, counted per call, and logs bridge_poll_failed at the first failure in a row and every tenth; it is no delivery outcome and makes nothing Broken. A batch whose handling fails keeps the cursor, so that it is polled again. A Connection whose client cannot be built is not polled; bridge_poll_failed is logged at the first read of the Connections that finds it so and every tenth, counted for each version of the Connection.

Every call runs under the context of the run, so that losing leadership or stopping the replica cancels a poll in flight at once. Running it on a frozen old Leader and its successor at once is safe: an event polled twice is handled once by its id, and a cursor an old Leader stores late only makes the bridge send events again.

func (*Poller) Run

func (p *Poller) Run(ctx context.Context) error

Run polls until ctx ends, which is when the Leader loses the lock or stops, and stops every loop before it returns: a loop starts for each Bridge Connection in poll mode, starts again when the Connection's version changes and stops when it leaves poll mode or is deleted, or its client cannot be built. A failed read of the Connections stops them too and returns its error, so that the Leader task runs again.

func (*Poller) Wake

func (p *Poller) Wake()

Wake reads the Connections again at once: a Connection changed, maybe on another replica.

type Probe

type Probe struct {
	OK      bool
	Latency time.Duration
	Message string
	Code    string
}

Probe is the result of a dry probe: whether it passed, its latency on the real clock, and when it failed what answered, in English, with its code, which clients translate.

func RunDryProbe

func RunDryProbe(ctx context.Context, c *Client, run Runner, realClock clock.Clock) (Probe, error)

RunDryProbe makes the dry probe of c through run (C-22.FR-2): `GET <base>/v1/info` without the token, timed on the real clock, on a client that may have none. It passes on a 401 answer with a problem and otherwise names what answered, a bridge it could not reach as delivery.FailureMessage does, without the bridge's name through a proxy, whose own name is the one that did not resolve. A rate_limited answer is handed to run as Transient: a request without a token says nothing of the bot's budget, so it never holds the Connection's limiter, least of all when an unsaved base URL answered it. Its error is the runner's own.

type PushConfig

type PushConfig struct {
	Connections Connections
	Events      *Events
	// Real is the real clock that webhook-timestamp is checked against.
	Real clock.Clock
	// Tolerance is bridge.push_tolerance; zero is PushTolerance.
	Tolerance time.Duration
	// BodyLimit bounds the body of an event; zero is MaxEventBytes.
	BodyLimit int64
	Log       *logging.Logger
}

PushConfig is what the push callback needs.

type Result

type Result struct {
	Status         int
	Classification Classification
	Error          outbound.Untrusted
	Code           string
	Network        string
	Blocked        bool
	Unanswered     bool
}

Result is how a call ended; a zero Classification is success. Error is the masked text of a failure: the problem's detail, or its title, when the bridge sent one, otherwise what outbound reports. Code is the check code the protocol names for the failure (token_invalid, protocol_version_unknown, protocol_mismatch), empty otherwise; Network is what failed when the call got no answer (outbound.Network*), and Blocked whether the outbound address policy refused it. Unanswered is a call without an answer whose request may have reached the bridge: one written in full before the answer was lost to a timeout or a lost connection — not one that failed while connecting, which sent nothing.

func (Result) CheckCode

func (r Result) CheckCode() string

CheckCode is the check code of a failed call: the one the protocol names, otherwise that of delivery.FailureCode; empty for a call that succeeded.

func (Result) OK

func (r Result) OK() bool

OK reports whether the call succeeded.

func (Result) Outcome

func (r Result) Outcome() delivery.Outcome

Outcome is the Result for delivery (C-22.FR-8): rate_limited waits for the channel's Destination or, with the scope bot, for every Destination of the Connection, and is Transient without a Retry-After or with one longer than DefaultRetryAfterMax, so that a long pause ends in Broken; forbidden is Fatal, gone is Gone and invalid is unknown, which ends the delivery as Not delivered. Unanswered is kept, so that delivery knows the request may have been posted.

type Route

type Route func(baseURL string, token logging.Secret) string

Route names the base URL a Connection's requests go to instead of its own, by that base URL and the token: under `muster dev` the fake bridge for https://bridge.example.org with one of its published tokens; an empty answer is the Connection's own base URL.

type Runner

type Runner func(ctx context.Context, f func(ctx context.Context, c delivery.Call) delivery.Outcome) (delivery.Outcome,
	error)

Runner makes the request of a check with the Call it is made in: on the interactive path when a person waits for it, at once for muster doctor. Its error is the runner's own — no limiter token within the budget — and ends the check.

func Direct

func Direct(c delivery.Call) Runner

Direct is the Runner that calls at once with c: muster doctor, which waits for no token.

func Interactive

func Interactive(in Path, s delivery.Subject) Runner

Interactive is the Runner of a check a person waits for: its request through the interactive path, limited by s.

type Scope

type Scope string

Scope is what a rate_limited answer holds: one channel, or every channel of the bot.

const (
	ScopeChannel Scope = "channel"
	ScopeBot     Scope = "bot"
)

The scopes of a rate_limited answer.

type Settings

type Settings struct {
	BaseURL    string
	Token      logging.Secret
	PushSecret logging.Secret
	Proxy      *outbound.Proxy
	Owner      outbound.Owner
	Route      Route
}

Settings are a Connection as its client needs it: the normalized base URL, the token, the push secret, which the bridge knows too and is masked like the token, and the proxy, nil for none; the Connection whose Request log keeps its requests, none for a client that records nothing; and the Route of `muster dev`, nil outside it.

type Stored

type Stored struct {
	Info   Info
	ReadAt time.Time
}

Stored is Muster's copy of the info of a Connection and when it was read, on the business clock.

type Target

type Target struct {
	Conn      Conn
	ChannelID string
}

Target is where a Bridge Destination posts: its Connection, with the protocol client, and its channel.

type Targets

type Targets interface {
	BridgeTarget(ctx context.Context, destinationID int64) (Target, error)
	BridgeInfo(ctx context.Context, conn Conn, class outbound.Class) (Info, Result)
}

Targets find the Target of a Destination by its id — of a deleted Destination too, for its final edit — and read the info of its Connection through the InfoCache, again past bridge.info_max_age; declared by their consumer, *connections.Service implements them. A Destination without a Target is ErrNoTarget.

type TestRenderer

type TestRenderer interface {
	TestRoot(src *messages.Source, markup messages.Markup, destination string) messages.Rendered
}

TestRenderer renders the Root message of a test or a preview, declared by its consumer; *messages.Renderer implements it.

type Tester

type Tester struct {
	Adapter  *Adapter
	Path     Path
	Renderer TestRenderer
	Budget   time.Duration
	Real     clock.Clock
}

Tester is the Destination test and the preview of Bridge Destinations, on the interactive path Path, the test within Budget (delivery.interactive_budget; zero is delivery.InteractiveBudget), timed on the real clock Real.

func (*Tester) Preview

func (t *Tester) Preview(ctx context.Context, in delivery.TestInput) ([]delivery.PreviewItem, error)

Preview renders, without posting anything, the test message of the source of in as the Bridge Destination would receive it (C-22.FR-17, C-16.FR-4): the item message, the envelope as JSON. The info of the Connection is read on the interactive path; without it the body has the protocol's floor as its limit and no buttons.

func (*Tester) Test

Test runs the test of the Bridge Destination of in (C-22.FR-17): the step message, within the budget. A Destination whose Connection cannot be read fails it; a request the outbound address policy refused is blocked.

Directories

Path Synopsis
Package gen provides primitives to interact with the openapi HTTP API.
Package gen provides primitives to interact with the openapi HTTP API.

Jump to

Keyboard shortcuts

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