implemented NATS event bus, websocket hub upgrade, and audit log

This commit is contained in:
2026-05-11 19:38:02 +02:00
parent db0f402ab2
commit 83d96d0a1e
16 changed files with 502 additions and 15 deletions
+64
View File
@@ -0,0 +1,64 @@
package handlers
import (
"net/http"
"strconv"
"time"
"xorm.io/xorm"
"github.com/forgeo/forgebucket/internal/api/middleware"
"github.com/forgeo/forgebucket/internal/models"
)
type AuditHandler struct{ db *xorm.Engine }
func NewAuditHandler(db *xorm.Engine) *AuditHandler { return &AuditHandler{db: db} }
// List returns recent audit log entries. Admin-only.
// Query params: limit (default 50, max 200), before (ID cursor for pagination),
// actor_id, method, since (RFC3339).
func (h *AuditHandler) List(w http.ResponseWriter, r *http.Request) {
isAdmin, _ := r.Context().Value(middleware.ContextKeyIsAdmin).(bool)
if !isAdmin {
jsonError(w, "admin access required", http.StatusForbidden)
return
}
q := r.URL.Query()
limit := 50
if l, err := strconv.Atoi(q.Get("limit")); err == nil && l > 0 {
if l > 200 {
l = 200
}
limit = l
}
sess := h.db.Desc("id").Limit(limit)
if before, err := strconv.ParseInt(q.Get("before"), 10, 64); err == nil && before > 0 {
sess = sess.And("id < ?", before)
}
if actorID, err := strconv.ParseInt(q.Get("actor_id"), 10, 64); err == nil && actorID > 0 {
sess = sess.And("actor_id = ?", actorID)
}
if method := q.Get("method"); method != "" {
sess = sess.And("method = ?", method)
}
if since := q.Get("since"); since != "" {
if t, err := time.Parse(time.RFC3339, since); err == nil {
sess = sess.And("occurred_at >= ?", t.UTC())
}
}
var entries []models.AuditLog
if err := sess.Find(&entries); err != nil {
jsonError(w, "could not fetch audit log", http.StatusInternalServerError)
return
}
if entries == nil {
entries = []models.AuditLog{}
}
jsonOK(w, entries)
}
+90 -9
View File
@@ -1,18 +1,74 @@
package handlers
import (
"encoding/json"
"log"
"net/http"
"sync"
"nhooyr.io/websocket"
"nhooyr.io/websocket/wsjson"
"github.com/forgeo/forgebucket/internal/events"
)
type WSHandler struct{}
func NewWSHandler() *WSHandler {
return &WSHandler{}
// WSHandler manages WebSocket connections and bridges NATS events to clients.
// All connected clients receive every platform event (subject + payload).
// Per-user filtering is added in Phase 2B when CI events carry access control.
type WSHandler struct {
bus events.EventBus
mu sync.RWMutex
clients map[string]chan events.WSEnvelope // connID → send channel
}
func NewWSHandler(bus events.EventBus) *WSHandler {
h := &WSHandler{
bus: bus,
clients: make(map[string]chan events.WSEnvelope),
}
h.subscribeAll()
return h
}
// subscribeAll wires the NATS wildcard subscription that fans events to all clients.
func (h *WSHandler) subscribeAll() {
unsub, err := h.bus.Subscribe(">", func(subject string, data []byte) {
env := events.WSEnvelope{Subject: subject, Payload: data}
h.mu.RLock()
defer h.mu.RUnlock()
for id, ch := range h.clients {
select {
case ch <- env:
default:
// Client send buffer full — drop event rather than block.
log.Printf("ws: dropped event %s for slow client %s", subject, id)
}
}
})
if err != nil {
log.Printf("ws: nats subscribe failed: %v", err)
return
}
// The subscription lives for the process lifetime; no cleanup needed.
_ = unsub
}
func (h *WSHandler) register(id string) chan events.WSEnvelope {
ch := make(chan events.WSEnvelope, 64)
h.mu.Lock()
h.clients[id] = ch
h.mu.Unlock()
return ch
}
func (h *WSHandler) unregister(id string) {
h.mu.Lock()
delete(h.clients, id)
h.mu.Unlock()
}
// Hub upgrades the HTTP connection to WebSocket, registers the client, and
// pumps NATS-sourced events to it until the connection closes.
func (h *WSHandler) Hub(w http.ResponseWriter, r *http.Request) {
conn, err := websocket.Accept(w, r, &websocket.AcceptOptions{
OriginPatterns: []string{"localhost:*"},
@@ -22,13 +78,38 @@ func (h *WSHandler) Hub(w http.ResponseWriter, r *http.Request) {
}
defer conn.CloseNow()
// Use remote address + a monotonic component as a simple unique ID.
connID := r.RemoteAddr + "|" + r.Header.Get("Sec-Websocket-Key")
send := h.register(connID)
defer h.unregister(connID)
ctx := r.Context()
for {
var msg map[string]any
if err := wsjson.Read(ctx, conn, &msg); err != nil {
break
// Write pump: drain the send channel and write to the WebSocket.
go func() {
for {
select {
case env, ok := <-send:
if !ok {
return
}
msg := map[string]any{
"subject": env.Subject,
"payload": json.RawMessage(env.Payload),
}
if err := wsjson.Write(ctx, conn, msg); err != nil {
return
}
case <-ctx.Done():
return
}
}
if err := wsjson.Write(ctx, conn, msg); err != nil {
}()
// Read pump: discard incoming messages (clients send no data for now),
// keeping the connection alive and detecting closes.
for {
if _, _, err := conn.Read(ctx); err != nil {
break
}
}