Documentation
¶
Overview ¶
Package precog provides predictive in-memory caching, concurrent request coalescing, and speculative pre-warming middleware for Go HTTP web services and modern browser applications.
Index ¶
- Constants
- Variables
- func BuildSpeculationRulesHeader(predictions []Prediction) string
- func CanonicalCacheKey(method, path, rawQuery, body string) string
- func CanonicalCacheKeyWithHost(method, host, path, rawQuery string, varyVals ...string) string
- func ClientScriptTag() string
- func FastHash64(method, path, rawQuery, body string) uint64
- func FastHash64WithHost(method, host, path, rawQuery string, varyVals ...string) uint64
- func NormalizeRoute(method, path string) string
- func ServeClientAssets(w http.ResponseWriter, r *http.Request) bool
- type AdaptiveMarkovPredictor
- func (p *AdaptiveMarkovPredictor) Predict(sessionID string, topK int) []Prediction
- func (p *AdaptiveMarkovPredictor) Record(sessionID string, method, path, rawQuery string)
- func (p *AdaptiveMarkovPredictor) ResetSession(sessionID string)
- func (p *AdaptiveMarkovPredictor) SeedTransition(fromPattern, toPattern string, weight int)
- type Config
- type DenseMatrixPredictor
- type DensePredictorConfig
- type EndpointRegistry
- type Engine
- func (e *Engine) Close() error
- func (e *Engine) Handler(rootHandler http.Handler) http.Handler
- func (e *Engine) IsRequestAuthenticated(r *http.Request) bool
- func (e *Engine) Middleware(next http.Handler) http.Handler
- func (e *Engine) Predictor() Predictor
- func (e *Engine) Stats() Stats
- func (e *Engine) Store() Store
- type InflightGroup
- type MemoryStore
- type Prediction
- type Predictor
- type PrefetchJob
- type Prefetcher
- type ResponseEntry
- type RistrettoStore
- type ShardedConfig
- type ShardedStore
- func (s *ShardedStore) Close() error
- func (s *ShardedStore) Del(key string)
- func (s *ShardedStore) Get(key string) (*ResponseEntry, bool)
- func (s *ShardedStore) GetByHash(h uint64) (*ResponseEntry, bool)
- func (s *ShardedStore) Set(key string, entry *ResponseEntry, ttl time.Duration) bool
- func (s *ShardedStore) SetByHash(h uint64, entry *ResponseEntry, ttl time.Duration) bool
- type Stats
- type Store
- type Telemetry
- type TieredStore
Constants ¶
const ( // DefaultMaxDenseRoutes defines the maximum route matrix dimension (1024 x 1024). DefaultMaxDenseRoutes = 1024 // NumSessionShards partitions user sessions to minimize mutex contention. NumSessionShards = 64 )
const ( // DefaultShards is 256 striped partitions to eliminate lock contention. DefaultShards = 256 // DefaultMaxShardSize is 1 MB per shard = 256 MB total. DefaultMaxShardSize = 1024 * 1024 )
const InvalidRouteID uint16 = 0xFFFF
InvalidRouteID is returned by GetOrRegister when the registry is at capacity. Callers must treat it as "no route" and skip modeling.
const (
// L1Slots defines the number of direct-mapped atomic cache slots.
L1Slots = 256
)
const MaxIndexedRoutes = 4096
MaxIndexedRoutes is the maximum number of distinct API endpoint patterns supported.
Variables ¶
var ClientScriptBytes []byte
ErrNotShareable is returned to waiting followers when the leader's response cannot be safely shared (e.g. Set-Cookie, private Cache-Control, or non-200 code).
var ErrStreamingResponse = errors.New("precog: response is streaming and cannot be coalesced")
ErrStreamingResponse is returned to waiting followers when the leader's response is detected as a live stream (e.g. SSE) and followers must execute independently.
Functions ¶
func BuildSpeculationRulesHeader ¶
func BuildSpeculationRulesHeader(predictions []Prediction) string
BuildSpeculationRulesHeader formats W3C Speculation Rules prefetch Link headers for modern browser C++ pre-warming.
func CanonicalCacheKey ¶
CanonicalCacheKey computes a deterministic 16-character hexadecimal hash key.
func CanonicalCacheKeyWithHost ¶ added in v1.1.0
CanonicalCacheKeyWithHost computes a deterministic 16-character hexadecimal hash key incorporating the request host and any negotiated Vary header values.
func ClientScriptTag ¶
func ClientScriptTag() string
ClientScriptTag returns the HTML script tag for embedding Precog in any web page or template.
func FastHash64 ¶
FastHash64 computes a 64-bit non-cryptographic hash using xxHash with zero allocations. Query parameters are canonicalized by sorting raw "&"-delimited segments, so parameter order never affects the hash.
func FastHash64WithHost ¶ added in v1.1.0
FastHash64WithHost computes a 64-bit non-cryptographic hash including host, path, canonicalized query parameters, and negotiated Vary values.
func NormalizeRoute ¶
NormalizeRoute converts concrete request paths into parameterized route patterns. Example: "GET /products/44" -> "GET /products/:id"
func ServeClientAssets ¶
func ServeClientAssets(w http.ResponseWriter, r *http.Request) bool
ServeClientAssets handles HTTP requests for /precog/precog.js, /precog/precog.wasm, and /precog/wasm_exec.js. Returns true if the request was handled, false otherwise.
Types ¶
type AdaptiveMarkovPredictor ¶
type AdaptiveMarkovPredictor struct {
// contains filtered or unexported fields
}
AdaptiveMarkovPredictor models navigation sequences using a map-based Markov chain.
func NewAdaptiveMarkovPredictor ¶
func NewAdaptiveMarkovPredictor() *AdaptiveMarkovPredictor
NewAdaptiveMarkovPredictor creates a map-based Markov chain predictor.
func (*AdaptiveMarkovPredictor) Predict ¶
func (p *AdaptiveMarkovPredictor) Predict(sessionID string, topK int) []Prediction
Predict calculates the top-K highest-probability next endpoints for the active session.
func (*AdaptiveMarkovPredictor) Record ¶
func (p *AdaptiveMarkovPredictor) Record(sessionID string, method, path, rawQuery string)
Record observes an API call for a given session and updates the Markov transition matrix.
func (*AdaptiveMarkovPredictor) ResetSession ¶
func (p *AdaptiveMarkovPredictor) ResetSession(sessionID string)
ResetSession clears trajectory memory for a finished or logged-out session.
func (*AdaptiveMarkovPredictor) SeedTransition ¶
func (p *AdaptiveMarkovPredictor) SeedTransition(fromPattern, toPattern string, weight int)
SeedTransition manually adds a known transition probability (useful for bootstrap/config).
type Config ¶
type Config struct {
// Store is the cache storage backend. Defaults to TieredStore wrapping ShardedStore if nil.
Store Store
// Predictor is the navigation sequence predictor. Defaults to DenseMatrixPredictor if nil.
Predictor Predictor
// ConfidenceThreshold is the minimum probability (0.0 to 1.0) required to trigger speculative pre-warming.
// Default: 0.65
ConfidenceThreshold float64
// TTL is the duration responses remain in the cache.
// Default: 60 seconds
TTL time.Duration
// SessionCookieName is the cookie key used to identify sessions.
// Default: "precog_sid"
SessionCookieName string
// CookieSecure sets the Secure flag on the session cookie.
CookieSecure bool
// SessionExtractor optionally overrides session resolution (e.g. from JWT or custom header).
SessionExtractor func(r *http.Request) string
// IsAuthenticated optionally determines whether a request carries authentication credentials.
// Responses to authenticated requests will NOT be stored in the shared cache unless
// the response explicitly contains `Cache-Control: public`.
// If nil, requests with Authorization, Proxy-Authorization, token headers, or cookies
// other than SessionCookieName are treated as authenticated.
IsAuthenticated func(r *http.Request) bool
// AuthCookieNames is an optional list of cookie names that indicate an authenticated session.
// If empty, any cookie other than SessionCookieName is considered an auth credential.
AuthCookieNames []string
// SkipRoutes is a list of path prefixes that will never be cached or speculatively prefetched.
SkipRoutes []string
// PublicRoutes is a list of path prefixes guaranteed to return public, non-personalized
// responses (e.g. "/api/catalog", "/api/products"). Requests to these routes may be
// shared-cached and coalesced even if authentication credentials are present.
PublicRoutes []string
// MaxResponseSize is the maximum response body size in bytes eligible for caching and buffering.
// Responses exceeding this limit bypass caching and stream directly to the client.
// Default: 2MB (2 * 1024 * 1024 bytes)
MaxResponseSize int64
// CoalesceAuthenticated controls whether requests carrying authentication credentials
// may be coalesced with identical concurrent requests for the exact same user identity.
// Default: false (authenticated requests bypass coalescing for strict security isolation).
CoalesceAuthenticated bool
// VaryHeaders is an optional list of request header names to evaluate for Vary negotiation
// if the response does not explicitly specify a Vary header.
VaryHeaders []string
// Workers is the number of concurrent speculative prefetch goroutines.
// Default: 4
Workers int
}
Config configures the Precog SDK engine.
type DenseMatrixPredictor ¶
type DenseMatrixPredictor struct {
// contains filtered or unexported fields
}
DenseMatrixPredictor models endpoint transition probabilities using a dense contiguous matrix. State transitions are updated atomically using atomic CPU instructions.
func NewDenseMatrixPredictor ¶
func NewDenseMatrixPredictor(cfg *DensePredictorConfig) *DenseMatrixPredictor
NewDenseMatrixPredictor creates a zero-GC contiguous matrix predictor.
func (*DenseMatrixPredictor) Predict ¶
func (p *DenseMatrixPredictor) Predict(sessionID string, topK int) []Prediction
Predict calculates top-K candidate routes for the active session.
func (*DenseMatrixPredictor) Record ¶
func (p *DenseMatrixPredictor) Record(sessionID string, method, path, rawQuery string)
Record observes an API interaction and updates the contiguous transition matrix using lock-free atomic instructions.
func (*DenseMatrixPredictor) Registry ¶
func (p *DenseMatrixPredictor) Registry() *EndpointRegistry
Registry returns the underlying dynamic endpoint registry.
func (*DenseMatrixPredictor) ResetSession ¶
func (p *DenseMatrixPredictor) ResetSession(sessionID string)
ResetSession clears navigation history for a session.
type DensePredictorConfig ¶
type DensePredictorConfig struct {
MaxRoutes int
MaxHistory int
Registry *EndpointRegistry
}
DensePredictorConfig configures the DenseMatrixPredictor.
type EndpointRegistry ¶
type EndpointRegistry struct {
// contains filtered or unexported fields
}
EndpointRegistry maps normalized route patterns to compact uint16 identifiers. Reads are lock-free via atomic.Value Copy-On-Write.
func NewEndpointRegistry ¶
func NewEndpointRegistry() *EndpointRegistry
NewEndpointRegistry creates a thread-safe endpoint registry.
func (*EndpointRegistry) Count ¶
func (r *EndpointRegistry) Count() int
Count returns the number of registered unique route patterns.
func (*EndpointRegistry) GetOrRegister ¶
func (r *EndpointRegistry) GetOrRegister(pattern string) uint16
GetOrRegister returns the uint16 identifier for a route pattern, registering it if new.
func (*EndpointRegistry) Lookup ¶
func (r *EndpointRegistry) Lookup(pattern string) (uint16, bool)
Lookup returns the ID for a pattern if registered, or false.
func (*EndpointRegistry) Pattern ¶
func (r *EndpointRegistry) Pattern(id uint16) string
Pattern returns the route pattern for a given uint16 ID in O(1) time.
type Engine ¶
type Engine struct {
// contains filtered or unexported fields
}
Engine represents the active Precog predictive caching runtime.
func (*Engine) Handler ¶
Handler wraps the root HTTP handler with Precog predictive caching and registers it with the prefetcher.
func (*Engine) IsRequestAuthenticated ¶
IsRequestAuthenticated determines whether an incoming HTTP request carries user authentication or credentials.
func (*Engine) Middleware ¶
Middleware returns a standard net/http middleware handler with production-grade predictive caching, security isolation, and RFC 9111 HTTP semantics compliance.
type InflightGroup ¶
type InflightGroup struct {
// contains filtered or unexported fields
}
InflightGroup coalesces concurrent requests for identical cache keys. Subsequent requests wait on the active in-flight execution and share the resulting entry, preventing duplicate upstream database or handler invocations.
func NewInflightGroup ¶
func NewInflightGroup() *InflightGroup
NewInflightGroup creates a sharded in-flight request coalescer.
func (*InflightGroup) Do ¶
func (g *InflightGroup) Do(key string, fn func() (*ResponseEntry, error)) (*ResponseEntry, error)
Do executes fn once for a given key. Concurrent callers with identical keys block until the active execution completes and share the returned entry.
func (*InflightGroup) DoContext ¶ added in v1.1.0
func (g *InflightGroup) DoContext(ctx context.Context, key string, fn func() (*ResponseEntry, error)) (*ResponseEntry, error)
DoContext executes fn once for a given key, respecting context cancellation for waiting callers. If ctx is cancelled before completion, waiting callers return ctx.Err() immediately.
type MemoryStore ¶
type MemoryStore struct {
// contains filtered or unexported fields
}
MemoryStore is a zero-dependency in-memory store suitable for testing.
func NewMemoryStore ¶
func NewMemoryStore() *MemoryStore
func (*MemoryStore) Close ¶
func (s *MemoryStore) Close() error
func (*MemoryStore) Del ¶
func (s *MemoryStore) Del(key string)
func (*MemoryStore) Get ¶
func (s *MemoryStore) Get(key string) (*ResponseEntry, bool)
func (*MemoryStore) Set ¶
func (s *MemoryStore) Set(key string, entry *ResponseEntry, ttl time.Duration) bool
type Prediction ¶
type Prediction struct {
Call string // e.g. "GET /cart" or "GET /reviews?product_id=44"
Pattern string // e.g. "GET /reviews"
Probability float64 // Confidence score between 0.0 and 1.0
}
Prediction represents a speculative next API endpoint.
type Predictor ¶
type Predictor interface {
Record(sessionID string, method, path, rawQuery string)
Predict(sessionID string, topK int) []Prediction
ResetSession(sessionID string)
}
Predictor models the user's sequential API access patterns.
type PrefetchJob ¶
type PrefetchJob struct {
SessionID string
Prediction Prediction
Host string
AuthHeaders http.Header
Cookies []*http.Cookie
IsAuth bool
}
PrefetchJob holds information needed to execute a speculative background fetch.
type Prefetcher ¶
type Prefetcher struct {
// contains filtered or unexported fields
}
Prefetcher executes speculative API requests in the background to warm the cache.
func NewPrefetcher ¶
func NewPrefetcher(handler http.Handler, store Store, inflight *InflightGroup, ttl time.Duration, threshold float64, workers int) *Prefetcher
NewPrefetcher initializes a worker pool for speculative cache warming.
func (*Prefetcher) Close ¶
func (p *Prefetcher) Close()
Close gracefully terminates the worker pool.
func (*Prefetcher) SetAuthChecker ¶
func (p *Prefetcher) SetAuthChecker(fn func(r *http.Request) bool)
SetAuthChecker registers a predicate function to identify authenticated requests.
func (*Prefetcher) SetOnWarmed ¶
func (p *Prefetcher) SetOnWarmed(fn func(job PrefetchJob, key string, bytes int))
SetOnWarmed registers a callback invoked whenever an endpoint is speculatively warmed.
func (*Prefetcher) Submit ¶
func (p *Prefetcher) Submit(sessionID string, preds []Prediction, origReq *http.Request)
Submit queues predictions that meet the confidence threshold for background warming.
type ResponseEntry ¶
type ResponseEntry struct {
Body []byte
Header http.Header
ContentType string
StatusCode int
CreatedAt time.Time
ExpiresAt time.Time
Vary map[string]string // request headers recorded from response Vary
}
ResponseEntry represents the HTTP response stored in the cache.
func (*ResponseEntry) MatchesVary ¶ added in v1.1.0
func (e *ResponseEntry) MatchesVary(r *http.Request) bool
MatchesVary returns true if the incoming request headers match the recorded Vary headers of this cached entry.
func (*ResponseEntry) WriteResponse ¶
func (e *ResponseEntry) WriteResponse(w http.ResponseWriter) (int64, error)
WriteResponse streams the cached response via the standard HTTP ResponseWriter.
type RistrettoStore ¶
type RistrettoStore struct {
// contains filtered or unexported fields
}
RistrettoStore implements Store using TinyLFU cache eviction.
func NewRistrettoStore ¶
func NewRistrettoStore(maxCost int64) (*RistrettoStore, error)
NewRistrettoStore creates a new TinyLFU cache with sane defaults.
func (*RistrettoStore) Close ¶
func (s *RistrettoStore) Close() error
func (*RistrettoStore) Del ¶
func (s *RistrettoStore) Del(key string)
func (*RistrettoStore) Get ¶
func (s *RistrettoStore) Get(key string) (*ResponseEntry, bool)
func (*RistrettoStore) Set ¶
func (s *RistrettoStore) Set(key string, entry *ResponseEntry, ttl time.Duration) bool
type ShardedConfig ¶
ShardedConfig configures the ShardedStore.
type ShardedStore ¶
type ShardedStore struct {
// contains filtered or unexported fields
}
ShardedStore is a partitioned byte-arena cache implementing Store. It uses primitive uint64 keys and uint32 offsets to minimize garbage collector scanning.
func NewShardedStore ¶
func NewShardedStore(cfg *ShardedConfig) *ShardedStore
NewShardedStore initializes a new sharded byte store.
func (*ShardedStore) Get ¶
func (s *ShardedStore) Get(key string) (*ResponseEntry, bool)
Get implements Store.
func (*ShardedStore) GetByHash ¶
func (s *ShardedStore) GetByHash(h uint64) (*ResponseEntry, bool)
GetByHash retrieves directly by uint64 hash, avoiding string overhead.
func (*ShardedStore) Set ¶
func (s *ShardedStore) Set(key string, entry *ResponseEntry, ttl time.Duration) bool
Set implements Store.
func (*ShardedStore) SetByHash ¶
func (s *ShardedStore) SetByHash(h uint64, entry *ResponseEntry, ttl time.Duration) bool
SetByHash writes directly using uint64 key hash with synchronous write consistency.
type Stats ¶
type Stats struct {
TotalRequests uint64 `json:"total_requests"`
CacheHits uint64 `json:"cache_hits"`
CacheMisses uint64 `json:"cache_misses"`
PrefetchesExecuted uint64 `json:"prefetches_executed"`
HitRate float64 `json:"hit_rate"`
}
Stats represents real-time operational metrics for Precog.
type Store ¶
type Store interface {
Get(key string) (*ResponseEntry, bool)
Set(key string, entry *ResponseEntry, ttl time.Duration) bool
Del(key string)
Close() error
}
Store defines the cache storage interface for Precog.
type Telemetry ¶
type Telemetry struct {
// contains filtered or unexported fields
}
Telemetry tracks cache efficiency and speculative accuracy atomically.
func NewTelemetry ¶
func NewTelemetry() *Telemetry
func (*Telemetry) RecordMiss ¶
func (t *Telemetry) RecordMiss()
func (*Telemetry) RecordPrefetch ¶
func (t *Telemetry) RecordPrefetch()
type TieredStore ¶
type TieredStore struct {
// contains filtered or unexported fields
}
TieredStore implements a two-tier caching hierarchy combining a direct-mapped atomic L1 cache with a sharded L2 store.
func NewTieredStore ¶
func NewTieredStore(l2 Store) *TieredStore
NewTieredStore creates a two-tier caching engine with the specified L2 backend. If l2 is nil, a default ShardedStore is used.
func (*TieredStore) Close ¶
func (t *TieredStore) Close() error
Close closes the underlying L2 store and clears L1.
func (*TieredStore) Del ¶
func (t *TieredStore) Del(key string)
Del invalidates the key in both L1 and L2.
func (*TieredStore) Get ¶
func (t *TieredStore) Get(key string) (*ResponseEntry, bool)
Get retrieves an item by key, checking L1 first before falling back to L2.
func (*TieredStore) Set ¶
func (t *TieredStore) Set(key string, entry *ResponseEntry, ttl time.Duration) bool
Set stores an item into L2 and populates L1 for instant subsequent hits.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
cmd
|
|
|
testserver
command
Command testserver is a self-contained integration target for verifying Precog behavior over real HTTP: cache HIT/MISS, speculative pre-warming, request coalescing, POST pass-through, and Set-Cookie exclusion.
|
Command testserver is a self-contained integration target for verifying Precog behavior over real HTTP: cache HIT/MISS, speculative pre-warming, request coalescing, POST pass-through, and Set-Cookie exclusion. |
|
wasm
command
|