-
Notifications
You must be signed in to change notification settings - Fork 0
/
pool.go
80 lines (67 loc) · 1.77 KB
/
pool.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
package reactor
import (
"sync"
)
// Pool provides a dynamically growing pool of workers capable of rendering.
type Pool struct {
code string
version string
workers []*Worker
mu sync.Mutex
}
// NewPool creates a new Pool of workers with the given server code. It
// creates a single Worker with the given code. Additional workers will
// be created on-demand as needed.
func NewPool(code string) *Pool {
return &Pool{
code: code,
version: checksum(code),
}
}
// UpdateCode updates the server code for the pool, causing any existing
// workers running an older version of the code to be closed in the future.
// Any requests that are currently in-flight will be allowed to finish.
func (p *Pool) UpdateCode(code string) {
p.mu.Lock()
p.code = code
p.version = checksum(code)
p.mu.Unlock()
}
// Render renders a React component with a worker from the pool. If a worker
// with the current code version is not available, a new worker will be created.
func (p *Pool) Render(req *Request) (*Response, error) {
w, err := p.Get()
if err != nil {
return nil, err
}
resp, err := w.Render(req)
if err != nil {
w.Close()
return nil, err
}
p.Put(w)
return resp, nil
}
// Get returns the next worker from the pool, creating a new worker if needed.
// Workers with previous code versions will be discarded, resulting in a new
// worker being created.
func (p *Pool) Get() (*Worker, error) {
p.mu.Lock()
defer p.mu.Unlock()
for len(p.workers) > 0 {
w := p.workers[0]
p.workers = p.workers[1:]
if w.closed || w.version != p.version {
w.Close()
continue
}
return w, nil
}
return NewWorker(p.code)
}
// Put returns a worker to the pool to be re-used in the future
func (p *Pool) Put(w *Worker) {
p.mu.Lock()
p.workers = append(p.workers, w)
p.mu.Unlock()
}