bahamut

package module
v1.72.0 Latest Latest
Warning

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

Go to latest
Published: Jul 9, 2019 License: Apache-2.0 Imports: 37 Imported by: 14

README

Bahamut

codecov

README IS A WORK IN PROGRESS AS WE ARE WRITTING MORE DOCUMENTATION ABOUT THIS PACKAGE.

Bahamut is a Go library that provides everything you need to set up a full blown API server based on an Elemental model generated from a Regolithe Specification.

The main concept of Bahamut is to only write core business logic, and letting it handle all the boring bookkeeping. You can implement various Processors interfaces, and register them when you start a Bahamut Server.

A Bahamut Server is not directly responsible for storing an retrieving data from a database. To do so, you can use any backend library you like in your processors, but we recommend using Manipulate, which provides a common interface for manipulating an Elemental model and multiple implementations for MongoDB, Cassandra or MemDB (with more to come). Later on, switching from Cassandra to MongoDB will be a no brainer.

Documentation

Overview

Package bahamut contains everything needed to build a fast and secure API server based on a set of Regolithe Specifications.

Bahamut uses an Elemental model generated from a set of Regolithe Specifications You will just need to write various processors to handle the business logic and storage.

Index

Constants

View Source
const (
	// PingStatusOK represents the status "ok"
	PingStatusOK = "ok"
	// PingStatusTimeout represents the status "timeout"
	PingStatusTimeout = "timeout"
	// PingStatusError represents the status "error"
	PingStatusError = "error"
)

Variables

View Source
var (
	ErrNotFound  = elemental.NewError("Not Found", "Unable to find the requested resource", "bahamut", http.StatusNotFound)
	ErrRateLimit = elemental.NewError("Rate Limit", "You have exceeded your rate limit", "bahamut", http.StatusTooManyRequests)
)

Various common errors

Functions

func CheckAuthentication

func CheckAuthentication(authenticators []RequestAuthenticator, ctx Context) (err error)

CheckAuthentication checks if the current context has been authenticated if there is any authenticator registered.

If it is not authenticated it stops the normal processing execution flow, and will write the Unauthorized response to the given writer. If not Authenticator is set, then it will always return true.

This is mostly used by autogenerated code, and you should not need to use it manually.

func CheckAuthorization

func CheckAuthorization(authorizers []Authorizer, ctx Context) (err error)

CheckAuthorization checks if the current context has been authorized if there is any authorizer registered.

If it is not authorized it stops the normal processing execution flow, and will write the Unauthorized response to the given writer. If not Authorizer is set, then it will always return true.

This is mostly used by autogenerated code, and you should not need to use it manually.

func InstallSIGINTHandler

func InstallSIGINTHandler(cancelFunc context.CancelFunc)

InstallSIGINTHandler installs signal handlers for graceful shutdown.

func RegisterProcessorOrDie

func RegisterProcessorOrDie(server Server, processor Processor, identity elemental.Identity)

RegisterProcessorOrDie will register the given Processor for the given Identity and will exit in case of errors. This is just a helper for Server.RegisterProcessor function.

func RetrieveHealthStatus

func RetrieveHealthStatus(timeout time.Duration, pingers map[string]Pinger) error

RetrieveHealthStatus returns the status for each Pinger.

func RunJob

func RunJob(ctx context.Context, job Job) (bool, error)

RunJob runs a Job can than be canceled at any time according to the context.

Types

type Auditer

type Auditer interface {
	Audit(Context, error)
}

Auditer is the interface an object must implement in order to handle audit traces.

type AuthAction

type AuthAction int

AuthAction is the type of action an Authenticator or an Authorizer can return.

const (

	// AuthActionOK means the authenticator/authorizer takes the responsibility
	// to grant the request. The execution in the chain will
	// stop and will be considered as a success.
	AuthActionOK AuthAction = iota

	// AuthActionKO means the authenticator/authorizer takes the responsibility
	// to reject the request. The execution in the chain will
	// stop and will be considered as a success.
	AuthActionKO

	// AuthActionContinue means the authenticator/authorizer does not take
	// any responsabolity and let the chain continue.
	// If the last authenticator in the chain returns AuthActionContinue,
	// Then the request will be considered as a success.
	AuthActionContinue
)

type Authorizer

type Authorizer interface {
	IsAuthorized(Context) (AuthAction, error)
}

Authorizer is the interface that must be implemented in order to to be used as the Bahamut Authorizer.

type Context

type Context interface {

	// Identifier returns the internal unique identifier of the context.
	Identifier() string

	// Context returns the underlying context.Context.
	Context() context.Context

	// Request returns the underlying *elemental.Request.
	Request() *elemental.Request

	// InputData returns the data sent by the client
	InputData() interface{}

	// SetInputData replaces the current input data.
	SetInputData(interface{})

	// OutputData returns the current output data.
	OutputData() interface{}

	// SetOutputData sets the data that will be returned to the client.
	SetOutputData(interface{})

	// Set count sets the count.
	SetCount(int)

	// Count returns the current count.
	Count() int

	// SetRedirect sets the redirect URL.
	SetRedirect(string)

	// Redirect returns the current value for redirection
	Redirect() string

	// SetStatusCode sets the status code that will be returned to the client.
	SetStatusCode(int)

	// StatusCode returns the current status code.
	StatusCode() int

	// AddMessage adds a custom message that will be sent as repponse header.
	AddMessage(string)

	// SetClaims sets the claims.
	SetClaims(claims []string)

	// Claims returns the list of claims.
	Claims() []string

	// Claims returns claims in a map.
	ClaimsMap() map[string]string

	// Duplicate creates a copy of the Context.
	Duplicate() Context

	// EnqueueEvents enqueues the given event to the Context.
	//
	// Bahamut will automatically generate events on the currently processed object.
	// But if your processor creates other objects alongside with the main one and you want to
	// send a push to the user, then you can use this method.
	//
	// The events you enqueue using EnqueueEvents will be sent in order to the enqueueing, and
	// *before* the main object related event.
	EnqueueEvents(...*elemental.Event)

	// SetMetadata sets opaque metadata that can be reteieved by Metadata().
	SetMetadata(key, value interface{})

	// Metadata returns the opaque data set by using SetMetadata().
	Metadata(key interface{}) interface{}
}

A Context contains all information about a current operation.

func NewContext

func NewContext(ctx context.Context, request *elemental.Request) Context

NewContext creates a new *Context.

type CreateProcessor

type CreateProcessor interface {
	ProcessCreate(Context) error
}

CreateProcessor is the interface a processor must implement in order to be able to manage OperationCreate.

type CustomUmarshaller

type CustomUmarshaller func(*elemental.Request) (elemental.Identifiable, error)

CustomUmarshaller is the type of function use to create custom unmarshalling.

type DeleteProcessor

type DeleteProcessor interface {
	ProcessDelete(Context) error
}

DeleteProcessor is the interface a processor must implement in order to be able to manage OperationDelete.

type FinishMeasurementFunc

type FinishMeasurementFunc func(code int, span opentracing.Span)

FinishMeasurementFunc is the kind of functinon returned by MetricsManager.MeasureRequest().

type HealthServerFunc

type HealthServerFunc func() error

HealthServerFunc is the type used by the Health Server to check the health of the server.

type HealthStatFunc

type HealthStatFunc func(http.ResponseWriter, *http.Request)

HealthStatFunc is the type used by the Health Server to return additional custom health info.

type InfoProcessor

type InfoProcessor interface {
	ProcessInfo(Context) error
}

InfoProcessor is the interface a processor must implement in order to be able to manage OperationInfo.

type Job

type Job func() error

Job is the type of function that can be run as a Job.

type MetricsManager

type MetricsManager interface {
	MeasureRequest(method string, url string) FinishMeasurementFunc
	RegisterWSConnection()
	UnregisterWSConnection()
	Write(w http.ResponseWriter, r *http.Request)
}

A MetricsManager handles Prometheus Metrics Management

func NewPrometheusMetricsManager

func NewPrometheusMetricsManager() MetricsManager

NewPrometheusMetricsManager returns a new MetricManager using the prometheus format.

type NATSOption

type NATSOption func(*natsPubSub)

A NATSOption represents an option to the pubsub backed by nats

func NATSOptClientID

func NATSOptClientID(clientID string) NATSOption

NATSOptClientID sets the client ID to use to connect to nats.

func NATSOptClusterID

func NATSOptClusterID(clusterID string) NATSOption

NATSOptClusterID sets the clusterID to use to connect to nats.

func NATSOptConnectRetryInterval added in v1.41.0

func NATSOptConnectRetryInterval(interval time.Duration) NATSOption

NATSOptConnectRetryInterval sets the connection retry interval

func NATSOptCredentials

func NATSOptCredentials(username string, password string) NATSOption

NATSOptCredentials sets the username and password to use to connect to nats.

func NATSOptTLS

func NATSOptTLS(tlsConfig *tls.Config) NATSOption

NATSOptTLS sets the tls config to use to connect nats.

type Option

type Option func(*config)

An Option represents a configuration option.

func OptAuditer

func OptAuditer(auditer Auditer) Option

OptAuditer configures the auditor to use to audit the requests.

The Audit() method will be run in a go routine so there is no need to deal with it in your implementation.

func OptAuthenticators

func OptAuthenticators(requestAuthenticators []RequestAuthenticator, sessionAuthenticators []SessionAuthenticator) Option

OptAuthenticators configures the authenticators.

RequestAuthenticators defines the list the RequestAuthenticator to use to authenticate the requests. They are executed in order from index 0 to index n. They will return a bahamut.AuthAction to tell if the current request authenticator grants, denies or let the chain continue. If an error is returned, the chain fails immediately. SessionAuthenticators defines the list of SessionAuthenticator that will be used to initially authentify a websocket connection. They are executed in order from index 0 to index n.They will return a bahamut.AuthAction to tell if the current session authenticator grants, denies or let the chain continue. If an error is returned, the chain fails immediately.

func OptAuthorizers

func OptAuthorizers(authorizers []Authorizer) Option

OptAuthorizers configures the authorizers.

Authorizers defines the list Authorizers to use to authorize the requests. They are executed in order from index 0 to index n. They will return a bahamut.AuthAction to tell if the current authorizer grants, denies or let the chain continue. If an error is returned, the chain fails immediately.

func OptCustomListener

func OptCustomListener(listener net.Listener) Option

OptCustomListener allows to set a custom listener for the api server..

func OptCustomRootHandler

func OptCustomRootHandler(handler http.HandlerFunc) Option

OptCustomRootHandler configures the custom root (/) handler.

func OptDisableCompression added in v1.45.0

func OptDisableCompression() Option

OptDisableCompression disables HTTP gzip compression.

This can be useful when your servers run behind a proxy for instance.

func OptDisableKeepAlive

func OptDisableKeepAlive() Option

OptDisableKeepAlive disables http keepalives.

There is a bug in Go <= 1.7 which makes the server eats all available fds. Use this option if you are using these versions.

func OptDisableMetaRoutes

func OptDisableMetaRoutes() Option

OptDisableMetaRoutes disables the meta routing.

func OptDisablePanicRecovery

func OptDisablePanicRecovery() Option

OptDisablePanicRecovery disables panic recovery.

func OptHealthCustomStats

func OptHealthCustomStats(handlers map[string]HealthStatFunc) Option

OptHealthCustomStats configures additional stats handler.

The healt server must be enabled using OptHealthServer or this option will have no effect. Parameter handlers is a map where the key will be used as the path in the health server. They must not start with an `_`, contain any `/`, be empty or the function will panic. If key contains a nil function, it will also panic.

func OptHealthServer

func OptHealthServer(listen string, handler HealthServerFunc) Option

OptHealthServer enables and configures the health server.

ListenAddress is the general listening address for the health server. HealthHandler is the type of the function to run to determine the health of the server.

func OptHealthServerMetricsManager

func OptHealthServerMetricsManager(manager MetricsManager) Option

OptHealthServerMetricsManager sets the MetricManager in the health server.

This option has no effect if the health server is not enabled.

func OptHealthServerTimeouts

func OptHealthServerTimeouts(read, write, idle time.Duration) Option

OptHealthServerTimeouts configures the health server timeouts.

func OptMTLS

func OptMTLS(caPool *x509.CertPool, authType tls.ClientAuthType) Option

OptMTLS configures the tls client authentication mechanism.

ClientCAPool is the *x509.CertPool to use for the authentifying client. AuthType defines the tls authentication mode to use for a secure server.

func OptModel

func OptModel(modelManagers map[int]elemental.ModelManager) Option

OptModel configures the elemental Model for the server.

modelManagers is a map of version to elemental.ModelManager. according to its identity.

func OptOpentracingExcludedIdentities

func OptOpentracingExcludedIdentities(identities []elemental.Identity) Option

OptOpentracingExcludedIdentities excludes the given identity from being traced.

func OptOpentracingTracer

func OptOpentracingTracer(tracer opentracing.Tracer) Option

OptOpentracingTracer sets the opentracing.Tracer to use.

func OptPostStartHook

func OptPostStartHook(hook func(Server) error) Option

OptPostStartHook registers a function that will be executed right after the server is started.

func OptPreStopHook

func OptPreStopHook(hook func(Server) error) Option

OptPreStopHook registers a function that will be executed just bbefore the server is stopped.

func OptProfilingGCP

func OptProfilingGCP(projectID string, servicePrefix string) Option

OptProfilingGCP configure gcp profiling.

ProjectID is the GCP project to use. When running on gcp, this can be empty. servicePrefix can be set to add a prefix to your service name when reporting profile to GCP. This allows to differentiate multiple instance of an application running in the same project.

func OptProfilingLocal

func OptProfilingLocal(listen string) Option

OptProfilingLocal configure local goops profiling.

func OptPushDispatchHandler

func OptPushDispatchHandler(dispatchHandler PushDispatchHandler) Option

OptPushDispatchHandler configures the push dispatcher.

DispatchHandler defines the handler that will be used to decide if a push event should be dispatch to push sessions.

func OptPushEndpoint

func OptPushEndpoint(endpoint string) Option

OptPushEndpoint sets the endpoint to use for websocket channel.

If unset, it fallsback to the default which is /events. This option has not effect if OptPushServer is not set.

func OptPushPublishHandler

func OptPushPublishHandler(publishHandler PushPublishHandler) Option

OptPushPublishHandler configures the push publisher.

PublishHandler defines the handler that will be used to decide if an event should be published.

func OptPushServer

func OptPushServer(service PubSubClient, topic string) Option

OptPushServer enables and configures the push server.

Service defines the pubsub server to use. Topic defines the default notification topic to use. DispatchHandler defines the handler that will be used to decide if a push event should be dispatch to push sessions. PublishHandler defines the handler that will be used to decide if an event should be published.

func OptRateLimiting

func OptRateLimiting(limit float64, burst int) Option

OptRateLimiting configures the rate limiting.

func OptReadOnly

func OptReadOnly(excluded []elemental.Identity) Option

OptReadOnly sets the server in read only mode.

All write operations will return a Locked HTTP Code (423) This is useful during maintenance. Excluded defines a list of elemental.Identity that will not be affected by the read only mode.

func OptRestServer

func OptRestServer(listen string) Option

OptRestServer configures the listening address of the server.

listen is the general listening address for the API server as

func OptServiceInfo

func OptServiceInfo(name string, version string, subversions map[string]interface{}) Option

OptServiceInfo configures the service basic information.

ServiceName contains the name of the service. ServiceVersion contains the version of the service itself. Version should contain information relative to the service version. like all it's libraries and things like that.

func OptTLS

func OptTLS(certs []tls.Certificate, certRetriever func(*tls.ClientHelloInfo) (*tls.Certificate, error)) Option

OptTLS configures server TLS.

ServerCertificates are the TLS certficates to use for the secure api server. If you set ServerCertificatesRetrieverFunc, the value of ServerCertificates will be ignored. ServerCertificatesRetrieverFunc is standard tls GetCertifcate function to use to retrieve the server certificates dynamically. - If you set this, the value of ServerCertificates will be ignored. - If EnableLetsEncrypt is set, this will be ignored

func OptTimeouts

func OptTimeouts(read, write, idle time.Duration) Option

OptTimeouts configures the timeouts of the server.

func OptTraceCleaner

func OptTraceCleaner(cleaner TraceCleaner) Option

OptTraceCleaner registers a trace cleaner that will be called to let a chance to clean up various sensitive information before sending the trace to the OpenTracing server.

func OptUnmarshallers

func OptUnmarshallers(unmarshallers map[elemental.Identity]CustomUmarshaller) Option

OptUnmarshallers sets the custom unmarshallers.

Unmarshallers contains a list of custom umarshaller per identity. This allows to create custom function to umarshal the payload of a request. If none is provided for a particular identity, the standard unmarshal function is used.

type PatchProcessor

type PatchProcessor interface {
	ProcessPatch(Context) error
}

PatchProcessor is the interface a processor must implement in order to be able to manage OperationPatch.

type Pinger

type Pinger interface {
	Ping(timeout time.Duration) error
}

A Pinger is an interface for objects that implements a Ping method

type Processor

type Processor interface{}

Processor is the interface for a Processor Unit

type PubSubClient

type PubSubClient interface {
	Publish(publication *Publication, opts ...PubSubOptPublish) error
	Subscribe(pubs chan *Publication, errors chan error, topic string, opts ...PubSubOptSubscribe) func()
	Connect() Waiter
	Disconnect() error
}

A PubSubClient is a structure that provides a publish/subscribe mechanism.

func NewLocalPubSubClient

func NewLocalPubSubClient() PubSubClient

NewLocalPubSubClient returns a PubSubClient backed by local channels.

func NewNATSPubSubClient

func NewNATSPubSubClient(natsURL string, options ...NATSOption) PubSubClient

NewNATSPubSubClient returns a new PubSubClient backend by Nats.

type PubSubOptPublish

type PubSubOptPublish func(interface{})

PubSubOptPublish is the type of option that can use in PubSubClient.Publish.

func NATSOptPublishRequireAck

func NATSOptPublishRequireAck(ctx context.Context) PubSubOptPublish

NATSOptPublishRequireAck is a helper to require a ack in the limit of the given context.Context. If the other side is bahamut.PubSubClient using the Subscribe method, then it will automatically send back the expected ack.

This option CANNOT be combined with NATSOptRespondToChannel

func NATSOptRespondToChannel added in v1.44.0

func NATSOptRespondToChannel(ctx context.Context, resp chan *Publication) PubSubOptPublish

NATSOptRespondToChannel will send the *Publication received to the provided channel.

This is an advanced option which is useful in situations where you want to block until you receive a response. The context parameter allows you to provide a deadline on how long you should wait before considering the request as a failure:

myCtx, _ := context.WithTimeout(context.Background(), 5*time.Second)
respCh := make(chan *Publication)
publishOption := NATSOptRespondToChannel(myCtx, respCh)

This option CANNOT be combined with NATSOptPublishRequireAck

type PubSubOptSubscribe

type PubSubOptSubscribe func(interface{})

PubSubOptSubscribe is the type of option that can use in PubSubClient.Subscribe.

func NATSOptSubscribeQueue

func NATSOptSubscribeQueue(queueGroup string) PubSubOptSubscribe

NATSOptSubscribeQueue sets the NATS subscriber queue group. In short, this allows to ensure only one subscriber in the queue group with the same name will receive the publication.

See: https://nats.io/documentation/concepts/nats-queueing/

func NATSOptSubscribeReplyTimeout added in v1.51.0

func NATSOptSubscribeReplyTimeout(t time.Duration) PubSubOptSubscribe

NATSOptSubscribeReplyTimeout sets the duration of time to wait before giving up waiting for a response to publish back to the client that is expecting a response

type Publication

type Publication struct {
	Data         []byte                     `msgpack:"data,omitempty" json:"data,omitempty"`
	Topic        string                     `msgpack:"topic,omitempty" json:"topic,omitempty"`
	Partition    int32                      `msgpack:"partition,omitempty" json:"partition,omitempty"`
	TrackingName string                     `msgpack:"trackingName,omitempty" json:"trackingName,omitempty"`
	TrackingData opentracing.TextMapCarrier `msgpack:"trackingData,omitempty" json:"trackingData,omitempty"`
	Encoding     elemental.EncodingType     `msgpack:"encoding,omitempty" json:"encoding,omitempty"`
	ResponseMode ResponseMode               `msgpack:"responseMode,omitempty" json:"responseMode,omitempty"`
	// contains filtered or unexported fields
}

Publication is a structure that can be published to a PublishServer.

func NewPublication

func NewPublication(topic string) *Publication

NewPublication returns a new Publication.

func (*Publication) Decode

func (p *Publication) Decode(dest interface{}) error

Decode decodes the data into the given dest.

func (*Publication) Duplicate

func (p *Publication) Duplicate() *Publication

Duplicate returns a copy of the publication

func (*Publication) Encode

func (p *Publication) Encode(o interface{}) error

Encode the given object into the publication.

func (*Publication) EncodeWithEncoding

func (p *Publication) EncodeWithEncoding(o interface{}, encoding elemental.EncodingType) error

EncodeWithEncoding the given object into the publication using the given encoding.

func (*Publication) Reply added in v1.51.0

func (p *Publication) Reply(response *Publication) error

Reply will publish the provided publication back to the client. An error is returned if the client was not expecting a response or the supplied publication was nil. If you take too long to reply to a publication an error may be returned in the errors channel you provided in your call to the `Subscribe` method as the client may have given up waiting for your response. Reply can only be called once for

func (*Publication) Span

func (p *Publication) Span() opentracing.Span

Span returns the current tracking span.

func (*Publication) StartTracing

func (p *Publication) StartTracing(tracer opentracing.Tracer, name string)

StartTracing starts a new tracer using wired data if any.

func (*Publication) StartTracingFromSpan

func (p *Publication) StartTracingFromSpan(span opentracing.Span, name string) error

StartTracingFromSpan starts a new child opentracing.Span using the given span as parent.

type PushDispatchHandler

type PushDispatchHandler interface {
	OnPushSessionInit(PushSession) (bool, error)
	OnPushSessionStart(PushSession)
	OnPushSessionStop(PushSession)
	ShouldDispatch(PushSession, *elemental.Event) (bool, error)
}

PushDispatchHandler is the interface that must be implemented in order to to be used as the Bahamut Push Dispatch handler.

type PushPublishHandler

type PushPublishHandler interface {
	ShouldPublish(*elemental.Event) (bool, error)
}

PushPublishHandler is the interface that must be implemented in order to to be used as the Bahamut Push Publish handler.

type PushSession

type PushSession interface {
	Session

	DirectPush(...*elemental.Event)
}

PushSession is a Push Session

type RateLimiter

type RateLimiter interface {
	RateLimit(*http.Request) (bool, error)
}

A RateLimiter is the interface an object must implement in order to limit the rate of the incoming requests.

type RequestAuthenticator

type RequestAuthenticator interface {
	AuthenticateRequest(Context) (AuthAction, error)
}

RequestAuthenticator is the interface that must be implemented in order to to be used as the Bahamut Authenticator.

type ResponseMode added in v1.47.0

type ResponseMode int

ResponseMode represents the response that is expected to be produced by the subscriber handling a publication.

const (
	// ResponseModeNone indicates that no response is expected for the received publication
	ResponseModeNone ResponseMode = iota
	// ResponseModeACK indicates that the subscriber should reply back with an ACK
	// as soon as it has received the publication BEFORE it starts processing the
	// publication.
	ResponseModeACK
	// ResponseModePublication indicates that the subscriber should reply back with a
	// Publication AFTER it has finished processing the publication. Obviously, the
	// subscriber should try to respond ASAP as there is a client waiting for a response.
	ResponseModePublication
)

func (ResponseMode) String added in v1.47.0

func (r ResponseMode) String() string

type RetrieveManyProcessor

type RetrieveManyProcessor interface {
	ProcessRetrieveMany(Context) error
}

RetrieveManyProcessor is the interface a processor must implement in order to be able to manage OperationRetrieveMany.

type RetrieveProcessor

type RetrieveProcessor interface {
	ProcessRetrieve(Context) error
}

RetrieveProcessor is the interface a processor must implement in order to be able to manage OperationRetrieve.

type RouteInfo

type RouteInfo struct {
	Identity string   `msgpack:"identity" json:"identity"`
	URL      string   `msgpack:"url" json:"url"`
	Verbs    []string `msgpack:"verbs,omitempty" json:"verbs,omitempty"`
	Private  bool     `msgpack:"private,omitempty" json:"private,omitempty"`
}

A RouteInfo contains basic information about an api route.

func (RouteInfo) String

func (r RouteInfo) String() string

type Server

type Server interface {

	// RegisterProcessor registers a new Processor for a particular Identity.
	RegisterProcessor(Processor, elemental.Identity) error

	// UnregisterProcessor unregisters a registered Processor for a particular identity.
	UnregisterProcessor(elemental.Identity) error

	// ProcessorForIdentity returns the registered Processor for a particular identity.
	ProcessorForIdentity(elemental.Identity) (Processor, error)

	// ProcessorsCount returns the number of registered processors.
	ProcessorsCount() int

	// Push pushes the given events to all active sessions.
	// It will use the PubSubClient configured in the pushConfig.
	Push(...*elemental.Event)

	// RoutesInfo returns the routing information of the server.
	RoutesInfo() map[int][]RouteInfo

	// VersionsInfo returns additional versioning info.
	VersionsInfo() map[string]interface{}

	// PushEndpoint returns the configured push endpoints.
	// If the push server is not active, it will return an
	// empty string.
	PushEndpoint() string

	// Run runs the server using the given context.Context.
	// You can stop the server by canceling the context.
	Run(context.Context)
}

Server is the interface of a bahamut server.

func New

func New(options ...Option) Server

New returns a new bahamut Server configured with the given options.

func NewServer

func NewServer(cfg config) Server

NewServer returns a new Bahamut Server.

type Session

type Session interface {
	Identifier() string
	Parameter(string) string
	Header(string) string
	SetClaims([]string)
	Claims() []string
	ClaimsMap() map[string]string
	Token() string
	TLSConnectionState() *tls.ConnectionState
	Metadata() interface{}
	SetMetadata(interface{})
	Context() context.Context
}

Session is the interface of a generic websocket session.

type SessionAuthenticator

type SessionAuthenticator interface {
	AuthenticateSession(Session) (AuthAction, error)
}

SessionAuthenticator is the interface that must be implemented in order to be used as the initial Web socket session Authenticator.

type TraceCleaner

type TraceCleaner func(elemental.Identity, []byte) []byte

TraceCleaner is the type of function that can be used to clean a trace data before it is sent to OpenTracing server. You can use this to strip passwords or other sensitive data.

type UpdateProcessor

type UpdateProcessor interface {
	ProcessUpdate(Context) error
}

UpdateProcessor is the interface a processor must implement in order to be able to manage OperationUpdate.

type Waiter

type Waiter interface {
	Wait(time.Duration) bool
}

A Waiter is the interface returned by Server.Connect that you can use to wait for the connection.

Directories

Path Synopsis
authorizer
simple
Package simple provides implementations of bahamut.SessionAuthenticator bahamut.RequestAuthenticator and a bahamut.Authorizer using a given function to decide if a request should be authenticated/authorized.
Package simple provides implementations of bahamut.SessionAuthenticator bahamut.RequestAuthenticator and a bahamut.Authorizer using a given function to decide if a request should be authenticated/authorized.
Package mocks is a generated GoMock package.
Package mocks is a generated GoMock package.

Jump to

Keyboard shortcuts

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