completed inbound pool. Refactored to inbound/outbound semantics.
This commit is contained in:
@@ -0,0 +1,186 @@
|
||||
package outbound
|
||||
|
||||
import (
|
||||
"context"
|
||||
"git.wisehodl.dev/jay/go-honeybee/transport"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Types
|
||||
|
||||
type WorkerFactory func(ctx context.Context, id string) (Worker, error)
|
||||
|
||||
// Pool Config
|
||||
|
||||
type PoolConfig struct {
|
||||
ConnectionConfig *transport.ConnectionConfig
|
||||
WorkerFactory WorkerFactory
|
||||
WorkerConfig *WorkerConfig
|
||||
}
|
||||
|
||||
type PoolOption func(*PoolConfig) error
|
||||
|
||||
func NewPoolConfig(options ...PoolOption) (*PoolConfig, error) {
|
||||
conf := GetDefaultPoolConfig()
|
||||
if err := applyPoolOptions(conf, options...); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := ValidatePoolConfig(conf); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return conf, nil
|
||||
}
|
||||
|
||||
func GetDefaultPoolConfig() *PoolConfig {
|
||||
return &PoolConfig{
|
||||
ConnectionConfig: nil,
|
||||
WorkerFactory: nil,
|
||||
WorkerConfig: nil,
|
||||
}
|
||||
}
|
||||
|
||||
func applyPoolOptions(config *PoolConfig, options ...PoolOption) error {
|
||||
for _, option := range options {
|
||||
if err := option(config); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func ValidatePoolConfig(config *PoolConfig) error {
|
||||
var err error
|
||||
|
||||
if config.ConnectionConfig != nil {
|
||||
err = transport.ValidateConnectionConfig(config.ConnectionConfig)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
if config.WorkerConfig != nil {
|
||||
err = ValidateWorkerConfig(config.WorkerConfig)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func WithConnectionConfig(cc *transport.ConnectionConfig) PoolOption {
|
||||
return func(c *PoolConfig) error {
|
||||
err := transport.ValidateConnectionConfig(cc)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
c.ConnectionConfig = cc
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func WithWorkerConfig(wc *WorkerConfig) PoolOption {
|
||||
return func(c *PoolConfig) error {
|
||||
err := ValidateWorkerConfig(wc)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
c.WorkerConfig = wc
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func WithWorkerFactory(wf WorkerFactory) PoolOption {
|
||||
return func(c *PoolConfig) error {
|
||||
c.WorkerFactory = wf
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// Worker Config
|
||||
|
||||
type WorkerConfig struct {
|
||||
KeepaliveTimeout time.Duration
|
||||
MaxQueueSize int
|
||||
}
|
||||
|
||||
type WorkerOption func(*WorkerConfig) error
|
||||
|
||||
func NewWorkerConfig(options ...WorkerOption) (*WorkerConfig, error) {
|
||||
conf := GetDefaultWorkerConfig()
|
||||
if err := applyWorkerOptions(conf, options...); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := ValidateWorkerConfig(conf); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return conf, nil
|
||||
}
|
||||
|
||||
func GetDefaultWorkerConfig() *WorkerConfig {
|
||||
return &WorkerConfig{
|
||||
KeepaliveTimeout: 20 * time.Second,
|
||||
MaxQueueSize: 0, // disabled by default
|
||||
}
|
||||
}
|
||||
|
||||
func applyWorkerOptions(config *WorkerConfig, options ...WorkerOption) error {
|
||||
for _, option := range options {
|
||||
if err := option(config); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func ValidateWorkerConfig(config *WorkerConfig) error {
|
||||
err := validateKeepaliveTimeout(config.KeepaliveTimeout)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
err = validateMaxQueueSize(config.MaxQueueSize)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateMaxQueueSize(value int) error {
|
||||
if value < 0 {
|
||||
return InvalidMaxQueueSize
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateKeepaliveTimeout(value time.Duration) error {
|
||||
if value < 0 {
|
||||
return InvalidKeepaliveTimeout
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// When KeepaliveTimeout is set to zero, keepalive timeouts are disabled.
|
||||
func WithKeepaliveTimeout(value time.Duration) WorkerOption {
|
||||
return func(c *WorkerConfig) error {
|
||||
err := validateKeepaliveTimeout(value)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
c.KeepaliveTimeout = value
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// When MaxQueueSize is set to zero, queue limits are disabled.
|
||||
func WithMaxQueueSize(value int) WorkerOption {
|
||||
return func(c *WorkerConfig) error {
|
||||
err := validateMaxQueueSize(value)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
c.MaxQueueSize = value
|
||||
return nil
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
package outbound
|
||||
|
||||
import (
|
||||
"git.wisehodl.dev/jay/go-honeybee/transport"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestNewPoolConfig(t *testing.T) {
|
||||
conf, err := NewPoolConfig()
|
||||
assert.NoError(t, err)
|
||||
|
||||
assert.Equal(t, conf, &PoolConfig{
|
||||
ConnectionConfig: nil,
|
||||
WorkerConfig: nil,
|
||||
WorkerFactory: nil,
|
||||
})
|
||||
}
|
||||
|
||||
func TestDefaultPoolConfig(t *testing.T) {
|
||||
conf := GetDefaultPoolConfig()
|
||||
|
||||
assert.Equal(t, conf, &PoolConfig{
|
||||
ConnectionConfig: nil,
|
||||
WorkerConfig: nil,
|
||||
WorkerFactory: nil,
|
||||
})
|
||||
}
|
||||
|
||||
func TestApplyPoolOptions(t *testing.T) {
|
||||
conf := &PoolConfig{}
|
||||
err := applyPoolOptions(
|
||||
conf,
|
||||
WithConnectionConfig(&transport.ConnectionConfig{}),
|
||||
)
|
||||
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, 0*time.Second, conf.ConnectionConfig.WriteTimeout)
|
||||
}
|
||||
|
||||
func TestWithConnectionConfig(t *testing.T) {
|
||||
conf := &PoolConfig{}
|
||||
opt := WithConnectionConfig(&transport.ConnectionConfig{WriteTimeout: 1 * time.Second})
|
||||
err := applyPoolOptions(conf, opt)
|
||||
assert.NoError(t, err)
|
||||
assert.NotNil(t, conf.ConnectionConfig)
|
||||
assert.Equal(t, 1*time.Second, conf.ConnectionConfig.WriteTimeout)
|
||||
|
||||
// invalid config is rejected
|
||||
conf = &PoolConfig{}
|
||||
opt = WithConnectionConfig(&transport.ConnectionConfig{WriteTimeout: -1 * time.Second})
|
||||
err = applyPoolOptions(conf, opt)
|
||||
assert.Error(t, err)
|
||||
}
|
||||
|
||||
func TestValidatePoolConfig(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
conf PoolConfig
|
||||
wantErr error
|
||||
wantErrText string
|
||||
}{
|
||||
{
|
||||
name: "valid empty",
|
||||
conf: *&PoolConfig{},
|
||||
},
|
||||
{
|
||||
name: "valid defaults",
|
||||
conf: *GetDefaultPoolConfig(),
|
||||
},
|
||||
{
|
||||
name: "valid complete",
|
||||
conf: PoolConfig{
|
||||
ConnectionConfig: &transport.ConnectionConfig{},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "invalid connection config",
|
||||
conf: PoolConfig{
|
||||
ConnectionConfig: &transport.ConnectionConfig{
|
||||
Retry: &transport.RetryConfig{
|
||||
InitialDelay: 10 * time.Second,
|
||||
MaxDelay: 1 * time.Second,
|
||||
},
|
||||
},
|
||||
},
|
||||
wantErrText: "initial delay may not exceed maximum delay",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
err := ValidatePoolConfig(&tc.conf)
|
||||
|
||||
if tc.wantErr != nil || tc.wantErrText != "" {
|
||||
if tc.wantErr != nil {
|
||||
assert.ErrorIs(t, err, tc.wantErr)
|
||||
}
|
||||
|
||||
if tc.wantErrText != "" {
|
||||
assert.ErrorContains(t, err, tc.wantErrText)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
assert.NoError(t, err)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package outbound
|
||||
|
||||
import "errors"
|
||||
import "fmt"
|
||||
|
||||
var (
|
||||
// Config errors
|
||||
InvalidKeepaliveTimeout = errors.New("keepalive timeout cannot be negative")
|
||||
InvalidMaxQueueSize = errors.New("maximum queue size cannot be negative")
|
||||
|
||||
// Pool errors
|
||||
ErrPoolClosed = errors.New("pool is closed")
|
||||
ErrPeerNotFound = errors.New("peer not found")
|
||||
ErrPeerExists = errors.New("peer already exists")
|
||||
|
||||
// Worker errors
|
||||
ErrConnectionUnavailable = errors.New("connection unavailable")
|
||||
)
|
||||
|
||||
func NewConfigError(err error) error {
|
||||
return fmt.Errorf("configuration error: %w", err)
|
||||
}
|
||||
|
||||
func NewPoolError(err error) error {
|
||||
return fmt.Errorf("pool error: %w", err)
|
||||
}
|
||||
|
||||
func NewWorkerError(id string, err error) error {
|
||||
return fmt.Errorf("worker %q error: %w", id, err)
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package outbound
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"git.wisehodl.dev/jay/go-honeybee/honeybeetest"
|
||||
"git.wisehodl.dev/jay/go-honeybee/transport"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"io"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func setupTestConnection(t *testing.T) (
|
||||
conn *transport.Connection,
|
||||
mockSocket *honeybeetest.MockSocket,
|
||||
incomingData chan honeybeetest.MockIncomingData,
|
||||
outgoingData chan honeybeetest.MockOutgoingData,
|
||||
) {
|
||||
t.Helper()
|
||||
|
||||
incomingData = make(chan honeybeetest.MockIncomingData, 10)
|
||||
outgoingData = make(chan honeybeetest.MockOutgoingData, 10)
|
||||
mockSocket = honeybeetest.NewMockSocket()
|
||||
|
||||
mockSocket.CloseFunc = func() error {
|
||||
mockSocket.Once.Do(func() { close(mockSocket.Closed) })
|
||||
return nil
|
||||
}
|
||||
|
||||
mockSocket.ReadMessageFunc = func() (int, []byte, error) {
|
||||
select {
|
||||
case data, ok := <-incomingData:
|
||||
if !ok {
|
||||
return 0, nil, io.EOF
|
||||
}
|
||||
return data.MsgType, data.Data, data.Err
|
||||
case <-mockSocket.Closed:
|
||||
return 0, nil, io.EOF
|
||||
}
|
||||
}
|
||||
|
||||
mockSocket.WriteMessageFunc = func(msgType int, data []byte) error {
|
||||
select {
|
||||
case outgoingData <- honeybeetest.MockOutgoingData{MsgType: msgType, Data: data}:
|
||||
return nil
|
||||
case <-mockSocket.Closed:
|
||||
return io.EOF
|
||||
default:
|
||||
return fmt.Errorf("mock outgoing channel unavailable")
|
||||
}
|
||||
}
|
||||
|
||||
var err error
|
||||
conn, err = transport.NewConnectionFromSocket(mockSocket, nil, nil)
|
||||
assert.NoError(t, err)
|
||||
return
|
||||
}
|
||||
@@ -0,0 +1,242 @@
|
||||
package outbound
|
||||
|
||||
import (
|
||||
"context"
|
||||
"git.wisehodl.dev/jay/go-honeybee/transport"
|
||||
"git.wisehodl.dev/jay/go-honeybee/types"
|
||||
"log/slog"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Types
|
||||
|
||||
type PoolEventKind string
|
||||
|
||||
const (
|
||||
EventConnected PoolEventKind = "connected"
|
||||
EventDisconnected PoolEventKind = "disconnected"
|
||||
)
|
||||
|
||||
type PoolEvent struct {
|
||||
ID string
|
||||
Kind PoolEventKind
|
||||
}
|
||||
|
||||
type InboxMessage struct {
|
||||
ID string
|
||||
Data []byte
|
||||
ReceivedAt time.Time
|
||||
}
|
||||
|
||||
type PoolPlugin struct {
|
||||
Inbox chan<- InboxMessage
|
||||
Events chan<- PoolEvent
|
||||
Errors chan<- error
|
||||
Logger *slog.Logger
|
||||
Dialer types.Dialer
|
||||
ConnectionConfig *transport.ConnectionConfig
|
||||
}
|
||||
|
||||
// Pool
|
||||
|
||||
type Peer struct {
|
||||
id string
|
||||
worker Worker
|
||||
}
|
||||
|
||||
type Pool struct {
|
||||
ctx context.Context
|
||||
cancel context.CancelFunc
|
||||
|
||||
peers map[string]*Peer
|
||||
inbox chan InboxMessage
|
||||
events chan PoolEvent
|
||||
errors chan error
|
||||
|
||||
dialer types.Dialer
|
||||
config *PoolConfig
|
||||
logger *slog.Logger
|
||||
|
||||
mu sync.RWMutex
|
||||
wg sync.WaitGroup
|
||||
closed bool
|
||||
}
|
||||
|
||||
func NewPool(ctx context.Context, config *PoolConfig, logger *slog.Logger,
|
||||
) (*Pool, error) {
|
||||
if config == nil {
|
||||
config = GetDefaultPoolConfig()
|
||||
}
|
||||
|
||||
// If a custom factory is supplied, config.WorkerConfig is not used.
|
||||
// The factory function should be non-blocking or else Connect() may cause
|
||||
// deadlocks.
|
||||
if config.WorkerFactory == nil {
|
||||
config.WorkerFactory = func(
|
||||
ctx context.Context, id string) (Worker, error) {
|
||||
return NewWorker(ctx, id, config.WorkerConfig)
|
||||
}
|
||||
}
|
||||
|
||||
if err := ValidatePoolConfig(config); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
pctx, cancel := context.WithCancel(ctx)
|
||||
|
||||
return &Pool{
|
||||
ctx: pctx,
|
||||
cancel: cancel,
|
||||
peers: make(map[string]*Peer),
|
||||
inbox: make(chan InboxMessage, 256),
|
||||
events: make(chan PoolEvent, 10),
|
||||
errors: make(chan error, 10),
|
||||
dialer: transport.NewDialer(),
|
||||
config: config,
|
||||
logger: logger,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (p *Pool) Peers() []string {
|
||||
p.mu.RLock()
|
||||
defer p.mu.RUnlock()
|
||||
|
||||
ids := make([]string, 0, len(p.peers))
|
||||
for i, _ := range p.peers {
|
||||
ids = append(ids, i)
|
||||
}
|
||||
return ids
|
||||
}
|
||||
|
||||
func (p *Pool) Inbox() <-chan InboxMessage {
|
||||
return p.inbox
|
||||
}
|
||||
|
||||
func (p *Pool) Events() <-chan PoolEvent {
|
||||
return p.events
|
||||
}
|
||||
|
||||
func (p *Pool) Errors() <-chan error {
|
||||
return p.errors
|
||||
}
|
||||
|
||||
func (p *Pool) SetDialer(d types.Dialer) {
|
||||
if d == nil {
|
||||
panic("dialer cannot be nil")
|
||||
}
|
||||
p.dialer = d
|
||||
}
|
||||
|
||||
func (p *Pool) Close() {
|
||||
p.mu.Lock()
|
||||
if p.closed {
|
||||
p.mu.Unlock()
|
||||
return
|
||||
}
|
||||
|
||||
p.closed = true
|
||||
p.cancel() // closes all workers
|
||||
|
||||
// remove all peers
|
||||
p.peers = make(map[string]*Peer)
|
||||
|
||||
p.mu.Unlock()
|
||||
|
||||
go func() {
|
||||
p.wg.Wait()
|
||||
close(p.inbox)
|
||||
close(p.events)
|
||||
close(p.errors)
|
||||
}()
|
||||
}
|
||||
|
||||
func (p *Pool) Connect(id string) error {
|
||||
id, err := transport.NormalizeURL(id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
|
||||
if p.closed {
|
||||
return NewPoolError(ErrPoolClosed)
|
||||
}
|
||||
|
||||
if _, exists := p.peers[id]; exists {
|
||||
return NewPoolError(ErrPeerExists)
|
||||
}
|
||||
|
||||
// The worker factory must be non-blocking to avoid deadlocks
|
||||
worker, err := p.config.WorkerFactory(p.ctx, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var logger *slog.Logger
|
||||
if p.logger != nil {
|
||||
logger = p.logger.With("id", id)
|
||||
}
|
||||
|
||||
pool := PoolPlugin{
|
||||
Inbox: p.inbox,
|
||||
Events: p.events,
|
||||
Errors: p.errors,
|
||||
Logger: logger,
|
||||
Dialer: p.dialer,
|
||||
ConnectionConfig: p.config.ConnectionConfig,
|
||||
}
|
||||
|
||||
p.wg.Add(1)
|
||||
go worker.Start(pool, &p.wg)
|
||||
|
||||
p.peers[id] = &Peer{id: id, worker: worker}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *Pool) Remove(id string) error {
|
||||
id, err := transport.NormalizeURL(id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
|
||||
if p.closed {
|
||||
return NewPoolError(ErrPoolClosed)
|
||||
}
|
||||
|
||||
peer, exists := p.peers[id]
|
||||
if !exists {
|
||||
return NewPoolError(ErrPeerNotFound)
|
||||
}
|
||||
delete(p.peers, id)
|
||||
|
||||
peer.worker.Stop()
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *Pool) Send(id string, data []byte) error {
|
||||
id, err := transport.NormalizeURL(id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
p.mu.RLock()
|
||||
defer p.mu.RUnlock()
|
||||
|
||||
if p.closed {
|
||||
return NewPoolError(ErrPoolClosed)
|
||||
}
|
||||
|
||||
peer, exists := p.peers[id]
|
||||
if !exists {
|
||||
return NewPoolError(ErrPeerNotFound)
|
||||
}
|
||||
|
||||
return peer.worker.Send(data)
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
package outbound
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"git.wisehodl.dev/jay/go-honeybee/honeybeetest"
|
||||
"git.wisehodl.dev/jay/go-honeybee/types"
|
||||
"github.com/gorilla/websocket"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"net/http"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// Helpers
|
||||
|
||||
func setupPool(t *testing.T) (*Pool, *honeybeetest.MockDialer) {
|
||||
t.Helper()
|
||||
pool, err := NewPool(context.Background(), nil, nil)
|
||||
assert.NoError(t, err)
|
||||
dialer := &honeybeetest.MockDialer{
|
||||
DialContextFunc: func(context.Context, string, http.Header) (types.Socket, *http.Response, error) {
|
||||
return honeybeetest.NewMockSocket(), nil, nil
|
||||
},
|
||||
}
|
||||
pool.dialer = dialer
|
||||
return pool, dialer
|
||||
}
|
||||
|
||||
func expectEvent(
|
||||
t *testing.T,
|
||||
events chan PoolEvent,
|
||||
expectedURL string,
|
||||
expectedKind PoolEventKind,
|
||||
) {
|
||||
t.Helper()
|
||||
honeybeetest.Eventually(t, func() bool {
|
||||
select {
|
||||
case e := <-events:
|
||||
return e.ID == expectedURL && e.Kind == expectedKind
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}, fmt.Sprintf("expected event: URL=%q, Kind=%q", expectedURL, expectedKind))
|
||||
}
|
||||
|
||||
// Tests
|
||||
|
||||
func TestPoolConnect(t *testing.T) {
|
||||
t.Run("successfully adds connection", func(t *testing.T) {
|
||||
pool, _ := setupPool(t)
|
||||
|
||||
err := pool.Connect("wss://test")
|
||||
assert.NoError(t, err)
|
||||
|
||||
honeybeetest.Eventually(t, func() bool {
|
||||
select {
|
||||
case event := <-pool.events:
|
||||
return event.ID == "wss://test" && event.Kind == EventConnected
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}, "expected event")
|
||||
|
||||
assert.Contains(t, pool.Peers(), "wss://test")
|
||||
|
||||
pool.Close()
|
||||
})
|
||||
|
||||
t.Run("does not add duplicate", func(t *testing.T) {
|
||||
pool, _ := setupPool(t)
|
||||
|
||||
err := pool.Connect("wss://test")
|
||||
assert.NoError(t, err)
|
||||
|
||||
// trailing slash normalizes to same key
|
||||
err = pool.Connect("wss://test/")
|
||||
assert.Error(t, err)
|
||||
assert.ErrorIs(t, err, ErrPeerExists)
|
||||
|
||||
assert.Len(t, pool.Peers(), 1)
|
||||
|
||||
pool.Close()
|
||||
})
|
||||
}
|
||||
|
||||
func TestPoolClose(t *testing.T) {
|
||||
t.Run("channels close after pool close", func(t *testing.T) {
|
||||
pool, _ := NewPool(context.Background(), nil, nil)
|
||||
pool.Close()
|
||||
_, ok := <-pool.Inbox()
|
||||
assert.False(t, ok)
|
||||
_, ok = <-pool.Events()
|
||||
assert.False(t, ok)
|
||||
_, ok = <-pool.Errors()
|
||||
assert.False(t, ok)
|
||||
})
|
||||
|
||||
t.Run("connect after close returns error", func(t *testing.T) {
|
||||
pool, _ := NewPool(context.Background(), nil, nil)
|
||||
pool.Close()
|
||||
err := pool.Connect("wss://test")
|
||||
assert.ErrorIs(t, err, ErrPoolClosed)
|
||||
})
|
||||
}
|
||||
|
||||
func TestPoolRemove(t *testing.T) {
|
||||
t.Run("removes known url", func(t *testing.T) {
|
||||
pool, _ := setupPool(t)
|
||||
|
||||
pool.Connect("wss://test")
|
||||
expectEvent(t, pool.events, "wss://test", EventConnected)
|
||||
|
||||
err := pool.Remove("wss://test/")
|
||||
assert.NoError(t, err)
|
||||
|
||||
// expect a disconnected event
|
||||
expectEvent(t, pool.events, "wss://test", EventDisconnected)
|
||||
|
||||
// connection no longer in pool
|
||||
assert.NotContains(t, pool.Peers(), "wss://test")
|
||||
})
|
||||
|
||||
t.Run("unknown url returns error", func(t *testing.T) {
|
||||
pool, _ := setupPool(t)
|
||||
|
||||
// remove unknown connection
|
||||
err := pool.Remove("wss://unknown")
|
||||
assert.ErrorIs(t, err, ErrPeerNotFound)
|
||||
})
|
||||
|
||||
t.Run("closed pool returns error", func(t *testing.T) {
|
||||
pool, _ := setupPool(t)
|
||||
|
||||
// close pool
|
||||
pool.Close()
|
||||
|
||||
// attempt to remove connection
|
||||
err := pool.Remove("wss://test")
|
||||
assert.ErrorIs(t, err, ErrPoolClosed)
|
||||
})
|
||||
|
||||
}
|
||||
|
||||
func TestPoolSend(t *testing.T) {
|
||||
mockSocket := honeybeetest.NewMockSocket()
|
||||
outgoingData := make(chan honeybeetest.MockOutgoingData, 10)
|
||||
mockSocket.WriteMessageFunc = func(msgType int, data []byte) error {
|
||||
outgoingData <- honeybeetest.MockOutgoingData{MsgType: msgType, Data: data}
|
||||
return nil
|
||||
}
|
||||
mockDialer := &honeybeetest.MockDialer{
|
||||
DialContextFunc: func(context.Context, string, http.Header) (types.Socket, *http.Response, error) {
|
||||
return mockSocket, nil, nil
|
||||
},
|
||||
}
|
||||
|
||||
pool, err := NewPool(context.Background(), nil, nil)
|
||||
assert.NoError(t, err)
|
||||
pool.dialer = mockDialer
|
||||
|
||||
err = pool.Connect("wss://test")
|
||||
assert.NoError(t, err)
|
||||
expectEvent(t, pool.events, "wss://test", EventConnected)
|
||||
|
||||
err = pool.Send("wss://test", []byte("hello"))
|
||||
assert.NoError(t, err)
|
||||
|
||||
honeybeetest.ExpectWrite(t, outgoingData, websocket.TextMessage, []byte("hello"))
|
||||
|
||||
pool.Close()
|
||||
}
|
||||
@@ -0,0 +1,410 @@
|
||||
package outbound
|
||||
|
||||
import (
|
||||
"container/list"
|
||||
"context"
|
||||
"git.wisehodl.dev/jay/go-honeybee/transport"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Worker
|
||||
|
||||
type Worker interface {
|
||||
Start(pool PoolPlugin, wg *sync.WaitGroup)
|
||||
Stop()
|
||||
Send(data []byte) error
|
||||
}
|
||||
|
||||
type ReceivedMessage struct {
|
||||
data []byte
|
||||
receivedAt time.Time
|
||||
}
|
||||
|
||||
type DefaultWorker struct {
|
||||
id string
|
||||
conn atomic.Pointer[transport.Connection]
|
||||
heartbeat chan struct{}
|
||||
config *WorkerConfig
|
||||
ctx context.Context
|
||||
cancel context.CancelFunc
|
||||
}
|
||||
|
||||
func NewWorker(
|
||||
ctx context.Context,
|
||||
id string,
|
||||
config *WorkerConfig,
|
||||
|
||||
) (*DefaultWorker, error) {
|
||||
if config == nil {
|
||||
config = GetDefaultWorkerConfig()
|
||||
}
|
||||
if err := ValidateWorkerConfig(config); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
wctx, wcancel := context.WithCancel(ctx)
|
||||
w := &DefaultWorker{
|
||||
id: id,
|
||||
config: config,
|
||||
heartbeat: make(chan struct{}),
|
||||
ctx: wctx,
|
||||
cancel: wcancel,
|
||||
}
|
||||
|
||||
return w, nil
|
||||
}
|
||||
|
||||
func (w *DefaultWorker) Start(
|
||||
pool PoolPlugin,
|
||||
wg *sync.WaitGroup,
|
||||
) {
|
||||
dial := make(chan struct{}, 1)
|
||||
newConn := make(chan *transport.Connection, 1)
|
||||
messages := make(chan ReceivedMessage, 256)
|
||||
keepalive := make(chan struct{}, 1)
|
||||
|
||||
var owg sync.WaitGroup
|
||||
owg.Add(4)
|
||||
|
||||
go func() {
|
||||
defer owg.Done()
|
||||
RunDialer(w.id, w.ctx, pool, dial, newConn)
|
||||
}()
|
||||
|
||||
go func() {
|
||||
defer owg.Done()
|
||||
RunKeepalive(w.ctx, w.heartbeat, keepalive, w.config.KeepaliveTimeout)
|
||||
}()
|
||||
|
||||
go func() {
|
||||
defer owg.Done()
|
||||
RunForwarder(w.id, w.ctx, messages, pool.Inbox, w.config.MaxQueueSize)
|
||||
}()
|
||||
|
||||
go func() {
|
||||
defer owg.Done()
|
||||
session := &Session{
|
||||
id: w.id,
|
||||
connPtr: &w.conn,
|
||||
messages: messages,
|
||||
heartbeat: w.heartbeat,
|
||||
dial: dial,
|
||||
keepalive: keepalive,
|
||||
newConn: newConn,
|
||||
}
|
||||
session.Start(w.ctx, pool)
|
||||
}()
|
||||
|
||||
owg.Wait()
|
||||
wg.Done()
|
||||
}
|
||||
|
||||
func (w *DefaultWorker) Stop() {
|
||||
w.cancel()
|
||||
}
|
||||
|
||||
func (w *DefaultWorker) Send(data []byte) error {
|
||||
conn := w.conn.Load()
|
||||
if conn == nil {
|
||||
// connection not established by session
|
||||
return NewWorkerError(w.id, ErrConnectionUnavailable)
|
||||
}
|
||||
|
||||
if err := conn.Send(data); err != nil {
|
||||
return NewWorkerError(w.id, err)
|
||||
}
|
||||
|
||||
select {
|
||||
case w.heartbeat <- struct{}{}:
|
||||
case <-w.ctx.Done():
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
type Session struct {
|
||||
id string
|
||||
connPtr *atomic.Pointer[transport.Connection]
|
||||
|
||||
messages chan<- ReceivedMessage
|
||||
heartbeat chan<- struct{}
|
||||
dial chan<- struct{}
|
||||
|
||||
keepalive <-chan struct{}
|
||||
newConn <-chan *transport.Connection
|
||||
}
|
||||
|
||||
func (s *Session) Start(
|
||||
ctx context.Context,
|
||||
pool PoolPlugin,
|
||||
) {
|
||||
for {
|
||||
// request new connection
|
||||
select {
|
||||
case s.dial <- struct{}{}:
|
||||
default:
|
||||
}
|
||||
|
||||
// obtain new connection
|
||||
var conn *transport.Connection
|
||||
preConn:
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-s.keepalive:
|
||||
select {
|
||||
case s.dial <- struct{}{}:
|
||||
default:
|
||||
}
|
||||
case conn = <-s.newConn:
|
||||
break preConn
|
||||
}
|
||||
}
|
||||
|
||||
// set up new connection
|
||||
s.connPtr.Store(conn)
|
||||
pool.Events <- PoolEvent{ID: s.id, Kind: EventConnected}
|
||||
|
||||
// set up session context
|
||||
sctx, scancel := context.WithCancel(ctx)
|
||||
onStop := func() { scancel() }
|
||||
|
||||
// start session
|
||||
var wg sync.WaitGroup
|
||||
wg.Add(2)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
RunReader(sctx, onStop, conn, s.messages, s.heartbeat)
|
||||
}()
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
RunStopMonitor(sctx, onStop, conn, s.keepalive)
|
||||
}()
|
||||
|
||||
// complete session
|
||||
wg.Wait()
|
||||
|
||||
// tear down connection
|
||||
s.connPtr.Store(nil)
|
||||
pool.Events <- PoolEvent{ID: s.id, Kind: EventDisconnected}
|
||||
|
||||
// exit if worker is shutting down
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
default:
|
||||
}
|
||||
|
||||
// refresh session
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func RunReader(
|
||||
ctx context.Context,
|
||||
onStop func(),
|
||||
conn *transport.Connection,
|
||||
messages chan<- ReceivedMessage,
|
||||
heartbeat chan<- struct{},
|
||||
) {
|
||||
defer func() {
|
||||
conn.Close()
|
||||
onStop()
|
||||
}()
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case data, ok := <-conn.Incoming():
|
||||
if !ok {
|
||||
// connection has closed
|
||||
return
|
||||
}
|
||||
|
||||
// send message forward
|
||||
messages <- ReceivedMessage{data: data, receivedAt: time.Now()}
|
||||
|
||||
// send heartbeat
|
||||
select {
|
||||
case heartbeat <- struct{}{}:
|
||||
case <-ctx.Done():
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func RunStopMonitor(
|
||||
ctx context.Context,
|
||||
onStop func(),
|
||||
conn *transport.Connection,
|
||||
keepalive <-chan struct{},
|
||||
) {
|
||||
defer func() {
|
||||
conn.Close()
|
||||
onStop()
|
||||
}()
|
||||
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
case <-keepalive:
|
||||
}
|
||||
}
|
||||
|
||||
func RunForwarder(
|
||||
id string,
|
||||
ctx context.Context,
|
||||
messages <-chan ReceivedMessage,
|
||||
inbox chan<- InboxMessage,
|
||||
maxQueueSize int,
|
||||
) {
|
||||
queue := list.New()
|
||||
|
||||
for {
|
||||
var out chan<- InboxMessage
|
||||
var next ReceivedMessage
|
||||
|
||||
// enable inbox if it is populated
|
||||
if queue.Len() > 0 {
|
||||
out = inbox
|
||||
|
||||
// read the first message in the queue
|
||||
next = queue.Front().Value.(ReceivedMessage)
|
||||
}
|
||||
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case msg := <-messages:
|
||||
// limit queue size if maximum is configured
|
||||
if maxQueueSize > 0 && queue.Len() >= maxQueueSize {
|
||||
// drop oldest message
|
||||
queue.Remove(queue.Front())
|
||||
}
|
||||
// add new message
|
||||
queue.PushBack(msg)
|
||||
// send next message to inbox
|
||||
case out <- InboxMessage{
|
||||
ID: id,
|
||||
Data: next.data,
|
||||
ReceivedAt: next.receivedAt,
|
||||
}:
|
||||
// drop message from queue
|
||||
queue.Remove(queue.Front())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func RunKeepalive(
|
||||
ctx context.Context,
|
||||
heartbeat <-chan struct{},
|
||||
keepalive chan<- struct{},
|
||||
timeout time.Duration,
|
||||
) {
|
||||
// disable keepalive timeout if not configured
|
||||
if timeout <= 0 {
|
||||
// drain heartbeats
|
||||
// wait for cancel and exit
|
||||
for {
|
||||
select {
|
||||
case <-heartbeat:
|
||||
case <-ctx.Done():
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
timer := time.NewTimer(timeout)
|
||||
defer timer.Stop()
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-heartbeat:
|
||||
// drain the timer channel and reset
|
||||
if !timer.Stop() {
|
||||
select {
|
||||
case <-timer.C:
|
||||
default:
|
||||
}
|
||||
}
|
||||
timer.Reset(timeout)
|
||||
// timer completed
|
||||
case <-timer.C:
|
||||
// send keepalive signal, then reset the timer
|
||||
select {
|
||||
case keepalive <- struct{}{}:
|
||||
default:
|
||||
}
|
||||
timer.Reset(timeout)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func connect(
|
||||
id string,
|
||||
ctx context.Context,
|
||||
pool PoolPlugin,
|
||||
) (*transport.Connection, error) {
|
||||
conn, err := transport.NewConnection(id, pool.ConnectionConfig, pool.Logger)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
conn.SetDialer(pool.Dialer)
|
||||
return conn, conn.Connect(ctx)
|
||||
}
|
||||
|
||||
func RunDialer(
|
||||
id string,
|
||||
ctx context.Context,
|
||||
pool PoolPlugin,
|
||||
|
||||
dial <-chan struct{},
|
||||
newConn chan<- *transport.Connection,
|
||||
) {
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-dial:
|
||||
// drain dial signals while connection is being established
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
for {
|
||||
select {
|
||||
case <-dial:
|
||||
case <-done:
|
||||
return
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
// dial a new connection
|
||||
conn, err := connect(id, ctx, pool)
|
||||
close(done)
|
||||
|
||||
// send error if dial failed and continue
|
||||
if err != nil {
|
||||
select {
|
||||
case pool.Errors <- err:
|
||||
case <-ctx.Done():
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
// send the new connection or close and exit
|
||||
select {
|
||||
case newConn <- conn:
|
||||
case <-ctx.Done():
|
||||
conn.Close()
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,236 @@
|
||||
package outbound
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"git.wisehodl.dev/jay/go-honeybee/honeybeetest"
|
||||
"git.wisehodl.dev/jay/go-honeybee/transport"
|
||||
"git.wisehodl.dev/jay/go-honeybee/types"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"net/http"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestRunDialer(t *testing.T) {
|
||||
t.Run("successful dial delivers connection to newConn", func(t *testing.T) {
|
||||
url := "wss://test"
|
||||
dial := make(chan struct{}, 1)
|
||||
newConn := make(chan *transport.Connection, 1)
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
|
||||
mockSocket := honeybeetest.NewMockSocket()
|
||||
pool := PoolPlugin{
|
||||
Errors: make(chan error, 1),
|
||||
Dialer: &honeybeetest.MockDialer{
|
||||
DialContextFunc: func(context.Context, string, http.Header) (types.Socket, *http.Response, error) {
|
||||
return mockSocket, nil, nil
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
go RunDialer(url, ctx, pool, dial, newConn)
|
||||
dial <- struct{}{}
|
||||
|
||||
honeybeetest.Eventually(t, func() bool {
|
||||
select {
|
||||
case <-newConn:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}, "expected new connection")
|
||||
})
|
||||
|
||||
t.Run("concurrent dial signals are drained; only one connection produced.",
|
||||
func(t *testing.T) {
|
||||
url := "wss://test"
|
||||
dial := make(chan struct{}, 1)
|
||||
newConn := make(chan *transport.Connection, 1)
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
|
||||
gate := make(chan struct{})
|
||||
dialCount := atomic.Int32{}
|
||||
|
||||
mockSocket := honeybeetest.NewMockSocket()
|
||||
connConfig := &transport.ConnectionConfig{Retry: nil} // disable retry
|
||||
started := make(chan struct{})
|
||||
startOnce := sync.Once{}
|
||||
pool := PoolPlugin{
|
||||
Errors: make(chan error, 1),
|
||||
Dialer: &honeybeetest.MockDialer{
|
||||
DialContextFunc: func(context.Context, string, http.Header) (types.Socket, *http.Response, error) {
|
||||
dialCount.Add(1)
|
||||
startOnce.Do(func() { close(started) })
|
||||
<-gate
|
||||
return mockSocket, nil, nil
|
||||
},
|
||||
},
|
||||
ConnectionConfig: connConfig,
|
||||
}
|
||||
|
||||
go RunDialer(url, ctx, pool, dial, newConn)
|
||||
dial <- struct{}{}
|
||||
|
||||
// wait for dial to start blocking on gate
|
||||
<-started
|
||||
|
||||
// flood dial while dialer is blocked
|
||||
for i := 0; i < 5; i++ {
|
||||
select {
|
||||
case dial <- struct{}{}:
|
||||
default:
|
||||
}
|
||||
}
|
||||
|
||||
close(gate)
|
||||
|
||||
// connection is cleared to connect
|
||||
honeybeetest.Eventually(t, func() bool {
|
||||
select {
|
||||
case <-newConn:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}, "expected new connection")
|
||||
|
||||
// connection was only dialed once
|
||||
assert.Equal(t, int32(1), dialCount.Load())
|
||||
|
||||
// dial channel still writable
|
||||
select {
|
||||
case dial <- struct{}{}:
|
||||
default:
|
||||
t.Fatal("dial channel should still accept sends")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("dial failure emits error, succeeds on next signal", func(t *testing.T) {
|
||||
url := "wss://test"
|
||||
errors := make(chan error, 1)
|
||||
dial := make(chan struct{}, 1)
|
||||
newConn := make(chan *transport.Connection, 1)
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
|
||||
// use atomic counter to fail first dial and pass second
|
||||
dialCount := atomic.Int32{}
|
||||
mockSocket := honeybeetest.NewMockSocket()
|
||||
connConfig := &transport.ConnectionConfig{Retry: nil} // disable retry
|
||||
pool := PoolPlugin{
|
||||
Errors: errors,
|
||||
Dialer: &honeybeetest.MockDialer{
|
||||
DialContextFunc: func(
|
||||
context.Context, string, http.Header,
|
||||
) (types.Socket, *http.Response, error) {
|
||||
if dialCount.Add(1) == 1 {
|
||||
// fail first
|
||||
return nil, nil, fmt.Errorf("dial failed")
|
||||
}
|
||||
// pass second
|
||||
return mockSocket, nil, nil
|
||||
},
|
||||
},
|
||||
ConnectionConfig: connConfig,
|
||||
}
|
||||
|
||||
go RunDialer(url, ctx, pool, dial, newConn)
|
||||
dial <- struct{}{}
|
||||
|
||||
honeybeetest.Eventually(t, func() bool {
|
||||
select {
|
||||
case err := <-errors:
|
||||
return err != nil
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}, "expected error")
|
||||
|
||||
dial <- struct{}{}
|
||||
|
||||
honeybeetest.Eventually(t, func() bool {
|
||||
select {
|
||||
case <-newConn:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}, "expected new connection")
|
||||
})
|
||||
|
||||
t.Run("exits on context cancellation", func(t *testing.T) {
|
||||
url := "wss://test"
|
||||
dial := make(chan struct{}, 1)
|
||||
newConn := make(chan *transport.Connection, 1)
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
|
||||
pool := PoolPlugin{Errors: make(chan error, 1)}
|
||||
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
RunDialer(url, ctx, pool, dial, newConn)
|
||||
close(done)
|
||||
}()
|
||||
|
||||
cancel()
|
||||
|
||||
honeybeetest.Eventually(t, func() bool {
|
||||
select {
|
||||
case <-done:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}, "expected done signal")
|
||||
})
|
||||
|
||||
t.Run("context cancelled during in-progress dial exits without delivering connection", func(t *testing.T) {
|
||||
url := "wss://test"
|
||||
dial := make(chan struct{}, 1)
|
||||
newConn := make(chan *transport.Connection, 1)
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
|
||||
pool := PoolPlugin{
|
||||
Errors: make(chan error, 1),
|
||||
ConnectionConfig: &transport.ConnectionConfig{Retry: nil},
|
||||
Dialer: &honeybeetest.MockDialer{
|
||||
DialContextFunc: func(ctx context.Context, _ string, _ http.Header) (types.Socket, *http.Response, error) {
|
||||
// block until context is cancelled
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return nil, nil, ctx.Err()
|
||||
}
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
RunDialer(url, ctx, pool, dial, newConn)
|
||||
close(done)
|
||||
}()
|
||||
|
||||
dial <- struct{}{}
|
||||
|
||||
// wait for dialer to block
|
||||
time.Sleep(20 * time.Millisecond)
|
||||
cancel()
|
||||
|
||||
honeybeetest.Eventually(t, func() bool {
|
||||
select {
|
||||
case <-done:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}, "expected done signal")
|
||||
|
||||
// no connection was sent
|
||||
assert.Empty(t, newConn)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
package outbound
|
||||
|
||||
import (
|
||||
"context"
|
||||
"git.wisehodl.dev/jay/go-honeybee/honeybeetest"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestRunForwarder(t *testing.T) {
|
||||
t.Run("message passes through to inbox", func(t *testing.T) {
|
||||
id := "wss://test"
|
||||
messages := make(chan ReceivedMessage, 1)
|
||||
inbox := make(chan InboxMessage, 1)
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
|
||||
go RunForwarder(id, ctx, messages, inbox, 0)
|
||||
|
||||
messages <- ReceivedMessage{data: []byte("hello"), receivedAt: time.Now()}
|
||||
|
||||
honeybeetest.Eventually(t, func() bool {
|
||||
select {
|
||||
case msg := <-inbox:
|
||||
return string(msg.Data) == "hello" && msg.ID == "wss://test"
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}, "expected message")
|
||||
})
|
||||
|
||||
t.Run("oldest message dropped when queue is full", func(t *testing.T) {
|
||||
id := "wss://test"
|
||||
messages := make(chan ReceivedMessage, 1)
|
||||
inbox := make(chan InboxMessage, 1)
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
|
||||
gate := make(chan struct{})
|
||||
gatedInbox := make(chan InboxMessage)
|
||||
|
||||
// gate the inbox from receiving messages until the gate is opened
|
||||
go func() {
|
||||
<-gate
|
||||
for msg := range gatedInbox {
|
||||
inbox <- msg
|
||||
}
|
||||
}()
|
||||
|
||||
go RunForwarder(id, ctx, messages, gatedInbox, 2)
|
||||
|
||||
// send three messages while the gated inbox is blocked
|
||||
messages <- ReceivedMessage{data: []byte("first"), receivedAt: time.Now()}
|
||||
messages <- ReceivedMessage{data: []byte("second"), receivedAt: time.Now()}
|
||||
messages <- ReceivedMessage{data: []byte("third"), receivedAt: time.Now()}
|
||||
|
||||
// allow time for the first message to be dropped
|
||||
time.Sleep(20 * time.Millisecond)
|
||||
|
||||
// close the gate, draining messages into the inbox
|
||||
close(gate)
|
||||
|
||||
// receive messages from the inbox
|
||||
var received []string
|
||||
honeybeetest.Eventually(t, func() bool {
|
||||
select {
|
||||
case msg := <-inbox:
|
||||
received = append(received, string(msg.Data))
|
||||
default:
|
||||
}
|
||||
return len(received) == 2
|
||||
}, "expected messages")
|
||||
|
||||
// first message was dropped
|
||||
assert.Equal(t, []string{"second", "third"}, received)
|
||||
|
||||
})
|
||||
|
||||
t.Run("exits on context cancellation", func(t *testing.T) {
|
||||
id := "wss://test"
|
||||
messages := make(chan ReceivedMessage, 1)
|
||||
inbox := make(chan InboxMessage, 1)
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
RunForwarder(id, ctx, messages, inbox, 0)
|
||||
close(done)
|
||||
}()
|
||||
|
||||
cancel()
|
||||
honeybeetest.Eventually(t, func() bool {
|
||||
select {
|
||||
case <-done:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}, "expected done signal")
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
package outbound
|
||||
|
||||
import (
|
||||
"context"
|
||||
"git.wisehodl.dev/jay/go-honeybee/honeybeetest"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestRunKeepalive(t *testing.T) {
|
||||
t.Run("heartbeat resets timer, no keepalive signal fired", func(t *testing.T) {
|
||||
heartbeat := make(chan struct{})
|
||||
keepalive := make(chan struct{}, 1)
|
||||
timeout := 200 * time.Millisecond
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
|
||||
go RunKeepalive(ctx, heartbeat, keepalive, timeout)
|
||||
|
||||
// send heartbeats faster than the timeout
|
||||
for i := 0; i < 5; i++ {
|
||||
time.Sleep(20 * time.Millisecond)
|
||||
heartbeat <- struct{}{}
|
||||
}
|
||||
|
||||
// because the timer is being reset, keepalive signal should not be sent
|
||||
honeybeetest.Never(t, func() bool {
|
||||
select {
|
||||
case <-keepalive:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}, "unexpected keepalive signal")
|
||||
})
|
||||
|
||||
t.Run("keepalive timeout fires signal", func(t *testing.T) {
|
||||
heartbeat := make(chan struct{}, 1)
|
||||
keepalive := make(chan struct{}, 1)
|
||||
timeout := 20 * time.Millisecond
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
|
||||
go RunKeepalive(ctx, heartbeat, keepalive, timeout)
|
||||
|
||||
// send no heartbeats, wait for timeout and keepalive signal
|
||||
honeybeetest.Eventually(t, func() bool {
|
||||
select {
|
||||
case <-keepalive:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}, "expected keepalive signal")
|
||||
})
|
||||
|
||||
t.Run("exits on context cancellation", func(t *testing.T) {
|
||||
heartbeat := make(chan struct{}, 1)
|
||||
keepalive := make(chan struct{}, 1)
|
||||
timeout := 20 * time.Second
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
RunKeepalive(ctx, heartbeat, keepalive, timeout)
|
||||
close(done)
|
||||
}()
|
||||
|
||||
cancel()
|
||||
honeybeetest.Eventually(t, func() bool {
|
||||
select {
|
||||
case <-done:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}, "expected done signal")
|
||||
})
|
||||
|
||||
t.Run("disabled keepalive drains heartbeats without blocking", func(t *testing.T) {
|
||||
heartbeat := make(chan struct{})
|
||||
keepalive := make(chan struct{}, 1)
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
|
||||
go RunKeepalive(ctx, heartbeat, keepalive, 0)
|
||||
|
||||
// these must not block
|
||||
for i := 0; i < 5; i++ {
|
||||
heartbeat <- struct{}{}
|
||||
}
|
||||
|
||||
honeybeetest.Never(t, func() bool {
|
||||
select {
|
||||
case <-keepalive:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}, "keepalive signal should not fire when disabled")
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
package outbound
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"git.wisehodl.dev/jay/go-honeybee/honeybeetest"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestWorkerSend(t *testing.T) {
|
||||
t.Run("data sent to mock socket", func(t *testing.T) {
|
||||
conn, _, _, outgoingData := setupTestConnection(t)
|
||||
defer conn.Close()
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
|
||||
heartbeat := make(chan struct{})
|
||||
heartbeatCount := atomic.Int32{}
|
||||
|
||||
w := &DefaultWorker{
|
||||
ctx: ctx,
|
||||
cancel: cancel,
|
||||
id: "wss://test",
|
||||
heartbeat: heartbeat,
|
||||
}
|
||||
w.conn.Store(conn)
|
||||
defer w.cancel()
|
||||
|
||||
go func() {
|
||||
for range heartbeat {
|
||||
heartbeatCount.Add(1)
|
||||
}
|
||||
}()
|
||||
|
||||
testData := []byte("hello")
|
||||
err := w.Send(testData)
|
||||
assert.NoError(t, err)
|
||||
|
||||
// one heartbeat was sent
|
||||
assert.Equal(t, 1, int(heartbeatCount.Load()))
|
||||
|
||||
// message was sent by the socket
|
||||
honeybeetest.Eventually(t, func() bool {
|
||||
select {
|
||||
case msg := <-outgoingData:
|
||||
return string(msg.Data) == "hello"
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}, "expected message")
|
||||
})
|
||||
|
||||
t.Run("sends one heartbeat per successful send", func(t *testing.T) {
|
||||
conn, _, _, _ := setupTestConnection(t)
|
||||
defer conn.Close()
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
|
||||
heartbeat := make(chan struct{})
|
||||
heartbeatCount := atomic.Int32{}
|
||||
|
||||
w := &DefaultWorker{
|
||||
ctx: ctx,
|
||||
cancel: cancel,
|
||||
id: "wss://test",
|
||||
heartbeat: heartbeat,
|
||||
}
|
||||
w.conn.Store(conn)
|
||||
defer w.cancel()
|
||||
|
||||
go func() {
|
||||
for range heartbeat {
|
||||
heartbeatCount.Add(1)
|
||||
}
|
||||
}()
|
||||
|
||||
const count = 3
|
||||
for i := 0; i < count; i++ {
|
||||
err := w.Send([]byte(fmt.Sprintf("msg-%d", i)))
|
||||
assert.NoError(t, err)
|
||||
}
|
||||
|
||||
assert.Equal(t, count, int(heartbeatCount.Load()))
|
||||
})
|
||||
|
||||
t.Run("returns error if connection is unavailable", func(t *testing.T) {
|
||||
// no connection available to worker
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
|
||||
heartbeat := make(chan struct{})
|
||||
|
||||
w := &DefaultWorker{
|
||||
ctx: ctx,
|
||||
cancel: cancel,
|
||||
id: "wss://test",
|
||||
heartbeat: heartbeat,
|
||||
}
|
||||
defer w.cancel()
|
||||
|
||||
go func() {
|
||||
for range heartbeat {
|
||||
}
|
||||
}()
|
||||
|
||||
err := w.Send([]byte("hello"))
|
||||
assert.ErrorIs(t, err, ErrConnectionUnavailable)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,196 @@
|
||||
package outbound
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"git.wisehodl.dev/jay/go-honeybee/honeybeetest"
|
||||
"git.wisehodl.dev/jay/go-honeybee/transport"
|
||||
"github.com/gorilla/websocket"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"io"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestRunReader(t *testing.T) {
|
||||
t.Run("message arrives with correct data and non-zero receivedAt", func(t *testing.T) {
|
||||
conn, _, incomingData, _ := setupTestConnection(t)
|
||||
defer conn.Close()
|
||||
|
||||
messages := make(chan ReceivedMessage, 1)
|
||||
heartbeat := make(chan struct{})
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
|
||||
go func() {
|
||||
for range heartbeat {
|
||||
}
|
||||
}()
|
||||
go RunReader(ctx, cancel, conn, messages, heartbeat)
|
||||
|
||||
before := time.Now()
|
||||
incomingData <- honeybeetest.MockIncomingData{
|
||||
MsgType: websocket.TextMessage,
|
||||
Data: []byte("hello"),
|
||||
}
|
||||
|
||||
honeybeetest.Eventually(t, func() bool {
|
||||
select {
|
||||
case msg := <-messages:
|
||||
return string(msg.data) == "hello" && msg.receivedAt.After(before)
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}, "expected message")
|
||||
})
|
||||
|
||||
t.Run("heartbeat receives one signal per message", func(t *testing.T) {
|
||||
conn, _, incomingData, _ := setupTestConnection(t)
|
||||
defer conn.Close()
|
||||
|
||||
messages := make(chan ReceivedMessage, 10)
|
||||
heartbeat := make(chan struct{})
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
|
||||
received := atomic.Int32{}
|
||||
go func() {
|
||||
for range heartbeat {
|
||||
received.Add(1)
|
||||
}
|
||||
}()
|
||||
go func() {
|
||||
for range messages {
|
||||
}
|
||||
}()
|
||||
go RunReader(ctx, cancel, conn, messages, heartbeat)
|
||||
|
||||
const count = 3
|
||||
for i := 0; i < count; i++ {
|
||||
incomingData <- honeybeetest.MockIncomingData{
|
||||
MsgType: websocket.TextMessage,
|
||||
Data: []byte(fmt.Sprintf("msg-%d", i)),
|
||||
}
|
||||
}
|
||||
|
||||
honeybeetest.Eventually(t, func() bool {
|
||||
return received.Load() == count
|
||||
}, fmt.Sprintf("expected %d messages", count))
|
||||
})
|
||||
|
||||
t.Run("incoming channel close calls conn.Close and onStop", func(t *testing.T) {
|
||||
conn, _, incomingData, _ := setupTestConnection(t)
|
||||
|
||||
messages := make(chan ReceivedMessage, 1)
|
||||
heartbeat := make(chan struct{})
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
|
||||
go func() {
|
||||
for range heartbeat {
|
||||
}
|
||||
}()
|
||||
go func() {
|
||||
for range messages {
|
||||
}
|
||||
}()
|
||||
go RunReader(ctx, cancel, conn, messages, heartbeat)
|
||||
|
||||
// induce connection closure via reader
|
||||
incomingData <- honeybeetest.MockIncomingData{Err: io.EOF}
|
||||
|
||||
err := <-conn.Errors()
|
||||
assert.ErrorIs(t, err, io.EOF)
|
||||
|
||||
honeybeetest.Eventually(t, func() bool {
|
||||
return conn.State() == transport.StateClosed
|
||||
}, "expected closed state")
|
||||
|
||||
honeybeetest.Eventually(t, func() bool {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}, "expected context to cancel")
|
||||
})
|
||||
|
||||
t.Run("sessionDone close calls conn.Close and onStop", func(t *testing.T) {
|
||||
conn, _, _, _ := setupTestConnection(t)
|
||||
|
||||
messages := make(chan ReceivedMessage, 1)
|
||||
heartbeat := make(chan struct{})
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
|
||||
go RunReader(ctx, cancel, conn, messages, heartbeat)
|
||||
|
||||
cancel()
|
||||
|
||||
honeybeetest.Eventually(t, func() bool {
|
||||
return conn.State() == transport.StateClosed
|
||||
}, "expected closed state")
|
||||
|
||||
honeybeetest.Eventually(t, func() bool {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}, "expected context to cancel")
|
||||
})
|
||||
}
|
||||
|
||||
func TestRunStopMonitor(t *testing.T) {
|
||||
t.Run("keepalive signal calls conn.Close and cancel", func(t *testing.T) {
|
||||
conn, _, _, _ := setupTestConnection(t)
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
|
||||
keepalive := make(chan struct{}, 1)
|
||||
|
||||
go RunStopMonitor(ctx, cancel, conn, keepalive)
|
||||
|
||||
keepalive <- struct{}{}
|
||||
|
||||
honeybeetest.Eventually(t, func() bool {
|
||||
return conn.State() == transport.StateClosed
|
||||
}, "expected closed state")
|
||||
|
||||
honeybeetest.Eventually(t, func() bool {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}, "expected context to cancel")
|
||||
})
|
||||
|
||||
t.Run("ctx.Done calls conn.Close and cancel", func(t *testing.T) {
|
||||
conn, _, _, _ := setupTestConnection(t)
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
|
||||
keepalive := make(chan struct{})
|
||||
|
||||
go RunStopMonitor(ctx, cancel, conn, keepalive)
|
||||
|
||||
cancel()
|
||||
|
||||
honeybeetest.Eventually(t, func() bool {
|
||||
return conn.State() == transport.StateClosed
|
||||
}, "expected closed state")
|
||||
|
||||
honeybeetest.Eventually(t, func() bool {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}, "expected context to cancel")
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,436 @@
|
||||
package outbound
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"git.wisehodl.dev/jay/go-honeybee/honeybeetest"
|
||||
"git.wisehodl.dev/jay/go-honeybee/transport"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func drainEvent(t *testing.T, events <-chan PoolEvent, kind PoolEventKind) {
|
||||
t.Helper()
|
||||
honeybeetest.Eventually(t, func() bool {
|
||||
select {
|
||||
case e := <-events:
|
||||
return e.Kind == kind
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}, fmt.Sprintf("expected %s event", kind))
|
||||
}
|
||||
|
||||
type testVars struct {
|
||||
id string
|
||||
|
||||
dial chan struct{}
|
||||
keepalive chan struct{}
|
||||
heartbeat chan struct{}
|
||||
newConn chan *transport.Connection
|
||||
messages chan ReceivedMessage
|
||||
|
||||
conn *transport.Connection
|
||||
mockSocket *honeybeetest.MockSocket
|
||||
incomingData chan honeybeetest.MockIncomingData
|
||||
outgoingData chan honeybeetest.MockOutgoingData
|
||||
|
||||
connPtr *atomic.Pointer[transport.Connection]
|
||||
}
|
||||
|
||||
func setup(t *testing.T) (
|
||||
ctx context.Context,
|
||||
cancel context.CancelFunc,
|
||||
vars testVars,
|
||||
) {
|
||||
t.Helper()
|
||||
ctx, cancel = context.WithCancel(context.Background())
|
||||
conn, mockSocket, incomingData, outgoingData := setupTestConnection(t)
|
||||
vars = testVars{
|
||||
id: "wss://test",
|
||||
dial: make(chan struct{}, 1),
|
||||
keepalive: make(chan struct{}, 1),
|
||||
heartbeat: make(chan struct{}, 1),
|
||||
newConn: make(chan *transport.Connection, 1),
|
||||
messages: make(chan ReceivedMessage, 256),
|
||||
conn: conn,
|
||||
mockSocket: mockSocket,
|
||||
incomingData: incomingData,
|
||||
outgoingData: outgoingData,
|
||||
connPtr: &atomic.Pointer[transport.Connection]{},
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func expectDial(t *testing.T, dial <-chan struct{}) {
|
||||
t.Helper()
|
||||
honeybeetest.Eventually(t, func() bool {
|
||||
select {
|
||||
case <-dial:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}, "expected dial signal")
|
||||
}
|
||||
|
||||
func TestRunSessionDial(t *testing.T) {
|
||||
t.Run("fires dial immediately on entry", func(t *testing.T) {
|
||||
ctx, cancel, v := setup(t)
|
||||
defer cancel()
|
||||
|
||||
pool := PoolPlugin{Events: make(chan PoolEvent, 10)}
|
||||
session := &Session{
|
||||
id: v.id,
|
||||
connPtr: v.connPtr,
|
||||
messages: v.messages,
|
||||
heartbeat: v.heartbeat,
|
||||
dial: v.dial,
|
||||
keepalive: v.keepalive,
|
||||
newConn: v.newConn,
|
||||
}
|
||||
|
||||
go session.Start(ctx, pool)
|
||||
|
||||
expectDial(t, v.dial)
|
||||
})
|
||||
|
||||
t.Run("keepalive fires dial", func(t *testing.T) {
|
||||
ctx, cancel, v := setup(t)
|
||||
defer cancel()
|
||||
|
||||
pool := PoolPlugin{Events: make(chan PoolEvent, 10)}
|
||||
session := &Session{
|
||||
id: v.id,
|
||||
connPtr: v.connPtr,
|
||||
messages: v.messages,
|
||||
heartbeat: v.heartbeat,
|
||||
dial: v.dial,
|
||||
keepalive: v.keepalive,
|
||||
newConn: v.newConn,
|
||||
}
|
||||
|
||||
go session.Start(ctx, pool)
|
||||
|
||||
// drain initial dial
|
||||
expectDial(t, v.dial)
|
||||
|
||||
v.keepalive <- struct{}{}
|
||||
expectDial(t, v.dial)
|
||||
})
|
||||
|
||||
t.Run("multiple keepalive signals each fire dial", func(t *testing.T) {
|
||||
ctx, cancel, v := setup(t)
|
||||
defer cancel()
|
||||
|
||||
pool := PoolPlugin{Events: make(chan PoolEvent, 10)}
|
||||
session := &Session{
|
||||
id: v.id,
|
||||
connPtr: v.connPtr,
|
||||
messages: v.messages,
|
||||
heartbeat: v.heartbeat,
|
||||
dial: v.dial,
|
||||
keepalive: v.keepalive,
|
||||
newConn: v.newConn,
|
||||
}
|
||||
|
||||
go session.Start(ctx, pool)
|
||||
|
||||
// drain initial dial
|
||||
expectDial(t, v.dial)
|
||||
|
||||
for i := 0; i < 3; i++ {
|
||||
v.keepalive <- struct{}{}
|
||||
expectDial(t, v.dial)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestRunSessionConnect(t *testing.T) {
|
||||
t.Run("connection pointer set after newConn received", func(t *testing.T) {
|
||||
ctx, cancel, v := setup(t)
|
||||
defer cancel()
|
||||
|
||||
pool := PoolPlugin{Events: make(chan PoolEvent, 10)}
|
||||
session := &Session{
|
||||
id: v.id,
|
||||
connPtr: v.connPtr,
|
||||
messages: v.messages,
|
||||
heartbeat: v.heartbeat,
|
||||
dial: v.dial,
|
||||
keepalive: v.keepalive,
|
||||
newConn: v.newConn,
|
||||
}
|
||||
|
||||
go session.Start(ctx, pool)
|
||||
|
||||
v.newConn <- v.conn
|
||||
|
||||
honeybeetest.Eventually(t, func() bool {
|
||||
return v.connPtr.Load() != nil
|
||||
}, "expected connection pointer to be set")
|
||||
})
|
||||
|
||||
t.Run("EventConnected emitted", func(t *testing.T) {
|
||||
ctx, cancel, v := setup(t)
|
||||
defer cancel()
|
||||
|
||||
events := make(chan PoolEvent, 10)
|
||||
pool := PoolPlugin{Events: events}
|
||||
session := &Session{
|
||||
id: v.id,
|
||||
connPtr: v.connPtr,
|
||||
messages: v.messages,
|
||||
heartbeat: v.heartbeat,
|
||||
dial: v.dial,
|
||||
keepalive: v.keepalive,
|
||||
newConn: v.newConn,
|
||||
}
|
||||
|
||||
go session.Start(ctx, pool)
|
||||
|
||||
v.newConn <- v.conn
|
||||
|
||||
honeybeetest.Eventually(t, func() bool {
|
||||
select {
|
||||
case event := <-events:
|
||||
return event.ID == v.id && event.Kind == EventConnected
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}, "expected EventConnected")
|
||||
})
|
||||
}
|
||||
|
||||
func TestRunSessionDisconnect(t *testing.T) {
|
||||
t.Run("EventDisconnected emitted on connection close", func(t *testing.T) {
|
||||
ctx, cancel, v := setup(t)
|
||||
defer cancel()
|
||||
|
||||
events := make(chan PoolEvent, 10)
|
||||
pool := PoolPlugin{Events: events}
|
||||
session := &Session{
|
||||
id: v.id,
|
||||
connPtr: v.connPtr,
|
||||
messages: v.messages,
|
||||
heartbeat: v.heartbeat,
|
||||
dial: v.dial,
|
||||
keepalive: v.keepalive,
|
||||
newConn: v.newConn,
|
||||
}
|
||||
|
||||
go session.Start(ctx, pool)
|
||||
|
||||
v.newConn <- v.conn
|
||||
drainEvent(t, events, EventConnected)
|
||||
|
||||
close(v.incomingData)
|
||||
|
||||
drainEvent(t, events, EventDisconnected)
|
||||
})
|
||||
|
||||
t.Run("connection pointer cleared after disconnect", func(t *testing.T) {
|
||||
ctx, cancel, v := setup(t)
|
||||
defer cancel()
|
||||
|
||||
events := make(chan PoolEvent, 10)
|
||||
pool := PoolPlugin{Events: events}
|
||||
session := &Session{
|
||||
id: v.id,
|
||||
connPtr: v.connPtr,
|
||||
messages: v.messages,
|
||||
heartbeat: v.heartbeat,
|
||||
dial: v.dial,
|
||||
keepalive: v.keepalive,
|
||||
newConn: v.newConn,
|
||||
}
|
||||
|
||||
go session.Start(ctx, pool)
|
||||
|
||||
v.newConn <- v.conn
|
||||
drainEvent(t, events, EventConnected)
|
||||
|
||||
close(v.incomingData)
|
||||
drainEvent(t, events, EventDisconnected)
|
||||
|
||||
honeybeetest.Eventually(t, func() bool {
|
||||
return v.connPtr.Load() == nil
|
||||
}, "expected connection pointer to be nil")
|
||||
})
|
||||
|
||||
t.Run("dial fires again after disconnect", func(t *testing.T) {
|
||||
ctx, cancel, v := setup(t)
|
||||
defer cancel()
|
||||
|
||||
events := make(chan PoolEvent, 10)
|
||||
pool := PoolPlugin{Events: events}
|
||||
session := &Session{
|
||||
id: v.id,
|
||||
connPtr: v.connPtr,
|
||||
messages: v.messages,
|
||||
heartbeat: v.heartbeat,
|
||||
dial: v.dial,
|
||||
keepalive: v.keepalive,
|
||||
newConn: v.newConn,
|
||||
}
|
||||
|
||||
go session.Start(ctx, pool)
|
||||
|
||||
v.newConn <- v.conn
|
||||
drainEvent(t, events, EventConnected)
|
||||
|
||||
// drain the initial dial signal before disconnecting
|
||||
<-v.dial
|
||||
|
||||
close(v.incomingData)
|
||||
drainEvent(t, events, EventDisconnected)
|
||||
|
||||
honeybeetest.Eventually(t, func() bool {
|
||||
select {
|
||||
case <-v.dial:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}, "expected dial signal after disconnect")
|
||||
})
|
||||
|
||||
t.Run("second connection cycle emits EventConnected", func(t *testing.T) {
|
||||
ctx, cancel, v := setup(t)
|
||||
defer cancel()
|
||||
|
||||
events := make(chan PoolEvent, 10)
|
||||
pool := PoolPlugin{Events: events}
|
||||
session := &Session{
|
||||
id: v.id,
|
||||
connPtr: v.connPtr,
|
||||
messages: v.messages,
|
||||
heartbeat: v.heartbeat,
|
||||
dial: v.dial,
|
||||
keepalive: v.keepalive,
|
||||
newConn: v.newConn,
|
||||
}
|
||||
|
||||
go session.Start(ctx, pool)
|
||||
|
||||
v.newConn <- v.conn
|
||||
drainEvent(t, events, EventConnected)
|
||||
|
||||
close(v.incomingData)
|
||||
drainEvent(t, events, EventDisconnected)
|
||||
|
||||
conn2, _, _, _ := setupTestConnection(t)
|
||||
v.newConn <- conn2
|
||||
drainEvent(t, events, EventConnected)
|
||||
})
|
||||
}
|
||||
|
||||
func TestRunSessionCancellation(t *testing.T) {
|
||||
t.Run("ctx cancelled pre-connection exits without emitting events", func(t *testing.T) {
|
||||
ctx, cancel, v := setup(t)
|
||||
events := make(chan PoolEvent, 10)
|
||||
pool := PoolPlugin{Events: events}
|
||||
session := &Session{
|
||||
id: v.id,
|
||||
connPtr: v.connPtr,
|
||||
messages: v.messages,
|
||||
heartbeat: v.heartbeat,
|
||||
dial: v.dial,
|
||||
keepalive: v.keepalive,
|
||||
newConn: v.newConn,
|
||||
}
|
||||
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
defer close(done)
|
||||
session.Start(ctx, pool)
|
||||
}()
|
||||
|
||||
cancel()
|
||||
|
||||
honeybeetest.Eventually(t, func() bool {
|
||||
select {
|
||||
case <-done:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}, "expected runSession to exit")
|
||||
|
||||
honeybeetest.Never(t, func() bool {
|
||||
select {
|
||||
case <-events:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}, "expected no events emitted")
|
||||
})
|
||||
|
||||
t.Run("ctx cancelled post-connection emits EventDisconnected", func(t *testing.T) {
|
||||
ctx, cancel, v := setup(t)
|
||||
events := make(chan PoolEvent, 10)
|
||||
pool := PoolPlugin{Events: events}
|
||||
session := &Session{
|
||||
id: v.id,
|
||||
connPtr: v.connPtr,
|
||||
messages: v.messages,
|
||||
heartbeat: v.heartbeat,
|
||||
dial: v.dial,
|
||||
keepalive: v.keepalive,
|
||||
newConn: v.newConn,
|
||||
}
|
||||
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
defer close(done)
|
||||
session.Start(ctx, pool)
|
||||
}()
|
||||
|
||||
v.newConn <- v.conn
|
||||
drainEvent(t, events, EventConnected)
|
||||
|
||||
cancel()
|
||||
drainEvent(t, events, EventDisconnected)
|
||||
|
||||
honeybeetest.Eventually(t, func() bool {
|
||||
select {
|
||||
case <-done:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}, "expected runSession to exit")
|
||||
})
|
||||
|
||||
t.Run("ctx cancelled post-connection clears connection pointer", func(t *testing.T) {
|
||||
ctx, cancel, v := setup(t)
|
||||
events := make(chan PoolEvent, 10)
|
||||
pool := PoolPlugin{Events: events}
|
||||
session := &Session{
|
||||
id: v.id,
|
||||
connPtr: v.connPtr,
|
||||
messages: v.messages,
|
||||
heartbeat: v.heartbeat,
|
||||
dial: v.dial,
|
||||
keepalive: v.keepalive,
|
||||
newConn: v.newConn,
|
||||
}
|
||||
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
defer close(done)
|
||||
session.Start(ctx, pool)
|
||||
}()
|
||||
|
||||
v.newConn <- v.conn
|
||||
drainEvent(t, events, EventConnected)
|
||||
|
||||
cancel()
|
||||
drainEvent(t, events, EventDisconnected)
|
||||
|
||||
honeybeetest.Eventually(t, func() bool {
|
||||
return v.connPtr.Load() == nil
|
||||
}, "expected connection pointer to be nil")
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,316 @@
|
||||
package outbound
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"git.wisehodl.dev/jay/go-honeybee/honeybeetest"
|
||||
"git.wisehodl.dev/jay/go-honeybee/transport"
|
||||
"git.wisehodl.dev/jay/go-honeybee/types"
|
||||
"github.com/gorilla/websocket"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"net/http"
|
||||
"sync"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func makeWorkerContext(t *testing.T) (
|
||||
inbox chan InboxMessage,
|
||||
events chan PoolEvent,
|
||||
errors chan error,
|
||||
pool PoolPlugin,
|
||||
) {
|
||||
t.Helper()
|
||||
inbox = make(chan InboxMessage, 256)
|
||||
events = make(chan PoolEvent, 10)
|
||||
errors = make(chan error, 10)
|
||||
pool = PoolPlugin{
|
||||
Inbox: inbox,
|
||||
Events: events,
|
||||
Errors: errors,
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func makeWorker(t *testing.T, ctx context.Context, cancel context.CancelFunc) *DefaultWorker {
|
||||
t.Helper()
|
||||
return &DefaultWorker{
|
||||
ctx: ctx,
|
||||
cancel: cancel,
|
||||
id: "wss://test",
|
||||
config: GetDefaultWorkerConfig(),
|
||||
heartbeat: make(chan struct{}),
|
||||
}
|
||||
}
|
||||
|
||||
func mockDialer(socket *honeybeetest.MockSocket) *honeybeetest.MockDialer {
|
||||
return &honeybeetest.MockDialer{
|
||||
DialContextFunc: func(context.Context, string, http.Header) (types.Socket, *http.Response, error) {
|
||||
return socket, nil, nil
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func TestWorkerStart(t *testing.T) {
|
||||
t.Run("EventConnected emitted after dial succeeds", func(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
|
||||
w := makeWorker(t, ctx, cancel)
|
||||
_, events, _, pool := makeWorkerContext(t)
|
||||
mockSocket := honeybeetest.NewMockSocket()
|
||||
pool.Dialer = mockDialer(mockSocket)
|
||||
|
||||
var wg sync.WaitGroup
|
||||
wg.Add(1)
|
||||
go w.Start(pool, &wg)
|
||||
|
||||
honeybeetest.Eventually(t, func() bool {
|
||||
select {
|
||||
case e := <-events:
|
||||
return e.ID == w.id && e.Kind == EventConnected
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}, "expected EventConnected")
|
||||
})
|
||||
|
||||
t.Run("Send delivers data to socket", func(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
|
||||
w := makeWorker(t, ctx, cancel)
|
||||
_, events, _, pool := makeWorkerContext(t)
|
||||
_, mockSocket, _, outgoingData := setupTestConnection(t)
|
||||
pool.Dialer = mockDialer(mockSocket)
|
||||
|
||||
var wg sync.WaitGroup
|
||||
wg.Add(1)
|
||||
go w.Start(pool, &wg)
|
||||
|
||||
honeybeetest.Eventually(t, func() bool {
|
||||
select {
|
||||
case e := <-events:
|
||||
return e.Kind == EventConnected
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}, "expected EventConnected")
|
||||
|
||||
err := w.Send([]byte("hello"))
|
||||
assert.NoError(t, err)
|
||||
|
||||
honeybeetest.Eventually(t, func() bool {
|
||||
select {
|
||||
case msg := <-outgoingData:
|
||||
return string(msg.Data) == "hello"
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}, "expected data on socket")
|
||||
})
|
||||
|
||||
t.Run("socket data arrives on Inbox", func(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
|
||||
w := makeWorker(t, ctx, cancel)
|
||||
inbox, events, _, pool := makeWorkerContext(t)
|
||||
|
||||
incomingData := make(chan honeybeetest.MockIncomingData, 10)
|
||||
mockSocket := honeybeetest.NewMockSocket()
|
||||
|
||||
mockSocket.CloseFunc = func() error {
|
||||
mockSocket.Once.Do(func() { close(mockSocket.Closed) })
|
||||
return nil
|
||||
}
|
||||
|
||||
mockSocket.ReadMessageFunc = func() (int, []byte, error) {
|
||||
select {
|
||||
case data := <-incomingData:
|
||||
return data.MsgType, data.Data, data.Err
|
||||
}
|
||||
}
|
||||
|
||||
pool.Dialer = mockDialer(mockSocket)
|
||||
|
||||
var wg sync.WaitGroup
|
||||
wg.Add(1)
|
||||
go w.Start(pool, &wg)
|
||||
|
||||
honeybeetest.Eventually(t, func() bool {
|
||||
select {
|
||||
case e := <-events:
|
||||
return e.Kind == EventConnected
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}, "expected EventConnected")
|
||||
|
||||
incomingData <- honeybeetest.MockIncomingData{
|
||||
MsgType: websocket.TextMessage,
|
||||
Data: []byte("hello"),
|
||||
}
|
||||
|
||||
honeybeetest.Eventually(t, func() bool {
|
||||
select {
|
||||
case msg := <-inbox:
|
||||
return msg.ID == w.id && string(msg.Data) == "hello"
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}, "expected message on Inbox")
|
||||
})
|
||||
|
||||
t.Run("socket close produces EventDisconnected then EventConnected", func(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
|
||||
w := makeWorker(t, ctx, cancel)
|
||||
_, events, _, pool := makeWorkerContext(t)
|
||||
_, mockSocket, incomingData, _ := setupTestConnection(t)
|
||||
pool.Dialer = mockDialer(mockSocket)
|
||||
|
||||
var wg sync.WaitGroup
|
||||
wg.Add(1)
|
||||
go w.Start(pool, &wg)
|
||||
|
||||
honeybeetest.Eventually(t, func() bool {
|
||||
select {
|
||||
case e := <-events:
|
||||
return e.Kind == EventConnected
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}, "expected EventConnected")
|
||||
|
||||
close(incomingData)
|
||||
|
||||
honeybeetest.Eventually(t, func() bool {
|
||||
select {
|
||||
case e := <-events:
|
||||
return e.Kind == EventDisconnected
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}, "expected EventDisconnected")
|
||||
|
||||
honeybeetest.Eventually(t, func() bool {
|
||||
select {
|
||||
case e := <-events:
|
||||
return e.Kind == EventConnected
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}, "expected second EventConnected")
|
||||
})
|
||||
|
||||
t.Run("Stop produces EventDisconnected and wg drains", func(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
|
||||
w := makeWorker(t, ctx, cancel)
|
||||
_, events, _, pool := makeWorkerContext(t)
|
||||
mockSocket := honeybeetest.NewMockSocket()
|
||||
pool.Dialer = mockDialer(mockSocket)
|
||||
|
||||
var wg sync.WaitGroup
|
||||
wg.Add(1)
|
||||
go w.Start(pool, &wg)
|
||||
|
||||
honeybeetest.Eventually(t, func() bool {
|
||||
select {
|
||||
case e := <-events:
|
||||
return e.Kind == EventConnected
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}, "expected EventConnected")
|
||||
|
||||
w.Stop()
|
||||
|
||||
honeybeetest.Eventually(t, func() bool {
|
||||
select {
|
||||
case e := <-events:
|
||||
return e.Kind == EventDisconnected
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}, "expected EventDisconnected")
|
||||
|
||||
done := make(chan struct{})
|
||||
go func() { wg.Wait(); close(done) }()
|
||||
honeybeetest.Eventually(t, func() bool {
|
||||
select {
|
||||
case <-done:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}, "expected wg to drain")
|
||||
})
|
||||
|
||||
t.Run("parent context cancel exits cleanly and wg drains", func(t *testing.T) {
|
||||
parentCtx, parentCancel := context.WithCancel(context.Background())
|
||||
workerCtx, workerCancel := context.WithCancel(parentCtx)
|
||||
|
||||
w := makeWorker(t, workerCtx, workerCancel)
|
||||
_, events, _, pool := makeWorkerContext(t)
|
||||
mockSocket := honeybeetest.NewMockSocket()
|
||||
pool.Dialer = mockDialer(mockSocket)
|
||||
|
||||
var wg sync.WaitGroup
|
||||
wg.Add(1)
|
||||
go w.Start(pool, &wg)
|
||||
|
||||
honeybeetest.Eventually(t, func() bool {
|
||||
select {
|
||||
case e := <-events:
|
||||
return e.Kind == EventConnected
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}, "expected EventConnected")
|
||||
|
||||
// drain events after parent cancel — we don't assert what they are,
|
||||
// only that the worker exits
|
||||
parentCancel()
|
||||
|
||||
done := make(chan struct{})
|
||||
go func() { wg.Wait(); close(done) }()
|
||||
honeybeetest.Eventually(t, func() bool {
|
||||
select {
|
||||
case <-done:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}, "expected wg to drain after parent cancel")
|
||||
})
|
||||
|
||||
t.Run("dial failure emits to Errors", func(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
|
||||
w := makeWorker(t, ctx, cancel)
|
||||
_, _, errors, pool := makeWorkerContext(t)
|
||||
pool.ConnectionConfig = &transport.ConnectionConfig{Retry: nil}
|
||||
pool.Dialer = &honeybeetest.MockDialer{
|
||||
DialContextFunc: func(context.Context, string, http.Header) (types.Socket, *http.Response, error) {
|
||||
return nil, nil, fmt.Errorf("dial failed")
|
||||
},
|
||||
}
|
||||
|
||||
var wg sync.WaitGroup
|
||||
wg.Add(1)
|
||||
go w.Start(pool, &wg)
|
||||
|
||||
honeybeetest.Eventually(t, func() bool {
|
||||
select {
|
||||
case err := <-errors:
|
||||
return err != nil
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}, "expected error on Errors channel")
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user