presence

package
v1.6.0 Latest Latest
Warning

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

Go to latest
Published: Oct 25, 2026 License: Apache-2.0 Imports: 11 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func DetectMessageType

func DetectMessageType(data []byte) string

DetectMessageType returns the "type" field from a JSON message.

func PresenceTopic

func PresenceTopic(serverID peer.ID) string

PresenceTopic returns the GossipSub topic for a server's presence events.

Types

type Cache

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

Cache is a TTL-based presence cache that stores and retrieves presence information for peers.

func NewCache

func NewCache(ttl time.Duration) *Cache

NewCache creates a new presence cache with the given TTL for entries.

func (*Cache) Cleanup

func (c *Cache) Cleanup()

Cleanup removes all expired entries from the cache.

func (*Cache) Get

func (c *Cache) Get(id peer.ID) *PresenceStatus

Get returns the cached presence status for a peer, or nil if the entry does not exist or has expired.

func (*Cache) GetStats

func (c *Cache) GetStats() map[string]any

GetStats returns cache statistics.

func (*Cache) Set

func (c *Cache) Set(id peer.ID, status *PresenceStatus)

Set stores or updates the presence status for a peer.

type Monitor

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

Monitor actively checks peer presence by attempting connections and caches the results.

func NewMonitor

func NewMonitor(cache *Cache, h host.Host, logger *slog.Logger) *Monitor

NewMonitor creates a new presence monitor.

func (*Monitor) CheckPresence

func (m *Monitor) CheckPresence(ctx context.Context, id peer.ID) *PresenceStatus

CheckPresence determines the current presence state of a peer. It first checks if the peer is already connected, and if not, attempts to establish a connection.

func (*Monitor) GetStats

func (m *Monitor) GetStats() map[string]any

GetStats returns monitoring statistics including cache stats.

func (*Monitor) StartPeriodicMonitoring

func (m *Monitor) StartPeriodicMonitoring(ctx context.Context, peers []peer.ID, interval time.Duration)

StartPeriodicMonitoring launches a background goroutine that periodically checks the presence of the given peers at the specified interval.

func (*Monitor) StopMonitoring

func (m *Monitor) StopMonitoring()

StopMonitoring cancels the periodic monitoring goroutine.

type PresenceChange

type PresenceChange struct {
	PeerID     peer.ID       `json:"peerId"`
	State      PresenceState `json:"state"`
	TTLSeconds int           `json:"ttlSeconds"`
}

PresenceChange represents a single peer's state change.

type PresenceConfig

type PresenceConfig struct {
	// HeartbeatInterval is how often the full online set is published.
	HeartbeatInterval time.Duration

	// TimeoutDuration is the TTL advertised on Online change events: how
	// long a subscriber may trust the claim without a heartbeat refreshing
	// it. It does not evict peers on the server; connectedness does.
	TimeoutDuration time.Duration

	// CheckInterval is how often the service reconciles its online set with
	// the network, catching any connect or disconnect the notifier missed.
	CheckInterval time.Duration

	BatchWindow     time.Duration
	MaxBatchSize    int
	EnableBroadcast bool
}

PresenceConfig holds presence service configuration.

func DefaultPresenceConfig

func DefaultPresenceConfig() *PresenceConfig

DefaultPresenceConfig returns sensible defaults.

type PresenceEvent

type PresenceEvent struct {
	Type      string           `json:"type"` // "event"
	ServerID  peer.ID          `json:"serverId"`
	Timestamp time.Time        `json:"timestamp"`
	Changes   []PresenceChange `json:"changes"`
}

PresenceEvent is a batch of presence changes published via GossipSub.

func DecodePresenceEvent

func DecodePresenceEvent(data []byte) (*PresenceEvent, error)

DecodePresenceEvent deserializes a PresenceEvent from JSON bytes.

func (*PresenceEvent) Encode

func (e *PresenceEvent) Encode() ([]byte, error)

Encode serializes a PresenceEvent to JSON bytes.

type PresenceHeartbeat

type PresenceHeartbeat struct {
	Type              string    `json:"type"` // "heartbeat"
	ServerID          peer.ID   `json:"serverId"`
	Timestamp         time.Time `json:"timestamp"`
	OnlineCount       int       `json:"onlineCount"`
	OnlinePeerIDs     []peer.ID `json:"onlinePeerIds"`
	HeartbeatSequence uint64    `json:"heartbeatSequence"`
	Page              int       `json:"page,omitempty"`
	PageCount         int       `json:"pageCount,omitempty"`
}

PresenceHeartbeat is a periodic liveness signal from a server carrying its online set.

A large online set is split across pages: every page of one heartbeat shares the HeartbeatSequence, Timestamp and OnlineCount, and carries its own slice of OnlinePeerIDs. A subscriber has the whole set once it holds all PageCount pages of a sequence. A heartbeat with PageCount of 0 or 1 is complete on its own, so a message from before paging still reads the same way.

func DecodePresenceHeartbeat

func DecodePresenceHeartbeat(data []byte) (*PresenceHeartbeat, error)

DecodePresenceHeartbeat deserializes a PresenceHeartbeat from JSON bytes.

func (*PresenceHeartbeat) Encode

func (h *PresenceHeartbeat) Encode() ([]byte, error)

Encode serializes a PresenceHeartbeat to JSON bytes.

type PresenceState

type PresenceState int

PresenceState represents the online status of a peer.

const (
	// Online indicates the peer is currently connected and reachable.
	Online PresenceState = iota

	// ProbablyOnline indicates the peer was recently seen but connectivity
	// has not been confirmed.
	ProbablyOnline

	// Offline indicates the peer could not be reached.
	Offline

	// Unknown indicates no presence information is available.
	Unknown
)

func (PresenceState) String

func (s PresenceState) String() string

String returns a human-readable representation of the presence state.

type PresenceStatus

type PresenceStatus struct {
	PeerID    peer.ID
	State     PresenceState
	LastSeen  time.Time
	CheckedAt time.Time
}

PresenceStatus holds presence information for a single peer.

type Service

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

Service manages server-side presence tracking and broadcasting.

func NewService

func NewService(h host.Host, node *node.Node, cache *Cache, cfg *PresenceConfig, logger *slog.Logger) *Service

NewService creates a new presence broadcasting service.

func (*Service) GetOnlineCount

func (s *Service) GetOnlineCount() int

GetOnlineCount returns the count of online peers.

func (*Service) GetOnlinePeers

func (s *Service) GetOnlinePeers() []peer.ID

GetOnlinePeers returns currently tracked online peers.

func (*Service) Name

func (s *Service) Name() string

Name returns the service name for lifecycle logging.

func (*Service) Start

func (s *Service) Start(ctx context.Context) error

Start joins the presence GossipSub topic and begins background loops.

func (*Service) Stop

func (s *Service) Stop() error

Stop cancels all background goroutines.

type Tracker

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

Tracker subscribes to presence topics from servers and maintains a local presence cache for contacts.

func NewTracker

func NewTracker(node *node.Node, cache *Cache, logger *slog.Logger) *Tracker

NewTracker creates a new client-side presence tracker.

func (*Tracker) AddContact

func (t *Tracker) AddContact(pid peer.ID)

AddContact adds a peer to track presence for.

func (*Tracker) GetOnlineContacts

func (t *Tracker) GetOnlineContacts() []peer.ID

GetOnlineContacts returns all contacts currently known to be online.

func (*Tracker) GetPresence

func (t *Tracker) GetPresence(pid peer.ID) PresenceState

GetPresence returns the cached presence state for a peer.

func (*Tracker) RemoveContact

func (t *Tracker) RemoveContact(pid peer.ID)

RemoveContact stops tracking presence for a peer.

func (*Tracker) SetOnChange

func (t *Tracker) SetOnChange(fn func(peer.ID, PresenceState))

SetOnChange registers a callback for presence state changes.

func (*Tracker) Stop

func (t *Tracker) Stop()

Stop cancels the tracker's subscription.

func (*Tracker) SubscribeToServer

func (t *Tracker) SubscribeToServer(ctx context.Context, serverID peer.ID) error

SubscribeToServer subscribes to presence events from the given server.

type VisibilityPreference

type VisibilityPreference int

VisibilityPreference controls who can see a peer's presence.

const (
	// VisibilityEveryone allows all peers to see presence.
	VisibilityEveryone VisibilityPreference = iota
	// VisibilityNobody hides presence from all peers.
	VisibilityNobody
)

Jump to

Keyboard shortcuts

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