1
0
mirror of https://github.com/bigchaindb/js-bigchaindb-driver.git synced 2024-06-29 00:57:44 +02:00
js-bigchaindb-driver/src/transport.js

66 lines
2.0 KiB
JavaScript
Raw Normal View History

2018-08-23 17:14:59 +02:00
// Copyright BigchainDB GmbH and BigchainDB contributors
// SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0)
// Code is Apache-2.0 and docs are CC-BY-4.0
2018-08-22 10:10:09 +02:00
import Request from './request'
export default class Transport {
constructor(nodes, headers, timeout) {
this.connectionPool = []
this.timeout = timeout
nodes.forEach(node => {
this.connectionPool.push(new Request(node, headers))
})
}
// Select the connection with the earliest backoff time
pickConnection() {
if (this.connectionPool.length === 1) {
return this.connectionPool[0]
}
let connection = this.connectionPool[0]
2018-08-23 17:14:59 +02:00
2018-08-22 10:10:09 +02:00
this.connectionPool.forEach(conn => {
// 0 the lowest value is the time for Thu Jan 01 1970 01:00:00 GMT+0100 (CET)
conn.backoffTime = conn.backoffTime ? conn.backoffTime : 0
connection = (conn.backoffTime < connection.backoffTime) ? conn : connection
})
return connection
}
async forwardRequest(path, headers) {
2018-08-23 17:14:59 +02:00
let response
let connection
2018-08-22 10:10:09 +02:00
while (!this.timeout || this.timeout > 0) {
2018-08-23 17:14:59 +02:00
connection = this.pickConnection()
2018-08-22 10:10:09 +02:00
// Date in milliseconds
const startTime = Date.now()
try {
2018-08-23 17:14:59 +02:00
// eslint-disable-next-line no-await-in-loop
response = await connection.request(
2018-08-22 10:10:09 +02:00
path,
headers,
this.timeout
)
const elapsed = Date.now() - startTime
2018-08-23 17:14:59 +02:00
if (connection.backoffTime) {
this.timeout += elapsed
} else {
return response
}
if (connection.retries > 3) {
throw connection.connectionError
2018-08-22 10:10:09 +02:00
}
2018-08-23 17:14:59 +02:00
} catch (err) {
throw err
2018-08-22 10:10:09 +02:00
}
}
2018-08-23 17:14:59 +02:00
const errorObject = {
message: 'Timeout error',
}
throw errorObject
2018-08-22 10:10:09 +02:00
}
}