Files
archie/modules/memory/internal/store/store.go
T

84 lines
2.9 KiB
Go

// Package store persists incident history.
package store
import (
"context"
"fmt"
"time"
"github.com/google/uuid"
"github.com/jmoiron/sqlx"
)
// Incident is the stored record of a run's investigation.
type Incident struct {
ID uuid.UUID `db:"id"`
RunID uuid.UUID `db:"run_id"`
TargetKind string `db:"target_kind"`
TargetID string `db:"target_id"`
Cause string `db:"cause"`
Summary string `db:"summary"`
Event []byte `db:"event"`
Actions []byte `db:"actions"`
At time.Time `db:"at"`
}
// Store is the memory module's Postgres store.
type Store struct {
db *sqlx.DB
}
// New returns a store on db.
func New(db *sqlx.DB) *Store { return &Store{db: db} }
// Upsert inserts an incident or updates the target, cause and summary for
// the same organisation and run. It preserves the original event and timestamp.
func (s *Store) Upsert(ctx context.Context, orgID string, in Incident) error {
if _, err := s.db.ExecContext(ctx, `
INSERT INTO memory.incidents (id, org_id, run_id, target_kind, target_id, cause, summary, event)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
ON CONFLICT (org_id, run_id) DO UPDATE
SET target_kind = EXCLUDED.target_kind, target_id = EXCLUDED.target_id,
cause = EXCLUDED.cause, summary = EXCLUDED.summary`,
in.ID, orgID, in.RunID, in.TargetKind, in.TargetID, in.Cause, in.Summary, in.Event); err != nil {
return fmt.Errorf("record incident: %w", err)
}
return nil
}
// SetActions replaces the recorded action outcomes for a run's incident.
func (s *Store) SetActions(ctx context.Context, orgID string, runID uuid.UUID, actions []byte) error {
if _, err := s.db.ExecContext(ctx, `
UPDATE memory.incidents SET actions = $3 WHERE org_id = $1 AND run_id = $2`,
orgID, runID, actions); err != nil {
return fmt.Errorf("record incident actions: %w", err)
}
return nil
}
// Incident returns a run's incident; ok is false when it has none.
func (s *Store) Incident(ctx context.Context, orgID string, runID uuid.UUID) (Incident, bool, error) {
var out []Incident
if err := s.db.SelectContext(ctx, &out, `
SELECT id, run_id, target_kind, target_id, cause, summary, event, actions, at
FROM memory.incidents WHERE org_id = $1 AND run_id = $2`, orgID, runID); err != nil {
return Incident{}, false, fmt.Errorf("read incident: %w", err)
}
if len(out) == 0 {
return Incident{}, false, nil
}
return out[0], true, nil
}
// ByTarget returns a target's incidents, newest first, up to limit.
func (s *Store) ByTarget(ctx context.Context, orgID, kind, id string, limit int) ([]Incident, error) {
var out []Incident
if err := s.db.SelectContext(ctx, &out, `
SELECT id, run_id, target_kind, target_id, cause, summary, event, actions, at
FROM memory.incidents WHERE org_id = $1 AND target_kind = $2 AND target_id = $3
ORDER BY at DESC LIMIT $4`, orgID, kind, id, limit); err != nil {
return nil, fmt.Errorf("list incidents: %w", err)
}
return out, nil
}