studysystem 1.0.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 (112) hide show
  1. studysystem/__init__.py +1 -0
  2. studysystem/assets/note-callouts.lua +100 -0
  3. studysystem/assets/note-no-html.lua +28 -0
  4. studysystem/assets/note.css +146 -0
  5. studysystem/cli.py +344 -0
  6. studysystem/dashboard.html +781 -0
  7. studysystem/dashboard.py +377 -0
  8. studysystem/db/__init__.py +1 -0
  9. studysystem/db/engine.py +158 -0
  10. studysystem/db/migrate.py +122 -0
  11. studysystem/db/migrations/env.py +59 -0
  12. studysystem/db/migrations/script.py.mako +29 -0
  13. studysystem/db/migrations/versions/0000_baseline.py +19 -0
  14. studysystem/db/migrations/versions/0001_the_whole_schema.py +1743 -0
  15. studysystem/db/migrations/versions/0002_semester_ignores_case.py +38 -0
  16. studysystem/db/migrations/versions/0003_course_vault_folder.py +26 -0
  17. studysystem/db/migrations/versions/0004_note_pdf_path.py +26 -0
  18. studysystem/db/migrations/versions/0005_tagging_kind.py +39 -0
  19. studysystem/db/migrations/versions/0006_practice_mode.py +36 -0
  20. studysystem/db/migrations/versions/0007_exam_prep_from.py +25 -0
  21. studysystem/db/migrations/versions/0008_more_papers_kind.py +37 -0
  22. studysystem/db/migrations/versions/0009_past_exam_month_date.py +28 -0
  23. studysystem/db/migrations/versions/0010_task_parts.py +70 -0
  24. studysystem/db/migrations/versions/0011_observation_kind.py +39 -0
  25. studysystem/db/migrations/versions/0012_profile_claim.py +52 -0
  26. studysystem/db/migrations/versions/0013_assumed_instructor_papers.py +40 -0
  27. studysystem/db/migrations/versions/0014_scan_confirmation.py +44 -0
  28. studysystem/db/migrations/versions/0015_practice_item_count.py +37 -0
  29. studysystem/db/migrations/versions/0016_timetable_patterns.py +102 -0
  30. studysystem/db/migrations/versions/0017_course_dropped.py +36 -0
  31. studysystem/db/migrations/versions/0018_syllabus_topics.py +82 -0
  32. studysystem/db/migrations/versions/0019_course_lab_group.py +36 -0
  33. studysystem/db/migrations/versions/0020_chapter_scope.py +61 -0
  34. studysystem/db/migrations/versions/0021_note_retired_at.py +28 -0
  35. studysystem/db/migrations/versions/0022_rescope.py +48 -0
  36. studysystem/db/migrations/versions/0023_backlog_reason.py +42 -0
  37. studysystem/db/migrations/versions/0024_guess_sensitivity.py +35 -0
  38. studysystem/db/migrations/versions/0025_shortfall_inputs.py +83 -0
  39. studysystem/db/migrations/versions/0026_trials_switch.py +36 -0
  40. studysystem/db/tables.py +1096 -0
  41. studysystem/demo.py +722 -0
  42. studysystem/errors.py +39 -0
  43. studysystem/server/__init__.py +83 -0
  44. studysystem/server/__main__.py +5 -0
  45. studysystem/services/__init__.py +1 -0
  46. studysystem/services/adherence.py +147 -0
  47. studysystem/services/assessments.py +171 -0
  48. studysystem/services/capacity.py +164 -0
  49. studysystem/services/claims.py +405 -0
  50. studysystem/services/course_folder.py +82 -0
  51. studysystem/services/courses.py +176 -0
  52. studysystem/services/coverage.py +121 -0
  53. studysystem/services/dashboard_key.py +102 -0
  54. studysystem/services/feedback.py +412 -0
  55. studysystem/services/forward_eval.py +65 -0
  56. studysystem/services/gate.py +77 -0
  57. studysystem/services/generation.py +2864 -0
  58. studysystem/services/ids.py +15 -0
  59. studysystem/services/intake.py +278 -0
  60. studysystem/services/launcher.py +455 -0
  61. studysystem/services/lookups.py +91 -0
  62. studysystem/services/materials.py +97 -0
  63. studysystem/services/note_markdown.py +241 -0
  64. studysystem/services/notes.py +396 -0
  65. studysystem/services/parts.py +65 -0
  66. studysystem/services/past_exams.py +115 -0
  67. studysystem/services/pdf_render.py +148 -0
  68. studysystem/services/pdf_worker.py +184 -0
  69. studysystem/services/plan.py +1300 -0
  70. studysystem/services/private_view.py +38 -0
  71. studysystem/services/profiles.py +544 -0
  72. studysystem/services/programs.py +16 -0
  73. studysystem/services/replacements.py +107 -0
  74. studysystem/services/rescope.py +277 -0
  75. studysystem/services/settings.py +50 -0
  76. studysystem/services/setup.py +235 -0
  77. studysystem/services/shortfall.py +443 -0
  78. studysystem/services/state.py +846 -0
  79. studysystem/services/statements.py +222 -0
  80. studysystem/services/study_loop.py +998 -0
  81. studysystem/services/summaries.py +369 -0
  82. studysystem/services/syllabus.py +138 -0
  83. studysystem/services/system_work.py +113 -0
  84. studysystem/services/taxonomy.py +459 -0
  85. studysystem/services/topics.py +477 -0
  86. studysystem/services/trials.py +201 -0
  87. studysystem/services/unconfirmed.py +95 -0
  88. studysystem/services/units.py +34 -0
  89. studysystem/services/users.py +53 -0
  90. studysystem/services/values.py +168 -0
  91. studysystem/startup.py +147 -0
  92. studysystem/tools/__init__.py +4 -0
  93. studysystem/tools/course_setup.py +185 -0
  94. studysystem/tools/dashboard.py +27 -0
  95. studysystem/tools/feedback.py +66 -0
  96. studysystem/tools/gate.py +24 -0
  97. studysystem/tools/generation.py +156 -0
  98. studysystem/tools/materials.py +32 -0
  99. studysystem/tools/notes.py +29 -0
  100. studysystem/tools/past_exams.py +51 -0
  101. studysystem/tools/ping.py +9 -0
  102. studysystem/tools/plan.py +40 -0
  103. studysystem/tools/profiles.py +94 -0
  104. studysystem/tools/results.py +77 -0
  105. studysystem/tools/study_loop.py +145 -0
  106. studysystem/tools/summaries.py +52 -0
  107. studysystem/tools/topics.py +143 -0
  108. studysystem-1.0.0.dist-info/METADATA +254 -0
  109. studysystem-1.0.0.dist-info/RECORD +112 -0
  110. studysystem-1.0.0.dist-info/WHEEL +4 -0
  111. studysystem-1.0.0.dist-info/entry_points.txt +3 -0
  112. studysystem-1.0.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,377 @@
1
+ """The dashboard front door (D-17, D-19): an HTTP route beside the MCP server, in a process of its
2
+ own (`study dashboard`), so it serves and writes with no host open. It calls the services the tools
3
+ call - one set of write rules, two entrances - and an error leaves in the same D-17 dict.
4
+
5
+ No login in v1 (D-05). What stands in for one is D-162: the route listens on 127.0.0.1 only; a
6
+ write must be JSON, so a page on another site has to ask the browser's permission first and is
7
+ never given it; and every request must name our own host, so a site that re-points its name to
8
+ 127.0.0.1 is refused too.
9
+ """
10
+
11
+ import datetime
12
+ import importlib.metadata
13
+ import json
14
+ import logging
15
+ import os
16
+ import signal
17
+ import sys
18
+ from collections.abc import Callable
19
+ from pathlib import Path
20
+
21
+ import uvicorn
22
+ from sqlalchemy import Engine
23
+ from sqlalchemy.exc import OperationalError
24
+ from starlette.applications import Starlette
25
+ from starlette.concurrency import run_in_threadpool
26
+ from starlette.middleware import Middleware
27
+ from starlette.middleware.base import BaseHTTPMiddleware, RequestResponseEndpoint
28
+ from starlette.requests import Request
29
+ from starlette.responses import HTMLResponse, JSONResponse, Response
30
+ from starlette.routing import Route
31
+
32
+ from studysystem.db.migrate import current_revision
33
+ from studysystem.errors import StudyError, busy
34
+ from studysystem.services import (
35
+ capacity,
36
+ dashboard_key,
37
+ feedback,
38
+ launcher,
39
+ state,
40
+ study_loop,
41
+ trials,
42
+ values,
43
+ )
44
+ from studysystem.services.users import current_user
45
+ from studysystem.startup import call_check, open_database
46
+
47
+ HOST = "127.0.0.1"
48
+ PAGE = Path(__file__).with_name("dashboard.html")
49
+ OWN_HOSTS = {"127.0.0.1", "localhost"}
50
+
51
+ # Any code not listed is the caller's to fix, so 400.
52
+ STATUS = {
53
+ "not_found": 404,
54
+ "wrong_host": 403,
55
+ "not_json": 415,
56
+ "no_user": 500,
57
+ "too_many_users": 500,
58
+ "database_busy": 503,
59
+ "database_missing": 503,
60
+ "database_unavailable": 503,
61
+ "schema_behind_head": 503,
62
+ "schema_ahead_of_head": 503,
63
+ "dashboard_locked": 401,
64
+ "session_ended": 409,
65
+ "session_expired": 409,
66
+ }
67
+
68
+ # These three answer on any schema (D-338): the page shows why the data routes refuse,
69
+ # `launcher.answering` reads /health to know the dashboard is up, and an upgrade must be able to
70
+ # stop it (D-342).
71
+ UNCHECKED_PATHS = {"/", "/health", "/shutdown", "/open"}
72
+
73
+ # No key needed (D-369): the page holds no data, /health names two versions, and /open takes a
74
+ # one-time code in place of the key.
75
+ KEYLESS_PATHS = {"/", "/health", "/open"}
76
+
77
+ # On every reply. No other page may show the dashboard inside itself, where a click meant for that
78
+ # page would land here. The page loads nothing from another address, so nothing else is allowed.
79
+ HEADERS = {
80
+ "Content-Security-Policy": "default-src 'none'; script-src 'unsafe-inline'; "
81
+ "style-src 'unsafe-inline'; img-src 'self' data:; font-src 'self' data:; connect-src 'self'; "
82
+ "base-uri 'none'; form-action 'none'; frame-ancestors 'none'",
83
+ "X-Frame-Options": "DENY",
84
+ "X-Content-Type-Options": "nosniff",
85
+ "Referrer-Policy": "no-referrer",
86
+ "Cache-Control": "no-store",
87
+ }
88
+
89
+ MAX_BODY = 100_000 # bytes; the longest write is a reason the student types
90
+
91
+ # How long a stop waits before it ends the process anyway (D-343). A write waits 5 s for a locked
92
+ # database, and `study stop` waits 15 s (launcher.WAIT_SECONDS).
93
+ STOP_SECONDS = 8
94
+
95
+ # Each write's service arguments, by the same names: study_log_hours's, study_start_session's,
96
+ # and the timer's stop (D-198).
97
+ HOURS_FIELDS = (
98
+ "code",
99
+ "minutes",
100
+ "topic_id",
101
+ "setup_key",
102
+ "material_id",
103
+ "session_id",
104
+ "voids",
105
+ "semester_name",
106
+ "deviation_reason",
107
+ "started_at",
108
+ )
109
+ START_FIELDS = ("code", "mode", "subject_type", "subject_id", "semester_name")
110
+ STOP_FIELDS = ("code", "session_id", "minutes", "setup_key", "semester_name", "deviation_reason")
111
+ ACCEPT_FIELDS = ("suggestion_id", "from_date")
112
+ CAPACITY_FIELDS = ("hours_per_week", "from_date") # study_set_capacity's (D-290)
113
+ CONFIRM_FIELDS = ("directive_id",) # from the Plan page only: no tool does it (D-311, D-368)
114
+ TRIALS_FIELDS = ("on",) # study_set_trials's (D-317)
115
+ # Fields the service reads as a number or a true/false; every other field must be text.
116
+ NUMBER_FIELDS = ("minutes", "hours_per_week")
117
+ FLAG_FIELDS = ("on",)
118
+
119
+
120
+ def _error(err: StudyError) -> JSONResponse:
121
+ return JSONResponse(err.to_dict(), status_code=STATUS.get(err.code, 400))
122
+
123
+
124
+ def _answer(call: Callable[[], dict]) -> JSONResponse:
125
+ """`tools.results.run` for HTTP: a success as JSON, a `StudyError` in the D-17 shape, a lock
126
+ wait as `database_busy`. Anything else raises, and the server logs it."""
127
+ try:
128
+ return JSONResponse(call())
129
+ except StudyError as err:
130
+ return _error(err)
131
+ except OperationalError as err:
132
+ return _error(busy(err))
133
+
134
+
135
+ def _locked() -> StudyError:
136
+ return StudyError(
137
+ code="dashboard_locked",
138
+ message="this browser was not opened by the study system, or the link was used already",
139
+ fix="ask your AI to open your dashboard, or run `study start` in a terminal and open the "
140
+ "link it prints",
141
+ )
142
+
143
+
144
+ async def _headers(request: Request, call_next: RequestResponseEndpoint) -> Response:
145
+ """HEADERS on every reply, refusals too: it is the outermost."""
146
+ reply = await call_next(request)
147
+ reply.headers.update(HEADERS)
148
+ return reply
149
+
150
+
151
+ async def _own_host(request: Request, call_next: RequestResponseEndpoint) -> Response:
152
+ """D-162 point 2, before every route - so a new route cannot forget it: a page whose own name
153
+ was re-pointed to 127.0.0.1 still sends that name."""
154
+ name = request.headers.get("host", "").rsplit(":", 1)[0]
155
+ if name not in OWN_HOSTS:
156
+ return _error(
157
+ StudyError(
158
+ code="wrong_host",
159
+ message=f"this route answers requests to 127.0.0.1 or localhost, not {name!r}",
160
+ fix=f"open the dashboard at http://{HOST}:<port>/",
161
+ )
162
+ )
163
+ return await call_next(request)
164
+
165
+
166
+ async def _json_body(request: Request) -> dict:
167
+ """D-162 point 1: a cross-site JSON request is preceded by a permission check the route never
168
+ grants, so only a same-site page can send one."""
169
+ media = request.headers.get("content-type", "").split(";")[0].strip().lower()
170
+ if media != "application/json":
171
+ raise StudyError(
172
+ code="not_json",
173
+ message=f"a write takes a JSON body, got {media or 'no content type'!r}",
174
+ fix="send the body as JSON with Content-Type: application/json",
175
+ )
176
+ raw = b""
177
+ async for chunk in request.stream():
178
+ raw += chunk
179
+ if len(raw) > MAX_BODY:
180
+ raise values.invalid("body", f"is over {MAX_BODY:,} bytes", "send a shorter body")
181
+ try:
182
+ body = json.loads(raw)
183
+ except (ValueError, RecursionError): # RecursionError: nested too deep to read
184
+ raise values.invalid("body", "is not valid JSON", "send one JSON object") from None
185
+ if not isinstance(body, dict):
186
+ raise values.invalid("body", "is not a JSON object", "send one JSON object")
187
+ values.storable("body", body)
188
+ return body
189
+
190
+
191
+ def _args(body: dict, route: str, fields: tuple[str, ...], needed: tuple[str, ...]) -> dict:
192
+ """The tool's schema checks names and types before the service runs; this is that check. A
193
+ mistyped name must not drop silently: `topic` for `topic_id` would log course-level hours,
194
+ and `source` is no field at all - only the timer's stop writes `timer` (D-198)."""
195
+ for field in body:
196
+ if field not in fields:
197
+ raise values.invalid(
198
+ field, f"is not a field of POST {route}", f"send only: {', '.join(fields)}"
199
+ )
200
+ for field in needed:
201
+ if body.get(field) is None:
202
+ fix = "send the course code, e.g. I3302" if field == "code" else f"send {field}"
203
+ raise values.invalid(field, "is missing", fix)
204
+ for field in fields:
205
+ if (
206
+ field not in NUMBER_FIELDS + FLAG_FIELDS
207
+ and body.get(field) is not None
208
+ and not isinstance(body[field], str)
209
+ ):
210
+ raise values.invalid(field, f"{body[field]!r} is not text", f"send {field} as a string")
211
+ return body
212
+
213
+
214
+ def _interrupt() -> None:
215
+ """Stop this process as Ctrl+C does: uvicorn lets the running requests finish, for STOP_SECONDS
216
+ at most, then exits."""
217
+ signal.raise_signal(signal.SIGINT)
218
+
219
+
220
+ def create_app(
221
+ engine: Engine,
222
+ check: Callable[[], None] | None = None,
223
+ stop: Callable[[], None] | None = None,
224
+ secret: bytes | None = None,
225
+ ) -> Starlette:
226
+ """The app on `engine`. Called by main(), which passes `call_check`, `_interrupt` and the data
227
+ folder's secret (D-369), and by tests, which pass their own engine. Without `stop` there is no
228
+ /shutdown; without `secret`, as for `study demo`, no key is asked."""
229
+ codes = None if secret is None else dashboard_key.Codes(secret)
230
+ version = importlib.metadata.version("studysystem")
231
+
232
+ async def at_head(request: Request, call_next: RequestResponseEndpoint) -> Response:
233
+ """`check` before every data route, in one place for the reason `_own_host` gives."""
234
+ if check is not None and request.url.path not in UNCHECKED_PATHS:
235
+ try:
236
+ await run_in_threadpool(check)
237
+ except StudyError as err:
238
+ return _error(err)
239
+ except OperationalError as err:
240
+ return _error(busy(err))
241
+ return await call_next(request)
242
+
243
+ async def keyed(request: Request, call_next: RequestResponseEndpoint) -> Response:
244
+ """The key, before every other route, in one place for the reason `_own_host` gives."""
245
+ path = request.url.path
246
+ if secret is not None and path not in KEYLESS_PATHS:
247
+ purpose = "stop" if path == "/shutdown" else "browser"
248
+ sent = request.headers.get(dashboard_key.HEADER)
249
+ if not dashboard_key.same(sent, dashboard_key.token(purpose, secret)):
250
+ return _error(_locked())
251
+ return await call_next(request)
252
+
253
+ async def open_browser(request: Request) -> JSONResponse:
254
+ """A browser's key, for the one-time code of a link that the study system opened."""
255
+ try:
256
+ body = await _json_body(request)
257
+ except StudyError as err:
258
+ return _error(err)
259
+ if not codes.take(body.get("code")):
260
+ return _error(_locked())
261
+ return JSONResponse({"key": dashboard_key.token("browser", secret)})
262
+
263
+ async def page(request: Request) -> HTMLResponse:
264
+ # The page is served here, same origin as /state and /hours, because D-162 blocks writes
265
+ # from a file:// page (D-186).
266
+ return HTMLResponse(await run_in_threadpool(PAGE.read_text, encoding="utf-8"))
267
+
268
+ def revision() -> str | None:
269
+ """What /health names. None when the file is lost or cannot be read: connecting would make
270
+ an empty one, or fail, and the launcher must still see a dashboard here (D-340)."""
271
+ try:
272
+ if check is not None:
273
+ check()
274
+ except StudyError as err:
275
+ if err.code in ("database_missing", "database_unavailable"):
276
+ return None
277
+ return current_revision(engine)
278
+
279
+ async def health(request: Request) -> JSONResponse:
280
+ nonce = request.query_params.get("nonce", "")
281
+ mine = {}
282
+ if secret is not None and 0 < len(nonce) <= dashboard_key.MAX_NONCE:
283
+ mine["proof"] = dashboard_key.proof(nonce, secret) # for the launcher
284
+ return await run_in_threadpool(
285
+ _answer, lambda: {"server_version": version, "schema_revision": revision()} | mine
286
+ )
287
+
288
+ async def get_state(request: Request) -> JSONResponse:
289
+ # Today in this machine's zone, as study_get_plan takes it.
290
+ return await run_in_threadpool(
291
+ _answer,
292
+ lambda: state.get_state(
293
+ engine, current_user(engine), datetime.datetime.now().astimezone().date(), version
294
+ ),
295
+ )
296
+
297
+ async def shutdown(request: Request) -> JSONResponse:
298
+ """`study stop` (D-342), which waits for the process that the reply names (D-343). A JSON
299
+ body, as every write, so another site cannot send it."""
300
+ try:
301
+ await _json_body(request)
302
+ except StudyError as err:
303
+ return _error(err)
304
+ stop()
305
+ return JSONResponse({"stopping": True, "pid": os.getpid()})
306
+
307
+ def write(
308
+ route: str, service: Callable[..., dict], fields: tuple[str, ...], needed: tuple[str, ...]
309
+ ) -> Route:
310
+ """A POST route: a checked JSON body, then `service` with the current user."""
311
+
312
+ async def handle(request: Request) -> JSONResponse:
313
+ try:
314
+ args = _args(await _json_body(request), route, fields, needed)
315
+ except StudyError as err:
316
+ return _error(err)
317
+ # In a worker thread: a write can wait out busy_timeout, and must not stall the others.
318
+ return await run_in_threadpool(
319
+ _answer, lambda: service(engine, current_user(engine), **args)
320
+ )
321
+
322
+ return Route(route, handle, methods=["POST"])
323
+
324
+ return Starlette(
325
+ routes=[
326
+ Route("/", page, methods=["GET"]),
327
+ Route("/health", health, methods=["GET"]),
328
+ Route("/state", get_state, methods=["GET"]),
329
+ write("/hours", study_loop.log_hours, HOURS_FIELDS, ("code",)),
330
+ write("/sessions", study_loop.start_session, START_FIELDS, ("code", "mode")),
331
+ write(
332
+ "/sessions/stop",
333
+ study_loop.stop_timer,
334
+ STOP_FIELDS,
335
+ ("code", "session_id", "minutes"),
336
+ ),
337
+ write("/capacity", capacity.set_capacity, CAPACITY_FIELDS, CAPACITY_FIELDS),
338
+ write(
339
+ "/capacity/accept",
340
+ capacity.accept_capacity_suggestion,
341
+ ACCEPT_FIELDS,
342
+ ACCEPT_FIELDS,
343
+ ),
344
+ write(
345
+ "/directives/confirm",
346
+ feedback.confirm_directive,
347
+ CONFIRM_FIELDS,
348
+ CONFIRM_FIELDS,
349
+ ),
350
+ write("/trials", trials.set_trials, TRIALS_FIELDS, TRIALS_FIELDS),
351
+ *([Route("/shutdown", shutdown, methods=["POST"])] if stop else []),
352
+ *([Route("/open", open_browser, methods=["POST"])] if codes else []),
353
+ ],
354
+ middleware=[ # in order: another site is refused before it can ask about the database
355
+ Middleware(BaseHTTPMiddleware, dispatch=_headers),
356
+ Middleware(BaseHTTPMiddleware, dispatch=_own_host),
357
+ Middleware(BaseHTTPMiddleware, dispatch=keyed),
358
+ Middleware(BaseHTTPMiddleware, dispatch=at_head),
359
+ ],
360
+ )
361
+
362
+
363
+ def main(port: int, *, locked: bool = True) -> None:
364
+ """Serve it. `study demo` is not locked: its data is invented."""
365
+ logging.basicConfig(stream=sys.stderr, level=logging.WARNING, format="%(asctime)s %(message)s")
366
+ logging.getLogger("studysystem").setLevel(logging.INFO)
367
+ engine = open_database()
368
+ secret = dashboard_key.key() if locked else None
369
+ if locked and sys.stdout is not None and sys.stdout.isatty(): # never into a log
370
+ print(launcher.invitation(port), flush=True)
371
+ uvicorn.run(
372
+ # with no key there is no /shutdown either: Ctrl+C stops `study demo`
373
+ create_app(engine, call_check(engine), _interrupt if locked else None, secret),
374
+ host=HOST,
375
+ port=port,
376
+ timeout_graceful_shutdown=STOP_SECONDS,
377
+ )
@@ -0,0 +1 @@
1
+ """Database layer: engine, table metadata (SQLAlchemy Core), migrations (Alembic)."""
@@ -0,0 +1,158 @@
1
+ """SQLite engine bootstrap: where the file lives, how every connection is configured,
2
+ and the once-a-day snapshot."""
3
+
4
+ import datetime
5
+ import os
6
+ import sqlite3
7
+ import time
8
+ from pathlib import Path
9
+
10
+ import platformdirs
11
+ from sqlalchemy import Engine, create_engine, event
12
+
13
+ from studysystem.errors import StudyError
14
+
15
+ # Ten tries, 50ms apart: the holder only needs to finish one PRAGMA.
16
+ _WAL_ATTEMPTS = 10
17
+ _WAL_BACKOFF = 0.05
18
+
19
+ # The execution option a read-only connection carries (`services.units.read_unit`): its
20
+ # transaction opens with a plain BEGIN instead of BEGIN IMMEDIATE.
21
+ READ_ONLY = "studysystem_read_only"
22
+
23
+
24
+ # How to put a copy back, for every fix that says to. A -wal file left by a crash holds pages of the
25
+ # old file: SQLite writes them over the restored one, which is then changed or damaged (D-340).
26
+ # Moved, not deleted: if the file turns out healthy, its -wal can hold hours that are nowhere else.
27
+ HOW_TO_RESTORE = (
28
+ "stop every study program, move studysystem.db, studysystem.db-wal and studysystem.db-shm "
29
+ "(those that are there) to another folder, then copy the snapshot back as studysystem.db"
30
+ )
31
+
32
+
33
+ class WalUnavailable(RuntimeError):
34
+ """The file could not be switched to WAL: another process kept it locked throughout."""
35
+
36
+
37
+ def unavailable(path: Path, e: BaseException) -> StudyError:
38
+ """The one-line refusal for a file the first connection could not use: locked, unreadable,
39
+ or not a database at all. For the server's start and the `study` commands only - a tool maps
40
+ just the lock wait (D-144). The driver text is kept, so the real fault stays visible."""
41
+ return StudyError(
42
+ code="database_unavailable",
43
+ message=f"cannot open {path}: {getattr(e, 'orig', None) or e}",
44
+ fix="if another program holds it (study migrate, the dashboard), close it and start "
45
+ "again; if it cannot be read or written, check its folder's permissions; only if it is "
46
+ f"damaged, restore a copy from the snapshots folder beside it: {HOW_TO_RESTORE}",
47
+ )
48
+
49
+
50
+ def data_dir() -> Path:
51
+
52
+ out = os.environ.get("STUDYSYSTEM_DATA_DIR")
53
+ if out:
54
+ path = Path(out)
55
+ else:
56
+ path = Path(platformdirs.user_data_dir("studysystem", appauthor=False))
57
+ # 0o700: on Linux and macOS, another account cannot read it. Windows ignores it.
58
+ path.mkdir(mode=0o700, parents=True, exist_ok=True)
59
+ return path
60
+
61
+
62
+ def db_path() -> Path:
63
+ return data_dir() / "studysystem.db"
64
+
65
+
66
+ def _ensure_wal(dbapi_conn) -> None:
67
+ """Put the file in WAL, tolerating another process doing the same thing.
68
+
69
+ `foreign_keys` and `busy_timeout` are settings of the connection, so every connection sets
70
+ them. `journal_mode` is not: it lives in the file header and outlives the connection that
71
+ wrote it, so all this has to do is get the file there once.
72
+
73
+ Switching takes an exclusive lock, and SQLite answers SQLITE_BUSY straight away rather than
74
+ waiting out `busy_timeout` - so two processes opening a new file at the same moment is a
75
+ real race, not a slow path. Reading the mode first skips the lock entirely once the file is
76
+ WAL, which is every connection after the first; the retry covers the first.
77
+ """
78
+ for _ in range(_WAL_ATTEMPTS):
79
+ if dbapi_conn.execute("PRAGMA journal_mode").fetchone()[0].lower() == "wal":
80
+ return
81
+ try:
82
+ dbapi_conn.execute("PRAGMA journal_mode = WAL")
83
+ return
84
+ except sqlite3.OperationalError:
85
+ time.sleep(_WAL_BACKOFF) # the holder is mid-switch; it lands in milliseconds
86
+ raise WalUnavailable(
87
+ "could not put the database in WAL mode: another process held it for "
88
+ f"{_WAL_ATTEMPTS * _WAL_BACKOFF:.1f}s"
89
+ )
90
+
91
+
92
+ def make_engine(path: Path) -> Engine:
93
+ engine = create_engine(f"sqlite:///{path.as_posix()}", connect_args={"isolation_level": None})
94
+
95
+ @event.listens_for(engine, "connect")
96
+ def on_connect(dbapi_conn, _record):
97
+ dbapi_conn.execute("PRAGMA foreign_keys = ON")
98
+ dbapi_conn.execute("PRAGMA busy_timeout = 5000")
99
+ _ensure_wal(dbapi_conn)
100
+
101
+ @event.listens_for(engine, "begin")
102
+ def on_begin(conn):
103
+ # A write takes the file's one write lock before its first read (D-22). A read opts out:
104
+ # under WAL a plain BEGIN still sees one consistent moment, and never waits on a writer.
105
+ if conn.get_execution_options().get(READ_ONLY):
106
+ conn.exec_driver_sql("BEGIN")
107
+ else:
108
+ conn.exec_driver_sql("BEGIN IMMEDIATE")
109
+
110
+ return engine
111
+
112
+
113
+ def has_snapshot() -> bool:
114
+ """Whether this data folder holds a finished copy: it had a database before (D-337). A folder
115
+ that cannot be read counts as holding one: unknown is not empty. `Path.glob` would hide that
116
+ error and answer no."""
117
+ try:
118
+ return any(name.endswith(".db") for name in os.listdir(data_dir() / "snapshots"))
119
+ except FileNotFoundError:
120
+ return False
121
+ except OSError:
122
+ return True
123
+
124
+
125
+ def snapshot(
126
+ engine: Engine, today: datetime.date, suffix: str = "", unique: bool = False
127
+ ) -> Path | None:
128
+ """Copy the database to snapshots/<date><suffix>.db. Skips if that file exists, which is
129
+ the once-a-day rule for the plain startup snapshot (D-22). With `unique` it never skips: a
130
+ taken name gets -2, -3, ... - two `study migrate` runs in one second keep a copy each (D-23)."""
131
+ folder = data_dir() / "snapshots"
132
+ folder.mkdir(parents=True, exist_ok=True)
133
+ stem = f"{today.isoformat()}{suffix}"
134
+ target = folder / f"{stem}.db"
135
+
136
+ n = 2
137
+ while target.exists():
138
+ if not unique:
139
+ return None
140
+ target = folder / f"{stem}-{n}.db"
141
+ n += 1
142
+
143
+ # Copied beside the real name and renamed in one step: a copy cut short (full disk, killed
144
+ # process) never sits under the day's name, where the exists() check would trust it all day.
145
+ # The pid keeps two servers starting together off each other's half-written file.
146
+ partial = target.with_name(f"{target.name}.{os.getpid()}.partial")
147
+ try:
148
+ raw = engine.raw_connection()
149
+ try:
150
+ raw.execute("VACUUM INTO ?", (partial.as_posix(),))
151
+ finally:
152
+ raw.close() # before the unlink below: Windows cannot delete an open file
153
+ except BaseException:
154
+ partial.unlink(missing_ok=True)
155
+ raise
156
+ os.replace(partial, target)
157
+
158
+ return target
@@ -0,0 +1,122 @@
1
+ """Migrations behind one command (D-22): only `study migrate` changes an existing schema. A
2
+ server or dashboard builds a brand-new database (D-324, D-335, D-337), and otherwise only checks
3
+ it: behind head it starts and every call refuses (D-325, D-338), ahead of head it does not start."""
4
+
5
+ import warnings
6
+ from collections.abc import Callable
7
+ from pathlib import Path
8
+
9
+ from alembic import command
10
+ from alembic.config import Config
11
+ from alembic.runtime.migration import MigrationContext
12
+ from alembic.script import ScriptDirectory
13
+ from sqlalchemy import Engine, inspect
14
+ from sqlalchemy.exc import SAWarning
15
+
16
+ from studysystem.db.engine import HOW_TO_RESTORE, READ_ONLY
17
+ from studysystem.errors import StudyError
18
+
19
+ MIGRATIONS_DIR = Path(__file__).parent / "migrations"
20
+
21
+
22
+ class SchemaBehindHead(StudyError):
23
+ """An empty database, or one an older build migrated: `study migrate` brings it to head."""
24
+
25
+ def __init__(self, current, head):
26
+ self.current, self.head = current, head
27
+ where = "has no schema yet" if current is None else f"is at {current}"
28
+ super().__init__(
29
+ code="schema_behind_head",
30
+ message=f"database {where}, head is {head}",
31
+ fix="run: study migrate",
32
+ )
33
+
34
+
35
+ class SchemaAheadOfHead(StudyError):
36
+ """A database a newer build migrated: this build's migrations do not know its revision, so
37
+ `study migrate` cannot help - an older build must not touch it. `running`: the newer build came
38
+ while this one ran, so a restart runs it, and a restored snapshot would lose data (D-338)."""
39
+
40
+ def __init__(self, current, head, running=False):
41
+ self.current, self.head = current, head
42
+ super().__init__(
43
+ code="schema_ahead_of_head",
44
+ message=f"database is at {current}, unknown to this build (its head is {head})",
45
+ fix="restart the app that runs this server, so it runs the newer build; for the "
46
+ "dashboard, run: study stop, then: study start"
47
+ if running
48
+ else "run the newer build that migrated it, or restore a snapshot taken before that "
49
+ f"migrate from the snapshots folder in the data directory: {HOW_TO_RESTORE}",
50
+ )
51
+
52
+
53
+ def alembic_config(engine: Engine | None = None) -> Config:
54
+ cfg = Config()
55
+ cfg.set_main_option("script_location", str(MIGRATIONS_DIR))
56
+ if engine is not None:
57
+ cfg.attributes["engine"] = engine
58
+
59
+ return cfg
60
+
61
+
62
+ def head_revision() -> str | None:
63
+ cfg = alembic_config()
64
+
65
+ return ScriptDirectory.from_config(cfg).get_current_head()
66
+
67
+
68
+ def current_revision(engine: Engine) -> str | None:
69
+ """The revision stamped in the database; a read, so it takes no write lock."""
70
+ with engine.connect() as conn:
71
+ conn.execution_options(**{READ_ONLY: True})
72
+ rev = MigrationContext.configure(conn).get_current_revision()
73
+ return rev
74
+
75
+
76
+ def has_tables(engine: Engine) -> bool:
77
+ """False for a file just created, one a killed first start left behind before its tables were
78
+ saved, or one emptied since. A read, so it takes no write lock."""
79
+ with engine.connect() as conn:
80
+ conn.execution_options(**{READ_ONLY: True})
81
+ return bool(inspect(conn).get_table_names())
82
+
83
+
84
+ def schema_check(engine: Engine, running: bool = True) -> Callable[[], None]:
85
+ """The check a server runs before every call (D-338). Head and the migrations this build knows
86
+ are read here, once: while it runs, an upgrade can replace the files on disk, and its database
87
+ must be compared with the build in memory. Each call of the check reads only the database's
88
+ revision, and raises unless it is head: behind (or empty) and ahead are different fixes."""
89
+ script = ScriptDirectory.from_config(alembic_config())
90
+ head = script.get_current_head()
91
+ known = {migration.revision for migration in script.walk_revisions()}
92
+
93
+ def check() -> None:
94
+ current = current_revision(engine)
95
+ if current == head:
96
+ return
97
+ if current is not None and current not in known:
98
+ raise SchemaAheadOfHead(current, head, running)
99
+ raise SchemaBehindHead(current, head)
100
+
101
+ return check
102
+
103
+
104
+ def check_schema(engine: Engine) -> None:
105
+ """The same check, once, at the start."""
106
+ schema_check(engine, running=False)()
107
+
108
+
109
+ def upgrade(engine: Engine) -> None:
110
+ # SQLAlchemy cannot reflect an expression index and says so at each table rebuild. The
111
+ # migrations recreate them, and a test lists every index the result must hold, so the lines
112
+ # would only worry a new user reading the host's log. Not silenced in env.py, where
113
+ # autogenerate runs too and a developer needs them (D-27).
114
+ with warnings.catch_warnings():
115
+ warnings.filterwarnings(
116
+ "ignore", "Skipped unsupported reflection of expression-based index", SAWarning
117
+ )
118
+ command.upgrade(alembic_config(engine), "head")
119
+
120
+
121
+ def downgrade(engine: Engine, target: str) -> None:
122
+ command.downgrade(alembic_config(engine), target)