forked from pubnub/go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
request_workers.go
81 lines (69 loc) · 1.57 KB
/
request_workers.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
package pubnub
import "net/http"
type nonSubMsgType int
const (
messageTypePublish nonSubMsgType = 1 << iota
messageTypePAM
)
type JobQResponse struct {
Resp *http.Response
Error error
}
type JobQItem struct {
Req *http.Request
Client *http.Client
JobResponse chan *JobQResponse
}
type RequestWorkers struct {
Workers chan chan *JobQItem
MaxWorkers int
Sem chan bool
}
type Worker struct {
Workers chan chan *JobQItem
JobChannel chan *JobQItem
id int
}
func NewRequestWorkers(workers chan chan *JobQItem, id int) Worker {
return Worker{
Workers: workers,
JobChannel: make(chan *JobQItem),
id: id,
}
}
func (pw Worker) Process(pubnub *PubNub) {
go func() {
for {
pw.Workers <- pw.JobChannel
job := <-pw.JobChannel
res, err := job.Client.Do(job.Req)
jqr := &JobQResponse{
Error: err,
Resp: res,
}
job.JobResponse <- jqr
}
}()
}
func (p *RequestWorkers) Start(pubnub *PubNub) {
pubnub.Config.Log.Println("Start: Running with workers ", p.MaxWorkers)
for i := 0; i < p.MaxWorkers; i++ {
pubnub.Config.Log.Println("Start: StartNonSubWorker ", i)
worker := NewRequestWorkers(p.Workers, i)
worker.Process(pubnub)
}
go p.ReadQueue(pubnub)
}
func (p *RequestWorkers) ReadQueue(pubnub *PubNub) {
for job := range pubnub.jobQueue {
pubnub.Config.Log.Println("ReadQueue: Got job for channel ", job.Req)
go func(job *JobQItem) {
jobChannel := <-p.Workers
jobChannel <- job
}(job)
}
pubnub.Config.Log.Println("ReadQueue: Exit")
}
func (p *RequestWorkers) Close() {
close(p.Workers)
}