metricscache

package
v0.46.0 Latest Latest
Warning

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

Go to latest
Published: Jul 3, 2026 License: Apache-2.0 Imports: 21 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// PointCost is the estimated memory cost per cached point in bytes.
	// 8 (int64 delta) + 8 (float64) = 16.
	PointCost = 16
	// EntryOverhead is the fixed overhead per cache entry in bytes.
	EntryOverhead = 128
)

Variables

This section is empty.

Functions

func EntryCost

func EntryCost(points int) uint32

EntryCost returns the estimated memory cost of an entry with the given number of points.

Types

type Block

type Block struct {
	Data  []byte // lz4-framed compressed payload
	MinTS int64
	MaxTS int64
	Count int
}

Block is the serialized, compressed form of a single cache entry. One block corresponds to one Entry (all points for one series).

The Data field contains an lz4-framed payload with the following uncompressed layout:

[ 4B uint32] count
if count >= 1:
  [ 8B int64 ] ts[0]
if count >= 2:
  [ 8B int64 ] first_interval = ts[1] - ts[0]
  [uvarint*(count-2)] zigzag-encoded double-deltas for ts[2:]:
    dd = (ts[i]-ts[i-1]) - (ts[i-1]-ts[i-2])
[8B*count] float64 values (little-endian IEEE 754)

Note: minTS/maxTS watermarks are stored in the outer Block struct (and disk metadata), not inside the compressed payload. They were removed from the header to avoid redundant ignored reads in Decode.

func EncodeBlock

func EncodeBlock(ts []int64, vals []float64, minTS, maxTS int64) (Block, error)

EncodeBlock encodes timestamps and values into a compressed Block.

ts and vals must have the same length and ts must be sorted. minTS and maxTS are the watermark bounds (may extend beyond ts range for empty-series entries).

func (Block) ByteSize

func (b Block) ByteSize() int

ByteSize returns the approximate size of the block in bytes.

func (Block) Decode

func (b Block) Decode() (ts []int64, vals []float64, err error)

Decode decompresses and decodes the block, returning the timestamps and values.

type Cache

type Cache struct {

	// Stats holds OTel metric counters for per-query cache diagnostics.
	Stats CacheStats
	// contains filtered or unexported fields
}

Cache is the top-level metrics cache.

func New

func New(opts Options) (*Cache, error)

New creates a new Cache with the given options.

func (*Cache) IsBigQuery

func (c *Cache) IsBigQuery(totalPoints int) bool

IsBigQuery returns true if the number of points would exceed the cache memory budget.

func (*Cache) Lookup

func (c *Cache) Lookup(k Key, start int64) (maxTS int64, hit bool)

Lookup gets the watermark maxTS and whether the cache has a hit covering start.

func (*Cache) Read

func (c *Cache) Read(k Key, from, to int64) (ts []int64, vals []float64, ok bool)

Read gets an entry and slices its points, copying the values to avoid aliasing.

func (*Cache) SafetyLag

func (c *Cache) SafetyLag() time.Duration

SafetyLag returns the duration from now that is not cached.

func (*Cache) Update

func (c *Cache) Update(k Key, u Update) (wrote bool)

Update gap-checks + fresh-starts + appends + markFetched + sets, atomic.

type CacheStats

type CacheStats struct {
	SeriesHits        metric.Int64Counter `name:"metrics_cache.series_hits" description:"Series with a cache watermark covering the full query range." unit:"{series}"`
	SeriesPartialHits metric.Int64Counter `` /* 139-byte string literal not displayed */
	SeriesMisses      metric.Int64Counter `name:"metrics_cache.series_misses" description:"Series that required a ClickHouse fetch." unit:"{series}"`
	BigQueries        metric.Int64Counter `` /* 139-byte string literal not displayed */
	SkippedInserts    metric.Int64Counter `` /* 135-byte string literal not displayed */
	FullyCovered      metric.Int64Counter `` /* 130-byte string literal not displayed */
}

CacheStats holds OTel counters for cache operation tracking.

type DiskStore

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

DiskStore is a directory-based persistent Store.

Each entry is stored as a pair of files:

  • <base>.json — human-readable metadata (key fields, watermarks, point count)
  • <base>.bin — raw LZ4-compressed block payload (DoubleDelta timestamps + float64 values)

An in-memory index maps Key → base filename for fast lookup. There is no eviction in v1: entries persist until the directory is cleared.

func NewDiskStore

func NewDiskStore(dir string) (*DiskStore, error)

NewDiskStore creates a DiskStore rooted at dir.

func (*DiskStore) Close

func (s *DiskStore) Close() error

Close is a no-op for DiskStore.

func (*DiskStore) Get

func (s *DiskStore) Get(key Key) (*Entry, bool)

Get retrieves an entry from disk. If the entry is corrupt or incomplete, it is deleted so it will be re-fetched.

func (*DiskStore) Set

func (s *DiskStore) Set(key Key, entry *Entry)

Set writes an entry to disk. Errors (e.g. ToBlock failure or disk I/O) are counted toward RejectedSets but otherwise ignored to match Store interface.

func (*DiskStore) Size

func (s *DiskStore) Size() int

Size returns the number of entries indexed in memory.

func (*DiskStore) Stats

func (s *DiskStore) Stats() StoreStats

Stats returns current stats. DiskStore tracks Size, RejectedSets and DiskSize.

type Entry

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

Entry is per-series cached sample data.

func FromBlock

func FromBlock(b Block) (*Entry, error)

FromBlock deserializes a Block back into an Entry.

func NewEntry

func NewEntry() *Entry

NewEntry creates a new empty Entry.

func (*Entry) Cost

func (e *Entry) Cost() uint32

Cost returns the estimated memory cost of the entry in bytes.

func (*Entry) Len

func (e *Entry) Len() int

Len returns the number of cached data points.

func (*Entry) ToBlock

func (e *Entry) ToBlock() (Block, error)

ToBlock serializes the entry to a compressed Block for disk storage.

func (*Entry) Watermarks

func (e *Entry) Watermarks() (minTS, maxTS int64)

Watermarks returns the coverage bounds [minTS, maxTS] of this entry.

type Key

type Key struct {
	Hash [16]byte
	Step int64  // Milliseconds. 0 means raw points.
	Fn   string // Aggregation function name; empty means raw/anyLast.
}

Key is a cache lookup key for one series at a given step and function.

type MemoryStore

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

MemoryStore is an in-memory Store backed by otter.

func NewMemoryStore

func NewMemoryStore(maxBytes int64) (*MemoryStore, error)

NewMemoryStore creates an otter-backed in-memory store with the given memory budget.

func (*MemoryStore) Close

func (s *MemoryStore) Close() error

Close is a no-op for the memory store.

func (*MemoryStore) Get

func (s *MemoryStore) Get(key Key) (*Entry, bool)

Get retrieves an entry from the memory store.

func (*MemoryStore) Set

func (s *MemoryStore) Set(key Key, entry *Entry)

Set stores an entry in the memory store.

func (*MemoryStore) Size

func (s *MemoryStore) Size() int

Size returns the current number of entries in the store.

func (*MemoryStore) Stats

func (s *MemoryStore) Stats() StoreStats

Stats returns current statistics from the backing otter cache.

type Options

type Options struct {
	// MaxBytes is the maximum memory budget. Zero disables the cache.
	MaxBytes int64
	// SafetyLag is the duration from now that is not cached.
	SafetyLag time.Duration // default 60s
	// MeterProvider is the OpenTelemetry meter provider for cache metrics.
	MeterProvider metric.MeterProvider
	// Store is the backing store. nil uses a new MemoryStore(MaxBytes).
	Store Store
}

Options configures the Cache.

type Store

type Store interface {
	Get(key Key) (*Entry, bool)
	Set(key Key, entry *Entry)
	Size() int
	Stats() StoreStats
	Close() error
}

Store is a pluggable backend for the metrics cache.

type StoreStats

type StoreStats struct {
	Hits         int64
	Misses       int64
	EvictedCount int64
	EvictedCost  int64
	RejectedSets int64
	Size         int
	Ratio        float64

	// DiskSize is the approximate total size of on-disk files (.json + .bin)
	// for DiskStore. It is zero for MemoryStore. Useful for monitoring
	// unbounded growth (DiskStore has no eviction in v1).
	DiskSize int64
}

StoreStats contains cache hit/eviction statistics from the backing store.

type Update

type Update struct {
	FetchFrom    int64
	UntilMs      int64
	TS           []int64
	Vals         []float64
	OnlyIfExists bool
}

Update contains parameters for Cache.Update.

Jump to

Keyboard shortcuts

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