-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
routes.go
387 lines (341 loc) · 11.3 KB
/
routes.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
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
package main
import (
"context"
"errors"
"fmt"
"io"
"log"
"math"
"net/http"
"strconv"
"strings"
"time"
"github.com/redis/go-redis/v9"
"github.com/google/uuid"
"github.com/jasonlovesdoggo/abacus/utils"
"github.com/gin-gonic/gin"
)
func StreamValueView(c *gin.Context) {
namespace, key := utils.GetNamespaceKey(c)
if namespace == "" || key == "" {
c.AbortWithStatus(http.StatusBadRequest)
return
}
dbKey := utils.CreateKey(c, namespace, key, false)
if dbKey == "" {
c.AbortWithStatus(http.StatusBadRequest)
return
}
// Initialize client channel
clientChan := make(chan int)
// Add this client to the event server for this specific key
utils.ValueEventServer.NewClients <- utils.KeyClientPair{
Key: dbKey,
Client: clientChan,
}
defer func() {
// Drain client channel to prevent blocking
go func() {
for range clientChan {
// Drain client channel to prevent blocking
}
}()
// Remove this client from the event server
utils.ValueEventServer.ClosedClients <- utils.KeyClientPair{
Key: dbKey,
Client: clientChan,
}
}()
// Send initial value
initialVal := Client.Get(context.Background(), dbKey).Val()
if count, err := strconv.Atoi(initialVal); err == nil {
_, err := c.Writer.WriteString(fmt.Sprintf("data: {\"value\":%d}\n\n", count))
if err != nil {
log.Printf("Error writing to client: %v", err)
return
}
c.Writer.Flush()
}
// Stream updates
c.Stream(func(w io.Writer) bool {
select {
case <-c.Request.Context().Done():
return false
case count, ok := <-clientChan:
if !ok {
return false
}
_, err := c.Writer.WriteString(fmt.Sprintf("data: {\"value\":%d}\n\n", count))
if err != nil {
log.Printf("Error writing to client: %v", err)
return false // Stream closed by client or server error
}
c.Writer.Flush()
return true
}
})
}
func HitView(c *gin.Context) {
namespace, key := utils.GetNamespaceKey(c)
if namespace == "" || key == "" {
return
}
dbKey := utils.CreateKey(c, namespace, key, false)
if dbKey == "" { // error is handled in CreateKey
return
}
// Get data from Redis
val, err := Client.Incr(context.Background(), dbKey).Result()
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to get data. Try again later."})
return
}
// check if val is is greater than the max value of an int
if val > math.MaxInt {
c.JSON(http.StatusBadRequest, gin.H{"error": "Value is too large. Max value is " + strconv.Itoa(math.
MaxInt), "message": "If you are seeing this error and have a legitimate use case, please contact me @ abacus@jasoncameron.dev"})
return
}
go func() {
utils.SetStream(dbKey, int(val)) // #nosec G115 -- This is safe as we perform a check (
// see above) to ensure val is within the range of an int.
Client.Expire(context.Background(), dbKey, utils.BaseTTLPeriod)
}()
if c.Query("callback") != "" {
c.JSONP(http.StatusOK, gin.H{"value": val})
} else {
c.JSON(http.StatusOK, gin.H{"value": val})
}
}
func GetView(c *gin.Context) {
namespace, key := utils.GetNamespaceKey(c)
if namespace == "" || key == "" {
return
}
dbKey := utils.CreateKey(c, namespace, key, false)
if dbKey == "" { // error is handled in CreateKey
return
}
// Get data from Redis
val, err := Client.Get(context.Background(), dbKey).Result()
if errors.Is(err, redis.Nil) {
c.JSON(http.StatusNotFound, gin.H{"error": "Key not found"})
return
} else if err != nil { // Other Redis errors
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to get data. Try again later."})
return
}
go func() {
Client.Expire(context.Background(), dbKey, utils.BaseTTLPeriod)
}()
intval, _ := strconv.Atoi(val)
if c.Query("callback") != "" {
c.JSONP(http.StatusOK, gin.H{"value": intval})
} else {
c.JSON(http.StatusOK, gin.H{"value": intval})
}
}
func CreateRandomView(c *gin.Context) {
key, _ := utils.GenerateRandomString(16)
namespace, err := utils.GenerateRandomString(16)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to generate random string. Try again later."})
return
}
c.Params = gin.Params{gin.Param{Key: "namespace", Value: namespace}, gin.Param{Key: "key", Value: key}}
CreateView(c)
}
func CreateView(c *gin.Context) {
namespace, key := utils.GetNamespaceKey(c)
if namespace == "" || key == "" {
return
}
dbKey := utils.CreateKey(c, namespace, key, false)
if dbKey == "" { // error is handled in CreateKey
return
}
initialValue, err := strconv.Atoi(c.DefaultQuery("initializer", "0"))
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "initializer must be a number"})
return
}
// Get data from Redis
created := Client.SetNX(context.Background(), dbKey, initialValue, utils.BaseTTLPeriod)
if created.Val() == false {
c.JSON(http.StatusConflict, gin.H{"error": "Key already exists, please use a different key."})
return
}
AdminKey := uuid.New().String() // Create a new admin key used for deletion and control
Client.Set(context.Background(), utils.CreateAdminKey(dbKey), AdminKey, 0) // todo: figure out how to handle admin keys (handle alongside admin orrrrrrr separately as in a routine once a month that deletes all admin keys with no corresponding key)
utils.SetStream(dbKey, initialValue)
c.JSON(http.StatusCreated, gin.H{"key": key, "namespace": namespace, "admin_key": AdminKey, "value": initialValue})
}
func InfoView(c *gin.Context) { // todo: write docs on what negative values mean (https://redis.io/commands/ttl/)
namespace, key := utils.GetNamespaceKey(c)
if namespace == "" || key == "" {
return
}
dbKey := utils.CreateKey(c, namespace, key, true)
if dbKey == "" { // error is handled in CreateKey
return
}
dbValue := Client.Get(context.Background(), dbKey).Val()
count, _ := strconv.Atoi(dbValue)
isGenuine := Client.Exists(context.Background(), utils.CreateAdminKey(dbKey)).Val() == 0
expiresAt := Client.TTL(context.Background(), dbKey).Val()
exists := expiresAt != -2
if !exists {
count = -1
}
c.JSON(http.StatusOK, gin.H{"value": count, "full_key": dbKey, "is_genuine": isGenuine, "expires_in": expiresAt.Seconds(), "expires_str": expiresAt.String(), "exists": exists})
}
func DeleteView(c *gin.Context) {
namespace, key := utils.GetNamespaceKey(c)
if namespace == "" || key == "" {
return
}
dbKey := utils.CreateKey(c, namespace, key, true)
if dbKey == "" { // error is handled in CreateKey
return
}
adminDBKey := utils.CreateAdminKey(dbKey) // Create the admin key
Client.Del(context.Background(), dbKey) // Delete the normal key
Client.Del(context.Background(), adminDBKey) // delete the admin key as it's now useless
c.JSON(http.StatusOK, gin.H{"status": "ok", "message": "Deleted key: " + dbKey})
utils.CloseStream(dbKey)
}
func SetView(c *gin.Context) {
updatedValueRaw, _ := c.GetQuery("value")
if updatedValueRaw == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "value is required, please provide a number in the fmt of ?value=NEW_VALUE"})
return
}
updatedValue, err := strconv.Atoi(updatedValueRaw)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "value must be a number"})
return
}
namespace, key := utils.GetNamespaceKey(c)
if namespace == "" || key == "" {
return
}
dbKey := utils.CreateKey(c, namespace, key, false)
if dbKey == "" { // error is handled in CreateKey
return
}
// Get data from Redis
val, err := Client.SetXX(context.Background(), dbKey, updatedValue, utils.BaseTTLPeriod).Result()
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to set data. Try again later."})
return
}
if val == false {
c.JSON(http.StatusConflict, gin.H{"error": "Key does not exist, please use a different key."})
} else {
go utils.SetStream(dbKey, updatedValue)
c.JSON(http.StatusOK, gin.H{"value": updatedValue})
}
}
func ResetView(c *gin.Context) {
namespace, key := utils.GetNamespaceKey(c)
if namespace == "" || key == "" {
return
}
dbKey := utils.CreateKey(c, namespace, key, false)
if dbKey == "" { // error is handled in CreateKey
return
}
// Get data from Redis
val, err := Client.SetXX(context.Background(), dbKey, 0, utils.BaseTTLPeriod).Result()
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to set data. Try again later."})
return
}
if val == false {
c.JSON(http.StatusConflict, gin.H{"error": "Key does not exist, please use a different key."})
} else {
c.JSON(http.StatusOK, gin.H{"value": 0})
go utils.SetStream(dbKey, 0)
}
}
func UpdateByView(c *gin.Context) {
updatedValueRaw, _ := c.GetQuery("value")
if updatedValueRaw == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "value is required, please provide a number in the fmt of ?value=NEW_VALUE"})
return
}
incrByValue, err := strconv.Atoi(updatedValueRaw)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "value must be a number, this means no floats."})
return
}
if incrByValue == 0 {
c.JSON(http.StatusBadRequest, gin.H{"error": "changing value by 0 does nothing, please provide a non-zero value in the fmt of ?value=NEW_VALUE"})
return
}
namespace, key := utils.GetNamespaceKey(c)
if namespace == "" || key == "" {
return
}
dbKey := utils.CreateKey(c, namespace, key, false)
if dbKey == "" { // error is handled in CreateKey
return
}
exists := Client.Exists(context.Background(), dbKey).Val() == 0
if exists {
c.JSON(http.StatusConflict, gin.H{"error": "Key does not exist, please first create it using /create."})
return
}
// Get data from Redis
val, err := Client.IncrByFloat(context.Background(), dbKey, float64(incrByValue)).Result()
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to set data. Try again later."})
return
}
c.JSON(http.StatusOK, gin.H{"value": int64(val)})
go utils.SetStream(dbKey, int(val))
}
func StatsView(c *gin.Context) {
// get average ttl using INFO
ctx := context.Background()
infoStr, err := Client.Info(ctx).Result()
if err != nil {
panic(err)
}
infoDict := make(map[string]map[string]string)
sections := strings.Split(infoStr, "\r\n\r\n")
for _, section := range sections {
lines := strings.Split(section, "\r\n")
sectionName := lines[0][2:] // Remove "# " prefix
infoDict[sectionName] = make(map[string]string)
for _, line := range lines[1:] {
parts := strings.Split(line, ":")
if len(parts) == 2 {
key := strings.TrimSpace(parts[0])
value := strings.TrimSpace(parts[1])
infoDict[sectionName][key] = value
}
}
}
total, _ := strconv.Atoi(Client.Get(ctx, "stats:Total").Val())
hits, _ := strconv.Atoi(Client.Get(ctx, "stats:hit").Val())
gets, _ := strconv.Atoi(Client.Get(ctx, "stats:get").Val())
create, _ := strconv.Atoi(Client.Get(ctx, "stats:create").Val())
totalKeys := create + (hits / 60) // 60 hits per key (average taken from the first 6m requests) ~ Json
c.JSON(http.StatusOK, gin.H{
"version": Version,
"uptime": time.Since(StartTime).String(),
"db_uptime": infoDict["Server"]["uptime_in_seconds"],
"db_version": infoDict["Server"]["redis_version"],
"expired_keys__since_restart": infoDict["Stats"]["expired_keys"],
"key_misses__since_restart": infoDict["Stats"]["keyspace_misses"],
"commands": map[string]int{
"total": total,
"get": gets,
"hit": hits,
"create": create,
},
"total_keys": totalKeys,
"shard": Shard,
})
}