Version: 0.1.0 Last Updated: November 2025
Creates a new CloudBridge client with the specified options.
func NewClient(opts ...Option) (*Client, error)Parameters:
opts- Variadic configuration options
Returns:
*Client- Configured client instanceerror- Configuration or initialization error
Example:
client, err := cloudbridge.NewClient(
cloudbridge.WithToken("token"),
cloudbridge.WithRegion("eu-central"),
)Starts accepting incoming connections and handling tunnels. This method blocks until the context is cancelled.
func (c *Client) Serve(ctx context.Context) errorParameters:
ctx- Context for cancellation
Returns:
error- Runtime error
Example:
go func() {
if err := client.Serve(ctx); err != nil {
log.Printf("Serve error: %v", err)
}
}()Establishes a P2P connection to the specified peer.
func (c *Client) Connect(ctx context.Context, peerID string) (Connection, error)Parameters:
ctx- Context for cancellation and timeoutpeerID- Target peer identifier
Returns:
Connection- Active connection to peererror- Connection error
Errors:
ErrAuth- Authentication failureErrPeerNotFound- Peer not availableErrTimeout- Connection timeoutErrNetwork- Network error
Example:
conn, err := client.Connect(ctx, "peer-123")
if err != nil {
return err
}
defer conn.Close()Creates a secure tunnel with the specified configuration.
func (c *Client) CreateTunnel(ctx context.Context, config TunnelConfig) (Tunnel, error)Parameters:
ctx- Context for cancellationconfig- Tunnel configuration
Returns:
Tunnel- Active tunnel instanceerror- Tunnel creation error
Example:
tunnel, err := client.CreateTunnel(ctx, cloudbridge.TunnelConfig{
LocalPort: 8080,
RemotePeer: "peer-123",
RemotePort: 3000,
})Joins a mesh network with the specified name.
func (c *Client) JoinMesh(ctx context.Context, networkName string) (Mesh, error)Parameters:
ctx- Context for cancellationnetworkName- Name of mesh network
Returns:
Mesh- Mesh network instanceerror- Join error
Example:
mesh, err := client.JoinMesh(ctx, "my-network")
if err != nil {
return err
}
defer mesh.Leave()Registers a service for discovery.
func (c *Client) RegisterService(ctx context.Context, config ServiceConfig) errorParameters:
ctx- Context for cancellationconfig- Service configuration
Returns:
error- Registration error
Example:
err := client.RegisterService(ctx, cloudbridge.ServiceConfig{
Name: "my-api",
Port: 8080,
Tags: []string{"http", "api"},
})Discovers services by name.
func (c *Client) DiscoverServices(ctx context.Context, serviceName string) ([]Service, error)Parameters:
ctx- Context for cancellationserviceName- Service name to discover
Returns:
[]Service- List of discovered serviceserror- Discovery error
Example:
services, err := client.DiscoverServices(ctx, "my-api")Checks the health of the client connection.
func (c *Client) Health(ctx context.Context) (*Health, error)Parameters:
ctx- Context for cancellation
Returns:
*Health- Health statuserror- Health check error
Example:
health, err := client.Health(ctx)
if err != nil {
return err
}
log.Printf("Status: %s, Latency: %v", health.Status, health.Latency)Registers a callback for connection events.
func (c *Client) OnConnect(callback func(peer string))Parameters:
callback- Function called when connected
Example:
client.OnConnect(func(peer string) {
log.Printf("Connected to: %s", peer)
})Registers a callback for disconnection events.
func (c *Client) OnDisconnect(callback func(peer string, err error))Parameters:
callback- Function called when disconnected
Example:
client.OnDisconnect(func(peer string, err error) {
log.Printf("Disconnected from %s: %v", peer, err)
})Registers a callback for reconnection events.
func (c *Client) OnReconnect(callback func(peer string))Parameters:
callback- Function called when reconnected
Example:
client.OnReconnect(func(peer string) {
log.Printf("Reconnected to: %s", peer)
})Closes the client and releases all resources.
func (c *Client) Close() errorReturns:
error- Close error
Example:
defer client.Close()Reads data from the connection.
func (c *Connection) Read(b []byte) (int, error)Parameters:
b- Buffer to read into
Returns:
int- Number of bytes readerror- Read error
Writes data to the connection.
func (c *Connection) Write(b []byte) (int, error)Parameters:
b- Data to write
Returns:
int- Number of bytes writtenerror- Write error
Closes the connection.
func (c *Connection) Close() errorReturns:
error- Close error
Returns the peer identifier.
func (c *Connection) PeerID() stringReturns:
string- Peer identifier
Returns connection metrics.
func (c *Connection) Metrics() (*ConnectionMetrics, error)Returns:
*ConnectionMetrics- Connection metricserror- Metrics error
Example:
metrics, err := conn.Metrics()
if err != nil {
return err
}
log.Printf("RTT: %v, Bytes sent: %d", metrics.RTT, metrics.BytesSent)Sets the read and write deadlines.
func (c *Connection) SetDeadline(t time.Time) errorParameters:
t- Deadline time
Returns:
error- Set deadline error
Sets the read deadline.
func (c *Connection) SetReadDeadline(t time.Time) errorSets the write deadline.
func (c *Connection) SetWriteDeadline(t time.Time) errorReturns the remote peer ID.
func (t *Tunnel) RemotePeer() stringReturns:
string- Remote peer identifier
Returns the local port.
func (t *Tunnel) LocalPort() intReturns:
int- Local port number
Returns the remote port.
func (t *Tunnel) RemotePort() intReturns:
int- Remote port number
Closes the tunnel.
func (t *Tunnel) Close() errorReturns:
error- Close error
Returns the network name.
func (m *Mesh) NetworkName() stringReturns:
string- Network name
Broadcasts a message to all peers.
func (m *Mesh) Broadcast(ctx context.Context, data []byte) errorParameters:
ctx- Context for cancellationdata- Message data
Returns:
error- Broadcast error
Example:
err := mesh.Broadcast(ctx, []byte("Hello mesh!"))Sends a message to a specific peer.
func (m *Mesh) Send(ctx context.Context, peerID string, data []byte) errorParameters:
ctx- Context for cancellationpeerID- Target peer identifierdata- Message data
Returns:
error- Send error
Example:
err := mesh.Send(ctx, "peer-123", []byte("Direct message"))Returns a channel for receiving messages.
func (m *Mesh) Messages() <-chan MessageReturns:
<-chan Message- Message receive channel
Example:
for msg := range mesh.Messages() {
log.Printf("From %s: %s", msg.From, string(msg.Data))
}Returns a list of connected peers.
func (m *Mesh) Peers() []stringReturns:
[]string- List of peer identifiers
Example:
peers := mesh.Peers()
log.Printf("Connected to %d peers", len(peers))Leaves the mesh network.
func (m *Mesh) Leave() errorReturns:
error- Leave error
Sets the authentication token.
func WithToken(token string) OptionParameters:
token- API authentication token
Sets the preferred region.
func WithRegion(region string) OptionParameters:
region- Region identifier (e.g., "eu-central")
Sets the operation timeout.
func WithTimeout(timeout time.Duration) OptionParameters:
timeout- Timeout duration
Sets the log level.
func WithLogLevel(level string) OptionParameters:
level- Log level ("debug", "info", "warn", "error")
Sets the retry policy.
func WithRetryPolicy(policy RetryPolicy) OptionParameters:
policy- Retry policy configuration
Sets the protocol preferences.
func WithProtocols(protocols ...Protocol) OptionParameters:
protocols- Ordered list of protocols
Disables TLS certificate verification.
func WithInsecureSkipVerify(skip bool) OptionParameters:
skip- Whether to skip verification
Warning: Not recommended for production use.
Checks if an error is an authentication error.
func IsAuthError(err error) boolChecks if an error is a network error.
func IsNetworkError(err error) boolChecks if an error is a peer not found error.
func IsPeerNotFoundError(err error) boolChecks if an error is a timeout error.
func IsTimeoutError(err error) booltype Health struct {
Status string
Latency time.Duration
ConnectedPeers int
}type ConnectionMetrics struct {
BytesSent uint64
BytesReceived uint64
RTT time.Duration
Connected bool
ConnectedAt time.Time
}type TunnelConfig struct {
LocalPort int
RemotePeer string
RemotePort int
Protocol Protocol
}type ServiceConfig struct {
Name string
Port int
Tags []string
}type Service struct {
Name string
Address string
Port int
Tags []string
Healthy bool
}type Message struct {
From string
Data []byte
}type Protocol string
const (
ProtocolQUIC Protocol = "quic"
ProtocolGRPC Protocol = "grpc"
ProtocolWebSocket Protocol = "websocket"
ProtocolTCP Protocol = "tcp"
)type RetryPolicy struct {
MaxRetries int
InitialDelay time.Duration
MaxDelay time.Duration
Multiplier float64
}CLOUDBRIDGE_TOKEN- Authentication tokenCLOUDBRIDGE_REGION- Preferred regionCLOUDBRIDGE_LOG_LEVEL- Log levelCLOUDBRIDGE_TIMEOUT- Operation timeout
- All context-aware methods respect cancellation
- Timeouts are configurable per operation
- Automatic retry on transient failures
- Connection pooling for performance
- Metrics collection for observability