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,325 @@
|
|
|
1
|
+
import assert from 'node:assert/strict';
|
|
2
|
+
import test from 'node:test';
|
|
3
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
4
|
+
import { mkdtempSync, rmSync } from 'node:fs';
|
|
5
|
+
import { tmpdir } from 'node:os';
|
|
6
|
+
import { join } from 'node:path';
|
|
7
|
+
import { createServer } from 'node:http';
|
|
8
|
+
import type { AddressInfo } from 'node:net';
|
|
9
|
+
import { setTimeout as delay } from 'node:timers/promises';
|
|
10
|
+
import { createPool } from 'mysql2/promise';
|
|
11
|
+
import type { AppConfig } from '../core/config/config';
|
|
12
|
+
import { migrateBailingHubCoreSchema } from '../infrastructure/schema/core-schema-migrator';
|
|
13
|
+
import { UsageRepository } from '../modules/usage/repository';
|
|
14
|
+
import { getUsageIdentity } from '../modules/usage/identity';
|
|
15
|
+
import { BillingRepository, getBillingRepository } from '../modules/usage/billing-repository';
|
|
16
|
+
import { ReferencePricing } from '../modules/usage/pricing';
|
|
17
|
+
import type { BillingRequest } from '../modules/usage/billing-contracts';
|
|
18
|
+
import { createBailingHubKernel } from './kernel';
|
|
19
|
+
|
|
20
|
+
const enabled = process.env.BAILING_USAGE_TEST_MYSQL === '1';
|
|
21
|
+
function gate() {
|
|
22
|
+
let release!: () => void;
|
|
23
|
+
const promise = new Promise<void>(resolve => { release = resolve; });
|
|
24
|
+
return { promise, release };
|
|
25
|
+
}
|
|
26
|
+
async function until(predicate: () => boolean, message: string) {
|
|
27
|
+
for (let i = 0; i < 300; i++) { if (predicate()) return; await delay(10); }
|
|
28
|
+
throw new Error(message);
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** Fresh loopback schema and synthetic provider; never loads deployment configuration. */
|
|
32
|
+
async function fixture(schedulerMode: 'managed' | 'standalone' = 'managed') {
|
|
33
|
+
const database = `kernel_usage_${randomUUID().replaceAll('-', '')}`;
|
|
34
|
+
const dir = mkdtempSync(join(tmpdir(), 'bailinghub-usage-lifecycle-'));
|
|
35
|
+
const mysql = { host: '127.0.0.1', port: 16307, user: 'root', password: '', connectionLimit: 8 };
|
|
36
|
+
const admin = createPool(mysql);
|
|
37
|
+
const providerGate = gate();
|
|
38
|
+
const cleanup: Array<() => void | Promise<unknown>> = [() => rmSync(dir, { recursive: true, force: true }), () => admin.end()];
|
|
39
|
+
async function dispose() {
|
|
40
|
+
providerGate.release();
|
|
41
|
+
let failed = false;
|
|
42
|
+
for (const release of cleanup.reverse()) { try { await release(); } catch { failed = true; } }
|
|
43
|
+
if (failed) throw new Error('Synthetic Kernel fixture cleanup failed');
|
|
44
|
+
}
|
|
45
|
+
try {
|
|
46
|
+
await admin.query(`CREATE DATABASE \`${database}\` CHARACTER SET utf8mb4 COLLATE utf8mb4_bin`);
|
|
47
|
+
cleanup.push(() => admin.query(`DROP DATABASE \`${database}\``));
|
|
48
|
+
await migrateBailingHubCoreSchema({ mysql: { ...mysql, database }, logger: { log() {}, warn() {} } });
|
|
49
|
+
const pool = createPool({ ...mysql, database });
|
|
50
|
+
cleanup.push(() => pool.end());
|
|
51
|
+
const repository = new UsageRepository(() => pool);
|
|
52
|
+
const state = { calls: 0 };
|
|
53
|
+
const provider = createServer(async (req, res) => {
|
|
54
|
+
for await (const _chunk of req) { /* synthetic input only */ }
|
|
55
|
+
state.calls++;
|
|
56
|
+
await providerGate.promise;
|
|
57
|
+
res.writeHead(200, { 'content-type': 'application/json' });
|
|
58
|
+
res.end(JSON.stringify(req.url === '/v1/chat/completions'
|
|
59
|
+
? { id: 'synthetic-original', choices: [{ index: 0, message: { role: 'assistant', content: 'Synthetic output' }, finish_reason: 'stop' }], usage: { prompt_tokens: 1, completion_tokens: 1, total_tokens: 2 } }
|
|
60
|
+
: { id: 'synthetic-original', data: [{ url: 'https://synthetic.invalid/image.png' }], usage: { input_image_count: 0, output_image_count: 1, output_image_type: '1k', output_width: 1024, output_height: 1024 } }));
|
|
61
|
+
});
|
|
62
|
+
cleanup.push(() => { provider.close(); provider.closeAllConnections(); });
|
|
63
|
+
await new Promise<void>(resolve => provider.listen(0, '127.0.0.1', resolve));
|
|
64
|
+
const modelId = 'synthetic/image', endpointId = 'synthetic-provider';
|
|
65
|
+
const price = { source: 'openrouter', modelId, endpointId, currency: 'USD', fetchedAt: Date.now(),
|
|
66
|
+
lines: [{ billable: 'output_image', unit: 'image', costUsd: '0.2', variant: '1k' }] };
|
|
67
|
+
await pool.query('INSERT INTO bz_usage_price_snapshots VALUES(?,?,?)', [
|
|
68
|
+
createHash('sha256').update(`image:${modelId}`).digest('hex'), JSON.stringify({ fetchedAt: Date.now(), items: [{ id: endpointId, pricing: price }] }), Date.now(),
|
|
69
|
+
]);
|
|
70
|
+
const service = await repository.putService({ id: 'synthetic-image', label: 'Synthetic image', expectedRevision: 0, config: {
|
|
71
|
+
credential: 'synthetic', model: 'synthetic-image', providerScope: database, maxInputBytes: 16384, maxOutputTokens: 100, timeoutMs: 10000,
|
|
72
|
+
purpose: 'tool', pricing: { source: 'openrouter', kind: 'image', modelId, endpointId },
|
|
73
|
+
tool: { name: 'generate_image', capability: 'image_generation', description: 'Synthetic image', outputs: ['image'], adapter: 'aliyun-image',
|
|
74
|
+
parameters: [{ name: 'prompt', type: 'string', required: true, description: 'Synthetic input' }] },
|
|
75
|
+
} });
|
|
76
|
+
const identity = getUsageIdentity(repository);
|
|
77
|
+
const chatModelId = 'synthetic/chat';
|
|
78
|
+
const chat = await repository.putService({ id: 'synthetic-chat', label: 'Synthetic chat', expectedRevision: 0, config: {
|
|
79
|
+
...service.config, purpose: 'chat', tool: undefined, pricing: { source: 'openrouter', kind: 'chat', modelId: chatModelId, endpointId },
|
|
80
|
+
} });
|
|
81
|
+
await pool.query('INSERT INTO bz_usage_price_snapshots VALUES(?,?,?)', [createHash('sha256').update(`chat:${chatModelId}`).digest('hex'),
|
|
82
|
+
JSON.stringify({ fetchedAt: Date.now(), items: [{ id: endpointId, pricing: { source: 'openrouter', modelId: chatModelId, endpointId, currency: 'USD', fetchedAt: Date.now(),
|
|
83
|
+
lines: [{ billable: 'prompt', unit: 'token', costUsd: '0.01' }, { billable: 'completion', unit: 'token', costUsd: '0.01' }] } }] }), Date.now()]);
|
|
84
|
+
const issuer = await identity.createIssuer({ id: 'synthetic-product', label: 'Synthetic product', permissions: ['identity:exchange'], service_ids: [service.id, chat.id] });
|
|
85
|
+
const user = await identity.exchange(issuer.credential!, { request_key: randomUUID(), tenant: 'synthetic', subject: 'same-subject', service_id: service.id, model_access: 'token_gateway' });
|
|
86
|
+
const tokens = getBillingRepository(repository);
|
|
87
|
+
await tokens.putPlan({ id: 'synthetic-plan', label: 'Synthetic allowance', expected_revision: 0, config: {
|
|
88
|
+
mode: 'credits', serviceIds: [service.id, chat.id], priceUsd: 100, multiplier: 1, duration: { unit: 'month', count: 1 },
|
|
89
|
+
} });
|
|
90
|
+
await tokens.grant(user.session.accountId, { request_key: 'synthetic-grant', plan_id: 'synthetic-plan', expected_revision: 0 });
|
|
91
|
+
const config: AppConfig = {
|
|
92
|
+
root: process.cwd(), runtimeRoot: dir, env: 'development', server: { host: '127.0.0.1', port: 0, token: '' }, brand: { name: 'Synthetic lifecycle test' },
|
|
93
|
+
displayTz: 'Asia/Shanghai', displayTzLabel: '北京时间', auditRetentionDays: 0, alerts: null, metrics: { enabled: false, token: '', scrapeTimeoutMs: 1000 },
|
|
94
|
+
bootstrapAdmin: null, concurrency: 1, killSwitchFile: join(dir, '.paused'), claudeBin: 'synthetic-unused', defaultProfile: 'readonly', brainDir: join(dir, 'brain'),
|
|
95
|
+
state: { backend: 'mysql', jsonlPath: join(dir, 'jobs.jsonl'), mysql: { ...mysql, database } }, projects: {},
|
|
96
|
+
llmCredentials: { synthetic: { base_url: `http://127.0.0.1:${(provider.address() as AddressInfo).port}/v1`, api_key: 'REPLACE_ME' } },
|
|
97
|
+
executor: { hubUrl: '', token: '', executorId: 'synthetic', targets: [], waitMs: 100, concurrency: 1, labels: [] },
|
|
98
|
+
};
|
|
99
|
+
const warnings: string[] = [];
|
|
100
|
+
const kernel = createBailingHubKernel({ instanceKey: database, config, schedulerMode, bootstrapLocalAdmin: false,
|
|
101
|
+
logger: { log() {}, warn(message) { warnings.push(message); }, error() {} } });
|
|
102
|
+
cleanup.push(() => kernel.close(5000));
|
|
103
|
+
await kernel.initialize();
|
|
104
|
+
const server = createServer((req, res) => { void kernel.handle(req, res).catch(error => res.destroy(error)); });
|
|
105
|
+
cleanup.push(() => { server.close(); server.closeAllConnections(); });
|
|
106
|
+
await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve));
|
|
107
|
+
const base = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
|
|
108
|
+
async function api(path: string, method = 'GET', body?: unknown) {
|
|
109
|
+
const response = await fetch(base + path, { method, headers: { authorization: `Bearer ${user.credential}`, 'content-type': 'application/json' },
|
|
110
|
+
...(body === undefined ? {} : { body: JSON.stringify(body) }) });
|
|
111
|
+
return { status: response.status, body: await response.json() as Record<string, any> };
|
|
112
|
+
}
|
|
113
|
+
const request = (operationId: string) => api('/usage/v1/model/tools/requests', 'POST', { operation_id: operationId, service_id: service.id, arguments: { prompt: 'Synthetic input' } });
|
|
114
|
+
const chatRequest = (operationId: string) => api('/usage/v1/model/requests', 'POST', { operation_id: operationId, service_id: chat.id, messages: [{ role: 'user', content: 'Synthetic input' }] });
|
|
115
|
+
return { kernel, repository, pool, providerGate, state, request, chatRequest, api, warnings, close: dispose };
|
|
116
|
+
} catch (error) { await dispose().catch(() => {}); throw error; }
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
test('Kernel drains detached model completion and late SQL settlement; timeout retains pool for same-instance retry', { skip: !enabled }, async () => {
|
|
120
|
+
const h = await fixture(), operationId = randomUUID(), settlementGate = gate();
|
|
121
|
+
const prototype = BillingRepository.prototype as unknown as { settleRecorded(r: BillingRequest): Promise<BillingRequest> };
|
|
122
|
+
const original = prototype.settleRecorded;
|
|
123
|
+
let entered = false, kernelRepository: UsageRepository | undefined;
|
|
124
|
+
prototype.settleRecorded = async function (this: BillingRepository, r) {
|
|
125
|
+
if (r.operationId === operationId) { entered = true; kernelRepository = this.repository; await settlementGate.promise; }
|
|
126
|
+
return original.call(this, r);
|
|
127
|
+
};
|
|
128
|
+
try {
|
|
129
|
+
const first = await h.request(operationId);
|
|
130
|
+
assert.equal(first.status, 202); assert.equal(first.body.result_state, 'pending');
|
|
131
|
+
await until(() => h.state.calls === 1, 'Synthetic provider did not start');
|
|
132
|
+
await assert.rejects(h.kernel.close(10), /usage background drain timed out/);
|
|
133
|
+
assert.equal((await h.request(operationId)).status, 503);
|
|
134
|
+
h.providerGate.release();
|
|
135
|
+
await until(() => entered, 'Late settlement did not start');
|
|
136
|
+
await assert.rejects(h.kernel.close(0), /usage background drain timed out/);
|
|
137
|
+
assert.ok(kernelRepository); await kernelRepository.getPool().query('SELECT 1');
|
|
138
|
+
const [before] = await h.pool.query<any[]>('SELECT result_state,billing_state FROM bz_usage_billing_requests');
|
|
139
|
+
assert.equal(before[0].result_state, 'complete'); assert.equal(before[0].billing_state, 'pending');
|
|
140
|
+
settlementGate.release();
|
|
141
|
+
await h.kernel.close(2000);
|
|
142
|
+
const [after] = await h.pool.query<any[]>('SELECT result_state,billing_state FROM bz_usage_billing_requests');
|
|
143
|
+
assert.equal(after[0].result_state, 'complete'); assert.equal(after[0].billing_state, 'settled');
|
|
144
|
+
const [ledger] = await h.pool.query<any[]>('SELECT COUNT(*) n FROM bz_usage_billing_ledger');
|
|
145
|
+
assert.equal(Number(ledger[0].n), 1); assert.equal(h.state.calls, 1);
|
|
146
|
+
} finally { settlementGate.release(); prototype.settleRecorded = original; await h.close(); }
|
|
147
|
+
});
|
|
148
|
+
|
|
149
|
+
test('normal model HTTP delivery does not wait for SQL settlement, but Kernel close does', { skip: !enabled }, async () => {
|
|
150
|
+
const h = await fixture(), operationId = randomUUID(), settlementGate = gate();
|
|
151
|
+
const prototype = BillingRepository.prototype as unknown as { settleRecorded(r: BillingRequest): Promise<BillingRequest> };
|
|
152
|
+
const original = prototype.settleRecorded;
|
|
153
|
+
let entered = false;
|
|
154
|
+
prototype.settleRecorded = async function (this: BillingRepository, r) {
|
|
155
|
+
if (r.operationId === operationId) { entered = true; await settlementGate.promise; }
|
|
156
|
+
return original.call(this, r);
|
|
157
|
+
};
|
|
158
|
+
try {
|
|
159
|
+
h.providerGate.release();
|
|
160
|
+
const response = await h.chatRequest(operationId);
|
|
161
|
+
assert.equal(response.status, 200); assert.equal(response.body.result_state, 'complete'); assert.equal(response.body.billing_state, 'pending');
|
|
162
|
+
await until(() => entered, 'Normal model settlement did not start');
|
|
163
|
+
await assert.rejects(h.kernel.close(10), /usage background drain timed out/);
|
|
164
|
+
settlementGate.release(); await h.kernel.close(2000);
|
|
165
|
+
const [rows] = await h.pool.query<any[]>('SELECT billing_state FROM bz_usage_billing_requests');
|
|
166
|
+
assert.equal(rows[0].billing_state, 'settled'); assert.equal(h.state.calls, 1);
|
|
167
|
+
} finally { settlementGate.release(); prototype.settleRecorded = original; await h.close(); }
|
|
168
|
+
});
|
|
169
|
+
|
|
170
|
+
test('failed background settlement retains original result and durable pending without replaying the provider', { skip: !enabled }, async () => {
|
|
171
|
+
const h = await fixture(), operationId = randomUUID();
|
|
172
|
+
const prototype = BillingRepository.prototype as unknown as { settleRecorded(r: BillingRequest): Promise<BillingRequest> };
|
|
173
|
+
const original = prototype.settleRecorded;
|
|
174
|
+
let fail = true;
|
|
175
|
+
prototype.settleRecorded = async function (this: BillingRepository, r) {
|
|
176
|
+
if (r.operationId === operationId && fail) throw new Error('SYNTHETIC_PRIVATE_ERROR_MUST_NOT_BE_LOGGED');
|
|
177
|
+
return original.call(this, r);
|
|
178
|
+
};
|
|
179
|
+
try {
|
|
180
|
+
assert.equal((await h.request(operationId)).status, 202); h.providerGate.release();
|
|
181
|
+
await until(() => h.warnings.some(x => x.includes('usage background settlement failed')), 'Settlement failure was not observed');
|
|
182
|
+
const recovered = await h.request(operationId);
|
|
183
|
+
assert.equal(recovered.status, 200); assert.equal(recovered.body.result_state, 'complete'); assert.equal(recovered.body.billing_state, 'pending');
|
|
184
|
+
assert.equal(h.warnings.join('\n').includes('SYNTHETIC_PRIVATE_ERROR'), false);
|
|
185
|
+
await h.kernel.close(2000); // pending is persisted work for maintenance, not an active provider or retry permit
|
|
186
|
+
const [before] = await h.pool.query<any[]>('SELECT result_hash,billing_state FROM bz_usage_billing_requests');
|
|
187
|
+
assert.ok(before[0].result_hash); assert.equal(before[0].billing_state, 'pending');
|
|
188
|
+
fail = false;
|
|
189
|
+
await getBillingRepository(h.repository).reconcilePendingUsage();
|
|
190
|
+
const [after] = await h.pool.query<any[]>('SELECT billing_state FROM bz_usage_billing_requests');
|
|
191
|
+
const [ledger] = await h.pool.query<any[]>('SELECT COUNT(*) n FROM bz_usage_billing_ledger');
|
|
192
|
+
assert.equal(after[0].billing_state, 'settled'); assert.equal(Number(ledger[0].n), 1); assert.equal(h.state.calls, 1);
|
|
193
|
+
} finally { prototype.settleRecorded = original; await h.close(); }
|
|
194
|
+
});
|
|
195
|
+
|
|
196
|
+
test('standalone shutdown uses the same Kernel background barrier before exit', { skip: !enabled }, async () => {
|
|
197
|
+
const h = await fixture('standalone');
|
|
198
|
+
let exitCode: number | undefined;
|
|
199
|
+
let standalone: ReturnType<typeof h.kernel.createStandaloneServer> | undefined;
|
|
200
|
+
try {
|
|
201
|
+
standalone = h.kernel.createStandaloneServer({ exit(code) { exitCode = code; } });
|
|
202
|
+
await standalone.start();
|
|
203
|
+
assert.equal((await h.request(randomUUID())).status, 202);
|
|
204
|
+
await until(() => h.state.calls === 1, 'Synthetic provider did not start');
|
|
205
|
+
let finished = false;
|
|
206
|
+
const closing = standalone.shutdown('test').then(() => { finished = true; });
|
|
207
|
+
await delay(20);
|
|
208
|
+
assert.equal(finished, false); assert.equal(exitCode, undefined);
|
|
209
|
+
h.providerGate.release(); await closing;
|
|
210
|
+
assert.equal(exitCode, 0);
|
|
211
|
+
const [rows] = await h.pool.query<any[]>('SELECT billing_state FROM bz_usage_billing_requests');
|
|
212
|
+
assert.equal(rows[0].billing_state, 'settled'); assert.equal(h.state.calls, 1);
|
|
213
|
+
} finally { h.providerGate.release(); await standalone?.shutdown('test'); await h.close(); }
|
|
214
|
+
});
|
|
215
|
+
|
|
216
|
+
test('Kernel waits for a real locked completion transaction before pool close', { skip: !enabled }, async () => {
|
|
217
|
+
const h = await fixture(), operationId = randomUUID();
|
|
218
|
+
const lock = await h.pool.getConnection();
|
|
219
|
+
try {
|
|
220
|
+
assert.equal((await h.request(operationId)).status, 202);
|
|
221
|
+
await until(() => h.state.calls === 1, 'Synthetic provider did not start');
|
|
222
|
+
await lock.beginTransaction();
|
|
223
|
+
await lock.query('SELECT id FROM bz_usage_billing_requests WHERE operation_id=? FOR UPDATE', [operationId]);
|
|
224
|
+
h.providerGate.release();
|
|
225
|
+
await assert.rejects(h.kernel.close(20), /usage background drain timed out/);
|
|
226
|
+
const [pending] = await h.pool.query<any[]>('SELECT result_state FROM bz_usage_billing_requests');
|
|
227
|
+
assert.equal(pending[0].result_state, 'pending');
|
|
228
|
+
await lock.rollback();
|
|
229
|
+
await h.kernel.close(2000);
|
|
230
|
+
const [done] = await h.pool.query<any[]>('SELECT result_state,billing_state FROM bz_usage_billing_requests');
|
|
231
|
+
assert.equal(done[0].result_state, 'complete'); assert.equal(done[0].billing_state, 'settled'); assert.equal(h.state.calls, 1);
|
|
232
|
+
} finally { await lock.rollback(); lock.release(); await h.close(); }
|
|
233
|
+
});
|
|
234
|
+
|
|
235
|
+
test('two Kernels with the same original operation ID own separate background work and pools', { skip: !enabled }, async () => {
|
|
236
|
+
const one = await fixture(), operationId = randomUUID();
|
|
237
|
+
let closeTwo: (() => Promise<void>) | undefined;
|
|
238
|
+
try {
|
|
239
|
+
const two = await fixture(); closeTwo = two.close;
|
|
240
|
+
assert.equal((await one.request(operationId)).status, 202); assert.equal((await two.request(operationId)).status, 202);
|
|
241
|
+
await until(() => one.state.calls === 1 && two.state.calls === 1, 'Synthetic providers did not start');
|
|
242
|
+
await assert.rejects(one.kernel.close(10), /usage background drain timed out/);
|
|
243
|
+
one.providerGate.release();
|
|
244
|
+
await one.kernel.close(2000);
|
|
245
|
+
assert.equal(two.kernel.isClosing(), false);
|
|
246
|
+
assert.equal((await two.request(operationId)).status, 202); assert.equal(two.state.calls, 1);
|
|
247
|
+
const [pending] = await two.pool.query<any[]>('SELECT result_state FROM bz_usage_billing_requests');
|
|
248
|
+
assert.equal(pending[0].result_state, 'pending');
|
|
249
|
+
await assert.rejects(two.kernel.close(10), /usage background drain timed out/);
|
|
250
|
+
two.providerGate.release(); await two.kernel.close(2000);
|
|
251
|
+
for (const h of [one, two]) {
|
|
252
|
+
const [rows] = await h.pool.query<any[]>('SELECT COUNT(*) n FROM bz_usage_billing_ledger');
|
|
253
|
+
assert.equal(Number(rows[0].n), 1); assert.equal(h.state.calls, 1);
|
|
254
|
+
}
|
|
255
|
+
} finally { await one.close(); await closeTwo?.(); }
|
|
256
|
+
});
|
|
257
|
+
|
|
258
|
+
test('Kernel tracks response cleanup, reconciliation and reference-price SQL refresh, and stops new maintenance', { skip: !enabled }, async () => {
|
|
259
|
+
const h = await fixture(), cleanupGate = gate(), reconciliationGate = gate(), priceGate = gate();
|
|
260
|
+
const cleanup = BillingRepository.prototype.cleanupExpiredResponses, reconcile = BillingRepository.prototype.reconcilePendingUsage;
|
|
261
|
+
let kernelRepository: UsageRepository | undefined, cleanupEntered = false, reconcileEntered = false, priceCalls = 0;
|
|
262
|
+
BillingRepository.prototype.cleanupExpiredResponses = async function (now) {
|
|
263
|
+
kernelRepository = this.repository; cleanupEntered = true; await cleanupGate.promise; return cleanup.call(this, now);
|
|
264
|
+
};
|
|
265
|
+
BillingRepository.prototype.reconcilePendingUsage = async function () {
|
|
266
|
+
reconcileEntered = true; await reconciliationGate.promise; return reconcile.call(this);
|
|
267
|
+
};
|
|
268
|
+
let refresh: Promise<unknown> | undefined;
|
|
269
|
+
try {
|
|
270
|
+
assert.equal((await h.api('/usage/v1/model/tools')).status, 200);
|
|
271
|
+
await until(() => cleanupEntered && reconcileEntered, 'Gateway maintenance was not registered');
|
|
272
|
+
assert.ok(kernelRepository);
|
|
273
|
+
const pricing = new ReferencePricing(kernelRepository, async () => {
|
|
274
|
+
priceCalls++; await priceGate.promise;
|
|
275
|
+
return new Response(JSON.stringify({ data: { endpoints: [{ tag: 'synthetic', pricing: { prompt: '1', completion: '1' } }] } }), { status: 200 });
|
|
276
|
+
});
|
|
277
|
+
await h.pool.query('INSERT INTO bz_usage_price_snapshots VALUES(?,?,?)', [createHash('sha256').update('chat:synthetic/refresh').digest('hex'),
|
|
278
|
+
JSON.stringify({ fetchedAt: 1, items: [{ id: 'synthetic', pricing: { source: 'openrouter', modelId: 'synthetic/refresh', endpointId: 'synthetic', currency: 'USD', fetchedAt: 1,
|
|
279
|
+
lines: [{ billable: 'prompt', unit: 'token', costUsd: '1' }, { billable: 'completion', unit: 'token', costUsd: '1' }] } }] }), 1]);
|
|
280
|
+
const cached = await pricing.inspect({ source: 'openrouter', kind: 'chat', modelId: 'synthetic/refresh', endpointId: 'synthetic' });
|
|
281
|
+
assert.equal(cached.availability.state, 'ready', 'Stale cached quote returns without waiting for refresh');
|
|
282
|
+
await until(() => priceCalls === 1, 'Reference refresh did not start');
|
|
283
|
+
refresh = pricing.catalog('chat', 'synthetic/refresh', true); // joins the already detached refresh
|
|
284
|
+
await assert.rejects(h.kernel.close(10), /usage background drain timed out/);
|
|
285
|
+
await kernelRepository.getPool().query('SELECT 1');
|
|
286
|
+
await assert.rejects(pricing.catalog('chat', 'synthetic/new-refresh', true), /同步已停止/);
|
|
287
|
+
assert.equal(kernelRepository.backgroundWork.startMaintenance('response-cleanup', async () => { throw new Error('must not run'); }), null);
|
|
288
|
+
cleanupGate.release(); reconciliationGate.release();
|
|
289
|
+
await assert.rejects(h.kernel.close(10), /usage background drain timed out/);
|
|
290
|
+
priceGate.release(); await refresh;
|
|
291
|
+
await h.kernel.close(2000);
|
|
292
|
+
const [saved] = await h.pool.query<any[]>('SELECT snapshot_json FROM bz_usage_price_snapshots WHERE cache_key=?', [createHash('sha256').update('chat:synthetic/refresh').digest('hex')]);
|
|
293
|
+
const snapshot = typeof saved[0].snapshot_json === 'string' ? JSON.parse(saved[0].snapshot_json) : saved[0].snapshot_json;
|
|
294
|
+
assert.equal(saved.length, 1); assert.ok(Number(snapshot.fetchedAt) > 1); assert.equal(priceCalls, 1); assert.equal(h.state.calls, 0);
|
|
295
|
+
} finally {
|
|
296
|
+
cleanupGate.release(); reconciliationGate.release(); priceGate.release(); await refresh?.catch(() => {});
|
|
297
|
+
BillingRepository.prototype.cleanupExpiredResponses = cleanup; BillingRepository.prototype.reconcilePendingUsage = reconcile;
|
|
298
|
+
await h.close();
|
|
299
|
+
}
|
|
300
|
+
});
|
|
301
|
+
|
|
302
|
+
for (const kind of ['response-cleanup', 'usage-reconciliation'] as const) {
|
|
303
|
+
test(`Kernel individually drains gateway ${kind} before closing its pool`, { skip: !enabled }, async () => {
|
|
304
|
+
const h = await fixture(), workGate = gate();
|
|
305
|
+
const cleanup = BillingRepository.prototype.cleanupExpiredResponses, reconcile = BillingRepository.prototype.reconcilePendingUsage;
|
|
306
|
+
let entered = false, kernelRepository: UsageRepository | undefined;
|
|
307
|
+
if (kind === 'response-cleanup') BillingRepository.prototype.cleanupExpiredResponses = async function (now) {
|
|
308
|
+
entered = true; kernelRepository = this.repository; await workGate.promise; return cleanup.call(this, now);
|
|
309
|
+
};
|
|
310
|
+
else BillingRepository.prototype.reconcilePendingUsage = async function () {
|
|
311
|
+
entered = true; kernelRepository = this.repository; await workGate.promise; return reconcile.call(this);
|
|
312
|
+
};
|
|
313
|
+
try {
|
|
314
|
+
assert.equal((await h.api('/usage/v1/model/tools')).status, 200);
|
|
315
|
+
await until(() => entered, 'Gateway background SQL did not start');
|
|
316
|
+
await assert.rejects(h.kernel.close(10), /usage background drain timed out/);
|
|
317
|
+
assert.ok(kernelRepository); await kernelRepository.getPool().query('SELECT 1');
|
|
318
|
+
workGate.release(); await h.kernel.close(2000);
|
|
319
|
+
assert.equal(h.state.calls, 0);
|
|
320
|
+
} finally {
|
|
321
|
+
workGate.release(); BillingRepository.prototype.cleanupExpiredResponses = cleanup; BillingRepository.prototype.reconcilePendingUsage = reconcile;
|
|
322
|
+
await h.close();
|
|
323
|
+
}
|
|
324
|
+
});
|
|
325
|
+
}
|
package/src/app/kernel.ts
CHANGED
|
@@ -180,6 +180,9 @@ export function createBailingHubKernel(input: CreateBailingHubKernelInputV1): Ba
|
|
|
180
180
|
queue: new Queue(cfg.concurrency, input.executionQueue),
|
|
181
181
|
serialScope: instanceKey,
|
|
182
182
|
});
|
|
183
|
+
composition.cfgStore?.usage?.backgroundWork.setFailureReporter(kind => {
|
|
184
|
+
logger.warn?.(`[Kernel ${instanceKey}] usage background ${kind} failed; original durable evidence is retained`);
|
|
185
|
+
});
|
|
183
186
|
const demoDataset = composition.cfgStore ? new DemoDatasetService(composition.cfgStore, cfg.demoDataset) : null;
|
|
184
187
|
const runtimeHelpers = createRuntimeContextHelpers({
|
|
185
188
|
cfg,
|
|
@@ -482,6 +485,13 @@ export function createBailingHubKernel(input: CreateBailingHubKernelInputV1): Ba
|
|
|
482
485
|
composition.queue.closeAdmission();
|
|
483
486
|
const queueDrained = await composition.queue.drain(remainingDrainMs());
|
|
484
487
|
if (!queueDrained) throw new Error(`Kernel ${instanceKey} execution queue drain timed out`);
|
|
488
|
+
const usageWork = composition.cfgStore?.usage?.backgroundWork;
|
|
489
|
+
if (usageWork) {
|
|
490
|
+
// Foreground handlers have finished registering their continuations.
|
|
491
|
+
// Stop new maintenance, but let already accepted completions settle.
|
|
492
|
+
usageWork.beginDrain();
|
|
493
|
+
if (!await usageWork.drain(remainingDrainMs())) throw new Error(`Kernel ${instanceKey} usage background drain timed out`);
|
|
494
|
+
}
|
|
485
495
|
targetRegistry.bindStore(null);
|
|
486
496
|
wecomRuntimeState.dispose();
|
|
487
497
|
wecomAccessTokenCache.dispose();
|
package/src/app/oss-edition.ts
CHANGED
|
@@ -29,6 +29,8 @@ import { AgentArtifactRepository } from './config-agent-artifact-repository';
|
|
|
29
29
|
import { AgentClientRuntimeRepository } from './config-agent-client-runtime-repository';
|
|
30
30
|
import { AgentConversationAuditRepository } from './config-agent-conversation-audit-repository';
|
|
31
31
|
import { AgentTaskControlRepository } from './config-agent-task-control-repository';
|
|
32
|
+
import { UsageRepository } from '../../modules/usage/repository';
|
|
33
|
+
import { getUsageIdentity } from '../../modules/usage/identity';
|
|
32
34
|
import { MysqlPoolOwner, type MysqlPoolResource } from '../mysql/pool-owner';
|
|
33
35
|
|
|
34
36
|
export type RouteRepositoryContract = Omit<Pick<RouteRepository, keyof RouteRepository>, 'compareAndSetAgentSetup'>
|
|
@@ -103,6 +105,8 @@ export interface ConfigStoreContract {
|
|
|
103
105
|
readonly agentConversationAudit?: AgentConversationAuditRepositoryContract;
|
|
104
106
|
/** Optional for extension hosts. Managed Sessions must never fall back without this repository. */
|
|
105
107
|
readonly agentTaskControl?: Pick<AgentTaskControlRepository, keyof AgentTaskControlRepository>;
|
|
108
|
+
/** Optional usage module. Dedicated usage requests fail closed when it is absent. */
|
|
109
|
+
readonly usage?: UsageRepository;
|
|
106
110
|
init(): Promise<void>;
|
|
107
111
|
close?(): Promise<void>;
|
|
108
112
|
readonly db: Pool;
|
|
@@ -140,9 +144,11 @@ export class ConfigStore implements ConfigStoreContract {
|
|
|
140
144
|
readonly agentClientRuntime = new AgentClientRuntimeRepository(() => this.pool);
|
|
141
145
|
readonly agentConversationAudit = new AgentConversationAuditRepository(() => this.pool);
|
|
142
146
|
readonly agentTaskControl = new AgentTaskControlRepository(() => this.pool);
|
|
147
|
+
readonly usage = new UsageRepository(() => this.pool);
|
|
143
148
|
|
|
144
149
|
constructor(cfg: AppConfig['state']['mysql'], poolOwner?: MysqlPoolResource) {
|
|
145
150
|
this.poolOwner = poolOwner ?? new MysqlPoolOwner(cfg);
|
|
151
|
+
getUsageIdentity(this.usage);
|
|
146
152
|
}
|
|
147
153
|
|
|
148
154
|
async init(): Promise<void> {
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
import assert from 'node:assert/strict';
|
|
2
|
+
import { randomUUID } from 'node:crypto';
|
|
3
|
+
import test from 'node:test';
|
|
4
|
+
import { createUsageTestHarness } from './test-harness';
|
|
5
|
+
import { usageHash } from './repository';
|
|
6
|
+
import type { BillingPlanConfig, BillingRequest, PriceSnapshot } from './billing-contracts';
|
|
7
|
+
|
|
8
|
+
const enabled = process.env.BAILING_USAGE_TEST_MYSQL === '1';
|
|
9
|
+
const day = 86_400_000, admin = 'synthetic-admin';
|
|
10
|
+
const price: PriceSnapshot = { source: 'openrouter', currency: 'USD', modelId: 'synthetic', endpointId: 'synthetic', fetchedAt: 1,
|
|
11
|
+
lines: [{ billable: 'prompt', unit: 'token', costUsd: '1' }, { billable: 'completion', unit: 'token', costUsd: '1' }] };
|
|
12
|
+
async function fixture(mode: 'periodic' | 'credits' = 'periodic', sourceOwner = 'hub') {
|
|
13
|
+
const h = await createUsageTestHarness();
|
|
14
|
+
let now = Date.now(); const startsAt = now;
|
|
15
|
+
Object.defineProperty(h.tokens, 'now', { value: async () => now });
|
|
16
|
+
const user = await h.seedUser({ grant: false });
|
|
17
|
+
const config: BillingPlanConfig = { mode, priceUsd: 100, multiplier: 1, serviceIds: [h.service.id],
|
|
18
|
+
...(mode === 'periodic' ? { periodAllowanceUsd: 20, periodUnit: 'week' as const } : {}), duration: { unit: 'day', count: 30 } };
|
|
19
|
+
const plan = await h.tokens.putPlan({ id: 'synthetic-reset', label: 'Synthetic reset', expected_revision: 0, config });
|
|
20
|
+
const grant = await h.tokens.grant(user.accountId, { request_key: randomUUID(), plan_id: plan.id, expected_revision: 0, starts_at: now }, sourceOwner);
|
|
21
|
+
const path = `/admin/api/usage/billing/accounts/${user.accountId}/reset`;
|
|
22
|
+
const reset = (revision: number, key = randomUUID()) => h.request(path, admin, 'POST', { request_key: key, expected_revision: revision });
|
|
23
|
+
const admit = async () => { const operationId = randomUUID(); return h.tokens.admit({ actor: user.actor, operationId, serviceId: h.service.id,
|
|
24
|
+
conversationId: null, turnId: null, requestHash: usageHash(operationId), expectedServiceRevision: h.service.revision,
|
|
25
|
+
serviceConfig: h.service.config, model: h.service.config.model, priceSnapshot: price }); };
|
|
26
|
+
const dispatch = async () => h.tokens.commitDispatch((await admit()).id, user.actor);
|
|
27
|
+
const finish = (r: BillingRequest, cost: number) => h.tokens.complete(r.id, r.fence!, { response: { output: 'synthetic' }, usage: { inputTokens: cost, outputTokens: 0 } });
|
|
28
|
+
return { ...h, user, config, plan, grant, path, reset, dispatch, finish, startsAt, setNow: (value: number) => { now = value; } };
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
test('manual reset restores the original weekly allowance, moves the anchor and preserves expiry and late settlement', { skip: !enabled }, async () => {
|
|
32
|
+
const h = await fixture();
|
|
33
|
+
try {
|
|
34
|
+
const late = await h.dispatch();
|
|
35
|
+
await h.finish(await h.dispatch(), 20);
|
|
36
|
+
assert.equal((await h.tokens.summary(h.user.accountId)).presentation.remaining, 0);
|
|
37
|
+
await h.tokens.putPlan({ id: h.plan.id, label: h.plan.label, expected_revision: 1, config: { ...h.config, priceUsd: 999, periodAllowanceUsd: 200 } });
|
|
38
|
+
h.setNow(h.startsAt + 2 * day);
|
|
39
|
+
const reset = await h.reset(1); assert.equal(reset.status, 200);
|
|
40
|
+
assert.notEqual(reset.body.id, h.grant.id);
|
|
41
|
+
assert.equal(reset.body.reset.previousGrantId, h.grant.id);
|
|
42
|
+
assert.equal(reset.body.reset.actor, 'admin-token');
|
|
43
|
+
const current = await h.tokens.summary(h.user.accountId);
|
|
44
|
+
assert.equal(current.availableUsd, 20); assert.equal(current.presentation.remaining, 100);
|
|
45
|
+
assert.equal(current.resetAt, h.startsAt + 9 * day); assert.equal(current.expiresAt, h.grant.expiresAt);
|
|
46
|
+
assert.equal(current.grant!.config.priceUsd, 100);
|
|
47
|
+
const done = await h.finish(late, 7);
|
|
48
|
+
assert.equal(done.grantId, h.grant.id);
|
|
49
|
+
assert.deepEqual(await h.finish(late, 7), done);
|
|
50
|
+
assert.equal((await h.tokens.summary(h.user.accountId)).availableUsd, 20);
|
|
51
|
+
const [pools] = await h.pool.query<any[]>('SELECT consumed_usd FROM bz_usage_billing_periods WHERE grant_id=?', [h.grant.id]);
|
|
52
|
+
assert.equal(Number(pools[0].consumed_usd), 27);
|
|
53
|
+
assert.equal((await h.tokens.findRequest(h.user.actor, late.operationId))!.resultState, 'complete');
|
|
54
|
+
h.setNow(h.startsAt + 28 * day);
|
|
55
|
+
assert.equal((await h.reset(2)).status, 200);
|
|
56
|
+
const final = await h.tokens.summary(h.user.accountId);
|
|
57
|
+
assert.equal(final.availableUsd, 20); assert.equal(final.resetAt, null); assert.equal(final.expiresAt, h.grant.expiresAt);
|
|
58
|
+
h.setNow(h.grant.expiresAt!);
|
|
59
|
+
assert.equal((await h.reset(3)).body.error, 'SERVICE_NOT_ENTITLED');
|
|
60
|
+
} finally { await h.close(); }
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
test('reset retries and concurrent clicks issue one allowance; replay after spending does not refill it', { skip: !enabled }, async () => {
|
|
64
|
+
const h = await fixture();
|
|
65
|
+
try {
|
|
66
|
+
const key = randomUUID();
|
|
67
|
+
const [first, duplicate] = await Promise.all([h.reset(1, key), h.reset(1, key)]);
|
|
68
|
+
assert.equal(first.status, 200); assert.deepEqual(duplicate.body, first.body);
|
|
69
|
+
await h.finish(await h.dispatch(), 5);
|
|
70
|
+
assert.deepEqual((await h.reset(1, key)).body, first.body);
|
|
71
|
+
assert.equal((await h.tokens.summary(h.user.accountId)).availableUsd, 15);
|
|
72
|
+
assert.equal((await h.reset(2, key)).body.error, 'USAGE_IDEMPOTENCY_CONFLICT');
|
|
73
|
+
assert.equal((await h.reset(1)).body.error, 'USAGE_REVISION_CONFLICT');
|
|
74
|
+
const results = await Promise.all([h.reset(2), h.reset(2)]);
|
|
75
|
+
assert.equal(results.filter(r => r.status === 200).length, 1);
|
|
76
|
+
assert.equal(results.filter(r => r.body.error === 'USAGE_REVISION_CONFLICT').length, 1);
|
|
77
|
+
assert.equal((await h.tokens.summary(h.user.accountId)).availableUsd, 20);
|
|
78
|
+
const [rows] = await h.pool.query<any[]>('SELECT COUNT(*) AS n FROM bz_usage_billing_grants WHERE account_id=?', [h.user.accountId]);
|
|
79
|
+
assert.equal(Number(rows[0].n), 3);
|
|
80
|
+
const [receipts] = await h.pool.query<any[]>('SELECT result_json FROM bz_usage_changes WHERE JSON_EXTRACT(result_json,\'$.reset\') IS NOT NULL');
|
|
81
|
+
assert.equal(receipts.length, 2);
|
|
82
|
+
} finally { await h.close(); }
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
test('credits reset restores the pack without periodic renewal or extending its life', { skip: !enabled }, async () => {
|
|
86
|
+
const h = await fixture('credits');
|
|
87
|
+
try {
|
|
88
|
+
await h.finish(await h.dispatch(), 40);
|
|
89
|
+
assert.equal((await h.tokens.summary(h.user.accountId)).availableUsd, 60);
|
|
90
|
+
h.setNow(h.startsAt + day);
|
|
91
|
+
assert.equal((await h.reset(1)).status, 200);
|
|
92
|
+
const summary = await h.tokens.summary(h.user.accountId);
|
|
93
|
+
assert.equal(summary.availableUsd, 100); assert.equal(summary.presentation.kind, 'credits');
|
|
94
|
+
assert.equal(summary.resetAt, null); assert.equal(summary.expiresAt, h.grant.expiresAt);
|
|
95
|
+
} finally { await h.close(); }
|
|
96
|
+
});
|
|
97
|
+
|
|
98
|
+
test('reset enforces adjustment permission, input shape, active account and active effective grant', { skip: !enabled }, async () => {
|
|
99
|
+
const h = await fixture();
|
|
100
|
+
try {
|
|
101
|
+
const body = { request_key: randomUUID(), expected_revision: 1 };
|
|
102
|
+
assert.equal((await h.request(h.path, 'synthetic-auditor', 'POST', body)).status, 403);
|
|
103
|
+
assert.equal((await h.request(h.path, admin, 'POST', { ...body, priceUsd: 999 })).status, 400);
|
|
104
|
+
assert.equal((await h.request(h.path, admin, 'POST', { expected_revision: 1 })).status, 400);
|
|
105
|
+
h.setNow(h.startsAt - 1);
|
|
106
|
+
assert.equal((await h.reset(1)).body.error, 'SERVICE_NOT_ENTITLED');
|
|
107
|
+
h.setNow(h.startsAt);
|
|
108
|
+
await h.tokens.control(h.user.accountId, { request_key: randomUUID(), expected_revision: 1, state: 'suspended' });
|
|
109
|
+
assert.equal((await h.reset(2)).body.error, 'SERVICE_NOT_ENTITLED');
|
|
110
|
+
await h.tokens.control(h.user.accountId, { request_key: randomUUID(), expected_revision: 2, state: 'active' });
|
|
111
|
+
await h.repository.setAccountState({ accountId: h.user.accountId, expectedRevision: 1, requestId: randomUUID(), actor: admin, state: 'suspended' });
|
|
112
|
+
assert.equal((await h.reset(3)).body.error, 'USAGE_ACCOUNT_SUSPENDED');
|
|
113
|
+
const [rows] = await h.pool.query<any[]>('SELECT COUNT(*) AS n FROM bz_usage_billing_grants WHERE account_id=?', [h.user.accountId]);
|
|
114
|
+
assert.equal(Number(rows[0].n), 1);
|
|
115
|
+
} finally { await h.close(); }
|
|
116
|
+
});
|
|
117
|
+
|
|
118
|
+
test('external entitlement owners retain control over their allowance', { skip: !enabled }, async () => {
|
|
119
|
+
const h = await fixture('periodic', 'issuer:synthetic-product');
|
|
120
|
+
try { assert.equal((await h.reset(1)).body.error, 'USAGE_SOURCE_CONFLICT'); }
|
|
121
|
+
finally { await h.close(); }
|
|
122
|
+
});
|