mirror of
https://github.com/lukaszraczylo/go-simple-graphql.git
synced 2026-10-13 00:48:37 +00:00
Compare commits
Vendored
+60
-33
@@ -3,6 +3,7 @@ package libpack_cache
|
|||||||
import (
|
import (
|
||||||
"bytes"
|
"bytes"
|
||||||
"compress/gzip"
|
"compress/gzip"
|
||||||
|
"hash/fnv"
|
||||||
"io"
|
"io"
|
||||||
"sync"
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
@@ -13,12 +14,25 @@ type CacheEntry struct {
|
|||||||
Value []byte
|
Value []byte
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const shardCount = 256 // Must be power of 2
|
||||||
|
|
||||||
|
type shard struct {
|
||||||
|
entries map[string]CacheEntry
|
||||||
|
sync.RWMutex
|
||||||
|
}
|
||||||
|
|
||||||
type Cache struct {
|
type Cache struct {
|
||||||
compressPool sync.Pool
|
compressPool sync.Pool
|
||||||
decompressPool sync.Pool
|
decompressPool sync.Pool
|
||||||
entries sync.Map
|
shards [shardCount]*shard
|
||||||
globalTTL time.Duration
|
globalTTL time.Duration
|
||||||
sync.RWMutex
|
}
|
||||||
|
|
||||||
|
// 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 {
|
func New(globalTTL time.Duration) *Cache {
|
||||||
@@ -32,13 +46,19 @@ func New(globalTTL time.Duration) *Cache {
|
|||||||
},
|
},
|
||||||
decompressPool: sync.Pool{
|
decompressPool: sync.Pool{
|
||||||
New: func() interface{} {
|
New: func() interface{} {
|
||||||
// Ensure that new is returning a new reader initialized with an empty byte buffer
|
|
||||||
r, _ := gzip.NewReader(bytes.NewReader([]byte{}))
|
r, _ := gzip.NewReader(bytes.NewReader([]byte{}))
|
||||||
return r
|
return r
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Initialize shards
|
||||||
|
for i := 0; i < shardCount; i++ {
|
||||||
|
cache.shards[i] = &shard{
|
||||||
|
entries: make(map[string]CacheEntry),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
go cache.cleanupRoutine(globalTTL)
|
go cache.cleanupRoutine(globalTTL)
|
||||||
return cache
|
return cache
|
||||||
}
|
}
|
||||||
@@ -52,33 +72,43 @@ func (c *Cache) cleanupRoutine(globalTTL time.Duration) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
func (c *Cache) Set(key string, value []byte, ttl time.Duration) {
|
func (c *Cache) Set(key string, value []byte, ttl time.Duration) {
|
||||||
c.Lock() // use the lock
|
shard := c.getShard(key)
|
||||||
defer c.Unlock()
|
shard.Lock()
|
||||||
|
defer shard.Unlock()
|
||||||
expiresAt := time.Now().Add(ttl)
|
|
||||||
|
|
||||||
compressedValue, err := c.compress(value)
|
compressedValue, err := c.compress(value)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
entry := CacheEntry{
|
shard.entries[key] = CacheEntry{
|
||||||
Value: compressedValue,
|
Value: compressedValue,
|
||||||
ExpiresAt: expiresAt,
|
ExpiresAt: time.Now().Add(ttl),
|
||||||
}
|
}
|
||||||
c.entries.Store(key, entry)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *Cache) Get(key string) ([]byte, bool) {
|
func (c *Cache) Get(key string) ([]byte, bool) {
|
||||||
c.RLock() // use the read lock
|
shard := c.getShard(key)
|
||||||
defer c.RUnlock()
|
shard.RLock()
|
||||||
|
entry, ok := shard.entries[key]
|
||||||
entry, ok := c.entries.Load(key)
|
if !ok {
|
||||||
if !ok || entry.(CacheEntry).ExpiresAt.Before(time.Now()) {
|
shard.RUnlock()
|
||||||
return nil, false
|
return nil, false
|
||||||
}
|
}
|
||||||
compressedValue := entry.(CacheEntry).Value
|
|
||||||
value, err := c.decompress(compressedValue)
|
if entry.ExpiresAt.Before(time.Now()) {
|
||||||
|
shard.RUnlock()
|
||||||
|
// Clean up expired entry in background
|
||||||
|
go func() {
|
||||||
|
shard.Lock()
|
||||||
|
delete(shard.entries, key)
|
||||||
|
shard.Unlock()
|
||||||
|
}()
|
||||||
|
return nil, false
|
||||||
|
}
|
||||||
|
shard.RUnlock()
|
||||||
|
|
||||||
|
value, err := c.decompress(entry.Value)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, false
|
return nil, false
|
||||||
}
|
}
|
||||||
@@ -87,26 +117,23 @@ func (c *Cache) Get(key string) ([]byte, bool) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (c *Cache) Delete(key string) {
|
func (c *Cache) Delete(key string) {
|
||||||
c.Lock()
|
shard := c.getShard(key)
|
||||||
defer c.Unlock()
|
shard.Lock()
|
||||||
|
delete(shard.entries, key)
|
||||||
_, ok := c.entries.Load(key)
|
shard.Unlock()
|
||||||
if !ok {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
c.entries.Delete(key)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *Cache) CleanExpiredEntries() {
|
func (c *Cache) CleanExpiredEntries() {
|
||||||
now := time.Now()
|
now := time.Now()
|
||||||
c.entries.Range(func(key, value interface{}) bool {
|
for _, shard := range c.shards {
|
||||||
entry := value.(CacheEntry)
|
shard.Lock()
|
||||||
if entry.ExpiresAt.Before(now) {
|
for key, entry := range shard.entries {
|
||||||
c.entries.Delete(key)
|
if entry.ExpiresAt.Before(now) {
|
||||||
|
delete(shard.entries, key)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return true
|
shard.Unlock()
|
||||||
})
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *Cache) compress(data []byte) ([]byte, error) {
|
func (c *Cache) compress(data []byte) ([]byte, error) {
|
||||||
|
|||||||
+52
-54
@@ -7,7 +7,6 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
"net/http"
|
"net/http"
|
||||||
"sync"
|
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/avast/retry-go/v4"
|
"github.com/avast/retry-go/v4"
|
||||||
@@ -15,11 +14,22 @@ import (
|
|||||||
libpack_logger "github.com/lukaszraczylo/go-simple-graphql/logging"
|
libpack_logger "github.com/lukaszraczylo/go-simple-graphql/logging"
|
||||||
)
|
)
|
||||||
|
|
||||||
var bufferPool = sync.Pool{
|
var (
|
||||||
New: func() interface{} {
|
// Shared HTTP transport with optimized settings
|
||||||
return new(bytes.Buffer)
|
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) {
|
func (qe *QueryExecutor) executeQuery() ([]byte, error) {
|
||||||
// Reuse buffer from pool to avoid allocations
|
// Reuse buffer from pool to avoid allocations
|
||||||
@@ -27,16 +37,9 @@ func (qe *QueryExecutor) executeQuery() ([]byte, error) {
|
|||||||
defer bufferPool.Put(buf)
|
defer bufferPool.Put(buf)
|
||||||
buf.Reset()
|
buf.Reset()
|
||||||
|
|
||||||
_, err := buf.Write(qe.Query)
|
buf.Write(qe.Query)
|
||||||
if err != nil {
|
|
||||||
qe.Logger.Error(&libpack_logger.LogMessage{
|
|
||||||
Message: "Can't write to buffer",
|
|
||||||
Pairs: map[string]interface{}{"error": err.Error()},
|
|
||||||
})
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
httpRequest, err := http.NewRequest(http.MethodPost, qe.endpoint, buf)
|
httpRequest, err := http.NewRequest(http.MethodPost, qe.endpoint, nil)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
qe.Logger.Error(&libpack_logger.LogMessage{
|
qe.Logger.Error(&libpack_logger.LogMessage{
|
||||||
Message: "Can't create HTTP request",
|
Message: "Can't create HTTP request",
|
||||||
@@ -48,78 +51,71 @@ func (qe *QueryExecutor) executeQuery() ([]byte, error) {
|
|||||||
for key, value := range qe.Headers {
|
for key, value := range qe.Headers {
|
||||||
httpRequest.Header.Set(key, fmt.Sprint(value))
|
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
|
retriesMax := 1
|
||||||
if qe.Retries {
|
if qe.Retries {
|
||||||
qe.Logger.Debug(&libpack_logger.LogMessage{
|
|
||||||
Message: "Retries enabled",
|
|
||||||
Pairs: map[string]interface{}{"retries": qe.retries_number},
|
|
||||||
})
|
|
||||||
retriesMax = qe.retries_number
|
retriesMax = qe.retries_number
|
||||||
} else {
|
|
||||||
qe.Logger.Debug(&libpack_logger.LogMessage{
|
|
||||||
Message: "Retries disabled",
|
|
||||||
Pairs: map[string]interface{}{"retries": 1},
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
var queryResult queryResults
|
var queryResult queryResults
|
||||||
err = retry.Do(
|
err = retry.Do(
|
||||||
func() error {
|
func() error {
|
||||||
httpResponse, err := qe.client.Do(httpRequest)
|
// Reset buffer before each retry
|
||||||
|
buf.Reset()
|
||||||
|
buf.Write(qe.Query)
|
||||||
|
|
||||||
|
// Set the body of the request
|
||||||
|
httpRequest.Body = io.NopCloser(bytes.NewReader(buf.Bytes()))
|
||||||
|
httpRequest.ContentLength = int64(buf.Len())
|
||||||
|
|
||||||
|
// Use default client if custom client is not set
|
||||||
|
client := qe.client
|
||||||
|
if client == nil {
|
||||||
|
client = defaultClient
|
||||||
|
}
|
||||||
|
httpResponse, err := client.Do(httpRequest)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
qe.Logger.Debug(&libpack_logger.LogMessage{
|
|
||||||
Message: "Error executing HTTP request",
|
|
||||||
Pairs: map[string]interface{}{"error": err.Error()},
|
|
||||||
})
|
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
defer func() {
|
defer func() {
|
||||||
_, err := io.Copy(io.Discard, httpResponse.Body)
|
io.Copy(io.Discard, httpResponse.Body)
|
||||||
if err != nil {
|
|
||||||
qe.Logger.Debug(&libpack_logger.LogMessage{
|
|
||||||
Message: "Error discarding HTTP response body",
|
|
||||||
Pairs: map[string]interface{}{"error": err.Error()},
|
|
||||||
})
|
|
||||||
}
|
|
||||||
httpResponse.Body.Close()
|
httpResponse.Body.Close()
|
||||||
}()
|
}()
|
||||||
|
|
||||||
if httpResponse.StatusCode < http.StatusOK || httpResponse.StatusCode >= http.StatusNoContent {
|
if httpResponse.StatusCode < http.StatusOK || httpResponse.StatusCode >= http.StatusMultipleChoices {
|
||||||
return fmt.Errorf("HTTP error - status code: %s for %s", httpResponse.Status, httpRequest.URL)
|
return fmt.Errorf("HTTP error - status code: %s for %s", httpResponse.Status, httpRequest.URL)
|
||||||
}
|
}
|
||||||
|
|
||||||
var reader io.ReadCloser
|
var reader io.Reader
|
||||||
encoding := httpResponse.Header.Get("Content-Encoding")
|
encoding := httpResponse.Header.Get("Content-Encoding")
|
||||||
if encoding == "gzip" {
|
if encoding == "gzip" {
|
||||||
reader, err = gzip.NewReader(httpResponse.Body)
|
gzipReader, err := gzip.NewReader(httpResponse.Body)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
qe.Logger.Debug(&libpack_logger.LogMessage{
|
|
||||||
Message: "Error creating gzip reader",
|
|
||||||
Pairs: map[string]interface{}{"error": err.Error()},
|
|
||||||
})
|
|
||||||
return fmt.Errorf("error creating gzip reader: %w", err)
|
return fmt.Errorf("error creating gzip reader: %w", err)
|
||||||
}
|
}
|
||||||
defer reader.Close()
|
defer gzipReader.Close()
|
||||||
|
reader = gzipReader
|
||||||
} else {
|
} else {
|
||||||
reader = httpResponse.Body
|
reader = httpResponse.Body
|
||||||
}
|
}
|
||||||
|
|
||||||
body, err := io.ReadAll(reader)
|
// Use buffer pool for reading response
|
||||||
|
respBuf := bufferPool.Get().(*bytes.Buffer)
|
||||||
|
respBuf.Reset()
|
||||||
|
defer bufferPool.Put(respBuf)
|
||||||
|
|
||||||
|
_, err = io.Copy(respBuf, reader)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
qe.Logger.Debug(&libpack_logger.LogMessage{
|
|
||||||
Message: "Error reading HTTP response",
|
|
||||||
Pairs: map[string]interface{}{"error": err.Error()},
|
|
||||||
})
|
|
||||||
return fmt.Errorf("error reading HTTP response: %w", err)
|
return fmt.Errorf("error reading HTTP response: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
err = json.Unmarshal(body, &queryResult)
|
// Unmarshal response directly from buffer
|
||||||
|
err = json.Unmarshal(respBuf.Bytes(), &queryResult)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
qe.Logger.Debug(&libpack_logger.LogMessage{
|
|
||||||
Message: "Error unmarshalling HTTP response",
|
|
||||||
Pairs: map[string]interface{}{"error": err.Error()},
|
|
||||||
})
|
|
||||||
return fmt.Errorf("error unmarshalling HTTP response: %w", err)
|
return fmt.Errorf("error unmarshalling HTTP response: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -134,6 +130,7 @@ func (qe *QueryExecutor) executeQuery() ([]byte, error) {
|
|||||||
retry.Attempts(uint(retriesMax)),
|
retry.Attempts(uint(retriesMax)),
|
||||||
retry.DelayType(retry.BackOffDelay),
|
retry.DelayType(retry.BackOffDelay),
|
||||||
retry.Delay(time.Duration(qe.retries_delay)),
|
retry.Delay(time.Duration(qe.retries_delay)),
|
||||||
|
retry.MaxDelay(10 * time.Second),
|
||||||
retry.LastErrorOnly(true),
|
retry.LastErrorOnly(true),
|
||||||
)
|
)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -160,6 +157,7 @@ func (qe *QueryExecutor) executeQuery() ([]byte, error) {
|
|||||||
return nil, errors.New("error executing query: no data")
|
return nil, errors.New("error executing query: no data")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Marshal queryResult.Data
|
||||||
jsonData, err := json.Marshal(queryResult.Data)
|
jsonData, err := json.Marshal(queryResult.Data)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
qe.Logger.Debug(&libpack_logger.LogMessage{
|
qe.Logger.Debug(&libpack_logger.LogMessage{
|
||||||
|
|||||||
@@ -4,10 +4,11 @@ go 1.21
|
|||||||
|
|
||||||
require (
|
require (
|
||||||
github.com/avast/retry-go/v4 v4.6.0
|
github.com/avast/retry-go/v4 v4.6.0
|
||||||
github.com/goccy/go-json v0.10.3
|
github.com/goccy/go-json v0.10.5
|
||||||
github.com/gookit/goutil v0.6.16
|
github.com/goccy/go-reflect v1.2.0
|
||||||
|
github.com/gookit/goutil v0.6.18
|
||||||
github.com/stretchr/testify v1.9.0
|
github.com/stretchr/testify v1.9.0
|
||||||
golang.org/x/net v0.29.0
|
golang.org/x/net v0.34.0
|
||||||
)
|
)
|
||||||
|
|
||||||
require (
|
require (
|
||||||
@@ -15,9 +16,9 @@ require (
|
|||||||
github.com/gookit/color v1.5.4 // indirect
|
github.com/gookit/color v1.5.4 // indirect
|
||||||
github.com/pmezard/go-difflib v1.0.0 // indirect
|
github.com/pmezard/go-difflib v1.0.0 // indirect
|
||||||
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect
|
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect
|
||||||
golang.org/x/sync v0.8.0 // indirect
|
golang.org/x/sync v0.10.0 // indirect
|
||||||
golang.org/x/sys v0.25.0 // indirect
|
golang.org/x/sys v0.29.0 // indirect
|
||||||
golang.org/x/term v0.24.0 // indirect
|
golang.org/x/term v0.28.0 // indirect
|
||||||
golang.org/x/text v0.18.0 // indirect
|
golang.org/x/text v0.21.0 // indirect
|
||||||
gopkg.in/yaml.v3 v3.0.1 // indirect
|
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -2,12 +2,14 @@ github.com/avast/retry-go/v4 v4.6.0 h1:K9xNA+KeB8HHc2aWFuLb25Offp+0iVRXEvFx8IinR
|
|||||||
github.com/avast/retry-go/v4 v4.6.0/go.mod h1:gvWlPhBVsvBbLkVGDg/KwvBv0bEkCOLRRSHKIr2PyOE=
|
github.com/avast/retry-go/v4 v4.6.0/go.mod h1:gvWlPhBVsvBbLkVGDg/KwvBv0bEkCOLRRSHKIr2PyOE=
|
||||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
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/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||||
github.com/goccy/go-json v0.10.3 h1:KZ5WoDbxAIgm2HNbYckL0se1fHD6rz5j4ywS6ebzDqA=
|
github.com/goccy/go-json v0.10.5 h1:Fq85nIqj+gXn/S5ahsiTlK3TmC85qgirsdTP/+DeaC4=
|
||||||
github.com/goccy/go-json v0.10.3/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M=
|
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 h1:FZmqs7XOyGgCAxmWyPslpiok1k05wmY3SJTytgvYFs0=
|
||||||
github.com/gookit/color v1.5.4/go.mod h1:pZJOeOS8DM43rXbp4AZo1n9zCU2qjpcRko0b6/QJi9w=
|
github.com/gookit/color v1.5.4/go.mod h1:pZJOeOS8DM43rXbp4AZo1n9zCU2qjpcRko0b6/QJi9w=
|
||||||
github.com/gookit/goutil v0.6.16 h1:9fRMCF4X9abdRD5+2HhBS/GwafjBlTUBjRtA5dgkvuw=
|
github.com/gookit/goutil v0.6.18 h1:MUVj0G16flubWT8zYVicIuisUiHdgirPAkmnfD2kKgw=
|
||||||
github.com/gookit/goutil v0.6.16/go.mod h1:op2q8AoPDFSiY2+qkHxcBWQMYxOLQ1GbLXqe7vrwscI=
|
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 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||||
github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
|
github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
|
||||||
@@ -16,16 +18,16 @@ github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e h1:JVG44RsyaB9T2KIHavM
|
|||||||
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e/go.mod h1:RbqR21r5mrJuqunuUZ/Dhy/avygyECGrLceyNeo4LiM=
|
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e/go.mod h1:RbqR21r5mrJuqunuUZ/Dhy/avygyECGrLceyNeo4LiM=
|
||||||
golang.org/x/exp v0.0.0-20220909182711-5c715a9e8561 h1:MDc5xs78ZrZr3HMQugiXOAkSZtfTpbJLDr/lwfgO53E=
|
golang.org/x/exp v0.0.0-20220909182711-5c715a9e8561 h1:MDc5xs78ZrZr3HMQugiXOAkSZtfTpbJLDr/lwfgO53E=
|
||||||
golang.org/x/exp v0.0.0-20220909182711-5c715a9e8561/go.mod h1:cyybsKvd6eL0RnXn6p/Grxp8F5bW7iYuBgsNCOHpMYE=
|
golang.org/x/exp v0.0.0-20220909182711-5c715a9e8561/go.mod h1:cyybsKvd6eL0RnXn6p/Grxp8F5bW7iYuBgsNCOHpMYE=
|
||||||
golang.org/x/net v0.29.0 h1:5ORfpBpCs4HzDYoodCDBbwHzdR5UrLBZ3sOnUJmFoHo=
|
golang.org/x/net v0.34.0 h1:Mb7Mrk043xzHgnRM88suvJFwzVrRfHEHJEl5/71CKw0=
|
||||||
golang.org/x/net v0.29.0/go.mod h1:gLkgy8jTGERgjzMic6DS9+SP0ajcu6Xu3Orq/SpETg0=
|
golang.org/x/net v0.34.0/go.mod h1:di0qlW3YNM5oh6GqDGQr92MyTozJPmybPK4Ev/Gm31k=
|
||||||
golang.org/x/sync v0.8.0 h1:3NFvSEYkUoMifnESzZl15y791HH1qU2xm6eCJU5ZPXQ=
|
golang.org/x/sync v0.10.0 h1:3NQrjDixjgGwUOCaF8w2+VYHv0Ve/vGYSbdkTa98gmQ=
|
||||||
golang.org/x/sync v0.8.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
|
golang.org/x/sync v0.10.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
|
||||||
golang.org/x/sys v0.25.0 h1:r+8e+loiHxRqhXVl6ML1nO3l1+oFoWbnlu2Ehimmi34=
|
golang.org/x/sys v0.29.0 h1:TPYlXGxvx1MGTn2GiZDhnjPA9wZzZeGKHHmKhHYvgaU=
|
||||||
golang.org/x/sys v0.25.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
golang.org/x/sys v0.29.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||||
golang.org/x/term v0.24.0 h1:Mh5cbb+Zk2hqqXNO7S1iTjEphVL+jb8ZWaqh/g+JWkM=
|
golang.org/x/term v0.28.0 h1:/Ts8HFuMR2E6IP/jlo7QVLZHggjKQbhu/7H0LJFr3Gg=
|
||||||
golang.org/x/term v0.24.0/go.mod h1:lOBK/LVxemqiMij05LGJ0tzNr8xlmwBRJ81PX6wVLH8=
|
golang.org/x/term v0.28.0/go.mod h1:Sw/lC2IAUZ92udQNf3WodGtn4k/XoLyZoh8v/8uiwek=
|
||||||
golang.org/x/text v0.18.0 h1:XvMDiNzPAl0jr17s6W9lcaIhGUfUORdGCNsuLmPG224=
|
golang.org/x/text v0.21.0 h1:zyQAAkrwaneQ066sspRyJaG9VNi/YJ1NfzcGB3hZ/qo=
|
||||||
golang.org/x/text v0.18.0/go.mod h1:BuEKDfySbSR4drPmRPG/7iBdf8hvFMuRexcpahXilzY=
|
golang.org/x/text v0.21.0/go.mod h1:4IBbMaMmOPCJ8SecivzSH54+73PCFmPWxNTLm+vZkEQ=
|
||||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
|
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 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||||
|
|||||||
+2
-2
@@ -9,7 +9,7 @@ import (
|
|||||||
libpack_logger "github.com/lukaszraczylo/go-simple-graphql/logging"
|
libpack_logger "github.com/lukaszraczylo/go-simple-graphql/logging"
|
||||||
)
|
)
|
||||||
|
|
||||||
func searchForKeysInMapStringInterface(msi map[string]interface{}, key string) (value any) {
|
func searchForKeysInMapStringInterface(msi map[string]interface{}, key string) interface{} {
|
||||||
if msi == nil {
|
if msi == nil {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
@@ -17,7 +17,7 @@ func searchForKeysInMapStringInterface(msi map[string]interface{}, key string) (
|
|||||||
}
|
}
|
||||||
|
|
||||||
func calculateHash(query *Query) string {
|
func calculateHash(query *Query) string {
|
||||||
hash := md5.Sum([]byte(query.JsonQuery))
|
hash := md5.Sum(query.JsonQuery)
|
||||||
return hex.EncodeToString(hash[:])
|
return hex.EncodeToString(hash[:])
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+2
-1
@@ -1,8 +1,9 @@
|
|||||||
package gql
|
package gql
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"reflect"
|
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
|
"github.com/goccy/go-reflect"
|
||||||
)
|
)
|
||||||
|
|
||||||
func (suite *Tests) Test_searchForKeysInMapStringInterface() {
|
func (suite *Tests) Test_searchForKeysInMapStringInterface() {
|
||||||
|
|||||||
@@ -4,11 +4,11 @@ import (
|
|||||||
"bytes"
|
"bytes"
|
||||||
"fmt"
|
"fmt"
|
||||||
"os"
|
"os"
|
||||||
"reflect"
|
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/goccy/go-json"
|
"github.com/goccy/go-json"
|
||||||
|
"github.com/goccy/go-reflect"
|
||||||
)
|
)
|
||||||
|
|
||||||
func captureStderr(f func()) string {
|
func captureStderr(f func()) string {
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
package gql
|
package gql
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"net/http"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/gookit/goutil/envutil"
|
"github.com/gookit/goutil/envutil"
|
||||||
@@ -38,3 +39,7 @@ func (b *BaseClient) SetOutput(responseType string) {
|
|||||||
// TODO: implement
|
// TODO: implement
|
||||||
b.responseType = responseType
|
b.responseType = responseType
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (b *BaseClient) SetHTTPClient(client *http.Client) {
|
||||||
|
b.client = client
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,67 @@
|
|||||||
|
// mock_server.go
|
||||||
|
package gql
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"io/ioutil"
|
||||||
|
"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 := ioutil.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,8 +1,8 @@
|
|||||||
package gql
|
package gql
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"bytes"
|
||||||
"fmt"
|
"fmt"
|
||||||
"sync"
|
|
||||||
|
|
||||||
"github.com/goccy/go-json"
|
"github.com/goccy/go-json"
|
||||||
"github.com/gookit/goutil"
|
"github.com/gookit/goutil"
|
||||||
@@ -10,55 +10,74 @@ import (
|
|||||||
libpack_logger "github.com/lukaszraczylo/go-simple-graphql/logging"
|
libpack_logger "github.com/lukaszraczylo/go-simple-graphql/logging"
|
||||||
)
|
)
|
||||||
|
|
||||||
var jsonBufferPool = sync.Pool{
|
|
||||||
New: func() interface{} {
|
|
||||||
return new([]byte)
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
func (b *BaseClient) convertToJSON(v any) []byte {
|
func (b *BaseClient) convertToJSON(v any) []byte {
|
||||||
jsonBuffer := jsonBufferPool.Get().(*[]byte)
|
buf := bufferPool.Get().(*bytes.Buffer)
|
||||||
defer jsonBufferPool.Put(jsonBuffer)
|
defer bufferPool.Put(buf)
|
||||||
|
buf.Reset()
|
||||||
|
|
||||||
*jsonBuffer = (*jsonBuffer)[:0]
|
// Use json.NewEncoder for better performance with buffers
|
||||||
jsonData, err := json.Marshal(v)
|
enc := json.NewEncoder(buf)
|
||||||
if err != nil {
|
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{
|
b.Logger.Error(&libpack_logger.LogMessage{
|
||||||
Message: "Can't convert to JSON",
|
Message: "Can't convert to JSON",
|
||||||
Pairs: map[string]interface{}{"error": err.Error()},
|
Pairs: errPairs,
|
||||||
})
|
})
|
||||||
|
errPairsPool.Put(errPairs)
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
*jsonBuffer = append(*jsonBuffer, jsonData...)
|
|
||||||
return *jsonBuffer
|
// Get the buffer bytes directly, trimming the trailing newline
|
||||||
|
bytes := buf.Bytes()
|
||||||
|
if len(bytes) > 0 && bytes[len(bytes)-1] == '\n' {
|
||||||
|
bytes = bytes[:len(bytes)-1]
|
||||||
|
}
|
||||||
|
|
||||||
|
// Make a copy of the bytes since the buffer will be reused
|
||||||
|
result := make([]byte, len(bytes))
|
||||||
|
copy(result, bytes)
|
||||||
|
return result
|
||||||
}
|
}
|
||||||
|
|
||||||
func (b *BaseClient) compileQuery(queryPartials ...any) *Query {
|
func (b *BaseClient) compileQuery(queryPartials ...any) *Query {
|
||||||
var query string
|
var query string
|
||||||
var variables map[string]interface{}
|
var variables map[string]interface{}
|
||||||
for _, partial := range queryPartials {
|
|
||||||
switch val := partial.(type) {
|
// Pre-allocate the query with an estimated size
|
||||||
case string:
|
if len(queryPartials) > 0 {
|
||||||
query = val
|
if str, ok := queryPartials[0].(string); ok {
|
||||||
case map[string]interface{}:
|
query = str
|
||||||
variables = val
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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 == "" {
|
if query == "" {
|
||||||
|
errPairs := errPairsPool.Get().(map[string]interface{})
|
||||||
|
errPairs["error"] = "query is empty"
|
||||||
b.Logger.Error(&libpack_logger.LogMessage{
|
b.Logger.Error(&libpack_logger.LogMessage{
|
||||||
Message: "Can't compile query",
|
Message: "Can't compile query",
|
||||||
Pairs: map[string]interface{}{"error": "query is empty"},
|
Pairs: errPairs,
|
||||||
})
|
})
|
||||||
|
errPairsPool.Put(errPairs)
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
jsonQuery := b.convertToJSON(&Query{Query: query, Variables: variables})
|
// Construct query object once
|
||||||
return &Query{
|
q := &Query{
|
||||||
Query: query,
|
Query: query,
|
||||||
Variables: variables,
|
Variables: variables,
|
||||||
JsonQuery: jsonQuery,
|
|
||||||
}
|
}
|
||||||
|
q.JsonQuery = b.convertToJSON(q)
|
||||||
|
return q
|
||||||
}
|
}
|
||||||
|
|
||||||
func (b *BaseClient) Query(query string, variables map[string]interface{}, headers map[string]interface{}) (any, error) {
|
func (b *BaseClient) Query(query string, variables map[string]interface{}, headers map[string]interface{}) (any, error) {
|
||||||
@@ -92,7 +111,7 @@ func (b *BaseClient) Query(query string, variables map[string]interface{}, heade
|
|||||||
Message: "Cache hit",
|
Message: "Cache hit",
|
||||||
Pairs: map[string]interface{}{"query": compiledQuery},
|
Pairs: map[string]interface{}{"query": compiledQuery},
|
||||||
})
|
})
|
||||||
return cachedValue, nil
|
return b.decodeResponse(cachedValue)
|
||||||
}
|
}
|
||||||
b.Logger.Debug(&libpack_logger.LogMessage{
|
b.Logger.Debug(&libpack_logger.LogMessage{
|
||||||
Message: "Cache miss",
|
Message: "Cache miss",
|
||||||
@@ -100,13 +119,6 @@ func (b *BaseClient) Query(query string, variables map[string]interface{}, heade
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
if enableRetries || b.retries_enable {
|
|
||||||
b.Logger.Debug(&libpack_logger.LogMessage{
|
|
||||||
Message: "Retries enabled",
|
|
||||||
Pairs: nil,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
q := &QueryExecutor{
|
q := &QueryExecutor{
|
||||||
BaseClient: b,
|
BaseClient: b,
|
||||||
Query: compiledQuery.JsonQuery,
|
Query: compiledQuery.JsonQuery,
|
||||||
@@ -129,7 +141,7 @@ func (b *BaseClient) Query(query string, variables map[string]interface{}, heade
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
return q.decodeResponse(rv)
|
return b.decodeResponse(rv)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (q *Query) parseHeadersAndVariables(headers map[string]interface{}) (enableCache, enableRetries, recompileRequired bool) {
|
func (q *Query) parseHeadersAndVariables(headers map[string]interface{}) (enableCache, enableRetries, recompileRequired bool) {
|
||||||
|
|||||||
+19
-2
@@ -36,10 +36,15 @@ func Benchmark_convertToJson(bn *testing.B) {
|
|||||||
b.convertToJSON(query)
|
b.convertToJSON(query)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func Benchmark_Query(bn *testing.B) {
|
func Benchmark_Query(bn *testing.B) {
|
||||||
|
mockServer := StartMockServer()
|
||||||
|
bn.Cleanup(func() {
|
||||||
|
mockServer.Close()
|
||||||
|
})
|
||||||
|
|
||||||
b := NewConnection()
|
b := NewConnection()
|
||||||
query := `query { viewer { login } }`
|
b.SetEndpoint(mockServer.URL)
|
||||||
|
query := "query { viewer { login } }"
|
||||||
variables := map[string]interface{}{
|
variables := map[string]interface{}{
|
||||||
"var1": "value1",
|
"var1": "value1",
|
||||||
}
|
}
|
||||||
@@ -54,7 +59,13 @@ func Benchmark_Query(bn *testing.B) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func Benchmark_QueryNoCacheNoRetry(bn *testing.B) {
|
func Benchmark_QueryNoCacheNoRetry(bn *testing.B) {
|
||||||
|
mockServer := StartMockServer()
|
||||||
|
bn.Cleanup(func() {
|
||||||
|
mockServer.Close()
|
||||||
|
})
|
||||||
|
|
||||||
b := NewConnection()
|
b := NewConnection()
|
||||||
|
b.SetEndpoint(mockServer.URL)
|
||||||
query := `query { viewer { login } }`
|
query := `query { viewer { login } }`
|
||||||
variables := map[string]interface{}{
|
variables := map[string]interface{}{
|
||||||
"var1": "value1",
|
"var1": "value1",
|
||||||
@@ -69,7 +80,13 @@ func Benchmark_QueryNoCacheNoRetry(bn *testing.B) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func Benchmark_QueryWithEmptyVariables(bn *testing.B) {
|
func Benchmark_QueryWithEmptyVariables(bn *testing.B) {
|
||||||
|
mockServer := StartMockServer()
|
||||||
|
bn.Cleanup(func() {
|
||||||
|
mockServer.Close()
|
||||||
|
})
|
||||||
|
|
||||||
b := NewConnection()
|
b := NewConnection()
|
||||||
|
b.SetEndpoint(mockServer.URL)
|
||||||
query := `query { viewer { login } }`
|
query := `query { viewer { login } }`
|
||||||
headers := map[string]interface{}{
|
headers := map[string]interface{}{
|
||||||
"Authorization": "Bearer token",
|
"Authorization": "Bearer token",
|
||||||
|
|||||||
+22
-156
@@ -1,8 +1,9 @@
|
|||||||
package gql
|
package gql
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"reflect"
|
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
|
"github.com/goccy/go-reflect"
|
||||||
)
|
)
|
||||||
|
|
||||||
func (suite *Tests) TestBaseClient_convertToJSON() {
|
func (suite *Tests) TestBaseClient_convertToJSON() {
|
||||||
@@ -115,182 +116,48 @@ func (suite *Tests) TestBaseClient_Query() {
|
|||||||
args args
|
args args
|
||||||
wantReturned_value any
|
wantReturned_value any
|
||||||
name string
|
name string
|
||||||
graphQLServer string
|
|
||||||
wantType string
|
wantType string
|
||||||
wantErr bool
|
wantErr bool
|
||||||
}{
|
}{
|
||||||
{
|
{
|
||||||
name: "TestBaseClient_Query_spacex_working",
|
name: "TestBaseClient_Query_viewer",
|
||||||
graphQLServer: "https://spacex-production.up.railway.app/",
|
|
||||||
args: args{
|
args: args{
|
||||||
query: `query Dragons {
|
query: "query { viewer { login } }",
|
||||||
dragons {
|
|
||||||
name
|
|
||||||
}
|
|
||||||
}`,
|
|
||||||
variables: nil,
|
variables: nil,
|
||||||
headers: map[string]interface{}{
|
headers: map[string]interface{}{
|
||||||
"x-apollo-operation-name": "Dragons/github.com/lukaszraczylo/go-simple-graphql",
|
"x-apollo-operation-name": "ViewerQuery",
|
||||||
"content-type": "application/json",
|
"content-type": "application/json",
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
wantReturned_value: string(`{"dragons":[{"name":"Dragon 1"},{"name":"Dragon 2"}]}`),
|
wantReturned_value: `{"viewer":{"login":"mockuser"}}`, // Adjusted expected value
|
||||||
wantErr: false,
|
wantErr: false,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "TestBaseClient_Query_spacex_invalid_query",
|
name: "TestBaseClient_Query_dragons",
|
||||||
graphQLServer: "https://spacex-production.up.railway.app/",
|
|
||||||
args: args{
|
args: args{
|
||||||
query: `query Dragons {
|
query: `query Dragons {
|
||||||
dragons {
|
dragons {
|
||||||
name
|
name
|
||||||
}
|
}
|
||||||
`,
|
}`,
|
||||||
variables: nil,
|
variables: nil,
|
||||||
headers: map[string]interface{}{
|
headers: map[string]interface{}{
|
||||||
"x-apollo-operation-name": "Dragons/github.com/lukaszraczylo/go-simple-graphql",
|
"x-apollo-operation-name": "DragonsQuery",
|
||||||
"content-type": "application/json",
|
"content-type": "application/json",
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
wantReturned_value: nil,
|
wantReturned_value: `{"dragons":[{"name":"Mock Dragon 1"},{"name":"Mock Dragon 2"}]}`, // Adjusted expected value
|
||||||
wantErr: true,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "TestBaseClient_Query_tgbotapp_working",
|
|
||||||
graphQLServer: "https://telegram-bot.app/v1/graphql",
|
|
||||||
args: args{
|
|
||||||
query: `query {
|
|
||||||
__type(name: "Query") {
|
|
||||||
name
|
|
||||||
}
|
|
||||||
}`,
|
|
||||||
},
|
|
||||||
wantReturned_value: string(`{"__type":null}`),
|
|
||||||
wantErr: false,
|
wantErr: false,
|
||||||
},
|
},
|
||||||
|
|
||||||
{
|
{
|
||||||
name: "TestBaseClient_Query_tgbotapp_invalid_query",
|
name: "TestBaseClient_Query_invalid_query",
|
||||||
graphQLServer: "https://telegram-bot.app/v1/graphql",
|
|
||||||
args: args{
|
args: args{
|
||||||
query: `query {
|
query: "query { potato { login } ",
|
||||||
__type(name: "Query") {
|
variables: nil,
|
||||||
name
|
headers: map[string]interface{}{
|
||||||
}
|
"x-apollo-operation-name": "InvalidQuery",
|
||||||
`,
|
"content-type": "application/json",
|
||||||
},
|
|
||||||
wantReturned_value: nil,
|
|
||||||
wantErr: true,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "TestBaseClient_Query_tgbotapp_invalid_wrong_field",
|
|
||||||
graphQLServer: "https://telegram-bot.app/v1/graphql",
|
|
||||||
args: args{
|
|
||||||
query: `query {
|
|
||||||
__type(name: "Query") {
|
|
||||||
name2
|
|
||||||
}
|
|
||||||
}`,
|
|
||||||
},
|
|
||||||
wantReturned_value: nil,
|
|
||||||
wantErr: true,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "TestBaseClient_Query_tgbotapp_wrong_url",
|
|
||||||
graphQLServer: "https://telegram-bot.app/v0/graphql",
|
|
||||||
args: args{
|
|
||||||
query: `query {
|
|
||||||
__type(name: "Query") {
|
|
||||||
name
|
|
||||||
}
|
|
||||||
}`,
|
|
||||||
},
|
|
||||||
wantReturned_value: nil,
|
|
||||||
wantErr: true,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "TestBaseClient_Query_tgbotapp_valid_query_mapstring",
|
|
||||||
graphQLServer: "https://telegram-bot.app/v1/graphql",
|
|
||||||
wantType: "mapstring",
|
|
||||||
args: args{
|
|
||||||
query: `query {
|
|
||||||
__type(name: "Query") {
|
|
||||||
name
|
|
||||||
}
|
|
||||||
}`,
|
|
||||||
},
|
|
||||||
wantReturned_value: map[string]interface{}{"__type": nil},
|
|
||||||
wantErr: false,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "TestBaseClient_Query_tgbotapp_valid_query_byte",
|
|
||||||
graphQLServer: "https://telegram-bot.app/v1/graphql",
|
|
||||||
wantType: "byte",
|
|
||||||
args: args{
|
|
||||||
query: `query {
|
|
||||||
__type(name: "Query") {
|
|
||||||
name
|
|
||||||
}
|
|
||||||
}`,
|
|
||||||
},
|
|
||||||
wantReturned_value: []byte(`{"__type":null}`),
|
|
||||||
wantErr: false,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "TestBaseClient_Query_tgbotapp_valid_query_string",
|
|
||||||
graphQLServer: "https://telegram-bot.app/v1/graphql",
|
|
||||||
wantType: "string",
|
|
||||||
args: args{
|
|
||||||
query: `query {
|
|
||||||
__type(name: "Query") {
|
|
||||||
name
|
|
||||||
}
|
|
||||||
}`,
|
|
||||||
},
|
|
||||||
wantReturned_value: string(`{"__type":null}`),
|
|
||||||
wantErr: false,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "TestBaseClient_Query_tgbotapp_valid_query_invalid_type",
|
|
||||||
graphQLServer: "https://telegram-bot.app/v1/graphql",
|
|
||||||
wantType: "potato",
|
|
||||||
args: args{
|
|
||||||
query: `query {
|
|
||||||
__type(name: "Query") {
|
|
||||||
name
|
|
||||||
}
|
|
||||||
}`,
|
|
||||||
},
|
|
||||||
wantReturned_value: nil,
|
|
||||||
wantErr: true,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "TestBaseClient_Query_tgbotapp_valid_query_cache",
|
|
||||||
graphQLServer: "https://telegram-bot.app/v1/graphql",
|
|
||||||
args: args{
|
|
||||||
query: `query {
|
|
||||||
__type(name: "Query") {
|
|
||||||
name
|
|
||||||
}
|
|
||||||
}`,
|
|
||||||
variables: map[string]interface{}{
|
|
||||||
"gqlcache": true,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
wantReturned_value: string(`{"__type":null}`),
|
|
||||||
wantErr: false,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "TestBaseClient_Query_tgbotapp_valid_query_with_retry",
|
|
||||||
graphQLServer: "https://telegram-bot.app/v0/graphql",
|
|
||||||
wantType: "byte",
|
|
||||||
args: args{
|
|
||||||
query: `query {
|
|
||||||
__type(name: "Query") {
|
|
||||||
name
|
|
||||||
}
|
|
||||||
}`,
|
|
||||||
variables: map[string]interface{}{
|
|
||||||
"gqlretries": true,
|
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
wantReturned_value: nil,
|
wantReturned_value: nil,
|
||||||
@@ -300,9 +167,8 @@ func (suite *Tests) TestBaseClient_Query() {
|
|||||||
for _, tt := range tests {
|
for _, tt := range tests {
|
||||||
suite.T().Run(tt.name, func(t *testing.T) {
|
suite.T().Run(tt.name, func(t *testing.T) {
|
||||||
b := NewConnection()
|
b := NewConnection()
|
||||||
if tt.graphQLServer != "" {
|
b.SetEndpoint(mockServer.URL)
|
||||||
b.SetEndpoint(tt.graphQLServer)
|
b.SetHTTPClient(mockServer.Client())
|
||||||
}
|
|
||||||
if tt.wantType != "" {
|
if tt.wantType != "" {
|
||||||
b.SetOutput(tt.wantType)
|
b.SetOutput(tt.wantType)
|
||||||
}
|
}
|
||||||
|
|||||||
+15
-1
@@ -1,6 +1,7 @@
|
|||||||
package gql
|
package gql
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"net/http/httptest"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
assertions "github.com/stretchr/testify/assert"
|
assertions "github.com/stretchr/testify/assert"
|
||||||
@@ -12,9 +13,22 @@ type Tests struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
var (
|
var (
|
||||||
assert *assertions.Assertions
|
assert *assertions.Assertions
|
||||||
|
mockServer *httptest.Server
|
||||||
)
|
)
|
||||||
|
|
||||||
|
func (suite *Tests) SetupSuite() {
|
||||||
|
// Start mock GraphQL server
|
||||||
|
mockServer = StartMockServer()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (suite *Tests) TearDownSuite() {
|
||||||
|
// Close the mock server
|
||||||
|
if mockServer != nil {
|
||||||
|
mockServer.Close()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func (suite *Tests) SetupTest() {
|
func (suite *Tests) SetupTest() {
|
||||||
assert = assertions.New(suite.T())
|
assert = assertions.New(suite.T())
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user