forked from retoor/devplacepy
Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
63366bb240 | ||
|
|
a55d12696a |
File diff suppressed because one or more lines are too long
@@ -30,26 +30,6 @@ def migrate_bug_tables_to_issue_tables() -> None:
|
||||
logger.info("Dropped table %s after migration", source_name)
|
||||
|
||||
|
||||
def _add_message_unique_index() -> None:
|
||||
if "messages" not in db.tables:
|
||||
return
|
||||
with db:
|
||||
db.query(
|
||||
"""
|
||||
DELETE FROM messages WHERE id NOT IN (
|
||||
SELECT MIN(id) FROM messages GROUP BY sender_uid, receiver_uid, content
|
||||
)
|
||||
"""
|
||||
)
|
||||
_index(
|
||||
db,
|
||||
"messages",
|
||||
"idx_messages_unique_sender_receiver_content",
|
||||
["sender_uid", "receiver_uid", "content"],
|
||||
unique=True,
|
||||
)
|
||||
|
||||
|
||||
def init_db():
|
||||
tables = db.tables
|
||||
_index(db, "users", "idx_users_username", ["username"])
|
||||
@@ -151,7 +131,6 @@ def init_db():
|
||||
"idx_messages_conversation_rev",
|
||||
["receiver_uid", "sender_uid"],
|
||||
)
|
||||
_add_message_unique_index()
|
||||
_index(db, "notifications", "idx_notifications_user", ["user_uid"])
|
||||
_index(db, "notifications", "idx_notifications_user_read", ["user_uid", "read"])
|
||||
_index(db, "push_registration", "idx_push_registration_user", ["user_uid"])
|
||||
|
||||
@@ -12,7 +12,6 @@ from fastapi import FastAPI, Request
|
||||
from fastapi.responses import HTMLResponse, RedirectResponse
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
from fastapi.exceptions import RequestValidationError
|
||||
from starlette.middleware.gzip import GZipMiddleware
|
||||
from devplacepy.config import (
|
||||
STATIC_DIR,
|
||||
STATIC_VERSION,
|
||||
@@ -610,10 +609,6 @@ async def response_timing(request: Request, call_next):
|
||||
response.headers["X-Response-Time"] = f"{(time.perf_counter() - start) * 1000:.1f}ms"
|
||||
return response
|
||||
|
||||
|
||||
app.add_middleware(GZipMiddleware, minimum_size=512, compresslevel=5)
|
||||
|
||||
|
||||
_home_cache = TTLCache(ttl=int(os.environ.get("DEVPLACE_HOME_CACHE_TTL", "60")), max_size=4)
|
||||
|
||||
|
||||
|
||||
@@ -88,7 +88,7 @@ def gateway_complete(
|
||||
{"role": "system", "content": system},
|
||||
{"role": "user", "content": text},
|
||||
],
|
||||
"temperature": 0.0,
|
||||
"temperature": 0.1,
|
||||
}
|
||||
headers = {
|
||||
"Content-Type": "application/json",
|
||||
|
||||
@@ -1,9 +1,6 @@
|
||||
# retoor <retoor@molodetz.nl>
|
||||
|
||||
import hashlib
|
||||
import logging
|
||||
import time
|
||||
from collections import OrderedDict
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any, Optional
|
||||
|
||||
@@ -18,16 +15,12 @@ from devplacepy.utils import (
|
||||
track_action,
|
||||
)
|
||||
from devplacepy.services.audit import record as audit
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
|
||||
from devplacepy.services.correction import schedule_correction
|
||||
from devplacepy.services.ai_modifier import schedule_modification
|
||||
|
||||
logger = logging.getLogger("messaging.persist")
|
||||
|
||||
MAX_CONTENT_LENGTH = 2000
|
||||
DEDUP_WINDOW_SECONDS = 3
|
||||
_content_cache: dict[str, tuple[float, str]] = OrderedDict()
|
||||
|
||||
|
||||
def _slim_attachment(attachment: dict[str, Any]) -> dict[str, Any]:
|
||||
@@ -88,60 +81,19 @@ def persist_message(
|
||||
|
||||
sender_uid = sender["uid"]
|
||||
sender_username = sender.get("username", "")
|
||||
|
||||
content_hash = hashlib.sha256(
|
||||
f"{sender_uid}:{receiver_uid}:{content}".encode()
|
||||
).hexdigest()[:16]
|
||||
now = time.time()
|
||||
last_seen, cached_uid = _content_cache.get(content_hash, (0.0, None))
|
||||
if now - last_seen < DEDUP_WINDOW_SECONDS and cached_uid is not None:
|
||||
logger.debug(
|
||||
"Dedup hit for message hash %s (original uid %s)", content_hash, cached_uid
|
||||
)
|
||||
cached = get_table("messages").find_one(uid=cached_uid)
|
||||
if cached:
|
||||
return {
|
||||
"uid": cached["uid"],
|
||||
"sender_uid": cached["sender_uid"],
|
||||
"receiver_uid": cached["receiver_uid"],
|
||||
"content": cached["content"],
|
||||
"read": cached.get("read", False),
|
||||
"created_at": cached["created_at"],
|
||||
}
|
||||
|
||||
messages_table = get_table("messages")
|
||||
msg_uid = generate_uid()
|
||||
created_at = datetime.now(timezone.utc).isoformat()
|
||||
|
||||
try:
|
||||
messages_table.insert(
|
||||
{
|
||||
"uid": msg_uid,
|
||||
"sender_uid": sender_uid,
|
||||
"receiver_uid": receiver_uid,
|
||||
"content": content,
|
||||
"read": False,
|
||||
"created_at": created_at,
|
||||
}
|
||||
)
|
||||
except IntegrityError:
|
||||
existing = messages_table.find_one(
|
||||
sender_uid=sender_uid, receiver_uid=receiver_uid, content=content
|
||||
)
|
||||
if not existing:
|
||||
raise
|
||||
logger.debug(
|
||||
"Dedup via unique constraint for message (uid %s)", existing["uid"]
|
||||
)
|
||||
_content_cache[content_hash] = (time.time(), existing["uid"])
|
||||
return {
|
||||
"uid": existing["uid"],
|
||||
"sender_uid": existing["sender_uid"],
|
||||
"receiver_uid": existing["receiver_uid"],
|
||||
"content": existing["content"],
|
||||
"read": existing.get("read", False),
|
||||
"created_at": existing["created_at"],
|
||||
messages_table.insert(
|
||||
{
|
||||
"uid": msg_uid,
|
||||
"sender_uid": sender_uid,
|
||||
"receiver_uid": receiver_uid,
|
||||
"content": content,
|
||||
"read": False,
|
||||
"created_at": created_at,
|
||||
}
|
||||
)
|
||||
|
||||
link_attachments(attachment_uids, "message", msg_uid)
|
||||
schedule_correction(sender, "messages", msg_uid, request)
|
||||
@@ -162,8 +114,6 @@ def persist_message(
|
||||
)
|
||||
track_action(sender_uid, "message")
|
||||
|
||||
_content_cache[content_hash] = (time.time(), msg_uid)
|
||||
|
||||
logger.info(
|
||||
"Message %s sent from %s to %s via %s",
|
||||
msg_uid,
|
||||
|
||||
@@ -11,7 +11,7 @@ How a request flows through middleware to a router, how the database layer is bu
|
||||
|
||||
## Middleware
|
||||
|
||||
Seven HTTP middlewares run as a stack around every request, listed outermost first. `response_timing` is the outermost, `refresh_db_snapshot` the innermost, and a `GZipMiddleware` (responses over 512 bytes) wraps the whole stack on top:
|
||||
Six HTTP middlewares run as a stack around every request, listed outermost first. `response_timing` is the outermost and `refresh_db_snapshot` the innermost. Compression is handled by nginx in production; the Python application does not compress responses itself.
|
||||
|
||||
| Middleware (outermost first) | Responsibility |
|
||||
|------------|----------------|
|
||||
|
||||
+2
-1
@@ -4,7 +4,8 @@ version = "1.0.0"
|
||||
description = "DevPlace - The Developer Social Network"
|
||||
requires-python = ">=3.12"
|
||||
dependencies = [
|
||||
"fastapi",
|
||||
"fastapi>=0.110.0",
|
||||
"starlette>=0.37.0",
|
||||
"uvicorn[standard]",
|
||||
"jinja2",
|
||||
"python-multipart",
|
||||
|
||||
@@ -166,23 +166,3 @@ def test_send_attachment_only_empty_content_succeeds(seeded_db):
|
||||
refresh_snapshot()
|
||||
row = get_table("messages").find_one(uid=msg["uid"])
|
||||
assert row["content"] == ""
|
||||
|
||||
|
||||
def test_duplicate_message_returns_same_uid(seeded_db):
|
||||
s, _ = _member()
|
||||
receiver = _db_user("bob_test")["uid"]
|
||||
content = _unique("dupmsg")
|
||||
|
||||
first = s.post(
|
||||
f"{BASE_URL}/messages/send",
|
||||
headers=JSON_audit_log,
|
||||
data={"content": content, "receiver_uid": receiver},
|
||||
).json()["data"]
|
||||
|
||||
second = s.post(
|
||||
f"{BASE_URL}/messages/send",
|
||||
headers=JSON_audit_log,
|
||||
data={"content": content, "receiver_uid": receiver},
|
||||
).json()["data"]
|
||||
|
||||
assert first["uid"] == second["uid"], "duplicate messages should return the same uid"
|
||||
|
||||
Reference in New Issue
Block a user