placement

package
v1.0.3 Latest Latest
Warning

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

Go to latest
Published: Nov 19, 2026 License: MIT Imports: 25 Imported by: ? 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 placement publishes opaque backend objects to three Data nodes. Its local index has a single metadata writer; Meta replication and fencing are responsibilities of the process which owns this store.

Index

Constants

View Source
const Replicas = 3

Variables

View Source
var (
	ErrInsufficientNodes = errors.New("three distinct healthy data nodes required")
	ErrUnavailable       = errors.New("all recorded data replicas unavailable")
	ErrListLimit         = errors.New("cluster object listing exceeds configured limit")
)
View Source
var ErrGCGenerationChanged = errors.New("GC root generation changed")
View Source
var ErrPlacementChanged = errors.New("placement changed during maintenance")

Functions

func CanonicalReference

func CanonicalReference(r Record) chunk.Ref

func ExportNamespaceSnapshot

func ExportNamespaceSnapshot(ctx context.Context, source, namespaceID, destination string, limits SnapshotLimits) error

ExportNamespaceSnapshot retains only the selected namespace's records. The source is immutable/offline; global format and applied marker are preserved. Publication is bounded by limits and never overwrites an existing target.

func NamespaceReferencedReplacementMutations

func NamespaceReferencedReplacementMutations(ctx context.Context, current, selected, namespaceID string, keepKeys []string, limits SnapshotLimits, maxBytes int) ([][]byte, error)

NamespaceReferencedReplacementMutations restores only the selected scope's referenced records. Other current scopes remain byte-for-byte untouched.

func NamespaceReplacementMutations

func NamespaceReplacementMutations(ctx context.Context, current, selected, namespaceID string, limits SnapshotLimits, maxBytes int) ([][]byte, error)

NamespaceReplacementMutations prepares normal per-object WAL records, first deleting the target's current objects and then restoring its selected image. It never edits other scopes or either input; maxBytes bounds all payloads.

func ScopedKey

func ScopedKey(namespaceID, key string) (string, error)

ScopedKey is the physical placement key used by all-namespace maintenance walks and backup reference lookup. Ordinary backend calls take logical keys.

func SnapshotPruneMutations

func SnapshotPruneMutations(ctx context.Context, image string, keepKeys []string, limits SnapshotLimits, maxBytes int) ([][]byte, error)

SnapshotPruneMutations returns deterministic CAS deletes for image records outside keepKeys. The input must be immutable/offline. Apply these only in an unpublished restore WAL, retaining its native authority marker and prefix; deleting native rows without a WAL suffix would reintroduce them on replay.

func UnscopeKey

func UnscopeKey(key string) (namespaceID, logical string, err error)

UnscopeKey decodes a physical maintenance key and validates canonical form. Default-namespace keys return an empty namespace identity.

func WalkSnapshotRecords

func WalkSnapshotRecords(ctx context.Context, filename string, limits SnapshotLimits, fn func(string, Record) error) error

WalkSnapshotRecords validates an offline image and streams its records. The source is opened read-only and remains unchanged on validation failure.

Types

type CommitFunc

type CommitFunc func(context.Context, func(context.Context, uint64) ([]byte, error)) error

CommitFunc serializes this mutation in the same authority log as namespace changes. prepare is evaluated under that authority's write gate.

type Config

type Config struct {
	Path           string
	Region         string
	Nodes          func() []Member
	Client         *clusterdata.Client
	MaxObjectBytes int64
	MaxConcurrent  int
	MaxListEntries int
	// PrepareTTL bounds unpublished plans and their GC retention. It must cover
	// the caller's maximum data/metadata publication lease (default ten minutes).
	PrepareTTL        time.Duration
	DataVolumeBytes   int64
	DataVolumeObjects int
	DataVolumeSlots   int
}

type DataVolume

type DataVolume struct {
	ID           string    `json:"id"`
	NamespaceID  string    `json:"namespace_id,omitempty"`
	Epoch        uint64    `json:"epoch"`
	Replicas     []Replica `json:"replicas"`
	Sealed       bool      `json:"sealed"`
	Objects      int       `json:"objects"`
	EncodedBytes int64     `json:"encoded_bytes"`
	Slot         int       `json:"slot"`
}

DataVolume is one stable logical address and its current complete RF3 group. It owns no bytes itself: immutable Data object identities stay content based.

type GCOptions

type GCOptions struct {
	PlacementCursor string
	NodeID          string
	Cursor          string
	Grace           time.Duration
	MaxObjects      int
	MaxBytes        int64
	MaxDuration     time.Duration
	PageSize        int
	// Freeze MUST prevent Prepare, Publish, data-volume route changes and
	// metadata/root publication until fn returns, including during network I/O. A sequence check outside
	// this freeze cannot prevent a deletion/publication race. Root capture may
	// briefly take an authority barrier, but must release it before network I/O.
	Freeze   func(context.Context, func() error) error
	Roots    func(context.Context) (GCRoots, error)
	Validate func(context.Context, string) error
	Check    func(context.Context) error
}

type GCReport

type GCReport struct {
	NextPlacement     string `json:"next_placement,omitempty"`
	NextNode          string `json:"next_node,omitempty"`
	NextCursor        string `json:"next_cursor,omitempty"`
	Epoch             string `json:"epoch"`
	Generation        string `json:"generation"`
	Scanned           int    `json:"scanned"`
	Deleted           int    `json:"deleted"`
	Retained          int    `json:"retained"`
	Protected         int    `json:"protected"`
	RemovedPlacements int    `json:"removed_placements"`
	Bytes             int64  `json:"bytes"`
	Truncated         bool   `json:"truncated"`
}

type GCRoots

type GCRoots struct {
	Generation  string
	Descriptors []clusterdata.Descriptor
}

GCRoots must describe every namespace's current, historical and persistent backup references. Generation names the exact authority/catalog capture; it must change whenever a root can be added, removed or rebound.

type MaintenanceOptions

type MaintenanceOptions struct {
	Cursor        string
	MaxObjects    int
	MaxBytes      int64
	MaxDuration   time.Duration
	VerifyReceipt func(clusterdata.Receipt) error
	Check         func(context.Context) error
	OnResult      func(MaintenanceReport, error)
}

MaintenanceOptions bounds one all-namespace scan. VerifyReceipt must verify the durable signature with the target node's receipt key. Check must enforce the current metadata authority gate; it runs before I/O and before submitting the replacement to CommitFunc, which enforces admission under its own gate. Check is never reentered from a commit callback. OnResult reports background iterations; it must not modify the store from inside a commit callback.

type MaintenanceReport

type MaintenanceReport struct {
	Next        string `json:"next,omitempty"`
	Scanned     int    `json:"scanned"`
	Repaired    int    `json:"repaired"`
	Moved       int    `json:"moved"`
	Copied      int    `json:"copied"`
	Unavailable int    `json:"unavailable"`
	Bytes       int64  `json:"bytes"`
}

type Member

type Member struct {
	NodeID             string   `json:"node_id"`
	Region             string   `json:"region,omitempty"`
	StorageIncarnation string   `json:"storage_incarnation"`
	Endpoints          []string `json:"endpoints"`
	Healthy            bool     `json:"healthy"`
	Capacity           int64    `json:"capacity,omitempty"`
	FreeBytes          int64    `json:"free_bytes,omitempty"`
	Weight             float64  `json:"weight,omitempty"`
	Draining           bool     `json:"draining,omitempty"`
}

Member comes from a lease-aware registry. Draining members remain readable but accept no new placement. Capacity and FreeBytes are bytes; zero Capacity preserves the legacy unknown-capacity behavior. Weight zero means automatic.

func Placement

func Placement(key string, members []Member) ([]Member, error)

Placement chooses distinct NodeIDs by rendezvous score. Registry duplicates are rejected rather than counting one service twice toward durability.

type Prepared

type Prepared struct {
	Key         string    `json:"key"`
	Record      Record    `json:"record"`
	UploadID    string    `json:"upload_id"`
	AttemptID   string    `json:"attempt_id"`
	Existing    bool      `json:"existing"`
	Expires     time.Time `json:"expires"`
	VolumeEpoch uint64    `json:"volume_epoch"`
	Expected    string    `json:"expected,omitempty"`
}

type Record

type Record struct {
	Version      int                    `json:"version"`
	DataVolumeID string                 `json:"data_volume_id"`
	Descriptor   clusterdata.Descriptor `json:"descriptor"`
	Replicas     []Replica              `json:"replicas,omitempty"`
	ModTime      time.Time              `json:"mod_time"`
}

func (Record) Reference

func (r Record) Reference() chunk.Ref

type Replica

type Replica struct {
	NodeID             string `json:"node_id"`
	StorageIncarnation string `json:"storage_incarnation"`
}

type SnapshotInfo

type SnapshotInfo struct {
	Bytes           int64
	Records         int
	AppliedSequence uint64
}

func CheckSnapshot

func CheckSnapshot(ctx context.Context, filename string, limits SnapshotLimits) (SnapshotInfo, error)

CheckSnapshot checks pages, schema and every record in an offline image.

type SnapshotLimits

type SnapshotLimits struct {
	MaxBytes       int64
	MaxRecords     int
	MaxObjectBytes int64
}

SnapshotLimits bound offline inspection independently of a running Store.

type Store

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

Store borrows Client and Nodes. Each active Put/Get owns at most one bounded object buffer; concurrent replica uploads read that same immutable buffer.

func Open

func Open(cfg Config) (*Store, error)

func (*Store) Abort

func (s *Store) Abort(ctx context.Context, p Prepared) error

Abort releases only the in-memory capacity reservation. Uploaded entities and descriptor protection remain until normal root-aware GC can reclaim them.

func (*Store) AppliedSequence

func (s *Store) AppliedSequence(ctx context.Context) (seq uint64, err error)

AppliedSequence is the placement-domain replay marker, not global WAL head.

func (*Store) Apply

func (s *Store) Apply(ctx context.Context, sequence uint64, payload []byte) error

Apply atomically records the authority sequence with the mutation. Replaying an already applied prefix cannot restore an older object index.

func (*Store) BindAuthorityIdentity

func (s *Store) BindAuthorityIdentity(ctx context.Context) error

BindAuthorityIdentity publishes the stable backend identity before namespace initialization, including on an empty volume replicated to another path.

func (*Store) Close

func (s *Store) Close() error

func (*Store) Delete

func (s *Store) Delete(ctx context.Context, key string) error

Delete deliberately leaves immutable Data objects for future offline GC.

func (*Store) GC

func (s *Store) GC(ctx context.Context, opts GCOptions) (report GCReport, result error)

GC has separate mark and sweep phases inside a mandatory publication freeze. It first removes unreferenced index records using CAS, then captures a fresh generation and sweeps only exact old immutable entities absent from all roots. Root descriptors conservatively retain every physical copy, including copies still referenced by an old backup placement. New/prepared/in-flight objects have independent Store and Data protection leases. The operation is bounded and never deletes a failed migration's old entity as part of that migration.

func (*Store) Get

func (s *Store) Get(ctx context.Context, key string) (io.ReadCloser, error)

Get retries recorded replicas, never a replacement disk incarnation which happens to reuse the same NodeID. Bytes are verified before reader delivery.

func (*Store) List

func (s *Store) List(ctx context.Context, prefix string) ([]backend.Object, error)

func (*Store) Lookup

func (s *Store) Lookup(ctx context.Context, key string) (Record, error)

Lookup returns an immutable placement record. Endpoint changes are resolved from Registry without rewriting the persisted replica identities.

func (*Store) Members

func (s *Store) Members() []Member

func (*Store) NamespaceID

func (s *Store) NamespaceID() string

func (*Store) Prepare

func (s *Store) Prepare(ctx context.Context, key string, d clusterdata.Descriptor) (Prepared, error)

func (*Store) Publish

func (s *Store) Publish(ctx context.Context, p Prepared, receipts []clusterdata.Receipt) (Record, error)

Publish accepts externally verified durable receipts. The content-key lock selects one canonical representation and logical volume across all racers.

func (*Store) Put

func (s *Store) Put(ctx context.Context, key string, r io.Reader, size int64) error

func (*Store) PutChunk

func (s *Store) PutChunk(ctx context.Context, ref chunk.Ref, encoded io.Reader) error

PutChunk publishes the exact representation supplied by chunk.Store. Unlike the opaque Backend.Put interface, it preserves the original content identity and wire codec rather than treating encoded bytes as a new raw chunk.

func (*Store) PutImmutable

func (s *Store) PutImmutable(ctx context.Context, key string, r io.Reader, size int64) error

func (*Store) Rebalance

func (s *Store) Rebalance(ctx context.Context, opts MaintenanceOptions) (MaintenanceReport, error)

func (*Store) Region

func (s *Store) Region() string

Region is the configured read preference. ResolveReference itself never snapshots membership; batch callers can select locality from one snapshot.

func (*Store) ReleasePrepared

func (s *Store) ReleasePrepared(p Prepared)

ReleasePrepared is idempotent and only releases the bounded RAM capacity reservation. Descriptor/Data protection keeps its original expiry.

func (*Store) Repair

Repair restores three verified replicas while preserving healthy placements. Rebalance additionally moves objects onto their current weighted rendezvous targets, including evacuation of draining nodes. Both retain old entities; only the placement reference changes after all new durable receipts pass.

func (*Store) ResolveChunkReference

func (s *Store) ResolveChunkReference(ctx context.Context, hash string, rawSize int64) (chunk.Ref, error)

ResolveChunkReference supplies the already chosen codec and locator after content deduplication. The namespace remains the store view's authenticated scope; a caller cannot widen it by choosing a hash or volume.

func (*Store) ResolveReference

func (s *Store) ResolveReference(ctx context.Context, ref chunk.Ref) (Record, error)

ResolveReference derives an exact immutable representation from the file's approved reference, then resolves only its logical volume in RAM. It does not probe the per-content object index or read Data bytes.

func (*Store) ResolveVolume

func (s *Store) ResolveVolume(ctx context.Context, id string) (DataVolume, error)

ResolveVolume is an O(1) in-memory lookup. Returned slices belong to the caller; a scoped view cannot resolve another namespace's volume.

func (*Store) RunMaintenance

func (s *Store) RunMaintenance(ctx context.Context, interval time.Duration, limits MaintenanceOptions) error

RunMaintenance repairs and rebalances bounded pages until cancellation. Temporary failures are reported and retried on the next interval; invalid configuration fails before the loop. The caller owns the goroutine and must cancel and join it before closing the root Store or its borrowed Client.

func (*Store) Scope

func (s *Store) Scope(namespaceID string) (*Store, error)

Scope borrows this root's database, authority-domain committer, object slots and key locks. Closing a view never closes the owning root Store.

func (*Store) SetCommitter

func (s *Store) SetCommitter(commit CommitFunc)

SetCommitter must be called before exposing the store or starting core.

func (*Store) Snapshot

func (s *Store) Snapshot(ctx context.Context, w io.Writer) error

Snapshot writes one consistent native index image. The owner must also hold the unified authority checkpoint barrier when pairing it with namespace and authority images; an isolated index snapshot is not a cluster checkpoint.

func (*Store) Stat

func (s *Store) Stat(ctx context.Context, key string) (backend.Object, error)

func (*Store) StorageIdentity

func (s *Store) StorageIdentity() string

func (*Store) WalkRecords

func (s *Store) WalkRecords(ctx context.Context, fn func(string, Record) error) error

WalkRecords visits bounded records without materializing the entire index. The callback must not modify this Store or retain borrowed transaction data.

Jump to

Keyboard shortcuts

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