Skip to content

Commit

Permalink
Merge pull request #2301 from Agenta-AI/fix/org-and-wrk-not-needed
Browse files Browse the repository at this point in the history
[Fix] - `organization_id` and `workspace_id` not required to manage `applications`
  • Loading branch information
mmabrouk authored Nov 25, 2024
2 parents 35dd4fc + 525d77c commit 0d53b97
Show file tree
Hide file tree
Showing 5 changed files with 27 additions and 152 deletions.
28 changes: 7 additions & 21 deletions agenta-backend/agenta_backend/routers/app_router.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,9 +50,7 @@
if isCloudEE():
from agenta_backend.commons.services import db_manager_ee
from agenta_backend.commons.services.selectors import (
get_user_own_org,
get_user_org_and_workspace_id,
get_org_default_workspace,
) # noqa pylint: disable-all
from agenta_backend.commons.utils.permissions import (
check_action_access,
Expand Down Expand Up @@ -220,9 +218,6 @@ async def create_app(
Permission.CREATE_APPLICATION,
)

if payload.workspace_id is None:
payload.workspace_id = request.state.workspace_id

try:
user_org_workspace_data = await get_user_org_and_workspace_id(
request.state.user_id
Expand All @@ -235,7 +230,7 @@ async def create_app(

has_permission = await check_rbac_permission(
user_org_workspace_data=user_org_workspace_data,
project_id=payload.project_id or request.state.project_id,
project_id=request.state.project_id,
permission=Permission.CREATE_APPLICATION,
)
logger.debug(
Expand All @@ -252,8 +247,7 @@ async def create_app(

app_db = await db_manager.create_app_and_envs(
payload.app_name,
project_id=payload.project_id or request.state.project_id,
workspace_id=payload.workspace_id,
project_id=request.state.project_id,
)
return CreateAppOutput(app_id=str(app_db.id), app_name=str(app_db.app_name))
except Exception as e:
Expand Down Expand Up @@ -310,18 +304,16 @@ async def update_app(
async def list_apps(
request: Request,
app_name: Optional[str] = None,
workspace_id: Optional[str] = None,
) -> List[App]:
"""
Retrieve a list of apps filtered by app_name and org_id.
Retrieve a list of apps filtered by app_name.
Args:
app_name (Optional[str]): The name of the app to filter by.
org_id (Optional[str]): The ID of the organization to filter by.
stoken_session (SessionContainer): The session container.
Returns:
List[App]: A list of apps filtered by app_name and org_id.
List[App]: A list of apps filtered by app_name.
Raises:
HTTPException: If there was an error retrieving the list of apps.
Expand All @@ -331,7 +323,6 @@ async def list_apps(
project_id=request.state.project_id,
user_uid=request.state.user_id,
app_name=app_name,
workspace_id=workspace_id,
)
return apps
except Exception as e:
Expand Down Expand Up @@ -491,12 +482,9 @@ async def create_app_and_variant_from_template(
)

logger.debug("Step 3: Checking user has permission to create app")
project = await db_manager_ee.get_project_by_workspace(
workspace_id=payload.workspace_id
)
has_permission = await check_rbac_permission(
user_org_workspace_data=user_org_workspace_data,
project_id=str(project.id),
project_id=request.state.project_id,
permission=Permission.CREATE_APPLICATION,
)
logger.debug(
Expand All @@ -518,8 +506,7 @@ async def create_app_and_variant_from_template(
app_name = payload.app_name.lower()
app = await db_manager.fetch_app_by_name_and_parameters(
app_name,
workspace_id=payload.workspace_id,
project_id=payload.project_id or request.state.project_id,
project_id=request.state.project_id,
)
if app is not None:
raise Exception(
Expand All @@ -542,8 +529,7 @@ async def create_app_and_variant_from_template(
app = await db_manager.create_app_and_envs(
app_name=app_name,
template_id=str(template_db.id),
project_id=payload.project_id or request.state.project_id,
workspace_id=payload.workspace_id,
project_id=request.state.project_id,
)

logger.debug(
Expand Down
22 changes: 3 additions & 19 deletions agenta-backend/agenta_backend/services/db_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -730,7 +730,6 @@ async def create_app_and_envs(
app_name: str,
template_id: Optional[str] = None,
project_id: Optional[str] = None,
workspace_id: Optional[str] = None,
) -> AppDB:
"""
Create a new app with the given name and organization ID.
Expand All @@ -747,10 +746,6 @@ async def create_app_and_envs(
ValueError: If an app with the same name already exists.
"""

if isCloudEE():
project = await db_manager_ee.get_project_by_workspace(workspace_id)
project_id = str(project.id)

app = await fetch_app_by_name_and_parameters(
app_name=app_name, project_id=project_id
)
Expand Down Expand Up @@ -1213,7 +1208,6 @@ async def list_apps(
project_id: str,
user_uid: str,
app_name: Optional[str] = None,
workspace_id: Optional[str] = None,
):
"""
Lists all the unique app names and their IDs from the database
Expand All @@ -1233,13 +1227,10 @@ async def list_apps(

elif isCloudEE():
if isCloudEE():
project = await db_manager_ee.get_project_by_workspace(
workspace_id=workspace_id
)
user_org_workspace_data = await get_user_org_and_workspace_id(user_uid) # type: ignore
has_permission = await check_rbac_permission( # type: ignore
user_org_workspace_data=user_org_workspace_data,
project_id=str(project.id),
project_id=project_id,
permission=Permission.VIEW_APPLICATION, # type: ignore
)
logger.debug(f"User has Permission to list apps: {has_permission}")
Expand All @@ -1251,7 +1242,7 @@ async def list_apps(

async with engine.session() as session:
result = await session.execute(
select(AppDB).filter_by(project_id=project.id)
select(AppDB).filter_by(project_id=project_id)
)
apps = result.unique().scalars().all()
return [converters.app_db_to_pydantic(app) for app in apps]
Expand Down Expand Up @@ -2785,26 +2776,19 @@ async def update_app_variant(

async def fetch_app_by_name_and_parameters(
app_name: str,
workspace_id: Optional[str] = None,
project_id: Optional[str] = None,
):
"""Fetch an app by its name and project identifier.
Args:
app_name (str): The name of the app
workspace_id (str, optional): The ID of the workspace. Defaults to None.
project_id (str, optional): The ID of the project. Defaults to None.
Returns:
AppDB: the instance of the app
"""

if not project_id and (isCloudEE() and workspace_id is not None):
project = await db_manager_ee.get_project_by_workspace(workspace_id)
project_id = str(project.id) if project else None

if project_id is None:
raise ValueError("Either workspace_id or project_id must be provided.")
raise ValueError("project_id must be provided.")

async with engine.session() as session:
query = select(AppDB).filter_by(
Expand Down
55 changes: 4 additions & 51 deletions agenta-cli/agenta/cli/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,16 +80,11 @@ def cli():
@click.command()
@click.option("--app-name", "--app_name", default=None)
@click.option("--backend-host", "backend_host", default=None)
@click.option(
"--organisation-name",
"organisation_name",
default=None,
help="The name of the organisation",
)
def init(app_name: str, backend_host: str, organisation_name: str):
init_option = "Blank App" if backend_host != "" and app_name != "" else ""
def init(app_name: str, backend_host: str):
"""Initialize a new Agenta app with the template files."""

init_option = "Blank App" if backend_host != "" and app_name != "" else ""

api_key = os.getenv("AGENTA_API_KEY")

if not app_name:
Expand Down Expand Up @@ -151,51 +146,9 @@ def init(app_name: str, backend_host: str, organisation_name: str):
api_key=api_key if where_question == "On agenta cloud" else "",
)

# list of user organizations
user_organizations = []

# validate the api key if it is provided
if where_question == "On agenta cloud":
try:
key_prefix = api_key.split(".")[0]
client.validate_api_key(key_prefix=key_prefix)
except Exception as ex:
click.echo(
click.style(
f"Error: Unable to validate API key.\nError: {ex}", fg="red"
)
)
sys.exit(1)
# Make request to fetch user organizations after api key validation
try:
organizations = client.list_organizations()
if len(organizations) >= 1:
user_organizations = organizations
except Exception as ex:
click.echo(click.style(f"Error: {ex}", fg="red"))
sys.exit(1)

organization = None
organization_choices = {}
if where_question == "On agenta cloud":
if not organisation_name:
organization_choices = {
f"{org.name}": org for org in user_organizations
}
which_organization = questionary.select(
"Which organization do you want to create the app for?",
choices=list(organization_choices.keys()),
).ask()
organisation_name = which_organization

organization = organization_choices.get(organisation_name)

# Get app_id after creating new app in the backend server
try:
app_id = client.apps.create_app(
app_name=app_name,
organization_id=organization.id if organization else None,
).app_id
app_id = client.apps.create_app(app_name=app_name).app_id
except Exception as ex:
click.echo(click.style(f"Error: {ex}", fg="red"))
sys.exit(1)
Expand Down
Loading

0 comments on commit 0d53b97

Please sign in to comment.