codehood-cli 0.5.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. codehood/__init__.py +0 -0
  2. codehood/__main__.py +4 -0
  3. codehood/actions/__init__.py +0 -0
  4. codehood/actions/base.py +119 -0
  5. codehood/actions/resources.py +30 -0
  6. codehood/api/__init__.py +0 -0
  7. codehood/api/base.py +256 -0
  8. codehood/api/generate.py +1370 -0
  9. codehood/api/generated.py +3818 -0
  10. codehood/api/openapi.py +134 -0
  11. codehood/api/pages.py +53 -0
  12. codehood/cli/__init__.py +64 -0
  13. codehood/cli/api.py +422 -0
  14. codehood/cli/attendance.py +136 -0
  15. codehood/cli/auth.py +106 -0
  16. codehood/cli/base.py +42 -0
  17. codehood/cli/chill.py +52 -0
  18. codehood/cli/exam.py +107 -0
  19. codehood/cli/grades.py +185 -0
  20. codehood/cli/init.py +161 -0
  21. codehood/cli/push.py +609 -0
  22. codehood/cli/show.py +77 -0
  23. codehood/cli/uitils.py +26 -0
  24. codehood/functional.py +40 -0
  25. codehood/globs.py +71 -0
  26. codehood/grades.py +74 -0
  27. codehood/hypothesis.py +274 -0
  28. codehood/models/__init__.py +0 -0
  29. codehood/models/base.py +15 -0
  30. codehood/models/repo.py +187 -0
  31. codehood/models/validators.py +177 -0
  32. codehood/push/__init__.py +225 -0
  33. codehood/push/base.py +216 -0
  34. codehood/push/calendar.py +664 -0
  35. codehood/push/errors.py +136 -0
  36. codehood/push/exam.py +636 -0
  37. codehood/push/exclude.py +60 -0
  38. codehood/push/grades.py +455 -0
  39. codehood/push/hook.py +48 -0
  40. codehood/push/links.py +614 -0
  41. codehood/push/ours.py +78 -0
  42. codehood/push/plan.py +1981 -0
  43. codehood/push/project.py +272 -0
  44. codehood/push/question.py +338 -0
  45. codehood/push/report.py +244 -0
  46. codehood/push/repository.py +326 -0
  47. codehood/push/resource.py +576 -0
  48. codehood/push/run.py +1275 -0
  49. codehood/push/unconsumed.py +208 -0
  50. codehood/push/wire.py +222 -0
  51. codehood/py.typed +0 -0
  52. codehood/repo/__init__.py +62 -0
  53. codehood/repo/_config.py +28 -0
  54. codehood/repo/_layout.py +132 -0
  55. codehood/repo/_scaffold.py +244 -0
  56. codehood/repo/diff.py +71 -0
  57. codehood/repo/file_tracker.py +124 -0
  58. codehood/theme.py +101 -0
  59. codehood/widgets/__init__.py +0 -0
  60. codehood/widgets/mascot.py +76 -0
  61. codehood/widgets/questions/__init__.py +65 -0
  62. codehood/widgets/questions/base.py +119 -0
  63. codehood/widgets/questions/controls.py +194 -0
  64. codehood/widgets/questions/fill_in.py +81 -0
  65. codehood/widgets/questions/responses.py +137 -0
  66. codehood/widgets/questions/simple.py +117 -0
  67. codehood_cli-0.5.0.dist-info/METADATA +294 -0
  68. codehood_cli-0.5.0.dist-info/RECORD +71 -0
  69. codehood_cli-0.5.0.dist-info/WHEEL +4 -0
  70. codehood_cli-0.5.0.dist-info/entry_points.txt +4 -0
  71. codehood_cli-0.5.0.dist-info/licenses/LICENSE +21 -0
codehood/push/run.py ADDED
@@ -0,0 +1,1275 @@
1
+ """
2
+ The imperative shell of `codehood push`.
3
+
4
+ The only thing in `codehood/push/` that touches HTTP: `fetch_server_state`
5
+ reads what the server currently holds, so `plan.plan_sync` can diff
6
+ against it; `run_plan` executes a plan one `Write` at a time.
7
+
8
+ This module is also the single place the core's `ResourceData` is
9
+ translated into the generated request models, so a change to the server's
10
+ union lands here and nowhere else.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import json
16
+ import warnings
17
+ from collections.abc import Iterable, Iterator, Mapping, Sequence
18
+ from dataclasses import dataclass, field, replace
19
+ from pathlib import Path
20
+ from typing import Protocol, cast
21
+ from urllib.parse import quote
22
+
23
+ import httpx
24
+ from pydantic import JsonValue
25
+
26
+ from ..api import generated
27
+ from ..api.base import CodehoodAPIError, auth_headers, query_params
28
+ from ..api.pages import read_all
29
+ from ..grades import ExamResult, ExamState
30
+ from ..models.base import Model
31
+ from .base import BaseEntry, BaseState
32
+ from .exam import ExamStatus
33
+ from .grades import ServerStudent
34
+ from .plan import (
35
+ BaseUpdate,
36
+ DeleteCalendarEvent,
37
+ DeleteExam,
38
+ DeleteGradeColumn,
39
+ DeleteQuestion,
40
+ DeleteRepository,
41
+ DeleteResource,
42
+ DeleteRollCall,
43
+ DeleteTimeSlot,
44
+ EntityKind,
45
+ Plan,
46
+ ServerEvent,
47
+ ServerExam,
48
+ ServerQuestion,
49
+ ServerState,
50
+ UpsertCalendarEvent,
51
+ UpsertCourse,
52
+ UpsertExam,
53
+ UpsertGradeColumn,
54
+ UpsertQuestion,
55
+ UpsertRepository,
56
+ UpsertResource,
57
+ UpsertTimeSlot,
58
+ Write,
59
+ )
60
+ from .project import (
61
+ RemoteEntry,
62
+ project_calendar_event,
63
+ project_course,
64
+ project_exam,
65
+ project_grade_column,
66
+ project_question,
67
+ project_resource,
68
+ project_time_slot,
69
+ )
70
+ from .question import MAX_UPLOAD_BYTES, QuestionStatus
71
+ from .repository import RepositoryEntry, batch_entries
72
+ from .resource import CodeData, FileData, LinkData, MdData, ResourceData
73
+ from .wire import (
74
+ event_payload,
75
+ grade_column_payload,
76
+ time_slot_payload,
77
+ wire_question,
78
+ )
79
+
80
+ __all__ = [
81
+ "HttpRepositoryApi",
82
+ "OpResult",
83
+ "RepositoryApi",
84
+ "apply",
85
+ "describe_failure",
86
+ "fetch_server_state",
87
+ "fetch_students",
88
+ "run_plan",
89
+ ]
90
+
91
+ #: The generated request-side members of `Resource.data`. The `FILE` member
92
+ #: exists twice in the spec -- the upload shape (`filename` plus `buffer`)
93
+ #: and the read-back shape (`link`, `mimeType`, `filename`) -- so the
94
+ #: generator qualifies both by the schema that owns them:
95
+ #: `ResourceCreateDataFile` is the one a push sends.
96
+ type RequestData = (
97
+ generated.DataMd
98
+ | generated.DataCode
99
+ | generated.ResourceCreateDataFile
100
+ | generated.DataLink
101
+ )
102
+
103
+ #: What each cell of the server's grades table is called in `ExamResult`.
104
+ EXAM_STATES: dict[str, ExamState] = {
105
+ "total": "graded",
106
+ "pending": "pending",
107
+ "in-progress": "in_progress",
108
+ "missed": "missed",
109
+ "empty": "not_held",
110
+ }
111
+
112
+
113
+ @dataclass(frozen=True)
114
+ class OpResult:
115
+ """
116
+ The outcome of executing one `Write`.
117
+ """
118
+
119
+ op: Write
120
+ ok: bool
121
+ message: str
122
+ #: The operation was never attempted because an earlier one it depends
123
+ #: on failed. Always paired with `ok=False`.
124
+ skipped: bool = False
125
+ #: The `rev` and `updatedAt` the server answered the write with, when it
126
+ #: answered with the stored entity.
127
+ rev: str | None = None
128
+ updated_at: str | None = None
129
+
130
+
131
+ class RepositoryApi(Protocol):
132
+ """
133
+ The repository endpoints of one course, as `run.py` uses them.
134
+
135
+ A seam: tests can pass a fake. `HttpRepositoryApi` is the real one. Every method
136
+ raises `httpx.HTTPStatusError` (or `CodehoodAPIError`) on a refused
137
+ request.
138
+ """
139
+
140
+ def list_trees(self) -> Mapping[str, str | None]:
141
+ """
142
+ `GET .../repository`: slug -> `tree`, `None` before the first commit.
143
+ """
144
+ ...
145
+
146
+ def upsert(self, slug: str) -> None:
147
+ """
148
+ `PUT .../repository` with `{slug}`.
149
+ """
150
+ ...
151
+
152
+ def missing(self, hashes: Sequence[str]) -> list[str]:
153
+ """
154
+ `POST /api/blob/missing`: the sha-256 hashes the server lacks.
155
+ """
156
+ ...
157
+
158
+ def upload(self, slug: str, entries: Sequence[RepositoryEntry]) -> None:
159
+ """
160
+ `POST .../repository/<slug>/files`: one multipart request, one part
161
+ per file, named by its sha-256.
162
+ """
163
+ ...
164
+
165
+ def commit(
166
+ self, slug: str, entries: Sequence[RepositoryEntry], message: str | None
167
+ ) -> str | None:
168
+ """
169
+ `POST .../repository/<slug>/commit`; returns the new `head`.
170
+ """
171
+ ...
172
+
173
+ def delete(self, slug: str) -> None:
174
+ """
175
+ `DELETE .../repository/<slug>`.
176
+ """
177
+ ...
178
+
179
+
180
+ class HttpRepositoryApi:
181
+ """
182
+ `RepositoryApi` over the REST API. Listing, upsert, delete and `missing`
183
+ use the generated client; the multipart upload and the commit are
184
+ hand-written because the generator handles neither a multipart body nor
185
+ an array of inline objects.
186
+ """
187
+
188
+ def __init__(self, client: httpx.Client, discipline: str, course: str) -> None:
189
+ self.client = client
190
+ self.discipline = discipline
191
+ self.course = course
192
+
193
+ def list_trees(self) -> Mapping[str, str | None]:
194
+ """
195
+ See `RepositoryApi.list_trees`.
196
+ """
197
+ items = read_all(
198
+ generated.repository_list,
199
+ discipline=self.discipline,
200
+ course=self.course,
201
+ client=self.client,
202
+ )
203
+ return {item.slug: item.tree for item in items}
204
+
205
+ def upsert(self, slug: str) -> None:
206
+ """
207
+ See `RepositoryApi.upsert`.
208
+ """
209
+ generated.repository_upsert(
210
+ discipline=self.discipline,
211
+ course=self.course,
212
+ body=generated.RepositoryCreate(slug=slug),
213
+ client=self.client,
214
+ )
215
+
216
+ def missing(self, hashes: Sequence[str]) -> list[str]:
217
+ """
218
+ See `RepositoryApi.missing`.
219
+ """
220
+ result = generated.blob_missing(
221
+ body=generated.BlobMissingInput(hashes=list(hashes)), client=self.client
222
+ )
223
+ return list(result.missing)
224
+
225
+ def upload(self, slug: str, entries: Sequence[RepositoryEntry]) -> None:
226
+ """
227
+ See `RepositoryApi.upload`. Reads each file from `entry.source`.
228
+ """
229
+ parts = {entry.sha256: entry.source for entry in entries}
230
+ files = [
231
+ (sha256, (sha256, source.read_bytes(), "application/octet-stream"))
232
+ for sha256, source in parts.items()
233
+ ]
234
+ # Built apart from the client: its default `Content-Type: application/json`
235
+ # would hide the multipart boundary `httpx` computes.
236
+ request = httpx.Request(
237
+ "POST",
238
+ self.client.base_url.join(self._url(slug, "files")),
239
+ files=files,
240
+ headers=auth_headers(self.client),
241
+ )
242
+ self.client.send(request).raise_for_status()
243
+
244
+ def commit(
245
+ self, slug: str, entries: Sequence[RepositoryEntry], message: str | None
246
+ ) -> str | None:
247
+ """
248
+ See `RepositoryApi.commit`.
249
+ """
250
+ body: dict[str, object] = {
251
+ "tree": [
252
+ {"path": entry.path, "mode": entry.mode, "hash": entry.sha256}
253
+ for entry in entries
254
+ ]
255
+ }
256
+ if message is not None:
257
+ body["message"] = message
258
+ response = self.client.post(
259
+ self._url(slug, "commit"), json=body, headers=auth_headers(self.client)
260
+ )
261
+ response.raise_for_status()
262
+ head = response.json().get("head")
263
+ return head if isinstance(head, str) else None
264
+
265
+ def delete(self, slug: str) -> None:
266
+ """
267
+ See `RepositoryApi.delete`.
268
+ """
269
+ generated.repository_delete(
270
+ discipline=self.discipline,
271
+ course=self.course,
272
+ slug=slug,
273
+ client=self.client,
274
+ )
275
+
276
+ def _url(self, *parts: str) -> str:
277
+ base = f"/api/course/{self.discipline}/{self.course}/repository"
278
+ return "/".join((base, *(quote(part, safe="") for part in parts)))
279
+
280
+
281
+ def fetch_server_state(
282
+ discipline: str,
283
+ course: str,
284
+ client: httpx.Client,
285
+ repositories: RepositoryApi | None = None,
286
+ ) -> ServerState:
287
+ """
288
+ Read what the server currently holds for a course.
289
+
290
+ The mapping's `cli.course.preSync` RPC does not exist on the server
291
+ (see `ROADBLOCKS.md`), so this reads the list endpoints instead: `GET
292
+ /api/course/{discipline}/{course}` for the course, then `.../resource`,
293
+ `.../question`, `.../time-slot`, `.../calendar-event` and
294
+ `.../grade-column`; `.../roll-call` adds each event's attendance count.
295
+ The listings carry whole bodies, so each entity becomes a `RemoteEntry`
296
+ (see `project.py`) without a request of its own: a course costs six
297
+ listings, seven when it has events, plus the repository listing, each
298
+ one request per page.
299
+ `repositories` gives `slug -> tree`; without it no repository is listed.
300
+
301
+ A time slot carries no `ref` column server-side, so its entry has no
302
+ `rev`.
303
+
304
+ Returns:
305
+ A course that does not exist yet reports nothing at all,
306
+ regardless of what those listings themselves would say.
307
+ """
308
+ try:
309
+ remote_course = generated.read_course(
310
+ discipline=discipline, course=course, client=client
311
+ )
312
+ except httpx.HTTPStatusError as exc:
313
+ if exc.response.status_code != 404:
314
+ raise
315
+ return ServerState(course_exists=False)
316
+
317
+ resources = read_all(
318
+ generated.list_resource, discipline=discipline, course=course, client=client
319
+ )
320
+ questions = _list_questions(discipline, course, client)
321
+ exams = read_all(
322
+ generated.list_exam,
323
+ discipline=discipline,
324
+ course=course,
325
+ statuses=["DRAFT", "SCHEDULED", "ONGOING", "COMPLETED"],
326
+ client=client,
327
+ )
328
+ time_slots = read_all(
329
+ generated.list_timeslot, discipline=discipline, course=course, client=client
330
+ )
331
+ calendar_events = read_all(
332
+ generated.list_calendar_event,
333
+ discipline=discipline,
334
+ course=course,
335
+ client=client,
336
+ )
337
+ grade_columns = read_all(
338
+ generated.list_grade_column, discipline=discipline, course=course, client=client
339
+ )
340
+ # A roll call hangs off a calendar event, so none can exist without one.
341
+ roll_calls = (
342
+ {
343
+ (roll_call.week, roll_call.time_slot): len(roll_call.attendances)
344
+ for roll_call in read_all(
345
+ generated.list_roll_call,
346
+ discipline=discipline,
347
+ course=course,
348
+ client=client,
349
+ )
350
+ }
351
+ if calendar_events
352
+ else {}
353
+ )
354
+ return ServerState(
355
+ course_exists=True,
356
+ course=RemoteEntry(
357
+ project_course(remote_course),
358
+ rev=remote_course.rev,
359
+ updated_at=remote_course.updated_at,
360
+ ),
361
+ resources={
362
+ resource.slug: RemoteEntry(
363
+ project_resource(resource),
364
+ rev=resource.rev,
365
+ updated_at=resource.updated_at,
366
+ )
367
+ for resource in resources
368
+ },
369
+ questions={
370
+ str(question["slug"]): _server_question(question)
371
+ for question in questions
372
+ if question["status"] != "ARCHIVED"
373
+ },
374
+ exams={
375
+ exam.slug: ServerExam(
376
+ entry=RemoteEntry(
377
+ project_exam(exam), rev=exam.rev, updated_at=exam.updated_at
378
+ ),
379
+ status=cast(ExamStatus, exam.status),
380
+ )
381
+ for exam in exams
382
+ },
383
+ time_slots={
384
+ slot.slug: RemoteEntry(
385
+ project_time_slot(slot), rev=None, updated_at=slot.updated_at
386
+ )
387
+ for slot in time_slots
388
+ },
389
+ calendar_events={
390
+ (event.week, event.time_slot.slug): _server_event(
391
+ event, roll_calls.get((event.week, event.time_slot.slug))
392
+ )
393
+ for event in calendar_events
394
+ },
395
+ grade_columns={
396
+ column.slug: RemoteEntry(
397
+ project_grade_column(column),
398
+ rev=column.rev,
399
+ updated_at=column.updated_at,
400
+ )
401
+ for column in grade_columns
402
+ },
403
+ repositories=dict(repositories.list_trees()) if repositories else {},
404
+ )
405
+
406
+
407
+ def fetch_students(
408
+ discipline: str, course: str, client: httpx.Client
409
+ ) -> tuple[ServerStudent, ...]:
410
+ """
411
+ Read every enrolled student with their result at every exam.
412
+
413
+ Returns:
414
+ Nothing for a course the server does not have yet: it has no
415
+ student to grade, and the columns are pushed empty.
416
+ """
417
+ try:
418
+ report = generated.course_grades(
419
+ discipline=discipline, course=course, client=client
420
+ )
421
+ except httpx.HTTPStatusError as exc:
422
+ if exc.response.status_code != 404:
423
+ raise
424
+ return ()
425
+ return tuple(_server_student(item) for item in report.students)
426
+
427
+
428
+ def run_plan(
429
+ ops: Iterable[Write],
430
+ *,
431
+ discipline: str,
432
+ course: str,
433
+ client: httpx.Client,
434
+ repositories: RepositoryApi | None = None,
435
+ ) -> Iterator[OpResult]:
436
+ """
437
+ Execute a plan, yielding one result per operation.
438
+
439
+ A failure executing an operation is caught and reported as a failed
440
+ `OpResult`; the remaining operations still run -- a sync is not
441
+ atomic, see `push.md`, "The contract". The exception is the course
442
+ row's own `PUT`: every other operation hangs off the course, so after
443
+ it fails the rest come back as skipped results, never attempted.
444
+
445
+ Repository ops go through `repositories`, `HttpRepositoryApi` over
446
+ `client` by default.
447
+ """
448
+ api = repositories or HttpRepositoryApi(client, discipline, course)
449
+ ops = list(ops)
450
+ blobs = _AttachmentBlobs.of(ops)
451
+ course_failed = False
452
+ for op in ops:
453
+ if course_failed:
454
+ yield OpResult(
455
+ op=op,
456
+ ok=False,
457
+ skipped=True,
458
+ message="not attempted: the course could not be written",
459
+ )
460
+ continue
461
+ result = _run_op(
462
+ op,
463
+ discipline=discipline,
464
+ course=course,
465
+ client=client,
466
+ repositories=api,
467
+ blobs=blobs,
468
+ )
469
+ yield result
470
+ course_failed = isinstance(op, UpsertCourse) and not result.ok
471
+
472
+
473
+ def apply(base: BaseState, plan: Plan, results: Sequence[OpResult]) -> BaseState:
474
+ """
475
+ The base once `plan` ran with `results`, leaving `base` untouched.
476
+
477
+ The updates that need no execution always apply. The update of a
478
+ confirmation applies only when its write succeeded: the stored payload is
479
+ the local one the plan carries, stamped with the `rev` and `updatedAt` of
480
+ the server's answer. Whatever else stays as it was.
481
+ """
482
+ collections: dict[EntityKind, dict[str, BaseEntry]] = {
483
+ kind: dict(getattr(base, name)) for kind, name in COLLECTION_OF.items()
484
+ }
485
+ succeeded = [result for result in results if result.ok]
486
+
487
+ def store(update: BaseUpdate, stamp: OpResult | None = None) -> None:
488
+ entries = collections[update.kind]
489
+ if update.entry is None:
490
+ entries.pop(update.key, None)
491
+ elif stamp is None:
492
+ entries[update.key] = update.entry
493
+ else:
494
+ entries[update.key] = replace(
495
+ update.entry, rev=stamp.rev, updated_at=stamp.updated_at
496
+ )
497
+
498
+ for update in plan.base_updates:
499
+ store(update)
500
+ for confirmation in plan.confirmations:
501
+ result = next((r for r in succeeded if r.op == confirmation.write), None)
502
+ if result is not None:
503
+ store(confirmation.update, result)
504
+ return BaseState(
505
+ course=collections["course"],
506
+ resources=collections["resource"],
507
+ questions=collections["question"],
508
+ exams=collections["exam"],
509
+ time_slots=collections["time_slot"],
510
+ calendar_events=collections["calendar_event"],
511
+ grade_columns=collections["grade_column"],
512
+ )
513
+
514
+
515
+ #
516
+ # Utilities
517
+ #
518
+ #: The `BaseState` collection of each kind of entity.
519
+ COLLECTION_OF: dict[EntityKind, str] = {
520
+ "course": "course",
521
+ "resource": "resources",
522
+ "question": "questions",
523
+ "exam": "exams",
524
+ "time_slot": "time_slots",
525
+ "calendar_event": "calendar_events",
526
+ "grade_column": "grade_columns",
527
+ }
528
+
529
+
530
+ @dataclass(frozen=True)
531
+ class _Stored:
532
+ """
533
+ The `rev` and `updated_at` of an entity read from a raw JSON response.
534
+ """
535
+
536
+ rev: str | None
537
+ updated_at: str | None
538
+
539
+ @classmethod
540
+ def of(cls, response: httpx.Response) -> _Stored:
541
+ body = response.json()
542
+ if not isinstance(body, dict):
543
+ return cls(None, None)
544
+ rev, updated_at = body.get("rev"), body.get("updatedAt")
545
+ return cls(
546
+ rev if isinstance(rev, str) else None,
547
+ updated_at if isinstance(updated_at, str) else None,
548
+ )
549
+
550
+
551
+ def _stamp(op: Write, response: object, message: str) -> OpResult:
552
+ """
553
+ A successful result carrying the `rev` and `updatedAt` of the entity the
554
+ server answered with.
555
+ """
556
+ rev = getattr(response, "rev", None)
557
+ updated_at = getattr(response, "updated_at", None)
558
+ return OpResult(
559
+ op=op,
560
+ ok=True,
561
+ message=message,
562
+ rev=rev if isinstance(rev, str) else None,
563
+ updated_at=updated_at if isinstance(updated_at, str) else None,
564
+ )
565
+
566
+
567
+ def describe_failure(exc: CodehoodAPIError | httpx.HTTPStatusError) -> str:
568
+ """
569
+ One line saying why a request failed, with the server's own message.
570
+
571
+ An undocumented error status (`400` on a question the server refuses)
572
+ reaches here as a bare `httpx.HTTPStatusError`, whose text only repeats
573
+ the URL; the reason is in the response body.
574
+ """
575
+ if not isinstance(exc, httpx.HTTPStatusError):
576
+ return str(exc)
577
+ status = exc.response.status_code
578
+ try:
579
+ message = exc.response.json()["message"]
580
+ except (ValueError, KeyError, TypeError):
581
+ message = exc.response.text.strip()
582
+ return (
583
+ f"{status} {message}" if message else f"{status} {exc.response.reason_phrase}"
584
+ )
585
+
586
+
587
+ def _run_op(
588
+ op: Write,
589
+ *,
590
+ discipline: str,
591
+ course: str,
592
+ client: httpx.Client,
593
+ repositories: RepositoryApi,
594
+ blobs: _AttachmentBlobs,
595
+ ) -> OpResult:
596
+ match op:
597
+ case UpsertCourse():
598
+ return _run_upsert_course(op, client=client)
599
+ case UpsertRepository():
600
+ return run_upsert_repository(op, repositories)
601
+ case DeleteRepository():
602
+ return run_delete_repository(op, repositories)
603
+ case UpsertResource():
604
+ return _run_upsert_resource(
605
+ op, discipline=discipline, course=course, client=client
606
+ )
607
+ case DeleteResource():
608
+ return _run_delete_resource(
609
+ op, discipline=discipline, course=course, client=client
610
+ )
611
+ case UpsertQuestion():
612
+ return _run_upsert_question(
613
+ op, discipline=discipline, course=course, client=client, blobs=blobs
614
+ )
615
+ case DeleteQuestion():
616
+ return _run_delete_question(
617
+ op, discipline=discipline, course=course, client=client
618
+ )
619
+ case UpsertExam():
620
+ return _run_upsert_exam(
621
+ op, discipline=discipline, course=course, client=client, blobs=blobs
622
+ )
623
+ case DeleteExam():
624
+ return _run_delete_exam(
625
+ op, discipline=discipline, course=course, client=client
626
+ )
627
+ case UpsertTimeSlot():
628
+ return _run_upsert_time_slot(
629
+ op, discipline=discipline, course=course, client=client
630
+ )
631
+ case DeleteTimeSlot():
632
+ return _run_delete_time_slot(
633
+ op, discipline=discipline, course=course, client=client
634
+ )
635
+ case UpsertCalendarEvent():
636
+ return _run_upsert_calendar_event(
637
+ op, discipline=discipline, course=course, client=client
638
+ )
639
+ case DeleteCalendarEvent():
640
+ return _run_delete_calendar_event(
641
+ op, discipline=discipline, course=course, client=client
642
+ )
643
+ case DeleteRollCall():
644
+ return _run_delete_roll_call(
645
+ op, discipline=discipline, course=course, client=client
646
+ )
647
+ case UpsertGradeColumn():
648
+ return _run_upsert_grade_column(
649
+ op, discipline=discipline, course=course, client=client
650
+ )
651
+ case DeleteGradeColumn():
652
+ return _run_delete_grade_column(
653
+ op, discipline=discipline, course=course, client=client
654
+ )
655
+
656
+
657
+ def run_upsert_repository(op: UpsertRepository, api: RepositoryApi) -> OpResult:
658
+ """
659
+ Push one repository: upsert it, ask which blobs are missing, upload
660
+ those in batches of at most `MAX_FILE_BYTES` (`batch_entries`), then
661
+ commit the tree.
662
+
663
+ A failed step stops the op and reports it; nothing after it runs. The
664
+ message says how many files were uploaded and the new head.
665
+ """
666
+ slug = op.tree.slug
667
+ entries = op.tree.entries
668
+ uploaded = 0
669
+ try:
670
+ api.upsert(slug)
671
+ hashes = list(dict.fromkeys(entry.sha256 for entry in entries))
672
+ missing = set(api.missing(hashes))
673
+ pending = [entry for entry in entries if entry.sha256 in missing]
674
+ for batch in batch_entries(_unique_blobs(pending)):
675
+ api.upload(slug, batch)
676
+ uploaded += len(batch)
677
+ head = api.commit(slug, entries, op.message)
678
+ except (CodehoodAPIError, httpx.HTTPStatusError) as exc:
679
+ return OpResult(op=op, ok=False, message=f"failed: {describe_failure(exc)}")
680
+ return OpResult(
681
+ op=op,
682
+ ok=True,
683
+ message=f"uploaded {uploaded} file(s), head {head}"
684
+ if head
685
+ else f"uploaded {uploaded} file(s)",
686
+ )
687
+
688
+
689
+ def run_delete_repository(op: DeleteRepository, api: RepositoryApi) -> OpResult:
690
+ """
691
+ Delete one repository, reporting a refused request as a failed result.
692
+ """
693
+ try:
694
+ api.delete(op.slug)
695
+ except (CodehoodAPIError, httpx.HTTPStatusError) as exc:
696
+ return OpResult(op=op, ok=False, message=f"failed: {describe_failure(exc)}")
697
+ return OpResult(op=op, ok=True, message=f"deleted {op.slug}")
698
+
699
+
700
+ def _unique_blobs(entries: Sequence[RepositoryEntry]) -> list[RepositoryEntry]:
701
+ """
702
+ One entry per distinct content: a part name may not repeat in an upload.
703
+ """
704
+ return list({entry.sha256: entry for entry in entries}.values())
705
+
706
+
707
+ def _run_upsert_course(op: UpsertCourse, *, client: httpx.Client) -> OpResult:
708
+ """
709
+ `PUT /api/course`, which takes the whole natural key in its body.
710
+
711
+ The course is addressed by `{instructor}_{edition}` everywhere else.
712
+ """
713
+ body = generated.CourseCreate(
714
+ discipline=op.key.discipline,
715
+ instructor=op.key.instructor,
716
+ edition=op.key.edition,
717
+ description=op.description,
718
+ startDate=op.start_date,
719
+ endDate=op.end_date,
720
+ rev=op.ref,
721
+ )
722
+ try:
723
+ stored = generated.upsert_course(body=body, client=client)
724
+ except (CodehoodAPIError, httpx.HTTPStatusError) as exc:
725
+ return OpResult(op=op, ok=False, message=f"failed: {describe_failure(exc)}")
726
+ return _stamp(op, stored, f"upserted course {op.discipline}/{op.course}")
727
+
728
+
729
+ def _run_upsert_resource(
730
+ op: UpsertResource, *, discipline: str, course: str, client: httpx.Client
731
+ ) -> OpResult:
732
+ body = generated.ResourceCreate(
733
+ slug=op.slug,
734
+ title=op.title,
735
+ description=op.description,
736
+ rev=op.ref,
737
+ event=(
738
+ generated.Event(week=op.event.week, timeSlot=op.event.time_slot)
739
+ if op.event is not None
740
+ else None
741
+ ),
742
+ data=_request_data(op.data),
743
+ )
744
+ try:
745
+ if isinstance(op.data, FileData) and _blob_missing(op.data, client):
746
+ stored: object = _upsert_resource_with_file(
747
+ body, op.data, discipline=discipline, course=course, client=client
748
+ )
749
+ else:
750
+ stored = generated.upsert_resource(
751
+ discipline=discipline, course=course, body=body, client=client
752
+ )
753
+ except (CodehoodAPIError, httpx.HTTPStatusError) as exc:
754
+ message = f"failed: {describe_failure(exc)}"
755
+ # Events go out before resources, so the lesson already links here.
756
+ if op.event is not None:
757
+ message += (
758
+ f"; event {op.event.week}/{op.event.time_slot} links to it, "
759
+ "and the link is broken until it uploads"
760
+ )
761
+ return OpResult(op=op, ok=False, message=message)
762
+ return _stamp(op, stored, f"upserted {op.slug}")
763
+
764
+
765
+ def _blob_missing(data: FileData, client: httpx.Client) -> bool:
766
+ """
767
+ Whether the server lacks the bytes of `data`, per `POST /api/blob/missing`.
768
+ """
769
+ result = generated.blob_missing(
770
+ body=generated.BlobMissingInput(hashes=[data.sha256]), client=client
771
+ )
772
+ return data.sha256 in result.missing
773
+
774
+
775
+ def _upsert_resource_with_file(
776
+ body: generated.ResourceCreate,
777
+ data: FileData,
778
+ *,
779
+ discipline: str,
780
+ course: str,
781
+ client: httpx.Client,
782
+ ) -> _Stored:
783
+ """
784
+ `PUT .../resource` as multipart: the JSON body in a `json` part and the
785
+ file's bytes in a part named by its sha-256.
786
+
787
+ Hand-written because the generator only builds JSON bodies. Returns the
788
+ `rev` and `updatedAt` of the stored resource.
789
+ """
790
+ url = "/api/course/{}/{}/resource".format(
791
+ quote(discipline, safe=""), quote(course, safe="")
792
+ )
793
+ payload = body.model_dump_json(by_alias=True)
794
+ # Built apart from the client: its default `Content-Type: application/json`
795
+ # would hide the multipart boundary `httpx` computes.
796
+ request = httpx.Request(
797
+ "PUT",
798
+ client.base_url.join(url),
799
+ data={"json": payload},
800
+ files=[(data.sha256, (data.filename, data.blob, "application/octet-stream"))],
801
+ headers=auth_headers(client),
802
+ )
803
+ response = client.send(request)
804
+ response.raise_for_status()
805
+ return _Stored.of(response)
806
+
807
+
808
+ def _run_delete_resource(
809
+ op: DeleteResource, *, discipline: str, course: str, client: httpx.Client
810
+ ) -> OpResult:
811
+ try:
812
+ generated.delete_resource(
813
+ discipline=discipline, course=course, slug=op.slug, client=client
814
+ )
815
+ except (CodehoodAPIError, httpx.HTTPStatusError) as exc:
816
+ return OpResult(op=op, ok=False, message=f"failed: {describe_failure(exc)}")
817
+ return OpResult(op=op, ok=True, message=f"deleted {op.slug}")
818
+
819
+
820
+ def _run_upsert_question(
821
+ op: UpsertQuestion,
822
+ *,
823
+ discipline: str,
824
+ course: str,
825
+ client: httpx.Client,
826
+ blobs: _AttachmentBlobs,
827
+ ) -> OpResult:
828
+ payload = wire_question(op.question)
829
+
830
+ # `model_validate` would round-trip `payload` through one of the
831
+ # generated union members, and that member fills every absent optional
832
+ # field back in as an explicit `None` -- which the server's schema
833
+ # rejects (`expected string, received null`), undoing the
834
+ # `exclude_none` above. `model_construct` skips validation and keeps
835
+ # `question` as the plain dict `generated.upsert_question`'s own
836
+ # `model_dump(by_alias=True)` then serializes verbatim.
837
+ body = generated.QuestionCreate.model_construct(
838
+ slug=op.slug,
839
+ status=op.status,
840
+ version=op.version,
841
+ rev=op.version,
842
+ question=payload,
843
+ )
844
+ try:
845
+ with warnings.catch_warnings():
846
+ # Pydantic warns that `question` (a plain dict, on purpose --
847
+ # see above) doesn't look like the union member it's typed as.
848
+ # The dict is exactly the payload we mean to send, so this is
849
+ # noise, not a signal.
850
+ warnings.simplefilter("ignore", UserWarning)
851
+ # Sent by hand: the body may carry `files`, and the answer needs
852
+ # only the `rev` and `updatedAt`.
853
+ stored = _put_with_blobs(
854
+ f"/api/course/{quote(discipline, safe='')}/"
855
+ f"{quote(course, safe='')}/question",
856
+ {
857
+ **body.model_dump(mode="json", by_alias=True, exclude={"files"}),
858
+ **({"files": op.files} if op.files else {}),
859
+ },
860
+ op.files,
861
+ op.blobs,
862
+ blobs,
863
+ client,
864
+ )
865
+ except (CodehoodAPIError, httpx.HTTPStatusError) as exc:
866
+ return _failed(op, exc, op.files, op.blobs)
867
+ return _stamp(op, stored, f"upserted {op.slug}")
868
+
869
+
870
+ @dataclass
871
+ class _AttachmentBlobs:
872
+ """
873
+ The attachment hashes a push cites and what the server says about them.
874
+
875
+ One `POST /api/blob/missing` answers for the whole push, asked before the
876
+ first write that cites a hash; each missing blob rides with the first
877
+ `PUT` that cites it.
878
+ """
879
+
880
+ hashes: tuple[str, ...]
881
+ _missing: set[str] | None = None
882
+ _sent: set[str] = field(default_factory=set)
883
+
884
+ @classmethod
885
+ def of(cls, ops: Iterable[Write]) -> _AttachmentBlobs:
886
+ """
887
+ The hashes cited by the questions and exams among `ops`, once each.
888
+ """
889
+ found: dict[str, None] = {}
890
+ for op in ops:
891
+ if isinstance(op, UpsertQuestion):
892
+ found.update(dict.fromkeys(op.files.values()))
893
+ elif isinstance(op, UpsertExam):
894
+ found.update(dict.fromkeys(_files_of(op.payload).values()))
895
+ return cls(tuple(found))
896
+
897
+ def to_send(self, hashes: Iterable[str], client: httpx.Client) -> list[str]:
898
+ """
899
+ The hashes among `hashes` the server lacks and no `PUT` has carried yet.
900
+
901
+ Raises:
902
+ CodehoodAPIError: `POST /api/blob/missing` failed.
903
+ httpx.HTTPStatusError: `POST /api/blob/missing` failed.
904
+ """
905
+ if self._missing is None:
906
+ result = generated.blob_missing(
907
+ body=generated.BlobMissingInput(hashes=list(self.hashes)),
908
+ client=client,
909
+ )
910
+ self._missing = set(result.missing)
911
+ return [h for h in dict.fromkeys(hashes) if h in self._missing - self._sent]
912
+
913
+ def sent(self, hashes: Iterable[str]) -> None:
914
+ """
915
+ Record that a `PUT` carried the bytes of `hashes`.
916
+ """
917
+ self._sent.update(hashes)
918
+
919
+
920
+ def _files_of(payload: Mapping[str, JsonValue]) -> dict[str, str]:
921
+ """
922
+ The `files` of an exam payload: attachment name -> sha-256.
923
+ """
924
+ files = payload.get("files")
925
+ if not isinstance(files, dict):
926
+ return {}
927
+ return {name: h for name, h in files.items() if isinstance(h, str)}
928
+
929
+
930
+ def _put_with_blobs(
931
+ url: str,
932
+ body: Mapping[str, object],
933
+ files: Mapping[str, str],
934
+ paths: Mapping[str, Path],
935
+ blobs: _AttachmentBlobs,
936
+ client: httpx.Client,
937
+ ) -> _Stored:
938
+ """
939
+ `PUT` `body`, as multipart with the bytes of the blobs the server lacks
940
+ when there are any, as JSON when there are none.
941
+
942
+ Multipart has the JSON in a `json` part and each blob in a part named by
943
+ its sha-256, as `_upsert_resource_with_file` does.
944
+ """
945
+ names = {h: name for name, h in files.items()}
946
+ pending = blobs.to_send(files.values(), client) if files else []
947
+ if pending:
948
+ # Built apart from the client: its default `Content-Type` would hide
949
+ # the multipart boundary `httpx` computes.
950
+ request = httpx.Request(
951
+ "PUT",
952
+ client.base_url.join(url),
953
+ data={"json": json.dumps(body)},
954
+ files=[
955
+ (h, (names[h], paths[h].read_bytes(), "application/octet-stream"))
956
+ for h in pending
957
+ ],
958
+ headers=auth_headers(client),
959
+ )
960
+ response = client.send(request)
961
+ else:
962
+ response = client.put(url, json=body, headers=auth_headers(client))
963
+ response.raise_for_status()
964
+ blobs.sent(pending)
965
+ return _Stored.of(response)
966
+
967
+
968
+ def _failed(
969
+ op: Write,
970
+ exc: CodehoodAPIError | httpx.HTTPStatusError,
971
+ files: Mapping[str, str],
972
+ paths: Mapping[str, Path],
973
+ ) -> OpResult:
974
+ """
975
+ A failed result; a `413` also states the limit and the largest file.
976
+ """
977
+ message = f"failed: {describe_failure(exc)}"
978
+ if (
979
+ isinstance(exc, httpx.HTTPStatusError)
980
+ and exc.response.status_code == 413
981
+ and files
982
+ ):
983
+ name, size = max(
984
+ ((n, paths[h].stat().st_size) for n, h in files.items() if h in paths),
985
+ key=lambda item: item[1],
986
+ default=("", 0),
987
+ )
988
+ limit = MAX_UPLOAD_BYTES // (1024 * 1024)
989
+ message += f" (the server takes at most {limit} MiB per request"
990
+ message += f"; largest file: {name}, {size} bytes)" if name else ")"
991
+ return OpResult(op=op, ok=False, message=message)
992
+
993
+
994
+ def _run_delete_question(
995
+ op: DeleteQuestion, *, discipline: str, course: str, client: httpx.Client
996
+ ) -> OpResult:
997
+ try:
998
+ generated.delete_question(
999
+ discipline=discipline, course=course, slug=op.slug, client=client
1000
+ )
1001
+ except (CodehoodAPIError, httpx.HTTPStatusError) as exc:
1002
+ return OpResult(op=op, ok=False, message=f"failed: {describe_failure(exc)}")
1003
+ return OpResult(op=op, ok=True, message=f"deleted {op.slug}")
1004
+
1005
+
1006
+ def _run_upsert_exam(
1007
+ op: UpsertExam,
1008
+ *,
1009
+ discipline: str,
1010
+ course: str,
1011
+ client: httpx.Client,
1012
+ blobs: _AttachmentBlobs,
1013
+ ) -> OpResult:
1014
+ # Sent as plain JSON: the generated body would put an explicit `null` on
1015
+ # the wire for `duration` and `scheduledAt`, which the server may hold
1016
+ # from an instructor action and a push must never blank.
1017
+ body = {**op.payload, "status": op.status, "rev": op.rev}
1018
+ files = _files_of(op.payload)
1019
+ try:
1020
+ stored = _put_with_blobs(
1021
+ f"/api/course/{discipline}/{course}/exam",
1022
+ body,
1023
+ files,
1024
+ op.blobs,
1025
+ blobs,
1026
+ client,
1027
+ )
1028
+ except (CodehoodAPIError, httpx.HTTPStatusError) as exc:
1029
+ return _failed(op, exc, files, op.blobs)
1030
+ return OpResult(
1031
+ op=op,
1032
+ ok=True,
1033
+ message=f"upserted {op.slug}",
1034
+ rev=stored.rev,
1035
+ updated_at=stored.updated_at,
1036
+ )
1037
+
1038
+
1039
+ def _run_delete_exam(
1040
+ op: DeleteExam, *, discipline: str, course: str, client: httpx.Client
1041
+ ) -> OpResult:
1042
+ try:
1043
+ generated.delete_exam(
1044
+ discipline=discipline, course=course, slug=op.slug, client=client
1045
+ )
1046
+ except (CodehoodAPIError, httpx.HTTPStatusError) as exc:
1047
+ return OpResult(op=op, ok=False, message=f"failed: {describe_failure(exc)}")
1048
+ return OpResult(op=op, ok=True, message=f"deleted {op.slug}")
1049
+
1050
+
1051
+ def _run_upsert_time_slot(
1052
+ op: UpsertTimeSlot, *, discipline: str, course: str, client: httpx.Client
1053
+ ) -> OpResult:
1054
+ body = generated.TimeSlotCreate.model_validate(time_slot_payload(op.slot))
1055
+ try:
1056
+ stored = generated.upsert_timeslot(
1057
+ discipline=discipline, course=course, body=body, client=client
1058
+ )
1059
+ except (CodehoodAPIError, httpx.HTTPStatusError) as exc:
1060
+ return OpResult(op=op, ok=False, message=f"failed: {describe_failure(exc)}")
1061
+ return _stamp(op, stored, f"upserted {op.slot.slug}")
1062
+
1063
+
1064
+ def _run_delete_time_slot(
1065
+ op: DeleteTimeSlot, *, discipline: str, course: str, client: httpx.Client
1066
+ ) -> OpResult:
1067
+ try:
1068
+ generated.delete_timeslot(
1069
+ discipline=discipline, course=course, slug=op.slug, client=client
1070
+ )
1071
+ except (CodehoodAPIError, httpx.HTTPStatusError) as exc:
1072
+ return OpResult(op=op, ok=False, message=f"failed: {describe_failure(exc)}")
1073
+ return OpResult(op=op, ok=True, message=f"deleted {op.slug}")
1074
+
1075
+
1076
+ def _run_upsert_calendar_event(
1077
+ op: UpsertCalendarEvent, *, discipline: str, course: str, client: httpx.Client
1078
+ ) -> OpResult:
1079
+ body = generated.CalendarEventCreate.model_validate(
1080
+ {**event_payload(op.event), "rev": op.event.ref}
1081
+ )
1082
+ try:
1083
+ stored = generated.upsert_calendar_event(
1084
+ discipline=discipline, course=course, body=body, client=client
1085
+ )
1086
+ except (CodehoodAPIError, httpx.HTTPStatusError) as exc:
1087
+ return OpResult(op=op, ok=False, message=f"failed: {describe_failure(exc)}")
1088
+ return _stamp(op, stored, f"upserted {op.event.week}/{op.event.time_slot}")
1089
+
1090
+
1091
+ def _run_delete_calendar_event(
1092
+ op: DeleteCalendarEvent, *, discipline: str, course: str, client: httpx.Client
1093
+ ) -> OpResult:
1094
+ try:
1095
+ generated.delete_calendar_event(
1096
+ discipline=discipline,
1097
+ course=course,
1098
+ week=str(op.week),
1099
+ time_slot=op.time_slot,
1100
+ client=client,
1101
+ )
1102
+ except (CodehoodAPIError, httpx.HTTPStatusError) as exc:
1103
+ return OpResult(op=op, ok=False, message=f"failed: {describe_failure(exc)}")
1104
+ return OpResult(op=op, ok=True, message=f"deleted {op.week}/{op.time_slot}")
1105
+
1106
+
1107
+ def _run_delete_roll_call(
1108
+ op: DeleteRollCall, *, discipline: str, course: str, client: httpx.Client
1109
+ ) -> OpResult:
1110
+ try:
1111
+ generated.delete_roll_call(
1112
+ discipline=discipline,
1113
+ course=course,
1114
+ week=str(op.week),
1115
+ time_slot=op.time_slot,
1116
+ client=client,
1117
+ )
1118
+ except (CodehoodAPIError, httpx.HTTPStatusError) as exc:
1119
+ return OpResult(op=op, ok=False, message=f"failed: {describe_failure(exc)}")
1120
+ return OpResult(op=op, ok=True, message=f"deleted {op.week}/{op.time_slot}")
1121
+
1122
+
1123
+ def _run_upsert_grade_column(
1124
+ op: UpsertGradeColumn, *, discipline: str, course: str, client: httpx.Client
1125
+ ) -> OpResult:
1126
+ column = op.column
1127
+ body = generated.GradeColumnCreate.model_validate(
1128
+ {**grade_column_payload(column), "rev": column.rev}
1129
+ )
1130
+ try:
1131
+ stored = generated.upsert_grade_column(
1132
+ discipline=discipline, course=course, body=body, client=client
1133
+ )
1134
+ except (CodehoodAPIError, httpx.HTTPStatusError) as exc:
1135
+ return OpResult(op=op, ok=False, message=f"failed: {describe_failure(exc)}")
1136
+ return _stamp(op, stored, f"upserted {column.slug} ({len(column.values)} values)")
1137
+
1138
+
1139
+ def _run_delete_grade_column(
1140
+ op: DeleteGradeColumn, *, discipline: str, course: str, client: httpx.Client
1141
+ ) -> OpResult:
1142
+ try:
1143
+ generated.delete_grade_column(
1144
+ discipline=discipline, course=course, slug=op.slug, client=client
1145
+ )
1146
+ except (CodehoodAPIError, httpx.HTTPStatusError) as exc:
1147
+ return OpResult(op=op, ok=False, message=f"failed: {describe_failure(exc)}")
1148
+ return OpResult(op=op, ok=True, message=f"deleted {op.slug}")
1149
+
1150
+
1151
+ def _server_student(item: generated.CourseGradesResponseStudentsItem) -> ServerStudent:
1152
+ """
1153
+ Project one student of the grades report into what the core computes
1154
+ from, with each exam total turned into the percentage the web shows.
1155
+ """
1156
+ exams: dict[str, ExamResult] = {}
1157
+ for slug, cell in item.results.items():
1158
+ total = getattr(cell, "total", None)
1159
+ exams[slug] = ExamResult(
1160
+ score=None if total is None else round(total * 100, 2),
1161
+ state=EXAM_STATES[cell.kind],
1162
+ )
1163
+ return ServerStudent(
1164
+ username=item.username,
1165
+ name=item.name,
1166
+ email=item.email,
1167
+ school_id=item.school_id,
1168
+ github=item.github_id,
1169
+ status="active" if item.status == "ACTIVE" else "dropped",
1170
+ exams=exams,
1171
+ )
1172
+
1173
+
1174
+ def _server_event(
1175
+ item: generated.CalendarEvent, attendances: int | None
1176
+ ) -> ServerEvent:
1177
+ """
1178
+ Project one item of the calendar-event listing down to its markers and
1179
+ its payload.
1180
+
1181
+ `attendances` is the size of the event's roll call, `None` without one.
1182
+ """
1183
+ return ServerEvent(
1184
+ ref=item.rev or "",
1185
+ kind=item.kind,
1186
+ attendances=attendances,
1187
+ entry=RemoteEntry(
1188
+ project_calendar_event(item), rev=item.rev, updated_at=item.updated_at
1189
+ ),
1190
+ )
1191
+
1192
+
1193
+ def _list_questions(
1194
+ discipline: str, course: str, client: httpx.Client
1195
+ ) -> list[dict[str, JsonValue]]:
1196
+ """
1197
+ `GET .../question` as plain JSON, with the live statuses only.
1198
+
1199
+ Not `generated.list_question`: its models drop the fields of a question
1200
+ type they do not declare, and the payload compares the whole document.
1201
+ `deleteQuestion` archives rather than removes a row -- see
1202
+ `ROADBLOCKS.md` -- so an archived question would otherwise look
1203
+ "current" forever and get re-planned for deletion on every push.
1204
+ Filtering to the live statuses keeps a deleted question gone for good,
1205
+ which is what `plan_sync`'s convergence (a second push plans nothing)
1206
+ requires.
1207
+ """
1208
+ return read_all(_question_page, discipline, course, client)
1209
+
1210
+
1211
+ class _QuestionPage(Model):
1212
+ """
1213
+ One page of `GET .../question`, its items kept as plain JSON.
1214
+ """
1215
+
1216
+ items: list[dict[str, JsonValue]]
1217
+ next: str | None
1218
+
1219
+
1220
+ def _question_page(
1221
+ discipline: str, course: str, client: httpx.Client, after: str | None = None
1222
+ ) -> _QuestionPage:
1223
+ """
1224
+ One page of `GET .../question` with the live statuses, starting after `after`.
1225
+
1226
+ Raises:
1227
+ httpx.HTTPStatusError: When the server refuses the request.
1228
+ """
1229
+ response = client.get(
1230
+ f"/api/course/{discipline}/{course}/question",
1231
+ params=query_params(
1232
+ {"statuses": ["DRAFT", "PUBLISHED", "HIDDEN"], "after": after}
1233
+ ),
1234
+ headers=auth_headers(client),
1235
+ )
1236
+ response.raise_for_status()
1237
+ return _QuestionPage.model_validate(response.json())
1238
+
1239
+
1240
+ def _server_question(item: dict[str, JsonValue]) -> ServerQuestion:
1241
+ """
1242
+ One item of the question listing, as its version, status and payload.
1243
+
1244
+ A question the server holds without a `rev` keeps it null: the planner
1245
+ decides what that means.
1246
+ """
1247
+ status = cast(QuestionStatus, item["status"])
1248
+ rev, updated_at = item.get("rev"), item.get("updatedAt")
1249
+ version = str(item["version"])
1250
+ return ServerQuestion(
1251
+ version=version,
1252
+ status=status,
1253
+ entry=RemoteEntry(
1254
+ project_question(item),
1255
+ rev=rev if isinstance(rev, str) else None,
1256
+ updated_at=updated_at if isinstance(updated_at, str) else None,
1257
+ ),
1258
+ )
1259
+
1260
+
1261
+ def _request_data(data: ResourceData) -> RequestData:
1262
+ """
1263
+ Translate the core's `ResourceData` into the generated union member.
1264
+ """
1265
+ match data:
1266
+ case MdData(content=content):
1267
+ return generated.DataMd(type="MD", content=content)
1268
+ case CodeData(content=content, language=language):
1269
+ return generated.DataCode(type="CODE", content=content, language=language)
1270
+ case FileData(filename=filename):
1271
+ return generated.ResourceCreateDataFile(
1272
+ type="FILE", filename=filename, hash=data.sha256
1273
+ )
1274
+ case LinkData(url=url):
1275
+ return generated.DataLink(type="LINK", url=url)