kodit 0.3.10__py3-none-any.whl → 0.3.12__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Potentially problematic release.
This version of kodit might be problematic. Click here for more details.
- kodit/_version.py +2 -2
- kodit/app.py +39 -19
- kodit/{infrastructure/indexing → application/services}/auto_indexing_service.py +9 -1
- kodit/application/services/code_indexing_application_service.py +16 -0
- kodit/application/services/sync_scheduler.py +4 -1
- kodit/config.py +22 -1
- kodit/domain/entities.py +5 -0
- kodit/domain/protocols.py +4 -0
- kodit/domain/services/index_query_service.py +5 -1
- kodit/domain/services/index_service.py +11 -0
- kodit/infrastructure/api/__init__.py +1 -0
- kodit/infrastructure/api/middleware/__init__.py +1 -0
- kodit/infrastructure/api/middleware/auth.py +34 -0
- kodit/infrastructure/api/v1/__init__.py +5 -0
- kodit/infrastructure/api/v1/dependencies.py +70 -0
- kodit/infrastructure/api/v1/routers/__init__.py +6 -0
- kodit/infrastructure/api/v1/routers/indexes.py +114 -0
- kodit/infrastructure/api/v1/routers/search.py +74 -0
- kodit/infrastructure/api/v1/schemas/__init__.py +25 -0
- kodit/infrastructure/api/v1/schemas/context.py +11 -0
- kodit/infrastructure/api/v1/schemas/index.py +101 -0
- kodit/infrastructure/api/v1/schemas/search.py +219 -0
- kodit/infrastructure/bm25/local_bm25_repository.py +4 -4
- kodit/infrastructure/bm25/vectorchord_bm25_repository.py +4 -1
- kodit/infrastructure/embedding/embedding_providers/local_embedding_provider.py +2 -9
- kodit/infrastructure/embedding/embedding_providers/openai_embedding_provider.py +4 -10
- kodit/infrastructure/sqlalchemy/index_repository.py +29 -0
- kodit/infrastructure/ui/progress.py +43 -0
- kodit/utils/dump_openapi.py +37 -0
- {kodit-0.3.10.dist-info → kodit-0.3.12.dist-info}/METADATA +16 -1
- {kodit-0.3.10.dist-info → kodit-0.3.12.dist-info}/RECORD +34 -21
- {kodit-0.3.10.dist-info → kodit-0.3.12.dist-info}/WHEEL +0 -0
- {kodit-0.3.10.dist-info → kodit-0.3.12.dist-info}/entry_points.txt +0 -0
- {kodit-0.3.10.dist-info → kodit-0.3.12.dist-info}/licenses/LICENSE +0 -0
kodit/_version.py
CHANGED
kodit/app.py
CHANGED
|
@@ -4,11 +4,15 @@ from collections.abc import AsyncIterator
|
|
|
4
4
|
from contextlib import asynccontextmanager
|
|
5
5
|
|
|
6
6
|
from asgi_correlation_id import CorrelationIdMiddleware
|
|
7
|
-
from fastapi import FastAPI
|
|
7
|
+
from fastapi import FastAPI, Response
|
|
8
|
+
from fastapi.responses import RedirectResponse
|
|
8
9
|
|
|
10
|
+
from kodit._version import version
|
|
11
|
+
from kodit.application.services.auto_indexing_service import AutoIndexingService
|
|
9
12
|
from kodit.application.services.sync_scheduler import SyncSchedulerService
|
|
10
13
|
from kodit.config import AppContext
|
|
11
|
-
from kodit.infrastructure.
|
|
14
|
+
from kodit.infrastructure.api.v1.routers import indexes_router, search_router
|
|
15
|
+
from kodit.infrastructure.api.v1.schemas.context import AppLifespanState
|
|
12
16
|
from kodit.mcp import mcp
|
|
13
17
|
from kodit.middleware import ASGICancelledErrorMiddleware, logging_middleware
|
|
14
18
|
|
|
@@ -18,7 +22,7 @@ _sync_scheduler_service: SyncSchedulerService | None = None
|
|
|
18
22
|
|
|
19
23
|
|
|
20
24
|
@asynccontextmanager
|
|
21
|
-
async def app_lifespan(_: FastAPI) -> AsyncIterator[
|
|
25
|
+
async def app_lifespan(_: FastAPI) -> AsyncIterator[AppLifespanState]:
|
|
22
26
|
"""Manage application lifespan for auto-indexing and sync."""
|
|
23
27
|
global _auto_indexing_service, _sync_scheduler_service # noqa: PLW0603
|
|
24
28
|
|
|
@@ -42,7 +46,7 @@ async def app_lifespan(_: FastAPI) -> AsyncIterator[None]:
|
|
|
42
46
|
interval_seconds=app_context.periodic_sync.interval_seconds
|
|
43
47
|
)
|
|
44
48
|
|
|
45
|
-
yield
|
|
49
|
+
yield AppLifespanState(app_context=app_context)
|
|
46
50
|
|
|
47
51
|
# Stop services
|
|
48
52
|
if _sync_scheduler_service:
|
|
@@ -57,33 +61,49 @@ mcp_http_app = mcp.http_app(transport="http", path="/")
|
|
|
57
61
|
|
|
58
62
|
|
|
59
63
|
@asynccontextmanager
|
|
60
|
-
async def combined_lifespan(app: FastAPI) -> AsyncIterator[
|
|
61
|
-
"""Combine app and MCP lifespans."""
|
|
64
|
+
async def combined_lifespan(app: FastAPI) -> AsyncIterator[AppLifespanState]:
|
|
65
|
+
"""Combine app and MCP lifespans, yielding state from app_lifespan."""
|
|
62
66
|
async with (
|
|
63
|
-
app_lifespan(app),
|
|
67
|
+
app_lifespan(app) as app_state,
|
|
64
68
|
mcp_sse_app.router.lifespan_context(app),
|
|
65
69
|
mcp_http_app.router.lifespan_context(app),
|
|
66
70
|
):
|
|
67
|
-
yield
|
|
71
|
+
yield app_state
|
|
68
72
|
|
|
69
73
|
|
|
70
|
-
app = FastAPI(
|
|
74
|
+
app = FastAPI(
|
|
75
|
+
title="kodit API",
|
|
76
|
+
lifespan=combined_lifespan,
|
|
77
|
+
responses={
|
|
78
|
+
500: {"description": "Internal server error"},
|
|
79
|
+
},
|
|
80
|
+
description="""
|
|
81
|
+
This is the REST API for the Kodit server. Please refer to the
|
|
82
|
+
[Kodit documentation](https://docs.helix.ml/kodit/) for more information.
|
|
83
|
+
""",
|
|
84
|
+
version=version,
|
|
85
|
+
)
|
|
71
86
|
|
|
72
|
-
# Add middleware
|
|
73
|
-
app.middleware("http")(logging_middleware)
|
|
74
|
-
app.add_middleware(CorrelationIdMiddleware)
|
|
87
|
+
# Add middleware. Remember, last runs first. Order is important.
|
|
88
|
+
app.middleware("http")(logging_middleware) # Then always log
|
|
89
|
+
app.add_middleware(CorrelationIdMiddleware) # Add correlation id first.
|
|
75
90
|
|
|
76
91
|
|
|
77
|
-
@app.get("/")
|
|
78
|
-
async def root() ->
|
|
79
|
-
"""
|
|
80
|
-
return
|
|
92
|
+
@app.get("/", include_in_schema=False)
|
|
93
|
+
async def root() -> RedirectResponse:
|
|
94
|
+
"""Redirect to the API documentation."""
|
|
95
|
+
return RedirectResponse(url="/docs")
|
|
81
96
|
|
|
82
97
|
|
|
83
98
|
@app.get("/healthz")
|
|
84
|
-
async def healthz() ->
|
|
99
|
+
async def healthz() -> Response:
|
|
85
100
|
"""Return a health check for the kodit API."""
|
|
86
|
-
return
|
|
101
|
+
return Response(status_code=200)
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
# Include API routers
|
|
105
|
+
app.include_router(indexes_router)
|
|
106
|
+
app.include_router(search_router)
|
|
87
107
|
|
|
88
108
|
|
|
89
109
|
# Add mcp routes last, otherwise previous routes aren't added
|
|
@@ -93,4 +113,4 @@ app.mount("/mcp", mcp_http_app)
|
|
|
93
113
|
|
|
94
114
|
# Wrap the entire app with ASGI middleware after all routes are added to suppress
|
|
95
115
|
# CancelledError at the ASGI level
|
|
96
|
-
|
|
116
|
+
ASGICancelledErrorMiddleware(app)
|
|
@@ -11,6 +11,7 @@ from kodit.application.factories.code_indexing_factory import (
|
|
|
11
11
|
create_code_indexing_application_service,
|
|
12
12
|
)
|
|
13
13
|
from kodit.config import AppContext
|
|
14
|
+
from kodit.infrastructure.ui.progress import create_log_progress_callback
|
|
14
15
|
|
|
15
16
|
|
|
16
17
|
class AutoIndexingService:
|
|
@@ -50,13 +51,20 @@ class AutoIndexingService:
|
|
|
50
51
|
|
|
51
52
|
for source in sources:
|
|
52
53
|
try:
|
|
54
|
+
# Only auto-index a source if it is new
|
|
55
|
+
if await service.does_index_exist(source):
|
|
56
|
+
self.log.info("Index already exists, skipping", source=source)
|
|
57
|
+
continue
|
|
58
|
+
|
|
53
59
|
self.log.info("Auto-indexing source", source=source)
|
|
54
60
|
|
|
55
61
|
# Create index
|
|
56
62
|
index = await service.create_index_from_uri(source)
|
|
57
63
|
|
|
58
64
|
# Run indexing (without progress callback for background mode)
|
|
59
|
-
await service.run_index(
|
|
65
|
+
await service.run_index(
|
|
66
|
+
index, progress_callback=create_log_progress_callback()
|
|
67
|
+
)
|
|
60
68
|
|
|
61
69
|
self.log.info("Successfully auto-indexed source", source=source)
|
|
62
70
|
|
|
@@ -53,6 +53,13 @@ class CodeIndexingApplicationService:
|
|
|
53
53
|
self.session = session
|
|
54
54
|
self.log = structlog.get_logger(__name__)
|
|
55
55
|
|
|
56
|
+
async def does_index_exist(self, uri: str) -> bool:
|
|
57
|
+
"""Check if an index exists for a source."""
|
|
58
|
+
# Check if index already exists
|
|
59
|
+
sanitized_uri, _ = self.index_domain_service.sanitize_uri(uri)
|
|
60
|
+
existing_index = await self.index_repository.get_by_uri(sanitized_uri)
|
|
61
|
+
return existing_index is not None
|
|
62
|
+
|
|
56
63
|
async def create_index_from_uri(
|
|
57
64
|
self, uri: str, progress_callback: ProgressCallback | None = None
|
|
58
65
|
) -> Index:
|
|
@@ -382,3 +389,12 @@ class CodeIndexingApplicationService:
|
|
|
382
389
|
)
|
|
383
390
|
|
|
384
391
|
await reporter.done("text_embeddings")
|
|
392
|
+
|
|
393
|
+
async def delete_index(self, index: Index) -> None:
|
|
394
|
+
"""Delete an index."""
|
|
395
|
+
# Delete the index from the domain
|
|
396
|
+
await self.index_domain_service.delete_index(index)
|
|
397
|
+
|
|
398
|
+
# Delete index from the database
|
|
399
|
+
await self.index_repository.delete(index)
|
|
400
|
+
await self.session.commit()
|
|
@@ -14,6 +14,7 @@ from kodit.config import AppContext
|
|
|
14
14
|
from kodit.domain.services.index_query_service import IndexQueryService
|
|
15
15
|
from kodit.infrastructure.indexing.fusion_service import ReciprocalRankFusionService
|
|
16
16
|
from kodit.infrastructure.sqlalchemy.index_repository import SqlAlchemyIndexRepository
|
|
17
|
+
from kodit.infrastructure.ui.progress import create_log_progress_callback
|
|
17
18
|
|
|
18
19
|
|
|
19
20
|
class SyncSchedulerService:
|
|
@@ -102,7 +103,9 @@ class SyncSchedulerService:
|
|
|
102
103
|
source=str(index.source.working_copy.remote_uri),
|
|
103
104
|
)
|
|
104
105
|
|
|
105
|
-
await service.run_index(
|
|
106
|
+
await service.run_index(
|
|
107
|
+
index, progress_callback=create_log_progress_callback()
|
|
108
|
+
)
|
|
106
109
|
success_count += 1
|
|
107
110
|
|
|
108
111
|
self.log.info(
|
kodit/config.py
CHANGED
|
@@ -5,13 +5,15 @@ from __future__ import annotations
|
|
|
5
5
|
import asyncio
|
|
6
6
|
from functools import wraps
|
|
7
7
|
from pathlib import Path
|
|
8
|
-
from typing import TYPE_CHECKING, Any, Literal, TypeVar
|
|
8
|
+
from typing import TYPE_CHECKING, Annotated, Any, Literal, TypeVar
|
|
9
9
|
|
|
10
10
|
import click
|
|
11
|
+
import structlog
|
|
11
12
|
from pydantic import BaseModel, Field, field_validator
|
|
12
13
|
from pydantic_settings import (
|
|
13
14
|
BaseSettings,
|
|
14
15
|
EnvSettingsSource,
|
|
16
|
+
NoDecode,
|
|
15
17
|
PydanticBaseSettingsSource,
|
|
16
18
|
SettingsConfigDict,
|
|
17
19
|
)
|
|
@@ -189,7 +191,26 @@ class AppContext(BaseSettings):
|
|
|
189
191
|
periodic_sync: PeriodicSyncConfig = Field(
|
|
190
192
|
default=PeriodicSyncConfig(), description="Periodic sync configuration"
|
|
191
193
|
)
|
|
194
|
+
api_keys: Annotated[list[str], NoDecode] = Field(
|
|
195
|
+
default_factory=list,
|
|
196
|
+
description="Comma-separated list of valid API keys (e.g. 'key1,key2')",
|
|
197
|
+
)
|
|
198
|
+
|
|
199
|
+
@field_validator("api_keys", mode="before")
|
|
200
|
+
@classmethod
|
|
201
|
+
def parse_api_keys(cls, v: Any) -> list[str]:
|
|
202
|
+
"""Parse API keys from CSV format."""
|
|
203
|
+
if v is None:
|
|
204
|
+
return []
|
|
205
|
+
if isinstance(v, list):
|
|
206
|
+
return v
|
|
207
|
+
if isinstance(v, str):
|
|
208
|
+
# Split by comma and strip whitespace
|
|
209
|
+
return [key.strip() for key in v.strip().split(",") if key.strip()]
|
|
210
|
+
return v
|
|
211
|
+
|
|
192
212
|
_db: Database | None = None
|
|
213
|
+
_log = structlog.get_logger(__name__)
|
|
193
214
|
|
|
194
215
|
def model_post_init(self, _: Any) -> None:
|
|
195
216
|
"""Post-initialization hook."""
|
kodit/domain/entities.py
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
"""Pure domain entities using Pydantic."""
|
|
2
2
|
|
|
3
|
+
import shutil
|
|
3
4
|
from dataclasses import dataclass
|
|
4
5
|
from datetime import datetime
|
|
5
6
|
from pathlib import Path
|
|
@@ -193,6 +194,10 @@ class WorkingCopy(BaseModel):
|
|
|
193
194
|
for file in self.files:
|
|
194
195
|
file.file_processing_status = FileProcessingStatus.CLEAN
|
|
195
196
|
|
|
197
|
+
def delete(self) -> None:
|
|
198
|
+
"""Delete the working copy."""
|
|
199
|
+
shutil.rmtree(self.cloned_path)
|
|
200
|
+
|
|
196
201
|
|
|
197
202
|
class Source(BaseModel):
|
|
198
203
|
"""Source domain entity."""
|
kodit/domain/protocols.py
CHANGED
|
@@ -63,4 +63,8 @@ class IndexQueryService:
|
|
|
63
63
|
|
|
64
64
|
async def get_snippets_by_ids(self, ids: list[int]) -> list[SnippetWithContext]:
|
|
65
65
|
"""Get snippets by their IDs."""
|
|
66
|
-
|
|
66
|
+
snippets = await self.index_repository.get_snippets_by_ids(ids)
|
|
67
|
+
|
|
68
|
+
# Return snippets in the same order as the ids
|
|
69
|
+
snippets.sort(key=lambda x: ids.index(x.snippet.id or 0))
|
|
70
|
+
return snippets
|
|
@@ -13,6 +13,7 @@ from kodit.domain.services.enrichment_service import EnrichmentDomainService
|
|
|
13
13
|
from kodit.domain.value_objects import (
|
|
14
14
|
EnrichmentIndexRequest,
|
|
15
15
|
EnrichmentRequest,
|
|
16
|
+
FileProcessingStatus,
|
|
16
17
|
LanguageMapping,
|
|
17
18
|
)
|
|
18
19
|
from kodit.infrastructure.cloning.git.working_copy import GitWorkingCopyProvider
|
|
@@ -103,6 +104,11 @@ class IndexDomainService:
|
|
|
103
104
|
files = index.source.working_copy.changed_files()
|
|
104
105
|
index.delete_snippets_for_files(files)
|
|
105
106
|
|
|
107
|
+
# Filter out deleted files - they don't exist on disk anymore
|
|
108
|
+
files = [
|
|
109
|
+
f for f in files if f.file_processing_status != FileProcessingStatus.DELETED
|
|
110
|
+
]
|
|
111
|
+
|
|
106
112
|
# Create a set of languages to extract snippets for
|
|
107
113
|
extensions = {file.extension() for file in files}
|
|
108
114
|
lang_files_map: dict[str, list[domain_entities.File]] = defaultdict(list)
|
|
@@ -290,3 +296,8 @@ class IndexDomainService:
|
|
|
290
296
|
continue
|
|
291
297
|
|
|
292
298
|
return working_copy
|
|
299
|
+
|
|
300
|
+
async def delete_index(self, index: domain_entities.Index) -> None:
|
|
301
|
+
"""Delete an index."""
|
|
302
|
+
# Delete the working copy
|
|
303
|
+
index.source.working_copy.delete()
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""API infrastructure modules."""
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""API middleware modules."""
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
"""API key-based authentication middleware for the REST API."""
|
|
2
|
+
|
|
3
|
+
from fastapi import Depends, HTTPException, Request, Security
|
|
4
|
+
from fastapi.security import APIKeyHeader
|
|
5
|
+
|
|
6
|
+
api_key_header_value = APIKeyHeader(
|
|
7
|
+
name="x-api-key",
|
|
8
|
+
auto_error=False,
|
|
9
|
+
description="API key for authentication (only if set in environmental variables)",
|
|
10
|
+
scheme_name="Header (X-API-KEY)",
|
|
11
|
+
)
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def valid_keys(request: Request) -> list[str]:
|
|
15
|
+
"""Get the valid keys from the app context."""
|
|
16
|
+
if not hasattr(request.state, "app_context"):
|
|
17
|
+
raise HTTPException(status_code=500, detail="App context not found")
|
|
18
|
+
app_context = request.state.app_context
|
|
19
|
+
return app_context.api_keys
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def api_key_auth(
|
|
23
|
+
api_key: str = Security(api_key_header_value),
|
|
24
|
+
valid_keys: list[str] = Depends(valid_keys),
|
|
25
|
+
) -> None:
|
|
26
|
+
"""Validate the API key."""
|
|
27
|
+
if len(valid_keys) == 0:
|
|
28
|
+
return
|
|
29
|
+
# Check if the API key is valid
|
|
30
|
+
if api_key not in valid_keys:
|
|
31
|
+
raise HTTPException(
|
|
32
|
+
status_code=401,
|
|
33
|
+
detail="Invalid API key",
|
|
34
|
+
)
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
"""FastAPI dependencies for the REST API."""
|
|
2
|
+
|
|
3
|
+
from collections.abc import AsyncGenerator
|
|
4
|
+
from typing import Annotated, cast
|
|
5
|
+
|
|
6
|
+
from fastapi import Depends, Request
|
|
7
|
+
from sqlalchemy.ext.asyncio import AsyncSession
|
|
8
|
+
|
|
9
|
+
from kodit.application.factories.code_indexing_factory import (
|
|
10
|
+
create_code_indexing_application_service,
|
|
11
|
+
)
|
|
12
|
+
from kodit.application.services.code_indexing_application_service import (
|
|
13
|
+
CodeIndexingApplicationService,
|
|
14
|
+
)
|
|
15
|
+
from kodit.config import AppContext
|
|
16
|
+
from kodit.domain.services.index_query_service import IndexQueryService
|
|
17
|
+
from kodit.infrastructure.indexing.fusion_service import ReciprocalRankFusionService
|
|
18
|
+
from kodit.infrastructure.sqlalchemy.index_repository import SqlAlchemyIndexRepository
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def get_app_context(request: Request) -> AppContext:
|
|
22
|
+
"""Get the app context dependency."""
|
|
23
|
+
app_context = cast("AppContext", request.state.app_context)
|
|
24
|
+
if app_context is None:
|
|
25
|
+
raise RuntimeError("App context not initialized")
|
|
26
|
+
return app_context
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
AppContextDep = Annotated[AppContext, Depends(get_app_context)]
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
async def get_db_session(
|
|
33
|
+
app_context: AppContextDep,
|
|
34
|
+
) -> AsyncGenerator[AsyncSession, None]:
|
|
35
|
+
"""Get database session dependency."""
|
|
36
|
+
db = await app_context.get_db()
|
|
37
|
+
async with db.session_factory() as session:
|
|
38
|
+
yield session
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
DBSessionDep = Annotated[AsyncSession, Depends(get_db_session)]
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
async def get_index_query_service(
|
|
45
|
+
session: DBSessionDep,
|
|
46
|
+
) -> IndexQueryService:
|
|
47
|
+
"""Get index query service dependency."""
|
|
48
|
+
return IndexQueryService(
|
|
49
|
+
index_repository=SqlAlchemyIndexRepository(session=session),
|
|
50
|
+
fusion_service=ReciprocalRankFusionService(),
|
|
51
|
+
)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
IndexQueryServiceDep = Annotated[IndexQueryService, Depends(get_index_query_service)]
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
async def get_indexing_app_service(
|
|
58
|
+
app_context: AppContextDep,
|
|
59
|
+
session: DBSessionDep,
|
|
60
|
+
) -> CodeIndexingApplicationService:
|
|
61
|
+
"""Get indexing application service dependency."""
|
|
62
|
+
return create_code_indexing_application_service(
|
|
63
|
+
app_context=app_context,
|
|
64
|
+
session=session,
|
|
65
|
+
)
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
IndexingAppServiceDep = Annotated[
|
|
69
|
+
CodeIndexingApplicationService, Depends(get_indexing_app_service)
|
|
70
|
+
]
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
"""Index management router for the REST API."""
|
|
2
|
+
|
|
3
|
+
from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException
|
|
4
|
+
|
|
5
|
+
from kodit.infrastructure.api.middleware.auth import api_key_auth
|
|
6
|
+
from kodit.infrastructure.api.v1.dependencies import (
|
|
7
|
+
IndexingAppServiceDep,
|
|
8
|
+
IndexQueryServiceDep,
|
|
9
|
+
)
|
|
10
|
+
from kodit.infrastructure.api.v1.schemas.index import (
|
|
11
|
+
IndexAttributes,
|
|
12
|
+
IndexCreateRequest,
|
|
13
|
+
IndexData,
|
|
14
|
+
IndexDetailResponse,
|
|
15
|
+
IndexListResponse,
|
|
16
|
+
IndexResponse,
|
|
17
|
+
)
|
|
18
|
+
|
|
19
|
+
router = APIRouter(
|
|
20
|
+
prefix="/api/v1/indexes",
|
|
21
|
+
tags=["indexes"],
|
|
22
|
+
dependencies=[Depends(api_key_auth)],
|
|
23
|
+
responses={
|
|
24
|
+
401: {"description": "Unauthorized"},
|
|
25
|
+
422: {"description": "Invalid request"},
|
|
26
|
+
},
|
|
27
|
+
)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
@router.get("")
|
|
31
|
+
async def list_indexes(
|
|
32
|
+
query_service: IndexQueryServiceDep,
|
|
33
|
+
) -> IndexListResponse:
|
|
34
|
+
"""List all indexes."""
|
|
35
|
+
indexes = await query_service.list_indexes()
|
|
36
|
+
return IndexListResponse(
|
|
37
|
+
data=[
|
|
38
|
+
IndexData(
|
|
39
|
+
type="index",
|
|
40
|
+
id=str(idx.id),
|
|
41
|
+
attributes=IndexAttributes(
|
|
42
|
+
created_at=idx.created_at,
|
|
43
|
+
updated_at=idx.updated_at,
|
|
44
|
+
uri=str(idx.source.working_copy.remote_uri),
|
|
45
|
+
),
|
|
46
|
+
)
|
|
47
|
+
for idx in indexes
|
|
48
|
+
]
|
|
49
|
+
)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
@router.post("", status_code=202)
|
|
53
|
+
async def create_index(
|
|
54
|
+
request: IndexCreateRequest,
|
|
55
|
+
background_tasks: BackgroundTasks,
|
|
56
|
+
app_service: IndexingAppServiceDep,
|
|
57
|
+
) -> IndexResponse:
|
|
58
|
+
"""Create a new index and start async indexing."""
|
|
59
|
+
# Create index using the application service
|
|
60
|
+
index = await app_service.create_index_from_uri(request.data.attributes.uri)
|
|
61
|
+
|
|
62
|
+
# Start async indexing in background
|
|
63
|
+
background_tasks.add_task(app_service.run_index, index)
|
|
64
|
+
|
|
65
|
+
return IndexResponse(
|
|
66
|
+
data=IndexData(
|
|
67
|
+
type="index",
|
|
68
|
+
id=str(index.id),
|
|
69
|
+
attributes=IndexAttributes(
|
|
70
|
+
created_at=index.created_at,
|
|
71
|
+
updated_at=index.updated_at,
|
|
72
|
+
uri=str(index.source.working_copy.remote_uri),
|
|
73
|
+
),
|
|
74
|
+
)
|
|
75
|
+
)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
@router.get("/{index_id}", responses={404: {"description": "Index not found"}})
|
|
79
|
+
async def get_index(
|
|
80
|
+
index_id: int,
|
|
81
|
+
query_service: IndexQueryServiceDep,
|
|
82
|
+
) -> IndexDetailResponse:
|
|
83
|
+
"""Get index details."""
|
|
84
|
+
index = await query_service.get_index_by_id(index_id)
|
|
85
|
+
if not index:
|
|
86
|
+
raise HTTPException(status_code=404, detail="Index not found")
|
|
87
|
+
|
|
88
|
+
return IndexDetailResponse(
|
|
89
|
+
data=IndexData(
|
|
90
|
+
type="index",
|
|
91
|
+
id=str(index.id),
|
|
92
|
+
attributes=IndexAttributes(
|
|
93
|
+
created_at=index.created_at,
|
|
94
|
+
updated_at=index.updated_at,
|
|
95
|
+
uri=str(index.source.working_copy.remote_uri),
|
|
96
|
+
),
|
|
97
|
+
),
|
|
98
|
+
)
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
@router.delete(
|
|
102
|
+
"/{index_id}", status_code=204, responses={404: {"description": "Index not found"}}
|
|
103
|
+
)
|
|
104
|
+
async def delete_index(
|
|
105
|
+
index_id: int,
|
|
106
|
+
query_service: IndexQueryServiceDep,
|
|
107
|
+
app_service: IndexingAppServiceDep,
|
|
108
|
+
) -> None:
|
|
109
|
+
"""Delete an index."""
|
|
110
|
+
index = await query_service.get_index_by_id(index_id)
|
|
111
|
+
if not index:
|
|
112
|
+
raise HTTPException(status_code=404, detail="Index not found")
|
|
113
|
+
|
|
114
|
+
await app_service.delete_index(index)
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
"""Search router for the REST API."""
|
|
2
|
+
|
|
3
|
+
from fastapi import APIRouter
|
|
4
|
+
|
|
5
|
+
from kodit.domain.value_objects import MultiSearchRequest, SnippetSearchFilters
|
|
6
|
+
from kodit.infrastructure.api.v1.dependencies import (
|
|
7
|
+
IndexingAppServiceDep,
|
|
8
|
+
)
|
|
9
|
+
from kodit.infrastructure.api.v1.schemas.search import (
|
|
10
|
+
SearchRequest,
|
|
11
|
+
SearchResponse,
|
|
12
|
+
SnippetAttributes,
|
|
13
|
+
SnippetData,
|
|
14
|
+
)
|
|
15
|
+
|
|
16
|
+
router = APIRouter(tags=["search"])
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
@router.post("/api/v1/search")
|
|
20
|
+
async def search_snippets(
|
|
21
|
+
request: SearchRequest,
|
|
22
|
+
app_service: IndexingAppServiceDep,
|
|
23
|
+
) -> SearchResponse:
|
|
24
|
+
"""Search code snippets with filters matching MCP tool."""
|
|
25
|
+
# Convert API request to domain request
|
|
26
|
+
domain_request = MultiSearchRequest(
|
|
27
|
+
keywords=request.data.attributes.keywords,
|
|
28
|
+
code_query=request.data.attributes.code,
|
|
29
|
+
text_query=request.data.attributes.text,
|
|
30
|
+
top_k=request.limit or 10,
|
|
31
|
+
filters=SnippetSearchFilters(
|
|
32
|
+
language=request.languages[0] if request.languages else None,
|
|
33
|
+
author=request.authors[0] if request.authors else None,
|
|
34
|
+
created_after=request.start_date,
|
|
35
|
+
created_before=request.end_date,
|
|
36
|
+
source_repo=request.sources[0] if request.sources else None,
|
|
37
|
+
file_path=request.file_patterns[0] if request.file_patterns else None,
|
|
38
|
+
)
|
|
39
|
+
if any(
|
|
40
|
+
[
|
|
41
|
+
request.languages,
|
|
42
|
+
request.authors,
|
|
43
|
+
request.start_date,
|
|
44
|
+
request.end_date,
|
|
45
|
+
request.sources,
|
|
46
|
+
request.file_patterns,
|
|
47
|
+
]
|
|
48
|
+
)
|
|
49
|
+
else None,
|
|
50
|
+
)
|
|
51
|
+
|
|
52
|
+
# Execute search using application service
|
|
53
|
+
results = await app_service.search(domain_request)
|
|
54
|
+
|
|
55
|
+
return SearchResponse(
|
|
56
|
+
data=[
|
|
57
|
+
SnippetData(
|
|
58
|
+
type="snippet",
|
|
59
|
+
id=result.id,
|
|
60
|
+
attributes=SnippetAttributes(
|
|
61
|
+
content=result.content,
|
|
62
|
+
created_at=result.created_at,
|
|
63
|
+
updated_at=result.created_at, # Use created_at as fallback
|
|
64
|
+
original_scores=result.original_scores,
|
|
65
|
+
source_uri=result.source_uri,
|
|
66
|
+
relative_path=result.relative_path,
|
|
67
|
+
language=result.language,
|
|
68
|
+
authors=result.authors,
|
|
69
|
+
summary=result.summary,
|
|
70
|
+
),
|
|
71
|
+
)
|
|
72
|
+
for result in results
|
|
73
|
+
]
|
|
74
|
+
)
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
"""JSON:API schemas for the REST API."""
|
|
2
|
+
|
|
3
|
+
from .index import (
|
|
4
|
+
IndexCreateRequest,
|
|
5
|
+
IndexDetailResponse,
|
|
6
|
+
IndexListResponse,
|
|
7
|
+
IndexResponse,
|
|
8
|
+
)
|
|
9
|
+
from .search import (
|
|
10
|
+
SearchRequest,
|
|
11
|
+
SearchResponse,
|
|
12
|
+
SearchResponseWithIncluded,
|
|
13
|
+
SnippetDetailResponse,
|
|
14
|
+
)
|
|
15
|
+
|
|
16
|
+
__all__ = [
|
|
17
|
+
"IndexCreateRequest",
|
|
18
|
+
"IndexDetailResponse",
|
|
19
|
+
"IndexListResponse",
|
|
20
|
+
"IndexResponse",
|
|
21
|
+
"SearchRequest",
|
|
22
|
+
"SearchResponse",
|
|
23
|
+
"SearchResponseWithIncluded",
|
|
24
|
+
"SnippetDetailResponse",
|
|
25
|
+
]
|