Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: version endpoint #612

Merged
merged 10 commits into from
Jan 17, 2025
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions poetry.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ build = ">=1.0.0"
wheel = ">=0.40.0"
litellm = ">=1.52.11"
pytest-asyncio = "0.25.2"
llama_cpp_python = ">=0.3.2"
llama_cpp_python = "==0.3.5"
alex-mcgovern marked this conversation as resolved.
Show resolved Hide resolved
scikit-learn = ">=1.6.0"
python-dotenv = ">=1.0.1"

Expand Down
41 changes: 40 additions & 1 deletion src/codegate/server.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
import traceback
from typing import AsyncGenerator

import structlog
from fastapi import APIRouter, FastAPI, Request
from fastapi import APIRouter, Depends, FastAPI, HTTPException, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from starlette.middleware.errors import ServerErrorMiddleware
from httpx import AsyncClient, HTTPStatusError

from codegate import __description__, __version__
from codegate.dashboard.dashboard import dashboard_router
Expand All @@ -27,6 +29,23 @@ async def custom_error_handler(request, exc: Exception):
logger.error(traceback.print_list(extracted_traceback[-3:]))
return JSONResponse({"error": str(exc)}, status_code=500)

async def get_http_client() -> AsyncGenerator[AsyncClient, None]:
async with AsyncClient() as client:
yield client

async def fetch_latest_version(client: AsyncClient) -> str:
url = "https://api.github.com/repos/stacklok/codegate/releases/latest"
headers = {
"Accept": "application/vnd.github+json",
"X-GitHub-Api-Version": "2022-11-28"
}
try:
response = await client.get(url, headers=headers)
response.raise_for_status()
data = response.json()
return data.get("tag_name", "unknown")
except HTTPStatusError as e:
raise HTTPException(status_code=e.response.status_code, detail=str(e))

def init_app(pipeline_factory: PipelineFactory) -> FastAPI:
"""Create the FastAPI application."""
Expand Down Expand Up @@ -94,6 +113,26 @@ async def log_user_agent(request: Request, call_next):
async def health_check():
return {"status": "healthy"}

@system_router.get("/version")
async def version_check(client: AsyncClient = Depends(get_http_client)):
try:
latest_version = await fetch_latest_version(client)

# normalize the versions as github will return them with a 'v' prefix
current_version = __version__.lstrip('v')
latest_version_stripped = latest_version.lstrip('v')

is_latest: bool = latest_version_stripped == current_version

return {
"current_version": current_version,
"latest_version": latest_version_stripped,
"is_latest": is_latest,
}
except HTTPException as e:
return {"current_version": __version__, "latest_version": "unknown", "error": e.detail}


aponcedeleonch marked this conversation as resolved.
Show resolved Hide resolved
app.include_router(system_router)
app.include_router(dashboard_router)

Expand Down
15 changes: 15 additions & 0 deletions tests/test_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,21 @@ def test_health_check(test_client: TestClient) -> None:
assert response.status_code == 200
assert response.json() == {"status": "healthy"}

def test_version_endpoint(test_client: TestClient) -> None:
"""Test the version endpoint."""
response = test_client.get("/version")
assert response.status_code == 200

response_data = response.json()
assert "current_version" in response_data
assert isinstance(response_data["current_version"], str)

assert "latest_version" in response_data
assert isinstance(response_data["latest_version"], str)

assert "is_latest" in response_data
assert isinstance(response_data["is_latest"], bool)


@patch("codegate.pipeline.secrets.manager.SecretsManager")
@patch("codegate.server.ProviderRegistry")
Expand Down
Loading