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
10 changes: 10 additions & 0 deletions pm-stack/cloudflare-export/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,16 @@ append-only `history.jsonl`:
}
```

`r2Buckets` is the complete bucket-name enumeration (every
`result_info.total_pages` page followed). When enumeration is
unavailable or cannot be proven complete — a non-200 answer, a
missing/malformed `result.buckets`, a failed later page, or a full
page with no pagination metadata — the document keeps `status: "ok"`
and all GraphQL metrics but records `"r2Buckets": null` plus a
`r2BucketsDetail` string naming the failed page and reason (#2574).
A partial list is never published as complete; 401/403 still throws
the `token-scope` contract above.

## Failure states (fail-closed)

A failed tick writes a failure document with `status`,
Expand Down
62 changes: 58 additions & 4 deletions pm-stack/cloudflare-export/cloudflare-quota-export.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -361,7 +361,7 @@ export function classifyBilling(probes) {
};
}

export function successDocument({ measuredAt, cycleStart, accountId, billing, parsed, r2Buckets }) {
export function successDocument({ measuredAt, cycleStart, accountId, billing, parsed, r2Buckets, r2BucketsDetail }) {
return {
service: "cloudflare",
source: SOURCE,
Expand All @@ -371,6 +371,9 @@ export function successDocument({ measuredAt, cycleStart, accountId, billing, pa
accountId,
billing,
r2Buckets,
// Present ONLY when enumeration failed: the list is explicitly
// unknown, never a silent [] or a truncated page (#2574).
...(r2BucketsDetail ? { r2BucketsDetail } : {}),
...(parsed.r2Unclassified?.length ? { r2UnclassifiedActions: parsed.r2Unclassified } : {}),
// #2287: the alerts array is present ONLY when a day is firing, so
// consumers can key on its presence; saturation of the grouped
Expand Down Expand Up @@ -494,9 +497,11 @@ export async function run({ token, accountId, now = new Date() } = {}) {

// R2 bucket enumeration directly (names only) — the storage figure
// itself comes from the analytics dataset, not the tracker prose.
const buckets = await apiJson(`/accounts/${acct}/r2/buckets?per_page=100`, token);
if (buckets.status === 401 || buckets.status === 403) throw scopeError("GET r2/buckets", buckets.status);
const r2Buckets = (buckets.body?.result?.buckets ?? []).map((b) => b.name).filter(Boolean);
// Enumeration is informational beside the independent GraphQL total:
// when it is unavailable or cannot be proven complete it is encoded
// as explicitly unknown (null + r2BucketsDetail), never published as
// an empty or partial list (#2574).
const { buckets: r2Buckets, detail: r2BucketsDetail } = await listR2Buckets(acct, token);

const start = cycleStartUtc(now);
const gql = await apiJson("/graphql", token, {
Expand Down Expand Up @@ -541,9 +546,58 @@ export async function run({ token, accountId, now = new Date() } = {}) {
billing,
parsed,
r2Buckets,
r2BucketsDetail,
});
}

// R2 bucket enumeration with honest pagination (#2574). Returns
// { buckets, detail }: buckets is the complete name list, or null when
// enumeration is unavailable or cannot be proven complete — with detail
// saying which page failed and why. 401/403 still throw scopeError (the
// token-scope contract); every other failure degrades to unknown while
// the GraphQL metrics continue, because the list is informational
// beside the independent storage total.
const R2_BUCKETS_PER_PAGE = 100;

export async function listR2Buckets(acct, token) {
const names = [];
let page = 1;
for (;;) {
const res = await apiJson(`/accounts/${acct}/r2/buckets?per_page=${R2_BUCKETS_PER_PAGE}&page=${page}`, token);
if (res.status === 401 || res.status === 403) throw scopeError("GET r2/buckets", res.status);
if (res.status !== 200) {
return {
buckets: null,
detail: `GET r2/buckets page ${page}: HTTP ${res.status} — enumeration unavailable, GraphQL storage total unaffected`,
};
}
const list = res.body?.result?.buckets;
if (!Array.isArray(list)) {
return {
buckets: null,
detail: `GET r2/buckets page ${page}: result.buckets missing or malformed — enumeration unknown`,
};
}
for (const b of list) {
if (typeof b?.name === "string" && b.name) names.push(b.name);
}
const totalPages = res.body?.result_info?.total_pages;
if (Number.isInteger(totalPages) && totalPages >= 1) {
if (page >= totalPages) return { buckets: names, detail: null };
page += 1;
continue;
}
// No usable pagination metadata: a short page proves nothing more
// follows, but a full page may hide further buckets — report unknown
// rather than a possibly truncated list.
if (list.length < R2_BUCKETS_PER_PAGE) return { buckets: names, detail: null };
return {
buckets: null,
detail: `GET r2/buckets page ${page}: full page with no result_info.total_pages — list may be truncated, enumeration unknown`,
};
}
}

async function writeOutputs(outDir, doc) {
await mkdir(outDir, { recursive: true });
const latest = join(outDir, "latest.json");
Expand Down
107 changes: 107 additions & 0 deletions pm-stack/cloudflare-export/cloudflare-quota-export.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import {
ExportError,
failureDocument,
foldKv,
listR2Buckets,
parseGraphqlUsage,
R2_STORAGE_GROUP_LIMIT,
run,
Expand Down Expand Up @@ -492,3 +493,109 @@ test("measurement strings use plain decimals; request counts remain integers (#2
);
}
});

// #2574: R2 bucket enumeration is explicit — unknown is null plus a
// detail, never a silent [] or a truncated page. Bucket pages are
// consumed in order for /r2/buckets; billing probes and GraphQL stay
// benign so the document's metrics prove the degradation is isolated.
function bucketPage(names, { page = 1, totalPages } = {}) {
return {
status: 200,
body: {
result: { buckets: names.map((name) => ({ name })) },
...(totalPages === undefined ? {} : {
result_info: { page, per_page: 100, total_pages: totalPages, count: names.length, total_count: 150 },
}),
},
};
}

async function runWithBuckets(bucketPages) {
let i = 0;
const prev = globalThis.fetch;
globalThis.fetch = async (url) => {
const u = String(url);
if (u.includes("/r2/buckets")) {
const p = bucketPages[Math.min(i++, bucketPages.length - 1)];
return { status: p.status, json: async () => p.body };
}
if (u.includes("/graphql")) {
return { status: 200, json: async () => ({ data: { viewer: { accounts: [ACCOUNT] } } }) };
}
return { status: 200, json: async () => ({}) };
};
try {
return await run({ token: "tok", accountId: "acct", now: NOW });
} finally {
globalThis.fetch = prev;
}
}

test("run: an HTTP 500 on buckets keeps metrics and marks enumeration unknown (#2574)", async () => {
const doc = await runWithBuckets([{ status: 500, body: {} }]);
assert.equal(doc.status, "ok");
assert.equal(doc.metrics.length, 11); // GraphQL metrics survive
assert.equal(doc.r2Buckets, null);
assert.match(doc.r2BucketsDetail, /HTTP 500/);
});

test("run: missing or malformed result.buckets marks enumeration unknown (#2574)", async () => {
for (const body of [{}, { result: {} }, { result: { buckets: "nope" } }, { result: { buckets: null } }]) {
const doc = await runWithBuckets([{ status: 200, body }]);
assert.equal(doc.status, "ok");
assert.equal(doc.r2Buckets, null);
assert.match(doc.r2BucketsDetail, /missing or malformed/);
}
});

test("run: pagination follows every reported page (#2574)", async () => {
const first = Array.from({ length: 100 }, (_, i) => `b${i}`);
const rest = Array.from({ length: 50 }, (_, i) => `b${100 + i}`);
const doc = await runWithBuckets([bucketPage(first, { page: 1, totalPages: 2 }), bucketPage(rest, { page: 2, totalPages: 2 })]);
assert.equal(doc.status, "ok");
assert.equal(doc.r2Buckets.length, 150);
assert.equal(doc.r2Buckets[0], "b0");
assert.equal(doc.r2Buckets[149], "b149");
assert.equal("r2BucketsDetail" in doc, false);
});

test("run: a later-page failure publishes unknown, never the partial list (#2574)", async () => {
const first = Array.from({ length: 100 }, (_, i) => `b${i}`);
const doc = await runWithBuckets([
bucketPage(first, { page: 1, totalPages: 2 }),
{ status: 500, body: {} },
]);
assert.equal(doc.status, "ok");
assert.equal(doc.r2Buckets, null); // not the 100-name partial page
assert.match(doc.r2BucketsDetail, /page 2/);
});

test("run: a malformed later page publishes unknown, never the partial list (#2574)", async () => {
const first = Array.from({ length: 100 }, (_, i) => `b${i}`);
const doc = await runWithBuckets([
bucketPage(first, { page: 1, totalPages: 2 }),
{ status: 200, body: { result: { buckets: "nope" } } },
]);
assert.equal(doc.r2Buckets, null);
assert.match(doc.r2BucketsDetail, /page 2/);
});

test("run: a full page with no pagination metadata is unknown, not complete (#2574)", async () => {
const full = Array.from({ length: 100 }, (_, i) => `b${i}`);
const doc = await runWithBuckets([bucketPage(full)]);
assert.equal(doc.r2Buckets, null);
assert.match(doc.r2BucketsDetail, /truncated/);
// A short page without metadata is still provably complete (existing shape).
const short = await runWithBuckets([bucketPage(["b1"])]);
assert.deepEqual(short.r2Buckets, ["b1"]);
assert.equal("r2BucketsDetail" in short, false);
});

test("run: 401/403 on buckets still throws the token-scope contract (#2574)", async () => {
await assert.rejects(runWithBuckets([{ status: 403, body: {} }]), (e) => {
assert.ok(e instanceof ExportError);
assert.equal(e.status, "token-scope");
assert.equal(e.exitCode, 3);
return true;
});
});