LLM-Driven Extraction of Unstructured Data — Built for API Deployments & ETL Pipeline Workflows
Python ai-agentsdata-engineeringdocument-aigenerative-aiidpjson-extractionllmmcp-serverocrpdf-extractionprompt-engineeringstructured-output
from django.db import transaction
from rest_framework import serializers
from tenant_account_v2.models import OrganizationMember
from utils.user_context import UserContext
from permissions.roles import ResourceRole
class AddOwnerSerializer(serializers.Serializer):
"""Validate and add a user as an OWNER of the resource in context.
Context requires ``resource``. A user already holding VIEWER access is
promoted to OWNER.
"""
user_id = serializers.IntegerField()
def validate_user_id(self, value: int) -> int:
resource = self.context["resource"]
organization = UserContext.get_organization()
member = (
OrganizationMember.objects.filter(user__id=value, organization=organization)
.select_related("user")
.first()
)
if member is None:
raise serializers.ValidationError("User not found in your organization.")
# Service accounts are machine identities excluded from sharing/membership
# everywhere else (see ``compute_effective_members``); keep them out of
# ownership too.
if member.user.is_service_account:
raise serializers.ValidationError(
"Service accounts cannot be added as owners."
)
if resource.memberships.filter(user_id=value, role=ResourceRole.OWNER).exists():
raise serializers.ValidationError("User is already an owner.")
return value
def save(self, **kwargs) -> bool:
"""Promote a viewer or create the owner row; whether anything changed.
A concurrent request may have made the user an owner since validation.
"""
resource = self.context["resource"]
user_id = self.validated_data["user_id"]
with transaction.atomic():
# Reverse manager auto-scopes to this resource. Lock the user's row
# by key (a concurrent share/ may add, remove or recreate it);
# create one only when there is none, then lock what exists.
for _ in range(3):
row = (
resource.memberships.select_for_update()
.filter(user_id=user_id)
.first()
)
if row is not None:
if row.role == ResourceRole.OWNER:
return False
resource.memberships.filter(pk=row.pk).update(role=ResourceRole.OWNER)
return True
_, created = resource.memberships.get_or_create(
user_id=user_id, defaults={"role": ResourceRole.OWNER}
)
if created:
return True
raise serializers.ValidationError("Could not add the co-owner; please retry.")
class RemoveOwnerSerializer(serializers.Serializer):
"""Validate and remove an OWNER, guarding the last-owner invariant.
Context requires ``resource`` and ``user_to_remove``.
"""
def validate(self, attrs: dict) -> dict:
resource = self.context["resource"]
user = self.context["user_to_remove"]
if not resource.memberships.filter(user=user, role=ResourceRole.OWNER).exists():
raise serializers.ValidationError("User is not an owner of this resource.")
# Symmetric with ``AddOwnerSerializer``: a removed service-account owner
# can't be re-added, so block removal to avoid an irrecoverable state.
if user.is_service_account:
raise serializers.ValidationError(
"Service accounts cannot be removed as owners."
)
return attrs
def save(self, **kwargs) -> bool:
"""Remove the OWNER row; whether there was one to remove."""
resource = self.context["resource"]
user = self.context["user_to_remove"]
with transaction.atomic():
# Lock the OWNER membership rows themselves, not the resource row:
# the org-exit purge (``tenant_account_v2.signals``) guards the
# same last-owner invariant, and only a shared lock target
# serializes the two paths (ordered by pk to match its scan and
# avoid deadlocks). Materialised via ``list`` — a locked
# ``.count()`` silently drops FOR UPDATE.
owner_rows = list(
resource.memberships.select_for_update()
.filter(role=ResourceRole.OWNER)
.order_by("pk")
.values_list("pk", "user_id")
)
# The org-exit carve-out (spec §7.4) keeps a departed owner's row,
# so a surviving row may belong to an ex-member; only another LIVE
# owner justifies removal — mirrors the signal's liveness check.
live_user_ids = set(
OrganizationMember.objects.filter(
organization=UserContext.get_organization()
).values_list("user_id", flat=True)
)
if not any(uid != user.id and uid in live_user_ids for _, uid in owner_rows):
raise serializers.ValidationError(
"Cannot remove the last owner. Add another owner first."
)
deleted, _ = resource.memberships.filter(
user=user, role=ResourceRole.OWNER
).delete()
return deleted > 0