reverse

package
v0.13.0 Latest Latest
Warning

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

Go to latest
Published: Nov 8, 2026 License: Apache-2.0 Imports: 24 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 reverse carries this cluster's own subtrees and blocks back into the fabric.

The cluster tells us what it accepted through the blockchain service's notification stream. That stream does not say where an object came from (the node's own p2p announces every notification to its gossip peers for exactly the same reason), so the origin filter is ours: anything the bridge previously delivered *into* the cluster is registered, and a notification for a registered hash is remote in origin and must not be pushed back up. What remains is what this cluster produced.

One consequence is worth stating plainly: content this node learned over libp2p while the tunnel was down looks unseen and will be pushed up after recovery. That duplicate is bounded by the outage and harmless (every receiver dedups by hash); the clean fix would be an origin marker on the notification, which Teranode does not provide (docs/architecture.md, Known upstream limitations).

Index

Constants

View Source
const (
	DefaultKeepaliveTime    = 30 * time.Second
	DefaultKeepaliveTimeout = 20 * time.Second

	// MinKeepaliveTime is grpc-go's own floor on the client ping interval
	// (internal.KeepaliveMinPingTime). grpc.WithKeepaliveParams SILENTLY raises
	// anything below it and logs a warning through grpc's logger, so a bridge
	// configured with -blockchain-keepalive 5s would not ping at 5s and the only
	// evidence would be a stray line from a library. Clamp here instead, where
	// the bridge can say so in its own log.
	MinKeepaliveTime = 10 * time.Second
)

Keepalive defaults, matching what teranode/util/grpc_helper.go gives every client (grpc_keepalive_time_seconds / grpc_keepalive_timeout_seconds).

Variables

This section is empty.

Functions

This section is empty.

Types

type Builder

type Builder interface {
	BuildSubtree(ctx context.Context, hash hashid.Hash) (frame []byte, ok bool, err error)
	BuildBlock(ctx context.Context, hash hashid.Hash) (frame []byte, ok bool, err error)
}

Builder turns an accepted object into the push frame for its class. It returns ok=false when the object should be skipped without being an error (for example a block whose parts are not all available yet).

type Config

type Config struct {
	// BlockchainAddr is host:port of the blockchain service's gRPC listener.
	BlockchainAddr string
	// Source identifies this subscriber to the cluster.
	Source string
	// Subtrees and Blocks are the up-tunnel publishers for each class. A nil
	// publisher disables that class.
	Subtrees, Blocks Publisher
	// Published, if set, receives every frame we publish, so the echo that comes
	// back down our own delivery lanes can be verified against it.
	Published Store

	// Ready, when set, gates publishing: the submitter only publishes while it
	// returns true.
	//
	// This exists because the origin filter is only as good as our view of the
	// object plane. A freshly started bridge has an EMPTY registry, so every
	// notification looks unseen, which reads as "locally produced", and the
	// cluster re-emits notifications for objects it already holds. The mine tag
	// covers blocks, but subtrees have no marker of their own beyond the block
	// that names them, so publishing while blind means republishing other
	// clusters' subtrees under our identity. Refusing to publish until delivery
	// is actually flowing costs nothing real: anything genuinely ours that is
	// missed here is still in the cluster and is re-announced by its own p2p.
	Ready func() bool

	// MineTag, when non-empty, is the local cluster's coinbase_arbitrary_text
	// (e.g. "/teranode1/"). Block notifications whose coinbase does not carry
	// it are treated as REMOTE in origin and skipped, closing the race the
	// seen-registry cannot: a block this cluster learned over libp2p before
	// the fabric delivered it looks unseen and would otherwise be republished
	// upward with false attribution. The check is stateless (derived from
	// block content), so it also survives bridge restarts, which wipe the
	// registry. Subtrees carry no coinbase and need no equivalent: their
	// notification has exactly one producer, local block assembly.
	MineTag []byte

	// GRPCMetrics, when set, instruments the blockchain connection with the
	// standard gRPC client metrics, the same provider Teranode uses.
	GRPCMetrics *grpcprom.ClientMetrics

	// ClusterPoll is how often to read the cluster's FSM state and tip height
	// over the blockchain connection. Zero disables the poll.
	ClusterPoll time.Duration

	// TLS mirrors Teranode's security_level_grpc and its certificate paths.
	// Level 0 (plaintext) is upstream's default; a cluster running any other
	// level cannot be reached at all by a plaintext dial. See dial.go.
	TLS TLSConfig

	// KeepaliveTime and KeepaliveTimeout set the client keepalive policy.
	// Zero picks upstream's client defaults (30s / 20s). KeepaliveTime must be
	// at least the server's grpc_server_min_ping_time_seconds or the server
	// answers GOAWAY too_many_pings.
	KeepaliveTime, KeepaliveTimeout time.Duration

	// PermitWithoutStream allows pings while no stream is open, matching
	// upstream's grpc_permit_without_stream default.
	PermitWithoutStream bool

	// APIKey is the cluster's grpc_admin_api_key, sent as x-api-key metadata
	// on every call. Teranode v0.16.1 and later require it on every blockchain
	// gRPC method but Health, from external clients as from its own services.
	// Empty sends no key, which an older cluster expects.
	APIKey string
}

Config points the subscriber at the cluster.

type PromoterConfig

type PromoterConfig struct {
	// ProbeURL is the PRIMARY bridge's /readyz. Configure this on the STANDBY
	// only: a configured primary never probes anyone and never auto-demotes.
	ProbeURL string
	// Interval between probes.
	Interval time.Duration
	// FailN consecutive failed probes promote the standby.
	FailN int
	// OKN consecutive healthy probes demote it again. Demotion is deliberately
	// slower than promotion: a flapping primary must not flap the role, and a
	// transient dual-publish is harmless (every receiver dedups by hash, the
	// failure model's "no corruption, just a gap" cuts both ways).
	OKN int
	// Probe overrides the HTTP check (tests). Nil uses a GET on ProbeURL.
	Probe func(ctx context.Context) bool
}

PromoterConfig tunes health-gated submitter failover.

type Publisher

type Publisher interface {
	Send(ctx context.Context, obj []byte) error
}

Publisher sends an encoded frame up the tunnel.

Publisher, Store and Builder are the reverse path's extension seams: an importing module supplies its own transport, published-frame record, or object builder without forking the subscriber loop.

type Stats

type Stats struct {
	SubtreesUp, BlocksUp, RemoteSkipped, Skipped, Failures, Reconnects uint64
	Gated                                                              uint64
	// ForeignSkipped counts block notifications whose coinbase carried another
	// cluster's tag, gossip-learned blocks correctly not republished.
	ForeignSkipped uint64
	// StandbyHeld counts publishes withheld because this bridge does not hold
	// the submitter role.
	StandbyHeld uint64
	// Active reports whether the submitter role is currently held.
	Active bool
}

Stats is a snapshot for logging and metrics.

type Store

type Store interface {
	Put(hash hashid.Hash, class string, body []byte)
}

Store records a published frame so the copy that returns down the delivery lanes can be byte-compared against what we actually sent.

type Subscriber

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

Subscriber watches the cluster and republishes what it produces.

func New

func New(cfg Config, seen *registry.Registry, build Builder, log *slog.Logger) (*Subscriber, error)

New dials the blockchain service.

Transport security follows Teranode's own security_level_grpc. From Teranode v0.16.1 the blockchain service also requires its grpc_admin_api_key on every method but Health (util.requiredAuthInterceptors); Config.APIKey carries it. Without it the Subscribe stream is refused Unauthenticated and the reverse path retries forever while delivery keeps working.

func (*Subscriber) Active

func (s *Subscriber) Active() bool

Active reports whether this subscriber currently publishes.

func (*Subscriber) Close

func (s *Subscriber) Close() error

Close drops the gRPC connection to the blockchain service.

func (*Subscriber) ClusterState

func (s *Subscriber) ClusterState() (state string, height uint64)

ClusterState is the last successfully read cluster state, for the health endpoint and the stats line. state is empty when nothing has been read yet.

func (*Subscriber) Run

func (s *Subscriber) Run(ctx context.Context) error

Run subscribes and republishes until ctx is cancelled, reconnecting on stream loss. The cluster restarts and rolls its gRPC connections periodically, so a dropped stream is routine rather than exceptional.

func (*Subscriber) RunClusterState

func (s *Subscriber) RunClusterState(ctx context.Context, every time.Duration, log *slog.Logger)

RunClusterState polls the cluster's FSM state and tip height over the blockchain connection the reverse path already holds, and publishes both as gauges.

Why the bridge reads state it does not act on

The bridge announces and submits identically whether the cluster is RUNNING, IDLE or CATCHINGBLOCKS. That is deliberate, the cluster is unmodified and decides for itself what to do with an announcement, but it means the most common degraded case has no visible cause from the bridge's own metrics: announcements succeed, pulls never follow, and every bridge counter looks healthy. Publishing the state the cluster reports turns that from a mystery into a reading, and it is also what the health endpoint reports as a dependency, mirroring how Teranode's own services treat FSM state (teranode/services/blockchain/fsm.go, CheckFSM).

Deliberately advisory: this never gates publishing. A bridge that stopped announcing while its cluster caught up would starve the very cluster it is meant to feed.

func (*Subscriber) RunPromoter

func (s *Subscriber) RunPromoter(ctx context.Context, cfg PromoterConfig, log *slog.Logger)

RunPromoter watches the primary and flips this subscriber's submitter role: FailN consecutive probe failures promote, OKN consecutive successes demote. It runs until ctx is cancelled. The worst case is bounded and benign in both directions, a dead primary costs FailN×Interval of publish gap (the failure model's existing "gap until promoted", now measured in seconds instead of an operator's pager), and a false promotion costs a window of dual-publish that hash dedup absorbs.

func (*Subscriber) SetActive

func (s *Subscriber) SetActive(v bool)

SetActive flips whether this subscriber holds the submitter role. A standby keeps its subscription, registry and origin filter warm (promotion is a flag flip, not a cold start) but publishes nothing while inactive.

func (*Subscriber) Stats

func (s *Subscriber) Stats() Stats

Stats returns a snapshot of the reverse path's counters.

type TLSConfig

type TLSConfig struct {
	SecurityLevel                 int
	CertFile, KeyFile, CACertFile string
}

TLSConfig selects the transport security for the blockchain connection, mirroring Teranode's security_level_grpc and its certificate paths.

Jump to

Keyboard shortcuts

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