Skip to content
This repository was archived by the owner on Jun 5, 2025. It is now read-only.

feat: initial work on endpoints for creating/updating workspace config #1107

Merged
merged 23 commits into from
Mar 5, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
7cd8ec5
feat: initial work on endpoints for creating/updating
alex-mcgovern Feb 19, 2025
b0141ab
Merge branch 'main' of github.com:stacklok/codegate into feat/configu…
alex-mcgovern Feb 19, 2025
57ec255
fix: return newly created `FullWorkspace` from POST /api/v1/workspaces
alex-mcgovern Feb 19, 2025
cd83f56
formatting
alex-mcgovern Feb 19, 2025
efbfa64
test: create workspace with config happy path
alex-mcgovern Feb 19, 2025
7e91e5e
Merge branch 'main' of github.com:stacklok/codegate into feat/configu…
alex-mcgovern Feb 19, 2025
358f7e5
Merge branch 'main' of github.com:stacklok/codegate into feat/configu…
alex-mcgovern Feb 20, 2025
af7251d
1 db per test
alex-mcgovern Feb 20, 2025
b87c276
test: basic happy path test for create/update workspace config
alex-mcgovern Feb 21, 2025
033e16b
Merge branch 'main' of github.com:stacklok/codegate into feat/configu…
alex-mcgovern Feb 21, 2025
37f7e78
fix failing test
alex-mcgovern Feb 21, 2025
56cc0de
chore: fmt pass
alex-mcgovern Feb 21, 2025
1a69daf
fix: internal server error when no config passed
alex-mcgovern Feb 21, 2025
7de81b5
tidy up
alex-mcgovern Feb 21, 2025
36a9551
test: more integration tests
alex-mcgovern Mar 4, 2025
2a50d9f
chore: tidy ups
alex-mcgovern Mar 4, 2025
76bb197
Merge branch 'main' of github.com:stacklok/codegate into feat/configu…
alex-mcgovern Mar 4, 2025
3b4787d
chore: revert openapi changes
alex-mcgovern Mar 4, 2025
d329538
lint fixes
alex-mcgovern Mar 4, 2025
bb4f838
Merge branch 'main' into feat/configure-workspace-endpoint
alex-mcgovern Mar 4, 2025
e5eb6b4
remove manual rollbacks, ensure re-raising all exceptions
alex-mcgovern Mar 4, 2025
7bcab23
Merge branch 'main' of github.com:stacklok/codegate into feat/configu…
alex-mcgovern Mar 4, 2025
baa7aa6
Merge branch 'main' into feat/configure-workspace-endpoint
alex-mcgovern Mar 5, 2025
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
2 changes: 1 addition & 1 deletion api/openapi.json
Original file line number Diff line number Diff line change
Expand Up @@ -2030,4 +2030,4 @@
}
}
}
}
}
68 changes: 46 additions & 22 deletions src/codegate/api/v1.py
Original file line number Diff line number Diff line change
Expand Up @@ -248,22 +248,18 @@ async def activate_workspace(request: v1_models.ActivateWorkspaceRequest, status

@v1.post("/workspaces", tags=["Workspaces"], generate_unique_id_function=uniq_name, status_code=201)
async def create_workspace(
request: v1_models.CreateOrRenameWorkspaceRequest,
) -> v1_models.Workspace:
request: v1_models.FullWorkspace,
) -> v1_models.FullWorkspace:
"""Create a new workspace."""
if request.rename_to is not None:
return await rename_workspace(request)
return await create_new_workspace(request)


async def create_new_workspace(
request: v1_models.CreateOrRenameWorkspaceRequest,
) -> v1_models.Workspace:
# Input validation is done in the model
try:
_ = await wscrud.add_workspace(request.name)
except AlreadyExistsError:
raise HTTPException(status_code=409, detail="Workspace already exists")
custom_instructions = request.config.custom_instructions if request.config else None
muxing_rules = request.config.muxing_rules if request.config else None

workspace_row, mux_rules = await wscrud.add_workspace(
request.name, custom_instructions, muxing_rules
)
except crud.WorkspaceNameAlreadyInUseError:
raise HTTPException(status_code=409, detail="Workspace name already in use")
except ValidationError:
raise HTTPException(
status_code=400,
Expand All @@ -277,18 +273,40 @@ async def create_new_workspace(
except Exception:
raise HTTPException(status_code=500, detail="Internal server error")

return v1_models.Workspace(name=request.name, is_active=False)
return v1_models.FullWorkspace(
name=workspace_row.name,
config=v1_models.WorkspaceConfig(
custom_instructions=workspace_row.custom_instructions or "",
muxing_rules=[mux_models.MuxRule.from_db_mux_rule(mux_rule) for mux_rule in mux_rules],
),
)


async def rename_workspace(
request: v1_models.CreateOrRenameWorkspaceRequest,
) -> v1_models.Workspace:
@v1.put(
"/workspaces/{workspace_name}",
tags=["Workspaces"],
generate_unique_id_function=uniq_name,
status_code=201,
)
async def update_workspace(
workspace_name: str,
request: v1_models.FullWorkspace,
) -> v1_models.FullWorkspace:
"""Update a workspace."""
try:
_ = await wscrud.rename_workspace(request.name, request.rename_to)
custom_instructions = request.config.custom_instructions if request.config else None
muxing_rules = request.config.muxing_rules if request.config else None

workspace_row, mux_rules = await wscrud.update_workspace(
workspace_name,
request.name,
custom_instructions,
muxing_rules,
)
except crud.WorkspaceDoesNotExistError:
raise HTTPException(status_code=404, detail="Workspace does not exist")
except AlreadyExistsError:
raise HTTPException(status_code=409, detail="Workspace already exists")
except crud.WorkspaceNameAlreadyInUseError:
raise HTTPException(status_code=409, detail="Workspace name already in use")
except ValidationError:
raise HTTPException(
status_code=400,
Expand All @@ -302,7 +320,13 @@ async def rename_workspace(
except Exception:
raise HTTPException(status_code=500, detail="Internal server error")

return v1_models.Workspace(name=request.rename_to, is_active=False)
return v1_models.FullWorkspace(
name=workspace_row.name,
config=v1_models.WorkspaceConfig(
custom_instructions=workspace_row.custom_instructions or "",
muxing_rules=[mux_models.MuxRule.from_db_mux_rule(mux_rule) for mux_rule in mux_rules],
),
)


@v1.delete(
Expand Down
9 changes: 1 addition & 8 deletions src/codegate/api/v1_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ def from_db_workspaces(


class WorkspaceConfig(pydantic.BaseModel):
system_prompt: str
custom_instructions: str

muxing_rules: List[mux_models.MuxRule]

Expand All @@ -72,13 +72,6 @@ class FullWorkspace(pydantic.BaseModel):
config: Optional[WorkspaceConfig] = None


class CreateOrRenameWorkspaceRequest(FullWorkspace):
# If set, rename the workspace to this name. Note that
# the 'name' field is still required and the workspace
# workspace must exist.
rename_to: Optional[str] = None


class ActivateWorkspaceRequest(pydantic.BaseModel):
name: str

Expand Down
31 changes: 30 additions & 1 deletion src/codegate/db/connection.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@
from sqlalchemy import CursorResult, TextClause, event, text
from sqlalchemy.engine import Engine
from sqlalchemy.exc import IntegrityError, OperationalError
from sqlalchemy.ext.asyncio import create_async_engine
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine
from sqlalchemy.orm import sessionmaker

from codegate.db.fim_cache import FimCache
from codegate.db.models import (
Expand Down Expand Up @@ -1025,6 +1026,34 @@ async def get_distance_to_persona(
return persona_distance[0]


class DbTransaction:
def __init__(self):
self._session = None

async def __aenter__(self):
self._session = sessionmaker(
bind=DbCodeGate()._async_db_engine,
class_=AsyncSession,
expire_on_commit=False,
)()
await self._session.begin()
return self

async def __aexit__(self, exc_type, exc_val, exc_tb):
if exc_type:
await self._session.rollback()
raise exc_val
else:
await self._session.commit()
await self._session.close()

async def commit(self):
await self._session.commit()

async def rollback(self):
await self._session.rollback()


def init_db_sync(db_path: Optional[str] = None):
"""DB will be initialized in the constructor in case it doesn't exist."""
current_dir = Path(__file__).parent
Expand Down
5 changes: 1 addition & 4 deletions src/codegate/pipeline/cli/commands.py
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,6 @@ def help(self) -> str:


class CodegateCommandSubcommand(CodegateCommand):

@property
@abstractmethod
def subcommands(self) -> Dict[str, Callable[[List[str]], Awaitable[str]]]:
Expand Down Expand Up @@ -174,7 +173,6 @@ async def run(self, args: List[str]) -> str:


class Workspace(CodegateCommandSubcommand):

def __init__(self):
self.workspace_crud = crud.WorkspaceCrud()

Expand Down Expand Up @@ -258,7 +256,7 @@ async def _rename_workspace(self, flags: Dict[str, str], args: List[str]) -> str
)

try:
await self.workspace_crud.rename_workspace(old_workspace_name, new_workspace_name)
await self.workspace_crud.update_workspace(old_workspace_name, new_workspace_name)
except crud.WorkspaceDoesNotExistError:
return f"Workspace **{old_workspace_name}** does not exist"
except AlreadyExistsError:
Expand Down Expand Up @@ -410,7 +408,6 @@ def help(self) -> str:


class CustomInstructions(CodegateCommandSubcommand):

def __init__(self):
self.workspace_crud = crud.WorkspaceCrud()

Expand Down
Loading