TykTechnologies / tyk

Tyk Open Source API Gateway written in Go, supporting REST, GraphQL, TCP and gRPC protocols
Other
9.51k stars 1.07k forks source link

[TT-12561] chore: move some root packages to internal #6388

Closed titpetric closed 14 hours ago

titpetric commented 1 month ago

User description

This moves several packages away from root scope to internal:

https://tyktech.atlassian.net/browse/TT-12561

These are all in gateway internal scope because:

1) plugins don't reasonably depend on them which means the change is likely non-breaking, 2) should be covered by coding standards under internal scope (and test constraints).

May block/trigger:

If any breakage occurs due to unforseen couplings (e.g. dashboard using any of these gateway packages...) then we need to investigate the coupling and decouple. Gateway is big, changes often, and isn't meant to expose internal API details by default, as breaking changes are considered heavily, the sooner we can move this out of scope, the sooner we can discover and prevent further coupling on these.

Some package like regexp remain in gateway scope, as they have known use in plugins. This is documented in 'Code structure guidelines' (confluence).

github-actions[bot] commented 1 month ago

PR Reviewer Guide ๐Ÿ”

โฑ๏ธ Estimated effort to review: 5 ๐Ÿ”ต๐Ÿ”ต๐Ÿ”ต๐Ÿ”ต๐Ÿ”ต
๐Ÿงช PR contains tests
๐Ÿ”’ No security concerns identified
โšก Key issues to review

**Possible Bug:** The PR introduces changes across multiple files and functionalities, including core areas like OAuth handling, RPC, and DNS caching. Given the complexity and potential impact of these changes, a thorough review and testing are crucial to ensure that no existing functionalities are broken. **Performance Concerns:** The changes involve modifications to critical paths, such as request handling and analytics processing. It is essential to evaluate the performance implications of these changes, especially under high load. **Code Organization:** The PR adds new functionalities and modifies existing ones across various parts of the system. Reviewing how these changes are organized within the codebase is necessary to maintain modularity and readability.
github-actions[bot] commented 1 month ago

PR Code Suggestions โœจ

CategorySuggestion                                                                                                                                    Score
Possible bug
Improve error handling for IP parsing in the IP blacklist middleware ___ **Replace the direct call to net.ParseIP(httputil.RealIP(r)) with a utility function that
handles potential parsing errors. This ensures robust error handling if the IP address is
malformed or if httputil.RealIP(r) returns an unexpected value.** [gateway/mw_ip_blacklist.go [26]](https://github.com/TykTechnologies/tyk/pull/6388/files#diff-d2e1549fccb4a65eebf5e97176ee3b550ed79a5c2ac7d49b8884c010c862f74eR26-R26) ```diff -remoteIP := net.ParseIP(httputil.RealIP(r)) +remoteIP, err := net.ParseIP(httputil.RealIP(r)) +if err != nil { + // Handle error, possibly return an appropriate HTTP error + return nil, http.StatusBadRequest +} ```
Suggestion importance[1-10]: 9 Why: Adding error handling for IP parsing is crucial for robustness and prevents potential runtime errors if the IP address is malformed. This suggestion correctly addresses a possible bug.
9
Add error handling for IP parsing in the IP whitelist middleware ___ **Similar to the blacklist middleware, modify the IP parsing to include error handling for
robustness.** [gateway/mw_ip_whitelist.go [26]](https://github.com/TykTechnologies/tyk/pull/6388/files#diff-3bb2d1b812d1a0b3a0708621538246669b57df37933bffb9e4dc0dbba757a3ccR26-R26) ```diff -remoteIP := net.ParseIP(httputil.RealIP(r)) +remoteIP, err := net.ParseIP(httputil.RealIP(r)) +if err != nil { + // Handle error, possibly return an appropriate HTTP error + return nil, http.StatusBadRequest +} ```
Suggestion importance[1-10]: 9 Why: Similar to the blacklist middleware, adding error handling for IP parsing ensures robustness and prevents potential runtime errors. This suggestion correctly addresses a possible bug.
9
Add error handling for empty IP addresses list ___ **Handle the case where `len(ips)` is zero to prevent index out of range errors.** [internal/dnscache/manager.go [126]](https://github.com/TykTechnologies/tyk/pull/6388/files#diff-63e8d1a87c16e257ff92d2ad8d5b3c7a764989e263ee9e05af1f5574f1a58a03R126-R126) ```diff +if len(ips) == 0 { + return nil, fmt.Errorf("no IPs found for host") +} return safeDial(ips[0]+":"+port, host) ```
Suggestion importance[1-10]: 9 Why: This suggestion correctly addresses a potential bug by adding error handling for cases where the IP list is empty, preventing index out of range errors.
9
Best practice
Use t.Fatalf to immediately halt test execution on critical setup errors ___ **Consider using t.Fatalf instead of t.Error in the setup function to halt the test
execution immediately if the DNS mock initialization fails. This prevents further test
execution which could lead to misleading results or panic due to uninitialized objects.** [internal/dnscache/storage_test.go [53]](https://github.com/TykTechnologies/tyk/pull/6388/files#diff-46bc0bd50428b9e2e98d4249a4f0a674d6324321cc85b9a6f5b4cae8d51e92ebR53-R53) ```diff -cfg.T.Error(err.Error()) +cfg.T.Fatalf("Failed to initialize DNS mock: %s", err) ```
Suggestion importance[1-10]: 9 Why: This suggestion improves test reliability by ensuring that the test halts immediately on critical setup errors, preventing misleading results or panics due to uninitialized objects.
9
Wrap errors to provide more context for debugging ___ **Add error wrapping to provide more context to the error returned when the plugin fails to
load or the symbol lookup fails. This helps in debugging by providing a stack trace and
the origin of the error.** [internal/goplugin/analyticsplugin.go [16]](https://github.com/TykTechnologies/tyk/pull/6388/files#diff-1d1cf806ac29415d592d2a948788c00d72af11adfd993591c50644397488d2ecR16-R16) ```diff -return nil, err +return nil, fmt.Errorf("failed to load plugin from path %s: %w", path, err) ```
Suggestion importance[1-10]: 8 Why: Adding error wrapping provides more context, which is valuable for debugging and understanding the origin of errors, enhancing maintainability and traceability.
8
Ensure IP address validity before using it in version check middleware ___ **Add error handling for the httputil.RealIP(r) call to ensure the IP address is valid
before using it in logging or analytics.** [gateway/mw_version_check.go [127]](https://github.com/TykTechnologies/tyk/pull/6388/files#diff-ea28ed4980be684295449af109cad7cef58b8823d9f270ab3f1537441645579aR127-R127) ```diff -Origin: httputil.RealIP(r) +ip := httputil.RealIP(r) +if ip == "" { + // Handle error or log warning about missing IP + return +} +Origin: ip ```
Suggestion importance[1-10]: 7 Why: Adding error handling for the IP address ensures that invalid or missing IPs are handled gracefully. This is a best practice for improving code robustness.
7
Enhancement
Add checks to ensure the token is not empty when used in Redis cache middleware ___ **Ensure that the token is not empty before using it as a key in Redis operations to prevent
potential misuse or unexpected behavior.** [gateway/mw_redis_cache.go [186]](https://github.com/TykTechnologies/tyk/pull/6388/files#diff-6266e0dbd16cef89e6de86a2c893114ba07799c804e2138172f9f94b08cdded8R186-R186) ```diff if token == "" { token = httputil.RealIP(r) + if token == "" { + // Handle case where IP is also empty, possibly log error or return + return + } } ```
Suggestion importance[1-10]: 8 Why: Ensuring the token is not empty before using it as a key in Redis operations prevents potential misuse or unexpected behavior. This enhancement improves the reliability of the code.
8
Enhance logging for debugging purposes ___ **Consider logging the selected IP address when using the random strategy for better
traceability.** [internal/dnscache/manager.go [141]](https://github.com/TykTechnologies/tyk/pull/6388/files#diff-63e8d1a87c16e257ff92d2ad8d5b3c7a764989e263ee9e05af1f5574f1a58a03R141-R141) ```diff ip := ips[m.rand.Intn(len(ips))] +logger.Debugf("Selected random IP: %s", ip) ```
Suggestion importance[1-10]: 7 Why: Adding a log statement for the selected random IP address improves traceability and debugging, although it is not crucial for functionality.
7
Error handling
Add error logging for DNS resolution failures ___ **Add error handling for potential failures in net.LookupHost to prevent unhandled errors.** [internal/dnscache/storage.go [72-74]](https://github.com/TykTechnologies/tyk/pull/6388/files#diff-7f9c3d6db7485a4cd4ed24d9eec3e835b03889f2b43498b82f41c4af8593f4beR72-R74) ```diff addrs, err := dc.resolveDNSRecord(hostName) +if err != nil { + logger.WithError(err).Error("Failed to resolve DNS record") + return nil, err +} ```
Suggestion importance[1-10]: 8 Why: This suggestion improves error handling by logging DNS resolution failures, which is important for diagnosing issues.
8
Maintainability
Use a constant for the plugin file paths to enhance maintainability ___ **Replace the hardcoded plugin file paths with a constant to avoid repetition and facilitate
easier maintenance or configuration changes.** [internal/goplugin/mw_go_plugin_test.go [24-26]](https://github.com/TykTechnologies/tyk/pull/6388/files#diff-58cb68383a1051b93ba06e337716558fc0a6fbb289b6e3ee51bdf3a161f6b61aR24-R26) ```diff -return "../test/goplugins/goplugins_race.so" -return "../test/goplugins/goplugins.so" +return testGoPluginPath ```
Suggestion importance[1-10]: 8 Why: This suggestion improves maintainability by reducing repetition and making future changes to the plugin file paths easier. However, it assumes the constant `testGoPluginPath` is defined and correctly set elsewhere in the code.
8
Use constants for expiration and checkInterval to enhance code clarity ___ **Replace the magic numbers for expiration and checkInterval with constants to improve code
readability and maintainability.** [internal/dnscache/storage_test.go [64]](https://github.com/TykTechnologies/tyk/pull/6388/files#diff-46bc0bd50428b9e2e98d4249a4f0a674d6324321cc85b9a6f5b4cae8d51e92ebR64-R64) ```diff -dnsCache := NewDnsCacheStorage(time.Duration(expiration)*time.Second, time.Duration(checkInterval)*time.Second) +const ( + expirationSeconds = 10 + checkIntervalSeconds = 5 +) +dnsCache := NewDnsCacheStorage(time.Duration(expirationSeconds)*time.Second, time.Duration(checkIntervalSeconds)*time.Second) ```
Suggestion importance[1-10]: 7 Why: Replacing magic numbers with constants improves code readability and maintainability, making it easier to understand and modify the code.
7
Refactor repetitive middleware setup into a helper function to improve code clarity and reduce duplication ___ **Consider using a loop or a helper function to reduce code duplication when setting up API
specifications with similar configurations.** [internal/goplugin/mw_go_plugin_test.go [429-435]](https://github.com/TykTechnologies/tyk/pull/6388/files#diff-58cb68383a1051b93ba06e337716558fc0a6fbb289b6e3ee51bdf3a161f6b61aR429-R435) ```diff -spec.CustomMiddleware = apidef.MiddlewareSection{ - Driver: apidef.GoPluginDriver, - Pre: []apidef.MiddlewareDefinition{ - { - Name: "MyPluginPre", - Path: goPluginFilename(), - }, - }, -} +setupCustomMiddleware(spec, "MyPluginPre", goPluginFilename()) ```
Suggestion importance[1-10]: 7 Why: This suggestion enhances code clarity and reduces duplication by using a helper function for middleware setup. It is beneficial for maintainability but requires additional implementation of the `setupCustomMiddleware` function.
7
Simplify the fileExist function for clarity and conciseness ___ **Simplify the fileExist function by directly returning the negation of errors.Is(err,
os.ErrNotExist), removing the need for an if-else structure.** [internal/goplugin/file_loader.go [21-24]](https://github.com/TykTechnologies/tyk/pull/6388/files#diff-978c853618bea6f2432907ef16a27372cdbd88b65db28d1203448faba4ed5336R21-R24) ```diff -if _, err := os.Stat(path); errors.Is(err, os.ErrNotExist) { +_, err := os.Stat(path) +fileExists := !errors.Is(err, os.ErrNotExist) +if !fileExists { log.Warningf("plugin file %v doesn't exist", path) - return false } -return true +return fileExists ```
Suggestion importance[1-10]: 6 Why: Simplifying the function improves code readability and conciseness, although the functional improvement is minor.
6
github-actions[bot] commented 1 month ago

API Changes

--- prev.txt    2024-07-04 17:19:14.837752287 +0000
+++ current.txt 2024-07-04 17:19:11.761727251 +0000
@@ -7052,193 +7052,6 @@
    CacheOptions
    OASDefinition
 )
-# Package: ./dlpython
-
-package python // import "github.com/TykTechnologies/tyk/dlpython"
-
-
-FUNCTIONS
-
-func FindPythonConfig(customVersion string) (selectedVersion string, err error)
-    FindPythonConfig scans PATH for common python-config locations.
-
-func GetItem(d unsafe.Pointer, k string) (unsafe.Pointer, error)
-    GetItem wraps PyDict_GetItemString
-
-func Init() error
-    Init will initialize the Python runtime.
-
-func LoadModuleDict(m string) (unsafe.Pointer, error)
-    LoadModuleDict wraps PyModule_GetDict.
-
-func PyBytesAsString(o unsafe.Pointer, l int) ([]byte, error)
-    PyBytesAsString wraps PyBytes_AsString
-
-func PyBytesFromString(input []byte) (unsafe.Pointer, error)
-    PyBytesFromString wraps PyBytesFromString
-
-func PyBytes_AsString(arg0 *C.PyObject) *C.char
-func PyBytes_FromStringAndSize(arg0 *C.char, arg1 C.long) *C.PyObject
-func PyDecRef(o unsafe.Pointer)
-func PyDict_GetItemString(dp *C.PyObject, key *C.char) *C.PyObject
-func PyErr_Print()
-func PyEval_InitThreads()
-func PyEval_SaveThread() *C.PyThreadState
-func PyGILState_Ensure() C.PyGILState_STATE
-func PyGILState_Release(arg0 C.PyGILState_STATE)
-func PyImportImport(modulePtr unsafe.Pointer) unsafe.Pointer
-func PyImport_Import(name *C.PyObject) *C.PyObject
-func PyIncRef(o unsafe.Pointer)
-func PyLongAsLong(o unsafe.Pointer) int
-    PyLongAsLong wraps PyLong_AsLong
-
-func PyLong_AsLong(arg0 *C.PyObject) C.long
-func PyModule_GetDict(arg0 *C.PyObject) *C.PyObject
-func PyObjectCallObject(o unsafe.Pointer, args unsafe.Pointer) (unsafe.Pointer, error)
-    PyObjectCallObject wraps PyObject_CallObject
-
-func PyObjectGetAttr(o unsafe.Pointer, attr interface{}) (unsafe.Pointer, error)
-    PyObjectGetAttr wraps PyObject_GetAttr
-
-func PyObject_CallObject(callable_object *C.PyObject, args *C.PyObject) *C.PyObject
-func PyObject_GetAttr(arg0 *C.PyObject, arg1 *C.PyObject) *C.PyObject
-func PyRunSimpleString(s string)
-    PyRunSimpleString wraps PyRun_SimpleStringFlags
-
-func PyRun_SimpleStringFlags(arg0 *C.char, arg1 unsafe.Pointer) C.int
-func PyTupleGetItem(tup unsafe.Pointer, pos int) (unsafe.Pointer, error)
-    PyTupleGetItem wraps PyTuple_GetItem
-
-func PyTupleNew(size int) (unsafe.Pointer, error)
-    PyTupleNew wraps PyTuple_New
-
-func PyTupleSetItem(tup unsafe.Pointer, pos int, o interface{}) error
-    PyTupleSetItem wraps PyTuple_SetItem
-
-func PyTuple_GetItem(arg0 *C.PyObject, arg1 C.long) *C.PyObject
-func PyTuple_New(size C.long) *C.PyObject
-func PyTuple_SetItem(arg0 *C.PyObject, arg1 C.long, arg2 *C.PyObject) C.int
-func PyUnicodeFromString(s string) unsafe.Pointer
-func PyUnicode_FromString(u *C.char) *C.PyObject
-func Py_DecRef(object *C.PyObject)
-func Py_IncRef(object *C.PyObject)
-func Py_Initialize()
-func Py_IsInitialized() C.int
-func SetPythonPath(p []string)
-    SetPythonPath is a helper for setting PYTHONPATH.
-
-func ToPyObject(p unsafe.Pointer) *C.PyObject
-# Package: ./dnscache
-
-package dnscache // import "github.com/TykTechnologies/tyk/dnscache"
-
-
-TYPES
-
-type DialContextFunc func(ctx context.Context, network, address string) (net.Conn, error)
-
-type DnsCacheItem struct {
-   Addrs []string
-}
-    DnsCacheItem represents single record in cache
-
-type DnsCacheManager struct {
-   // Has unexported fields.
-}
-    DnsCacheManager is responsible for in-memory dns query records cache.
-    It allows to init dns caching and to hook into net/http dns resolution chain
-    in order to cache query response ip records.
-
-func NewDnsCacheManager(multipleIPsHandleStrategy config.IPsHandleStrategy) *DnsCacheManager
-    NewDnsCacheManager returns new empty/non-initialized DnsCacheManager
-
-func (m *DnsCacheManager) CacheStorage() IDnsCacheStorage
-
-func (m *DnsCacheManager) DisposeCache()
-    DisposeCache clear all entries from cache and disposes/disables caching of
-    dns queries
-
-func (m *DnsCacheManager) InitDNSCaching(ttl, checkInterval time.Duration)
-    InitDNSCaching initializes manager's cache storage if it wasn't initialized
-    before with provided ttl, checkinterval values Initialized cache storage
-    enables caching of previously hoooked net.Dialer DialContext calls
-
-    Otherwise leave storage as is.
-
-func (m *DnsCacheManager) IsCacheEnabled() bool
-
-func (m *DnsCacheManager) SetCacheStorage(cache IDnsCacheStorage)
-
-func (m *DnsCacheManager) WrapDialer(dialer *net.Dialer) DialContextFunc
-    WrapDialer returns wrapped version of net.Dialer#DialContext func with
-    hooked up caching of dns queries.
-
-    Actual dns server call occures in net.Resolver#LookupIPAddr method, linked
-    to net.Dialer instance by net.Dialer#Resolver field
-
-type DnsCacheStorage struct {
-   // Has unexported fields.
-}
-    DnsCacheStorage is an in-memory cache of auto-purged dns query ip responses
-
-func NewDnsCacheStorage(expiration, checkInterval time.Duration) *DnsCacheStorage
-
-func (dc *DnsCacheStorage) Clear()
-    Clear deletes all records from cache
-
-func (dc *DnsCacheStorage) Delete(key string)
-
-func (dc *DnsCacheStorage) FetchItem(hostName string) ([]string, error)
-    FetchItem returns list of ips from cache or resolves them and add to cache
-
-func (dc *DnsCacheStorage) Get(key string) (DnsCacheItem, bool)
-    Get returns non expired item from cache
-
-func (dc *DnsCacheStorage) Items(includeExpired bool) map[string]DnsCacheItem
-    Items returns map of non expired dns cache items
-
-func (dc *DnsCacheStorage) Set(key string, addrs []string)
-
-type IDnsCacheManager interface {
-   InitDNSCaching(ttl, checkInterval time.Duration)
-   WrapDialer(dialer *net.Dialer) DialContextFunc
-   SetCacheStorage(cache IDnsCacheStorage)
-   CacheStorage() IDnsCacheStorage
-   IsCacheEnabled() bool
-   DisposeCache()
-}
-    IDnsCacheManager is an interface for abstracting interaction with dns cache.
-    Implemented by DnsCacheManager
-
-type IDnsCacheStorage interface {
-   FetchItem(key string) ([]string, error)
-   Get(key string) (DnsCacheItem, bool)
-   Set(key string, addrs []string)
-   Delete(key string)
-   Clear()
-}
-    IDnsCacheStorage is an interface for working with cached storage of
-    dns record. Wrapped by IDnsCacheManager/DnsCacheManager. Implemented by
-    DnsCacheStorage
-
-type MockStorage struct {
-   MockFetchItem func(key string) ([]string, error)
-   MockGet       func(key string) (DnsCacheItem, bool)
-   MockSet       func(key string, addrs []string)
-   MockDelete    func(key string)
-   MockClear     func()
-}
-
-func (ms *MockStorage) Clear()
-
-func (ms *MockStorage) Delete(key string)
-
-func (ms *MockStorage) FetchItem(key string) ([]string, error)
-
-func (ms *MockStorage) Get(key string) (DnsCacheItem, bool)
-
-func (ms *MockStorage) Set(key string, addrs []string)
-
 # Package: ./gateway

 package gateway // import "github.com/TykTechnologies/tyk/gateway"
@@ -10579,29 +10392,6 @@
     Save implements the main method of the BundleSaver interface. It makes use
     of archive/zip.

-# Package: ./goplugin
-
-package goplugin // import "github.com/TykTechnologies/tyk/goplugin"
-
-
-FUNCTIONS
-
-func GetAnalyticsHandler(path string, symbol string) (func(record *analytics.AnalyticsRecord), error)
-func GetHandler(path string, symbol string) (http.HandlerFunc, error)
-func GetPluginFileNameToLoad(pluginStorage storage, pluginPath string) (string, error)
-    GetPluginFileNameToLoad check which file to load based on name, tyk version,
-    os and architecture but it also takes care of returning the name of the file
-    that exists
-
-func GetResponseHandler(path string, symbol string) (func(rw http.ResponseWriter, res *http.Response, req *http.Request), error)
-func GetSymbol(modulePath string, symbol string) (interface{}, error)
-
-TYPES
-
-type FileSystemStorage struct{}
-    FileSystemStorage implements storage interface, it uses the filesystem as
-    store
-
 # Package: ./header

 package header // import "github.com/TykTechnologies/tyk/header"
@@ -10876,175 +10666,6 @@
     SubexpNames returns result of regexp.Regexp.SubexpNames of wrapped regular
     expression.

-# Package: ./request
-
-package request // import "github.com/TykTechnologies/tyk/request"
-
-
-FUNCTIONS
-
-func RealIP(r *http.Request) string
-    RealIP takes a request object, and returns the real Client IP address.
-
-# Package: ./rpc
-
-package rpc // import "github.com/TykTechnologies/tyk/rpc"
-
-
-CONSTANTS
-
-const (
-   ClientSingletonCall     = "gorpcClientCall"
-   FuncClientSingletonCall = "gorpcDispatcherClientCall"
-)
-const ANALYTICS_KEYNAME = "tyk-system-analytics"
-
-VARIABLES
-
-var (
-   GlobalRPCCallTimeout = 30 * time.Second
-   GlobalRPCPingTimeout = 60 * time.Second
-   Log                  = &logrus.Logger{}
-   Instrument           *health.Stream
-
-   // UseSyncLoginRPC for tests where we dont need to execute as a goroutine
-   UseSyncLoginRPC bool
-
-   AnalyticsSerializers []serializer.AnalyticsSerializer
-)
-var ErrRPCIsDown = errors.New("RPCStorageHandler: rpc is either down or was not configured")
-    ErrRPCIsDown this is returned when we can't reach rpc server.
-
-
-FUNCTIONS
-
-func CloseConnections()
-func Connect(connConfig Config, suppressRegister bool, dispatcherFuncs map[string]interface{},
-   getGroupLoginFunc func(string, string) interface{},
-   emergencyModeFunc func(),
-   emergencyModeLoadedFunc func()) bool
-    Connect will establish a connection to the RPC server specified in
-    connection options
-
-func Disconnect() bool
-func EmitErrorEvent(jobName string, funcName string, err error)
-func EmitErrorEventKv(jobName string, funcName string, err error, kv map[string]string)
-func ForceConnected(t *testing.T)
-    ForceConnected only intended to be used in tests do not use it for any other
-    thing
-
-func FuncClientSingleton(funcName string, request interface{}) (result interface{}, err error)
-    FuncClientSingleton performs RPC call. This might be called before we have
-    established RPC connection, in that case we perform a retry with exponential
-    backoff ensuring indeed we can't connect to the rpc, this will eventually
-    fall into emergency mode( That is handled outside of this function call)
-
-func GroupLogin() bool
-func IsEmergencyMode() bool
-func LoadCount() int
-func Login() bool
-    Login tries to login to the rpc sever. Returns true if it succeeds and false
-    if it fails.
-
-func Reset()
-func ResetEmergencyMode()
-func SetEmergencyMode(t *testing.T, value bool)
-    SetEmergencyMode used in tests to force emergency mode
-
-func SetLoadCounts(t *testing.T, value int)
-
-TYPES
-
-type AnalyticsRecord struct {
-   Method        string
-   Path          string
-   RawPath       string
-   ContentLength int64
-   UserAgent     string
-   Day           int
-   Month         time.Month
-   Year          int
-   Hour          int
-   ResponseCode  int
-   APIKey        string
-   TimeStamp     time.Time
-   APIVersion    string
-   APIName       string
-   APIID         string
-   OrgID         string
-   OauthID       string
-   RequestTime   int64
-   RawRequest    string
-   RawResponse   string
-   IPAddress     string
-   Geo           GeoData
-   Tags          []string
-   Alias         string
-   TrackPath     bool
-   ExpireAt      time.Time `bson:"expireAt" json:"expireAt"`
-}
-
-type Config struct {
-   UseSSL                bool   `json:"use_ssl"`
-   SSLInsecureSkipVerify bool   `json:"ssl_insecure_skip_verify"`
-   SSLMinVersion         uint16 `json:"ssl_min_version"`
-   SSLMaxVersion         uint16 `json:"ssl_max_version"`
-   ConnectionString      string `json:"connection_string"`
-   RPCKey                string `json:"rpc_key"`
-   APIKey                string `json:"api_key"`
-   GroupID               string `json:"group_id"`
-   CallTimeout           int    `json:"call_timeout"`
-   PingTimeout           int    `json:"ping_timeout"`
-   RPCPoolSize           int    `json:"rpc_pool_size"`
-}
-
-type GeoData struct {
-   Country struct {
-       ISOCode string `maxminddb:"iso_code"`
-   } `maxminddb:"country"`
-
-   City struct {
-       GeoNameID uint              `maxminddb:"geoname_id"`
-       Names     map[string]string `maxminddb:"names"`
-   } `maxminddb:"city"`
-
-   Location struct {
-       Latitude  float64 `maxminddb:"latitude"`
-       Longitude float64 `maxminddb:"longitude"`
-       TimeZone  string  `maxminddb:"time_zone"`
-   } `maxminddb:"location"`
-}
-
-type Purger struct {
-   Store storage.Handler
-}
-    RPCPurger will purge analytics data into a Mongo database, requires that the
-    Mongo DB string is specified in the Config object
-
-func (r *Purger) Connect()
-    Connect Connects to RPC
-
-func (r *Purger) PurgeCache()
-    PurgeCache will pull the data from the in-memory store and drop it into the
-    specified MongoDB collection
-
-func (r Purger) PurgeLoop(ctx context.Context, interval time.Duration)
-    PurgeLoop starts the loop that will pull data out of the in-memory store and
-    into RPC.
-
-type SyncronizerForcer struct {
-   // Has unexported fields.
-}
-
-func NewSyncForcer(controller *storage.ConnectionHandler, getNodeDataFunc func() []byte) *SyncronizerForcer
-    NewSyncForcer returns a new syncforcer with a connected redis with a key
-    prefix synchronizer-group- for group synchronization control.
-
-func (sf *SyncronizerForcer) GroupLoginCallback(userKey string, groupID string) interface{}
-    GroupLoginCallback checks if the groupID key exists in the storage to turn
-    on/off ForceSync param. If the the key doesn't exists in the storage,
-    it creates it and set ForceSync to true
-
 # Package: ./signature_validator

 package signature_validator // import "github.com/TykTechnologies/tyk/signature_validator"
@@ -11647,67 +11268,6 @@

 func (v *Vault) Get(key string) (string, error)

-# Package: ./tcp
-
-package tcp // import "github.com/TykTechnologies/tyk/tcp"
-
-
-FUNCTIONS
-
-func IsSocketClosed(err error) bool
-    IsSocketClosed returns true if err is a result of reading from closed
-    network connection
-
-
-TYPES
-
-type ConnState uint
-
-const (
-   Active ConnState = iota
-   Open
-   Closed
-)
-type Modifier struct {
-   ModifyRequest  func(src, dst net.Conn, data []byte) ([]byte, error)
-   ModifyResponse func(src, dst net.Conn, data []byte) ([]byte, error)
-}
-    Modifier define rules for tranforming incoming and outcoming TCP messages To
-    filter response set data to empty To close connection, return error
-
-type Proxy struct {
-   sync.RWMutex
-
-   DialTLS         func(network, addr string) (net.Conn, error)
-   Dial            func(network, addr string) (net.Conn, error)
-   TLSConfigTarget *tls.Config
-
-   ReadTimeout  time.Duration
-   WriteTimeout time.Duration
-
-   SyncStats func(Stat)
-   // Duration in which connection stats will be flushed. Defaults to one second.
-   StatsSyncInterval time.Duration
-   // Has unexported fields.
-}
-
-func (p *Proxy) AddDomainHandler(domain, target string, modifier *Modifier)
-
-func (p *Proxy) RemoveDomainHandler(domain string)
-
-func (p *Proxy) Serve(l net.Listener) error
-
-func (p *Proxy) Swap(new *Proxy)
-
-type Stat struct {
-   State    ConnState
-   BytesIn  int64
-   BytesOut int64
-}
-    Stat defines basic statistics about a tcp connection
-
-func (s *Stat) Flush() Stat
-
 # Package: ./templates

 package templates // import "github.com/TykTechnologies/tyk/templates"
@@ -11948,226 +11508,6 @@
 func MyPluginReturningError(rw http.ResponseWriter, r *http.Request)
 # Package: ./tests/regression

-# Package: ./trace
-
-package trace // import "github.com/TykTechnologies/tyk/trace"
-
-
-VARIABLES
-
-var ErrManagerDisabled = errors.New("trace: trace is diabled")
-    ErrManagerDisabled is returned when trying to use global trace manager when
-    it is disabled.
-
-
-FUNCTIONS
-
-func AddTracer(tracer, service string) error
-    AddTracer initialize a tracer for the service.
-
-func Close() error
-    Close calls Close on the global tace manager.
-
-func Debug(ctx context.Context, logrus Logrus, args ...interface{})
-    Debug creates debug log on both logrus and span.
-
-func Disable()
-    Disable disables the global trace manager.
-
-func Enable()
-    Enable sets the global manager to enabled.
-
-func Error(ctx context.Context, logrus Logrus, args ...interface{})
-func Extract(tr Tracer, h http.Header) (opentracing.SpanContext, error)
-func ExtractFromContext(ctx context.Context, h http.Header) (opentracing.SpanContext, error)
-func GetServiceID(ctx context.Context) string
-    GetServiceID returns service name attched to context returns an empty string
-    if the service name key is not found.
-
-func Handle(service string, h http.Handler) http.Handler
-    Handle returns a http.Handler with root opentracting setup. This should be
-    the topmost handler.
-
-func Info(ctx context.Context, logrus Logrus, args ...interface{})
-func Inject(service string, span opentracing.Span, h http.Header) error
-func InjectFromContext(ctx context.Context, span opentracing.Span, h http.Header) error
-func IsEnabled() bool
-    IsEnabled returns true if the global trace manager is enabled.
-
-func Log(ctx context.Context, fields ...opentracingLog.Field)
-    Log tries to check if there is a span in ctx and adds logs fields on the
-    span.
-
-func Root(service string, r *http.Request) (opentracing.Span, *http.Request)
-func SetInit(fn InitFunc)
-func SetLogger(log Logger)
-func SetServiceID(ctx context.Context, service string) context.Context
-    SetServiceID returns context with service assigned to it.
-
-func SetupTracing(name string, opts map[string]interface{})
-func Span(ctx context.Context, ops string, opts ...opentracing.StartSpanOption) (opentracing.Span, context.Context)
-    Span creates a new span for the given ops. If tracing is disabled in this
-    ctx then a noop span is created and the same ctx is returned.
-
-    Note that the returned context contains the returned span as active span.
-    So any spans created form the returned context will be children of the
-    returned span.
-
-func Warning(ctx context.Context, logrus Logrus, args ...interface{})
-
-TYPES
-
-type Config struct {
-   Name string
-   Opts map[string]interface{}
-}
-
-type InitFunc func(name string, service string, opts map[string]interface{}, logger Logger) (Tracer, error)
-    InitFunc this is a function for initializing a Tracer
-
-type Logger interface {
-   Errorf(format string, args ...interface{})
-   Info(args ...interface{})
-   Infof(format string, args ...interface{})
-}
-    Logger defines api for logging messages by the OpenTracer struct. This is a
-    workaround to avoid trying this to logrus
-
-type Logrus interface {
-   Debug(args ...interface{})
-   Error(args ...interface{})
-   Warning(args ...interface{})
-   Info(args ...interface{})
-}
-    Logrus implements a subset of logrus api to reduce friction when we want to
-    log both on opentracing and on logrus.
-
-type NoopTracer struct {
-   opentracing.NoopTracer
-}
-    NoopTracer wraps opentracing.NoopTracer to satisfy Tracer interface.
-
-func (n NoopTracer) Close() error
-    Close implements io.Closer interface by doing nothing.
-
-func (n NoopTracer) Name() string
-
-type StdLogger struct{}
-
-func (StdLogger) Error(args ...interface{})
-
-func (StdLogger) Errorf(format string, args ...interface{})
-
-func (StdLogger) Info(args ...interface{})
-
-func (StdLogger) Infof(format string, args ...interface{})
-
-type Tracer interface {
-   Name() string
-   opentracing.Tracer
-   io.Closer
-}
-
-func Get(service string) Tracer
-    Get returns a tracer stored on the global trace manager.
-
-func Init(name string, service string, opts map[string]interface{}, logger Logger) (Tracer, error)
-    Init returns a tracer for a given name.
-
-# Package: ./trace/jaeger
-
-package jaeger // import "github.com/TykTechnologies/tyk/trace/jaeger"
-
-
-CONSTANTS
-
-const Name = "jaeger"
-    Name is the name of this tracer.
-
-
-FUNCTIONS
-
-func Load(opts map[string]interface{}) (*config.Configuration, error)
-    Load returns jaeger configuration from opts. Please see jaeger configuration
-    for details about the key value pairs
-
-    https://github.com/jaegertracing/jaeger-client-go/blob/master/config/config.go#L37
-
-
-TYPES
-
-type Logger interface {
-   Errorf(msg string, args ...interface{})
-   Infof(msg string, args ...interface{})
-}
-
-type Trace struct {
-   opentracing.Tracer
-   io.Closer
-}
-
-func Init(service string, opts map[string]interface{}, log Logger) (*Trace, error)
-    Init returns a implementation of tyk.Tracer using jaeger client.
-
-func (Trace) Name() string
-
-# Package: ./trace/openzipkin
-
-package openzipkin // import "github.com/TykTechnologies/tyk/trace/openzipkin"
-
-
-CONSTANTS
-
-const Name = "zipkin"
-
-FUNCTIONS
-
-func Load(opts map[string]interface{}) (*config.ZipkinConfig, error)
-    Load retusn a zipkin configuration from the opts.
-
-func NewTracer(zip *zipkin.Tracer) *zipkinTracer
-
-TYPES
-
-type Span struct {
-   // Has unexported fields.
-}
-
-func (Span) BaggageItem(restrictedKey string) string
-
-func (s Span) Context() opentracing.SpanContext
-
-func (s Span) Finish()
-
-func (s Span) FinishWithOptions(opts opentracing.FinishOptions)
-
-func (s Span) Log(data opentracing.LogData)
-
-func (s Span) LogEvent(event string)
-
-func (s Span) LogEventWithPayload(event string, payload interface{})
-
-func (s Span) LogFields(fields ...opentracingLog.Field)
-
-func (s Span) LogKV(alternatingKeyValues ...interface{})
-
-func (s Span) SetBaggageItem(restrictedKey, value string) opentracing.Span
-
-func (s Span) SetOperationName(operationName string) opentracing.Span
-
-func (s Span) SetTag(key string, value interface{}) opentracing.Span
-
-func (s Span) Tracer() opentracing.Tracer
-
-type Tracer struct {
-   opentracing.Tracer
-   reporter.Reporter
-}
-
-func Init(service string, opts map[string]interface{}) (*Tracer, error)
-
-func (Tracer) Name() string
-
 # Package: ./user

 package user // import "github.com/TykTechnologies/tyk/user"
sonarcloud[bot] commented 1 month ago

Quality Gate Failed Quality Gate failed

Failed conditions
50.5% Coverage on New Code (required โ‰ฅ 80%)

See analysis details on SonarCloud

titpetric commented 1 month ago

Dashboard uses:

  1 /TykTechnologies/tyk/apidef/adapter"
  1 /TykTechnologies/tyk/apidef/importer"
  1 /TykTechnologies/tyk/config"
  1 /TykTechnologies/tyk/log"
  1 /TykTechnologies/tyk/storage"
  4 /TykTechnologies/tyk/header"
  5 /TykTechnologies/tyk/user"
  8 /TykTechnologies/tyk/certs"
 11 /TykTechnologies/tyk/gateway"
 14 /TykTechnologies/tyk/apidef/oas"
 21 /TykTechnologies/tyk/apidef"
 36 /TykTechnologies/tyk/test"