perf: reuse authorized chat snapshot when reading history

This commit is contained in:
2026-11-15 19:33:13 +03:00
parent fa3a69d9b4
commit cabd0cacb3
52 changed files with 256655 additions and 6 deletions
+23
View File
@@ -0,0 +1,23 @@
name: Application integration
on: [push, pull_request, workflow_dispatch]
permissions:
contents: read
jobs:
application:
runs-on: ubuntu-latest
timeout-minutes: 20
steps:
- uses: actions/checkout@v4
- uses: astral-sh/setup-uv@v6
with:
version: 0.13.7
- run: uv sync --locked
- run: make bootstrap check validate lint PYTHON=.venv/bin/python
- run: VCS_REF=$(git rev-parse HEAD) docker compose up -d --build --wait
- run: make test test-student PYTHON=.venv/bin/python BASE_URL=http://127.0.0.1:8083
env:
NO_PROXY: localhost,127.0.0.1
no_proxy: localhost,127.0.0.1
- run: make verify VERIFY_OUTPUT=evidence/cluster-ci.json
- if: always()
run: docker compose down --volumes --remove-orphans
+22 -1
View File
@@ -77,7 +77,26 @@ HAProxy 3.2.1 закреплён digest, использует Docker DNS 127.0.0
Проверки выполняются последовательно относительно изменений одного стенда. Первый собственный прогон был испорчен ошибочной пересборкой всех API/LB во время тестов: 503 и connection refused; этот прогон не засчитан. Повтор на готовом стенде: **87passed, 279.66с**; детали в `evidence/http-tests.json`.
Результаты аварийных сценариев, матрицы масштабирования и чистого clone добавляются после их выполнения. Для уровня5 предусмотрены фиксированная суммарная квота API1CPU/1024MiB и серия с ростом ресурсов0.5CPU/256MiB на реплику; 1/2/4 процесса, C1/8/32, два повтора,2с прогрева и6с измерения. Смешанный closed-loop профиль:80% чтений истории limit20 и20% отправок с уникальными ключами. Перед каждой ячейкой в отдельном исследовательском проекте очищается только его новая БД и создаётся100 сообщений. Отдельно сравнивается пул1/10 при N2/C32 в трёх чередующихся повторах. Пока измерений нет, выигрыш не заявляется.
В `evidence/cluster-first.json` сохранены30 параллельных одинаковых POST через обе реальные реплики: один Message. Инъекция исключения в INSERT idempotency вернула500 и оставила0 сообщений; повтор того же key после удаления fault завершился201. Искусственное истечение записи разрешило новый результат.
Остановка API1:221 подтверждённых записей/215 чтений,7 ошибок, первый успех после завершения action4.191с от его старта. API2:211/203,9 ошибок,3.643с. Это15-секундные серии с паузой40ms между циклами чтение/запись. Все подтверждённые Message и уникальность text проверены по полной истории. Public failover отдельно:115 успешных записей,3 ошибки, восстановление3.142с; наблюдались2 alias до отказа. Операторские before/after содержат CID/PID/StartedAt и реальные квоты/ports.
Поочерёдная замена:655 подтверждённых записей,36 ошибок запросов за45-секундное окно. Старые контейнеры заменены новыми API3/4; replay прежнего ключа вернул исходный Message. Стенд не обещает безошибочную замену: в этой реализации обнаружение изменения адресов и закрытие keep-alive могут давать краткие503/обрывы. Подтверждённые данные не потеряны; клиент может повторить неопределённый POST тем же ключом. Полный restart API/PG/cache/LB прошёл public persistence; StartedAt всех state services и LB изменились. Ни volumes, ни токены не заменялись.
| Критерий README | Реализация и проверка | Evidence |
|---|---|---|
| 3: две API, один LB, общий PG/сессии | Compose scale2, HTTP через LB, реальные разные CID/PID | `evidence/cluster-first.json` |
| 3: единая действующая сессия через реплики | 30 concurrent POST, два alias, один результат | тот же файл |
| 3: остановка любой API, запись≤10с, сохранность | обе API остановлены по очереди, проверена вся история | тот же файл |
| 3: одинаковый ключ без дублей, конфликт body | PostgreSQL transaction, HTTP concurrent/conflict, 5xx rollback | `evidence/http-tests.json`, `evidence/cluster-first.json` |
| 3: smoke/persistence/failover | исходные публичные TCP-сценарии | `evidence/cluster-first.json`; smoke повторяется в clean clone |
| 4: readiness, deadlines, SIGTERM и исключение backend | HAProxy check1с/fall2 и конечные бюджеты | `infra/haproxy.cfg`, `evidence/cluster-first.json` |
| 4: остановить каждую API с RPS/errors/recovery | собственные15-секундные серии | `evidence/cluster-first.json` |
| 4: квоты, закрытые API ports, нет container_name | compose и inspect обеих API | тот же файл |
| 4: последовательная замена под нагрузкой, миграции отдельно | surge одна готовая API, SIGTERM старой;002 expand | тот же файл, `migrations/002_idempotency.sql` |
| 5: fixed/growing1/2/4, saturation, улучшение | изолированная матрица | результат добавляется после выполнения |
Матрица масштабирования и чистый clone ещё выполняются. Для уровня5 предусмотрены фиксированная суммарная квота API1CPU/1024MiB и серия с ростом ресурсов0.5CPU/256MiB на реплику; 1/2/4 процесса, C1/8/32, два повтора,2с прогрева и6с измерения. Смешанный closed-loop профиль:80% чтений истории limit20 и20% отправок с уникальными ключами. Перед каждой ячейкой в отдельном исследовательском проекте очищается только его новая БД и создаётся100 сообщений. Отдельно сравнивается пул1/10 при N2/C32 в трёх чередующихся повторах. Пока измерений нет, выигрыш не заявляется.
## Вопросы защиты
@@ -94,3 +113,5 @@ HAProxy 3.2.1 закреплён digest, использует Docker DNS 127.0.0
Один LB, PostgreSQL, Valkey и Docker-host; потеря БД/host не маскируется ростом API. TLS, репликация PostgreSQL, backup/PITR и промышленное наблюдение здесь не добавлены. HTTP доступен только на loopback, данные синтетические. Closed-loop имеет coordinated omission; короткий локальный прогон не задаёт production SLA. Пул — на процесс: рост реплик увеличивает возможное суммарное число PG-соединений.
Источники: [HAProxy3.2 configuration](https://docs.haproxy.org/3.2/configuration.html), [PG18 explicit locks](https://www.postgresql.org/docs/18/explicit-locking.html), [Compose services](https://docs.docker.com/reference/compose-file/services/). Библиотеки перечислены в `pyproject.toml`, точные версии — `uv.lock`. Помощь ИИ использована при разборе требований, подготовке реализации и проверок; результаты подтверждаются сохранёнными запусками.
Собственный `.github/workflows/application.yml` описывает сборку и интеграцию на runner с Docker; наличие файла не означает, что удалённый runner запущен или CI прошёл.
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+30
View File
@@ -0,0 +1,30 @@
# Измерения масштабирования
Source commit: `fa3a69d9b4267939fae8db422dff31cd079725f5`.
Медианы повторов; latency percentile внутри каждого прогона относится только к успешным ответам.
| Серия | API | C | RPS | p95, ms | Ошибки |
|---|---:|---:|---:|---:|---:|
| fixed | 1 | 1 | 157.3 | 8.95 | 0 |
| fixed | 1 | 8 | 205.2 | 75.84 | 0 |
| fixed | 1 | 32 | 177.9 | 425.05 | 0 |
| fixed | 2 | 1 | 140.8 | 9.81 | 0 |
| fixed | 2 | 8 | 185.1 | 99.24 | 0 |
| fixed | 2 | 32 | 162.1 | 462.64 | 0 |
| fixed | 4 | 1 | 134.2 | 10.61 | 0 |
| fixed | 4 | 8 | 155.2 | 222.69 | 0 |
| fixed | 4 | 32 | 128.5 | 883.62 | 0 |
| growing | 1 | 1 | 124.3 | 13.84 | 0 |
| growing | 1 | 8 | 110.4 | 102.86 | 0 |
| growing | 1 | 32 | 94.1 | 455.20 | 0 |
| growing | 2 | 1 | 132.6 | 11.20 | 0 |
| growing | 2 | 8 | 185.3 | 98.75 | 0 |
| growing | 2 | 32 | 164.3 | 520.34 | 0 |
| growing | 4 | 1 | 123.4 | 12.82 | 0 |
| growing | 4 | 8 | 257.9 | 107.74 | 0 |
| growing | 4 | 32 | 158.9 | 577.39 | 0 |
Пул1 → пул10: 200.4 → 175.8 успешных RPS (N2/C32, три повтора).
Настройка считается подтверждённым улучшением только при наблюдаемом выигрыше; это ограниченная локальная серия.
+62
View File
@@ -0,0 +1,62 @@
{
"source_commit": "fa3a69d9b4267939fae8db422dff31cd079725f5",
"date": "2026-11-15T16:18:34.862014+00:00",
"host": "macOS-15.4.1-arm64-arm-64bit-Mach-O",
"docker": {
"ServerVersion": "29.9.2",
"NCPU": 8,
"MemTotal": 6209978368,
"Architecture": "aarch64",
"OperatingSystem": "Docker Desktop"
},
"duration": 6,
"warmup": 2,
"profile": "80% GET history limit20; 20% POST unique key; closed-loop",
"complete": true,
"cells": [
"01-fixed-n1-c1-r1-p10.json",
"02-fixed-n1-c1-r2-p10.json",
"03-fixed-n1-c8-r1-p10.json",
"04-fixed-n1-c8-r2-p10.json",
"05-fixed-n1-c32-r1-p10.json",
"06-fixed-n1-c32-r2-p10.json",
"07-fixed-n2-c1-r1-p10.json",
"08-fixed-n2-c1-r2-p10.json",
"09-fixed-n2-c8-r1-p10.json",
"10-fixed-n2-c8-r2-p10.json",
"11-fixed-n2-c32-r1-p10.json",
"12-fixed-n2-c32-r2-p10.json",
"13-fixed-n4-c1-r1-p10.json",
"14-fixed-n4-c1-r2-p10.json",
"15-fixed-n4-c8-r1-p10.json",
"16-fixed-n4-c8-r2-p10.json",
"17-fixed-n4-c32-r1-p10.json",
"18-fixed-n4-c32-r2-p10.json",
"19-growing-n1-c1-r1-p10.json",
"20-growing-n1-c1-r2-p10.json",
"21-growing-n1-c8-r1-p10.json",
"22-growing-n1-c8-r2-p10.json",
"23-growing-n1-c32-r1-p10.json",
"24-growing-n1-c32-r2-p10.json",
"25-growing-n2-c1-r1-p10.json",
"26-growing-n2-c1-r2-p10.json",
"27-growing-n2-c8-r1-p10.json",
"28-growing-n2-c8-r2-p10.json",
"29-growing-n2-c32-r1-p10.json",
"30-growing-n2-c32-r2-p10.json",
"31-growing-n4-c1-r1-p10.json",
"32-growing-n4-c1-r2-p10.json",
"33-growing-n4-c8-r1-p10.json",
"34-growing-n4-c8-r2-p10.json",
"35-growing-n4-c32-r1-p10.json",
"36-growing-n4-c32-r2-p10.json",
"37-pool-n2-c32-r1-p1.json",
"38-pool-n2-c32-r1-p10.json",
"39-pool-n2-c32-r2-p10.json",
"40-pool-n2-c32-r2-p1.json",
"41-pool-n2-c32-r3-p1.json",
"42-pool-n2-c32-r3-p10.json"
],
"runtime_image_revision": "df4eee9a55f0cd9476744ea4c75cba1c1b3a4a98",
"runtime_equal_to_source_commit": true
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 106 KiB

+43
View File
@@ -0,0 +1,43 @@
series,replicas,concurrency,repeat,pool_size,successful_rps,errors,error_ratio,p50_ms,p95_ms,p99_ms
fixed,1,1,1,10,165.07767947989907,0,0.0,5.686,7.629,10.809
fixed,1,1,2,10,149.61439409018604,0,0.0,5.981,10.269,17.642
fixed,1,8,1,10,211.65991899019832,0,0.0,31.413,68.508,94.733
fixed,1,8,2,10,198.8283289091601,0,0.0,34.161,83.179,106.195
fixed,1,32,1,10,179.06741388685083,0,0.0,152.428,439.242,719.485
fixed,1,32,2,10,176.78095424063739,0,0.0,155.509,410.849,692.851
fixed,2,1,1,10,129.02990662137603,0,0.0,6.278,10.864,54.8
fixed,2,1,2,10,152.62929263739855,0,0.0,6.123,8.759,14.204
fixed,2,8,1,10,196.4800359108998,0,0.0,17.626,94.998,115.954
fixed,2,8,2,10,173.69962390399843,0,0.0,22.429,103.486,184.548
fixed,2,32,1,10,156.50040487681198,0,0.0,181.718,443.704,663.946
fixed,2,32,2,10,167.65953701338876,0,0.0,166.392,481.584,704.593
fixed,4,1,1,10,142.48482239783186,0,0.0,6.389,10.367,17.647
fixed,4,1,2,10,125.88207648163838,0,0.0,6.332,10.843,44.555
fixed,4,8,1,10,118.34539999970386,0,0.0,12.522,264.825,464.998
fixed,4,8,2,10,192.1342057427685,0,0.0,9.542,180.554,195.196
fixed,4,32,1,10,138.28620618496345,0,0.0,15.618,974.776,1248.537
fixed,4,32,2,10,118.77886331824459,0,0.0,198.297,792.454,1376.883
growing,1,1,1,10,116.48100146330145,0,0.0,5.944,16.399,77.405
growing,1,1,2,10,132.20926320279918,0,0.0,6.018,11.287,72.127
growing,1,8,1,10,109.33665681551416,0,0.0,86.76,103.52,114.182
growing,1,8,2,10,111.36479209555996,0,0.0,86.354,102.192,107.991
growing,1,32,1,10,97.35188039185765,0,0.0,308.314,415.437,489.101
growing,1,32,2,10,90.82762345324294,0,0.0,320.147,494.966,585.341
growing,2,1,1,10,124.799942422262,0,0.0,6.546,11.811,59.12
growing,2,1,2,10,140.46007909177436,0,0.0,6.62,10.59,16.863
growing,2,8,1,10,195.37255277667734,0,0.0,16.973,95.054,167.252
growing,2,8,2,10,175.30636015284236,0,0.0,19.372,102.439,184.685
growing,2,32,1,10,158.50391583720702,0,0.0,178.795,565.052,758.551
growing,2,32,2,10,170.11492222924323,0,0.0,177.916,475.635,605.655
growing,4,1,1,10,115.16211935610346,0,0.0,6.858,14.033,58.519
growing,4,1,2,10,131.5487532925524,0,0.0,6.616,11.609,22.638
growing,4,8,1,10,277.1422612739073,0,0.0,12.846,95.114,156.297
growing,4,8,2,10,238.7251942336141,0,0.0,14.245,120.368,204.822
growing,4,32,1,10,151.42242336820735,0,0.0,148.202,613.274,828.682
growing,4,32,2,10,166.35153942031727,0,0.0,127.253,541.513,733.458
pool,2,32,1,1,206.3668093701107,0,0.0,148.348,298.829,416.622
pool,2,32,1,10,157.87641931117705,0,0.0,204.863,416.938,510.686
pool,2,32,2,10,178.67593359431726,0,0.0,185.302,327.124,402.2
pool,2,32,2,1,168.0097097888627,0,0.0,179.629,394.52,504.704
pool,2,32,3,1,200.35677878454243,0,0.0,151.213,304.633,404.823
pool,2,32,3,10,175.76904087132343,0,0.0,190.759,392.898,474.386
1 series replicas concurrency repeat pool_size successful_rps errors error_ratio p50_ms p95_ms p99_ms
2 fixed 1 1 1 10 165.07767947989907 0 0.0 5.686 7.629 10.809
3 fixed 1 1 2 10 149.61439409018604 0 0.0 5.981 10.269 17.642
4 fixed 1 8 1 10 211.65991899019832 0 0.0 31.413 68.508 94.733
5 fixed 1 8 2 10 198.8283289091601 0 0.0 34.161 83.179 106.195
6 fixed 1 32 1 10 179.06741388685083 0 0.0 152.428 439.242 719.485
7 fixed 1 32 2 10 176.78095424063739 0 0.0 155.509 410.849 692.851
8 fixed 2 1 1 10 129.02990662137603 0 0.0 6.278 10.864 54.8
9 fixed 2 1 2 10 152.62929263739855 0 0.0 6.123 8.759 14.204
10 fixed 2 8 1 10 196.4800359108998 0 0.0 17.626 94.998 115.954
11 fixed 2 8 2 10 173.69962390399843 0 0.0 22.429 103.486 184.548
12 fixed 2 32 1 10 156.50040487681198 0 0.0 181.718 443.704 663.946
13 fixed 2 32 2 10 167.65953701338876 0 0.0 166.392 481.584 704.593
14 fixed 4 1 1 10 142.48482239783186 0 0.0 6.389 10.367 17.647
15 fixed 4 1 2 10 125.88207648163838 0 0.0 6.332 10.843 44.555
16 fixed 4 8 1 10 118.34539999970386 0 0.0 12.522 264.825 464.998
17 fixed 4 8 2 10 192.1342057427685 0 0.0 9.542 180.554 195.196
18 fixed 4 32 1 10 138.28620618496345 0 0.0 15.618 974.776 1248.537
19 fixed 4 32 2 10 118.77886331824459 0 0.0 198.297 792.454 1376.883
20 growing 1 1 1 10 116.48100146330145 0 0.0 5.944 16.399 77.405
21 growing 1 1 2 10 132.20926320279918 0 0.0 6.018 11.287 72.127
22 growing 1 8 1 10 109.33665681551416 0 0.0 86.76 103.52 114.182
23 growing 1 8 2 10 111.36479209555996 0 0.0 86.354 102.192 107.991
24 growing 1 32 1 10 97.35188039185765 0 0.0 308.314 415.437 489.101
25 growing 1 32 2 10 90.82762345324294 0 0.0 320.147 494.966 585.341
26 growing 2 1 1 10 124.799942422262 0 0.0 6.546 11.811 59.12
27 growing 2 1 2 10 140.46007909177436 0 0.0 6.62 10.59 16.863
28 growing 2 8 1 10 195.37255277667734 0 0.0 16.973 95.054 167.252
29 growing 2 8 2 10 175.30636015284236 0 0.0 19.372 102.439 184.685
30 growing 2 32 1 10 158.50391583720702 0 0.0 178.795 565.052 758.551
31 growing 2 32 2 10 170.11492222924323 0 0.0 177.916 475.635 605.655
32 growing 4 1 1 10 115.16211935610346 0 0.0 6.858 14.033 58.519
33 growing 4 1 2 10 131.5487532925524 0 0.0 6.616 11.609 22.638
34 growing 4 8 1 10 277.1422612739073 0 0.0 12.846 95.114 156.297
35 growing 4 8 2 10 238.7251942336141 0 0.0 14.245 120.368 204.822
36 growing 4 32 1 10 151.42242336820735 0 0.0 148.202 613.274 828.682
37 growing 4 32 2 10 166.35153942031727 0 0.0 127.253 541.513 733.458
38 pool 2 32 1 1 206.3668093701107 0 0.0 148.348 298.829 416.622
39 pool 2 32 1 10 157.87641931117705 0 0.0 204.863 416.938 510.686
40 pool 2 32 2 10 178.67593359431726 0 0.0 185.302 327.124 402.2
41 pool 2 32 2 1 168.0097097888627 0 0.0 179.629 394.52 504.704
42 pool 2 32 3 1 200.35677878454243 0 0.0 151.213 304.633 404.823
43 pool 2 32 3 10 175.76904087132343 0 0.0 190.759 392.898 474.386
+173
View File
@@ -0,0 +1,173 @@
"""Чередующееся сравнение двух собственных образов на отдельном стенде."""
import argparse
import asyncio
import json
import os
import socket
import threading
import time
from datetime import UTC, datetime
from pathlib import Path
from uuid import uuid4
import httpx
from research.run import command, compose, cpu_counters, load, sample
from scripts.stand import actor, auth
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--before", required=True)
parser.add_argument("--after", required=True)
parser.add_argument("--output", required=True)
args = parser.parse_args()
out = Path(args.output)
out.mkdir(parents=True, exist_ok=False)
with socket.socket() as sock:
sock.bind(("127.0.0.1", 0))
port = sock.getsockname()[1]
project = "lab3-compare-" + uuid4().hex[:8]
env = {
**os.environ,
"COMPOSE_PROJECT_NAME": project,
"PUBLIC_PORT": str(port),
"API_REPLICAS": "4",
"API_CPUS": "1",
"API_MEMORY": "384m",
"DB_POOL_SIZE": "10",
}
report = {
"date": datetime.now(UTC).isoformat(),
"complete": False,
"profile": "80% GET limit20;20% POST; C16; 100 seed; warmup2s/measure12s; four API each1CPU/384MiB; PostgreSQL 0.1 vs 1CPU",
"images": {},
"cells": [],
}
for name, image in [("before", args.before), ("after", args.after)]:
info = json.loads(command(["docker", "image", "inspect", image], env))[
0
]
report["images"][name] = {
"image": image,
"digest": info["Id"],
"revision": info["Config"]["Labels"][
"org.opencontainers.image.revision"
],
}
try:
number = 0
cases = [
(repeat, version, pg_cpu)
for repeat in range(1, 4)
for pg_cpu in [0.1, 1.0]
for version in (
["before", "after"] if repeat % 2 else ["after", "before"]
)
]
for repeat, version, pg_cpu in cases:
number += 1
env["API_IMAGE"] = (
args.before if version == "before" else args.after
)
compose(env, "up", "-d", "--no-build", "--wait")
pg_cid = compose(env, "ps", "-q", "postgres")
command(["docker", "update", "--cpus", str(pg_cpu), pg_cid], env)
time.sleep(3)
assert project.startswith("lab3-compare-")
compose(
env,
"exec",
"-T",
"postgres",
"psql",
"-U",
"messenger",
"-d",
"messenger",
"-v",
"ON_ERROR_STOP=1",
"-c",
"TRUNCATE idempotency,messages,members,chats,sessions,users",
)
base = f"http://127.0.0.1:{port}"
with httpx.Client(
base_url=base, trust_env=False, timeout=15
) as client:
user, _, session = actor(client)
r = client.post(
"/api/v1/chats",
headers=auth(session),
json={
"title": "Controlled comparison",
"member_ids": [user["id"]],
},
)
assert r.status_code == 201
chat = r.json()["id"]
for i in range(100):
r = client.post(
f"/api/v1/chats/{chat}/messages",
headers={
**auth(session),
"Idempotency-Key": uuid4().hex,
},
json={"text": f"Seed {i}"},
)
assert r.status_code == 201
asyncio.run(load(base, session["token"], chat, 16, 2))
counters = cpu_counters(env)
pg_before = command(
["docker", "exec", pg_cid, "cat", "/sys/fs/cgroup/cpu.stat"],
env,
)
samples = []
stop = threading.Event()
thread = threading.Thread(target=sample, args=(env, stop, samples))
thread.start()
try:
result = asyncio.run(
load(base, session["token"], chat, 16, 12)
)
finally:
stop.set()
thread.join()
result.update(
version=version,
repeat=repeat,
samples=samples,
pg_cpu_limit=pg_cpu,
pg_cpu_before=pg_before,
pg_cpu_after=command(
[
"docker",
"exec",
pg_cid,
"cat",
"/sys/fs/cgroup/cpu.stat",
],
env,
),
cgroup_before=counters,
cgroup_after=cpu_counters(env),
)
name = f"{number:02}-{version}-pg{pg_cpu}-r{repeat}.json"
(out / name).write_text(
json.dumps(result, ensure_ascii=False, indent=2) + "\n"
)
report["cells"].append(name)
print(
f"{name}: {result['successful_rps']:.1f} RPS; {result['errors']} errors",
flush=True,
)
report["complete"] = True
finally:
(out / "run.json").write_text(
json.dumps(report, ensure_ascii=False, indent=2) + "\n"
)
compose(env, "down", "--volumes", "--remove-orphans")
if __name__ == "__main__":
main()
+2 -2
View File
@@ -268,13 +268,13 @@ async def send(request: Request, chat_id: str):
async def history(request: Request, chat_id: str):
user = await actor(request)
cid = parse_uuid(chat_id)
await run_io(service(request).get_chat, actor_id=user.id, chat_id=cid)
chat = await run_io(service(request).get_chat, actor_id=user.id, chat_id=cid)
limit, cursor = pagination(request)
return response(
await run_io(
service(request).history,
actor_id=user.id,
chat_id=cid,
chat=chat,
limit=limit,
cursor=cursor,
)
+5 -3
View File
@@ -7,7 +7,7 @@ from uuid import UUID, uuid4
from src.cursor import decode_cursor, encode_cursor
from src.domain import Chat, Message, Record, User, order_key, utcnow
from src.errors import DomainError, invalid
from src.errors import DomainError, invalid, not_found
from src.password import Passwords
from src.repository import PostgresRepository
@@ -158,9 +158,11 @@ class MessengerService:
return page(rows=rows, limit=limit, scope=scope)
def history(
self, *, actor_id: UUID, chat_id: UUID, limit: int, cursor: str | None
self, *, actor_id: UUID, chat: Chat, limit: int, cursor: str | None
) -> dict:
self.get_chat(actor_id=actor_id, chat_id=chat_id)
if actor_id not in chat.member_ids:
raise not_found()
chat_id = chat.id
scope = f"messages:{chat_id}"
after = decode_cursor(value=cursor, scope=scope)
rows = self.repository.list_messages(
+23
View File
@@ -0,0 +1,23 @@
from conftest import check, headers
def test_history_acl_precedes_query_validation(client, actors, chat):
path = f"/api/v1/chats/{chat['id']}/messages"
check(
client.get(
path,
headers=headers(actors[2]),
params={"limit": 0, "cursor": "broken"},
),
404,
"Error",
)
check(
client.get(
path,
headers=headers(actors[0]),
params={"limit": 0, "cursor": "broken"},
),
400,
"Error",
)