policy

package
v0.9.0 Latest Latest
Warning

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

Go to latest
Published: May 25, 2026 License: MIT Imports: 8 Imported by: 0

Documentation

Overview

Package policy provides channel conformance checks and policy enforcement.

Index

Constants

This section is empty.

Variables

View Source
var (
	// MaxLengthRule checks message content length.
	MaxLengthRule = func(maxLength int) ConformanceRule {
		return ConformanceRule{
			ID:          "max_length",
			Name:        "Maximum Message Length",
			Description: fmt.Sprintf("Messages must not exceed %d characters", maxLength),
			Severity:    SeverityWarning,
			Enabled:     true,
			Check: func(_ context.Context, msg *Message) error {
				if len(msg.Content) > maxLength {
					return fmt.Errorf("message length %d exceeds maximum %d", len(msg.Content), maxLength)
				}
				return nil
			},
		}
	}

	// NoEmptyContentRule checks that messages have content.
	NoEmptyContentRule = ConformanceRule{
		ID:          "no_empty_content",
		Name:        "No Empty Content",
		Description: "Messages must have non-empty content",
		Severity:    SeverityError,
		Enabled:     true,
		Check: func(_ context.Context, msg *Message) error {
			if msg.Content == "" {
				return fmt.Errorf("message content is empty")
			}
			return nil
		},
	}

	// ValidSenderRule checks that messages have a sender.
	ValidSenderRule = ConformanceRule{
		ID:          "valid_sender",
		Name:        "Valid Sender",
		Description: "Messages must have a valid sender ID",
		Severity:    SeverityError,
		Enabled:     true,
		Check: func(_ context.Context, msg *Message) error {
			if msg.SenderID == "" {
				return fmt.Errorf("sender ID is required")
			}
			return nil
		},
	}

	// ContentPatternRule checks message content against a regex pattern.
	ContentPatternRule = func(id, name string, pattern string, severity Severity, mustMatch bool) ConformanceRule {
		re := regexp.MustCompile(pattern)
		return ConformanceRule{
			ID:          id,
			Name:        name,
			Description: fmt.Sprintf("Content must %smatch pattern: %s", map[bool]string{true: "", false: "not "}[mustMatch], pattern),
			Severity:    severity,
			Enabled:     true,
			Check: func(_ context.Context, msg *Message) error {
				matches := re.MatchString(msg.Content)
				if mustMatch && !matches {
					return fmt.Errorf("content does not match required pattern")
				}
				if !mustMatch && matches {
					return fmt.Errorf("content matches prohibited pattern")
				}
				return nil
			},
		}
	}

	// RateLimitRule checks if sender is within rate limits.
	RateLimitRule = func(maxPerMinute int, tracker RateLimitTracker) ConformanceRule {
		return ConformanceRule{
			ID:          "rate_limit",
			Name:        "Rate Limit",
			Description: fmt.Sprintf("Senders limited to %d messages per minute", maxPerMinute),
			Severity:    SeverityWarning,
			Enabled:     true,
			Check: func(ctx context.Context, msg *Message) error {
				count := tracker.GetCount(msg.SenderID)
				if count >= maxPerMinute {
					return fmt.Errorf("rate limit exceeded: %d/%d messages per minute", count, maxPerMinute)
				}
				tracker.Increment(msg.SenderID)
				return nil
			},
		}
	}
)

Predefined conformance rules.

Functions

This section is empty.

Types

type CheckResult

type CheckResult struct {
	// RuleID is the ID of the rule that was checked.
	RuleID string

	// RuleName is the name of the rule.
	RuleName string

	// Passed indicates if the check passed.
	Passed bool

	// Severity is the rule severity.
	Severity Severity

	// Message is the result message.
	Message string

	// Duration is how long the check took.
	Duration time.Duration

	// Timestamp is when the check was performed.
	Timestamp time.Time
}

CheckResult represents the result of a conformance check.

type ConformanceCheckFunc

type ConformanceCheckFunc func(ctx context.Context, msg *Message) error

ConformanceCheckFunc is a function that checks conformance. Returns nil if conformant, error if violation detected.

type ConformanceChecker

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

ConformanceChecker validates messages against channel policies.

func NewConformanceChecker

func NewConformanceChecker(config ConformanceConfig) (*ConformanceChecker, error)

NewConformanceChecker creates a new conformance checker.

func (*ConformanceChecker) AddRule

func (c *ConformanceChecker) AddRule(rule ConformanceRule)

AddRule adds a new conformance rule.

func (*ConformanceChecker) Check

Check performs all applicable conformance checks on a message.

func (*ConformanceChecker) DisableRule

func (c *ConformanceChecker) DisableRule(id string)

DisableRule disables a rule by ID.

func (*ConformanceChecker) EnableRule

func (c *ConformanceChecker) EnableRule(id string)

EnableRule enables a rule by ID.

func (*ConformanceChecker) ListRules

func (c *ConformanceChecker) ListRules() []ConformanceRule

ListRules returns all registered rules.

func (*ConformanceChecker) RemoveRule

func (c *ConformanceChecker) RemoveRule(id string)

RemoveRule removes a rule by ID.

type ConformanceConfig

type ConformanceConfig struct {
	// Rules are the conformance rules to apply.
	Rules []ConformanceRule

	// ObservopsProvider is the observops provider for metrics.
	ObservopsProvider observops.Provider

	// AgentopsStore is the agentops store for event recording.
	AgentopsStore agentops.Store

	// Logger is the logger for conformance events.
	Logger *slog.Logger
}

ConformanceConfig configures the conformance checker.

type ConformanceReport

type ConformanceReport struct {
	// Channel is the channel that was checked.
	Channel string

	// MessageID is the message identifier.
	MessageID string

	// Results are the individual check results.
	Results []CheckResult

	// Passed indicates if all checks passed.
	Passed bool

	// Duration is the total check duration.
	Duration time.Duration

	// Timestamp is when the report was generated.
	Timestamp time.Time
}

ConformanceReport is a collection of check results.

type ConformanceRule

type ConformanceRule struct {
	// ID is the unique identifier for this rule.
	ID string

	// Name is the human-readable name for this rule.
	Name string

	// Description describes what this rule checks.
	Description string

	// Severity indicates the rule importance.
	Severity Severity

	// Channels is the list of channels this rule applies to.
	// Empty means all channels.
	Channels []string

	// Check is the function that performs the conformance check.
	Check ConformanceCheckFunc

	// Enabled controls whether this rule is active.
	Enabled bool
}

ConformanceRule defines a single conformance check.

type InMemoryRateLimitTracker

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

InMemoryRateLimitTracker is a simple in-memory rate limit tracker.

func NewInMemoryRateLimitTracker

func NewInMemoryRateLimitTracker(window time.Duration) *InMemoryRateLimitTracker

NewInMemoryRateLimitTracker creates a new in-memory rate limit tracker.

func (*InMemoryRateLimitTracker) GetCount

func (t *InMemoryRateLimitTracker) GetCount(senderID string) int

GetCount returns the current count for a sender.

func (*InMemoryRateLimitTracker) Increment

func (t *InMemoryRateLimitTracker) Increment(senderID string)

Increment increments the count for a sender.

type Message

type Message struct {
	// Channel is the channel the message is from/to.
	Channel string

	// Direction is "inbound" or "outbound".
	Direction string

	// Content is the message content.
	Content string

	// SenderID is the message sender identifier.
	SenderID string

	// Metadata contains additional message metadata.
	Metadata map[string]any

	// Timestamp is when the message was created.
	Timestamp time.Time
}

Message represents a message to be checked for conformance.

type RateLimitTracker

type RateLimitTracker interface {
	GetCount(senderID string) int
	Increment(senderID string)
}

RateLimitTracker tracks message rates per sender.

type Severity

type Severity string

Severity indicates the importance of a conformance rule.

const (
	SeverityInfo     Severity = "info"
	SeverityWarning  Severity = "warning"
	SeverityError    Severity = "error"
	SeverityCritical Severity = "critical"
)

Jump to

Keyboard shortcuts

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