cache

package
v0.11.0 Latest Latest
Warning

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

Go to latest
Published: Oct 7, 2025 License: MIT Imports: 27 Imported by: 0

Documentation

Overview

Package cache provides binary format serialization for fuzzy cache data structures.

Index

Constants

View Source
const (
	CacheMagic   = 0x44554d42 // "DUMB" in little-endian
	CacheVersion = 1
	HeaderSize   = 28 // Size of binary header
)

Binary format constants for cache file structure

Variables

This section is empty.

Functions

func DaysFromTime

func DaysFromTime(t time.Time) uint32

DaysFromTime converts a time.Time to days since Unix epoch.

func IsValidCacheFile

func IsValidCacheFile(filename string) bool

IsValidCacheFile checks if a file is a valid cache file without fully loading it.

func TimeFromDays

func TimeFromDays(days uint32) time.Time

TimeFromDays converts days since Unix epoch back to time.Time.

Types

type BinaryHeader

type BinaryHeader struct {
	Magic        uint32 // Magic number for format identification
	Version      uint32 // Cache format version
	EntryCount   uint32 // Number of entries in cache
	IndexOffset  uint64 // Offset to trigram index section
	LastModified int64  // Unix timestamp of last modification
}

BinaryHeader represents the cache file header.

type CacheConfig

type CacheConfig struct {
	// File paths
	CacheFile string // Path to binary cache file

	// Performance tuning
	MaxEntries       uint32  // Maximum entries to cache
	TrigramThreshold uint32  // Minimum trigram matches required
	ScoreThreshold   float64 // Minimum score for results
	MaxResults       int     // Maximum results to return

	// Scoring weights
	URLWeight     float64 // Weight for URL matches
	TitleWeight   float64 // Weight for title matches
	RecencyWeight float64 // Weight for recency
	VisitWeight   float64 // Weight for visit count

	// Cache behavior
	TTL           time.Duration // Cache time-to-live
	WarmupEnabled bool          // Enable background cache warming
}

CacheConfig holds configuration for the fuzzy cache.

func DefaultCacheConfig

func DefaultCacheConfig() *CacheConfig

DefaultCacheConfig returns sensible default configuration.

func (*CacheConfig) GetStateDir

func (c *CacheConfig) GetStateDir() (string, error)

GetStateDir returns the state directory using the config package.

type CacheHeader added in v0.7.0

type CacheHeader struct {
	Magic     uint64 // Magic bytes for file identification
	Version   uint32 // Cache format version
	DataSize  uint64 // Size of data section
	RuleCount uint32 // Number of filter rules
	Created   int64  // Unix timestamp when cache was created
	Checksum  uint64 // CRC64 checksum of data section
}

CacheHeader represents the binary cache file header

type CacheManager

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

CacheManager handles the lifecycle of the fuzzy cache with smart invalidation.

func NewCacheManager

func NewCacheManager(queries HistoryQuerier, config *CacheConfig) *CacheManager

NewCacheManager creates a new cache manager.

func (*CacheManager) GetCache

func (cm *CacheManager) GetCache(ctx context.Context) (*DmenuFuzzyCache, error)

GetCache returns the current cache, loading from filesystem or DB as needed.

func (*CacheManager) GetTopEntries

func (cm *CacheManager) GetTopEntries(ctx context.Context) (*FuzzyResult, error)

GetTopEntries returns the top entries without a search query.

func (*CacheManager) InvalidateAndRefresh

func (cm *CacheManager) InvalidateAndRefresh(ctx context.Context)

InvalidateAndRefresh forces cache invalidation and refresh. This should be called when we know the DB has changed (e.g., after adding history).

func (*CacheManager) OnApplicationExit

func (cm *CacheManager) OnApplicationExit(ctx context.Context)

OnApplicationExit should be called when the application is about to exit. This triggers a background cache refresh for the next startup.

func (*CacheManager) Search

func (cm *CacheManager) Search(ctx context.Context, query string) (*FuzzyResult, error)

Search performs a fuzzy search using the cached data.

func (*CacheManager) Stats

func (cm *CacheManager) Stats() CacheStats

Stats returns cache statistics.

type CacheStats

type CacheStats struct {
	EntryCount   int       // Number of cached entries
	TrigramCount int       // Number of trigrams in index
	FileSize     int64     // Size of cache file on disk
	LastModified time.Time // When cache was last built
	FileModTime  time.Time // When cache file was last modified
}

CacheStats provides information about the cache state.

func (CacheStats) String

func (cs CacheStats) String() string

String returns a string representation of cache stats.

type CompactEntry

type CompactEntry struct {
	URL        string // Original URL
	Title      string // Page title
	FaviconURL string // URL to favicon for this entry
	VisitCount uint16 // Max 65535 visits (sufficient for most use cases)
	LastVisit  uint32 // Days since Unix epoch (saves 4 bytes vs time.Time)
	Score      uint16 // Pre-computed base score (0-65535)
}

CompactEntry represents a history entry optimized for memory usage.

func NewCompactEntry

func NewCompactEntry(url, title, faviconURL string, visitCount int64, lastVisit time.Time) CompactEntry

NewCompactEntry creates a CompactEntry from database values.

func (*CompactEntry) Display

func (e *CompactEntry) Display() string

Display returns a formatted string for dmenu display.

type CosmeticRule added in v0.7.0

type CosmeticRule struct {
	Domain   string
	Selector string
}

CosmeticRule represents a compiled cosmetic filtering rule

type DmenuFuzzyCache

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

DmenuFuzzyCache provides high-performance fuzzy search for dmenu history.

func (*DmenuFuzzyCache) LoadFromBinary

func (c *DmenuFuzzyCache) LoadFromBinary(filename string) error

LoadFromBinary loads cache from a binary file using memory mapping.

func (*DmenuFuzzyCache) SaveToBinary

func (c *DmenuFuzzyCache) SaveToBinary(filename string) error

SaveToBinary writes the cache to a binary file using memory mapping for performance.

func (*DmenuFuzzyCache) Search

func (c *DmenuFuzzyCache) Search(query string, config *CacheConfig) *FuzzyResult

Search performs a fuzzy search on the cache and returns ranked results.

type FaviconCache added in v0.5.0

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

FaviconCache manages favicon caching to local files

func NewFaviconCache added in v0.5.0

func NewFaviconCache() (*FaviconCache, error)

NewFaviconCache creates a new favicon cache

func (*FaviconCache) CacheAsync added in v0.5.0

func (fc *FaviconCache) CacheAsync(faviconURL string)

CacheAsync downloads and caches a favicon asynchronously

func (*FaviconCache) CachePNGData added in v0.10.0

func (fc *FaviconCache) CachePNGData(pageURL string, pngData []byte) error

CachePNGData caches PNG favicon data directly for a URL

func (*FaviconCache) CleanOld added in v0.5.0

func (fc *FaviconCache) CleanOld() error

CleanOld removes cached favicons older than 30 days

func (*FaviconCache) GetCachedPath added in v0.5.0

func (fc *FaviconCache) GetCachedPath(faviconURL string) string

GetCachedPath returns the local file path for a favicon URL if cached, empty string otherwise

func (*FaviconCache) GetCachedPathForURL added in v0.10.0

func (fc *FaviconCache) GetCachedPathForURL(pageURL string) string

GetCachedPathForURL returns the cached path for a page URL (not favicon URL)

type FilterCache added in v0.7.0

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

FilterCache provides high-performance binary filter caching with memory mapping

func NewFilterCache added in v0.7.0

func NewFilterCache(path string) *FilterCache

NewFilterCache creates a new filter cache instance

func (*FilterCache) IsValid added in v0.7.0

func (fc *FilterCache) IsValid() bool

IsValid checks if the cache file exists and has valid format

func (*FilterCache) LoadMapped added in v0.7.0

func (fc *FilterCache) LoadMapped() (*FilterData, error)

LoadMapped loads the cache file using memory mapping for zero-copy access

func (*FilterCache) Remove added in v0.7.0

func (fc *FilterCache) Remove() error

Remove deletes the cache file

func (*FilterCache) Size added in v0.7.0

func (fc *FilterCache) Size() int64

Size returns the size of the cache file in bytes

func (*FilterCache) Unmap added in v0.7.0

func (fc *FilterCache) Unmap() error

Unmap releases the memory-mapped data

func (*FilterCache) Write added in v0.7.0

func (fc *FilterCache) Write(data *FilterData) error

Write saves filter data to cache in binary format

type FilterData added in v0.7.0

type FilterData struct {
	Version       uint32
	Created       time.Time
	NetworkRules  []NetworkRule
	CosmeticRules []CosmeticRule
}

FilterData represents the compiled filter data for caching

type FilterRule added in v0.7.0

type FilterRule struct {
	Type         uint8  // Rule type (0=network, 1=cosmetic)
	Priority     uint8  // Rule priority
	Action       uint8  // Action to take (0=block, 1=allow, etc.)
	Flags        uint8  // Additional flags
	PatternLen   uint16 // Length of pattern string
	DomainLen    uint16 // Length of domain string
	ResourceType uint32 // Bitmask of resource types

}

FilterRule represents a compiled filter rule in binary format

type FuzzyMatch

type FuzzyMatch struct {
	Entry        *CompactEntry // Matched entry
	Score        float64       // Final fuzzy match score (0.0-1.0)
	URLScore     float64       // URL similarity score
	TitleScore   float64       // Title similarity score
	RecencyScore float64       // Recency boost score
	VisitScore   float64       // Visit count boost score
	MatchType    MatchType     // Type of match found
}

FuzzyMatch represents a single fuzzy search match.

type FuzzyResult

type FuzzyResult struct {
	Matches   []FuzzyMatch  // Matching entries
	QueryTime time.Duration // Time taken to execute query
}

FuzzyResult contains the results of a fuzzy search query.

func (*FuzzyResult) Reset

func (r *FuzzyResult) Reset()

Reset clears the FuzzyResult for reuse.

type FuzzySearcher

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

FuzzySearcher provides high-performance fuzzy search capabilities.

func NewFuzzySearcher

func NewFuzzySearcher(config *CacheConfig) *FuzzySearcher

NewFuzzySearcher creates a new fuzzy searcher with the given config.

type HistoryQuerier

type HistoryQuerier interface {
	GetHistory(ctx context.Context, limit int64) ([]db.History, error)
	GetShortcuts(ctx context.Context) ([]db.Shortcut, error)
}

HistoryQuerier defines the interface for querying history data.

type MatchType

type MatchType uint8

MatchType indicates how the query matched the entry.

const (
	MatchTypeExact   MatchType = iota // Exact substring match
	MatchTypePrefix                   // Prefix match
	MatchTypeFuzzy                    // Fuzzy similarity match
	MatchTypeTrigram                  // Trigram-based match
)

Match type constants for different matching strategies

func (MatchType) String

func (mt MatchType) String() string

String returns a string representation of the match type.

type NetworkRule added in v0.7.0

type NetworkRule struct {
	Pattern      string
	Domain       string
	Action       uint8  // 0=block, 1=allow
	ResourceType uint32 // Bitmask of resource types
	Priority     uint8
}

NetworkRule represents a compiled network filtering rule

type Trie

type Trie struct {
	Root *TrieNode
}

Trie represents a compressed prefix tree for fast prefix matching.

func NewTrie

func NewTrie() *Trie

NewTrie creates a new empty trie.

func (*Trie) Insert

func (t *Trie) Insert(text string, entryID uint32)

Insert adds an entry to the trie for all its prefixes.

func (*Trie) PrefixSearch

func (t *Trie) PrefixSearch(query string) []uint32

PrefixSearch finds all entries that start with any word in the query.

func (*Trie) Search

func (t *Trie) Search(prefix string) []uint32

Search finds all entries that match the given prefix.

type TrieNode

type TrieNode struct {
	Children map[rune]*TrieNode // Child nodes
	Entries  []uint32           // Entry IDs that end at this node
	IsEnd    bool               // Marks end of a prefix
}

TrieNode represents a node in the prefix trie.

Directories

Path Synopsis
Package mock_cache is a generated GoMock package.
Package mock_cache is a generated GoMock package.

Jump to

Keyboard shortcuts

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