Skip to content

Commit 8de8c69

Browse files
šŸ“ Add docstrings to codex/refactor-_process-to-use-own-sqlalchemy-session
Docstrings generation was requested by @shayancoin. * #90 (comment) The following files were modified: * `backend/api/routes_sync.py` * `backend/api/security.py` * `backend/tests/test_sync_routes_metrics.py`
1 parent af747dd commit 8de8c69

File tree

3 files changed

+51
-9
lines changed

3 files changed

+51
-9
lines changed

ā€Žbackend/api/routes_sync.pyā€Ž

Lines changed: 18 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -69,12 +69,17 @@ async def hygraph_webhook(
6969
db: Session = Depends(get_db),
7070
) -> Dict[str, Any]:
7171
"""
72-
Webhook receiver:
73-
- HMAC validated (dependency)
74-
- Single size guard (2MB) already enforced by dependency; body/raw set on request.state
75-
- DB dedup via SyncEvent(event_id, body_sha256 unique)
76-
- 202 fast-ack with background processing (pull_all)
77-
- Structured JSON log line and Prometheus counters
72+
Handle a Hygraph webhook by recording the event, deduplicating, and scheduling a background full sync.
73+
74+
Attempts to create a SyncEvent to deduplicate incoming webhooks; if the event is already recorded, returns a 200 response with {"ok": True, "dedup": True}. Parses the request body as JSON and, on success, enqueues a background task that runs a full pull (HygraphService.pull_all) using a dedicated DB session; the background task updates Prometheus counters and logs results. On enqueueing, returns a 202 response with {"ok": True, "accepted": True}.
75+
76+
Returns:
77+
A JSONResponse indicating one of:
78+
- {"ok": True, "dedup": True} with status 200 when the event is a duplicate.
79+
- {"ok": True, "accepted": True} with status 202 when the event was accepted and background processing was scheduled.
80+
81+
Raises:
82+
HTTPException: Raised with a BAD_REQUEST error envelope when the request body is not valid JSON.
7883
"""
7984
start = time.perf_counter()
8085
raw = getattr(request.state, "raw_body", b"")
@@ -109,6 +114,13 @@ async def hygraph_webhook(
109114
raise HTTPException(status_code=400, detail=_error_envelope("BAD_REQUEST", "Invalid JSON payload"))
110115

111116
async def _process(event_id_local: Optional[str], body_sha_local: str) -> None:
117+
"""
118+
Perform the background Hygraph sync: pull all content, update Prometheus metrics, and log success or failure.
119+
120+
Parameters:
121+
event_id_local (Optional[str]): Optional sync event identifier used for logging and correlation.
122+
body_sha_local (str): SHA-256 of the webhook body used for correlation in logs and metrics.
123+
"""
112124
t0 = time.perf_counter()
113125
session = SessionLocal()
114126
try:

ā€Žbackend/api/security.pyā€Ž

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,15 @@
1414

1515

1616
def _load_expected_write_token(settings: Settings) -> str:
17-
"""Resolve the configured API write token from settings or environment."""
17+
"""
18+
Resolve the API write token from the provided settings or the API_WRITE_TOKEN environment variable.
19+
20+
Parameters:
21+
settings (Settings): Configuration object that may contain an `api_write_token` attribute.
22+
23+
Returns:
24+
str: The resolved token with surrounding whitespace removed; an empty string if no token is configured.
25+
"""
1826

1927
token = getattr(settings, "api_write_token", None)
2028
if isinstance(token, str) and token.strip():
@@ -113,4 +121,4 @@ async def validate_hygraph_request(
113121
raise HTTPException(status_code=HTTP_401_UNAUTHORIZED, detail="Invalid signature")
114122
request.state.raw_body = body
115123
request.state.body_sha256 = hashlib.sha256(body).hexdigest()
116-
return True
124+
return True

ā€Žbackend/tests/test_sync_routes_metrics.pyā€Ž

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,11 +15,23 @@
1515

1616
def _sig(secret: str, body: bytes) -> str:
1717
# x-hygraph-signature uses sha256=<hex>
18+
"""
19+
Compute an HMAC-SHA256 signature for a request body using the given secret.
20+
21+
Returns:
22+
A string in the form "sha256=<hex digest>" containing the lowercase hexadecimal HMAC-SHA256 of the body (the secret is encoded as UTF-8).
23+
"""
1824
return "sha256=" + hmac.new(secret.encode("utf-8"), body, hashlib.sha256).hexdigest()
1925

2026

2127
@pytest.fixture()
2228
def client():
29+
"""
30+
Provide a TestClient configured for the application's FastAPI app for use in tests.
31+
32+
Returns:
33+
TestClient: A TestClient instance bound to the FastAPI app.
34+
"""
2335
return TestClient(app)
2436

2537

@@ -64,6 +76,16 @@ def test_webhook_background_uses_new_session(client, caplog, monkeypatch):
6476
calls: list[bool] = []
6577

6678
async def fake_pull_all(db, page_size=None):
79+
"""
80+
Simulate a Hygraph `pull_all` call for tests and record whether the provided DB session is active.
81+
82+
Parameters:
83+
db: Database session or connection; its `is_active` attribute is appended to the test `calls` list.
84+
page_size (optional): Ignored; accepted for API compatibility.
85+
86+
Returns:
87+
dict: Counts for pulled entities with keys `materials`, `modules`, and `systems`, each set to 0.
88+
"""
6789
db.execute(text("SELECT 1"))
6890
calls.append(db.is_active)
6991
return {"materials": 0, "modules": 0, "systems": 0}
@@ -99,4 +121,4 @@ async def fake_pull_modules(db, page_size=None):
99121
)
100122
assert r.status_code == 200
101123
assert r.json()["ok"] is True
102-
assert r.json()["data"]["processed"] == 5
124+
assert r.json()["data"]["processed"] == 5

0 commit comments

Comments
Ā (0)