-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpooler.go
3112 lines (2673 loc) · 85 KB
/
pooler.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package retrypool
import (
"context"
"errors"
"fmt"
"log/slog"
"math/rand"
"reflect"
"runtime"
"sort"
"sync"
"sync/atomic"
"time"
"github.com/sasha-s/go-deadlock"
"golang.org/x/time/rate"
)
/// Pool
/// - 3 core components: Runner (run() or runWorker()), TaskQueue, Worker
/// - each doesn't know about the other, the pool manages the interactions
/// Worker
/// - Start: initial state, accept new tasks, queue is open, processing tasks
/// - Pause: won't accept new tasks, queue tasks are redistributed to other workers (if zero workers then to deadtasks), finish current task (might be retried or go to deadtasks), out of any operations, paused while triggering OnPause
/// - Resume: accept new tasks, queue is open again, continue processing, resumed while triggering OnResume
/// - Remove: no more new tasks, queue tasks are redistribute to other workers (if zero workers then to deadtasks), finish current task (might be retried or go to deadtasks), out of any operations, removed from the Pool while triggering OnRemove
// Initialize deadlock detection
func init() {
// ATTENTION TO MYSELF FROM THE FUTURE
// Also see that we commented all the logs, it's on purpose for the performances (for now we mogged the old retrypool).
// DO NOT REMOVE THAT
// When you're development and debugging, you MUST replace all `sync.` with their `deadlock.` counterparts to allow you to detect deadlocks!!
deadlock.Opts.DeadlockTimeout = time.Second * 2
deadlock.Opts.OnPotentialDeadlock = func() {
fmt.Println("Potential deadlock detected")
buf := make([]byte, 1<<16)
n := runtime.Stack(buf, true)
fmt.Printf("Stack trace:\n%s\n", string(buf[:n]))
}
}
// Worker interface for task processing
type Worker[T any] interface {
Run(ctx context.Context, data T) error
}
type WorkerFactory[T any] func() Worker[T]
// TaskState represents the state of a task
type TaskState int
const (
TaskStateCreated TaskState = iota
TaskStatePending
TaskStateQueued
TaskStateRunning
TaskStateCompleted
TaskStateFailed
TaskStateDead
)
func (s TaskState) String() string {
switch s {
case TaskStateCreated:
return "Created"
case TaskStatePending:
return "Pending"
case TaskStateQueued:
return "Queued"
case TaskStateRunning:
return "Running"
case TaskStateCompleted:
return "Completed"
case TaskStateFailed:
return "Failed"
case TaskStateDead:
return "Dead"
default:
return "Unknown"
}
}
// TaskAction represents the action to take for a failed task
type TaskAction int
const (
TaskActionRetry TaskAction = iota + 1 // Task will retry using its own state
TaskActionForceRetry // Force a retry, ignoring retry limits
TaskActionRemove // Remove the task and recycle resources
TaskActionAddToDeadTasks // Add the task to dead tasks
)
// NoWorkerPolicy defines the behavior when no workers are available
type NoWorkerPolicy int
const (
NoWorkerPolicyReject NoWorkerPolicy = iota // Default behavior: Reject the task submission with an error
NoWorkerPolicyAddToDeadTasks // Add the task to dead tasks
)
// Predefined errors
var (
ErrPoolClosed = errors.New("pool is closed")
ErrRateLimitExceeded = errors.New("rate limit exceeded")
ErrNoWorkersAvailable = errors.New("no workers available")
ErrInvalidWorkerID = errors.New("invalid worker ID")
ErrMaxQueueSizeExceeded = errors.New("max queue size exceeded")
ErrTaskTimeout = errors.New("task timeout")
)
// TaskStateTransition represents a state change
type TaskStateTransition[T any] struct {
FromState TaskState
ToState TaskState
Task *Task[T]
Reason string
Timestamp time.Time
}
// stateMetrics tracks counts for each state
type stateMetrics struct {
counts map[TaskState]*atomic.Int64
mu sync.RWMutex
callbacks map[TaskState][]func(interface{})
}
var allTaskStates = []TaskState{
TaskStateCreated,
TaskStatePending,
TaskStateQueued,
TaskStateRunning,
TaskStateCompleted,
TaskStateFailed,
TaskStateDead,
}
func newStateMetrics() *stateMetrics {
sm := &stateMetrics{
counts: make(map[TaskState]*atomic.Int64),
callbacks: make(map[TaskState][]func(interface{})),
}
for _, state := range allTaskStates {
sm.counts[state] = &atomic.Int64{}
}
return sm
}
type taskQueues[T any] struct {
mu deadlock.Mutex
queues map[int]TaskQueue[T]
}
func newTaskQueues[T any]() *taskQueues[T] {
return &taskQueues[T]{
queues: make(map[int]TaskQueue[T]),
}
}
// Methods for the taskQueues type
func (tq *taskQueues[T]) get(id int) (TaskQueue[T], bool) {
tq.mu.Lock()
defer tq.mu.Unlock()
q, ok := tq.queues[id]
return q, ok
}
func (tq *taskQueues[T]) set(id int, queue TaskQueue[T]) {
tq.mu.Lock()
defer tq.mu.Unlock()
tq.queues[id] = queue
}
func (tq *taskQueues[T]) delete(id int) {
tq.mu.Lock()
defer tq.mu.Unlock()
delete(tq.queues, id)
}
func (tq *taskQueues[T]) getOrCreate(id int, creator func() TaskQueue[T]) TaskQueue[T] {
tq.mu.Lock()
defer tq.mu.Unlock()
if q, ok := tq.queues[id]; ok {
return q
}
q := creator()
tq.queues[id] = q
return q
}
func (tq *taskQueues[T]) range_(f func(id int, q TaskQueue[T]) bool) {
tq.mu.Lock()
defer tq.mu.Unlock()
for id, q := range tq.queues {
if !f(id, q) {
break
}
}
}
// Pool manages a set of workers and tasks
type Pool[T any] struct {
workers map[int]*workerState[T]
nextWorkerID int
taskQueues *taskQueues[T]
taskQueueType TaskQueueType
mu deadlock.Mutex
cond *sync.Cond
stopped bool
ctx context.Context
cancel context.CancelFunc
config Config[T]
metrics Metrics
limiter *rate.Limiter
taskPool sync.Pool
deadTasks []*DeadTask[T]
deadMu deadlock.Mutex
roundRobinIndex atomic.Int64
totalProcessing atomic.Int64
totalQueueSize atomic.Int64
availableWorkers atomic.Int64
deadTaskNotifications chan int
logger Logger
stateMetrics *stateMetrics
workerQueues map[int]*atomic.Int64
queueMu sync.RWMutex
}
// New initializes the Pool with given workers and options
func New[T any](ctx context.Context, workers []Worker[T], options ...Option[T]) *Pool[T] {
ctx, cancel := context.WithCancel(ctx)
pool := &Pool[T]{
workers: make(map[int]*workerState[T]),
nextWorkerID: 0,
taskQueues: newTaskQueues[T](),
taskQueueType: TaskQueueTypeSlice, // default one // TODO: make this configurable
config: newDefaultConfig[T](),
ctx: ctx,
cancel: cancel,
logger: NewLogger(slog.LevelDebug),
deadTaskNotifications: make(chan int, 1000), // todo: make this configurable
stateMetrics: newStateMetrics(),
workerQueues: make(map[int]*atomic.Int64),
}
pool.logger.Disable()
pool.logger.Info(ctx, "Creating new Pool", "workers_count", len(workers))
for _, option := range options {
option(pool)
}
pool.logger.Debug(ctx, "Pool configuration", "config", pool.config)
pool.cond = sync.NewCond(&pool.mu)
pool.taskPool = sync.Pool{
New: func() interface{} {
return &Task[T]{}
},
}
// Start dead task handler if callback is set
if pool.config.onDeadTask != nil {
go pool.handleDeadTaskNotifications(ctx)
}
for _, worker := range workers {
// In asynchronous mode, that function will start the worker in a new goroutine
err := pool.Add(worker, nil)
if err != nil {
pool.logger.Error(ctx, "Failed to add worker", "error", err)
}
}
// In synchronous mode, we want the Pool to have ONE goroutine but it manage ALL the workers and ALL the same rules
if !pool.config.async {
pool.logger.Debug(ctx, "Starting pool in synchronous mode")
go pool.run()
}
return pool
}
func (p *Pool[T]) IsAsync() bool {
return p.config.async
}
func (p *Pool[T]) IsRoundRobin() bool {
return p.config.roundRobin
}
// If you're using round robin, it might comes handy to know the current index
func (p *Pool[T]) RoundRobinIndex() int {
return int(p.roundRobinIndex.Load())
}
// SetOnTaskSuccess allows setting the onTaskSuccess handler after pool creation
func (p *Pool[T]) SetOnTaskSuccess(handler func(data T)) {
p.mu.Lock()
defer p.mu.Unlock()
p.config.onTaskSuccess = handler
}
// SetOnTaskFailure allows setting the onTaskFailure handler after pool creation
func (p *Pool[T]) SetOnTaskFailure(handler func(data T, err error) TaskAction) {
p.mu.Lock()
defer p.mu.Unlock()
p.config.onTaskFailure = handler
}
// SetOnTaskAttempt allows setting the onTaskAttempt handler after pool creation
func (p *Pool[T]) SetOnTaskAttempt(handler func(task *Task[T], workerID int)) {
p.mu.Lock()
defer p.mu.Unlock()
p.config.onTaskAttempt = handler
}
type MetricsSnapshot struct {
TasksSubmitted int64
TasksProcessed int64
TasksSucceeded int64
TasksFailed int64
DeadTasks int64
}
func (p *Pool[T]) GetMetricsSnapshot() MetricsSnapshot {
return MetricsSnapshot{
TasksSubmitted: p.metrics.TasksSubmitted.Load(),
TasksProcessed: p.metrics.TasksProcessed.Load(),
TasksSucceeded: p.metrics.TasksSucceeded.Load(),
TasksFailed: p.metrics.TasksFailed.Load(),
DeadTasks: p.metrics.DeadTasks.Load(),
}
}
// NewWorkerID generates a new worker ID
func (p *Pool[T]) NewWorkerID() int {
p.mu.Lock()
defer p.mu.Unlock()
workerID := p.nextWorkerID
p.nextWorkerID++
return workerID
}
// Option type for configuring the Pool
type Option[T any] func(*Pool[T])
// WithLogger sets the logger for the pool and all its components
func WithLogger[T any](logger Logger) Option[T] {
return func(p *Pool[T]) {
p.logger = logger
}
}
// WithAttempts sets the maximum number of attempts
func WithAttempts[T any](attempts int) Option[T] {
return func(p *Pool[T]) {
p.logger.Debug(p.ctx, "Setting attempts", "attempts", attempts)
p.config.attempts = attempts
}
}
// WithOnPanic sets a custom panic handler for the pool
func WithOnPanic[T any](handler func(recovery interface{}, stackTrace string)) Option[T] {
return func(p *Pool[T]) {
p.logger.Debug(p.ctx, "Setting OnPanic handler")
p.config.onPanic = handler
}
}
// WithOnWorkerPanic sets a custom panic handler for workers
func WithOnWorkerPanic[T any](handler func(workerID int, recovery interface{}, stackTrace string)) Option[T] {
return func(p *Pool[T]) {
p.logger.Debug(p.ctx, "Setting OnWorkerPanic handler")
p.config.onWorkerPanic = handler
}
}
// WithDelay sets the delay between retries
func WithDelay[T any](delay time.Duration) Option[T] {
return func(p *Pool[T]) {
p.logger.Debug(p.ctx, "Setting delay", "delay", delay)
p.config.delay = delay
}
}
// WithMaxDelay sets the maximum delay between retries
func WithMaxDelay[T any](maxDelay time.Duration) Option[T] {
return func(p *Pool[T]) {
p.logger.Debug(p.ctx, "Setting max delay", "max_delay", maxDelay)
p.config.maxDelay = maxDelay
}
}
// WithMaxJitter sets the maximum jitter for delay between retries
func WithMaxJitter[T any](maxJitter time.Duration) Option[T] {
return func(p *Pool[T]) {
p.logger.Debug(p.ctx, "Setting max jitter", "max_jitter", maxJitter)
p.config.maxJitter = maxJitter
}
}
// WithDelayFunc sets a custom function to determine the delay between retries
func WithDelayFunc[T any](delayFunc DelayFunc[T]) Option[T] {
return func(p *Pool[T]) {
p.logger.Debug(p.ctx, "Setting DelayFunc")
p.config.delayFunc = delayFunc
}
}
// WithRetryPolicy sets a custom retry policy for the pool
func WithRetryPolicy[T any](policy RetryPolicy[T]) Option[T] {
return func(p *Pool[T]) {
p.logger.Debug(p.ctx, "Setting RetryPolicy")
p.config.retryPolicy = policy
}
}
// WithMaxQueueSize sets the maximum queue size for the pool
func WithMaxQueueSize[T any](size int) Option[T] {
return func(p *Pool[T]) {
p.logger.Debug(p.ctx, "Setting max queue size", "size", size)
p.config.maxQueueSize = size
}
}
// WithOnDeadTask sets a callback when a task is added to dead tasks
func WithOnDeadTask[T any](handler func(deadTaskIndex int)) Option[T] {
return func(p *Pool[T]) {
p.logger.Debug(p.ctx, "Setting OnDeadTask handler")
p.config.onDeadTask = handler
}
}
// WithDeadTasksLimit sets the limit for dead tasks
func WithDeadTasksLimit[T any](limit int) Option[T] {
return func(p *Pool[T]) {
p.logger.Debug(p.ctx, "Setting dead tasks limit", "limit", limit)
p.config.deadTasksLimit = limit
}
}
// WithIfRetry sets the function to determine if an error is retryable
func WithIfRetry[T any](retryIf func(err error) bool) Option[T] {
return func(p *Pool[T]) {
p.logger.Debug(p.ctx, "Setting retry condition function")
p.config.retryIf = retryIf
}
}
// WithNoWorkerPolicy sets the policy when no workers are available
func WithNoWorkerPolicy[T any](policy NoWorkerPolicy) Option[T] {
return func(p *Pool[T]) {
p.logger.Debug(p.ctx, "Setting NoWorkerPolicy", "policy", policy)
p.config.noWorkerPolicy = policy
}
}
// WithRateLimit sets the rate limit for task submissions. In async mode,
// the first burst of tasks (up to 2 * number of workers) may be processed
// immediately before the rate limit takes full effect. This provides faster
// startup while maintaining the desired steady-state rate.
func WithRateLimit[T any](rps float64) Option[T] {
return func(p *Pool[T]) {
p.logger.Debug(p.ctx, "Setting rate limit", "requests_per_second", rps)
// Allow burst size to be the number of workers * 2, minimum of 1
burstSize := len(p.workers) * 2
if burstSize < 1 {
burstSize = 1
}
p.limiter = rate.NewLimiter(rate.Limit(rps), burstSize)
}
}
// WithOnTaskSuccess sets a callback for successful task completion
func WithOnTaskSuccess[T any](handler func(data T)) Option[T] {
return func(p *Pool[T]) {
p.logger.Debug(p.ctx, "Setting OnTaskSuccess handler")
p.config.onTaskSuccess = handler
}
}
// WithOnTaskFailure sets a callback for task failure
func WithOnTaskFailure[T any](handler func(data T, err error) TaskAction) Option[T] {
return func(p *Pool[T]) {
p.logger.Debug(p.ctx, "Setting OnTaskFailure handler")
p.config.onTaskFailure = handler
}
}
// WithSynchronousMode sets the pool to synchronous mode
func WithSynchronousMode[T any]() Option[T] {
return func(p *Pool[T]) {
p.logger.Debug(p.ctx, "Setting pool to synchronous mode")
p.config.async = false
}
}
// WithRoundRobinDistribution sets the task distribution to round-robin
func WithRoundRobinDistribution[T any]() Option[T] {
return func(p *Pool[T]) {
p.logger.Debug(p.ctx, "Setting round-robin task distribution")
p.config.roundRobin = true
}
}
func WithLoopTicker[T any](d time.Duration) Option[T] {
return func(p *Pool[T]) {
p.logger.Debug(p.ctx, "Setting loop ticker", "duration", d)
p.config.loopTicker = d
}
}
// WithTaskQueueType sets the type of task queue
func WithTaskQueueType[T any](queueType TaskQueueType) Option[T] {
return func(p *Pool[T]) {
p.logger.Debug(p.ctx, "Setting task queue type", "queue_type", queueType)
p.taskQueueType = queueType
}
}
// WithOnTaskAttempt sets a callback that is called whenever a worker attempts a task
func WithOnTaskAttempt[T any](handler func(task *Task[T], workerID int)) Option[T] {
return func(p *Pool[T]) {
p.logger.Debug(p.ctx, "Setting OnTaskAttempt handler")
p.config.onTaskAttempt = handler
}
}
// updateRateLimiterBurst updates the rate limiter's burst size based on active workers
func (p *Pool[T]) updateRateLimiterBurst() {
if p.limiter == nil {
return
}
// Calculate active workers
activeWorkers := int(p.availableWorkers.Load())
burstSize := activeWorkers * 2
if burstSize < 1 {
burstSize = 1
}
currentRate := p.limiter.Limit()
p.limiter = rate.NewLimiter(currentRate, burstSize)
p.logger.Debug(p.ctx, "Updated rate limiter burst size", "active_workers", activeWorkers, "burst_size", burstSize)
}
// Config holds configurations for the pool
type Config[T any] struct {
attempts int
delay time.Duration
maxDelay time.Duration
maxJitter time.Duration
delayFunc DelayFunc[T]
retryPolicy RetryPolicy[T]
maxQueueSize int
onPanic func(recovery interface{}, stackTrace string)
onWorkerPanic func(workerID int, recovery interface{}, stackTrace string)
onTaskSuccess func(data T)
onTaskFailure func(data T, err error) TaskAction
onDeadTask func(deadTaskIndex int)
onTaskAttempt func(task *Task[T], workerID int)
deadTasksLimit int
retryIf func(err error) bool
roundRobin bool
noWorkerPolicy NoWorkerPolicy
loopTicker time.Duration
async bool
}
// newDefaultConfig initializes default configurations
func newDefaultConfig[T any]() Config[T] {
return Config[T]{
attempts: -1, // Unlimited attempts by default
delay: time.Millisecond,
retryPolicy: nil,
retryIf: func(err error) bool {
return err != nil
},
async: true,
noWorkerPolicy: NoWorkerPolicyReject,
}
}
// DelayFunc defines a function to calculate delay before retrying a task
type DelayFunc[T any] func(retries int, err error, config *Config[T]) time.Duration
// RetryPolicy defines an interface for retry policies
type RetryPolicy[T any] interface {
ComputeDelay(retries int, err error, config *Config[T]) time.Duration
}
// ExponentialBackoffRetryPolicy implements exponential backoff with jitter
type ExponentialBackoffRetryPolicy[T any] struct {
BaseDelay time.Duration
MaxDelay time.Duration
MaxJitter time.Duration
}
// ComputeDelay computes the delay using exponential backoff with jitter
func (p ExponentialBackoffRetryPolicy[T]) ComputeDelay(retries int, err error, config *Config[T]) time.Duration {
delay := p.BaseDelay * (1 << retries)
if delay > p.MaxDelay {
delay = p.MaxDelay
}
jitter := time.Duration(rand.Int63n(int64(p.MaxJitter)))
return delay + jitter
}
// FixedDelayRetryPolicy implements a fixed delay between retries
type FixedDelayRetryPolicy[T any] struct {
Delay time.Duration
MaxJitter time.Duration
}
// ComputeDelay computes the delay using fixed delay with jitter
func (p FixedDelayRetryPolicy[T]) ComputeDelay(retries int, err error, config *Config[T]) time.Duration {
if p.MaxJitter <= 0 {
return p.Delay
}
jitter := time.Duration(rand.Int63n(int64(p.MaxJitter)))
return p.Delay + jitter
}
// Metrics holds metrics for the pool
type Metrics struct {
TasksSubmitted atomic.Int64
TasksProcessed atomic.Int64
TasksSucceeded atomic.Int64
TasksFailed atomic.Int64
DeadTasks atomic.Int64
}
// Task represents a task in the pool
type Task[T any] struct {
mu deadlock.Mutex
data T
retries int
totalDuration time.Duration
attemptStartTime time.Time
durations []time.Duration
errors []error
deadReason string
state TaskState
totalTimeout time.Duration
attemptTimeout time.Duration
notifiedProcessed *ProcessedNotification
notifiedQueued *QueuedNotification
queuedCb func()
runningCb func()
processedCb func()
immediateRetry bool
bounceRetry bool
attemptedWorkers map[int]struct{} // Track workers that attempted this task
lastWorkerID int // Last worker that processed this task
queuedAt []time.Time // When task entered different queues
processedAt []time.Time // When task started processing
stateHistory []*TaskStateTransition[T]
}
func (t *Task[T]) GetData() T {
t.mu.Lock()
defer t.mu.Unlock()
return t.data
}
func (t *Task[T]) GetAttemptedWorkers() []int {
t.mu.Lock()
defer t.mu.Unlock()
ids := make([]int, 0, len(t.attemptedWorkers))
for id := range t.attemptedWorkers {
ids = append(ids, id)
}
return ids
}
// GetFreeWorkers returns a list of worker IDs that have no tasks in their queue
func (p *Pool[T]) GetFreeWorkers() []int {
p.mu.Lock()
defer p.mu.Unlock()
freeWorkers := []int{}
for id, state := range p.workers {
state.mu.Lock()
isPaused := state.paused.Load()
isRemoved := state.removed.Load()
hasCurrentTask := state.currentTask != nil
state.mu.Unlock()
if !isPaused && !isRemoved {
if queue, ok := p.taskQueues.get(id); ok && queue.Length() == 0 && !hasCurrentTask {
freeWorkers = append(freeWorkers, id)
}
}
}
return freeWorkers
}
// SubmitToFreeWorker attempts to submit a task to a free worker
func (p *Pool[T]) SubmitToFreeWorker(taskData T, options ...TaskOption[T]) error {
// Get the list of free workers without holding the lock
freeWorkers := p.GetFreeWorkers()
p.mu.Lock()
defer p.mu.Unlock()
if len(freeWorkers) == 0 {
p.logger.Warn(p.ctx, "No free workers available for task submission", "task_data", taskData)
return ErrNoWorkersAvailable
}
// Select a random free worker
selectedWorkerID := freeWorkers[rand.Intn(len(freeWorkers))]
q := p.taskQueues.getOrCreate(selectedWorkerID, func() TaskQueue[T] {
return p.NewTaskQueue(p.taskQueueType)
})
task := p.taskPool.Get().(*Task[T])
*task = Task[T]{data: taskData, state: TaskStateCreated}
for _, option := range options {
option(task)
}
if err := p.TransitionTaskState(task, TaskStatePending, "SubmittedToFreeWorker"); err != nil {
return err
}
p.logger.Debug(p.ctx, "Submitting task to free worker", "worker_id", selectedWorkerID, "task_data", taskData)
p.metrics.TasksSubmitted.Add(1)
p.UpdateTotalQueueSize(1)
q.Enqueue(task)
p.UpdateWorkerQueueSize(selectedWorkerID, 1)
if task.notifiedQueued != nil {
task.notifiedQueued.Notify()
}
if task.queuedCb != nil {
task.queuedCb()
}
if err := p.TransitionTaskState(task, TaskStateQueued, "Task enqueued to free worker"); err != nil {
return err
}
// Signal differently based on mode
if p.config.async {
p.cond.Broadcast()
} else {
p.cond.Signal()
}
return nil
}
// TransitionTaskState handles state changes and maintains counts
func (p *Pool[T]) TransitionTaskState(task *Task[T], to TaskState, reason string) error {
task.mu.Lock()
from := task.state
if !isValidTransition(from, to) {
task.mu.Unlock()
return fmt.Errorf("invalid state transition from %s to %s", from, to)
}
transition := &TaskStateTransition[T]{
FromState: from,
ToState: to,
Task: task,
Reason: reason,
Timestamp: time.Now(),
}
task.state = to
task.stateHistory = append(task.stateHistory, transition)
task.mu.Unlock()
fromCounter, fromExists := p.stateMetrics.counts[from]
if !fromExists {
return fmt.Errorf("stateMetrics.counts does not have from state: %v", from)
}
fromCounter.Add(-1)
toCounter, toExists := p.stateMetrics.counts[to]
if !toExists {
return fmt.Errorf("stateMetrics.counts does not have to state: %v", to)
}
toCounter.Add(1)
p.stateMetrics.mu.RLock()
if callbacks, exists := p.stateMetrics.callbacks[to]; exists {
for _, cb := range callbacks {
go cb(transition)
}
}
p.stateMetrics.mu.RUnlock()
return nil
}
func isValidTransition(from, to TaskState) bool {
switch from {
case TaskStateCreated:
return to == TaskStatePending || to == TaskStateDead
case TaskStatePending:
return to == TaskStateQueued || to == TaskStateDead
case TaskStateQueued:
return to == TaskStateRunning || to == TaskStateDead
case TaskStateRunning:
return to == TaskStateCompleted || to == TaskStateFailed || to == TaskStateDead
case TaskStateFailed:
return to == TaskStateQueued || to == TaskStateDead
case TaskStateCompleted, TaskStateDead:
return false
default:
return false
}
}
// DeadTask represents a task that has failed permanently
type DeadTask[T any] struct {
Data T
Retries int
TotalDuration time.Duration
Errors []error
Reason string
StateHistory []*TaskStateTransition[T]
}
// Worker interface for task processing
// Already defined earlier
// TaskOption functions for configuring individual tasks
type TaskOption[T any] func(*Task[T])
// WithImmediateRetry allows the submitted task to retry immediately
func WithImmediateRetry[T any]() TaskOption[T] {
return func(t *Task[T]) {
t.immediateRetry = true
}
}
// WithBounceRetry enables retry on different workers
func WithBounceRetry[T any]() TaskOption[T] {
return func(t *Task[T]) {
t.bounceRetry = true
t.attemptedWorkers = make(map[int]struct{})
}
}
// WithDuration sets a per-attempt time limit for the task
func WithDuration[T any](d time.Duration) TaskOption[T] {
return func(t *Task[T]) {
t.attemptTimeout = d
}
}
// WithTimeout sets a total time limit for the task
func WithTimeout[T any](d time.Duration) TaskOption[T] {
return func(t *Task[T]) {
t.totalTimeout = d
}
}
// WithProcessedNotification sets a notification for when a task is processed
func WithProcessedNotification[T any](n *ProcessedNotification) TaskOption[T] {
return func(t *Task[T]) {
t.notifiedProcessed = n
}
}
// WithQueuedNotification sets a notification for when a task is queued
func WithQueuedNotification[T any](n *QueuedNotification) TaskOption[T] {
return func(t *Task[T]) {
t.notifiedQueued = n
}
}
// WithQueuedCb sets a callback for when a task is queued
func WithQueuedCb[T any](cb func()) TaskOption[T] {
return func(t *Task[T]) {
t.queuedCb = cb
}
}
// WithProcessedCb sets a callback for when a task is processed
func WithProcessedCb[T any](cb func()) TaskOption[T] {
return func(t *Task[T]) {
t.processedCb = cb
}
}
// WithRunningCb sets a callback for when a task is running
func WithRunningCb[T any](cb func()) TaskOption[T] {
return func(t *Task[T]) {
t.runningCb = cb
}
}
// Submit allows the developer to send data directly without pre-allocation.
func (p *Pool[T]) Submit(data T, options ...TaskOption[T]) error {
if p.availableWorkers.Load() == 0 {
p.logger.Error(p.ctx, "Attempted to submit task with no workers available")
switch p.config.noWorkerPolicy {
case NoWorkerPolicyAddToDeadTasks:
p.logger.Warn(p.ctx, "No workers available, adding task to dead tasks")
t := p.taskPool.Get().(*Task[T])
*t = Task[T]{data: data}
t.deadReason = "No workers available"
p.addDeadTask(t)
return nil
default:
return ErrNoWorkersAvailable
}
}
if p.limiter != nil {
if err := p.limiter.Wait(p.ctx); err != nil {
p.logger.Warn(p.ctx, "Rate limit wait failed", "error", err)
return ErrRateLimitExceeded
}
}
p.mu.Lock()
defer p.mu.Unlock()
if p.config.maxQueueSize > 0 && p.metrics.TasksSubmitted.Load()-p.metrics.TasksSucceeded.Load()-p.DeadTaskCount() >= int64(p.config.maxQueueSize) {
p.logger.Warn(p.ctx, "Max queue size exceeded")
return ErrMaxQueueSizeExceeded
}
t := p.taskPool.Get().(*Task[T])
*t = Task[T]{data: data, state: TaskStateCreated}
for _, option := range options {
option(t)
}
if err := p.TransitionTaskState(t, TaskStatePending, "Submitted"); err != nil {
return err
}
p.metrics.TasksSubmitted.Add(1)
p.UpdateTotalQueueSize(1)
err := p.submitTask(t)
if err != nil {
p.logger.Warn(p.ctx, "Submit failed", "error", err)
return err
}
return nil
}
// submitTask submits a task to the pool
func (p *Pool[T]) submitTask(task *Task[T]) error {
if p.stopped {
p.logger.Error(p.ctx, "Attempted to submit task to stopped pool", "task_data", task.data)
return ErrPoolClosed
}
if len(p.workers) == 0 {
p.logger.Error(p.ctx, "Attempted to submit task with no workers available", "task_data", task.data)
return ErrNoWorkersAvailable
}
p.logger.Debug(p.ctx, "Submitting task", "task_data", task.data, "immediate_retry", task.immediateRetry, "bounce_retry", task.bounceRetry)
selectedWorkerID := p.selectWorkerForTask(task)
if selectedWorkerID == -1 {
// No suitable worker found
if task.bounceRetry {
p.logger.Debug(p.ctx, "All workers attempted, resetting attempted workers list", "task_data", task.data)
task.attemptedWorkers = make(map[int]struct{})
selectedWorkerID = p.selectWorkerForTask(task)
}
if selectedWorkerID == -1 {
p.logger.Error(p.ctx, "No available workers for task", "task_data", task.data)
return ErrNoWorkersAvailable
}
}
p.logger.Debug(p.ctx, "Selected worker for task", "worker_id", selectedWorkerID)
q := p.taskQueues.getOrCreate(selectedWorkerID, func() TaskQueue[T] {
return p.NewTaskQueue(p.taskQueueType)
})
// Record when the task is queued
task.mu.Lock()
task.queuedAt = append(task.queuedAt, time.Now())