Merge pull request #555 from seaweedfs/feat/oss-layout-pure

layout: content names, shard paths and manifest encodings
This commit is contained in:
Ping Qiu authored and GitHub committed 2026-11-24 11:58:00 -08:00
commit 346fd4bf1c
2 files changed
+851

No files matched your search

@@ -0,0 +1,440 @@
// Package layout holds the pure, content-named layout of a volume's store
// objects: chunk names, their pool paths, manifest segments and roots.
//
// Under <base>/<volume>/:
//
// pool/<index/10000>/<index>-<sha256> a chunk's bytes
// seg/<shard>-<sha256> the manifest segment of one shard
// root/<sha256> the segment names, one per shard
//
// Every name is derived from the object's content, so a name that exists
// names a complete object and writing it again is a no-op. Nothing here
// touches a store except Present and MissingOwn, which only look names up.
package layout
import (
"bytes"
"context"
"crypto/sha256"
"encoding/binary"
"encoding/hex"
"errors"
"fmt"
"path"
"sort"
"strconv"
"strings"
)
// ShardSize is the number of chunk indexes per pool directory and per
// manifest segment.
const ShardSize = 10000
const (
PoolDir = "pool"
SegDir = "seg"
RootDir = "root"
)
// ErrMalformed reports a name or an encoding that is not canonical.
var ErrMalformed = errors.New("layout: malformed")
// Hash is the SHA-256 of an object's bytes.
type Hash [sha256.Size]byte
func (h Hash) String() string { return hex.EncodeToString(h[:]) }
// Sum returns the SHA-256 of b.
func Sum(b []byte) Hash { return sha256.Sum256(b) }
func parseHash(s string) (Hash, error) {
var h Hash
if len(s) != 2*len(h) || strings.ToLower(s) != s {
return h, fmt.Errorf("%w: hash %q is not 64 lower-case hex digits", ErrMalformed, s)
}
if _, err := hex.Decode(h[:], []byte(s)); err != nil {
return h, fmt.Errorf("%w: hash %q: %v", ErrMalformed, s, err)
}
return h, nil
}
// parseIndex accepts only canonical decimal: no sign, no leading zero.
func parseIndex(s string) (uint64, error) {
if s == "" || (len(s) > 1 && s[0] == '0') || strings.TrimLeft(s, "0123456789") != "" {
return 0, fmt.Errorf("%w: index %q is not canonical decimal", ErrMalformed, s)
}
n, err := strconv.ParseUint(s, 10, 64)
if err != nil {
return 0, fmt.Errorf("%w: index %q: %v", ErrMalformed, s, err)
}
return n, nil
}
// Shard returns the shard of a chunk index.
func Shard(index uint64) uint64 { return index / ShardSize }
// ChunkName is one chunk of one volume: its index and the hash of its bytes.
type ChunkName struct {
Index uint64
Hash Hash
}
// NameChunk names the chunk at index holding data.
func NameChunk(index uint64, data []byte) ChunkName {
return ChunkName{Index: index, Hash: Sum(data)}
}
// String is the file name of the chunk: <index>-<sha256>.
func (c ChunkName) String() string {
return strconv.FormatUint(c.Index, 10) + "-" + c.Hash.String()
}
// ParseChunkName parses <index>-<sha256>.
func ParseChunkName(s string) (ChunkName, error) {
i, h, ok := strings.Cut(s, "-")
if !ok {
return ChunkName{}, fmt.Errorf("%w: chunk name %q", ErrMalformed, s)
}
idx, err := parseIndex(i)
if err != nil {
return ChunkName{}, err
}
hash, err := parseHash(h)
if err != nil {
return ChunkName{}, err
}
return ChunkName{Index: idx, Hash: hash}, nil
}
// Dir is the chunk's pool directory relative to the volume root:
// pool/<index/10000>.
func (c ChunkName) Dir() string {
return path.Join(PoolDir, strconv.FormatUint(Shard(c.Index), 10))
}
// Path is the chunk's path relative to the volume root.
func (c ChunkName) Path() string { return path.Join(c.Dir(), c.String()) }
// Verify checks that data is the content c names.
func (c ChunkName) Verify(data []byte) error {
if got := Sum(data); got != c.Hash {
return fmt.Errorf("layout: chunk %d: content hash %s does not match its name %s", c.Index, got, c.Hash)
}
return nil
}
// Ref is one entry of a manifest: the chunk at an index, held in the pool
// of Owner (the volume itself, or the source volume of a restore).
type Ref struct {
Owner string
Chunk ChunkName
}
// checkOwner enforces a plain path element, as volume ids are.
func checkOwner(o string) error {
if o == "" || o == "." || o == ".." || strings.ContainsAny(o, "/\\") {
return fmt.Errorf("%w: owner %q is not a plain path element", ErrMalformed, o)
}
return nil
}
// Segment is the manifest of one shard: the chunks present in it. An index
// with no entry reads as zeros.
type Segment struct {
Shard uint64
Chunks map[uint64]Ref // by chunk index
}
var segMagic = []byte("SWBSEG\x01")
var rootMagic = []byte("SWBROOT\x01")
// Encode returns the canonical bytes of s: entries in index order. It
// refuses an empty segment (a shard with no chunk is left out of the root)
// and an entry outside the shard or keyed by another index than its chunk.
func (s Segment) Encode() ([]byte, error) {
if len(s.Chunks) == 0 {
return nil, fmt.Errorf("%w: segment of shard %d is empty", ErrMalformed, s.Shard)
}
idx := make([]uint64, 0, len(s.Chunks))
for i, r := range s.Chunks {
if r.Chunk.Index != i {
return nil, fmt.Errorf("%w: segment entry %d names chunk %d", ErrMalformed, i, r.Chunk.Index)
}
if Shard(i) != s.Shard {
return nil, fmt.Errorf("%w: chunk %d is not in shard %d", ErrMalformed, i, s.Shard)
}
if err := checkOwner(r.Owner); err != nil {
return nil, err
}
idx = append(idx, i)
}
sort.Slice(idx, func(a, b int) bool { return idx[a] < idx[b] })
var b bytes.Buffer
b.Write(segMagic)
b.Write(binary.AppendUvarint(nil, s.Shard))
b.Write(binary.AppendUvarint(nil, uint64(len(idx))))
for _, i := range idx {
r := s.Chunks[i]
b.Write(binary.AppendUvarint(nil, i))
b.Write(binary.AppendUvarint(nil, uint64(len(r.Owner))))
b.WriteString(r.Owner)
b.Write(r.Chunk.Hash[:])
}
return b.Bytes(), nil
}
// reader decodes uvarints and fixed fields, failing on a short input.
type reader struct {
b []byte
err error
}
func (r *reader) uvarint() uint64 {
if r.err != nil {
return 0
}
v, n := binary.Uvarint(r.b)
if n <= 0 {
r.err = fmt.Errorf("%w: bad varint", ErrMalformed)
return 0
}
r.b = r.b[n:]
return v
}
func (r *reader) bytes(n uint64) []byte {
if r.err != nil {
return nil
}
if uint64(len(r.b)) < n {
r.err = fmt.Errorf("%w: truncated", ErrMalformed)
return nil
}
out := r.b[:n]
r.b = r.b[n:]
return out
}
// DecodeSegment parses canonical segment bytes. Bytes that decode but are
// not what Encode would write (unsorted, duplicate, non-minimal varints,
// trailing bytes) are refused, so a segment has exactly one encoding and
// therefore exactly one name.
func DecodeSegment(b []byte) (Segment, error) {
if !bytes.HasPrefix(b, segMagic) {
return Segment{}, fmt.Errorf("%w: not a segment", ErrMalformed)
}
r := &reader{b: b[len(segMagic):]}
s := Segment{Shard: r.uvarint(), Chunks: map[uint64]Ref{}}
n := r.uvarint()
if r.err == nil && n > ShardSize {
return Segment{}, fmt.Errorf("%w: segment claims %d entries", ErrMalformed, n)
}
for k := uint64(0); k < n && r.err == nil; k++ {
i := r.uvarint()
owner := string(r.bytes(r.uvarint()))
var h Hash
copy(h[:], r.bytes(uint64(len(h))))
if r.err == nil {
if _, dup := s.Chunks[i]; dup {
return Segment{}, fmt.Errorf("%w: chunk %d twice", ErrMalformed, i)
}
s.Chunks[i] = Ref{Owner: owner, Chunk: ChunkName{Index: i, Hash: h}}
}
}
if r.err != nil {
return Segment{}, r.err
}
again, err := s.Encode()
if err != nil {
return Segment{}, err
}
if !bytes.Equal(again, b) {
return Segment{}, fmt.Errorf("%w: segment bytes are not canonical", ErrMalformed)
}
return s, nil
}
// SegName names one shard's segment: <shard>-<sha256 of its bytes>.
type SegName struct {
Shard uint64
Hash Hash
}
func (n SegName) String() string {
return strconv.FormatUint(n.Shard, 10) + "-" + n.Hash.String()
}
// Path is the segment's path relative to the volume root.
func (n SegName) Path() string { return path.Join(SegDir, n.String()) }
// ParseSegName parses <shard>-<sha256>.
func ParseSegName(s string) (SegName, error) {
c, err := ParseChunkName(s) // same shape
if err != nil {
return SegName{}, fmt.Errorf("segment name: %w", err)
}
return SegName{Shard: c.Index, Hash: c.Hash}, nil
}
// NameSegment returns the name and bytes of s.
func NameSegment(s Segment) (SegName, []byte, error) {
b, err := s.Encode()
if err != nil {
return SegName{}, nil, err
}
return SegName{Shard: s.Shard, Hash: Sum(b)}, b, nil
}
// Root is the image at one moment: the segment of every shard that holds a
// chunk. A shard without a segment reads as zeros.
type Root struct {
Segments map[uint64]SegName // by shard
}
// Encode returns the canonical bytes of r: segments in shard order. An
// empty root (an all-zero image) is valid.
func (r Root) Encode() ([]byte, error) {
shards := make([]uint64, 0, len(r.Segments))
for sh, n := range r.Segments {
if n.Shard != sh {
return nil, fmt.Errorf("%w: root entry %d names segment of shard %d", ErrMalformed, sh, n.Shard)
}
shards = append(shards, sh)
}
sort.Slice(shards, func(a, b int) bool { return shards[a] < shards[b] })
var b bytes.Buffer
b.Write(rootMagic)
b.Write(binary.AppendUvarint(nil, uint64(len(shards))))
for _, sh := range shards {
b.Write(binary.AppendUvarint(nil, sh))
h := r.Segments[sh].Hash
b.Write(h[:])
}
return b.Bytes(), nil
}
// maxRootShards bounds a decoded root: one entry needs at least 33 bytes.
func maxRootShards(n int) uint64 { return uint64(n / (1 + sha256.Size)) }
// DecodeRoot parses canonical root bytes; non-canonical bytes are refused.
func DecodeRoot(b []byte) (Root, error) {
if !bytes.HasPrefix(b, rootMagic) {
return Root{}, fmt.Errorf("%w: not a root", ErrMalformed)
}
r := &reader{b: b[len(rootMagic):]}
out := Root{Segments: map[uint64]SegName{}}
n := r.uvarint()
if r.err == nil && n > maxRootShards(len(r.b)) {
return Root{}, fmt.Errorf("%w: root claims %d shards", ErrMalformed, n)
}
for k := uint64(0); k < n && r.err == nil; k++ {
sh := r.uvarint()
var h Hash
copy(h[:], r.bytes(uint64(len(h))))
if r.err == nil {
if _, dup := out.Segments[sh]; dup {
return Root{}, fmt.Errorf("%w: shard %d twice", ErrMalformed, sh)
}
out.Segments[sh] = SegName{Shard: sh, Hash: h}
}
}
if r.err != nil {
return Root{}, r.err
}
again, _ := out.Encode()
if !bytes.Equal(again, b) {
return Root{}, fmt.Errorf("%w: root bytes are not canonical", ErrMalformed)
}
return out, nil
}
// RootName is the name of a root: the SHA-256 of its bytes.
type RootName struct{ Hash Hash }
func (n RootName) String() string { return n.Hash.String() }
// Path is the root's path relative to the volume root.
func (n RootName) Path() string { return path.Join(RootDir, n.String()) }
// ParseRootName parses a root file name.
func ParseRootName(s string) (RootName, error) {
h, err := parseHash(s)
if err != nil {
return RootName{}, fmt.Errorf("root name: %w", err)
}
return RootName{Hash: h}, nil
}
// NameRoot returns the name and bytes of r.
func NameRoot(r Root) (RootName, []byte, error) {
b, err := r.Encode()
if err != nil {
return RootName{}, nil, err
}
return RootName{Hash: Sum(b)}, b, nil
}
// Build splits a manifest (chunk index -> ref) into one segment per shard
// and the root naming them. It returns the root and every segment with its
// bytes, keyed by name, for the caller to write before the root.
func Build(manifest map[uint64]Ref) (Root, map[SegName][]byte, error) {
shards := map[uint64]Segment{}
for i, r := range manifest {
sh := Shard(i)
s, ok := shards[sh]
if !ok {
s = Segment{Shard: sh, Chunks: map[uint64]Ref{}}
shards[sh] = s
}
s.Chunks[i] = r
}
root := Root{Segments: map[uint64]SegName{}}
segs := map[SegName][]byte{}
for sh, s := range shards {
n, b, err := NameSegment(s)
if err != nil {
return Root{}, nil, err
}
root.Segments[sh] = n
segs[n] = b
}
return root, segs, nil
}
// Lookup reports whether the entry name exists in dir. A missing entry is
// (false, nil); any other failure is an error, never "absent".
type Lookup func(ctx context.Context, dir, name string) (bool, error)
// Present reports whether the object at rel (a Path of this package) exists
// under the volume root. An object exists only once it is complete (data
// first, file entry after), so true means complete.
func Present(ctx context.Context, look Lookup, volRoot, rel string) (bool, error) {
full := path.Join(volRoot, rel)
return look(ctx, path.Dir(full), path.Base(full))
}
// MissingOwn returns, in index order, the chunks of manifest held by vol's
// own pool that are not present there: the names a commit naming manifest
// would leave dangling. Chunks of another owner are not looked up (the
// owner's pool holds them).
func MissingOwn(ctx context.Context, look Lookup, volRoot, vol string, manifest map[uint64]Ref) ([]ChunkName, error) {
idx := make([]uint64, 0, len(manifest))
for i, r := range manifest {
if r.Owner == vol {
idx = append(idx, i)
}
}
sort.Slice(idx, func(a, b int) bool { return idx[a] < idx[b] })
var missing []ChunkName
for _, i := range idx {
c := manifest[i].Chunk
ok, err := Present(ctx, look, volRoot, c.Path())
if err != nil {
return nil, fmt.Errorf("layout: look up chunk %s: %w", c, err)
}
if !ok {
missing = append(missing, c)
}
}
return missing, nil
}
@@ -0,0 +1,411 @@
package layout
import (
"bytes"
"context"
"encoding/binary"
"errors"
"math"
"math/rand"
"path"
"reflect"
"strconv"
"strings"
"testing"
)
// SHA-256("abc"), FIPS 180-2 test vector.
const abcHash = "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
func mustHash(t *testing.T, s string) Hash {
t.Helper()
h, err := parseHash(s)
if err != nil {
t.Fatal(err)
}
return h
}
func TestChunkName_GoldenNameAndPath(t *testing.T) {
c := NameChunk(12345, []byte("abc"))
if got := c.String(); got != "12345-"+abcHash {
t.Fatalf("name %q", got)
}
if got := c.Path(); got != "pool/1/12345-"+abcHash {
t.Fatalf("path %q", got)
}
if err := c.Verify([]byte("abc")); err != nil {
t.Fatal(err)
}
if err := c.Verify([]byte("abd")); err == nil {
t.Fatal("Verify accepted other bytes")
}
}
func TestShard_Boundaries(t *testing.T) {
for _, tc := range []struct{ idx, shard uint64 }{
{0, 0}, {9999, 0}, {10000, 1}, {19999, 1}, {20000, 2}, {math.MaxUint64, math.MaxUint64 / 10000},
} {
if got := Shard(tc.idx); got != tc.shard {
t.Errorf("Shard(%d) = %d; want %d", tc.idx, got, tc.shard)
}
c := ChunkName{Index: tc.idx}
if want := path.Join("pool", strconv.FormatUint(tc.shard, 10)); c.Dir() != want {
t.Errorf("Dir(%d) = %q; want %q", tc.idx, c.Dir(), want)
}
}
}
func TestParseChunkName_RoundTripAndRefusals(t *testing.T) {
for _, idx := range []uint64{0, 7, 10000, math.MaxUint64} {
c := ChunkName{Index: idx, Hash: mustHash(t, abcHash)}
got, err := ParseChunkName(c.String())
if err != nil || got != c {
t.Fatalf("round trip of %s: %+v %v", c, got, err)
}
}
for _, bad := range []string{
"",
abcHash, // no index
"12345", // no hash
"012-" + abcHash, // leading zero
"+1-" + abcHash, // sign
"-" + abcHash, // empty index
"18446744073709551616-" + abcHash, // overflows uint64
"1-" + strings.ToUpper(abcHash), // upper-case hex
"1-" + abcHash[:63], // short
"1-" + abcHash + "0", // long
"1-" + abcHash[:63] + "g", // not hex
"1-" + abcHash + "-x", // trailing part
} {
if _, err := ParseChunkName(bad); !errors.Is(err, ErrMalformed) {
t.Errorf("ParseChunkName(%q): %v; want ErrMalformed", bad, err)
}
}
}
func ref(owner string, idx uint64, data string) Ref {
return Ref{Owner: owner, Chunk: NameChunk(idx, []byte(data))}
}
// goldenSegment is the encoding of shard 1 holding chunk 10000 ("abc", own)
// and chunk 10001 (from volume "src"), written out by hand.
func goldenSegment(t *testing.T) []byte {
t.Helper()
h := mustHash(t, abcHash)
h2 := Sum([]byte("x"))
var b []byte
b = append(b, "SWBSEG\x01"...)
b = binary.AppendUvarint(b, 1) // shard
b = binary.AppendUvarint(b, 2) // entries
b = binary.AppendUvarint(b, 10000)
b = binary.AppendUvarint(b, 2)
b = append(b, "v1"...)
b = append(b, h[:]...)
b = binary.AppendUvarint(b, 10001)
b = binary.AppendUvarint(b, 3)
b = append(b, "src"...)
b = append(b, h2[:]...)
return b
}
func TestSegment_GoldenEncodingRoundTrip(t *testing.T) {
s := Segment{Shard: 1, Chunks: map[uint64]Ref{10001: ref("src", 10001, "x"), 10000: ref("v1", 10000, "abc")}}
got, err := s.Encode()
if err != nil {
t.Fatal(err)
}
want := goldenSegment(t)
if !bytes.Equal(got, want) {
t.Fatalf("encoding\n got %x\nwant %x", got, want)
}
back, err := DecodeSegment(got)
if err != nil || !reflect.DeepEqual(back, s) {
t.Fatalf("decode: %+v %v", back, err)
}
n, b, err := NameSegment(s)
if err != nil || !bytes.Equal(b, want) || n.Hash != Sum(want) || n.Shard != 1 {
t.Fatalf("name %s %v", n, err)
}
if n.Path() != "seg/1-"+Sum(want).String() {
t.Fatalf("path %q", n.Path())
}
if p, err := ParseSegName(n.String()); err != nil || p != n {
t.Fatalf("ParseSegName: %+v %v", p, err)
}
}
func TestSegment_EncodeRefusals(t *testing.T) {
for name, s := range map[string]Segment{
"empty": {Shard: 0, Chunks: map[uint64]Ref{}},
"chunk outside shard": {Shard: 0, Chunks: map[uint64]Ref{10000: ref("v1", 10000, "a")}},
"key is not the index": {Shard: 0, Chunks: map[uint64]Ref{1: ref("v1", 2, "a")}},
"owner empty": {Shard: 0, Chunks: map[uint64]Ref{1: ref("", 1, "a")}},
"owner with slash": {Shard: 0, Chunks: map[uint64]Ref{1: ref("a/b", 1, "a")}},
"owner dot-dot": {Shard: 0, Chunks: map[uint64]Ref{1: ref("..", 1, "a")}},
} {
if _, err := s.Encode(); !errors.Is(err, ErrMalformed) {
t.Errorf("%s: %v; want ErrMalformed", name, err)
}
}
}
// segBytes writes entries in the given order, without the checks Encode
// makes: the hostile inputs DecodeSegment must refuse.
func segBytes(shard uint64, entries ...Ref) []byte {
var b []byte
b = append(b, "SWBSEG\x01"...)
b = binary.AppendUvarint(b, shard)
b = binary.AppendUvarint(b, uint64(len(entries)))
for _, r := range entries {
b = binary.AppendUvarint(b, r.Chunk.Index)
b = binary.AppendUvarint(b, uint64(len(r.Owner)))
b = append(b, r.Owner...)
b = append(b, r.Chunk.Hash[:]...)
}
return b
}
func TestDecodeSegment_RefusesNonCanonical(t *testing.T) {
a, c := ref("v1", 1, "a"), ref("v1", 2, "b")
good := segBytes(0, a, c)
if _, err := DecodeSegment(good); err != nil {
t.Fatalf("control: %v", err)
}
nonMinimal := append([]byte("SWBSEG\x01"), 0x80, 0x00) // shard 0 in two bytes
nonMinimal = append(nonMinimal, segBytes(0, a, c)[len("SWBSEG\x01")+1:]...)
huge := append([]byte("SWBSEG\x01"), 0)
huge = binary.AppendUvarint(huge, ShardSize+1)
for name, b := range map[string][]byte{
"wrong magic": append([]byte("SWBSEG\x02"), good[7:]...),
"unsorted": segBytes(0, c, a),
"duplicate": segBytes(0, a, a),
"empty": segBytes(0),
"outside shard": segBytes(1, a),
"bad owner": segBytes(0, ref("a/b", 1, "a")),
"trailing byte": append(append([]byte(nil), good...), 0),
"truncated": good[:len(good)-1],
"non-minimal varint": nonMinimal,
"count above a shard": huge,
} {
if _, err := DecodeSegment(b); !errors.Is(err, ErrMalformed) {
t.Errorf("%s: %v; want ErrMalformed", name, err)
}
}
}
func TestRoot_GoldenEncodingRoundTrip(t *testing.T) {
s0 := SegName{Shard: 0, Hash: mustHash(t, abcHash)}
s3 := SegName{Shard: 3, Hash: Sum([]byte("x"))}
r := Root{Segments: map[uint64]SegName{3: s3, 0: s0}}
var want []byte
want = append(want, "SWBROOT\x01"...)
want = binary.AppendUvarint(want, 2)
want = binary.AppendUvarint(want, 0)
want = append(want, s0.Hash[:]...)
want = binary.AppendUvarint(want, 3)
want = append(want, s3.Hash[:]...)
got, err := r.Encode()
if err != nil || !bytes.Equal(got, want) {
t.Fatalf("encoding %x %v\nwant %x", got, err, want)
}
back, err := DecodeRoot(got)
if err != nil || !reflect.DeepEqual(back, r) {
t.Fatalf("decode %+v %v", back, err)
}
n, _, err := NameRoot(r)
if err != nil || n.Hash != Sum(want) || n.Path() != "root/"+Sum(want).String() {
t.Fatalf("name %s %v", n, err)
}
if p, err := ParseRootName(n.String()); err != nil || p != n {
t.Fatalf("ParseRootName %+v %v", p, err)
}
empty, err := Root{}.Encode() // an all-zero image
if err != nil {
t.Fatal(err)
}
if back, err := DecodeRoot(empty); err != nil || len(back.Segments) != 0 {
t.Fatalf("empty root: %+v %v", back, err)
}
}
func TestRoot_Refusals(t *testing.T) {
if _, err := (Root{Segments: map[uint64]SegName{1: {Shard: 2}}}).Encode(); !errors.Is(err, ErrMalformed) {
t.Errorf("root keyed by another shard: %v", err)
}
h := Sum([]byte("x"))
raw := func(shards ...uint64) []byte {
b := append([]byte(nil), "SWBROOT\x01"...)
b = binary.AppendUvarint(b, uint64(len(shards)))
for _, s := range shards {
b = binary.AppendUvarint(b, s)
b = append(b, h[:]...)
}
return b
}
good := raw(0, 5)
if _, err := DecodeRoot(good); err != nil {
t.Fatalf("control: %v", err)
}
huge := binary.AppendUvarint(append([]byte(nil), "SWBROOT\x01"...), 1<<40)
for name, b := range map[string][]byte{
"wrong magic": append([]byte("SWBSEG\x01"), good[8:]...),
"unsorted": raw(5, 0),
"duplicate": raw(5, 5),
"trailing byte": append(append([]byte(nil), good...), 0),
"truncated": good[:len(good)-1],
"huge count": huge,
} {
if _, err := DecodeRoot(b); !errors.Is(err, ErrMalformed) {
t.Errorf("%s: %v; want ErrMalformed", name, err)
}
}
for _, bad := range []string{"", abcHash[:63], strings.ToUpper(abcHash), "1-" + abcHash} {
if _, err := ParseRootName(bad); !errors.Is(err, ErrMalformed) {
t.Errorf("ParseRootName(%q): %v", bad, err)
}
}
}
// A manifest's root does not depend on map order, and changing one chunk
// changes only its shard's segment name and the root name: the unchanged
// shards' segments are reused as they are.
func TestBuild_ShardsAndIncrementalReuse(t *testing.T) {
m := map[uint64]Ref{
0: ref("v1", 0, "a"), 9999: ref("v1", 9999, "b"),
10000: ref("src", 10000, "c"),
30005: ref("v1", 30005, "d"),
}
root, segs, err := Build(m)
if err != nil {
t.Fatal(err)
}
if len(root.Segments) != 3 || len(segs) != 3 {
t.Fatalf("shards %v, segments %d; want shards 0, 1, 3", root.Segments, len(segs))
}
got := map[uint64]Ref{}
for sh, n := range root.Segments {
s, err := DecodeSegment(segs[n])
if err != nil || s.Shard != sh || Sum(segs[n]) != n.Hash {
t.Fatalf("segment %s: %+v %v", n, s, err)
}
for i, r := range s.Chunks {
got[i] = r
}
}
if !reflect.DeepEqual(got, m) {
t.Fatalf("manifest read back %v; want %v", got, m)
}
r1, _, _ := NameRoot(root)
for k := 0; k < 20; k++ { // map order never shows
again, _, _ := Build(m)
if r, _, _ := NameRoot(again); r != r1 {
t.Fatal("the root name depends on map order")
}
}
m2 := map[uint64]Ref{}
for i, r := range m {
m2[i] = r
}
m2[30005] = ref("v1", 30005, "d2")
root2, _, err := Build(m2)
if err != nil {
t.Fatal(err)
}
for _, sh := range []uint64{0, 1} {
if root2.Segments[sh] != root.Segments[sh] {
t.Errorf("shard %d segment changed although none of its chunks did", sh)
}
}
if root2.Segments[3] == root.Segments[3] {
t.Error("shard 3 segment unchanged although its chunk changed")
}
if r2, _, _ := NameRoot(root2); r2 == r1 {
t.Error("root name unchanged although the image changed")
}
}
func TestEncodings_RandomRoundTrip(t *testing.T) {
rng := rand.New(rand.NewSource(1))
owners := []string{"v1", "src", "a b"} // ids may hold spaces
for k := 0; k < 200; k++ {
m := map[uint64]Ref{}
for j := rng.Intn(50); j > 0; j-- {
i := uint64(rng.Int63n(100000))
var d [8]byte
rng.Read(d[:])
m[i] = Ref{Owner: owners[rng.Intn(len(owners))], Chunk: NameChunk(i, d[:])}
}
root, segs, err := Build(m)
if err != nil {
t.Fatal(err)
}
_, rb, err := NameRoot(root)
if err != nil {
t.Fatal(err)
}
back, err := DecodeRoot(rb)
if err != nil || !reflect.DeepEqual(back.Segments, root.Segments) {
t.Fatalf("root round trip: %v", err)
}
for n, b := range segs {
s, err := DecodeSegment(b)
if err != nil {
t.Fatal(err)
}
if again, _ := s.Encode(); !bytes.Equal(again, b) || Sum(b) != n.Hash {
t.Fatalf("segment %s does not re-encode to its name", n)
}
}
}
}
type fakeStore struct {
have map[string]bool
fail string // a path whose lookup fails
asked []string
}
func (f *fakeStore) look(_ context.Context, dir, name string) (bool, error) {
p := path.Join(dir, name)
f.asked = append(f.asked, p)
if p == f.fail {
return false, errors.New("filer unavailable")
}
return f.have[p], nil
}
func TestPresentAndMissingOwn(t *testing.T) {
ctx := context.Background()
const vr = "/swblock/chunks/v1"
a, b, foreign := ref("v1", 3, "a"), ref("v1", 10007, "b"), ref("src", 5, "c")
m := map[uint64]Ref{3: a, 10007: b, 5: foreign}
f := &fakeStore{have: map[string]bool{path.Join(vr, a.Chunk.Path()): true}}
if ok, err := Present(ctx, f.look, vr, a.Chunk.Path()); err != nil || !ok {
t.Fatalf("Present of an uploaded chunk: %t %v", ok, err)
}
if ok, err := Present(ctx, f.look, vr, b.Chunk.Path()); err != nil || ok {
t.Fatalf("Present of a missing chunk: %t %v", ok, err)
}
f.asked = nil
missing, err := MissingOwn(ctx, f.look, vr, "v1", m)
if err != nil || len(missing) != 1 || missing[0] != b.Chunk {
t.Fatalf("MissingOwn: %v %v; want [%s]", missing, err, b.Chunk)
}
for _, p := range f.asked {
if strings.Contains(p, foreign.Chunk.String()) {
t.Fatalf("MissingOwn looked up the foreign chunk at %s", p)
}
}
if want := path.Join(vr, "pool/1", b.Chunk.String()); f.asked[len(f.asked)-1] != want {
t.Fatalf("looked up %v; want the shard directory path %s last", f.asked, want)
}
// A failed lookup is an error, never "absent" and never "present".
f.fail = path.Join(vr, b.Chunk.Path())
if got, err := MissingOwn(ctx, f.look, vr, "v1", m); err == nil {
t.Fatalf("MissingOwn with a failing lookup: %v, no error", got)
}
if _, err := Present(ctx, f.look, vr, b.Chunk.Path()); err == nil {
t.Fatal("Present with a failing lookup: no error")
}
}