Просмотр исходного кода

refactor: keep configuration issues in armature-health

Configuration issues are now stored by armature-health's in-memory store
instead of OliveTin's own lists. The checks stay in configcheck, and the
issue list, Diagnostics page, -syntaxcheck output and logs are unchanged.
No database is needed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
jamesread 2 дней назад
Родитель
Сommit
dee253bd00

+ 2 - 1
service/go.mod

@@ -10,6 +10,7 @@ exclude github.com/alecthomas/go-check-sumtype v0.5.0
 require (
 	connectrpc.com/connect v1.21.1
 	github.com/Masterminds/semver v1.5.0
+	github.com/MicahParks/jwkset v0.11.4
 	github.com/MicahParks/keyfunc/v3 v3.9.1
 	github.com/PaesslerAG/jsonpath v0.1.1
 	github.com/alexedwards/argon2id v1.0.0
@@ -20,6 +21,7 @@ require (
 	github.com/golang-jwt/jwt/v5 v5.3.1
 	github.com/golangci/golangci-lint/v2 v2.15.0
 	github.com/google/uuid v1.6.0
+	github.com/jamesread/armature-health/v2 v2.0.0
 	github.com/jamesread/golure v0.0.0-20261111213547-dc225fc15a30
 	github.com/knadh/koanf/parsers/yaml v1.1.1
 	github.com/knadh/koanf/providers/env v1.1.0
@@ -75,7 +77,6 @@ require (
 	github.com/ClickHouse/clickhouse-go-linter v1.2.1 // indirect
 	github.com/Djarvur/go-err113 v0.1.1 // indirect
 	github.com/Masterminds/semver/v3 v3.5.0 // indirect
-	github.com/MicahParks/jwkset v0.11.4 // indirect
 	github.com/Microsoft/go-winio v0.6.4 // indirect
 	github.com/MirrexOne/unqueryvet v1.5.4 // indirect
 	github.com/OpenPeeDeeP/depguard/v2 v2.3.0 // indirect

+ 20 - 0
service/go.sum

@@ -54,6 +54,8 @@ dev.gaijin.team/go/exhaustruct/v5 v5.2.0 h1:HZB49Fshn8qHJCi9VzYtrcnR1jbLteRHXfnQ
 dev.gaijin.team/go/exhaustruct/v5 v5.2.0/go.mod h1:5IshpqhgGdKIrF8lBmi3M6YKmI7T3hMzAL9nrflko88=
 dev.gaijin.team/go/golib v0.9.0 h1:6cA78yIjdgimPQgaf0W9oHhaFDHxeOyhf2wmdRoDJTc=
 dev.gaijin.team/go/golib v0.9.0/go.mod h1:J6xujTcJ4o8QcgApNjGTxpz2tg9uNjrwFJQczoM0VYE=
+filippo.io/edwards25519 v1.1.1 h1:YpjwWWlNmGIDyXOn8zLzqiD+9TyIlPhGFG96P39uBpw=
+filippo.io/edwards25519 v1.1.1/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4=
 github.com/4meepo/tagalign v1.4.4 h1:052JDGj2pBORc6NkD30dDXpsUpoYszDeUwr9/5YZuVA=
 github.com/4meepo/tagalign v1.4.4/go.mod h1:00WwRjiuSbrRJnSVeGWPLp2epS5Q/l4UEy0apLLS37c=
 github.com/Abirdcfly/dupword v0.1.8 h1:SrhcUuGsROBuChFxHALRYzyyPODWn9zwghmzPvD9Cd8=
@@ -209,6 +211,8 @@ github.com/docker/go-connections v0.8.2 h1:9d9DEokx5W7qlr0shkFXIxEA7+TTD+llwzcyk
 github.com/docker/go-connections v0.8.2/go.mod h1:no1qkHdjq7kLMGUXYAduOhYPSJxxvgWBh7ogVvptn3Q=
 github.com/docker/go-units v0.5.0 h1:69rxXcBk27SvSaaxTtLh/8llcHD8vYHT7WSdRZ/jvr4=
 github.com/docker/go-units v0.5.0/go.mod h1:fgPhTUdO+D/Jk86RDLlptpiXQzgHJF7gydDDbaIK4Dk=
+github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
+github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
 github.com/ettle/strcase v0.2.0 h1:fGNiVF21fHXpX1niBgk0aROov1LagYsOwV/xqKDKR/Q=
 github.com/ettle/strcase v0.2.0/go.mod h1:DajmHElDSaX76ITe3/VHVyMin4LWSJN5Z909Wp+ED1A=
 github.com/expr-lang/expr v1.17.8 h1:W1loDTT+0PQf5YteHSTpju2qfUfNoBt4yw9+wOEU9VM=
@@ -240,6 +244,8 @@ github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
 github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
 github.com/go-quicktest/qt v1.102.0 h1:HSQxCeh5YZH3EL3W39ixjtyaEhcWSXQHtHnMBzSs474=
 github.com/go-quicktest/qt v1.102.0/go.mod h1:p4lGIVX+8Wa6ZPNDvqcxq36XpUDLh42FLetFU7odllI=
+github.com/go-sql-driver/mysql v1.9.3 h1:U/N249h2WzJ3Ukj8SowVFjdtZKfu9vlLZxjPXV1aweo=
+github.com/go-sql-driver/mysql v1.9.3/go.mod h1:qn46aNg1333BRMNU69Lq93t8du/dwxI64Gl8i5p1WMU=
 github.com/go-task/slim-sprig/v3 v3.0.0 h1:sUs3vkvUymDpBKi3qH1YSqBQk9+9D/8M2mN1vB6EwHI=
 github.com/go-task/slim-sprig/v3 v3.0.0/go.mod h1:W848ghGpv3Qj3dhTPRyJypKRiqCdHZiAzKg9hl15HA8=
 github.com/go-toolsmith/astcast v1.1.0 h1:+JN9xZV1A+Re+95pgnMgDboWNVnIMMQXwfBwLRPgSC8=
@@ -337,6 +343,8 @@ github.com/hexops/gotextdiff v1.0.3 h1:gitA9+qJrrTCsiCl7+kh75nPqQt1cx4ZkudSTLoUq
 github.com/hexops/gotextdiff v1.0.3/go.mod h1:pSWU5MAI3yDq+fZBTazCSJysOMbxWL1BSow5/V2vxeg=
 github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
 github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
+github.com/jamesread/armature-health/v2 v2.0.0 h1:rJO1zFqPKL6Ji5OeyEWlAeL5qYjdIyLpKgntMAGgcr8=
+github.com/jamesread/armature-health/v2 v2.0.0/go.mod h1:PqpA8CV9tJvwjjXaiNBhOVKZHPaeJs4Krga4DngYsKI=
 github.com/jamesread/golure v0.0.0-20261111213547-dc225fc15a30 h1:OH3LW5inwllequ0Saiv/y7mvfGWSmEE0rLROIEW5IBs=
 github.com/jamesread/golure v0.0.0-20261111213547-dc225fc15a30/go.mod h1:eanAcCk4sl2dM5bax4jeSCexnVYRF2IhhtQ4B+Wx8DU=
 github.com/jdx/go-netrc v1.0.0 h1:QbLMLyCZGj0NA8glAhxUpf1zDg6cxnWgMBbjq40W0gQ=
@@ -439,6 +447,8 @@ github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq
 github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ=
 github.com/nakabonne/nestif v0.3.1 h1:wm28nZjhQY5HyYPx+weN3Q65k6ilSBxDb8v5S81B81U=
 github.com/nakabonne/nestif v0.3.1/go.mod h1:9EtoZochLn5iUprVDmDjqGKPofoUEBL8U4Ngq6aY7OE=
+github.com/ncruces/go-strftime v1.0.0 h1:HMFp8mLCTPp341M/ZnA4qaf7ZlsbTc+miZjCLOFAw7w=
+github.com/ncruces/go-strftime v1.0.0/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls=
 github.com/nishanths/exhaustive v0.17.1 h1:zlwR7GV/UqKrm3AJdeXqldUTSsbyfdqS8f/m0oMYLD0=
 github.com/nishanths/exhaustive v0.17.1/go.mod h1:/nBwAMRn2QmCjWQ3PiJ939yRSwvWLKSa21L2C6Tp84E=
 github.com/nishanths/predeclared v0.3.1 h1:qb/HpkPb0bF0drRBFkTyKY1ZRWcilc6gtxaBZGgn8H8=
@@ -497,6 +507,8 @@ github.com/quic-go/quic-go v0.65.0 h1:BJQSjdTvLPLmWtaCupUphRbgxgpZhdO/GMpr9Eoe3B
 github.com/quic-go/quic-go v0.65.0/go.mod h1:RAro2j2yN9a9EiPACLHT9IB2NXCvGQmmo/alT0yYI0w=
 github.com/raeperd/recvcheck v0.3.2 h1:uEL/XDkUASomQfB/KbepaVsVnyKqNSeqNHHX0au9VAk=
 github.com/raeperd/recvcheck v0.3.2/go.mod h1:1GYvabo+pT440BrQ5iT7Vf1JZl15rCYslKq6W+NV7HI=
+github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
+github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
 github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ=
 github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=
 github.com/robfig/cron/v3 v3.0.1 h1:WdRxkvbJztn8LMz/QEvLN5sBU+xKpSqwwUO1Pjr4qDs=
@@ -772,6 +784,14 @@ gotest.tools/v3 v3.5.2 h1:7koQfIKdy+I8UTetycgUqXWSDwpgv193Ka+qRsmBY8Q=
 gotest.tools/v3 v3.5.2/go.mod h1:LtdLGcnqToBH83WByAAi/wiwSFCArdFIUV/xxN4pcjA=
 honnef.co/go/tools v0.8.2 h1:+jPbCzuYxYrcoOvCecYUFDj+XJQRmzIhJmlbpps21Zk=
 honnef.co/go/tools v0.8.2/go.mod h1:xG1Q4n+mg3bKZrO6RWFA9jFlkqplflmDRHGeuexiLDs=
+modernc.org/libc v1.77.1 h1:Ct8j47QtiZ1Enj2DtFXQtUqrPCAjdCmPjtCuvrYQ0Hs=
+modernc.org/libc v1.77.1/go.mod h1:87/pZ4L6nD1zqW4nItuS12YO7hN1igAah34xjnQo/W0=
+modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU=
+modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg=
+modernc.org/memory v1.12.1 h1:nFMiWrpStgZczNl6XI9GnIk/rWhYIyHGUaR04pGbp9g=
+modernc.org/memory v1.12.1/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw=
+modernc.org/sqlite v1.60.1 h1:/blz53O951KWFOso4QQvEs/Fq6cDBKLtMVrYNSeJVKw=
+modernc.org/sqlite v1.60.1/go.mod h1:1dIoEagfDE72QytD5scH1lxARtaUgKgHC/NuApA27r0=
 mvdan.cc/gofumpt v0.12.0 h1:1Lbudkz2kpM9Cjz2pL4M19u7q+GaEhCTNf7N9mfpcho=
 mvdan.cc/gofumpt v0.12.0/go.mod h1:SmBHHrljiZu/uoypeKup3rFzP6eoC9UwCp2iH5E3jZA=
 mvdan.cc/unparam v0.0.0-20261102141913-394cd0a56cd5 h1:+w/oD0+NrvT39TwXLC5ElQte8LwPcFuTWdbJ+98LeAE=

+ 7 - 6
service/internal/configcheck/rebuild.go

@@ -16,18 +16,19 @@ import (
 	"gopkg.in/yaml.v3"
 )
 
-// Rebuild clears and rebuilds the issue list from the current config, entity
-// state, sticky load-time reports, runtime reports, and any extra issues provided by callers
-// (for example literal argument default validation from the executor).
+// Rebuild rebuilds the issue list from the current config, entity state, sticky
+// load-time reports, and any extra issues provided by callers (for example literal
+// argument default validation from the executor). Runtime reports are kept.
 func Rebuild(cfg *config.Config, extra ...configissues.Issue) {
 	if cfg == nil {
-		configissues.Replace(append(configissues.CopyRuntime(), extra...))
+		configissues.ReplaceLoadIssues(nil)
+		configissues.Replace(extra)
 		return
 	}
 
+	configissues.ReplaceLoadIssues(configissues.CopySticky())
+
 	collected := make([]configissues.Issue, 0)
-	collected = append(collected, configissues.CopySticky()...)
-	collected = append(collected, configissues.CopyRuntime()...)
 	collected = append(collected, collectActionGroupIssues(cfg)...)
 	collected = append(collected, collectAclReferenceIssues(cfg)...)
 	collected = append(collected, collectArgumentIssues(cfg)...)

+ 165 - 0
service/internal/configissues/health.go

@@ -0,0 +1,165 @@
+package configissues
+
+import (
+	"slices"
+	"sort"
+	"strings"
+	"sync"
+
+	health "github.com/jamesread/armature-health/v2"
+)
+
+const (
+	attrCode         = "code"
+	attrActionID     = "action_id"
+	attrActionTitle  = "action_title"
+	attrArgumentName = "argument_name"
+	attrSource       = "source"
+	attrConfigFile   = "config_file"
+)
+
+var (
+	orderMu sync.Mutex
+	// orderBySource keeps the position of each issue in the last list set for a
+	// source, so List keeps the order the issues were collected in.
+	orderBySource = map[string]map[string]int{}
+)
+
+// issueKey identifies the same problem across rebuilds. Severity is left out
+// so that a change in severity updates the issue rather than raising a new one.
+func issueKey(issue Issue) string {
+	return strings.Join([]string{
+		issue.Code,
+		issue.ActionID,
+		issue.ActionTitle,
+		issue.ArgumentName,
+		issue.Source,
+		issue.ConfigFile,
+		issue.Message,
+	}, "\x00")
+}
+
+// armature-health treats anything that is not a warning or an error as info.
+// OliveTin has always treated such issues as warnings.
+func healthSeverity(severity string) health.Severity {
+	if severity == SeverityError {
+		return health.SeverityError
+	}
+	return health.SeverityWarning
+}
+
+func toHealthIssue(issue Issue) health.Issue {
+	return health.Issue{
+		Key:      issueKey(issue),
+		Severity: healthSeverity(issue.Severity),
+		Title:    issue.Message,
+		Attributes: map[string]string{
+			attrCode:         issue.Code,
+			attrActionID:     issue.ActionID,
+			attrActionTitle:  issue.ActionTitle,
+			attrArgumentName: issue.ArgumentName,
+			attrSource:       issue.Source,
+			attrConfigFile:   issue.ConfigFile,
+		},
+	}
+}
+
+func toHealthIssues(issues []Issue) []health.Issue {
+	seen := make(map[string]bool, len(issues))
+	out := make([]health.Issue, 0, len(issues))
+	for _, issue := range issues {
+		converted := toHealthIssue(issue)
+		if seen[converted.Key] {
+			continue
+		}
+		seen[converted.Key] = true
+		out = append(out, converted)
+	}
+	return out
+}
+
+func fromHealthIssue(view health.IssueView) Issue {
+	return Issue{
+		Severity:     view.Severity,
+		Code:         view.Attributes[attrCode],
+		Message:      view.Title,
+		ActionID:     view.Attributes[attrActionID],
+		ActionTitle:  view.Attributes[attrActionTitle],
+		ArgumentName: view.Attributes[attrArgumentName],
+		Source:       view.Attributes[attrSource],
+		ConfigFile:   view.Attributes[attrConfigFile],
+	}
+}
+
+func rememberOrder(sourceID string, issues []Issue) {
+	positions := make(map[string]int, len(issues))
+	for index, issue := range issues {
+		key := issueKey(issue)
+		if _, exists := positions[key]; !exists {
+			positions[key] = index
+		}
+	}
+
+	orderMu.Lock()
+	defer orderMu.Unlock()
+	orderBySource[sourceID] = positions
+}
+
+// orderedIssues lists each problem once, in the order OliveTin has always used:
+// load-time issues, then runtime issues, then issues derived from the config.
+// Within a source, issues keep the order they were collected in, and issues
+// reported between rebuilds follow in the order they were reported.
+func orderedIssues(stored []health.IssueView) []Issue {
+	views := uniqueIssueViews(stored)
+
+	orderMu.Lock()
+	defer orderMu.Unlock()
+
+	sort.SliceStable(views, func(left, right int) bool {
+		return issueSortsBefore(views[left], views[right])
+	})
+
+	out := make([]Issue, 0, len(views))
+	for _, view := range views {
+		out = append(out, fromHealthIssue(view))
+	}
+	return out
+}
+
+func uniqueIssueViews(stored []health.IssueView) []health.IssueView {
+	views := slices.Clone(stored)
+	sort.SliceStable(views, func(left, right int) bool {
+		return sourceRank(views[left].CheckID) < sourceRank(views[right].CheckID)
+	})
+
+	seen := make(map[string]bool, len(views))
+	out := make([]health.IssueView, 0, len(views))
+	for _, view := range views {
+		if seen[view.IssueKey] {
+			continue
+		}
+		seen[view.IssueKey] = true
+		out = append(out, view)
+	}
+	return out
+}
+
+func issueSortsBefore(left, right health.IssueView) bool {
+	if sourceRank(left.CheckID) != sourceRank(right.CheckID) {
+		return sourceRank(left.CheckID) < sourceRank(right.CheckID)
+	}
+
+	leftPosition, leftPushed := orderBySource[left.CheckID][left.IssueKey]
+	rightPosition, rightPushed := orderBySource[right.CheckID][right.IssueKey]
+	if leftPushed && rightPushed {
+		return leftPosition < rightPosition
+	}
+	if leftPushed != rightPushed {
+		return leftPushed
+	}
+	return left.ID < right.ID
+}
+
+func sourceRank(sourceID string) int {
+	return slices.Index(sourceOrder, sourceID)
+}

+ 168 - 0
service/internal/configissues/health_test.go

@@ -0,0 +1,168 @@
+package configissues
+
+import (
+	"context"
+	"testing"
+
+	log "github.com/sirupsen/logrus"
+	logtest "github.com/sirupsen/logrus/hooks/test"
+	"github.com/stretchr/testify/assert"
+	"github.com/stretchr/testify/require"
+)
+
+func resetIssues(t *testing.T) {
+	t.Helper()
+
+	clear := func() {
+		BeginConfigLoad()
+		ReplaceLoadIssues(nil)
+		Replace(nil)
+		ClearRuntime()
+	}
+
+	clear()
+	t.Cleanup(clear)
+}
+
+func captureLogs(t *testing.T) *logtest.Hook {
+	t.Helper()
+
+	hook := logtest.NewGlobal()
+	t.Cleanup(func() {
+		log.StandardLogger().ReplaceHooks(make(log.LevelHooks))
+	})
+	return hook
+}
+
+func issueLogEntries(hook *logtest.Hook) []*log.Entry {
+	out := make([]*log.Entry, 0)
+	for _, entry := range hook.AllEntries() {
+		if _, ok := entry.Data["code"]; ok {
+			out = append(out, entry)
+		}
+	}
+	return out
+}
+
+func testIssue(code, message string) Issue {
+	return Issue{Severity: SeverityWarning, Code: code, Message: message}
+}
+
+func messages(issues []Issue) []string {
+	out := make([]string, 0, len(issues))
+	for _, issue := range issues {
+		out = append(out, issue.Message)
+	}
+	return out
+}
+
+func TestReplaceOnlyLogsNewIssues(t *testing.T) {
+	resetIssues(t)
+	hook := captureLogs(t)
+
+	first := testIssue(CodeCronInvalid, "first")
+	Replace([]Issue{first})
+	Replace([]Issue{first})
+	assert.Len(t, issueLogEntries(hook), 1, "an unchanged issue must not be logged again")
+
+	Replace([]Issue{first, testIssue(CodeCronInvalid, "second")})
+	entries := issueLogEntries(hook)
+	require.Len(t, entries, 2)
+	assert.Equal(t, "second", entries[1].Message)
+	assert.Equal(t, log.WarnLevel, entries[1].Level)
+	assert.Equal(t, CodeCronInvalid, entries[1].Data["code"])
+}
+
+func TestIssueIsLoggedAgainWhenItBecomesAnError(t *testing.T) {
+	resetIssues(t)
+	hook := captureLogs(t)
+
+	issue := testIssue(CodeTemplateParse, "broken template")
+	Replace([]Issue{issue})
+
+	issue.Severity = SeverityError
+	Replace([]Issue{issue})
+
+	entries := issueLogEntries(hook)
+	require.Len(t, entries, 2)
+	assert.Equal(t, log.ErrorLevel, entries[1].Level)
+	require.Len(t, List(), 1)
+	assert.Equal(t, SeverityError, List()[0].Severity)
+}
+
+func TestIssueWithoutSeverityIsLoggedAsWarning(t *testing.T) {
+	resetIssues(t)
+	hook := captureLogs(t)
+
+	Replace([]Issue{{Code: CodeCronInvalid, Message: "no severity"}})
+
+	entries := issueLogEntries(hook)
+	require.Len(t, entries, 1)
+	assert.Equal(t, log.WarnLevel, entries[0].Level)
+}
+
+func TestRuntimeIssuesSurviveRebuildAndCountOccurrences(t *testing.T) {
+	resetIssues(t)
+
+	issue := Issue{Severity: SeverityWarning, Code: CodeDeprecatedAPICall, Message: "deprecated", Source: "StartActionByGet"}
+	ReportRuntime(issue)
+	ReportRuntime(issue)
+
+	Replace(nil)
+	ReplaceLoadIssues(nil)
+
+	assert.Equal(t, []Issue{issue}, List())
+
+	stored, err := service.ListIssues(context.Background(), false, true)
+	require.NoError(t, err)
+	require.Len(t, stored, 1)
+	assert.Equal(t, 2, stored[0].Occurrences)
+}
+
+func TestReportedIssueIsResolvedByNextRebuild(t *testing.T) {
+	resetIssues(t)
+
+	Report(Issue{Severity: SeverityWarning, Code: CodeWatcherPath, Message: "cannot watch", ActionID: "a1"})
+	assert.Equal(t, 1, Count())
+
+	Replace(nil)
+	assert.Equal(t, 0, Count())
+}
+
+func TestLoadIssuesAreClearedByTheNextLoad(t *testing.T) {
+	resetIssues(t)
+
+	BeginConfigLoad()
+	ReportSticky(testIssue(CodeEnvUnset, "FOO is not set"))
+	ReplaceLoadIssues(CopySticky())
+	assert.Equal(t, 1, Count())
+
+	BeginConfigLoad()
+	ReplaceLoadIssues(CopySticky())
+	assert.Equal(t, 0, Count())
+}
+
+func TestIssueInTwoSourcesIsListedOnce(t *testing.T) {
+	resetIssues(t)
+
+	issue := testIssue(CodeConfigDecode, "bad value")
+	ReplaceLoadIssues([]Issue{issue})
+	Report(issue)
+
+	assert.Equal(t, []Issue{issue}, List())
+}
+
+func TestListKeepsCollectionOrder(t *testing.T) {
+	resetIssues(t)
+
+	ReplaceLoadIssues([]Issue{testIssue(CodeEnvUnset, "load")})
+	ReportRuntime(testIssue(CodeDeprecatedAPICall, "runtime"))
+	Replace([]Issue{testIssue(CodeCronInvalid, "config b"), testIssue(CodeCronInvalid, "config a")})
+	Report(testIssue(CodeWatcherPath, "reported"))
+
+	assert.Equal(t, []string{"load", "runtime", "config b", "config a", "reported"}, messages(List()))
+
+	Replace([]Issue{testIssue(CodeCronInvalid, "config a"), testIssue(CodeCronInvalid, "config c"), testIssue(CodeCronInvalid, "config b")})
+
+	assert.Equal(t, []string{"load", "runtime", "config a", "config c", "config b"}, messages(List()))
+}

+ 18 - 27
service/internal/configissues/runtime.go

@@ -1,10 +1,10 @@
 package configissues
 
-import "sync"
+import (
+	"context"
 
-var (
-	runtimeMu     sync.Mutex
-	runtimeIssues []Issue
+	health "github.com/jamesread/armature-health/v2"
+	log "github.com/sirupsen/logrus"
 )
 
 // ReportRuntime records an issue discovered while OliveTin is running, rather
@@ -12,36 +12,27 @@ var (
 // method). Unlike Report, runtime issues are kept when the issue list is
 // rebuilt on config reload or entity changes. They are cleared on restart.
 func ReportRuntime(issue Issue) {
-	addRuntime(issue)
-	Report(issue)
+	raise(sourceRuntime, issue)
 }
 
-func addRuntime(issue Issue) {
-	runtimeMu.Lock()
-	defer runtimeMu.Unlock()
+// CopyRuntime returns a copy of the runtime issues.
+func CopyRuntime() []Issue {
+	stored, err := service.ListIssues(context.Background(), false, true)
+	if err != nil {
+		log.WithError(err).Error("Could not list runtime issues")
+		return []Issue{}
+	}
 
-	fingerprint := issueFingerprint(issue)
-	for _, existing := range runtimeIssues {
-		if issueFingerprint(existing) == fingerprint {
-			return
+	runtime := make([]health.IssueView, 0)
+	for _, view := range stored {
+		if view.CheckID == sourceRuntime {
+			runtime = append(runtime, view)
 		}
 	}
-
-	runtimeIssues = append(runtimeIssues, issue)
-}
-
-// CopyRuntime returns a copy of the runtime issues.
-func CopyRuntime() []Issue {
-	runtimeMu.Lock()
-	defer runtimeMu.Unlock()
-	out := make([]Issue, len(runtimeIssues))
-	copy(out, runtimeIssues)
-	return out
+	return orderedIssues(runtime)
 }
 
 // ClearRuntime removes all runtime issues. Intended for tests.
 func ClearRuntime() {
-	runtimeMu.Lock()
-	defer runtimeMu.Unlock()
-	runtimeIssues = nil
+	setSource(sourceRuntime, nil)
 }

+ 113 - 61
service/internal/configissues/store.go

@@ -1,17 +1,44 @@
 package configissues
 
 import (
+	"context"
 	"sync"
+	"time"
 
+	health "github.com/jamesread/armature-health/v2"
 	log "github.com/sirupsen/logrus"
 )
 
+// Issues are kept by armature-health in memory, grouped by where they come from.
+// A rebuild replaces the "config" and "config.load" sources, and leaves "runtime"
+// alone, so issues found while OliveTin is running survive config reloads.
+const (
+	sourceConfig     = "config"
+	sourceConfigLoad = "config.load"
+	sourceRuntime    = "runtime"
+)
+
+var sourceOrder = []string{sourceConfigLoad, sourceRuntime, sourceConfig}
+
+// OliveTin only shows open issues, so resolved ones are not kept for long.
+const resolvedRetention = time.Hour
+
 var (
-	storeMu sync.RWMutex
-	issues  []Issue
+	service = health.NewService(nil, nil, nil, health.Options{
+		SourceTitles: map[string]string{
+			sourceConfig:     "Configuration",
+			sourceConfigLoad: "Configuration loading",
+			sourceRuntime:    "Runtime",
+		},
+		ResolvedRetention: resolvedRetention,
+	})
 
 	stickyMu sync.Mutex
 	sticky   []Issue
+
+	// writeMu makes each change and the logging of the issues it adds one step,
+	// so concurrent reports cannot log the same new issue twice.
+	writeMu sync.Mutex
 )
 
 // BeginConfigLoad clears sticky issues captured during config decode/include load.
@@ -29,7 +56,8 @@ func ReportSticky(issue Issue) {
 	sticky = append(sticky, issue)
 }
 
-func copySticky() []Issue {
+// CopySticky returns a copy of sticky load-time issues.
+func CopySticky() []Issue {
 	stickyMu.Lock()
 	defer stickyMu.Unlock()
 	out := make([]Issue, len(sticky))
@@ -37,43 +65,101 @@ func copySticky() []Issue {
 	return out
 }
 
-// CopySticky returns a copy of sticky load-time issues.
-func CopySticky() []Issue {
-	return copySticky()
+// Replace sets the issues derived from the current configuration. Issues that
+// were already present are kept (and not logged again), and missing ones are
+// resolved.
+func Replace(next []Issue) {
+	setSource(sourceConfig, next)
 }
 
-// Replace sets the current issue list and logs only newly appeared issues.
-func Replace(next []Issue) {
-	storeMu.Lock()
-	defer storeMu.Unlock()
+// ReplaceLoadIssues sets the issues found while loading configuration.
+func ReplaceLoadIssues(next []Issue) {
+	setSource(sourceConfigLoad, next)
+}
 
-	previous := make(map[string]struct{}, len(issues))
-	for _, issue := range issues {
-		previous[issueFingerprint(issue)] = struct{}{}
+// Report adds a live issue if it is not already present and logs it when new.
+// Use this for runtime discoveries that happen outside Rebuild (for example
+// filesystem watcher setup failures). The next Rebuild resolves it unless the
+// rebuild finds it again.
+func Report(issue Issue) {
+	raise(sourceConfig, issue)
+}
+
+// List returns the current issues.
+func List() []Issue {
+	stored, err := service.ListIssues(context.Background(), false, true)
+	if err != nil {
+		log.WithError(err).Error("Could not list configuration issues")
+		return []Issue{}
+	}
+
+	return orderedIssues(stored)
+}
+
+// Count returns the number of current issues.
+func Count() int {
+	return len(List())
+}
+
+func setSource(sourceID string, next []Issue) {
+	writeMu.Lock()
+	defer writeMu.Unlock()
+
+	before := openSeverities()
+	rememberOrder(sourceID, next)
+
+	if err := service.SetIssues(context.Background(), sourceID, toHealthIssues(next)); err != nil {
+		log.WithError(err).WithField("source", sourceID).Error("Could not save configuration issues")
+		return
+	}
+
+	logNewIssues(before, next)
+}
+
+func raise(sourceID string, issue Issue) {
+	writeMu.Lock()
+	defer writeMu.Unlock()
+
+	before := openSeverities()
+
+	if err := service.Raise(context.Background(), sourceID, toHealthIssue(issue)); err != nil {
+		log.WithError(err).WithField("source", sourceID).Error("Could not save configuration issue")
+		return
+	}
+
+	logNewIssues(before, []Issue{issue})
+}
+
+// openSeverities returns the severity of every open issue, by key, across all sources.
+func openSeverities() map[string]string {
+	stored, err := service.ListIssues(context.Background(), false, true)
+	if err != nil {
+		log.WithError(err).Error("Could not list configuration issues")
+		return map[string]string{}
 	}
 
-	issues = make([]Issue, len(next))
-	copy(issues, next)
+	severities := make(map[string]string, len(stored))
+	for _, view := range stored {
+		severities[view.IssueKey] = view.Severity
+	}
+	return severities
+}
 
+// logNewIssues logs issues that were not open before, or whose severity changed,
+// in the order they were collected, so startup and reloads do not repeat the
+// same warnings.
+func logNewIssues(before map[string]string, issues []Issue) {
 	for _, issue := range issues {
-		if _, exists := previous[issueFingerprint(issue)]; exists {
+		key := issueKey(issue)
+		severity := string(healthSeverity(issue.Severity))
+		if before[key] == severity {
 			continue
 		}
+		before[key] = severity
 		logNewIssue(issue)
 	}
 }
 
-func issueFingerprint(issue Issue) string {
-	return issue.Severity + "\x00" +
-		issue.Code + "\x00" +
-		issue.ActionID + "\x00" +
-		issue.ActionTitle + "\x00" +
-		issue.ArgumentName + "\x00" +
-		issue.Source + "\x00" +
-		issue.ConfigFile + "\x00" +
-		issue.Message
-}
-
 func logNewIssue(issue Issue) {
 	fields := log.Fields{
 		"code":         issue.Code,
@@ -89,37 +175,3 @@ func logNewIssue(issue Issue) {
 	}
 	log.WithFields(fields).Warn(issue.Message)
 }
-
-// Report adds a live issue if it is not already present and logs it when new.
-// Use this for runtime discoveries that happen outside Rebuild (for example
-// filesystem watcher setup failures).
-func Report(issue Issue) {
-	storeMu.Lock()
-	defer storeMu.Unlock()
-
-	issueFingerprintValue := issueFingerprint(issue)
-	for _, existing := range issues {
-		if issueFingerprint(existing) == issueFingerprintValue {
-			return
-		}
-	}
-
-	issues = append(issues, issue)
-	logNewIssue(issue)
-}
-
-// List returns a copy of the current issues.
-func List() []Issue {
-	storeMu.RLock()
-	defer storeMu.RUnlock()
-	out := make([]Issue, len(issues))
-	copy(out, issues)
-	return out
-}
-
-// Count returns the number of current issues.
-func Count() int {
-	storeMu.RLock()
-	defer storeMu.RUnlock()
-	return len(issues)
-}

+ 4 - 0
specs/config-issues.md

@@ -10,6 +10,10 @@ Operators should see configuration problems in Diagnostics instead of only in se
 
 The issue list is cleared and rebuilt when configuration is loaded or reloaded, and when entity data changes. Some findings that can only be detected while configuration is first being loaded (for example references to unset environment variables that are expanded away during that load, or included files that failed to parse) are kept across later rebuilds until the next configuration load begins.
 
+Issues found while OliveTin is running rather than from the configuration (for example calls to deprecated API methods) are kept across rebuilds until OliveTin restarts.
+
+Issues are kept in memory only. No database is needed, and the list starts empty on each start.
+
 ## What is collected
 
 Issues include: