feat(stove-api): expose estimate and operator controls
This commit is contained in:
+17
-2
@@ -70,11 +70,17 @@ def collect(hours: int = 24) -> dict:
|
||||
"broken_users": sorted({r[0] for r in broken}),
|
||||
}
|
||||
out["topups"] = _topups(since)
|
||||
try:
|
||||
import stove_api_digest
|
||||
out["stove_api"] = stove_api_digest.collect(hours)
|
||||
except sqlite3.Error:
|
||||
out["stove_api"] = None
|
||||
t = out["topups"]
|
||||
# Cron sends with --quiet-ok and decides by this flag: a day of payments is not quiet.
|
||||
out["quiet"] = (out["broken_runs"] == 0 and out["masked_errors"] == 0
|
||||
and out["feedback"] == 0
|
||||
and not (t["count"] or t["refunds"] or t["unpaid"]))
|
||||
and not (t["count"] or t["refunds"] or t["unpaid"])
|
||||
and not (out["stove_api"] and out["stove_api"]["total"]))
|
||||
return out
|
||||
|
||||
|
||||
@@ -105,7 +111,8 @@ def render(d: dict) -> str:
|
||||
head = f"📊 smeta-web за {d['hours']} ч"
|
||||
t = d.get("topups") or {"count": 0, "kop": 0, "refunds": 0, "unpaid": 0}
|
||||
if (d["quiet"] and not d["active_users"] and not d["registrations"]
|
||||
and not (t["count"] or t["refunds"] or t["unpaid"])):
|
||||
and not (t["count"] or t["refunds"] or t["unpaid"])
|
||||
and not (d.get("stove_api") or {}).get("total")):
|
||||
return f"{head}: тихо — живых обращений не было."
|
||||
lines = [
|
||||
head + ":",
|
||||
@@ -119,6 +126,9 @@ def render(d: dict) -> str:
|
||||
f"• Пополнений за сутки: {t['count']} на {_rub(t['kop'])}; "
|
||||
f"возвратов {t['refunds']}; неоплаченных {t['unpaid']}",
|
||||
]
|
||||
if d.get("stove_api"):
|
||||
import stove_api_digest
|
||||
lines.append(stove_api_digest.render(d["stove_api"]))
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
@@ -132,6 +142,11 @@ if __name__ == "__main__":
|
||||
help="не слать, если день прошёл тихо")
|
||||
args = ap.parse_args()
|
||||
|
||||
try:
|
||||
import stove_cleanup
|
||||
stove_cleanup.cleanup()
|
||||
except sqlite3.Error:
|
||||
pass
|
||||
data = collect(args.hours)
|
||||
text = render(data)
|
||||
print(text)
|
||||
|
||||
@@ -1965,3 +1965,15 @@ event loop без `to_thread`.
|
||||
трогают.
|
||||
7. **Независимый сигнал.** Сам сторож: если новая проверка начнёт будить попусту, это видно
|
||||
в первые же сутки.
|
||||
|
||||
## 2026-11-26 — завершение API печей для release/dev
|
||||
|
||||
1. Действие: подключить цены, сопоставление, HTTP, админку и наблюдение; затем влить в release и проверить dev 8106.
|
||||
2. Риск: внешний API, чтение нормативов и расход ИИ — высокий для dev, без записи в нормативные базы.
|
||||
3. Прогон №1: ключ, зона, нормативы и валидный ответ; №100: кеш и лимиты; №1000: ограничение параллелизма, уборка и размер истории.
|
||||
4. Побочное действие видят владелец ключа, оператор и dev. Прод не затрагивается.
|
||||
5. Проверка: контрактные тесты, один общий predeploy gate, smoke на dev с тестовым ключом.
|
||||
6. Обратимость: откат release до предыдущего SHA, перезапуск dev; таблицы добавлены без удаления данных.
|
||||
7. Отвергнуто: прямой push в main — нет разрешения на прод.
|
||||
8. Отвергнуто: подмена отсутствующей цены нулём — искажает смету.
|
||||
9. Итог: допускаем только объяснённую неполноту и проверяемый источник каждой суммы.
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
# Завершение API для сайта печей — 26.11.2026
|
||||
|
||||
Цель: работающий API в release на dev 8106. Main и прод ждут отдельной команды владельца.
|
||||
|
||||
Критерии приёмки:
|
||||
- POST /api/v1/stove-estimate: ключ до чтения тела, лимиты, единый формат отказов, успешный ответ по действующим нормативным данным.
|
||||
- Расценки, цены ресурсов, зоны, происхождение и отсутствующие данные обрабатываются без выдуманных сумм.
|
||||
- Сопоставление строк, кеш, история, управление ключами и сводка подключены.
|
||||
- Публичный протокол и OpenAPI доступны без раскрытия остальных маршрутов.
|
||||
- Адресные проверки маршрутов и расчёта, затем один полный прогон и реальный smoke dev 8106.
|
||||
- Ветка release включает изменение и совпадает с запущенным dev; main и прод не меняются.
|
||||
|
||||
Порядок: контракты/ценовые адаптеры → сопоставление → транспорт и админка → наблюдение → тесты → release/dev. Риск: неполные нормативы; ответ оставляет сумму пустой и называет причину. Риск: расходы ИИ; лимит ключа и краткий пакет кандидатов.
|
||||
|
||||
Проверка на тестовых копиях нормативов: отопительная печь 210+76 кирпичей, масса 1320 кг, Москва — HTTP 200, ОТ+ЭМ 4001–4002 ₽, итог частичный. База ГЭСН хранит агрегат 0,53 тыс. шт/м³; раздельной нормы шамотного кирпича нет. В ФГИС ЦС под общими названиями кирпича несколько марок и единиц, поэтому цена кирпича без уточнения не подставляется и обе строки стоят в `missing`. Таблица ТСН 8-31 в текущем индексе имеет подтверждённые дефекты (см. `docs/TASK.md`, 2026-11-25b), поэтому московский способ ТСН может отсутствовать с записью причины в `basis.notes`.
|
||||
|
||||
Сопоставление материалов использует ограниченный список кодов из формы региона и отдельный бюджет ИИ; неверный код модели не кешируется. Перед выпуском: 174 адресных теста и интеграционный smoke через общий FastAPI app на временной БД прошли. Полный predeploy gate запускается один раз таймером после push в release; фиксируем SHA и результат ниже.
|
||||
+25
-4
@@ -1100,11 +1100,32 @@ def calendar_timegm_year(year: int) -> int:
|
||||
QUICK_CHECKS = QUICK_CHECKS + (check_topups, check_npd_year_income)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(exit_code(main()))
|
||||
|
||||
|
||||
# Проверки проверки (T8): добавлены после объявления QUICK_CHECKS, потому что живут
|
||||
# в конце файла рядом со своими данными.
|
||||
QUICK_CHECKS = QUICK_CHECKS + (check_stuck_reviews, check_unpriced_review_calls,
|
||||
check_review_notifications)
|
||||
|
||||
|
||||
def check_stove_api() -> Check:
|
||||
"""Read-only API health signal; reports registry, sustained 5xx and stuck calls."""
|
||||
try:
|
||||
import db, stove_guard, stove_keys
|
||||
from stove_keys import iso
|
||||
now = time.time()
|
||||
with db._conn() as con:
|
||||
row = con.execute("SELECT COUNT(*) AS total, SUM(CASE WHEN http_status>=500 THEN 1 ELSE 0 END) AS errors "
|
||||
"FROM stove_api_requests WHERE ts>=?", (iso(now-3600),)).fetchone()
|
||||
stuck = con.execute("SELECT COUNT(*) FROM stove_api_requests WHERE status='opened' AND ts<?",
|
||||
(iso(now-600),)).fetchone()[0]
|
||||
bad = stove_guard.bad_key_stats()["count_10m"]
|
||||
chain_ok = any(p.uses_api_token for p in __import__('agent_provider').provider_chain('stove-api@local'))
|
||||
ok = chain_ok and (row['errors'] or 0) < 3 and stuck == 0 and bad < 500
|
||||
return Check('stove_api', ok, f"calls={row['total']} 5xx={row['errors'] or 0} stuck={stuck} bad_keys={bad} chain={chain_ok}")
|
||||
except Exception as exc:
|
||||
return Check('stove_api', False, str(exc))
|
||||
|
||||
QUICK_CHECKS = QUICK_CHECKS + (check_stove_api,)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(exit_code(main()))
|
||||
|
||||
@@ -236,6 +236,12 @@ async def favicon():
|
||||
import admin_api
|
||||
app.include_router(admin_api.router)
|
||||
|
||||
import stove_api
|
||||
app.include_router(stove_api.secure)
|
||||
app.include_router(stove_api.public)
|
||||
import stove_api_admin
|
||||
app.include_router(stove_api_admin.router)
|
||||
|
||||
# v2 живёт без inline: старый /admin сохраняет текущую политику до вывода из эксплуатации.
|
||||
ADMIN_V2_CSP = ("default-src 'self'; script-src 'self'; style-src 'self'; "
|
||||
"img-src 'self' data:; font-src 'self' data:; connect-src 'self'; "
|
||||
@@ -572,7 +578,7 @@ _AUDIT_MAP = [
|
||||
# /api/telegram/status спрашивает страница регистрации раз в несколько секунд, пока человек
|
||||
# ждёт код: без пропуска журнал действий залило бы шумом.
|
||||
_SKIP_PREFIXES = ("/static/", "/favicon", "/api/tus", "/api/limits", "/api/my-stats",
|
||||
"/api/telegram/status") # tus chunks are logged on completion, not per-PATCH
|
||||
"/api/telegram/status", "/api/v1/") # tus chunks are logged on completion, not per-PATCH
|
||||
|
||||
|
||||
def _resolve_action(method: str, path: str) -> str | None:
|
||||
@@ -770,7 +776,8 @@ async def security_headers_middleware(request: Request, call_next):
|
||||
@app.middleware("http")
|
||||
async def request_id_middleware(request: Request, call_next):
|
||||
"""R-01: номер запроса на КАЖДОМ ответе, включая ошибки и поток."""
|
||||
rid = (contract_errors.sane_request_id(request.headers.get("X-Request-Id"))
|
||||
rid = (uuid.uuid4().hex[:16] if request.url.path.startswith("/api/v1/") else
|
||||
contract_errors.sane_request_id(request.headers.get("X-Request-Id"))
|
||||
or uuid.uuid4().hex[:16])
|
||||
request.state.request_id = rid
|
||||
try:
|
||||
|
||||
@@ -395,3 +395,9 @@ def _tariff_view(db, username: str) -> dict:
|
||||
except Exception: # noqa: BLE001 — цена справочная, ронять из-за неё нельзя
|
||||
_log.exception("limits_snapshot: не удалось определить действующую цену")
|
||||
return view
|
||||
|
||||
|
||||
def global_cap_reached() -> bool:
|
||||
"""Read-only global AI cost gate for external API; never toggles chat kill switch."""
|
||||
import db
|
||||
return db.total_cost_since(time.time() - WINDOW_SECONDS) >= _float_setting("GLOBAL_DAILY_COST_USD", 20.0)
|
||||
|
||||
@@ -8,6 +8,7 @@ import { CustomersPage } from '/static/admin2/pages/customers.js';
|
||||
import { MoneyPage } from '/static/admin2/pages/money.js';
|
||||
import { WorkPage } from '/static/admin2/pages/work.js';
|
||||
import { SystemPage } from '/static/admin2/pages/system.js';
|
||||
import { StoveApiPage } from '/static/admin2/pages/stove-api.js';
|
||||
|
||||
const html = htm.bind(h);
|
||||
const TITLES = {
|
||||
@@ -16,6 +17,7 @@ const TITLES = {
|
||||
money: ["Деньги", "Поступления, поток и обязательства"],
|
||||
work: ["Работа", "Очередь, прогоны и сбои"],
|
||||
system: ["Система", "Здоровье службы и настройки"],
|
||||
"stove-api": ["API печей", "Ключи, лимиты и история вызовов"],
|
||||
};
|
||||
const App = () => {
|
||||
const [section, setSection] = useState(sectionFromPath(location.pathname));
|
||||
@@ -78,7 +80,8 @@ const App = () => {
|
||||
: section === 'customers' ? html`<${CustomersPage} />`
|
||||
: section === 'money' ? html`<${MoneyPage} />`
|
||||
: section === 'work' ? html`<${WorkPage} />`
|
||||
: section === 'system' ? html`<${SystemPage} />` : html`
|
||||
: section === 'system' ? html`<${SystemPage} />`
|
||||
: section === 'stove-api' ? html`<${StoveApiPage} />` : html`
|
||||
<section class="card" aria-labelledby="placeholder">
|
||||
<h2 id="placeholder">Раздел готовится</h2>
|
||||
<p>Данные и действия подключит следующий этап.</p>
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
import { h } from '/static/admin2/vendor/preact.module.js';
|
||||
import { useEffect, useState } from '/static/admin2/vendor/hooks.module.js';
|
||||
import htm from '/static/admin2/vendor/htm.module.js';
|
||||
import { api } from '/static/admin2/api.js';
|
||||
import { Table } from '/static/admin2/ui/table.js';
|
||||
import { Loading } from '/static/admin2/ui/loading.js';
|
||||
|
||||
const html = htm.bind(h);
|
||||
const base = '/api/admin/v2/stove-api';
|
||||
|
||||
export function StoveApiPage() {
|
||||
const [data, setData] = useState(null);
|
||||
const [error, setError] = useState('');
|
||||
const [name, setName] = useState('');
|
||||
const [note, setNote] = useState('');
|
||||
const [secret, setSecret] = useState('');
|
||||
const [selected, setSelected] = useState(null);
|
||||
const load = () => api(base).then((d) => { setData(d); setError(''); })
|
||||
.catch((e) => setError(e.message || 'API не отвечает'));
|
||||
useEffect(() => { load(); const t = setInterval(load, 60000); return () => clearInterval(t); }, []);
|
||||
const act = async (path, opts) => {
|
||||
try { await api(path, opts); await load(); }
|
||||
catch (e) { setError(e.message || 'Действие не выполнено'); }
|
||||
};
|
||||
const create = async (e) => {
|
||||
e.preventDefault();
|
||||
try {
|
||||
const made = await api(base + '/keys', {method: 'POST', body: JSON.stringify({name, note})});
|
||||
setSecret(made.secret);
|
||||
setName(''); setNote(''); await load();
|
||||
} catch (err) { setError(err.message || 'Ключ не создан'); }
|
||||
};
|
||||
const show = async (row) => {
|
||||
try { setSelected(await api(base + '/requests/' + encodeURIComponent(row.request_id))); }
|
||||
catch (e) { setError(e.message || 'Запрос не найден'); }
|
||||
};
|
||||
if (!data) return html`${error && html`<div role="alert" class="card error">${error}</div>`}<${Loading} />`;
|
||||
return html`
|
||||
${error && html`<div role="alert" class="card error">${error}</div>`}
|
||||
<section class="card">
|
||||
<h2>Состояние API</h2>
|
||||
<p>${data.enabled ? 'Включено' : 'Выключено'} · неверных ключей за сутки: ${data.invalid_keys.count_24h}</p>
|
||||
<button type="button" onClick=${() => act(base + '/enabled?enabled=' + (!data.enabled), {method: 'POST'})}>
|
||||
${data.enabled ? 'Выключить API' : 'Включить API'}</button>
|
||||
</section>
|
||||
<section class="card">
|
||||
<h2>Выдать ключ</h2>
|
||||
<form onSubmit=${create}>
|
||||
<label>Название <input value=${name} onInput=${(e) => setName(e.target.value)} required maxLength="100" /></label>
|
||||
<label>Заметка <input value=${note} onInput=${(e) => setNote(e.target.value)} maxLength="500" /></label>
|
||||
<button type="submit">Создать ключ</button>
|
||||
</form>
|
||||
${secret && html`<p role="status">Секрет виден только сейчас. Скопируйте и передайте владельцу защищённым способом:</p>
|
||||
<code>${secret}</code><button type="button" onClick=${() => navigator.clipboard.writeText(secret)}>Скопировать</button>
|
||||
<button type="button" onClick=${() => setSecret('')}>Скрыть</button>`}
|
||||
</section>
|
||||
<section class="card">
|
||||
<h2>Ключи</h2>
|
||||
<${Table} columns=${[
|
||||
{key: 'name', label: 'Название'}, {key: 'key_prefix', label: 'Префикс'},
|
||||
{key: 'calls_24h', label: 'Вызовов/сут'}, {key: 'limit_day', label: 'Лимит/сут'},
|
||||
{key: 'ai_budget_rub_day', label: 'ИИ ₽/сут'},
|
||||
{key: 'status', label: 'Статус', render: (r) => r.revoked_at ? 'отозван' : r.disabled ? 'отключён' : 'работает'},
|
||||
{key: 'actions', label: 'Действия', render: (r) => r.revoked_at ? '' : html`
|
||||
<button type="button" onClick=${() => act(base + '/keys/' + r.id + '/disabled?disabled=' + (!r.disabled), {method: 'POST'})}>${r.disabled ? 'Включить' : 'Отключить'}</button>
|
||||
<button type="button" onClick=${() => {
|
||||
const limit = Number(prompt('Новый лимит вызовов за сутки', String(r.limit_day)));
|
||||
if (Number.isInteger(limit) && limit >= 0) act(base + '/keys/' + r.id + '/limits', {method: 'PATCH', body: JSON.stringify({limit_day: limit})});
|
||||
}}>Лимит</button>
|
||||
<button type="button" onClick=${() => {
|
||||
const budget = Number(prompt('Новый бюджет ИИ, ₽ за сутки', String(r.ai_budget_rub_day)));
|
||||
if (Number.isFinite(budget) && budget >= 0) act(base + '/keys/' + r.id + '/limits', {method: 'PATCH', body: JSON.stringify({ai_budget_rub_day: budget})});
|
||||
}}>Бюджет ИИ</button>
|
||||
<button type="button" onClick=${() => {
|
||||
if (confirm('Отозвать ключ без восстановления?')) act(base + '/keys/' + r.id + '/revoke', {method: 'POST'});
|
||||
}}>Отозвать</button>`},
|
||||
]} rows=${data.keys.map((r) => ({...r, key: r.id}))} empty="Ключей пока нет" />
|
||||
</section>
|
||||
<section class="card">
|
||||
<h2>Последние вызовы</h2>
|
||||
<${Table} columns=${[
|
||||
{key: 'ts', label: 'Когда'}, {key: 'key_id', label: 'Ключ'},
|
||||
{key: 'request_id', label: 'Запрос'}, {key: 'http_status', label: 'HTTP'},
|
||||
{key: 'error_code', label: 'Ошибка'}, {key: 'duration_ms', label: 'мс'},
|
||||
]} rows=${data.history.map((r) => ({...r, key: r.id}))} onRowClick=${show} empty="Вызовов нет" />
|
||||
${selected && html`<details open><summary>Запрос ${selected.request_id}</summary>
|
||||
<pre>${JSON.stringify({request: selected.request, response: selected.response}, null, 2)}</pre>
|
||||
<button type="button" onClick=${() => setSelected(null)}>Скрыть</button></details>`}
|
||||
</section>`;
|
||||
}
|
||||
@@ -5,6 +5,7 @@ export const SECTIONS = [
|
||||
["money", "Деньги", `${BASE}/money`],
|
||||
["work", "Работа", `${BASE}/work`],
|
||||
["system", "Система", `${BASE}/system`],
|
||||
["stove-api", "API печей", `${BASE}/stove-api`],
|
||||
];
|
||||
|
||||
export function sectionFromPath(pathname) {
|
||||
|
||||
+238
@@ -0,0 +1,238 @@
|
||||
"""Public transport for the stove estimate API."""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
import time
|
||||
import uuid
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
|
||||
from fastapi import APIRouter, Request
|
||||
from fastapi.responses import JSONResponse, PlainTextResponse
|
||||
from pydantic import ValidationError
|
||||
|
||||
import stove_cache
|
||||
import stove_calc
|
||||
import stove_contract as c
|
||||
import stove_history
|
||||
import stove_keys
|
||||
import stove_match
|
||||
import stove_pricing
|
||||
|
||||
log = logging.getLogger("smeta_web")
|
||||
secure = APIRouter(tags=["stove-estimate"])
|
||||
public = APIRouter(tags=["stove-estimate"])
|
||||
_pool = ThreadPoolExecutor(max_workers=4, thread_name_prefix="stove-api")
|
||||
_slots = asyncio.Semaphore(24)
|
||||
BODY_LIMIT = 256 * 1024
|
||||
DEADLINE = 45
|
||||
|
||||
|
||||
def _rid(request: Request) -> str:
|
||||
rid = getattr(request.state, "request_id", None)
|
||||
if not rid:
|
||||
rid = uuid.uuid4().hex[:16]
|
||||
request.state.request_id = rid
|
||||
return rid
|
||||
|
||||
|
||||
def _error(request: Request, status: int, code: str, detail: str, retry=None, allow=None):
|
||||
payload = c.StoveError(detail=detail, code=code, request_id=_rid(request),
|
||||
documentation_url=c.DOCUMENTATION_URL).model_dump()
|
||||
headers = {"X-Request-Id": _rid(request)}
|
||||
if retry:
|
||||
headers["Retry-After"] = str(retry)
|
||||
if allow:
|
||||
headers["Allow"] = allow
|
||||
if status == 401:
|
||||
headers["WWW-Authenticate"] = "Bearer"
|
||||
return JSONResponse(payload, status_code=status, headers=headers)
|
||||
|
||||
|
||||
def _ip(request: Request) -> str:
|
||||
return request.client.host if request.client else "unknown"
|
||||
|
||||
|
||||
async def _run_sync(fn, *args, deadline):
|
||||
loop = asyncio.get_running_loop()
|
||||
return await asyncio.wait_for(loop.run_in_executor(_pool, fn, *args),
|
||||
timeout=max(0.01, deadline-time.monotonic()))
|
||||
|
||||
|
||||
async def _body(request: Request):
|
||||
length = request.headers.get("content-length")
|
||||
if length:
|
||||
try:
|
||||
if int(length) > BODY_LIMIT:
|
||||
return None, _error(request, 413, "body_too_large", "Тело запроса больше 256 КБ")
|
||||
except ValueError:
|
||||
return None, _error(request, 400, "invalid_request", "Неверный Content-Length")
|
||||
if request.headers.get("content-type", "").split(";", 1)[0].strip().lower() != "application/json":
|
||||
return None, _error(request, 415, "unsupported_media_type", "Нужен application/json")
|
||||
chunks, size = [], 0
|
||||
async for chunk in request.stream():
|
||||
size += len(chunk)
|
||||
if size > BODY_LIMIT:
|
||||
return None, _error(request, 413, "body_too_large", "Тело запроса больше 256 КБ")
|
||||
chunks.append(chunk)
|
||||
try:
|
||||
return json.loads(b"".join(chunks)), None
|
||||
except (ValueError, UnicodeDecodeError, RecursionError):
|
||||
return None, _error(request, 400, "invalid_json", "Тело запроса не является JSON")
|
||||
|
||||
|
||||
async def _estimate(request: Request):
|
||||
began, deadline = time.monotonic(), time.monotonic() + DEADLINE
|
||||
rid = _rid(request)
|
||||
secret = (request.headers.get("X-API-Key") or "").strip()
|
||||
try:
|
||||
auth = await _run_sync(stove_keys.authenticate, secret, _ip(request), deadline=deadline)
|
||||
except Exception:
|
||||
log.exception("stove_api: registry error rid=%s", rid)
|
||||
return _error(request, 503, "service_unavailable", "Реестр ключей временно недоступен", 30)
|
||||
status = auth["status"]
|
||||
if status == "invalid_api_key":
|
||||
return _error(request, 401, "invalid_api_key", "Неверный ключ API")
|
||||
if status == "address_blocked":
|
||||
return _error(request, 429, "rate_limited", "Слишком много неверных ключей", auth["retry_after"])
|
||||
if status == "key_inactive":
|
||||
return _error(request, 401, "key_inactive", "Ключ API отключён или отозван")
|
||||
if status == "api_off":
|
||||
return _error(request, 503, "service_unavailable", "API временно выключен", auth["retry_after"])
|
||||
key = auth["key"]
|
||||
try:
|
||||
admitted = await _run_sync(lambda: stove_history.open_request(
|
||||
key_id=key["id"], request_id=rid, limit_day=key["limit_day"]), deadline=deadline)
|
||||
except Exception:
|
||||
log.exception("stove_api: limit storage error rid=%s", rid)
|
||||
return _error(request, 503, "service_unavailable", "Лимиты API временно недоступны", 30)
|
||||
common_headers = {"Infosmeta-RateLimit-Limit": str(admitted["limit"]),
|
||||
"Infosmeta-RateLimit-Remaining": str(admitted["remaining"])}
|
||||
if not admitted["admitted"]:
|
||||
response = _error(request, 429, "rate_limited", "Лимит обращений исчерпан", admitted["retry_after"])
|
||||
response.headers.update(common_headers)
|
||||
return response
|
||||
opened = True
|
||||
response = _error(request, 500, "internal_error", "Внутренняя ошибка сервера", 30)
|
||||
request_obj = None
|
||||
context_len = 0
|
||||
cached = False
|
||||
try:
|
||||
try:
|
||||
await asyncio.wait_for(_slots.acquire(), timeout=0.01)
|
||||
except asyncio.TimeoutError:
|
||||
response = _error(request, 503, "service_unavailable", "Очередь API занята", 30)
|
||||
return response
|
||||
try:
|
||||
raw, bad = await _body(request)
|
||||
if bad:
|
||||
response = bad
|
||||
return response
|
||||
try:
|
||||
parsed = c.StoveRequest.model_validate(raw)
|
||||
except ValidationError as exc:
|
||||
response = _error(request, 400, "invalid_request", "; ".join(c.problems(exc)))
|
||||
return response
|
||||
context_len = len(parsed.stove.context or "")
|
||||
request_obj = parsed.model_dump(exclude={"stove": {"context"}})
|
||||
prices = await _run_sync(stove_pricing.load, parsed, deadline=deadline)
|
||||
version = prices.get("valid_at") or "период не указан"
|
||||
fingerprint = stove_cache.cache_key(key["id"], request_obj, version,
|
||||
prices.get("region"), prices.get("zone"))
|
||||
existing = await _run_sync(stove_cache.response_get, fingerprint, deadline=deadline)
|
||||
if existing:
|
||||
answer = existing["response"]
|
||||
cached = True
|
||||
else:
|
||||
prices = await stove_match.fill(prices, key_id=key["id"],
|
||||
budget=float(key["ai_budget_rub_day"]), deadline=deadline, request_id=rid)
|
||||
answer = stove_calc.build_answer(parsed, prices)
|
||||
await _run_sync(lambda: stove_cache.response_put(
|
||||
fingerprint, key_id=key["id"], response=answer, base_version=version), deadline=deadline)
|
||||
answer = c.StoveAnswer.model_validate(dict(answer, request_id=rid)).model_dump()
|
||||
response = JSONResponse(answer, headers={**common_headers, "X-Request-Id": rid})
|
||||
return response
|
||||
finally:
|
||||
_slots.release()
|
||||
except stove_match.BudgetExhausted:
|
||||
response = _error(request, 429, "ai_budget_exhausted", "Суточный бюджет подбора исчерпан", 3600)
|
||||
return response
|
||||
except stove_match.MatchingUnavailable as exc:
|
||||
response = _error(request, 503, "matching_unavailable", str(exc), exc.retry_after)
|
||||
return response
|
||||
except stove_pricing.InvalidRegion as exc:
|
||||
response = _error(request, 400, "invalid_request", str(exc))
|
||||
return response
|
||||
except stove_pricing.ReferenceUnavailable:
|
||||
response = _error(request, 503, "service_unavailable", "Нормативные данные временно недоступны", 30)
|
||||
return response
|
||||
except asyncio.TimeoutError:
|
||||
response = _error(request, 503, "service_unavailable", "Срок обработки запроса истёк", 30)
|
||||
return response
|
||||
except Exception:
|
||||
log.exception("stove_api: calculation failed rid=%s", rid)
|
||||
response = _error(request, 500, "internal_error", "Внутренняя ошибка сервера")
|
||||
return response
|
||||
finally:
|
||||
if opened:
|
||||
response.headers.update(common_headers)
|
||||
try:
|
||||
await asyncio.to_thread(stove_history.finish_request, rid,
|
||||
status="ok" if response.status_code < 400 else "error",
|
||||
http_status=response.status_code, request_obj=request_obj,
|
||||
response_obj=json.loads(response.body), context_present=bool(context_len),
|
||||
context_len=context_len, duration_ms=int((time.monotonic()-began)*1000),
|
||||
cached=cached, region=request_obj["stove"]["region"] if request_obj else None,
|
||||
zone=request_obj["stove"].get("zone") if request_obj else None,
|
||||
kind=request_obj["stove"]["kind"] if request_obj else None,
|
||||
error_code=json.loads(response.body).get("code"))
|
||||
except Exception:
|
||||
log.exception("stove_api: history write failed rid=%s", rid)
|
||||
raise HistoryUnavailable(common_headers) from None
|
||||
|
||||
|
||||
class HistoryUnavailable(RuntimeError):
|
||||
def __init__(self, headers):
|
||||
self.headers = headers
|
||||
|
||||
|
||||
@secure.post(c.ESTIMATE_PATH, responses={400: {"model": c.StoveError},
|
||||
401: {"model": c.StoveError},
|
||||
429: {"model": c.StoveError},
|
||||
503: {"model": c.StoveError}})
|
||||
async def estimate(request: Request):
|
||||
try:
|
||||
return await _estimate(request)
|
||||
except HistoryUnavailable as exc:
|
||||
response = _error(request, 503, "service_unavailable", "История API временно недоступна", 30)
|
||||
response.headers.update(exc.headers)
|
||||
return response
|
||||
|
||||
|
||||
PROTOCOL = """# API оценки кладки печи v1\n\nPOST `/api/v1/stove-estimate` с заголовками `X-API-Key: ism_...` и `Content-Type: application/json`. Тело: `{"stove":{"kind":"heating","bricks":{"ceramic":210,"fireclay":76},"region":"Москва","mass_kg":1320,"materials":[{"name":"Глина шамотная","qty":0.5,"unit":"т"}]}}`.\n\nВиды: `heating`, `heating_cooking`, `kitchen`, `bread`, `bath`, `fireplace`. `zone` указывайте для субъекта с несколькими ценовыми зонами. `context` служит только подсказкой и не сохраняется.\n\nОтвет содержит вилку прямых затрат в рублях: `works`, `materials`, `total`, способы в `basis.ways`, неоценённые строки в `missing`, нехватку данных в `missing_data`. `null` означает отсутствие проверенной суммы. НР и СП не начислены. Расчёт не является проектом или договором.\n\nКлюч выдаёт оператор и может отключить или отозвать. Лимиты по умолчанию: 1000 ответов за скользящие сутки, 30 обращений в минуту, 256 КБ тела. При 429 ориентируйтесь на `Retry-After`. История запросов без поля `context` хранится до 12 месяцев. Инфосмета должна быть указана как источник расчёта при показе результата человеку.\n\nОшибки: `detail`, `code`, `request_id`, `documentation_url`. Схема: `/api/v1/stove-estimate/openapi.json`.\n"""
|
||||
|
||||
|
||||
@public.get(c.PROTOCOL_PATH)
|
||||
async def protocol():
|
||||
return PlainTextResponse(PROTOCOL, media_type="text/markdown; charset=utf-8")
|
||||
|
||||
|
||||
@public.get(c.SCHEMA_PATH)
|
||||
async def schema():
|
||||
return JSONResponse({"openapi": "3.1.0", "info": {"title": "Stove Estimate API", "version": "1.0"},
|
||||
"paths": {c.ESTIMATE_PATH: {"post": {"summary": "Estimate stove masonry",
|
||||
"security": [{"ApiKey": []}],
|
||||
"requestBody": {"required": True, "content": {"application/json": {"schema": c.StoveRequest.model_json_schema()}}},
|
||||
"responses": {"200": {"description": "Estimate", "content": {"application/json": {"schema": c.StoveAnswer.model_json_schema()}}},
|
||||
"default": {"description": "Error", "content": {"application/json": {"schema": c.StoveError.model_json_schema()}}}}}}},
|
||||
"components": {"securitySchemes": {"ApiKey": {"type": "apiKey", "in": "header", "name": "X-API-Key"}}}})
|
||||
|
||||
|
||||
@public.api_route("/api/v1/{path:path}", methods=["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS", "TRACE"], include_in_schema=False)
|
||||
async def fallback(request: Request, path: str):
|
||||
known = {c.ESTIMATE_PATH: "POST", c.PROTOCOL_PATH: "GET", c.SCHEMA_PATH: "GET"}
|
||||
route = "/api/v1/" + path
|
||||
if route in known:
|
||||
return _error(request, 405, "method_not_allowed", "Метод не разрешён", allow=known[route])
|
||||
return _error(request, 404, "not_found", "Маршрут не найден")
|
||||
@@ -0,0 +1,100 @@
|
||||
"""Operator controls for the stove API. All routes inherit the admin dependency."""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
from fastapi import APIRouter, Depends, HTTPException, Request
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
import db
|
||||
import stove_cache
|
||||
import stove_guard
|
||||
import stove_history
|
||||
import stove_keys
|
||||
from admin_auth import require_admin
|
||||
|
||||
router = APIRouter(prefix="/api/admin/v2/stove-api", tags=["stove-api-admin"],
|
||||
dependencies=[Depends(require_admin)])
|
||||
|
||||
|
||||
class NewKey(BaseModel):
|
||||
name: str = Field(min_length=1, max_length=100)
|
||||
note: str = Field(default="", max_length=500)
|
||||
limit_day: int = Field(default=1000, ge=0, le=100000)
|
||||
ai_budget_rub_day: float = Field(default=300, ge=0, le=10000)
|
||||
|
||||
|
||||
class Limits(BaseModel):
|
||||
limit_day: int | None = Field(default=None, ge=0, le=100000)
|
||||
ai_budget_rub_day: float | None = Field(default=None, ge=0, le=10000)
|
||||
|
||||
|
||||
def _audit(request: Request, action: str, detail: str):
|
||||
db.log_action(require_admin(request), action, request.method, str(request.url.path),
|
||||
detail=detail, ip=request.client.host if request.client else None, status_code=200)
|
||||
|
||||
|
||||
@router.get("")
|
||||
async def overview():
|
||||
keys, bad = await asyncio.gather(asyncio.to_thread(stove_keys.list_keys),
|
||||
asyncio.to_thread(stove_guard.bad_key_stats))
|
||||
return {"enabled": await asyncio.to_thread(stove_keys.api_enabled),
|
||||
"keys": keys, "invalid_keys": bad,
|
||||
"history": await asyncio.to_thread(stove_history.list_requests, limit=25)}
|
||||
|
||||
|
||||
@router.post("/keys")
|
||||
async def create_key(request: Request, body: NewKey):
|
||||
made = await asyncio.to_thread(stove_keys.create_key, name=body.name, note=body.note,
|
||||
limit_day=body.limit_day, ai_budget_rub_day=body.ai_budget_rub_day)
|
||||
await asyncio.to_thread(_audit, request, "stove_api.key_create", f"id={made['id']}")
|
||||
return made # secret appears only once
|
||||
|
||||
|
||||
@router.post("/keys/{key_id}/disabled")
|
||||
async def disabled(key_id: int, request: Request, disabled: bool = True):
|
||||
ok = await asyncio.to_thread(stove_keys.set_disabled, key_id, disabled)
|
||||
if not ok:
|
||||
raise HTTPException(404, "Ключ не найден")
|
||||
await asyncio.to_thread(_audit, request, "stove_api.key_disabled", f"id={key_id},disabled={disabled}")
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
@router.post("/keys/{key_id}/revoke")
|
||||
async def revoke(key_id: int, request: Request):
|
||||
ok = await asyncio.to_thread(stove_keys.revoke_key, key_id)
|
||||
if not ok:
|
||||
raise HTTPException(404, "Ключ не найден")
|
||||
await asyncio.to_thread(_audit, request, "stove_api.key_revoke", f"id={key_id}")
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
@router.patch("/keys/{key_id}/limits")
|
||||
async def limits(key_id: int, request: Request, body: Limits):
|
||||
if body.limit_day is None and body.ai_budget_rub_day is None:
|
||||
raise HTTPException(400, "Укажите хотя бы один лимит")
|
||||
made = await asyncio.to_thread(stove_keys.set_limit, key_id, limit_day=body.limit_day,
|
||||
ai_budget_rub_day=body.ai_budget_rub_day)
|
||||
if not made:
|
||||
raise HTTPException(404, "Ключ не найден")
|
||||
await asyncio.to_thread(_audit, request, "stove_api.key_limits", f"id={key_id}")
|
||||
return made
|
||||
|
||||
|
||||
@router.post("/enabled")
|
||||
async def enabled(request: Request, enabled: bool):
|
||||
await asyncio.to_thread(stove_keys.set_api_enabled, enabled)
|
||||
await asyncio.to_thread(_audit, request, "stove_api.switch", f"enabled={enabled}")
|
||||
return {"enabled": enabled}
|
||||
|
||||
|
||||
@router.get("/requests")
|
||||
async def requests(key_id: int | None = None, limit: int = 50, offset: int = 0):
|
||||
return await asyncio.to_thread(stove_history.list_requests, key_id, limit=limit, offset=offset)
|
||||
|
||||
|
||||
@router.get("/requests/{request_id}")
|
||||
async def request_detail(request_id: str):
|
||||
item = await asyncio.to_thread(stove_history.get_request, request_id)
|
||||
if item is None:
|
||||
raise HTTPException(404, "Запрос не найден")
|
||||
return item
|
||||
@@ -0,0 +1,29 @@
|
||||
"""Daily operational summary for the stove API."""
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
import db
|
||||
import stove_guard
|
||||
from stove_keys import iso
|
||||
|
||||
|
||||
def collect(hours: int = 24) -> dict:
|
||||
since = time.time() - hours * 3600
|
||||
with db._conn() as con:
|
||||
rows = con.execute("SELECT COUNT(*) AS total, SUM(CASE WHEN http_status>=500 THEN 1 ELSE 0 END) AS errors, "
|
||||
"SUM(CASE WHEN cached=1 THEN 1 ELSE 0 END) AS cached, "
|
||||
"COUNT(DISTINCT key_id) AS keys, COALESCE(SUM(ai_cost_rub),0) AS ai_rub "
|
||||
"FROM stove_api_requests WHERE ts>=?",
|
||||
(iso(since),)).fetchone()
|
||||
body = con.execute("SELECT COALESCE(SUM(history_bytes),0) FROM stove_api_keys").fetchone()[0]
|
||||
return {"total": rows["total"], "errors": rows["errors"] or 0,
|
||||
"cached": rows["cached"] or 0, "keys": rows["keys"],
|
||||
"ai_rub": round(rows["ai_rub"], 2), "history_bytes": body,
|
||||
"invalid_keys": stove_guard.bad_key_stats()["count_24h"]}
|
||||
|
||||
|
||||
def render(stats: dict) -> str:
|
||||
return (f"• API печей: {stats['total']} вызовов, {stats['keys']} ключей, "
|
||||
f"{stats['errors']} ошибок 5xx, {stats['cached']} из кеша; "
|
||||
f"ИИ {stats['ai_rub']} ₽, история {stats['history_bytes']} Б, "
|
||||
f"неверных ключей {stats['invalid_keys']}")
|
||||
+7
-2
@@ -102,6 +102,8 @@ def build_answer(stove: c.StoveRequest, prices: dict) -> dict:
|
||||
answer["total"] = _fork([work + amount for _, work in ways])
|
||||
if ways and ways[0][1] is not None:
|
||||
answer["works"] = _fork([work for _, work in ways])
|
||||
if answer["total"] is None:
|
||||
answer["total"] = dict(answer["works"])
|
||||
return answer
|
||||
|
||||
|
||||
@@ -148,12 +150,15 @@ def _volumes(stove: c.StoveRequest, prices: dict, notes: list):
|
||||
body, ways, gaps = stove.stove, [], []
|
||||
norms = prices.get("norms") or {}
|
||||
kinds = [k for k in c.BRICK_KINDS if getattr(body.bricks, k) > 0]
|
||||
absent = [k for k in kinds if not norms.get(k)]
|
||||
aggregate = norms.get("aggregate")
|
||||
absent = [] if aggregate else [k for k in kinds if not norms.get(k)]
|
||||
if aggregate:
|
||||
notes.append("объём по суммарной норме кирпича ГЭСН; раздельной нормы на шамотный кирпич нет")
|
||||
if absent:
|
||||
names = " и ".join(c.BRICK_NAMES[k] for k in absent)
|
||||
notes.append(f"в составе расценки нет нормы на {names} — объём по кирпичу не посчитан")
|
||||
else:
|
||||
per_m3 = sum(_fraction(norms[k]) for k in kinds) * 1000
|
||||
per_m3 = (_fraction(aggregate) if aggregate else sum(_fraction(norms[k]) for k in kinds)) * 1000
|
||||
pieces = sum(getattr(body.bricks, k) for k in kinds)
|
||||
ways.append((f"по кирпичу ({_bricks_label(body.bricks)})", Fraction(pieces) / per_m3))
|
||||
if body.mass_kg is not None:
|
||||
|
||||
+7
-1
@@ -27,9 +27,15 @@ def cleanup(*, now=None) -> dict:
|
||||
"UPDATE stove_api_requests SET status=? WHERE status=? AND ts<?",
|
||||
(stove_history.STATUS_NO_RESPONSE, stove_history.STATUS_OPENED,
|
||||
stove_history.iso(now - stove_history.STALE_OPEN_SEC))).rowcount
|
||||
with db._conn() as conn:
|
||||
settled = conn.execute(
|
||||
"UPDATE llm_usage SET input_tokens=0, cache_tokens=0, output_tokens=0, "
|
||||
"cost_basis='unknown' WHERE path='api:stove-estimate' AND cost_basis='pending' "
|
||||
"AND ts<?", (now - 600,)).rowcount
|
||||
freed = _free_old_bodies(stove_history.iso(now - stove_history.BODY_KEEP_SEC))
|
||||
total = _finish_caps()
|
||||
return {"closed_stale": closed, "deleted_bodies": freed, "history_bytes": total}
|
||||
return {"closed_stale": closed, "settled_ai": settled,
|
||||
"deleted_bodies": freed, "history_bytes": total}
|
||||
|
||||
|
||||
def _free_old_bodies(old: str) -> int:
|
||||
|
||||
+213
@@ -0,0 +1,213 @@
|
||||
"""Bounded AI selection of normative resource codes for unmatched stove bill lines."""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import threading
|
||||
import time
|
||||
|
||||
import agent_provider
|
||||
import db
|
||||
import fgis_ref
|
||||
import gateway
|
||||
import provider_health
|
||||
import quotas
|
||||
import stove_cache
|
||||
import stove_pricing
|
||||
import stove_history
|
||||
import zaika_quota
|
||||
from stove_units import convert_qty
|
||||
|
||||
USER = "stove-api@local"
|
||||
PATH = "api:stove-estimate"
|
||||
RESERVE_RUB = 5.0
|
||||
GLOBAL_RUB_DAY = 600.0
|
||||
_lock = threading.Lock()
|
||||
_semaphore = asyncio.Semaphore(3)
|
||||
|
||||
|
||||
class MatchingUnavailable(RuntimeError):
|
||||
def __init__(self, retry_after=30):
|
||||
super().__init__("Сопоставление материалов временно недоступно")
|
||||
self.retry_after = retry_after
|
||||
|
||||
|
||||
class BudgetExhausted(RuntimeError):
|
||||
retry_after = 3600
|
||||
|
||||
|
||||
def _reserve(key_id: int, budget: float, profile) -> int:
|
||||
now = time.time()
|
||||
with _lock:
|
||||
with db._conn() as con:
|
||||
row = con.execute(
|
||||
"SELECT COALESCE(SUM(price_rub),0) AS spent FROM llm_usage "
|
||||
"WHERE path=? AND tab_id=? AND ts>=? AND cost_basis!='unknown' "
|
||||
"AND (cost_basis!='pending' OR ts>=?)",
|
||||
(PATH, f"stove:{key_id}", now-86400, now-600)).fetchone()
|
||||
key_spent = float(row["spent"])
|
||||
row = con.execute(
|
||||
"SELECT COALESCE(SUM(price_rub),0) AS spent FROM llm_usage "
|
||||
"WHERE path=? AND ts>=?", (PATH, now-86400)).fetchone()
|
||||
total = float(row["spent"])
|
||||
stop = con.execute("SELECT value FROM app_settings WHERE key='agent_killswitch'").fetchone()
|
||||
reason = con.execute("SELECT value FROM app_settings WHERE key='agent_killswitch_reason'").fetchone()
|
||||
if key_spent + RESERVE_RUB > budget:
|
||||
raise BudgetExhausted()
|
||||
try:
|
||||
global_full = quotas.global_cap_reached()
|
||||
except Exception as exc:
|
||||
raise MatchingUnavailable(3600) from exc
|
||||
if total + RESERVE_RUB > GLOBAL_RUB_DAY or global_full:
|
||||
raise MatchingUnavailable(3600)
|
||||
if stop and stop[0] == "on" and reason and reason[0] == "manual":
|
||||
raise MatchingUnavailable(3600)
|
||||
return db.create_llm_usage_stub(USER, f"stove:{key_id}", PATH, RESERVE_RUB,
|
||||
provider=profile.name, model=profile.model)
|
||||
|
||||
|
||||
def _candidates(name: str, unit: str, region: str, zone: str | None) -> list[dict]:
|
||||
found = fgis_ref.find_resource_price(query=name, region=region, zone=zone, limit=12)
|
||||
if found.get("status") == "db_unavailable":
|
||||
raise MatchingUnavailable(30)
|
||||
if found.get("status") != "ok" or found.get("multiple_zones"):
|
||||
return []
|
||||
rows = []
|
||||
for row in found.get("results", []):
|
||||
if (row.get("code") and convert_qty(1, unit, row.get("unit")) is not None
|
||||
and stove_pricing._price(row)[0] is not None):
|
||||
rows.append(row)
|
||||
return rows[:12]
|
||||
|
||||
|
||||
def _profile_chain():
|
||||
chain = [p for p in agent_provider.provider_chain(USER)
|
||||
if p.uses_api_token and provider_health.should_include(p.name)]
|
||||
if any(p.name == "glm" for p in chain):
|
||||
quota = zaika_quota.snapshot()
|
||||
if quota.get("known") and (quota.get("percent_used") or 0) >= 80:
|
||||
chain = [p for p in chain if p.name != "glm"]
|
||||
return chain
|
||||
|
||||
|
||||
async def _call(profile, body: dict, timeout: float) -> tuple[str, dict]:
|
||||
async def consume():
|
||||
chunks, usage = [], {}
|
||||
async for event in gateway._provider_stream(profile, body):
|
||||
if "delta" in event:
|
||||
chunks.append(event["delta"])
|
||||
if "usage" in event:
|
||||
usage = event["usage"] or {}
|
||||
return "".join(chunks), usage
|
||||
return await asyncio.wait_for(consume(), timeout=timeout)
|
||||
|
||||
|
||||
async def _ask(batch: list[dict], key_id: int, budget: float, deadline: float, request_id: str) -> list[dict]:
|
||||
try:
|
||||
await asyncio.wait_for(_semaphore.acquire(), timeout=min(10, max(0.01, deadline-time.monotonic())))
|
||||
except asyncio.TimeoutError as exc:
|
||||
raise MatchingUnavailable() from exc
|
||||
try:
|
||||
chain = await asyncio.to_thread(_profile_chain)
|
||||
if not chain:
|
||||
raise MatchingUnavailable()
|
||||
prompt = {"task": "Выбери для каждой строки один код из её списка candidates или null. "
|
||||
"Верни только JSON массив объектов {index,code}. Не придумывай коды.",
|
||||
"lines": [{"index": x["index"], "name": x["line"]["name"],
|
||||
"unit": x["line"]["unit"],
|
||||
"candidates": [{"code": r["code"], "name": r["name"][:80], "unit": r["unit"]}
|
||||
for r in x["candidates"]]} for x in batch]}
|
||||
body = {"messages": [{"role": "user", "content": json.dumps(prompt, ensure_ascii=False)}],
|
||||
"max_tokens": 2000}
|
||||
for profile in chain[:2]:
|
||||
usage_id = await asyncio.to_thread(_reserve, key_id, budget, profile)
|
||||
started = time.time()
|
||||
usage = {}
|
||||
try:
|
||||
text, usage = await _call(profile, body, max(0.1, min(20, deadline-time.monotonic())))
|
||||
payload = json.loads(text.strip().removeprefix("```json").removesuffix("```").strip())
|
||||
if not isinstance(payload, list):
|
||||
raise ValueError("ответ модели не массив")
|
||||
valid = {x["index"]: {r["code"] for r in x["candidates"]} for x in batch}
|
||||
picked = {}
|
||||
for item in payload:
|
||||
if not isinstance(item, dict) or item.get("index") not in valid:
|
||||
raise ValueError("неизвестный номер строки")
|
||||
code = item.get("code")
|
||||
picked[item["index"]] = (code if code in valid[item["index"]] else
|
||||
None if code is None else "__invalid__")
|
||||
if set(picked) != set(valid):
|
||||
raise ValueError("пропущена строка")
|
||||
return [picked[x["index"]] for x in batch]
|
||||
except gateway.ProviderError as exc:
|
||||
if profile.name == "glm" and exc.status == 429:
|
||||
await asyncio.to_thread(zaika_quota.note_refusal, profile.name, str(exc))
|
||||
continue
|
||||
except (asyncio.TimeoutError, ValueError, RuntimeError, OSError, json.JSONDecodeError):
|
||||
continue
|
||||
finally:
|
||||
priced = gateway._price(USER, profile.model, usage, started) if usage else {}
|
||||
price = priced.get("price_rub")
|
||||
await asyncio.to_thread(db.settle_llm_usage_stub, usage_id,
|
||||
input_tokens=(usage.get("input_tokens") or 0),
|
||||
cache_tokens=usage.get("cache_read_input_tokens") or 0,
|
||||
output_tokens=usage.get("output_tokens") or 0,
|
||||
price_rub=price if price is not None else RESERVE_RUB,
|
||||
cost_rub=priced.get("cost_rub"), cost_usd=priced.get("cost_usd"),
|
||||
provider=profile.name, model=profile.model,
|
||||
cost_basis=priced.get("cost_basis") or "unknown")
|
||||
await asyncio.to_thread(stove_history.add_ai_cost, request_id,
|
||||
price if price is not None else RESERVE_RUB,
|
||||
priced.get("cost_usd"))
|
||||
raise MatchingUnavailable()
|
||||
finally:
|
||||
_semaphore.release()
|
||||
|
||||
|
||||
async def fill(prices: dict, *, key_id: int, budget: float, deadline: float, request_id: str) -> dict:
|
||||
"""Resolve only unmatched non-brick lines; all assignments are checked against candidates."""
|
||||
todo = []
|
||||
for index, line in enumerate(prices.get("lines") or []):
|
||||
if line.get("code") is not None or line.get("bricks"):
|
||||
continue
|
||||
ck = stove_cache.cache_key(key_id, prices["region"], prices.get("zone"),
|
||||
line["name"], line["unit"], prices["valid_at"])
|
||||
cached = await asyncio.to_thread(stove_cache.match_get, ck)
|
||||
if cached:
|
||||
if cached.get("code"):
|
||||
got = await asyncio.to_thread(fgis_ref.find_resource_price,
|
||||
query=cached["code"], region=prices["region"], zone=prices.get("zone"), limit=2)
|
||||
rows = [r for r in got.get("results", []) if r.get("code") == cached["code"]]
|
||||
if rows and stove_pricing._price(rows[0])[0] is not None:
|
||||
prices["lines"][index] = stove_pricing._line(line["name"], line["qty"], line["unit"], rows[0])
|
||||
continue
|
||||
await asyncio.to_thread(stove_cache.match_delete, ck)
|
||||
else:
|
||||
continue
|
||||
candidates = await asyncio.to_thread(_candidates, line["name"], line["unit"],
|
||||
prices["region"], prices.get("zone"))
|
||||
if candidates:
|
||||
todo.append({"index": index, "line": line, "candidates": candidates, "cache_key": ck})
|
||||
else:
|
||||
await asyncio.to_thread(stove_cache.match_put, ck, key_id=key_id,
|
||||
line_norm=fgis_ref.norm_text(line["name"]), kind="material",
|
||||
code=None, name=None, unit=None, ttl_sec=stove_cache.NEG_TTL_SEC,
|
||||
base_version=prices["valid_at"])
|
||||
if todo:
|
||||
for start in range(0, len(todo), 25):
|
||||
batch = todo[start:start+25]
|
||||
codes = await _ask(batch, key_id, budget, deadline, request_id)
|
||||
for item, code in zip(batch, codes):
|
||||
row = next((r for r in item["candidates"] if r["code"] == code), None)
|
||||
line = item["line"]
|
||||
if row:
|
||||
prices["lines"][item["index"]] = stove_pricing._line(line["name"], line["qty"], line["unit"], row)
|
||||
if code == "__invalid__":
|
||||
continue
|
||||
await asyncio.to_thread(stove_cache.match_put, item["cache_key"], key_id=key_id,
|
||||
line_norm=fgis_ref.norm_text(line["name"]), kind="material",
|
||||
code=code, name=row["name"] if row else None,
|
||||
unit=row["unit"] if row else None,
|
||||
ttl_sec=stove_cache.POS_TTL_SEC if row else stove_cache.NEG_TTL_SEC,
|
||||
base_version=prices["valid_at"])
|
||||
return prices
|
||||
@@ -0,0 +1,157 @@
|
||||
"""Read-only adapter from stove estimates to the normative reference databases."""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
|
||||
import fgis_ref
|
||||
import fsnb_ref
|
||||
import rim_calc
|
||||
import tsn_calc
|
||||
import tsn_ref
|
||||
import stove_contract as c
|
||||
from stove_units import convert_qty
|
||||
|
||||
RATES = {
|
||||
"heating": ("08-08-003-01", "8-31-1"),
|
||||
"heating_cooking": ("08-08-003-06", "8-31-6"),
|
||||
"kitchen": ("08-08-003-05", "8-31-5"),
|
||||
"bread": ("08-08-003-09", "8-31-9"),
|
||||
}
|
||||
BRICK_QUERY = {"ceramic": "кирпич керамический", "fireclay": "кирпич шамотный"}
|
||||
_BRICK_WORDS = ("кирпич", "шамот", "огнеупор")
|
||||
_ROMAN = ("I", "II", "III", "IV")
|
||||
|
||||
|
||||
class ReferenceUnavailable(RuntimeError):
|
||||
pass
|
||||
|
||||
|
||||
class InvalidRegion(ValueError):
|
||||
pass
|
||||
|
||||
|
||||
def _period(label: str | None) -> str:
|
||||
value = label or ""
|
||||
m = re.search(r"([1-4])\s*(?:квартал|кв)\.?\s*(20\d\d)", value, re.I)
|
||||
return f"{_ROMAN[int(m[1])-1]} кв. {m[2]}" if m else value
|
||||
|
||||
|
||||
def _choose(result: dict, unit: str, query: str) -> dict | None:
|
||||
"""Accept only an exact name and convertible unit; fuzzy search is for AI candidates."""
|
||||
if result.get("status") != "ok" or result.get("multiple_zones"):
|
||||
return None
|
||||
normal = fgis_ref.norm_text(query)
|
||||
same = [x for x in result.get("results", []) if fgis_ref.norm_text(x["name"]) == normal
|
||||
and convert_qty(1, unit, x.get("unit")) is not None]
|
||||
return same[0] if len(same) == 1 else None
|
||||
|
||||
|
||||
def _price(row: dict) -> tuple[float | None, str | None]:
|
||||
if row.get("price_calc") is not None:
|
||||
return row["price_calc"], "calc"
|
||||
if row.get("price_current") is not None:
|
||||
return row["price_current"], "current"
|
||||
return None, None
|
||||
|
||||
|
||||
def _line(name: str, qty: float, unit: str, row: dict | None, *, bricks=False) -> dict:
|
||||
out = {"name": name, "qty": qty, "unit": unit, "code": None, "bricks": bricks}
|
||||
if row:
|
||||
price, kind = _price(row)
|
||||
out.update(code=row["code"], resource_name=row["name"], resource_unit=row["unit"],
|
||||
price=price, price_kind=kind)
|
||||
return out
|
||||
|
||||
|
||||
def _norms(code: str) -> dict:
|
||||
got = fsnb_ref.find_gesn_composition(query=code, base="2022")
|
||||
if got.get("status") == "db_unavailable":
|
||||
raise ReferenceUnavailable("составы ГЭСН не доступны")
|
||||
works = [x for x in got.get("results", []) if x.get("code") == code and x.get("base_type") == "ГЭСН"]
|
||||
if not works:
|
||||
return {"ceramic": None, "fireclay": None}
|
||||
out = {"ceramic": None, "fireclay": None}
|
||||
for row in works[0].get("resources") or []:
|
||||
name = (row.get("name") or "").lower()
|
||||
if "кирпич" not in name or row.get("quantity") is None:
|
||||
continue
|
||||
kind = "fireclay" if "шамот" in name or "огнеупор" in name else "ceramic"
|
||||
if convert_qty(1, row.get("unit"), "1000 шт") is None:
|
||||
continue
|
||||
out[kind] = (out[kind] or 0) + float(float(row["quantity"]) * float(convert_qty(1, row["unit"], "1000 шт")))
|
||||
if out["ceramic"] and out["fireclay"] is None:
|
||||
out["aggregate"] = out["ceramic"]
|
||||
return out
|
||||
|
||||
|
||||
def _tsn(kind: str, notes: list[str]) -> dict | None:
|
||||
code = RATES[kind][1]
|
||||
found = tsn_ref.find_work(code, limit=20)
|
||||
rows = [r for r in found.get("items", []) if r.get("code") == code
|
||||
and r.get("book") == "ТСН-2001.3" and r.get("chapter") == "3-8"]
|
||||
if len(rows) != 1:
|
||||
notes.append(f"ТСН {code}: точная строка книги/главы не найдена")
|
||||
return None
|
||||
row = rows[0]
|
||||
if row.get("ot") is None or row.get("em") is None or row["ot"] + row["em"] <= 0:
|
||||
notes.append(f"ТСН {code}: нет ОТ или ЭМ")
|
||||
return None
|
||||
index = tsn_calc.find_rate_index(row)
|
||||
if index.get("status") != "ok":
|
||||
notes.append(f"ТСН {code}: коэффициент выпуска не найден")
|
||||
return None
|
||||
return {"code": code, "labor": row["ot"] * index["value"],
|
||||
"machines": row["em"] * index["value"]}
|
||||
|
||||
|
||||
def load(stove: c.StoveRequest) -> dict:
|
||||
s = stove.stove
|
||||
notes: list[str] = []
|
||||
probe = fgis_ref.find_resource_price(query=BRICK_QUERY["ceramic"], region=s.region, zone=s.zone, limit=12)
|
||||
status = probe.get("status")
|
||||
if status in ("region_not_found", "region_ambiguous", "zone_not_found"):
|
||||
raise InvalidRegion(probe.get("message") or status)
|
||||
if status in ("db_unavailable", "error"):
|
||||
raise ReferenceUnavailable(probe.get("message") or status)
|
||||
if probe.get("multiple_zones"):
|
||||
return {"valid_at": "период не указан", "region": s.region, "zone_required": [z["zone_name"] for z in probe.get("zones", [])], "notes": []}
|
||||
region = probe.get("region") or s.region
|
||||
zones = probe.get("zones") or []
|
||||
zone = zones[0]["zone_name"] if zones else s.zone
|
||||
periods = [r.get("period") for r in probe.get("results", []) if r.get("period")]
|
||||
out = {"valid_at": _period(periods[0]) if periods else "период не указан", "region": region,
|
||||
"zone": s.zone and zone, "notes": notes, "lines": [], "brick_lines_skipped": []}
|
||||
if s.kind in RATES:
|
||||
code = RATES[s.kind][0]
|
||||
rate = rim_calc.calc_rim_rate(code=code, region=region, zone=zone)
|
||||
if rate.get("status") == "zone_required":
|
||||
out["zone_required"] = [z["zone_name"] for z in rate.get("zones", [])]
|
||||
return out
|
||||
if rate.get("status") == "db_unavailable":
|
||||
raise ReferenceUnavailable(rate.get("message") or "РИМ не доступен")
|
||||
if rate.get("status") == "ok":
|
||||
totals = rate["totals"]
|
||||
if totals.get("labor") is not None and totals.get("machines") is not None:
|
||||
out["federal"] = {"code": code, "labor": totals["labor"], "machines": totals["machines"],
|
||||
"machinist_labor_excluded": totals.get("machinist_labor_excluded", False)}
|
||||
if not totals.get("complete"):
|
||||
notes.append("в составе ФЕР есть неоценённые ресурсы; для работ взяты только ОТ и ЭМ")
|
||||
else:
|
||||
notes.append(f"ФЕР {code}: {rate.get('status')}")
|
||||
out["norms"] = _norms(code)
|
||||
if region.lower() in ("москва", "город москва", "г. москва"):
|
||||
out["tsn"] = _tsn(s.kind, notes)
|
||||
for kind, qty in (("ceramic", s.bricks.ceramic), ("fireclay", s.bricks.fireclay)):
|
||||
if not qty:
|
||||
continue
|
||||
query = BRICK_QUERY[kind]
|
||||
got = probe if kind == "ceramic" else fgis_ref.find_resource_price(query=query, region=region, zone=zone, limit=12)
|
||||
out["lines"].append(_line(query, qty, "шт", _choose(got, "шт", query), bricks=True))
|
||||
for item in s.materials or []:
|
||||
name = item.name
|
||||
if any(word in name.lower() for word in _BRICK_WORDS):
|
||||
out["brick_lines_skipped"].append(name)
|
||||
continue
|
||||
got = fgis_ref.find_resource_price(query=name, region=region, zone=zone, limit=12)
|
||||
out["lines"].append(_line(name, item.qty, item.unit, _choose(got, item.unit, name)))
|
||||
return out
|
||||
@@ -0,0 +1,75 @@
|
||||
"""Boundary tests: authentication precedes body parsing; success and errors share a contract."""
|
||||
import os
|
||||
import sys
|
||||
|
||||
from fastapi import FastAPI
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
if ROOT not in sys.path:
|
||||
sys.path.insert(0, ROOT)
|
||||
|
||||
import stove_api
|
||||
|
||||
|
||||
def _client():
|
||||
app = FastAPI()
|
||||
app.include_router(stove_api.secure)
|
||||
app.include_router(stove_api.public)
|
||||
return TestClient(app)
|
||||
|
||||
|
||||
def test_invalid_key_wins_over_invalid_body(monkeypatch):
|
||||
monkeypatch.setattr(stove_api.stove_keys, "authenticate", lambda secret, ip: {"status": "invalid_api_key"})
|
||||
response = _client().post("/api/v1/stove-estimate", content="not-json",
|
||||
headers={"Content-Type": "application/json", "X-API-Key": "wrong"})
|
||||
assert response.status_code == 401
|
||||
assert response.json()["code"] == "invalid_api_key"
|
||||
assert response.json()["request_id"] == response.headers["X-Request-Id"]
|
||||
|
||||
|
||||
def test_estimate_success_and_history(monkeypatch):
|
||||
calls = []
|
||||
key = {"id": 7, "limit_day": 1000, "ai_budget_rub_day": 300}
|
||||
monkeypatch.setattr(stove_api.stove_keys, "authenticate", lambda *args: {"status": "ok", "key": key})
|
||||
monkeypatch.setattr(stove_api.stove_history, "open_request", lambda **kw:
|
||||
{"admitted": True, "limit": 1000, "remaining": 999})
|
||||
monkeypatch.setattr(stove_api.stove_history, "finish_request", lambda *args, **kw: calls.append(kw))
|
||||
monkeypatch.setattr(stove_api.stove_pricing, "load", lambda parsed:
|
||||
{"valid_at": "III кв. 2026", "region": "Москва", "lines": []})
|
||||
monkeypatch.setattr(stove_api.stove_cache, "response_get", lambda key: None)
|
||||
monkeypatch.setattr(stove_api.stove_cache, "response_put", lambda *args, **kw: None)
|
||||
async def fill(prices, **kw):
|
||||
return prices
|
||||
monkeypatch.setattr(stove_api.stove_match, "fill", fill)
|
||||
response = _client().post("/api/v1/stove-estimate", json={"stove": {
|
||||
"kind": "bath", "bricks": {"ceramic": 1, "fireclay": 0}, "region": "Москва"}},
|
||||
headers={"X-API-Key": "test"})
|
||||
assert response.status_code == 200, response.text
|
||||
body = response.json()
|
||||
assert body["total"] is None
|
||||
assert body["missing_data"] == ["расценка на кладку банной печи: в базах нет", "ведомость материалов"]
|
||||
assert body["request_id"] == response.headers["X-Request-Id"]
|
||||
assert response.headers["Infosmeta-RateLimit-Remaining"] == "999"
|
||||
assert calls and calls[0]["http_status"] == 200
|
||||
|
||||
|
||||
def test_invalid_request_reports_field_path(monkeypatch):
|
||||
key = {"id": 7, "limit_day": 1000, "ai_budget_rub_day": 300}
|
||||
monkeypatch.setattr(stove_api.stove_keys, "authenticate", lambda *args: {"status": "ok", "key": key})
|
||||
monkeypatch.setattr(stove_api.stove_history, "open_request", lambda **kw:
|
||||
{"admitted": True, "limit": 1000, "remaining": 999})
|
||||
monkeypatch.setattr(stove_api.stove_history, "finish_request", lambda *args, **kw: None)
|
||||
response = _client().post("/api/v1/stove-estimate", json={"stove": {"kind": "bath"}},
|
||||
headers={"X-API-Key": "test"})
|
||||
assert response.status_code == 400
|
||||
assert response.json()["code"] == "invalid_request"
|
||||
assert "stove.bricks" in response.json()["detail"]
|
||||
|
||||
|
||||
def test_protocol_and_schema_are_public():
|
||||
client = _client()
|
||||
assert client.get("/api/v1/stove-estimate/protocol").status_code == 200
|
||||
schema = client.get("/api/v1/stove-estimate/openapi.json").json()
|
||||
assert "stove" in schema["paths"]["/api/v1/stove-estimate"]["post"]["requestBody"]["content"]["application/json"]["schema"]["properties"]
|
||||
assert client.get("/api/v1/stove-estimate").json()["code"] == "method_not_allowed"
|
||||
@@ -257,3 +257,11 @@ def test_no_bill_is_named_and_bricks_alone_are_materials():
|
||||
assert out["missing_data"] == ["ведомость материалов"]
|
||||
assert out["materials"] == {"min": 4420, "max": 4420, "min_way": 0, "max_way": 0}
|
||||
assert out["total"]["min"] == 4420 + 1106
|
||||
|
||||
|
||||
def test_works_only_are_a_valid_partial_total_when_material_prices_are_missing():
|
||||
out = _checked(_run(lines=[dict(UNMATCHED)], notes=[]))
|
||||
assert out["works"] is not None
|
||||
assert out["materials"] is None
|
||||
assert out["total"] == out["works"]
|
||||
assert out["missing"] == [UNMATCHED["name"]]
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
"""AI matcher accepts only supplied codes and keeps provider failures out of the cache."""
|
||||
import asyncio
|
||||
import os
|
||||
import sys
|
||||
from types import SimpleNamespace
|
||||
|
||||
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
if ROOT not in sys.path:
|
||||
sys.path.insert(0, ROOT)
|
||||
|
||||
import stove_match
|
||||
|
||||
|
||||
def _prices():
|
||||
return {"region": "Москва", "zone": None, "valid_at": "III кв. 2026",
|
||||
"lines": [{"name": "Глина шамотная", "qty": 0.5, "unit": "т", "code": None}]}
|
||||
|
||||
|
||||
def _candidate():
|
||||
return {"code": "17.4.05.01-0051", "name": "Глина огнеупорная шамотная", "unit": "кг", "price_calc": 26.08}
|
||||
|
||||
|
||||
def test_match_uses_only_candidate_code_and_writes_cache(monkeypatch):
|
||||
saved = []
|
||||
monkeypatch.setattr(stove_match.stove_cache, "match_get", lambda key: None)
|
||||
monkeypatch.setattr(stove_match.stove_cache, "match_put", lambda key, **kw: saved.append(kw))
|
||||
monkeypatch.setattr(stove_match, "_candidates", lambda *args: [_candidate()])
|
||||
monkeypatch.setattr(stove_match, "_profile_chain", lambda: [SimpleNamespace(name="glm", model="mock")])
|
||||
monkeypatch.setattr(stove_match, "_reserve", lambda *args: 42)
|
||||
monkeypatch.setattr(stove_match.db, "settle_llm_usage_stub", lambda *args, **kw: None)
|
||||
monkeypatch.setattr(stove_match.stove_history, "add_ai_cost", lambda *args, **kw: None)
|
||||
monkeypatch.setattr(stove_match.gateway, "_price", lambda *args: {"price_rub": 1.0})
|
||||
async def stream(*args):
|
||||
yield {"delta": '[{"index":0,"code":"17.4.05.01-0051"}]'}
|
||||
yield {"usage": {"input_tokens": 50, "output_tokens": 10}}
|
||||
monkeypatch.setattr(stove_match.gateway, "_provider_stream", stream)
|
||||
result = asyncio.run(stove_match.fill(_prices(), key_id=1, budget=300, deadline=__import__('time').monotonic()+10, request_id="rid"))
|
||||
assert result["lines"][0]["code"] == "17.4.05.01-0051"
|
||||
assert result["lines"][0]["price"] == 26.08
|
||||
assert saved[0]["code"] == "17.4.05.01-0051"
|
||||
|
||||
|
||||
def test_out_of_list_code_is_missing_and_not_cached(monkeypatch):
|
||||
saved = []
|
||||
monkeypatch.setattr(stove_match.stove_cache, "match_get", lambda key: None)
|
||||
monkeypatch.setattr(stove_match.stove_cache, "match_put", lambda key, **kw: saved.append(kw))
|
||||
monkeypatch.setattr(stove_match, "_candidates", lambda *args: [_candidate()])
|
||||
monkeypatch.setattr(stove_match, "_profile_chain", lambda: [SimpleNamespace(name="glm", model="mock")])
|
||||
monkeypatch.setattr(stove_match, "_reserve", lambda *args: 42)
|
||||
monkeypatch.setattr(stove_match.db, "settle_llm_usage_stub", lambda *args, **kw: None)
|
||||
monkeypatch.setattr(stove_match.stove_history, "add_ai_cost", lambda *args, **kw: None)
|
||||
monkeypatch.setattr(stove_match.gateway, "_price", lambda *args: {"price_rub": 1.0})
|
||||
async def stream(*args):
|
||||
yield {"delta": '[{"index":0,"code":"invented"}]'}
|
||||
yield {"usage": {"input_tokens": 50, "output_tokens": 10}}
|
||||
monkeypatch.setattr(stove_match.gateway, "_provider_stream", stream)
|
||||
result = asyncio.run(stove_match.fill(_prices(), key_id=1, budget=300, deadline=__import__('time').monotonic()+10, request_id="rid"))
|
||||
assert result["lines"][0]["code"] is None
|
||||
assert saved == []
|
||||
Reference in New Issue
Block a user