-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinmemory.go
137 lines (107 loc) · 2.15 KB
/
inmemory.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
package main
import (
"bufio"
"context"
"errors"
"os"
"strings"
"sync"
)
type Node struct {
Value *Task
Next *Node
}
type InmemQueue struct {
head *Node
tail *Node
size int
in_progress int
lock sync.Mutex
}
func (q *InmemQueue) Add(ctx context.Context, t *Task) {
// TODO: Deprecate Add method
q.Put(ctx, t)
}
func (q *InmemQueue) Put(ctx context.Context, t *Task) {
q.lock.Lock()
defer q.lock.Unlock()
node := &Node{Value: t}
q.tail.Next = node
q.tail = node
q.size++
}
func (q *InmemQueue) Take(ctx context.Context) (*Task, error) {
q.lock.Lock()
defer q.lock.Unlock()
if q.head.Next == nil {
return nil, errors.New("empty queue")
}
node := q.head.Next
q.head.Next = node.Next
node.Next = nil
q.size--
q.in_progress++
return node.Value, nil
}
func (q *InmemQueue) Get(ctx context.Context) (*Task, error) {
// TODO: Deprecate Get method
return q.Take(ctx)
}
func (q *InmemQueue) Size(ctx context.Context) int64 {
return int64(q.size + q.in_progress)
}
func (q *InmemQueue) TaskDone(ctx context.Context) {
q.lock.Lock()
defer q.lock.Unlock()
q.in_progress--
}
func (q *InmemQueue) LoadFromFile(site *Site, Filepath string) error {
f, err := os.Open(Filepath)
if err != nil {
return err
}
defer f.Close()
scanner := bufio.NewScanner(f)
ctx := context.Background()
for scanner.Scan() {
items := strings.Split(scanner.Text(), "|||")
task, err := site.NewTask(items[0], site.MaxDepth-1)
if err != nil {
continue
}
q.Put(ctx, task)
}
if err := scanner.Err(); err != nil {
return err
}
return nil
}
func NewInmemQueue() *InmemQueue {
q := &InmemQueue{}
q.head = &Node{}
q.tail = q.head
return q
}
type InmemVisited struct {
items map[string]bool
lock sync.RWMutex
}
func (v *InmemVisited) Add(ctx context.Context, uri string) {
v.lock.Lock()
defer v.lock.Unlock()
v.items[uri] = true
}
func (v *InmemVisited) Exists(ctx context.Context, uri string) bool {
v.lock.RLock()
defer v.lock.RUnlock()
if _, exists := v.items[uri]; exists {
return true
}
return false
}
func NewInmemVisited() *InmemVisited {
v := &InmemVisited{
items: make(map[string]bool),
}
return v
}