transfer

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: 65 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 transfer holds helpers the data-export integration suites share.

Index

Constants

View Source
const (
	StreamGroup    = "default"
	StreamName     = "sw"
	MeasureGroup   = "sw_metric"
	MeasureName    = "service_cpm_minute"
	MeasureFile    = "service_cpm_minute_data.json"
	IndexModeGroup = "index_mode"
	IndexModeName  = "service_traffic"
	IndexModeFile  = "service_traffic_data.json"
	TraceGroup     = "test-trace-group"
	TraceName      = "sw"
	PropertyGroup  = "sw"
	PropertyName   = "ui_menu"
	PropertyFile   = "sw1.json"
)

The groups and resources the data-export suites write (test/cases/<catalog>/data).

View Source
const (
	MeasureRows       = 6
	TopNSourceMeasure = "service_instance_cpm_minute"
	TopNSourcePoints  = 6
)

WriteSuiteData writes MeasureRows points into MeasureName and TopNSourcePoints into TopNSourceMeasure, the source measure of a Top-N aggregation of MeasureGroup.

View Source
const (
	// RoundTripTimeout bounds how long an import target may take to flush and commit what it
	// imported before an export of it holds every row.
	RoundTripTimeout = 3 * time.Minute
)
View Source
const WriteInterval = 500 * time.Millisecond

WriteInterval spaces the points WriteSuiteData writes.

Variables

View Source
var Catalogs = []string{"stream", "measure", "trace", "property"}

Catalogs lists the on-disk catalog directories of a data node that hold export snapshots.

Functions

func CopyWithGroup

func CopyWithGroup(src, dst, group string, edit func(*commonv1.Group)) string

CopyWithGroup copies the artifact src to dst with the schema of group changed by edit, keeping its manifest consistent, and returns dst.

func CreateRequest

func CreateRequest(selectors []*transferv1.Selector, preempt bool) *transferv1.PlanRequest

CreateRequest builds the CreateSession PlanRequest a client sends to the liaison: no id, the given selectors and preempt flag.

func CurrentNodeName

func CurrentNodeName(addr string) string

CurrentNodeName asks the data node at addr for the node id the liaison registers it under.

func DefaultExportOptions

func DefaultExportOptions(output string) config.Export

DefaultExportOptions are the bydbctl defaults of an export into output, read from the option tags, with a parallelism of 4.

func DefaultImportOptions

func DefaultImportOptions(input string) config.Import

DefaultImportOptions are the bydbctl defaults of an import of input, read from the option tags, with --verify-timeout at least the suite's eventually timeout. Each gets its own progress file outside input: the default is one per artifact, and a finished import is not imported again, but the suites import one artifact into the same target more than once expecting a fresh import each time (a re-import onto the rows already stored). A resume reuses the options of the run it resumes.

func DefaultNativeExportOptions

func DefaultNativeExportOptions(output string) config.Export

DefaultNativeExportOptions are DefaultExportOptions for a native export: no compression.

func ExpectAbortedOutput

func ExpectAbortedOutput(dir string)

ExpectAbortedOutput asserts what an aborted export leaves behind: no manifest, and every file renamed into place below nodes/ a complete, decodable CSV file. A file cut short keeps its .tmp name.

func ExpectRolledFiles

func ExpectRolledFiles(a *Artifact)

ExpectRolledFiles asserts the shape of an export written with --compress none and a one-byte --max-file-size: plain .csv files of one row each, every file of a writer numbered consecutively and starting with the header (VerifyLayouts checks its content).

func ExpectRoundTrip

func ExpectRoundTrip(g gomega.Gomega, topN rowdiff.TopN, dirA, dirB string, groups ...string) *rowdiff.Report

ExpectRoundTrip asserts with g that the artifact dirB, exported from an import target, holds the same logical rows as the source artifact dirA for the given groups (every group of dirA when none is given), and returns the comparison report for further assertions. topN merges the copies of each Top-N result (rowdiff.Options.TopN); this package cannot provide it, as decoding Top-N values needs banyand/measure (see package topncheck).

func ExpectSameQueries

func ExpectSameQueries(g gomega.Gomega, src, dst *grpc.ClientConn)

ExpectSameQueries runs the suite's query-layer checks against src and dst over the same time window and asserts that each query returns a non-empty result on src and the same normalized result on dst: a measure query by an entity tag, a stream query by a non-entity indexed tag, a trace query ordered by an index rule (the order must match), and an index-mode measure query. Rowdiff compares stored rows only; these queries also read the target's series and inverted indexes.

func ExpireLease

func ExpireLease(path string)

ExpireLease rewrites a .lease file so that its expiresAt lies in the past.

func ExportEntries

func ExportEntries(dataDir, catalog string) []string

ExportEntries lists the entries of one catalog's export snapshot directory on a data node.

func ExportEventually

func ExportEventually(addr, root string, check func(g gomega.Gomega, dir string)) string

ExportEventually exports through the liaison at addr into new directories below root until the export satisfies check, which sees the export directory, and returns that directory. A target flushes and commits what it imported on its own schedule (properties and index-mode documents are not reconciled by --verify), so the first exports may still miss rows.

func ExportFrom

func ExportFrom(addr, root string) string

ExportFrom exports every catalog through the liaison at addr into a new directory below root and returns it.

func GroupRows

func GroupRows(frames []*transferv1.PlanResponse, catalog commonv1.Catalog, group string) uint64

GroupRows sums the total_count of one catalog and group's shards on every node.

func HashTree

func HashTree(root string) map[string]string

HashTree fingerprints the part files and segment metadata below root: relative path -> content hash. The inverted index directories (sidx/, idx/) are skipped: their writers persist and merge on their own schedule, so their bytes move even when nobody reads them. Parts are immutable, which is what "planning never writes" can be asserted on.

func Heartbeat

func Heartbeat(conn *grpc.ClientConn, id string) []*transferv1.SessionsResponse

Heartbeat runs ACTION_HEARTBEAT for id and returns every frame.

func IndexModeDocs

func IndexModeDocs(frames []*transferv1.PlanResponse, group string) uint64

IndexModeDocs adds up the series index documents the inventory reports for a measure group, on every node: in a group of index-mode measures only, the rows written once they are flushed.

func IsLiveProperty

func IsLiveProperty(r map[string]string) bool

IsLiveProperty reports whether a property row is live: its _delete_time is 0 or null.

func IsNull

func IsNull(cell string) bool

IsNull reports whether a cell is the CSV null marker.

func Layouts

func Layouts(dir string) map[string]*csvfmt.Layout

Layouts computes the CSV layout of every group the artifact's schema holds, keyed "<catalog>/<group>", the way a data node does: resources sorted by name.

func LeaseFile

func LeaseFile(dataDir, catalog, id string) string

LeaseFile returns the .lease path of one catalog's copy of an export session.

func List

List runs ACTION_LIST and returns every frame.

func MeasuresOf

func MeasuresOf(dir, group string) []*databasev1.Measure

MeasuresOf returns the measures of a group from the artifact's schema, sorted by name.

func MustPlan

MustPlan is Plan asserting success and at least one frame.

func NewExportDir

func NewExportDir(root string) string

NewExportDir returns a path below root that does not exist yet.

func Plan

Plan runs one ExportService.Plan call and drains every frame it streams.

func PropertiesOf

func PropertiesOf(dir, group string) []*databasev1.Property

PropertiesOf returns the property schemas of a group from the artifact's schema, sorted by name.

func PropertyDocs

func PropertyDocs(frames []*transferv1.PlanResponse, group string) uint64

PropertyDocs adds up the documents the inventory reports for a property group, on every node.

func ReadLastHeartbeat

func ReadLastHeartbeat(path string) int64

ReadLastHeartbeat returns the lastHeartbeatAt stamp of a .lease file.

func ReadLease

func ReadLease(path string) export.Lease

ReadLease parses a data node's .lease file with the production reader.

func ReadRequest

func ReadRequest(id string) *transferv1.PlanRequest

ReadRequest builds the ReadSession PlanRequest that inventories (and renews) the existing session id.

func Release

func Release(conn *grpc.ClientConn, id string) []string

Release runs ACTION_RELEASE for id and returns the nodes whose frame carries the `error` outcome.

func ReleaseOutcome

func ReleaseOutcome(conn *grpc.ClientConn, id string) *exporter.ReleaseResult

ReleaseOutcome runs ACTION_RELEASE for id and returns every node's answer, sorted into the nodes that released it, the nodes that did not hold it and the failed ones.

func RequireNativePartNames

func RequireNativePartNames(t testing.TB, catalog commonv1.Catalog, partDir string, wire []queue.FileInfo, skipped ...string)

RequireNativePartNames pins nativefmt's disk-to-wire names of catalog's parts to the engine: every file of the part flushed at partDir must map to a name of wire, the files the engine's sync sender streams for it, or be skipped, and every name of wire must be mapped; each of skipped, a file the part may lack, must be skipped too. A renamed or new part file then fails the engine's tests instead of an import.

func RewriteLease

func RewriteLease(path string, mutate func(*export.Lease))

RewriteLease applies mutate to a .lease document and replaces the file atomically, so a data node reading it concurrently never sees a torn document.

func RowsByStageNode

func RowsByStageNode(frames []*transferv1.PlanResponse, catalog commonv1.Catalog, group string) map[string]map[string]uint64

RowsByStageNode sums the total_count of one catalog and group's shards per node stage ("" is the default stage) and node; nodes without rows are left out.

func RowsCount

func RowsCount(a *Artifact, catalog, group string) int

RowsCount counts the rows of one catalog and group across every node.

func Schemas

func Schemas[T proto.Message](dir, kind string, newMsg func() T) []T

Schemas decodes one schema/<kind>.jsonl file into messages created by newMsg.

func SessionDir

func SessionDir(dataDir, catalog, id string) string

SessionDir returns <dataDir>/<catalog>/export-snapshots/<id>, the directory a data node keeps one catalog's snapshot of an export session in.

func Sessions

Sessions runs one ExportService.Sessions call and drains every frame it streams: one per data node through a liaison, a single one straight from a data node.

func StableTree

func StableTree(root string) map[string]string

StableTree waits until two consecutive fingerprints of root agree and returns the last one.

func StreamsOf

func StreamsOf(dir, group string) []*databasev1.Stream

StreamsOf returns the streams of a group from the artifact's schema, sorted by name.

func Summary

func Summary(frames []*transferv1.PlanResponse) *transferv1.PlanSummary

Summary returns the final frame of a Plan stream, asserting it is the `summary` frame.

func TombstoneProperty

func TombstoneProperty() *propertyv1.Property

TombstoneProperty is the ui_menu property of group "sw" that WriteTombstone applies and deletes, so the property catalog holds a deleted document.

func TracesOf

func TracesOf(dir, group string) []*databasev1.Trace

TracesOf returns the traces of a group from the artifact's schema, sorted by name.

func TreeDiff

func TreeDiff(before, after map[string]string) []string

TreeDiff lists the files whose presence or content differ between two fingerprints.

func UnitFrames

func UnitFrames(frames []*transferv1.PlanResponse) []*transferv1.UnitFrame

UnitFrames keeps the `units` frames of a Plan stream, dropping the `created` and `summary` frames.

func WriteTombstone

func WriteTombstone(conn *grpc.ClientConn)

WriteTombstone applies TombstoneProperty and deletes it again.

Types

type Artifact

type Artifact struct {
	Manifest *manifest.Manifest
	Dir      string
	Files    []*CSVFile
}

Artifact is a decoded export output directory.

func ReadArtifact

func ReadArtifact(dir string, annotations bool) *Artifact

ReadArtifact reads manifest.json and decodes every CSV file below nodes/. annotations tells whether every file must start with the #datatype line before its header.

func (*Artifact) ExpectReplicasEqual

func (a *Artifact) ExpectReplicasEqual() int

ExpectReplicasEqual asserts that every shard listed by more than one source of a unit holds the same rows under each source, and returns how many such shards it compared. The delete time of a property tombstone is compared only for being set.

func (*Artifact) ExportedGroups

func (a *Artifact) ExportedGroups() []string

ExportedGroups lists the "<catalog>/<group>" keys that have at least one file.

func (*Artifact) FilesOf

func (a *Artifact) FilesOf(catalog, group string) []*CSVFile

FilesOf returns the files of one catalog and group, across nodes.

func (*Artifact) LatestProperties

func (a *Artifact) LatestProperties() map[string]map[string]string

LatestProperties returns the latest revision of every entity of the suites' property resource across nodes, keyed by _id: the row with the largest _mod_revision, a tombstone winning over a live row of the same revision. Older revisions are dropped.

func (*Artifact) LiveProperty

func (a *Artifact) LiveProperty() map[string]string

LiveProperty returns the latest revision of the first entity, by _id, of the suites' property resource whose latest revision is live and that is not the tombstone, or nil.

func (*Artifact) NodeDirs

func (a *Artifact) NodeDirs() []string

NodeDirs returns the directories below nodes/ that hold files.

func (*Artifact) RowsOf

func (a *Artifact) RowsOf(catalog, group, name string) map[string][]map[string]string

RowsOf returns the rows of one resource in one catalog and group, per node directory, keyed by header.

func (*Artifact) VerifyLayouts

func (a *Artifact) VerifyLayouts() map[string]*csvfmt.Layout

VerifyLayouts asserts that every file starts with its group's header and, when the artifact was written with annotations, with its #datatype line.

func (*Artifact) VerifyLiteralCells

func (a *Artifact) VerifyLiteralCells(d SuiteData, layouts map[string]*csvfmt.Layout)

VerifyLiteralCells cross-checks a few critical cells of the suite data against literal strings written by hand from the documented cell encoding, independently of the csvfmt encoders that both the data node and Expected use: a shared encoder bug would otherwise pass the cell-by-cell comparison. The suites write no float field and no int array, so those two encoders are pinned to literals directly.

func (*Artifact) VerifyManifest

func (a *Artifact) VerifyManifest()

VerifyManifest checks the manifest against the files on disk: the file sets are equal, every file has the announced bytes and CRC-32, the rowCounts of every shard and of every source's segment files are the rows its files hold and totalCount is their sum, the schema files exist and every source node has its directory.

func (*Artifact) VerifySuiteData

func (a *Artifact) VerifySuiteData(d SuiteData, perNode func(group string) bool)

VerifySuiteData asserts that the artifact holds exactly the rows the suites wrote, cell by cell, in the files their group's layout describes. perNode reports for a "<catalog>/<group>" whether every node directory holds all of the group's rows (its replicas cover every node); otherwise the rows are split across the node directories.

type CSVFile

type CSVFile struct {
	// Path is the artifact-relative slash path: nodes/<dir>/<catalog>/<group>/...
	Path    string
	NodeDir string
	Catalog string
	Group   string
	// Segment is the segment suffix; "" for property files.
	Segment string
	// Prefix is the path without the "-<seq>.csv[.gz]" tail, shared by the files one writer rolled.
	Prefix   string
	Header   []string
	Datatype []string
	Rows     [][]string
	Shard    int
	Seq      int
	// SegmentLevel marks the segment-<seq> file of index-mode measure rows.
	SegmentLevel bool
}

CSVFile is one decoded CSV file of an artifact.

func (*CSVFile) Row

func (f *CSVFile) Row(i int) map[string]string

Row returns the row i keyed by header.

type Expected

type Expected struct {
	// Rows maps the key to the expected row, keyed by header.
	Rows map[string]map[string]string
	// Key is the header whose cell identifies a row.
	Key string
	// Ignore lists headers whose cells are not predictable and are not compared.
	Ignore []string
}

Expected is the set of rows one resource must export, keyed by an identity column.

func ExpectedMeasure

func ExpectedMeasure(layout *csvfmt.Layout, measure *databasev1.Measure, file, keyTag string, base time.Time, interval time.Duration) Expected

ExpectedMeasure is what test/cases/measure/data.Write(conn, name, group, file, base, interval) wrote, laid out with layout; rows are keyed by keyTag ("family.tag"). _version is not compared.

func ExpectedProperty

func ExpectedProperty(layout *csvfmt.Layout, file string) Expected

ExpectedProperty is the property test/cases/property/data.WriteToGroup applied from file, laid out with layout; rows are keyed by _id. The revisions and _updated_at are not compared and _delete_time is expected to be 0.

func ExpectedStream

func ExpectedStream(layout *csvfmt.Layout, stream *databasev1.Stream, base time.Time, interval time.Duration) Expected

ExpectedStream is what test/cases/stream/data.WriteToGroup(conn, name, group, name, base, interval) wrote, laid out with layout; rows are keyed by _element_id.

func ExpectedTrace

func ExpectedTrace(layout *csvfmt.Layout, trace *databasev1.Trace, base time.Time, interval time.Duration) Expected

ExpectedTrace is what test/cases/trace/data.WriteToGroup(conn, name, group, name, base, interval) wrote, laid out with layout; rows are keyed by _span.

func (Expected) Add

func (e Expected) Add(layout *csvfmt.Layout, p *propertyv1.Property, deleteTime int64)

Add expects one more property row with the given delete time.

func (Expected) Match

func (e Expected) Match(got []map[string]string, desc string)

Match asserts that got holds exactly the expected rows, cell by cell.

type ExportRun

type ExportRun struct {
	Err error
	// Log is what the exporter printed to its log writer (stderr for bydbctl).
	Log string
	Out string
}

ExportRun is the outcome of one RunExport call.

func RunExport

func RunExport(ctx context.Context, addr string, opts config.Export, hook func(line string), moreAddrs ...string) ExportRun

RunExport connects to the liaisons at addrs the way bydbctl does (Preflight, FetchGroups) and runs exporter.RunExport with opts. hook, when not nil, sees every line of the log and of the output as it is printed, on the printing goroutine.

func (ExportRun) ExitCode

func (r ExportRun) ExitCode() int

ExitCode is the process exit code bydbctl would return: 0 on success.

func (ExportRun) SessionID

func (r ExportRun) SessionID() string

SessionID returns the session id the run announced, or "".

type ImportRun

type ImportRun struct {
	Err    error
	Result *importer.Result
	// Log is what the importer printed to its log writer (stderr for bydbctl); Out is the plan.
	Log string
	Out string
}

ImportRun is the outcome of one RunImport call.

func RunImport

func RunImport(ctx context.Context, addr string, opts config.Import, hook func(event string)) ImportRun

RunImport connects to the liaison at addr the way bydbctl does (Preflight) and runs importer.RunImport with opts. hook, when not nil, sees every line of the log and of the output as it is printed, and every acknowledged batch as "batch <work item> seq=<n> rows=<r>" right after its acknowledgement, on the pushing goroutine, so a test can stop a node in the middle of an import.

func RunImportAt

func RunImportAt(ctx context.Context, addr string, opts config.Import, now func() time.Time, hook func(event string)) ImportRun

RunImportAt is RunImport with now as the reference time of the TTL gate (nil for time.Now), so that a spec can import as if later, when the target TTL refuses the artifact's rows.

func (ImportRun) ExitCode

func (r ImportRun) ExitCode() int

ExitCode is the process exit code bydbctl would return: 0 on success.

type NativeArtifact

type NativeArtifact struct {
	Manifest *manifest.Manifest
	// Containers maps the path prefix of every container, relative to the artifact, to its
	// volume paths in order.
	Containers map[string][]string
	Dir        string
	// Plain lists the files that are not containers, such as segment metadata files.
	Plain []string
}

NativeArtifact is a native artifact read back from disk.

func ReadNativeArtifact

func ReadNativeArtifact(dir string) *NativeArtifact

ReadNativeArtifact reads the manifest of a native artifact and checks it against the files on disk: importer.OpenArtifact must accept it with every data file verified, the artifact must be uncompressed native, the manifest must list exactly the data files on disk, and every shard container must hold no orphan file.

func (*NativeArtifact) Open

func (a *NativeArtifact) Open(prefix string) *bnc.VolumeSet

Open opens the volumes of the container at prefix as one volume set.

type SuiteData

type SuiteData struct {
	StreamBase  time.Time
	MeasureBase time.Time
	TraceBase   time.Time
	Interval    time.Duration
}

SuiteData is when and how densely the suites wrote their data.

func WriteSuiteData

func WriteSuiteData(conn *grpc.ClientConn) SuiteData

WriteSuiteData writes the data the export and import suites share (test/cases/<catalog>/data): the stream, the measure, the index-mode measure, the Top-N source measure, the trace, the properties and the tombstone. It returns the base times the data was written with.

Directories

Path Synopsis
Package progress counts what the tests assert on in the progress files of a data export and a data import, read the way the exporter and the importer read them.
Package progress counts what the tests assert on in the progress files of a data export and a data import, read the way the exporter and the importer read them.
Package topncheck asserts the Top-N results of a CSV export.
Package topncheck asserts the Top-N results of a CSV export.

Jump to

Keyboard shortcuts

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