Back to godoc.org
go.aporeto.io/bahamut

Package bahamut

v1.120.0
Latest Go to latest

The latest major version is .

Published: Jun 25, 2020 | License: Apache-2.0 | Module: go.aporeto.io/bahamut

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

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

Variables

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

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.

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.
	//
	// If you use SetOutputData after having already used SetResponseWriter,
	// the call will panic.
	SetOutputData(interface{})

	// SetResponseWriter sets the ResponseWriter function to use to write the response back to the client.
	//
	// No additional operation or check will be performed by Bahamut. You are responsible
	// for correctly encoding the response, setting the header etc. This is useful when
	// you want to handle a route that is note really fitting in the handling of an elemental Model
	// like for instance handling file download, response streaming etc.
	//
	// If you use SetResponseWriter after having already used SetOutputData,
	// the call will panic.
	SetResponseWriter(ResponseWriter)

	// 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

	// SetNext can be use to give the next pagination token.
	SetNext(string)

	// 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{}

	// outputCookies adds cookies to the response that
	// will be returned to the client.
	AddOutputCookies(cookies ...*http.Cookie)
}

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 CustomMarshaller

type CustomMarshaller func(*elemental.Response, interface{}, error) ([]byte, error)

CustomMarshaller is the type of function use to create custom marshalling.

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 IdentifiableRetriever

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

An IdentifiableRetriever is the type of function you can use to perform transparent patch support using elemental.SparseIdentifiable. If this is set in the configuration, the handler for PATCH method will use this function to retrieve the target identifiable, will apply the patch and treat the request as a standard update.

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()
	RegisterTCPConnection()
	UnregisterTCPConnection()
	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

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 OptCORSOrigin

func OptCORSOrigin(origin string) Option

OptCORSOrigin sets the allowed origin for CORS requests. If not set, bahamut will use the HTTP Header `Origin` and if it cannot find it, it will use `*`. If this option is set, the given origin will always be used.

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

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 OptHTTPLogger

func OptHTTPLogger(l *log.Logger) Option

OptHTTPLogger sets the logger to be used internally by the underlying Go HTTP server.

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 OptIdentifiableRetriever

func OptIdentifiableRetriever(f IdentifiableRetriever) Option

OptIdentifiableRetriever sets the IdentifiableRetriever tha will be used to perform transparent patch support using elemental.SparseIdentifiable. When set, the handler for PATCH method will use this function to retrieve the target identifiable, will apply the patch and treat the request as a standard elemental update operation.

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 OptMarshallers

func OptMarshallers(marshallers map[elemental.Identity]CustomMarshaller) Option

OptMarshallers sets the custom marshallers.

Marshallers contains a list of custom marshaller per identity. This allows to create custom function to marshal the payload of a response. If none is provided for a particular identity, the standard unmarshal function is used.

func OptMaxConnection

func OptMaxConnection(n int) Option

OptMaxConnection sets the maximum number of concurrent connection to the server. 0, which is the default, means no limit.

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 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 OptTLSDisableSessionTicket

func OptTLSDisableSessionTicket(disabled bool) Option

OptTLSDisableSessionTicket controls if the TLS session tickets should be disabled.

func OptTLSNextProtos

func OptTLSNextProtos(nextProtos []string) Option

OptTLSNextProtos configures server TLS next protocols.

You can use it to set it to []string{'h2'} for instance to enable http2

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

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

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

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 is called when a new push session wants to connect.
	// If it returns false, the push session will be considered
	// as forbidden. If it returns an error, it will be returned
	// to the client.
	OnPushSessionInit(PushSession) (bool, error)

	// OnPushSessionStart is called when a new push session starts.
	OnPushSessionStart(PushSession)

	// OnPushSessionStart is called when a new push session terminated.
	OnPushSessionStop(PushSession)

	// ShouldDispatch is called to decide if the given event should be sent to the given session.
	// The last parameter will contain whatever has been returned by SummarizeEvent.
	// It is NOT safe to modify the given *elemental.Event. This would cause
	// race conditions. You can only safely read from it.
	ShouldDispatch(PushSession, *elemental.Event, interface{}) (bool, error)

	// RelatedEventIdentities allows to return a list of related identities
	// associated to the main event identity. This allows to pass filtering
	// in case a push on identity A must also trigger a push on identity B and C.
	RelatedEventIdentities(string) []string

	// SummarizeEvent is called once per event and allows the implementation
	// to return an interface that will be passed to ShouldDispatch.
	// If you need to decode an event to read some information to make a
	// dispatch decision, this is a good place as it will allow you to only
	// do this once.
	SummarizeEvent(event *elemental.Event) (interface{}, 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

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

func (r ResponseMode) String() string

type ResponseWriter

type ResponseWriter func(w http.ResponseWriter) int

A ResponseWriter is a function you can use in the Context to handle the writing of the response by yourself. You are responsible for the full handling of the response, including encoding, setting the CORS headers etc.

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
	PushConfig() *elemental.PushConfig
	SetClaims([]string)
	Claims() []string
	ClaimsMap() map[string]string
	Token() string
	TLSConnectionState() *tls.ConnectionState
	Metadata() interface{}
	SetMetadata(interface{})
	Context() context.Context
	ClientIP() string
	Cookie(string) (*http.Cookie, error)
}

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.

Package Files

Documentation was rendered with GOOS=linux and GOARCH=amd64.

Jump to identifier

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to identifier