-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathqueue.go
More file actions
201 lines (169 loc) · 4.36 KB
/
queue.go
File metadata and controls
201 lines (169 loc) · 4.36 KB
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
package main
import (
"context"
"fmt"
"log"
"sync"
"time"
)
const statusStarting = "🔍 Starting..."
type Messenger interface {
Send(ctx context.Context, chatID int64, text string, withCancelID string) (messageID int, err error)
Edit(ctx context.Context, chatID int64, messageID int, text string, withCancelID string) error
Delete(ctx context.Context, chatID int64, messageID int) error
}
type DownloadEntry struct {
ID string
ChatID int64
URL string
Username string
AudioOnly bool
statusMessageID int
ctx context.Context
cancel context.CancelFunc
canceled bool
}
func (e *DownloadEntry) Ctx() context.Context { return e.ctx }
func (e *DownloadEntry) StatusMessageID() int { return e.statusMessageID }
func (e *DownloadEntry) Canceled() bool { return e.canceled }
func (e *DownloadEntry) ShortID() string {
if len(e.ID) >= 8 {
return e.ID[:8]
}
return e.ID
}
func (e *DownloadEntry) LogTag() string {
return e.ShortID() + " " + e.Username
}
type DownloadQueue struct {
mu sync.Mutex
entries []*DownloadEntry
wakeup chan struct{}
messenger Messenger
worker func(ctx context.Context, e *DownloadEntry)
parentCtx context.Context
processing bool
}
func NewDownloadQueue(parentCtx context.Context, messenger Messenger, worker func(ctx context.Context, e *DownloadEntry)) *DownloadQueue {
return &DownloadQueue{
entries: nil,
wakeup: make(chan struct{}, 1),
messenger: messenger,
worker: worker,
parentCtx: parentCtx,
}
}
func (q *DownloadQueue) Add(e *DownloadEntry) error {
e.ctx, e.cancel = context.WithCancel(q.parentCtx)
q.mu.Lock()
posSnapshot := len(q.entries)
q.mu.Unlock()
text := statusStarting
if posSnapshot > 0 {
text = queuedAtText(posSnapshot)
}
msgID, err := q.messenger.Send(q.parentCtx, e.ChatID, text, e.ID)
if err != nil {
e.cancel()
return fmt.Errorf("sending status message: %w", err)
}
e.statusMessageID = msgID
q.mu.Lock()
q.entries = append(q.entries, e)
size := len(q.entries)
q.mu.Unlock()
log.Printf("queue: enqueued [%s] url=%q position=#%d size=%d", e.LogTag(), e.URL, posSnapshot, size)
select {
case q.wakeup <- struct{}{}:
default:
}
return nil
}
func (q *DownloadQueue) Cancel(id string) {
q.mu.Lock()
idx := indexOfEntry(q.entries, id)
if idx < 0 {
q.mu.Unlock()
return
}
e := q.entries[idx]
e.canceled = true
if idx == 0 && q.processing {
q.mu.Unlock()
log.Printf("queue: cancel running [%s]", e.LogTag())
e.cancel()
return
}
q.entries = append(q.entries[:idx], q.entries[idx+1:]...)
followers := append([]*DownloadEntry(nil), q.entries...)
size := len(q.entries)
q.mu.Unlock()
log.Printf("queue: cancel queued [%s] size=%d", e.LogTag(), size)
e.cancel()
if e.statusMessageID != 0 {
if err := q.messenger.Delete(q.parentCtx, e.ChatID, e.statusMessageID); err != nil {
log.Printf("queue: error deleting canceled status: %v", err)
}
}
q.bumpFollowerPositions(followers)
}
func (q *DownloadQueue) Run() {
for {
q.mu.Lock()
if len(q.entries) == 0 {
q.mu.Unlock()
select {
case <-q.parentCtx.Done():
return
case <-q.wakeup:
continue
}
}
e := q.entries[0]
q.processing = true
q.mu.Unlock()
if e.ctx.Err() == nil {
log.Printf("queue: starting [%s] url=%q", e.LogTag(), e.URL)
start := time.Now()
q.worker(e.ctx, e)
outcome := "completed"
if e.ctx.Err() != nil {
outcome = "canceled"
}
log.Printf("queue: %s [%s] in %s", outcome, e.LogTag(), time.Since(start).Round(100*time.Millisecond))
}
q.mu.Lock()
q.processing = false
if len(q.entries) > 0 && q.entries[0].ID == e.ID {
q.entries = q.entries[1:]
}
followers := append([]*DownloadEntry(nil), q.entries...)
q.mu.Unlock()
e.cancel()
q.bumpFollowerPositions(followers)
}
}
func (q *DownloadQueue) bumpFollowerPositions(followers []*DownloadEntry) {
for i, f := range followers {
if i == 0 {
continue
}
if f.statusMessageID == 0 {
continue
}
if err := q.messenger.Edit(q.parentCtx, f.ChatID, f.statusMessageID, queuedAtText(i), f.ID); err != nil {
log.Printf("queue: error bumping follower position: %v", err)
}
}
}
func queuedAtText(position int) string {
return fmt.Sprintf("👨👦👦 Queued at #%d", position)
}
func indexOfEntry(entries []*DownloadEntry, id string) int {
for i, e := range entries {
if e.ID == id {
return i
}
}
return -1
}