diff --git a/.claude/rules/security.md b/.claude/rules/security.md index 9de25ce..98c123d 100644 --- a/.claude/rules/security.md +++ b/.claude/rules/security.md @@ -30,8 +30,9 @@ - Panic recovery prevents a single request from crashing the process. - Structured logs must never contain secrets or raw personal/financial data. - Auth: short-lived HS256 JWT access tokens (`JWT_SIGNING_SECRET`, at least 32 - characters) + two roles (operator, admin); `RequireRole` exists but is not - yet mounted on any route. + characters) + two roles (operator, admin); admin-only routes (e.g. + `PATCH /rules/{id}`) are enforced server-side with `auth.RequireRole` + next to the route they protect. ## Reporting diff --git a/.env.example b/.env.example index 1f019c8..5b9cf96 100644 --- a/.env.example +++ b/.env.example @@ -20,6 +20,9 @@ CORS_ALLOWED_ORIGINS=http://localhost:5173,http://localhost:8081 JWT_SIGNING_SECRET=dev_only_example_secret_change_me_32+chars JWT_ACCESS_TOKEN_TTL=15m +# How often the realtime relay polls the transactional outbox. +OUTBOX_POLL_INTERVAL=500ms + # Demo account passwords for `go run ./cmd/api seed-users` (operator@example.com, # admin@example.com). SAFE example dev values only. DEMO_OPERATOR_PASSWORD=operator_dev_password diff --git a/CLAUDE.md b/CLAUDE.md index a67dd4d..2b6fba9 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -31,8 +31,8 @@ product, and must never be represented as one. - **Real-time:** PostgreSQL transactional **outbox** + an in-process WebSocket hub. Do **not** add Kafka, Redis, NATS, or RabbitMQ. - **Auth:** short-lived (15m default) HS256 JWT access tokens via `POST - /login`; two roles (operator, admin). `RequireRole` exists but is not yet - mounted on any route. + /login`; two roles (operator, admin). Admin-only routes (rule changes) are + enforced server-side with `auth.RequireRole`. ## Contract-first diff --git a/README.md b/README.md index fc95d89..94511a8 100644 --- a/README.md +++ b/README.md @@ -16,13 +16,13 @@ near-real-time monitoring and alerting platform: migrations, structured JSON logging, validated configuration, graceful shutdown. - **Frontend** — React + TypeScript + Vite, Tailwind + shadcn-compatible components, TanStack Query, Recharts. -- **Real-time (planned)** — PostgreSQL transactional outbox + an in-process - WebSocket hub. No Kafka/Redis/NATS/RabbitMQ. +- **Real-time** — PostgreSQL transactional outbox relayed to an in-process + WebSocket hub at `/ws`. No Kafka/Redis/NATS/RabbitMQ. - **Contracts** — OpenAPI for REST, AsyncAPI for events, as the source of truth. This repository is the **bootstrap**: structure, skeletons, contracts, docs, local environment, and CI. Business features (transactions, alerts, rule -evaluation, live streaming) arrive in later issues. +evaluation) arrive in later issues. ## Repository layout diff --git a/apps/api/cmd/api/main.go b/apps/api/cmd/api/main.go index 9e08485..deff9b1 100644 --- a/apps/api/cmd/api/main.go +++ b/apps/api/cmd/api/main.go @@ -29,7 +29,10 @@ import ( "github.com/vianbas/finwatch/apps/api/internal/config" "github.com/vianbas/finwatch/apps/api/internal/platform/httpserver" "github.com/vianbas/finwatch/apps/api/internal/platform/postgres" - "github.com/vianbas/finwatch/apps/api/internal/rules" + "github.com/vianbas/finwatch/apps/api/internal/realtime" + realtimehttp "github.com/vianbas/finwatch/apps/api/internal/realtime/httpapi" + realtimestore "github.com/vianbas/finwatch/apps/api/internal/realtime/store" + rulehttp "github.com/vianbas/finwatch/apps/api/internal/rules/httpapi" rulestore "github.com/vianbas/finwatch/apps/api/internal/rules/store" "github.com/vianbas/finwatch/apps/api/internal/transactions" txhttp "github.com/vianbas/finwatch/apps/api/internal/transactions/httpapi" @@ -73,7 +76,7 @@ func main() { type appServices struct { transactions *transactions.Service alerts *alerts.Service - rules rules.Repository + rules *rulestore.Store } // buildServices wires the feature modules over a connection pool, registering @@ -254,16 +257,24 @@ func run() error { authSvc := auth.NewService(authstore.New(pool), issuer) authHandler := authhttp.NewHandler(authSvc, logger) + // Realtime: the relay moves committed outbox events into the hub, which + // fans them out to /ws clients. + hub := realtime.NewHub(logger) + relay := realtime.NewRelay(realtimestore.New(pool), hub, cfg.OutboxPollInterval, logger) + router := httpserver.NewRouter(httpserver.RouterDeps{ Logger: logger, Health: httpserver.NewHealthHandler(pool), PublicModules: []httpserver.RouteRegistrar{ httpserver.RegistrarFunc(authHandler.RegisterPublicRoutes), + // /ws authenticates its own handshake (token in a subprotocol). + realtimehttp.NewHandler(hub, verifier, cfg.CORSAllowedOrigins, logger), }, Modules: []httpserver.RouteRegistrar{ httpserver.RegistrarFunc(authHandler.RegisterProtectedRoutes), txhttp.NewHandler(svcs.transactions, logger), alerthttp.NewHandler(svcs.alerts, logger), + rulehttp.NewHandler(svcs.rules, logger), }, RequireAuth: auth.RequireAuth(verifier), CORSAllowedOrigins: cfg.CORSAllowedOrigins, @@ -282,6 +293,12 @@ func run() error { ctx, stop := signal.NotifyContext(ctx, os.Interrupt, syscall.SIGTERM) defer stop() + relayDone := make(chan struct{}) + go func() { + defer close(relayDone) + relay.Run(ctx) + }() + serverErr := make(chan error, 1) go func() { logger.Info("http server listening", slog.String("addr", srv.Addr)) @@ -304,6 +321,12 @@ func run() error { slog.Duration("timeout", cfg.ShutdownTimeout)) } + // Stop relaying, then tell WebSocket clients to reconnect elsewhere: + // Shutdown does not track upgraded (hijacked) connections. + stop() + <-relayDone + hub.Close() + shutdownCtx, cancel := context.WithTimeout(context.Background(), cfg.ShutdownTimeout) defer cancel() if err := srv.Shutdown(shutdownCtx); err != nil { diff --git a/apps/api/go.mod b/apps/api/go.mod index 29e1666..c627725 100644 --- a/apps/api/go.mod +++ b/apps/api/go.mod @@ -3,6 +3,7 @@ module github.com/vianbas/finwatch/apps/api go 1.26.0 require ( + github.com/coder/websocket v1.8.15 github.com/go-chi/chi/v5 v5.3.0 github.com/golang-jwt/jwt/v5 v5.3.1 github.com/jackc/pgx/v5 v5.10.0 diff --git a/apps/api/go.sum b/apps/api/go.sum index b0ed1e0..c1b774b 100644 --- a/apps/api/go.sum +++ b/apps/api/go.sum @@ -1,3 +1,5 @@ +github.com/coder/websocket v1.8.15 h1:6B2JPeOGlpff2Uz6vOEH1Vzpi0iUz20A+lPVhPHtNUA= +github.com/coder/websocket v1.8.15/go.mod h1:NX3SzP+inril6yawo5CQXx8+fk145lPDC6pumgx0mVg= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= diff --git a/apps/api/internal/config/config.go b/apps/api/internal/config/config.go index c2b634f..00e2d64 100644 --- a/apps/api/internal/config/config.go +++ b/apps/api/internal/config/config.go @@ -44,6 +44,10 @@ type Config struct { JWTSigningSecret string // JWTAccessTokenTTL bounds how long an issued access token remains valid. JWTAccessTokenTTL time.Duration + + // OutboxPollInterval is how often the realtime relay polls for unpublished + // outbox events. + OutboxPollInterval time.Duration } // Addr returns the host:port the HTTP server should bind to. @@ -102,6 +106,10 @@ func Load(getenv func(string) string) (*Config, error) { return nil, err } + if cfg.OutboxPollInterval, err = durationEnv(getenv, "OUTBOX_POLL_INTERVAL", 500*time.Millisecond); err != nil { + return nil, err + } + if err := cfg.Validate(); err != nil { return nil, err } @@ -141,6 +149,7 @@ func (c Config) Validate() error { "HTTP_IDLE_TIMEOUT": c.IdleTimeout, "HTTP_SHUTDOWN_TIMEOUT": c.ShutdownTimeout, "JWT_ACCESS_TOKEN_TTL": c.JWTAccessTokenTTL, + "OUTBOX_POLL_INTERVAL": c.OutboxPollInterval, } { if d <= 0 { return fmt.Errorf("config: %s must be a positive duration", name) diff --git a/apps/api/internal/config/config_test.go b/apps/api/internal/config/config_test.go index 0ff077d..da12270 100644 --- a/apps/api/internal/config/config_test.go +++ b/apps/api/internal/config/config_test.go @@ -78,6 +78,26 @@ func TestLoad_JWTDefaultsAndOverrides(t *testing.T) { } } +func TestLoad_OutboxPollIntervalDefaultAndOverride(t *testing.T) { + cfg, err := Load(envFunc(validEnv())) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if cfg.OutboxPollInterval != 500*time.Millisecond { + t.Errorf("OutboxPollInterval = %v, want 500ms", cfg.OutboxPollInterval) + } + + env := validEnv() + env["OUTBOX_POLL_INTERVAL"] = "2s" + cfg, err = Load(envFunc(env)) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if cfg.OutboxPollInterval != 2*time.Second { + t.Errorf("OutboxPollInterval = %v, want 2s", cfg.OutboxPollInterval) + } +} + func TestLoad_ValidationErrors(t *testing.T) { tests := []struct { name string @@ -95,6 +115,8 @@ func TestLoad_ValidationErrors(t *testing.T) { {"short jwt signing secret", func(m map[string]string) { m["JWT_SIGNING_SECRET"] = "too-short" }}, {"non-duration jwt ttl", func(m map[string]string) { m["JWT_ACCESS_TOKEN_TTL"] = "soon" }}, {"zero jwt ttl", func(m map[string]string) { m["JWT_ACCESS_TOKEN_TTL"] = "0s" }}, + {"non-duration outbox poll interval", func(m map[string]string) { m["OUTBOX_POLL_INTERVAL"] = "often" }}, + {"negative outbox poll interval", func(m map[string]string) { m["OUTBOX_POLL_INTERVAL"] = "-1s" }}, {"published example secret in staging", func(m map[string]string) { m["APP_ENV"] = "staging" m["JWT_SIGNING_SECRET"] = "dev_only_example_secret_change_me_32+chars" diff --git a/apps/api/internal/platform/httpserver/cors_test.go b/apps/api/internal/platform/httpserver/cors_test.go index a00592c..87ba3f4 100644 --- a/apps/api/internal/platform/httpserver/cors_test.go +++ b/apps/api/internal/platform/httpserver/cors_test.go @@ -35,8 +35,8 @@ func TestCORS_PreflightFromAllowedOrigin(t *testing.T) { if got := h.Get("Access-Control-Allow-Origin"); got != "http://localhost:5173" { t.Errorf("Access-Control-Allow-Origin = %q, want %q", got, "http://localhost:5173") } - if got := h.Get("Access-Control-Allow-Methods"); got != "GET, POST" { - t.Errorf("Access-Control-Allow-Methods = %q, want %q", got, "GET, POST") + if got := h.Get("Access-Control-Allow-Methods"); got != "GET, POST, PATCH" { + t.Errorf("Access-Control-Allow-Methods = %q, want %q", got, "GET, POST, PATCH") } if got := h.Get("Access-Control-Allow-Headers"); got != "Authorization, Content-Type" { t.Errorf("Access-Control-Allow-Headers = %q, want %q", got, "Authorization, Content-Type") diff --git a/apps/api/internal/platform/httpserver/middleware.go b/apps/api/internal/platform/httpserver/middleware.go index 42e3950..f2b0e85 100644 --- a/apps/api/internal/platform/httpserver/middleware.go +++ b/apps/api/internal/platform/httpserver/middleware.go @@ -85,6 +85,13 @@ func (s *statusRecorder) WriteHeader(code int) { s.ResponseWriter.WriteHeader(code) } +// Unwrap exposes the underlying writer to http.ResponseController, so +// handlers behind AccessLog can still hijack (WebSocket upgrades) and set +// connection deadlines. +func (s *statusRecorder) Unwrap() http.ResponseWriter { + return s.ResponseWriter +} + // CORS returns a middleware that answers cross-origin requests from an // explicit allow-list of origins, using exact string comparison (no // wildcards, no suffix matching). It exists to let the web app (served from a @@ -125,7 +132,7 @@ func CORS(allowedOrigins []string) func(http.Handler) http.Handler { if r.Method == http.MethodOptions && r.Header.Get("Access-Control-Request-Method") != "" { h := w.Header() h.Set("Access-Control-Allow-Origin", origin) - h.Set("Access-Control-Allow-Methods", "GET, POST") + h.Set("Access-Control-Allow-Methods", "GET, POST, PATCH") h.Set("Access-Control-Allow-Headers", "Authorization, Content-Type") h.Set("Access-Control-Max-Age", "600") w.WriteHeader(http.StatusNoContent) diff --git a/apps/api/internal/platform/postgres/db/outbox.sql.go b/apps/api/internal/platform/postgres/db/outbox.sql.go new file mode 100644 index 0000000..6e1d6ac --- /dev/null +++ b/apps/api/internal/platform/postgres/db/outbox.sql.go @@ -0,0 +1,65 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.31.1 +// source: outbox.sql + +package db + +import ( + "context" + + "github.com/jackc/pgx/v5/pgtype" +) + +const listUnpublishedOutboxEvents = `-- name: ListUnpublishedOutboxEvents :many +SELECT id, event_type, payload, occurred_at +FROM outbox_events +WHERE published_at IS NULL +ORDER BY occurred_at, id +LIMIT $1 +` + +type ListUnpublishedOutboxEventsRow struct { + ID int64 `json:"id"` + EventType string `json:"event_type"` + Payload []byte `json:"payload"` + OccurredAt pgtype.Timestamptz `json:"occurred_at"` +} + +// Oldest first, served by the outbox_events_unpublished_idx partial index. +func (q *Queries) ListUnpublishedOutboxEvents(ctx context.Context, limit int32) ([]ListUnpublishedOutboxEventsRow, error) { + rows, err := q.db.Query(ctx, listUnpublishedOutboxEvents, limit) + if err != nil { + return nil, err + } + defer rows.Close() + var items []ListUnpublishedOutboxEventsRow + for rows.Next() { + var i ListUnpublishedOutboxEventsRow + if err := rows.Scan( + &i.ID, + &i.EventType, + &i.Payload, + &i.OccurredAt, + ); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + +const markOutboxEventsPublished = `-- name: MarkOutboxEventsPublished :exec +UPDATE outbox_events +SET published_at = now() +WHERE id = ANY($1::bigint[]) + AND published_at IS NULL +` + +func (q *Queries) MarkOutboxEventsPublished(ctx context.Context, ids []int64) error { + _, err := q.db.Exec(ctx, markOutboxEventsPublished, ids) + return err +} diff --git a/apps/api/internal/platform/postgres/db/rules.sql.go b/apps/api/internal/platform/postgres/db/rules.sql.go index 5fe6fef..3105ef7 100644 --- a/apps/api/internal/platform/postgres/db/rules.sql.go +++ b/apps/api/internal/platform/postgres/db/rules.sql.go @@ -7,6 +7,8 @@ package db import ( "context" + + "github.com/jackc/pgx/v5/pgtype" ) const insertRuleIfAbsent = `-- name: InsertRuleIfAbsent :exec @@ -71,3 +73,66 @@ func (q *Queries) ListEnabledRules(ctx context.Context) ([]Rule, error) { } return items, nil } + +const listRules = `-- name: ListRules :many +SELECT id, name, field, operator, value, severity, enabled, created_at +FROM rules +ORDER BY created_at, id +` + +func (q *Queries) ListRules(ctx context.Context) ([]Rule, error) { + rows, err := q.db.Query(ctx, listRules) + if err != nil { + return nil, err + } + defer rows.Close() + var items []Rule + for rows.Next() { + var i Rule + if err := rows.Scan( + &i.ID, + &i.Name, + &i.Field, + &i.Operator, + &i.Value, + &i.Severity, + &i.Enabled, + &i.CreatedAt, + ); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + +const setRuleEnabled = `-- name: SetRuleEnabled :one +UPDATE rules +SET enabled = $1 +WHERE id = $2 +RETURNING id, name, field, operator, value, severity, enabled, created_at +` + +type SetRuleEnabledParams struct { + Enabled bool `json:"enabled"` + ID pgtype.UUID `json:"id"` +} + +func (q *Queries) SetRuleEnabled(ctx context.Context, arg SetRuleEnabledParams) (Rule, error) { + row := q.db.QueryRow(ctx, setRuleEnabled, arg.Enabled, arg.ID) + var i Rule + err := row.Scan( + &i.ID, + &i.Name, + &i.Field, + &i.Operator, + &i.Value, + &i.Severity, + &i.Enabled, + &i.CreatedAt, + ) + return i, err +} diff --git a/apps/api/internal/realtime/event.go b/apps/api/internal/realtime/event.go new file mode 100644 index 0000000..baceb2b --- /dev/null +++ b/apps/api/internal/realtime/event.go @@ -0,0 +1,43 @@ +// Package realtime relays committed outbox events to connected WebSocket +// clients through an in-process hub (ADR 0003). Delivery is at-least-once and +// only to clients connected at publish time; there is no replay. +package realtime + +import ( + "encoding/json" + "strconv" + "time" +) + +// envelopeVersion is the schema version of every event's data payload. +const envelopeVersion = 1 + +// Event is one outbox row ready to be relayed. +type Event struct { + // ID is the outbox row id; it is stable across redeliveries. + ID int64 + Type string + Payload json.RawMessage + OccurredAt time.Time +} + +// envelope is the wire form of an Event. It matches the Envelope schema in +// contracts/asyncapi.yaml. +type envelope struct { + ID string `json:"id"` + Type string `json:"type"` + Version int `json:"version"` + OccurredAt string `json:"occurredAt"` + Data json.RawMessage `json:"data"` +} + +// MarshalEnvelope renders e as the contract's common event envelope. +func MarshalEnvelope(e Event) ([]byte, error) { + return json.Marshal(envelope{ + ID: strconv.FormatInt(e.ID, 10), + Type: e.Type, + Version: envelopeVersion, + OccurredAt: e.OccurredAt.UTC().Format(time.RFC3339Nano), + Data: e.Payload, + }) +} diff --git a/apps/api/internal/realtime/httpapi/handler.go b/apps/api/internal/realtime/httpapi/handler.go new file mode 100644 index 0000000..cbe6b82 --- /dev/null +++ b/apps/api/internal/realtime/httpapi/handler.go @@ -0,0 +1,176 @@ +// Package httpapi exposes the realtime hub as the /ws WebSocket endpoint +// described in contracts/asyncapi.yaml. It authenticates the handshake, +// upgrades, and streams hub events to the client until either side ends it. +package httpapi + +import ( + "context" + "log/slog" + "net/http" + "net/url" + "strings" + "time" + + "github.com/coder/websocket" + "github.com/go-chi/chi/v5" + + "github.com/vianbas/finwatch/apps/api/internal/auth" + "github.com/vianbas/finwatch/apps/api/internal/platform/web" + "github.com/vianbas/finwatch/apps/api/internal/realtime" +) + +const ( + // subprotocol is the application protocol the server selects. + subprotocol = "finwatch.v1" + // bearerPrefix marks the subprotocol carrying the access token, since + // browsers cannot set an Authorization header on a WebSocket handshake. + bearerPrefix = "bearer." + + writeTimeout = 10 * time.Second + pingInterval = 30 * time.Second +) + +// TokenVerifier validates an access token. *auth.Verifier implements it. +type TokenVerifier interface { + Verify(token string) (auth.Claims, error) +} + +// Handler serves the /ws endpoint. +type Handler struct { + hub *realtime.Hub + verifier TokenVerifier + originPatterns []string + log *slog.Logger +} + +// NewHandler constructs a Handler. allowedOrigins are the browser origins +// (e.g. http://localhost:5173) permitted to open cross-origin connections; +// same-origin connections are always allowed. +func NewHandler(hub *realtime.Hub, verifier TokenVerifier, allowedOrigins []string, log *slog.Logger) *Handler { + patterns := make([]string, 0, len(allowedOrigins)) + for _, o := range allowedOrigins { + if u, err := url.Parse(o); err == nil && u.Host != "" { + patterns = append(patterns, u.Host) + } + } + return &Handler{hub: hub, verifier: verifier, originPatterns: patterns, log: log} +} + +// RegisterRoutes mounts /ws. It authenticates the handshake itself, so it must +// be mounted outside the bearer-header auth middleware. +func (h *Handler) RegisterRoutes(r chi.Router) { + r.Get("/ws", h.serve) +} + +func (h *Handler) serve(w http.ResponseWriter, r *http.Request) { + token, hasProtocol := parseSubprotocols(r) + if !hasProtocol { + web.WriteError(w, http.StatusBadRequest, "UNSUPPORTED_SUBPROTOCOL", "subprotocol "+subprotocol+" is required") + return + } + if token == "" { + w.Header().Set("WWW-Authenticate", "Bearer") + web.WriteError(w, http.StatusUnauthorized, "UNAUTHORIZED", "missing bearer token") + return + } + claims, err := h.verifier.Verify(token) + if err != nil { + w.Header().Set("WWW-Authenticate", "Bearer") + web.WriteError(w, http.StatusUnauthorized, "UNAUTHORIZED", "invalid or expired token") + return + } + + // The server's read/write timeouts are connection deadlines that survive + // the upgrade; clear them so the stream outlives them. Pings and per-write + // timeouts bound a dead peer instead. + rc := http.NewResponseController(w) + if err := rc.SetReadDeadline(time.Time{}); err != nil { + h.log.ErrorContext(r.Context(), "realtime: clear read deadline failed", slog.String("error", err.Error())) + web.WriteError(w, http.StatusInternalServerError, "INTERNAL", "failed to open event stream") + return + } + if err := rc.SetWriteDeadline(time.Time{}); err != nil { + h.log.ErrorContext(r.Context(), "realtime: clear write deadline failed", slog.String("error", err.Error())) + web.WriteError(w, http.StatusInternalServerError, "INTERNAL", "failed to open event stream") + return + } + + conn, err := websocket.Accept(w, r, &websocket.AcceptOptions{ + Subprotocols: []string{subprotocol}, + OriginPatterns: h.originPatterns, + }) + if err != nil { + // Accept has already written an error response (e.g. 403 for a + // disallowed origin). + h.log.InfoContext(r.Context(), "realtime: upgrade rejected", slog.String("error", err.Error())) + return + } + defer func() { _ = conn.CloseNow() }() + + h.stream(r.Context(), conn, claims.ExpiresAt) +} + +// stream relays hub events to conn until the client goes away, the hub drops +// the subscription, or the access token expires. +func (h *Handler) stream(ctx context.Context, conn *websocket.Conn, expiresAt time.Time) { + sub := h.hub.Subscribe() + defer sub.Close() + + // The stream is server-to-client only: CloseRead handles control frames + // and closes with 1008 if the client sends a data message. + ctx = conn.CloseRead(ctx) + + expiry := time.NewTimer(time.Until(expiresAt)) + defer expiry.Stop() + ping := time.NewTicker(pingInterval) + defer ping.Stop() + + for { + select { + case <-ctx.Done(): + return + case <-sub.Done(): + switch sub.Reason() { + case realtime.DropSlow: + _ = conn.Close(websocket.StatusTryAgainLater, "client fell behind") + case realtime.DropShutdown: + _ = conn.Close(websocket.StatusGoingAway, "server shutting down") + } + return + case <-expiry.C: + _ = conn.Close(websocket.StatusPolicyViolation, "token expired") + return + case <-ping.C: + pctx, cancel := context.WithTimeout(ctx, writeTimeout) + err := conn.Ping(pctx) + cancel() + if err != nil { + return + } + case msg := <-sub.Events(): + wctx, cancel := context.WithTimeout(ctx, writeTimeout) + err := conn.Write(wctx, websocket.MessageText, msg) + cancel() + if err != nil { + return + } + } + } +} + +// parseSubprotocols reads the offered subprotocols, reporting the bearer +// token (empty if absent) and whether finwatch.v1 was offered. +func parseSubprotocols(r *http.Request) (token string, hasProtocol bool) { + for _, header := range r.Header.Values("Sec-WebSocket-Protocol") { + for _, p := range strings.Split(header, ",") { + p = strings.TrimSpace(p) + switch { + case p == subprotocol: + hasProtocol = true + case strings.HasPrefix(p, bearerPrefix): + token = strings.TrimPrefix(p, bearerPrefix) + } + } + } + return token, hasProtocol +} diff --git a/apps/api/internal/realtime/httpapi/handler_test.go b/apps/api/internal/realtime/httpapi/handler_test.go new file mode 100644 index 0000000..b3d2642 --- /dev/null +++ b/apps/api/internal/realtime/httpapi/handler_test.go @@ -0,0 +1,279 @@ +package httpapi + +import ( + "context" + "encoding/json" + "errors" + "io" + "log/slog" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/coder/websocket" + "github.com/go-chi/chi/v5" + + "github.com/vianbas/finwatch/apps/api/internal/auth" + "github.com/vianbas/finwatch/apps/api/internal/platform/httpserver" + "github.com/vianbas/finwatch/apps/api/internal/realtime" +) + +const serverTimeout = 100 * time.Millisecond + +// fakeVerifier accepts "valid" (long-lived) and "short" (expires soon). +type fakeVerifier struct{} + +func (fakeVerifier) Verify(token string) (auth.Claims, error) { + switch token { + case "valid": + return auth.Claims{UserID: "u1", Role: auth.RoleOperator, ExpiresAt: time.Now().Add(time.Hour)}, nil + case "short": + return auth.Claims{UserID: "u1", Role: auth.RoleOperator, ExpiresAt: time.Now().Add(150 * time.Millisecond)}, nil + default: + return auth.Claims{}, errors.New("invalid token") + } +} + +// newServer serves the handler behind AccessLog (exercising Unwrap) on a +// server with deliberately short read/write timeouts, which the handler must +// clear for long-lived streams. +func newServer(t *testing.T) (*httptest.Server, *realtime.Hub) { + t.Helper() + log := slog.New(slog.NewTextHandler(io.Discard, nil)) + hub := realtime.NewHub(log) + h := NewHandler(hub, fakeVerifier{}, []string{"http://allowed.example"}, log) + + r := chi.NewRouter() + r.Use(httpserver.AccessLog(log)) + h.RegisterRoutes(r) + + srv := httptest.NewUnstartedServer(r) + srv.Config.ReadTimeout = serverTimeout + srv.Config.WriteTimeout = serverTimeout + srv.Start() + t.Cleanup(srv.Close) + return srv, hub +} + +func wsURL(srv *httptest.Server) string { + return "ws" + strings.TrimPrefix(srv.URL, "http") + "/ws" +} + +func dial(t *testing.T, srv *httptest.Server, protocols ...string) (*websocket.Conn, *http.Response, error) { + t.Helper() + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) + defer cancel() + conn, resp, err := websocket.Dial(ctx, wsURL(srv), &websocket.DialOptions{Subprotocols: protocols}) + if conn != nil { + t.Cleanup(func() { _ = conn.CloseNow() }) + } + return conn, resp, err +} + +func waitFor(t *testing.T, cond func() bool) { + t.Helper() + deadline := time.Now().Add(2 * time.Second) + for !cond() { + if time.Now().After(deadline) { + t.Fatal("condition not met in time") + } + time.Sleep(5 * time.Millisecond) + } +} + +func readEnvelope(t *testing.T, conn *websocket.Conn) map[string]any { + t.Helper() + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) + defer cancel() + typ, msg, err := conn.Read(ctx) + if err != nil { + t.Fatalf("read: %v", err) + } + if typ != websocket.MessageText { + t.Fatalf("message type = %v, want text", typ) + } + var env map[string]any + if err := json.Unmarshal(msg, &env); err != nil { + t.Fatalf("decode: %v", err) + } + return env +} + +func readCloseStatus(t *testing.T, conn *websocket.Conn) websocket.StatusCode { + t.Helper() + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) + defer cancel() + _, _, err := conn.Read(ctx) + return websocket.CloseStatus(err) +} + +func event(id int64) realtime.Event { + return realtime.Event{ + ID: id, + Type: "transaction.observed", + Payload: json.RawMessage(`{"amountMinor":1250}`), + OccurredAt: time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC), + } +} + +func TestServe_RejectsHandshake(t *testing.T) { + srv, hub := newServer(t) + tests := []struct { + name string + protocols []string + want int + }{ + {"no subprotocols", nil, http.StatusBadRequest}, + {"token without finwatch.v1", []string{"bearer.valid"}, http.StatusBadRequest}, + {"missing token", []string{"finwatch.v1"}, http.StatusUnauthorized}, + {"invalid token", []string{"finwatch.v1", "bearer.forged"}, http.StatusUnauthorized}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + _, resp, err := dial(t, srv, tt.protocols...) + if err == nil { + t.Fatal("dial succeeded, want rejection") + } + if resp == nil || resp.StatusCode != tt.want { + t.Fatalf("status = %v, want %d", resp, tt.want) + } + }) + } + if hub.Len() != 0 { + t.Errorf("hub has %d subscribers after rejected handshakes", hub.Len()) + } +} + +func TestServe_RejectsDisallowedOrigin(t *testing.T) { + srv, _ := newServer(t) + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) + defer cancel() + _, resp, err := websocket.Dial(ctx, wsURL(srv), &websocket.DialOptions{ + Subprotocols: []string{"finwatch.v1", "bearer.valid"}, + HTTPHeader: http.Header{"Origin": []string{"http://evil.example"}}, + }) + if err == nil || resp == nil || resp.StatusCode != http.StatusForbidden { + t.Fatalf("err=%v resp=%v, want 403", err, resp) + } +} + +func TestServe_StreamsEventsBeyondServerTimeouts(t *testing.T) { + srv, hub := newServer(t) + conn, _, err := dial(t, srv, "finwatch.v1", "bearer.valid") + if err != nil { + t.Fatalf("dial: %v", err) + } + if conn.Subprotocol() != "finwatch.v1" { + t.Errorf("subprotocol = %q, want finwatch.v1", conn.Subprotocol()) + } + waitFor(t, func() bool { return hub.Len() == 1 }) + + // Outlive the server's read/write timeouts before the first event. + time.Sleep(3 * serverTimeout) + hub.Publish(event(7)) + hub.Publish(event(7)) // a relay redelivery + + for range 2 { + env := readEnvelope(t, conn) + if env["id"] != "7" || env["type"] != "transaction.observed" || env["version"] != float64(1) { + t.Errorf("envelope = %v", env) + } + if env["occurredAt"] != "2026-01-02T03:04:05Z" { + t.Errorf("occurredAt = %v", env["occurredAt"]) + } + } +} + +func TestServe_AllowsListedOrigin(t *testing.T) { + srv, _ := newServer(t) + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) + defer cancel() + conn, _, err := websocket.Dial(ctx, wsURL(srv), &websocket.DialOptions{ + Subprotocols: []string{"finwatch.v1", "bearer.valid"}, + HTTPHeader: http.Header{"Origin": []string{"http://allowed.example"}}, + }) + if err != nil { + t.Fatalf("dial: %v", err) + } + _ = conn.CloseNow() +} + +func TestServe_ClientDisconnectUnsubscribes(t *testing.T) { + srv, hub := newServer(t) + conn, _, err := dial(t, srv, "finwatch.v1", "bearer.valid") + if err != nil { + t.Fatalf("dial: %v", err) + } + waitFor(t, func() bool { return hub.Len() == 1 }) + + _ = conn.Close(websocket.StatusNormalClosure, "bye") + + waitFor(t, func() bool { return hub.Len() == 0 }) +} + +func TestServe_HubShutdownClosesWithGoingAway(t *testing.T) { + srv, hub := newServer(t) + conn, _, err := dial(t, srv, "finwatch.v1", "bearer.valid") + if err != nil { + t.Fatalf("dial: %v", err) + } + waitFor(t, func() bool { return hub.Len() == 1 }) + + hub.Close() + + if got := readCloseStatus(t, conn); got != websocket.StatusGoingAway { + t.Errorf("close status = %v, want %v", got, websocket.StatusGoingAway) + } +} + +func TestServe_TokenExpiryClosesWithPolicyViolation(t *testing.T) { + srv, _ := newServer(t) + conn, _, err := dial(t, srv, "finwatch.v1", "bearer.short") + if err != nil { + t.Fatalf("dial: %v", err) + } + if got := readCloseStatus(t, conn); got != websocket.StatusPolicyViolation { + t.Errorf("close status = %v, want %v", got, websocket.StatusPolicyViolation) + } +} + +func TestServe_SlowClientClosesWithTryAgainLater(t *testing.T) { + srv, hub := newServer(t) + conn, _, err := dial(t, srv, "finwatch.v1", "bearer.valid") + if err != nil { + t.Fatalf("dial: %v", err) + } + waitFor(t, func() bool { return hub.Len() == 1 }) + + // The client does not read; flood until the hub drops it. + for i := int64(0); hub.Len() == 1; i++ { + hub.Publish(event(i)) + if i > 100_000 { + t.Fatal("hub never dropped the non-reading client") + } + } + + // Drain buffered events until the close frame arrives. + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + for { + _, _, err := conn.Read(ctx) + if err != nil { + if got := websocket.CloseStatus(err); got != websocket.StatusTryAgainLater { + t.Errorf("close status = %v (err %v), want %v", got, err, websocket.StatusTryAgainLater) + } + return + } + } +} + +func TestParseSubprotocols(t *testing.T) { + r := httptest.NewRequest(http.MethodGet, "/ws", nil) + r.Header.Add("Sec-WebSocket-Protocol", "finwatch.v1, bearer.a.b-c_d") + token, ok := parseSubprotocols(r) + if !ok || token != "a.b-c_d" { + t.Errorf("got (%q, %v), want (a.b-c_d, true)", token, ok) + } +} diff --git a/apps/api/internal/realtime/hub.go b/apps/api/internal/realtime/hub.go new file mode 100644 index 0000000..63c8164 --- /dev/null +++ b/apps/api/internal/realtime/hub.go @@ -0,0 +1,139 @@ +package realtime + +import ( + "log/slog" + "sync" +) + +// subscriberBuffer is how many encoded events a subscriber may lag behind +// before the hub drops it rather than block the relay. +const subscriberBuffer = 64 + +// DropReason says why the hub ended a subscription. +type DropReason int + +const ( + // DropNone means the subscription is still active or was closed by its + // owner. + DropNone DropReason = iota + // DropSlow means the subscriber's buffer was full when an event arrived. + DropSlow + // DropShutdown means the hub was closed. + DropShutdown +) + +// Hub fans encoded events out to subscribers. Publish never blocks: a +// subscriber that cannot keep up is dropped and expected to reconnect and +// refetch. +type Hub struct { + log *slog.Logger + + mu sync.Mutex + subs map[*Subscription]struct{} + closed bool +} + +// NewHub constructs an empty Hub. +func NewHub(log *slog.Logger) *Hub { + return &Hub{log: log, subs: make(map[*Subscription]struct{})} +} + +// Subscription is one subscriber's view of the hub. +type Subscription struct { + hub *Hub + events chan []byte + done chan struct{} + reason DropReason // written under hub.mu before done is closed +} + +// Events delivers encoded envelopes in publish order. +func (s *Subscription) Events() <-chan []byte { return s.events } + +// Done is closed when the subscription ends, by Close or by the hub. +func (s *Subscription) Done() <-chan struct{} { return s.done } + +// Reason reports why the hub ended the subscription. It is only meaningful +// once Done is closed. +func (s *Subscription) Reason() DropReason { + s.hub.mu.Lock() + defer s.hub.mu.Unlock() + return s.reason +} + +// Close unsubscribes. It is safe to call more than once and after the hub has +// dropped the subscription. +func (s *Subscription) Close() { + s.hub.mu.Lock() + defer s.hub.mu.Unlock() + s.hub.removeLocked(s, DropNone) +} + +// Subscribe registers a new subscriber. Subscribing to a closed hub returns a +// subscription that is already done. +func (h *Hub) Subscribe() *Subscription { + s := &Subscription{ + hub: h, + events: make(chan []byte, subscriberBuffer), + done: make(chan struct{}), + } + h.mu.Lock() + defer h.mu.Unlock() + if h.closed { + s.reason = DropShutdown + close(s.done) + return s + } + h.subs[s] = struct{}{} + return s +} + +// Publish encodes e once and offers it to every subscriber. +func (h *Hub) Publish(e Event) { + msg, err := MarshalEnvelope(e) + if err != nil { + // The payload came from a JSONB column, so this indicates a bug rather + // than bad input; skip the event instead of wedging the relay. + h.log.Error("realtime: encode event failed", + slog.Int64("event_id", e.ID), slog.String("error", err.Error())) + return + } + + h.mu.Lock() + defer h.mu.Unlock() + for s := range h.subs { + select { + case s.events <- msg: + default: + h.removeLocked(s, DropSlow) + h.log.Warn("realtime: dropped slow subscriber", slog.Int64("event_id", e.ID)) + } + } +} + +// Len reports the number of active subscribers. +func (h *Hub) Len() int { + h.mu.Lock() + defer h.mu.Unlock() + return len(h.subs) +} + +// Close ends every subscription with DropShutdown and rejects new ones. +func (h *Hub) Close() { + h.mu.Lock() + defer h.mu.Unlock() + h.closed = true + for s := range h.subs { + h.removeLocked(s, DropShutdown) + } +} + +// removeLocked ends s if it is still registered. The events channel is never +// closed, so a concurrent Publish can never send on a closed channel. +func (h *Hub) removeLocked(s *Subscription, reason DropReason) { + if _, ok := h.subs[s]; !ok { + return + } + delete(h.subs, s) + s.reason = reason + close(s.done) +} diff --git a/apps/api/internal/realtime/hub_test.go b/apps/api/internal/realtime/hub_test.go new file mode 100644 index 0000000..fc942b4 --- /dev/null +++ b/apps/api/internal/realtime/hub_test.go @@ -0,0 +1,135 @@ +package realtime + +import ( + "encoding/json" + "io" + "log/slog" + "testing" + "time" +) + +func discardLogger() *slog.Logger { + return slog.New(slog.NewTextHandler(io.Discard, nil)) +} + +func testEvent(id int64) Event { + return Event{ + ID: id, + Type: "alert.raised", + Payload: json.RawMessage(`{"alertId":"00000000-0000-0000-0000-000000000001"}`), + OccurredAt: time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC), + } +} + +func receive(t *testing.T, s *Subscription) envelope { + t.Helper() + select { + case msg := <-s.Events(): + var env envelope + if err := json.Unmarshal(msg, &env); err != nil { + t.Fatalf("decode envelope: %v", err) + } + return env + default: + t.Fatal("no event buffered") + return envelope{} + } +} + +func isDone(s *Subscription) bool { + select { + case <-s.Done(): + return true + default: + return false + } +} + +func TestMarshalEnvelope(t *testing.T) { + e := testEvent(42) + e.OccurredAt = time.Date(2026, 1, 2, 10, 4, 5, 0, time.FixedZone("UTC+7", 7*3600)) + got, err := MarshalEnvelope(e) + if err != nil { + t.Fatalf("MarshalEnvelope: %v", err) + } + want := `{"id":"42","type":"alert.raised","version":1,"occurredAt":"2026-01-02T03:04:05Z",` + + `"data":{"alertId":"00000000-0000-0000-0000-000000000001"}}` + if string(got) != want { + t.Errorf("envelope =\n%s\nwant\n%s", got, want) + } +} + +func TestHub_FansOutToEverySubscriber(t *testing.T) { + h := NewHub(discardLogger()) + a, b := h.Subscribe(), h.Subscribe() + + h.Publish(testEvent(1)) + + for _, s := range []*Subscription{a, b} { + if env := receive(t, s); env.ID != "1" || env.Type != "alert.raised" { + t.Errorf("got %+v", env) + } + } +} + +func TestHub_DropsSlowSubscriberWithoutBlocking(t *testing.T) { + h := NewHub(discardLogger()) + slow, fast := h.Subscribe(), h.Subscribe() + + for i := range subscriberBuffer { + h.Publish(testEvent(int64(i))) + receive(t, fast) + } + if isDone(slow) { + t.Fatal("slow subscriber dropped before its buffer was full") + } + + h.Publish(testEvent(999)) // must not block + + if !isDone(slow) || slow.Reason() != DropSlow { + t.Fatalf("slow subscriber: done=%v reason=%v, want done with DropSlow", isDone(slow), slow.Reason()) + } + if env := receive(t, fast); env.ID != "999" { + t.Errorf("fast subscriber got id %q, want 999", env.ID) + } + if h.Len() != 1 { + t.Errorf("Len = %d, want 1", h.Len()) + } +} + +func TestSubscription_CloseUnsubscribes(t *testing.T) { + h := NewHub(discardLogger()) + s := h.Subscribe() + + s.Close() + s.Close() // idempotent + + if !isDone(s) || s.Reason() != DropNone { + t.Fatalf("done=%v reason=%v, want done with DropNone", isDone(s), s.Reason()) + } + if h.Len() != 0 { + t.Errorf("Len = %d, want 0", h.Len()) + } + h.Publish(testEvent(1)) + if len(s.Events()) != 0 { + t.Error("closed subscription still received an event") + } +} + +func TestHub_CloseEndsSubscriptionsAndRejectsNewOnes(t *testing.T) { + h := NewHub(discardLogger()) + s := h.Subscribe() + + h.Close() + + if !isDone(s) || s.Reason() != DropShutdown { + t.Fatalf("done=%v reason=%v, want done with DropShutdown", isDone(s), s.Reason()) + } + late := h.Subscribe() + if !isDone(late) || late.Reason() != DropShutdown { + t.Errorf("subscription after Close: done=%v reason=%v", isDone(late), late.Reason()) + } + if h.Len() != 0 { + t.Errorf("Len = %d, want 0", h.Len()) + } +} diff --git a/apps/api/internal/realtime/relay.go b/apps/api/internal/realtime/relay.go new file mode 100644 index 0000000..455cacb --- /dev/null +++ b/apps/api/internal/realtime/relay.go @@ -0,0 +1,103 @@ +package realtime + +import ( + "context" + "fmt" + "log/slog" + "time" +) + +const ( + // relayBatchSize bounds how many outbox rows one fetch reads. + relayBatchSize = 100 + // maxRelayBackoff caps the wait between polls while the outbox is failing. + maxRelayBackoff = 30 * time.Second +) + +// Outbox is the relay's view of the outbox_events table. +type Outbox interface { + // ListUnpublished returns up to limit unpublished events, oldest first. + ListUnpublished(ctx context.Context, limit int) ([]Event, error) + // MarkPublished stamps published_at on the given event ids. + MarkPublished(ctx context.Context, ids []int64) error +} + +// Publisher receives relayed events. Publish must not block. +type Publisher interface { + Publish(e Event) +} + +// Relay polls the outbox and hands unpublished events to a Publisher, marking +// them published afterwards. An event is published before it is marked, so a +// failed mark leads to redelivery (at-least-once), never to loss. +// +// The relay assumes a single running instance, matching the single-process +// deployment in ADR 0003. +type Relay struct { + outbox Outbox + pub Publisher + interval time.Duration + log *slog.Logger +} + +// NewRelay constructs a Relay that polls every interval. +func NewRelay(outbox Outbox, pub Publisher, interval time.Duration, log *slog.Logger) *Relay { + return &Relay{outbox: outbox, pub: pub, interval: interval, log: log} +} + +// Run polls until ctx is cancelled. Consecutive failures back off +// exponentially up to maxRelayBackoff. +func (r *Relay) Run(ctx context.Context) { + wait := r.interval + timer := time.NewTimer(wait) + defer timer.Stop() + + for { + select { + case <-ctx.Done(): + return + case <-timer.C: + } + + if _, err := r.drain(ctx); err != nil { + if ctx.Err() != nil { + return + } + wait = min(wait*2, maxRelayBackoff) + r.log.Error("realtime: relay outbox failed", + slog.String("error", err.Error()), slog.Duration("retry_in", wait)) + } else { + wait = r.interval + } + timer.Reset(wait) + } +} + +// drain relays batches until the outbox has no more unpublished events, +// returning how many events were published. +func (r *Relay) drain(ctx context.Context) (int, error) { + total := 0 + for { + events, err := r.outbox.ListUnpublished(ctx, relayBatchSize) + if err != nil { + return total, fmt.Errorf("list unpublished: %w", err) + } + if len(events) == 0 { + return total, nil + } + + ids := make([]int64, len(events)) + for i, e := range events { + r.pub.Publish(e) + ids[i] = e.ID + } + if err := r.outbox.MarkPublished(ctx, ids); err != nil { + return total, fmt.Errorf("mark published: %w", err) + } + total += len(events) + + if len(events) < relayBatchSize { + return total, nil + } + } +} diff --git a/apps/api/internal/realtime/relay_test.go b/apps/api/internal/realtime/relay_test.go new file mode 100644 index 0000000..7e3f3a2 --- /dev/null +++ b/apps/api/internal/realtime/relay_test.go @@ -0,0 +1,182 @@ +package realtime + +import ( + "context" + "errors" + "sync" + "testing" + "time" +) + +// fakeOutbox is an in-memory Outbox. markErrs are returned by successive +// MarkPublished calls before it starts succeeding. +type fakeOutbox struct { + mu sync.Mutex + events []Event + published map[int64]bool + listErr error + markErrs []error +} + +func newFakeOutbox(n int) *fakeOutbox { + o := &fakeOutbox{published: make(map[int64]bool)} + for i := 1; i <= n; i++ { + o.events = append(o.events, testEvent(int64(i))) + } + return o +} + +func (o *fakeOutbox) ListUnpublished(_ context.Context, limit int) ([]Event, error) { + o.mu.Lock() + defer o.mu.Unlock() + if o.listErr != nil { + return nil, o.listErr + } + var out []Event + for _, e := range o.events { + if !o.published[e.ID] && len(out) < limit { + out = append(out, e) + } + } + return out, nil +} + +func (o *fakeOutbox) MarkPublished(_ context.Context, ids []int64) error { + o.mu.Lock() + defer o.mu.Unlock() + if len(o.markErrs) > 0 { + err := o.markErrs[0] + o.markErrs = o.markErrs[1:] + return err + } + for _, id := range ids { + o.published[id] = true + } + return nil +} + +func (o *fakeOutbox) unpublished() int { + o.mu.Lock() + defer o.mu.Unlock() + return len(o.events) - len(o.published) +} + +type recordingPublisher struct { + mu sync.Mutex + ids []int64 +} + +func (p *recordingPublisher) Publish(e Event) { + p.mu.Lock() + defer p.mu.Unlock() + p.ids = append(p.ids, e.ID) +} + +func (p *recordingPublisher) published() []int64 { + p.mu.Lock() + defer p.mu.Unlock() + return append([]int64(nil), p.ids...) +} + +func TestRelay_DrainPublishesInOrderAcrossBatches(t *testing.T) { + n := relayBatchSize*2 + 5 + outbox := newFakeOutbox(n) + pub := &recordingPublisher{} + r := NewRelay(outbox, pub, time.Millisecond, discardLogger()) + + got, err := r.drain(context.Background()) + if err != nil { + t.Fatalf("drain: %v", err) + } + if got != n { + t.Errorf("drained %d, want %d", got, n) + } + ids := pub.published() + if len(ids) != n { + t.Fatalf("published %d events, want %d", len(ids), n) + } + for i, id := range ids { + if id != int64(i+1) { + t.Fatalf("published[%d] = %d, want %d", i, id, i+1) + } + } + if outbox.unpublished() != 0 { + t.Errorf("%d events left unpublished", outbox.unpublished()) + } +} + +func TestRelay_FailedMarkRedeliversSameEvents(t *testing.T) { + outbox := newFakeOutbox(2) + outbox.markErrs = []error{errors.New("connection reset")} + pub := &recordingPublisher{} + r := NewRelay(outbox, pub, time.Millisecond, discardLogger()) + + if _, err := r.drain(context.Background()); err == nil { + t.Fatal("first drain: want mark error, got nil") + } + if outbox.unpublished() != 2 { + t.Fatalf("unpublished = %d after failed mark, want 2", outbox.unpublished()) + } + if _, err := r.drain(context.Background()); err != nil { + t.Fatalf("second drain: %v", err) + } + + // At-least-once: both events reach the hub twice with stable ids, and + // nothing is lost. + want := []int64{1, 2, 1, 2} + got := pub.published() + if len(got) != len(want) { + t.Fatalf("published %v, want %v", got, want) + } + for i := range want { + if got[i] != want[i] { + t.Fatalf("published %v, want %v", got, want) + } + } + if outbox.unpublished() != 0 { + t.Errorf("%d events left unpublished", outbox.unpublished()) + } +} + +func TestRelay_ListErrorPublishesNothing(t *testing.T) { + outbox := newFakeOutbox(3) + outbox.listErr = errors.New("database unavailable") + pub := &recordingPublisher{} + r := NewRelay(outbox, pub, time.Millisecond, discardLogger()) + + if _, err := r.drain(context.Background()); err == nil { + t.Fatal("want list error, got nil") + } + if len(pub.published()) != 0 { + t.Errorf("published %v, want none", pub.published()) + } +} + +func TestRelay_RunRecoversAndStopsOnCancel(t *testing.T) { + outbox := newFakeOutbox(3) + outbox.markErrs = []error{errors.New("transient")} + pub := &recordingPublisher{} + r := NewRelay(outbox, pub, time.Millisecond, discardLogger()) + + ctx, cancel := context.WithCancel(context.Background()) + done := make(chan struct{}) + go func() { + defer close(done) + r.Run(ctx) + }() + + deadline := time.Now().Add(2 * time.Second) + for outbox.unpublished() != 0 { + if time.Now().After(deadline) { + t.Fatal("relay did not publish all events after a transient failure") + } + time.Sleep(time.Millisecond) + } + + cancel() + select { + case <-done: + case <-time.After(2 * time.Second): + t.Fatal("Run did not return after cancel") + } +} diff --git a/apps/api/internal/realtime/store/store.go b/apps/api/internal/realtime/store/store.go new file mode 100644 index 0000000..882ef20 --- /dev/null +++ b/apps/api/internal/realtime/store/store.go @@ -0,0 +1,48 @@ +// Package store implements the realtime relay's Outbox over PostgreSQL. +package store + +import ( + "context" + "fmt" + + "github.com/jackc/pgx/v5/pgxpool" + + "github.com/vianbas/finwatch/apps/api/internal/platform/postgres/db" + "github.com/vianbas/finwatch/apps/api/internal/realtime" +) + +// Store reads and marks rows in outbox_events. +type Store struct { + q *db.Queries +} + +// New constructs a Store over the given pool. +func New(pool *pgxpool.Pool) *Store { + return &Store{q: db.New(pool)} +} + +// ListUnpublished implements realtime.Outbox. +func (s *Store) ListUnpublished(ctx context.Context, limit int) ([]realtime.Event, error) { + rows, err := s.q.ListUnpublishedOutboxEvents(ctx, int32(limit)) + if err != nil { + return nil, fmt.Errorf("store: list unpublished outbox events: %w", err) + } + events := make([]realtime.Event, len(rows)) + for i, row := range rows { + events[i] = realtime.Event{ + ID: row.ID, + Type: row.EventType, + Payload: row.Payload, + OccurredAt: row.OccurredAt.Time.UTC(), + } + } + return events, nil +} + +// MarkPublished implements realtime.Outbox. +func (s *Store) MarkPublished(ctx context.Context, ids []int64) error { + if err := s.q.MarkOutboxEventsPublished(ctx, ids); err != nil { + return fmt.Errorf("store: mark outbox events published: %w", err) + } + return nil +} diff --git a/apps/api/internal/realtime/store/store_integration_test.go b/apps/api/internal/realtime/store/store_integration_test.go new file mode 100644 index 0000000..ea480d1 --- /dev/null +++ b/apps/api/internal/realtime/store/store_integration_test.go @@ -0,0 +1,139 @@ +package store + +import ( + "context" + "os" + "path/filepath" + "sort" + "strings" + "testing" + "time" + + "github.com/jackc/pgx/v5/pgxpool" +) + +// These tests exercise real PostgreSQL behaviour. They run only when +// FINWATCH_TEST_DATABASE_URL points at a disposable database, e.g.: +// +// make dev # starts Postgres on localhost:5432 +// FINWATCH_TEST_DATABASE_URL='postgres://finwatch:finwatch_dev_password@localhost:5432/finwatch?sslmode=disable' \ +// go test ./internal/realtime/store/... +// +// Without the env var they skip, so `make verify` stays green without a DB. + +func newTestPool(t *testing.T) *pgxpool.Pool { + t.Helper() + url := os.Getenv("FINWATCH_TEST_DATABASE_URL") + if url == "" { + t.Skip("set FINWATCH_TEST_DATABASE_URL to run store integration tests") + } + pool, err := pgxpool.New(context.Background(), url) + if err != nil { + t.Fatalf("connect: %v", err) + } + t.Cleanup(pool.Close) + resetSchema(t, pool) + return pool +} + +func resetSchema(t *testing.T, pool *pgxpool.Pool) { + t.Helper() + ctx := context.Background() + if _, err := pool.Exec(ctx, `DROP SCHEMA public CASCADE; CREATE SCHEMA public`); err != nil { + t.Fatalf("reset schema: %v", err) + } + dir := filepath.Join("..", "..", "..", "migrations") + entries, err := os.ReadDir(dir) + if err != nil { + t.Fatalf("read migrations dir: %v", err) + } + var ups []string + for _, e := range entries { + if strings.HasSuffix(e.Name(), ".up.sql") { + ups = append(ups, e.Name()) + } + } + sort.Strings(ups) + for _, name := range ups { + sql, err := os.ReadFile(filepath.Join(dir, name)) + if err != nil { + t.Fatalf("read %s: %v", name, err) + } + if _, err := pool.Exec(ctx, string(sql)); err != nil { + t.Fatalf("apply %s: %v", name, err) + } + } +} + +func insertEvent(t *testing.T, pool *pgxpool.Pool, eventType, payload string, occurredAt time.Time) int64 { + t.Helper() + var id int64 + err := pool.QueryRow(context.Background(), ` + INSERT INTO outbox_events (aggregate, event_type, payload, occurred_at) + VALUES ('test', $1, $2, $3) + RETURNING id + `, eventType, payload, occurredAt).Scan(&id) + if err != nil { + t.Fatalf("insert outbox event: %v", err) + } + return id +} + +func TestStore_ListUnpublishedOldestFirstAndMarkPublished(t *testing.T) { + pool := newTestPool(t) + ctx := context.Background() + s := New(pool) + + base := time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC) + later := insertEvent(t, pool, "alert.raised", `{"n":2}`, base.Add(time.Minute)) + earlier := insertEvent(t, pool, "transaction.observed", `{"n":1}`, base) + + events, err := s.ListUnpublished(ctx, 10) + if err != nil { + t.Fatalf("ListUnpublished: %v", err) + } + if len(events) != 2 || events[0].ID != earlier || events[1].ID != later { + t.Fatalf("events = %+v, want ids [%d %d]", events, earlier, later) + } + e := events[0] + if e.Type != "transaction.observed" || string(e.Payload) != `{"n": 1}` || !e.OccurredAt.Equal(base) { + t.Errorf("event = {Type:%s Payload:%s OccurredAt:%s}", e.Type, e.Payload, e.OccurredAt) + } + if e.OccurredAt.Location() != time.UTC { + t.Errorf("OccurredAt location = %v, want UTC", e.OccurredAt.Location()) + } + + limited, err := s.ListUnpublished(ctx, 1) + if err != nil || len(limited) != 1 || limited[0].ID != earlier { + t.Fatalf("limit 1: events=%+v err=%v", limited, err) + } + + if err := s.MarkPublished(ctx, []int64{earlier}); err != nil { + t.Fatalf("MarkPublished: %v", err) + } + events, err = s.ListUnpublished(ctx, 10) + if err != nil || len(events) != 1 || events[0].ID != later { + t.Fatalf("after mark: events=%+v err=%v, want only %d", events, err, later) + } + + // Re-marking (a redelivery after a lost acknowledgement) keeps the + // original published_at. + var first time.Time + if err := pool.QueryRow(ctx, `SELECT published_at FROM outbox_events WHERE id = $1`, earlier).Scan(&first); err != nil { + t.Fatalf("read published_at: %v", err) + } + if err := s.MarkPublished(ctx, []int64{earlier, later}); err != nil { + t.Fatalf("MarkPublished again: %v", err) + } + var again time.Time + if err := pool.QueryRow(ctx, `SELECT published_at FROM outbox_events WHERE id = $1`, earlier).Scan(&again); err != nil { + t.Fatalf("read published_at: %v", err) + } + if !again.Equal(first) { + t.Errorf("published_at changed on re-mark: %v -> %v", first, again) + } + events, err = s.ListUnpublished(ctx, 10) + if err != nil || len(events) != 0 { + t.Fatalf("after marking all: events=%+v err=%v", events, err) + } +} diff --git a/apps/api/internal/rules/httpapi/handler.go b/apps/api/internal/rules/httpapi/handler.go new file mode 100644 index 0000000..f3e2857 --- /dev/null +++ b/apps/api/internal/rules/httpapi/handler.go @@ -0,0 +1,138 @@ +// Package httpapi exposes rule management over HTTP. Listing is open to any +// authenticated role; changing a rule requires the admin role, enforced here +// with auth.RequireRole so the check sits next to the route it protects. +package httpapi + +import ( + "context" + "encoding/json" + "errors" + "io" + "log/slog" + "net/http" + "time" + + "github.com/go-chi/chi/v5" + + "github.com/vianbas/finwatch/apps/api/internal/auth" + "github.com/vianbas/finwatch/apps/api/internal/platform/web" + "github.com/vianbas/finwatch/apps/api/internal/rules" +) + +// maxUpdateBodyBytes bounds the PATCH body; a valid one is ~20 bytes. +const maxUpdateBodyBytes = 1 << 10 + +// Store is the rule persistence the handler needs. +type Store interface { + List(ctx context.Context) ([]rules.Rule, error) + SetEnabled(ctx context.Context, id string, enabled bool) (rules.Rule, error) +} + +// Handler serves the rules HTTP endpoints. +type Handler struct { + store Store + log *slog.Logger +} + +// NewHandler constructs a Handler. +func NewHandler(store Store, log *slog.Logger) *Handler { + return &Handler{store: store, log: log} +} + +// RegisterRoutes mounts the rules routes. They must run behind +// auth.RequireAuth, which RequireRole relies on for the caller's claims. +func (h *Handler) RegisterRoutes(r chi.Router) { + r.Get("/rules", h.list) + r.With(auth.RequireRole(auth.RoleAdmin)).Patch("/rules/{id}", h.update) +} + +func (h *Handler) list(w http.ResponseWriter, r *http.Request) { + rs, err := h.store.List(r.Context()) + if err != nil { + h.log.ErrorContext(r.Context(), "list rules failed", slog.String("error", err.Error())) + web.WriteError(w, http.StatusInternalServerError, "INTERNAL", "failed to list rules") + return + } + items := make([]ruleDTO, len(rs)) + for i, rule := range rs { + items[i] = toDTO(rule) + } + web.WriteJSON(w, http.StatusOK, ruleListDTO{Items: items}) +} + +func (h *Handler) update(w http.ResponseWriter, r *http.Request) { + enabled, ok := decodeUpdate(w, r) + if !ok { + web.WriteError(w, http.StatusBadRequest, "INVALID_BODY", `body must be {"enabled": true|false}`) + return + } + + id := chi.URLParam(r, "id") + rule, err := h.store.SetEnabled(r.Context(), id, enabled) + if errors.Is(err, rules.ErrNotFound) { + web.WriteError(w, http.StatusNotFound, "NOT_FOUND", "rule not found") + return + } + if err != nil { + h.log.ErrorContext(r.Context(), "update rule failed", slog.String("error", err.Error())) + web.WriteError(w, http.StatusInternalServerError, "INTERNAL", "failed to update rule") + return + } + + // Who changed which rule, for traceability. The user id is an opaque + // synthetic identifier; emails and tokens are never logged. + claims, _ := auth.ClaimsFromContext(r.Context()) + h.log.InfoContext(r.Context(), "rule updated", + slog.String("rule_id", rule.ID), + slog.Bool("enabled", rule.Enabled), + slog.String("user_id", claims.UserID), + ) + web.WriteJSON(w, http.StatusOK, toDTO(rule)) +} + +// decodeUpdate strictly parses {"enabled": bool}: bounded size, no unknown +// fields, the field required, and nothing after the object. +func decodeUpdate(w http.ResponseWriter, r *http.Request) (bool, bool) { + r.Body = http.MaxBytesReader(w, r.Body, maxUpdateBodyBytes) + dec := json.NewDecoder(r.Body) + dec.DisallowUnknownFields() + + var body struct { + Enabled *bool `json:"enabled"` + } + if err := dec.Decode(&body); err != nil || body.Enabled == nil { + return false, false + } + if _, err := dec.Token(); !errors.Is(err, io.EOF) { + return false, false + } + return *body.Enabled, true +} + +type ruleDTO struct { + ID string `json:"id"` + Name string `json:"name"` + Field string `json:"field"` + Operator string `json:"operator"` + Value string `json:"value"` + Severity string `json:"severity"` + Enabled bool `json:"enabled"` + CreatedAt string `json:"createdAt"` +} + +type ruleListDTO struct { + Items []ruleDTO `json:"items"` +} + +func toDTO(r rules.Rule) ruleDTO { + return ruleDTO{ + ID: r.ID, + Name: r.Name, + Field: string(r.Field), + Operator: string(r.Operator), + Value: r.Value, + Severity: r.Severity, + Enabled: r.Enabled, + CreatedAt: r.CreatedAt.UTC().Format(time.RFC3339Nano), + } +} diff --git a/apps/api/internal/rules/httpapi/handler_test.go b/apps/api/internal/rules/httpapi/handler_test.go new file mode 100644 index 0000000..2009c4c --- /dev/null +++ b/apps/api/internal/rules/httpapi/handler_test.go @@ -0,0 +1,236 @@ +package httpapi + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "log/slog" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/vianbas/finwatch/apps/api/internal/auth" + "github.com/vianbas/finwatch/apps/api/internal/platform/httpserver" + "github.com/vianbas/finwatch/apps/api/internal/rules" +) + +const ( + testSecret = "test-only-signing-secret-at-least-32-chars" + ruleID = "11111111-1111-1111-1111-111111111111" +) + +type fakeStore struct { + rules []rules.Rule + setCalls int + lastID string + lastOn bool + setErr error + listErr error +} + +func (f *fakeStore) List(context.Context) ([]rules.Rule, error) { + return f.rules, f.listErr +} + +func (f *fakeStore) SetEnabled(_ context.Context, id string, enabled bool) (rules.Rule, error) { + f.setCalls++ + f.lastID, f.lastOn = id, enabled + if f.setErr != nil { + return rules.Rule{}, f.setErr + } + r := f.rules[0] + r.Enabled = enabled + return r, nil +} + +func newFakeStore() *fakeStore { + return &fakeStore{rules: []rules.Rule{{ + ID: ruleID, Name: "high-value-debit", Field: rules.FieldAmountMinor, Operator: rules.OpGTE, + Value: "500000", Severity: "high", Enabled: true, + CreatedAt: time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC), + }}} +} + +// newRouter mounts the handler exactly as cmd/api does: as a protected module +// behind the real RequireAuth middleware. +func newRouter(t *testing.T, store Store) (http.Handler, *bytes.Buffer) { + t.Helper() + var logs bytes.Buffer + log := slog.New(slog.NewJSONHandler(&logs, nil)) + return httpserver.NewRouter(httpserver.RouterDeps{ + Logger: log, + Health: httpserver.NewHealthHandler(nil), + Modules: []httpserver.RouteRegistrar{NewHandler(store, log)}, + RequireAuth: auth.RequireAuth(auth.NewVerifier([]byte(testSecret))), + }), &logs +} + +func token(t *testing.T, secret string, role auth.Role) string { + t.Helper() + tok, err := auth.NewIssuer([]byte(secret), time.Minute).Issue("user-"+string(role), string(role)+"@example.com", role) + if err != nil { + t.Fatalf("issue token: %v", err) + } + return tok +} + +func do(t *testing.T, h http.Handler, method, path, bearer, body string) *httptest.ResponseRecorder { + t.Helper() + req := httptest.NewRequest(method, path, strings.NewReader(body)) + if bearer != "" { + req.Header.Set("Authorization", "Bearer "+bearer) + } + rec := httptest.NewRecorder() + h.ServeHTTP(rec, req) + return rec +} + +func errorCode(t *testing.T, rec *httptest.ResponseRecorder) string { + t.Helper() + var env struct { + Error struct{ Code string } `json:"error"` + } + if err := json.Unmarshal(rec.Body.Bytes(), &env); err != nil { + t.Fatalf("decode error envelope %q: %v", rec.Body.String(), err) + } + return env.Error.Code +} + +func TestList_AnyAuthenticatedRole(t *testing.T) { + for _, role := range []auth.Role{auth.RoleOperator, auth.RoleAdmin} { + t.Run(string(role), func(t *testing.T) { + h, _ := newRouter(t, newFakeStore()) + rec := do(t, h, http.MethodGet, "/rules", token(t, testSecret, role), "") + if rec.Code != http.StatusOK { + t.Fatalf("status = %d, body %s", rec.Code, rec.Body) + } + want := `{"items":[{"id":"` + ruleID + `","name":"high-value-debit","field":"amount_minor",` + + `"operator":"gte","value":"500000","severity":"high","enabled":true,"createdAt":"2026-01-02T03:04:05Z"}]}` + if got := strings.TrimSpace(rec.Body.String()); got != want { + t.Errorf("body =\n%s\nwant\n%s", got, want) + } + }) + } +} + +func TestUpdate_RoleEnforcement(t *testing.T) { + tests := []struct { + name string + bearer func(t *testing.T) string + wantStatus int + wantCode string + wantCalls int + }{ + {"admin may update", func(t *testing.T) string { return token(t, testSecret, auth.RoleAdmin) }, http.StatusOK, "", 1}, + {"operator is forbidden", func(t *testing.T) string { return token(t, testSecret, auth.RoleOperator) }, http.StatusForbidden, "FORBIDDEN", 0}, + {"no token", func(*testing.T) string { return "" }, http.StatusUnauthorized, "UNAUTHORIZED", 0}, + {"admin claim with forged signature", func(t *testing.T) string { + return token(t, "another-secret-that-is-also-32-chars-long", auth.RoleAdmin) + }, http.StatusUnauthorized, "UNAUTHORIZED", 0}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + store := newFakeStore() + h, _ := newRouter(t, store) + rec := do(t, h, http.MethodPatch, "/rules/"+ruleID, tt.bearer(t), `{"enabled":false}`) + if rec.Code != tt.wantStatus { + t.Fatalf("status = %d, want %d (body %s)", rec.Code, tt.wantStatus, rec.Body) + } + if tt.wantCode != "" && errorCode(t, rec) != tt.wantCode { + t.Errorf("code = %q, want %q", errorCode(t, rec), tt.wantCode) + } + if store.setCalls != tt.wantCalls { + t.Errorf("SetEnabled called %d times, want %d", store.setCalls, tt.wantCalls) + } + }) + } +} + +func TestUpdate_AdminSuccess(t *testing.T) { + store := newFakeStore() + h, logs := newRouter(t, store) + + rec := do(t, h, http.MethodPatch, "/rules/"+ruleID, token(t, testSecret, auth.RoleAdmin), `{"enabled": false}`) + + if rec.Code != http.StatusOK { + t.Fatalf("status = %d, body %s", rec.Code, rec.Body) + } + if store.lastID != ruleID || store.lastOn { + t.Errorf("SetEnabled(%q, %v), want (%q, false)", store.lastID, store.lastOn, ruleID) + } + var got ruleDTO + if err := json.Unmarshal(rec.Body.Bytes(), &got); err != nil || got.Enabled || got.ID != ruleID { + t.Errorf("response = %+v (err %v), want rule %s disabled", got, err, ruleID) + } + line := logs.String() + for _, want := range []string{`"msg":"rule updated"`, `"rule_id":"` + ruleID + `"`, `"enabled":false`, `"user_id":"user-admin"`} { + if !strings.Contains(line, want) { + t.Errorf("log missing %s:\n%s", want, line) + } + } + if strings.Contains(line, "@example.com") || strings.Contains(line, "Bearer") { + t.Errorf("log leaks email or token:\n%s", line) + } +} + +func TestUpdate_RejectsInvalidBodies(t *testing.T) { + bodies := map[string]string{ + "empty": ``, + "malformed": `{"enabled":`, + "missing field": `{}`, + "null": `{"enabled":null}`, + "not a bool": `{"enabled":"false"}`, + "unknown field": `{"enabled":true,"severity":"low"}`, + "trailing data": `{"enabled":true}{"enabled":false}`, + "oversized": `{"enabled":true,"pad":"` + strings.Repeat("x", maxUpdateBodyBytes) + `"}`, + } + for name, body := range bodies { + t.Run(name, func(t *testing.T) { + store := newFakeStore() + h, _ := newRouter(t, store) + rec := do(t, h, http.MethodPatch, "/rules/"+ruleID, token(t, testSecret, auth.RoleAdmin), body) + if rec.Code != http.StatusBadRequest || errorCode(t, rec) != "INVALID_BODY" { + t.Fatalf("status = %d body %s, want 400 INVALID_BODY", rec.Code, rec.Body) + } + if store.setCalls != 0 { + t.Errorf("SetEnabled called on invalid body") + } + }) + } +} + +func TestUpdate_StoreErrors(t *testing.T) { + tests := []struct { + name string + err error + wantStatus int + wantCode string + }{ + {"not found", rules.ErrNotFound, http.StatusNotFound, "NOT_FOUND"}, + {"database failure", errors.New("connection refused"), http.StatusInternalServerError, "INTERNAL"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + store := newFakeStore() + store.setErr = tt.err + h, _ := newRouter(t, store) + rec := do(t, h, http.MethodPatch, "/rules/"+ruleID, token(t, testSecret, auth.RoleAdmin), `{"enabled":true}`) + if rec.Code != tt.wantStatus || errorCode(t, rec) != tt.wantCode { + t.Errorf("status = %d code %q, want %d %q", rec.Code, errorCode(t, rec), tt.wantStatus, tt.wantCode) + } + }) + } +} + +func TestList_StoreError(t *testing.T) { + store := newFakeStore() + store.listErr = errors.New("connection refused") + h, _ := newRouter(t, store) + rec := do(t, h, http.MethodGet, "/rules", token(t, testSecret, auth.RoleOperator), "") + if rec.Code != http.StatusInternalServerError || errorCode(t, rec) != "INTERNAL" { + t.Errorf("status = %d body %s, want 500 INTERNAL", rec.Code, rec.Body) + } +} diff --git a/apps/api/internal/rules/rule.go b/apps/api/internal/rules/rule.go index c238ac4..927e7c5 100644 --- a/apps/api/internal/rules/rule.go +++ b/apps/api/internal/rules/rule.go @@ -6,7 +6,9 @@ package rules import ( "context" + "errors" "strconv" + "time" "github.com/vianbas/finwatch/apps/api/internal/transactions" ) @@ -32,15 +34,19 @@ const ( // Rule is a single declarative rule. Value is stored as text and interpreted // per field (an integer for amount_minor, a literal otherwise). type Rule struct { - ID string - Name string - Field Field - Operator Operator - Value string - Severity string - Enabled bool + ID string + Name string + Field Field + Operator Operator + Value string + Severity string + Enabled bool + CreatedAt time.Time } +// ErrNotFound is returned when a rule id does not exist. +var ErrNotFound = errors.New("rules: rule not found") + // Match is a rule that fired for a transaction. type Match struct { RuleID string diff --git a/apps/api/internal/rules/store/store.go b/apps/api/internal/rules/store/store.go index 52319f2..a60c0b7 100644 --- a/apps/api/internal/rules/store/store.go +++ b/apps/api/internal/rules/store/store.go @@ -3,8 +3,11 @@ package store import ( "context" + "errors" "fmt" + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgxpool" "github.com/vianbas/finwatch/apps/api/internal/platform/postgres/db" @@ -28,19 +31,53 @@ func (s *Store) ListEnabled(ctx context.Context) ([]rules.Rule, error) { if err != nil { return nil, fmt.Errorf("store: list rules: %w", err) } + return toDomainAll(rows), nil +} + +// List returns every rule, enabled or not, oldest first. +func (s *Store) List(ctx context.Context) ([]rules.Rule, error) { + rows, err := db.New(s.pool).ListRules(ctx) + if err != nil { + return nil, fmt.Errorf("store: list all rules: %w", err) + } + return toDomainAll(rows), nil +} + +// SetEnabled enables or disables a rule and returns it, or rules.ErrNotFound. +func (s *Store) SetEnabled(ctx context.Context, id string, enabled bool) (rules.Rule, error) { + uid, err := pgconv.ParseUUID(id) + if err != nil { + return rules.Rule{}, rules.ErrNotFound // an unparseable id cannot exist + } + row, err := db.New(s.pool).SetRuleEnabled(ctx, db.SetRuleEnabledParams{ID: uid, Enabled: enabled}) + if errors.Is(err, pgx.ErrNoRows) { + return rules.Rule{}, rules.ErrNotFound + } + if err != nil { + return rules.Rule{}, fmt.Errorf("store: set rule enabled: %w", err) + } + return toDomain(row), nil +} + +func toDomainAll(rows []db.Rule) []rules.Rule { out := make([]rules.Rule, 0, len(rows)) for _, r := range rows { - out = append(out, rules.Rule{ - ID: pgconv.UUIDString(r.ID), - Name: r.Name, - Field: rules.Field(r.Field), - Operator: rules.Operator(r.Operator), - Value: r.Value, - Severity: r.Severity, - Enabled: r.Enabled, - }) + out = append(out, toDomain(r)) + } + return out +} + +func toDomain(r db.Rule) rules.Rule { + return rules.Rule{ + ID: pgconv.UUIDString(r.ID), + Name: r.Name, + Field: rules.Field(r.Field), + Operator: rules.Operator(r.Operator), + Value: r.Value, + Severity: r.Severity, + Enabled: r.Enabled, + CreatedAt: r.CreatedAt.Time.UTC(), } - return out, nil } // EnsureDefaults inserts the generic default rules if they are not present. It diff --git a/apps/api/internal/rules/store/store_integration_test.go b/apps/api/internal/rules/store/store_integration_test.go new file mode 100644 index 0000000..6136dd5 --- /dev/null +++ b/apps/api/internal/rules/store/store_integration_test.go @@ -0,0 +1,128 @@ +package store + +import ( + "context" + "errors" + "os" + "path/filepath" + "sort" + "strings" + "testing" + "time" + + "github.com/jackc/pgx/v5/pgxpool" + + "github.com/vianbas/finwatch/apps/api/internal/rules" +) + +// These tests exercise real PostgreSQL behaviour. They run only when +// FINWATCH_TEST_DATABASE_URL points at a disposable database, e.g.: +// +// make dev # starts Postgres on localhost:5432 +// FINWATCH_TEST_DATABASE_URL='postgres://finwatch:finwatch_dev_password@localhost:5432/finwatch?sslmode=disable' \ +// go test ./internal/rules/store/... +// +// Without the env var they skip, so `make verify` stays green without a DB. + +func newTestPool(t *testing.T) *pgxpool.Pool { + t.Helper() + url := os.Getenv("FINWATCH_TEST_DATABASE_URL") + if url == "" { + t.Skip("set FINWATCH_TEST_DATABASE_URL to run store integration tests") + } + pool, err := pgxpool.New(context.Background(), url) + if err != nil { + t.Fatalf("connect: %v", err) + } + t.Cleanup(pool.Close) + resetSchema(t, pool) + return pool +} + +func resetSchema(t *testing.T, pool *pgxpool.Pool) { + t.Helper() + ctx := context.Background() + if _, err := pool.Exec(ctx, `DROP SCHEMA public CASCADE; CREATE SCHEMA public`); err != nil { + t.Fatalf("reset schema: %v", err) + } + dir := filepath.Join("..", "..", "..", "migrations") + entries, err := os.ReadDir(dir) + if err != nil { + t.Fatalf("read migrations dir: %v", err) + } + var ups []string + for _, e := range entries { + if strings.HasSuffix(e.Name(), ".up.sql") { + ups = append(ups, e.Name()) + } + } + sort.Strings(ups) + for _, name := range ups { + sql, err := os.ReadFile(filepath.Join(dir, name)) + if err != nil { + t.Fatalf("read %s: %v", name, err) + } + if _, err := pool.Exec(ctx, string(sql)); err != nil { + t.Fatalf("apply %s: %v", name, err) + } + } +} + +func TestStore_ListAndSetEnabled(t *testing.T) { + pool := newTestPool(t) + ctx := context.Background() + s := New(pool) + + if err := s.EnsureDefaults(ctx); err != nil { + t.Fatalf("EnsureDefaults: %v", err) + } + all, err := s.List(ctx) + if err != nil || len(all) != len(rules.DefaultRules) { + t.Fatalf("List = %d rules (err %v), want %d", len(all), err, len(rules.DefaultRules)) + } + target := all[0] + if !target.Enabled || target.CreatedAt.IsZero() || target.CreatedAt.Location() != time.UTC { + t.Fatalf("unexpected seeded rule %+v", target) + } + + got, err := s.SetEnabled(ctx, target.ID, false) + if err != nil { + t.Fatalf("SetEnabled(false): %v", err) + } + if got.ID != target.ID || got.Enabled || got.Name != target.Name { + t.Errorf("SetEnabled returned %+v, want %s disabled", got, target.ID) + } + + // Disabled rules stay listed but drop out of evaluation. + all, err = s.List(ctx) + if err != nil || len(all) != len(rules.DefaultRules) { + t.Fatalf("List after disable = %d (err %v)", len(all), err) + } + enabled, err := s.ListEnabled(ctx) + if err != nil { + t.Fatalf("ListEnabled: %v", err) + } + for _, r := range enabled { + if r.ID == target.ID { + t.Errorf("disabled rule %s still returned by ListEnabled", target.ID) + } + } + + // Idempotent, and reversible. + if _, err := s.SetEnabled(ctx, target.ID, false); err != nil { + t.Fatalf("SetEnabled(false) again: %v", err) + } + if got, err := s.SetEnabled(ctx, target.ID, true); err != nil || !got.Enabled { + t.Fatalf("SetEnabled(true) = %+v, %v", got, err) + } +} + +func TestStore_SetEnabledUnknownRule(t *testing.T) { + pool := newTestPool(t) + s := New(pool) + for _, id := range []string{"00000000-0000-0000-0000-000000000000", "not-a-uuid"} { + if _, err := s.SetEnabled(context.Background(), id, false); !errors.Is(err, rules.ErrNotFound) { + t.Errorf("SetEnabled(%q) err = %v, want ErrNotFound", id, err) + } + } +} diff --git a/apps/api/queries/outbox.sql b/apps/api/queries/outbox.sql new file mode 100644 index 0000000..938f841 --- /dev/null +++ b/apps/api/queries/outbox.sql @@ -0,0 +1,13 @@ +-- name: ListUnpublishedOutboxEvents :many +-- Oldest first, served by the outbox_events_unpublished_idx partial index. +SELECT id, event_type, payload, occurred_at +FROM outbox_events +WHERE published_at IS NULL +ORDER BY occurred_at, id +LIMIT $1; + +-- name: MarkOutboxEventsPublished :exec +UPDATE outbox_events +SET published_at = now() +WHERE id = ANY(sqlc.arg(ids)::bigint[]) + AND published_at IS NULL; diff --git a/apps/api/queries/rules.sql b/apps/api/queries/rules.sql index 5b2cc37..0541a32 100644 --- a/apps/api/queries/rules.sql +++ b/apps/api/queries/rules.sql @@ -8,3 +8,14 @@ ORDER BY created_at, id; INSERT INTO rules (name, field, operator, value, severity, enabled) VALUES ($1, $2, $3, $4, $5, $6) ON CONFLICT (name) DO NOTHING; + +-- name: ListRules :many +SELECT id, name, field, operator, value, severity, enabled, created_at +FROM rules +ORDER BY created_at, id; + +-- name: SetRuleEnabled :one +UPDATE rules +SET enabled = sqlc.arg(enabled) +WHERE id = sqlc.arg(id) +RETURNING id, name, field, operator, value, severity, enabled, created_at; diff --git a/apps/web/src/app/AppShell.tsx b/apps/web/src/app/AppShell.tsx index 6809e5d..217ab1b 100644 --- a/apps/web/src/app/AppShell.tsx +++ b/apps/web/src/app/AppShell.tsx @@ -2,6 +2,8 @@ import { useState } from "react"; import { NavLink, Outlet } from "react-router-dom"; import { Activity, Bell, LayoutDashboard, Menu, Wrench } from "lucide-react"; import { cn } from "@/lib/utils"; +import { ConnectionStatus } from "@/app/ConnectionStatus"; +import { useRealtimeEvents } from "@/app/useRealtimeEvents"; const navItems = [ { to: "/dashboard", label: "Dashboard", icon: LayoutDashboard }, @@ -16,6 +18,7 @@ const navItems = [ */ export function AppShell() { const [mobileOpen, setMobileOpen] = useState(false); + const { status } = useRealtimeEvents(); return (