This repository has been archived by the owner on Feb 25, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathqueue.go
143 lines (125 loc) · 2.3 KB
/
queue.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
package crawler
import (
"net/url"
"sync"
"time"
)
type Error string
func (e Error) Error() string { return string(e) }
const (
ErrNotAbsoluteURL = Error("not an absolute url")
ErrRejectedURL = Error("url rejected")
ErrQueueClosed = Error("queue is shut down")
ErrDuplicateURL = Error("duplicate url")
ErrEmptyURL = Error("empty url")
ErrLimitReached = Error("limit reached")
)
type pusher interface {
Push(*url.URL) error
Close() error
}
type Queue struct {
push chan *url.URL
pop chan *url.URL
timer *time.Timer
ttl time.Duration
mu sync.Mutex
closed bool
set map[string]struct{}
limit int64
done int64
}
func NewQueue(limit int64, ttl time.Duration) *Queue {
q := &Queue{
push: make(chan *url.URL, 64), // queue channel capacity
pop: make(chan *url.URL, 64), // queue channel capacity
timer: time.NewTimer(ttl),
ttl: ttl,
set: make(map[string]struct{}),
limit: limit,
}
go q.run(256) // initial queue slice capacity
return q
}
func (q *Queue) Push(url *url.URL) error {
if url == nil {
return ErrEmptyURL
}
q.mu.Lock()
if q.closed {
q.mu.Unlock()
return ErrQueueClosed
}
if q.limit > 0 && q.done > q.limit {
q.mu.Unlock()
return ErrLimitReached
}
key := normalizeKey(url)
if len(key) == 0 {
q.mu.Unlock()
return ErrEmptyURL
}
if _, found := q.set[key]; found {
q.mu.Unlock()
return ErrDuplicateURL
}
q.set[key] = struct{}{}
q.done++
q.push <- url
q.mu.Unlock()
return nil
}
func (q *Queue) Close() error {
q.mu.Lock()
if q.closed {
q.mu.Unlock()
return ErrQueueClosed
}
q.closed = true
close(q.push)
q.mu.Unlock()
return nil
}
func (q *Queue) Pop() <-chan *url.URL {
return q.pop
}
func (q *Queue) run(capacity int) {
queue := make([]*url.URL, 0, capacity)
defer func() {
for len(queue) > 0 {
q.pop <- queue[0]
queue = queue[1:]
}
close(q.pop)
}()
for {
if len(queue) == 0 {
select {
case url, ok := <-q.push:
if !ok {
q.Close()
return
}
queue = append(queue, url)
q.timer.Reset(q.ttl)
case <-q.timer.C:
q.Close()
return
}
}
select {
case url, ok := <-q.push:
if !ok {
q.Close()
return
}
queue = append(queue, url)
q.timer.Reset(q.ttl)
case q.pop <- queue[0]:
queue = queue[1:]
case <-q.timer.C:
q.Close()
return
}
}
}