Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
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
92 changes: 73 additions & 19 deletions cloud_pipelines_backend/projects/api_routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,9 @@
- GET /api/projects/{project_id} -- one project, with resource counts.
- PATCH /api/projects/{project_id} -- edit name, description or data.
- DELETE /api/projects/{project_id} -- hard delete, cascading resources.
- GET /api/users/me/projects -- projects I created or contributed to.
- PUT /api/projects/{project_id}/contributors/me -- record my contribution.
- GET /api/projects/{project_id}/contributors -- list the creator and contributors.
- GET /api/projects/{project_id}/runs -- runs submitted for this project.
- POST /api/projects/{project_id}/resources/ -- attach a resource.
- GET /api/projects/{project_id}/resources/ -- list them, filtered and paged.
Expand Down Expand Up @@ -196,6 +199,17 @@ class ProjectResponse(ProjectSummaryResponse):
somewhere to go."""


class ProjectListQuery(pydantic.BaseModel):
page_size: int = pydantic.Field(default=20, ge=1, le=100)
page_token: str | None = None
created_by: str | None = None
workspace_id: str | None = None


class ProjectContributorsResponse(pydantic.BaseModel):
contributors: list[str]


class ProjectListResponse(pydantic.BaseModel):
projects: list[ProjectSummaryResponse]
total_count: int
Expand Down Expand Up @@ -623,33 +637,25 @@ def create_project(
# A new project has no resources, so `{}` without a query.
return _to_project_response(project=project, resource_counts={})

@router.get(f"{_PROJECTS_BASE}/", tags=[_TAG], description=_PUBLIC_READ_POLICY)
def list_projects(
session: SessionDep,
user_details: UserDep,
page_size: int = fastapi.Query(default=20, ge=1, le=100),
page_token: str | None = fastapi.Query(default=None),
created_by: str | None = fastapi.Query(default=None),
workspace_id: str | None = fastapi.Query(default=None),
def _project_page(
session: orm.Session,
query: ProjectListQuery,
*,
contributed_by: str | None = None,
) -> ProjectListResponse:
"""Every project, most recently updated first.

Unfiltered by default -- there is no implicit created-by-me scope. `created_by` and
`workspace_id` narrow it and compose with AND.
"""
_authenticated_user(user_details)
# `is not None`, not truthiness: `?page_token=` present and empty is a malformed token.
cursor = (
_decode_cursor(page_token=page_token, timestamp_field="updated_at")
if page_token is not None
_decode_cursor(page_token=query.page_token, timestamp_field="updated_at")
if query.page_token is not None
else None
)
page = project_service.list_projects(
session=session,
page_size=page_size,
page_size=query.page_size,
cursor=cursor,
created_by=created_by,
workspace_id=workspace_id,
created_by=query.created_by,
workspace_id=query.workspace_id,
contributed_by=contributed_by,
)
counts = project_service.count_resources(
session=session,
Expand All @@ -672,6 +678,54 @@ def list_projects(
),
)

@router.get(f"{_PROJECTS_BASE}/", tags=[_TAG], description=_PUBLIC_READ_POLICY)
def list_projects(
session: SessionDep,
user_details: UserDep,
query: Annotated[ProjectListQuery, fastapi.Query()],
) -> ProjectListResponse:
"""All projects, optionally filtered by creator and workspace."""
_authenticated_user(user_details)
return _project_page(session, query)

@router.get("/api/users/me/projects", tags=[_TAG])
def list_my_projects(
session: SessionDep,
user_details: UserDep,
query: Annotated[ProjectListQuery, fastapi.Query()],
) -> ProjectListResponse:
"""Projects the signed-in person created or contributed to."""
return _project_page(
session, query, contributed_by=_authenticated_user(user_details)
)

@router.put(
f"{_PROJECTS_BASE}/{{project_id}}/contributors/me",
status_code=status.HTTP_204_NO_CONTENT,
dependencies=write_dependencies,
tags=[_TAG],
)
def record_contributor(
project_id: str, session: SessionDep, user_details: UserDep
) -> None:
"""Remember the signed-in person's contribution to this project."""
user_id = _authenticated_user(user_details, required_permissions=("write",))
project_service.record_contributor(
session=session, project_id=project_id, user_id=user_id
)

@router.get(f"{_PROJECTS_BASE}/{{project_id}}/contributors", tags=[_TAG])
def list_contributors(
project_id: str, session: SessionDep, user_details: UserDep
) -> ProjectContributorsResponse:
"""The creator and others who have contributed, including people who are offline."""
_authenticated_user(user_details)
return ProjectContributorsResponse(
contributors=project_service.list_contributors(
session=session, project_id=project_id
)
)

@router.get(
f"{_PROJECTS_BASE}/{{project_id}}",
tags=[_TAG],
Expand Down
21 changes: 20 additions & 1 deletion cloud_pipelines_backend/projects/db_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
existing database and alters nothing else -- which is also why no column here can be added to a
table that already ships, and why an index added later also needs `create_indexes_added_later`.

Every table carries two JSON columns: `data` is the client's, stored opaquely and never
Workspaces, projects and resources carry two JSON columns: `data` is the client's, stored opaquely and never
inspected here, and `extra_data` is a backend-only escape hatch that stays off the HTTP contract
in both directions.

Expand Down Expand Up @@ -185,6 +185,25 @@ class Project(bts._TableBase):
)


class ProjectContributor(bts._TableBase):
"""A person who contributed to a project. Its creator is already recorded on the project."""

__tablename__ = "project_contributor"

project_id: orm.Mapped[bts.IdType] = orm.mapped_column(
sql.String(_ID_LENGTH),
sql.ForeignKey(
Project.id, ondelete="CASCADE", name="fk_project_contributor_project_id"
),
primary_key=True,
)
user_id: orm.Mapped[str] = orm.mapped_column(primary_key=True)

__table_args__ = (
sql.Index("ix_project_contributor_user_project", user_id, project_id),
)


class ProjectResource(bts._TableBase):
"""One thing attached to a project: a document, or a reference to something external."""

Expand Down
65 changes: 62 additions & 3 deletions cloud_pipelines_backend/projects/services.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
import pydantic
import sqlalchemy as sql
from sqlalchemy import orm
from sqlalchemy.dialects import mysql, sqlite

from .. import api_server_sql
from .. import filter_query_models
Expand Down Expand Up @@ -600,22 +601,75 @@ def get_project(
raise errors.ProjectNotFoundError(f"Project {project_id!r} was not found.")
return project

def record_contributor(
self, *, session: orm.Session, project_id: str, user_id: str
) -> None:
"""Record the caller once, even if two tabs contribute concurrently."""
contributors = db_models.ProjectContributor
project = db_models.Project
with session.begin():
# Selecting from the parent keeps a racing delete from creating an orphan,
# even on SQLite connections with foreign-key enforcement disabled.
source = sql.select(project.id, sql.literal(user_id)).where(
project.id == project_id
)
columns = ["project_id", "user_id"]
if session.get_bind().dialect.name == "sqlite":
statement = (
sqlite.insert(contributors)
.from_select(columns, source)
.on_conflict_do_nothing(index_elements=["project_id", "user_id"])
)
else:
statement = (
mysql.insert(contributors)
.from_select(columns, source)
.on_duplicate_key_update(user_id=user_id)
)
result = session.execute(statement)
if result.rowcount == 0:
# A repeated contribution and a missing project can both affect zero rows.
self.get_project(session=session, project_id=project_id)

def list_contributors(self, *, session: orm.Session, project_id: str) -> list[str]:
project = self.get_project(session=session, project_id=project_id)
names = set(
session.scalars(
sql.select(db_models.ProjectContributor.user_id).where(
db_models.ProjectContributor.project_id == project_id
)
)
)
if project.created_by:
names.add(project.created_by)
return sorted(names)

def list_projects(
self,
*,
session: orm.Session,
page_size: int,
contributed_by: str | None = None,
cursor: tuple[datetime.datetime, str] | None = None,
created_by: str | None = None,
workspace_id: str | None = None,
) -> Page[db_models.Project]:
"""A page of projects, most recently updated first.

Returns **every** project, not the caller's: `created_by` is attribution, not access
control. The keyset runs on `updated_at`, which a `PATCH` moves, so a walk is not a
snapshot.
Filters apply to both the total and the rows. The personal view includes the
project creator even for projects created before contributions were recorded.
"""
filters = []
if contributed_by is not None:
contributed_ids = sql.select(db_models.ProjectContributor.project_id).where(
db_models.ProjectContributor.user_id == contributed_by
)
filters.append(
sql.or_(
db_models.Project.created_by == contributed_by,
db_models.Project.id.in_(contributed_ids),
)
)
if workspace_id is not None:
filters.append(db_models.Project.workspace_id == workspace_id)
if created_by is not None:
Expand Down Expand Up @@ -718,6 +772,11 @@ def delete_project(
db_models.ProjectResource.project_id == project_id
)
)
session.execute(
sql.delete(db_models.ProjectContributor).where(
db_models.ProjectContributor.project_id == project_id
)
)
session.delete(project)
return counts

Expand Down
74 changes: 74 additions & 0 deletions tests/projects/test_project_api_routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -750,3 +750,77 @@ def test_they_can_still_read(
self, no_write_client: fastapi.testclient.TestClient
) -> None:
assert no_write_client.get("/api/projects/").status_code == 200


class TestProjectContributors:
def test_personal_list_includes_created_and_contributed_projects(
self,
client: fastapi.testclient.TestClient,
other_user_client: fastapi.testclient.TestClient,
) -> None:
shared = create_project(client, name="Shared", workspace_id=SANDBOX)
create_project(client, name="Other", workspace_id=SANDBOX)
own = create_project(other_user_client, name="Own", workspace_id=INTERNAL)
base = f"/api/projects/{shared['id']}"
mine = "/api/users/me/projects"

assert other_user_client.get(base).status_code == 200
assert [p["id"] for p in other_user_client.get(mine).json()["projects"]] == [
own["id"]
]
assert client.get(base + "/contributors").json() == {
"contributors": [DEFAULT_USER]
}

for writer in (client, other_user_client, other_user_client):
assert writer.put(base + "/contributors/me").status_code == 204
assert client.get(base + "/contributors").json() == {
"contributors": sorted([DEFAULT_USER, OTHER_USER])
}
page = other_user_client.get(mine, params={"page_size": 1}).json()
assert page["total_count"] == 2
following = other_user_client.get(
mine, params={"page_size": 1, "page_token": page["next_page_token"]}
).json()
assert following["next_page_token"] is None
assert {p["id"] for p in page["projects"] + following["projects"]} == {
own["id"],
shared["id"],
}
filtered = other_user_client.get(
mine, params={"workspace_id": SANDBOX, "created_by": DEFAULT_USER}
).json()
assert filtered["total_count"] == 1
assert [p["id"] for p in filtered["projects"]] == [shared["id"]]
assert filtered["projects"][0]["created_by"] == DEFAULT_USER
assert (
other_user_client.get(
"/api/projects/", params={"created_by": OTHER_USER}
).json()["total_count"]
== 1
)

def test_recording_obeys_write_permissions_and_project_deletion(
self,
client: fastapi.testclient.TestClient,
other_user_client: fastapi.testclient.TestClient,
no_write_client: fastapi.testclient.TestClient,
read_only_client: fastapi.testclient.TestClient,
session: orm.Session,
) -> None:
project = create_project(client)
base = f"/api/projects/{project['id']}"
own_contribution = base + "/contributors/me"
assert no_write_client.put(own_contribution).status_code == 403
assert read_only_client.put(own_contribution).status_code == 503
assert other_user_client.put(own_contribution).status_code == 204
assert client.delete(base).status_code == 200
assert other_user_client.put(own_contribution).status_code == 404
assert client.get(base + "/contributors").status_code == 404
assert (
other_user_client.get("/api/users/me/projects").json()["total_count"] == 0
)
assert (
session.get(db_models.ProjectContributor, (project["id"], OTHER_USER))
is None
)
Loading