All files / src/components AdminLambdaStatsPanel.vue

100% Statements 55/55
96.61% Branches 57/59
100% Functions 14/14
100% Lines 50/50

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  82x 2x 2x                             2x     231x                   9x                 60x       2x 2x 2x 2x     2x                 2x                                         17x                                                                       23x 23x 23x 23x   23x                     23x 23x     23x     74x   8x   4x       4x   58x           23x 29x 29x 37x 37x   37x     37x         9x 2x 2x   7x 7x       231x 33x       231x 33x         60x 59x       2x 2x 1x   1x       23x                                    
<template>
  <div class="admin-lambda-stats-panel">
    <p class="text-muted">{{ t('admin.lambdaStatsDescription') }}</p>
    <p class="text-muted small">{{ t('admin.freeOverrideNote') }}</p>
 
    <ErrorAlert
      v-if="adminStore.lambdaStatsError"
      :title="t('common.error')"
      :message="adminStore.lambdaStatsError"
    />
    <LoadingSpinner v-if="adminStore.lambdaStatsLoading && adminStore.lambdaStats.length === 0" />
 
    <template v-else-if="!adminStore.lambdaStatsError">
      <p v-if="adminStore.lambdaStats.length === 0" class="text-muted">
        {{ t('admin.noLambdaStatsFound') }}
      </p>
 
      <div v-else class="table-responsive">
        <table class="table table-hover align-middle">
          <thead>
            <tr>
              <th
                v-for="col in columns"
                :key="col.key"
                :class="{ 'text-end': col.numeric }"
                :aria-sort="ariaSort(col.key)"
              >
                <button
                  type="button"
                  class="btn btn-link p-0 text-reset fw-bold text-decoration-none sort-header"
                  :data-sort-key="col.key"
                  @click="sortBy(col.key)"
                >
                  {{ t(col.labelKey) }}
                  <font-awesome-icon :icon="sortIcon(col.key)" class="ms-1 sort-icon" />
                </button>
              </th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="fn in sortedStats" :key="fn.functionKey">
              <td>
                <code>{{ fn.functionKey }}</code>
              </td>
              <td class="text-end">{{ fn.invocationCount.toLocaleString() }}</td>
              <td class="text-end">{{ fn.avgDurationMs.toLocaleString() }} ms</td>
              <td class="text-end">{{ formatDuration(fn.totalDurationMs) }}</td>
              <td class="text-end">{{ formatPercent(fn.timeSharePercent) }}</td>
              <td>{{ formatDateTime(fn.lastSeenAt) || '—' }}</td>
              <td>
                <div class="form-check form-switch mb-0">
                  <input
                    :id="`free-override-${fn.functionKey}`"
                    class="form-check-input"
                    type="checkbox"
                    role="switch"
                    :aria-label="t('admin.freeOverrideLabel')"
                    :checked="!!fn.freeOverride"
                    :disabled="adminStore.lambdaBillingSavingKey === fn.functionKey"
                    @change="toggleFree(fn, ($event.target as HTMLInputElement).checked)"
                  />
                  <label class="form-check-label" :for="`free-override-${fn.functionKey}`">
                    <span
                      class="badge"
                      :class="fn.credits.billed ? 'bg-warning text-dark' : 'bg-secondary'"
                    >
                      {{ fn.credits.billed ? t('admin.creditsBilled') : t('admin.creditsFree') }}
                    </span>
                  </label>
                </div>
                <span
                  v-if="fn.credits.billed && fn.credits.billing === 'conditional'"
                  class="text-muted small ms-1"
                >
                  ({{ t('admin.creditsConditionalNote') }})
                </span>
                <ul
                  v-if="fn.credits.billed && fn.credits.pools.length"
                  class="credit-pools-list mb-0 mt-1"
                >
                  <li v-for="p in fn.credits.pools" :key="p.pool">{{ p.pool }}: {{ p.rate }}</li>
                </ul>
                <div v-if="fn.freeOverride" class="text-muted small mt-1">
                  {{ t('admin.freeOverrideSince') }}
                  {{ formatDate(fn.freeOverride.updatedAt) }}
                </div>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </template>
  </div>
</template>
 
<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
import { useAdminStore, type LambdaStatEntry } from '@/stores/admin'
import { useUILanguage } from '@/composables/useUILanguage'
import { useDateFormat } from '@/composables/useDateFormat'
import { formatDuration } from '@/utils/formatDuration'
import { useToastStore } from '@/stores/toast'
import { getErrorMessage } from '@/utils/errors'
import LoadingSpinner from '@/components/LoadingSpinner.vue'
import ErrorAlert from '@/components/ErrorAlert.vue'
 
type SortKey =
  | 'functionKey'
  | 'invocationCount'
  | 'avgDurationMs'
  | 'totalDurationMs'
  | 'timeSharePercent'
  | 'lastSeenAt'
  | 'credits'
type SortDirection = 'asc' | 'desc'
 
const adminStore = useAdminStore()
const toastStore = useToastStore()
const { t } = useUILanguage()
const { formatDate, formatDateTime } = useDateFormat()
 
const columns: Array<{ key: SortKey; labelKey: string; numeric: boolean }> = [
  { key: 'functionKey', labelKey: 'admin.colFunction', numeric: false },
  { key: 'invocationCount', labelKey: 'admin.colInvocations', numeric: true },
  { key: 'avgDurationMs', labelKey: 'admin.colAvgDuration', numeric: true },
  { key: 'totalDurationMs', labelKey: 'admin.colTotalTime', numeric: true },
  { key: 'timeSharePercent', labelKey: 'admin.colTimeShare', numeric: true },
  { key: 'lastSeenAt', labelKey: 'admin.colLastSeen', numeric: false },
  { key: 'credits', labelKey: 'admin.colLambdaCredits', numeric: false }
]
 
// Same order the API returns (busiest first) until the admin picks another.
const sortKey = ref<SortKey>('invocationCount')
const sortDirection = ref<SortDirection>('desc')
 
// A text column reads naturally A→Z first, a number or date biggest/latest first.
const TEXT_KEYS: SortKey[] = ['functionKey']
 
function sortValue(fn: LambdaStatEntry, key: SortKey): string | number {
  switch (key) {
    case 'functionKey':
      return fn.functionKey
    case 'lastSeenAt':
      return fn.lastSeenAt ? new Date(fn.lastSeenAt).getTime() : 0
    case 'credits':
      // A function that costs nothing — naturally or via an "always free"
      // override — sorts below any that does, then by how many pools apply
      return fn.credits.billed ? fn.credits.pools.length : 0
    default:
      return fn[key]
  }
}
 
// Sorting happens client-side: the list is one row per Lambda (a bounded,
// code-defined set, not user data), already fully loaded in one response.
const sortedStats = computed(() => {
  const factor = sortDirection.value === 'asc' ? 1 : -1
  return [...adminStore.lambdaStats].sort((a, b) => {
    const left = sortValue(a, sortKey.value)
    const right = sortValue(b, sortKey.value)
    const result =
      typeof left === 'string' && typeof right === 'string'
        ? left.localeCompare(right)
        : (left as number) - (right as number)
    return result * factor || a.functionKey.localeCompare(b.functionKey)
  })
})
 
function sortBy(key: SortKey) {
  if (sortKey.value === key) {
    sortDirection.value = sortDirection.value === 'asc' ? 'desc' : 'asc'
    return
  }
  sortKey.value = key
  sortDirection.value = TEXT_KEYS.includes(key) ? 'asc' : 'desc'
}
 
function ariaSort(key: SortKey): 'ascending' | 'descending' | 'none' {
  if (sortKey.value !== key) return 'none'
  return sortDirection.value === 'asc' ? 'ascending' : 'descending'
}
 
function sortIcon(key: SortKey): string {
  if (sortKey.value !== key) return 'fa-solid fa-sort'
  return sortDirection.value === 'asc' ? 'fa-solid fa-sort-up' : 'fa-solid fa-sort-down'
}
 
// A share that rounds to 0.0 would read as "no time at all" for a function that did run
function formatPercent(value: number): string {
  if (value > 0 && value < 0.1) return '< 0.1 %'
  return `${value.toLocaleString(undefined, { minimumFractionDigits: 1, maximumFractionDigits: 1 })} %`
}
 
async function toggleFree(fn: LambdaStatEntry, free: boolean) {
  try {
    await adminStore.updateLambdaBilling(fn.functionKey, free)
    toastStore.success(free ? t('admin.freeOverrideEnabled') : t('admin.freeOverrideDisabled'))
  } catch (err) {
    toastStore.error(getErrorMessage(err, t('admin.freeOverrideError'), t))
  }
}
 
onMounted(() => adminStore.fetchLambdaStats())
</script>
 
<style scoped>
.sort-icon {
  opacity: 0.6;
}
 
[aria-sort='none'] .sort-icon {
  opacity: 0.25;
}
 
.credit-pools-list {
  padding-left: 1.1rem;
  font-size: 0.8rem;
  color: var(--bs-secondary-color);
}
</style>