refactor code
This commit is contained in:
+1
-29
@@ -1,5 +1,4 @@
|
||||
import base64
|
||||
import logging
|
||||
import re
|
||||
from datetime import datetime
|
||||
from uuid import UUID
|
||||
@@ -8,7 +7,6 @@ from fastapi import APIRouter, Depends, Header, Query, Request, Response
|
||||
|
||||
from .cursor import CursorError, decode_cursor, encode_cursor
|
||||
from .errors import ApiError
|
||||
from .storage.history_cache import HistoryCache
|
||||
from .storage.postgres import PostgresStore
|
||||
from .models import (
|
||||
Chat,
|
||||
@@ -23,7 +21,6 @@ from .models import (
|
||||
)
|
||||
|
||||
router = APIRouter()
|
||||
cache_logger = logging.getLogger("messenger.cache")
|
||||
BEARER_CHALLENGE = {"WWW-Authenticate": 'Bearer realm="messenger"'}
|
||||
BASIC_CHALLENGE = {"WWW-Authenticate": 'Basic realm="messenger", charset="UTF-8"'}
|
||||
IDEMPOTENCY_KEY = re.compile(r"^[A-Za-z0-9._:-]{1,128}$")
|
||||
@@ -31,9 +28,6 @@ IDEMPOTENCY_KEY = re.compile(r"^[A-Za-z0-9._:-]{1,128}$")
|
||||
def get_store(request: Request) -> PostgresStore:
|
||||
return request.app.state.store
|
||||
|
||||
def get_history_cache(request: Request) -> HistoryCache:
|
||||
return request.app.state.history_cache
|
||||
|
||||
|
||||
async def get_current_user(
|
||||
authorization: str | None = Header(default=None),
|
||||
@@ -175,33 +169,11 @@ async def list_messages(
|
||||
chat_id: UUID,
|
||||
user: dict = Depends(get_current_user),
|
||||
store: PostgresStore = Depends(get_store),
|
||||
cache: HistoryCache = Depends(get_history_cache),
|
||||
limit: int = Query(default=50, ge=1, le=100),
|
||||
cursor: str | None = Query(default=None, min_length=1),
|
||||
) -> MessagePageResponse:
|
||||
scope = "messages:" + str(chat_id)
|
||||
after = cursor_position(cursor, scope)
|
||||
if cursor is None:
|
||||
version = await store.history_version_for_member(chat_id, user["id"])
|
||||
rows = await cache.get(chat_id, version, limit)
|
||||
if rows is None:
|
||||
lock_token = await cache.acquire_load_lock(chat_id, version, limit)
|
||||
if lock_token == "":
|
||||
rows = await cache.wait_for_fill(chat_id, version, limit)
|
||||
if rows is None:
|
||||
cache_logger.info(
|
||||
"history_sql_page_load chat_id=%s version=%s limit=%s",
|
||||
chat_id,
|
||||
version,
|
||||
limit,
|
||||
)
|
||||
try:
|
||||
rows = await store.list_messages_for_member(chat_id, user["id"], None, limit)
|
||||
await cache.set(chat_id, version, limit, rows)
|
||||
finally:
|
||||
if lock_token:
|
||||
await cache.release_load_lock(chat_id, version, limit, lock_token)
|
||||
else:
|
||||
rows = await store.list_messages_for_member(chat_id, user["id"], after, limit)
|
||||
rows = await store.list_messages_for_member(chat_id, user["id"], after, limit)
|
||||
page = rows[:limit]
|
||||
return MessagePageResponse(items=page, next_cursor=next_page_cursor(rows, limit, scope))
|
||||
|
||||
Reference in New Issue
Block a user