Documentation ¶
Overview ¶
Package connector implements the base class of all microservices.
Index ¶
- Constants
- type Connector
- func (c *Connector) Config(name string) (value string)
- func (c *Connector) DefineConfig(name string, options ...cfg.Option) error
- func (c *Connector) DefineCounter(name, help string, labels []string) error
- func (c *Connector) DefineGauge(name, help string, labels []string) error
- func (c *Connector) DefineHistogram(name, help string, buckets []float64, labels []string) error
- func (c *Connector) Deployment() string
- func (c *Connector) Description() string
- func (c *Connector) DistribCache() *dlru.Cache
- func (c *Connector) ExecuteResTemplate(name string, data any) (string, error)
- func (c *Connector) ForceTrace(ctx context.Context)
- func (c *Connector) GET(ctx context.Context, url string) (*http.Response, error)
- func (c *Connector) Go(ctx context.Context, f func(ctx context.Context) (err error)) error
- func (c *Connector) Hostname() string
- func (c *Connector) ID() string
- func (c *Connector) IncrementMetric(name string, val float64, labels ...string) error
- func (c *Connector) IsStarted() bool
- func (c *Connector) Lifetime() context.Context
- func (c *Connector) LoadResString(ctx context.Context, stringKey string) (string, error)
- func (c *Connector) Locality() string
- func (c *Connector) LogDebug(ctx context.Context, msg string, fields ...log.Field)
- func (c *Connector) LogError(ctx context.Context, msg string, fields ...log.Field)
- func (c *Connector) LogInfo(ctx context.Context, msg string, fields ...log.Field)
- func (c *Connector) LogWarn(ctx context.Context, msg string, fields ...log.Field)
- func (c *Connector) MustReadResFile(name string) []byte
- func (c *Connector) MustReadResTextFile(name string) string
- func (c *Connector) Now(ctx context.Context) time.Time
- func (c *Connector) NowX(ctx context.Context) timex.Timex
- func (c *Connector) ObserveMetric(name string, val float64, labels ...string) error
- func (c *Connector) POST(ctx context.Context, url string, body any) (*http.Response, error)
- func (c *Connector) Parallel(jobs ...func() (err error)) error
- func (c *Connector) Plane() string
- func (c *Connector) Publish(ctx context.Context, options ...pub.Option) <-chan *pub.Response
- func (c *Connector) ReadResFile(name string) ([]byte, error)
- func (c *Connector) ReadResTextFile(name string) (string, error)
- func (c *Connector) Request(ctx context.Context, options ...pub.Option) (*http.Response, error)
- func (c *Connector) ResFS() service.FS
- func (c *Connector) ResetConfig(name string) error
- func (c *Connector) ServeResFile(name string, w http.ResponseWriter, r *http.Request) error
- func (c *Connector) SetConfig(name string, value any) error
- func (c *Connector) SetDeployment(deployment string) error
- func (c *Connector) SetDescription(description string) error
- func (c *Connector) SetHostname(hostname string) error
- func (c *Connector) SetLocality(locality string) error
- func (c *Connector) SetOnConfigChanged(handler service.ConfigChangedHandler) error
- func (c *Connector) SetOnShutdown(handler service.ShutdownHandler) error
- func (c *Connector) SetOnStartup(handler service.StartupHandler) error
- func (c *Connector) SetPlane(plane string) error
- func (c *Connector) SetResFS(fs service.FS) error
- func (c *Connector) SetResFSDir(directoryPath string) error
- func (c *Connector) SetVersion(version int) error
- func (c *Connector) Shutdown() (err error)
- func (c *Connector) Span(ctx context.Context) trc.Span
- func (c *Connector) StartSpan(ctx context.Context, spanName string, opts ...trc.Option) (context.Context, trc.Span)
- func (c *Connector) StartTicker(name string, interval time.Duration, handler service.TickerHandler) error
- func (c *Connector) Startup() (err error)
- func (c *Connector) Subscribe(method string, path string, handler sub.HTTPHandler, options ...sub.Option) error
- func (c *Connector) Unsubscribe(method string, path string) error
- func (c *Connector) Version() int
- type HTTPHandler
Constants ¶
const ( PROD string = "PROD" // PROD for a production environment LAB string = "LAB" // LAB for all non-production environments such as dev integration, test, staging, etc. LOCAL string = "LOCAL" // LOCAL when developing on the local machine TESTING string = "TESTING" // TESTING when running inside a testing app )
Deployment environments
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Connector ¶
type Connector struct {
// contains filtered or unexported fields
}
Connector is the base class of a microservice. It provides the microservice such functions as connecting to the NATS messaging bus, communications with other microservices, logging, config, etc.
func (*Connector) Config ¶
Config returns the value of a previously defined property. The value of the property is available after the microservice has started after being obtained from the configurator microservice. Property names are case-insensitive.
func (*Connector) DefineConfig ¶
DefineConfig defines a property used to configure the microservice. Properties must be defined before the service starts. Config property names are case-insensitive.
func (*Connector) DefineCounter ¶
DefineCounter defines a new counter metric. The metric can later be incremented.
func (*Connector) DefineGauge ¶
DefineGauge defines a new gauge metric. The metric can later be observed or incremented.
func (*Connector) DefineHistogram ¶
DefineHistogram defines a new histogram metric. The metric can later be observed.
func (*Connector) Deployment ¶
Deployment indicates what deployment environment the microservice is running in: PROD for a production environment; LAB for all non-production environments such as dev integration, test, staging, etc.; LOCAL when developing on the local machine; TESTING when running inside a testing app.
func (*Connector) Description ¶
Description returns the human-friendly description of the microservice.
func (*Connector) DistribCache ¶
DistribCache is a cache that stores data among all peers of the microservice. By default the cache is limited to 32MB per peer and a 1 hour TTL.
Operating on a distributed cache is slower than on a local cache because it involves network communication among peers. However, the memory capacity of a distributed cache scales linearly with the number of peers and its content is often able to survive a restart of the microservice.
Cache elements can get evicted for various reason and without warning. Cache only that which you can afford to lose and reconstruct. Do not use the cache to share state among peers. The cache is subject to race conditions in rare situations.
func (*Connector) ExecuteResTemplate ¶
ExecuteResTemplate parses the resource file as a template, executes it given the data, and returns the result. The template is assumed to be a text template unless the file name ends in .html, in which case it is processed as an HTML template.
{{ var | attr }}, {{ var | url }}, {{ var | css }} or {{ var | safe }} may be used to prevent the escaping of a variable in an HTML template. These map to htmltemplate.HTMLAttr, htmltemplate.URL, htmltemplate.CSS and htmltemplate.HTML respectively. Use of these types presents a security risk.
func (*Connector) ForceTrace ¶
ForceTrace forces the trace containing the span to be exported
func (*Connector) Go ¶
Go launches a goroutine in the lifetime context of the microservice. Errors and panics are automatically captured and logged. On shutdown, the microservice will attempt to gracefully end a pending goroutine before termination.
func (*Connector) Hostname ¶
Hostname returns the hostname of the microservice. A microservice is addressable by its hostname.
func (*Connector) IncrementMetric ¶
IncrementMetric adds the given value to a counter or gauge metric. The name and labels must match a previously defined metric. Gauge metrics support subtraction by use of a negative value. Counter metrics only allow addition and a negative value will result in an error.
func (*Connector) IsStarted ¶
IsStarted indicates if the microservice has been successfully started.
func (*Connector) Lifetime ¶
Lifetime returns a context that gets cancelled when the microservice is shutdown. The Done() channel can be used to detect when the microservice is shutting down. In most cases the lifetime context should be used instead of the background context.
func (*Connector) LoadResString ¶
LoadResString returns a string from the string bundle in the language best matched to the locale in the context. The string bundle is a YAML file that must be loadable from the service's resource FS with the name strings.yaml. The YAML is expected to be in the following format:
stringKey: default: Localized en: Localized en-UK: Localised fr: Localisée
If a default is not provided, English (en) is used as the fallback language. String keys and locale names are case-sensitive.
func (*Connector) LogDebug ¶
LogDebug logs a message at DEBUG level. DEBUG level messages are ignored in PROD environments or if the MICROBUS_LOG_DEBUG environment variable is not set. The message should be static and concise. Optional fields can be added for variable data.
Example:
c.LogDebug(ctx, "Tight loop", log.String("index", i))
func (*Connector) LogError ¶
LogError logs a message at ERROR level. The message should be static and concise. Optional fields can be added for variable data. To log an error object use the log.Error field.
Example:
c.LogError(ctx, "Opening file", log.Error(err), log.String("file", fileName))
func (*Connector) LogInfo ¶
LogInfo logs a message at INFO level. The message should be static and concise. Optional fields can be added for variable data.
Example:
c.LogInfo(ctx, "File uploaded", log.String("gb", sizeGB))
func (*Connector) LogWarn ¶
LogWarn logs a message at WARN level. The message should be static and concise. Optional fields can be added for variable data.
Example:
c.LogWarn(ctx, "Dropping job", log.String("job", jobID))
func (*Connector) MustReadResFile ¶
MustReadResFile returns the content of a resource file, or nil if not found.
func (*Connector) MustReadResTextFile ¶
MustReadResTextFile returns the content of a resource file as a string, or "" if not found.
func (*Connector) Now ¶
Now returns the current time in the UTC timezone. The time may be offset if the context was a clock shift was set on the context using the frame.
func (*Connector) NowX ¶
NowX returns the current time in the UTC timezone. The time may be offset if the context was a clock shift was set on the context using the frame.
func (*Connector) ObserveMetric ¶
ObserveMetric observes the given value using a histogram or summary, or sets it as a gauge's value. The name and labels must match a previously defined metric.
func (*Connector) POST ¶
POST makes a POST request. Body of type io.Reader, []byte and string is serialized in binary form. url.Values is serialized as form data. All other types are serialized as JSON.
func (*Connector) Parallel ¶
Parallel executes multiple jobs in parallel and returns the first error it encounters. It is a convenient pattern for calling multiple other microservices and thus amortize the network latency. There is no mechanism to identify the failed jobs so this pattern isn't suited for jobs that update data and require to be rolled back on failure.
func (*Connector) Plane ¶
Plane is a unique prefix set for all communications sent or received by this microservice. It is used to isolate communication among a group of microservices over a NATS cluster that is shared with other microservices. If not explicitly set, the value is pulled from the Plane config, or the default "microbus" is used
func (*Connector) Publish ¶
Publish makes an HTTP request then awaits and returns the responses asynchronously. By default, publish performs a multicast and multiple responses (or none at all) may be returned. Use the Request method or pass in pub.Unicast() to Publish to perform a unicast.
func (*Connector) ReadResFile ¶
ReadResFile returns the content of a resource file.
func (*Connector) ReadResTextFile ¶
ReadResTextFile returns the content of a resource file as a string.
func (*Connector) Request ¶
Request makes an HTTP request then awaits and returns a single response synchronously. If no response is received, an ack timeout (404) error is returned.
func (*Connector) ResetConfig ¶
ResetConfig resets the value of a previously defined configuration property to its default value. This value will be overridden on the next fetch of values from the configurator core microservice, except in a TESTING deployment wherein the configurator is disabled. Configuration property names are case-insensitive.
func (*Connector) ServeResFile ¶
ServeResFile serves the content of a resources file as a response to a web request.
func (*Connector) SetConfig ¶
SetConfig sets the value of a previously defined configuration property. This value will be overridden on the next fetch of values from the configurator core microservice, except in a TESTING deployment wherein the configurator is disabled. Configuration property names are case-insensitive.
func (*Connector) SetDeployment ¶
SetDeployment sets what deployment environment the microservice is running in. Explicitly setting a deployment will override any value specified by the Deployment config property. Setting an empty value will clear this override.
Valid values are: PROD for a production environment; LAB for all non-production environments such as dev integration, test, staging, etc.; LOCAL when developing on the local machine; TESTING when running inside a testing app.
func (*Connector) SetDescription ¶
SetDescription sets a human-friendly description of the microservice.
func (*Connector) SetHostname ¶
SetHostname sets the hostname of the microservice. Hostnames are case-insensitive. Each segment of the hostname may contain letters, numbers, hyphens or underscores only. Segments are separated by dots. For example, this.is.a.valid.host-name.123.local
func (*Connector) SetLocality ¶
SetLocality sets the geographic locality of the microservice which is used to optimize routing. Localities are hierarchical with the more specific identifiers first, separated by dots. It can be set to correlate to AWS regions such as az1.dc2.west.us, or arbitrarily to rome.italy.europe for example. Localities are case-insensitive. Each segment of the hostname may contain letters, numbers, hyphens or underscores only.
func (*Connector) SetOnConfigChanged ¶
func (c *Connector) SetOnConfigChanged(handler service.ConfigChangedHandler) error
SetOnConfigChanged adds a function to be called when a new config was received from the configurator. Callbacks are called in the order they were added.
func (*Connector) SetOnShutdown ¶
func (c *Connector) SetOnShutdown(handler service.ShutdownHandler) error
SetOnShutdown adds a function to be called during the shutting down of the microservice. Shutdown callbacks are called in the reverse order they were added, whether of the status of a corresponding startup callback.
func (*Connector) SetOnStartup ¶
func (c *Connector) SetOnStartup(handler service.StartupHandler) error
SetOnStartup adds a function to be called during the starting up of the microservice. Startup callbacks are called in the order they were added.
func (*Connector) SetPlane ¶
SetPlane sets a unique prefix for all communications sent or received by this microservice. A plane is used to isolate communication among a group of microservices over a NATS cluster that is shared with other microservices. Explicitly setting a plane overrides any value specified by the Plane config. The plane can only contain alphanumeric case-sensitive characters. Setting an empty value will clear this override
func (*Connector) SetResFS ¶
SetResFS initialized the connector to load resource files from an arbitrary FS.
func (*Connector) SetResFSDir ¶
SetResFSDir initialized the connector to load resource files from a directory.
func (*Connector) SetVersion ¶
SetVersion sets the sequential version number of the microservice.
func (*Connector) Shutdown ¶
Shutdown the microservice by deactivating subscriptions and disconnecting from the NATS bus.
func (*Connector) StartSpan ¶
func (c *Connector) StartSpan(ctx context.Context, spanName string, opts ...trc.Option) (context.Context, trc.Span)
StartSpan creates a tracing span and a context containing the newly-created span. If the context provided already contains asSpan then the newly-created span will be a child of that span, otherwise it will be a root span.
Any Span that is created must also be ended. This is the responsibility of the user. Implementations of this API may leak memory or other resources if spans are not ended.
func (*Connector) StartTicker ¶
func (c *Connector) StartTicker(name string, interval time.Duration, handler service.TickerHandler) error
StartTicker initiates a recurring job at a set interval. Tickers do not run when the connector is running in the TESTING deployment environment.
func (*Connector) Startup ¶
Startup the microservice by connecting to the NATS bus and activating the subscriptions.
func (*Connector) Subscribe ¶
func (c *Connector) Subscribe(method string, path string, handler sub.HTTPHandler, options ...sub.Option) error
Subscribe assigns a function to handle HTTP requests to the given path. If the path ends with a / all sub-paths under the path are capture by the subscription
If the path does not include a hostname, the default host is used. If a port is not specified, 443 is used by default. If a method is not specified, * is used by default to capture all methods.
Examples of valid paths:
(empty) / :1080 :1080/ :1080/path /path/with/slash path/with/no/slash https://www.example.com/path https://www.example.com:1080/path
func (*Connector) Unsubscribe ¶
Unsubscribe removes the handler for the specified path
type HTTPHandler ¶
type HTTPHandler = sub.HTTPHandler
HTTPHandler extends the standard http.Handler to also return an error