cache

package
v0.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 1, 2023 License: MIT Imports: 17 Imported by: 0

Documentation

Index

Constants

View Source
const (
	HeaderCacheControl = "Cache-Control"
	HeaderDate         = "Date"

	HeaderAuthorization = "Authorization"

	// Request headers
	HeaderPragma            = "Pragma"
	HeaderIfRange           = "If-Range"
	HeaderIfMatch           = "If-Match"
	HeaderIfNoneMatch       = "If-None-Match"
	HeaderIfModifiedSince   = "If-Modified-Since"
	HeaderIfUnmodifiedSince = "If-Unmodified-Since"

	// Response headers
	HeaderAge          = "Age"
	HeaderEtag         = "Etag"
	HeaderExpires      = "Expires"
	HeaderLastModified = "Last-Modified"
)
View Source
const (
	HIT  = "HIT"
	MISS = "MISS"
)

Variables

View Source
var DefaultTTL = 120 * time.Second

DefaultTTL is the default time-to-live for cache entries.

Functions

func CalculateAge

func CalculateAge(headers *http.Header, responseTime time.Time, now time.Time) time.Duration

CalculateAge calculates the value of Age headers in seconds. https://httpwg.org/specs/rfc7234.html#age.calculations

func Contains

func Contains[K comparable, V any](m map[K]V, k K) bool

Contains checks if the given key is in the map.

func IsCacheableRequest

func IsCacheableRequest(req *http.Request) bool

IsCacheableRequest checks if a request can be served from cache. This does not depend on cache-control headers as request cache-control headers only decide whether validation is required and whether the response can be cached.

func IsCacheableResponse

func IsCacheableResponse(res *http.Response) bool

IsCacheableResponse checks if a response can be stored in cache. Note that if a request is not cacheable according to `CanServeRequestFromCache` then its response is also not cacheable. Hence, CanServeRequestFromCache and `IsCacheableResponse` together should cover the cacheability of the response.

func Max

func Max(x, y int64) int64

Max returns the max of the given values.

func StableHashKey

func StableHashKey(k Key) uint64

Produces a hash of key that is consistent across restarts, architectures, builds, and configurations. Caches that store persistent entries based on a 64-bit hash should (but are not required to) use stableHashKey.

Types

type Content

type Content struct {
	// Type is the content type to be ignored by the cache.
	Type string `yaml:"type" json:"type"`

	// TypeMatcher contains the compiled `Type` patterns.
	TypeMatcher *regexp.Regexp `json:"-"`

	// Size is the max content size in bytes.
	Size int `yaml:"size,omitempty" json:"size,omitempty"`
}

Content holds the specific content-type and max content size used for excluding responses from caching. Every response matching the specified content type regex and exceeding the max content size is excluded from cache. If max size is not specified, only type is used to decide wethter to cache the response or not.

type Entry

type Entry struct {
	// Body is the entry body as a serialized http.Response
	Body []byte

	// Timestamp is the time the body was last modified.
	Timestamp int64
}

Entry is the cache entry.

func DecodeEntry

func DecodeEntry(data []byte) (*Entry, error)

DecodeEntry decodes a byte array into an Entry.

func (*Entry) Encode

func (e *Entry) Encode() ([]byte, error)

Encode encodes an entry into a byte array.

type EntryStatus

type EntryStatus int

EntryStatus is the state of a cached response.

const (
	// EntryInvalid indicates that the cached response is not usable or valid (cache miss).
	EntryInvalid EntryStatus = iota

	// EntryOk indicates that the cached response is valid and can be used (cache hit).
	EntryOk

	// EntryRequiresValidation indicates that the cached response needs to be validated.
	EntryRequiresValidation

	// EntryError indicates an error occurred while retrieving the response.
	EntryLookupError
)

func (EntryStatus) String

func (s EntryStatus) String() string

String returns the Entry Status as a string.

type Exclude

type Exclude struct {
	// Path contains the paths to be ignored by the cache.
	Path []string `yaml:"path" json:"path"`

	// PathMatcher contains the compile `Path` patterns.
	PathMatcher []*regexp.Regexp `json:"-"`

	// Header contains the headers to be ignored by the cache.
	Header map[string]string `yaml:"header" json:"header"`

	// Content contains the content types to be ignored by the cache.
	Content []Content `yaml:"content" json:"content"`
}

Exclude holds the cache ignore information.

type HttpCache

type HttpCache struct {
	// contains filtered or unexported fields
}

HttpCache is the http cache.

func NewHttpCache

func NewHttpCache(config *HttpCacheConfig, pdr provider.Provider) (*HttpCache, error)

NewHttpCache creates a new http cache.

func (*HttpCache) Config

func (c *HttpCache) Config() *HttpCacheConfig

Config returns the current cache config.

func (*HttpCache) DefaultCacheControl

func (c *HttpCache) DefaultCacheControl() string

DefaultCacheControl returns the default cache control.

func (*HttpCache) DefaultTTL

func (c *HttpCache) DefaultTTL() time.Duration

DefaultTTL returns the TTL as specified in the configuration as a valid duration in seconds. If not specified, the default value is returned.

func (*HttpCache) Delete

func (c *HttpCache) Delete(ctx context.Context, lookup *LookupRequest)

Deletes deletes the response matching the request key from the cache.

func (*HttpCache) FetchResponse

func (c *HttpCache) FetchResponse(ctx context.Context, lookup LookupRequest) *LookupResult

FetchResponse fetches a response matching the given request.

func (*HttpCache) ForceCacheControl

func (c *HttpCache) ForceCacheControl() bool

ForceCacheControl specifies whether to overwrite an existing cache-control header.

func (*HttpCache) IsExcludedContent

func (c *HttpCache) IsExcludedContent(content string, length int64) bool

IsExcludedContent checks if the specific responses content-type and size is excluded from caching.

func (*HttpCache) IsExcludedHeader

func (c *HttpCache) IsExcludedHeader(h http.Header) bool

IsExcludedHeader checks whether a specific HTTP header is excluded from caching.

func (*HttpCache) IsExcludedPath

func (c *HttpCache) IsExcludedPath(p string) bool

IsExcludedPath checks whether a specific path is excluded from caching.

func (*HttpCache) MarkCachedResponses

func (c *HttpCache) MarkCachedResponses() bool

MarkCachedResponses returns true if cached responses should be marked.

func (*HttpCache) PathTTL

func (c *HttpCache) PathTTL(p string) time.Duration

PathTTL matches a path with the configured path regex. If a match is found, the corresponding TTL is returned, otherwise DefaultTTL.

func (*HttpCache) StoreResponse

func (c *HttpCache) StoreResponse(_ context.Context, lookup *LookupRequest,
	response *http.Response, responseTime time.Time)

StoreResponse stores a response in the cache.

func (*HttpCache) Strict added in v0.2.0

func (c *HttpCache) Strict() bool

Strict returns true if the cache mode is `strict`.

func (*HttpCache) UpdateConfig

func (c *HttpCache) UpdateConfig(config *HttpCacheConfig)

UpdateConfig updates the cache config in a concurrent safe way.

func (*HttpCache) XCacheHeader

func (c *HttpCache) XCacheHeader() string

XCacheHeader returns the XCache debug header key.

type HttpCacheConfig

type HttpCacheConfig struct {
	// Strict specifies the cache mode. When strict mode is enabled (default), the http cache
	// respects the directives set in the Cache-Control header. If disabled (cache mode all),
	// the http cache ignores the Cache-Control directives and stores every response until it
	// is expired by its TTL (time-to-live).
	Strict bool `yaml:"strict" json:"strict"`

	// XCache specifies if the XCache debug header should be attached to responses.
	// If the response exists in the cache the header value is HIT, MISS otherwise.
	XCache bool `yaml:"x_header" json:"x_header"`

	// XCacheName is the name of the X-Cache header.
	XCacheName string `yaml:"x_header_name" json:"x_header_name"`

	// Default TTL is the default TTL for cache entries. Overrides 'DefaultTTL'.
	DefaultTTL string `yaml:"default_ttl" json:"default_ttl"`

	// DefaultCacheControl specifies a default cache-control header.
	DefaultCacheControl string `yaml:"default_cache_control" json:"default_cache_control"`

	// ForceCacheControl specifies whether to overwrite an existing cache-control header.
	ForceCacheControl bool `yaml:"force_cache_control" json:"force_cache_control"`

	// Timeouts holds the TTLs per path/resource.
	Timeouts []Timeout `yaml:"timeouts" json:"timeouts"`

	// Exclude contains the cache exclude configuration.
	Exclude *Exclude `yaml:"exclude" json:"exclude"`
}

HttpCacheConfig holds the http cache configuration.

type Key

type Key struct {
	ClusterName string
	Host        string
	Path        string
	Query       string
	Scheme      string
}

Key is the cache key.

func NewKeyFromRequst

func NewKeyFromRequst(req *http.Request) *Key

NewFromRequest creates a cache key from the given request.

func (Key) Hash

func (k Key) Hash() uint64

Hash produces a stable hash of key.

func (Key) String

func (k Key) String() string

String encodes the cache key as string.

type LookupRequest

type LookupRequest struct {
	// Request is the original request.
	Request *http.Request

	// ReqCacheControl holds the parsed request cache control.
	ReqCacheControl RequestCacheControl

	// Key is the cache key generated from the request.
	Key *Key

	// Timestamp is the time this lookup was created.
	Timestamp time.Time
	// contains filtered or unexported fields
}

LookupRequest holds the context for looking up a request.

func NewLookupRequest

func NewLookupRequest(req *http.Request, timestamp time.Time, strict bool) *LookupRequest

NewLookupRequest creates a new lookup request structure.

type LookupResult

type LookupResult struct {
	// Status holds the status of the cached entry.
	Status EntryStatus
	// contains filtered or unexported fields
}

LookupResult wraps the cached response.

func (*LookupResult) Header

func (r *LookupResult) Header() http.Header

Header returns the cached response header.

func (*LookupResult) Response

func (r *LookupResult) Response() *http.Response

Response returns the cached response.

func (*LookupResult) UpdateHeader

func (r *LookupResult) UpdateHeader(header http.Header)

UpdateHeader add any headers to the cached response.

type RequestCacheControl

type RequestCacheControl struct {
	// MustValidate is true if 'no-cache' directive is present.
	// A cached response must not be served without successful validation on the origin.
	MustValidate bool

	// NoStore is true if the 'no-store' directive is present.
	// Any part of either the request or any response to this request must not be cached (stored).
	NoStore bool

	// NoTransform is true if the 'no-transform' directive is present.
	// No transformations should be done to the response of this request, as defined by:
	// https://httpwg.org/specs/rfc7230.html#message.transformations
	NoTransform bool

	// OnlyIfCached is true if the 'only-if-cached' directive is present.
	// The request should be satisfied using a cached response only, or respond with 504 (Gateway Timeout).
	OnlyIfCached bool

	// MaxAge indicates that the client is unwilling to accept a response whose age exceeds the
	// specified duration.
	MaxAge time.Duration

	// MinFresh indicates that the client is willing to accept a response whose freshness lifetime
	// is no less than its current age plus the specified time, i.e. the client is unwilling to
	// receive a cached response that satisfies:
	//   expiration_time - now < min-fresh
	MinFresh time.Duration

	// MaxStale indicates that the client is willing to accept a response that has exceeded its
	// freshness lifetime, i.e. the client is willing to receive a stale response that satisfies:
	//   now - expiration_time < max-stale
	// If max-stale is assigned no value, the client is willing to accept any stale response.
	MaxStale time.Duration
}

RequestCacheControl holds the parsed request cache-control header. https://httpwg.org/specs/rfc7234.html#cache-request-directive

func ParseRequestCacheControl

func ParseRequestCacheControl(header string) RequestCacheControl

ParseRequestCacheControl parses the cache-control header into a RequestCacheControl.

func (*RequestCacheControl) SetDefaults

func (cc *RequestCacheControl) SetDefaults()

SetDefaults sets default values.

type RequestHeaderMap

type RequestHeaderMap = map[string]string

type ResponseCacheControl

type ResponseCacheControl struct {
	// MustValidate is true if 'no-cache' directive is present; arguments are ignored for now.
	// This response must not be used to satisfy subsequent requests without successful validation
	// on the origin.
	MustValidate bool

	// NoStore is true if any of 'no-store' or 'private' directives is present.
	// 'private' arguments are ignored for now so it is equivalent to 'no-store'.
	// Any part of either the immediate request or response must not be cached (stored).
	NoStore bool

	// NoTransform is true if the 'no-transform' directive is present.
	// No transformations should be applied to the response, as defined by:
	// https://httpwg.org/specs/rfc7230.html#message.transformations
	NoTransform bool

	// NoStale is true if any of 'must-revalidate' or 'proxy-revalidate' directives is present.
	// This response must not be served stale without successful validation on the origin.
	NoStale bool

	// IsPublic is true if the 'public' directive is present.
	// This response may be stored, even if the response would normally be non-cacheable or
	// cacheable only within a private cache, see:
	// https://httpwg.org/specs/rfc7234.html#cache-response-directive.public
	IsPublic bool

	// MaxAge is set if to 's-maxage' if present, otherwise is set to 'max-age' if present.
	// Indicates the maximum time after which this response will be considered stale.
	MaxAge time.Duration
}

ResponseCacheControl holds the parsed response cache-control header. https://httpwg.org/specs/rfc7234.html#cache-response-directive

func ParseResponseCacheControl

func ParseResponseCacheControl(header string) ResponseCacheControl

ParseResponseCacheControl parses the Cache Control header into a ResponseCacheControl.

func (*ResponseCacheControl) SetDefaults

func (cc *ResponseCacheControl) SetDefaults()

SetDefaults sets default values.

type ResponseHeaderMap

type ResponseHeaderMap = map[string]string

type Timeout

type Timeout struct {
	// Path is the path the ttl is applied to. String or Regex.
	Path string `yaml:"path" json:"path"`
	// TTL is the corresponing resource ttl.
	TTL time.Duration `yaml:"ttl" json:"ttl"`
	// Matcher holds the compiled regex.
	Matcher *regexp.Regexp `json:"-"`
}

Timeout holds the custom TTL configuration

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL