channelize

package module
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Feb 28, 2023 License: MIT Imports: 13 Imported by: 0

README

channelize

build Go Report Card codecov Go Reference

Channelize is a websocket framework based on gorilla websocket that manages inbound and outbound streams. It gives the client the option of receiving events in different channels. Channelize is useful when your websocket server is reading different types of events from a message broker. e.g., you might have multiple kafka topics or NATs subjects.

Channelize gives you this option to categorize the outbound messages. You can choose a name for each event type and register them as a channel in the Channelize and send messages to those channels. Then client can subscribe to one or more channels to receive the streams.

The main usage of Channelize is in cryptocurrency exchanges, when you have multiple channels like user's balances, user's orders, user's trades, market trades, mini-ticker data, etc. The front-end should be able to subscribe to the related channels in each page and unsubscribe those that doesn't need any more.

channelize

Table of Contents

Install

To use Channelize, first you should use go get command to get the latest version of this library:

go get -u github.com/hmdsefi/channelize

Next step is importing channelize to your project:

import "github.com/hmdsefi/channelize"
How to use

To use Channelize, first you should know about the channel concept. A channel is a unique name for a stream of events that have the same type. A channel can be public or private. A public channel sends the outbound messages to the all available connections that subscribed to that channel. A private channel needs authentication, it sends the outbound messages to a specific connection that already subscribed to that private channel with a valid token.

Public channels

To use public channels, first you should register your public channels with one of the following functions:

channel := channelize.RegisterPublicChannel("my-public-channel")
channels := channelize.RegisterPublicChannels("my-public-channel1", "my-public-channel2")

Registering same channel more than once won't break anything. It will override the previous one. To send messages to the channels, you should create an instance of Channelize struct to be able to use the library APIs.

chlz := channelize.NewChannelize()

Then you can call the following function in your consumer function to send the messages to the proper channel:

err := chlz.SendPublicMessage(ctx, channel, message)
if err != nil {
return err
}

Channelize struct gives you this option to create your handler or using the handler that channelize creates for you. If you want to implement the handler by yourself, then you can use the following method:

connection := chlz.CreateConnection(ctx context.Context, wsConn *websocket.Conn, options ...conn.Option)

Or you can create the handler by calling the following method:

handler := chlz.MakeHTTPHandler(appCtx context.Context, upgrader websocket.Upgrader, options ...conn.Option)

To subscribe to one or more public channels, client should send the following message to the server:

{
  "type": "subscribe",
  "params": {
    "channels": [
      "my-public-channel1",
      "my-public-channel2"
    ]
  }
}

To unsubscribe one or more channels, client should send the following message to the server:

{
  "type": "unsubscribe",
  "params": {
    "channels": [
      "my-public-channel1"
    ]
  }
}
Private channels

To use private channels, first you should register your private channels with one of the following functions:

channel := channelize.RegisterPrivateChannel("my-private-channel")
channels := channelize.RegisterPrivateChannels("my-private-channel1", "my-private-channel2")

Private channels need authentication. To provide authentication you should implement the function type that is defined in auth package:

type AuthenticateFunc func (token string) (*Token, error)

Then you should pass as an option to the Channelize constructor:

chlz := channelize.NewChannelize(channelize.WithAuthFunc(MyAuthFunc)))

You can use CreateConnection or MakeHTTPHandler to create the connection for the client just like public channels. To send the message to the client you should use the following function:

err := chlz.SendPrivateMessage(ctx, channel, userID, message)
if err != nil {
return err
}

To subscribe to private channels, client should fill the token field with the proper value:

{
  "type": "subscribe",
  "params": {
    "channels": [
      "my-public-channel1",
      "my-private-channel1"
    ],
    "token": "618bb5b00161cbd68bc744b2ea84c96601d6705f31cc7d32e01c3371f6e7"
  }
}

To unsubscribe, client can use the following message:

{
  "type": "unsubscribe",
  "params": {
    "channels": [
      "my-private-channel1"
    ]
  }
}
Metrics

You can find the following prometheus metrics in Channelize:

METRIC TYPE DESCRIPTION
open_connections gauge Number of open connections.
private_connections gauge Number of private connections.
private_connections_storage_length gauge Number of stored private connections.
open_connections_storage_length gauge Number of stored open connections.
subscribed_channels_storage_length gauge Number of subscribed channels that are stored.

License

MIT License, please see LICENSE for details.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func RegisterPrivateChannel

func RegisterPrivateChannel(channelStr string) channel.Channel

RegisterPrivateChannel creates and registers a new channel by calling the internal channel.RegisterPrivateChannel function. It returns the created channel.

func RegisterPrivateChannels

func RegisterPrivateChannels(channels ...string) []channel.Channel

RegisterPrivateChannels creates and registers a list of input channels by calling the internal channel.RegisterPrivateChannels function. It returns a list of created channels.

func RegisterPublicChannel

func RegisterPublicChannel(channelStr string) channel.Channel

RegisterPublicChannel creates and registers a new channel by calling the internal channel.RegisterPublicChannel function. It returns the created channel.

func RegisterPublicChannels

func RegisterPublicChannels(channels ...string) []channel.Channel

RegisterPublicChannels creates and registers a list of input channels by calling the internal channel.RegisterPublicChannels function. It returns a list of created channels.

func WithAuthFunc

func WithAuthFunc(authFunc auth.AuthenticateFunc) func(config *Config)

func WithLogger

func WithLogger(logger log.Logger) func(config *Config)

func WithOutboundBufferSize

func WithOutboundBufferSize(size int) conn.Option

WithOutboundBufferSize sets the outbound buffer size.

func WithPingMessageFunc

func WithPingMessageFunc(messageFunc conn.PingMessageFunc) conn.Option

WithPingMessageFunc sets the ping function. Client send customized ping messages.

func WithPingPeriod

func WithPingPeriod(duration time.Duration) conn.Option

WithPingPeriod sets the ping period.

func WithPongWait

func WithPongWait(duration time.Duration) conn.Option

WithPongWait sets the pong wait duration.

Types

type Channelize

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

Channelize wraps all the internal implementations and restricts the exposed functionalities to reduce the public API surface.

It provides more APIs like HTTP handlers to facilitate the API usage.

func NewChannelize

func NewChannelize(options ...Option) *Channelize

NewChannelize creates new instance of Channelize struct. It uses in-memory storage by default to store the connections and mapping between the connections and channels.

func (*Channelize) CreateConnection

func (c *Channelize) CreateConnection(ctx context.Context, wsConn *websocket.Conn, options ...conn.Option) *conn.Connection

CreateConnection creates a `conn.Connection` object with the input options.

func (*Channelize) MakeHTTPHandler

func (c *Channelize) MakeHTTPHandler(appCtx context.Context, upgrader websocket.Upgrader, options ...conn.Option) http.HandlerFunc

MakeHTTPHandler makes a built-in HTTP handler function. The client should provide the websocket.Upgrader. It automatically creates the websocket.Conn and conn.Connection.

func (*Channelize) SendPrivateMessage

func (c *Channelize) SendPrivateMessage(ctx context.Context, ch channel.Channel, userID string, message interface{}) error

SendPrivateMessage sends the message to the input channel.

func (*Channelize) SendPublicMessage

func (c *Channelize) SendPublicMessage(ctx context.Context, ch channel.Channel, message interface{}) error

SendPublicMessage sends the message to the input channel.

type Config

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

Config represents Channelize configuration.

type Option

type Option func(*Config)

Directories

Path Synopsis
_examples
internal

Jump to

Keyboard shortcuts

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