Skip to content

Commit

Permalink
fix: avoid multiple queries to db for the same account
Browse files Browse the repository at this point in the history
  • Loading branch information
dolcalmi committed Nov 1, 2024
1 parent 08df882 commit b4d8f81
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 9 deletions.
27 changes: 22 additions & 5 deletions core/api/src/servers/exporter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -301,14 +301,31 @@ const createWalletGauge = ({
})
}

const inProgressBalanceQueries = new Map<string, Promise<number>>()

const getWalletBalance = async (walletId: WalletId): Promise<number> => {
const walletBalance = await LedgerService().getWalletBalance(walletId)
if (walletBalance instanceof Error) {
logger.warn({ walletId, walletBalance }, "impossible to get balance")
return 0
const inProgressKey = `wallet-${walletId}`

const inProgress = inProgressBalanceQueries.get(inProgressKey)
if (inProgress) {
return inProgress
}

return walletBalance
const balancePromise = (async () => {
try {
const walletBalance = await LedgerService().getWalletBalance(walletId)
if (walletBalance instanceof Error) {
logger.warn({ walletId, walletBalance }, "impossible to get balance")
return 0
}
return walletBalance
} finally {
inProgressBalanceQueries.delete(inProgressKey)
}
})()

inProgressBalanceQueries.set(inProgressKey, balancePromise)
return balancePromise
}

const createColdStorageWalletGauge = () => {
Expand Down
26 changes: 22 additions & 4 deletions core/api/src/services/ledger/admin-legacy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,30 @@ import {
UnknownLedgerError,
} from "@/domain/ledger"

const inProgressQueries = new Map<string, Promise<number>>()

const getWalletBalance = async (account: string, query = {}) => {
const params = { account, currency: "BTC", ...query }
const { balance } = await MainBookAdmin.balance(params, {
readPreference: "secondaryPreferred",
})
return balance
const inProgressKey = `${account}-${JSON.stringify(params)}`

const inProgress = inProgressQueries.get(inProgressKey)
if (inProgress) {
return inProgress
}

const balancePromise = (async () => {
try {
const { balance } = await MainBookAdmin.balance(params, {
readPreference: "secondaryPreferred",
})
return balance
} finally {
inProgressQueries.delete(inProgressKey)
}
})()

inProgressQueries.set(inProgressKey, balancePromise)
return balancePromise
}

export const getAssetsBalance = (endDate?: Date) =>
Expand Down

0 comments on commit b4d8f81

Please sign in to comment.