Исправить 500 на дубликатах member_ids в разном регистре UUID.
Skeleton contracts / contracts (pull_request) Canceled after 0s
Skeleton contracts / contracts (pull_request) Canceled after 0s
Нормализуем UUID до проверки уникальности и отвечаем 400 invalid_request вместо UniqueViolation. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -1,5 +1,5 @@
|
|||||||
rollback: api count 119 -> 119, sql probe rows 0
|
rollback: api count 125 -> 125, sql probe rows 0
|
||||||
username race: one 201, eleven 409, one row
|
username race: one 201, eleven 409, one row
|
||||||
migrations reapplied, users 26 -> 26, versions 001_init
|
migrations reapplied, users 46 -> 46, versions 001_init
|
||||||
redis persistence: rdb_last_bgsave_status:ok, aof_enabled:1, aof_last_write_status:ok, aof_current_size:7677
|
redis persistence: rdb_last_bgsave_status:ok, aof_enabled:1, aof_last_write_status:ok, aof_current_size:14166
|
||||||
PASS student checks
|
PASS student checks
|
||||||
|
|||||||
+8
-4
@@ -58,18 +58,22 @@ class CreateChat(StrictModel):
|
|||||||
def member_ids_ok(cls, value):
|
def member_ids_ok(cls, value):
|
||||||
if not isinstance(value, list) or not (1 <= len(value) <= 100):
|
if not isinstance(value, list) or not (1 <= len(value) <= 100):
|
||||||
raise ValueError("member_ids")
|
raise ValueError("member_ids")
|
||||||
|
# Сравниваем и возвращаем канонический UUID (нижний регистр + дефисы),
|
||||||
|
# иначе u и u.upper() проходят как «разные» строки и падают UniqueViolation в БД.
|
||||||
|
normalized = []
|
||||||
seen = set()
|
seen = set()
|
||||||
for item in value:
|
for item in value:
|
||||||
if not isinstance(item, str):
|
if not isinstance(item, str):
|
||||||
raise ValueError("member_ids")
|
raise ValueError("member_ids")
|
||||||
try:
|
try:
|
||||||
uuid.UUID(item)
|
canonical = str(uuid.UUID(item))
|
||||||
except ValueError as exc:
|
except ValueError as exc:
|
||||||
raise ValueError("member_ids") from exc
|
raise ValueError("member_ids") from exc
|
||||||
if item in seen:
|
if canonical in seen:
|
||||||
raise ValueError("member_ids")
|
raise ValueError("member_ids")
|
||||||
seen.add(item)
|
seen.add(canonical)
|
||||||
return value
|
normalized.append(canonical)
|
||||||
|
return normalized
|
||||||
|
|
||||||
|
|
||||||
class CreateMessage(StrictModel):
|
class CreateMessage(StrictModel):
|
||||||
|
|||||||
+21
-4
@@ -11,7 +11,7 @@ from pathlib import Path
|
|||||||
|
|
||||||
import psycopg
|
import psycopg
|
||||||
import redis
|
import redis
|
||||||
from psycopg.errors import ForeignKeyViolation
|
from psycopg.errors import ForeignKeyViolation, UniqueViolation
|
||||||
from psycopg.rows import dict_row
|
from psycopg.rows import dict_row
|
||||||
from psycopg_pool import ConnectionPool, PoolTimeout
|
from psycopg_pool import ConnectionPool, PoolTimeout
|
||||||
|
|
||||||
@@ -414,11 +414,25 @@ class Store:
|
|||||||
return deleted == 1
|
return deleted == 1
|
||||||
|
|
||||||
def create_chat(self, title, member_ids, caller_id):
|
def create_chat(self, title, member_ids, caller_id):
|
||||||
if caller_id not in member_ids:
|
# Ещё раз через UUID: дубликаты в разном регистре уже отсекаются в schemas,
|
||||||
|
# здесь — страховка и единый канонический вид для caller/members.
|
||||||
|
try:
|
||||||
|
caller_uuid = uuid.UUID(str(caller_id))
|
||||||
|
member_uuids = []
|
||||||
|
seen = set()
|
||||||
|
for item in member_ids:
|
||||||
|
member_uuid = uuid.UUID(str(item))
|
||||||
|
if member_uuid in seen:
|
||||||
|
raise ValueError("members")
|
||||||
|
seen.add(member_uuid)
|
||||||
|
member_uuids.append(member_uuid)
|
||||||
|
except ValueError as exc:
|
||||||
|
raise ValueError("members") from exc
|
||||||
|
if caller_uuid not in seen:
|
||||||
raise ValueError("members")
|
raise ValueError("members")
|
||||||
chat_id = uuid.uuid4()
|
chat_id = uuid.uuid4()
|
||||||
created = utc_now()
|
created = utc_now()
|
||||||
member_uuids = [uuid.UUID(item) for item in member_ids]
|
canonical_members = [str(item) for item in member_uuids]
|
||||||
try:
|
try:
|
||||||
with self._connect() as conn:
|
with self._connect() as conn:
|
||||||
try:
|
try:
|
||||||
@@ -442,9 +456,12 @@ class Store:
|
|||||||
).fetchone()
|
).fetchone()
|
||||||
except ForeignKeyViolation as exc:
|
except ForeignKeyViolation as exc:
|
||||||
raise ValueError("members") from exc
|
raise ValueError("members") from exc
|
||||||
|
except UniqueViolation as exc:
|
||||||
|
# Дубликат участника, если обошли schema-валидацию.
|
||||||
|
raise ValueError("members") from exc
|
||||||
except psycopg.OperationalError as exc:
|
except psycopg.OperationalError as exc:
|
||||||
_db_down(exc)
|
_db_down(exc)
|
||||||
return public_chat(row, member_ids)
|
return public_chat(row, canonical_members)
|
||||||
|
|
||||||
def _member(self, conn, chat_id, user_id):
|
def _member(self, conn, chat_id, user_id):
|
||||||
return conn.execute(
|
return conn.execute(
|
||||||
|
|||||||
@@ -162,6 +162,20 @@ def main():
|
|||||||
after = int(psql("SELECT count(*) FROM chats;"))
|
after = int(psql("SELECT count(*) FROM chats;"))
|
||||||
check(status == 400 and before == after, "chat rollback left a row {} {}".format(before, after))
|
check(status == 400 and before == after, "chat rollback left a row {} {}".format(before, after))
|
||||||
|
|
||||||
|
# Один UUID дважды в разном регистре — 400, не 500 UniqueViolation.
|
||||||
|
before_case = int(psql("SELECT count(*) FROM chats;"))
|
||||||
|
status, _, body_case = call(
|
||||||
|
"POST",
|
||||||
|
"/api/v1/chats",
|
||||||
|
{"title": "Дубликат UUID", "member_ids": [alice["id"], alice["id"].upper()]},
|
||||||
|
bearer(token),
|
||||||
|
)
|
||||||
|
after_case = int(psql("SELECT count(*) FROM chats;"))
|
||||||
|
check(
|
||||||
|
status == 400 and before_case == after_case and body_case.get("error", {}).get("code") == "invalid_request",
|
||||||
|
"case-duplicate member_ids {} chats {}->{}".format(status, before_case, after_case),
|
||||||
|
)
|
||||||
|
|
||||||
psql("DELETE FROM chats WHERE title = 'rollback-probe';")
|
psql("DELETE FROM chats WHERE title = 'rollback-probe';")
|
||||||
broken = compose(
|
broken = compose(
|
||||||
"exec",
|
"exec",
|
||||||
|
|||||||
Reference in New Issue
Block a user