feat(system): add runtime task queue observability dashboard for system admins
Expose live asynq queue depths and worker-pool concurrency via a new SystemAdmin API and settings UI, so operators can monitor parsing/wiki backlog without Redis CLI access.
This commit is contained in:
@@ -120,6 +120,12 @@ func (f fakeTaskInspector) HasQueuedTasksForKnowledge(
|
||||
return f.queued[knowledgeID], nil
|
||||
}
|
||||
|
||||
func (f fakeTaskInspector) QueueStats(
|
||||
_ context.Context,
|
||||
) ([]types.QueueStat, bool, error) {
|
||||
return nil, false, nil
|
||||
}
|
||||
|
||||
func newHousekeepingSvcForTest(db *gorm.DB) *HousekeepingService {
|
||||
return newHousekeepingSvcWithInspector(db, fakeTaskInspector{})
|
||||
}
|
||||
|
||||
@@ -2246,7 +2246,7 @@ func (s *knowledgeService) ReparseKnowledge(
|
||||
// - Any in-flight worker reads the new status at its next checkpoint and
|
||||
// bails (see processChunks / ProcessDocument / downstream handlers).
|
||||
// - The asynq inspector (if available) dequeues pending / scheduled / retry
|
||||
// tasks for this knowledge_id across the default / critical / low queues
|
||||
// tasks for this knowledge_id across all queues used by the pipeline
|
||||
// and signals active workers to stop. Lite mode (no Redis) skips the
|
||||
// dequeue step — the checkpoint-based abort is the only stop signal there.
|
||||
// - Idempotent: re-calling on an already-cancelled row is a no-op.
|
||||
|
||||
@@ -43,6 +43,11 @@ type SystemHandler struct {
|
||||
// tests that wire a partial container still compile. In production
|
||||
// the dig graph always provides one.
|
||||
auditSvc interfaces.AuditLogService
|
||||
// taskInspector backs the SystemAdmin runtime queue dashboard. Always
|
||||
// provided by the container (asynq-backed in Redis mode, a no-op in
|
||||
// Lite mode), so GetRuntimeQueues can distinguish "no queues in this
|
||||
// deployment" from "queues are empty".
|
||||
taskInspector interfaces.TaskInspector
|
||||
}
|
||||
|
||||
// NewSystemHandler creates a new system handler
|
||||
@@ -53,6 +58,7 @@ func NewSystemHandler(cfg *config.Config,
|
||||
userSvc interfaces.UserService,
|
||||
systemSettingSvc interfaces.SystemSettingService,
|
||||
auditSvc interfaces.AuditLogService,
|
||||
taskInspector interfaces.TaskInspector,
|
||||
) *SystemHandler {
|
||||
return &SystemHandler{
|
||||
cfg: cfg,
|
||||
@@ -62,6 +68,7 @@ func NewSystemHandler(cfg *config.Config,
|
||||
userSvc: userSvc,
|
||||
systemSettingSvc: systemSettingSvc,
|
||||
auditSvc: auditSvc,
|
||||
taskInspector: taskInspector,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1374,6 +1381,76 @@ func (h *SystemHandler) ListSystemAdmins(c *gin.Context) {
|
||||
// @Success 200 {array} types.SystemSetting "list of settings"
|
||||
// @Failure 403 {object} map[string]interface{} "Forbidden: not a system admin"
|
||||
// @Router /system/admin/settings [get]
|
||||
// RuntimeQueuesResponse is the payload for the SystemAdmin runtime queue
|
||||
// dashboard. `available` is false in Lite mode (no Redis/asynq) so the
|
||||
// UI can render an "unavailable in this deployment" state instead of an
|
||||
// empty table. ParseConcurrency / WikiConcurrency are the *configured*
|
||||
// worker-pool sizes (resolved DB > ENV > default); they are static
|
||||
// capacity, not the live active-worker count (see QueueStat.Active for
|
||||
// what's actually running).
|
||||
type RuntimeQueuesResponse struct {
|
||||
Available bool `json:"available"`
|
||||
ParseConcurrency int `json:"parse_concurrency"`
|
||||
WikiConcurrency int `json:"wiki_concurrency"`
|
||||
Queues []types.QueueStat `json:"queues"`
|
||||
Timestamp int64 `json:"timestamp"`
|
||||
}
|
||||
|
||||
// defaultParseConcurrency / defaultWikiConcurrency mirror the unexported
|
||||
// router constants (defaultAsynqConcurrency / defaultWikiAsynqConcurrency).
|
||||
// Duplicated here rather than exported from router to avoid an import
|
||||
// cycle (router already imports handler); kept in sync by convention.
|
||||
const (
|
||||
defaultParseConcurrency = 32
|
||||
defaultWikiConcurrency = 16
|
||||
)
|
||||
|
||||
// GetRuntimeQueues godoc
|
||||
// @Summary 获取解析任务队列运行时状态
|
||||
// @Description 返回各 asynq 队列的实时深度(pending/active/scheduled/retry 等)与 worker 并发配置,仅系统管理员可见
|
||||
// @Tags 系统管理
|
||||
// @Produce json
|
||||
// @Success 200 {object} RuntimeQueuesResponse
|
||||
// @Router /system/admin/runtime/queues [get]
|
||||
func (h *SystemHandler) GetRuntimeQueues(c *gin.Context) {
|
||||
ctx := logger.CloneContext(c.Request.Context())
|
||||
resp := RuntimeQueuesResponse{
|
||||
ParseConcurrency: defaultParseConcurrency,
|
||||
WikiConcurrency: defaultWikiConcurrency,
|
||||
Timestamp: time.Now().Unix(),
|
||||
}
|
||||
|
||||
if h.taskInspector != nil {
|
||||
stats, supported, err := h.taskInspector.QueueStats(ctx)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "get queue stats failed: %v", err)
|
||||
}
|
||||
resp.Available = supported
|
||||
if stats != nil {
|
||||
resp.Queues = stats
|
||||
}
|
||||
}
|
||||
// Always emit a non-nil array so the JSON serialises to `[]` rather
|
||||
// than `null`, keeping the frontend iteration simple.
|
||||
if resp.Queues == nil {
|
||||
resp.Queues = []types.QueueStat{}
|
||||
}
|
||||
|
||||
// Resolve configured worker-pool sizes (DB > ENV > default). These
|
||||
// are the same keys NewParseAsynqServer / NewWikiAsynqServer read at
|
||||
// startup, so operators see the value that will apply on next restart.
|
||||
if h.systemSettingSvc != nil {
|
||||
resp.ParseConcurrency = int(h.systemSettingSvc.GetInt(
|
||||
ctx, "asynq.concurrency", "WEKNORA_ASYNQ_CONCURRENCY", defaultParseConcurrency,
|
||||
))
|
||||
resp.WikiConcurrency = int(h.systemSettingSvc.GetInt(
|
||||
ctx, "asynq.wiki_concurrency", "WEKNORA_WIKI_ASYNQ_CONCURRENCY", defaultWikiConcurrency,
|
||||
))
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, resp)
|
||||
}
|
||||
|
||||
func (h *SystemHandler) ListSystemSettings(c *gin.Context) {
|
||||
ctx := logger.CloneContext(c.Request.Context())
|
||||
rows, err := h.systemSettingSvc.List(ctx)
|
||||
|
||||
@@ -875,6 +875,12 @@ func RegisterSystemAdminRoutes(
|
||||
adminRoutes.PUT("/settings/:key", handler.UpdateSystemSetting)
|
||||
adminRoutes.DELETE("/settings/:key", handler.ResetSystemSetting)
|
||||
|
||||
// Runtime observability: live asynq queue depths + worker pool
|
||||
// concurrency for the parse/wiki pools. Read-only snapshot for the
|
||||
// SystemAdmin runtime dashboard. Returns available=false in Lite
|
||||
// mode (no Redis) so the UI degrades gracefully.
|
||||
adminRoutes.GET("/runtime/queues", handler.GetRuntimeQueues)
|
||||
|
||||
// Bulk action — write the current default-quota setting onto
|
||||
// every existing tenant. Lives under /tenants instead of
|
||||
// /settings because it changes tenants, not the setting row.
|
||||
|
||||
@@ -182,7 +182,6 @@ func NewParseAsynqServer(svc interfaces.SystemSettingService) *asynq.Server {
|
||||
log.Printf("asynq parse-pool server starting with concurrency=%d redis_op_timeout=%dms",
|
||||
concurrency, readRedisOpTimeoutMs())
|
||||
return newAsynqServer(concurrency, map[string]int{
|
||||
types.QueueCritical: 6, // Highest priority queue
|
||||
types.QueueDefault: 3, // Default priority queue
|
||||
types.QueueLow: 1, // Lowest priority queue
|
||||
types.QueueMultimodal: 1, // Isolated lane for high-volume slow VLM image tasks
|
||||
|
||||
@@ -18,8 +18,8 @@ func NewAsynqInspector() *asynq.Inspector {
|
||||
}
|
||||
|
||||
// asynqTaskInspector implements interfaces.TaskInspector backed by an
|
||||
// *asynq.Inspector. Scans the queues we actually use ("default",
|
||||
// "critical", "low") and matches tasks whose payload carries the given
|
||||
// *asynq.Inspector. Scans the queues we actually use and matches tasks
|
||||
// whose payload carries the given
|
||||
// knowledge_id. Best-effort: any scan/delete error is logged and
|
||||
// swallowed so the cancel API still returns success even when Redis is
|
||||
// flaky.
|
||||
@@ -52,7 +52,6 @@ type knowledgeIDProbe struct {
|
||||
// its (potentially hundreds of) pending image:multimodal tasks.
|
||||
var queuesScanned = []string{
|
||||
types.QueueDefault,
|
||||
types.QueueCritical,
|
||||
types.QueueLow,
|
||||
types.QueueMultimodal,
|
||||
types.QueueGraph,
|
||||
@@ -60,6 +59,22 @@ var queuesScanned = []string{
|
||||
types.QueueWiki,
|
||||
}
|
||||
|
||||
// queueMeta records each queue's worker pool and scheduling weight for
|
||||
// the runtime dashboard. Weights MUST stay in sync with the maps in
|
||||
// NewParseAsynqServer / NewWikiAsynqServer (task.go) — this is display
|
||||
// metadata only, the servers remain the source of truth for scheduling.
|
||||
var queueMeta = map[string]struct {
|
||||
pool string
|
||||
weight int
|
||||
}{
|
||||
types.QueueDefault: {pool: "parse", weight: 3},
|
||||
types.QueueLow: {pool: "parse", weight: 1},
|
||||
types.QueueMultimodal: {pool: "parse", weight: 1},
|
||||
types.QueueGraph: {pool: "parse", weight: 1},
|
||||
types.QueueQuestion: {pool: "parse", weight: 1},
|
||||
types.QueueWiki: {pool: "wiki", weight: 1},
|
||||
}
|
||||
|
||||
// taskTypesForKnowledgeCancel lists every asynq task type that carries
|
||||
// a knowledge_id in its payload and should be cancelable. The set is
|
||||
// deliberately narrow: we don't touch FAQ import / KB-level tasks
|
||||
@@ -137,6 +152,53 @@ func (a *asynqTaskInspector) HasQueuedTasksForKnowledge(
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// QueueStats returns a depth snapshot for every queue this app enqueues
|
||||
// into. Read-only: it calls Inspector.GetQueueInfo per queue and maps
|
||||
// the result onto types.QueueStat, attaching static pool/weight metadata
|
||||
// from queueMeta. A queue that has never received a task yields
|
||||
// ErrQueueNotFound from asynq; we still surface it as a zeroed row so the
|
||||
// dashboard shows the complete lane set even before a queue receives its
|
||||
// first task.
|
||||
func (a *asynqTaskInspector) QueueStats(
|
||||
ctx context.Context,
|
||||
) ([]types.QueueStat, bool, error) {
|
||||
if a == nil || a.inspector == nil {
|
||||
return nil, false, nil
|
||||
}
|
||||
stats := make([]types.QueueStat, 0, len(queuesScanned))
|
||||
for _, queue := range queuesScanned {
|
||||
meta := queueMeta[queue]
|
||||
stat := types.QueueStat{
|
||||
Name: queue,
|
||||
Pool: meta.pool,
|
||||
Weight: meta.weight,
|
||||
}
|
||||
info, err := a.inspector.GetQueueInfo(queue)
|
||||
if err != nil {
|
||||
if !errors.Is(err, asynq.ErrQueueNotFound) {
|
||||
logger.Warnf(ctx, "[TaskInspector] queue info queue=%s: %v", queue, err)
|
||||
}
|
||||
// Zeroed row: queue not created yet (or transient error).
|
||||
stats = append(stats, stat)
|
||||
continue
|
||||
}
|
||||
stat.Size = info.Size
|
||||
stat.Pending = info.Pending
|
||||
stat.Active = info.Active
|
||||
stat.Scheduled = info.Scheduled
|
||||
stat.Retry = info.Retry
|
||||
stat.Archived = info.Archived
|
||||
stat.Completed = info.Completed
|
||||
stat.Processed = info.Processed
|
||||
stat.Failed = info.Failed
|
||||
stat.Paused = info.Paused
|
||||
stat.LatencyMs = info.Latency.Milliseconds()
|
||||
stat.MemoryUsageBytes = info.MemoryUsage
|
||||
stats = append(stats, stat)
|
||||
}
|
||||
return stats, true, nil
|
||||
}
|
||||
|
||||
// queueStateHasMatch pages through one (queue, state) list looking for a
|
||||
// task that references knowledgeID. Mirrors the delete* scanners but is
|
||||
// strictly read-only and returns early on the first hit. A backend error
|
||||
@@ -335,3 +397,12 @@ func (noopTaskInspector) HasQueuedTasksForKnowledge(
|
||||
) (bool, error) {
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// QueueStats reports "not supported" in Lite mode: there is no Redis /
|
||||
// asynq backend to inspect, so the runtime dashboard renders an
|
||||
// "unavailable in this deployment" state instead of an empty table.
|
||||
func (noopTaskInspector) QueueStats(
|
||||
ctx context.Context,
|
||||
) ([]types.QueueStat, bool, error) {
|
||||
return nil, false, nil
|
||||
}
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
package interfaces
|
||||
|
||||
import "context"
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
)
|
||||
|
||||
// TaskInspector abstracts queue inspection / cancellation against the
|
||||
// task backend. It is best-effort: implementations may scan a finite
|
||||
@@ -39,4 +43,18 @@ type TaskInspector interface {
|
||||
// always returns false — inline executors never queue, so the
|
||||
// span/updated_at checks remain authoritative there.
|
||||
HasQueuedTasksForKnowledge(ctx context.Context, knowledgeID string) (bool, error)
|
||||
|
||||
// QueueStats returns a read-only depth snapshot for every queue this
|
||||
// application enqueues into, for the System Admin runtime dashboard.
|
||||
//
|
||||
// The `supported` bool reports whether queue inspection is available
|
||||
// on the current backend: true in asynq/Redis mode, false in Lite
|
||||
// mode (no Redis) where tasks run inline and no queue exists. Callers
|
||||
// use it to render an "unavailable in this deployment" state rather
|
||||
// than an empty table.
|
||||
//
|
||||
// Best-effort: a per-queue backend error is logged and that queue is
|
||||
// surfaced as a zeroed row (so the full lane set stays visible) rather
|
||||
// than failing the whole call.
|
||||
QueueStats(ctx context.Context) (stats []types.QueueStat, supported bool, err error)
|
||||
}
|
||||
|
||||
+37
-5
@@ -4,9 +4,8 @@ package types
|
||||
// router.NewParseAsynqServer / router.NewWikiAsynqServer — a task enqueued to a
|
||||
// queue that no server subscribes to will never be consumed.
|
||||
const (
|
||||
QueueCritical = "critical"
|
||||
QueueDefault = "default"
|
||||
QueueLow = "low"
|
||||
QueueDefault = "default"
|
||||
QueueLow = "low"
|
||||
// QueueMultimodal isolates high-volume, slow VLM image tasks (OCR + caption)
|
||||
// so a single large scanned PDF (hundreds–thousands of page images) cannot
|
||||
// saturate the shared worker pool and block user-facing document parsing in
|
||||
@@ -33,6 +32,39 @@ const (
|
||||
QueueWiki = "wiki"
|
||||
)
|
||||
|
||||
// QueueStat is a read-only depth snapshot of a single asynq queue, used
|
||||
// by the System Admin runtime dashboard. Field names mirror the counts
|
||||
// exposed by asynq.QueueInfo. Pool / Weight are static metadata (which
|
||||
// worker pool drains the queue and its scheduling weight within that
|
||||
// pool) so the UI can group and explain the lanes without the frontend
|
||||
// hard-coding the topology.
|
||||
type QueueStat struct {
|
||||
Name string `json:"name"`
|
||||
// Pool is the worker pool that drains this queue: "parse" or "wiki".
|
||||
Pool string `json:"pool"`
|
||||
// Weight is the queue's scheduling weight inside its pool. Must match
|
||||
// the maps in router.NewParseAsynqServer / NewWikiAsynqServer.
|
||||
Weight int `json:"weight"`
|
||||
// Size is the total number of tasks in the queue (pending + active +
|
||||
// scheduled + retry + aggregating + archived).
|
||||
Size int `json:"size"`
|
||||
Pending int `json:"pending"`
|
||||
Active int `json:"active"`
|
||||
Scheduled int `json:"scheduled"`
|
||||
Retry int `json:"retry"`
|
||||
Archived int `json:"archived"`
|
||||
Completed int `json:"completed"`
|
||||
// Processed / Failed are today's counters (reset daily).
|
||||
Processed int `json:"processed"`
|
||||
Failed int `json:"failed"`
|
||||
// Paused reports whether the queue is paused (tasks not consumed).
|
||||
Paused bool `json:"paused"`
|
||||
// LatencyMs is the age of the oldest pending task, in milliseconds.
|
||||
LatencyMs int64 `json:"latency_ms"`
|
||||
// MemoryUsageBytes is the approximate Redis memory the queue occupies.
|
||||
MemoryUsageBytes int64 `json:"memory_usage_bytes"`
|
||||
}
|
||||
|
||||
const (
|
||||
TypeChunkExtract = "chunk:extract"
|
||||
TypeDocumentProcess = "document:process" // 文档处理任务
|
||||
@@ -216,8 +248,8 @@ type KnowledgeListDeletePayload struct {
|
||||
// KnowledgeListReparsePayload represents the batch knowledge reparse task payload
|
||||
type KnowledgeListReparsePayload struct {
|
||||
TracingContext
|
||||
TenantID uint64 `json:"tenant_id"`
|
||||
KnowledgeIDs []string `json:"knowledge_ids"`
|
||||
TenantID uint64 `json:"tenant_id"`
|
||||
KnowledgeIDs []string `json:"knowledge_ids"`
|
||||
ProcessConfig *KnowledgeProcessOverrides `json:"process_config,omitempty"`
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user