Files
Pulse/internal/monitoring/task_queue.go
pulse-triage[bot] 17120e4c9d Keep a slow scheduled poll from taking another worker slot
Reserve each provider and connection when it leaves the queue. Periodic replanning skips that key until the worker returns, and an explicit edit or removal keeps precedence over its follow-up. Use the same ownership with local workers and with a shared process limit.

Refs: https://github.com/rcourtman/Pulse/issues/5089
Change-source: pulse-maintainer
2026-11-25 07:01:55 +00:00

332 lines
7.4 KiB
Go

package monitoring
import (
"container/heap"
"context"
"sync"
"time"
)
type claimFollowup uint8
const (
followWorkerSchedule claimFollowup = iota
followExplicitSchedule
dropWorkerSchedule
)
type scheduledTaskEntry struct {
task ScheduledTask // queued task, or the explicit successor of a claim
index int // -1 while a worker owns the entry
followup claimFollowup
}
func (e *scheduledTaskEntry) key() string {
return schedulerKey(e.task.InstanceType, e.task.InstanceName)
}
type taskHeap []*scheduledTaskEntry
func (h taskHeap) Len() int { return len(h) }
func (h taskHeap) Less(i, j int) bool {
if h[i].task.NextRun.Equal(h[j].task.NextRun) {
if h[i].task.Priority == h[j].task.Priority {
return h[i].task.InstanceName < h[j].task.InstanceName
}
return h[i].task.Priority > h[j].task.Priority
}
return h[i].task.NextRun.Before(h[j].task.NextRun)
}
func (h taskHeap) Swap(i, j int) {
h[i], h[j] = h[j], h[i]
h[i].index = i
h[j].index = j
}
func (h *taskHeap) Push(x interface{}) {
entry := x.(*scheduledTaskEntry)
entry.index = len(*h)
*h = append(*h, entry)
}
func (h *taskHeap) Pop() interface{} {
old := *h
n := len(old)
if n == 0 {
return nil
}
entry := old[n-1]
old[n-1] = nil
entry.index = -1
*h = old[:n-1]
return entry
}
// TaskQueue is a thread-safe min-heap over scheduled tasks. The index also
// holds claimed tasks, which are not part of the heap or queue snapshots.
type TaskQueue struct {
mu sync.Mutex
entries map[string]*scheduledTaskEntry
heap taskHeap
}
// NewTaskQueue constructs an empty queue.
func NewTaskQueue() *TaskQueue {
tq := &TaskQueue{
entries: make(map[string]*scheduledTaskEntry),
heap: make(taskHeap, 0),
}
heap.Init(&tq.heap)
return tq
}
// Upsert schedules an explicit request. If a worker has already claimed the
// target, retain the latest request for when that worker returns.
func (q *TaskQueue) Upsert(task ScheduledTask) {
q.upsert(task, false)
}
// upsertPlan refreshes the ordinary plan, but not the work the queue has
// already dispatched. A slow provider cannot fill a second worker slot.
func (q *TaskQueue) upsertPlan(task ScheduledTask) {
q.upsert(task, true)
}
func (q *TaskQueue) upsert(task ScheduledTask, fromPlanner bool) {
key := schedulerKey(task.InstanceType, task.InstanceName)
q.mu.Lock()
defer q.mu.Unlock()
if entry, ok := q.entries[key]; ok {
if entry.index < 0 {
if !fromPlanner {
entry.task = task
entry.followup = followExplicitSchedule
}
return
}
entry.task = task
heap.Fix(&q.heap, entry.index)
return
}
entry := &scheduledTaskEntry{task: task}
heap.Push(&q.heap, entry)
q.entries[key] = entry
}
// completeClaim returns ownership and optionally queues its successor in the
// same critical section. An explicit edit or removal made during the claim
// takes precedence over the returning worker's normal schedule.
func (q *TaskQueue) completeClaim(task, next ScheduledTask, scheduled bool) {
key := schedulerKey(task.InstanceType, task.InstanceName)
q.mu.Lock()
defer q.mu.Unlock()
entry, ok := q.entries[key]
if !ok || entry.index >= 0 {
return
}
switch entry.followup {
case followExplicitSchedule:
// Upsert has already stored the replacement in the claimed entry.
case followWorkerSchedule:
if !scheduled {
delete(q.entries, key)
return
}
entry.task = next
case dropWorkerSchedule:
delete(q.entries, key)
return
}
entry.followup = followWorkerSchedule
heap.Push(&q.heap, entry)
}
// Get returns the queued task for an instance, if present.
func (q *TaskQueue) Get(instanceType InstanceType, instance string) (ScheduledTask, bool) {
key := schedulerKey(instanceType, instance)
q.mu.Lock()
defer q.mu.Unlock()
entry, ok := q.entries[key]
if !ok || entry.index < 0 {
return ScheduledTask{}, false
}
return entry.task, true
}
// Remove deletes a queued task or cancels the successor of a claimed task.
func (q *TaskQueue) Remove(instanceType InstanceType, instance string) {
key := schedulerKey(instanceType, instance)
q.mu.Lock()
defer q.mu.Unlock()
entry, ok := q.entries[key]
if !ok {
return
}
if entry.index < 0 {
entry.followup = dropWorkerSchedule
return
}
heap.Remove(&q.heap, entry.index)
delete(q.entries, key)
}
// WaitNext blocks until a task is due or context is cancelled. A successful
// caller owns the target until it calls completeClaim, even after a deadline.
func (q *TaskQueue) WaitNext(ctx context.Context) (ScheduledTask, bool) {
var (
timer *time.Timer
resetTimer = func(d time.Duration) <-chan time.Time {
if d <= 0 {
d = time.Millisecond
}
if timer == nil {
timer = time.NewTimer(d)
return timer.C
}
if !timer.Stop() {
select {
case <-timer.C:
default:
}
}
timer.Reset(d)
return timer.C
}
stopTimer = func() {
if timer == nil {
return
}
if !timer.Stop() {
select {
case <-timer.C:
default:
}
}
}
)
defer stopTimer()
for {
select {
case <-ctx.Done():
return ScheduledTask{}, false
default:
}
q.mu.Lock()
if len(q.heap) == 0 {
q.mu.Unlock()
timerCh := resetTimer(100 * time.Millisecond)
select {
case <-ctx.Done():
return ScheduledTask{}, false
case <-timerCh:
continue
}
}
entry := q.heap[0]
delay := time.Until(entry.task.NextRun)
if delay <= 0 {
heap.Pop(&q.heap)
task := entry.task
q.mu.Unlock()
return task, true
}
q.mu.Unlock()
if delay > 250*time.Millisecond {
delay = 250 * time.Millisecond
}
timerCh := resetTimer(delay)
select {
case <-ctx.Done():
return ScheduledTask{}, false
case <-timerCh:
}
}
}
// Size returns the number of tasks currently queued.
func (q *TaskQueue) Size() int {
q.mu.Lock()
defer q.mu.Unlock()
return len(q.heap)
}
// QueueSnapshot represents the current state of the task queue.
type QueueSnapshot struct {
Depth int `json:"depth"`
DueWithinSeconds int `json:"dueWithinSeconds"`
PerType map[string]int `json:"perType"`
}
func emptyQueueSnapshot() QueueSnapshot {
return QueueSnapshot{
PerType: map[string]int{},
}
}
// Snapshot returns a snapshot of the queue state for API exposure.
func (q *TaskQueue) Snapshot() QueueSnapshot {
if q == nil {
return emptyQueueSnapshot()
}
q.mu.Lock()
defer q.mu.Unlock()
snapshot := emptyQueueSnapshot()
snapshot.Depth = len(q.heap)
now := time.Now()
for _, entry := range q.heap {
typeStr := string(entry.task.InstanceType)
snapshot.PerType[typeStr]++
if entry.task.NextRun.Sub(now) <= 12*time.Second {
snapshot.DueWithinSeconds++
}
}
return snapshot
}
// DeadLetterTask represents a task in the dead-letter queue.
type DeadLetterTask struct {
Instance string `json:"instance"`
Type string `json:"type"`
NextRun time.Time `json:"nextRun"`
LastError string `json:"lastError,omitempty"`
Failures int `json:"failures"`
}
// PeekAll returns up to 'limit' dead-letter tasks for inspection.
func (q *TaskQueue) PeekAll(limit int) []DeadLetterTask {
q.mu.Lock()
defer q.mu.Unlock()
if limit <= 0 || limit > len(q.heap) {
limit = len(q.heap)
}
result := make([]DeadLetterTask, 0, limit)
for i := 0; i < limit && i < len(q.heap); i++ {
entry := q.heap[i]
result = append(result, DeadLetterTask{
Instance: entry.task.InstanceName,
Type: string(entry.task.InstanceType),
NextRun: entry.task.NextRun,
Failures: 0, // will be populated by Monitor
})
}
return result
}