connector

package
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Jul 9, 2024 License: Apache-2.0 Imports: 51 Imported by: 0

Documentation

Overview

Package connector implements the base class of all microservices.

Index

Constants

View Source
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 New

func New(hostname string) *Connector

New constructs a new Connector with the given hostname.

func NewConnector

func NewConnector() *Connector

NewConnector constructs a new Connector.

func (*Connector) Config

func (c *Connector) Config(name string) (value string)

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

func (c *Connector) DefineConfig(name string, options ...cfg.Option) error

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

func (c *Connector) DefineCounter(name, help string, labels []string) error

DefineCounter defines a new counter metric. The metric can later be incremented.

func (*Connector) DefineGauge

func (c *Connector) DefineGauge(name, help string, labels []string) error

DefineGauge defines a new gauge metric. The metric can later be observed or incremented.

func (*Connector) DefineHistogram

func (c *Connector) DefineHistogram(name, help string, buckets []float64, labels []string) error

DefineHistogram defines a new histogram metric. The metric can later be observed.

func (*Connector) Deployment

func (c *Connector) Deployment() string

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

func (c *Connector) Description() string

Description returns the human-friendly description of the microservice.

func (*Connector) DistribCache

func (c *Connector) DistribCache() *dlru.Cache

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

func (c *Connector) ExecuteResTemplate(name string, data any) (string, error)

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

func (c *Connector) ForceTrace(ctx context.Context)

ForceTrace forces the trace containing the span to be exported

func (*Connector) GET

func (c *Connector) GET(ctx context.Context, url string) (*http.Response, error)

GET makes a GET request.

func (*Connector) Go

func (c *Connector) Go(ctx context.Context, f func(ctx context.Context) (err error)) error

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

func (c *Connector) Hostname() string

Hostname returns the hostname of the microservice. A microservice is addressable by its hostname.

func (*Connector) ID

func (c *Connector) ID() string

ID is a unique identifier of a particular instance of the microservice

func (*Connector) IncrementMetric

func (c *Connector) IncrementMetric(name string, val float64, labels ...string) error

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

func (c *Connector) IsStarted() bool

IsStarted indicates if the microservice has been successfully started.

func (*Connector) Lifetime

func (c *Connector) Lifetime() context.Context

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

func (c *Connector) LoadResString(ctx context.Context, stringKey string) (string, error)

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) Locality

func (c *Connector) Locality() string

Locality returns the geographic locality of the microservice.

func (*Connector) LogDebug

func (c *Connector) LogDebug(ctx context.Context, msg string, fields ...log.Field)

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

func (c *Connector) LogError(ctx context.Context, msg string, fields ...log.Field)

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

func (c *Connector) LogInfo(ctx context.Context, msg string, fields ...log.Field)

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

func (c *Connector) LogWarn(ctx context.Context, msg string, fields ...log.Field)

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

func (c *Connector) MustReadResFile(name string) []byte

MustReadResFile returns the content of a resource file, or nil if not found.

func (*Connector) MustReadResTextFile

func (c *Connector) MustReadResTextFile(name string) string

MustReadResTextFile returns the content of a resource file as a string, or "" if not found.

func (*Connector) Now

func (c *Connector) Now(ctx context.Context) time.Time

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

func (c *Connector) NowX(ctx context.Context) timex.Timex

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

func (c *Connector) ObserveMetric(name string, val float64, labels ...string) error

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

func (c *Connector) POST(ctx context.Context, url string, body any) (*http.Response, error)

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

func (c *Connector) Parallel(jobs ...func() (err error)) error

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

func (c *Connector) Plane() string

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

func (c *Connector) Publish(ctx context.Context, options ...pub.Option) <-chan *pub.Response

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

func (c *Connector) ReadResFile(name string) ([]byte, error)

ReadResFile returns the content of a resource file.

func (*Connector) ReadResTextFile

func (c *Connector) ReadResTextFile(name string) (string, error)

ReadResTextFile returns the content of a resource file as a string.

func (*Connector) Request

func (c *Connector) Request(ctx context.Context, options ...pub.Option) (*http.Response, error)

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) ResFS

func (c *Connector) ResFS() service.FS

ResFS returns the FS associated with the connector.

func (*Connector) ResetConfig

func (c *Connector) ResetConfig(name string) error

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

func (c *Connector) ServeResFile(name string, w http.ResponseWriter, r *http.Request) error

ServeResFile serves the content of a resources file as a response to a web request.

func (*Connector) SetConfig

func (c *Connector) SetConfig(name string, value any) error

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

func (c *Connector) SetDeployment(deployment string) error

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

func (c *Connector) SetDescription(description string) error

SetDescription sets a human-friendly description of the microservice.

func (*Connector) SetHostname

func (c *Connector) SetHostname(hostname string) error

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

func (c *Connector) SetLocality(locality string) error

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

func (c *Connector) SetPlane(plane string) error

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

func (c *Connector) SetResFS(fs service.FS) error

SetResFS initialized the connector to load resource files from an arbitrary FS.

func (*Connector) SetResFSDir

func (c *Connector) SetResFSDir(directoryPath string) error

SetResFSDir initialized the connector to load resource files from a directory.

func (*Connector) SetVersion

func (c *Connector) SetVersion(version int) error

SetVersion sets the sequential version number of the microservice.

func (*Connector) Shutdown

func (c *Connector) Shutdown() (err error)

Shutdown the microservice by deactivating subscriptions and disconnecting from the NATS bus.

func (*Connector) Span

func (c *Connector) Span(ctx context.Context) trc.Span

Span returns the tracing span stored in the context.

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

func (c *Connector) Startup() (err error)

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

func (c *Connector) Unsubscribe(method string, path string) error

Unsubscribe removes the handler for the specified path

func (*Connector) Version

func (c *Connector) Version() int

Version is the sequential version number of the microservice.

type HTTPHandler

type HTTPHandler = sub.HTTPHandler

HTTPHandler extends the standard http.Handler to also return an error

Jump to

Keyboard shortcuts

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