blob: 0ac6d15a35f9b41b3cb8310c46d2f416d587fb04 [file]
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
"""JSON API routes for llmao (STeVe-style module registration)."""
from __future__ import annotations
import functools
import logging
import asfquart
import asfquart.auth
from asfquart.auth import Requirements
from quart import jsonify, request
from llmao.auth import current_identity
from llmao.intent import UnknownHostError
from llmao.provisioning import HOST_HEADER, config_for_host, fetch_refusal, rental_name
from llmao.seam import AuthzError
APP = asfquart.APP
_LOGGER = logging.getLogger(__name__)
class HttpError(Exception):
"""Expected HTTP error from an API handler (not AuthzError)."""
def __init__(self, status: int, message: str):
super().__init__(message)
self.status = status
def _ok_extras(result) -> str:
"""Short success extras from a JSON-ish dict; never includes secrets."""
if not isinstance(result, dict):
return ""
parts = []
if result.get("host") is not None:
parts.append(f"host={result['host']}")
servers = result.get("servers")
if isinstance(servers, list):
models = ",".join(f"{s.get('name')}:{s.get('port')}" if isinstance(s, dict) else str(s) for s in servers)
parts.append(f"models={models}")
if result.get("project") is not None:
parts.append(f"project={result['project']}")
if "count" in result:
parts.append(f"count={result['count']}")
if "provisioned" in result:
parts.append(f"provisioned={result['provisioned']}")
return (" " + " ".join(parts)) if parts else ""
def api(fn):
"""JSON handlers: jsonify the return value; AuthzError → 403; else log + 500."""
def no_store(response):
"""Nothing this decorator returns may be stored by anything in between.
/vllm/config answers with a rental's own vLLM bearer and the fleet's
Hugging Face token. One choke point for every @api route, error
replies included: an error body names the host it was asked about.
"""
response.headers["Cache-Control"] = "no-store"
return response
def err(status, message):
body = {"error": {"message": message, "type": "llmao_error", "code": status}}
return no_store(jsonify(body)), status
@functools.wraps(fn)
async def wrapper(*args, **kwargs):
try:
result = await fn(*args, **kwargs)
except AuthzError as e:
_LOGGER.warning("%s: %s", fn.__name__, e)
return err(403, str(e))
except HttpError as e:
msg = f"{fn.__name__}: {e.status} {e}"
if e.status >= 500:
_LOGGER.error(msg)
else:
_LOGGER.warning(msg)
return err(e.status, str(e))
except Exception:
_LOGGER.exception("unhandled error in %s", fn.__name__)
return err(500, "internal error in gateway; check the server log")
if fn.__name__ == "healthz":
_LOGGER.debug("%s ok", fn.__name__)
else:
_LOGGER.info("%s ok%s", fn.__name__, _ok_extras(result))
return no_store(jsonify(result))
return wrapper
@APP.get("/healthz")
@api
async def healthz():
return {"status": "ok"}
@APP.get("/vllm/config")
@api
async def vllm_config():
"""JSON for the calling rental (docs/rental-protocol.md); the pieces are llmao/provisioning.py's."""
refusal = fetch_refusal(APP.cfg, request.headers.get("Authorization"))
if refusal:
raise HttpError(*refusal)
name = rental_name(
claimed=request.headers.get(HOST_HEADER),
remote_addr=request.remote_addr,
)
# Every fetch is recorded by name; whether the name is intended is the
# fleet's call, and a name nothing intends shows on the /models strip.
APP.provisioning.note(name)
approval = APP.fleet.approvals.get(name)
try:
return config_for_host(name, models=APP.models, cfg=APP.cfg, approved=approval and list(approval.models))
except UnknownHostError:
raise HttpError(404, f"unknown fleet host: {name}") from None
@APP.get("/v1/projects/<project>/usage")
@asfquart.auth.require
@api
async def project_usage(project: str):
seam = APP.seam
ident = await current_identity(APP.cfg)
rows = await seam.project_activity(ident, project)
total = round(sum(r.get("cost_usd", 0.0) for r in rows), 6)
return {
"project": project,
"entries": rows,
"total_cost_usd": total,
"count": len(rows),
}
@APP.get("/v1/projects/<project>/budget")
@asfquart.auth.require({Requirements.committer})
@api
async def project_budget(project: str):
seam = APP.seam
ident = await current_identity(APP.cfg)
info = await seam.team_status(ident, project)
if info is None:
return {"project": project, "provisioned": False}
return {
"project": project,
"provisioned": True,
"max_budget_usd": info.max_budget,
"spend_usd": info.spend,
"remaining_usd": round(max(0.0, info.max_budget - info.spend), 6),
}