fieldalignment of all structs to save memory

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
This commit is contained in:
Василий Толстов 2021-03-06 19:45:13 +03:00
parent cb70dfa664
commit bbbcb22565
65 changed files with 667 additions and 671 deletions

View File

@ -34,20 +34,20 @@ type Option func(*Options) error
type Endpoint struct { type Endpoint struct {
// Name Greeter.Hello // Name Greeter.Hello
Name string Name string
// Description e.g what's this endpoint for // Desciption for endpoint
Description string Description string
// Handler e.g rpc, proxy // Handler e.g rpc, proxy
Handler string Handler string
// Body destination
// "*" or "" - top level message value
// "string" - inner message value
Body string
// Host e.g example.com // Host e.g example.com
Host []string Host []string
// Method e.g GET, POST // Method e.g GET, POST
Method []string Method []string
// Path e.g /greeter. Expect POSIX regex // Path e.g /greeter. Expect POSIX regex
Path []string Path []string
// Body destination
// "*" or "" - top level message value
// "string" - inner message value
Body string
// Stream flag // Stream flag
Stream bool Stream bool
} }

View File

@ -13,11 +13,11 @@ var (
// Options struct holds handler options // Options struct holds handler options
type Options struct { type Options struct {
MaxRecvSize int64
Namespace string
Router router.Router Router router.Router
Client client.Client Client client.Client
Logger logger.Logger Logger logger.Logger
Namespace string
MaxRecvSize int64
} }
// Option func signature // Option func signature

View File

@ -8,9 +8,12 @@ import (
// Options struct // Options struct
type Options struct { type Options struct {
Handler string // Context is for external defined options
Context context.Context
// Handler name
Handler string
// ServicePrefix is the prefix
ServicePrefix string ServicePrefix string
Context context.Context
} }
// Option func // Option func

View File

@ -11,11 +11,16 @@ import (
// Options holds the options for api router // Options holds the options for api router
type Options struct { type Options struct {
Handler string // Register for service lookup
Register register.Register Register register.Register
// Resolver to use
Resolver resolver.Resolver Resolver resolver.Resolver
Logger logger.Logger // Logger micro logger
Context context.Context Logger logger.Logger
// Context is for external options
Context context.Context
// Handler name
Handler string
} }
// Option func signature // Option func signature

View File

@ -53,30 +53,30 @@ type Auth interface {
// Account provided by an auth provider // Account provided by an auth provider
type Account struct { type Account struct {
// ID of the account e.g. email // Metadata any other associated metadata
Metadata metadata.Metadata `json:"metadata"`
// ID of the account e.g. email or uuid
ID string `json:"id"` ID string `json:"id"`
// Type of the account, e.g. service // Type of the account, e.g. service
Type string `json:"type"` Type string `json:"type"`
// Issuer of the account // Issuer of the account
Issuer string `json:"issuer"` Issuer string `json:"issuer"`
// Any other associated metadata
Metadata metadata.Metadata `json:"metadata"`
// Scopes the account has access to
Scopes []string `json:"scopes"`
// Secret for the account, e.g. the password // Secret for the account, e.g. the password
Secret string `json:"secret"` Secret string `json:"secret"`
// Scopes the account has access to
Scopes []string `json:"scopes"`
} }
// Token can be short or long lived // Token can be short or long lived
type Token struct { type Token struct {
// The token to be used for accessing resources
AccessToken string `json:"access_token"`
// RefreshToken to be used to generate a new token
RefreshToken string `json:"refresh_token"`
// Time of token creation // Time of token creation
Created time.Time `json:"created"` Created time.Time `json:"created"`
// Time of token expiry // Time of token expiry
Expiry time.Time `json:"expiry"` Expiry time.Time `json:"expiry"`
// The token to be used for accessing resources
AccessToken string `json:"access_token"`
// RefreshToken to be used to generate a new token
RefreshToken string `json:"refresh_token"`
} }
// Expired returns a boolean indicating if the token needs to be refreshed // Expired returns a boolean indicating if the token needs to be refreshed
@ -106,17 +106,15 @@ const (
// Rule is used to verify access to a resource // Rule is used to verify access to a resource
type Rule struct { type Rule struct {
// ID of the rule, e.g. "public" // Resource that rule belongs to
ID string
// Scope the rule requires, a blank scope indicates open to the public and * indicates the rule
// applies to any valid account
Scope string
// Resource the rule applies to
Resource *Resource Resource *Resource
// Access determines if the rule grants or denies access to the resource // ID of the rule
ID string
// Scope of the rule
Scope string
// Access flag allow/deny
Access Access Access Access
// Priority the rule should take when verifying a request, the higher the value the sooner the // Priority holds the rule priority
// rule will be applied
Priority int32 Priority int32
} }

View File

@ -26,33 +26,34 @@ func NewOptions(opts ...Option) Options {
// Options struct holds auth options // Options struct holds auth options
type Options struct { type Options struct {
Name string // Context holds the external options
// Issuer of the service's account Context context.Context
Issuer string // Meter used for metrics
// ID is the services auth ID Meter meter.Meter
ID string // Logger used for logging
// Secret is used to authenticate the service Logger logger.Logger
Secret string // Tracer used for tracing
Tracer tracer.Tracer
// Store used for stre data
Store store.Store
// Token is the services token used to authenticate itself // Token is the services token used to authenticate itself
Token *Token Token *Token
// PublicKey for decoding JWTs
PublicKey string
// PrivateKey for encoding JWTs
PrivateKey string
// LoginURL is the relative url path where a user can login // LoginURL is the relative url path where a user can login
LoginURL string LoginURL string
// Store to back auth // PrivateKey for encoding JWTs
Store store.Store PrivateKey string
// PublicKey for decoding JWTs
PublicKey string
// Secret is used to authenticate the service
Secret string
// ID is the services auth ID
ID string
// Issuer of the service's account
Issuer string
// Name holds the auth name
Name string
// Addrs sets the addresses of auth // Addrs sets the addresses of auth
Addrs []string Addrs []string
// Logger sets the logger
Logger logger.Logger
// Meter sets tht meter
Meter meter.Meter
// Tracer
Tracer tracer.Tracer
// Context to store other options
Context context.Context
} }
// Option func // Option func
@ -124,18 +125,12 @@ func LoginURL(url string) Option {
// GenerateOptions struct // GenerateOptions struct
type GenerateOptions struct { type GenerateOptions struct {
// Metadata associated with the account
Metadata metadata.Metadata Metadata metadata.Metadata
// Scopes the account has access too
Scopes []string
// Provider of the account, e.g. oauth
Provider string Provider string
// Type of the account, e.g. user Type string
Type string Secret string
// Secret used to authenticate the account Issuer string
Secret string Scopes []string
// Issuer of the account, e.g. micro
Issuer string
} }
// GenerateOption func // GenerateOption func
@ -194,16 +189,11 @@ func NewGenerateOptions(opts ...GenerateOption) GenerateOptions {
// TokenOptions struct // TokenOptions struct
type TokenOptions struct { type TokenOptions struct {
// ID for the account ID string
ID string Secret string
// Secret for the account
Secret string
// RefreshToken is used to refesh a token
RefreshToken string RefreshToken string
// Expiry is the time the token should live for Issuer string
Expiry time.Duration Expiry time.Duration
// Issuer of the account
Issuer string
} }
// TokenOption func // TokenOption func

View File

@ -13,28 +13,27 @@ import (
) )
type memoryBroker struct { type memoryBroker struct {
opts Options opts Options
addr string
sync.RWMutex
connected bool
Subscribers map[string][]*memorySubscriber Subscribers map[string][]*memorySubscriber
addr string
sync.RWMutex
connected bool
} }
type memoryEvent struct { type memoryEvent struct {
opts Options opts Options
topic string
err error err error
message interface{} message interface{}
topic string
} }
type memorySubscriber struct { type memorySubscriber struct {
id string
topic string
exit chan bool
handler Handler
opts SubscribeOptions opts SubscribeOptions
ctx context.Context ctx context.Context
exit chan bool
handler Handler
id string
topic string
} }
func (m *memoryBroker) Options() Options { func (m *memoryBroker) Options() Options {

View File

@ -13,25 +13,26 @@ import (
// Options struct // Options struct
type Options struct { type Options struct {
Name string // Tracer used for tracing
// Addrs useed by broker
Addrs []string
// ErrorHandler executed when errors occur processing messages
ErrorHandler Handler
// Codec used to marshal/unmarshal messages
Codec codec.Codec
// Logger the used logger
Logger logger.Logger
// Meter the used for metrics
Meter meter.Meter
// Tracer used for trace
Tracer tracer.Tracer Tracer tracer.Tracer
// TLSConfig for secure communication // Register can be used for clustering
TLSConfig *tls.Config
// Register used for clustering
Register register.Register Register register.Register
// Context is used for non default options // Codec holds the codec for marshal/unmarshal
Codec codec.Codec
// Logger used for logging
Logger logger.Logger
// Meter used for metrics
Meter meter.Meter
// Context holds external options
Context context.Context Context context.Context
// TLSConfig holds tls.TLSConfig options
TLSConfig *tls.Config
// ErrorHandler used when broker can't unmarshal incoming message
ErrorHandler Handler
// Name holds the broker name
Name string
// Addrs holds the broker address
Addrs []string
} }
// NewOptions create new Options // NewOptions create new Options
@ -59,10 +60,10 @@ func Context(ctx context.Context) Option {
// PublishOptions struct // PublishOptions struct
type PublishOptions struct { type PublishOptions struct {
// BodyOnly says that only body of the message must be published // Context holds external options
BodyOnly bool
// Context for non default options
Context context.Context Context context.Context
// BodyOnly flag says the message contains raw body bytes
BodyOnly bool
} }
// NewPublishOptions creates PublishOptions struct // NewPublishOptions creates PublishOptions struct
@ -80,22 +81,16 @@ func NewPublishOptions(opts ...PublishOption) PublishOptions {
// SubscribeOptions struct // SubscribeOptions struct
type SubscribeOptions struct { type SubscribeOptions struct {
// AutoAck ack messages if handler returns nil err // Context holds external options
AutoAck bool
// ErrorHandler executed when errors occur processing messages
ErrorHandler Handler
// Group for subscriber, Subscribers with the same group name
// will create a shared subscription where each
// receives a subset of messages.
Group string
// BodyOnly says that consumed only body of the message
BodyOnly bool
// Context is used for non default options
Context context.Context Context context.Context
// ErrorHandler used when broker can't unmarshal incoming message
ErrorHandler Handler
// Group holds consumer group
Group string
// AutoAck flag specifies auto ack of incoming message when no error happens
AutoAck bool
// BodyOnly flag specifies that message contains only body bytes without header
BodyOnly bool
} }
// Option func // Option func

View File

@ -21,12 +21,12 @@ type Source struct {
// Package is packaged format for source // Package is packaged format for source
type Package struct { type Package struct {
// Source of the package
Source *Source
// Name of the package // Name of the package
Name string Name string
// Location of the package // Location of the package
Path string Path string
// Type of package e.g tarball, binary, docker // Type of package e.g tarball, binary, docker
Type string Type string
// Source of the package
Source *Source
} }

View File

@ -31,12 +31,12 @@ type noopMessage struct {
} }
type noopRequest struct { type noopRequest struct {
body interface{}
codec codec.Codec
service string service string
method string method string
endpoint string endpoint string
contentType string contentType string
body interface{}
codec codec.Codec
stream bool stream bool
} }

View File

@ -18,35 +18,40 @@ import (
// Options holds client options // Options holds client options
type Options struct { type Options struct {
Name string // CallOptions contains default CallOptions
// Used to select codec
ContentType string
// Proxy address to send requests via
Proxy string
// Plugged interfaces
Broker broker.Broker
Codecs map[string]codec.Codec
Router router.Router
Selector selector.Selector
Transport transport.Transport
Logger logger.Logger
Meter meter.Meter
// Lookup used for looking up routes
Lookup LookupFunc
// Connection Pool
PoolSize int
PoolTTL time.Duration
Tracer tracer.Tracer
// Wrapper that used client
Wrappers []Wrapper
// CallOptions that used by default
CallOptions CallOptions CallOptions CallOptions
// Logger used to log messages
// Context is used for non default options Logger logger.Logger
// Tracer used for tracing
Tracer tracer.Tracer
// Broker used to publish messages
Broker broker.Broker
// Meter used for metrics
Meter meter.Meter
// Router used to get route
Router router.Router
// Selector used to select needed address
Selector selector.Selector
// Transport used for transfer messages
Transport transport.Transport
// Context is used for external options
Context context.Context Context context.Context
// Codecs map
Codecs map[string]codec.Codec
// Lookup func used to get destination addr
Lookup LookupFunc
// Proxy is used for proxy requests
Proxy string
// ContentType is Used to select codec
ContentType string
// Name is the client name
Name string
// Wrappers contains wrappers
Wrappers []Wrapper
// PoolSize connection pool size
PoolSize int
// PoolTTL conection pool ttl
PoolTTL time.Duration
} }
// NewCallOptions creates new call options struct // NewCallOptions creates new call options struct
@ -60,34 +65,34 @@ func NewCallOptions(opts ...CallOption) CallOptions {
// CallOptions holds client call options // CallOptions holds client call options
type CallOptions struct { type CallOptions struct {
// Address of remote hosts // Router used for route
Address []string
// Backoff func
Backoff BackoffFunc
// DialTimeout is the transport Dial Timeout
DialTimeout time.Duration
// Retries is the number of Call attempts
Retries int
// Retry func to be used for retries
Retry RetryFunc
// RequestTimeout specifies request timeout
RequestTimeout time.Duration
// Router to use for this call
Router router.Router Router router.Router
// Selector to use for the call // Selector selects addr
Selector selector.Selector Selector selector.Selector
// SelectOptions to use when selecting a route // Context used for deadline
SelectOptions []selector.SelectOption
// StreamTimeout timeout for the stream
StreamTimeout time.Duration
// AuthToken specifies the auth token as the authorization header
AuthToken bool
// Network to lookup the route within
Network string
// CallWrappers is for low level call func
CallWrappers []CallWrapper
// Context is used for non default options
Context context.Context Context context.Context
// Retry func used for retries
Retry RetryFunc
// Backoff func used for backoff when retry
Backoff BackoffFunc
// Network name
Network string
// CallWrappers call wrappers
CallWrappers []CallWrapper
// SelectOptions selector options
SelectOptions []selector.SelectOption
// Address specifies static addr list
Address []string
// Retries specifies retries num
Retries int
// StreamTimeout stream timeout
StreamTimeout time.Duration
// RequestTimeout request timeout
RequestTimeout time.Duration
// DialTimeout dial timeout
DialTimeout time.Duration
// AuthToken flag
AuthToken bool
} }
// Context pass context to client // Context pass context to client
@ -108,10 +113,10 @@ func NewPublishOptions(opts ...PublishOption) PublishOptions {
// PublishOptions holds publish options // PublishOptions holds publish options
type PublishOptions struct { type PublishOptions struct {
// Exchange is the routing exchange for the message // Context used for external options
Exchange string
// Context holds additional options
Context context.Context Context context.Context
// Exchange topic exchange name
Exchange string
} }
// NewMessageOptions creates message options struct // NewMessageOptions creates message options struct
@ -125,6 +130,7 @@ func NewMessageOptions(opts ...MessageOption) MessageOptions {
// MessageOptions holds client message options // MessageOptions holds client message options
type MessageOptions struct { type MessageOptions struct {
// ContentType specify content-type of message
ContentType string ContentType string
} }
@ -139,12 +145,12 @@ func NewRequestOptions(opts ...RequestOption) RequestOptions {
// RequestOptions holds client request options // RequestOptions holds client request options
type RequestOptions struct { type RequestOptions struct {
// ContentType specify content-type of request // Context used for external options
ContentType string
// Stream says that request is the streaming
Stream bool
// Context can hold other options
Context context.Context Context context.Context
// ContentType specify content-type of message
ContentType string
// Stream flag
Stream bool
} }
// NewOptions creates new options struct // NewOptions creates new options struct

View File

@ -5,13 +5,13 @@ import (
) )
type testRequest struct { type testRequest struct {
service string opts RequestOptions
codec codec.Codec
body interface{}
method string method string
endpoint string endpoint string
contentType string contentType string
codec codec.Codec service string
body interface{}
opts RequestOptions
} }
func (r *testRequest) ContentType() string { func (r *testRequest) ContentType() string {

View File

@ -51,16 +51,14 @@ type Codec interface {
// the communication, likely followed by the body. // the communication, likely followed by the body.
// In the case of an error, body may be nil. // In the case of an error, body may be nil.
type Message struct { type Message struct {
Id string Header metadata.Metadata
Type MessageType
Target string Target string
Method string Method string
Endpoint string Endpoint string
Error string Error string
Id string
// The values read from the socket Body []byte
Header metadata.Metadata Type MessageType
Body []byte
} }
// NewMessage creates new codec message // NewMessage creates new codec message

View File

@ -11,10 +11,14 @@ type Option func(*Options)
// Options contains codec options // Options contains codec options
type Options struct { type Options struct {
// Meter used for metrics
Meter meter.Meter
// Logger used for logging
Logger logger.Logger
// Tracer used for tracing
Tracer tracer.Tracer
// MaxMsgSize specifies max messages size that reads by codec
MaxMsgSize int MaxMsgSize int
Meter meter.Meter
Logger logger.Logger
Tracer tracer.Tracer
} }
// MaxMsgSize sets the max message size // MaxMsgSize sets the max message size

View File

@ -11,26 +11,32 @@ import (
// Options hold the config options // Options hold the config options
type Options struct { type Options struct {
Name string // Struct holds the destination config struct
AllowFail bool
BeforeLoad []func(context.Context, Config) error
AfterLoad []func(context.Context, Config) error
BeforeSave []func(context.Context, Config) error
AfterSave []func(context.Context, Config) error
// Struct that holds config data
Struct interface{} Struct interface{}
// StructTag name
StructTag string
// Logger that will be used
Logger logger.Logger
// Meter that will be used
Meter meter.Meter
// Tracer used for trace
Tracer tracer.Tracer
// Codec that used for load/save // Codec that used for load/save
Codec codec.Codec Codec codec.Codec
// Context for alternative data // Tracer that will be used
Tracer tracer.Tracer
// Meter that will be used
Meter meter.Meter
// Logger that will be used
Logger logger.Logger
// Context used for external options
Context context.Context Context context.Context
// Name of the config
Name string
// StructTag name
StructTag string
// BeforeSave contains slice of funcs that runs before save
BeforeSave []func(context.Context, Config) error
// AfterLoad contains slice of funcs that runs after load
AfterLoad []func(context.Context, Config) error
// BeforeLoad contains slice of funcs that runs before load
BeforeLoad []func(context.Context, Config) error
// AfterSave contains slice of funcs that runs after save
AfterSave []func(context.Context, Config) error
// AllowFail flag to allow fail in config source
AllowFail bool
} }
// Option function signature // Option function signature

View File

@ -37,10 +37,14 @@ var (
// Error type // Error type
type Error struct { type Error struct {
Id string // Id holds error id or service, usually someting like my_service or uuid
Code int32 Id string
// Detail holds some useful details about error
Detail string Detail string
// Status usually holds text of http status
Status string Status string
// Code holds error code
Code int32
} }
// Error satisfies error interface // Error satisfies error interface
@ -49,7 +53,7 @@ func (e *Error) Error() string {
return string(b) return string(b)
} }
// New generates a custom error. // New generates a custom error
func New(id, detail string, code int32) error { func New(id, detail string, code int32) error {
return &Error{ return &Error{
Id: id, Id: id,

View File

@ -21,9 +21,9 @@ func init() {
} }
type defaultLogger struct { type defaultLogger struct {
sync.RWMutex
opts Options opts Options
enc *json.Encoder enc *json.Encoder
sync.RWMutex
} }
// Init(opts...) should only overwrite provided options // Init(opts...) should only overwrite provided options

View File

@ -11,17 +11,18 @@ type Option func(*Options)
// Options holds logger options // Options holds logger options
type Options struct { type Options struct {
Name string // Out holds the output writer
// The logging level the logger should log at. default is `InfoLevel`
Level Level
// fields to always be logged
Fields map[string]interface{}
// It's common to set this to a file, or leave it default which is `os.Stderr`
Out io.Writer Out io.Writer
// Caller skip frame count for file:line info // Context holds exernal options
CallerSkipCount int
// Alternative options
Context context.Context Context context.Context
// Fields holds additional metadata
Fields map[string]interface{}
// Name holds the logger name
Name string
// CallerSkipCount number of frmaes to skip
CallerSkipCount int
// The logging level the logger should log
Level Level
} }
// NewOptions creates new options struct // NewOptions creates new options struct

View File

@ -27,10 +27,10 @@ var (
// Iterator used to iterate over metadata with order // Iterator used to iterate over metadata with order
type Iterator struct { type Iterator struct {
md Metadata
keys []string
cur int cur int
cnt int cnt int
keys []string
md Metadata
} }
// Next advance iterator to next element // Next advance iterator to next element

View File

@ -11,17 +11,26 @@ type Option func(*Options)
// Options for metrics implementations: // Options for metrics implementations:
type Options struct { type Options struct {
Name string // Logger used for logging
Logger logger.Logger
// Context holds external options
Context context.Context
// Name holds the meter name
Name string
// Address holds the address that serves metrics
Address string Address string
Path string // Path holds the path for metrics
Labels Labels Path string
//TimingObjectives map[float64]float64 // MetricPrefix holds the prefix for all metrics
Logger logger.Logger MetricPrefix string
Context context.Context // LabelPrefix holds the prefix for all labels
MetricPrefix string LabelPrefix string
LabelPrefix string // Labels holds the default labels
Labels Labels
// WriteProcessMetrics flag to write process metrics
WriteProcessMetrics bool WriteProcessMetrics bool
WriteFDMetrics bool // WriteFDMetrics flag to write fd metrics
WriteFDMetrics bool
} }
// NewOptions prepares a set of options: // NewOptions prepares a set of options:

View File

@ -73,9 +73,9 @@ func Meter(m meter.Meter) Option {
} }
type wrapper struct { type wrapper struct {
opts Options
callFunc client.CallFunc
client.Client client.Client
callFunc client.CallFunc
opts Options
} }
func NewClientWrapper(opts ...Option) client.Wrapper { func NewClientWrapper(opts ...Option) client.Wrapper {

View File

@ -15,6 +15,18 @@ type Option func(*Options)
// Options configure network // Options configure network
type Options struct { type Options struct {
// Router used for routing
Router router.Router
// Proxy holds the proxy
Proxy proxy.Proxy
// Logger used for logging
Logger logger.Logger
// Meter used for metrics
Meter meter.Meter
// Tracer used for tracing
Tracer tracer.Tracer
// Tunnel used for transfer data
Tunnel tunnel.Tunnel
// Id of the node // Id of the node
Id string Id string
// Name of the network // Name of the network
@ -25,18 +37,6 @@ type Options struct {
Advertise string Advertise string
// Nodes is a list of nodes to connect to // Nodes is a list of nodes to connect to
Nodes []string Nodes []string
// Tunnel is network tunnel
Tunnel tunnel.Tunnel
// Router is network router
Router router.Router
// Proxy is network proxy
Proxy proxy.Proxy
// Logger
Logger logger.Logger
// Meter
Meter meter.Meter
// Tracer
Tracer tracer.Tracer
} }
// Id sets the id of the network node // Id sets the id of the network node

View File

@ -14,19 +14,14 @@ import (
) )
type memorySocket struct { type memorySocket struct {
recv chan *Message
send chan *Message
// sock exit
exit chan bool
// listener exit
lexit chan bool
local string
remote string
// for send/recv transport.Timeout
timeout time.Duration
ctx context.Context ctx context.Context
recv chan *Message
exit chan bool
lexit chan bool
send chan *Message
local string
remote string
timeout time.Duration
sync.RWMutex sync.RWMutex
} }
@ -36,19 +31,19 @@ type memoryClient struct {
} }
type memoryListener struct { type memoryListener struct {
addr string topts Options
ctx context.Context
lopts ListenOptions
exit chan bool exit chan bool
conn chan *memorySocket conn chan *memorySocket
lopts ListenOptions addr string
topts Options
sync.RWMutex sync.RWMutex
ctx context.Context
} }
type memoryTransport struct { type memoryTransport struct {
opts Options opts Options
sync.RWMutex
listeners map[string]*memoryListener listeners map[string]*memoryListener
sync.RWMutex
} }
func (ms *memorySocket) Recv(m *Message) error { func (ms *memorySocket) Recv(m *Message) error {

View File

@ -13,26 +13,24 @@ import (
// Options struct holds the transport options // Options struct holds the transport options
type Options struct { type Options struct {
Name string // Meter used for metrics
// Addrs is the list of intermediary addresses to connect to
Addrs []string
// Codec is the codec interface to use where headers are not supported
// by the transport and the entire payload must be encoded
Codec codec.Codec
// TLSConfig to secure the connection. The assumption is that this
// is mTLS keypair
TLSConfig *tls.Config
// Timeout sets the timeout for Send/Recv
Timeout time.Duration
// Logger sets the logger
Logger logger.Logger
// Meter sets the meter
Meter meter.Meter Meter meter.Meter
// Tracer sets the tracer // Tracer used for tracing
Tracer tracer.Tracer Tracer tracer.Tracer
// Other options for implementations of the interface // Codec used for marshal/unmarshal messages
// can be stored in a context Codec codec.Codec
// Logger used for logging
Logger logger.Logger
// Context holds external options
Context context.Context Context context.Context
// TLSConfig holds tls.TLSConfig options
TLSConfig *tls.Config
// Name holds the transport name
Name string
// Addrs holds the transport addrs
Addrs []string
// Timeout holds the timeout
Timeout time.Duration
} }
// NewOptions returns new options // NewOptions returns new options
@ -53,18 +51,12 @@ func NewOptions(opts ...Option) Options {
// DialOptions struct // DialOptions struct
type DialOptions struct { type DialOptions struct {
// Tells the transport this is a streaming connection with // Context holds the external options
// multiple calls to send/recv and that send may not even be called
Stream bool
// Timeout for dialing
Timeout time.Duration
// TODO: add tls options when dialling
// Currently set in global options
// Other options for implementations of the interface
// can be stored in a context
Context context.Context Context context.Context
// Timeout holds the timeout
Timeout time.Duration
// Stream flag
Stream bool
} }
// NewDialOptions returns new DialOptions // NewDialOptions returns new DialOptions
@ -85,10 +77,10 @@ func NewDialOptions(opts ...DialOption) DialOptions {
type ListenOptions struct { type ListenOptions struct {
// TODO: add tls options when listening // TODO: add tls options when listening
// Currently set in global options // Currently set in global options
// Context holds the external options
// Other options for implementations of the interface
// can be stored in a context
Context context.Context Context context.Context
// TLSConfig holds the *tls.Config options
TLSConfig *tls.Config
} }
// NewListenOptions returns new ListenOptions // NewListenOptions returns new ListenOptions

View File

@ -17,17 +17,16 @@ type tunBroker struct {
} }
type tunSubscriber struct { type tunSubscriber struct {
topic string opts broker.SubscribeOptions
handler broker.Handler
opts broker.SubscribeOptions
closed chan bool
listener tunnel.Listener listener tunnel.Listener
handler broker.Handler
closed chan bool
topic string
} }
type tunEvent struct { type tunEvent struct {
topic string
message *broker.Message message *broker.Message
topic string
} }
// used to access tunnel from options context // used to access tunnel from options context

View File

@ -22,23 +22,24 @@ type Option func(*Options)
// Options provides network configuration options // Options provides network configuration options
type Options struct { type Options struct {
Name string // Logger used for logging
// Id is tunnel id
Id string
// Address is tunnel address
Address string
// Nodes are remote nodes
Nodes []string
// The shared auth token
Token string
// Transport listens to incoming connections
Transport transport.Transport
// Logger
Logger logger.Logger Logger logger.Logger
// Meter // Meter used for metrics
Meter meter.Meter Meter meter.Meter
// Tracer // Tracer used for tracing
Tracer tracer.Tracer Tracer tracer.Tracer
// Transport used for communication
Transport transport.Transport
// Token the shared auth token
Token string
// Name holds the tunnel name
Name string
// Id holds the tunnel id
Id string
// Address holds the tunnel address
Address string
// Nodes holds the tunnel nodes
Nodes []string
} }
// DialOption func // DialOption func
@ -61,9 +62,9 @@ type ListenOption func(*ListenOptions)
// ListenOptions provides listen options // ListenOptions provides listen options
type ListenOptions struct { type ListenOptions struct {
// specify mode of the session // Mode specify mode of the session
Mode Mode Mode Mode
// The read timeout // Timeout the read timeout
Timeout time.Duration Timeout time.Duration
} }

View File

@ -23,33 +23,44 @@ import (
// Options for micro service // Options for micro service
type Options struct { type Options struct {
Name string // Context holds external options or cancel stuff
Version string
Metadata metadata.Metadata
Auths []auth.Auth
Brokers []broker.Broker
Loggers []logger.Logger
Meters []meter.Meter
Configs []config.Config
Clients []client.Client
Servers []server.Server
Stores []store.Store
Registers []register.Register
Tracers []tracer.Tracer
Routers []router.Router
// Runtime runtime.Runtime
// Profile profile.Profile
// Before and After funcs
BeforeStart []func(context.Context) error
BeforeStop []func(context.Context) error
AfterStart []func(context.Context) error
AfterStop []func(context.Context) error
// Other options for implementations of the interface
// can be stored in a context
Context context.Context Context context.Context
// Metadata holds service metadata
Metadata metadata.Metadata
// Version holds service version
Version string
// Name holds service name
Name string
// Brokers holds brokers
Brokers []broker.Broker
// Loggers holds loggers
Loggers []logger.Logger
// Meters holds meter
Meters []meter.Meter
// Configs holds config
Configs []config.Config
// Clients holds clients
Clients []client.Client
// Auths holds auths
Auths []auth.Auth
// Stores holds stores
Stores []store.Store
// Registers holds registers
Registers []register.Register
// Tracers holds tracers
Tracers []tracer.Tracer
// Routers holds routers
Routers []router.Router
// BeforeStart holds funcs that runs before service starts
BeforeStart []func(context.Context) error
// BeforeStop holds funcs that runs before service stops
BeforeStop []func(context.Context) error
// AfterStart holds funcs that runs after service starts
AfterStart []func(context.Context) error
// AfterStop holds funcs that runs after service stops
AfterStop []func(context.Context) error
// Servers holds servers
Servers []server.Server
} }
// NewOptions returns new Options filled with defaults and overrided by provided opts // NewOptions returns new Options filled with defaults and overrided by provided opts

View File

@ -11,9 +11,9 @@ import (
) )
type httpProfile struct { type httpProfile struct {
server *http.Server
sync.Mutex sync.Mutex
running bool running bool
server *http.Server
} }
var ( var (

View File

@ -13,16 +13,12 @@ import (
) )
type profiler struct { type profiler struct {
opts profile.Options exit chan bool
cpuFile *os.File
memFile *os.File
opts profile.Options
sync.Mutex sync.Mutex
running bool running bool
exit chan bool
// where the cpu profile is written
cpuFile *os.File
// where the mem profile is written
memFile *os.File
} }
func (p *profiler) writeHeap(f *os.File) { func (p *profiler) writeHeap(f *os.File) {

View File

@ -11,20 +11,20 @@ import (
// Options for proxy // Options for proxy
type Options struct { type Options struct {
// Specific endpoint to always call // Tracer used for tracing
Endpoint string
// The default client to use
Client client.Client
// The default router to use
Router router.Router
// Extra links for different clients
Links map[string]client.Client
// Logger
Logger logger.Logger
// Meter
Meter meter.Meter
// Tracer
Tracer tracer.Tracer Tracer tracer.Tracer
// Client for communication
Client client.Client
// Router for routing
Router router.Router
// Logger used for logging
Logger logger.Logger
// Meter used for metrics
Meter meter.Meter
// Links holds the communication links
Links map[string]client.Client
// Endpoint holds the destination address
Endpoint string
} }
// Option func signature // Option func signature

View File

@ -16,9 +16,9 @@ var (
) )
type node struct { type node struct {
*Node
TTL time.Duration
LastSeen time.Time LastSeen time.Time
*Node
TTL time.Duration
} }
type record struct { type record struct {
@ -405,10 +405,10 @@ func (m *memory) String() string {
} }
type watcher struct { type watcher struct {
id string
wo WatchOptions
res chan *Result res chan *Result
exit chan bool exit chan bool
wo WatchOptions
id string
} }
func (m *watcher) Next() (*Result, error) { func (m *watcher) Next() (*Result, error) {

View File

@ -12,20 +12,22 @@ import (
// Options holds options for register // Options holds options for register
type Options struct { type Options struct {
Name string // Tracer used for tracing
Addrs []string
Timeout time.Duration
TLSConfig *tls.Config
// Logger that will be used
Logger logger.Logger
// Meter that will be used
Meter meter.Meter
// Tracer
Tracer tracer.Tracer Tracer tracer.Tracer
// Other options for implementations of the interface // Context holds external options
// can be stored in a context
Context context.Context Context context.Context
// Logged used for logging
Logger logger.Logger
// Meter used for metrics
Meter meter.Meter
// TLSConfig holds tls.TLSConfig options
TLSConfig *tls.Config
// Name holds the name of register
Name string
// Addrs specifies register addrs
Addrs []string
// Timeout specifies timeout
Timeout time.Duration
} }
// NewOptions returns options that filled by opts // NewOptions returns options that filled by opts
@ -44,13 +46,9 @@ func NewOptions(opts ...Option) Options {
// RegisterOptions holds options for register method // RegisterOptions holds options for register method
type RegisterOptions struct { type RegisterOptions struct {
TTL time.Duration Context context.Context
// Other options for implementations of the interface Domain string
// can be stored in a context TTL time.Duration
Context context.Context
// Domain to register the service in
Domain string
// Attempts specify attempts for register
Attempts int Attempts int
} }

View File

@ -52,17 +52,17 @@ type Service struct {
// Node holds node register info // Node holds node register info
type Node struct { type Node struct {
Metadata metadata.Metadata `json:"metadata"`
Id string `json:"id"` Id string `json:"id"`
Address string `json:"address"` Address string `json:"address"`
Metadata metadata.Metadata `json:"metadata"`
} }
// Endpoint holds endpoint register info // Endpoint holds endpoint register info
type Endpoint struct { type Endpoint struct {
Name string `json:"name"`
Request *Value `json:"request"` Request *Value `json:"request"`
Response *Value `json:"response"` Response *Value `json:"response"`
Metadata metadata.Metadata `json:"metadata"` Metadata metadata.Metadata `json:"metadata"`
Name string `json:"name"`
} }
// Value holds additional kv stuff // Value holds additional kv stuff

View File

@ -7,14 +7,17 @@ import "time"
type Watcher interface { type Watcher interface {
// Next is a blocking call // Next is a blocking call
Next() (*Result, error) Next() (*Result, error)
// Stop stops the watcher
Stop() Stop()
} }
// Result is returned by a call to Next on // Result is returned by a call to Next on
// the watcher. Actions can be create, update, delete // the watcher. Actions can be create, update, delete
type Result struct { type Result struct {
Action string // Service holds register service
Service *Service Service *Service
// Action holds the action
Action string
} }
// EventType defines register event type // EventType defines register event type
@ -45,12 +48,12 @@ func (t EventType) String() string {
// Event is register event // Event is register event
type Event struct { type Event struct {
// Id is register id
Id string
// Type defines type of event
Type EventType
// Timestamp is event timestamp // Timestamp is event timestamp
Timestamp time.Time Timestamp time.Time
// Service is register service // Service is register service
Service *Service Service *Service
// Id is register id
Id string
// Type defines type of event
Type EventType
} }

View File

@ -12,9 +12,9 @@ import (
// Resolver is a DNS network resolve // Resolver is a DNS network resolve
type Resolver struct { type Resolver struct {
// The resolver address to use
Address string
goresolver *net.Resolver goresolver *net.Resolver
// Address of resolver to use
Address string
sync.RWMutex sync.RWMutex
} }

View File

@ -10,23 +10,15 @@ import (
// Options are router options // Options are router options
type Options struct { type Options struct {
Name string Logger logger.Logger
// Id is router id Context context.Context
Id string
// Address is router address
Address string
// Gateway is network gateway
Gateway string
// Network is network address
Network string
// Register is the local register
Register register.Register Register register.Register
// Precache routes Name string
Gateway string
Network string
Id string
Address string
Precache bool Precache bool
// Logger
Logger logger.Logger
// Context for additional options
Context context.Context
} }
// Id sets Router Id // Id sets Router Id

View File

@ -15,10 +15,10 @@ var (
// Route is network route // Route is network route
type Route struct { type Route struct {
// Metadata for the route
Metadata metadata.Metadata
// Service is destination service name // Service is destination service name
Service string Service string
// Address is service node address
Address string
// Gateway is route gateway // Gateway is route gateway
Gateway string Gateway string
// Network is network address // Network is network address
@ -27,10 +27,10 @@ type Route struct {
Router string Router string
// Link is network link // Link is network link
Link string Link string
// Address is service node address
Address string
// Metric is the route cost metric // Metric is the route cost metric
Metric int64 Metric int64
// Metadata for the route
Metadata metadata.Metadata
} }
// Hash returns route hash sum. // Hash returns route hash sum.

View File

@ -38,14 +38,14 @@ func (t EventType) String() string {
// Event is returned by a call to Next on the watcher. // Event is returned by a call to Next on the watcher.
type Event struct { type Event struct {
// Unique id of the event // Route is table route
Route Route
// Timestamp is event timestamp
Timestamp time.Time
// Id of the event
Id string Id string
// Type defines type of event // Type defines type of event
Type EventType Type EventType
// Timestamp is event timestamp
Timestamp time.Time
// Route is table route
Route Route
} }
// Watcher defines routing table watcher interface // Watcher defines routing table watcher interface

View File

@ -10,18 +10,12 @@ import (
// Options configure runtime // Options configure runtime
type Options struct { type Options struct {
// Scheduler for updates
Scheduler Scheduler Scheduler Scheduler
// Service type to manage Client client.Client
Type string Logger logger.Logger
// Source of the services repository Type string
Source string Source string
// Base image to use Image string
Image string
// Client to use when making requests
Client client.Client
// Logger
Logger logger.Logger
} }
// Option func signature // Option func signature
@ -77,42 +71,26 @@ type ReadOption func(o *ReadOptions)
// CreateOptions configure runtime services // CreateOptions configure runtime services
type CreateOptions struct { type CreateOptions struct {
// Command to execut Context context.Context
Command []string Output io.Writer
// Args to pass into command
Args []string
// Environment to configure
Env []string
// Log output
Output io.Writer
// Type of service to create
Type string
// Retries before failing deploy
Retries int
// Specify the image to use
Image string
// Namespace to create the service in
Namespace string
// Specify the context to use
Context context.Context
// Secrets to use
Secrets map[string]string
// Resources to allocate the service
Resources *Resources Resources *Resources
Secrets map[string]string
Image string
Namespace string
Type string
Command []string
Args []string
Env []string
Retries int
} }
// ReadOptions queries runtime services // ReadOptions queries runtime services
type ReadOptions struct { type ReadOptions struct {
// Service name Context context.Context
Service string Service string
// Version queries services with given version Version string
Version string Type string
// Type of service
Type string
// Namespace the service is running in
Namespace string Namespace string
// Specify the context to use
Context context.Context
} }
// CreateType sets the type of service to create // CreateType sets the type of service to create
@ -238,12 +216,9 @@ type UpdateOption func(o *UpdateOptions)
// UpdateOptions struct // UpdateOptions struct
type UpdateOptions struct { type UpdateOptions struct {
// Namespace the service is running in Context context.Context
Secrets map[string]string
Namespace string Namespace string
// Specify the context to use
Context context.Context
// Secrets to use
Secrets map[string]string
} }
// UpdateSecret sets a secret to provide the service with // UpdateSecret sets a secret to provide the service with
@ -276,10 +251,8 @@ type DeleteOption func(o *DeleteOptions)
// DeleteOptions struct // DeleteOptions struct
type DeleteOptions struct { type DeleteOptions struct {
// Namespace the service is running in Context context.Context
Namespace string Namespace string
// Specify the context to use
Context context.Context
} }
// DeleteNamespace sets the namespace // DeleteNamespace sets the namespace
@ -301,14 +274,10 @@ type LogsOption func(o *LogsOptions)
// LogsOptions configure runtime logging // LogsOptions configure runtime logging
type LogsOptions struct { type LogsOptions struct {
// How many existing lines to show Context context.Context
Count int64
// Stream new lines?
Stream bool
// Namespace the service is running in
Namespace string Namespace string
// Specify the context to use Count int64
Context context.Context Stream bool
} }
// LogsCount confiures how many existing lines to show // LogsCount confiures how many existing lines to show

View File

@ -37,15 +37,20 @@ type Runtime interface {
// Logs returns a log stream // Logs returns a log stream
type Logs interface { type Logs interface {
// Error retuns error
Error() error Error() error
// Chan return chan log
Chan() chan Log Chan() chan Log
// Stop stops the log stream
Stop() error Stop() error
} }
// Log is a log message // Log is a log message
type Log struct { type Log struct {
Message string // Metadata holds metadata
Metadata metadata.Metadata Metadata metadata.Metadata
// Message holds the message
Message string
} }
// Scheduler is a runtime service scheduler // Scheduler is a runtime service scheduler
@ -84,28 +89,28 @@ func (t EventType) String() string {
// Event is notification event // Event is notification event
type Event struct { type Event struct {
// ID of the event // Timestamp of event
ID string
// Type is event type
Type EventType
// Timestamp is event timestamp
Timestamp time.Time Timestamp time.Time
// Service the event relates to // Service the event relates to
Service *Service Service *Service
// Options to use when processing the event // Options to use when processing the event
Options *CreateOptions Options *CreateOptions
// ID of the event
ID string
// Type is event type
Type EventType
} }
// Service is runtime service // Service is runtime service
type Service struct { type Service struct {
// Metadata stores metadata
Metadata metadata.Metadata
// Name of the service // Name of the service
Name string Name string
// Version of the service // Version of the service
Version string Version string
// url location of source // Name of the service
Source string Source string
// Metadata stores metadata
Metadata metadata.Metadata
} }
// Resources which are allocated to a serivce // Resources which are allocated to a serivce

View File

@ -7,10 +7,10 @@ import (
) )
type rpcHandler struct { type rpcHandler struct {
name string
handler interface{}
endpoints []*register.Endpoint
opts HandlerOptions opts HandlerOptions
handler interface{}
name string
endpoints []*register.Endpoint
} }
func newRpcHandler(handler interface{}, opts ...HandlerOption) Handler { func newRpcHandler(handler interface{}, opts ...HandlerOption) Handler {

View File

@ -32,16 +32,16 @@ const (
) )
type noopServer struct { type noopServer struct {
h Handler
opts Options opts Options
h Handler
rsvc *register.Service rsvc *register.Service
handlers map[string]Handler handlers map[string]Handler
subscribers map[*subscriber][]broker.Subscriber subscribers map[*subscriber][]broker.Subscriber
registered bool
started bool
exit chan chan error exit chan chan error
wg *sync.WaitGroup wg *sync.WaitGroup
sync.RWMutex sync.RWMutex
registered bool
started bool
} }
// NewServer returns new noop server // NewServer returns new noop server

View File

@ -23,50 +23,62 @@ type Option func(*Options)
// Options server struct // Options server struct
type Options struct { type Options struct {
Codecs map[string]codec.Codec // Context holds the external options and can be used for server shutdown
Broker broker.Broker Context context.Context
Register register.Register // Broker holds the server broker
Tracer tracer.Tracer Broker broker.Broker
Auth auth.Auth // Register holds the register
Logger logger.Logger Register register.Register
Meter meter.Meter // Tracer holds the tracer
Transport transport.Transport Tracer tracer.Tracer
Metadata metadata.Metadata // Auth holds the auth
Name string Auth auth.Auth
Address string // Logger holds the logger
Advertise string Logger logger.Logger
Id string // Meter holds the meter
Namespace string Meter meter.Meter
Version string // Transport holds the transport
HdlrWrappers []HandlerWrapper Transport transport.Transport
SubWrappers []SubscriberWrapper // Router for requests
// RegisterCheck runs a check function before registering the service
RegisterCheck func(context.Context) error
// The register expiry time
RegisterTTL time.Duration
// The interval on which to register
RegisterInterval time.Duration
// RegisterAttempts specify how many times try to register
RegisterAttempts int
// DeegisterAttempts specify how many times try to deregister
DeregisterAttempts int
// The router for requests
Router Router Router Router
// TLSConfig specifies tls.Config for secure serving
TLSConfig *tls.Config
Wait *sync.WaitGroup
// Listener may be passed if already created // Listener may be passed if already created
Listener net.Listener Listener net.Listener
// MaxConn limit connections to server // Wait group
Wait *sync.WaitGroup
// TLSConfig specifies tls.Config for secure serving
TLSConfig *tls.Config
// Metadata holds the server metadata
Metadata metadata.Metadata
// RegisterCheck run before register server
RegisterCheck func(context.Context) error
// Codecs map to handle content-type
Codecs map[string]codec.Codec
// Id holds the id of the server
Id string
// Namespace for te server
Namespace string
// Name holds the server name
Name string
// Address holds the server address
Address string
// Advertise holds the advertie addres
Advertise string
// Version holds the server version
Version string
// SubWrappers holds the server subscribe wrappers
SubWrappers []SubscriberWrapper
// HdlrWrappers holds the handler wrappers
HdlrWrappers []HandlerWrapper
// RegisterAttempts holds the number of register attempts before error
RegisterAttempts int
// RegisterInterval holds he interval for re-register
RegisterInterval time.Duration
// RegisterTTL specifies TTL for register record
RegisterTTL time.Duration
// MaxConn limits number of connections
MaxConn int MaxConn int
// Other options for implementations of the interface // DeregisterAttempts holds the number of deregister attempts before error
// can be stored in a context DeregisterAttempts int
Context context.Context
} }
// NewOptions returns new options struct with default or passed values // NewOptions returns new options struct with default or passed values
@ -303,9 +315,12 @@ type HandlerOption func(*HandlerOptions)
// HandlerOptions struct // HandlerOptions struct
type HandlerOptions struct { type HandlerOptions struct {
Internal bool // Context holds external options
Context context.Context
// Metadata for hondler
Metadata map[string]metadata.Metadata Metadata map[string]metadata.Metadata
Context context.Context // Internal flag limits exporting to other nodes via register
Internal bool
} }
// NewHandlerOptions creates new HandlerOptions // NewHandlerOptions creates new HandlerOptions
@ -327,13 +342,16 @@ type SubscriberOption func(*SubscriberOptions)
// SubscriberOptions struct // SubscriberOptions struct
type SubscriberOptions struct { type SubscriberOptions struct {
// AutoAck defaults to true. When a handler returns // Context holds the external options
// with a nil error the message is acked. Context context.Context
AutoAck bool // Queue holds the subscribtion queue
Queue string Queue string
// AutoAck flag for auto ack messages after processing
AutoAck bool
// Internal flag limit exporting info via register
Internal bool Internal bool
// BodyOnly flag specifies that message without headers
BodyOnly bool BodyOnly bool
Context context.Context
} }
// NewSubscriberOptions create new SubscriberOptions // NewSubscriberOptions create new SubscriberOptions

View File

@ -6,12 +6,12 @@ import (
) )
type rpcMessage struct { type rpcMessage struct {
payload interface{}
codec codec.Codec
header metadata.Metadata
topic string topic string
contentType string contentType string
payload interface{}
header metadata.Metadata
body []byte body []byte
codec codec.Codec
} }
func (r *rpcMessage) ContentType() string { func (r *rpcMessage) ContentType() string {

View File

@ -28,19 +28,19 @@ var (
) )
type handler struct { type handler struct {
method reflect.Value
reqType reflect.Type reqType reflect.Type
ctxType reflect.Type ctxType reflect.Type
method reflect.Value
} }
type subscriber struct { type subscriber struct {
topic string opts SubscriberOptions
rcvr reflect.Value
typ reflect.Type typ reflect.Type
subscriber interface{} subscriber interface{}
rcvr reflect.Value
topic string
handlers []*handler handlers []*handler
endpoints []*register.Endpoint endpoints []*register.Endpoint
opts SubscriberOptions
} }
// Is this an exported - upper case - name? // Is this an exported - upper case - name?

View File

@ -14,28 +14,27 @@ import (
// Options contains configuration for the Store // Options contains configuration for the Store
type Options struct { type Options struct {
// Meter used for metrics
Meter meter.Meter
// Tracer used for tracing
Tracer tracer.Tracer
// Context holds external options
Context context.Context
// Codec used to marshal/unmarshal
Codec codec.Codec
// Logger used for logging
Logger logger.Logger
// TLSConfig holds tls.TLSConfig options
TLSConfig *tls.Config
// Name specifies store name // Name specifies store name
Name string Name string
// Nodes contains the addresses or other connection information of the backing storage. // Database specifies store database
// For example, an etcd implementation would contain the nodes of the cluster.
// A SQL implementation could contain one or more connection strings.
Nodes []string
// Database allows multiple isolated stores to be kept in one backend, if supported.
Database string Database string
// Table is analag for a table in database backends or a key prefix in KV backends // Table specifies store table
Table string Table string
// Codec that used for marshal/unmarshal value // Nodes contains store address
Codec codec.Codec // TODO: replace with Addrs
// Logger the logger Nodes []string
Logger logger.Logger
// Meter the meter
Meter meter.Meter
// Tracer the tacer
Tracer tracer.Tracer
// TLSConfig specifies tls.Config for secure
TLSConfig *tls.Config
// Context should contain all implementation specific options
Context context.Context
} }
// NewOptions creates options struct // NewOptions creates options struct
@ -139,10 +138,14 @@ func NewReadOptions(opts ...ReadOption) ReadOptions {
// ReadOptions configures an individual Read operation // ReadOptions configures an individual Read operation
type ReadOptions struct { type ReadOptions struct {
Database string // Context holds external options
Table string Context context.Context
// Database holds the database name
Database string
// Table holds table name
Table string
// Namespace holds namespace
Namespace string Namespace string
Context context.Context
} }
// ReadOption sets values in ReadOptions // ReadOption sets values in ReadOptions
@ -167,12 +170,18 @@ func NewWriteOptions(opts ...WriteOption) WriteOptions {
// WriteOptions configures an individual Write operation // WriteOptions configures an individual Write operation
type WriteOptions struct { type WriteOptions struct {
Database string // Context holds external options
Table string Context context.Context
TTL time.Duration // Metadata contains additional metadata
Metadata metadata.Metadata Metadata metadata.Metadata
// Database holds database name
Database string
// Table holds table name
Table string
// Namespace holds namespace
Namespace string Namespace string
Context context.Context // TTL specifies key TTL
TTL time.Duration
} }
// WriteOption sets values in WriteOptions // WriteOption sets values in WriteOptions
@ -211,10 +220,14 @@ func NewDeleteOptions(opts ...DeleteOption) DeleteOptions {
// DeleteOptions configures an individual Delete operation // DeleteOptions configures an individual Delete operation
type DeleteOptions struct { type DeleteOptions struct {
Database string // Context holds external options
Table string Context context.Context
// Database holds database name
Database string
// Table holds table name
Table string
// Namespace holds namespace
Namespace string Namespace string
Context context.Context
} }
// DeleteOption sets values in DeleteOptions // DeleteOption sets values in DeleteOptions
@ -239,18 +252,14 @@ func NewListOptions(opts ...ListOption) ListOptions {
// ListOptions configures an individual List operation // ListOptions configures an individual List operation
type ListOptions struct { type ListOptions struct {
// List from the following
Database, Table string
// Prefix returns all keys that are prefixed with key
Prefix string
// Suffix returns all keys that end with key
Suffix string
// Limit limits the number of returned keys
Limit uint
// Offset when combined with Limit supports pagination
Offset uint
Namespace string
Context context.Context Context context.Context
Database string
Prefix string
Suffix string
Namespace string
Table string
Limit uint
Offset uint
} }
// ListOption sets values in ListOptions // ListOption sets values in ListOptions
@ -297,8 +306,10 @@ type ExistsOption func(*ExistsOptions)
// ExistsOptions holds options for Exists method // ExistsOptions holds options for Exists method
type ExistsOptions struct { type ExistsOptions struct {
// Context holds external options
Context context.Context
// Namespace contains namespace
Namespace string Namespace string
Context context.Context
} }
// NewExistsOptions helper for Exists method // NewExistsOptions helper for Exists method

View File

@ -7,23 +7,22 @@ import (
type memorySync struct { type memorySync struct {
options Options options Options
locks map[string]*memoryLock
mtx gosync.RWMutex mtx gosync.RWMutex
locks map[string]*memoryLock
} }
type memoryLock struct { type memoryLock struct {
id string
time time.Time time time.Time
ttl time.Duration
release chan bool release chan bool
id string
ttl time.Duration
} }
type memoryLeader struct { type memoryLeader struct {
opts LeaderOptions opts LeaderOptions
id string
resign func(id string) error resign func(id string) error
status chan bool status chan bool
id string
} }
func (m *memoryLeader) Resign() error { func (m *memoryLeader) Resign() error {

View File

@ -10,11 +10,17 @@ import (
// Options holds the sync options // Options holds the sync options
type Options struct { type Options struct {
Nodes []string // Logger used for logging
Prefix string
Logger logger.Logger Logger logger.Logger
// Tracer used for tracing
Tracer tracer.Tracer Tracer tracer.Tracer
Meter meter.Meter // Meter used for merics
Meter meter.Meter
// Prefix holds prefix?
Prefix string
// Nodes holds the nodes
// TODO: change to Addrs ?
Nodes []string
} }
// Option func signature // Option func signature

View File

@ -32,9 +32,9 @@ func (t *noopTracer) Name() string {
} }
type noopSpan struct { type noopSpan struct {
name string
ctx context.Context ctx context.Context
tracer Tracer tracer Tracer
name string
} }
func (s *noopSpan) Finish(opts ...SpanOption) { func (s *noopSpan) Finish(opts ...SpanOption) {

View File

@ -14,10 +14,10 @@ type EventOption func(o *EventOptions)
// Options struct // Options struct
type Options struct { type Options struct {
// Logger used for logging
Logger logger.Logger
// Name of the tracer // Name of the tracer
Name string Name string
// Logger is the logger for messages
Logger logger.Logger
} }
// Option func // Option func

View File

@ -36,30 +36,30 @@ type Span interface {
} }
type Label struct { type Label struct {
key string
val interface{} val interface{}
key string
} }
func Any(k string, v interface{}) Label { func Any(k string, v interface{}) Label {
return Label{k, v} return Label{key: k, val: v}
} }
func String(k string, v string) Label { func String(k string, v string) Label {
return Label{k, v} return Label{key: k, val: v}
} }
func Int(k string, v int) Label { func Int(k string, v int) Label {
return Label{k, v} return Label{key: k, val: v}
} }
func Int64(k string, v int64) Label { func Int64(k string, v int64) Label {
return Label{k, v} return Label{key: k, val: v}
} }
func Float64(k string, v float64) Label { func Float64(k string, v float64) Label {
return Label{k, v} return Label{key: k, val: v}
} }
func Bool(k string, v bool) Label { func Bool(k string, v bool) Label {
return Label{k, v} return Label{key: k, val: v}
} }

View File

@ -12,11 +12,11 @@ import (
) )
type tWrapper struct { type tWrapper struct {
opts Options client.Client
serverHandler server.HandlerFunc serverHandler server.HandlerFunc
serverSubscriber server.SubscriberFunc serverSubscriber server.SubscriberFunc
clientCallFunc client.CallFunc clientCallFunc client.CallFunc
client.Client opts Options
} }
type ClientCallObserver func(context.Context, client.Request, interface{}, []client.CallOption, tracer.Span, error) type ClientCallObserver func(context.Context, client.Request, interface{}, []client.CallOption, tracer.Span, error)

View File

@ -11,17 +11,16 @@ import (
// CertOptions are passed to cert options // CertOptions are passed to cert options
type CertOptions struct { type CertOptions struct {
IsCA bool NotAfter time.Time
NotBefore time.Time
Parent *x509.Certificate
SerialNumber *big.Int
Subject pkix.Name Subject pkix.Name
DNSNames []string DNSNames []string
IPAddresses []net.IP IPAddresses []net.IP
SerialNumber *big.Int Pub ed25519.PublicKey
NotBefore time.Time Priv ed25519.PrivateKey
NotAfter time.Time IsCA bool
Parent *x509.Certificate
Pub ed25519.PublicKey
Priv ed25519.PrivateKey
} }
// CertOption sets CertOptions // CertOption sets CertOptions

View File

@ -10,18 +10,17 @@ import (
) )
type pool struct { type pool struct {
size int tr transport.Transport
ttl time.Duration
tr transport.Transport
sync.Mutex
conns map[string][]*poolConn conns map[string][]*poolConn
size int
ttl time.Duration
sync.Mutex
} }
type poolConn struct { type poolConn struct {
transport.Client
id string
created time.Time created time.Time
transport.Client
id string
} }
func newPool(options Options) *pool { func newPool(options Options) *pool {

View File

@ -10,11 +10,10 @@ import (
// Buffer is ring buffer // Buffer is ring buffer
type Buffer struct { type Buffer struct {
size int
sync.RWMutex
vals []*Entry
streams map[string]*Stream streams map[string]*Stream
vals []*Entry
size int
sync.RWMutex
} }
// Entry is ring buffer data entry // Entry is ring buffer data entry
@ -25,12 +24,12 @@ type Entry struct {
// Stream is used to stream the buffer // Stream is used to stream the buffer
type Stream struct { type Stream struct {
// Id of the stream
Id string
// Buffered entries // Buffered entries
Entries chan *Entry Entries chan *Entry
// Stop channel // Stop channel
Stop chan bool Stop chan bool
// Id of the stream
Id string
} }
// Put adds a new value to ring buffer // Put adds a new value to ring buffer

View File

@ -8,18 +8,18 @@ const (
// Template is a compiled representation of path templates. // Template is a compiled representation of path templates.
type Template struct { type Template struct {
// Version is the version number of the format. // Verb is a VERB part in the template
Version int Verb string
// OpCodes is a sequence of operations. // Original template (example: /v1/a_bit_of_everything)
Template string
// OpCodes is a sequence of operations
OpCodes []int OpCodes []int
// Pool is a constant pool // Pool is a constant pool
Pool []string Pool []string
// Verb is a VERB part in the template. // Fields is a list of field paths bound in this template
Verb string
// Fields is a list of field paths bound in this template.
Fields []string Fields []string
// Original template (example: /v1/a_bit_of_everything) // Version is the version number of the format
Template string Version int
} }
// Compiler compiles utilities representation of path templates into marshallable operations. // Compiler compiles utilities representation of path templates into marshallable operations.
@ -29,14 +29,8 @@ type Compiler interface {
} }
type op struct { type op struct {
// code is the opcode of the operation str string
code OpCode code OpCode
// str is a string operand of the code.
// operand is ignored if str is not empty.
str string
// operand is a numeric operand of the code.
operand int operand int
} }

View File

@ -6,8 +6,8 @@ import (
) )
type apiRouter struct { type apiRouter struct {
routes []router.Route
router.Router router.Router
routes []router.Route
} }
func (r *apiRouter) Lookup(...router.QueryOption) ([]router.Route, error) { func (r *apiRouter) Lookup(...router.QueryOption) ([]router.Route, error) {

View File

@ -25,9 +25,10 @@ type rop struct {
// Pattern is a template pattern of http request paths defined in github.com/googleapis/googleapis/google/api/http.proto. // Pattern is a template pattern of http request paths defined in github.com/googleapis/googleapis/google/api/http.proto.
type Pattern struct { type Pattern struct {
verb string
// ops is a list of operations // ops is a list of operations
ops []rop ops []rop
// pool is a constant pool indexed by the operands or vars. // pool is a constant pool indexed by the operands or vars
pool []string pool []string
// vars is a list of variables names to be bound by this pattern // vars is a list of variables names to be bound by this pattern
vars []string vars []string
@ -35,8 +36,6 @@ type Pattern struct {
stacksize int stacksize int
// tailLen is the length of the fixed-size segments after a deep wildcard // tailLen is the length of the fixed-size segments after a deep wildcard
tailLen int tailLen int
// verb is the VERB part of the path pattern. It is empty if the pattern does not have VERB part.
verb string
// assumeColonVerb indicates whether a path suffix after a final // assumeColonVerb indicates whether a path suffix after a final
// colon may only be interpreted as a verb. // colon may only be interpreted as a verb.
assumeColonVerb bool assumeColonVerb bool

View File

@ -8,9 +8,9 @@ import (
) )
type template struct { type template struct {
segments []segment
verb string verb string
template string template string
segments []segment
} }
type segment interface { type segment interface {

View File

@ -6,8 +6,8 @@ import (
// Pool holds the socket pool // Pool holds the socket pool
type Pool struct { type Pool struct {
sync.RWMutex
pool map[string]*Socket pool map[string]*Socket
sync.RWMutex
} }
// Get socket from pool // Get socket from pool

View File

@ -9,17 +9,12 @@ import (
// Socket is our pseudo socket for transport.Socket // Socket is our pseudo socket for transport.Socket
type Socket struct { type Socket struct {
id string
// closed
closed chan bool closed chan bool
// remote addr send chan *transport.Message
recv chan *transport.Message
id string
remote string remote string
// local addr local string
local string
// send chan
send chan *transport.Message
// recv chan
recv chan *transport.Message
} }
// SetLocal sets the local addr // SetLocal sets the local addr

View File

@ -21,10 +21,9 @@ type Stream interface {
type stream struct { type stream struct {
Stream Stream
sync.RWMutex
err error err error
request *request request *request
sync.RWMutex
} }
type request struct { type request struct {

View File

@ -21,9 +21,9 @@ type Sync interface {
type syncStore struct { type syncStore struct {
storeOpts store.Options storeOpts store.Options
syncOpts Options
pendingWrites []*deque.Deque pendingWrites []*deque.Deque
pendingWriteTickers []*time.Ticker pendingWriteTickers []*time.Ticker
syncOpts Options
sync.RWMutex sync.RWMutex
} }
@ -123,7 +123,7 @@ func (c *syncStore) Sync() error {
} }
type internalRecord struct { type internalRecord struct {
expiresAt time.Time
key string key string
value []byte value []byte
expiresAt time.Time
} }

View File

@ -12,11 +12,10 @@ import (
// authClaims to be encoded in the JWT // authClaims to be encoded in the JWT
type authClaims struct { type authClaims struct {
Type string `json:"type"`
Scopes []string `json:"scopes"`
Metadata metadata.Metadata `json:"metadata"` Metadata metadata.Metadata `json:"metadata"`
jwt.StandardClaims jwt.StandardClaims
Type string `json:"type"`
Scopes []string `json:"scopes"`
} }
// JWT implementation of token provider // JWT implementation of token provider
@ -51,7 +50,7 @@ func (j *JWT) Generate(acc *auth.Account, opts ...token.GenerateOption) (*token.
// generate the JWT // generate the JWT
expiry := time.Now().Add(options.Expiry) expiry := time.Now().Add(options.Expiry)
t := jwt.NewWithClaims(jwt.SigningMethodRS256, authClaims{ t := jwt.NewWithClaims(jwt.SigningMethodRS256, authClaims{
acc.Type, acc.Scopes, acc.Metadata, jwt.StandardClaims{ Type: acc.Type, Scopes: acc.Scopes, Metadata: acc.Metadata, StandardClaims: jwt.StandardClaims{
Subject: acc.ID, Subject: acc.ID,
Issuer: acc.Issuer, Issuer: acc.Issuer,
ExpiresAt: expiry.Unix(), ExpiresAt: expiry.Unix(),

View File

@ -25,10 +25,10 @@ type Provider interface {
// Token holds the auth token // Token holds the auth token
type Token struct { type Token struct {
// The actual token // Created time of token created
Token string `json:"token"`
// Time of token creation
Created time.Time `json:"created"` Created time.Time `json:"created"`
// Time of token expiry // Expiry ime of the token
Expiry time.Time `json:"expiry"` Expiry time.Time `json:"expiry"`
// Token holds the actual token
Token string `json:"token"`
} }