events

package
v0.6.0 Latest Latest
Warning

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

Go to latest
Published: Nov 29, 2026 License: Apache-2.0 Imports: 33 Imported by: 4 modules, 3 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.

README

events

Package events (pkg.akt.dev/go/util/events) publishes the Akash audit, deployment and market events a node emits onto a pubsub.Bus: in the order the chain executed them, each once, with no height skipped. The recognized set is in decode.go.

Usage

bus := pubsub.NewBus()
defer bus.Close()

sub, err := bus.Subscribe()
if err != nil {
	return err
}

svc, err := events.NewEvents(ctx, "tcp://localhost:26657", "my-app", bus,
	events.WithStartHeight(bootstrapHeight)) // optional: the height your state was read at
if err != nil {
	return err
}
defer svc.Shutdown()

for {
	select {
	case ev := <-sub.Events():
		if closed, ok := ev.(*mtypes.EventLeaseClosed); ok {
			_ = closed // handle it
		}
	case <-svc.Done():
		return svc.Err() // non-nil only if the bus refused an event
	}
}

NewEvents fails on an invalid node URI or option and, without WithStartHeight, when the node does not answer its first status query. Once started, the service stops only on Shutdown, when its context ends, or when the bus refuses an event.

Guarantees

  • Events go out in execution order: PreBlock and BeginBlock events, then transactions, then EndBlock events.
  • Each height is published once and none is skipped. A height that cannot be fetched is retried forever, and every later event waits behind it. A bus that refuses an event stops the service, possibly partway through a height.
  • A recognized event that cannot be decoded, such as one with an enum value from a newer chain, is skipped and logged at error level, since a retry cannot change the outcome.
  • Without WithStartHeight the service publishes from the block after the node's latest height, so it replays nothing. Its position is not persisted and events carry no height: to start without a gap after reading chain state, pass the height it was read at.

Design

Own connection. The service opens its own connection from the node URI: an HTTP JSON-RPC client with its own pool for block results and status queries, and a websocket subscribed to new block headers. Its lifecycle is separate from any client the caller holds. Accepted URIs are tcp, http, https, ws, wss and unix; //host[:port] means tcp and a bare host:port is rejected. A missing port defaults to 80, or 443 for https and wss. A ws or wss URI is queried over http or https. Credentials in the URI are sent as Basic auth and masked in URI errors.

Liveness. The websocket is pinged every 5 s and counts as dead after 15 s without a pong or a message. Blocks are expected every watchdog window, so a live connection that delivers no new block for a whole window, counted from its last block or from when it connected, is presumed lost too: a node that stopped advancing but still answers pings, a subscription the node dropped without a word and a halted chain look the same from here. A lost or rejected connection is redialed at once, then once per retry interval, for as long as it takes; the service never subscribes twice on one connection. Each window without a new block, the watchdog also asks the node for its latest height, so events keep flowing even while the websocket cannot connect. Keep the window well above the chain's slowest normal block time, since a slower block costs a reconnect.

Run loop. One goroutine owns all state and only selects on results and timers. Every call to the node (dial, block fetch, status) runs in a goroutine of its own, bounded by the fetch timeout and cancelled on shutdown, so the loop never blocks on the network and Shutdown returns promptly.

Cursor. cursor.go decides what to fetch and what to publish. It starts no goroutines and reads no clock.

  • At most WithPrefetch heights, from the next one to publish on, are in flight or waiting at a time. They are published strictly in order, however the fetches complete.
  • When the next height fails, the cursor parks on it and retries it once per retry interval. After 30 s stalled it logs an error once and asks the node whether the height was pruned; the answer only explains the stall, the height is never skipped.
  • When a height above the cursor fails, no new fetch from it on starts until the cursor reaches it. It is then retried as the cursor height, and prefetching resumes.
  • A result for another height than the one requested counts as a failed fetch.

Options

Option Default Effect
WithWatchdogTimeout 8 s Time without a new block before redialing and polling the node.
WithFetchTimeout 10 s Bound on every call to the node, the websocket dial and writes included.
WithRetryInterval 5 s Pace of retries for a failed height, and of redials.
WithPrefetch 4 Heights fetched ahead at once; 1 fetches one at a time.
WithStartHeight node's latest Publish from block h+1.
WithLogger logger in ctx Where the service logs.

Files

File Contents
publish.go Service, NewEvents, lifecycle and run loop
cursor.go In-order cursor
ws.go Websocket header stream: dial, subscribe, ping and pong
node.go Node URI parsing; HTTP and websocket targets
decode.go Block results to typed events
options.go Options
query.go Header subscription query

Documentation

Index

Constants

View Source
const (
	// DefaultWatchdogTimeout is how long the service waits for a new block header before
	// it presumes the connection lost, redials it, and asks the node how far the chain
	// has got (see WithWatchdogTimeout).
	DefaultWatchdogTimeout = 8 * time.Second

	// DefaultFetchTimeout is how long the service waits for the node to answer a block
	// fetch or a status query. A call that has not returned by then counts as a failed
	// attempt and is retried. It also bounds the websocket dial, handshake included, and
	// every websocket write.
	DefaultFetchTimeout = 10 * time.Second

	// DefaultRetryInterval is how often a block that cannot be fetched is retried (see
	// WithRetryInterval).
	DefaultRetryInterval = 5 * time.Second

	// DefaultPrefetch is how many blocks the service fetches at once (see WithPrefetch).
	DefaultPrefetch = 4
)

Variables

This section is empty.

Functions

This section is empty.

Types

type Option added in v0.4.6

type Option func(*options) error

Option configures the events service. It follows the functional options pattern, so settings can be added without breaking NewEvents callers. An option that returns an error makes NewEvents fail with that error.

func WithFetchTimeout added in v0.4.8

func WithFetchTimeout(d time.Duration) Option

WithFetchTimeout sets how long the service waits for the node to answer a block fetch or a status query before it counts the call as failed and retries it. It also bounds the websocket dial, handshake included, and every websocket write, so it must leave room for a slow node to complete a handshake. It must be positive. The default is DefaultFetchTimeout.

func WithLogger added in v0.4.6

func WithLogger(l log.Logger) Option

WithLogger sets the logger the service reports to, including every loss and re-establishment of the block subscription. It must not be nil. By default the service uses the logger carried by the context passed to NewEvents (see util/ctxlog), which discards everything when the context carries none.

func WithPrefetch added in v0.4.8

func WithPrefetch(n int) Option

WithPrefetch sets how many blocks the service may fetch at once while it catches up. Blocks are still published strictly in order; prefetching only overlaps the waits on the node. 1 fetches one block at a time. It must be at least 1. The default is DefaultPrefetch.

func WithRetryInterval added in v0.4.8

func WithRetryInterval(d time.Duration) Option

WithRetryInterval sets how often a block that cannot be fetched is retried. The service never gives up on a block, because a skipped block is a lost event, so a block the node cannot serve is retried at this pace for as long as the service runs. It must be positive. The default is DefaultRetryInterval.

func WithStartHeight added in v0.4.6

func WithStartHeight(h int64) Option

WithStartHeight makes the service publish events from block h+1 on, where h is the last block the caller has already accounted for, for example the height its bootstrap queries were pinned to. Without it the service starts from the node's latest height when NewEvents runs, and anything the caller has not seen at or below that height is neither queried nor published. h must not be negative. A height the node no longer retains parks the cursor until a node that retains it answers.

func WithWatchdogTimeout added in v0.4.6

func WithWatchdogTimeout(d time.Duration) Option

WithWatchdogTimeout sets how long the service waits for a new block header. Blocks are expected every window: once one passes without a new block, a live connection is presumed lost and redialed, and the service asks the node how far the chain has got and fetches the blocks it has missed itself, once per window until a new header arrives. Keep the window well above the chain's slowest normal block time, since any block slower than it costs a reconnect. It must be positive. The default is DefaultWatchdogTimeout.

type Service

type Service interface {
	// Shutdown stops the event monitoring service and waits for it to finish.
	Shutdown()
	// Done is closed once the service has stopped, whether through Shutdown, its parent
	// context, or on its own (see Err).
	Done() <-chan struct{}
	// Err returns why the service stopped on its own: the bus's error when the bus
	// stopped accepting events. It returns nil while the service runs and once it was
	// stopped through Shutdown or its parent context.
	Err() error
}

Service represents an event monitoring service that watches the chain and publishes the transaction events it recognises to a message bus.

func NewEvents

func NewEvents(ctx context.Context, nodeURI string, name string, bus pubsub.Bus, opts ...Option) (Service, error)

NewEvents creates and starts a blockchain event monitoring service for the node at nodeURI: tcp://, http://, https://, ws://, wss:// or unix://.

The service opens its own connection to the node, a websocket for block headers and an HTTP client for block results, so its lifecycle is its own, separate from any client the caller holds. It processes each block in order, publishing the events it recognises exactly once: none is published twice and no height is skipped (see below for the one kind of event that is). It tracks the last published height, so a gap between headers, for example across a reconnect, is back-filled rather than lost.

The websocket is watched with ping and pong. A connection that stops answering, whether reset, closed or silently dropped somewhere along the way, is noticed within the pong wait and redialed: the first time at once, then once per retry interval (WithRetryInterval, DefaultRetryInterval by default) for as long as it takes. The service never subscribes twice on one connection; a node that rejects the subscription is asked again on a fresh connection, at the same pace. Every loss of the subscription is logged at warn level and every dial at info level (see WithLogger). Blocks are expected every watchdog window (WithWatchdogTimeout, DefaultWatchdogTimeout by default): a live connection that delivers no new block for a whole window is presumed lost and redialed the same way, since a node that stopped advancing but still answers pings, a subscription the node dropped without a word and a halted chain look the same from here. Each such window the watchdog also asks the node how far the chain has got, so events keep flowing while the websocket is down.

Blocks are fetched off the service's loop, up to WithPrefetch (DefaultPrefetch by default) at a time while it catches up, and published strictly in order. Every call to the node is bounded by the fetch timeout (WithFetchTimeout, DefaultFetchTimeout by default) and cancelled when the service stops, so a stuck request never holds it and Shutdown returns promptly.

A height that cannot be fetched parks the cursor and is retried once per retry interval on its own timer, so a transient failure (a pooled backend that does not have the height yet, a rate-limited request) costs one retry interval rather than waiting for the next header or watchdog tick. The cursor never moves past it, because a skipped height is a lost event: a missed EventLeaseClosed leaves a provider running a closed lease. Later events wait behind it until it is served, however long that takes: the service never gives up on a height. A long stall is logged at error level, once. A node that answers with another height's results is treated as failing.

A recognized event that cannot be decoded, for example one carrying an enum value from a newer chain, is skipped and logged at error level. Retrying its height cannot change the outcome, so the rest of the height and later heights go out as usual.

The service stops on its own only when the bus refuses an event; Err then says why.

It starts from the node's latest height, so historical events are not replayed, unless WithStartHeight says where the caller left off.

Jump to

Keyboard shortcuts

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