Spaces:
Running on Zero
Running on Zero
Commit ·
7982d01
1
Parent(s): 120bd9a
speed
Browse files- app/bot/handlers/admin.py +23 -1
- app/bot/handlers/gate.py +4 -3
- app/bot/handlers/library.py +5 -6
- app/bot/handlers/start.py +33 -20
- app/bot/middlewares/context.py +44 -11
- app/core/aio.py +12 -0
- app/core/cache.py +40 -0
- app/db/session.py +36 -2
- app/main.py +15 -9
- app/services/gate.py +1 -1
- app/services/referrals.py +2 -0
- app/services/users.py +22 -0
- tests/test_logic.py +11 -0
app/bot/handlers/admin.py
CHANGED
|
@@ -1,10 +1,12 @@
|
|
| 1 |
"""Admin-only tools (English on purpose). Admin ids come from the ADMIN_IDS secret."""
|
| 2 |
import logging
|
|
|
|
| 3 |
from typing import Optional
|
| 4 |
|
| 5 |
from aiogram import F, Router
|
| 6 |
from aiogram.filters import BaseFilter, Command, CommandObject
|
| 7 |
from aiogram.types import Message
|
|
|
|
| 8 |
from sqlalchemy.ext.asyncio import AsyncSession
|
| 9 |
|
| 10 |
from app.config import get_settings
|
|
@@ -31,7 +33,8 @@ HELP = (
|
|
| 31 |
"/addcourse <natural|social|all> <year 0-5> <code> <name...>\n"
|
| 32 |
" e.g. <code>/addcourse natural 1 Math1011 Calculus I</code>\n"
|
| 33 |
"/courses : list courses with ids\n"
|
| 34 |
-
"/stats : numbers\n
|
|
|
|
| 35 |
"<b>Upload a file:</b> send it here with caption\n"
|
| 36 |
"<code><course_id> <slide|exam|note|book> [title]</code>\n"
|
| 37 |
"e.g. <code>3 exam Midterm 2017</code>"
|
|
@@ -43,6 +46,25 @@ async def admin_help(message: Message) -> None:
|
|
| 43 |
await message.answer(HELP)
|
| 44 |
|
| 45 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 46 |
@router.message(Command("addcourse"))
|
| 47 |
async def add_course(message: Message, command: CommandObject, session: AsyncSession) -> None:
|
| 48 |
parts = (command.args or "").split(maxsplit=3)
|
|
|
|
| 1 |
"""Admin-only tools (English on purpose). Admin ids come from the ADMIN_IDS secret."""
|
| 2 |
import logging
|
| 3 |
+
import time
|
| 4 |
from typing import Optional
|
| 5 |
|
| 6 |
from aiogram import F, Router
|
| 7 |
from aiogram.filters import BaseFilter, Command, CommandObject
|
| 8 |
from aiogram.types import Message
|
| 9 |
+
from sqlalchemy import text
|
| 10 |
from sqlalchemy.ext.asyncio import AsyncSession
|
| 11 |
|
| 12 |
from app.config import get_settings
|
|
|
|
| 33 |
"/addcourse <natural|social|all> <year 0-5> <code> <name...>\n"
|
| 34 |
" e.g. <code>/addcourse natural 1 Math1011 Calculus I</code>\n"
|
| 35 |
"/courses : list courses with ids\n"
|
| 36 |
+
"/stats : numbers\n"
|
| 37 |
+
"/ping : measure database and Telegram speed\n\n"
|
| 38 |
"<b>Upload a file:</b> send it here with caption\n"
|
| 39 |
"<code><course_id> <slide|exam|note|book> [title]</code>\n"
|
| 40 |
"e.g. <code>3 exam Midterm 2017</code>"
|
|
|
|
| 46 |
await message.answer(HELP)
|
| 47 |
|
| 48 |
|
| 49 |
+
@router.message(Command("ping"))
|
| 50 |
+
async def ping(message: Message, session: AsyncSession) -> None:
|
| 51 |
+
"""Where does the time go? DB #1 includes connecting; DB #2 is the pure round-trip."""
|
| 52 |
+
t0 = time.perf_counter()
|
| 53 |
+
await session.execute(text("SELECT 1"))
|
| 54 |
+
db1 = (time.perf_counter() - t0) * 1000
|
| 55 |
+
t0 = time.perf_counter()
|
| 56 |
+
await session.execute(text("SELECT 1"))
|
| 57 |
+
db2 = (time.perf_counter() - t0) * 1000
|
| 58 |
+
t0 = time.perf_counter()
|
| 59 |
+
await message.bot.get_me()
|
| 60 |
+
tg = (time.perf_counter() - t0) * 1000
|
| 61 |
+
await message.answer(
|
| 62 |
+
f"🏓 DB #1 (with checkout): <b>{db1:.0f} ms</b>\n"
|
| 63 |
+
f"DB #2 (pure round-trip): <b>{db2:.0f} ms</b>\n"
|
| 64 |
+
f"Telegram API: <b>{tg:.0f} ms</b>"
|
| 65 |
+
)
|
| 66 |
+
|
| 67 |
+
|
| 68 |
@router.message(Command("addcourse"))
|
| 69 |
async def add_course(message: Message, command: CommandObject, session: AsyncSession) -> None:
|
| 70 |
parts = (command.args or "").split(maxsplit=3)
|
app/bot/handlers/gate.py
CHANGED
|
@@ -3,6 +3,7 @@ from aiogram.types import CallbackQuery
|
|
| 3 |
from sqlalchemy.ext.asyncio import AsyncSession
|
| 4 |
|
| 5 |
from app.bot.handlers.start import next_step
|
|
|
|
| 6 |
from app.core.i18n import t
|
| 7 |
from app.db.models import User
|
| 8 |
from app.services import gate
|
|
@@ -16,10 +17,10 @@ async def gate_check(call: CallbackQuery, user: User, session: AsyncSession) ->
|
|
| 16 |
if not await gate.is_member(call.bot, user.id, fresh=True):
|
| 17 |
await call.answer(t(user.lang, "gate_not_yet"), show_alert=True)
|
| 18 |
return
|
| 19 |
-
await call.answer()
|
| 20 |
if not user.gate_passed:
|
| 21 |
user.gate_passed = True
|
| 22 |
await referral_service.reward_if_eligible(session, call.bot, user)
|
| 23 |
if call.message:
|
| 24 |
-
await call.message.delete()
|
| 25 |
-
|
|
|
|
|
|
| 3 |
from sqlalchemy.ext.asyncio import AsyncSession
|
| 4 |
|
| 5 |
from app.bot.handlers.start import next_step
|
| 6 |
+
from app.core.aio import gather_safe
|
| 7 |
from app.core.i18n import t
|
| 8 |
from app.db.models import User
|
| 9 |
from app.services import gate
|
|
|
|
| 17 |
if not await gate.is_member(call.bot, user.id, fresh=True):
|
| 18 |
await call.answer(t(user.lang, "gate_not_yet"), show_alert=True)
|
| 19 |
return
|
|
|
|
| 20 |
if not user.gate_passed:
|
| 21 |
user.gate_passed = True
|
| 22 |
await referral_service.reward_if_eligible(session, call.bot, user)
|
| 23 |
if call.message:
|
| 24 |
+
await gather_safe(call.answer(), call.message.delete(), next_step(call.message, user))
|
| 25 |
+
else:
|
| 26 |
+
await call.answer()
|
app/bot/handlers/library.py
CHANGED
|
@@ -6,6 +6,7 @@ from aiogram.types import CallbackQuery, Message
|
|
| 6 |
from sqlalchemy.ext.asyncio import AsyncSession
|
| 7 |
|
| 8 |
from app.bot.keyboards import library as kb
|
|
|
|
| 9 |
from app.core.catalog import KINDS
|
| 10 |
from app.core.i18n import all_translations, t
|
| 11 |
from app.db.models import User
|
|
@@ -18,12 +19,10 @@ router = Router()
|
|
| 18 |
async def _show(target: Union[Message, CallbackQuery], text: str, markup) -> None:
|
| 19 |
"""Edit the current message when navigating, send a new one when opening from the menu."""
|
| 20 |
if isinstance(target, CallbackQuery):
|
|
|
|
| 21 |
if target.message:
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
except TelegramBadRequest:
|
| 25 |
-
pass # "message is not modified"
|
| 26 |
-
await target.answer()
|
| 27 |
else:
|
| 28 |
await target.answer(text, reply_markup=markup)
|
| 29 |
|
|
@@ -80,7 +79,7 @@ async def on_file(call: CallbackQuery, user: User, session: AsyncSession) -> Non
|
|
| 80 |
await call.answer(t(user.lang, "file_missing"), show_alert=True)
|
| 81 |
return
|
| 82 |
course = await repo.get_course(session, material.course_id) if material.course_id else None
|
| 83 |
-
await call.answer()
|
| 84 |
try:
|
| 85 |
await lib.send_material(call.bot, call.from_user.id, material, course)
|
| 86 |
material.downloads = (material.downloads or 0) + 1
|
|
|
|
| 6 |
from sqlalchemy.ext.asyncio import AsyncSession
|
| 7 |
|
| 8 |
from app.bot.keyboards import library as kb
|
| 9 |
+
from app.core.aio import gather_safe
|
| 10 |
from app.core.catalog import KINDS
|
| 11 |
from app.core.i18n import all_translations, t
|
| 12 |
from app.db.models import User
|
|
|
|
| 19 |
async def _show(target: Union[Message, CallbackQuery], text: str, markup) -> None:
|
| 20 |
"""Edit the current message when navigating, send a new one when opening from the menu."""
|
| 21 |
if isinstance(target, CallbackQuery):
|
| 22 |
+
calls = [target.answer()]
|
| 23 |
if target.message:
|
| 24 |
+
calls.append(target.message.edit_text(text, reply_markup=markup))
|
| 25 |
+
await gather_safe(*calls) # "message is not modified" etc. are logged, never raised
|
|
|
|
|
|
|
|
|
|
| 26 |
else:
|
| 27 |
await target.answer(text, reply_markup=markup)
|
| 28 |
|
|
|
|
| 79 |
await call.answer(t(user.lang, "file_missing"), show_alert=True)
|
| 80 |
return
|
| 81 |
course = await repo.get_course(session, material.course_id) if material.course_id else None
|
| 82 |
+
await gather_safe(call.answer(), call.bot.send_chat_action(call.from_user.id, "upload_document"))
|
| 83 |
try:
|
| 84 |
await lib.send_material(call.bot, call.from_user.id, material, course)
|
| 85 |
material.downloads = (material.downloads or 0) + 1
|
app/bot/handlers/start.py
CHANGED
|
@@ -4,6 +4,7 @@ from aiogram.types import CallbackQuery, Message
|
|
| 4 |
from sqlalchemy.ext.asyncio import AsyncSession
|
| 5 |
|
| 6 |
from app.bot.keyboards.common import main_menu, stream_kb, year_kb
|
|
|
|
| 7 |
from app.core.catalog import STREAMS, YEARS
|
| 8 |
from app.core.i18n import t
|
| 9 |
from app.db.models import User
|
|
@@ -11,43 +12,55 @@ from app.db.models import User
|
|
| 11 |
router = Router()
|
| 12 |
|
| 13 |
|
| 14 |
-
async def next_step(message: Message, user: User) -> None:
|
| 15 |
-
"""
|
| 16 |
lang = user.lang
|
|
|
|
| 17 |
if user.stream is None:
|
| 18 |
-
await message.answer(t(lang, "choose_stream"), reply_markup=stream_kb(lang))
|
| 19 |
elif user.year is None:
|
| 20 |
-
await message.answer(t(lang, "choose_year"), reply_markup=year_kb(lang))
|
| 21 |
else:
|
| 22 |
-
await message.answer(t(lang, "menu_title"), reply_markup=main_menu(lang))
|
| 23 |
|
| 24 |
|
| 25 |
@router.message(CommandStart())
|
| 26 |
async def cmd_start(message: Message, user: User) -> None:
|
| 27 |
-
|
| 28 |
-
await next_step(message, user)
|
| 29 |
|
| 30 |
|
| 31 |
@router.callback_query(F.data.startswith("ob:stream:"))
|
| 32 |
-
async def pick_stream(call: CallbackQuery, user: User
|
| 33 |
value = call.data.split(":")[2]
|
| 34 |
if value in STREAMS:
|
| 35 |
user.stream = value
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 40 |
|
| 41 |
|
| 42 |
@router.callback_query(F.data.startswith("ob:year:"))
|
| 43 |
-
async def pick_year(call: CallbackQuery, user: User
|
| 44 |
value = call.data.split(":")[2]
|
| 45 |
if value.isdigit() and int(value) in YEARS:
|
| 46 |
user.year = int(value)
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4 |
from sqlalchemy.ext.asyncio import AsyncSession
|
| 5 |
|
| 6 |
from app.bot.keyboards.common import main_menu, stream_kb, year_kb
|
| 7 |
+
from app.core.aio import gather_safe
|
| 8 |
from app.core.catalog import STREAMS, YEARS
|
| 9 |
from app.core.i18n import t
|
| 10 |
from app.db.models import User
|
|
|
|
| 12 |
router = Router()
|
| 13 |
|
| 14 |
|
| 15 |
+
async def next_step(message: Message, user: User, prefix: str = "") -> None:
|
| 16 |
+
"""ONE message for whichever onboarding step is missing (else the main menu)."""
|
| 17 |
lang = user.lang
|
| 18 |
+
lead = f"{prefix}\n\n" if prefix else ""
|
| 19 |
if user.stream is None:
|
| 20 |
+
await message.answer(lead + t(lang, "choose_stream"), reply_markup=stream_kb(lang))
|
| 21 |
elif user.year is None:
|
| 22 |
+
await message.answer(lead + t(lang, "choose_year"), reply_markup=year_kb(lang))
|
| 23 |
else:
|
| 24 |
+
await message.answer(lead + t(lang, "menu_title"), reply_markup=main_menu(lang))
|
| 25 |
|
| 26 |
|
| 27 |
@router.message(CommandStart())
|
| 28 |
async def cmd_start(message: Message, user: User) -> None:
|
| 29 |
+
welcome = t(user.lang, "welcome", name=message.from_user.full_name)
|
| 30 |
+
await next_step(message, user, prefix=welcome)
|
| 31 |
|
| 32 |
|
| 33 |
@router.callback_query(F.data.startswith("ob:stream:"))
|
| 34 |
+
async def pick_stream(call: CallbackQuery, user: User) -> None:
|
| 35 |
value = call.data.split(":")[2]
|
| 36 |
if value in STREAMS:
|
| 37 |
user.stream = value
|
| 38 |
+
if not call.message:
|
| 39 |
+
await call.answer()
|
| 40 |
+
return
|
| 41 |
+
if user.year is None:
|
| 42 |
+
# edit the same message: 1 API call instead of delete + send
|
| 43 |
+
await gather_safe(
|
| 44 |
+
call.answer(),
|
| 45 |
+
call.message.edit_text(t(user.lang, "choose_year"), reply_markup=year_kb(user.lang)),
|
| 46 |
+
)
|
| 47 |
+
else:
|
| 48 |
+
await gather_safe(call.answer(), call.message.delete(), next_step(call.message, user))
|
| 49 |
|
| 50 |
|
| 51 |
@router.callback_query(F.data.startswith("ob:year:"))
|
| 52 |
+
async def pick_year(call: CallbackQuery, user: User) -> None:
|
| 53 |
value = call.data.split(":")[2]
|
| 54 |
if value.isdigit() and int(value) in YEARS:
|
| 55 |
user.year = int(value)
|
| 56 |
+
if not call.message:
|
| 57 |
+
await call.answer()
|
| 58 |
+
return
|
| 59 |
+
if user.year is not None:
|
| 60 |
+
await gather_safe(
|
| 61 |
+
call.answer(),
|
| 62 |
+
call.message.delete(),
|
| 63 |
+
call.message.answer(t(user.lang, "onboarded"), reply_markup=main_menu(user.lang)),
|
| 64 |
+
)
|
| 65 |
+
else:
|
| 66 |
+
await gather_safe(call.answer(), call.message.delete(), next_step(call.message, user))
|
app/bot/middlewares/context.py
CHANGED
|
@@ -3,6 +3,7 @@ from typing import Any, Awaitable, Callable, Optional
|
|
| 3 |
from aiogram import BaseMiddleware
|
| 4 |
from aiogram.types import Message, TelegramObject
|
| 5 |
|
|
|
|
| 6 |
from app.db.session import SessionFactory
|
| 7 |
from app.services import engagement
|
| 8 |
from app.services import users as users_service
|
|
@@ -16,21 +17,53 @@ def _referrer_from(event: TelegramObject) -> Optional[int]:
|
|
| 16 |
return None
|
| 17 |
|
| 18 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
class ContextMiddleware(BaseMiddleware):
|
| 20 |
-
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
|
| 22 |
async def __call__(self, handler: Callable[[TelegramObject, dict], Awaitable[Any]],
|
| 23 |
event: TelegramObject, data: dict) -> Any:
|
| 24 |
tg = data.get("event_from_user")
|
| 25 |
if tg is None or tg.is_bot:
|
| 26 |
return await handler(event, data)
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
from aiogram import BaseMiddleware
|
| 4 |
from aiogram.types import Message, TelegramObject
|
| 5 |
|
| 6 |
+
from app.core import cache
|
| 7 |
from app.db.session import SessionFactory
|
| 8 |
from app.services import engagement
|
| 9 |
from app.services import users as users_service
|
|
|
|
| 17 |
return None
|
| 18 |
|
| 19 |
|
| 20 |
+
def _needs_commit(session) -> bool:
|
| 21 |
+
sync = session.sync_session
|
| 22 |
+
return bool(
|
| 23 |
+
sync.info.get("wrote")
|
| 24 |
+
or sync.new
|
| 25 |
+
or sync.deleted
|
| 26 |
+
or any(sync.is_modified(obj) for obj in sync.dirty)
|
| 27 |
+
)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
class ContextMiddleware(BaseMiddleware):
|
| 31 |
+
"""Per update: the current `user` (from memory when possible) + a lazily-connecting DB session.
|
| 32 |
+
|
| 33 |
+
- cache hit -> no DB query at all; a DB connection is only taken if a handler needs one
|
| 34 |
+
- read-only -> no COMMIT
|
| 35 |
+
- same user's updates are serialized with a lock (no lost updates / double onboarding)
|
| 36 |
+
"""
|
| 37 |
|
| 38 |
async def __call__(self, handler: Callable[[TelegramObject, dict], Awaitable[Any]],
|
| 39 |
event: TelegramObject, data: dict) -> Any:
|
| 40 |
tg = data.get("event_from_user")
|
| 41 |
if tg is None or tg.is_bot:
|
| 42 |
return await handler(event, data)
|
| 43 |
+
|
| 44 |
+
async with cache.lock_for(tg.id):
|
| 45 |
+
snap = cache.get(tg.id)
|
| 46 |
+
async with SessionFactory() as session:
|
| 47 |
+
if snap:
|
| 48 |
+
user = users_service.from_snapshot(snap)
|
| 49 |
+
session.add(user) # attach without any query
|
| 50 |
+
else:
|
| 51 |
+
user = await users_service.get_or_create(session, tg, _referrer_from(event))
|
| 52 |
+
data.update(session=session, user=user, lang=user.lang)
|
| 53 |
+
if user.is_banned:
|
| 54 |
+
return None
|
| 55 |
+
if user.gate_passed:
|
| 56 |
+
engagement.touch(user) # daily streak + points
|
| 57 |
+
|
| 58 |
+
result = await handler(event, data)
|
| 59 |
+
|
| 60 |
+
if _needs_commit(session):
|
| 61 |
+
await session.commit()
|
| 62 |
+
for other_id in session.sync_session.info.pop("invalidate", ()):
|
| 63 |
+
cache.invalidate(other_id) # rows changed on behalf of another user
|
| 64 |
+
fresh = users_service.snapshot(user)
|
| 65 |
+
if fresh:
|
| 66 |
+
cache.put(tg.id, fresh)
|
| 67 |
+
else:
|
| 68 |
+
cache.invalidate(tg.id)
|
| 69 |
+
return result
|
app/core/aio.py
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import asyncio
|
| 2 |
+
import logging
|
| 3 |
+
|
| 4 |
+
log = logging.getLogger(__name__)
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
async def gather_safe(*aws) -> None:
|
| 8 |
+
"""Run independent Telegram calls in parallel; log (never raise) failures."""
|
| 9 |
+
results = await asyncio.gather(*aws, return_exceptions=True)
|
| 10 |
+
for res in results:
|
| 11 |
+
if isinstance(res, Exception):
|
| 12 |
+
log.info("Parallel call failed: %r", res)
|
app/core/cache.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""In-memory user snapshots (so most updates need ZERO database round-trips)
|
| 2 |
+
plus per-user locks (same user's updates run one at a time)."""
|
| 3 |
+
import asyncio
|
| 4 |
+
import time
|
| 5 |
+
import weakref
|
| 6 |
+
from typing import Optional
|
| 7 |
+
|
| 8 |
+
_TTL = 600 # seconds
|
| 9 |
+
_MAX = 20_000
|
| 10 |
+
_snapshots: dict[int, tuple[float, dict]] = {}
|
| 11 |
+
_locks: "weakref.WeakValueDictionary[int, asyncio.Lock]" = weakref.WeakValueDictionary()
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def get(user_id: int) -> Optional[dict]:
|
| 15 |
+
item = _snapshots.get(user_id)
|
| 16 |
+
if item is None:
|
| 17 |
+
return None
|
| 18 |
+
expires, data = item
|
| 19 |
+
if expires < time.monotonic():
|
| 20 |
+
_snapshots.pop(user_id, None)
|
| 21 |
+
return None
|
| 22 |
+
return dict(data)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def put(user_id: int, data: dict) -> None:
|
| 26 |
+
if len(_snapshots) >= _MAX:
|
| 27 |
+
_snapshots.clear()
|
| 28 |
+
_snapshots[user_id] = (time.monotonic() + _TTL, dict(data))
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def invalidate(user_id: int) -> None:
|
| 32 |
+
_snapshots.pop(user_id, None)
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def lock_for(user_id: int) -> asyncio.Lock:
|
| 36 |
+
lock = _locks.get(user_id)
|
| 37 |
+
if lock is None:
|
| 38 |
+
lock = asyncio.Lock()
|
| 39 |
+
_locks[user_id] = lock
|
| 40 |
+
return lock
|
app/db/session.py
CHANGED
|
@@ -1,10 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
from sqlalchemy.engine import make_url
|
| 2 |
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
|
|
|
|
| 3 |
|
| 4 |
from app.config import get_settings
|
| 5 |
from app.db.base import Base
|
| 6 |
from app.db.migrate import run_migrations
|
| 7 |
|
|
|
|
|
|
|
| 8 |
|
| 9 |
def _build_engine():
|
| 10 |
url = make_url(get_settings().database_url)
|
|
@@ -14,10 +21,10 @@ def _build_engine():
|
|
| 14 |
# Supabase/Neon behind a transaction pooler:
|
| 15 |
# - drop ?sslmode=..., force asyncpg, require SSL
|
| 16 |
# - statement_cache_size=0 (pgbouncer transaction mode has no session prepared statements)
|
| 17 |
-
# -
|
| 18 |
url = url.set(drivername="postgresql+asyncpg", query={})
|
| 19 |
connect_args = {"ssl": "require", "statement_cache_size": 0}
|
| 20 |
-
kwargs.update(pool_size=5, max_overflow=5, pool_pre_ping=True, pool_recycle=
|
| 21 |
return create_async_engine(url, connect_args=connect_args, **kwargs)
|
| 22 |
|
| 23 |
|
|
@@ -25,9 +32,36 @@ engine = _build_engine()
|
|
| 25 |
SessionFactory = async_sessionmaker(engine, expire_on_commit=False, class_=AsyncSession)
|
| 26 |
|
| 27 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 28 |
async def init_db() -> None:
|
| 29 |
import app.db.models # noqa: F401 (register tables)
|
| 30 |
|
| 31 |
async with engine.begin() as conn:
|
| 32 |
await conn.run_sync(Base.metadata.create_all)
|
| 33 |
await run_migrations(engine)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import asyncio
|
| 2 |
+
import logging
|
| 3 |
+
|
| 4 |
+
from sqlalchemy import event
|
| 5 |
from sqlalchemy.engine import make_url
|
| 6 |
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
|
| 7 |
+
from sqlalchemy.orm import Session
|
| 8 |
|
| 9 |
from app.config import get_settings
|
| 10 |
from app.db.base import Base
|
| 11 |
from app.db.migrate import run_migrations
|
| 12 |
|
| 13 |
+
log = logging.getLogger(__name__)
|
| 14 |
+
|
| 15 |
|
| 16 |
def _build_engine():
|
| 17 |
url = make_url(get_settings().database_url)
|
|
|
|
| 21 |
# Supabase/Neon behind a transaction pooler:
|
| 22 |
# - drop ?sslmode=..., force asyncpg, require SSL
|
| 23 |
# - statement_cache_size=0 (pgbouncer transaction mode has no session prepared statements)
|
| 24 |
+
# - small client-side pool + pre_ping so stale connections never reach a handler
|
| 25 |
url = url.set(drivername="postgresql+asyncpg", query={})
|
| 26 |
connect_args = {"ssl": "require", "statement_cache_size": 0}
|
| 27 |
+
kwargs.update(pool_size=5, max_overflow=5, pool_pre_ping=True, pool_recycle=1800)
|
| 28 |
return create_async_engine(url, connect_args=connect_args, **kwargs)
|
| 29 |
|
| 30 |
|
|
|
|
| 32 |
SessionFactory = async_sessionmaker(engine, expire_on_commit=False, class_=AsyncSession)
|
| 33 |
|
| 34 |
|
| 35 |
+
@event.listens_for(Session, "after_flush")
|
| 36 |
+
def _mark_written(session, flush_context) -> None:
|
| 37 |
+
"""Remember that this session wrote something, so the middleware knows a COMMIT is needed
|
| 38 |
+
(read-only updates then skip the COMMIT round-trip entirely)."""
|
| 39 |
+
session.info["wrote"] = True
|
| 40 |
+
|
| 41 |
+
|
| 42 |
async def init_db() -> None:
|
| 43 |
import app.db.models # noqa: F401 (register tables)
|
| 44 |
|
| 45 |
async with engine.begin() as conn:
|
| 46 |
await conn.run_sync(Base.metadata.create_all)
|
| 47 |
await run_migrations(engine)
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
async def warm_up(n: int = 3) -> None:
|
| 51 |
+
"""Open a few pooled connections now so the first real users don't pay the handshake."""
|
| 52 |
+
|
| 53 |
+
async def one() -> None:
|
| 54 |
+
async with engine.connect() as conn:
|
| 55 |
+
await conn.exec_driver_sql("SELECT 1")
|
| 56 |
+
|
| 57 |
+
await asyncio.gather(*[one() for _ in range(n)], return_exceptions=True)
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
async def keepalive(interval: int = 45) -> None:
|
| 61 |
+
while True:
|
| 62 |
+
await asyncio.sleep(interval)
|
| 63 |
+
try:
|
| 64 |
+
async with engine.connect() as conn:
|
| 65 |
+
await conn.exec_driver_sql("SELECT 1")
|
| 66 |
+
except Exception as exc:
|
| 67 |
+
log.warning("DB keepalive failed: %r", exc)
|
app/main.py
CHANGED
|
@@ -8,7 +8,7 @@ from aiogram.enums import ParseMode
|
|
| 8 |
from app.bot.loader import build_dispatcher
|
| 9 |
from app.config import get_settings
|
| 10 |
from app.core.logging import setup_logging
|
| 11 |
-
from app.db.session import init_db
|
| 12 |
|
| 13 |
log = logging.getLogger(__name__)
|
| 14 |
|
|
@@ -16,18 +16,24 @@ log = logging.getLogger(__name__)
|
|
| 16 |
async def run_bot_forever() -> None:
|
| 17 |
setup_logging()
|
| 18 |
await init_db()
|
|
|
|
|
|
|
| 19 |
bot = Bot(
|
| 20 |
token=get_settings().bot_token,
|
| 21 |
default=DefaultBotProperties(parse_mode=ParseMode.HTML),
|
| 22 |
)
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 31 |
|
| 32 |
|
| 33 |
if __name__ == "__main__":
|
|
|
|
| 8 |
from app.bot.loader import build_dispatcher
|
| 9 |
from app.config import get_settings
|
| 10 |
from app.core.logging import setup_logging
|
| 11 |
+
from app.db.session import init_db, keepalive, warm_up
|
| 12 |
|
| 13 |
log = logging.getLogger(__name__)
|
| 14 |
|
|
|
|
| 16 |
async def run_bot_forever() -> None:
|
| 17 |
setup_logging()
|
| 18 |
await init_db()
|
| 19 |
+
await warm_up()
|
| 20 |
+
keepalive_task = asyncio.create_task(keepalive()) # keep a reference so it isn't garbage-collected
|
| 21 |
bot = Bot(
|
| 22 |
token=get_settings().bot_token,
|
| 23 |
default=DefaultBotProperties(parse_mode=ParseMode.HTML),
|
| 24 |
)
|
| 25 |
+
await bot.me() # cache bot info (used by the invite link) before the first user arrives
|
| 26 |
+
try:
|
| 27 |
+
while True:
|
| 28 |
+
try:
|
| 29 |
+
# handle_signals=False because we run in a non-main thread
|
| 30 |
+
await build_dispatcher().start_polling(bot, handle_signals=False)
|
| 31 |
+
break
|
| 32 |
+
except Exception:
|
| 33 |
+
log.exception("Polling crashed; restarting in 5s")
|
| 34 |
+
await asyncio.sleep(5)
|
| 35 |
+
finally:
|
| 36 |
+
keepalive_task.cancel()
|
| 37 |
|
| 38 |
|
| 39 |
if __name__ == "__main__":
|
app/services/gate.py
CHANGED
|
@@ -10,7 +10,7 @@ from app.config import get_settings
|
|
| 10 |
log = logging.getLogger(__name__)
|
| 11 |
_OK = {ChatMemberStatus.CREATOR, ChatMemberStatus.ADMINISTRATOR, ChatMemberStatus.MEMBER}
|
| 12 |
_cache: dict[int, float] = {}
|
| 13 |
-
_TTL =
|
| 14 |
|
| 15 |
|
| 16 |
async def is_member(bot: Bot, user_id: int, *, fresh: bool = False) -> bool:
|
|
|
|
| 10 |
log = logging.getLogger(__name__)
|
| 11 |
_OK = {ChatMemberStatus.CREATOR, ChatMemberStatus.ADMINISTRATOR, ChatMemberStatus.MEMBER}
|
| 12 |
_cache: dict[int, float] = {}
|
| 13 |
+
_TTL = 1800 # seconds a positive result is trusted
|
| 14 |
|
| 15 |
|
| 16 |
async def is_member(bot: Bot, user_id: int, *, fresh: bool = False) -> bool:
|
app/services/referrals.py
CHANGED
|
@@ -21,6 +21,8 @@ async def reward_if_eligible(session: AsyncSession, bot: Bot, invitee: User) ->
|
|
| 21 |
return
|
| 22 |
await repo.add(session, inviter.id, invitee.id)
|
| 23 |
inviter.points += REFERRAL_POINTS
|
|
|
|
|
|
|
| 24 |
try:
|
| 25 |
await bot.send_message(inviter.id, t(inviter.lang, "referral_reward", points=REFERRAL_POINTS))
|
| 26 |
except Exception as exc:
|
|
|
|
| 21 |
return
|
| 22 |
await repo.add(session, inviter.id, invitee.id)
|
| 23 |
inviter.points += REFERRAL_POINTS
|
| 24 |
+
# the inviter's cached snapshot is now stale; drop it once this transaction commits
|
| 25 |
+
session.sync_session.info.setdefault("invalidate", set()).add(inviter.id)
|
| 26 |
try:
|
| 27 |
await bot.send_message(inviter.id, t(inviter.lang, "referral_reward", points=REFERRAL_POINTS))
|
| 28 |
except Exception as exc:
|
app/services/users.py
CHANGED
|
@@ -1,12 +1,19 @@
|
|
| 1 |
from typing import Optional
|
| 2 |
|
| 3 |
from aiogram.types import User as TgUser
|
|
|
|
| 4 |
from sqlalchemy.ext.asyncio import AsyncSession
|
|
|
|
| 5 |
|
| 6 |
from app.config import get_settings
|
| 7 |
from app.db.models import User
|
| 8 |
from app.db.repos import users as repo
|
| 9 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10 |
|
| 11 |
async def get_or_create(
|
| 12 |
session: AsyncSession, tg: TgUser, referrer_hint: Optional[int] = None
|
|
@@ -25,3 +32,18 @@ async def get_or_create(
|
|
| 25 |
lang=get_settings().default_lang,
|
| 26 |
referred_by=referred_by,
|
| 27 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
from typing import Optional
|
| 2 |
|
| 3 |
from aiogram.types import User as TgUser
|
| 4 |
+
from sqlalchemy import inspect
|
| 5 |
from sqlalchemy.ext.asyncio import AsyncSession
|
| 6 |
+
from sqlalchemy.orm import make_transient_to_detached
|
| 7 |
|
| 8 |
from app.config import get_settings
|
| 9 |
from app.db.models import User
|
| 10 |
from app.db.repos import users as repo
|
| 11 |
|
| 12 |
+
SNAPSHOT_COLS = (
|
| 13 |
+
"id", "username", "full_name", "lang", "stream", "year", "referred_by",
|
| 14 |
+
"gate_passed", "points", "streak", "best_streak", "last_active_on", "is_banned",
|
| 15 |
+
)
|
| 16 |
+
|
| 17 |
|
| 18 |
async def get_or_create(
|
| 19 |
session: AsyncSession, tg: TgUser, referrer_hint: Optional[int] = None
|
|
|
|
| 32 |
lang=get_settings().default_lang,
|
| 33 |
referred_by=referred_by,
|
| 34 |
)
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def snapshot(user: User) -> Optional[dict]:
|
| 38 |
+
"""Plain-dict copy of the user row, or None if some column is not loaded."""
|
| 39 |
+
loaded = inspect(user).dict
|
| 40 |
+
if any(col not in loaded for col in SNAPSHOT_COLS):
|
| 41 |
+
return None
|
| 42 |
+
return {col: loaded[col] for col in SNAPSHOT_COLS}
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def from_snapshot(data: dict) -> User:
|
| 46 |
+
"""Rebuild a clean, detached User (no DB query). Attach with session.add()."""
|
| 47 |
+
user = User(**data)
|
| 48 |
+
make_transient_to_detached(user) # treat attributes as freshly loaded, no pending changes
|
| 49 |
+
return user
|
tests/test_logic.py
CHANGED
|
@@ -6,6 +6,7 @@ from types import SimpleNamespace
|
|
| 6 |
|
| 7 |
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
| 8 |
|
|
|
|
| 9 |
from app.services.engagement import DAILY_POINTS, MILESTONES, touch # noqa: E402
|
| 10 |
from app.services.ingest import parse_caption # noqa: E402
|
| 11 |
|
|
@@ -42,6 +43,16 @@ def test_streak_continues_and_resets():
|
|
| 42 |
assert u.streak == 1 and u.best_streak == 3
|
| 43 |
|
| 44 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 45 |
if __name__ == "__main__":
|
| 46 |
for name, fn in list(globals().items()):
|
| 47 |
if name.startswith("test_"):
|
|
|
|
| 6 |
|
| 7 |
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
| 8 |
|
| 9 |
+
from app.core import cache # noqa: E402
|
| 10 |
from app.services.engagement import DAILY_POINTS, MILESTONES, touch # noqa: E402
|
| 11 |
from app.services.ingest import parse_caption # noqa: E402
|
| 12 |
|
|
|
|
| 43 |
assert u.streak == 1 and u.best_streak == 3
|
| 44 |
|
| 45 |
|
| 46 |
+
def test_cache_roundtrip_and_isolation():
|
| 47 |
+
cache.put(7, {"points": 5})
|
| 48 |
+
got = cache.get(7)
|
| 49 |
+
assert got == {"points": 5}
|
| 50 |
+
got["points"] = 99 # mutating the copy must not touch the cache
|
| 51 |
+
assert cache.get(7) == {"points": 5}
|
| 52 |
+
cache.invalidate(7)
|
| 53 |
+
assert cache.get(7) is None
|
| 54 |
+
|
| 55 |
+
|
| 56 |
if __name__ == "__main__":
|
| 57 |
for name, fn in list(globals().items()):
|
| 58 |
if name.startswith("test_"):
|