Feat/operator alerts (#1635)
* feat(state): durable operator alerts owned by the State Store Alerts dedup on org+kind+subject, resolve themselves when a condition clears, and are raised, resolved, dismissed and listed through the state contract. Task transitions raise needs-human and failed alerts in the same transaction; the store checks service health and prunes closed alerts. Each raise and resolve queues a webhook delivery whose attempts are kept. * feat(notify): deliver operator alerts to the webhook; raise config and release alerts notify.webhook now receives raised and resolved alerts above a severity threshold with HMAC-signed payloads, bounded retry and every attempt recorded on the alert. archied raises model alias, provider and credential-binding alerts from the effective configuration, an update alert from the release channel, and a credential-rejected alert from the egress resolver. The dashboard API lists and dismisses the caller's org's alerts. * feat(ui): alert bell in the top bar and webhook alert settings The bell lists the org's open alerts by severity with dismiss and a link per alert, and refreshes from the event stream. The task settings page gains the webhook severity threshold and signing secret. ui/dist rebuilt.
This commit is contained in:
1 parent
f34f60f9c7
commit
8a3ba32c5a
43 files changed
+4671
-465
No files matched your search
@@ -0,0 +1,349 @@
|
||||
package archied
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"maps"
|
||||
"net/http"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/domain/alert"
|
||||
"github.com/samcharles93/archie-core/internal/domain/org"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/alertwebhook"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/controlplanerpc"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/modelcatalog"
|
||||
"github.com/samcharles93/archie-core/internal/releaseupdate"
|
||||
)
|
||||
|
||||
const (
|
||||
// deliveryInterval is how often due webhook deliveries are claimed.
|
||||
deliveryInterval = 15 * time.Second
|
||||
// releaseCheckInterval is how often GitHub is asked for a newer release.
|
||||
releaseCheckInterval = 6 * time.Hour
|
||||
// alertCallTimeout bounds one check's calls to the State Store.
|
||||
alertCallTimeout = 20 * time.Second
|
||||
// credentialReportEvery is how long an unchanged credential state goes
|
||||
// unreported, so the egress path does not call the State Store per request.
|
||||
credentialReportEvery = 10 * time.Minute
|
||||
)
|
||||
|
||||
// alertChecks raises the alerts that have no transition to hang on: the
|
||||
// daemon's configuration and the release channel. Each check lists what it
|
||||
// owns, so alerts from before a restart are still cleared once fixed.
|
||||
type alertChecks struct {
|
||||
store alert.Store
|
||||
log func(msg string, args ...any)
|
||||
cfg func() config.Config
|
||||
// catalog is the models the providers currently offer.
|
||||
catalog func() modelcatalog.Snapshot
|
||||
// release is the newest release the update channel offers.
|
||||
release func(context.Context) (releaseupdate.Snapshot, error)
|
||||
}
|
||||
|
||||
func (c alertChecks) reporter() alert.Reporter {
|
||||
return alert.Reporter{Raiser: c.store, By: "archied"}
|
||||
}
|
||||
|
||||
// sync makes the open alerts of kind in orgID match active: it raises each
|
||||
// input and resolves the alerts, snoozed or open, whose condition cleared.
|
||||
func (c alertChecks) sync(ctx context.Context, orgID org.OrgID, kind string, active []alert.Input) {
|
||||
reporter := c.reporter()
|
||||
subjects := make([]string, 0, len(active))
|
||||
for _, in := range active {
|
||||
reporter.Raise(ctx, in)
|
||||
subjects = append(subjects, in.Subject)
|
||||
}
|
||||
existing, err := c.store.ListAlerts(ctx, orgID, alert.Filter{States: []alert.State{alert.StateOpen, alert.StateDismissed}, Limit: 500})
|
||||
if err != nil {
|
||||
c.log("alerts not checked", "kind", kind, "err", err)
|
||||
return
|
||||
}
|
||||
for _, a := range existing {
|
||||
if a.Kind == kind && a.Condition && !slices.Contains(subjects, a.Subject) {
|
||||
reporter.Resolve(ctx, a.Key)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// checkConfig raises the alerts the effective configuration implies: a
|
||||
// missing or dangling model alias, and providers and granted services with no
|
||||
// usable credential.
|
||||
func (c alertChecks) checkConfig(ctx context.Context) {
|
||||
cfg := c.cfg()
|
||||
c.sync(ctx, org.DefaultOrgID, alert.KindModelAlias, modelAliasAlerts(cfg.Models, c.catalog()))
|
||||
c.sync(ctx, org.DefaultOrgID, alert.KindProviderNoKey, providerAlerts(cfg.Providers))
|
||||
unbound := unboundAlerts(cfg)
|
||||
for _, orgID := range credentialOrgs(cfg) {
|
||||
c.sync(ctx, orgID, alert.KindToolNoBinding, unbound[orgID])
|
||||
}
|
||||
}
|
||||
|
||||
func modelAliasAlerts(aliases map[string]string, catalog modelcatalog.Snapshot) []alert.Input {
|
||||
var out []alert.Input
|
||||
input := func(alias, title, body string) alert.Input {
|
||||
return alert.Input{
|
||||
Org: org.DefaultOrgID, Kind: alert.KindModelAlias, Subject: "alias:" + alias,
|
||||
Severity: alert.SeverityAction, Condition: true, Title: title, Body: body, Link: "/settings/models",
|
||||
}
|
||||
}
|
||||
if strings.TrimSpace(aliases[config.DefaultModelAlias]) == "" {
|
||||
out = append(out, input(config.DefaultModelAlias, "No default model alias is set",
|
||||
"Agent steps and chat use the default alias when none is named. Point it at a model in model settings."))
|
||||
}
|
||||
for _, alias := range slices.Sorted(maps.Keys(aliases)) {
|
||||
providerID, modelID, ok := strings.Cut(aliases[alias], "/")
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
offered := catalogModels(catalog, providerID)
|
||||
// A provider the catalogue does not list is a credential problem, not
|
||||
// a retired model.
|
||||
if len(offered) > 0 && !slices.Contains(offered, modelID) {
|
||||
out = append(out, input(alias, fmt.Sprintf("Model alias %q points at a model that no longer exists", alias),
|
||||
fmt.Sprintf("The %s provider no longer offers the model this alias names. Choose another in model settings.", providerID)))
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func catalogModels(catalog modelcatalog.Snapshot, providerID string) []string {
|
||||
for _, provider := range catalog.Providers {
|
||||
if provider.ID == providerID {
|
||||
ids := make([]string, len(provider.Models))
|
||||
for i, model := range provider.Models {
|
||||
ids[i] = model.ID
|
||||
}
|
||||
return ids
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func providerAlerts(providers map[string]config.Provider) []alert.Input {
|
||||
var out []alert.Input
|
||||
for _, name := range slices.Sorted(maps.Keys(providers)) {
|
||||
if !providers[name].Disabled {
|
||||
continue
|
||||
}
|
||||
out = append(out, alert.Input{
|
||||
Org: org.DefaultOrgID, Kind: alert.KindProviderNoKey, Subject: "provider:" + name,
|
||||
Severity: alert.SeverityAction, Condition: true,
|
||||
Title: fmt.Sprintf("Provider %q has no usable credential", name),
|
||||
Body: "Its API key could not be resolved, so models on this provider cannot run. Check its credential in credential bindings.",
|
||||
Link: "/settings/credential-bindings",
|
||||
})
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// credentialOrgs are the orgs whose identities are granted credentials, the
|
||||
// instance org always among them.
|
||||
func credentialOrgs(cfg config.Config) []org.OrgID {
|
||||
orgs := []org.OrgID{org.DefaultOrgID}
|
||||
for _, name := range append([]string{""}, identityNames(cfg)...) {
|
||||
orgName, _ := cfg.CredentialAccess(name)
|
||||
if id := org.OrgID(credentialOrg(orgName)); !slices.Contains(orgs, id) {
|
||||
orgs = append(orgs, id)
|
||||
}
|
||||
}
|
||||
return orgs
|
||||
}
|
||||
|
||||
func identityNames(cfg config.Config) []string {
|
||||
names := make([]string, 0, len(cfg.Identities))
|
||||
for _, id := range cfg.Identities {
|
||||
names = append(names, id.Name)
|
||||
}
|
||||
return names
|
||||
}
|
||||
|
||||
func credentialOrg(name string) string {
|
||||
if name == "" {
|
||||
return string(org.DefaultOrgID)
|
||||
}
|
||||
return name
|
||||
}
|
||||
|
||||
// unboundAlerts are the granted services with no credential binding in the
|
||||
// granting identity's org, by org. A model provider needs no binding of its
|
||||
// own here: its key is the provider's.
|
||||
func unboundAlerts(cfg config.Config) map[org.OrgID][]alert.Input {
|
||||
out := map[org.OrgID][]alert.Input{}
|
||||
seen := map[alert.Key]bool{}
|
||||
for _, name := range append([]string{""}, identityNames(cfg)...) {
|
||||
orgName, granted := cfg.CredentialAccess(name)
|
||||
orgID := org.OrgID(credentialOrg(orgName))
|
||||
bound := cfg.Containers.BoundCredentials(orgName, granted, granted)
|
||||
for _, service := range granted {
|
||||
key := alert.Key{Org: orgID, Kind: alert.KindToolNoBinding, Subject: "service:" + service}
|
||||
if _, ok := cfg.Providers[service]; ok || bound[service].Service != "" || seen[key] {
|
||||
continue
|
||||
}
|
||||
seen[key] = true
|
||||
out[orgID] = append(out[orgID], alert.Input{
|
||||
Key: key, Severity: alert.SeverityAction, Condition: true,
|
||||
Title: fmt.Sprintf("%q is granted but has no credential binding", service),
|
||||
Body: "Runs that use this service cannot authenticate. Bind a credential to it.",
|
||||
Link: "/settings/credential-bindings",
|
||||
})
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// checkRelease raises an info alert while the update channel offers a newer
|
||||
// release. A failed check changes nothing: the next one decides.
|
||||
func (c alertChecks) checkRelease(ctx context.Context) {
|
||||
snapshot, err := c.release(ctx)
|
||||
if err != nil {
|
||||
c.log("release check failed", "err", err)
|
||||
return
|
||||
}
|
||||
var active []alert.Input
|
||||
if available := snapshot.Available(); len(available) > 0 {
|
||||
parts := make([]string, len(available))
|
||||
for i, component := range available {
|
||||
parts[i] = fmt.Sprintf("%s %s", component.Label, component.Available)
|
||||
}
|
||||
active = append(active, alert.Input{
|
||||
Org: org.DefaultOrgID, Kind: alert.KindReleaseAvailable, Subject: "release",
|
||||
Severity: alert.SeverityInfo, Condition: true,
|
||||
Title: "A newer release is available", Body: "Available: " + strings.Join(parts, ", ") + ".",
|
||||
Link: "/settings/status",
|
||||
})
|
||||
}
|
||||
c.sync(ctx, org.DefaultOrgID, alert.KindReleaseAvailable, active)
|
||||
}
|
||||
|
||||
// every runs fn now and then each interval until ctx ends.
|
||||
func every(ctx context.Context, interval time.Duration, fn func(context.Context)) {
|
||||
ticker := time.NewTicker(interval)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
callCtx, cancel := context.WithTimeout(ctx, alertCallTimeout)
|
||||
fn(callCtx)
|
||||
cancel()
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-ticker.C:
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// startAlerts starts the daemon's alert checks and the webhook delivery loop.
|
||||
// The State Store being away costs the checks a tick, nothing else.
|
||||
func (b *boot) startAlerts(ctx context.Context) {
|
||||
client, ok := b.stateStore.(alert.Store)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
reader := controlplanerpc.NewRPCClient(b.controlPlaneRPC)
|
||||
catalog := controlplanerpc.UpdateService(reader, "").Catalog
|
||||
checks := alertChecks{
|
||||
store: client, log: b.log.Warn, cfg: b.cfgHolder.Get, catalog: b.catalogState,
|
||||
release: func(ctx context.Context) (releaseupdate.Snapshot, error) { return catalog.Check(ctx) },
|
||||
}
|
||||
b.alertChecks = &checks
|
||||
go every(ctx, releaseCheckInterval, checks.checkRelease)
|
||||
go every(ctx, deliveryInterval, b.deliverAlerts(client))
|
||||
checks.checkConfig(ctx)
|
||||
}
|
||||
|
||||
// recheckAlerts re-evaluates the configuration alerts after the configuration
|
||||
// changed. It never blocks the change that caused it.
|
||||
func (b *boot) recheckAlerts(ctx context.Context) {
|
||||
checks := b.alertChecks
|
||||
if checks == nil {
|
||||
return
|
||||
}
|
||||
go func() {
|
||||
ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), alertCallTimeout)
|
||||
defer cancel()
|
||||
checks.checkConfig(ctx)
|
||||
}()
|
||||
}
|
||||
|
||||
// deliverAlerts sends due webhook deliveries. A delivery the webhook is not
|
||||
// configured for, or whose alert is below the severity threshold, is closed
|
||||
// as skipped; one that fails is retried by the store on its schedule.
|
||||
func (b *boot) deliverAlerts(store alert.Deliverer) func(context.Context) {
|
||||
client := &http.Client{Timeout: 15 * time.Second}
|
||||
return func(ctx context.Context) {
|
||||
due, err := store.ClaimAlertDeliveries(ctx, 20)
|
||||
if err != nil {
|
||||
b.log.Warn("alert deliveries not claimed", "err", err)
|
||||
return
|
||||
}
|
||||
notify := b.cfgHolder.Get().Notify
|
||||
for _, d := range due {
|
||||
outcome := alert.Outcome{DeliveryID: d.ID}
|
||||
threshold := alert.Severity(notify.MinSeverity)
|
||||
if !threshold.Valid() {
|
||||
threshold = alert.SeverityWarning
|
||||
}
|
||||
if notify.Webhook == "" || d.Alert.Severity.Rank() < threshold.Rank() {
|
||||
outcome.Skipped = true
|
||||
} else {
|
||||
secret := ""
|
||||
if notify.Secret != (config.SecretRef{}) {
|
||||
secret, err = b.secrets.Resolve(notify.Secret)
|
||||
}
|
||||
if err != nil {
|
||||
outcome.Error = "notify secret could not be resolved"
|
||||
} else {
|
||||
outcome = alertwebhook.Send(ctx, client, notify.Webhook, secret, d)
|
||||
}
|
||||
}
|
||||
if err := store.RecordAlertAttempt(ctx, outcome); err != nil {
|
||||
b.log.Warn("alert delivery not recorded", "delivery", d.ID, "err", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// credentialWatch raises an alert when a bound credential cannot be resolved
|
||||
// and clears it once it can. The egress path calls observe per request, so an
|
||||
// unchanged state is reported at most every credentialReportEvery.
|
||||
type credentialWatch struct {
|
||||
reporter alert.Reporter
|
||||
mu sync.Mutex
|
||||
last map[alert.Key]credentialState
|
||||
}
|
||||
|
||||
type credentialState struct {
|
||||
rejected bool
|
||||
at time.Time
|
||||
}
|
||||
|
||||
func (w *credentialWatch) observe(ctx context.Context, orgName, service string, rejected bool) {
|
||||
if w == nil {
|
||||
return
|
||||
}
|
||||
key := alert.Key{Org: org.OrgID(credentialOrg(orgName)), Kind: alert.KindCredentialInvalid, Subject: "service:" + service}
|
||||
w.mu.Lock()
|
||||
if w.last == nil {
|
||||
w.last = map[alert.Key]credentialState{}
|
||||
}
|
||||
previous, known := w.last[key]
|
||||
if known && previous.rejected == rejected && time.Since(previous.at) < credentialReportEvery {
|
||||
w.mu.Unlock()
|
||||
return
|
||||
}
|
||||
w.last[key] = credentialState{rejected: rejected, at: time.Now()}
|
||||
w.mu.Unlock()
|
||||
go func() {
|
||||
ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), alertCallTimeout)
|
||||
defer cancel()
|
||||
w.reporter.Sync(ctx, rejected, alert.Input{
|
||||
Key: key, Severity: alert.SeverityAction, Condition: true,
|
||||
Title: fmt.Sprintf("The credential bound to %q is not working", service),
|
||||
Body: "Its secret could not be resolved, so runs that use this service cannot authenticate. Check the binding.",
|
||||
Link: "/settings/credential-bindings",
|
||||
})
|
||||
}()
|
||||
}
|
||||
@@ -32,6 +32,7 @@ import (
|
||||
"github.com/samcharles93/archie-core/internal/daemon"
|
||||
"github.com/samcharles93/archie-core/internal/domain/access"
|
||||
"github.com/samcharles93/archie-core/internal/domain/agent"
|
||||
"github.com/samcharles93/archie-core/internal/domain/alert"
|
||||
"github.com/samcharles93/archie-core/internal/domain/applystatus"
|
||||
"github.com/samcharles93/archie-core/internal/domain/health"
|
||||
"github.com/samcharles93/archie-core/internal/domain/identity"
|
||||
@@ -201,6 +202,13 @@ type boot struct {
|
||||
// signal path rather than inventing a new one.
|
||||
shutdown context.CancelFunc
|
||||
|
||||
// alertChecks re-evaluates the configuration alerts when the configuration
|
||||
// changes. Nil until the daemon's run loop starts them.
|
||||
alertChecks *alertChecks
|
||||
// credentialWatch reports bound credentials that stop resolving. Nil
|
||||
// when the State Store has no alert surface.
|
||||
credentialWatch *credentialWatch
|
||||
|
||||
cleanups []func()
|
||||
}
|
||||
|
||||
@@ -270,6 +278,9 @@ func (b *boot) openStateStoreAdapter(ctx context.Context) error {
|
||||
return err
|
||||
}
|
||||
b.stateStore = client
|
||||
if alerts, ok := b.stateStore.(alert.Store); ok {
|
||||
b.credentialWatch = &credentialWatch{reporter: alert.Reporter{Raiser: alerts, Log: b.log, By: "archied"}}
|
||||
}
|
||||
b.taskModels = client
|
||||
b.controlPlaneRPC = client.ControlPlane()
|
||||
b.controlPlane = controlplane.NewRPCClient(b.controlPlaneRPC)
|
||||
@@ -680,6 +691,7 @@ func (b *boot) publishConfig(ctx context.Context, cfg config.Config) {
|
||||
// The daemon owns the published configuration view.
|
||||
if b.processName != applystatus.Gateway {
|
||||
b.publishConfigSnapshot(ctx)
|
||||
b.recheckAlerts(ctx)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -785,6 +797,7 @@ func (b *boot) runLoop(ctx context.Context, once bool) error {
|
||||
b.log.Info("archied running", "repos", len(b.cfg.Repos), "poll", b.cfg.PollInterval.Std().String(), "label", b.cfg.Label)
|
||||
b.startDrainMonitor(ctx)
|
||||
b.startWatchdog(ctx)
|
||||
b.startAlerts(ctx)
|
||||
if err := b.d.Run(ctx); err != nil && ctx.Err() == nil {
|
||||
b.log.Error("daemon exited", "err", err)
|
||||
return err
|
||||
|
||||
@@ -58,7 +58,7 @@ func (b *boot) setupKitLauncher(ctx context.Context) {
|
||||
// container logs in with, against the live grants and bindings; a setup
|
||||
// session's token resolves through the session grants instead.
|
||||
b.sessionGrants = &sessionGrants{}
|
||||
resolver := runCredentialResolver{runs: b.stateStoreGrants.Client, sessions: b.sessionGrants, models: b.taskModels, config: b.cfgHolder, secrets: b.secrets}
|
||||
resolver := runCredentialResolver{runs: b.stateStoreGrants.Client, sessions: b.sessionGrants, models: b.taskModels, config: b.cfgHolder, secrets: b.secrets, credentials: b.credentialWatch}
|
||||
// Without a harness secret store, Register refuses a Kit with a
|
||||
// required OAuth credential.
|
||||
oauthStore, _ := b.stateStore.(egress.OAuthStore)
|
||||
|
||||
@@ -33,12 +33,14 @@ type runCredentialResolver struct {
|
||||
secrets interface {
|
||||
Resolve(config.SecretRef) (string, error)
|
||||
}
|
||||
// credentials, when set, is told whether each bound secret resolved.
|
||||
credentials *credentialWatch
|
||||
}
|
||||
|
||||
func (r runCredentialResolver) Resolve(ctx context.Context, credential, service string) (string, error) {
|
||||
if r.sessions != nil {
|
||||
if org, services, ok := r.sessions.GrantedFor(credential); ok {
|
||||
return r.resolveBinding(org, services, service)
|
||||
return r.resolveBinding(ctx, org, services, service)
|
||||
}
|
||||
}
|
||||
task, err := r.runs.TaskForCredential(ctx, credential)
|
||||
@@ -53,13 +55,13 @@ func (r runCredentialResolver) Resolve(ctx context.Context, credential, service
|
||||
if r.isModelProvider(ctx, cfg, task, service) {
|
||||
granted = append(slices.Clone(granted), service)
|
||||
}
|
||||
return r.resolveBinding(org, granted, service)
|
||||
return r.resolveBinding(ctx, org, granted, service)
|
||||
}
|
||||
|
||||
// resolveBinding resolves service from the org's binding when the run or
|
||||
// session is granted it. An OAuth binding resolves to the empty string: the
|
||||
// proxy supplies the org's token set itself.
|
||||
func (r runCredentialResolver) resolveBinding(org string, granted []string, service string) (string, error) {
|
||||
func (r runCredentialResolver) resolveBinding(ctx context.Context, org string, granted []string, service string) (string, error) {
|
||||
cfg := r.config.Get()
|
||||
binding, ok := cfg.Containers.BoundCredentials(org, granted, []string{service})[service]
|
||||
if !ok {
|
||||
@@ -71,7 +73,9 @@ func (r runCredentialResolver) resolveBinding(org string, granted []string, serv
|
||||
if r.secrets == nil {
|
||||
return "", egress.ErrUnbound
|
||||
}
|
||||
return r.secrets.Resolve(binding.Secret)
|
||||
value, err := r.secrets.Resolve(binding.Secret)
|
||||
r.credentials.observe(ctx, org, service, err != nil)
|
||||
return value, err
|
||||
}
|
||||
|
||||
// isModelProvider reports whether service is a provider the task's models
|
||||
|
||||
@@ -94,6 +94,7 @@ func compose(ctx context.Context, d deps) *webui.Server {
|
||||
srv.Policies = policies
|
||||
}
|
||||
wireOrgSurface(srv, d.Store)
|
||||
wireAlerts(srv, d.Store)
|
||||
if presence, ok := d.Store.(storecontract.PresenceStore); ok {
|
||||
srv.Presence = presence
|
||||
srv.RunningVersions = servicekit.RunningVersions(ctx, presence, 0)
|
||||
@@ -228,3 +229,11 @@ func refusalStore(store storecontract.TaskStore) storecontract.CaptureRefusalSto
|
||||
refusals, _ := store.(storecontract.CaptureRefusalStore)
|
||||
return refusals
|
||||
}
|
||||
|
||||
// wireAlerts gives the dashboard the State Store's alert surface when the
|
||||
// store has one.
|
||||
func wireAlerts(srv *webui.Server, store any) {
|
||||
if alerts, ok := store.(webui.AlertSource); ok {
|
||||
srv.Alerts = alerts
|
||||
}
|
||||
}
|
||||
@@ -124,12 +124,12 @@ func runtimeConfigFrom(ctx context.Context, reader controlplanerpc.ResourceReade
|
||||
}
|
||||
|
||||
func runtimeToolConfigFrom(ctx context.Context, reader controlplanerpc.ResourceReader, versions map[string]int64, out config.Config) (config.Config, map[string]int64, error) {
|
||||
policy := taskPolicy{DiffCapLines: out.DiffCap(), NotifyWebhook: out.Notify.Webhook}
|
||||
policy := taskPolicyOf(out)
|
||||
if err := layerResourceJSON(ctx, reader, versions, TaskPolicyKind, &policy); err != nil {
|
||||
return config.Config{}, nil, err
|
||||
}
|
||||
out.DiffCapLines = new(policy.DiffCapLines)
|
||||
out.Notify.Webhook = policy.NotifyWebhook
|
||||
out.Notify = config.Notify{Webhook: policy.NotifyWebhook, MinSeverity: policy.NotifyMinSeverity, Secret: policy.NotifySecret}
|
||||
|
||||
if err := layerResource(ctx, reader, versions, ToolSettingsKind, func(settings toolSettings) error {
|
||||
headers := make(map[string]map[string]string, len(out.Tools.MCPServers))
|
||||
|
||||
@@ -5,18 +5,21 @@ import (
|
||||
"net/url"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/domain/alert"
|
||||
)
|
||||
|
||||
const TaskPolicyKind = "task-policy"
|
||||
|
||||
type taskPolicy struct {
|
||||
DiffCapLines int `json:"diff_cap_lines"`
|
||||
NotifyWebhook string `json:"notify_webhook"`
|
||||
DiffCapLines int `json:"diff_cap_lines"`
|
||||
NotifyWebhook string `json:"notify_webhook"`
|
||||
NotifyMinSeverity string `json:"notify_min_severity"`
|
||||
NotifySecret config.SecretRef `json:"notify_secret"`
|
||||
}
|
||||
|
||||
func taskPolicyDefinition() Definition {
|
||||
return Definition{Kind: TaskPolicyKind, Title: "Task policy", ApplyMode: "live", Document: taskPolicy{}, Seed: func(cfg config.Config) any {
|
||||
return taskPolicy{DiffCapLines: cfg.DiffCap(), NotifyWebhook: cfg.Notify.Webhook}
|
||||
return taskPolicyOf(cfg)
|
||||
}, Validate: func(input []byte) error {
|
||||
return validateAs(input, func(doc taskPolicy) error {
|
||||
if doc.DiffCapLines < 0 {
|
||||
@@ -28,7 +31,20 @@ func taskPolicyDefinition() Definition {
|
||||
return fmt.Errorf("notify_webhook must be an HTTP or HTTPS URL")
|
||||
}
|
||||
}
|
||||
if !alert.Severity(doc.NotifyMinSeverity).Valid() && doc.NotifyMinSeverity != "" {
|
||||
return fmt.Errorf("notify_min_severity must be info, warning or action")
|
||||
}
|
||||
if (doc.NotifySecret.Engine == "") != (doc.NotifySecret.Key == "") {
|
||||
return fmt.Errorf("notify_secret needs both an engine and a key")
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}}
|
||||
}
|
||||
|
||||
func taskPolicyOf(cfg config.Config) taskPolicy {
|
||||
return taskPolicy{
|
||||
DiffCapLines: cfg.DiffCap(), NotifyWebhook: cfg.Notify.Webhook,
|
||||
NotifyMinSeverity: cfg.Notify.MinSeverity, NotifySecret: cfg.Notify.Secret,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
package statestore
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"slices"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/alert"
|
||||
"github.com/samcharles93/archie-core/internal/domain/org"
|
||||
"github.com/samcharles93/archie-core/internal/domain/presence"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/staterpc"
|
||||
)
|
||||
|
||||
const (
|
||||
// alertSweepInterval is how often the store checks service health and
|
||||
// prunes closed alerts.
|
||||
alertSweepInterval = time.Minute
|
||||
// alertRetention is how long a resolved or dismissed alert is kept.
|
||||
alertRetention = 30 * 24 * time.Hour
|
||||
// serviceGrace is how long a service may be unhealthy before it is worth
|
||||
// an operator's attention: restarts and updates pass through it.
|
||||
serviceGrace = 5 * time.Minute
|
||||
)
|
||||
|
||||
// serviceWatch remembers since when each service has been unhealthy.
|
||||
type serviceWatch struct {
|
||||
since map[string]time.Time
|
||||
}
|
||||
|
||||
// unhealthy returns the services that have been down or degraded for longer
|
||||
// than serviceGrace, and forgets those that recovered. A service that never
|
||||
// reported is absent rather than unhealthy and is left out.
|
||||
func (w *serviceWatch) unhealthy(mesh []presence.Service, now time.Time) []string {
|
||||
if w.since == nil {
|
||||
w.since = map[string]time.Time{}
|
||||
}
|
||||
var out []string
|
||||
for _, service := range mesh {
|
||||
if !slices.Contains(presence.Services(), service.Service) || service.ReportedAt.IsZero() {
|
||||
continue
|
||||
}
|
||||
if service.State == presence.StateUp {
|
||||
delete(w.since, service.Service)
|
||||
continue
|
||||
}
|
||||
since, ok := w.since[service.Service]
|
||||
if !ok {
|
||||
since = now
|
||||
w.since[service.Service] = since
|
||||
}
|
||||
if now.Sub(since) >= serviceGrace {
|
||||
out = append(out, service.Service)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func serviceAlert(name string) alert.Input {
|
||||
return alert.Input{
|
||||
Org: org.DefaultOrgID, Kind: alert.KindServiceUnhealthy, Subject: "service:" + name,
|
||||
Severity: alert.SeverityWarning, Condition: true,
|
||||
Title: name + " is unhealthy",
|
||||
Body: fmt.Sprintf("%s has not been healthy for over %d minutes.", name, int(serviceGrace.Minutes())),
|
||||
Link: "/settings/status",
|
||||
}
|
||||
}
|
||||
|
||||
// startSweeps starts the store's periodic work: auto-updating packages, and
|
||||
// checking service health and pruning alerts.
|
||||
func (b *server) startSweeps(ctx context.Context, deps staterpc.Deps) {
|
||||
go b.autoUpdatePackages(ctx, deps.Packages)
|
||||
if deps.Alerts != nil {
|
||||
go b.sweepAlerts(ctx, deps.Alerts)
|
||||
}
|
||||
}
|
||||
|
||||
// sweepAlerts raises and clears service health alerts and prunes closed
|
||||
// alerts, until ctx ends. Service health has no transition to hang an alert
|
||||
// on, so it is checked here, next to the presence records it reads.
|
||||
func (b *server) sweepAlerts(ctx context.Context, store alert.Store) {
|
||||
pruner, _ := b.st.(alert.Pruner)
|
||||
records, _ := b.st.(interface {
|
||||
ListPresence(context.Context) ([]storecontract.Presence, error)
|
||||
})
|
||||
reporter := alert.Reporter{Raiser: store, Log: b.log, By: "state-store"}
|
||||
var watch serviceWatch
|
||||
ticker := time.NewTicker(alertSweepInterval)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
if records != nil {
|
||||
b.checkServices(ctx, reporter, records, &watch)
|
||||
}
|
||||
if pruner != nil {
|
||||
if _, err := pruner.PruneAlerts(ctx, time.Now().Add(-alertRetention)); err != nil && ctx.Err() == nil {
|
||||
b.log.Warn("prune alerts", "err", err)
|
||||
}
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-ticker.C:
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (b *server) checkServices(ctx context.Context, reporter alert.Reporter, records interface {
|
||||
ListPresence(context.Context) ([]storecontract.Presence, error)
|
||||
}, watch *serviceWatch,
|
||||
) {
|
||||
list, err := records.ListPresence(ctx)
|
||||
if err != nil {
|
||||
if ctx.Err() == nil {
|
||||
b.log.Warn("service health not checked", "err", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
now := time.Now()
|
||||
mesh := presence.Mesh(list, now)
|
||||
down := watch.unhealthy(mesh, now)
|
||||
for _, service := range mesh {
|
||||
if slices.Contains(presence.Services(), service.Service) {
|
||||
reporter.Sync(ctx, slices.Contains(down, service.Service), serviceAlert(service.Service))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -20,6 +20,7 @@ import (
|
||||
"github.com/samcharles93/archie-core/internal/app/servicekit"
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/domain/access"
|
||||
"github.com/samcharles93/archie-core/internal/domain/alert"
|
||||
"github.com/samcharles93/archie-core/internal/domain/health"
|
||||
"github.com/samcharles93/archie-core/internal/domain/identity"
|
||||
"github.com/samcharles93/archie-core/internal/domain/org"
|
||||
@@ -144,7 +145,7 @@ func Run(ctx context.Context, options Options) error { //nolint:cyclop // the co
|
||||
|
||||
deps := b.stateStoreDeps(grants)
|
||||
controlPlaneDeps(&deps, control)
|
||||
go b.autoUpdatePackages(ctx, deps.Packages)
|
||||
b.startSweeps(ctx, deps)
|
||||
return serveStateStore(ctx, listener, deps, opts)
|
||||
}
|
||||
|
||||
@@ -432,6 +433,9 @@ func (b *server) accessDeps(deps *staterpc.Deps) {
|
||||
if os, ok := b.st.(org.Repository); ok {
|
||||
deps.Orgs = os
|
||||
}
|
||||
if as, ok := b.st.(alert.Store); ok {
|
||||
deps.Alerts = as
|
||||
}
|
||||
}
|
||||
|
||||
// serveStateStore registers the StateStore gRPC service and serves it until
|
||||
|
||||
@@ -433,7 +433,6 @@ type TaskConfig struct {
|
||||
MaxRetries int `json:"max_retries"`
|
||||
Dispatch Dispatch `json:"dispatch"`
|
||||
DiffCapLines int `json:"diff_cap_lines"`
|
||||
Notify Notify `json:"notify"`
|
||||
Forge TaskForge `json:"forge"`
|
||||
ToolPolicy ToolPolicy `json:"tool_policy"`
|
||||
Review Review `json:"review"`
|
||||
@@ -469,7 +468,6 @@ func (c Config) ForTask() TaskConfig {
|
||||
MaxRetries: c.MaxRetries,
|
||||
Dispatch: Dispatch{Trigger: c.Dispatch.Trigger, AckReaction: c.Dispatch.AckReaction},
|
||||
DiffCapLines: c.DiffCap(),
|
||||
Notify: c.Notify,
|
||||
Forge: TaskForge{Host: c.Forge.Host},
|
||||
ToolPolicy: c.Tools.Policy,
|
||||
Review: c.Review,
|
||||
@@ -490,7 +488,6 @@ func (tc TaskConfig) ToConfig() Config {
|
||||
MaxRetries: tc.MaxRetries,
|
||||
Dispatch: Dispatch{Trigger: tc.Dispatch.Trigger, AckReaction: tc.Dispatch.AckReaction},
|
||||
DiffCapLines: &tc.DiffCapLines,
|
||||
Notify: tc.Notify,
|
||||
Forge: Forge{Host: tc.Forge.Host},
|
||||
Tools: ToolsConfig{Policy: tc.ToolPolicy},
|
||||
Review: tc.Review,
|
||||
@@ -899,10 +896,17 @@ type TelegramConfig struct {
|
||||
Token SecretRef `toml:"token" yaml:"token"`
|
||||
}
|
||||
|
||||
// Notify configures outbound notifications (n8n webhook → email etc.).
|
||||
// Notify configures outbound alert deliveries (n8n webhook → email etc.).
|
||||
type Notify struct {
|
||||
// Webhook receives JSON POSTs for events that need a human. Empty disables.
|
||||
// Webhook receives a JSON POST when an operator alert is raised or
|
||||
// resolved. Empty disables.
|
||||
Webhook string `toml:"webhook" json:"webhook" yaml:"webhook"`
|
||||
// MinSeverity is the lowest alert severity delivered: info, warning or
|
||||
// action. Empty means warning.
|
||||
MinSeverity string `toml:"min_severity" json:"min_severity" yaml:"min_severity"`
|
||||
// Secret signs each payload with HMAC-SHA256 in X-Archie-Signature.
|
||||
// Empty sends payloads unsigned.
|
||||
Secret SecretRef `toml:"secret" json:"-" yaml:"secret"`
|
||||
}
|
||||
|
||||
// Web configures the observability dashboard. Health is archied's own liveness
|
||||
|
||||
+1449
-325
File diff suppressed because it is too large.
Load diff
@@ -152,6 +152,12 @@ const (
|
||||
StateStoreService_SetMembership_FullMethodName = "/state.v1.StateStoreService/SetMembership"
|
||||
StateStoreService_RemoveMembership_FullMethodName = "/state.v1.StateStoreService/RemoveMembership"
|
||||
StateStoreService_AssignAgent_FullMethodName = "/state.v1.StateStoreService/AssignAgent"
|
||||
StateStoreService_RaiseAlert_FullMethodName = "/state.v1.StateStoreService/RaiseAlert"
|
||||
StateStoreService_ResolveAlert_FullMethodName = "/state.v1.StateStoreService/ResolveAlert"
|
||||
StateStoreService_DismissAlert_FullMethodName = "/state.v1.StateStoreService/DismissAlert"
|
||||
StateStoreService_ListAlerts_FullMethodName = "/state.v1.StateStoreService/ListAlerts"
|
||||
StateStoreService_ClaimAlertDeliveries_FullMethodName = "/state.v1.StateStoreService/ClaimAlertDeliveries"
|
||||
StateStoreService_RecordAlertAttempt_FullMethodName = "/state.v1.StateStoreService/RecordAlertAttempt"
|
||||
)
|
||||
|
||||
// StateStoreServiceClient is the client API for StateStoreService service.
|
||||
@@ -413,6 +419,18 @@ type StateStoreServiceClient interface {
|
||||
SetMembership(ctx context.Context, in *SetMembershipRequest, opts ...grpc.CallOption) (*SetMembershipResponse, error)
|
||||
RemoveMembership(ctx context.Context, in *RemoveMembershipRequest, opts ...grpc.CallOption) (*RemoveMembershipResponse, error)
|
||||
AssignAgent(ctx context.Context, in *AssignAgentRequest, opts ...grpc.CallOption) (*AssignAgentResponse, error)
|
||||
// Operator alerts (internal/domain/alert). A caller acting for a principal
|
||||
// reads, dismisses and raises only in that principal's org; a request org is
|
||||
// ignored for it. A service acting for no one names the org itself.
|
||||
// RaiseAlert and ResolveAlert are idempotent, so a periodic check can call
|
||||
// them every tick. ClaimAlertDeliveries and RecordAlertAttempt serve the
|
||||
// outbound webhook and refuse a caller scoped to an org.
|
||||
RaiseAlert(ctx context.Context, in *RaiseAlertRequest, opts ...grpc.CallOption) (*RaiseAlertResponse, error)
|
||||
ResolveAlert(ctx context.Context, in *ResolveAlertRequest, opts ...grpc.CallOption) (*ResolveAlertResponse, error)
|
||||
DismissAlert(ctx context.Context, in *DismissAlertRequest, opts ...grpc.CallOption) (*DismissAlertResponse, error)
|
||||
ListAlerts(ctx context.Context, in *ListAlertsRequest, opts ...grpc.CallOption) (*ListAlertsResponse, error)
|
||||
ClaimAlertDeliveries(ctx context.Context, in *ClaimAlertDeliveriesRequest, opts ...grpc.CallOption) (*ClaimAlertDeliveriesResponse, error)
|
||||
RecordAlertAttempt(ctx context.Context, in *RecordAlertAttemptRequest, opts ...grpc.CallOption) (*RecordAlertAttemptResponse, error)
|
||||
}
|
||||
|
||||
type stateStoreServiceClient struct {
|
||||
@@ -1780,6 +1798,66 @@ func (c *stateStoreServiceClient) AssignAgent(ctx context.Context, in *AssignAge
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *stateStoreServiceClient) RaiseAlert(ctx context.Context, in *RaiseAlertRequest, opts ...grpc.CallOption) (*RaiseAlertResponse, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(RaiseAlertResponse)
|
||||
err := c.cc.Invoke(ctx, StateStoreService_RaiseAlert_FullMethodName, in, out, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *stateStoreServiceClient) ResolveAlert(ctx context.Context, in *ResolveAlertRequest, opts ...grpc.CallOption) (*ResolveAlertResponse, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(ResolveAlertResponse)
|
||||
err := c.cc.Invoke(ctx, StateStoreService_ResolveAlert_FullMethodName, in, out, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *stateStoreServiceClient) DismissAlert(ctx context.Context, in *DismissAlertRequest, opts ...grpc.CallOption) (*DismissAlertResponse, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(DismissAlertResponse)
|
||||
err := c.cc.Invoke(ctx, StateStoreService_DismissAlert_FullMethodName, in, out, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *stateStoreServiceClient) ListAlerts(ctx context.Context, in *ListAlertsRequest, opts ...grpc.CallOption) (*ListAlertsResponse, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(ListAlertsResponse)
|
||||
err := c.cc.Invoke(ctx, StateStoreService_ListAlerts_FullMethodName, in, out, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *stateStoreServiceClient) ClaimAlertDeliveries(ctx context.Context, in *ClaimAlertDeliveriesRequest, opts ...grpc.CallOption) (*ClaimAlertDeliveriesResponse, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(ClaimAlertDeliveriesResponse)
|
||||
err := c.cc.Invoke(ctx, StateStoreService_ClaimAlertDeliveries_FullMethodName, in, out, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *stateStoreServiceClient) RecordAlertAttempt(ctx context.Context, in *RecordAlertAttemptRequest, opts ...grpc.CallOption) (*RecordAlertAttemptResponse, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(RecordAlertAttemptResponse)
|
||||
err := c.cc.Invoke(ctx, StateStoreService_RecordAlertAttempt_FullMethodName, in, out, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// StateStoreServiceServer is the server API for StateStoreService service.
|
||||
// All implementations must embed UnimplementedStateStoreServiceServer
|
||||
// for forward compatibility.
|
||||
@@ -2039,6 +2117,18 @@ type StateStoreServiceServer interface {
|
||||
SetMembership(context.Context, *SetMembershipRequest) (*SetMembershipResponse, error)
|
||||
RemoveMembership(context.Context, *RemoveMembershipRequest) (*RemoveMembershipResponse, error)
|
||||
AssignAgent(context.Context, *AssignAgentRequest) (*AssignAgentResponse, error)
|
||||
// Operator alerts (internal/domain/alert). A caller acting for a principal
|
||||
// reads, dismisses and raises only in that principal's org; a request org is
|
||||
// ignored for it. A service acting for no one names the org itself.
|
||||
// RaiseAlert and ResolveAlert are idempotent, so a periodic check can call
|
||||
// them every tick. ClaimAlertDeliveries and RecordAlertAttempt serve the
|
||||
// outbound webhook and refuse a caller scoped to an org.
|
||||
RaiseAlert(context.Context, *RaiseAlertRequest) (*RaiseAlertResponse, error)
|
||||
ResolveAlert(context.Context, *ResolveAlertRequest) (*ResolveAlertResponse, error)
|
||||
DismissAlert(context.Context, *DismissAlertRequest) (*DismissAlertResponse, error)
|
||||
ListAlerts(context.Context, *ListAlertsRequest) (*ListAlertsResponse, error)
|
||||
ClaimAlertDeliveries(context.Context, *ClaimAlertDeliveriesRequest) (*ClaimAlertDeliveriesResponse, error)
|
||||
RecordAlertAttempt(context.Context, *RecordAlertAttemptRequest) (*RecordAlertAttemptResponse, error)
|
||||
mustEmbedUnimplementedStateStoreServiceServer()
|
||||
}
|
||||
|
||||
@@ -2448,6 +2538,24 @@ func (UnimplementedStateStoreServiceServer) RemoveMembership(context.Context, *R
|
||||
func (UnimplementedStateStoreServiceServer) AssignAgent(context.Context, *AssignAgentRequest) (*AssignAgentResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method AssignAgent not implemented")
|
||||
}
|
||||
func (UnimplementedStateStoreServiceServer) RaiseAlert(context.Context, *RaiseAlertRequest) (*RaiseAlertResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method RaiseAlert not implemented")
|
||||
}
|
||||
func (UnimplementedStateStoreServiceServer) ResolveAlert(context.Context, *ResolveAlertRequest) (*ResolveAlertResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method ResolveAlert not implemented")
|
||||
}
|
||||
func (UnimplementedStateStoreServiceServer) DismissAlert(context.Context, *DismissAlertRequest) (*DismissAlertResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method DismissAlert not implemented")
|
||||
}
|
||||
func (UnimplementedStateStoreServiceServer) ListAlerts(context.Context, *ListAlertsRequest) (*ListAlertsResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method ListAlerts not implemented")
|
||||
}
|
||||
func (UnimplementedStateStoreServiceServer) ClaimAlertDeliveries(context.Context, *ClaimAlertDeliveriesRequest) (*ClaimAlertDeliveriesResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method ClaimAlertDeliveries not implemented")
|
||||
}
|
||||
func (UnimplementedStateStoreServiceServer) RecordAlertAttempt(context.Context, *RecordAlertAttemptRequest) (*RecordAlertAttemptResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method RecordAlertAttempt not implemented")
|
||||
}
|
||||
func (UnimplementedStateStoreServiceServer) mustEmbedUnimplementedStateStoreServiceServer() {}
|
||||
func (UnimplementedStateStoreServiceServer) testEmbeddedByValue() {}
|
||||
|
||||
@@ -4842,6 +4950,114 @@ func _StateStoreService_AssignAgent_Handler(srv interface{}, ctx context.Context
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _StateStoreService_RaiseAlert_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(RaiseAlertRequest)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(StateStoreServiceServer).RaiseAlert(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: StateStoreService_RaiseAlert_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(StateStoreServiceServer).RaiseAlert(ctx, req.(*RaiseAlertRequest))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _StateStoreService_ResolveAlert_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(ResolveAlertRequest)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(StateStoreServiceServer).ResolveAlert(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: StateStoreService_ResolveAlert_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(StateStoreServiceServer).ResolveAlert(ctx, req.(*ResolveAlertRequest))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _StateStoreService_DismissAlert_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(DismissAlertRequest)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(StateStoreServiceServer).DismissAlert(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: StateStoreService_DismissAlert_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(StateStoreServiceServer).DismissAlert(ctx, req.(*DismissAlertRequest))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _StateStoreService_ListAlerts_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(ListAlertsRequest)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(StateStoreServiceServer).ListAlerts(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: StateStoreService_ListAlerts_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(StateStoreServiceServer).ListAlerts(ctx, req.(*ListAlertsRequest))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _StateStoreService_ClaimAlertDeliveries_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(ClaimAlertDeliveriesRequest)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(StateStoreServiceServer).ClaimAlertDeliveries(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: StateStoreService_ClaimAlertDeliveries_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(StateStoreServiceServer).ClaimAlertDeliveries(ctx, req.(*ClaimAlertDeliveriesRequest))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _StateStoreService_RecordAlertAttempt_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(RecordAlertAttemptRequest)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(StateStoreServiceServer).RecordAlertAttempt(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: StateStoreService_RecordAlertAttempt_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(StateStoreServiceServer).RecordAlertAttempt(ctx, req.(*RecordAlertAttemptRequest))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
// StateStoreService_ServiceDesc is the grpc.ServiceDesc for StateStoreService service.
|
||||
// It's only intended for direct use with grpc.RegisterService,
|
||||
// and not to be introspected or modified (even as a copy)
|
||||
@@ -5369,6 +5585,30 @@ var StateStoreService_ServiceDesc = grpc.ServiceDesc{
|
||||
MethodName: "AssignAgent",
|
||||
Handler: _StateStoreService_AssignAgent_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "RaiseAlert",
|
||||
Handler: _StateStoreService_RaiseAlert_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "ResolveAlert",
|
||||
Handler: _StateStoreService_ResolveAlert_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "DismissAlert",
|
||||
Handler: _StateStoreService_DismissAlert_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "ListAlerts",
|
||||
Handler: _StateStoreService_ListAlerts_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "ClaimAlertDeliveries",
|
||||
Handler: _StateStoreService_ClaimAlertDeliveries_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "RecordAlertAttempt",
|
||||
Handler: _StateStoreService_RecordAlertAttempt_Handler,
|
||||
},
|
||||
},
|
||||
Streams: []grpc.StreamDesc{
|
||||
{
|
||||
|
||||
@@ -123,10 +123,9 @@ func TestIdentityTasksUseLiveSettings(t *testing.T) {
|
||||
root.Models = map[string]string{"builder": model}
|
||||
root.Budgets.MaxSteps++
|
||||
root.Dispatch.Trigger = "label"
|
||||
root.Notify.Webhook = "https://example.test/notify"
|
||||
d.Cfg.Set(root)
|
||||
got := d.configFor(task)
|
||||
if !reflect.DeepEqual(got.Models, root.Models) || !reflect.DeepEqual(got.Providers, root.Providers) || got.Budgets != root.Budgets || got.Dispatch != root.Dispatch || got.Notify != root.Notify {
|
||||
if !reflect.DeepEqual(got.Models, root.Models) || !reflect.DeepEqual(got.Providers, root.Providers) || got.Budgets != root.Budgets || got.Dispatch != root.Dispatch {
|
||||
t.Fatalf("identity settings replaced the current runtime settings: %+v", got)
|
||||
}
|
||||
repo, ok := d.repoFor(task)
|
||||
|
||||
@@ -0,0 +1,279 @@
|
||||
// Package alert is the operator's list of things that need a human. The State
|
||||
// Store owns the rows; services raise and clear alerts through its contract and
|
||||
// never read the table.
|
||||
//
|
||||
// An alert is one row per (org, kind, subject). A condition alert is backed by
|
||||
// something that can stop being true, so whoever detects it resolves it when
|
||||
// it clears. An event alert records something that happened and stays until
|
||||
// an operator dismisses it.
|
||||
//
|
||||
// Titles and bodies are shown to every member of the org and sent to the
|
||||
// notify webhook. A raiser writes them from fixed text and ids, never from an
|
||||
// error string, a command line or a credential.
|
||||
package alert
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/org"
|
||||
)
|
||||
|
||||
// Severity orders how loudly an alert asks for attention.
|
||||
type Severity string
|
||||
|
||||
const (
|
||||
SeverityInfo Severity = "info"
|
||||
SeverityWarning Severity = "warning"
|
||||
SeverityAction Severity = "action"
|
||||
)
|
||||
|
||||
// Rank orders severities, highest first needing the most attention. An unknown
|
||||
// severity ranks below info.
|
||||
func (s Severity) Rank() int {
|
||||
switch s {
|
||||
case SeverityAction:
|
||||
return 3
|
||||
case SeverityWarning:
|
||||
return 2
|
||||
case SeverityInfo:
|
||||
return 1
|
||||
default:
|
||||
return 0
|
||||
}
|
||||
}
|
||||
|
||||
// Valid reports whether s is a known severity.
|
||||
func (s Severity) Valid() bool { return s.Rank() > 0 }
|
||||
|
||||
// State is where an alert is in its life.
|
||||
type State string
|
||||
|
||||
const (
|
||||
StateOpen State = "open"
|
||||
StateResolved State = "resolved"
|
||||
StateDismissed State = "dismissed"
|
||||
)
|
||||
|
||||
// Conditions and events the in-tree raisers use. The kind is part of the
|
||||
// dedup key, so renaming one orphans its open alerts.
|
||||
const (
|
||||
KindTaskNeedsHuman = "task.needs_human"
|
||||
KindTaskFailed = "task.failed"
|
||||
KindModelAlias = "model.alias"
|
||||
KindProviderNoKey = "provider.no_credential"
|
||||
KindToolNoBinding = "tool.no_credential"
|
||||
KindCredentialInvalid = "credential.rejected"
|
||||
KindServiceUnhealthy = "service.unhealthy"
|
||||
KindReleaseAvailable = "release.available"
|
||||
)
|
||||
|
||||
// Limits on what a raiser may store.
|
||||
const (
|
||||
maxKindLen = 64
|
||||
maxSubjectLen = 200
|
||||
maxTitleLen = 200
|
||||
maxBodyLen = 2000
|
||||
maxLinkLen = 500
|
||||
)
|
||||
|
||||
// ErrInvalid is returned for an alert the store would refuse to hold.
|
||||
var ErrInvalid = errors.New("alert: invalid")
|
||||
|
||||
// Key is what makes two raises the same alert.
|
||||
type Key struct {
|
||||
Org org.OrgID
|
||||
Kind string
|
||||
Subject string
|
||||
}
|
||||
|
||||
// Input is one raise.
|
||||
type Input struct {
|
||||
Key
|
||||
Severity Severity
|
||||
Title string
|
||||
Body string
|
||||
// Link is the dashboard path that fixes it, such as /tasks/12.
|
||||
Link string
|
||||
// Condition is true when the raiser resolves the alert itself once the
|
||||
// condition clears. An event alert (false) stays until dismissed.
|
||||
Condition bool
|
||||
}
|
||||
|
||||
// Validate refuses an input the store cannot hold.
|
||||
func (in Input) Validate() error {
|
||||
switch {
|
||||
case in.Org == "":
|
||||
return fmt.Errorf("%w: org is required", ErrInvalid)
|
||||
case in.Kind == "" || len(in.Kind) > maxKindLen:
|
||||
return fmt.Errorf("%w: kind is required and at most %d bytes", ErrInvalid, maxKindLen)
|
||||
case in.Subject == "" || len(in.Subject) > maxSubjectLen:
|
||||
return fmt.Errorf("%w: subject is required and at most %d bytes", ErrInvalid, maxSubjectLen)
|
||||
case !in.Severity.Valid():
|
||||
return fmt.Errorf("%w: severity %q", ErrInvalid, in.Severity)
|
||||
case strings.TrimSpace(in.Title) == "" || len(in.Title) > maxTitleLen:
|
||||
return fmt.Errorf("%w: title is required and at most %d bytes", ErrInvalid, maxTitleLen)
|
||||
case len(in.Body) > maxBodyLen:
|
||||
return fmt.Errorf("%w: body is at most %d bytes", ErrInvalid, maxBodyLen)
|
||||
case len(in.Link) > maxLinkLen || (in.Link != "" && !strings.HasPrefix(in.Link, "/")):
|
||||
return fmt.Errorf("%w: link must be a dashboard path of at most %d bytes", ErrInvalid, maxLinkLen)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Alert is one row.
|
||||
type Alert struct {
|
||||
ID int64
|
||||
Key
|
||||
Severity Severity
|
||||
Title string
|
||||
Body string
|
||||
Link string
|
||||
Condition bool
|
||||
State State
|
||||
FirstRaised time.Time
|
||||
LastSeen time.Time
|
||||
Count int64
|
||||
// ClosedBy and ClosedAt say who resolved or dismissed the alert and when.
|
||||
ClosedBy string
|
||||
ClosedAt time.Time
|
||||
// Deliveries are the outbound notices this alert owed, newest first.
|
||||
Deliveries []Delivery
|
||||
}
|
||||
|
||||
// Apply is the alert after a raise. prev is the existing row, nil when there
|
||||
// is none. opened reports that the alert became open: it is new, or it was
|
||||
// resolved, or it was an event alert that had been dismissed. An open alert
|
||||
// raised again only bumps its count and last seen. A dismissed condition
|
||||
// alert is snoozed: it stays dismissed until the condition clears and recurs.
|
||||
func Apply(prev *Alert, in Input, now time.Time) (next Alert, opened bool) {
|
||||
fresh := Alert{
|
||||
Key: in.Key, Severity: in.Severity, Title: in.Title, Body: in.Body, Link: in.Link,
|
||||
Condition: in.Condition, State: StateOpen, FirstRaised: now, LastSeen: now, Count: 1,
|
||||
}
|
||||
if prev == nil {
|
||||
return fresh, true
|
||||
}
|
||||
next = *prev
|
||||
next.Severity, next.Title, next.Body, next.Link, next.Condition = in.Severity, in.Title, in.Body, in.Link, in.Condition
|
||||
next.LastSeen = now
|
||||
switch {
|
||||
case prev.State == StateOpen:
|
||||
next.Count++
|
||||
return next, false
|
||||
case prev.State == StateDismissed && prev.Condition && in.Condition:
|
||||
return next, false
|
||||
default:
|
||||
fresh.ID, fresh.Deliveries = prev.ID, prev.Deliveries
|
||||
return fresh, true
|
||||
}
|
||||
}
|
||||
|
||||
// Resolve is the alert after its condition cleared. changed reports that it
|
||||
// moved to resolved. Only a condition alert has a condition to clear: an
|
||||
// event alert stays until dismissed, and a resolved alert stays as it is. A
|
||||
// snoozed (dismissed) condition alert resolves, so it can come back if the
|
||||
// condition recurs.
|
||||
func Resolve(prev Alert, by string, now time.Time) (next Alert, changed bool) {
|
||||
if !prev.Condition || prev.State == StateResolved {
|
||||
return prev, false
|
||||
}
|
||||
prev.State, prev.ClosedBy, prev.ClosedAt = StateResolved, by, now
|
||||
return prev, true
|
||||
}
|
||||
|
||||
// Dismiss is the alert after an operator dismissed it. changed reports that it
|
||||
// moved to dismissed; only an open alert can be dismissed.
|
||||
func Dismiss(prev Alert, by string, now time.Time) (next Alert, changed bool) {
|
||||
if prev.State != StateOpen {
|
||||
return prev, false
|
||||
}
|
||||
prev.State, prev.ClosedBy, prev.ClosedAt = StateDismissed, by, now
|
||||
return prev, true
|
||||
}
|
||||
|
||||
// Filter selects what List returns.
|
||||
type Filter struct {
|
||||
// States to include; empty means open only.
|
||||
States []State
|
||||
Limit int
|
||||
}
|
||||
|
||||
// Store is the State Store's alert surface.
|
||||
type Store interface {
|
||||
Raiser
|
||||
// Dismiss dismisses an open alert in org.
|
||||
DismissAlert(ctx context.Context, orgID org.OrgID, id int64, by string) error
|
||||
// List returns an org's alerts, highest severity then newest first.
|
||||
ListAlerts(ctx context.Context, orgID org.OrgID, filter Filter) ([]Alert, error)
|
||||
Deliverer
|
||||
}
|
||||
|
||||
// Pruner removes alerts that closed before a retention cutoff, with their
|
||||
// deliveries. The State Store runs it; it is not part of the contract.
|
||||
type Pruner interface {
|
||||
PruneAlerts(ctx context.Context, cutoff time.Time) (int64, error)
|
||||
}
|
||||
|
||||
// Raiser is what a service needs to raise and clear alerts.
|
||||
type Raiser interface {
|
||||
// RaiseAlert stores in, idempotently: see Apply.
|
||||
RaiseAlert(ctx context.Context, in Input) (Alert, error)
|
||||
// ResolveAlert clears a condition alert; no alert under key is not an
|
||||
// error.
|
||||
ResolveAlert(ctx context.Context, key Key, by string) error
|
||||
}
|
||||
|
||||
// Reporter raises and clears alerts for a service. A failure is logged and
|
||||
// left for the next check: reporting never blocks or fails the caller's work.
|
||||
// The zero Reporter, and one with no Raiser, does nothing.
|
||||
type Reporter struct {
|
||||
Raiser Raiser
|
||||
Log *slog.Logger
|
||||
// By names the resolver recorded on alerts this reporter clears.
|
||||
By string
|
||||
}
|
||||
|
||||
// Raise stores in.
|
||||
func (r Reporter) Raise(ctx context.Context, in Input) {
|
||||
if r.Raiser == nil {
|
||||
return
|
||||
}
|
||||
if _, err := r.Raiser.RaiseAlert(ctx, in); err != nil {
|
||||
r.warn("alert not raised", in.Key, err)
|
||||
}
|
||||
}
|
||||
|
||||
// Resolve clears the alert under key.
|
||||
func (r Reporter) Resolve(ctx context.Context, key Key) {
|
||||
if r.Raiser == nil {
|
||||
return
|
||||
}
|
||||
if err := r.Raiser.ResolveAlert(ctx, key, r.By); err != nil {
|
||||
r.warn("alert not resolved", key, err)
|
||||
}
|
||||
}
|
||||
|
||||
// Sync raises in while active holds and resolves it once it does not. It is
|
||||
// the whole body of a periodic check for one condition.
|
||||
func (r Reporter) Sync(ctx context.Context, active bool, in Input) {
|
||||
if active {
|
||||
r.Raise(ctx, in)
|
||||
return
|
||||
}
|
||||
r.Resolve(ctx, in.Key)
|
||||
}
|
||||
|
||||
func (r Reporter) warn(msg string, key Key, err error) {
|
||||
if r.Log != nil {
|
||||
r.Log.Warn(msg, "org", key.Org, "kind", key.Kind, "subject", key.Subject, "err", err)
|
||||
}
|
||||
}
|
||||
|
||||
// ErrNotFound is returned for an alert or delivery that does not exist, or
|
||||
// that belongs to another org.
|
||||
var ErrNotFound = errors.New("alert: not found")
|
||||
@@ -0,0 +1,85 @@
|
||||
package alert
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Delivery states.
|
||||
const (
|
||||
DeliveryPending = "pending"
|
||||
DeliveryDelivered = "delivered"
|
||||
DeliveryFailed = "failed"
|
||||
// DeliverySkipped is a notice nothing was configured to send, or whose
|
||||
// severity was below the threshold.
|
||||
DeliverySkipped = "skipped"
|
||||
)
|
||||
|
||||
// What a delivery announces.
|
||||
const (
|
||||
EventRaised = "raised"
|
||||
EventResolved = "resolved"
|
||||
)
|
||||
|
||||
// MaxDeliveryAttempts bounds the retries of one notice. After the last the
|
||||
// delivery is failed and kept on the alert.
|
||||
const MaxDeliveryAttempts = 5
|
||||
|
||||
// RetryDelay is how long to wait after the attempt-th failed attempt.
|
||||
func RetryDelay(attempt int64) time.Duration {
|
||||
delays := [...]time.Duration{time.Minute, 5 * time.Minute, 15 * time.Minute, time.Hour}
|
||||
return delays[min(max(attempt, 1), int64(len(delays)))-1]
|
||||
}
|
||||
|
||||
// Delivery is one notice an alert owes: raised or resolved.
|
||||
type Delivery struct {
|
||||
ID int64
|
||||
AlertID int64
|
||||
Event string
|
||||
State string
|
||||
CreatedAt time.Time
|
||||
// NextAttemptAt is when a pending delivery is next due.
|
||||
NextAttemptAt time.Time
|
||||
Attempts []Attempt
|
||||
}
|
||||
|
||||
// Attempt is one try at a delivery.
|
||||
type Attempt struct {
|
||||
N int64
|
||||
At time.Time
|
||||
StatusCode int
|
||||
Error string
|
||||
}
|
||||
|
||||
// Due is a delivery with the alert it announces.
|
||||
type Due struct {
|
||||
Delivery
|
||||
Alert Alert
|
||||
// Attempt is the number of this try, counting from one.
|
||||
Attempt int64
|
||||
}
|
||||
|
||||
// Outcome is how one attempt went.
|
||||
type Outcome struct {
|
||||
DeliveryID int64
|
||||
// Skipped closes the delivery without an attempt.
|
||||
Skipped bool
|
||||
StatusCode int
|
||||
// Error is empty on success. It is stored on the alert and shown to the
|
||||
// operator, so it names the failure and never the request.
|
||||
Error string
|
||||
}
|
||||
|
||||
// OK reports a successful attempt.
|
||||
func (o Outcome) OK() bool { return !o.Skipped && o.Error == "" }
|
||||
|
||||
// Deliverer is the outbound half of the store: the due notices, and what
|
||||
// became of each.
|
||||
type Deliverer interface {
|
||||
// ClaimDeliveries returns up to limit pending deliveries that are due and
|
||||
// pushes each one's next attempt out, so a worker that dies mid-attempt
|
||||
// does not strand it and two workers do not send it twice.
|
||||
ClaimAlertDeliveries(ctx context.Context, limit int) ([]Due, error)
|
||||
// RecordAttempt records an attempt and settles or reschedules the delivery.
|
||||
RecordAlertAttempt(ctx context.Context, outcome Outcome) error
|
||||
}
|
||||
@@ -1,16 +1,13 @@
|
||||
package workflow
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
// notify posts a one-way notice on a forge-backed task's issue and, when
|
||||
// configured, to the notify webhook.
|
||||
// notify posts a one-way notice on a forge-backed task's issue. The operator
|
||||
// alert for the task waiting on a human is raised by the State Store when the
|
||||
// task parks.
|
||||
func notify(ctx context.Context, tc *TaskContext, kind string) {
|
||||
if tc.Task.IsForgeBacked() {
|
||||
if _, err := tc.Forge.Comment(ctx, tc.Task.Owner, tc.Task.Repo, tc.Task.IssueNumber, deliveryNotice(tc, kind)); err != nil {
|
||||
@@ -18,37 +15,6 @@ func notify(ctx context.Context, tc *TaskContext, kind string) {
|
||||
"kind", kind, "issue", tc.Task.IssueNumber, "err", err)
|
||||
}
|
||||
}
|
||||
url := tc.Cfg.Notify.Webhook
|
||||
if url == "" {
|
||||
return
|
||||
}
|
||||
fields := map[string]any{
|
||||
"type": kind, "repo": tc.Repo.FullName(), "task_id": tc.Task.ID,
|
||||
"source": tc.Task.Source, "identity": tc.Task.Identity,
|
||||
"title": tc.Task.Title, "prd": tc.Task.Plan,
|
||||
}
|
||||
if tc.Task.IsForgeBacked() {
|
||||
fields["issue"] = tc.Task.IssueNumber
|
||||
fields["issue_url"] = fmt.Sprintf("%s/%s/issues/%d",
|
||||
tc.Cfg.Forge.Host, tc.Repo.FullName(), tc.Task.IssueNumber)
|
||||
}
|
||||
payload, _ := json.Marshal(fields)
|
||||
reqCtx, cancel := context.WithTimeout(ctx, 10*time.Second)
|
||||
defer cancel()
|
||||
req, err := http.NewRequestWithContext(reqCtx, http.MethodPost, url, bytes.NewReader(payload))
|
||||
if err != nil {
|
||||
tc.Log.Warn("notify webhook request build failed", "err", err)
|
||||
return
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
tc.Log.Warn("notify webhook failed", "err", err)
|
||||
return
|
||||
}
|
||||
if err := resp.Body.Close(); err != nil {
|
||||
tc.Log.Warn("close notify webhook response", "err", err)
|
||||
}
|
||||
}
|
||||
|
||||
// deliveryNotice is the body of the one-way notice notify posts on a
|
||||
|
||||
@@ -72,6 +72,10 @@ const (
|
||||
KindTaskArchiveRequested = "task_archive_requested"
|
||||
KindWorkRequestSubmitted = "work_request_submitted"
|
||||
KindLog = "log" // data: level, msg
|
||||
// KindAlert marks an operator alert opening, resolving or being
|
||||
// dismissed, so the dashboard's bell updates over the event stream.
|
||||
// data: id, kind, state, severity.
|
||||
KindAlert = "alert"
|
||||
|
||||
// KindChangesCaptured records one attempt's change at commit or push time.
|
||||
// data: schema, owner, repo, base, branch, head_sha, base_sha, pr_number,
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
// Package alertwebhook delivers operator alerts to the notify webhook.
|
||||
package alertwebhook
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/alert"
|
||||
"github.com/samcharles93/archie-core/internal/webhookguard"
|
||||
)
|
||||
|
||||
// SignatureHeader carries the payload's HMAC-SHA256 when a secret is set.
|
||||
const SignatureHeader = "X-Archie-Signature"
|
||||
|
||||
const timeout = 10 * time.Second
|
||||
|
||||
type payload struct {
|
||||
Event string `json:"event"`
|
||||
Attempt int64 `json:"attempt"`
|
||||
Alert body `json:"alert"`
|
||||
}
|
||||
|
||||
type body struct {
|
||||
ID int64 `json:"id"`
|
||||
Org string `json:"org"`
|
||||
Kind string `json:"kind"`
|
||||
Subject string `json:"subject"`
|
||||
Severity string `json:"severity"`
|
||||
Title string `json:"title"`
|
||||
Body string `json:"body"`
|
||||
Link string `json:"link"`
|
||||
State string `json:"state"`
|
||||
FirstRaised time.Time `json:"first_raised"`
|
||||
LastSeen time.Time `json:"last_seen"`
|
||||
Count int64 `json:"count"`
|
||||
}
|
||||
|
||||
// Payload is the JSON body sent for a due delivery.
|
||||
func Payload(due alert.Due) ([]byte, error) {
|
||||
a := due.Alert
|
||||
return json.Marshal(payload{
|
||||
Event: due.Event, Attempt: due.Attempt,
|
||||
Alert: body{
|
||||
ID: a.ID, Org: string(a.Org), Kind: a.Kind, Subject: a.Subject, Severity: string(a.Severity),
|
||||
Title: a.Title, Body: a.Body, Link: a.Link, State: string(a.State),
|
||||
FirstRaised: a.FirstRaised, LastSeen: a.LastSeen, Count: a.Count,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
// Send posts due to webhook, signed with secret when it is not empty. The
|
||||
// outcome's error names what went wrong without the webhook URL, which may
|
||||
// carry a token.
|
||||
func Send(ctx context.Context, client *http.Client, webhook, secret string, due alert.Due) alert.Outcome {
|
||||
out := alert.Outcome{DeliveryID: due.ID}
|
||||
data, err := Payload(due)
|
||||
if err != nil {
|
||||
out.Error = "encode payload"
|
||||
return out
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(ctx, timeout)
|
||||
defer cancel()
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, webhook, bytes.NewReader(data))
|
||||
if err != nil {
|
||||
out.Error = "invalid webhook URL"
|
||||
return out
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("X-Archie-Event", due.Event)
|
||||
req.Header.Set("X-Archie-Delivery", fmt.Sprint(due.ID))
|
||||
if secret != "" {
|
||||
req.Header.Set(SignatureHeader, webhookguard.SignHMAC(data, secret))
|
||||
}
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
if urlErr, ok := errors.AsType[*url.Error](err); ok {
|
||||
err = urlErr.Err
|
||||
}
|
||||
out.Error = err.Error()
|
||||
return out
|
||||
}
|
||||
_ = resp.Body.Close()
|
||||
out.StatusCode = resp.StatusCode
|
||||
if resp.StatusCode < 200 || resp.StatusCode > 299 {
|
||||
out.Error = fmt.Sprintf("webhook answered %d", resp.StatusCode)
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,328 @@
|
||||
// Operator alerts: the Postgres implementation of internal/domain/alert.Store.
|
||||
// Every write runs in a transaction that holds an advisory lock on the alert's
|
||||
// key, so a raise and a resolve of one alert never interleave, and records the
|
||||
// event and the delivery the change owes in the same commit.
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/alert"
|
||||
"github.com/samcharles93/archie-core/internal/domain/org"
|
||||
"github.com/samcharles93/archie-core/internal/events"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/postgresdb"
|
||||
)
|
||||
|
||||
var (
|
||||
_ alert.Store = (*Store)(nil)
|
||||
_ alert.Pruner = (*Store)(nil)
|
||||
)
|
||||
|
||||
// deliveriesPerAlert bounds the delivery history one listed alert carries.
|
||||
const deliveriesPerAlert = 10
|
||||
|
||||
func alertFromRow(r postgresdb.Alert) alert.Alert {
|
||||
a := alert.Alert{
|
||||
ID: r.ID,
|
||||
Org: org.OrgID(r.OrgID), Kind: r.Kind, Subject: r.Subject,
|
||||
Severity: alert.Severity(r.Severity), Title: r.Title, Body: r.Body, Link: r.Link,
|
||||
Condition: r.IsCondition, State: alert.State(r.State),
|
||||
FirstRaised: r.FirstRaised, LastSeen: r.LastSeen, Count: r.Count, ClosedBy: r.ClosedBy,
|
||||
}
|
||||
if r.ClosedAt.Valid {
|
||||
a.ClosedAt = r.ClosedAt.Time
|
||||
}
|
||||
return a
|
||||
}
|
||||
|
||||
func alertParams(a alert.Alert) postgresdb.UpsertAlertParams {
|
||||
return postgresdb.UpsertAlertParams{
|
||||
OrgID: string(a.Org), Kind: a.Kind, Subject: a.Subject, Severity: string(a.Severity),
|
||||
Title: a.Title, Body: a.Body, Link: a.Link, IsCondition: a.Condition, State: string(a.State),
|
||||
FirstRaised: a.FirstRaised, LastSeen: a.LastSeen, Count: a.Count, ClosedBy: a.ClosedBy,
|
||||
ClosedAt: pgtype.Timestamptz{Time: a.ClosedAt, Valid: !a.ClosedAt.IsZero()},
|
||||
}
|
||||
}
|
||||
|
||||
func alertLockKey(k alert.Key) string { return string(k.Org) + "\x00" + k.Kind + "\x00" + k.Subject }
|
||||
|
||||
// lockedAlert takes the key's lock and returns the stored alert, nil when
|
||||
// there is none.
|
||||
func lockedAlert(ctx context.Context, q *postgresdb.Queries, key alert.Key) (*alert.Alert, error) {
|
||||
if err := q.LockAlertKey(ctx, alertLockKey(key)); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
row, err := q.GetAlertByKey(ctx, postgresdb.GetAlertByKeyParams{OrgID: string(key.Org), Kind: key.Kind, Subject: key.Subject})
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
a := alertFromRow(row)
|
||||
return &a, nil
|
||||
}
|
||||
|
||||
// alertChanged records an alert's change on the event stream, and the
|
||||
// delivery it owes when delivery is not empty.
|
||||
func alertChanged(ctx context.Context, q *postgresdb.Queries, a alert.Alert, delivery string) error {
|
||||
if delivery != "" {
|
||||
if err := q.InsertAlertDelivery(ctx, postgresdb.InsertAlertDeliveryParams{AlertID: a.ID, Event: delivery}); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
_, err := insertEventQ(org.WithOrg(ctx, a.Org), q, events.Event{
|
||||
Kind: events.KindAlert, Detail: a.Title,
|
||||
Data: map[string]any{"id": a.ID, "kind": a.Kind, "state": string(a.State), "severity": string(a.Severity)},
|
||||
})
|
||||
return err
|
||||
}
|
||||
|
||||
// raiseAlert stores in under q, which must be a transaction.
|
||||
func raiseAlert(ctx context.Context, q *postgresdb.Queries, in alert.Input) (alert.Alert, error) {
|
||||
if err := in.Validate(); err != nil {
|
||||
return alert.Alert{}, err
|
||||
}
|
||||
prev, err := lockedAlert(ctx, q, in.Key)
|
||||
if err != nil {
|
||||
return alert.Alert{}, err
|
||||
}
|
||||
next, opened := alert.Apply(prev, in, time.Now().UTC())
|
||||
row, err := q.UpsertAlert(ctx, alertParams(next))
|
||||
if err != nil {
|
||||
return alert.Alert{}, err
|
||||
}
|
||||
stored := alertFromRow(row)
|
||||
if opened {
|
||||
if err := alertChanged(ctx, q, stored, alert.EventRaised); err != nil {
|
||||
return alert.Alert{}, err
|
||||
}
|
||||
}
|
||||
return stored, nil
|
||||
}
|
||||
|
||||
// resolveAlert clears the alert under key through q, which must be a
|
||||
// transaction.
|
||||
func resolveAlert(ctx context.Context, q *postgresdb.Queries, key alert.Key, by string) error {
|
||||
prev, err := lockedAlert(ctx, q, key)
|
||||
if err != nil || prev == nil {
|
||||
return err
|
||||
}
|
||||
next, changed := alert.Resolve(*prev, by, time.Now().UTC())
|
||||
if !changed {
|
||||
return nil
|
||||
}
|
||||
row, err := q.UpsertAlert(ctx, alertParams(next))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return alertChanged(ctx, q, alertFromRow(row), alert.EventResolved)
|
||||
}
|
||||
|
||||
func (s *Store) inTx(ctx context.Context, fn func(*postgresdb.Queries) error) error {
|
||||
tx, err := s.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer func() { _ = tx.Rollback(ctx) }()
|
||||
if err := fn(postgresdb.New(tx)); err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Commit(ctx)
|
||||
}
|
||||
|
||||
// Raise stores in idempotently.
|
||||
func (s *Store) RaiseAlert(ctx context.Context, in alert.Input) (alert.Alert, error) {
|
||||
var out alert.Alert
|
||||
err := s.inTx(ctx, func(q *postgresdb.Queries) (err error) {
|
||||
out, err = raiseAlert(ctx, q, in)
|
||||
return err
|
||||
})
|
||||
return out, err
|
||||
}
|
||||
|
||||
// Resolve clears the alert under key.
|
||||
func (s *Store) ResolveAlert(ctx context.Context, key alert.Key, by string) error {
|
||||
return s.inTx(ctx, func(q *postgresdb.Queries) error { return resolveAlert(ctx, q, key, by) })
|
||||
}
|
||||
|
||||
// Dismiss dismisses an open alert of orgID. An alert of another org is
|
||||
// indistinguishable from none.
|
||||
func (s *Store) DismissAlert(ctx context.Context, orgID org.OrgID, id int64, by string) error {
|
||||
return s.inTx(ctx, func(q *postgresdb.Queries) error {
|
||||
row, err := q.GetOrgAlert(ctx, postgresdb.GetOrgAlertParams{OrgID: string(orgID), ID: id})
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return alert.ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
prev, err := lockedAlert(ctx, q, alertFromRow(row).Key)
|
||||
if err != nil || prev == nil {
|
||||
return errors.Join(err, alert.ErrNotFound)
|
||||
}
|
||||
next, changed := alert.Dismiss(*prev, by, time.Now().UTC())
|
||||
if !changed {
|
||||
return nil
|
||||
}
|
||||
stored, err := q.UpsertAlert(ctx, alertParams(next))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return alertChanged(ctx, q, alertFromRow(stored), "")
|
||||
})
|
||||
}
|
||||
|
||||
// List returns an org's alerts with their deliveries.
|
||||
func (s *Store) ListAlerts(ctx context.Context, orgID org.OrgID, filter alert.Filter) ([]alert.Alert, error) {
|
||||
states := []string{string(alert.StateOpen)}
|
||||
if len(filter.States) > 0 {
|
||||
states = states[:0]
|
||||
for _, st := range filter.States {
|
||||
states = append(states, string(st))
|
||||
}
|
||||
}
|
||||
limit := filter.Limit
|
||||
if limit <= 0 || limit > 500 {
|
||||
limit = 200
|
||||
}
|
||||
q := s.queries()
|
||||
rows, err := q.ListAlerts(ctx, postgresdb.ListAlertsParams{OrgID: string(orgID), States: states, PageLimit: int32(limit)})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out := make([]alert.Alert, len(rows))
|
||||
ids := make([]int64, len(rows))
|
||||
for i, r := range rows {
|
||||
out[i], ids[i] = alertFromRow(r), r.ID
|
||||
}
|
||||
if len(ids) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
deliveries, err := alertDeliveries(ctx, q, ids)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for i := range out {
|
||||
out[i].Deliveries = deliveries[out[i].ID]
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// alertDeliveries returns each alert's newest deliveries with their attempts.
|
||||
func alertDeliveries(ctx context.Context, q *postgresdb.Queries, alertIDs []int64) (map[int64][]alert.Delivery, error) {
|
||||
rows, err := q.ListAlertDeliveries(ctx, alertIDs)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
byAlert := map[int64][]alert.Delivery{}
|
||||
var deliveryIDs []int64
|
||||
for _, r := range rows {
|
||||
if len(byAlert[r.AlertID]) >= deliveriesPerAlert {
|
||||
continue
|
||||
}
|
||||
byAlert[r.AlertID] = append(byAlert[r.AlertID], deliveryFromRow(r))
|
||||
deliveryIDs = append(deliveryIDs, r.ID)
|
||||
}
|
||||
if len(deliveryIDs) == 0 {
|
||||
return byAlert, nil
|
||||
}
|
||||
attempts, err := q.ListAlertAttempts(ctx, deliveryIDs)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
byDelivery := map[int64][]alert.Attempt{}
|
||||
for _, a := range attempts {
|
||||
byDelivery[a.DeliveryID] = append(byDelivery[a.DeliveryID], alert.Attempt{
|
||||
N: a.Attempt, At: a.At, StatusCode: int(a.StatusCode), Error: a.Error,
|
||||
})
|
||||
}
|
||||
for _, list := range byAlert {
|
||||
for i := range list {
|
||||
list[i].Attempts = byDelivery[list[i].ID]
|
||||
}
|
||||
}
|
||||
return byAlert, nil
|
||||
}
|
||||
|
||||
func deliveryFromRow(r postgresdb.AlertDelivery) alert.Delivery {
|
||||
return alert.Delivery{
|
||||
ID: r.ID, AlertID: r.AlertID, Event: r.Event, State: r.State,
|
||||
CreatedAt: r.CreatedAt, NextAttemptAt: r.NextAttemptAt,
|
||||
}
|
||||
}
|
||||
|
||||
// Prune removes alerts closed before cutoff, with their deliveries.
|
||||
func (s *Store) PruneAlerts(ctx context.Context, cutoff time.Time) (int64, error) {
|
||||
return s.queries().PruneAlerts(ctx, pgtype.Timestamptz{Time: cutoff, Valid: true})
|
||||
}
|
||||
|
||||
// ClaimDeliveries returns the due deliveries with their alerts.
|
||||
func (s *Store) ClaimAlertDeliveries(ctx context.Context, limit int) ([]alert.Due, error) {
|
||||
if limit <= 0 || limit > 100 {
|
||||
limit = 20
|
||||
}
|
||||
var out []alert.Due
|
||||
err := s.inTx(ctx, func(q *postgresdb.Queries) error {
|
||||
rows, err := q.ClaimAlertDeliveries(ctx, int32(limit))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, r := range rows {
|
||||
row, err := q.GetAlert(ctx, r.AlertID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
out = append(out, alert.Due{Delivery: deliveryFromRow(r), Alert: alertFromRow(row), Attempt: r.Attempts + 1})
|
||||
}
|
||||
return nil
|
||||
})
|
||||
return out, err
|
||||
}
|
||||
|
||||
// RecordAttempt records one attempt and settles or reschedules the delivery.
|
||||
func (s *Store) RecordAlertAttempt(ctx context.Context, o alert.Outcome) error {
|
||||
return s.inTx(ctx, func(q *postgresdb.Queries) error {
|
||||
d, err := q.LockAlertDelivery(ctx, o.DeliveryID)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return alert.ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if d.State != alert.DeliveryPending {
|
||||
return nil
|
||||
}
|
||||
now := time.Now().UTC()
|
||||
params := postgresdb.SettleAlertDeliveryParams{ID: d.ID, State: alert.DeliveryPending, Attempts: d.Attempts, NextAttemptAt: d.NextAttemptAt}
|
||||
switch {
|
||||
case o.Skipped:
|
||||
params.State = alert.DeliverySkipped
|
||||
default:
|
||||
params.Attempts++
|
||||
if err := q.InsertAlertAttempt(ctx, postgresdb.InsertAlertAttemptParams{
|
||||
DeliveryID: d.ID, Attempt: params.Attempts, StatusCode: int64(o.StatusCode), Error: o.Error,
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
switch {
|
||||
case o.OK():
|
||||
params.State = alert.DeliveryDelivered
|
||||
case params.Attempts >= alert.MaxDeliveryAttempts:
|
||||
params.State = alert.DeliveryFailed
|
||||
default:
|
||||
params.NextAttemptAt = now.Add(alert.RetryDelay(params.Attempts))
|
||||
}
|
||||
}
|
||||
if err := q.SettleAlertDelivery(ctx, params); err != nil {
|
||||
return fmt.Errorf("settle alert delivery: %w", err)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
-- Operator alerts: things that need a human, one row per (org, kind, subject).
|
||||
-- Raising an open alert again bumps the row instead of adding one. A
|
||||
-- condition-backed alert resolves when its condition clears; an event alert
|
||||
-- stays until dismissed. Deliveries are the outbound notices (the notify
|
||||
-- webhook) each raise or resolve owes, with every attempt kept.
|
||||
|
||||
-- +goose Up
|
||||
|
||||
CREATE TABLE alerts (
|
||||
id bigint GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
|
||||
org_id text NOT NULL,
|
||||
kind text NOT NULL,
|
||||
subject text NOT NULL,
|
||||
severity text NOT NULL CHECK (severity IN ('info', 'warning', 'action')),
|
||||
title text NOT NULL,
|
||||
body text NOT NULL DEFAULT '',
|
||||
link text NOT NULL DEFAULT '',
|
||||
is_condition boolean NOT NULL,
|
||||
state text NOT NULL DEFAULT 'open' CHECK (state IN ('open', 'resolved', 'dismissed')),
|
||||
first_raised timestamptz NOT NULL,
|
||||
last_seen timestamptz NOT NULL,
|
||||
count bigint NOT NULL DEFAULT 1,
|
||||
closed_by text NOT NULL DEFAULT '',
|
||||
closed_at timestamptz,
|
||||
UNIQUE (org_id, kind, subject)
|
||||
);
|
||||
CREATE INDEX idx_alerts_org_state ON alerts (org_id, state, id);
|
||||
CREATE INDEX idx_alerts_closed ON alerts (closed_at) WHERE state <> 'open';
|
||||
|
||||
CREATE TABLE alert_deliveries (
|
||||
id bigint GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
|
||||
alert_id bigint NOT NULL REFERENCES alerts (id) ON DELETE CASCADE,
|
||||
event text NOT NULL CHECK (event IN ('raised', 'resolved')),
|
||||
state text NOT NULL DEFAULT 'pending' CHECK (state IN ('pending', 'delivered', 'failed', 'skipped')),
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
next_attempt_at timestamptz NOT NULL DEFAULT now(),
|
||||
attempts bigint NOT NULL DEFAULT 0
|
||||
);
|
||||
CREATE INDEX idx_alert_deliveries_due ON alert_deliveries (next_attempt_at) WHERE state = 'pending';
|
||||
CREATE INDEX idx_alert_deliveries_alert ON alert_deliveries (alert_id, id);
|
||||
|
||||
CREATE TABLE alert_delivery_attempts (
|
||||
id bigint GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
|
||||
delivery_id bigint NOT NULL REFERENCES alert_deliveries (id) ON DELETE CASCADE,
|
||||
attempt bigint NOT NULL,
|
||||
at timestamptz NOT NULL DEFAULT now(),
|
||||
status_code bigint NOT NULL DEFAULT 0,
|
||||
error text NOT NULL DEFAULT ''
|
||||
);
|
||||
CREATE INDEX idx_alert_delivery_attempts_delivery ON alert_delivery_attempts (delivery_id, id);
|
||||
|
||||
-- +goose Down
|
||||
|
||||
DROP TABLE alert_delivery_attempts;
|
||||
DROP TABLE alert_deliveries;
|
||||
DROP TABLE alerts;
|
||||
@@ -0,0 +1,448 @@
|
||||
// Code generated by sqlc. DO NOT EDIT.
|
||||
// versions:
|
||||
// sqlc v1.31.1
|
||||
// source: alerts.sql
|
||||
|
||||
package postgresdb
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
)
|
||||
|
||||
const claimAlertDeliveries = `-- name: ClaimAlertDeliveries :many
|
||||
UPDATE alert_deliveries SET next_attempt_at = now() + interval '2 minutes'
|
||||
WHERE id IN (
|
||||
SELECT d.id FROM alert_deliveries d
|
||||
WHERE d.state = 'pending' AND d.next_attempt_at <= now()
|
||||
ORDER BY d.id LIMIT $1 FOR UPDATE SKIP LOCKED)
|
||||
RETURNING id, alert_id, event, state, created_at, next_attempt_at, attempts
|
||||
`
|
||||
|
||||
func (q *Queries) ClaimAlertDeliveries(ctx context.Context, pageLimit int32) ([]AlertDelivery, error) {
|
||||
rows, err := q.db.Query(ctx, claimAlertDeliveries, pageLimit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var items []AlertDelivery
|
||||
for rows.Next() {
|
||||
var i AlertDelivery
|
||||
if err := rows.Scan(
|
||||
&i.ID,
|
||||
&i.AlertID,
|
||||
&i.Event,
|
||||
&i.State,
|
||||
&i.CreatedAt,
|
||||
&i.NextAttemptAt,
|
||||
&i.Attempts,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const getAlert = `-- name: GetAlert :one
|
||||
SELECT id, org_id, kind, subject, severity, title, body, link, is_condition, state, first_raised, last_seen, count, closed_by, closed_at
|
||||
FROM alerts WHERE id = $1
|
||||
`
|
||||
|
||||
func (q *Queries) GetAlert(ctx context.Context, id int64) (Alert, error) {
|
||||
row := q.db.QueryRow(ctx, getAlert, id)
|
||||
var i Alert
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.OrgID,
|
||||
&i.Kind,
|
||||
&i.Subject,
|
||||
&i.Severity,
|
||||
&i.Title,
|
||||
&i.Body,
|
||||
&i.Link,
|
||||
&i.IsCondition,
|
||||
&i.State,
|
||||
&i.FirstRaised,
|
||||
&i.LastSeen,
|
||||
&i.Count,
|
||||
&i.ClosedBy,
|
||||
&i.ClosedAt,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const getAlertByKey = `-- name: GetAlertByKey :one
|
||||
SELECT id, org_id, kind, subject, severity, title, body, link, is_condition, state, first_raised, last_seen, count, closed_by, closed_at
|
||||
FROM alerts WHERE org_id = $1 AND kind = $2 AND subject = $3
|
||||
`
|
||||
|
||||
type GetAlertByKeyParams struct {
|
||||
OrgID string
|
||||
Kind string
|
||||
Subject string
|
||||
}
|
||||
|
||||
func (q *Queries) GetAlertByKey(ctx context.Context, arg GetAlertByKeyParams) (Alert, error) {
|
||||
row := q.db.QueryRow(ctx, getAlertByKey, arg.OrgID, arg.Kind, arg.Subject)
|
||||
var i Alert
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.OrgID,
|
||||
&i.Kind,
|
||||
&i.Subject,
|
||||
&i.Severity,
|
||||
&i.Title,
|
||||
&i.Body,
|
||||
&i.Link,
|
||||
&i.IsCondition,
|
||||
&i.State,
|
||||
&i.FirstRaised,
|
||||
&i.LastSeen,
|
||||
&i.Count,
|
||||
&i.ClosedBy,
|
||||
&i.ClosedAt,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const getOrgAlert = `-- name: GetOrgAlert :one
|
||||
SELECT id, org_id, kind, subject, severity, title, body, link, is_condition, state, first_raised, last_seen, count, closed_by, closed_at
|
||||
FROM alerts WHERE org_id = $1 AND id = $2
|
||||
`
|
||||
|
||||
type GetOrgAlertParams struct {
|
||||
OrgID string
|
||||
ID int64
|
||||
}
|
||||
|
||||
func (q *Queries) GetOrgAlert(ctx context.Context, arg GetOrgAlertParams) (Alert, error) {
|
||||
row := q.db.QueryRow(ctx, getOrgAlert, arg.OrgID, arg.ID)
|
||||
var i Alert
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.OrgID,
|
||||
&i.Kind,
|
||||
&i.Subject,
|
||||
&i.Severity,
|
||||
&i.Title,
|
||||
&i.Body,
|
||||
&i.Link,
|
||||
&i.IsCondition,
|
||||
&i.State,
|
||||
&i.FirstRaised,
|
||||
&i.LastSeen,
|
||||
&i.Count,
|
||||
&i.ClosedBy,
|
||||
&i.ClosedAt,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const insertAlertAttempt = `-- name: InsertAlertAttempt :exec
|
||||
INSERT INTO alert_delivery_attempts (delivery_id, attempt, status_code, error) VALUES ($1, $2, $3, $4)
|
||||
`
|
||||
|
||||
type InsertAlertAttemptParams struct {
|
||||
DeliveryID int64
|
||||
Attempt int64
|
||||
StatusCode int64
|
||||
Error string
|
||||
}
|
||||
|
||||
func (q *Queries) InsertAlertAttempt(ctx context.Context, arg InsertAlertAttemptParams) error {
|
||||
_, err := q.db.Exec(ctx, insertAlertAttempt,
|
||||
arg.DeliveryID,
|
||||
arg.Attempt,
|
||||
arg.StatusCode,
|
||||
arg.Error,
|
||||
)
|
||||
return err
|
||||
}
|
||||
|
||||
const insertAlertDelivery = `-- name: InsertAlertDelivery :exec
|
||||
INSERT INTO alert_deliveries (alert_id, event) VALUES ($1, $2)
|
||||
`
|
||||
|
||||
type InsertAlertDeliveryParams struct {
|
||||
AlertID int64
|
||||
Event string
|
||||
}
|
||||
|
||||
func (q *Queries) InsertAlertDelivery(ctx context.Context, arg InsertAlertDeliveryParams) error {
|
||||
_, err := q.db.Exec(ctx, insertAlertDelivery, arg.AlertID, arg.Event)
|
||||
return err
|
||||
}
|
||||
|
||||
const listAlertAttempts = `-- name: ListAlertAttempts :many
|
||||
SELECT id, delivery_id, attempt, at, status_code, error
|
||||
FROM alert_delivery_attempts WHERE delivery_id = ANY($1::bigint[]) ORDER BY delivery_id, id
|
||||
`
|
||||
|
||||
func (q *Queries) ListAlertAttempts(ctx context.Context, deliveryIds []int64) ([]AlertDeliveryAttempt, error) {
|
||||
rows, err := q.db.Query(ctx, listAlertAttempts, deliveryIds)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var items []AlertDeliveryAttempt
|
||||
for rows.Next() {
|
||||
var i AlertDeliveryAttempt
|
||||
if err := rows.Scan(
|
||||
&i.ID,
|
||||
&i.DeliveryID,
|
||||
&i.Attempt,
|
||||
&i.At,
|
||||
&i.StatusCode,
|
||||
&i.Error,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const listAlertDeliveries = `-- name: ListAlertDeliveries :many
|
||||
SELECT id, alert_id, event, state, created_at, next_attempt_at, attempts
|
||||
FROM alert_deliveries WHERE alert_id = ANY($1::bigint[]) ORDER BY alert_id, id DESC
|
||||
`
|
||||
|
||||
func (q *Queries) ListAlertDeliveries(ctx context.Context, alertIds []int64) ([]AlertDelivery, error) {
|
||||
rows, err := q.db.Query(ctx, listAlertDeliveries, alertIds)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var items []AlertDelivery
|
||||
for rows.Next() {
|
||||
var i AlertDelivery
|
||||
if err := rows.Scan(
|
||||
&i.ID,
|
||||
&i.AlertID,
|
||||
&i.Event,
|
||||
&i.State,
|
||||
&i.CreatedAt,
|
||||
&i.NextAttemptAt,
|
||||
&i.Attempts,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const listAlerts = `-- name: ListAlerts :many
|
||||
SELECT id, org_id, kind, subject, severity, title, body, link, is_condition, state, first_raised, last_seen, count, closed_by, closed_at
|
||||
FROM alerts
|
||||
WHERE org_id = $1 AND state = ANY($2::text[])
|
||||
ORDER BY CASE severity WHEN 'action' THEN 3 WHEN 'warning' THEN 2 ELSE 1 END DESC, last_seen DESC, id DESC
|
||||
LIMIT $3
|
||||
`
|
||||
|
||||
type ListAlertsParams struct {
|
||||
OrgID string
|
||||
States []string
|
||||
PageLimit int32
|
||||
}
|
||||
|
||||
func (q *Queries) ListAlerts(ctx context.Context, arg ListAlertsParams) ([]Alert, error) {
|
||||
rows, err := q.db.Query(ctx, listAlerts, arg.OrgID, arg.States, arg.PageLimit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var items []Alert
|
||||
for rows.Next() {
|
||||
var i Alert
|
||||
if err := rows.Scan(
|
||||
&i.ID,
|
||||
&i.OrgID,
|
||||
&i.Kind,
|
||||
&i.Subject,
|
||||
&i.Severity,
|
||||
&i.Title,
|
||||
&i.Body,
|
||||
&i.Link,
|
||||
&i.IsCondition,
|
||||
&i.State,
|
||||
&i.FirstRaised,
|
||||
&i.LastSeen,
|
||||
&i.Count,
|
||||
&i.ClosedBy,
|
||||
&i.ClosedAt,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const lockAlertDelivery = `-- name: LockAlertDelivery :one
|
||||
SELECT id, alert_id, event, state, created_at, next_attempt_at, attempts
|
||||
FROM alert_deliveries WHERE id = $1 FOR UPDATE
|
||||
`
|
||||
|
||||
func (q *Queries) LockAlertDelivery(ctx context.Context, id int64) (AlertDelivery, error) {
|
||||
row := q.db.QueryRow(ctx, lockAlertDelivery, id)
|
||||
var i AlertDelivery
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.AlertID,
|
||||
&i.Event,
|
||||
&i.State,
|
||||
&i.CreatedAt,
|
||||
&i.NextAttemptAt,
|
||||
&i.Attempts,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const lockAlertKey = `-- name: LockAlertKey :exec
|
||||
|
||||
SELECT pg_advisory_xact_lock(hashtextextended($1::text, 0))
|
||||
`
|
||||
|
||||
// Operator alerts and their outbound deliveries (internal/domain/alert).
|
||||
// Serialises raisers of one alert, so two first raises cannot both insert.
|
||||
func (q *Queries) LockAlertKey(ctx context.Context, lockKey string) error {
|
||||
_, err := q.db.Exec(ctx, lockAlertKey, lockKey)
|
||||
return err
|
||||
}
|
||||
|
||||
const pruneAlerts = `-- name: PruneAlerts :execrows
|
||||
DELETE FROM alerts WHERE state <> 'open' AND closed_at < $1
|
||||
`
|
||||
|
||||
func (q *Queries) PruneAlerts(ctx context.Context, closedAt pgtype.Timestamptz) (int64, error) {
|
||||
result, err := q.db.Exec(ctx, pruneAlerts, closedAt)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return result.RowsAffected(), nil
|
||||
}
|
||||
|
||||
const settleAlertDelivery = `-- name: SettleAlertDelivery :exec
|
||||
UPDATE alert_deliveries SET state = $2, attempts = $3, next_attempt_at = $4 WHERE id = $1
|
||||
`
|
||||
|
||||
type SettleAlertDeliveryParams struct {
|
||||
ID int64
|
||||
State string
|
||||
Attempts int64
|
||||
NextAttemptAt time.Time
|
||||
}
|
||||
|
||||
func (q *Queries) SettleAlertDelivery(ctx context.Context, arg SettleAlertDeliveryParams) error {
|
||||
_, err := q.db.Exec(ctx, settleAlertDelivery,
|
||||
arg.ID,
|
||||
arg.State,
|
||||
arg.Attempts,
|
||||
arg.NextAttemptAt,
|
||||
)
|
||||
return err
|
||||
}
|
||||
|
||||
const taskAlertInfo = `-- name: TaskAlertInfo :one
|
||||
SELECT org_id, title, workflow, park_class FROM tasks WHERE id = $1
|
||||
`
|
||||
|
||||
type TaskAlertInfoRow struct {
|
||||
OrgID string
|
||||
Title string
|
||||
Workflow string
|
||||
ParkClass string
|
||||
}
|
||||
|
||||
func (q *Queries) TaskAlertInfo(ctx context.Context, id int64) (TaskAlertInfoRow, error) {
|
||||
row := q.db.QueryRow(ctx, taskAlertInfo, id)
|
||||
var i TaskAlertInfoRow
|
||||
err := row.Scan(
|
||||
&i.OrgID,
|
||||
&i.Title,
|
||||
&i.Workflow,
|
||||
&i.ParkClass,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const upsertAlert = `-- name: UpsertAlert :one
|
||||
INSERT INTO alerts (org_id, kind, subject, severity, title, body, link, is_condition, state, first_raised, last_seen, count, closed_by, closed_at)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14)
|
||||
ON CONFLICT (org_id, kind, subject) DO UPDATE SET
|
||||
severity = excluded.severity, title = excluded.title, body = excluded.body, link = excluded.link,
|
||||
is_condition = excluded.is_condition, state = excluded.state, first_raised = excluded.first_raised,
|
||||
last_seen = excluded.last_seen, count = excluded.count, closed_by = excluded.closed_by, closed_at = excluded.closed_at
|
||||
RETURNING id, org_id, kind, subject, severity, title, body, link, is_condition, state, first_raised, last_seen, count, closed_by, closed_at
|
||||
`
|
||||
|
||||
type UpsertAlertParams struct {
|
||||
OrgID string
|
||||
Kind string
|
||||
Subject string
|
||||
Severity string
|
||||
Title string
|
||||
Body string
|
||||
Link string
|
||||
IsCondition bool
|
||||
State string
|
||||
FirstRaised time.Time
|
||||
LastSeen time.Time
|
||||
Count int64
|
||||
ClosedBy string
|
||||
ClosedAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
func (q *Queries) UpsertAlert(ctx context.Context, arg UpsertAlertParams) (Alert, error) {
|
||||
row := q.db.QueryRow(ctx, upsertAlert,
|
||||
arg.OrgID,
|
||||
arg.Kind,
|
||||
arg.Subject,
|
||||
arg.Severity,
|
||||
arg.Title,
|
||||
arg.Body,
|
||||
arg.Link,
|
||||
arg.IsCondition,
|
||||
arg.State,
|
||||
arg.FirstRaised,
|
||||
arg.LastSeen,
|
||||
arg.Count,
|
||||
arg.ClosedBy,
|
||||
arg.ClosedAt,
|
||||
)
|
||||
var i Alert
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.OrgID,
|
||||
&i.Kind,
|
||||
&i.Subject,
|
||||
&i.Severity,
|
||||
&i.Title,
|
||||
&i.Body,
|
||||
&i.Link,
|
||||
&i.IsCondition,
|
||||
&i.State,
|
||||
&i.FirstRaised,
|
||||
&i.LastSeen,
|
||||
&i.Count,
|
||||
&i.ClosedBy,
|
||||
&i.ClosedAt,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
@@ -44,6 +44,43 @@ type AccessPolicyVersion struct {
|
||||
UpdatedAt time.Time
|
||||
}
|
||||
|
||||
type Alert struct {
|
||||
ID int64
|
||||
OrgID string
|
||||
Kind string
|
||||
Subject string
|
||||
Severity string
|
||||
Title string
|
||||
Body string
|
||||
Link string
|
||||
IsCondition bool
|
||||
State string
|
||||
FirstRaised time.Time
|
||||
LastSeen time.Time
|
||||
Count int64
|
||||
ClosedBy string
|
||||
ClosedAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
type AlertDelivery struct {
|
||||
ID int64
|
||||
AlertID int64
|
||||
Event string
|
||||
State string
|
||||
CreatedAt time.Time
|
||||
NextAttemptAt time.Time
|
||||
Attempts int64
|
||||
}
|
||||
|
||||
type AlertDeliveryAttempt struct {
|
||||
ID int64
|
||||
DeliveryID int64
|
||||
Attempt int64
|
||||
At time.Time
|
||||
StatusCode int64
|
||||
Error string
|
||||
}
|
||||
|
||||
type ApplyStatus struct {
|
||||
Process string
|
||||
Kind string
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
-- Operator alerts and their outbound deliveries (internal/domain/alert).
|
||||
|
||||
-- name: LockAlertKey :exec
|
||||
-- Serialises raisers of one alert, so two first raises cannot both insert.
|
||||
SELECT pg_advisory_xact_lock(hashtextextended(sqlc.arg(lock_key)::text, 0));
|
||||
|
||||
-- name: GetAlertByKey :one
|
||||
SELECT id, org_id, kind, subject, severity, title, body, link, is_condition, state, first_raised, last_seen, count, closed_by, closed_at
|
||||
FROM alerts WHERE org_id = $1 AND kind = $2 AND subject = $3;
|
||||
|
||||
-- name: GetOrgAlert :one
|
||||
SELECT id, org_id, kind, subject, severity, title, body, link, is_condition, state, first_raised, last_seen, count, closed_by, closed_at
|
||||
FROM alerts WHERE org_id = $1 AND id = $2;
|
||||
|
||||
-- name: GetAlert :one
|
||||
SELECT id, org_id, kind, subject, severity, title, body, link, is_condition, state, first_raised, last_seen, count, closed_by, closed_at
|
||||
FROM alerts WHERE id = $1;
|
||||
|
||||
-- name: UpsertAlert :one
|
||||
INSERT INTO alerts (org_id, kind, subject, severity, title, body, link, is_condition, state, first_raised, last_seen, count, closed_by, closed_at)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14)
|
||||
ON CONFLICT (org_id, kind, subject) DO UPDATE SET
|
||||
severity = excluded.severity, title = excluded.title, body = excluded.body, link = excluded.link,
|
||||
is_condition = excluded.is_condition, state = excluded.state, first_raised = excluded.first_raised,
|
||||
last_seen = excluded.last_seen, count = excluded.count, closed_by = excluded.closed_by, closed_at = excluded.closed_at
|
||||
RETURNING id, org_id, kind, subject, severity, title, body, link, is_condition, state, first_raised, last_seen, count, closed_by, closed_at;
|
||||
|
||||
-- name: ListAlerts :many
|
||||
SELECT id, org_id, kind, subject, severity, title, body, link, is_condition, state, first_raised, last_seen, count, closed_by, closed_at
|
||||
FROM alerts
|
||||
WHERE org_id = $1 AND state = ANY(sqlc.arg(states)::text[])
|
||||
ORDER BY CASE severity WHEN 'action' THEN 3 WHEN 'warning' THEN 2 ELSE 1 END DESC, last_seen DESC, id DESC
|
||||
LIMIT sqlc.arg(page_limit);
|
||||
|
||||
-- name: PruneAlerts :execrows
|
||||
DELETE FROM alerts WHERE state <> 'open' AND closed_at < $1;
|
||||
|
||||
-- name: InsertAlertDelivery :exec
|
||||
INSERT INTO alert_deliveries (alert_id, event) VALUES ($1, $2);
|
||||
|
||||
-- name: ClaimAlertDeliveries :many
|
||||
UPDATE alert_deliveries SET next_attempt_at = now() + interval '2 minutes'
|
||||
WHERE id IN (
|
||||
SELECT d.id FROM alert_deliveries d
|
||||
WHERE d.state = 'pending' AND d.next_attempt_at <= now()
|
||||
ORDER BY d.id LIMIT sqlc.arg(page_limit) FOR UPDATE SKIP LOCKED)
|
||||
RETURNING id, alert_id, event, state, created_at, next_attempt_at, attempts;
|
||||
|
||||
-- name: LockAlertDelivery :one
|
||||
SELECT id, alert_id, event, state, created_at, next_attempt_at, attempts
|
||||
FROM alert_deliveries WHERE id = $1 FOR UPDATE;
|
||||
|
||||
-- name: SettleAlertDelivery :exec
|
||||
UPDATE alert_deliveries SET state = $2, attempts = $3, next_attempt_at = $4 WHERE id = $1;
|
||||
|
||||
-- name: InsertAlertAttempt :exec
|
||||
INSERT INTO alert_delivery_attempts (delivery_id, attempt, status_code, error) VALUES ($1, $2, $3, $4);
|
||||
|
||||
-- name: ListAlertDeliveries :many
|
||||
SELECT id, alert_id, event, state, created_at, next_attempt_at, attempts
|
||||
FROM alert_deliveries WHERE alert_id = ANY(sqlc.arg(alert_ids)::bigint[]) ORDER BY alert_id, id DESC;
|
||||
|
||||
-- name: ListAlertAttempts :many
|
||||
SELECT id, delivery_id, attempt, at, status_code, error
|
||||
FROM alert_delivery_attempts WHERE delivery_id = ANY(sqlc.arg(delivery_ids)::bigint[]) ORDER BY delivery_id, id;
|
||||
|
||||
-- name: TaskAlertInfo :one
|
||||
SELECT org_id, title, workflow, park_class FROM tasks WHERE id = $1;
|
||||
@@ -338,7 +338,7 @@ func (s *Store) CancelExecution(ctx context.Context, taskID int64, reason, to st
|
||||
if n == 0 {
|
||||
return nil, storecontract.ErrStaleTransition
|
||||
}
|
||||
if err := q.InsertTransition(ctx, postgresdb.InsertTransitionParams{
|
||||
if err := recordTransition(ctx, q, postgresdb.InsertTransitionParams{
|
||||
TaskID: taskID, FromStatus: execution.Status, ToStatus: to, Detail: clip(reason, 4000),
|
||||
}); err != nil {
|
||||
return nil, err
|
||||
|
||||
@@ -276,7 +276,7 @@ func (s *Store) Transition(ctx context.Context, taskID int64, from, to, detail s
|
||||
if n == 0 {
|
||||
return storecontract.ErrStaleTransition
|
||||
}
|
||||
if err := q.InsertTransition(ctx, postgresdb.InsertTransitionParams{
|
||||
if err := recordTransition(ctx, q, postgresdb.InsertTransitionParams{
|
||||
TaskID: taskID, FromStatus: from, ToStatus: to, Detail: clip(detail, 4000),
|
||||
}); err != nil {
|
||||
return err
|
||||
@@ -291,7 +291,7 @@ func (s *Store) Transition(ctx context.Context, taskID int64, from, to, detail s
|
||||
return err
|
||||
}
|
||||
if promoted > 0 {
|
||||
if err := q.InsertTransition(ctx, postgresdb.InsertTransitionParams{
|
||||
if err := recordTransition(ctx, q, postgresdb.InsertTransitionParams{
|
||||
TaskID: taskID, FromStatus: workflow.StatusPROpen, ToStatus: workflow.StatusQueued,
|
||||
Detail: "queued the next review",
|
||||
}); err != nil {
|
||||
@@ -327,7 +327,7 @@ func (s *Store) ParkTask(ctx context.Context, taskID int64, from, detail, class
|
||||
if n == 0 {
|
||||
return storecontract.ErrStaleTransition
|
||||
}
|
||||
if err := q.InsertTransition(ctx, postgresdb.InsertTransitionParams{
|
||||
if err := recordTransition(ctx, q, postgresdb.InsertTransitionParams{
|
||||
TaskID: taskID, FromStatus: from, ToStatus: workflow.StatusParked, Detail: clip(detail, 4000),
|
||||
}); err != nil {
|
||||
return err
|
||||
@@ -409,7 +409,7 @@ func (s *Store) BeginRemediation(ctx context.Context, taskID int64, payload stri
|
||||
if n == 0 {
|
||||
return storecontract.ErrStaleTransition
|
||||
}
|
||||
if err := q.InsertTransition(ctx, postgresdb.InsertTransitionParams{
|
||||
if err := recordTransition(ctx, q, postgresdb.InsertTransitionParams{
|
||||
TaskID: taskID, FromStatus: workflow.StatusPROpen, ToStatus: workflow.StatusQueued,
|
||||
Detail: "review reaction queued remediation",
|
||||
}); err != nil {
|
||||
@@ -589,7 +589,7 @@ func (s *Store) RespondReviewGate(ctx context.Context, taskID int64, fromStatus,
|
||||
if rereview {
|
||||
detail = "operator requested a re-review"
|
||||
}
|
||||
if err := q.InsertTransition(ctx, postgresdb.InsertTransitionParams{
|
||||
if err := recordTransition(ctx, q, postgresdb.InsertTransitionParams{
|
||||
TaskID: taskID, FromStatus: fromStatus, ToStatus: workflow.StatusQueued, Detail: detail,
|
||||
}); err != nil {
|
||||
return err
|
||||
@@ -619,7 +619,7 @@ func (s *Store) requeue(ctx context.Context, taskID int64, fromStatus, wf, detai
|
||||
if n == 0 {
|
||||
return storecontract.ErrStaleTransition
|
||||
}
|
||||
if err := q.InsertTransition(ctx, postgresdb.InsertTransitionParams{
|
||||
if err := recordTransition(ctx, q, postgresdb.InsertTransitionParams{
|
||||
TaskID: taskID, FromStatus: fromStatus, ToStatus: workflow.StatusQueued, Detail: detail,
|
||||
}); err != nil {
|
||||
return err
|
||||
@@ -684,7 +684,7 @@ func (s *Store) RecoverStale(ctx context.Context) (int64, error) {
|
||||
return 0, err
|
||||
}
|
||||
}
|
||||
if err := q.InsertTransition(ctx, postgresdb.InsertTransitionParams{
|
||||
if err := recordTransition(ctx, q, postgresdb.InsertTransitionParams{
|
||||
TaskID: execution.ID, FromStatus: workflow.StatusRunning, ToStatus: workflow.StatusQueued,
|
||||
Detail: "re-queued after a crashed or replaced daemon",
|
||||
}); err != nil {
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/alert"
|
||||
"github.com/samcharles93/archie-core/internal/domain/org"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/postgresdb"
|
||||
"github.com/samcharles93/archie-core/internal/taskstate"
|
||||
)
|
||||
|
||||
// systemResolver is recorded as the resolver of an alert the store clears
|
||||
// itself because the task moved on.
|
||||
const systemResolver = "system"
|
||||
|
||||
// recordTransition writes a transition's audit row and the alerts that
|
||||
// transition raises or clears, in the same transaction. Every task status
|
||||
// move goes through it, so the alerts follow the state without a poller.
|
||||
func recordTransition(ctx context.Context, q *postgresdb.Queries, p postgresdb.InsertTransitionParams) error {
|
||||
if err := q.InsertTransition(ctx, p); err != nil {
|
||||
return err
|
||||
}
|
||||
return syncTaskAlerts(ctx, q, p)
|
||||
}
|
||||
|
||||
// needsHuman reports whether a task in status, parked with class, is waiting
|
||||
// on an operator's decision.
|
||||
func needsHuman(status, class string) bool {
|
||||
return status == workflow.StatusWaitingHuman || (status == workflow.StatusParked && class == taskstate.ParkNeedsHuman)
|
||||
}
|
||||
|
||||
// failed reports whether a task in status, parked with class, will not
|
||||
// succeed without an operator starting it over.
|
||||
func failed(status, class string) bool {
|
||||
return status == workflow.StatusDead || (status == workflow.StatusParked && class == taskstate.ParkTerminal)
|
||||
}
|
||||
|
||||
func syncTaskAlerts(ctx context.Context, q *postgresdb.Queries, p postgresdb.InsertTransitionParams) error {
|
||||
leaving := p.FromStatus == workflow.StatusWaitingHuman || p.FromStatus == workflow.StatusParked
|
||||
if !leaving && p.ToStatus != workflow.StatusWaitingHuman && p.ToStatus != workflow.StatusParked && p.ToStatus != workflow.StatusDead {
|
||||
return nil
|
||||
}
|
||||
info, err := q.TaskAlertInfo(ctx, p.TaskID)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
subject := fmt.Sprintf("task:%d", p.TaskID)
|
||||
link := fmt.Sprintf("/tasks/%d", p.TaskID)
|
||||
name := fmt.Sprintf("Task #%d", p.TaskID)
|
||||
described := name
|
||||
if info.Title != "" {
|
||||
described = fmt.Sprintf("%s %q", name, info.Title)
|
||||
}
|
||||
key := func(kind string) alert.Key {
|
||||
return alert.Key{Org: org.OrgID(info.OrgID), Kind: kind, Subject: subject}
|
||||
}
|
||||
|
||||
if needsHuman(p.ToStatus, info.ParkClass) {
|
||||
body := described + " is waiting for your approval or review."
|
||||
if p.ToStatus == workflow.StatusParked {
|
||||
body = described + " is parked and needs a decision."
|
||||
}
|
||||
_, err := raiseAlert(ctx, q, alert.Input{
|
||||
Key: key(alert.KindTaskNeedsHuman), Severity: alert.SeverityAction, Condition: true,
|
||||
Title: name + " needs you", Body: body, Link: link,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
} else if leaving {
|
||||
if err := resolveAlert(ctx, q, key(alert.KindTaskNeedsHuman), systemResolver); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if failed(p.ToStatus, info.ParkClass) {
|
||||
_, err := raiseAlert(ctx, q, alert.Input{
|
||||
Key: key(alert.KindTaskFailed), Severity: alert.SeverityWarning,
|
||||
Title: name + " failed", Body: described + " failed and will not run again until you retry it.", Link: link,
|
||||
})
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,190 @@
|
||||
// Alerts: the operator alert RPCs. A caller acting for a principal is
|
||||
// confined to that principal's org; a service acting for no one names the org
|
||||
// on the request.
|
||||
package staterpc
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
|
||||
pb "github.com/samcharles93/archie-core/internal/contracts/state/v1"
|
||||
"github.com/samcharles93/archie-core/internal/domain/access"
|
||||
"github.com/samcharles93/archie-core/internal/domain/alert"
|
||||
"github.com/samcharles93/archie-core/internal/domain/org"
|
||||
)
|
||||
|
||||
var errAlertsUnavailable = status.Error(codes.Unavailable, "alert store unavailable")
|
||||
|
||||
// alertOrg is the org a call acts in.
|
||||
func alertOrg(ctx context.Context, requested string) (org.OrgID, error) {
|
||||
if id, ok := org.Scope(ctx); ok {
|
||||
return id, nil
|
||||
}
|
||||
if requested == "" {
|
||||
return "", status.Error(codes.InvalidArgument, "org_id is required")
|
||||
}
|
||||
return org.OrgID(requested), nil
|
||||
}
|
||||
|
||||
func alertStatus(err error) error {
|
||||
switch {
|
||||
case errors.Is(err, alert.ErrInvalid):
|
||||
return status.Error(codes.InvalidArgument, err.Error())
|
||||
case errors.Is(err, alert.ErrNotFound):
|
||||
return status.Error(codes.NotFound, alert.ErrNotFound.Error())
|
||||
default:
|
||||
return mapError(err)
|
||||
}
|
||||
}
|
||||
|
||||
func alertProto(a alert.Alert) *pb.Alert {
|
||||
return &pb.Alert{
|
||||
Id: a.ID, OrgId: string(a.Org), Kind: a.Kind, Subject: a.Subject,
|
||||
Severity: string(a.Severity), Title: a.Title, Body: a.Body, Link: a.Link,
|
||||
Condition: a.Condition, State: string(a.State),
|
||||
FirstRaised: timestamp(a.FirstRaised), LastSeen: timestamp(a.LastSeen), Count: a.Count,
|
||||
ClosedBy: a.ClosedBy, ClosedAt: timestamp(a.ClosedAt),
|
||||
Deliveries: mapValues(a.Deliveries, alertDeliveryProto),
|
||||
}
|
||||
}
|
||||
|
||||
func alertValue(a *pb.Alert) alert.Alert {
|
||||
return alert.Alert{
|
||||
ID: a.GetId(),
|
||||
Org: org.OrgID(a.GetOrgId()), Kind: a.GetKind(), Subject: a.GetSubject(),
|
||||
Severity: alert.Severity(a.GetSeverity()), Title: a.GetTitle(), Body: a.GetBody(), Link: a.GetLink(),
|
||||
Condition: a.GetCondition(), State: alert.State(a.GetState()),
|
||||
FirstRaised: timeValue(a.GetFirstRaised()), LastSeen: timeValue(a.GetLastSeen()), Count: a.GetCount(),
|
||||
ClosedBy: a.GetClosedBy(), ClosedAt: timeValue(a.GetClosedAt()),
|
||||
Deliveries: mapValues(a.GetDeliveries(), alertDeliveryValue),
|
||||
}
|
||||
}
|
||||
|
||||
func alertDeliveryProto(d alert.Delivery) *pb.AlertDelivery {
|
||||
return &pb.AlertDelivery{
|
||||
Id: d.ID, Event: d.Event, State: d.State, CreatedAt: timestamp(d.CreatedAt),
|
||||
Attempts: mapValues(d.Attempts, func(a alert.Attempt) *pb.AlertAttempt {
|
||||
return &pb.AlertAttempt{N: a.N, At: timestamp(a.At), StatusCode: int64(a.StatusCode), Error: a.Error}
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
func alertDeliveryValue(d *pb.AlertDelivery) alert.Delivery {
|
||||
return alert.Delivery{
|
||||
ID: d.GetId(), Event: d.GetEvent(), State: d.GetState(), CreatedAt: timeValue(d.GetCreatedAt()),
|
||||
Attempts: mapValues(d.GetAttempts(), func(a *pb.AlertAttempt) alert.Attempt {
|
||||
return alert.Attempt{N: a.GetN(), At: timeValue(a.GetAt()), StatusCode: int(a.GetStatusCode()), Error: a.GetError()}
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
func (s *server) RaiseAlert(ctx context.Context, r *pb.RaiseAlertRequest) (*pb.RaiseAlertResponse, error) {
|
||||
if s.deps.Alerts == nil {
|
||||
return nil, errAlertsUnavailable
|
||||
}
|
||||
orgID, err := alertOrg(ctx, r.GetOrgId())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
stored, err := s.deps.Alerts.RaiseAlert(ctx, alert.Input{
|
||||
Org: orgID, Kind: r.GetKind(), Subject: r.GetSubject(),
|
||||
Severity: alert.Severity(r.GetSeverity()), Title: r.GetTitle(), Body: r.GetBody(), Link: r.GetLink(),
|
||||
Condition: r.GetCondition(),
|
||||
})
|
||||
if err != nil {
|
||||
return nil, alertStatus(err)
|
||||
}
|
||||
return &pb.RaiseAlertResponse{Alert: alertProto(stored)}, nil
|
||||
}
|
||||
|
||||
func (s *server) ResolveAlert(ctx context.Context, r *pb.ResolveAlertRequest) (*pb.ResolveAlertResponse, error) {
|
||||
if s.deps.Alerts == nil {
|
||||
return nil, errAlertsUnavailable
|
||||
}
|
||||
orgID, err := alertOrg(ctx, r.GetOrgId())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
key := alert.Key{Org: orgID, Kind: r.GetKind(), Subject: r.GetSubject()}
|
||||
if err := s.deps.Alerts.ResolveAlert(ctx, key, access.ActorFromContext(ctx)); err != nil {
|
||||
return nil, alertStatus(err)
|
||||
}
|
||||
return &pb.ResolveAlertResponse{}, nil
|
||||
}
|
||||
|
||||
func (s *server) DismissAlert(ctx context.Context, r *pb.DismissAlertRequest) (*pb.DismissAlertResponse, error) {
|
||||
if s.deps.Alerts == nil {
|
||||
return nil, errAlertsUnavailable
|
||||
}
|
||||
orgID, err := alertOrg(ctx, r.GetOrgId())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := s.deps.Alerts.DismissAlert(ctx, orgID, r.GetId(), access.ActorFromContext(ctx)); err != nil {
|
||||
return nil, alertStatus(err)
|
||||
}
|
||||
return &pb.DismissAlertResponse{}, nil
|
||||
}
|
||||
|
||||
func (s *server) ListAlerts(ctx context.Context, r *pb.ListAlertsRequest) (*pb.ListAlertsResponse, error) {
|
||||
if s.deps.Alerts == nil {
|
||||
return nil, errAlertsUnavailable
|
||||
}
|
||||
orgID, err := alertOrg(ctx, r.GetOrgId())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
filter := alert.Filter{Limit: int(r.GetLimit())}
|
||||
for _, st := range r.GetStates() {
|
||||
filter.States = append(filter.States, alert.State(st))
|
||||
}
|
||||
alerts, err := s.deps.Alerts.ListAlerts(ctx, orgID, filter)
|
||||
if err != nil {
|
||||
return nil, alertStatus(err)
|
||||
}
|
||||
return &pb.ListAlertsResponse{Alerts: mapValues(alerts, alertProto)}, nil
|
||||
}
|
||||
|
||||
// requireUnscoped refuses a caller confined to an org: the delivery queue
|
||||
// spans every org.
|
||||
func requireUnscoped(ctx context.Context) error {
|
||||
if _, ok := org.Scope(ctx); ok {
|
||||
return status.Error(codes.PermissionDenied, "alert deliveries are not available to an org-scoped caller")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *server) ClaimAlertDeliveries(ctx context.Context, r *pb.ClaimAlertDeliveriesRequest) (*pb.ClaimAlertDeliveriesResponse, error) {
|
||||
if s.deps.Alerts == nil {
|
||||
return nil, errAlertsUnavailable
|
||||
}
|
||||
if err := requireUnscoped(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
due, err := s.deps.Alerts.ClaimAlertDeliveries(ctx, int(r.GetLimit()))
|
||||
if err != nil {
|
||||
return nil, alertStatus(err)
|
||||
}
|
||||
return &pb.ClaimAlertDeliveriesResponse{Due: mapValues(due, func(d alert.Due) *pb.DueAlertDelivery {
|
||||
return &pb.DueAlertDelivery{Delivery: alertDeliveryProto(d.Delivery), Alert: alertProto(d.Alert), Attempt: d.Attempt}
|
||||
})}, nil
|
||||
}
|
||||
|
||||
func (s *server) RecordAlertAttempt(ctx context.Context, r *pb.RecordAlertAttemptRequest) (*pb.RecordAlertAttemptResponse, error) {
|
||||
if s.deps.Alerts == nil {
|
||||
return nil, errAlertsUnavailable
|
||||
}
|
||||
if err := requireUnscoped(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
err := s.deps.Alerts.RecordAlertAttempt(ctx, alert.Outcome{
|
||||
DeliveryID: r.GetDeliveryId(), Skipped: r.GetSkipped(), StatusCode: int(r.GetStatusCode()), Error: r.GetError(),
|
||||
})
|
||||
if err != nil {
|
||||
return nil, alertStatus(err)
|
||||
}
|
||||
return &pb.RecordAlertAttemptResponse{}, nil
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
// Alerts: the client half of the operator alert RPCs.
|
||||
package staterpc
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
pb "github.com/samcharles93/archie-core/internal/contracts/state/v1"
|
||||
"github.com/samcharles93/archie-core/internal/domain/alert"
|
||||
"github.com/samcharles93/archie-core/internal/domain/org"
|
||||
)
|
||||
|
||||
var _ alert.Store = (*Client)(nil)
|
||||
|
||||
func (c *Client) RaiseAlert(ctx context.Context, in alert.Input) (alert.Alert, error) {
|
||||
r, err := c.client.RaiseAlert(ctx, &pb.RaiseAlertRequest{
|
||||
OrgId: string(in.Org), Kind: in.Kind, Subject: in.Subject, Severity: string(in.Severity),
|
||||
Title: in.Title, Body: in.Body, Link: in.Link, Condition: in.Condition,
|
||||
})
|
||||
if err != nil {
|
||||
return alert.Alert{}, unmapError(err)
|
||||
}
|
||||
return alertValue(r.GetAlert()), nil
|
||||
}
|
||||
|
||||
func (c *Client) ResolveAlert(ctx context.Context, key alert.Key, _ string) error {
|
||||
_, err := c.client.ResolveAlert(ctx, &pb.ResolveAlertRequest{OrgId: string(key.Org), Kind: key.Kind, Subject: key.Subject})
|
||||
return unmapError(err)
|
||||
}
|
||||
|
||||
func (c *Client) DismissAlert(ctx context.Context, orgID org.OrgID, id int64, _ string) error {
|
||||
_, err := c.client.DismissAlert(ctx, &pb.DismissAlertRequest{OrgId: string(orgID), Id: id})
|
||||
return unmapError(err)
|
||||
}
|
||||
|
||||
func (c *Client) ListAlerts(ctx context.Context, orgID org.OrgID, filter alert.Filter) ([]alert.Alert, error) {
|
||||
states := make([]string, len(filter.States))
|
||||
for i, st := range filter.States {
|
||||
states[i] = string(st)
|
||||
}
|
||||
r, err := c.client.ListAlerts(ctx, &pb.ListAlertsRequest{OrgId: string(orgID), States: states, Limit: int32(filter.Limit)})
|
||||
if err != nil {
|
||||
return nil, unmapError(err)
|
||||
}
|
||||
return mapValues(r.GetAlerts(), alertValue), nil
|
||||
}
|
||||
|
||||
func (c *Client) ClaimAlertDeliveries(ctx context.Context, limit int) ([]alert.Due, error) {
|
||||
r, err := c.client.ClaimAlertDeliveries(ctx, &pb.ClaimAlertDeliveriesRequest{Limit: int32(limit)})
|
||||
if err != nil {
|
||||
return nil, unmapError(err)
|
||||
}
|
||||
return mapValues(r.GetDue(), func(d *pb.DueAlertDelivery) alert.Due {
|
||||
delivery := alertDeliveryValue(d.GetDelivery())
|
||||
a := alertValue(d.GetAlert())
|
||||
delivery.AlertID = a.ID
|
||||
return alert.Due{Delivery: delivery, Alert: a, Attempt: d.GetAttempt()}
|
||||
}), nil
|
||||
}
|
||||
|
||||
func (c *Client) RecordAlertAttempt(ctx context.Context, o alert.Outcome) error {
|
||||
_, err := c.client.RecordAlertAttempt(ctx, &pb.RecordAlertAttemptRequest{
|
||||
DeliveryId: o.DeliveryID, Skipped: o.Skipped, StatusCode: int64(o.StatusCode), Error: o.Error,
|
||||
})
|
||||
return unmapError(err)
|
||||
}
|
||||
@@ -0,0 +1,209 @@
|
||||
package staterpc
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
|
||||
pb "github.com/samcharles93/archie-core/internal/contracts/state/v1"
|
||||
"github.com/samcharles93/archie-core/internal/domain/alert"
|
||||
"github.com/samcharles93/archie-core/internal/domain/org"
|
||||
)
|
||||
|
||||
// fakeAlerts holds alerts in memory and applies the same transition rules the
|
||||
// State Store does, so the test drives the RPC handlers' org handling and the
|
||||
// domain's dedup, resolve and dismiss rules without a database.
|
||||
type fakeAlerts struct {
|
||||
alert.Store
|
||||
next int64
|
||||
alerts map[alert.Key]*alert.Alert
|
||||
}
|
||||
|
||||
func (f *fakeAlerts) RaiseAlert(_ context.Context, in alert.Input) (alert.Alert, error) {
|
||||
if err := in.Validate(); err != nil {
|
||||
return alert.Alert{}, err
|
||||
}
|
||||
prev := f.alerts[in.Key]
|
||||
next, _ := alert.Apply(prev, in, time.Now())
|
||||
if prev == nil {
|
||||
f.next++
|
||||
next.ID = f.next
|
||||
}
|
||||
f.alerts[in.Key] = &next
|
||||
return next, nil
|
||||
}
|
||||
|
||||
func (f *fakeAlerts) ResolveAlert(_ context.Context, key alert.Key, by string) error {
|
||||
if prev := f.alerts[key]; prev != nil {
|
||||
next, _ := alert.Resolve(*prev, by, time.Now())
|
||||
f.alerts[key] = &next
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *fakeAlerts) DismissAlert(_ context.Context, orgID org.OrgID, id int64, by string) error {
|
||||
for key, a := range f.alerts {
|
||||
if a.ID == id && key.Org == orgID {
|
||||
next, _ := alert.Dismiss(*a, by, time.Now())
|
||||
f.alerts[key] = &next
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return alert.ErrNotFound
|
||||
}
|
||||
|
||||
func (f *fakeAlerts) ListAlerts(_ context.Context, orgID org.OrgID, filter alert.Filter) ([]alert.Alert, error) {
|
||||
states := filter.States
|
||||
if len(states) == 0 {
|
||||
states = []alert.State{alert.StateOpen}
|
||||
}
|
||||
var out []alert.Alert
|
||||
for key, a := range f.alerts {
|
||||
if key.Org == orgID && slices.Contains(states, a.State) {
|
||||
out = append(out, *a)
|
||||
}
|
||||
}
|
||||
slices.SortFunc(out, func(a, b alert.Alert) int { return strings.Compare(a.Subject, b.Subject) })
|
||||
return out, nil
|
||||
}
|
||||
|
||||
type alertStep struct {
|
||||
as org.OrgID // the caller's scope; empty is a service acting for no one
|
||||
op string // raise, event, resolve, dismiss or list
|
||||
org string // the org the request names
|
||||
subject string
|
||||
states []string
|
||||
want []string // list: "org subject state xcount"
|
||||
code codes.Code
|
||||
}
|
||||
|
||||
func TestAlerts(t *testing.T) {
|
||||
const a, b = "org-a", "org-b"
|
||||
cases := []struct {
|
||||
name string
|
||||
steps []alertStep
|
||||
}{
|
||||
{"raising again bumps one row", []alertStep{
|
||||
{op: "raise", org: a, subject: "t1"},
|
||||
{op: "raise", org: a, subject: "t1"},
|
||||
{op: "raise", org: a, subject: "t1"},
|
||||
{op: "raise", org: a, subject: "t2"},
|
||||
{op: "list", org: a, want: []string{"org-a t1 open x3", "org-a t2 open x1"}},
|
||||
}},
|
||||
{"a condition alert resolves itself", []alertStep{
|
||||
{op: "raise", org: a, subject: "t1"},
|
||||
{op: "resolve", org: a, subject: "t1"},
|
||||
{op: "resolve", org: a, subject: "t1"},
|
||||
{op: "list", org: a},
|
||||
{op: "list", org: a, states: []string{"resolved"}, want: []string{"org-a t1 resolved x1"}},
|
||||
}},
|
||||
{"an event alert is not resolved by a check", []alertStep{
|
||||
{op: "event", org: a, subject: "t1"},
|
||||
{op: "resolve", org: a, subject: "t1"},
|
||||
{op: "list", org: a, want: []string{"org-a t1 open x1"}},
|
||||
}},
|
||||
{"a dismissed condition stays snoozed until it clears and recurs", []alertStep{
|
||||
{op: "raise", org: a, subject: "t1"},
|
||||
{op: "dismiss", as: a, subject: "t1"},
|
||||
{op: "raise", org: a, subject: "t1"},
|
||||
{op: "list", org: a},
|
||||
{op: "resolve", org: a, subject: "t1"},
|
||||
{op: "raise", org: a, subject: "t1"},
|
||||
{op: "list", org: a, want: []string{"org-a t1 open x1"}},
|
||||
}},
|
||||
{"a dismissed event comes back when it happens again", []alertStep{
|
||||
{op: "event", org: a, subject: "t1"},
|
||||
{op: "dismiss", as: a, subject: "t1"},
|
||||
{op: "list", org: a},
|
||||
{op: "event", org: a, subject: "t1"},
|
||||
{op: "list", org: a, want: []string{"org-a t1 open x1"}},
|
||||
}},
|
||||
{"orgs never see each other's alerts", []alertStep{
|
||||
{op: "raise", org: a, subject: "t1"},
|
||||
{op: "raise", org: b, subject: "t1"},
|
||||
{op: "raise", org: b, subject: "t2"},
|
||||
{op: "list", as: a, want: []string{"org-a t1 open x1"}},
|
||||
{op: "list", as: b, org: a, want: []string{"org-b t1 open x1", "org-b t2 open x1"}},
|
||||
}},
|
||||
{"a scoped caller cannot reach another org", []alertStep{
|
||||
{op: "raise", org: a, subject: "t1"},
|
||||
{op: "dismiss", as: b, org: a, subject: "t1", code: codes.NotFound},
|
||||
{op: "raise", as: b, org: a, subject: "t9"},
|
||||
{op: "list", as: a, want: []string{"org-a t1 open x1"}},
|
||||
{op: "list", as: b, want: []string{"org-b t9 open x1"}},
|
||||
}},
|
||||
{"a service must name the org", []alertStep{
|
||||
{op: "raise", subject: "t1", code: codes.InvalidArgument},
|
||||
}},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
s := &server{deps: Deps{Alerts: &fakeAlerts{alerts: map[alert.Key]*alert.Alert{}}}}
|
||||
for i, step := range tc.steps {
|
||||
ctx := context.Background()
|
||||
if step.as != "" {
|
||||
ctx = org.WithScope(ctx, step.as)
|
||||
}
|
||||
got, err := runAlertStep(ctx, s, step)
|
||||
if status.Code(err) != step.code {
|
||||
t.Fatalf("step %d (%s): code %v, want %v (%v)", i, step.op, status.Code(err), step.code, err)
|
||||
}
|
||||
if step.op == "list" && !slices.Equal(got, step.want) {
|
||||
t.Fatalf("step %d: listed %q, want %q", i, got, step.want)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func runAlertStep(ctx context.Context, s *server, step alertStep) ([]string, error) {
|
||||
switch step.op {
|
||||
case "raise", "event":
|
||||
_, err := s.RaiseAlert(ctx, &pb.RaiseAlertRequest{
|
||||
OrgId: step.org, Kind: "k", Subject: step.subject, Severity: "action", Title: "t",
|
||||
Condition: step.op == "raise",
|
||||
})
|
||||
return nil, err
|
||||
case "resolve":
|
||||
_, err := s.ResolveAlert(ctx, &pb.ResolveAlertRequest{OrgId: step.org, Kind: "k", Subject: step.subject})
|
||||
return nil, err
|
||||
case "dismiss":
|
||||
// The alert's id is looked up under the org the step names, or the
|
||||
// caller's own.
|
||||
owner := cmpOr(step.org, string(step.as))
|
||||
listed, err := s.deps.Alerts.ListAlerts(ctx, org.OrgID(owner), alert.Filter{})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
id := int64(-1)
|
||||
for _, a := range listed {
|
||||
if a.Subject == step.subject {
|
||||
id = a.ID
|
||||
}
|
||||
}
|
||||
_, err = s.DismissAlert(ctx, &pb.DismissAlertRequest{OrgId: step.org, Id: id})
|
||||
return nil, err
|
||||
default:
|
||||
r, err := s.ListAlerts(ctx, &pb.ListAlertsRequest{OrgId: step.org, States: step.states})
|
||||
var out []string
|
||||
for _, a := range r.GetAlerts() {
|
||||
out = append(out, fmt.Sprintf("%s %s %s x%d", a.GetOrgId(), a.GetSubject(), a.GetState(), a.GetCount()))
|
||||
}
|
||||
return out, err
|
||||
}
|
||||
}
|
||||
|
||||
func cmpOr(values ...string) string {
|
||||
for _, v := range values {
|
||||
if v != "" {
|
||||
return v
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
@@ -19,6 +19,7 @@ import (
|
||||
controlpb "github.com/samcharles93/archie-core/internal/contracts/controlplane/v1"
|
||||
pb "github.com/samcharles93/archie-core/internal/contracts/state/v1"
|
||||
"github.com/samcharles93/archie-core/internal/domain/access"
|
||||
"github.com/samcharles93/archie-core/internal/domain/alert"
|
||||
"github.com/samcharles93/archie-core/internal/domain/binding"
|
||||
"github.com/samcharles93/archie-core/internal/domain/identity"
|
||||
"github.com/samcharles93/archie-core/internal/domain/mapping"
|
||||
@@ -143,6 +144,9 @@ type Deps struct {
|
||||
// Denials records and lists denial records. Optional: nil disables the
|
||||
// pair with codes.Unavailable.
|
||||
Denials access.DenialStore
|
||||
// Alerts is the operator alert store. Optional: nil answers the alert
|
||||
// RPCs with codes.Unavailable.
|
||||
Alerts alert.Store
|
||||
// Orgs persists orgs, workspaces, memberships and agent assignments.
|
||||
// Optional: nil answers the org RPCs with codes.Unavailable.
|
||||
Orgs org.Repository
|
||||
|
||||
@@ -24,3 +24,11 @@ func VerifyHMAC(body []byte, signature, secret string) bool {
|
||||
mac.Write(body)
|
||||
return hmac.Equal(supplied, mac.Sum(nil))
|
||||
}
|
||||
|
||||
// SignHMAC is the "sha256=" hex HMAC-SHA256 of body, the form VerifyHMAC
|
||||
// accepts.
|
||||
func SignHMAC(body []byte, secret string) string {
|
||||
mac := hmac.New(sha256.New, []byte(secret))
|
||||
mac.Write(body)
|
||||
return "sha256=" + hex.EncodeToString(mac.Sum(nil))
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
package webui
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/access"
|
||||
"github.com/samcharles93/archie-core/internal/domain/alert"
|
||||
"github.com/samcharles93/archie-core/internal/domain/org"
|
||||
)
|
||||
|
||||
// AlertSource is the alert surface the dashboard reads and dismisses
|
||||
// through. The caller's org is the only one it can reach.
|
||||
type AlertSource interface {
|
||||
ListAlerts(ctx context.Context, orgID org.OrgID, filter alert.Filter) ([]alert.Alert, error)
|
||||
DismissAlert(ctx context.Context, orgID org.OrgID, id int64, by string) error
|
||||
}
|
||||
|
||||
type alertView struct {
|
||||
ID int64 `json:"id"`
|
||||
Kind string `json:"kind"`
|
||||
Subject string `json:"subject"`
|
||||
Severity string `json:"severity"`
|
||||
Title string `json:"title"`
|
||||
Body string `json:"body"`
|
||||
Link string `json:"link,omitempty"`
|
||||
Condition bool `json:"condition"`
|
||||
State string `json:"state"`
|
||||
FirstRaised time.Time `json:"first_raised"`
|
||||
LastSeen time.Time `json:"last_seen"`
|
||||
Count int64 `json:"count"`
|
||||
ClosedBy string `json:"closed_by,omitempty"`
|
||||
ClosedAt *time.Time `json:"closed_at,omitempty"`
|
||||
Deliveries []deliveryView `json:"deliveries"`
|
||||
}
|
||||
|
||||
type deliveryView struct {
|
||||
Event string `json:"event"`
|
||||
State string `json:"state"`
|
||||
Created time.Time `json:"created_at"`
|
||||
Attempts []attemptView `json:"attempts"`
|
||||
}
|
||||
|
||||
type attemptView struct {
|
||||
N int64 `json:"n"`
|
||||
At time.Time `json:"at"`
|
||||
StatusCode int `json:"status_code,omitempty"`
|
||||
Error string `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
func viewOfAlert(a alert.Alert) alertView {
|
||||
view := alertView{
|
||||
ID: a.ID, Kind: a.Kind, Subject: a.Subject, Severity: string(a.Severity), Title: a.Title,
|
||||
Body: a.Body, Link: a.Link, Condition: a.Condition, State: string(a.State),
|
||||
FirstRaised: a.FirstRaised, LastSeen: a.LastSeen, Count: a.Count, ClosedBy: a.ClosedBy,
|
||||
Deliveries: make([]deliveryView, 0, len(a.Deliveries)),
|
||||
}
|
||||
if !a.ClosedAt.IsZero() {
|
||||
view.ClosedAt = &a.ClosedAt
|
||||
}
|
||||
for _, d := range a.Deliveries {
|
||||
dv := deliveryView{Event: d.Event, State: d.State, Created: d.CreatedAt, Attempts: make([]attemptView, 0, len(d.Attempts))}
|
||||
for _, at := range d.Attempts {
|
||||
dv.Attempts = append(dv.Attempts, attemptView{N: at.N, At: at.At, StatusCode: at.StatusCode, Error: at.Error})
|
||||
}
|
||||
view.Deliveries = append(view.Deliveries, dv)
|
||||
}
|
||||
return view
|
||||
}
|
||||
|
||||
// handleAlerts lists the caller's org's alerts: open ones unless ?state names
|
||||
// others (comma separated), most severe first.
|
||||
func (s *Server) handleAlerts(w http.ResponseWriter, r *http.Request) {
|
||||
if s.Alerts == nil {
|
||||
http.Error(w, "alerts unavailable", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
filter := alert.Filter{}
|
||||
if states := r.URL.Query().Get("state"); states != "" {
|
||||
for state := range strings.SplitSeq(states, ",") {
|
||||
filter.States = append(filter.States, alert.State(strings.TrimSpace(state)))
|
||||
}
|
||||
}
|
||||
alerts, err := s.Alerts.ListAlerts(r.Context(), policyOrg(r), filter)
|
||||
if err != nil {
|
||||
s.Log.Error("list alerts", "err", err)
|
||||
http.Error(w, "list alerts failed", http.StatusBadGateway)
|
||||
return
|
||||
}
|
||||
views := make([]alertView, len(alerts))
|
||||
for i, a := range alerts {
|
||||
views[i] = viewOfAlert(a)
|
||||
}
|
||||
writeJSON(w, map[string]any{"alerts": views})
|
||||
}
|
||||
|
||||
// handleAlertDismiss dismisses one open alert of the caller's org.
|
||||
func (s *Server) handleAlertDismiss(w http.ResponseWriter, r *http.Request) {
|
||||
if s.Alerts == nil {
|
||||
http.Error(w, "alerts unavailable", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
|
||||
if err != nil {
|
||||
http.Error(w, "invalid alert id", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
err = s.Alerts.DismissAlert(r.Context(), policyOrg(r), id, access.ActorFromContext(r.Context()))
|
||||
switch {
|
||||
case errors.Is(err, alert.ErrNotFound):
|
||||
http.Error(w, "alert not found", http.StatusNotFound)
|
||||
case err != nil:
|
||||
s.Log.Error("dismiss alert", "err", err)
|
||||
http.Error(w, "dismiss alert failed", http.StatusBadGateway)
|
||||
default:
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
}
|
||||
@@ -94,6 +94,10 @@ type Server struct {
|
||||
// dashboard.
|
||||
ApplyStatus storecontract.ApplyStatusStore
|
||||
|
||||
// Alerts lists and dismisses the caller's org's operator alerts. Nil
|
||||
// answers 503.
|
||||
Alerts AlertSource
|
||||
|
||||
// Presence lists every service instance's record, behind the services
|
||||
// card. Nil answers 503.
|
||||
Presence storecontract.PresenceStore
|
||||
@@ -253,6 +257,8 @@ func (s *Server) registerCoreRoutes(mux *http.ServeMux) {
|
||||
mux.HandleFunc("POST /api/channels/{id}/reload", instanceOnly(s.handleChannelReload))
|
||||
mux.HandleFunc("GET /api/version", s.handleVersion)
|
||||
mux.HandleFunc("GET /api/capabilities", s.handleCapabilities)
|
||||
mux.HandleFunc("GET /api/alerts", s.handleAlerts)
|
||||
mux.HandleFunc("POST /api/alerts/{id}/dismiss", s.handleAlertDismiss)
|
||||
}
|
||||
|
||||
func (s *Server) registerTaskRoutes(mux *http.ServeMux) {
|
||||
|
||||
Reference in new issue
Block a user