turnpike

package module
v0.0.0-...-6ba5e35 Latest Latest
Warning

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

Go to latest
Published: Jan 12, 2018 License: MIT Imports: 16 Imported by: 0

README

Turnpike

Build Status GoDoc

Go implementation of WAMP - The Web Application Messaging Protocol

WAMP ("The Web Application Messaging Protocol") is a communication protocol that enables distributed application architectures, with application functionality spread across nodes and all application communication decoupled by messages routed via dedicated WAMP routers.

At its core, WAMP provides applications with two asynchronous messaging patterns within one unified protocol:

  • Publish & Subscribe
  • Remote Procedure Calls

This package provides router and client library implementations as well as a basic stand-alone router. The router library can be used to embed a WAMP router in another application, or to build a custom router implementation. The client library can be used to communicate with any WAMP router.

Status

Turnpike v2 is still under development, but is getting close to a stable release. If you have any feedback or suggestions, please open an issue.

Installation

This library is designed to be used with Glide

Client library usage

TODO

Server library usage

main.go:

package main

import (
	"log"
	"net/http"

	"github.com/dcarbone/turnpike"
)

func main() {
	turnpike.Debug()
	s := turnpike.NewBasicWebSocketServer("example.realm")
	server := &http.Server{
		Handler: s,
		Addr:    ":8000",
	}
	log.Println("turnpike server starting on port 8000")
	log.Fatal(server.ListenAndServe())
}

This creates a simple WAMP router listening for websocket connections on port 8000 with a single realm configured.

You can build it like this:

go build -o router main.go

Which will create an executable in your working directory that can be run like this:

./router

Stand-alone router usage

Run the router with default settings:

$GOPATH/bin/turnpike

Router options:

Usage of turnpike:
  -port int
        port to run on (default 8000)
  -realm string
        realm name (default "realm1")

Documentation

Overview

Package turnpike implements WAMPv2 - The Web Application Messaging Protocol.

It provides router and client library implementations as well as a basic stand-alone router. The router library can be used to embed a WAMP router in another application, or to build a custom router implementation. The client library can be used to communicate with any WAMP router.

See the official WAMP documentation at http://wamp.ws for more details on the protocol.

Index

Constants

View Source
const (

	// Peer provided an incorrect URI for any URI-based attribute of WAMP message,
	// such as realm, topic or procedure.
	ErrInvalidUri = URI("wamp.error.invalid_uri")

	// A Dealer could not perform a call, since no procedure is currently
	// registered under the given URI.
	ErrNoSuchProcedure = URI("wamp.error.no_such_procedure")

	// A procedure could not be registered, since a procedure with the given URI
	// is already registered.
	ErrProcedureAlreadyExists = URI("wamp.error.procedure_already_exists")

	// A Dealer could not perform an unregister, since the given registration is
	// not active.
	ErrNoSuchRegistration = URI("wamp.error.no_such_registration")

	// A Broker could not perform an unsubscribe, since the given subscription is
	// not active.
	ErrNoSuchSubscription = URI("wamp.error.no_such_subscription")

	// A call failed, since the given argument types or values are not acceptable
	// to the called procedure - in which case the Callee may throw this error. Or
	// a Router performing payload validation checked the payload (args / kwargs)
	// of a call, call result, call error or publish, and the payload did not
	// conform - in which case the Router may throw this error.
	ErrInvalidArgument = URI("wamp.error.invalid_argument")

	// The Peer is shutting down completely - used as a GOODBYE (or ABORT) reason.
	ErrSystemShutdown = URI("wamp.error.system_shutdown")

	// The Peer wants to leave the realm - used as a GOODBYE reason.
	ErrCloseRealm = URI("wamp.error.close_realm")

	// A Peer acknowledges ending of a session - used as a GOOBYE reply reason.
	ErrGoodbyeAndOut = URI("wamp.error.goodbye_and_out")

	// A join, call, register, publish or subscribe failed, since the Peer is not
	// authorized to perform the operation.
	ErrNotAuthorized = URI("wamp.error.not_authorized")

	// A Dealer or Broker could not determine if the Peer is authorized to perform
	// a join, call, register, publish or subscribe, since the authorization
	// operation itself failed. E.g. a custom authorizer ran into an error.
	ErrAuthorizationFailed = URI("wamp.error.authorization_failed")

	// Peer wanted to join a non-existing realm (and the Router did not allow to
	// auto-create the realm)
	ErrNoSuchRealm = URI("wamp.error.no_such_realm")

	// A Peer was to be authenticated under a Role that does not (or no longer)
	// exists on the Router. For example, the Peer was successfully authenticated,
	// but the Role configured does not exists - hence there is some
	// misconfiguration in the Router.
	ErrNoSuchRole = URI("wamp.error.no_such_role")
)

Variables

This section is empty.

Functions

func Debug

func Debug()

Debug changes the log output to stderr

func DebugOff

func DebugOff()

DebugOff changes the log to a noop logger

func DefaultDialer

func DefaultDialer(subProtocols []string, tlsConfig *tls.Config, dialFunc DialFunc) *websocket.Dialer

func SetLogger

func SetLogger(l Logger)

SetLogger allows users to inject their own logger instead of the default one.

Types

type AuthFunc

type AuthFunc func(helloDetails, challengeDetails map[string]interface{}) (string, map[string]interface{}, error)

AuthFunc takes the HELLO details and CHALLENGE details and returns the signature string and a details map

type AuthenticationError

type AuthenticationError string

Peer was unable to authenticate

func (AuthenticationError) Error

func (e AuthenticationError) Error() string

type Authenticator

type Authenticator interface {
	// Authenticate takes the HELLO details and returns a (WELCOME) details map if the
	// authentication is successful, otherwise it returns an error
	Authenticate(details map[string]interface{}) (map[string]interface{}, error)
}

Authenticator describes a type that can handle authentication based solely on the HELLO message.

Use CRAuthenticator for more complex authentication schemes.

type Authorizer

type Authorizer interface {
	Authorize(session *Session, msg Message) (bool, error)
}

Authorizer is the interface implemented by an object that can determine whether a particular request is authorized or not.

Authorize takes the session and the message (request), and returns true if the request is authorized, otherwise false.

func NewDefaultAuthorizer

func NewDefaultAuthorizer() Authorizer

NewDefaultAuthorizer returns the default authorizer struct

type BasicMethodHandler

type BasicMethodHandler func(args []interface{}, kwargs map[string]interface{}) (result *CallResult)

BasicMethodHandler is an RPC endpoint that doesn't expect the `Details` map

type BinaryData

type BinaryData []byte

BindaryData is a byte array that can be marshalled and unmarshalled according to WAMP specifications: https://github.com/tavendo/WAMP/blob/master/spec/basic.md#binary-conversion-of-json-strings

This type *should* be used in types that will be marshalled as JSON.

func (BinaryData) MarshalJSON

func (b BinaryData) MarshalJSON() ([]byte, error)

func (*BinaryData) UnmarshalJSON

func (b *BinaryData) UnmarshalJSON(arr []byte) error

type Broker

type Broker interface {
	// Publishes a message to all Subscribers.
	Publish(context.Context, *Session, *MessagePublish)
	// Subscribes to messages on a URI.
	Subscribe(context.Context, *Session, *MessageSubscribe)
	// Unsubscribes from messages on a URI.
	Unsubscribe(context.Context, *Session, *MessageUnsubscribe)
	// Removes all subscriptions of the subscriber.
	RemoveSession(*Session)
}

Broker is the interface implemented by an object that handles routing EVENTS from Publishers to Subscribers.

func NewDefaultBroker

func NewDefaultBroker() Broker

NewDefaultBroker initializes and returns a simple broker that matches URIs to Subscribers.

type CRAuthenticator

type CRAuthenticator interface {
	// accept HELLO details and returns a challenge map (which will be sent in a CHALLENGE message)
	Challenge(details map[string]interface{}) (map[string]interface{}, error)
	// accept a challenge map (same as was generated in Challenge) and a signature string, and
	// authenticates the signature string against the challenge. Returns a details map and error.
	Authenticate(challenge map[string]interface{}, signature string) (map[string]interface{}, error)
}

CRAuthenticator describes a type that can handle challenge/response authentication.

func NewBasicTicketAuthenticator

func NewBasicTicketAuthenticator(tickets ...string) CRAuthenticator

NewBasicTicketAuthenticator creates a basic ticket authenticator from a static set of valid tickets.

This method of ticket-based authentication is insecure, but useful for bootstrapping. Do not use this in production.

type CallResult

type CallResult struct {
	Args   []interface{}
	Kwargs map[string]interface{}
	Err    URI
}

CallResult represents the result of a MessageCall.

type Client

type Client struct {
	Peer

	// ReceiveTimeout is the amount of time that the client will block waiting for a response from the router.
	ReceiveTimeout time.Duration
	// Auth is a map of WAMP authmethods to functions that will handle each auth type
	Auth map[string]AuthFunc

	// ReceiveDone is notified when the client's connection to the router is lost.
	ReceiveDone chan bool
	// contains filtered or unexported fields
}

A Client routes messages to/from a WAMP router.

func NewClient

func NewClient(p Peer) (*Client, error)

NewClient takes a connected Peer and returns a new Client

func NewWebSocketClient

func NewWebSocketClient(serialization SerializationFormat, url string, tlscfg *tls.Config, dial DialFunc) (*Client, error)

NewWebSocketClient creates a new websocket client connected to the specified `url` and using the specified `serialization`.

func (*Client) BasicRegister

func (c *Client) BasicRegister(procedure string, fn BasicMethodHandler) error

BasicRegister registers a BasicMethodHandler procedure with the router

func (*Client) Call

func (c *Client) Call(procedure string, options map[string]interface{}, args []interface{}, kwargs map[string]interface{}) (*Result, error)

MessageCall calls a procedure given a URI.

func (*Client) Close

func (c *Client) Close(ctx context.Context) error

Close closes the connection to the server.

func (*Client) JoinRealm

func (c *Client) JoinRealm(ctx context.Context, realm string, details map[string]interface{}) (map[string]interface{}, error)

JoinRealm joins a WAMP realm, but does not handle challenge/response authentication.

func (*Client) LeaveRealm

func (c *Client) LeaveRealm(ctx context.Context) error

LeaveRealm leaves the current realm without closing the connection to the server.

func (*Client) Publish

func (c *Client) Publish(topic string, options map[string]interface{}, args []interface{}, kwargs map[string]interface{}) error

Publish publishes an EVENT to all subscribed peers.

func (*Client) Receive

func (c *Client) Receive()

Receive handles messages from the server until this client disconnects.

This function blocks and is most commonly run in a goroutine.

func (*Client) Register

func (c *Client) Register(procedure string, fn MethodHandler, options map[string]interface{}) error

MessageRegister registers a MethodHandler procedure with the router.

func (*Client) Subscribe

func (c *Client) Subscribe(topic string, options map[string]interface{}, fn PublishEventHandler) error

MessageSubscribe registers the PublishEventHandler to be called for every message in the provided topic.

func (*Client) Unregister

func (c *Client) Unregister(procedure string) error

MessageUnregister removes a procedure with the router

func (*Client) Unsubscribe

func (c *Client) Unsubscribe(topic string) error

MessageUnsubscribe removes the registered PublishEventHandler from the topic.

type Dealer

type Dealer interface {
	// MessageRegister a procedure on an endpoint
	Register(context.Context, *Session, *MessageRegister)
	// MessageUnregister a procedure on an endpoint
	Unregister(context.Context, *Session, *MessageUnregister)
	// MessageCall a procedure on an endpoint
	Call(context.Context, *Session, *MessageCall)
	// Return the result of a procedure call
	Yield(context.Context, *Session, *MessageYield)
	// Handle an ERROR message from an invocation
	Error(context.Context, *Session, *MessageError)
	// Remove a callee's registrations
	RemoveSession(*Session)
}

A Dealer routes and manages RPC calls to callees.

func NewDefaultDealer

func NewDefaultDealer() Dealer

NewDefaultDealer returns the default turnpike dealer implementation

type DialFunc

type DialFunc func(network, addr string) (net.Conn, error)

type Error

type Error interface {
	error
	Terminal() bool
}

type ID

type ID uint64

An ID is a unique, non-negative number. Different uses may have additional restrictions.

func NewID

func NewID() ID

NewID generates a random WAMP ID.

type Interceptor

type Interceptor interface {
	Intercept(session *Session, msg *Message)
}

Interceptor is the interface implemented by an object that intercepts messages in the router to modify them somehow.

Intercept takes the session and (a pointer to) the message, and (possibly) modifies the message.

func NewDefaultInterceptor

func NewDefaultInterceptor() Interceptor

NewDefaultInterceptor returns the default interceptor, which does nothing.

type JSONSerializer

type JSONSerializer struct {
}

JSONSerializer is an implementation of Serializer that handles serializing and deserializing JSON encoded payloads.

func (*JSONSerializer) Deserialize

func (s *JSONSerializer) Deserialize(data []byte) (Message, error)

Deserialize unmarshals the payload into a message.

This method does not handle binary data according to WAMP specifications automatically, but instead uses the default implementation in encoding/json. Use the BinaryData type in your structures if using binary data.

func (*JSONSerializer) Serialize

func (s *JSONSerializer) Serialize(msg Message) ([]byte, error)

Serialize marshals the payload into a message.

This method does not handle binary data according to WAMP specifications automatically, but instead uses the default implementation in encoding/json. Use the BinaryData type in your structures if using binary data.

type Logger

type Logger interface {
	Println(v ...interface{})
	Printf(format string, v ...interface{})
}

Logger is an interface compatible with log.Logger.

type Message

type Message interface {
	MessageType() MessageType
	ToPayload() []interface{}
}

Message is a generic container for a WAMP message.

type MessageAbort

type MessageAbort struct {
	Details map[string]interface{}
	Reason  URI
}

[MessageAbort, Details|dict, Reason|uri]

func (MessageAbort) MessageType

func (MessageAbort) MessageType() MessageType

func (MessageAbort) ToPayload

func (msg MessageAbort) ToPayload() []interface{}

type MessageAuthenticate

type MessageAuthenticate struct {
	Signature string
	Extra     map[string]interface{}
}

[MessageAuthenticate, Signature|string, Extra|dict]

func (MessageAuthenticate) MessageType

func (MessageAuthenticate) MessageType() MessageType

func (MessageAuthenticate) ToPayload

func (msg MessageAuthenticate) ToPayload() []interface{}

type MessageCall

type MessageCall struct {
	Request     ID
	Options     map[string]interface{}
	Procedure   URI
	Arguments   []interface{}          `wamp:"omitempty"`
	ArgumentsKw map[string]interface{} `wamp:"omitempty"`
}

[MessageCall, Request|id, Options|dict, Procedure|uri] [MessageCall, Request|id, Options|dict, Procedure|uri, Arguments|list] [MessageCall, Request|id, Options|dict, Procedure|uri, Arguments|list, ArgumentsKw|dict]

func (MessageCall) MessageType

func (MessageCall) MessageType() MessageType

func (MessageCall) ToPayload

func (msg MessageCall) ToPayload() []interface{}

type MessageCancel

type MessageCancel struct {
	Request ID
	Options map[string]interface{}
}

[MessageCancel, MessageCall.Request|id, Options|dict]

func (MessageCancel) MessageType

func (MessageCancel) MessageType() MessageType

func (MessageCancel) ToPayload

func (msg MessageCancel) ToPayload() []interface{}

type MessageChallenge

type MessageChallenge struct {
	AuthMethod string
	Extra      map[string]interface{}
}

[MessageChallenge, AuthMethod|string, Extra|dict]

func (MessageChallenge) MessageType

func (MessageChallenge) MessageType() MessageType

func (MessageChallenge) ToPayload

func (msg MessageChallenge) ToPayload() []interface{}

type MessageError

type MessageError struct {
	Type        MessageType
	Request     ID
	Details     map[string]interface{}
	Error       URI
	Arguments   []interface{}          `wamp:"omitempty"`
	ArgumentsKw map[string]interface{} `wamp:"omitempty"`
}

[MessageError, REQUEST.Type|int, REQUEST.Request|id, Details|dict, Error|uri] [MessageError, REQUEST.Type|int, REQUEST.Request|id, Details|dict, Error|uri, Arguments|list] [MessageError, REQUEST.Type|int, REQUEST.Request|id, Details|dict, Error|uri, Arguments|list, ArgumentsKw|dict]

func (MessageError) MessageType

func (MessageError) MessageType() MessageType

func (MessageError) ToPayload

func (msg MessageError) ToPayload() []interface{}

type MessageEvent

type MessageEvent struct {
	Subscription ID
	Publication  ID
	Details      map[string]interface{}
	Arguments    []interface{}          `wamp:"omitempty"`
	ArgumentsKw  map[string]interface{} `wamp:"omitempty"`
}

[MessageEvent, MessageSubscribed.Subscription|id, MessagePublished.Publication|id, Details|dict] [MessageEvent, MessageSubscribed.Subscription|id, MessagePublished.Publication|id, Details|dict, MessagePublish.Arguments|list] [MessageEvent, MessageSubscribed.Subscription|id, MessagePublished.Publication|id, Details|dict, MessagePublish.Arguments|list, MessagePublish.ArgumentsKw|dict]

func (MessageEvent) MessageType

func (MessageEvent) MessageType() MessageType

func (MessageEvent) ToPayload

func (msg MessageEvent) ToPayload() []interface{}

type MessageExtension

type MessageExtension interface {
	Message
	TypeName() string
}

MessageExtension is a generic container for WAMP message extensions

type MessageExtensionProviderFunc

type MessageExtensionProviderFunc func(MessageType, ...interface{}) MessageExtension

MessageExtensionProviderFunc defines a function that will be called whenever a custom message is seen.

type MessageGoodbye

type MessageGoodbye struct {
	Details map[string]interface{}
	Reason  URI
}

[MessageGoodbye, Details|dict, Reason|uri]

func (MessageGoodbye) MessageType

func (MessageGoodbye) MessageType() MessageType

func (MessageGoodbye) ToPayload

func (msg MessageGoodbye) ToPayload() []interface{}

type MessageHello

type MessageHello struct {
	Realm   URI
	Details map[string]interface{}
}

[MessageHello, Realm|uri, Details|dict]

func (MessageHello) MessageType

func (MessageHello) MessageType() MessageType

func (MessageHello) ToPayload

func (msg MessageHello) ToPayload() []interface{}

type MessageInterrupt

type MessageInterrupt struct {
	Request ID
	Options map[string]interface{}
}

[MessageInterrupt, MessageInvocation.Request|id, Options|dict]

func (MessageInterrupt) MessageType

func (MessageInterrupt) MessageType() MessageType

func (MessageInterrupt) ToPayload

func (msg MessageInterrupt) ToPayload() []interface{}

type MessageInvocation

type MessageInvocation struct {
	Request      ID
	Registration ID
	Details      map[string]interface{}
	Arguments    []interface{}          `wamp:"omitempty"`
	ArgumentsKw  map[string]interface{} `wamp:"omitempty"`
}

[MessageInvocation, Request|id, MessageRegistered.Registration|id, Details|dict] [MessageInvocation, Request|id, MessageRegistered.Registration|id, Details|dict, MessageCall.Arguments|list] [MessageInvocation, Request|id, MessageRegistered.Registration|id, Details|dict, MessageCall.Arguments|list, MessageCall.ArgumentsKw|dict]

func (MessageInvocation) MessageType

func (MessageInvocation) MessageType() MessageType

func (MessageInvocation) ToPayload

func (msg MessageInvocation) ToPayload() []interface{}

type MessagePackSerializer

type MessagePackSerializer struct {
}

MessagePackSerializer is an implementation of Serializer that handles serializing and deserializing msgpack encoded payloads.

func (*MessagePackSerializer) Deserialize

func (s *MessagePackSerializer) Deserialize(data []byte) (Message, error)

Deserialize decodes a msgpack payload into a Message.

func (*MessagePackSerializer) Serialize

func (s *MessagePackSerializer) Serialize(msg Message) ([]byte, error)

Serialize encodes a Message into a msgpack payload.

type MessagePublish

type MessagePublish struct {
	Request     ID
	Options     map[string]interface{}
	Topic       URI
	Arguments   []interface{}          `wamp:"omitempty"`
	ArgumentsKw map[string]interface{} `wamp:"omitempty"`
}

[MessagePublish, Request|id, Options|dict, Topic|uri] [MessagePublish, Request|id, Options|dict, Topic|uri, Arguments|list] [MessagePublish, Request|id, Options|dict, Topic|uri, Arguments|list, ArgumentsKw|dict]

func (MessagePublish) MessageType

func (MessagePublish) MessageType() MessageType

func (MessagePublish) ToPayload

func (msg MessagePublish) ToPayload() []interface{}

type MessagePublished

type MessagePublished struct {
	Request     ID
	Publication ID
}

[MessagePublished, MessagePublish.Request|id, Publication|id]

func (MessagePublished) MessageType

func (MessagePublished) MessageType() MessageType

func (MessagePublished) ToPayload

func (msg MessagePublished) ToPayload() []interface{}

type MessageRegister

type MessageRegister struct {
	Request   ID
	Options   map[string]interface{}
	Procedure URI
}

[MessageRegister, Request|id, Options|dict, Procedure|uri]

func (MessageRegister) MessageType

func (MessageRegister) MessageType() MessageType

func (MessageRegister) ToPayload

func (msg MessageRegister) ToPayload() []interface{}

type MessageRegistered

type MessageRegistered struct {
	Request      ID
	Registration ID
}

[MessageRegistered, MessageRegister.Request|id, Registration|id]

func (MessageRegistered) MessageType

func (MessageRegistered) MessageType() MessageType

func (MessageRegistered) ToPayload

func (msg MessageRegistered) ToPayload() []interface{}

type MessageResult

type MessageResult struct {
	Request     ID
	Details     map[string]interface{}
	Arguments   []interface{}          `wamp:"omitempty"`
	ArgumentsKw map[string]interface{} `wamp:"omitempty"`
}

[MessageResult, MessageCall.Request|id, Details|dict] [MessageResult, MessageCall.Request|id, Details|dict, MessageYield.Arguments|list] [MessageResult, MessageCall.Request|id, Details|dict, MessageYield.Arguments|list, MessageYield.ArgumentsKw|dict]

func (MessageResult) MessageType

func (MessageResult) MessageType() MessageType

func (MessageResult) ToPayload

func (msg MessageResult) ToPayload() []interface{}

type MessageSubscribe

type MessageSubscribe struct {
	Request ID
	Options map[string]interface{}
	Topic   URI
}

[MessageSubscribe, Request|id, Options|dict, Topic|uri]

func (MessageSubscribe) MessageType

func (MessageSubscribe) MessageType() MessageType

func (MessageSubscribe) ToPayload

func (msg MessageSubscribe) ToPayload() []interface{}

type MessageSubscribed

type MessageSubscribed struct {
	Request      ID
	Subscription ID
}

[MessageSubscribed, MessageSubscribe.Request|id, Subscription|id]

func (MessageSubscribed) MessageType

func (MessageSubscribed) MessageType() MessageType

func (MessageSubscribed) ToPayload

func (msg MessageSubscribed) ToPayload() []interface{}

type MessageType

type MessageType uint32

Type values sourced from: http://wamp-proto.org/static/rfc/draft-oberstet-hybi-crossbar-wamp.html#rfc.section.6.5

const (
	MessageTypeHello        MessageType = 1
	MessageTypeWelcome      MessageType = 2
	MessageTypeAbort        MessageType = 3
	MessageTypeChallenge    MessageType = 4
	MessageTypeAuthenticate MessageType = 5
	MessageTypeGoodbye      MessageType = 6
	MessageTypeError        MessageType = 8
	MessageTypePublish      MessageType = 16
	MessageTypePublished    MessageType = 17
	MessageTypeSubscribe    MessageType = 32
	MessageTypeSubscribed   MessageType = 33
	MessageTypeUnsubscribe  MessageType = 34
	MessageTypeUnsubscribed MessageType = 35
	MessageTypeEvent        MessageType = 36
	MessageTypeCall         MessageType = 48
	MessageTypeCancel       MessageType = 49
	MessageTypeResult       MessageType = 50
	MessageTypeRegister     MessageType = 64
	MessageTypeRegistered   MessageType = 65
	MessageTypeUnregister   MessageType = 66
	MessageTypeUnregistered MessageType = 67
	MessageTypeInvocation   MessageType = 68
	MessageTypeInterrupt    MessageType = 69
	MessageTypeYield        MessageType = 70

	MessageTypeExtensionMin MessageType = 256
	MessageTypeExtensionMax MessageType = 1023
)

func (MessageType) New

func (mt MessageType) New() Message

func (MessageType) String

func (mt MessageType) String() string

type MessageUnregister

type MessageUnregister struct {
	Request      ID
	Registration ID
}

[MessageUnregister, Request|id, MessageRegistered.Registration|id]

func (MessageUnregister) MessageType

func (MessageUnregister) MessageType() MessageType

func (MessageUnregister) ToPayload

func (msg MessageUnregister) ToPayload() []interface{}

type MessageUnregistered

type MessageUnregistered struct {
	Request ID
}

[MessageUnregistered, MessageUnregister.Request|id]

func (MessageUnregistered) MessageType

func (MessageUnregistered) MessageType() MessageType

func (MessageUnregistered) ToPayload

func (msg MessageUnregistered) ToPayload() []interface{}

type MessageUnsubscribe

type MessageUnsubscribe struct {
	Request      ID
	Subscription ID
}

[MessageUnsubscribe, Request|id, MessageSubscribed.Subscription|id]

func (MessageUnsubscribe) MessageType

func (MessageUnsubscribe) MessageType() MessageType

func (MessageUnsubscribe) ToPayload

func (msg MessageUnsubscribe) ToPayload() []interface{}

type MessageUnsubscribed

type MessageUnsubscribed struct {
	Request ID
}

[MessageUnsubscribed, MessageUnsubscribed.Request|id]

func (MessageUnsubscribed) MessageType

func (MessageUnsubscribed) MessageType() MessageType

func (MessageUnsubscribed) ToPayload

func (msg MessageUnsubscribed) ToPayload() []interface{}

type MessageWelcome

type MessageWelcome struct {
	ID      ID
	Details map[string]interface{}
}

[MessageWelcome, Session|id, Details|dict]

func (MessageWelcome) MessageType

func (MessageWelcome) MessageType() MessageType

func (MessageWelcome) ToPayload

func (msg MessageWelcome) ToPayload() []interface{}

type MessageYield

type MessageYield struct {
	Request     ID
	Options     map[string]interface{}
	Arguments   []interface{}          `wamp:"omitempty"`
	ArgumentsKw map[string]interface{} `wamp:"omitempty"`
}

[MessageYield, MessageInvocation.Request|id, Options|dict] [MessageYield, MessageInvocation.Request|id, Options|dict, Arguments|list] [MessageYield, MessageInvocation.Request|id, Options|dict, Arguments|list, ArgumentsKw|dict]

func (MessageYield) MessageType

func (MessageYield) MessageType() MessageType

func (MessageYield) ToPayload

func (msg MessageYield) ToPayload() []interface{}

type MethodHandler

type MethodHandler func(args []interface{}, kwargs map[string]interface{}, details map[string]interface{}) (result *CallResult)

MethodHandler is an RPC endpoint.

type NoSuchRealmError

type NoSuchRealmError string

func (NoSuchRealmError) Error

func (e NoSuchRealmError) Error() string

type Peer

type Peer interface {
	Sender

	// Closes the peer connection and any channel returned from Receive().
	// Multiple calls to Close() will have no effect.
	Close() error
	Closed() bool

	// Receive will wait
	Receive() (Message, error)
	// ReceiveUntil will attempt to return a message if the provided context is not done'd prior to message retrieval.
	ReceiveUntil(context.Context) (Message, error)
}

Peer is the interface that must be implemented by all WAMP peers. It must be a single in, multi-out writer.

func NewPeer

func NewPeer(serializer Serializer, msgType int, conn *websocket.Conn) Peer

func NewWebSocketPeer

func NewWebSocketPeer(serialization SerializationFormat, url string, tlscfg *tls.Config, dial DialFunc) (Peer, error)

TODO: Hate this. Change.

type PublishEventHandler

type PublishEventHandler func(*MessageEvent)

PublishEventHandler handles a publish event.

type RPCError

type RPCError struct {
	ErrorMessage *Error
	Procedure    string
}

func (RPCError) Error

func (rpc RPCError) Error() string

type Realm

type Realm struct {
	Broker
	Dealer
	Authorizer
	Interceptor

	URI              URI
	CRAuthenticators map[string]CRAuthenticator
	Authenticators   map[string]Authenticator
	AuthTimeout      time.Duration
	// contains filtered or unexported fields
}

A Realm is a WAMP routing and administrative domain.

Clients that have connected to a WAMP router are joined to a realm and all message delivery is handled by the realm.

func (*Realm) Close

func (r *Realm) Close()

Close disconnects all clients after sending a goodbye message

func (*Realm) Closed

func (r *Realm) Closed() bool

type RealmExistsError

type RealmExistsError string

func (RealmExistsError) Error

func (e RealmExistsError) Error() string

type Router

type Router interface {
	Accept(Peer) error
	Close() error
	RegisterRealm(*Realm) error
	GetLocalPeer(URI, map[string]interface{}) (Peer, error)
	AddSessionOpenCallback(func(*Session, string))
	AddSessionCloseCallback(func(*Session, string))
}

A Router handles new Peers and routes requests to the requested Realm.

func NewDefaultRouter

func NewDefaultRouter() Router

NewDefaultRouter creates a very basic WAMP router.

type Sender

type Sender interface {
	// Send a message to the peer
	Send(context.Context, Message) error
	SendAsync(context.Context, Message, chan error) <-chan error
}

A Sender can send a message to its peer.

For clients, this sends a message to the router, and for routers, this sends a message to the client.

type SerializationFormat

type SerializationFormat int

SerializationFormat indicates the data serialization format used in a WAMP session

const (
	// Use JSON-encoded strings as a payload.
	SerializationFormatJSON SerializationFormat = iota
	// Use msgpack-encoded strings as a payload.
	SerializationFormatMSGPack
)

type Serializer

type Serializer interface {
	Serialize(Message) ([]byte, error)
	Deserialize([]byte) (Message, error)
}

Serializer is the interface implemented by an object that can serialize and deserialize WAMP messages

type Session

type Session struct {
	Peer
	ID      ID
	Details map[string]interface{}
}

Session represents an active WAMP session

func (Session) String

func (s Session) String() string

type URI

type URI string

Message is a generic container for a WAMP message. URIs are dot-separated identifiers, where each component *should* only contain letters, numbers or underscores.

See the documentation for specifics: https://github.com/wamp-proto/wamp-proto/blob/master/rfc/text/basic/bp_identifiers.md#uris-uris

type WebSocketProtocol

type WebSocketProtocol string
const (
	WebSocketProtocolJSON    WebSocketProtocol = "wamp.2.json"
	WebSocketProtocolMSGPack WebSocketProtocol = "wamp.2.msgpack"
)

type WebSocketServer

type WebSocketServer struct {
	Router
	Upgrader *websocket.Upgrader

	// The serializer to use for text frames. Defaults to JSONSerializer.
	TextSerializer Serializer
	// The serializer to use for binary frames. Defaults to JSONSerializer.
	BinarySerializer Serializer
	// contains filtered or unexported fields
}

WebSocketServer handles websocket connections.

func NewBasicWebSocketServer

func NewBasicWebSocketServer(uri string) *WebSocketServer

NewBasicWebSocketServer creates a new WebSocketServer with a single basic realm

func NewWebSocketServer

func NewWebSocketServer(realms []*Realm) (*WebSocketServer, error)

NewWebSocketServer creates a new WebSocketServer from a map of realms

func (*WebSocketServer) GetLocalClient

func (s *WebSocketServer) GetLocalClient(realm string, details map[string]interface{}) (*Client, error)

GetLocalClient returns a client connected to the specified realm

func (*WebSocketServer) RegisterProtocol

func (s *WebSocketServer) RegisterProtocol(protocol WebSocketProtocol, payloadType int, serializer Serializer) error

RegisterProtocol registers a serializer that should be used for a given protocol string and payload type.

func (*WebSocketServer) ServeHTTP

func (s *WebSocketServer) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP handles a new HTTP connection.

Jump to

Keyboard shortcuts

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