Documentation
¶
Overview ¶
Package daramjwee contains the core implementation of the Cache interface.
Index ¶
- Variables
- func ReadAll(rc io.ReadCloser) ([]byte, error)
- type BeginSetUsesContext
- type Cache
- type CacheGroup
- type CacheRuntimeConfig
- type Config
- type ConfigError
- type DaramjweeCache
- func (c *DaramjweeCache) Close()
- func (c *DaramjweeCache) Delete(ctx context.Context, key string) error
- func (c *DaramjweeCache) Get(ctx context.Context, key string, req GetRequest, fetcher Fetcher) (*GetResponse, error)
- func (c *DaramjweeCache) ScheduleRefresh(ctx context.Context, key string, fetcher Fetcher) error
- func (c *DaramjweeCache) Set(ctx context.Context, key string, metadata *Metadata) (WriteSink, error)
- type EvictionPolicy
- type FetchResult
- type FetchUsesContext
- type Fetcher
- type GetRequest
- type GetResponse
- type GetStatus
- type GetStreamUsesContext
- type GroupConfig
- type GroupOption
- type JobKind
- type Metadata
- type Option
- func WithCloseTimeout(timeout time.Duration) Option
- func WithFillLeaseTimeout(timeout time.Duration) Option
- func WithFreshness(positive, negative time.Duration) Option
- func WithOpTimeout(timeout time.Duration) Option
- func WithQueueLimit(limit int) Option
- func WithTierFreshness(index int, positive, negative time.Duration) Option
- func WithTiers(stores ...Store) Option
- func WithWeight(weight int) Option
- func WithWorkerQueue(size int) Option
- func WithWorkerStrategy(strategy string) Option
- func WithWorkerTimeout(timeout time.Duration) Option
- func WithWorkers(count int) Option
- type StagedWriteSink
- type StagingStore
- type Store
- type TierFreshnessOverride
- type TierValidator
- type WriteSink
Constants ¶
This section is empty.
Variables ¶
var ErrBackgroundJobRejected = errors.New("daramjwee: background job rejected")
var ErrCacheClosed = errors.New("daramjwee: cache is closed")
var ErrCacheableNotFound = errors.New("daramjwee: resource not found, but this state is cacheable")
ErrCacheableNotFound is returned when a resource is not found, but this state is cacheable (e.g., a negative cache entry).
var ErrNilFetcher = errors.New("daramjwee: nil fetcher")
ErrNilFetcher is returned when a cache operation that may call the origin is invoked without a Fetcher.
var ErrNilMetadata = errors.New("daramjwee: nil metadata encountered")
var ErrNotFound = errors.New("daramjwee: object not found")
ErrNotFound is returned when an object is not found in the cache or the origin.
var ErrNotModified = errors.New("daramjwee: resource not modified")
ErrNotModified is a sentinel error returned by a Fetcher when the resource at the origin has not changed compared to the cached version.
var ErrTopWriteInvalidated = errors.New("daramjwee: top-tier write invalidated")
Functions ¶
Types ¶
type BeginSetUsesContext ¶ added in v0.4.1
type BeginSetUsesContext interface {
BeginSetUsesContext() bool
}
BeginSetUsesContext is an optional Store extension for backends whose returned sinks continue using the provided context after BeginSet returns.
type Cache ¶
type Cache interface {
// Get retrieves an object using the cache's current representation and
// optional client validator request metadata.
// On a cache miss, it uses the provided Fetcher to retrieve data from the origin.
// The fetcher must not be nil.
Get(ctx context.Context, key string, req GetRequest, fetcher Fetcher) (*GetResponse, error)
// Set provides a writer to stream an object into the cache.
// The cache entry is finalized when the returned writer is closed.
// This pattern is ideal for use with io.MultiWriter for simultaneous
// response-to-client and writing-to-cache scenarios.
// NOTE: The caller is responsible for calling Close() or Abort() on the
// returned sink to ensure resources are released.
Set(ctx context.Context, key string, metadata *Metadata) (WriteSink, error)
// Delete removes an object from the cache.
Delete(ctx context.Context, key string) error
// ScheduleRefresh asynchronously refreshes a cache entry using the provided Fetcher.
// The fetcher must not be nil.
ScheduleRefresh(ctx context.Context, key string, fetcher Fetcher) error
// Close gracefully shuts down the cache and its background workers.
Close()
}
Cache is the primary public interface for interacting with daramjwee. It enforces a memory-safe, stream-based interaction model.
type CacheGroup ¶ added in v0.8.0
CacheGroup owns a shared background runtime for multiple caches.
func NewGroup ¶ added in v0.8.0
func NewGroup(logger log.Logger, opts ...GroupOption) (CacheGroup, error)
NewGroup constructs a CacheGroup with a shared bounded runtime.
type CacheRuntimeConfig ¶ added in v0.8.0
type Config ¶
type Config struct {
Tiers []Store
WorkerStrategy string
Workers int
WorkerQueue int
WorkerTimeout time.Duration
Weight int
QueueLimit int
OpTimeout time.Duration
CloseTimeout time.Duration
PositiveFreshness time.Duration
NegativeFreshness time.Duration
TierFreshnessOverrides map[int]TierFreshnessOverride
// contains filtered or unexported fields
}
Config holds all the configurable settings for the daramjwee cache.
type ConfigError ¶
type ConfigError struct {
Message string
}
ConfigError represents an error that occurs during the configuration process.
func (*ConfigError) Error ¶
func (e *ConfigError) Error() string
Error returns the error message for ConfigError.
type DaramjweeCache ¶
type DaramjweeCache struct {
// contains filtered or unexported fields
}
DaramjweeCache is a concrete implementation of the Cache interface.
func (*DaramjweeCache) Delete ¶
func (c *DaramjweeCache) Delete(ctx context.Context, key string) error
Delete sequentially deletes an object from all tiers to prevent deadlocks.
func (*DaramjweeCache) Get ¶
func (c *DaramjweeCache) Get(ctx context.Context, key string, req GetRequest, fetcher Fetcher) (*GetResponse, error)
Get retrieves data based on the requested caching strategy. It checks ordered tiers from top to bottom and finally fetches from the origin.
func (*DaramjweeCache) ScheduleRefresh ¶
ScheduleRefresh submits a background cache refresh job to the worker.
type EvictionPolicy ¶
type EvictionPolicy interface {
// Touch is called when an item is accessed.
Touch(key string)
// Add is called when a new item is added, along with its size in bytes.
Add(key string, size int64)
// Remove is called when an item is explicitly deleted.
Remove(key string)
// Evict is called to determine which item(s) should be evicted.
// It should return one or more keys to be removed.
Evict() []string
}
EvictionPolicy defines the contract for a cache eviction strategy.
func NewNullEvictionPolicy ¶
func NewNullEvictionPolicy() EvictionPolicy
NewNullEvictionPolicy creates a new no-op eviction policy.
type FetchResult ¶
type FetchResult struct {
Body io.ReadCloser
Metadata *Metadata
}
FetchResult holds the data and metadata returned from a successful fetch operation.
type FetchUsesContext ¶ added in v0.4.1
type FetchUsesContext interface {
FetchUsesContext() bool
}
FetchUsesContext is an optional Fetcher extension for fetchers whose returned body continues using the provided context after Fetch returns.
type Fetcher ¶
type Fetcher interface {
Fetch(ctx context.Context, oldMetadata *Metadata) (*FetchResult, error)
}
Fetcher defines the contract for fetching an object from an origin.
type GetRequest ¶ added in v0.6.0
type GetRequest struct {
// IfNoneMatch compares the caller's validator against the cache's current
// representation validator.
IfNoneMatch string
}
GetRequest controls cache read behavior.
type GetResponse ¶ added in v0.6.0
type GetResponse struct {
Status GetStatus
Body io.ReadCloser
Metadata Metadata
}
GetResponse carries the result of a cache read decision. It also implements io.ReadCloser by delegating to Body, allowing callers to continue using io.ReadAll/Close on successful body-bearing responses.
func (*GetResponse) Close ¶ added in v0.6.0
func (r *GetResponse) Close() error
Close closes the response body when present.
type GetStatus ¶ added in v0.6.0
type GetStatus int
GetStatus describes the result of a cache read decision.
type GetStreamUsesContext ¶ added in v0.4.1
type GetStreamUsesContext interface {
GetStreamUsesContext() bool
}
GetStreamUsesContext is an optional Store extension for backends whose returned readers continue using the provided context after GetStream returns.
type GroupConfig ¶ added in v0.8.0
type GroupConfig struct {
Workers int
WorkerTimeout time.Duration
WorkerQueueDefault int
CloseTimeout time.Duration
}
GroupConfig holds the shared runtime defaults used by caches created from a CacheGroup.
type GroupOption ¶ added in v0.8.0
type GroupOption func(*GroupConfig) error
GroupOption configures a CacheGroup.
func WithGroupCloseTimeout ¶ added in v0.8.0
func WithGroupCloseTimeout(timeout time.Duration) GroupOption
WithGroupCloseTimeout sets the timeout for graceful shutdown of the shared cache group.
func WithGroupWorkerQueueDefault ¶ added in v0.8.0
func WithGroupWorkerQueueDefault(size int) GroupOption
WithGroupWorkerQueueDefault sets the default queue capacity used for group-attached caches.
func WithGroupWorkerTimeout ¶ added in v0.8.0
func WithGroupWorkerTimeout(timeout time.Duration) GroupOption
WithGroupWorkerTimeout sets the timeout applied to each shared runtime worker job.
func WithGroupWorkers ¶ added in v0.8.0
func WithGroupWorkers(count int) GroupOption
WithGroupWorkers sets the number of shared runtime workers used by caches in a group.
type Metadata ¶
Metadata holds essential metadata about a cached item. It is designed to be extensible for future needs (e.g., LastModified, Size).
func (Metadata) MarshalJSON ¶ added in v0.6.0
MarshalJSON writes the new CacheTag field name while remaining compatible with older stored metadata that used ETag on disk.
func (*Metadata) UnmarshalJSON ¶ added in v0.6.0
UnmarshalJSON accepts both CacheTag and the legacy ETag field names.
type Option ¶
Option is a function type that modifies the Config.
func WithCloseTimeout ¶ added in v0.5.0
WithCloseTimeout sets the timeout for graceful shutdown of the cache.
func WithFillLeaseTimeout ¶ added in v0.9.1
WithFillLeaseTimeout bounds how long a cache miss or lower-tier promotion response may hold the top-tier write lock while the caller consumes the body. The lease can preempt only after the target store's BeginSet has returned a sink; BeginSet setup time is bounded by the operation context instead. A timeout of 0 disables the lease timer; negative values are rejected.
func WithFreshness ¶ added in v0.5.0
WithFreshness sets the chain-wide default freshness duration for positive and negative cache entries across the ordered tier chain. A duration of 0 causes entries to be considered stale immediately.
func WithOpTimeout ¶ added in v0.5.0
WithOpTimeout sets the setup-stage timeout for cache operations like Get and Set.
func WithQueueLimit ¶ added in v0.8.0
WithQueueLimit sets the bounded queue capacity for a cache attached to a shared group runtime.
func WithTierFreshness ¶ added in v0.4.1
WithTierFreshness overrides the positive and negative freshness durations for a specific tier index. The configured values override the chain-wide default. A duration of 0 causes entries to be considered stale immediately.
func WithTiers ¶ added in v0.4.1
WithTiers sets the regular cache tiers in top-to-bottom order. It replaces the entire tier chain, so any WithTierFreshness override indices are validated against the final order during cache initialization.
func WithWeight ¶ added in v0.8.0
WithWeight sets the relative dequeue weight for a cache attached to a shared group runtime.
func WithWorkerQueue ¶ added in v0.5.0
WithWorkerQueue sets the queue capacity used for async background jobs.
func WithWorkerStrategy ¶ added in v0.5.0
WithWorkerStrategy sets the background worker strategy. Supported values are "pool" and "all"; unknown values return a configuration error.
func WithWorkerTimeout ¶ added in v0.5.0
WithWorkerTimeout sets the timeout applied to each background job.
func WithWorkers ¶ added in v0.5.0
WithWorkers sets the number of background workers used for async jobs.
type StagedWriteSink ¶ added in v0.9.1
StagedWriteSink is an optional store capability used by the cache core to separate invisible staging from visible publish.
type StagingStore ¶ added in v0.9.1
type StagingStore interface {
BeginStagedSet(ctx context.Context, key string, metadata *Metadata) (StagedWriteSink, error)
}
StagingStore is an optional Store extension. Stores that implement it let the cache coordinate only the short commit phase instead of holding cache-level same-key ownership for the full caller-controlled write lifetime. BeginStagedSet must keep the currently readable value for key unchanged until Commit succeeds. Abort and failed Commit must leave no visible value from the staged writer, and Delete must not wait for an uncommitted staged writer on the same key to commit or abort. Commit and Abort are terminal and must tolerate repeated cleanup calls because the cache may call Abort after a failed Commit to release hidden staging resources.
type Store ¶
type Store interface {
// GetStream retrieves an object and its metadata as a stream.
// Successful lookups must return non-nil metadata.
GetStream(ctx context.Context, key string) (io.ReadCloser, *Metadata, error)
// BeginSet returns a sink that stages data into the store.
// The currently readable value for key must remain unchanged until the
// returned sink is successfully closed or aborted.
// Implementations should honor ctx during setup; cache-level fill leases
// start only after BeginSet returns and cannot interrupt a blocked BeginSet.
BeginSet(ctx context.Context, key string, metadata *Metadata) (WriteSink, error)
// Delete removes the last committed object from the store.
// It must not wait for an uncommitted BeginSet sink on the same key to
// close or abort.
Delete(ctx context.Context, key string) error
// Stat retrieves metadata for an object without its data.
Stat(ctx context.Context, key string) (*Metadata, error)
}
Store defines the interface for a single cache storage tier (e.g., memory, disk).
type TierFreshnessOverride ¶ added in v0.5.0
type TierValidator ¶ added in v0.4.1
TierValidator is an optional Store extension for stores that restrict which positions they can safely occupy in the ordered tier chain.
type WriteSink ¶ added in v0.4.1
type WriteSink interface {
io.WriteCloser
Abort() error
}
WriteSink is the terminal write contract for cache stores. Close publishes the staged write, and Abort discards it. Implementations used by Store.BeginSet must not call back into Cache methods from Close or Abort because cache tiers may coordinate commit ordering while those terminal methods run. Write must return promptly when the underlying storage rejects or stalls a staged write; cache-level fill preemption cannot interrupt a blocked Write.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
cmd
|
|
|
daramjwee
command
|
|
|
cache_group
command
|
|
|
file_objstore
command
|
|
|
file_objstore_gcs_vind
command
|
|
|
file_objstore_provider
command
|
|
|
file_objstore_s3_vind
command
|
|
|
filestore_default
command
|
|
|
filestore_policy
command
Package main demonstrates basic FileStore usage with LRU eviction policy.
|
Package main demonstrates basic FileStore usage with LRU eviction policy. |
|
filestore_policy/demo
command
|
|
|
generic_cache
command
|
|
|
memstore_lru
command
|
|
|
memstore_s3fifo
command
|
|
|
memstore_sieve
command
|
|
|
multi_tier_cache
command
|
|
|
internal
|
|
|
pkg
|
|