duplex

package module
v0.0.0-...-084c276 Latest Latest
Warning

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

Go to latest
Published: Apr 28, 2026 License: MIT Imports: 13 Imported by: 0

README

banner

Duplex

A minimal, Go-based library to run CL∆ clients or servers.

Example Usage

package main

import (
    // ...
    "github.com/cloudlink-delta/duplex"
)

func main() {

    // Creates a new duplex instance with a unique name.
    instance := duplex.New("my server")

    // Overrides the default behavior of a built-in CL Delta opcode.
    // Remapped functions have the highest priority during processing.
    instance.Remap("G_MSG", func(peer *duplex.Peer, packet *duplex.RxPacket) {
		// ...
	})

    // If you want to switch back to the built-in behavior of a opcode...
    instance.Unmap("G_MSG")

    // Creates a new opcode handler.
    // Custom handlers have the lowest priority during processing.
    // Any remapped or built-in handlers will run first.
    instance.Bind("MY_OPCODE", func(peer *duplex.Peer, packet *duplex.RxPacket) {
		// ...
	})

    // If you need to remove a custom handler...
    instance.Unbind("MY_OPCODE")

    // To run the instance, simply call Run().
    // Note that Run() will block code execution.
    instance.Run()
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Config

type Config struct {
	Hostname     string
	Secure       bool
	Port         int
	ICEServers   []webrtc.ICEServer
	EnablePinger bool
	PingInterval int64 // in milliseconds
	LogLevel     zerolog.Level
}

type Instance

type Instance struct {
	Name                             string
	Pinger                           bool
	PingInterval                     time.Duration
	Handler                          *peer.Peer
	Close                            chan bool
	Done                             chan bool
	RetryCounter                     int
	MaxRetries                       int
	Peers                            Peers
	OnCreate                         func()
	AfterNegotiation                 func(*Peer)
	OnOpen                           func(*Peer)
	OnClose                          func(*Peer)
	CustomHandlersRequiredFeatures   map[string][]string
	CustomHandlers                   map[string]func(*Peer, *RxPacket)
	RemappedHandlersRequiredFeatures map[string][]string
	RemappedHandlers                 map[string]func(*Peer, *RxPacket)
	IsBridge                         bool
	IsRelay                          bool
	IsDiscovery                      bool
	OnBridgeConnected                func(*Peer)
	OnRelayConnected                 func(*Peer)
	OnDiscoveryConnected             func(*Peer)

	Logger *zerolog.Logger
	// contains filtered or unexported fields
}

Instance is a representation of a duplex instance.

func New

func New(ID string, args *Config) *Instance

func (*Instance) AttemptReconnect

func (i *Instance) AttemptReconnect()

func (*Instance) Bind

func (i *Instance) Bind(opcode string, handler func(*Peer, *RxPacket), required_features ...string)

func (*Instance) Broadcast

func (i *Instance) Broadcast(packet *TxPacket, peers PeerSlice)

func (*Instance) Connect

func (i *Instance) Connect(id string) *Peer

func (*Instance) GetPeerState

func (i *Instance) GetPeerState() PeerState

func (*Instance) PeerHandler

func (i *Instance) PeerHandler(conn *Peer)

func (*Instance) Remap

func (i *Instance) Remap(opcode string, handler func(*Peer, *RxPacket), required_features ...string)

func (*Instance) Run

func (i *Instance) Run()

func (*Instance) SpawnTicker

func (i *Instance) SpawnTicker(conn *Peer)

func (*Instance) Unbind

func (i *Instance) Unbind(opcode string)

func (*Instance) Unmap

func (i *Instance) Unmap(opcode string)

type Listener

type Listener func(*RxPacket)

type NegotiationArgs

type NegotiationArgs struct {
	Version     VersionArgs `json:"version"`
	SpecVersion int         `json:"spec_version"`
	Plugins     []string    `json:"plugins"`
	IsBridge    bool        `json:"is_bridge"`
	IsRelay     bool        `json:"is_relay"`
	IsDiscovery bool        `json:"is_discovery"`
}

type OpcodeMatcher

type OpcodeMatcher struct {
	Opcodes  []string
	Callback func(*RxPacket)
}

type Packet

type Packet struct {
	Opcode   string `json:"opcode"`
	Origin   string `json:"origin,omitempty"`
	Target   string `json:"target,omitempty"`
	TTL      int    `json:"ttl,omitempty"`
	Id       string `json:"id,omitempty"`
	Method   string `json:"method,omitempty"`
	Listener string `json:"listener,omitempty"`
}

type Peer

type Peer struct {
	Parent               *Instance      // Pointer to the parent instance that created this peer
	Lock                 *sync.Mutex    // Lock for thread safety
	KeyStore             map[string]any // Map of key-value pairs of any type
	KeyLock              *sync.Mutex
	OpcodeMatchers       map[*Peer]*OpcodeMatcher // Map of key-value pairs to listen to specific opcodes from specific peers.
	Listeners            map[string]Listener      // Map of key-value pairs to listeners.
	Features             []string                 // List of features advertised by this peer
	IsInitiator          bool                     // True if this peer initiated the connection
	IsBridge             bool                     // True if this peer is a bridge
	IsRelay              bool                     // True if this peer is a relay
	IsDiscovery          bool                     // True if this peer is a discovery
	Done                 chan bool                // Channel to signal connection closure
	RTT                  int64                    // Round-trip time (in milliseconds)
	GiveNameRemapper     func() string
	Logger               zerolog.Logger
	*peer.DataConnection // Pointer to the peer data connection
}

Peer is a representation of a peer connection for a duplex instance.

func (*Peer) GiveName

func (c *Peer) GiveName() string

Returns the peer's preferred ID.

func (*Peer) HandleNegotiate

func (conn *Peer) HandleNegotiate(reader *RxPacket)

func (*Peer) HandlePacket

func (conn *Peer) HandlePacket(r *RxPacket)

func (*Peer) IsClient

func (c *Peer) IsClient() bool

Returns true if the peer does not advertise any features.

func (*Peer) Read

func (c *Peer) Read(data any) *RxPacket

Goroutine that reads incoming messages from the peer.

func (*Peer) SendAndWaitForReply

func (conn *Peer) SendAndWaitForReply(request *TxPacket) *RxPacket

SendAndWaitForReply sends a packet and waits for a response with the given opcode. The packet needs to be tagged with a listener string. The function will return a channel that will receive the response packet when it is received. If the opcode of the received packet does not match the reply opcode, the function will return nil. The function will also return nil if the packet is not tagged with a listener string. The function will block until the response is received or the underlying connection is closed. The function is safe for concurrent use.

func (*Peer) SendNegotiate

func (conn *Peer) SendNegotiate(r *RxPacket)

SendNegotiate sends a NEGOTIATE packet to a newly connected peer.

func (*Peer) WaitForMatchedPacket

func (conn *Peer) WaitForMatchedPacket(opcodes ...string) *RxPacket

Creates a callback that fires whenever a specific connection receives a specific packet opcode.

func (*Peer) Write

func (c *Peer) Write(packet *TxPacket)

Goroutine that writes messages to the peer.

func (*Peer) WriteBlocking

func (c *Peer) WriteBlocking(packet *TxPacket)

WriteBlocking is a variant of Write that has a blocking mode that exits when it has finished sending the entire message to the recipient.

type PeerSlice

type PeerSlice []*Peer

type PeerState

type PeerState struct {
	Uptime          string `json:"uptime"`
	ConnectionState bool   `json:"connection_state"`
}

type Peers

type Peers map[string]*Peer

func (*Peers) ToSlice

func (p *Peers) ToSlice(exclusions ...*Peer) PeerSlice

type RxPacket

type RxPacket struct {
	Packet
	Payload json.RawMessage `json:"payload,omitempty"`
}

func (*RxPacket) String

func (p *RxPacket) String() string

type TxPacket

type TxPacket struct {
	Packet
	Payload any `json:"payload,omitempty"`
}

func (*TxPacket) String

func (p *TxPacket) String() string

type VersionArgs

type VersionArgs struct {
	Type  string `json:"type"`
	Major int    `json:"major"`
	Minor int    `json:"minor"`
	Patch int    `json:"patch"`
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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