Documentation
¶
Overview ¶
Package slack is Muster's client of Slack's Web API (C-24): calls of `https://slack.com/api/<method>` with a Connection's bot token or app-level token as a bearer token, through internal/outbound with the Connection's proxy in the caller's client class (ADR-0015), JSON for the write methods and form-encoded for the others, with both tokens and the Slack signing secret registered for redaction; the classification of every answer by Slack's `error` (classify.go); the Connection check (check.go); the Destination check of a channel and the channel list (channels.go); delivery (adapter.go), whose messages are laid out in blocks (layout.go) and sent with the unexported chat calls of this file; and the presses of people (presses.go) — confirmed by the signed callback of http mode (callback.go) or by the Leader's Socket Mode connections, which confirm each envelope at once and hand its press over (socket.go) — and their private answers (answers.go), with chat.postEphemeral or the press's response_url; and Account links (links.go): the lookup of a person by email or name and the bot's direct messages with a code.
Index ¶
- Constants
- Variables
- func MissingScopesMessage(missing []string) string
- func NewCallback(cfg CallbackConfig) http.Handler
- func ValidChannelID(id string) bool
- type Adapter
- func (a *Adapter) Check(ctx context.Context, c delivery.Call) delivery.Outcome
- func (a *Adapter) LengthLimit() int
- func (a *Adapter) Markup() messages.Markup
- func (a *Adapter) Publish(ctx context.Context, c delivery.Call, m delivery.Message) delivery.Outcome
- func (a *Adapter) Reply(ctx context.Context, c delivery.Call, root delivery.Root, m delivery.Message) delivery.Outcome
- func (a *Adapter) Update(ctx context.Context, c delivery.Call, messageID string, m delivery.Message) delivery.Outcome
- type Answer
- type Args
- type AuthTest
- type Bindings
- type Bot
- type CallbackConfig
- type Channel
- type ChannelCheck
- type ChannelList
- type Check
- type Class
- type Classification
- type Client
- func (c *Client) AppAuthTest(ctx context.Context, class outbound.Class) (AuthTest, Result)
- func (c *Client) AuthTest(ctx context.Context, class outbound.Class) (AuthTest, Result)
- func (c *Client) Base() string
- func (c *Client) BotsInfo(ctx context.Context, class outbound.Class, botID string) (Bot, Result)
- func (c *Client) Call(ctx context.Context, class outbound.Class, method string, args Args) Result
- func (c *Client) CallApp(ctx context.Context, class outbound.Class, method string, args Args) Result
- func (c *Client) ConversationsInfo(ctx context.Context, class outbound.Class, channelID string) (Channel, Result)
- func (c *Client) ConversationsList(ctx context.Context, class outbound.Class, cursor string) ([]Channel, Result)
- func (c *Client) DialSocket(ctx context.Context, address logging.Secret) (*outbound.WebSocket, error)
- func (c *Client) OpenSocket(ctx context.Context) (logging.Secret, Result)
- func (c *Client) Via() string
- type Commands
- type Conn
- type Connections
- type Handler
- type Identity
- type LinkBots
- type LinkConnections
- type Links
- type ListFailedError
- type ListedChannel
- type Network
- type Path
- type Presses
- type Probe
- type RateLimitedError
- type Result
- type Route
- type Runner
- type Settings
- type SocketConn
- type SocketSource
- type Sockets
- type Step
- type Target
- type Targets
- type TestRenderer
- type Tester
Constants ¶
const ( HeaderSignature = "X-Slack-Signature" HeaderTimestamp = "X-Slack-Request-Timestamp" )
The headers of a request that Slack signs (F-104).
const ( CodeChannelNotFound = "channel_not_found" CodeChannelArchived = "channel_archived" CodeBotNotInChannel = "bot_not_in_channel" )
The codes of the item channel besides those of the Connection check (DestinationCheckItem.code), which clients translate.
const ( MessageChannelNotFound = "The channel was not found, or the bot cannot see it." MessageChannelArchived = "The channel is archived." MessageInviteBotUnnamed = "Invite the bot to the channel." )
The messages of the item channel that failed, in English; the one of bot_not_in_channel is that of reference.md.
const ( StepToken = "token" StepScopes = "scopes" StepAppToken = "app_token" )
The steps of the connection check of a Slack Connection (C-24.FR-2).
const ( CodeTokenInvalid = "token_invalid" CodeWrongTokenType = "wrong_token_type" CodeMissingScope = "missing_scope" CodeAppMismatch = "app_mismatch" )
The codes of the failures the steps name (ConnectionCheckStep.code), which clients translate: a token Slack refused, a token that is not a bot's, missing scopes and two tokens of different apps. Any other failure has the code of delivery.FailureCode.
const ( MessageTokenInvalid = "Slack refused the token." //nolint:gosec // G101: a message, not a credential MessageWrongTokenType = "This is not a bot token." //nolint:gosec // G101: a message, not a credential MessageNotAppToken = "This is not an app-level token." //nolint:gosec // G101: a message, not a credential MessageAppMismatch = "The app-level token belongs to another Slack app than the bot token." )
The messages of the steps that failed, in English (reference.md).
const ( CodeNotSlack = "not_slack" CodeUnexpectedStatus = "unexpected_status" )
The codes of the dry probe that reached no Slack Web API (ConnectionCheckStep.code); a probe without an answer has the code of delivery.FailureCode.
const ( EventModeSocket = "socket" EventModeHTTP = "http" )
The event modes of a Connection (connection.slack.event_mode): Socket Mode with the app-level token, or presses posted to the callback address and signed with the Slack signing secret.
const ( ViaDirect = "direct" ViaProxy = "proxy" )
The paths of a Connection's requests (ConnectionPath).
const ( // HelloTimeout is slack.hello_timeout: how long a new connection may take to say hello before it is closed. HelloTimeout = 10 * time.Second // PingInterval is how often an open connection is pinged, and PingTimeout how long its pong may take. PingInterval = 30 * time.Second PingTimeout = 10 * time.Second // SocketBackoffBase and SocketBackoffCap are slack.socket_backoff: the wait after a failed connection doubles // from the base up to the cap, with equal jitter, and starts from the base again once a connection has lasted // socketSettled after its hello, or is ended by a planned refresh. It is never shorter than a Retry-After of // apps.connections.open, up to the cap. SocketBackoffBase = time.Second SocketBackoffCap = 5 * time.Minute // SocketReadInterval is how often the Connections are read again without a wake. SocketReadInterval = time.Minute )
The waits of Socket Mode (C-24.FR-9, F-100), all on the real clock.
const BaseURL = "https://slack.com/api/"
BaseURL is the only address of Slack's Web API (C-24.FR-1): a Connection has no address of its own.
const ( // CallTimeout bounds every call; a check names it when nothing answered within it. CallTimeout = 10 * time.Second )
The timeouts of a call and the largest answer read.
const CallbackPath = "/api/v1/callbacks/slack/"
CallbackPath is the path below MUSTER_INGEST_URL where Slack posts the button presses of a Connection in http mode, followed by its public_id (C-24.FR-9).
const CallbackPattern = "POST " + CallbackPath + "{connection_id}"
CallbackPattern is the route of slackInteraction on the callback mux of the ingest listener: Slack posts the presses of a Connection in http mode to CallbackPath followed by its public_id (C-24.FR-9).
const FormatJSON = "json"
FormatJSON is the format of the preview item of a Slack Destination: the body of chat.postMessage as JSON.
const HintAnotherClientConnected = "another program is connected to this Slack app through Socket Mode: presses are " +
"shared between them at random; use one Slack app for each Connection and share it with no other Connection or " +
"installation"
HintAnotherClientConnected is what muster doctor says of a Slack Connection in socket mode whose last hello counted another connection of its Slack app than the Leader's (C-24.FR-2, F-102).
const HooksHost = "hooks.slack.com"
HooksHost is the only host a press's response_url is called on outside `muster dev` (C-24.FR-11).
const ItemChannel = "channel"
ItemChannel is the one item of the Destination check of a Slack Destination (C-24.FR-3): conversations.info.
const LengthLimit = 3000
LengthLimit is the longest text of a section in code points of the mrkdwn as sent, entities and link markup included (F-076): the length limit the adapter declares, which the body of a message is shortened to (C-12.FR-11).
const MaxRequestBytes = 1 << 20
MaxRequestBytes bounds the raw body of a press, which is read whole before its form is parsed.
const MaxWaitingPresses = 64
MaxWaitingPresses bounds the presses one process keeps waiting for a slot; one more is dropped, unanswered, and logged as failed. A slot frees in the time of one Command, so 64 waiting presses are seconds of work for the ParallelPresses slots and more than the people of a team press at once, while the payloads they hold stay under 64 MiB, MaxRequestBytes each, however often a captured signed request is replayed within slack.request_tolerance.
const MessageProxyRefused = delivery.MessageProxyRefused
MessageProxyRefused is the message of a request that the Connection's proxy refused with 407, as every check says it.
const ParallelPresses = 2
ParallelPresses is slack.parallel_presses: the most Slack presses one process handles at a time, over all its Slack Connections and both event modes; the others wait for a slot, already confirmed.
const PressDeadline = 30 * time.Second
PressDeadline bounds each press from the moment it is handed over to the end of its Command, its wait for a slot included, so that a Command stuck on the database frees its slot and the presses waiting behind it end: the 30 s that Mattermost waits for the answer to a press (F-032), which bounds a Mattermost press the same way. The answer to the person keeps its own Budget, so that a press that ran out of time, waiting or running, is still told that it failed.
const RequestTolerance = 5 * time.Minute
RequestTolerance is slack.request_tolerance: the longest a press's X-Slack-Request-Timestamp may be from Muster's real clock, either way, as Slack recommends (F-104).
const SocketDomain = "slack.com"
SocketDomain is the domain whose hosts a Socket Mode address may be on outside `muster dev` (C-24.FR-9, ADR-0015).
const (
StepDryProbe = "dry_probe"
)
The step of the dry probe of a Slack Connection (C-24.FR-2) and the messages of what answered it.
const StepMessage = "message"
StepMessage is the step of a test and the item of a preview that is the Root message.
Variables ¶
var ErrNoConnection = errors.New("no such slack connection")
ErrNoConnection is a press for a Connection that is unknown, deleted or not a Slack one.
var ErrNoTarget = errors.New("the destination has no slack connection")
ErrNoTarget is a Destination that has no Slack Connection to post through: it, or its Connection, no longer exists, or it is not a Slack Destination.
var RequiredScopes = []string{"chat:write", "channels:read", "groups:read", "im:write", "users:read",
"users:read.email"}
RequiredScopes are the scopes the bot token needs, and no other (C-24.FR-1).
Functions ¶
func MissingScopesMessage ¶
MissingScopesMessage is the message of the step scopes for the scopes the bot token lacks.
func NewCallback ¶
func NewCallback(cfg CallbackConfig) http.Handler
NewCallback is the callback of the presses of Slack Connections in http mode, slackInteraction (C-24.FR-9, AC-11), which answers every request itself. The raw body is read, up to MaxRequestBytes, before anything else; a larger one is answered 400. Nothing changes before a request is authenticated: an unknown or deleted Connection, one in socket mode, an X-Slack-Request-Timestamp further than the Tolerance from the real clock, either way, and an X-Slack-Signature that is not `v0=` and the hex HMAC-SHA256 of `v0:<timestamp>:<raw body>` under the Connection's Slack signing secret, compared in constant time, are all answered 401 with one body, so that the endpoint reveals nothing about which Connections exist. An authenticated body without a `payload` field that is a JSON object is answered 400. Any other request is answered 200 with an empty body at once, and its payload goes to Presses in the process's context, since Slack waits only 3 seconds (F-093). Each refusal logs slack_press_rejected with its reason, never the signature, the secret, the headers or the body; a Connection that cannot be read is answered 500 and logs slack_press as failed. 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 ValidChannelID ¶
ValidChannelID reports whether id names a channel a Slack Destination can post to, as entered: no lower case, no #.
Types ¶
type Adapter ¶
Adapter is the delivery adapter of Slack Destinations (C-24.FR-4 to FR-8): Publish, Update and Reply, called by the delivery worker and the interactive path only, in the client class of their Call, and Check, the Destination check of C-24.FR-3, which the Broken probe runs in the delivery class (C-24.FR-15). Version is the version the context of a Root message names. The message id is the Root message's `ts`.
func (*Adapter) Check ¶
Check runs the Destination check of C-24.FR-3 at once, in the client class of c: one conversations.info, which posts nothing. The Broken probe calls it in the delivery class.
func (*Adapter) LengthLimit ¶
LengthLimit is the longest text of a section, which the body of a Root message is shortened to (F-076).
func (*Adapter) Publish ¶
func (a *Adapter) Publish(ctx context.Context, c delivery.Call, m delivery.Message) delivery.Outcome
Publish posts the Root message m with chat.postMessage, with the Mentions of a Loud call in its `text` and top section; its link is that of the workspace the Connection's check stored.
func (*Adapter) Reply ¶
func (a *Adapter) Reply(ctx context.Context, c delivery.Call, root delivery.Root, m delivery.Message) delivery.Outcome
Reply posts m into the Thread of root with chat.postMessage and its `thread_ts`, never broadcast (C-24.FR-6), with the Mentions of a Loud call. A reply that Slack posted into the channel instead — its root was deleted before any reply (F-091) — is deleted at once with chat.delete, and the Root message is gone (C-24.FR-8).
func (*Adapter) Update ¶
func (a *Adapter) Update(ctx context.Context, c delivery.Call, messageID string, m delivery.Message) delivery.Outcome
Update edits the Root message messageID to m with chat.update, Quiet and without Mentions (C-24.FR-6). An edit answered message_not_found reads the channel in the same client class: the Root message was deleted when the bot is still a member of a channel that is not archived, and the answer is Fatal otherwise (C-24.FR-8).
type Answer ¶
type Answer struct {
Status int
RetryAfter time.Duration
HasRetryAfter bool
Error string
Needed string
}
Answer is what Classify reads of an answer: its status, 0 without one; its Retry-After, valid when HasRetryAfter; and the `error` and `needed` of an `ok: false` answer.
type Args ¶
Args are the arguments of a method: sent as a JSON object to the write methods, and form-encoded to the others, where each is text, a bool, an int or int64, or a list of texts joined with commas.
type AuthTest ¶
type AuthTest struct {
URL string `json:"url"`
Team string `json:"team"`
User string `json:"user"`
TeamID string `json:"team_id"`
UserID string `json:"user_id"`
BotID string `json:"bot_id"`
AppID string `json:"app_id"`
}
AuthTest is the answer of auth.test (F-072): with a bot token the workspace's address and name, the bot's name and user id, the workspace's id and the bot's id; with an app-level token the app's id alone.
type Bindings ¶
type Bindings interface {
SlackPressBinding(ctx context.Context, connectionID int64, channelID, ts string) (delivery.SlackBinding, error)
SlackTestDestination(ctx context.Context, connectionID int64, publicID, channelID string) (delivery.Destination,
bool, error)
}
Bindings are delivery's reads of what a press is bound to; *delivery.Service implements them.
type Bot ¶
type Bot struct {
ID string `json:"id"`
Name string `json:"name"`
AppID string `json:"app_id"`
UserID string `json:"user_id"`
Deleted bool `json:"deleted"`
}
Bot is a bot as bots.info answers it: its id, name, app and user.
type CallbackConfig ¶
type CallbackConfig struct {
Connections Connections
// Presses handle each confirmed press after its answer.
Presses Handler
// Real is the real clock that X-Slack-Request-Timestamp is checked against (S-020).
Real clock.Clock
// Tolerance is slack.request_tolerance; zero is RequestTolerance.
Tolerance time.Duration
// Base is the context of the process that a press is handled in once it is answered: never the request's, which
// ends with its answer, and not one that the start of a shutdown ends, since the shutdown drains the presses and
// ends Base with its grace period; nil takes the request's without its end.
Base context.Context //nolint:containedctx // the process context the presses outlive their requests in
Log *logging.Logger
}
CallbackConfig is what the callback of presses in http mode needs.
type Channel ¶
type Channel struct {
ID string `json:"id"`
Name string `json:"name"`
IsMember bool `json:"is_member"`
IsArchived bool `json:"is_archived"`
IsPrivate bool `json:"is_private"`
}
Channel is a channel as conversations.info and conversations.list answer it (F-098): its id and name, masked, whether the bot is a member, whether it is archived and whether it is private.
type ChannelCheck ¶
type ChannelCheck struct {
Name string
Message string
Code string
MissingScopes []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, for missing_scope, the scopes Slack named as needed; 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 CheckChannel ¶
func CheckChannel(ctx context.Context, c *Client, run Runner, channelID, botName string) (ChannelCheck, error)
CheckChannel runs the Destination check of the channel channelID through run (C-24.FR-3): one conversations.info, which posts nothing, in the class of the Call run makes it in — the interactive path for a save and for "Check", the background class for muster doctor, the delivery class for the Broken probe. An archived channel is channel_archived; one the bot is not a member of is bot_not_in_channel with the text that names botName, the bot's handle, or without a name when it is empty; a token Slack refuses is token_invalid, a missing scope missing_scope with the scopes of `needed`, an unknown channel, a deleted one or a private one without the bot channel_not_found; a request without an answer, or one the outbound address policy refuses, has the code of delivery.FailureCode with the text of delivery.FailureMessage; any other answer is request_failed with Slack's masked error. Its error is the runner's own.
type ChannelList ¶
type ChannelList struct {
Channels []ListedChannel
Truncated bool
}
ChannelList is the channel list of a Slack Connection: its channels by name, and whether channels were left after the last page it read.
func Channels ¶
Channels lists the channels of C-24.FR-3 through run: conversations.list of the public and private channels that are not archived, page by page, at most maxChannelPages pages, keeping those the bot is a member of whose name contains q, regardless of case, by name; Truncated when a page was left. A page answered 429 stops the list at once with a *RateLimitedError and waits for nothing: the interactive path holds the Connection's limiter for its Retry-After. A page that failed otherwise is a *ListFailedError. Its other errors are the runner's own.
type Check ¶
Check is the result of a connection check: its steps, and what it found once the step token passed.
func RunCheck ¶
func RunCheck(ctx context.Context, c *Client, run Runner, realClock clock.Clock, mode string) (Check, error)
RunCheck runs the connection check of c in the event mode mode (C-24.FR-2) through run, timing each request on the real clock:
- token — auth.test with the bot token: the bot and its workspace; a token Slack refuses is token_invalid, and one that is not a bot's — not_allowed_token_type, or an answer without bot_id — wrong_token_type;
- scopes — no request: the x-oauth-scopes of that answer must name every scope of RequiredScopes, else missing_scope names the missing ones in their order, in the message and in MissingScopes;
- app_token, in socket mode only — apps.connections.open with the app-level token first, so that a token that is not an app-level one, not_allowed_token_type, is wrong_token_type; the check opens no WebSocket and drops the answer's url unread. Then auth.test with the app-level token answers the app's id, which must equal the bot's app_id that bots.info answers, else app_mismatch.
A step that fails skips the steps after it. Any other failure has the code of delivery.FailureCode: without an answer with the text of delivery.FailureMessage — the name of Slack's address, which is left out through a proxy whose own name is the one that did not resolve, the TLS failure, the time, the proxy — or the error's own; with an answer request_failed with Slack's masked error. A RetryAfter goes back to run as it is, so that the interactive path holds the Connection's limiter. Its error is the runner's own.
type Class ¶
type Class string
Class is the class of a failed call (C-24.FR-8), decided by Slack's `error` and, without one, by the status.
const ( ClassRetryAfter Class = "retry_after" ClassTransient Class = "transient" ClassFatal Class = "fatal" ClassMarkupRejected Class = "markup_rejected" ClassGoneCandidate Class = "gone_candidate" ClassUnknown Class = "unknown" )
The classes of a failed call. A Gone-candidate is a `chat.update` that answered message_not_found: the adapter reads the channel before it takes the Root message for deleted (adapter.go).
type Classification ¶
Classification is how a call is classified: its class, the wait of a RetryAfter, and the reason, Slack's `error` with the scopes `needed` names, masked and untrusted. The zero value is a call that succeeded.
func Classify ¶
func Classify(a Answer) Classification
Classify classifies an answer (C-24.FR-8): without an answer Transient; 429 RetryAfter for its Retry-After, Transient without one; 408 and 5xx Transient; otherwise by the `error` of an `ok: false` answer, whatever its status (F-070) — internal_error, fatal_error, service_unavailable and request_timeout Transient; a refused token, the wrong kind of token, a missing scope and a channel the bot cannot use Fatal; markup Slack refused MarkupRejected; message_not_found a Gone-candidate; any other error Unknown — and without an error a 2xx succeeded and any other status is Unknown. The reason is the error with the scopes `needed` names.
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client calls Slack's Web API for one Connection, in the interactive, delivery and background client classes; the outbound client of a class is built on its first call.
func NewClient ¶
NewClient builds the client of the Connection s, checking its settings with the interactive class. Its requests go to BaseURL, or to what s.Route answers for the bot token when it answers. Both tokens, the Slack signing secret and the proxy password are registered for redaction.
func (*Client) AppAuthTest ¶
AppAuthTest calls auth.test with the app-level token: the app's id, masked.
func (*Client) AuthTest ¶
AuthTest calls auth.test with the bot token: the bot and its workspace, masked.
func (*Client) Base ¶
Base is the base URL the client's requests go to: BaseURL, or the Route's answer.
func (*Client) BotsInfo ¶
BotsInfo calls bots.info with the bot token for the bot botID (scope users:read): its app, masked.
func (*Client) CallApp ¶
func (c *Client) CallApp(ctx context.Context, class outbound.Class, method string, args Args) Result
CallApp calls method in class with the app-level token.
func (*Client) ConversationsInfo ¶
func (c *Client) ConversationsInfo(ctx context.Context, class outbound.Class, channelID string) (Channel, Result)
ConversationsInfo calls conversations.info with the bot token for the channel channelID (scopes channels:read and groups:read): the channel, masked, which answers even when the bot is not a member of it.
func (*Client) ConversationsList ¶
func (c *Client) ConversationsList(ctx context.Context, class outbound.Class, cursor string) ([]Channel, Result)
ConversationsList calls conversations.list with the bot token for one page of the public and private channels the bot sees that are not archived, from cursor, empty for the first page: the channels, masked; the cursor of the next page is the Result's NextCursor, empty after the last one.
func (*Client) DialSocket ¶
func (c *Client) DialSocket(ctx context.Context, address logging.Secret) (*outbound.WebSocket, error)
DialSocket opens the Socket Mode connection at address through outbound.DialWebSocket in the background class, with the Connection's proxy, and lets it read messages of up to MaxRequestBytes. An address socketTarget does not accept is not dialled. Its error never shows the address's query, nor the client's secrets.
func (*Client) OpenSocket ¶
OpenSocket calls apps.connections.open with the app-level token in the background class (F-100) and returns the address of a new Socket Mode connection, with its single-use ticket, as a Secret: only an address that socketTarget accepts, built anew. Its record in the Request log has the ticket masked by its shape, and the answer's body is dropped from the Result, so that the ticket travels no further. An answer without an address is unknown, and so is one whose address the client may not connect to, without showing it.
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 runs; *groups.Service implements them.
type Conn ¶
Conn is a Slack Connection as its presses need it: its ids, its event mode and its Web API client, which answers the people who pressed.
type Connections ¶
type Connections interface {
SlackPressConnection(ctx context.Context, publicID string) (Conn, logging.Secret, error)
}
Connections find the Connection a press names with its Slack signing secret: a Slack Connection in socket mode, or in http mode without a stored secret, comes with an empty one, which the callback refuses; one that is unknown, deleted or not a Slack one is ErrNoConnection. *connections.Service implements it.
type Handler ¶
Handler takes the payload of each press the callback confirmed and handles it in the background, in ctx; *Presses implements it.
type Identity ¶
type Identity struct {
TeamID string
TeamName string
TeamURL string
BotID string
BotUserID string
BotName string
AppID string
}
Identity is what a check found: the workspace's id, name and address, the bot's id, user id and name from the step token, and the app's id from the step app_token, empty without it.
type LinkBots ¶
type LinkBots struct {
Conns LinkConnections
Path Path
}
LinkBots run the calls of an Account link through the bot of a Slack Connection (C-24.FR-12, C-18.FR-11): the lookup of the account by email or name and the bot's direct messages, on the interactive path, never as a delivery. They implement accountlinks.SlackBots.
func (LinkBots) Session ¶
func (l LinkBots) Session(ctx context.Context, publicID string, f func(ctx context.Context, b accountlinks.SlackBot) error) error
Session takes one limiter token of the Connection publicID on the interactive path and runs f with its bot; a 429 with Retry-After that a direct message of f gets holds the Connection, as for any chat.postMessage, while one of a lookup holds nothing, since Slack limits each method per app and workspace (F-099). A Connection that is unknown, deleted or not a Slack one is accountlinks.ErrNoConnection; no token within the budget is a *delivery.LimitedError and runs nothing.
type LinkConnections ¶
type LinkConnections interface {
// SlackLinkConnection is the Slack Connection publicID with its client, in either event mode; one that is unknown,
// deleted or not a Slack Connection is ErrNoConnection.
SlackLinkConnection(ctx context.Context, publicID string) (Conn, error)
}
LinkConnections find the Slack Connection of an Account link, declared by their consumer; *connections.Service implements them.
type Links ¶
type Links interface {
Lookup(ctx context.Context, identitySpace, externalID string) (accountlinks.User, error)
}
Links map a Slack account to its User; *accountlinks.Service implements them.
type ListFailedError ¶
ListFailedError is a page of the channel list that failed otherwise: Text is what answered, masked and untrusted.
func (*ListFailedError) Error ¶
func (e *ListFailedError) Error() string
type ListedChannel ¶
ListedChannel is a channel of the channel list: its id, its name and whether it is private.
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 Presses ¶
type Presses struct {
// Bindings find the message a press names among the Connection's deliveries.
Bindings Bindings
// Links map the account that pressed to its User.
Links Links
// Commands run the Commands of presses through the dispatcher.
Commands Commands
// Roles are the Permissions of each Role, which a linked User presses with.
Roles auth.Roles
// Keys verify the signed action ids: the Keyring.
Keys buttons.Keys
// Path is the interactive path, which the answers take.
Path Path
// Budget is delivery.interactive_budget, within which each way of an answer is made or fails; zero is
// delivery.InteractiveBudget.
Budget time.Duration
// Business is the business clock, from which a Snooze lasts its duration.
Business clock.Clock
// PublicURL is MUSTER_PUBLIC_URL, the base of the profile link of an account without an Account link.
PublicURL string
// Parallel is slack.parallel_presses; zero is ParallelPresses.
Parallel int
Log *logging.Logger
// contains filtered or unexported fields
}
Presses is the one handler of Slack presses for both event modes (C-24.FR-10): the callback of http mode hands it every press it confirmed through Go, and Socket Mode every interactive envelope. It handles at most Parallel presses at a time; the others wait for a slot, already confirmed, MaxWaitingPresses at most, and each press has PressDeadline for its wait and its Command. Each press is verified, bound to its message, run as the linked User through the dispatcher and, when there is something to say, answered privately (answers.go); it is logged as slack_press. Wait lets the shutdown drain the presses handed to Go.
func (*Presses) Go ¶
Go handles the interaction payload of the Connection c, which Slack already had confirmed, in the background, in ctx: a context of the process, never a request's, whose end ends the press as failed. Wait waits for it.
func (*Presses) Handle ¶
Handle handles the interaction payload of the Connection c, which Slack already had confirmed (C-24.FR-10): another kind of interaction than block_actions is ignored at once; a press waits for a slot, is verified, bound and run within PressDeadline, and once its slot is free again the person who pressed is answered, when there is something to say (C-24.FR-11), unless ctx has ended, so that nothing can reach Slack any more. A press that finds MaxWaitingPresses presses waiting is dropped and not answered; one whose deadline ends while it waits is answered that it failed. The answer is made once: a failure of both its ways is logged, never retried. A panic is a failed press, logged without its value.
type Probe ¶
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 ¶
RunDryProbe makes the dry probe of c through run (C-24.FR-2): `POST <base>auth.test` without any token, which Slack answers 200 with `{"ok":false,"error":"not_authed"}` (F-070), timed on the real clock, on a client that may have no token and sends none. It passes on that answer and otherwise names what answered: not_slack for an answer that is not that JSON, unexpected_status for JSON with another status, and the code of delivery.FailureCode with the text of delivery.FailureMessage without an answer, without Slack's name through a proxy, whose own name is the one that did not resolve. A RetryAfter 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. Its error is the runner's own.
type RateLimitedError ¶
RateLimitedError is a page of the channel list that Slack answered 429: the list stops, and the caller answers that it can be asked again after RetryAfter, zero when Slack named no wait.
func (*RateLimitedError) Error ¶
func (e *RateLimitedError) Error() string
type Result ¶
type Result struct {
Status int
Classification Classification
Error outbound.Untrusted
ErrorCode string
Needed []string
Warning outbound.Untrusted
NextCursor string
Scopes []string
AcceptedScopes []string
Body []byte
Network string
Detail string
Blocked bool
}
Result is how a call ended; a zero Classification is success. Error is the masked, untrusted text of a failure: Slack's `error`, with `needed` when it names one, or what outbound reports; ErrorCode is Slack's `error` alone, masked, empty without an `ok: false` answer, and Needed the scopes its `needed` names, masked. Warning is the `warning` of the answer and NextCursor its `response_metadata.next_cursor`; Scopes are the token's scopes that the answer's x-oauth-scopes names, kept on a failure too, and AcceptedScopes those of x-accepted-oauth-scopes. Body is the answer of a call that succeeded, or of an `ok: false` answer, which a test step shows, with the secrets replaced. Network is what failed when the call got no answer (outbound.Network*), Detail its masked text, and Blocked whether the outbound address policy refused the address.
func (Result) CheckCode ¶
CheckCode is the check code of a failed call that its step does not name: that of delivery.FailureCode, which is request_failed for any call that got an answer; empty for a call that succeeded.
func (Result) Outcome ¶
Outcome is the Result for delivery (C-24.FR-8): RetryAfter holds the whole Connection, since Slack limits each method per app and workspace (F-099); Transient, Fatal and MarkupRejected are themselves; a Gone-candidate is unknown until the adapter reads the channel, and Unknown is unknown.
type Route ¶
Route names the base URL a Connection's requests go to instead of BaseURL, by its bot token: under `muster dev` the fake Slack server for its published tokens; an empty answer is Slack.
type Runner ¶
type Runner func(ctx context.Context, f func(ctx context.Context, c delivery.Call) delivery.Outcome) (delivery.Outcome, error)
Runner makes one 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.
type Settings ¶
type Settings struct {
BotToken logging.Secret
AppToken logging.Secret
SigningSecret logging.Secret
Proxy *outbound.Proxy
Owner outbound.Owner
Route Route
}
Settings are a Connection as its client needs it: the bot token, the app-level token, empty without one, and the Slack signing secret, which is never sent and is registered for redaction only; 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 SocketConn ¶
SocketConn is a Slack Connection in socket mode as its Socket Mode connection needs it: the Connection with its client, its version, and Err when its client could not be built.
type SocketSource ¶
type SocketSource interface {
SocketConnections(ctx context.Context) ([]SocketConn, error)
RecordSocketHello(ctx context.Context, c SocketConn, otherConnections int) error
}
SocketSource lists the Slack Connections in socket mode that are not deleted and records what a hello of one counted: the connections of its Slack app beyond those the Leader holds, for the version its socket read. *connections.Service implements it.
type Sockets ¶
type Sockets struct {
// Source lists the Connections and records their hellos.
Source SocketSource
// Presses handle the presses of the interactive envelopes; *Presses implements it.
Presses Handler
// Recorder keeps the records of the envelopes; nil records nothing.
Recorder requestlog.EnvelopeRecorder
// Base is the context of the process the presses are handled in, as the callback's: the start of a shutdown does
// not end it, the end of its grace period does, so that a press Slack considers delivered is still handled after
// the Leader stops; nil takes Run's context without its end.
Base context.Context //nolint:containedctx // the process context the presses outlive the Leader in
// Real is the real clock that times the confirmations.
Real clock.Clock
Log *logging.Logger
// HelloTimeout, BackoffBase, BackoffCap and Every replace HelloTimeout, SocketBackoffBase, SocketBackoffCap and
// SocketReadInterval when they are set.
HelloTimeout, BackoffBase, BackoffCap, Every time.Duration
// contains filtered or unexported fields
}
Sockets holds the Socket Mode connections of an Organization's Slack Connections, the Leader task slack_socket_mode (C-24.FR-9, ADR-0007). Run holds one connection for each Connection in socket mode, and starts again for each new version of it: before each connection apps.connections.open answers its address, which is dialled through the Connection's proxy; the connection must say hello within HelloTimeout, is pinged every PingInterval and closed when a pong takes longer than PingTimeout. Every envelope with an envelope_id is confirmed with {"envelope_id": …} on its socket at once, before anything else is done with it; an interactive one is then handed to Presses in Base, as the callback of http mode hands over its presses, and any other type is ignored; each is recorded in the Request log. A disconnect warning or refresh_requested opens the next connection, with its hello, before the old one is closed; link_disabled, too_many_websockets, a failed dial, a missing hello and a connection that ended back off by slack.socket_backoff — at least as long as a Retry-After of apps.connections.open asks, up to the cap, and reset once a connection has lasted socketSettled or by a planned refresh — and log slack_socket_failed, with the address's query masked; nothing counts them and nothing becomes Broken. Each hello stores, through Source, the connections of the app it counts beyond those held, and then logs slack_socket_connected, and slack_socket_shared when there are any; a holder's writer does it in order, within helloWriteTimeout, so that a slow store holds up neither the frames nor the hello, and a count the next hello replaces before it is stored is left out. A socket Muster lets go is closed with a normal closure, cut after closeGrace without an answer; a broken one is closed at once.
Running it on two replicas at once is safe: each press reaches one of their connections.
func (*Sockets) Run ¶
Run holds the connections until ctx ends, which is when the Leader loses the lock or stops, and closes every one of them at once before it returns, after their readers, pingers and records have ended: a holder starts for each Connection in socket mode, starts again when the Connection's version changes and stops when it leaves socket mode, is deleted, or its client cannot be built — logged once for each version. The Connections are read again on Wake and every Every. When the first read fails Run returns its error, so that the Leader task runs again; a later one is logged as leader_task_failed, keeps the holders, which hold versions read before, and is tried again at the next wake or Every.
type Step ¶
type Step struct {
Name string
OK bool
Skipped bool
Latency time.Duration
Via string
Message string
Code string
MissingScopes []string
}
Step is one step of a check: whether it passed or was skipped, its latency on the real clock and path, and when it failed what answered, in English, with its code, which clients translate, and with CodeMissingScope the scopes the bot token lacks, which clients name in their own words (D396). The step scopes makes no request and has no latency.
type Target ¶
type Target struct {
Client *Client
ConnectionID int64
ConnectionPublicID string
ChannelID string
TeamURL string
BotName string
}
Target is where a Slack Destination posts: the client of its Connection, the Connection's id and public_id, the channel id of the Destination, the workspace's address that the Connection's last passing check stored — empty before one — which the link to a message starts with, and the bot's name that check stored, which the text of bot_not_in_channel names.
type Targets ¶
Targets find the Target of a Destination by its id, declared by their consumer; *connections.Service implements them. A Destination without one 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 Slack 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 sending anything, the Root message of the source of in as the Slack Destination would receive it (C-24.FR-13, C-16.FR-4): the item message, the body of chat.postMessage as JSON, Quiet, with the buttons a test message would carry, whose presses change nothing; its request is that call with the bot token masked.