220 lines
8.5 KiB
Go
220 lines
8.5 KiB
Go
package daemon
|
|
|
|
import (
|
|
"context"
|
|
"strings"
|
|
|
|
"github.com/samcharles93/archie-core/internal/config"
|
|
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
|
"github.com/samcharles93/archie-core/internal/domain/workintake"
|
|
"github.com/samcharles93/archie-core/internal/forge"
|
|
"github.com/samcharles93/archie-core/internal/taskstate"
|
|
)
|
|
|
|
func (d *Daemon) issueSources(ctx context.Context) []IssueSource {
|
|
return d.IssueSources(ctx)
|
|
}
|
|
|
|
// pollIssuesWithConfig returns the repo's issues the dispatch rule makes
|
|
// work, using the given forge client and dispatch config. complete is false when any part of the poll failed or was skipped, so
|
|
// the result must not be read as the whole eligible set.
|
|
func (d *Daemon) pollIssuesWithConfig(ctx context.Context, fg forge.Forge, cfg config.Config, repo config.Repo) (issues []forge.Issue, complete bool) {
|
|
labelled := func() ([]forge.Issue, bool) {
|
|
// A label trigger needs a non-empty label or it would match every open issue.
|
|
if cfg.Label == "" {
|
|
d.Log.ErrorContext(ctx, "label trigger configured with an empty label; refusing to poll (an empty label matches every open issue)", "repo", repo.FullName())
|
|
return nil, false
|
|
}
|
|
issues, err := fg.IssuesWithLabel(ctx, repo.Owner, repo.Name, cfg.Label)
|
|
if err != nil {
|
|
d.Log.ErrorContext(ctx, "label poll failed", "repo", repo.FullName(), "err", err)
|
|
return nil, false
|
|
}
|
|
return issues, true
|
|
}
|
|
assigned := func() ([]forge.Issue, bool) {
|
|
if cfg.BotUser == "" {
|
|
d.Log.ErrorContext(ctx, "assignee trigger needs the connection's account; refusing to poll", "repo", repo.FullName())
|
|
return nil, false
|
|
}
|
|
issues, err := fg.AssignedIssues(ctx, repo.Owner, repo.Name, cfg.BotUser)
|
|
if err != nil {
|
|
d.Log.ErrorContext(ctx, "assigned poll failed", "repo", repo.FullName(), "err", err)
|
|
return nil, false
|
|
}
|
|
return issues, true
|
|
}
|
|
switch cfg.Dispatch.Trigger {
|
|
case "label":
|
|
return labelled()
|
|
case "either":
|
|
byAssignee, assignedOK := assigned()
|
|
byLabel, labelledOK := labelled()
|
|
seen := map[int]bool{}
|
|
for _, is := range byAssignee {
|
|
seen[is.Number] = true
|
|
}
|
|
issues = byAssignee
|
|
for _, is := range byLabel {
|
|
if !seen[is.Number] {
|
|
issues = append(issues, is)
|
|
}
|
|
}
|
|
return issues, assignedOK && labelledOK
|
|
default: // "assignee" (default)
|
|
return assigned()
|
|
}
|
|
}
|
|
|
|
// poll discovers work through every organisation connection, resolved
|
|
// afresh each cycle so a rotated credential or a new connection applies to
|
|
// the next poll.
|
|
func (d *Daemon) poll(ctx context.Context) error {
|
|
var failed []string
|
|
room := d.Cfg.Get().IntakePerPass
|
|
for _, source := range d.issueSources(ctx) {
|
|
if !d.identityActive(ctx, source.Identity) {
|
|
continue
|
|
}
|
|
cfg := d.Cfg.Get()
|
|
cfg.BotUser = source.BotUser
|
|
if source.Dispatch.Trigger != "" {
|
|
cfg.Dispatch, cfg.Label = source.Dispatch, source.Label
|
|
}
|
|
tag := string(source.Identity)
|
|
for _, repo := range source.Repos {
|
|
issues, complete := d.pollIssuesWithConfig(ctx, source.Forge, cfg, repo)
|
|
if complete {
|
|
d.withdrawUnpolled(ctx, repo, tag, dispatchRule(cfg), issues)
|
|
} else {
|
|
failed = append(failed, repo.FullName())
|
|
}
|
|
d.publishDiscovered(ctx, source.Forge, cfg, repo, issues, tag, &room)
|
|
}
|
|
}
|
|
return passFailed("issue poll", failed)
|
|
}
|
|
|
|
// rememberPoll records a repo's latest eligible set and returns the previous
|
|
// one, reporting whether it was taken under the same rule.
|
|
func (d *Daemon) rememberPoll(key string, current polledIssues) (polledIssues, bool) {
|
|
d.lastPolledMu.Lock()
|
|
defer d.lastPolledMu.Unlock()
|
|
previous, seen := d.lastPolled[key]
|
|
if d.lastPolled == nil {
|
|
d.lastPolled = map[string]polledIssues{}
|
|
}
|
|
d.lastPolled[key] = current
|
|
return previous, seen && previous.rule == current.rule
|
|
}
|
|
|
|
// withdrawUnpolled declines the queued or running work of an identity's
|
|
// issues in repo that a complete poll no longer returns: the issue was
|
|
// closed, unlabelled or unassigned.
|
|
func (d *Daemon) withdrawUnpolled(ctx context.Context, repo config.Repo, identity, rule string, polled []forge.Issue) {
|
|
eligible := make(map[int]bool, len(polled))
|
|
for _, is := range polled {
|
|
eligible[is.Number] = true
|
|
}
|
|
// Only an issue the same rule found eligible last time and no longer
|
|
// finds was withdrawn. A changed label, trigger or bot user, or the first
|
|
// poll after a restart, only records the new set: tasks picked up under
|
|
// the old rule were not withdrawn by anyone.
|
|
previous, sameRule := d.rememberPoll(identity+"\x00"+repo.FullName(), polledIssues{rule: rule, eligible: eligible})
|
|
if !sameRule {
|
|
return
|
|
}
|
|
active, err := d.Store.TasksPage(ctx, storecontract.TaskPage{
|
|
Statuses: []string{taskstate.Queued, taskstate.Running}, Limit: 500,
|
|
})
|
|
if err != nil {
|
|
d.Log.WarnContext(ctx, "withdrawal check: active tasks unavailable", "repo", repo.FullName(), "err", err)
|
|
return
|
|
}
|
|
for _, t := range active {
|
|
if t.Owner != repo.Owner || t.Repo != repo.Name || t.Identity != identity ||
|
|
!t.IsForgeBacked() || t.PRNumber > 0 || eligible[t.IssueNumber] || !previous.eligible[t.IssueNumber] {
|
|
continue
|
|
}
|
|
if err := d.WithdrawTask(ctx, t.ID, "the issue is no longer assigned, labelled or open"); err != nil {
|
|
d.Log.WarnContext(ctx, "withdraw task", "task", t.ID, "err", err)
|
|
}
|
|
}
|
|
}
|
|
|
|
// publishDiscovered publishes a repo's discovered issues until the pass has
|
|
// created its cap of tasks. room is what is left of the cap; the issues left
|
|
// over are found again by the next poll, because an issue with a task is
|
|
// skipped and one without is not. A cap of zero or less is no cap.
|
|
func (d *Daemon) publishDiscovered(ctx context.Context, fg forge.Forge, cfg config.Config, repo config.Repo, issues []forge.Issue, identity string, room *int) {
|
|
capped := *room > 0
|
|
for _, is := range issues {
|
|
if capped && *room == 0 {
|
|
d.Log.InfoContext(ctx, "intake cap reached; remaining issues wait for the next poll", "repo", repo.FullName())
|
|
return
|
|
}
|
|
if d.pollNATS(ctx, fg, cfg, repo, is, strings.Join(is.Labels, ","), identity) && capped {
|
|
*room--
|
|
}
|
|
}
|
|
}
|
|
|
|
// pollNATS publishes a discovered issue to NATS and reports whether it created
|
|
// a task.
|
|
func (d *Daemon) pollNATS(ctx context.Context, fg forge.Forge, cfg config.Config, repo config.Repo, is forge.Issue, labels, identity string) bool {
|
|
// Read-only existence check prevents rediscovering an existing task.
|
|
existing, err := d.Store.TaskByIssue(ctx, repo.Owner, repo.Name, is.Number)
|
|
if err != nil {
|
|
d.Log.ErrorContext(ctx, "task lookup failed", "repo", repo.FullName(), "issue", is.Number, "err", err)
|
|
return false
|
|
}
|
|
if existing != nil {
|
|
return false
|
|
}
|
|
// An issue whose label-routed workflow the identity's org disabled must
|
|
// not queue a task at all. Skip without acknowledging, so a later poll
|
|
// picks the issue up again if the workflow is re-enabled.
|
|
if routed, disabled, err := d.disabledRoutedWorkflow(ctx, labels, identity); err != nil {
|
|
d.Log.WarnContext(ctx, "routed workflow check failed; publishing anyway", "repo", repo.FullName(), "issue", is.Number, "err", err)
|
|
} else if disabled {
|
|
d.Log.InfoContext(ctx, "issue skipped: its routed workflow is disabled for this org", "repo", repo.FullName(), "issue", is.Number, "workflow", routed)
|
|
return false
|
|
}
|
|
// Classify and encode here: the envelope, its routing kind and its
|
|
// subject belong to the work-intake domain, not to the transport.
|
|
parsed := workintake.SplitLabels(labels)
|
|
task := workintake.TaskEnvelope{
|
|
Owner: repo.Owner,
|
|
Repo: repo.Name,
|
|
Number: is.Number,
|
|
Title: is.Title,
|
|
Body: is.Body,
|
|
Labels: parsed,
|
|
Identity: identity,
|
|
Kind: workintake.KindForLabels(parsed),
|
|
}
|
|
if err := d.PublishTask(ctx, task); err != nil {
|
|
d.Log.ErrorContext(ctx, "task publish failed", "repo", repo.FullName(), "issue", is.Number, "err", err)
|
|
return false
|
|
}
|
|
d.acknowledge(ctx, fg, cfg, repo, is)
|
|
return true
|
|
}
|
|
|
|
// acknowledge posts the pickup reaction
|
|
// using fg -- the forge client that owns repo (identity-scoped or root) --
|
|
// and the ack reaction from cfg, the dispatch config that owns this poll.
|
|
func (d *Daemon) acknowledge(ctx context.Context, fg forge.Forge, cfg config.Config, repo config.Repo, is forge.Issue) {
|
|
d.Log.InfoContext(ctx, "issue queued", "repo", repo.FullName(), "issue", is.Number, "title", is.Title)
|
|
if ack := cfg.Dispatch.AckReaction; ack != "" {
|
|
if err := fg.React(ctx, repo.Owner, repo.Name, is.Number, ack); err != nil {
|
|
d.Log.WarnContext(ctx, "ack reaction failed", "issue", is.Number, "err", err)
|
|
}
|
|
}
|
|
}
|
|
|
|
// dispatchRule identifies the rule a poll selects issues by.
|
|
func dispatchRule(cfg config.Config) string {
|
|
return cfg.Dispatch.Trigger + "\x00" + cfg.Label + "\x00" + cfg.BotUser
|
|
}
|