Documentation
¶
Overview ¶
Package cocaine12 provides primitives, interfaces and structs to work with Cocaine Application Engine
Index ¶
- Constants
- Variables
- func AttachTraceInfo(ctx context.Context, traceInfo TraceInfo) context.Context
- func BeginNewTraceContext(ctx context.Context) context.Context
- func BeginNewTraceContextWithLogger(ctx context.Context, logger Logger) context.Context
- func CleanTraceInfo(ctx context.Context) context.Context
- func DefaultFallbackHandler(ctx context.Context, event string, request Request, response Response)
- func HeadersCocaineToHTTP(hdr Headers) http.Header
- func Register(name string, factory TokenManagerFactory)
- func TokenManagers() []string
- func UnpackProxyRequest(raw []byte) (*http.Request, error)
- func WrapHTTPFuncs(...) map[string]EventHandler
- func WrapHandleFuncs(hfs map[string]http.HandlerFunc) map[string]EventHandler
- func WriteHead(code int, headers Headers) []byte
- type Channel
- type CloseSpan
- type CocaineHeaders
- type CommonMessageInfo
- type ConnectionError
- type DefaultValues
- type EndpointItem
- type Entry
- func (e *Entry) Debug(args ...interface{})
- func (e *Entry) Debugf(format string, args ...interface{})
- func (e *Entry) Err(args ...interface{})
- func (e *Entry) Errf(format string, args ...interface{})
- func (e *Entry) Info(args ...interface{})
- func (e *Entry) Infof(format string, args ...interface{})
- func (e *Entry) Warn(args ...interface{})
- func (e *Entry) Warnf(format string, args ...interface{})
- type EntryLogger
- type ErrRequest
- type EventHandler
- type EventHandlers
- type FallbackEventHandler
- type Fields
- type Headers
- type Locator
- type Logger
- type Message
- type MultiConnectionError
- type NullTokenManager
- type ReaderWithContext
- type Request
- type RequestHandler
- type Response
- type ResponseStream
- type ResponseWriter
- type Rx
- type Service
- type ServiceError
- type ServiceInfo
- type ServiceResult
- type Severity
- type StreamDescriptionItem
- type TerminationHandler
- type Token
- type TokenManager
- type TokenManagerFactory
- type TraceInfo
- type Tx
- type Worker
- func (w *Worker) EnableStackSignal(enable bool)
- func (w *Worker) On(event string, handler EventHandler)
- func (w *Worker) Run(handlers map[string]EventHandler) error
- func (w *Worker) SetDebug(debug bool)
- func (w *Worker) SetFallbackHandler(handler FallbackEventHandler)
- func (w *Worker) SetTerminationHandler(handler TerminationHandler)
- func (w *Worker) Stop()
- func (w *Worker) Token() Token
- type WorkerNG
Constants ¶
const ( TraceInfoValue = "trace.traceinfo" TraceStartTimeValue = "trace.starttime" )
const ( // ErrorNoEventHandler returns when there is no handler for a given event ErrorNoEventHandler = 200 // ErrorPanicInHandler returns when a handler is recovered from panic ErrorPanicInHandler = 100 )
const (
ErrDisconnected = -100
)
Variables ¶
var ( // ErrStreamIsClosed means that a response stream is closed ErrStreamIsClosed = errors.New("Stream is closed") // ErrBadPayload means that a message payload is malformed ErrBadPayload = errors.New("payload is not []byte") // ErrMalformedErrorMessage means that we receive a corrupted or // unproper message ErrMalformedErrorMessage = &ErrRequest{ Message: "malformed error message", Category: cworkererrorcategory, Code: cdefaulterrrorcode, } )
var ( ErrInvalidHeaderLength = errors.New("invalid header size") ErrInvalidHeaderType = errors.New("invalid header type") ErrInvalidTraceType = errors.New("invalid trace header number type") ErrInvalidTraceNumber = errors.New("invalid trace header number") ErrInvalidTraceValueType = errors.New("invalid trace value type") ErrNotAllTracesPresent = errors.New("not all trace values present") )
var ( // ErrDisowned raises when the worker doesn't receive // a heartbeat message during a heartbeat timeout ErrDisowned = errors.New("disowned from cocaine-runtime") // ErrNoCocaineEndpoint means that the worker doesn't know an endpoint // to Cocaine ErrNoCocaineEndpoint = errors.New("cocaine endpoint must be specified") // ErrConnectionLost means that the connection between the worker and // runtime has been lost ErrConnectionLost = errors.New("the connection to runtime has been lost") )
var ( // ErrZeroEndpoints returns from serviceCreateIO if passed `endpoints` is an empty array ErrZeroEndpoints = errors.New("Endpoints must contain at least one item") )
Functions ¶
func AttachTraceInfo ¶
AttachTraceInfo binds given TraceInfo to the context. If ctx is nil, then TraceInfo will be attached to context.Background()
func BeginNewTraceContext ¶
It might be used in client applications.
func CleanTraceInfo ¶
CleanTraceInfo might be used to clear context instance from trace info to disable tracing in some RPC calls to get rid of overhead
func DefaultFallbackHandler ¶
DefaultFallbackHandler sends an error message if a client requests unhandled event
func HeadersCocaineToHTTP ¶
HeadersCocaineToHTTP converts Cocaine representation of headers to net/http.Header
func Register ¶
func Register(name string, factory TokenManagerFactory)
Register makes a token manager factory available by the provided name. If Register is called twice with the same name or if factory is nil, it panics.
func TokenManagers ¶
func TokenManagers() []string
TokenManagers returns a sorted list of the names of the registered token manager factories.
func UnpackProxyRequest ¶
UnpackProxyRequest unpacks a HTTPRequest from a serialized cocaine form
func WrapHTTPFuncs ¶
func WrapHTTPFuncs(hfs map[string]func(ctx context.Context, w http.ResponseWriter, req *http.Request)) map[string]EventHandler
func WrapHandleFuncs ¶
func WrapHandleFuncs(hfs map[string]http.HandlerFunc) map[string]EventHandler
WrapHandleFuncs wraps the bunch of http.Handlers to allow them handle requests via Worker
Types ¶
type CloseSpan ¶
type CloseSpan func()
CloseSpan closes attached span. It should be call after the rpc ends.
func NewSpan ¶
func NewSpan(ctx context.Context, rpcNameFormat string, args ...interface{}) (context.Context, CloseSpan)
NewSpan starts new span and returns a context with attached TraceInfo and Done. If ctx is nil or has no TraceInfo new span won't start to support sampling, so it's user responsibility to make sure that the context has TraceInfo. Anyway it safe to call CloseSpan function even in this case, it actually does nothing.
type CocaineHeaders ¶
type CocaineHeaders []interface{}
type CommonMessageInfo ¶
type CommonMessageInfo struct { // Session id Session uint64 // Message type number MsgType uint64 }
CommonMessageInfo consists of a session number and a message type
type ConnectionError ¶
type ConnectionError struct { EndpointItem Err error }
ConnectionError contains an error and an endpoint
type DefaultValues ¶
type DefaultValues interface { ApplicationName() string Debug() bool Endpoint() string Locators() []string Protocol() int UUID() string DC() string Token() Token }
DefaultValues provides an interface to read various information provided by Cocaine-Runtime to the worker
type EndpointItem ¶
EndpointItem is one of possible endpoints of a service
func (*EndpointItem) String ¶
func (e *EndpointItem) String() string
type EntryLogger ¶
type EntryLogger interface { Errf(format string, args ...interface{}) Err(args ...interface{}) Warnf(format string, args ...interface{}) Warn(args ...interface{}) Infof(format string, args ...interface{}) Info(args ...interface{}) Debugf(format string, args ...interface{}) Debug(args ...interface{}) }
type ErrRequest ¶
func (*ErrRequest) Error ¶
func (e *ErrRequest) Error() string
type EventHandler ¶
EventHandler represents a type of handler
func WrapHTTPFunc ¶
func WrapHTTPFunc(handler func(ctx context.Context, w http.ResponseWriter, req *http.Request)) EventHandler
func WrapHandler ¶
func WrapHandler(handler http.Handler) EventHandler
WrapHandler provides opportunity for using Go web frameworks, which supports http.Handler interface
Trivial example which is used martini web framework import ( "github.com/cocaine/cocaine-framework-go/cocaine" "github.com/codegangsta/martini" ) func main() { m := martini.Classic() m.Get("", func() string { return "This is an example server" }) m.Get("/hw", func() string { return "Hello world!" }) binds := map[string]cocaine.EventHandler{ "example": cocaine.WrapHandler(m, nil), } if worker, err := cocaine.NewWorker(); err == nil{ worker.Loop(binds) }else{ panic(err) } }
func WrapHandlerFunc ¶
func WrapHandlerFunc(hf http.HandlerFunc) EventHandler
WrapHandlerFunc provides opportunity for using Go web frameworks, which supports http.HandlerFunc interface
Trivial example is import ( "net/http" "github.com/cocaine/cocaine-framework-go/cocaine" ) func handler(w http.ResponseWriter, req *http.Request) { w.Header().Set("Content-Type", "text/plain") w.Write([]byte("This is an example server.\n")) } func main() { binds := map[string]cocaine.EventHandler{ "example": cocaine.WrapHandlerFunc(handler, nil), } if worker, err := cocaine.NewWorker(); err == nil{ worker.Loop(binds) }else{ panic(err) } }
type EventHandlers ¶
type EventHandlers struct {
// contains filtered or unexported fields
}
func NewEventHandlers ¶
func NewEventHandlers() *EventHandlers
func NewEventHandlersFromMap ¶
func NewEventHandlersFromMap(handlers map[string]EventHandler) *EventHandlers
func (*EventHandlers) On ¶
func (e *EventHandlers) On(name string, handler EventHandler)
func (*EventHandlers) SetFallbackHandler ¶
func (e *EventHandlers) SetFallbackHandler(handler RequestHandler)
SetFallbackHandler sets the handler to be a fallback handler
type FallbackEventHandler ¶
type FallbackEventHandler RequestHandler
FallbackEventHandler handles an event if there is no other handler for the given event
type Headers ¶
type Headers [][2]string
Headers are packed as a tuple of tuples HTTP headers from Cocaine
func HeadersHTTPtoCocaine ¶
HeadersHTTPtoCocaine converts net/http.Header to Cocaine representation
type Locator ¶
type Locator interface { Resolve(ctx context.Context, name string) (*ServiceInfo, error) Close() }
Locator is used to Resolve new services. It should be closed after last usage
func NewLocator ¶
NewLocator creates a new Locator using given endpoints
type Logger ¶
type Logger interface { EntryLogger WithFields(Fields) *Entry Verbosity(context.Context) Severity V(level Severity) bool Close() // contains filtered or unexported methods }
Logger represents an interface for a cocaine.Logger
type Message ¶
type Message struct { // _struct bool `codec:",toarray"` CommonMessageInfo Payload []interface{} Headers CocaineHeaders }
type MultiConnectionError ¶
type MultiConnectionError []ConnectionError
MultiConnectionError returns from a connector which iterates over provided endpoints
func (MultiConnectionError) Error ¶
func (m MultiConnectionError) Error() string
type NullTokenManager ¶
type NullTokenManager struct{}
NullTokenManager represents no-op token manager. It always returns an empty token.
func (*NullTokenManager) Stop ¶
func (t *NullTokenManager) Stop()
func (*NullTokenManager) Token ¶
func (t *NullTokenManager) Token() Token
type ReaderWithContext ¶
func RequestReader ¶
func RequestReader(ctx context.Context, req Request) ReaderWithContext
type RequestHandler ¶
RequestHandler represents a type of handler
type ResponseStream ¶
type ResponseStream interface { io.WriteCloser // ZeroCopyWrite sends data to a client. // Response takes the ownership of the buffer, so provided buffer must not be edited. ZeroCopyWrite(data []byte) error ErrorMsg(code int, message string) error }
ResponseStream provides an interface for a handler to reply
type ResponseWriter ¶
type ResponseWriter struct {
// contains filtered or unexported fields
}
ResponseWriter implements http.ResponseWriter interface. It implements cocaine integration.
func (*ResponseWriter) Header ¶
func (w *ResponseWriter) Header() http.Header
Header returns the header map that will be sent by WriteHeader
func (*ResponseWriter) Write ¶
func (w *ResponseWriter) Write(data []byte) (n int, err error)
Write writes the data to the connection as part of an HTTP reply
func (*ResponseWriter) WriteHeader ¶
func (w *ResponseWriter) WriteHeader(code int)
WriteHeader sends an HTTP response header with status code
func (*ResponseWriter) WriteString ¶
func (w *ResponseWriter) WriteString(data string) (n int, err error)
WriteString writes the string to the connection as part of an HTTP reply
type Rx ¶
type Rx interface { Get(context.Context) (ServiceResult, error) Closed() bool // contains filtered or unexported methods }
type Service ¶
type Service struct { *ServiceInfo // contains filtered or unexported fields }
Allows you to invoke methods of services and send events to other cloud applications.
func NewService ¶
func (*Service) Call ¶
func (service *Service) Call(ctx context.Context, name string, args ...interface{}) (Channel, error)
Calls a remote method by name and pass args
type ServiceError ¶
func (*ServiceError) Error ¶
func (err *ServiceError) Error() string
type ServiceInfo ¶
type ServiceInfo struct { Endpoints []EndpointItem Version uint64 API dispatchMap }
type ServiceResult ¶
type StreamDescriptionItem ¶
type StreamDescriptionItem struct { Name string Description *streamDescription }
type TerminationHandler ¶
TerminationHandler invokes when termination message is received
type Token ¶
type Token struct {
// contains filtered or unexported fields
}
Token carries information about an authorization token.
type TokenManager ¶
type TokenManager interface { Token() Token Stop() }
TokenManager automates tokens housekeeping, like timely updation to be able to always provide the most fresh tokens.
func NewTokenManager ¶
func NewTokenManager(appName string, token Token) (TokenManager, error)
type TokenManagerFactory ¶
type TokenManagerFactory interface {
Create(appName string, token Token) (TokenManager, error)
}
type TraceInfo ¶
type TraceInfo struct {
Trace, Span, Parent uint64
// contains filtered or unexported fields
}
func GetTraceInfo ¶
type Worker ¶
type Worker struct {
// contains filtered or unexported fields
}
Worker performs IO operations between an application and cocaine-runtime, dispatches incoming messages This is an adapter to WorkerNG
func NewWorker ¶
NewWorker connects to the cocaine-runtime and create WorkerNG on top of this connection
func (*Worker) EnableStackSignal ¶
EnableStackSignal allows/disallows the worker to catch SIGUSR1 to print all goroutines stacks. It's enabled by default. This function must be called before Worker.Run to take effect.
func (*Worker) On ¶
func (w *Worker) On(event string, handler EventHandler)
On binds the handler for a given event
func (*Worker) SetDebug ¶
SetDebug enables debug mode of the Worker. It allows to print Stack of a paniced handler
func (*Worker) SetFallbackHandler ¶
func (w *Worker) SetFallbackHandler(handler FallbackEventHandler)
SetFallbackHandler sets the handler to be a fallback handler
func (*Worker) SetTerminationHandler ¶
func (w *Worker) SetTerminationHandler(handler TerminationHandler)
SetTerminationHandler allows to attach handler which will be called when SIGTERM arrives
type WorkerNG ¶
type WorkerNG struct {
// contains filtered or unexported fields
}
WorkerNG performs IO operations between an application and cocaine-runtime, dispatches incoming messages
func NewWorkerNG ¶
NewWorkerNG connects to the cocaine-runtime and create WorkerNG on top of this connection
func (*WorkerNG) EnableStackSignal ¶
EnableStackSignal allows/disallows the worker to catch SIGUSR1 to print all goroutines stacks. It's enabled by default. This function must be called before Worker.Run to take effect.
func (*WorkerNG) Run ¶
func (w *WorkerNG) Run(handler RequestHandler, terminationHandler TerminationHandler) error
Run makes the worker anounce itself to a cocaine-runtime as being ready to hadnle incoming requests and hablde them terminationHandler allows to attach handler which will be called when SIGTERM arrives
Source Files
¶
- apilocator.go
- asocket.go
- channel.go
- clogger.go
- defaults.go
- dispatch.go
- doc.go
- entry.go
- fallbacklogger.go
- handler.go
- httphandler.go
- httpresponse.go
- locator.go
- logger.go
- protocol.go
- service.go
- serviceinfo.go
- sessions.go
- severity.go
- stack.go
- token.go
- trace.go
- utils.go
- version.go
- worker.go
- worker_handlers.go
- worker_protocol.go
- workerng.go
- wprotov1.go