cache

package
v0.6.0 Latest Latest
Warning

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

Go to latest
Published: Sep 12, 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 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 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) 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

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