Spaces:
Build error
Build error
File size: 5,728 Bytes
4b1daed | 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 | // Package workers provides worker pool for CPU-intensive operations
package workers
import (
"context"
"runtime"
"sync"
"sync/atomic"
"time"
"go.uber.org/zap"
)
// Pool manages a pool of worker goroutines
type Pool struct {
maxWorkers int
taskQueue chan Task
workerWg sync.WaitGroup
shutdownChan chan struct{}
logger *zap.Logger
// Metrics
activeWorkers int64
completedTasks int64
failedTasks int64
queuedTasks int64
}
// Task represents a unit of work
type Task struct {
ID string
Execute func(ctx context.Context) error
OnError func(error)
Priority int
Ctx context.Context
}
// Config for worker pool
type Config struct {
MaxWorkers int
QueueSize int
Logger *zap.Logger
}
// DefaultConfig returns sensible defaults
func DefaultConfig() Config {
return Config{
MaxWorkers: runtime.NumCPU() * 2,
QueueSize: 1000,
}
}
// NewPool creates a new worker pool
func NewPool(cfg Config) *Pool {
if cfg.MaxWorkers <= 0 {
cfg.MaxWorkers = runtime.NumCPU() * 2
}
if cfg.QueueSize <= 0 {
cfg.QueueSize = 1000
}
if cfg.Logger == nil {
cfg.Logger, _ = zap.NewProduction()
}
p := &Pool{
maxWorkers: cfg.MaxWorkers,
taskQueue: make(chan Task, cfg.QueueSize),
shutdownChan: make(chan struct{}),
logger: cfg.Logger,
}
// Start workers
for i := 0; i < cfg.MaxWorkers; i++ {
p.workerWg.Add(1)
go p.worker(i)
}
p.logger.Info("worker pool started",
zap.Int("workers", cfg.MaxWorkers),
zap.Int("queue_size", cfg.QueueSize),
)
return p
}
func (p *Pool) worker(id int) {
defer p.workerWg.Done()
for {
select {
case <-p.shutdownChan:
return
case task, ok := <-p.taskQueue:
if !ok {
return
}
atomic.AddInt64(&p.activeWorkers, 1)
atomic.AddInt64(&p.queuedTasks, -1)
err := p.executeTask(task)
if err != nil {
atomic.AddInt64(&p.failedTasks, 1)
if task.OnError != nil {
task.OnError(err)
}
p.logger.Error("task failed",
zap.Int("worker_id", id),
zap.String("task_id", task.ID),
zap.Error(err),
)
} else {
atomic.AddInt64(&p.completedTasks, 1)
}
atomic.AddInt64(&p.activeWorkers, -1)
}
}
}
func (p *Pool) executeTask(task Task) (err error) {
// Recover from panics
defer func() {
if r := recover(); r != nil {
switch x := r.(type) {
case error:
err = x
default:
err = &PanicError{Value: r}
}
}
}()
ctx := task.Ctx
if ctx == nil {
ctx = context.Background()
}
return task.Execute(ctx)
}
// Submit adds a task to the pool
func (p *Pool) Submit(task Task) error {
select {
case <-p.shutdownChan:
return ErrPoolShutdown
case p.taskQueue <- task:
atomic.AddInt64(&p.queuedTasks, 1)
return nil
default:
return ErrQueueFull
}
}
// SubmitWait submits a task and waits for completion
func (p *Pool) SubmitWait(ctx context.Context, fn func(context.Context) error) error {
done := make(chan error, 1)
task := Task{
Ctx: ctx,
Execute: func(ctx context.Context) error {
err := fn(ctx)
done <- err
return err
},
}
if err := p.Submit(task); err != nil {
return err
}
select {
case err := <-done:
return err
case <-ctx.Done():
return ctx.Err()
}
}
// SubmitBatch submits multiple tasks and returns a channel for results
func (p *Pool) SubmitBatch(tasks []Task) <-chan error {
results := make(chan error, len(tasks))
go func() {
var wg sync.WaitGroup
for _, task := range tasks {
wg.Add(1)
t := task
originalExecute := t.Execute
t.Execute = func(ctx context.Context) error {
defer wg.Done()
err := originalExecute(ctx)
results <- err
return err
}
if err := p.Submit(t); err != nil {
wg.Done()
results <- err
}
}
wg.Wait()
close(results)
}()
return results
}
// Metrics returns current pool metrics
func (p *Pool) Metrics() PoolMetrics {
return PoolMetrics{
ActiveWorkers: atomic.LoadInt64(&p.activeWorkers),
QueuedTasks: atomic.LoadInt64(&p.queuedTasks),
CompletedTasks: atomic.LoadInt64(&p.completedTasks),
FailedTasks: atomic.LoadInt64(&p.failedTasks),
MaxWorkers: p.maxWorkers,
QueueCapacity: cap(p.taskQueue),
}
}
// PoolMetrics contains worker pool statistics
type PoolMetrics struct {
ActiveWorkers int64
QueuedTasks int64
CompletedTasks int64
FailedTasks int64
MaxWorkers int
QueueCapacity int
}
// Shutdown gracefully shuts down the pool
func (p *Pool) Shutdown(timeout time.Duration) error {
close(p.shutdownChan)
done := make(chan struct{})
go func() {
p.workerWg.Wait()
close(done)
}()
select {
case <-done:
close(p.taskQueue)
p.logger.Info("worker pool shutdown complete")
return nil
case <-time.After(timeout):
p.logger.Warn("worker pool shutdown timed out")
return ErrShutdownTimeout
}
}
// Resize dynamically adjusts the number of workers
func (p *Pool) Resize(newSize int) {
if newSize <= 0 || newSize == p.maxWorkers {
return
}
if newSize > p.maxWorkers {
// Add workers
for i := p.maxWorkers; i < newSize; i++ {
p.workerWg.Add(1)
go p.worker(i)
}
}
// Note: Reducing workers requires more complex logic
// For now, we only support increasing
p.maxWorkers = newSize
p.logger.Info("worker pool resized", zap.Int("new_size", newSize))
}
// Error types
var (
ErrPoolShutdown = &PoolError{Message: "worker pool is shutdown"}
ErrQueueFull = &PoolError{Message: "task queue is full"}
ErrShutdownTimeout = &PoolError{Message: "shutdown timeout exceeded"}
)
type PoolError struct {
Message string
}
func (e *PoolError) Error() string {
return e.Message
}
type PanicError struct {
Value interface{}
}
func (e *PanicError) Error() string {
return "panic in task execution"
}
|