Skip to content

Commit 0aeccad

Browse files
jnsdlsclaude
andcommitted
feat: accept a parsed PushBody in handle_mutate_request
A caller that needs push-level fields such as `timestamp` can parse the body once and pass the PushBody, instead of parsing it twice. The handler keeps upstream's (transact, mutation) signature. Closes #25 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent fecb718 commit 0aeccad

2 files changed

Lines changed: 88 additions & 18 deletions

File tree

‎src/zero_server/server/process_mutations.py‎

Lines changed: 29 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@
1515
import logging
1616
from collections.abc import Awaitable, Callable, Mapping
1717
from dataclasses import dataclass
18-
from typing import Any, Literal, Protocol
18+
from typing import Literal, Protocol
1919

2020
from pydantic import TypeAdapter, ValidationError
2121

@@ -155,6 +155,14 @@ def _parse_failure(
155155
)
156156

157157

158+
def _parse_push_body(json_body: object) -> PushBody | ServerPushFailed:
159+
try:
160+
return PushBody.from_json(json_body)
161+
except ValidationError as error:
162+
logger.error("Failed to parse push body", exc_info=error)
163+
return _parse_failure("push body", error, [])
164+
165+
158166
async def handle_mutate_request[T](
159167
*,
160168
db_provider: Database[T],
@@ -165,9 +173,13 @@ async def handle_mutate_request[T](
165173
) -> MutateResponse:
166174
"""Process one `/mutate` request from zero-cache.
167175
168-
`query` is the request's query string and `body` its JSON, either raw bytes or already parsed.
176+
`query` is the request's query string and `body` its JSON: raw bytes, decoded JSON, or a `PushBody`.
169177
`user_id` is the authenticated user, `None` when logged out; reporting it back is what makes
170178
zero-cache treat the connection's user as server-validated.
179+
180+
A caller that needs push-level fields such as `timestamp` parses once with `PushBody.from_json` and
181+
passes the result. If that parse fails, pass the raw body instead and return the parse failure this
182+
produces.
171183
"""
172184
return await handle_mutate(db_provider, handler, query, body, user_id, report_user_id=True)
173185

@@ -182,21 +194,21 @@ async def handle_mutate[T](
182194
report_user_id: bool,
183195
) -> MutateResponse:
184196
"""`handle_mutate_request`, and the legacy form that reports no user ID at all."""
185-
json_body: Any = body
186-
if isinstance(body, bytes):
187-
try:
188-
json_body = json.loads(body, parse_constant=_refuse_constant)
189-
except ValueError as error:
190-
logger.error("Failed to parse push body", exc_info=error)
191-
return _parse_failure("push body", error, [], syntax=True)
192-
193-
mutation_ids: list[MutationID] = []
194-
try:
195-
push_body = PushBody.from_json(json_body)
196-
mutation_ids = [MutationID(id=m.id, clientID=m.client_id) for m in push_body.mutations]
197-
except ValidationError as error:
198-
logger.error("Failed to parse push body", exc_info=error)
199-
return _parse_failure("push body", error, mutation_ids)
197+
match body:
198+
case PushBody():
199+
push_body = body
200+
case bytes():
201+
try:
202+
json_body = json.loads(body, parse_constant=_refuse_constant)
203+
except ValueError as error:
204+
logger.error("Failed to parse push body", exc_info=error)
205+
return _parse_failure("push body", error, [], syntax=True)
206+
push_body = _parse_push_body(json_body)
207+
case _:
208+
push_body = _parse_push_body(body)
209+
if isinstance(push_body, ServerPushFailed):
210+
return push_body
211+
mutation_ids = [MutationID(id=m.id, clientID=m.client_id) for m in push_body.mutations]
200212

201213
try:
202214
params = MutateParams.from_json(dict(query))

‎tests/unit/test_mutate.py‎

Lines changed: 59 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,13 @@
1-
"""Branches of the mutate endpoint the wire tier cannot reach: raw bodies upstream would read off a Request."""
1+
"""Branches of the mutate endpoint the wire tier cannot reach: raw bodies upstream would read off a Request,
2+
and bodies the caller has already parsed."""
23

4+
import json
35
from typing import Any
46

57
import pytest
68

79
from zero_server.protocol.mutation import CustomMutation, MutationResponse
10+
from zero_server.protocol.push import PushBody
811
from zero_server.server.process_mutations import TransactFn, handle_mutate_request
912

1013
QUERY = {"schema": "zero_0", "appID": "zero"}
@@ -41,3 +44,58 @@ async def test_raw_body_is_parsed() -> None:
4144
db_provider=NoDatabase(), handler=handler, query=QUERY, body=body, user_id="u"
4245
)
4346
assert response.to_json() == {"kind": "MutateResponse", "userID": "u", "mutations": []}
47+
48+
49+
PUSH = {"clientGroupID": "g", "mutations": [], "pushVersion": 1, "timestamp": 1, "requestID": "r"}
50+
MUTATION = {"type": "custom", "id": 1, "clientID": "c", "name": "issue.create", "args": [], "timestamp": 1}
51+
52+
53+
class AcceptingDatabase:
54+
"""Accepts each mutation's ID as the next one, and records nothing."""
55+
56+
async def transaction(self, callback: Any, transaction_input: Any = None) -> Any:
57+
class Hooks:
58+
async def update_client_mutation_id(self) -> int:
59+
return transaction_input.mutation_id
60+
61+
async def write_mutation_result(self, result: MutationResponse) -> None:
62+
pass
63+
64+
return await callback(None, Hooks())
65+
66+
67+
async def failing_handler(transact: TransactFn[Any], mutation: CustomMutation) -> MutationResponse:
68+
raise ValueError("no such issue")
69+
70+
71+
@pytest.mark.parametrize(
72+
("push", "query"),
73+
[
74+
(PUSH, QUERY),
75+
({**PUSH, "mutations": [MUTATION]}, QUERY),
76+
({**PUSH, "mutations": [MUTATION], "pushVersion": 2}, QUERY),
77+
({**PUSH, "mutations": [MUTATION]}, {"appID": "zero"}),
78+
],
79+
ids=["success", "mutation-error", "unsupported-push-version", "bad-query"],
80+
)
81+
async def test_parsed_body_matches_raw(push: dict[str, Any], query: dict[str, str]) -> None:
82+
async def respond(body: object) -> object:
83+
response = await handle_mutate_request(
84+
db_provider=AcceptingDatabase(), handler=failing_handler, query=query, body=body, user_id="u"
85+
)
86+
return response.to_json()
87+
88+
assert await respond(PushBody.from_json(push)) == await respond(json.dumps(push).encode())
89+
90+
91+
async def test_parsed_body_is_not_validated_again(monkeypatch: pytest.MonkeyPatch) -> None:
92+
push_body = PushBody.from_json(PUSH)
93+
94+
def refuse(value: object) -> PushBody:
95+
raise AssertionError("parsed body validated again")
96+
97+
monkeypatch.setattr(PushBody, "from_json", refuse)
98+
response = await handle_mutate_request(
99+
db_provider=NoDatabase(), handler=handler, query=QUERY, body=push_body, user_id="u"
100+
)
101+
assert response.to_json() == {"kind": "MutateResponse", "userID": "u", "mutations": []}

0 commit comments

Comments
 (0)