-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmonitor.go
More file actions
220 lines (190 loc) · 5.1 KB
/
monitor.go
File metadata and controls
220 lines (190 loc) · 5.1 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
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
package dlfetch
import (
"sort"
"sync"
"time"
)
type Monitor interface {
add(DownloadRequest)
update(id int, done, total int64, ds float64, eta string)
close()
markAsCompleted(id int)
markAsFailed(id int, err error)
GetSnapshot() MonitorSnapshot
EventSignal() <-chan struct{}
}
type TaskMonitor struct {
mu sync.RWMutex
tasks map[int]*DownloadTask
eventSignal chan struct{}
}
// Creates a TaskMonitor
func NewMonitor() *TaskMonitor {
return &TaskMonitor{
tasks: make(map[int]*DownloadTask),
eventSignal: make(chan struct{}, 1),
}
}
// EventSignal returns a read-only channel that signals
// whenever the TaskMonitor's state changes.
func (m *TaskMonitor) EventSignal() <-chan struct{} {
return m.eventSignal
}
// signalEvent sends a signal on the eventSignal channel
// to notify listeners that the TaskMonitor has changed.
// If the channel already has a pending signal, it does nothing
// to avoid blocking or sending duplicate notifications.
func (m *TaskMonitor) signalEvent() {
select {
case m.eventSignal <- struct{}{}:
default:
}
}
func (m *TaskMonitor) close() {
m.mu.Lock()
defer m.mu.Unlock()
select {
case <-m.eventSignal:
// already closed or drained
default:
close(m.eventSignal)
}
}
// Add downloadRequest to track its progress
func (m *TaskMonitor) add(req DownloadRequest) {
m.mu.Lock()
defer m.mu.Unlock()
m.tasks[req.ID] = &DownloadTask{
ID: req.ID,
FileName: req.FileName,
FilePath: req.FullPath,
Status: StatusPending,
EnqueuedAt: time.Now(),
}
m.signalEvent()
}
// Update the progress and status of a download task
func (m *TaskMonitor) update(id int, done int64, total int64, ds float64, eta string) {
m.mu.Lock()
defer m.mu.Unlock()
if t, ok := m.tasks[id]; ok {
// set startedAt if not already set
if t.StartedAt.IsZero() {
t.StartedAt = time.Now()
t.Status = StatusInProgress
}
t.DoneBytes = done
t.TotalBytes = total
t.DownloadSpeed = ds
t.ETA = eta
}
m.signalEvent()
}
// Mark task as completed
func (m *TaskMonitor) markAsCompleted(id int) {
m.mu.Lock()
defer m.mu.Unlock()
if t, ok := m.tasks[id]; ok {
if t.TotalBytes > 0 {
t.DoneBytes = t.TotalBytes
}
t.Status = StatusCompleted
now := time.Now()
t.CompletedAt = &now
}
m.signalEvent()
}
// Mark task as failed
func (m *TaskMonitor) markAsFailed(id int, err error) {
m.mu.Lock()
defer m.mu.Unlock()
if t, ok := m.tasks[id]; ok {
t.Status = StatusFailed
t.Error = err.Error()
}
m.signalEvent()
}
// GetSnapshot returns a copy of the current state of all download
func (m *TaskMonitor) GetSnapshot() MonitorSnapshot {
m.mu.RLock()
defer m.mu.RUnlock()
snapshot := MonitorSnapshot{}
var pendingTasks []pendingTask
for _, t := range m.tasks {
snapshot.Tasks = append(snapshot.Tasks, *t)
snapshot.Count.Total++
switch t.Status {
case StatusPending:
snapshot.Count.Pending++
pendingTasks = append(pendingTasks, pendingTask{
id: t.ID,
enqueuedAt: t.EnqueuedAt,
})
case StatusCompleted:
snapshot.Count.Completed++
case StatusFailed:
snapshot.Count.Failed++
case StatusInProgress:
snapshot.Count.InProgress++
}
}
// Sort pending tasks by enqueue time (FIFO order)
sort.Slice(pendingTasks, func(i, j int) bool {
return pendingTasks[i].enqueuedAt.Before(pendingTasks[j].enqueuedAt)
})
queuePositions := make(map[int]int)
for pos, pt := range pendingTasks {
queuePositions[pt.id] = pos + 1
}
for i := range snapshot.Tasks {
if snapshot.Tasks[i].Status == StatusPending {
snapshot.Tasks[i].QueuePosition = queuePositions[snapshot.Tasks[i].ID]
} else {
snapshot.Tasks[i].QueuePosition = 0 // Not in pending state
}
}
return snapshot
}
// Monitor Writer
// This is a custom writer that reports progress to the monitor
type monitorWriter struct {
id int
total int64
written int64
monitor Monitor
startTime time.Time
}
func (mw *monitorWriter) Write(p []byte) (int, error) {
n := len(p)
mw.written += int64(n)
// Set startTime, when we start the download
if mw.startTime.IsZero() {
mw.startTime = time.Now()
}
elapsed := time.Since(mw.startTime).Seconds()
speedBPS := float64(mw.written) / elapsed
var eta string
if mw.total > 0 {
remainingBytes := mw.total - mw.written
if speedBPS > 0 {
etaSec := float64(remainingBytes) / speedBPS
eta = time.Duration(etaSec * float64(time.Second)).Truncate(time.Second).String()
} else {
eta = "calculating..."
}
} else {
eta = "unknown"
}
mw.monitor.update(mw.id, mw.written, mw.total, speedBPS, eta)
return n, nil
}
// No-Op Monitor
// This is default monitor that does nothing
type noopMonitor struct{}
func (n *noopMonitor) add(DownloadRequest) {}
func (n *noopMonitor) update(int, int64, int64, float64, string) {}
func (n *noopMonitor) close() {}
func (n *noopMonitor) markAsCompleted(int) {}
func (n *noopMonitor) markAsFailed(int, error) {}
func (n *noopMonitor) GetSnapshot() MonitorSnapshot { return MonitorSnapshot{} }
func (n *noopMonitor) EventSignal() <-chan struct{} { return nil }