rules

package
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 30, 2026 License: MIT Imports: 7 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func EnvForResource

func EnvForResource(rt ResourceType) (*cel.Env, error)

EnvForResource returns the appropriate CEL environment for the given resource type.

func LockEnv

func LockEnv() (*cel.Env, error)

LockEnv returns a CEL environment for evaluating rules against db.Lock resources.

func QueryEnv

func QueryEnv() (*cel.Env, error)

QueryEnv returns a CEL environment for evaluating rules against db.Query resources.

func TransactionEnv

func TransactionEnv() (*cel.Env, error)

TransactionEnv returns a CEL environment for evaluating rules against db.Transaction resources.

Types

type CancelAction

type CancelAction struct{}

CancelAction calls pg_cancel_backend.

func (*CancelAction) Execute

func (a *CancelAction) Execute(ctx context.Context, database *db.DB, pid int) error

func (*CancelAction) Name

func (a *CancelAction) Name() string

type Engine

type Engine struct {
	// contains filtered or unexported fields
}

Engine evaluates rules against snapshots and manages violation history.

func NewEngine

func NewEngine(rules []Rule, database *db.DB, violationTTL time.Duration, maxViolations int) *Engine

NewEngine creates a new rules engine.

func (*Engine) Evaluate

func (e *Engine) Evaluate(ctx context.Context, snap Snapshot)

Evaluate runs all rules against the snapshot.

func (*Engine) ManualAction

func (e *Engine) ManualAction(ruleName string, pid int) string

ManualAction manually fires an action for a violation and appends events to the log. Returns the result message for display.

func (*Engine) RecentViolations

func (e *Engine) RecentViolations() []Violation

RecentViolations returns violation history within TTL, newest first.

func (*Engine) RuleCount

func (e *Engine) RuleCount() int

RuleCount returns the number of active rules.

func (*Engine) Rules

func (e *Engine) Rules() []Rule

Rules returns a snapshot of the configured rules.

func (*Engine) UpdateRules

func (e *Engine) UpdateRules(rules []Rule)

UpdateRules hot-swaps the rule set.

func (*Engine) ViolatedPIDs

func (e *Engine) ViolatedPIDs() map[int]Violation

ViolatedPIDs returns a map of PIDs currently in active violation.

type EventKind

type EventKind string

EventKind identifies a type of violation lifecycle event.

const (
	EventDetected EventKind = "violation detected"
	EventAction   EventKind = "action triggered"
	EventSent     EventKind = "action sent"
	EventCooldown EventKind = "cooldown set"
	EventClosed   EventKind = "violation closed"
	EventError    EventKind = "error"
)

type Executor

type Executor interface {
	Execute(ctx context.Context, database *db.DB, pid int) error
	Name() string
}

Executor is the interface for rule actions.

type LogAction

type LogAction struct{}

LogAction writes a log line to stderr.

func (*LogAction) Execute

func (a *LogAction) Execute(_ context.Context, _ *db.DB, pid int) error

func (*LogAction) Name

func (a *LogAction) Name() string

type ResourceType

type ResourceType string

ResourceType identifies the kind of Postgres resource a rule targets.

const (
	ResourceQuery       ResourceType = "query"
	ResourceTransaction ResourceType = "transaction"
	ResourceLock        ResourceType = "lock"
)

type Rule

type Rule struct {
	Name       string
	Enabled    bool
	Resource   ResourceType
	Program    cel.Program
	Expression string
	Action     Executor
	Cooldown   time.Duration
	DryRun     bool
}

Rule binds a CEL expression to a resource type, an action, and cooldown config.

func BuildRules

func BuildRules(configs []RuleConfig, readonly bool) ([]Rule, error)

BuildRules compiles rule configs into executable rules. If readonly is true, all rules are forced to dry-run mode.

type RuleConfig

type RuleConfig struct {
	Name     string `yaml:"name"`
	Enabled  *bool  `yaml:"enabled"`
	DryRun   bool   `yaml:"dry_run"`
	Resource string `yaml:"resource"`
	When     string `yaml:"when"`
	Action   string `yaml:"action"`
	Cooldown string `yaml:"cooldown"`
}

RuleConfig is the YAML representation of a rule.

type Snapshot

type Snapshot struct {
	Queries      []db.Query
	Transactions []db.Transaction
	Locks        []db.Lock
}

Snapshot holds the data fetched in one polling tick.

type TerminateAction

type TerminateAction struct{}

TerminateAction calls pg_terminate_backend.

func (*TerminateAction) Execute

func (a *TerminateAction) Execute(ctx context.Context, database *db.DB, pid int) error

func (*TerminateAction) Name

func (a *TerminateAction) Name() string

type Violation

type Violation struct {
	RuleName     string
	ResourceType ResourceType
	PID          int
	Expression   string
	ActionName   string
	Active       bool
	DryRun       bool
	Events       []ViolationEvent

	QuerySnap       *db.Query
	TransactionSnap *db.Transaction
	LockSnap        *db.Lock
}

Violation records that a rule fired against a resource, with a full lifecycle audit log of events.

func (*Violation) CreatedAt

func (v *Violation) CreatedAt() time.Time

CreatedAt returns the timestamp of the first event.

func (*Violation) LastEvent

func (v *Violation) LastEvent() ViolationEvent

LastEvent returns the most recent event, or a zero event if empty.

type ViolationEvent

type ViolationEvent struct {
	Time    time.Time
	Kind    EventKind
	Message string
}

ViolationEvent is a timestamped entry in a violation's audit log.

type ViolationStore

type ViolationStore struct {
	// contains filtered or unexported fields
}

ViolationStore retains violations with TTL eviction and cooldown dedup.

func NewViolationStore

func NewViolationStore(ttl time.Duration, maxSize int) *ViolationStore

NewViolationStore creates a new violation store.

func (*ViolationStore) MarkActive

func (s *ViolationStore) MarkActive(activePIDs map[int]bool)

MarkActive updates the Active flag and appends a closed event for violations whose PID is no longer present.

func (*ViolationStore) Prune

func (s *ViolationStore) Prune()

Prune removes violations whose last event is older than TTL.

func (*ViolationStore) Recent

func (s *ViolationStore) Recent() []Violation

Recent returns violations within the TTL window, newest first.

func (*ViolationStore) RecordOrUpdate

func (s *ViolationStore) RecordOrUpdate(v Violation, cooldown time.Duration) (*Violation, bool)

RecordOrUpdate finds an existing active violation for the same rule+PID and returns it for event appending, or creates a new one. Returns the violation pointer and whether the action should fire (not in cooldown).

func (*ViolationStore) ViolatedPIDs

func (s *ViolationStore) ViolatedPIDs() map[int]Violation

ViolatedPIDs returns a map of PIDs currently in active violation.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL