relaycore

package
v1.0.1 Latest Latest
Warning

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

Go to latest
Published: Jun 2, 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

Index

Constants

View Source
const (
	CacheMaxCost     = 20000 // each item cost would be 1
	CacheNumCounters = 20000 // expect 2000 items
	EntryTTL         = 5 * time.Minute
	// ResetTombstoneWindow drops SetSeenBlockFromKey writes that land within
	// this window after a ResetState. A relay response can travel through the
	// relay-processor pipeline for several milliseconds between when its
	// blockSeen was determined and when it reaches the consistency cache; if
	// /debug/reset-* fires in that window, the late-arriving write would
	// re-poison the just-cleared store. 100 ms is long enough to absorb a
	// pipeline's worth of in-flight responses and short enough that operators
	// triggering reset won't notice the brief write-blocked period.
	ResetTombstoneWindow = 100 * time.Millisecond
)
View Source
const (
	MaxCallsPerRelay = 50
)

Variables

View Source
var DisableBatchRequestRetry = true

DisableBatchRequestRetry prevents batch requests from being retried when set to true. Batch requests (JSON-RPC batches) cannot be hashed for caching, so retries may be unnecessary. This is controlled via the --disable-batch-request-retry flag. Disabled by default (true) because batch retries can cause issues with stateful operations.

View Source
var RelayRetryLimit = 2

Functions

func ShouldSkipConsistencyValidation

func ShouldSkipConsistencyValidation(requestedBlock int64) bool

ShouldSkipConsistencyValidation returns true when consistency validation should not be applied to the request. Validation is skipped for: - NOT_APPLICABLE requests (no block parsing) - Historical block requests (specific block number > 0) - Special block tags (EARLIEST, FINALIZED, SAFE, PENDING)

Validation is only applied for LATEST_BLOCK requests where we expect the most recent state.

func UpgradeToArchiveIfNeeded

func UpgradeToArchiveIfNeeded(ctx context.Context, protocolMessage chainlib.ProtocolMessage, archiveStatus *ArchiveStatus, relayParser RelayParserInf, cache RetryHashCacheInf, numberOfRetriesLaunched int, numberOfNodeErrors uint64) chainlib.ProtocolMessage

UpgradeToArchiveIfNeeded manages the archive extension lifecycle based on retry count. On first retry (attempt #1): adds archive extension. On second retry (attempt #2): removes archive extension if previously upgraded. If upgraded and 2+ node errors: caches hashes and returns original message (archive failed).

func ValidateEndpointCapability

func ValidateEndpointCapability(
	endpointLatestBlock int64,
	seenBlock int64,
	requestedBlock int64,
	config *ConsistencyValidationConfig,
) error

ValidateEndpointCapability checks if an endpoint can serve a request based on its current latest block compared to the user's seen block. This is the pre-request validation used for endpoint selection/prioritization.

Parameters:

  • endpointLatestBlock: The endpoint's tracked latest block
  • seenBlock: The previously seen block for this user
  • requestedBlock: The block requested in the original request
  • config: Validation configuration with thresholds

Returns:

  • nil if the endpoint is capable or validation should be skipped
  • ConsistencyError if the endpoint is too far behind

Types

type Action

type Action int

Action represents the post-relay decision action.

const (
	ActionRetry Action = iota
	ActionStop
)

type ArchiveAction

type ArchiveAction int

ArchiveAction represents the archive mutation to apply.

const (
	ArchiveNoChange ArchiveAction = iota
	ArchiveAdd
	ArchiveRemove
)

type ArchiveStatus

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

func (*ArchiveStatus) Copy

func (as *ArchiveStatus) Copy() *ArchiveStatus

func (*ArchiveStatus) IsArchive

func (as *ArchiveStatus) IsArchive() bool

func (*ArchiveStatus) IsUpgraded

func (as *ArchiveStatus) IsUpgraded() bool

func (*ArchiveStatus) SetArchive

func (as *ArchiveStatus) SetArchive(v bool)

func (*ArchiveStatus) SetUpgraded

func (as *ArchiveStatus) SetUpgraded(v bool)

type ChainIdAndApiInterfaceGetter

type ChainIdAndApiInterfaceGetter interface {
	GetChainIdAndApiInterface() (string, string)
}

ChainIdAndApiInterfaceGetter interface

type Consistency

type Consistency interface {
	SetSeenBlock(blockSeen int64, userData common.UserData)
	GetSeenBlock(userData common.UserData) (int64, bool)
	SetSeenBlockFromKey(blockSeen int64, key string)
	Key(userData common.UserData) string
}

Consistency interface for managing block consistency

func NewConsistency

func NewConsistency(specId string) Consistency

type ConsistencyImpl

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

ConsistencyImpl is the default implementation of Consistency.

mu, gen, and lastResetAtNano together serialize write paths against ResetState:

  • mu (RWMutex): ristretto's Clear() docs warn it "is not an atomic operation (but that shouldn't be a problem as it's assumed that Set/Get calls won't be occurring until after this)." Writes take the read-lock around the internal SetWithTTL so Clear runs under the exclusive write-lock with no concurrent Set/Get in flight — making ristretto's precondition hold.

  • gen (atomic counter): closes the queued-writer hole. A writer suspended between function entry and RLock can acquire RLock after ResetState has Cleared, see an empty cache (found=false), bypass the monotonic guard, and re-poison the store with whatever stale blockSeen it captured before the reset. Writes snapshot gen before RLock and drop the write if ResetState advanced gen while they were waiting.

  • lastResetAtNano (tombstone window): closes the fresh-post-reset hole. A relay response can be in flight in the relay processor for several milliseconds between when blockSeen was determined and when it reaches this cache; if /debug/reset-* fires in that gap, the late-arriving SetSeenBlockFromKey call enters this function only AFTER ResetState's gen.Add — so its startGen snapshot already matches the post-reset gen and the gen check passes. The tombstone drops any write whose RLock acquires within ResetTombstoneWindow of the most recent ResetState.

func (*ConsistencyImpl) GetLatestBlock

func (cc *ConsistencyImpl) GetLatestBlock(key string) (block int64, found bool)

func (*ConsistencyImpl) GetSeenBlock

func (cc *ConsistencyImpl) GetSeenBlock(userData common.UserData) (int64, bool)

func (*ConsistencyImpl) Key

func (cc *ConsistencyImpl) Key(userData common.UserData) string

func (*ConsistencyImpl) ResetState

func (cc *ConsistencyImpl) ResetState()

ResetState flushes every seen-block entry from the cache.

Why this is necessary: SetSeenBlockFromKey's monotonic guard only writes when the new block is strictly greater than the stored one. A test that accidentally sends a millisecond timestamp as a block parameter (~1.7T) poisons the entry, and the guard then rejects every legitimate ~20M block update until the 5-minute TTL expires — and ongoing traffic keeps refreshing the entry, so the TTL never actually fires. Flushing the whole cache is the only recovery short of a process restart.

Intended for the debug /debug/reset-* paths only; ristretto's Clear pauses and restarts the cache's processItems goroutine, so this is not suitable for the hot path.

The exclusive lock blocks every concurrent SetSeenBlockFromKey for the duration of Clear, which is what ristretto's Clear doc requires to make the operation behave atomically. gen is advanced and lastResetAtNano is stamped before Clear so any SetSeenBlockFromKey that was waiting on RLock (gen check) or that arrives within ResetTombstoneWindow afterward (tombstone check) drops its write rather than re-poisoning the cleared store.

func (*ConsistencyImpl) SetLatestBlock

func (cc *ConsistencyImpl) SetLatestBlock(key string, block int64)

func (*ConsistencyImpl) SetSeenBlock

func (cc *ConsistencyImpl) SetSeenBlock(blockSeen int64, userData common.UserData)

func (*ConsistencyImpl) SetSeenBlockFromKey

func (cc *ConsistencyImpl) SetSeenBlockFromKey(blockSeen int64, key string)

used on subscription, where we already have the dapp key stored, but we don't keep the dappId and ip separately

The Get-then-Set sequence is held under the read-lock so that ResetState's exclusive lock blocks every in-flight write until Clear has run. The generation snapshot before RLock catches writes queued behind ResetState's Lock; the tombstone check catches writes that entered the function during or just after Clear (relay-pipeline-delayed responses). Either condition drops the write to keep the cleared cache cleared.

type ConsistencyValidationConfig

type ConsistencyValidationConfig struct {
	// EndpointLagThreshold is the maximum number of blocks an endpoint can be behind
	// the seen block before being deprioritized or skipped (for pre-request validation).
	// This is typically more lenient than StalenessThreshold.
	EndpointLagThreshold int64

	// EnableWaitForCatchup determines whether to wait for endpoints to catch up
	// during pre-request validation. If false, endpoints that are too far behind
	// are simply skipped.
	EnableWaitForCatchup bool

	// MaxWaitTime is the maximum time to wait for an endpoint to catch up
	// when EnableWaitForCatchup is true.
	MaxWaitTime time.Duration
}

ConsistencyValidationConfig holds configuration for consistency validation with chain-specific thresholds derived from chain spec values. Only pre-request validation is used (post-response validation removed).

func DefaultConsistencyValidationConfig

func DefaultConsistencyValidationConfig() *ConsistencyValidationConfig

DefaultConsistencyValidationConfig returns a default configuration suitable for most chains. Uses conservative defaults.

func NewConsistencyValidationConfig

func NewConsistencyValidationConfig(
	blockLagForQosSync int64,
	blockDistanceToFinalization uint32,
	averageBlockTime time.Duration,
) *ConsistencyValidationConfig

NewConsistencyValidationConfig creates a new ConsistencyValidationConfig with thresholds derived from chain spec values.

Parameters:

  • blockLagForQosSync: The block lag threshold used for QoS sync calculations
  • blockDistanceToFinalization: The number of blocks until finalization
  • averageBlockTime: The average time between blocks for this chain

Derivation logic:

  • EndpointLagThreshold: max(blockLagForQosSync*2, blockDistanceToFinalization), minimum 10
  • MaxWaitTime: averageBlockTime * 2 - wait up to 2 average block times

func (*ConsistencyValidationConfig) IsEndpointTooFarBehind

func (c *ConsistencyValidationConfig) IsEndpointTooFarBehind(lag int64) bool

IsEndpointTooFarBehind checks if the given lag exceeds the endpoint threshold. lag = seenBlock - endpointLatestBlock

type DecisionInput

type DecisionInput struct {
	Selection     Selection
	AttemptNumber int
	IsBatch       bool
	Summary       ResultsSummary
	ArchiveStatus *ArchiveStatus
	// NodeErrors is from the state machine's atomic counter (set by HasRequiredNodeResults).
	// Used only by decideMutation() for archive threshold checks. Differs from
	// Summary.NodeErrors (from GetResultsSummary scan) in source but should converge.
	NodeErrors    uint64
	IsTickerHedge bool // true when called from ticker.C (hedge), false from gotResults (retry)
}

DecisionInput is assembled by the state machine for the policy engine.

type DecisionOutput

type DecisionOutput struct {
	Action   Action
	Mutation MutationOutput
	Reason   string
}

DecisionOutput tells the state machine what to do.

type LatestBlockEstimator

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

LatestBlockEstimator approximates the network latest block based on provider observations. It is fed with every successful relay response so archive extensions and "latest" requests can auto-detect heights.

func NewLatestBlockEstimator

func NewLatestBlockEstimator() *LatestBlockEstimator

func (*LatestBlockEstimator) Estimate

func (lbe *LatestBlockEstimator) Estimate(chainParser chainlib.ChainParser) (int64, int)

Estimate expected block height based on time elapsed. Returns the expected block height as well as the number of provider observations included.

func (*LatestBlockEstimator) Record

func (lbe *LatestBlockEstimator) Record(providerAddress string, latestBlock int64)

type MetricsInterface

type MetricsInterface interface {
	SetRelayNodeErrorMetric(chainId string, apiInterface string, providerAddress string, method string)
}

MetricsInterface for relay processor metrics

type MutationOutput

type MutationOutput struct {
	ArchiveAction ArchiveAction
	CacheHashes   bool
}

MutationOutput holds archive + cache side effects.

type RelayError

type RelayError struct {
	Err          error
	ProviderInfo common.ProviderInfo
	Response     *RelayResponse
	LavaError    *common.LavaError // classified error code (nil if not yet classified)
}

TODO: there's no need to save error twice and provider info twice, this can just be a RelayResponse

func (RelayError) GetError

func (re RelayError) GetError() error

GetError returns the underlying error

func (RelayError) String

func (re RelayError) String() string

type RelayErrors

type RelayErrors struct {
	RelayErrors       []RelayError
	OnFailureMergeAll bool
}

func (*RelayErrors) AddError

func (r *RelayErrors) AddError(err RelayError)

AddError adds a new error to the RelayErrors collection

func (*RelayErrors) GetBestErrorMessageForUser

func (r *RelayErrors) GetBestErrorMessageForUser() RelayError

GetBestErrorMessageForUser picks the single error to return to the user out of all failed relays. Precedence, in order:

  1. MAJORITY CONSENSUS: if a single error string appears on at least half the failed providers, return it regardless of category or score. Agreement across providers is the strongest signal we have.
  2. EXTERNAL PREFERENCE: among scored candidates (non-nil reputation+stake), external errors (node/chain) beat internal errors (protocol/transport) regardless of score — the user can act on an external error.
  3. SCORE TIEBREAK: within the same category, the provider with the highest reputation × stake wins.
  4. FALLBACK: if nothing scored, return the first error or merge all.

NOTE: the external preference is second-class — a Category=Internal majority will beat a solo Category=External error. That matches "trust consensus over individual signals", and flipping it would require a behavioral change the relay-race design isn't ready for.

type RelayParserInf

type RelayParserInf interface {
	ParseRelay(
		ctx context.Context,
		url string,
		req string,
		connectionType string,
		dappID string,
		consumerIp string,
		metadata []pairingtypes.Metadata,
	) (protocolMessage chainlib.ProtocolMessage, err error)
}

type RelayPolicyInf

type RelayPolicyInf interface {
	Decide(input DecisionInput) DecisionOutput
	OnSendRelayResult(err error, isPairingListEmpty bool, selection Selection) SendResult
	GetConsecutiveBatchErrors() int
}

RelayPolicyInf is the interface that the policy engine must implement.

type RelayProcessor

type RelayProcessor struct {
	ResultsManager
	RelayStateMachine
	// contains filtered or unexported fields
}

func NewRelayProcessor

func NewRelayProcessor(
	ctx context.Context,
	crossValidationParams *common.CrossValidationParams,
	consistency Consistency,
	metricsInf MetricsInterface,
	chainIdAndApiInterfaceGetter ChainIdAndApiInterfaceGetter,
	relayRetriesManager *lavaprotocol.RelayRetriesManager,
	relayStateMachine RelayStateMachine,
) *RelayProcessor

func (*RelayProcessor) GetAllowSessionDegradation

func (rp *RelayProcessor) GetAllowSessionDegradation() bool

true if we never got an extension. (default value)

func (*RelayProcessor) GetCrossValidationParams

func (rp *RelayProcessor) GetCrossValidationParams() *common.CrossValidationParams

func (*RelayProcessor) GetCrossValidationQueriedProviders

func (rp *RelayProcessor) GetCrossValidationQueriedProviders() []string

GetCrossValidationQueriedProviders returns the list of all providers that were queried for cross-validation

func (*RelayProcessor) GetResultsSummary

func (rp *RelayProcessor) GetResultsSummary() ResultsSummary

GetResultsSummary returns a pure data summary for the policy engine. No decisions.

func (*RelayProcessor) GetStatefulRelayTargets

func (rp *RelayProcessor) GetStatefulRelayTargets() []string

GetStatefulRelayTargets returns the list of providers that received a stateful relay

func (*RelayProcessor) GetUsedProviders

func (rp *RelayProcessor) GetUsedProviders() *lavasession.UsedProviders

func (*RelayProcessor) HasRequiredNodeResults

func (rp *RelayProcessor) HasRequiredNodeResults(tries int) (bool, int)

func (*RelayProcessor) NodeResults

func (rp *RelayProcessor) NodeResults() []common.RelayResult

this function returns all results that came from a node, meaning success, and node errors

func (*RelayProcessor) ProcessingResult

func (rp *RelayProcessor) ProcessingResult() (returnedResult *common.RelayResult, processingError error)

this function returns the results according to the defined strategy results were stored in WaitForResults and now there's logic to select which results are returned to the user will return an error if we did not meet quota of replies, if we did we follow the strategies: if return strategy == get_first: return the first success, if none: get best node error if strategy == stateless get majority of node responses on error: we will return a placeholder relayResult, with a provider address and a status code

func (*RelayProcessor) SetCrossValidationQueriedProviders

func (rp *RelayProcessor) SetCrossValidationQueriedProviders(providers []string)

SetCrossValidationQueriedProviders stores the list of all providers that were queried for cross-validation This includes providers whose responses may not have been received (due to early exit when threshold met)

func (*RelayProcessor) SetDisallowDegradation

func (rp *RelayProcessor) SetDisallowDegradation()

in case we had an extension and managed to get a session successfully, we prevent session degradation.

func (*RelayProcessor) SetResponse

func (rp *RelayProcessor) SetResponse(response *RelayResponse)

func (*RelayProcessor) SetStatefulRelayTargets

func (rp *RelayProcessor) SetStatefulRelayTargets(providers []string)

SetStatefulRelayTargets stores the list of providers that received a stateful relay

func (*RelayProcessor) String

func (rp *RelayProcessor) String() string

func (*RelayProcessor) WaitForResults

func (rp *RelayProcessor) WaitForResults(ctx context.Context) error

this function waits for the processing results, they are written by multiple go routines and read by this go routine it then updates the responses in their respective place, node errors, protocol errors or success results

type RelayResponse

type RelayResponse struct {
	RelayResult common.RelayResult
	Err         error
}

RelayResponse represents a response from a relay operation

type RelaySenderInf

type RelaySenderInf interface {
	RelayParserInf
	GetProcessingTimeout(chainMessage chainlib.ChainMessage) (processingTimeout time.Duration, relayTimeout time.Duration)
	GetChainIdAndApiInterface() (string, string)
}

RelaySenderInf is the unified interface for relay senders (Consumer and SmartRouter). Both ConsumerRelaySender and SmartRouterRelaySender have identical signatures.

type RelayState

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

func GetEmptyRelayState

func GetEmptyRelayState(ctx context.Context, protocolMessage chainlib.ProtocolMessage) *RelayState

func NewRelayState

func NewRelayState(ctx context.Context, protocolMessage chainlib.ProtocolMessage, stateNumber int, cache RetryHashCacheInf, relayParser RelayParserInf, archiveStatus *ArchiveStatus) *RelayState

func (*RelayState) CheckIsArchive

func (rs *RelayState) CheckIsArchive(relayRequestData *pairingtypes.RelayPrivateData) bool

func (*RelayState) GetArchiveStatus

func (rs *RelayState) GetArchiveStatus() *ArchiveStatus

func (*RelayState) GetIsArchive

func (rs *RelayState) GetIsArchive() bool

func (*RelayState) GetIsEarliestUsed

func (rs *RelayState) GetIsEarliestUsed() bool

func (*RelayState) GetIsUpgraded

func (rs *RelayState) GetIsUpgraded() bool

func (*RelayState) GetProtocolMessage

func (rs *RelayState) GetProtocolMessage() chainlib.ProtocolMessage

func (*RelayState) GetStateNumber

func (rs *RelayState) GetStateNumber() int

func (*RelayState) SetIsArchive

func (rs *RelayState) SetIsArchive(isArchive bool)

func (*RelayState) SetIsEarliestUsed

func (rs *RelayState) SetIsEarliestUsed()

func (*RelayState) SetProtocolMessage

func (rs *RelayState) SetProtocolMessage(protocolMessage chainlib.ProtocolMessage)

func (*RelayState) UpgradeToArchiveIfNeeded

func (rs *RelayState) UpgradeToArchiveIfNeeded(numberOfRetriesLaunched int, numberOfNodeErrors uint64)

Legacy method wrapper for backward compatibility

type RelayStateMachine

type RelayStateMachine interface {
	GetProtocolMessage() chainlib.ProtocolMessage
	GetDebugState() bool
	GetRelayTaskChannel() (chan RelayStateSendInstructions, error)
	UpdateBatch(err error)
	GetSelection() Selection
	GetCrossValidationParams() *common.CrossValidationParams // nil for Stateless/Stateful, non-nil for CrossValidation
	GetUsedProviders() *lavasession.UsedProviders
	SetResultsChecker(resultsChecker ResultsCheckerInf)
	SetRelayRetriesManager(relayRetriesManager *lavaprotocol.RelayRetriesManager)
}

RelayStateMachine interface for managing relay state

func NewUnifiedRelayStateMachine

func NewUnifiedRelayStateMachine(
	ctx context.Context,
	usedProviders *lavasession.UsedProviders,
	relaySender RelaySenderInf,
	protocolMessage chainlib.ProtocolMessage,
	analytics *metrics.RelayMetrics,
	debugRelays bool,
	config StateMachineConfig,
	policy RelayPolicyInf,
) (RelayStateMachine, error)

type RelayStateSendInstructions

type RelayStateSendInstructions struct {
	Analytics      *metrics.RelayMetrics
	Err            error
	Done           bool
	RelayState     *RelayState
	NumOfProviders int
}

RelayStateSendInstructions struct for relay instructions

func (*RelayStateSendInstructions) IsDone

func (rssi *RelayStateSendInstructions) IsDone() bool

type ResultsCheckerInf

type ResultsCheckerInf interface {
	WaitForResults(ctx context.Context) error
	HasRequiredNodeResults(tries int) (bool, int)
	GetCrossValidationParams() *common.CrossValidationParams // nil for Stateless/Stateful, non-nil for CrossValidation
	GetResultsSummary() ResultsSummary
}

ResultsCheckerInf interface for checking results

type ResultsManager

type ResultsManager interface {
	String() string
	NodeResults() []common.RelayResult
	RequiredResults(requiredSuccesses int, selection Selection) bool
	ProtocolErrors() uint64
	HasResults() bool
	GetResults() (success int, nodeErrors int, specialNodeErrors int, protocolErrors int)
	GetResultsData() (successResults []common.RelayResult, nodeErrors []common.RelayResult, protocolErrors []RelayError)
	SetResponse(response *RelayResponse, protocolMessage chainlib.ProtocolMessage) (nodeError error)
	GetBestNodeErrorMessageForUser() RelayError
	GetBestProtocolErrorMessageForUser() RelayError
	NodeErrors() (ret []common.RelayResult)
}

func NewResultsManager

func NewResultsManager(guid uint64, chainID string) ResultsManager

type ResultsManagerInst

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

func (*ResultsManagerInst) GetBestNodeErrorMessageForUser

func (rp *ResultsManagerInst) GetBestNodeErrorMessageForUser() RelayError

func (*ResultsManagerInst) GetBestProtocolErrorMessageForUser

func (rp *ResultsManagerInst) GetBestProtocolErrorMessageForUser() RelayError

func (*ResultsManagerInst) GetResults

func (rm *ResultsManagerInst) GetResults() (success int, nodeErrors int, specialNodeErrors int, protocolErrors int)

func (*ResultsManagerInst) GetResultsData

func (rp *ResultsManagerInst) GetResultsData() (successResults []common.RelayResult, nodeErrors []common.RelayResult, protocolErrors []RelayError)

func (*ResultsManagerInst) HasResults

func (rp *ResultsManagerInst) HasResults() bool

this function defines if we should use the manager to return the result (meaning it has some insight and responses) or just return to the user

func (*ResultsManagerInst) NodeErrors

func (rp *ResultsManagerInst) NodeErrors() (ret []common.RelayResult)

only when locked

func (*ResultsManagerInst) NodeResults

func (rp *ResultsManagerInst) NodeResults() []common.RelayResult

this function returns all results that came from a node, meaning success, and node errors

func (*ResultsManagerInst) ProtocolErrors

func (rp *ResultsManagerInst) ProtocolErrors() uint64

func (*ResultsManagerInst) RequiredResults

func (rp *ResultsManagerInst) RequiredResults(requiredSuccesses int, selection Selection) bool

func (*ResultsManagerInst) SetResponse

func (rp *ResultsManagerInst) SetResponse(response *RelayResponse, protocolMessage chainlib.ProtocolMessage) (nodeError error)

func (*ResultsManagerInst) String

func (rm *ResultsManagerInst) String() string

type ResultsSummary

type ResultsSummary struct {
	SuccessCount              int
	NodeErrors                int
	SpecialNodeErrors         int
	ProtocolErrors            int
	HasNonRetryableNodeError  bool  // any node error with IsNonRetryable flag (umbrella — THE RETRY GATE)
	HasUnsupportedMethod      bool  // subset of non-retryable, for caching decisions and zero-CU
	HasPermanentProtocolError bool  // any non-retryable protocol error (excluding epoch mismatch)
	HasEpochMismatch          bool  // any protocol error is epoch mismatch
	HashErr                   error // hash computation error (nil = hash OK)
}

ResultsSummary is pure data reported by the RelayProcessor for the policy engine.

type RetryHashCacheInf

type RetryHashCacheInf interface {
	CheckHashInCache(hash string) bool
	AddHashToCache(hash string)
}

type Selection

type Selection int
const (
	Stateless       Selection = iota // Single provider with retries on failure, sequential provider attempts until success
	Stateful                         // All top providers at once, waits for best result (no retries) or for all providers to return a response
	CrossValidation                  // maxParticipants providers at once, no retries, waits for agreementThreshold matching responses
)

Selection Enum - defines relay behavior modes

type SendResult

type SendResult int

SendResult represents the pre-relay send result decision.

const (
	SendSuccess SendResult = iota
	SendRetry
	SendStop
)

type StateMachineConfig

type StateMachineConfig struct {
	// EnableCircuitBreaker enables the PairingListEmptyError circuit breaker (SmartRouter only)
	EnableCircuitBreaker bool
	// CircuitBreakerThreshold is the number of consecutive pairing errors before tripping (default: 2)
	CircuitBreakerThreshold int
	// EnableTimeoutPriority enables priority timeout checks before each select case (SmartRouter only)
	EnableTimeoutPriority bool
	// MaxRetries is the maximum number of ticker relay retries
	MaxRetries int
	// SendRelayAttempts is the number of consecutive batch errors before giving up
	SendRelayAttempts int
}

StateMachineConfig configures behavior differences between Consumer and SmartRouter state machines

type UnifiedRelayStateMachine

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

UnifiedRelayStateMachine is the single state machine implementation used by both Consumer and SmartRouter. Behavior differences are controlled via StateMachineConfig. Retry decisions are centralized in the policy engine (RelayPolicyInf).

func (*UnifiedRelayStateMachine) GetCrossValidationParams

func (sm *UnifiedRelayStateMachine) GetCrossValidationParams() *common.CrossValidationParams

func (*UnifiedRelayStateMachine) GetDebugState

func (sm *UnifiedRelayStateMachine) GetDebugState() bool

func (*UnifiedRelayStateMachine) GetProtocolMessage

func (sm *UnifiedRelayStateMachine) GetProtocolMessage() chainlib.ProtocolMessage

func (*UnifiedRelayStateMachine) GetRelayTaskChannel

func (sm *UnifiedRelayStateMachine) GetRelayTaskChannel() (chan RelayStateSendInstructions, error)

func (*UnifiedRelayStateMachine) GetSelection

func (sm *UnifiedRelayStateMachine) GetSelection() Selection

func (*UnifiedRelayStateMachine) GetUsedProviders

func (sm *UnifiedRelayStateMachine) GetUsedProviders() *lavasession.UsedProviders

func (*UnifiedRelayStateMachine) Initialized

func (sm *UnifiedRelayStateMachine) Initialized() bool

func (*UnifiedRelayStateMachine) SetRelayRetriesManager

func (sm *UnifiedRelayStateMachine) SetRelayRetriesManager(relayRetriesManager *lavaprotocol.RelayRetriesManager)

func (*UnifiedRelayStateMachine) SetResultsChecker

func (sm *UnifiedRelayStateMachine) SetResultsChecker(resultsChecker ResultsCheckerInf)

func (*UnifiedRelayStateMachine) UpdateBatch

func (sm *UnifiedRelayStateMachine) UpdateBatch(err error)

Jump to

Keyboard shortcuts

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