Compare commits

...
31 Commits
Author SHA1 Message Date
lukaszraczylo 1fd4fe4f73 Add dummy change for PR #2 2025-03-21 20:04:13 +00:00
lukaszraczylo e84eff3233 Add dummy change for PR #1 2025-03-21 20:04:05 +00:00
lukaszraczylo 3d89a77565 Fix static tests 2025-02-05 18:58:00 +00:00
lukaszraczyloandgithub-actions[bot] 4a4b24fa45 Update go.mod and go.sum
Signed-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2025-02-05 03:05:35 +00:00
lukaszraczyloandgithub-actions[bot] d2453fe2f5 Update go.mod and go.sum
Signed-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2025-01-28 03:04:14 +00:00
lukaszraczylo 28eec46f4c General improvements:
Added sharded cache to reduce lock contention
Optimized buffer usage with pre-sized pools
Improved HTTP client with connection pooling and timeouts
Reduced allocations in JSON handling
2025-01-08 11:16:51 +00:00
lukaszraczyloandgithub-actions[bot] 63e449ef77 Update go.mod and go.sum
Signed-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2025-01-07 03:09:25 +00:00
lukaszraczyloandgithub-actions[bot] 50cfc5f98d Update go.mod and go.sum
Signed-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2025-01-05 03:10:35 +00:00
lukaszraczyloandgithub-actions[bot] 4a575ac9c8 Update go.mod and go.sum
Signed-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2024-12-19 03:12:34 +00:00
lukaszraczyloandgithub-actions[bot] f54cedaeb3 Update go.mod and go.sum
Signed-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2024-12-12 03:17:28 +00:00
lukaszraczyloandgithub-actions[bot] 1080083384 Update go.mod and go.sum
Signed-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2024-12-10 03:18:24 +00:00
lukaszraczyloandgithub-actions[bot] 941aadb869 Update go.mod and go.sum
Signed-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2024-12-05 03:17:28 +00:00
lukaszraczyloandgithub-actions[bot] 8174ae6f9c Update go.mod and go.sum
Signed-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2024-11-09 03:06:06 +00:00
lukaszraczyloandgithub-actions[bot] 992a29da85 Update go.mod and go.sum
Signed-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2024-11-08 03:06:12 +00:00
lukaszraczyloandgithub-actions[bot] ecf2c06401 Update go.mod and go.sum
Signed-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2024-10-05 03:07:15 +00:00
lukaszraczyloandgithub-actions[bot] fb0785229c Update go.mod and go.sum
Signed-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2024-10-03 03:08:02 +00:00
lukaszraczylo 8ac446db41 fixup! Move towards go-reflect from goccy. 2024-09-28 17:01:17 +01:00
lukaszraczylo 586af64d70 Move towards go-reflect from goccy. 2024-09-28 17:00:53 +01:00
lukaszraczylo 50c1033ad1 Use the mocks for tests and benchmarks. 2024-09-13 21:27:34 +01:00
lukaszraczylo 7a791965ca Improve the speed & reliability of the code. 2024-09-13 21:27:34 +01:00
lukaszraczyloandgithub-actions[bot] 05b057c67c Update go.mod and go.sum
Signed-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2024-09-06 03:04:47 +00:00
lukaszraczyloandgithub-actions[bot] 9c729d814a Update go.mod and go.sum
Signed-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2024-09-05 03:03:42 +00:00
lukaszraczyloandgithub-actions[bot] 9d5e2122b8 Update go.mod and go.sum
Signed-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2024-08-09 03:03:59 +00:00
lukaszraczyloandgithub-actions[bot] a19f1d257a Update go.mod and go.sum
Signed-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2024-08-07 03:03:51 +00:00
lukaszraczyloandgithub-actions[bot] 563c952c78 Update go.mod and go.sum
Signed-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2024-08-05 03:03:39 +00:00
lukaszraczyloandgithub-actions[bot] 2f259a4b3f Update go.mod and go.sum
Signed-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2024-07-31 15:18:46 +00:00
lukaszraczyloandGitHub 957857537a Update autoupdate.yaml 2024-07-31 16:16:59 +01:00
lukaszraczylo 4ea4bbb6cc Add autoupdate functionality. 2024-07-23 20:25:22 +01:00
lukaszraczyloandGitHub 36ef16ad3d general improvements (#2)
* Replaced strutil.Md5 with crypto/md5 and encoding/hex to reduce dependency and potential allocations.

* Move to improved logging library.

* fixup! Move to improved logging library.
2024-06-28 09:22:52 +01:00
lukaszraczylo 42170f9b8e fixup! Revamp the query compilation process. 2024-05-14 11:30:42 +01:00
lukaszraczylo 4f438b7eac Revamp the query compilation process. 2024-05-14 11:18:31 +01:00
24 changed files with 1116 additions and 457 deletions
+73
View File
@@ -0,0 +1,73 @@
name: Autoupdate go.mod and go.sum
on:
workflow_dispatch:
schedule:
- cron: "0 3 * * *"
env:
GO_VERSION: ">=1.21"
jobs:
# This job is responsible for preparation of the build
# environment variables.
prepare:
name: Preparing build context
runs-on: ubuntu-latest
steps:
- name: Checkout repo
uses: actions/checkout@v4
- name: Install Go
uses: actions/setup-go@v5
id: cache
with:
go-version: ${{env.GO_VERSION}}
cache-dependency-path: "**/*.sum"
- name: Go get dependencies
if: steps.cache.outputs.cache-hit != 'true'
run: |
go get ./...
# This job is responsible for running tests and linting the codebase
test:
name: "Unit testing"
runs-on: ubuntu-latest
container: golang:1
needs: [prepare]
steps:
- name: Checkout repository
uses: actions/checkout@v4
with:
fetch-depth: 0 # Ensure full history is checked out
token: ${{ secrets.GHCR_TOKEN }}
- name: Install Go
uses: actions/setup-go@v5
with:
go-version: ${{env.GO_VERSION}}
cache-dependency-path: "**/*.sum"
- name: Install dependencies
run: |
apt-get update
apt-get install ca-certificates make -y
update-ca-certificates
go mod tidy
go get -u -v ./...
go mod tidy -v
- name: Run unit tests
run: |
CI_RUN=${CI} make test
git config --global --add safe.directory /__w/go-simple-graphql/go-simple-graphql
- name: Commit changes
uses: stefanzweifel/git-auto-commit-action@v5
with:
commit_message: "Update go.mod and go.sum"
commit_options: "--no-verify --signoff"
file_pattern: "go.mod go.sum"
+60 -33
View File
@@ -3,6 +3,7 @@ package libpack_cache
import (
"bytes"
"compress/gzip"
"hash/fnv"
"io"
"sync"
"time"
@@ -13,12 +14,25 @@ type CacheEntry struct {
Value []byte
}
const shardCount = 256 // Must be power of 2
type shard struct {
entries map[string]CacheEntry
sync.RWMutex
}
type Cache struct {
entries sync.Map
globalTTL time.Duration
compressPool sync.Pool
decompressPool sync.Pool
sync.RWMutex // Reintroduced to provide lock methods
shards [shardCount]*shard
globalTTL time.Duration
}
// getShard returns the appropriate shard for a given key
func (c *Cache) getShard(key string) *shard {
hash := fnv.New32a()
hash.Write([]byte(key))
return c.shards[hash.Sum32()%shardCount]
}
func New(globalTTL time.Duration) *Cache {
@@ -32,13 +46,19 @@ func New(globalTTL time.Duration) *Cache {
},
decompressPool: sync.Pool{
New: func() interface{} {
// Ensure that new is returning a new reader initialized with an empty byte buffer
r, _ := gzip.NewReader(bytes.NewReader([]byte{}))
return r
},
},
}
// Initialize shards
for i := 0; i < shardCount; i++ {
cache.shards[i] = &shard{
entries: make(map[string]CacheEntry),
}
}
go cache.cleanupRoutine(globalTTL)
return cache
}
@@ -52,33 +72,43 @@ func (c *Cache) cleanupRoutine(globalTTL time.Duration) {
}
}
func (c *Cache) Set(key string, value []byte, ttl time.Duration) {
c.Lock() // use the lock
defer c.Unlock()
expiresAt := time.Now().Add(ttl)
shard := c.getShard(key)
shard.Lock()
defer shard.Unlock()
compressedValue, err := c.compress(value)
if err != nil {
return
}
entry := CacheEntry{
shard.entries[key] = CacheEntry{
Value: compressedValue,
ExpiresAt: expiresAt,
ExpiresAt: time.Now().Add(ttl),
}
c.entries.Store(key, entry)
}
func (c *Cache) Get(key string) ([]byte, bool) {
c.RLock() // use the read lock
defer c.RUnlock()
entry, ok := c.entries.Load(key)
if !ok || entry.(CacheEntry).ExpiresAt.Before(time.Now()) {
shard := c.getShard(key)
shard.RLock()
entry, ok := shard.entries[key]
if !ok {
shard.RUnlock()
return nil, false
}
compressedValue := entry.(CacheEntry).Value
value, err := c.decompress(compressedValue)
if entry.ExpiresAt.Before(time.Now()) {
shard.RUnlock()
// Clean up expired entry in background
go func() {
shard.Lock()
delete(shard.entries, key)
shard.Unlock()
}()
return nil, false
}
shard.RUnlock()
value, err := c.decompress(entry.Value)
if err != nil {
return nil, false
}
@@ -87,26 +117,23 @@ func (c *Cache) Get(key string) ([]byte, bool) {
}
func (c *Cache) Delete(key string) {
c.Lock()
defer c.Unlock()
_, ok := c.entries.Load(key)
if !ok {
return
}
c.entries.Delete(key)
shard := c.getShard(key)
shard.Lock()
delete(shard.entries, key)
shard.Unlock()
}
func (c *Cache) CleanExpiredEntries() {
now := time.Now()
c.entries.Range(func(key, value interface{}) bool {
entry := value.(CacheEntry)
if entry.ExpiresAt.Before(now) {
c.entries.Delete(key)
for _, shard := range c.shards {
shard.Lock()
for key, entry := range shard.entries {
if entry.ExpiresAt.Before(now) {
delete(shard.entries, key)
}
}
return true
})
shard.Unlock()
}
}
func (c *Cache) compress(data []byte) ([]byte, error) {
+1
View File
@@ -0,0 +1 @@
This is a dummy change for PR #1
+1
View File
@@ -0,0 +1 @@
This is a dummy change for PR #2
+86 -28
View File
@@ -11,101 +11,159 @@ import (
"github.com/avast/retry-go/v4"
"github.com/goccy/go-json"
libpack_logger "github.com/lukaszraczylo/go-simple-graphql/logging"
)
var (
// Shared HTTP transport with optimized settings
defaultTransport = &http.Transport{
MaxIdleConns: 100,
MaxIdleConnsPerHost: 100,
IdleConnTimeout: 90 * time.Second,
DisableCompression: false, // Enable compression for responses
ForceAttemptHTTP2: true,
}
// Shared HTTP client with timeouts
defaultClient = &http.Client{
Transport: defaultTransport,
Timeout: 30 * time.Second,
}
)
func (qe *QueryExecutor) executeQuery() ([]byte, error) {
httpRequest, err := http.NewRequest(http.MethodPost, qe.endpoint, bytes.NewBuffer(qe.Query))
// Reuse buffer from pool to avoid allocations
buf := bufferPool.Get().(*bytes.Buffer)
defer bufferPool.Put(buf)
buf.Reset()
buf.Write(qe.Query)
httpRequest, err := http.NewRequest(http.MethodPost, qe.endpoint, nil)
if err != nil {
qe.Logger.Error("Can't create HTTP request", map[string]interface{}{"error": err})
qe.Logger.Error(&libpack_logger.LogMessage{
Message: "Can't create HTTP request",
Pairs: map[string]interface{}{"error": err.Error()},
})
return nil, err
}
for key, value := range qe.Headers {
httpRequest.Header.Set(key, fmt.Sprint(value))
}
// Set Content-Type header if not already set
if httpRequest.Header.Get("Content-Type") == "" {
httpRequest.Header.Set("Content-Type", "application/json")
}
retriesMax := 1
if qe.Retries {
qe.Logger.Debug("Retries enabled", map[string]interface{}{"retries": qe.retries_number})
retriesMax = qe.retries_number
} else {
qe.Logger.Debug("Retries disabled", map[string]interface{}{"retries": 1})
}
var queryResult queryResults
err = retry.Do(
func() error {
httpResponse, err := qe.client.Do(httpRequest)
// Reset buffer before each retry
buf.Reset()
buf.Write(qe.Query)
// Set the body of the request
httpRequest.Body = io.NopCloser(bytes.NewReader(buf.Bytes()))
httpRequest.ContentLength = int64(buf.Len())
// Use default client if custom client is not set
client := qe.client
if client == nil {
client = defaultClient
}
httpResponse, err := client.Do(httpRequest)
if err != nil {
qe.Logger.Debug("Error executing HTTP request", map[string]interface{}{"error": err.Error()})
return err
}
defer func() {
_, err := io.Copy(io.Discard, httpResponse.Body)
if err != nil {
qe.Logger.Debug("Error discarding HTTP response body", map[string]interface{}{"error": err.Error()})
}
io.Copy(io.Discard, httpResponse.Body)
httpResponse.Body.Close()
}()
if httpResponse.StatusCode < http.StatusOK || httpResponse.StatusCode >= http.StatusNoContent {
if httpResponse.StatusCode < http.StatusOK || httpResponse.StatusCode >= http.StatusMultipleChoices {
return fmt.Errorf("HTTP error - status code: %s for %s", httpResponse.Status, httpRequest.URL)
}
var reader io.ReadCloser
var reader io.Reader
encoding := httpResponse.Header.Get("Content-Encoding")
switch encoding {
case "gzip":
reader, err = gzip.NewReader(httpResponse.Body)
if encoding == "gzip" {
gzipReader, err := gzip.NewReader(httpResponse.Body)
if err != nil {
qe.Logger.Debug("Error creating gzip reader", map[string]interface{}{"error": err.Error()})
return fmt.Errorf("error creating gzip reader: %w", err)
}
defer reader.Close()
default:
defer gzipReader.Close()
reader = gzipReader
} else {
reader = httpResponse.Body
}
body, err := io.ReadAll(reader)
// Use buffer pool for reading response
respBuf := bufferPool.Get().(*bytes.Buffer)
respBuf.Reset()
defer bufferPool.Put(respBuf)
_, err = io.Copy(respBuf, reader)
if err != nil {
qe.Logger.Debug("Error reading HTTP response", map[string]interface{}{"error": err.Error()})
return fmt.Errorf("error reading HTTP response: %w", err)
}
err = json.Unmarshal(body, &queryResult)
// Unmarshal response directly from buffer
err = json.Unmarshal(respBuf.Bytes(), &queryResult)
if err != nil {
qe.Logger.Debug("Error unmarshalling HTTP response", map[string]interface{}{"error": err.Error()})
return fmt.Errorf("error unmarshalling HTTP response: %w", err)
}
return nil
},
retry.OnRetry(func(n uint, err error) {
qe.Logger.Warning("Retrying query", map[string]interface{}{"error": err.Error(), "attempt": n})
qe.Logger.Warning(&libpack_logger.LogMessage{
Message: "Retrying query",
Pairs: map[string]interface{}{"error": err.Error(), "attempt": n + 1},
})
}),
retry.Attempts(uint(retriesMax)),
retry.DelayType(retry.BackOffDelay),
retry.Delay(time.Duration(qe.retries_delay)),
retry.MaxDelay(10 * time.Second),
retry.LastErrorOnly(true),
)
if err != nil {
qe.Logger.Debug("Error executing HTTP request", map[string]interface{}{"error": err.Error()})
qe.Logger.Debug(&libpack_logger.LogMessage{
Message: "Error executing HTTP request",
Pairs: map[string]interface{}{"error": err.Error()},
})
return nil, err
}
if len(queryResult.Errors) > 0 {
qe.Logger.Debug("Error executing query", map[string]interface{}{"error": queryResult.Errors})
qe.Logger.Debug(&libpack_logger.LogMessage{
Message: "Error executing query",
Pairs: map[string]interface{}{"error": queryResult.Errors},
})
return nil, fmt.Errorf("error executing query: %s", queryResult.Errors)
}
if queryResult.Data == nil {
qe.Logger.Debug("Error executing query", map[string]interface{}{"error": "no data"})
qe.Logger.Debug(&libpack_logger.LogMessage{
Message: "Error executing query",
Pairs: map[string]interface{}{"error": "no data"},
})
return nil, errors.New("error executing query: no data")
}
// Marshal queryResult.Data
jsonData, err := json.Marshal(queryResult.Data)
if err != nil {
qe.Logger.Debug("Error marshalling query result", map[string]interface{}{"error": err.Error(), "data": queryResult.Data})
qe.Logger.Debug(&libpack_logger.LogMessage{
Message: "Error marshalling query result",
Pairs: map[string]interface{}{"error": err.Error(), "data": queryResult.Data},
})
return nil, fmt.Errorf("error marshalling query result: %w. Data: %s", err, queryResult.Data)
}
+8 -10
View File
@@ -4,23 +4,21 @@ go 1.21
require (
github.com/avast/retry-go/v4 v4.6.0
github.com/goccy/go-json v0.10.2
github.com/gookit/goutil v0.6.15
github.com/rs/zerolog v1.32.0
github.com/goccy/go-json v0.10.5
github.com/goccy/go-reflect v1.2.0
github.com/gookit/goutil v0.6.18
github.com/stretchr/testify v1.9.0
golang.org/x/net v0.25.0
golang.org/x/net v0.34.0
)
require (
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/gookit/color v1.5.4 // indirect
github.com/mattn/go-colorable v0.1.13 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect
golang.org/x/sync v0.7.0 // indirect
golang.org/x/sys v0.20.0 // indirect
golang.org/x/term v0.20.0 // indirect
golang.org/x/text v0.15.0 // indirect
golang.org/x/sync v0.11.0 // indirect
golang.org/x/sys v0.30.0 // indirect
golang.org/x/term v0.29.0 // indirect
golang.org/x/text v0.22.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)
+16 -29
View File
@@ -1,46 +1,33 @@
github.com/avast/retry-go/v4 v4.6.0 h1:K9xNA+KeB8HHc2aWFuLb25Offp+0iVRXEvFx8IinRJA=
github.com/avast/retry-go/v4 v4.6.0/go.mod h1:gvWlPhBVsvBbLkVGDg/KwvBv0bEkCOLRRSHKIr2PyOE=
github.com/coreos/go-systemd/v22 v22.5.0/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU=
github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I=
github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=
github.com/goccy/go-json v0.10.5 h1:Fq85nIqj+gXn/S5ahsiTlK3TmC85qgirsdTP/+DeaC4=
github.com/goccy/go-json v0.10.5/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M=
github.com/goccy/go-reflect v1.2.0 h1:O0T8rZCuNmGXewnATuKYnkL0xm6o8UNOJZd/gOkb9ms=
github.com/goccy/go-reflect v1.2.0/go.mod h1:n0oYZn8VcV2CkWTxi8B9QjkCoq6GTtCEdfmR66YhFtE=
github.com/gookit/color v1.5.4 h1:FZmqs7XOyGgCAxmWyPslpiok1k05wmY3SJTytgvYFs0=
github.com/gookit/color v1.5.4/go.mod h1:pZJOeOS8DM43rXbp4AZo1n9zCU2qjpcRko0b6/QJi9w=
github.com/gookit/goutil v0.6.15 h1:mMQ0ElojNZoyPD0eVROk5QXJPh2uKR4g06slgPDF5Jo=
github.com/gookit/goutil v0.6.15/go.mod h1:qdKdYEHQdEtyH+4fNdQNZfJHhI0jUZzHxQVAV3DaMDY=
github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA=
github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg=
github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/gookit/goutil v0.6.18 h1:MUVj0G16flubWT8zYVicIuisUiHdgirPAkmnfD2kKgw=
github.com/gookit/goutil v0.6.18/go.mod h1:AY/5sAwKe7Xck+mEbuxj0n/bc3qwrGNe3Oeulln7zBA=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/rs/xid v1.5.0/go.mod h1:trrq9SKmegXys3aeAKXMUTdJsYXVwGY3RLcfgqegfbg=
github.com/rs/zerolog v1.32.0 h1:keLypqrlIjaFsbmJOBdB/qvyF8KEtCWHwobLp5l/mQ0=
github.com/rs/zerolog v1.32.0/go.mod h1:/7mN4D5sKwJLZQ2b/znpjC3/GQWY/xaDXUM0kKWRHss=
github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e h1:JVG44RsyaB9T2KIHavMF/ppJZNG9ZpyihvCd0w101no=
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e/go.mod h1:RbqR21r5mrJuqunuUZ/Dhy/avygyECGrLceyNeo4LiM=
golang.org/x/exp v0.0.0-20220909182711-5c715a9e8561 h1:MDc5xs78ZrZr3HMQugiXOAkSZtfTpbJLDr/lwfgO53E=
golang.org/x/exp v0.0.0-20220909182711-5c715a9e8561/go.mod h1:cyybsKvd6eL0RnXn6p/Grxp8F5bW7iYuBgsNCOHpMYE=
golang.org/x/net v0.25.0 h1:d/OCCoBEUq33pjydKrGQhw7IlUPI2Oylr+8qLx49kac=
golang.org/x/net v0.25.0/go.mod h1:JkAGAh7GEvH74S6FOH42FLoXpXbE/aqXSrIQjXgsiwM=
golang.org/x/sync v0.7.0 h1:YsImfSBoP9QPYL0xyKJPq0gcaJdG3rInoqxTWbfQu9M=
golang.org/x/sync v0.7.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.20.0 h1:Od9JTbYCk261bKm4M/mw7AklTlFYIa0bIp9BgSm1S8Y=
golang.org/x/sys v0.20.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/term v0.20.0 h1:VnkxpohqXaOBYJtBmEppKUG6mXpi+4O6purfc2+sMhw=
golang.org/x/term v0.20.0/go.mod h1:8UkIAJTvZgivsXaD6/pH6U9ecQzZ45awqEOzuCvwpFY=
golang.org/x/text v0.15.0 h1:h1V/4gjBv8v9cjcR6+AR5+/cIYK5N/WAgiv4xlsEtAk=
golang.org/x/text v0.15.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
golang.org/x/net v0.34.0 h1:Mb7Mrk043xzHgnRM88suvJFwzVrRfHEHJEl5/71CKw0=
golang.org/x/net v0.34.0/go.mod h1:di0qlW3YNM5oh6GqDGQr92MyTozJPmybPK4Ev/Gm31k=
golang.org/x/sync v0.11.0 h1:GGz8+XQP4FvTTrjZPzNKTMFtSXH80RAzG+5ghFPgK9w=
golang.org/x/sync v0.11.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
golang.org/x/sys v0.30.0 h1:QjkSwP/36a20jFYWkSue1YwXzLmsV5Gfq7Eiy72C1uc=
golang.org/x/sys v0.30.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/term v0.29.0 h1:L6pJp37ocefwRRtYPKSWOWzOtWSxVajvz2ldH/xi3iU=
golang.org/x/term v0.29.0/go.mod h1:6bl4lRlvVuDgSf3179VpIxBF0o10JUpXWOnI7nErv7s=
golang.org/x/text v0.22.0 h1:bofq7m3/HAFvbF51jz3Q9wLg3jkvSPuiZu/pD1XwgtM=
golang.org/x/text v0.22.0/go.mod h1:YRoo4H8PVmsu+E3Ou7cqLVH8oXWIHVoX0jqUWALQhfY=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
+15 -6
View File
@@ -1,13 +1,15 @@
package gql
import (
"crypto/md5"
"encoding/hex"
"fmt"
"github.com/goccy/go-json"
"github.com/gookit/goutil/strutil"
libpack_logger "github.com/lukaszraczylo/go-simple-graphql/logging"
)
func searchForKeysInMapStringInterface(msi map[string]interface{}, key string) (value any) {
func searchForKeysInMapStringInterface(msi map[string]interface{}, key string) interface{} {
if msi == nil {
return nil
}
@@ -15,7 +17,8 @@ func searchForKeysInMapStringInterface(msi map[string]interface{}, key string) (
}
func calculateHash(query *Query) string {
return strutil.Md5(query.JsonQuery)
hash := md5.Sum(query.JsonQuery)
return hex.EncodeToString(hash[:])
}
func (b *BaseClient) cacheLookup(hash string) []byte {
@@ -29,7 +32,10 @@ func (b *BaseClient) decodeResponse(response []byte) (any, error) {
var result map[string]interface{}
err := json.Unmarshal(response, &result)
if err != nil {
b.Logger.Error("Can't decode response into mapstring", map[string]interface{}{"error": err.Error()})
b.Logger.Error(&libpack_logger.LogMessage{
Message: "Can't decode response into mapstring",
Pairs: map[string]interface{}{"error": err.Error()},
})
return nil, err
}
return result, nil
@@ -38,7 +44,10 @@ func (b *BaseClient) decodeResponse(response []byte) (any, error) {
case "byte":
return response, nil
default:
b.Logger.Error("Can't decode response;", map[string]interface{}{"error": "unknown response type"})
return nil, fmt.Errorf("Can't decode response - unknown response type specified")
b.Logger.Error(&libpack_logger.LogMessage{
Message: "Can't decode response",
Pairs: map[string]interface{}{"error": "unknown response type"},
})
return nil, fmt.Errorf("can't decode response - unknown response type specified")
}
}
+2 -1
View File
@@ -1,8 +1,9 @@
package gql
import (
"reflect"
"testing"
"github.com/goccy/go-reflect"
)
func (suite *Tests) Test_searchForKeysInMapStringInterface() {
+12 -3
View File
@@ -6,6 +6,7 @@ import (
"strings"
"time"
libpack_logger "github.com/lukaszraczylo/go-simple-graphql/logging"
"golang.org/x/net/http2"
)
@@ -28,7 +29,10 @@ func (b *BaseClient) createHttpClient() (http_client *http.Client) {
return http.ErrUseLastResponse
},
}
b.Logger.Debug("Using HTTP/1.1 over http", nil)
b.Logger.Debug(&libpack_logger.LogMessage{
Message: "Using HTTP/1.1 over http",
Pairs: nil,
})
} else if strings.HasPrefix(b.endpoint, "https://") {
tlsClientConfig := &tls.Config{}
if strings.HasPrefix(b.endpoint, "https://") {
@@ -46,9 +50,14 @@ func (b *BaseClient) createHttpClient() (http_client *http.Client) {
return http.ErrUseLastResponse
},
}
b.Logger.Debug("Using HTTP/2 over https", nil)
b.Logger.Debug(&libpack_logger.LogMessage{
Message: "Using HTTP/2 over https",
Pairs: nil,
})
} else {
b.Logger.Critical("Invalid endpoint - neither http or https", nil)
b.Logger.Critical(&libpack_logger.LogMessage{
Message: "Invalid endpoint - neither http or https",
})
}
return http_client
}
+204
View File
@@ -0,0 +1,204 @@
package libpack_logger
import (
"bytes"
"flag"
"fmt"
"io"
"os"
"path/filepath"
"runtime"
"strings"
"sync"
"time"
"github.com/goccy/go-json"
)
const (
_ = iota
LEVEL_DEBUG
LEVEL_INFO
LEVEL_WARN
LEVEL_ERROR
LEVEL_FATAL
)
var LevelNames = [...]string{
"none",
"debug",
"info",
"warn",
"error",
"fatal",
}
const (
defaultFormat = time.RFC3339
defaultMinLevel = LEVEL_INFO
defaultShowCaller = false
)
var defaultOutput = os.Stdout
type Logger struct {
output io.Writer
format string
minLogLevel int
showCaller bool
}
type LogMessage struct {
output io.Writer
Pairs map[string]any
Message string
}
func (m *LogMessage) String() string {
return m.Message
}
var fieldNames = map[string]string{
"timestamp": "timestamp",
"level": "level",
"message": "message",
}
func New() *Logger {
return &Logger{
format: defaultFormat,
minLogLevel: defaultMinLevel,
output: defaultOutput,
showCaller: defaultShowCaller,
}
}
func (l *Logger) SetOutput(output io.Writer) *Logger {
l.output = output
return l
}
var bufferPool = sync.Pool{
New: func() any {
return new(bytes.Buffer)
},
}
var defaultPairs = make(map[string]any)
func GetLogLevel(level string) int {
for i, name := range LevelNames {
if name == strings.ToLower(level) {
return i
}
}
return defaultMinLevel
}
func (l *Logger) log(level int, m *LogMessage) {
if m.Pairs == nil {
m.Pairs = defaultPairs
}
m.Pairs[fieldNames["timestamp"]] = time.Now().Format(l.format)
m.Pairs[fieldNames["level"]] = LevelNames[level]
m.Pairs[fieldNames["message"]] = m.Message
if l.showCaller {
m.Pairs["caller"] = getCaller()
}
buffer := bufferPool.Get().(*bytes.Buffer)
defer bufferPool.Put(buffer)
buffer.Reset()
var encoder = json.NewEncoder(buffer)
err := encoder.Encode(m.Pairs)
if err != nil {
fmt.Println("Error marshalling log message:", err)
return
}
// if not running in test - use stderr and stdout, otherwise - use logger's output setting
if flag.Lookup("test.v") != nil {
m.output = os.Stdout
if level >= LEVEL_ERROR {
m.output = os.Stderr
}
}
// Use logger's output setting instead of os.Stdout or os.Stderr
l.output.Write(buffer.Bytes())
}
func (l *Logger) Debug(m *LogMessage) {
if l.shouldLog(LEVEL_DEBUG) {
l.log(LEVEL_DEBUG, m)
}
}
func (l *Logger) Info(m *LogMessage) {
if l.shouldLog(LEVEL_INFO) {
l.log(LEVEL_INFO, m)
}
}
func (l *Logger) Warn(m *LogMessage) {
if l.shouldLog(LEVEL_WARN) {
l.log(LEVEL_WARN, m)
}
}
func (l *Logger) Warning(m *LogMessage) {
l.Warn(m)
}
func (l *Logger) Error(m *LogMessage) {
if l.shouldLog(LEVEL_ERROR) {
l.log(LEVEL_ERROR, m)
}
}
func (l *Logger) Fatal(m *LogMessage) {
if l.shouldLog(LEVEL_FATAL) {
l.log(LEVEL_FATAL, m)
}
}
func (l *Logger) Critical(m *LogMessage) {
l.Fatal(m)
os.Exit(1)
}
func (l *Logger) shouldLog(level int) bool {
return level >= l.minLogLevel
}
func (l *Logger) SetFormat(format string) *Logger {
l.format = format
return l
}
func (l *Logger) SetMinLogLevel(level int) *Logger {
l.minLogLevel = level
return l
}
func (l *Logger) SetFieldName(field, name string) *Logger {
fieldNames[field] = name
return l
}
func (l *Logger) SetShowCaller(show bool) *Logger {
l.showCaller = show
return l
}
func getCaller() string {
_, file, line, ok := runtime.Caller(3)
if !ok {
return "unknown:0"
}
file = filepath.Base(file)
return fmt.Sprintf("%s:%d", file, line)
}
+140
View File
@@ -0,0 +1,140 @@
package libpack_logger
import (
"bytes"
"testing"
"time"
)
func Benchmark_NewLogger(b *testing.B) {
type triggers struct {
ModFormat struct {
Format string
}
ModLevel struct {
Level int
}
}
tests := []struct {
name string
triggers triggers
}{
{
name: "BenchmarkNew",
},
{
name: "BenchmarkNewChangeTimeFormat",
triggers: triggers{
ModFormat: struct{ Format string }{
Format: time.RFC3339Nano,
},
},
},
{
name: "BenchmarkNewChangeLogLevel",
triggers: triggers{
ModLevel: struct{ Level int }{
Level: LEVEL_DEBUG,
},
},
},
{
name: "BenchmarkNewChangeTimeFormatAndLogLevel",
triggers: triggers{
ModFormat: struct{ Format string }{
Format: time.RFC3339Nano,
},
ModLevel: struct{ Level int }{
Level: LEVEL_DEBUG,
},
},
},
}
for _, tt := range tests {
b.Run(tt.name, func(b *testing.B) {
for i := 0; i < b.N; i++ {
got := New()
if tt.triggers.ModFormat.Format != "" {
got.SetFormat(tt.triggers.ModFormat.Format)
}
if tt.triggers.ModLevel.Level != 0 {
got.SetMinLogLevel(tt.triggers.ModLevel.Level)
}
}
})
}
}
func Benchmark_Log_Debug(b *testing.B) {
output := &bytes.Buffer{}
logger := New().SetMinLogLevel(LEVEL_DEBUG).SetOutput(output)
msg := &LogMessage{
Message: "debug message",
Pairs: make(map[string]any),
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
logger.Debug(msg)
}
}
func Benchmark_Log_Info(b *testing.B) {
output := &bytes.Buffer{}
logger := New().SetMinLogLevel(LEVEL_INFO).SetOutput(output)
msg := &LogMessage{
Message: "info message",
Pairs: make(map[string]any),
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
logger.Info(msg)
}
}
func Benchmark_Log_Warn(b *testing.B) {
output := &bytes.Buffer{}
logger := New().SetMinLogLevel(LEVEL_WARN).SetOutput(output)
msg := &LogMessage{
Message: "warn message",
Pairs: make(map[string]any),
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
logger.Warn(msg)
}
}
func Benchmark_Log_Error(b *testing.B) {
output := &bytes.Buffer{}
logger := New().SetMinLogLevel(LEVEL_ERROR).SetOutput(output)
msg := &LogMessage{
Message: "error message",
Pairs: map[string]any{"key": "value"},
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
logger.Error(msg)
}
}
func Benchmark_Log_Fatal(b *testing.B) {
output := &bytes.Buffer{}
logger := New().SetMinLogLevel(LEVEL_FATAL).SetOutput(output)
msg := &LogMessage{
Message: "fatal message",
Pairs: make(map[string]any),
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
logger.Fatal(msg)
}
}
+31
View File
@@ -0,0 +1,31 @@
package libpack_logger
import (
"testing"
assertions "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/suite"
)
type LoggerTestSuite struct {
suite.Suite
}
var (
assert *assertions.Assertions
)
func (suite *LoggerTestSuite) BeforeTest(suiteName, testName string) {
}
func (suite *LoggerTestSuite) SetupTest() {
assert = assertions.New(suite.T())
}
// TearDownTest is run after each test to clean up
func (suite *LoggerTestSuite) TearDownTest() {
}
func TestSuite(t *testing.T) {
suite.Run(t, new(LoggerTestSuite))
}
+157
View File
@@ -0,0 +1,157 @@
package libpack_logger
import (
"bytes"
"fmt"
"testing"
"time"
"github.com/goccy/go-json"
"github.com/goccy/go-reflect"
)
func (suite *LoggerTestSuite) Test_LogMessageString() {
msg := &LogMessage{
Message: "test message",
}
assert.Equal("test message", msg.String())
}
func callLoggerMethod(logger *Logger, methodName string, message *LogMessage) {
// Get the method by name using reflection
method := reflect.ValueOf(logger).MethodByName(methodName)
if method.IsValid() {
// Call the method with the message as an argument
method.Call([]reflect.Value{reflect.ValueOf(message)})
} else {
fmt.Printf("Method %s does not exist on Logger\n", methodName)
}
}
func (suite *LoggerTestSuite) Test_LogsLevelsPrint() {
output := &bytes.Buffer{}
logger := New().SetOutput(output)
tests := []struct {
pairs map[string]any
name string
method string
message string
loggerMinLevel int
messageLogLevel int
wantOutput bool
}{
{
name: "Log: Debug, Level: Debug - no pairs",
method: "Debug",
loggerMinLevel: LEVEL_DEBUG,
messageLogLevel: LEVEL_DEBUG,
message: "debug message",
wantOutput: true,
},
{
name: "Log: Info, Level: Info - one pair",
method: "Info",
loggerMinLevel: LEVEL_INFO,
messageLogLevel: LEVEL_INFO,
message: "info message",
pairs: map[string]any{
"key": "value",
},
wantOutput: true,
},
{
name: "Log: Info, Level: Warn - with pairs",
method: "Info",
loggerMinLevel: LEVEL_WARN,
messageLogLevel: LEVEL_INFO,
message: "warn message",
pairs: map[string]any{
"key1": "value1",
"key2": "value2",
},
wantOutput: false,
},
{
name: "Log: Warn, Level: Info - with 500 pairs",
method: "Warn",
loggerMinLevel: LEVEL_INFO,
messageLogLevel: LEVEL_WARN,
message: "warn message with 500 pairs",
pairs: func() map[string]any {
pairs := make(map[string]any)
for i := 0; i < 500; i++ {
pairs[fmt.Sprintf("key%d", i)] = fmt.Sprintf("value%d", i)
}
return pairs
}(),
wantOutput: true,
},
}
for _, tt := range tests {
suite.T().Run(tt.name, func(t *testing.T) {
msg := &LogMessage{
Message: tt.message,
Pairs: tt.pairs,
}
output.Reset()
// Set logger's minimum log level
logger.SetMinLogLevel(tt.loggerMinLevel)
fmt.Println("Logger min log level:", LevelNames[logger.minLogLevel])
// Call the logging method
callLoggerMethod(logger, tt.method, msg)
logOutput := output.String()
fmt.Println("Output:", logOutput)
if tt.wantOutput {
var loggedMessage map[string]any
err := json.Unmarshal([]byte(logOutput), &loggedMessage)
if err != nil {
t.Fatalf("Error unmarshalling log message: %v\nLog output: %s", err, logOutput)
}
if !containsLogMessage(logOutput, tt.message) {
t.Errorf("Expected log message %q, but got %q", tt.message, logOutput)
}
assert.Equal(LevelNames[tt.messageLogLevel], loggedMessage["level"])
if tt.pairs != nil {
for k, v := range tt.pairs {
assert.Equal(v, loggedMessage[k])
}
}
} else {
assert.Equal("", logOutput)
}
})
}
}
func containsLogMessage(logOutput, expectedMessage string) bool {
return bytes.Contains([]byte(logOutput), []byte(expectedMessage))
}
func (suite *LoggerTestSuite) Test_SetFormat() {
logger := New().SetFormat(time.RFC3339Nano)
assert.Equal(time.RFC3339Nano, logger.format)
}
func (suite *LoggerTestSuite) Test_SetMinLogLevel() {
logger := New().SetMinLogLevel(LEVEL_DEBUG)
assert.Equal(LEVEL_DEBUG, logger.minLogLevel)
}
func (suite *LoggerTestSuite) Test_ShouldLog() {
logger := New().SetMinLogLevel(LEVEL_WARN)
assert.True(logger.shouldLog(LEVEL_WARN))
assert.True(logger.shouldLog(LEVEL_ERROR))
assert.False(logger.shouldLog(LEVEL_INFO))
assert.False(logger.shouldLog(LEVEL_DEBUG))
}
-120
View File
@@ -1,120 +0,0 @@
package libpack_logging
import (
"io"
"os"
"sync"
"time"
"github.com/gookit/goutil/envutil"
"github.com/rs/zerolog"
)
type LogConfig struct {
logger zerolog.Logger
}
var (
baseLogger zerolog.Logger
eventPool = sync.Pool{
New: func() interface{} {
return new(zerolog.Event)
},
}
fieldMapPool = sync.Pool{
New: func() interface{} {
return make(map[string]interface{})
},
}
)
func init() {
zerolog.TimeFieldFormat = time.RFC3339
zerolog.MessageFieldName = "short_message"
zerolog.TimestampFieldName = "timestamp"
zerolog.LevelFieldName = "level"
zerolog.LevelFatalValue = "critical"
baseLogger = zerolog.New(os.Stdout).With().Timestamp().Logger()
switch logLevel := envutil.Getenv("LOG_LEVEL", "info"); logLevel {
case "debug":
baseLogger = baseLogger.Level(zerolog.DebugLevel)
case "warn":
baseLogger = baseLogger.Level(zerolog.WarnLevel)
case "error":
baseLogger = baseLogger.Level(zerolog.ErrorLevel)
default:
baseLogger = baseLogger.Level(zerolog.InfoLevel)
}
}
func NewLogger() *LogConfig {
return &LogConfig{logger: baseLogger}
}
func (lw *LogConfig) log(w io.Writer, level zerolog.Level, message string, fields map[string]interface{}) {
logger := lw.logger.Output(w)
event := logger.WithLevel(level).CallerSkipFrame(3)
for k, val := range fields {
switch v := val.(type) {
case string:
event = event.Str(k, v)
case int:
event = event.Int(k, v)
case float64:
event = event.Float64(k, v)
default:
event = event.Interface(k, val)
}
}
event.Msg(message)
}
func (lw *LogConfig) logWithLevel(level zerolog.Level, message string, fields map[string]interface{}) {
if lw.logger.GetLevel() <= level {
w := os.Stdout
if level >= zerolog.ErrorLevel {
w = os.Stderr
}
lw.log(w, level, message, fields)
}
}
func (lw *LogConfig) Debug(message string, fields map[string]interface{}) {
lw.logWithLevel(zerolog.DebugLevel, message, fields)
}
func (lw *LogConfig) Info(message string, fields map[string]interface{}) {
lw.logWithLevel(zerolog.InfoLevel, message, fields)
}
func (lw *LogConfig) Warning(message string, fields map[string]interface{}) {
lw.logWithLevel(zerolog.WarnLevel, message, fields)
}
func (lw *LogConfig) Error(message string, fields map[string]interface{}) {
lw.logWithLevel(zerolog.ErrorLevel, message, fields)
}
func (lw *LogConfig) Critical(message string, fields map[string]interface{}) {
lw.logWithLevel(zerolog.FatalLevel, message, fields)
os.Exit(1)
}
// Helper function to get a new fields map from the pool
func getFieldsMap() map[string]interface{} {
return fieldMapPool.Get().(map[string]interface{})
}
// Helper function to put a used fields map back into the pool
func putFieldsMap(fields map[string]interface{}) {
for k := range fields {
delete(fields, k)
}
fieldMapPool.Put(fields)
}
-32
View File
@@ -1,32 +0,0 @@
package libpack_logging
import (
"os"
"testing"
)
func BenchmarkNewLogger(b *testing.B) {
for i := 0; i < b.N; i++ {
NewLogger()
}
}
func BenchmarkInfoLog(b *testing.B) {
oldEnv := os.Getenv("LOG_LEVEL")
os.Setenv("LOG_LEVEL", "info")
oldStdout := os.Stdout
oldStderr := os.Stderr
os.Stdout, _ = os.Open(os.DevNull)
os.Stderr, _ = os.Open(os.DevNull)
defer func() {
os.Stdout = oldStdout
os.Stderr = oldStderr
os.Setenv("LOG_LEVEL", oldEnv)
}()
testsLogger := NewLogger()
b.ResetTimer()
for i := 0; i < b.N; i++ {
testsLogger.Info("test", map[string]interface{}{"test": "test"})
}
}
+11 -2
View File
@@ -1,6 +1,7 @@
package gql
import (
"net/http"
"time"
"github.com/gookit/goutil/envutil"
@@ -12,7 +13,7 @@ func NewConnection() (b *BaseClient) {
b = &BaseClient{
endpoint: envutil.Getenv("GRAPHQL_ENDPOINT", "https://api.github.com/graphql"),
responseType: envutil.Getenv("GRAPHQL_OUTPUT", "string"),
Logger: logging.NewLogger(),
Logger: logging.New(),
cache: cache.New(time.Duration(envutil.GetInt("GRAPHQL_CACHE_TTL", 5)) * time.Second),
cache_global: envutil.GetBool("GRAPHQL_CACHE_ENABLED", false),
retries_enable: envutil.GetBool("GRAPHQL_RETRIES_ENABLE", false),
@@ -20,7 +21,11 @@ func NewConnection() (b *BaseClient) {
retries_number: envutil.GetInt("GRAPHQL_RETRIES_NUMBER", 3),
}
b.client = b.createHttpClient()
b.Logger.Debug("Created new GraphQL client connection", map[string]interface{}{"values": b})
b.Logger.Debug(&logging.LogMessage{
Message: "Created new GraphQL client connection",
Pairs: map[string]interface{}{
"values": b,
}})
return b
}
@@ -34,3 +39,7 @@ func (b *BaseClient) SetOutput(responseType string) {
// TODO: implement
b.responseType = responseType
}
func (b *BaseClient) SetHTTPClient(client *http.Client) {
b.client = client
}
+67
View File
@@ -0,0 +1,67 @@
// mock_server.go
package gql
import (
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"strings"
"golang.org/x/net/http2"
)
func StartMockServer() *httptest.Server {
// Create your handler
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Your existing handler code
bodyBytes, err := io.ReadAll(r.Body)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
var req struct {
Variables map[string]interface{} `json:"variables"`
Query string `json:"query"`
}
err = json.Unmarshal(bodyBytes, &req)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
// Simple validation to check for unbalanced braces as a syntax error
if !strings.HasPrefix(strings.TrimSpace(req.Query), "query") || !strings.HasSuffix(strings.TrimSpace(req.Query), "}") {
resp := []byte(`{"errors":[{"message":"Syntax Error: Invalid query"}]}`)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusBadRequest)
w.Write(resp)
return
}
var resp []byte
if strings.Contains(req.Query, "viewer") {
resp = []byte(`{"data":{"viewer":{"login":"mockuser"}}}`)
} else if strings.Contains(req.Query, "dragons") {
resp = []byte(`{"data":{"dragons":[{"name":"Mock Dragon 1"},{"name":"Mock Dragon 2"}]}}`)
} else {
resp = []byte(`{"errors":[{"message":"Unknown query"}]}`)
w.WriteHeader(http.StatusBadRequest)
}
w.Header().Set("Content-Type", "application/json")
w.Write(resp)
})
// Create an unstarted server
server := httptest.NewUnstartedServer(handler)
// Configure the server to support HTTP/2
http2.ConfigureServer(server.Config, &http2.Server{})
server.TLS = server.Config.TLSConfig
// Start the server with TLS
server.StartTLS()
return server
}
+24
View File
@@ -0,0 +1,24 @@
package gql
import (
"bytes"
"sync"
)
var (
// Pre-sized buffer pool for better performance
bufferPool = sync.Pool{
New: func() interface{} {
// Pre-allocate buffer with 4KB capacity
b := bytes.NewBuffer(make([]byte, 0, 4096))
return b
},
}
// Pre-allocate error maps to reduce allocations
errPairsPool = sync.Pool{
New: func() interface{} {
return make(map[string]interface{}, 1)
},
}
)
+91 -32
View File
@@ -1,36 +1,81 @@
package gql
import (
"bytes"
"fmt"
"github.com/goccy/go-json"
"github.com/gookit/goutil"
"github.com/gookit/goutil/strutil"
libpack_logger "github.com/lukaszraczylo/go-simple-graphql/logging"
)
func (b *BaseClient) convertToJSON(v any) []byte {
jsonData, err := json.Marshal(v)
if err != nil {
b.Logger.Error("Can't convert to JSON", map[string]interface{}{"error": err.Error()})
buf := bufferPool.Get().(*bytes.Buffer)
defer bufferPool.Put(buf)
buf.Reset()
// Use json.NewEncoder for better performance with buffers
enc := json.NewEncoder(buf)
enc.SetEscapeHTML(false) // Reduce unnecessary escaping
if err := enc.Encode(v); err != nil {
errPairs := errPairsPool.Get().(map[string]interface{})
errPairs["error"] = err.Error()
b.Logger.Error(&libpack_logger.LogMessage{
Message: "Can't convert to JSON",
Pairs: errPairs,
})
errPairsPool.Put(errPairs)
return nil
}
return jsonData
// Get the buffer bytes directly, trimming the trailing newline
bytes := buf.Bytes()
if len(bytes) > 0 && bytes[len(bytes)-1] == '\n' {
bytes = bytes[:len(bytes)-1]
}
// Make a copy of the bytes since the buffer will be reused
result := make([]byte, len(bytes))
copy(result, bytes)
return result
}
func (b *BaseClient) compileQuery(queryPartials ...any) *Query {
q := &Query{}
for _, partial := range queryPartials {
switch val := partial.(type) {
case string:
q.Query = val
case map[string]interface{}:
q.Variables = val
var query string
var variables map[string]interface{}
// Pre-allocate the query with an estimated size
if len(queryPartials) > 0 {
if str, ok := queryPartials[0].(string); ok {
query = str
}
}
if q.Query == "" {
b.Logger.Error("Can't compile query", map[string]interface{}{"error": "query is empty"})
// Only allocate variables map if we have more than one partial
if len(queryPartials) > 1 {
if vars, ok := queryPartials[1].(map[string]interface{}); ok {
variables = vars
}
}
if query == "" {
errPairs := errPairsPool.Get().(map[string]interface{})
errPairs["error"] = "query is empty"
b.Logger.Error(&libpack_logger.LogMessage{
Message: "Can't compile query",
Pairs: errPairs,
})
errPairsPool.Put(errPairs)
return nil
}
// Construct query object once
q := &Query{
Query: query,
Variables: variables,
}
q.JsonQuery = b.convertToJSON(q)
return q
}
@@ -38,10 +83,16 @@ func (b *BaseClient) compileQuery(queryPartials ...any) *Query {
func (b *BaseClient) Query(query string, variables map[string]interface{}, headers map[string]interface{}) (any, error) {
compiledQuery := b.compileQuery(query, variables)
if compiledQuery.JsonQuery == nil {
b.Logger.Error("Can't compile query", map[string]interface{}{"error": "query is empty"})
b.Logger.Error(&libpack_logger.LogMessage{
Message: "Can't compile query",
Pairs: map[string]interface{}{"error": "query is empty"},
})
return nil, fmt.Errorf("can't compile query")
}
b.Logger.Debug("Compiled query", map[string]interface{}{"query": compiledQuery})
b.Logger.Debug(&libpack_logger.LogMessage{
Message: "Compiled query",
Pairs: map[string]interface{}{"query": compiledQuery},
})
enableCache, enableRetries, recompileRequired := compiledQuery.parseHeadersAndVariables(headers)
if recompileRequired {
@@ -50,18 +101,22 @@ func (b *BaseClient) Query(query string, variables map[string]interface{}, heade
var queryHash string
if (enableCache || b.cache_global) && strutil.HasPrefix(compiledQuery.Query, "query") {
b.Logger.Debug("Cache enabled", nil)
b.Logger.Debug(&libpack_logger.LogMessage{
Message: "Cache enabled",
Pairs: nil,
})
queryHash = calculateHash(compiledQuery)
cachedValue := b.cacheLookup(queryHash)
if cachedValue != nil {
b.Logger.Debug("Cache hit", map[string]interface{}{"query": compiledQuery})
return cachedValue, nil
if cachedValue := b.cacheLookup(queryHash); cachedValue != nil {
b.Logger.Debug(&libpack_logger.LogMessage{
Message: "Cache hit",
Pairs: map[string]interface{}{"query": compiledQuery},
})
return b.decodeResponse(cachedValue)
}
b.Logger.Debug("Cache miss", map[string]interface{}{"query": compiledQuery})
}
if enableRetries || b.retries_enable {
b.Logger.Debug("Retries enabled", nil)
b.Logger.Debug(&libpack_logger.LogMessage{
Message: "Cache miss",
Pairs: map[string]interface{}{"query": compiledQuery},
})
}
q := &QueryExecutor{
@@ -76,16 +131,17 @@ func (b *BaseClient) Query(query string, variables map[string]interface{}, heade
}(),
Retries: enableRetries || b.retries_enable,
}
defer func() { q = nil }()
rv, err := q.executeQuery()
if err != nil {
b.Logger.Error("Error executing query", map[string]interface{}{"error": err.Error()})
b.Logger.Error(&libpack_logger.LogMessage{
Message: "Error executing query",
Pairs: map[string]interface{}{"error": err.Error()},
})
return nil, err
}
returnedValue, err := q.decodeResponse(rv)
return returnedValue, err
return b.decodeResponse(rv)
}
func (q *Query) parseHeadersAndVariables(headers map[string]interface{}) (enableCache, enableRetries, recompileRequired bool) {
@@ -97,9 +153,12 @@ func (q *Query) parseHeadersAndVariables(headers map[string]interface{}) (enable
varEnableRetries, _ := goutil.ToBool(searchForKeysInMapStringInterface(q.Variables, "gqlretries"))
enableCache = enableCache || varEnableCache
enableRetries = enableRetries || varEnableRetries
delete(q.Variables, "gqlcache")
delete(q.Variables, "gqlretries")
recompileRequired = true
if varEnableCache || varEnableRetries {
delete(q.Variables, "gqlcache")
delete(q.Variables, "gqlretries")
recompileRequired = true
}
}
return enableCache, enableRetries, recompileRequired
+79 -3
View File
@@ -1,6 +1,8 @@
package gql
import "testing"
import (
"testing"
)
func Benchmark_compileQuery(bn *testing.B) {
b := NewConnection()
@@ -12,12 +14,86 @@ func Benchmark_compileQuery(bn *testing.B) {
}
}
func Benchmark_convertToJson(bn *testing.B) {
func Benchmark_compileQueryWithVariables(bn *testing.B) {
b := NewConnection()
variables := map[string]interface{}{
"var1": "value1",
}
bn.ResetTimer()
for i := 0; i < bn.N; i++ {
b.convertToJSON(
b.compileQuery(
`query { viewer { login } }`,
variables,
)
}
}
func Benchmark_convertToJson(bn *testing.B) {
b := NewConnection()
query := `query { viewer { login } }`
bn.ResetTimer()
for i := 0; i < bn.N; i++ {
b.convertToJSON(query)
}
}
func Benchmark_Query(bn *testing.B) {
mockServer := StartMockServer()
bn.Cleanup(func() {
mockServer.Close()
})
b := NewConnection()
b.SetEndpoint(mockServer.URL)
query := "query { viewer { login } }"
variables := map[string]interface{}{
"var1": "value1",
}
headers := map[string]interface{}{
"Authorization": "Bearer token",
"gqlcache": "true",
}
bn.ResetTimer()
for i := 0; i < bn.N; i++ {
_, _ = b.Query(query, variables, headers)
}
}
func Benchmark_QueryNoCacheNoRetry(bn *testing.B) {
mockServer := StartMockServer()
bn.Cleanup(func() {
mockServer.Close()
})
b := NewConnection()
b.SetEndpoint(mockServer.URL)
query := `query { viewer { login } }`
variables := map[string]interface{}{
"var1": "value1",
}
headers := map[string]interface{}{
"Authorization": "Bearer token",
}
bn.ResetTimer()
for i := 0; i < bn.N; i++ {
_, _ = b.Query(query, variables, headers)
}
}
func Benchmark_QueryWithEmptyVariables(bn *testing.B) {
mockServer := StartMockServer()
bn.Cleanup(func() {
mockServer.Close()
})
b := NewConnection()
b.SetEndpoint(mockServer.URL)
query := `query { viewer { login } }`
headers := map[string]interface{}{
"Authorization": "Bearer token",
"gqlcache": "true",
}
bn.ResetTimer()
for i := 0; i < bn.N; i++ {
_, _ = b.Query(query, nil, headers)
}
}
+22 -156
View File
@@ -1,8 +1,9 @@
package gql
import (
"reflect"
"testing"
"github.com/goccy/go-reflect"
)
func (suite *Tests) TestBaseClient_convertToJSON() {
@@ -115,182 +116,48 @@ func (suite *Tests) TestBaseClient_Query() {
args args
wantReturned_value any
name string
graphQLServer string
wantType string
wantErr bool
}{
{
name: "TestBaseClient_Query_spacex_working",
graphQLServer: "https://spacex-production.up.railway.app/",
name: "TestBaseClient_Query_viewer",
args: args{
query: `query Dragons {
dragons {
name
}
}`,
query: "query { viewer { login } }",
variables: nil,
headers: map[string]interface{}{
"x-apollo-operation-name": "Dragons/github.com/lukaszraczylo/go-simple-graphql",
"x-apollo-operation-name": "ViewerQuery",
"content-type": "application/json",
},
},
wantReturned_value: string(`{"dragons":[{"name":"Dragon 1"},{"name":"Dragon 2"}]}`),
wantReturned_value: `{"viewer":{"login":"mockuser"}}`, // Adjusted expected value
wantErr: false,
},
{
name: "TestBaseClient_Query_spacex_invalid_query",
graphQLServer: "https://spacex-production.up.railway.app/",
name: "TestBaseClient_Query_dragons",
args: args{
query: `query Dragons {
dragons {
name
}
`,
dragons {
name
}
}`,
variables: nil,
headers: map[string]interface{}{
"x-apollo-operation-name": "Dragons/github.com/lukaszraczylo/go-simple-graphql",
"x-apollo-operation-name": "DragonsQuery",
"content-type": "application/json",
},
},
wantReturned_value: nil,
wantErr: true,
},
{
name: "TestBaseClient_Query_tgbotapp_working",
graphQLServer: "https://telegram-bot.app/v1/graphql",
args: args{
query: `query {
__type(name: "Query") {
name
}
}`,
},
wantReturned_value: string(`{"__type":null}`),
wantReturned_value: `{"dragons":[{"name":"Mock Dragon 1"},{"name":"Mock Dragon 2"}]}`, // Adjusted expected value
wantErr: false,
},
{
name: "TestBaseClient_Query_tgbotapp_invalid_query",
graphQLServer: "https://telegram-bot.app/v1/graphql",
name: "TestBaseClient_Query_invalid_query",
args: args{
query: `query {
__type(name: "Query") {
name
}
`,
},
wantReturned_value: nil,
wantErr: true,
},
{
name: "TestBaseClient_Query_tgbotapp_invalid_wrong_field",
graphQLServer: "https://telegram-bot.app/v1/graphql",
args: args{
query: `query {
__type(name: "Query") {
name2
}
}`,
},
wantReturned_value: nil,
wantErr: true,
},
{
name: "TestBaseClient_Query_tgbotapp_wrong_url",
graphQLServer: "https://telegram-bot.app/v0/graphql",
args: args{
query: `query {
__type(name: "Query") {
name
}
}`,
},
wantReturned_value: nil,
wantErr: true,
},
{
name: "TestBaseClient_Query_tgbotapp_valid_query_mapstring",
graphQLServer: "https://telegram-bot.app/v1/graphql",
wantType: "mapstring",
args: args{
query: `query {
__type(name: "Query") {
name
}
}`,
},
wantReturned_value: map[string]interface{}{"__type": nil},
wantErr: false,
},
{
name: "TestBaseClient_Query_tgbotapp_valid_query_byte",
graphQLServer: "https://telegram-bot.app/v1/graphql",
wantType: "byte",
args: args{
query: `query {
__type(name: "Query") {
name
}
}`,
},
wantReturned_value: []byte(`{"__type":null}`),
wantErr: false,
},
{
name: "TestBaseClient_Query_tgbotapp_valid_query_string",
graphQLServer: "https://telegram-bot.app/v1/graphql",
wantType: "string",
args: args{
query: `query {
__type(name: "Query") {
name
}
}`,
},
wantReturned_value: string(`{"__type":null}`),
wantErr: false,
},
{
name: "TestBaseClient_Query_tgbotapp_valid_query_invalid_type",
graphQLServer: "https://telegram-bot.app/v1/graphql",
wantType: "potato",
args: args{
query: `query {
__type(name: "Query") {
name
}
}`,
},
wantReturned_value: nil,
wantErr: true,
},
{
name: "TestBaseClient_Query_tgbotapp_valid_query_cache",
graphQLServer: "https://telegram-bot.app/v1/graphql",
args: args{
query: `query {
__type(name: "Query") {
name
}
}`,
variables: map[string]interface{}{
"gqlcache": true,
},
},
wantReturned_value: string(`{"__type":null}`),
wantErr: false,
},
{
name: "TestBaseClient_Query_tgbotapp_valid_query_with_retry",
graphQLServer: "https://telegram-bot.app/v0/graphql",
wantType: "byte",
args: args{
query: `query {
__type(name: "Query") {
name
}
}`,
variables: map[string]interface{}{
"gqlretries": true,
query: "query { potato { login } ",
variables: nil,
headers: map[string]interface{}{
"x-apollo-operation-name": "InvalidQuery",
"content-type": "application/json",
},
},
wantReturned_value: nil,
@@ -300,9 +167,8 @@ func (suite *Tests) TestBaseClient_Query() {
for _, tt := range tests {
suite.T().Run(tt.name, func(t *testing.T) {
b := NewConnection()
if tt.graphQLServer != "" {
b.SetEndpoint(tt.graphQLServer)
}
b.SetEndpoint(mockServer.URL)
b.SetHTTPClient(mockServer.Client())
if tt.wantType != "" {
b.SetOutput(tt.wantType)
}
+1 -1
View File
@@ -10,7 +10,7 @@ import (
type BaseClient struct {
cache *cache.Cache
Logger *logging.LogConfig
Logger *logging.Logger
client *http.Client
endpoint string
responseType string
+15 -1
View File
@@ -1,6 +1,7 @@
package gql
import (
"net/http/httptest"
"testing"
assertions "github.com/stretchr/testify/assert"
@@ -12,9 +13,22 @@ type Tests struct {
}
var (
assert *assertions.Assertions
assert *assertions.Assertions
mockServer *httptest.Server
)
func (suite *Tests) SetupSuite() {
// Start mock GraphQL server
mockServer = StartMockServer()
}
func (suite *Tests) TearDownSuite() {
// Close the mock server
if mockServer != nil {
mockServer.Close()
}
}
func (suite *Tests) SetupTest() {
assert = assertions.New(suite.T())
}