Note
Segment has paused maintenance on this project, but may return it to an active status in the future. Issues and pull requests from external contributors are not being considered, although internal contributions may appear from time to time. The project remains available under its open source license for anyone to use.
Fault tolerant jsonrpc with retries and timeouts
This module provides fault-tolerance on top of @segment/jsonrpc2.
Retries are off by default and should only be used for idempotent RPC methods.
$ npm install --save @segment/fault-tolerant-jsonrpc
const jsonrpc = require('@segment/fault-tolerant-jsonrpc')
// This is an example service client,
// implemented using fault-tolerant-jsonrpc
function Client (addr, opts) {
opts = opts || {}
// We should only allow retries for idempotent requests
const idempotentDefaults = Object.assign({
retryOptions: { retries: 3 },
// Custom retry function
// This allows the clients to decide what sorts of errors
// are worth retrying
shouldRetry: function(originalError) {
if (originalError.code === "SYSTEM_ERROR") {
return true
}
return false
},
timeout: 500,
totalTimeout: 2000
}, opts.idempotentDefaults)
const rpc = jsonrpc(addr, opts.globalDefaults)
return {
getAll () {
return rpc.call('Items.GetAll', null, idempotentDefaults)
},
getOne (id) {
return rpc.call('Items.GetOne', id, idempotentDefaults)
},
createOne (data) {
// Intentionally not using retries since this
// RPC method _could_ result in duplicate writes
return rpc.call('Items.CreateOne', data)
}
}
}
const itemService = Client('http://localhost:3000')
itemService
.getAll()
.then(console.log)
.catch(console.log)
itemService
.getOne('item-1')
.then(console.log)
.catch(console.log)
itemService
.createOne({ some: 'thing' })
.then(console.log)
.catch(console.log)
Returns a jsonrpc client where client.call
supports retries and timeouts. This
package exposes the same API as jsonrpc2
with the addition of the following options:
options.retryOptions
is passed to thep-retry
module.options.totalTimeout
is passed to thep-timeout
module.
Same API as the above but global options can be overwritten on a per request basis.