Skip to content

armgit / Pulse

Public Imported from GitHub
0

Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.

14.4 KB
Raw Blame
// Package ai provides AI-powered infrastructure monitoring and investigation.
package ai

import (
	"sync"
	"time"

	"github.com/rcourtman/pulse-go-rewrite/internal/config"
	"github.com/rs/zerolog/log"
)

// PatrolHistoryPersistence interface for saving/loading patrol run history
type PatrolHistoryPersistence interface {
	SavePatrolRunHistory(runs []PatrolRunRecord) error
	LoadPatrolRunHistory() ([]PatrolRunRecord, error)
	SavePatrolSchedule(next time.Time, interval time.Duration) error
	LoadPatrolSchedule() (time.Time, time.Duration, error)
}

// PatrolHistoryPersistenceAdapter bridges ConfigPersistence to PatrolHistoryPersistence interface
type PatrolHistoryPersistenceAdapter struct {
	config *config.ConfigPersistence
}

// NewPatrolHistoryPersistenceAdapter creates a new adapter
func NewPatrolHistoryPersistenceAdapter(cfg *config.ConfigPersistence) *PatrolHistoryPersistenceAdapter {
	return &PatrolHistoryPersistenceAdapter{config: cfg}
}

func (a *PatrolHistoryPersistenceAdapter) SavePatrolSchedule(next time.Time, interval time.Duration) error {
	return a.config.SavePatrolSchedule(next, interval)
}

func (a *PatrolHistoryPersistenceAdapter) LoadPatrolSchedule() (time.Time, time.Duration, error) {
	data, err := a.config.LoadPatrolRunHistory()
	if err != nil {
		return time.Time{}, 0, err
	}
	return data.NextScheduledAt, data.ScheduleInterval, nil
}

// SavePatrolRunHistory saves patrol run history to disk via ConfigPersistence
func (a *PatrolHistoryPersistenceAdapter) SavePatrolRunHistory(runs []PatrolRunRecord) error {
	// Convert from ai.PatrolRunRecord to config.PatrolRunRecord
	records := make([]config.PatrolRunRecord, 0, len(runs))
	for _, r := range runs {
		normalized := normalizePatrolRunRecord(r)
		if isDemoPatrolRunRecord(normalized) {
			continue
		}
		durationMs := normalized.DurationMs
		if durationMs == 0 && normalized.Duration > 0 {
			durationMs = int64(normalized.Duration / time.Millisecond)
		}
		records = append(records, config.PatrolRunRecord{
			ID:                        normalized.ID,
			Source:                    normalized.Source,
			StartedAt:                 normalized.StartedAt,
			CompletedAt:               normalized.CompletedAt,
			DurationMs:                durationMs,
			Type:                      normalized.Type,
			TriggerReason:             normalized.TriggerReason,
			ScopeResourceIDs:          normalized.ScopeResourceIDs,
			EffectiveScopeResourceIDs: normalized.EffectiveScopeResourceIDs,
			ScopeResourceTypes:        normalized.ScopeResourceTypes,
			ScopeContext:              normalized.ScopeContext,
			ObjectiveContext:          clonePatrolObjectiveContext(normalized.ObjectiveContext),
			AlertIdentifier:           normalized.AlertIdentifier,
			FindingID:                 normalized.FindingID,
			ResourcesChecked:          normalized.ResourcesChecked,
			NodesChecked:              normalized.NodesChecked,
			GuestsChecked:             normalized.GuestsChecked,
			DockerChecked:             normalized.DockerChecked,
			StorageChecked:            normalized.StorageChecked,
			HostsChecked:              normalized.HostsChecked,
			TrueNASChecked:            normalized.TrueNASChecked,
			PBSChecked:                normalized.PBSChecked,
			PMGChecked:                normalized.PMGChecked,
			KubernetesChecked:         normalized.KubernetesChecked,
			NewFindings:               normalized.NewFindings,
			ExistingFindings:          normalized.ExistingFindings,
			RejectedFindings:          normalized.RejectedFindings,
			ResolvedFindings:          normalized.ResolvedFindings,
			FindingsSummary:           normalized.FindingsSummary,
			FindingIDs:                normalized.FindingIDs,
			ErrorCount:                normalized.ErrorCount,
			Status:                    normalized.Status,
			ErrorSummary:              normalized.ErrorSummary,
			ErrorDetail:               normalized.ErrorDetail,
			TriageFlags:               normalized.TriageFlags,
			TriageSkippedLLM:          normalized.TriageSkippedLLM,
			AIAnalysis:                normalized.AIAnalysis,
			InputTokens:               normalized.InputTokens,
			OutputTokens:              normalized.OutputTokens,
			CacheCreationInputTokens:  normalized.CacheCreationInputTokens,
			CacheReadInputTokens:      normalized.CacheReadInputTokens,
			ToolCalls:                 convertAIToolCallsToConfig(normalized.ToolCalls),
			ToolCallCount:             normalized.ToolCallCount,
		})
	}
	return a.config.SavePatrolRunHistory(records)
}

// LoadPatrolRunHistory loads patrol run history from disk via ConfigPersistence
func (a *PatrolHistoryPersistenceAdapter) LoadPatrolRunHistory() ([]PatrolRunRecord, error) {
	data, err := a.config.LoadPatrolRunHistory()
	if err != nil {
		return nil, err
	}

	// Convert from config.PatrolRunRecord to ai.PatrolRunRecord
	runCount := clampHistoryCount(len(data.Runs), 0, MaxPatrolRunHistory)
	runs := make([]PatrolRunRecord, 0, runCount)
	for _, r := range data.Runs[:runCount] {
		run := normalizePatrolRunRecord(PatrolRunRecord{
			ID:                        r.ID,
			Source:                    r.Source,
			StartedAt:                 r.StartedAt,
			CompletedAt:               r.CompletedAt,
			Duration:                  time.Duration(r.DurationMs) * time.Millisecond, // Convert milliseconds to nanoseconds
			DurationMs:                r.DurationMs,
			Type:                      r.Type,
			TriggerReason:             r.TriggerReason,
			ScopeResourceIDs:          r.ScopeResourceIDs,
			EffectiveScopeResourceIDs: r.EffectiveScopeResourceIDs,
			ScopeResourceTypes:        r.ScopeResourceTypes,
			ScopeContext:              r.ScopeContext,
			ObjectiveContext:          clonePatrolObjectiveContext(r.ObjectiveContext),
			AlertIdentifier:           r.AlertIdentifier,
			FindingID:                 r.FindingID,
			ResourcesChecked:          r.ResourcesChecked,
			NodesChecked:              r.NodesChecked,
			GuestsChecked:             r.GuestsChecked,
			DockerChecked:             r.DockerChecked,
			StorageChecked:            r.StorageChecked,
			HostsChecked:              r.HostsChecked,
			TrueNASChecked:            r.TrueNASChecked,
			PBSChecked:                r.PBSChecked,
			PMGChecked:                r.PMGChecked,
			KubernetesChecked:         r.KubernetesChecked,
			NewFindings:               r.NewFindings,
			ExistingFindings:          r.ExistingFindings,
			RejectedFindings:          r.RejectedFindings,
			ResolvedFindings:          r.ResolvedFindings,
			FindingsSummary:           r.FindingsSummary,
			FindingIDs:                r.FindingIDs,
			ErrorCount:                r.ErrorCount,
			Status:                    r.Status,
			ErrorSummary:              r.ErrorSummary,
			ErrorDetail:               r.ErrorDetail,
			TriageFlags:               r.TriageFlags,
			TriageSkippedLLM:          r.TriageSkippedLLM,
			AIAnalysis:                r.AIAnalysis,
			InputTokens:               r.InputTokens,
			OutputTokens:              r.OutputTokens,
			CacheCreationInputTokens:  r.CacheCreationInputTokens,
			CacheReadInputTokens:      r.CacheReadInputTokens,
			ToolCalls:                 convertConfigToolCallsToAI(r.ToolCalls),
			ToolCallCount:             r.ToolCallCount,
		})
		if !IsDemoMode() && isDemoPatrolRunRecord(run) {
			continue
		}
		runs = append(runs, run)
	}
	return runs, nil
}

func convertAIToolCallsToConfig(calls []ToolCallRecord) []config.ToolCallRecord {
	if len(calls) == 0 {
		return nil
	}
	out := make([]config.ToolCallRecord, len(calls))
	for i, c := range calls {
		out[i] = config.ToolCallRecord{
			ID:        c.ID,
			ToolName:  c.ToolName,
			Input:     c.Input,
			Output:    c.Output,
			Success:   c.Success,
			StartTime: c.StartTime,
			EndTime:   c.EndTime,
			Duration:  c.Duration,
		}
	}
	return out
}

func convertConfigToolCallsToAI(calls []config.ToolCallRecord) []ToolCallRecord {
	if len(calls) == 0 {
		return nil
	}
	out := make([]ToolCallRecord, len(calls))
	for i, c := range calls {
		out[i] = ToolCallRecord{
			ID:        c.ID,
			ToolName:  c.ToolName,
			Input:     c.Input,
			Output:    c.Output,
			Success:   c.Success,
			StartTime: c.StartTime,
			EndTime:   c.EndTime,
			Duration:  c.Duration,
		}
	}
	return out
}

// PatrolRunHistoryStore provides thread-safe storage for patrol run history with optional persistence
type PatrolRunHistoryStore struct {
	mu               sync.RWMutex
	runs             []PatrolRunRecord
	maxRuns          int
	persistence      PatrolHistoryPersistence
	nextScheduledAt  time.Time
	scheduleInterval time.Duration
	// Debounce save operations
	saveTimer    *time.Timer
	savePending  bool
	saveDebounce time.Duration

	// Error tracking for persistence
	lastSaveError error
	lastSaveTime  time.Time
	onSaveError   func(err error)
}

func clampHistoryCount(value, minValue, maxValue int) int {
	if value < minValue {
		return minValue
	}
	if value > maxValue {
		return maxValue
	}
	return value
}

func normalizeHistoryRequestCount(requested, storeMax, available int) int {
	if requested <= 0 {
		requested = MaxPatrolRunHistory
	}
	requested = clampHistoryCount(requested, 0, MaxPatrolRunHistory)
	requested = clampHistoryCount(requested, 0, storeMax)
	return clampHistoryCount(requested, 0, available)
}

// NewPatrolRunHistoryStore creates a new patrol run history store
func NewPatrolRunHistoryStore(maxRuns int) *PatrolRunHistoryStore {
	if maxRuns <= 0 {
		maxRuns = MaxPatrolRunHistory
	}
	return &PatrolRunHistoryStore{
		runs:         make([]PatrolRunRecord, 0, maxRuns),
		maxRuns:      maxRuns,
		saveDebounce: 5 * time.Second,
	}
}

// SetPersistence sets the persistence layer and loads existing history
func (s *PatrolRunHistoryStore) SetPersistence(p PatrolHistoryPersistence) error {
	s.mu.Lock()
	s.persistence = p
	s.mu.Unlock()

	// Load existing history from disk
	if p != nil {
		runs, err := p.LoadPatrolRunHistory()
		if err != nil {
			return err
		}
		if len(runs) > 0 {
			if len(runs) > s.maxRuns {
				runs = runs[:s.maxRuns]
			}
			s.mu.Lock()
			s.runs = runs
			s.mu.Unlock()
			log.Info().Int("count", len(runs)).Msg("loaded patrol run history from disk")
		}
		next, interval, err := p.LoadPatrolSchedule()
		if err != nil {
			return err
		}
		s.mu.Lock()
		s.nextScheduledAt, s.scheduleInterval = next, interval
		s.mu.Unlock()
	}
	return nil
}

func (s *PatrolRunHistoryStore) Schedule() (time.Time, time.Duration) {
	s.mu.RLock()
	defer s.mu.RUnlock()
	return s.nextScheduledAt, s.scheduleInterval
}

// SetSchedule persists before the scheduler waits or starts its next run. Run
// history still uses its ordinary debounce; a restart must not reset this cursor.
func (s *PatrolRunHistoryStore) SetSchedule(next time.Time, interval time.Duration) error {
	s.mu.Lock()
	if s.nextScheduledAt.Equal(next) && s.scheduleInterval == interval && s.lastSaveError == nil {
		s.mu.Unlock()
		return nil
	}
	s.nextScheduledAt, s.scheduleInterval = next, interval
	persistence := s.persistence
	s.mu.Unlock()
	if persistence == nil {
		return nil
	}
	err := persistence.SavePatrolSchedule(next, interval)
	s.mu.Lock()
	s.lastSaveError = err
	if err == nil {
		s.lastSaveTime = time.Now()
	}
	onErr := s.onSaveError
	s.mu.Unlock()
	if err != nil && onErr != nil {
		onErr(err)
	}
	return err
}

// Add adds a new patrol run to the history
func (s *PatrolRunHistoryStore) Add(run PatrolRunRecord) {
	if run.DurationMs == 0 && run.Duration > 0 {
		run.DurationMs = run.Duration.Milliseconds()
	}
	if run.Duration == 0 && run.DurationMs > 0 {
		run.Duration = time.Duration(run.DurationMs) * time.Millisecond
	}

	s.mu.Lock()
	defer s.mu.Unlock()

	// Prepend (newest first)
	s.runs = append([]PatrolRunRecord{run}, s.runs...)

	// Trim to max
	if len(s.runs) > s.maxRuns {
		s.runs = s.runs[:s.maxRuns]
	}

	// Schedule save
	s.scheduleSaveLocked()
}

// GetAll returns all runs (newest first)
func (s *PatrolRunHistoryStore) GetAll() []PatrolRunRecord {
	s.mu.RLock()
	defer s.mu.RUnlock()

	result := make([]PatrolRunRecord, len(s.runs))
	copy(result, s.runs)
	return result
}

// GetRecent returns at most n recent runs
func (s *PatrolRunHistoryStore) GetRecent(n int) []PatrolRunRecord {
	s.mu.RLock()
	defer s.mu.RUnlock()

	n = normalizeHistoryRequestCount(n, s.maxRuns, len(s.runs))

	result := make([]PatrolRunRecord, n)
	copy(result, s.runs[:n])
	return result
}

// GetByID returns a single run by ID.
func (s *PatrolRunHistoryStore) GetByID(id string) (PatrolRunRecord, bool) {
	s.mu.RLock()
	defer s.mu.RUnlock()

	for _, run := range s.runs {
		if run.ID == id {
			return run, true
		}
	}

	return PatrolRunRecord{}, false
}

// Count returns the number of runs in history
func (s *PatrolRunHistoryStore) Count() int {
	s.mu.RLock()
	defer s.mu.RUnlock()
	return len(s.runs)
}

// scheduleSaveLocked schedules a debounced save operation.
// MUST be called with s.mu held (either Lock or is deferred with unlock).
func (s *PatrolRunHistoryStore) scheduleSaveLocked() {
	if s.persistence == nil {
		return
	}

	// Cancel existing timer if pending
	if s.saveTimer != nil {
		s.saveTimer.Stop()
	}

	s.savePending = true
	s.saveTimer = time.AfterFunc(s.saveDebounce, func() {
		s.mu.Lock()
		if !s.savePending {
			s.mu.Unlock()
			return
		}
		s.savePending = false
		// Copy runs while locked
		runs := make([]PatrolRunRecord, len(s.runs))
		copy(runs, s.runs)
		persistence := s.persistence
		s.mu.Unlock()

		// Save outside lock
		if persistence != nil {
			if err := persistence.SavePatrolRunHistory(runs); err != nil {
				log.Error().Err(err).Msg("failed to save patrol run history")
				s.mu.Lock()
				s.lastSaveError = err
				onErr := s.onSaveError
				s.mu.Unlock()
				if onErr != nil {
					onErr(err)
				}
			} else {
				s.mu.Lock()
				s.lastSaveError = nil
				s.lastSaveTime = time.Now()
				s.mu.Unlock()
			}
		}
	})
}

// SetOnSaveError sets a callback that is called when persistence fails.
func (s *PatrolRunHistoryStore) SetOnSaveError(fn func(err error)) {
	s.mu.Lock()
	defer s.mu.Unlock()
	s.onSaveError = fn
}

// GetPersistenceStatus returns the last save error, last save time, and whether persistence is configured.
func (s *PatrolRunHistoryStore) GetPersistenceStatus() (lastError error, lastSaveTime time.Time, hasPersistence bool) {
	s.mu.RLock()
	defer s.mu.RUnlock()
	return s.lastSaveError, s.lastSaveTime, s.persistence != nil
}

// FlushPersistence immediately saves any pending changes
func (s *PatrolRunHistoryStore) FlushPersistence() error {
	s.mu.Lock()
	if s.saveTimer != nil {
		s.saveTimer.Stop()
	}
	s.savePending = false
	runs := make([]PatrolRunRecord, len(s.runs))
	copy(runs, s.runs)
	persistence := s.persistence
	s.mu.Unlock()

	if persistence != nil {
		return persistence.SavePatrolRunHistory(runs)
	}
	return nil
}