bnc

package
v0.12.0 Latest Latest
Warning

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

Go to latest
Published: Dec 6, 2026 License: Apache-2.0 Imports: 17 Imported by: ? modules, 0 packages

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

Documentation

Overview

Package bnc implements the .bnc native container of data export: the engine files of one shard or one segment index directory packed back to back, byte for byte, followed by a footer that names them.

Layout, all integers little endian:

member 0 | … | member n-1 | footer | footer CRC-32 (u32) | footer length (u32) | "BNCA"

The footer, whose CRC-32 (IEEE) and length follow it:

uvarint volume_seq   number of this volume in its container, from 1
byte    last         1 when this is the last volume of the container, else 0
uvarint count        number of members, at least 1
repeat count times:
  uvarint path_len
  bytes   path       UTF-8, '/'-separated, relative to the container root
  u64     size       bytes of this member
  u32     crc32      IEEE CRC-32 of those bytes
  uvarint file_offset where these bytes start in their file, 0 for a whole file
  uvarint file_size  size of the whole file, equal to size for a whole file

Every uvarint is minimally encoded. Offsets in the container are not stored: a member starts where the one before it ends, and the last one ends where the footer starts. The last magic byte is the format version.

A container larger than a volume limit is written as several volumes, each a complete container within the limit. A file that crosses the end of a volume is split: its first piece ends that volume and the rest continues as the first member of the next one, so the volumes in order, joined by a VolumeSet, hold every file whole. A part, too, may span volumes: an importer joins every volume of a container before it groups the parts.

What the container can and cannot prove. Open, Verify and a VolumeSet check that the bytes are a well-formed container whose members match their CRC-32s and whose volumes join. They cannot prove that it is the container the caller expects, or that it is whole:

  • a container carries no identity: a valid container of another artifact, unit or node passes every check;
  • a prefix that ends exactly at an inner boundary, such as a first member that is itself a container, or a set of volumes whose last one says it is last, opens and verifies;
  • a file the producer never packed, such as a missing secondary index part, leaves nothing to detect; ShardLayout.Orphans holds leftovers of incomplete parts, not omissions.

The manifest is the final authority: compare the Summary of every volume with the manifest entry of that path before trusting a container.

Reading a file through VolumeSet.Open checks the CRC-32 of each piece on the Read that returns its last byte, and Close returns the first error a Read returned. Helpers that stop at an exact length, such as io.CopyN and io.ReadFull, drop that final error: check Close before committing the bytes anywhere. Checking while streaming this way costs one pass over the data; running Verify first and then reading again costs two.

The package must not import anything under banyand/ so that data nodes and clients share exactly the same code.

Index

Constants

View Source
const (
	// MinFileSize is the smallest volume limit a VolumeWriter accepts, far above the trailer
	// and the footer entry of the longest path, so that every volume holds file bytes.
	MinFileSize = 64 << 10

	// VolumeExt is the extension of a volume file.
	VolumeExt = ".bnc"
)
View Source
const (

	// WriteSize is the largest slice a Sink.Write call receives.
	WriteSize = 256 << 10
)

Variables

View Source
var (
	// ErrCorrupt reports a container that does not follow the format.
	ErrCorrupt = errors.New("corrupt bnc container")
	// ErrUnsupportedVersion reports a container of a format version this code cannot read.
	ErrUnsupportedVersion = errors.New("unsupported bnc container version")
	// ErrChecksum reports member bytes that do not match their CRC-32; it is an ErrCorrupt.
	ErrChecksum = fmt.Errorf("%w: member checksum mismatch", ErrCorrupt)
)

Functions

func CheckFileSize

func CheckFileSize(maxFileSize uint64) error

CheckFileSize refuses a volume limit a VolumeWriter does not accept: any non-zero value below MinFileSize.

func GroupVolumes

func GroupVolumes(paths []string) map[string][]string

GroupVolumes groups the volume paths among paths by container prefix, each group in volume order; a path that is not a volume name is left out.

func ParseVolumeName

func ParseVolumeName(p string) (prefix string, seq uint32, ok bool)

ParseVolumeName splits a volume path "<prefix>-NNNNN.bnc" into its container prefix and volume number; ok is false for any other path.

func VolumeName

func VolumeName(prefix string, seq uint32) string

VolumeName is the path of volume seq (from 1) of the container at prefix: "<prefix>-NNNNN.bnc".

Types

type Class

type Class struct {
	// PartType is "" for a core part and the index name for a trace secondary index part.
	PartType string
	PartID   uint64
	Kind     Kind
}

Class is the classification of a shard container member.

func ClassifyShardPath

func ClassifyShardPath(p string) Class

ClassifyShardPath classifies a member path of a shard container. Part IDs must be written as the engine writes them: sixteen lower-case hexadecimal digits.

type Container

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

Container is one opened volume whose structure has been checked. Its methods may be called concurrently. Files are read through a VolumeSet, which joins the pieces of a file split across volumes.

func Open

func Open(r io.ReaderAt, size int64) (*Container, error)

Open checks the structure of the container of size bytes in r with two ReadAt calls, without reading the members: the trailer, the footer and its CRC-32, every footer bound, and every member path. A truncated container is detected only when its tail no longer parses, and a container that opens is not proven complete: the size and CRC-32 a manifest records are the final word (see the package documentation).

func OpenFile

func OpenFile(path string) (*Container, error)

OpenFile opens and checks the container in the regular file at path, sizing it on the open descriptor. Close releases the file.

func (*Container) Close

func (c *Container) Close() error

Close closes the file of a Container from OpenFile; it does nothing for one from Open.

func (*Container) Entries

func (c *Container) Entries() []Entry

Entries returns a copy of the members in footer order.

func (*Container) Verify

func (c *Container) Verify(ctx context.Context) (Summary, error)

Verify reads the whole container once: it checks the CRC-32 of every member, checks that the footer and trailer still hold what Open read, and returns the size and CRC-32 of the file, which the caller compares with the manifest; success alone does not prove the container is the expected one or complete. A canceled ctx returns ctx.Err() unwrapped.

type Entry

type Entry struct {
	Path       string
	Offset     int64
	Size       int64
	FileOffset int64
	FileSize   int64
	CRC32      uint32
}

Entry is one member of a container as its footer describes it: a whole file, or one piece of a file split across consecutive volumes. Offset is where its bytes start in the container, derived from the sizes of the members before it; Size and CRC32 cover those bytes. FileOffset is where they start in the file and FileSize is the size of the whole file, so a whole file has FileOffset 0 and FileSize equal to Size.

type File

type File struct {
	Path string
	Size int64
	// contains filtered or unexported fields
}

File is one file of a VolumeSet, whole: its path and size, and where its pieces are.

type Kind

type Kind uint8

Kind classifies a member of a shard container (a stream, measure or trace shard directory).

const (
	// KindOther is any member the other kinds do not cover.
	KindOther Kind = iota
	// KindPart is a file of a part: "<016x>/<file>" for a core part, or
	// "sidx/<index>/<016x>/<file>" for a trace secondary index part.
	KindPart
	// KindSnapshot is a part visibility list "<016x>.snp" at the shard root.
	KindSnapshot
	// KindElementIndex is a file of the stream element index "idx/".
	KindElementIndex
)

type Member

type Member struct {
	Path string
	Size int64
}

Member is one file to pack: its path relative to the container root and its size.

func OrderIndexDir

func OrderIndexDir(files []Member) []Member

OrderIndexDir returns every file of a native index directory (a segment's sidx/ or a property shard) in write order, segment files before .snp manifests, so a manifest never precedes the segments it names.

func OrderShard

func OrderShard(files []Member) []Member

OrderShard returns the members of a stream, measure or trace shard directory in write order: part by part in ascending ID (core files, then each secondary index part by index name, files by path), the .snp files, the idx/ tree (segment files before .snp files), then every other file. Members are kept as given: the engine snapshot already leaves out runtime files.

type PartGroup

type PartGroup struct {
	// Subs holds the core part first, then the secondary index parts by index name.
	Subs   []SubPart
	PartID uint64
}

PartGroup is one part of a shard container: its core files and those of its trace secondary index parts.

type ShardLayout

type ShardLayout struct {
	Parts        []PartGroup
	Snapshots    []File
	ElementIndex []File
	Others       []File
	// Orphans are files of incomplete parts: a part without core files (its secondary index
	// outlived it), a core part without its metadata.json, or a secondary index part without
	// its manifest.json. A closed segment can hold such leftovers; a receiver cannot load
	// them, so an importer skips them.
	Orphans []File
}

ShardLayout is a shard container split by kind.

type Sink

type Sink interface {
	StartFile(relativePath string, seq uint32) error
	Write(p []byte) error
	FinishFile(sum Summary) error
}

Sink receives the volumes of a VolumeWriter. Write gets at most WriteSize bytes, and the slice is reused once Write returns: a Sink that keeps the bytes must copy them. A file is complete only when FinishFile follows its StartFile; after any error FinishFile is not called, and the caller must discard the file it started.

type SubPart

type SubPart struct {
	// PartType is "" for the core part and the index name for a secondary index part.
	PartType string
	// Files are the other files of the sub part, by path.
	Files []File
	// Meta is the metadata.json of a core part or the manifest.json of a secondary index part.
	Meta File
}

SubPart is the core part or one secondary index part of a PartGroup.

type Summary

type Summary struct {
	Bytes   uint64
	CRC32   uint32
	Entries uint32
}

Summary describes a whole container file in the types of manifest.File and FileFinished.

type VolumeSet

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

VolumeSet is the volumes of one container, joined in order: a file split across volumes reads as one. Its methods may be called concurrently.

func NewVolumeSet

func NewVolumeSet(containers []*Container) (*VolumeSet, error)

NewVolumeSet joins volumes the caller opened, given in volume order; Close closes them.

func OpenVolumes

func OpenVolumes(paths []string) (*VolumeSet, error)

OpenVolumes reads the footers of the volume files at paths, given in volume order, and joins them into a VolumeSet. Volumes are opened again on demand to read files or verify; while no file is read, the set keeps at most one of them open, which Close releases.

func (*VolumeSet) Close

func (s *VolumeSet) Close() error

Close closes the volumes the caller opened for NewVolumeSet and the volume kept open for reading, and returns the first error.

func (*VolumeSet) Files

func (s *VolumeSet) Files() []File

Files returns the files of the set in write order.

func (*VolumeSet) Open

func (s *VolumeSet) Open(f File) (io.ReadCloser, error)

Open returns a reader of the bytes of f, a file of s, across the volumes that hold it; each volume is open only while its piece is read. The Read that returns the last byte of a piece whose bytes do not match its CRC-32 returns ErrChecksum. Close releases the volume being read and returns the first error any Read returned, so a caller whose copy helper drops a final error, as io.CopyN and io.ReadFull do once they have all the bytes, still sees it: check the error of Close before trusting the bytes.

func (*VolumeSet) ReadFile

func (s *VolumeSet) ReadFile(f File, limit int64) ([]byte, error)

ReadFile reads a small file whole, such as the metadata.json of a part, refusing a file larger than limit bytes and checking its CRC-32.

func (*VolumeSet) Shard

func (s *VolumeSet) Shard() *ShardLayout

Shard groups the files of a shard container whatever their order in the volumes.

func (*VolumeSet) Verify

func (s *VolumeSet) Verify(ctx context.Context) ([]Summary, error)

Verify verifies every volume in order, one at a time through one buffer, and returns their summaries.

func (*VolumeSet) VolumeEntries

func (s *VolumeSet) VolumeEntries(i int) int

VolumeEntries returns the number of entries in the footer of volume i of the set.

type VolumeWriter

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

VolumeWriter packs files into volumes "<pathPrefix>-<seq>.bnc", seq printed with five digits from 1. Every volume is a complete container of at most maxFileSize bytes; it is filled up to that size, and a file that crosses the end of a volume continues as the first member of the next one, so the volumes in order hold every file whole. Its first error sticks.

func NewVolumeWriter

func NewVolumeWriter(sink Sink, pathPrefix string, maxFileSize uint64, open func(path string) (io.ReadCloser, error)) (*VolumeWriter, error)

NewVolumeWriter returns a VolumeWriter whose volume files are at most maxFileSize bytes on disk, footer and trailer included; 0 never splits, and any other value below MinFileSize is an error. open returns the bytes of a member by its path.

func (*VolumeWriter) Add

func (v *VolumeWriter) Add(ctx context.Context, m Member) error

Add writes the file m, splitting it across volumes where it crosses the end of one. Paths must be unique and none may be a directory of another, across all volumes.

func (*VolumeWriter) Close

func (v *VolumeWriter) Close() error

Close seals the last volume. A VolumeWriter that got no file produces no volume.

type Writer

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

Writer writes one container. Its first error sticks: every later call returns it, and a closed Writer fails every call.

func NewWriter

func NewWriter(w io.Writer) *Writer

NewWriter returns a Writer that writes a container to w.

func (*Writer) Add

func (w *Writer) Add(ctx context.Context, path string, size int64, r io.Reader) error

Add copies exactly size bytes of r as member path, checking ctx before each block. It reads r until io.EOF, so r must end: a shorter or longer r is an error, because snapshot files are frozen and a mismatch means the source changed. Errors of r keep their identity, and a canceled ctx returns ctx.Err() unwrapped.

func (*Writer) Close

func (w *Writer) Close() (Summary, error)

Close appends the footer, its CRC-32, its length and the magic, and returns the totals of the container. A container needs at least one member. A container a Writer writes alone is volume 1, and the last one.

Jump to

Keyboard shortcuts

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