ЛР3 - БВТ2303 - Кунецкий - на 5 #12
@@ -18,3 +18,7 @@ __pycache__
|
||||
node_modules
|
||||
evidence
|
||||
.DS_Store
|
||||
bin
|
||||
coverage.out
|
||||
coverage.out.tmp
|
||||
*.log
|
||||
|
||||
+81
-10
@@ -1,13 +1,84 @@
|
||||
# Copy to .env for your LOCAL synthetic test environment; never commit .env.
|
||||
# These are logical interface suggestions; map actual framework names in REPORT.md.
|
||||
APP_HOST=0.0.0.0
|
||||
APP_PORT=8080
|
||||
APP_ENV=lab
|
||||
# Values below are the variables this implementation actually reads
|
||||
# (viper: section.name -> SECTION_NAME, see internal/config/config.go).
|
||||
#
|
||||
# Mapping to the logical names suggested by the skeleton:
|
||||
# APP_HOST / APP_PORT -> SERVER_HOST / SERVER_PORT
|
||||
# SESSION_STORE=postgres -> server-side sessions live in PostgreSQL (SESSION_TTL_SECONDS)
|
||||
# DATABASE_URL_FILE -> unused: POSTGRES_* below pass no secret files
|
||||
# CACHE_URL_FILE -> unused: REDIS_* below pass no secret files
|
||||
# API_REPLICAS -> number of API replicas of the stand (compose.yaml)
|
||||
#
|
||||
# APP_ENV selects config/<env>/config.yaml; the implementation supports only `dev`.
|
||||
APP_ENV=dev
|
||||
|
||||
SERVER_HOST=0.0.0.0
|
||||
SERVER_PORT=8080
|
||||
SERVER_READ_HEADER_TIMEOUT=10s
|
||||
SERVER_SHUTDOWN_TIMEOUT=10s
|
||||
# Предел размера тела запроса (байт): защищает реплику от чтения огромного тела
|
||||
# до валидации. Для вложений LAB4 (до 10 MiB) значение нужно поднять.
|
||||
SERVER_MAX_BODY_BYTES=262144
|
||||
|
||||
LOG_LEVEL=info
|
||||
LOG_FORMAT=json
|
||||
|
||||
# Synthetic credentials for the local stand only; override in .env for anything else.
|
||||
POSTGRES_HOST=localhost
|
||||
POSTGRES_PORT=5432
|
||||
POSTGRES_DATABASE=messenger
|
||||
POSTGRES_USER=messenger
|
||||
POSTGRES_PASSWORD=messenger
|
||||
POSTGRES_SSL_MODE=disable
|
||||
POSTGRES_MAX_CONNS=10
|
||||
POSTGRES_MIN_CONNS=1
|
||||
POSTGRES_MAX_CONN_LIFETIME=1h
|
||||
POSTGRES_MAX_CONN_IDLE_TIME=30m
|
||||
POSTGRES_CONNECT_TIMEOUT=5s
|
||||
POSTGRES_QUERY_TIMEOUT=5s
|
||||
|
||||
REDIS_ENABLED=true
|
||||
REDIS_HOST=localhost
|
||||
REDIS_PORT=6379
|
||||
REDIS_PASSWORD=
|
||||
REDIS_DB=0
|
||||
# -1 disables go-redis retries; 0 keeps the library default (3 retries).
|
||||
REDIS_MAX_RETRIES=-1
|
||||
REDIS_DIAL_TIMEOUT=300ms
|
||||
REDIS_READ_TIMEOUT=200ms
|
||||
REDIS_WRITE_TIMEOUT=200ms
|
||||
REDIS_POOL_SIZE=10
|
||||
|
||||
CACHE_ENABLED=true
|
||||
CACHE_CHAT_LIST_TTL=5m
|
||||
CACHE_LOCK_TTL=10s
|
||||
CACHE_LOCK_WAIT_TIMEOUT=2s
|
||||
|
||||
SESSION_TTL_SECONDS=3600
|
||||
# Choose credentials locally. File paths contain no secret values.
|
||||
DATABASE_URL_FILE=/run/secrets/database_url
|
||||
# Optional on 3, required use on 4 in lab2; Redis OR Valkey:
|
||||
SESSION_STORE=postgres
|
||||
CACHE_URL_FILE=/run/secrets/cache_url
|
||||
API_REPLICAS=2
|
||||
|
||||
# Retention of a message Idempotency-Key in the shared store; contract 1.3.0
|
||||
# requires at least 24 h.
|
||||
IDEMPOTENCY_TTL_SECONDS=86400
|
||||
|
||||
# Lab3 stand (compose.yaml): number of API replicas behind the LB and per-replica
|
||||
# CPU/RAM limits. Track 1 varies them to compare 1/2/4 replicas at a fixed total
|
||||
# budget, e.g. API_REPLICAS=4 API_CPU_LIMIT=0.25 API_MEM_LIMIT=192M.
|
||||
API_REPLICAS=2
|
||||
API_CPU_LIMIT=0.50
|
||||
API_MEM_LIMIT=256M
|
||||
|
||||
# Connections of ONE API replica to PostgreSQL; the total is replicas × value.
|
||||
# Track 1 checks whether the shared connection budget becomes the saturation
|
||||
# point: at 4 replicas the default 10 means 40 connections against one database.
|
||||
POSTGRES_MAX_CONNS=10
|
||||
|
||||
# CPU quota of the shared database. Track 1 shows it is the stand's saturation
|
||||
# point: the API uses a fraction of its budget while PostgreSQL sits at its own.
|
||||
POSTGRES_CPU_LIMIT=0.50
|
||||
|
||||
# Memory quota of the shared database. The track 1 series r/g/pool were measured
|
||||
# with 512M, the db1cpu control — with 384M (see evidence/track1/profile-*.json).
|
||||
POSTGRES_MEM_LIMIT=384M
|
||||
|
||||
# Loopback port of the HAProxy operator page (UP/DOWN of every replica).
|
||||
LB_STATS_PORT=8404
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
name: Application
|
||||
|
||||
on: [push, pull_request]
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
env:
|
||||
GO_VERSION: "1.27.0"
|
||||
GOLANGCI_LINT_VERSION: v2.13.2
|
||||
|
||||
jobs:
|
||||
lint:
|
||||
name: Lint
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: ${{ env.GO_VERSION }}
|
||||
cache: true
|
||||
- run: make lint
|
||||
|
||||
unit-test:
|
||||
name: Unit tests
|
||||
needs: lint
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: ${{ env.GO_VERSION }}
|
||||
cache: true
|
||||
- run: make unit-test
|
||||
|
||||
build:
|
||||
name: Docker build
|
||||
needs: unit-test
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: docker/setup-buildx-action@v3
|
||||
- uses: docker/build-push-action@v6
|
||||
with:
|
||||
context: .
|
||||
push: false
|
||||
tags: mtusi-messenger:ci
|
||||
|
||||
stand:
|
||||
name: Lab3 stand scenario
|
||||
needs: build
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 20
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- run: cp .env.example .env
|
||||
- run: docker compose --env-file .env config --quiet
|
||||
- run: docker compose --env-file .env up -d --build
|
||||
- name: Wait for readiness through the load balancer
|
||||
run: |
|
||||
for attempt in $(seq 1 60); do
|
||||
if curl -fsS -o /dev/null http://localhost:8080/health/ready; then exit 0; fi
|
||||
sleep 2
|
||||
done
|
||||
docker compose --env-file .env ps
|
||||
exit 1
|
||||
- name: Public smoke through the LB
|
||||
run: make test
|
||||
- name: Parallel idempotency through the LB
|
||||
run: python3 student-tests/idempotency_parallel.py --base-url http://localhost:8080
|
||||
- name: Stop one API replica and keep writing
|
||||
run: make test-failover ACTION_SCRIPT=scripts/stop-one.sh
|
||||
- name: Logs on failure
|
||||
if: failure()
|
||||
run: docker compose --env-file .env logs --tail 100
|
||||
- if: always()
|
||||
run: docker compose --env-file .env down -v
|
||||
@@ -24,6 +24,8 @@ target/
|
||||
bin/
|
||||
obj/
|
||||
coverage/
|
||||
coverage.out
|
||||
coverage.out.tmp
|
||||
*.log
|
||||
.DS_Store
|
||||
.idea/
|
||||
|
||||
+139
@@ -0,0 +1,139 @@
|
||||
# yaml-language-server: $schema=https://golangci-lint.run/jsonschema/golangci.v2.13.jsonschema.json
|
||||
|
||||
version: "2"
|
||||
|
||||
run:
|
||||
timeout: 5m
|
||||
tests: true
|
||||
build-tags:
|
||||
- integration
|
||||
|
||||
linters:
|
||||
default: standard
|
||||
enable:
|
||||
- bodyclose
|
||||
- contextcheck
|
||||
- containedctx
|
||||
- noctx
|
||||
- rowserrcheck
|
||||
- sqlclosecheck
|
||||
- fatcontext
|
||||
- errorlint
|
||||
- errname
|
||||
- nilerr
|
||||
- nilnil
|
||||
- asasalint
|
||||
- durationcheck
|
||||
- exhaustive
|
||||
- forcetypeassert
|
||||
- gocheckcompilerdirectives
|
||||
- gocritic
|
||||
- makezero
|
||||
- musttag
|
||||
- reassign
|
||||
- recvcheck
|
||||
- unparam
|
||||
- wastedassign
|
||||
- gosec
|
||||
- canonicalheader
|
||||
- copyloopvar
|
||||
- exptostd
|
||||
- intrange
|
||||
- perfsprint
|
||||
- unconvert
|
||||
- usestdlibvars
|
||||
- usetesting
|
||||
- prealloc
|
||||
- revive
|
||||
- misspell
|
||||
- nolintlint
|
||||
- gomoddirectives
|
||||
- sloglint
|
||||
- depguard
|
||||
- forbidigo
|
||||
- testifylint
|
||||
- thelper
|
||||
- tparallel
|
||||
|
||||
settings:
|
||||
govet:
|
||||
enable-all: true
|
||||
disable:
|
||||
- fieldalignment
|
||||
- shadow
|
||||
|
||||
gosec:
|
||||
excludes:
|
||||
- G404
|
||||
|
||||
exhaustive:
|
||||
default-signifies-exhaustive: true
|
||||
|
||||
nolintlint:
|
||||
require-explanation: true
|
||||
require-specific: true
|
||||
|
||||
sloglint:
|
||||
attr-only: true
|
||||
no-global: default
|
||||
context: scope
|
||||
|
||||
testifylint:
|
||||
enable-all: true
|
||||
|
||||
depguard:
|
||||
rules:
|
||||
main:
|
||||
deny:
|
||||
- pkg: math/rand$
|
||||
desc: use math/rand/v2
|
||||
- pkg: github.com/pkg/errors
|
||||
desc: use stdlib errors and fmt.Errorf with %w
|
||||
- pkg: io/ioutil
|
||||
desc: deprecated
|
||||
domain:
|
||||
files:
|
||||
- "**/internal/domain/**"
|
||||
deny:
|
||||
- pkg: database/sql
|
||||
desc: domain must not depend on infrastructure
|
||||
- pkg: net/http
|
||||
desc: domain must not depend on transport
|
||||
|
||||
forbidigo:
|
||||
forbid:
|
||||
- pattern: ^fmt\.Print(f|ln)?$
|
||||
msg: use slog
|
||||
- pattern: ^log\.(Print|Fatal|Panic).*$
|
||||
msg: use slog
|
||||
|
||||
exclusions:
|
||||
generated: lax
|
||||
presets:
|
||||
- comments
|
||||
- std-error-handling
|
||||
- common-false-positives
|
||||
rules:
|
||||
- path: _test\.go
|
||||
linters:
|
||||
- gosec
|
||||
- prealloc
|
||||
- forcetypeassert
|
||||
- unparam
|
||||
|
||||
formatters:
|
||||
enable:
|
||||
- gofumpt
|
||||
- goimports
|
||||
settings:
|
||||
gofumpt:
|
||||
module-path: mtusi-messenger
|
||||
goimports:
|
||||
local-prefixes:
|
||||
- mtusi-messenger
|
||||
exclusions:
|
||||
generated: lax
|
||||
|
||||
issues:
|
||||
max-issues-per-linter: 0
|
||||
max-same-issues: 0
|
||||
@@ -0,0 +1,35 @@
|
||||
#https://vektra.github.io/mockery/latest/configuration/
|
||||
|
||||
all: false
|
||||
dir: "{{.InterfaceDir}}/mocks"
|
||||
pkgname: mocks
|
||||
filename: "{{.InterfaceName}}.go"
|
||||
structname: "Mock{{.InterfaceName}}"
|
||||
template: testify
|
||||
formatter: goimports
|
||||
force-file-write: true
|
||||
include-auto-generated: false
|
||||
log-level: info
|
||||
|
||||
packages:
|
||||
mtusi-messenger/internal/platform/cache:
|
||||
config:
|
||||
all: true
|
||||
mtusi-messenger/internal/storage/redis:
|
||||
config:
|
||||
all: true
|
||||
mtusi-messenger/internal/service/user:
|
||||
config:
|
||||
all: true
|
||||
mtusi-messenger/internal/service/chat:
|
||||
config:
|
||||
all: true
|
||||
mtusi-messenger/internal/service/message:
|
||||
config:
|
||||
all: true
|
||||
mtusi-messenger/internal/service/session:
|
||||
config:
|
||||
all: true
|
||||
mtusi-messenger/internal/transport/rest:
|
||||
config:
|
||||
all: true
|
||||
@@ -0,0 +1,10 @@
|
||||
# yaml-language-server: $schema=https://raw.githubusercontent.com/ogen-go/ogen/v1.24.0/schemas/ogen.jsonschema.json
|
||||
|
||||
# https://ogen.dev/docs/config/
|
||||
generator:
|
||||
features:
|
||||
disable:
|
||||
- paths/client
|
||||
- webhooks/client
|
||||
- webhooks/server
|
||||
- ogen/otel
|
||||
+53
@@ -0,0 +1,53 @@
|
||||
# syntax=docker/dockerfile:1.7
|
||||
|
||||
ARG GO_VERSION=1.27.1
|
||||
ARG ALPINE_VERSION=3.22
|
||||
|
||||
FROM golang:${GO_VERSION}-alpine AS build
|
||||
# Platform of the produced binaries. Left empty on purpose: the classic builder
|
||||
# does not supply these args, and the previous hardcoded `amd64` default silently
|
||||
# produced x86-64 binaries inside an arm64 image. Those ran under emulation and
|
||||
# the Go runtime crashed under load (fatals like "found pointer to free object").
|
||||
# Empty means "build for the builder's own platform"; cross-compile explicitly:
|
||||
# docker build --build-arg TARGETARCH=amd64 ...
|
||||
ARG TARGETOS
|
||||
ARG TARGETARCH
|
||||
ARG VERSION=dev
|
||||
ENV GOTOOLCHAIN=local
|
||||
WORKDIR /opt
|
||||
|
||||
COPY go.mod go.sum ./
|
||||
RUN go mod download
|
||||
|
||||
# The Go compiler spikes well above 1 GiB per package on large dependencies, so
|
||||
# an unbounded parallel build OOMs small Docker VMs and CI runners. Cap
|
||||
# parallelism; override with --build-arg GOFLAGS=-p=$(nproc) on a bigger host.
|
||||
ARG GOFLAGS="-p=2"
|
||||
ENV GOFLAGS=$GOFLAGS
|
||||
|
||||
COPY . .
|
||||
RUN CGO_ENABLED=0 GOOS=${TARGETOS} GOARCH=${TARGETARCH} \
|
||||
go build -trimpath -buildvcs=false -tags timetzdata \
|
||||
-ldflags="-s -w -X main.version=${VERSION}" \
|
||||
-o /out/messenger ./cmd/messenger \
|
||||
&& CGO_ENABLED=0 GOOS=${TARGETOS} GOARCH=${TARGETARCH} \
|
||||
go build -trimpath -buildvcs=false -tags timetzdata \
|
||||
-ldflags="-s -w -X main.version=${VERSION}" \
|
||||
-o /out/migrate ./cmd/migrate
|
||||
|
||||
FROM alpine:${ALPINE_VERSION} AS runtime
|
||||
RUN apk add --no-cache ca-certificates wget \
|
||||
&& addgroup -S -g 10001 app \
|
||||
&& adduser -S -D -H -u 10001 -G app app
|
||||
|
||||
COPY --from=build --chown=10001:10001 /out/messenger /usr/local/bin/messenger
|
||||
COPY --from=build --chown=10001:10001 /out/migrate /usr/local/bin/migrate
|
||||
COPY --chown=10001:10001 config/dev/config.yaml /etc/messenger/dev/config.yaml
|
||||
|
||||
USER 10001:10001
|
||||
EXPOSE 8080
|
||||
STOPSIGNAL SIGTERM
|
||||
HEALTHCHECK --interval=10s --timeout=3s --start-period=5s --retries=3 \
|
||||
CMD wget -q -O /dev/null "http://127.0.0.1:${SERVER_PORT:-8080}/health/live" || exit 1
|
||||
|
||||
ENTRYPOINT ["/usr/local/bin/messenger"]
|
||||
@@ -3,11 +3,13 @@ BASE_URL ?= http://localhost:8080
|
||||
CA_FILE ?=
|
||||
ACTION_SCRIPT ?=
|
||||
TLS_ARGS = $(if $(CA_FILE),--ca-file "$(CA_FILE)",)
|
||||
PYTHON_LOCAL = env -u HTTP_PROXY -u HTTPS_PROXY -u ALL_PROXY -u http_proxy -u https_proxy -u all_proxy NO_PROXY=localhost,127.0.0.1,::1 no_proxy=localhost,127.0.0.1,::1 $(PYTHON)
|
||||
|
||||
.PHONY: help check validate test load test-persistence test-failover
|
||||
.PHONY: help check validate test load test-persistence test-failover smoke-local load-local test-idempotency test-lb-readiness up down ps logs
|
||||
|
||||
help:
|
||||
@echo "check: offline structure; validate: full OpenAPI (requirements-dev.txt); test: running API; load: synthetic writes"
|
||||
@echo "up/down/ps/logs: lab3 stand from compose.yaml (LB + API_REPLICAS replicas + stores)"
|
||||
|
||||
check:
|
||||
$(PYTHON) scripts/check_contract.py
|
||||
@@ -16,15 +18,130 @@ validate:
|
||||
$(PYTHON) scripts/validate_openapi.py
|
||||
|
||||
test:
|
||||
$(PYTHON) tests/smoke.py --base-url "$(BASE_URL)" $(TLS_ARGS)
|
||||
$(PYTHON_LOCAL) tests/smoke.py --base-url "$(BASE_URL)" $(TLS_ARGS)
|
||||
|
||||
load:
|
||||
$(PYTHON) tests/load.py --base-url "$(BASE_URL)" $(TLS_ARGS)
|
||||
$(PYTHON_LOCAL) tests/load.py --base-url "$(BASE_URL)" $(TLS_ARGS)
|
||||
|
||||
test-persistence:
|
||||
@test -n "$(ACTION_SCRIPT)" || (echo "Set ACTION_SCRIPT to your implemented executable restart hook"; exit 2)
|
||||
$(PYTHON) tests/resilience.py --mode persistence --action-script "$(ACTION_SCRIPT)" --base-url "$(BASE_URL)" $(TLS_ARGS)
|
||||
$(PYTHON_LOCAL) tests/resilience.py --mode persistence --action-script "$(ACTION_SCRIPT)" --base-url "$(BASE_URL)" $(TLS_ARGS)
|
||||
|
||||
test-failover:
|
||||
@test -n "$(ACTION_SCRIPT)" || (echo "Set ACTION_SCRIPT to your implemented executable stop-one hook"; exit 2)
|
||||
$(PYTHON) tests/resilience.py --mode failover --action-script "$(ACTION_SCRIPT)" --base-url "$(BASE_URL)" $(TLS_ARGS)
|
||||
$(PYTHON_LOCAL) tests/resilience.py --mode failover --action-script "$(ACTION_SCRIPT)" --base-url "$(BASE_URL)" $(TLS_ARGS)
|
||||
|
||||
# Локальный запуск без прокси: в окружении автора HTTP(S)_PROXY ломает localhost.
|
||||
smoke-local:
|
||||
$(PYTHON_LOCAL) tests/smoke.py --base-url "$(BASE_URL)" $(TLS_ARGS)
|
||||
|
||||
load-local:
|
||||
$(PYTHON_LOCAL) tests/load.py --base-url "$(BASE_URL)" $(TLS_ARGS)
|
||||
|
||||
# Собственная проверка уровня 4: параллельные повторы одного Idempotency-Key
|
||||
# через LB обязаны создать ровно одно сообщение.
|
||||
test-idempotency:
|
||||
$(PYTHON_LOCAL) student-tests/idempotency_parallel.py --base-url "$(BASE_URL)" $(TLS_ARGS)
|
||||
|
||||
# Собственная проверка уровня 4: LB обязан убрать из ротации реплику, которая
|
||||
# осталась доступной, но потеряла БД (readiness 503).
|
||||
test-lb-readiness:
|
||||
scripts/lb_readiness_check.sh
|
||||
|
||||
COMPOSE_BIN ?= docker compose
|
||||
COMPOSE_FILE ?= compose.yaml
|
||||
ENV_FILE ?= .env
|
||||
|
||||
up:
|
||||
$(COMPOSE_BIN) --env-file $(ENV_FILE) -f $(COMPOSE_FILE) up -d --build
|
||||
|
||||
down:
|
||||
$(COMPOSE_BIN) --env-file $(ENV_FILE) -f $(COMPOSE_FILE) down
|
||||
|
||||
ps:
|
||||
$(COMPOSE_BIN) --env-file $(ENV_FILE) -f $(COMPOSE_FILE) ps
|
||||
|
||||
logs:
|
||||
$(COMPOSE_BIN) --env-file $(ENV_FILE) -f $(COMPOSE_FILE) logs -f --tail 100
|
||||
|
||||
.DEFAULT_GOAL := help
|
||||
GO ?= go
|
||||
APP_NAME ?= messenger
|
||||
CMD_PKG := ./cmd/$(APP_NAME)
|
||||
LOCAL_BIN := $(CURDIR)/bin
|
||||
GOLANGCI_LINT_VERSION ?= v2.13.2
|
||||
GOLANGCI_LINT := $(LOCAL_BIN)/golangci-lint
|
||||
OPENAPI_SPEC := contracts/openapi.json
|
||||
OGEN_CONFIG := .ogen.yml
|
||||
OAS_DIR := internal/transport/rest/internal/oas
|
||||
|
||||
-include .env
|
||||
export
|
||||
|
||||
# .env feeds local tooling, but its application variables must not leak into the
|
||||
# Go test process: the config tests assert defaults and the dev YAML, so an
|
||||
# ambient REDIS_ENABLED/CACHE_ENABLED would fail them.
|
||||
ENV_KEYS := $(shell sed -n 's/^\([A-Za-z_][A-Za-z0-9_]*\)=.*/\1/p' .env 2>/dev/null)
|
||||
CLEAN_ENV = env $(addprefix -u ,$(ENV_KEYS))
|
||||
|
||||
.PHONY: unit-test
|
||||
unit-test:
|
||||
$(CLEAN_ENV) $(GO) test -race -shuffle=on -count=1 -timeout=5m ./...
|
||||
|
||||
.PHONY: integration-test
|
||||
integration-test:
|
||||
$(GO) test -tags=integration -p 1 -count=1 -timeout=15m ./internal/storage/postgres ./internal/storage/redis
|
||||
|
||||
.PHONY: test-db-up test-db-down
|
||||
test-db-up:
|
||||
@docker-compose -f docker-compose.local.yaml up -d --wait postgres redis
|
||||
|
||||
test-db-down:
|
||||
@docker-compose -f docker-compose.local.yaml down
|
||||
|
||||
# не учитываем генеренные файлы, также cmd в подсчете покрытия
|
||||
COVER_EXCLUDE ?= /(mocks|oas)/|/cmd/
|
||||
|
||||
.PHONY: cover
|
||||
cover:
|
||||
$(CLEAN_ENV) $(GO) test -race -shuffle=on -count=1 -timeout=5m \
|
||||
-covermode=atomic -coverprofile=coverage.out.tmp ./...
|
||||
@grep -Ev '$(COVER_EXCLUDE)' coverage.out.tmp > coverage.out
|
||||
@rm coverage.out.tmp
|
||||
$(GO) tool cover -func=coverage.out | tail -n 1
|
||||
$(GO) tool cover -html=coverage.out
|
||||
|
||||
.PHONY: generate
|
||||
generate: generate-api generate-mocks sqlc
|
||||
|
||||
.PHONY: generate-api
|
||||
generate-api:
|
||||
$(GO) tool ogen --config $(OGEN_CONFIG) --target $(OAS_DIR) --package oas --clean $(OPENAPI_SPEC)
|
||||
|
||||
.PHONY: generate-mocks
|
||||
generate-mocks:
|
||||
$(GO) tool mockery
|
||||
|
||||
.PHONY: sqlc
|
||||
sqlc:
|
||||
$(GO) tool sqlc generate
|
||||
|
||||
.PHONY: dev-up dev-down dev-reload
|
||||
dev-up:
|
||||
@docker-compose -f docker-compose.local.yaml up -d --build
|
||||
|
||||
dev-down:
|
||||
@docker-compose -f docker-compose.local.yaml down
|
||||
|
||||
dev-reload:
|
||||
@docker-compose -f docker-compose.local.yaml up -d --build --force-recreate
|
||||
|
||||
.PHONY: migrate
|
||||
migrate:
|
||||
$(GO) run ./cmd/migrate up
|
||||
|
||||
$(GOLANGCI_LINT):
|
||||
GOBIN=$(LOCAL_BIN) $(GO) install github.com/golangci/golangci-lint/v2/cmd/golangci-lint@$(GOLANGCI_LINT_VERSION)
|
||||
|
||||
lint: $(GOLANGCI_LINT)
|
||||
$(GOLANGCI_LINT) run -v
|
||||
|
||||
@@ -1,37 +1,238 @@
|
||||
# Отчёт — лабораторная 3
|
||||
|
||||
- Автор, группа: TODO
|
||||
- Целевая оценка; выбранный трек 5, если нужен: TODO
|
||||
- Commit/PR: TODO после публикации
|
||||
- Использованные источники, библиотеки и помощь ИИ: TODO
|
||||
- Автор, группа: Владислав Кунецкий, БВT2303
|
||||
- Целевая оценка; выбранный трек 5, если нужен: 5; трек 1 «Цена масштабирования»
|
||||
- Commit/PR: solution/bvt2303-kunetsky (fork репозитория лабораторной 3)
|
||||
- Использованные источники, библиотеки и помощь ИИ: ogen (HTTP-транспорт из `contracts/openapi.json`), sqlc (SQL-слой), goose (миграции), pgx/v5, go-redis/v9, viper + validator (конфигурация), mockery/v3 + testify (тесты), zap через `log/slog`. Помощь ИИ использовалась для обсуждения архитектуры, ревью и подготовки кода; решение проверено и изменено автором. База перенесена из лабораторной 2.
|
||||
|
||||
## Запуск из чистого clone
|
||||
|
||||
TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных.
|
||||
Требования: Docker Engine с Compose v2 (`docker compose`), `make`; Python 3.9+ (только стандартная библиотека) для проверок; Go 1.27 — для локальной сборки и unit/integration-тестов.
|
||||
|
||||
Проверено на: macOS 25.5.0, Apple M5 Pro, 48 GiB RAM, Docker Engine 29.5.2 (Colima, macOS Virtualization.framework), Docker Compose 5.5.1, Go 1.27.1. Docker VM: **2 vCPU и ≈1.9 GiB RAM** — лимиты контейнеров в `compose.yaml` подобраны под этот бюджет (API 0.5 CPU / 256 MiB на реплику, PostgreSQL 0.5 CPU / 384 MiB, Redis 0.25 / 192 MiB, LB 0.25 / 64 MiB), суммарно меньше доступного. Образы зафиксированы по версии: `haproxy:3.2-alpine`, `redis:7.4-alpine`, `postgres:18-alpine@sha256:77f585114c32fbca283dc835b0596f4e52b51b4c6662d7810b2f4084f60a1873`; приложение собирается из `Dockerfile` (`golang:1.27.1-alpine` → `alpine:3.22`), сборка ограничена `GOFLAGS=-p=2`, чтобы компилятор Go не выбил память небольшой VM.
|
||||
|
||||
```sh
|
||||
cp .env.example .env # синтетические креды локального стенда, реальных секретов нет
|
||||
make up # docker compose --env-file .env up -d --build
|
||||
make ps # контейнеры и health
|
||||
curl -fsS http://localhost:8080/health/ready
|
||||
|
||||
make test # публичный smoke (профиль lab3) через LB
|
||||
make test-idempotency # параллельные повторы одного Idempotency-Key
|
||||
make test-persistence ACTION_SCRIPT=scripts/restart.sh
|
||||
make test-failover ACTION_SCRIPT=scripts/stop-one.sh
|
||||
python3 student-tests/replica_failover.py --action-script scripts/stop-one.sh
|
||||
make test-lb-readiness # LB и реплика, потерявшая БД (readiness 503)
|
||||
scripts/rolling_update.sh # поочерёдная замена реплик под нагрузкой
|
||||
|
||||
make down # остановка стенда; named volumes остаются
|
||||
```
|
||||
|
||||
Намеренное удаление учебных данных (удаляет volumes и сессии):
|
||||
|
||||
```sh
|
||||
docker compose --env-file .env down -v
|
||||
```
|
||||
|
||||
Оператору достаточно `cp .env.example .env` и `make up`: миграции выполняет отдельный сервис `migrate` (`goose up`), он завершается успешно до старта API-реплик (`depends_on: service_completed_successfully`), поэтому реплики не гоняют схему наперегонки. Приложение принимает SIGTERM и дренирует сервер в пределах `SERVER_SHUTDOWN_TIMEOUT=10s`; у контейнера API `stop_grace_period: 15s`, чтобы Docker не убил запрос в полёте.
|
||||
|
||||
### Соответствие переменных `.env.example` реальной конфигурации
|
||||
|
||||
| Логическое имя из задания | Реальная переменная | Смысл |
|
||||
| --- | --- | --- |
|
||||
| `APP_HOST` / `APP_PORT` | `SERVER_HOST` / `SERVER_PORT` | адрес и порт HTTP-сервера API |
|
||||
| `APP_ENV` | `APP_ENV` | выбор `config/<env>/config.yaml`; реализован только `dev` |
|
||||
| `SESSION_STORE=postgres` | — | сессии лежат в PostgreSQL (`sessions.token_hash`), параметр не нужен |
|
||||
| `DATABASE_URL_FILE` | `POSTGRES_*` | параметры подключения к общей БД без файлов секретов |
|
||||
| `CACHE_URL_FILE` | `REDIS_*`, `CACHE_*` | общий кэш списка чатов и его блокировки |
|
||||
| `IDEMPOTENCY_TTL_SECONDS` | `IDEMPOTENCY_TTL_SECONDS` | срок хранения записи идемпотентности (по умолчанию 86400 с) |
|
||||
| `API_REPLICAS` | `API_REPLICAS` | число API-реплик стенда (`deploy.replicas`) |
|
||||
| — | `API_CPU_LIMIT` / `API_MEM_LIMIT` | лимиты CPU/RAM одной реплики (для профилей трека 1) |
|
||||
| — | `POSTGRES_CPU_LIMIT` / `POSTGRES_MEM_LIMIT` / `POSTGRES_MAX_CONNS` | бюджет общего PostgreSQL и пул соединений одной реплики (трек 1) |
|
||||
| — | `SERVER_MAX_BODY_BYTES` | предел размера тела запроса (413 при превышении) |
|
||||
| — | `LB_STATS_PORT` | loopback-порт страницы оператора HAProxy |
|
||||
|
||||
## Архитектура и решения
|
||||
|
||||
TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab2, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации.
|
||||
Схема: клиент → LB (HAProxy с активными проверками `/health/ready`) → 2+ API-реплики → общие PostgreSQL и Redis. Единая точка входа — только LB: `127.0.0.1:8080`; порты API и хранилищ наружу не публикуются.
|
||||
|
||||
| Роль | Сервис в compose | Образ / версия | Проверка готовности | Сеть и порт | Данные |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| Единая точка входа | `lb` | `haproxy:3.2-alpine` | активный `httpchk GET /health/ready`, период 2 с, `fall 2 rise 2` | публикует `127.0.0.1:8080`; страница оператора `127.0.0.1:8404` | — |
|
||||
| API-реплики | `api`, `deploy.replicas=${API_REPLICAS:-2}` | сборка из `Dockerfile` → `mtusi-messenger:lab3` | Docker healthcheck `/health/ready`, интервал 10 с | только внутренняя сеть, alias `api-replica` | — |
|
||||
| Миграции схемы | `migrate` | тот же образ, one-shot `goose up` | завершение с кодом 0 до старта реплик | только внутренняя сеть | — |
|
||||
| Источник истины | `postgres` | `postgres:18-alpine@sha256:77f5…1873` | `pg_isready`, 5 с | только внутренняя сеть | volume `postgres18-data` |
|
||||
| Кэш и блокировки | `redis` | `redis:7.4-alpine` (AOF everysec) | `redis-cli ping`, 5 с | только внутренняя сеть | volume `redis7-data` |
|
||||
| Credentials | — | — | — | `.env` (вне git, синтетические значения для локального стенда), в контейнеры передаются явными переменными | — |
|
||||
|
||||
- **Источник истины — PostgreSQL**: пользователи, чаты, участники, сообщения, серверные сессии (`sha256(token)`), записи идемпотентности. Транзакционные границы: создание чата вместе с участниками; отправка сообщения вместе с записью идемпотентности.
|
||||
- **Redis/Valkey** — кэш списка чатов с распределённой блокировкой от stampede и версиями (`user_chat_versions`); не хранит ничего, что нужно для корректности ответа.
|
||||
- **Общие сессии**: сессия создаётся одной репликой, любые другие её читают из БД, поэтому логин не привязан к реплике (sticky-сессии не используются).
|
||||
- **`X-Instance-Id`**: значение стабильно в пределах процесса (`INSTANCE_ID` или hostname = короткий ID контейнера) и проставляется middleware на **каждый** ответ, включая ошибки 400/404/405, которые формирует транспорт, а не handler.
|
||||
- **Идемпотентность отправки** (`Idempotency-Key` обязателен, `[A-Za-z0-9._:-]{1,128}`):
|
||||
- таблица `message_idempotency (actor_id, chat_id, key, request_hash, message_id, expires_at)`, PK `(actor_id, chat_id, key)` — область уникальности «пользователь + чат + ключ»;
|
||||
- claim — один `INSERT ... ON CONFLICT (actor_id, chat_id, key) DO UPDATE ... WHERE expires_at <= now() RETURNING`: живая запись не перезаписывается, истёкшая занимается заново;
|
||||
- вставка сообщения и запись `message_id` идут в **одной транзакции с claim**, поэтому не бывает ключа без сообщения и наоборот; при откате (например, отправитель не участник) ключ не занимается;
|
||||
- конкурентный повтор через разные реплики блокируется на строке и после коммита победителя возвращает его сообщение → ровно один INSERT в `messages`;
|
||||
- повтор с тем же ключом и другим payload — `409`, для этого хранится `request_hash` (sha256 канонического payload `{"text":...}`; порядок ключей и пробелы в JSON не влияют).
|
||||
- **LB**: HAProxy 3.2 (образ зафиксирован), `server-template api 4 api-replica:8080` + `resolvers docker` (Docker DNS 127.0.0.11, `hold valid 5s`) — адреса берутся из общего сетевого alias, выданного всем репликам, и переразрешаются каждые 5 с, поэтому масштабирование (1/2/4), замена контейнеров и смена IP не требуют правки конфига. Балансировка `leastconn`. Aктивные проверки готовности: `option httpchk GET /health/ready` + `http-check expect status 200`, `inter 2s fall 2 rise 2` — неготовая реплика исключается из ротации за ≤4 с и возвращается за ≤4 с. Это принципиально: пассивные проверки (nginx OSS, прежний вариант) не умели убирать реплику, которая остаётся доступной по сети, но теряет БД — она продолжала получать трафик и отвечать 503 (зафиксировано в ревью: 20 из 40 запросов `/health/live`). После перехода на активные проверки такая реплика получает **0 из 40** запросов, её статус `DOWN` (`evidence/lb-readiness.txt`), а запись через LB не прерывается (1 247 RPS, ноль ошибок в том же сценарии).
|
||||
- **Повторы и идемпотентность**: HAProxy настроен на `retry-on conn-failure` + `retries 2` — повтор происходит только когда соединение не установилось и запрос не ушёл. Уже отправленный POST не повторяется, поэтому прозрачного дублирования создания чата нет (прежний вариант с `proxy_next_upstream ... non_idempotent` этим страдал). Неопределённый результат повтора остаётся за клиентом, а отправка сообщения защищена обязательным `Idempotency-Key`.
|
||||
- **Страница оператора**: `127.0.0.1:8404/stats` (только loopback) показывает, какие реплики `UP`/`DOWN` и почему — именно по ней сняты доказательства выше.
|
||||
- **Предел размера тела**: `SERVER_MAX_BODY_BYTES` (по умолчанию 256 КиБ). Тело больше лимита отклоняется с `413` до чтения и декодирования, поэтому публичный `POST /api/v1/users` не может выбить память реплики (раньше JSON-декодер читал тело целиком до любой валидации и до аутентификации). Для вложений ЛР4 (до 10 MiB) значение поднимается явно — это объявленный переход.
|
||||
- **Логи**: заголовочные параметры (в том числе `Idempotency-Key`) попадают в лог как `redacted`, тела запросов — только своим размером; пароли, токены и содержимое сообщений не логируются.
|
||||
- **Миграции**: одна последовательность для всего стенда (`migrate`), совместимость с работающей версией — новая таблица добавляется отдельной миграцией, старый код её не читает. Новая миграция пронумерована `00003`, а не `00002`: в базе, перенесённой из ЛР2, goose уже содержит применённую версию 2 (другая миграция того же репозитория), и совпадающий номер был бы молча пропущен при обновлении существующего стенда — это проверено на dev-базе (`goose: no migrations to run. current version: 2` при отсутствующей таблице).
|
||||
|
||||
### Что перенесено из lab2
|
||||
|
||||
Перенос: ветки `lab1` + `lab2` репозитория `mtusi-messenger`, перенесены только исходники, миграции, собственные тесты, Dockerfile и конфигурации (по правилам CONTRIBUTING.md; README/COURSE/contracts/публичные tests остались от skeleton ЛР3).
|
||||
|
||||
- Транспорт: HTTP-слой, сгенерированный ogen из `contracts/openapi.json`, REST-адаптер поверх него, middleware X-Request-Id и структурного логирования.
|
||||
- Домен и сервисы: user / chat / message / session с валидацией и keyset-пагинацией.
|
||||
- PostgreSQL — источник истины: pgx + sqlc, миграции goose, транзакции на создание чата.
|
||||
- Сессии: Basic только при создании сессии, далее Bearer; в БД `sha256(token)`, TTL, переживают перезапуск процесса.
|
||||
- Redis/Valkey: кэш списка чатов с распределённой блокировкой от stampede (`user_chat_versions`).
|
||||
- Наблюдаемость: `/health/live`, `/health/ready`, структурированные логи (log/slog + zap).
|
||||
- Инструменты: multi-stage `Dockerfile`, `docker-compose.local.yaml` для локального запуска, Makefile-таргеты, `.github/workflows/app.yml`.
|
||||
|
||||
### Изменения в этой работе (лаб. 3)
|
||||
|
||||
- Контракт 1.3.0: транспорт перегенерирован, `X-Instance-Id` во всех ответах, обязательный `Idempotency-Key` для отправки сообщения.
|
||||
- Общая идемпотентность в PostgreSQL (миграция `00003_message_idempotency.sql`, sqlc-запросы, транзакция в `MessageRepository.Create`), 409 на конфликт payload.
|
||||
- `IDEMPOTENCY_TTL_SECONDS` в конфиге (по умолчанию 24 ч), `.env.example` приведён к реальным переменным.
|
||||
- Стенд ЛР3: `compose.yaml` (LB + `API_REPLICAS` реплик + PostgreSQL + Redis + одноразовый `migrate`), конфигурация LB `infra/lb/haproxy.cfg` (активные проверки готовности, ограниченные повторы, страница оператора), action-скрипты `scripts/stop-one.sh` и `scripts/restart.sh`, Makefile-таргеты `up/down/ps/logs`.
|
||||
- Собственные проверки: `make test-idempotency` (параллельные повторы через LB), `student-tests/replica_failover.py` (поочерёдная остановка каждой реплики с метриками), `scripts/lb_readiness_check.sh` (неготовая реплика и LB), `scripts/rolling_update.sh`, эксперименты трека 1.
|
||||
- Исправления по итогам аудита: отправка в несуществующий чат больше не даёт `500` из-за нарушения внешнего ключа от claim'а ключа идемпотентности (`23503` → `404`); добавлен предел размера тела (`413`, см. выше); заголовочные параметры не пишутся в лог; у проверок LB задан `timeout check 1s`, чтобы «залипшая» реплика исключалась за ограниченное время; у собственного сценария rolling update появился настоящий «наплыв» (новая реплика поднимается до снятия старой) и корректный счётчик 5xx (в HAProxy статус в логе печатается без кавычки, прежний шаблон молча давал нули).
|
||||
- `Dockerfile`: убран жёстко заданный `TARGETARCH=amd64` — на Apple Silicon он давал x86-64 бинарник внутри arm64-образа, тот исполнялся через эмуляцию и падал по runtime-фаталам под нагрузкой (см. «Ограничения»); сборка ограничена `GOFLAGS=-p=2`, чтобы компилятор не выбил память небольшой Colima VM.
|
||||
- Удалён осиротевший `scripts/track1_benchmark.py` (бенчмарк in-memory хранилища ЛР1: сам in-memory store удалён ещё в ЛР2, скрипт ссылался на несуществующий файл).
|
||||
|
||||
## Доказательства критериев
|
||||
|
||||
Артефакты ЛР1/ЛР2 перенесены в `evidence/lab1-2/` (там же пояснение, почему они не относятся к этой работе); в `evidence/` — только доказательства ЛР3.
|
||||
|
||||
| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства |
|
||||
| --- | --- | --- | --- |
|
||||
| Публичный smoke | make test | TODO | TODO |
|
||||
| Остальные пункты уровня 3 | TODO | TODO | TODO |
|
||||
| Все пункты уровня 4, если заявлен | TODO | TODO | TODO |
|
||||
| Выбранный трек 5, если заявлен | TODO | TODO | TODO |
|
||||
| Публичный smoke | `make test` | `PASS: lab3 public API scenario` через LB с двумя репликами | `evidence/smoke.txt` |
|
||||
| Разные запросы одного пользователя обслуживают разные реплики | 40× `GET /users/me` через LB одной сессией (и 40× `/health/live`) | два разных `X-Instance-Id`, распределение видно по репликам | `evidence/failover/sequential.txt` (одна сессия), `evidence/lb-readiness.txt` (счётчики по репликам) |
|
||||
| Идемпотентность: повтор, конкурентный повтор, смена реплики | `make test-idempotency` | 12 параллельных повторов одного ключа → одно сообщение; 12 разных payload → один 201 и одиннадцать 409; без ключа и с недопустимым ключом → 400 | `evidence/idempotency.txt` |
|
||||
| Остановка одной реплики при работающей другой | `make test-failover ACTION_SCRIPT=scripts/stop-one.sh` (два прогона) | 127 и 100 подтверждённых записей, 0 ошибок, первое восстановление 0.21 с и 2.24 с | `evidence/failover/run1.txt`, `evidence/failover/run2.txt` |
|
||||
| Последовательно остановлена каждая реплика, с измерениями (RPS, ошибки, время) | `python3 student-tests/replica_failover.py --action-script scripts/stop-one.sh` | реплика A: 91 запись (6.06 RPS), 0 ошибок, восстановление 1.66 с; реплика B: 100 записей (6.66 RPS), 0 ошибок, 1.66 с; после отказа обслуживает только вторая реплика; восстановление обеих 0.18–0.20 с; дублей нет (191 сообщение) | `evidence/failover/sequential.txt` |
|
||||
| LB исключает неготовую реплику | `scripts/lb_readiness_check.sh` | реплика с потерянной БД (осталась доступной, readiness 503): **0 из 40** запросов, статус `DOWN` **через 2 с** (проверка `inter 2s fall 2 timeout check 1s`), при этом запись через LB не прервалась (1 163 RPS, 0 ошибок) | `evidence/lb-readiness.txt` |
|
||||
| Предел размера тела | `python3`-проверка публичного `POST /api/v1/users` | тело 400 КиБ (сверх лимита 256 КиБ) → `413`, тело 100 КиБ → `400` (схема); реплика не выбита | `evidence/body-limit.txt` |
|
||||
| Отказ БД не превращается в 500 | `python3`-проверка: `POST` сообщения напрямую в реплику (в обход LB) при остановленном PostgreSQL | напрямую к реплике — `503`, через LB — `503` с `X-Instance-Id` (ответ приложения), после возврата БД — `201` | `evidence/db-outage.txt` |
|
||||
| Сохранность при перезапуске API и хранилищ | `make test-persistence ACTION_SCRIPT=scripts/restart.sh` | `PASS`: подтверждённые сообщения и прежний токен после перезапуска, volumes не удалялись | `evidence/persistence.txt` |
|
||||
| Лимиты CPU/RAM, отсутствие публичных портов API, отсутствие `container_name` | `docker compose --env-file .env config`, `docker ps` | лимиты у каждого сервиса, публикуется только `127.0.0.1:8080` (LB) | `evidence/stand.txt` |
|
||||
| Поочерёдная замена реплик под нагрузкой | `scripts/rolling_update.sh` (60 с, 8 клиентов; наплыв по одной реплике) | 97 359 подтверждённых записей, 3 переходные ошибки (0.003 %), **3 ответа 5xx от LB** за окно обновления, `restarts=0`; каждый шаг подтверждён сменой образа новых реплик и числом UP-слотов | `evidence/rolling-update/after/` |
|
||||
| Контроль: тот же код вне Docker | `student-tests/rolling_update_load.py` против нативного процесса (90 с, 32 клиента) | 220 781 запрос, 0 ошибок, 2 452 RPS, p50 12.5 мс, p95 17.5 мс, p99 22.4 мс | `evidence/native-load.txt` |
|
||||
| Проверки качества | `make check`, `make validate`, `make unit-test` (`-race`), `make integration-test` | все PASS, включая интеграционный тест «отправка в несуществующий чат → 404» | `evidence/quality.txt` |
|
||||
| Трек 1: цена масштабирования | `scripts/track1_series.sh` + `scripts/track1_controls.sh` + `scripts/track1_report.py` | потолок ≈1 300–1 550 RPS: 1/2/4 реплики → −3 %/−5 %; бюджет API ×3, бюджет БД ×2 и бюджет LB ×4 не меняют RPS (перемежающий контроль: ±0.05 %), пул соединений не исчерпан; дрейф серии измерен | `evidence/track1/summary.md`, `evidence/track1/scaling-*.png` |
|
||||
|
||||
TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены.
|
||||
`make check`, `make validate` (полная OpenAPI-валидация в venv) и `make unit-test` (`-race`) проходят; интеграционные тесты PostgreSQL (`-tags=integration`, включая конкурентный повтор одного ключа) — тоже.
|
||||
|
||||
## Эксперименты и отказы
|
||||
|
||||
TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения.
|
||||
|
||||
| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных |
|
||||
| --- | --- | --- | --- |
|
||||
| TODO | TODO | TODO | TODO |
|
||||
| `docker stop` одной API-реплики (прогон 1) | записи продолжаются, остановленная реплика исчезает из ответов | 127 успешных записей, 0 ошибок | 0.21 с |
|
||||
| `docker stop` другой API-реплики (прогон 2) | то же | 100 записей, 0 ошибок | 2.24 с |
|
||||
| Поочерёдно остановлены обе реплики (свой скрипт) | после каждой остановки пишет только вторая реплика, дублей нет | 91 и 100 записей (6.06 и 6.66 RPS), 0 ошибок, повторы с тем же ключом дубля не создали | 1.66 с и 1.66 с |
|
||||
| Одной реплике закрыт доступ к БД (она остаётся доступной, readiness 503) | LB исключает её из ротации | 0 из 40 запросов ей, статус `DOWN` через 2 с, запись через LB не прервалась | — |
|
||||
| Поочерёдная замена каждой реплики под нагрузкой (наплыв) | потери только на время остановки, дублей нет | 97 359 записей, 3 переходные ошибки, 3 ответа 5xx от LB, `restarts=0`, смена образа подтверждена по шагам | окно замены 5–6 с на реплику |
|
||||
| Перезапуск API и всех хранилищ с сохранением volumes | сессия и данные живут | `PASS`, прежний токен работает | потери нет |
|
||||
| Эмуляция x86-64 бинарника в arm64-образе (`--build-arg TARGETARCH=amd64`) | реплики замедляются и падают | в контроле (45 с, 8 клиентов) падений **не воспроизведено**: 89 560 запросов, 0 ошибок, 0 ответов 5xx; crash-loop наблюдались в других условиях | эффект не измерен (`evidence/rolling-update/emulated/`) |
|
||||
| Удвоенный CPU БД, четырёхкратный CPU LB, пул 5 вместо 10, 32 клиента | пропускная способность вырастет, если узкое место — БД, LB или пул | бюджеты БД и LB не меняют RPS (перемежающий контроль: +0.04 % и −0.02 % при лимитах, проверенных по `docker inspect`); меньший пул хуже (−7 %); 32 клиента снижают RPS до 1 284 и растят p95 до 52.8 мс | `evidence/track1/summary.md`, `evidence/load-32clients.txt` |
|
||||
|
||||
## Трек 1. Цена масштабирования
|
||||
|
||||
Методика: один и тот же профиль `tests/load.py` (closed loop, `concurrency=8`, `duration=60` с, прогрев 15 с) против стенда на 1, 2 и 4 API-репликах при **фиксированном суммарном бюджете** 1.0 CPU / 768 MiB на API; затем серия с ростом бюджета — 2 реплики и суммарно 0.5, 1.0 и 1.5 CPU. Бюджеты общих хранилищ между профилями не меняются: PostgreSQL 0.50 CPU / 384 MiB, Redis 0.25 / 192, LB 0.25 / 64. В контрольных профилях меняется ровно одна ручка: пул соединений реплики 10 → 5, бюджет CPU PostgreSQL 0.50 → 1.00, бюджет CPU балансировщика 0.25 → 1.00.
|
||||
|
||||
Бюджеты хранилищ compose применяет при **создании** контейнера, поэтому скрипт пересоздаёт PostgreSQL и LB, когда бюджет профиля отличается от действующего, и проверяет применение по `docker inspect`: в `profile-*.json` и в строке `=== applied … ===` сводки попадают значения, снятые с работающих контейнеров, а не переменные запуска. Без этой проверки профиль описывал бы намерение, а измерение шло бы на прежнем лимите — на этом и провалился первый контроль удвоения CPU БД; тот прогон вместе с прогоном, где нагрузку подавал клиент хоста, лежит в `evidence/track1/superseded/`. Генератор работает **внутри VM** (`CLIENT=vm`, контейнер в сети стенда): клиент на хосте через проброс порта под шквалом новых соединений получает отказы самого проброса, не относящиеся к стенду (разбор — `evidence/path-overhead/`). Вся серия снимается одной командой `scripts/track1_series.sh` (~15 минут); профили с уже снятыми артефактами при повторном запуске пропускаются.
|
||||
|
||||
Бюджеты выбраны под Colima VM (2 vCPU, ≈1.9 GiB), чтобы измерения шли в её пределах, а не за счёт хоста. Ресурсы реплик считаются суммированием по одному timestamp: в первой версии сводки несколько реплик усреднялись как одна выборка, что занижало CPU и память вдвое — исправлено, сырые CSV не менялись. Сводка учитывает только контейнеры своего проекта (`--prefix`): параллельно поднятый стенд другой лаборатории иначе попадал в те же колонки (`…-lab2-postgres-1` → `postgres`). Сырые артефакты — `evidence/track1/` (`load-*.json`, `stats-*.csv`, `profile-*.json`), сводка — `evidence/track1/summary.md`, графики — `scaling-fixed-budget.png` и `scaling-growth.png`.
|
||||
|
||||
### Профили и результаты
|
||||
|
||||
Серия 1 — фиксированный суммарный бюджет 1.0 CPU / 768 MiB на API (PostgreSQL 0.50 CPU / 384 MiB, Redis 0.25, LB 0.25), нагрузка `tests/load.py` (closed loop, 8 клиентов, 60 с, прогрев 15 с, клиент внутри VM):
|
||||
|
||||
| реплик | CPU на реплику | успешный RPS | p50, мс | p95, мс | p99, мс | ошибки | API CPU (сумма) | PG CPU | LB CPU | строк в `messages` |
|
||||
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
|
||||
| 1 | 1.00 | 1 542.9 | 5.05 | 8.01 | 10.24 | 0 | 0.24 | 0.39 | 0.10 | 3.60 млн |
|
||||
| 2 | 0.50 | 1 491.3 | 5.25 | 8.23 | 10.30 | 0 | 0.28 | 0.36 | 0.10 | 3.71 млн |
|
||||
| 4 | 0.25 | 1 415.7 | 5.54 | 8.61 | 10.75 | 0 | 0.31 | 0.35 | 0.10 | 3.82 млн |
|
||||
|
||||
Серия 2 — рост бюджета API при 2 репликах:
|
||||
|
||||
| суммарный CPU API | CPU на реплику | успешный RPS | p95, мс | ошибки | API CPU (сумма) | PG CPU |
|
||||
| --- | --- | --- | --- | --- | --- | --- |
|
||||
| 0.5 | 0.25 | 1 489.9 | 8.25 | 0 | 0.28 | 0.36 |
|
||||
| 1.0 | 0.50 | 1 496.3 | 8.22 | 0 | 0.27 | 0.37 |
|
||||
| 1.5 | 0.75 | 1 491.3 | 8.18 | 0 | 0.27 | 0.36 |
|
||||
|
||||
Трехкратный бюджет API не сдвигает пропускную способность (1 490 → 1 496 → 1 491), а лишние реплики при неизменном суммарном бюджете её снижают: каждая реплика — ещё один процесс, соединения и копия кэша, а суммарный CPU фиксирован.
|
||||
|
||||
Отказов в чистой серии почти нет: 13 профилей из 15 без единого отказа, в двух профилях `pool` — по 4 обрыва в момент пересоздания реплики. Прежние прогоны показывали до 26 % отказов, но это были отказы соединений **у клиента на хосте**, а не у стенда: в контроле `evidence/path-overhead/` балансировщик отдал все запросы без 5xx, логи API не содержат ошибок, а клиент внутри VM не отказал ни разу. Подтверждённых записей не потеряно: повтор с тем же ключом дубля не создаёт (см. проверку идемпотентности).
|
||||
|
||||
Контроль снят попарно с эталоном, чтобы дрейф серии не выдавался за эффект бюджета (`scripts/track1_controls.sh`; лимиты применены к контейнерам и проверены по `docker inspect`):
|
||||
|
||||
| профиль | что изменено | успешный RPS | отличие от соседнего эталона |
|
||||
| --- | --- | --- | --- |
|
||||
| `ctl1base` / `ctl3base` | эталон (2 реплики, PostgreSQL 0.50, LB 0.25) | 1 391.1 / 1 360.1 | −2.2 % за два профиля — масштаб дрейфа |
|
||||
| `ctl2pg` | бюджет CPU PostgreSQL 0.50 → 1.00 | 1 391.6 | **+0.04 %** |
|
||||
| `ctl4lb` | бюджет CPU балансировщика 0.25 → 1.00 | 1 359.8 | **−0.02 %** |
|
||||
| `pool10` / `pool5` | пул соединений реплики 10 → 5 (4 реплики) | 1 399.0 / 1 299.6 | −7 % (меньший пул хуже) |
|
||||
| 32 клиента вместо 8 | — | 1 284 | p95 52.8 мс вместо ≈8-9 мс (`evidence/load-32clients.txt`) |
|
||||
|
||||
Профили серии `db1cpu` (PostgreSQL 1.00) и `lb1cpu` (LB 1.00) показывают на 15 % и 8 % меньше, чем `r2`, но сняты позже, и разница объясняется дрейфом: тот же профиль `r2`, повторённый в конце серии (`d2`), даёт 1 389 RPS вместо 1 491 (−6.9 %). Поэтому вопрос «помогает ли бюджет БД» решают именно перемежающие профили, а не сравнение через полчаса.
|
||||
|
||||
Стенд дрейфует по ходу серии: таблица `messages` растёт (≈95 тыс. строк на профиль, 3.6 → 5.1 млн за серию), и эталон `r2`, снятый в начале и в конце, даёт 1 491 и 1 389 RPS (−6.9 %, ≈0.9 % на профиль); независимая оценка дрейфа по двум эталонам перемежающего контроля — 2.2 % за два профиля. Повторы одной конфигурации внутри сессии расходятся до ~2 %. Поэтому профили сравнимы только внутри одной серии и рядом по времени, а влияние каждой ручки проверяется попарно с эталоном. Качественный вывод устойчив: **три независимые серии** дали одно и то же — рост числа реплик при фиксированном бюджете не помогает (первая: +3 % на двух, −9 % на четырёх; вторая: −7 % и −8 %; третья, чистая: −3.3 % и −5.1 %).
|
||||
|
||||
### Где насыщение
|
||||
|
||||
Потолок закрытого цикла на этой машине — **≈1 300–1 550 RPS подтверждённых записей**, и ни одна ручка стенда его не двигает:
|
||||
|
||||
| что меняли | как проверено | результат |
|
||||
| --- | --- | --- |
|
||||
| число API-реплик 1 → 2 → 4 при неизменном суммарном бюджете | серия 1 | −3.3 % и −5.1 % |
|
||||
| суммарный бюджет API 0.5 → 1.0 → 1.5 CPU | серия 2 | +0.1 % (плоско) |
|
||||
| бюджет CPU PostgreSQL 0.50 → 1.00 | перемежающий контроль | +0.04 % |
|
||||
| бюджет CPU балансировщика 0.25 → 1.00 | перемежающий контроль | −0.02 % |
|
||||
| пул соединений реплики 10 → 5 | пара профилей при 4 репликах | −7 % (хуже) |
|
||||
| клиент на хосте вместо клиента внутри VM | `evidence/path-overhead/` | тот же RPS (1 539 против 1 475) |
|
||||
| 32 клиента вместо 8 | `evidence/load-32clients.txt` | 1 284 RPS, p95 растёт до 52.8 мс |
|
||||
|
||||
Измерениями исключены: **клиент** (тот же закрытый цикл по тривиальному серверу на хосте даёт 4 469 RPS без отказов), **путь «хост → проброс порта → VM»** (клиент внутри VM даёт ту же пропускную способность), **квоты CPU PostgreSQL и LB** (перемежающий контроль: ±0.05 % при лимитах, проверенных по `docker inspect`), **размер пула** (19–22 соединения из 100; меньший пул только вредит). Сами сервисы при этом недогружены: реплики вместе берут 0.24–0.31 ядра из бюджета 1.0, PostgreSQL — 0.35–0.39 из 0.50, LB — 0.10 из 0.25 (в `docker stats` 100 % = одно ядро, проверено отдельным экспериментом: `evidence/quota-semantics.txt`).
|
||||
|
||||
Значит упор не в бюджет и не в число процессов, а в стоимость одной записи: сообщение — это транзакция из трёх обращений к БД (claim ключа идемпотентности, вставка сообщения, запись `message_id`), плюс проверка участников чата и работа с кэшем списка чатов, и всё это на 2 vCPU. Гипотеза следующего шага: сократить путь записи до двух обращений (вставка сообщения и upsert ключа в одной транзакции, конфликт — откат и повторное чтение) и перемерить перемежающим контролем. Числа сняты на одной конфигурации одиночными прогонами закрытого цикла, поэтому это не «предельная ёмкость системы»: на другом Docker-host потолок будет иным (см. «Ограничения»).
|
||||
|
||||
### Подтверждённое улучшение и проверенные гипотезы
|
||||
|
||||
**Подтверждено (измерено до/после):** балансировщик перестал отправлять трафик неготовой реплике. `scripts/lb_readiness_check.sh` поднимает рядом с рабочими репликами третью с тем же сетевым alias, но её доступ к БД идёт через временный TCP-прокси; после остановки прокси реплика остаётся доступной по сети, её `/health/ready` отвечает 503.
|
||||
|
||||
| Вариант LB | запросов неготовой реплике из 40 | статус в LB | запись через LB |
|
||||
| --- | --- | --- | --- |
|
||||
| пассивные проверки (nginx OSS, до правки) | 20 из 40 `/health/live` и бизнес-запросы (зафиксировано в ревью) | продолжает обслуживать | 503 и 200 вперемешку |
|
||||
| активные проверки (HAProxy, `httpchk /health/ready`, `inter 2s fall 2 rise 2`, `timeout check 1s`) | **0 из 40** | `DOWN` **через 2 с** (измерено) | 1 163 RPS, 0 ошибок (`evidence/lb-readiness.txt`) |
|
||||
|
||||
Вместе с этим убраны две связанные проблемы: прозрачный повтор POST (`proxy_next_upstream ... non_idempotent` мог повторить создание чата) заменён на `retry-on conn-failure`, а недоступная реплика убирается из ротации полностью, а не «на 3 секунды». Сценарий rolling update проходит под нагрузкой: 97 359 подтверждённых записей, 3 переходные ошибки (0.003 %), `restarts=0` (`evidence/rolling-update/after/`, где каждый шаг подтверждён сменой образа новой реплики и числом UP-слотов).
|
||||
|
||||
**Дефект доказан, эффект его устранения — нет.** Архитектурная ошибка унаследованного `Dockerfile` (`ARG TARGETARCH=amd64`, а классический builder платформу не подставляет → x86-64 бинарник в arm64-образе) подтверждена ELF-заголовками (`evidence/arch.txt`): `e_machine=0x3e` против `0xb7`. Но контролируемое сравнение **не подтвердило**, что именно она вызывала прежние runtime-фаталы: прогон rolling update на эмулируемом образе завершился без ошибок — 89 560 успешных запросов за 45 с, 0 ошибок, 0 ответов 5xx (`evidence/rolling-update/emulated/load.json`). Падения (`fatal error: found pointer to free object`, `sync: inconsistent mutex state`, crash-loop реплик) наблюдались в других условиях и в приложенный A/B не попали. Корректная формулировка: эмуляция x86-64 на arm64 — доказанный дефект сборки, который устранён, но его вклад в те падения не измерен.
|
||||
|
||||
**Проверено измерениями (перемежающий контроль, лимиты подтверждены по `docker inspect`):** ни бюджет CPU PostgreSQL (0.50 → 1.00), ни бюджет CPU балансировщика (0.25 → 1.00) не меняют пропускную способность (+0.04 % и −0.02 %), поэтому потолок закрытого цикла на этой машине задаёт не нехватка ресурсов у БД или LB. Пул соединений 10 → 5 при четырёх репликах оказался хуже на 7 % — меньший пул не улучшение, а потеря.
|
||||
|
||||
**Следующий шаг для измерения:** сократить число обращений к БД на одно сообщение — сейчас их три (claim ключа, вставка сообщения, запись `message_id`), нужно два (вставка сообщения + upsert ключа в той же транзакции, конфликт — через откат и повторное чтение). Гипотеза: меньше round-trip и меньше версий строк. Эффект измеряется тем же способом, что и бюджеты, — перемежающим контролем (`scripts/track1_controls.sh`: эталон → изменение → эталон), потому что собственный дрейф серии сопоставим с ожидаемым выигрышем.
|
||||
|
||||
## Ограничения и следующие шаги
|
||||
|
||||
TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза.
|
||||
- **Архитектура образа (главная находка этапа отладки).** Унаследованный `Dockerfile` содержал `ARG TARGETARCH=amd64`, а классический builder платформу не подставляет — в arm64-образ попадал x86-64 бинарник (`e_machine=0x3e` против `0xb7` у busybox базового образа; в стеке паники видно `runtime/asm_amd64.s`). Пока нагрузка была низкой, эмуляция справлялась; под нагрузкой Go runtime падал с `fatal error: found pointer to free object`, `sync: inconsistent mutex state`, `bad pointer in Go heap`, `runtime: name offset base pointer out of range` — и это выглядело как проблема приложения. Контрольный эксперимент снял подозрения с кода: тот же исходник, собранный нативно (вне Docker, против локальной БД), выдержал 90 с при 32 клиентах — 220 781 запрос, 0 ошибок, p50 12.5 мс, p95 17.5 мс, p99 22.4 мс, 2 452 успешных RPS (`evidence/native-load.txt`), тогда как контейнерный стенд через LB даёт ≈1 300–1 700 RPS. После исправления (`ARG TARGETARCH` без значения по умолчанию, кросс-сборка — явным `--build-arg`) стенд стабилен, однако строгий A/B связь с прежними падениями не подтвердил (см. «Подтверждённое улучшение»). Если вы собираете под другую платформу, задавайте `TARGETOS`/`TARGETARCH` явно.
|
||||
- **Ресурсы VM.** Colima (macOS Virtualization.framework) даёт 2 vCPU и ≈1.9 GiB RAM: сборка образа была один раз убита OOM, поэтому компилятор ограничен `GOFLAGS=-p=2`, а бюджеты экспериментов трека 1 подобраны под VM (1.0 CPU суммарно на API), иначе измеряется не масштабирование, а нехватка ресурсов.
|
||||
- **Измерения трека 1 не переносятся на другую машину.** Все числа получены на одной конфигурации (Docker VM: 2 vCPU, ≈1.9 GiB; хост: 18 ядер) одиночными прогонами закрытого цикла, поэтому это не «пропускная способность системы», а точки одного профиля на конкретном стенде: на другом Docker-host и потолок, и точка насыщения будут иными, а сравнивать между собой можно только профили одной серии.
|
||||
- **Что означает CPU% в `docker stats`.** Проверено экспериментом: контейнер, упёртый в `--cpus 0.5` (`cpu.max = 50000 100000`), показывает 49.49 %, то есть процент считается от одного ядра и 50 % = полная квота 0.5 CPU (`evidence/quota-semantics.txt`). Прежняя оговорка отчёта о «заниженных» значениях снята: колонки читаются однозначно.
|
||||
- **Проброс порта хоста не выдерживает нагрузку генератора.** `tests/load.py` ходит без keep-alive (новое TCP-соединение на запрос). Клиент на хосте получает отказы соединения от проброса порта: в контроле `evidence/path-overhead/` тот же профиль дал 26 % отказов при клиенте на хосте и 0 % при клиенте внутри VM и тот же RPS. Точечный пробник из 40 000 быстрых подключений подряд получил 38 706 `ECONNREFUSED`, а прогон на ~4 500 соединений/с оставил проброс порта (вместе с доступом к Docker-эндпоинту Colima) неработоспособным до `colima restart`. Стенд при этом не падал: в прогонах с клиентскими отказами балансировщик отдал все запросы без 5xx, а логи API не содержат ни одной ошибки (сценарии отказа, персистентности и rolling update снимались клиентом на хосте раньше и прошли с 0-3 отказами — там темп новых соединений был ниже, чем в серии трека 1). Поэтому серия трека 1 снимается клиентом внутри VM.
|
||||
- **«Потолок задаёт проброс порта» — опровергнуто измерением.** Прежняя формулировка объясняла потолок ≈1 500 RPS виртуализацией и пробросом порта. Контроль с клиентом внутри VM даёт ту же пропускную способность (1 475 против 1 539 RPS, различия в пределах разброса) вообще без проброса, значит этот путь потолок не задаёт; клиент тоже не потолок — тот же закрытый цикл по тривиальному локальному серверу даёт 4 469 RPS. Нативная оценка 2 452 RPS снята другим генератором, на хосте с 18 ядрами и против локальной БД, поэтому она не изолирует причину: отличается и доступный CPU, и способ подачи нагрузки. Корректная формулировка: узкое место — внутри стенда (путь записи сообщения), а не в виртуализации.
|
||||
- **Окно обнаружения отказа.** Готовность проверяется активно (`httpchk /health/ready`, период 2 с, `fall 2`, `timeout check 1s`) — измеренное время перехода реплики в `DOWN` после потери БД: **2 с** (`evidence/lb-readiness.txt`); теоретическая верхняя граница ~4 с. Между фактическим отказом и первой неудачной проверкой реплика ещё получает трафик, поэтому клиент может увидеть 503 от неё или ошибку соединения — в измеренных сценариях это единичные переходные ошибки (0–2 %), они учтены в таблицах отказа.
|
||||
- **Строгая проверка «до/после» по архитектуре не удалась.** Исходный дефект сборки доказан (ELF-заголовки), но воспроизвести падения в контролируемом A/B не удалось: эмулируемый образ в коротком прогоне тоже прошёл без ошибок. Считать эффект устранения измеренным нельзя.
|
||||
- **Переходные ошибки при смене состава реплик.** HAProxy не повторяет уже отправленный POST (осознанно: прозрачный повтор неидемпотентной операции запрещён контрактом), а переиспользуемые соединения к снятому контейнеру рвутся — поэтому в момент замены или масштабирования клиент может увидеть единичный 502: ≤0.25 % в сериях трека 1 и 0.003 % в rolling update. Неопределённый результат клиент повторяет сам, и для сообщений это безопасно благодаря `Idempotency-Key`.
|
||||
- Один Docker-host: эксперименты показывают отказ **процесса** API, но не отказ узла. Потеря хоста, а также LB, PostgreSQL и Redis остаются единичными точками отказа; выживание узла БД не заявлено.
|
||||
- PostgreSQL не реплицирована, Redis не кластеризован — при их отказе стенд недоступен, это честное учебное упрощение.
|
||||
- Генератор нагрузки `tests/load.py` — closed-loop: он ограничен клиентом и страдает coordinated omission, поэтому измеренный RPS — это пропускная способность HTTP-подтверждений, а не предельная ёмкость системы. Для серьёзных выводов нужен k6/Locust или свой open-loop генератор.
|
||||
- **Принятые риски (осознанно, вне объёма ЛР3).** Пароли хешируются Argon2id с 64 МиБ памяти на хеш, а ограничителя частоты нет: 4–5 одновременных регистраций на реплику с бюджетом 256 МиБ могут её выбить, а перебор паролей не throttled. Контракт делает `429` факультативным, защита вынесена в ЛР7 по карте курса; предел размера тела при этом закрыт (см. выше). Страница оператора HAProxy доступна без аутентификации, но только на loopback. `docker-compose.local.yaml` (локальная разработка из ЛР2) публикует PostgreSQL и Redis на 127.0.0.1 с синтетическим паролем — для стенда ЛР3 не используется. `X-Request-ID` принимается от клиента как есть: это нужно для сквозной корреляции, подделка значения искажает только аудит, инъекция в лог невозможна (Go запрещает переводы строк в заголовках, лог пишется JSON). `Makefile` экспортирует `-include .env` в окружение рецептов — при синтетических значениях это безопасно.
|
||||
- Записи идемпотентности не удаляются фоновым процессом: истёкшие строки занимаются лениво при повторном использовании ключа, остальные ждут будущей уборки (индекс `expires_at` уже есть).
|
||||
|
||||
@@ -0,0 +1,175 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/signal"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"mtusi-messenger/internal/config"
|
||||
"mtusi-messenger/internal/health"
|
||||
"mtusi-messenger/internal/logger"
|
||||
"mtusi-messenger/internal/platform/cache"
|
||||
"mtusi-messenger/internal/platform/token"
|
||||
"mtusi-messenger/internal/service/chat"
|
||||
"mtusi-messenger/internal/service/message"
|
||||
"mtusi-messenger/internal/service/session"
|
||||
"mtusi-messenger/internal/service/user"
|
||||
"mtusi-messenger/internal/storage/postgres"
|
||||
storageredis "mtusi-messenger/internal/storage/redis"
|
||||
"mtusi-messenger/internal/transport/rest"
|
||||
)
|
||||
|
||||
func main() {
|
||||
log := logger.New()
|
||||
|
||||
cfg, err := config.Load()
|
||||
if err != nil {
|
||||
log.Error("load config", slog.Any("error", err))
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
log = logger.New(
|
||||
logger.WithLevel(cfg.SlogLevel()),
|
||||
logger.WithFormat(cfg.LoggerFormat()),
|
||||
)
|
||||
slog.SetDefault(log)
|
||||
|
||||
if err := run(cfg, log); err != nil {
|
||||
log.Error("shutdown with error", slog.Any("error", err))
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
func run(cfg config.Config, log *slog.Logger) error {
|
||||
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
|
||||
defer stop()
|
||||
|
||||
store, err := postgres.New(ctx, cfg.Postgres, time.Duration(cfg.Idempotency.TTLSeconds)*time.Second)
|
||||
if err != nil {
|
||||
return fmt.Errorf("connect database: %w", err)
|
||||
}
|
||||
|
||||
defer store.Close()
|
||||
|
||||
redisCache, err := connectRedis(cfg.Redis)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
defer func() { _ = redisCache.Close() }()
|
||||
|
||||
sessionRepo := session.Repository(store.Sessions())
|
||||
chatRepo := chat.Repository(store.Chats())
|
||||
|
||||
pingers := []health.Pinger{store}
|
||||
|
||||
if cfg.Redis.Enabled {
|
||||
if cfg.Cache.Enabled {
|
||||
distributed, err := cache.NewDistributed(redisCache, cache.DistributedConfig{
|
||||
LockTTL: cfg.Cache.LockTTL,
|
||||
WaitTimeout: cfg.Cache.LockWaitTimeout,
|
||||
}, log)
|
||||
if err != nil {
|
||||
return fmt.Errorf("build distributed cache: %w", err)
|
||||
}
|
||||
|
||||
chatRepo = storageredis.NewChatRepository(
|
||||
store.Chats(),
|
||||
distributed,
|
||||
cfg.Cache.ChatListTTL,
|
||||
log,
|
||||
)
|
||||
}
|
||||
|
||||
log.Info("redis cache enabled", slog.String("host", cfg.Redis.Host), slog.Int("port", cfg.Redis.Port))
|
||||
}
|
||||
|
||||
ttl := time.Duration(cfg.Session.TTLSeconds) * time.Second
|
||||
sessionService := session.NewService(sessionRepo, token.New(), ttl)
|
||||
|
||||
router, err := rest.NewRouter(
|
||||
rest.NewHandler(
|
||||
user.NewService(store.Users()),
|
||||
chat.NewService(chatRepo),
|
||||
message.NewService(store.Messages()),
|
||||
health.New(pingers...),
|
||||
sessionService,
|
||||
),
|
||||
rest.NewSecurityHandler(sessionService),
|
||||
log,
|
||||
cfg.Server.MaxBodyBytes,
|
||||
)
|
||||
if err != nil {
|
||||
return fmt.Errorf("build router: %w", err)
|
||||
}
|
||||
|
||||
server := &http.Server{
|
||||
Addr: cfg.Addr(),
|
||||
Handler: router,
|
||||
ReadHeaderTimeout: cfg.Server.ReadHeaderTimeout,
|
||||
}
|
||||
|
||||
errc := make(chan error, 1)
|
||||
|
||||
go func() {
|
||||
log.Info("server started", slog.String("addr", cfg.Addr()))
|
||||
|
||||
if err := server.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
|
||||
errc <- err
|
||||
}
|
||||
|
||||
close(errc)
|
||||
}()
|
||||
|
||||
select {
|
||||
case err, ok := <-errc:
|
||||
if ok && err != nil {
|
||||
return fmt.Errorf("listen: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
case <-ctx.Done():
|
||||
}
|
||||
|
||||
log.Info("shutdown signal received", slog.Duration("timeout", cfg.Server.ShutdownTimeout))
|
||||
|
||||
shutdownCtx, cancel := context.WithTimeout(context.Background(), cfg.Server.ShutdownTimeout)
|
||||
defer cancel()
|
||||
|
||||
if err := server.Shutdown(shutdownCtx); err != nil {
|
||||
return fmt.Errorf("shutdown: %w", err)
|
||||
}
|
||||
|
||||
log.Info("server stopped")
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func connectRedis(cfg config.Redis) (cache.LockStore, error) {
|
||||
if !cfg.Enabled {
|
||||
return cache.NoOpCache{}, nil
|
||||
}
|
||||
|
||||
client, err := cache.NewRedis(cache.RedisConfig{
|
||||
Host: cfg.Host,
|
||||
Port: cfg.Port,
|
||||
Password: cfg.Password,
|
||||
DB: cfg.DB,
|
||||
MaxRetries: cfg.MaxRetries,
|
||||
DialTimeout: cfg.DialTimeout,
|
||||
ReadTimeout: cfg.ReadTimeout,
|
||||
WriteTimeout: cfg.WriteTimeout,
|
||||
PoolSize: cfg.PoolSize,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("connect redis: %w", err)
|
||||
}
|
||||
|
||||
return client, nil
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"os"
|
||||
|
||||
"github.com/pressly/goose/v3"
|
||||
|
||||
"mtusi-messenger/internal/config"
|
||||
"mtusi-messenger/internal/logger"
|
||||
"mtusi-messenger/internal/storage/postgres/migrations"
|
||||
|
||||
_ "github.com/jackc/pgx/v5/stdlib"
|
||||
)
|
||||
|
||||
func main() {
|
||||
log := logger.New()
|
||||
|
||||
if err := run(os.Args[1:]); err != nil {
|
||||
log.Error("migrate failed", slog.Any("error", err))
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
func run(args []string) error {
|
||||
cfg, err := config.Load()
|
||||
if err != nil {
|
||||
return fmt.Errorf("load config: %w", err)
|
||||
}
|
||||
|
||||
slog.SetDefault(logger.New(
|
||||
logger.WithLevel(cfg.SlogLevel()),
|
||||
logger.WithFormat(cfg.LoggerFormat()),
|
||||
))
|
||||
|
||||
command := "up"
|
||||
if len(args) > 0 {
|
||||
command = args[0]
|
||||
}
|
||||
|
||||
db, err := sql.Open("pgx", cfg.Postgres.DSN())
|
||||
if err != nil {
|
||||
return fmt.Errorf("open database: %w", err)
|
||||
}
|
||||
|
||||
defer func() { _ = db.Close() }()
|
||||
|
||||
pingCtx, cancel := context.WithTimeout(context.Background(), cfg.Postgres.ConnectTimeout)
|
||||
defer cancel()
|
||||
|
||||
if err := db.PingContext(pingCtx); err != nil {
|
||||
return fmt.Errorf("ping database: %w", err)
|
||||
}
|
||||
|
||||
goose.SetBaseFS(migrations.FS)
|
||||
|
||||
if err := goose.SetDialect("postgres"); err != nil {
|
||||
return fmt.Errorf("set dialect: %w", err)
|
||||
}
|
||||
|
||||
if err := goCommand(db, command); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func goCommand(db *sql.DB, command string) error {
|
||||
switch command {
|
||||
case "up":
|
||||
return goose.Up(db, ".")
|
||||
case "up-by-one":
|
||||
return goose.UpByOne(db, ".")
|
||||
case "down":
|
||||
return goose.Down(db, ".")
|
||||
case "status":
|
||||
return goose.Status(db, ".")
|
||||
case "version":
|
||||
return goose.Version(db, ".")
|
||||
case "redo":
|
||||
return goose.Redo(db, ".")
|
||||
default:
|
||||
return errors.New("unknown command: " + command + " (up, up-by-one, down, status, version, redo)")
|
||||
}
|
||||
}
|
||||
+173
@@ -0,0 +1,173 @@
|
||||
# Lab3 stand: two API replicas behind a HAProxy load balancer.
|
||||
#
|
||||
# cp -n .env.example .env
|
||||
# docker compose --env-file .env up -d --build
|
||||
# curl http://localhost:8080/health/ready
|
||||
#
|
||||
# Only the load balancer is published (127.0.0.1). Stores and API replicas are
|
||||
# reachable from the host via `docker compose exec` / `docker compose logs`.
|
||||
# No container_name anywhere: replica hostnames stay the short container IDs,
|
||||
# which the application reports back as X-Instance-Id.
|
||||
name: mtusi-messenger-lab3
|
||||
|
||||
x-app: &app
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile
|
||||
image: mtusi-messenger:lab3
|
||||
|
||||
services:
|
||||
postgres:
|
||||
image: postgres:18-alpine@sha256:77f585114c32fbca283dc835b0596f4e52b51b4c6662d7810b2f4084f60a1873
|
||||
environment:
|
||||
POSTGRES_USER: ${POSTGRES_USER:-messenger}
|
||||
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-messenger}
|
||||
POSTGRES_DB: ${POSTGRES_DB:-messenger}
|
||||
volumes:
|
||||
- postgres18-data:/var/lib/postgresql
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U $${POSTGRES_USER} -d $${POSTGRES_DB}"]
|
||||
interval: 5s
|
||||
timeout: 5s
|
||||
retries: 10
|
||||
start_period: 5s
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
# Saturation point of the stand (see REPORT.md, track 1): the database
|
||||
# runs at its quota while API replicas idle. Raise this knob to give the
|
||||
# shared dependency more of the host CPU.
|
||||
cpus: "${POSTGRES_CPU_LIMIT:-0.50}"
|
||||
memory: ${POSTGRES_MEM_LIMIT:-384M}
|
||||
restart: unless-stopped
|
||||
|
||||
redis:
|
||||
image: redis:7.4-alpine
|
||||
command:
|
||||
- redis-server
|
||||
- --appendonly
|
||||
- "yes"
|
||||
- --appendfsync
|
||||
- everysec
|
||||
- --save
|
||||
- "60"
|
||||
- "1"
|
||||
volumes:
|
||||
- redis7-data:/data
|
||||
healthcheck:
|
||||
test: ["CMD", "redis-cli", "ping"]
|
||||
interval: 5s
|
||||
timeout: 3s
|
||||
retries: 10
|
||||
start_period: 3s
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
cpus: "0.25"
|
||||
memory: 192M
|
||||
restart: unless-stopped
|
||||
|
||||
# One-shot schema bootstrap; runs once to completion before any API replica.
|
||||
migrate:
|
||||
<<: *app
|
||||
entrypoint: ["/usr/local/bin/migrate"]
|
||||
command: ["up"]
|
||||
environment:
|
||||
APP_CONFIG: /etc/messenger/dev/config.yaml
|
||||
POSTGRES_HOST: postgres
|
||||
POSTGRES_PORT: "5432"
|
||||
POSTGRES_DATABASE: ${POSTGRES_DB:-messenger}
|
||||
POSTGRES_USER: ${POSTGRES_USER:-messenger}
|
||||
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-messenger}
|
||||
POSTGRES_SSL_MODE: disable
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
cpus: "0.50"
|
||||
memory: 256M
|
||||
# One-shot: healthcheck из образа (проверка /health/live) для него бессмыслен.
|
||||
healthcheck:
|
||||
disable: true
|
||||
restart: "no"
|
||||
|
||||
api:
|
||||
<<: *app
|
||||
# Общий сетевой alias: LB резолвит одно имя в адреса всех реплик, поэтому
|
||||
# масштабирование и замена контейнеров не зависят от их номеров/ID.
|
||||
networks:
|
||||
default:
|
||||
aliases:
|
||||
- api-replica
|
||||
env_file:
|
||||
- path: .env
|
||||
required: false
|
||||
# Explicit values win over localhost defaults coming from .env (see .env.example).
|
||||
environment:
|
||||
APP_CONFIG: /etc/messenger/dev/config.yaml
|
||||
POSTGRES_HOST: postgres
|
||||
POSTGRES_PORT: "5432"
|
||||
POSTGRES_DATABASE: ${POSTGRES_DB:-messenger}
|
||||
POSTGRES_USER: ${POSTGRES_USER:-messenger}
|
||||
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-messenger}
|
||||
POSTGRES_SSL_MODE: disable
|
||||
REDIS_ENABLED: "true"
|
||||
REDIS_HOST: redis
|
||||
REDIS_PORT: "6379"
|
||||
CACHE_ENABLED: "true"
|
||||
# Размер пула соединений ОДНОЙ реплики; общий расход = реплики × значение.
|
||||
# Это один из общих ресурсов, который масштабирование расходует первым.
|
||||
POSTGRES_MAX_CONNS: "${POSTGRES_MAX_CONNS:-10}"
|
||||
deploy:
|
||||
replicas: ${API_REPLICAS:-2}
|
||||
resources:
|
||||
limits:
|
||||
cpus: "${API_CPU_LIMIT:-0.50}"
|
||||
memory: ${API_MEM_LIMIT:-256M}
|
||||
# The app drains on SIGTERM within SERVER_SHUTDOWN_TIMEOUT; keep the grace
|
||||
# period above it so Docker does not SIGKILL an in-flight request.
|
||||
stop_grace_period: 15s
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
redis:
|
||||
condition: service_healthy
|
||||
migrate:
|
||||
condition: service_completed_successfully
|
||||
healthcheck:
|
||||
test: ["CMD", "wget", "-q", "-O", "/dev/null", "http://127.0.0.1:8080/health/ready"]
|
||||
interval: 10s
|
||||
# Готовность проверяет PostgreSQL (критичную зависимость; кэш деградирует
|
||||
# безопасно): под насыщающей нагрузкой ответ может подойти к секундам, и
|
||||
# слишком строгий таймаут помечает занятую, но работающую реплику как
|
||||
# unhealthy.
|
||||
timeout: 5s
|
||||
retries: 6
|
||||
start_period: 5s
|
||||
restart: unless-stopped
|
||||
|
||||
# Public entry point. Active /health/ready probes remove a not-ready replica from
|
||||
# rotation entirely; infra/lb/haproxy.cfg holds the upstream, checks and retries.
|
||||
lb:
|
||||
image: haproxy:3.2-alpine
|
||||
volumes:
|
||||
- ./infra/lb/haproxy.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro
|
||||
ports:
|
||||
- "127.0.0.1:${SERVER_PORT:-8080}:80"
|
||||
# Operator-only stats page on loopback: shows which replica is UP/DOWN and why.
|
||||
- "127.0.0.1:${LB_STATS_PORT:-8404}:8404"
|
||||
depends_on:
|
||||
api:
|
||||
condition: service_healthy
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
cpus: "${LB_CPU_LIMIT:-0.25}"
|
||||
memory: 64M
|
||||
restart: unless-stopped
|
||||
|
||||
volumes:
|
||||
postgres18-data:
|
||||
redis7-data:
|
||||
@@ -0,0 +1,54 @@
|
||||
env: dev
|
||||
|
||||
server:
|
||||
host: 0.0.0.0
|
||||
port: 8080
|
||||
read_header_timeout: 10s
|
||||
shutdown_timeout: 10s
|
||||
# Предел размера тела запроса; JSON API ЛР3 укладывается в сотни килобайт,
|
||||
# а загрузка вложений ЛР4 (до 10 MiB) поднимает это значение явно.
|
||||
max_body_bytes: 262144
|
||||
|
||||
log:
|
||||
level: info
|
||||
format: json
|
||||
|
||||
postgres:
|
||||
host: localhost
|
||||
port: 5432
|
||||
database: messenger
|
||||
user: messenger
|
||||
# Dev default for a local run without environment overrides; POSTGRES_PASSWORD wins.
|
||||
password: messenger
|
||||
ssl_mode: disable
|
||||
max_conns: 10
|
||||
min_conns: 1
|
||||
max_conn_lifetime: 1h
|
||||
max_conn_idle_time: 30m
|
||||
connect_timeout: 5s
|
||||
query_timeout: 5s
|
||||
|
||||
redis:
|
||||
enabled: true
|
||||
host: localhost
|
||||
port: 6379
|
||||
db: 0
|
||||
# -1 disables go-redis retries; 0 keeps the library default (3 retries).
|
||||
max_retries: -1
|
||||
dial_timeout: 300ms
|
||||
read_timeout: 200ms
|
||||
write_timeout: 200ms
|
||||
pool_size: 10
|
||||
|
||||
cache:
|
||||
enabled: true
|
||||
chat_list_ttl: 5m
|
||||
lock_ttl: 10s
|
||||
lock_wait_timeout: 2s
|
||||
|
||||
session:
|
||||
ttl_seconds: 3600
|
||||
|
||||
# Retention of a message Idempotency-Key; contract 1.3.0 requires ≥ 24 h.
|
||||
idempotency:
|
||||
ttl_seconds: 86400
|
||||
@@ -0,0 +1,104 @@
|
||||
name: mtusi-messenger-lab2
|
||||
|
||||
x-app: &app
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile
|
||||
image: mtusi-messenger:lab2
|
||||
|
||||
services:
|
||||
postgres:
|
||||
image: postgres:18-alpine@sha256:77f585114c32fbca283dc835b0596f4e52b51b4c6662d7810b2f4084f60a1873
|
||||
environment:
|
||||
POSTGRES_USER: ${POSTGRES_USER:-messenger}
|
||||
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-messenger}
|
||||
POSTGRES_DB: ${POSTGRES_DB:-messenger}
|
||||
ports:
|
||||
- "127.0.0.1:${POSTGRES_PORT:-5432}:5432"
|
||||
volumes:
|
||||
- postgres18-data:/var/lib/postgresql
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U $${POSTGRES_USER} -d $${POSTGRES_DB}"]
|
||||
interval: 5s
|
||||
timeout: 5s
|
||||
retries: 10
|
||||
start_period: 5s
|
||||
restart: unless-stopped
|
||||
redis:
|
||||
image: redis:7.4-alpine
|
||||
command:
|
||||
- redis-server
|
||||
- --appendonly
|
||||
- "yes"
|
||||
- --appendfsync
|
||||
- everysec
|
||||
- --save
|
||||
- "60"
|
||||
- "1"
|
||||
ports:
|
||||
- "127.0.0.1:${REDIS_PORT:-6379}:6379"
|
||||
volumes:
|
||||
- redis7-data:/data
|
||||
healthcheck:
|
||||
test: ["CMD", "redis-cli", "ping"]
|
||||
interval: 5s
|
||||
timeout: 3s
|
||||
retries: 10
|
||||
start_period: 3s
|
||||
restart: unless-stopped
|
||||
migrate:
|
||||
<<: *app
|
||||
entrypoint: ["/usr/local/bin/migrate"]
|
||||
command: ["up"]
|
||||
environment:
|
||||
APP_CONFIG: /etc/messenger/dev/config.yaml
|
||||
POSTGRES_HOST: postgres
|
||||
POSTGRES_PORT: "5432"
|
||||
POSTGRES_DATABASE: ${POSTGRES_DB:-messenger}
|
||||
POSTGRES_USER: ${POSTGRES_USER:-messenger}
|
||||
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-messenger}
|
||||
POSTGRES_SSL_MODE: disable
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
restart: "no"
|
||||
|
||||
api:
|
||||
<<: *app
|
||||
env_file:
|
||||
- path: .env
|
||||
required: false
|
||||
environment:
|
||||
APP_CONFIG: /etc/messenger/dev/config.yaml
|
||||
POSTGRES_HOST: postgres
|
||||
POSTGRES_PORT: "5432"
|
||||
POSTGRES_DATABASE: ${POSTGRES_DB:-messenger}
|
||||
POSTGRES_USER: ${POSTGRES_USER:-messenger}
|
||||
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-messenger}
|
||||
POSTGRES_SSL_MODE: disable
|
||||
REDIS_ENABLED: "${REDIS_ENABLED:-true}"
|
||||
REDIS_HOST: redis
|
||||
REDIS_PORT: "6379"
|
||||
CACHE_ENABLED: "${CACHE_ENABLED:-true}"
|
||||
ports:
|
||||
- "127.0.0.1:${SERVER_PORT:-8080}:8080"
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
redis:
|
||||
condition: service_healthy
|
||||
migrate:
|
||||
condition: service_completed_successfully
|
||||
healthcheck:
|
||||
test: ["CMD", "wget", "-q", "-O", "/dev/null", "http://127.0.0.1:8080/health/ready"]
|
||||
interval: 10s
|
||||
timeout: 3s
|
||||
retries: 5
|
||||
start_period: 5s
|
||||
restart: unless-stopped
|
||||
|
||||
volumes:
|
||||
postgres18-data:
|
||||
name: mtusi-messenger-lab2-postgres18-data
|
||||
redis7-data:
|
||||
name: mtusi-messenger-lab2-redis7-data
|
||||
@@ -0,0 +1,7 @@
|
||||
# Architecture of the app binary inside the image
|
||||
# generated: 2026-10-15T19:03:01Z
|
||||
|
||||
## emulated build (--build-arg TARGETARCH=amd64): e_machine 3e = x86-64
|
||||
02 00 3e 00
|
||||
## fixed build (no TARGETARCH default): e_machine b7 = aarch64
|
||||
02 00 b7 00
|
||||
@@ -0,0 +1,3 @@
|
||||
# body limit check — 2026-10-16T14:02:25Z (limit 256 KiB from SERVER_MAX_BODY_BYTES)
|
||||
тело 400 КиБ (сверх лимита): 413
|
||||
тело 100 КиБ (в пределах): в„– 400
|
||||
@@ -0,0 +1,7 @@
|
||||
# Отказ PostgreSQL на пути отправки сообщения — 2026-10-16T14:10:06Z
|
||||
до остановки БД, через LB : 201 (instance=828f6451261b)
|
||||
до остановки БД, напрямую : 201
|
||||
при остановленной БД, напрямую (ожидается 503): 503
|
||||
при остановленной БД, через LB : 503 (instance=828f6451261b)
|
||||
готовность после возврата БД: True
|
||||
после возврата БД, через LB : 201 (instance=828f6451261b)
|
||||
@@ -0,0 +1,5 @@
|
||||
# make test-failover (прогон 1) — 2026-10-16T13:59:43Z
|
||||
env -u HTTP_PROXY -u HTTPS_PROXY -u ALL_PROXY -u http_proxy -u https_proxy -u all_proxy NO_PROXY=localhost,127.0.0.1,::1 no_proxy=localhost,127.0.0.1,::1 python3 tests/resilience.py --mode failover --action-script "scripts/stop-one.sh" --base-url "http://localhost:8080"
|
||||
Executing explicit failover hook; hook output suppressed to avoid leaking secrets.
|
||||
{"observed_instances_before": 2, "successful_writes": 127, "failed_attempts": 0, "first_recovery_seconds": 0.214}
|
||||
PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence.
|
||||
@@ -0,0 +1,5 @@
|
||||
# make test-failover (прогон 2) — 2026-10-16T13:59:43Z
|
||||
env -u HTTP_PROXY -u HTTPS_PROXY -u ALL_PROXY -u http_proxy -u https_proxy -u all_proxy NO_PROXY=localhost,127.0.0.1,::1 no_proxy=localhost,127.0.0.1,::1 python3 tests/resilience.py --mode failover --action-script "scripts/stop-one.sh" --base-url "http://localhost:8080"
|
||||
Executing explicit failover hook; hook output suppressed to avoid leaking secrets.
|
||||
{"observed_instances_before": 2, "successful_writes": 100, "failed_attempts": 0, "first_recovery_seconds": 2.237}
|
||||
PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence.
|
||||
@@ -0,0 +1,54 @@
|
||||
# student-tests/replica_failover.py — 2026-10-16T13:59:43Z
|
||||
{
|
||||
"before": {
|
||||
"instances": [
|
||||
"52861386fddb",
|
||||
"8587b4251b72"
|
||||
]
|
||||
},
|
||||
"replicas": [
|
||||
{
|
||||
"stopped": "52861386fddb",
|
||||
"stopped_container": "stop-one.sh: stopped api replica(s): mtusi-messenger-lab3-api-5",
|
||||
"hook_returncode": 0,
|
||||
"hook_seconds": 0.151,
|
||||
"hook_error": "",
|
||||
"successful_writes": 91,
|
||||
"successful_rps": 6.06,
|
||||
"failed_attempts": 0,
|
||||
"uncertain_retries": 0,
|
||||
"first_recovery_seconds": 1.659,
|
||||
"instances_after_recovery": [
|
||||
"8587b4251b72"
|
||||
],
|
||||
"messages_in_history": 91,
|
||||
"restored_seconds": 0.201,
|
||||
"instances_restored": [
|
||||
"52861386fddb",
|
||||
"8587b4251b72"
|
||||
]
|
||||
},
|
||||
{
|
||||
"stopped": "8587b4251b72",
|
||||
"stopped_container": "stop-one.sh: stopped api replica(s): mtusi-messenger-lab3-api-6",
|
||||
"hook_returncode": 0,
|
||||
"hook_seconds": 0.154,
|
||||
"hook_error": "",
|
||||
"successful_writes": 100,
|
||||
"successful_rps": 6.66,
|
||||
"failed_attempts": 0,
|
||||
"uncertain_retries": 0,
|
||||
"first_recovery_seconds": 1.656,
|
||||
"instances_after_recovery": [
|
||||
"52861386fddb"
|
||||
],
|
||||
"messages_in_history": 191,
|
||||
"restored_seconds": 0.182,
|
||||
"instances_restored": [
|
||||
"52861386fddb",
|
||||
"8587b4251b72"
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
PASS: каждая реплика остановлена по очереди; записи продолжились, дублей и потерь нет
|
||||
@@ -0,0 +1,4 @@
|
||||
# make test-idempotency — 2026-10-16T13:59:43Z
|
||||
env -u HTTP_PROXY -u HTTPS_PROXY -u ALL_PROXY -u http_proxy -u https_proxy -u all_proxy NO_PROXY=localhost,127.0.0.1,::1 no_proxy=localhost,127.0.0.1,::1 python3 student-tests/idempotency_parallel.py --base-url "http://localhost:8080"
|
||||
{"replay": {"workers": 12, "instances": ["52861386fddb", "8587b4251b72"], "message_id": "01a14502-f747-7fa8-bbad-84fa27f0ce80"}, "conflict": {"workers": 12, "accepted": 1, "conflicts": 11}, "stable_body": {"message_id": "01a14502-f771-7ea3-a03a-4d559e466ac8"}, "key_required": {"status": 400}}
|
||||
PASS: параллельный повтор с одним Idempotency-Key создаёт ровно одно сообщение
|
||||
@@ -0,0 +1,17 @@
|
||||
# Артефакты предыдущих лабораторных (ЛР1 и ЛР2)
|
||||
|
||||
Файлы перенесены сюда из `evidence/`, потому что относятся к **прежним** конфигурациям
|
||||
стенда и не являются доказательствами ЛР3: они сняты в ЛР1/ЛР2 в репозитории
|
||||
`mtusi-messenger` и попали сюда вместе с переносом кода. Часть из них ссылается на
|
||||
образ `mtusi2026lab1-messenger` и на in-memory хранилище, которое удалено ещё в ЛР2,
|
||||
поэтому их нельзя читать как проверки текущего решения.
|
||||
|
||||
- `check.txt`, `quality.txt`, `concurrency.txt`, `docker.txt`, `health.txt`, `restart.txt`, `sigterm.txt` — ЛР1: офлайн-проверка структуры, линт и тесты, конкурентные чтения, запуск контейнера и обработка SIGTERM.
|
||||
- `memory-experiment.*` — ЛР1: сравнение in-memory хранилища и PostgreSQL.
|
||||
- `track1-benchmark/` — ЛР1, трек 1: бенчмарк append-оптимизации in-memory хранилища (скрипт `scripts/track1_benchmark.py` удалён в ЛР3 как осиротевший: он ссылался на удалённый файл хранилища).
|
||||
- `cache/` — ЛР2: эксперименты с кэшем списка чатов, согласованность и поведение при отказе Redis.
|
||||
- `postgres/explain-analyze.txt` — ЛР2: план запроса истории сообщений.
|
||||
|
||||
Доказательства ЛР3 лежат рядом, в `evidence/` (`smoke.txt`, `idempotency.txt`,
|
||||
`persistence.txt`, `failover/`, `lb-readiness.txt`, `rolling-update/`,
|
||||
`stand.txt`, `arch.txt`, `track1/`), и собраны в `REPORT.md`.
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
# API cache performance experiment
|
||||
# generated: 2026-10-09T21:41:31Z
|
||||
running trial 1, cache=False, requests=1000
|
||||
{"requests": 1000, "workers": 8, "duration_seconds": 0.455918375053443, "rps": 2193.375074831716, "p50_ms": 3.3378750667907298, "p95_ms": 5.237665958702564, "p99_ms": 7.377958972938359, "trial": 1, "cache_enabled": false}
|
||||
running trial 1, cache=True, requests=1000
|
||||
{"requests": 1000, "workers": 8, "duration_seconds": 0.424924207967706, "rps": 2353.360861182094, "p50_ms": 3.075250016991049, "p95_ms": 5.355541012249887, "p99_ms": 6.619499996304512, "trial": 1, "cache_enabled": true}
|
||||
running trial 2, cache=False, requests=1000
|
||||
{"requests": 1000, "workers": 8, "duration_seconds": 0.5072490000165999, "rps": 1971.4183763147382, "p50_ms": 3.680104040540755, "p95_ms": 6.2174160266295075, "p99_ms": 8.554207975976169, "trial": 2, "cache_enabled": false}
|
||||
running trial 2, cache=True, requests=1000
|
||||
{"requests": 1000, "workers": 8, "duration_seconds": 0.4116047500865534, "rps": 2429.51520795063, "p50_ms": 2.9188335174694657, "p95_ms": 5.480541964061558, "p99_ms": 7.245125016197562, "trial": 2, "cache_enabled": true}
|
||||
{"results": [{"requests": 1000, "workers": 8, "duration_seconds": 0.455918375053443, "rps": 2193.375074831716, "p50_ms": 3.3378750667907298, "p95_ms": 5.237665958702564, "p99_ms": 7.377958972938359, "trial": 1, "cache_enabled": false}, {"requests": 1000, "workers": 8, "duration_seconds": 0.424924207967706, "rps": 2353.360861182094, "p50_ms": 3.075250016991049, "p95_ms": 5.355541012249887, "p99_ms": 6.619499996304512, "trial": 1, "cache_enabled": true}, {"requests": 1000, "workers": 8, "duration_seconds": 0.5072490000165999, "rps": 1971.4183763147382, "p50_ms": 3.680104040540755, "p95_ms": 6.2174160266295075, "p99_ms": 8.554207975976169, "trial": 2, "cache_enabled": false}, {"requests": 1000, "workers": 8, "duration_seconds": 0.4116047500865534, "rps": 2429.51520795063, "p50_ms": 2.9188335174694657, "p95_ms": 5.480541964061558, "p99_ms": 7.245125016197562, "trial": 2, "cache_enabled": true}], "users": 4, "chats": 60, "sessions_cached_in_both_modes": true}
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
# Cache consistency evidence (track 1)
|
||||
# generated: 2026-10-09T21:38:43Z
|
||||
# redis: localhost:6379 db=1
|
||||
|
||||
=== RUN TestChatRepositorySuite
|
||||
=== RUN TestChatRepositorySuite/TestBrokenCacheEntryIsDroppedAndRepopulated
|
||||
=== RUN TestChatRepositorySuite/TestCacheUnavailableFallsBackToSource
|
||||
=== RUN TestChatRepositorySuite/TestConcurrentColdReadsAreDeduplicated
|
||||
chat_repository_test.go:226: distributed lock: 100 concurrent cold reads -> 1 source load
|
||||
=== RUN TestChatRepositorySuite/TestConcurrentColdReadsWithoutProtectionStampede
|
||||
chat_repository_test.go:427: stampede demonstration: 100 concurrent reads -> 100 source loads
|
||||
=== RUN TestChatRepositorySuite/TestCreateInvalidatesMemberCaches
|
||||
=== RUN TestChatRepositorySuite/TestDeeperPagesBypassCache
|
||||
=== RUN TestChatRepositorySuite/TestEvictedCacheEntryReloadsFromSource
|
||||
=== RUN TestChatRepositorySuite/TestFirstPageIsCached
|
||||
=== RUN TestChatRepositorySuite/TestLimitIsPartOfCacheKey
|
||||
=== RUN TestChatRepositorySuite/TestMultipleInstancesShareDistributedLock
|
||||
chat_repository_test.go:276: multi-instance distributed lock: 3 instances x 30 reads -> 1 source load
|
||||
=== RUN TestChatRepositorySuite/TestSlowLoaderBeyondCacheBudgetReturnsData
|
||||
=== RUN TestChatRepositorySuite/TestSourceErrorIsNotRetried
|
||||
--- PASS: TestChatRepositorySuite (0.83s)
|
||||
--- PASS: TestChatRepositorySuite/TestBrokenCacheEntryIsDroppedAndRepopulated (0.00s)
|
||||
--- PASS: TestChatRepositorySuite/TestCacheUnavailableFallsBackToSource (0.00s)
|
||||
--- PASS: TestChatRepositorySuite/TestConcurrentColdReadsAreDeduplicated (0.03s)
|
||||
--- PASS: TestChatRepositorySuite/TestConcurrentColdReadsWithoutProtectionStampede (0.02s)
|
||||
--- PASS: TestChatRepositorySuite/TestCreateInvalidatesMemberCaches (0.01s)
|
||||
--- PASS: TestChatRepositorySuite/TestDeeperPagesBypassCache (0.00s)
|
||||
--- PASS: TestChatRepositorySuite/TestEvictedCacheEntryReloadsFromSource (0.00s)
|
||||
--- PASS: TestChatRepositorySuite/TestFirstPageIsCached (0.00s)
|
||||
--- PASS: TestChatRepositorySuite/TestLimitIsPartOfCacheKey (0.00s)
|
||||
--- PASS: TestChatRepositorySuite/TestMultipleInstancesShareDistributedLock (0.05s)
|
||||
--- PASS: TestChatRepositorySuite/TestSlowLoaderBeyondCacheBudgetReturnsData (0.70s)
|
||||
--- PASS: TestChatRepositorySuite/TestSourceErrorIsNotRetried (0.00s)
|
||||
PASS
|
||||
ok mtusi-messenger/internal/storage/redis 1.338s
|
||||
? mtusi-messenger/internal/storage/redis/mocks [no test files]
|
||||
Vendored
+22
@@ -0,0 +1,22 @@
|
||||
# Cache latency experiment
|
||||
# generated: 2026-10-06T15:53:09Z
|
||||
go version go1.27.1 darwin/arm64
|
||||
Darwin arm64
|
||||
2026/10/06 18:53:10 OK 00001_init.sql (10.27ms)
|
||||
2026/10/06 18:53:10 goose: successfully migrated database to version: 1
|
||||
=== RUN TestCacheLatencyExperiment
|
||||
cache_latency_experiment_test.go:83: baseline: requests=1000 source_loads=1000 p50=317.209µs p95=343.542µs p99=377.625µs
|
||||
cache_latency_experiment_test.go:84: redis cache: requests=1000 source_loads=1 p50=411.791µs p95=527.709µs p99=565.625µs
|
||||
--- PASS: TestCacheLatencyExperiment (0.97s)
|
||||
=== RUN TestCacheLatencyExperiment
|
||||
cache_latency_experiment_test.go:83: baseline: requests=1000 source_loads=1000 p50=271.125µs p95=330.584µs p99=389.209µs
|
||||
cache_latency_experiment_test.go:84: redis cache: requests=1000 source_loads=1 p50=388µs p95=453.959µs p99=512.625µs
|
||||
--- PASS: TestCacheLatencyExperiment (0.86s)
|
||||
=== RUN TestCacheLatencyExperiment
|
||||
cache_latency_experiment_test.go:83: baseline: requests=1000 source_loads=1000 p50=268.541µs p95=318.417µs p99=367.083µs
|
||||
cache_latency_experiment_test.go:84: redis cache: requests=1000 source_loads=1 p50=408.833µs p95=473.125µs p99=541.042µs
|
||||
--- PASS: TestCacheLatencyExperiment (0.88s)
|
||||
PASS
|
||||
ok mtusi-messenger/internal/storage/postgres 3.097s
|
||||
? mtusi-messenger/internal/storage/postgres/internal/sqlcgen [no test files]
|
||||
? mtusi-messenger/internal/storage/postgres/migrations [no test files]
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
# Cache performance experiment
|
||||
# generated: 2026-10-09T21:41:14Z
|
||||
go version go1.27.1 darwin/arm64
|
||||
Darwin arm64
|
||||
2026/10/10 00:41:15 OK 00001_init.sql (10.03ms)
|
||||
2026/10/10 00:41:15 OK 00002_user_chat_versions.sql (2.17ms)
|
||||
2026/10/10 00:41:15 goose: successfully migrated database to version: 2
|
||||
=== RUN TestCachePerformanceExperiment
|
||||
cache_performance_experiment_test.go:115: baseline (no cache): requests=10000 concurrency=50 sql=10000 duration=1.528s rps=6542 p50=7.490875ms p95=9.302792ms p99=10.779ms
|
||||
cache_performance_experiment_test.go:116: redis cache (cold): requests=10000 concurrency=50 sql=1 duration=851ms rps=11749 p50=4.192709ms p95=5.318916ms p99=5.905625ms
|
||||
cache_performance_experiment_test.go:117: redis cache (hot): requests=10000 concurrency=50 sql=0 duration=751ms rps=13320 p50=3.670958ms p95=4.644958ms p99=5.21475ms
|
||||
--- PASS: TestCachePerformanceExperiment (3.50s)
|
||||
=== RUN TestCachePerformanceExperiment
|
||||
cache_performance_experiment_test.go:115: baseline (no cache): requests=10000 concurrency=50 sql=10000 duration=1.415s rps=7066 p50=6.901958ms p95=8.697666ms p99=10.560416ms
|
||||
cache_performance_experiment_test.go:116: redis cache (cold): requests=10000 concurrency=50 sql=1 duration=846ms rps=11815 p50=4.033083ms p95=6.0305ms p99=6.963417ms
|
||||
cache_performance_experiment_test.go:117: redis cache (hot): requests=10000 concurrency=50 sql=0 duration=817ms rps=12234 p50=3.999959ms p95=5.060959ms p99=5.802042ms
|
||||
--- PASS: TestCachePerformanceExperiment (3.39s)
|
||||
=== RUN TestCachePerformanceExperiment
|
||||
cache_performance_experiment_test.go:115: baseline (no cache): requests=10000 concurrency=50 sql=10000 duration=1.511s rps=6618 p50=7.302667ms p95=9.420708ms p99=12.437917ms
|
||||
cache_performance_experiment_test.go:116: redis cache (cold): requests=10000 concurrency=50 sql=1 duration=827ms rps=12093 p50=3.984125ms p95=5.655167ms p99=6.8085ms
|
||||
cache_performance_experiment_test.go:117: redis cache (hot): requests=10000 concurrency=50 sql=0 duration=817ms rps=12247 p50=3.946959ms p95=5.363208ms p99=6.508458ms
|
||||
--- PASS: TestCachePerformanceExperiment (3.55s)
|
||||
PASS
|
||||
ok mtusi-messenger/internal/storage/postgres 10.978s
|
||||
? mtusi-messenger/internal/storage/postgres/internal/sqlcgen [no test files]
|
||||
? mtusi-messenger/internal/storage/postgres/migrations [no test files]
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
baseline: 6ms
|
||||
after stop: 476ms
|
||||
stop: n=1 max=476ms p95=476ms budget=2000ms
|
||||
pause parallel: n=30 max=215ms p95=214ms budget=2000ms
|
||||
create during pause: 201
|
||||
after recovery: new chat visible, 5ms
|
||||
lock keys without TTL: 0
|
||||
PASS: redis outage handled within budget
|
||||
@@ -0,0 +1,3 @@
|
||||
$ make check
|
||||
env -u HTTP_PROXY -u HTTPS_PROXY -u ALL_PROXY -u http_proxy -u https_proxy -u all_proxy NO_PROXY=localhost,127.0.0.1,::1 no_proxy=localhost,127.0.0.1,::1 python3 scripts/check_contract.py
|
||||
PASS: offline skeleton structure, local refs and Python syntax; application NOT tested.
|
||||
@@ -0,0 +1,2 @@
|
||||
command: docker run + Python ThreadPoolExecutor(10), 100 POST messages
|
||||
{"sent": 100, "read": 100, "unique": 100}
|
||||
@@ -0,0 +1,11 @@
|
||||
$ docker inspect --format ...
|
||||
status=running health=healthy user=10001:10001
|
||||
$ curl -i http://127.0.0.1:8080/health/live
|
||||
HTTP/1.1 200 OK
|
||||
Access-Control-Expose-Headers: X-Request-Id
|
||||
Content-Type: application/json; charset=utf-8
|
||||
X-Request-Id: 3d145e7d-423a-4510-9d6b-6f45b7cf552d
|
||||
Date: Thu, 24 Sep 2026 20:13:14 GMT
|
||||
Content-Length: 15
|
||||
|
||||
{"status":"ok"}
|
||||
@@ -0,0 +1 @@
|
||||
{"status":"ok"}
|
||||
File diff suppressed because it is too large
Load Diff
Binary file not shown.
|
After Width: | Height: | Size: 102 KiB |
@@ -0,0 +1,8 @@
|
||||
$ python3 scripts/memory_experiment.py --image mtusi2026lab1-messenger:arm64 --memory 64m --max-messages 20000 --output evidence/memory-experiment.json --plot evidence/memory-experiment.png
|
||||
memory_limit=64m
|
||||
successful_messages=8610
|
||||
failed_requests=0
|
||||
OOMKilled=true
|
||||
exit_code=137
|
||||
failure_time_seconds=5.9315
|
||||
plot=evidence/memory-experiment.png
|
||||
@@ -0,0 +1,64 @@
|
||||
# EXPLAIN (ANALYZE, BUFFERS)
|
||||
|
||||
## history_first_page
|
||||
|
||||
Limit (cost=0.29..5.40 rows=51 width=73) (actual time=0.007..0.012 rows=51.00 loops=1)
|
||||
Buffers: shared hit=4
|
||||
-> Index Scan using messages_chat_id_created_at_id_idx on messages (cost=0.29..1002.85 rows=10000 width=73) (actual time=0.006..0.009 rows=51.00 loops=1)
|
||||
Index Cond: (chat_id = '01a0f77e-9381-736f-9a2b-af3b1e1e87fd'::uuid)
|
||||
Index Searches: 1
|
||||
Buffers: shared hit=4
|
||||
Planning:
|
||||
Buffers: shared hit=44
|
||||
Planning Time: 0.147 ms
|
||||
Execution Time: 0.019 ms
|
||||
|
||||
## history_next_page
|
||||
|
||||
Limit (cost=0.29..7.71 rows=51 width=73) (actual time=0.004..0.010 rows=51.00 loops=1)
|
||||
Buffers: shared hit=4
|
||||
-> Index Scan using messages_chat_id_created_at_id_idx on messages (cost=0.29..524.01 rows=3599 width=73) (actual time=0.004..0.008 rows=51.00 loops=1)
|
||||
Index Cond: ((chat_id = '01a0f77e-9381-736f-9a2b-af3b1e1e87fd'::uuid) AND (ROW(created_at, id) > ROW('2026-10-01 11:44:23.146682+00'::timestamp with time zone, '00000000-0000-0000-0000-000000000000'::uuid)))
|
||||
Index Searches: 1
|
||||
Buffers: shared hit=4
|
||||
Planning Time: 0.021 ms
|
||||
Execution Time: 0.027 ms
|
||||
|
||||
## chats_list_for_member
|
||||
|
||||
Limit (cost=0.57..446.14 rows=51 width=70) (actual time=0.018..0.081 rows=51.00 loops=1)
|
||||
Buffers: shared hit=309
|
||||
-> Nested Loop (cost=0.57..87375.78 rows=10001 width=70) (actual time=0.018..0.079 rows=51.00 loops=1)
|
||||
Buffers: shared hit=309
|
||||
-> Index Scan using chats_created_at_id_idx on chats c (cost=0.29..554.24 rows=10001 width=38) (actual time=0.004..0.007 rows=51.00 loops=1)
|
||||
Index Searches: 1
|
||||
Buffers: shared hit=3
|
||||
-> Index Only Scan using chat_members_user_id_chat_id_idx on chat_members visible (cost=0.29..0.36 rows=1 width=16) (actual time=0.001..0.001 rows=1.00 loops=51)
|
||||
Index Cond: ((user_id = '01a0f77e-937a-7d1e-aacb-8909b9a65779'::uuid) AND (chat_id = c.id))
|
||||
Heap Fetches: 51
|
||||
Index Searches: 51
|
||||
Buffers: shared hit=153
|
||||
SubPlan 1
|
||||
-> Aggregate (cost=8.31..8.32 rows=1 width=32) (actual time=0.001..0.001 rows=1.00 loops=51)
|
||||
Buffers: shared hit=153
|
||||
-> Index Only Scan using chat_members_pkey on chat_members m (cost=0.29..8.30 rows=1 width=16) (actual time=0.000..0.000 rows=1.00 loops=51)
|
||||
Index Cond: (chat_id = c.id)
|
||||
Heap Fetches: 51
|
||||
Index Searches: 51
|
||||
Buffers: shared hit=153
|
||||
Planning:
|
||||
Buffers: shared hit=95
|
||||
Planning Time: 0.250 ms
|
||||
Execution Time: 0.098 ms
|
||||
|
||||
## user_by_username
|
||||
|
||||
Index Scan using users_username_key on users (cost=0.29..8.30 rows=1 width=42) (actual time=0.005..0.005 rows=1.00 loops=1)
|
||||
Index Cond: (username = 'bulk_5000'::text)
|
||||
Index Searches: 1
|
||||
Buffers: shared hit=3
|
||||
Planning:
|
||||
Buffers: shared hit=43
|
||||
Planning Time: 0.085 ms
|
||||
Execution Time: 0.008 ms
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
$ make check
|
||||
env -u HTTP_PROXY -u HTTPS_PROXY -u ALL_PROXY -u http_proxy -u https_proxy -u all_proxy NO_PROXY=localhost,127.0.0.1,::1 no_proxy=localhost,127.0.0.1,::1 python3 scripts/check_contract.py
|
||||
PASS: offline skeleton structure, local refs and Python syntax; application NOT tested.
|
||||
|
||||
$ go vet ./...
|
||||
|
||||
$ make lint
|
||||
/Users/vladislav/Projects/mtusi2026lab1-fork/bin/golangci-lint run -v
|
||||
level=info msg="golangci-lint has version 2.13.2 built with go1.27.0 from (unknown, modified: ?, mod sum: \"h1:bCyq3E4vo9qwzifjpzJqYndEt7Ncva80qkk8G2B4TXU=\") on (unknown)"
|
||||
level=info msg="[config_reader] Config search paths: [./ /Users/vladislav/Projects/mtusi2026lab1-fork /Users/vladislav/Projects /Users/vladislav /Users /]"
|
||||
level=info msg="[config_reader] Used config file .golangci.yml"
|
||||
level=info msg="[config_reader] Module name \"mtusi-messenger\""
|
||||
level=info msg="[goenv] Read go env for 5.97475ms: map[string]string{\"GOCACHE\":\"/Users/vladislav/Library/Caches/go-build\", \"GOROOT\":\"/opt/homebrew/Cellar/go/1.27.1/libexec\"}"
|
||||
level=info msg="[lintersdb] Active 50 linters: [asasalint bodyclose canonicalheader containedctx contextcheck copyloopvar depguard durationcheck errcheck errname errorlint exhaustive exptostd fatcontext forbidigo forcetypeassert gocheckcompilerdirectives gocritic gofumpt goimports gomoddirectives gosec govet ineffassign intrange makezero misspell musttag nilerr nilnil noctx nolintlint perfsprint prealloc reassign recvcheck revive rowserrcheck sloglint sqlclosecheck staticcheck testifylint thelper tparallel unconvert unparam unused usestdlibvars usetesting wastedassign]"
|
||||
level=info msg="[loader] Using build tags: [integration]"
|
||||
level=info msg="[loader] Go packages loading at mode 8767 (compiled_files|files|name|types_sizes|deps|exports_file|imports) took 122.006042ms"
|
||||
level=info msg="[runner/filename_unadjuster] Pre-built 0 adjustments in 4.792166ms"
|
||||
level=info msg="[linters_context/goanalysis] analyzers took 0s with no stages"
|
||||
level=info msg="[runner/exclusion_rules] Skipped 2 issues by rules: [Path: \"_test\\\\.go\", Linters: \"gosec, prealloc, forcetypeassert, unparam\"]"
|
||||
level=info msg="[runner] Issues before processing: 280, after processing: 0"
|
||||
level=info msg="[runner] Processors filtering stat (in/out): exclusion_paths: 280/280, invalid_issue: 280/280, path_absoluter: 280/280, filename_unadjuster: 280/280, generated_file_filter: 280/100, exclusion_rules: 100/0, cgo: 280/280, path_relativity: 280/280"
|
||||
level=info msg="[runner] processing took 607.916µs with stages: generated_file_filter: 420.959µs, exclusion_rules: 86.124µs, path_relativity: 83.917µs, sort_results: 4.458µs, invalid_issue: 4.292µs, cgo: 3.959µs, path_absoluter: 1.417µs, filename_unadjuster: 792ns, max_same_issues: 582ns, nolint_filter: 457ns, fixer: 292ns, exclusion_paths: 167ns, path_prettifier: 125ns, source_code: 125ns, path_shortener: 124ns, uniq_by_line: 42ns, severity-rules: 42ns, max_per_file_from_linter: 42ns, max_from_linter: 0s, diff: 0s"
|
||||
level=info msg="[runner] linters took 422.737625ms with stages: goanalysis_metalinter: 422.101875ms"
|
||||
0 issues.
|
||||
level=info msg="File cache stats: 0 entries of total size 0B"
|
||||
level=info msg="Memory: 7 samples, avg is 87.0MB, max is 111.2MB"
|
||||
level=info msg="Execution took 555.972916ms"
|
||||
|
||||
$ make unit-test
|
||||
go test -race -shuffle=on -count=1 -timeout=5m ./...
|
||||
? mtusi-messenger/cmd/messenger [no test files]
|
||||
ok mtusi-messenger/internal/config 1.838s
|
||||
ok mtusi-messenger/internal/domain 1.498s
|
||||
ok mtusi-messenger/internal/logger 2.150s
|
||||
ok mtusi-messenger/internal/service/chat 2.470s
|
||||
? mtusi-messenger/internal/service/chat/mocks [no test files]
|
||||
ok mtusi-messenger/internal/service/message 2.797s
|
||||
? mtusi-messenger/internal/service/message/mocks [no test files]
|
||||
ok mtusi-messenger/internal/service/user 3.474s
|
||||
? mtusi-messenger/internal/service/user/mocks [no test files]
|
||||
ok mtusi-messenger/internal/storage/memory 3.159s
|
||||
ok mtusi-messenger/internal/transport/rest 3.863s
|
||||
? mtusi-messenger/internal/transport/rest/oas [no test files]
|
||||
@@ -0,0 +1,10 @@
|
||||
$ docker stop mtusi2026lab1-messenger-lab1
|
||||
$ docker run -d --name mtusi2026lab1-messenger-lab1 -p 127.0.0.1:8080:8080 mtusi2026lab1-messenger:verify
|
||||
$ curl -i -H "X-User-Id: <created-before-restart>" http://127.0.0.1:8080/api/v1/users/me
|
||||
HTTP/1.1 401 Unauthorized
|
||||
Content-Type: application/json; charset=utf-8
|
||||
X-Request-Id: eadf9c21-d861-4c2c-8e76-46f086d27a11
|
||||
Date: Thu, 24 Sep 2026 20:13:02 GMT
|
||||
Content-Length: 110
|
||||
|
||||
{"error":{"code":"unauthorized","message":"Unauthorized","request_id":"eadf9c21-d861-4c2c-8e76-46f086d27a11"}}
|
||||
@@ -0,0 +1,7 @@
|
||||
$ docker kill --signal=TERM mtusi2026lab1-messenger-lab1
|
||||
$ docker wait mtusi2026lab1-messenger-lab1
|
||||
0
|
||||
elapsed_ms=114
|
||||
{"level":"info","time":"2026-09-24T20:14:19.192628563Z","msg":"server started","addr":"0.0.0.0:8080"}
|
||||
{"level":"info","time":"2026-09-24T20:14:20.186231067Z","msg":"shutdown signal received","timeout":"10s"}
|
||||
{"level":"info","time":"2026-09-24T20:14:20.188996621Z","msg":"server stopped"}
|
||||
@@ -0,0 +1,21 @@
|
||||
goos: darwin
|
||||
goarch: arm64
|
||||
pkg: mtusi-messenger/internal/storage/memory
|
||||
cpu: Apple M5 Pro
|
||||
BenchmarkMessageCreate/history=1000-18 3822346 309.5 ns/op 16 B/op 1 allocs/op
|
||||
BenchmarkMessageCreate/history=1000-18 3904586 307.6 ns/op 16 B/op 1 allocs/op
|
||||
BenchmarkMessageCreate/history=1000-18 3889698 308.1 ns/op 16 B/op 1 allocs/op
|
||||
BenchmarkMessageCreate/history=1000-18 3892981 308.2 ns/op 16 B/op 1 allocs/op
|
||||
BenchmarkMessageCreate/history=1000-18 3888345 308.3 ns/op 16 B/op 1 allocs/op
|
||||
BenchmarkMessageCreate/history=10000-18 3578911 335.4 ns/op 16 B/op 1 allocs/op
|
||||
BenchmarkMessageCreate/history=10000-18 3570348 335.9 ns/op 16 B/op 1 allocs/op
|
||||
BenchmarkMessageCreate/history=10000-18 3581305 335.0 ns/op 16 B/op 1 allocs/op
|
||||
BenchmarkMessageCreate/history=10000-18 3573933 336.0 ns/op 16 B/op 1 allocs/op
|
||||
BenchmarkMessageCreate/history=10000-18 3563053 336.4 ns/op 16 B/op 1 allocs/op
|
||||
BenchmarkMessageCreate/history=50000-18 3425475 349.8 ns/op 16 B/op 1 allocs/op
|
||||
BenchmarkMessageCreate/history=50000-18 3435330 349.1 ns/op 16 B/op 1 allocs/op
|
||||
BenchmarkMessageCreate/history=50000-18 3438290 349.3 ns/op 16 B/op 1 allocs/op
|
||||
BenchmarkMessageCreate/history=50000-18 3420394 349.8 ns/op 16 B/op 1 allocs/op
|
||||
BenchmarkMessageCreate/history=50000-18 3420736 350.1 ns/op 16 B/op 1 allocs/op
|
||||
PASS
|
||||
ok mtusi-messenger/internal/storage/memory 18.237s
|
||||
@@ -0,0 +1,128 @@
|
||||
[
|
||||
{
|
||||
"history": 100,
|
||||
"concurrency": 1,
|
||||
"duration_seconds": 2.002,
|
||||
"successful_requests": 526,
|
||||
"failed_requests": 0,
|
||||
"rps": 262.791,
|
||||
"p50_ms": 3.378,
|
||||
"p95_ms": 4.12,
|
||||
"p99_ms": 16.979,
|
||||
"rss_min_kib": 18880,
|
||||
"rss_max_kib": 22816,
|
||||
"rss_delta_kib": 3936
|
||||
},
|
||||
{
|
||||
"history": 100,
|
||||
"concurrency": 4,
|
||||
"duration_seconds": 2.002,
|
||||
"successful_requests": 1450,
|
||||
"failed_requests": 0,
|
||||
"rps": 724.134,
|
||||
"p50_ms": 4.18,
|
||||
"p95_ms": 16.695,
|
||||
"p99_ms": 21.604,
|
||||
"rss_min_kib": 20512,
|
||||
"rss_max_kib": 24208,
|
||||
"rss_delta_kib": 3696
|
||||
},
|
||||
{
|
||||
"history": 100,
|
||||
"concurrency": 16,
|
||||
"duration_seconds": 2.079,
|
||||
"successful_requests": 2315,
|
||||
"failed_requests": 0,
|
||||
"rps": 1113.309,
|
||||
"p50_ms": 8.563,
|
||||
"p95_ms": 29.584,
|
||||
"p99_ms": 93.023,
|
||||
"rss_min_kib": 18880,
|
||||
"rss_max_kib": 25296,
|
||||
"rss_delta_kib": 6416
|
||||
},
|
||||
{
|
||||
"history": 1000,
|
||||
"concurrency": 1,
|
||||
"duration_seconds": 2.007,
|
||||
"successful_requests": 478,
|
||||
"failed_requests": 0,
|
||||
"rps": 238.14,
|
||||
"p50_ms": 3.477,
|
||||
"p95_ms": 10.892,
|
||||
"p99_ms": 20.404,
|
||||
"rss_min_kib": 23120,
|
||||
"rss_max_kib": 23584,
|
||||
"rss_delta_kib": 464
|
||||
},
|
||||
{
|
||||
"history": 1000,
|
||||
"concurrency": 4,
|
||||
"duration_seconds": 2.003,
|
||||
"successful_requests": 1380,
|
||||
"failed_requests": 0,
|
||||
"rps": 688.971,
|
||||
"p50_ms": 4.197,
|
||||
"p95_ms": 17.189,
|
||||
"p99_ms": 28.458,
|
||||
"rss_min_kib": 23344,
|
||||
"rss_max_kib": 24592,
|
||||
"rss_delta_kib": 1248
|
||||
},
|
||||
{
|
||||
"history": 1000,
|
||||
"concurrency": 16,
|
||||
"duration_seconds": 2.005,
|
||||
"successful_requests": 2298,
|
||||
"failed_requests": 0,
|
||||
"rps": 1146.063,
|
||||
"p50_ms": 8.474,
|
||||
"p95_ms": 29.384,
|
||||
"p99_ms": 92.528,
|
||||
"rss_min_kib": 23232,
|
||||
"rss_max_kib": 26272,
|
||||
"rss_delta_kib": 3040
|
||||
},
|
||||
{
|
||||
"history": 5000,
|
||||
"concurrency": 1,
|
||||
"duration_seconds": 2.001,
|
||||
"successful_requests": 494,
|
||||
"failed_requests": 0,
|
||||
"rps": 246.902,
|
||||
"p50_ms": 3.414,
|
||||
"p95_ms": 10.767,
|
||||
"p99_ms": 18.996,
|
||||
"rss_min_kib": 25248,
|
||||
"rss_max_kib": 25296,
|
||||
"rss_delta_kib": 48
|
||||
},
|
||||
{
|
||||
"history": 5000,
|
||||
"concurrency": 4,
|
||||
"duration_seconds": 2.004,
|
||||
"successful_requests": 1398,
|
||||
"failed_requests": 0,
|
||||
"rps": 697.712,
|
||||
"p50_ms": 4.147,
|
||||
"p95_ms": 17.142,
|
||||
"p99_ms": 26.446,
|
||||
"rss_min_kib": 24816,
|
||||
"rss_max_kib": 25104,
|
||||
"rss_delta_kib": 288
|
||||
},
|
||||
{
|
||||
"history": 5000,
|
||||
"concurrency": 16,
|
||||
"duration_seconds": 2.006,
|
||||
"successful_requests": 2261,
|
||||
"failed_requests": 0,
|
||||
"rps": 1126.862,
|
||||
"p50_ms": 8.635,
|
||||
"p95_ms": 24.133,
|
||||
"p99_ms": 93.225,
|
||||
"rss_min_kib": 25200,
|
||||
"rss_max_kib": 26752,
|
||||
"rss_delta_kib": 1552
|
||||
}
|
||||
]
|
||||
@@ -0,0 +1,110 @@
|
||||
[
|
||||
{
|
||||
"history": 100,
|
||||
"concurrency": 1,
|
||||
"rps_before": 262.791,
|
||||
"p95_ms_before": 4.12,
|
||||
"p99_ms_before": 16.979,
|
||||
"rss_max_kib_before": 22816,
|
||||
"rps_after": 265.189,
|
||||
"p95_ms_after": 4.276,
|
||||
"p99_ms_after": 17.123,
|
||||
"rss_max_kib_after": 22736
|
||||
},
|
||||
{
|
||||
"history": 100,
|
||||
"concurrency": 4,
|
||||
"rps_before": 724.134,
|
||||
"p95_ms_before": 16.695,
|
||||
"p99_ms_before": 21.604,
|
||||
"rss_max_kib_before": 24208,
|
||||
"rps_after": 720.55,
|
||||
"p95_ms_after": 16.868,
|
||||
"p99_ms_after": 21.043,
|
||||
"rss_max_kib_after": 24128
|
||||
},
|
||||
{
|
||||
"history": 100,
|
||||
"concurrency": 16,
|
||||
"rps_before": 1113.309,
|
||||
"p95_ms_before": 29.584,
|
||||
"p99_ms_before": 93.023,
|
||||
"rss_max_kib_before": 25296,
|
||||
"rps_after": 1125.923,
|
||||
"p95_ms_after": 29.142,
|
||||
"p99_ms_after": 91.221,
|
||||
"rss_max_kib_after": 25216
|
||||
},
|
||||
{
|
||||
"history": 1000,
|
||||
"concurrency": 1,
|
||||
"rps_before": 238.14,
|
||||
"p95_ms_before": 10.892,
|
||||
"p99_ms_before": 20.404,
|
||||
"rss_max_kib_before": 23584,
|
||||
"rps_after": 237.68,
|
||||
"p95_ms_after": 11.279,
|
||||
"p99_ms_after": 19.675,
|
||||
"rss_max_kib_after": 23504
|
||||
},
|
||||
{
|
||||
"history": 1000,
|
||||
"concurrency": 4,
|
||||
"rps_before": 688.971,
|
||||
"p95_ms_before": 17.189,
|
||||
"p99_ms_before": 28.458,
|
||||
"rss_max_kib_before": 24592,
|
||||
"rps_after": 667.05,
|
||||
"p95_ms_after": 17.243,
|
||||
"p99_ms_after": 29.938,
|
||||
"rss_max_kib_after": 25280
|
||||
},
|
||||
{
|
||||
"history": 1000,
|
||||
"concurrency": 16,
|
||||
"rps_before": 1146.063,
|
||||
"p95_ms_before": 29.384,
|
||||
"p99_ms_before": 92.528,
|
||||
"rss_max_kib_before": 26272,
|
||||
"rps_after": 1102.581,
|
||||
"p95_ms_after": 30.252,
|
||||
"p99_ms_after": 93.912,
|
||||
"rss_max_kib_after": 25200
|
||||
},
|
||||
{
|
||||
"history": 5000,
|
||||
"concurrency": 1,
|
||||
"rps_before": 246.902,
|
||||
"p95_ms_before": 10.767,
|
||||
"p99_ms_before": 18.996,
|
||||
"rss_max_kib_before": 25296,
|
||||
"rps_after": 241.241,
|
||||
"p95_ms_after": 10.897,
|
||||
"p99_ms_after": 18.681,
|
||||
"rss_max_kib_after": 25456
|
||||
},
|
||||
{
|
||||
"history": 5000,
|
||||
"concurrency": 4,
|
||||
"rps_before": 697.712,
|
||||
"p95_ms_before": 17.142,
|
||||
"p99_ms_before": 26.446,
|
||||
"rss_max_kib_before": 25104,
|
||||
"rps_after": 685.839,
|
||||
"p95_ms_after": 17.418,
|
||||
"p99_ms_after": 26.618,
|
||||
"rss_max_kib_after": 25376
|
||||
},
|
||||
{
|
||||
"history": 5000,
|
||||
"concurrency": 16,
|
||||
"rps_before": 1126.862,
|
||||
"p95_ms_before": 24.133,
|
||||
"p99_ms_before": 93.225,
|
||||
"rss_max_kib_before": 26752,
|
||||
"rps_after": 1079.866,
|
||||
"p95_ms_after": 31.525,
|
||||
"p99_ms_after": 94.709,
|
||||
"rss_max_kib_after": 26640
|
||||
}
|
||||
]
|
||||
@@ -0,0 +1,211 @@
|
||||
{
|
||||
"mode": "baseline",
|
||||
"command": [
|
||||
"go",
|
||||
"run",
|
||||
"-overlay",
|
||||
"/var/folders/jd/nsgkfx9s75xb84909646j0zm0000gn/T/messenger-track1-58qai1az/overlay.json",
|
||||
"./cmd/messenger"
|
||||
],
|
||||
"go_version": "go version go1.27.1 darwin/arm64",
|
||||
"os_arch": [
|
||||
"darwin",
|
||||
"arm64"
|
||||
],
|
||||
"requests_per_case": 100000,
|
||||
"rss_source": "ps RSS of go run child executable, KiB; sampled every 100 ms",
|
||||
"rows": [
|
||||
{
|
||||
"history": 1000,
|
||||
"concurrency": 1,
|
||||
"duration_seconds": 13.634,
|
||||
"requested_requests": 100000,
|
||||
"warmup_requests": 100,
|
||||
"successful_requests": 100000,
|
||||
"failed_requests": 0,
|
||||
"rps": 7334.409,
|
||||
"p50_ms": 0.13,
|
||||
"p95_ms": 0.146,
|
||||
"p99_ms": 0.186,
|
||||
"rss_min_kib": 23616,
|
||||
"rss_max_kib": 59968,
|
||||
"rss_delta_kib": 36352
|
||||
},
|
||||
{
|
||||
"history": 1000,
|
||||
"concurrency": 4,
|
||||
"duration_seconds": 11.333,
|
||||
"requested_requests": 100000,
|
||||
"warmup_requests": 100,
|
||||
"successful_requests": 100000,
|
||||
"failed_requests": 0,
|
||||
"rps": 8823.924,
|
||||
"p50_ms": 0.42,
|
||||
"p95_ms": 0.654,
|
||||
"p99_ms": 0.869,
|
||||
"rss_min_kib": 23424,
|
||||
"rss_max_kib": 58464,
|
||||
"rss_delta_kib": 35040
|
||||
},
|
||||
{
|
||||
"history": 1000,
|
||||
"concurrency": 16,
|
||||
"duration_seconds": 13.63,
|
||||
"requested_requests": 100000,
|
||||
"warmup_requests": 100,
|
||||
"successful_requests": 100000,
|
||||
"failed_requests": 0,
|
||||
"rps": 7336.995,
|
||||
"p50_ms": 2.021,
|
||||
"p95_ms": 3.514,
|
||||
"p99_ms": 4.631,
|
||||
"rss_min_kib": 23520,
|
||||
"rss_max_kib": 66544,
|
||||
"rss_delta_kib": 43024
|
||||
},
|
||||
{
|
||||
"history": 1000,
|
||||
"concurrency": 32,
|
||||
"duration_seconds": 13.538,
|
||||
"requested_requests": 100000,
|
||||
"warmup_requests": 100,
|
||||
"successful_requests": 100000,
|
||||
"failed_requests": 0,
|
||||
"rps": 7386.656,
|
||||
"p50_ms": 4.022,
|
||||
"p95_ms": 7.026,
|
||||
"p99_ms": 8.953,
|
||||
"rss_min_kib": 23856,
|
||||
"rss_max_kib": 65616,
|
||||
"rss_delta_kib": 41760
|
||||
},
|
||||
{
|
||||
"history": 10000,
|
||||
"concurrency": 1,
|
||||
"duration_seconds": 14.008,
|
||||
"requested_requests": 100000,
|
||||
"warmup_requests": 100,
|
||||
"successful_requests": 100000,
|
||||
"failed_requests": 0,
|
||||
"rps": 7138.887,
|
||||
"p50_ms": 0.13,
|
||||
"p95_ms": 0.149,
|
||||
"p99_ms": 0.21,
|
||||
"rss_min_kib": 25984,
|
||||
"rss_max_kib": 70416,
|
||||
"rss_delta_kib": 44432
|
||||
},
|
||||
{
|
||||
"history": 10000,
|
||||
"concurrency": 4,
|
||||
"duration_seconds": 11.057,
|
||||
"requested_requests": 100000,
|
||||
"warmup_requests": 100,
|
||||
"successful_requests": 100000,
|
||||
"failed_requests": 0,
|
||||
"rps": 9043.732,
|
||||
"p50_ms": 0.406,
|
||||
"p95_ms": 0.626,
|
||||
"p99_ms": 0.841,
|
||||
"rss_min_kib": 26272,
|
||||
"rss_max_kib": 67376,
|
||||
"rss_delta_kib": 41104
|
||||
},
|
||||
{
|
||||
"history": 10000,
|
||||
"concurrency": 16,
|
||||
"duration_seconds": 13.436,
|
||||
"requested_requests": 100000,
|
||||
"warmup_requests": 100,
|
||||
"successful_requests": 100000,
|
||||
"failed_requests": 0,
|
||||
"rps": 7442.895,
|
||||
"p50_ms": 1.977,
|
||||
"p95_ms": 3.485,
|
||||
"p99_ms": 4.703,
|
||||
"rss_min_kib": 26576,
|
||||
"rss_max_kib": 75616,
|
||||
"rss_delta_kib": 49040
|
||||
},
|
||||
{
|
||||
"history": 10000,
|
||||
"concurrency": 32,
|
||||
"duration_seconds": 13.546,
|
||||
"requested_requests": 100000,
|
||||
"warmup_requests": 100,
|
||||
"successful_requests": 100000,
|
||||
"failed_requests": 0,
|
||||
"rps": 7382.485,
|
||||
"p50_ms": 4.01,
|
||||
"p95_ms": 7.051,
|
||||
"p99_ms": 9.096,
|
||||
"rss_min_kib": 25456,
|
||||
"rss_max_kib": 77792,
|
||||
"rss_delta_kib": 52336
|
||||
},
|
||||
{
|
||||
"history": 50000,
|
||||
"concurrency": 1,
|
||||
"duration_seconds": 13.969,
|
||||
"requested_requests": 100000,
|
||||
"warmup_requests": 100,
|
||||
"successful_requests": 100000,
|
||||
"failed_requests": 0,
|
||||
"rps": 7158.653,
|
||||
"p50_ms": 0.13,
|
||||
"p95_ms": 0.149,
|
||||
"p99_ms": 0.211,
|
||||
"rss_min_kib": 40080,
|
||||
"rss_max_kib": 81072,
|
||||
"rss_delta_kib": 40992
|
||||
},
|
||||
{
|
||||
"history": 50000,
|
||||
"concurrency": 4,
|
||||
"duration_seconds": 11.014,
|
||||
"requested_requests": 100000,
|
||||
"warmup_requests": 100,
|
||||
"successful_requests": 100000,
|
||||
"failed_requests": 0,
|
||||
"rps": 9079.212,
|
||||
"p50_ms": 0.404,
|
||||
"p95_ms": 0.623,
|
||||
"p99_ms": 0.823,
|
||||
"rss_min_kib": 40448,
|
||||
"rss_max_kib": 77088,
|
||||
"rss_delta_kib": 36640
|
||||
},
|
||||
{
|
||||
"history": 50000,
|
||||
"concurrency": 16,
|
||||
"duration_seconds": 13.479,
|
||||
"requested_requests": 100000,
|
||||
"warmup_requests": 100,
|
||||
"successful_requests": 100000,
|
||||
"failed_requests": 0,
|
||||
"rps": 7419.068,
|
||||
"p50_ms": 1.99,
|
||||
"p95_ms": 3.471,
|
||||
"p99_ms": 4.694,
|
||||
"rss_min_kib": 42336,
|
||||
"rss_max_kib": 79552,
|
||||
"rss_delta_kib": 37216
|
||||
},
|
||||
{
|
||||
"history": 50000,
|
||||
"concurrency": 32,
|
||||
"duration_seconds": 13.464,
|
||||
"requested_requests": 100000,
|
||||
"warmup_requests": 100,
|
||||
"successful_requests": 100000,
|
||||
"failed_requests": 0,
|
||||
"rps": 7427.333,
|
||||
"p50_ms": 3.99,
|
||||
"p95_ms": 7.049,
|
||||
"p99_ms": 9.007,
|
||||
"rss_min_kib": 40336,
|
||||
"rss_max_kib": 89552,
|
||||
"rss_delta_kib": 49216
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,266 @@
|
||||
[
|
||||
{
|
||||
"history": 1000,
|
||||
"concurrency": 1,
|
||||
"requested_requests": 100000,
|
||||
"warmup_requests": 100,
|
||||
"duration_seconds_before": 13.634,
|
||||
"duration_seconds_after": 13.919,
|
||||
"successful_requests_before": 100000,
|
||||
"successful_requests_after": 100000,
|
||||
"failed_requests_before": 0,
|
||||
"failed_requests_after": 0,
|
||||
"rps_before": 7334.409,
|
||||
"rps_after": 7184.594,
|
||||
"p50_ms_before": 0.13,
|
||||
"p50_ms_after": 0.129,
|
||||
"p95_ms_before": 0.146,
|
||||
"p95_ms_after": 0.15,
|
||||
"p99_ms_before": 0.186,
|
||||
"p99_ms_after": 0.231,
|
||||
"rss_max_kib_before": 59968,
|
||||
"rss_max_kib_after": 62048
|
||||
},
|
||||
{
|
||||
"history": 1000,
|
||||
"concurrency": 4,
|
||||
"requested_requests": 100000,
|
||||
"warmup_requests": 100,
|
||||
"duration_seconds_before": 11.333,
|
||||
"duration_seconds_after": 11.115,
|
||||
"successful_requests_before": 100000,
|
||||
"successful_requests_after": 100000,
|
||||
"failed_requests_before": 0,
|
||||
"failed_requests_after": 0,
|
||||
"rps_before": 8823.924,
|
||||
"rps_after": 8996.523,
|
||||
"p50_ms_before": 0.42,
|
||||
"p50_ms_after": 0.407,
|
||||
"p95_ms_before": 0.654,
|
||||
"p95_ms_after": 0.632,
|
||||
"p99_ms_before": 0.869,
|
||||
"p99_ms_after": 0.867,
|
||||
"rss_max_kib_before": 58464,
|
||||
"rss_max_kib_after": 61040
|
||||
},
|
||||
{
|
||||
"history": 1000,
|
||||
"concurrency": 16,
|
||||
"requested_requests": 100000,
|
||||
"warmup_requests": 100,
|
||||
"duration_seconds_before": 13.63,
|
||||
"duration_seconds_after": 13.364,
|
||||
"successful_requests_before": 100000,
|
||||
"successful_requests_after": 100000,
|
||||
"failed_requests_before": 0,
|
||||
"failed_requests_after": 0,
|
||||
"rps_before": 7336.995,
|
||||
"rps_after": 7482.719,
|
||||
"p50_ms_before": 2.021,
|
||||
"p50_ms_after": 1.977,
|
||||
"p95_ms_before": 3.514,
|
||||
"p95_ms_after": 3.445,
|
||||
"p99_ms_before": 4.631,
|
||||
"p99_ms_after": 4.577,
|
||||
"rss_max_kib_before": 66544,
|
||||
"rss_max_kib_after": 61328
|
||||
},
|
||||
{
|
||||
"history": 1000,
|
||||
"concurrency": 32,
|
||||
"requested_requests": 100000,
|
||||
"warmup_requests": 100,
|
||||
"duration_seconds_before": 13.538,
|
||||
"duration_seconds_after": 13.547,
|
||||
"successful_requests_before": 100000,
|
||||
"successful_requests_after": 100000,
|
||||
"failed_requests_before": 0,
|
||||
"failed_requests_after": 0,
|
||||
"rps_before": 7386.656,
|
||||
"rps_after": 7381.5,
|
||||
"p50_ms_before": 4.022,
|
||||
"p50_ms_after": 4.016,
|
||||
"p95_ms_before": 7.026,
|
||||
"p95_ms_after": 7.058,
|
||||
"p99_ms_before": 8.953,
|
||||
"p99_ms_after": 9.054,
|
||||
"rss_max_kib_before": 65616,
|
||||
"rss_max_kib_after": 68768
|
||||
},
|
||||
{
|
||||
"history": 10000,
|
||||
"concurrency": 1,
|
||||
"requested_requests": 100000,
|
||||
"warmup_requests": 100,
|
||||
"duration_seconds_before": 14.008,
|
||||
"duration_seconds_after": 13.984,
|
||||
"successful_requests_before": 100000,
|
||||
"successful_requests_after": 100000,
|
||||
"failed_requests_before": 0,
|
||||
"failed_requests_after": 0,
|
||||
"rps_before": 7138.887,
|
||||
"rps_after": 7150.931,
|
||||
"p50_ms_before": 0.13,
|
||||
"p50_ms_after": 0.131,
|
||||
"p95_ms_before": 0.149,
|
||||
"p95_ms_after": 0.146,
|
||||
"p99_ms_before": 0.21,
|
||||
"p99_ms_after": 0.187,
|
||||
"rss_max_kib_before": 70416,
|
||||
"rss_max_kib_after": 68128
|
||||
},
|
||||
{
|
||||
"history": 10000,
|
||||
"concurrency": 4,
|
||||
"requested_requests": 100000,
|
||||
"warmup_requests": 100,
|
||||
"duration_seconds_before": 11.057,
|
||||
"duration_seconds_after": 11.046,
|
||||
"successful_requests_before": 100000,
|
||||
"successful_requests_after": 100000,
|
||||
"failed_requests_before": 0,
|
||||
"failed_requests_after": 0,
|
||||
"rps_before": 9043.732,
|
||||
"rps_after": 9052.965,
|
||||
"p50_ms_before": 0.406,
|
||||
"p50_ms_after": 0.404,
|
||||
"p95_ms_before": 0.626,
|
||||
"p95_ms_after": 0.628,
|
||||
"p99_ms_before": 0.841,
|
||||
"p99_ms_after": 0.859,
|
||||
"rss_max_kib_before": 67376,
|
||||
"rss_max_kib_after": 71632
|
||||
},
|
||||
{
|
||||
"history": 10000,
|
||||
"concurrency": 16,
|
||||
"requested_requests": 100000,
|
||||
"warmup_requests": 100,
|
||||
"duration_seconds_before": 13.436,
|
||||
"duration_seconds_after": 13.439,
|
||||
"successful_requests_before": 100000,
|
||||
"successful_requests_after": 100000,
|
||||
"failed_requests_before": 0,
|
||||
"failed_requests_after": 0,
|
||||
"rps_before": 7442.895,
|
||||
"rps_after": 7440.817,
|
||||
"p50_ms_before": 1.977,
|
||||
"p50_ms_after": 1.989,
|
||||
"p95_ms_before": 3.485,
|
||||
"p95_ms_after": 3.468,
|
||||
"p99_ms_before": 4.703,
|
||||
"p99_ms_after": 4.701,
|
||||
"rss_max_kib_before": 75616,
|
||||
"rss_max_kib_after": 73712
|
||||
},
|
||||
{
|
||||
"history": 10000,
|
||||
"concurrency": 32,
|
||||
"requested_requests": 100000,
|
||||
"warmup_requests": 100,
|
||||
"duration_seconds_before": 13.546,
|
||||
"duration_seconds_after": 13.478,
|
||||
"successful_requests_before": 100000,
|
||||
"successful_requests_after": 100000,
|
||||
"failed_requests_before": 0,
|
||||
"failed_requests_after": 0,
|
||||
"rps_before": 7382.485,
|
||||
"rps_after": 7419.326,
|
||||
"p50_ms_before": 4.01,
|
||||
"p50_ms_after": 3.984,
|
||||
"p95_ms_before": 7.051,
|
||||
"p95_ms_after": 7.049,
|
||||
"p99_ms_before": 9.096,
|
||||
"p99_ms_after": 9.096,
|
||||
"rss_max_kib_before": 77792,
|
||||
"rss_max_kib_after": 70976
|
||||
},
|
||||
{
|
||||
"history": 50000,
|
||||
"concurrency": 1,
|
||||
"requested_requests": 100000,
|
||||
"warmup_requests": 100,
|
||||
"duration_seconds_before": 13.969,
|
||||
"duration_seconds_after": 13.863,
|
||||
"successful_requests_before": 100000,
|
||||
"successful_requests_after": 100000,
|
||||
"failed_requests_before": 0,
|
||||
"failed_requests_after": 0,
|
||||
"rps_before": 7158.653,
|
||||
"rps_after": 7213.61,
|
||||
"p50_ms_before": 0.13,
|
||||
"p50_ms_after": 0.129,
|
||||
"p95_ms_before": 0.149,
|
||||
"p95_ms_after": 0.145,
|
||||
"p99_ms_before": 0.211,
|
||||
"p99_ms_after": 0.191,
|
||||
"rss_max_kib_before": 81072,
|
||||
"rss_max_kib_after": 81824
|
||||
},
|
||||
{
|
||||
"history": 50000,
|
||||
"concurrency": 4,
|
||||
"requested_requests": 100000,
|
||||
"warmup_requests": 100,
|
||||
"duration_seconds_before": 11.014,
|
||||
"duration_seconds_after": 11.066,
|
||||
"successful_requests_before": 100000,
|
||||
"successful_requests_after": 100000,
|
||||
"failed_requests_before": 0,
|
||||
"failed_requests_after": 0,
|
||||
"rps_before": 9079.212,
|
||||
"rps_after": 9036.335,
|
||||
"p50_ms_before": 0.404,
|
||||
"p50_ms_after": 0.405,
|
||||
"p95_ms_before": 0.623,
|
||||
"p95_ms_after": 0.63,
|
||||
"p99_ms_before": 0.823,
|
||||
"p99_ms_after": 0.842,
|
||||
"rss_max_kib_before": 77088,
|
||||
"rss_max_kib_after": 86832
|
||||
},
|
||||
{
|
||||
"history": 50000,
|
||||
"concurrency": 16,
|
||||
"requested_requests": 100000,
|
||||
"warmup_requests": 100,
|
||||
"duration_seconds_before": 13.479,
|
||||
"duration_seconds_after": 13.416,
|
||||
"successful_requests_before": 100000,
|
||||
"successful_requests_after": 100000,
|
||||
"failed_requests_before": 0,
|
||||
"failed_requests_after": 0,
|
||||
"rps_before": 7419.068,
|
||||
"rps_after": 7453.53,
|
||||
"p50_ms_before": 1.99,
|
||||
"p50_ms_after": 1.978,
|
||||
"p95_ms_before": 3.471,
|
||||
"p95_ms_after": 3.455,
|
||||
"p99_ms_before": 4.694,
|
||||
"p99_ms_after": 4.688,
|
||||
"rss_max_kib_before": 79552,
|
||||
"rss_max_kib_after": 89824
|
||||
},
|
||||
{
|
||||
"history": 50000,
|
||||
"concurrency": 32,
|
||||
"requested_requests": 100000,
|
||||
"warmup_requests": 100,
|
||||
"duration_seconds_before": 13.464,
|
||||
"duration_seconds_after": 13.542,
|
||||
"successful_requests_before": 100000,
|
||||
"successful_requests_after": 100000,
|
||||
"failed_requests_before": 0,
|
||||
"failed_requests_after": 0,
|
||||
"rps_before": 7427.333,
|
||||
"rps_after": 7384.536,
|
||||
"p50_ms_before": 3.99,
|
||||
"p50_ms_after": 4.005,
|
||||
"p95_ms_before": 7.049,
|
||||
"p95_ms_after": 7.084,
|
||||
"p99_ms_before": 9.007,
|
||||
"p99_ms_after": 9.203,
|
||||
"rss_max_kib_before": 89552,
|
||||
"rss_max_kib_after": 80128
|
||||
}
|
||||
]
|
||||
@@ -0,0 +1,209 @@
|
||||
{
|
||||
"mode": "optimized",
|
||||
"command": [
|
||||
"go",
|
||||
"run",
|
||||
"./cmd/messenger"
|
||||
],
|
||||
"go_version": "go version go1.27.1 darwin/arm64",
|
||||
"os_arch": [
|
||||
"darwin",
|
||||
"arm64"
|
||||
],
|
||||
"requests_per_case": 100000,
|
||||
"rss_source": "ps RSS of go run child executable, KiB; sampled every 100 ms",
|
||||
"rows": [
|
||||
{
|
||||
"history": 1000,
|
||||
"concurrency": 1,
|
||||
"duration_seconds": 13.919,
|
||||
"requested_requests": 100000,
|
||||
"warmup_requests": 100,
|
||||
"successful_requests": 100000,
|
||||
"failed_requests": 0,
|
||||
"rps": 7184.594,
|
||||
"p50_ms": 0.129,
|
||||
"p95_ms": 0.15,
|
||||
"p99_ms": 0.231,
|
||||
"rss_min_kib": 23504,
|
||||
"rss_max_kib": 62048,
|
||||
"rss_delta_kib": 38544
|
||||
},
|
||||
{
|
||||
"history": 1000,
|
||||
"concurrency": 4,
|
||||
"duration_seconds": 11.115,
|
||||
"requested_requests": 100000,
|
||||
"warmup_requests": 100,
|
||||
"successful_requests": 100000,
|
||||
"failed_requests": 0,
|
||||
"rps": 8996.523,
|
||||
"p50_ms": 0.407,
|
||||
"p95_ms": 0.632,
|
||||
"p99_ms": 0.867,
|
||||
"rss_min_kib": 23744,
|
||||
"rss_max_kib": 61040,
|
||||
"rss_delta_kib": 37296
|
||||
},
|
||||
{
|
||||
"history": 1000,
|
||||
"concurrency": 16,
|
||||
"duration_seconds": 13.364,
|
||||
"requested_requests": 100000,
|
||||
"warmup_requests": 100,
|
||||
"successful_requests": 100000,
|
||||
"failed_requests": 0,
|
||||
"rps": 7482.719,
|
||||
"p50_ms": 1.977,
|
||||
"p95_ms": 3.445,
|
||||
"p99_ms": 4.577,
|
||||
"rss_min_kib": 22480,
|
||||
"rss_max_kib": 61328,
|
||||
"rss_delta_kib": 38848
|
||||
},
|
||||
{
|
||||
"history": 1000,
|
||||
"concurrency": 32,
|
||||
"duration_seconds": 13.547,
|
||||
"requested_requests": 100000,
|
||||
"warmup_requests": 100,
|
||||
"successful_requests": 100000,
|
||||
"failed_requests": 0,
|
||||
"rps": 7381.5,
|
||||
"p50_ms": 4.016,
|
||||
"p95_ms": 7.058,
|
||||
"p99_ms": 9.054,
|
||||
"rss_min_kib": 23152,
|
||||
"rss_max_kib": 68768,
|
||||
"rss_delta_kib": 45616
|
||||
},
|
||||
{
|
||||
"history": 10000,
|
||||
"concurrency": 1,
|
||||
"duration_seconds": 13.984,
|
||||
"requested_requests": 100000,
|
||||
"warmup_requests": 100,
|
||||
"successful_requests": 100000,
|
||||
"failed_requests": 0,
|
||||
"rps": 7150.931,
|
||||
"p50_ms": 0.131,
|
||||
"p95_ms": 0.146,
|
||||
"p99_ms": 0.187,
|
||||
"rss_min_kib": 25936,
|
||||
"rss_max_kib": 68128,
|
||||
"rss_delta_kib": 42192
|
||||
},
|
||||
{
|
||||
"history": 10000,
|
||||
"concurrency": 4,
|
||||
"duration_seconds": 11.046,
|
||||
"requested_requests": 100000,
|
||||
"warmup_requests": 100,
|
||||
"successful_requests": 100000,
|
||||
"failed_requests": 0,
|
||||
"rps": 9052.965,
|
||||
"p50_ms": 0.404,
|
||||
"p95_ms": 0.628,
|
||||
"p99_ms": 0.859,
|
||||
"rss_min_kib": 26448,
|
||||
"rss_max_kib": 71632,
|
||||
"rss_delta_kib": 45184
|
||||
},
|
||||
{
|
||||
"history": 10000,
|
||||
"concurrency": 16,
|
||||
"duration_seconds": 13.439,
|
||||
"requested_requests": 100000,
|
||||
"warmup_requests": 100,
|
||||
"successful_requests": 100000,
|
||||
"failed_requests": 0,
|
||||
"rps": 7440.817,
|
||||
"p50_ms": 1.989,
|
||||
"p95_ms": 3.468,
|
||||
"p99_ms": 4.701,
|
||||
"rss_min_kib": 26480,
|
||||
"rss_max_kib": 73712,
|
||||
"rss_delta_kib": 47232
|
||||
},
|
||||
{
|
||||
"history": 10000,
|
||||
"concurrency": 32,
|
||||
"duration_seconds": 13.478,
|
||||
"requested_requests": 100000,
|
||||
"warmup_requests": 100,
|
||||
"successful_requests": 100000,
|
||||
"failed_requests": 0,
|
||||
"rps": 7419.326,
|
||||
"p50_ms": 3.984,
|
||||
"p95_ms": 7.049,
|
||||
"p99_ms": 9.096,
|
||||
"rss_min_kib": 26176,
|
||||
"rss_max_kib": 70976,
|
||||
"rss_delta_kib": 44800
|
||||
},
|
||||
{
|
||||
"history": 50000,
|
||||
"concurrency": 1,
|
||||
"duration_seconds": 13.863,
|
||||
"requested_requests": 100000,
|
||||
"warmup_requests": 100,
|
||||
"successful_requests": 100000,
|
||||
"failed_requests": 0,
|
||||
"rps": 7213.61,
|
||||
"p50_ms": 0.129,
|
||||
"p95_ms": 0.145,
|
||||
"p99_ms": 0.191,
|
||||
"rss_min_kib": 40592,
|
||||
"rss_max_kib": 81824,
|
||||
"rss_delta_kib": 41232
|
||||
},
|
||||
{
|
||||
"history": 50000,
|
||||
"concurrency": 4,
|
||||
"duration_seconds": 11.066,
|
||||
"requested_requests": 100000,
|
||||
"warmup_requests": 100,
|
||||
"successful_requests": 100000,
|
||||
"failed_requests": 0,
|
||||
"rps": 9036.335,
|
||||
"p50_ms": 0.405,
|
||||
"p95_ms": 0.63,
|
||||
"p99_ms": 0.842,
|
||||
"rss_min_kib": 42944,
|
||||
"rss_max_kib": 86832,
|
||||
"rss_delta_kib": 43888
|
||||
},
|
||||
{
|
||||
"history": 50000,
|
||||
"concurrency": 16,
|
||||
"duration_seconds": 13.416,
|
||||
"requested_requests": 100000,
|
||||
"warmup_requests": 100,
|
||||
"successful_requests": 100000,
|
||||
"failed_requests": 0,
|
||||
"rps": 7453.53,
|
||||
"p50_ms": 1.978,
|
||||
"p95_ms": 3.455,
|
||||
"p99_ms": 4.688,
|
||||
"rss_min_kib": 40768,
|
||||
"rss_max_kib": 89824,
|
||||
"rss_delta_kib": 49056
|
||||
},
|
||||
{
|
||||
"history": 50000,
|
||||
"concurrency": 32,
|
||||
"duration_seconds": 13.542,
|
||||
"requested_requests": 100000,
|
||||
"warmup_requests": 100,
|
||||
"successful_requests": 100000,
|
||||
"failed_requests": 0,
|
||||
"rps": 7384.536,
|
||||
"p50_ms": 4.005,
|
||||
"p95_ms": 7.084,
|
||||
"p99_ms": 9.203,
|
||||
"rss_min_kib": 42848,
|
||||
"rss_max_kib": 80128,
|
||||
"rss_delta_kib": 37280
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
goos: darwin
|
||||
goarch: arm64
|
||||
pkg: mtusi-messenger/internal/storage/memory
|
||||
cpu: Apple M5 Pro
|
||||
BenchmarkMessageCreate/history=1000-18 4830075 243.3 ns/op 16 B/op 1 allocs/op
|
||||
BenchmarkMessageCreate/history=1000-18 4958697 241.4 ns/op 16 B/op 1 allocs/op
|
||||
BenchmarkMessageCreate/history=1000-18 4984602 241.8 ns/op 16 B/op 1 allocs/op
|
||||
BenchmarkMessageCreate/history=1000-18 4976372 241.8 ns/op 16 B/op 1 allocs/op
|
||||
BenchmarkMessageCreate/history=1000-18 4962843 241.7 ns/op 16 B/op 1 allocs/op
|
||||
BenchmarkMessageCreate/history=10000-18 4967149 241.8 ns/op 16 B/op 1 allocs/op
|
||||
BenchmarkMessageCreate/history=10000-18 4946976 242.1 ns/op 16 B/op 1 allocs/op
|
||||
BenchmarkMessageCreate/history=10000-18 4950400 242.3 ns/op 16 B/op 1 allocs/op
|
||||
BenchmarkMessageCreate/history=10000-18 4938321 242.4 ns/op 16 B/op 1 allocs/op
|
||||
BenchmarkMessageCreate/history=10000-18 4955269 242.2 ns/op 16 B/op 1 allocs/op
|
||||
BenchmarkMessageCreate/history=50000-18 4943572 242.0 ns/op 16 B/op 1 allocs/op
|
||||
BenchmarkMessageCreate/history=50000-18 4969927 242.4 ns/op 16 B/op 1 allocs/op
|
||||
BenchmarkMessageCreate/history=50000-18 4931466 242.5 ns/op 16 B/op 1 allocs/op
|
||||
BenchmarkMessageCreate/history=50000-18 4948990 242.8 ns/op 16 B/op 1 allocs/op
|
||||
BenchmarkMessageCreate/history=50000-18 4953249 242.6 ns/op 16 B/op 1 allocs/op
|
||||
PASS
|
||||
ok mtusi-messenger/internal/storage/memory 18.240s
|
||||
@@ -0,0 +1,128 @@
|
||||
[
|
||||
{
|
||||
"history": 100,
|
||||
"concurrency": 1,
|
||||
"duration_seconds": 2.002,
|
||||
"successful_requests": 531,
|
||||
"failed_requests": 0,
|
||||
"rps": 265.189,
|
||||
"p50_ms": 3.355,
|
||||
"p95_ms": 4.276,
|
||||
"p99_ms": 17.123,
|
||||
"rss_min_kib": 18800,
|
||||
"rss_max_kib": 22736,
|
||||
"rss_delta_kib": 3936
|
||||
},
|
||||
{
|
||||
"history": 100,
|
||||
"concurrency": 4,
|
||||
"duration_seconds": 2.005,
|
||||
"successful_requests": 1445,
|
||||
"failed_requests": 0,
|
||||
"rps": 720.55,
|
||||
"p50_ms": 4.197,
|
||||
"p95_ms": 16.868,
|
||||
"p99_ms": 21.043,
|
||||
"rss_min_kib": 20768,
|
||||
"rss_max_kib": 24128,
|
||||
"rss_delta_kib": 3360
|
||||
},
|
||||
{
|
||||
"history": 100,
|
||||
"concurrency": 16,
|
||||
"duration_seconds": 2.012,
|
||||
"successful_requests": 2265,
|
||||
"failed_requests": 0,
|
||||
"rps": 1125.923,
|
||||
"p50_ms": 8.851,
|
||||
"p95_ms": 29.142,
|
||||
"p99_ms": 91.221,
|
||||
"rss_min_kib": 20672,
|
||||
"rss_max_kib": 25216,
|
||||
"rss_delta_kib": 4544
|
||||
},
|
||||
{
|
||||
"history": 1000,
|
||||
"concurrency": 1,
|
||||
"duration_seconds": 2.011,
|
||||
"successful_requests": 478,
|
||||
"failed_requests": 0,
|
||||
"rps": 237.68,
|
||||
"p50_ms": 3.467,
|
||||
"p95_ms": 11.279,
|
||||
"p99_ms": 19.675,
|
||||
"rss_min_kib": 23264,
|
||||
"rss_max_kib": 23504,
|
||||
"rss_delta_kib": 240
|
||||
},
|
||||
{
|
||||
"history": 1000,
|
||||
"concurrency": 4,
|
||||
"duration_seconds": 2.004,
|
||||
"successful_requests": 1337,
|
||||
"failed_requests": 0,
|
||||
"rps": 667.05,
|
||||
"p50_ms": 4.249,
|
||||
"p95_ms": 17.243,
|
||||
"p99_ms": 29.938,
|
||||
"rss_min_kib": 23264,
|
||||
"rss_max_kib": 25280,
|
||||
"rss_delta_kib": 2016
|
||||
},
|
||||
{
|
||||
"history": 1000,
|
||||
"concurrency": 16,
|
||||
"duration_seconds": 2.005,
|
||||
"successful_requests": 2211,
|
||||
"failed_requests": 0,
|
||||
"rps": 1102.581,
|
||||
"p50_ms": 8.818,
|
||||
"p95_ms": 30.252,
|
||||
"p99_ms": 93.912,
|
||||
"rss_min_kib": 23424,
|
||||
"rss_max_kib": 25200,
|
||||
"rss_delta_kib": 1776
|
||||
},
|
||||
{
|
||||
"history": 5000,
|
||||
"concurrency": 1,
|
||||
"duration_seconds": 2.002,
|
||||
"successful_requests": 483,
|
||||
"failed_requests": 0,
|
||||
"rps": 241.241,
|
||||
"p50_ms": 3.466,
|
||||
"p95_ms": 10.897,
|
||||
"p99_ms": 18.681,
|
||||
"rss_min_kib": 25456,
|
||||
"rss_max_kib": 25456,
|
||||
"rss_delta_kib": 0
|
||||
},
|
||||
{
|
||||
"history": 5000,
|
||||
"concurrency": 4,
|
||||
"duration_seconds": 2.003,
|
||||
"successful_requests": 1374,
|
||||
"failed_requests": 0,
|
||||
"rps": 685.839,
|
||||
"p50_ms": 4.207,
|
||||
"p95_ms": 17.418,
|
||||
"p99_ms": 26.618,
|
||||
"rss_min_kib": 24304,
|
||||
"rss_max_kib": 25376,
|
||||
"rss_delta_kib": 1072
|
||||
},
|
||||
{
|
||||
"history": 5000,
|
||||
"concurrency": 16,
|
||||
"duration_seconds": 2.002,
|
||||
"successful_requests": 2162,
|
||||
"failed_requests": 0,
|
||||
"rps": 1079.866,
|
||||
"p50_ms": 8.939,
|
||||
"p95_ms": 31.525,
|
||||
"p99_ms": 94.709,
|
||||
"rss_min_kib": 24848,
|
||||
"rss_max_kib": 26640,
|
||||
"rss_delta_kib": 1792
|
||||
}
|
||||
]
|
||||
@@ -0,0 +1,31 @@
|
||||
# LB excludes a not-ready but reachable replica (lab3)
|
||||
# generated: 2026-10-16T14:02:26Z
|
||||
# lb: haproxy:3.2-alpine
|
||||
|
||||
## 1. baseline: requests through LB by replica
|
||||
18 52861386fddb
|
||||
22 8587b4251b72
|
||||
stats: api1=UP api2=UP api3=MAINT (resolution) api4=MAINT (resolution) api5=MAINT (resolution) api6=MAINT (resolution) api7=MAINT (resolution) api8=MAINT (resolution) BACKEND=UP
|
||||
|
||||
## 2. start a temporary TCP proxy to postgres and a candidate replica behind the same network alias
|
||||
instance-id: 9e9e905440d3, readiness while its database is reachable: 200
|
||||
load balancer slot for the candidate: api3, stats: api1=UP api2=UP api3=UP api4=MAINT (resolution) api5=MAINT (resolution) api6=MAINT (resolution) api7=MAINT (resolution) api8=MAINT (resolution) BACKEND=UP
|
||||
|
||||
## 3. cut the candidate's database access (stop only the TCP proxy)
|
||||
candidate is still running: running, readiness: 503
|
||||
waiting for the load balancer to mark api3 DOWN
|
||||
api3 went DOWN 2s after its database was cut (check: inter 2s fall 2)
|
||||
stats after failure: api1=UP api2=UP api3=DOWN api4=MAINT (resolution) api5=MAINT (resolution) api6=MAINT (resolution) api7=MAINT (resolution) api8=MAINT (resolution) BACKEND=UP
|
||||
|
||||
## 4. 40 requests through LB while the candidate is not ready
|
||||
18 52861386fddb
|
||||
22 8587b4251b72
|
||||
(the candidate must not appear above)
|
||||
|
||||
## 5. business writes through LB during the exclusion
|
||||
"failed_requests": 0,
|
||||
"error_ratio": 0.0,
|
||||
"successful_rps": 1163.529,
|
||||
|
||||
## 6. cleanup
|
||||
stats after cleanup: api1=UP api2=UP api3=MAINT (resolution) api4=MAINT (resolution) api5=MAINT (resolution) api6=MAINT (resolution) api7=MAINT (resolution) api8=MAINT (resolution) BACKEND=UP
|
||||
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"lab": 3,
|
||||
"workload": "closed-loop POST messages; no automatic retries",
|
||||
"requested_duration_seconds": 30.0,
|
||||
"elapsed_seconds": 30.031,
|
||||
"concurrency": 32,
|
||||
"successful_requests": 38549,
|
||||
"failed_requests": 0,
|
||||
"error_ratio": 0.0,
|
||||
"successful_rps": 1283.644,
|
||||
"successful_latency_ms": {
|
||||
"p50": 19.177,
|
||||
"p95": 52.823,
|
||||
"p99": 60.246
|
||||
},
|
||||
"note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead."
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
# контейнерный стенд через LB, 32 клиента, 30 с — 2026-10-16T14:26:39Z
|
||||
{
|
||||
"lab": 3,
|
||||
"workload": "closed-loop POST messages; no automatic retries",
|
||||
"requested_duration_seconds": 30.0,
|
||||
"elapsed_seconds": 30.031,
|
||||
"concurrency": 32,
|
||||
"successful_requests": 38549,
|
||||
"failed_requests": 0,
|
||||
"error_ratio": 0.0,
|
||||
"successful_rps": 1283.644,
|
||||
"successful_latency_ms": {
|
||||
"p50": 19.177,
|
||||
"p95": 52.823,
|
||||
"p99": 60.246
|
||||
},
|
||||
"note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead."
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
{
|
||||
"lab": 3,
|
||||
"workload": "closed-loop POST messages; failures counted, not raised",
|
||||
"requested_duration_seconds": 90.0,
|
||||
"elapsed_seconds": 90.033,
|
||||
"concurrency": 32,
|
||||
"successful_requests": 220781,
|
||||
"failed_requests": 0,
|
||||
"error_ratio": 0.0,
|
||||
"errors_by_kind": {},
|
||||
"successful_rps": 2452.222,
|
||||
"successful_latency_ms": {
|
||||
"p50": 12.541,
|
||||
"p95": 17.549,
|
||||
"p99": 22.396
|
||||
},
|
||||
"instances": {
|
||||
"Vladislavs-MacBook-Pro.local": 220781
|
||||
},
|
||||
"bootstrap_attempts": 1,
|
||||
"note": "Percentiles cover successful writes only; transitional errors are expected during a rolling update."
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
# нативный процесс вне Docker, 32 клиента, 90 с — 2026-10-16T14:26:39Z
|
||||
{
|
||||
"lab": 3,
|
||||
"workload": "closed-loop POST messages; failures counted, not raised",
|
||||
"requested_duration_seconds": 90.0,
|
||||
"elapsed_seconds": 90.033,
|
||||
"concurrency": 32,
|
||||
"successful_requests": 220781,
|
||||
"failed_requests": 0,
|
||||
"error_ratio": 0.0,
|
||||
"errors_by_kind": {},
|
||||
"successful_rps": 2452.222,
|
||||
"successful_latency_ms": {
|
||||
"p50": 12.541,
|
||||
"p95": 17.549,
|
||||
"p99": 22.396
|
||||
},
|
||||
"instances": {
|
||||
"Vladislavs-MacBook-Pro.local": 220781
|
||||
},
|
||||
"bootstrap_attempts": 1,
|
||||
"note": "Percentiles cover successful writes only; transitional errors are expected during a rolling update."
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
# Контроль пути «хост -> Colima VM -> LB»
|
||||
|
||||
Один и тот же генератор (`tests/load.py`), один и тот же профиль (закрытый цикл,
|
||||
8 клиентов, 15 с прогрева, 60 с замера) и один и тот же стенд. Меняется только
|
||||
место клиента: на хосте (через опубликованный порт) или в контейнере внутри VM
|
||||
(напрямую в балансировщик по docker-сети). Воспроизведение:
|
||||
`scripts/path_overhead_check.sh`.
|
||||
|
||||
| клиент | успешных | отказов | ошибки | RPS | p50, мс | p95, мс |
|
||||
| --- | --- | --- | --- | --- | --- | --- |
|
||||
| на хосте, `http://127.0.0.1:8080` | 92 378 | 32 575 | 26.1 % | 1 539 | 3.79 | 7.16 |
|
||||
| в VM, `http://lb` | 88 596 | **0** | 0 % | 1 475 | 5.29 | 8.42 |
|
||||
|
||||
## Что это показывает
|
||||
|
||||
1. **Пропускная способность одна и та же** (1 539 против 1 475, разница в пределах
|
||||
разброса; клиент в VM даже немного медленнее, потому что делит с стендом те же
|
||||
2 vCPU). Значит путь «хост -> проброс порта -> VM» **не задаёт потолок**: его
|
||||
исключение из маршрута ничего не прибавляет.
|
||||
2. **Отказы целиком клиентские.** Тот же стенд под той же нагрузкой не отказал ни
|
||||
разу для клиента внутри VM. При этом за прогон с 26 % клиентских отказов
|
||||
балансировщик отдал все запросы без 5xx (`hrsp_5xx=0` в статистике HAProxy), а
|
||||
в логах API нет ни одной записи уровня выше `info`.
|
||||
3. Причина — сам проброс порта: генератор ходит без keep-alive (новое TCP-соединение
|
||||
на запрос), и под шквалом соединений forwarder хоста начинает их отклонять.
|
||||
Наблюдения: в момент замера на хосте было **19 556 сокетов в `TIME_WAIT`** при
|
||||
диапазоне эфемерных портов 49 152-65 535 (16 384), а точечный пробник из 40 000
|
||||
быстрых подключений подряд получил 1 294 успеха и 38 706 `ECONNREFUSED`.
|
||||
4. Предел этой хрупкости тоже измерен: прогон на ~4 500 соединений/с по тривиальному
|
||||
`/health/live` дал 100 % отказов, после чего проброс порта (и доступ к Docker-эндпоинту
|
||||
Colima) перестал отвечать до `colima restart`. Стенд при этом не падал — недоступным
|
||||
был именно хостовый путь; серия трека 1 поэтому снимается клиентом внутри VM
|
||||
(`CLIENT=vm`), где отказов нет.
|
||||
|
||||
Клиент на хосте способен на большее: тот же закрытый цикл по тривиальному серверу,
|
||||
поднятому на самом хосте (без Docker), дал 4 469 RPS без отказов — то есть ~1 500 RPS
|
||||
не являются потолком генератора.
|
||||
|
||||
Артефакты: `outside.txt`, `inside.txt`, `load-outside.json`, `load-inside.json`,
|
||||
`summary.txt`.
|
||||
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"lab": 3,
|
||||
"workload": "closed-loop POST messages; no automatic retries",
|
||||
"requested_duration_seconds": 60.0,
|
||||
"elapsed_seconds": 60.073,
|
||||
"concurrency": 8,
|
||||
"successful_requests": 88596,
|
||||
"failed_requests": 0,
|
||||
"error_ratio": 0.0,
|
||||
"successful_rps": 1474.795,
|
||||
"successful_latency_ms": {
|
||||
"p50": 5.292,
|
||||
"p95": 8.415,
|
||||
"p99": 10.433
|
||||
},
|
||||
"note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead."
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"lab": 3,
|
||||
"workload": "closed-loop POST messages; no automatic retries",
|
||||
"requested_duration_seconds": 60.0,
|
||||
"elapsed_seconds": 60.073,
|
||||
"concurrency": 8,
|
||||
"successful_requests": 88596,
|
||||
"failed_requests": 0,
|
||||
"error_ratio": 0.0,
|
||||
"successful_rps": 1474.795,
|
||||
"successful_latency_ms": {
|
||||
"p50": 5.292,
|
||||
"p95": 8.415,
|
||||
"p99": 10.433
|
||||
},
|
||||
"note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead."
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"lab": 3,
|
||||
"workload": "closed-loop POST messages; no automatic retries",
|
||||
"requested_duration_seconds": 60.0,
|
||||
"elapsed_seconds": 60.026,
|
||||
"concurrency": 8,
|
||||
"successful_requests": 92378,
|
||||
"failed_requests": 32575,
|
||||
"error_ratio": 0.260698,
|
||||
"successful_rps": 1538.959,
|
||||
"successful_latency_ms": {
|
||||
"p50": 3.793,
|
||||
"p95": 7.159,
|
||||
"p99": 21.756
|
||||
},
|
||||
"note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead."
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"lab": 3,
|
||||
"workload": "closed-loop POST messages; no automatic retries",
|
||||
"requested_duration_seconds": 60.0,
|
||||
"elapsed_seconds": 60.026,
|
||||
"concurrency": 8,
|
||||
"successful_requests": 92378,
|
||||
"failed_requests": 32575,
|
||||
"error_ratio": 0.260698,
|
||||
"successful_rps": 1538.959,
|
||||
"successful_latency_ms": {
|
||||
"p50": 3.793,
|
||||
"p95": 7.159,
|
||||
"p99": 21.756
|
||||
},
|
||||
"note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead."
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
# Контроль пути к балансировщику
|
||||
# generated: 2026-10-16T18:17:21Z
|
||||
# profile: tests/load.py duration=60 concurrency=8 warmup=15
|
||||
# docker network: mtusi-messenger-lab3_default
|
||||
# клиент в VM: python:3.12-alpine
|
||||
|
||||
=== извне: клиент на хосте, http://127.0.0.1:8080 ===
|
||||
|
||||
=== изнутри: клиент в VM, http://lb ===
|
||||
@@ -0,0 +1,4 @@
|
||||
# make test-persistence — 2026-10-16T13:59:43Z
|
||||
env -u HTTP_PROXY -u HTTPS_PROXY -u ALL_PROXY -u http_proxy -u https_proxy -u all_proxy NO_PROXY=localhost,127.0.0.1,::1 no_proxy=localhost,127.0.0.1,::1 python3 tests/resilience.py --mode persistence --action-script "scripts/restart.sh" --base-url "http://localhost:8080"
|
||||
Executing explicit persistence hook; hook output suppressed to avoid leaking secrets.
|
||||
PASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence.
|
||||
@@ -0,0 +1,35 @@
|
||||
# quality checks — 2026-10-16T14:30:53Z
|
||||
python3 scripts/check_contract.py
|
||||
PASS: offline skeleton structure, local refs and Python syntax; application NOT tested.
|
||||
.venv/bin/python scripts/validate_openapi.py
|
||||
PASS: full OpenAPI 3.1 and JSON Schema validation; application NOT tested.
|
||||
env -u APP_ENV -u SERVER_HOST -u SERVER_PORT -u SERVER_READ_HEADER_TIMEOUT -u SERVER_SHUTDOWN_TIMEOUT -u LOG_LEVEL -u LOG_FORMAT -u POSTGRES_HOST -u POSTGRES_PORT -u POSTGRES_DATABASE -u POSTGRES_USER -u POSTGRES_PASSWORD -u POSTGRES_SSL_MODE -u POSTGRES_MAX_CONNS -u POSTGRES_MIN_CONNS -u POSTGRES_MAX_CONN_LIFETIME -u POSTGRES_MAX_CONN_IDLE_TIME -u POSTGRES_CONNECT_TIMEOUT -u POSTGRES_QUERY_TIMEOUT -u REDIS_ENABLED -u REDIS_HOST -u REDIS_PORT -u REDIS_PASSWORD -u REDIS_DB -u REDIS_MAX_RETRIES -u REDIS_DIAL_TIMEOUT -u REDIS_READ_TIMEOUT -u REDIS_WRITE_TIMEOUT -u REDIS_POOL_SIZE -u CACHE_ENABLED -u CACHE_CHAT_LIST_TTL -u CACHE_LOCK_TTL -u CACHE_LOCK_WAIT_TIMEOUT -u SESSION_TTL_SECONDS -u IDEMPOTENCY_TTL_SECONDS -u API_REPLICAS -u API_CPU_LIMIT -u API_MEM_LIMIT go test -race -shuffle=on -count=1 -timeout=5m ./...
|
||||
? mtusi-messenger/cmd/messenger [no test files]
|
||||
? mtusi-messenger/cmd/migrate [no test files]
|
||||
ok mtusi-messenger/internal/config 1.633s
|
||||
ok mtusi-messenger/internal/domain 1.222s
|
||||
ok mtusi-messenger/internal/health 1.397s
|
||||
ok mtusi-messenger/internal/logger 1.803s
|
||||
ok mtusi-messenger/internal/platform/cache 2.104s
|
||||
? mtusi-messenger/internal/platform/cache/mocks [no test files]
|
||||
ok mtusi-messenger/internal/platform/password 2.659s
|
||||
ok mtusi-messenger/internal/platform/token 2.147s
|
||||
ok mtusi-messenger/internal/service/chat 2.733s
|
||||
? mtusi-messenger/internal/service/chat/mocks [no test files]
|
||||
ok mtusi-messenger/internal/service/message 2.527s
|
||||
? mtusi-messenger/internal/service/message/mocks [no test files]
|
||||
ok mtusi-messenger/internal/service/session 3.204s
|
||||
? mtusi-messenger/internal/service/session/mocks [no test files]
|
||||
ok mtusi-messenger/internal/service/user 3.505s
|
||||
? mtusi-messenger/internal/service/user/mocks [no test files]
|
||||
ok mtusi-messenger/internal/storage/postgres 3.147s
|
||||
? mtusi-messenger/internal/storage/postgres/internal/sqlcgen [no test files]
|
||||
? mtusi-messenger/internal/storage/postgres/migrations [no test files]
|
||||
? mtusi-messenger/internal/storage/redis [no test files]
|
||||
? mtusi-messenger/internal/storage/redis/mocks [no test files]
|
||||
ok mtusi-messenger/internal/transport/rest 3.609s
|
||||
? mtusi-messenger/internal/transport/rest/internal/oas [no test files]
|
||||
? mtusi-messenger/internal/transport/rest/mocks [no test files]
|
||||
go test -tags=integration -p 1 -count=1 -timeout=15m ./internal/storage/postgres ./internal/storage/redis
|
||||
ok mtusi-messenger/internal/storage/postgres 7.210s
|
||||
ok mtusi-messenger/internal/storage/redis 1.192s
|
||||
@@ -0,0 +1,33 @@
|
||||
# Что означает CPU% в `docker stats` на этом стенде
|
||||
|
||||
Колонка `cpu_percent` в `stats-*.csv` снимается через `docker stats`. Чтобы не
|
||||
толковать её наугад, поведение проверено прямым экспериментом на том же Docker-host
|
||||
(Colima, 2 vCPU).
|
||||
|
||||
```sh
|
||||
docker run -d --name lab3-quota-probe --cpus 0.5 alpine:3.20 sh -c 'while :; do :; done'
|
||||
sleep 12
|
||||
docker stats --no-stream --format '{{.Name}} CPU={{.CPUPerc}}' lab3-quota-probe
|
||||
docker exec lab3-quota-probe cat /sys/fs/cgroup/cpu.max
|
||||
```
|
||||
|
||||
```
|
||||
lab3-quota-probe CPU=49.49% MEM=344KiB / 1.913GiB
|
||||
50000 100000
|
||||
```
|
||||
|
||||
Контейнер упёрт в свою квоту (`cpu.max = 50000 100000` — это 0.5 CPU) и показывает
|
||||
**49.49 %**. Значит в этом окружении `docker stats` печатает процент от **одного
|
||||
ядра**: 100 % = 1 ядро, квота 0.5 CPU = ~50 %, квота 0.25 = ~25 %.
|
||||
|
||||
Как это читать в артефактах:
|
||||
|
||||
| сервис | квота | наблюдение в профилях | вывод |
|
||||
| --- | --- | --- | --- |
|
||||
| `postgres` | 0.50 | 45-50.5 % | 0.45-0.5 ядра, то есть **у самой квоты** |
|
||||
| `api` (2 реплики) | 0.50 каждая | ~20 % каждая | 0.2 ядра, квота не выбрана |
|
||||
| `lb` | 0.25 | 11-14 % | 0.11-0.14 ядра, квота не выбрана |
|
||||
|
||||
Отсюда же следует, что разница между профилем `r2` (PostgreSQL 0.50) и `db1cpu`
|
||||
(PostgreSQL 1.00) читается корректно: в `db1cpu` загрузка БД падала до ~46 %, то есть
|
||||
удвоенная квота не была использована — БД не была зажата квотой.
|
||||
@@ -0,0 +1,26 @@
|
||||
{
|
||||
"lab": 3,
|
||||
"workload": "closed-loop POST messages; failures counted, not raised",
|
||||
"requested_duration_seconds": 60.0,
|
||||
"elapsed_seconds": 60.013,
|
||||
"concurrency": 8,
|
||||
"successful_requests": 97359,
|
||||
"failed_requests": 3,
|
||||
"error_ratio": 3.1e-05,
|
||||
"errors_by_kind": {
|
||||
"http_error": 3
|
||||
},
|
||||
"successful_rps": 1622.308,
|
||||
"successful_latency_ms": {
|
||||
"p50": 4.011,
|
||||
"p95": 8.688,
|
||||
"p99": 23.718
|
||||
},
|
||||
"instances": {
|
||||
"f00a99f95855": 594,
|
||||
"8782633d0431": 48162,
|
||||
"4248067e3f04": 48603
|
||||
},
|
||||
"bootstrap_attempts": 1,
|
||||
"note": "Percentiles cover successful writes only; transitional errors are expected during a rolling update."
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
{
|
||||
"lab": 3,
|
||||
"workload": "closed-loop POST messages; failures counted, not raised",
|
||||
"requested_duration_seconds": 60.0,
|
||||
"elapsed_seconds": 60.013,
|
||||
"concurrency": 8,
|
||||
"successful_requests": 97359,
|
||||
"failed_requests": 3,
|
||||
"error_ratio": 3.1e-05,
|
||||
"errors_by_kind": {
|
||||
"http_error": 3
|
||||
},
|
||||
"successful_rps": 1622.308,
|
||||
"successful_latency_ms": {
|
||||
"p50": 4.011,
|
||||
"p95": 8.688,
|
||||
"p99": 23.718
|
||||
},
|
||||
"instances": {
|
||||
"f00a99f95855": 594,
|
||||
"8782633d0431": 48162,
|
||||
"4248067e3f04": 48603
|
||||
},
|
||||
"bootstrap_attempts": 1,
|
||||
"note": "Percentiles cover successful writes only; transitional errors are expected during a rolling update."
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
# Rolling update under load (surge, one replica at a time)
|
||||
# generated: 2026-10-16T14:26:39Z
|
||||
# load: tolerant loader, duration=60s concurrency=8
|
||||
# проверки готовности LB: httpchk /health/ready, inter 2s fall 2 rise 2, timeout check 1s
|
||||
|
||||
time="2026-10-16T17:26:40+03:00" level=warning msg="buildx Docker CLI plugin not found: falling back to the classic builder. BuildKit-only build features (multi-arch, secrets, ssh, additional contexts, ...) will not be available"
|
||||
Image mtusi-messenger:lab3 Building
|
||||
Image mtusi-messenger:lab3 Building
|
||||
Sending build context to Docker daemon 238kB␍
|
||||
Step 1/25 : ARG GO_VERSION=1.27.1
|
||||
Step 2/25 : ARG ALPINE_VERSION=3.22
|
||||
Step 3/25 : FROM golang:${GO_VERSION}-alpine AS build
|
||||
---> 8a5910f31396
|
||||
Step 4/25 : ARG TARGETOS
|
||||
---> Using cache
|
||||
---> d5f2c47ea7a5
|
||||
Step 5/25 : ARG TARGETARCH
|
||||
---> Using cache
|
||||
---> 047ee34b445c
|
||||
Step 6/25 : ARG VERSION=dev
|
||||
---> Using cache
|
||||
---> a529d045efeb
|
||||
Step 7/25 : ENV GOTOOLCHAIN=local
|
||||
---> Using cache
|
||||
---> 428f1b16b5c5
|
||||
Step 8/25 : WORKDIR /opt
|
||||
---> Using cache
|
||||
---> f37febf8b423
|
||||
Step 9/25 : COPY go.mod go.sum ./
|
||||
---> Using cache
|
||||
---> c4015f597b99
|
||||
Step 10/25 : RUN go mod download
|
||||
---> Using cache
|
||||
---> 34ef6a6167b0
|
||||
Step 11/25 : ARG GOFLAGS="-p=2"
|
||||
---> Using cache
|
||||
---> deb54a0ce57a
|
||||
Step 12/25 : ENV GOFLAGS=$GOFLAGS
|
||||
---> Using cache
|
||||
---> 3da36569422d
|
||||
Step 13/25 : COPY . .
|
||||
---> 198f052f6cce
|
||||
Step 14/25 : RUN CGO_ENABLED=0 GOOS=${TARGETOS} GOARCH=${TARGETARCH} go build -trimpath -buildvcs=false -tags timetzdata -ldflags="-s -w -X main.version=${VERSION}" -o /out/messenger ./cmd/messenger && CGO_ENABLED=0 GOOS=${TARGETOS} GOARCH=${TARGETARCH} go build -trimpath -buildvcs=false -tags timetzdata -ldflags="-s -w -X main.version=${VERSION}" -o /out/migrate ./cmd/migrate
|
||||
---> Running in 658437823eb9
|
||||
---> Removed intermediate container 658437823eb9
|
||||
---> 10a89d0bb592
|
||||
Step 15/25 : FROM alpine:${ALPINE_VERSION} AS runtime
|
||||
---> 5291449c3df7
|
||||
Step 16/25 : RUN apk add --no-cache ca-certificates wget && addgroup -S -g 10001 app && adduser -S -D -H -u 10001 -G app app
|
||||
---> Using cache
|
||||
---> f47b074d9bd5
|
||||
Step 17/25 : COPY --from=build --chown=10001:10001 /out/messenger /usr/local/bin/messenger
|
||||
---> Using cache
|
||||
---> 703f8f10d2cc
|
||||
Step 18/25 : COPY --from=build --chown=10001:10001 /out/migrate /usr/local/bin/migrate
|
||||
---> Using cache
|
||||
---> c9121622dae2
|
||||
Step 19/25 : COPY --chown=10001:10001 config/dev/config.yaml /etc/messenger/dev/config.yaml
|
||||
---> Using cache
|
||||
---> 0379076307ea
|
||||
Step 20/25 : USER 10001:10001
|
||||
---> Using cache
|
||||
---> 2ff943b7d2e0
|
||||
Step 21/25 : EXPOSE 8080
|
||||
---> Using cache
|
||||
---> 01674ab574a6
|
||||
Step 22/25 : STOPSIGNAL SIGTERM
|
||||
---> Using cache
|
||||
---> 6c30af2a102c
|
||||
Step 23/25 : HEALTHCHECK --interval=10s --timeout=3s --start-period=5s --retries=3 CMD wget -q -O /dev/null "http://127.0.0.1:${SERVER_PORT:-8080}/health/live" || exit 1
|
||||
---> Using cache
|
||||
---> 76379f8db08d
|
||||
Step 24/25 : ENTRYPOINT ["/usr/local/bin/messenger"]
|
||||
---> Using cache
|
||||
---> 778babec5020
|
||||
Step 25/25 : LABEL com.docker.compose.image.builder=classic
|
||||
---> Using cache
|
||||
---> 9e7e0224c87c
|
||||
Successfully built 9e7e0224c87c
|
||||
Successfully tagged mtusi-messenger:lab3
|
||||
Image mtusi-messenger:lab3 Built
|
||||
Image mtusi-messenger:lab3 Built
|
||||
реплик до обновления: 2
|
||||
образ старых реплик: sha256:9e7e0224c87cee0ccfa05d5799ec8e2a84b836e51fbda6f1dc3d175d5c0d4640
|
||||
образ новой ревизии: sha256:9e7e0224c87cee0ccfa05d5799ec8e2a84b836e51fbda6f1dc3d175d5c0d4640
|
||||
ревизия меняется: нет (образ не изменился)
|
||||
слотов UP до: 3; restarts до: mtusi-messenger-lab3-api-1=0 mtusi-messenger-lab3-api-2=0
|
||||
|
||||
step 1: lb-rollout-1 обслуживает (образ 9e7e0224c87cee0ccfa05d5799ec8e2a84b836e51fbda6f1dc3d175d5c0d4640, instance 8782633d0431), старый контейнер 2ed432da6dd1 (2ed432da6dd1) снят; UP-слотов 3; 5xx накоплено 416; старт шага 2026-10-16T14:27:22Z
|
||||
step 2: lb-rollout-2 обслуживает (образ 9e7e0224c87cee0ccfa05d5799ec8e2a84b836e51fbda6f1dc3d175d5c0d4640, instance 4248067e3f04), старый контейнер f00a99f95855 (f00a99f95855) снят; UP-слотов 4; 5xx накоплено 419; старт шага 2026-10-16T14:27:22Z
|
||||
|
||||
load summary (tolerant generator):
|
||||
{
|
||||
"lab": 3,
|
||||
"workload": "closed-loop POST messages; failures counted, not raised",
|
||||
"requested_duration_seconds": 60.0,
|
||||
"elapsed_seconds": 60.013,
|
||||
"concurrency": 8,
|
||||
"successful_requests": 97359,
|
||||
"failed_requests": 3,
|
||||
"error_ratio": 3.1e-05,
|
||||
"errors_by_kind": {
|
||||
"http_error": 3
|
||||
},
|
||||
"successful_rps": 1622.308,
|
||||
"successful_latency_ms": {
|
||||
"p50": 4.011,
|
||||
"p95": 8.688,
|
||||
"p99": 23.718
|
||||
},
|
||||
"instances": {
|
||||
"f00a99f95855": 594,
|
||||
"8782633d0431": 48162,
|
||||
"4248067e3f04": 48603
|
||||
},
|
||||
"bootstrap_attempts": 1,
|
||||
"note": "Percentiles cover successful writes only; transitional errors are expected during a rolling update."
|
||||
}
|
||||
|
||||
5xx от LB за время обновления (hrsp_5xx frontend): 3
|
||||
restarts после: lb-rollout-2=0 lb-rollout-1=0
|
||||
|
||||
возврат стенда под управление compose:
|
||||
Container mtusi-messenger-lab3-api-2 Creating
|
||||
Container mtusi-messenger-lab3-api-1 Creating
|
||||
Container mtusi-messenger-lab3-api-1 Created
|
||||
Container mtusi-messenger-lab3-api-2 Created
|
||||
Container mtusi-messenger-lab3-api-1 Starting
|
||||
Container mtusi-messenger-lab3-api-1 Started
|
||||
Container mtusi-messenger-lab3-api-2 Starting
|
||||
Container mtusi-messenger-lab3-api-2 Started
|
||||
снято временных контейнеров наплыва: проверено
|
||||
UP-слотов после: 3; restarts в конце: mtusi-messenger-lab3-api-1=0 mtusi-messenger-lab3-api-2=0
|
||||
API containers после обновления:
|
||||
mtusi-messenger-lab3-api-1 Up Less than a second (health: starting)
|
||||
mtusi-messenger-lab3-api-2 Up Less than a second (health: starting)
|
||||
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"lab": 3,
|
||||
"workload": "closed-loop POST messages; failures counted, not raised",
|
||||
"requested_duration_seconds": 45.0,
|
||||
"elapsed_seconds": 45.014,
|
||||
"concurrency": 8,
|
||||
"successful_requests": 89560,
|
||||
"failed_requests": 0,
|
||||
"error_ratio": 0.0,
|
||||
"errors_by_kind": {},
|
||||
"successful_rps": 1989.584,
|
||||
"successful_latency_ms": {
|
||||
"p50": 3.905,
|
||||
"p95": 6.02,
|
||||
"p99": 7.984
|
||||
},
|
||||
"instances": {
|
||||
"388ebcb74200": 7524,
|
||||
"73d07d7d76db": 45354,
|
||||
"cc6274635bd6": 36682
|
||||
},
|
||||
"note": "Percentiles cover successful writes only; transitional errors are expected during a rolling update."
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"lab": 3,
|
||||
"workload": "closed-loop POST messages; failures counted, not raised",
|
||||
"requested_duration_seconds": 45.0,
|
||||
"elapsed_seconds": 45.014,
|
||||
"concurrency": 8,
|
||||
"successful_requests": 89560,
|
||||
"failed_requests": 0,
|
||||
"error_ratio": 0.0,
|
||||
"errors_by_kind": {},
|
||||
"successful_rps": 1989.584,
|
||||
"successful_latency_ms": {
|
||||
"p50": 3.905,
|
||||
"p95": 6.02,
|
||||
"p99": 7.984
|
||||
},
|
||||
"instances": {
|
||||
"388ebcb74200": 7524,
|
||||
"73d07d7d76db": 45354,
|
||||
"cc6274635bd6": 36682
|
||||
},
|
||||
"note": "Percentiles cover successful writes only; transitional errors are expected during a rolling update."
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
# Rolling update under load
|
||||
# generated: 2026-10-15T19:03:13Z
|
||||
# load: tests/load.py duration=45s concurrency=8 (closed loop)
|
||||
# steps: delete one replica, recreate it from the freshly built image, wait for health + LB
|
||||
|
||||
time="2026-10-15T22:03:13+03:00" level=warning msg="buildx Docker CLI plugin not found: falling back to the classic builder. BuildKit-only build features (multi-arch, secrets, ssh, additional contexts, ...) will not be available"
|
||||
Image mtusi-messenger:lab3 Building
|
||||
Image mtusi-messenger:lab3 Building
|
||||
Sending build context to Docker daemon 213.7kB␍
|
||||
Step 1/25 : ARG GO_VERSION=1.27.1
|
||||
Step 2/25 : ARG ALPINE_VERSION=3.22
|
||||
Step 3/25 : FROM golang:${GO_VERSION}-alpine AS build
|
||||
---> 8a5910f31396
|
||||
Step 4/25 : ARG TARGETOS
|
||||
---> Using cache
|
||||
---> d5f2c47ea7a5
|
||||
Step 5/25 : ARG TARGETARCH
|
||||
---> Using cache
|
||||
---> 047ee34b445c
|
||||
Step 6/25 : ARG VERSION=dev
|
||||
---> Using cache
|
||||
---> a529d045efeb
|
||||
Step 7/25 : ENV GOTOOLCHAIN=local
|
||||
---> Using cache
|
||||
---> 428f1b16b5c5
|
||||
Step 8/25 : WORKDIR /opt
|
||||
---> Using cache
|
||||
---> f37febf8b423
|
||||
Step 9/25 : COPY go.mod go.sum ./
|
||||
---> Using cache
|
||||
---> c4015f597b99
|
||||
Step 10/25 : RUN go mod download
|
||||
---> Using cache
|
||||
---> 34ef6a6167b0
|
||||
Step 11/25 : ARG GOFLAGS="-p=2"
|
||||
---> Using cache
|
||||
---> deb54a0ce57a
|
||||
Step 12/25 : ENV GOFLAGS=$GOFLAGS
|
||||
---> Using cache
|
||||
---> 3da36569422d
|
||||
Step 13/25 : COPY . .
|
||||
---> Using cache
|
||||
---> 596dc1ab02d1
|
||||
Step 14/25 : RUN CGO_ENABLED=0 GOOS=${TARGETOS} GOARCH=${TARGETARCH} go build -trimpath -buildvcs=false -tags timetzdata -ldflags="-s -w -X main.version=${VERSION}" -o /out/messenger ./cmd/messenger && CGO_ENABLED=0 GOOS=${TARGETOS} GOARCH=${TARGETARCH} go build -trimpath -buildvcs=false -tags timetzdata -ldflags="-s -w -X main.version=${VERSION}" -o /out/migrate ./cmd/migrate
|
||||
---> Using cache
|
||||
---> 01aa8bc6200d
|
||||
Step 15/25 : FROM alpine:${ALPINE_VERSION} AS runtime
|
||||
---> 5291449c3df7
|
||||
Step 16/25 : RUN apk add --no-cache ca-certificates wget && addgroup -S -g 10001 app && adduser -S -D -H -u 10001 -G app app
|
||||
---> Using cache
|
||||
---> f47b074d9bd5
|
||||
Step 17/25 : COPY --from=build --chown=10001:10001 /out/messenger /usr/local/bin/messenger
|
||||
---> Using cache
|
||||
---> 50fc6abe3b04
|
||||
Step 18/25 : COPY --from=build --chown=10001:10001 /out/migrate /usr/local/bin/migrate
|
||||
---> Using cache
|
||||
---> 9bf6afe0256d
|
||||
Step 19/25 : COPY --chown=10001:10001 config/dev/config.yaml /etc/messenger/dev/config.yaml
|
||||
---> Using cache
|
||||
---> 0d1870a325ec
|
||||
Step 20/25 : USER 10001:10001
|
||||
---> Using cache
|
||||
---> 1991f2ae06cc
|
||||
Step 21/25 : EXPOSE 8080
|
||||
---> Using cache
|
||||
---> 762d1bfb7606
|
||||
Step 22/25 : STOPSIGNAL SIGTERM
|
||||
---> Using cache
|
||||
---> 8a9d8f4f7101
|
||||
Step 23/25 : HEALTHCHECK --interval=10s --timeout=3s --start-period=5s --retries=3 CMD wget -q -O /dev/null "http://127.0.0.1:${SERVER_PORT:-8080}/health/live" || exit 1
|
||||
---> Using cache
|
||||
---> 65dea502a3f3
|
||||
Step 24/25 : ENTRYPOINT ["/usr/local/bin/messenger"]
|
||||
---> Using cache
|
||||
---> 83bbee72905e
|
||||
Step 25/25 : LABEL com.docker.compose.image.builder=classic
|
||||
---> Using cache
|
||||
---> 037f969d5ea1
|
||||
Successfully built 037f969d5ea1
|
||||
Successfully tagged mtusi-messenger:lab3
|
||||
Image mtusi-messenger:lab3 Built
|
||||
Image mtusi-messenger:lab3 Built
|
||||
Container mtusi-messenger-lab3-api-13 Recreate
|
||||
Container mtusi-messenger-lab3-api-14 Recreate
|
||||
Container mtusi-messenger-lab3-api-13 Recreated
|
||||
Container mtusi-messenger-lab3-api-14 Recreated
|
||||
Container mtusi-messenger-lab3-api-14 Starting
|
||||
Container mtusi-messenger-lab3-api-14 Started
|
||||
Container mtusi-messenger-lab3-api-13 Starting
|
||||
Container mtusi-messenger-lab3-api-13 Started
|
||||
replicas before: 2; instances seen through LB: 2
|
||||
Container mtusi-messenger-lab3-api-13 Running
|
||||
Container mtusi-messenger-lab3-api-14 Creating
|
||||
Container mtusi-messenger-lab3-api-14 Created
|
||||
Container mtusi-messenger-lab3-api-14 Starting
|
||||
Container mtusi-messenger-lab3-api-14 Started
|
||||
step 1: removed 54a7e7888b5f at 2026-10-15T19:03:20Z, 2 healthy replicas served again at 2026-10-15T19:03:26Z
|
||||
Container mtusi-messenger-lab3-api-14 Running
|
||||
Container mtusi-messenger-lab3-api-15 Creating
|
||||
Container mtusi-messenger-lab3-api-15 Created
|
||||
Container mtusi-messenger-lab3-api-15 Starting
|
||||
Container mtusi-messenger-lab3-api-15 Started
|
||||
step 2: removed 388ebcb74200 at 2026-10-15T19:03:26Z, 2 healthy replicas served again at 2026-10-15T19:03:31Z
|
||||
|
||||
load summary (tolerant generator):
|
||||
{
|
||||
"lab": 3,
|
||||
"workload": "closed-loop POST messages; failures counted, not raised",
|
||||
"requested_duration_seconds": 45.0,
|
||||
"elapsed_seconds": 45.014,
|
||||
"concurrency": 8,
|
||||
"successful_requests": 89560,
|
||||
"failed_requests": 0,
|
||||
"error_ratio": 0.0,
|
||||
"errors_by_kind": {},
|
||||
"successful_rps": 1989.584,
|
||||
"successful_latency_ms": {
|
||||
"p50": 3.905,
|
||||
"p95": 6.02,
|
||||
"p99": 7.984
|
||||
},
|
||||
"instances": {
|
||||
"388ebcb74200": 7524,
|
||||
"73d07d7d76db": 45354,
|
||||
"cc6274635bd6": 36682
|
||||
},
|
||||
"note": "Percentiles cover successful writes only; transitional errors are expected during a rolling update."
|
||||
}
|
||||
|
||||
LB responses with 5xx during the update: 0
|
||||
|
||||
API containers after the update:
|
||||
mtusi-messenger-lab3-api-15 Up 41 seconds (healthy)
|
||||
mtusi-messenger-lab3-api-14 Up 46 seconds (healthy)
|
||||
@@ -0,0 +1,3 @@
|
||||
# make test — 2026-10-16T14:07:37Z (final image)
|
||||
env -u HTTP_PROXY -u HTTPS_PROXY -u ALL_PROXY -u http_proxy -u https_proxy -u all_proxy NO_PROXY=localhost,127.0.0.1,::1 no_proxy=localhost,127.0.0.1,::1 python3 tests/smoke.py --base-url "http://localhost:8080"
|
||||
PASS: lab3 public API scenario; infrastructure and grading evidence remain separate.
|
||||
@@ -0,0 +1,34 @@
|
||||
# Lab3 stand evidence
|
||||
# generated: 2026-10-16T13:38:19Z
|
||||
|
||||
## docker ps (ports)
|
||||
mtusi-messenger-lab3-api-6 | 8080/tcp
|
||||
mtusi-messenger-lab3-api-5 | 8080/tcp
|
||||
mtusi-messenger-lab3-lb-1 | 127.0.0.1:8404->8404/tcp, 127.0.0.1:8080->80/tcp
|
||||
mtusi-messenger-lab3-postgres-1 | 5432/tcp
|
||||
mtusi-messenger-lab3-redis-1 | 6379/tcp
|
||||
|
||||
## compose config: limits/replicas/published
|
||||
api:
|
||||
replicas: 2
|
||||
cpus: 0.5
|
||||
memory: "268435456"
|
||||
lb:
|
||||
cpus: 0.25
|
||||
memory: "67108864"
|
||||
published: "8080"
|
||||
published: "8404"
|
||||
migrate:
|
||||
cpus: 0.5
|
||||
memory: "268435456"
|
||||
postgres:
|
||||
cpus: 0.5
|
||||
memory: "402653184"
|
||||
redis:
|
||||
cpus: 0.25
|
||||
memory: "201326592"
|
||||
default:
|
||||
build:
|
||||
image: mtusi-messenger:lab3
|
||||
|
||||
container_name: absent
|
||||
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"lab": 3,
|
||||
"workload": "closed-loop POST messages; no automatic retries",
|
||||
"requested_duration_seconds": 60.0,
|
||||
"elapsed_seconds": 60.082,
|
||||
"concurrency": 8,
|
||||
"successful_requests": 83581,
|
||||
"failed_requests": 0,
|
||||
"error_ratio": 0.0,
|
||||
"successful_rps": 1391.108,
|
||||
"successful_latency_ms": {
|
||||
"p50": 5.571,
|
||||
"p95": 9.03,
|
||||
"p99": 11.692
|
||||
},
|
||||
"note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead."
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"lab": 3,
|
||||
"workload": "closed-loop POST messages; no automatic retries",
|
||||
"requested_duration_seconds": 60.0,
|
||||
"elapsed_seconds": 60.072,
|
||||
"concurrency": 8,
|
||||
"successful_requests": 83599,
|
||||
"failed_requests": 0,
|
||||
"error_ratio": 0.0,
|
||||
"successful_rps": 1391.647,
|
||||
"successful_latency_ms": {
|
||||
"p50": 5.575,
|
||||
"p95": 8.994,
|
||||
"p99": 11.512
|
||||
},
|
||||
"note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead."
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"lab": 3,
|
||||
"workload": "closed-loop POST messages; no automatic retries",
|
||||
"requested_duration_seconds": 60.0,
|
||||
"elapsed_seconds": 60.078,
|
||||
"concurrency": 8,
|
||||
"successful_requests": 81711,
|
||||
"failed_requests": 0,
|
||||
"error_ratio": 0.0,
|
||||
"successful_rps": 1360.087,
|
||||
"successful_latency_ms": {
|
||||
"p50": 5.664,
|
||||
"p95": 9.482,
|
||||
"p99": 12.322
|
||||
},
|
||||
"note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead."
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"lab": 3,
|
||||
"workload": "closed-loop POST messages; no automatic retries",
|
||||
"requested_duration_seconds": 60.0,
|
||||
"elapsed_seconds": 60.074,
|
||||
"concurrency": 8,
|
||||
"successful_requests": 81688,
|
||||
"failed_requests": 0,
|
||||
"error_ratio": 0.0,
|
||||
"successful_rps": 1359.794,
|
||||
"successful_latency_ms": {
|
||||
"p50": 5.688,
|
||||
"p95": 9.37,
|
||||
"p99": 12.032
|
||||
},
|
||||
"note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead."
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"lab": 3,
|
||||
"workload": "closed-loop POST messages; no automatic retries",
|
||||
"requested_duration_seconds": 60.0,
|
||||
"elapsed_seconds": 60.068,
|
||||
"concurrency": 8,
|
||||
"successful_requests": 83445,
|
||||
"failed_requests": 0,
|
||||
"error_ratio": 0.0,
|
||||
"successful_rps": 1389.179,
|
||||
"successful_latency_ms": {
|
||||
"p50": 5.585,
|
||||
"p95": 9.054,
|
||||
"p99": 11.711
|
||||
},
|
||||
"note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead."
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"lab": 3,
|
||||
"workload": "closed-loop POST messages; no automatic retries",
|
||||
"requested_duration_seconds": 60.0,
|
||||
"elapsed_seconds": 60.077,
|
||||
"concurrency": 8,
|
||||
"successful_requests": 76301,
|
||||
"failed_requests": 0,
|
||||
"error_ratio": 0.0,
|
||||
"successful_rps": 1270.045,
|
||||
"successful_latency_ms": {
|
||||
"p50": 6.057,
|
||||
"p95": 10.141,
|
||||
"p99": 13.724
|
||||
},
|
||||
"note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead."
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"lab": 3,
|
||||
"workload": "closed-loop POST messages; no automatic retries",
|
||||
"requested_duration_seconds": 60.0,
|
||||
"elapsed_seconds": 60.064,
|
||||
"concurrency": 8,
|
||||
"successful_requests": 89486,
|
||||
"failed_requests": 0,
|
||||
"error_ratio": 0.0,
|
||||
"successful_rps": 1489.856,
|
||||
"successful_latency_ms": {
|
||||
"p50": 5.238,
|
||||
"p95": 8.245,
|
||||
"p99": 10.54
|
||||
},
|
||||
"note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead."
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"lab": 3,
|
||||
"workload": "closed-loop POST messages; no automatic retries",
|
||||
"requested_duration_seconds": 60.0,
|
||||
"elapsed_seconds": 60.071,
|
||||
"concurrency": 8,
|
||||
"successful_requests": 89886,
|
||||
"failed_requests": 0,
|
||||
"error_ratio": 0.0,
|
||||
"successful_rps": 1496.325,
|
||||
"successful_latency_ms": {
|
||||
"p50": 5.207,
|
||||
"p95": 8.221,
|
||||
"p99": 10.508
|
||||
},
|
||||
"note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead."
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"lab": 3,
|
||||
"workload": "closed-loop POST messages; no automatic retries",
|
||||
"requested_duration_seconds": 60.0,
|
||||
"elapsed_seconds": 60.061,
|
||||
"concurrency": 8,
|
||||
"successful_requests": 89566,
|
||||
"failed_requests": 0,
|
||||
"error_ratio": 0.0,
|
||||
"successful_rps": 1491.252,
|
||||
"successful_latency_ms": {
|
||||
"p50": 5.251,
|
||||
"p95": 8.176,
|
||||
"p99": 10.209
|
||||
},
|
||||
"note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead."
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"lab": 3,
|
||||
"workload": "closed-loop POST messages; no automatic retries",
|
||||
"requested_duration_seconds": 60.0,
|
||||
"elapsed_seconds": 60.071,
|
||||
"concurrency": 8,
|
||||
"successful_requests": 82138,
|
||||
"failed_requests": 0,
|
||||
"error_ratio": 0.0,
|
||||
"successful_rps": 1367.357,
|
||||
"successful_latency_ms": {
|
||||
"p50": 5.67,
|
||||
"p95": 9.26,
|
||||
"p99": 12.055
|
||||
},
|
||||
"note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead."
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"lab": 3,
|
||||
"workload": "closed-loop POST messages; no automatic retries",
|
||||
"requested_duration_seconds": 60.0,
|
||||
"elapsed_seconds": 60.074,
|
||||
"concurrency": 8,
|
||||
"successful_requests": 84040,
|
||||
"failed_requests": 4,
|
||||
"error_ratio": 4.8e-05,
|
||||
"successful_rps": 1398.951,
|
||||
"successful_latency_ms": {
|
||||
"p50": 5.556,
|
||||
"p95": 8.741,
|
||||
"p99": 11.048
|
||||
},
|
||||
"note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead."
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"lab": 3,
|
||||
"workload": "closed-loop POST messages; no automatic retries",
|
||||
"requested_duration_seconds": 60.0,
|
||||
"elapsed_seconds": 60.078,
|
||||
"concurrency": 8,
|
||||
"successful_requests": 78078,
|
||||
"failed_requests": 4,
|
||||
"error_ratio": 5.1e-05,
|
||||
"successful_rps": 1299.617,
|
||||
"successful_latency_ms": {
|
||||
"p50": 5.957,
|
||||
"p95": 9.594,
|
||||
"p99": 12.386
|
||||
},
|
||||
"note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead."
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"lab": 3,
|
||||
"workload": "closed-loop POST messages; no automatic retries",
|
||||
"requested_duration_seconds": 60.0,
|
||||
"elapsed_seconds": 60.075,
|
||||
"concurrency": 8,
|
||||
"successful_requests": 92690,
|
||||
"failed_requests": 0,
|
||||
"error_ratio": 0.0,
|
||||
"successful_rps": 1542.892,
|
||||
"successful_latency_ms": {
|
||||
"p50": 5.047,
|
||||
"p95": 8.006,
|
||||
"p99": 10.239
|
||||
},
|
||||
"note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead."
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"lab": 3,
|
||||
"workload": "closed-loop POST messages; no automatic retries",
|
||||
"requested_duration_seconds": 60.0,
|
||||
"elapsed_seconds": 60.073,
|
||||
"concurrency": 8,
|
||||
"successful_requests": 89588,
|
||||
"failed_requests": 0,
|
||||
"error_ratio": 0.0,
|
||||
"successful_rps": 1491.325,
|
||||
"successful_latency_ms": {
|
||||
"p50": 5.245,
|
||||
"p95": 8.225,
|
||||
"p99": 10.303
|
||||
},
|
||||
"note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead."
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"lab": 3,
|
||||
"workload": "closed-loop POST messages; no automatic retries",
|
||||
"requested_duration_seconds": 60.0,
|
||||
"elapsed_seconds": 60.069,
|
||||
"concurrency": 8,
|
||||
"successful_requests": 85041,
|
||||
"failed_requests": 0,
|
||||
"error_ratio": 0.0,
|
||||
"successful_rps": 1415.713,
|
||||
"successful_latency_ms": {
|
||||
"p50": 5.538,
|
||||
"p95": 8.614,
|
||||
"p99": 10.749
|
||||
},
|
||||
"note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead."
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
{"label":"ctl1base","replicas":2,"total_cpu":1.0,"total_mem_mb":768,"duration":60,"concurrency":8,"warmup":15,"postgres_cpu_limit":"0.50","postgres_mem_limit":"384M","postgres_max_conns":10,"lb_cpu_limit":"0.25","client":"vm"}
|
||||
@@ -0,0 +1 @@
|
||||
{"label":"ctl2pg","replicas":2,"total_cpu":1.0,"total_mem_mb":768,"duration":60,"concurrency":8,"warmup":15,"postgres_cpu_limit":"1.00","postgres_mem_limit":"384M","postgres_max_conns":10,"lb_cpu_limit":"0.25","client":"vm"}
|
||||
@@ -0,0 +1 @@
|
||||
{"label":"ctl3base","replicas":2,"total_cpu":1.0,"total_mem_mb":768,"duration":60,"concurrency":8,"warmup":15,"postgres_cpu_limit":"0.50","postgres_mem_limit":"384M","postgres_max_conns":10,"lb_cpu_limit":"0.25","client":"vm"}
|
||||
@@ -0,0 +1 @@
|
||||
{"label":"ctl4lb","replicas":2,"total_cpu":1.0,"total_mem_mb":768,"duration":60,"concurrency":8,"warmup":15,"postgres_cpu_limit":"0.50","postgres_mem_limit":"384M","postgres_max_conns":10,"lb_cpu_limit":"1.00","client":"vm"}
|
||||
@@ -0,0 +1 @@
|
||||
{"label":"d2","replicas":2,"total_cpu":1.0,"total_mem_mb":768,"duration":60,"concurrency":8,"warmup":15,"postgres_cpu_limit":"0.50","postgres_mem_limit":"384M","postgres_max_conns":10,"lb_cpu_limit":"0.25","client":"vm"}
|
||||
@@ -0,0 +1 @@
|
||||
{"label":"db1cpu","replicas":2,"total_cpu":1.0,"total_mem_mb":768,"duration":60,"concurrency":8,"warmup":15,"postgres_cpu_limit":"1.00","postgres_mem_limit":"384M","postgres_max_conns":10,"lb_cpu_limit":"0.25","client":"vm"}
|
||||
@@ -0,0 +1 @@
|
||||
{"label":"g05","replicas":2,"total_cpu":0.5,"total_mem_mb":768,"duration":60,"concurrency":8,"warmup":15,"postgres_cpu_limit":"0.50","postgres_mem_limit":"384M","postgres_max_conns":10,"lb_cpu_limit":"0.25","client":"vm"}
|
||||
@@ -0,0 +1 @@
|
||||
{"label":"g10","replicas":2,"total_cpu":1.0,"total_mem_mb":768,"duration":60,"concurrency":8,"warmup":15,"postgres_cpu_limit":"0.50","postgres_mem_limit":"384M","postgres_max_conns":10,"lb_cpu_limit":"0.25","client":"vm"}
|
||||
@@ -0,0 +1 @@
|
||||
{"label":"g15","replicas":2,"total_cpu":1.5,"total_mem_mb":768,"duration":60,"concurrency":8,"warmup":15,"postgres_cpu_limit":"0.50","postgres_mem_limit":"384M","postgres_max_conns":10,"lb_cpu_limit":"0.25","client":"vm"}
|
||||
@@ -0,0 +1 @@
|
||||
{"label":"lb1cpu","replicas":2,"total_cpu":1.0,"total_mem_mb":768,"duration":60,"concurrency":8,"warmup":15,"postgres_cpu_limit":"0.50","postgres_mem_limit":"384M","postgres_max_conns":10,"lb_cpu_limit":"1.00","client":"vm"}
|
||||
@@ -0,0 +1 @@
|
||||
{"label":"pool10","replicas":4,"total_cpu":1.0,"total_mem_mb":768,"duration":60,"concurrency":8,"warmup":15,"postgres_cpu_limit":"0.50","postgres_mem_limit":"384M","postgres_max_conns":10,"lb_cpu_limit":"0.25","client":"vm"}
|
||||
@@ -0,0 +1 @@
|
||||
{"label":"pool5","replicas":4,"total_cpu":1.0,"total_mem_mb":768,"duration":60,"concurrency":8,"warmup":15,"postgres_cpu_limit":"0.50","postgres_mem_limit":"384M","postgres_max_conns":5,"lb_cpu_limit":"0.25","client":"vm"}
|
||||
@@ -0,0 +1 @@
|
||||
{"label":"r1","replicas":1,"total_cpu":1.0,"total_mem_mb":768,"duration":60,"concurrency":8,"warmup":15,"postgres_cpu_limit":"0.50","postgres_mem_limit":"384M","postgres_max_conns":10,"lb_cpu_limit":"0.25","client":"vm"}
|
||||
@@ -0,0 +1 @@
|
||||
{"label":"r2","replicas":2,"total_cpu":1.0,"total_mem_mb":768,"duration":60,"concurrency":8,"warmup":15,"postgres_cpu_limit":"0.50","postgres_mem_limit":"384M","postgres_max_conns":10,"lb_cpu_limit":"0.25","client":"vm"}
|
||||
@@ -0,0 +1 @@
|
||||
{"label":"r4","replicas":4,"total_cpu":1.0,"total_mem_mb":768,"duration":60,"concurrency":8,"warmup":15,"postgres_cpu_limit":"0.50","postgres_mem_limit":"384M","postgres_max_conns":10,"lb_cpu_limit":"0.25","client":"vm"}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 55 KiB |
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user