bailinghub 0.8.0 → 0.9.1
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/.dockerignore +6 -0
- package/.npmignore +6 -0
- package/CONTRIBUTING.md +4 -0
- package/GOVERNANCE.md +9 -0
- package/README.en.md +8 -6
- package/README.md +8 -6
- package/SECURITY.md +8 -2
- package/THIRD_PARTY_NOTICES.md +17 -17
- package/docker-compose.images.yml +2 -2
- package/docs/ARCHITECTURE.md +1 -1
- package/docs/CHANGELOG.en.md +22 -1
- package/docs/CHANGELOG.md +22 -1
- package/docs/COMPATIBILITY.en.md +8 -0
- package/docs/IMPLEMENTATION_STATUS.en.md +73 -0
- package/docs/IMPLEMENTATION_STATUS.md +73 -0
- package/docs/INDEPENDENT_VALIDATION.en.md +4 -4
- package/docs/INDEPENDENT_VALIDATION.md +4 -4
- package/docs/KERNEL_HOST_API.en.md +18 -0
- package/docs/KERNEL_HOST_API.md +18 -0
- package/docs/MODEL_BILLING.en.md +123 -0
- package/docs/MODEL_BILLING.md +125 -0
- package/docs/PERIOD_ALLOWANCE_UPGRADE.en.md +31 -0
- package/docs/PERIOD_ALLOWANCE_UPGRADE.md +31 -0
- package/docs/README.en.md +8 -1
- package/docs/README.md +7 -0
- package/docs/RELEASE_NOTES_NEXT.en.md +4 -2
- package/docs/RELEASE_NOTES_NEXT.md +4 -2
- package/docs/RELEASE_NOTES_v0.9.0.en.md +45 -0
- package/docs/RELEASE_NOTES_v0.9.0.md +45 -0
- package/docs/RELEASE_NOTES_v0.9.1.en.md +38 -0
- package/docs/RELEASE_NOTES_v0.9.1.md +38 -0
- package/docs/UPGRADE_v0.9.0.en.md +54 -0
- package/docs/UPGRADE_v0.9.0.md +54 -0
- package/docs/UPGRADE_v0.9.1.en.md +39 -0
- package/docs/UPGRADE_v0.9.1.md +39 -0
- package/docs//345/205/274/345/256/271/346/200/247/344/270/216/345/215/207/347/272/247.md +8 -0
- package/package.json +5 -4
- package/scripts/check-doc-links.mjs +6 -0
- package/scripts/check-image-tags.sh +1 -1
- package/scripts/check-release-consistency.test.mjs +2 -2
- package/scripts/dependency-audit.mjs +134 -0
- package/scripts/dependency-audit.test.mjs +125 -0
- package/scripts/install.sh +1 -1
- package/scripts/osps-results.py +114 -0
- package/scripts/publish-images.sh +1 -1
- package/scripts/release-audit.mjs +2 -0
- package/scripts/sdk-runtime-test.mjs +6 -0
- package/scripts/verify-billing-install-upgrade.mjs +225 -0
- package/scripts/verify-github-repo.mjs +2 -0
- package/sdk/node/README.md +17 -0
- package/sdk/node/examples/billing.mjs +21 -0
- package/sdk/node/package.json +5 -1
- package/sdk/node/src/index.mjs +2 -0
- package/sdk/node/src/usage.d.mts +74 -0
- package/sdk/node/src/usage.mjs +62 -0
- package/sdk/node/tests/usage-types.mts +23 -0
- package/sdk/node/tests/usage.test.mjs +81 -0
- package/sdk/php7/README.md +19 -2
- package/sdk/php7/examples/billing.php +27 -0
- package/sdk/php7/examples/well-known.php +1 -1
- package/sdk/php7/src/ToolSpec.php +1 -1
- package/sdk/php7/src/UsageClient.php +95 -0
- package/sdk/php7/src/UsageClientException.php +22 -0
- package/sdk/php7/tests/billing-core-http.php +59 -0
- package/sdk/php7/tests/usage-client.php +78 -0
- package/security/dependency-audit-exceptions.json +192 -0
- package/sql/063_usage_model_billing.sql +153 -0
- package/sql/064_period_plan_allowance.sql +25 -0
- package/sql/README.en.md +12 -4
- package/sql/README.md +14 -6
- package/src/app/auth.ts +2 -0
- package/src/app/kernel-usage-lifecycle.mysql.test.ts +325 -0
- package/src/app/kernel.ts +10 -0
- package/src/app/oss-edition.ts +1 -0
- package/src/infrastructure/config/configstore.ts +6 -0
- package/src/modules/usage/allowance-reset.mysql.test.ts +122 -0
- package/src/modules/usage/background-work.test.ts +144 -0
- package/src/modules/usage/background-work.ts +50 -0
- package/src/modules/usage/billing-contracts.ts +59 -0
- package/src/modules/usage/billing-decimal.test.ts +22 -0
- package/src/modules/usage/billing-decimal.ts +36 -0
- package/src/modules/usage/billing-external.ts +39 -0
- package/src/modules/usage/billing-gateway.mysql.test.ts +24 -0
- package/src/modules/usage/billing-ledger.test.ts +51 -0
- package/src/modules/usage/billing-ledger.ts +104 -0
- package/src/modules/usage/billing-presentation.mysql.test.ts +95 -0
- package/src/modules/usage/billing-presentation.test.ts +49 -0
- package/src/modules/usage/billing-presentation.ts +34 -0
- package/src/modules/usage/billing-prices.mysql.test.ts +88 -0
- package/src/modules/usage/billing-repository.mysql.test.ts +181 -0
- package/src/modules/usage/billing-repository.ts +465 -0
- package/src/modules/usage/contracts.ts +49 -0
- package/src/modules/usage/dynamic-plan-models.mysql.test.ts +221 -0
- package/src/modules/usage/errors.ts +19 -0
- package/src/modules/usage/http.ts +85 -0
- package/src/modules/usage/identity-revocation.mysql.test.ts +286 -0
- package/src/modules/usage/identity.mysql.test.ts +120 -0
- package/src/modules/usage/identity.ts +303 -0
- package/src/modules/usage/issuer-sdk-billing.mysql.test.ts +92 -0
- package/src/modules/usage/model-gateway.mysql.test.ts +207 -0
- package/src/modules/usage/model-gateway.ts +236 -0
- package/src/modules/usage/model-tool-gateway.mysql.test.ts +137 -0
- package/src/modules/usage/model-tool-provider.test.ts +37 -0
- package/src/modules/usage/model-tool-provider.ts +110 -0
- package/src/modules/usage/model-tools.test.ts +36 -0
- package/src/modules/usage/model-tools.ts +62 -0
- package/src/modules/usage/period-allowance.mysql.test.ts +97 -0
- package/src/modules/usage/period.test.ts +26 -0
- package/src/modules/usage/period.ts +96 -0
- package/src/modules/usage/pricing.test.ts +178 -0
- package/src/modules/usage/pricing.ts +229 -0
- package/src/modules/usage/provider-failure.ts +37 -0
- package/src/modules/usage/provider-stream.test.ts +85 -0
- package/src/modules/usage/provider-stream.ts +77 -0
- package/src/modules/usage/provider.test.ts +67 -0
- package/src/modules/usage/provider.ts +142 -0
- package/src/modules/usage/repository.ts +541 -0
- package/src/modules/usage/service-availability.mysql.test.ts +68 -0
- package/src/modules/usage/service-availability.ts +13 -0
- package/src/modules/usage/service-delete.mysql.test.ts +87 -0
- package/src/modules/usage/stream-http.ts +32 -0
- package/src/modules/usage/test-harness.ts +109 -0
- package/src/modules/usage/usage-deletion.mysql.test.ts +312 -0
- package/src/modules/usage/usage-deletion.ts +119 -0
- package/src/modules/usage/validation.test.ts +18 -0
- package/src/modules/usage/validation.ts +33 -0
- package/src/routes/admin-billing-usage.ts +73 -0
- package/src/routes/admin-usage.ts +147 -0
- package/src/routes/admin.ts +4 -0
- package/src/routes/private.ts +8 -0
- package/web/connect/bailing-connect-php7.tgz +0 -0
- package/web/console/assets/Accounts-Bervi5JU.css +1 -0
- package/web/console/assets/Accounts-DKhw_QLr.js +3 -0
- package/web/console/assets/{AgentClients-Bf7sUUs_.js → AgentClients-CM4_5HaA.js} +1 -1
- package/web/console/assets/AgentTasks-BsG850Il.css +1 -0
- package/web/console/assets/AgentTasks-CkQgZTU5.js +2 -0
- package/web/console/assets/{Approvals-BIbZvInm.js → Approvals-B9O9TkbO.js} +1 -1
- package/web/console/assets/{Audit-KyPSmBdZ.js → Audit-2vDC1SPu.js} +1 -1
- package/web/console/assets/{BrandLockup-Sv5DU2G6.js → BrandLockup-BgASiRSE.js} +1 -1
- package/web/console/assets/{Channels-B9n4fbxg.js → Channels-A-GvkNBt.js} +1 -1
- package/web/console/assets/{ChatEntries-xsOCUXi_.js → ChatEntries-BLxymI67.js} +1 -1
- package/web/console/assets/{Clients-CI3DBDHf.js → Clients-DeNlmvS6.js} +1 -1
- package/web/console/assets/{Cost-JgNXQPlN.js → Cost-CBq_L4Kz.js} +1 -1
- package/web/console/assets/{Credentials-B5UUUdt0.js → Credentials-DmtbctNj.js} +1 -1
- package/web/console/assets/{Diagnostics-BMGciWQb.js → Diagnostics-BbcRDiA-.js} +1 -1
- package/web/console/assets/{Executors-CRbboOCZ.js → Executors-gGgmQrDt.js} +1 -1
- package/web/console/assets/{HelpTip-i-KJhf5s.js → HelpTip-Dtdt2tKR.js} +1 -1
- package/web/console/assets/{Kb-CgLNGjRp.js → Kb-lgY6OXUz.js} +2 -2
- package/web/console/assets/{Login-C52JmXzx.js → Login-DA6BASZd.js} +1 -1
- package/web/console/assets/{Projects-CDOvHPVS.js → Projects-DEbmB_sT.js} +1 -1
- package/web/console/assets/Routes-CyXV4Pba.css +1 -0
- package/web/console/assets/Routes-qS6LLoyS.js +124 -0
- package/web/console/assets/{Runs-DYNDXsqk.js → Runs-DG-VLRSc.js} +1 -1
- package/web/console/assets/{Setup-B91P6i1x.js → Setup-DEpVF5uw.js} +1 -1
- package/web/console/assets/Shell-DgoPgK1E.js +1 -0
- package/web/console/assets/Shell-ykb-tUfo.css +1 -0
- package/web/console/assets/{StorageBuckets-DkuDM0oX.js → StorageBuckets-DJtNN769.js} +1 -1
- package/web/console/assets/{SystemSettings-B7Mqj3k1.js → SystemSettings-0DEUgeTR.js} +1 -1
- package/web/console/assets/{SystemStatus-Db93b6dc.js → SystemStatus-CR1phiPE.js} +1 -1
- package/web/console/assets/{Targets-CuuIYeZO.js → Targets-D65l-IMB.js} +1 -1
- package/web/console/assets/{Tools-CHiqz9XZ.js → Tools-DqtrINrN.js} +1 -1
- package/web/console/assets/Usage-B5njXNjx.js +1 -0
- package/web/console/assets/Usage-CAeDGjrb.css +1 -0
- package/web/console/assets/UsageAccess-CGGaWTuj.css +1 -0
- package/web/console/assets/UsageAccess-ChnB4pjb.js +1 -0
- package/web/console/assets/UsageHelp-BBKIvbQ5.js +1 -0
- package/web/console/assets/UsageHelp-CSM4xO0K.css +1 -0
- package/web/console/assets/{index-QnmD7N7F.js → index-65JiiUr4.js} +1 -1
- package/web/console/assets/{index-Fi9gkGxV.css → index-Cxuc9OCj.css} +1 -1
- package/web/console/assets/index-sLKrJd_p.js +2 -0
- package/web/console/assets/{request-DeGya810.js → request-BpaimqEb.js} +1 -1
- package/web/console/assets/{schema-BqlqLw1R.js → schema-D0Z4kFCZ.js} +1 -1
- package/web/console/assets/{util-4bN2dv7B.js → util-DZYfJ5Zo.js} +1 -1
- package/web/console/assets/{vendor-element-CZoEjZr8.js → vendor-element-8cVcdt5T.js} +2 -2
- package/web/console/assets/{vendor-mammoth-BUEEDX6A.js → vendor-mammoth-CnDA23N0.js} +1 -1
- package/web/console/assets/vendor-vue-Co7x2FW6.js +29 -0
- package/web/console/index.html +4 -4
- package/web-admin/README.md +17 -0
- package/web-admin/package-lock.json +83 -85
- package/web-admin/src/components/UsageDeletionPreview.vue +44 -0
- package/web-admin/src/components/UsageHelp.vue +72 -0
- package/web-admin/src/components/UsageServiceReferences.vue +169 -0
- package/web-admin/src/layout/Shell.vue +22 -5
- package/web-admin/src/pages/Accounts.vue +3 -3
- package/web-admin/src/pages/AgentTasks.vue +2 -2
- package/web-admin/src/pages/Routes.vue +5 -1
- package/web-admin/src/pages/Usage.vue +2470 -0
- package/web-admin/src/pages/UsageAccess.vue +1147 -0
- package/web-admin/src/router.ts +8 -4
- package/web-admin/src/styles/base.css +57 -0
- package/web-admin/src/table-widths.ts +16 -1
- package/web-admin/src/usage-deletion.ts +40 -0
- package/web-admin/src/usage-management.ts +13 -0
- package/web-admin/src/usage-presentation.test.ts +21 -0
- package/web-admin/src/usage-presentation.ts +107 -0
- package/web-admin/src/usage-price-preview.test.ts +60 -0
- package/web-admin/src/usage-price-preview.ts +54 -0
- package/web-admin/tests/token-usage.browser.mjs +773 -0
- package/web-admin/tests/usage-access.browser.mjs +398 -0
- package/web/console/assets/Accounts-B4ePH5jp.css +0 -1
- package/web/console/assets/Accounts-BRCR3O0P.js +0 -3
- package/web/console/assets/AgentTasks--bqL_QKg.js +0 -2
- package/web/console/assets/AgentTasks-C8ox3TyS.css +0 -1
- package/web/console/assets/Routes-DkMIjMQA.css +0 -1
- package/web/console/assets/Routes-X9vHLpKW.js +0 -124
- package/web/console/assets/Shell-Bj6C8Hgo.css +0 -1
- package/web/console/assets/Shell-BsRa7bQQ.js +0 -1
- package/web/console/assets/index-UGvfF3Xr.js +0 -2
- package/web/console/assets/vendor-vue-B2uhHUfE.js +0 -29
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
import assert from 'node:assert/strict';
|
|
2
|
+
import test from 'node:test';
|
|
3
|
+
import { UsageBackgroundWork } from './background-work';
|
|
4
|
+
|
|
5
|
+
function deferred<T>() {
|
|
6
|
+
let resolve!: (value: T) => void;
|
|
7
|
+
const promise = new Promise<T>(done => { resolve = done; });
|
|
8
|
+
return { promise, resolve };
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
function gate() {
|
|
12
|
+
const value = deferred<void>();
|
|
13
|
+
return { promise: value.promise, release: () => value.resolve(undefined) };
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
const turn = () => new Promise<void>(resolve => setImmediate(resolve));
|
|
17
|
+
|
|
18
|
+
test('usage work is already in flight when its factory first runs', async (t) => {
|
|
19
|
+
const owner = new UsageBackgroundWork(), held = gate(), observed = deferred<boolean>();
|
|
20
|
+
t.after(() => held.release());
|
|
21
|
+
const task = owner.track('model-completion', async () => {
|
|
22
|
+
// This is observed from inside the factory, not from private tracker state.
|
|
23
|
+
observed.resolve(await owner.drain(0));
|
|
24
|
+
await held.promise;
|
|
25
|
+
});
|
|
26
|
+
assert.equal(await observed.promise, false);
|
|
27
|
+
held.release();
|
|
28
|
+
await task;
|
|
29
|
+
assert.equal(await owner.drain(100), true);
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
test('drain waits for a late child even when the original snapshot parent does not await it', async (t) => {
|
|
33
|
+
const owner = new UsageBackgroundWork(), parentGate = gate(), childGate = gate();
|
|
34
|
+
const childEntered = deferred<void>();
|
|
35
|
+
t.after(() => { parentGate.release(); childGate.release(); });
|
|
36
|
+
let child: Promise<void> | undefined;
|
|
37
|
+
const parent = owner.track('model-completion', async () => {
|
|
38
|
+
await parentGate.promise;
|
|
39
|
+
child = owner.track('settlement', async () => {
|
|
40
|
+
childEntered.resolve(undefined);
|
|
41
|
+
await childGate.promise;
|
|
42
|
+
});
|
|
43
|
+
// Intentionally finish this parent: a one-snapshot drain would return early.
|
|
44
|
+
});
|
|
45
|
+
owner.beginDrain();
|
|
46
|
+
let drainReturned = false;
|
|
47
|
+
const drained = owner.drain(2000).then(result => { drainReturned = true; return result; });
|
|
48
|
+
parentGate.release();
|
|
49
|
+
await parent;
|
|
50
|
+
await childEntered.promise;
|
|
51
|
+
await turn();
|
|
52
|
+
assert.equal(drainReturned, false);
|
|
53
|
+
assert.equal(await owner.drain(0), false);
|
|
54
|
+
childGate.release();
|
|
55
|
+
assert.ok(child);
|
|
56
|
+
await child;
|
|
57
|
+
assert.equal(await drained, true);
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
test('beginDrain rejects future maintenance before its factory can perform side effects', async () => {
|
|
61
|
+
const owner = new UsageBackgroundWork();
|
|
62
|
+
let acceptedEffects = 0, rejectedEffects = 0;
|
|
63
|
+
const accepted = owner.startMaintenance('response-cleanup', async () => { acceptedEffects++; });
|
|
64
|
+
assert.ok(accepted);
|
|
65
|
+
owner.beginDrain();
|
|
66
|
+
assert.equal(owner.acceptingRequests, false);
|
|
67
|
+
for (const kind of ['response-cleanup', 'usage-reconciliation', 'reference-price-refresh'] as const) {
|
|
68
|
+
assert.equal(owner.startMaintenance(kind, async () => { rejectedEffects++; }), null);
|
|
69
|
+
}
|
|
70
|
+
await accepted;
|
|
71
|
+
await turn();
|
|
72
|
+
assert.equal(acceptedEffects, 1); // Previously accepted maintenance is not cancelled.
|
|
73
|
+
assert.equal(rejectedEffects, 0);
|
|
74
|
+
assert.equal(await owner.drain(0), true);
|
|
75
|
+
assert.equal(owner.acceptingRequests, false);
|
|
76
|
+
});
|
|
77
|
+
|
|
78
|
+
test('zero budget and a timed-out drain retain accepted work for a same-owner retry', async (t) => {
|
|
79
|
+
const owner = new UsageBackgroundWork(), held = gate(), entered = deferred<void>();
|
|
80
|
+
t.after(() => held.release());
|
|
81
|
+
let starts = 0, completed = 0;
|
|
82
|
+
const task = owner.track('model-completion', async () => {
|
|
83
|
+
starts++;
|
|
84
|
+
entered.resolve(undefined);
|
|
85
|
+
await held.promise;
|
|
86
|
+
completed++;
|
|
87
|
+
});
|
|
88
|
+
await entered.promise;
|
|
89
|
+
owner.beginDrain();
|
|
90
|
+
assert.equal(await owner.drain(0), false);
|
|
91
|
+
assert.equal(await owner.drain(10), false);
|
|
92
|
+
assert.equal(starts, 1);
|
|
93
|
+
assert.equal(completed, 0);
|
|
94
|
+
assert.equal(owner.acceptingRequests, false);
|
|
95
|
+
assert.equal(owner.startMaintenance('usage-reconciliation', async () => { completed += 100; }), null);
|
|
96
|
+
held.release();
|
|
97
|
+
await task;
|
|
98
|
+
assert.equal(await owner.drain(100), true);
|
|
99
|
+
assert.equal(starts, 1);
|
|
100
|
+
assert.equal(completed, 1);
|
|
101
|
+
assert.equal(owner.acceptingRequests, false);
|
|
102
|
+
});
|
|
103
|
+
|
|
104
|
+
test('two owners isolate admission and drain; one pending completion cannot hold the other', async (t) => {
|
|
105
|
+
const one = new UsageBackgroundWork(), two = new UsageBackgroundWork(), held = gate();
|
|
106
|
+
t.after(() => held.release());
|
|
107
|
+
let oneCompleted = false, twoCompleted = false;
|
|
108
|
+
const pending = one.track('model-completion', async () => { await held.promise; oneCompleted = true; });
|
|
109
|
+
one.beginDrain();
|
|
110
|
+
assert.equal(two.acceptingRequests, true);
|
|
111
|
+
const independent = two.startMaintenance('usage-reconciliation', async () => { twoCompleted = true; });
|
|
112
|
+
assert.ok(independent);
|
|
113
|
+
two.beginDrain();
|
|
114
|
+
assert.equal(await two.drain(100), true);
|
|
115
|
+
assert.equal(twoCompleted, true);
|
|
116
|
+
assert.equal(oneCompleted, false);
|
|
117
|
+
assert.equal(await one.drain(0), false);
|
|
118
|
+
held.release();
|
|
119
|
+
await pending;
|
|
120
|
+
assert.equal(await one.drain(100), true);
|
|
121
|
+
assert.equal(oneCompleted, true);
|
|
122
|
+
});
|
|
123
|
+
|
|
124
|
+
test('rejected work is drained and reported using only its fixed kind', async () => {
|
|
125
|
+
const owner = new UsageBackgroundWork(), reported: unknown[][] = [];
|
|
126
|
+
owner.setFailureReporter((...args: unknown[]) => { reported.push(args); });
|
|
127
|
+
const failed = owner.track('settlement', async () => {
|
|
128
|
+
throw new Error('Synthetic provider body must not enter lifecycle diagnostics');
|
|
129
|
+
});
|
|
130
|
+
owner.beginDrain();
|
|
131
|
+
await assert.rejects(failed, { message: 'Synthetic provider body must not enter lifecycle diagnostics' });
|
|
132
|
+
assert.equal(await owner.drain(100), true);
|
|
133
|
+
assert.deepEqual(reported, [['settlement']]);
|
|
134
|
+
assert.equal(await owner.drain(0), true);
|
|
135
|
+
});
|
|
136
|
+
|
|
137
|
+
test('a throwing failure reporter cannot keep rejected work live or replace its failure', async () => {
|
|
138
|
+
const owner = new UsageBackgroundWork();
|
|
139
|
+
owner.setFailureReporter(() => { throw new Error('Synthetic diagnostic sink failure'); });
|
|
140
|
+
const failed = owner.track('usage-reconciliation', async () => { throw new Error('Synthetic original work failure'); });
|
|
141
|
+
await assert.rejects(failed, { message: 'Synthetic original work failure' });
|
|
142
|
+
owner.beginDrain();
|
|
143
|
+
assert.equal(await owner.drain(100), true);
|
|
144
|
+
});
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
export type UsageBackgroundKind = 'model-completion' | 'settlement' | 'response-cleanup' | 'usage-reconciliation' | 'reference-price-refresh';
|
|
2
|
+
type MaintenanceKind = Exclude<UsageBackgroundKind, 'model-completion' | 'settlement'>;
|
|
3
|
+
|
|
4
|
+
/** One UsageRepository owns its accepted work, including children created during drain. */
|
|
5
|
+
export class UsageBackgroundWork {
|
|
6
|
+
private readonly pending = new Set<Promise<unknown>>();
|
|
7
|
+
private draining = false;
|
|
8
|
+
private failureReporter: ((kind: UsageBackgroundKind) => void) | undefined;
|
|
9
|
+
|
|
10
|
+
get acceptingRequests(): boolean { return !this.draining; }
|
|
11
|
+
setFailureReporter(reporter: (kind: UsageBackgroundKind) => void): void { this.failureReporter = reporter; }
|
|
12
|
+
beginDrain(): void { this.draining = true; }
|
|
13
|
+
|
|
14
|
+
track<T>(kind: UsageBackgroundKind, run: () => Promise<T>): Promise<T> {
|
|
15
|
+
// Register before invoking run: even an immediately resolving parent must not
|
|
16
|
+
// leave a gap before its SQL/settlement continuation has been registered.
|
|
17
|
+
const work = Promise.resolve().then(run);
|
|
18
|
+
this.pending.add(work);
|
|
19
|
+
void work.then(() => { this.pending.delete(work); }, () => {
|
|
20
|
+
this.pending.delete(work);
|
|
21
|
+
// Report only the fixed work kind; provider bodies, SQL and credentials
|
|
22
|
+
// are never included in lifecycle diagnostics.
|
|
23
|
+
try { this.failureReporter?.(kind); } catch { /* diagnostics cannot own lifecycle */ }
|
|
24
|
+
});
|
|
25
|
+
return work;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
startMaintenance<T>(kind: MaintenanceKind, run: () => Promise<T>): Promise<T> | null {
|
|
29
|
+
return this.draining ? null : this.track(kind, run);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
async drain(drainMs: number): Promise<boolean> {
|
|
33
|
+
const deadline = Date.now() + Math.max(0, drainMs);
|
|
34
|
+
while (this.pending.size) {
|
|
35
|
+
const remaining = deadline - Date.now();
|
|
36
|
+
if (remaining <= 0) return false;
|
|
37
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
38
|
+
try {
|
|
39
|
+
const drained = await Promise.race([
|
|
40
|
+
Promise.allSettled([...this.pending]).then(() => true),
|
|
41
|
+
new Promise<boolean>(resolve => { timer = setTimeout(() => resolve(false), remaining); }),
|
|
42
|
+
]);
|
|
43
|
+
if (!drained) return false;
|
|
44
|
+
} finally { if (timer) clearTimeout(timer); }
|
|
45
|
+
// A tracked completion can register settlement after drain started. Do
|
|
46
|
+
// not mistake a finished snapshot for a quiescent repository.
|
|
47
|
+
}
|
|
48
|
+
return true;
|
|
49
|
+
}
|
|
50
|
+
}
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import type { UsageActor, UsageServiceConfig } from './contracts';
|
|
2
|
+
|
|
3
|
+
export interface BillingAllowanceConfig {
|
|
4
|
+
mode: 'credits' | 'periodic'; priceUsd: number;
|
|
5
|
+
/** Required for periodic plans only; priceUsd remains the sale price. */
|
|
6
|
+
periodAllowanceUsd?: number;
|
|
7
|
+
periodUnit?: 'day' | 'week' | 'month';
|
|
8
|
+
duration: { unit: 'day' | 'month' | 'forever'; count: number };
|
|
9
|
+
}
|
|
10
|
+
export interface PriceLine { billable: string; unit: 'token' | 'image' | 'megapixel' | 'second' | 'request'; costUsd: string; variant?: string }
|
|
11
|
+
export interface PriceTier { minPromptTokens: number; lines: PriceLine[] }
|
|
12
|
+
export interface PriceSnapshot { source: 'openrouter'; modelId: string; endpointId: string; currency: 'USD'; fetchedAt: number; lines: PriceLine[]; tiers?: PriceTier[] }
|
|
13
|
+
export interface BillingRate { planId: string; planRevision: number; multiplier: number; price: PriceSnapshot }
|
|
14
|
+
export interface BillingPlanConfig extends BillingAllowanceConfig { serviceIds: string[]; multiplier: number }
|
|
15
|
+
export interface BillingPlan {
|
|
16
|
+
id: string; label: string; revision: number; state: 'active' | 'suspended';
|
|
17
|
+
config: BillingPlanConfig; createdAt: number; updatedAt: number;
|
|
18
|
+
}
|
|
19
|
+
export interface BillingGrant {
|
|
20
|
+
id: string; accountId: string; planId: string; planRevision: number; label: string;
|
|
21
|
+
revision: number; state: 'active' | 'suspended'; sourceOwner: string;
|
|
22
|
+
startsAt: number; expiresAt: number | null; config: BillingAllowanceConfig;
|
|
23
|
+
}
|
|
24
|
+
export interface BillingSummary {
|
|
25
|
+
schema: 'bailing.billing-summary.v1'; accountId: string; grant: BillingGrant | null;
|
|
26
|
+
plan: Pick<BillingPlan, 'id' | 'label' | 'revision'> & { serviceIds: string[]; multiplier: number } | null;
|
|
27
|
+
availableUsd: number; consumedUsd: number; currentPeriodConsumedUsd: number;
|
|
28
|
+
overageUsd: number; resetAt: number | null; expiresAt: number | null; pendingRequests: number;
|
|
29
|
+
presentation: UsagePresentation;
|
|
30
|
+
}
|
|
31
|
+
/** Customer display only. Raw Token accounting remains an independent machine contract. */
|
|
32
|
+
export interface UsagePresentation {
|
|
33
|
+
schema: 'bailing.usage-presentation.v1';
|
|
34
|
+
kind: 'credits' | 'percentage' | 'none';
|
|
35
|
+
state: 'active' | 'depleted' | 'not_started' | 'expired' | 'suspended' | 'unavailable';
|
|
36
|
+
remaining: number | null; total: number | null; displayValue: string | null;
|
|
37
|
+
}
|
|
38
|
+
export interface TokenUsage { inputTokens: number; outputTokens: number; totalTokens: number }
|
|
39
|
+
export interface BillingRequest {
|
|
40
|
+
id: string; operationId: string; accountId: string; userId: string; sessionId: string;
|
|
41
|
+
serviceId: string; conversationId: string | null; turnId: string | null; requestHash: string;
|
|
42
|
+
revision: number; state: 'admitted' | 'dispatch_committed' | 'completed' | 'unknown' | 'cancelled' | 'failed';
|
|
43
|
+
resultState: 'pending' | 'complete' | 'unknown' | 'cancelled' | 'failed'; billingState: 'pending' | 'settled';
|
|
44
|
+
serviceConfig: UsageServiceConfig; serviceRevision: number; model: string; fence: string | null;
|
|
45
|
+
grantId: string; grantRevision: number; periodStart: number; periodEnd: number | null;
|
|
46
|
+
billingRate: BillingRate;
|
|
47
|
+
grantConfig: BillingAllowanceConfig; response: Record<string, unknown> | null; resultHash: string | null; usage: TokenUsage | null;
|
|
48
|
+
rawUsage: Record<string, unknown> | null; referenceCostUsd: number | null; billedUsd: number | null; overageUsd: number | null; cancelledAt: number | null;
|
|
49
|
+
createdAt: number; updatedAt: number; created?: boolean;
|
|
50
|
+
}
|
|
51
|
+
export interface BillingAdmissionInput {
|
|
52
|
+
actor: UsageActor; operationId: string; serviceId: string; conversationId: string | null;
|
|
53
|
+
turnId: string | null; requestHash: string; expectedServiceRevision: number;
|
|
54
|
+
serviceConfig: UsageServiceConfig; model: string; priceSnapshot: PriceSnapshot;
|
|
55
|
+
}
|
|
56
|
+
export interface BillingCompletionInput {
|
|
57
|
+
response: Record<string, unknown>; usage?: { inputTokens: number; outputTokens: number };
|
|
58
|
+
rawUsage?: Record<string, unknown>; executionId?: string;
|
|
59
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import test from 'node:test';
|
|
2
|
+
import assert from 'node:assert/strict';
|
|
3
|
+
import { usdAmount, usdDecimal, usdMicros, USD_SCALE } from './billing-decimal';
|
|
4
|
+
import { billedUsdMicros, validateBillingPlan } from './billing-ledger';
|
|
5
|
+
|
|
6
|
+
test('USD arithmetic keeps twelve decimals and rejects silent precision loss', () => {
|
|
7
|
+
assert.equal(USD_SCALE, 1_000_000_000_000n);
|
|
8
|
+
assert.equal(usdMicros('0.000000001'), 1000n);
|
|
9
|
+
assert.equal(usdMicros(0.1) + usdMicros(0.2), 300_000_000_000n);
|
|
10
|
+
assert.equal(usdAmount(usdMicros('0.000000000001')), 1e-12);
|
|
11
|
+
assert.equal(usdDecimal(usdMicros('12.012345678912')), '12.012345678912');
|
|
12
|
+
for (const invalid of [1e-13, -1, NaN, Infinity, '1.0000000000001']) assert.throws(() => usdMicros(invalid));
|
|
13
|
+
assert.throws(() => usdAmount(usdMicros('9007199254740990.000000000001')), /exactly/);
|
|
14
|
+
});
|
|
15
|
+
test('uniform multiplier computes money without inventing generated-image tokens', () => {
|
|
16
|
+
assert.equal(usdDecimal(billedUsdMicros('0.2', 1.5)), '0.3');
|
|
17
|
+
assert.equal(usdDecimal(billedUsdMicros('0.000000000001', 0.5)), '0.000000000001');
|
|
18
|
+
assert.equal(usdDecimal(billedUsdMicros('0', 1.5)), '0');
|
|
19
|
+
const config = { mode: 'credits', serviceIds: ['a'], priceUsd: 100, multiplier: 1.5, duration: { unit: 'day', count: 1 } };
|
|
20
|
+
assert.equal(validateBillingPlan(config).multiplier, 1.5);
|
|
21
|
+
assert.throws(() => validateBillingPlan({ ...config, modelRates: {} }), /unsupported/);
|
|
22
|
+
});
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { UsageError, usageAssert } from './errors';
|
|
2
|
+
|
|
3
|
+
export const USD_SCALE = 1_000_000_000_000n;
|
|
4
|
+
const MAX_DECIMAL = 10n ** 30n - 1n;
|
|
5
|
+
/** Parse decimal/scientific notation without multiplying a binary floating point value. */
|
|
6
|
+
export function usdMicros(value: string | number, name = 'amount'): bigint {
|
|
7
|
+
usageAssert((typeof value === 'number' && Number.isFinite(value)) || typeof value === 'string',
|
|
8
|
+
'USAGE_INVALID_INPUT', `${name} must be a finite decimal.`, 400);
|
|
9
|
+
const match = /^(\d+)(?:\.(\d+))?(?:e([+-]?\d+))?$/i.exec(String(value));
|
|
10
|
+
usageAssert(match, 'USAGE_INVALID_INPUT', `${name} must be a nonnegative decimal.`, 400);
|
|
11
|
+
const exponent = Number(match[3] ?? 0), fraction = match[2] ?? '';
|
|
12
|
+
usageAssert(Number.isInteger(exponent) && Math.abs(exponent) <= 30, 'USAGE_INVALID_INPUT', `${name} is outside the decimal range.`, 400);
|
|
13
|
+
const coefficient = BigInt(match[1]! + fraction), shift = 12 + exponent - fraction.length;
|
|
14
|
+
let micros: bigint;
|
|
15
|
+
if (shift >= 0) micros = coefficient * 10n ** BigInt(shift);
|
|
16
|
+
else {
|
|
17
|
+
const divisor = 10n ** BigInt(-shift);
|
|
18
|
+
usageAssert(coefficient % divisor === 0n, 'USAGE_INVALID_INPUT', `${name} allows at most twelve decimal places.`, 400);
|
|
19
|
+
micros = coefficient / divisor;
|
|
20
|
+
}
|
|
21
|
+
usageAssert(micros <= MAX_DECIMAL, 'USAGE_INVALID_INPUT', `${name} is outside the decimal range.`, 400);
|
|
22
|
+
return micros;
|
|
23
|
+
}
|
|
24
|
+
export function usdDecimal(micros: bigint): string {
|
|
25
|
+
usageAssert(micros >= 0n && micros <= MAX_DECIMAL, 'METERING_UNAVAILABLE', 'The recorded amount exceeds the accounting range.', 503);
|
|
26
|
+
const fractional = String(micros % USD_SCALE).padStart(12, '0').replace(/0+$/, '');
|
|
27
|
+
return `${micros / USD_SCALE}${fractional ? `.${fractional}` : ''}`;
|
|
28
|
+
}
|
|
29
|
+
/** Never silently round persisted decimal evidence when serializing the numeric API. */
|
|
30
|
+
export function usdAmount(micros: bigint): number {
|
|
31
|
+
const value = Number(usdDecimal(micros));
|
|
32
|
+
if (value > Number.MAX_SAFE_INTEGER || usdMicros(value) !== micros)
|
|
33
|
+
throw new UsageError('METERING_UNAVAILABLE', 'The amount cannot be represented exactly by the numeric usage interface.', 503, { reason: 'decimal_precision' });
|
|
34
|
+
return value;
|
|
35
|
+
}
|
|
36
|
+
export function positivePart(micros: bigint): bigint { return micros > 0n ? micros : 0n; }
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import type { IncomingMessage, ServerResponse } from 'node:http';
|
|
2
|
+
import { readBody, send } from '../../app/http';
|
|
3
|
+
import { usageAssert } from './errors';
|
|
4
|
+
import { authenticateUsageIssuerRequest, getUsageIdentity, usageFields, usageKey } from './identity';
|
|
5
|
+
import { getBillingRepository } from './billing-repository';
|
|
6
|
+
import type { UsageRepository } from './repository';
|
|
7
|
+
|
|
8
|
+
/** External products can use the same plan/grant implementation with explicit source ownership. */
|
|
9
|
+
export async function handleExternalBillingUsage(repository: UsageRepository, req: IncomingMessage, res: ServerResponse, url: URL): Promise<boolean> {
|
|
10
|
+
const match = url.pathname.match(/^\/usage\/v1\/external\/billing\/accounts\/([A-Za-z0-9_.:-]+)\/(summary|grant|control)$/);
|
|
11
|
+
const plans = url.pathname === '/usage/v1/external/billing/plans';
|
|
12
|
+
if (!match && !plans) return false;
|
|
13
|
+
const identity = getUsageIdentity(repository), tokens = getBillingRepository(repository);
|
|
14
|
+
usageAssert(await tokens.ready(), 'USAGE_UNSUPPORTED', '美元套餐尚未就绪。', 503);
|
|
15
|
+
const { issuer } = await authenticateUsageIssuerRequest(identity, req, req.method === 'GET' ? 'usage:read' : 'entitlements:write');
|
|
16
|
+
if (plans) {
|
|
17
|
+
usageAssert(req.method === 'GET', 'USAGE_INVALID_INPUT', '使用只读套餐目录。', 405);
|
|
18
|
+
send(res, 200, { items: (await tokens.listPlans()).filter(plan => plan.config.serviceIds.every(id => issuer.serviceIds.includes(id))) }); return true;
|
|
19
|
+
}
|
|
20
|
+
const [, accountId, action] = match!;
|
|
21
|
+
const summary = await tokens.summary(accountId!);
|
|
22
|
+
if (req.method === 'GET' && action === 'summary') {
|
|
23
|
+
// Account ownership must be proven even when no new billing grant exists yet.
|
|
24
|
+
await identity.requireIssuerAccount(issuer, accountId!);
|
|
25
|
+
send(res, 200, summary); return true;
|
|
26
|
+
}
|
|
27
|
+
usageAssert(req.method === 'POST' && (action === 'grant' || action === 'control'), 'USAGE_INVALID_INPUT', '不支持的套餐操作。', 405);
|
|
28
|
+
const body = await readBody(req, 8192);
|
|
29
|
+
if (action === 'grant') {
|
|
30
|
+
const fields = usageFields(body, ['request_key','plan_id','expected_revision','starts_at'], ['request_key','plan_id','expected_revision']);
|
|
31
|
+
const plan = (await tokens.listPlans()).find(p => p.id === usageKey(fields.plan_id, 'plan_id'));
|
|
32
|
+
usageAssert(plan, 'USAGE_NOT_FOUND', '套餐不存在。', 404);
|
|
33
|
+
usageAssert(plan.config.serviceIds.every(id => issuer.serviceIds.includes(id)), 'USAGE_FORBIDDEN', '此来源未获准发放该套餐。', 403);
|
|
34
|
+
}
|
|
35
|
+
await identity.requireIssuerAccount(issuer, accountId!);
|
|
36
|
+
if (action === 'grant') usageAssert(issuer.permissions.includes('allowance:grant'), 'USAGE_FORBIDDEN', '开通额度还需要 allowance:grant 权限。', 403);
|
|
37
|
+
send(res, 200, action === 'grant' ? await tokens.grant(accountId!, body, `issuer:${issuer.id}`) : await tokens.control(accountId!, body, `issuer:${issuer.id}`));
|
|
38
|
+
return true;
|
|
39
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import test from 'node:test';
|
|
2
|
+
import assert from 'node:assert/strict';
|
|
3
|
+
import { randomUUID } from 'node:crypto';
|
|
4
|
+
import { createUsageTestHarness } from './test-harness';
|
|
5
|
+
const enabled = process.env.BAILING_USAGE_TEST_MYSQL === '1';
|
|
6
|
+
test('USD HTTP: plan-wide multiplier and original price snapshot survive a plan edit', {skip:!enabled},async()=>{
|
|
7
|
+
const h=await createUsageTestHarness();try{
|
|
8
|
+
const user=await h.seedUser({grant:false}),id=randomUUID();
|
|
9
|
+
const config={mode:'credits',priceUsd:1000,multiplier:1.5,serviceIds:[h.service.id],duration:{unit:'month',count:1}};
|
|
10
|
+
assert.equal((await h.request('/admin/api/usage/billing/plans','synthetic-admin','POST',{id,label:'Synthetic',expected_revision:0,config})).status,200);
|
|
11
|
+
assert.equal((await h.request(`/admin/api/usage/billing/accounts/${user.accountId}/grant`,'synthetic-admin','POST',{request_key:randomUUID(),plan_id:id,expected_revision:0})).status,200);
|
|
12
|
+
const models=await h.request('/usage/v1/model/models',user.token);assert.deepEqual(models.body.items[0].billing_rate,{multiplier:1.5});
|
|
13
|
+
const input={operation_id:randomUUID(),messages:[{role:'user',content:'Synthetic'}]};
|
|
14
|
+
const first=await h.request('/usage/v1/model/requests',user.token,'POST',input);assert.equal(first.status,200,JSON.stringify(first.body));
|
|
15
|
+
await h.tokens.drainSettlements();
|
|
16
|
+
assert.equal((await h.request('/admin/api/usage/billing/plans','synthetic-admin','POST',{id,label:'Synthetic',expected_revision:1,config:{...config,multiplier:2}})).status,200);
|
|
17
|
+
const replay=await h.request('/usage/v1/model/requests',user.token,'POST',input);
|
|
18
|
+
assert.equal(replay.body.reference_cost_usd,25);assert.equal(replay.body.billed_usd,37.5);assert.deepEqual(replay.body.billing_rate,first.body.billing_rate);assert.equal(h.state.calls,1);
|
|
19
|
+
const next=await h.request('/usage/v1/model/requests',user.token,'POST',{...input,operation_id:randomUUID()});await h.tokens.drainSettlements();
|
|
20
|
+
assert.equal((await h.request(`/usage/v1/model/requests/${next.body.operation_id}`,user.token)).body.billed_usd,50);
|
|
21
|
+
const summary=(await h.request('/usage/v1/model/summary',user.token)).body;assert.equal(summary.availableUsd,912.5);assert.equal(summary.consumedUsd,87.5);
|
|
22
|
+
assert.equal(summary.presentation.displayValue,'912500');
|
|
23
|
+
}finally{await h.close();}
|
|
24
|
+
});
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import test from 'node:test';
|
|
2
|
+
import assert from 'node:assert/strict';
|
|
3
|
+
import { billingAllowance, billingExpiry, billingPeriod, tokenUsage, validateBillingPlan } from './billing-ledger';
|
|
4
|
+
import type { BillingPlanConfig } from './billing-contracts';
|
|
5
|
+
const config: BillingPlanConfig = { mode: 'periodic', serviceIds: ['synthetic-model'], priceUsd: 1000, periodAllowanceUsd: 1000, periodUnit: 'month', duration: { unit: 'month', count: 3 }, multiplier: 1.5 };
|
|
6
|
+
test('Token plans reject turn limits and invalid units; Credits changes display only', () => {
|
|
7
|
+
assert.deepEqual(validateBillingPlan(config), config);
|
|
8
|
+
assert.throws(() => validateBillingPlan({ ...config, maxOperationsPerTurn: 8 }), /unsupported fields/);
|
|
9
|
+
assert.throws(() => validateBillingPlan({ ...config, priceUsd: 0 }), /range/);
|
|
10
|
+
assert.throws(() => validateBillingPlan({ ...config, duration: { unit: 'forever', count: 0 } }), /expiry/);
|
|
11
|
+
assert.throws(() => validateBillingPlan({ ...config, serviceIds: ['one','one'] }), /unique/);
|
|
12
|
+
assert.throws(() => validateBillingPlan({ ...config, multiplier: 0 }), /between/);
|
|
13
|
+
assert.deepEqual(tokenUsage({ inputTokens: 60, outputTokens: 40 }), { inputTokens: 60, outputTokens: 40, totalTokens: 100 });
|
|
14
|
+
assert.throws(() => tokenUsage({ inputTokens: Number.MAX_SAFE_INTEGER, outputTokens: 1 }), /range/);
|
|
15
|
+
assert.throws(() => validateBillingPlan({ ...config, displayUnit: 'credits' }), /unsupported fields/);
|
|
16
|
+
assert.throws(() => validateBillingPlan({ ...config, displayUnit: 'tokens' }), /unsupported fields/);
|
|
17
|
+
for (const field of ['quotaTokens','tokensPerCredit','modelRates']) assert.throws(() => validateBillingPlan({ ...config, [field]: 1 }), /unsupported fields/);
|
|
18
|
+
});
|
|
19
|
+
test('Calendar expiry and reset preserve grant anchor, month end, expiry and no rollover', () => {
|
|
20
|
+
const start = Date.UTC(2028, 0, 31, 12, 30, 45, 123), expiresAt = billingExpiry(start, config.duration);
|
|
21
|
+
assert.equal(expiresAt, Date.UTC(2028, 3, 30, 12, 30, 45, 123));
|
|
22
|
+
const grant = { startsAt: start, expiresAt, config };
|
|
23
|
+
assert.equal(billingPeriod(grant, Date.UTC(2028, 1, 29, 12, 30, 45, 122))!.start, start);
|
|
24
|
+
assert.deepEqual(billingPeriod(grant, Date.UTC(2028, 1, 29, 12, 30, 45, 123)), { start: Date.UTC(2028, 1, 29, 12, 30, 45, 123), end: Date.UTC(2028, 2, 31, 12, 30, 45, 123) });
|
|
25
|
+
assert.equal(billingPeriod(grant, start - 1), null);
|
|
26
|
+
assert.equal(billingPeriod(grant, expiresAt!), null);
|
|
27
|
+
});
|
|
28
|
+
|
|
29
|
+
test('plan models may be empty; allowance snapshots explicitly exclude model selection', () => {
|
|
30
|
+
assert.deepEqual(validateBillingPlan({ ...config, serviceIds: [] }).serviceIds, []);
|
|
31
|
+
const { serviceIds: _models, multiplier: _multiplier, ...allowance } = config;
|
|
32
|
+
assert.deepEqual(billingAllowance(config), allowance);
|
|
33
|
+
assert.equal('serviceIds' in billingAllowance(config), false);
|
|
34
|
+
assert.notEqual(billingAllowance(config).duration, config.duration);
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
test('periodic allowance is explicit and independent of sale price; credits have no period allowance', () => {
|
|
38
|
+
const periodic = { ...config, priceUsd: 100, periodAllowanceUsd: 20, periodUnit: 'week' as const };
|
|
39
|
+
assert.equal(validateBillingPlan(periodic).periodAllowanceUsd, 20);
|
|
40
|
+
for (const invalid of [undefined, null, 0, -1, Infinity, NaN, '20', 1_000_000_001]) {
|
|
41
|
+
assert.throws(() => validateBillingPlan({ ...periodic, periodAllowanceUsd: invalid }), /periodAllowanceUsd/);
|
|
42
|
+
}
|
|
43
|
+
assert.throws(() => validateBillingPlan({ ...periodic, periodAllowanceUsd: 0.0000000000001 }), /periodAllowanceUsd/);
|
|
44
|
+
const { periodAllowanceUsd: _allowance, periodUnit: _period, ...base } = periodic;
|
|
45
|
+
const credits = { ...base, mode: 'credits' as const };
|
|
46
|
+
assert.equal(validateBillingPlan(credits).priceUsd, 100);
|
|
47
|
+
assert.throws(() => validateBillingPlan({ ...credits, periodAllowanceUsd: 20 }), /do not accept/);
|
|
48
|
+
for (const unknown of ['periodQuotaUsd', 'maxRequests', 'maxTurns']) {
|
|
49
|
+
assert.throws(() => validateBillingPlan({ ...periodic, [unknown]: 1 }), /unsupported fields/);
|
|
50
|
+
}
|
|
51
|
+
});
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
import { usageAssert } from './errors';
|
|
2
|
+
import { assertKnownFields, integer } from './validation';
|
|
3
|
+
import { periodBounds } from './period';
|
|
4
|
+
import { usdMicros, USD_SCALE } from './billing-decimal';
|
|
5
|
+
import type { BillingAllowanceConfig, BillingRate, BillingGrant, PriceSnapshot, BillingPlanConfig, TokenUsage } from './billing-contracts';
|
|
6
|
+
|
|
7
|
+
export function billingKey(value: unknown, name = 'id', max = 191): string {
|
|
8
|
+
usageAssert(typeof value === 'string' && value.length > 0 && value.length <= max && /^[A-Za-z0-9][A-Za-z0-9_.:-]*$/.test(value),
|
|
9
|
+
'USAGE_INVALID_INPUT', `Invalid ${name}.`, 400);
|
|
10
|
+
return value;
|
|
11
|
+
}
|
|
12
|
+
export function validateBillingPlan(value: unknown): BillingPlanConfig {
|
|
13
|
+
assertKnownFields(value, ['mode','serviceIds','priceUsd','periodAllowanceUsd','multiplier','periodUnit','duration'], 'USD plan');
|
|
14
|
+
const c = value as BillingPlanConfig;
|
|
15
|
+
usageAssert(Array.isArray(c.serviceIds) && c.serviceIds.length <= 64, 'USAGE_INVALID_INPUT', 'Model services must be an explicit list.', 400);
|
|
16
|
+
c.serviceIds.forEach(id => billingKey(id, 'serviceId'));
|
|
17
|
+
usageAssert(new Set(c.serviceIds).size === c.serviceIds.length, 'USAGE_INVALID_INPUT', 'Model services must be unique.', 400);
|
|
18
|
+
return { ...billingAllowance(c), serviceIds: [...c.serviceIds], multiplier: validateMultiplier(c.multiplier) };
|
|
19
|
+
}
|
|
20
|
+
/** Project immutable allowance terms; model selection belongs only to the current plan. */
|
|
21
|
+
export function billingAllowance(value: BillingAllowanceConfig): BillingAllowanceConfig {
|
|
22
|
+
const c = value;
|
|
23
|
+
usageAssert(['credits','periodic'].includes(c.mode), 'USAGE_INVALID_INPUT', 'Choose an allowance pack or a periodic plan.', 400);
|
|
24
|
+
usageAssert(typeof c.priceUsd === 'number' && c.priceUsd > 0 && c.priceUsd <= 1_000_000_000, 'USAGE_INVALID_INPUT', 'priceUsd must be positive and within range.', 400);
|
|
25
|
+
usdMicros(c.priceUsd, 'priceUsd');
|
|
26
|
+
if (c.mode === 'periodic') {
|
|
27
|
+
usageAssert(typeof c.periodAllowanceUsd === 'number' && c.periodAllowanceUsd > 0 && c.periodAllowanceUsd <= 1_000_000_000,
|
|
28
|
+
'USAGE_INVALID_INPUT', 'periodAllowanceUsd must be positive and within range for periodic plans.', 400);
|
|
29
|
+
usdMicros(c.periodAllowanceUsd, 'periodAllowanceUsd');
|
|
30
|
+
} else usageAssert(c.periodAllowanceUsd === undefined, 'USAGE_INVALID_INPUT', 'Credits plans do not accept periodAllowanceUsd.', 400);
|
|
31
|
+
usageAssert(c.mode === 'periodic' ? ['day','week','month'].includes(c.periodUnit ?? '') : c.periodUnit === undefined,
|
|
32
|
+
'USAGE_INVALID_INPUT', 'Periodic plans require one reset schedule; allowance packs have no reset.', 400);
|
|
33
|
+
assertKnownFields(c.duration, ['unit','count'], 'duration');
|
|
34
|
+
usageAssert(['day','month','forever'].includes(c.duration.unit), 'USAGE_INVALID_INPUT', 'Unsupported duration.', 400);
|
|
35
|
+
usageAssert(c.duration.unit !== 'forever' || c.mode === 'credits', 'USAGE_INVALID_INPUT', 'Periodic subscriptions need an expiry.', 400);
|
|
36
|
+
integer(c.duration.count, 'duration.count', c.duration.unit === 'forever' ? 0 : 1, 1200);
|
|
37
|
+
return { mode: c.mode, priceUsd: c.priceUsd, duration: structuredClone(c.duration),
|
|
38
|
+
...(c.mode === 'periodic' ? { periodAllowanceUsd: c.periodAllowanceUsd } : {}),
|
|
39
|
+
...(c.periodUnit === undefined ? {} : { periodUnit: c.periodUnit }) };
|
|
40
|
+
}
|
|
41
|
+
/** Effective allowance from explicit terms; never infer periodic allowance from sale price. */
|
|
42
|
+
export function billingAllowanceUsd(config: BillingAllowanceConfig): number {
|
|
43
|
+
const terms = billingAllowance(config);
|
|
44
|
+
return terms.mode === 'periodic' ? terms.periodAllowanceUsd! : terms.priceUsd;
|
|
45
|
+
}
|
|
46
|
+
/** Calendar months retain the original UTC day, clamping only in shorter months. */
|
|
47
|
+
export function billingExpiry(startsAt: number, duration: BillingAllowanceConfig['duration']): number | null {
|
|
48
|
+
integer(startsAt, 'startsAt', 0, 8_000_000_000_000_000);
|
|
49
|
+
if (duration.unit === 'forever') return null;
|
|
50
|
+
if (duration.unit === 'day') return integer(startsAt + duration.count * 86_400_000, 'expiresAt');
|
|
51
|
+
const start = new Date(startsAt), out = new Date(startsAt);
|
|
52
|
+
out.setUTCDate(1); out.setUTCMonth(out.getUTCMonth() + duration.count);
|
|
53
|
+
out.setUTCDate(Math.min(start.getUTCDate(), new Date(Date.UTC(out.getUTCFullYear(), out.getUTCMonth() + 1, 0)).getUTCDate()));
|
|
54
|
+
return integer(out.getTime(), 'expiresAt');
|
|
55
|
+
}
|
|
56
|
+
export function billingPeriod(grant: Pick<BillingGrant, 'startsAt' | 'expiresAt' | 'config'>, now: number): { start: number; end: number | null } | null {
|
|
57
|
+
if (now < grant.startsAt || (grant.expiresAt !== null && now >= grant.expiresAt)) return null;
|
|
58
|
+
if (grant.config.mode === 'credits') return { start: grant.startsAt, end: grant.expiresAt };
|
|
59
|
+
const p = periodBounds({ unit: grant.config.periodUnit!, anchor: grant.startsAt, timezone: 'UTC' }, now)!;
|
|
60
|
+
return { start: p.start, end: Math.min(p.end, grant.expiresAt ?? p.end) };
|
|
61
|
+
}
|
|
62
|
+
export function tokenUsage(value: { inputTokens: number; outputTokens: number }): TokenUsage {
|
|
63
|
+
const inputTokens = integer(value.inputTokens, 'inputTokens'), outputTokens = integer(value.outputTokens, 'outputTokens');
|
|
64
|
+
return { inputTokens, outputTokens, totalTokens: integer(inputTokens + outputTokens, 'totalTokens') };
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export function validateMultiplier(value: unknown): number {
|
|
68
|
+
usageAssert(typeof value === 'number' && value >= 0.000001 && value <= 1000,
|
|
69
|
+
'USAGE_INVALID_INPUT', 'multiplier must be between 0.000001 and 1000.', 400);
|
|
70
|
+
usdMicros(value, 'multiplier'); return value;
|
|
71
|
+
}
|
|
72
|
+
export function tokenBillingRate(planId: string, planRevision: number, multiplier: number, price: PriceSnapshot): BillingRate {
|
|
73
|
+
billingKey(planId, 'planId'); integer(planRevision, 'planRevision', 1);
|
|
74
|
+
usageAssert(price?.source === 'openrouter' && price.currency === 'USD' && typeof price.modelId === 'string' && price.modelId.length > 0
|
|
75
|
+
&& typeof price.endpointId === 'string' && price.endpointId.length > 0 && Array.isArray(price.lines) && price.lines.length > 0,
|
|
76
|
+
'METERING_UNAVAILABLE', 'A verified reference price snapshot is required.', 503);
|
|
77
|
+
integer(price.fetchedAt, 'fetchedAt');
|
|
78
|
+
const lineSets = [price.lines];
|
|
79
|
+
if (price.tiers !== undefined) {
|
|
80
|
+
usageAssert(Array.isArray(price.tiers) && price.tiers.length <= 64, 'METERING_UNAVAILABLE', 'Invalid reference price tiers.', 503);
|
|
81
|
+
const seen = new Set<number>();
|
|
82
|
+
for (const tier of price.tiers) {
|
|
83
|
+
usageAssert(Number.isSafeInteger(tier.minPromptTokens) && tier.minPromptTokens > 0 && !seen.has(tier.minPromptTokens),
|
|
84
|
+
'METERING_UNAVAILABLE', 'Reference price thresholds must be unique positive token counts.', 503);
|
|
85
|
+
seen.add(tier.minPromptTokens); lineSets.push(tier.lines);
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
for (const lines of lineSets) {
|
|
89
|
+
usageAssert(Array.isArray(lines) && lines.length > 0 && lines.length <= 64, 'METERING_UNAVAILABLE', 'Invalid reference price lines.', 503);
|
|
90
|
+
for (const line of lines) {
|
|
91
|
+
const validUnit = ['prompt','completion','input_cache_read','input_cache_write'].includes(line.billable) ? line.unit === 'token'
|
|
92
|
+
: ['input_image','output_image','input_reference'].includes(line.billable) ? ['token','image','megapixel'].includes(line.unit)
|
|
93
|
+
: ['request','web_search'].includes(line.billable) && line.unit === 'request';
|
|
94
|
+
usageAssert(validUnit, 'METERING_UNAVAILABLE', 'Invalid reference price line.', 503);
|
|
95
|
+
usdMicros(line.costUsd, 'costUsd');
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
return { planId, planRevision, multiplier: validateMultiplier(multiplier), price: structuredClone(price) };
|
|
99
|
+
}
|
|
100
|
+
/** Round a positive sub-unit charge up, never silently turn it into free usage. */
|
|
101
|
+
export function billedUsdMicros(referenceCostUsd: string, multiplier: number): bigint {
|
|
102
|
+
const product = usdMicros(referenceCostUsd) * usdMicros(validateMultiplier(multiplier));
|
|
103
|
+
return (product + USD_SCALE - 1n) / USD_SCALE;
|
|
104
|
+
}
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import test from 'node:test';
|
|
2
|
+
import assert from 'node:assert/strict';
|
|
3
|
+
import { randomUUID } from 'node:crypto';
|
|
4
|
+
import { createUsageTestHarness } from './test-harness';
|
|
5
|
+
import { getBillingRepository } from './billing-repository';
|
|
6
|
+
import { billingAllowance } from './billing-ledger';
|
|
7
|
+
import { billingPeriod } from './billing-ledger';
|
|
8
|
+
import type { BillingPlanConfig } from './billing-contracts';
|
|
9
|
+
|
|
10
|
+
const enabled = process.env.BAILING_USAGE_TEST_MYSQL === '1';
|
|
11
|
+
test('customer allowance presentation uses persisted authority and all summary APIs agree', { skip: !enabled }, async t => {
|
|
12
|
+
const h = await createUsageTestHarness(), tokens = getBillingRepository(h.repository);
|
|
13
|
+
const config: BillingPlanConfig = { mode: 'credits', serviceIds: [h.service.id], priceUsd: 10_000, multiplier: 1, duration: { unit: 'month', count: 1 } };
|
|
14
|
+
const dbNow = async () => Number((await h.pool.query<any[]>('SELECT CAST(UNIX_TIMESTAMP(CURRENT_TIMESTAMP(3))*1000 AS UNSIGNED) AS ms'))[0][0].ms);
|
|
15
|
+
async function open(c = config, startsAt?: number) {
|
|
16
|
+
const user = await h.seedUser({ grant: false }), id = randomUUID();
|
|
17
|
+
await tokens.putPlan({ id, label: 'Synthetic allowance', expected_revision: 0, config: c });
|
|
18
|
+
const grant = await tokens.grant(user.accountId, { request_key: id, plan_id: id, expected_revision: 0, ...(startsAt === undefined ? {} : { starts_at: startsAt }) });
|
|
19
|
+
return { ...user, grant, planId: id };
|
|
20
|
+
}
|
|
21
|
+
async function allSummaries(user: { accountId: string; token: string }) {
|
|
22
|
+
const results = await Promise.all([
|
|
23
|
+
h.request('/usage/v1/model/summary', user.token),
|
|
24
|
+
h.request(`/admin/api/usage/billing/accounts/${user.accountId}/summary`, 'synthetic-admin'),
|
|
25
|
+
h.request(`/usage/v1/external/billing/accounts/${user.accountId}/summary`, h.issuerToken),
|
|
26
|
+
]);
|
|
27
|
+
results.forEach(r => assert.equal(r.status, 200, JSON.stringify(r.body)));
|
|
28
|
+
assert.deepEqual(results[0]!.body.presentation, results[1]!.body.presentation);
|
|
29
|
+
assert.deepEqual(results[0]!.body.presentation, results[2]!.body.presentation);
|
|
30
|
+
return results[0]!.body;
|
|
31
|
+
}
|
|
32
|
+
try {
|
|
33
|
+
await t.test('no grant is unavailable, identity stays usable, removed display selector is rejected', async () => {
|
|
34
|
+
const user = await h.seedUser({ grant: false }), summary = await allSummaries(user);
|
|
35
|
+
assert.deepEqual(summary.presentation, { schema: 'bailing.usage-presentation.v1', kind: 'none', state: 'unavailable', remaining: null, total: null, displayValue: null });
|
|
36
|
+
const bad = await h.request('/admin/api/usage/billing/plans', 'synthetic-admin', 'POST', { id: randomUUID(), label: 'Unsupported selector', expected_revision: 0, config: { ...config, displayUnit: 'tokens' } });
|
|
37
|
+
assert.equal(bad.status, 400); assert.equal(h.state.calls, 0);
|
|
38
|
+
});
|
|
39
|
+
await t.test('credits reflect actual usage; pending billing does not erase balance; reads never debit or regrant', async () => {
|
|
40
|
+
const user = await open(), operation = randomUUID();
|
|
41
|
+
const result = await h.request('/usage/v1/model/requests', user.token, 'POST', { operation_id: operation, messages: [{ role: 'user', content: 'Synthetic' }] });
|
|
42
|
+
assert.equal(result.body.billing_state, 'pending');
|
|
43
|
+
await h.tokens.drainSettlements();
|
|
44
|
+
const saved = await h.request(`/usage/v1/model/requests/${operation}`, user.token);
|
|
45
|
+
assert.equal(saved.body.billed_usd, 25);
|
|
46
|
+
let summary = await allSummaries(user);
|
|
47
|
+
assert.deepEqual(summary.presentation, { schema: 'bailing.usage-presentation.v1', kind: 'credits', state: 'active', remaining: 9_975_000, total: 10_000_000, displayValue: '9975000' });
|
|
48
|
+
h.state.mode = 'missing_usage';
|
|
49
|
+
const pending = await h.request('/usage/v1/model/requests', user.token, 'POST', { operation_id: randomUUID(), messages: [{ role: 'user', content: 'Synthetic pending' }] });
|
|
50
|
+
assert.equal(pending.body.result_state, 'complete'); assert.equal(pending.body.billing_state, 'pending'); h.state.mode = 'ok';
|
|
51
|
+
summary = await allSummaries(user); assert.equal(summary.pendingRequests, 1); assert.equal(summary.presentation.displayValue, '9975000');
|
|
52
|
+
for (let i = 0; i < 3; i++) await allSummaries(user);
|
|
53
|
+
const [rows] = await h.pool.query<any[]>('SELECT (SELECT COUNT(*) FROM bz_usage_billing_grants WHERE account_id=?) AS grants,(SELECT COUNT(*) FROM bz_usage_billing_ledger WHERE account_id=?) AS ledger', [user.accountId,user.accountId]);
|
|
54
|
+
assert.equal(Number(rows[0].grants), 1); assert.equal(Number(rows[0].ledger), 1);
|
|
55
|
+
assert.equal(summary.grant.id, user.grant.id); assert.equal(summary.grant.revision, 1);
|
|
56
|
+
});
|
|
57
|
+
await t.test('template mode and conversion edits do not change an existing grant or its presentation', async () => {
|
|
58
|
+
const user = await open();
|
|
59
|
+
await tokens.putPlan({ id: user.planId, label: 'Periodic template', expected_revision: 1, config: { ...config, mode: 'periodic', periodAllowanceUsd: 123, periodUnit: 'week', multiplier: 7, priceUsd: 123 } });
|
|
60
|
+
const summary = await allSummaries(user);
|
|
61
|
+
assert.equal(summary.presentation.kind, 'credits'); assert.equal(summary.presentation.total, 10_000_000);
|
|
62
|
+
assert.equal(summary.grant.id, user.grant.id); assert.equal(summary.grant.planRevision, 1); assert.equal(summary.grant.revision, 1);
|
|
63
|
+
assert.deepEqual(summary.grant.config, billingAllowance(config));
|
|
64
|
+
});
|
|
65
|
+
await t.test('periodic projection uses current period only and clamps overage to depleted zero', async () => {
|
|
66
|
+
const now = await dbNow(), startsAt = now - 86_400_000 - 1000;
|
|
67
|
+
const user = await open({ ...config, mode: 'periodic', periodAllowanceUsd: 1000, periodUnit: 'day', priceUsd: 1000 }, startsAt);
|
|
68
|
+
const period = billingPeriod(user.grant, now)!;
|
|
69
|
+
await h.pool.execute('INSERT INTO bz_usage_billing_periods (grant_id,period_start,period_end,allowance_usd,consumed_usd) VALUES (?,?,?,?,?),(?,?,?,?,?)',
|
|
70
|
+
[user.grant.id,startsAt,startsAt + 86_400_000,1000,1000,user.grant.id,period.start,period.end,1000,875]);
|
|
71
|
+
let summary = await allSummaries(user);
|
|
72
|
+
assert.equal(summary.consumedUsd, 1875); assert.equal(summary.currentPeriodConsumedUsd, 875);
|
|
73
|
+
assert.deepEqual(summary.presentation, { schema: 'bailing.usage-presentation.v1', kind: 'percentage', state: 'active', remaining: 12.5, total: 100, displayValue: '12' });
|
|
74
|
+
await h.pool.execute('UPDATE bz_usage_billing_periods SET consumed_usd=1005 WHERE grant_id=? AND period_start=?', [user.grant.id,period.start]);
|
|
75
|
+
summary = await allSummaries(user); assert.equal(summary.presentation.state, 'depleted'); assert.equal(summary.presentation.remaining, 0); assert.equal(summary.presentation.displayValue, '0');
|
|
76
|
+
assert.equal(summary.overageUsd, 5);
|
|
77
|
+
});
|
|
78
|
+
await t.test('future, expired and suspended state comes from persisted grant and account with DB time', async () => {
|
|
79
|
+
const future = await open(config, await dbNow() + 60_000);
|
|
80
|
+
assert.equal((await allSummaries(future)).presentation.state, 'not_started');
|
|
81
|
+
const user = await open();
|
|
82
|
+
await h.pool.execute('UPDATE bz_usage_billing_grants SET expires_at=? WHERE id=?', [await dbNow() - 1,user.grant.id]);
|
|
83
|
+
let summary = await allSummaries(user); assert.equal(summary.presentation.state, 'expired'); assert.equal(summary.presentation.remaining, null); assert.equal(summary.presentation.displayValue, null);
|
|
84
|
+
await h.pool.execute("UPDATE bz_usage_billing_grants SET state='suspended' WHERE id=?", [user.grant.id]);
|
|
85
|
+
summary = await allSummaries(user); assert.equal(summary.presentation.state, 'suspended'); assert.equal(summary.presentation.remaining, null);
|
|
86
|
+
const account = await open();
|
|
87
|
+
await h.pool.execute("UPDATE bz_usage_accounts SET state='suspended' WHERE id=?", [account.accountId]);
|
|
88
|
+
assert.equal((await h.request('/usage/v1/model/summary', account.token)).status, 403);
|
|
89
|
+
const admin = await h.request(`/admin/api/usage/billing/accounts/${account.accountId}/summary`, 'synthetic-admin');
|
|
90
|
+
const external = await h.request(`/usage/v1/external/billing/accounts/${account.accountId}/summary`, h.issuerToken);
|
|
91
|
+
assert.equal(admin.body.presentation.state, 'suspended'); assert.equal(admin.body.presentation.remaining, null); assert.deepEqual(external.body.presentation, admin.body.presentation);
|
|
92
|
+
assert.equal((await h.request('/usage/v1/model/summary?now=0', future.token)).status, 400);
|
|
93
|
+
});
|
|
94
|
+
} finally { await h.close(); }
|
|
95
|
+
});
|