This repository has been archived by the owner on Feb 23, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathqueue_processor.go
206 lines (176 loc) · 5.08 KB
/
queue_processor.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
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
package main
import (
"bufio"
"fmt"
"log"
"os"
"strconv"
"sync"
"time"
"github.com/getsentry/sentry-go"
"github.com/go-redis/redis"
"github.com/tomocrafter/go-twitter/twitter"
)
type lookupQueue struct {
ticker *time.Ticker
executing bool
queue *Queue
}
type Callback func(tweet twitter.Tweet)
type Queue map[int64][]Callback
func NewLookupQueue() *lookupQueue {
queue := make(Queue)
return &lookupQueue{
ticker: time.NewTicker(1 * time.Second),
queue: &queue,
}
}
func (t *lookupQueue) LookupTweetBlocking(id int64) twitter.Tweet {
tc := make(chan twitter.Tweet, 1)
t.EnqueueLookupHandler(id, func(tweet twitter.Tweet) {
tc <- tweet
})
tweet, ok := <-tc
if !ok {
panic("unrecoverable panic occurred: channel unexpectedly closed while looking up tweet")
}
return tweet
}
// EnqueueLookupHandler はキューに検索するIDとツイートを処理するコールバックを追加します
func (t *lookupQueue) EnqueueLookupHandler(id int64, handler Callback) {
(*t.queue)[id] = append((*t.queue)[id], handler)
}
// StartTicker は1秒間に一度キューの中身をすべて検索にかけ、コールバックを呼びます
func (t *lookupQueue) StartTicker() {
for n := range t.ticker.C {
go t.Execute(n)
}
}
func (t *lookupQueue) Execute(n time.Time) {
if t.executing {
sentry.CaptureMessage("called progress function during executing")
return
}
t.executing = true
defer func() {
t.executing = false
}()
// Check for redis rate limit.
resetStr, err := redisClient.Get(ShowRateLimitReset).Result()
if err != nil {
if err != redis.Nil {
sentry.CaptureException(err)
return // DO NOT execute statuses/lookup if redis is down!
}
} else {
if reset, err := strconv.ParseInt(resetStr, 10, 64); err == nil {
if reset > n.Unix() {
return // rate limited!
}
} else {
sentry.CaptureException(fmt.Errorf("not int64 value (%s) passed by redis with key %s", resetStr, ShowRateLimitReset))
// Reset the value of redis
redisClient.Del(ShowRateLimitReset)
}
}
// Move queue here
queue := *t.queue
if len(queue) == 0 {
return // queue is still empty then do nothing.
}
// and re-create
newQueue := make(Queue)
t.queue = &newQueue
// Make the list of ids for lookup
ids := make([]int64, 0, len(queue))
for id := range queue {
ids = append(ids, id)
}
log.Printf("Looking up tweet(s): %v\n", ids)
// fallback to the statuses/show endpoint if statuses/lookup endpoint is exceeded rate limit.
fallbackToShow := false
tweets, resp, err := client.Statuses.Lookup(ids, &twitter.StatusLookupParams{
TrimUser: twitter.Bool(true),
IncludeEntities: twitter.Bool(true),
TweetMode: "extended",
})
if err != nil {
if resp != nil {
if err.(twitter.APIError).Errors[0].Code == 88 {
sentry.CaptureMessage("API /statuses/lookup somehow exceeded rate limit!")
fallbackToShow = true
} else {
sentry.CaptureException(fmt.Errorf("non rate limit error occurred while calling /statuses/lookup: %s", err))
return
}
} else {
sentry.CaptureException(fmt.Errorf("connection error occurred while calling /statuses/lookup: %s", err))
return
}
}
if fallbackToShow {
for _, id := range ids {
tweet, resp, err := client.Statuses.Show(id, &twitter.StatusShowParams{
TrimUser: twitter.Bool(true),
IncludeMyRetweet: twitter.Bool(false),
IncludeEntities: twitter.Bool(true),
TweetMode: "extended",
})
if err != nil {
if resp != nil {
if err.(twitter.APIError).Errors[0].Code == 88 { // Rate limit exceeded
sentry.CaptureMessage("API /statuses/show/:id exceeded rate limit!")
redisClient.Set(ShowRateLimitReset, resp.Header.Get("x-rate-limit-reset"), 0)
break // Process only the retrieved tweets.
}
if resp.StatusCode == 404 { // Tweet already deleted.
continue
}
}
sentry.CaptureException(fmt.Errorf("error occurred while calling /statuses/show: %s", err))
continue
}
tweets = append(tweets, *tweet)
}
}
foundIds := make([]int64, 0, len(ids))
// Calling callbacks!
// Ignore tweet that already deleted.
var wg sync.WaitGroup
for _, tweet := range tweets {
foundIds = append(foundIds, tweet.ID)
cbs := queue[tweet.ID]
for _, cb := range cbs {
wg.Add(1)
go func(tweet twitter.Tweet, cb Callback) {
defer wg.Done()
cb(tweet)
}(tweet, cb)
}
}
// wait until all of worker goroutines (callback caller) done.
wg.Wait()
if len(foundIds) < len(ids) {
w := bufio.NewWriterSize(os.Stdout, 512)
_, _ = w.WriteString("Could not fetch tweet(s): [")
// writing the difference of ids and foundIds to stdout
// ref. https://stackoverflow.com/questions/19374219/how-to-find-the-difference-between-two-slices-of-strings
for _, s1 := range ids {
found := false
for _, s2 := range foundIds {
if s1 == s2 {
found = true
break
}
}
// String not found. We add it to return slice
if !found {
// TODO: faster way to write int64 to buffer without casting to string.
_, _ = w.WriteString(string(s1))
}
}
_, _ = w.WriteRune(']')
// Now print to stdout!
_ = w.Flush()
}
}