Documentation
¶
Overview ¶
Package daramjwee contains the core implementation of the Cache interface.
Index ¶
- Constants
- Variables
- func ReadAll(rc io.ReadCloser) ([]byte, error)
- type AdmissionPolicy
- type BeginSetUsesContext
- type BodySpec
- 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 DropReason
- type EvictionPolicy
- type FanoutSpec
- type FetchResult
- type FetchUsesContext
- type Fetcher
- type Freshness
- type GetRequest
- type GetResponse
- type GetStatus
- type GetStreamUsesContext
- type GroupConfig
- type GroupOption
- type Job
- type JobKind
- type Metadata
- type Observation
- 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 WithPromotionProbation(maxEntries int) 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 Outcome
- type Planner
- type PublishSpec
- type ReadPlan
- type ReadSession
- type RefreshSpec
- type ReplySpec
- type SourceKind
- type StagedWriteSink
- type StagingStore
- type Store
- type TierFreshnessOverride
- type TierValidator
- type UpperTierHealth
- type WriteSink
Constants ¶
const ( DropReasonRejected = runtime.DropReasonRejected DropReasonShutdown = runtime.DropReasonShutdown )
const ( JobKindRefresh = runtime.JobKindRefresh JobKindPersist = runtime.JobKindPersist )
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 ErrCommitOutcomeUnknown = errors.New("daramjwee: commit outcome is unknown")
ErrCommitOutcomeUnknown means a staged commit reached durable storage but its final outcome could not be confirmed. The store must fail closed until it is reconciled or reopened safely.
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 ErrReadStateUncertain = errors.New("daramjwee: read state is uncertain")
ErrReadStateUncertain means a higher tier owns a newer generation but cannot currently prove its contents. Callers must not fall through to older tiers.
var ErrTopWriteInvalidated = errors.New("daramjwee: top-tier write invalidated")
Functions ¶
Types ¶
type AdmissionPolicy ¶ added in v0.15.0
type AdmissionPolicy int
AdmissionPolicy controls lower-tier promotion.
const ( AdmissionAllowed AdmissionPolicy = iota AdmissionDeferred )
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
PromotionProbationEntries int
// 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) Close ¶
func (c *DaramjweeCache) Close()
Close safely shuts down the worker. Multiple calls are safe: the first call performs the shutdown and subsequent calls block until the first shutdown completes, then return the same result.
func (*DaramjweeCache) Delete ¶
func (c *DaramjweeCache) Delete(ctx context.Context, key string) error
Delete sequentially deletes an object from all tiers to prevent deadlocks. Deletion order is bottom-up: lower tiers are deleted before the top tier to prevent resurrection of deleted values through lower-tier promotion.
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 DropReason ¶ added in v0.15.0
type DropReason = runtime.DropReason
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 FanoutSpec ¶ added in v0.15.0
type FanoutSpec int
const ( FanoutNone FanoutSpec = iota FanoutAfterPublish )
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 Freshness ¶ added in v0.15.0
type Freshness int
Freshness classifies a cache entry by its freshness window.
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 CloneMetadata ¶ added in v0.9.2
CloneMetadata returns a deep copy of the given Metadata. It returns nil if meta is nil.
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 Observation ¶ added in v0.15.0
type Observation struct {
Source SourceKind
SourceTier int
EntryNegative bool
Freshness Freshness
ConditionalMatched bool
UpperTiersHealth UpperTierHealth
Admission AdmissionPolicy
HasTopStore bool
}
Observation contains the I/O-free facts used to plan a cache read.
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 WithPromotionProbation ¶ added in v0.14.1
WithPromotionProbation enables 2-hit probation for lower-tier promotion: the first lower-tier hit for a key is served without promoting to the top tier, and only the second hit promotes. maxEntries bounds the probation set with FIFO eviction. This prevents one-hit wonders from polluting the hot tier at the cost of one extra lower-tier read per cold key.
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 Planner ¶ added in v0.15.0
type Planner struct{}
Planner converts observations into read plans without performing I/O.
func (*Planner) Plan ¶ added in v0.15.0
func (p *Planner) Plan(obs Observation) ReadPlan
type PublishSpec ¶ added in v0.15.0
type PublishSpec int
const ( PublishNone PublishSpec = iota PublishOnEOF )
type ReadPlan ¶ added in v0.15.0
type ReadPlan struct {
Reply ReplySpec
Body BodySpec
Publish PublishSpec
Refresh RefreshSpec
Fanout FanoutSpec
}
ReadPlan describes the response and side effects for a cache read.
type ReadSession ¶ added in v0.15.0
type ReadSession struct {
// contains filtered or unexported fields
}
ReadSession releases resources owned by one Get call exactly once.
func (*ReadSession) Finish ¶ added in v0.15.0
func (s *ReadSession) Finish(outcome Outcome) error
Finish releases all resources. Repeated calls are harmless.
func (*ReadSession) SetMissLeader ¶ added in v0.15.0
func (s *ReadSession) SetMissLeader(_ *missLead, release func())
SetMissLeader arranges for miss leadership to be released with the session.
func (*ReadSession) WaitForPublish ¶ added in v0.15.0
func (s *ReadSession) WaitForPublish()
WaitForPublish blocks until Finish is called.
type RefreshSpec ¶ added in v0.15.0
type RefreshSpec int
const ( RefreshNone RefreshSpec = iota RefreshOnClose )
type SourceKind ¶ added in v0.15.0
type SourceKind int
SourceKind identifies where a cache lookup found an entry.
const ( SourceNone SourceKind = iota SourceTop SourceLower )
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 confirmed failed Commit must leave no visible value from the staged writer. An error matching ErrCommitOutcomeUnknown is an indeterminate outcome, not a confirmed failure; the store must fail closed until reconciliation. 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 UpperTierHealth ¶ added in v0.15.0
type UpperTierHealth int
UpperTierHealth reports whether every tier above the source was readable.
const ( UpperTiersClean UpperTierHealth = iota UpperTiersDirty )
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
¶
- background_runtime.go
- cache.go
- cache_context.go
- cache_persist.go
- cache_pool.go
- cache_read.go
- cache_read_execution.go
- cache_refresh.go
- cache_refresh_callback.go
- daramjwee.go
- group.go
- group_options.go
- logging.go
- metadata_json.go
- miss_coalesce.go
- nullstore.go
- options.go
- planner.go
- promotion_probation.go
- read_session.go
- streaming.go
- write_coordinator.go
- write_coordinator_sink_base.go
- write_coordinator_sinks.go
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
|
|
|
stripedlock
Package stripedlock provides a striped lock manager for reducing contention by distributing keys across a fixed number of mutexes.
|
Package stripedlock provides a striped lock manager for reducing contention by distributing keys across a fixed number of mutexes. |
|
pkg
|
|