0.3.5 • Published 6 years ago

@usvc/boilerplate v0.3.5

Weekly downloads
-
License
MIT
Repository
github
Last release
6 years ago

@usvc/boilerplate

Quick, opinionated, Express-based boilerplate for microservices written in Node.

What's Included

  • Metrics monitoring with Prometheus
  • Contextual logging with Winston
  • Logs centralisation with FluentD (td-agent)
  • Distributed tracing with Zipkin
  • Tracable request object with Zipkin
  • Zipkin-instrumented Request object
  • Bootstrapped HTTP server with Express
  • Liveness and readiness health checks
  • Cross Origin Resource Sharing (CORS) support
  • Content Security Policy (CSP) support

TL;DR

Usage

Install this boilerplate with:

npm i @usvc/boilerplate;
# or via yarn
yarn add @usvc/boilerplate;

Basic Usage w/ No Configuration

import {Boilerplate} from '@usvc/boilerplate';

Boilerplate.init();

const {
  app, // bootstrapped Express application
  logger, // contextual logger
  request, // request object
} = Boilerplate;

const server = app.listen(3000);

server.on('listening', () => {
  logger.info('Server listening on http://localhost:3000');
});

Advanced Usage w/ Full Configurations

import {Boilerplate} from '@usvc/boilerplate';

Boilerplate.init({
  appAccessLoggingBypassUrls: [],
  appCookieSessionName: 'usvcbp',
  appCorsWhitelist: [],
  appCspChildSrc: ['"self"'],
  appCspConnectSrc: ['"self"'],
  appCspDefaultSrc: ['"self"'],
  appCspFontSrc: ['"self"'],
  appCspFrameSrc: ['"self"'],
  appCspImgSrc: ['"self"'],
  appCspMediaSrc: ['"self"'],
  appCspObjectSrc: ['"none"'],
  appCspReportUri: '/csp-report',
  appCspScriptSrc: ['"self"'],
  appCspStyleSrc: ['"self"'],
  appEnableCors: true,
  appEnableCsp: true,
  appJsonBodyContentType: '*/json',
  appJsonBodySizeLimit: '2mb',
  appLivenessCheckEndpoint: '/healthz',
  appLivenessChecks: {},
  appMetricsEndpoint: '/metrics',
  appReadinessCheckEndpoint: '/readyz',
  appReadinessChecks: {},
  appUrlEncodedBodyContentType: '*/x-www-form-urlencoded',
  appUrlEncodedBodySizeLimit: '2mb',
  logger: 'winston',
  logsCollator: 'fluentd',
  fluentdHost: 'localhost',
  fluentdPort: '24224',
  requester: 'request',
  serviceId: 'usvcbp',
  tracer: 'zipkin',
  winstonFormats: [],
  winstonLevel: 'silly',
  winstonTransports: [],
  zipkinHeaders: {},
  zipkinHost: 'localhost',
  zipkinPort: '9411',
  zipkinSampleFrequency: 1.0,
  zipkinScheme: 'http',
});

Examples

Proof-of-Concept

Requires docker and docker-compose to be available on your machine

Clone this repository, install dependencies and run:

npm run eg:poc;

To shut it down, run:

npm run eg:poc:down;

Configuration

The boilerplate is initialized through the .init() function. It accepts configuration options from both the environment as well as parameters. Note that environment configuration will always take precendence over parameter configuration, this is so that parameterised code can be written for development, but can also be modified for a production environment via environment.

Configuring Boilerplate

Config ParameterEnvironment VariableDefault ValueDescription
loggerN/A"winston"Decides which logger to use
logsCollatorN/A"fluentd"Decides which logs collator to use
requesterN/A"request"Decides which request module to use. "fetch" is also available
tracerN/A"zipkin"Decides which tracer to use
serviceIdSERVICE_ID"usvcbp"The ID of the service instance we're spinning up

Configuring Application

Config ParameterEnvironment VariableDefault ValueDescription
appAccessLoggingBypassUrlsN/A[]List of URLs to ignore when performing access logging
appCookieSessionNameN/A"usvcbp"Cookie session name
appCorsWhitelistN/A[]URL whitelist for Cross Origin Resource Sharing (CORS)
appCspChildSrcN/A['"self"']Defines the child-src property in the Content Security Policy
appCspConnectSrcN/A['"self"']Defines the connect-src property in the Content Security Policy
appCspDefaultSrcN/A['"self"']Defines the default-src property in the Content Security Policy
appCspFontSrcN/A['"self"']Defines the font-src property in the Content Security Policy
appCspFrameSrcN/A['"self"']Defines the frame-src property in the Content Security Policy
appCspImgSrcN/A['"self"']Defines the img-src property in the Content Security Policy
appCspMediaSrcN/A['"self"']Defines the media-src property in the Content Security Policy
appCspObjectSrcN/A['"none"']Defines the object-src property in the Content Security Policy
appCspReportUriN/A/csp-reportDefines the report-uri property in the Content Security Policy
appCspScriptSrcN/A['"self"']Defines the script-src property in the Content Security Policy
appCspStyleSrcN/A['"self"']Defines the style-src property in the Content Security Policy
appEnableCorsN/AtrueIf set to false, disables Cross Origin Resource Sharing (CORS) (useful for server-side-only services)
appEnableCspN/AtrueIf set to false, disables Content Security Policy (CSP) from being sent (useful for server-side-only services)
appJsonBodyContentTypeN/A"*/json"Defines the Content-Type HTTP header value before the body value is parsed as JSON
appJsonBodySizeLimitN/A"2mb"Defines the maximum size limit of the JSON body when Content-Type HTTP header is set to the value of :appJsonBodyContentType
appLivenessChecksN/A{}A key-value mapping where the key is a string identifying the check, and the value is a function returning a Promise that resolves to a Health object
appLivenessCheckEndpointLIVENESS_CHECK_ENDPOINT"/healthz"Endpoint from which a container orchestrator can do a HTTP GET to check the service instance's liveness
appMetricsEndpointMETRICS_ENDPOINT"/metrics"Endpoint from which a metrics scraper can use to access the metrics of the service instance
appReadinessChecksN/A{}A key-value mapping where the key is a string identifying the check, and the value is a function returning a Promise that resolves to a Health object
appReadinessCheckEndpointREADINESS_CHECK_ENDPOINT"/readyz"Endpoint from which a container orchestrator can do a HTTP GET to check the service instance's readiness for requests
appUrlEncodedBodyContentTypeN/A"*/x-www-form-urlencoded"Defines the Content-Type HTTP header value before the body value is parsed as JSON
appUrlEncodedBodySizeLimitN/A"2mb"Defines the maximum size limit of the JSON body when Content-Type HTTP header is set to the value of :appUrlEncodedBodyContentType

Configuring Logs Collator

Config ParameterEnvironment VariableDefault ValueDescription
fluentdHostFLUENTD_HOST"localhost"Host of the FluentD service instance
fluentdPortFLUENTD_PORT"24224"Port of the FluentD service instance

Configuring Logger

Config ParameterEnvironment VariableDefault ValueDescription
winstonFormatsN/A[]Array of unwrapped Winston formats
winstonLevelN/A"silly"Minimum level to log
winstonTransportsN/A[]Array of additional Winston transports to use

Configuring Tracer

Config ParameterEnvironment VariableDefault ValueDescription
zipkinHeadersN/A{}Additional headers to add to the Zipkin API call
zipkinHostZIPKIN_HOST"localhost"Host of the Zipkin instance
zipkinPortZIPKIN_PORT"9411"Port of the Zipkin instance
zipkinSampleFrequencyZIPKIN_SAMPLE_FREQUENCY1.0Frequency of request sampling
zipkinSchemeZIPKIN_SCHEME"http"Protocol of the Zipkin instance

Types

Type: Health

interface Health {
  data?: object;
  message?: string;
  status: boolean;
}

Development Lifecycle

TODO

License

This package is licensed under the MIT license. See the LICENSE file for details.

Cheers