slackapp

package
v0.32.2 Latest Latest
Warning

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

Go to latest
Published: Oct 31, 2026 License: Apache-2.0 Imports: 30 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 slackapp is the factory's Slack App (factory interfaces F9): a sponsored principal that drafts and files issues from a thread, and a webhook subscriber that keeps the thread told. It never answers an approval and never relays room text.

Index

Constants

This section is empty.

Variables

View Source
var ErrSignature = errors.New("slackapp: request not signed by Slack")

ErrSignature is any request that does not verify; it never says which check failed.

View Source
var ErrThreadTooLong = errors.New("slackapp: slack: the thread is too long")

ErrThreadTooLong is a thread with more pages than Thread follows: its latest draft cannot be known, so nothing is edited or filed from it.

View Source
var ErrUnknownTool = errors.New("slackapp: the broker does not offer this tool")

ErrUnknownTool is the broker without the tool asked: the self-serve link is off there.

Functions

This section is empty.

Types

type App

type App struct {
	Slack       Slack
	Broker      BrokerAPI
	Threads     Threads
	Verifier    Verifier
	WebhookKeys func() ([][]byte, error)
	TeamID      string
	BotUserID   string
	RoomsURL    string
	Channels    map[string]Channel
	Async       func(func()) // runs an event's handling after the 200; nil means go f()
	Now         func() time.Time
	Metrics     Recorder
	Logger      *slog.Logger
	// contains filtered or unexported fields
}

App is the flows: a mention drafts, the draft's author amends it with replies in its thread, a maintainer's check mark files, the broker's webhooks tell the thread. A thread reply is read only to amend an unfiled draft; none is ever a command and no approval is answered (invariant 8).

func (*App) Events

func (a *App) Events() http.Handler

Events is the events listener's handler: the signature first, nothing read before it.

func (*App) Webhooks

func (a *App) Webhooks() http.Handler

Webhooks is the webhooks listener's handler: the delivery is verified with the broker's keys (read at use) before it is decoded. It answers once the thread is told, so a Slack failure is a 502 and the broker's at-least-once retry brings the event back.

type Broker

type Broker struct {
	URL    string // the broker's base URL, from config only
	Tokens *Tokens
	HC     *http.Client // httpx.New in production
}

Broker is the room-broker's MCP endpoint, called as the App's own principal. It never calls tasks/*: the App follows a room through webhooks.

func (Broker) IssueDraft

func (b Broker) IssueDraft(ctx context.Context, d Draft) (Draft, error)

IssueDraft asks the broker to judge a draft against the issue template.

func (Broker) RunCreate

func (b Broker) RunCreate(ctx context.Context, c RunCreate) (RunResult, error)

RunCreate files the run. Its arguments are run_create's schema exactly: `text` is the draft's body and dataClass is always public.

func (Broker) SlackLinkCode

func (b Broker) SlackLinkCode(ctx context.Context, team, user, handle, name string) (string, error)

SlackLinkCode asks the broker for a one-time link for the Slack user, handle and name shown on the page. The answer must be the link page with one code, or it is not passed on to the user.

func (b Broker) SlackUnlink(ctx context.Context, team, user string) (bool, error)

SlackUnlink asks the broker to remove the Slack user's link; unlinked is false when none was.

type BrokerAPI

type BrokerAPI interface {
	IssueDraft(ctx context.Context, d Draft) (Draft, error)
	RunCreate(ctx context.Context, c RunCreate) (RunResult, error)
	SlackLinkCode(ctx context.Context, team, user, handle, name string) (string, error)
	SlackUnlink(ctx context.Context, team, user string) (bool, error)
}

BrokerAPI is what the flows call on the broker; Broker has it, and the test fakes it.

type Channel

type Channel struct {
	Repositories []string `json:"repositories"`
	MaxCostUSD   float64  `json:"maxCostUSD"`
}

Channel is a channel the App serves: the repositories a draft there may name, and the max_cost a ✅ there sends.

type Config

type Config struct {
	TeamID            string             `json:"teamID"`
	BotUserIDFile     string             `json:"botUserIDFile"`
	BotTokenFile      string             `json:"botTokenFile"`
	SigningSecretFile string             `json:"signingSecretFile"`
	WebhookKeyFile    string             `json:"webhookKeyFile"`
	BrokerURL         string             `json:"brokerURL"`
	RoomsURL          string             `json:"roomsURL"`
	IssuerURL         string             `json:"issuerURL"`
	ClientIDFile      string             `json:"clientIDFile"`
	ClientSecretFile  string             `json:"clientSecretFile"`
	ProjectIDFile     string             `json:"projectIDFile"`
	Namespace         string             `json:"namespace"`
	Channels          map[string]Channel `json:"channels"`
	// The three listeners (M11): Slack's events (public), the broker's webhooks (cluster only),
	// and metrics with the probes. Defaults :8080, :8081 and :9090; a test passes 127.0.0.1:0.
	EventsAddr   string `json:"eventsAddr,omitempty"`
	WebhooksAddr string `json:"webhooksAddr,omitempty"`
	OpsAddr      string `json:"opsAddr,omitempty"`
}

Config is the App's config file, loaded strictly as the broker's config is.

func LoadConfig

func LoadConfig(path string) (Config, error)

LoadConfig reads, strictly decodes, defaults and validates the file at path.

type ConfigMapThreads

type ConfigMapThreads struct {
	C         client.Client
	Namespace string
	Now       func() time.Time
	MaxBytes  int          // the encoded map's cap; defaults to 900 KiB (a ConfigMap holds 1 MiB)
	Logger    *slog.Logger // optional
}

ConfigMapThreads keeps the map in one ConfigMap: a key per room, the thread as JSON.

func (ConfigMapThreads) Get

func (m ConfigMapThreads) Get(ctx context.Context, room string) (Thread, bool, error)

Get is the thread a room was filed from, if any.

func (ConfigMapThreads) Put

func (m ConfigMapThreads) Put(ctx context.Context, room string, t Thread) error

Put records the thread and drops every entry older than 30 days. A conflict (another replica or a restart racing) re-reads and retries, three attempts in all.

type Draft

type Draft struct{ Repo, Title, Body string }

Draft is an issue as typed in a thread: the repository, the title and the body.

func ApplyReply

func ApplyReply(d Draft, text string) (out Draft, changed bool)

ApplyReply amends a draft with a reply in its thread: `Title:` replaces the title (the area rule applies again), `Should:` / `Expected:` and `Acceptance:` / `Done when:` / `Check:` replace their sections, any other text is appended to what is wrong. changed is false when the reply holds nothing to apply.

func ParseMention

func ParseMention(text, botUserID string, repos []string) (Draft, error)

ParseMention shapes a mention into a draft (R22): the text starts with <@botUserID>, line 1's rest is "[<owner/repo>] <title>" and composeBody turns the remaining lines into the template the factory's validator holds (the App adapts, the validator stays strict).

Where the channel serves exactly one repository, line 1 is the title alone (the repository named first, bare or in brackets, is still accepted), and a title that starts with something owner/name-shaped stays a title. Otherwise only is "".

type DraftPayload

type DraftPayload struct {
	Repo   string `json:"repo"`
	Title  string `json:"title"`
	Body   string `json:"body"`
	SHA256 string `json:"sha256"`
	// Author is the Slack user who wrote the mention: the only one whose thread replies edit the
	// draft. Rev counts the drafts the thread has had, 1 for the first.
	Author string `json:"author,omitempty"`
	Rev    int    `json:"rev,omitempty"`
}

DraftPayload is the checked draft and its hash, sha256 hex of repo, title and body joined by NUL.

type Message

type Message struct {
	TS, ThreadTS, User, Text string
	Metadata                 *Metadata
}

Message is a Slack message as the ✅ flow reads it (M9). User is who posted it: the App's own bot user for its drafts.

type Metadata

type Metadata struct {
	EventType    string       `json:"event_type"`
	EventPayload DraftPayload `json:"event_payload"`
}

Metadata is the draft the App attaches to its own message (R23); Slack keeps it off the visible text.

type Recorder

type Recorder interface {
	Request(ctx context.Context, route, outcome string)
}

Recorder counts requests for factory_slack_requests_total{route, outcome}.

type Refused

type Refused string

Refused is a tool's refusal ("rejected: <code>"), shown in the thread as is.

func (Refused) Error

func (r Refused) Error() string

type RunCreate

type RunCreate struct {
	Draft
	MaxCostUSD float64
	OnBehalfOf string // slack:<team>/<user>
	Ref        string // slack/<team>/<channel>/<thread_ts>
	Key        string // the idempotency key
}

RunCreate is a draft filed as a run for the person who asked.

type RunResult

type RunResult struct {
	Room      string
	Issue     int
	Duplicate bool
	Sponsor   string
}

RunResult is what run_create answered: Sponsor is the GitHub login the factory filed as, "" when it did not say.

type Slack

type Slack interface {
	// Thread is the thread's messages, oldest first, the parent included, with their metadata.
	Thread(ctx context.Context, channel, threadTS string) ([]Message, error)
	Post(ctx context.Context, channel, threadTS, text string, meta *Metadata) (ts string, err error)
	Message(ctx context.Context, channel, ts string) (Message, error)
	// PostEphemeral is a message only user sees, in channel (and threadTS, when set).
	PostEphemeral(ctx context.Context, channel, user, threadTS, text string) error
	// UserName is the user's handle and display name, for the link page only; "" when Slack does
	// not say.
	UserName(ctx context.Context, user string) (handle, display string, err error)
}

Slack is the Web API calls the App makes.

type SlackClient

type SlackClient struct {
	BaseURL string // https://slack.com/api/ when empty
	Token   func() string
	HC      *http.Client // httpx.New in production
	Logger  *slog.Logger // Slack's error code on every failed call; discarded when nil
}

SlackClient is Slack's Web API over httpx. Token is read at use, so a rotated Secret applies.

func (*SlackClient) Message

func (c *SlackClient) Message(ctx context.Context, channel, ts string) (Message, error)

Message is conversations.replies for one ts (M9): the draft is a thread reply, which conversations.history never returns. The answer may also hold the thread's parent, so it keeps only the message whose ts is the one asked.

func (*SlackClient) Post

func (c *SlackClient) Post(ctx context.Context, channel, threadTS, text string, meta *Metadata) (string, error)

Post is chat.postMessage: no unfurling, the metadata attached when there is one.

func (*SlackClient) PostEphemeral

func (c *SlackClient) PostEphemeral(ctx context.Context, channel, user, threadTS, text string) error

PostEphemeral is chat.postEphemeral (chat:write): text that only user sees, never stored in the channel's history.

func (*SlackClient) Thread

func (c *SlackClient) Thread(ctx context.Context, channel, threadTS string) ([]Message, error)

Thread is conversations.replies for a thread, followed over a few pages at most.

func (*SlackClient) UserName

func (c *SlackClient) UserName(ctx context.Context, user string) (string, string, error)

UserName is users.info (users:read): the handle, unique in the workspace, and the profile's display name, else its real name (both set by the user). Without the scope Slack answers missing_scope, an error the caller shrugs off.

type Thread

type Thread struct {
	Channel string    `json:"channel"`
	TS      string    `json:"ts"`
	At      time.Time `json:"at"`
}

Thread is where a room filed from Slack is followed (R25). At is when it was put, for the 30-day prune.

type Threads

type Threads interface {
	Put(ctx context.Context, room string, t Thread) error
	Get(ctx context.Context, room string) (Thread, bool, error)
}

Threads is the thread map, the ConfigMap factory-slack-threads in production.

type Tokens

type Tokens struct {
	Fetch func(ctx context.Context) (*oauth2.Token, error)
	// contains filtered or unexported fields
}

Tokens caches the App's client-credentials token until it expires or the broker refuses it (L9): clientcredentials' own TokenSource reuses a token until it expires and cannot be told that the broker refused it. Fetch should go through httpx (oauth2.HTTPClient in the context).

func (*Tokens) Invalidate

func (s *Tokens) Invalidate()

Invalidate drops the cached token after a 401, so the retry fetches a new one.

func (*Tokens) Token

func (s *Tokens) Token(ctx context.Context) (string, error)

Token is the cached access token, fetched when there is none or it expired.

type Verifier

type Verifier struct {
	Secret func() string
	Now    func() time.Time
}

Verifier checks Slack's v0 request signature (R27). Secret is read at use: a rotation is a Secret update and a restart-free reload.

func (Verifier) Body

func (v Verifier) Body(r *http.Request) ([]byte, error)

Body reads and verifies the request's body, returning it only when Slack signed it.

Jump to

Keyboard shortcuts

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