-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcounters.go
More file actions
211 lines (189 loc) · 5.16 KB
/
counters.go
File metadata and controls
211 lines (189 loc) · 5.16 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
package main
import (
"fmt"
"math"
"path/filepath"
"strings"
"sync/atomic"
"time"
)
// Write method for countingWriter to track the number of bytes written
func (w *countingWriter) Write(data []byte) (int, error) {
n, err := w.ResponseWriter.Write(data)
w.bytesWritten += int64(n)
return n, err
}
// normalizeStatsPath makes map keys consistent with API display paths (slash-separated).
func normalizeStatsPath(p string) string {
return filepath.ToSlash(strings.TrimSpace(p))
}
func lookupDownloadCount(displayPath string) int64 {
statsMutex.Lock()
defer statsMutex.Unlock()
key := normalizeStatsPath(displayPath)
if s, ok := downloadStats[key]; ok {
return s.Count
}
return 0
}
// Called after serving a file to update global stats and print download progress
func (w *countingWriter) finish() {
var elapsed time.Duration
if !w.startedAt.IsZero() {
elapsed = time.Since(w.startedAt)
}
recordServedDownload(w.path, w.clientIP, w.bytesWritten, w.fileSize, w.isRangeRequest, elapsed)
}
func formatServedDuration(d time.Duration) string {
if d < 0 {
d = 0
}
if d < time.Second {
return fmt.Sprintf("%.1fs", d.Seconds())
}
d = d.Round(time.Second)
sec := int64(d / time.Second)
if sec < 60 {
return fmt.Sprintf("%ds", sec)
}
m := sec / 60
s := sec % 60
if s == 0 {
return fmt.Sprintf("%dm", m)
}
return fmt.Sprintf("%dm %ds", m, s)
}
// formatServedDataSize uses decimal (SI) units: prefer GB only when >= 1 GB so e.g. 900 MB stays MB; whole GB when rounded.
func formatServedDataSize(bytes int64) string {
if bytes < 0 {
bytes = 0
}
const kb, mb, gb = 1000.0, 1e6, 1e9
f := float64(bytes)
if f >= gb {
g := f / gb
ig := int64(math.Round(g))
if math.Abs(g-float64(ig)) < 0.0005 {
return fmt.Sprintf("%dGB", ig)
}
return fmt.Sprintf("%.2fGB", g)
}
if f >= mb {
return fmt.Sprintf("%.0fMB", f/mb)
}
if f >= kb {
return fmt.Sprintf("%.0fKB", f/kb)
}
return fmt.Sprintf("%dB", bytes)
}
func formatServedMbps(bytesWritten int64, elapsed time.Duration) string {
if elapsed < time.Millisecond {
return "?mbit/s"
}
sec := elapsed.Seconds()
if sec <= 0 {
return "?mbit/s"
}
mbps := (float64(bytesWritten) * 8.0) / sec / 1e6
if mbps >= 100 {
return fmt.Sprintf("%.0fmbit/s", mbps)
}
if mbps >= 10 {
return fmt.Sprintf("%.1fmbit/s", mbps)
}
return fmt.Sprintf("%.2fmbit/s", mbps)
}
func recordServedDownload(relPath, clientIP string, bytesWritten, fileSize int64, isRangeRequest bool, elapsed time.Duration) {
statsMutex.Lock()
defer statsMutex.Unlock()
key := normalizeStatsPath(relPath)
stats := downloadStats[key]
stats.Bytes += bytesWritten
stats.Count++
downloadStats[key] = stats
partial := isRangeRequest
if fileSize > 0 {
partial = partial || bytesWritten < fileSize
}
perClientMu.Lock()
if _, ok := perClientFileStats[clientIP]; !ok {
perClientFileStats[clientIP] = make(map[string]clientFileStat)
}
cf := perClientFileStats[clientIP][key]
if partial {
cf.Partial++
} else {
cf.Full++
}
perClientFileStats[clientIP][key] = cf
perClientMu.Unlock()
kind := "full"
if partial {
kind = "partial"
}
sizeStr := formatServedDataSize(bytesWritten)
timeStr := formatServedDuration(elapsed)
rateStr := formatServedMbps(bytesWritten, elapsed)
outPrintf("Served file %s to %s (%s), sent %d bytes in %s (%s@%s)\n", key, clientIP, kind, bytesWritten, timeStr, sizeStr, rateStr)
if serverCfg.ByteLimit > 0 {
atomic.AddInt64(&globalBytesTransferred, bytesWritten)
}
appendServerEvent("download", clientIP, fmt.Sprintf("path=%s kind=%s bytes=%d", key, kind, bytesWritten))
}
// Write method for rateLimitedWriter that throttles writes based on bandwidth limit
func (w *rateLimitedWriter) Write(data []byte) (int, error) {
w.mu.Lock()
defer w.mu.Unlock()
dataLen := int64(len(data))
if dataLen == 0 {
return w.ResponseWriter.Write(data)
}
now := time.Now()
elapsed := now.Sub(w.lastWrite).Seconds()
// Reset counter if more than 1 second has passed
if elapsed >= 1.0 {
w.bytesWritten = 0
w.lastWrite = now
elapsed = 0
}
// Calculate how long to wait if we've exceeded the limit
if w.bytesWritten >= w.bytesPerSecond {
waitTime := time.Duration((1.0 - elapsed) * float64(time.Second))
if waitTime > 0 {
time.Sleep(waitTime)
w.bytesWritten = 0
w.lastWrite = time.Now()
}
}
// Write data in chunks to respect the bandwidth limit
totalWritten := 0
chunkSize := int64(8192) // 8KB chunks for smoother throttling
if chunkSize > w.bytesPerSecond {
chunkSize = w.bytesPerSecond
}
for int64(totalWritten) < dataLen {
remaining := dataLen - int64(totalWritten)
chunk := chunkSize
if chunk > remaining {
chunk = remaining
}
// Check if we can write this chunk without exceeding the limit
if w.bytesWritten+chunk > w.bytesPerSecond {
// Wait until we can write more
elapsed := time.Since(w.lastWrite).Seconds()
if elapsed < 1.0 {
waitTime := time.Duration((1.0 - elapsed) * float64(time.Second))
time.Sleep(waitTime)
}
w.bytesWritten = 0
w.lastWrite = time.Now()
}
n, err := w.ResponseWriter.Write(data[totalWritten : totalWritten+int(chunk)])
totalWritten += n
w.bytesWritten += int64(n)
if err != nil {
return totalWritten, err
}
}
return totalWritten, nil
}