Categorygithub.com/savannahghi/serverutils
modulepackage
0.0.9
Repository: https://github.com/savannahghi/serverutils.git
Documentation: pkg.go.dev

# README

Build Status Maintained Linting and Tests Coverage Status

Server Utils Library

serverutils are utilities used by several backend services. These includes starting up and running the server.

Installing it

serverutils is compatible with modern Go releases in module mode, with Go installed:

go get -u github.com/savannahghi/serverutils

will resolve and add the package to the current development module, along with its dependencies.

Alternatively the same can be achieved if you use import in a package:

import "github.com/savannahghi/serverutils"

and run go get without parameters.

The package name is serverutils

Developing

The default branch library is main

We try to follow semantic versioning ( https://semver.org/ ). For that reason, every major, minor and point release should be tagged.

git tag -m "v0.0.1" "v0.0.1"
git push --tags

Continuous integration tests must pass on Travis CI. Our coverage threshold is 90% i.e you must keep coverage above 90%.

Environment variables

In order to run tests, you need to have an env.sh file similar to this one:

# Application settings
export DEBUG=true
export IS_RUNNING_TESTS=true
export SENTRY_DSN=<a Sentry Data Source Name>
export GOOGLE_CLOUD_PROJECT="Google Cloud project id"

This file must not be committed to version control.

It is important to export the environment variables. If they are not exported, they will not be visible to child processes e.g go test ./....

These environment variables should also be set up on Travis CI environment variable section.

Contributing

I would like to cover the entire GitHub API and contributions are of course always welcome. The calling pattern is pretty well established, so adding new methods is relatively straightforward. See CONTRIBUTING.md for details.

Versioning

In general, serverutils follows semver as closely as we can for tagging releases of the package. For self-contained libraries, the application of semantic versioning is relatively straightforward and generally understood. We've adopted the following versioning policy:

  • We increment the major version with any incompatible change to non-preview functionality, including changes to the exported Go API surface or behavior of the API.
  • We increment the minor version with any backwards-compatible changes to functionality, as well as any changes to preview functionality in the GitHub API. GitHub makes no guarantee about the stability of preview functionality, so neither do we consider it a stable part of the go-github API.
  • We increment the patch version with any backwards-compatible bug fixes.

License

This library is distributed under the MIT license found in the LICENSE file.

# Functions

BoolEnv gets and parses a boolean environment variable.
CloseStackDriverErrorClient closes a StackDriver error client and logs any arising error.
CloseStackDriverLoggingClient closes a StackDriver logging client and logs any arising error.
ConvertStringToInt converts a supplied string value to an integer.
CustomHTTPRequestMetricsMiddleware is used to implement custom metrics for our http requests The custom middleware used to collect any custom http request stats It will also be used to capture distributed trace requests and propagate them through context.
DecodeJSONToTargetStruct maps JSON from a HTTP request to a struct.
EnableStatsAndTraceExporters a wrapper for initializing metrics exporters TODO:Look into improvements.
ErrorMap turns the supplied error into a map with "error" as the key.
GenerateLatencyBounds is used in generating latency bounds The arguments provided should be in millisecond format e.g 1s == 1000ms interval will be used as an increment value [>=0ms, >=100ms, >=200ms, >=300ms,...., >=1000ms].
GetEnvVar retrieves the environment variable with the supplied name and fails if it is not able to do so.
GetRunningEnvironment returns the environment where the service is running.
HealthStatusCheck endpoint to check if the server is working.
InitOtelSDK returns an OpenTelemetry TracerProvider configured to use the Jaeger exporter for sending traces/spans.
IsDebug returns true if debug has been turned on in the environment.
IsRunningTests returns true if debug has been turned on in the environment.
ListenAddress determines what port to listen on and falls back to a default port if the environment does not supply a port.
LogStartupError is used to e.g log fatal startup errors.
MetricsCollectorService returns name of service suffixed by it's running environment this helps identify metrics from different services at the backend/metrics viewer.
MustGetEnvVar returns the value of the environment variable with the indicated name or panics.
NewErrorResponseWriter returns an initialized ErrorResponseWriter.
NewImportPlugin initializes a new import plugin early sources are the source files to add before loading the service schema late sources are the source files to add after loading the service schema generate is a flag to determine whether to generate schema files or not path represents the path to store the imported schema files the folder name is `exported`.
NewMetricsResponseWriter new http.ResponseWriter wrapper.
RecordGraphqlResolverMetrics records the metrics for a specific graphql resolver It should be deferred until the execution of the resolver function is completed.
RecordHTTPStats adds tags and records the metrics for a request.
RequestDebugMiddleware dumps the incoming HTTP request to the log for inspection.
Sentry initializes Sentry, for error reporting.
StackDriver initializes StackDriver logging, error reporting, profiling etc.
StartTestServer starts up test server.
WriteJSONResponse writes the content supplied via the `source` parameter to the supplied http ResponseWriter.

# Constants

AppName is the name of "this server".
AppVersion is the app version (used for StackDriver error reporting).
DebugEnvVarName is used to determine if we should print extended tracing / logging (debugging aids) to the console.
DefaultPort is the default port at which the server listens if the port environment variable is not set.
DemoEnv runs the service under demo.
DSNEnvVarName is the Sentry reporting config.
Environment points to where this service is running e.g staging, testing, prod.
GoogleCloudProjectIDEnvVarName is used to determine the ID of the GCP project e.g for setting up StackDriver client.
IsRunningTestsEnvVarName is used to determine if we are running in a test environment.
PortEnvVarName is the name of the environment variable that defines the server port.
ProdEnv runs the service under production.
Resolver status values.
Resolver status values.
StagingEnv runs the service under staging.
TestingEnv runs the service under testing.
TraceSampleRateEnvVarName indicates the percentage of transactions to be captured when doing performance monitoring.

# Variables

DefaultServiceViews are the default/common server views provided by base package The views can be used by the various services.
Server HTTP measures used to record metrics.
Server HTTP measures used to record metrics.
Server HTTP measures used to record metrics.
Method is the HTTP method of the request.
Path is the URL path (not including query string) in the request.
Views for the collected metrics i.e how they are exported to the various backends.
StatusCode is the numeric HTTP response status code.
1 min in intervals of 200ms.
Error is the error recorded if an error occurs.
Resolver is the Graphql resolver used when making a GraphQl request.
ResolverStatus is used to tag whether passed or failed it is either pass/fail...make constants.
Views for the collected metrics i.e how they are exported to the various backends.
Views for the collected metrics i.e how they are exported to the various backends.

# Structs

ErrorResponseWriter is a http.ResponseWriter that always errors on attempted writes.
ImportPlugin is a gqlgen plugin that hooks into the gqlgen code generation lifecycle and adds schema definitions from an imported library.
MetricsResponseWriter implements the http.ResponseWriter Interface it is a wrapper of http.ResponseWriter and enables obtaining measures.

# Type aliases

PrepareServer is the signature of a function that Knows how to prepare & initialise the server.