Documentation
¶
Index ¶
- Constants
- func NewHTTPClient(cfg HTTPClientConfig) *http.Client
- func NewProxyResponseDiffer(opts ...diff.Option) *proxyResponseDiffer
- type CallbackFunc
- type CheckFunc
- type HTTPClientConfig
- type Option
- func WithCallbackFn(fn CallbackFunc) Option
- func WithHTTPClient(client *http.Client) Option
- func WithLiveTimeout(timeout time.Duration) Option
- func WithLogger(logger *slog.Logger) Option
- func WithMaxConcurrentCallbacks(n int) Option
- func WithShadowTimeout(timeout time.Duration) Option
- func WithShouldProxyToShadow(checks ...CheckFunc) Option
- type Proxy
- type ProxyRequest
- type ProxyResponse
- type SamplingRate
- type ShadowRule
- type ShadowRuleAction
Constants ¶
const ShadowHeader = "X-Mroki-Mode"
ShadowHeader is the fixed header added to requests forwarded to the shadow service so downstream systems can distinguish shadow traffic from live traffic. The name is intentionally not configurable so consumers can rely on a stable convention. The live request path is never modified.
const ShadowHeaderValue = "shadow"
ShadowHeaderValue is the value set on ShadowHeader for shadow requests. Consumers can match it to distinguish a shadow request from a live one even when both upstreams share a host (differing only by path or query).
Variables ¶
This section is empty.
Functions ¶
func NewHTTPClient ¶ added in v1.6.0
func NewHTTPClient(cfg HTTPClientConfig) *http.Client
NewHTTPClient builds an HTTP client for proxying live and shadow traffic. The connection-pool fields from cfg are applied verbatim; the remaining transport settings (timeouts, keep-alive, HTTP/2) are fixed and not configurable.
func NewProxyResponseDiffer ¶
Types ¶
type CallbackFunc ¶
type CallbackFunc func(req ProxyRequest, live, shadow ProxyResponse) error
type CheckFunc ¶
CheckFunc returns true if the request should be proxied to shadow
func MaxBodySizeCheck ¶
MaxBodySizeCheck skips shadow for large or chunked bodies maxBytes <= 0 means unlimited (always returns true)
func SamplingRateCheck ¶
func SamplingRateCheck(rate *SamplingRate) CheckFunc
SamplingRateCheck skips shadow based on sampling probability. rate == nil means always sample (always returns true). rate=1.0 and rate=0.0 use fast paths without RNG computation.
func ShadowRulesCheck ¶ added in v1.6.0
func ShadowRulesCheck(rules []ShadowRule) CheckFunc
ShadowRulesCheck evaluates an ordered list of shadow rules against incoming requests. Rules are evaluated in definition order; first match wins. Unmatched requests are allowed (shadowed).
type HTTPClientConfig ¶ added in v1.6.0
type HTTPClientConfig struct {
// MaxIdleConns is the maximum number of idle connections across all hosts.
MaxIdleConns int
// MaxIdleConnsPerHost is the maximum number of idle connections per host.
MaxIdleConnsPerHost int
// MaxConnsPerHost limits the total number of connections per host.
MaxConnsPerHost int
// IdleConnTimeout is how long an idle connection is kept before closing.
IdleConnTimeout time.Duration
}
HTTPClientConfig holds the tunable connection-pool settings for the proxy's HTTP client. Values are applied verbatim by NewHTTPClient — net/http's zero semantics apply (0 means "no limit", or for IdleConnTimeout "no timeout"). This package is intentionally unopinionated: it holds no operational defaults. Callers that need tuned pool sizes (e.g. the proxy binary's config layer) own those defaults and pass them in.
type Option ¶
type Option func(*Proxy)
func WithCallbackFn ¶
func WithCallbackFn(fn CallbackFunc) Option
func WithHTTPClient ¶
WithHTTPClient allows setting a custom HTTP client
func WithLiveTimeout ¶
WithLiveTimeout sets the timeout for live requests
func WithLogger ¶
WithLogger sets the logger for proxy operations
func WithMaxConcurrentCallbacks ¶ added in v1.6.0
WithMaxConcurrentCallbacks bounds the number of background callback goroutines that may run concurrently. When the limit is reached, further shadow comparisons are dropped (with a warning) instead of spawning unbounded goroutines under load — the live response is unaffected. A value <= 0 leaves the limit unset (unbounded); this package holds no default, so the limit is owned by the caller's config layer.
func WithShadowTimeout ¶
WithShadowTimeout sets the timeout for shadow requests
func WithShouldProxyToShadow ¶
WithShouldProxyToShadow adds check functions to determine if shadow should be proxied Multiple checks can be provided - all must return true (AND logic) Can be called multiple times to add more checks
type Proxy ¶
func (*Proxy) ServeHTTP ¶
func (p *Proxy) ServeHTTP(w http.ResponseWriter, r *http.Request)
ServeHTTP implements the http.Handler interface for proxying requests.
Request Flow:
- Reads request body (needed to replay to both services)
- Launches live request with client context + timeout
- Launches shadow request (if sampled) with independent context + timeout
- Waits for live response and returns to client immediately
- Invokes callback with raw responses in background goroutine
Context Handling:
- Live requests inherit the client's request context (r.Context()) This means if the client disconnects, live request is cancelled
- Shadow requests use context.Background() as parent context This makes shadow independent of client connection state, ensuring complete response data collection even if client disconnects
- Both contexts have their own timeout values for safety
Timeouts:
- liveTimeout: Controls how long to wait for live service (blocks client)
- shadowTimeout: Controls how long shadow service can run (doesn't block client)
- Shadow timeout can be longer since it doesn't impact user experience
type ProxyRequest ¶
type ProxyRequest struct {
Method string
Path string
RawQuery string
Headers http.Header
Body []byte
}
ProxyRequest represents the original HTTP request being proxied
type ProxyResponse ¶
type SamplingRate ¶
type SamplingRate float64
func NewSamplingRate ¶
func NewSamplingRate(rate float64) (*SamplingRate, error)
func (SamplingRate) IsZero ¶
func (s SamplingRate) IsZero() bool
IsZero checks if the sampling rate is zero.
func (SamplingRate) Sample ¶
func (s SamplingRate) Sample() bool
Sample decides whether to sample based on the sampling rate. It returns true if the request should be sampled, false otherwise. Fast paths: rate=1.0 always returns true, rate=0.0 always returns false (no RNG).
func (SamplingRate) String ¶
func (s SamplingRate) String() string
String returns the sampling rate as a formatted string.
type ShadowRule ¶ added in v1.6.0
type ShadowRule struct {
// contains filtered or unexported fields
}
ShadowRule is a value object representing a single shadow matching rule. It combines an action (allow/deny), an HTTP method (or "*" for any), and a Caddy-style path pattern.
func BaseShadowRules ¶ added in v1.6.0
func BaseShadowRules() []ShadowRule
BaseShadowRules returns the rules that deny non-idempotent methods (POST, PUT, DELETE, PATCH). They are always appended as the final, catch-all entries of the rule list so that the write-protection cannot be accidentally dropped by configuring custom rules. User-supplied rules are evaluated first and can override these per pattern (e.g. "allow POST:/api/v1/search"). GET, HEAD, and OPTIONS requests are shadowed by default.
A fresh slice is returned on each call so callers cannot mutate shared state.
func NewShadowRule ¶ added in v1.6.0
func NewShadowRule(action ShadowRuleAction, method, pathPattern string) (ShadowRule, error)
NewShadowRule creates a validated ShadowRule from its components.
func ParseShadowRule ¶ added in v1.6.0
func ParseShadowRule(s string) (ShadowRule, error)
ParseShadowRule parses a single rule string of the form "ACTION METHOD:path". Example: "deny POST:*", "allow GET:/api/v1/*".
func ParseShadowRules ¶ added in v1.6.0
func ParseShadowRules(s string) ([]ShadowRule, error)
ParseShadowRules parses a comma-separated list of shadow rules. Example: "deny *:/health/*,allow POST:/api/v1/search,deny POST:*"
func (ShadowRule) Action ¶ added in v1.6.0
func (r ShadowRule) Action() ShadowRuleAction
Action returns the rule's action.
func (ShadowRule) Matches ¶ added in v1.6.0
func (r ShadowRule) Matches(method, reqPath string) bool
Matches reports whether the rule matches the given HTTP method and path.
func (ShadowRule) Method ¶ added in v1.6.0
func (r ShadowRule) Method() string
Method returns the rule's HTTP method.
func (ShadowRule) Path ¶ added in v1.6.0
func (r ShadowRule) Path() string
Path returns the rule's path pattern.
func (ShadowRule) String ¶ added in v1.6.0
func (r ShadowRule) String() string
String returns the rule in its parseable form: "ACTION METHOD:path".
type ShadowRuleAction ¶ added in v1.6.0
type ShadowRuleAction string
ShadowRuleAction determines whether a matching request is allowed or denied from being shadowed.
const ( ShadowRuleAllow ShadowRuleAction = "allow" ShadowRuleDeny ShadowRuleAction = "deny" )