precog

package module
v1.1.2 Latest Latest
Warning

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

Go to latest
Published: Oct 20, 2026 License: MIT Imports: 21 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

Precog

Go Reference Go Report Card

Precog is a predictive caching middleware for Go. It caches API responses in a low-overhead in-memory store, coalesces concurrent duplicate requests, learns navigation patterns with a Markov predictor, and speculatively pre-warms the responses users are likely to need next, both on the server and in the browser.


What it does

  • Caches safe responses (GET/HEAD) in a two-tier store: a lock-free direct-mapped L1 (atomic pointer slots, ~5 ns hits, zero allocations) backed by a pointer-free sharded byte-arena L2 (256 shards, no GC scanning of the index).
  • Coalesces concurrent requests for the same resource, so 50 simultaneous cache misses trigger exactly one handler execution (one database call).
  • Predicts the next request per session using a dense lock-free transition matrix and pre-warms predicted endpoints in background workers.
  • Accelerates the browser: serves an embedded client SDK (precog.js) that runs the same predictor as WebAssembly, pre-fetches into the browser's native CacheStorage, and injects W3C Speculation Rules.

Installation

go get github.com/adam-Sar/precog

Quick Start

package main

import (
	"log"
	"net/http"
	"time"

	"github.com/adam-Sar/precog"
)

func main() {
	mux := http.NewServeMux()

	mux.HandleFunc("/api/items", func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		_, _ = w.Write([]byte(`{"items": ["item1", "item2"]}`))
	})

	engine, err := precog.New(precog.Config{
		TTL:                 5 * time.Minute,
		ConfidenceThreshold: 0.60,
	})
	if err != nil {
		log.Fatalf("failed to init precog: %v", err)
	}
	defer engine.Close()

	log.Println("Server running on :8080 with precog")
	http.ListenAndServe(":8080", engine.Handler(mux))
}

Wrap your router with engine.Handler(mux). It works with net/http, Chi, Echo, Gin, or anything that speaks http.Handler.

Responses carry an X-Cache: HIT|MISS header so you can observe what's happening.

Caching policy & Security boundaries

Precog only caches and coalesces when it is provably safe to do so:

  • Method Safety: Only GET/HEAD requests are cached or coalesced; all other methods pass straight through.
  • Status & Headers: Only 200 OK responses are stored. Responses with Set-Cookie are never shared-cached (RFC 9111 §3.5) and are never shared across coalesced callers.
  • Authentication Isolation: Requests carrying credentials (Authorization, API tokens, or session cookies) bypass the shared cache and in-flight coalescing by default. They can only be shared if declared in PublicRoutes or if the upstream handler explicitly declares Cache-Control: public.
  • Cross-User Coalescing Defense: Private or unshareable responses are never delivered to waiting followers; waiters automatically fall back to independent upstream execution.
  • Client Directives: Client Cache-Control: no-cache, no-store, max-age=0 and Pragma: no-cache are fully respected.
  • Virtual Host Isolation: Cache keys incorporate the request Host to prevent cross-tenant cache pollution in multi-tenant environments.
  • Vary Header Support: RFC 9111 §4.1 compliant secondary keying. Responses with Vary: * are never cached. Responses with Vary: Accept-Encoding or other headers are stored under variant keys and verified on subsequent lookups.
  • Streaming & SSE: Server-Sent Events (text/event-stream), WebSockets, chunked transfers, and http.Flusher/http.Hijacker interfaces bypass caching and stream without buffering.
  • Oversized Response Protection: Responses exceeding MaxResponseSize (default: 2MB) stream through directly to protect server memory.

Sessions

Precog tracks navigation per session to drive predictions. A session is resolved in this order:

  1. SessionExtractor from Config, if you provide one (e.g. read a JWT claim or custom header).
  2. The cookie named by SessionCookieName (default precog_sid, set automatically).
  3. The X-Session-ID request header.

Configuration

engine, err := precog.New(precog.Config{
	// Minimum Markov confidence (0.0-1.0) to trigger background prefetch. Default: 0.65
	ConfidenceThreshold: 0.65,

	// How long cached responses stay valid. Default: 60s
	TTL: 5 * time.Minute,

	// Custom store backend. Default: two-tier L1 + sharded L2.
	Store: precog.NewTieredStore(precog.NewShardedStore(&precog.ShardedConfig{
		NumShards:    256,
		MaxCostBytes: 256 * 1024 * 1024,
	})),

	// Custom predictor. Default: DenseMatrixPredictor (max 1024 routes).
	Predictor: precog.NewDenseMatrixPredictor(&precog.DensePredictorConfig{
		MaxRoutes: 1024,
	}),

	// Path prefixes guaranteed to be public catalog/reference data.
	// Eligible for shared caching and coalescing even if authentication headers exist.
	PublicRoutes: []string{"/api/catalog", "/api/products"},

	// Maximum response body size eligible for in-memory caching.
	// Responses larger than this bypass caching and stream directly. Default: 2MB
	MaxResponseSize: 2 * 1024 * 1024,

	// Isolated coalescing for authenticated requests (scoped strictly per-user).
	// Default: false (authenticated requests bypass coalescing for strict security).
	CoalesceAuthenticated: false,

	// Cookie name for session tracking. Default: "precog_sid"
	SessionCookieName: "precog_sid",

	// Set the Secure flag on the session cookie (use behind HTTPS).
	CookieSecure: true,

	// Override session resolution (e.g. from a JWT or custom header).
	SessionExtractor: func(r *http.Request) string { return r.Header.Get("X-User") },

	// Optional custom authentication detector. By default, requests with Authorization,
	// Proxy-Authorization, API token headers, or cookies other than SessionCookieName
	// are treated as authenticated.
	IsAuthenticated: func(r *http.Request) bool {
		return r.Header.Get("Authorization") != "" || r.Header.Get("X-User-Token") != ""
	},

	// Whitelist specific cookie names that represent authenticated sessions.
	AuthCookieNames: []string{"session_id", "jwt"},

	// Path prefixes never cached or prefetched.
	SkipRoutes: []string{"/healthz", "/metrics", "/admin"},

	// Concurrent speculative prefetch workers. Default: 4
	Workers: 8,
})

Browser SDK

Precog serves its client SDK at /precog/precog.js. Include it in your HTML:

<script src="/precog/precog.js" defer></script>

The SDK automatically:

  1. Loads the WebAssembly predictor from /precog/precog.wasm (or runs the lightweight JS tracker fallback).
  2. Intercepts fetch() calls and link hovers to learn navigation patterns.
  3. Pre-fetches predicted URLs into the browser's CacheStorage for zero-latency repeat requests.
  4. Strictly inspects response Cache-Control (private and no-store responses and Set-Cookie are never stored in browser CacheStorage).
  5. Injects W3C Speculation Rules for Chromium-native prefetching.
  6. Honors data-precog-skip and rel="nofollow" attributes on links to prevent speculative prefetching.
  7. Exposes window.Precog.reset() to invalidate all browser cache entries upon user logout.

Benchmarks

Measured on an Intel Core i7-1165G7 @ 2.80GHz (go test -bench . -benchmem):

Core Caching & Modeling Primitives
Benchmark Component Speed / Op Allocations Memory / Op
TieredStore L1 Atomic Hit 4.50 ns/op 0 allocs/op 0 B/op
EndpointRegistry Route Lookup 7.41 ns/op 0 allocs/op 0 B/op
FastHash64 (Bare Path) 33.37 ns/op 0 allocs/op 0 B/op
FastHash64 (Multi-Param Query) 188.2 ns/op 1 allocs/op 64 B/op
ShardedStore Parallel Read (256 Shards) 97.55 ns/op 5 allocs/op 199 B/op
Dense Matrix Predictor Query 508.7 ns/op 6 allocs/op 280 B/op
Dense Matrix Lock-Free Record 864.0 ns/op 13 allocs/op 295 B/op
Complete End-to-End HTTP Middleware Stack
End-to-End HTTP Benchmark Speed / Op Throughput Allocations / Op
HTTP Middleware Parallel Cache Hits 2.08 µs/op ~480,000 req/sec 30 allocs/op (1640 B)
HTTP Middleware Single Cache Hit 5.00 µs/op ~200,000 req/sec 30 allocs/op (1661 B)
HTTP In-Flight Request Coalescing 4.81 µs/op ~207,000 req/sec 39 allocs/op (6788 B)

License

MIT License. See LICENSE for details.

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

View Source
const (
	// DefaultMaxDenseRoutes defines the maximum route matrix dimension (1024 x 1024).
	DefaultMaxDenseRoutes = 1024
	// NumSessionShards partitions user sessions to minimize mutex contention.
	NumSessionShards = 64
)
View Source
const (
	// DefaultShards is 256 striped partitions to eliminate lock contention.
	DefaultShards = 256
	// DefaultMaxShardSize is 1 MB per shard = 256 MB total.
	DefaultMaxShardSize = 1024 * 1024
)
View Source
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.

View Source
const (
	// L1Slots defines the number of direct-mapped atomic cache slots.
	L1Slots = 256
)
View Source
const MaxIndexedRoutes = 4096

MaxIndexedRoutes is the maximum number of distinct API endpoint patterns supported.

Variables

View Source
var ClientScriptBytes []byte
View Source
var ErrNotShareable = errors.New("precog: response is private or unshareable")

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).

View Source
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

func CanonicalCacheKey(method, path, rawQuery, body string) string

CanonicalCacheKey computes a deterministic 16-character hexadecimal hash key.

func CanonicalCacheKeyWithHost added in v1.1.0

func CanonicalCacheKeyWithHost(method, host, path, rawQuery string, varyVals ...string) string

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

func FastHash64(method, path, rawQuery, body string) uint64

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

func FastHash64WithHost(method, host, path, rawQuery string, varyVals ...string) uint64

FastHash64WithHost computes a 64-bit non-cryptographic hash including host, path, canonicalized query parameters, and negotiated Vary values.

func NormalizeRoute

func NormalizeRoute(method, path string) string

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 New

func New(cfg Config) (*Engine, error)

New initializes the Precog SDK with the given configuration.

func (*Engine) Close

func (e *Engine) Close() error

Close gracefully flushes background workers and closes the cache store.

func (*Engine) Handler

func (e *Engine) Handler(rootHandler http.Handler) http.Handler

Handler wraps the root HTTP handler with Precog predictive caching and registers it with the prefetcher.

func (*Engine) IsRequestAuthenticated

func (e *Engine) IsRequestAuthenticated(r *http.Request) bool

IsRequestAuthenticated determines whether an incoming HTTP request carries user authentication or credentials.

func (*Engine) Middleware

func (e *Engine) Middleware(next http.Handler) http.Handler

Middleware returns a standard net/http middleware handler with production-grade predictive caching, security isolation, and RFC 9111 HTTP semantics compliance.

func (*Engine) Predictor

func (e *Engine) Predictor() Predictor

Predictor returns the active prediction engine.

func (*Engine) Stats

func (e *Engine) Stats() Stats

Stats returns a snapshot of runtime metrics (hit rate, prefetches, latency saved).

func (*Engine) Store

func (e *Engine) Store() Store

Store returns the underlying cache storage.

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

type ShardedConfig struct {
	NumShards    int
	MaxCostBytes int64
}

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) Close

func (s *ShardedStore) Close() error

Close implements Store.

func (*ShardedStore) Del

func (s *ShardedStore) Del(key string)

Del implements 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) RecordHit

func (t *Telemetry) RecordHit()

func (*Telemetry) RecordMiss

func (t *Telemetry) RecordMiss()

func (*Telemetry) RecordPrefetch

func (t *Telemetry) RecordPrefetch()

func (*Telemetry) Stats

func (t *Telemetry) Stats() Stats

Stats returns a point-in-time snapshot of the cache metrics.

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) L2

func (t *TieredStore) L2() Store

L2 returns the underlying L2 store.

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.

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

Jump to

Keyboard shortcuts

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