GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — Merge pull request #2236 from developing-today/queue/2986-1051-github… · developing-today/code@69091a5

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • pm-stack/aggregator
    • scripts
      • collect-github-billing.ts
    • src
      • model.ts
      • snapshot-records.ts
      • snapshots.ts
      • sources
        • github-billing.ts
    • test
      • github-billing.test.ts
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎pm-stack/aggregator/scripts/collect-github-billing.ts‎

Copy file name to clipboard
+108Lines changed: 108 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,108 @@
1+
#!/usr/bin/env bun
2+
// Daily GitHub billing collector (#1051; hub design §2.2/§5): reads
3+
// the unified billing usage endpoint with the existing gh OAuth token
4+
// (no billing-scoped token needed for the own-account read — the old
5+
// per-product endpoints are gone, 410) and appends per-day §4
6+
// snapshot records to the writers' outbox, which the fleet-feed
7+
// collector drains into the feed and the aggregator ingests into the
8+
// snapshot store. Records carry their usage date, so re-running a
9+
// month re-derives identical records and the store dedupes them.
10+
//
11+
// Runtime home: wherever gh carries the `user` scope — the endpoint
12+
// 404s without it. Today that is the sandbox-side writer context (the
13+
// same home as append-usage-snapshots under stewardship); the
14+
// laptop's gh (gist/read:org/repo/workflow) cannot read it until its
15+
// auth gains `user` via an interactive `gh auth refresh -s user`.
16+
//
17+
// Usage: bun run scripts/collect-github-billing.ts [--year YYYY] [--month M]
18+
// [--user dezren39] [--by <name>] [--print]
19+
// --print write records to stdout instead of the outbox (dry run).
20+
// Env: USAGE_SNAPSHOT_OUTBOX_PATH, GH_BILLING_USER.
21+
import { execFileSync } from "node:child_process";
22+
import { appendFile, mkdir } from "node:fs/promises";
23+
import { homedir } from "node:os";
24+
import { dirname, join } from "node:path";
25+
import type { SnapshotRecord } from "../src/model.ts";
26+
import { isSnapshotRecord, snapshotKey } from "../src/snapshots.ts";
27+
import {
28+
aggregateBillingUsage,
29+
recordsFromBillingUsage,
30+
summarizeBillingDays,
31+
type BillingUsageItem,
32+
} from "../src/sources/github-billing.ts";
33+
34+
const HOME = homedir();
35+
const outboxPath =
36+
process.env.USAGE_SNAPSHOT_OUTBOX_PATH ??
37+
join(
38+
HOME,
39+
"workspace/goals/keep-the-four-repos-healthy/hidden_files/usage-snapshot-outbox.jsonl",
40+
);
41+
42+
function argValue(flag: string): string | undefined {
43+
const i = process.argv.indexOf(flag);
44+
return i >= 0 ? process.argv[i + 1] : undefined;
45+
}
46+
47+
function fetchUsageItems(user: string, year: number, month: number): BillingUsageItem[] {
48+
let out: string;
49+
try {
50+
out = execFileSync(
51+
"gh",
52+
["api", `users/${user}/settings/billing/usage?year=${year}&month=${month}`],
53+
{ encoding: "utf8", maxBuffer: 64 * 1024 * 1024 },
54+
);
55+
} catch (e) {
56+
throw new Error(
57+
`gh api billing usage failed — the endpoint needs a gh token with the "user" scope ` +
58+
`(a 404 here usually means the scope, not a missing user). Underlying error: ${String(e)}`,
59+
);
60+
}
61+
const parsed: unknown = JSON.parse(out);
62+
const items = (parsed as { usageItems?: unknown }).usageItems;
63+
if (!Array.isArray(items)) throw new Error("billing usage response has no usageItems array");
64+
return items as BillingUsageItem[];
65+
}
66+
67+
async function main(): Promise<void> {
68+
const now = new Date();
69+
const year = Number(argValue("--year") ?? now.getUTCFullYear());
70+
const month = Number(argValue("--month") ?? now.getUTCMonth() + 1);
71+
const user = argValue("--user") ?? process.env.GH_BILLING_USER ?? "dezren39";
72+
const observedBy = argValue("--by") ?? "collect-github-billing";
73+
const items = fetchUsageItems(user, year, month);
74+
const totals = summarizeBillingDays(aggregateBillingUsage(items));
75+
console.log(
76+
`collect-github-billing: ${user} ${year}-${String(month).padStart(2, "0")}: ` +
77+
`${items.length} items — actions ${totals.actionsMinutes} min, ` +
78+
`codespaces ${totals.codespacesHours} h, storage ` +
79+
`${Math.round((totals.actionsStorageGbHours + totals.codespacesStorageGbHours) * 1000) / 1000} GB-hours, ` +
80+
`gross $${totals.grossUsd}, net $${totals.netUsd} ` +
81+
`(source: GET /users/${user}/settings/billing/usage)`,
82+
);
83+
const records: SnapshotRecord[] = recordsFromBillingUsage(items, observedBy);
84+
const valid = records.filter(isSnapshotRecord);
85+
if (valid.length !== records.length)
86+
throw new Error(`${records.length - valid.length} derived record(s) failed validation`);
87+
const seen = new Set<string>();
88+
const fresh = valid.filter((r) => {
89+
const k = snapshotKey(r);
90+
if (seen.has(k)) return false;
91+
seen.add(k);
92+
return true;
93+
});
94+
if (process.argv.includes("--print")) {
95+
for (const r of fresh) console.log(JSON.stringify(r));
96+
console.log(`collect-github-billing: ${fresh.length} record(s) (dry run, outbox untouched)`);
97+
return;
98+
}
99+
if (!fresh.length) {
100+
console.log(`collect-github-billing: no records derived; outbox untouched (${outboxPath})`);
101+
return;
102+
}
103+
await mkdir(dirname(outboxPath), { recursive: true });
104+
await appendFile(outboxPath, fresh.map((r) => JSON.stringify(r)).join("\n") + "\n", "utf8");
105+
console.log(`collect-github-billing: appended ${fresh.length} record(s) to ${outboxPath}`);
106+
}
107+
108+
await main();
Collapse file

‎pm-stack/aggregator/src/model.ts‎

Copy file name to clipboardExpand all lines: pm-stack/aggregator/src/model.ts
+1-1Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1264,7 +1264,7 @@ export interface SnapshotRecord {
12641264
serviceId: string;
12651265
metricId: string;
12661266
value: number | { low: number; high: number };
1267-
unit: "pct" | "usd" | "count" | "gb" | "tokens" | "usd-est";
1267+
unit: "pct" | "usd" | "count" | "gb" | "tokens" | "usd-est" | "minutes" | "hours" | "gb-hours";
12681268
limit?: number | null;
12691269
resetsAt?: string | null;
12701270
source: UsageSourceClass;
Collapse file

‎pm-stack/aggregator/src/snapshot-records.ts‎

Copy file name to clipboardExpand all lines: pm-stack/aggregator/src/snapshot-records.ts
+2Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,8 @@ const UNIT_MAP: Partial<Record<UsageUnit, SnapshotRecord["unit"]>> = {
7575
gb: "gb",
7676
usd: "usd",
7777
pct: "pct",
78+
minutes: "minutes",
79+
hours: "hours",
7880
};
7981

8082
/** Family-2 services: every measured metric becomes one record at the
Collapse file

‎pm-stack/aggregator/src/snapshots.ts‎

Copy file name to clipboardExpand all lines: pm-stack/aggregator/src/snapshots.ts
+1-1Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ import { join } from "node:path";
2121
import type { SnapshotRecord, UsageSourceClass } from "./model.ts";
2222

2323
const SOURCES: ReadonlySet<string> = new Set(["api", "console", "manual", "estimate", "invoice"]);
24-
const UNITS: ReadonlySet<string> = new Set(["pct", "usd", "count", "gb", "tokens", "usd-est"]);
24+
const UNITS: ReadonlySet<string> = new Set(["pct", "usd", "count", "gb", "tokens", "usd-est", "minutes", "hours", "gb-hours"]);
2525
const FILE_RE = /^usage-(\d{4}-\d{2})\.jsonl$/;
2626

2727
const ROLLUP_RE = /^usage-(\d{4}-\d{2})\.rollup\.jsonl$/;
Collapse file

‎pm-stack/aggregator/src/sources/github-billing.ts‎

Copy file name to clipboard
+168Lines changed: 168 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,168 @@
1+
// GitHub billing collector core (#1051; hub design §2.2/§5): maps the
2+
// unified billing usage endpoint's items to §4 snapshot records.
3+
//
4+
// GET /users/{user}/settings/billing/usage?year=YYYY&month=M
5+
//
6+
// answers with the account's existing gh OAuth token — the old
7+
// per-product billing endpoints are gone (410, "This endpoint has been
8+
// moved"), and no billing-scoped token is needed for the own-account
9+
// usage read (verified live 2026-10-29, triage task 2315). Items are
10+
// per-day, per-SKU rows:
11+
// { date, product, sku, unitType, quantity, pricePerUnit,
12+
// grossAmount, discountAmount, netAmount, repositoryName }
13+
//
14+
// Aggregation is a group-by on date: Actions minutes, Codespaces
15+
// core-hours, storage GB-hours (the endpoint's own unit — GB-hours is
16+
// NOT GB; the snapshot unit keeps them distinct), plus gross/net USD
17+
// across all products. Records are stamped at the usage day (midday
18+
// UTC, the store's day convention), never at collection time, so a
19+
// re-run re-derives identical records and the store dedupes them.
20+
//
21+
// Pure functions, no I/O — scripts/collect-github-billing.ts owns the
22+
// gh call and the outbox append; tests feed literals.
23+
import type { SnapshotRecord } from "../model.ts";
24+
import { dayTs } from "../snapshot-records.ts";
25+
26+
export interface BillingUsageItem {
27+
date?: string;
28+
product?: string;
29+
sku?: string;
30+
unitType?: string;
31+
quantity?: number;
32+
grossAmount?: number;
33+
discountAmount?: number;
34+
netAmount?: number;
35+
[key: string]: unknown;
36+
}
37+
38+
export interface BillingDayAggregate {
39+
date: string;
40+
actionsMinutes: number;
41+
codespacesHours: number;
42+
actionsStorageGbHours: number;
43+
codespacesStorageGbHours: number;
44+
grossUsd: number;
45+
netUsd: number;
46+
}
47+
48+
function round(n: number, dp: number): number {
49+
const f = 10 ** dp;
50+
return Math.round(n * f) / f;
51+
}
52+
53+
function emptyDay(date: string): BillingDayAggregate {
54+
return {
55+
date,
56+
actionsMinutes: 0,
57+
codespacesHours: 0,
58+
actionsStorageGbHours: 0,
59+
codespacesStorageGbHours: 0,
60+
grossUsd: 0,
61+
netUsd: 0,
62+
};
63+
}
64+
65+
/** Codespaces compute rows are machine-hours, but the hub's
66+
* `codespaces-hours` metric is core-hours (src/saas-extract.ts):
67+
* one hour on an N-core machine consumes N core-hours (GitHub's
68+
* Codespaces pricing multiplier). The core count is parsed from the
69+
* SKU ("Codespaces 2-core"); a SKU with no parseable core count is
70+
* taken at face value (x1) rather than dropped. */
71+
function codespacesCoreMultiplier(sku: unknown): number {
72+
if (typeof sku !== "string") return 1;
73+
const m = /(\d+)\s*-core/i.exec(sku);
74+
return m ? Number(m[1]) : 1;
75+
}
76+
77+
/** Per-day aggregates from raw endpoint items, oldest day first. */
78+
export function aggregateBillingUsage(items: BillingUsageItem[]): BillingDayAggregate[] {
79+
const byDate = new Map<string, BillingDayAggregate>();
80+
for (const item of items) {
81+
if (typeof item.date !== "string" || item.date.length < 10) continue;
82+
const date = item.date.slice(0, 10);
83+
const day = byDate.get(date) ?? emptyDay(date);
84+
const qty = typeof item.quantity === "number" ? item.quantity : 0;
85+
// Classification is case-insensitive: the endpoint's documented
86+
// response example spells product/unitType "Actions"/"minutes"
87+
// while live rows arrive as "actions"/"Minutes" — both must
88+
// classify identically, never silently drop to money-only.
89+
const product = typeof item.product === "string" ? item.product.toLowerCase() : "";
90+
const unit = typeof item.unitType === "string" ? item.unitType.toLowerCase() : "";
91+
if (product === "actions" && unit === "minutes") day.actionsMinutes += qty;
92+
else if (product === "actions" && unit === "gigabytehours")
93+
day.actionsStorageGbHours += qty;
94+
else if (product === "codespaces" && unit === "hours")
95+
day.codespacesHours += qty * codespacesCoreMultiplier(item.sku);
96+
else if (product === "codespaces" && unit === "gigabytehours")
97+
day.codespacesStorageGbHours += qty;
98+
// Gross/net span every product the endpoint reports, known or not.
99+
if (typeof item.grossAmount === "number") day.grossUsd += item.grossAmount;
100+
if (typeof item.netAmount === "number") day.netUsd += item.netAmount;
101+
byDate.set(date, day);
102+
}
103+
return [...byDate.values()]
104+
.sort((a, b) => a.date.localeCompare(b.date))
105+
.map((d) => ({
106+
date: d.date,
107+
actionsMinutes: round(d.actionsMinutes, 3),
108+
codespacesHours: round(d.codespacesHours, 3),
109+
actionsStorageGbHours: round(d.actionsStorageGbHours, 3),
110+
codespacesStorageGbHours: round(d.codespacesStorageGbHours, 3),
111+
grossUsd: round(d.grossUsd, 2),
112+
netUsd: round(d.netUsd, 2),
113+
}));
114+
}
115+
116+
/** Month totals over per-day aggregates — the collector's test target
117+
* ("reproduces the endpoint's aggregates within accrual"). */
118+
export function summarizeBillingDays(days: BillingDayAggregate[]): Omit<BillingDayAggregate, "date"> {
119+
const total = {
120+
actionsMinutes: 0,
121+
codespacesHours: 0,
122+
actionsStorageGbHours: 0,
123+
codespacesStorageGbHours: 0,
124+
grossUsd: 0,
125+
netUsd: 0,
126+
};
127+
for (const d of days) {
128+
total.actionsMinutes += d.actionsMinutes;
129+
total.codespacesHours += d.codespacesHours;
130+
total.actionsStorageGbHours += d.actionsStorageGbHours;
131+
total.codespacesStorageGbHours += d.codespacesStorageGbHours;
132+
total.grossUsd += d.grossUsd;
133+
total.netUsd += d.netUsd;
134+
}
135+
return {
136+
actionsMinutes: round(total.actionsMinutes, 3),
137+
codespacesHours: round(total.codespacesHours, 3),
138+
actionsStorageGbHours: round(total.actionsStorageGbHours, 3),
139+
codespacesStorageGbHours: round(total.codespacesStorageGbHours, 3),
140+
grossUsd: round(total.grossUsd, 2),
141+
netUsd: round(total.netUsd, 2),
142+
};
143+
}
144+
145+
/** §4 snapshot records for one month of endpoint items, under the
146+
* hub's existing `github` service and card metric ids where they
147+
* exist (`codespaces-hours`). Zero aggregates emit no record — a day
148+
* with no Codespaces use is an absence, not a 0 observation. */
149+
export function recordsFromBillingUsage(
150+
items: BillingUsageItem[],
151+
observedBy: string,
152+
): SnapshotRecord[] {
153+
const out: SnapshotRecord[] = [];
154+
for (const day of aggregateBillingUsage(items)) {
155+
const ts = dayTs(day.date);
156+
const push = (metricId: string, value: number, unit: SnapshotRecord["unit"]) => {
157+
if (value === 0) return;
158+
out.push({ ts, serviceId: "github", metricId, value, unit, source: "api", observedBy });
159+
};
160+
push("actions-minutes", day.actionsMinutes, "minutes");
161+
push("codespaces-hours", day.codespacesHours, "hours");
162+
push("actions-storage-gb-hours", day.actionsStorageGbHours, "gb-hours");
163+
push("codespaces-storage-gb-hours", day.codespacesStorageGbHours, "gb-hours");
164+
push("billing-gross", day.grossUsd, "usd");
165+
push("billing-net", day.netUsd, "usd");
166+
}
167+
return out;
168+
}

0 commit comments

Comments
0 (0)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.