-
Notifications
You must be signed in to change notification settings - Fork 1.1k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merging to release-5.3: TT-14085: Remove the pmylund/go-cache dependency (#6871) #6874
Draft
buger
wants to merge
1
commit into
release-5.3
Choose a base branch
from
merge/release-5.3/89b51c320d48dd855c1ea9542f8161558cba3249
base: release-5.3
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Merging to release-5.3: TT-14085: Remove the pmylund/go-cache dependency (#6871) #6874
buger
wants to merge
1
commit into
release-5.3
from
merge/release-5.3/89b51c320d48dd855c1ea9542f8161558cba3249
Conversation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<details open> <summary><a href="https://tyktech.atlassian.net/browse/TT-14085" title="TT-14085" target="_blank">TT-14085</a></summary> <br /> <table> <tr> <th>Summary</th> <td>[Testing/memory leak] Remove pmylund/go-cache</td> </tr> <tr> <th>Type</th> <td> <img alt="Story" src="https://tyktech.atlassian.net/rest/api/2/universal_avatar/view/type/issuetype/avatar/10315?size=medium" /> Story </td> </tr> <tr> <th>Status</th> <td>In Dev</td> </tr> <tr> <th>Points</th> <td>N/A</td> </tr> <tr> <th>Labels</th> <td><a href="https://tyktech.atlassian.net/issues?jql=project%20%3D%20TT%20AND%20labels%20%3D%20SESAP%20ORDER%20BY%20created%20DESC" title="SESAP">SESAP</a></td> </tr> </table> </details> <!-- do not remove this marker as it will break jira-lint's functionality. added_by_jira_lint --> --- This implements a subset of go-cache as used in gateway under internal/cache, dropping the dependency. https://tyktech.atlassian.net/browse/TT-14085 ___ Enhancement, Tests, Bug fix ___ - Replaced `pmylund/go-cache` with a custom internal cache implementation. - Introduced a new `internal/cache` package with cache, item, and janitor functionalities. - Updated DNS cache, gateway, and regexp modules to use the new internal cache. - Added comprehensive unit tests for the new cache implementation and its components. ___ <table><thead><tr><th></th><th align="left">Relevant files</th></tr></thead><tbody><tr><td><strong>Enhancement</strong></td><td><details><summary>8 files</summary><table> <tr> <td><strong>storage.go</strong><dd><code>Updated DNS cache to use internal cache</code> </dd></td> <td><a href="https://github.com/TykTechnologies/tyk/pull/6871/files#diff-71a52cd6346b22e5bcb1e45481fdfb05b761510d3eeb6b631f4129ed1e98b08f">+6/-3</a> </td> </tr> <tr> <td><strong>server.go</strong><dd><code>Refactored gateway cache setup and teardown</code> </dd></td> <td><a href="https://github.com/TykTechnologies/tyk/pull/6871/files#diff-4652d1bf175a0be8f5e61ef7177c9666f23e077d8626b73ac9d13358fa8b525b">+29/-17</a> </td> </tr> <tr> <td><strong>cache.go</strong><dd><code>Implemented custom cache with expiration and cleanup</code> </dd></td> <td><a href="https://github.com/TykTechnologies/tyk/pull/6871/files#diff-113f0a3ddf486bd0f7ee93e06851fe642139355ce485bd7acd848729688962b2">+117/-48</a></td> </tr> <tr> <td><strong>const.go</strong><dd><code>Added constants for cache expiration</code> </dd></td> <td><a href="https://github.com/TykTechnologies/tyk/pull/6871/files#diff-448694a8bd4e5850fc1628a98916e274108b60b306cff2975b9a2163ab7cf5a2">+7/-0</a> </td> </tr> <tr> <td><strong>item.go</strong><dd><code>Added cache item structure with expiration logic</code> </dd></td> <td><a href="https://github.com/TykTechnologies/tyk/pull/6871/files#diff-147d35cb74dbca325fb8155b41d86be735558ccf7e1a5b11c51a6f8df5931a6b">+18/-0</a> </td> </tr> <tr> <td><strong>janitor.go</strong><dd><code>Implemented janitor for periodic cache cleanup</code> </dd></td> <td><a href="https://github.com/TykTechnologies/tyk/pull/6871/files#diff-2a5458b21c11f19afea01dc950c2f3caaeb1793b83d585443dfa347dbf8088aa">+44/-0</a> </td> </tr> <tr> <td><strong>repository.go</strong><dd><code>Added repository interface for cache abstraction</code> </dd></td> <td><a href="https://github.com/TykTechnologies/tyk/pull/6871/files#diff-51bf85b4acebd1b757ab007b04a58ffc3b570f4c579252910895262c718bd877">+76/-0</a> </td> </tr> <tr> <td><strong>cache.go</strong><dd><code>Updated regexp cache to use internal cache</code> </dd></td> <td><a href="https://github.com/TykTechnologies/tyk/pull/6871/files#diff-0420ba44813cfb841c564160f4a3106d2a9bc4c4477dc8ee4ab97582253f7753">+4/-3</a> </td> </tr> </table></details></td></tr><tr><td><strong>Tests</strong></td><td><details><summary>5 files</summary><table> <tr> <td><strong>testutil.go</strong><dd><code>Added cache cleanup in gateway test utilities</code> </dd></td> <td><a href="https://github.com/TykTechnologies/tyk/pull/6871/files#diff-7aaf6ae49fb8f58a8c99d337fedd15b3e430dd928ed547e425ef429b10d28ce8">+2/-0</a> </td> </tr> <tr> <td><strong>cache_test.go</strong><dd><code>Added unit tests for custom cache implementation</code> </dd></td> <td><a href="https://github.com/TykTechnologies/tyk/pull/6871/files#diff-7fbdfb41b04a92f43e9826f893f4f7efa7431219a257f97f2c1d8219efb3f1fb">+42/-24</a> </td> </tr> <tr> <td><strong>item_test.go</strong><dd><code>Added unit tests for cache item expiration logic</code> </dd></td> <td><a href="https://github.com/TykTechnologies/tyk/pull/6871/files#diff-6451c091258b5c8ac564e0d6fc75ad211e3396850060b10fc373a1bd568d9ed9">+47/-0</a> </td> </tr> <tr> <td><strong>janitor_test.go</strong><dd><code>Added unit tests for janitor functionality</code> </dd></td> <td><a href="https://github.com/TykTechnologies/tyk/pull/6871/files#diff-8549318827857e1a242451f72bba0b50fc221816657117017b3d22649acd987e">+33/-0</a> </td> </tr> <tr> <td><strong>repository_test.go</strong><dd><code>Added unit tests for cache repository implementation</code> </dd></td> <td><a href="https://github.com/TykTechnologies/tyk/pull/6871/files#diff-7c39208ed77b58d98849988d77bfa71fff24184f061811a87672af313ada0dac">+45/-0</a> </td> </tr> </table></details></td></tr><tr><td><strong>Dependencies</strong></td><td><details><summary>2 files</summary><table> <tr> <td><strong>go.mod</strong><dd><code>Removed `pmylund/go-cache` dependency</code> </dd></td> <td><a href="https://github.com/TykTechnologies/tyk/pull/6871/files#diff-33ef32bf6c23acb95f5902d7097b7a1d5128ca061167ec0716715b0b9eeaa5f6">+0/-1</a> </td> </tr> <tr> <td><strong>go.sum</strong><dd><code>Removed `pmylund/go-cache` entries</code> </dd></td> <td><a href="https://github.com/TykTechnologies/tyk/pull/6871/files#diff-3295df7234525439d778f1b282d146a4f1ff6b415248aaac074e8042d9f42d63">+0/-2</a> </td> </tr> </table></details></td></tr><tr><td><strong>Configuration changes</strong></td><td><details><summary>1 files</summary><table> <tr> <td><strong>Taskfile.yml</strong><dd><code>Added taskfile for cache package development</code> </dd></td> <td><a href="https://github.com/TykTechnologies/tyk/pull/6871/files#diff-b6690cc441b7677d64006ca10ac2360e951c7eec45cda9560763e0782e3767a8">+34/-0</a> </td> </tr> </table></details></td></tr></tr></tbody></table> ___ > <details> <summary> Need help?</summary><li>Type <code>/help how to ...</code> in the comments thread for any questions about PR-Agent usage.</li><li>Check out the <a href="https://qodo-merge-docs.qodo.ai/usage-guide/">documentation</a> for more information.</li></details> --------- Co-authored-by: Tit Petric <[email protected]> (cherry picked from commit 89b51c3)
API Changes --- prev.txt 2025-02-15 16:26:48.258166503 +0000
+++ current.txt 2025-02-15 16:26:44.531165774 +0000
@@ -7062,3366 +7062,6 @@
# Package: ./gateway
-package gateway // import "github.com/TykTechnologies/tyk/gateway"
-
-Tyk Gateway API
-
-The code below describes the Tyk Gateway API Version: 2.8.0
-
- Schemes: https, http
- Host: localhost
- BasePath: /tyk/
-
- Consumes:
- - application/json
-
- Produces:
- - application/json
-
- Security:
- - api_key:
-
- SecurityDefinitions:
- api_key:
- type: apiKey
- name: X-Tyk-Authorization
- in: header
-
-swagger:meta
-
-CONSTANTS
-
-const (
- LDAPStorageEngine apidef.StorageEngineCode = "ldap"
- RPCStorageEngine apidef.StorageEngineCode = "rpc"
-)
-const (
- // HeartBeatStarted Zero value - the handlers started
- HeartBeatStarted = 0
-
- // HeartBeatStopped value - the handlers invoked shutdown
- HeartBeatStopped = 1
-)
- Constants for heartBeatStopSentinel indicators.
-
- Go 1.17 adds atomic.Value.Swap which is great, but 1.19 adds atomic.Bool and
- other types. This is a go <1.13 cludge.
-
-const (
- EventQuotaExceeded apidef.TykEvent = "QuotaExceeded"
- EventRateLimitExceeded apidef.TykEvent = "RatelimitExceeded"
- EventAuthFailure apidef.TykEvent = "AuthFailure"
- EventKeyExpired apidef.TykEvent = "KeyExpired"
- EventVersionFailure apidef.TykEvent = "VersionFailure"
- EventOrgQuotaExceeded apidef.TykEvent = "OrgQuotaExceeded"
- EventOrgRateLimitExceeded apidef.TykEvent = "OrgRateLimitExceeded"
- EventTriggerExceeded apidef.TykEvent = "TriggerExceeded"
- EventBreakerTriggered apidef.TykEvent = "BreakerTriggered"
- EventBreakerTripped apidef.TykEvent = "BreakerTripped"
- EventBreakerReset apidef.TykEvent = "BreakerReset"
- EventHOSTDOWN apidef.TykEvent = "HostDown"
- EventHOSTUP apidef.TykEvent = "HostUp"
- EventTokenCreated apidef.TykEvent = "TokenCreated"
- EventTokenUpdated apidef.TykEvent = "TokenUpdated"
- EventTokenDeleted apidef.TykEvent = "TokenDeleted"
-)
- Register new event types here, the string is the code used to hook at the
- Api Deifnititon JSON/BSON level
-
-const (
- MsgAuthFieldMissing = "Authorization field missing"
- MsgApiAccessDisallowed = "Access to this API has been disallowed"
- MsgBearerMailformed = "Bearer token malformed"
- MsgKeyNotAuthorized = "Key not authorised"
- MsgOauthClientRevoked = "Key not authorised. OAuth client access was revoked"
- MsgKeyNotAuthorizedUnexpectedSigningMethod = "Key not authorized: Unexpected signing method"
- MsgCertificateExpired = "Certificate has expired"
-)
-const (
- // Zero value - the service is open and ready to use
- OPEN = 0
-
- // Closed value - the service shouldn't be used
- CLOSED = 1
-)
-const (
- UnHealthyHostMetaDataTargetKey = "target_url"
- UnHealthyHostMetaDataAPIKey = "api_id"
- UnHealthyHostMetaDataHostKey = "host_name"
- PollerCacheKey = "PollerActiveInstanceID"
- PoolerHostSentinelKeyPrefix = "PollerCheckerInstance:"
-
- UptimeAnalytics_KEYNAME = "tyk-uptime-analytics"
-)
-const (
- DEFAULT_ORG_SESSION_EXPIRATION = int64(604800)
-)
-const (
- ErrAuthAuthorizationFieldMissing = "auth.auth_field_missing"
- ErrAuthKeyNotFound = "auth.key_not_found"
- ErrAuthCertNotFound = "auth.cert_not_found"
- ErrAuthCertExpired = "auth.cert_expired"
- ErrAuthKeyIsInvalid = "auth.key_is_invalid"
-
- MsgNonExistentKey = "Attempted access with non-existent key."
- MsgNonExistentCert = "Attempted access with non-existent cert."
- MsgInvalidKey = "Attempted access with invalid key."
-)
-const (
- KID = "kid"
- SUB = "sub"
- HMACSign = "hmac"
- RSASign = "rsa"
- ECDSASign = "ecdsa"
-)
-const (
- ErrOAuthAuthorizationFieldMissing = "oauth.auth_field_missing"
- ErrOAuthAuthorizationFieldMalformed = "oauth.auth_field_malformed"
- ErrOAuthKeyNotFound = "oauth.key_not_found"
- ErrOAuthClientDeleted = "oauth.client_deleted"
-)
-const (
- ResetQuota string = "resetQuota"
- CertificateRemoved string = "CertificateRemoved"
- CertificateAdded string = "CertificateAdded"
- OAuthRevokeToken string = "oAuthRevokeToken"
- OAuthRevokeAccessToken string = "oAuthRevokeAccessToken"
- OAuthRevokeRefreshToken string = "oAuthRevokeRefreshToken"
- OAuthRevokeAllTokens string = "revoke_all_tokens"
- OauthClientAdded string = "OauthClientAdded"
- OauthClientRemoved string = "OauthClientRemoved"
- OauthClientUpdated string = "OauthClientUpdated"
-)
-const (
- // QuotaKeyPrefix serves as a standard prefix for generating quota keys.
- QuotaKeyPrefix = "quota-"
- // RateLimitKeyPrefix serves as a standard prefix for generating rate limit keys.
- RateLimitKeyPrefix = "rate-limit-"
- SentinelRateLimitKeyPostfix = ".BLOCKED"
-)
-const (
-
- // Accepts any http requests on /, only allows GET on /get, etc.
- // All return a JSON with request info.
- TestHttpAny = "http://" + testHttpListen
- TestHttpGet = TestHttpAny + "/get"
-
- MockOrgID = "507f1f77bcf86cd799439011"
- NonCanonicalHeaderKey = "X-CertificateOuid"
-)
-const BackupApiKeyBase = "node-definition-backup:"
-const BackupPolicyKeyBase = "node-policy-backup:"
-const CoProcessDefaultKeyPrefix = "coprocess-data:"
- CoProcessDefaultKeyPrefix is used as a key prefix for this CP.
-
-const EH_CoProcessHandler apidef.TykEventHandlerName = "cp_dynamic_handler"
- Constant for event system.
-
-const EH_JSVMHandler apidef.TykEventHandlerName = "eh_dynamic_handler"
-const EH_LogHandler apidef.TykEventHandlerName = "eh_log_handler"
- The name for event handlers as defined in the API Definition JSON/BSON
- format
-
-const ListDetailed = "detailed"
-const LoopScheme = "tyk"
-const OIDPREFIX = "openid"
-const RPCKeyPrefix = "rpc:"
-const RestrictedFieldValidationFailedLogMsg = "Error during GraphQL request restricted fields validation: '%s'"
-const SAFE_METHODS = "SAFE_METHODS"
- const used by cache middleware
-
-const UnexpectedSigningMethod = "Unexpected signing method"
-const XTykAPIExpires = "x-tyk-api-expires"
-
-VARIABLES
-
-var (
- GlobalRate = ratecounter.NewRateCounter(1 * time.Second)
-)
-var (
- ErrTokenValidationFailed = errors.New("error happened during the access token validation")
- ErrKIDNotAString = errors.New("kid is not a string")
- ErrNoMatchingKIDFound = errors.New("no matching KID could be found")
-)
-var (
- ProxyingRequestFailedErr = errors.New("there was a problem proxying the request")
- GraphQLDepthLimitExceededErr = errors.New("depth limit exceeded")
-)
-var (
- ErrNoSuitableUserIDClaimFound = errors.New("no suitable claims for user ID were found")
- ErrEmptyUserIDInSubClaim = errors.New("found an empty user ID in sub claim")
-)
-var (
- NewRelicApplication newrelic.Application
-
- ErrSyncResourceNotKnown = errors.New("unknown resource to sync")
-)
-var (
- EnableTestDNSMock = false
- MockHandle *test.DnsMockHandle
-)
-var (
- VERSION = build.Version
- Commit = build.Commit
-)
- Deprecated: All of the following variables are deprecated in favor of
- importing the information from the internal/build package directly.
- These placeholders remain for compatibility but are likely to be removed in
- a future version.
-
-var (
- ErrPoliciesFetchFailed = errors.New("fetch policies request login failure")
-)
-var (
- ErrRequestMalformed = errors.New("request malformed")
-)
-var GatewayFireSystemEvent func(name apidef.TykEvent, meta interface{})
- GatewayFireSystemEvent declared as global variable, set during gw start
-
-var JWKCache cache.Repository = cache.New(240, 30)
-var LoopHostRE = regexp.MustCompile("tyk://([^/]+)")
-var NonAlphaNumRE = regexp.MustCompile("[^A-Za-z0-9]+")
-var TykErrors = make(map[string]config.TykError)
-
-FUNCTIONS
-
-func APILoopingName(name string) string
-func AddNewRelicInstrumentation(app newrelic.Application, r *mux.Router)
- AddNewRelicInstrumentation adds NewRelic instrumentation to the router
-
-func AuthFailed(m TykMiddleware, r *http.Request, token string)
- TODO: move this method to base middleware?
-
-func CheckPortWhiteList(w map[string]config.PortWhiteList, listenPort int, protocol string) error
-func CoProcessLog(CMessage, CLogLevel *C.char)
- CoProcessLog is a bridge for using Tyk log from CP.
-
-func CreateCoProcessMiddleware(hookName string, hookType coprocess.HookType, mwDriver apidef.MiddlewareDriver, baseMid *BaseMiddleware) func(http.Handler) http.Handler
- CreateCoProcessMiddleware initializes a new CP middleware, takes hook type
- (pre, post, etc.), hook name ("my_hook") and driver ("python").
-
-func CreateJWKToken(jGen ...func(*jwt.Token)) string
-func CreateJWKTokenECDSA(jGen ...func(*jwt.Token)) string
-func CreateSession(gw *Gateway, sGen ...func(s *user.SessionState)) string
- Deprecated: Use Test.CreateSession instead.
-
-func CreateStandardPolicy() *user.Policy
-func CreateStandardSession() *user.SessionState
-func DoCoprocessReload()
-func DurationToMillisecond(d time.Duration) float64
-func EncodeRequestToEvent(r *http.Request) string
- EncodeRequestToEvent will write the request out in wire protocol and encode
- it to base64 and store it in an Event object
-
-func EnsureTransport(host, protocol string) string
- EnsureTransport sanitizes host/protocol pairs and returns a valid URL.
-
-func GenerateTestBinaryData() (buf *bytes.Buffer)
-func GetAccessDefinitionByAPIIDOrSession(currentSession *user.SessionState, api *APISpec) (accessDef *user.AccessDefinition, allowanceScope string, err error)
-func GetTLSClient(cert *tls.Certificate, caCert []byte) *http.Client
-func GetTLSConfig(cert *tls.Certificate, caCert []byte) *tls.Config
-func InitTestMain(ctx context.Context, m *testing.M) int
-func InstrumentationMW(next http.Handler) http.Handler
- InstrumentationMW will set basic instrumentation events, variables and
- timers on API jobs
-
-func JSONToFormValues(r *http.Request) error
- JSONToFormValues if r has header Content-Type set to application/json this
- will decode request body as json to map[string]string and adds the key/value
- pairs in r.Form.
-
-func LoadPoliciesFromDir(dir string) (map[string]user.Policy, error)
-func LoadPoliciesFromFile(filePath string) (map[string]user.Policy, error)
-func LoopingUrl(host string) string
-func NewPythonDispatcher(conf config.Config) (dispatcher coprocess.Dispatcher, err error)
- NewPythonDispatcher wraps all the actions needed for this CP.
-
-func NormalisePath(a *analytics.AnalyticsRecord, globalConfig *config.Config)
-func ParseRSAPublicKey(data []byte) (interface{}, error)
-func ProtoMap(inputMap map[string][]string) map[string]string
- ProtoMap is a helper function for maps with string slice values.
-
-func ProtoSessionState(session *user.SessionState) *coprocess.SessionState
- ProtoSessionState takes a standard SessionState and outputs a SessionState
- object compatible with Protocol Buffers.
-
-func ProxyHandler(p *ReverseProxy, apiSpec *APISpec) http.Handler
- ProxyHandler Proxies requests through to their final destination, if they
- make it through the middleware chain.
-
-func PythonInit(pythonVersion string) error
- PythonInit initializes the Python interpreter.
-
-func PythonLoadDispatcher() error
- PythonLoadDispatcher creates reference to the dispatcher class.
-
-func PythonNewDispatcher(bundleRootPath string) (coprocess.Dispatcher, error)
- PythonNewDispatcher creates an instance of TykDispatcher.
-
-func PythonSetEnv(pythonPaths ...string)
- PythonSetEnv sets PYTHONPATH, it's called before initializing the
- interpreter.
-
-func RevokeAllTokens(storage ExtendedOsinStorageInterface, clientId, clientSecret string) (int, []string, error)
-func RevokeToken(storage ExtendedOsinStorageInterface, token, tokenTypeHint string)
-func Start()
-func TestHelperSSEServer(tb testing.TB) *httptest.Server
-func TestHelperSSEStreamClient(tb testing.TB, ts *Test, enableWebSockets bool) error
-func TestReq(t testing.TB, method, urlStr string, body interface{}) *http.Request
-func TestReqBody(t testing.TB, body interface{}) io.Reader
-func TykGetData(CKey *C.char) *C.char
- TykGetData is a CoProcess API function for fetching data.
-
-func TykSessionState(session *coprocess.SessionState) *user.SessionState
- TykSessionState takes a coprocess.SessionState (as returned by the Protocol
- Buffer binding), and outputs a standard Tyk SessionState.
-
-func TykStoreData(CKey, CValue *C.char, CTTL C.int)
- TykStoreData is a CoProcess API function for storing data.
-
-func TykTriggerEvent(CEventName, CPayload *C.char)
- TykTriggerEvent is a CoProcess API function for triggering Tyk system
- events.
-
-func UpdateAPIVersion(spec *APISpec, name string, verGen func(version *apidef.VersionInfo))
-func WrappedCharsetReader(s string, i io.Reader) (io.Reader, error)
-
-TYPES
-
-type APIAllCertificateBasics struct {
- Certs []*certs.CertificateBasics `json:"certs"`
-}
-
-type APIAllCertificates struct {
- CertIDs []string `json:"certs"`
-}
-
-type APICertificateStatusMessage struct {
- CertID string `json:"id"`
- Status string `json:"status"`
- Message string `json:"message"`
-}
-
-type APIDefinitionLoader struct {
- Gw *Gateway `json:"-"`
-}
- APIDefinitionLoader will load an Api definition from a storage system.
-
-func (a APIDefinitionLoader) FromDashboardService(endpoint string) ([]*APISpec, error)
- FromDashboardService will connect and download ApiDefintions from a Tyk
- Dashboard instance.
-
-func (a APIDefinitionLoader) FromDir(dir string) []*APISpec
- FromDir will load APIDefinitions from a directory on the filesystem.
- Definitions need to be the JSON representation of APIDefinition object
-
-func (a APIDefinitionLoader) FromRPC(store RPCDataLoader, orgId string, gw *Gateway) ([]*APISpec, error)
- FromCloud will connect and download ApiDefintions from a Mongo DB instance.
-
-func (a APIDefinitionLoader) GetOASFilepath(path string) string
-
-func (a APIDefinitionLoader) MakeSpec(def *nestedApiDefinition, logger *logrus.Entry) (*APISpec, error)
- MakeSpec will generate a flattened URLSpec from and APIDefinitions'
- VersionInfo data. paths are keyed to the Api version name, which is
- determined during routing to speed up lookups
-
-func (a APIDefinitionLoader) ParseDefinition(r io.Reader) (api apidef.APIDefinition)
-
-func (a APIDefinitionLoader) ParseOAS(r io.Reader) (oas oas.OAS)
-
-type APIError struct {
- Message htmltemplate.HTML
-}
- APIError is generic error object returned if there is something wrong with
- the request
-
-type APISpec struct {
- *apidef.APIDefinition
- OAS oas.OAS
- sync.RWMutex
-
- Checksum string
- RxPaths map[string][]URLSpec
- WhiteListEnabled map[string]bool
-
- AuthManager SessionHandler
- OAuthManager *OAuthManager
- OrgSessionManager SessionHandler
- EventPaths map[apidef.TykEvent][]config.TykEventHandler
- Health HealthChecker
- JSVM JSVM
- ResponseChain []TykResponseHandler
- RoundRobin RoundRobin
- URLRewriteEnabled bool
- CircuitBreakerEnabled bool
- EnforcedTimeoutEnabled bool
- LastGoodHostList *apidef.HostList
- HasRun bool
- ServiceRefreshInProgress bool
- HTTPTransport *TykRoundTripper
- HTTPTransportCreated time.Time
- WSTransport http.RoundTripper
- WSTransportCreated time.Time
- GlobalConfig config.Config
- OrgHasNoSession bool
- AnalyticsPluginConfig *GoAnalyticsPlugin
-
- GraphEngine graphengine.Engine
-
- HasMock bool
- HasValidateRequest bool
- OASRouter routers.Router
- // Has unexported fields.
-}
- APISpec represents a path specification for an API, to avoid enumerating
- multiple nested lists, a single flattened URL list is checked for matching
- paths and then it's status evaluated if found.
-
-func BuildAPI(apiGens ...func(spec *APISpec)) (specs []*APISpec)
-
-func BuildOASAPI(oasGens ...func(oasDef *oas.OAS)) (specs []*APISpec)
-
-func CloneAPI(a *APISpec) *APISpec
-
-func (a *APISpec) CheckSpecMatchesStatus(r *http.Request, rxPaths []URLSpec, mode URLStatus) (bool, interface{})
- CheckSpecMatchesStatus checks if a URL spec has a specific status.
- Deprecated: The function doesn't follow go return conventions (T, ok);
- use FindSpecMatchesStatus;
-
-func (a *APISpec) Expired() bool
-
-func (a *APISpec) FindSpecMatchesStatus(r *http.Request, rxPaths []URLSpec, mode URLStatus) (*URLSpec, bool)
- FindSpecMatchesStatus checks if a URL spec has a specific status and returns
- the URLSpec for it.
-
-func (s *APISpec) FireEvent(name apidef.TykEvent, meta interface{})
-
-func (a *APISpec) GetSessionLifetimeRespectsKeyExpiration() bool
- GetSessionLifetimeRespectsKeyExpiration returns a boolean to tell whether
- session lifetime should respect to key expiration or not. The global config
- takes the precedence. If the global one is `true`, value of the one in api
- level doesn't matter.
-
-func (a *APISpec) Init(authStore, sessionStore, healthStore, orgStore storage.Handler)
-
-func (s *APISpec) Release()
- Release releases all resources associated with API spec
-
-func (a *APISpec) RequestValid(r *http.Request) (bool, RequestStatus)
- RequestValid will check if an incoming request has valid version data and
- return a RequestStatus that describes the status of the request
-
-func (a *APISpec) SanitizeProxyPaths(r *http.Request)
-
-func (a *APISpec) StopSessionManagerPool()
-
-func (a *APISpec) StripListenPath(reqPath string) string
- StripListenPath will strip the listen path from the URL, keeping version in
- tact.
-
-func (a *APISpec) StripVersionPath(reqPath string) string
- StripVersionPath will strip the version from the URL. The input URL should
- already have listen path stripped.
-
-func (a *APISpec) URLAllowedAndIgnored(r *http.Request, rxPaths []URLSpec, whiteListStatus bool) (RequestStatus, interface{})
- URLAllowedAndIgnored checks if a url is allowed and ignored.
-
-func (s *APISpec) Validate(oasConfig config.OASConfig) error
- Validate returns nil if s is a valid spec and an error stating why the spec
- is not valid.
-
-func (a *APISpec) Version(r *http.Request) (*apidef.VersionInfo, RequestStatus)
- Version attempts to extract the version data from a request, depending on
- where it is stored in the request (currently only "header" is supported)
-
-type AccessRightsCheck struct {
- *BaseMiddleware
-}
- AccessRightsCheck is a middleware that will check if the key bing used
- to access the API has permission to access the specific version. If no
- permission data is in the user.SessionState, then it is assumed that the
- user can go through.
-
-func (a *AccessRightsCheck) Name() string
-
-func (a *AccessRightsCheck) ProcessRequest(w http.ResponseWriter, r *http.Request, _ interface{}) (error, int)
- ProcessRequest will run any checks on the request on the way through the
- system, return an error to have the chain fail
-
-type AuthKey struct {
- *BaseMiddleware
-}
- KeyExists will check if the key being used to access the API is in the
- request data, and then if the key is in the storage engine
-
-func (k *AuthKey) Name() string
-
-func (k *AuthKey) ProcessRequest(_ http.ResponseWriter, r *http.Request, _ interface{}) (error, int)
-
-type BaseExtractor struct {
- Config *apidef.MiddlewareIdExtractor
- IDExtractorConfig apidef.IDExtractorConfig
- *BaseMiddleware
-
- Spec *APISpec
-}
- BaseExtractor is the base structure for an ID extractor, it implements the
- IdExtractor interface. Other extractors may override some of its methods.
-
-func (e *BaseExtractor) Error(r *http.Request, err error, message string) (returnOverrides ReturnOverrides)
- Error is a helper for logging the extractor errors. It always returns HTTP
- 400 (so we don't expose any details).
-
-func (e *BaseExtractor) ExtractAndCheck(_ *http.Request) (sessionID string, returnOverrides ReturnOverrides)
- ExtractAndCheck is called from the CP middleware, if ID extractor is enabled
- for the current API.
-
-func (e *BaseExtractor) ExtractBody(r *http.Request) (string, error)
- ExtractBody is used when BodySource is specified.
-
-func (e *BaseExtractor) ExtractForm(r *http.Request, paramName string) (formValue string, err error)
- ExtractForm is used when a FormSource is specified.
-
-func (e *BaseExtractor) ExtractHeader(r *http.Request) (headerValue string, err error)
- ExtractHeader is used when a HeaderSource is specified.
-
-func (e *BaseExtractor) GenerateSessionID(input string, mw *BaseMiddleware) (sessionID string)
- GenerateSessionID is a helper for generating session IDs, it takes an input
- (usually the extractor output) and a middleware pointer.
-
-type BaseMiddleware struct {
- Spec *APISpec
- Proxy ReturningHttpHandler
- Gw *Gateway `json:"-"`
-
- // Has unexported fields.
-}
- BaseMiddleware wraps up the ApiSpec and Proxy objects to be included in a
- middleware handler, this can probably be handled better.
-
-func NewBaseMiddleware(gw *Gateway, spec *APISpec, proxy ReturningHttpHandler, logger *logrus.Entry) *BaseMiddleware
- NewBaseMiddleware creates a new *BaseMiddleware. The passed logrus.Entry
- is duplicated. BaseMiddleware keeps the pointer to *Gateway and *APISpec,
- as well as Proxy. The logger duplication is used so that basemiddleware
- copies can be created for different middleware.
-
-func (t *BaseMiddleware) ApplyPolicies(session *user.SessionState) error
- ApplyPolicies will check if any policies are loaded. If any are, it will
- overwrite the session state to use the policy values.
-
-func (t *BaseMiddleware) Base() *BaseMiddleware
- Base serves to provide the full BaseMiddleware API. It's part of
- the TykMiddleware interface. It escapes to a wider API surface than
- TykMiddleware, used by middlewares, etc.
-
-func (t *BaseMiddleware) CheckSessionAndIdentityForValidKey(originalKey string, r *http.Request) (user.SessionState, bool)
- CheckSessionAndIdentityForValidKey will check first the Session store for a
- valid key, if not found, it will try the Auth Handler, if not found it will
- fail
-
-func (t *BaseMiddleware) Config() (interface{}, error)
-
-func (m *BaseMiddleware) Copy() *BaseMiddleware
- Copy provides a new BaseMiddleware with it's own logger scope (copy).
- The Spec, Proxy and Gw values are not copied.
-
-func (t *BaseMiddleware) EnabledForSpec() bool
-
-func (t *BaseMiddleware) FireEvent(name apidef.TykEvent, meta interface{})
- FireEvent is added to the BaseMiddleware object so it is available across
- the entire stack
-
-func (t *BaseMiddleware) Init()
-
-func (t *BaseMiddleware) Logger() (logger *logrus.Entry)
- Logger is used by middleware process functions.
-
-func (t *BaseMiddleware) OrgSession(orgID string) (user.SessionState, bool)
-
-func (t *BaseMiddleware) OrgSessionExpiry(orgid string) int64
-
-func (t *BaseMiddleware) SetName(name string)
-
-func (t *BaseMiddleware) SetOrgExpiry(orgid string, expiry int64)
-
-func (t *BaseMiddleware) SetRequestLogger(r *http.Request) *logrus.Entry
-
-func (t *BaseMiddleware) UpdateRequestSession(r *http.Request) bool
-
-type BaseTykResponseHandler struct {
- Spec *APISpec `json:"-"`
- Gw *Gateway `json:"-"`
-}
-
-func (b *BaseTykResponseHandler) Enabled() bool
-
-func (b *BaseTykResponseHandler) HandleError(writer http.ResponseWriter, h *http.Request)
-
-func (b *BaseTykResponseHandler) HandleResponse(rw http.ResponseWriter, res *http.Response, req *http.Request, ses *user.SessionState) error
-
-func (b *BaseTykResponseHandler) Init(i interface{}, spec *APISpec) error
-
-func (b *BaseTykResponseHandler) Name() string
-
-type BasicAuthKeyIsValid struct {
- *BaseMiddleware
-
- // Has unexported fields.
-}
- BasicAuthKeyIsValid uses a username instead of
-
-func (k *BasicAuthKeyIsValid) EnabledForSpec() bool
- EnabledForSpec checks if UseBasicAuth is set in the API definition.
-
-func (k *BasicAuthKeyIsValid) Name() string
-
-func (k *BasicAuthKeyIsValid) ProcessRequest(w http.ResponseWriter, r *http.Request, _ interface{}) (error, int)
- ProcessRequest will run any checks on the request on the way through the
- system, return an error to have the chain fail
-
-type BatchReplyUnit struct {
- RelativeURL string `json:"relative_url"`
- Code int `json:"code"`
- Headers http.Header `json:"headers"`
- Body string `json:"body"`
-}
- BatchReplyUnit encodes a request suitable for replying to a batch request
-
-type BatchRequestHandler struct {
- Gw *Gateway `json:"-"`
- API *APISpec
-}
- BatchRequestHandler handles batch requests on /tyk/batch for any API
- Definition that has the feature enabled
-
-func (b *BatchRequestHandler) ConstructRequests(batchRequest BatchRequestStructure, unsafe bool) ([]*http.Request, error)
-
-func (b *BatchRequestHandler) DecodeBatchRequest(r *http.Request) (BatchRequestStructure, error)
-
-func (b *BatchRequestHandler) HandleBatchRequest(w http.ResponseWriter, r *http.Request)
- HandleBatchRequest is the actual http handler for a batch request on an API
- definition
-
-func (b *BatchRequestHandler) MakeRequests(batchRequest BatchRequestStructure, requestSet []*http.Request) []BatchReplyUnit
-
-func (b *BatchRequestHandler) ManualBatchRequest(requestObject []byte) ([]byte, error)
- HandleBatchRequest is the actual http handler for a batch request on an API
- definition
-
-type BatchRequestStructure struct {
- Requests []RequestDefinition `json:"requests"`
- SuppressParallelExecution bool `json:"suppress_parallel_execution"`
-}
- BatchRequestStructure defines a batch request order
-
-type Bundle struct {
- Name string
- Data []byte
- Path string
- Spec *APISpec
- Manifest apidef.BundleManifest
- Gw *Gateway `json:"-"`
-}
- Bundle is the basic bundle data structure, it holds the bundle name and the
- data.
-
-func (b *Bundle) AddToSpec()
- AddToSpec attaches the custom middleware settings to an API definition.
-
-func (b *Bundle) Verify() error
- Verify performs a signature verification on the bundle file.
-
-type BundleGetter interface {
- Get() ([]byte, error)
-}
- BundleGetter is used for downloading bundle data, see HttpBundleGetter for
- reference.
-
-type BundleSaver interface {
- Save(*Bundle, string, *APISpec) error
-}
- BundleSaver is an interface used by bundle saver structures.
-
-type CertificateCheckMW struct {
- *BaseMiddleware
-}
- CertificateCheckMW is used if domain was not detected or multiple APIs bind
- on the same domain. In this case authentification check happens not on TLS
- side but on HTTP level using this middleware
-
-func (m *CertificateCheckMW) EnabledForSpec() bool
-
-func (m *CertificateCheckMW) Name() string
-
-func (m *CertificateCheckMW) ProcessRequest(w http.ResponseWriter, r *http.Request, _ interface{}) (error, int)
-
-type ChainObject struct {
- ThisHandler http.Handler
- RateLimitChain http.Handler
- Open bool
- Skip bool
-}
-
-type CoProcessEventHandler struct {
- Spec *APISpec
- SpecJSON json.RawMessage
- // Has unexported fields.
-}
-
-func (l *CoProcessEventHandler) HandleEvent(em config.EventMessage)
-
-func (l *CoProcessEventHandler) Init(handlerConf interface{}) error
-
-type CoProcessEventWrapper struct {
- Event config.EventMessage `json:"message"`
- Handler string `json:"handler_name"`
- SpecJSON *json.RawMessage `json:"spec"`
-}
-
-type CoProcessMiddleware struct {
- *BaseMiddleware
-
- HookType coprocess.HookType
- HookName string
- MiddlewareDriver apidef.MiddlewareDriver
- RawBodyOnly bool
-
- // Has unexported fields.
-}
- CoProcessMiddleware is the basic CP middleware struct.
-
-func (m *CoProcessMiddleware) EnabledForSpec() bool
- EnabledForSpec checks if this middleware should be enabled for a given API.
-
-func (m *CoProcessMiddleware) Name() string
-
-func (m *CoProcessMiddleware) ProcessRequest(w http.ResponseWriter, r *http.Request, _ interface{}) (error, int)
- ProcessRequest will run any checks on the request on the way through the
- system, return an error to have the chain fail
-
-type CoProcessor struct {
- Middleware *CoProcessMiddleware
-}
- CoProcessor represents a CoProcess during the request.
-
-func (c *CoProcessor) BuildObject(req *http.Request, res *http.Response, spec *APISpec) (*coprocess.Object, error)
- BuildObject constructs a CoProcessObject from a given http.Request.
-
-func (c *CoProcessor) Dispatch(object *coprocess.Object) (*coprocess.Object, error)
-
-func (c *CoProcessor) ObjectPostProcess(object *coprocess.Object, r *http.Request, origURL string, origMethod string) (err error)
- ObjectPostProcess does CoProcessObject post-processing (adding/removing
- headers or params, etc.).
-
-type ComplexityFailReason int
-
-const (
- ComplexityFailReasonNone ComplexityFailReason = iota
- ComplexityFailReasonInternalError
- ComplexityFailReasonDepthLimitExceeded
-)
-type ConfigPayload struct {
- Configuration config.Config
- ForHostname string
- ForNodeID string
- TimeStamp int64
-}
-
-type CustomMiddlewareResponseHook struct {
- BaseTykResponseHandler
- // Has unexported fields.
-}
-
-func (h CustomMiddlewareResponseHook) Base() *BaseTykResponseHandler
-
-func (h *CustomMiddlewareResponseHook) HandleError(rw http.ResponseWriter, req *http.Request)
-
-func (h *CustomMiddlewareResponseHook) HandleResponse(rw http.ResponseWriter, res *http.Response, req *http.Request, ses *user.SessionState) error
-
-func (h *CustomMiddlewareResponseHook) Init(mwDef interface{}, spec *APISpec) error
-
-func (h *CustomMiddlewareResponseHook) Name() string
-
-type DBAccessDefinition struct {
- APIName string `json:"api_name"`
- APIID string `json:"api_id"`
- Versions []string `json:"versions"`
- AllowedURLs []user.AccessSpec `bson:"allowed_urls" json:"allowed_urls"` // mapped string MUST be a valid regex
- RestrictedTypes []graphql.Type `json:"restricted_types"`
- AllowedTypes []graphql.Type `json:"allowed_types"`
- DisableIntrospection bool `json:"disable_introspection"`
- FieldAccessRights []user.FieldAccessDefinition `json:"field_access_rights"`
- Limit *user.APILimit `json:"limit"`
-}
-
-func (d *DBAccessDefinition) ToRegularAD() user.AccessDefinition
-
-type DBPolicy struct {
- user.Policy
- AccessRights map[string]DBAccessDefinition `bson:"access_rights" json:"access_rights"`
-}
-
-func (d *DBPolicy) ToRegularPolicy() user.Policy
-
-type DashboardServiceSender interface {
- Init() error
- Register() error
- DeRegister() error
- StartBeating() error
- StopBeating()
- Ping() error
- NotifyDashboardOfEvent(interface{}) error
-}
-
-type DefaultHealthChecker struct {
- Gw *Gateway `json:"-"`
-
- APIID string
- // Has unexported fields.
-}
-
-func (h *DefaultHealthChecker) ApiHealthValues() (HealthCheckValues, error)
-
-func (h *DefaultHealthChecker) CreateKeyName(subKey HealthPrefix) string
-
-func (h *DefaultHealthChecker) Init(storeType storage.Handler)
-
-func (h *DefaultHealthChecker) StoreCounterVal(counterType HealthPrefix, value string)
-
-type DefaultKeyGenerator struct {
- Gw *Gateway `json:"-"`
-}
-
-func (d DefaultKeyGenerator) GenerateAuthKey(orgID string) string
- GenerateAuthKey is a utility function for generating new auth keys. Returns
- the storage key name and the actual key
-
-func (DefaultKeyGenerator) GenerateHMACSecret() string
- GenerateHMACSecret is a utility function for generating new auth keys.
- Returns the storage key name and the actual key
-
-type DefaultSessionManager struct {
- Gw *Gateway `json:"-"`
- // Has unexported fields.
-}
-
-func (b *DefaultSessionManager) Init(store storage.Handler)
-
-func (b *DefaultSessionManager) KeyExpired(newSession *user.SessionState) bool
- KeyExpired checks if a key has expired, if the value of
- user.SessionState.Expires is 0, it will be ignored
-
-func (b *DefaultSessionManager) RemoveSession(orgID string, keyName string, hashed bool) bool
- RemoveSession removes session from storage
-
-func (b *DefaultSessionManager) ResetQuota(keyName string, session *user.SessionState, isHashed bool)
-
-func (b *DefaultSessionManager) ResetQuotaObfuscateKey(keyName string) string
-
-func (b *DefaultSessionManager) SessionDetail(orgID string, keyName string, hashed bool) (user.SessionState, bool)
- SessionDetail returns the session detail using the storage engine (either in
- memory or Redis)
-
-func (b *DefaultSessionManager) Sessions(filter string) []string
- Sessions returns all sessions in the key store that match a filter key (a
- prefix)
-
-func (b *DefaultSessionManager) Stop()
-
-func (b *DefaultSessionManager) Store() storage.Handler
-
-func (b *DefaultSessionManager) UpdateSession(keyName string, session *user.SessionState,
- resetTTLTo int64, hashed bool) error
- UpdateSession updates the session state in the storage engine
-
-type DummyProxyHandler struct {
- SH SuccessHandler
- Gw *Gateway `json:"-"`
-}
-
-func (d *DummyProxyHandler) ServeHTTP(w http.ResponseWriter, r *http.Request)
-
-type DynamicMiddleware struct {
- *BaseMiddleware
-
- MiddlewareClassName string
- Pre bool
- UseSession bool
- Auth bool
-}
- DynamicMiddleware is a generic middleware that will execute JS code before
- continuing
-
-func (d *DynamicMiddleware) Name() string
-
-func (d *DynamicMiddleware) ProcessRequest(w http.ResponseWriter, r *http.Request, _ interface{}) (error, int)
- ProcessRequest will run any checks on the request on the way through the
- system, return an error to have the chain fail
-
-type EndPointCacheMeta struct {
- Method string
- CacheKeyRegex string
- CacheOnlyResponseCodes []int
- Timeout int64
-}
-
-type ErrorHandler struct {
- *BaseMiddleware
-}
- ErrorHandler is invoked whenever there is an issue with a proxied request,
- most middleware will invoke the ErrorHandler if something is wrong with the
- request and halt the request processing through the chain
-
-func (e *ErrorHandler) HandleError(w http.ResponseWriter, r *http.Request, errMsg string, errCode int, writeResponse bool)
- HandleError is the actual error handler and will store the error details in
- analytics if analytics processing is enabled.
-
-type EventCurcuitBreakerMeta struct {
- EventMetaDefault
- Path string
- APIID string
- CircuitEvent circuit.BreakerEvent
-}
- EventCurcuitBreakerMeta is the event status for a circuit breaker tripping
-
-type EventHostStatusMeta struct {
- EventMetaDefault
- HostInfo HostHealthReport
-}
-
-type EventKeyFailureMeta struct {
- EventMetaDefault
- Path string
- Origin string
- Key string
-}
- EventKeyFailureMeta is the metadata structure for any failure related to a
- key, such as quota or auth failures.
-
-type EventMetaDefault struct {
- Message string
- OriginatingRequest string
-}
- EventMetaDefault is a standard embedded struct to be used with custom event
- metadata types, gives an interface for easily extending event metadata
- objects
-
-type EventTokenMeta struct {
- EventMetaDefault
- Org string
- Key string
-}
-
-type EventTriggerExceededMeta struct {
- EventMetaDefault
- OrgID string `json:"org_id"`
- Key string `json:"key"`
- TriggerLimit int64 `json:"trigger_limit"`
- UsagePercentage int64 `json:"usage_percentage"`
-}
-
-type EventVersionFailureMeta struct {
- EventMetaDefault
- Path string
- Origin string
- Key string
- Reason string
-}
- EventVersionFailureMeta is the metadata structure for an auth failure
- (EventKeyExpired)
-
-type ExtendedCircuitBreakerMeta struct {
- apidef.CircuitBreakerMeta
- CB *circuit.Breaker `json:"-"`
-}
-
-type ExtendedOsinClientInterface interface {
- osin.Client
- GetDescription() string
-}
-
-type ExtendedOsinStorageInterface interface {
- osin.Storage
-
- // Create OAuth clients
- SetClient(id string, orgID string, client osin.Client, ignorePrefix bool) error
-
- // Custom getter to handle prefixing issues in Redis
- GetClientNoPrefix(id string) (osin.Client, error)
-
- GetClientTokens(id string) ([]OAuthClientToken, error)
- GetPaginatedClientTokens(id string, page int) ([]OAuthClientToken, int, error)
-
- GetExtendedClient(id string) (ExtendedOsinClientInterface, error)
-
- // Custom getter to handle prefixing issues in Redis
- GetExtendedClientNoPrefix(id string) (ExtendedOsinClientInterface, error)
-
- GetClients(filter string, orgID string, ignorePrefix bool) ([]ExtendedOsinClientInterface, error)
-
- DeleteClient(id string, orgID string, ignorePrefix bool) error
-
- // GetUser retrieves a Basic Access user token type from the key store
- GetUser(string) (*user.SessionState, error)
-
- // SetUser updates a Basic Access user token type in the key store
- SetUser(string, *user.SessionState, int64) error
-}
-
-type ExternalOAuthMiddleware struct {
- *BaseMiddleware
-}
-
-func (k *ExternalOAuthMiddleware) EnabledForSpec() bool
-
-func (k *ExternalOAuthMiddleware) Name() string
-
-func (k *ExternalOAuthMiddleware) ProcessRequest(w http.ResponseWriter, r *http.Request, _ interface{}) (error, int)
-
-type FileBundleGetter struct {
- URL string
- InsecureSkipVerify bool
-}
- FileBundleGetter is a BundleGetter for testing.
-
-func (g *FileBundleGetter) Get() ([]byte, error)
- Get mocks an HTTP(S) GET request.
-
-type GRPCDispatcher struct {
- coprocess.Dispatcher
-}
- GRPCDispatcher implements a coprocess.Dispatcher
-
-func (d *GRPCDispatcher) Dispatch(object *coprocess.Object) (*coprocess.Object, error)
- Dispatch takes a CoProcessMessage and sends it to the CP.
-
-func (d *GRPCDispatcher) DispatchEvent(eventJSON []byte)
- DispatchEvent dispatches a Tyk event.
-
-func (d *GRPCDispatcher) HandleMiddlewareCache(b *apidef.BundleManifest, basePath string)
- HandleMiddlewareCache isn't used by gRPC.
-
-func (d *GRPCDispatcher) Reload()
- Reload triggers a reload affecting CP middlewares and event handlers.
-
-type Gateway struct {
- DefaultProxyMux *proxyMux
-
- DRLManager *drl.DRL
-
- Analytics RedisAnalyticsHandler
- GlobalEventsJSVM JSVM
- MainNotifier RedisNotifier
- DefaultOrgStore DefaultSessionManager
- DefaultQuotaStore DefaultSessionManager
- GlobalSessionManager SessionHandler
- MonitoringHandler config.TykEventHandler
- RPCListener RPCStorageHandler
- DashService DashboardServiceSender
- CertificateManager certs.CertificateManager
- GlobalHostChecker HostCheckerManager
- ConnectionWatcher *httputil.ConnectionWatcher
- HostCheckTicker chan struct{}
- HostCheckerClient *http.Client
- TracerProvider otel.TracerProvider
-
- SessionLimiter SessionLimiter
- SessionMonitor Monitor
-
- // RPCGlobalCache stores keys
- RPCGlobalCache cache.Repository
- // RPCCertCache stores certificates
- RPCCertCache cache.Repository
- // key session memory cache
- SessionCache cache.Repository
- // org session memory cache
- ExpiryCache cache.Repository
- // memory cache to store arbitrary items
- UtilCache cache.Repository
- // ServiceCache is the service discovery cache
- ServiceCache cache.Repository
-
- // Nonce to use when interacting with the dashboard service
- ServiceNonce string
- ServiceNonceMutex sync.RWMutex
-
- RedisPurgeOnce sync.Once
- RpcPurgeOnce sync.Once
-
- // OnConnect this is a callback which is called whenever we transition redis Disconnected to connected
- OnConnect func()
-
- // SessionID is the unique session id which is used while connecting to dashboard to prevent multiple node allocation.
- SessionID string
-
- // ReloadTestCase use this when in any test for gateway reloads
- ReloadTestCase *ReloadMachinery
-
- // map[bundleName]map[fileName]fileContent used for tests
- TestBundles map[string]map[string]string
- TestBundleMu sync.Mutex
-
- // RedisController keeps track of redis connection and singleton
- StorageConnectionHandler *storage.ConnectionHandler
-
- // Has unexported fields.
-}
-
-func NewGateway(config config.Config, ctx context.Context) *Gateway
-
-func (gw *Gateway) ApplyLifetime(sess *user.SessionState, specs ...*APISpec) int64
- ApplyLifetime calculates the lifetime for the key. It considers the access
- rights and the bigger lifetime will be used
-
-func (gw *Gateway) BuildAndLoadAPI(apiGens ...func(spec *APISpec)) (specs []*APISpec)
-
-func (gw *Gateway) CoProcessInit()
- CoProcessInit creates a new CoProcessDispatcher, it will be called when Tyk
- starts.
-
-func (gw *Gateway) CreateDefinitionFromString(defStr string) *APISpec
-
-func (gw *Gateway) DoReload()
-
-func (gw *Gateway) EventHandlerByName(handlerConf apidef.EventHandlerTriggerConfig, spec *APISpec) (config.TykEventHandler, error)
- EventHandlerByName is a convenience function to get event handler instances
- from an API Definition
-
-func (gw *Gateway) FetchBundle(spec *APISpec) (Bundle, error)
- FetchBundle will fetch a given bundle, using the right BundleGetter.
- The first argument is the bundle name, the base bundle URL will be used as
- prefix.
-
-func (gw *Gateway) FireSystemEvent(name apidef.TykEvent, meta interface{})
-
-func (gw *Gateway) GetApiSpecsFromAccessRights(sess *user.SessionState) []*APISpec
- GetApiSpecsFromAccessRights from the session.AccessRights returns the
- collection of api specs
-
-func (gw *Gateway) GetConfig() config.Config
-
-func (gw *Gateway) GetNodeID() string
- GetNodeID reads NodeID safely.
-
-func (gw *Gateway) GetStorageForApi(apiID string) (ExtendedOsinStorageInterface, int, error)
-
-func (gw *Gateway) InitHostCheckManager(ctx context.Context, store storage.Handler)
-
-func (gw *Gateway) InitializeRPCCache()
-
-func (gw *Gateway) LoadAPI(specs ...*APISpec) (out []*APISpec)
-
-func (gw *Gateway) LoadDefinitionsFromRPCBackup() ([]*APISpec, error)
-
-func (gw *Gateway) LoadPoliciesFromDashboard(endpoint, secret string, allowExplicit bool) (map[string]user.Policy, error)
- LoadPoliciesFromDashboard will connect and download Policies from a Tyk
- Dashboard instance.
-
-func (gw *Gateway) LoadPoliciesFromRPC(store RPCDataLoader, orgId string, allowExplicit bool) (map[string]user.Policy, error)
-
-func (gw *Gateway) LoadPoliciesFromRPCBackup() (map[string]user.Policy, error)
-
-func (gw *Gateway) LoadSampleAPI(def string) (spec *APISpec)
-
-func (gw *Gateway) MarshalJSON() ([]byte, error)
-
-func (gw *Gateway) MonitorApplicationInstrumentation()
-
-func (gw *Gateway) NewGRPCDispatcher() (coprocess.Dispatcher, error)
- NewGRPCDispatcher wraps all the actions needed for this CP.
-
-func (gw *Gateway) NewMultiTargetProxy(spec *APISpec, logger *logrus.Entry) *MultiTargetProxy
-
-func (gw *Gateway) NotifyCurrentServerStatus()
-
-func (gw *Gateway) PolicyByID(id string) (user.Policy, bool)
- PolicyByID will return a Policy matching the passed Policy ID.
-
-func (gw *Gateway) PolicyCount() int
- PolicyCount will return the number of policies loaded in the gateway.
-
-func (gw *Gateway) PolicyIDs() []string
- PolicyIDs returns a list of IDs for each policy loaded in the gateway.
-
-func (gw *Gateway) ProcessOauthClientsOps(clients map[string]string)
- ProcessOauthClientsOps performs the appropriate action for the received
- clients it can be any of the Create,Update and Delete operations
-
-func (gw *Gateway) ProcessSingleOauthClientEvent(apiId, oauthClientId, orgID, event string)
-
-func (gw *Gateway) RevokeAllTokensHandler(w http.ResponseWriter, r *http.Request)
-
-func (gw *Gateway) RevokeTokenHandler(w http.ResponseWriter, r *http.Request)
-
-func (gw *Gateway) SetCheckerHostList()
-
-func (gw *Gateway) SetConfig(conf config.Config, skipReload ...bool)
-
-func (gw *Gateway) SetNodeID(nodeID string)
- SetNodeID writes NodeID safely.
-
-func (gw *Gateway) SetPolicies(pols map[string]user.Policy)
- SetPolicies updates the internal policy map with a new policy map.
-
-func (gw *Gateway) SetPoliciesByID(pols ...user.Policy)
- SetPoliciesByID will update the internal policiesByID map with new policies.
- The key used will be the policy ID.
-
-func (gw *Gateway) SetupNewRelic() (app newrelic.Application)
- SetupNewRelic creates new newrelic.Application instance
-
-func (gw *Gateway) SignatureVerifier() (goverify.Verifier, error)
- SignatureVerifier returns a verifier to use for validating signatures.
- It is configured with the PublicKeyPath value in gateway config.
-
-func (gw *Gateway) TykNewSingleHostReverseProxy(target *url.URL, spec *APISpec, logger *logrus.Entry) *ReverseProxy
- TykNewSingleHostReverseProxy returns a new ReverseProxy that rewrites URLs
- to the scheme, host, and base path provided in target. If the target's path
- is "/base" and the incoming request was for "/dir", the target request will
- be for /base/dir. This version modifies the stdlib version by also setting
- the host to the target, this allows us to work with heroku and other such
- providers
-
-func (gw *Gateway) TykOsinNewServer(config *osin.ServerConfig, storage ExtendedOsinStorageInterface) *TykOsinServer
- TykOsinNewServer creates a new server instance, but uses an extended
- interface so we can SetClient() too.
-
-func (gw *Gateway) UnmarshalJSON(data []byte) error
-
-type GetConfigPayload struct {
- FromHostname string
- FromNodeID string
- TimeStamp int64
-}
-
-type GoAnalyticsPlugin struct {
- Path string // path to .so file
- FuncName string // function symbol to look up
-
- // Has unexported fields.
-}
-
-type GoPluginMiddleware struct {
- *BaseMiddleware
-
- Path string // path to .so file
- SymbolName string // function symbol to look up
-
- Meta apidef.GoPluginMeta
- APILevel bool
- // Has unexported fields.
-}
- GoPluginMiddleware is a generic middleware that will execute Go-plugin code
- before continuing
-
-func (m *GoPluginMiddleware) EnabledForSpec() bool
-
-func (m *GoPluginMiddleware) Name() string
-
-func (m *GoPluginMiddleware) ProcessRequest(w http.ResponseWriter, r *http.Request, conf interface{}) (err error, respCode int)
-
-type GranularAccessFailReason int
-
-const (
- GranularAccessFailReasonNone GranularAccessFailReason = iota
- GranularAccessFailReasonInternalError
- GranularAccessFailReasonValidationError
-)
-type GranularAccessMiddleware struct {
- *BaseMiddleware
-}
- GranularAccessMiddleware will check if a URL is specifically enabled for the
- key
-
-func (m *GranularAccessMiddleware) Name() string
-
-func (m *GranularAccessMiddleware) ProcessRequest(w http.ResponseWriter, r *http.Request, _ interface{}) (error, int)
- ProcessRequest will run any checks on the request on the way through the
- system, return an error to have the chain fail
-
-type GraphQLComplexityMiddleware struct {
- *BaseMiddleware
-}
-
-func (m *GraphQLComplexityMiddleware) EnabledForSpec() bool
-
-func (m *GraphQLComplexityMiddleware) Name() string
-
-func (m *GraphQLComplexityMiddleware) ProcessRequest(w http.ResponseWriter, r *http.Request, _ interface{}) (error, int)
- ProcessRequest will run any checks on the request on the way through the
- system, return an error to have the chain fail
-
-type GraphQLGranularAccessMiddleware struct {
- *BaseMiddleware
-}
-
-func (m *GraphQLGranularAccessMiddleware) EnabledForSpec() bool
-
-func (m *GraphQLGranularAccessMiddleware) Name() string
-
-func (m *GraphQLGranularAccessMiddleware) ProcessRequest(w http.ResponseWriter, r *http.Request, _ interface{}) (error, int)
- ProcessRequest will run any checks on the request on the way through the
- system, return an error to have the chain fail
-
-type GraphQLMiddleware struct {
- *BaseMiddleware
-}
-
-func (m *GraphQLMiddleware) EnabledForSpec() bool
-
-func (m *GraphQLMiddleware) Init()
-
-func (m *GraphQLMiddleware) Name() string
-
-func (m *GraphQLMiddleware) OnBeforeFetch(ctx resolve.HookContext, input []byte)
-
-func (m *GraphQLMiddleware) OnBeforeStart(reqCtx context.Context, operation *gql.Request) error
- OnBeforeStart - is a graphql.WebsocketBeforeStartHook which allows to
- perform security checks for all operations over websocket connections
-
-func (m *GraphQLMiddleware) OnData(ctx resolve.HookContext, output []byte, singleFlight bool)
-
-func (m *GraphQLMiddleware) OnError(ctx resolve.HookContext, output []byte, singleFlight bool)
-
-func (m *GraphQLMiddleware) ProcessRequest(w http.ResponseWriter, r *http.Request, _ interface{}) (error, int)
-
-type GraphQLRequest struct {
- Query string `json:"query"`
- Variables json.RawMessage `json:"variables"`
-}
-
-type GraphqlComplexityChecker struct {
- // Has unexported fields.
-}
-
-func (c *GraphqlComplexityChecker) DepthLimitEnabled(accessDef *user.AccessDefinition) bool
-
-func (c *GraphqlComplexityChecker) DepthLimitExceeded(gqlRequest *graphql.Request, accessDef *user.AccessDefinition, schema *graphql.Schema) ComplexityFailReason
-
-type GraphqlGranularAccessChecker struct{}
-
-func (g *GraphqlGranularAccessChecker) CheckGraphqlRequestFieldAllowance(gqlRequest *graphql.Request, accessDef *user.AccessDefinition, schema *graphql.Schema) GraphqlGranularAccessResult
-
-type GraphqlGranularAccessResult struct {
- // Has unexported fields.
-}
-
-type HMACFieldValues struct {
- KeyID string
- Algorthm string
- Headers []string
- Signature string
-}
-
-type HTTPBundleGetter struct {
- URL string
- InsecureSkipVerify bool
-}
- HTTPBundleGetter is a simple HTTP BundleGetter.
-
-func (g *HTTPBundleGetter) Get() ([]byte, error)
- Get performs an HTTP GET request.
-
-type HTTPDashboardHandler struct {
- RegistrationEndpoint string
- DeRegistrationEndpoint string
- HeartBeatEndpoint string
- KeyQuotaTriggerEndpoint string
-
- Secret string
-
- Gw *Gateway `json:"-"`
- // Has unexported fields.
-}
-
-func (h *HTTPDashboardHandler) DeRegister() error
-
-func (h *HTTPDashboardHandler) Init() error
-
-func (h *HTTPDashboardHandler) NotifyDashboardOfEvent(event interface{}) error
- NotifyDashboardOfEvent acts as a form of event which informs the dashboard
- of a key which has reached a certain usage quota
-
-func (h *HTTPDashboardHandler) Ping() error
-
-func (h *HTTPDashboardHandler) Register() error
-
-func (h *HTTPDashboardHandler) StartBeating() error
-
-func (h *HTTPDashboardHandler) StopBeating()
-
-type HTTPSignatureValidationMiddleware struct {
- *BaseMiddleware
-
- // Has unexported fields.
-}
- HTTPSignatureValidationMiddleware will check if the request has a signature,
- and if the request is allowed through
-
-func (k *HTTPSignatureValidationMiddleware) EnabledForSpec() bool
-
-func (hm *HTTPSignatureValidationMiddleware) Init()
-
-func (hm *HTTPSignatureValidationMiddleware) Name() string
-
-func (hm *HTTPSignatureValidationMiddleware) ProcessRequest(w http.ResponseWriter, r *http.Request, _ interface{}) (error, int)
-
-type HeaderInjector struct {
- BaseTykResponseHandler
- // Has unexported fields.
-}
-
-func (h *HeaderInjector) Base() *BaseTykResponseHandler
-
-func (h *HeaderInjector) Enabled() bool
-
-func (h *HeaderInjector) HandleError(rw http.ResponseWriter, req *http.Request)
-
-func (h *HeaderInjector) HandleResponse(rw http.ResponseWriter, res *http.Response, req *http.Request, ses *user.SessionState) error
-
-func (h *HeaderInjector) Init(c interface{}, spec *APISpec) error
-
-func (*HeaderInjector) Name() string
-
-type HeaderInjectorOptions struct {
- AddHeaders map[string]string `mapstructure:"add_headers" bson:"add_headers" json:"add_headers"`
- RemoveHeaders []string `mapstructure:"remove_headers" bson:"remove_headers" json:"remove_headers"`
-}
-
-type HeaderTransform struct {
- BaseTykResponseHandler
- // Has unexported fields.
-}
-
-func (h *HeaderTransform) Base() *BaseTykResponseHandler
-
-func (h *HeaderTransform) HandleError(rw http.ResponseWriter, req *http.Request)
-
-func (h *HeaderTransform) HandleResponse(rw http.ResponseWriter,
- res *http.Response, req *http.Request, ses *user.SessionState) error
-
-func (h *HeaderTransform) Init(c interface{}, spec *APISpec) error
-
-func (h *HeaderTransform) Name() string
-
-type HeaderTransformOptions struct {
- RevProxyTransform RevProxyTransform `mapstructure:"rev_proxy_header_cleanup" bson:"rev_proxy_header_cleanup" json:"rev_proxy_header_cleanup"`
-}
-
-type HealthCheckValues struct {
- ThrottledRequestsPS float64 `bson:"throttle_reqests_per_second,omitempty" json:"throttle_reqests_per_second"`
- QuotaViolationsPS float64 `bson:"quota_violations_per_second,omitempty" json:"quota_violations_per_second"`
- KeyFailuresPS float64 `bson:"key_failures_per_second,omitempty" json:"key_failures_per_second"`
- AvgUpstreamLatency float64 `bson:"average_upstream_latency,omitempty" json:"average_upstream_latency"`
- AvgRequestsPS float64 `bson:"average_requests_per_second,omitempty" json:"average_requests_per_second"`
-}
-
-type HealthChecker interface {
- Init(storage.Handler)
- ApiHealthValues() (HealthCheckValues, error)
- StoreCounterVal(HealthPrefix, string)
-}
-
-type HealthPrefix string
-
-const (
- Throttle HealthPrefix = "Throttle"
- QuotaViolation HealthPrefix = "QuotaViolation"
- KeyFailure HealthPrefix = "KeyFailure"
- RequestLog HealthPrefix = "Request"
- BlockedRequestLog HealthPrefix = "BlockedRequest"
-)
-type HostCheckCallBacks struct {
- // Up is a callback invoked when the host checker identifies a host to be up.
- Up func(context.Context, HostHealthReport)
-
- // Ping when provided this callback will be invoked on every every call to a
- // remote host.
- Ping func(context.Context, HostHealthReport)
-
- // Fail is invoked when the host checker decides a host is not healthy.
- Fail func(context.Context, HostHealthReport)
-}
- HostCheckCallBacks defines call backs which will be invoked on different
- states of the health check
-
-type HostCheckerManager struct {
- Gw *Gateway `json:"-"`
- Id string
-
- // Has unexported fields.
-}
-
-func (hc *HostCheckerManager) AmIPolling() bool
-
-func (hc *HostCheckerManager) CheckActivePollerLoop(ctx context.Context)
- CheckActivePollerLoop manages the state of the HostCheckerManager UptimeTest
- polling loop, this will start the checking loop if it hasnt been started
- yet.
-
- The check happens in a 10 seconds interval.
-
-func (hc *HostCheckerManager) DoServiceDiscoveryListUpdateForID(apiID string)
-
-func (hc *HostCheckerManager) GenerateCheckerId()
-
-func (hc *HostCheckerManager) HostDown(urlStr string) bool
-
-func (hc *HostCheckerManager) Init(store storage.Handler)
-
-func (hc *HostCheckerManager) ListFromService(apiID string) ([]HostData, error)
-
-func (hc *HostCheckerManager) OnHostBackUp(ctx context.Context, report HostHealthReport)
-
-func (hc *HostCheckerManager) OnHostDown(ctx context.Context, report HostHealthReport)
-
-func (hc *HostCheckerManager) OnHostReport(ctx context.Context, report HostHealthReport)
-
-func (hc *HostCheckerManager) PrepareTrackingHost(checkObject apidef.HostCheckObject, apiID string) (HostData, error)
-
-func (hc *HostCheckerManager) RecordUptimeAnalytics(report HostHealthReport) error
- RecordHit will store an AnalyticsRecord in Redis
-
-func (hc *HostCheckerManager) Start(ctx context.Context)
-
-func (hc *HostCheckerManager) StartPoller(ctx context.Context)
-
-func (hc *HostCheckerManager) StopPoller()
-
-func (hc *HostCheckerManager) UpdateTrackingList(hd []HostData)
-
-func (hc *HostCheckerManager) UpdateTrackingListByAPIID(hd []HostData, apiId string)
-
-type HostData struct {
- CheckURL string
- Protocol string
- Timeout time.Duration
- EnableProxyProtocol bool
- Commands []apidef.CheckCommand
- Method string
- Headers map[string]string
- Body string
- MetaData map[string]string
-}
-
-type HostHealthReport struct {
- HostData
- ResponseCode int
- Latency float64
- IsTCPError bool
-}
-
-type HostSample struct {
- // Has unexported fields.
-}
-
-type HostUptimeChecker struct {
- HostList map[string]HostData
-
- Gw *Gateway `json:"-"`
-
- // Has unexported fields.
-}
-
-func (h *HostUptimeChecker) CheckHost(toCheck HostData)
-
-func (h *HostUptimeChecker) HostCheckLoop(ctx context.Context)
-
-func (h *HostUptimeChecker) HostReporter(ctx context.Context)
-
-func (h *HostUptimeChecker) Init(workers, triggerLimit, timeout int, hostList map[string]HostData, cb HostCheckCallBacks)
-
-func (h *HostUptimeChecker) ResetList(hostList map[string]HostData)
-
-func (h *HostUptimeChecker) Start(ctx context.Context)
-
-func (h *HostUptimeChecker) Stop()
-
-type IPBlackListMiddleware struct {
- *BaseMiddleware
-}
- IPBlackListMiddleware lets you define a list of IPs to block from upstream
-
-func (i *IPBlackListMiddleware) EnabledForSpec() bool
-
-func (i *IPBlackListMiddleware) Name() string
-
-func (i *IPBlackListMiddleware) ProcessRequest(w http.ResponseWriter, r *http.Request, _ interface{}) (error, int)
- ProcessRequest will run any checks on the request on the way through the
- system, return an error to have the chain fail
-
-type IPWhiteListMiddleware struct {
- *BaseMiddleware
-}
- IPWhiteListMiddleware lets you define a list of IPs to allow upstream
-
-func (i *IPWhiteListMiddleware) EnabledForSpec() bool
-
-func (i *IPWhiteListMiddleware) Name() string
-
-func (i *IPWhiteListMiddleware) ProcessRequest(w http.ResponseWriter, r *http.Request, _ interface{}) (error, int)
- ProcessRequest will run any checks on the request on the way through the
- system, return an error to have the chain fail
-
-type IdExtractor interface {
- ExtractAndCheck(*http.Request) (string, ReturnOverrides)
- GenerateSessionID(string, *BaseMiddleware) string
-}
- IdExtractor is the base interface for an ID extractor.
-
-type InterfaceNotification struct {
- Type string
- Message string
- OrgID string
- Timestamp time.Time
-}
-
-type JSVM struct {
- Spec *APISpec
- VM *otto.Otto `json:"-"`
- Timeout time.Duration
- Log *logrus.Entry `json:"-"` // logger used by the JS code
- RawLog *logrus.Logger `json:"-"` // logger used by `rawlog` func to avoid formatting
- Gw *Gateway `json:"-"`
-}
-
-func (j *JSVM) DeInit()
-
-func (j *JSVM) Init(spec *APISpec, logger *logrus.Entry, gw *Gateway)
- Init creates the JSVM with the core library and sets up a default timeout.
-
-func (j *JSVM) LoadJSPaths(paths []string, prefix string)
- LoadJSPaths will load JS classes and functionality in to the VM by file
-
-func (j *JSVM) LoadTykJSApi()
-
-type JSVMContextGlobal struct {
- APIID string
- OrgID string
-}
-
-type JSVMEventHandler struct {
- Spec *APISpec
- SpecJSON string
- Gw *Gateway `json:"-"`
- // Has unexported fields.
-}
- JSVMEventHandler is a scriptable event handler
-
-func (l *JSVMEventHandler) HandleEvent(em config.EventMessage)
- HandleEvent will be fired when the event handler instance is found in an
- APISpec EventPaths object during a request chain
-
-func (l *JSVMEventHandler) Init(handlerConf interface{}) error
- New enables the intitialisation of event handler instances when they are
- created on ApiSpec creation
-
-type JWK struct {
- Alg string `json:"alg"`
- Kty string `json:"kty"`
- Use string `json:"use"`
- X5c []string `json:"x5c"`
- N string `json:"n"`
- E string `json:"e"`
- KID string `json:"kid"`
- X5t string `json:"x5t"`
-}
-
-type JWKs struct {
- Keys []JWK `json:"keys"`
-}
-
-type JWTMiddleware struct {
- *BaseMiddleware
-}
-
-func (k *JWTMiddleware) EnabledForSpec() bool
-
-func (k *JWTMiddleware) Name() string
-
-func (k *JWTMiddleware) ProcessRequest(w http.ResponseWriter, r *http.Request, _ interface{}) (error, int)
-
-type KeyExpired struct {
- *BaseMiddleware
-}
- KeyExpired middleware will check if the requesting key is expired or not.
- It makes use of the authManager to do so.
-
-func (k *KeyExpired) Name() string
-
-func (k *KeyExpired) ProcessRequest(w http.ResponseWriter, r *http.Request, _ interface{}) (error, int)
- ProcessRequest will run any checks on the request on the way through the
- system, return an error to have the chain fail
-
-type LDAPStorageHandler struct {
- LDAPServer string
- LDAPPort uint16
- BaseDN string
- Attributes []string
- SessionAttributeName string
- SearchString string
- // Has unexported fields.
-}
- LDAPStorageHandler implements storage.Handler, this is a read-only
- implementation to access keys from an LDAP service
-
-func (l LDAPStorageHandler) AddToSet(keyName, value string)
-
-func (l LDAPStorageHandler) AddToSortedSet(keyName, value string, score float64)
-
-func (l LDAPStorageHandler) AppendToSet(keyName, value string)
-
-func (l *LDAPStorageHandler) Connect() bool
-
-func (l *LDAPStorageHandler) Decrement(keyName string)
-
-func (r *LDAPStorageHandler) DeleteAllKeys() bool
-
-func (l *LDAPStorageHandler) DeleteKey(cn string) bool
-
-func (l *LDAPStorageHandler) DeleteKeys(keys []string) bool
-
-func (l *LDAPStorageHandler) DeleteRawKey(cn string) bool
-
-func (l *LDAPStorageHandler) DeleteRawKeys([]string) bool
-
-func (l LDAPStorageHandler) DeleteScanMatch(pattern string) bool
-
-func (l LDAPStorageHandler) Exists(keyName string) (bool, error)
-
-func (l LDAPStorageHandler) GetAndDeleteSet(keyName string) []interface{}
-
-func (l *LDAPStorageHandler) GetExp(cn string) (int64, error)
-
-func (l *LDAPStorageHandler) GetKey(filter string) (string, error)
-
-func (l LDAPStorageHandler) GetKeyPrefix() string
-
-func (l *LDAPStorageHandler) GetKeys(filter string) []string
-
-func (l *LDAPStorageHandler) GetKeysAndValues() map[string]string
-
-func (l *LDAPStorageHandler) GetKeysAndValuesWithFilter(filter string) map[string]string
-
-func (l *LDAPStorageHandler) GetListRange(keyName string, from, to int64) ([]string, error)
-
-func (r *LDAPStorageHandler) GetMultiKey(keyNames []string) ([]string, error)
-
-func (l *LDAPStorageHandler) GetRawKey(filter string) (string, error)
-
-func (l *LDAPStorageHandler) GetRollingWindow(keyName string, per int64, pipeline bool) (int, []interface{})
-
-func (l LDAPStorageHandler) GetSet(keyName string) (map[string]string, error)
-
-func (l LDAPStorageHandler) GetSortedSetRange(keyName, scoreFrom, scoreTo string) ([]string, []float64, error)
-
-func (l *LDAPStorageHandler) IncrememntWithExpire(keyName string, timeout int64) int64
-
-func (l *LDAPStorageHandler) LoadConfFromMeta(meta map[string]interface{})
-
-func (l LDAPStorageHandler) RemoveFromList(keyName, value string) error
-
-func (l LDAPStorageHandler) RemoveFromSet(keyName, value string)
-
-func (l LDAPStorageHandler) RemoveSortedSetRange(keyName, scoreFrom, scoreTo string) error
-
-func (l *LDAPStorageHandler) SetExp(cn string, exp int64) error
-
-func (l *LDAPStorageHandler) SetKey(cn, session string, timeout int64) error
-
-func (l *LDAPStorageHandler) SetRawKey(cn, session string, timeout int64) error
-
-func (l *LDAPStorageHandler) SetRollingWindow(keyName string, per int64, val string, pipeline bool) (int, []interface{})
-
-type LogMessageEventHandler struct {
- Gw *Gateway `json:"-"`
- // Has unexported fields.
-}
- LogMessageEventHandler is a sample Event Handler
-
-func (l *LogMessageEventHandler) HandleEvent(em config.EventMessage)
- HandleEvent will be fired when the event handler instance is found in an
- APISpec EventPaths object during a request chain
-
-func (l *LogMessageEventHandler) Init(handlerConf interface{}) error
- New enables the intitialisation of event handler instances when they are
- created on ApiSpec creation
-
-type MethodNotAllowedHandler struct{}
-
-func (m MethodNotAllowedHandler) ServeHTTP(w http.ResponseWriter, r *http.Request)
-
-type MiddlewareContextVars struct {
- *BaseMiddleware
-}
-
-func (m *MiddlewareContextVars) EnabledForSpec() bool
-
-func (m *MiddlewareContextVars) Name() string
-
-func (m *MiddlewareContextVars) ProcessRequest(w http.ResponseWriter, r *http.Request, _ interface{}) (error, int)
- ProcessRequest will run any checks on the request on the way through the
- system, return an error to have the chain fail
-
-type MiniRequestObject struct {
- Headers map[string][]string
- SetHeaders map[string]string
- DeleteHeaders []string
- Body []byte
- URL string
- Params map[string][]string
- AddParams map[string]string
- ExtendedParams map[strin...*[Comment body truncated]* |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
TT-14085: Remove the pmylund/go-cache dependency (#6871)
User description
TT-14085
This implements a subset of go-cache as used in gateway under
internal/cache, dropping the dependency.
https://tyktech.atlassian.net/browse/TT-14085
PR Type
Enhancement, Tests, Bug fix
Description
Replaced
pmylund/go-cache
with a custom internal cacheimplementation.
Introduced a new
internal/cache
package with cache, item, andjanitor functionalities.
Updated DNS cache, gateway, and regexp modules to use the new internal
cache.
Added comprehensive unit tests for the new cache implementation and
its components.
Changes walkthrough 📝
8 files
Updated DNS cache to use internal cache
Refactored gateway cache setup and teardown
Implemented custom cache with expiration and cleanup
Added constants for cache expiration
Added cache item structure with expiration logic
Implemented janitor for periodic cache cleanup
Added repository interface for cache abstraction
Updated regexp cache to use internal cache
5 files
Added cache cleanup in gateway test utilities
Added unit tests for custom cache implementation
Added unit tests for cache item expiration logic
Added unit tests for janitor functionality
Added unit tests for cache repository implementation
2 files
Removed `pmylund/go-cache` dependency
Removed `pmylund/go-cache` entries
1 files
Added taskfile for cache package development
...
in the comments thread for any questions about PR-Agentusage.
for more information.
Co-authored-by: Tit Petric [email protected]