queue

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: 29 Imported by: 1 module, 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 queue implements the data transmission queue.

Index

Constants

View Source
const (
	// OutcomeDeliveryFailed is a delivery that failed and is not retried. Outcome.Err holds the error.
	OutcomeDeliveryFailed = "delivery_failed"
	// OutcomeRetriesExhausted is a retryable failure that persisted past the retry limit.
	OutcomeRetriesExhausted = "retries_exhausted"
	// OutcomeShutdownDeadline is a request still held, or still in a delivery, when Close's drain deadline passed.
	OutcomeShutdownDeadline = "shutdown_deadline"
)

The reasons an accepted request was not delivered.

View Source
const DefaultReceiveMemWaitTimeout = 5 * time.Minute

DefaultReceiveMemWaitTimeout bounds how long a chunked sync receiver waits for memory to recover before it answers SERVER_BUSY.

View Source
const DefaultScanPrefetch = 2

DefaultScanPrefetch is the default depth of a node stream's chunk buffer.

View Source
const PartTypeCore = "core"

PartTypeCore is the PartInfo.part_type of a core part on the chunked sync wire.

Variables

View Source
var ErrNoNodeLocated = errors.New("no node located for the batch")

ErrNoNodeLocated is the delivery failure of a batch that no node was located for: the locate failed, or it returned no node. Its cause, if any, is wrapped with it.

View Source
var ErrNotImplemented = errors.New("not implemented")

ErrNotImplemented is returned by Client implementations that have no peers to dial — notably the standalone local pipeline. Callers (e.g. the cluster barrier fan-out) treat this sentinel as "no peer to probe; skip" rather than as a hard failure, so the standalone path degrades to in-process self-probing without a special-cased branch in the caller.

View Source
var ErrRetryable = errors.New("retryable delivery failure")

ErrRetryable marks a delivery error that is worth retrying, such as a destination that is not ready yet. Any other error ends the request.

View Source
var ErrScanIdleTimeout = errors.New("scan stream idle timeout")

ErrScanIdleTimeout is the terminal error of a node stream that went silent.

View Source
var ErrServerBusy = errors.New("receiver under memory pressure")

ErrServerBusy signals the receiver is under memory pressure and the sender should back off and retry the whole part.

View Source
var ErrStreamClosed = errors.New("node stream closed")

ErrStreamClosed is returned by NodeStream.Next after the stream was closed by its owner.

Functions

func CheckSyncVersion added in v0.12.0

func CheckSyncVersion(info *clusterv1.VersionInfo) (clusterv1.SyncStatus, string)

CheckSyncVersion is the version check of a chunked sync receiver: a frame without version info is accepted, otherwise the API version must match and the file format version must be the current or a compatible one. It returns SYNC_STATUS_CHUNK_RECEIVED when the frame may be read, and the refusing status with its reason otherwise. The data node receiver and the in-process one share it.

func ChunkChecksum added in v0.12.0

func ChunkChecksum(data []byte) string

ChunkChecksum returns the checksum a chunked sync frame carries for its chunk data: the lowercase hexadecimal CRC-32 (IEEE) of data.

func ChunkChecksumMismatch added in v0.12.0

func ChunkChecksumMismatch(req *clusterv1.SyncPartRequest) string

ChunkChecksumMismatch returns the refusal message of a frame whose chunk data does not match its checksum, or "" when they match. The sender recognizes the refusal by its "checksum mismatch" text.

func ClearChunkedSyncFailureInjector added in v0.9.0

func ClearChunkedSyncFailureInjector()

ClearChunkedSyncFailureInjector removes the registered failure injector.

func FillPartContext added in v0.11.3

func FillPartContext(c *ChunkedSyncPartContext, info *clusterv1.PartInfo)

FillPartContext copies the description of a part from the sync protocol into c.

func FinishPart added in v0.11.3

func FinishPart(c *ChunkedSyncPartContext) error

FinishPart finishes the part c holds, if any, and drops its handler.

func RegisterChunkedSyncFailureInjector added in v0.9.0

func RegisterChunkedSyncFailureInjector(injector ChunkedSyncFailureInjector)

RegisterChunkedSyncFailureInjector registers a failure injector for testing.

func Retryable added in v0.12.0

func Retryable(err error) error

Retryable marks err as retryable. errors.Is still finds err in the result.

func SyncVersionInfo added in v0.12.0

func SyncVersionInfo(fileFormatVersion string) *clusterv1.VersionInfo

SyncVersionInfo is the version info a chunked sync sender puts on its frames: this binary's API version and compatible file format versions, with the file format version of the data sent, which is the sender's own unless it relays data written elsewhere.

Types

type Admission added in v0.12.0

type Admission uint8

Admission is the decision Offer made, taken at the moment it made it.

const (
	// Accepted means the publisher owns the request until it calls Release.
	Accepted Admission = iota
	// RefusedPressure means the memory pressure check reported high pressure.
	RefusedPressure
	// RefusedFull means the allowance had no room for the request.
	RefusedFull
	// RefusedClosed means Close had already started.
	RefusedClosed
)

func (Admission) String added in v0.12.0

func (a Admission) String() string

type BatchPublisher added in v0.5.0

type BatchPublisher interface {
	bus.Publisher
	Close() (map[string]*common.Error, error)
}

BatchPublisher is the interface for publishing data in batch.

type BufferedConfig added in v0.12.0

type BufferedConfig struct {
	// Pressure reports high memory pressure. It runs on every Offer, so it must
	// not block. Nil means never.
	Pressure func() bool
	// Logger reports a panic of the delivery goroutine itself.
	Logger *logger.Logger
	// Name names the delivery goroutine.
	Name string
	// MaxBytes is the allowance: the bytes held, queued or in a delivery.
	MaxBytes int64
	// MaxCount bounds the number of requests held before delivery takes them.
	MaxCount int
	// BatchCount closes a batch at this many requests.
	BatchCount int
	// BatchBytes closes a batch at this many bytes. Zero means MaxBytes/4.
	BatchBytes int64
	// FlushInterval closes a batch that has not filled, and paces retries.
	FlushInterval time.Duration
	// MaxRetries bounds the retries of one request after its first attempt.
	MaxRetries int
	// DrainTimeout bounds Close.
	DrainTimeout time.Duration
}

BufferedConfig bounds a BufferedPublisher.

type BufferedPublisher added in v0.12.0

type BufferedPublisher interface {
	// Offer accepts or refuses req without waiting for storage, the network
	// or free capacity, and reports the decision it made. On Accepted the
	// publisher owns req until it calls req.Release. On any refusal the caller
	// keeps req.
	Offer(req *BufferedRequest) Admission
	// Start begins delivery. Requests accepted before it are held, within the
	// same allowance. Only the first call has an effect, and none after Close.
	Start(d Delivery)
	// Close stops admission, drains within the drain timeout and returns even
	// when a delivery is stuck.
	Close()
	// Bytes reports the bytes charged against the allowance, and the part of
	// them in a delivery.
	Bytes() (charged, inFlight int64)
}

BufferedPublisher accepts requests without waiting and delivers them in batches on its own goroutine.

It owns the whole buffering lifecycle: admission, byte accounting, batching, bounded retries and the shutdown drain. Only the Delivery differs between a local and a remote destination. BatchPublisher and its callers are unrelated.

func NewBufferedPublisher added in v0.12.0

func NewBufferedPublisher(ctx context.Context, cfg BufferedConfig) BufferedPublisher

NewBufferedPublisher returns a publisher that holds requests until Start. Every Deliver runs under ctx, so a value it carries, such as a mark for the logging the destination does, reaches the delivery goroutine.

type BufferedRequest added in v0.12.0

type BufferedRequest struct {
	// Data is the message body handed to Delivery.
	Data any
	// Done settles the accounting: exactly once, by the drain deadline at the
	// latest. For a stuck delivery it runs while Deliver may still read and
	// write the request, so it must read only what is safe to share with it.
	Done func(Outcome)
	// Release frees the request: exactly once, after Done has returned, when
	// neither Deliver nor Close can still read it.
	Release func()
	// Bytes is what the request holds, charged against the allowance until Release.
	Bytes int64
	// contains filtered or unexported fields
}

BufferedRequest is one request offered to a BufferedPublisher. A caller may pool requests: once Release runs, the publisher no longer reads it.

type ChunkedSyncClient added in v0.9.0

type ChunkedSyncClient interface {
	// SyncStreamingParts sends streaming parts using chunked transfer.
	SyncStreamingParts(ctx context.Context, parts []StreamingPartData) (*SyncResult, error)
	// Close releases resources associated with the client.
	Close() error
}

ChunkedSyncClient provides methods for chunked data synchronization with streaming support.

type ChunkedSyncFailureInjector added in v0.9.0

type ChunkedSyncFailureInjector interface {
	// BeforeSync returns whether the current SyncStreamingParts invocation should
	// short-circuit. The returned slice provides the failed parts that should be
	// reported back to the caller when a failure is injected.
	BeforeSync(parts []StreamingPartData) (bool, []FailedPart, error)
}

ChunkedSyncFailureInjector allows tests to deterministically inject failures into chunked sync operations. It is only intended for test code.

func GetChunkedSyncFailureInjector added in v0.9.0

func GetChunkedSyncFailureInjector() ChunkedSyncFailureInjector

GetChunkedSyncFailureInjector returns the currently registered failure injector.

type ChunkedSyncHandler added in v0.9.0

type ChunkedSyncHandler interface {
	// HandleFileChunk processes incoming file chunks as they arrive.
	// This method is called for each chunk of file data to enable streaming processing.
	HandleFileChunk(ctx *ChunkedSyncPartContext, chunk []byte) error

	// CreatePartHandler creates a new part handler for the given context.
	CreatePartHandler(ctx *ChunkedSyncPartContext) (PartHandler, error)
}

ChunkedSyncHandler handles incoming chunked sync requests on the server side.

type ChunkedSyncPartContext added in v0.9.0

type ChunkedSyncPartContext struct {
	Handler PartHandler
	// Context carries the gRPC stream context for receive-side cancellation
	// (memory wait upper bound / disconnect).
	Context               context.Context
	Group                 string
	FileName              string
	PartType              string
	ID                    uint64
	CompressedSizeBytes   uint64
	UncompressedSizeBytes uint64
	TotalCount            uint64
	BlocksCount           uint64
	MinTimestamp          int64
	MaxTimestamp          int64
	MinKey                int64
	MaxKey                int64
	ShardID               uint32
}

ChunkedSyncPartContext represents the context for a chunked sync operation.

func SwitchPart added in v0.11.3

SwitchPart returns the context of the part info describes, the one chunked sync receiver step shared by the cluster receiver and the in-process relay. A frame continuing the open part cur returns cur, telling its handler about a new part type when the type changes; a frame starting another part finishes cur into pending (see PendingParts.Finish) and creates the new part's handler. On an error the returned context is the one to close: cur when it could not be finished, the new one when its handler could not be created.

func (*ChunkedSyncPartContext) Close added in v0.9.0

func (c *ChunkedSyncPartContext) Close() error

Close releases resources associated with the context.

func (*ChunkedSyncPartContext) RetrieveContext added in v0.11.0

func (c *ChunkedSyncPartContext) RetrieveContext() context.Context

RetrieveContext returns the part's stream context, or context.Background() if none was set. Used by receive handlers to bound memory-pressure waits.

type Client added in v0.5.0

type Client interface {
	run.Unit
	bus.Publisher
	bus.Broadcaster
	route.TableProvider
	// Scatterer opens one Scan stream per node that matches the message's node
	// selectors, as Broadcast does, and returns the streams without reading them.
	bus.Scatterer
	// NewBatchPublisher creates a batch publisher whose timeout starts when Close seals the batch.
	NewBatchPublisher(timeout time.Duration) BatchPublisher
	NewChunkedSyncClient(node string, chunkSize uint32) (ChunkedSyncClient, error)
	// SetSelfNode stamps the publisher's own node identity onto the wire
	// (SenderNode / SenderRole / SenderTier on every SendRequest) and onto
	// the banyandb_lifecycle_migration_* metric labels. Pass "" for any
	// dimension the caller doesn't know (e.g. the lifecycle has no Role
	// enum entry; the tier is untracked when the co-located data node's
	// tier isn't known at boot time).
	SetSelfNode(name, role, tier string)
	// NewNodeSchemaStatusClient returns a client for the cluster.v1
	// NodeSchemaStatusService against the named node, sharing the underlying
	// *grpc.ClientConn from this queue client's existing connection pool.
	// The standalone local pipeline returns ErrNotImplemented so callers can
	// treat it as "no peer to probe" without a type-switch.
	NewNodeSchemaStatusClient(node string) (clusterv1.NodeSchemaStatusServiceClient, error)
	// NewExportClient borrows the pooled connection to node and wraps it as an
	// transferv1.ExportServiceClient so the liaison can fan Plan/Sessions out
	// without dialing. The standalone local pipeline answers with an in-process
	// client of the ExportService registered through SetExportServer.
	NewExportClient(node string) (transferv1.ExportServiceClient, error)
	// NewChunkedSyncRelayClient returns a raw cluster.v1 ChunkedSyncService client of the
	// named node, sharing the pooled connection, so a relay can forward chunk frames it did not
	// read from disk. The standalone local pipeline answers with an in-process client that
	// feeds the chunked sync handlers registered on it.
	NewChunkedSyncRelayClient(node string) (clusterv1.ChunkedSyncServiceClient, error)
	Register(bus.Topic, schema.EventHandler)
	OnAddOrUpdate(md schema.Metadata)
	GracefulStop()
	HealthyNodes() []string
}

Client is the interface for publishing data to the queue.

type Delivery added in v0.12.0

type Delivery interface {
	// Deliver writes one batch and reports whether the destination took it. A
	// failure wrapped with Retryable is retried; any other ends the batch. It
	// must not keep batch after it returns.
	Deliver(ctx context.Context, batch []any) error
}

Delivery writes batches to a destination.

func NewLocalDelivery added in v0.12.0

func NewLocalDelivery(client Client, topic bus.Topic, timeout time.Duration) Delivery

NewLocalDelivery returns the Delivery that publishes each batch to topic through client's batch publisher, one message per request. A topic with no subscriber yet is a retryable failure: on the local pipeline it is a service that has not started.

func NewNodeDelivery added in v0.12.0

func NewNodeDelivery(client Client, topic bus.Topic, node func() (string, error), timeout time.Duration) Delivery

NewNodeDelivery returns the same Delivery for a client that reaches other nodes: each batch goes to the node that node returns when the batch is delivered. A failed locate is retryable, because nothing was published; once a batch is published, its outcome is final.

type FailedPart added in v0.9.0

type FailedPart struct {
	PartID string
	Error  string
}

FailedPart contains information about a part that failed to sync.

type FileData added in v0.9.0

type FileData struct {
	FileName string
	Data     []byte
}

FileData represents file data with name and content.

type FileInfo added in v0.9.0

type FileInfo struct {
	Reader fs.SeqReader
	Name   string
}

FileInfo represents information about an individual file within a part.

type NodeStream added in v0.12.0

type NodeStream = bus.NodeStream

NodeStream is one node's chunk sequence; see bus.NodeStream.

type Outcome added in v0.12.0

type Outcome struct {
	// Err is the last delivery error, when there was one.
	Err error
	// Reason is why the request was not delivered: one of the Outcome* reasons.
	Reason string
	// Delivered is set only for a completed delivery. Acceptance never counts as written.
	Delivered bool
}

Outcome is how an accepted request ended.

type PartHandler added in v0.9.0

type PartHandler interface {
	NewPartType(ctx *ChunkedSyncPartContext) error
	FinishSync() error
	Close() error
}

PartHandler handles individual parts during sync operations.

type PartSealer added in v0.11.3

type PartSealer interface {
	// SealSync writes what remains of the part, as FinishSync does, without introducing it.
	// FinishSync of a sealed part only introduces it; Close of a sealed part removes it.
	SealSync() error
}

PartSealer is a PartHandler whose part can be completed on disk without being introduced. A chunked sync session seals every part it finishes before the sender's completion arrives, so a session that fails midway leaves none of its parts in the receiver: the sender resends every part of a failed session, and parts introduced before the failure would be stored twice.

type PendingParts added in v0.11.3

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

PendingParts holds the parts of a chunked sync session that are sealed but not introduced yet. A nil PendingParts finishes every part at once.

func (*PendingParts) Commit added in v0.11.3

Commit completes the session: it finishes the open part c into p, then introduces every part p holds in the order they were finished.

When c cannot be sealed, Commit returns the error at once and introduces nothing: c and every part p holds are left for the caller to Discard. When a held part cannot be introduced, the parts before it stay introduced, that part and every part after it are discarded, and the error is returned.

func (*PendingParts) Discard added in v0.11.3

func (p *PendingParts) Discard(c *ChunkedSyncPartContext) error

Discard abandons the session: it closes the open part c, if any, and removes every part p holds, so none of them is introduced. It is the counterpart of Commit, and every path that ends a session without its completion calls it once with the session's open part. It returns the errors the parts reported while closing.

func (*PendingParts) Finish added in v0.11.3

Finish finishes the part c holds, if any, and drops it from c. A part whose handler is a PartSealer is sealed and kept until Commit or Discard; any other part is finished at once.

type Queue

type Queue interface {
	Client
	Server
	run.Service
}

Queue builds a data transmission tunnel between subscribers and publishers.

func Local added in v0.5.0

func Local() Queue

Local return a new local Queue.

type ScatterOptions added in v0.12.0

type ScatterOptions = bus.ScatterOptions

ScatterOptions tunes the node streams opened by Client.Scatter.

type Server added in v0.5.0

type Server interface {
	run.Unit
	bus.Subscriber
	// SubscribeStream registers the listener that serves Scan calls for the topic.
	SubscribeStream(topic bus.Topic, listener bus.StreamListener) error
	RegisterChunkedSyncHandler(topic bus.Topic, handler ChunkedSyncHandler)
	GetPort() *uint32
	SetRouteProviders(providers map[string]route.TableProvider)
	// SetMetadataRepo enables fodc.v1.GroupLifecycleService — liaison-only
	// by design; data-node processes must not call it.
	SetMetadataRepo(repo metadata.Repo)
	// SetNodeSchemaStatusRepo enables cluster.v1.NodeSchemaStatusService —
	// per-node by design (reports the local schema cache); liaison and
	// data-node processes both call it.
	SetNodeSchemaStatusRepo(svc metadata.Service)
	// SetExportServer enables transfer.v1.ExportService on the data-node gRPC server.
	// The planner is served as-is; the liaison stamps node identity on its frames.
	// The standalone local pipeline keeps it for NewExportClient.
	SetExportServer(srv transferv1.ExportServiceServer)
}

Server is the interface for receiving data from the queue.

type StreamingPartData added in v0.9.0

type StreamingPartData struct {
	Group                 string
	Topic                 string
	PartType              string
	Files                 []FileInfo
	ID                    uint64
	CompressedSizeBytes   uint64
	UncompressedSizeBytes uint64
	TotalCount            uint64
	BlocksCount           uint64
	MinTimestamp          int64
	MaxTimestamp          int64
	MinKey                int64
	MaxKey                int64
	ShardID               uint32
}

StreamingPartData represents streaming part data for syncing.

type SyncMetadata added in v0.9.0

type SyncMetadata = clusterv1.SyncMetadata

SyncMetadata is an alias for clusterv1.SyncMetadata.

type SyncResult added in v0.9.0

type SyncResult struct {
	SessionID   string
	FailedParts []FailedPart
	TotalBytes  uint64
	DurationMs  int64
	ChunksCount uint32
	PartsCount  uint32
	Success     bool
}

SyncResult represents the result of a sync operation.

Directories

Path Synopsis
Package pub implements the queue client.
Package pub implements the queue client.
Package sub implements the queue server.
Package sub implements the queue server.

Jump to

Keyboard shortcuts

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