wsbrokerclient

package module
v0.0.0-...-7dbcabc Latest Latest
Warning

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

Go to latest
Published: Nov 2, 2026 License: Apache-2.0 Imports: 5 Imported by: 0 modules, 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.

README

This Repository has been moved to https://gitlab.switch.ch/ub-unibas/library-infrastructure/wsbrokerclient

WSBrokerClient

Go Reference License

WSBrokerClient is an enterprise-grade Go client library for WSBroker. It provides seamless WebSocket and REST integration, robust mutual TLS (mTLS) certificate management with hot-reloading via certloader, jittered exponential backoff auto-reconnection, dynamic pub/sub channel state management, and stream subscriptions.


Table of Contents


Features

  • High-Performance WebSocket Engine: Powered by coder/websocket with concurrent-safe write synchronization and context-aware timeouts.
  • Enterprise mTLS Security: Full integration with go.ub.unibas.ch/cloud/certloader/v2 supporting dynamic hot-reloading of client certificates, MiniVault PKI, local file pairs, environment variables, or standard Go *tls.Config.
  • Intelligent Auto-Reconnection: Built-in connection supervisor with jittered exponential backoff and transparent channel resubscription upon network restore.
  • Dynamic Pub/Sub & Stream Subscriptions: Join/leave channels dynamically, consume channel events via Go channels (Subscription.Events(), SubscribeTyped), or register target/type-specific handlers.
  • Custom Domain Events & Generics: Thread-safe payload type registry and generic helpers (OnTyped[T], SubscribeTyped[T], ToTyped[T]) for type-safe message handling without reflection overhead.
  • Direct Point-to-Point Messaging: Send targeted events directly to specific connected clients.
  • Request-Response & RPC Patterns: Synchronous 1:1 RPC (Request/Request1), fire-and-forget (Request0), and multi-response streaming (RequestN) with correlation via RefID and correlation sessions.
  • NTP Time Synchronization: Accurate clock offset measurement and synchronized time over WebSocket connections.
  • Automatic Heartbeat Management: Responds to server pings with standard pong envelopes and sends periodic client-side keepalive pings.
  • RESTful Client Included: Full HTTP client implementation for WSBroker REST management endpoints (/api/v1/publish, /api/v1/channels, /api/v1/clients, etc.).

Architecture & Diagrams

System Architecture
graph TB
    subgraph App["Your Go Application"]
        WSClient["WSBroker WebSocket Client\n(pkg/client)"]
        RESTClient["WSBroker REST Client\n(pkg/restclient)"]
        CertLoader["CertLoader PKI Engine\n(go.ub.unibas.ch/cloud/certloader/v2)"]
    end

    subgraph Server["WSBroker Server"]
        WSEndpoint["WebSocket Controller\n(/ws/:name/:mode, /ws/channel/:channel/:mode)"]
        RESTEndpoint["REST Controller\n(/api/v1/publish, /api/v1/channels)"]
        BrokerEngine["Connection Manager & Worker Pool"]
    end

    CertLoader -->|Supplies mTLS Certificates| WSClient
    CertLoader -->|Supplies mTLS Certificates| RESTClient
    WSClient <-->|mTLS / WSS Encrypted WebSocket| WSEndpoint
    RESTClient -->|mTLS / HTTPS POST & GET| RESTEndpoint
    WSEndpoint <--> BrokerEngine
    RESTEndpoint --> BrokerEngine

Connection & Channel Lifecycle
sequenceDiagram
    autonumber
    actor App as Your Application
    participant Client as WSBrokerClient
    participant Server as WSBroker Server

    Note over App,Server: 1. Connection & Initial Subscriptions
    App->>Client: Connect(ctx)
    Client->>Server: WebSocket Handshake (GET /ws/node-01/rw?channel=alerts)
    Server-->>Client: 101 Switching Protocols (Connected)
    Client-->>App: OnConnect Callback Triggered

    Note over App,Server: 2. Dynamic Channel Attach & Detach
    App->>Client: Attach("metrics", "logs")
    Client->>Server: {"type": "attach", "target": "metrics"}
    Client->>Server: {"type": "attach", "target": "logs"}
    Server-->>Client: Subscribed to metrics & logs

    App->>Client: Detach("logs")
    Client->>Server: {"type": "detach", "target": "logs"}
    Server-->>Client: Unsubscribed from logs

    Note over App,Server: 3. Message Broadcasting & Streaming
    App->>Client: Broadcast("metrics", {"cpu": 45.2})
    Client->>Server: {"type": "message", "target": "metrics", "data": {"cpu": 45.2}}
    Server-->>Client: Inbound Channel Message Dispatch
    Client-->>App: Delivery to Subscription.Events() channel

Automatic Reconnection & Resubscription Flow
sequenceDiagram
    autonumber
    participant App as Application
    participant Client as WSBrokerClient
    participant Server as WSBroker Server

    Note over Client,Server: Normal Operation (Subscribed to "alerts", "telemetry")
    Server--xClient: Network Drop / Connection Lost
    Client->>Client: Update State to Reconnecting
    Client-->>App: OnDisconnect(err) Callback

    loop Exponential Backoff with Jitter
        Client->>Client: Calculate Next Sleep Duration
        Client->>Server: Attempt WebSocket Handshake
        alt Connection Failed
            Server--xClient: Handshake Refused / Network Down
            Client-->>App: OnError(err) Callback
        else Connection Successful
            Server-->>Client: 101 Switching Protocols
            Client->>Client: Update State to Connected
        end
    end

    Note over Client,Server: Channel Resubscription
    Client->>Server: {"type": "attach", "target": "alerts"}
    Client->>Server: {"type": "attach", "target": "telemetry"}
    Client-->>App: OnReconnect() and OnConnect() Callbacks
    Note over App,Server: Seamless Resumption of Stream Flow

mTLS Handshake & Security Model
sequenceDiagram
    autonumber
    participant Client as WSBrokerClient
    participant PKI as CertLoader / MiniVault
    participant Server as WSBroker (mTLS)

    PKI->>Client: Load Client Cert, Key & Trusted Root CA
    Client->>Server: TLS ClientHello (Supported Ciphers, TLS 1.3)
    Server->>Client: ServerHello + Server Certificate
    Client->>Client: Validate Server Cert against Root CA
    Server->>Client: CertificateRequest (Require Client Certificate)
    Client->>Server: Client Certificate + CertificateVerify
    Server->>Server: Validate Client Cert against Server CA Pool
    Server-->>Client: Finished (Secure mTLS Tunnel Established)
    Client->>Server: Upgrade: websocket (Authorization: Bearer <token>)

Installation

go get github.com/je4/wsbrokerclient

Quick Start

package main

import (
	"context"
	"fmt"
	"time"

	"github.com/je4/wsbrokerclient"
)

type SensorTelemetry struct {
	DeviceID    string  `json:"device_id"`
	Temperature float64 `json:"temperature"`
	Humidity    float64 `json:"humidity"`
}

func main() {
	ctx := context.Background()

	// 1. Initialize Client
	cli, err := wsbrokerclient.New(wsbrokerclient.DefaultConfig(),
		wsbrokerclient.WithEndpoint("ws://localhost:8080"),
		wsbrokerclient.WithClientName("sensor-node-01"),
		wsbrokerclient.WithInitialChannels("telemetry", "alerts"),
		wsbrokerclient.WithAutoReconnect(true),
	)
	if err != nil {
		panic(err)
	}
	defer cli.Close()

	// 2. Stream-based subscription
	sub, err := cli.Subscribe(ctx, "telemetry")
	if err != nil {
		panic(err)
	}
	defer sub.Unsubscribe()

	go func() {
		for evt := range sub.Events() {
			var data SensorTelemetry
			if err := evt.UnmarshalData(&data); err == nil {
				fmt.Printf("[%s] Temp: %.1f°C, Humidity: %.1f%%\n", data.DeviceID, data.Temperature, data.Humidity)
			}
		}
	}()

	// 3. Connect to WSBroker
	if err := cli.Connect(ctx); err != nil {
		panic(err)
	}

	// 4. Broadcast sensor data
	_ = cli.Broadcast(ctx, "telemetry", SensorTelemetry{
		DeviceID:    "sensor-node-01",
		Temperature: 22.4,
		Humidity:    48.0,
	})

	time.Sleep(2 * time.Second)
}

Security & mTLS Configuration

mTLS via certloader (MiniVault, File, Env, Dev)

WSBrokerClient directly integrates with go.ub.unibas.ch/cloud/certloader/v2. It handles dynamic client certificates with automatic hot-reloading:

import (
	"github.com/je4/wsbrokerclient"
	"go.ub.unibas.ch/cloud/certloader/v2/pkg/loader"
)

// Example: File-based mTLS
certConfig := &loader.Config{
	Type: "FILE",
	File: &loader.FileConfig{
		Cert: "/etc/ssl/certs/client.cert.pem",
		Key:  "/etc/ssl/private/client.key.pem",
		CA:   []string{"/etc/ssl/certs/ca.crt"},
	},
}

cli, err := wsbrokerclient.New(wsbrokerclient.DefaultConfig(),
	wsbrokerclient.WithEndpoint("wss://broker.internal.org:8080"),
	wsbrokerclient.WithClientName("service-a"),
	wsbrokerclient.WithTLSCertLoader(certConfig),
)
mTLS via standard crypto/tls
import (
	"crypto/tls"
	"crypto/x509"
	"os"

	"github.com/je4/wsbrokerclient"
)

cert, _ := tls.LoadX509KeyPair("client.crt", "client.key")
caCert, _ := os.ReadFile("ca.crt")
caPool := x509.NewCertPool()
caPool.AppendCertsFromPEM(caCert)

tlsConfig := &tls.Config{
	Certificates: []tls.Certificate{cert},
	RootCAs:      caPool,
	MinVersion:   tls.VersionTLS13,
}

cli, err := wsbrokerclient.New(wsbrokerclient.DefaultConfig(),
	wsbrokerclient.WithEndpoint("wss://localhost:8080"),
	wsbrokerclient.WithTLSConfig(tlsConfig),
)
Bearer Token Authentication
cli, err := wsbrokerclient.New(wsbrokerclient.DefaultConfig(),
	wsbrokerclient.WithEndpoint("wss://localhost:8080"),
	wsbrokerclient.WithBearerToken("your-secure-bearer-token"),
)

Core Usage Guide

Dynamic Channel Subscriptions & Streaming
// Stream subscription using Go channel
sub, err := cli.Subscribe(ctx, "orders")
if err != nil {
	log.Fatal(err)
}
defer sub.Unsubscribe()

for evt := range sub.Events() {
	fmt.Printf("Received order event: %s\n", evt.String())
}

// Or manually attach/detach channels
_ = cli.Attach(ctx, "notifications", "billing")
_ = cli.Detach(ctx, "billing")
Event Handlers & Callbacks
// Listen to all messages targeted to "alerts" channel
cli.OnChannel("alerts", func(evt *wsbrokerclient.RawEvent) {
	fmt.Println("Alert received:", evt.String())
})

// Listen to direct messages sent to this client
cli.OnDirect(func(evt *wsbrokerclient.RawEvent) {
	var msg string
	_ = evt.UnmarshalData(&msg)
	fmt.Printf("Direct message from %s: %s\n", evt.Source, msg)
})

// Connection lifecycle callbacks
cli.OnConnect(func() {
	fmt.Println("Connected to WSBroker!")
})

cli.OnDisconnect(func(err error) {
	fmt.Printf("Disconnected from WSBroker: %v\n", err)
})

cli.OnReconnect(func() {
	fmt.Println("Successfully reconnected and re-subscribed!")
})
Generic Strongly-Typed Listeners & Subscriptions

For type-safe message handling, WSBrokerClient offers generic helper functions that automatically decode incoming RawEvent JSON payloads into strongly-typed *wsbrokerclient.Event[T] structures.

type SensorTelemetry struct {
	DeviceID    string  `json:"device_id"`
	Temperature float64 `json:"temperature"`
	Humidity    float64 `json:"humidity"`
}

// 1. Strongly-typed listener by EventType with optional error handler
unsub := wsbrokerclient.OnTyped[SensorTelemetry](cli, "sensor/telemetry", func(evt *wsbrokerclient.Event[SensorTelemetry]) {
	fmt.Printf("[%s] Temp: %.1f°C, Humidity: %.1f%%\n", evt.Data.DeviceID, evt.Data.Temperature, evt.Data.Humidity)
}, func(raw *wsbrokerclient.RawEvent, err error) {
	log.Printf("Failed to unmarshal telemetry event: %v", err)
})
defer unsub()

// 2. Strongly-typed channel listener
_ = wsbrokerclient.OnChannelTyped[SensorTelemetry](cli, "telemetry", func(evt *wsbrokerclient.Event[SensorTelemetry]) {
	fmt.Printf("Channel telemetry: %+v\n", evt.Data)
})

// 3. Strongly-typed streaming subscription
sub, err := wsbrokerclient.SubscribeTyped[SensorTelemetry](ctx, cli, "telemetry")
if err != nil {
	log.Fatal(err)
}
defer sub.Unsubscribe()

for evt := range sub.Events() {
	fmt.Printf("Streamed event: %+v\n", evt.Data)
}
Custom Domain Events & Type Registry

WSBrokerClient includes a thread-safe global payload registry (RegisterPayload[T]) allowing applications to register domain-specific payload structs associated with custom EventType identifiers.

When receiving dynamic events via raw.GetData() or wsbrokerclient.UnmarshalDynamic(raw), the client automatically unmarshals into the registered Go struct without reflection overhead.

package rfidclient

import "github.com/je4/wsbrokerclient"

const TypeTagRead wsbrokerclient.EventType = "rfid/tag_read"

type TagReadData struct {
	EPC     string  `json:"epc"`
	RSSI    float64 `json:"rssi"`
	Antenna int     `json:"antenna"`
}

func init() {
	// Register TagReadData for automatic dynamic unmarshaling (panics on duplicates)
	wsbrokerclient.RegisterPayload[TagReadData](TypeTagRead)
}

// In event handler:
func HandleIncomingEvent(raw *wsbrokerclient.RawEvent) {
	data, err := raw.GetData()
	if err != nil {
		log.Printf("Failed to decode data: %v", err)
		return
	}

	switch v := data.(type) {
	case *TagReadData:
		fmt.Printf("RFID Tag Read: EPC=%s RSSI=%.1f\n", v.EPC, v.RSSI)
	default:
		fmt.Printf("Other payload: %v\n", v)
	}
}
Direct Client-to-Client Messaging
// Send a direct message to a specific client identifier ("worker-42")
err := cli.SendDirect(ctx, "worker-42", map[string]string{
	"task": "process_chunk",
	"chunk_id": "9812",
})
Publishing & Broadcasting
// Broadcast structured JSON to all subscribers of "events"
err := cli.Broadcast(ctx, "events", map[string]any{
	"event": "user_signup",
	"user_id": 1042,
})
Request-Response & RPC Patterns

WSBrokerClient provides built-in correlation mechanisms for synchronous and streaming Request-Response workflows over asynchronous WebSocket connections. Responses are correlated either by matching the response's RefID to the request's evt.ID, or by matching Session.

API Methods Overview
Method Behavior Description
cli.Request(ctx, evt) / cli.Request1(ctx, evt) Synchronous (1:1) Generates evt.ID (if missing), sends the event, and blocks until a single correlated response arrives or ctx expires.
cli.Request0(ctx, evt) Fire-and-Forget Generates evt.ID (if missing) and sends the event immediately without registering waiters or waiting for responses.
cli.RequestN(ctx, evt, numResults, ch) Multi-Response Streaming Sends evt, streams up to numResults correlated incoming responses into ch, and returns when all responses are collected or ctx expires.
cli.Reply(ctx, reqEvt, data) Responder Helper Creates a correlated reply event (RefID = reqEvt.ID, preserving reqEvt.Session) and sends it back to reqEvt.Source.
cli.ReplyType(ctx, reqEvt, type, data) Responder Helper Same as Reply(), but allows specifying a custom EventType.
Usage Examples
// --- Requester side ---

// 1. Single synchronous Request-Response (Request / Request1)
reqEvt, _ := wsbrokerclient.NewMessageEvent("", "worker-01", "get_status")
respEvt, err := cli.Request(ctx, reqEvt)
if err != nil {
	log.Fatalf("Request failed: %v", err)
}
var status string
_ = respEvt.UnmarshalData(&status)
fmt.Printf("Received response: %s\n", status)

// 2. Fire-and-forget Request (Request0)
// Sends with guaranteed Event ID without blocking for responses
_ = cli.Request0(ctx, reqEvt)

// 3. Multi-Response Streaming (RequestN)
// Query multiple workers across a channel and collect up to N correlated responses
broadcastReq, _ := wsbrokerclient.NewMessageEvent("", "cluster-workers", "ping_all")
respCh := make(chan *wsbrokerclient.RawEvent, 5)

// RequestN streams up to 3 responses into respCh or returns on ctx timeout
go func() {
	err := cli.RequestN(ctx, broadcastReq, 3, respCh)
	if err != nil {
		log.Printf("RequestN finished: %v", err)
	}
}()

// 4. Replying to a Request
cli.OnDirect(func(evt *wsbrokerclient.RawEvent) {
	var query string
	_ = evt.UnmarshalData(&query)

	// Reply automatically preserves RefID = evt.ID and correlation sessions
	_ = cli.Reply(ctx, evt, "result-for-"+query)
})
NTP & Clock Synchronization

WSBrokerClient provides integrated NTP time synchronization over the WebSocket connection, allowing clients to measure latency and clock offset against the broker without needing direct UDP access:

// 1. Measure clock offset against the broker's NTP server
offset, err := cli.SyncNTP(ctx)
if err != nil {
	log.Fatalf("NTP sync failed: %v", err)
}
fmt.Printf("Measured clock offset: %v\n", offset)

// 2. Obtain NTP-synchronized time
synchronizedTime := cli.Time()
fmt.Printf("NTP-synchronized local time: %v\n", synchronizedTime)

// 3. Query detailed NTP response
ntpResp, err := cli.NTP(ctx)
if err == nil {
	fmt.Printf("Stratum: %d, Precision: %v, RTT: %v\n", ntpResp.Stratum, ntpResp.Precision, ntpResp.RTT)
}
Heartbeat & Ping/Pong Handling

WSBrokerClient automatically maintains connection health through periodic keepalive frames and automatic heartbeat replies:

  • Automatic Server Ping Response: The client automatically intercepts server TypePing events and responds immediately with a correlated TypePong envelope (RefID = ping.ID).
  • Periodic Client Keepalive: Configured via Config.PingInterval (defaults to 20 seconds).
  • Manual Ping: Use cli.Ping(ctx) to explicitly verify round-trip connectivity to the server.

REST Management API Client

WSBrokerClient includes a dedicated REST API client for interacting with WSBroker's administrative endpoints:

import (
	"context"
	"fmt"

	"github.com/je4/wsbrokerclient"
)

func main() {
	ctx := context.Background()

	restCli, err := wsbrokerclient.NewRESTClient(wsbrokerclient.RESTConfig{
		BaseURL: "https://localhost:8080",
		Bearer:  "secret-token",
		// TLSCertLoader or TLSConfig can also be configured here for mTLS REST access
	})
	if err != nil {
		panic(err)
	}
	defer restCli.Close()

	// 1. Health-check
	pong, _ := restCli.Ping(ctx)
	fmt.Println("Ping status:", pong)

	// 2. Publish to channel
	resp, _ := restCli.PublishToChannel(ctx, "alerts", "rest-admin", "Maintenance scheduled")
	fmt.Printf("Published to %d subscribers\n", resp.Subscribers)

	// 3. List active channels
	channels, _ := restCli.GetChannels(ctx)
	for _, ch := range channels {
		fmt.Printf("Channel %s: %d active clients\n", ch.Name, ch.Subscribers)
	}

	// 4. Force disconnect a client
	_ = restCli.DisconnectClient(ctx, "bad-client-node")
}

Demo Application (wschat)

A complete reference implementation featuring an interactive HTMX web chat interface, mTLS with certloader, dynamic channels, and lifecycle management is available in the demo/wschat directory.

See demo/wschat/README.md for detailed documentation and instructions on running the demo.


Configuration Reference

Client Configuration (client.Config)
Field Type Default Description
Endpoint string "" Target server URL (e.g. wss://localhost:8080).
ClientName string Auto-generated Unique client identifier.
InitialChannels []string nil Channels to subscribe to upon connection.
Mode ConnectionMode ModeRW ("rw") Access permission mode: ModeRW ("rw"), ModeRO ("ro"), or ModeWO ("wo").
Bearer string "" Bearer authentication token.
TLSConfig *tls.Config nil Custom standard TLS configuration.
TLSCertLoader *loader.Config nil Dynamic mTLS certificate loader config.
AutoReconnect bool true Enables automatic reconnection on disconnect.
ReconnectInterval time.Duration 1s Initial wait duration for reconnect attempts.
MaxReconnectInterval time.Duration 30s Maximum exponential backoff interval.
ReconnectBackoffFactor float64 1.5 Backoff multiplier per attempt.
MaxReconnectAttempts int 0 (infinite) Max reconnection retries before stopping.
PingInterval time.Duration 20s Periodic heartbeat ping interval (0 = disabled).
ConnectTimeout time.Duration 10s Timeout for connection handshake.
WriteTimeout time.Duration 5s Timeout for writing frames.

License

Copyright © 2024-2026 Jürgen Enge / Universitätsbibliothek Basel.

Licensed under the Apache License, Version 2.0.

Documentation

Overview

Package wsbrokerclient provides a high-performance, mTLS-enabled Go client library for WSBroker, featuring automatic reconnection, dynamic channel subscriptions, point-to-point and broadcast messaging, and RESTful management APIs.

Index

Constants

View Source
const (
	TypeAttach              = event.TypeAttach
	TypeDetach              = event.TypeDetach
	TypeMessage             = event.TypeMessage
	TypeFile                = event.TypeFile
	TypePing                = event.TypePing
	TypePong                = event.TypePong
	TypeNTPQuery            = event.TypeNTPQuery
	TypeNTPResponse         = event.TypeNTPResponse
	TypeNTPError            = event.TypeNTPError
	TypeChannelInfoQuery    = event.TypeChannelInfoQuery
	TypeChannelInfoResponse = event.TypeChannelInfoResponse
	TypeChannelInfoError    = event.TypeChannelInfoError
)

Standard EventType constants.

View Source
const (
	StateDisconnected = client.StateDisconnected
	StateConnecting   = client.StateConnecting
	StateConnected    = client.StateConnected
	StateReconnecting = client.StateReconnecting
	StateClosed       = client.StateClosed
)

Standard ConnectionState constants.

View Source
const (
	ModeRW = client.ModeRW
	ModeRO = client.ModeRO
	ModeWO = client.ModeWO
)

Standard ConnectionMode constants.

Variables

View Source
var (
	WithEndpoint          = client.WithEndpoint
	WithClientName        = client.WithClientName
	WithInitialChannels   = client.WithInitialChannels
	WithMode              = client.WithMode
	WithBearerToken       = client.WithBearerToken
	WithTLSConfig         = client.WithTLSConfig
	WithTLSCertLoader     = client.WithTLSCertLoader
	WithAutoReconnect     = client.WithAutoReconnect
	WithReconnectStrategy = client.WithReconnectStrategy
	WithPingInterval      = client.WithPingInterval
	WithReadLimit         = client.WithReadLimit
	WithConnectTimeout    = client.WithConnectTimeout
	WithWriteTimeout      = client.WithWriteTimeout
	WithLogger            = client.WithLogger
)

Functional options re-exported from client package.

View Source
var (
	NewEvent               = event.NewEvent
	NewMessageEvent        = event.NewMessageEvent
	NewRawEvent            = event.NewRawEvent
	NewFileMessage         = event.NewFileMessage
	NewReplyEvent          = event.NewReplyEvent
	NewWSMessage           = event.NewWSMessage
	GenerateEventID        = event.GenerateEventID
	GenerateSessionID      = client.GenerateSessionID
	RegisterPayloadFactory = event.RegisterPayloadFactory
	GetPayloadUnmarshaler  = event.GetPayloadUnmarshaler
)

Event constructors re-exported from event package.

Functions

func RegisterPayload

func RegisterPayload[T any](eventType EventType)

RegisterPayload associates an EventType with a concrete payload type T in the global registry.

func UnmarshalDynamic

func UnmarshalDynamic(raw *RawEvent) (any, error)

UnmarshalDynamic unmarshals a RawEvent's data payload according to the type registry.

Types

type BaseEvent

type BaseEvent = event.BaseEvent

BaseEvent encapsulates all transport, routing, and correlation metadata.

type BrokerClient

type BrokerClient = client.BrokerClient

BrokerClient is an alias for ClientInterface for compatibility with downstream controllers and clients.

type ChannelInfo

type ChannelInfo = event.ChannelInfo

ChannelInfo holds channel subscriber and client details.

type Client

type Client = client.Client

Client is the WebSocket client for WSBroker.

func New

func New(cfg Config, opts ...Option) (*Client, error)

New creates a new WSBroker WebSocket client.

type ClientInterface

type ClientInterface = client.ClientInterface

ClientInterface defines the standard interface for communicating with a WSBroker server.

type Config

type Config = client.Config

Config defines client configuration options.

func DefaultConfig

func DefaultConfig() Config

DefaultConfig returns default client configuration.

type ConnectionMode

type ConnectionMode = client.ConnectionMode

ConnectionMode specifies the access permission mode of a WebSocket connection.

func ParseConnectionMode

func ParseConnectionMode(s string) (ConnectionMode, error)

ParseConnectionMode parses and validates a string into a ConnectionMode.

type ConnectionState

type ConnectionState = client.ConnectionState

ConnectionState represents the state of the connection.

type Event

type Event[T any] = event.Event[T]

Event is the standardized generic message envelope coupling transport metadata with a domain payload.

func NewEventTyped

func NewEventTyped[T any](eventType EventType, source, target string, data T) (*Event[T], error)

NewEventTyped constructs a strongly-typed Event[T] with generated ID and metadata.

func RequestPayload

func RequestPayload[Resp any, Req any](ctx context.Context, c ClientInterface, target string, reqType event.EventType, payload Req) (*Event[Resp], error)

RequestPayload creates and sends a typed request, returning a strongly-typed response.

func RequestTyped

func RequestTyped[Resp any](ctx context.Context, c ClientInterface, evt *RawEvent) (*Event[Resp], error)

RequestTyped sends a RawEvent request and unmarshals the correlated response payload into Resp.

func ToTyped

func ToTyped[T any](raw *RawEvent, expectedTypes ...EventType) (*Event[T], error)

ToTyped converts a RawEvent into a strongly-typed Event[T] by unmarshaling its JSON payload into T.

type EventHandler

type EventHandler = client.EventHandler

EventHandler is a callback invoked when an event is received.

type EventType

type EventType = event.EventType

EventType is the category of message.

type FileMessage

type FileMessage = event.FileMessage

FileMessage represents a file attachment payload.

type NTPQueryOptions

type NTPQueryOptions = ntp.QueryOptions

NTPQueryOptions holds options for querying NTP time.

type NTPResponse

type NTPResponse = ntp.Response

NTPResponse is the NTP query response from github.com/beevik/ntp.

type Option

type Option = client.Option

Option modifies client configuration.

type PayloadUnmarshaler

type PayloadUnmarshaler = event.PayloadUnmarshaler

PayloadUnmarshaler defines a factory function that decodes raw JSON payload into a concrete type.

type PublishResponse

type PublishResponse = restclient.PublishResponse

PublishResponse is returned after a REST publish.

type RESTClient

type RESTClient = restclient.RESTClient

RESTClient is the HTTP client for WSBroker REST APIs.

func NewRESTClient

func NewRESTClient(cfg RESTConfig, opts ...RESTOption) (*RESTClient, error)

NewRESTClient creates a new WSBroker REST client.

type RESTConfig

type RESTConfig = restclient.Config

RESTConfig defines configuration for RESTClient.

func DefaultRESTConfig

func DefaultRESTConfig() RESTConfig

DefaultRESTConfig returns default REST client configuration.

type RESTOption

type RESTOption = restclient.Option

RESTOption modifies RESTClient configuration.

type RawEvent

type RawEvent = event.RawEvent

RawEvent represents an event envelope with unparsed JSON payload.

func ToRaw

func ToRaw[T any](evt *Event[T]) (*RawEvent, error)

ToRaw converts a typed Event[T] into a RawEvent by JSON-marshaling its payload into jsontext.Value.

type Subscription

type Subscription = client.Subscription

Subscription represents an active channel subscription stream.

type TypedEventHandler

type TypedEventHandler[T any] = client.TypedEventHandler[T]

TypedEventHandler is a callback function invoked with a strongly-typed Event[T].

type TypedSubscription

type TypedSubscription[T any] = client.TypedSubscription[T]

TypedSubscription represents an active streaming channel subscription producing strongly-typed events.

func SubscribeTyped

func SubscribeTyped[T any](ctx context.Context, c ClientInterface, channel string, bufferSize ...int) (TypedSubscription[T], error)

SubscribeTyped returns a streaming TypedSubscription for the given channel, emitting decoded *Event[T].

type UnsubscribeFunc

type UnsubscribeFunc = client.UnsubscribeFunc

UnsubscribeFunc stops a subscription or listener.

func OnChannelTyped

func OnChannelTyped[T any](c ClientInterface, channel string, handler TypedEventHandler[T], errHandler ...func(raw *RawEvent, err error)) UnsubscribeFunc

OnChannelTyped registers a listener for events targeted to a channel with automatic unmarshaling into Event[T].

func OnEventTyped

func OnEventTyped[T any](c ClientInterface, handler TypedEventHandler[T], errHandler ...func(raw *RawEvent, err error)) UnsubscribeFunc

OnEventTyped registers a global event listener with automatic unmarshaling into Event[T].

func OnTyped

func OnTyped[T any](c ClientInterface, eventType EventType, handler TypedEventHandler[T], errHandler ...func(raw *RawEvent, err error)) UnsubscribeFunc

OnTyped registers a listener for events of a specific EventType with automatic unmarshaling into Event[T].

type WSMessage

type WSMessage = event.WSMessage

WSMessage represents a logged WebSocket message event for telemetry and debugging.

Directories

Path Synopsis
cmd
wschat command
demo
pkg
client
Package client provides a robust, mTLS-capable WebSocket client for WSBroker with automatic reconnection, dynamic channel subscription tracking, and event routing.
Package client provides a robust, mTLS-capable WebSocket client for WSBroker with automatic reconnection, dynamic channel subscription tracking, and event routing.
event
Package event defines the event envelope data structures, event types, and serialization helpers used by wsbroker clients and servers.
Package event defines the event envelope data structures, event types, and serialization helpers used by wsbroker clients and servers.
ntp
restclient
Package restclient provides a client for WSBroker's HTTP REST management and publish APIs.
Package restclient provides a client for WSBroker's HTTP REST management and publish APIs.

Jump to

Keyboard shortcuts

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