fix(storage): count a finished Bunny upload the moment it lands

Two reasons the number on the storage page could read as nothing.

The per-user Bunny figure was computed inside a two minute cache. The declared
size lands on the row in the same transaction that deletes the reservation, so
for up to two minutes an upload that had just succeeded counted as nothing:
usage fell back towards zero and the next upload was measured against a total
that ignored the one before it. The call to Bunny stays cached, because it is
the slow half and its answer is the same for everybody. The join against our own
rows is now read fresh, per user, on every check.

A failed call to Bunny returned an empty map before it had looked at a single
row, so an account with gigabytes of declared uploads read as empty whenever
Bunny was unreachable. Bunny's figure being gone is not a reason to forget the
sizes we wrote down ourselves.

The rule for which of the two numbers to charge is unchanged, and the comment
above it now says why rather than guessing. What Bunny reports mid-encode is
partial: storageSize counts what has been written so far and climbs as each
rendition lands. A six minute cut uploaded at 2.5 GB read as 475 MB halfway
through and settled above 3 GB once it finished, because Bunny keeps the
original alongside every rendition. Taking the larger of the declared size and
Bunny's is right at every point on that curve; taking Bunny's whenever it is
non-zero would hand most of the quota back in the middle of an encode.

The settings card also claimed a 200 GB limit while showing a 3 GB one, and told
a trial account to delete files or contact support.
This commit is contained in:
2026-08-18 11:42:30 +03:00
parent 2c4c6101d5
commit 63288761ed
8 changed files with 328 additions and 65 deletions
+16 -9
View File
@@ -32,11 +32,13 @@ import {
enforceStorageQuota,
reserveStorageQuota,
releaseStorageReservation,
getStorageLimitForUser,
getStorageContextForUser,
storageExceededResponse,
UPLOAD_RESERVATION_PURPOSES,
type StorageContext,
type UploadReservationPurpose,
} from '@/lib/storage-quota';
import { getCachedUserBunnyStorage } from '@/lib/admin-stats';
import { getUserBunnyStorageBytes } from '@/lib/admin-stats';
import { isStripeFeatureEnabled } from '@/lib/feature-flags';
// Sentinel thrown inside a Prisma transaction when a fake reservationId is
@@ -307,6 +309,9 @@ export async function POST(request: NextRequest, { params }: RouteParams) {
// was still in flight.
let reservationPurpose: UploadReservationPurpose | null = null;
let reservationBilledUserId: string | null = null;
// Carried out of the try so the quota refusal in the catch can be worded for
// the account it is refusing, rather than telling a trial to delete files.
let storageForRefusal: StorageContext | null = null;
let finalizedR2AssetSession: {
sessionId: string;
reservationId: string | null;
@@ -582,14 +587,15 @@ export async function POST(request: NextRequest, { params }: RouteParams) {
// quota check below, Bunny included. Leaving Bunny out read its own storage as
// zero, and on an account whose storage is all Bunny that made the fallback a
// check that could not fail.
const preFetchedBunnyData =
provider === VideoAssetProvider.YOUTUBE ? null : await getCachedUserBunnyStorage();
const preFetchedBunnyBytes =
provider === VideoAssetProvider.YOUTUBE ? null : await getUserBunnyStorageBytes(billedUserId);
// The ceiling this account is actually held to, read for the fallback below.
// It used to compare against the plan limit, which is 200 GiB whoever is
// asking: a caller who quoted a reservation id that no longer existed was
// measured against the paid ceiling even on a trial worth 3 GiB.
const storageLimitBytes = await getStorageLimitForUser(billedUserId);
const storage = await getStorageContextForUser(billedUserId);
storageForRefusal = storage;
// Create the VideoAsset and atomically consume the upload reservation (if any)
// so the spot is never double-counted.
@@ -631,12 +637,11 @@ export async function POST(request: NextRequest, { params }: RouteParams) {
WHERE "billedUserId" = ${billedUserId}
AND "expiresAt" > NOW()
`;
const bunnyData = preFetchedBunnyData ?? {};
const totalUsed =
(r2Row?.total ?? BigInt(0)) +
(resRow?.total ?? BigInt(0)) +
BigInt(bunnyData[billedUserId] ?? 0);
if (isStripeFeatureEnabled() && totalUsed + assetSizeBytes >= storageLimitBytes) {
BigInt(preFetchedBunnyBytes ?? 0);
if (isStripeFeatureEnabled() && totalUsed + assetSizeBytes >= storage.limitBytes) {
throw new QuotaExceededInTxError();
}
}
@@ -712,7 +717,9 @@ export async function POST(request: NextRequest, { params }: RouteParams) {
return withCacheControl(response, 'private, no-store');
} catch (error) {
if (error instanceof QuotaExceededInTxError) {
return apiErrors.storageExceeded() as NextResponse;
return storageForRefusal
? storageExceededResponse(storageForRefusal)
: (apiErrors.storageExceeded() as NextResponse);
}
await releaseStorageReservation(
reservationId,