Fix up various flow issues.

This commit is contained in:
Josh Harvey 2017-09-12 00:00:24 +03:00
parent 08bd7da33f
commit 0d8a8547f5
8 changed files with 60 additions and 40 deletions

View file

@ -8,6 +8,7 @@ const logger = require('./logger')
const plugins = require('./plugins')
const helper = require('./cash-out-helper')
const socket = require('./socket-client')
const E = require('./error')
module.exports = {
post,
@ -17,8 +18,8 @@ module.exports = {
cancel
}
const UPDATEABLE_FIELDS = ['txHash', 'status', 'dispense', 'dispenseConfirmed',
'notified', 'redeem', 'phone', 'error', 'swept']
const UPDATEABLE_FIELDS = ['txHash', 'txVersion', 'status', 'dispense', 'dispenseConfirmed',
'notified', 'redeem', 'phone', 'error', 'swept', 'publishedAt', 'confirmedAt']
const STALE_INCOMING_TX_AGE = T.week
const STALE_LIVE_INCOMING_TX_AGE = 10 * T.minutes
@ -37,7 +38,11 @@ function httpError (msg, code) {
return err
}
function post (tx, pi) {
function selfPost (tx, pi) {
return post(tx, pi, false)
}
function post (tx, pi, fromClient = true) {
const TransactionMode = pgp.txMode.TransactionMode
const isolationLevel = pgp.txMode.isolationLevel
const tmSRD = new TransactionMode({tiLevel: isolationLevel.serializable})
@ -48,6 +53,9 @@ function post (tx, pi) {
return t.oneOrNone(sql, [tx.id])
.then(toObj)
.then(oldTx => {
const isStale = fromClient && oldTx && (oldTx.txVersion >= tx.txVersion)
if (isStale) throw new E.StaleTxError('Stale tx')
return preProcess(oldTx, tx, pi)
.then(preProcessedTx => upsert(oldTx, preProcessedTx))
})
@ -280,8 +288,33 @@ function postProcess (txVector, pi) {
return Promise.resolve({})
}
function isPublished (status) {
return _.includes(status, ['published', 'rejected', 'authorized', 'instant', 'confirmed'])
}
function isConfirmed (status) {
return status === 'confirmed'
}
function updateStatus (oldTx, newTx) {
return _.set('status', ratchetStatus(oldTx.status, newTx.status), newTx)
const oldStatus = oldTx.status
const newStatus = ratchetStatus(oldStatus, newTx.status)
const publishedAt = !oldTx.publishedAt && isPublished(newStatus)
? 'now()^'
: undefined
const confirmedAt = !oldTx.confirmedAt && isConfirmed(newStatus)
? 'now()^'
: undefined
const updateRec = {
publishedAt,
confirmedAt,
status: newStatus
}
return _.merge(newTx, updateRec)
}
function ratchetStatus (oldStatus, newStatus) {
@ -311,8 +344,8 @@ function processTxStatus (tx, settings) {
const pi = plugins(settings, tx.deviceId)
return pi.getStatus(tx)
.then(res => _.set('status', res.status, tx))
.then(_tx => post(_tx, pi))
.then(res => _.assign(tx, {status: res.status}))
.then(_tx => selfPost(_tx, pi))
}
function monitorLiveIncoming (settings) {