Publish frozen exercise releases and report whether they stay offerable.
Deploy Development / deploy (push) Successful in 1m12s
Test Suite / pytest-backend (push) Failing after 30s
Test Suite / lint-backend (push) Successful in 0s
Test Suite / build-frontend (push) Successful in 16s
Test Suite / k6 /health Baseline (push) Successful in 35s
Test Suite / playwright-tests (push) Failing after 7m42s
Deploy Development / deploy (push) Successful in 1m12s
Test Suite / pytest-backend (push) Failing after 30s
Test Suite / lint-backend (push) Successful in 0s
Test Suite / build-frontend (push) Successful in 16s
Test Suite / k6 /health Baseline (push) Successful in 35s
Test Suite / playwright-tests (push) Failing after 7m42s
Recipients can ask whether a released exercise is still offerable. Archiving or removing the source stops new offers; the frozen copy stays fetchable until withdrawal. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
b537750671
commit
fe3633ba8b
21 files changed
+3862
-12
No files matched your search
@@ -0,0 +1,460 @@
|
||||
"""Distributionsfreigabe: Maschinenabruf und Redaktion.
|
||||
|
||||
Maschinenabruf authentifiziert allein über den Distributions-Schlüssel.
|
||||
# ACCESS_LAYER exempt: kein Trainer-Mandant; Kanal kommt aus der Anbindung.
|
||||
Die Redaktions- und Verwaltungsrouten nutzen TenantContext.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, Header, HTTPException, Query
|
||||
from fastapi.responses import FileResponse, Response
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from club_tenancy import is_superadmin
|
||||
from db import get_cursor, get_db
|
||||
from distribution_contract import (
|
||||
InvalidCursor,
|
||||
cursor_secret,
|
||||
decode_cursor,
|
||||
distribution_enabled,
|
||||
)
|
||||
from distribution_service import (
|
||||
backlog_count,
|
||||
confirm_draft,
|
||||
create_draft,
|
||||
issue_key,
|
||||
list_changes,
|
||||
load_asset,
|
||||
load_availability,
|
||||
load_manifest,
|
||||
overview,
|
||||
resolve_bearer,
|
||||
retire_release,
|
||||
update_draft,
|
||||
withdraw_release,
|
||||
)
|
||||
from tenant_context import TenantContext, get_tenant_context
|
||||
|
||||
router = APIRouter(prefix="/api/distribution/v1", tags=["distribution"])
|
||||
editorial = APIRouter(tags=["distribution-editorial"])
|
||||
|
||||
NO_STORE = {"Cache-Control": "private, no-store"}
|
||||
|
||||
|
||||
def _machine(authorization: Optional[str]):
|
||||
if not distribution_enabled():
|
||||
raise HTTPException(status_code=404, detail="Nicht gefunden", headers=NO_STORE)
|
||||
if not authorization or not authorization.lower().startswith("bearer "):
|
||||
raise HTTPException(
|
||||
status_code=401,
|
||||
detail={"code": "invalid_key", "message": "Schlüssel ungültig."},
|
||||
headers=NO_STORE,
|
||||
)
|
||||
token = authorization.split(" ", 1)[1].strip()
|
||||
held: Optional[HTTPException] = None
|
||||
binding = None
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
try:
|
||||
binding = resolve_bearer(cur, token)
|
||||
except HTTPException as exc:
|
||||
held = exc
|
||||
if held is not None:
|
||||
held.headers = {**(held.headers or {}), **NO_STORE}
|
||||
raise held
|
||||
return binding
|
||||
|
||||
|
||||
def _superadmin(tenant: TenantContext) -> None:
|
||||
if not is_superadmin(tenant.global_role):
|
||||
raise HTTPException(status_code=403, detail="Nur Superadmins dürfen die Distribution verwalten.")
|
||||
|
||||
|
||||
class PublisherBody(BaseModel):
|
||||
name: str = Field(min_length=1, max_length=200)
|
||||
kind: str
|
||||
club_id: Optional[int] = None
|
||||
|
||||
|
||||
class RecipientBody(BaseModel):
|
||||
name: str = Field(min_length=1, max_length=200)
|
||||
|
||||
|
||||
class RelationshipBody(BaseModel):
|
||||
publisher_id: str
|
||||
recipient_id: str
|
||||
|
||||
|
||||
class BindingBody(BaseModel):
|
||||
recipient_id: str
|
||||
name: str = Field(min_length=1, max_length=200)
|
||||
|
||||
|
||||
class KeyBody(BaseModel):
|
||||
expires_at: Optional[str] = None
|
||||
|
||||
|
||||
class ProfileBody(BaseModel):
|
||||
profile_id: int
|
||||
|
||||
|
||||
class ExerciseAssignBody(BaseModel):
|
||||
exercise_id: int
|
||||
|
||||
|
||||
class SuspendBody(BaseModel):
|
||||
kind: str
|
||||
id: str
|
||||
|
||||
|
||||
class DraftBody(BaseModel):
|
||||
publisher_id: str
|
||||
recipient_id: str
|
||||
cut: Optional[dict] = None
|
||||
|
||||
|
||||
class CutBody(BaseModel):
|
||||
cut: dict
|
||||
|
||||
|
||||
class ReasonBody(BaseModel):
|
||||
reason_code: str
|
||||
|
||||
|
||||
@router.get("/changes")
|
||||
def get_changes(
|
||||
cursor: Optional[str] = None,
|
||||
limit: Optional[int] = Query(default=None),
|
||||
authorization: Optional[str] = Header(default=None),
|
||||
):
|
||||
binding = _machine(authorization)
|
||||
if limit is None:
|
||||
limit = 50
|
||||
elif limit < 1 or limit > 100:
|
||||
raise HTTPException(status_code=400, detail={"code": "invalid_limit", "message": "limit ist 1 bis 100."}, headers=NO_STORE)
|
||||
try:
|
||||
seq = decode_cursor(cursor_secret(), binding["recipient_id"], cursor)
|
||||
except InvalidCursor:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail={"code": "invalid_cursor", "message": "Cursor ungültig."},
|
||||
headers=NO_STORE,
|
||||
)
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
payload = list_changes(cur, binding["recipient_id"], seq, limit)
|
||||
return Response(
|
||||
content=__import__("json").dumps(payload, ensure_ascii=False, separators=(",", ":")),
|
||||
media_type="application/json",
|
||||
headers=NO_STORE,
|
||||
)
|
||||
|
||||
|
||||
@router.get("/exercises/{source_id}/availability")
|
||||
def get_availability(source_id: str, authorization: Optional[str] = Header(default=None)):
|
||||
binding = _machine(authorization)
|
||||
held: Optional[HTTPException] = None
|
||||
payload = None
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
try:
|
||||
payload = load_availability(cur, binding["recipient_id"], source_id)
|
||||
except HTTPException as exc:
|
||||
held = exc
|
||||
if held is not None:
|
||||
held.headers = {**(held.headers or {}), **NO_STORE}
|
||||
raise held
|
||||
return Response(
|
||||
content=__import__("json").dumps(payload, ensure_ascii=False, separators=(",", ":")),
|
||||
media_type="application/json",
|
||||
headers=NO_STORE,
|
||||
)
|
||||
|
||||
|
||||
@router.get("/releases/{release_id}")
|
||||
def get_release(release_id: str, authorization: Optional[str] = Header(default=None)):
|
||||
binding = _machine(authorization)
|
||||
held: Optional[HTTPException] = None
|
||||
body = b""
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
try:
|
||||
body = load_manifest(cur, binding["recipient_id"], release_id)
|
||||
except HTTPException as exc:
|
||||
held = exc
|
||||
if held is not None:
|
||||
held.headers = {**(held.headers or {}), **NO_STORE}
|
||||
raise held
|
||||
return Response(content=body, media_type="application/json", headers=NO_STORE)
|
||||
|
||||
|
||||
@router.get("/releases/{release_id}/assets/{asset_id}")
|
||||
def get_asset(release_id: str, asset_id: str, authorization: Optional[str] = Header(default=None)):
|
||||
binding = _machine(authorization)
|
||||
held: Optional[HTTPException] = None
|
||||
path = None
|
||||
media_type = "application/octet-stream"
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
try:
|
||||
path, media_type = load_asset(cur, binding["recipient_id"], release_id, asset_id)
|
||||
except HTTPException as exc:
|
||||
held = exc
|
||||
if held is not None:
|
||||
held.headers = {**(held.headers or {}), **NO_STORE}
|
||||
raise held
|
||||
return FileResponse(path, media_type=media_type, headers=NO_STORE)
|
||||
|
||||
|
||||
@editorial.get("/api/exercises/{exercise_id}/distribution")
|
||||
def exercise_distribution(exercise_id: int, tenant: TenantContext = Depends(get_tenant_context)):
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
return overview(cur, exercise_id, tenant.profile_id, tenant.global_role or "")
|
||||
|
||||
|
||||
@editorial.post("/api/exercises/{exercise_id}/distribution/drafts")
|
||||
def post_draft(exercise_id: int, body: DraftBody, tenant: TenantContext = Depends(get_tenant_context)):
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
from routers.exercises import _assert_can_edit_exercise
|
||||
|
||||
_assert_can_edit_exercise(cur, exercise_id, tenant)
|
||||
result = create_draft(
|
||||
cur,
|
||||
exercise_id,
|
||||
body.publisher_id,
|
||||
body.recipient_id,
|
||||
tenant.profile_id,
|
||||
tenant.global_role or "",
|
||||
body.cut,
|
||||
)
|
||||
conn.commit()
|
||||
return result
|
||||
|
||||
|
||||
@editorial.put("/api/exercises/{exercise_id}/distribution/drafts/{draft_id}")
|
||||
def put_draft(exercise_id: int, draft_id: str, body: CutBody, tenant: TenantContext = Depends(get_tenant_context)):
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
from routers.exercises import _assert_can_edit_exercise
|
||||
|
||||
_assert_can_edit_exercise(cur, exercise_id, tenant)
|
||||
result = update_draft(
|
||||
cur, exercise_id, draft_id, body.cut, tenant.profile_id, tenant.global_role or ""
|
||||
)
|
||||
conn.commit()
|
||||
return result
|
||||
|
||||
|
||||
@editorial.post("/api/exercises/{exercise_id}/distribution/drafts/{draft_id}/confirm")
|
||||
def post_confirm(exercise_id: int, draft_id: str, tenant: TenantContext = Depends(get_tenant_context)):
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
result = confirm_draft(cur, exercise_id, draft_id, tenant.profile_id, tenant.global_role or "")
|
||||
conn.commit()
|
||||
return result
|
||||
|
||||
|
||||
@editorial.post("/api/distribution/releases/{release_id}/retire")
|
||||
def post_retire(release_id: str, tenant: TenantContext = Depends(get_tenant_context)):
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
result = retire_release(cur, release_id, tenant.profile_id, tenant.global_role or "")
|
||||
conn.commit()
|
||||
return result
|
||||
|
||||
|
||||
@editorial.post("/api/distribution/releases/{release_id}/withdraw")
|
||||
def post_withdraw(release_id: str, body: ReasonBody, tenant: TenantContext = Depends(get_tenant_context)):
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
result = withdraw_release(cur, release_id, body.reason_code, tenant.profile_id, tenant.global_role or "", "release", None)
|
||||
conn.commit()
|
||||
return result
|
||||
|
||||
|
||||
@editorial.post("/api/distribution/releases/{release_id}/variants/{variant_id}/withdraw")
|
||||
def post_withdraw_variant(
|
||||
release_id: str,
|
||||
variant_id: str,
|
||||
body: ReasonBody,
|
||||
tenant: TenantContext = Depends(get_tenant_context),
|
||||
):
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
result = withdraw_release(
|
||||
cur, release_id, body.reason_code, tenant.profile_id, tenant.global_role or "", "variant", variant_id
|
||||
)
|
||||
conn.commit()
|
||||
return result
|
||||
|
||||
|
||||
@editorial.post("/api/distribution/releases/{release_id}/assets/{asset_id}/withdraw")
|
||||
def post_withdraw_asset(
|
||||
release_id: str,
|
||||
asset_id: str,
|
||||
body: ReasonBody,
|
||||
tenant: TenantContext = Depends(get_tenant_context),
|
||||
):
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
result = withdraw_release(
|
||||
cur, release_id, body.reason_code, tenant.profile_id, tenant.global_role or "", "asset", asset_id
|
||||
)
|
||||
conn.commit()
|
||||
return result
|
||||
|
||||
|
||||
@editorial.post("/api/distribution/admin/publishers")
|
||||
def post_publisher(body: PublisherBody, tenant: TenantContext = Depends(get_tenant_context)):
|
||||
_superadmin(tenant)
|
||||
if body.kind not in ("platform", "own", "club"):
|
||||
raise HTTPException(status_code=400, detail="kind ist platform, own oder club.")
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO distribution_publishers (name, kind, club_id)
|
||||
VALUES (%s, %s, %s)
|
||||
RETURNING id
|
||||
""",
|
||||
(body.name, body.kind, body.club_id),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
conn.commit()
|
||||
return {"id": str(row["id"])}
|
||||
|
||||
|
||||
@editorial.post("/api/distribution/admin/recipients")
|
||||
def post_recipient(body: RecipientBody, tenant: TenantContext = Depends(get_tenant_context)):
|
||||
_superadmin(tenant)
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute(
|
||||
"INSERT INTO distribution_recipients (name) VALUES (%s) RETURNING id",
|
||||
(body.name,),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
conn.commit()
|
||||
return {"id": str(row["id"])}
|
||||
|
||||
|
||||
@editorial.post("/api/distribution/admin/relationships")
|
||||
def post_relationship(body: RelationshipBody, tenant: TenantContext = Depends(get_tenant_context)):
|
||||
_superadmin(tenant)
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO distribution_relationships (publisher_id, recipient_id)
|
||||
VALUES (%s, %s)
|
||||
RETURNING id
|
||||
""",
|
||||
(body.publisher_id, body.recipient_id),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
conn.commit()
|
||||
return {"id": str(row["id"])}
|
||||
|
||||
|
||||
@editorial.post("/api/distribution/admin/bindings")
|
||||
def post_binding(body: BindingBody, tenant: TenantContext = Depends(get_tenant_context)):
|
||||
_superadmin(tenant)
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO distribution_bindings (recipient_id, name)
|
||||
VALUES (%s, %s)
|
||||
RETURNING id
|
||||
""",
|
||||
(body.recipient_id, body.name),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
conn.commit()
|
||||
return {"id": str(row["id"])}
|
||||
|
||||
|
||||
@editorial.post("/api/distribution/admin/bindings/{binding_id}/keys")
|
||||
def post_key(binding_id: str, body: KeyBody, tenant: TenantContext = Depends(get_tenant_context)):
|
||||
_superadmin(tenant)
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
result = issue_key(cur, binding_id, body.expires_at)
|
||||
conn.commit()
|
||||
return result
|
||||
|
||||
|
||||
@editorial.post("/api/distribution/admin/keys/{key_prefix}/revoke")
|
||||
def post_revoke(key_prefix: str, tenant: TenantContext = Depends(get_tenant_context)):
|
||||
_superadmin(tenant)
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute(
|
||||
"UPDATE distribution_keys SET revoked_at = NOW() WHERE key_prefix = %s AND revoked_at IS NULL",
|
||||
(key_prefix,),
|
||||
)
|
||||
conn.commit()
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
@editorial.post("/api/distribution/admin/publishers/{publisher_id}/releasers")
|
||||
def post_releaser(publisher_id: str, body: ProfileBody, tenant: TenantContext = Depends(get_tenant_context)):
|
||||
_superadmin(tenant)
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO distribution_releasers (publisher_id, profile_id)
|
||||
VALUES (%s, %s)
|
||||
ON CONFLICT DO NOTHING
|
||||
""",
|
||||
(publisher_id, body.profile_id),
|
||||
)
|
||||
conn.commit()
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
@editorial.post("/api/distribution/admin/publishers/{publisher_id}/exercises")
|
||||
def post_assign(publisher_id: str, body: ExerciseAssignBody, tenant: TenantContext = Depends(get_tenant_context)):
|
||||
_superadmin(tenant)
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO distribution_publisher_exercises (publisher_id, exercise_id)
|
||||
VALUES (%s, %s)
|
||||
ON CONFLICT DO NOTHING
|
||||
""",
|
||||
(publisher_id, body.exercise_id),
|
||||
)
|
||||
conn.commit()
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
@editorial.post("/api/distribution/admin/suspend")
|
||||
def post_suspend(body: SuspendBody, tenant: TenantContext = Depends(get_tenant_context)):
|
||||
_superadmin(tenant)
|
||||
table = {
|
||||
"publisher": "distribution_publishers",
|
||||
"recipient": "distribution_recipients",
|
||||
"binding": "distribution_bindings",
|
||||
}.get(body.kind)
|
||||
if table is None:
|
||||
raise HTTPException(status_code=400, detail="kind ist publisher, recipient oder binding.")
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute(f"UPDATE {table} SET status = 'suspended' WHERE id = %s", (body.id,))
|
||||
conn.commit()
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
@editorial.get("/api/distribution/admin/backlog")
|
||||
def get_backlog(tenant: TenantContext = Depends(get_tenant_context)):
|
||||
_superadmin(tenant)
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
return {"count": backlog_count(cur)}
|
||||
Reference in new issue
Block a user