@softure-ai/ci-usage 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +21 -0
- package/LICENSE +21 -0
- package/README.md +128 -2
- package/dist/billing.d.ts +37 -0
- package/dist/billing.d.ts.map +1 -0
- package/dist/billing.js +83 -0
- package/dist/billing.js.map +1 -0
- package/dist/cli/command.d.ts +33 -0
- package/dist/cli/command.d.ts.map +1 -0
- package/dist/cli/command.js +203 -0
- package/dist/cli/command.js.map +1 -0
- package/dist/cli/main.d.ts +3 -0
- package/dist/cli/main.d.ts.map +1 -0
- package/dist/cli/main.js +10 -0
- package/dist/cli/main.js.map +1 -0
- package/dist/collect.d.ts +45 -0
- package/dist/collect.d.ts.map +1 -0
- package/dist/collect.js +189 -0
- package/dist/collect.js.map +1 -0
- package/dist/github.d.ts +41 -0
- package/dist/github.d.ts.map +1 -0
- package/dist/github.js +91 -0
- package/dist/github.js.map +1 -0
- package/dist/index.d.ts +10 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +11 -0
- package/dist/index.js.map +1 -0
- package/dist/messages/en.d.ts +51 -0
- package/dist/messages/en.d.ts.map +1 -0
- package/dist/messages/en.js +51 -0
- package/dist/messages/en.js.map +1 -0
- package/dist/messages/index.d.ts +11 -0
- package/dist/messages/index.d.ts.map +1 -0
- package/dist/messages/index.js +13 -0
- package/dist/messages/index.js.map +1 -0
- package/dist/prices.d.ts +32 -0
- package/dist/prices.d.ts.map +1 -0
- package/dist/prices.js +52 -0
- package/dist/prices.js.map +1 -0
- package/dist/publish.d.ts +29 -0
- package/dist/publish.d.ts.map +1 -0
- package/dist/publish.js +91 -0
- package/dist/publish.js.map +1 -0
- package/dist/report.d.ts +57 -0
- package/dist/report.d.ts.map +1 -0
- package/dist/report.js +168 -0
- package/dist/report.js.map +1 -0
- package/dist/runner.d.ts +28 -0
- package/dist/runner.d.ts.map +1 -0
- package/dist/runner.js +55 -0
- package/dist/runner.js.map +1 -0
- package/dist/usage.d.ts +67 -0
- package/dist/usage.d.ts.map +1 -0
- package/dist/usage.js +112 -0
- package/dist/usage.js.map +1 -0
- package/examples/ci-usage.yml +34 -0
- package/package.json +42 -4
- package/src/billing.ts +102 -0
- package/src/cli/command.ts +212 -0
- package/src/cli/main.ts +10 -0
- package/src/collect.ts +230 -0
- package/src/github.ts +113 -0
- package/src/index.ts +10 -0
- package/src/messages/en.ts +52 -0
- package/src/messages/index.ts +15 -0
- package/src/prices.ts +74 -0
- package/src/publish.ts +95 -0
- package/src/report.ts +215 -0
- package/src/runner.ts +64 -0
- package/src/usage.ts +192 -0
package/dist/usage.js
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
// Billable minutes per job and their sums per repository, workflow and job name.
|
|
2
|
+
import { getMinutePrice } from "./prices.js";
|
|
3
|
+
import { classifyRunner } from "./runner.js";
|
|
4
|
+
const MINUTE_MS = 60_000;
|
|
5
|
+
/**
|
|
6
|
+
* Billable minutes of one job: its run time rounded up to a whole minute, as GitHub and Ubicloud bill. A job that
|
|
7
|
+
* never started costs nothing; one that started without a recorded end is billed up to the run's last update.
|
|
8
|
+
*/
|
|
9
|
+
export function getJobMinutes(job) {
|
|
10
|
+
if (job.startedAt === null)
|
|
11
|
+
return 0;
|
|
12
|
+
const start = Date.parse(job.startedAt);
|
|
13
|
+
const end = Date.parse(job.completedAt ?? job.runUpdatedAt);
|
|
14
|
+
if (!Number.isFinite(start) || !Number.isFinite(end) || end <= start)
|
|
15
|
+
return 0;
|
|
16
|
+
return Math.ceil((end - start) / MINUTE_MS);
|
|
17
|
+
}
|
|
18
|
+
const LONGEST_JOBS = 10;
|
|
19
|
+
function emptyCost() {
|
|
20
|
+
return { minutes: 0, usd: 0, unpricedMinutes: 0 };
|
|
21
|
+
}
|
|
22
|
+
function addCost(total, minutes, price) {
|
|
23
|
+
total.minutes += minutes;
|
|
24
|
+
if (price === null) {
|
|
25
|
+
total.unpricedMinutes += minutes;
|
|
26
|
+
if (minutes > 0)
|
|
27
|
+
total.usd = null;
|
|
28
|
+
}
|
|
29
|
+
else if (total.usd !== null) {
|
|
30
|
+
total.usd += minutes * price;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
function roundUsd(cost) {
|
|
34
|
+
if (cost.usd !== null)
|
|
35
|
+
cost.usd = Math.round(cost.usd * 10_000) / 10_000;
|
|
36
|
+
}
|
|
37
|
+
/** Nearest-rank percentile of sorted minutes; 0 for an empty list. */
|
|
38
|
+
export function getPercentile(sorted, percentile) {
|
|
39
|
+
if (sorted.length === 0)
|
|
40
|
+
return 0;
|
|
41
|
+
const rank = Math.max(1, Math.ceil((percentile / 100) * sorted.length));
|
|
42
|
+
return sorted[rank - 1] ?? 0;
|
|
43
|
+
}
|
|
44
|
+
/** Sums the jobs of one repository; workflows and their jobs are sorted by minutes, most first. */
|
|
45
|
+
export function summarizeUsage(repository, jobs, options) {
|
|
46
|
+
const total = emptyCost();
|
|
47
|
+
const byProvider = { "github-hosted": emptyCost(), ubicloud: emptyCost(), "self-hosted": emptyCost() };
|
|
48
|
+
const workflows = new Map();
|
|
49
|
+
const runIds = new Set();
|
|
50
|
+
const longest = [];
|
|
51
|
+
for (const job of jobs) {
|
|
52
|
+
const minutes = getJobMinutes(job);
|
|
53
|
+
const runner = classifyRunner({ labels: job.labels, runnerGroupName: job.runnerGroupName });
|
|
54
|
+
const price = getMinutePrice(runner, options);
|
|
55
|
+
runIds.add(job.runId);
|
|
56
|
+
addCost(total, minutes, price);
|
|
57
|
+
addCost(byProvider[runner.provider], minutes, price);
|
|
58
|
+
const workflow = workflows.get(job.workflowPath) ?? { cost: emptyCost(), name: job.workflowName, runIds: new Set(), jobs: 0, byJob: new Map() };
|
|
59
|
+
workflows.set(job.workflowPath, workflow);
|
|
60
|
+
workflow.runIds.add(job.runId);
|
|
61
|
+
workflow.jobs += 1;
|
|
62
|
+
addCost(workflow.cost, minutes, price);
|
|
63
|
+
const key = `${job.name}\u0000${runner.label}`;
|
|
64
|
+
const bucket = workflow.byJob.get(key) ?? { cost: emptyCost(), runner, durations: [] };
|
|
65
|
+
workflow.byJob.set(key, bucket);
|
|
66
|
+
bucket.durations.push(minutes);
|
|
67
|
+
addCost(bucket.cost, minutes, price);
|
|
68
|
+
if (minutes > 0)
|
|
69
|
+
longest.push({ workflow: job.workflowName, job: job.name, runner: runner.label, minutes, url: job.htmlUrl });
|
|
70
|
+
}
|
|
71
|
+
const byWorkflow = [...workflows.entries()].map(([path, bucket]) => {
|
|
72
|
+
roundUsd(bucket.cost);
|
|
73
|
+
const byJob = [...bucket.byJob.entries()].map(([key, jobBucket]) => {
|
|
74
|
+
roundUsd(jobBucket.cost);
|
|
75
|
+
const sorted = [...jobBucket.durations].sort((a, b) => a - b);
|
|
76
|
+
return {
|
|
77
|
+
name: key.split("\u0000")[0] ?? key,
|
|
78
|
+
runner: jobBucket.runner.label,
|
|
79
|
+
provider: jobBucket.runner.provider,
|
|
80
|
+
count: sorted.length,
|
|
81
|
+
p50Minutes: getPercentile(sorted, 50),
|
|
82
|
+
p95Minutes: getPercentile(sorted, 95),
|
|
83
|
+
...jobBucket.cost,
|
|
84
|
+
};
|
|
85
|
+
});
|
|
86
|
+
byJob.sort((a, b) => b.minutes - a.minutes || a.name.localeCompare(b.name));
|
|
87
|
+
return {
|
|
88
|
+
name: bucket.name,
|
|
89
|
+
path,
|
|
90
|
+
runs: bucket.runIds.size,
|
|
91
|
+
jobs: bucket.jobs,
|
|
92
|
+
share: total.minutes === 0 ? 0 : Math.round((bucket.cost.minutes / total.minutes) * 1000) / 1000,
|
|
93
|
+
byJob,
|
|
94
|
+
...bucket.cost,
|
|
95
|
+
};
|
|
96
|
+
});
|
|
97
|
+
byWorkflow.sort((a, b) => b.minutes - a.minutes || a.path.localeCompare(b.path));
|
|
98
|
+
roundUsd(total);
|
|
99
|
+
for (const cost of Object.values(byProvider))
|
|
100
|
+
roundUsd(cost);
|
|
101
|
+
longest.sort((a, b) => b.minutes - a.minutes || a.url.localeCompare(b.url));
|
|
102
|
+
return {
|
|
103
|
+
repository,
|
|
104
|
+
runs: runIds.size,
|
|
105
|
+
jobs: jobs.length,
|
|
106
|
+
...total,
|
|
107
|
+
byProvider,
|
|
108
|
+
byWorkflow,
|
|
109
|
+
longestJobs: longest.slice(0, LONGEST_JOBS),
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
//# sourceMappingURL=usage.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"usage.js","sourceRoot":"","sources":["../src/usage.ts"],"names":[],"mappings":"AAAA,iFAAiF;AACjF,OAAO,EAAE,cAAc,EAAqB,MAAM,aAAa,CAAC;AAChE,OAAO,EAAE,cAAc,EAAmC,MAAM,aAAa,CAAC;AAmB9E,MAAM,SAAS,GAAG,MAAM,CAAC;AAEzB;;;GAGG;AACH,MAAM,UAAU,aAAa,CAAC,GAAc;IAC1C,IAAI,GAAG,CAAC,SAAS,KAAK,IAAI;QAAE,OAAO,CAAC,CAAC;IACrC,MAAM,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC;IACxC,MAAM,GAAG,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,WAAW,IAAI,GAAG,CAAC,YAAY,CAAC,CAAC;IAC5D,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,GAAG,CAAC,IAAI,GAAG,IAAI,KAAK;QAAE,OAAO,CAAC,CAAC;IAC/E,OAAO,IAAI,CAAC,IAAI,CAAC,CAAC,GAAG,GAAG,KAAK,CAAC,GAAG,SAAS,CAAC,CAAC;AAC9C,CAAC;AA8CD,MAAM,YAAY,GAAG,EAAE,CAAC;AAExB,SAAS,SAAS;IAChB,OAAO,EAAE,OAAO,EAAE,CAAC,EAAE,GAAG,EAAE,CAAC,EAAE,eAAe,EAAE,CAAC,EAAE,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AAC,MAAM,CAAC,UAAU,CAAC;QAAE,QAAQ,CAAC,IAAI,CAAC,CAAC;IAC7D,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,OAAO,GAAG,CAAC,CAAC,OAAO,IAAI,CAAC,CAAC,GAAG,CAAC,aAAa,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC;IAE5E,OAAO;QACL,UAAU;QACV,IAAI,EAAE,MAAM,CAAC,IAAI;QACjB,IAAI,EAAE,IAAI,CAAC,MAAM;QACjB,GAAG,KAAK;QACR,UAAU;QACV,UAAU;QACV,WAAW,EAAE,OAAO,CAAC,KAAK,CAAC,CAAC,EAAE,YAAY,CAAC;KAC5C,CAAC;AACJ,CAAC"}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
# The CI minutes report of this repository: every Monday and by hand (Actions → ci-usage → Run workflow).
|
|
2
|
+
# Copy to .github/workflows/ci-usage.yml. With no secret it reports on this repository with GITHUB_TOKEN. To cover
|
|
3
|
+
# several repositories (and add what GitHub billed), create a fine-grained token with "Actions: read" on them (plus
|
|
4
|
+
# organization "Administration: read" or user "Plan: read" for billing) as the repository secret CI_USAGE_TOKEN.
|
|
5
|
+
name: ci-usage
|
|
6
|
+
|
|
7
|
+
on:
|
|
8
|
+
schedule:
|
|
9
|
+
- cron: "30 6 * * 1"
|
|
10
|
+
workflow_dispatch:
|
|
11
|
+
inputs:
|
|
12
|
+
days:
|
|
13
|
+
description: Length of the period in days, ending now (1 to 31)
|
|
14
|
+
type: string
|
|
15
|
+
default: "7"
|
|
16
|
+
|
|
17
|
+
permissions: {}
|
|
18
|
+
|
|
19
|
+
jobs:
|
|
20
|
+
ci-usage:
|
|
21
|
+
uses: SOFTURE/AI/.github/workflows/ci-usage.yml@master
|
|
22
|
+
permissions:
|
|
23
|
+
contents: read
|
|
24
|
+
actions: read
|
|
25
|
+
issues: write
|
|
26
|
+
with:
|
|
27
|
+
days: ${{ inputs.days || '7' }}
|
|
28
|
+
# repositories: acme/app, acme/api # needs CI_USAGE_TOKEN
|
|
29
|
+
# billing: org:acme # needs CI_USAGE_TOKEN with billing read access
|
|
30
|
+
# prices: '{"my-runner":0.004}' # runners the built-in table does not know
|
|
31
|
+
# ubicloud-premium: true # when premium runners are enabled in Ubicloud
|
|
32
|
+
# runs-on: '"ubicloud-standard-2"' # the report's own runner, as JSON
|
|
33
|
+
secrets:
|
|
34
|
+
CI_USAGE_TOKEN: ${{ secrets.CI_USAGE_TOKEN }}
|
package/package.json
CHANGED
|
@@ -1,6 +1,44 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@softure-ai/ci-usage",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "SOFTURE AI CI usage: how many GitHub Actions minutes each repository, workflow and job used in a period, on GitHub-hosted and Ubicloud runners, with the estimated cost of each, as JSON and Markdown for people and agents; the CLI behind the reusable ci-usage.yml workflow.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"sideEffects": false,
|
|
8
|
+
"engines": {
|
|
9
|
+
"node": ">=22"
|
|
10
|
+
},
|
|
11
|
+
"repository": {
|
|
12
|
+
"type": "git",
|
|
13
|
+
"url": "git+https://github.com/SOFTURE/AI.git",
|
|
14
|
+
"directory": "tools/ci-usage"
|
|
15
|
+
},
|
|
16
|
+
"files": [
|
|
17
|
+
"dist",
|
|
18
|
+
"CHANGELOG.md",
|
|
19
|
+
"src",
|
|
20
|
+
"examples",
|
|
21
|
+
"!src/**/*.test.ts"
|
|
22
|
+
],
|
|
23
|
+
"publishConfig": {
|
|
24
|
+
"access": "public",
|
|
25
|
+
"provenance": true
|
|
26
|
+
},
|
|
27
|
+
"bin": {
|
|
28
|
+
"softure-ci-usage": "./dist/cli/main.js"
|
|
29
|
+
},
|
|
30
|
+
"exports": {
|
|
31
|
+
".": {
|
|
32
|
+
"@softure-ai/source": "./src/index.ts",
|
|
33
|
+
"types": "./dist/index.d.ts",
|
|
34
|
+
"default": "./dist/index.js"
|
|
35
|
+
},
|
|
36
|
+
"./package.json": "./package.json"
|
|
37
|
+
},
|
|
38
|
+
"scripts": {
|
|
39
|
+
"build": "tsc -p tsconfig.build.json"
|
|
40
|
+
},
|
|
41
|
+
"dependencies": {
|
|
42
|
+
"zod": "^4.6.7"
|
|
43
|
+
}
|
|
44
|
+
}
|
package/src/billing.ts
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
// What GitHub actually billed for Actions, per repository and SKU, from the billing usage API. Optional: it needs a
|
|
2
|
+
// fine-grained token with organization "Administration: read" or user "Plan: read", and its answer only ever
|
|
3
|
+
// completes the estimate.
|
|
4
|
+
import { z } from "zod";
|
|
5
|
+
import type { GithubClient } from "./github.js";
|
|
6
|
+
|
|
7
|
+
export type BillingAccount = { kind: "org" | "user"; name: string };
|
|
8
|
+
|
|
9
|
+
export type AccountResult = { ok: true; account: BillingAccount } | { ok: false; error: string };
|
|
10
|
+
|
|
11
|
+
/** Reads `org:<name>` or `user:<name>`; an empty value means no billing lookup. */
|
|
12
|
+
export function parseBillingAccount(value: string | undefined): AccountResult | null {
|
|
13
|
+
if (value === undefined || value.trim() === "") return null;
|
|
14
|
+
const match = /^(org|user):([A-Za-z0-9][A-Za-z0-9-]*)$/.exec(value.trim());
|
|
15
|
+
if (!match?.[1] || !match[2]) return { ok: false, error: `--billing must be org:<organization> or user:<user>, not "${value}"` };
|
|
16
|
+
return { ok: true, account: { kind: match[1] as "org" | "user", name: match[2] } };
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
const ITEM = z.object({
|
|
20
|
+
date: z.string(),
|
|
21
|
+
product: z.string(),
|
|
22
|
+
sku: z.string(),
|
|
23
|
+
quantity: z.number(),
|
|
24
|
+
unitType: z.string(),
|
|
25
|
+
netAmount: z.number(),
|
|
26
|
+
grossAmount: z.number().optional(),
|
|
27
|
+
repositoryName: z.string().nullable().optional(),
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
const USAGE = z.object({ usageItems: z.array(ITEM) });
|
|
31
|
+
|
|
32
|
+
export interface BilledSku {
|
|
33
|
+
sku: string;
|
|
34
|
+
minutes: number;
|
|
35
|
+
grossUsd: number;
|
|
36
|
+
netUsd: number;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export type BillingResult = { ok: true; byRepository: Record<string, BilledSku[]> } | { ok: false; error: string };
|
|
40
|
+
|
|
41
|
+
function getMonths(from: Date, to: Date): { year: number; month: number }[] {
|
|
42
|
+
const months: { year: number; month: number }[] = [];
|
|
43
|
+
let year = from.getUTCFullYear();
|
|
44
|
+
let month = from.getUTCMonth();
|
|
45
|
+
const last = new Date(to.getTime() - 1);
|
|
46
|
+
while (year < last.getUTCFullYear() || (year === last.getUTCFullYear() && month <= last.getUTCMonth())) {
|
|
47
|
+
months.push({ year, month: month + 1 });
|
|
48
|
+
month += 1;
|
|
49
|
+
if (month === 12) {
|
|
50
|
+
month = 0;
|
|
51
|
+
year += 1;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
return months;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** The usage item's repository as `owner/name`: GitHub gives the name alone or the full name. */
|
|
58
|
+
function matchRepository(item: string | null | undefined, repositories: readonly string[]): string | null {
|
|
59
|
+
if (!item) return null;
|
|
60
|
+
return repositories.find((repository) => repository === item || repository.split("/")[1] === item) ?? null;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export interface BillingOptions {
|
|
64
|
+
client: GithubClient;
|
|
65
|
+
account: BillingAccount;
|
|
66
|
+
repositories: readonly string[];
|
|
67
|
+
from: Date;
|
|
68
|
+
to: Date;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** Sums the Actions minute items of the period per repository and SKU. */
|
|
72
|
+
export async function getBillingUsage(options: BillingOptions): Promise<BillingResult> {
|
|
73
|
+
const base = options.account.kind === "org" ? `/organizations/${options.account.name}` : `/users/${options.account.name}`;
|
|
74
|
+
const sums = new Map<string, Map<string, BilledSku>>();
|
|
75
|
+
for (const { year, month } of getMonths(options.from, options.to)) {
|
|
76
|
+
const result = await options.client.get(`${base}/settings/billing/usage`, { year: String(year), month: String(month) });
|
|
77
|
+
if (!result.ok) return { ok: false, error: `billing usage of ${options.account.kind}:${options.account.name} unavailable: ${result.message}` };
|
|
78
|
+
const parsed = USAGE.safeParse(result.data);
|
|
79
|
+
if (!parsed.success) return { ok: false, error: `billing usage of ${options.account.kind}:${options.account.name} answered an unexpected shape` };
|
|
80
|
+
for (const item of parsed.data.usageItems) {
|
|
81
|
+
if (item.product.toLowerCase() !== "actions" || item.unitType.toLowerCase() !== "minutes") continue;
|
|
82
|
+
const date = Date.parse(item.date);
|
|
83
|
+
if (!(date >= options.from.getTime() && date < options.to.getTime())) continue;
|
|
84
|
+
const repository = matchRepository(item.repositoryName, options.repositories);
|
|
85
|
+
if (repository === null) continue;
|
|
86
|
+
const skus = sums.get(repository) ?? new Map<string, BilledSku>();
|
|
87
|
+
sums.set(repository, skus);
|
|
88
|
+
const sum = skus.get(item.sku) ?? { sku: item.sku, minutes: 0, grossUsd: 0, netUsd: 0 };
|
|
89
|
+
skus.set(item.sku, sum);
|
|
90
|
+
sum.minutes += item.quantity;
|
|
91
|
+
sum.grossUsd += item.grossAmount ?? item.netAmount;
|
|
92
|
+
sum.netUsd += item.netAmount;
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
const byRepository: Record<string, BilledSku[]> = {};
|
|
96
|
+
for (const repository of options.repositories) {
|
|
97
|
+
byRepository[repository] = [...(sums.get(repository)?.values() ?? [])]
|
|
98
|
+
.map((sum) => ({ ...sum, grossUsd: Math.round(sum.grossUsd * 10_000) / 10_000, netUsd: Math.round(sum.netUsd * 10_000) / 10_000 }))
|
|
99
|
+
.sort((a, b) => b.minutes - a.minutes);
|
|
100
|
+
}
|
|
101
|
+
return { ok: true, byRepository };
|
|
102
|
+
}
|
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { dirname, join, resolve } from "node:path";
|
|
3
|
+
import { parseArgs } from "node:util";
|
|
4
|
+
import { getBillingUsage, parseBillingAccount } from "../billing.js";
|
|
5
|
+
import { collectRepository, parseRunCache, type CollectResult, type RunCache } from "../collect.js";
|
|
6
|
+
import { createGithubClient, DEFAULT_RESERVE, type FetchLike } from "../github.js";
|
|
7
|
+
import { parsePriceOverrides } from "../prices.js";
|
|
8
|
+
import { publishReport } from "../publish.js";
|
|
9
|
+
import { buildReport, JSON_FILE, MARKDOWN_FILE, renderMarkdown, type BuildReportOptions, type CiUsageReport } from "../report.js";
|
|
10
|
+
|
|
11
|
+
export interface CommandContext {
|
|
12
|
+
cwd: string;
|
|
13
|
+
env: NodeJS.ProcessEnv;
|
|
14
|
+
write: (text: string) => void;
|
|
15
|
+
writeError: (text: string) => void;
|
|
16
|
+
/** Replaces the network in tests. */
|
|
17
|
+
fetch?: FetchLike;
|
|
18
|
+
now?: () => Date;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export const DEFAULT_DAYS = 7;
|
|
22
|
+
const DAY_MS = 86_400_000;
|
|
23
|
+
const REPOSITORY = /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/;
|
|
24
|
+
|
|
25
|
+
export const USAGE = `Usage:
|
|
26
|
+
softure-ci-usage report [--repository <owner/name>[,<owner/name>…]] [--days ${String(DEFAULT_DAYS)} | --from <date> --to <date>]
|
|
27
|
+
[--out-dir .] [--prices <json>] [--ubicloud-premium] [--billing org:<name>|user:<name>]
|
|
28
|
+
[--cache <file>] [--reserve ${String(DEFAULT_RESERVE)}]
|
|
29
|
+
softure-ci-usage publish [--repository <owner/name>] [--report-dir .] [--run-url <url>]
|
|
30
|
+
|
|
31
|
+
report reads the finished workflow runs of the period through the Actions API and writes ${JSON_FILE} and ${MARKDOWN_FILE}:
|
|
32
|
+
billable minutes and estimated USD per repository, workflow and job, on GitHub-hosted, Ubicloud and other runners.
|
|
33
|
+
publish keeps the issue labelled ci-usage in the repository up to date with the report and comments the run's totals.
|
|
34
|
+
|
|
35
|
+
The token comes from GITHUB_TOKEN (or GH_TOKEN): "Actions: read" on every repository for report (plus organization
|
|
36
|
+
"Administration: read" or user "Plan: read" for --billing), "Issues: write" for publish. The repository defaults to
|
|
37
|
+
GITHUB_REPOSITORY. A report that could not count every run is marked partial and still exits 0.`;
|
|
38
|
+
|
|
39
|
+
function getToken(env: NodeJS.ProcessEnv): string | undefined {
|
|
40
|
+
const token = env.GITHUB_TOKEN ?? env.GH_TOKEN;
|
|
41
|
+
return token === undefined || token === "" ? undefined : token;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** An empty value means "not set", so a workflow can always pass its input through. */
|
|
45
|
+
function toOptional(value: string | undefined): string | undefined {
|
|
46
|
+
return value === undefined || value.trim() === "" ? undefined : value.trim();
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export function parseRepositories(values: readonly string[] | undefined, env: NodeJS.ProcessEnv): { ok: true; repositories: string[] } | { ok: false; error: string } {
|
|
50
|
+
const listed = (values ?? []).flatMap((value) => value.split(/[\s,]+/)).filter((value) => value !== "");
|
|
51
|
+
const repositories = listed.length > 0 ? [...new Set(listed)] : env.GITHUB_REPOSITORY ? [env.GITHUB_REPOSITORY] : [];
|
|
52
|
+
if (repositories.length === 0) return { ok: false, error: "--repository is required outside GitHub Actions (owner/name)" };
|
|
53
|
+
const wrong = repositories.find((repository) => !REPOSITORY.test(repository));
|
|
54
|
+
return wrong === undefined ? { ok: true, repositories } : { ok: false, error: `--repository must be owner/name, not "${wrong}"` };
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function parseDate(name: string, value: string): Date | string {
|
|
58
|
+
const date = new Date(/^\d{4}-\d{2}-\d{2}$/.test(value) ? `${value}T00:00:00Z` : value);
|
|
59
|
+
return Number.isNaN(date.getTime()) ? `--${name} must be a date (YYYY-MM-DD) or an ISO time, not "${value}"` : date;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export function parsePeriod(values: { days?: string; from?: string; to?: string }, now: Date): { ok: true; from: Date; to: Date } | { ok: false; error: string } {
|
|
63
|
+
const fromValue = toOptional(values.from);
|
|
64
|
+
const toValue = toOptional(values.to);
|
|
65
|
+
if (fromValue !== undefined || toValue !== undefined) {
|
|
66
|
+
if (fromValue === undefined) return { ok: false, error: "--to needs --from" };
|
|
67
|
+
const from = parseDate("from", fromValue);
|
|
68
|
+
if (typeof from === "string") return { ok: false, error: from };
|
|
69
|
+
const to = toValue === undefined ? now : parseDate("to", toValue);
|
|
70
|
+
if (typeof to === "string") return { ok: false, error: to };
|
|
71
|
+
return from < to ? { ok: true, from, to } : { ok: false, error: "--from must be before --to" };
|
|
72
|
+
}
|
|
73
|
+
const daysValue = toOptional(values.days);
|
|
74
|
+
const days = daysValue === undefined ? DEFAULT_DAYS : Number(daysValue);
|
|
75
|
+
if (!Number.isInteger(days) || days < 1 || days > 31) return { ok: false, error: `--days must be a whole number from 1 to 31, not "${String(daysValue)}"` };
|
|
76
|
+
return { ok: true, from: new Date(now.getTime() - days * DAY_MS), to: now };
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function readCache(path: string | undefined): RunCache {
|
|
80
|
+
if (path === undefined || !existsSync(path)) return parseRunCache(null);
|
|
81
|
+
return parseRunCache(readFileSync(path, "utf8"));
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function writeFile(path: string, text: string): void {
|
|
85
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
86
|
+
writeFileSync(path, text);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
async function runReport(args: string[], context: CommandContext): Promise<number> {
|
|
90
|
+
const { values } = parseArgs({
|
|
91
|
+
args,
|
|
92
|
+
options: {
|
|
93
|
+
repository: { type: "string", multiple: true },
|
|
94
|
+
days: { type: "string" },
|
|
95
|
+
from: { type: "string" },
|
|
96
|
+
to: { type: "string" },
|
|
97
|
+
"out-dir": { type: "string", default: "." },
|
|
98
|
+
prices: { type: "string" },
|
|
99
|
+
"ubicloud-premium": { type: "boolean", default: false },
|
|
100
|
+
billing: { type: "string" },
|
|
101
|
+
cache: { type: "string" },
|
|
102
|
+
reserve: { type: "string" },
|
|
103
|
+
},
|
|
104
|
+
});
|
|
105
|
+
const now = context.now?.() ?? new Date();
|
|
106
|
+
const repositories = parseRepositories(values.repository, context.env);
|
|
107
|
+
const period = parsePeriod(values, now);
|
|
108
|
+
const prices = parsePriceOverrides(values.prices);
|
|
109
|
+
const billing = parseBillingAccount(values.billing);
|
|
110
|
+
const reserve = toOptional(values.reserve) === undefined ? DEFAULT_RESERVE : Number(values.reserve);
|
|
111
|
+
const errors = [
|
|
112
|
+
repositories.ok ? null : repositories.error,
|
|
113
|
+
period.ok ? null : period.error,
|
|
114
|
+
prices.ok ? null : prices.error,
|
|
115
|
+
billing === null || billing.ok ? null : billing.error,
|
|
116
|
+
Number.isInteger(reserve) && reserve >= 0 ? null : `--reserve must be a whole number of requests, not "${String(values.reserve)}"`,
|
|
117
|
+
].filter((error): error is string => error !== null);
|
|
118
|
+
const token = getToken(context.env);
|
|
119
|
+
if (token === undefined) errors.push("GITHUB_TOKEN (or GH_TOKEN) is not set");
|
|
120
|
+
if (errors.length > 0 || !repositories.ok || !period.ok || !prices.ok || token === undefined) {
|
|
121
|
+
context.writeError(`${errors.join("\n")}\n\n${USAGE}\n`);
|
|
122
|
+
return 1;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
const client = createGithubClient({ token, reserve, ...(context.fetch ? { fetch: context.fetch } : {}) });
|
|
126
|
+
const cachePath = toOptional(values.cache) === undefined ? undefined : resolve(context.cwd, String(values.cache));
|
|
127
|
+
const cache = readCache(cachePath);
|
|
128
|
+
const collected: CollectResult[] = [];
|
|
129
|
+
for (const repository of repositories.repositories) {
|
|
130
|
+
collected.push(await collectRepository({ client, repository, from: period.from, to: period.to, cache }));
|
|
131
|
+
}
|
|
132
|
+
let billingResult: BuildReportOptions["billing"] = null;
|
|
133
|
+
if (billing?.ok) {
|
|
134
|
+
const result = await getBillingUsage({ client, account: billing.account, repositories: repositories.repositories, from: period.from, to: period.to });
|
|
135
|
+
billingResult = result.ok ? { byRepository: result.byRepository } : { error: result.error };
|
|
136
|
+
}
|
|
137
|
+
const report = buildReport({
|
|
138
|
+
collected,
|
|
139
|
+
from: period.from,
|
|
140
|
+
to: period.to,
|
|
141
|
+
generatedAt: now,
|
|
142
|
+
priceOptions: { prices: prices.prices, ubicloudPremium: values["ubicloud-premium"] },
|
|
143
|
+
billing: billingResult,
|
|
144
|
+
});
|
|
145
|
+
const outDir = resolve(context.cwd, values["out-dir"]);
|
|
146
|
+
writeFile(join(outDir, JSON_FILE), `${JSON.stringify(report, null, 2)}\n`);
|
|
147
|
+
writeFile(join(outDir, MARKDOWN_FILE), renderMarkdown(report));
|
|
148
|
+
if (cachePath !== undefined) {
|
|
149
|
+
const merged: RunCache = { version: 1, runs: Object.assign({}, ...collected.map((result) => result.cache.runs)) as RunCache["runs"] };
|
|
150
|
+
writeFile(cachePath, JSON.stringify(merged));
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
for (const repository of report.repositories) {
|
|
154
|
+
const usd = repository.usd === null ? "unknown" : repository.usd.toFixed(2);
|
|
155
|
+
context.write(repository.error === null ? `${repository.repository}: ${String(repository.minutes)} minutes, ${usd} USD, ${String(repository.runs)} runs${repository.partial.length > 0 ? " (partial)" : ""}\n` : `${repository.repository}: not read (${repository.error})\n`);
|
|
156
|
+
}
|
|
157
|
+
context.write(`requests: ${String(client.getRequestCount())}, rate limit left: ${String(client.getRemaining() ?? "unknown")}\n`);
|
|
158
|
+
return report.repositories.every((repository) => repository.error !== null) ? 1 : 0;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
async function runPublish(args: string[], context: CommandContext): Promise<number> {
|
|
162
|
+
const { values } = parseArgs({
|
|
163
|
+
args,
|
|
164
|
+
options: {
|
|
165
|
+
repository: { type: "string" },
|
|
166
|
+
"report-dir": { type: "string", default: "." },
|
|
167
|
+
"run-url": { type: "string" },
|
|
168
|
+
},
|
|
169
|
+
});
|
|
170
|
+
const repositories = parseRepositories(values.repository === undefined ? undefined : [values.repository], context.env);
|
|
171
|
+
const token = getToken(context.env);
|
|
172
|
+
const dir = resolve(context.cwd, values["report-dir"]);
|
|
173
|
+
const errors: string[] = [];
|
|
174
|
+
if (!repositories.ok) errors.push(repositories.error);
|
|
175
|
+
else if (repositories.repositories.length !== 1) errors.push("publish takes one --repository");
|
|
176
|
+
if (token === undefined) errors.push("GITHUB_TOKEN (or GH_TOKEN) is not set");
|
|
177
|
+
if (!existsSync(join(dir, JSON_FILE)) || !existsSync(join(dir, MARKDOWN_FILE))) errors.push(`${JSON_FILE} and ${MARKDOWN_FILE} are not in ${dir}: run report first`);
|
|
178
|
+
const repository = repositories.ok ? repositories.repositories[0] : undefined;
|
|
179
|
+
if (errors.length > 0 || token === undefined || repository === undefined) {
|
|
180
|
+
context.writeError(`${errors.join("\n")}\n\n${USAGE}\n`);
|
|
181
|
+
return 1;
|
|
182
|
+
}
|
|
183
|
+
const report = JSON.parse(readFileSync(join(dir, JSON_FILE), "utf8")) as CiUsageReport;
|
|
184
|
+
const markdown = readFileSync(join(dir, MARKDOWN_FILE), "utf8");
|
|
185
|
+
const { GITHUB_SERVER_URL: server, GITHUB_REPOSITORY: current, GITHUB_RUN_ID: runId } = context.env;
|
|
186
|
+
const runUrl = toOptional(values["run-url"]) ?? (server && current && runId ? `${server}/${current}/actions/runs/${runId}` : `https://github.com/${repository}/actions`);
|
|
187
|
+
const client = createGithubClient({ token, ...(context.fetch ? { fetch: context.fetch } : {}) });
|
|
188
|
+
const result = await publishReport({ client, repository, report, markdown, runUrl });
|
|
189
|
+
if (!result.ok) {
|
|
190
|
+
context.writeError(`publishing the report to ${repository} failed: ${result.error}\n`);
|
|
191
|
+
return 1;
|
|
192
|
+
}
|
|
193
|
+
context.write(`${result.created ? "created" : "updated"} ${result.url}\n`);
|
|
194
|
+
return 0;
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
export async function runCommand(argv: string[], context: CommandContext): Promise<number> {
|
|
198
|
+
const [command, ...args] = argv;
|
|
199
|
+
try {
|
|
200
|
+
if (command === "report") return await runReport(args, context);
|
|
201
|
+
if (command === "publish") return await runPublish(args, context);
|
|
202
|
+
} catch (error) {
|
|
203
|
+
// parseArgs throws on an unknown or malformed option: a usage error, not a bug.
|
|
204
|
+
if (error instanceof TypeError && "code" in error && String(error.code).startsWith("ERR_PARSE_ARGS")) {
|
|
205
|
+
context.writeError(`${error.message}\n\n${USAGE}\n`);
|
|
206
|
+
return 1;
|
|
207
|
+
}
|
|
208
|
+
throw error;
|
|
209
|
+
}
|
|
210
|
+
context.writeError(`${command === undefined ? "No command given." : `Unknown command "${command}".`}\n\n${USAGE}\n`);
|
|
211
|
+
return 1;
|
|
212
|
+
}
|
package/src/cli/main.ts
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Entry point of the `softure-ci-usage` bin; the behaviour is in command.ts.
|
|
3
|
+
import { runCommand } from "./command.js";
|
|
4
|
+
|
|
5
|
+
process.exitCode = await runCommand(process.argv.slice(2), {
|
|
6
|
+
cwd: process.cwd(),
|
|
7
|
+
env: process.env,
|
|
8
|
+
write: (text) => process.stdout.write(text),
|
|
9
|
+
writeError: (text) => process.stderr.write(text),
|
|
10
|
+
});
|