All Projects → qbeon → Webwire Go

qbeon / Webwire Go

Licence: mit
A transport independent asynchronous duplex messaging library for Go

Programming Languages

go
31211 projects - #10 most used programming language
golang
3204 projects

Projects that are alternatives of or similar to Webwire Go

Emberclear
Encrypted Chat. No History. No Logs.
Stars: ✭ 157 (-27.31%)
Mutual labels:  messaging, websockets
Spring Streaming
SPA on Spring Boot 1.x, WebSockets and React, gradle, nodejs, spring-boot, gradle multi project, spring-mvc, spring-data, gradle dependency update plugin, react-router
Stars: ✭ 6 (-97.22%)
Mutual labels:  messaging, websockets
Django instagram
Photo sharing social media site built with Python/Django. Based on Instagram's design.
Stars: ✭ 165 (-23.61%)
Mutual labels:  messaging, websockets
Bigq
Messaging platform in C# for TCP and Websockets, with or without SSL
Stars: ✭ 18 (-91.67%)
Mutual labels:  messaging, websockets
Nexus
Full-feature WAMP v2 router and client written in Go
Stars: ✭ 186 (-13.89%)
Mutual labels:  messaging, websockets
React Discord Clone
Discord Clone using React, Node, Express, Socket-IO and Mysql
Stars: ✭ 198 (-8.33%)
Mutual labels:  messaging
Watsontcp
WatsonTcp is the easiest way to build TCP-based clients and servers in C#.
Stars: ✭ 209 (-3.24%)
Mutual labels:  messaging
Djangochannelsgraphqlws
Django Channels based WebSocket GraphQL server with Graphene-like subscriptions
Stars: ✭ 203 (-6.02%)
Mutual labels:  websockets
Simple Vpn
A simple VPN allowing mesh-like communication between nodes, over websockets
Stars: ✭ 201 (-6.94%)
Mutual labels:  websockets
Wok
A cherrypy framework for multi-purpose plug-ins
Stars: ✭ 215 (-0.46%)
Mutual labels:  websockets
Chatview
This is an Android library which can be used to add chat functionality to your android application with just a few lines of code.
Stars: ✭ 211 (-2.31%)
Mutual labels:  messaging
Async Tungstenite
Async binding for Tungstenite, the Lightweight stream-based WebSocket implementation
Stars: ✭ 207 (-4.17%)
Mutual labels:  websockets
Hexnut
🔩 Hexnut is a middleware based, express/koa like framework for web sockets
Stars: ✭ 204 (-5.56%)
Mutual labels:  websockets
Aleph
Asynchronous communication for Clojure
Stars: ✭ 2,389 (+1006.02%)
Mutual labels:  websockets
Vonage Ruby Sdk
Vonage REST API client for Ruby. API support for SMS, Voice, Text-to-Speech, Numbers, Verify (2FA) and more.
Stars: ✭ 203 (-6.02%)
Mutual labels:  messaging
Arduinowebsockets
A library for writing modern websockets applications with Arduino (ESP8266 and ESP32)
Stars: ✭ 213 (-1.39%)
Mutual labels:  websockets
Strimzi Kafka Operator
Apache Kafka running on Kubernetes
Stars: ✭ 2,833 (+1211.57%)
Mutual labels:  messaging
Easy.messagehub
No need for .NET Events! A thread-safe, high performance & easy to use cross platform implementation of the Event Aggregator Pattern.
Stars: ✭ 208 (-3.7%)
Mutual labels:  messaging
Lgwebosremote
Command line webOS remote for LGTVs
Stars: ✭ 211 (-2.31%)
Mutual labels:  websockets
Rabbitmq Objc Client
RabbitMQ client for Objective-C and Swift
Stars: ✭ 207 (-4.17%)
Mutual labels:  messaging


WebWire

WebWire for Go
An asynchronous duplex messaging library

Travis CI: build status Coveralls: Test Coverage GoReportCard CodeBeat: Status CodeClimate: Maintainability
Licence: MIT GoDoc

OpenCollective


WebWire is a high-performance transport independent asynchronous duplex messaging library and an open source binary message protocol with builtin authentication and support for UTF8 and UTF16 encoding. The webwire-go library provides a server implementation for the Go programming language.

Table of Contents

Installation

Choose any stable release from the available release tags and copy the source code into your project's vendor directory: $YOURPROJECT/vendor/github.com/qbeon/webwire-go. All necessary transitive dependencies are already embedded into the webwire-go repository.

Dep

If you're using dep, just use dep ensure to add a specific version of webwire-go including all its transitive dependencies to your project: dep ensure -add github.com/qbeon/[email protected]. This will remove all embedded transitive dependencies and move them to your projects vendor directory.

Go Get

You can also use go get: go get github.com/qbeon/webwire-go but beware that this will fetch the latest commit of the master branch which is currently not yet considered a stable release branch. It's therefore recommended to use dep instead.

Contribution

Contribution of any kind is always welcome and appreciated, check out our Contribution Guidelines for more information!

Maintainers

Maintainer Role Specialization
Roman Sharkov Core Maintainer Dev (Go, JavaScript)
Daniil Trishkin CI Maintainer DevOps

WebWire Binary Protocol

WebWire is built for speed and portability implementing an open source binary protocol. Protocol Subset Diagram

The first byte defines the type of the message. Requests and replies contain an incremental 8-byte identifier that must be unique in the context of the senders' session. A 0 to 255 bytes long 7-bit ASCII encoded name is contained in the header of a signal or request message. A header-padding byte is applied in case of UTF16 payload encoding to properly align the payload sequence. Fraudulent messages are recognized by analyzing the message length, out-of-range memory access attacks are therefore prevented.

Examples

Features

Request-Reply

Clients can initiate multiple simultaneous requests and receive replies asynchronously. Requests are multiplexed through the connection similar to HTTP2 pipelining. The below examples are using the webwire Go client.

// Send a request to the server,
// this will block the goroutine until either a reply is received
// or the default timeout triggers (if there is one)
reply, err := client.Request(
	context.Background(), // No cancelation, default timeout
	nil,                  // No name
	wwr.Payload{
		Data: []byte("sudo rm -rf /"), // Binary request payload
	},
)
defer reply.Close() // Close the reply
if err != nil {
	// Oh oh, the request failed for some reason!
}
reply.PayloadUtf8() // Here we go!

Requests will respect cancelable contexts and deadlines

cancelableCtx, cancel := context.WithCancel(context.Background())
defer cancel()
timedCtx, cancelTimed := context.WithTimeout(cancelableCtx, 1*time.Second)
defer cancelTimed()

// Send a cancelable request to the server with a 1 second deadline
// will block the goroutine for 1 second at max
reply, err := client.Request(timedCtx, nil, wwr.Payload{
	Encoding: wwr.EncodingUtf8,
	Data:     []byte("hurry up!"),
})
defer reply.Close()

// Investigate errors manually...
switch err.(type) {
case wwr.ErrCanceled:
	// Request was prematurely canceled by the sender
case wwr.ErrDeadlineExceeded:
	// Request timed out, server didn't manage to reply
	// within the user-specified context deadline
case wwr.TimeoutErr:
	// Request timed out, server didn't manage to reply
	// within the specified default request timeout duration
case nil:
	// Replied successfully
}

// ... or check for a timeout error the easier way:
if err != nil {
	if wwr.IsErrTimeout(err) {
		// Timed out due to deadline excess or default timeout
	} else {
		// Unexpected error
	}
}

reply // Just in time!

Client-side Signals

Individual clients can send signals to the server. Signals are one-way messages guaranteed to arrive, though they're not guaranteed to be processed like requests are. In cases such as when the server is being shut down, incoming signals are ignored by the server and dropped while requests will acknowledge the failure. The below examples are using the webwire Go client.

// Send signal to server
err := client.Signal(
	[]byte("eventA"),
	wwr.Payload{
		Encoding: wwr.EncodingUtf8,
		Data:     []byte("something"),
	},
)

Server-side Signals

The server also can send signals to individual connected clients.

func OnRequest(
  _ context.Context,
  conn wwr.Connection,
  _ wwr.Message,
) (wwr.Payload, error) {
	// Send a signal to the client before replying to the request
	conn.Signal(
		nil, // No message name
		wwr.Payload{
			Encoding: wwr.EncodingUtf8,
			Data:     []byte("example")),
		},
	)

	// Reply nothing
	return wwr.Payload{}, nil
}

Namespaces

Different kinds of requests and signals can be differentiated using the builtin namespacing feature.

func OnRequest(
	_ context.Context,
	_ wwr.Connection,
	msg wwr.Message,
) (wwr.Payload, error) {
	switch msg.Name() {
	case "auth":
		// Authentication request
		return wwr.Payload{
			Encoding: wwr.EncodingUtf8,
      			Data:     []byte("this is an auth request"),
		}
	case "query":
		// Query request
		return wwr.Payload{
			Encoding: wwr.EncodingUtf8,
			Data:     []byte("this is a query request"),
		}
	}

	// Otherwise return nothing
	return wwr.Payload{}, nil
}
func OnSignal(
	_ context.Context,
	_ wwr.Connection,
	msg wwr.Message,
) {
	switch string(msg.Name()) {
	case "event A":
		// handle event A
	case "event B":
		// handle event B
	}
}

Sessions

Individual connections can get sessions assigned to identify them. The state of the session is automagically synchronized between the client and the server. WebWire doesn't enforce any kind of authentication technique though, it just provides a way to authenticate a connection. WebWire also doesn't enforce any kind of session storage, the user could implement a custom session manager implementing the WebWire SessionManager interface to use any kind of volatile or persistent session storage, be it a database or a simple in-memory map.

func OnRequest(
	_ context.Context,
	conn wwr.Connection,
	msg wwr.Message,
) (wwr.Payload, error) {
	// Verify credentials
	if string(msg.Payload()) != "secret:pass" {
		return wwr.Payload{}, wwr.ReqErr {
			Code:    "WRONG_CREDENTIALS",
			Message: "Incorrect username or password, try again",
		}
	}
	// Create session (will automatically synchronize to the client)
	err := conn.CreateSession(/*something that implements wwr.SessionInfo*/)
	if err != nil {
		return nil, fmt.Errorf("Couldn't create session for some reason")
	}

	// Complete request, reply nothing
	return wwr.Payload{}, nil
}

WebWire provides a basic file-based session manager implementation out of the box used by default when no custom session manager is defined. The default session manager creates a file with a .wwrsess extension for each opened session in the configured directory (which, by default, is the directory of the executable). During the restoration of a session the file is looked up by name using the session key, read and unmarshalled recreating the session object.

Concurrency

Messages are parsed and handled concurrently in a separate goroutine by default. The total number of concurrently executed handlers can be independently throttled down for each individual connection, which is unlimited by default.

All exported interfaces provided by both the server and the client are thread safe and can thus safely be used concurrently from within multiple goroutines, the library automatically synchronizes all concurrent operations.

Hooks

Various hooks provide the ability to asynchronously react to different kinds of events and control the behavior of both the client and the server.

Server-side Hooks

  • OnClientConnected
  • OnClientDisconnected
  • OnSignal
  • OnRequest

SessionManager Hooks

  • OnSessionCreated
  • OnSessionLookup
  • OnSessionClosed

SessionKeyGenerator Hooks

  • Generate

Graceful Shutdown

The server will finish processing all ongoing signals and requests before closing when asked to shut down.

// Will block until all handlers have finished
server.Shutdown()

While the server is shutting down new connections are refused with 503 Service Unavailable and incoming new requests from connected clients will be rejected with a special error: RegErrSrvShutdown. Any incoming signals from connected clients will be ignored during the shutdown.

Server-side client connections also support graceful shutdown, a connection will be closed when all work on it is done, while incoming requests and signals are handled similarly to shutting down the server.

// Will block until all work on this connection is done
connection.Close()

Multi-Language Support

The following libraries provide seamless support for various development environments providing fully compliant protocol implementations supporting the latest features.

Security

A webwire server can be hosted by a TLS protected server transport implementation to prevent man-in-the-middle attacks as well as to verify the identity of the server during connection establishment. Setting up a TLS protected websocket server for example is easy:

// Setup a secure webwire server instance
server, err := wwr.NewServer(
	serverImplementation,
	wwr.ServerOptions{
		Host: "localhost:443",
	},
	// Use a TLS protected transport layer
	&wwrgorilla.Transport{
		TLS: &wwrgorilla.TLS{
			// Provide key and certificate
			CertFilePath:       "path/to/certificate.crt",
			PrivateKeyFilePath: "path/to/private.key",
			// Specify TLS configs
			Config: &tls.Config{
				MinVersion:               tls.VersionTLS12,
				CurvePreferences:         []tls.CurveID{tls.X25519, tls.CurveP256},
				PreferServerCipherSuites: true,
				CipherSuites: []uint16{
					tls.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,
					tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
					tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
				},
			},
		},
	},
)
if err != nil {
	panic(fmt.Errorf("failed setting up wwr server: %s", err))
}
// Launch
if err := server.Run(); err != nil {
	panic(fmt.Errorf("wwr server failed: %s", err))
}

The above code example is using the webwire-go-gorilla transport implementation.


© 2018 Roman Sharkov [email protected]

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].