65 lines
2.3 KiB
Python
65 lines
2.3 KiB
Python
#!/usr/bin/env python3
|
|
"""Конкурентный стресс БД: N потоков одновременно пишут (save_message) и читают
|
|
(get_history). Проверяет отсутствие «database is locked» под нагрузкой — acceptance
|
|
для WAL + busy_timeout (2.1). Создаёт и в конце удаляет только свои тест-строки
|
|
(username LIKE 'conc%'). Exit 1 при lock-ошибках.
|
|
|
|
Запуск на дев-сервере (из каталога инстанса):
|
|
DB_PATH=./smeta-web.db python3 tests/db_concurrency.py [workers] [iters]
|
|
"""
|
|
import sqlite3
|
|
import sys
|
|
import threading
|
|
import time
|
|
from pathlib import Path
|
|
|
|
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
|
import db
|
|
|
|
WORKERS = int(sys.argv[1]) if len(sys.argv) > 1 else 20
|
|
ITERS = int(sys.argv[2]) if len(sys.argv) > 2 else 50
|
|
errors: list[str] = []
|
|
|
|
|
|
def worker(wid: int):
|
|
for i in range(ITERS):
|
|
try:
|
|
db.save_message(f"conc{wid}", "t", "user", f"msg {wid}-{i} " + "x" * 200)
|
|
db.get_history(f"conc{wid}", "t", limit=10)
|
|
except Exception as e: # noqa: BLE001 — фиксируем любой сбой конкуренции
|
|
errors.append(f"{type(e).__name__}: {e}")
|
|
|
|
|
|
def main():
|
|
# текущий режим журнала
|
|
with db._conn() as c:
|
|
mode = c.execute("PRAGMA journal_mode").fetchone()[0]
|
|
t0 = time.time()
|
|
threads = [threading.Thread(target=worker, args=(w,)) for w in range(WORKERS)]
|
|
for t in threads:
|
|
t.start()
|
|
for t in threads:
|
|
t.join()
|
|
dt = time.time() - t0
|
|
total = WORKERS * ITERS * 2
|
|
locks = [e for e in errors if "locked" in e.lower()]
|
|
|
|
# teardown: удаляем только свои тест-строки
|
|
try:
|
|
with db._conn() as c:
|
|
c.execute("DELETE FROM messages WHERE username LIKE 'conc%'")
|
|
except Exception as e: # noqa: BLE001
|
|
print(f" teardown warn: {e}")
|
|
|
|
print(f"journal_mode={mode} workers={WORKERS} iters={ITERS} ops={total} "
|
|
f"time={dt:.1f}s ops/s={total/dt:.0f}")
|
|
print(f"errors={len(errors)} locks={len(locks)}")
|
|
for e in errors[:5]:
|
|
print(" ", e)
|
|
print("LOCKED ERRORS PRESENT" if locks else "NO LOCK ERRORS — WAL OK")
|
|
sys.exit(1 if locks else 0)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|