mirror of
https://github.com/lukaszraczylo/go-simple-graphql.git
synced 2026-10-12 00:45:31 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
25252ac30f | ||
|
|
1c56b9fbb4 | ||
|
|
5030fec4ff | ||
|
|
3d89a77565 | ||
|
|
4a4b24fa45 | ||
|
|
d2453fe2f5 | ||
|
|
28eec46f4c | ||
|
|
63e449ef77 | ||
|
|
50cfc5f98d | ||
|
|
4a575ac9c8 | ||
|
|
f54cedaeb3 | ||
|
|
1080083384 | ||
|
|
941aadb869 | ||
|
|
8174ae6f9c | ||
|
|
992a29da85 | ||
|
|
ecf2c06401 | ||
|
|
fb0785229c | ||
|
|
8ac446db41 | ||
|
|
586af64d70 | ||
|
|
50c1033ad1 | ||
|
|
7a791965ca | ||
|
|
05b057c67c | ||
|
|
9c729d814a | ||
|
|
9d5e2122b8 | ||
|
|
a19f1d257a | ||
|
|
563c952c78 | ||
|
|
2f259a4b3f | ||
|
|
957857537a | ||
|
|
4ea4bbb6cc | ||
|
|
36ef16ad3d | ||
|
|
42170f9b8e | ||
|
|
4f438b7eac | ||
|
|
569867d04b | ||
|
|
9a58df7a54 | ||
|
|
4e60a90ce4 | ||
|
|
2f4c8cc5d8 | ||
|
|
154233df14
|
||
|
|
29afbd08fd
|
||
|
|
a107ee953b
|
||
|
|
58094f85c7
|
||
|
|
ac957ac95b
|
||
|
|
ef4ab45424
|
||
|
|
4fc826c1f6
|
||
|
|
3217edf37f
|
||
|
|
ae96059f61
|
||
|
|
2ce7016d7e
|
||
|
|
9da7c9bec9
|
||
|
|
ca13be5ef6
|
||
|
|
1df2ae5d16
|
||
|
|
39f489210b
|
||
|
|
21c9119bcb
|
||
|
|
a7b385f0b7
|
||
|
|
7d3abf5464
|
||
|
|
7af4e1f96a
|
||
|
|
7623410bfe
|
||
|
|
8e26d79df7
|
||
|
|
aa25c43795
|
||
|
|
dfb082ad51
|
||
|
|
ce736958c6
|
||
|
|
4472041b21
|
||
|
|
b81e612f51
|
||
|
|
3c508eaf15
|
||
|
|
4d0c04cb26
|
||
|
|
55182f2f3d
|
||
|
|
841c136e71
|
||
|
|
833517f35c
|
@@ -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"
|
||||
@@ -12,6 +12,6 @@ jobs:
|
||||
shared:
|
||||
uses: telegram-bot-app/ci-scripts/.github/workflows/library-test-publish.yaml@main
|
||||
with:
|
||||
enable-code-scans: true
|
||||
enable-code-scans: false
|
||||
secrets:
|
||||
ghcr-token: ${{ secrets.GHCR_TOKEN }}
|
||||
@@ -1,104 +0,0 @@
|
||||
package gql
|
||||
|
||||
import (
|
||||
"crypto/tls"
|
||||
"time"
|
||||
|
||||
"github.com/lukaszraczylo/go-simple-graphql/utils/concurrency"
|
||||
"github.com/lukaszraczylo/go-simple-graphql/utils/logger"
|
||||
|
||||
"golang.org/x/net/http2"
|
||||
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"github.com/allegro/bigcache"
|
||||
"github.com/gookit/goutil/envutil"
|
||||
)
|
||||
|
||||
func NewConnection() *BaseClient {
|
||||
|
||||
b := &BaseClient{
|
||||
client: &http.Client{},
|
||||
concurrencyManager: concurrency.NewPool(-1),
|
||||
MaxGoRoutines: -1,
|
||||
LoggingLevel: logger.Warn,
|
||||
LoggerColorful: true,
|
||||
}
|
||||
|
||||
if b.LoggerWriter == nil {
|
||||
b.LoggerWriter = log.New(os.Stdout, "", log.LstdFlags)
|
||||
}
|
||||
|
||||
b.endpoint = envutil.Getenv("GRAPHQL_ENDPOINT", "https://api.github.com/graphql")
|
||||
b.responseType = envutil.Getenv("GRAPHQL_OUTPUT", "string")
|
||||
b.validate = envutil.GetBool("GRAPHQL_VALIDATE", false)
|
||||
b.cache.enabled = envutil.GetBool("GRAPHQL_CACHE_ENABLED", true)
|
||||
b.cache.ttl = envutil.GetInt("GRAPHQL_CACHE_TTL", 60)
|
||||
|
||||
b.retries.enabled = envutil.GetBool("GRAPHQL_RETRIES_ENABLED", true)
|
||||
b.retries.max = envutil.GetInt("GRAPHQL_RETRIES_MAX", 1)
|
||||
b.retries.delay = envutil.GetInt("GRAPHQL_RETRIES_DELAY", 300)
|
||||
|
||||
if b.cache.enabled {
|
||||
var err error
|
||||
b.cache.client, err = bigcache.NewBigCache(bigcache.DefaultConfig(time.Duration(b.cache.ttl) * time.Second))
|
||||
if err != nil {
|
||||
b.Logger.Error(b, "Error while creating cache client;", "error", err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
b_tmp_log_level := envutil.Getenv("LOG_LEVEL", "info")
|
||||
|
||||
switch b_tmp_log_level {
|
||||
case "silent":
|
||||
b.LoggingLevel = logger.Silent
|
||||
case "error":
|
||||
b.LoggingLevel = logger.Error
|
||||
case "warn":
|
||||
b.LoggingLevel = logger.Warn
|
||||
case "info":
|
||||
b.LoggingLevel = logger.Info
|
||||
case "debug":
|
||||
b.LoggingLevel = logger.Debug
|
||||
}
|
||||
|
||||
b.Logger = NewLogger(b.LoggerWriter, logger.Config{
|
||||
Colorful: b.LoggerColorful,
|
||||
LogLevel: b.LoggingLevel,
|
||||
})
|
||||
|
||||
var httpClient *http.Client
|
||||
if strings.HasPrefix(b.endpoint, "http://") {
|
||||
httpClient = &http.Client{
|
||||
Transport: http.DefaultTransport,
|
||||
}
|
||||
} else {
|
||||
tlsClientConfig := &tls.Config{}
|
||||
if strings.HasPrefix(b.endpoint, "https://") {
|
||||
tlsClientConfig.InsecureSkipVerify = true
|
||||
}
|
||||
http2Transport := &http2.Transport{
|
||||
AllowHTTP: true,
|
||||
TLSClientConfig: tlsClientConfig,
|
||||
}
|
||||
httpClient = &http.Client{
|
||||
Transport: http2Transport,
|
||||
}
|
||||
}
|
||||
b.client = httpClient
|
||||
|
||||
b.Logger.Debug(b, "graphQL client initialized;", "endpoint", b.endpoint, "responseType", b.responseType, "validate", b.validate, "cache", b.cache.enabled, "cacheTTL", b.cache.ttl, "maxGoRoutines", b.MaxGoRoutines, "loggingLevel", b_tmp_log_level, "loggerColorful", b.LoggerColorful)
|
||||
b.Logger.Info(b, "graphQL client initialized;")
|
||||
return b
|
||||
}
|
||||
|
||||
func (b *BaseClient) SetEndpoint(endpoint string) {
|
||||
b.endpoint = endpoint
|
||||
}
|
||||
|
||||
func (b *BaseClient) SetOutput(output string) {
|
||||
b.responseType = output
|
||||
}
|
||||
-131
@@ -1,131 +0,0 @@
|
||||
package gql
|
||||
|
||||
import (
|
||||
"os"
|
||||
"testing"
|
||||
|
||||
"github.com/lukaszraczylo/go-simple-graphql/utils/logger"
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestNewConnection(t *testing.T) {
|
||||
tests := []struct {
|
||||
want *BaseClient
|
||||
name string
|
||||
}{
|
||||
{
|
||||
name: "Test NewConnection",
|
||||
want: &BaseClient{
|
||||
endpoint: "https://api.github.com/graphql",
|
||||
responseType: "string",
|
||||
},
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
// temporarily set GRAPHQL_ENDPOINT env variable to https://api.github.com/graphql
|
||||
// and GRAPHQL_OUTPUT to string
|
||||
current := os.Getenv("GRAPHQL_ENDPOINT")
|
||||
defer os.Setenv("GRAPHQL_ENDPOINT", current)
|
||||
os.Setenv("GRAPHQL_ENDPOINT", "https://api.github.com/graphql")
|
||||
|
||||
got := NewConnection()
|
||||
assert.Equal(t, tt.want.endpoint, got.endpoint)
|
||||
assert.Equal(t, tt.want.responseType, got.responseType)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewConnectionLogLevels(t *testing.T) {
|
||||
tests := []struct {
|
||||
want *BaseClient
|
||||
name string
|
||||
env string
|
||||
}{
|
||||
{
|
||||
name: "Test NewConnection with log level set to debug",
|
||||
env: "debug",
|
||||
want: &BaseClient{
|
||||
endpoint: "https://api.github.com/graphql",
|
||||
responseType: "string",
|
||||
LoggingLevel: logger.Debug,
|
||||
},
|
||||
},
|
||||
|
||||
{
|
||||
name: "Test NewConnection with log level set to info",
|
||||
env: "info",
|
||||
want: &BaseClient{
|
||||
endpoint: "https://api.github.com/graphql",
|
||||
responseType: "string",
|
||||
LoggingLevel: logger.Info,
|
||||
},
|
||||
},
|
||||
|
||||
{
|
||||
name: "Test NewConnection with log level set to warn",
|
||||
env: "warn",
|
||||
want: &BaseClient{
|
||||
endpoint: "https://api.github.com/graphql",
|
||||
responseType: "string",
|
||||
LoggingLevel: logger.Warn,
|
||||
},
|
||||
},
|
||||
|
||||
{
|
||||
name: "Test NewConnection with log level set to error",
|
||||
env: "error",
|
||||
want: &BaseClient{
|
||||
endpoint: "https://api.github.com/graphql",
|
||||
responseType: "string",
|
||||
LoggingLevel: logger.Error,
|
||||
},
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
// temporarily set GRAPHQL_ENDPOINT env variable to https://api.github.com/graphql
|
||||
// and GRAPHQL_OUTPUT to string
|
||||
current := os.Getenv("GRAPHQL_ENDPOINT")
|
||||
defer os.Setenv("GRAPHQL_ENDPOINT", current)
|
||||
os.Setenv("GRAPHQL_ENDPOINT", "https://api.github.com/graphql")
|
||||
current_log_level := os.Getenv("LOG_LEVEL")
|
||||
defer os.Setenv("LOG_LEVEL", current_log_level)
|
||||
os.Setenv("LOG_LEVEL", tt.env)
|
||||
|
||||
got := NewConnection()
|
||||
assert.Equal(t, tt.want.endpoint, got.endpoint)
|
||||
assert.Equal(t, tt.want.responseType, got.responseType)
|
||||
assert.Equal(t, tt.want.LoggingLevel, got.LoggingLevel)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestBaseClient_SetEndpoint(t *testing.T) {
|
||||
type fields struct {
|
||||
}
|
||||
type args struct {
|
||||
endpoint string
|
||||
}
|
||||
tests := []struct {
|
||||
name string
|
||||
fields fields
|
||||
args args
|
||||
want string
|
||||
}{
|
||||
{
|
||||
name: "Test SetEndpoint",
|
||||
args: args{
|
||||
endpoint: "https://potato/graphql",
|
||||
},
|
||||
want: "https://potato/graphql",
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
b := NewConnection()
|
||||
b.SetEndpoint(tt.args.endpoint)
|
||||
assert.Equal(t, tt.want, b.endpoint)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
package gql
|
||||
|
||||
func (c *BaseClient) cacheLookup(hash string) []byte {
|
||||
if c.cache.client != nil {
|
||||
g, err := c.cache.client.Get(hash)
|
||||
if err == nil {
|
||||
c.Logger.Debug(c, "Cache hit;", "hash", hash)
|
||||
return g
|
||||
}
|
||||
// if error is not nil it means that hash is not present in cache
|
||||
c.Logger.Debug(c, "Cache miss;", "hash", hash)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
Vendored
+180
@@ -0,0 +1,180 @@
|
||||
package libpack_cache
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"compress/gzip"
|
||||
"hash/fnv"
|
||||
"io"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
type CacheEntry struct {
|
||||
ExpiresAt time.Time
|
||||
Value []byte
|
||||
}
|
||||
|
||||
const shardCount = 256 // Must be power of 2
|
||||
|
||||
type shard struct {
|
||||
entries map[string]CacheEntry
|
||||
sync.RWMutex
|
||||
}
|
||||
|
||||
type Cache struct {
|
||||
compressPool sync.Pool
|
||||
decompressPool sync.Pool
|
||||
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 {
|
||||
cache := &Cache{
|
||||
globalTTL: globalTTL,
|
||||
compressPool: sync.Pool{
|
||||
New: func() interface{} {
|
||||
w := gzip.NewWriter(nil)
|
||||
return w
|
||||
},
|
||||
},
|
||||
decompressPool: sync.Pool{
|
||||
New: func() interface{} {
|
||||
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
|
||||
}
|
||||
|
||||
func (c *Cache) cleanupRoutine(globalTTL time.Duration) {
|
||||
ticker := time.NewTicker(globalTTL / 2)
|
||||
defer ticker.Stop()
|
||||
|
||||
for range ticker.C {
|
||||
c.CleanExpiredEntries()
|
||||
}
|
||||
}
|
||||
func (c *Cache) Set(key string, value []byte, ttl time.Duration) {
|
||||
shard := c.getShard(key)
|
||||
shard.Lock()
|
||||
defer shard.Unlock()
|
||||
|
||||
compressedValue, err := c.compress(value)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
shard.entries[key] = CacheEntry{
|
||||
Value: compressedValue,
|
||||
ExpiresAt: time.Now().Add(ttl),
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Cache) Get(key string) ([]byte, bool) {
|
||||
shard := c.getShard(key)
|
||||
shard.RLock()
|
||||
entry, ok := shard.entries[key]
|
||||
if !ok {
|
||||
shard.RUnlock()
|
||||
return nil, false
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
return value, true
|
||||
}
|
||||
|
||||
func (c *Cache) Delete(key string) {
|
||||
shard := c.getShard(key)
|
||||
shard.Lock()
|
||||
delete(shard.entries, key)
|
||||
shard.Unlock()
|
||||
}
|
||||
|
||||
func (c *Cache) CleanExpiredEntries() {
|
||||
now := time.Now()
|
||||
for _, shard := range c.shards {
|
||||
shard.Lock()
|
||||
for key, entry := range shard.entries {
|
||||
if entry.ExpiresAt.Before(now) {
|
||||
delete(shard.entries, key)
|
||||
}
|
||||
}
|
||||
shard.Unlock()
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Cache) compress(data []byte) ([]byte, error) {
|
||||
w := c.compressPool.Get().(*gzip.Writer)
|
||||
defer c.compressPool.Put(w)
|
||||
|
||||
var buf bytes.Buffer
|
||||
w.Reset(&buf)
|
||||
if _, err := w.Write(data); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := w.Close(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return buf.Bytes(), nil
|
||||
}
|
||||
|
||||
func (c *Cache) decompress(data []byte) ([]byte, error) {
|
||||
r, ok := c.decompressPool.Get().(*gzip.Reader)
|
||||
if !ok || r == nil {
|
||||
// If r is nil or type assertion fails, create a new gzip.Reader
|
||||
var err error
|
||||
r, err = gzip.NewReader(bytes.NewReader(data))
|
||||
if err != nil {
|
||||
return nil, err // Handle the error if gzip.NewReader fails
|
||||
}
|
||||
} else {
|
||||
// Reset the existing reader with new data
|
||||
if err := r.Reset(bytes.NewReader(data)); err != nil {
|
||||
return nil, err // Handle the error if Reset fails
|
||||
}
|
||||
}
|
||||
defer r.Close()
|
||||
|
||||
// Ensure the reader is returned to the pool
|
||||
defer c.decompressPool.Put(r)
|
||||
|
||||
// Read all the data from the reader
|
||||
decompressedData, err := io.ReadAll(r)
|
||||
if err != nil {
|
||||
return nil, err // Handle the error if reading fails
|
||||
}
|
||||
return decompressedData, nil
|
||||
}
|
||||
Vendored
+46
@@ -0,0 +1,46 @@
|
||||
package libpack_cache
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Assume that New function initializes the cache and it is defined somewhere in the libpack_cache package.
|
||||
|
||||
func BenchmarkCacheSet(b *testing.B) {
|
||||
cache := New(30 * time.Second) // Initializing the cache with a TTL of 30 seconds
|
||||
key := "benchmark-key"
|
||||
value := []byte("benchmark-value")
|
||||
|
||||
b.ResetTimer() // Reset the timer to exclude the setup time from the benchmark
|
||||
|
||||
for i := 0; i < b.N; i++ {
|
||||
cache.Set(key, value, 5*time.Second)
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkCacheGet(b *testing.B) {
|
||||
cache := New(30 * time.Second) // Initializing the cache
|
||||
key := "benchmark-key"
|
||||
value := []byte("benchmark-value")
|
||||
cache.Set(key, value, 5*time.Second) // Pre-set a value to retrieve
|
||||
|
||||
b.ResetTimer() // Start timing
|
||||
|
||||
for i := 0; i < b.N; i++ {
|
||||
_, _ = cache.Get(key)
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkCacheExpire(b *testing.B) {
|
||||
key := "benchmark-expire-key"
|
||||
value := []byte("benchmark-value")
|
||||
ttl := 5 * time.Millisecond // Setting a short TTL for quick expiration
|
||||
|
||||
for i := 0; i < b.N; i++ {
|
||||
cache := New(30 * time.Second)
|
||||
cache.Set(key, value, ttl)
|
||||
time.Sleep(ttl) // Wait for the key to expire
|
||||
_, _ = cache.Get(key)
|
||||
}
|
||||
}
|
||||
Vendored
+112
@@ -0,0 +1,112 @@
|
||||
package libpack_cache
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/suite"
|
||||
)
|
||||
|
||||
type CacheTestSuite struct {
|
||||
suite.Suite
|
||||
}
|
||||
|
||||
func (suite *CacheTestSuite) SetupTest() {
|
||||
}
|
||||
|
||||
func TestCachingTestSuite(t *testing.T) {
|
||||
suite.Run(t, new(CacheTestSuite))
|
||||
}
|
||||
|
||||
func (suite *CacheTestSuite) Test_New() {
|
||||
suite.T().Run("should return a new cache", func(t *testing.T) {
|
||||
cache := New(2 * time.Second)
|
||||
suite.NotNil(cache)
|
||||
})
|
||||
}
|
||||
|
||||
func (suite *CacheTestSuite) Test_CacheUse() {
|
||||
cache := New(30 * time.Second)
|
||||
tests := []struct {
|
||||
name string
|
||||
cache_value string
|
||||
}{
|
||||
{
|
||||
name: "test1",
|
||||
cache_value: "test1-123",
|
||||
},
|
||||
{
|
||||
name: "test2",
|
||||
cache_value: "test2-123",
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
suite.T().Run(tt.name, func(t *testing.T) {
|
||||
cache.Set(tt.name, []byte(tt.name), 5*time.Second)
|
||||
c, ok := cache.Get(tt.name)
|
||||
suite.Equal(true, ok)
|
||||
suite.Equal(tt.name, string(c))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func (suite *CacheTestSuite) Test_CacheDelete() {
|
||||
cache := New(30 * time.Second)
|
||||
tests := []struct {
|
||||
name string
|
||||
cache_value string
|
||||
}{
|
||||
{
|
||||
name: "test1",
|
||||
cache_value: "test1-123",
|
||||
},
|
||||
{
|
||||
name: "test2",
|
||||
cache_value: "test2-123",
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
suite.T().Run(tt.name, func(t *testing.T) {
|
||||
cache.Set(tt.name, []byte(tt.name), 5*time.Second)
|
||||
c, ok := cache.Get(tt.name)
|
||||
suite.Equal(true, ok)
|
||||
suite.Equal(tt.name, string(c))
|
||||
cache.Delete(tt.name)
|
||||
c, ok = cache.Get(tt.name)
|
||||
suite.Equal(false, ok)
|
||||
suite.Equal("", string(c))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func (suite *CacheTestSuite) Test_CacheExpire() {
|
||||
cache := New(30 * time.Second)
|
||||
tests := []struct {
|
||||
name string
|
||||
cache_value string
|
||||
ttl time.Duration
|
||||
}{
|
||||
{
|
||||
name: "test1",
|
||||
cache_value: "test1-123",
|
||||
ttl: 2 * time.Second,
|
||||
},
|
||||
{
|
||||
name: "test2",
|
||||
cache_value: "test2-123",
|
||||
ttl: 5 * time.Second,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
suite.T().Run(tt.name, func(t *testing.T) {
|
||||
cache.Set(tt.name, []byte(tt.name), tt.ttl)
|
||||
c, ok := cache.Get(tt.name)
|
||||
suite.Equal(true, ok)
|
||||
suite.Equal(tt.name, string(c))
|
||||
time.Sleep(tt.ttl)
|
||||
c, ok = cache.Get(tt.name)
|
||||
suite.Equal(false, ok)
|
||||
suite.Equal("", string(c))
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
package gql
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"compress/gzip"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"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) {
|
||||
// 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(&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 {
|
||||
retriesMax = qe.retries_number
|
||||
}
|
||||
|
||||
var queryResult queryResults
|
||||
err = retry.Do(
|
||||
func() error {
|
||||
// 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 {
|
||||
return err
|
||||
}
|
||||
defer func() {
|
||||
io.Copy(io.Discard, httpResponse.Body)
|
||||
httpResponse.Body.Close()
|
||||
}()
|
||||
|
||||
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.Reader
|
||||
encoding := httpResponse.Header.Get("Content-Encoding")
|
||||
if encoding == "gzip" {
|
||||
gzipReader, err := gzip.NewReader(httpResponse.Body)
|
||||
if err != nil {
|
||||
return fmt.Errorf("error creating gzip reader: %w", err)
|
||||
}
|
||||
defer gzipReader.Close()
|
||||
reader = gzipReader
|
||||
} else {
|
||||
reader = httpResponse.Body
|
||||
}
|
||||
|
||||
// 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 {
|
||||
return fmt.Errorf("error reading HTTP response: %w", err)
|
||||
}
|
||||
|
||||
// Unmarshal response directly from buffer
|
||||
err = json.Unmarshal(respBuf.Bytes(), &queryResult)
|
||||
if err != nil {
|
||||
return fmt.Errorf("error unmarshalling HTTP response: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
},
|
||||
retry.OnRetry(func(n uint, err error) {
|
||||
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(&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(&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(&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(&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)
|
||||
}
|
||||
|
||||
if qe.CacheKey != "no-cache" {
|
||||
qe.cache.Set(qe.CacheKey, jsonData, qe.CacheTTL)
|
||||
}
|
||||
|
||||
return jsonData, nil
|
||||
}
|
||||
@@ -1,29 +1,26 @@
|
||||
module github.com/lukaszraczylo/go-simple-graphql
|
||||
|
||||
go 1.20
|
||||
go 1.23.0
|
||||
|
||||
toolchain go1.23.6
|
||||
|
||||
require (
|
||||
github.com/allegro/bigcache v1.2.1
|
||||
github.com/avast/retry-go/v4 v4.3.3
|
||||
github.com/gookit/goutil v0.6.8
|
||||
github.com/json-iterator/go v1.1.12
|
||||
github.com/stretchr/testify v1.8.2
|
||||
golang.org/x/net v0.9.0
|
||||
github.com/avast/retry-go/v4 v4.6.1
|
||||
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.10.0
|
||||
golang.org/x/net v0.36.0
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/davecgh/go-spew v1.1.1 // indirect
|
||||
github.com/gookit/color v1.5.3 // indirect
|
||||
github.com/kr/pretty v0.3.0 // indirect
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
|
||||
github.com/modern-go/reflect2 v1.0.2 // indirect
|
||||
github.com/gookit/color v1.5.4 // indirect
|
||||
github.com/pmezard/go-difflib v1.0.0 // indirect
|
||||
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect
|
||||
golang.org/x/exp v0.0.0-20221126150942-6ab00d035af9 // indirect
|
||||
golang.org/x/sync v0.1.0 // indirect
|
||||
golang.org/x/sys v0.7.0 // indirect
|
||||
golang.org/x/term v0.7.0 // indirect
|
||||
golang.org/x/text v0.9.0 // indirect
|
||||
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 // 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
|
||||
)
|
||||
|
||||
@@ -1,61 +1,34 @@
|
||||
github.com/allegro/bigcache v1.2.1 h1:hg1sY1raCwic3Vnsvje6TT7/pnZba83LeFck5NrFKSc=
|
||||
github.com/allegro/bigcache v1.2.1/go.mod h1:Cb/ax3seSYIx7SuZdm2G2xzfwmv3TPSk2ucNfQESPXM=
|
||||
github.com/avast/retry-go/v4 v4.3.3 h1:G56Bp6mU0b5HE1SkaoVjscZjlQb0oy4mezwY/cGH19w=
|
||||
github.com/avast/retry-go/v4 v4.3.3/go.mod h1:rg6XFaiuFYII0Xu3RDbZQkxCofFwruZKW8oEF1jpWiU=
|
||||
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/avast/retry-go/v4 v4.6.1 h1:VkOLRubHdisGrHnTu89g08aQEWEgRU7LVEop3GbIcMk=
|
||||
github.com/avast/retry-go/v4 v4.6.1/go.mod h1:V6oF8njAwxJ5gRo1Q7Cxab24xs5NCWZBeaHHBklR8mA=
|
||||
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/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
|
||||
github.com/gookit/color v1.5.3 h1:twfIhZs4QLCtimkP7MOxlF3A0U/5cDPseRT9M/+2SCE=
|
||||
github.com/gookit/color v1.5.3/go.mod h1:NUzwzeehUfl7GIb36pqId+UGmRfQcU/WiiyTTeNjHtE=
|
||||
github.com/gookit/goutil v0.6.8 h1:B2XXSCGav5TXWtKRT9i/s/owOLXXB7sY6UsfqeSLroE=
|
||||
github.com/gookit/goutil v0.6.8/go.mod h1:u+Isykc6RQcZ4GQzulsaGm+Famd97U5Tzp3aQyo+jyA=
|
||||
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
|
||||
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
|
||||
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
|
||||
github.com/kr/pretty v0.3.0 h1:WgNl7dwNpEZ6jJ9k1snq4pZsg7DOEN8hP9Xw0Tsjwk0=
|
||||
github.com/kr/pretty v0.3.0/go.mod h1:640gp4NfQd8pI5XOwp5fnNeVWj67G7CFk/SaSQn7NBk=
|
||||
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
|
||||
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
|
||||
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
|
||||
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
|
||||
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
||||
github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
|
||||
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
|
||||
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.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/rogpeppe/go-internal v1.6.1 h1:/FiVV8dS/e+YqF2JvO3yXRFbBLTIuSDkuC7aBOAvL+k=
|
||||
github.com/rogpeppe/go-internal v1.6.1/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
|
||||
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
|
||||
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
|
||||
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
|
||||
github.com/stretchr/testify v1.8.2 h1:+h33VjcLVPDHtOdpUCuF+7gSuG3yGIftsP1YvFihtJ8=
|
||||
github.com/stretchr/testify v1.8.2/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
|
||||
github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA=
|
||||
github.com/stretchr/testify v1.10.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-20221126150942-6ab00d035af9 h1:yZNXmy+j/JpX19vZkVktWqAo7Gny4PBWYYK3zskGpx4=
|
||||
golang.org/x/exp v0.0.0-20221126150942-6ab00d035af9/go.mod h1:CxIveKay+FTh1D0yPZemJVgC/95VzuuOLq5Qi4xnoYc=
|
||||
golang.org/x/net v0.9.0 h1:aWJ/m6xSmxWBx+V0XRHTlrYrPG56jKsLdTFmsSsCzOM=
|
||||
golang.org/x/net v0.9.0/go.mod h1:d48xBJpPfHeWQsugry2m+kC02ZBRGRgulfHnEXEuWns=
|
||||
golang.org/x/sync v0.1.0 h1:wsuoTGHzEhffawBOhz5CYhcrV4IdKZbEyZjBMuTp12o=
|
||||
golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sys v0.7.0 h1:3jlCCIQZPdOYu1h8BkNvLz8Kgwtae2cagcG/VamtZRU=
|
||||
golang.org/x/sys v0.7.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/term v0.7.0 h1:BEvjmm5fURWqcfbSKTdpkDXYBrUS1c0m8agp14W48vQ=
|
||||
golang.org/x/term v0.7.0/go.mod h1:P32HKFT3hSsZrRxla30E9HqToFYAQPCMs/zFMBUFqPY=
|
||||
golang.org/x/text v0.9.0 h1:2sjJmO8cDvYveuX97RDLsxlyUxLl+GHoLxBiRdHllBE=
|
||||
golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=
|
||||
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.36.0 h1:vWF2fRbw4qslQsQzgFqZff+BItCvGFQqKzKIzx1rmoA=
|
||||
golang.org/x/net v0.36.0/go.mod h1:bFmbeoIPfrw4sMHNhb4J9f6+tPziuGjq7Jk/38fxi1I=
|
||||
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/check.v1 v1.0.0-20180628173108-788fd7840127 h1:qIbj1fsPNlZgppZ+VLlY7N33q108Sa+fhmuc+sWQYwY=
|
||||
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI=
|
||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
|
||||
+53
@@ -0,0 +1,53 @@
|
||||
package gql
|
||||
|
||||
import (
|
||||
"crypto/md5"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
|
||||
"github.com/goccy/go-json"
|
||||
libpack_logger "github.com/lukaszraczylo/go-simple-graphql/logging"
|
||||
)
|
||||
|
||||
func searchForKeysInMapStringInterface(msi map[string]interface{}, key string) interface{} {
|
||||
if msi == nil {
|
||||
return nil
|
||||
}
|
||||
return msi[key]
|
||||
}
|
||||
|
||||
func calculateHash(query *Query) string {
|
||||
hash := md5.Sum(query.JsonQuery)
|
||||
return hex.EncodeToString(hash[:])
|
||||
}
|
||||
|
||||
func (b *BaseClient) cacheLookup(hash string) []byte {
|
||||
obj, _ := b.cache.Get(hash)
|
||||
return obj
|
||||
}
|
||||
|
||||
func (b *BaseClient) decodeResponse(response []byte) (any, error) {
|
||||
switch b.responseType {
|
||||
case "mapstring":
|
||||
var result map[string]interface{}
|
||||
err := json.Unmarshal(response, &result)
|
||||
if err != nil {
|
||||
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
|
||||
case "string":
|
||||
return string(response), nil
|
||||
case "byte":
|
||||
return response, nil
|
||||
default:
|
||||
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")
|
||||
}
|
||||
}
|
||||
+107
@@ -0,0 +1,107 @@
|
||||
package gql
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/goccy/go-reflect"
|
||||
)
|
||||
|
||||
func (suite *Tests) Test_searchForKeysInMapStringInterface() {
|
||||
type args struct {
|
||||
msi map[string]interface{}
|
||||
key string
|
||||
}
|
||||
tests := []struct {
|
||||
wantValue any
|
||||
args args
|
||||
name string
|
||||
}{
|
||||
{
|
||||
name: "Test_searchForKeysInMapStringInterface_exists",
|
||||
args: args{
|
||||
msi: map[string]interface{}{
|
||||
"gqlcache": true,
|
||||
"test": "test2",
|
||||
},
|
||||
key: "test",
|
||||
},
|
||||
wantValue: "test2",
|
||||
},
|
||||
{
|
||||
name: "Test_searchForKeysInMapStringInterface_not_exists",
|
||||
args: args{
|
||||
msi: map[string]interface{}{
|
||||
"gqlcache": true,
|
||||
"test": "test2",
|
||||
},
|
||||
key: "test-new",
|
||||
},
|
||||
wantValue: nil,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
suite.T().Run(tt.name, func(t *testing.T) {
|
||||
assert.Equal(tt.wantValue, searchForKeysInMapStringInterface(tt.args.msi, tt.args.key))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func (suite *Tests) TestBaseClient_decodeResponse() {
|
||||
type args struct {
|
||||
response []byte
|
||||
}
|
||||
tests := []struct {
|
||||
want any
|
||||
name string
|
||||
setType string
|
||||
wantType string
|
||||
args args
|
||||
wantErr bool
|
||||
}{
|
||||
{
|
||||
name: "TestBaseClient_decodeResponse_mapstring",
|
||||
args: args{
|
||||
response: []byte(`{"data":{"viewer":{"login":"lukaszraczylo"}}}`),
|
||||
},
|
||||
want: map[string]interface{}{
|
||||
"data": map[string]interface{}{
|
||||
"viewer": map[string]interface{}{
|
||||
"login": "lukaszraczylo",
|
||||
},
|
||||
},
|
||||
},
|
||||
setType: "mapstring",
|
||||
wantType: "map[string]interface {}",
|
||||
},
|
||||
{
|
||||
name: "TestBaseClient_decodeResponse_string",
|
||||
args: args{
|
||||
response: []byte(`{"data":{"viewer":{"login":"lukaszraczylo"}}}`),
|
||||
},
|
||||
want: `{"data":{"viewer":{"login":"lukaszraczylo"}}}`,
|
||||
setType: "string",
|
||||
wantType: "string",
|
||||
},
|
||||
{
|
||||
name: "TestBaseClient_decodeResponse_byte",
|
||||
args: args{
|
||||
response: []byte(`{"data":{"viewer":{"login":"lukaszraczylo"}}}`),
|
||||
},
|
||||
want: []byte(`{"data":{"viewer":{"login":"lukaszraczylo"}}}`),
|
||||
setType: "byte",
|
||||
wantType: "[]uint8",
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
suite.T().Run(tt.name, func(t *testing.T) {
|
||||
b := NewConnection()
|
||||
b.SetOutput(tt.setType)
|
||||
got, err := b.decodeResponse(tt.args.response)
|
||||
if (err != nil) != tt.wantErr {
|
||||
t.Errorf("decodeResponse() error = %v, wantErr %v", err, tt.wantErr)
|
||||
return
|
||||
}
|
||||
assert.Equal(tt.wantType, reflect.TypeOf(got).String())
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package gql
|
||||
|
||||
import (
|
||||
"crypto/tls"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
libpack_logger "github.com/lukaszraczylo/go-simple-graphql/logging"
|
||||
"golang.org/x/net/http2"
|
||||
)
|
||||
|
||||
func (b *BaseClient) createHttpClient() (http_client *http.Client) {
|
||||
httpTransport := &http.Transport{
|
||||
MaxIdleConns: 512,
|
||||
MaxConnsPerHost: 512,
|
||||
MaxIdleConnsPerHost: 512,
|
||||
IdleConnTimeout: 15 * time.Second,
|
||||
ResponseHeaderTimeout: 15 * time.Second,
|
||||
DisableKeepAlives: false,
|
||||
DisableCompression: false,
|
||||
}
|
||||
|
||||
if strings.HasPrefix(b.endpoint, "http://") {
|
||||
http_client = &http.Client{
|
||||
Timeout: 15 * time.Second,
|
||||
Transport: httpTransport,
|
||||
CheckRedirect: func(req *http.Request, via []*http.Request) error {
|
||||
return http.ErrUseLastResponse
|
||||
},
|
||||
}
|
||||
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://") {
|
||||
tlsClientConfig.InsecureSkipVerify = true
|
||||
}
|
||||
http2Transport := &http2.Transport{
|
||||
AllowHTTP: true,
|
||||
TLSClientConfig: tlsClientConfig,
|
||||
ReadIdleTimeout: 15 * time.Second,
|
||||
PingTimeout: 15 * time.Second,
|
||||
}
|
||||
http_client = &http.Client{
|
||||
Transport: http2Transport,
|
||||
CheckRedirect: func(req *http.Request, via []*http.Request) error {
|
||||
return http.ErrUseLastResponse
|
||||
},
|
||||
}
|
||||
b.Logger.Debug(&libpack_logger.LogMessage{
|
||||
Message: "Using HTTP/2 over https",
|
||||
Pairs: nil,
|
||||
})
|
||||
} else {
|
||||
b.Logger.Critical(&libpack_logger.LogMessage{
|
||||
Message: "Invalid endpoint - neither http or https",
|
||||
})
|
||||
}
|
||||
return http_client
|
||||
}
|
||||
@@ -1,141 +0,0 @@
|
||||
package gql
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"reflect"
|
||||
"time"
|
||||
|
||||
"github.com/lukaszraczylo/go-simple-graphql/utils/logger"
|
||||
|
||||
"github.com/gookit/goutil/timex"
|
||||
)
|
||||
|
||||
func NewLogger(writer Writer, config logger.Config) Logger {
|
||||
colorfulPrint := "%s[%s]%s %%s %%s"
|
||||
closeColor, debugColor, infoColor, warnColor, errorColor := "\033[0m", "\033[1;34m", "\033[1;32m", "\033[1;33m", "\033[1;31m"
|
||||
if !config.Colorful {
|
||||
closeColor, debugColor, infoColor, warnColor, errorColor = "", "", "", "", ""
|
||||
}
|
||||
debugStr := fmt.Sprintf(colorfulPrint, debugColor, "DEBUG", closeColor)
|
||||
infoStr := fmt.Sprintf(colorfulPrint, infoColor, "INFO", closeColor)
|
||||
warnStr := fmt.Sprintf(colorfulPrint, warnColor, "WARN", closeColor)
|
||||
errStr := fmt.Sprintf(colorfulPrint, errorColor, "ERROR", closeColor)
|
||||
|
||||
return &logging{
|
||||
Writer: writer,
|
||||
Config: config,
|
||||
infoStr: infoStr,
|
||||
warnStr: warnStr,
|
||||
errStr: errStr,
|
||||
debugStr: debugStr,
|
||||
}
|
||||
}
|
||||
|
||||
func setDate() string {
|
||||
tx := time.Now()
|
||||
return timex.DateFormat(tx, "Y-m-d H:I:S")
|
||||
}
|
||||
|
||||
func (l logging) Debug(client *BaseClient, msg string, data ...any) {
|
||||
if l.LogLevel >= logger.Debug {
|
||||
t := setDate()
|
||||
msg, data = censorSensitiveInfo(client, msg, data...)
|
||||
if client != nil {
|
||||
l.Printf(l.debugStr, fmt.Sprintf("[%s] %s", t, msg), sprint(data...))
|
||||
} else {
|
||||
l.Printf(l.debugStr, msg, sprint(data...))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (l logging) Info(client *BaseClient, msg string, data ...any) {
|
||||
if l.LogLevel >= logger.Info {
|
||||
t := setDate()
|
||||
msg, data = censorSensitiveInfo(client, msg, data...)
|
||||
if client != nil {
|
||||
l.Printf(l.infoStr, fmt.Sprintf("[%s] %s", t, msg), sprint(data...))
|
||||
} else {
|
||||
l.Printf(l.infoStr, msg, sprint(data...))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (l logging) Warn(client *BaseClient, msg string, data ...any) {
|
||||
if l.LogLevel >= logger.Warn {
|
||||
t := setDate()
|
||||
msg, data = censorSensitiveInfo(client, msg, data...)
|
||||
if client != nil {
|
||||
l.Printf(l.warnStr, fmt.Sprintf("[%s] %s", t, msg), sprint(data...))
|
||||
} else {
|
||||
l.Printf(l.warnStr, msg, sprint(data...))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (l logging) Error(client *BaseClient, msg string, data ...any) {
|
||||
if l.LogLevel >= logger.Error {
|
||||
t := setDate()
|
||||
msg, data = censorSensitiveInfo(client, msg, data...)
|
||||
if client != nil {
|
||||
l.Printf(l.errStr, fmt.Sprintf("[%s] %s", t, msg), sprint(data...))
|
||||
} else {
|
||||
l.Printf(l.errStr, msg, sprint(data...))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type Logger interface {
|
||||
Debug(*BaseClient, string, ...any)
|
||||
Info(*BaseClient, string, ...any)
|
||||
Warn(*BaseClient, string, ...any)
|
||||
Error(*BaseClient, string, ...any)
|
||||
}
|
||||
|
||||
type Writer interface {
|
||||
Printf(string, ...any)
|
||||
}
|
||||
|
||||
type logging struct {
|
||||
Writer
|
||||
debugStr string
|
||||
infoStr string
|
||||
warnStr string
|
||||
errStr string
|
||||
logger.Config
|
||||
}
|
||||
|
||||
func censorSensitiveInfo(client *BaseClient, a string, b ...any) (string, []any) {
|
||||
// if client == nil || client.Token == "" {
|
||||
// return a, b
|
||||
// }
|
||||
// tokenFixed := strings.Split(client.Token, ":")[1]
|
||||
// for t := range b {
|
||||
// if b[t] != nil {
|
||||
// rV := reflect.TypeOf(b[t]).Kind()
|
||||
// if rV == reflect.String {
|
||||
// b[t] = strings.ReplaceAll(b[t].(string), tokenFixed, strings.Repeat("X", len(tokenFixed)))
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// a = strings.ReplaceAll(a, tokenFixed, strings.Repeat("X", len(tokenFixed)))
|
||||
// return a, b
|
||||
return a, b
|
||||
}
|
||||
|
||||
func sprint(a ...any) string {
|
||||
for t := range a {
|
||||
if a[t] != nil {
|
||||
rV := reflect.TypeOf(a[t]).Kind()
|
||||
if rV == reflect.Ptr {
|
||||
a[t] = reflect.ValueOf(a[t]).Elem().Interface()
|
||||
}
|
||||
rV = reflect.TypeOf(a[t]).Kind()
|
||||
if rV == reflect.Struct || rV == reflect.Map || rV == reflect.Slice {
|
||||
a[t], _ = logger.Serialize(a[t])
|
||||
}
|
||||
}
|
||||
}
|
||||
r := fmt.Sprintln(a...)
|
||||
r = r[:len(r)-1]
|
||||
return r
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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))
|
||||
}
|
||||
@@ -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))
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package gql
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/gookit/goutil/envutil"
|
||||
cache "github.com/lukaszraczylo/go-simple-graphql/cache"
|
||||
logging "github.com/lukaszraczylo/go-simple-graphql/logging"
|
||||
)
|
||||
|
||||
func NewConnection() (b *BaseClient) {
|
||||
b = &BaseClient{
|
||||
endpoint: envutil.Getenv("GRAPHQL_ENDPOINT", "https://api.github.com/graphql"),
|
||||
responseType: envutil.Getenv("GRAPHQL_OUTPUT", "string"),
|
||||
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),
|
||||
retries_delay: time.Duration(envutil.GetInt("GRAPHQL_RETRIES_DELAY", 250) * int(time.Millisecond)),
|
||||
retries_number: envutil.GetInt("GRAPHQL_RETRIES_NUMBER", 3),
|
||||
}
|
||||
b.client = b.createHttpClient()
|
||||
b.Logger.Debug(&logging.LogMessage{
|
||||
Message: "Created new GraphQL client connection",
|
||||
Pairs: map[string]interface{}{
|
||||
"values": b,
|
||||
}})
|
||||
return b
|
||||
}
|
||||
|
||||
func (b *BaseClient) SetEndpoint(endpoint string) {
|
||||
b.endpoint = endpoint
|
||||
}
|
||||
|
||||
func (b *BaseClient) SetOutput(responseType string) {
|
||||
// allowed are byte, string, mapstring
|
||||
// check if responseType is allowed
|
||||
// TODO: implement
|
||||
b.responseType = responseType
|
||||
}
|
||||
|
||||
func (b *BaseClient) SetHTTPClient(client *http.Client) {
|
||||
b.client = client
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package gql
|
||||
|
||||
import "testing"
|
||||
|
||||
func Benchmark_newConnection(b *testing.B) {
|
||||
for i := 0; i < b.N; i++ {
|
||||
NewConnection()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package gql
|
||||
|
||||
import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
func (suite *Tests) TestNewConnection() {
|
||||
tests := []struct {
|
||||
name string
|
||||
}{
|
||||
{
|
||||
name: "TestNewConnection",
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
suite.T().Run(tt.name, func(t *testing.T) {
|
||||
got := NewConnection()
|
||||
assert.NotNil(suite.T(), got)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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)
|
||||
},
|
||||
}
|
||||
)
|
||||
@@ -1,157 +1,165 @@
|
||||
package gql
|
||||
|
||||
import (
|
||||
"context"
|
||||
"bytes"
|
||||
"fmt"
|
||||
"reflect"
|
||||
"strconv"
|
||||
|
||||
"github.com/lukaszraczylo/go-simple-graphql/utils/helpers"
|
||||
|
||||
"github.com/goccy/go-json"
|
||||
"github.com/gookit/goutil"
|
||||
"github.com/gookit/goutil/strutil"
|
||||
|
||||
jsoniter "github.com/json-iterator/go"
|
||||
libpack_logger "github.com/lukaszraczylo/go-simple-graphql/logging"
|
||||
)
|
||||
|
||||
var json = jsoniter.ConfigCompatibleWithStandardLibrary
|
||||
func (b *BaseClient) convertToJSON(v any) []byte {
|
||||
buf := bufferPool.Get().(*bytes.Buffer)
|
||||
defer bufferPool.Put(buf)
|
||||
buf.Reset()
|
||||
|
||||
func (c *BaseClient) convertToJson(v any) []byte {
|
||||
json, err := json.Marshal(v)
|
||||
if err != nil {
|
||||
c.Logger.Error(c, "Can't convert to json;", "error", err.Error())
|
||||
// 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 json
|
||||
|
||||
// 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 (c *BaseClient) NewQuery(q ...any) *Query {
|
||||
query := &Query{}
|
||||
func (b *BaseClient) compileQuery(queryPartials ...any) *Query {
|
||||
var query string
|
||||
var variables map[string]interface{}
|
||||
|
||||
if len(q) > 0 {
|
||||
for _, v := range q {
|
||||
switch val := v.(type) {
|
||||
case string:
|
||||
query.query = val
|
||||
case map[string]interface{}:
|
||||
query.variables = val
|
||||
case context.Context:
|
||||
query.context = val
|
||||
}
|
||||
// Pre-allocate the query with an estimated size
|
||||
if len(queryPartials) > 0 {
|
||||
if str, ok := queryPartials[0].(string); ok {
|
||||
query = str
|
||||
}
|
||||
}
|
||||
|
||||
query.compiledQuery = c.convertToJson(request{
|
||||
Query: query.query,
|
||||
Variables: query.variables,
|
||||
// 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
|
||||
}
|
||||
|
||||
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(&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(&libpack_logger.LogMessage{
|
||||
Message: "Compiled query",
|
||||
Pairs: map[string]interface{}{"query": compiledQuery},
|
||||
})
|
||||
|
||||
c.Logger.Debug(c, "Clearing previously prepared variables and query")
|
||||
query.variables = nil
|
||||
|
||||
if query.context == nil {
|
||||
query.context = context.Background()
|
||||
enableCache, enableRetries, recompileRequired := compiledQuery.parseHeadersAndVariables(headers)
|
||||
if recompileRequired {
|
||||
compiledQuery = b.compileQuery(query, variables)
|
||||
}
|
||||
|
||||
if c.validate {
|
||||
c.Logger.Warn(c, "Validating query is not active")
|
||||
}
|
||||
|
||||
query.query = ""
|
||||
c.Logger.Debug(c, "Query prepared;", "query", helpers.BytesToString(query.compiledQuery))
|
||||
|
||||
return query
|
||||
}
|
||||
|
||||
// Query is a function that sends a query to the server
|
||||
// It takes 3 arguments:
|
||||
// 1. queryContent: the query string
|
||||
// 2. queryVariables: the variables for the query
|
||||
// 3. queryHeaders: the headers for the query
|
||||
// It looks a bit weird because of the backward compatibility
|
||||
|
||||
func (c *BaseClient) Query(queryContent string, queryVariables interface{}, queryHeaders map[string]interface{}) (any, error) {
|
||||
var queryHash string
|
||||
var cachedResponse []byte
|
||||
|
||||
cbc := reflect.ValueOf(*c).Interface().(BaseClient)
|
||||
cacheBaseClient := &cbc
|
||||
|
||||
query := cacheBaseClient.NewQuery(queryContent, queryVariables)
|
||||
|
||||
// Check for library specific headers
|
||||
if len(queryHeaders) > 0 {
|
||||
queryHeadersModified := c.parseQueryHeaders(queryHeaders)
|
||||
// compare if there are any changes
|
||||
|
||||
if !reflect.DeepEqual(queryHeadersModified, queryHeaders) {
|
||||
cacheBaseClient.Logger.Debug(cacheBaseClient, "Headers modified, creating a new client")
|
||||
if (enableCache || b.cache_global) && strutil.HasPrefix(compiledQuery.Query, "query") {
|
||||
b.Logger.Debug(&libpack_logger.LogMessage{
|
||||
Message: "Cache enabled",
|
||||
Pairs: nil,
|
||||
})
|
||||
queryHash = calculateHash(compiledQuery)
|
||||
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(&libpack_logger.LogMessage{
|
||||
Message: "Cache miss",
|
||||
Pairs: map[string]interface{}{"query": compiledQuery},
|
||||
})
|
||||
}
|
||||
|
||||
if cacheBaseClient.cache.enabled {
|
||||
queryHash = strutil.Md5(fmt.Sprintf("%s-%+v", query.compiledQuery, queryHeaders))
|
||||
cacheBaseClient.Logger.Debug(cacheBaseClient, "Hash calculated;", "hash:", queryHash)
|
||||
|
||||
cachedResponse = cacheBaseClient.cacheLookup(queryHash)
|
||||
if cachedResponse != nil {
|
||||
cacheBaseClient.Logger.Debug(cacheBaseClient, "Found cached response")
|
||||
return cacheBaseClient.decodeResponse(cachedResponse), nil
|
||||
} else {
|
||||
cacheBaseClient.Logger.Debug(cacheBaseClient, "No cached response found")
|
||||
}
|
||||
q := &QueryExecutor{
|
||||
BaseClient: b,
|
||||
Query: compiledQuery.JsonQuery,
|
||||
Headers: headers,
|
||||
CacheKey: func() string {
|
||||
if queryHash != "" {
|
||||
return queryHash
|
||||
}
|
||||
return "no-cache"
|
||||
}(),
|
||||
Retries: enableRetries || b.retries_enable,
|
||||
}
|
||||
|
||||
response, err := cacheBaseClient.executeQuery(query.compiledQuery, queryHeaders)
|
||||
rv, err := q.executeQuery()
|
||||
if err != nil {
|
||||
cacheBaseClient.Logger.Error(cacheBaseClient, "Error while executing query;", "error", err.Error())
|
||||
b.Logger.Error(&libpack_logger.LogMessage{
|
||||
Message: "Error executing query",
|
||||
Pairs: map[string]interface{}{"error": err.Error()},
|
||||
})
|
||||
return nil, err
|
||||
}
|
||||
|
||||
jsonData, err := json.Marshal(response)
|
||||
if err != nil {
|
||||
cacheBaseClient.Logger.Error(cacheBaseClient, "Error while converting to json;", "error", err.Error())
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if cacheBaseClient.cache.enabled {
|
||||
cacheBaseClient.cache.client.Set(queryHash, jsonData)
|
||||
}
|
||||
|
||||
return cacheBaseClient.decodeResponse(jsonData), err
|
||||
return b.decodeResponse(rv)
|
||||
}
|
||||
|
||||
func (c *BaseClient) decodeResponse(jsonData []byte) any {
|
||||
switch c.responseType {
|
||||
case "mapstring":
|
||||
var response map[string]interface{}
|
||||
err := json.Unmarshal(jsonData, &response)
|
||||
if err != nil {
|
||||
c.Logger.Error(c, "Error while converting to map[string]interface{};", "error", err.Error())
|
||||
return nil
|
||||
}
|
||||
return response
|
||||
case "string":
|
||||
return helpers.BytesToString(jsonData)
|
||||
case "byte":
|
||||
return jsonData
|
||||
default:
|
||||
c.Logger.Error(c, "Unknown response type", "response", c.responseType)
|
||||
return nil
|
||||
}
|
||||
}
|
||||
func (q *Query) parseHeadersAndVariables(headers map[string]interface{}) (enableCache, enableRetries, recompileRequired bool) {
|
||||
enableCache, _ = goutil.ToBool(searchForKeysInMapStringInterface(headers, "gqlcache"))
|
||||
enableRetries, _ = goutil.ToBool(searchForKeysInMapStringInterface(headers, "gqlretries"))
|
||||
|
||||
func (c *BaseClient) parseQueryHeaders(queryHeaders map[string]interface{}) (returnHeaders map[string]interface{}) {
|
||||
returnHeaders = make(map[string]interface{})
|
||||
for k, v := range queryHeaders {
|
||||
if k == "gqlcache" {
|
||||
c.cache.enabled, _ = strconv.ParseBool(fmt.Sprintf("%v", v))
|
||||
continue
|
||||
if q.Variables != nil {
|
||||
varEnableCache, _ := goutil.ToBool(searchForKeysInMapStringInterface(q.Variables, "gqlcache"))
|
||||
varEnableRetries, _ := goutil.ToBool(searchForKeysInMapStringInterface(q.Variables, "gqlretries"))
|
||||
enableCache = enableCache || varEnableCache
|
||||
enableRetries = enableRetries || varEnableRetries
|
||||
|
||||
if varEnableCache || varEnableRetries {
|
||||
delete(q.Variables, "gqlcache")
|
||||
delete(q.Variables, "gqlretries")
|
||||
recompileRequired = true
|
||||
}
|
||||
if k == "gqlretries" {
|
||||
c.retries.enabled, _ = strconv.ParseBool(fmt.Sprintf("%v", v))
|
||||
continue
|
||||
}
|
||||
returnHeaders[k] = v
|
||||
}
|
||||
return returnHeaders
|
||||
|
||||
return enableCache, enableRetries, recompileRequired
|
||||
}
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
package gql
|
||||
|
||||
import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
func Benchmark_compileQuery(bn *testing.B) {
|
||||
b := NewConnection()
|
||||
bn.ResetTimer()
|
||||
for i := 0; i < bn.N; i++ {
|
||||
b.compileQuery(
|
||||
`query { viewer { login } }`,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
func Benchmark_compileQueryWithVariables(bn *testing.B) {
|
||||
b := NewConnection()
|
||||
variables := map[string]interface{}{
|
||||
"var1": "value1",
|
||||
}
|
||||
bn.ResetTimer()
|
||||
for i := 0; i < bn.N; i++ {
|
||||
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)
|
||||
}
|
||||
}
|
||||
+106
-396
@@ -1,474 +1,184 @@
|
||||
package gql
|
||||
|
||||
import (
|
||||
"math/rand"
|
||||
"reflect"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/goccy/go-reflect"
|
||||
)
|
||||
|
||||
func TestBaseClient_convertToJson(t *testing.T) {
|
||||
type fields struct {
|
||||
}
|
||||
func (suite *Tests) TestBaseClient_convertToJSON() {
|
||||
type args struct {
|
||||
v any
|
||||
}
|
||||
tests := []struct {
|
||||
name string
|
||||
fields fields
|
||||
args args
|
||||
want []byte
|
||||
name string
|
||||
args args
|
||||
want []byte
|
||||
}{
|
||||
{
|
||||
name: "Test convertToJson",
|
||||
fields: fields{},
|
||||
name: "TestBaseClient_convertToJSON_query",
|
||||
args: args{
|
||||
v: `query { viewer { login } }`,
|
||||
},
|
||||
want: []byte(`"query { viewer { login } }"`),
|
||||
},
|
||||
{
|
||||
name: "TestBaseClient_convertToJSON_variables",
|
||||
args: args{
|
||||
v: map[string]interface{}{
|
||||
"query": "query { hello }",
|
||||
"login": "lukaszraczylo",
|
||||
"first": 10,
|
||||
},
|
||||
},
|
||||
want: []byte(`{"query":"query { hello }"}`),
|
||||
},
|
||||
{
|
||||
name: "Test convertToJson with variables",
|
||||
fields: fields{},
|
||||
args: args{
|
||||
v: map[string]interface{}{
|
||||
"query": "query { hello }",
|
||||
"variables": map[string]interface{}{"name": "John"},
|
||||
},
|
||||
},
|
||||
want: []byte(`{"query":"query { hello }","variables":{"name":"John"}}`),
|
||||
want: []byte(`{"first":10,"login":"lukaszraczylo"}`),
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
c := &BaseClient{}
|
||||
if got := c.convertToJson(tt.args.v); !reflect.DeepEqual(got, tt.want) {
|
||||
t.Errorf("BaseClient.convertToJson() = %v, want %v", got, tt.want)
|
||||
suite.T().Run(tt.name, func(t *testing.T) {
|
||||
b := NewConnection()
|
||||
if got := b.convertToJSON(tt.args.v); !reflect.DeepEqual(got, tt.want) {
|
||||
assert.Equal(tt.want, got)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestBaseClient_NewQuery(t *testing.T) {
|
||||
type fields struct {
|
||||
}
|
||||
func (suite *Tests) TestBaseClient_compileQuery() {
|
||||
type args struct {
|
||||
q []any
|
||||
query_partials []any
|
||||
}
|
||||
tests := []struct {
|
||||
fields fields
|
||||
want *Query
|
||||
name string
|
||||
args args
|
||||
wantQ *Query
|
||||
name string
|
||||
args args
|
||||
}{
|
||||
{
|
||||
name: "Test NewQuery",
|
||||
fields: fields{},
|
||||
name: "TestBaseClient_compileQuery_query",
|
||||
args: args{
|
||||
q: []any{
|
||||
"query { hello }",
|
||||
query_partials: []any{
|
||||
`query { viewer { login } }`,
|
||||
},
|
||||
},
|
||||
want: &Query{
|
||||
compiledQuery: []byte(`{"variables":null,"query":"query { hello }"}`),
|
||||
wantQ: &Query{
|
||||
Query: `query { viewer { login } }`,
|
||||
JsonQuery: []byte(`{"query":"query { viewer { login } }"}`),
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "Test NewQuery with variables",
|
||||
fields: fields{},
|
||||
name: "TestBaseClient_compileQuery_with_variables",
|
||||
args: args{
|
||||
q: []any{
|
||||
"query { hello }",
|
||||
map[string]interface{}{"name": "John"},
|
||||
query_partials: []any{
|
||||
`query { viewer { login } }`,
|
||||
map[string]interface{}{
|
||||
"login": "lukaszraczylo",
|
||||
"first": 10,
|
||||
},
|
||||
},
|
||||
},
|
||||
want: &Query{
|
||||
compiledQuery: []byte(`{"variables":{"name":"John"},"query":"query { hello }"}`),
|
||||
wantQ: &Query{
|
||||
Query: `query { viewer { login } }`,
|
||||
Variables: map[string]interface{}{
|
||||
"login": "lukaszraczylo",
|
||||
"first": 10,
|
||||
},
|
||||
JsonQuery: []byte(`{"variables":{"first":10,"login":"lukaszraczylo"},"query":"query { viewer { login } }"}`),
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "TestBaseClient_compileQuery_variables_without_query",
|
||||
args: args{
|
||||
query_partials: []any{
|
||||
map[string]interface{}{
|
||||
"login": "lukaszraczylo",
|
||||
"first": 10,
|
||||
},
|
||||
},
|
||||
},
|
||||
wantQ: nil,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
c := NewConnection()
|
||||
gotQuery := c.NewQuery(tt.args.q...)
|
||||
assert.Equal(t, tt.want.query, gotQuery.query)
|
||||
assert.Equal(t, tt.want.variables, gotQuery.variables)
|
||||
assert.Equal(t, tt.want.compiledQuery, gotQuery.compiledQuery)
|
||||
suite.T().Run(tt.name, func(t *testing.T) {
|
||||
b := NewConnection()
|
||||
got := b.compileQuery(tt.args.query_partials...)
|
||||
assert.Equal(tt.wantQ, got)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestBaseClient_decodeResponse(t *testing.T) {
|
||||
type fields struct {
|
||||
responseType string
|
||||
}
|
||||
func (suite *Tests) TestBaseClient_Query() {
|
||||
type args struct {
|
||||
jsonData []byte
|
||||
variables map[string]interface{}
|
||||
headers map[string]interface{}
|
||||
query string
|
||||
}
|
||||
tests := []struct {
|
||||
fields fields
|
||||
want any
|
||||
name string
|
||||
args args
|
||||
args args
|
||||
wantReturned_value any
|
||||
name string
|
||||
wantType string
|
||||
wantErr bool
|
||||
}{
|
||||
{
|
||||
name: "Test decodeResponse - string",
|
||||
fields: fields{
|
||||
responseType: "string",
|
||||
},
|
||||
name: "TestBaseClient_Query_viewer",
|
||||
args: args{
|
||||
jsonData: []byte(`{"data":{"hello":"world"}}`),
|
||||
},
|
||||
want: `{"data":{"hello":"world"}}`,
|
||||
},
|
||||
{
|
||||
name: "Test decodeResponse - byte",
|
||||
fields: fields{
|
||||
responseType: "byte",
|
||||
},
|
||||
args: args{
|
||||
jsonData: []byte(`{"data":{"hello":"world"}}`),
|
||||
},
|
||||
want: []byte(`{"data":{"hello":"world"}}`),
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
c := NewConnection()
|
||||
c.responseType = tt.fields.responseType
|
||||
if got := c.decodeResponse(tt.args.jsonData); !reflect.DeepEqual(got, tt.want) {
|
||||
t.Errorf("BaseClient.decodeResponse() = %v, want %v", got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestBaseClient_Query(t *testing.T) {
|
||||
type fields struct {
|
||||
graphql_endpoint string
|
||||
repeat int
|
||||
}
|
||||
type args struct {
|
||||
queryVariables interface{}
|
||||
queryHeaders map[string]interface{}
|
||||
queryContent string
|
||||
}
|
||||
tests := []struct {
|
||||
want any
|
||||
args args
|
||||
name string
|
||||
fields fields
|
||||
wantErr bool
|
||||
}{
|
||||
{
|
||||
name: "Test Query - failing",
|
||||
fields: fields{
|
||||
graphql_endpoint: "https://spacex-production.up.railway.app/",
|
||||
},
|
||||
args: args{
|
||||
queryContent: "query { hello }",
|
||||
},
|
||||
want: ``,
|
||||
wantErr: true,
|
||||
},
|
||||
{
|
||||
name: "Test Query - success",
|
||||
fields: fields{
|
||||
graphql_endpoint: "https://spacex-production.up.railway.app/",
|
||||
},
|
||||
args: args{
|
||||
queryContent: `query Dragons {
|
||||
dragons {
|
||||
name
|
||||
}
|
||||
}`,
|
||||
queryHeaders: map[string]interface{}{
|
||||
"x-apollo-operation-name": "Missions-Potato-Test-Golang",
|
||||
query: "query { viewer { login } }",
|
||||
variables: nil,
|
||||
headers: map[string]interface{}{
|
||||
"x-apollo-operation-name": "ViewerQuery",
|
||||
"content-type": "application/json",
|
||||
},
|
||||
},
|
||||
wantErr: false,
|
||||
want: `{"dragons":[{"name":"Dragon 1"},{"name":"Dragon 2"}]}`,
|
||||
wantReturned_value: `{"viewer":{"login":"mockuser"}}`, // Adjusted expected value
|
||||
wantErr: false,
|
||||
},
|
||||
{
|
||||
name: "Test Query - success",
|
||||
fields: fields{
|
||||
repeat: 2,
|
||||
graphql_endpoint: "https://spacex-production.up.railway.app/",
|
||||
},
|
||||
name: "TestBaseClient_Query_dragons",
|
||||
args: args{
|
||||
queryContent: `query Dragons {
|
||||
dragons {
|
||||
name
|
||||
first_flight
|
||||
}
|
||||
}`,
|
||||
queryHeaders: map[string]interface{}{
|
||||
"x-apollo-operation-name": "Missions-Potato-Test-Golang-Cached",
|
||||
query: `query Dragons {
|
||||
dragons {
|
||||
name
|
||||
}
|
||||
}`,
|
||||
variables: nil,
|
||||
headers: map[string]interface{}{
|
||||
"x-apollo-operation-name": "DragonsQuery",
|
||||
"content-type": "application/json",
|
||||
},
|
||||
},
|
||||
wantErr: false,
|
||||
want: `{"dragons":[{"first_flight":"2010-12-08","name":"Dragon 1"},{"first_flight":"2019-03-02","name":"Dragon 2"}]}`,
|
||||
wantReturned_value: `{"dragons":[{"name":"Mock Dragon 1"},{"name":"Mock Dragon 2"}]}`, // Adjusted expected value
|
||||
wantErr: false,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
c := NewConnection()
|
||||
|
||||
if tt.fields.graphql_endpoint != "" {
|
||||
c.endpoint = tt.fields.graphql_endpoint
|
||||
}
|
||||
|
||||
repeat := 1
|
||||
if tt.fields.repeat != 0 {
|
||||
repeat = tt.fields.repeat
|
||||
}
|
||||
|
||||
for i := 0; i < repeat; i++ {
|
||||
|
||||
got, err := c.Query(tt.args.queryContent, tt.args.queryVariables, tt.args.queryHeaders)
|
||||
|
||||
if err != nil && tt.wantErr {
|
||||
assert.Error(t, err)
|
||||
} else {
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, tt.want, got)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// benchmarks
|
||||
|
||||
func BenchmarkBaseClient_convertToJson(b *testing.B) {
|
||||
c := NewConnection()
|
||||
query := c.NewQuery("query { hello }")
|
||||
for i := 0; i < b.N; i++ {
|
||||
_ = c.convertToJson(query)
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkNewQuery(b *testing.B) {
|
||||
c := NewConnection()
|
||||
for i := 0; i < b.N; i++ {
|
||||
_ = c.NewQuery("query { hello }")
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkDecodeResponse(b *testing.B) {
|
||||
c := NewConnection()
|
||||
for i := 0; i < b.N; i++ {
|
||||
_ = c.decodeResponse([]byte(`{"data":{"hello":"world"}}`))
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkQueryNoCache(b *testing.B) {
|
||||
c := NewConnection()
|
||||
c.cache.enabled = false
|
||||
for i := 0; i < b.N; i++ {
|
||||
_, _ = c.Query(`query MyQuery {
|
||||
bots {
|
||||
bot_name
|
||||
}
|
||||
}`, nil, nil)
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkQueryWithCache(b *testing.B) {
|
||||
c := NewConnection()
|
||||
c.cache.enabled = true
|
||||
for i := 0; i < b.N; i++ {
|
||||
_, _ = c.Query(`query MyQuery {
|
||||
bots {
|
||||
bot_name
|
||||
}
|
||||
}`, nil, nil)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBaseClient_parseQueryHeaders(t *testing.T) {
|
||||
type fields struct {
|
||||
}
|
||||
type args struct {
|
||||
queryHeaders map[string]interface{}
|
||||
}
|
||||
tests := []struct {
|
||||
name string
|
||||
fields fields
|
||||
args args
|
||||
wantReturnHeaders map[string]interface{}
|
||||
}{
|
||||
{
|
||||
name: "Test parseQueryHeaders - no change",
|
||||
fields: fields{},
|
||||
name: "TestBaseClient_Query_invalid_query",
|
||||
args: args{
|
||||
queryHeaders: map[string]interface{}{
|
||||
"x-test-header": "test",
|
||||
"x-test-header-next": true,
|
||||
},
|
||||
},
|
||||
wantReturnHeaders: map[string]interface{}{
|
||||
"x-test-header": "test",
|
||||
"x-test-header-next": true,
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "Test parseQueryHeaders - lib-headers removed",
|
||||
fields: fields{},
|
||||
args: args{
|
||||
queryHeaders: map[string]interface{}{
|
||||
"x-test-header": "test",
|
||||
"gqlcache": true,
|
||||
},
|
||||
},
|
||||
wantReturnHeaders: map[string]interface{}{
|
||||
"x-test-header": "test",
|
||||
},
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
c := NewConnection()
|
||||
if gotReturnHeaders := c.parseQueryHeaders(tt.args.queryHeaders); !reflect.DeepEqual(gotReturnHeaders, tt.wantReturnHeaders) {
|
||||
t.Errorf("BaseClient.parseQueryHeaders() = %v, want %v", gotReturnHeaders, tt.wantReturnHeaders)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestBaseClient_QueryCache(t *testing.T) {
|
||||
type fields struct {
|
||||
graphql_endpoint string
|
||||
cache_enabled bool
|
||||
}
|
||||
type args struct {
|
||||
queryVariables interface{}
|
||||
queryHeaders map[string]interface{}
|
||||
queryContent string
|
||||
}
|
||||
tests := []struct {
|
||||
want any
|
||||
args args
|
||||
name string
|
||||
fields fields
|
||||
wantErr bool
|
||||
}{
|
||||
{
|
||||
name: "Test QueryCache - enabled",
|
||||
fields: fields{
|
||||
graphql_endpoint: "https://spacex-production.up.railway.app/",
|
||||
cache_enabled: true,
|
||||
},
|
||||
args: args{
|
||||
queryContent: `query Dragons {
|
||||
dragons {
|
||||
name
|
||||
}
|
||||
}`,
|
||||
queryHeaders: map[string]interface{}{
|
||||
"x-apollo-operation-name": "Missions-Potato-Test-Golang",
|
||||
"content-type": "application/json",
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "Test QueryCache - disabled",
|
||||
fields: fields{
|
||||
graphql_endpoint: "https://spacex-production.up.railway.app/",
|
||||
cache_enabled: false,
|
||||
},
|
||||
args: args{
|
||||
queryContent: `query Dragons {
|
||||
dragons {
|
||||
name
|
||||
}
|
||||
}`,
|
||||
queryHeaders: map[string]interface{}{
|
||||
"x-apollo-operation-name": "Missions-Potato-Test-Golang",
|
||||
query: "query { potato { login } ",
|
||||
variables: nil,
|
||||
headers: map[string]interface{}{
|
||||
"x-apollo-operation-name": "InvalidQuery",
|
||||
"content-type": "application/json",
|
||||
},
|
||||
},
|
||||
wantReturned_value: nil,
|
||||
wantErr: true,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
c := NewConnection()
|
||||
c.cache.enabled = tt.fields.cache_enabled
|
||||
|
||||
if tt.fields.graphql_endpoint != "" {
|
||||
c.endpoint = tt.fields.graphql_endpoint
|
||||
suite.T().Run(tt.name, func(t *testing.T) {
|
||||
b := NewConnection()
|
||||
b.SetEndpoint(mockServer.URL)
|
||||
b.SetHTTPClient(mockServer.Client())
|
||||
if tt.wantType != "" {
|
||||
b.SetOutput(tt.wantType)
|
||||
}
|
||||
|
||||
_, err := c.Query(tt.args.queryContent, tt.args.queryVariables, tt.args.queryHeaders)
|
||||
if !tt.wantErr {
|
||||
assert.NoError(t, err)
|
||||
gotReturned_value, err := b.Query(tt.args.query, tt.args.variables, tt.args.headers)
|
||||
if tt.wantErr {
|
||||
assert.Error(err)
|
||||
} else {
|
||||
assert.Error(t, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestBaseClient_QueryCacheRandomizedRace(t *testing.T) {
|
||||
type fields struct {
|
||||
graphql_endpoint string
|
||||
cache_enabled bool
|
||||
}
|
||||
type args struct {
|
||||
queryVariables interface{}
|
||||
queryHeaders map[string]interface{}
|
||||
queryContent string
|
||||
}
|
||||
tests := []struct {
|
||||
want any
|
||||
args args
|
||||
name string
|
||||
fields fields
|
||||
wantErr bool
|
||||
}{
|
||||
{
|
||||
name: "Test QueryCache - enabled",
|
||||
fields: fields{
|
||||
graphql_endpoint: "https://spacex-production.up.railway.app/",
|
||||
},
|
||||
args: args{
|
||||
queryContent: `query Dragons {
|
||||
dragons {
|
||||
name
|
||||
}
|
||||
}`,
|
||||
queryHeaders: map[string]interface{}{
|
||||
"x-apollo-operation-name": "Missions-Potato-Test-Golang",
|
||||
"content-type": "application/json",
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
c := NewConnection()
|
||||
if tt.fields.graphql_endpoint != "" {
|
||||
c.endpoint = tt.fields.graphql_endpoint
|
||||
}
|
||||
|
||||
for i := 0; i < 10; i++ {
|
||||
c.cache.enabled = rand.Intn(2) == 0
|
||||
go func() {
|
||||
_, err := c.Query(tt.args.queryContent, tt.args.queryVariables, tt.args.queryHeaders)
|
||||
if !tt.wantErr {
|
||||
assert.NoError(t, err)
|
||||
} else {
|
||||
assert.Error(t, err)
|
||||
}
|
||||
}()
|
||||
assert.NoError(err)
|
||||
}
|
||||
assert.Equal(tt.wantReturned_value, gotReturned_value)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
-67
@@ -1,67 +0,0 @@
|
||||
package gql
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/avast/retry-go/v4"
|
||||
)
|
||||
|
||||
func (c *BaseClient) executeQuery(query []byte, headers any) (result any, err error) {
|
||||
var queryResult queryResults
|
||||
httpRequest, err := http.NewRequest("POST", c.endpoint, bytes.NewBuffer(query))
|
||||
if err != nil {
|
||||
c.Logger.Error(c, "Error while creating http request;", "error", err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
for key, value := range headers.(map[string]interface{}) {
|
||||
httpRequest.Header.Add(key, fmt.Sprintf("%s", value))
|
||||
}
|
||||
|
||||
var httpResponse *http.Response
|
||||
|
||||
err = retry.Do(
|
||||
func() error {
|
||||
httpResponse, err = c.client.Do(httpRequest)
|
||||
if err != nil {
|
||||
c.Logger.Error(c, "Error while executing http request;", "error", err.Error())
|
||||
return err
|
||||
}
|
||||
defer httpResponse.Body.Close()
|
||||
|
||||
if httpResponse.StatusCode <= 200 && httpResponse.StatusCode >= 204 {
|
||||
return err
|
||||
}
|
||||
|
||||
body, err := ioutil.ReadAll(httpResponse.Body)
|
||||
if err != nil {
|
||||
c.Logger.Error(c, "Error while reading http response;", "error", err.Error())
|
||||
return err
|
||||
}
|
||||
|
||||
err = json.Unmarshal(body, &queryResult)
|
||||
if err != nil {
|
||||
c.Logger.Error(c, "Error while unmarshalling http response;", "error", err.Error())
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
},
|
||||
retry.OnRetry(func(n uint, err error) {
|
||||
c.Logger.Error(c, "Retrying query", "error", err.Error())
|
||||
}),
|
||||
retry.Attempts(uint(c.retries.max)),
|
||||
retry.DelayType(retry.BackOffDelay),
|
||||
retry.Delay(time.Duration(c.retries.delay)*time.Second),
|
||||
retry.LastErrorOnly(true),
|
||||
)
|
||||
|
||||
if len(queryResult.Errors) > 0 {
|
||||
return nil, fmt.Errorf("%v", queryResult.Errors)
|
||||
}
|
||||
return queryResult.Data, nil
|
||||
}
|
||||
+2
-2
@@ -1,9 +1,9 @@
|
||||
version: 1
|
||||
force:
|
||||
major: 1
|
||||
minor: 1
|
||||
minor: 2
|
||||
patch: 0
|
||||
commit: 6a8f99f6ef8f65a303dad74c272ff12bf9fe526f
|
||||
commit: 3217edf37fd1765c4f2594e3ba122a6a9c251296
|
||||
wording:
|
||||
minor:
|
||||
- minor-release
|
||||
|
||||
+25
-36
@@ -1,52 +1,41 @@
|
||||
package gql
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/lukaszraczylo/go-simple-graphql/utils/concurrency"
|
||||
"github.com/lukaszraczylo/go-simple-graphql/utils/logger"
|
||||
|
||||
"github.com/allegro/bigcache"
|
||||
cache "github.com/lukaszraczylo/go-simple-graphql/cache"
|
||||
logging "github.com/lukaszraczylo/go-simple-graphql/logging"
|
||||
)
|
||||
|
||||
type cacheStore struct {
|
||||
client *bigcache.BigCache
|
||||
ttl int
|
||||
enabled bool
|
||||
}
|
||||
|
||||
type retriesConfig struct {
|
||||
enabled bool
|
||||
max int
|
||||
delay int
|
||||
}
|
||||
|
||||
type BaseClient struct {
|
||||
Logger Logger
|
||||
LoggerWriter Writer
|
||||
client *http.Client
|
||||
concurrencyManager *concurrency.Pool
|
||||
endpoint string
|
||||
responseType string
|
||||
cache cacheStore
|
||||
MaxGoRoutines int
|
||||
LoggingLevel logger.LogLevel
|
||||
LoggerColorful bool
|
||||
validate bool
|
||||
retries retriesConfig
|
||||
cache *cache.Cache
|
||||
Logger *logging.Logger
|
||||
client *http.Client
|
||||
endpoint string
|
||||
responseType string
|
||||
retries_delay time.Duration
|
||||
retries_number int
|
||||
MaxGoRoutines int
|
||||
cache_global bool
|
||||
retries_enable bool
|
||||
}
|
||||
|
||||
type Query struct {
|
||||
context context.Context
|
||||
variables map[string]any `json:"variables"`
|
||||
query string `json:"query"`
|
||||
compiledQuery []byte `json:"compiledQuery"`
|
||||
Variables map[string]interface{} `json:"variables,omitempty"`
|
||||
Query string `json:"query,omitempty"`
|
||||
JsonQuery []byte `json:"jsonQuery,omitempty"`
|
||||
}
|
||||
|
||||
type request struct {
|
||||
Variables any `json:"variables"`
|
||||
Query string `json:"query"`
|
||||
type QueryExecutor struct {
|
||||
Result any
|
||||
Error error
|
||||
*BaseClient
|
||||
Headers map[string]interface{}
|
||||
CacheKey string
|
||||
Query []byte
|
||||
CacheTTL time.Duration
|
||||
Retries bool
|
||||
}
|
||||
|
||||
type queryResults struct {
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
package gql
|
||||
|
||||
import (
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
assertions "github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/suite"
|
||||
)
|
||||
|
||||
type Tests struct {
|
||||
suite.Suite
|
||||
}
|
||||
|
||||
var (
|
||||
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())
|
||||
}
|
||||
|
||||
func (suite *Tests) BeforeTest(suiteName, testName string) {
|
||||
}
|
||||
|
||||
func TestSuite(t *testing.T) {
|
||||
suite.Run(t, new(Tests))
|
||||
}
|
||||
@@ -1,30 +0,0 @@
|
||||
package concurrency
|
||||
|
||||
type Pool struct {
|
||||
queue chan struct{}
|
||||
jobs int
|
||||
}
|
||||
|
||||
func NewPool(size int) *Pool {
|
||||
if size < 0 {
|
||||
size = 0
|
||||
}
|
||||
return &Pool{
|
||||
jobs: size,
|
||||
queue: make(chan struct{}, size),
|
||||
}
|
||||
}
|
||||
|
||||
func (p *Pool) Enqueue(job func(params ...any), params ...any) {
|
||||
if p.jobs == 0 {
|
||||
go job(params...)
|
||||
return
|
||||
}
|
||||
p.queue <- struct{}{}
|
||||
go func() {
|
||||
defer func() {
|
||||
<-p.queue
|
||||
}()
|
||||
job(params...)
|
||||
}()
|
||||
}
|
||||
@@ -1,74 +0,0 @@
|
||||
package concurrency
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestNewPool(t *testing.T) {
|
||||
type args struct {
|
||||
size int
|
||||
}
|
||||
tests := []struct {
|
||||
want *Pool
|
||||
name string
|
||||
args args
|
||||
}{
|
||||
{
|
||||
name: "TestNewPool",
|
||||
args: args{
|
||||
size: 0,
|
||||
},
|
||||
want: &Pool{
|
||||
jobs: 0,
|
||||
queue: make(chan struct{}, 0),
|
||||
},
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
got := NewPool(tt.args.size)
|
||||
assert.Equal(t, got.jobs, tt.want.jobs)
|
||||
assert.Equal(t, cap(got.queue), cap(tt.want.queue))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestPool_Enqueue(t *testing.T) {
|
||||
type fields struct {
|
||||
queue chan struct{}
|
||||
jobs int
|
||||
}
|
||||
type args struct {
|
||||
job func(params ...any)
|
||||
params []any
|
||||
}
|
||||
tests := []struct {
|
||||
name string
|
||||
fields fields
|
||||
args args
|
||||
}{
|
||||
{
|
||||
name: "TestPool_Enqueue",
|
||||
fields: fields{
|
||||
queue: make(chan struct{}, 0),
|
||||
jobs: 0,
|
||||
},
|
||||
args: args{
|
||||
job: func(params ...any) {
|
||||
return
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
p := &Pool{
|
||||
queue: tt.fields.queue,
|
||||
jobs: tt.fields.jobs,
|
||||
}
|
||||
p.Enqueue(tt.args.job, tt.args.params...)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
package helpers
|
||||
|
||||
import (
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
func StringToBytes(s string) []byte {
|
||||
return unsafe.Slice(unsafe.StringData(s), len(s))
|
||||
}
|
||||
|
||||
func BytesToString(b []byte) string {
|
||||
return unsafe.String(unsafe.SliceData(b), len(b))
|
||||
}
|
||||
@@ -1,70 +0,0 @@
|
||||
package helpers
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestStringToBytes(t *testing.T) {
|
||||
type args struct {
|
||||
s string
|
||||
}
|
||||
tests := []struct {
|
||||
name string
|
||||
args args
|
||||
want []byte
|
||||
}{
|
||||
{
|
||||
name: "TestStringToBytes",
|
||||
args: args{
|
||||
s: "hello world",
|
||||
},
|
||||
want: []byte("hello world"),
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if got := StringToBytes(tt.args.s); !reflect.DeepEqual(got, tt.want) {
|
||||
t.Errorf("StringToBytes() = %v, want %v", got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestBytesToString(t *testing.T) {
|
||||
type args struct {
|
||||
b []byte
|
||||
}
|
||||
tests := []struct {
|
||||
name string
|
||||
want string
|
||||
args args
|
||||
}{
|
||||
{
|
||||
name: "TestBytesToString",
|
||||
args: args{
|
||||
b: []byte("hello world"),
|
||||
},
|
||||
want: "hello world",
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if got := BytesToString(tt.args.b); got != tt.want {
|
||||
t.Errorf("BytesToString() = %v, want %v", got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkStringToBytes(b *testing.B) {
|
||||
for i := 0; i < b.N; i++ {
|
||||
StringToBytes("hello world")
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkBytesToString(b *testing.B) {
|
||||
for i := 0; i < b.N; i++ {
|
||||
BytesToString([]byte("hello world"))
|
||||
}
|
||||
}
|
||||
@@ -1,72 +0,0 @@
|
||||
package logger
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
|
||||
"github.com/lukaszraczylo/go-simple-graphql/utils/helpers"
|
||||
"github.com/lukaszraczylo/go-simple-graphql/utils/ordered_map"
|
||||
|
||||
jsoniter "github.com/json-iterator/go"
|
||||
)
|
||||
|
||||
var json = jsoniter.ConfigCompatibleWithStandardLibrary
|
||||
|
||||
const (
|
||||
reset = "\033[0m"
|
||||
redBold = "\033[1;31m"
|
||||
greenBold = "\033[1;32m"
|
||||
yellowBold = "\033[1;33m"
|
||||
blueBold = "\033[1;34m"
|
||||
)
|
||||
|
||||
type LogLevel int
|
||||
|
||||
const (
|
||||
Silent LogLevel = iota
|
||||
Error
|
||||
Warn
|
||||
Info
|
||||
Debug
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
Colorful bool
|
||||
LogLevel LogLevel
|
||||
}
|
||||
|
||||
func Serialize(v any) (string, error) {
|
||||
marshal, err := json.Marshal(internalSerialize(v))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return helpers.BytesToString(marshal), nil
|
||||
}
|
||||
|
||||
func internalSerialize(v any) any {
|
||||
if v != nil {
|
||||
switch reflect.TypeOf(v).Kind() {
|
||||
case reflect.Struct:
|
||||
r := ordered_map.New()
|
||||
name := reflect.TypeOf(v).Name()
|
||||
if name != "" {
|
||||
r.Set("_", reflect.TypeOf(v).String())
|
||||
}
|
||||
for i := 0; i < reflect.ValueOf(v).NumField(); i++ {
|
||||
r.Set(reflect.TypeOf(v).Field(i).Name, internalSerialize(reflect.ValueOf(v).Field(i).Interface()))
|
||||
}
|
||||
return r
|
||||
case reflect.Ptr:
|
||||
if !reflect.ValueOf(v).IsNil() {
|
||||
return internalSerialize(reflect.ValueOf(v).Elem().Interface())
|
||||
}
|
||||
case reflect.Slice:
|
||||
var r []any
|
||||
tmpSlice := reflect.ValueOf(v)
|
||||
for i := 0; i < tmpSlice.Len(); i++ {
|
||||
r = append(r, internalSerialize(tmpSlice.Index(i).Interface()))
|
||||
}
|
||||
return r
|
||||
}
|
||||
}
|
||||
return v
|
||||
}
|
||||
@@ -1,84 +0,0 @@
|
||||
package logger
|
||||
|
||||
import "testing"
|
||||
|
||||
type Person struct {
|
||||
Name string
|
||||
Age int
|
||||
}
|
||||
|
||||
func TestSerializeStruct(t *testing.T) {
|
||||
person := Person{Name: "Alice", Age: 30}
|
||||
expected := `{"_":"logger.Person","Name":"Alice","Age":30}`
|
||||
actual, err := Serialize(person)
|
||||
if err != nil {
|
||||
t.Errorf("Error: %v", err)
|
||||
}
|
||||
if actual != expected {
|
||||
t.Errorf("Expected: %v\nActual: %v", expected, actual)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSerializeNilPointer(t *testing.T) {
|
||||
var person *Person
|
||||
expected := `null`
|
||||
actual, err := Serialize(person)
|
||||
if err != nil {
|
||||
t.Errorf("Error: %v", err)
|
||||
}
|
||||
if actual != expected {
|
||||
t.Errorf("Expected: %v\nActual: %v", expected, actual)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSerializeNonNilPointer(t *testing.T) {
|
||||
person := &Person{Name: "Alice", Age: 30}
|
||||
expected := `{"_":"logger.Person","Name":"Alice","Age":30}`
|
||||
actual, err := Serialize(person)
|
||||
if err != nil {
|
||||
t.Errorf("Error: %v", err)
|
||||
}
|
||||
if actual != expected {
|
||||
t.Errorf("Expected: %v\nActual: %v", expected, actual)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSerializeSlice(t *testing.T) {
|
||||
people := []Person{
|
||||
{Name: "Alice", Age: 30},
|
||||
{Name: "Bob", Age: 40},
|
||||
}
|
||||
expected := `[{"_":"logger.Person","Name":"Alice","Age":30},{"_":"logger.Person","Name":"Bob","Age":40}]`
|
||||
actual, err := Serialize(people)
|
||||
if err != nil {
|
||||
t.Errorf("Error: %v", err)
|
||||
}
|
||||
if actual != expected {
|
||||
t.Errorf("Expected: %v\nActual: %v", expected, actual)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSerializeSliceOfPointers(t *testing.T) {
|
||||
people := []*Person{
|
||||
{Name: "Alice", Age: 30},
|
||||
{Name: "Bob", Age: 40},
|
||||
}
|
||||
expected := `[{"_":"logger.Person","Name":"Alice","Age":30},{"_":"logger.Person","Name":"Bob","Age":40}]`
|
||||
|
||||
actual, err := Serialize(people)
|
||||
if err != nil {
|
||||
t.Errorf("Error: %v", err)
|
||||
}
|
||||
if actual != expected {
|
||||
t.Errorf("Expected: %v\nActual: %v", expected, actual)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSerializeUnsupportedType(t *testing.T) {
|
||||
type UnsupportedType chan int
|
||||
unsupportedType := make(UnsupportedType)
|
||||
_, err := Serialize(unsupportedType)
|
||||
if err == nil {
|
||||
t.Errorf("Expected an error, but got nil")
|
||||
}
|
||||
}
|
||||
@@ -1,64 +0,0 @@
|
||||
package ordered_map
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
|
||||
jsoniter "github.com/json-iterator/go"
|
||||
)
|
||||
|
||||
var json = jsoniter.ConfigCompatibleWithStandardLibrary
|
||||
|
||||
type OrderedMap struct {
|
||||
values map[string]interface{}
|
||||
keys []string
|
||||
}
|
||||
|
||||
func New() *OrderedMap {
|
||||
o := OrderedMap{}
|
||||
o.keys = []string{}
|
||||
o.values = map[string]interface{}{}
|
||||
return &o
|
||||
}
|
||||
|
||||
func (o *OrderedMap) Set(key string, value interface{}) {
|
||||
_, exists := o.values[key]
|
||||
if !exists {
|
||||
o.keys = append(o.keys, key)
|
||||
}
|
||||
o.values[key] = value
|
||||
}
|
||||
|
||||
func (o OrderedMap) MarshalJSON() ([]byte, error) {
|
||||
var buf bytes.Buffer
|
||||
buf.WriteByte('{')
|
||||
encoder := json.NewEncoder(&buf)
|
||||
encoder.SetEscapeHTML(false)
|
||||
encoder.SetIndent("", "")
|
||||
for i, k := range o.keys {
|
||||
if i > 0 {
|
||||
buf.WriteByte(',')
|
||||
}
|
||||
buf.WriteByte('"')
|
||||
buf.WriteString(k)
|
||||
buf.WriteString(`":`)
|
||||
customEncoder := &customJsonEncoder{buf: &buf}
|
||||
if err := customEncoder.Encode(o.values[k]); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
buf.WriteByte('}')
|
||||
return buf.Bytes(), nil
|
||||
}
|
||||
|
||||
type customJsonEncoder struct {
|
||||
buf *bytes.Buffer
|
||||
}
|
||||
|
||||
func (e *customJsonEncoder) Encode(v interface{}) error {
|
||||
data, err := json.Marshal(v)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
e.buf.Write(data)
|
||||
return nil
|
||||
}
|
||||
@@ -1,164 +0,0 @@
|
||||
package ordered_map
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestNew(t *testing.T) {
|
||||
tests := []struct {
|
||||
want *OrderedMap
|
||||
name string
|
||||
}{
|
||||
{
|
||||
name: "TestNew",
|
||||
want: &OrderedMap{
|
||||
keys: []string{},
|
||||
values: map[string]interface{}{},
|
||||
},
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if got := New(); !reflect.DeepEqual(got, tt.want) {
|
||||
t.Errorf("New() = %v, want %v", got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestOrderedMap_Set(t *testing.T) {
|
||||
type fields struct {
|
||||
values map[string]interface{}
|
||||
keys []string
|
||||
}
|
||||
type args struct {
|
||||
value interface{}
|
||||
key string
|
||||
}
|
||||
tests := []struct {
|
||||
args args
|
||||
name string
|
||||
fields fields
|
||||
}{
|
||||
{
|
||||
name: "TestOrderedMap_Set",
|
||||
fields: fields{
|
||||
values: map[string]interface{}{},
|
||||
keys: []string{},
|
||||
},
|
||||
args: args{},
|
||||
},
|
||||
{
|
||||
name: "TestOrderedMap_Set2",
|
||||
fields: fields{
|
||||
values: map[string]interface{}{
|
||||
"hello": "world",
|
||||
},
|
||||
keys: []string{"hello"},
|
||||
},
|
||||
args: args{},
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
o := &OrderedMap{
|
||||
values: tt.fields.values,
|
||||
keys: tt.fields.keys,
|
||||
}
|
||||
o.Set(tt.args.key, tt.args.value)
|
||||
for _, key := range o.keys {
|
||||
if _, ok := o.values[key]; !ok {
|
||||
t.Errorf("OrderedMap.Set() key not found in values map")
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestOrderedMap_MarshalJSON(t *testing.T) {
|
||||
type fields struct {
|
||||
values map[string]interface{}
|
||||
keys []string
|
||||
}
|
||||
tests := []struct {
|
||||
name string
|
||||
fields fields
|
||||
want []byte
|
||||
wantErr bool
|
||||
}{
|
||||
{
|
||||
name: "TestOrderedMap_MarshalJSON",
|
||||
fields: fields{
|
||||
values: map[string]interface{}{
|
||||
"hello": "world",
|
||||
},
|
||||
keys: []string{"hello"},
|
||||
},
|
||||
want: []byte(`{"hello":"world"}`),
|
||||
wantErr: false,
|
||||
},
|
||||
{
|
||||
name: "TestOrderedMap_MarshalJSON2",
|
||||
fields: fields{
|
||||
values: map[string]interface{}{
|
||||
"hello": "world",
|
||||
"foo": "bar",
|
||||
},
|
||||
keys: []string{"hello", "foo"},
|
||||
},
|
||||
want: []byte(`{"hello":"world","foo":"bar"}`),
|
||||
wantErr: false,
|
||||
},
|
||||
{
|
||||
name: "TestOrderedMap_MarshalJSON_with_error",
|
||||
fields: fields{
|
||||
values: map[string]interface{}{
|
||||
"hello": "world",
|
||||
"foo": make(chan int),
|
||||
},
|
||||
keys: []string{"hello", "foo"},
|
||||
},
|
||||
want: nil,
|
||||
wantErr: true,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
o := OrderedMap{
|
||||
values: tt.fields.values,
|
||||
keys: tt.fields.keys,
|
||||
}
|
||||
got, err := o.MarshalJSON()
|
||||
if (err != nil) != tt.wantErr {
|
||||
t.Errorf("OrderedMap.MarshalJSON() error = %v, wantErr %v", err, tt.wantErr)
|
||||
return
|
||||
}
|
||||
if !reflect.DeepEqual(got, tt.want) {
|
||||
t.Errorf("OrderedMap.MarshalJSON() = %v, want %v", got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkOrderedMapTest(b *testing.B) {
|
||||
m := New()
|
||||
for i := 0; i < b.N; i++ {
|
||||
m.Set("hello", "world")
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkOrderedMarshalJSON(b *testing.B) {
|
||||
m := New()
|
||||
for i := 0; i < b.N; i++ {
|
||||
m.Set("hello", "world")
|
||||
m.MarshalJSON()
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkMapTest(b *testing.B) {
|
||||
m := make(map[string]interface{})
|
||||
for i := 0; i < b.N; i++ {
|
||||
m["hello"] = "world"
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user