Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 26 additions & 6 deletions app/(dashboard)/browser/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,11 @@ import { useDialog } from "@/lib/feedback/dialog"
import { useMessage } from "@/lib/feedback/message"
import { formatDateTime, formatInteger, niceBytes } from "@/lib/functions"
import { normalizeDateToIso } from "@/lib/safe-date"
import { getAccountBucketUsage } from "@/lib/account-bucket-usage"
import {
getAccountBucketUsage,
getAccountBucketDisplayUsage,
getAccountBucketInitialUsage,
} from "@/lib/account-bucket-usage"
import { BucketNameCell, type BucketNameRow } from "@/components/buckets/name-cell"
import { loadBucketPolicyStatuses } from "@/lib/bucket-policy-status"
import { BrowserContent } from "./content"
Expand All @@ -35,7 +39,7 @@ interface BucketRow {
IsPublic?: boolean
}

type BucketViewRow = BucketRow & BucketNameRow
type BucketViewRow = BucketRow & BucketNameRow & { InitialUsage?: boolean }

function BrowserBucketsPage() {
const { t } = useTranslation()
Expand Down Expand Up @@ -146,10 +150,19 @@ function BrowserBucketsPage() {

const usageLoading = accountInfoLoading || !hasFetchedPolicy
const bucketUsage = useMemo(() => getAccountBucketUsage(userInfo), [userInfo])
const displayUsage = useMemo(() => getAccountBucketDisplayUsage(userInfo), [userInfo])
const initialUsage = useMemo(() => getAccountBucketInitialUsage(userInfo), [userInfo])
useEffect(() => {
if (!hasFetchedPolicy || data.length === 0) return
const timer = window.setInterval(() => {
if (document.visibilityState === "visible") void fetchUserPolicy()
Comment thread
cxymds marked this conversation as resolved.
Resolved
}, 30000)
return () => window.clearInterval(timer)
}, [hasFetchedPolicy, data.length, fetchUserPolicy])
const rowsWithUsage = useMemo(
() =>
data.map((row) => {
const usage = bucketUsage.get(row.Name)
const usage = displayUsage.get(row.Name)
const BucketHref = `/browser?bucket=${encodeURIComponent(row.Name)}`
if (!usage) return { ...row, BucketHref }

Expand All @@ -159,9 +172,10 @@ function BrowserBucketsPage() {
Count: usage.objectsCount,
Size: niceBytes(String(usage.sizeBytes)),
SizeBytes: usage.sizeBytes,
InitialUsage: usage.initial,
}
}),
[bucketUsage, data],
[displayUsage, data],
)
const filteredData = useMemo(
() =>
Expand Down Expand Up @@ -193,7 +207,12 @@ function BrowserBucketsPage() {
meta: { align: "end" },
cell: ({ row }) =>
typeof row.original.Count === "number" ? (
formatInteger(row.original.Count)
<span>
{formatInteger(row.original.Count)}
{row.original.InitialUsage && (
<span className="ms-2 text-xs text-muted-foreground">{t("Initial statistics")}</span>
)}
</span>
) : usageLoading ? (
<Spinner className="size-3 text-muted-foreground" />
) : (
Expand Down Expand Up @@ -319,9 +338,10 @@ function BrowserBucketsPage() {
<BucketUsageOverview
names={data.map((bucket) => bucket.Name)}
usage={bucketUsage}
initialUsage={initialUsage}
unavailable={pending || loadError}
usageLoading={pending || usageLoading}
usageAvailable={!usageLoading && Array.isArray(userInfo?.buckets)}
usageAvailable={Array.isArray(userInfo?.buckets)}
/>

<DataTable
Expand Down
21 changes: 17 additions & 4 deletions components/buckets/list.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import { usePermissions } from "@/hooks/use-permissions"
import { Spinner } from "@/components/ui/spinner"
import { formatDateTime, formatInteger, niceBytes } from "@/lib/functions"
import { normalizeDateToIso } from "@/lib/safe-date"
import { getAccountBucketUsage } from "@/lib/account-bucket-usage"
import { getAccountBucketDisplayUsage } from "@/lib/account-bucket-usage"
import { BucketNameCell, type BucketNameRow } from "@/components/buckets/name-cell"
import { loadBucketPolicyStatuses } from "@/lib/bucket-policy-status"
import type { ColumnDef } from "@tanstack/react-table"
Expand All @@ -27,7 +27,7 @@ export interface BucketListRow {
IsPublic?: boolean
}

type BucketListViewRow = BucketListRow & BucketNameRow
type BucketListViewRow = BucketListRow & BucketNameRow & { InitialUsage?: boolean }

interface BucketListProps {
title: React.ReactNode
Expand Down Expand Up @@ -122,7 +122,14 @@ export function BucketList({ title, emptyDescription, getBucketHref }: BucketLis
}, [fetchBuckets])

const usageLoading = accountInfoLoading || !hasFetchedPolicy
const bucketUsage = React.useMemo(() => getAccountBucketUsage(userInfo), [userInfo])
const bucketUsage = React.useMemo(() => getAccountBucketDisplayUsage(userInfo), [userInfo])
React.useEffect(() => {
if (!hasFetchedPolicy || data.length === 0) return
const timer = window.setInterval(() => {
if (document.visibilityState === "visible") void fetchUserPolicy()
}, 30000)
return () => window.clearInterval(timer)
}, [hasFetchedPolicy, data.length, fetchUserPolicy])
const rowsWithUsage = React.useMemo(
() =>
data.map((row) => {
Expand All @@ -136,6 +143,7 @@ export function BucketList({ title, emptyDescription, getBucketHref }: BucketLis
Count: usage.objectsCount,
Size: niceBytes(String(usage.sizeBytes)),
SizeBytes: usage.sizeBytes,
InitialUsage: usage.initial,
}
}),
[bucketUsage, data, getBucketHref],
Expand Down Expand Up @@ -166,7 +174,12 @@ export function BucketList({ title, emptyDescription, getBucketHref }: BucketLis
meta: { align: "end" },
cell: ({ row }) =>
typeof row.original.Count === "number" ? (
formatInteger(row.original.Count)
<span>
{formatInteger(row.original.Count)}
{row.original.InitialUsage && (
<span className="ms-2 text-xs text-muted-foreground">{t("Initial statistics")}</span>
)}
</span>
) : usageLoading ? (
<Spinner className="size-3 text-muted-foreground" />
) : (
Expand Down
23 changes: 18 additions & 5 deletions components/buckets/usage-overview.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,15 +11,20 @@ export function BucketUsageOverview({
unavailable,
usageAvailable = true,
usageLoading = false,
initialUsage = new Map(),
}: {
names: string[]
usage: Map<string, { objectsCount: number; sizeBytes: number } | null>
usageLoading?: boolean
usageAvailable?: boolean
unavailable: boolean
initialUsage?: ReadonlyMap<string, { objectsCount: number; sizeBytes: number }>
}) {
const { t, i18n } = useTranslation()
const summary = !unavailable && usageAvailable ? summarizeBucketUsage(names, usage) : undefined
const complete = !unavailable && usageAvailable ? summarizeBucketUsage(names, usage) : undefined
const initial = complete && complete.measuredBuckets === 0 ? summarizeBucketUsage(names, initialUsage) : undefined
const showingInitial = initial && initial.measuredBuckets > 0
const summary = showingInitial ? initial : complete
const hasValues = summary && (summary.measuredBuckets > 0 || names.length === 0)
const measurementReported = summary && (names.length === 0 || names.some((name) => usage.has(name)))
const statisticsState = usageLoading
Expand All @@ -33,7 +38,11 @@ export function BucketUsageOverview({
? t("Loading…")
: t("Usage unavailable")
const distribution =
summary && summary.measuredBuckets === names.length && summary.sizeBytes !== undefined && summary.sizeBytes > 0
!showingInitial &&
summary &&
summary.measuredBuckets === names.length &&
summary.sizeBytes !== undefined &&
summary.sizeBytes > 0
? names
.map((name) => ({ name, size: usage.get(name)!.sizeBytes }))
.filter((bucket) => bucket.size > 0)
Expand Down Expand Up @@ -72,15 +81,19 @@ export function BucketUsageOverview({
<dl className="col-span-2 grid grid-cols-2 items-end gap-5 sm:col-span-1 sm:grid-cols-[1.6fr_1fr]">
{summary.sizeBytes !== undefined && (
<div className="min-w-0">
<dt className="text-xs text-muted-foreground">{t("Measured size")}</dt>
<dt className="text-xs text-muted-foreground">
{t(showingInitial ? "Scanned size" : "Measured size")}
</dt>
<dd className="mt-2 break-words font-heading text-4xl font-semibold tracking-tight tabular-nums lg:text-5xl">
{niceBytes(String(summary.sizeBytes))}
</dd>
</div>
)}
{summary.objectsCount !== undefined && (
<div>
<dt className="text-xs text-muted-foreground">{t("Measured objects")}</dt>
<dt className="text-xs text-muted-foreground">
{t(showingInitial ? "Scanned objects" : "Measured objects")}
</dt>
<dd className="mt-2 font-heading text-2xl font-medium tabular-nums">
{formatInteger(summary.objectsCount)}
</dd>
Expand All @@ -101,7 +114,7 @@ export function BucketUsageOverview({
</div>
{hasValues && (
<p className="mt-3 text-xs text-muted-foreground" role="status">
{coverage}
{showingInitial ? t("Initial statistics") : coverage}
</p>
)}
</div>
Expand Down
45 changes: 31 additions & 14 deletions hooks/use-permissions.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,7 @@ export function PermissionsProvider({ children }: { children: React.ReactNode })
const [hasResolvedAdmin, setHasResolvedAdmin] = useState(false)
const [hasFetchedPolicy, setHasFetchedPolicy] = useState(false)
const requestEpochRef = useRef(0)
const userPolicyRequestRef = useRef(0)
const [permissionRevision, setPermissionRevision] = useState(0)
const identityKey = JSON.stringify([
isAuthenticated,
Expand Down Expand Up @@ -166,35 +167,51 @@ export function PermissionsProvider({ children }: { children: React.ReactNode })
const fetchUserPolicy = useCallback(async () => {
if (!api) return
const requestEpoch = requestEpochRef.current
const requestId = userPolicyRequestRef.current + 1
userPolicyRequestRef.current = requestId
// Same-identity refreshes may overlap; only the newest request can publish.
const isCurrentRequest = () =>
requestEpoch === requestEpochRef.current && requestId === userPolicyRequestRef.current

setIsLoading(true)
// /is-admin includes IAM administrators; /account/info reports caller.is_owner.
const ownerRequest = api.get("/account/info", { suppress403Redirect: true }).then(
(info) => {
if (requestEpoch === requestEpochRef.current) setIsOwner((info as { is_admin?: unknown })?.is_admin === true)
if (isCurrentRequest()) setIsOwner((info as { is_admin?: unknown })?.is_admin === true)
},
() => {
if (requestEpoch === requestEpochRef.current) setIsOwner(false)
if (isCurrentRequest()) setIsOwner(false)
},
)
try {
const info = (await api.get("/accountinfo", { suppress403Redirect: true })) as Record<string, unknown>
if (requestEpoch !== requestEpochRef.current) return
setUserInfo(info)
const policyStr = info?.policy as string
if (policyStr) {
setUserPolicy(JSON.parse(policyStr) as ConsolePolicy)
} else {
setUserPolicy(null)
const info = (await api.get("/accountinfo?view=snapshot", { suppress403Redirect: true })) as Record<
string,
unknown
>
if (!isCurrentRequest()) return
const policyStr = info?.policy
if (policyStr !== undefined && policyStr !== null && typeof policyStr !== "string") {
throw new SyntaxError("Account policy must be a JSON string")
}
const nextPolicy = policyStr ? (JSON.parse(policyStr) as ConsolePolicy) : null
setUserInfo(info)
setUserPolicy(nextPolicy)
permissionClient.invalidate()
} catch (e) {
if (requestEpoch !== requestEpochRef.current) return
if (!isCurrentRequest()) return
console.error("Failed to fetch user policy", e)
setUserInfo(null)
setUserPolicy(null)
const status = e && typeof e === "object" && "status" in e ? e.status : undefined
const temporaryFailure =
!(e instanceof SyntaxError) &&
(status === undefined || (typeof status === "number" && status >= 500 && status < 600))
// Transient failures retain this identity's last successful snapshot.
if (!temporaryFailure) {
setUserInfo(null)
setUserPolicy(null)
permissionClient.invalidate()
}
} finally {
if (requestEpoch === requestEpochRef.current) {
if (isCurrentRequest()) {
setIsLoading(false)
setHasFetchedPolicy(true)
}
Expand Down
3 changes: 3 additions & 0 deletions i18n/locales/ar-MA.json
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
{
"Initial statistics": "الإحصاءات الأولية · غير مكتملة",
"Scanned size": "الحجم الذي تم فحصه",
"Scanned objects": "الكائنات التي تم فحصها",
"Statistics pending": "في انتظار الإحصاءات",
"Statistics unavailable": "الإحصاءات غير متاحة",
"Cluster scanner status": "حالة ماسح العنقود",
Expand Down
3 changes: 3 additions & 0 deletions i18n/locales/de-DE.json
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
{
"Initial statistics": "Erste Statistik · Unvollständig",
"Scanned size": "Erfasste Größe",
"Scanned objects": "Erfasste Objekte",
"Statistics pending": "Statistik ausstehend",
"Statistics unavailable": "Statistik nicht verfügbar",
"Cluster scanner status": "Scannerstatus des Clusters",
Expand Down
3 changes: 3 additions & 0 deletions i18n/locales/en-US.json
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
{
"Initial statistics": "Initial statistics · Partial",
"Scanned size": "Scanned size",
"Scanned objects": "Scanned objects",
"Statistics pending": "Awaiting statistics",
"Statistics unavailable": "Statistics unavailable",
"Cluster scanner status": "Cluster scanner status",
Expand Down
3 changes: 3 additions & 0 deletions i18n/locales/es-ES.json
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
{
"Initial statistics": "Estadísticas iniciales · Parciales",
"Scanned size": "Tamaño analizado",
"Scanned objects": "Objetos analizados",
"Statistics pending": "Estadísticas pendientes",
"Statistics unavailable": "Estadísticas no disponibles",
"Cluster scanner status": "Estado del escáner del clúster",
Expand Down
3 changes: 3 additions & 0 deletions i18n/locales/fr-FR.json
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
{
"Initial statistics": "Premières statistiques · Partielles",
"Scanned size": "Taille analysée",
"Scanned objects": "Objets analysés",
"Statistics pending": "Statistiques en attente",
"Statistics unavailable": "Statistiques indisponibles",
"Cluster scanner status": "État de l’analyse du cluster",
Expand Down
3 changes: 3 additions & 0 deletions i18n/locales/id-ID.json
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
{
"Initial statistics": "Statistik awal · Belum lengkap",
"Scanned size": "Ukuran dipindai",
"Scanned objects": "Objek dipindai",
"Statistics pending": "Menunggu statistik",
"Statistics unavailable": "Statistik tidak tersedia",
"Cluster scanner status": "Status pemindai klaster",
Expand Down
3 changes: 3 additions & 0 deletions i18n/locales/it-IT.json
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
{
"Initial statistics": "Statistiche iniziali · Parziali",
"Scanned size": "Dimensione analizzata",
"Scanned objects": "Oggetti analizzati",
"Statistics pending": "Statistiche in attesa",
"Statistics unavailable": "Statistiche non disponibili",
"Cluster scanner status": "Stato della scansione del cluster",
Expand Down
3 changes: 3 additions & 0 deletions i18n/locales/ja-JP.json
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
{
"Initial statistics": "初回統計 · 未完了",
"Scanned size": "スキャン済みサイズ",
"Scanned objects": "スキャン済みオブジェクト",
"Statistics pending": "統計待ち",
"Statistics unavailable": "統計を取得できません",
"Cluster scanner status": "クラスターのスキャナー状態",
Expand Down
3 changes: 3 additions & 0 deletions i18n/locales/ko-KR.json
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
{
"Initial statistics": "첫 통계 · 미완료",
"Scanned size": "스캔된 용량",
"Scanned objects": "스캔된 객체",
"Statistics pending": "통계 대기 중",
"Statistics unavailable": "통계를 사용할 수 없음",
"Cluster scanner status": "클러스터 스캐너 상태",
Expand Down
3 changes: 3 additions & 0 deletions i18n/locales/pt-BR.json
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
{
"Initial statistics": "Estatísticas iniciais · Parciais",
"Scanned size": "Tamanho verificado",
"Scanned objects": "Objetos verificados",
"Statistics pending": "Estatísticas pendentes",
"Statistics unavailable": "Estatísticas indisponíveis",
"Cluster scanner status": "Estado do scanner do cluster",
Expand Down
3 changes: 3 additions & 0 deletions i18n/locales/ru-RU.json
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
{
"Initial statistics": "Первичная статистика · Неполная",
"Scanned size": "Просканированный объём",
"Scanned objects": "Просканированные объекты",
"Statistics pending": "Статистика ожидается",
"Statistics unavailable": "Статистика недоступна",
"Cluster scanner status": "Состояние сканера кластера",
Expand Down
3 changes: 3 additions & 0 deletions i18n/locales/tr-TR.json
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
{
"Initial statistics": "İlk istatistikler · Kısmi",
"Scanned size": "Taranan boyut",
"Scanned objects": "Taranan nesneler",
"Statistics pending": "İstatistikler bekleniyor",
"Statistics unavailable": "İstatistikler kullanılamıyor",
"Cluster scanner status": "Küme tarayıcısının durumu",
Expand Down
3 changes: 3 additions & 0 deletions i18n/locales/vi-VN.json
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
{
"Initial statistics": "Thống kê đầu tiên · Chưa hoàn tất",
"Scanned size": "Dung lượng đã quét",
"Scanned objects": "Đối tượng đã quét",
"Statistics pending": "Chờ thống kê",
"Statistics unavailable": "Không có thống kê",
"Cluster scanner status": "Trạng thái trình quét của cụm",
Expand Down
3 changes: 3 additions & 0 deletions i18n/locales/zh-CN.json
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
{
"Initial statistics": "首次统计 · 未完成",
"Scanned size": "已扫描容量",
"Scanned objects": "已扫描对象数",
"Statistics pending": "待统计",
"Statistics unavailable": "统计不可用",
"Cluster scanner status": "集群扫描器状态",
Expand Down
3 changes: 3 additions & 0 deletions i18n/locales/zh-TW.json
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
{
"Initial statistics": "首次統計 · 未完成",
"Scanned size": "已掃描容量",
"Scanned objects": "已掃描物件數",
"Statistics pending": "待統計",
"Statistics unavailable": "統計無法取得",
"Cluster scanner status": "叢集掃描器狀態",
Expand Down
Loading