feat(admin): track and display per-user download egress for Bunny version downloads

This commit is contained in:
Yusuf İpek
2026-02-22 20:19:55 +03:00
parent bbae612a70
commit 609b33bbcb
5 changed files with 116 additions and 5 deletions
+1 -1
View File
@@ -18,7 +18,7 @@ export default async function AdminLayout({
return (
<div className="relative flex min-h-screen flex-col">
<Header user={session.user} />
<div className="container mx-auto px-4 md:px-8 flex-1 items-start md:grid md:grid-cols-[220px_minmax(0,1fr)] md:gap-6 lg:grid-cols-[240px_minmax(0,1fr)] lg:gap-10">
<div className="w-full px-4 md:px-8 flex-1 items-start md:grid md:grid-cols-[220px_minmax(0,1fr)] md:gap-6 lg:grid-cols-[240px_minmax(0,1fr)] lg:gap-10">
{/* Mobile Nav */}
<div className="md:hidden py-4 border-b mb-4">
<nav className="flex items-center gap-4 overflow-x-auto">
+19 -3
View File
@@ -5,6 +5,7 @@ import { redirect } from 'next/navigation';
import {
getCachedBunnyStorageStats,
getCachedUserBunnyStorage,
getCachedUserDownloadEgress,
getCachedUserMediaStorage
} from '@/lib/admin-stats';
import { Film, HardDrive } from 'lucide-react';
@@ -33,6 +34,7 @@ type SortBy =
| 'projectsOwned'
| 'totalComments'
| 'bunnyUpload'
| 'downloadEgress'
| 'mediaStorage';
type SortDirection = 'asc' | 'desc';
@@ -45,6 +47,7 @@ const SORTABLE_COLUMNS: SortBy[] = [
'projectsOwned',
'totalComments',
'bunnyUpload',
'downloadEgress',
'mediaStorage',
];
@@ -90,7 +93,7 @@ export default async function AdminUsersPage({
? resolvedSearchParams.sortDirection
: getDefaultSortDirection(sortBy);
const [users, userStorage, userBunnyStorage, bunnyStorageStats] = await Promise.all([
const [users, userStorage, userBunnyStorage, userDownloadEgress, bunnyStorageStats] = await Promise.all([
db.user.findMany({
orderBy: { createdAt: 'desc' },
select: {
@@ -118,6 +121,7 @@ export default async function AdminUsersPage({
}),
getCachedUserMediaStorage(),
getCachedUserBunnyStorage(),
getCachedUserDownloadEgress(),
getCachedBunnyStorageStats(),
]);
@@ -128,6 +132,7 @@ export default async function AdminUsersPage({
0
),
bunnyUploadBytes: userBunnyStorage[user.id] || 0,
downloadEgressBytes: userDownloadEgress[user.id] || 0,
mediaStorageBytes: userStorage[user.id]?.total || 0,
}));
@@ -150,6 +155,8 @@ export default async function AdminUsersPage({
comparison = a._count.comments - b._count.comments;
} else if (sortBy === 'bunnyUpload') {
comparison = a.bunnyUploadBytes - b.bunnyUploadBytes;
} else if (sortBy === 'downloadEgress') {
comparison = a.downloadEgressBytes - b.downloadEgressBytes;
} else if (sortBy === 'mediaStorage') {
comparison = a.mediaStorageBytes - b.mediaStorageBytes;
}
@@ -193,7 +200,7 @@ export default async function AdminUsersPage({
};
return (
<div className="flex-1 space-y-4 px-4 md:px-8">
<div className="flex-1 space-y-4">
<div className="flex items-center justify-between space-y-2">
<h2 className="text-3xl font-bold tracking-tight">Users</h2>
</div>
@@ -275,6 +282,12 @@ export default async function AdminUsersPage({
<span className="text-xs">{getSortIndicator('bunnyUpload', sortBy, sortDirection)}</span>
</Link>
</TableHead>
<TableHead className="text-right">
<Link href={buildSortHref('downloadEgress')} className="inline-flex items-center justify-end gap-1 hover:underline">
Download Egress (Est.)
<span className="text-xs">{getSortIndicator('downloadEgress', sortBy, sortDirection)}</span>
</Link>
</TableHead>
<TableHead className="text-right">
<Link href={buildSortHref('mediaStorage')} className="inline-flex items-center justify-end gap-1 hover:underline">
Media Storage
@@ -286,7 +299,7 @@ export default async function AdminUsersPage({
<TableBody>
{paginatedUsers.length === 0 ? (
<TableRow>
<TableCell colSpan={8} className="h-24 text-center">
<TableCell colSpan={9} className="h-24 text-center">
No users found.
</TableCell>
</TableRow>
@@ -309,6 +322,9 @@ export default async function AdminUsersPage({
<TableCell className="text-right text-sm font-medium">
{formatBytes(user.bunnyUploadBytes)}
</TableCell>
<TableCell className="text-right text-sm font-medium">
{formatBytes(user.downloadEgressBytes)}
</TableCell>
<TableCell className="text-right text-sm">
<div className="flex flex-col items-end">
<span className="font-medium text-foreground">{formatBytes(user.mediaStorageBytes)}</span>
+42 -1
View File
@@ -2,6 +2,7 @@ import { db } from '@/lib/db';
import { auth, checkProjectAccess } from '@/lib/auth';
import { apiErrors, successResponse, withCacheControl } from '@/lib/api-response';
import { rateLimit } from '@/lib/rate-limit';
import { DownloadEgressSource } from '@prisma/client';
type RouteParams = { params: Promise<{ versionId: string }> };
type BunnyDownloadSourcePreference = 'auto' | 'original' | 'compressed';
@@ -304,6 +305,19 @@ function resolveSafeDownloadMetadata(
};
}
function parseEstimatedBytes(contentLengthHeader: string | null): bigint {
if (!contentLengthHeader) return BigInt(0);
const normalized = contentLengthHeader.trim();
if (!/^\d+$/.test(normalized)) return BigInt(0);
try {
const parsed = BigInt(normalized);
return parsed > BigInt(0) ? parsed : BigInt(0);
} catch {
return BigInt(0);
}
}
// GET /api/versions/[versionId]/download
export async function GET(request: Request, { params }: RouteParams) {
try {
@@ -328,7 +342,16 @@ export async function GET(request: Request, { params }: RouteParams) {
include: {
video: {
include: {
project: true,
project: {
include: {
workspace: {
select: {
id: true,
ownerId: true,
},
},
},
},
},
},
},
@@ -415,6 +438,24 @@ export async function GET(request: Request, { params }: RouteParams) {
const contentLength = upstream.headers.get('content-length');
if (contentLength) response.headers.set('Content-Length', contentLength);
try {
await db.downloadEgressEvent.create({
data: {
versionId: version.id,
videoId: version.video.id,
projectId: version.video.project.id,
workspaceId: version.video.project.workspace.id,
billedUserId: version.video.project.workspace.ownerId,
downloaderUserId: session?.user?.id ?? null,
source: source.sourceType === 'original' ? DownloadEgressSource.ORIGINAL : DownloadEgressSource.COMPRESSED,
quality: source.quality,
estimatedBytes: parseEstimatedBytes(contentLength),
},
});
} catch (egressError) {
console.error('Failed to record download egress event:', egressError);
}
return withCacheControl(response, 'private, no-store');
} catch (error) {
console.error('Error downloading version:', error);