cache

package
v0.8.0 Latest Latest
Warning

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

Go to latest
Published: Nov 19, 2026 License: AGPL-3.0 Imports: 67 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package cache acquires verified source bytes into immutable memory or OCI-backed filesystems.

Index

Constants

View Source
const Forever time.Duration = -1

Forever retains a successfully resolved pin regardless of elapsed time.

Variables

This section is empty.

Functions

func AcquisitionIdentity

func AcquisitionIdentity(input any) string

AcquisitionIdentity reports the held generation and shaping of cache-owned filesystems. Anonymous inputs and wrappers have no acquisition authority.

func CredentialsUnavailable

func CredentialsUnavailable(err error) bool

CredentialsUnavailable leaves cancellation precedence and retry decisions to the caller.

func FileName

func FileName(input fs.FS) string

FileName returns the acquired payload path, or empty for a directory view.

func MachineCredentialErr

func MachineCredentialErr(cause error) error

MachineCredentialErr masks machine diagnostics while preserving typed causes.

func NameBlob

func NameBlob(name string, generation fs.FS) fs.FS

NameBlob gives an acquired Blob generation a filename and shaping identity.

func RecordInventory

func RecordInventory[T io.WriterTo](ctx context.Context, c *Cache, inventory AcceptedInventory[T]) error

RecordInventory atomically replaces accepted content and its searchable provenance.

func RenderPersistenceDisabledReason

func RenderPersistenceDisabledReason() string

RenderPersistenceDisabledReason returns why this binary cannot persist renders, or an empty string when it can.

Types

type AcceptedInventory

type AcceptedInventory[T io.WriterTo] struct {
	Key, Lookup, Acceptance string
	History                 RenderHistory
	Content                 T
	Work                    *manifest.AcquisitionWork
}

AcceptedInventory publishes one complete inventory and its source evidence.

type ArchiveKey

type ArchiveKey struct {
	// Content describes the producer inputs.
	Content any
	Ignore  string
	Policy  string
	// Required lists unprefixed descriptor annotation names; it does not affect identity.
	Required []string
}

ArchiveKey identifies an archive and its source-ignore policy. Content MUST include the effective credentials used by the producer.

type BlobKey

type BlobKey struct {
	// Content describes the producer inputs, or a nonempty identity for rendered content.
	Content any
	// Render selects pending work or accepted history; zero denotes source content.
	Render RenderMode
	// Validate checks a candidate against this caller's inputs under the acquisition lock.
	// Streams belong to the callback; the callback never affects identity.
	Validate func(context.Context, fs.FS) (bool, error)
	// Observe receives the validated candidate or nil before production, once per call.
	// Returning true completes this call without producing or publishing a generation.
	Observe func(context.Context, fs.FS) (bool, error)
	// Required lists unprefixed descriptor annotation names; it does not affect identity.
	Required []string
}

BlobKey identifies single-file content. Content MUST include the effective credentials used by the producer.

func InputFrameIdentity

func InputFrameIdentity(origin, url string, content *Frame) (BlobKey, string)

InputFrameIdentity separates stable source lookup from certified frame content.

type Cache

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

Cache owns acquired generations until Close. Readers MUST finish before Close.

func New

func New(ctx context.Context, root string) (*Cache, error)

New selects backing once. An empty root allocates no files or directories.

func (*Cache) Acquire

func (c *Cache) Acquire(
	ctx context.Context,
	key ArchiveKey,
	policyValue *Policy,
	produce func(context.Context, ProducerInput) (ProducerResult, error),
) (fs.FS, ocispec.Descriptor, string, error)

Acquire publishes a complete archive or revalidates its previous generation after produce succeeds. Its acquisition identity is empty on failure.

func (*Cache) Blob

func (c *Cache) Blob(
	ctx context.Context,
	key BlobKey,
	policyValue *Policy,
	produce func(context.Context, ProducerInput) (ProducerResult, error),
) (fs.FS, ocispec.Descriptor, string, error)

Blob returns an immutable filesystem over a complete generation. A nil producer only looks up a fresh generation; zero Policy.MaxAge with a producer replaces the generation. Unchanged production retains the previous payload and replaces its upstream metadata. A successful generation rejected by Validate is returned once without being retained for reuse. Its acquisition identity is empty on failure.

func (*Cache) CanPersistRenders

func (c *Cache) CanPersistRenders() bool

CanPersistRenders reports whether the cache owner can persist accepted renders.

func (*Cache) Close

func (c *Cache) Close() error

Close releases this owner's share. It MUST follow all acquired readers.

func (*Cache) Compose

func (c *Cache) Compose(
	ctx context.Context,
	request Composition,
	policyValue *Policy,
) (fs.FS, ocispec.Descriptor, string, error)

Compose borrows input filesystems until production returns. Output backing belongs to the cache.

func (*Cache) Directory

func (c *Cache) Directory() string

Directory returns the resolved disk boundary, or empty for a memory owner.

func (*Cache) Git

func (c *Cache) Git(
	ctx context.Context,
	key GitKey,
	policyValue *Policy,
	produce func(context.Context, storage.Storer, billy.Filesystem) (plumbing.Hash, error),
) (*GitGeneration, string, error)

Git acquires a private generation through the common freshness and publication path. Its acquisition identity is empty on failure.

func (*Cache) ProducersForPaths

func (c *Cache) ProducersForPaths(
	ctx context.Context,
	query []manifest.SourceEvidence,
) (map[manifest.NamedResource][]manifest.SourceEvidence, error)

ProducersForPaths returns producers whose accepted source paths reach the supplied changes. The result is positive admission evidence, never proof that an inventory remains complete.

func (*Cache) RecordRender

func (c *Cache) RecordRender(ctx context.Context, acceptance RenderAcceptance) error

RecordRender MUST publish accepted frames and searchable source evidence together.

func (*Cache) RenderMetadata

func (c *Cache) RenderMetadata(
	ctx context.Context,
	content, lookup string,
	work *manifest.AcquisitionWork,
) (RenderMetadata, error)

RenderMetadata returns the current descriptor and generation without opening the payload. Enabled reports whether this owner can persist renders. A nonempty lookup MUST identify Blob accepted history for this content; an empty lookup derives it.

type Composition

type Composition struct {
	// Content retains contextual facts beyond the cache-derived filesystem and operation identity.
	Content any
	Base    CompositionInput
	Inputs  []CompositionInput
	Copies  []Copy
	Policy  string
	Ignore  string
}

Composition MUST identify the complete base and ordered operations before cache reuse.

type CompositionInput

type CompositionInput struct {
	FS fs.FS
	// Empty Content forces fresh production because the backing can change.
	Content string
}

CompositionInput MUST identify immutable backing or force fresh production.

type Copy

type Copy struct {
	Input   int
	From    string
	To      string
	Exclude []string
	Mode    CopyMode
	// ExtractContent retains contextual identity facts for nested extraction acquisitions.
	// It constructs opaque facts only, without filesystem access or publication.
	ExtractContent func(path, destination string) any
}

Copy paths MUST use secure resolution for PlaceTree and relative archive paths otherwise.

type CopyMode

type CopyMode uint8

CopyMode MUST select one of the supported operations.

const (
	CopyFiles CopyMode = iota
	MergeYAML
	ExtractArchive
	PlaceTree
)

Copy modes retain the established overwrite, merge, and extraction semantics.

type Error

type Error struct{ Err error }

Error MUST retain manifest.ErrFlux and the underlying cause.

func (*Error) Error

func (e *Error) Error() string

func (*Error) Unwrap

func (e *Error) Unwrap() []error

type Frame

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

Frame retains immutable metadata and the acquired generation, never a mutable lookup. It MUST NOT be copied after payload access.

func NewFrame

func NewFrame(domain string, metadata any, payload []byte) (*Frame, error)

NewFrame returns no frame when metadata exceeds the optional persistence limit.

func OpenFrame

func OpenFrame(ctx context.Context, domain string, generation fs.FS, metadata any) (*Frame, error)

OpenFrame decodes the index without hydrating payloads or retaining an open file.

func (*Frame) History

History requires current final content before it supplies accepted records.

func (*Frame) Payload

func (f *Frame) Payload(ctx context.Context) ([]byte, error)

Payload returns immutable bytes after validating the complete payload identity.

func (*Frame) PreparePublication

func (f *Frame) PreparePublication(ctx context.Context, input FramePublicationInput) (*FramePublication, error)

PreparePublication returns no publication when complete evidence cannot be fingerprinted or encoded within the limit.

func (*Frame) ReadPayload

func (f *Frame) ReadPayload(ctx context.Context, offset int64, size int) ([]byte, error)

ReadPayload uses payload-relative coordinates within the retained immutable generation.

type FramePublication

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

FramePublication keeps prepared bytes and identities immutable across concurrent callers.

func (*FramePublication) Frame

func (p *FramePublication) Frame() *Frame

Frame exposes the prepared snapshot without changing the original acceptance.

func (*FramePublication) Identity

func (p *FramePublication) Identity() string

Identity binds deduplication to the complete prepared publication.

func (*FramePublication) WriteTo

func (p *FramePublication) WriteTo(w io.Writer) (int64, error)

WriteTo preserves the original writer error and byte count.

type FramePublicationInput

type FramePublicationInput struct {
	Owner    manifest.NamedResource
	Content  any
	Records  iter.Seq2[manifest.NamedResource, manifest.DiscoveryRecord]
	Complete bool
}

FramePublicationInput MUST describe the accepted output under Owner.

type GitGeneration

type GitGeneration struct {
	Backing  billy.Filesystem
	Worktree billy.Filesystem
	Commit   plumbing.Hash
	// contains filtered or unexported fields
}

GitGeneration retains sealed object backing and any upstream recursive checkout. Every reader MUST construct its own storer; publication retains no producer handles.

type GitKey

type GitKey struct {
	Content           any
	Ref               string
	RecurseSubmodules bool
}

GitKey identifies a Git family, its normalized requested ref and recursion policy. Content MUST include the effective credentials used by the producer.

type Policy

type Policy struct {
	// Work borrows counters owned by this acquisition caller.
	Work *manifest.AcquisitionWork
	// HistoryWork borrows separate cells for accepted render history.
	HistoryWork *manifest.AcquisitionWork
	// Admit runs before each production attempt's timeout and staged storage.
	// Success MUST return a non-nil release, called once after cleanup/publication.
	// On error the callback owns partial cleanup; cache failures do not retry or persist outcomes.
	Admit func(context.Context) (func(), error)
	// Timeout bounds each production attempt; nil adds no deadline.
	Timeout *time.Duration
	// MaxAge bounds freshness; Forever retains immutable pins.
	MaxAge time.Duration
	// Retry applies only to producer failures.
	Retry RetryConfig
}

Policy is the caller's immutable freshness, retry, admission and operation timeout policy.

type ProducerInput

type ProducerInput struct {
	io.Writer
	// contains filtered or unexported fields
}

ProducerInput writes new content or exposes the owner's last complete generation.

func (ProducerInput) Previous

func (p ProducerInput) Previous(ctx context.Context) (*ocispec.Descriptor, error)

Previous returns independent upstream metadata, or nil when no usable payload exists. It retains no open reader and MUST only be called during production.

func (ProducerInput) Work

Work returns the physical acquisition counters borrowed from the caller.

type ProducerResult

type ProducerResult struct {
	ocispec.Descriptor

	// Unchanged requires a usable previous payload and forbids writing new bytes.
	Unchanged bool
}

ProducerResult reports new bytes or successful validation of the previous payload.

type RenderAcceptance

type RenderAcceptance struct {
	Owner       manifest.NamedResource
	Receipt     *manifest.RenderReceipt
	Records     iter.Seq2[manifest.NamedResource, manifest.DiscoveryRecord]
	Sources     []manifest.SourceEvidence
	Content     any
	Work        *manifest.RenderWork
	Source      manifest.SourceIdentity
	Reads       *store.ReadSet
	OutputReads *store.ReadSet
}

RenderAcceptance MUST retain complete emission evidence and live captures through publication.

type RenderBinding

type RenderBinding[P any] struct {
	Key      string                 `json:"Key"`
	Source   manifest.NamedResource `json:"Source"`
	Artifact store.ArtifactHistory  `json:"Artifact"`
	Policy   P                      `json:"Policy"`
}

RenderBinding MUST keep raw render identity separate from the acquisition family.

func (*RenderBinding[P]) Equal

func (b *RenderBinding[P]) Equal(other *RenderBinding[P], equalPolicy func(*P, *P) bool) bool

Equal MUST compare typed policy without hashing or reflection.

func (*RenderBinding[P]) Fingerprint

func (b *RenderBinding[P]) Fingerprint() string

Fingerprint MUST derive history identity within the cache owner.

func (*RenderBinding[P]) Refresh

func (b *RenderBinding[P]) Refresh(key string, source manifest.NamedResource, artifact *store.SourceArtifact)

Refresh MUST preserve retained policy slices and earlier request snapshots.

type RenderFrame

type RenderFrame struct {
	Key     string
	Lookup  string
	Binding string
	Output  []byte
	Stored  *Frame
}

RenderFrame MUST retain Frame by pointer because Frame contains atomic state.

func OpenRenderFrame

func OpenRenderFrame(ctx context.Context, domain string, generation fs.FS, metadata any) (RenderFrame, error)

OpenRenderFrame MUST preserve storage error classification while hydrating reusable output.

func (*RenderFrame) Encode

func (f *RenderFrame) Encode(domain string, metadata any) (*Frame, error)

Encode MUST reuse immutable stored envelopes until the binding changes.

func (*RenderFrame) Rebind

func (f *RenderFrame) Rebind(binding string)

Rebind MUST operate on a renderer's copied frame to preserve previous receipts.

type RenderHistory

type RenderHistory struct {
	Owner   manifest.NamedResource `json:"Owner"`
	Sources []manifest.SourceEvidence
}

RenderHistory supplies source paths associated with one accepted inventory.

type RenderMetadata

type RenderMetadata struct {
	Descriptor ocispec.Descriptor
	Identity   string
	Enabled    bool
}

RenderMetadata identifies the accepted generation without opening its payload.

type RenderMode

type RenderMode uint8

RenderMode identifies the acquisition phase of rendered content.

const (
	// RenderPending validates accepted history, then coalesces immutable work until Close.
	RenderPending RenderMode = iota + 1
	// RenderAccepted persists only complete accepted render history with identified backing.
	RenderAccepted
)

type RenderPublication

type RenderPublication struct {
	Frame    RenderFrame
	Domain   string
	Metadata any
	Content  any
	Sources  []manifest.SourceEvidence
}

RenderPublication MUST project engine metadata without publishing or encoding it.

type RetryConfig

type RetryConfig struct {
	// Attempts includes the first try; values <= 1 disable retries.
	Attempts int
	// MinWait defaults to 750 milliseconds when nonpositive.
	MinWait time.Duration
	// MaxWait defaults to 15 minutes when nonpositive.
	MaxWait time.Duration
	// Jitter is a fraction in [0,1]; non-finite values disable jitter.
	Jitter float64
}

RetryConfig bounds producer attempts within one acquisition.

type SweepOpts

type SweepOpts struct {
	// MaxAge retires named tags whose payload mtime predates now-MaxAge.
	// Coalesced access timestamps allow one second of retention grace.
	// Zero disables age retirement; unreachable Git generations are always collected.
	MaxAge time.Duration
	// DryRun reports the selection without locking or changing the cache.
	DryRun bool
}

SweepOpts tunes Sweep's behavior.

type SweepResult

type SweepResult struct {
	// Removed lists selected tags and absolute Git-generation paths, sorted together.
	Removed []string
	// Bytes counts selected Git-generation bytes only. Upstream graph GC decides
	// blob reclamation; dry-run does not estimate reclaimed blob bytes.
	Bytes int64
	// Errors aggregates failures applying the selection.
	Errors []error
}

SweepResult summarizes Sweep's selection and any failures applying it.

func Sweep

func Sweep(ctx context.Context, root string, opts SweepOpts) (SweepResult, error)

Sweep retires unused named tags and collects unreachable Git generations. Destructive sweeps require exclusive store ownership; dry-run never writes.

type TerminalError

type TerminalError struct {
	// Err retains the typed cause and its diagnostic text.
	Err error
	// Attempted distinguishes producer exhaustion from a suppressed non-attempt.
	Attempted bool
}

TerminalError prevents an outer acquisition from repeating a completed sequence.

func (*TerminalError) Error

func (e *TerminalError) Error() string

Error preserves the underlying diagnostic.

func (*TerminalError) Unwrap

func (e *TerminalError) Unwrap() []error

Unwrap exposes the domain sentinel and the underlying cause.

Jump to

Keyboard shortcuts

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