Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
232 changes: 228 additions & 4 deletions cmd/watch-tower/export.go
Original file line number Diff line number Diff line change
@@ -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)
}
Loading
Loading