Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changelog.d/added-rfc-notify-cards.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
- Render RFC lifecycle notices as Discord summary-card embeds alongside transition text when `rfc_format: card` is configured on the designated announcer.
46 changes: 31 additions & 15 deletions src/cmd/hive/rfcnotify_wire.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ const rfcRepoVisibilityTTL = time.Hour
// poster, built once from the config that enabled them.
type rfcNotifyState struct {
sweeper *rfcnotify.Sweeper
pub rfcnotify.Publisher
post rfcnotify.Poster
// channel the poster was built for; a config change rebuilds it.
channel string
Expand All @@ -45,9 +46,11 @@ type rfcNotifyState struct {
// statePath is rfcNotifyStatePath in production; tests point it at a
// temp dir.
statePath string
// newPoster builds the Discord poster; nil means discordRFCPoster.
// newPoster builds the Discord poster; nil builds botPublisher.
// Tests inject a recorder.
newPoster func(token, channel string) rfcnotify.Poster
// newPublisher builds the Discord publisher; nil adapts newPoster or builds botPublisher.
newPublisher func(token, channel string) rfcnotify.Publisher
}

// rfcNotifyState lazily builds the boot's notice state.
Expand Down Expand Up @@ -99,10 +102,6 @@ func (s *rfcNotifyState) ensure(cfg *config.Config, repos int, logger *slog.Logg
if !ok {
return false
}
newPoster := s.newPoster
if newPoster == nil {
newPoster = discordRFCPoster(logger)
}
gates := rfcNotifyGatesFor(cfg, repos)
if s.sweeper == nil || s.gates != gates {
s.sweeper = rfcnotify.NewSweeper(rfcnotify.Options{
Expand All @@ -117,20 +116,36 @@ func (s *rfcNotifyState) ensure(cfg *config.Config, repos int, logger *slog.Logg
})
s.gates = gates
}
if s.post == nil || s.channel != channel {
s.post = newPoster(token, channel)
if s.pub == nil || s.channel != channel {
if s.newPublisher != nil {
s.pub = s.newPublisher(token, channel)
s.post = func(content string) error { return s.pub.Post(content) }
} else if s.newPoster != nil {
p := s.newPoster(token, channel)
s.post = p
s.pub = p
} else {
bot := discord.NewBot(discord.Config{Token: token}, logger)
s.pub = botPublisher{bot: bot, channel: channel}
s.post = func(content string) error { return bot.SendMessageTo(channel, content) }
}
s.channel = channel
}
return true
}

// discordRFCPoster posts through the bot token to the RFC channel without
// starting the command bot.
func discordRFCPoster(logger *slog.Logger) func(token, channel string) rfcnotify.Poster {
return func(token, channel string) rfcnotify.Poster {
bot := discord.NewBot(discord.Config{Token: token}, logger)
return func(content string) error { return bot.SendMessageTo(channel, content) }
}
// botPublisher adapts discord.Bot to rfcnotify.Publisher.
type botPublisher struct {
bot *discord.Bot
channel string
}

func (p botPublisher) Post(content string) error {
return p.bot.SendMessageTo(p.channel, content)
}

func (p botPublisher) PostCard(content string, embed rfcnotify.Embed) (string, error) {
return p.bot.SendEmbedTo(p.channel, content, embed)
}

type rfcRepoVisibility struct {
Expand Down Expand Up @@ -321,6 +336,7 @@ func rfcNotifyIssues(snaps []github.IssueSnapshot) []rfcnotify.Issue {
out = append(out, rfcnotify.Issue{
Repo: s.Repo, Number: s.Number, Title: s.Title, URL: s.URL, Author: s.Author,
State: s.State, StateReason: s.StateReason, Labels: s.Labels, CreatedAt: s.CreatedAt,
Body: s.Body,
})
}
return out
Expand All @@ -337,7 +353,7 @@ func runRFCNotifySweep(ctx context.Context, src rfcnotify.Source, repos int, cfg
if src == nil || state == nil || !state.ensure(cfg, repos, logger) {
return rfcnotify.Result{}
}
res, err := state.sweeper.Run(ctx, src, state.post)
res, err := state.sweeper.Run(ctx, src, state.pub)
if err != nil {
logger.Warn("rfc notify sweep failed", "error", err)
return res
Expand Down
73 changes: 73 additions & 0 deletions src/cmd/hive/rfcnotify_wire_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -451,3 +451,76 @@ func TestRunRFCNotifySweepRFCPRs(t *testing.T) {
t.Fatalf("merge: %+v posted=%q", res, posted)
}
}

func TestRFCNotifyIssues_MapsBody(t *testing.T) {
snaps := []github.IssueSnapshot{
{
Repo: "o/r",
Number: 42,
Title: "RFC: Test",
Body: "| Target | v5 |\n\n## Summary\nHello",
},
}
issues := rfcNotifyIssues(snaps)
if len(issues) != 1 {
t.Fatalf("len(issues) = %d, want 1", len(issues))
}
if issues[0].Body != snaps[0].Body {
t.Errorf("Body = %q, want %q", issues[0].Body, snaps[0].Body)
}
}

type testCardPublisher struct {
posted []string
cards []rfcnotify.Embed
}

func (p *testCardPublisher) Post(content string) error {
p.posted = append(p.posted, content)
return nil
}

func (p *testCardPublisher) PostCard(content string, embed rfcnotify.Embed) (string, error) {
p.cards = append(p.cards, embed)
return "msg-id-1", nil
}

func TestRFCNotifyWire_CardFormatPostsEmbed(t *testing.T) {
logger := slog.New(slog.NewTextHandler(io.Discard, nil))
cfg := &config.Config{
Notifications: config.NotificationsConfig{
Discord: &config.DiscordConfig{
BotToken: "tok",
RFCChannelID: "chan",
RFCFormat: "card",
RFCAnnouncer: true,
},
},
}
pub := &testCardPublisher{}
state := &rfcNotifyState{
statePath: filepath.Join(t.TempDir(), "rfc-notify.json"),
newPublisher: func(token, channel string) rfcnotify.Publisher {
return pub
},
}
src := &rfcNotifyFakeSource{
open: []rfcnotify.Issue{{Repo: "o/r", Number: 1, Title: "Existing RFC", State: "open", Labels: []string{"rfc"}}},
}
ctx := context.Background()
runRFCNotifySweep(ctx, src, 1, cfg, nil, state, logger)

body := "| Field | Value |\n| --- | --- |\n| Target | v5 |\n| Status | Proposal |\n\n## Summary\nTest summary\n\n## Decisions for maintainers\n1. Question\n"
src.updated = []rfcnotify.Issue{
{Repo: "o/r", Number: 2, Title: "RFC: Rich Card", URL: "https://x/2", State: "open", CreatedAt: time.Now().Add(time.Hour), Body: body},
}
forcePoll(state)
runRFCNotifySweep(ctx, src, 1, cfg, nil, state, logger)

if len(pub.cards) != 1 {
t.Fatalf("cards = %d, want 1", len(pub.cards))
}
if pub.cards[0].Title != "#2 RFC: Rich Card" {
t.Errorf("card.Title = %q", pub.cards[0].Title)
}
}
2 changes: 1 addition & 1 deletion src/docs/notifications.md
Original file line number Diff line number Diff line change
Expand Up @@ -210,7 +210,7 @@ These keys sit next to `rfc_channel_id`. All of them default off, and with none

| Key | Default | Effect |
| --- | --- | --- |
| `rfc_format` | `""` (= `line`) | `line` posts one line per transition. `card` selects rich mode; card rendering lands in a later change. Any other value is a config error. |
| `rfc_format` | `""` (= `line`) | `line` posts one line per transition. `card` posts the transition text (including a linked RFC for accepted documents) alongside a Discord summary card (embed) with target, status, scrubbed summary, open-decision count and colour by state (held grey, needs-decision amber, ready green, closed completed blue, closed not-planned dark); malformed bodies fall back to the line. Any other value is a config error. |
| `rfc_threads` | `false` | Rich mode: one Discord thread per RFC (rendering lands later). |
| `rfc_announcer` | `false` | Marks this hive as the one designated announcer for `rfc_channel_id`. Rich mode posts only from the announcer. |
| `rfc_backlink_comment` | `false` | Parsed now; a later change uses it to comment the thread link back on the RFC. |
Expand Down
5 changes: 4 additions & 1 deletion src/pkg/dashboard/api_event_triggers_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -174,7 +174,10 @@ func TestEventTriggersRejectInvalidAndUnpersistedRules(t *testing.T) {
t.Fatalf("failed persistence accepted: %d %s", failed.Code, failed.Body.String())
}
cfg.SourcePath = t.TempDir()
config.RuntimeConfigFile, config.DashboardOverlayFile = t.TempDir(), t.TempDir()
// Save removes an empty runtime-path directory and retries successfully.
// A missing parent keeps the fallback unwritable after that retry.
unwritable := filepath.Join(t.TempDir(), "missing")
config.RuntimeConfigFile, config.DashboardOverlayFile = filepath.Join(unwritable, "runtime"), filepath.Join(unwritable, "overlay")
failed = putEventTriggers(s, `{"rules":[]}`, version)
if failed.Code != http.StatusInternalServerError || !reflect.DeepEqual(cfg.TriggerRulesSnapshot(), before) ||
strings.Contains(failed.Body.String(), cfg.SourcePath) {
Expand Down
145 changes: 128 additions & 17 deletions src/pkg/discord/bot.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"log/slog"
"net/http"
"net/url"
"strconv"
"strings"
"sync"
"time"
Expand Down Expand Up @@ -98,6 +99,7 @@ type Bot struct {
mu sync.RWMutex
logger *slog.Logger
client *http.Client
sleep func(time.Duration)

msgQueue chan msgItem
lastState *statusSnapshot
Expand Down Expand Up @@ -193,45 +195,154 @@ func (b *Bot) SendMessage(content string) error {
return b.SendMessageTo(b.channelID, content)
}

// Embed represents a Discord embed object.
type Embed struct {
Title string `json:"title,omitempty"`
Description string `json:"description,omitempty"`
URL string `json:"url,omitempty"`
Color int `json:"color,omitempty"`
Author *EmbedAuthor `json:"author,omitempty"`
Fields []EmbedField `json:"fields,omitempty"`
Footer *EmbedFooter `json:"footer,omitempty"`
Timestamp string `json:"timestamp,omitempty"`
}

// EmbedAuthor is the author field of a Discord embed.
type EmbedAuthor struct {
Name string `json:"name,omitempty"`
URL string `json:"url,omitempty"`
IconURL string `json:"icon_url,omitempty"`
}

// EmbedField is a name/value field within a Discord embed.
type EmbedField struct {
Name string `json:"name"`
Value string `json:"value"`
Inline bool `json:"inline,omitempty"`
}

// EmbedFooter is the footer field of a Discord embed.
type EmbedFooter struct {
Text string `json:"text"`
IconURL string `json:"icon_url,omitempty"`
}

const maxDiscordRetryAfter = 5 * time.Second

// SendMessageTo posts content to an arbitrary channel the bot token can
// write to, bypassing the status channel and the drain queue. It works on a
// Bot that was never started, so a feature that only needs to post (RFC
// lifecycle notices, pkg/rfcnotify) can share the token without running the
// command loops.
func (b *Bot) SendMessageTo(channelID, content string) error {
if strings.TrimSpace(channelID) == "" {
return fmt.Errorf("discord send: channel id not configured")
payload := map[string]any{
"content": content,
}
_, err := b.postMessage(channelID, payload)
return err
}

// SendEmbedTo posts an embed (and optional content) to an arbitrary channel
// the bot token can write to. It always sets allowed_mentions: {parse: []} so
// user text never pings roles, users or @everyone, and returns the created
// message ID.
func (b *Bot) SendEmbedTo(channelID, content string, embed Embed) (string, error) {
payload := map[string]any{
"content": content,
"allowed_mentions": map[string]any{"parse": []string{}},
"embeds": []Embed{embed},
}
if content != "" {
payload["content"] = content
}
return b.postMessage(channelID, payload)
}

func (b *Bot) postMessage(channelID string, payload map[string]any) (string, error) {
if strings.TrimSpace(channelID) == "" {
return "", fmt.Errorf("discord send: channel id not configured")
}
if payload == nil {
payload = make(map[string]any)
}
payload["allowed_mentions"] = map[string]any{"parse": []string{}}
data, err := json.Marshal(payload)
if err != nil {
return err
return "", err
}

url := fmt.Sprintf("%s/channels/%s/messages", discordAPIBase, channelID)
req, err := http.NewRequest(http.MethodPost, url, bytes.NewReader(data))
if err != nil {
return err
}

req.Header.Set("Authorization", "Bot "+b.token)
req.Header.Set("Content-Type", "application/json")
doRequest := func() (*http.Response, []byte, error) {
req, err := http.NewRequest(http.MethodPost, url, bytes.NewReader(data))
if err != nil {
return nil, nil, err
}

resp, err := b.client.Do(req)
req.Header.Set("Authorization", "Bot "+b.token)
req.Header.Set("Content-Type", "application/json")

resp, err := b.client.Do(req)
if err != nil {
return nil, nil, fmt.Errorf("discord send: %w", err)
}
defer func() { _ = resp.Body.Close() }()

body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, nil, fmt.Errorf("discord read body: %w", err)
}
return resp, body, nil
}

resp, body, err := doRequest()
if err != nil {
return fmt.Errorf("discord send: %w", err)
return "", err
}

if resp.StatusCode == http.StatusTooManyRequests {
retryAfter := parseDiscordRetryAfter(resp.Header.Get("Retry-After"), body)
if retryAfter <= 0 {
retryAfter = 100 * time.Millisecond
}
if retryAfter > maxDiscordRetryAfter {
retryAfter = maxDiscordRetryAfter
}
if b.sleep != nil {
b.sleep(retryAfter)
} else {
time.Sleep(retryAfter)
}
resp, body, err = doRequest()
if err != nil {
return "", err
}
}
defer func() { _ = resp.Body.Close() }()

if resp.StatusCode >= 400 {
body, _ := io.ReadAll(resp.Body)
return fmt.Errorf("discord API %d: %s", resp.StatusCode, string(body))
return "", fmt.Errorf("discord API %d: %s", resp.StatusCode, string(body))
}

return nil
var created struct {
ID string `json:"id"`
}
if err := json.Unmarshal(body, &created); err == nil && created.ID != "" {
return created.ID, nil
}
return "", nil
}

func parseDiscordRetryAfter(header string, body []byte) time.Duration {
var rl struct {
RetryAfter float64 `json:"retry_after"`
}
if err := json.Unmarshal(body, &rl); err == nil && rl.RetryAfter > 0 {
return time.Duration(rl.RetryAfter * float64(time.Second))
}
if header = strings.TrimSpace(header); header != "" {
if f, err := strconv.ParseFloat(header, 64); err == nil && f > 0 {
return time.Duration(f * float64(time.Second))
}
}
return 0
}

func (b *Bot) enqueue(content string) {
Expand Down
Loading
Loading