From bceed5de4e9f02cf09d325b1a8332005160e4d2f Mon Sep 17 00:00:00 2001 From: Julian Blacher Date: Fri, 27 Nov 2026 13:15:07 -0300 Subject: [PATCH 1/2] feat(engine): record alerts and sink deliveries in the ledger The runner only wrote dedupe keys and cursors; the alerts and sends tables were never populated, so there was nothing to export or audit. Each alert that passes predicates, rate limit and dedupe is now stored before any sink is called, with a JSON payload and an event fingerprint, and every sink attempt is recorded as sent or failed. Sending behaviour is unchanged and dry-run still writes nothing. Adds ListCursors and ListAlerts (with per-sink sends and rule/since/limit filters) to the store. Co-Authored-By: Claude Opus 5.5 --- internal/engine/runner.go | 90 ++++++++++++++++++- internal/engine/runner_ledger_test.go | 89 +++++++++++++++++++ internal/storage/store.go | 121 ++++++++++++++++++++++++++ internal/storage/store_list_test.go | 89 +++++++++++++++++++ 4 files changed, 388 insertions(+), 1 deletion(-) create mode 100644 internal/engine/runner_ledger_test.go create mode 100644 internal/storage/store_list_test.go diff --git a/internal/engine/runner.go b/internal/engine/runner.go index e840971..83dba00 100644 --- a/internal/engine/runner.go +++ b/internal/engine/runner.go @@ -2,6 +2,9 @@ package engine import ( "context" + "crypto/rand" + "encoding/hex" + "encoding/json" "fmt" "strings" "time" @@ -196,19 +199,104 @@ func (r *Runner) handleEvents(ctx context.Context, events []Event) error { return err } } + payload := toSinkPayload(ev, exec.rule.ID) + alertID, err := r.recordAlert(ctx, ev, payload, now) + if err != nil { + return err + } for _, sinkID := range exec.rule.Sinks { s := r.sinks[sinkID] if s == nil { continue } - if err := s.Send(ctx, toSinkPayload(ev, exec.rule.ID)); err != nil { + sendErr := s.Send(ctx, payload) + status := "sent" + if sendErr != nil { + status = "failed" + } + if err := r.store.InsertSend(ctx, storage.Send{ + AlertID: alertID, + SinkID: sinkID, + Status: status, + CreatedAt: r.nowFunc(), + }); err != nil { return err } + if sendErr != nil { + return sendErr + } } } return nil } +// recordAlert writes the alert to the ledger before any sink is called, so +// `watch-tower export alerts` shows every alert and its delivery outcome. +func (r *Runner) recordAlert(ctx context.Context, ev Event, payload sink.EventPayload, now time.Time) (string, error) { + id, err := newAlertID() + if err != nil { + return "", err + } + doc := alertPayloadJSON(payload) + body, err := json.Marshal(doc) + if err != nil { + // An unencodable decoded arg must not stop alerting; keep the rest. + doc["args"] = nil + doc["args_error"] = err.Error() + if body, err = json.Marshal(doc); err != nil { + return "", fmt.Errorf("encode alert payload: %w", err) + } + } + if err := r.store.InsertAlert(ctx, storage.Alert{ + ID: id, + RuleID: payload.RuleID, + Fingerprint: eventFingerprint(ev), + TxHash: ev.TxHash, + PayloadJSON: string(body), + CreatedAt: now, + }); err != nil { + return "", err + } + return id, nil +} + +func newAlertID() (string, error) { + b := make([]byte, 16) + if _, err := rand.Read(b); err != nil { + return "", fmt.Errorf("generate alert id: %w", err) + } + return hex.EncodeToString(b), nil +} + +// eventFingerprint identifies the on-chain event an alert came from, so +// repeated alerts for the same event can be spotted in exports. +func eventFingerprint(ev Event) string { + logIndex := "" + if ev.LogIndex != nil { + logIndex = fmt.Sprintf("%d", *ev.LogIndex) + } + return fmt.Sprintf("%s|%s|%s|%s|%d", ev.RuleID, ev.SourceID, ev.TxHash, logIndex, ev.AppID) +} + +func alertPayloadJSON(p sink.EventPayload) map[string]any { + out := map[string]any{ + "rule_id": p.RuleID, + "chain": p.Chain, + "source_id": p.SourceID, + "height": p.Height, + "hash": p.Hash, + "txhash": p.TxHash, + "args": p.Args, + } + if p.LogIndex != nil { + out["log_index"] = *p.LogIndex + } + if p.AppID != 0 { + out["app_id"] = p.AppID + } + return out +} + func allPredicates(preds []Predicate, args map[string]any) (bool, error) { for _, p := range preds { ok, err := p(args) diff --git a/internal/engine/runner_ledger_test.go b/internal/engine/runner_ledger_test.go new file mode 100644 index 0000000..2542aa9 --- /dev/null +++ b/internal/engine/runner_ledger_test.go @@ -0,0 +1,89 @@ +package engine + +import ( + "context" + "encoding/json" + "errors" + "testing" + "time" + + "github.com/devblac/watch-tower/internal/config" + "github.com/devblac/watch-tower/internal/sink" + "github.com/devblac/watch-tower/internal/storage" +) + +type failingSink struct{} + +func (failingSink) Send(context.Context, sink.EventPayload) error { return errors.New("boom") } + +func TestRunnerRecordsAlertsAndSends(t *testing.T) { + store := newTestStore(t) + rule := config.Rule{ + ID: "r1", + Match: config.MatchSpec{Where: []string{"value > 10"}}, + Sinks: []string{"ok", "bad"}, + } + cfg := &config.Config{Rules: []config.Rule{rule}} + okSink := &fakeSink{} + runner, err := NewRunner(store, cfg, nil, nil, map[string]sink.Sender{"ok": okSink, "bad": failingSink{}}, false, 0, 0) + if err != nil { + t.Fatalf("runner: %v", err) + } + now := time.Date(2026, 3, 4, 5, 6, 7, 0, time.UTC) + runner.nowFunc = func() time.Time { return now } + + idx := uint(3) + evs := []Event{{ + RuleID: "r1", Chain: "evm", SourceID: "main", Height: 99, TxHash: "0xabc", LogIndex: &idx, + Args: map[string]any{"value": 20, "bytes": []any{func() {}}}, // unencodable arg + }} + if err := runner.handleEvents(context.Background(), evs); err == nil { + t.Fatalf("expected the failing sink error to surface") + } + + alerts, err := store.ListAlerts(context.Background(), storage.AlertFilter{}) + if err != nil { + t.Fatalf("list: %v", err) + } + if len(alerts) != 1 { + t.Fatalf("expected 1 alert, got %d", len(alerts)) + } + a := alerts[0] + if a.RuleID != "r1" || a.TxHash != "0xabc" || a.Fingerprint != "r1|main|0xabc|3|0" || !a.CreatedAt.Equal(now) { + t.Fatalf("unexpected alert: %+v", a.Alert) + } + var doc map[string]any + if err := json.Unmarshal([]byte(a.PayloadJSON), &doc); err != nil { + t.Fatalf("payload not JSON: %v", err) + } + if doc["height"] != float64(99) || doc["args_error"] == nil { + t.Fatalf("unexpected payload: %v", doc) + } + // Sinks run in rule order: "ok" succeeds, then "bad" fails and stops the pass. + if len(a.Sends) != 2 { + t.Fatalf("expected 2 sends, got %+v", a.Sends) + } + statuses := map[string]string{} + for _, s := range a.Sends { + statuses[s.SinkID] = s.Status + } + if statuses["ok"] != "sent" || statuses["bad"] != "failed" { + t.Fatalf("unexpected statuses: %v", statuses) + } +} + +func TestRunnerDryRunRecordsNothing(t *testing.T) { + store := newTestStore(t) + rule := config.Rule{ID: "r1", Sinks: []string{"s1"}} + runner, err := NewRunner(store, &config.Config{Rules: []config.Rule{rule}}, nil, nil, map[string]sink.Sender{"s1": &fakeSink{}}, true, 0, 0) + if err != nil { + t.Fatalf("runner: %v", err) + } + if err := runner.handleEvents(context.Background(), []Event{{RuleID: "r1", TxHash: "0x1"}}); err != nil { + t.Fatalf("handle: %v", err) + } + alerts, _ := store.ListAlerts(context.Background(), storage.AlertFilter{}) + if len(alerts) != 0 { + t.Fatalf("dry-run must not write alerts, got %d", len(alerts)) + } +} diff --git a/internal/storage/store.go b/internal/storage/store.go index b764cf3..ddb95e0 100644 --- a/internal/storage/store.go +++ b/internal/storage/store.go @@ -5,6 +5,7 @@ import ( "database/sql" "errors" "fmt" + "sort" "time" _ "modernc.org/sqlite" @@ -254,3 +255,123 @@ func nullTime(t time.Time) any { } return t.UTC() } + +// Cursor is the persisted scan position of a source. +type Cursor struct { + SourceID string + Height uint64 + Hash string + UpdatedAt time.Time +} + +// ListCursors returns every stored cursor ordered by source id. +func (s *Store) ListCursors(ctx context.Context) ([]Cursor, error) { + rows, err := s.db.QueryContext(ctx, ` +SELECT source_id, height, hash, updated_at FROM cursors ORDER BY source_id; +`) + if err != nil { + return nil, fmt.Errorf("list cursors: %w", err) + } + defer rows.Close() + + var out []Cursor + for rows.Next() { + var c Cursor + if err := rows.Scan(&c.SourceID, &c.Height, &c.Hash, &c.UpdatedAt); err != nil { + return nil, fmt.Errorf("scan cursor: %w", err) + } + out = append(out, c) + } + if err := rows.Err(); err != nil { + return nil, fmt.Errorf("list cursors: %w", err) + } + return out, nil +} + +// AlertFilter narrows ListAlerts. Zero values mean "no filter". +type AlertFilter struct { + RuleID string + Since time.Time + // Limit keeps only the most recent N alerts. + Limit int +} + +// AlertWithSends is an alert together with its per-sink delivery records. +type AlertWithSends struct { + Alert + Sends []Send +} + +// ListAlerts returns alerts oldest first, each with its sink deliveries. +func (s *Store) ListAlerts(ctx context.Context, f AlertFilter) ([]AlertWithSends, error) { + query := ` +SELECT a.id, a.rule_id, COALESCE(a.fingerprint, ''), COALESCE(a.txhash, ''), + COALESCE(a.payload_json, ''), a.created_at, + s.sink_id, s.status, s.response_code, s.created_at +FROM alerts a +LEFT JOIN sends s ON s.alert_id = a.id` + var args []any + if f.RuleID != "" { + query += ` WHERE a.rule_id = ?` + args = append(args, f.RuleID) + } + query += ` ORDER BY a.created_at, a.id, s.sink_id;` + + rows, err := s.db.QueryContext(ctx, query, args...) + if err != nil { + return nil, fmt.Errorf("list alerts: %w", err) + } + defer rows.Close() + + var out []AlertWithSends + index := map[string]int{} + for rows.Next() { + var ( + a Alert + sinkID sql.NullString + status sql.NullString + code sql.NullInt64 + sentAt sql.NullTime + ) + if err := rows.Scan(&a.ID, &a.RuleID, &a.Fingerprint, &a.TxHash, &a.PayloadJSON, &a.CreatedAt, + &sinkID, &status, &code, &sentAt); err != nil { + return nil, fmt.Errorf("scan alert: %w", err) + } + i, seen := index[a.ID] + if !seen { + i = len(out) + index[a.ID] = i + out = append(out, AlertWithSends{Alert: a}) + } + if sinkID.Valid { + out[i].Sends = append(out[i].Sends, Send{ + AlertID: a.ID, + SinkID: sinkID.String, + Status: status.String, + ResponseCode: int(code.Int64), + CreatedAt: sentAt.Time, + }) + } + } + if err := rows.Err(); err != nil { + return nil, fmt.Errorf("list alerts: %w", err) + } + + // Ordering and time filtering happen here rather than in SQL because rows + // written with CURRENT_TIMESTAMP and with bound time values use different + // text layouts, which do not compare reliably as strings. + sort.SliceStable(out, func(i, j int) bool { return out[i].CreatedAt.Before(out[j].CreatedAt) }) + if !f.Since.IsZero() { + kept := out[:0] + for _, a := range out { + if !a.CreatedAt.Before(f.Since) { + kept = append(kept, a) + } + } + out = kept + } + if f.Limit > 0 && len(out) > f.Limit { + out = out[len(out)-f.Limit:] + } + return out, nil +} diff --git a/internal/storage/store_list_test.go b/internal/storage/store_list_test.go new file mode 100644 index 0000000..b98b340 --- /dev/null +++ b/internal/storage/store_list_test.go @@ -0,0 +1,89 @@ +package storage + +import ( + "context" + "testing" + "time" +) + +func TestListCursors(t *testing.T) { + store := newTestStore(t) + ctx := context.Background() + + if got, err := store.ListCursors(ctx); err != nil || len(got) != 0 { + t.Fatalf("empty store: got %v, err %v", got, err) + } + if err := store.UpsertCursor(ctx, "evm_main", 100, "0xaa"); err != nil { + t.Fatal(err) + } + if err := store.UpsertCursor(ctx, "algo_main", 7, "BB"); err != nil { + t.Fatal(err) + } + + got, err := store.ListCursors(ctx) + if err != nil { + t.Fatalf("list: %v", err) + } + if len(got) != 2 || got[0].SourceID != "algo_main" || got[1].SourceID != "evm_main" { + t.Fatalf("unexpected cursors: %+v", got) + } + if got[1].Height != 100 || got[1].Hash != "0xaa" { + t.Fatalf("unexpected evm cursor: %+v", got[1]) + } + if got[1].UpdatedAt.IsZero() || time.Since(got[1].UpdatedAt) > time.Hour { + t.Fatalf("updated_at not parsed: %v", got[1].UpdatedAt) + } +} + +func TestListAlertsWithSendsAndFilters(t *testing.T) { + store := newTestStore(t) + ctx := context.Background() + base := time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC) + + alerts := []Alert{ + {ID: "a1", RuleID: "whale", TxHash: "0x1", PayloadJSON: `{"n":1}`, CreatedAt: base}, + {ID: "a2", RuleID: "app", TxHash: "0x2", CreatedAt: base.Add(time.Hour)}, + {ID: "a3", RuleID: "whale", TxHash: "0x3", CreatedAt: base.Add(2 * time.Hour)}, + } + for _, a := range alerts { + if err := store.InsertAlert(ctx, a); err != nil { + t.Fatalf("insert %s: %v", a.ID, err) + } + } + if err := store.InsertSend(ctx, Send{AlertID: "a1", SinkID: "slack", Status: "sent", CreatedAt: base}); err != nil { + t.Fatal(err) + } + if err := store.InsertSend(ctx, Send{AlertID: "a1", SinkID: "webhook", Status: "failed", CreatedAt: base}); err != nil { + t.Fatal(err) + } + + all, err := store.ListAlerts(ctx, AlertFilter{}) + if err != nil { + t.Fatalf("list: %v", err) + } + if len(all) != 3 || all[0].ID != "a1" || all[2].ID != "a3" { + t.Fatalf("unexpected order: %+v", all) + } + if !all[0].CreatedAt.Equal(base) { + t.Fatalf("created_at = %v, want %v", all[0].CreatedAt, base) + } + if len(all[0].Sends) != 2 || all[0].Sends[0].SinkID != "slack" || all[0].Sends[1].Status != "failed" { + t.Fatalf("unexpected sends: %+v", all[0].Sends) + } + if len(all[1].Sends) != 0 { + t.Fatalf("a2 should have no sends: %+v", all[1].Sends) + } + + byRule, _ := store.ListAlerts(ctx, AlertFilter{RuleID: "whale"}) + if len(byRule) != 2 { + t.Fatalf("rule filter: got %d", len(byRule)) + } + since, _ := store.ListAlerts(ctx, AlertFilter{Since: base.Add(30 * time.Minute)}) + if len(since) != 2 || since[0].ID != "a2" { + t.Fatalf("since filter: %+v", since) + } + limited, _ := store.ListAlerts(ctx, AlertFilter{Limit: 1}) + if len(limited) != 1 || limited[0].ID != "a3" { + t.Fatalf("limit should keep most recent: %+v", limited) + } +} From 5806d17ceda3e0b3205371af54b5bead37767576 Mon Sep 17 00:00:00 2001 From: Julian Blacher Date: Fri, 27 Nov 2026 13:15:12 -0300 Subject: [PATCH 2/2] feat(cli): implement state and export commands Both commands were stubs that printed TODO although the README documents them. - state: per-source cursor height, chain head, lag, confirmations, hash and last update; flags --format table|json, --offline, --db. Flags sources not started yet and cursors no longer in the config; an unreachable RPC is reported on its row. - export alerts|cursors: --format json|csv, -o file, and for alerts --rule, --since (duration or RFC3339) and --limit, including each alert's per-sink delivery status. --db reads the ledger without loading the config, and both commands refuse a missing database instead of creating an empty one. Co-Authored-By: Claude Opus 5.5 --- cmd/watch-tower/export.go | 232 +++++++++++++++++++++++++- cmd/watch-tower/state.go | 233 ++++++++++++++++++++++++++- cmd/watch-tower/state_export_test.go | 217 +++++++++++++++++++++++++ cmd/watch-tower/store_open.go | 43 +++++ 4 files changed, 717 insertions(+), 8 deletions(-) create mode 100644 cmd/watch-tower/state_export_test.go create mode 100644 cmd/watch-tower/store_open.go diff --git a/cmd/watch-tower/export.go b/cmd/watch-tower/export.go index 900aa6a..3d0cb89 100644 --- a/cmd/watch-tower/export.go +++ b/cmd/watch-tower/export.go @@ -1,17 +1,241 @@ package main import ( + "encoding/csv" + "encoding/json" "fmt" + "io" + "os" + "strconv" + "strings" + "time" + "github.com/devblac/watch-tower/internal/storage" "github.com/spf13/cobra" ) +var ( + flagExportFormat string + flagExportDB string + flagExportOut string + flagExportRule string + flagExportSince string + flagExportLimit int +) + +func init() { + exportCmd.PersistentFlags().StringVar(&flagExportFormat, "format", "json", "Output format: json|csv") + exportCmd.PersistentFlags().StringVar(&flagExportDB, "db", "", "Database path (skips loading the config)") + exportCmd.PersistentFlags().StringVarP(&flagExportOut, "output", "o", "", "Write to a file instead of stdout") + + exportAlertsCmd.Flags().StringVar(&flagExportRule, "rule", "", "Only alerts from this rule id") + exportAlertsCmd.Flags().StringVar(&flagExportSince, "since", "", "Only alerts newer than a duration (24h) or RFC3339 time") + exportAlertsCmd.Flags().IntVar(&flagExportLimit, "limit", 0, "Only the N most recent alerts") + + exportCmd.AddCommand(exportAlertsCmd, exportCursorsCmd) +} + var exportCmd = &cobra.Command{ Use: "export", - Short: "Export alerts or cursors (stub)", + Short: "Export alerts or cursors as JSON or CSV", + Example: ` watch-tower export alerts --format json + watch-tower export alerts --rule usdc_whale --since 24h --format csv -o alerts.csv + watch-tower export cursors --format csv`, +} + +var exportAlertsCmd = &cobra.Command{ + Use: "alerts", + Short: "Export recorded alerts with their per-sink delivery status", + Args: cobra.NoArgs, + RunE: func(cmd *cobra.Command, args []string) error { + if err := checkExportFormat(); err != nil { + return err + } + filter := storage.AlertFilter{RuleID: flagExportRule, Limit: flagExportLimit} + if flagExportSince != "" { + since, err := parseSince(flagExportSince, time.Now()) + if err != nil { + return err + } + filter.Since = since + } + return withExportStore(cmd, func(store *storage.Store, w io.Writer) error { + alerts, err := store.ListAlerts(cmd.Context(), filter) + if err != nil { + return err + } + if flagExportFormat == "csv" { + return writeAlertsCSV(w, alerts) + } + return writeAlertsJSON(w, alerts) + }) + }, +} + +var exportCursorsCmd = &cobra.Command{ + Use: "cursors", + Short: "Export the stored cursor of each source", + Args: cobra.NoArgs, RunE: func(cmd *cobra.Command, args []string) error { - // TODO: Export alerts/cursors as csv/json. - fmt.Fprintln(cmd.OutOrStdout(), "export: TODO export alerts|cursors to csv|json.") - return nil + if err := checkExportFormat(); err != nil { + return err + } + return withExportStore(cmd, func(store *storage.Store, w io.Writer) error { + cursors, err := store.ListCursors(cmd.Context()) + if err != nil { + return err + } + if flagExportFormat == "csv" { + return writeCursorsCSV(w, cursors) + } + return writeCursorsJSON(w, cursors) + }) }, } + +func checkExportFormat() error { + if flagExportFormat != "json" && flagExportFormat != "csv" { + return fmt.Errorf("unsupported format %q (want json or csv)", flagExportFormat) + } + return nil +} + +// withExportStore opens the ledger and the output destination for fn. +func withExportStore(cmd *cobra.Command, fn func(*storage.Store, io.Writer) error) error { + dbPath, _, err := resolveDBPath(flagExportDB) + if err != nil { + return err + } + store, err := openExistingStore(dbPath) + if err != nil { + return err + } + defer store.Close() + + if flagExportOut == "" { + return fn(store, cmd.OutOrStdout()) + } + f, err := os.Create(flagExportOut) + if err != nil { + return fmt.Errorf("create output: %w", err) + } + if err := fn(store, f); err != nil { + f.Close() + return err + } + return f.Close() +} + +// parseSince accepts a duration ("24h", "90m") or an RFC3339 timestamp. +func parseSince(s string, now time.Time) (time.Time, error) { + if d, err := time.ParseDuration(s); err == nil { + if d < 0 { + return time.Time{}, fmt.Errorf("--since must be a positive duration, got %s", s) + } + return now.Add(-d), nil + } + if t, err := time.Parse(time.RFC3339, s); err == nil { + return t, nil + } + return time.Time{}, fmt.Errorf("--since: want a duration like 24h or an RFC3339 time, got %q", s) +} + +type sendJSON struct { + SinkID string `json:"sink_id"` + Status string `json:"status"` + ResponseCode int `json:"response_code,omitempty"` + CreatedAt time.Time `json:"created_at"` +} + +type alertJSON struct { + ID string `json:"id"` + RuleID string `json:"rule_id"` + Fingerprint string `json:"fingerprint,omitempty"` + TxHash string `json:"txhash,omitempty"` + CreatedAt time.Time `json:"created_at"` + Payload json.RawMessage `json:"payload,omitempty"` + Sends []sendJSON `json:"sends"` +} + +func writeAlertsJSON(w io.Writer, alerts []storage.AlertWithSends) error { + out := make([]alertJSON, 0, len(alerts)) + for _, a := range alerts { + row := alertJSON{ + ID: a.ID, + RuleID: a.RuleID, + Fingerprint: a.Fingerprint, + TxHash: a.TxHash, + CreatedAt: a.CreatedAt.UTC(), + Sends: []sendJSON{}, + } + if a.PayloadJSON != "" { + if json.Valid([]byte(a.PayloadJSON)) { + row.Payload = json.RawMessage(a.PayloadJSON) + } else { + quoted, _ := json.Marshal(a.PayloadJSON) + row.Payload = quoted + } + } + for _, s := range a.Sends { + row.Sends = append(row.Sends, sendJSON{SinkID: s.SinkID, Status: s.Status, ResponseCode: s.ResponseCode, CreatedAt: s.CreatedAt.UTC()}) + } + out = append(out, row) + } + return encodeJSON(w, out) +} + +func writeAlertsCSV(w io.Writer, alerts []storage.AlertWithSends) error { + cw := csv.NewWriter(w) + if err := cw.Write([]string{"id", "rule_id", "fingerprint", "txhash", "created_at", "sends", "payload_json"}); err != nil { + return err + } + for _, a := range alerts { + sends := make([]string, 0, len(a.Sends)) + for _, s := range a.Sends { + sends = append(sends, s.SinkID+":"+s.Status) + } + if err := cw.Write([]string{ + a.ID, a.RuleID, a.Fingerprint, a.TxHash, + a.CreatedAt.UTC().Format(time.RFC3339), strings.Join(sends, ";"), a.PayloadJSON, + }); err != nil { + return err + } + } + cw.Flush() + return cw.Error() +} + +type cursorJSON struct { + SourceID string `json:"source_id"` + Height uint64 `json:"height"` + Hash string `json:"hash"` + UpdatedAt time.Time `json:"updated_at"` +} + +func writeCursorsJSON(w io.Writer, cursors []storage.Cursor) error { + out := make([]cursorJSON, 0, len(cursors)) + for _, c := range cursors { + out = append(out, cursorJSON{SourceID: c.SourceID, Height: c.Height, Hash: c.Hash, UpdatedAt: c.UpdatedAt.UTC()}) + } + return encodeJSON(w, out) +} + +func writeCursorsCSV(w io.Writer, cursors []storage.Cursor) error { + cw := csv.NewWriter(w) + if err := cw.Write([]string{"source_id", "height", "hash", "updated_at"}); err != nil { + return err + } + for _, c := range cursors { + if err := cw.Write([]string{c.SourceID, strconv.FormatUint(c.Height, 10), c.Hash, c.UpdatedAt.UTC().Format(time.RFC3339)}); err != nil { + return err + } + } + cw.Flush() + return cw.Error() +} + +func encodeJSON(w io.Writer, v any) error { + enc := json.NewEncoder(w) + enc.SetIndent("", " ") + return enc.Encode(v) +} diff --git a/cmd/watch-tower/state.go b/cmd/watch-tower/state.go index 9753863..f2c5699 100644 --- a/cmd/watch-tower/state.go +++ b/cmd/watch-tower/state.go @@ -1,17 +1,242 @@ package main import ( + "context" + "encoding/json" "fmt" + "io" + "sort" + "text/tabwriter" + "time" + "github.com/devblac/watch-tower/internal/config" + "github.com/devblac/watch-tower/internal/source/algorand" + "github.com/devblac/watch-tower/internal/source/evm" + "github.com/devblac/watch-tower/internal/storage" "github.com/spf13/cobra" ) +var ( + flagStateFormat string + flagStateOffline bool + flagStateDB string +) + +func init() { + stateCmd.Flags().StringVar(&flagStateFormat, "format", "table", "Output format: table|json") + stateCmd.Flags().BoolVar(&flagStateOffline, "offline", false, "Do not query RPCs for the chain head (no lag)") + stateCmd.Flags().StringVar(&flagStateDB, "db", "", "Database path (skips loading the config; implies --offline)") +} + var stateCmd = &cobra.Command{ Use: "state", - Short: "Show cursors and processing lag (stub)", + Short: "Show cursors and processing lag per source", + Long: `Show where each source's cursor is, and how far it trails the chain head. + +Lag is measured against the current head, so a lag equal to the configured +confirmations is normal: watch-tower only processes confirmed blocks.`, RunE: func(cmd *cobra.Command, args []string) error { - // TODO: Read cursor state from storage and present lag per source. - fmt.Fprintln(cmd.OutOrStdout(), "state: TODO display cursors and lag.") - return nil + if flagStateFormat != "table" && flagStateFormat != "json" { + return fmt.Errorf("unsupported format %q (want table or json)", flagStateFormat) + } + dbPath, cfg, err := resolveDBPath(flagStateDB) + if err != nil { + return err + } + store, err := openExistingStore(dbPath) + if err != nil { + return err + } + defer store.Close() + + var fetch headFetcher + if !flagStateOffline && cfg != nil { + fetch = rpcHead + } + rows, err := collectState(cmd.Context(), cfg, store, fetch) + if err != nil { + return err + } + if flagStateFormat == "json" { + return writeStateJSON(cmd.OutOrStdout(), rows) + } + return writeStateTable(cmd.OutOrStdout(), rows) }, } + +// headFetcher returns the current chain head height/round for a source. +type headFetcher func(ctx context.Context, src config.Source) (uint64, error) + +// sourceState is one row of `watch-tower state`. +type sourceState struct { + SourceID string `json:"source_id"` + Type string `json:"type,omitempty"` + Height *uint64 `json:"height"` + Hash string `json:"hash,omitempty"` + UpdatedAt *time.Time `json:"updated_at"` + Head *uint64 `json:"head"` + Lag *uint64 `json:"lag"` + Confirmations *uint64 `json:"confirmations,omitempty"` + Note string `json:"note,omitempty"` +} + +const headTimeout = 5 * time.Second + +// collectState merges configured sources with stored cursors. Sources come in +// config order, then cursors left over from sources no longer configured. +// A nil fetch skips head lookups. +func collectState(ctx context.Context, cfg *config.Config, store *storage.Store, fetch headFetcher) ([]sourceState, error) { + cursors, err := store.ListCursors(ctx) + if err != nil { + return nil, err + } + byID := make(map[string]storage.Cursor, len(cursors)) + for _, c := range cursors { + byID[c.SourceID] = c + } + + var rows []sourceState + seen := map[string]bool{} + if cfg != nil { + for _, src := range cfg.Sources { + seen[src.ID] = true + row := sourceState{SourceID: src.ID, Type: src.Type} + if conf, ok := cfg.Global.Confirmations[src.Type]; ok { + c := conf + row.Confirmations = &c + } + if c, ok := byID[src.ID]; ok { + fillCursor(&row, c) + } else { + row.Note = "not started" + } + if fetch != nil { + hctx, cancel := context.WithTimeout(ctx, headTimeout) + head, err := fetch(hctx, src) + cancel() + if err != nil { + row.Note = joinNote(row.Note, "head unavailable: "+err.Error()) + } else { + row.Head = &head + if row.Height != nil && head >= *row.Height { + lag := head - *row.Height + row.Lag = &lag + } + } + } + rows = append(rows, row) + } + } + + var orphans []storage.Cursor + for _, c := range cursors { + if !seen[c.SourceID] { + orphans = append(orphans, c) + } + } + sort.Slice(orphans, func(i, j int) bool { return orphans[i].SourceID < orphans[j].SourceID }) + for _, c := range orphans { + row := sourceState{SourceID: c.SourceID} + fillCursor(&row, c) + if cfg != nil { + row.Note = "not in config" + } + rows = append(rows, row) + } + return rows, nil +} + +func fillCursor(row *sourceState, c storage.Cursor) { + h := c.Height + row.Height = &h + row.Hash = c.Hash + if !c.UpdatedAt.IsZero() { + t := c.UpdatedAt.UTC() + row.UpdatedAt = &t + } +} + +func joinNote(a, b string) string { + if a == "" { + return b + } + return a + "; " + b +} + +// rpcHead asks the source's node for its latest height/round. +func rpcHead(ctx context.Context, src config.Source) (uint64, error) { + switch src.Type { + case "evm": + cli, err := evm.NewRPCClient(src.RPCURL) + if err != nil { + return 0, err + } + defer cli.Close() + hdr, err := cli.HeaderByNumber(ctx, nil) + if err != nil { + return 0, err + } + return hdr.Number.Uint64(), nil + case "algorand": + cli, err := algorand.NewAlgodClient(src.AlgodURL) + if err != nil { + return 0, err + } + st, err := cli.Status().Do(ctx) + if err != nil { + return 0, err + } + return st.LastRound, nil + default: + return 0, fmt.Errorf("unsupported source type %q", src.Type) + } +} + +func writeStateJSON(w io.Writer, rows []sourceState) error { + if rows == nil { + rows = []sourceState{} + } + enc := json.NewEncoder(w) + enc.SetIndent("", " ") + return enc.Encode(rows) +} + +func writeStateTable(w io.Writer, rows []sourceState) error { + if len(rows) == 0 { + _, err := fmt.Fprintln(w, "No sources configured and no cursors stored.") + return err + } + tw := tabwriter.NewWriter(w, 0, 0, 2, ' ', 0) + fmt.Fprintln(tw, "SOURCE\tTYPE\tHEIGHT\tHEAD\tLAG\tCONF\tHASH\tUPDATED\tNOTE") + for _, r := range rows { + updated := "-" + if r.UpdatedAt != nil { + updated = r.UpdatedAt.Format(time.RFC3339) + } + fmt.Fprintf(tw, "%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n", + r.SourceID, dash(r.Type), optUint(r.Height), optUint(r.Head), optUint(r.Lag), + optUint(r.Confirmations), dash(shortHash(r.Hash)), updated, r.Note) + } + return tw.Flush() +} + +func optUint(v *uint64) string { + if v == nil { + return "-" + } + return fmt.Sprintf("%d", *v) +} + +func dash(s string) string { + if s == "" { + return "-" + } + return s +} + +func shortHash(h string) string { + if len(h) <= 14 { + return h + } + return h[:8] + "…" + h[len(h)-4:] +} diff --git a/cmd/watch-tower/state_export_test.go b/cmd/watch-tower/state_export_test.go new file mode 100644 index 0000000..3aa13d9 --- /dev/null +++ b/cmd/watch-tower/state_export_test.go @@ -0,0 +1,217 @@ +package main + +import ( + "bytes" + "context" + "encoding/csv" + "encoding/json" + "errors" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/devblac/watch-tower/internal/config" + "github.com/devblac/watch-tower/internal/storage" +) + +func seedStore(t *testing.T) (string, *storage.Store) { + t.Helper() + path := filepath.Join(t.TempDir(), "wt.db") + store, err := storage.Open(path) + if err != nil { + t.Fatalf("open: %v", err) + } + t.Cleanup(func() { _ = store.Close() }) + ctx := context.Background() + must := func(err error) { + t.Helper() + if err != nil { + t.Fatal(err) + } + } + must(store.UpsertCursor(ctx, "evm_main", 1000, "0x1111111111111111111111111111111111111111111111111111111111111111")) + must(store.UpsertCursor(ctx, "old_source", 5, "OLD")) + at := time.Date(2026, 5, 6, 7, 8, 9, 0, time.UTC) + must(store.InsertAlert(ctx, storage.Alert{ID: "a1", RuleID: "whale", TxHash: "0xabc", PayloadJSON: `{"height":990}`, CreatedAt: at})) + must(store.InsertSend(ctx, storage.Send{AlertID: "a1", SinkID: "slack", Status: "sent", CreatedAt: at})) + must(store.InsertAlert(ctx, storage.Alert{ID: "a2", RuleID: "other", CreatedAt: at.Add(time.Minute)})) + return path, store +} + +func TestCollectState(t *testing.T) { + _, store := seedStore(t) + cfg := &config.Config{ + Global: config.GlobalConfig{Confirmations: map[string]uint64{"evm": 12}}, + Sources: []config.Source{ + {ID: "evm_main", Type: "evm"}, + {ID: "algo_main", Type: "algorand"}, + }, + } + fetch := func(_ context.Context, src config.Source) (uint64, error) { + if src.ID == "algo_main" { + return 0, errors.New("connection refused") + } + return 1012, nil + } + + rows, err := collectState(context.Background(), cfg, store, fetch) + if err != nil { + t.Fatalf("collect: %v", err) + } + if len(rows) != 3 { + t.Fatalf("expected 3 rows, got %+v", rows) + } + + evmRow, algoRow, orphan := rows[0], rows[1], rows[2] + if evmRow.SourceID != "evm_main" || *evmRow.Height != 1000 || *evmRow.Head != 1012 || *evmRow.Lag != 12 || *evmRow.Confirmations != 12 { + t.Fatalf("unexpected evm row: %+v", evmRow) + } + if algoRow.Height != nil || algoRow.Head != nil || !strings.Contains(algoRow.Note, "not started") || !strings.Contains(algoRow.Note, "connection refused") { + t.Fatalf("unexpected algo row: %+v", algoRow) + } + if orphan.SourceID != "old_source" || orphan.Note != "not in config" { + t.Fatalf("unexpected orphan row: %+v", orphan) + } + + var table bytes.Buffer + if err := writeStateTable(&table, rows); err != nil { + t.Fatal(err) + } + for _, want := range []string{"SOURCE", "evm_main", "1012", "0x111111…1111", "not in config"} { + if !strings.Contains(table.String(), want) { + t.Errorf("table missing %q:\n%s", want, table.String()) + } + } +} + +func TestCollectState_OfflineWithoutConfig(t *testing.T) { + _, store := seedStore(t) + rows, err := collectState(context.Background(), nil, store, nil) + if err != nil { + t.Fatalf("collect: %v", err) + } + if len(rows) != 2 || rows[0].SourceID != "evm_main" || rows[0].Head != nil || rows[0].Note != "" { + t.Fatalf("unexpected rows: %+v", rows) + } +} + +// runCLI executes the root command and restores flag globals afterwards. +func runCLI(t *testing.T, args ...string) (string, error) { + t.Helper() + t.Cleanup(func() { + flagStateFormat, flagStateOffline, flagStateDB = "table", false, "" + flagExportFormat, flagExportDB, flagExportOut = "json", "", "" + flagExportRule, flagExportSince, flagExportLimit = "", "", 0 + }) + var out bytes.Buffer + rootCmd.SilenceErrors, rootCmd.SilenceUsage = true, true + rootCmd.SetOut(&out) + rootCmd.SetArgs(args) + defer rootCmd.SetArgs(nil) + err := rootCmd.ExecuteContext(context.Background()) + return out.String(), err +} + +func TestExportAlertsJSON(t *testing.T) { + path, _ := seedStore(t) + out, err := runCLI(t, "export", "alerts", "--db", path) + if err != nil { + t.Fatalf("export: %v", err) + } + var got []alertJSON + if err := json.Unmarshal([]byte(out), &got); err != nil { + t.Fatalf("not JSON: %v\n%s", err, out) + } + var compact bytes.Buffer + if len(got) == 2 { + _ = json.Compact(&compact, got[0].Payload) + } + if len(got) != 2 || got[0].ID != "a1" || compact.String() != `{"height":990}` { + t.Fatalf("unexpected alerts: %+v", got) + } + if len(got[0].Sends) != 1 || got[0].Sends[0].Status != "sent" || len(got[1].Sends) != 0 { + t.Fatalf("unexpected sends: %+v", got) + } +} + +func TestExportAlertsCSVWithFiltersToFile(t *testing.T) { + path, _ := seedStore(t) + outFile := filepath.Join(t.TempDir(), "alerts.csv") + if _, err := runCLI(t, "export", "alerts", "--db", path, "--format", "csv", "--rule", "whale", "-o", outFile); err != nil { + t.Fatalf("export: %v", err) + } + f, err := os.Open(outFile) + if err != nil { + t.Fatal(err) + } + defer f.Close() + records, err := csv.NewReader(f).ReadAll() + if err != nil { + t.Fatalf("csv: %v", err) + } + if len(records) != 2 || records[1][0] != "a1" || records[1][5] != "slack:sent" || records[1][4] != "2026-05-06T07:08:09Z" { + t.Fatalf("unexpected csv: %v", records) + } +} + +func TestExportCursorsCSV(t *testing.T) { + path, _ := seedStore(t) + out, err := runCLI(t, "export", "cursors", "--db", path, "--format", "csv") + if err != nil { + t.Fatalf("export: %v", err) + } + records, err := csv.NewReader(strings.NewReader(out)).ReadAll() + if err != nil { + t.Fatalf("csv: %v", err) + } + if len(records) != 3 || records[1][0] != "evm_main" || records[1][1] != "1000" { + t.Fatalf("unexpected csv: %v", records) + } +} + +func TestStateJSONFromDB(t *testing.T) { + path, _ := seedStore(t) + out, err := runCLI(t, "state", "--db", path, "--format", "json") + if err != nil { + t.Fatalf("state: %v", err) + } + var rows []sourceState + if err := json.Unmarshal([]byte(out), &rows); err != nil { + t.Fatalf("not JSON: %v\n%s", err, out) + } + if len(rows) != 2 || *rows[0].Height != 1000 { + t.Fatalf("unexpected rows: %+v", rows) + } +} + +func TestReadCommandsRejectMissingDBAndBadFormat(t *testing.T) { + missing := filepath.Join(t.TempDir(), "nope.db") + if _, err := runCLI(t, "state", "--db", missing); err == nil || !strings.Contains(err.Error(), "no database") { + t.Fatalf("expected missing db error, got %v", err) + } + if _, err := os.Stat(missing); !os.IsNotExist(err) { + t.Fatalf("state must not create the database") + } + path, _ := seedStore(t) + if _, err := runCLI(t, "export", "alerts", "--db", path, "--format", "xml"); err == nil { + t.Fatalf("expected format error") + } +} + +func TestParseSince(t *testing.T) { + now := time.Date(2026, 1, 2, 0, 0, 0, 0, time.UTC) + if got, err := parseSince("24h", now); err != nil || !got.Equal(now.Add(-24*time.Hour)) { + t.Fatalf("duration: %v %v", got, err) + } + if got, err := parseSince("2025-12-31T00:00:00Z", now); err != nil || got.Day() != 31 { + t.Fatalf("rfc3339: %v %v", got, err) + } + if _, err := parseSince("yesterday", now); err == nil { + t.Fatalf("expected error") + } + if _, err := parseSince("-1h", now); err == nil { + t.Fatalf("expected error for negative duration") + } +} diff --git a/cmd/watch-tower/store_open.go b/cmd/watch-tower/store_open.go new file mode 100644 index 0000000..f31ec6a --- /dev/null +++ b/cmd/watch-tower/store_open.go @@ -0,0 +1,43 @@ +package main + +import ( + "errors" + "fmt" + "os" + + "github.com/devblac/watch-tower/internal/config" + "github.com/devblac/watch-tower/internal/storage" +) + +// defaultDBPath matches the documented default for global.db_path. +const defaultDBPath = "./watch_tower.db" + +// resolveDBPath picks the database for read-only commands: an explicit --db +// wins; otherwise the config's global.db_path (or the default) is used. +// The config is returned when it was loaded, nil otherwise. +func resolveDBPath(dbFlag string) (string, *config.Config, error) { + if dbFlag != "" { + return dbFlag, nil, nil + } + cfg, err := config.Load(cfgPath) + if err != nil { + return "", nil, fmt.Errorf("load config (or pass --db): %w", err) + } + path := cfg.Global.DBPath + if path == "" { + path = defaultDBPath + } + return path, cfg, nil +} + +// openExistingStore opens the ledger without creating it, so a typo in the +// path reports an error instead of showing an empty fresh database. +func openExistingStore(path string) (*storage.Store, error) { + if _, err := os.Stat(path); err != nil { + if errors.Is(err, os.ErrNotExist) { + return nil, fmt.Errorf("no database at %s (has `watch-tower run` been started?)", path) + } + return nil, fmt.Errorf("stat database: %w", err) + } + return storage.Open(path) +}