-
-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathcoverage.html
More file actions
5738 lines (4897 loc) · 244 KB
/
Copy pathcoverage.html
File metadata and controls
5738 lines (4897 loc) · 244 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
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
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>graphql-monitoring-proxy: Go Coverage Report</title>
<style>
body {
background: black;
color: rgb(80, 80, 80);
}
body, pre, #legend span {
font-family: Menlo, monospace;
font-weight: bold;
}
#topbar {
background: black;
position: fixed;
top: 0; left: 0; right: 0;
height: 42px;
border-bottom: 1px solid rgb(80, 80, 80);
}
#content {
margin-top: 50px;
}
#nav, #legend {
float: left;
margin-left: 10px;
}
#legend {
margin-top: 12px;
}
#nav {
margin-top: 10px;
}
#legend span {
margin: 0 5px;
}
.cov0 { color: rgb(192, 0, 0) }
.cov1 { color: rgb(128, 128, 128) }
.cov2 { color: rgb(116, 140, 131) }
.cov3 { color: rgb(104, 152, 134) }
.cov4 { color: rgb(92, 164, 137) }
.cov5 { color: rgb(80, 176, 140) }
.cov6 { color: rgb(68, 188, 143) }
.cov7 { color: rgb(56, 200, 146) }
.cov8 { color: rgb(44, 212, 149) }
.cov9 { color: rgb(32, 224, 152) }
.cov10 { color: rgb(20, 236, 155) }
</style>
</head>
<body>
<div id="topbar">
<div id="nav">
<select id="files">
<option value="file0">github.com/lukaszraczylo/graphql-monitoring-proxy/api.go (63.3%)</option>
<option value="file1">github.com/lukaszraczylo/graphql-monitoring-proxy/buffer_pool.go (70.0%)</option>
<option value="file2">github.com/lukaszraczylo/graphql-monitoring-proxy/cache/cache.go (66.7%)</option>
<option value="file3">github.com/lukaszraczylo/graphql-monitoring-proxy/cache/memory/buffer_pool.go (0.0%)</option>
<option value="file4">github.com/lukaszraczylo/graphql-monitoring-proxy/cache/memory/lru_memory_cache.go (0.0%)</option>
<option value="file5">github.com/lukaszraczylo/graphql-monitoring-proxy/cache/memory/memory.go (92.1%)</option>
<option value="file6">github.com/lukaszraczylo/graphql-monitoring-proxy/cache/redis/redis.go (73.5%)</option>
<option value="file7">github.com/lukaszraczylo/graphql-monitoring-proxy/cache/redis/wrapper.go (0.0%)</option>
<option value="file8">github.com/lukaszraczylo/graphql-monitoring-proxy/circuit_breaker_metrics.go (93.8%)</option>
<option value="file9">github.com/lukaszraczylo/graphql-monitoring-proxy/connection_pool.go (69.4%)</option>
<option value="file10">github.com/lukaszraczylo/graphql-monitoring-proxy/details.go (83.0%)</option>
<option value="file11">github.com/lukaszraczylo/graphql-monitoring-proxy/events.go (18.9%)</option>
<option value="file12">github.com/lukaszraczylo/graphql-monitoring-proxy/graphql.go (85.4%)</option>
<option value="file13">github.com/lukaszraczylo/graphql-monitoring-proxy/logging/logger.go (93.4%)</option>
<option value="file14">github.com/lukaszraczylo/graphql-monitoring-proxy/lru_cache.go (28.2%)</option>
<option value="file15">github.com/lukaszraczylo/graphql-monitoring-proxy/main.go (45.9%)</option>
<option value="file16">github.com/lukaszraczylo/graphql-monitoring-proxy/monitoring.go (100.0%)</option>
<option value="file17">github.com/lukaszraczylo/graphql-monitoring-proxy/monitoring/defaults.go (100.0%)</option>
<option value="file18">github.com/lukaszraczylo/graphql-monitoring-proxy/monitoring/helpers.go (98.8%)</option>
<option value="file19">github.com/lukaszraczylo/graphql-monitoring-proxy/monitoring/monitoring.go (58.8%)</option>
<option value="file20">github.com/lukaszraczylo/graphql-monitoring-proxy/proxy.go (81.2%)</option>
<option value="file21">github.com/lukaszraczylo/graphql-monitoring-proxy/ratelimit.go (88.2%)</option>
<option value="file22">github.com/lukaszraczylo/graphql-monitoring-proxy/ratelimit_errors.go (6.2%)</option>
<option value="file23">github.com/lukaszraczylo/graphql-monitoring-proxy/server.go (3.6%)</option>
<option value="file24">github.com/lukaszraczylo/graphql-monitoring-proxy/shutdown.go (0.0%)</option>
<option value="file25">github.com/lukaszraczylo/graphql-monitoring-proxy/tracing/tracing.go (66.7%)</option>
</select>
</div>
<div id="legend">
<span>not tracked</span>
<span class="cov0">not covered</span>
<span class="cov8">covered</span>
</div>
</div>
<div id="content">
<pre class="file" id="file0" style="display: none">package main
import (
"context"
"fmt"
"os"
"sync"
"time"
"github.com/goccy/go-json"
fiber "github.com/gofiber/fiber/v2"
"github.com/gofrs/flock"
libpack_cache "github.com/lukaszraczylo/graphql-monitoring-proxy/cache"
libpack_config "github.com/lukaszraczylo/graphql-monitoring-proxy/config"
libpack_logger "github.com/lukaszraczylo/graphql-monitoring-proxy/logging"
)
var (
bannedUsersIDs = make(map[string]string)
bannedUsersIDsMutex sync.RWMutex
)
func enableApi(ctx context.Context) error <span class="cov8" title="1">{
if !cfg.Server.EnableApi </span><span class="cov8" title="1">{
return nil
}</span>
<span class="cov0" title="0">apiserver := fiber.New(fiber.Config{
DisableStartupMessage: true,
AppName: fmt.Sprintf("GraphQL Monitoring Proxy - %s v%s", libpack_config.PKG_NAME, libpack_config.PKG_VERSION),
})
api := apiserver.Group("/api")
api.Post("/user-ban", apiBanUser)
api.Post("/user-unban", apiUnbanUser)
api.Post("/cache-clear", apiClearCache)
api.Get("/cache-stats", apiCacheStats)
// Start banned users reload in a separate goroutine with context
go periodicallyReloadBannedUsers(ctx)
// Start server in a goroutine and handle shutdown
errCh := make(chan error, 1)
go func() </span><span class="cov0" title="0">{
if err := apiserver.Listen(fmt.Sprintf(":%d", cfg.Server.ApiPort)); err != nil </span><span class="cov0" title="0">{
errCh <- err
}</span>
}()
// Wait for context cancellation or error
<span class="cov0" title="0">select </span>{
case <-ctx.Done():<span class="cov0" title="0">
cfg.Logger.Info(&libpack_logger.LogMessage{
Message: "Shutting down API server",
})
return apiserver.Shutdown()</span>
case err := <-errCh:<span class="cov0" title="0">
return err</span>
}
}
func periodicallyReloadBannedUsers(ctx context.Context) <span class="cov0" title="0">{
ticker := time.NewTicker(10 * time.Second)
defer ticker.Stop()
for </span><span class="cov0" title="0">{
select </span>{
case <-ctx.Done():<span class="cov0" title="0">
cfg.Logger.Info(&libpack_logger.LogMessage{
Message: "Stopping banned users reload",
})
return</span>
case <-ticker.C:<span class="cov0" title="0">
loadBannedUsers()
cfg.Logger.Debug(&libpack_logger.LogMessage{
Message: "Banned users reloaded",
Pairs: map[string]interface{}{"users": bannedUsersIDs},
})</span>
}
}
}
func checkIfUserIsBanned(c *fiber.Ctx, userID string) bool <span class="cov8" title="1">{
bannedUsersIDsMutex.RLock()
_, found := bannedUsersIDs[userID]
bannedUsersIDsMutex.RUnlock()
cfg.Logger.Debug(&libpack_logger.LogMessage{
Message: "Checking if user is banned",
Pairs: map[string]interface{}{"user_id": userID, "banned": found},
})
if found </span><span class="cov8" title="1">{
cfg.Logger.Info(&libpack_logger.LogMessage{
Message: "User is banned",
Pairs: map[string]interface{}{"user_id": userID},
})
if err := c.Status(fiber.StatusForbidden).SendString("User is banned"); err != nil </span><span class="cov0" title="0">{
cfg.Logger.Error(&libpack_logger.LogMessage{
Message: "Failed to send banned user response",
Pairs: map[string]interface{}{"error": err.Error()},
})
}</span>
}
<span class="cov8" title="1">return found</span>
}
func apiClearCache(c *fiber.Ctx) error <span class="cov8" title="1">{
cfg.Logger.Debug(&libpack_logger.LogMessage{
Message: "Clearing cache via API",
})
libpack_cache.CacheClear()
cfg.Logger.Info(&libpack_logger.LogMessage{
Message: "Cache cleared via API",
})
return c.SendString("OK: cache cleared")
}</span>
func apiCacheStats(c *fiber.Ctx) error <span class="cov8" title="1">{
return c.JSON(libpack_cache.GetCacheStats())
}</span>
type apiBanUserRequest struct {
UserID string `json:"user_id"`
Reason string `json:"reason"`
}
func apiBanUser(c *fiber.Ctx) error <span class="cov8" title="1">{
var req apiBanUserRequest
if err := c.BodyParser(&req); err != nil </span><span class="cov8" title="1">{
cfg.Logger.Error(&libpack_logger.LogMessage{
Message: "Can't parse the ban user request",
Pairs: map[string]interface{}{"error": err.Error()},
})
return c.Status(fiber.StatusBadRequest).SendString("Invalid request payload")
}</span>
<span class="cov8" title="1">if req.UserID == "" || req.Reason == "" </span><span class="cov8" title="1">{
return c.Status(fiber.StatusBadRequest).SendString("user_id and reason are required")
}</span>
<span class="cov8" title="1">bannedUsersIDsMutex.Lock()
bannedUsersIDs[req.UserID] = req.Reason
bannedUsersIDsMutex.Unlock()
cfg.Logger.Info(&libpack_logger.LogMessage{
Message: "Banned user",
Pairs: map[string]interface{}{"user_id": req.UserID, "reason": req.Reason},
})
if err := storeBannedUsers(); err != nil </span><span class="cov0" title="0">{
return c.Status(fiber.StatusInternalServerError).SendString("Failed to store banned users")
}</span>
<span class="cov8" title="1">return c.SendString("OK: user banned")</span>
}
func apiUnbanUser(c *fiber.Ctx) error <span class="cov8" title="1">{
var req apiBanUserRequest
if err := c.BodyParser(&req); err != nil </span><span class="cov8" title="1">{
cfg.Logger.Error(&libpack_logger.LogMessage{
Message: "Can't parse the unban user request",
Pairs: map[string]interface{}{"error": err.Error()},
})
return c.Status(fiber.StatusBadRequest).SendString("Invalid request payload")
}</span>
<span class="cov8" title="1">if req.UserID == "" </span><span class="cov8" title="1">{
return c.Status(fiber.StatusBadRequest).SendString("user_id is required")
}</span>
<span class="cov8" title="1">bannedUsersIDsMutex.Lock()
delete(bannedUsersIDs, req.UserID)
bannedUsersIDsMutex.Unlock()
cfg.Logger.Info(&libpack_logger.LogMessage{
Message: "Unbanned user",
Pairs: map[string]interface{}{"user_id": req.UserID},
})
if err := storeBannedUsers(); err != nil </span><span class="cov0" title="0">{
return c.Status(fiber.StatusInternalServerError).SendString("Failed to store banned users")
}</span>
<span class="cov8" title="1">return c.SendString("OK: user unbanned")</span>
}
func storeBannedUsers() error <span class="cov8" title="1">{
fileLock := flock.New(fmt.Sprintf("%s.lock", cfg.Api.BannedUsersFile))
if err := lockFile(fileLock); err != nil </span><span class="cov0" title="0">{
return err
}</span>
<span class="cov8" title="1">defer func() </span><span class="cov8" title="1">{
if err := fileLock.Unlock(); err != nil </span><span class="cov0" title="0">{
cfg.Logger.Error(&libpack_logger.LogMessage{
Message: "Failed to unlock file",
Pairs: map[string]interface{}{"error": err.Error()},
})
}</span>
}()
<span class="cov8" title="1">bannedUsersIDsMutex.RLock()
data, err := json.Marshal(bannedUsersIDs)
bannedUsersIDsMutex.RUnlock()
if err != nil </span><span class="cov0" title="0">{
cfg.Logger.Error(&libpack_logger.LogMessage{
Message: "Can't marshal banned users",
Pairs: map[string]interface{}{"error": err.Error()},
})
return err
}</span>
<span class="cov8" title="1">if err := os.WriteFile(cfg.Api.BannedUsersFile, data, 0o644); err != nil </span><span class="cov0" title="0">{
cfg.Logger.Error(&libpack_logger.LogMessage{
Message: "Can't write banned users to file",
Pairs: map[string]interface{}{"error": err.Error()},
})
return err
}</span>
<span class="cov8" title="1">return nil</span>
}
func loadBannedUsers() <span class="cov8" title="1">{
if _, err := os.Stat(cfg.Api.BannedUsersFile); os.IsNotExist(err) </span><span class="cov8" title="1">{
cfg.Logger.Info(&libpack_logger.LogMessage{
Message: "Banned users file doesn't exist - creating it",
Pairs: map[string]interface{}{"file": cfg.Api.BannedUsersFile},
})
if err := os.WriteFile(cfg.Api.BannedUsersFile, []byte("{}"), 0o644); err != nil </span><span class="cov0" title="0">{
cfg.Logger.Error(&libpack_logger.LogMessage{
Message: "Can't create and write to the file",
Pairs: map[string]interface{}{"error": err.Error()},
})
return
}</span>
}
<span class="cov8" title="1">fileLock := flock.New(fmt.Sprintf("%s.lock", cfg.Api.BannedUsersFile))
if err := lockFileRead(fileLock); err != nil </span><span class="cov0" title="0">{
cfg.Logger.Error(&libpack_logger.LogMessage{
Message: "Can't lock the file [load]",
Pairs: map[string]interface{}{"error": err.Error()},
})
return
}</span>
<span class="cov8" title="1">defer func() </span><span class="cov8" title="1">{
if err := fileLock.Unlock(); err != nil </span><span class="cov0" title="0">{
cfg.Logger.Error(&libpack_logger.LogMessage{
Message: "Failed to unlock file",
Pairs: map[string]interface{}{"error": err.Error()},
})
}</span>
}()
<span class="cov8" title="1">data, err := os.ReadFile(cfg.Api.BannedUsersFile)
if err != nil </span><span class="cov0" title="0">{
cfg.Logger.Error(&libpack_logger.LogMessage{
Message: "Can't read banned users from file",
Pairs: map[string]interface{}{"error": err.Error()},
})
return
}</span>
<span class="cov8" title="1">var newBannedUsers map[string]string
if err := json.Unmarshal(data, &newBannedUsers); err != nil </span><span class="cov8" title="1">{
cfg.Logger.Error(&libpack_logger.LogMessage{
Message: "Can't unmarshal banned users",
Pairs: map[string]interface{}{"error": err.Error()},
})
return
}</span>
<span class="cov8" title="1">bannedUsersIDsMutex.Lock()
bannedUsersIDs = newBannedUsers
bannedUsersIDsMutex.Unlock()</span>
}
func lockFile(fileLock *flock.Flock) error <span class="cov8" title="1">{
// Add timeout to prevent indefinite blocking
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
// Try to acquire lock with timeout
lockChan := make(chan error, 1)
go func() </span><span class="cov8" title="1">{
lockChan <- fileLock.Lock()
}</span>()
<span class="cov8" title="1">select </span>{
case err := <-lockChan:<span class="cov8" title="1">
if err != nil </span><span class="cov0" title="0">{
cfg.Logger.Error(&libpack_logger.LogMessage{
Message: "Can't lock the file",
Pairs: map[string]interface{}{"error": err.Error()},
})
return err
}</span>
<span class="cov8" title="1">return nil</span>
case <-ctx.Done():<span class="cov0" title="0">
cfg.Logger.Error(&libpack_logger.LogMessage{
Message: "File lock timeout",
Pairs: map[string]interface{}{"timeout": "30s"},
})
return fmt.Errorf("file lock timeout after 30 seconds")</span>
}
}
func lockFileRead(fileLock *flock.Flock) error <span class="cov8" title="1">{
// Add timeout to prevent indefinite blocking
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
// Try to acquire read lock with timeout
lockChan := make(chan error, 1)
go func() </span><span class="cov8" title="1">{
lockChan <- fileLock.RLock()
}</span>()
<span class="cov8" title="1">select </span>{
case err := <-lockChan:<span class="cov8" title="1">
if err != nil </span><span class="cov0" title="0">{
cfg.Logger.Error(&libpack_logger.LogMessage{
Message: "Can't lock the file for reading",
Pairs: map[string]interface{}{"error": err.Error()},
})
return err
}</span>
<span class="cov8" title="1">return nil</span>
case <-ctx.Done():<span class="cov0" title="0">
cfg.Logger.Error(&libpack_logger.LogMessage{
Message: "File read lock timeout",
Pairs: map[string]interface{}{"timeout": "30s"},
})
return fmt.Errorf("file read lock timeout after 30 seconds")</span>
}
}
</pre>
<pre class="file" id="file1" style="display: none">package main
import (
"bytes"
"compress/gzip"
"io"
"sync"
)
// BufferPool manages reusable buffers for HTTP operations
type BufferPool struct {
pool sync.Pool
}
// NewBufferPool creates a new buffer pool
func NewBufferPool() *BufferPool <span class="cov8" title="1">{
return &BufferPool{
pool: sync.Pool{
New: func() interface{} </span><span class="cov8" title="1">{
// Create a buffer with 4KB initial capacity
return bytes.NewBuffer(make([]byte, 0, 4096))
}</span>,
},
}
}
// Get retrieves a buffer from the pool
func (bp *BufferPool) Get() *bytes.Buffer <span class="cov8" title="1">{
buf := bp.pool.Get().(*bytes.Buffer)
buf.Reset()
return buf
}</span>
// Put returns a buffer to the pool
func (bp *BufferPool) Put(buf *bytes.Buffer) <span class="cov8" title="1">{
// Only return buffers that aren't too large (avoid memory bloat)
if buf.Cap() > 1024*1024 </span><span class="cov0" title="0">{ // 1MB limit
return
}</span>
<span class="cov8" title="1">buf.Reset()
bp.pool.Put(buf)</span>
}
// GzipWriterPool manages reusable gzip writers
type GzipWriterPool struct {
pool sync.Pool
}
// NewGzipWriterPool creates a new gzip writer pool
func NewGzipWriterPool() *GzipWriterPool <span class="cov8" title="1">{
return &GzipWriterPool{
pool: sync.Pool{
New: func() interface{} </span><span class="cov0" title="0">{
// Create a gzip writer with default compression
return gzip.NewWriter(nil)
}</span>,
},
}
}
// Get retrieves a gzip writer from the pool
func (gp *GzipWriterPool) Get(w io.Writer) *gzip.Writer <span class="cov0" title="0">{
gz := gp.pool.Get().(*gzip.Writer)
gz.Reset(w)
return gz
}</span>
// Put returns a gzip writer to the pool
func (gp *GzipWriterPool) Put(gz *gzip.Writer) <span class="cov0" title="0">{
gz.Reset(nil)
gp.pool.Put(gz)
}</span>
// GzipReaderPool manages reusable gzip readers
type GzipReaderPool struct {
pool sync.Pool
}
// NewGzipReaderPool creates a new gzip reader pool
func NewGzipReaderPool() *GzipReaderPool <span class="cov8" title="1">{
return &GzipReaderPool{
pool: sync.Pool{
New: func() interface{} </span><span class="cov8" title="1">{
// We'll reset the reader when getting from pool
return &gzip.Reader{}
}</span>,
},
}
}
// Get retrieves a gzip reader from the pool
func (gp *GzipReaderPool) Get(r io.Reader) (*gzip.Reader, error) <span class="cov8" title="1">{
gr := gp.pool.Get().(*gzip.Reader)
if err := gr.Reset(r); err != nil </span><span class="cov8" title="1">{
// If reset fails, create a new reader
return gzip.NewReader(r)
}</span>
<span class="cov8" title="1">return gr, nil</span>
}
// Put returns a gzip reader to the pool
func (gp *GzipReaderPool) Put(gr *gzip.Reader) <span class="cov8" title="1">{
gr.Close()
gp.pool.Put(gr)
}</span>
// Global buffer pools
var (
httpBufferPool = NewBufferPool()
gzipWriterPool = NewGzipWriterPool()
gzipReaderPool = NewGzipReaderPool()
)
// GetHTTPBuffer gets a buffer from the global pool
func GetHTTPBuffer() *bytes.Buffer <span class="cov8" title="1">{
return httpBufferPool.Get()
}</span>
// PutHTTPBuffer returns a buffer to the global pool
func PutHTTPBuffer(buf *bytes.Buffer) <span class="cov8" title="1">{
httpBufferPool.Put(buf)
}</span>
// GetGzipWriter gets a gzip writer from the global pool
func GetGzipWriter(w io.Writer) *gzip.Writer <span class="cov0" title="0">{
return gzipWriterPool.Get(w)
}</span>
// PutGzipWriter returns a gzip writer to the global pool
func PutGzipWriter(gz *gzip.Writer) <span class="cov0" title="0">{
gzipWriterPool.Put(gz)
}</span>
// GetGzipReader gets a gzip reader from the global pool
func GetGzipReader(r io.Reader) (*gzip.Reader, error) <span class="cov8" title="1">{
return gzipReaderPool.Get(r)
}</span>
// PutGzipReader returns a gzip reader to the global pool
func PutGzipReader(gr *gzip.Reader) <span class="cov8" title="1">{
gzipReaderPool.Put(gr)
}</pre>
<pre class="file" id="file2" style="display: none">package libpack_cache
import (
"bytes"
"compress/gzip"
"io"
"sync/atomic"
"time"
fiber "github.com/gofiber/fiber/v2"
"github.com/gookit/goutil/strutil"
libpack_cache_memory "github.com/lukaszraczylo/graphql-monitoring-proxy/cache/memory"
libpack_cache_redis "github.com/lukaszraczylo/graphql-monitoring-proxy/cache/redis"
libpack_logger "github.com/lukaszraczylo/graphql-monitoring-proxy/logging"
)
type CacheConfig struct {
Logger *libpack_logger.Logger
Client CacheClient
Redis struct {
URL string `json:"url"`
Password string `json:"password"`
DB int `json:"db"`
Enable bool `json:"enable"`
}
Memory struct {
MaxMemorySize int64 `json:"max_memory_size"` // Maximum memory size in bytes
MaxEntries int64 `json:"max_entries"` // Maximum number of entries
}
TTL int `json:"ttl"`
}
type CacheStats struct {
CachedQueries int64 `json:"cached_queries"`
CacheHits int64 `json:"cache_hits"`
CacheMisses int64 `json:"cache_misses"`
}
type CacheClient interface {
Set(key string, value []byte, ttl time.Duration)
Get(key string) ([]byte, bool)
Delete(key string)
Clear()
CountQueries() int64
// Memory usage reporting methods
GetMemoryUsage() int64 // Returns current memory usage in bytes
GetMaxMemorySize() int64 // Returns max memory size in bytes
}
var (
cacheStats *CacheStats
config *CacheConfig
)
func CalculateHash(c *fiber.Ctx) string <span class="cov8" title="1">{
return strutil.Md5(c.Body())
}</span>
func EnableCache(cfg *CacheConfig) <span class="cov8" title="1">{
if cfg.Logger == nil </span><span class="cov0" title="0">{
cfg.Logger = libpack_logger.New()
cfg.Logger.Info(&libpack_logger.LogMessage{
Message: "Initializing in-module logger",
})
}</span>
<span class="cov8" title="1">cacheStats = &CacheStats{}
if ShouldUseRedisCache(cfg) </span><span class="cov8" title="1">{
cfg.Logger.Debug(&libpack_logger.LogMessage{
Message: "Using Redis cache",
})
redisClient, err := libpack_cache_redis.New(&libpack_cache_redis.RedisClientConfig{
RedisDB: cfg.Redis.DB,
RedisServer: cfg.Redis.URL,
RedisPassword: cfg.Redis.Password,
})
if err != nil </span><span class="cov0" title="0">{
cfg.Logger.Error(&libpack_logger.LogMessage{
Message: "Failed to create Redis client",
Pairs: map[string]interface{}{"error": err.Error()},
})
// Fall back to memory cache
cfg.Client = libpack_cache_memory.New(time.Duration(cfg.TTL) * time.Second)
}</span> else<span class="cov8" title="1"> {
cfg.Client = libpack_cache_redis.NewCacheWrapper(redisClient, cfg.Logger)
}</span>
} else<span class="cov0" title="0"> {
cfg.Logger.Debug(&libpack_logger.LogMessage{
Message: "Using in-memory cache",
Pairs: map[string]interface{}{
"max_memory_size_bytes": cfg.Memory.MaxMemorySize,
"max_entries": cfg.Memory.MaxEntries,
},
})
// Use memory size and entry limits if configured, otherwise use defaults
if cfg.Memory.MaxMemorySize > 0 || cfg.Memory.MaxEntries > 0 </span><span class="cov0" title="0">{
maxMemory := cfg.Memory.MaxMemorySize
if maxMemory <= 0 </span><span class="cov0" title="0">{
maxMemory = libpack_cache_memory.DefaultMaxMemorySize
}</span>
<span class="cov0" title="0">maxEntries := cfg.Memory.MaxEntries
if maxEntries <= 0 </span><span class="cov0" title="0">{
maxEntries = libpack_cache_memory.DefaultMaxCacheSize
}</span>
<span class="cov0" title="0">cfg.Client = libpack_cache_memory.NewWithSize(
time.Duration(cfg.TTL)*time.Second,
maxMemory,
maxEntries,
)</span>
} else<span class="cov0" title="0"> {
// Backward compatibility
cfg.Client = libpack_cache_memory.New(time.Duration(cfg.TTL) * time.Second)
}</span>
}
<span class="cov8" title="1">config = cfg</span>
}
func CacheLookup(hash string) []byte <span class="cov8" title="1">{
if !IsCacheInitialized() </span><span class="cov0" title="0">{
return nil
}</span>
<span class="cov8" title="1">obj, found := config.Client.Get(hash)
if found </span><span class="cov8" title="1">{
atomic.AddInt64(&cacheStats.CacheHits, 1)
// If the cached data is compressed, decompress it
if len(obj) > 2 && obj[0] == 0x1f && obj[1] == 0x8b </span><span class="cov8" title="1">{
reader, err := gzip.NewReader(bytes.NewReader(obj))
if err != nil </span><span class="cov0" title="0">{
config.Logger.Error(&libpack_logger.LogMessage{
Message: "Failed to create gzip reader for cached data",
Pairs: map[string]interface{}{"error": err.Error(), "hash": hash},
})
return nil
}</span>
// Ensure reader is always closed, even on error
<span class="cov8" title="1">defer func() </span><span class="cov8" title="1">{
if closeErr := reader.Close(); closeErr != nil </span><span class="cov0" title="0">{
config.Logger.Error(&libpack_logger.LogMessage{
Message: "Failed to close gzip reader",
Pairs: map[string]interface{}{"error": closeErr.Error(), "hash": hash},
})
}</span>
}()
<span class="cov8" title="1">decompressed, err := io.ReadAll(reader)
if err != nil </span><span class="cov0" title="0">{
config.Logger.Error(&libpack_logger.LogMessage{
Message: "Failed to decompress cached data",
Pairs: map[string]interface{}{"error": err.Error(), "hash": hash},
})
return nil
}</span>
<span class="cov8" title="1">return decompressed</span>
}
<span class="cov8" title="1">return obj</span>
}
<span class="cov8" title="1">atomic.AddInt64(&cacheStats.CacheMisses, 1)
return nil</span>
}
func CacheDelete(hash string) <span class="cov8" title="1">{
if !IsCacheInitialized() </span><span class="cov8" title="1">{
return
}</span>
<span class="cov8" title="1">config.Logger.Debug(&libpack_logger.LogMessage{
Message: "Deleting data from cache",
Pairs: map[string]interface{}{"hash": hash},
})
// Use atomic operations with validation to prevent inconsistent statistics
for </span><span class="cov8" title="1">{
current := atomic.LoadInt64(&cacheStats.CachedQueries)
if current <= 0 </span><span class="cov8" title="1">{
break</span> // Don't go below zero
}
<span class="cov8" title="1">if atomic.CompareAndSwapInt64(&cacheStats.CachedQueries, current, current-1) </span><span class="cov8" title="1">{
break</span>
}
// Retry if CAS failed due to concurrent modification
}
<span class="cov8" title="1">config.Client.Delete(hash)</span>
}
func CacheStore(hash string, data []byte) <span class="cov8" title="1">{
if !IsCacheInitialized() </span><span class="cov0" title="0">{
config.Logger.Debug(&libpack_logger.LogMessage{
Message: "Cache not initialized",
})
return
}</span>
<span class="cov8" title="1">config.Logger.Debug(&libpack_logger.LogMessage{
Message: "Storing data in cache",
Pairs: map[string]interface{}{"hash": hash},
})
atomic.AddInt64(&cacheStats.CachedQueries, 1)
config.Client.Set(hash, data, time.Duration(config.TTL)*time.Second)</span>
}
func CacheStoreWithTTL(hash string, data []byte, ttl time.Duration) <span class="cov8" title="1">{
if !IsCacheInitialized() </span><span class="cov8" title="1">{
return
}</span>
<span class="cov8" title="1">config.Logger.Debug(&libpack_logger.LogMessage{
Message: "Storing data in cache with TTL",
Pairs: map[string]interface{}{"hash": hash, "ttl": ttl},
})
atomic.AddInt64(&cacheStats.CachedQueries, 1)
config.Client.Set(hash, data, ttl)</span>
}
func CacheGetQueries() int64 <span class="cov8" title="1">{
if !IsCacheInitialized() </span><span class="cov8" title="1">{
return 0
}</span>
<span class="cov8" title="1">config.Logger.Debug(&libpack_logger.LogMessage{
Message: "Counting cache queries",
})
return config.Client.CountQueries()</span>
}
func CacheClear() <span class="cov8" title="1">{
config.Client.Clear()
cacheStats = &CacheStats{}
}</span>
func GetCacheStats() *CacheStats <span class="cov8" title="1">{
if !IsCacheInitialized() </span><span class="cov8" title="1">{
return &CacheStats{}
}</span>
<span class="cov8" title="1">config.Logger.Debug(&libpack_logger.LogMessage{
Message: "Getting cache stats",
})
cacheStats.CachedQueries = CacheGetQueries()
return cacheStats</span>
}
// GetCacheMemoryUsage returns the current memory usage of the cache in bytes
func GetCacheMemoryUsage() int64 <span class="cov0" title="0">{
if !IsCacheInitialized() </span><span class="cov0" title="0">{
return 0
}</span>
<span class="cov0" title="0">return config.Client.GetMemoryUsage()</span>
}
// GetCacheMaxMemorySize returns the maximum memory size allowed for the cache in bytes
func GetCacheMaxMemorySize() int64 <span class="cov0" title="0">{
if !IsCacheInitialized() </span><span class="cov0" title="0">{
return 0
}</span>
<span class="cov0" title="0">return config.Client.GetMaxMemorySize()</span>
}
func ShouldUseRedisCache(cfg *CacheConfig) bool <span class="cov8" title="1">{
return cfg.Redis.Enable
}</span>
func IsCacheInitialized() bool <span class="cov8" title="1">{
return config != nil && config.Client != nil
}</span>
</pre>
<pre class="file" id="file3" style="display: none">package libpack_cache_memory
import (
"bytes"
"sync"
)
var bufferPool = sync.Pool{
New: func() interface{} <span class="cov0" title="0">{
return bytes.NewBuffer(make([]byte, 0, 4096))
}</span>,
}
// GetBuffer gets a buffer from the pool
func GetBuffer() *bytes.Buffer <span class="cov0" title="0">{
buf := bufferPool.Get().(*bytes.Buffer)
buf.Reset()
return buf
}</span>
// PutBuffer returns a buffer to the pool
func PutBuffer(buf *bytes.Buffer) <span class="cov0" title="0">{
if buf.Cap() > 1024*1024 </span><span class="cov0" title="0">{ // Don't pool buffers larger than 1MB
return
}</span>
<span class="cov0" title="0">buf.Reset()
bufferPool.Put(buf)</span>
}</pre>
<pre class="file" id="file4" style="display: none">package libpack_cache_memory
import (
"compress/gzip"
"container/list"
"sync"
"sync/atomic"
"time"
)
// LRUMemoryCache is an efficient LRU-based memory cache implementation
type LRUMemoryCache struct {
maxMemorySize int64
maxEntries int64
currentMemory int64
currentCount int64
mu sync.RWMutex
entries map[string]*lruEntry
evictList *list.List
gzipWriterPool *sync.Pool
gzipReaderPool *sync.Pool
cancel func()
}
type lruEntry struct {
key string
value []byte
compressed bool
size int64
expiresAt time.Time
element *list.Element
}
// NewLRUMemoryCache creates a new LRU memory cache
func NewLRUMemoryCache(maxMemorySize, maxEntries int64) *LRUMemoryCache <span class="cov0" title="0">{
return &LRUMemoryCache{
maxMemorySize: maxMemorySize,
maxEntries: maxEntries,
entries: make(map[string]*lruEntry),
evictList: list.New(),
gzipWriterPool: &sync.Pool{
New: func() interface{} </span><span class="cov0" title="0">{
return gzip.NewWriter(nil)
}</span>,
},
gzipReaderPool: &sync.Pool{
New: func() interface{} <span class="cov0" title="0">{
return &gzip.Reader{}
}</span>,
},
}
}
// Set adds or updates an entry in the cache
func (c *LRUMemoryCache) Set(key string, value []byte, ttl time.Duration) <span class="cov0" title="0">{
c.mu.Lock()
defer c.mu.Unlock()
// Calculate expiry time
expiresAt := time.Now().Add(ttl)
// Check if we should compress
compressed := false
finalValue := value
if len(value) > 1024 </span><span class="cov0" title="0">{ // Compress if larger than 1KB
if compressedData, err := c.compress(value); err == nil && len(compressedData) < len(value) </span><span class="cov0" title="0">{
compressed = true
finalValue = compressedData
}</span>
}
<span class="cov0" title="0">entrySize := int64(len(key) + len(finalValue) + 64) // 64 bytes overhead estimate
// Check if key exists
if existing, exists := c.entries[key]; exists </span><span class="cov0" title="0">{
// Update existing entry
c.evictList.MoveToFront(existing.element)
atomic.AddInt64(&c.currentMemory, -existing.size)
atomic.AddInt64(&c.currentMemory, entrySize)
existing.value = finalValue
existing.compressed = compressed
existing.size = entrySize
existing.expiresAt = expiresAt
c.evictIfNeeded()
return
}</span>
// Create new entry
<span class="cov0" title="0">entry := &lruEntry{
key: key,
value: finalValue,
compressed: compressed,
size: entrySize,
expiresAt: expiresAt,
}
element := c.evictList.PushFront(entry)
entry.element = element
c.entries[key] = entry