Repository navigation
Expand file tree
/
Copy pathserver.go
More file actions
90 lines (76 loc) · 2.14 KB
/
Copy pathserver.go
File metadata and controls
90 lines (76 loc) · 2.14 KB
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
package gopherqueue
import (
"context"
"errors"
"log"
"sync"
)
// Server represents the main GopherQueue worker engine orchestrator.
type Server struct {
cfg *Config
registry *HandlerRegistry
pool *WorkerPool
chain Chain
mu sync.Mutex
running bool
}
// NewServer initializes a new Server instance with functional options.
func NewServer(opts ...Option) *Server {
cfg := defaultConfig()
for _, opt := range opts {
opt(cfg)
}
return &Server{
cfg: cfg,
registry: NewHandlerRegistry(),
}
}
// Register registers a job handler function for a specific job type.
func (s *Server) Register(jobType string, fn func(ctx context.Context, job *Job) error) {
s.mu.Lock()
defer s.mu.Unlock()
s.registry.Register(jobType, func(ctx context.Context, job *Job) error {
pipeline := s.chain.Then(HandlerFunc(fn))
return pipeline.ProcessJob(ctx, job)
})
}
// Use appends one or more middlewares to the server's global middleware pipeline.
func (s *Server) Use(middlewares ...MiddlewareFunc) {
s.mu.Lock()
defer s.mu.Unlock()
s.chain = s.chain.Append(middlewares...)
}
// Run starts the worker pool and blocks until the context is cancelled or Shutdown is called.
func (s *Server) Run(ctx context.Context) error {
s.mu.Lock()
if s.running {
s.mu.Unlock()
return errors.New("gopherqueue: server is already running")
}
if s.cfg.Storage == nil {
s.mu.Unlock()
return errors.New("gopherqueue: storage engine is required")
}
s.running = true
s.mu.Unlock()
log.Printf("[GopherQueue Server] Starting engine on queue '%s' with %d workers...", s.cfg.QueueName, s.cfg.Concurrency)
s.pool = NewWorkerPool(s.cfg.QueueName, s.cfg.Concurrency, s.cfg.PollInterval, s.cfg.Storage, s.registry)
s.pool.Start(ctx)
<-ctx.Done()
return s.Shutdown(context.Background())
}
// Shutdown gracefully stops all active workers.
func (s *Server) Shutdown(ctx context.Context) error {
s.mu.Lock()
defer s.mu.Unlock()
if !s.running {
return nil
}
log.Println("[GopherQueue Server] Shutting down worker engine...")
if s.pool != nil {
s.pool.Stop()
}
s.running = false
log.Println("[GopherQueue Server] Server stopped cleanly.")
return nil
}