bahamut

package module
v1.148.0 Latest Latest
Warning

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

Go to latest
Published: Aug 11, 2023 License: Apache-2.0 Imports: 40 Imported by: 14

README

Bahamut

Codacy Badge Codacy Badge

Note: this is a work in progress.

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 (manipmongo), MemDB (manipmemory) or can be used to issue ReST calls using maniphttp.

It is usually used by clients to interact with the API of a Bahamut service, but also used for Bahamut Services to talk together.

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"
)
View Source
const CORSOriginMirror = "_mirror_"

CORSOriginMirror instruts to mirror any incoming origin. This should not be used in production as this is a development feature that is not secure.

Variables

View Source
var (
	// ErrInvalidAPIVersion is returned when the url cannot be parsed
	// to find a valid version.
	ErrInvalidAPIVersion = elemental.NewError("Bad Request", fmt.Sprintf("Invalid api version number"), "bahamut", http.StatusBadRequest)

	// ErrUnknownAPIVersion when there is no elemental.ModelManager configured
	// to handle the requested version of the api.
	ErrUnknownAPIVersion = elemental.NewError("Bad Request", fmt.Sprintf("Unknown api version"), "bahamut", http.StatusBadRequest)
)
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 RegisterCustomHandlerOrDie added in v1.112.1

func RegisterCustomHandlerOrDie(server Server, handler http.HandlerFunc, path string)

RegisterCustomHandlerOrDie will register a handler for a given path. This is just a helper for the Server.Register Identity and will exit in case of errors. This is just a helper for Server.RegisterCustomRouteHandler function.

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 CORSPolicy added in v1.140.0

type CORSPolicy struct {
	AllowOrigin      string
	AllowHeaders     []string
	AllowMethods     []string
	ExposeHeaders    []string
	MaxAge           int
	AllowCredentials bool
	// contains filtered or unexported fields
}

CORSPolicy allows to configure CORS Access Control header of a response.

func (*CORSPolicy) Inject added in v1.140.0

func (a *CORSPolicy) Inject(h http.Header, origin string, preflight bool)

Inject injects the CORS header on the given http.Header. It will use the given request origin to determine the allow origin policy and the method to determine if it should inject pre-flight OPTIONS header. If the given http.Header is nil, this function is a no op.

type CORSPolicyController added in v1.140.0

type CORSPolicyController interface {

	// PolicyForRequest returns the CORSPolicy to
	// apply for the given http.Request.
	PolicyForRequest(*http.Request) *CORSPolicy
}

A CORSPolicyController allows to return the CORS policy for a given http.Request.

func NewDefaultCORSController added in v1.140.0

func NewDefaultCORSController(origin string, additionalOrigins []string) CORSPolicyController

NewDefaultCORSController returns a CORSPolicyController that always returns a CORSAccessControlPolicy with sensible defaults.

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() any

	// SetInputData replaces the current input data.
	SetInputData(any)

	// OutputData returns the current output data.
	OutputData() any

	// 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(any)

	// SetDisableOutputDataPush will instruct the bahamut server to
	// not automatically push the content of OutputData.
	SetDisableOutputDataPush(bool)

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

	// Metadata returns the opaque data set by using SetMetadata().
	Metadata(key any) any

	// 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 added in v1.76.0

type CustomMarshaller func(*elemental.Response, any, 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) time.Duration

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 added in v1.104.0

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, path 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 MockContext added in v1.140.0

type MockContext struct {
	MockCtx                   context.Context
	MockOutputData            any
	MockInputData             any
	MockMetadata              map[any]any
	MockClaimsMap             map[string]string
	MockResponseWriter        ResponseWriter
	MockRequest               *elemental.Request
	MockRedirect              string
	MockNext                  string
	MockID                    string
	MockMessages              []string
	MockOutputCookies         []*http.Cookie
	MockClaims                []string
	MockEvents                elemental.Events
	MockCount                 int
	MockStatusCode            int
	MockDisableOutputDataPush bool
}

A MockContext can be used to mock a bahamut.Context to help writing unit tests.

func NewMockContext added in v1.140.0

func NewMockContext(ctx context.Context) *MockContext

NewMockContext returns a new MockContext.

func (*MockContext) AddMessage added in v1.140.0

func (c *MockContext) AddMessage(msg string)

AddMessage adds a message to the context.

func (*MockContext) AddOutputCookies added in v1.140.0

func (c *MockContext) AddOutputCookies(cookies ...*http.Cookie)

AddOutputCookies add the given cookie to the context.

func (*MockContext) Claims added in v1.140.0

func (c *MockContext) Claims() []string

Claims returns the user claims associated to the context.

func (*MockContext) ClaimsMap added in v1.140.0

func (c *MockContext) ClaimsMap() map[string]string

ClaimsMap returns the user claims as a map.

func (*MockContext) Context added in v1.140.0

func (c *MockContext) Context() context.Context

Context returns the context.Context.

func (*MockContext) Count added in v1.140.0

func (c *MockContext) Count() int

Count returns the context's count.

func (*MockContext) Duplicate added in v1.140.0

func (c *MockContext) Duplicate() Context

Duplicate creates a copy of the context.

func (*MockContext) EnqueueEvents added in v1.140.0

func (c *MockContext) EnqueueEvents(events ...*elemental.Event)

EnqueueEvents enqueus the given additional event in the context's queue.

func (*MockContext) Identifier added in v1.140.0

func (c *MockContext) Identifier() string

Identifier returns the context identifier.

func (*MockContext) InputData added in v1.140.0

func (c *MockContext) InputData() any

InputData returns the context's input data.

func (*MockContext) Metadata added in v1.140.0

func (c *MockContext) Metadata(key any) any

Metadata returtns the metadata associated to the given key.

func (*MockContext) OutputData added in v1.140.0

func (c *MockContext) OutputData() any

OutputData returns the context's output data.

func (*MockContext) Redirect added in v1.140.0

func (c *MockContext) Redirect() string

Redirect returns the context's redirect url.

func (*MockContext) Request added in v1.140.0

func (c *MockContext) Request() *elemental.Request

Request returns the context's request.

func (*MockContext) SetClaims added in v1.140.0

func (c *MockContext) SetClaims(claims []string)

SetClaims sets the user claims associated to the context.

func (*MockContext) SetCount added in v1.140.0

func (c *MockContext) SetCount(count int)

SetCount sets the context's count.

func (*MockContext) SetDisableOutputDataPush added in v1.140.0

func (c *MockContext) SetDisableOutputDataPush(disabled bool)

SetDisableOutputDataPush disables automatic pushing of output data.

func (*MockContext) SetInputData added in v1.140.0

func (c *MockContext) SetInputData(data any)

SetInputData sets the context's input data.

func (*MockContext) SetMetadata added in v1.140.0

func (c *MockContext) SetMetadata(key, value any)

SetMetadata sets the metadata values for the given key.

func (*MockContext) SetNext added in v1.140.0

func (c *MockContext) SetNext(next string)

SetNext sets the context's next value.

func (*MockContext) SetOutputData added in v1.140.0

func (c *MockContext) SetOutputData(data any)

SetOutputData sets the context's output data.

func (*MockContext) SetRedirect added in v1.140.0

func (c *MockContext) SetRedirect(url string)

SetRedirect sets the context's redirect url.

func (*MockContext) SetResponseWriter added in v1.140.0

func (c *MockContext) SetResponseWriter(writer ResponseWriter)

SetResponseWriter sets the context's custom response writer.

func (*MockContext) SetStatusCode added in v1.140.0

func (c *MockContext) SetStatusCode(code int)

SetStatusCode sets the context's status code.

func (*MockContext) StatusCode added in v1.140.0

func (c *MockContext) StatusCode() int

StatusCode returns the context's status code.

type MockSession added in v1.140.0

type MockSession struct {
	MockMetadata           any
	MockClaimsMap          map[string]string
	MockCookies            map[string]*http.Cookie
	MockHeaders            map[string]string
	MockParameters         map[string]string
	MockPushConfig         *elemental.PushConfig
	MockTLSConnectionState *tls.ConnectionState
	MockDirectPush         func(...*elemental.Event)
	MockClientIP           string
	MockIdentifier         string
	MockToken              string
	MockClaims             []string
}

A MockSession can be used to mock a bahamut.Session.

func NewMockSession added in v1.140.0

func NewMockSession() *MockSession

NewMockSession returns a new MockSession.

func (*MockSession) Claims added in v1.140.0

func (s *MockSession) Claims() []string

Claims is part of the PushSession interface.

func (*MockSession) ClaimsMap added in v1.140.0

func (s *MockSession) ClaimsMap() map[string]string

ClaimsMap is part of the PushSession interface.

func (*MockSession) ClientIP added in v1.140.0

func (s *MockSession) ClientIP() string

ClientIP is part of the PushSession interface.

func (*MockSession) Context added in v1.140.0

func (s *MockSession) Context() context.Context

Context is part of the PushSession interface.

func (*MockSession) Cookie added in v1.140.0

func (s *MockSession) Cookie(c string) (*http.Cookie, error)

Cookie is part of the Session interface.

func (*MockSession) DirectPush added in v1.140.0

func (s *MockSession) DirectPush(evts ...*elemental.Event)

DirectPush is part of the PushSession interface

func (*MockSession) Header added in v1.140.0

func (s *MockSession) Header(k string) string

Header is part of the PushSession interface.

func (*MockSession) Identifier added in v1.140.0

func (s *MockSession) Identifier() string

Identifier is part of the PushSession interface.

func (*MockSession) Metadata added in v1.140.0

func (s *MockSession) Metadata() any

Metadata is part of the PushSession interface.

func (*MockSession) Parameter added in v1.140.0

func (s *MockSession) Parameter(k string) string

Parameter is part of the PushSession interface.

func (*MockSession) PushConfig added in v1.140.0

func (s *MockSession) PushConfig() *elemental.PushConfig

PushConfig is part of the PushSession interface.

func (*MockSession) SetClaims added in v1.140.0

func (s *MockSession) SetClaims(claims []string)

SetClaims is part of the PushSession interface.

func (*MockSession) SetMetadata added in v1.140.0

func (s *MockSession) SetMetadata(m any)

SetMetadata is part of the PushSession interface.

func (*MockSession) TLSConnectionState added in v1.140.0

func (s *MockSession) TLSConnectionState() *tls.ConnectionState

TLSConnectionState is part of the PushSession interface.

func (*MockSession) Token added in v1.140.0

func (s *MockSession) Token() string

Token is part of the PushSession interface.

type NATSOption

type NATSOption func(*natsPubSub)

A NATSOption represents an option to the pubsub backed by nats

func NATSErrorHandler added in v1.112.1

func NATSErrorHandler(handler func(*nats.Conn, *nats.Subscription, error)) NATSOption

NATSErrorHandler sets the error handler to install in nats client.

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 OptAPIRateLimiting added in v1.112.1

func OptAPIRateLimiting(identity elemental.Identity, limit float64, burst int, condition func(*elemental.Request) bool) Option

OptAPIRateLimiting configures the per-api rate limiting. The optional parameter condition is a function that can be provided to decide if the rate limiter should apply based on the custom computation iof the incoming request.

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 OptCORSAccessControl added in v1.140.0

func OptCORSAccessControl(controller CORSPolicyController) Option

OptCORSAccessControl configures CORS access control policy.

By default, no CORS headers are injected by bahamut. You can use NewDefaultCORSAccessControler to get a sensible default policy.

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 OptEnableAPIPathPrefix added in v1.112.1

func OptEnableAPIPathPrefix(prefix string) Option

OptEnableAPIPathPrefix enables a path prefix for all API resources other than root. This enables customization of the paths of the API endpoints.

func OptEnableCustomRoutePathPrefix added in v1.112.1

func OptEnableCustomRoutePathPrefix(prefix string) Option

OptEnableCustomRoutePathPrefix enables custom routes in the server that start with the given prefix. A user must also provide an API prefix in this case and the two must not overlap. Otherwise, the configuration will be rejected.

func OptErrorTransformer added in v1.112.1

func OptErrorTransformer(f func(error) error) Option

OptErrorTransformer sets the error transformer func to use. If non nil, this will be called to eventually transform the error before converting it to the elemental.Errors that will be returned to the client. If the function return nil, the original error will be used.

func OptHTTPLogger added in v1.112.1

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 added in v1.104.0

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 OptMTLSVerifyPeerCertificates added in v1.140.0

func OptMTLSVerifyPeerCertificates(f func([][]byte, [][]*x509.Certificate) error) Option

OptMTLSVerifyPeerCertificates configures the optionnal function to to perform custom peer certificate verification.

func OptMarshallers added in v1.76.0

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 added in v1.112.1

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 OptPushServerEnableSubjectHierarchies added in v1.112.1

func OptPushServerEnableSubjectHierarchies() Option

OptPushServerEnableSubjectHierarchies will cause the push server to push to specific subject hierarchies under the configured pub/sub topic you have chosen for your push server. This option has no effect if OptPushServer is not set.

For example:

If the push server topic has been set to "global-events" and the server is about to push a "create" event w/ an identity
value of "apples", enabling this option, would cause the push server to target a new publication to the subject
"global-events.apples.create", INSTEAD OF "global-events". Consequently, as a result of this, any upstream push
servers that are interested in receiving all events you publish to this topic would need to utilize subject wildcards.

See: https://docs.nats.io/nats-concepts/subjects#wildcards for more details.

func OptRateLimiting

func OptRateLimiting(limit float64, burst int) Option

OptRateLimiting configures the global 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]any) 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 added in v1.112.1

func OptTLSDisableSessionTicket(disabled bool) Option

OptTLSDisableSessionTicket controls if the TLS session tickets should be disabled.

func OptTLSNextProtos added in v1.112.1

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 any

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(ctx context.Context) error
	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(any)

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(any)

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 {
	TrackingData opentracing.TextMapCarrier `msgpack:"trackingData,omitempty" json:"trackingData,omitempty"`

	Topic        string                 `msgpack:"topic,omitempty" json:"topic,omitempty"`
	TrackingName string                 `msgpack:"trackingName,omitempty" json:"trackingName,omitempty"`
	Encoding     elemental.EncodingType `msgpack:"encoding,omitempty" json:"encoding,omitempty"`
	Data         []byte                 `msgpack:"data,omitempty" json:"data,omitempty"`
	ResponseMode ResponseMode           `msgpack:"responseMode,omitempty" json:"responseMode,omitempty"`
	Partition    int32                  `msgpack:"partition,omitempty" json:"partition,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 any) 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 any) error

Encode the given object into the publication.

func (*Publication) EncodeWithEncoding

func (p *Publication) EncodeWithEncoding(o any, 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 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, any) (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) (any, 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 ResponseWriter added in v1.112.1

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

	// RegisterCustomRouteHandler registers a generic HTTP handler for a given
	// path. Users are responsible for all processing in this path.
	RegisterCustomRouteHandler(path string, handler http.HandlerFunc) error

	// UnregisterCustomRouteHandler unregisters a generic HTTP handler for a path.
	UnregisterCustomRouteHandler(path string) error

	// CustomHandlers returns a map of all the custom handlers.
	CustomHandlers() map[string]http.HandlerFunc

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

	// 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() any
	SetMetadata(any)
	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.

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.

Jump to

Keyboard shortcuts

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