package db import ( "encoding/json" "fmt" "time" ) // Sweep statuses stored in sources.status. Empty means "no sweep recorded yet". const ( SyncOK = "ok" SyncError = "error" SyncUnconfigured = "unconfigured" ) // SyncRecord is one sweep outcome, upserted after every ingest sweep so sync // health survives restarts. It lives in the DB rather than in watcher memory // because the MCP process shares the database file but not the process. type SyncRecord struct { SourceID string Status string // ok | error | unconfigured Interval time.Duration New int Updated int Unchanged int Scanned int Err string // error message when Status == error } // RecordSync upserts one sweep outcome. Success timestamps are kept when a // later sweep fails, so "last known good" survives an error. func (k *KnoxDB) RecordSync(r SyncRecord) error { now := time.Now().UTC().Format(time.RFC3339) counts, _ := json.Marshal(map[string]int{ "new": r.New, "updated": r.Updated, "unchanged": r.Unchanged, "scanned": r.Scanned, }) successAt := "" if r.Status == SyncOK { successAt = now } errAt := "" if r.Status == SyncError { errAt = now } if _, err := k.db.Exec( `INSERT INTO sources (id, name, status, last_attempt_at, last_success_at, last_error_at, last_error, last_counts, interval_seconds) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT(id) DO UPDATE SET status=excluded.status, last_attempt_at=excluded.last_attempt_at, last_success_at=CASE WHEN excluded.last_success_at!='' THEN excluded.last_success_at ELSE sources.last_success_at END, last_error_at=CASE WHEN excluded.last_error_at!='' THEN excluded.last_error_at ELSE sources.last_error_at END, last_error=excluded.last_error, last_counts=excluded.last_counts, interval_seconds=excluded.interval_seconds`, r.SourceID, r.SourceID, r.Status, now, successAt, errAt, r.Err, string(counts), int(r.Interval.Seconds()), ); err != nil { return fmt.Errorf("record sync status for %s: %w", r.SourceID, err) } return nil } // SourceStatus is the read-side view for `knox sync-status` and the MCP tool. // Status is a verdict computed from the stored sweep state, not the raw stored // value: stored "ok" can still read "stale" when the last success is overdue. type SourceStatus struct { ID string `json:"id"` Name string `json:"name"` Status string `json:"status"` // ok | stale | error | unconfigured | never Healthy bool `json:"healthy"` LastAttempt string `json:"last_attempt,omitempty"` LastSuccess string `json:"last_success,omitempty"` LastError string `json:"last_error,omitempty"` LastErrorDetail string `json:"last_error_detail,omitempty"` IntervalSeconds int `json:"interval_seconds,omitempty"` LastCounts map[string]int `json:"last_counts,omitempty"` Entries int `json:"entries"` LastCollected string `json:"last_collected,omitempty"` Detail string `json:"detail,omitempty"` } // staleAfter is how far past its interval a source's last success may slip // before it is reported stale. Sweeps jitter and can be missed while a machine // sleeps; a single interval is too twitchy for that. const staleAfter = 2.5 func (k *KnoxDB) SourceSync() ([]SourceStatus, error) { rows, err := k.db.Query( `SELECT s.id, s.name, COALESCE(s.status,''), COALESCE(s.last_attempt_at,''), COALESCE(s.last_success_at,''), COALESCE(s.last_error_at,''), COALESCE(s.last_error,''), COALESCE(s.last_counts,''), COALESCE(s.interval_seconds,0), COALESCE(o.n,0), COALESCE(o.last_collected,'') FROM sources s LEFT JOIN ( SELECT source_id, COUNT(DISTINCT fingerprint) AS n, MAX(collected_at) AS last_collected FROM observations GROUP BY source_id ) o ON o.source_id = s.id ORDER BY s.id`, ) if err != nil { return nil, fmt.Errorf("query source sync status: %w", err) } defer rows.Close() now := time.Now().UTC() out := make([]SourceStatus, 0, 8) for rows.Next() { var s SourceStatus var status, attempt, success, errAt, errMsg, counts string if err := rows.Scan(&s.ID, &s.Name, &status, &attempt, &success, &errAt, &errMsg, &counts, &s.IntervalSeconds, &s.Entries, &s.LastCollected); err != nil { return nil, fmt.Errorf("scan source sync status: %w", err) } s.LastAttempt, s.LastSuccess, s.LastError, s.LastErrorDetail = attempt, success, errAt, errMsg if counts != "" { _ = json.Unmarshal([]byte(counts), &s.LastCounts) } switch { case status == SyncUnconfigured: s.Status = SyncUnconfigured s.Detail = "source not configured (env missing); sweep is a no-op" case status == SyncError && (success == "" || parseRFC3339(errAt).After(parseRFC3339(success))): s.Status = SyncError s.Healthy = false case status == "": s.Status = "never" s.Healthy = s.Entries > 0 if s.Healthy { s.Detail = "no sweeps recorded; entries exist (event-driven or ingested before tracking)" } default: s.Status = status s.Healthy = true if status == SyncOK && s.IntervalSeconds > 0 { if since := now.Sub(parseRFC3339(success)); since > time.Duration(staleAfter*float64(time.Duration(s.IntervalSeconds)*time.Second)) { s.Status = "stale" s.Healthy = false s.Detail = fmt.Sprintf("last success %s ago, interval %s", relTime(now, parseRFC3339(success)), time.Duration(s.IntervalSeconds)*time.Second) } } } out = append(out, s) } return out, rows.Err() } func parseRFC3339(s string) time.Time { t, _ := time.Parse(time.RFC3339, s) return t } // relTime renders "3h ago" style age for a timestamp at or before now. func relTime(now, t time.Time) string { if t.IsZero() { return "never" } d := now.Sub(t) switch { case d < 0: return "just now" case d < time.Minute: return fmt.Sprintf("%ds", int(d.Seconds())) case d < time.Hour: return fmt.Sprintf("%dm", int(d.Minutes())) case d < 24*time.Hour: return fmt.Sprintf("%dh", int(d.Hours())) default: return fmt.Sprintf("%dd", int(d.Hours()/24)) } } // RelTime exposes relTime for the CLI formatter. func RelTime(now, t time.Time) string { return relTime(now, t) } // ParseRFC3339 exposes parseRFC3339 for the CLI formatter. func ParseRFC3339(s string) time.Time { return parseRFC3339(s) }