MSP-8172 Add vendor

This commit is contained in:
Синельник Тимур Романович committed 2026-07-29 12:52:27 +03:00
1 parent 5175d87e08
commit eb066cb055
2619 files changed
+757077 -2

No files matched your search

+74
View File
@@ -0,0 +1,74 @@
# Created by .ignore support plugin (hsz.mobi)
### JetBrains template
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and WebStorm
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
# User-specific stuff:
/.idea/
.idea/**/workspace.xml
.idea/**/tasks.xml
.idea/dictionaries
*.iml
convert_service
convert-service
# Sensitive or high-churn files:
.idea/**/dataSources/
.idea/**/dataSources.ids
.idea/**/dataSources.local.xml
.idea/**/sqlDataSources.xml
.idea/**/dynamic.xml
.idea/**/uiDesigner.xml
# Gradle:
.idea/**/gradle.xml
.idea/**/libraries
# CMake
cmake-build-debug/
cmake-build-release/
# Mongo Explorer plugin:
.idea/**/mongoSettings.xml
## File-based project format:
*.iws
## Plugin-specific files:
# IntelliJ
out/
# mpeltonen/sbt-idea plugin
.idea_modules/
# JIRA plugin
atlassian-ide-plugin.xml
# Cursive Clojure plugin
.idea/replstate.xml
# Crashlytics plugin (for Android Studio and IntelliJ)
com_crashlytics_export_strings.xml
crashlytics.properties
crashlytics-build.properties
fabric.properties
### Go template
# Binaries for programs and plugins
*.exe
*.exe~
*.dll
*.so
*.dylib
# Test binary, build with `go test -c`
*.test
# Output of the go coverage tool, specifically when used with LiteIDE
*.out
/node_modules/
/vendor/
google/
package.json
yarn.lock
+1
View File
@@ -0,0 +1 @@
4.1.1
+32
View File
@@ -0,0 +1,32 @@
### v4.1.1
* `EncodeEvent` returns error
### v4.1.0
* extract `msg.Codec` iface
* add `etp.WithClientCodec` `etp.WithServerCodec`
* provide Godoc
### v4.0.0
* change conn id type to string, generate it from `crypto/rand`
### v3.0.0
* fully reimplemented with API change (see Migrated to V3 in README.MD)
### v2.1.3
- client: fully process workers channel before closing connection
- fix closing server connection
- use atomic for connection context
- server rooms: add api to retrieve all connections
### v2.1.2
- add worker queue for client to prevent read blocking
### v2.1.1
- fix bug in server.BroadcastToAll method
### v2.1.0
- migrate to go modules
- add ping method
### v2.0.2
- fixed deadlock on ack data chan when Acker.Notify() executed before Acker.Await()
### v2.0.1
- fixed data race when pushing response data to EmitWithAck channel
- add using buffer from pool in parser.EncodeEvent to decrease allocations
### v2.0.0
**NOTE**: protocol has changed, release is not compatible with 1.x.x
- add `OnWithAck` `EmitWithAck` methods for sync RPC
- add `sync.Pool` using
- add tests
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2019 txix-open
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+172
View File
@@ -0,0 +1,172 @@
# etp
[![GoDoc](https://godoc.org/github.com/txix-open/etp/v4?status.svg)](https://godoc.org/github.com/txix-open/etp/v4)
![Build and test](https://github.com/txix-open/etp/actions/workflows/main.yml/badge.svg)
[![codecov](https://codecov.io/gh/txix-open/etp/branch/master/graph/badge.svg?token=JMTTJ5O6WB)](https://codecov.io/gh/txix-open/etp)
[![Go Report Card](https://goreportcard.com/badge/github.com/txix-open/etp/v4)](https://goreportcard.com/report/github.com/txix-open/etp/v4)
ETP - event transport protocol on WebSocket, simple and powerful.
Highly inspired by [socket.io](https://socket.io/). But there is no good implementation in Go, that is why `etp` exists.
The package based on [github.com/nhooyr/websocket](https://github.com/nhooyr/websocket).
## Install
```bash
go get -u github.com/txix-open/etp/v4
```
## Features:
- Rooms for server
- [Javascript client](https://github.com/txix-open/isp-etp-js-client)
- Concurrent event emitting
- Context based API
- Event acknowledgment (for sync communication)
## Internals
- WebSocket message
- `websocket.MessageText` (not binary)
- `<eventName>||<ackId>||<eventData>`
- can be overridden by custom `msg.Codec`
- Each event is handled concurrently in separated goroutine
- Message limit is `1MB` by default
## Complete example
```go
package main
import (
"context"
"fmt"
"net/http"
"time"
"github.com/txix-open/etp/v4"
"github.com/txix-open/etp/v4/msg"
)
func main() {
srv := etp.NewServer(etp.WithServerAcceptOptions(&etp.AcceptOptions{
InsecureSkipVerify: true, //completely ignore CORS checks, enable only for dev purposes
}))
//callback to handle new connection
srv.OnConnect(func(conn *etp.Conn) {
//you have access to original HTTP request
fmt.Printf("id: %d, url: %s, connected\n", conn.Id(), conn.HttpRequest().URL)
srv.Rooms().Join(conn, "goodClients") //leave automatically then disconnected
conn.Data().Set("key", "value") //put any data associative with connection
})
//callback to handle disconnection
srv.OnDisconnect(func(conn *etp.Conn, err error) {
fmt.Println("disconnected", conn.Id(), err, etp.IsNormalClose(err))
})
//callback to handle any error during serving
srv.OnError(func(conn *etp.Conn, err error) {
connId := uint64(0)
// be careful, conn can be nil on upgrading protocol error (before success WebSocket connection)
if conn != nil {
connId = conn.Id()
}
fmt.Println("error", connId, err)
})
//your business event handler
//each event is handled in separated goroutine
srv.On("hello", etp.HandlerFunc(func(ctx context.Context, conn *etp.Conn, event msg.Event) []byte {
fmt.Printf("hello event received: %s, %s\n", event.Name, event.Data)
return []byte("hello handled")
}))
//fallback handler
srv.OnUnknownEvent(etp.HandlerFunc(func(ctx context.Context, conn *etp.Conn, event msg.Event) []byte {
fmt.Printf("unknown event received, %s, %s\n", event.Name, event.Data)
_ = conn.Close() //you may close a connection whenever you want
return nil
}))
mux := http.NewServeMux()
mux.Handle("GET /ws", srv)
go func() {
err := http.ListenAndServe(":8080", mux)
if err != nil {
panic(err)
}
}()
time.Sleep(1 * time.Second)
cli := etp.NewClient().
OnDisconnect(func(conn *etp.Conn, err error) { //basically you have all handlers like a server here
fmt.Println("client disconnected", conn.Id(), err)
})
err := cli.Dial(context.Background(), "ws://localhost:8080/ws")
if err != nil {
panic(err)
}
//to check connection is still alive
err = cli.Ping(context.Background())
if err != nil {
panic(err)
}
//simply emit event
err = cli.Emit(context.Background(), "hello", []byte("fire and forget"))
if err != nil {
panic(err)
}
//emit event and wait server response
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second) //highly recommended to set up timeout for waiting acknowledgment
defer cancel()
resp, err := cli.EmitWithAck(ctx, "hello", []byte("wait acknowledgment"))
if err != nil {
panic(err)
}
fmt.Printf("hello resposne: '%s'\n", resp)
//data can be empty
err = cli.Emit(ctx, "unknown event", nil)
if err != nil {
panic(err)
}
time.Sleep(15 * time.Second)
//call to disconnect all clients
srv.Shutdown()
}
```
## V4 Migration
* Internal message format is the same as `v2`
* Each event now is handled in separated goroutine (completely async)
* Significantly reduce code base, removed redundant interfaces
* Fixed some memory leaks and potential deadlocks
* Main package `github.com/txix-open/isp-etp-go/v2` -> `github.com/txix-open/etp/v4`
* `OnDefault` -> `OnUnknownEvent`
* `On*` API are the same either `etp.Client` and `etp.Server`
* WAS
```go
srv.On("event", func (conn etp.Conn, data []byte) {
log.Println("Received " + testEvent + ":" + string(data))
}).
```
* BECOME
```go
srv.On("hello", etp.HandlerFunc(func(ctx context.Context, conn *etp.Conn, event msg.Event) []byte {
fmt.Printf("hello event received: %s, %s\n", event.Name, event.Data)
return []byte("hello handled")
}))
```
The second param now is an interface.
+27
View File
@@ -0,0 +1,27 @@
// Package bpool provides a buffer pool for reusing *bytes.Buffer instances.
// It reduces memory allocations by recycling buffers.
package bpool
import (
"bytes"
"sync"
)
var (
bpool = sync.Pool{New: func() any {
return bytes.NewBuffer(make([]byte, 1024))
}}
)
// Get returns a buffer from the pool. The buffer is reset before being returned.
// Callers must call Put when done using the buffer.
func Get() *bytes.Buffer {
b := bpool.Get().(*bytes.Buffer)
b.Reset()
return b
}
// Put returns a buffer to the pool for reuse.
func Put(b *bytes.Buffer) {
bpool.Put(b)
}
+166
View File
@@ -0,0 +1,166 @@
// Package etp provides a client-server communication library using WebSockets.
// It supports event-based messaging, acknowledgments, and room-based broadcasting.
package etp
import (
"context"
"errors"
"fmt"
"sync"
"sync/atomic"
"github.com/coder/websocket"
"github.com/txix-open/etp/v4/internal"
)
var (
// ErrClientClosed is returned when the client is closed or not connected.
ErrClientClosed = errors.New("client closed")
)
// Client represents a WebSocket client for event-based communication.
// It is safe for concurrent use.
type Client struct {
mux *mux
idGenerator *internal.IdGenerator
opts *clientOptions
conn *atomic.Pointer[Conn]
lock sync.Locker
}
// NewClient creates a new Client instance with the provided options.
func NewClient(opts ...ClientOption) *Client {
options := defaultClientOptions()
for _, opt := range opts {
opt(options)
}
return &Client{
mux: newMux(),
idGenerator: internal.NewIdGenerator(),
opts: options,
conn: &atomic.Pointer[Conn]{},
lock: &sync.Mutex{},
}
}
// On registers an event handler for the specified event name.
// It returns the Client to allow method chaining.
func (c *Client) On(event string, handler Handler) *Client {
c.mux.On(event, handler)
return c
}
// OnConnect registers a handler to be called when the client connects.
// It returns the Client to allow method chaining.
func (c *Client) OnConnect(handler ConnectHandler) *Client {
c.mux.OnConnect(handler)
return c
}
// OnDisconnect registers a handler to be called when the client disconnects.
// It returns the Client to allow method chaining.
func (c *Client) OnDisconnect(handler DisconnectHandler) *Client {
c.mux.OnDisconnect(handler)
return c
}
// OnError registers a handler to be called when an error occurs.
// It returns the Client to allow method chaining.
func (c *Client) OnError(handler ErrorHandler) *Client {
c.mux.OnError(handler)
return c
}
// OnUnknownEvent registers a handler to be called when an unknown event is received.
// It returns the Client to allow method chaining.
func (c *Client) OnUnknownEvent(handler Handler) *Client {
c.mux.OnUnknownEvent(handler)
return c
}
// Dial establishes a WebSocket connection to the specified URL.
// It returns an error if already connected or if the WebSocket dial fails.
func (c *Client) Dial(ctx context.Context, url string) error {
c.lock.Lock()
defer c.lock.Unlock()
if c.conn.Load() != nil {
return errors.New("already connected")
}
ws, resp, err := websocket.Dial(ctx, url, c.opts.dialOptions)
if err != nil {
return fmt.Errorf("websocket dial: %w", err)
}
ws.SetReadLimit(c.opts.readLimit)
id := c.idGenerator.Next()
conn := newConn(id, resp.Request, ws, c.opts.codec)
c.conn.Store(conn)
keeper := newKeeper(conn, c.mux)
go func() {
defer func() {
_ = ws.CloseNow()
}()
keeper.Serve(context.Background())
c.lock.Lock()
defer c.lock.Unlock()
conn := c.conn.Load()
if conn != nil && conn.Id() == id {
c.conn.Store(nil)
}
}()
return nil
}
// Emit sends an event with the specified data to the server.
// It returns ErrClientClosed if the client is not connected.
func (c *Client) Emit(ctx context.Context, event string, data []byte) error {
conn := c.conn.Load()
if conn == nil {
return ErrClientClosed
}
return conn.Emit(ctx, event, data)
}
// EmitWithAck sends an event with the specified data to the server and waits for an acknowledgment.
// It returns ErrClientClosed if the client is not connected.
// The response data from the server is returned on success.
func (c *Client) EmitWithAck(ctx context.Context, event string, data []byte) ([]byte, error) {
conn := c.conn.Load()
if conn == nil {
return nil, ErrClientClosed
}
return conn.EmitWithAck(ctx, event, data)
}
// Ping sends a ping to the server to check the connection health.
// It returns ErrClientClosed if the client is not connected.
func (c *Client) Ping(ctx context.Context) error {
conn := c.conn.Load()
if conn == nil {
return ErrClientClosed
}
return conn.Ping(ctx)
}
// Close closes the client connection.
// It returns ErrClientClosed if the client is already closed.
func (c *Client) Close() error {
c.lock.Lock()
defer c.lock.Unlock()
conn := c.conn.Load()
if conn == nil {
return ErrClientClosed
}
err := conn.Close()
c.conn.Store(nil)
return err
}
+48
View File
@@ -0,0 +1,48 @@
package etp
import (
"github.com/coder/websocket"
"github.com/txix-open/etp/v4/msg"
)
// DialOptions is an alias for websocket.DialOptions.
type DialOptions = websocket.DialOptions
// ClientOption is a function that configures a clientOptions struct.
type ClientOption func(*clientOptions)
// clientOptions holds configuration options for a Client.
type clientOptions struct {
dialOptions *DialOptions
readLimit int64
codec msg.Codec
}
// defaultClientOptions returns the default client configuration.
func defaultClientOptions() *clientOptions {
return &clientOptions{
readLimit: defaultReadLimit,
codec: msg.NewLineCodec(),
}
}
// WithClientDialOptions sets the WebSocket dial options for the client.
func WithClientDialOptions(opts *DialOptions) ClientOption {
return func(o *clientOptions) {
o.dialOptions = opts
}
}
// WithClientReadLimit sets the maximum message size in bytes that the client can read.
func WithClientReadLimit(limit int64) ClientOption {
return func(o *clientOptions) {
o.readLimit = limit
}
}
// WithClientCodec sets the codec for encoding and decoding events.
func WithClientCodec(codec msg.Codec) ClientOption {
return func(o *clientOptions) {
o.codec = codec
}
}
+15
View File
@@ -0,0 +1,15 @@
package etp
import (
"errors"
"github.com/coder/websocket"
)
// IsNormalClose checks if the error is a WebSocket normal closure.
func IsNormalClose(err error) bool {
if wsError, ok := errors.AsType[websocket.CloseError](err); ok {
return wsError.Code == websocket.StatusNormalClosure
}
return false
}
+122
View File
@@ -0,0 +1,122 @@
package etp
import (
"context"
"fmt"
"net/http"
"github.com/coder/websocket"
"github.com/txix-open/etp/v4/bpool"
"github.com/txix-open/etp/v4/internal"
"github.com/txix-open/etp/v4/msg"
"github.com/txix-open/etp/v4/store"
)
// Conn represents a WebSocket connection associated with a client or server.
type Conn struct {
id string
request *http.Request
ws *websocket.Conn
data *store.Store
acks *internal.Acks
codec msg.Codec
}
// newConn creates a new connection with the provided parameters.
func newConn(
id string,
request *http.Request,
ws *websocket.Conn,
codec msg.Codec,
) *Conn {
return &Conn{
id: id,
request: request,
ws: ws,
data: store.New(),
acks: internal.NewAcks(),
codec: codec,
}
}
// Id returns the unique identifier for the connection.
func (c *Conn) Id() string {
return c.id
}
// HttpRequest returns the underlying HTTP request associated with the connection.
func (c *Conn) HttpRequest() *http.Request {
return c.request
}
// Data returns the key-value store for connection-specific data.
func (c *Conn) Data() *store.Store {
return c.data
}
// Emit sends an event with the specified data over the connection.
func (c *Conn) Emit(ctx context.Context, event string, data []byte) error {
message := msg.Event{
Name: event,
AckId: 0,
Data: data,
}
return c.emit(ctx, message)
}
// EmitWithAck sends an event with the specified data and waits for an acknowledgment.
// It returns the response data from the receiver on success.
func (c *Conn) EmitWithAck(ctx context.Context, event string, data []byte) ([]byte, error) {
ack := c.acks.NextAck()
defer c.acks.DeleteAck(ack.Id())
message := msg.Event{
Name: event,
AckId: ack.Id(),
Data: data,
}
err := c.emit(ctx, message)
if err != nil {
return nil, err
}
response, err := ack.Wait(ctx)
if err != nil {
return nil, fmt.Errorf("failed to wait ack: %w", err)
}
return response, nil
}
// Ping sends a WebSocket ping to check connection health.
func (c *Conn) Ping(ctx context.Context) error {
return c.ws.Ping(ctx)
}
// Close closes the WebSocket connection with a normal closure status.
func (c *Conn) Close() error {
return c.ws.Close(websocket.StatusNormalClosure, "")
}
// emit encodes and writes an event to the WebSocket connection.
func (c *Conn) emit(ctx context.Context, event msg.Event) error {
buff := bpool.Get()
defer bpool.Put(buff)
err := c.codec.EncodeEvent(buff, event)
if err != nil {
return fmt.Errorf("failed to encode event: %w", err)
}
err = c.ws.Write(ctx, websocket.MessageText, buff.Bytes())
if err != nil {
return fmt.Errorf("failed to write event: %w", err)
}
return nil
}
// notifyAck notifies the acknowledgment handler with the received response data.
func (c *Conn) notifyAck(ackId uint64, data []byte) {
c.acks.NotifyAck(ackId, data)
}
+136
View File
@@ -0,0 +1,136 @@
package etp
import (
"context"
"sync"
"github.com/txix-open/etp/v4/msg"
)
// Handler is an interface for handling events.
// The Handle method processes an event and returns a response.
type Handler interface {
Handle(ctx context.Context, conn *Conn, event msg.Event) []byte
}
// HandlerFunc is a function type that implements the Handler interface.
type HandlerFunc func(ctx context.Context, conn *Conn, event msg.Event) []byte
// Handle calls the underlying function.
func (h HandlerFunc) Handle(ctx context.Context, conn *Conn, event msg.Event) []byte {
return h(ctx, conn, event)
}
// ConnectHandler is a function type called when a connection is established.
type ConnectHandler func(conn *Conn)
// DisconnectHandler is a function type called when a connection is closed.
type DisconnectHandler func(conn *Conn, err error)
// ErrorHandler is a function type called when an error occurs.
type ErrorHandler func(conn *Conn, err error)
// mux is an internal event multiplexer that manages handlers.
type mux struct {
handlers map[string]Handler
onUnknownEvent Handler
onConnect ConnectHandler
onDisconnect DisconnectHandler
onError ErrorHandler
readLock sync.Locker
writeLock sync.Locker
}
// newMux creates a new mux instance.
func newMux() *mux {
lock := &sync.RWMutex{}
return &mux{
handlers: make(map[string]Handler),
readLock: lock.RLocker(),
writeLock: lock,
}
}
// On registers an event handler for the specified event name.
func (m *mux) On(event string, handler Handler) {
m.writeLock.Lock()
m.handlers[event] = handler
m.writeLock.Unlock()
}
// OnConnect registers a handler to be called when a connection is established.
func (m *mux) OnConnect(handler ConnectHandler) {
m.writeLock.Lock()
m.onConnect = handler
m.writeLock.Unlock()
}
// OnDisconnect registers a handler to be called when a connection is closed.
func (m *mux) OnDisconnect(handler DisconnectHandler) {
m.writeLock.Lock()
m.onDisconnect = handler
m.writeLock.Unlock()
}
// OnError registers a handler to be called when an error occurs.
func (m *mux) OnError(handler ErrorHandler) {
m.writeLock.Lock()
m.onError = handler
m.writeLock.Unlock()
}
// OnUnknownEvent registers a handler to be called when an unknown event is received.
func (m *mux) OnUnknownEvent(handler Handler) {
m.writeLock.Lock()
m.onUnknownEvent = handler
m.writeLock.Unlock()
}
// handle dispatches an event to the appropriate handler.
// It returns the response from the handler.
func (m *mux) handle(ctx context.Context, conn *Conn, event msg.Event) []byte {
m.readLock.Lock()
handler, ok := m.handlers[event.Name]
if !ok {
handler = m.onUnknownEvent
}
m.readLock.Unlock()
if handler != nil {
return handler.Handle(ctx, conn, event)
}
return nil
}
// handleConnect calls the registered connect handler.
func (m *mux) handleConnect(conn *Conn) {
m.readLock.Lock()
onConnect := m.onConnect
m.readLock.Unlock()
if onConnect != nil {
onConnect(conn)
}
}
// handleDisconnect calls the registered disconnect handler.
func (m *mux) handleDisconnect(conn *Conn, err error) {
m.readLock.Lock()
onDisconnect := m.onDisconnect
m.readLock.Unlock()
if onDisconnect != nil {
onDisconnect(conn, err)
}
}
// handleError calls the registered error handler.
func (m *mux) handleError(conn *Conn, err error) {
m.readLock.Lock()
onError := m.onError
m.readLock.Unlock()
if onError != nil {
onError(conn, err)
}
}
+50
View File
@@ -0,0 +1,50 @@
package internal
import (
"context"
"strings"
)
type Ack struct {
id uint64
response chan []byte
}
func NewAck(id uint64) *Ack {
return &Ack{
id: id,
response: make(chan []byte, 1),
}
}
func (a *Ack) Wait(ctx context.Context) ([]byte, error) {
select {
case data := <-a.response:
return data, nil
case <-ctx.Done():
return nil, ctx.Err()
}
}
func (a *Ack) Notify(data []byte) {
select {
case a.response <- data:
default:
}
}
func (a *Ack) Id() uint64 {
return a.id
}
const (
ackPrefix = "__ack_"
)
func ToAckEvent(event string) string {
return ackPrefix + event
}
func IsAckEvent(event string) bool {
return strings.HasPrefix(event, ackPrefix)
}
+46
View File
@@ -0,0 +1,46 @@
package internal
import (
"sync"
)
type Acks struct {
lock sync.Locker
acks map[uint64]*Ack
idGenerator *SequenceGenerator
}
func NewAcks() *Acks {
return &Acks{
lock: &sync.Mutex{},
acks: make(map[uint64]*Ack),
idGenerator: NewSequenceGenerator(),
}
}
func (a *Acks) NextAck() *Ack {
a.lock.Lock()
defer a.lock.Unlock()
id := a.idGenerator.Next()
ack := NewAck(id)
a.acks[id] = ack
return ack
}
func (a *Acks) NotifyAck(ackId uint64, data []byte) {
a.lock.Lock()
defer a.lock.Unlock()
ack, ok := a.acks[ackId]
if ok {
ack.Notify(data)
}
}
func (a *Acks) DeleteAck(ackId uint64) {
a.lock.Lock()
defer a.lock.Unlock()
delete(a.acks, ackId)
}
+37
View File
@@ -0,0 +1,37 @@
package internal
import (
"crypto/rand"
"encoding/hex"
"sync/atomic"
)
type SequenceGenerator struct {
next *atomic.Uint64
}
func NewSequenceGenerator() *SequenceGenerator {
return &SequenceGenerator{
next: &atomic.Uint64{},
}
}
func (g *SequenceGenerator) Next() uint64 {
return g.next.Add(1)
}
type IdGenerator struct {
}
func NewIdGenerator() *IdGenerator {
return &IdGenerator{}
}
func (g *IdGenerator) Next() string {
value := make([]byte, 16)
_, err := rand.Read(value)
if err != nil {
panic(err)
}
return hex.EncodeToString(value)
}
+68
View File
@@ -0,0 +1,68 @@
package etp
import (
"context"
"github.com/txix-open/etp/v4/internal"
"github.com/txix-open/etp/v4/msg"
)
type keeper struct {
conn *Conn
mux *mux
}
func newKeeper(conn *Conn, mux *mux) *keeper {
return &keeper{
conn: conn,
mux: mux,
}
}
func (k *keeper) Serve(ctx context.Context) {
k.mux.handleConnect(k.conn)
for {
err := k.readAndHandleMessage(ctx)
if err != nil {
k.mux.handleDisconnect(k.conn, err)
return
}
}
}
func (k *keeper) readAndHandleMessage(ctx context.Context) error {
_, data, err := k.conn.ws.Read(ctx)
if err != nil {
return err
}
event, err := k.conn.codec.UnmarshalEvent(data)
if err != nil {
k.mux.onError(k.conn, err)
return nil
}
if internal.IsAckEvent(event.Name) {
k.conn.notifyAck(event.AckId, event.Data)
return nil
}
go func() {
response := k.mux.handle(ctx, k.conn, event)
if !event.IsAckRequired() {
return
}
message := msg.Event{
Name: internal.ToAckEvent(event.Name),
AckId: event.AckId,
Data: response,
}
err := k.conn.emit(ctx, message)
if err != nil {
k.mux.onError(k.conn, err)
}
}()
return nil
}
+26
View File
@@ -0,0 +1,26 @@
// Package msg provides message types and codecs for event-based communication.
package msg
import (
"bytes"
)
// Codec defines an interface for encoding and decoding events.
type Codec interface {
// UnmarshalEvent decodes event data from bytes.
UnmarshalEvent(data []byte) (Event, error)
// EncodeEvent encodes an event to bytes.
EncodeEvent(w *bytes.Buffer, event Event) error
}
// Event represents a communication event with a name, optional acknowledgment ID, and data payload.
type Event struct {
Name string
AckId uint64
Data []byte
}
// IsAckRequired returns true if the event requires an acknowledgment.
func (e Event) IsAckRequired() bool {
return e.AckId > 0
}
+65
View File
@@ -0,0 +1,65 @@
package msg
import (
"bytes"
"fmt"
"strconv"
)
const (
// Delimiter is the separator used between event name, ack ID, and data.
Delimiter = "||"
noBodyEventParts = 2
)
var (
delimiter = []byte(Delimiter)
)
// LineCodec is a simple text-based codec that uses "||" as a delimiter.
// The format is: <eventName>||<ackId>||<eventData>
type LineCodec struct{}
// NewLineCodec creates a new LineCodec instance.
func NewLineCodec() LineCodec {
return LineCodec{}
}
// UnmarshalEvent decodes an event from the line-based format.
// It returns an error if the format is invalid or if the ackId cannot be parsed.
func (LineCodec) UnmarshalEvent(data []byte) (Event, error) {
parts := bytes.SplitN(data, delimiter, 3)
if len(parts) < noBodyEventParts {
return Event{}, fmt.Errorf("expected format: <eventName>||<ackId>||<eventData>, got: %s", string(data))
}
ackId, err := strconv.Atoi(string(parts[1]))
if err != nil {
return Event{}, fmt.Errorf("parse ackId: %w", err)
}
var eventData []byte
if len(parts) > noBodyEventParts {
eventData = parts[2]
}
return Event{
Name: string(parts[0]),
AckId: uint64(ackId),
Data: eventData,
}, nil
}
// EncodeEvent encodes an event to the line-based format.
func (LineCodec) EncodeEvent(buff *bytes.Buffer, event Event) error {
ackId := strconv.FormatInt(int64(event.AckId), 10)
buff.Grow(len(event.Name) + len(ackId) + len(event.Data) + len(delimiter)*2)
buff.WriteString(event.Name)
buff.Write(delimiter)
buff.WriteString(ackId)
if len(event.Data) > 0 {
buff.Write(delimiter)
buff.Write(event.Data)
}
return nil
}
+138
View File
@@ -0,0 +1,138 @@
package etp
import "sync"
const (
// idsRoom is the internal room name for tracking all connections.
idsRoom = "__id"
)
// Rooms manages groups of connections for broadcasting.
// It is safe for concurrent use.
type Rooms struct {
mu sync.RWMutex
rooms map[string]map[string]*Conn
}
// newRooms creates a new Rooms instance.
func newRooms() *Rooms {
return &Rooms{
rooms: make(map[string]map[string]*Conn),
}
}
// Get retrieves a connection by its ID from the internal room.
// It returns the connection and a boolean indicating whether it exists.
func (s *Rooms) Get(connId string) (*Conn, bool) {
s.mu.RLock()
var (
conn *Conn
ok bool
)
idRoom, roomExist := s.rooms[idsRoom]
if roomExist {
conn, ok = idRoom[connId]
}
s.mu.RUnlock()
return conn, ok
}
// Join adds a connection to the specified rooms.
// New rooms are created if they do not exist.
func (s *Rooms) Join(conn *Conn, rooms ...string) {
s.mu.Lock()
for _, room := range rooms {
if conns, ok := s.rooms[room]; ok {
conns[conn.Id()] = conn
} else {
s.rooms[room] = map[string]*Conn{
conn.Id(): conn,
}
}
}
s.mu.Unlock()
}
// LeaveByConnId removes a connection from the specified rooms.
// Empty rooms are automatically deleted.
func (s *Rooms) LeaveByConnId(id string, rooms ...string) {
s.mu.Lock()
for _, room := range rooms {
if conns, ok := s.rooms[room]; ok {
delete(conns, id)
if len(conns) == 0 {
delete(s.rooms, room)
}
}
}
s.mu.Unlock()
}
// Len returns the number of connections in the specified room.
func (s *Rooms) Len(room string) int {
s.mu.RLock()
defer s.mu.RUnlock()
return len(s.rooms[room])
}
// Clear removes the specified rooms.
func (s *Rooms) Clear(rooms ...string) {
s.mu.Lock()
for _, room := range rooms {
delete(s.rooms, room)
}
s.mu.Unlock()
}
// Rooms returns a slice of all room names, excluding the internal room.
func (s *Rooms) Rooms() []string {
s.mu.RLock()
result := make([]string, 0, len(s.rooms))
for room := range s.rooms {
if room != idsRoom {
result = append(result, room)
}
}
s.mu.RUnlock()
return result
}
// ToBroadcast returns all connections in the specified rooms for broadcasting.
// Duplicate connections are included multiple times if they belong to multiple rooms.
func (s *Rooms) ToBroadcast(rooms ...string) []*Conn {
s.mu.RLock()
result := make([]*Conn, 0)
for _, room := range rooms {
if conns, ok := s.rooms[room]; ok {
for _, conn := range conns {
result = append(result, conn)
}
}
}
s.mu.RUnlock()
return result
}
// AllConns returns all connections managed by the server.
func (s *Rooms) AllConns() []*Conn {
return s.ToBroadcast(idsRoom)
}
// add adds a connection to the internal room.
func (s *Rooms) add(conn *Conn) {
s.Join(conn, idsRoom)
}
// remove removes a connection from all rooms.
func (s *Rooms) remove(conn *Conn) {
s.mu.Lock()
defer s.mu.Unlock()
for room, conns := range s.rooms {
delete(conns, conn.Id())
if len(conns) == 0 {
delete(s.rooms, room)
}
}
}
+103
View File
@@ -0,0 +1,103 @@
package etp
import (
"fmt"
"net/http"
"github.com/coder/websocket"
"github.com/txix-open/etp/v4/internal"
)
// Server represents a WebSocket server for event-based communication.
// It is safe for concurrent use.
type Server struct {
idGenerator *internal.IdGenerator
mux *mux
rooms *Rooms
opts *serverOptions
}
// NewServer creates a new Server instance with the provided options.
func NewServer(opts ...ServerOption) *Server {
options := defaultServerOptions()
for _, opt := range opts {
opt(options)
}
return &Server{
idGenerator: internal.NewIdGenerator(),
mux: newMux(),
rooms: newRooms(),
opts: options,
}
}
// On registers an event handler for the specified event name.
// It returns the Server to allow method chaining.
func (s *Server) On(event string, handler Handler) *Server {
s.mux.On(event, handler)
return s
}
// OnConnect registers a handler to be called when a client connects.
// It returns the Server to allow method chaining.
func (s *Server) OnConnect(handler ConnectHandler) *Server {
s.mux.OnConnect(handler)
return s
}
// OnDisconnect registers a handler to be called when a client disconnects.
// It returns the Server to allow method chaining.
func (s *Server) OnDisconnect(handler DisconnectHandler) *Server {
s.mux.OnDisconnect(handler)
return s
}
// OnError registers a handler to be called when an error occurs.
// It returns the Server to allow method chaining.
func (s *Server) OnError(handler ErrorHandler) *Server {
s.mux.OnError(handler)
return s
}
// OnUnknownEvent registers a handler to be called when an unknown event is received.
// It returns the Server to allow method chaining.
func (s *Server) OnUnknownEvent(handler Handler) *Server {
s.mux.OnUnknownEvent(handler)
return s
}
// Rooms returns the Rooms instance for managing connection groups.
func (s *Server) Rooms() *Rooms {
return s.rooms
}
// ServeHTTP handles HTTP requests by upgrading them to WebSocket connections.
// It implements the http.Handler interface.
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
ws, err := websocket.Accept(w, r, s.opts.acceptOptions)
if err != nil {
s.mux.handleError(nil, fmt.Errorf("websocket accept error: %w", err))
return
}
defer func() {
_ = ws.CloseNow()
}()
ws.SetReadLimit(s.opts.readLimit)
id := s.idGenerator.Next()
conn := newConn(id, r, ws, s.opts.codec)
s.rooms.add(conn)
defer s.rooms.remove(conn)
keeper := newKeeper(conn, s.mux)
keeper.Serve(r.Context())
}
// Shutdown closes all active connections on the server.
func (s *Server) Shutdown() {
for _, conn := range s.rooms.AllConns() {
_ = conn.Close()
}
}
+53
View File
@@ -0,0 +1,53 @@
package etp
import (
"github.com/coder/websocket"
"github.com/txix-open/etp/v4/msg"
)
const (
// defaultReadLimit is the default maximum message size in bytes.
defaultReadLimit = 1 * 1024 * 1024
)
// AcceptOptions is an alias for websocket.AcceptOptions.
type AcceptOptions = websocket.AcceptOptions
// ServerOption is a function that configures a serverOptions struct.
type ServerOption func(*serverOptions)
// serverOptions holds configuration options for a Server.
type serverOptions struct {
acceptOptions *AcceptOptions
readLimit int64
codec msg.Codec
}
// defaultServerOptions returns the default server configuration.
func defaultServerOptions() *serverOptions {
return &serverOptions{
readLimit: defaultReadLimit,
codec: msg.NewLineCodec(),
}
}
// WithServerAcceptOptions sets the WebSocket accept options for the server.
func WithServerAcceptOptions(opts *AcceptOptions) ServerOption {
return func(options *serverOptions) {
options.acceptOptions = opts
}
}
// WithServerReadLimit sets the maximum message size in bytes that the server can read.
func WithServerReadLimit(limit int64) ServerOption {
return func(options *serverOptions) {
options.readLimit = limit
}
}
// WithServerCodec sets the codec for encoding and decoding events.
func WithServerCodec(codec msg.Codec) ServerOption {
return func(o *serverOptions) {
o.codec = codec
}
}
+71
View File
@@ -0,0 +1,71 @@
// Package store provides a thread-safe key-value store for arbitrary data.
package store
import (
"fmt"
"sync"
)
// Store is a thread-safe key-value store for arbitrary data.
type Store struct {
data map[string]any
lock sync.Locker
}
// New creates a new Store instance.
func New() *Store {
return &Store{
data: make(map[string]any),
lock: &sync.Mutex{},
}
}
// Set stores a value with the specified key.
func (s *Store) Set(key string, value any) {
s.lock.Lock()
defer s.lock.Unlock()
s.data[key] = value
}
// Get retrieves a value by key. It returns nil if the key does not exist.
func (s *Store) Get(key string) any {
s.lock.Lock()
defer s.lock.Unlock()
return s.data[key]
}
// Range iterates over all key-value pairs in the store.
// The iteration stops if the function f returns false.
func (s *Store) Range(f func(key string, value any) bool) {
s.lock.Lock()
defer s.lock.Unlock()
for k, v := range s.data {
if !f(k, v) {
return
}
}
}
// Get is a type-safe helper function to retrieve a typed value from the store.
// It returns an error if the key does not exist or if the value cannot be cast to the requested type.
func Get[T any](store *Store, key string) (T, error) {
store.lock.Lock()
defer store.lock.Unlock()
var empty T
value, ok := store.data[key]
if !ok {
return empty, fmt.Errorf("value for key %s not found", key)
}
casted, ok := value.(T)
if !ok {
return empty, fmt.Errorf("expected type %T, but got %T", empty, value)
}
return casted, nil
}