π OpenHands: AI-Driven Development
Refactor: Github Service (#6580)
Rohit Malhotra4adef574c0cb
diff --git a/frontend/src/api/github.ts b/frontend/src/api/github.tsindex c69ca870d7..4b83229f3e 100644--- a/frontend/src/api/github.ts+++ b/frontend/src/api/github.ts@@ -14,7 +14,7 @@ export const retrieveGitHubAppRepositories = async (per_page = 30,) => {const installationId = installations[installationIndex];- const response = await openHands.get<GitHubAppRepository>(+ const response = await openHands.get<GitHubRepository[]>("/api/github/repositories",{params: {@@ -26,7 +26,11 @@ export const retrieveGitHubAppRepositories = async (},);- const link = response.headers.link ?? "";+ const link =+ response.data.length > 0 && response.data[0].link_header+ ? response.data[0].link_header+ : "";+const nextPage = extractNextPageFromLink(link);let nextInstallation: number | null;@@ -39,7 +43,7 @@ export const retrieveGitHubAppRepositories = async (}return {- data: response.data.repositories,+ data: response.data,nextPage,installationIndex: nextInstallation,};@@ -64,7 +68,10 @@ export const retrieveGitHubUserRepositories = async (},);- const link = response.headers.link ?? "";+ const link =+ response.data.length > 0 && response.data[0].link_header+ ? response.data[0].link_header+ : "";const nextPage = extractNextPageFromLink(link);return { data: response.data, nextPage };diff --git a/frontend/src/api/open-hands.ts b/frontend/src/api/open-hands.tsindex ea796b822c..92da6c4d29 100644--- a/frontend/src/api/open-hands.ts+++ b/frontend/src/api/open-hands.ts@@ -297,7 +297,7 @@ class OpenHands {query: string,per_page = 5,): Promise<GitHubRepository[]> {- const response = await openHands.get<{ items: GitHubRepository[] }>(+ const response = await openHands.get<GitHubRepository[]>("/api/github/search/repositories",{params: {@@ -307,7 +307,7 @@ class OpenHands {},);- return response.data.items;+ return response.data;}static async getTrajectory(diff --git a/frontend/src/types/github.d.ts b/frontend/src/types/github.d.tsindex cb432961eb..36ccb3ee74 100644--- a/frontend/src/types/github.d.ts+++ b/frontend/src/types/github.d.ts@@ -17,10 +17,7 @@ interface GitHubRepository {id: number;full_name: string;stargazers_count?: number;-}--interface GitHubAppRepository {- repositories: GitHubRepository[];+ link_header?: string;}interface GitHubCommit {diff --git a/openhands/server/data_models/gh_types.py b/openhands/server/data_models/gh_types.pynew file mode 100644index 0000000000..e6b67392bc--- /dev/null+++ b/openhands/server/data_models/gh_types.py@@ -0,0 +1,17 @@+from pydantic import BaseModel+++class GitHubUser(BaseModel):+ id: int+ login: str+ avatar_url: str+ company: str | None = None+ name: str | None = None+ email: str | None = None+++class GitHubRepository(BaseModel):+ id: int+ full_name: str+ stargazers_count: int | None = None+ link_header: str | None = Nonediff --git a/openhands/server/listen.py b/openhands/server/listen.pyindex bb37909eb2..d195f8bce5 100644--- a/openhands/server/listen.py+++ b/openhands/server/listen.py@@ -5,7 +5,6 @@ from openhands.server.listen_socket import siofrom openhands.server.middleware import (AttachConversationMiddleware,CacheControlMiddleware,- GitHubTokenMiddleware,InMemoryRateLimiter,LocalhostCORSMiddleware,RateLimitMiddleware,@@ -29,6 +28,5 @@ base_app.add_middleware(rate_limiter=InMemoryRateLimiter(requests=10, seconds=1),)base_app.middleware('http')(AttachConversationMiddleware(base_app))-base_app.middleware('http')(GitHubTokenMiddleware(base_app))app = socketio.ASGIApp(sio, other_asgi_app=base_app)diff --git a/openhands/server/middleware.py b/openhands/server/middleware.pyindex ac7a480837..6b71721ae2 100644--- a/openhands/server/middleware.py+++ b/openhands/server/middleware.py@@ -12,7 +12,6 @@ from starlette.requests import Request as StarletteRequestfrom starlette.types import ASGIAppfrom openhands.server import shared-from openhands.server.auth import get_user_idfrom openhands.server.types import SessionMiddlewareInterface@@ -181,21 +180,3 @@ class AttachConversationMiddleware(SessionMiddlewareInterface):await self._detach_session(request)return response---class GitHubTokenMiddleware(SessionMiddlewareInterface):- def __init__(self, app):- self.app = app-- async def __call__(self, request: Request, call_next: Callable):- settings_store = await shared.SettingsStoreImpl.get_instance(- shared.config, get_user_id(request)- )- settings = await settings_store.load()-- if settings and settings.github_token:- request.state.github_token = settings.github_token.get_secret_value()- else:- request.state.github_token = None-- return await call_next(request)diff --git a/openhands/server/routes/github.py b/openhands/server/routes/github.pyindex d92105419e..6ab9882fe3 100644--- a/openhands/server/routes/github.py+++ b/openhands/server/routes/github.py@@ -1,25 +1,16 @@-from fastapi import APIRouter, Depends, HTTPException, Request, status+from fastapi import APIRouter, Dependsfrom fastapi.responses import JSONResponse-from openhands.server.auth import get_github_token, get_user_id+from openhands.server.auth import get_user_id+from openhands.server.data_models.gh_types import GitHubRepository, GitHubUserfrom openhands.server.services.github_service import GitHubServicefrom openhands.server.shared import server_config+from openhands.server.types import GhAuthenticationError, GHUnknownExceptionfrom openhands.utils.import_utils import get_implapp = APIRouter(prefix='/api/github')-def require_github_token(request: Request):- github_token = get_github_token(request)- if not github_token:- raise HTTPException(- status_code=status.HTTP_401_UNAUTHORIZED,- detail='Missing GitHub token',- )-- return github_token--GithubServiceImpl = get_impl(GitHubService, server_config.github_service_class)@@ -29,32 +20,70 @@ async def get_github_repositories(per_page: int = 10,sort: str = 'pushed',installation_id: int | None = None,- github_token: str = Depends(require_github_token),github_user_id: str | None = Depends(get_user_id),):- client = GithubServiceImpl(github_token, github_user_id)- return await client.fetch_response(- 'get_repositories', page, per_page, sort, installation_id- )+ client = GithubServiceImpl(github_user_id)+ try:+ repos: list[GitHubRepository] = await client.get_repositories(+ page, per_page, sort, installation_id+ )+ return repos++ except GhAuthenticationError as e:+ return JSONResponse(+ content=str(e),+ status_code=401,+ )++ except GHUnknownException as e:+ return JSONResponse(+ content=str(e),+ status_code=500,+ )@app.get('/user')async def get_github_user(- github_token: str = Depends(require_github_token),github_user_id: str | None = Depends(get_user_id),):- client = GithubServiceImpl(github_token, github_user_id)- return await client.fetch_response('get_user')+ client = GithubServiceImpl(github_user_id)+ try:+ user: GitHubUser = await client.get_user()+ return user++ except GhAuthenticationError as e:+ return JSONResponse(+ content=str(e),+ status_code=401,+ )++ except GHUnknownException as e:+ return JSONResponse(+ content=str(e),+ status_code=500,+ )@app.get('/installations')async def get_github_installation_ids(- github_token: str = Depends(require_github_token),github_user_id: str | None = Depends(get_user_id),):- client = GithubServiceImpl(github_token, github_user_id)- installations_ids = await client.get_installation_ids()- return JSONResponse(content=installations_ids)+ client = GithubServiceImpl(github_user_id)+ try:+ installations_ids: list[int] = await client.get_installation_ids()+ return installations_ids++ except GhAuthenticationError as e:+ return JSONResponse(+ content=str(e),+ status_code=401,+ )++ except GHUnknownException as e:+ return JSONResponse(+ content=str(e),+ status_code=500,+ )@app.get('/search/repositories')@@ -63,11 +92,23 @@ async def search_github_repositories(per_page: int = 5,sort: str = 'stars',order: str = 'desc',- github_token: str = Depends(require_github_token),github_user_id: str | None = Depends(get_user_id),):- client = GithubServiceImpl(github_token, github_user_id)- response = await client.search_repositories(query, per_page, sort, order)- json_response = JSONResponse(content=response.json())- response.close()- return json_response+ client = GithubServiceImpl(github_user_id)+ try:+ repos: list[GitHubRepository] = await client.search_repositories(+ query, per_page, sort, order+ )+ return repos++ except GhAuthenticationError as e:+ return JSONResponse(+ content=str(e),+ status_code=401,+ )++ except GHUnknownException as e:+ return JSONResponse(+ content=str(e),+ status_code=500,+ )diff --git a/openhands/server/routes/settings.py b/openhands/server/routes/settings.pyindex aa538f5e3d..aaad862e81 100644--- a/openhands/server/routes/settings.py+++ b/openhands/server/routes/settings.py@@ -46,14 +46,13 @@ async def store_settings(settings: POSTSettingsModel,) -> JSONResponse:# Check if token is valid+if settings.github_token:try:# We check if the token is valid by getting the user# If the token is invalid, this will raise an exception- github = GitHubService(settings.github_token, None)- response = await github.fetch_response('get_user')- if response.status_code != status.HTTP_200_OK:- raise Exception('Invalid Github Token')+ github = GitHubService(None)+ await github.validate_user(settings.github_token)except Exception as e:logger.warning(f'Invalid GitHub token: {e}')diff --git a/openhands/server/services/github_service.py b/openhands/server/services/github_service.pyindex dd11d17832..561733fba8 100644--- a/openhands/server/services/github_service.py+++ b/openhands/server/services/github_service.py@@ -1,21 +1,29 @@+from typing import Any+import httpx-import requests-from fastapi import Response-from fastapi.responses import JSONResponse-from openhands.server.shared import server_config-from openhands.server.types import AppMode-from openhands.utils.async_utils import call_sync_from_async+from openhands.server.data_models.gh_types import GitHubRepository, GitHubUser+from openhands.server.shared import SettingsStoreImpl, config, server_config+from openhands.server.types import AppMode, GhAuthenticationError, GHUnknownExceptionclass GitHubService:BASE_URL = 'https://api.github.com'- def __init__(self, token: str, user_id: str | None):- self.token = token+ def __init__(self, user_id: str | None):self.user_id = user_id+ self.token = ''++ async def _get_github_headers(self):+ """+ Retrieve the GH Token from settings store to construct the headers+ """++ settings_store = await SettingsStoreImpl.get_instance(config, self.user_id)+ settings = await settings_store.load()+ if settings and settings.github_token:+ self.token = settings.github_token.get_secret_value()- def _get_github_headers(self):return {'Authorization': f'Bearer {self.token}','Accept': 'application/vnd.github.v3+json',@@ -27,72 +35,99 @@ class GitHubService:async def _get_latest_token(self):pass- async def _fetch_data(self, url: str, params: dict | None = None) -> Response:+ async def _fetch_data(+ self, url: str, params: dict | None = None+ ) -> tuple[Any, dict]:try:async with httpx.AsyncClient() as client:- response = await client.get(- url, headers=self._get_github_headers(), params=params- )+ github_headers = await self._get_github_headers()+ response = await client.get(url, headers=github_headers, params=params)if server_config.app_mode == AppMode.SAAS and self._has_token_expired(response.status_code):await self._get_latest_token()+ github_headers = await self._get_github_headers()response = await client.get(- url, headers=self._get_github_headers(), params=params+ url, headers=github_headers, params=params)response.raise_for_status()- return response+ headers = {}+ if 'Link' in response.headers:+ headers['Link'] = response.headers['Link']- except httpx.HTTPStatusError as e:- status_code = e.response.status_code- error_detail = e.response.text+ return response.json(), headers- return httpx.Response(- status_code=status_code, json=f'GitHub API error: {error_detail}'- )- except httpx.HTTPError as e:- return httpx.Response(status_code=500, json=f'HTTP error: {str(e)}')+ except httpx.HTTPStatusError:+ raise GhAuthenticationError('Invalid Github token')++ except httpx.HTTPError:+ raise GHUnknownException('Unknown error')- async def get_user(self):+ async def get_user(self) -> GitHubUser:url = f'{self.BASE_URL}/user'- return await self._fetch_data(url)+ response, _ = await self._fetch_data(url)++ return GitHubUser(+ id=response.get('id'),+ login=response.get('login'),+ avatar_url=response.get('avatar_url'),+ company=response.get('company'),+ name=response.get('name'),+ email=response.get('email'),+ )++ async def validate_user(self, token) -> GitHubUser:+ self.token = token+ return await self.get_user()async def get_repositories(self, page: int, per_page: int, sort: str, installation_id: int | None- ):+ ) -> list[GitHubRepository]:params = {'page': str(page), 'per_page': str(per_page)}if installation_id:url = f'{self.BASE_URL}/user/installations/{installation_id}/repositories'+ response, headers = await self._fetch_data(url, params)+ response = response.get('repositories', [])else:url = f'{self.BASE_URL}/user/repos'params['sort'] = sort- return await self._fetch_data(url, params)+ response, headers = await self._fetch_data(url, params)++ next_link: str = headers.get('Link', '')+ repos = [+ GitHubRepository(+ id=repo.get('id'),+ full_name=repo.get('full_name'),+ stargazers_count=repo.get('stargazers_count'),+ link_header=next_link,+ )+ for repo in response+ ]+ return reposasync def get_installation_ids(self) -> list[int]:url = f'{self.BASE_URL}/user/installations'- response = await self._fetch_data(url)- data = response.json()- if not isinstance(data, dict):- return []-- installations = data.get('installations', [])+ response, _ = await self._fetch_data(url)+ installations = response.get('installations', [])return [i['id'] for i in installations]async def search_repositories(self, query: str, per_page: int, sort: str, order: str- ):+ ) -> list[GitHubRepository]:url = f'{self.BASE_URL}/search/repositories'params = {'q': query, 'per_page': per_page, 'sort': sort, 'order': order}- return await call_sync_from_async(- requests.get, url, headers=self._get_github_headers(), params=params- )- async def fetch_response(self, method: str, *args, **kwargs):- response = await getattr(self, method)(*args, **kwargs)- json_response = JSONResponse(- content=response.json(), status_code=response.status_code- )- if 'Link' in response.headers:- json_response.headers['Link'] = response.headers['Link']- return json_response+ response, _ = await self._fetch_data(url, params)+ repos = response.get('items', [])++ repos = [+ GitHubRepository(+ id=repo.get('id'),+ full_name=repo.get('full_name'),+ stargazers_count=repo.get('stargazers_count'),+ )+ for repo in repos+ ]++ return reposdiff --git a/openhands/server/types.py b/openhands/server/types.pyindex 4c8c1dc96a..da115de8cd 100644--- a/openhands/server/types.py+++ b/openhands/server/types.py@@ -42,3 +42,15 @@ class LLMAuthenticationError(ValueError):"""Raised when there is an issue with LLM authentication."""pass+++class GhAuthenticationError(ValueError):+ """Raised when there is an issue with LLM authentication."""++ pass+++class GHUnknownException(ValueError):+ """Raised when there is an issue with LLM authentication."""++ pass