refactor(billing): 计费语义下沉到 Lua(内核只解 YAML/传数据)+ 采纳 PR #2 语义

按 issue #1 的修复方向(维护者评论):内核不再持有任何计费语义,billing 逻辑
全部在 `plugins/billing.lua`;内核只负责解 config.yaml、校验 schema、把
profile + 源 base_url 作为**数据**交给插件,再把插件算出的价目通过 `prices`
侧车注入。计费账目仍持久化在插件状态文件(`plugin_dir/.billing.state.json`)。

## 变更
- **删除** `internal/billing`(compile.go 359 行 + 其 Go 测试);
- 新增 `core.compileBillingPrices`:把 profile/sources JSON 化后调用插件导出
  `compile_prices`,返回价目表 + 未匹配规则清单(供错误日志点名 URL);
- `applyBillingDSL` / 规则编辑器改为走同一个插件编译入口(编辑器 lenient,
  半成品规则可保存、可报告);
- `billing.lua` 新增 `compile_prices`:URL 归一匹配、首条命中优先、
  free/subscription/unpriced/token、USD/M→per-token、peak 窗口、
  long_context 边际价、reasoning 可选价、default 策略、未匹配清单。
  错误通过载荷 `error` 字段回传(插件导出第二返回值通道不可靠)。

## 与 PR #2(valuelesser)合并后的语义
- **token 规则不产生任何源条目**:未列价的模型落到 unpriced 统计(可见),
  不再"静默计 $0"。比 issue 正文里的 `{per_request:0}` 标记更收口;
- `default: free` 由**编译期**给未匹配源写 `{per_request:0}` 标记;
  `unpriced`/缺省不写。删除无人读取的 `default_mode` 死键;
- 保留 `unmatched_rules` 清单(只用于降级应用时点名过期 URL)。

## 判据(原 Go 单测平移到 Lua + PR #2 的用例)
- `internal/lua/billing_compile_test.go`:通配符不标记源、token 规则无源条目、
  任意源条目不得携带 token 价(根因直防)、free/subscription 保留有意零价、
  reasoning 缺席、long_context 三种形态、peak 形状、URL 归一+首条优先、
  lenient 未匹配清单、硬错误 5 例、default 两态;
- `internal/lua/billing_test.go`:编译输出驱动真实 priceFor 的 A/B 用例
  (旧形状 cost=0 / 新形状 0.75 且 unpriced=0)、default 编译期语义 e2e;
- `internal/gateway`:token 规则断言"无源条目"、模型价 per-token 量级;
- `internal/core`:过期规则 URL 降级应用(有效规则仍生效)。
This commit is contained in:
root
2026-10-20 18:33:26 +08:00
parent 442fa5e3f6
commit b4c5f0f0fc
10 changed files with 819 additions and 765 deletions

View File

@ -72,6 +72,228 @@ local DEFAULT_PRICES = {
}
plugin.prices = DEFAULT_PRICES
-- ===== 规则 → 价格表编译(Lua 侧,内核只给数据) ======================
--
-- 为什么编译在插件里(GitCode issue #1 的建议方向):
-- 内核只负责把 config.yaml 解成结构体(YAML 解析 + schema 校验),并把
-- profile 与源的 base_url 作为**数据**通过 plugin.compile_prices 传进插件;
-- "规则如何变成价目表"(free/subscription/unpriced/token、URL 归一匹配、
-- 首条命中优先、token 价的 per-million → per-token、peak 窗口、
-- long_context 边际价、reasoning 可选价、未匹配规则/源)全部在这里。
--
-- 这样内核不需要认识任何计费语义,也不会再出现"两处各写一半、组合起来
-- 静默归零"——issue #1 的真因正是 compile.go 与 priceFor() 各有一套覆盖语义。
--
-- 返回形态(供内核 SetState 注入 plugin.prices):
-- { prices = <价目表>, unmatched_rules = {...}, unmatched_sources = {...} }
-- 硬错误用 `return nil, "原因"`,内核据此拒绝保存/记录 ERROR。
local function normalizeURL(u)
u = tostring(u or ""):gsub("^%s+", ""):gsub("%s+$", "")
u = u:gsub("/+$", "")
return u:lower()
end
local function matchSources(pattern, sources)
local out = {}
if pattern == "*" then
for _, s in ipairs(sources or {}) do out[#out + 1] = s.name end
return out
end
local want = normalizeURL(pattern)
for _, s in ipairs(sources or {}) do
if normalizeURL(s.base_url) == want then out[#out + 1] = s.name end
end
return out
end
-- USD per million → USD per token. 与内核校验用的是同一口径(/1e6),
-- 数值范围与 Go 的 ParseFloatUSDPerM 一致(不允许负数/非数字)。
local function usdPerM(v)
local s = tostring(v == nil and "" or v)
s = s:gsub("^%s+", ""):gsub("%s+$", "")
local n = tonumber(s)
if n == nil then return nil, "not a number: \"" .. tostring(v) .. "\"" end
if n < 0 then return nil, "negative price: \"" .. tostring(v) .. "\"" end
return n / 1e6, nil
end
-- peak 窗口的**唯一**合法形状:{ multiplier, windows = { { days, hours } } }。
-- 早期部署过的 {start,end,weekdays} 没有任何读取方(peak 静默按非高峰计价)。
local function compilePeak(pk)
local win = {}
if type(pk.weekdays) == "table" and #pk.weekdays > 0 then
local days = {}
for i, d in ipairs(pk.weekdays) do days[i] = d end
win.days = days
end
if type(pk.hours) == "table" and #pk.hours > 0 then
local hours = {}
for i, h in ipairs(pk.hours) do hours[i] = { h[1], h[2] } end
win.hours = hours
end
local out = { multiplier = tonumber(pk.multiplier) or 1 }
if next(win) ~= nil then out.windows = { win } end
return out
end
-- long_context 的边际价:绝对值(USD/M 字符串)优先,其次倍数 × 基础价。
-- 两者都缺 ⇒ 报错(一个"没有价格的阶梯"是静默 no-op,写它的人一定有意图)。
local function longContextRate(lc, basePerToken)
local prompt = tostring(lc.prompt == nil and "" or lc.prompt)
prompt = prompt:gsub("^%s+", ""):gsub("%s+$", "")
local mult = tonumber(lc.multiplier) or 0
if prompt ~= "" then
local v, err = usdPerM(prompt)
if not v then return nil, err end
return v, nil
end
if mult > 0 then return basePerToken * mult, nil end
return nil, "needs either prompt or multiplier"
end
local function applyRule(prices, rule, srcName)
local mode = rule.mode
if mode == "free" or mode == "subscription" then
-- 显式零价:这里 0 本身就是语义(不是"未定价")。
prices.sources[srcName] = { prompt = 0, completion = 0, per_request = 0 }
if mode == "subscription" then
if prices.subscriptions == nil then prices.subscriptions = {} end
local cur = tostring(rule.currency == nil and "" or rule.currency)
if cur == "" then cur = "USD" end
prices.subscriptions[srcName] = {
monthly = tonumber(rule.subscription) or 0, currency = cur,
}
end
return true
end
if mode == "unpriced" then
-- 刻意不写源条目:让 unpriced_reqs/unpriced_models 抓住它。
return true
end
if mode == "token" then
if type(rule.models) ~= "table" or next(rule.models) == nil then
return nil, string.format("rule for url %q: mode token requires at least one model",
tostring(rule.url))
end
for modelID, t in pairs(rule.models) do
local prompt, perr = usdPerM(t.prompt)
if not prompt then return nil, string.format("model %q prompt: %s", tostring(modelID), perr) end
local completion, cerr = usdPerM(t.completion)
if not completion then return nil, string.format("model %q completion: %s", tostring(modelID), cerr) end
local entry = { prompt = prompt, completion = completion }
if t.cache_discount ~= nil then entry.cache_discount = tonumber(t.cache_discount) end
-- reasoning 可选,且**缺席**而非 0:写 0 等于"思考免费",会静默少报
-- 每一个把 reasoning 按输出计价的 provider。
local reasoning = tostring(t.reasoning == nil and "" or t.reasoning)
reasoning = reasoning:gsub("^%s+", ""):gsub("%s+$", "")
if reasoning ~= "" then
local rp, rerr = usdPerM(reasoning)
if not rp then return nil, string.format("model %q reasoning: %s", tostring(modelID), rerr) end
entry.reasoning_price = rp
end
if type(t.long_context) == "table" then
local above = tonumber(t.long_context.above) or 0
if above <= 0 then
return nil, string.format("model %q long_context: above must be > 0", tostring(modelID))
end
local rate, lerr = longContextRate(t.long_context, prompt)
if not rate then
return nil, string.format("model %q long_context: %s", tostring(modelID), lerr)
end
entry.long_context = { above = above, prompt = rate }
end
if type(rule.peak) == "table" then entry.peak = compilePeak(rule.peak) end
prices.models[modelID] = entry
end
-- ★ token 规则**不写任何源条目**(模型维度只发布模型价)。
--
-- 此前写 `{per_request:0}` 或 `{prompt:0,completion:0}` 都是为了"标记该源
-- 已定价",但 priceFor() 让源层**无条件覆盖**模型层的 prompt/completion:
-- * `{prompt:0,completion:0}` ⇒ 规则刚发布的模型价被清零(issue #1 本体);
-- * 只写 `{per_request:0}` ⇒ 模型价没被清零,但同源上**未列入 rule.Models**
-- 的模型仍被评为"已定价"、静默计 0,unpriced 计数依旧不涨。
-- 第二条仍然是"静默少报",只是窄一点。所以统一收口:token 规则不产生源条目,
-- 未列价的模型落到 unpriced 统计里(可见)。真正"边际成本为零"用
-- mode=free / mode=subscription —— 它们写的是有意为之的零价标记。
return true
end
return nil, string.format("unknown mode %q", tostring(mode))
end
local function compilePrices(profile, sources, lenient)
if type(profile) ~= "table" then return nil, "no billing profile" end
sources = sources or {}
local prices = {
currency = "USD",
default = { prompt = 0, completion = 0, per_request = 0 },
sources = {}, models = {}, keys = {},
}
local rules = type(profile.rules) == "table" and profile.rules or {}
-- currency 是 profile 级声明:第一条带 currency 的规则生效。
for i = 1, #rules do
local c = rules[i].currency
if type(c) == "string" and c ~= "" then prices.currency = c break end
end
local matched = {}
local unmatched_rules = {}
for i = 1, #rules do
local rule = rules[i]
local url = tostring(rule.url == nil and "" or rule.url)
local targets = matchSources(url, sources)
if #targets == 0 and url ~= "*" then
if lenient then
unmatched_rules[#unmatched_rules + 1] = url
else
return nil, string.format("rule url %q matches no configured source base_url", url)
end
else
for _, srcName in ipairs(targets) do
-- 首条命中优先:两条规则匹配同一个源是歧义,后面的不能悄悄覆盖前面的。
if not matched[srcName] then
matched[srcName] = true
local ok, err = applyRule(prices, rule, srcName)
if not ok then return nil, err end
end
end
end
end
-- profile 的 default 策略:只影响**没有规则命中**的源。
--
-- `free` = 运营声明"其余源一律免费" ⇒ 必须被识别为已定价,否则它们会一直计入
-- unpriced,告警变成噪音;标记用 `{per_request:0}`(只标记、不碰 token 价,
-- 否则任何通配符价目表都会被它清零,等于同一个 bug 换个入口复现)。
-- `unpriced`(或缺省)= 不写条目,让插件的 unpriced 计数看得见它们。
--
-- 这个策略以前只被校验、却被写进一个没人读的 `default_mode` 键 ⇒
-- `default: free` 与 `default: unpriced` 运行时完全等价。
if profile.default == "free" then
for _, src in ipairs(sources) do
if not matched[src.name] and prices.sources[src.name] == nil then
prices.sources[src.name] = { per_request = 0 }
end
end
end
local unmatched_sources = {}
for _, src in ipairs(sources) do
if not matched[src.name] then unmatched_sources[#unmatched_sources + 1] = src.name end
end
return { prices = prices, unmatched_rules = unmatched_rules, unmatched_sources = unmatched_sources }
end
-- 内核入口:profile 与源的 base_url 都是**数据**,插件不认识 config.yaml。
plugin.compile_prices = function(args)
args = args or {}
local out, err = compilePrices(args.profile, args.sources, args.lenient and true or false)
-- 错误用**表里的 error 字段**回传,而不是第二个返回值:内核桥的
-- `Call` 只把第一个返回值解码成数据(第二个返回值的错误通道在插件导出上
-- 并不可靠),用 {error=...} 是本仓库其它插件导出一致的约定。
if not out then return { error = tostring(err) } end
return out
end
plugin.exports = plugin.exports or {}
plugin.exports[#plugin.exports + 1] = "compile_prices"
-- Default prompt-cache discount. 0.1 = a cache read costs a tenth of a fresh
-- token, which is what DeepSeek/Qwen/Kimi and most others charge. It can be
-- overridden per price entry (prices.models.<m>.cache_discount) or globally by
@ -241,17 +463,6 @@ local function priceFor(payload)
if kp.peak ~= nil then out.peak = kp.peak end
end
-- profile-level default for sources no rule matched.
--
-- compile.go has always written `default_mode` ("free" | "unpriced") into the
-- prices table, but NOTHING read it — so `default: free` and
-- `default: unpriced` behaved identically at runtime (both fell through to
-- prices.default's zeros and counted as unpriced debt). That is a second
-- silent under-report (GitCode issue #1 follow-up). "free" is a DELIBERATE
-- zero, so it must be marked priced; anything else stays countable debt.
if not out.priced and p.default_mode == "free" then
out.priced = true
end
return out
end