storage

package
v1.10.0 Latest Latest
Warning

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

Go to latest
Published: Aug 23, 2026 License: MIT Imports: 39 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 storage's shale-cluster-backed room (app-persistence) KV store.

Key names and JSON schema match the slatedb room repo, so the on-wire record is identical across both slatedb-tagged backends. Co-location is by shaleShardKey, not by renaming keys.

Key layout (all sharded on {app-slug})

rooms/<app-slug>/<uuid>                     JSON record, carries byte_total + key_count
roomkv/<app-slug>/<uuid>/<key>              raw value bytes, sentinel-prefixed
roomcreate/<app-slug>/<subnet>/<ts>/<uuid>  creation ledger marker
roombytes/<app-slug>                        per-app byte counter

Everything an app owns co-locates on one shard, so loading a room, counting its creations and checking the per-app cap are all single-shard. The room repo never fans out on the hot path.

Both caps are strict

A CAS read-set is discrete key checks and ScanPrefix is not allowed inside a transaction, so a cap whose magnitude is "the sum over a key range" needs a discrete counter the read-set can carry. The two caps use different members:

  • Per-APP: roombytes/<app> is read-checked and incremented in the same CAS, so two concurrent same-app writers cannot both pass a stale sum.
  • Per-ROOM: byte_total + key_count live ON the room record and are validated inside the CAS. That record is already in the read-set and is rewritten on every put, so two writers to DISTINCT keys of one room still conflict on it and the loser retries against updated totals.

Every room key co-shards, so a put is a single-shard read-check-validate-write with no reserve/confirm split.

Index

Constants

View Source
const CompressedBodyPrefixLen = len(magicV1)

CompressedBodyPrefixLen is the width of the at-rest framing prefix that EncodeCompressedBody writes ahead of the zstd stream. Exported so a caller computing the quota-relevant payload size subtracts the real width rather than hardcoding it.

View Source
const CoordinatorCAS = "cas"

CoordinatorCAS selects the CAS/lease coordination adapter for ShaleConfig.Coordinator: membership as one document in the ConditionalStore. It is the only clustered adapter; the empty string is single-node.

View Source
const (
	StepEntryWritten durable.StepName = "entry"
)

Steps an insert records. Only the ones a resolver needs to distinguish are named: what matters is whether the ENTRY was written, because that is the thing a rollback removes.

Variables

View Source
var (
	ErrNotFound       = domain.ErrNotFound
	ErrServiceFull    = domain.ErrServiceFull
	ErrTooManyNewKeys = domain.ErrTooManyNewKeys
	ErrSlugTaken      = domain.ErrSlugTaken
	ErrAppRoomsFull   = domain.ErrAppRoomsFull
	ErrRoomDataFull   = domain.ErrRoomDataFull
	ErrOverUserQuota  = domain.ErrOverUserQuota
)
View Source
var ErrConcurrentChange = domain.ErrConcurrentChange

ErrConcurrentChange aliases the domain-owned sentinel, matching how the rest of the storage error vocabulary is re-exported.

View Source
var ErrFenced = errors.New("storage: upload fenced; recovery took it over")

ErrFenced reports that the caller's blob-ownership epoch is stale: recovery took this upload over and its bytes are gone or going. The write must abort.

It is not a transient - retrying with the same epoch can only fail again, and retrying with a fresh one would bind bytes that no longer exist.

View Source
var ResolveGrace = 10 * time.Minute

ResolveGrace is how old an intent must be before a sweep may act on it.

It is not a tuning knob, it is a correctness requirement. Which pod HANDLES a request is chosen by the load balancer; which pod STORES that request's intent is chosen by hashing the owner. The two are unrelated, so a node's own local intents are routinely created by uploads other nodes are handling right now - and an in-flight intent is indistinguishable from an abandoned one.

The value guard cannot separate them: a live upload's entry MATCHES the intent describing it, so a guarded delete would fire against a running request. Only elapsed time distinguishes the two, so this MUST exceed the longest plausible upload (the same contract DefaultOrphanGrace carries for the blob plane). A var so tests can shrink it.

Functions

func DecodeCompressedStream added in v0.45.0

func DecodeCompressedStream(rc io.ReadCloser, label string) (io.ReadCloser, error)

DecodeCompressedStream wraps a raw stored blob stream in a reader yielding the DECOMPRESSED bytes, closing the underlying reader on Close (including on any error path). Shared by the standalone GetReader and the shale-blob read path so both decode identically. label names the blob in error messages.

func EncodeCompressedBody added in v0.45.0

func EncodeCompressedBody(r io.Reader) ([]byte, error)

EncodeCompressedBody returns `magic + zstd(r)` buffered in memory: the exact at-rest format Put writes and DecodeCompressedStream reads. The shale-blob stage path streams to BlobKV.StageBlob rather than through CompressedBlobStore.Put, and calls this so a site file is stored in the same format as a paste. The body is bounded by one file (the untar's per-file cap), so buffering is safe.

Not the only encoder of this format: the service-layer streaming upload path re-implements it to hash, cap and encode stdin in a single pass. See magicV1.

func EncodeCompressedTo added in v0.99.1

func EncodeCompressedTo(w io.Writer, r io.Reader) (int64, string, error)

EncodeCompressedTo streams magic + zstd(r) into w, returning the bytes written and the sha256 of the RAW input.

Exists so a caller can encode to a file and learn the exact at-rest length WITHOUT holding the body: staging with a known size lets the object store choose a sane part size, where an unknown length makes it allocate a full multipart part buffer - measured at 128 MiB of RSS growth for a 32 MiB upload, worse than the buffering this replaced.

func WithBlobOwnerEpoch added in v0.97.0

func WithBlobOwnerEpoch(ctx context.Context, epoch int64) context.Context

WithBlobOwnerEpoch returns a child context carrying the epoch this upload claimed, for the authoritative write to check as it binds.

func WithPendingBinds added in v0.95.0

func WithPendingBinds(ctx context.Context, refs []cluster.BlobRef) context.Context

WithPendingBinds returns a child context carrying refs for the next authoritative {slug} write triggered under it. Empty refs return the parent unchanged (the no-bind path).

Types

type AppendResult

type AppendResult = domain.AppendResult

type BlobStore

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

BlobStore is a content-addressed on-disk store. Bytes live at <root>/<sha256[:2]>/<sha256> so directory fanout stays sane; records pointing at the same bytes share one file.

It stores whatever bytes it is handed and does NOT satisfy service.BlobStore: the at-rest encoding is CompressedBlobStore's, and every wiring path must pass through that wrapper. Giving the raw store the encoder methods would let a mis-wiring compile and then serve undecoded bytes.

func NewBlobStore

func NewBlobStore(root string) (*BlobStore, error)

func (*BlobStore) Get

func (b *BlobStore) Get(sha string) ([]byte, error)

Get returns the bytes for sha, or ErrNotFound.

func (*BlobStore) GetReader added in v0.44.0

func (b *BlobStore) GetReader(sha string) (io.ReadCloser, int64, error)

GetReader returns a streaming reader over the bytes for sha, or ErrNotFound. The caller MUST Close it. The int64 is the on-disk length of the raw stored bytes: for blobs wrapped by CompressedBlobStore that is the compressed length, not the decoded one.

func (*BlobStore) Put

func (b *BlobStore) Put(sha string, r io.Reader, size int64) error

Put streams r into the content-addressed location for sha. An existing file at the destination is trusted as-is: only a sha256 collision could reach it with different bytes. size is accepted for parity with S3-shaped backends that need Content-Length up front; the disk store does not need it.

func (*BlobStore) Remove

func (b *BlobStore) Remove(sha string) error

Remove deletes a blob by sha. No-op when the file is already gone (treat as success - the GC may have removed it under us).

func (*BlobStore) WalkBlobs

func (b *BlobStore) WalkBlobs(fn func(sha string) error) error

WalkBlobs visits every blob file under root and calls fn(sha) with the sha encoded in the filename. Stops on the first non-nil error.

type CompressedBlobStore added in v0.42.0

type CompressedBlobStore struct {
	Inner innerBlobStore
}

CompressedBlobStore wraps another BlobStore and transparently zstd-encodes on Put, decodes on Get. The at-rest format carries a 4-byte magic prefix; a blob without it is returned as-is, so uncompressed blobs stay readable.

Compression lives in the storage layer so callers above keep thinking in original uncompressed bytes, and dedup stays keyed on the sha256 of those original bytes.

func NewCompressedBlobStore added in v0.42.0

func NewCompressedBlobStore(inner innerBlobStore) *CompressedBlobStore

NewCompressedBlobStore wraps inner with the compression layer.

func (*CompressedBlobStore) EncodeBody added in v0.75.0

func (s *CompressedBlobStore) EncodeBody(r io.Reader) ([]byte, int, error)

EncodeBody implements the service-side BlobStore encoder, returning the at-rest body and the payload size excluding the framing prefix, so a caller needing the on-disk footprint does not redo the framing arithmetic.

func (*CompressedBlobStore) Get added in v0.42.0

func (c *CompressedBlobStore) Get(sha string) ([]byte, error)

Get returns the UNCOMPRESSED bytes for sha. A blob without the magic header is returned as-is, so an uncompressed blob stays readable without a mass rewrite of the store.

func (*CompressedBlobStore) GetReader added in v0.44.0

func (c *CompressedBlobStore) GetReader(sha string) (io.ReadCloser, int64, error)

GetReader streams the UNCOMPRESSED bytes for sha without buffering the whole blob the way Get does, yielding byte-identical output. The caller MUST Close it: Close releases both the zstd decoder and the inner reader. The int64 is the inner COMPRESSED length, not the decoded length, so it must not be used as a Content-Length.

func (*CompressedBlobStore) Put added in v0.42.0

func (c *CompressedBlobStore) Put(sha string, r io.Reader, _ int64) error

Put reads UNCOMPRESSED bytes from r and writes `magic + zstd(bytes)` to the inner store. The size argument is ignored: the inner store is handed the COMPRESSED length, which is what a backend wanting a Content-Length needs.

func (*CompressedBlobStore) PutPrecompressed added in v0.43.0

func (c *CompressedBlobStore) PutPrecompressed(sha string, body []byte) error

PutPrecompressed writes a body that is ALREADY zstd-encoded with the magic prefix in place, for the service-layer streaming upload path that encodes incrementally as stdin arrives.

type EncodedStream added in v0.99.0

type EncodedStream struct {
	io.Reader
	// contains filtered or unexported fields
}

EncodedStream is a lazily-encoded upload body: magic + zstd(raw), produced as the reader is consumed rather than assembled first.

SHA and CompressedSize are only valid once the reader has been read to EOF. Nothing here is known in advance, which is the point: knowing either would require holding the whole body.

func EncodeCompressedStream added in v0.99.0

func EncodeCompressedStream(r io.Reader) *EncodedStream

EncodeCompressedStream wraps r so it yields the at-rest format without ever materialising it.

The pipe is what makes this constant-memory: the compressor writes only as fast as the object store reads, so an in-flight upload costs the zstd window and a copy buffer regardless of how large the file is.

The raw bytes are hashed on the way past, so the caller gets the sha WITHOUT a second pass - which is what previously forced the whole file into memory, since the sha had to be known before staging could start.

A read error propagates through CloseWithError, so a truncated upload fails the stage rather than silently storing a short object.

func (*EncodedStream) CompressedSize added in v0.99.0

func (e *EncodedStream) CompressedSize() int

CompressedSize is the at-rest footprint EXCLUDING the magic prefix, matching how pastes charge quota. Valid after the reader reaches EOF.

func (*EncodedStream) SHA added in v0.99.0

func (e *EncodedStream) SHA() string

SHA is the hex sha256 of the RAW bytes, which is what a record stores and what the site manifest keys on. Valid after the reader reaches EOF.

type InnerBlobStore added in v0.44.0

type InnerBlobStore = innerBlobStore

InnerBlobStore is the exported alias of innerBlobStore, so wiring code in cmd/ can name the type the compression layer wraps. The write-back cache satisfies it and slots between this layer and the durable backend.

type ShaleConfig added in v0.95.0

type ShaleConfig struct {
	NodeID    string // stable node identity; required by cluster.Open
	Endpoint  string // e.g. "http://minio:9000"; empty for AWS
	Region    string // e.g. "us-east-1"
	Bucket    string // bucket name (required)
	AccessKey string
	SecretKey string
	UseSSL    bool   // false -> slate sets AWS_ALLOW_HTTP=true (MinIO dev)
	DbName    string // logical db name within the bucket; key prefix for SlateDB files

	// LocalDir is the on-disk location for a build whose engine is LOCAL (see
	// shale_backing.go). Empty means keep the store in memory, which is what a
	// test wants. The object-store engine ignores it: its location is the
	// bucket plus DbName above.
	LocalDir string

	// UnitCount selects the backend SHAPE. Zero opens the single-backend path:
	// one slatedb database per node. A value >= 1, which MUST be a power of two,
	// selects MULTI-BACKEND (sharded) mode: the keyspace is partitioned into
	// UnitCount units, each its own slatedb database, distributed across the
	// cluster's nodes by the ring and routed per key by ShardKeyFn ->
	// UnitForHash. Each unit is a full slatedb instance (memtable, WAL,
	// compaction) per owning replica, so keep this small on small deployments.
	// The two layouts are NOT on-disk-compatible: switching an existing
	// deployment is a one-time operator data copy, not in-place (docs/SPEC.md
	// "Sharded metadata (multi-backend mode)"). Operator env:
	// HOSTTHIS_SHALE_UNIT_COUNT.
	UnitCount int

	// GRPCAddr is this node's gRPC forwarding address, broadcast to peers as
	// their forwarding target. Required in multi-node mode (cluster.Open errors
	// otherwise). Ignored in single-node mode.
	GRPCAddr string

	// Coordinator selects the coordination adapter. Empty is single-node.
	// CoordinatorCAS coordinates through one membership document in
	// ConditionalStore (required then); GRPCAddr is still required, because
	// peer forwarding is transport, not coordination. Operator env:
	// HOSTTHIS_SHALE_COORDINATOR (docs/SPEC.md "Coordination is a pluggable
	// choice").
	Coordinator string

	// ReplicationFactor is forwarded to cluster.Config. Zero is normalized to 1
	// by cluster.Open (single owner per key, no replicas). R=1 is the
	// horizontal-write-scaling shape; R>1 trades write throughput for
	// availability (docs/SPEC.md "R=1 vs R=2").
	ReplicationFactor int

	// RelaxedDurability selects the slate backend's write-durability mode.
	// False, the zero value, is the SAFE DEFAULT: a write is acked only after
	// the object-store flush. True enables fast-ack at the memtable with a
	// background flush, removing the per-commit flush round-trip from the hot
	// path. ONLY safe at ReplicationFactor >= 2 across anti-affinity-separated
	// nodes (a replica holds the write through the flush window); at R=1 a
	// single crash loses the un-flushed writes. See docs/SPEC.md "Relaxed
	// durability: fast-ack at the memtable".
	//
	// The operator-facing env var HOSTTHIS_METADATA_AWAIT_DURABLE is the
	// INVERSE (default true), matching slatedb's own AwaitDurable terminology;
	// the field is inverted here so the struct's zero value is the safe one.
	RelaxedDurability bool

	// CacheBytes sizes the slatedb SST block + metadata cache (an in-memory
	// Moka cache) the slate backend is given. Zero disables it, and slatedb's
	// no-block-cache default re-fetches SST blocks from the object store on
	// every read, which is pathological on a distributed-MinIO backend. A few
	// hundred MiB holds the hot SST working set in RAM. Operator env:
	// HOSTTHIS_METADATA_CACHE_BYTES.
	CacheBytes uint64

	// ReapFenceWALs enables slatedb's fence-WAL garbage collector. slatedb
	// writes a small "fence" WAL object every time a unit DB is opened (to
	// claim the single-writer epoch), and ships that GC category in DRY-RUN
	// (garbage_collector_options.wal_fence_options.dry_run = true), so fence
	// WALs are never deleted and accumulate one-per-open forever, bloating a
	// unit's object-store prefix until a cold-start open (which re-reads every
	// WAL) crawls. True flips that flag off via the slate backend's Settings so
	// the GC reaps fence WALs older than its min_age (slatedb's conservative
	// 300s default) and a unit's WAL count stays bounded. False leaves
	// slatedb's defaults untouched, which suffices for callers that open
	// briefly and never accumulate (tests, the migration tool). Operator env:
	// HOSTTHIS_SLATEDB_FENCE_GC (default on; "false" is the kill-switch).
	ReapFenceWALs bool

	// WriteTimeout / ReadTimeout, when > 0, override the cluster's per-dispatch
	// write/read deadline (cluster.Config defaults each to 5s). The bulk
	// migration tool raises these well above 5s: a single CAS commit on an
	// un-GC'd (bloated) unit can stall past 5s under a migrate burst, and a
	// DeadlineExceeded there aborts the whole run.
	WriteTimeout time.Duration
	ReadTimeout  time.Duration

	// TombstoneGrace is forwarded to cluster.Config.TombstoneGracePeriod: at
	// R>1, tombstones older than this are purged natively when a replica
	// position mounts, so the backend's compaction can reclaim them. Zero
	// disables the purge. Eligibility (R>1, write-ack bar covering all
	// replicas) is decided inside shale. Operator env:
	// HOSTTHIS_METADATA_TOMBSTONE_GRACE (docs/SPEC.md "Tombstone purge:
	// reclaiming replicated deletes").
	TombstoneGrace time.Duration

	// Logger receives the skip lines from the tolerant background scans (the
	// / repair-on-read) when they hit an undecodable record. nil falls back to
	// log.Default(). It never affects the blob-GC ref-set scans, which fail
	// closed rather than skip+log.
	Logger *log.Logger

	// BlobStore is the OPTIONAL streaming blob byte plane. When set, the repo
	// opens its cluster via cluster.NewBlobKV (the blob-capable surface), so a
	// staged blob's pointer co-commits with the metadata on the owning shard
	// (docs/SPEC.md "Shale-collocated blobs"). It must be a DISTINCT bucket
	// from the metadata's object store. nil keeps the metadata-only path
	// (cluster.Open, no *BlobKV), which ShaleBlobUnit is not wired for.
	BlobStore blob.Store

	// ConditionalStore is the OPTIONAL shared CAS arbiter (create-if-absent /
	// compare-and-set over the metadata object store) that enables the
	// HOMOGENEOUS bootstrap: cluster.Open then decides form-vs-join at runtime
	// against the __cluster/init marker instead of using the founder/joiner
	// seed asymmetry, and AllowSoloStart lets the first pod up come up solo and
	// contend to form. Every pod must wire the SAME store (same bucket, same
	// key prefix) so the marker is one shared object. nil keeps the seed-based
	// bootstrap. Only meaningful in multi-backend (sharded) mode. See
	// docs/SPEC.md "Homogeneous bootstrap (optional)".
	ConditionalStore storageunit.ConditionalStore

	// RegisterGRPC is an OPTIONAL, OPAQUE hook letting the composition root
	// register other cluster-internal services on the SAME gRPC server
	// NewShaleRepo constructs and serves in multi-node mode: one advertised
	// address per pod, one listener lifecycle, reachable at exactly the address
	// shale forwarding already dials (docs/SPEC.md "Multi-pod relay: the peer
	// transport"). Called once, after shale's own node service is registered
	// and BEFORE Serve starts. Ignored in single-node mode (no server exists).
	// The hook's type is all this package knows about what rides along.
	RegisterGRPC func(*grpc.Server)
}

ShaleConfig captures the parameters needed to open a shale cluster over the slate backend. The S3 connection fields mirror SlateConfig (same underlying SlateDB-on-object-storage engine); NodeID, the peer-discovery fields, and the consistency knobs are the cluster-layer additions.

Coordinator selects the topology: empty is single-node (every op local, no ring routing), CoordinatorCAS is multi-node over the membership document, with gRPC forwarding and ring routing. ShardKeyFn and the per-family co-location are identical at every node count.

type ShaleIntentLog added in v0.95.0

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

ShaleIntentLog stores intents in the metadata cluster at intents/<scope>/<id>. The scope leads the key so it is the shard key (see shale_shardkey.go), which is what makes Outstanding one single-shard prefix scan on the shard the caller is already reading from.

Nothing above storage names this type. It is reached only through durable.Log, so replacing it with a workflow engine is one wiring change (docs/SPEC.md "The durability mechanism is a port, not a layer").

func NewShaleIntentLog added in v0.95.0

func NewShaleIntentLog(c *cluster.Cluster, lg *log.Logger) *ShaleIntentLog

NewShaleIntentLog is called from the same composition root that opens the cluster, so the log shares its connection rather than owning one.

func (*ShaleIntentLog) Advance added in v0.95.0

func (r *ShaleIntentLog) Advance(_ context.Context, id durable.ID, scope durable.Scope, step durable.StepName) error

Advance re-reads inside the CAS rather than trusting a caller-supplied prior value: two steps of the same operation can be recorded concurrently only if the caller is buggy, but a retry recording the same step must stay a no-op.

func (*ShaleIntentLog) Begin added in v0.95.0

func (*ShaleIntentLog) Complete added in v0.95.0

func (r *ShaleIntentLog) Complete(_ context.Context, id durable.ID, scope durable.Scope) error

Complete drops the intent. An absent intent is success: two resolvers racing to finish the same work must both be able to return cleanly.

func (*ShaleIntentLog) Outstanding added in v0.95.0

func (r *ShaleIntentLog) Outstanding(_ context.Context, scope durable.Scope) ([]durable.Intent, error)

Outstanding lists the scope's un-completed intents. An undecodable row is SKIPPED rather than failing the call: this runs inside ordinary reads, and one bad intent must not break a user's listing. The tolerant scan skips a TRUNCATED envelope (the R>1 damage shape) the same way the JSON check below skips a bad payload, so the fail-open claim holds for envelope-level damage too. The skip is logged - an intent nothing can parse is work nothing will ever resolve, so it needs an operator.

type ShaleRepo added in v0.95.0

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

ShaleRepo is the shale-cluster-backed metadata store, satisfying the same service-layer interfaces. Every operation goes through the cluster handle, which routes per-shard via shaleShardKey and commits single-shard writes through per-shard CAS.

In multi-node mode (a cas Coordinator) the repo ALSO owns the process-level gRPC peer-forwarding server: cluster.Open advertises the node's GRPCAddr via the coordinator but does not stand up the listener peers forward routed reads/writes/migrations to (docs/SPEC.md "Peer forwarding"). NewShaleRepo binds that listener and serves the cluster's rpc handlers on it.

func NewShaleRepo added in v0.95.0

func NewShaleRepo(cfg ShaleConfig) (*ShaleRepo, error)

NewShaleRepo opens a shale cluster over a fresh slate backend. The caller must Close() to flush and shut down the cluster, which shuts down the backend too.

shaleShardKey is the ShardKeyFn, so every family co-locates on the shard keyed by its subject, which is what makes an owner's enumeration index and the per-slug authoritative rows each single-shard.

In multi-node mode the gRPC peer-forwarding listener is bound BEFORE the cluster opens, and the listener's ACTUAL address is advertised. That matters when GRPCAddr is ":0": the real port is known only after Listen, and a peer forwarding to the advertised address must reach the one actually served.

func (*ShaleRepo) AdmitNewKey added in v0.95.0

func (r *ShaleRepo) AdmitNewKey(identity, subnet string, now time.Time, limitPerSubnet int, window time.Duration) (knownAlready bool, err error)

AdmitNewKey checks the subnet's in-window budget and admits a fresh (identity, subnet) pair on the {subnet} shard.

The cap is APPROXIMATE under concurrency, not exact. The in-window count is a prefix scan, which shale does not permit inside a CAS transaction, and the transaction's read-set covers only the candidate's OWN row. Two first-sight identities in one subnet therefore write DIFFERENT keys, raise no conflict, and can both commit having each observed a count one below the limit. The overshoot is bounded by how many first-sight keys race in one subnet at once; a serial attacker sees the exact cap, and every admitted row counts against every later admit, so the gate does not decay. Making it exact needs a per-subnet counter in the transaction's read-set, which is a key-layout change (a new family plus its shaleShardKey routing), not a local edit.

The candidate key IS read inside the tx, which is what makes a racing admit of the SAME pair resolve as known-already instead of writing the row twice.

func (*ShaleRepo) AppendManifestVersion added in v0.95.0

func (r *ShaleRepo) AppendManifestVersion(ctx context.Context, slug domain.Slug, m domain.Manifest, root domain.ManifestEntry, size int, userCap int64, now time.Time) (AppendResult, error)

AppendManifestVersion appends a version whose content is a whole manifest - the multi-entry shape a directory redeploy writes. Otherwise identical to AppendVersionWithQuotaCheck: same quota check, same head roll, same single-shard boundary.

root describes the entry a listing shows; size is the version's CHARGED bytes, which for a directory is its deduped blob total rather than the root file's size.

func (*ShaleRepo) AppendVersionWithQuotaCheck added in v0.95.0

func (r *ShaleRepo) AppendVersionWithQuotaCheck(ctx context.Context, slug domain.Slug, kind domain.ContentKind, contentSHA string, size int, userCap int64, now time.Time) (AppendResult, error)

AppendVersionWithQuotaCheck appends a new version. The per-owner cap is enforced by a scan-and-compare BEFORE the authoritative write: the owner's combined paste+site used bytes (which already include this paste's current versions) plus the new version's bytes must not exceed the cap. The check and the write are not atomic, the same bounded over-admit InsertWithQuotaCheck documents.

The version row lands on the {slug} shard; the index projection's cached size is then refreshed on the {id} shard, which is what starts the new version's bytes counting.

func (*ShaleRepo) ClaimBlobOwnership added in v0.97.0

func (r *ShaleRepo) ClaimBlobOwnership(_ context.Context, slug domain.Slug) (int64, error)

ClaimBlobOwnership takes ownership of a slug's staged bytes and returns the epoch the caller must present at bind time.

Called BEFORE the first byte is staged. A fresh slug starts at epoch 1; a slug whose previous attempt was taken over returns whatever recovery left, so the new attempt is fenced against the old one rather than inheriting its identity.

func (*ShaleRepo) ClearStagedRefs added in v0.97.0

func (r *ShaleRepo) ClearStagedRefs(_ context.Context, slug domain.Slug) error

ClearStagedRefs drops an upload's staged records.

Called when the write COMMITS: those bytes are bound now, and a record that outlives its commit is a standing instruction to delete live data. Also called after recovery unstages them, where it is ordinary cleanup.

Idempotent, so a partial clear converges on the next pass.

func (*ShaleRepo) Close added in v0.95.0

func (r *ShaleRepo) Close() error

Close shuts down the peer-forwarding gRPC server, then the cluster (and the underlying slate backend). GracefulStop drains in-flight RPCs and closes the listener, so the forwarding port is released with no leaked goroutine.

func (*ShaleRepo) CountByOwner added in v0.95.0

func (r *ShaleRepo) CountByOwner(owner string) (int, error)

CountByOwner returns how many pastes the owner's enumeration index holds. It counts entries and reads no authoritative rows, so it agrees with what ListByOwner renders (docs/SPEC.md "Listing is O(1) reads") - including a phantom entry, which both count and list report. MarkFailed and Delete drop the entry, so neither a failed nor a deleted paste is counted.

func (*ShaleRepo) CountRoomCreates added in v0.95.0

func (r *ShaleRepo) CountRoomCreates(appSlug domain.Slug, subnet string, now time.Time, window time.Duration) (perSubnet, perApp int, err error)

CountRoomCreates returns the in-window (perSubnet, perApp) creation counts via a single-shard ScanPrefix on roomcreate/<app>/: the per-app count is every in-window row, the per-subnet count the subset whose <subnet> segment matches. The fixed-width <ts> on each marker is what the window compares.

func (*ShaleRepo) CreateRoom added in v0.95.0

func (r *ShaleRepo) CreateRoom(room domain.Room, subnet string, appCap int64, now time.Time) error

CreateRoom mints an empty room, records the creation-accounting marker, and enforces the per-app aggregate cap in ONE {app-slug}-shard CAS: the room record, the ledger marker and the per-app counter all co-shard. The creation rate-limit DECISION runs in the service via CountRoomCreates OUTSIDE this call, so that gate stays a SOFT bound. Returns ErrSlugTaken on an (app, id) collision, ErrAppRoomsFull past the byte cap.

func (*ShaleRepo) DebugClusterState added in v0.95.0

func (r *ShaleRepo) DebugClusterState() string

DebugClusterState returns the cluster's per-position handoff dump for live diagnosis, or "" when there is no cluster. Exposed so the metadata adapter can serve it on an optional debug port without leaking the cluster handle.

func (*ShaleRepo) Delete added in v0.95.0

func (r *ShaleRepo) Delete(slug domain.Slug, wantIdentity domain.Identity, wantCreatedAt time.Time) error

Delete removes a paste entirely: a whole-paste delete is a full removal, not a tombstone. The authoritative {slug} rows go away and the {id} enumeration-index entry is dropped, which is what stops the owner's scan-derived quota sum counting the paste. Idempotent on a missing paste.

The version enumeration runs outside the transaction (ScanPrefix is unsupported inside a CAS tx), so the cascade joins the read set two ways: the head row is read INSIDE the tx, and the candidate NEXT version key is read ExpectAbsent. Without those the tx would carry only writes and commit unconditionally, leaving a version row a concurrent append wrote alive under a deleted paste - an orphan the owner's next list is the only thing that prunes, whose ContentSHA keeps its blob out of the GC's reach forever.

A racing append aborts the delete rather than re-scanning. Transact already spends a full CAS budget on the conflict, so a second retry layer here would only re-run an exhausted one; and the version set is read OUTSIDE the tx, so the only fix for a stale scan is to start over from the caller. wantIdentity + wantCreatedAt name the exact paste instance the caller authorized (from its own ownership read). They are re-checked INSIDE the {slug} transaction against the head that transaction reads: the service-layer ownership check happens OUTSIDE any transaction, so on its own it cannot stop a delete+re-mint of the same slug from committing in the window and having this delete destroy the NEW owner's paste.

func (*ShaleRepo) DeleteRoom added in v0.95.0

func (r *ShaleRepo) DeleteRoom(appSlug domain.Slug, id domain.RoomID) error

DeleteRoom removes a room record and EVERY value in its namespace, then decrements the per-app counter by the freed bytes, all on the one {app-slug} shard. Idempotent: a missing room is a no-op.

The value keys are enumerated OUTSIDE the CAS, since ScanPrefix is not allowed inside, so the enumeration is fenced on the room record's seq exactly as ScanRoom fences its scan: read the seq, scan, then re-read the record inside the CAS and require the same seq. Every mutation bumps that seq in its own CAS, so a put committing in the window is detected and the whole pass retries. Without the fence a value written in that window survives as a row no scan can reach (its room is gone) and its bytes stay charged to the per-app counter forever, which nothing repairs.

Given equal fence values, every delete and the counter decrement land in ONE CAS, so the room and all its values vanish atomically (the shale analogue of a relational FK cascade).

func (*ShaleRepo) DeleteRoomValue added in v0.95.0

func (r *ShaleRepo) DeleteRoomValue(appSlug domain.Slug, id domain.RoomID, key string, now time.Time) (uint64, error)

DeleteRoomValue removes key and bumps the room's clock (a delete is a write), in one {app-slug}-shard CAS: re-check the room exists, delete the value, credit the freed bytes back to the per-app counter and the record's running totals, touch the room. Returns the assigned per-room sequence, and ErrNotFound only when the ROOM does not exist.

Idempotent: deleting an absent key succeeds and still assigns a seq, because a seq bump rides every commit and no relay subscriber may see a bump with no frame.

func (*ShaleRepo) DeleteVersion added in v0.95.0

func (r *ShaleRepo) DeleteVersion(slug domain.Slug, ver int) error

DeleteVersion tombstones a single version: it stays visible in the list flagged deleted, but its content blob is no longer referenced, so the GC reclaims it. Its bytes leave the owner's scan-derived sum via the index-projection refresh after the tombstone commits; a lost refresh is a bounded stale-cache window the owner's next list heals. Re-deleting an already-tombstoned version is a no-op.

func (*ShaleRepo) DropStaleOwnerEntry added in v1.7.1

func (r *ShaleRepo) DropStaleOwnerEntry(slug domain.Slug, owner string) (bool, error)

DropStaleOwnerEntry removes slug from the owner's OWN index - the owner-doc entry and the identity_pastes enumeration row - when the authoritative pastes/<slug> row is ABSENT: the residue a death between Delete's {slug} transaction and its {id}-shard index drop strands (insert's entry-first order can strand the same shape). Reports whether anything was dropped (docs/SPEC.md "Delete heals its own lost tail").

Ordering is load-bearing: the stamp is captured BEFORE the row-absence gate, so the CAS can only ever drop the entry generation that was observed before absence was proven. A re-mint landing after the stamp read writes a fresh CreatedAt and the CAS misses it. Capturing the stamp after the gate would hand a racing re-mint's fresh stamp to the CAS - the gate and the subject read at two instants, the exact shape the v1.4.1 audit removed.

The stamp must also be OLD (staleEntryGrace): confirmInsert writes the index entry before the paste row commits, so a mid-insert entry is row-absent, self-stamped, and would pass both the gate and its own stamp check - no reordering can defend state whose row does not exist yet. Age can: a mid-insert entry is milliseconds old, while real lost-tail residue is minutes old before any delete retries it. Too-young entries are left for a later retry.

A slug whose row EXISTS - any owner, including a settled re-mint - drops nothing and reports false, so the caller keeps answering plain not-found and existence never leaks. An UNREADABLE row also drops nothing (fail open: unreadable is not absent).

BOTH representations go in the one CAS. Dropping only the doc entry would leave the renderable enumeration row, and ownerDocCandidate copies a renderable row into a rebuilt doc without reading its paste - the phantom would return with the next doc rebuild.

Cost: at most three point Gets plus one single-shard CAS. No scans on this path for a doc-holding owner (the candidate walk inside dropOwnerEntry early-returns on a decodable doc); a docless owner's reads already pay the scan shape.

func (*ShaleRepo) FenceBlobOwnership added in v0.97.0

func (r *ShaleRepo) FenceBlobOwnership(_ context.Context, slug domain.Slug) (int64, error)

FenceBlobOwnership bumps the epoch so the writer that claimed it can no longer bind, and returns the new value.

Recovery calls this BEFORE unstaging anything. The order is the whole mechanism: bump-then-delete makes a resumed writer's bind abort with certainty, where delete-then-bump leaves a window in which it binds bytes that are already gone.

func (*ShaleRepo) GRPCAddr added in v0.95.0

func (r *ShaleRepo) GRPCAddr() string

GRPCAddr returns this node's ACTUAL bound gRPC forwarding address, the one advertised to peers, or "" in single-node mode. The configured GRPCAddr may have been ":0", so the served port is only knowable post-bind.

func (*ShaleRepo) Get added in v0.95.0

func (r *ShaleRepo) Get(slug domain.Slug) (domain.Paste, error)

func (*ShaleRepo) GetBlobStream added in v0.95.0

func (r *ShaleRepo) GetBlobStream(ctx context.Context, routeKey []byte, blobid string) (io.ReadCloser, int64, error)

GetBlobStream streams the STORED (still compressed) bytes for blobid under routeKey's shard; ShaleBlobUnit.Read wraps it in the magic-peek + zstd decode. ctx MUST outlive the returned reader, which drives the lazy object-store stream. An unbound or deleted pointer yields blob.ErrNotFound.

func (*ShaleRepo) GetRoom added in v0.95.0

func (r *ShaleRepo) GetRoom(appSlug domain.Slug, id domain.RoomID) (domain.Room, error)

GetRoom returns the room record for (appSlug, id) or ErrNotFound.

func (*ShaleRepo) GetRoomValue added in v0.95.0

func (r *ShaleRepo) GetRoomValue(appSlug domain.Slug, id domain.RoomID, key string) ([]byte, error)

GetRoomValue returns one value scoped by (appSlug, id, key), VERBATIM. A missing key and a missing room both return ErrNotFound, so this layer leaks no per-key existence.

func (*ShaleRepo) GetVersion added in v0.95.0

func (r *ShaleRepo) GetVersion(slug domain.Slug, ver int) (domain.Version, error)

func (*ShaleRepo) HasBlobPlane added in v0.95.0

func (r *ShaleRepo) HasBlobPlane() bool

HasBlobPlane reports whether this repo runs the transactional shale-blob path. The cmd wiring uses it to pick ShaleBlobUnit over StandaloneBlobUnit and to schedule SweepOrphans.

func (*ShaleRepo) InsertWithQuotaCheck added in v0.95.0

func (r *ShaleRepo) InsertWithQuotaCheck(ctx context.Context, p domain.Paste, userCap int64, now time.Time) error

InsertWithQuotaCheck creates a paste. The per-owner cap is enforced by a scan-and-compare BEFORE the authoritative write: the owner's combined paste+site used bytes come from the enumeration indexes, and the upload is rejected with ErrOverUserQuota if used+body would exceed the cap. The check and the write are NOT atomic, so two concurrent uploads from the SAME identity can both pass and both land - a bounded over-admit, acceptable because one key is one person and the object-store bucket quota backstops the durable total (docs/SPEC.md "Scan-derived quota").

The authoritative write is the {slug} CAS (slug-collision read-check + blob bind); the {id} enumeration-index entry and first-seen are written SYNCHRONOUSLY after it, since the index IS the quota source of truth and a subsequent scan must see this paste. A crash between the two leaves a paste the index does not list: a bounded under-count the owner's next list heals.

func (*ShaleRepo) IsVersionServed added in v1.4.0

func (r *ShaleRepo) IsVersionServed(slug domain.Slug, ver int) (bool, error)

IsVersionServed reports whether ver is the version the paste's URL currently serves. It backs the per-version delete guard, so it decides from the authoritative HEAD and version ROWS and NEVER the disposable cache: a stale cache must not be able to let the guard free the served version's blob (docs/SPEC.md "Destructive operations decide from the rows and the head").

Pinned: the pinned number, from the head alone. Unpinned: the head serves the newest live version, named EXACTLY by its blob id on the blob path (a point read of the target row, no scan) and, on the sha-keyed dev path that has no blob id, by the newest non-deleted ver_num from a rows scan (a content sha is not unique per version, so it cannot identify one).

func (*ShaleRepo) ListByOwner added in v0.95.0

func (r *ShaleRepo) ListByOwner(owner string) ([]domain.Paste, error)

ListByOwner returns the owner's pastes from ONE single-shard prefix scan of identity_pastes/<id>/, rendering each row from the entry's own cached fields. No per-item reads: listing cost is FLAT in how many pastes an owner holds (docs/SPEC.md "Listing is O(1) reads").

Nothing here validates an entry against its authoritative row. A crash between the two writes of an insert (or a delete) can leave an entry whose paste does not exist, and that entry is simply listed - a deliberate acceptance, not an oversight. Detecting it would mean reading every paste on every listing, which is the cost this design exists to remove.

An entry written before the display fields existed carries no Kind and cannot be rendered from the cache, so it is resolved once against its row and rewritten fat. That is a migration path, self-limiting to one read per entry ever - not a validation pass.

func (*ShaleRepo) ListVersions added in v0.95.0

func (r *ShaleRepo) ListVersions(slug domain.Slug) ([]domain.Version, error)

func (*ShaleRepo) MarkFailed added in v0.95.0

func (r *ShaleRepo) MarkFailed(slug domain.Slug) error

MarkFailed flips a paste's status pending -> failed and drops its enumeration-index entry, serving both the background finalizer's failure transition and the list-time age-out. The paste ROW stays, flipped to failed, so a read can serve an error page; its bytes stop counting the instant the status flips, because the scan skips a failed head row. Only a still-pending paste transitions, so this never un-counts a ready paste. Idempotent. See docs/SPEC.md "Paste lifecycle status (async blob write)".

func (*ShaleRepo) MarkReady added in v0.95.0

func (r *ShaleRepo) MarkReady(slug domain.Slug) error

MarkReady flips a paste's status pending -> ready on the {slug} shard, the background finalizer's success transition once the blob landed. Only a still-pending paste advances, so a late finalizer cannot resurrect a paste it already failed; already-ready, failed and absent are all no-ops. See docs/SPEC.md "Paste lifecycle status (async blob write)".

func (*ShaleRepo) MountReadiness added in v0.95.0

func (r *ShaleRepo) MountReadiness() cluster.MountReadiness

MountReadiness returns the cluster's point-in-time mount-state counts (desired / mounted / pending / failed-open positions plus one representative acquire error). Cheap enough for a probe polled every few seconds; all zero in single-backend mode.

func (*ShaleRepo) OwnerFirstSeen added in v0.95.0

func (r *ShaleRepo) OwnerFirstSeen(owner string) (time.Time, error)

func (*ShaleRepo) OwnerSummary added in v1.3.0

func (r *ShaleRepo) OwnerSummary(owner string, now time.Time) (domain.OwnerSummary, error)

OwnerSummary answers whoami's count + first-seen + byte-sum with ONE read when the owner has a doc. A pre-migration owner composes the same figures from the legacy scans, read-only. SiteBytes stays zero on the legacy path: a directory is a paste, so its bytes are already in the paste sum.

func (*ShaleRepo) PeerGRPCAddrs added in v0.95.0

func (r *ShaleRepo) PeerGRPCAddrs() []string

PeerGRPCAddrs returns the CURRENT gRPC addresses of every OTHER live cluster member, read from the coordinator's ring membership. These are the addresses peers advertised at join (exactly what shale forwarding dials), kept current by the same coordination that tracks joins, leaves and deploy churn, so the view is fresher than DNS. The composition root adapts it onto the relay's Peers port (docs/SPEC.md "Multi-pod relay: peer discovery"). Single-node returns empty. Safe for concurrent use.

func (*ShaleRepo) PreClaimSlug added in v0.96.0

func (r *ShaleRepo) PreClaimSlug(_ context.Context, slug domain.Slug, owner string, _ time.Time) error

PreClaimSlug stakes a metadata-only claim on slug BEFORE a transactional directory deploy consumes its untar stream, so every file stages under the {slug} shard and the pointers co-bind with the manifest at commit.

A single {slug}-shard CAS writing slug_owner/<slug> IFF the slug is free and not already pre-claimed. Both reads join the read-set, so concurrent claims serialize and one loses. Returns ErrSlugTaken on any collision; the caller re-mints and re-claims.

A claim is durable and no sweep reclaims one, so a deploy that does not commit under the slug MUST hand it back via ReleaseSlugClaim or the slug is spent. Only a crash in that window leaves a marker with no paste, and a later insert minting the slug overwrites it unconditionally.

owner and now are accepted for symmetry with the seam; a claim is a stake, not a byte reservation, so it charges no quota.

func (*ShaleRepo) PutRoomValue added in v0.95.0

func (r *ShaleRepo) PutRoomValue(appSlug domain.Slug, id domain.RoomID, key string, val []byte, appCap int64, now time.Time) (uint64, error)

PutRoomValue writes val under key, enforcing the per-room and per-app caps, in ONE {app-slug}-shard CAS: re-read the value key for the byte delta, validate both caps from values the read-set carries (the per-ROOM byte total + key count on the room record, and the per-APP roombytes/<app> counter), write the value, touch the room. Value, counter and record all co-shard, so no reserve/confirm split is needed.

The per-room cap is strict because the room record is in the read-set (read for the room-exists check, rewritten on the clock touch): two writers to DISTINCT keys of one room do not conflict on their disjoint value keys, but DO conflict on the shared record, so the loser retries against updated totals. That in-record figure exists because ScanPrefix is not allowed inside a CAS, so the cap needs a discrete value the read-set can carry.

Returns the assigned per-room sequence: each commit observes the prior seq and writes exactly prior + 1, so density and uniqueness fall out of the same conflict that makes the per-room cap strict (SPEC "The per-room sequence: assignment at commit").

Returns ErrNotFound if the room is gone, ErrRoomDataFull (413) on the per-room cap, ErrAppRoomsFull (507) on the per-app aggregate. Rooms hold no blobs, so this path touches no object-store quota and has no service-wide byte cap (SPEC "Rooms -> Quota and abuse -> Durable total-bytes ceiling").

func (*ShaleRepo) Ready added in v0.95.0

func (r *ShaleRepo) Ready(minMountedFraction float64) bool

Ready reports whether this node has mounted at least ceil(minMountedFraction * desired) of its desired storage-unit positions. Edge contract is the cluster predicate's: desired == 0 is vacuously ready, a fraction <= 0 means no floor.

func (*ShaleRepo) RecordStagedRef added in v0.97.0

func (r *ShaleRepo) RecordStagedRef(_ context.Context, slug domain.Slug, ref cluster.BlobRef) error

func (*ShaleRepo) ReleaseSlugClaim added in v0.96.0

func (r *ShaleRepo) ReleaseSlugClaim(_ context.Context, slug domain.Slug, owner string) error

ReleaseSlugClaim hands a pre-claimed slug back when the deploy that staked it never committed, so an aborted deploy does not burn the slug: PreClaimSlug rejects any slug carrying a marker, and nothing else removes one.

A single {slug}-shard CAS deleting slug_owner/<slug> IFF it still holds owner's stake AND no paste exists. Both reads join the read-set, so a racing insert that makes the marker load-bearing conflicts instead of losing its owner pointer, and an ambiguous commit that actually landed keeps its marker. A missing or foreign claim is a no-op, so a repeated release is harmless.

func (*ShaleRepo) ResolveBlobID added in v0.95.0

func (r *ShaleRepo) ResolveBlobID(slug domain.Slug, contentSHA string) (string, error)

ResolveBlobID maps a (slug, contentSHA) back to the shale blob id GetBlob needs. The http/manage read seam holds only the content sha, while the blob id lives on the metadata, so this routed lookup bridges the two. It checks, in order:

  1. the paste head row: its served ContentSHA -> its BlobID (the common path, since an HTML/markdown paste read passes the head's ContentSHA),
  2. the paste's version rows: a non-head (pinned or Show'd) version whose ContentSHA matches -> that version's BlobID,
  3. the site row's FileBlobs[sha], for a static-site file read.

Returns ("", ErrNotFound) when no metadata references the sha (a deleted or unbound blob), which the seam maps to blob.ErrNotFound. A legacy row with an empty BlobID returns ""; the seam reads "" as sha-keyed and falls back.

func (*ShaleRepo) ResolveIntents added in v0.95.0

func (r *ShaleRepo) ResolveIntents(ctx context.Context, intents []durable.Intent, now time.Time) (int, error)

ResolveIntents resolves the intents this node can see that are older than the grace, and reports how many it settled.

Safe to run concurrently with other nodes and with live traffic: each step is idempotent, the compensating delete is value-guarded, and an intent younger than the grace is left alone. There are no locks.

One bad intent does not stop the sweep. This runs at boot on a serving node, so a single unresolvable record must not deny the whole sweep to every other.

func (*ShaleRepo) RouteKeyForSlug added in v0.95.0

func (r *ShaleRepo) RouteKeyForSlug(slug string) []byte

RouteKeyForSlug returns the canonical metadata route key a slug's blobs co-locate with: pastes/<slug>. pastes/<slug> and sites/<slug> both shard on <slug>, so they resolve to the SAME unit and the SAME bref key, and one route key covers staging, reading and unbind-key derivation for either record kind. Exported because ShaleBlobUnit lives in another package and shaleKeyPaste does not.

func (*ShaleRepo) ScanRoom added in v0.95.0

func (r *ShaleRepo) ScanRoom(appSlug domain.Slug, id domain.RoomID) (domain.RoomKV, error)

ScanRoom returns the whole namespace for (appSlug, id), stamped with the EXACT per-room sequence the snapshot reflects. Single-shard ScanPrefix over roomkv/<app>/<uuid>/, so it never fans out. An existing room with no values returns an empty (non-nil) RoomKV; a nonexistent room scans empty at seq 0, and the service layer's prior GetRoom is what turns that into a 404.

Shale cannot put a prefix scan inside a CAS (no phantom protection), so exactness runs a SEQ FENCE: read the room record's seq, scan, re-read the seq. Every mutation bumps that seq in its own CAS, so equal fence values mean the scan is exactly the state at S; a change means a commit interleaved and the scan retries. On retry exhaustion the scan FAILS rather than returning a state whose S is a lie - the join fails and the client reconnects.

Replication bar (R <= 2)

The fence assumes every read it issues observes every mutation the equal fence values bracket. That holds at R=1, and at R=2 because the write bar is 2/2, so any member a read lands on is complete.

At R >= 3 a write acks on a quorum, so a read-one union scan served mid-handoff by a member outside some write's ack set could miss a mutation both fence reads agree is committed. S would be stamped high with the mutation absent, a hole the splice contract CANNOT detect because the snapshot claims to cover it.

Raising the room tier past R=2 requires revisiting this fence, e.g. a quorum union scan, or bracketing the scan and fence reads on the same member set. Pinned by TestShaleRoomSeqFence_ReplicationBar.

func (*ShaleRepo) SetName added in v0.95.0

func (r *ShaleRepo) SetName(slug domain.Slug, name string, wantIdentity domain.Identity, wantCreatedAt time.Time) error

wantIdentity + wantCreatedAt name the paste the caller authorized. The head rename re-checks them INSIDE the {slug} transaction: without it a delete + re-mint of the slug by another owner in the window makes the first tx relabel the NEW owner's paste, and the confirmed identity is then reused for the index/doc write rather than a fresh out-of-tx read that could resolve to the wrong owner.

func (*ShaleRepo) SetPinnedVersion added in v0.95.0

func (r *ShaleRepo) SetPinnedVersion(slug domain.Slug, ver domain.Version) error

func (*ShaleRepo) StageBlobStream added in v0.95.0

func (r *ShaleRepo) StageBlobStream(ctx context.Context, routeKey []byte, body io.Reader, size int64, contentHash string) (cluster.BlobRef, error)

StageBlobStream streams an already-encoded body to the final object, returning the BlobRef the binding transaction consumes. routeKey is the metadata key whose shard the blob co-locates with (pastes/<slug> or sites/<slug>, which route to the same unit). contentHash rides on the ref into the persisted blob.Pointer, feeding the site read path's sha -> blob-id side-table.

func (*ShaleRepo) StagedRefs added in v0.97.0

func (r *ShaleRepo) StagedRefs(slug domain.Slug) ([]cluster.BlobRef, error)

StagedRefs returns every ref recorded for one upload.

A record that will not decode is returned as an error rather than skipped: the caller deletes bytes from this list, and silently dropping an unreadable entry would leak rather than mislead - but silently dropping a PARTIALLY readable one could delete the wrong object, so neither is a choice this function is entitled to make.

func (*ShaleRepo) StagedUploadsLocalForTest added in v0.97.1

func (r *ShaleRepo) StagedUploadsLocalForTest() ([]domain.Slug, error)

StagedUploadsLocalForTest exposes the candidate scan so the blob-plane suite can assert on WHICH uploads it reports, which the reclaimed count cannot show.

func (*ShaleRepo) SubnetSnapshot added in v0.95.0

func (r *ShaleRepo) SubnetSnapshot(subnet string, now time.Time, window time.Duration) (int, time.Time, error)

SubnetSnapshot counts in-window rows for a subnet and finds the oldest first_seen among them. Single-shard scan on the {subnet} shard.

func (*ShaleRepo) SubnetsForIdentity added in v0.95.0

func (r *ShaleRepo) SubnetsForIdentity(identity string, now time.Time, window time.Duration) (int, error)

SubnetsForIdentity counts distinct in-window subnets for an identity.

Reads the IDENTITY-leading index, so the cost is the number of subnets THIS key has been seen in rather than the number of keygate rows in the whole cluster, which is what a filtered scan of the global keygate/ prefix costs.

DISPLAY ONLY (whoami via KeyGate.Inspect, whose error is discarded): an entry not yet projected under-reports the count rather than weakening the Sybil control, which reads the transactionally-written subnet-leading rows.

func (*ShaleRepo) SumActiveBytesByOwner added in v0.95.0

func (r *ShaleRepo) SumActiveBytesByOwner(owner string, now time.Time) (int, error)

SumActiveBytesByOwner derives the owner's active PASTE bytes from ONE single-shard prefix scan of identity_pastes/<id>/, summing the cached size each entry carries with ZERO per-entry fan-out to the {slug} shards. The write paths keep the cached size equal to the paste's live (non-deleted) version sum and the owner's next list heals drift, so the figure trails the authoritative sums by at most that owner's next read (docs/SPEC.md "Scan-derived quota").

func (*ShaleRepo) SweepIntents added in v0.95.0

func (r *ShaleRepo) SweepIntents(ctx context.Context, now time.Time) (int, error)

SweepIntents is the boot sweep: it resolves every intent stored on the units THIS node has mounted.

The scan is node-LOCAL. cluster.LocalScanPrefix walks this node's own mounted units, so no network fan-out happens even though the intent family logically spans every shard. Across the fleet every unit is covered, because every unit is mounted by someone.

Call it after the node is serving, not before. Deciding an intent requires reading the authoritative row, which lives on a DIFFERENT shard that may not be mounted anywhere yet during a cold start - gating readiness on that read would deadlock a cold cluster.

func (*ShaleRepo) SweepStagedBytes added in v0.97.0

func (r *ShaleRepo) SweepStagedBytes(ctx context.Context, now time.Time) (int, error)

SweepStagedBytes reclaims the staged objects of uploads that stopped making progress, and reports how many uploads it actually reclaimed - never how many it looked at.

Driven by the staged records rather than by durable intents, because the two answer different questions. An intent tracks a paste CREATION - it exists to decide whether half-written metadata should be finished or undone. Staged bytes outlive that: an append and a redeploy stage bytes without creating anything, and an upload that dies while staging never reaches the insert that would open an intent at all. That last case is the likeliest abandonment there is - a long multi-file deploy interrupted partway - so routing byte reclamation through intents would miss its main case.

The scan is node-LOCAL, for the same reason the intent sweep's is: every unit is mounted by someone, so the fleet covers the keyspace without any node fanning out.

Call it after the node is serving. Reclaiming reads and writes the slug's shard, which may not be mounted anywhere yet during a cold start.

func (*ShaleRepo) Unpin added in v0.95.0

func (r *ShaleRepo) Unpin(slug domain.Slug) error

Unpin clears the pin and rolls the head to the latest LIVE version, the same rule latestActiveVerNum and the read path apply. Tombstoned versions are skipped: pointing the head at one would serve bytes the owner deleted, or 404 once the GC reclaims them. ErrNotFound when no live version remains.

The version scan runs outside the transaction (ScanPrefix is unsupported inside a CAS tx), so the candidate NEXT version key is read ExpectAbsent inside the tx. An append that lands after the scan is then either visible to that read or fails the read-check, and both routes abort rather than commit a head chosen from a stale version set.

func (*ShaleRepo) WaitPendingConfirms added in v0.95.0

func (r *ShaleRepo) WaitPendingConfirms()

WaitPendingConfirms blocks until every background confirm goroutine has finished. The insert's confirm step is synchronous, so this is currently a no-op; it is the drain seam Close and the tests go through.

type ShaleRoomRepo added in v0.95.0

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

ShaleRoomRepo is the service.RoomRepo + service.SweepRooms adapter over a ShaleRepo, delegating to its `...Room` methods so the room repo shares one cluster handle (and shard routing) with the paste + site repos.

func NewShaleRoomRepo added in v0.95.0

func NewShaleRoomRepo(repo *ShaleRepo) *ShaleRoomRepo

NewShaleRoomRepo wraps a ShaleRepo so the no-auth room-persistence tier runs on the shale backend.

func (*ShaleRoomRepo) CountRoomCreates added in v0.95.0

func (s *ShaleRoomRepo) CountRoomCreates(appSlug domain.Slug, subnet string, now time.Time, window time.Duration) (perSubnet, perApp int, err error)

func (*ShaleRoomRepo) CreateRoom added in v0.95.0

func (s *ShaleRoomRepo) CreateRoom(room domain.Room, subnet string, appCap int64, now time.Time) error

service.RoomRepo

func (*ShaleRoomRepo) DeleteValue added in v0.95.0

func (s *ShaleRoomRepo) DeleteValue(appSlug domain.Slug, id domain.RoomID, key string, now time.Time) (uint64, error)

func (*ShaleRoomRepo) GetRoom added in v0.95.0

func (s *ShaleRoomRepo) GetRoom(appSlug domain.Slug, id domain.RoomID) (domain.Room, error)

func (*ShaleRoomRepo) GetValue added in v0.95.0

func (s *ShaleRoomRepo) GetValue(appSlug domain.Slug, id domain.RoomID, key string) ([]byte, error)

func (*ShaleRoomRepo) PutValue added in v0.95.0

func (s *ShaleRoomRepo) PutValue(appSlug domain.Slug, id domain.RoomID, key string, val []byte, appCap int64, now time.Time) (uint64, error)

func (*ShaleRoomRepo) ScanRoom added in v0.95.0

func (s *ShaleRoomRepo) ScanRoom(appSlug domain.Slug, id domain.RoomID) (domain.RoomKV, error)

type Sites added in v0.96.0

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

func NewSites added in v0.96.0

func NewSites(repo *ShaleRepo) *Sites

func (*Sites) Delete added in v0.96.0

func (a *Sites) Delete(slug domain.Slug, wantIdentity domain.Identity, wantCreatedAt time.Time) error

func (*Sites) Get added in v0.96.0

func (a *Sites) Get(slug domain.Slug) (domain.Site, error)

Get returns the directory owning slug.

A slug that is a DOCUMENT reads as not-found, not as a one-file site: the caller asked for a directory, and answering with a document would let a paste be served through the site path. The shape is read from the kind, not inferred from the manifest's size.

func (*Sites) InsertWithQuotaCheck added in v0.96.0

func (a *Sites) InsertWithQuotaCheck(ctx context.Context, s domain.Site, storedBytes int, userCap int64, now time.Time) error

InsertWithQuotaCheck stores a new directory as a paste.

storedBytes is the CHARGED size: a directory's distinct blob total, which is what the quota counts, rather than the root file's size.

func (*Sites) ListSitesByOwner added in v0.96.0

func (a *Sites) ListSitesByOwner(string, time.Time) ([]domain.Site, error)

ListSitesByOwner returns NOTHING, for the reason the sum returns zero: a directory is already in the paste listing the caller concatenates this onto, so returning it here would show it twice.

func (*Sites) PreClaimSlug added in v0.96.0

func (a *Sites) PreClaimSlug(ctx context.Context, slug domain.Slug, owner string, now time.Time) error

PreClaimSlug stakes the paste claim, so a directory's files stage on the same shard its manifest commits to.

func (*Sites) ReleaseSlugClaim added in v0.96.0

func (a *Sites) ReleaseSlugClaim(ctx context.Context, slug domain.Slug, owner string) error

ReleaseSlugClaim drops a claim whose deploy never landed.

func (*Sites) ReplaceWithQuotaCheck added in v0.96.0

func (a *Sites) ReplaceWithQuotaCheck(ctx context.Context, s domain.Site, storedBytes int, userCap int64, now time.Time) error

ReplaceWithQuotaCheck re-deploys an existing directory by APPENDING the new manifest as a version.

Prior versions stay live, exactly as they do for a document, so a directory pins, rolls back and rolls forward like anything else. That is the point of one paste model: a redeploy is an update, and an update has never thrown away what it replaced.

It therefore CHARGES like an update too - every live version counts against quota, and an owner reclaims bytes by deleting versions they no longer want. Blob dedup keeps the cost proportional to what actually changed: a redeploy touching one file of two hundred stores and charges for one blob.

Ownership is enforced here rather than inside the append: a slug that is not a directory, and one owned by another identity, both yield the not-found sentinel, so "not yours" stays indistinguishable from "does not exist".

func (*Sites) SumActiveBytesByOwner added in v0.96.0

func (a *Sites) SumActiveBytesByOwner(string, time.Time) (int64, error)

SumActiveBytesByOwner reports ZERO, and that is not a stub.

A directory IS a paste, so its bytes are already in the paste sum the service adds this to. Reporting them again would bill every directory twice.

type WriteBackBlobStore added in v0.44.0

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

WriteBackBlobStore is a local-disk write-back cache in front of a durable backend: Put writes to the pod's local disk and enqueues an asynchronous upload, Get/GetReader serve from the cache first and fall back to the backend. It is OPT-IN, trading a durability window (the local copy lands immediately, the backend copy follows the async upload) for a fast upload ack. See SPEC "Local-disk write-back cache".

Compressed bytes live at <dir>/<sha[:2]>/<sha>; an uploaded entry additionally carries a zero-byte <dir>/<sha[:2]>/<sha>.up marker. No marker means the blob is not yet confirmed durable in the backend, so the local copy is the ONLY one and must not be evicted.

func NewWriteBackBlobStore added in v0.44.0

func NewWriteBackBlobStore(durable durableBlobStore, cfg WriteBackConfig) (*WriteBackBlobStore, error)

NewWriteBackBlobStore builds the cache, re-enqueues any blob the cache dir shows was not confirmed uploaded before the last shutdown, and starts the uploader pool. Call Close to stop the uploaders.

func (*WriteBackBlobStore) Close added in v0.44.0

func (w *WriteBackBlobStore) Close()

Close stops the background uploaders without draining the queue: a blob not yet uploaded stays in the cache unmarked and is re-enqueued by the next process's startup rescan.

func (*WriteBackBlobStore) Get added in v0.44.0

func (w *WriteBackBlobStore) Get(sha string) ([]byte, error)

Get returns the bytes for sha, cache-first then durable backend.

func (*WriteBackBlobStore) GetReader added in v0.44.0

func (w *WriteBackBlobStore) GetReader(sha string) (io.ReadCloser, int64, error)

GetReader streams the bytes for sha, cache-first then durable backend.

func (*WriteBackBlobStore) Put added in v0.44.0

func (w *WriteBackBlobStore) Put(sha string, r io.Reader, size int64) error

Put writes the bytes to the local cache and enqueues an async upload, returning once the local write is durable (fsync'd + renamed). If the durable backend already holds the object, nothing is written or enqueued.

func (*WriteBackBlobStore) PutPrecompressed added in v0.44.0

func (w *WriteBackBlobStore) PutPrecompressed(sha string, body []byte) error

PutPrecompressed takes the body already in its stored (compressed, magic-prefixed) representation, mirroring the other backends.

func (*WriteBackBlobStore) Remove added in v0.44.0

func (w *WriteBackBlobStore) Remove(sha string) error

Remove deletes sha from both the durable backend and the local cache.

func (*WriteBackBlobStore) WalkBlobs added in v0.44.0

func (w *WriteBackBlobStore) WalkBlobs(fn func(sha string) error) error

WalkBlobs delegates to the durable backend, which is authoritative for what exists for GC purposes. A not-yet-uploaded local-only blob belongs to a live paste whose metadata references it, so it is not a GC candidate and shows up in the backend once uploaded.

type WriteBackConfig added in v0.44.0

type WriteBackConfig struct {
	// Dir is the local cache directory. Required.
	Dir string
	// MaxBytes is the soft cap on the cache's on-disk size. Past it,
	// already-uploaded entries are evicted oldest-first; not-yet-uploaded
	// entries are never evicted. <= 0 means 1 GiB.
	MaxBytes int64
	// Workers is the number of background uploader goroutines. <= 0 means 2.
	Workers int
	// Logger receives non-fatal uploader diagnostics. nil discards.
	Logger *log.Logger
	// contains filtered or unexported fields
}

WriteBackConfig tunes the local-disk write-back cache.

Jump to

Keyboard shortcuts

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