1
0
mirror of https://github.com/go-micro/go-micro.git synced 2024-12-30 10:10:44 +02:00

fix: struct field alignment (#2632)

This commit is contained in:
Lukasz Raczylo 2023-04-26 00:16:34 +00:00 committed by GitHub
parent 0f9b2f00c9
commit a7522e7d6c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
113 changed files with 694 additions and 637 deletions

View File

@ -32,12 +32,12 @@ type Api interface {
// Options are API options. // Options are API options.
type Options struct { type Options struct {
// Address of the server
Address string
// Router for resolving routes // Router for resolving routes
Router router.Router Router router.Router
// Client to use for RPC // Client to use for RPC
Client client.Client Client client.Client
// Address of the server
Address string
} }
// Option type are API option args. // Option type are API option args.

View File

@ -47,13 +47,13 @@ type Request struct {
// Response is the response of the generic `api-client` call. // Response is the response of the generic `api-client` call.
type Response struct { type Response struct {
// json and base64 encoded response body // json and base64 encoded response body
Body string `json:"body"` Body string `json:"body"`
// error fields. Error json example
// {"id":"go.micro.client","code":500,"detail":"malformed method name: \"\"","status":"Internal Server Error"}
Code int `json:"code"`
ID string `json:"id"` ID string `json:"id"`
Detail string `json:"detail"` Detail string `json:"detail"`
Status string `json:"status"` Status string `json:"status"`
// error fields. Error json example
// {"id":"go.micro.client","code":500,"detail":"malformed method name: \"\"","status":"Internal Server Error"}
Code int `json:"code"`
} }
// Client enables generic calls to micro. // Client enables generic calls to micro.

View File

@ -13,11 +13,11 @@ var (
// Options is the list of api Options. // Options is the list of api 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 is a api Option. // Option is a api Option.

View File

@ -31,8 +31,8 @@ type Endpoint struct {
// Options is a struct of available options. // Options is a struct of available options.
type Options struct { type Options struct {
Handler string
Namespace func(*http.Request) string Namespace func(*http.Request) string
Handler string
} }
// Option is a helper for a single option. // Option is a helper for a single option.

View File

@ -9,10 +9,10 @@ import (
// Options is a struct of options available. // Options is a struct of options available.
type Options struct { type Options struct {
Handler string
Registry registry.Registry Registry registry.Registry
Resolver resolver.Resolver Resolver resolver.Resolver
Logger logger.Logger Logger logger.Logger
Handler string
} }
// Option is a helper for a single options. // Option is a helper for a single options.

View File

@ -27,16 +27,17 @@ type endpoint struct {
// router is the default router. // router is the default router.
type registryRouter struct { type registryRouter struct {
exit chan bool
opts router.Options opts router.Options
// registry cache // registry cache
rc cache.Cache rc cache.Cache
sync.RWMutex exit chan bool
eps map[string]*router.Route eps map[string]*router.Route
// compiled regexp for host and path // compiled regexp for host and path
ceps map[string]*endpoint ceps map[string]*endpoint
sync.RWMutex
} }
func (r *registryRouter) isStopped() bool { func (r *registryRouter) isStopped() bool {

View File

@ -25,10 +25,10 @@ type endpoint struct {
// Router is the default router. // Router is the default router.
type Router struct { type Router struct {
exit chan bool
opts router.Options opts router.Options
exit chan bool
eps map[string]*endpoint
sync.RWMutex sync.RWMutex
eps map[string]*endpoint
} }
func (r *Router) isStopd() bool { func (r *Router) isStopd() bool {

View File

@ -9,18 +9,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
// Original template (example: /v1/a_bit_of_everything)
Template string
// OpCodes is a sequence of operations. // 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.
Verb string
// Fields is a list of field paths bound in this template. // 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.
@ -30,13 +30,14 @@ type Compiler interface {
} }
type op struct { type op struct {
// code is the opcode of the operation
code OpCode
// str is a string operand of the code. // str is a string operand of the code.
// operand is ignored if str is not empty. // operand is ignored if str is not empty.
str string str string
// code is the opcode of the operation
code OpCode
// operand is a numeric operand of the code. // operand is a numeric operand of the code.
operand int operand int
} }

View File

@ -107,9 +107,9 @@ func tokenize(path string) (tokens []string, verb string) {
// parser is a parser of the template syntax defined in github.com/googleapis/googleapis/google/api/http.proto. // parser is a parser of the template syntax defined in github.com/googleapis/googleapis/google/api/http.proto.
type parser struct { type parser struct {
logger log.Logger
tokens []string tokens []string
accepted []string accepted []string
logger log.Logger
} }
// topLevelSegments is the target of this parser. // topLevelSegments is the target of this parser.

View File

@ -24,6 +24,8 @@ 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 is the VERB part of the path pattern. It is empty if the pattern does not have VERB part.
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.
@ -34,16 +36,14 @@ 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
} }
type patternOptions struct { type patternOptions struct {
assumeColonVerb bool
logger log.Logger logger log.Logger
assumeColonVerb bool
} }
// PatternOpt is an option for creating Patterns. // PatternOpt is an option for creating Patterns.

View File

@ -9,9 +9,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

@ -10,17 +10,9 @@ type Option func(o *Options)
// Options represents various options you can present to ACME providers. // Options represents various options you can present to ACME providers.
type Options struct { type Options struct {
// AcceptTLS must be set to true to indicate that you have read your
// provider's terms of service.
AcceptToS bool
// CA is the CA to use
CA string
// ChallengeProvider is a go-acme/lego challenge provider. Set this if you // ChallengeProvider is a go-acme/lego challenge provider. Set this if you
// want to use DNS Challenges. Otherwise, tls-alpn-01 will be used // want to use DNS Challenges. Otherwise, tls-alpn-01 will be used
ChallengeProvider challenge.Provider ChallengeProvider challenge.Provider
// Issue certificates for domains on demand. Otherwise, certs will be
// retrieved / issued on start-up.
OnDemand bool
// Cache is a storage interface. Most ACME libraries have an cache, but // Cache is a storage interface. Most ACME libraries have an cache, but
// there's no defined interface, so if you consume this option // there's no defined interface, so if you consume this option
// sanity check it before using. // sanity check it before using.
@ -28,6 +20,14 @@ type Options struct {
// Logger is the underling logging framework // Logger is the underling logging framework
Logger logger.Logger Logger logger.Logger
// CA is the CA to use
CA string
// AcceptTLS must be set to true to indicate that you have read your
// provider's terms of service.
AcceptToS bool
// Issue certificates for domains on demand. Otherwise, certs will be
// retrieved / issued on start-up.
OnDemand bool
} }
// AcceptToS indicates whether you accept your CA's terms of service. // AcceptToS indicates whether you accept your CA's terms of service.

View File

@ -6,9 +6,9 @@ import (
type Config struct { type Config struct {
AllowOrigin string AllowOrigin string
AllowCredentials bool
AllowMethods string AllowMethods string
AllowHeaders string AllowHeaders string
AllowCredentials bool
} }
// CombinedCORSHandler wraps a server and provides CORS headers. // CombinedCORSHandler wraps a server and provides CORS headers.

View File

@ -15,12 +15,13 @@ import (
) )
type httpServer struct { type httpServer struct {
mux *http.ServeMux
opts server.Options opts server.Options
mtx sync.RWMutex mux *http.ServeMux
address string
exit chan chan error exit chan chan error
address string
mtx sync.RWMutex
} }
func NewServer(address string, opts ...server.Option) server.Server { func NewServer(address string, opts ...server.Option) server.Server {

View File

@ -13,16 +13,16 @@ import (
type Option func(o *Options) type Option func(o *Options)
type Options struct { type Options struct {
ACMEProvider acme.Provider
Resolver resolver.Resolver
Logger logger.Logger
CORSConfig *cors.Config
TLSConfig *tls.Config
ACMEHosts []string
Wrappers []Wrapper
EnableACME bool EnableACME bool
EnableCORS bool EnableCORS bool
CORSConfig *cors.Config
ACMEProvider acme.Provider
EnableTLS bool EnableTLS bool
ACMEHosts []string
TLSConfig *tls.Config
Resolver resolver.Resolver
Wrappers []Wrapper
Logger logger.Logger
} }
type Wrapper func(h http.Handler) http.Handler type Wrapper func(h http.Handler) http.Handler

View File

@ -53,30 +53,30 @@ type Rules interface {
// Account provided by an auth provider. // Account provided by an auth provider.
type Account struct { type Account struct {
// Any other associated metadata
Metadata map[string]string `json:"metadata"`
// ID of the account e.g. email // ID of the account e.g. email
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 map[string]string `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,13 +106,13 @@ 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 {
// Resource the rule applies to
Resource *Resource
// ID of the rule, e.g. "public" // ID of the rule, e.g. "public"
ID string ID string
// Scope the rule requires, a blank scope indicates open to the public and * indicates the rule // Scope the rule requires, a blank scope indicates open to the public and * indicates the rule
// applies to any valid account // applies to any valid account
Scope string Scope string
// Resource the rule applies to
Resource *Resource
// Access determines if the rule grants or denies access to the resource // Access determines if the rule grants or denies access to the resource
Access Access Access Access
// Priority the rule should take when verifying a request, the higher the value the sooner the // Priority the rule should take when verifying a request, the higher the value the sooner the

View File

@ -20,22 +20,22 @@ func NewOptions(opts ...Option) Options {
} }
type Options struct { type Options struct {
// Logger is the underline logger
Logger logger.Logger
// Token is the services token used to authenticate itself
Token *Token
// Namespace the service belongs to // Namespace the service belongs to
Namespace string Namespace string
// ID is the services auth ID // ID is the services auth ID
ID string ID string
// Secret is used to authenticate the service // Secret is used to authenticate the service
Secret string Secret string
// Token is the services token used to authenticate itself
Token *Token
// PublicKey for decoding JWTs // PublicKey for decoding JWTs
PublicKey string PublicKey string
// PrivateKey for encoding JWTs // PrivateKey for encoding JWTs
PrivateKey string PrivateKey string
// Addrs sets the addresses of auth // Addrs sets the addresses of auth
Addrs []string Addrs []string
// Logger is the underline logger
Logger logger.Logger
} }
type Option func(o *Options) type Option func(o *Options)
@ -93,14 +93,14 @@ func ClientToken(token *Token) Option {
type GenerateOptions struct { type GenerateOptions struct {
// Metadata associated with the account // Metadata associated with the account
Metadata map[string]string Metadata map[string]string
// Scopes the account has access too
Scopes []string
// Provider of the account, e.g. oauth // Provider of the account, e.g. oauth
Provider string Provider string
// Type of the account, e.g. user // Type of the account, e.g. user
Type string Type string
// Secret used to authenticate the account // Secret used to authenticate the account
Secret string Secret string
// Scopes the account has access too
Scopes []string
} }
type GenerateOption func(o *GenerateOptions) type GenerateOption func(o *GenerateOptions)

View File

@ -29,38 +29,40 @@ import (
// HTTP Broker is a point to point async broker. // HTTP Broker is a point to point async broker.
type httpBroker struct { type httpBroker struct {
id string opts Options
address string
opts Options r registry.Registry
mux *http.ServeMux mux *http.ServeMux
c *http.Client c *http.Client
r registry.Registry
sync.RWMutex
subscribers map[string][]*httpSubscriber subscribers map[string][]*httpSubscriber
running bool
exit chan chan error exit chan chan error
inbox map[string][][]byte
id string
address string
sync.RWMutex
// offline message inbox // offline message inbox
mtx sync.RWMutex mtx sync.RWMutex
inbox map[string][][]byte running bool
} }
type httpSubscriber struct { type httpSubscriber struct {
opts SubscribeOptions opts SubscribeOptions
id string
topic string
fn Handler fn Handler
svc *registry.Service svc *registry.Service
hb *httpBroker hb *httpBroker
id string
topic string
} }
type httpEvent struct { type httpEvent struct {
err error
m *Message m *Message
t string t string
err error
} }
var ( var (

View File

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

View File

@ -10,23 +10,24 @@ import (
) )
type Options struct { type Options struct {
Addrs []string Codec codec.Marshaler
Secure bool
Codec codec.Marshaler
// Logger is the underlying logger // Logger is the underlying logger
Logger logger.Logger Logger logger.Logger
// Registry used for clustering
Registry registry.Registry
// Other options for implementations of the interface
// can be stored in a context
Context context.Context
// Handler executed when error happens in broker mesage // Handler executed when error happens in broker mesage
// processing // processing
ErrorHandler Handler ErrorHandler Handler
TLSConfig *tls.Config TLSConfig *tls.Config
// Registry used for clustering Addrs []string
Registry registry.Registry Secure bool
// Other options for implementations of the interface
// can be stored in a context
Context context.Context
} }
type PublishOptions struct { type PublishOptions struct {
@ -36,17 +37,18 @@ type PublishOptions struct {
} }
type SubscribeOptions struct { type SubscribeOptions struct {
// AutoAck defaults to true. When a handler returns
// with a nil error the message is acked. // Other options for implementations of the interface
AutoAck bool // can be stored in a context
Context context.Context
// Subscribers with the same queue name // Subscribers with the same queue name
// will create a shared subscription where each // will create a shared subscription where each
// receives a subset of messages. // receives a subset of messages.
Queue string Queue string
// Other options for implementations of the interface // AutoAck defaults to true. When a handler returns
// can be stored in a context // with a nil error the message is acked.
Context context.Context AutoAck bool
} }
type Option func(*Options) type Option func(*Options)

2
cache/memory.go vendored
View File

@ -8,9 +8,9 @@ import (
type memCache struct { type memCache struct {
opts Options opts Options
sync.RWMutex
items map[string]Item items map[string]Item
sync.RWMutex
} }
func (c *memCache) Get(ctx context.Context, key string) (interface{}, time.Time, error) { func (c *memCache) Get(ctx context.Context, key string) (interface{}, time.Time, error) {

8
cache/options.go vendored
View File

@ -9,14 +9,14 @@ import (
// Options represents the options for the cache. // Options represents the options for the cache.
type Options struct { type Options struct {
Expiration time.Duration
Items map[string]Item
// Address represents the address or other connection information of the cache service.
Address string
// Context should contain all implementation specific options, using context.WithValue. // Context should contain all implementation specific options, using context.WithValue.
Context context.Context Context context.Context
// Logger is the be used logger // Logger is the be used logger
Logger logger.Logger Logger logger.Logger
Items map[string]Item
// Address represents the address or other connection information of the cache service.
Address string
Expiration time.Duration
} }
// Option manipulates the Options passed. // Option manipulates the Options passed.

View File

@ -31,31 +31,19 @@ var (
// Options are the Client options. // Options are the Client options.
type Options struct { type Options struct {
// Used to select codec
ContentType string
// Plugged interfaces // Default Call Options
Broker broker.Broker CallOptions CallOptions
Codecs map[string]codec.NewCodec
Registry registry.Registry
Selector selector.Selector
Transport transport.Transport
// Router sets the router // Router sets the router
Router Router Router Router
// Connection Pool Registry registry.Registry
PoolSize int Selector selector.Selector
PoolTTL time.Duration Transport transport.Transport
// Response cache // Plugged interfaces
Cache *Cache Broker broker.Broker
// Middleware for client
Wrappers []Wrapper
// Default Call Options
CallOptions CallOptions
// Logger is the underline logger // Logger is the underline logger
Logger logger.Logger Logger logger.Logger
@ -63,22 +51,40 @@ type Options struct {
// Other options for implementations of the interface // Other options for implementations of the interface
// can be stored in a context // can be stored in a context
Context context.Context Context context.Context
Codecs map[string]codec.NewCodec
// Response cache
Cache *Cache
// Used to select codec
ContentType string
// Middleware for client
Wrappers []Wrapper
// Connection Pool
PoolSize int
PoolTTL time.Duration
} }
// CallOptions are options used to make calls to a server. // CallOptions are options used to make calls to a server.
type CallOptions struct { type CallOptions struct {
// Other options for implementations of the interface
// can be stored in a context
Context context.Context
// Backoff func
Backoff BackoffFunc
// Check if retriable func
Retry RetryFunc
SelectOptions []selector.SelectOption SelectOptions []selector.SelectOption
// Address of remote hosts // Address of remote hosts
Address []string Address []string
// Backoff func
Backoff BackoffFunc // Middleware for low level call func
// Check if retriable func CallWrappers []CallWrapper
Retry RetryFunc
// Number of Call attempts
Retries int
// Transport Dial Timeout. Used for initial dial to establish a connection.
DialTimeout time.Duration
// ConnectionTimeout of one request to the server. // ConnectionTimeout of one request to the server.
// Set this lower than the RequestTimeout to enbale retries on connection timeout. // Set this lower than the RequestTimeout to enbale retries on connection timeout.
ConnectionTimeout time.Duration ConnectionTimeout time.Duration
@ -86,27 +92,24 @@ type CallOptions struct {
RequestTimeout time.Duration RequestTimeout time.Duration
// Stream timeout for the stream // Stream timeout for the stream
StreamTimeout time.Duration StreamTimeout time.Duration
// Use the services own auth token
ServiceToken bool
// Duration to cache the response for // Duration to cache the response for
CacheExpiry time.Duration CacheExpiry time.Duration
// Transport Dial Timeout. Used for initial dial to establish a connection.
DialTimeout time.Duration
// Number of Call attempts
Retries int
// Use the services own auth token
ServiceToken bool
// ConnClose sets the Connection: close header. // ConnClose sets the Connection: close header.
ConnClose bool ConnClose bool
// Middleware for low level call func
CallWrappers []CallWrapper
// Other options for implementations of the interface
// can be stored in a context
Context context.Context
} }
type PublishOptions struct { type PublishOptions struct {
// Exchange is the routing exchange for the message
Exchange string
// Other options for implementations of the interface // Other options for implementations of the interface
// can be stored in a context // can be stored in a context
Context context.Context Context context.Context
// Exchange is the routing exchange for the message
Exchange string
} }
type MessageOptions struct { type MessageOptions struct {
@ -114,12 +117,12 @@ type MessageOptions struct {
} }
type RequestOptions struct { type RequestOptions struct {
ContentType string
Stream bool
// Other options for implementations of the interface // Other options for implementations of the interface
// can be stored in a context // can be stored in a context
Context context.Context Context context.Context
ContentType string
Stream bool
} }
// NewOptions creates new Client options. // NewOptions creates new Client options.

View File

@ -30,11 +30,12 @@ const (
) )
type rpcClient struct { type rpcClient struct {
seq uint64
once atomic.Value
opts Options opts Options
once atomic.Value
pool pool.Pool pool pool.Pool
seq uint64
mu sync.RWMutex mu sync.RWMutex
} }

View File

@ -1,9 +1,9 @@
package client package client
type message struct { type message struct {
payload interface{}
topic string topic string
contentType string contentType string
payload interface{}
} }
func newMessage(topic string, payload interface{}, contentType string, opts ...MessageOption) Message { func newMessage(topic string, payload interface{}, contentType string, opts ...MessageOption) Message {

View File

@ -5,13 +5,13 @@ import (
) )
type rpcRequest struct { type rpcRequest struct {
opts RequestOptions
codec codec.Codec
body interface{}
service string service string
method string method string
endpoint string endpoint string
contentType string contentType string
codec codec.Codec
body interface{}
opts RequestOptions
} }
func newRequest(service, endpoint string, request interface{}, contentType string, reqOpts ...RequestOption) Request { func newRequest(service, endpoint string, request interface{}, contentType string, reqOpts ...RequestOption) Request {

View File

@ -6,10 +6,10 @@ import (
) )
type rpcResponse struct { type rpcResponse struct {
header map[string]string
body []byte
socket transport.Socket socket transport.Socket
codec codec.Codec codec codec.Codec
header map[string]string
body []byte
} }
func (r *rpcResponse) Codec() codec.Reader { func (r *rpcResponse) Codec() codec.Reader {

View File

@ -11,22 +11,23 @@ import (
// Implements the streamer interface. // Implements the streamer interface.
type rpcStream struct { type rpcStream struct {
sync.RWMutex
id string
closed chan bool
// Indicates whether connection should be closed directly.
close bool
err error err error
request Request request Request
response Response response Response
codec codec.Codec codec codec.Codec
context context.Context context context.Context
// signal whether we should send EOS closed chan bool
sendEOS bool
// release releases the connection back to the pool // release releases the connection back to the pool
release func(err error) release func(err error)
id string
sync.RWMutex
// Indicates whether connection should be closed directly.
close bool
// signal whether we should send EOS
sendEOS bool
} }
func (r *rpcStream) isClosed() bool { func (r *rpcStream) isClosed() bool {

View File

@ -55,14 +55,15 @@ type Marshaler 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 {
// The values read from the socket
Header map[string]string
Id string Id string
Type MessageType
Target string Target string
Method string Method string
Endpoint string Endpoint string
Error string Error string
// The values read from the socket Body []byte
Header map[string]string Type MessageType
Body []byte
} }

View File

@ -10,22 +10,24 @@ import (
) )
type clientCodec struct { type clientCodec struct {
dec *json.Decoder // for reading JSON values
enc *json.Encoder // for writing JSON values
c io.Closer
// temporary work space // temporary work space
req clientRequest req clientRequest
resp clientResponse resp clientResponse
sync.Mutex c io.Closer
dec *json.Decoder // for reading JSON values
enc *json.Encoder // for writing JSON values
pending map[interface{}]string pending map[interface{}]string
sync.Mutex
} }
type clientRequest struct { type clientRequest struct {
Method string `json:"method"`
Params [1]interface{} `json:"params"` Params [1]interface{} `json:"params"`
ID interface{} `json:"id"` ID interface{} `json:"id"`
Method string `json:"method"`
} }
type clientResponse struct { type clientResponse struct {

View File

@ -11,11 +11,11 @@ import (
) )
type jsonCodec struct { type jsonCodec struct {
buf *bytes.Buffer
mt codec.MessageType
rwc io.ReadWriteCloser rwc io.ReadWriteCloser
buf *bytes.Buffer
c *clientCodec c *clientCodec
s *serverCodec s *serverCodec
mt codec.MessageType
} }
func (j *jsonCodec) Close() error { func (j *jsonCodec) Close() error {

View File

@ -19,9 +19,9 @@ type serverCodec struct {
} }
type serverRequest struct { type serverRequest struct {
Method string `json:"method"`
Params *json.RawMessage `json:"params"`
ID interface{} `json:"id"` ID interface{} `json:"id"`
Params *json.RawMessage `json:"params"`
Method string `json:"method"`
} }
type serverResponse struct { type serverResponse struct {

View File

@ -17,10 +17,10 @@ type flusher interface {
} }
type protoCodec struct { type protoCodec struct {
sync.Mutex
rwc io.ReadWriteCloser rwc io.ReadWriteCloser
mt codec.MessageType
buf *bytes.Buffer buf *bytes.Buffer
mt codec.MessageType
sync.Mutex
} }
func (c *protoCodec) Close() error { func (c *protoCodec) Close() error {

View File

@ -37,11 +37,12 @@ type Watcher interface {
type Options struct { type Options struct {
Loader loader.Loader Loader loader.Loader
Reader reader.Reader Reader reader.Reader
Source []source.Source
// for alternative data // for alternative data
Context context.Context Context context.Context
Source []source.Source
WithWatcherDisabled bool WithWatcherDisabled bool
} }

View File

@ -13,21 +13,21 @@ import (
) )
type config struct { type config struct {
// the current values
vals reader.Values
exit chan bool exit chan bool
// the current snapshot
snap *loader.Snapshot
opts Options opts Options
sync.RWMutex sync.RWMutex
// the current snapshot
snap *loader.Snapshot
// the current values
vals reader.Values
} }
type watcher struct { type watcher struct {
lw loader.Watcher lw loader.Watcher
rd reader.Reader rd reader.Reader
path []string
value reader.Value value reader.Value
path []string
} }
func newConfig(opts ...Option) (Config, error) { func newConfig(opts ...Option) (Config, error) {

View File

@ -45,11 +45,12 @@ type Snapshot struct {
// Options contains all options for a config loader. // Options contains all options for a config loader.
type Options struct { type Options struct {
Reader reader.Reader Reader reader.Reader
Source []source.Source
// for alternative data // for alternative data
Context context.Context Context context.Context
Source []source.Source
WithWatcherDisabled bool WithWatcherDisabled bool
} }

View File

@ -17,34 +17,35 @@ import (
) )
type memory struct { type memory struct {
exit chan bool
opts loader.Options
sync.RWMutex
// the current snapshot
snap *loader.Snapshot
// the current values // the current values
vals reader.Values vals reader.Values
exit chan bool
// the current snapshot
snap *loader.Snapshot
watchers *list.List
opts loader.Options
// all the sets // all the sets
sets []*source.ChangeSet sets []*source.ChangeSet
// all the sources // all the sources
sources []source.Source sources []source.Source
watchers *list.List sync.RWMutex
} }
type updateValue struct { type updateValue struct {
version string
value reader.Value value reader.Value
version string
} }
type watcher struct { type watcher struct {
exit chan bool
path []string
value reader.Value value reader.Value
reader reader.Reader reader reader.Reader
version atomic.Value version atomic.Value
exit chan bool
updates chan updateValue updates chan updateValue
path []string
} }
func (w *watcher) getVersion() string { func (w *watcher) getVersion() string {

View File

@ -18,14 +18,14 @@ type Secrets interface {
} }
type Options struct { type Options struct {
// Context for other opts
Context context.Context
// Key is a symmetric key for encoding // Key is a symmetric key for encoding
Key []byte Key []byte
// Private key for decoding // Private key for decoding
PrivateKey []byte PrivateKey []byte
// Public key for encoding // Public key for encoding
PublicKey []byte PublicKey []byte
// Context for other opts
Context context.Context
} }
// Option sets options. // Option sets options.

View File

@ -15,9 +15,9 @@ var (
) )
type env struct { type env struct {
opts source.Options
prefixes []string prefixes []string
strippedPrefixes []string strippedPrefixes []string
opts source.Options
} }
func (e *env) Read() (*source.ChangeSet, error) { func (e *env) Read() (*source.ChangeSet, error) {

View File

@ -10,9 +10,9 @@ import (
) )
type file struct { type file struct {
opts source.Options
fs fs.FS fs fs.FS
path string path string
opts source.Options
} }
var ( var (

View File

@ -10,9 +10,9 @@ import (
) )
type memory struct { type memory struct {
sync.RWMutex
ChangeSet *source.ChangeSet ChangeSet *source.ChangeSet
Watchers map[string]*watcher Watchers map[string]*watcher
sync.RWMutex
} }
func (s *memory) Read() (*source.ChangeSet, error) { func (s *memory) Read() (*source.ChangeSet, error) {

View File

@ -5,9 +5,9 @@ import (
) )
type watcher struct { type watcher struct {
Id string
Updates chan *source.ChangeSet Updates chan *source.ChangeSet
Source *memory Source *memory
Id string
} }
func (w *watcher) Next() (*source.ChangeSet, error) { func (w *watcher) Next() (*source.ChangeSet, error) {

View File

@ -21,11 +21,11 @@ type Source interface {
// ChangeSet represents a set of changes from a source. // ChangeSet represents a set of changes from a source.
type ChangeSet struct { type ChangeSet struct {
Data []byte Timestamp time.Time
Checksum string Checksum string
Format string Format string
Source string Source string
Timestamp time.Time Data []byte
} }
// Watcher watches a source for changes. // Watcher watches a source for changes.

View File

@ -7,12 +7,12 @@ type Option func(*Options)
// Options are logger options. // Options are logger options.
type Options struct { type Options struct {
// Format specifies the output format
Format FormatFunc
// Name of the log // Name of the log
Name string Name string
// Size is the size of ring buffer // Size is the size of ring buffer
Size int Size int
// Format specifies the output format
Format FormatFunc
} }
// Name of the log. // Name of the log.

View File

@ -10,11 +10,11 @@ import (
// Should stream from OS. // Should stream from OS.
type osLog struct { type osLog struct {
format FormatFunc format FormatFunc
once sync.Once
sync.RWMutex
buffer *ring.Buffer buffer *ring.Buffer
subs map[string]*osStream subs map[string]*osStream
sync.RWMutex
once sync.Once
} }
type osStream struct { type osStream struct {

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

@ -12,15 +12,15 @@ import (
) )
type profiler struct { type profiler struct {
opts profile.Options
sync.Mutex
running bool
// where the cpu profile is written // where the cpu profile is written
cpuFile *os.File cpuFile *os.File
// where the mem profile is written // where the mem profile is written
memFile *os.File memFile *os.File
opts profile.Options
sync.Mutex
running bool
} }
func (p *profiler) Start() error { func (p *profiler) Start() error {

View File

@ -9,10 +9,10 @@ import (
) )
type memTracer struct { type memTracer struct {
opts Options
// ring buffer of traces // ring buffer of traces
buffer *ring.Buffer buffer *ring.Buffer
opts Options
} }
func (t *memTracer) Read(opts ...ReadOption) ([]*Span, error) { func (t *memTracer) Read(opts ...ReadOption) ([]*Span, error) {

View File

@ -36,6 +36,10 @@ const (
// Span is used to record an entry. // Span is used to record an entry.
type Span struct { type Span struct {
// Start time
Started time.Time
// associated data
Metadata map[string]string
// Id of the trace // Id of the trace
Trace string Trace string
// name of the span // name of the span
@ -44,12 +48,8 @@ type Span struct {
Id string Id string
// parent span id // parent span id
Parent string Parent string
// Start time
Started time.Time
// Duration in nano seconds // Duration in nano seconds
Duration time.Duration Duration time.Duration
// associated data
Metadata map[string]string
// Type // Type
Type SpanType Type SpanType
} }

View File

@ -38,19 +38,19 @@ type NackFunc func() error
// Event is the object returned by the broker when you subscribe to a topic. // Event is the object returned by the broker when you subscribe to a topic.
type Event struct { type Event struct {
// ID to uniquely identify the event
ID string
// Topic of event, e.g. "registry.service.created"
Topic string
// Timestamp of the event // Timestamp of the event
Timestamp time.Time Timestamp time.Time
// Metadata contains the values the event was indexed by // Metadata contains the values the event was indexed by
Metadata map[string]string Metadata map[string]string
// Payload contains the encoded message
Payload []byte
ackFunc AckFunc ackFunc AckFunc
nackFunc NackFunc nackFunc NackFunc
// ID to uniquely identify the event
ID string
// Topic of event, e.g. "registry.service.created"
Topic string
// Payload contains the encoded message
Payload []byte
} }
// Unmarshal the events message into an object. // Unmarshal the events message into an object.

View File

@ -21,15 +21,16 @@ func NewStream(opts ...Option) (Stream, error) {
} }
type subscriber struct { type subscriber struct {
Group string
Topic string
Channel chan Event Channel chan Event
sync.RWMutex
retryMap map[string]int retryMap map[string]int
Group string
Topic string
retryLimit int retryLimit int
autoAck bool
ackWait time.Duration ackWait time.Duration
sync.RWMutex
autoAck bool
} }
type mem struct { type mem struct {

View File

@ -25,9 +25,9 @@ func NewOptions(opts ...Option) *Options {
} }
type StoreOptions struct { type StoreOptions struct {
TTL time.Duration
Backup Backup Backup Backup
Logger logger.Logger Logger logger.Logger
TTL time.Duration
} }
type StoreOption func(o *StoreOptions) type StoreOption func(o *StoreOptions)
@ -66,21 +66,21 @@ func WithTimestamp(t time.Time) PublishOption {
// ConsumeOptions contains all the options which can be provided when subscribing to a topic. // ConsumeOptions contains all the options which can be provided when subscribing to a topic.
type ConsumeOptions struct { type ConsumeOptions struct {
// Group is the name of the consumer group, if two consumers have the same group the events
// are distributed between them
Group string
// Offset is the time from which the messages should be consumed from. If not provided then // Offset is the time from which the messages should be consumed from. If not provided then
// the messages will be consumed starting from the moment the Subscription starts. // the messages will be consumed starting from the moment the Subscription starts.
Offset time.Time Offset time.Time
// Group is the name of the consumer group, if two consumers have the same group the events
// are distributed between them
Group string
AckWait time.Duration
// RetryLimit indicates number of times a message is retried
RetryLimit int
// AutoAck if true (default true), automatically acknowledges every message so it will not be redelivered. // AutoAck if true (default true), automatically acknowledges every message so it will not be redelivered.
// If false specifies that each message need ts to be manually acknowledged by the subscriber. // If false specifies that each message need ts to be manually acknowledged by the subscriber.
// If processing is successful the message should be ack'ed to remove the message from the stream. // If processing is successful the message should be ack'ed to remove the message from the stream.
// If processing is unsuccessful the message should be nack'ed (negative acknowledgement) which will mean it will // If processing is unsuccessful the message should be nack'ed (negative acknowledgement) which will mean it will
// remain on the stream to be processed again. // remain on the stream to be processed again.
AutoAck bool AutoAck bool
AckWait time.Duration
// RetryLimit indicates number of times a message is retried
RetryLimit int
// CustomRetries indicates whether to use RetryLimit // CustomRetries indicates whether to use RetryLimit
CustomRetries bool CustomRetries bool
} }

View File

@ -23,8 +23,8 @@ func init() {
} }
type defaultLogger struct { type defaultLogger struct {
sync.RWMutex
opts Options opts Options
sync.RWMutex
} }
// Init (opts...) should only overwrite provided options. // Init (opts...) should only overwrite provided options.

View File

@ -8,16 +8,16 @@ import (
type Option func(*Options) type Option func(*Options)
type Options struct { type Options struct {
// 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` // 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
CallerSkipCount int
// Alternative options // Alternative options
Context context.Context Context context.Context
// fields to always be logged
Fields map[string]interface{}
// Caller skip frame count for file:line info
CallerSkipCount int
// The logging level the logger should log at. default is `InfoLevel`
Level Level
} }
// WithFields set default fields for the logger. // WithFields set default fields for the logger.

View File

@ -24,29 +24,31 @@ import (
// Options for micro service. // Options for micro service.
type Options struct { type Options struct {
Auth auth.Auth Registry registry.Registry
Broker broker.Broker Store store.Store
Cache cache.Cache Auth auth.Auth
Cmd cmd.Cmd Cmd cmd.Cmd
Config config.Config Config config.Config
Client client.Client Client client.Client
Server server.Server Server server.Server
Store store.Store
Registry registry.Registry
Runtime runtime.Runtime
Transport transport.Transport
Profile profile.Profile
Logger logger.Logger
// Before and After funcs
BeforeStart []func() error
BeforeStop []func() error
AfterStart []func() error
AfterStop []func() error
// Other options for implementations of the interface // Other options for implementations of the interface
// can be stored in a context // can be stored in a context
Context context.Context Context context.Context
Cache cache.Cache
Runtime runtime.Runtime
Profile profile.Profile
Transport transport.Transport
Logger logger.Logger
Broker broker.Broker
// Before and After funcs
BeforeStart []func() error
AfterStart []func() error
AfterStop []func() error
BeforeStop []func() error
Signal bool Signal bool
} }

View File

@ -23,20 +23,23 @@ type Cache interface {
} }
type Options struct { type Options struct {
Logger log.Logger
// TTL is the cache TTL // TTL is the cache TTL
TTL time.Duration TTL time.Duration
Logger log.Logger
} }
type Option func(o *Options) type Option func(o *Options)
type cache struct { type cache struct {
registry.Registry
opts Options opts Options
// registry cache registry.Registry
sync.RWMutex // status of the registry
// used to hold onto the cache
// in failure state
status error
// used to prevent cache breakdwon
sg singleflight.Group
cache map[string][]*registry.Service cache map[string][]*registry.Service
ttls map[string]time.Time ttls map[string]time.Time
watched map[string]bool watched map[string]bool
@ -46,12 +49,9 @@ type cache struct {
// indicate whether its running // indicate whether its running
watchedRunning map[string]bool watchedRunning map[string]bool
// status of the registry
// used to hold onto the cache // registry cache
// in failure state sync.RWMutex
status error
// used to prevent cache breakdwon
sg singleflight.Group
} }
var ( var (

View File

@ -26,43 +26,43 @@ var (
) )
type mdnsTxt struct { type mdnsTxt struct {
Metadata map[string]string
Service string Service string
Version string Version string
Endpoints []*Endpoint Endpoints []*Endpoint
Metadata map[string]string
} }
type mdnsEntry struct { type mdnsEntry struct {
id string
node *mdns.Server node *mdns.Server
id string
} }
type mdnsRegistry struct { type mdnsRegistry struct {
opts *Options opts *Options
// the mdns domain
domain string
sync.Mutex
services map[string][]*mdnsEntry services map[string][]*mdnsEntry
mtx sync.RWMutex
// watchers // watchers
watchers map[string]*mdnsWatcher watchers map[string]*mdnsWatcher
// listener // listener
listener chan *mdns.ServiceEntry listener chan *mdns.ServiceEntry
// the mdns domain
domain string
mtx sync.RWMutex
sync.Mutex
} }
type mdnsWatcher struct { type mdnsWatcher struct {
id string
wo WatchOptions wo WatchOptions
ch chan *mdns.ServiceEntry ch chan *mdns.ServiceEntry
exit chan struct{} exit chan struct{}
// the mdns domain
domain string
// the registry // the registry
registry *mdnsRegistry registry *mdnsRegistry
id string
// the mdns domain
domain string
} }
func encode(txt *mdnsTxt) ([]string, error) { func encode(txt *mdnsTxt) ([]string, error) {

View File

@ -14,9 +14,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 {
@ -30,9 +30,10 @@ type record struct {
type memRegistry struct { type memRegistry struct {
options *Options options *Options
sync.RWMutex
records map[string]map[string]*record records map[string]map[string]*record
watchers map[string]*memWatcher watchers map[string]*memWatcher
sync.RWMutex
} }
func NewMemoryRegistry(opts ...Option) Registry { func NewMemoryRegistry(opts ...Option) Registry {

View File

@ -5,10 +5,10 @@ import (
) )
type memWatcher struct { type memWatcher struct {
id string
wo WatchOptions wo WatchOptions
res chan *Result res chan *Result
exit chan bool exit chan bool
id string
} }
func (m *memWatcher) Next() (*Result, error) { func (m *memWatcher) Next() (*Result, error) {

View File

@ -9,30 +9,30 @@ import (
) )
type Options struct { type Options struct {
Logger logger.Logger
// Other options for implementations of the interface
// can be stored in a context
Context context.Context
TLSConfig *tls.Config
Addrs []string Addrs []string
Timeout time.Duration Timeout time.Duration
Secure bool Secure bool
TLSConfig *tls.Config
Logger logger.Logger
// Other options for implementations of the interface
// can be stored in a context
Context context.Context
} }
type RegisterOptions struct { type RegisterOptions struct {
TTL time.Duration
// Other options for implementations of the interface // Other options for implementations of the interface
// can be stored in a context // can be stored in a context
Context context.Context Context context.Context
TTL time.Duration
} }
type WatchOptions struct { type WatchOptions struct {
// Specify a service to watch
// If blank, the watch is for all services
Service string
// Other options for implementations of the interface // Other options for implementations of the interface
// can be stored in a context // can be stored in a context
Context context.Context Context context.Context
// Specify a service to watch
// If blank, the watch is for all services
Service string
} }
type DeregisterOptions struct { type DeregisterOptions struct {

View File

@ -37,16 +37,16 @@ type Service struct {
} }
type Node struct { type Node struct {
Metadata map[string]string `json:"metadata"`
Id string `json:"id"` Id string `json:"id"`
Address string `json:"address"` Address string `json:"address"`
Metadata map[string]string `json:"metadata"`
} }
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 map[string]string `json:"metadata"` Metadata map[string]string `json:"metadata"`
Name string `json:"name"`
} }
type Value struct { type Value struct {

View File

@ -13,8 +13,8 @@ type Watcher interface {
// 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 *Service Service *Service
Action string
} }
// EventType defines registry event type. // EventType defines registry event type.
@ -45,12 +45,12 @@ func (t EventType) String() string {
// Event is registry event. // Event is registry event.
type Event struct { type Event struct {
// Id is registry 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 registry service // Service is registry service
Service *Service Service *Service
// Id is registry id
Id string
// Type defines type of event
Type EventType
} }

View File

@ -21,18 +21,18 @@ import (
const defaultNamespace = "default" const defaultNamespace = "default"
type runtime struct { type runtime struct {
sync.RWMutex
// options configure runtime // options configure runtime
options *Options options *Options
// used to stop the runtime // used to stop the runtime
closed chan bool closed chan bool
// used to start new services // used to start new services
start chan *service start chan *service
// indicates if we're running
running bool
// namespaces stores services grouped by namespace, e.g. namespaces["foo"]["go.micro.auth:latest"] // namespaces stores services grouped by namespace, e.g. namespaces["foo"]["go.micro.auth:latest"]
// would return the latest version of go.micro.auth from the foo namespace // would return the latest version of go.micro.auth from the foo namespace
namespaces map[string]map[string]*service namespaces map[string]map[string]*service
sync.RWMutex
// indicates if we're running
running bool
} }
// NewRuntime creates new local runtime and returns it. // NewRuntime creates new local runtime and returns it.
@ -434,13 +434,13 @@ func (r *runtime) Logs(s *Service, options ...LogsOption) (LogStream, error) {
} }
type logStream struct { type logStream struct {
err error
logger log.Logger
tail *tail.Tail tail *tail.Tail
service string
stream chan LogRecord stream chan LogRecord
stop chan bool
service string
sync.Mutex sync.Mutex
stop chan bool
err error
logger log.Logger
} }
func (l *logStream) Chan() chan LogRecord { func (l *logStream) Chan() chan LogRecord {

View File

@ -15,17 +15,17 @@ import (
type action int type action int
type kubernetes struct { type kubernetes struct {
sync.RWMutex
// options configure runtime
options *runtime.Options
// indicates if we're running
running bool
// used to stop the runtime
closed chan bool
// client is kubernetes client // client is kubernetes client
client client.Client client client.Client
// options configure runtime
options *runtime.Options
// used to stop the runtime
closed chan bool
// namespaces which exist // namespaces which exist
namespaces []client.Namespace namespaces []client.Namespace
sync.RWMutex
// indicates if we're running
running bool
} }
// namespaceExists returns a boolean indicating if a namespace exists. // namespaceExists returns a boolean indicating if a namespace exists.
@ -346,12 +346,12 @@ func (k *kubernetes) Logs(s *runtime.Service, options ...runtime.LogsOption) (ru
} }
type kubeStream struct { type kubeStream struct {
err error
// the k8s log stream // the k8s log stream
stream chan runtime.LogRecord stream chan runtime.LogRecord
stop chan bool
// the stop chan // the stop chan
sync.Mutex sync.Mutex
stop chan bool
err error
} }
func (k *kubeStream) Error() error { func (k *kubeStream) Error() error {

View File

@ -15,9 +15,9 @@ import (
) )
type klog struct { type klog struct {
options runtime.LogsOptions
client client.Client client client.Client
serviceName string serviceName string
options runtime.LogsOptions
} }
func (k *klog) podLogStream(podName string, stream *kubeStream) error { func (k *klog) podLogStream(podName string, stream *kubeStream) error {

View File

@ -15,20 +15,20 @@ type Builder interface {
// Source is the source of a build. // Source is the source of a build.
type Source struct { type Source struct {
// Language is the language of code
Language string
// Location of the source // Location of the source
Repository *source.Repository Repository *source.Repository
// Language is the language of code
Language string
} }
// Package is micro service package. // Package is micro service package.
type Package struct { type Package struct {
// Source of the binary
Source *Source
// Name of the binary // Name of the binary
Name string Name string
// Location of the binary // Location of the binary
Path string Path string
// Type of binary // Type of binary
Type string Type string
// Source of the binary
Source *Source
} }

View File

@ -14,8 +14,8 @@ import (
) )
type Builder struct { type Builder struct {
Options build.Options
Client *docker.Client Client *docker.Client
Options build.Options
} }
func (d *Builder) Build(s *build.Source) (*build.Package, error) { func (d *Builder) Build(s *build.Source) (*build.Package, error) {

View File

@ -205,8 +205,6 @@ const defaultRepo = "github.com/micro/services"
// Source is not just git related @todo move. // Source is not just git related @todo move.
type Source struct { type Source struct {
// is it a local folder intended for a local runtime?
Local bool
// absolute path to service folder in local mode // absolute path to service folder in local mode
FullPath string FullPath string
// path of folder to repo root // path of folder to repo root
@ -220,6 +218,8 @@ type Source struct {
// dir to repo root // dir to repo root
// blank for non local // blank for non local
LocalRepoRoot string LocalRepoRoot string
// is it a local folder intended for a local runtime?
Local bool
} }
// Name to be passed to RPC call runtime.Create Update Delete // Name to be passed to RPC call runtime.Create Update Delete

View File

@ -22,22 +22,22 @@ type Process interface {
type Executable struct { type Executable struct {
// Package containing executable // Package containing executable
Package *build.Package Package *build.Package
// Initial working directory
Dir string
// The env variables // The env variables
Env []string Env []string
// Args to pass // Args to pass
Args []string Args []string
// Initial working directory
Dir string
} }
// PID is the running process. // PID is the running process.
type PID struct { type PID struct {
// ID of the process
ID string
// Stdin // Stdin
Input io.Writer Input io.Writer
// Stdout // Stdout
Output io.Reader Output io.Reader
// Stderr // Stderr
Error io.Reader Error io.Reader
// ID of the process
ID string
} }

View File

@ -14,16 +14,16 @@ type Option func(o *Options)
type Options struct { type Options struct {
// Scheduler for updates // Scheduler for updates
Scheduler Scheduler Scheduler Scheduler
// Client to use when making requests
Client client.Client
// Logger underline logger
Logger logger.Logger
// Service type to manage // Service type to manage
Type string Type string
// Source of the services repository // Source of the services repository
Source string Source string
// Base image to use // Base image to use
Image string Image string
// Client to use when making requests
Client client.Client
// Logger underline logger
Logger logger.Logger
} }
func NewOptions(opts ...Option) *Options { func NewOptions(opts ...Option) *Options {
@ -86,28 +86,30 @@ type ReadOption func(o *ReadOptions)
// CreateOptions configure runtime services. // CreateOptions configure runtime services.
type CreateOptions struct { type CreateOptions struct {
// Log output
Output io.Writer
// Specify the context to use
Context context.Context
// Type of service to create
Type string
// Specify the image to use
Image string
// Namespace to create the service in
Namespace string
// Command to execut // Command to execut
Command []string Command []string
// Args to pass into command // Args to pass into command
Args []string Args []string
// Environment to configure // Environment to configure
Env []string Env []string
// Log output
Output io.Writer
// Type of service to create
Type string
// Retries before failing deploy // Retries before failing deploy
Retries int 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
} }
// ReadOptions queries runtime services. // ReadOptions queries runtime services.
type ReadOptions struct { type ReadOptions struct {
// Specify the context to use
Context context.Context
// Service name // Service name
Service string Service string
// Version queries services with given version // Version queries services with given version
@ -116,8 +118,6 @@ type ReadOptions struct {
Type string Type string
// Namespace the service is running in // 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.
@ -222,10 +222,10 @@ func ReadContext(ctx context.Context) ReadOption {
type UpdateOption func(o *UpdateOptions) type UpdateOption func(o *UpdateOptions)
type UpdateOptions struct { type UpdateOptions struct {
// Namespace the service is running in
Namespace string
// Specify the context to use // Specify the context to use
Context context.Context Context context.Context
// Namespace the service is running in
Namespace string
} }
// UpdateNamespace sets the namespace. // UpdateNamespace sets the namespace.
@ -245,10 +245,10 @@ func UpdateContext(ctx context.Context) UpdateOption {
type DeleteOption func(o *DeleteOptions) type DeleteOption func(o *DeleteOptions)
type DeleteOptions struct { type DeleteOptions struct {
// Namespace the service is running in
Namespace string
// Specify the context to use // Specify the context to use
Context context.Context Context context.Context
// Namespace the service is running in
Namespace string
} }
// DeleteNamespace sets the namespace. // DeleteNamespace sets the namespace.
@ -270,14 +270,14 @@ type LogsOption func(o *LogsOptions)
// LogsOptions configure runtime logging. // LogsOptions configure runtime logging.
type LogsOptions struct { type LogsOptions struct {
// Specify the context to use
Context context.Context
// Namespace the service is running in
Namespace string
// How many existing lines to show // How many existing lines to show
Count int64 Count int64
// Stream new lines? // Stream new lines?
Stream bool Stream bool
// Namespace the service is running in
Namespace string
// Specify the context to use
Context context.Context
} }
// LogsExistingCount confiures how many existing lines to show. // LogsExistingCount confiures how many existing lines to show.

View File

@ -45,8 +45,8 @@ type LogStream interface {
} }
type LogRecord struct { type LogRecord struct {
Message string
Metadata map[string]string Metadata map[string]string
Message string
} }
// Scheduler is a runtime service scheduler. // Scheduler is a runtime service scheduler.
@ -85,26 +85,26 @@ func (t EventType) String() string {
// Event is notification event. // Event is notification event.
type Event struct { type Event struct {
// ID of the event
ID string
// Type is event type
Type EventType
// Timestamp is event timestamp // 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 map[string]string
// 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 // url location of source
Source string Source string
// Metadata stores metadata
Metadata map[string]string
} }

View File

@ -15,29 +15,32 @@ import (
) )
type service struct { type service struct {
sync.RWMutex
running bool
closed chan bool
err error
updated time.Time updated time.Time
retries int // to be used logger
maxRetries int Logger log.Logger
// output for logs // output for logs
output io.Writer output io.Writer
// service to manage err error
*Service
// process creator // process creator
Process *proc.Process Process *proc.Process
closed chan bool
// service to manage
*Service
// Exec // Exec
Exec *process.Executable Exec *process.Executable
// process pid // process pid
PID *process.PID PID *process.PID
// to be used logger
Logger log.Logger retries int
maxRetries int
sync.RWMutex
running bool
} }
func newService(s *Service, c CreateOptions, l log.Logger) *service { func newService(s *Service, c CreateOptions, l log.Logger) *service {

View File

@ -19,12 +19,13 @@ type Options struct {
} }
type SelectOptions struct { type SelectOptions struct {
Filters []Filter
Strategy Strategy
// Other options for implementations of the interface // Other options for implementations of the interface
// can be stored in a context // can be stored in a context
Context context.Context Context context.Context
Strategy Strategy
Filters []Filter
} }
type Option func(*Options) type Option func(*Options)

View File

@ -5,19 +5,19 @@ import "context"
type HandlerOption func(*HandlerOptions) type HandlerOption func(*HandlerOptions)
type HandlerOptions struct { type HandlerOptions struct {
Internal bool
Metadata map[string]map[string]string Metadata map[string]map[string]string
Internal bool
} }
type SubscriberOption func(*SubscriberOptions) type SubscriberOption func(*SubscriberOptions)
type SubscriberOptions struct { type SubscriberOptions struct {
Context context.Context
Queue string
// AutoAck defaults to true. When a handler returns // AutoAck defaults to true. When a handler returns
// with a nil error the message is acked. // with a nil error the message is acked.
AutoAck bool AutoAck bool
Queue string
Internal bool Internal bool
Context context.Context
} }
// EndpointMetadata is a Handler option that allows metadata to be added to // EndpointMetadata is a Handler option that allows metadata to be added to

View File

@ -9,11 +9,11 @@ import (
) )
type MockServer struct { type MockServer struct {
sync.Mutex
Running bool
Opts server.Options Opts server.Options
Handlers map[string]server.Handler Handlers map[string]server.Handler
Subscribers map[string][]server.Subscriber Subscribers map[string][]server.Subscriber
sync.Mutex
Running bool
} }
var ( var (

View File

@ -6,9 +6,9 @@ import (
) )
type MockHandler struct { type MockHandler struct {
Id string
Opts server.HandlerOptions Opts server.HandlerOptions
Hdlr interface{} Hdlr interface{}
Id string
} }
func (m *MockHandler) Name() string { func (m *MockHandler) Name() string {

View File

@ -6,9 +6,9 @@ import (
) )
type MockSubscriber struct { type MockSubscriber struct {
Id string
Opts server.SubscriberOptions Opts server.SubscriberOptions
Sub interface{} Sub interface{}
Id string
} }
func (m *MockSubscriber) Topic() string { func (m *MockSubscriber) Topic() string {

View File

@ -40,38 +40,41 @@ func WithRouterLogger(l logger.Logger) RouterOption {
} }
type Options struct { type Options struct {
Codecs map[string]codec.NewCodec Logger logger.Logger
Broker broker.Broker
Registry registry.Registry
Tracer trace.Tracer
Transport transport.Transport
Metadata map[string]string
Name string
Address string
Advertise string
Id string
Version string
HdlrWrappers []HandlerWrapper
SubWrappers []SubscriberWrapper
ListenOptions []transport.ListenOption
Logger logger.Logger
// RegisterCheck runs a check function before registering the service Broker broker.Broker
RegisterCheck func(context.Context) error Registry registry.Registry
// The register expiry time Tracer trace.Tracer
RegisterTTL time.Duration Transport transport.Transport
// The interval on which to register
RegisterInterval time.Duration
// The router for requests
Router Router
// TLSConfig specifies tls.Config for secure serving
TLSConfig *tls.Config
// Other options for implementations of the interface // Other options for implementations of the interface
// can be stored in a context // can be stored in a context
Context context.Context Context context.Context
// The router for requests
Router Router
// RegisterCheck runs a check function before registering the service
RegisterCheck func(context.Context) error
Metadata map[string]string
// TLSConfig specifies tls.Config for secure serving
TLSConfig *tls.Config
Codecs map[string]codec.NewCodec
Name string
Id string
Version string
Advertise string
Address string
HdlrWrappers []HandlerWrapper
ListenOptions []transport.ListenOption
SubWrappers []SubscriberWrapper
// The interval on which to register
RegisterInterval time.Duration
// The register expiry time
RegisterTTL time.Duration
} }
// NewOptions creates new server options. // NewOptions creates new server options.

View File

@ -19,22 +19,23 @@ import (
) )
type rpcCodec struct { type rpcCodec struct {
socket transport.Socket socket transport.Socket
codec codec.Codec codec codec.Codec
protocol string
req *transport.Message req *transport.Message
buf *readWriteCloser buf *readWriteCloser
first chan bool
protocol string
// check if we're the first // check if we're the first
sync.RWMutex sync.RWMutex
first chan bool
} }
type readWriteCloser struct { type readWriteCloser struct {
sync.RWMutex
wbuf *bytes.Buffer wbuf *bytes.Buffer
rbuf *bytes.Buffer rbuf *bytes.Buffer
sync.RWMutex
} }
var ( var (

View File

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

View File

@ -9,26 +9,26 @@ import (
) )
type rpcRequest struct { type rpcRequest struct {
socket transport.Socket
codec codec.Codec
rawBody interface{}
header map[string]string
service string service string
method string method string
endpoint string endpoint string
contentType string contentType string
socket transport.Socket
codec codec.Codec
header map[string]string
body []byte body []byte
rawBody interface{}
stream bool stream bool
first bool first bool
} }
type rpcMessage struct { type rpcMessage struct {
topic string
contentType string
payload interface{} payload interface{}
header map[string]string header map[string]string
body []byte
codec codec.NewCodec codec codec.NewCodec
topic string
contentType string
body []byte
} }
func (r *rpcRequest) Codec() codec.Reader { func (r *rpcRequest) Codec() codec.Reader {

View File

@ -26,19 +26,19 @@ var (
) )
type methodType struct { type methodType struct {
sync.Mutex // protects counters
method reflect.Method
ArgType reflect.Type ArgType reflect.Type
ReplyType reflect.Type ReplyType reflect.Type
ContextType reflect.Type ContextType reflect.Type
method reflect.Method
sync.Mutex // protects counters
stream bool stream bool
} }
type service struct { type service struct {
name string // name of service
rcvr reflect.Value // receiver of methods for the service
typ reflect.Type // type of the receiver typ reflect.Type // type of the receiver
method map[string]*methodType // registered methods method map[string]*methodType // registered methods
rcvr reflect.Value // receiver of methods for the service
name string // name of service
} }
type request struct { type request struct {
@ -53,25 +53,29 @@ type response struct {
// router represents an RPC router. // router represents an RPC router.
type router struct { type router struct {
name string ops RouterOptions
ops RouterOptions
mu sync.Mutex // protects the serviceMap
serviceMap map[string]*service serviceMap map[string]*service
reqLock sync.Mutex // protects freeReq
freeReq *request freeReq *request
respLock sync.Mutex // protects freeResp
freeResp *response freeResp *response
subscribers map[string][]*subscriber
name string
// handler wrappers // handler wrappers
hdlrWrappers []HandlerWrapper hdlrWrappers []HandlerWrapper
// subscriber wrappers // subscriber wrappers
subWrappers []SubscriberWrapper subWrappers []SubscriberWrapper
su sync.RWMutex su sync.RWMutex
subscribers map[string][]*subscriber
mu sync.Mutex // protects the serviceMap
reqLock sync.Mutex // protects freeReq
respLock sync.Mutex // protects freeResp
} }
// rpcRouter encapsulates functions that become a Router. // rpcRouter encapsulates functions that become a Router.

View File

@ -27,25 +27,26 @@ import (
) )
type rpcServer struct { type rpcServer struct {
opts Options
// Subscribe to service name
subscriber broker.Subscriber
// Goal: // Goal:
// router Router // router Router
router *router router *router
exit chan chan error exit chan chan error
sync.RWMutex
opts Options
handlers map[string]Handler handlers map[string]Handler
subscribers map[Subscriber][]broker.Subscriber subscribers map[Subscriber][]broker.Subscriber
// Marks the serve as started
started bool
// Used for first registration
registered bool
// Subscribe to service name
subscriber broker.Subscriber
// Graceful exit // Graceful exit
wg *sync.WaitGroup wg *sync.WaitGroup
// Cached service // Cached service
rsvc *registry.Service rsvc *registry.Service
sync.RWMutex
// Marks the serve as started
started bool
// Used for first registration
registered bool
} }
// NewRPCServer will create a new default RPC server. // NewRPCServer will create a new default RPC server.

View File

@ -11,13 +11,13 @@ import (
// Implements the Streamer interface. // Implements the Streamer interface.
type rpcStream struct { type rpcStream struct {
sync.RWMutex
id string
closed bool
err error err error
request Request request Request
codec codec.Codec codec codec.Codec
context context.Context context context.Context
id string
sync.RWMutex
closed bool
} }
func (r *rpcStream) Context() context.Context { func (r *rpcStream) Context() context.Context {

View File

@ -6,10 +6,10 @@ import (
// waitgroup for global management of connections. // waitgroup for global management of connections.
type waitGroup struct { type waitGroup struct {
// local waitgroup
lg sync.WaitGroup
// global waitgroup // global waitgroup
gg *sync.WaitGroup gg *sync.WaitGroup
// local waitgroup
lg sync.WaitGroup
} }
// NewWaitGroup returns a new double waitgroup for global management of processes. // NewWaitGroup returns a new double waitgroup for global management of processes.

View File

@ -12,19 +12,19 @@ const (
) )
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 []*registry.Endpoint endpoints []*registry.Endpoint
opts SubscriberOptions
} }
func newSubscriber(topic string, sub interface{}, opts ...SubscriberOption) Subscriber { func newSubscriber(topic string, sub interface{}, opts ...SubscriberOption) Subscriber {

View File

@ -32,10 +32,10 @@ type memoryStore struct {
} }
type storeRecord struct { type storeRecord struct {
expiresAt time.Time
metadata map[string]interface{}
key string key string
value []byte value []byte
metadata map[string]interface{}
expiresAt time.Time
} }
func (m *memoryStore) key(prefix, key string) string { func (m *memoryStore) key(prefix, key string) string {

View File

@ -10,20 +10,20 @@ import (
// Options contains configuration for the Store. // Options contains configuration for the Store.
type Options struct { type Options struct {
// Nodes contains the addresses or other connection information of the backing storage.
// 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
// Table is analogous to a table in database backends or a key prefix in KV backends
Table string
// Context should contain all implementation specific options, using context.WithValue. // Context should contain all implementation specific options, using context.WithValue.
Context context.Context Context context.Context
// Client to use for RPC // Client to use for RPC
Client client.Client Client client.Client
// Logger is the underline logger // Logger is the underline logger
Logger logger.Logger Logger logger.Logger
// Database allows multiple isolated stores to be kept in one backend, if supported.
Database string
// Table is analogous to a table in database backends or a key prefix in KV backends
Table string
// Nodes contains the addresses or other connection information of the backing storage.
// For example, an etcd implementation would contain the nodes of the cluster.
// A SQL implementation could contain one or more connection strings.
Nodes []string
} }
// Option sets values in Options. // Option sets values in Options.
@ -127,9 +127,9 @@ func ReadOffset(o uint) ReadOption {
// WriteOptions configures an individual Write operation // WriteOptions configures an individual Write operation
// If Expiry and TTL are set TTL takes precedence. // If Expiry and TTL are set TTL takes precedence.
type WriteOptions struct { type WriteOptions struct {
Database, Table string
// Expiry is the time the record expires // Expiry is the time the record expires
Expiry time.Time Expiry time.Time
Database, Table string
// TTL is the time until the record expires // TTL is the time until the record expires
TTL time.Duration TTL time.Duration
} }

View File

@ -36,12 +36,12 @@ type Store interface {
// Record is an item stored or retrieved from a Store. // Record is an item stored or retrieved from a Store.
type Record struct { type Record struct {
// Any associated metadata for indexing
Metadata map[string]interface{} `json:"metadata"`
// The key to store the record // The key to store the record
Key string `json:"key"` Key string `json:"key"`
// The value within the record // The value within the record
Value []byte `json:"value"` Value []byte `json:"value"`
// Any associated metadata for indexing
Metadata map[string]interface{} `json:"metadata"`
// Time to expire a record: TODO: change to timestamp // Time to expire a record: TODO: change to timestamp
Expiry time.Duration `json:"expiry,omitempty"` Expiry time.Duration `json:"expiry,omitempty"`
} }

View File

@ -39,11 +39,11 @@ type Leader interface {
} }
type Options struct { type Options struct {
Nodes []string
Prefix string
TLSConfig *tls.Config
Context context.Context Context context.Context
Logger logger.Logger Logger logger.Logger
TLSConfig *tls.Config
Prefix string
Nodes []string
} }
type Option func(o *Options) type Option func(o *Options)

View File

@ -17,23 +17,25 @@ import (
) )
type httpTransportClient struct { type httpTransportClient struct {
ht *httpTransport
addr string
conn net.Conn
dialOpts DialOptions dialOpts DialOptions
once sync.Once conn net.Conn
ht *httpTransport
// request must be stored for response processing
req chan *http.Request
buff *bufio.Reader
addr string
// local/remote ip
local string
remote string
reqList []*http.Request
sync.RWMutex sync.RWMutex
// request must be stored for response processing once sync.Once
req chan *http.Request
reqList []*http.Request
buff *bufio.Reader
closed bool
// local/remote ip closed bool
local string
remote string
} }
func (h *httpTransportClient) Local() string { func (h *httpTransportClient) Local() string {

View File

@ -13,15 +13,14 @@ import (
) )
type httpTransportSocket struct { type httpTransportSocket struct {
ht *httpTransport w http.ResponseWriter
w http.ResponseWriter
r *http.Request
rw *bufio.ReadWriter
mtx sync.RWMutex
// the hijacked when using http 1 // the hijacked when using http 1
conn net.Conn conn net.Conn
ht *httpTransport
r *http.Request
rw *bufio.ReadWriter
// for the first request // for the first request
ch chan *http.Request ch chan *http.Request
@ -33,6 +32,8 @@ type httpTransportSocket struct {
// local/remote ip // local/remote ip
local string local string
remote string remote string
mtx sync.RWMutex
} }
func (h *httpTransportSocket) Local() string { func (h *httpTransportSocket) Local() string {

View File

@ -16,8 +16,7 @@ import (
) )
type memorySocket struct { type memorySocket struct {
// True server mode, False client mode ctx context.Context
server bool
// Client receiver of io.Pipe with gob // Client receiver of io.Pipe with gob
crecv *gob.Decoder crecv *gob.Decoder
// Client sender of the io.Pipe with gob // Client sender of the io.Pipe with gob
@ -36,7 +35,8 @@ type memorySocket struct {
// for send/recv Timeout // for send/recv Timeout
timeout time.Duration timeout time.Duration
ctx context.Context // True server mode, False client mode
server bool
} }
type memoryClient struct { type memoryClient struct {
@ -45,19 +45,19 @@ type memoryClient struct {
} }
type memoryListener struct { type memoryListener struct {
addr string lopts ListenOptions
ctx context.Context
exit chan bool exit chan bool
conn chan *memorySocket conn chan *memorySocket
lopts ListenOptions
topts Options topts Options
addr string
sync.RWMutex sync.RWMutex
ctx context.Context
} }
type memoryTransport struct { type memoryTransport struct {
opts Options
sync.RWMutex
listeners map[string]*memoryListener listeners map[string]*memoryListener
opts Options
sync.RWMutex
} }
func (ms *memorySocket) Recv(m *Message) error { func (ms *memorySocket) Recv(m *Message) error {

View File

@ -15,39 +15,30 @@ var (
) )
type Options struct { type Options struct {
// Addrs is the list of intermediary addresses to connect to
Addrs []string
// Codec is the codec interface to use where headers are not supported // Codec is the codec interface to use where headers are not supported
// by the transport and the entire payload must be encoded // by the transport and the entire payload must be encoded
Codec codec.Marshaler Codec codec.Marshaler
// Secure tells the transport to secure the connection.
// In the case TLSConfig is not specified best effort self-signed
// certs should be used
Secure bool
// 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
// Other options for implementations of the interface // Other options for implementations of the interface
// can be stored in a context // can be stored in a context
Context context.Context Context context.Context
// Logger is the underline logger // Logger is the underline logger
Logger logger.Logger Logger logger.Logger
// TLSConfig to secure the connection. The assumption is that this
// is mTLS keypair
TLSConfig *tls.Config
// Addrs is the list of intermediary addresses to connect to
Addrs []string
// Timeout sets the timeout for Send/Recv
Timeout time.Duration
// BuffSizeH2 is the HTTP2 buffer size // BuffSizeH2 is the HTTP2 buffer size
BuffSizeH2 int BuffSizeH2 int
// Secure tells the transport to secure the connection.
// In the case TLSConfig is not specified best effort self-signed
// certs should be used
Secure bool
} }
type DialOptions struct { type DialOptions struct {
// Tells the transport this is a streaming connection with
// multiple calls to send/recv and that send may not even be called
Stream bool
// Timeout for dialing
Timeout time.Duration
// ConnClose sets the Connection header to close
ConnClose bool
// InsecureSkipVerify skip TLS verification.
InsecureSkipVerify bool
// TODO: add tls options when dialing // TODO: add tls options when dialing
// Currently set in global options // Currently set in global options
@ -55,6 +46,15 @@ type DialOptions struct {
// Other options for implementations of the interface // Other options for implementations of the interface
// can be stored in a context // can be stored in a context
Context context.Context Context context.Context
// Timeout for dialing
Timeout time.Duration
// Tells the transport this is a streaming connection with
// multiple calls to send/recv and that send may not even be called
Stream bool
// ConnClose sets the Connection header to close
ConnClose bool
// InsecureSkipVerify skip TLS verification.
InsecureSkipVerify bool
} }
type ListenOptions struct { type ListenOptions struct {

View File

@ -19,28 +19,31 @@ import (
) )
type Options struct { type Options struct {
// For the Command Line itself
Name string
Description string
Version string
// We need pointers to things so we can swap them out if needed. // Other options for implementations of the interface
Broker *broker.Broker // can be stored in a context
Registry *registry.Registry Context context.Context
Selector *selector.Selector Auth *auth.Auth
Selector *selector.Selector
Profile *profile.Profile
Registry *registry.Registry
Brokers map[string]func(...broker.Option) broker.Broker
Transport *transport.Transport Transport *transport.Transport
Cache *cache.Cache Cache *cache.Cache
Config *config.Config Config *config.Config
Client *client.Client Client *client.Client
Server *server.Server Server *server.Server
Runtime *runtime.Runtime Runtime *runtime.Runtime
Store *store.Store Caches map[string]func(...cache.Option) cache.Cache
Tracer *trace.Tracer Tracer *trace.Tracer
Auth *auth.Auth Profiles map[string]func(...profile.Option) profile.Profile
Profile *profile.Profile
Brokers map[string]func(...broker.Option) broker.Broker // We need pointers to things so we can swap them out if needed.
Caches map[string]func(...cache.Option) cache.Cache Broker *broker.Broker
Auths map[string]func(...auth.Option) auth.Auth
Store *store.Store
Configs map[string]func(...config.Option) (config.Config, error) Configs map[string]func(...config.Option) (config.Config, error)
Clients map[string]func(...client.Option) client.Client Clients map[string]func(...client.Option) client.Client
Registries map[string]func(...registry.Option) registry.Registry Registries map[string]func(...registry.Option) registry.Registry
@ -50,12 +53,11 @@ type Options struct {
Runtimes map[string]func(...runtime.Option) runtime.Runtime Runtimes map[string]func(...runtime.Option) runtime.Runtime
Stores map[string]func(...store.Option) store.Store Stores map[string]func(...store.Option) store.Store
Tracers map[string]func(...trace.Option) trace.Tracer Tracers map[string]func(...trace.Option) trace.Tracer
Auths map[string]func(...auth.Option) auth.Auth Version string
Profiles map[string]func(...profile.Option) profile.Profile
// Other options for implementations of the interface // For the Command Line itself
// can be stored in a context Name string
Context context.Context Description string
} }
// Command line Name. // Command line Name.

View File

@ -30,9 +30,9 @@ func RegisterHandler(s server.Server, readDir string) {
} }
type handler struct { type handler struct {
readDir string
session *session
logger log.Logger logger log.Logger
session *session
readDir string
} }
func (h *handler) Open(ctx context.Context, req *proto.OpenRequest, rsp *proto.OpenResponse) error { func (h *handler) Open(ctx context.Context, req *proto.OpenRequest, rsp *proto.OpenResponse) error {
@ -120,9 +120,9 @@ func (h *handler) Write(ctx context.Context, req *proto.WriteRequest, rsp *proto
} }
type session struct { type session struct {
sync.Mutex
files map[int64]*os.File files map[int64]*os.File
counter int64 counter int64
sync.Mutex
} }
func (s *session) Add(file *os.File) int64 { func (s *session) Add(file *os.File) int64 {

View File

@ -16,20 +16,20 @@ import (
// Request is used to construct a http request for the k8s API. // Request is used to construct a http request for the k8s API.
type Request struct { type Request struct {
// the request context // the request context
context context.Context context context.Context
client *http.Client body io.Reader
header http.Header
params url.Values
method string
host string
namespace string
resource string err error
client *http.Client
header http.Header
params url.Values
resourceName *string resourceName *string
subResource *string subResource *string
body io.Reader method string
host string
namespace string
err error resource string
} }
// Params is the object to pass in to set parameters // Params is the object to pass in to set parameters
@ -246,10 +246,10 @@ func (r *Request) Raw() (*http.Response, error) {
// Options ... // Options ...
type Options struct { type Options struct {
Host string
Namespace string
BearerToken *string BearerToken *string
Client *http.Client Client *http.Client
Host string
Namespace string
} }
// NewRequest creates a k8s api request. // NewRequest creates a k8s api request.

View File

@ -5,8 +5,8 @@ type CreateOptions struct {
} }
type GetOptions struct { type GetOptions struct {
Namespace string
Labels map[string]string Labels map[string]string
Namespace string
} }
type UpdateOptions struct { type UpdateOptions struct {
Namespace string Namespace string
@ -19,13 +19,13 @@ type ListOptions struct {
} }
type LogOptions struct { type LogOptions struct {
Namespace string
Params map[string]string Params map[string]string
Namespace string
} }
type WatchOptions struct { type WatchOptions struct {
Namespace string
Params map[string]string Params map[string]string
Namespace string
} }
type CreateOption func(*CreateOptions) type CreateOption func(*CreateOptions)

View File

@ -3,9 +3,9 @@ package client
// ContainerPort. // ContainerPort.
type ContainerPort struct { type ContainerPort struct {
Name string `json:"name,omitempty"` Name string `json:"name,omitempty"`
Protocol string `json:"protocol,omitempty"`
HostPort int `json:"hostPort,omitempty"` HostPort int `json:"hostPort,omitempty"`
ContainerPort int `json:"containerPort"` ContainerPort int `json:"containerPort"`
Protocol string `json:"protocol,omitempty"`
} }
// EnvVar is environment variable. // EnvVar is environment variable.
@ -32,9 +32,9 @@ type Container struct {
// DeploymentSpec defines micro deployment spec. // DeploymentSpec defines micro deployment spec.
type DeploymentSpec struct { type DeploymentSpec struct {
Replicas int `json:"replicas,omitempty"`
Selector *LabelSelector `json:"selector"` Selector *LabelSelector `json:"selector"`
Template *Template `json:"template,omitempty"` Template *Template `json:"template,omitempty"`
Replicas int `json:"replicas,omitempty"`
} }
// DeploymentCondition describes the state of deployment. // DeploymentCondition describes the state of deployment.
@ -47,12 +47,12 @@ type DeploymentCondition struct {
// DeploymentStatus is returned when querying deployment. // DeploymentStatus is returned when querying deployment.
type DeploymentStatus struct { type DeploymentStatus struct {
Conditions []DeploymentCondition `json:"conditions,omitempty"`
Replicas int `json:"replicas,omitempty"` Replicas int `json:"replicas,omitempty"`
UpdatedReplicas int `json:"updatedReplicas,omitempty"` UpdatedReplicas int `json:"updatedReplicas,omitempty"`
ReadyReplicas int `json:"readyReplicas,omitempty"` ReadyReplicas int `json:"readyReplicas,omitempty"`
AvailableReplicas int `json:"availableReplicas,omitempty"` AvailableReplicas int `json:"availableReplicas,omitempty"`
UnavailableReplicas int `json:"unavailableReplicas,omitempty"` UnavailableReplicas int `json:"unavailableReplicas,omitempty"`
Conditions []DeploymentCondition `json:"conditions,omitempty"`
} }
// Deployment is Kubernetes deployment. // Deployment is Kubernetes deployment.
@ -84,17 +84,17 @@ type LoadBalancerStatus struct {
// Metadata defines api object metadata. // Metadata defines api object metadata.
type Metadata struct { type Metadata struct {
Labels map[string]string `json:"labels,omitempty"`
Annotations map[string]string `json:"annotations,omitempty"`
Name string `json:"name,omitempty"` Name string `json:"name,omitempty"`
Namespace string `json:"namespace,omitempty"` Namespace string `json:"namespace,omitempty"`
Version string `json:"version,omitempty"` Version string `json:"version,omitempty"`
Labels map[string]string `json:"labels,omitempty"`
Annotations map[string]string `json:"annotations,omitempty"`
} }
// PodSpec is a pod. // PodSpec is a pod.
type PodSpec struct { type PodSpec struct {
Containers []Container `json:"containers"`
ServiceAccountName string `json:"serviceAccountName"` ServiceAccountName string `json:"serviceAccountName"`
Containers []Container `json:"containers"`
} }
// PodList. // PodList.
@ -111,11 +111,11 @@ type Pod struct {
// PodStatus. // PodStatus.
type PodStatus struct { type PodStatus struct {
Conditions []PodCondition `json:"conditions,omitempty"`
Containers []ContainerStatus `json:"containerStatuses"`
PodIP string `json:"podIP"` PodIP string `json:"podIP"`
Phase string `json:"phase"` Phase string `json:"phase"`
Reason string `json:"reason"` Reason string `json:"reason"`
Conditions []PodCondition `json:"conditions,omitempty"`
Containers []ContainerStatus `json:"containerStatuses"`
} }
// PodCondition describes the state of pod. // PodCondition describes the state of pod.
@ -137,16 +137,16 @@ type ContainerState struct {
// Resource is API resource. // Resource is API resource.
type Resource struct { type Resource struct {
Value interface{}
Name string Name string
Kind string Kind string
Value interface{}
} }
// ServicePort configures service ports. // ServicePort configures service ports.
type ServicePort struct { type ServicePort struct {
Name string `json:"name,omitempty"` Name string `json:"name,omitempty"`
Port int `json:"port"`
Protocol string `json:"protocol,omitempty"` Protocol string `json:"protocol,omitempty"`
Port int `json:"port"`
} }
// ServiceSpec provides service configuration. // ServiceSpec provides service configuration.
@ -197,9 +197,9 @@ type ImagePullSecret struct {
// Secret. // Secret.
type Secret struct { type Secret struct {
Type string `json:"type,omitempty"`
Data map[string]string `json:"data"` Data map[string]string `json:"data"`
Metadata *Metadata `json:"metadata"` Metadata *Metadata `json:"metadata"`
Type string `json:"type,omitempty"`
} }
// ServiceAccount. // ServiceAccount.

View File

@ -18,16 +18,17 @@ import (
type ServiceEntry struct { type ServiceEntry struct {
Name string Name string
Host string Host string
Info string
AddrV4 net.IP AddrV4 net.IP
AddrV6 net.IP AddrV6 net.IP
Port int
Info string
InfoFields []string InfoFields []string
TTL int
Type uint16
Addr net.IP // @Deprecated Addr net.IP // @Deprecated
Port int
TTL int
Type uint16
hasTXT bool hasTXT bool
sent bool sent bool
} }
@ -39,13 +40,13 @@ func (s *ServiceEntry) complete() bool {
// QueryParam is used to customize how a Lookup is performed. // QueryParam is used to customize how a Lookup is performed.
type QueryParam struct { type QueryParam struct {
Service string // Service to lookup
Domain string // Lookup domain, default "local"
Type uint16 // Lookup type, defaults to dns.TypePTR
Context context.Context // Context Context context.Context // Context
Timeout time.Duration // Lookup timeout, default 1 second. Ignored if Context is provided
Interface *net.Interface // Multicast interface to use Interface *net.Interface // Multicast interface to use
Entries chan<- *ServiceEntry // Entries Channel Entries chan<- *ServiceEntry // Entries Channel
Service string // Service to lookup
Domain string // Lookup domain, default "local"
Timeout time.Duration // Lookup timeout, default 1 second. Ignored if Context is provided
Type uint16 // Lookup type, defaults to dns.TypePTR
WantUnicastResponse bool // Unicast response desired, as per 5.4 in RFC WantUnicastResponse bool // Unicast response desired, as per 5.4 in RFC
} }
@ -170,9 +171,10 @@ type client struct {
ipv4MulticastConn *net.UDPConn ipv4MulticastConn *net.UDPConn
ipv6MulticastConn *net.UDPConn ipv6MulticastConn *net.UDPConn
closed bool
closedCh chan struct{} // TODO(reddaly): This doesn't appear to be used. closedCh chan struct{} // TODO(reddaly): This doesn't appear to be used.
closeLock sync.Mutex closeLock sync.Mutex
closed bool
} }
// NewClient creates a new mdns Client that can be used to query // NewClient creates a new mdns Client that can be used to query

Some files were not shown because too many files have changed in this diff Show More