All files / admin analytics-costs.js

100% Statements 127/127
87.93% Branches 51/58
100% Functions 27/27
100% Lines 114/114

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 2901x 1x         1x 1x       1x 1x   1x 1x 1x 1x 1x 1x 1x   1x     1x   432x 430x     13x 13x                               13x       13x 13x 409x   13x                 13x 13x                     409x 163x 3x 2x 2x       13x 13x   13x 409x   13x 13x     13x 163x   13x       13x       10x   10x 9x   12x   9x 9x     8x                       10x 10x 10x   10x     10x 11x                         11x 13x         13x   9x     9x 9x             9x       13x 13x   13x   9x             11x     10x       334x 334x 334x 170x 170x   334x     156x 2x         409x 409x 409x       13x 330x           2x 2x 79x 79x 79x     2x 2x 4x       13x 13x 409x 200x     13x       13x 13x 13x   13x 13x 13x 13x   13x 13x   409x 13x 10x 10x 12x   10x 10x   1x       13x 334x   13x                                 1x  
const { CostExplorerClient, GetCostAndUsageCommand } = require('@aws-sdk/client-cost-explorer')
const { DynamoDBClient } = require('@aws-sdk/client-dynamodb')
const {
  DynamoDBDocumentClient,
  BatchGetCommand,
  BatchWriteCommand
} = require('@aws-sdk/lib-dynamodb')
const { requirePlatformAdmin } = require('../utils/requirePlatformAdmin')
 
// AWS Cost Explorer only exposes its API from the us-east-1 endpoint, regardless
// of which region the billed resources actually run in (eu-central-1 here).
const ceClient = new CostExplorerClient({ region: 'us-east-1' })
const docClient = DynamoDBDocumentClient.from(new DynamoDBClient({}))
 
const DAYS = 30
const DEFAULT_MONTHS = 6
const MIN_MONTHS = 1
const MAX_MONTHS = 12
const UNTAGGED_ENVIRONMENT = 'untagged'
const BATCH_GET_CHUNK = 100
const BATCH_WRITE_CHUNK = 25
// AWS closes the previous month's invoice within the first days of the month
const INVOICE_CLOSE_DAY = 5
// How long a not-yet-final day is served from cache before being re-fetched,
// to bound Cost Explorer requests (billed per request) while staying fresh
const REFRESH_INTERVAL_MS = 6 * 60 * 60 * 1000
 
const formatDate = (date) => date.toISOString().slice(0, 10)
const addDays = (date, days) => new Date(date.getTime() + days * 24 * 60 * 60 * 1000)
 
function parseMonths(raw) {
  const parsed = parseInt(raw, 10)
  return Number.isFinite(parsed)
    ? Math.min(Math.max(parsed, MIN_MONTHS), MAX_MONTHS)
    : DEFAULT_MONTHS
}
 
/**
 * Every date this lambda asks about is a completed day (Cost Explorer's
 * `TimePeriod.End` is exclusive and "today" is always the end), but a
 * completed day is NOT final: AWS keeps adding usage to it for 24-72h, and
 * month-level charges (tax, Route 53 hosted zones, support, credits) land on
 * the first or last day of the month once the invoice closes, a few days into
 * the following month. Caching those days forever made the chart drift below
 * the AWS console, so only days flagged `final` are trusted from the cache.
 */
function neededDates(granularity, months, today) {
  const start =
    granularity === 'MONTHLY'
      ? new Date(Date.UTC(today.getUTCFullYear(), today.getUTCMonth() - (months - 1), 1))
      : addDays(today, -DAYS)
 
  const dates = []
  for (let d = start; d < today; d = addDays(d, 1)) {
    dates.push(formatDate(d))
  }
  return dates
}
 
/**
 * Days before this cutoff belong to a month whose invoice AWS has closed:
 * the current month once we are past its first few days, the previous one
 * before that (its invoice may still be open).
 */
function settledCutoff(today) {
  const monthOffset = today.getUTCDate() > INVOICE_CLOSE_DAY ? 0 : -1
  return formatDate(
    new Date(Date.UTC(today.getUTCFullYear(), today.getUTCMonth() + monthOffset, 1))
  )
}
 
/**
 * A cached day is reused when AWS has finalized it, or — for a day still
 * open to adjustments — when it was fetched recently enough. A settled day
 * cached before it was final is fetched once more to pick up its final value.
 */
function needsFetch(date, record, cutoff, now) {
  if (!record) return true
  if (record.final) return false
  if (date < cutoff) return true
  const fetchedAt = Date.parse(record.fetchedAt ?? '')
  return !Number.isFinite(fetchedAt) || now.getTime() - fetchedAt > REFRESH_INTERVAL_MS
}
 
async function batchGetDays(dates) {
  const found = new Map()
  const tableName = process.env.AWS_COST_DAILY_TABLE_NAME
 
  for (let i = 0; i < dates.length; i += BATCH_GET_CHUNK) {
    let keys = dates.slice(i, i + BATCH_GET_CHUNK).map((date) => ({ date }))
 
    while (keys.length > 0) {
      const result = await docClient.send(
        new BatchGetCommand({ RequestItems: { [tableName]: { Keys: keys } } })
      )
      for (const item of result.Responses?.[tableName] ?? []) {
        found.set(item.date, item)
      }
      keys = result.UnprocessedKeys?.[tableName]?.Keys ?? []
    }
  }
 
  return found
}
 
async function writeDays(dayRecords) {
  const tableName = process.env.AWS_COST_DAILY_TABLE_NAME
 
  for (let i = 0; i < dayRecords.length; i += BATCH_WRITE_CHUNK) {
    let requestItems = dayRecords
      .slice(i, i + BATCH_WRITE_CHUNK)
      .map((item) => ({ PutRequest: { Item: item } }))
 
    while (requestItems.length > 0) {
      const result = await docClient.send(
        new BatchWriteCommand({ RequestItems: { [tableName]: requestItems } })
      )
      requestItems = result.UnprocessedItems?.[tableName] ?? []
    }
  }
}
 
/**
 * Backfills every missing date in one Cost Explorer request (billed per
 * request, not per day, so a 300-day gap costs the same as a 1-day gap) by
 * spanning from the earliest to the latest missing date — even if that span
 * also covers already-cached dates in between, which just get refreshed.
 */
async function fetchMissingDays(missingDates, cutoff, now) {
  const sorted = [...missingDates].sort()
  const start = sorted[0]
  const end = formatDate(addDays(new Date(sorted[sorted.length - 1]), 1))
 
  const dayRecords = new Map()
  let nextPageToken
 
  do {
    const result = await ceClient.send(
      new GetCostAndUsageCommand({
        TimePeriod: { Start: start, End: end },
        Granularity: 'DAILY',
        Metrics: ['UnblendedCost'],
        GroupBy: [
          { Type: 'DIMENSION', Key: 'SERVICE' },
          { Type: 'TAG', Key: 'Environment' }
        ],
        NextPageToken: nextPageToken
      })
    )
 
    for (const period of result.ResultsByTime ?? []) {
      const date = period.TimePeriod?.Start
 
      // Cost Explorer leaves the per-period `Total` field empty whenever
      // `GroupBy` is used, so the total must be derived by summing the
      // per-group amounts rather than read from `period.Total`.
      const byServiceAndEnvironment = (period.Groups ?? [])
        .map((group) => {
          const [service, environmentTag] = group.Keys ?? []
          // A TAG group's key is formatted "Environment$<value>" — an empty
          // value means the resource isn't tagged at all.
          const environment = (environmentTag ?? '').split('$')[1] || UNTAGGED_ENVIRONMENT
          return {
            service,
            environment,
            amount: Number(group.Metrics?.UnblendedCost?.Amount ?? 0)
          }
        })
        // Negative amounts are credits/refunds: the console nets them out
        .filter((entry) => entry.amount !== 0)
 
      // With GroupBy, Cost Explorer may split one day's groups across several
      // pages, repeating the same period: merge them instead of overwriting.
      const existing = dayRecords.get(date)
      const entries = [...(existing?.byServiceAndEnvironment ?? []), ...byServiceAndEnvironment]
 
      dayRecords.set(date, {
        date,
        totalCost: entries.reduce((sum, entry) => sum + entry.amount, 0),
        byServiceAndEnvironment: entries,
        final: date < cutoff && !period.Estimated && (existing?.final ?? true),
        fetchedAt: now.toISOString()
      })
    }
 
    nextPageToken = result.NextPageToken
  } while (nextPageToken)
 
  return dayRecords
}
 
function aggregate(entries) {
  const byService = new Map()
  let total = 0
  for (const entry of entries) {
    total += entry.amount
    byService.set(entry.service, (byService.get(entry.service) ?? 0) + entry.amount)
  }
  return {
    total,
    byService: [...byService.entries()]
      .map(([service, amount]) => ({ service, amount }))
      .sort((a, b) => b.amount - a.amount)
  }
}
 
function entriesFor(dayRecords, date, environment) {
  const record = dayRecords.get(date)
  const entries = record?.byServiceAndEnvironment ?? []
  return environment ? entries.filter((entry) => entry.environment === environment) : entries
}
 
function buildSeries(dates, dayRecords, granularity, environment) {
  if (granularity !== 'MONTHLY') {
    return dates.map((date) => ({
      period: date,
      ...aggregate(entriesFor(dayRecords, date, environment))
    }))
  }
 
  const byMonth = new Map()
  for (const date of dates) {
    const period = `${date.slice(0, 7)}-01`
    const entries = entriesFor(dayRecords, date, environment)
    byMonth.set(period, [...(byMonth.get(period) ?? []), ...entries])
  }
 
  return [...byMonth.entries()]
    .sort(([a], [b]) => a.localeCompare(b))
    .map(([period, entries]) => ({ period, ...aggregate(entries) }))
}
 
function availableEnvironmentsFrom(dates, dayRecords) {
  const environments = new Set()
  for (const date of dates) {
    for (const entry of dayRecords.get(date)?.byServiceAndEnvironment ?? []) {
      environments.add(entry.environment)
    }
  }
  return [...environments].sort()
}
 
async function analyticsCostsHandler(event) {
  const granularity = event.queryStringParameters?.granularity === 'MONTHLY' ? 'MONTHLY' : 'DAILY'
  const months = parseMonths(event.queryStringParameters?.months)
  const environment = event.queryStringParameters?.environment || null
 
  const now = new Date()
  const today = new Date(now)
  today.setUTCHours(0, 0, 0, 0)
  const cutoff = settledCutoff(today)
 
  const dates = neededDates(granularity, months, today)
  const dayRecords = await batchGetDays(dates)
 
  const missingDates = dates.filter((date) => needsFetch(date, dayRecords.get(date), cutoff, now))
  if (missingDates.length > 0) {
    const fetched = await fetchMissingDays(missingDates, cutoff, now)
    for (const [date, record] of fetched) {
      dayRecords.set(date, record)
    }
    try {
      await writeDays([...fetched.values()])
    } catch (error) {
      console.error('Error caching AWS cost data:', error)
    }
  }
 
  const series = buildSeries(dates, dayRecords, granularity, environment)
  const totalCost = series.reduce((sum, entry) => sum + entry.total, 0)
 
  return {
    statusCode: 200,
    headers: {
      'Content-Type': 'application/json',
      'Access-Control-Allow-Origin': '*'
    },
    body: JSON.stringify({
      currency: 'USD',
      granularity,
      environment,
      availableEnvironments: availableEnvironmentsFrom(dates, dayRecords),
      totalCost,
      series
    })
  }
}
 
exports.handler = requirePlatformAdmin(analyticsCostsHandler)