diff --git a/tests/integration/api.security.test.js b/tests/integration/api.security.test.js index 58f9728..a377410 100644 --- a/tests/integration/api.security.test.js +++ b/tests/integration/api.security.test.js @@ -409,6 +409,11 @@ test('Api security', { timeout: 90000 }, async (main) => { await testGetEndpointSecurity(n, httpClient, api, invalidToken, readonlyUser, encoding) }) + await main.test('Api: get finance/cost-summary', async (n) => { + const api = `${appNodeBaseUrl}${ENDPOINTS.FINANCE_COST_SUMMARY}?start=1700000000000&end=1700100000000` + await testGetEndpointSecurity(n, httpClient, api, invalidToken, readonlyUser, encoding) + }) + await main.test('Api: get ext-data', async (n) => { const api = `${appNodeBaseUrl}${ENDPOINTS.EXT_DATA}?type=miner` await testGetEndpointSecurity(n, httpClient, api, invalidToken, readonlyUser, encoding) diff --git a/tests/unit/handlers/finance.handlers.test.js b/tests/unit/handlers/finance.handlers.test.js new file mode 100644 index 0000000..fd8cb01 --- /dev/null +++ b/tests/unit/handlers/finance.handlers.test.js @@ -0,0 +1,149 @@ +'use strict' + +const test = require('brittle') +const { + getCostSummary, + processConsumptionData, + processPriceData, + processCostsData, + calculateCostSummary +} = require('../../../workers/lib/server/handlers/finance.handlers') + +test('getCostSummary - happy path', async (t) => { + const mockCtx = { + conf: { + orks: [{ rpcPublicKey: 'key1' }] + }, + net_r0: { + jRequest: async (key, method, payload) => { + if (method === 'tailLogCustomRangeAggr') { + return [{ data: { 1700006400000: { site_power_w: 5000 } } }] + } + if (method === 'getWrkExtData') { + return { data: [{ prices: [{ ts: 1700006400000, price: 40000 }] }] } + } + return {} + } + }, + globalDataLib: { + getGlobalData: async () => [] + } + } + + const mockReq = { + query: { start: 1700000000000, end: 1700100000000, period: 'daily' } + } + + const result = await getCostSummary(mockCtx, mockReq, {}) + t.ok(result.log, 'should return log array') + t.ok(result.summary, 'should return summary') + t.ok(Array.isArray(result.log), 'log should be array') + t.pass() +}) + +test('getCostSummary - missing start throws', async (t) => { + const mockCtx = { + conf: { orks: [] }, + net_r0: { jRequest: async () => ({}) }, + globalDataLib: { getGlobalData: async () => [] } + } + + try { + await getCostSummary(mockCtx, { query: { end: 1700100000000 } }, {}) + t.fail('should have thrown') + } catch (err) { + t.is(err.message, 'ERR_MISSING_START_END', 'should throw missing start/end error') + } + t.pass() +}) + +test('getCostSummary - invalid range throws', async (t) => { + const mockCtx = { + conf: { orks: [] }, + net_r0: { jRequest: async () => ({}) }, + globalDataLib: { getGlobalData: async () => [] } + } + + try { + await getCostSummary(mockCtx, { query: { start: 1700100000000, end: 1700000000000 } }, {}) + t.fail('should have thrown') + } catch (err) { + t.is(err.message, 'ERR_INVALID_DATE_RANGE', 'should throw invalid range error') + } + t.pass() +}) + +test('getCostSummary - empty ork results', async (t) => { + const mockCtx = { + conf: { orks: [{ rpcPublicKey: 'key1' }] }, + net_r0: { jRequest: async () => ({}) }, + globalDataLib: { getGlobalData: async () => [] } + } + + const result = await getCostSummary(mockCtx, { query: { start: 1700000000000, end: 1700100000000 } }, {}) + t.ok(result.log, 'should return log array') + t.is(result.log.length, 0, 'log should be empty') + t.pass() +}) + +test('processConsumptionData - processes valid data', (t) => { + const results = [[{ data: { 1700006400000: { site_power_w: 5000 } } }]] + const daily = processConsumptionData(results) + t.ok(typeof daily === 'object', 'should return object') + t.pass() +}) + +test('processConsumptionData - handles error results', (t) => { + const results = [{ error: 'timeout' }] + const daily = processConsumptionData(results) + t.is(Object.keys(daily).length, 0, 'should be empty') + t.pass() +}) + +test('processPriceData - processes valid data', (t) => { + const results = [[{ prices: [{ ts: 1700006400000, price: 40000 }] }]] + const daily = processPriceData(results) + t.ok(typeof daily === 'object', 'should return object') + t.pass() +}) + +test('processCostsData - processes app-node format (energyCost)', (t) => { + const costs = [ + { site: 'site1', year: 2023, month: 11, energyCost: 30000, operationalCost: 6000 } + ] + + const result = processCostsData(costs) + t.ok(result['2023-11'], 'should have month key') + t.is(result['2023-11'].energyCostPerDay, 1000, 'should have daily energy cost (30000/30)') + t.is(result['2023-11'].operationalCostPerDay, 200, 'should have daily operational cost (6000/30)') + t.pass() +}) + +test('processCostsData - handles non-array input', (t) => { + const result = processCostsData(null) + t.is(Object.keys(result).length, 0, 'should be empty') + t.pass() +}) + +test('calculateCostSummary - calculates from log entries', (t) => { + const log = [ + { energyCostsUSD: 5000, operationalCostsUSD: 1000, totalCostsUSD: 6000, consumptionMWh: 100, btcPrice: 40000 }, + { energyCostsUSD: 3000, operationalCostsUSD: 600, totalCostsUSD: 3600, consumptionMWh: 60, btcPrice: 42000 } + ] + + const summary = calculateCostSummary(log) + t.is(summary.totalEnergyCostsUSD, 8000, 'should sum energy costs') + t.is(summary.totalOperationalCostsUSD, 1600, 'should sum operational costs') + t.is(summary.totalCostsUSD, 9600, 'should sum total costs') + t.is(summary.totalConsumptionMWh, 160, 'should sum consumption') + t.ok(summary.avgAllInCostPerMWh !== null, 'should calculate avg all-in cost') + t.ok(summary.avgBtcPrice !== null, 'should calculate avg BTC price') + t.pass() +}) + +test('calculateCostSummary - handles empty log', (t) => { + const summary = calculateCostSummary([]) + t.is(summary.totalCostsUSD, 0, 'should be zero') + t.is(summary.avgAllInCostPerMWh, null, 'should be null') + t.pass() +}) diff --git a/tests/unit/routes/finance.routes.test.js b/tests/unit/routes/finance.routes.test.js new file mode 100644 index 0000000..8cd0ae2 --- /dev/null +++ b/tests/unit/routes/finance.routes.test.js @@ -0,0 +1,39 @@ +'use strict' + +const test = require('brittle') +const { testModuleStructure, testHandlerFunctions, testOnRequestFunctions } = require('../helpers/routeTestHelpers') +const { createRoutesForTest } = require('../helpers/mockHelpers') + +const ROUTES_PATH = '../../../workers/lib/server/routes/finance.routes.js' + +test('finance routes - module structure', (t) => { + testModuleStructure(t, ROUTES_PATH, 'finance') + t.pass() +}) + +test('finance routes - route definitions', (t) => { + const routes = createRoutesForTest(ROUTES_PATH) + const routeUrls = routes.map(route => route.url) + t.ok(routeUrls.includes('/auth/finance/cost-summary'), 'should have cost-summary route') + t.pass() +}) + +test('finance routes - HTTP methods', (t) => { + const routes = createRoutesForTest(ROUTES_PATH) + routes.forEach(route => { + t.is(route.method, 'GET', `route ${route.url} should be GET`) + }) + t.pass() +}) + +test('finance routes - handler functions', (t) => { + const routes = createRoutesForTest(ROUTES_PATH) + testHandlerFunctions(t, routes, 'finance') + t.pass() +}) + +test('finance routes - onRequest functions', (t) => { + const routes = createRoutesForTest(ROUTES_PATH) + testOnRequestFunctions(t, routes, 'finance') + t.pass() +}) diff --git a/workers/lib/constants.js b/workers/lib/constants.js index f1f407e..f2de347 100644 --- a/workers/lib/constants.js +++ b/workers/lib/constants.js @@ -108,7 +108,10 @@ const ENDPOINTS = { THING_CONFIG: '/auth/thing-config', // WebSocket endpoint - WEBSOCKET: '/ws' + WEBSOCKET: '/ws', + + // Finance endpoints + FINANCE_COST_SUMMARY: '/auth/finance/cost-summary' } const HTTP_METHODS = { @@ -183,6 +186,41 @@ const STATUS_CODES = { INTERNAL_SERVER_ERROR: 500 } +const RPC_METHODS = { + TAIL_LOG_RANGE_AGGR: 'tailLogCustomRangeAggr', + GET_WRK_EXT_DATA: 'getWrkExtData', + LIST_THINGS: 'listThings', + TAIL_LOG: 'tailLog' +} + +const WORKER_TYPES = { + MINER: 'miner', + POWERMETER: 'powermeter', + MINERPOOL: 'minerpool', + MEMPOOL: 'mempool' +} + +const AGGR_FIELDS = { + HASHRATE_SUM: 'hashrate_mhs_5m_sum_aggr', + SITE_POWER: 'site_power_w' +} + +const PERIOD_TYPES = { + DAILY: 'daily', + WEEKLY: 'weekly', + MONTHLY: 'monthly', + YEARLY: 'yearly' +} + +const NON_METRIC_KEYS = [ + 'ts', + 'site', + 'year', + 'monthName', + 'month', + 'period' +] + const RPC_TIMEOUT = 15000 const RPC_CONCURRENCY_LIMIT = 2 @@ -202,5 +240,10 @@ module.exports = { STATUS_CODES, RPC_TIMEOUT, RPC_CONCURRENCY_LIMIT, - USER_SETTINGS_TYPE + USER_SETTINGS_TYPE, + RPC_METHODS, + WORKER_TYPES, + AGGR_FIELDS, + PERIOD_TYPES, + NON_METRIC_KEYS } diff --git a/workers/lib/period.utils.js b/workers/lib/period.utils.js new file mode 100644 index 0000000..63a1144 --- /dev/null +++ b/workers/lib/period.utils.js @@ -0,0 +1,176 @@ +'use strict' + +const { PERIOD_TYPES, NON_METRIC_KEYS } = require('./constants') + +const getStartOfDay = (ts) => Math.floor(ts / 86400000) * 86400000 + +const convertMsToSeconds = (timestampMs) => { + return Math.floor(timestampMs / 1000) +} + +const PERIOD_CALCULATORS = { + daily: (timestamp) => getStartOfDay(timestamp), + monthly: (timestamp) => { + const date = new Date(timestamp) + return new Date(date.getFullYear(), date.getMonth(), 1).getTime() + }, + yearly: (timestamp) => { + const date = new Date(timestamp) + return new Date(date.getFullYear(), 0, 1).getTime() + } +} + +const aggregateByPeriod = (log, period, nonMetricKeys = []) => { + if (period === PERIOD_TYPES.DAILY) { + return log + } + + const allNonMetricKeys = new Set([...NON_METRIC_KEYS, ...nonMetricKeys]) + + const grouped = log.reduce((acc, entry) => { + let date + try { + date = new Date(Number(entry.ts)) + + if (isNaN(date.getTime())) { + return acc + } + } catch (error) { + return acc + } + + let groupKey + + if (period === PERIOD_TYPES.MONTHLY) { + groupKey = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}` + } else if (period === PERIOD_TYPES.YEARLY) { + groupKey = `${date.getFullYear()}` + } else { + groupKey = `${entry.ts}` + } + + if (!acc[groupKey]) { + acc[groupKey] = [] + } + acc[groupKey].push(entry) + return acc + }, {}) + + const aggregatedResults = Object.entries(grouped).map(([groupKey, entries]) => { + const aggregated = entries.reduce((acc, entry) => { + Object.entries(entry).forEach(([key, val]) => { + if (allNonMetricKeys.has(key)) { + if (!acc[key] || acc[key] === null || acc[key] === undefined) { + acc[key] = val + } + } else { + const numVal = Number(val) || 0 + acc[key] = (acc[key] || 0) + numVal + } + }) + return acc + }, {}) + + try { + if (period === PERIOD_TYPES.MONTHLY) { + const [year, month] = groupKey.split('-').map(Number) + + const newDate = new Date(year, month - 1, 1) + if (isNaN(newDate.getTime())) { + throw new Error(`Invalid date for monthly grouping: ${groupKey}`) + } + + aggregated.ts = newDate.getTime() + aggregated.month = month + aggregated.year = year + aggregated.monthName = newDate.toLocaleString('en-US', { month: 'long' }) + } else if (period === PERIOD_TYPES.YEARLY) { + const year = parseInt(groupKey) + + const newDate = new Date(year, 0, 1) + if (isNaN(newDate.getTime())) { + throw new Error(`Invalid date for yearly grouping: ${groupKey}`) + } + + aggregated.ts = newDate.getTime() + aggregated.year = year + } + } catch (error) { + aggregated.ts = entries[0].ts + + try { + const fallbackDate = new Date(Number(entries[0].ts)) + if (!isNaN(fallbackDate.getTime())) { + if (period === PERIOD_TYPES.MONTHLY) { + aggregated.month = fallbackDate.getMonth() + 1 + aggregated.year = fallbackDate.getFullYear() + aggregated.monthName = fallbackDate.toLocaleString('en-US', { month: 'long' }) + } else if (period === PERIOD_TYPES.YEARLY) { + aggregated.year = fallbackDate.getFullYear() + } + } + } catch (fallbackError) { + console.warn('Could not extract date info from fallback timestamp', fallbackError) + } + } + + return aggregated + }) + + return aggregatedResults.sort((a, b) => Number(b.ts) - Number(a.ts)) +} + +const getPeriodKey = (timestamp, period) => { + const calculator = PERIOD_CALCULATORS[period] || PERIOD_CALCULATORS.daily + return calculator(timestamp) +} + +const getPeriodEndDate = (periodTs, period) => { + const periodEnd = new Date(periodTs) + + switch (period) { + case PERIOD_TYPES.MONTHLY: + periodEnd.setMonth(periodEnd.getMonth() + 1) + break + case PERIOD_TYPES.YEARLY: + periodEnd.setFullYear(periodEnd.getFullYear() + 1) + break + } + + return periodEnd +} + +const isTimestampInPeriod = (timestamp, periodTs, period) => { + if (period === PERIOD_TYPES.DAILY) return timestamp === periodTs + + const periodEnd = getPeriodEndDate(periodTs, period) + return timestamp >= periodTs && timestamp < periodEnd.getTime() +} + +const getFilteredPeriodData = ( + sourceData, + periodTs, + period, + filterFn = (entries) => entries +) => { + if (period === PERIOD_TYPES.DAILY) { + return sourceData[periodTs] || (typeof filterFn === 'function' ? {} : 0) + } + + const entriesInPeriod = Object.entries(sourceData).filter(([tsStr]) => { + const timestamp = Number(tsStr) + return isTimestampInPeriod(timestamp, periodTs, period) + }) + + return filterFn(entriesInPeriod, sourceData) +} + +module.exports = { + getStartOfDay, + convertMsToSeconds, + getPeriodEndDate, + aggregateByPeriod, + getPeriodKey, + isTimestampInPeriod, + getFilteredPeriodData +} diff --git a/workers/lib/server/handlers/finance.handlers.js b/workers/lib/server/handlers/finance.handlers.js new file mode 100644 index 0000000..3a0dcdb --- /dev/null +++ b/workers/lib/server/handlers/finance.handlers.js @@ -0,0 +1,226 @@ +'use strict' + +const { + WORKER_TYPES, + AGGR_FIELDS, + PERIOD_TYPES, + RPC_METHODS, + GLOBAL_DATA_TYPES +} = require('../../constants') +const { + requestRpcEachLimit, + getStartOfDay, + safeDiv, + runParallel +} = require('../../utils') +const { aggregateByPeriod } = require('../../period.utils') + +async function getCostSummary (ctx, req) { + const start = Number(req.query.start) + const end = Number(req.query.end) + const period = req.query.period || PERIOD_TYPES.MONTHLY + + if (!start || !end) { + throw new Error('ERR_MISSING_START_END') + } + + if (start >= end) { + throw new Error('ERR_INVALID_DATE_RANGE') + } + + const startDate = new Date(start).toISOString() + const endDate = new Date(end).toISOString() + + const [productionCosts, priceResults, consumptionResults] = await runParallel([ + (cb) => getProductionCosts(ctx, null, start, end) + .then(r => cb(null, r)).catch(cb), + + (cb) => requestRpcEachLimit(ctx, RPC_METHODS.GET_WRK_EXT_DATA, { + type: WORKER_TYPES.MEMPOOL, + query: { key: 'prices', start, end } + }).then(r => cb(null, r)).catch(cb), + + (cb) => requestRpcEachLimit(ctx, RPC_METHODS.TAIL_LOG_RANGE_AGGR, { + keys: [{ + type: WORKER_TYPES.POWERMETER, + startDate, + endDate, + fields: { [AGGR_FIELDS.SITE_POWER]: 1 }, + shouldReturnDailyData: 1 + }] + }).then(r => cb(null, r)).catch(cb) + ]) + + const costsByMonth = processCostsData(productionCosts) + const dailyPrices = processPriceData(priceResults) + const dailyConsumption = processConsumptionData(consumptionResults) + + const allDays = new Set([ + ...Object.keys(dailyConsumption), + ...Object.keys(dailyPrices) + ]) + + const log = [] + for (const dayTs of [...allDays].sort()) { + const ts = Number(dayTs) + const consumption = dailyConsumption[dayTs] || {} + const btcPrice = dailyPrices[dayTs] || 0 + + const powerW = consumption.powerW || 0 + const consumptionMWh = (powerW * 24) / 1000000 + + const monthKey = `${new Date(ts).getFullYear()}-${String(new Date(ts).getMonth() + 1).padStart(2, '0')}` + const costs = costsByMonth[monthKey] || {} + const energyCostsUSD = costs.energyCostPerDay || 0 + const operationalCostsUSD = costs.operationalCostPerDay || 0 + const totalCostsUSD = energyCostsUSD + operationalCostsUSD + + log.push({ + ts, + consumptionMWh, + energyCostsUSD, + operationalCostsUSD, + totalCostsUSD, + allInCostPerMWh: safeDiv(totalCostsUSD, consumptionMWh), + energyCostPerMWh: safeDiv(energyCostsUSD, consumptionMWh), + btcPrice + }) + } + + const aggregated = aggregateByPeriod(log, period) + const summary = calculateCostSummary(aggregated) + + return { log: aggregated, summary } +} + +function processConsumptionData (results) { + const daily = {} + for (const res of results) { + if (res.error || !res) continue + const data = Array.isArray(res) ? res : (res.data || res.result || []) + if (!Array.isArray(data)) continue + for (const entry of data) { + if (!entry) continue + const items = entry.data || entry.items || entry + if (Array.isArray(items)) { + for (const item of items) { + const ts = getStartOfDay(item.ts || item.timestamp) + if (!daily[ts]) daily[ts] = { powerW: 0 } + daily[ts].powerW += (item[AGGR_FIELDS.SITE_POWER] || item.site_power_w || 0) + } + } else if (typeof items === 'object') { + for (const [key, val] of Object.entries(items)) { + const ts = getStartOfDay(Number(key)) + if (!daily[ts]) daily[ts] = { powerW: 0 } + const power = typeof val === 'object' ? (val[AGGR_FIELDS.SITE_POWER] || val.site_power_w || 0) : (Number(val) || 0) + daily[ts].powerW += power + } + } + } + } + return daily +} + +function processPriceData (results) { + const daily = {} + for (const res of results) { + if (res.error || !res) continue + const data = Array.isArray(res) ? res : (res.data || res.result || []) + if (!Array.isArray(data)) continue + for (const entry of data) { + if (!entry) continue + const items = entry.data || entry.prices || entry + if (Array.isArray(items)) { + for (const item of items) { + const ts = getStartOfDay(item.ts || item.timestamp || item.time) + if (ts && item.price) { + daily[ts] = item.price + } + } + } else if (typeof items === 'object' && !Array.isArray(items)) { + for (const [key, val] of Object.entries(items)) { + const ts = getStartOfDay(Number(key)) + if (ts) { + daily[ts] = typeof val === 'object' ? (val.USD || val.price || 0) : Number(val) || 0 + } + } + } + } + } + return daily +} + +async function getProductionCosts (ctx, site, start, end) { + if (!ctx.globalDataLib) return [] + const costs = await ctx.globalDataLib.getGlobalData({ + type: GLOBAL_DATA_TYPES.PRODUCTION_COSTS + }) + if (!Array.isArray(costs)) return [] + + const startDate = new Date(start) + const endDate = new Date(end) + return costs.filter(entry => { + if (!entry || !entry.year || !entry.month) return false + if (site && entry.site !== site) return false + const entryDate = new Date(entry.year, entry.month - 1, 1) + return entryDate >= startDate && entryDate <= endDate + }) +} + +function processCostsData (costs) { + const byMonth = {} + if (!Array.isArray(costs)) return byMonth + for (const entry of costs) { + if (!entry || !entry.year || !entry.month) continue + const key = `${entry.year}-${String(entry.month).padStart(2, '0')}` + const daysInMonth = new Date(entry.year, entry.month, 0).getDate() + byMonth[key] = { + energyCostPerDay: (entry.energyCost || entry.energyCostsUSD || 0) / daysInMonth, + operationalCostPerDay: (entry.operationalCost || entry.operationalCostsUSD || 0) / daysInMonth + } + } + return byMonth +} + +function calculateCostSummary (log) { + if (!log.length) { + return { + totalEnergyCostsUSD: 0, + totalOperationalCostsUSD: 0, + totalCostsUSD: 0, + totalConsumptionMWh: 0, + avgAllInCostPerMWh: null, + avgEnergyCostPerMWh: null, + avgBtcPrice: null + } + } + + const totals = log.reduce((acc, entry) => { + acc.energyCosts += entry.energyCostsUSD || 0 + acc.operationalCosts += entry.operationalCostsUSD || 0 + acc.totalCosts += entry.totalCostsUSD || 0 + acc.consumption += entry.consumptionMWh || 0 + acc.btcPriceSum += entry.btcPrice || 0 + acc.btcPriceCount += entry.btcPrice ? 1 : 0 + return acc + }, { energyCosts: 0, operationalCosts: 0, totalCosts: 0, consumption: 0, btcPriceSum: 0, btcPriceCount: 0 }) + + return { + totalEnergyCostsUSD: totals.energyCosts, + totalOperationalCostsUSD: totals.operationalCosts, + totalCostsUSD: totals.totalCosts, + totalConsumptionMWh: totals.consumption, + avgAllInCostPerMWh: safeDiv(totals.totalCosts, totals.consumption), + avgEnergyCostPerMWh: safeDiv(totals.energyCosts, totals.consumption), + avgBtcPrice: safeDiv(totals.btcPriceSum, totals.btcPriceCount) + } +} + +module.exports = { + getCostSummary, + processConsumptionData, + processPriceData, + getProductionCosts, + processCostsData, + calculateCostSummary +} diff --git a/workers/lib/server/index.js b/workers/lib/server/index.js index ac884da..eb67811 100644 --- a/workers/lib/server/index.js +++ b/workers/lib/server/index.js @@ -8,6 +8,7 @@ const globalRoutes = require('./routes/global.routes') const thingsRoutes = require('./routes/things.routes') const settingsRoutes = require('./routes/settings.routes') const wsRoutes = require('./routes/ws.routes') +const financeRoutes = require('./routes/finance.routes') /** * Collect all routes into a flat array for server injection. @@ -22,7 +23,8 @@ function routes (ctx) { ...thingsRoutes(ctx), ...usersRoutes(ctx), ...settingsRoutes(ctx), - ...wsRoutes(ctx) + ...wsRoutes(ctx), + ...financeRoutes(ctx) ] } diff --git a/workers/lib/server/routes/finance.routes.js b/workers/lib/server/routes/finance.routes.js new file mode 100644 index 0000000..47d9e70 --- /dev/null +++ b/workers/lib/server/routes/finance.routes.js @@ -0,0 +1,35 @@ +'use strict' + +const { + ENDPOINTS, + HTTP_METHODS +} = require('../../constants') +const { + getCostSummary +} = require('../handlers/finance.handlers') +const { createCachedAuthRoute } = require('../lib/routeHelpers') + +module.exports = (ctx) => { + const schemas = require('../schemas/finance.schemas.js') + + return [ + { + method: HTTP_METHODS.GET, + url: ENDPOINTS.FINANCE_COST_SUMMARY, + schema: { + querystring: schemas.query.costSummary + }, + ...createCachedAuthRoute( + ctx, + (req) => [ + 'finance/cost-summary', + req.query.start, + req.query.end, + req.query.period + ], + ENDPOINTS.FINANCE_COST_SUMMARY, + getCostSummary + ) + } + ] +} diff --git a/workers/lib/server/schemas/finance.schemas.js b/workers/lib/server/schemas/finance.schemas.js new file mode 100644 index 0000000..00567c9 --- /dev/null +++ b/workers/lib/server/schemas/finance.schemas.js @@ -0,0 +1,18 @@ +'use strict' + +const schemas = { + query: { + costSummary: { + type: 'object', + properties: { + start: { type: 'integer' }, + end: { type: 'integer' }, + period: { type: 'string', enum: ['daily', 'monthly', 'yearly'] }, + overwriteCache: { type: 'boolean' } + }, + required: ['start', 'end'] + } + } +} + +module.exports = schemas diff --git a/workers/lib/utils.js b/workers/lib/utils.js index 886ae5f..9d5878e 100644 --- a/workers/lib/utils.js +++ b/workers/lib/utils.js @@ -2,6 +2,7 @@ const async = require('async') const { RPC_TIMEOUT, RPC_CONCURRENCY_LIMIT } = require('./constants') +const { getStartOfDay } = require('./period.utils') const dateNowSec = () => Math.floor(Date.now() / 1000) @@ -128,6 +129,19 @@ const requestRpcMapLimit = async (ctx, method, payload) => { }) } +const safeDiv = (num, denom) => { + if (!denom || !num) return null + return num / denom +} + +const runParallel = (tasks) => + new Promise((resolve, reject) => { + async.parallel(tasks, (err, results) => { + if (err) reject(err) + else resolve(results) + }) + }) + module.exports = { dateNowSec, extractIps, @@ -137,5 +151,8 @@ module.exports = { getAuthTokenFromHeaders, parseJsonQueryParam, requestRpcEachLimit, - requestRpcMapLimit + requestRpcMapLimit, + getStartOfDay, + safeDiv, + runParallel }