accounts/sql/20260205_agents_table.sql
Haitao Pan 8b8a2aa3fa feat(agent-persistence): implement PostgreSQL persistence for agent registry
Core Changes:
- Add Agent struct and management methods to Store interface
- Implement PostgreSQL store methods (UpsertAgent, ListAgents, DeleteAgent, DeleteStaleAgents)
- Integrate persistence into Registry with async database writes
- Add Load() method to restore agents from database on startup
- Implement runAgentCleanup background task (5min interval, 10min stale threshold)

Database:
- Update agents table schema to use JSONB for groups field
- Add indexes on last_heartbeat and healthy columns
- Support health tracking and automatic cleanup of stale agents

Documentation:
- Add comprehensive DB access and upgrade guide
- Include agent persistence implementation plan
- Document diagnostic procedures and troubleshooting steps
- Add walkthrough of multi-agent support implementation

This enables:
- Persistent agent state across service restarts
- Automatic cleanup of offline agents
- Multi-agent support with shared token authentication
2026-02-05 08:34:25 +08:00

23 lines
1.3 KiB
SQL

-- Agent registration and health tracking
-- Migration: 20260205_agents_table.sql
CREATE TABLE IF NOT EXISTS public.agents (
id TEXT PRIMARY KEY, -- Agent ID (e.g., "hk-xhttp.svc.plus")
name TEXT NOT NULL DEFAULT '', -- Display name
groups JSONB NOT NULL DEFAULT '[]'::jsonb, -- Agent groups (e.g., ["internal"])
healthy BOOLEAN NOT NULL DEFAULT false, -- Last reported health status
last_heartbeat TIMESTAMPTZ, -- Last successful heartbeat time
clients_count INTEGER NOT NULL DEFAULT 0, -- Number of Xray clients
sync_revision TEXT, -- Last sync revision
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE INDEX IF NOT EXISTS idx_agents_last_heartbeat ON public.agents(last_heartbeat);
CREATE INDEX IF NOT EXISTS idx_agents_healthy ON public.agents(healthy);
COMMENT ON TABLE public.agents IS 'Registered agents with health tracking and automatic cleanup';
COMMENT ON COLUMN public.agents.id IS 'Self-reported agent ID from StatusReport.agentId';
COMMENT ON COLUMN public.agents.last_heartbeat IS 'Last successful heartbeat timestamp, used for stale agent cleanup';
COMMENT ON COLUMN public.agents.groups IS 'Agent groups inherited from authentication credential';