diff --git a/agent/internal/queue/queue.go b/agent/internal/queue/queue.go
index a5516aad..a39002c6 100644
--- a/agent/internal/queue/queue.go
+++ b/agent/internal/queue/queue.go
@@ -16,11 +16,20 @@ const schema = `
CREATE TABLE IF NOT EXISTS pending (
id TEXT PRIMARY KEY,
queued_at INTEGER NOT NULL,
- payload TEXT NOT NULL
+ payload TEXT NOT NULL,
+ attempts INTEGER NOT NULL DEFAULT 0
);
CREATE INDEX IF NOT EXISTS idx_queued_at ON pending (queued_at);
`
+// Stats describes the entries currently buffered locally. RetryCount is the
+// number of delivery attempts made for entries that are still pending.
+type Stats struct {
+ Pending int
+ OldestQueuedAt *time.Time
+ RetryCount int
+}
+
// Queue is a persistent, ordered event queue backed by SQLite.
type Queue struct {
db *sql.DB
@@ -43,9 +52,48 @@ func New(dbPath string) (*Queue, error) {
_ = db.Close()
return nil, fmt.Errorf("queue: apply schema: %w", err)
}
+ hasAttempts, err := pendingHasColumn(db, "attempts")
+ if err != nil {
+ _ = db.Close()
+ return nil, err
+ }
+ if !hasAttempts {
+ // Older agents created pending without attempts. Keep those databases
+ // readable and upgrade them in place without requiring data loss.
+ if _, err := db.Exec(`ALTER TABLE pending ADD COLUMN attempts INTEGER NOT NULL DEFAULT 0`); err != nil {
+ _ = db.Close()
+ return nil, fmt.Errorf("queue: migrate schema: %w", err)
+ }
+ }
return &Queue{db: db}, nil
}
+func pendingHasColumn(db *sql.DB, name string) (bool, error) {
+ rows, err := db.Query(`PRAGMA table_info(pending)`)
+ if err != nil {
+ return false, fmt.Errorf("queue: inspect schema: %w", err)
+ }
+ defer rows.Close()
+
+ for rows.Next() {
+ var cid int
+ var columnName, columnType string
+ var notNull int
+ var defaultValue sql.NullString
+ var primaryKey int
+ if err := rows.Scan(&cid, &columnName, &columnType, ¬Null, &defaultValue, &primaryKey); err != nil {
+ return false, fmt.Errorf("queue: inspect schema: %w", err)
+ }
+ if columnName == name {
+ return true, nil
+ }
+ }
+ if err := rows.Err(); err != nil {
+ return false, fmt.Errorf("queue: inspect schema: %w", err)
+ }
+ return false, nil
+}
+
// Push persists an entry to the queue. The entry must have a non-empty ID.
func (q *Queue) Push(entry types.Entry) error {
if entry.ID == "" {
@@ -77,6 +125,12 @@ func (q *Queue) Flush(limit int) ([]types.Entry, error) {
if limit <= 0 {
return nil, fmt.Errorf("queue: flush limit must be positive, got %d", limit)
}
+ if _, err := q.db.Exec(
+ `UPDATE pending SET attempts = attempts + 1 WHERE id IN (SELECT id FROM pending ORDER BY queued_at ASC LIMIT ?)`,
+ limit,
+ ); err != nil {
+ return nil, fmt.Errorf("queue: mark attempts: %w", err)
+ }
rows, err := q.db.Query(
`SELECT id, payload FROM pending ORDER BY queued_at ASC LIMIT ?`,
limit,
@@ -119,6 +173,23 @@ func (q *Queue) Flush(limit int) ([]types.Entry, error) {
return entries, rowsErr
}
+// Stats returns a bounded summary of the current persistent queue without
+// exposing event payloads. A nil OldestQueuedAt means the queue is empty.
+func (q *Queue) Stats() (Stats, error) {
+ var stats Stats
+ var oldest sql.NullInt64
+ if err := q.db.QueryRow(
+ `SELECT COUNT(*), MIN(queued_at), COALESCE(SUM(attempts), 0) FROM pending`,
+ ).Scan(&stats.Pending, &oldest, &stats.RetryCount); err != nil {
+ return Stats{}, fmt.Errorf("queue: stats: %w", err)
+ }
+ if oldest.Valid {
+ queuedAt := time.UnixMilli(oldest.Int64).UTC()
+ stats.OldestQueuedAt = &queuedAt
+ }
+ return stats, nil
+}
+
// Delete removes entries by ID. Silently ignores IDs not in the table.
// The SQL string is constructed by repeating '?' placeholders — IDs are
// passed as bound parameters (args...) and never interpolated into the
diff --git a/agent/internal/queue/queue_test.go b/agent/internal/queue/queue_test.go
index 6894fdaa..64d82b4f 100644
--- a/agent/internal/queue/queue_test.go
+++ b/agent/internal/queue/queue_test.go
@@ -1,6 +1,7 @@
package queue_test
import (
+ "database/sql"
"path/filepath"
"testing"
"time"
@@ -8,6 +9,7 @@ import (
"blackbox/agent/internal/queue"
"blackbox/shared/types"
"github.com/oklog/ulid/v2"
+ _ "modernc.org/sqlite"
)
func newTestQueue(t *testing.T) *queue.Queue {
@@ -164,3 +166,82 @@ func TestSweepStale_RemovesOldEntries(t *testing.T) {
t.Errorf("expected only fresh entry to remain, got %+v", rows)
}
}
+
+func TestStats_ReportsPendingOldestAndRetries(t *testing.T) {
+ q := newTestQueue(t)
+
+ oldest := time.Now().UTC().Add(-2 * time.Minute).Truncate(time.Millisecond)
+ entry := types.Entry{ID: ulid.Make().String(), Source: "docker", Event: "start"}
+ if err := q.PushAt(entry, oldest); err != nil {
+ t.Fatalf("PushAt: %v", err)
+ }
+
+ stats, err := q.Stats()
+ if err != nil {
+ t.Fatalf("Stats: %v", err)
+ }
+ if stats.Pending != 1 || stats.RetryCount != 0 || stats.OldestQueuedAt == nil {
+ t.Fatalf("unexpected initial stats: %+v", stats)
+ }
+ if !stats.OldestQueuedAt.Equal(oldest) {
+ t.Fatalf("oldest queued at = %v, want %v", stats.OldestQueuedAt, oldest)
+ }
+
+ if _, err := q.Flush(1); err != nil {
+ t.Fatalf("Flush: %v", err)
+ }
+ stats, err = q.Stats()
+ if err != nil {
+ t.Fatalf("Stats after flush: %v", err)
+ }
+ if stats.RetryCount != 1 {
+ t.Fatalf("retry count = %d, want 1", stats.RetryCount)
+ }
+}
+
+func TestNew_MigratesLegacyPendingTableOnce(t *testing.T) {
+ path := filepath.Join(t.TempDir(), "queue.db")
+ db, err := sql.Open("sqlite", path)
+ if err != nil {
+ t.Fatalf("sql.Open: %v", err)
+ }
+ _, err = db.Exec(`CREATE TABLE pending (
+ id TEXT PRIMARY KEY,
+ queued_at INTEGER NOT NULL,
+ payload TEXT NOT NULL
+ )`)
+ if err != nil {
+ t.Fatalf("create legacy pending: %v", err)
+ }
+ if err := db.Close(); err != nil {
+ t.Fatalf("close legacy db: %v", err)
+ }
+
+ q, err := queue.New(path)
+ if err != nil {
+ t.Fatalf("queue.New legacy: %v", err)
+ }
+ if err := q.Close(); err != nil {
+ t.Fatalf("close migrated queue: %v", err)
+ }
+ q, err = queue.New(path)
+ if err != nil {
+ t.Fatalf("queue.New migrated: %v", err)
+ }
+ t.Cleanup(func() { _ = q.Close() })
+
+ entry := types.Entry{ID: ulid.Make().String(), Source: "docker", Event: "start"}
+ if err := q.Push(entry); err != nil {
+ t.Fatalf("Push after migration: %v", err)
+ }
+ if _, err := q.Flush(1); err != nil {
+ t.Fatalf("Flush after migration: %v", err)
+ }
+ stats, err := q.Stats()
+ if err != nil {
+ t.Fatalf("Stats after migration: %v", err)
+ }
+ if stats.RetryCount != 1 {
+ t.Fatalf("retry count = %d, want 1", stats.RetryCount)
+ }
+}
diff --git a/agent/main.go b/agent/main.go
index 956614e2..f77037d4 100644
--- a/agent/main.go
+++ b/agent/main.go
@@ -49,13 +49,6 @@ func main() {
nodeName = "unknown"
}
}
- info := collectNodeInfo(serverURL)
- infoJSON, err := json.Marshal(info)
- if err != nil {
- log.Printf("WARNING: failed to marshal node info: %v", err)
- infoJSON = []byte("{}")
- }
-
watchPaths := splitEnv("WATCH_PATHS")
watchIgnore := splitEnv("WATCH_IGNORE")
@@ -78,6 +71,7 @@ func main() {
} else if swept > 0 {
log.Printf("queue: swept %d stale entries (older than 7 days)", swept)
}
+ info := collectNodeInfo(serverURL)
c := client.New(serverURL, agentToken, nodeName)
s := sender.New(c, q)
@@ -130,7 +124,7 @@ func main() {
Source: "agent",
Event: "start",
Content: "Blackbox Agent started",
- Metadata: string(infoJSON),
+ Metadata: nodeMetadata(info, q),
}
go func() {
@@ -148,7 +142,7 @@ func main() {
Source: "agent",
Event: "heartbeat",
Content: "Blackbox Agent heartbeat",
- Metadata: string(infoJSON),
+ Metadata: nodeMetadata(info, q),
}
}
}
@@ -167,7 +161,7 @@ func main() {
Source: "agent",
Event: "shutdown",
Content: "Blackbox Agent shutting down",
- Metadata: string(infoJSON),
+ Metadata: nodeMetadata(info, q),
}
cancel()
<-s.Done()
@@ -304,9 +298,35 @@ func summarizeUnitDiff(current, previous []string) string {
}
type nodeInfo struct {
- AgentVersion string `json:"agent_version"`
- IPAddress string `json:"ip_address"`
- OsInfo string `json:"os_info"`
+ AgentVersion string `json:"agent_version"`
+ IPAddress string `json:"ip_address"`
+ OsInfo string `json:"os_info"`
+ Queue *queueInfo `json:"queue,omitempty"`
+}
+
+type queueInfo struct {
+ Depth int `json:"depth"`
+ OldestAt *time.Time `json:"oldest_at,omitempty"`
+ RetryCount int `json:"retry_count"`
+}
+
+func nodeMetadata(info nodeInfo, q *queue.Queue) string {
+ stats, err := q.Stats()
+ if err != nil {
+ log.Printf("queue: failed to read stats: %v", err)
+ } else {
+ info.Queue = &queueInfo{
+ Depth: stats.Pending,
+ OldestAt: stats.OldestQueuedAt,
+ RetryCount: stats.RetryCount,
+ }
+ }
+ metadata, err := json.Marshal(info)
+ if err != nil {
+ log.Printf("WARNING: failed to marshal node metadata: %v", err)
+ return "{}"
+ }
+ return string(metadata)
}
func collectNodeInfo(serverURL string) nodeInfo {
diff --git a/agent/main_test.go b/agent/main_test.go
index 5c3eb1c4..174a5fa0 100644
--- a/agent/main_test.go
+++ b/agent/main_test.go
@@ -2,8 +2,10 @@ package main
import (
"context"
+ "encoding/json"
"io"
"net/http"
+ "path/filepath"
"reflect"
"slices"
"strings"
@@ -12,6 +14,7 @@ import (
"blackbox/agent/internal/client"
"blackbox/agent/internal/files"
+ "blackbox/agent/internal/queue"
"blackbox/agent/internal/systemd"
)
@@ -53,6 +56,25 @@ func TestLoadSystemdUnits(t *testing.T) {
}
}
+func TestNodeMetadata_OmitsQueueWhenStatsFail(t *testing.T) {
+ q, err := queue.New(filepath.Join(t.TempDir(), "queue.db"))
+ if err != nil {
+ t.Fatalf("queue.New: %v", err)
+ }
+ if err := q.Close(); err != nil {
+ t.Fatalf("queue.Close: %v", err)
+ }
+
+ metadata := nodeMetadata(nodeInfo{AgentVersion: "1.0.0"}, q)
+ var got map[string]any
+ if err := json.Unmarshal([]byte(metadata), &got); err != nil {
+ t.Fatalf("metadata JSON: %v", err)
+ }
+ if _, ok := got["queue"]; ok {
+ t.Fatalf("queue metadata present after stats failure: %s", metadata)
+ }
+}
+
func TestRefreshSystemdSettingsKeepsExistingUnitsOnFetchFailure(t *testing.T) {
t.Parallel()
diff --git a/server/docs/openapi.yaml b/server/docs/openapi.yaml
index 7a091edb..eeeb351c 100644
--- a/server/docs/openapi.yaml
+++ b/server/docs/openapi.yaml
@@ -251,7 +251,7 @@ components:
Node:
type: object
- required: [id, name, last_seen, status, agent_version, ip_address, os_info]
+ required: [id, name, last_seen, status, agent_version, ip_address, os_info, queue_reported, queue_depth, queue_retry_count]
properties:
id:
type: string
@@ -269,6 +269,22 @@ components:
type: string
os_info:
type: string
+ queue_reported:
+ type: boolean
+ description: Whether the agent supports and reported persistent queue statistics.
+ queue_depth:
+ type: integer
+ minimum: 0
+ description: Number of events currently buffered on the agent.
+ queue_oldest_at:
+ type: string
+ format: date-time
+ nullable: true
+ description: Timestamp of the oldest buffered event, when the queue is non-empty.
+ queue_retry_count:
+ type: integer
+ minimum: 0
+ description: Delivery attempts made for events that remain buffered.
InviteCode:
type: object
diff --git a/server/internal/handlers/agent_push.go b/server/internal/handlers/agent_push.go
index 69fe1667..d8160924 100644
--- a/server/internal/handlers/agent_push.go
+++ b/server/internal/handlers/agent_push.go
@@ -155,6 +155,12 @@ func upsertNode(database *gorm.DB, entry types.Entry) bool {
if updatedNode.OsInfo != "" {
updates["os_info"] = updatedNode.OsInfo
}
+ if updatedNode.QueueReported {
+ updates["queue_reported"] = true
+ updates["queue_depth"] = updatedNode.QueueDepth
+ updates["queue_oldest_at"] = updatedNode.QueueOldestAt
+ updates["queue_retry_count"] = updatedNode.QueueRetries
+ }
}
if err := database.Model(&node).Updates(updates).Error; err != nil {
@@ -169,6 +175,11 @@ func applyHeartbeatMeta(node *models.Node, metadata string) {
AgentVersion string `json:"agent_version"`
IPAddress string `json:"ip_address"`
OsInfo string `json:"os_info"`
+ Queue *struct {
+ Depth int `json:"depth"`
+ OldestAt *time.Time `json:"oldest_at"`
+ RetryCount int `json:"retry_count"`
+ } `json:"queue"`
}
if err := json.Unmarshal([]byte(metadata), &meta); err != nil {
return
@@ -182,6 +193,12 @@ func applyHeartbeatMeta(node *models.Node, metadata string) {
if meta.OsInfo != "" {
node.OsInfo = meta.OsInfo
}
+ if meta.Queue != nil {
+ node.QueueReported = true
+ node.QueueDepth = max(meta.Queue.Depth, 0)
+ node.QueueOldestAt = meta.Queue.OldestAt
+ node.QueueRetries = max(meta.Queue.RetryCount, 0)
+ }
}
func broadcastNodeStatus(database *gorm.DB, h *hub.Hub) {
diff --git a/server/internal/handlers/agent_push_upsert_test.go b/server/internal/handlers/agent_push_upsert_test.go
index c3fa8166..f6bc2464 100644
--- a/server/internal/handlers/agent_push_upsert_test.go
+++ b/server/internal/handlers/agent_push_upsert_test.go
@@ -37,6 +37,7 @@ func TestAgentPush_CreatesNode(t *testing.T) {
assert.Equal(t, "v0.2.1", node.AgentVersion)
assert.Equal(t, "10.0.0.5", node.IPAddress)
assert.Equal(t, "Ubuntu 24.04 LTS", node.OsInfo)
+ assert.False(t, node.QueueReported)
assert.WithinDuration(t, startedAt, node.LastSeen, 2*time.Second)
}
@@ -65,6 +66,33 @@ func TestAgentPush_HeartbeatUpdatesNodeMetadata(t *testing.T) {
assert.Equal(t, "Ubuntu 24.04 LTS", node.OsInfo)
}
+func TestAgentPush_HeartbeatUpdatesQueueMetadata(t *testing.T) {
+ database := newTestDB(t)
+
+ oldest := time.Now().UTC().Add(-3 * time.Minute).Truncate(time.Millisecond)
+ meta := `{"agent_version":"v0.4.0","queue":{"depth":4,"oldest_at":"` + oldest.Format(time.RFC3339Nano) + `","retry_count":7}}`
+ entry := types.Entry{
+ ID: ulid.Make().String(),
+ Timestamp: time.Now().UTC(),
+ NodeName: "homelab-01",
+ Source: "agent",
+ Event: "heartbeat",
+ Content: "Blackbox Agent heartbeat",
+ Metadata: meta,
+ }
+ req, rr, authMiddleware := authenticatedAgentRequest(t, entry, "homelab-01")
+ authMiddleware(handlers.AgentPush(database, nil, testIncidentChannel(t), nil)).ServeHTTP(rr, req)
+
+ require.Equal(t, http.StatusCreated, rr.Code, rr.Body.String())
+ var node models.Node
+ require.NoError(t, database.Where("name = ?", "homelab-01").First(&node).Error)
+ assert.True(t, node.QueueReported)
+ assert.Equal(t, 4, node.QueueDepth)
+ assert.Equal(t, 7, node.QueueRetries)
+ require.NotNil(t, node.QueueOldestAt)
+ assert.WithinDuration(t, oldest, *node.QueueOldestAt, time.Millisecond)
+}
+
func TestAgentPush_ThrottlesLastSeenUpdates(t *testing.T) {
database := newTestDB(t)
diff --git a/server/internal/handlers/nodes.go b/server/internal/handlers/nodes.go
index f29f6f4e..75aa6f75 100644
--- a/server/internal/handlers/nodes.go
+++ b/server/internal/handlers/nodes.go
@@ -18,6 +18,10 @@ type nodeResponse struct {
IPAddress string `json:"ip_address"`
OsInfo string `json:"os_info"`
Status string `json:"status"`
+ QueueReported bool `json:"queue_reported"`
+ QueueDepth int `json:"queue_depth"`
+ QueueOldestAt *time.Time `json:"queue_oldest_at,omitempty"`
+ QueueRetries int `json:"queue_retry_count"`
}
func ListNodes(database *gorm.DB) http.HandlerFunc {
@@ -39,6 +43,10 @@ func ListNodes(database *gorm.DB) http.HandlerFunc {
IPAddress: node.IPAddress,
OsInfo: node.OsInfo,
Status: effectiveNodeStatus(node, now),
+ QueueReported: node.QueueReported,
+ QueueDepth: node.QueueDepth,
+ QueueOldestAt: node.QueueOldestAt,
+ QueueRetries: node.QueueRetries,
}
}
diff --git a/server/internal/handlers/nodes_test.go b/server/internal/handlers/nodes_test.go
index 6adadf9b..5ee97983 100644
--- a/server/internal/handlers/nodes_test.go
+++ b/server/internal/handlers/nodes_test.go
@@ -89,3 +89,36 @@ func TestListNodes_ExplicitOfflineOverridesFreshLastSeen(t *testing.T) {
require.Len(t, nodes, 1)
assert.Equal(t, "offline", nodes[0].Status)
}
+
+func TestListNodes_IncludesQueueVisibility(t *testing.T) {
+ database := newTestDB(t)
+ oldest := time.Now().UTC().Add(-4 * time.Minute).Truncate(time.Millisecond)
+ require.NoError(t, database.Create(&models.Node{
+ ID: ulid.Make().String(),
+ Name: "queued-node",
+ LastSeen: time.Now().UTC(),
+ QueueReported: true,
+ QueueDepth: 3,
+ QueueOldestAt: &oldest,
+ QueueRetries: 5,
+ }).Error)
+
+ req := httptest.NewRequest(http.MethodGet, "/api/nodes", nil)
+ rr := httptest.NewRecorder()
+ handlers.ListNodes(database)(rr, req)
+
+ require.Equal(t, http.StatusOK, rr.Code)
+ var nodes []struct {
+ QueueReported bool `json:"queue_reported"`
+ QueueDepth int `json:"queue_depth"`
+ QueueOldestAt *time.Time `json:"queue_oldest_at"`
+ QueueRetries int `json:"queue_retry_count"`
+ }
+ require.NoError(t, json.Unmarshal(rr.Body.Bytes(), &nodes))
+ require.Len(t, nodes, 1)
+ assert.True(t, nodes[0].QueueReported)
+ assert.Equal(t, 3, nodes[0].QueueDepth)
+ assert.Equal(t, 5, nodes[0].QueueRetries)
+ require.NotNil(t, nodes[0].QueueOldestAt)
+ assert.WithinDuration(t, oldest, *nodes[0].QueueOldestAt, time.Millisecond)
+}
diff --git a/server/internal/models/node.go b/server/internal/models/node.go
index d31a2bad..67af4fdd 100644
--- a/server/internal/models/node.go
+++ b/server/internal/models/node.go
@@ -12,4 +12,8 @@ type Node struct {
IPAddress string `json:"ip_address"`
OsInfo string `json:"os_info"`
Capabilities string `gorm:"not null;default:'[]'" json:"capabilities"` // JSON []string
+ QueueReported bool `json:"queue_reported"`
+ QueueDepth int `json:"queue_depth"`
+ QueueOldestAt *time.Time `json:"queue_oldest_at,omitempty"`
+ QueueRetries int `json:"queue_retry_count"`
}
diff --git a/web/src/api/client.ts b/web/src/api/client.ts
index 7c088705..ca80a40b 100644
--- a/web/src/api/client.ts
+++ b/web/src/api/client.ts
@@ -80,6 +80,10 @@ export interface Node {
ip_address: string
os_info: string
status: 'online' | 'offline'
+ queue_reported?: boolean
+ queue_depth?: number
+ queue_oldest_at?: string | null
+ queue_retry_count?: number
}
export interface EntryNote {
diff --git a/web/src/pages/NodesPage.tsx b/web/src/pages/NodesPage.tsx
index 73d55bcf..4ad78cf1 100644
--- a/web/src/pages/NodesPage.tsx
+++ b/web/src/pages/NodesPage.tsx
@@ -11,6 +11,10 @@ interface NodeViewModel {
agentVersion: string
ipAddress: string
osInfo: string | null | undefined
+ queueReported: boolean
+ queueDepth: number
+ queueOldestAt: string | null
+ queueRetries: number
}
function formatTimestamp(ts?: string | null | Date) {
@@ -57,6 +61,23 @@ function OsCell({ osInfo }: { osInfo: string | null | undefined }) {
)
}
+function QueueCell({ node, mobile = false }: { node: NodeViewModel; mobile?: boolean }) {
+ if (!node.queueReported) return -
+
+ const oldest = node.queueOldestAt ? formatTimestamp(node.queueOldestAt) : null
+ return (
+ 0 ? 'var(--warning, #F59E0B)' : 'var(--muted)', fontSize: 11 }}>
+ {node.queueDepth} pending
+ {node.queueRetries > 0 && · {node.queueRetries} attempts}
+ {oldest && (
+
+ {mobile ? ` · oldest ${oldest}` : `oldest ${oldest}`}
+
+ )}
+
+ )
+}
+
function getNodeStatusPresentation(status: string) {
const isOnline = status === 'online'
return {
@@ -76,6 +97,10 @@ function toNodeViewModel(node: ReturnType['nodes'][number])
agentVersion: node.agent_version || '-',
ipAddress: node.ip_address || '-',
osInfo: node.os_info,
+ queueReported: node.queue_reported === true,
+ queueDepth: Math.max(0, node.queue_depth ?? 0),
+ queueOldestAt: node.queue_oldest_at ?? null,
+ queueRetries: Math.max(0, node.queue_retry_count ?? 0),
}
}
@@ -120,6 +145,10 @@ function NodeItem({ node, variant }: { node: NodeViewModel; variant: 'desktop' |
IP
{node.ipAddress}
+
+ QUEUE
+
+
)
@@ -152,6 +181,9 @@ function NodeItem({ node, variant }: { node: NodeViewModel; variant: 'desktop' |
{node.ipAddress}
|
+
+
+ |
)
}
@@ -217,6 +249,7 @@ export default function NodesPage() {
OS |
VERSION |
IP |
+ QUEUE |