JSPM

  • Created
  • Published
  • Downloads 1735
  • Score
    100M100P100Q107254F
  • License MIT

Fault tolerant, balanced, full featured HTTP client for modern web applications and distributed systems

Package Exports

  • resilient

This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (resilient) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

Readme

resilient.js Build Status Stories in Ready Code Climate Gitter chat

A browser and node.js fault tolerant, balanced, configurable and full featured HTTP client for distributed and reactive systems

For more information about the resilient and how it works, see the project site

Note: resilient is still a beta preview version

Features

  • Fault tolerant, transparent fallback
  • Client-side based balancer using a simple best availability algorithm
  • Smart balancer logic based on server stats (lantency, errors, requests...)
  • Configurable balancer policy and weight
  • Servers discovering based on the resilient high-level protocol
  • Server-side dynamic client configuration support (experimental)
  • Built-in support for servers caching to improve reliability
  • Parallel servers discovering for a faster
  • Highly configurable (timeout, retry times, cache, implicit delay...)
  • Cross-engine (browsers and node.js)
  • Full HTTP features support (it uses request and lil-http)
  • Lightweight library (just 7KB gzipped)

Installation

Node.js

npm install resilient

Browser

Via Bower

bower install resilient

Via Component

component install resilient-http/resilient.js

Or loading the script remotely

<script src="//cdn.rawgit.com/resilient-http/resilient.js/0.1.0-beta.2/resilient.js"></script>

Environments

It runs properly in any ES5 compliant engine

  • Node.js >= 0.6
  • Chrome >= 5
  • Firefox >= 3
  • Safari >= 5
  • Opera >= 10
  • IE >= 9

How it works?

Basic usage

If require is available, you must use it to fetch the module. Otherwise it will be available as global exposed as resilient

var Resilient = require('resilient')

Static servers

Define your server pool

var servers = [
  'http://api1.server.com',
  'http://api2.server.com',
  'http://api3.server.com'
]

Create a new client and set the servers

var client = Resilient({ service: { basePath: '/api/1.0' }})
client.setServers(servers)

Perform the request (the best available server will be use)

client.get('/users', function (err, res) {
  // ...
})

Dynamic servers discovering

Define your discovering servers pool

var servers = [
  'http://discover1.server.com',
  'http://discover2.server.com',
  'http://discover3.server.com'
]

Create a new client and set the discovering servers

var client = Resilient({ service: { basePath: '/api/1.0' }})
client.discoveryServers(servers)

Perform the request (the best available server will be use)

client.get('/users', function (err, res) {
  // ...
})

API

resilient([ options ])

Creates a new resilient client with a custom config

Options

The options object has three different blocks and levels of configuration

Service

There are specific config options for the servers of the client service. Resilient is a resource-oriented HTTP client, which could be ideal for RESTful Web services

  • servers array - A list of valid URIs of servers to reach for the given service. Default null

  • refresh number - Servers list expiration time to live in miliseconds. Default 60 seconds. Once the time expired, will try to discovery it from discovery servers

  • retry number - Number of times to retry if all requests failed. Default 0

  • retryWait number - Number of milisenconds to wait before retry. Default to 1000

  • path string - Server request path as part of the final URL

  • data mixed - Payload data to send as body request

  • headers object - Map of strings representing HTTP headers to send to the server

  • timeout number - Request maximum timeout in miliseconds before to abort it. Default to 10 seconds

  • auth object - Authentication credentials to the server. Object must have the user and password properties

  • async boolean - Set to false if the request must be performed as synchronous operation (not recommended, browser only)

  • withCredentials boolean - Whether to set the withCredentials flag on the XHR object. See [MDN][withcredentials] for more information

  • method string - Request HTTP method. Default to GET

  • responseType string - Define how to handle the response data. Allowed values are: text, arraybuffer, blob or document

  • proxy string - URI for the HTTP proxy to use (node.js only)

See aditional HTTP options for node.js here

Balancer
  • enable boolean - Enable/disable the smart client balancer. Default true
  • weight object - Balacer point percentage weight for server scoring policy. Default to 25 (response), 25 (latency) and 50 (errors)
Discovery

Specific configuration for discovery servers requests, behavior and logic

  • servers array - A list of valid URIs of endpoints to use as discovery servers. Default null
  • cache boolean - Enable/disable discovery servers cache in case of global fallback. Default true
  • path string - Server request path as part of the final URL
  • expires number - Discovery servers list expiration time to live in miliseconds. Default 180 seconds
  • timeout number - Server discovery network timeout in miliseconds. Default 2 seconds
  • cache boolean - Enable/disable discovery servers cache in case of fallback. Default true
  • auth object - Authentication credentials required for the discovery server. Object must have the user and password properties
  • headers object - Map of strings representing HTTP headers to send to the discovery server
  • method string - Request HTTP method. Default to GET
  • data mixed - Optional data to send as payload to discovery servers. Default null

Response object

Browser
  • data mixed - Body response. If the MIME type is JSON-compatible, it will be transparently parsed
  • status number - HTTP response status code
  • headers object - Response headers
  • xhr object - Original XHR instance
  • error mixed - Error info, usually an Error instance (in case that an error happens)
Node.js

See http.IncomingMessage

Error object

It will be an Error instance with the following members

  • message string - Human readable error message
  • status number - Internal error code or HTTP status
  • code number - Optional error code (node.js only)
  • stack string - Optional stack error trace
  • request object - Original response object (node.js only). Optional
  • error Error - Original throwed error object (node.js only). Optional
  • xhr ``
Built-in error codes
  • 1000 - All requests failed. No servers available
  • 1001 - Cannot update discovery servers. Empty or invalid response body
  • 1002 - Missing discovery servers. Cannot resolve the server
  • 1003 - Cannot resolve servers. Missing data
  • 1004 - Discovery server response is invalid or empty
  • 1005 - Missing discovery servers during retry process
  • 1006 - Internal state error (usually by an unexpected exception)

resilient#send(path, options, callback)

resilient#get(path, options, callback)

resilient#post(path, options, callback)

resilient#put(path, options, callback)

resilient#del(path, options, callback)

resilient#patch(path, options, callback)

resilient#head(path, options, callback)

resilient#setOptions(options)

resilient#getOptions()

resilient#setServiceOptions(options)

resilient#setDiscoveryOptions(options)

resilient#getHttpOptions(type)

resilient#getHttpOptions(type)

resilient#getServers(type)

resilient#discoveryServers([ servers ])

resilient#discoverServers(callback)

resilient#updateServers([ callback ])

resilient#flushCache()

resilient#client()

Return: Client

resilient#areServersUpdated()

resilient#balancer()

resilient.VERSION

Type: string

Current library version

resilient.CLIENT_VERSION

Type: string

Current HTTP client library version

resilient.defaults

Type: object

Default config options

resilient.Servers(list)

Create a new servers store

resilient.Options(options)

Create a new options store

resilient.Client(resilient)

Creates a new resilient HTTP public API client

Useful to provide encapsulation to the resilient API and expose only the HTTP client (the common interface the developers want to consum)

resilient.request(options [, cb])

Use the plain HTTP client

Contributing

Wanna help? Cool! It will be appreciated :)

You must add new test cases for any new feature or refactor you do, always following the same design/code patterns that already exist

Development

Only node.js is required for development

Clone the repository

$ git clone https://github.com/resilient-http/resilient.js.git && cd resilient.js

Install development dependencies

$ npm install

Install browser dependencies

$ bower install

Generate browser bundle source

$ make browser

Run tests (in a headless browser)

$ make test

Run tests (in real browsers)

$ make karma

License

MIT © Tomas Aparicio and contributors