Coverage for app / router / app / projects / inheritance / router.py: 65%

176 statements  

« prev     ^ index     » next       coverage.py v7.13.5, created at 2026-10-31 11:21 +0000

1"""What a project inherits from its parent (``app/services/inheritance.py``): 

2read its declarations, declare one resource or a whole kind, withdraw one, 

3and see what in the project depends on a declaration before withdrawing it. 

4 

5Declaring is a change to the project, so it versions the project with 

6``inheritance`` in its changed fields and its declarations in the children 

7snapshot, beside its members and invites. 

8""" 

9 

10from typing import Literal 

11from uuid import UUID, uuid4 

12 

13from fastapi import APIRouter, Depends, HTTPException, status 

14from pydantic import BaseModel 

15from sqlalchemy.orm import Session 

16 

17from app.db.postgres import models as m 

18from app.db.postgres.models import Project, User 

19from app.dependency.base import get_db 

20from app.dependency.resource_access import verify_list_scope 

21from app.dependency.user.context import get_current_user 

22from app.services import access, inheritance, membership 

23from app.services import workspace as workspace_service 

24from app.services.membership import PROJECT 

25from app.util.time import UTCDateTime, naive_utcnow 

26 

27#: Mounted under ``project_router`` (``/projects``). 

28inheritance_router = APIRouter(tags=["App - Projects"]) 

29 

30 

31class InheritableKind(BaseModel): 

32 key: str 

33 label: str 

34 #: Whether a parent can require it of every project (rules). 

35 requirable: bool = False 

36 

37 

38class Declaration(BaseModel): 

39 id: UUID 

40 kind: str 

41 #: None: every resource of the kind, future ones included. 

42 resource_id: UUID | None = None 

43 resource_name: str | None = None 

44 declared_by_user_id: UUID | None = None 

45 created_at: UTCDateTime | None = None 

46 

47 

48class RequiredRule(BaseModel): 

49 id: UUID 

50 name: str 

51 #: ``required`` for every project, or ``pinned`` to this one. 

52 reason: Literal["required", "pinned"] 

53 

54 

55class Parent(BaseModel): 

56 key: str 

57 kind: Literal["personal", "organisation"] 

58 name: str | None = None 

59 

60 

61class InheritanceRead(BaseModel): 

62 parent: Parent 

63 kinds: list[InheritableKind] 

64 declarations: list[Declaration] 

65 #: The parent's rules that apply here without a declaration. 

66 required: list[RequiredRule] 

67 

68 

69class DeclarationCreate(BaseModel): 

70 kind: str 

71 #: Omit to inherit every resource of the kind. 

72 resource_id: UUID | None = None 

73 

74 

75class Dependent(BaseModel): 

76 kind: str 

77 id: UUID 

78 name: str | None = None 

79 

80 

81def _project(db: Session, project_id: UUID) -> Project: 

82 project = db.get(Project, project_id) 

83 if project is None: 

84 raise HTTPException( 

85 status_code=status.HTTP_404_NOT_FOUND, detail="Project not found" 

86 ) 

87 return project 

88 

89 

90def _workspace(db: Session, project: Project) -> workspace_service.Workspace: 

91 return workspace_service.Workspace( 

92 workspace_service.WorkspaceKind.project, 

93 project.id, 

94 name=project.name, 

95 parent=workspace_service.home_of(db, project, named=True), 

96 ) 

97 

98 

99def _may_declare( 

100 db: Session, 

101 project: Project, 

102 ws: workspace_service.Workspace, 

103 entry: inheritance.Inheritable, 

104 user: User, 

105) -> None: 

106 """403 unless ``user`` may change what the project inherits of 

107 ``entry``'s kind: an admin of it, or an editor of the kind's area there — 

108 and able to read the parent. A personal project inherits its owner's 

109 work, so only its owner declares; nobody else may expose it.""" 

110 if user.is_superuser: 

111 return 

112 parent = ws.parent 

113 if parent.kind is workspace_service.WorkspaceKind.personal: 

114 if parent.id != user.id: 

115 raise HTTPException( 

116 status_code=status.HTTP_403_FORBIDDEN, 

117 detail="Only the project's owner can share their own work into it.", 

118 ) 

119 else: 

120 verify_list_scope(parent.id, "organisation", user, db) 

121 m_ = membership.effective_membership(db, PROJECT, project.id, user.id) 

122 kind = access.kind_of(entry.model) 

123 if m_ is None or ( 

124 kind is not None and access.effective(m_)[kind.area] < access.AccessLevel.editor 

125 ): 

126 area = access.AREA_LABELS[kind.area] if kind else "this area" 

127 raise HTTPException( 

128 status_code=status.HTTP_403_FORBIDDEN, 

129 detail=f"Choosing what this project inherits of {area} needs an " 

130 "editor of it here, or an admin.", 

131 ) 

132 

133 

134def _names(db: Session, rows: list[m.WorkspaceInheritance]) -> dict[UUID, str]: 

135 names: dict[UUID, str] = {} 

136 by_kind: dict[str, list[UUID]] = {} 

137 for d in rows: 

138 if d.resource_id is not None: 

139 by_kind.setdefault(d.kind, []).append(d.resource_id) 

140 for key, ids in by_kind.items(): 

141 entry = inheritance.entry_for(key) 

142 if entry is None: 

143 continue 

144 for id_, name in ( 

145 db.query(entry.model.id, entry.model.name) 

146 .filter(entry.model.id.in_(ids)) 

147 .all() 

148 ): 

149 names[id_] = name 

150 return names 

151 

152 

153def _read(db: Session, project: Project) -> InheritanceRead: 

154 ws = _workspace(db, project) 

155 rows = inheritance.declarations(db, project.id) 

156 names = _names(db, rows) 

157 R = m.Rule 

158 required = ( 

159 db.query(R) 

160 .filter( 

161 ws.parent.owns(R), R.is_active.is_(True), inheritance.required_clause(ws) 

162 ) 

163 .order_by(R.priority.desc(), R.name) 

164 .all() 

165 ) 

166 return InheritanceRead( 

167 parent=Parent( 

168 key=ws.parent.key, kind=ws.parent.kind.value, name=ws.parent.name 

169 ), 

170 kinds=[ 

171 InheritableKind(key=e.key, label=e.label, requirable=e.requirable) 

172 for e in inheritance.INHERITABLE.values() 

173 ], 

174 declarations=[ 

175 Declaration( 

176 id=d.id, 

177 kind=d.kind, 

178 resource_id=d.resource_id, 

179 resource_name=names.get(d.resource_id) if d.resource_id else None, 

180 declared_by_user_id=d.declared_by_user_id, 

181 created_at=d.created_at, 

182 ) 

183 for d in rows 

184 # A declaration whose resource has gone is inert; leave it out. 

185 if d.resource_id is None or d.resource_id in names 

186 ], 

187 required=[ 

188 RequiredRule( 

189 id=r.id, 

190 name=r.name, 

191 reason="required" if r.required_for_projects else "pinned", 

192 ) 

193 for r in required 

194 ], 

195 ) 

196 

197 

198@inheritance_router.get("/{project_id}/inheritance", response_model=InheritanceRead) 

199def get_inheritance( 

200 project_id: UUID, 

201 db: Session = Depends(get_db), 

202 current_user: User = Depends(get_current_user), 

203): 

204 """What the project inherits from its parent: each declaration (one 

205 resource, or every resource of a kind), and the parent's rules that 

206 apply here without one. Any member may read it.""" 

207 project = _project(db, project_id) 

208 membership.require_member(db, PROJECT, project.id, current_user) 

209 return _read(db, project) 

210 

211 

212class Candidate(BaseModel): 

213 id: UUID 

214 name: str 

215 #: Already inherited, by itself or with its whole kind. 

216 inherited: bool = False 

217 

218 

219@inheritance_router.get( 

220 "/{project_id}/inheritance/candidates", 

221 response_model=list[Candidate], 

222) 

223def inheritance_candidates( 

224 project_id: UUID, 

225 kind: str, 

226 db: Session = Depends(get_db), 

227 current_user: User = Depends(get_current_user), 

228): 

229 """The parent's resources of ``kind`` this project could inherit — what 

230 a declaration picks from — each marked when it already does. Any member 

231 may read it, as they may read the parent's work.""" 

232 project = _project(db, project_id) 

233 membership.require_member(db, PROJECT, project.id, current_user) 

234 entry = inheritance.entry_for(kind) 

235 if entry is None: 

236 raise HTTPException( 

237 status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, 

238 detail=f"{kind!r} can't be inherited.", 

239 ) 

240 ws = _workspace(db, project) 

241 M = entry.model 

242 rows = db.query(M.id, M.name).filter(ws.parent.owns(M)).order_by(M.name).all() 

243 inherited = ( 

244 { 

245 r[0] 

246 for r in db.query(M.id) 

247 .filter( 

248 M.id.in_([row[0] for row in rows]), inheritance.inherited_clause(M, ws) 

249 ) 

250 .all() 

251 } 

252 if rows 

253 else set() 

254 ) 

255 return [Candidate(id=i, name=n, inherited=i in inherited) for i, n in rows] 

256 

257 

258@inheritance_router.post( 

259 "/{project_id}/inheritance", 

260 response_model=Declaration, 

261 status_code=status.HTTP_201_CREATED, 

262) 

263def declare_inheritance( 

264 project_id: UUID, 

265 body: DeclarationCreate, 

266 db: Session = Depends(get_db), 

267 current_user: User = Depends(get_current_user), 

268): 

269 """Inherit one of the parent's resources, or every resource of a kind 

270 (no ``resource_id``) — which absorbs the kind's single declarations. 

271 422 for a kind that can't be inherited or a built-in (already in every 

272 workspace), 404 for a resource the parent doesn't own, 409 when it is 

273 already inherited.""" 

274 project = _project(db, project_id) 

275 entry = inheritance.entry_for(body.kind) 

276 if entry is None: 

277 raise HTTPException( 

278 status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, 

279 detail=f"{body.kind!r} can't be inherited. Inheritable: " 

280 + ", ".join(inheritance.INHERITABLE), 

281 ) 

282 ws = _workspace(db, project) 

283 _may_declare(db, project, ws, entry, current_user) 

284 

285 W = m.WorkspaceInheritance 

286 existing = db.query(W).filter(W.project_id == project.id, W.kind == entry.key).all() 

287 if any(d.resource_id is None for d in existing): 

288 raise HTTPException( 

289 status_code=status.HTTP_409_CONFLICT, 

290 detail=f"This project already inherits every one of " 

291 f"{ws.parent.name or 'its parent'}'s {entry.label.lower()}.", 

292 ) 

293 if body.resource_id is not None: 

294 row = db.get(entry.model, body.resource_id) 

295 if row is not None and getattr(row, "is_system", False) is True: 

296 raise HTTPException( 

297 status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, 

298 detail="Built-in resources are in every workspace already.", 

299 ) 

300 if row is None or not ws.parent.owns_row(row): 

301 raise HTTPException( 

302 status_code=status.HTTP_404_NOT_FOUND, 

303 detail=f"No such {entry.label.lower().rstrip('s')} in " 

304 f"{ws.parent.name or 'the parent'}.", 

305 ) 

306 if any(d.resource_id == body.resource_id for d in existing): 

307 raise HTTPException( 

308 status_code=status.HTTP_409_CONFLICT, 

309 detail="This project already inherits it.", 

310 ) 

311 else: 

312 # The whole kind covers each one declared so far. 

313 for d in existing: 

314 db.delete(d) 

315 

316 declaration = W( 

317 id=uuid4(), 

318 project_id=project.id, 

319 kind=entry.key, 

320 resource_id=body.resource_id, 

321 declared_by_user_id=current_user.id, 

322 created_at=naive_utcnow(), 

323 ) 

324 db.add(declaration) 

325 membership.record_change(db, PROJECT, project, current_user, "inheritance") 

326 db.commit() 

327 names = _names(db, [declaration]) 

328 return Declaration( 

329 id=declaration.id, 

330 kind=declaration.kind, 

331 resource_id=declaration.resource_id, 

332 resource_name=names.get(declaration.resource_id), 

333 declared_by_user_id=declaration.declared_by_user_id, 

334 created_at=declaration.created_at, 

335 ) 

336 

337 

338def _declaration(db: Session, project: Project, declaration_id: UUID): 

339 W = m.WorkspaceInheritance 

340 row = ( 

341 db.query(W) 

342 .filter(W.id == declaration_id, W.project_id == project.id) 

343 .one_or_none() 

344 ) 

345 if row is None: 

346 raise HTTPException( 

347 status_code=status.HTTP_404_NOT_FOUND, detail="Declaration not found" 

348 ) 

349 return row 

350 

351 

352@inheritance_router.delete( 

353 "/{project_id}/inheritance/{declaration_id}", 

354 status_code=status.HTTP_204_NO_CONTENT, 

355) 

356def withdraw_inheritance( 

357 project_id: UUID, 

358 declaration_id: UUID, 

359 db: Session = Depends(get_db), 

360 current_user: User = Depends(get_current_user), 

361): 

362 """Stop inheriting it. What in the project used it stops reaching it — 

363 ``…/dependents`` lists that first.""" 

364 project = _project(db, project_id) 

365 declaration = _declaration(db, project, declaration_id) 

366 entry = inheritance.entry_for(declaration.kind) 

367 if entry is not None: 

368 _may_declare(db, project, _workspace(db, project), entry, current_user) 

369 db.delete(declaration) 

370 membership.record_change(db, PROJECT, project, current_user, "inheritance") 

371 db.commit() 

372 

373 

374@inheritance_router.get( 

375 "/{project_id}/inheritance/{declaration_id}/dependents", 

376 response_model=list[Dependent], 

377) 

378def inheritance_dependents( 

379 project_id: UUID, 

380 declaration_id: UUID, 

381 db: Session = Depends(get_db), 

382 current_user: User = Depends(get_current_user), 

383): 

384 """What the project's own work uses of what the declaration brings: its 

385 agents granted an inherited repository or skillset, its repositories 

386 holding an inherited source, its experiments on an inherited dataset.""" 

387 project = _project(db, project_id) 

388 membership.require_member(db, PROJECT, project.id, current_user) 

389 declaration = _declaration(db, project, declaration_id) 

390 entry = inheritance.entry_for(declaration.kind) 

391 if entry is None: 

392 return [] 

393 ws = _workspace(db, project) 

394 M = entry.model 

395 ids = ( 

396 [declaration.resource_id] 

397 if declaration.resource_id is not None 

398 else [r[0] for r in db.query(M.id).filter(ws.parent.owns(M)).all()] 

399 ) 

400 if not ids: 

401 return [] 

402 found: list[Dependent] = [] 

403 

404 def _add(kind: str, rows): 

405 found.extend(Dependent(kind=kind, id=r.id, name=r.name) for r in rows) 

406 

407 if M is m.KnowledgeRepository: 

408 _add( 

409 "agent", 

410 db.query(m.Agent) 

411 .join(m.AgentRepository, m.AgentRepository.agent_id == m.Agent.id) 

412 .filter(m.AgentRepository.repository_id.in_(ids), ws.owns(m.Agent)) 

413 .all(), 

414 ) 

415 elif M is m.Skillset: 

416 _add( 

417 "agent", 

418 db.query(m.Agent) 

419 .join(m.AgentSkillset, m.AgentSkillset.agent_id == m.Agent.id) 

420 .filter(m.AgentSkillset.skillset_id.in_(ids), ws.owns(m.Agent)) 

421 .all(), 

422 ) 

423 elif M is m.Knowledge: 

424 _add( 

425 "repository", 

426 db.query(m.KnowledgeRepository) 

427 .join( 

428 m.RepositoryKnowledge, 

429 m.RepositoryKnowledge.repository_id == m.KnowledgeRepository.id, 

430 ) 

431 .filter( 

432 m.RepositoryKnowledge.knowledge_id.in_(ids), 

433 ws.owns(m.KnowledgeRepository), 

434 ) 

435 .all(), 

436 ) 

437 elif M is m.TestSuite: 

438 _add( 

439 "experiment", 

440 db.query(m.Experiment) 

441 .filter(m.Experiment.dataset_id.in_(ids), ws.owns(m.Experiment)) 

442 .all(), 

443 ) 

444 return found