Class: AMQPBackend

Implementation of IBackend

The AMQP Backend is used to communicate with your other backend services using RPC over a message queue

new AMQPBackend(amqpURI, replyExchange, rpcQueue)

Arguments

  1. amqpURI (string): URI used to connect to the message queue
  2. replyExchange (string): Name of the exchange to listen for replies on
  3. rpcQueue (string): Queue to send requests on

Example

var b = new AMQPBackend("amqp://SOME_IP:2345", "cerberusResponse", "rpcQueue")

Interface: IBackend

Backend Interface

enable(sendResponse)

Called by Cerberus.addFrontend when this backend is enabled

Arguments

  1. sendResponse (SendResponse)

Returns

  1. (void)

handleConnection(connection)

Optional function that is called when a frontend receives a new connection

Arguments

  1. connection (CerberusConnection)

Returns

  1. (void)

handleRequest(request)

Handle a request and send a response using sendResponse

Arguments

  1. request (CerberusRequest)

Returns

  1. (void)

Class: HTTPBackend

Implementation of IBackend

The HTTP Backend is used to communicate with your other backend services via HTTP requests

new HTTPBackend(generateRequestOptions)

Arguments

  1. generateRequestOptions: generate options for the request node library given a CerberusRequest

Example

new HTTPBackend((req) => ({
  url: "https://some-internal-host:4032",
  method: "POST",
  json: {
      user: req.connection.userID,
      data: req.data.color,
  },
}))

Class: ZMQBackend

Implementation of IBackend

The ZMQ Backend is used to communicate with your other backend services using ZeroMQ

new ZMQBackend(zmqPushURI, zmqSubURI)

Arguments

  1. zmqPushURI (string): URI to connect to a ZMQ push socket
  2. zmqSubURI (string): URI to connect to a ZMQ sub socket

Example

new ZMQBackend("tcp://SOME_IP:2345", "tcp://SOME_IP:2346")

Enum: EventType

Class: Cerberus

The main Cerberus class

new Cerberus()

Arguments

Example

var c = new Cerberus()

addFrontend(frontend)

Adds a frontend

Arguments

  1. frontend (IFrontend)

Returns

  1. (void)

Example

var c = new Cerberus()

// Add a Websocket frontend
c.addFrontend(new WSFrontend(8080))

// Add a HTTP frontend
// `location.query` is what we want to store
c.addFrontend(new HTTPFrontend(8081, false, (httpReq, location) => location.query))

addPlugin(plugin, eventType)

Adds a plugin. If a plugin contains multiple handlers, you will need to add the plugin once for every handler. For example, if a plugin needs to run during both requests and responses, you will need to add it once to the request chain and once to the response chain. Note: The order in which plugins are added is the order in which they are executed.

Arguments

  1. plugin (IPlugin)
  2. eventType ("connection" | "request" | "response")

Returns

  1. (void)

Example

var latencyMeasurement = ... // Some plugin
c.addPlugin(latencyMeasurement, "request")

// Add other plugins

c.addPlugin(latencyMeasurement, "response")

on(type, middleware)

Run an EventHandler when an event fires

Arguments

  1. type ("connection" | "request" | "response")
  2. middleware (EventHandler)

Returns

  1. (void)

Example

var c = new Cerberus();
c.on('request', function(request) {
    // Do something
})

c.on('response', function(response) {
    // Do something
})

c.on('connection', function(connection) {
    // Do something
})

setBackend(backend)

Sets the backend

Arguments

  1. backend (IBackend)

Returns

  1. (void)

Interface: IFrontend

Frontend Interface

enable(createConnection, sendRequest)

Called by Cerberus.addFrontend when this frontend is enabled

Arguments

  1. createConnection (CreateConnection)
  2. sendRequest (SendRequest)

Returns

  1. (void)

Class: HTTPFrontend

Implementation of IFrontend

HTTPFrontend starts a HTTP server on a specified port

new HTTPFrontend(port, allowForwadedFor, getDataFromRequest)

Arguments

  1. port (number): The port to run the server on
  2. allowForwadedFor (boolean): Whether or not to look at IP addresses in the x-forwarded-for header
  3. getDataFromRequest: A function that returns data to store in a CerberusRequest given a HTTP request

Example

var c = new Cerberus()

// Add a HTTP frontend
// `location.query` is what we want to store
c.addFrontend(new HTTPFrontend(8081, false, (httpReq, location) => location.query))

Class: WSFrontend

Implementation of IFrontend

WSFrontend starts a Websocket server on a specified port

new WSFrontend(port, allowForwadedFor)

Arguments

  1. port (number): The port to run the server on
  2. allowForwadedFor (boolean): Whether or not to look at IP addresses in the x-forwarded-for header

Example

var c = new Cerberus()

// Add a Websocket frontend
c.addFrontend(new WSFrontend(8080, false))

Class: LatencyLogger

Implementation of IPlugin

A plugin that logs the time between a request and the corresponding response.

new LatencyLogger(maxNumConcurrentRequestsToTrack, maxRequestAge, getRequestMethodName)

Arguments

  1. maxNumConcurrentRequestsToTrack (number): The max number of requests that can be tracked at a time
  2. maxRequestAge (number): The longest request that can be tracked (in ms)
  3. getRequestMethodName: Function to get the name to be logged given a CerberusRequest

Example

new LatencyLogger(500, 1000, (req) => req.data.method)

Class: HMACAuthenticator

Implementation of IPlugin

A plugin that validates a HMAC signed token when a new connection is established. This is compatible with signed cookies from Express (https://github.com/expressjs/cookie-parser) When the authenticator receives a CerberusRequest object, it sets the userID field in the request if the token is valid

new HMACAuthenticator(key, queryParamName, shouldErrorOnInvalidToken)

Arguments

  1. key (string): The key that the token should be signed with
  2. queryParamName (string): The name of the query parameter where the token is stored
  3. shouldErrorOnInvalidToken (boolean): Whether or not connections with invalid tokens should throw an error be closed. If this is false, unsigned requests won't have a valid userID

Example

var c = new Cerberus()

c.addPlugin(new HMACAuthenticator("SUPER_SECRET_HMAC_KEY", "token", false))

Class: LRUCache

Implementation of IPlugin

A plugin to cache specific requests and responses in an in-memory LRU cache.

new LRUCache(cacheParams, getCacheKey)

Arguments

  1. cacheParams (object): Params to pass into lru-cache
  2. getCacheKey: A function to get cache keys given a request. Can return null if you do not want to cache the response to a given request

Example

// Use the location as the cache key
var cachePlugin = new LRUCache({max: 5000, maxAge: 60 * 60 * 1000}, (request) => request.data.location)

// Build request pipeline
c.addPlugin(cachePlugin, "request")

// Add other stuff

// Build response pipeline
c.addPlugin(cachePlugin, "response")

Class: RedisCache

Implementation of IPlugin

A plugin to cache specific requests and responses in Redis. This is useful for sharing a cache between multiple Cerberus instances.

new RedisCache(hostname, port, redisCachePrefix, getCacheKey)

Arguments

  1. hostname (string): Redis hostname or IP address
  2. port (number): Redis port
  3. redisCachePrefix (string): Prefix to add to cache keys returned by getCacheKey
  4. getCacheKey: A function to get cache keys given a request. Can return null if you do not want to cache the response to a given request

Example

// Use the location as the cache key
var cachePlugin = new RedisCache("127.0.0.1", 6379, "", (request) => request.data.location)

// Build request pipeline
c.addPlugin(cachePlugin, "request")

// Add other stuff

// Build response pipeline
c.addPlugin(cachePlugin, "response")

Interface: IPlugin

Note: at least one of the handle methods in this interface must be implemented Each handler can return one of the following:

Connection and request handlers can also return these:

handleConnection(connection)

Optional function that is called when Cerberus receives a new connection

Arguments

  1. connection (CerberusConnection)

Returns

  1. (string | true | false | void | CerberusConnection | Promise<string | true | false | void | CerberusConnection>)

handleRequest(request)

Optional function to handle requests

Arguments

  1. request (CerberusRequest)

Returns

  1. (string | true | false | void | CerberusRequest | Promise<string | true | false | void | CerberusRequest>)

handleResponse(response)

Optional function to handle responses

Arguments

  1. response (CerberusResponse)

Returns

  1. (true | false | void | CerberusResponse | Promise<true | false | void | CerberusResponse>)

setResponseSender(sendResponse)

If a plugin ever wants to send a response, it can get a function to do so by implementing this function. This is useful in caching plugins

Arguments

  1. sendResponse (SendResponse)

Returns

  1. (void)

Class: RateLimit

Implementation of IPlugin

A configurable rate limiter for requests based on IP address.

new RateLimit(numRequests, timeframe, shouldRateLimit)

Arguments

  1. numRequests (any): The number of requests allowed in timeframe
  2. timeframe (any): The timeframe in ms for the rate limit
  3. shouldRateLimit: A function that takes a CerberusRequest and returns whether or not to count the request against the rate limit.

Example

var c = new Cerberus()

// Limit all calls to 10 requests per second per IP address
c.addPlugin(new RateLimit(10, 1000, () => true))

Class: CerberusConnection

CerberusConnection is a standardized representation of a connection to Cerberus

new CerberusConnection(sendFn, closeFn, headers, location, ipAddr)

Arguments

  1. sendFn (ConnectionSendFunction): A function that sends data on the connection
  2. closeFn (ConnectionCloseFunction): A function that closes the connection
  3. headers (object): Headers
  4. location (Url): Output of uri.parse
  5. ipAddr (string): Remote IP address

Class: CerberusRequest

Request is a standardized representation of a request to Cerberus

new CerberusRequest(connection, data)

Arguments

  1. connection (CerberusConnection): The connection that this request originated from
  2. data (object): Data for this request

Class: CerberusResponse

Response is a standardized representation of a response in Cerberus

new CerberusResponse(connection, data, requestID)

Arguments

  1. connection (CerberusConnection): The connection that this response should be sent on
  2. data (object): Data for this response. Should be able to stringify using JSON.stringify
  3. requestID (RequestID): The RequestID for the request corresponding to this response