lab4 done

This commit is contained in:
Khakimov Dmitrij
2026-11-10 20:42:03 +03:00
parent 276dbdad8a
commit b2bd7501d3
129 changed files with 9319 additions and 109 deletions
+14 -1
View File
@@ -1,8 +1,8 @@
.git
.github
.gitignore
.env
.env.*
!.env.example
secrets
certs
volumes
@@ -17,4 +17,17 @@ backups
__pycache__
node_modules
evidence
examples
scripts
tests
*.md
Dockerfile*
Makefile
requirements-dev.txt
lab.json
.DS_Store
.idea
.vscode
.agents
.codex
+60
View File
@@ -0,0 +1,60 @@
FROM golang:1.26.4-alpine3.23@sha256:18b460dd17542c2ba43299a633cf6ebfc1115101509531471d7cfce1019af083 AS goose-builder
RUN GOBIN=/out CGO_ENABLED=0 go install \
-tags='no_clickhouse no_libsql no_mssql no_mysql no_sqlite3 no_vertica no_ydb no_spanner' \
github.com/pressly/goose/v3/cmd/goose@v3.27.1
FROM alpine:3.23@sha256:075c2c1a4068c1e251228ca2b0ea8b163f835ca5d66e758b93c7fc89b1995616 AS migrations
COPY --from=goose-builder /out/goose /usr/local/bin/goose
COPY migrations /migrations
COPY infra/migrate.sh /usr/local/bin/migrate
USER 10001:10001
ENTRYPOINT ["/usr/local/bin/migrate"]
CMD ["up"]
FROM golang:1.26.4-alpine3.23@sha256:18b460dd17542c2ba43299a633cf6ebfc1115101509531471d7cfce1019af083 AS builder
WORKDIR /src
RUN apk add --no-cache gcc musl-dev
COPY go.mod go.sum ./
RUN go mod download
COPY cmd ./cmd
COPY contracts ./contracts
COPY dto ./dto
COPY internal ./internal
COPY migrations ./migrations
RUN CGO_ENABLED=0 GOOS=linux go build \
-trimpath \
-ldflags="-s -w" \
-o /out/messenger ./cmd
RUN CGO_ENABLED=0 GOOS=linux go build -trimpath -ldflags="-s -w" -o /out/reconcile ./cmd/reconcile
FROM builder AS tests
COPY --from=goose-builder /out/goose /usr/local/bin/goose
ENV GOOSE_MIGRATION_DIR=/src/migrations
CMD ["go", "test", "-p=1", "-race", "-count=1", "-v", "./..."]
FROM alpine:3.23@sha256:075c2c1a4068c1e251228ca2b0ea8b163f835ca5d66e758b93c7fc89b1995616
RUN addgroup -S messenger \
&& adduser -S -D -H -u 10001 -G messenger messenger
COPY --from=builder --chown=messenger:messenger /out/messenger /usr/local/bin/messenger
COPY --from=builder --chown=messenger:messenger /out/reconcile /usr/local/bin/reconcile
ENV PORT=8080
EXPOSE 8080
USER messenger:messenger
HEALTHCHECK --interval=10s --timeout=3s --start-period=3s --retries=3 \
CMD wget -q -O /dev/null "http://127.0.0.1:${PORT}/health/ready" || exit 1
STOPSIGNAL SIGTERM
ENTRYPOINT ["/usr/local/bin/messenger"]
+34
View File
@@ -0,0 +1,34 @@
FROM golang:1.26.4-alpine3.23@sha256:18b460dd17542c2ba43299a633cf6ebfc1115101509531471d7cfce1019af083 AS minio-builder
ADD --checksum=sha256:8b11129f6a6830768bcdebab569290ad956618f5ff6ef4857b633acb64f95126 https://codeload.github.com/minio/minio/tar.gz/01ce918d8279a20e4706b96a64396146894adee4 /tmp/source.tar.gz
RUN mkdir /src && tar -xzf /tmp/source.tar.gz -C /src --strip-components=1
WORKDIR /src
RUN CGO_ENABLED=0 go build -trimpath -ldflags='-s -w' -o /out/minio .
RUN echo '8b11129f6a6830768bcdebab569290ad956618f5ff6ef4857b633acb64f95126 /tmp/source.tar.gz' | sha256sum -c -
FROM golang:1.26.4-alpine3.23@sha256:18b460dd17542c2ba43299a633cf6ebfc1115101509531471d7cfce1019af083 AS mc-builder
ADD --checksum=sha256:4cea8ed209c8f96e59ea1a5cc4901019b54c2be6d6f5f16c6749ea8bdcf4172e https://codeload.github.com/minio/mc/tar.gz/d6541ea280b73a834b64d4097e21f2be77676104 /tmp/source.tar.gz
RUN mkdir /src && tar -xzf /tmp/source.tar.gz -C /src --strip-components=1
WORKDIR /src
RUN CGO_ENABLED=0 go build -trimpath -ldflags='-s -w' -o /out/mc .
RUN echo '4cea8ed209c8f96e59ea1a5cc4901019b54c2be6d6f5f16c6749ea8bdcf4172e /tmp/source.tar.gz' | sha256sum -c -
FROM alpine:3.23@sha256:075c2c1a4068c1e251228ca2b0ea8b163f835ca5d66e758b93c7fc89b1995616 AS minio
LABEL org.opencontainers.image.source="https://github.com/minio/minio" \
org.opencontainers.image.revision="01ce918d8279a20e4706b96a64396146894adee4" \
org.opencontainers.image.version="RELEASE.2025-09-07T16-13-09Z" \
org.opencontainers.image.licenses="AGPL-3.0"
RUN mkdir /data && chown 10001:10001 /data
COPY --from=minio-builder /out/minio /usr/local/bin/minio
COPY infra/minio-entrypoint.sh /usr/local/bin/start-minio
USER 10001:10001
EXPOSE 9000
ENTRYPOINT ["/usr/local/bin/start-minio"]
FROM alpine:3.23@sha256:075c2c1a4068c1e251228ca2b0ea8b163f835ca5d66e758b93c7fc89b1995616 AS mc
LABEL org.opencontainers.image.source="https://github.com/minio/mc" \
org.opencontainers.image.revision="d6541ea280b73a834b64d4097e21f2be77676104" \
org.opencontainers.image.version="RELEASE.2025-08-13T08-35-41Z" \
org.opencontainers.image.licenses="AGPL-3.0"
COPY --from=mc-builder /out/mc /usr/local/bin/mc
USER 10001:10001
ENTRYPOINT ["mc"]
+73 -7
View File
@@ -1,13 +1,21 @@
PYTHON ?= python3
BASE_URL ?= http://localhost:8080
PYTHON ?= $(if $(wildcard .venv/bin/python),.venv/bin/python,python3)
GO ?= go
PORT ?= 8080
BASE_URL ?= http://localhost:$(PORT)
IMAGE ?= mtusi-messenger:lab4
CA_FILE ?=
ACTION_SCRIPT ?=
ACTION_SCRIPT ?= scripts/restart.sh
FAILOVER_SCRIPT ?= scripts/stop-one.sh
RECONCILE_ARGS ?=
export PYTHONDONTWRITEBYTECODE=1
TLS_ARGS = $(if $(CA_FILE),--ca-file "$(CA_FILE)",)
.PHONY: help check validate test load test-persistence test-failover
.PHONY: help run docker-build docker-run check validate test test-own test-all load test-persistence bootstrap up down migrate test-integration test-grade4 test-lab4 test-reconcile measure-uploads measure-load migrate-status rolling-update test-failover wait bootstrap-s3 reconcile reconcile-apply
export PORT BASE_URL
help:
@echo "check: offline structure; validate: full OpenAPI (requirements-dev.txt); test: running API; load: synthetic writes"
@echo "up: build and deploy Swarm stack; down: stop with volumes retained; test-integration: PostgreSQL race/rollback/EXPLAIN; test-grade4: cross-replica idempotency, both failures and rolling update; check: offline structure; validate: full OpenAPI (requirements-dev.txt); test: running API; load: synthetic writes"
check:
$(PYTHON) scripts/check_contract.py
@@ -18,6 +26,11 @@ validate:
test:
$(PYTHON) tests/smoke.py --base-url "$(BASE_URL)" $(TLS_ARGS)
test-own:
$(GO) test -race ./...
test-all: check validate test-own
load:
$(PYTHON) tests/load.py --base-url "$(BASE_URL)" $(TLS_ARGS)
@@ -25,6 +38,59 @@ 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)
bootstrap:
./scripts/bootstrap.sh
up:
$(PYTHON) scripts/swarm.py up
down:
$(PYTHON) scripts/swarm.py down
migrate:
$(PYTHON) scripts/swarm.py migrate
migrate-status:
$(PYTHON) scripts/swarm.py migrate-status
rolling-update:
$(PYTHON) scripts/swarm.py update
run:
PORT="$(PORT)" $(GO) run ./cmd
docker-build:
docker build -t "$(IMAGE)" .
test-integration:
$(PYTHON) scripts/swarm.py test-integration
test-grade4:
$(PYTHON) tests/own/swarm_grade4.py
test-lab4:
$(PYTHON) tests/own/lab4.py
test-reconcile:
$(PYTHON) tests/own/reconcile.py
measure-uploads:
$(PYTHON) scripts/measure_uploads.py
bootstrap-s3:
$(PYTHON) scripts/swarm.py bootstrap-s3
reconcile:
$(PYTHON) scripts/swarm.py reconcile $(RECONCILE_ARGS)
reconcile-apply:
$(PYTHON) scripts/swarm.py reconcile --apply $(RECONCILE_ARGS)
measure-load:
$(PYTHON) scripts/measure_load.py --base-url "$(BASE_URL)"
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) tests/resilience.py --mode failover --action-script "$(if $(filter command line,$(origin ACTION_SCRIPT)),$(ACTION_SCRIPT),$(FAILOVER_SCRIPT))" --base-url "$(BASE_URL)" $(TLS_ARGS)
wait:
$(PYTHON) scripts/swarm.py wait
+105
View File
@@ -0,0 +1,105 @@
package main
import (
"context"
"errors"
"fmt"
"log"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/redis/go-redis/v9"
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/app/chat"
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/attachment"
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/config"
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/repository/postgres"
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/session"
chatusecase "gitflic.ru/akselbant/mtusi2026lab1-fork/internal/usecase/chat"
)
const shutdownTimeout = 8 * time.Second
func main() {
cfg, err := config.Load()
if err != nil {
log.Fatal(err)
}
poolConfig, err := pgxpool.ParseConfig("sslmode=disable")
if err != nil {
log.Fatal("invalid PostgreSQL config")
}
poolConfig.ConnConfig.Host = cfg.PostgresHost
poolConfig.ConnConfig.Port = cfg.PostgresPort
poolConfig.ConnConfig.User = cfg.PostgresUser
poolConfig.ConnConfig.Database = cfg.PostgresDatabase
poolConfig.ConnConfig.Password = cfg.PostgresPassword
poolConfig.ConnConfig.ConnectTimeout = cfg.QueryTimeout
poolConfig.ConnConfig.RuntimeParams["timezone"] = "UTC"
poolConfig.ConnConfig.RuntimeParams["statement_timeout"] = fmt.Sprint(cfg.QueryTimeout.Milliseconds())
poolConfig.MaxConns = cfg.PostgresMaxConns
poolConfig.MinConns = 1
poolConfig.MaxConnLifetime = time.Hour
poolConfig.MaxConnIdleTime = 5 * time.Minute
pool, err := pgxpool.NewWithConfig(context.Background(), poolConfig)
if err != nil {
log.Fatal("cannot create PostgreSQL pool")
}
defer pool.Close()
redisClient := redis.NewClient(&redis.Options{
Addr: cfg.RedisAddr, PoolSize: 10, MaxActiveConns: 10, PoolTimeout: cfg.QueryTimeout,
DialTimeout: cfg.QueryTimeout, ReadTimeout: cfg.QueryTimeout, WriteTimeout: cfg.QueryTimeout,
MaxRetries: -1, ContextTimeoutEnabled: true,
})
defer redisClient.Close()
repo := postgres.New(pool, cfg.QueryTimeout)
sessions := session.NewRedis(redisClient, cfg.QueryTimeout)
useCase := chatusecase.New(repo, sessions, cfg.SessionTTL)
objectStore, err := attachment.NewStore(cfg.S3Endpoint, cfg.S3Bucket, cfg.S3AccessKey, cfg.S3SecretKey, cfg.S3UseSSL)
if err != nil {
log.Fatal("invalid S3 config")
}
handler := chat.NewChat(useCase, cfg.CursorKey).WithAttachments(attachment.New(pool, objectStore))
port := cfg.Port
e := handler.Router()
e.Server.ReadHeaderTimeout = 5 * time.Second
e.Server.ReadTimeout = 50 * time.Second
e.Server.WriteTimeout = 55 * time.Second
e.Server.IdleTimeout = 60 * time.Second
serverErrors := make(chan error, 1)
go func() {
log.Printf("HTTP server is listening on :%s", port)
serverErrors <- e.Start(":" + port)
}()
stop := make(chan os.Signal, 1)
signal.Notify(stop, syscall.SIGINT, syscall.SIGTERM)
select {
case sig := <-stop:
log.Printf("received %s, shutting down", sig)
case err := <-serverErrors:
if !errors.Is(err, http.ErrServerClosed) {
log.Fatalf("HTTP server failed: %v", err)
}
return
}
handler.Drain()
// Allow two 1-second LB checks to remove this backend before closing the listener.
time.Sleep(3 * time.Second)
ctx, cancel := context.WithTimeout(context.Background(), shutdownTimeout)
defer cancel()
if err := e.Shutdown(ctx); err != nil {
log.Printf("graceful shutdown failed: %v", err)
if closeErr := e.Close(); closeErr != nil {
log.Printf("forced shutdown failed: %v", closeErr)
}
return
}
log.Printf("shutdown complete")
}
+57
View File
@@ -0,0 +1,57 @@
package main
import (
"context"
"encoding/json"
"flag"
"log"
"os"
"time"
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/attachment"
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/config"
"github.com/jackc/pgx/v5/pgxpool"
)
func main() {
apply := flag.Bool("apply", false, "apply safe repairs; default dry-run")
grace := flag.Duration("grace", 2*time.Minute, "minimum object/metadata age (at least 90s)")
timeout := flag.Duration("timeout", 10*time.Minute, "whole scan deadline")
flag.Parse()
if *grace < attachment.MinimumGrace {
log.Fatal("grace must be at least 90s")
}
cfg, err := config.Load()
if err != nil {
log.Fatal(err)
}
pc, err := pgxpool.ParseConfig("sslmode=disable")
if err != nil {
log.Fatal("invalid DB config")
}
pc.ConnConfig.Host = cfg.PostgresHost
pc.ConnConfig.Port = cfg.PostgresPort
pc.ConnConfig.User = cfg.PostgresUser
pc.ConnConfig.Password = cfg.PostgresPassword
pc.ConnConfig.Database = cfg.PostgresDatabase
pc.ConnConfig.ConnectTimeout = 3 * time.Second
pc.ConnConfig.RuntimeParams["statement_timeout"] = "5000"
pc.MaxConns = 2
ctx, cancel := context.WithTimeout(context.Background(), *timeout)
defer cancel()
pool, err := pgxpool.NewWithConfig(ctx, pc)
if err != nil {
log.Fatal("cannot create DB pool")
}
defer pool.Close()
store, err := attachment.NewStore(cfg.S3Endpoint, cfg.S3Bucket, cfg.S3AccessKey, cfg.S3SecretKey, cfg.S3UseSSL)
if err != nil {
log.Fatal("invalid S3 config")
}
result, err := attachment.New(pool, store).Reconcile(ctx, *apply, *grace)
_ = json.NewEncoder(os.Stdout).Encode(result)
if err != nil {
log.Print(err)
os.Exit(1)
}
}
+1 -3
View File
@@ -1,14 +1,12 @@
# Topology worksheet, deliberately NOT a runnable stack (no application supplied).
# Implement compose.yaml or stack.yaml; do not submit this empty file as deployment.
# Service names below are logical roles, not imposed container names.
x-lab-number: 5
x-lab-number: 4
x-required-roles:
- api
- postgres
- load_balancer
- s3
- broker
- worker
# TODO: implement real images/builds, network wiring, volumes, healthchecks,
# credentials and bootstrap. Details: contracts/infrastructure.json and README.md.
services: {}
+161
View File
@@ -0,0 +1,161 @@
name: mtusi2026lab4
services:
postgres:
image: postgres:17.6-alpine3.22
environment:
POSTGRES_USER: messenger
POSTGRES_DB: messenger
POSTGRES_PASSWORD_FILE: /run/secrets/postgres_password
secrets:
- postgres_password
volumes:
- postgres_data:/var/lib/postgresql/data
healthcheck:
test: [CMD-SHELL, 'pg_isready -U messenger -d messenger']
interval: 2s
timeout: 2s
retries: 30
cpus: 1.0
mem_limit: 512m
redis:
image: redis:7.4.5-alpine3.21
command: [redis-server, /usr/local/etc/redis/redis.conf]
volumes:
- redis_data:/data
- ./infra/redis.conf:/usr/local/etc/redis/redis.conf:ro
healthcheck:
test: [CMD, redis-cli, ping]
interval: 2s
timeout: 2s
retries: 30
cpus: 0.5
mem_limit: 128m
minio:
image: mtusi-minio:RELEASE.2025-09-07T16-13-09Z
build:
context: .
dockerfile: Dockerfile.storage
target: minio
secrets: [s3_root_access_key, s3_root_secret_key]
volumes: [s3_data:/data]
healthcheck:
test: [CMD, wget, -q, -T, '2', -O, /dev/null, 'http://127.0.0.1:9000/minio/health/live']
interval: 2s
timeout: 3s
start_period: 15s
retries: 30
cpus: 1.0
mem_limit: 512m
stop_grace_period: 20s
s3_bootstrap:
image: mtusi-mc:RELEASE.2025-08-13T08-35-41Z
build:
context: .
dockerfile: Dockerfile.storage
target: mc
entrypoint: [/bin/sh, /bootstrap.sh]
configs:
- source: s3_bootstrap
target: /bootstrap.sh
- source: s3_policy
target: /policy.json
secrets: [s3_root_access_key, s3_root_secret_key, s3_access_key, s3_secret_key]
depends_on:
minio:
condition: service_healthy
cpus: 0.5
mem_limit: 512m
migrations:
image: mtusi-migrations:lab4
build:
context: .
target: migrations
environment:
GOOSE_DRIVER: postgres
GOOSE_DBSTRING: host=postgres user=messenger dbname=messenger sslmode=disable connect_timeout=5
POSTGRES_PASSWORD_FILE: /run/secrets/postgres_password
secrets:
- postgres_password
depends_on:
postgres:
condition: service_healthy
cpus: 0.5
mem_limit: 128m
api:
build: .
image: mtusi-messenger:lab4
environment: &api_environment
POSTGRES_HOST: postgres
POSTGRES_USER: messenger
POSTGRES_DB: messenger
POSTGRES_PASSWORD_FILE: /run/secrets/postgres_password
POSTGRES_MAX_CONNS: '10'
REDIS_ADDR: redis:6379
CURSOR_KEY_FILE: /run/secrets/cursor_key
SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600}
QUERY_TIMEOUT_MS: '2000'
S3_ENDPOINT: minio:9000
S3_BUCKET: attachments
S3_ACCESS_KEY_FILE: /run/secrets/s3_access_key
S3_SECRET_KEY_FILE: /run/secrets/s3_secret_key
S3_USE_SSL: 'false'
GOMEMLIMIT: 1152MiB
GOGC: '50'
secrets: &api_secrets
- postgres_password
- cursor_key
- s3_access_key
- s3_secret_key
ports:
- '127.0.0.1:${PORT:-8080}:8080'
depends_on:
postgres:
condition: service_healthy
redis:
condition: service_healthy
migrations:
condition: service_completed_successfully
s3_bootstrap:
condition: service_completed_successfully
cpus: 1.0
mem_limit: 1536m
stop_grace_period: 10s
tests:
image: mtusi-messenger-tests:lab4
profiles: [test]
build:
context: .
target: tests
environment:
<<: *api_environment
INTEGRATION_TESTS: '1'
secrets: *api_secrets
depends_on:
postgres:
condition: service_healthy
redis:
condition: service_healthy
cpus: 1.0
mem_limit: 1g
configs:
s3_bootstrap:
file: ./infra/s3-bootstrap.sh
s3_policy:
file: ./infra/s3-policy.json
secrets:
s3_root_access_key:
file: ./secrets/s3_root_access_key
s3_root_secret_key:
file: ./secrets/s3_root_secret_key
s3_access_key:
file: ./secrets/s3_access_key
s3_secret_key:
file: ./secrets/s3_secret_key
postgres_password:
file: ./secrets/postgres_password
cursor_key:
file: ./secrets/cursor_key
volumes:
postgres_data:
redis_data:
s3_data:
+9
View File
@@ -0,0 +1,9 @@
package contracts
import _ "embed"
// OpenAPI is embedded so Swagger UI works from a compiled binary and does not
// depend on the process working directory.
//
//go:embed openapi.json
var OpenAPI []byte
+1 -17
View File
@@ -1,5 +1,5 @@
{
"lab": 5,
"lab": 4,
"kind": "requirements, not runnable deployment",
"required_for_grade_3": [
{
@@ -27,22 +27,6 @@
],
"private_bucket": true,
"persistent_volume": true
},
{
"role": "broker",
"choose_one": [
"RabbitMQ",
"Redis Streams",
"Valkey Streams",
"NATS JetStream",
"documented durable equivalent"
],
"persistent_volume": true,
"delivery": "at-least-once"
},
{
"role": "worker",
"separate_process": true
}
],
"optional_components": [
-63
View File
@@ -1,63 +0,0 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "urn:mtusi:messenger:attachment-job:v1",
"title": "Durable attachment processing job v1",
"type": "object",
"additionalProperties": false,
"required": [
"schema_version",
"job_id",
"type",
"attachment_id",
"pipeline_version",
"attempt",
"created_at"
],
"properties": {
"schema_version": {
"const": 1
},
"job_id": {
"type": "string",
"format": "uuid"
},
"type": {
"const": "attachment.process.v1"
},
"attachment_id": {
"type": "string",
"format": "uuid"
},
"pipeline_version": {
"type": "integer",
"minimum": 1
},
"attempt": {
"type": "integer",
"minimum": 1
},
"created_at": {
"type": "string",
"format": "date-time"
},
"traceparent": {
"type": "string",
"pattern": "^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$"
},
"tracestate": {
"type": "string",
"maxLength": 512
}
},
"examples": [
{
"schema_version": 1,
"job_id": "11111111-1111-4111-8111-111111111111",
"type": "attachment.process.v1",
"attachment_id": "22222222-2222-4222-8222-222222222222",
"pipeline_version": 1,
"attempt": 1,
"created_at": "2026-09-01T12:00:00Z"
}
]
}
+5 -11
View File
@@ -1,8 +1,8 @@
{
"openapi": "3.1.0",
"info": {
"title": "MTUSI Messenger — лабораторная 5",
"version": "1.5.0",
"title": "MTUSI Messenger — лабораторная 4",
"version": "1.4.0",
"description": "Нормативный минимум на 3. Семантика: contracts/README.md. Расширения на 4/5 не должны менять этот API. Наличие кода ошибки в схеме не требует реализовать факультативную причину его выдачи."
},
"servers": [
@@ -2151,7 +2151,7 @@
"operationId": "uploadAttachment",
"summary": "Принять один PNG/JPEG, до 10 MiB",
"responses": {
"202": {
"201": {
"description": "Успех",
"headers": {
"X-Request-Id": {
@@ -2936,10 +2936,7 @@
"schema": {
"type": "string",
"enum": [
"original",
"thumbnail",
"crop",
"optimized"
"original"
],
"default": "original"
}
@@ -3464,10 +3461,7 @@
"status": {
"type": "string",
"enum": [
"queued",
"processing",
"ready",
"failed"
"ready"
]
},
"variants": {
+13
View File
@@ -0,0 +1,13 @@
package dto
type CreateChatRequest struct {
Title string `json:"title"`
MemberIDs []string `json:"member_ids"`
}
type CreateChatResponse struct {
ID string `json:"id"`
Title string `json:"title"`
MemberIDs []string `json:"member_ids"`
CreatedAt Timestamp `json:"created_at"`
}
+16
View File
@@ -0,0 +1,16 @@
package dto
type CreateMessageRequest struct {
ChatID string `json:"-"`
Text string `json:"text"`
AttachmentIDs []string `json:"attachment_ids"`
}
type CreateMessageResponse struct {
ID string `json:"id"`
ChatID string `json:"chat_id"`
SenderID string `json:"sender_id"`
Text string `json:"text"`
AttachmentIDs []string `json:"attachment_ids"`
CreatedAt Timestamp `json:"created_at"`
}
+33
View File
@@ -0,0 +1,33 @@
package dto
import (
"bytes"
"encoding/json"
"errors"
)
// Keep absent attachment_ids equivalent to [], while rejecting JSON null and
// wrong types rather than quietly treating them as an empty message body.
func (r *CreateMessageRequest) UnmarshalJSON(data []byte) error {
type payload CreateMessageRequest
var fields map[string]json.RawMessage
if err := json.Unmarshal(data, &fields); err != nil || fields == nil {
return errors.New("Ожидается JSON-объект")
}
text, exists := fields["text"]
if !exists || bytes.Equal(bytes.TrimSpace(text), []byte("null")) {
return errors.New("Требуется строка text")
}
if ids, exists := fields["attachment_ids"]; exists && bytes.Equal(bytes.TrimSpace(ids), []byte("null")) {
return errors.New("attachment_ids должен быть массивом")
}
decoder := json.NewDecoder(bytes.NewReader(data))
decoder.DisallowUnknownFields()
var decoded payload
if err := decoder.Decode(&decoded); err != nil {
return err
}
decoded.ChatID = r.ChatID
*r = CreateMessageRequest(decoded)
return nil
}
+21
View File
@@ -0,0 +1,21 @@
package dto
import (
"encoding/json"
"testing"
)
func TestMessageStrictFields(t *testing.T) {
for _, body := range []string{`null`, `[]`, `{}`, `{"text":null}`, `{"text":"x","attachment_ids":null}`, `{"text":"x","attachment_ids":"x"}`, `{"text":"x","extra":1}`} {
var r CreateMessageRequest
if err := json.Unmarshal([]byte(body), &r); err == nil {
t.Fatalf("accepted %s", body)
}
}
for _, body := range []string{`{"text":"x"}`, `{"text":"x","attachment_ids":[]}`, `{"text":"","attachment_ids":["id"]}`} {
var r CreateMessageRequest
if err := json.Unmarshal([]byte(body), &r); err != nil {
t.Fatalf("rejected %s: %v", body, err)
}
}
}
+14
View File
@@ -0,0 +1,14 @@
package dto
type CreateUserRequest struct {
Password string `json:"password"`
Username string `json:"username"`
DisplayName string `json:"display_name"`
}
type CreateUserResponse struct {
ID string `json:"id"`
Username string `json:"username"`
DisplayName string `json:"display_name"`
CreatedAt Timestamp `json:"created_at"`
}
+10
View File
@@ -0,0 +1,10 @@
package dto
type CurrentUserRequest struct{}
type CurrentUserResponse struct {
ID string `json:"id"`
Username string `json:"username"`
DisplayName string `json:"display_name"`
CreatedAt Timestamp `json:"created_at"`
}
+11
View File
@@ -0,0 +1,11 @@
package dto
type ErrorResponse struct {
Error ErrorDetails `json:"error"`
}
type ErrorDetails struct {
Code string `json:"code"`
Message string `json:"message"`
RequestID string `json:"request_id"`
}
+12
View File
@@ -0,0 +1,12 @@
package dto
type GetChatRequest struct {
ChatID string `json:"-"`
}
type GetChatResponse struct {
ID string `json:"id"`
Title string `json:"title"`
MemberIDs []string `json:"member_ids"`
CreatedAt Timestamp `json:"created_at"`
}
+18
View File
@@ -0,0 +1,18 @@
package dto
type ListChatsRequest struct {
Limit int `json:"-"`
Cursor string `json:"-"`
}
type ListChatsResponse struct {
Items []ListChatsItem `json:"items"`
NextCursor *string `json:"next_cursor"`
}
type ListChatsItem struct {
ID string `json:"id"`
Title string `json:"title"`
MemberIDs []string `json:"member_ids"`
CreatedAt Timestamp `json:"created_at"`
}
+21
View File
@@ -0,0 +1,21 @@
package dto
type ListMessagesRequest struct {
ChatID string `json:"-"`
Limit int `json:"-"`
Cursor string `json:"-"`
}
type ListMessagesResponse struct {
Items []ListMessagesItem `json:"items"`
NextCursor *string `json:"next_cursor"`
}
type ListMessagesItem struct {
ID string `json:"id"`
ChatID string `json:"chat_id"`
SenderID string `json:"sender_id"`
Text string `json:"text"`
AttachmentIDs []string `json:"attachment_ids"`
CreatedAt Timestamp `json:"created_at"`
}
+7
View File
@@ -0,0 +1,7 @@
package dto
type LivenessRequest struct{}
type LivenessResponse struct {
Status string `json:"status"`
}
+7
View File
@@ -0,0 +1,7 @@
package dto
type ReadinessRequest struct{}
type ReadinessResponse struct {
Status string `json:"status"`
}
+8
View File
@@ -0,0 +1,8 @@
package dto
type CreateSessionResponse struct {
Token string `json:"token"`
TokenType string `json:"token_type"`
ExpiresAt Timestamp `json:"expires_at"`
User CreateUserResponse `json:"user"`
}
+11
View File
@@ -0,0 +1,11 @@
package dto
import "time"
// Timestamp preserves PostgreSQL microseconds and is readable by Python 3.9 clients.
// time.Time's variable-length fractional part is not supported by those clients.
type Timestamp time.Time
func (t Timestamp) MarshalJSON() ([]byte, error) {
return []byte(`"` + time.Time(t).UTC().Format("2006-01-02T15:04:05.000000Z") + `"`), nil
}
+15
View File
@@ -0,0 +1,15 @@
package dto
import (
"encoding/json"
"testing"
"time"
)
func TestTimestampFixedMicroseconds(t *testing.T) {
timestamp := Timestamp(time.Date(2026, 1, 2, 3, 4, 5, 123400000, time.UTC))
encoded, err := json.Marshal(timestamp)
if err != nil || string(encoded) != `"2026-01-02T03:04:05.123400Z"` {
t.Fatalf("timestamp=%s err=%v", encoded, err)
}
}
+104
View File
@@ -0,0 +1,104 @@
{
"negative_cases": [
{
"case": "oversized_bytes",
"status": 413
},
{
"case": "damaged_png",
"status": 415
},
{
"case": "corrupt_crc",
"status": 415
},
{
"case": "mime_spoof",
"status": 415
},
{
"case": "not_image",
"status": 415
},
{
"case": "unsupported_mime",
"status": 415
},
{
"case": "pixel_budget",
"status": 413
},
{
"case": "unsafe_slash",
"status": 400
},
{
"case": "unsafe_backslash",
"status": 400
},
{
"case": "unsafe_control",
"status": 400
},
{
"case": "empty_filename",
"status": 400
},
{
"case": "foreign_attachment",
"status": 404
},
{
"case": "foreign_chat_link",
"status": 404
},
{
"case": "unknown_attachment",
"status": 404
},
{
"case": "duplicate_ids",
"status": 400
},
{
"case": "missing_authentication",
"status": 401
},
{
"case": "unknown_variant",
"status": 404
},
{
"case": "chunked_oversized",
"status": 413
}
],
"failures": {
"client_disconnect": {
"metadata_added": 0,
"spool_files_remaining": 0
},
"upload_replica_failure": {
"upload_instance": "alixbvpbjnzvtqvo5hhfpokc6",
"download_instance": "h6fc30dhoabp0jcfl6zrpjdzx",
"recovery_seconds": 0.51,
"sha256": "8502afe2cc5bab33ac834c834874369d29e7896599b5a256d68d80c5395d99c3"
},
"s3_outage": {
"liveness": 200,
"readiness": 503,
"recovery_seconds": 19.285
}
},
"checksums": {
"image/png": "8502afe2cc5bab33ac834c834874369d29e7896599b5a256d68d80c5395d99c3",
"image/jpeg": "41feb40d75a595386c72cfc8a5bc013c2dedc445b73316ebbd3b3eac13491c5d"
},
"bucket_security": {
"anonymous_get_status": 403,
"create_bucket_denied": true,
"write_outside_prefix_denied": true,
"console_published": false,
"bootstrap_repeats": 2
}
}
+2
View File
@@ -0,0 +1,2 @@
.venv/bin/python tests/own/lab4.py
PASS: PNG/JPEG, bounded uploads, MIME/damage/ACL/link errors, disconnect, private S3, repeat bootstrap, S3 outage.
+8
View File
@@ -0,0 +1,8 @@
image mtusi-mc:RELEASE.2025-08-13T08-35-41Z could not be accessed on a registry to record
its digest. Each node will access mtusi-mc:RELEASE.2025-08-13T08-35-41Z independently,
possibly leading to different nodes running different
versions of the image.
0pza81k652zzumhh8w5zfuxw8
mtusi-lab4_s3-bootstrap.0.jjp4j3jx92l1@colima | PASS: private bucket and restricted API account configured.
mtusi-lab4_s3-bootstrap
+112
View File
@@ -0,0 +1,112 @@
DEPRECATED: The legacy builder is deprecated and will be removed in a future release.
Install the buildx component to build images with BuildKit:
https://docs.docker.com/go/buildx/
Sending build context to Docker daemon 401.9kB␍
Step 1/35 : FROM golang:1.26.4-alpine3.23@sha256:18b460dd17542c2ba43299a633cf6ebfc1115101509531471d7cfce1019af083 AS goose-builder
---> 18b460dd1754
Step 2/35 : RUN GOBIN=/out CGO_ENABLED=0 go install -tags='no_clickhouse no_libsql no_mssql no_mysql no_sqlite3 no_vertica no_ydb no_spanner' github.com/pressly/goose/v3/cmd/goose@v3.27.1
---> Using cache
---> 7012ef857c0c
Step 3/35 : FROM alpine:3.23@sha256:075c2c1a4068c1e251228ca2b0ea8b163f835ca5d66e758b93c7fc89b1995616 AS migrations
---> 075c2c1a4068
Step 4/35 : COPY --from=goose-builder /out/goose /usr/local/bin/goose
---> Using cache
---> 6a0ad52336c1
Step 5/35 : COPY migrations /migrations
---> Using cache
---> 19018c7bfac9
Step 6/35 : COPY infra/migrate.sh /usr/local/bin/migrate
---> Using cache
---> 0cc075ba3459
Step 7/35 : USER 10001:10001
---> Using cache
---> 37de51af32cd
Step 8/35 : ENTRYPOINT ["/usr/local/bin/migrate"]
---> Using cache
---> e7539a967679
Step 9/35 : CMD ["up"]
---> Using cache
---> 841d9bb239cd
Step 10/35 : FROM golang:1.26.4-alpine3.23@sha256:18b460dd17542c2ba43299a633cf6ebfc1115101509531471d7cfce1019af083 AS builder
---> 18b460dd1754
Step 11/35 : WORKDIR /src
---> Using cache
---> 1ba013278a4a
Step 12/35 : RUN apk add --no-cache gcc musl-dev
---> Using cache
---> a0ea65f0bded
Step 13/35 : COPY go.mod go.sum ./
---> Using cache
---> e98ccecfb093
Step 14/35 : RUN go mod download
---> Using cache
---> 91d546c71507
Step 15/35 : COPY cmd ./cmd
---> Using cache
---> b4e431a9d5f2
Step 16/35 : COPY contracts ./contracts
---> Using cache
---> 958477d6c98e
Step 17/35 : COPY dto ./dto
---> Using cache
---> d115fe2e1af4
Step 18/35 : COPY internal ./internal
---> 2f61826e3774
Step 19/35 : COPY migrations ./migrations
---> d96dd811bc83
Step 20/35 : RUN CGO_ENABLED=0 GOOS=linux go build -trimpath -ldflags="-s -w" -o /out/messenger ./cmd
---> Running in 3d7cd429d659
---> Removed intermediate container 3d7cd429d659
---> 2ad69db4c288
Step 21/35 : RUN CGO_ENABLED=0 GOOS=linux go build -trimpath -ldflags="-s -w" -o /out/reconcile ./cmd/reconcile
---> Running in 7b9a510ed472
---> Removed intermediate container 7b9a510ed472
---> 4a49dc2719a3
Step 22/35 : FROM builder AS tests
---> 4a49dc2719a3
Step 23/35 : COPY --from=goose-builder /out/goose /usr/local/bin/goose
---> 5df1413dfc44
Step 24/35 : ENV GOOSE_MIGRATION_DIR=/src/migrations
---> Running in c30eee45a5e7
---> Removed intermediate container c30eee45a5e7
---> 173325b59e7d
Step 25/35 : CMD ["go", "test", "-p=1", "-race", "-count=1", "-v", "./..."]
---> Running in 384e08125582
---> Removed intermediate container 384e08125582
---> 187ea6b3bcac
Step 26/35 : FROM alpine:3.23@sha256:075c2c1a4068c1e251228ca2b0ea8b163f835ca5d66e758b93c7fc89b1995616
---> 075c2c1a4068
Step 27/35 : RUN addgroup -S messenger && adduser -S -D -H -u 10001 -G messenger messenger
---> Using cache
---> 33192b561bfc
Step 28/35 : COPY --from=builder --chown=messenger:messenger /out/messenger /usr/local/bin/messenger
---> 37a18e0c6edf
Step 29/35 : COPY --from=builder --chown=messenger:messenger /out/reconcile /usr/local/bin/reconcile
---> b0e79d0416ba
Step 30/35 : ENV PORT=8080
---> Running in 48da45f81d52
---> Removed intermediate container 48da45f81d52
---> a7c04e9ff97b
Step 31/35 : EXPOSE 8080
---> Running in 671ff92f3fad
---> Removed intermediate container 671ff92f3fad
---> e56b07b42f04
Step 32/35 : USER messenger:messenger
---> Running in 8003e4ea3b5d
---> Removed intermediate container 8003e4ea3b5d
---> 48b4424b156b
Step 33/35 : HEALTHCHECK --interval=10s --timeout=3s --start-period=3s --retries=3 CMD wget -q -O /dev/null "http://127.0.0.1:${PORT}/health/ready" || exit 1
---> Running in c05d11001e2b
---> Removed intermediate container c05d11001e2b
---> 563fbe4dcd7d
Step 34/35 : STOPSIGNAL SIGTERM
---> Running in 8fb80a0e0f6c
---> Removed intermediate container 8fb80a0e0f6c
---> c5a0a88ba147
Step 35/35 : ENTRYPOINT ["/usr/local/bin/messenger"]
---> Running in 9e51b29d5939
---> Removed intermediate container 9e51b29d5939
---> c28dcd6e4410
Successfully built c28dcd6e4410
Successfully tagged mtusi-messenger:lab4
+313
View File
@@ -0,0 +1,313 @@
.venv/bin/python scripts/swarm.py up
vphhh79vd5ti8501q6m9lzulj
Local secrets are ready.
DEPRECATED: The legacy builder is deprecated and will be removed in a future release.
Install the buildx component to build images with BuildKit:
https://docs.docker.com/go/buildx/
Sending build context to Docker daemon 398.8kB␍
Step 1/20 : FROM golang:1.26.4-alpine3.23@sha256:18b460dd17542c2ba43299a633cf6ebfc1115101509531471d7cfce1019af083 AS minio-builder
---> 18b460dd1754
Step 2/20 : ADD --checksum=sha256:8b11129f6a6830768bcdebab569290ad956618f5ff6ef4857b633acb64f95126 https://codeload.github.com/minio/minio/tar.gz/01ce918d8279a20e4706b96a64396146894adee4 /tmp/source.tar.gz
---> Using cache
---> 4a2b9310629e
Step 3/20 : RUN mkdir /src && tar -xzf /tmp/source.tar.gz -C /src --strip-components=1
---> Using cache
---> 5166de215d05
Step 4/20 : WORKDIR /src
---> Using cache
---> 1f12c7444ff0
Step 5/20 : RUN CGO_ENABLED=0 go build -trimpath -ldflags='-s -w' -o /out/minio .
---> Using cache
---> 8477e9d7324c
Step 6/20 : RUN echo '8b11129f6a6830768bcdebab569290ad956618f5ff6ef4857b633acb64f95126 /tmp/source.tar.gz' | sha256sum -c -
---> Using cache
---> 94162de69c8c
Step 7/20 : FROM golang:1.26.4-alpine3.23@sha256:18b460dd17542c2ba43299a633cf6ebfc1115101509531471d7cfce1019af083 AS mc-builder
---> 18b460dd1754
Step 8/20 : ADD --checksum=sha256:4cea8ed209c8f96e59ea1a5cc4901019b54c2be6d6f5f16c6749ea8bdcf4172e https://codeload.github.com/minio/mc/tar.gz/d6541ea280b73a834b64d4097e21f2be77676104 /tmp/source.tar.gz
---> Using cache
---> 5e135fc72a2c
Step 9/20 : RUN mkdir /src && tar -xzf /tmp/source.tar.gz -C /src --strip-components=1
---> Using cache
---> cbffdcf35dd5
Step 10/20 : WORKDIR /src
---> Using cache
---> 3322378e2ebd
Step 11/20 : RUN CGO_ENABLED=0 go build -trimpath -ldflags='-s -w' -o /out/mc .
---> Using cache
---> 0aba858f1d48
Step 12/20 : RUN echo '4cea8ed209c8f96e59ea1a5cc4901019b54c2be6d6f5f16c6749ea8bdcf4172e /tmp/source.tar.gz' | sha256sum -c -
---> Using cache
---> af0a57fdfed1
Step 13/20 : FROM alpine:3.23@sha256:075c2c1a4068c1e251228ca2b0ea8b163f835ca5d66e758b93c7fc89b1995616 AS minio
---> 075c2c1a4068
Step 14/20 : LABEL org.opencontainers.image.source="https://github.com/minio/minio" org.opencontainers.image.revision="01ce918d8279a20e4706b96a64396146894adee4" org.opencontainers.image.version="RELEASE.2025-09-07T16-13-09Z" org.opencontainers.image.licenses="AGPL-3.0"
---> Using cache
---> 57200264604d
Step 15/20 : RUN mkdir /data && chown 10001:10001 /data
---> Using cache
---> c7024406f9a9
Step 16/20 : COPY --from=minio-builder /out/minio /usr/local/bin/minio
---> Using cache
---> 0d1965ab7125
Step 17/20 : COPY infra/minio-entrypoint.sh /usr/local/bin/start-minio
---> Using cache
---> e5c21da70a4f
Step 18/20 : USER 10001:10001
---> Using cache
---> 9bc52122d9f2
Step 19/20 : EXPOSE 9000
---> Using cache
---> 2ca448e77273
Step 20/20 : ENTRYPOINT ["/usr/local/bin/start-minio"]
---> Using cache
---> 3a0797aa5ead
Successfully built 3a0797aa5ead
Successfully tagged mtusi-minio:RELEASE.2025-09-07T16-13-09Z
DEPRECATED: The legacy builder is deprecated and will be removed in a future release.
Install the buildx component to build images with BuildKit:
https://docs.docker.com/go/buildx/
Sending build context to Docker daemon 398.8kB␍
Step 1/25 : FROM golang:1.26.4-alpine3.23@sha256:18b460dd17542c2ba43299a633cf6ebfc1115101509531471d7cfce1019af083 AS minio-builder
---> 18b460dd1754
Step 2/25 : ADD --checksum=sha256:8b11129f6a6830768bcdebab569290ad956618f5ff6ef4857b633acb64f95126 https://codeload.github.com/minio/minio/tar.gz/01ce918d8279a20e4706b96a64396146894adee4 /tmp/source.tar.gz
---> Using cache
---> 4a2b9310629e
Step 3/25 : RUN mkdir /src && tar -xzf /tmp/source.tar.gz -C /src --strip-components=1
---> Using cache
---> 5166de215d05
Step 4/25 : WORKDIR /src
---> Using cache
---> 1f12c7444ff0
Step 5/25 : RUN CGO_ENABLED=0 go build -trimpath -ldflags='-s -w' -o /out/minio .
---> Using cache
---> 8477e9d7324c
Step 6/25 : RUN echo '8b11129f6a6830768bcdebab569290ad956618f5ff6ef4857b633acb64f95126 /tmp/source.tar.gz' | sha256sum -c -
---> Using cache
---> 94162de69c8c
Step 7/25 : FROM golang:1.26.4-alpine3.23@sha256:18b460dd17542c2ba43299a633cf6ebfc1115101509531471d7cfce1019af083 AS mc-builder
---> 18b460dd1754
Step 8/25 : ADD --checksum=sha256:4cea8ed209c8f96e59ea1a5cc4901019b54c2be6d6f5f16c6749ea8bdcf4172e https://codeload.github.com/minio/mc/tar.gz/d6541ea280b73a834b64d4097e21f2be77676104 /tmp/source.tar.gz
---> Using cache
---> 5e135fc72a2c
Step 9/25 : RUN mkdir /src && tar -xzf /tmp/source.tar.gz -C /src --strip-components=1
---> Using cache
---> cbffdcf35dd5
Step 10/25 : WORKDIR /src
---> Using cache
---> 3322378e2ebd
Step 11/25 : RUN CGO_ENABLED=0 go build -trimpath -ldflags='-s -w' -o /out/mc .
---> Using cache
---> 0aba858f1d48
Step 12/25 : RUN echo '4cea8ed209c8f96e59ea1a5cc4901019b54c2be6d6f5f16c6749ea8bdcf4172e /tmp/source.tar.gz' | sha256sum -c -
---> Using cache
---> af0a57fdfed1
Step 13/25 : FROM alpine:3.23@sha256:075c2c1a4068c1e251228ca2b0ea8b163f835ca5d66e758b93c7fc89b1995616 AS minio
---> 075c2c1a4068
Step 14/25 : LABEL org.opencontainers.image.source="https://github.com/minio/minio" org.opencontainers.image.revision="01ce918d8279a20e4706b96a64396146894adee4" org.opencontainers.image.version="RELEASE.2025-09-07T16-13-09Z" org.opencontainers.image.licenses="AGPL-3.0"
---> Using cache
---> 57200264604d
Step 15/25 : RUN mkdir /data && chown 10001:10001 /data
---> Using cache
---> c7024406f9a9
Step 16/25 : COPY --from=minio-builder /out/minio /usr/local/bin/minio
---> Using cache
---> 0d1965ab7125
Step 17/25 : COPY infra/minio-entrypoint.sh /usr/local/bin/start-minio
---> Using cache
---> e5c21da70a4f
Step 18/25 : USER 10001:10001
---> Using cache
---> 9bc52122d9f2
Step 19/25 : EXPOSE 9000
---> Using cache
---> 2ca448e77273
Step 20/25 : ENTRYPOINT ["/usr/local/bin/start-minio"]
---> Using cache
---> 3a0797aa5ead
Step 21/25 : FROM alpine:3.23@sha256:075c2c1a4068c1e251228ca2b0ea8b163f835ca5d66e758b93c7fc89b1995616 AS mc
---> 075c2c1a4068
Step 22/25 : LABEL org.opencontainers.image.source="https://github.com/minio/mc" org.opencontainers.image.revision="d6541ea280b73a834b64d4097e21f2be77676104" org.opencontainers.image.version="RELEASE.2025-08-13T08-35-41Z" org.opencontainers.image.licenses="AGPL-3.0"
---> Using cache
---> 9257dca2de26
Step 23/25 : COPY --from=mc-builder /out/mc /usr/local/bin/mc
---> Using cache
---> 4bea21e69e8d
Step 24/25 : USER 10001:10001
---> Using cache
---> 45d00b9fce3e
Step 25/25 : ENTRYPOINT ["mc"]
---> Using cache
---> 0713832dbf4a
Successfully built 0713832dbf4a
Successfully tagged mtusi-mc:RELEASE.2025-08-13T08-35-41Z
DEPRECATED: The legacy builder is deprecated and will be removed in a future release.
Install the buildx component to build images with BuildKit:
https://docs.docker.com/go/buildx/
Sending build context to Docker daemon 398.3kB␍
Step 1/35 : FROM golang:1.26.4-alpine3.23@sha256:18b460dd17542c2ba43299a633cf6ebfc1115101509531471d7cfce1019af083 AS goose-builder
---> 18b460dd1754
Step 2/35 : RUN GOBIN=/out CGO_ENABLED=0 go install -tags='no_clickhouse no_libsql no_mssql no_mysql no_sqlite3 no_vertica no_ydb no_spanner' github.com/pressly/goose/v3/cmd/goose@v3.27.1
---> Using cache
---> 7012ef857c0c
Step 3/35 : FROM alpine:3.23@sha256:075c2c1a4068c1e251228ca2b0ea8b163f835ca5d66e758b93c7fc89b1995616 AS migrations
---> 075c2c1a4068
Step 4/35 : COPY --from=goose-builder /out/goose /usr/local/bin/goose
---> Using cache
---> 6a0ad52336c1
Step 5/35 : COPY migrations /migrations
---> Using cache
---> 19018c7bfac9
Step 6/35 : COPY infra/migrate.sh /usr/local/bin/migrate
---> Using cache
---> 0cc075ba3459
Step 7/35 : USER 10001:10001
---> Using cache
---> 37de51af32cd
Step 8/35 : ENTRYPOINT ["/usr/local/bin/migrate"]
---> Using cache
---> e7539a967679
Step 9/35 : CMD ["up"]
---> Using cache
---> 841d9bb239cd
Step 10/35 : FROM golang:1.26.4-alpine3.23@sha256:18b460dd17542c2ba43299a633cf6ebfc1115101509531471d7cfce1019af083 AS builder
---> 18b460dd1754
Step 11/35 : WORKDIR /src
---> Using cache
---> 1ba013278a4a
Step 12/35 : RUN apk add --no-cache gcc musl-dev
---> Using cache
---> a0ea65f0bded
Step 13/35 : COPY go.mod go.sum ./
---> Using cache
---> e98ccecfb093
Step 14/35 : RUN go mod download
---> Using cache
---> 91d546c71507
Step 15/35 : COPY cmd ./cmd
---> Using cache
---> b4e431a9d5f2
Step 16/35 : COPY contracts ./contracts
---> Using cache
---> 958477d6c98e
Step 17/35 : COPY dto ./dto
---> Using cache
---> d115fe2e1af4
Step 18/35 : COPY internal ./internal
---> Using cache
---> 72552b328db4
Step 19/35 : COPY migrations ./migrations
---> Using cache
---> a68ac4a31860
Step 20/35 : RUN CGO_ENABLED=0 GOOS=linux go build -trimpath -ldflags="-s -w" -o /out/messenger ./cmd
---> Using cache
---> 7303ceff230d
Step 21/35 : RUN CGO_ENABLED=0 GOOS=linux go build -trimpath -ldflags="-s -w" -o /out/reconcile ./cmd/reconcile
---> Using cache
---> e6cc7991dac9
Step 22/35 : FROM builder AS tests
---> e6cc7991dac9
Step 23/35 : COPY --from=goose-builder /out/goose /usr/local/bin/goose
---> Using cache
---> 5749aa2abe35
Step 24/35 : ENV GOOSE_MIGRATION_DIR=/src/migrations
---> Using cache
---> ca0a6f733ba8
Step 25/35 : CMD ["go", "test", "-p=1", "-race", "-count=1", "-v", "./..."]
---> Using cache
---> c643755b8aac
Step 26/35 : FROM alpine:3.23@sha256:075c2c1a4068c1e251228ca2b0ea8b163f835ca5d66e758b93c7fc89b1995616
---> 075c2c1a4068
Step 27/35 : RUN addgroup -S messenger && adduser -S -D -H -u 10001 -G messenger messenger
---> Using cache
---> 33192b561bfc
Step 28/35 : COPY --from=builder --chown=messenger:messenger /out/messenger /usr/local/bin/messenger
---> Using cache
---> 136320eda1d3
Step 29/35 : COPY --from=builder --chown=messenger:messenger /out/reconcile /usr/local/bin/reconcile
---> Using cache
---> 4acf2a8fc638
Step 30/35 : ENV PORT=8080
---> Using cache
---> 6fbea06a8135
Step 31/35 : EXPOSE 8080
---> Using cache
---> 333a62acf202
Step 32/35 : USER messenger:messenger
---> Using cache
---> 60a29210a7f2
Step 33/35 : HEALTHCHECK --interval=10s --timeout=3s --start-period=3s --retries=3 CMD wget -q -O /dev/null "http://127.0.0.1:${PORT}/health/ready" || exit 1
---> Using cache
---> 803ac1f944e5
Step 34/35 : STOPSIGNAL SIGTERM
---> Using cache
---> 40299d0a0f9f
Step 35/35 : ENTRYPOINT ["/usr/local/bin/messenger"]
---> Using cache
---> c81ae0702578
Successfully built c81ae0702578
Successfully tagged mtusi-messenger:lab4
DEPRECATED: The legacy builder is deprecated and will be removed in a future release.
Install the buildx component to build images with BuildKit:
https://docs.docker.com/go/buildx/
Sending build context to Docker daemon 398.3kB␍
Step 1/9 : FROM golang:1.26.4-alpine3.23@sha256:18b460dd17542c2ba43299a633cf6ebfc1115101509531471d7cfce1019af083 AS goose-builder
---> 18b460dd1754
Step 2/9 : RUN GOBIN=/out CGO_ENABLED=0 go install -tags='no_clickhouse no_libsql no_mssql no_mysql no_sqlite3 no_vertica no_ydb no_spanner' github.com/pressly/goose/v3/cmd/goose@v3.27.1
---> Using cache
---> 7012ef857c0c
Step 3/9 : FROM alpine:3.23@sha256:075c2c1a4068c1e251228ca2b0ea8b163f835ca5d66e758b93c7fc89b1995616 AS migrations
---> 075c2c1a4068
Step 4/9 : COPY --from=goose-builder /out/goose /usr/local/bin/goose
---> Using cache
---> 6a0ad52336c1
Step 5/9 : COPY migrations /migrations
---> Using cache
---> 19018c7bfac9
Step 6/9 : COPY infra/migrate.sh /usr/local/bin/migrate
---> Using cache
---> 0cc075ba3459
Step 7/9 : USER 10001:10001
---> Using cache
---> 37de51af32cd
Step 8/9 : ENTRYPOINT ["/usr/local/bin/migrate"]
---> Using cache
---> e7539a967679
Step 9/9 : CMD ["up"]
---> Using cache
---> 841d9bb239cd
Successfully built 841d9bb239cd
Successfully tagged mtusi-migrations:lab4
kkk3r78zn9bb09xudyehchs4p
mtusi-lab4_migrations.0.mzx2ds4dsbyh@colima | 2026/10/28 19:14:47 OK 001_initial.sql (17.71ms)
mtusi-lab4_migrations.0.mzx2ds4dsbyh@colima | 2026/10/28 19:14:47 OK 002_idempotency.sql (2.54ms)
mtusi-lab4_migrations.0.mzx2ds4dsbyh@colima | 2026/10/28 19:14:47 OK 003_attachments.sql (5.13ms)
mtusi-lab4_migrations.0.mzx2ds4dsbyh@colima | 2026/10/28 19:14:47 OK 004_message_attachments.sql (2.34ms)
mtusi-lab4_migrations.0.mzx2ds4dsbyh@colima | 2026/10/28 19:14:47 goose: successfully migrated database to version: 4
mtusi-lab4_migrations
Since --detach=false was not specified, tasks will be created in the background.
In a future release, --detach=false will become the default.
Updating service mtusi-lab4_redis (id: zlhenabo1vgqarsazgqa6d897)
Updating service mtusi-lab4_minio (id: ygvoo1fje6vqlxw02ugw7awa8)
Updating service mtusi-lab4_api (id: xiueb8lcewfukmzn8wocqcmjh)
Updating service mtusi-lab4_lb (id: uo65o8allz5azrqbx4zchi811)
Updating service mtusi-lab4_postgres (id: vxi6yu73ah85o0xog5w8r1t5k)
f6qbximmjnxx8ezv05jxgsngz
mtusi-lab4_s3-bootstrap.0.p9vksdlsfz2l@colima | PASS: private bucket and restricted API account configured.
mtusi-lab4_s3-bootstrap
mtusi-lab4_api scaled to 2
mtusi-lab4_api
PASS: rolling update completed
PASS: Swarm stack ready at http://localhost:8080
+81
View File
@@ -0,0 +1,81 @@
{
"docker_engine": {
"cpus": 2,
"memory_bytes": 2053644288,
"os": "Ubuntu 24.04.4 LTS",
"kernel": "6.8.0-117-generic",
"architecture": "aarch64",
"version": "29.5.2"
},
"host": {
"architecture": "arm64",
"system": "Darwin",
"model": "MacBookPro18,3",
"cpu_cores": 8,
"memory_bytes": 17179869184
},
"host_go": "go version go1.27.2 darwin/arm64",
"host_python": "3.9.6",
"images": [
{
"tag": "mtusi-messenger:lab4",
"image_id": "sha256:c28dcd6e4410ee011a827852286b93296c8a0f20ddb268524b4d92371014403e",
"repo_digests": [
"mtusi-messenger@sha256:c28dcd6e4410ee011a827852286b93296c8a0f20ddb268524b4d92371014403e"
],
"source_labels": {}
},
{
"tag": "mtusi-minio:RELEASE.2025-09-07T16-13-09Z",
"image_id": "sha256:3a0797aa5eadafe23e8a7b205c39511a9280b7500da6ef0e5d604cc74f46c3ed",
"repo_digests": [
"mtusi-minio@sha256:3a0797aa5eadafe23e8a7b205c39511a9280b7500da6ef0e5d604cc74f46c3ed"
],
"source_labels": {
"org.opencontainers.image.licenses": "AGPL-3.0",
"org.opencontainers.image.revision": "01ce918d8279a20e4706b96a64396146894adee4",
"org.opencontainers.image.source": "https://github.com/minio/minio",
"org.opencontainers.image.version": "RELEASE.2025-09-07T16-13-09Z"
}
},
{
"tag": "mtusi-mc:RELEASE.2025-08-13T08-35-41Z",
"image_id": "sha256:0713832dbf4ab9a3b716ab0a4cca6629fec96224bc1425f26ab6ba42c5463a99",
"repo_digests": [
"mtusi-mc@sha256:0713832dbf4ab9a3b716ab0a4cca6629fec96224bc1425f26ab6ba42c5463a99"
],
"source_labels": {
"org.opencontainers.image.licenses": "AGPL-3.0",
"org.opencontainers.image.revision": "d6541ea280b73a834b64d4097e21f2be77676104",
"org.opencontainers.image.source": "https://github.com/minio/mc",
"org.opencontainers.image.version": "RELEASE.2025-08-13T08-35-41Z"
}
},
{
"tag": "postgres:17.6-alpine3.22",
"image_id": "sha256:ef257d85f76e48da1c64832459b59fcaba1a4dac97bf5d7450c77753542eee94",
"repo_digests": [
"postgres@sha256:ef257d85f76e48da1c64832459b59fcaba1a4dac97bf5d7450c77753542eee94"
],
"source_labels": {}
},
{
"tag": "redis:7.4.5-alpine3.21",
"image_id": "sha256:bb186d083732f669da90be8b0f975a37812b15e913465bb14d845db72a4e3e08",
"repo_digests": [
"redis@sha256:bb186d083732f669da90be8b0f975a37812b15e913465bb14d845db72a4e3e08"
],
"source_labels": {}
},
{
"tag": "haproxy:3.2.6-alpine",
"image_id": "sha256:3a819392f5a6af2a9203d1c63ff0feba74f0c940623a558511be06d7d85e361c",
"repo_digests": [
"haproxy@sha256:3a819392f5a6af2a9203d1c63ff0feba74f0c940623a558511be06d7d85e361c"
],
"source_labels": {}
}
],
"go_container_version": "1.26.4",
"test_data": "synthetic; no credentials/tokens saved"
}
+4
View File
@@ -0,0 +1,4 @@
.venv/bin/python 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": 112, "failed_attempts": 2, "first_recovery_seconds": 2.061}
PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence.
+13
View File
@@ -0,0 +1,13 @@
? gitflic.ru/akselbant/mtusi2026lab1-fork/cmd [no test files]
? gitflic.ru/akselbant/mtusi2026lab1-fork/cmd/reconcile [no test files]
? gitflic.ru/akselbant/mtusi2026lab1-fork/contracts [no test files]
ok gitflic.ru/akselbant/mtusi2026lab1-fork/dto (cached)
ok gitflic.ru/akselbant/mtusi2026lab1-fork/internal/app/chat 13.184s
ok gitflic.ru/akselbant/mtusi2026lab1-fork/internal/attachment 2.905s
? gitflic.ru/akselbant/mtusi2026lab1-fork/internal/config [no test files]
? gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain [no test files]
ok gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/password (cached)
? gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/repository [no test files]
ok gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/repository/postgres 2.388s
? gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/session [no test files]
ok gitflic.ru/akselbant/mtusi2026lab1-fork/internal/usecase/chat (cached)
+338
View File
@@ -0,0 +1,338 @@
.venv/bin/python scripts/swarm.py test-integration
DEPRECATED: The legacy builder is deprecated and will be removed in a future release.
Install the buildx component to build images with BuildKit:
https://docs.docker.com/go/buildx/
Sending build context to Docker daemon 398.3kB␍
Step 1/25 : FROM golang:1.26.4-alpine3.23@sha256:18b460dd17542c2ba43299a633cf6ebfc1115101509531471d7cfce1019af083 AS goose-builder
---> 18b460dd1754
Step 2/25 : RUN GOBIN=/out CGO_ENABLED=0 go install -tags='no_clickhouse no_libsql no_mssql no_mysql no_sqlite3 no_vertica no_ydb no_spanner' github.com/pressly/goose/v3/cmd/goose@v3.27.1
---> Using cache
---> 7012ef857c0c
Step 3/25 : FROM alpine:3.23@sha256:075c2c1a4068c1e251228ca2b0ea8b163f835ca5d66e758b93c7fc89b1995616 AS migrations
---> 075c2c1a4068
Step 4/25 : COPY --from=goose-builder /out/goose /usr/local/bin/goose
---> Using cache
---> 6a0ad52336c1
Step 5/25 : COPY migrations /migrations
---> Using cache
---> 19018c7bfac9
Step 6/25 : COPY infra/migrate.sh /usr/local/bin/migrate
---> Using cache
---> 0cc075ba3459
Step 7/25 : USER 10001:10001
---> Using cache
---> 37de51af32cd
Step 8/25 : ENTRYPOINT ["/usr/local/bin/migrate"]
---> Using cache
---> e7539a967679
Step 9/25 : CMD ["up"]
---> Using cache
---> 841d9bb239cd
Step 10/25 : FROM golang:1.26.4-alpine3.23@sha256:18b460dd17542c2ba43299a633cf6ebfc1115101509531471d7cfce1019af083 AS builder
---> 18b460dd1754
Step 11/25 : WORKDIR /src
---> Using cache
---> 1ba013278a4a
Step 12/25 : RUN apk add --no-cache gcc musl-dev
---> Using cache
---> a0ea65f0bded
Step 13/25 : COPY go.mod go.sum ./
---> Using cache
---> e98ccecfb093
Step 14/25 : RUN go mod download
---> Using cache
---> 91d546c71507
Step 15/25 : COPY cmd ./cmd
---> Using cache
---> b4e431a9d5f2
Step 16/25 : COPY contracts ./contracts
---> Using cache
---> 958477d6c98e
Step 17/25 : COPY dto ./dto
---> Using cache
---> d115fe2e1af4
Step 18/25 : COPY internal ./internal
---> Using cache
---> 72552b328db4
Step 19/25 : COPY migrations ./migrations
---> Using cache
---> a68ac4a31860
Step 20/25 : RUN CGO_ENABLED=0 GOOS=linux go build -trimpath -ldflags="-s -w" -o /out/messenger ./cmd
---> Using cache
---> 7303ceff230d
Step 21/25 : RUN CGO_ENABLED=0 GOOS=linux go build -trimpath -ldflags="-s -w" -o /out/reconcile ./cmd/reconcile
---> Using cache
---> e6cc7991dac9
Step 22/25 : FROM builder AS tests
---> e6cc7991dac9
Step 23/25 : COPY --from=goose-builder /out/goose /usr/local/bin/goose
---> Using cache
---> 5749aa2abe35
Step 24/25 : ENV GOOSE_MIGRATION_DIR=/src/migrations
---> Using cache
---> ca0a6f733ba8
Step 25/25 : CMD ["go", "test", "-p=1", "-race", "-count=1", "-v", "./..."]
---> Using cache
---> c643755b8aac
Successfully built c643755b8aac
Successfully tagged mtusi-messenger-tests:lab4
qs9c5xskdu6nyjiv287eg68b8
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | ? gitflic.ru/akselbant/mtusi2026lab1-fork/cmd [no test files]
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | ? gitflic.ru/akselbant/mtusi2026lab1-fork/cmd/reconcile [no test files]
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | ? gitflic.ru/akselbant/mtusi2026lab1-fork/contracts [no test files]
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | === RUN TestMessageStrictFields
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | --- PASS: TestMessageStrictFields (0.00s)
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | === RUN TestTimestampFixedMicroseconds
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | --- PASS: TestTimestampFixedMicroseconds (0.00s)
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | PASS
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | ok gitflic.ru/akselbant/mtusi2026lab1-fork/dto 1.013s
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | === RUN TestRejectsMalformedJSON
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:40 request_id=94533522-1e48-4953-9857-91c107c2aac7 method=POST path=/api/v1/users status=400 response_bytes=140 latency=130.671µs
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | --- PASS: TestRejectsMalformedJSON (0.01s)
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | === RUN TestHidesForeignChat
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:40 request_id=8b136f4b-a1b6-4756-9dda-92871979845c method=POST path=/api/v1/users status=201 response_bytes=141 latency=369.112982ms
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:41 request_id=df98ca4b-5f1f-4ef1-a8eb-7708ccfe2367 method=POST path=/api/v1/auth/sessions status=201 response_bytes=269 latency=397.145342ms
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:41 request_id=c535a54a-6ce6-49b0-8ec7-47e70ea04799 method=POST path=/api/v1/users status=201 response_bytes=147 latency=364.216754ms
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:41 request_id=fea0410a-7349-4fc3-8541-f479066736b7 method=POST path=/api/v1/auth/sessions status=201 response_bytes=275 latency=359.930021ms
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:41 request_id=b7201791-c957-4ee8-8237-2aab675777ec method=POST path=/api/v1/chats status=201 response_bytes=163 latency=174.381µs
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:41 request_id=30b379c6-e33c-42bc-963a-54de252a1e44 method=GET path=/api/v1/chats/:chat_id status=404 response_bytes=126 latency=53.002µs
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | --- PASS: TestHidesForeignChat (1.50s)
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | === RUN TestRejectsEmptyMessage
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:42 request_id=92d81694-3fcf-452b-be3d-24e21f938fb8 method=POST path=/api/v1/users status=201 response_bytes=157 latency=411.707889ms
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:42 request_id=792cc573-4974-4744-86bc-7ce29f78c5a2 method=POST path=/api/v1/auth/sessions status=201 response_bytes=285 latency=357.462544ms
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:42 request_id=4aec085d-f3fe-4b56-a0f2-b6bb55c32fd5 method=POST path=/api/v1/chats status=201 response_bytes=163 latency=135.922µs
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:42 request_id=bae49af4-9cb9-414e-8227-7991f680a0ab method=POST path=/api/v1/chats/:chat_id/messages status=400 response_bytes=172 latency=150.047µs
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | --- PASS: TestRejectsEmptyMessage (0.77s)
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | === RUN TestRejectsDuplicateUsername
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:42 request_id=c6f9b126-b2a0-4672-b4de-a59183cffe86 method=POST path=/api/v1/users status=201 response_bytes=149 latency=370.366912ms
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:43 request_id=c174982c-6a8d-4fc7-8d4b-6cbe68b34d70 method=POST path=/api/v1/auth/sessions status=201 response_bytes=277 latency=365.829696ms
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:43 request_id=b8771b83-4e05-4335-a6bd-4de115eb5e20 method=POST path=/api/v1/users status=409 response_bytes=170 latency=358.448604ms
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | --- PASS: TestRejectsDuplicateUsername (1.10s)
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | === RUN TestPaginatesMessagesAcrossMultiplePages
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:44 request_id=fb5f658b-7688-4017-9758-bea1d60af1cf method=POST path=/api/v1/users status=201 response_bytes=151 latency=366.583521ms
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:44 request_id=ddf8c2e9-34d2-4b17-aaa5-66ee679b9a4b method=POST path=/api/v1/auth/sessions status=201 response_bytes=279 latency=393.325397ms
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:44 request_id=32abde1e-d2e7-46fe-ad10-210533f83bd5 method=POST path=/api/v1/chats status=201 response_bytes=163 latency=136.838µs
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:44 request_id=227b702f-3d9d-4307-a1a8-30ab4f7aa8f2 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=228 latency=217.05µs
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:44 request_id=edc8c38d-6beb-4353-b6c1-d1c8f337282b method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=228 latency=132.629µs
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:44 request_id=27b25c6f-8b85-4f74-9a26-bc175b6e490f method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=228 latency=120.337µs
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:44 request_id=148f8872-b793-4898-a57f-78f66d57fbb6 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=228 latency=115.879µs
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:44 request_id=d2b4fae7-2633-4406-920a-af6bad40e7c9 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=228 latency=113.254µs
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:44 request_id=65190391-2026-4f9e-b907-b52379ad8afe method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=228 latency=141.005µs
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:44 request_id=094c52b2-7bb7-4ba0-be47-2695d64f4867 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=228 latency=181.464µs
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:44 request_id=ebf5592b-9a0e-4ea4-8fa7-b7d2eb14639e method=GET path=/api/v1/chats/:chat_id/messages status=200 response_bytes=725 latency=304.594µs
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:44 request_id=c0d34ec3-f7c3-4639-8160-d6e32d09ff42 method=GET path=/api/v1/chats/:chat_id/messages status=200 response_bytes=725 latency=180.132µs
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:44 request_id=0e2daae8-eec7-4e5e-a222-2f11927517a0 method=GET path=/api/v1/chats/:chat_id/messages status=200 response_bytes=725 latency=168.339µs
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:44 request_id=b8dc3150-f39e-4d7b-a0af-38ffa5a8936d method=GET path=/api/v1/chats/:chat_id/messages status=200 response_bytes=259 latency=110.796µs
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | --- PASS: TestPaginatesMessagesAcrossMultiplePages (0.77s)
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | === RUN TestConcurrentMessagesAreUnique
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:44 request_id=a35f6c93-191f-4fe2-8640-6390ceab09fc method=POST path=/api/v1/users status=201 response_bytes=153 latency=372.343576ms
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:45 request_id=4dd49805-f2ef-4166-b188-ebbbc1924d9a method=POST path=/api/v1/auth/sessions status=201 response_bytes=281 latency=371.622652ms
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:45 request_id=745e9e01-1f34-4e95-81fe-6a3ae7cf9ea4 method=POST path=/api/v1/users status=201 response_bytes=153 latency=394.884355ms
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:45 request_id=95ac49aa-2560-42da-90c1-902d76341ccd method=POST path=/api/v1/auth/sessions status=201 response_bytes=281 latency=358.911214ms
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:46 request_id=249bef9d-e9fb-462a-99c3-1946037d1d0c method=POST path=/api/v1/users status=201 response_bytes=153 latency=374.597959ms
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:46 request_id=ef3349aa-4db5-4ab6-998e-50fa2f3262bb method=POST path=/api/v1/auth/sessions status=201 response_bytes=281 latency=364.93841ms
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:47 request_id=3007dbff-cdb7-42b9-ac50-77dc7c2ebc4f method=POST path=/api/v1/users status=201 response_bytes=153 latency=396.618954ms
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:47 request_id=01f269ef-e3c5-4240-9070-37312feb0e6b method=POST path=/api/v1/auth/sessions status=201 response_bytes=281 latency=372.262695ms
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:47 request_id=ab7c6c66-e836-4704-a516-3c4b51322e74 method=POST path=/api/v1/users status=201 response_bytes=153 latency=358.500208ms
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:48 request_id=b5f8edd3-d534-401f-8e68-fac601795f3f method=POST path=/api/v1/auth/sessions status=201 response_bytes=281 latency=369.620285ms
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:48 request_id=1362a848-874b-4b9b-b7fe-735ae74cc76d method=POST path=/api/v1/users status=201 response_bytes=153 latency=401.141119ms
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:49 request_id=953f6f2b-9fd3-49c5-b660-94a56615c24c method=POST path=/api/v1/auth/sessions status=201 response_bytes=281 latency=376.048273ms
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:49 request_id=56532a32-ca19-4238-b539-486b339d0bbb method=POST path=/api/v1/users status=201 response_bytes=153 latency=365.0437ms
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:49 request_id=89c7cf01-2523-4ae6-9a85-dd1a76a61039 method=POST path=/api/v1/auth/sessions status=201 response_bytes=281 latency=362.393272ms
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:50 request_id=0af98040-fde9-4694-a646-c60f794e097f method=POST path=/api/v1/users status=201 response_bytes=153 latency=360.604883ms
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:50 request_id=92c16b19-7579-47aa-9fb0-a3595b644fc7 method=POST path=/api/v1/auth/sessions status=201 response_bytes=281 latency=373.615906ms
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:50 request_id=460293e1-83ce-4a90-9255-cea43854fe3f method=POST path=/api/v1/users status=201 response_bytes=153 latency=366.494027ms
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:51 request_id=f564332d-7da7-40c0-9842-20cf89412495 method=POST path=/api/v1/auth/sessions status=201 response_bytes=281 latency=375.265646ms
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:51 request_id=62b8365d-f837-4354-8383-1456f1b72154 method=POST path=/api/v1/users status=201 response_bytes=153 latency=358.727985ms
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:51 request_id=a2a37a46-5e62-41e6-bfa3-2bce4c2e3ad8 method=POST path=/api/v1/auth/sessions status=201 response_bytes=281 latency=395.19545ms
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:51 request_id=5267f89c-aaf1-47b4-8c6a-9714ca727915 method=POST path=/api/v1/chats status=201 response_bytes=514 latency=188.799µs
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:51 request_id=c5b24f54-0511-46a1-82e5-0061ec77cb32 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=239 latency=208.924µs
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:51 request_id=f72ec60f-87ae-4bf6-b996-ce192a118119 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=239 latency=159.047µs
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:51 request_id=8afe7b58-5dce-42a1-adf2-1145ac360d45 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=239 latency=148.63µs
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:51 request_id=7b09b2e8-26b4-42af-bee4-016a8e269a6b method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=239 latency=160.922µs
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:51 request_id=81276d1e-5a76-4f9b-a7aa-f9857012dc26 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=239 latency=260.717µs
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:51 request_id=8904e3d2-be95-47dc-a2fa-d3eaf50a3578 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=239 latency=142.714µs
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:51 request_id=a03ae327-db89-4091-b3af-578a51335de2 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=239 latency=216.716µs
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:51 request_id=a498db7b-49fb-4935-bb51-891c908fa4f8 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=239 latency=139.089µs
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:51 request_id=2c981e76-6d36-494c-89ba-3336d357095d method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=239 latency=140.255µs
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:51 request_id=b9b68e40-c117-4bc7-8f41-b16dd197571a method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=239 latency=150.047µs
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:51 request_id=7223bf26-18da-419a-a853-3b50f5f04a4b method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=239 latency=132.047µs
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:51 request_id=16cc739c-a6a1-4c4c-a0bb-ec393bab1534 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=239 latency=162.423µs
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:51 request_id=0aef904a-3e95-41de-b5b4-0bff73ed6722 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=239 latency=153.297µs
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:51 request_id=25534c61-60fe-4374-bfda-db1354ea6012 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=239 latency=145.714µs
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:51 request_id=53c00161-1317-49e3-84db-eb7c99300efa method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=239 latency=146.422µs
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:51 request_id=1adf4594-5a16-4773-bff0-1b097ab75276 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=239 latency=133.63µs
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:51 request_id=78902daf-2bbe-4307-a4d3-e6e9042a6291 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=239 latency=180.09µs
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:51 request_id=7d53cfa6-047a-48c8-8fef-59024e131a96 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=239 latency=185.173µs
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:51 request_id=b2942d4f-3e6a-4c91-8dbf-a32c6af07f43 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=239 latency=206.424µs
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:51 request_id=5760c94c-8ecd-4067-832b-11909584e440 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=239 latency=266.593µs
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:51 request_id=2b89e564-7bdd-4d5f-9e78-78445d1cbf70 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=239 latency=153.922µs
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:51 request_id=f8fe6364-dab9-4122-9364-cc8a4e8e3d75 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=239 latency=208.757µs
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:51 request_id=3af65a8b-625c-4fc7-ac62-bfbc353ac7a6 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=239 latency=151.214µs
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:51 request_id=755c991e-1d9e-4279-b187-d607b13823ff method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=239 latency=159.422µs
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:51 request_id=c36f80e6-63d2-4dc5-a2ee-01e6ab546ef3 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=239 latency=245.509µs
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:51 request_id=e03d69f4-1738-49f5-b579-cdf4a632cc45 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=239 latency=153.131µs
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:51 request_id=05255c0a-5b54-4b53-b714-08f15260687e method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=239 latency=180.423µs
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:51 request_id=70f18e4c-0cdf-40a9-9e45-048f73171b1d method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=239 latency=126.796µs
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:51 request_id=ed2a3480-d27e-44eb-bc85-bd088d0cd3a3 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=239 latency=192.631µs
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:51 request_id=51c5b7ad-f0a6-4127-aca2-1d300b973d21 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=239 latency=214.091µs
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:51 request_id=e8718af1-4fbd-4b3b-8189-9c066828773c method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=239 latency=151.922µs
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:51 request_id=cd61dc79-f672-45c5-91a5-797ac5bd8680 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=239 latency=170.214µs
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:51 request_id=e9226bfb-5572-4513-9a97-0e90e532cec1 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=239 latency=129.838µs
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:51 request_id=8286f6ba-c4cc-4eb9-8b10-da07785cf32a method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=239 latency=164.173µs
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:51 request_id=d85b2fd6-05bf-4f9b-818a-09ca9ae2df48 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=239 latency=142.005µs
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:51 request_id=0ba6f4c9-0162-48d9-b610-bf28b56d39cd method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=239 latency=144.339µs
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:51 request_id=296d49e0-2b8b-4493-9835-bee0c4f23261 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=239 latency=243.426µs
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:51 request_id=9cf7e296-e25f-4d63-a1db-de1c262e2b8c method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=239 latency=208.632µs
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:51 request_id=8fa7d17d-40d0-4dc6-a4bd-b6c514bceb4a method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=239 latency=133.171µs
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:51 request_id=9e1b6e9b-7487-446f-b948-175f7d88e714 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=239 latency=163.506µs
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:51 request_id=3cf21baa-455a-4dac-b8c2-732150d32af8 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=239 latency=323.762µs
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:51 request_id=688c501c-30c9-46bc-ba4d-9d6a9202200d method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=239 latency=572.521µs
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:51 request_id=65eefba1-b010-405b-b534-8e30d577d755 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=239 latency=503.852µs
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:51 request_id=988807ed-875a-4d13-be2c-eb083546e583 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=239 latency=193.299µs
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:51 request_id=0ae6f088-d7cb-4d57-a3db-bedb1d222bc7 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=239 latency=129.088µs
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:51 request_id=038588a3-1ed6-4c91-bb8c-de5e55113175 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=239 latency=320.887µs
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:51 request_id=ff151126-07e7-4100-a2af-e9765d071ca2 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=239 latency=762.652µs
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:51 request_id=4cf0b177-670d-41b1-aa74-dafd209611e3 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=239 latency=202.549µs
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:51 request_id=f893e111-2ccc-49a7-a34e-38c8248d5f3b method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=239 latency=145.422µs
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:51 request_id=ece5e0f5-e795-4d1e-8bfe-2722feed55f7 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=239 latency=150.047µs
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:51 request_id=45f9158b-a65f-4527-a741-2a8b3af800ac method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=239 latency=165.089µs
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:51 request_id=ddc311c8-9d3f-4977-a159-a4d1daff9bf9 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=239 latency=166.298µs
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:51 request_id=a0ab6cc9-4a7d-471e-9b65-932e3089cbc7 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=239 latency=165.84µs
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:51 request_id=76e8f478-d9dc-4443-9bb8-310b8e9dd45a method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=239 latency=266.51µs
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:51 request_id=96cb53f0-70bd-45aa-b735-6b5003310461 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=239 latency=353.721µs
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:51 request_id=f1dda2fb-4016-440f-9fb6-c95a024038e6 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=239 latency=169.048µs
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:51 request_id=e553ec3c-0ab2-4007-8363-48f94f36f000 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=239 latency=141.796µs
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:51 request_id=78043ec3-1ec7-4c62-970c-950382757345 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=239 latency=187.298µs
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:51 request_id=6222f780-9cdf-4d85-b99b-2897e61cbc43 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=239 latency=808.862µs
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:51 request_id=73702805-906e-46ed-b38a-0206be2646dc method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=239 latency=695.567µs
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:51 request_id=1186e970-9cb0-4db8-a44e-6d823c940ba7 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=239 latency=410.557µs
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:51 request_id=98aaedba-db19-4504-a633-8a057f94d54e method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=239 latency=311.22µs
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:51 request_id=92a3bfc9-1577-4a57-9bdd-351208fd7d93 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=239 latency=1.151249ms
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:51 request_id=015c2bd0-266c-478a-99c8-516c482aeebe method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=239 latency=266.801µs
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:51 request_id=664b2b6c-39ae-46d5-bed9-72caa9acb7f2 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=239 latency=249.759µs
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:51 request_id=286c54ea-04d6-4af2-b00e-8ab00720b2ac method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=239 latency=273.885µs
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:51 request_id=89ab422c-a181-43b7-8e4c-cbcdfe3c18b0 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=239 latency=1.459927ms
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:51 request_id=9bbdd304-3f76-4f00-85bb-3c964aefb553 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=239 latency=334.178µs
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:51 request_id=52dcf62b-df81-4c8f-8b60-c54965aaa140 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=239 latency=1.887567ms
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:52 request_id=68f8ee3e-6eec-4f40-9428-dbeff99fd58a method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=239 latency=1.955945ms
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:52 request_id=efa4cdeb-c02b-4332-a745-9ba14b490f76 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=239 latency=2.642094ms
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:52 request_id=73f2e45a-8d59-4540-b193-98f1a4dca76a method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=239 latency=486.101µs
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:52 request_id=c74d1c30-bde3-46d2-9b37-566419bf5376 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=239 latency=507.602µs
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:52 request_id=65789068-cb57-4684-82d8-e201be139913 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=239 latency=2.130868ms
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:52 request_id=fcffe674-7c32-4ee1-b34f-3841ac041030 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=239 latency=191.966µs
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:52 request_id=5ea31e02-1c46-4305-ad02-1fa2217b9738 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=239 latency=4.155481ms
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:52 request_id=b281c62b-cbeb-4e81-9c96-40757c5a88bf method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=239 latency=150.547µs
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:52 request_id=5aceee05-4b98-45ca-974a-1e919fdde991 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=239 latency=131.963µs
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:52 request_id=f82374a1-7d40-403d-aa70-5de8f913d2cc method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=239 latency=167.798µs
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:52 request_id=5a725d61-e66a-445b-9b40-57ba6183a195 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=239 latency=207.841µs
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:52 request_id=8ab66e91-8556-454b-913e-7b2c130dfd8e method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=239 latency=152.631µs
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:52 request_id=423f02cb-0169-42fd-a1ed-5b6952cb262d method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=239 latency=132.88µs
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:52 request_id=7da7d9d5-13e8-4495-9ec8-18ef6966bd41 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=239 latency=160.839µs
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:52 request_id=870557ee-8823-4a7a-b78e-a440a1d8a0f7 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=239 latency=146.588µs
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:52 request_id=52f91333-d9c9-4365-9453-cdfcb0c3f5a7 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=239 latency=146.172µs
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:52 request_id=af8b17fd-7edc-4208-a40d-84ca21e160f3 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=239 latency=167.798µs
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:52 request_id=d4c625e7-5ebf-4eea-8d60-45af463edf4c method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=239 latency=165.798µs
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:52 request_id=083768b9-8f2a-4681-bcd4-5ae52228e0bb method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=239 latency=186.59µs
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:52 request_id=46101c43-7641-481a-869d-3543f25ef54d method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=239 latency=436.099µs
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:52 request_id=ba6ff758-a13f-4580-8ba2-da63a2351ca8 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=239 latency=162.255µs
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:52 request_id=e6379b05-1acd-4b5a-b5a6-99e7bccc5f01 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=239 latency=134.672µs
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:52 request_id=d9fb6747-2b9e-41cf-b53c-1a7750fc91f0 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=239 latency=202.966µs
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:52 request_id=e5e5ec36-88eb-412f-8c2c-3f82c87c4590 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=239 latency=171.006µs
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:52 request_id=8c2d9c31-df32-49d8-9c38-780f4fab1746 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=239 latency=184.465µs
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:52 request_id=95fd52ea-b8d8-45df-a68a-ceba9d27b133 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=239 latency=135.922µs
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:52 request_id=ae9ee763-096d-480c-b24b-cd349cb18978 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=239 latency=384.431µs
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:52 request_id=088337f5-bb46-4911-80fd-fa855dc98200 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=239 latency=145.463µs
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:52 request_id=2aa7e674-07c8-4282-8798-fcf641d08133 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=239 latency=138.797µs
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:52 request_id=e0339717-77bb-4bd7-a321-34eaf1984fb9 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=239 latency=163.923µs
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:52 request_id=74331de8-09a1-4057-8604-bd04d68465f4 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=239 latency=145.922µs
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:52 request_id=da1793af-1f78-46eb-8751-52961c9bd4af method=GET path=/api/v1/chats/:chat_id/messages status=200 response_bytes=4332 latency=865.156µs
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:52 request_id=41cc821a-71d8-48f3-a2ec-618e8d6370b3 method=GET path=/api/v1/chats/:chat_id/messages status=200 response_bytes=4332 latency=796.404µs
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:52 request_id=58db51d8-2b41-4a61-9f48-e28a79b88470 method=GET path=/api/v1/chats/:chat_id/messages status=200 response_bytes=4332 latency=728.859µs
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:52 request_id=6b05dcf0-ee67-43cf-96d4-ef406c94761e method=GET path=/api/v1/chats/:chat_id/messages status=200 response_bytes=4332 latency=616.272µs
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:52 request_id=8bbd35fc-09c2-4ede-af22-3fb7147d5620 method=GET path=/api/v1/chats/:chat_id/messages status=200 response_bytes=4332 latency=611.938µs
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:52 request_id=10bfa4c2-537d-442a-8e5b-0da397c81cc0 method=GET path=/api/v1/chats/:chat_id/messages status=200 response_bytes=3616 latency=446.391µs
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | --- PASS: TestConcurrentMessagesAreUnique (7.52s)
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | PASS
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | ok gitflic.ru/akselbant/mtusi2026lab1-fork/internal/app/chat 12.755s
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | === RUN TestSpoolOriginalAndFullValidation
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | --- PASS: TestSpoolOriginalAndFullValidation (0.00s)
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | === RUN TestSpoolLimitsBeforeDecode
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | --- PASS: TestSpoolLimitsBeforeDecode (0.02s)
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | === RUN TestFilenameAndCancelledUpload
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | --- PASS: TestFilenameAndCancelledUpload (0.00s)
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | === RUN TestReconcileRejectsUnsafeGrace
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | --- PASS: TestReconcileRejectsUnsafeGrace (0.00s)
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | === RUN TestValid16BitWidePNG
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | --- PASS: TestValid16BitWidePNG (0.08s)
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | PASS
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | ok gitflic.ru/akselbant/mtusi2026lab1-fork/internal/attachment 1.160s
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | ? gitflic.ru/akselbant/mtusi2026lab1-fork/internal/config [no test files]
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | ? gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain [no test files]
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | === RUN TestUnicodeAndSalt
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | --- PASS: TestUnicodeAndSalt (2.23s)
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | PASS
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | ok gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/password 3.266s
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | ? gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/repository [no test files]
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | === RUN TestS3WireFixture
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | --- PASS: TestS3WireFixture (0.00s)
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | === RUN TestIntegration
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | storage_test.go:84: goose up: 2026/10/28 19:17:59 OK 001_initial.sql (24.32ms)
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:59 OK 002_idempotency.sql (1.98ms)
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:59 OK 003_attachments.sql (4.14ms)
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:59 OK 004_message_attachments.sql (1.77ms)
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:59 goose: successfully migrated database to version: 4
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | storage_test.go:85: goose up: 2026/10/28 19:17:59 goose: no migrations to run. current version: 4
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | === RUN TestIntegration/registration_race
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | storage_test.go:121: 12 concurrent INSERTs: 1 success, 11 unique conflicts
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | === RUN TestIntegration/rollback
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | storage_test.go:139: failed second member INSERT left 0 chats and 0 members
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | === RUN TestIntegration/lab4_attachments_and_reconciliation
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | lab4_test.go:248: ACL, original bytes, cross-chat attachment rejection, ordered/concurrent idempotency and absent=[] passed
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | lab4_test.go:316: dry-run={Apply:false GraceSeconds:90 ObjectsScanned:4 MetadataScanned:2 BytesScanned:94 ListRequestsEstimate:1 StatRequests:3 DBQueries:12 Orphans:1 Missing:1 FreshSkipped:1 LockedSkipped:1 ReferencedMissing:1 Deleted:0 MarkedFailed:0 DurationMS:7 Actions:[{Kind:orphan Key:original/9da5bf1b-bbc2-4c8e-8816-d473c908db4a Applied:false} {Kind:missing Key:original/65f5dff4-bc2f-469b-8b6b-6bc1275f8d6a Applied:false}]} apply={Apply:true GraceSeconds:90 ObjectsScanned:4 MetadataScanned:2 BytesScanned:94 ListRequestsEstimate:1 StatRequests:3 DBQueries:13 Orphans:1 Missing:1 FreshSkipped:1 LockedSkipped:1 ReferencedMissing:1 Deleted:1 MarkedFailed:1 DurationMS:5 Actions:[{Kind:orphan Key:original/9da5bf1b-bbc2-4c8e-8816-d473c908db4a Applied:true} {Kind:missing Key:original/65f5dff4-bc2f-469b-8b6b-6bc1275f8d6a Applied:true}]} repeat={Apply:true GraceSeconds:90 ObjectsScanned:3 MetadataScanned:2 BytesScanned:88 ListRequestsEstimate:1 StatRequests:1 DBQueries:7 Orphans:0 Missing:0 FreshSkipped:1 LockedSkipped:1 ReferencedMissing:0 Deleted:0 MarkedFailed:0 DurationMS:2 Actions:[]}; fresh, locked and referenced objects retained
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | === RUN TestIntegration/keyset_and_explain
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | storage_test.go:193: EXPLAIN on 10,000 messages, cursor near the end (9,000):
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | storage_test.go:199: Limit (cost=0.29..18.05 rows=51 width=142) (actual time=0.011..0.032 rows=51 loops=1)
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | storage_test.go:199: Buffers: shared hit=10
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | storage_test.go:199: -> Index Scan using messages_history_idx on messages m (cost=0.29..348.68 rows=1000 width=142) (actual time=0.011..0.028 rows=51 loops=1)
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | storage_test.go:199: Index Cond: ((chat_id = '3945a437-ac3b-4af6-a505-e156a979dd08'::uuid) AND (ROW(created_at, id) > ROW('2026-01-01 00:00:00.9+00'::timestamp with time zone, '00000000-0000-0000-0000-000000000000'::uuid)))
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | storage_test.go:199: Buffers: shared hit=10
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | storage_test.go:199: Planning Time: 0.031 ms
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | storage_test.go:199: Execution Time: 0.061 ms
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | storage_test.go:204: keyset traversal returned 10,000 distinct messages, including equal timestamps
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | === RUN TestIntegration/idempotency_race
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | storage_test.go:254: 16 concurrent PostgreSQL requests: one effect, identical replay, changed body conflicts
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | === RUN TestIntegration/goose_legacy_and_down
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | storage_test.go:268: goose up: 2026/10/28 19:17:59 OK 001_initial.sql (1.62ms)
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:59 OK 002_idempotency.sql (1.13ms)
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:59 OK 003_attachments.sql (583.4µs)
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:59 OK 004_message_attachments.sql (2.74ms)
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:59 goose: successfully migrated database to version: 4
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | storage_test.go:269: goose up: 2026/10/28 19:17:59 goose: no migrations to run. current version: 4
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | storage_test.go:276: adopted legacy schema: all existing messages are unchanged
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | storage_test.go:277: goose reset: 2026/10/28 19:17:59 OK 004_message_attachments.sql (5.92ms)
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:59 OK 003_attachments.sql (3.96ms)
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:59 OK 002_idempotency.sql (2.73ms)
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:59 OK 001_initial.sql (9.78ms)
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | storage_test.go:282: goose up: 2026/10/28 19:17:59 OK 001_initial.sql (10.62ms)
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:59 OK 002_idempotency.sql (1.69ms)
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:59 OK 003_attachments.sql (3.22ms)
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:59 OK 004_message_attachments.sql (1.21ms)
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | 2026/10/28 19:17:59 goose: successfully migrated database to version: 4
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | storage_test.go:286: down and up succeeded in isolated schema
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | --- PASS: TestIntegration (0.64s)
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | --- PASS: TestIntegration/registration_race (0.04s)
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | --- PASS: TestIntegration/rollback (0.00s)
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | --- PASS: TestIntegration/lab4_attachments_and_reconciliation (0.04s)
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | --- PASS: TestIntegration/keyset_and_explain (0.08s)
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | --- PASS: TestIntegration/idempotency_race (0.01s)
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | --- PASS: TestIntegration/goose_legacy_and_down (0.12s)
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | PASS
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | ok gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/repository/postgres 1.675s
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | ? gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/session [no test files]
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | === RUN TestPasswordContract
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | --- PASS: TestPasswordContract (0.00s)
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | PASS
mtusi-lab4_tests.0.lks3m3xxmw5s@colima | ok gitflic.ru/akselbant/mtusi2026lab1-fork/internal/usecase/chat 1.011s
mtusi-lab4_tests
+3
View File
@@ -0,0 +1,3 @@
.venv/bin/python 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.
File diff suppressed because it is too large Load Diff
+7
View File
@@ -0,0 +1,7 @@
.venv/bin/python tests/own/reconcile.py
Fresh scan cost: {"objects_scanned": 130, "metadata_scanned": 30, "list_requests_estimate": 1, "stat_requests": 7, "db_queries": 30, "duration_ms": 27}
Fresh scan cost: {"objects_scanned": 1130, "metadata_scanned": 30, "list_requests_estimate": 2, "stat_requests": 7, "db_queries": 30, "duration_ms": 64}
Waiting92s for actual S3 timestamps: measuring aged-object locking, DB and HEAD cost next.
Aged scan cost: {"objects_scanned": 1130, "metadata_scanned": 30, "list_requests_estimate": 2, "stat_requests": 1131, "db_queries": 2323, "duration_ms": 999}
Aged scan cost: {"objects_scanned": 130, "metadata_scanned": 30, "list_requests_estimate": 1, "stat_requests": 131, "db_queries": 323, "duration_ms": 129}
PASS: real two-store faults, grace, lock, dry-run/apply/repeat, linked data preserved and paginated scan cost.
+54
View File
@@ -0,0 +1,54 @@
{
"api": {
"all_original_tasks_replaced": true,
"mounts_unchanged": true,
"before": [
"05qp70hqicx1m3uten0t88c9p",
"1diq18xi0jmwpzqzhhq39hjad"
],
"after": [
"g2s34c3zuztbxehcxyypsyrxy",
"rz3qizaxp0s2bguzbs57me0op"
]
},
"lb": {
"all_original_tasks_replaced": true,
"mounts_unchanged": true,
"before": [
"psq3iyz4kraq9u3n2mtkyfijf"
],
"after": [
"oaiciqwjik1afkel0hdgwvhwy"
]
},
"postgres": {
"all_original_tasks_replaced": true,
"mounts_unchanged": true,
"before": [
"7xbetpe47jvp1uuu2di2uk7vy"
],
"after": [
"i3scdtmsi49zwytqye6hc3k15"
]
},
"redis": {
"all_original_tasks_replaced": true,
"mounts_unchanged": true,
"before": [
"x8ejqk47qyz4rgtgygq48wos7"
],
"after": [
"tqq4m5ygv0nohjefvbdprapzz"
]
},
"minio": {
"all_original_tasks_replaced": true,
"mounts_unchanged": true,
"before": [
"ww19llqoe6yjvteqx3by0i4r1"
],
"after": [
"lfmr13mco26ik0a37xk2ntene"
]
}
}
+6
View File
@@ -0,0 +1,6 @@
.venv/bin/python tests/own/swarm_grade4.py
PASS: shared-key race on two replicas; replay/conflict/scope/validation/access/logout
{"action": "stop-one", "target": "rz3qizaxp0s2bguzbs57me0op", "duration_seconds": 15.458, "successful_writes": 1078, "failed_attempts": 7, "successful_rps": 69.739, "first_recovery_seconds": 1.349, "max_success_gap_seconds": 1.055, "instances_before": ["rz3qizaxp0s2bguzbs57me0op", "xcgz2hubz1xrzmrkoyrgwq0tq"], "instances_after": ["j7awgfnedlt9ne1esywrappxx", "xcgz2hubz1xrzmrkoyrgwq0tq"], "confirmed_messages_checked": 1229, "duplicate_bodies": 0}
{"action": "stop-one", "target": "xcgz2hubz1xrzmrkoyrgwq0tq", "duration_seconds": 15.467, "successful_writes": 1091, "failed_attempts": 7, "successful_rps": 70.537, "first_recovery_seconds": 1.384, "max_success_gap_seconds": 1.057, "instances_before": ["j7awgfnedlt9ne1esywrappxx", "xcgz2hubz1xrzmrkoyrgwq0tq"], "instances_after": ["5vy560hk6k0q3eicqodd9dp2z", "j7awgfnedlt9ne1esywrappxx"], "confirmed_messages_checked": 1251, "duplicate_bodies": 0}
{"action": "update", "target": null, "duration_seconds": 44.156, "successful_writes": 3362, "failed_attempts": 0, "successful_rps": 76.139, "first_recovery_seconds": null, "max_success_gap_seconds": 0.152, "instances_before": ["5vy560hk6k0q3eicqodd9dp2z", "j7awgfnedlt9ne1esywrappxx"], "instances_after": ["j201rqxerkxdq0vbcw3armc3m", "uqyjmps3u9fyl976lpj944pc5"], "confirmed_messages_checked": 3519, "duplicate_bodies": 0}
PASS: each original replica stopped and replaced; rolling update under load; confirmations and sessions preserved
+2
View File
@@ -0,0 +1,2 @@
.venv/bin/python tests/smoke.py --base-url "http://localhost:8080"
PASS: lab4 public API scenario; infrastructure and grading evidence remain separate.
+146
View File
@@ -0,0 +1,146 @@
{
"stack": "mtusi-lab4",
"docker": "29.5.2",
"services": {
"lb": {
"image": "haproxy:3.2.6-alpine",
"limits": {
"NanoCPUs": 500000000,
"MemoryBytes": 134217728
},
"published_ports": [
{
"Protocol": "tcp",
"TargetPort": 8080,
"PublishedPort": 8080,
"PublishMode": "host"
}
],
"secret_names": [],
"mounts": [],
"tasks": [
{
"id": "oaiciqwjik1afkel0hdgwvhwy",
"state": "running",
"container": "ace6b5a9ab2ac3a291bca557e7eb89ba6354ed586625332b99dc3d1cdfaab6b5"
}
]
},
"api": {
"image": "mtusi-messenger:lab4",
"limits": {
"NanoCPUs": 1000000000,
"MemoryBytes": 1610612736
},
"published_ports": [],
"secret_names": [
"mtusi-lab4_cursor_key",
"mtusi-lab4_postgres_password",
"mtusi-lab4_s3_access_key",
"mtusi-lab4_s3_secret_key"
],
"mounts": [],
"tasks": [
{
"id": "g2s34c3zuztbxehcxyypsyrxy",
"state": "running",
"container": "303dc53972fde0fe71990f644cb1b56658441a4d1cb6410ffc351ccceb0cd3a7"
},
{
"id": "rz3qizaxp0s2bguzbs57me0op",
"state": "running",
"container": "f69bf37c2237e13f08bf4aa397936d4fed84a17395410f0af469b2cbc3e41699"
}
]
},
"postgres": {
"image": "postgres:17.6-alpine3.22",
"limits": {
"NanoCPUs": 1000000000,
"MemoryBytes": 536870912
},
"published_ports": [],
"secret_names": [
"mtusi-lab4_postgres_password"
],
"mounts": [
{
"Type": "volume",
"Source": "mtusi-lab4_postgres_data",
"Target": "/var/lib/postgresql/data",
"VolumeOptions": {
"Labels": {
"com.docker.stack.namespace": "mtusi-lab4"
}
}
}
],
"tasks": [
{
"id": "i3scdtmsi49zwytqye6hc3k15",
"state": "running",
"container": "1622ddce8784f7dc1092ba808f05583898e08ba57a5c390d227265e4243744dc"
}
]
},
"redis": {
"image": "redis:7.4.5-alpine3.21",
"limits": {
"NanoCPUs": 500000000,
"MemoryBytes": 134217728
},
"published_ports": [],
"secret_names": [],
"mounts": [
{
"Type": "volume",
"Source": "mtusi-lab4_redis_data",
"Target": "/data",
"VolumeOptions": {
"Labels": {
"com.docker.stack.namespace": "mtusi-lab4"
}
}
}
],
"tasks": [
{
"id": "tqq4m5ygv0nohjefvbdprapzz",
"state": "running",
"container": "dfe7c35a3887061560c608484e33ce1036222d8f683a5729599fb0a4e33065f3"
}
]
},
"minio": {
"image": "mtusi-minio:RELEASE.2025-09-07T16-13-09Z",
"limits": {
"NanoCPUs": 1000000000,
"MemoryBytes": 536870912
},
"published_ports": [],
"secret_names": [
"mtusi-lab4_s3_root_access_key",
"mtusi-lab4_s3_root_secret_key"
],
"mounts": [
{
"Type": "volume",
"Source": "mtusi-lab4_s3_data",
"Target": "/data",
"VolumeOptions": {
"Labels": {
"com.docker.stack.namespace": "mtusi-lab4"
}
}
}
],
"tasks": [
{
"id": "lfmr13mco26ik0a37xk2ntene",
"state": "running",
"container": "8110ff5d0c7a776005653182ecfd927fe59a8b38b02b4645e1bd03fa1c6fdeff"
}
]
}
}
}
+146
View File
@@ -0,0 +1,146 @@
{
"stack": "mtusi-lab4",
"docker": "29.5.2",
"services": {
"lb": {
"image": "haproxy:3.2.6-alpine",
"limits": {
"NanoCPUs": 500000000,
"MemoryBytes": 134217728
},
"published_ports": [
{
"Protocol": "tcp",
"TargetPort": 8080,
"PublishedPort": 8080,
"PublishMode": "host"
}
],
"secret_names": [],
"mounts": [],
"tasks": [
{
"id": "psq3iyz4kraq9u3n2mtkyfijf",
"state": "running",
"container": "c9246107dbeb5aa78d3574865ddb2e9ac2d117c87830ca7be5214bdc8e8768b4"
}
]
},
"api": {
"image": "mtusi-messenger:lab4",
"limits": {
"NanoCPUs": 1000000000,
"MemoryBytes": 1610612736
},
"published_ports": [],
"secret_names": [
"mtusi-lab4_cursor_key",
"mtusi-lab4_postgres_password",
"mtusi-lab4_s3_access_key",
"mtusi-lab4_s3_secret_key"
],
"mounts": [],
"tasks": [
{
"id": "05qp70hqicx1m3uten0t88c9p",
"state": "running",
"container": "0beaa8438aa0f61c069729d0d3e83220df07e49288451658d3c92f698c1b7fbc"
},
{
"id": "1diq18xi0jmwpzqzhhq39hjad",
"state": "running",
"container": "bc1d5078efd2145c84e341ae457360f490f32539d7e4f6d5155378c918da69c8"
}
]
},
"postgres": {
"image": "postgres:17.6-alpine3.22",
"limits": {
"NanoCPUs": 1000000000,
"MemoryBytes": 536870912
},
"published_ports": [],
"secret_names": [
"mtusi-lab4_postgres_password"
],
"mounts": [
{
"Type": "volume",
"Source": "mtusi-lab4_postgres_data",
"Target": "/var/lib/postgresql/data",
"VolumeOptions": {
"Labels": {
"com.docker.stack.namespace": "mtusi-lab4"
}
}
}
],
"tasks": [
{
"id": "7xbetpe47jvp1uuu2di2uk7vy",
"state": "running",
"container": "7a24978349b4630091ba38d365fcd74b20c60bd9a27fc15d5cb967e3874e09de"
}
]
},
"redis": {
"image": "redis:7.4.5-alpine3.21",
"limits": {
"NanoCPUs": 500000000,
"MemoryBytes": 134217728
},
"published_ports": [],
"secret_names": [],
"mounts": [
{
"Type": "volume",
"Source": "mtusi-lab4_redis_data",
"Target": "/data",
"VolumeOptions": {
"Labels": {
"com.docker.stack.namespace": "mtusi-lab4"
}
}
}
],
"tasks": [
{
"id": "x8ejqk47qyz4rgtgygq48wos7",
"state": "running",
"container": "33a57e377891ce0c82807b12757cf0103ef9461502d1a64efdeec506744d9c27"
}
]
},
"minio": {
"image": "mtusi-minio:RELEASE.2025-09-07T16-13-09Z",
"limits": {
"NanoCPUs": 1000000000,
"MemoryBytes": 536870912
},
"published_ports": [],
"secret_names": [
"mtusi-lab4_s3_root_access_key",
"mtusi-lab4_s3_root_secret_key"
],
"mounts": [
{
"Type": "volume",
"Source": "mtusi-lab4_s3_data",
"Target": "/data",
"VolumeOptions": {
"Labels": {
"com.docker.stack.namespace": "mtusi-lab4"
}
}
}
],
"tasks": [
{
"id": "ww19llqoe6yjvteqx3by0i4r1",
"state": "running",
"container": "d71ce1a062fe9ba9060f5266a9f00d89a34583f133a609769bb2510deaa52470"
}
]
}
}
}
+146
View File
@@ -0,0 +1,146 @@
{
"stack": "mtusi-lab4",
"docker": "29.5.2",
"services": {
"lb": {
"image": "haproxy:3.2.6-alpine",
"limits": {
"NanoCPUs": 500000000,
"MemoryBytes": 134217728
},
"published_ports": [
{
"Protocol": "tcp",
"TargetPort": 8080,
"PublishedPort": 8080,
"PublishMode": "host"
}
],
"secret_names": [],
"mounts": [],
"tasks": [
{
"id": "oaiciqwjik1afkel0hdgwvhwy",
"state": "running",
"container": "ace6b5a9ab2ac3a291bca557e7eb89ba6354ed586625332b99dc3d1cdfaab6b5"
}
]
},
"api": {
"image": "mtusi-messenger:lab4",
"limits": {
"NanoCPUs": 1000000000,
"MemoryBytes": 1610612736
},
"published_ports": [],
"secret_names": [
"mtusi-lab4_cursor_key",
"mtusi-lab4_postgres_password",
"mtusi-lab4_s3_access_key",
"mtusi-lab4_s3_secret_key"
],
"mounts": [],
"tasks": [
{
"id": "uqyjmps3u9fyl976lpj944pc5",
"state": "running",
"container": "2f98c5810a5f8557476af364186cb66e02c46003fece8827e200313d27f2fd74"
},
{
"id": "j201rqxerkxdq0vbcw3armc3m",
"state": "running",
"container": "68730a58baf57c19b9919e752e34b7ad247ff29d94918f28fb7ede200c1a95f1"
}
]
},
"postgres": {
"image": "postgres:17.6-alpine3.22",
"limits": {
"NanoCPUs": 1000000000,
"MemoryBytes": 536870912
},
"published_ports": [],
"secret_names": [
"mtusi-lab4_postgres_password"
],
"mounts": [
{
"Type": "volume",
"Source": "mtusi-lab4_postgres_data",
"Target": "/var/lib/postgresql/data",
"VolumeOptions": {
"Labels": {
"com.docker.stack.namespace": "mtusi-lab4"
}
}
}
],
"tasks": [
{
"id": "i3scdtmsi49zwytqye6hc3k15",
"state": "running",
"container": "1622ddce8784f7dc1092ba808f05583898e08ba57a5c390d227265e4243744dc"
}
]
},
"redis": {
"image": "redis:7.4.5-alpine3.21",
"limits": {
"NanoCPUs": 500000000,
"MemoryBytes": 134217728
},
"published_ports": [],
"secret_names": [],
"mounts": [
{
"Type": "volume",
"Source": "mtusi-lab4_redis_data",
"Target": "/data",
"VolumeOptions": {
"Labels": {
"com.docker.stack.namespace": "mtusi-lab4"
}
}
}
],
"tasks": [
{
"id": "tqq4m5ygv0nohjefvbdprapzz",
"state": "running",
"container": "dfe7c35a3887061560c608484e33ce1036222d8f683a5729599fb0a4e33065f3"
}
]
},
"minio": {
"image": "mtusi-minio:RELEASE.2025-09-07T16-13-09Z",
"limits": {
"NanoCPUs": 1000000000,
"MemoryBytes": 536870912
},
"published_ports": [],
"secret_names": [
"mtusi-lab4_s3_root_access_key",
"mtusi-lab4_s3_root_secret_key"
],
"mounts": [
{
"Type": "volume",
"Source": "mtusi-lab4_s3_data",
"Target": "/data",
"VolumeOptions": {
"Labels": {
"com.docker.stack.namespace": "mtusi-lab4"
}
}
}
],
"tasks": [
{
"id": "lfmr13mco26ik0a37xk2ntene",
"state": "running",
"container": "8110ff5d0c7a776005653182ecfd927fe59a8b38b02b4645e1bd03fa1c6fdeff"
}
]
}
}
}
+146
View File
@@ -0,0 +1,146 @@
{
"stack": "mtusi-lab4",
"docker": "29.5.2",
"services": {
"lb": {
"image": "haproxy:3.2.6-alpine",
"limits": {
"NanoCPUs": 500000000,
"MemoryBytes": 134217728
},
"published_ports": [
{
"Protocol": "tcp",
"TargetPort": 8080,
"PublishedPort": 8080,
"PublishMode": "host"
}
],
"secret_names": [],
"mounts": [],
"tasks": [
{
"id": "psq3iyz4kraq9u3n2mtkyfijf",
"state": "running",
"container": "c9246107dbeb5aa78d3574865ddb2e9ac2d117c87830ca7be5214bdc8e8768b4"
}
]
},
"api": {
"image": "mtusi-messenger:lab4",
"limits": {
"NanoCPUs": 1000000000,
"MemoryBytes": 1610612736
},
"published_ports": [],
"secret_names": [
"mtusi-lab4_cursor_key",
"mtusi-lab4_postgres_password",
"mtusi-lab4_s3_access_key",
"mtusi-lab4_s3_secret_key"
],
"mounts": [],
"tasks": [
{
"id": "0gwv6ha33wg3dao0mqxl9gu0n",
"state": "running",
"container": "f37c59b0556d4bc5b3f5c0432e8c58da4888ca5286635954131ea37c0714ead1"
},
{
"id": "rbtm0mbmnbzr2oqcz8icho3qr",
"state": "running",
"container": "17d5f64c6fdd70ac3cdc27e655308909d4670ca0a7b743384ac7fe34e172d428"
}
]
},
"postgres": {
"image": "postgres:17.6-alpine3.22",
"limits": {
"NanoCPUs": 1000000000,
"MemoryBytes": 536870912
},
"published_ports": [],
"secret_names": [
"mtusi-lab4_postgres_password"
],
"mounts": [
{
"Type": "volume",
"Source": "mtusi-lab4_postgres_data",
"Target": "/var/lib/postgresql/data",
"VolumeOptions": {
"Labels": {
"com.docker.stack.namespace": "mtusi-lab4"
}
}
}
],
"tasks": [
{
"id": "uy9m8wn36msy9qzttodwobkez",
"state": "running",
"container": "41c7c4bb6a37b443982f168a8e8494847581c2e30d1d6f5bf817284aebaf96b9"
}
]
},
"redis": {
"image": "redis:7.4.5-alpine3.21",
"limits": {
"NanoCPUs": 500000000,
"MemoryBytes": 134217728
},
"published_ports": [],
"secret_names": [],
"mounts": [
{
"Type": "volume",
"Source": "mtusi-lab4_redis_data",
"Target": "/data",
"VolumeOptions": {
"Labels": {
"com.docker.stack.namespace": "mtusi-lab4"
}
}
}
],
"tasks": [
{
"id": "x8ejqk47qyz4rgtgygq48wos7",
"state": "running",
"container": "33a57e377891ce0c82807b12757cf0103ef9461502d1a64efdeec506744d9c27"
}
]
},
"minio": {
"image": "mtusi-minio:RELEASE.2025-09-07T16-13-09Z",
"limits": {
"NanoCPUs": 1000000000,
"MemoryBytes": 536870912
},
"published_ports": [],
"secret_names": [
"mtusi-lab4_s3_root_access_key",
"mtusi-lab4_s3_root_secret_key"
],
"mounts": [
{
"Type": "volume",
"Source": "mtusi-lab4_s3_data",
"Target": "/data",
"VolumeOptions": {
"Labels": {
"com.docker.stack.namespace": "mtusi-lab4"
}
}
}
],
"tasks": [
{
"id": "jafk96quou17emokdyfk1qi4t",
"state": "running",
"container": "a04bf799191faea4386533680968586c90d67adeef8f37166824aa4723f8ac03"
}
]
}
}
}
+3
View File
@@ -0,0 +1,3 @@
.venv/bin/python scripts/swarm.py update
mtusi-lab4_api
PASS: rolling update completed
+105
View File
@@ -0,0 +1,105 @@
{
"concurrency": 10,
"warmup_uploads": 1,
"memory_method": "cgroup v2 memory.current sampled every >=100ms; values include file cache",
"runs": [
{
"width": 512,
"height": 512,
"size_bytes": 787252,
"sha256": "1a09c45b4a706ff8009c1adf0e9f10e428d8059d335e074cf4ad456680d4b473",
"requests": 10,
"successful": 10,
"errors": 0,
"duration_seconds": 0.325,
"successful_rps": 30.816,
"latency_ms": {
"0.5": 120.287,
"0.95": 172.127,
"0.99": 172.127
},
"baseline_bytes": {
"a43c3f7e6e92": 45240320,
"007b52fbba64": 45174784
},
"sampled_peak_bytes": {
"a43c3f7e6e92": 47005696,
"007b52fbba64": 46907392
},
"kernel_lifetime_peak_before_bytes": {
"a43c3f7e6e92": 46804992,
"007b52fbba64": 46718976
},
"kernel_lifetime_peak_after_bytes": {
"a43c3f7e6e92": 48623616,
"007b52fbba64": 48693248
},
"sampled_peak_sum_bytes": 93913088,
"samples": [
{
"seconds": 0.045,
"bytes": {
"a43c3f7e6e92": 47005696,
"007b52fbba64": 46907392
}
},
{
"seconds": 0.325,
"bytes": {
"a43c3f7e6e92": 46116864,
"007b52fbba64": 46080000
}
}
]
},
{
"width": 1024,
"height": 768,
"size_bytes": 2360847,
"sha256": "ad94bc1d209135dea4d3caa0712cee92cfaa97ba3ccdd5797aff6664fcce4a2a",
"requests": 10,
"successful": 10,
"errors": 0,
"duration_seconds": 0.401,
"successful_rps": 24.957,
"latency_ms": {
"0.5": 258.573,
"0.95": 324.694,
"0.99": 324.694
},
"baseline_bytes": {
"a43c3f7e6e92": 46067712,
"007b52fbba64": 46063616
},
"sampled_peak_bytes": {
"a43c3f7e6e92": 41107456,
"007b52fbba64": 13651968
},
"kernel_lifetime_peak_before_bytes": {
"a43c3f7e6e92": 48623616,
"007b52fbba64": 48693248
},
"kernel_lifetime_peak_after_bytes": {
"a43c3f7e6e92": 49119232,
"007b52fbba64": 49922048
},
"sampled_peak_sum_bytes": 54759424,
"samples": [
{
"seconds": 0.043,
"bytes": {
"a43c3f7e6e92": 41107456,
"007b52fbba64": 13651968
}
},
{
"seconds": 0.401,
"bytes": {
"a43c3f7e6e92": 13234176,
"007b52fbba64": 10956800
}
}
]
}
]
}
+4
View File
@@ -0,0 +1,4 @@
.venv/bin/python scripts/measure_uploads.py
{"width": 512, "height": 512, "size_bytes": 787252, "sha256": "1a09c45b4a706ff8009c1adf0e9f10e428d8059d335e074cf4ad456680d4b473", "requests": 10, "successful": 10, "errors": 0, "duration_seconds": 0.325, "successful_rps": 30.816, "latency_ms": {"0.5": 120.287, "0.95": 172.127, "0.99": 172.127}, "baseline_bytes": {"a43c3f7e6e92": 45240320, "007b52fbba64": 45174784}, "sampled_peak_bytes": {"a43c3f7e6e92": 47005696, "007b52fbba64": 46907392}, "kernel_lifetime_peak_before_bytes": {"a43c3f7e6e92": 46804992, "007b52fbba64": 46718976}, "kernel_lifetime_peak_after_bytes": {"a43c3f7e6e92": 48623616, "007b52fbba64": 48693248}, "sampled_peak_sum_bytes": 93913088}
{"width": 1024, "height": 768, "size_bytes": 2360847, "sha256": "ad94bc1d209135dea4d3caa0712cee92cfaa97ba3ccdd5797aff6664fcce4a2a", "requests": 10, "successful": 10, "errors": 0, "duration_seconds": 0.401, "successful_rps": 24.957, "latency_ms": {"0.5": 258.573, "0.95": 324.694, "0.99": 324.694}, "baseline_bytes": {"a43c3f7e6e92": 46067712, "007b52fbba64": 46063616}, "sampled_peak_bytes": {"a43c3f7e6e92": 41107456, "007b52fbba64": 13651968}, "kernel_lifetime_peak_before_bytes": {"a43c3f7e6e92": 48623616, "007b52fbba64": 48693248}, "kernel_lifetime_peak_after_bytes": {"a43c3f7e6e92": 49119232, "007b52fbba64": 49922048}, "sampled_peak_sum_bytes": 54759424}
PASS: ten simultaneous uploads at two sizes; all originals verified; memory samples saved.
+8
View File
@@ -0,0 +1,8 @@
python3 scripts/check_contract.py
PASS: offline skeleton structure, local refs and Python syntax; application NOT tested.
.venv/bin/python scripts/validate_openapi.py
/Users/dkhakimovig/mtusi2026lab4/.venv/lib/python3.9/site-packages/urllib3/__init__.py:35: NotOpenSSLWarning: urllib3 v2 only supports OpenSSL 1.1.1+, currently the 'ssl' module is compiled with 'LibreSSL 2.8.3'. See: https://github.com/urllib3/urllib3/issues/3020
warnings.warn(
PASS: full OpenAPI 3.1 and JSON Schema validation; application NOT tested.
PASS: goose3.27.1 migration syntax validated.
PASS: mandatory lab4 contract and public checks unchanged.
+72
View File
@@ -0,0 +1,72 @@
{
"idempotency": {
"parallel_requests": 16,
"instances": [
"rz3qizaxp0s2bguzbs57me0op",
"xcgz2hubz1xrzmrkoyrgwq0tq"
],
"unique_message_ids": 1
},
"failovers": [
{
"action": "stop-one",
"target": "rz3qizaxp0s2bguzbs57me0op",
"duration_seconds": 15.458,
"successful_writes": 1078,
"failed_attempts": 7,
"successful_rps": 69.739,
"first_recovery_seconds": 1.349,
"max_success_gap_seconds": 1.055,
"instances_before": [
"rz3qizaxp0s2bguzbs57me0op",
"xcgz2hubz1xrzmrkoyrgwq0tq"
],
"instances_after": [
"j7awgfnedlt9ne1esywrappxx",
"xcgz2hubz1xrzmrkoyrgwq0tq"
],
"confirmed_messages_checked": 1229,
"duplicate_bodies": 0
},
{
"action": "stop-one",
"target": "xcgz2hubz1xrzmrkoyrgwq0tq",
"duration_seconds": 15.467,
"successful_writes": 1091,
"failed_attempts": 7,
"successful_rps": 70.537,
"first_recovery_seconds": 1.384,
"max_success_gap_seconds": 1.057,
"instances_before": [
"j7awgfnedlt9ne1esywrappxx",
"xcgz2hubz1xrzmrkoyrgwq0tq"
],
"instances_after": [
"5vy560hk6k0q3eicqodd9dp2z",
"j7awgfnedlt9ne1esywrappxx"
],
"confirmed_messages_checked": 1251,
"duplicate_bodies": 0
}
],
"rolling_update": {
"action": "update",
"target": null,
"duration_seconds": 44.156,
"successful_writes": 3362,
"failed_attempts": 0,
"successful_rps": 76.139,
"first_recovery_seconds": null,
"max_success_gap_seconds": 0.152,
"instances_before": [
"5vy560hk6k0q3eicqodd9dp2z",
"j7awgfnedlt9ne1esywrappxx"
],
"instances_after": [
"j201rqxerkxdq0vbcw3armc3m",
"uqyjmps3u9fyl976lpj944pc5"
],
"confirmed_messages_checked": 3519,
"duplicate_bodies": 0
}
}
+42
View File
@@ -0,0 +1,42 @@
module gitflic.ru/akselbant/mtusi2026lab1-fork
go 1.26.4
require (
github.com/google/uuid v1.6.0
github.com/jackc/pgx/v5 v5.7.6
github.com/labstack/echo/v4 v4.13.4
github.com/minio/minio-go/v7 v7.0.95
github.com/redis/go-redis/v9 v9.12.1
github.com/swaggest/swgui v1.8.9
golang.org/x/crypto v0.39.0
)
require (
github.com/cespare/xxhash/v2 v2.3.0 // indirect
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
github.com/dustin/go-humanize v1.0.1 // indirect
github.com/go-ini/ini v1.67.0 // indirect
github.com/goccy/go-json v0.10.5 // indirect
github.com/jackc/pgpassfile v1.0.0 // indirect
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
github.com/jackc/puddle/v2 v2.2.2 // indirect
github.com/klauspost/compress v1.18.0 // indirect
github.com/klauspost/cpuid/v2 v2.2.11 // indirect
github.com/labstack/gommon v0.4.2 // indirect
github.com/mattn/go-colorable v0.1.14 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/minio/crc64nvme v1.0.2 // indirect
github.com/minio/md5-simd v1.1.2 // indirect
github.com/philhofer/fwd v1.2.0 // indirect
github.com/rs/xid v1.6.0 // indirect
github.com/tinylib/msgp v1.3.0 // indirect
github.com/valyala/bytebufferpool v1.0.0 // indirect
github.com/valyala/fasttemplate v1.2.2 // indirect
github.com/vearutop/statigz v1.4.0 // indirect
golang.org/x/net v0.41.0 // indirect
golang.org/x/sync v0.15.0 // indirect
golang.org/x/sys v0.33.0 // indirect
golang.org/x/text v0.26.0 // indirect
golang.org/x/time v0.11.0 // indirect
)
+90
View File
@@ -0,0 +1,90 @@
github.com/andybalholm/brotli v1.0.5 h1:8uQZIdzKmjc/iuPu7O2ioW48L81FgatrcpfFmiq/cCs=
github.com/andybalholm/brotli v1.0.5/go.mod h1:fO7iG3H7G2nSZ7m0zPUDn85XEX2GTukHGRSepvi9Eig=
github.com/bool64/dev v0.2.45 h1:3nLKhAS/6Oklk3Mt2lHYSN/Cb4tdAD77KLwzeP+6eYE=
github.com/bool64/dev v0.2.45/go.mod h1:iJbh1y/HkunEPhgebWRNcs8wfGq7sjvJ6W5iabL8ACg=
github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs=
github.com/bsm/ginkgo/v2 v2.12.0/go.mod h1:SwYbGRRDovPVboqFv0tPTcG1sN61LM1Z4ARdbAV9g4c=
github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA=
github.com/bsm/gomega v1.27.10/go.mod h1:JyEr/xRbxbtgWNi8tIEVPUYZ5Dzef52k01W3YH0H+O0=
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78=
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc=
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
github.com/go-ini/ini v1.67.0 h1:z6ZrTEZqSWOTyH2FlglNbNgARyHG8oLW9gMELqKr06A=
github.com/go-ini/ini v1.67.0/go.mod h1:ByCAeIL28uOIIG0E3PJtZPDL8WnHpFKFOtgjp+3Ies8=
github.com/goccy/go-json v0.10.5 h1:Fq85nIqj+gXn/S5ahsiTlK3TmC85qgirsdTP/+DeaC4=
github.com/goccy/go-json v0.10.5/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
github.com/jackc/pgx/v5 v5.7.6 h1:rWQc5FwZSPX58r1OQmkuaNicxdmExaEz5A2DO2hUuTk=
github.com/jackc/pgx/v5 v5.7.6/go.mod h1:aruU7o91Tc2q2cFp5h4uP3f6ztExVpyVv88Xl/8Vl8M=
github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo=
github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
github.com/klauspost/compress v1.18.0 h1:c/Cqfb0r+Yi+JtIEq73FWXVkRonBlf0CRNYc8Zttxdo=
github.com/klauspost/compress v1.18.0/go.mod h1:2Pp+KzxcywXVXMr50+X0Q/Lsb43OQHYWRCY2AiWywWQ=
github.com/klauspost/cpuid/v2 v2.0.1/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
github.com/klauspost/cpuid/v2 v2.2.11 h1:0OwqZRYI2rFrjS4kvkDnqJkKHdHaRnCm68/DY4OxRzU=
github.com/klauspost/cpuid/v2 v2.2.11/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0=
github.com/labstack/echo/v4 v4.13.4 h1:oTZZW+T3s9gAu5L8vmzihV7/lkXGZuITzTQkTEhcXEA=
github.com/labstack/echo/v4 v4.13.4/go.mod h1:g63b33BZ5vZzcIUF8AtRH40DrTlXnx4UMC8rBdndmjQ=
github.com/labstack/gommon v0.4.2 h1:F8qTUNXgG1+6WQmqoUWnz8WiEU60mXVVw0P4ht1WRA0=
github.com/labstack/gommon v0.4.2/go.mod h1:QlUFxVM+SNXhDL/Z7YhocGIBYOiwB0mXm1+1bAPHPyU=
github.com/mattn/go-colorable v0.1.14 h1:9A9LHSqF/7dyVVX6g0U9cwm9pG3kP9gSzcuIPHPsaIE=
github.com/mattn/go-colorable v0.1.14/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8=
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/minio/crc64nvme v1.0.2 h1:6uO1UxGAD+kwqWWp7mBFsi5gAse66C4NXO8cmcVculg=
github.com/minio/crc64nvme v1.0.2/go.mod h1:eVfm2fAzLlxMdUGc0EEBGSMmPwmXD5XiNRpnu9J3bvg=
github.com/minio/md5-simd v1.1.2 h1:Gdi1DZK69+ZVMoNHRXJyNcxrMA4dSxoYHZSQbirFg34=
github.com/minio/md5-simd v1.1.2/go.mod h1:MzdKDxYpY2BT9XQFocsiZf/NKVtR7nkE4RoEpN+20RM=
github.com/minio/minio-go/v7 v7.0.95 h1:ywOUPg+PebTMTzn9VDsoFJy32ZuARN9zhB+K3IYEvYU=
github.com/minio/minio-go/v7 v7.0.95/go.mod h1:wOOX3uxS334vImCNRVyIDdXX9OsXDm89ToynKgqUKlo=
github.com/philhofer/fwd v1.2.0 h1:e6DnBTl7vGY+Gz322/ASL4Gyp1FspeMvx1RNDoToZuM=
github.com/philhofer/fwd v1.2.0/go.mod h1:RqIHx9QI14HlwKwm98g9Re5prTQ6LdeRQn+gXJFxsJM=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/redis/go-redis/v9 v9.12.1 h1:k5iquqv27aBtnTm2tIkROUDp8JBXhXZIVu1InSgvovg=
github.com/redis/go-redis/v9 v9.12.1/go.mod h1:huWgSWd8mW6+m0VPhJjSSQ+d6Nh1VICQ6Q5lHuCH/Iw=
github.com/rs/xid v1.6.0 h1:fV591PaemRlL6JfRxGDEPl69wICngIQ3shQtzfy2gxU=
github.com/rs/xid v1.6.0/go.mod h1:7XoLgs4eV+QndskICGsho+ADou8ySMSjJKDIan90Nz0=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA=
github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
github.com/swaggest/swgui v1.8.9 h1:cxAgIwouPpZPlvX68jY5fpwarzLbkc8/IL6DMj+H460=
github.com/swaggest/swgui v1.8.9/go.mod h1:eTJfgwudbyw9xMwqO26vs82ei2u6//JnUAofx2vGB3M=
github.com/tinylib/msgp v1.3.0 h1:ULuf7GPooDaIlbyvgAxBV/FI7ynli6LZ1/nVUNu+0ww=
github.com/tinylib/msgp v1.3.0/go.mod h1:ykjzy2wzgrlvpDCRc4LA8UXy6D8bzMSuAF3WD57Gok0=
github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw=
github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc=
github.com/valyala/fasttemplate v1.2.2 h1:lxLXG0uE3Qnshl9QyaK6XJxMXlQZELvChBOCmQD0Loo=
github.com/valyala/fasttemplate v1.2.2/go.mod h1:KHLXt3tVN2HBp8eijSv/kGJopbvo7S+qRAEEKiv+SiQ=
github.com/vearutop/statigz v1.4.0 h1:RQL0KG3j/uyA/PFpHeZ/L6l2ta920/MxlOAIGEOuwmU=
github.com/vearutop/statigz v1.4.0/go.mod h1:LYTolBLiz9oJISwiVKnOQoIwhO1LWX1A7OECawGS8XE=
golang.org/x/crypto v0.39.0 h1:SHs+kF4LP+f+p14esP5jAoDpHU8Gu/v9lFRK6IT5imM=
golang.org/x/crypto v0.39.0/go.mod h1:L+Xg3Wf6HoL4Bn4238Z6ft6KfEpN0tJGo53AAPC632U=
golang.org/x/net v0.41.0 h1:vBTly1HeNPEn3wtREYfy4GZ/NECgw2Cnl+nK6Nz3uvw=
golang.org/x/net v0.41.0/go.mod h1:B/K4NNqkfmg07DQYrbwvSluqCJOOXwUjeb/5lOisjbA=
golang.org/x/sync v0.15.0 h1:KWH3jNZsfyT6xfAfKiz6MRNmd46ByHDYaZ7KSkCtdW8=
golang.org/x/sync v0.15.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.33.0 h1:q3i8TbbEz+JRD9ywIRlyRAQbM0qF7hu24q3teo2hbuw=
golang.org/x/sys v0.33.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
golang.org/x/text v0.26.0 h1:P42AVeLghgTYr4+xUnTRKDMqpar+PtX7KWuNQL21L8M=
golang.org/x/text v0.26.0/go.mod h1:QK15LZJUUQVJxhz7wXgxSy/CJaTFjd0G+YLonydOVQA=
golang.org/x/time v0.11.0 h1:/bpjEDfN9tkoN/ryeYHnv5hcMlc8ncjMcM4XBk5NWV0=
golang.org/x/time v0.11.0/go.mod h1:CDIdPxbZBQxdj6cxyCIdrNogrJKMJ7pr37NYpMcMDSg=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
+10 -3
View File
@@ -1,7 +1,14 @@
# Инфраструктура студента
Здесь разместите конфигурации выбранных сервисов; основную топологию — в корневом compose.yaml/stack.yaml. `compose.example.yaml` — только worksheet ролей и намеренно не запускается. `contracts/infrastructure.json` задаёт минимальные роли, не готовые образы/пароли.
Основной стенд использует `stack.yaml`: HAProxy → две API-реплики → PostgreSQL, Redis AOF и приватный MinIO.
Запуск: `make up`. Остановка с сохранением данных: `make down`.
Версии, секреты, ограничения и проверки описаны в [REPORT.md](../REPORT.md).
В REPORT.md сопоставьте роль → service name → версия/digest → health/readiness → volume → сеть/порт → способ передачи credentials. Приведите bootstrap (schema, bucket, broker topology, а с lab6 provisioning) и безопасное повторение этих команд.
`s3-bootstrap.sh` идемпотентно создаёт bucket и отдельного API-пользователя по `s3-policy.json`.
`minio-entrypoint.sh` читает root keys из Docker secrets. Консоль слушает loopback контейнера.
`Dockerfile.storage` собирает MinIO и mc из исходников с фиксированными commit и SHA-256.
`haproxy.cfg` проверяет readiness реплик. `redis.conf` включает AOF и запрещает eviction.
`migrate.sh` запускает goose без автоматической загрузки файлов окружения.
Приложение строится из исходников. Не используйте заранее существующий образ преподавательского сервера вместо своей реализации. Restart hook перезапускает все соответствующие stores с volumes; failover hook останавливает только заданную API-реплику.
Restart hook перезапускает API, HAProxy, PostgreSQL, Redis и MinIO с сохранением volumes.
Failover hook останавливает API-реплику по `TARGET_INSTANCE_ID`; Swarm создаёт новую task с другим ID.
+36
View File
@@ -0,0 +1,36 @@
global
log stdout format raw local0
maxconn 1024
defaults
log global
mode http
timeout connect 1s
timeout client 55s
timeout server 55s
timeout check 1s
retries 0
option http-server-close
resolvers docker
nameserver dns 127.0.0.11:53
resolve_retries 3
timeout resolve 1s
timeout retry 1s
hold valid 1s
hold obsolete 1s
hold nx 1s
hold refused 1s
hold timeout 1s
frontend public
bind :8080
default_backend api
backend api
balance roundrobin
option httpchk
http-check send meth GET uri /health/ready ver HTTP/1.1 hdr Host api
http-check expect status 200
default-server inter 1s fastinter 500ms downinter 1s fall 2 rise 1
server-template replica 1-8 tasks.api:8080 check resolvers docker init-addr none
+8
View File
@@ -0,0 +1,8 @@
#!/bin/sh
set -eu
# Keep the password out of argv and disable automatic dotenv loading.
if [ -n "${POSTGRES_PASSWORD_FILE:-}" ]; then
PGPASSWORD=$(cat "$POSTGRES_PASSWORD_FILE")
export PGPASSWORD
fi
exec goose -env /dev/null -dir /migrations -timeout 30s "$@"
+5
View File
@@ -0,0 +1,5 @@
#!/bin/sh
set -eu
export MINIO_ROOT_USER="$(cat /run/secrets/s3_root_access_key)"
export MINIO_ROOT_PASSWORD="$(cat /run/secrets/s3_root_secret_key)"
exec minio server /data --address :9000 --console-address 127.0.0.1:9001
+9
View File
@@ -0,0 +1,9 @@
bind 0.0.0.0
protected-mode no
port 6379
dir /data
appendonly yes
appendfsync always
save ""
maxmemory 64mb
maxmemory-policy noeviction
+11
View File
@@ -0,0 +1,11 @@
#!/bin/sh
set -eu
export MC_CONFIG_DIR=/tmp/mc
mc alias set admin http://minio:9000 "$(cat /run/secrets/s3_root_access_key)" "$(cat /run/secrets/s3_root_secret_key)" >/dev/null
mc ready admin >/dev/null
mc mb --ignore-existing admin/attachments >/dev/null
mc anonymous set none admin/attachments >/dev/null
mc admin policy create admin attachments-api /policy.json >/dev/null
mc admin user add admin "$(cat /run/secrets/s3_access_key)" "$(cat /run/secrets/s3_secret_key)" >/dev/null
mc admin policy attach admin attachments-api --user "$(cat /run/secrets/s3_access_key)" >/dev/null
printf '%s\n' 'PASS: private bucket and restricted API account configured.'
+21
View File
@@ -0,0 +1,21 @@
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": ["s3:GetBucketLocation"],
"Resource": ["arn:aws:s3:::attachments"]
},
{
"Effect": "Allow",
"Action": ["s3:ListBucket"],
"Resource": ["arn:aws:s3:::attachments"],
"Condition": {"StringLike": {"s3:prefix": ["original/*"]}}
},
{
"Effect": "Allow",
"Action": ["s3:GetObject", "s3:PutObject", "s3:DeleteObject"],
"Resource": ["arn:aws:s3:::attachments/original/*"]
}
]
}
+25
View File
@@ -0,0 +1,25 @@
# Схема и транзакционные границы
PostgreSQL — источник истины пользователей, чатов, участников и сообщений.
Redis — источник истины сессий: SHA-256 токена → user_id, expires_at; TTL до
абсолютного expires_at, без продления при чтении. Logout удаляет ключ.
Redis использует AOF с appendfsync always и отдельный именованный volume.
- users: UUID PK, UNIQUE(username), password_hash (Argon2id), display_name, created_at.
- chats: UUID PK, title, created_at; индекс (created_at, id).
- chat_members: PK(chat_id, user_id), FK к chats/users; ordinal сохраняет порядок
участников; UNIQUE(chat_id, ordinal); индекс (user_id, chat_id).
- messages: UUID PK, FK chat_id/sender_id через членство; text, created_at.
Индекс (chat_id, created_at, id) отвечает равенству по чату и keyset-предикату
(created_at, id) > ($timestamp, $id), ORDER BY created_at, id LIMIT $limit.
- goose_db_version: журнал goose CLI; SQL-миграция и запись её версии
коммитятся в одной транзакции. Сервис migrations завершается до старта API.
Регистрация — один INSERT, гонка разрешается UNIQUE, проигравшие получают 409.
Создание чата — одна транзакция: INSERT чата, затем участников; любой неверный
FK откатывает всю операцию, включая уже вставленных участников.
Отправка сообщения — один INSERT с FK на членство. Чтения идут в PostgreSQL,
кэша истории нет, подтверждённый COMMIT виден следующему запросу.
При конкурентной записи keyset не даёт snapshot: поздний COMMIT с ключом до
уже прочитанного cursor может быть пропущен. created_at задаёт PostgreSQL,
UUID разрешает совпадения времени; часы не используются как уникальный ID.
+31
View File
@@ -0,0 +1,31 @@
package chat
import (
"errors"
"github.com/labstack/echo/v4"
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain"
)
func (h *Chat) authorizedChat(c echo.Context, requestedChat domain.Chat) (domain.Chat, bool, error) {
chat, err := h.useCase.GetChat(c.Request().Context(), authenticatedUser(c).ID, requestedChat)
if err != nil {
return domain.Chat{}, false, h.useCaseError(c, err)
}
return chat, true, nil
}
func (h *Chat) cursorPosition(raw string, present bool, scope, owner string) (*domain.Position, error) {
if !present {
return nil, nil
}
if raw == "" {
return nil, errors.New("empty cursor")
}
createdAt, id, err := h.cursor.decode(raw, scope, owner)
if err != nil {
return nil, err
}
return &domain.Position{CreatedAt: createdAt, ID: id}, nil
}
+68
View File
@@ -0,0 +1,68 @@
package chat
import (
"context"
"mime"
"net/http"
"time"
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/attachment"
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain"
"github.com/labstack/echo/v4"
)
func (h *Chat) WithAttachments(service *attachment.Service) *Chat { h.attachments = service; return h }
func (h *Chat) uploadAttachment(c echo.Context) error {
chat, ok, err := h.authorizedChat(c, domain.Chat{ID: c.Param("chat_id")})
if err != nil || !ok {
return err
}
filename, present, err := oneQueryValue(c, "filename")
if err != nil || !present {
return h.invalid(c, "Требуется один filename")
}
if c.Request().ContentLength > attachment.MaxBytes {
return h.writeError(c, 413, "payload_too_large", "Файл превышает 10 MiB")
}
// Both socket reads and the application operation have a fixed deadline.
deadline := time.Now().Add(attachment.UploadTimeout)
_ = http.NewResponseController(c.Response().Writer).SetReadDeadline(deadline)
defer http.NewResponseController(c.Response().Writer).SetReadDeadline(time.Time{})
c.Request().Body = http.MaxBytesReader(c.Response(), c.Request().Body, attachment.MaxBytes+1)
a, err := h.attachments.Upload(c.Request().Context(), chat.ID, authenticatedUser(c).ID, filename, c.Request().Header.Get("Content-Type"), c.Request().Body)
if err != nil {
return h.useCaseError(c, err)
}
return c.JSON(http.StatusCreated, a)
}
func (h *Chat) getAttachment(c echo.Context) error {
a, err := h.attachments.Get(c.Request().Context(), c.Param("attachment_id"), authenticatedUser(c).ID)
if err != nil {
return h.useCaseError(c, err)
}
return c.JSON(http.StatusOK, a)
}
func (h *Chat) attachmentContent(c echo.Context) error {
a, err := h.attachments.Get(c.Request().Context(), c.Param("attachment_id"), authenticatedUser(c).ID)
if err != nil {
return h.useCaseError(c, err)
}
variant, present, err := oneQueryValue(c, "variant")
if err != nil {
return h.invalid(c, "Некорректный variant")
}
if present && variant != "original" {
return h.writeError(c, 404, "not_found", "Вариант не найден")
}
ctx, cancel := context.WithTimeout(c.Request().Context(), 45*time.Second)
defer cancel()
obj, err := h.attachments.Content(ctx, a)
if err != nil {
return h.useCaseError(c, err)
}
defer obj.Close()
c.Response().Header().Set("Content-Disposition", mime.FormatMediaType("attachment", map[string]string{"filename": a.Filename}))
c.Response().Header().Set("X-Content-Type-Options", "nosniff")
c.Response().Header().Set("Cache-Control", "private, no-store")
return c.Stream(http.StatusOK, a.ContentType, obj)
}
+33
View File
@@ -0,0 +1,33 @@
package chat
import (
"net/http"
"github.com/labstack/echo/v4"
"gitflic.ru/akselbant/mtusi2026lab1-fork/dto"
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain"
)
func (h *Chat) createChat(c echo.Context) error {
var request dto.CreateChatRequest
if err := decodeJSON(c, &request); err != nil {
return h.jsonError(c, err)
}
callerID := authenticatedUser(c).ID
chat, err := h.useCase.CreateChat(c.Request().Context(), callerID, createChatRequestToDomain(request))
if err != nil {
return h.useCaseError(c, err)
}
return c.JSON(http.StatusCreated, createChatResponseFromDomain(chat))
}
func createChatRequestToDomain(request dto.CreateChatRequest) domain.Chat {
return domain.Chat{Title: request.Title, MemberIDs: request.MemberIDs}
}
func createChatResponseFromDomain(chat domain.Chat) dto.CreateChatResponse {
return dto.CreateChatResponse{
ID: chat.ID, Title: chat.Title, MemberIDs: chat.MemberIDs, CreatedAt: dto.Timestamp(chat.CreatedAt),
}
}
+58
View File
@@ -0,0 +1,58 @@
package chat
import (
"net/http"
"regexp"
"github.com/labstack/echo/v4"
"gitflic.ru/akselbant/mtusi2026lab1-fork/dto"
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain"
)
var idempotencyKeyPattern = regexp.MustCompile(`^[A-Za-z0-9._:-]{1,128}$`)
func (h *Chat) createMessage(c echo.Context) error {
request := dto.CreateMessageRequest{ChatID: c.Param("chat_id")}
chat, ok, err := h.authorizedChat(c, domain.Chat{ID: request.ChatID})
if err != nil {
return err
}
if !ok {
return nil
}
if err := decodeJSON(c, &request); err != nil {
return h.jsonError(c, err)
}
request.ChatID = chat.ID
keys := c.Request().Header.Values("Idempotency-Key")
if len(keys) != 1 || !idempotencyKeyPattern.MatchString(keys[0]) {
return h.invalid(c, "Требуется Idempotency-Key: ASCII [A-Za-z0-9._:-]{1,128}")
}
input := createMessageRequestToDomain(request)
input.IdempotencyKey = keys[0]
message, err := h.useCase.CreateMessage(c.Request().Context(), authenticatedUser(c).ID, input)
if err != nil {
return h.useCaseError(c, err)
}
return c.JSON(http.StatusCreated, createMessageResponseFromDomain(message))
}
func createMessageRequestToDomain(request dto.CreateMessageRequest) domain.Message {
return domain.Message{ChatID: request.ChatID, Text: request.Text, AttachmentIDs: request.AttachmentIDs}
}
func createMessageResponseFromDomain(message domain.Message) dto.CreateMessageResponse {
return dto.CreateMessageResponse{
ID: message.ID, ChatID: message.ChatID, SenderID: message.SenderID,
Text: message.Text, AttachmentIDs: nonnilIDs(message.AttachmentIDs), CreatedAt: dto.Timestamp(message.CreatedAt),
}
}
func nonnilIDs(ids []string) []string {
if ids == nil {
return []string{}
}
return ids
}
+32
View File
@@ -0,0 +1,32 @@
package chat
import (
"net/http"
"github.com/labstack/echo/v4"
"gitflic.ru/akselbant/mtusi2026lab1-fork/dto"
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain"
)
func (h *Chat) createUser(c echo.Context) error {
var request dto.CreateUserRequest
if err := decodeJSON(c, &request); err != nil {
return h.jsonError(c, err)
}
user, err := h.useCase.CreateUser(c.Request().Context(), createUserRequestToDomain(request), request.Password)
if err != nil {
return h.useCaseError(c, err)
}
return c.JSON(http.StatusCreated, createUserResponseFromDomain(user))
}
func createUserRequestToDomain(request dto.CreateUserRequest) domain.User {
return domain.User{Username: request.Username, DisplayName: request.DisplayName}
}
func createUserResponseFromDomain(user domain.User) dto.CreateUserResponse {
return dto.CreateUserResponse{
ID: user.ID, Username: user.Username, DisplayName: user.DisplayName, CreatedAt: dto.Timestamp(user.CreatedAt),
}
}
+21
View File
@@ -0,0 +1,21 @@
package chat
import (
"net/http"
"github.com/labstack/echo/v4"
"gitflic.ru/akselbant/mtusi2026lab1-fork/dto"
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain"
)
func (h *Chat) currentUser(c echo.Context) error {
user := authenticatedUser(c)
return c.JSON(http.StatusOK, currentUserResponseFromDomain(user))
}
func currentUserResponseFromDomain(user domain.User) dto.CurrentUserResponse {
return dto.CurrentUserResponse{
ID: user.ID, Username: user.Username, DisplayName: user.DisplayName, CreatedAt: dto.Timestamp(user.CreatedAt),
}
}
+75
View File
@@ -0,0 +1,75 @@
package chat
import (
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"errors"
"strings"
"time"
"github.com/google/uuid"
)
type cursorPayload struct {
Scope string `json:"scope"`
Owner string `json:"owner"`
CreatedAt string `json:"created_at"`
ID string `json:"id"`
}
type cursorCodec struct {
secret [32]byte
}
func (c cursorCodec) encode(scope, owner string, createdAt time.Time, id string) string {
payload, err := json.Marshal(cursorPayload{
Scope: scope,
Owner: owner,
CreatedAt: createdAt.UTC().Format(time.RFC3339Nano),
ID: id,
})
if err != nil {
panic("cannot encode cursor: " + err.Error())
}
signature := c.sign(payload)
return base64.RawURLEncoding.EncodeToString(payload) + "." + base64.RawURLEncoding.EncodeToString(signature)
}
func (c cursorCodec) decode(raw, scope, owner string) (time.Time, string, error) {
parts := strings.Split(raw, ".")
if len(parts) != 2 {
return time.Time{}, "", errors.New("malformed cursor")
}
payload, err := base64.RawURLEncoding.DecodeString(parts[0])
if err != nil {
return time.Time{}, "", errors.New("malformed cursor")
}
signature, err := base64.RawURLEncoding.DecodeString(parts[1])
if err != nil || !hmac.Equal(signature, c.sign(payload)) {
return time.Time{}, "", errors.New("invalid cursor signature")
}
var value cursorPayload
if err := json.Unmarshal(payload, &value); err != nil {
return time.Time{}, "", errors.New("malformed cursor payload")
}
if value.Scope != scope || value.Owner != owner {
return time.Time{}, "", errors.New("cursor belongs to another resource")
}
parsedID, err := uuid.Parse(value.ID)
if err != nil || parsedID.String() != value.ID {
return time.Time{}, "", errors.New("malformed cursor id")
}
createdAt, err := time.Parse(time.RFC3339Nano, value.CreatedAt)
if err != nil {
return time.Time{}, "", errors.New("malformed cursor timestamp")
}
return createdAt, value.ID, nil
}
func (c cursorCodec) sign(payload []byte) []byte {
mac := hmac.New(sha256.New, c.secret[:])
_, _ = mac.Write(payload)
return mac.Sum(nil)
}
+95
View File
@@ -0,0 +1,95 @@
package chat
import (
"errors"
"net/http"
"github.com/google/uuid"
"github.com/labstack/echo/v4"
"gitflic.ru/akselbant/mtusi2026lab1-fork/dto"
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain"
)
func (h *Chat) invalid(c echo.Context, message string) error {
return h.writeError(c, http.StatusBadRequest, "invalid_request", message)
}
func (h *Chat) jsonError(c echo.Context, err error) error {
if errors.Is(err, errUnsupportedMediaType) {
return h.writeError(c, http.StatusUnsupportedMediaType, "unsupported_media_type", "Content-Type должен быть application/json")
}
var tooLarge *http.MaxBytesError
if errors.As(err, &tooLarge) {
return h.writeError(c, http.StatusRequestEntityTooLarge, "payload_too_large", "Тело запроса слишком большое")
}
return h.invalid(c, err.Error())
}
func (h *Chat) useCaseError(c echo.Context, err error) error {
applicationError, ok := domain.AsApplicationError(err)
if !ok {
return err
}
status := http.StatusInternalServerError
switch applicationError.Code {
case "unsupported_media_type":
status = http.StatusUnsupportedMediaType
case "payload_too_large":
status = http.StatusRequestEntityTooLarge
case domain.ErrorUnavailable:
status = http.StatusServiceUnavailable
case domain.ErrorInvalid:
status = http.StatusBadRequest
case domain.ErrorUnauthorized:
status = http.StatusUnauthorized
challenge := `Bearer realm="messenger"`
if c.Path() == "/api/v1/auth/sessions" {
challenge = `Basic realm="messenger", charset="UTF-8"`
}
c.Response().Header().Set("WWW-Authenticate", challenge)
case domain.ErrorNotFound:
status = http.StatusNotFound
case domain.ErrorConflict:
status = http.StatusConflict
}
return h.writeError(c, status, string(applicationError.Code), applicationError.Message)
}
func (h *Chat) writeError(c echo.Context, status int, code, message string) error {
return c.JSON(status, dto.ErrorResponse{Error: dto.ErrorDetails{
Code: code,
Message: message,
RequestID: requestID(c),
}})
}
func (h *Chat) httpErrorHandler(err error, c echo.Context) {
if c.Response().Committed {
return
}
status := http.StatusInternalServerError
code := "internal_error"
message := "Внутренняя ошибка сервера"
var httpError *echo.HTTPError
if errors.As(err, &httpError) {
status = httpError.Code
switch status {
case http.StatusNotFound:
code, message = "not_found", "Объект не найден"
case http.StatusMethodNotAllowed, http.StatusBadRequest:
code, message = "invalid_request", "Некорректный запрос"
}
}
_ = h.writeError(c, status, code, message)
}
func requestID(c echo.Context) string {
value, _ := c.Get(requestIDKey).(string)
if value == "" {
value = uuid.NewString()
c.Set(requestIDKey, value)
c.Response().Header().Set("X-Request-Id", value)
}
return value
}
+32
View File
@@ -0,0 +1,32 @@
package chat
import (
"net/http"
"github.com/labstack/echo/v4"
"gitflic.ru/akselbant/mtusi2026lab1-fork/dto"
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain"
)
func (h *Chat) getChat(c echo.Context) error {
request := dto.GetChatRequest{ChatID: c.Param("chat_id")}
chat, ok, err := h.authorizedChat(c, getChatRequestToDomain(request))
if err != nil {
return err
}
if !ok {
return nil
}
return c.JSON(http.StatusOK, getChatResponseFromDomain(chat))
}
func getChatRequestToDomain(request dto.GetChatRequest) domain.Chat {
return domain.Chat{ID: request.ChatID}
}
func getChatResponseFromDomain(chat domain.Chat) dto.GetChatResponse {
return dto.GetChatResponse{
ID: chat.ID, Title: chat.Title, MemberIDs: chat.MemberIDs, CreatedAt: dto.Timestamp(chat.CreatedAt),
}
}
+53
View File
@@ -0,0 +1,53 @@
package chat
import (
"net/http"
"github.com/labstack/echo/v4"
"gitflic.ru/akselbant/mtusi2026lab1-fork/dto"
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain"
)
func (h *Chat) listChats(c echo.Context) error {
limit, err := parseLimit(c)
if err != nil {
return h.invalid(c, err.Error())
}
rawCursor, cursorPresent, err := oneQueryValue(c, "cursor")
if err != nil {
return h.invalid(c, "cursor должен быть указан один раз")
}
request := dto.ListChatsRequest{Limit: limit, Cursor: rawCursor}
userID := authenticatedUser(c).ID
position, err := h.cursorPosition(request.Cursor, cursorPresent, "chats", userID)
if err != nil {
return h.invalid(c, "Некорректный cursor")
}
page, err := h.useCase.ListChats(c.Request().Context(), userID, listChatsRequestToDomain(request, position))
if err != nil {
return h.useCaseError(c, err)
}
var next *string
if page.HasMore {
last := page.Items[len(page.Items)-1]
encoded := h.cursor.encode("chats", userID, last.CreatedAt, last.ID)
next = &encoded
}
return c.JSON(http.StatusOK, listChatsResponseFromDomain(page, next))
}
func listChatsRequestToDomain(request dto.ListChatsRequest, position *domain.Position) domain.Pagination {
return domain.Pagination{After: position, Limit: request.Limit}
}
func listChatsResponseFromDomain(page domain.ChatPage, nextCursor *string) dto.ListChatsResponse {
items := make([]dto.ListChatsItem, 0, len(page.Items))
for _, chat := range page.Items {
items = append(items, dto.ListChatsItem{
ID: chat.ID, Title: chat.Title, MemberIDs: chat.MemberIDs, CreatedAt: dto.Timestamp(chat.CreatedAt),
})
}
return dto.ListChatsResponse{Items: items, NextCursor: nextCursor}
}
+70
View File
@@ -0,0 +1,70 @@
package chat
import (
"net/http"
"github.com/labstack/echo/v4"
"gitflic.ru/akselbant/mtusi2026lab1-fork/dto"
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain"
)
func (h *Chat) listMessages(c echo.Context) error {
request := dto.ListMessagesRequest{ChatID: c.Param("chat_id")}
chat, ok, err := h.authorizedChat(c, domain.Chat{ID: request.ChatID})
if err != nil {
return err
}
if !ok {
return nil
}
limit, err := parseLimit(c)
if err != nil {
return h.invalid(c, err.Error())
}
rawCursor, cursorPresent, err := oneQueryValue(c, "cursor")
if err != nil {
return h.invalid(c, "cursor должен быть указан один раз")
}
request.ChatID = chat.ID
request.Limit = limit
request.Cursor = rawCursor
position, err := h.cursorPosition(request.Cursor, cursorPresent, "messages", request.ChatID)
if err != nil {
return h.invalid(c, "Некорректный cursor")
}
page, err := h.useCase.ListMessages(
c.Request().Context(), authenticatedUser(c).ID,
listMessagesChatToDomain(request), listMessagesPaginationToDomain(request, position),
)
if err != nil {
return h.useCaseError(c, err)
}
var next *string
if page.HasMore {
last := page.Items[len(page.Items)-1]
encoded := h.cursor.encode("messages", request.ChatID, last.CreatedAt, last.ID)
next = &encoded
}
return c.JSON(http.StatusOK, listMessagesResponseFromDomain(page, next))
}
func listMessagesChatToDomain(request dto.ListMessagesRequest) domain.Chat {
return domain.Chat{ID: request.ChatID}
}
func listMessagesPaginationToDomain(request dto.ListMessagesRequest, position *domain.Position) domain.Pagination {
return domain.Pagination{After: position, Limit: request.Limit}
}
func listMessagesResponseFromDomain(page domain.MessagePage, nextCursor *string) dto.ListMessagesResponse {
items := make([]dto.ListMessagesItem, 0, len(page.Items))
for _, message := range page.Items {
items = append(items, dto.ListMessagesItem{
ID: message.ID, ChatID: message.ChatID, SenderID: message.SenderID,
Text: message.Text, AttachmentIDs: nonnilIDs(message.AttachmentIDs), CreatedAt: dto.Timestamp(message.CreatedAt),
})
}
return dto.ListMessagesResponse{Items: items, NextCursor: nextCursor}
}
+13
View File
@@ -0,0 +1,13 @@
package chat
import (
"net/http"
"github.com/labstack/echo/v4"
"gitflic.ru/akselbant/mtusi2026lab1-fork/dto"
)
func (h *Chat) liveness(c echo.Context) error {
return c.JSON(http.StatusOK, dto.LivenessResponse{Status: "ok"})
}
+43
View File
@@ -0,0 +1,43 @@
package chat
import (
"net/http"
"github.com/google/uuid"
"github.com/labstack/echo/v4"
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain"
)
const (
requestIDKey = "request_id"
userKey = "current_user"
)
func (h *Chat) requestIDMiddleware(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
requestID := uuid.NewString()
c.Set(requestIDKey, requestID)
c.Response().Header().Set("X-Request-Id", requestID)
c.Response().Header().Set("X-Instance-Id", h.instanceID)
if h.draining.Load() && c.Request().URL.Path != "/health/live" {
return h.writeError(c, http.StatusServiceUnavailable, "unavailable", "Реплика завершает работу")
}
return next(c)
}
}
func (h *Chat) authenticate(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
user, err := h.useCase.Authenticate(c.Request().Context(), bearerToken(c))
if err != nil {
return h.useCaseError(c, err)
}
c.Set(userKey, user)
return next(c)
}
}
func authenticatedUser(c echo.Context) domain.User {
return c.Get(userKey).(domain.User)
}
+25
View File
@@ -0,0 +1,25 @@
package chat
import (
"context"
"net/http"
"time"
"github.com/labstack/echo/v4"
"gitflic.ru/akselbant/mtusi2026lab1-fork/dto"
)
func (h *Chat) readiness(c echo.Context) error {
ctx, cancel := context.WithTimeout(c.Request().Context(), 2*time.Second)
defer cancel()
if err := h.useCase.Ready(ctx); err != nil {
return h.useCaseError(c, err)
}
if h.attachments != nil {
if err := h.attachments.Ready(ctx); err != nil {
return h.useCaseError(c, err)
}
}
return c.JSON(http.StatusOK, dto.ReadinessResponse{Status: "ok"})
}
+74
View File
@@ -0,0 +1,74 @@
package chat
import (
"encoding/json"
"errors"
"fmt"
"io"
"mime"
"net/http"
"strconv"
"github.com/labstack/echo/v4"
)
const (
defaultLimit = 50
maxLimit = 100
maxJSONBody = 1 << 20
)
var errUnsupportedMediaType = errors.New("unsupported media type")
func decodeJSON(c echo.Context, target any) error {
mediaType, _, err := mime.ParseMediaType(c.Request().Header.Get(echo.HeaderContentType))
if err != nil || mediaType != echo.MIMEApplicationJSON {
return errUnsupportedMediaType
}
reader := http.MaxBytesReader(c.Response(), c.Request().Body, maxJSONBody)
decoder := json.NewDecoder(reader)
decoder.DisallowUnknownFields()
if err := decoder.Decode(target); err != nil {
var tooLarge *http.MaxBytesError
if errors.As(err, &tooLarge) {
return err
}
return errors.New("Некорректное JSON-тело")
}
var extra any
err = decoder.Decode(&extra)
var tooLarge *http.MaxBytesError
if errors.As(err, &tooLarge) {
return err
}
if !errors.Is(err, io.EOF) {
return errors.New("JSON-тело должно содержать ровно один объект")
}
return nil
}
func parseLimit(c echo.Context) (int, error) {
raw, present, err := oneQueryValue(c, "limit")
if err != nil {
return 0, errors.New("limit должен быть указан один раз")
}
if !present {
return defaultLimit, nil
}
limit, err := strconv.Atoi(raw)
if err != nil || limit < 1 || limit > maxLimit {
return 0, fmt.Errorf("limit должен быть целым числом от 1 до %d", maxLimit)
}
return limit, nil
}
func oneQueryValue(c echo.Context, name string) (string, bool, error) {
values, present := c.QueryParams()[name]
if !present {
return "", false, nil
}
if len(values) != 1 {
return "", true, errors.New("query parameter must occur once")
}
return values[0], true, nil
}
+93
View File
@@ -0,0 +1,93 @@
package chat
import (
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/attachment"
"log"
"os"
"sync/atomic"
"github.com/google/uuid"
"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
"github.com/swaggest/swgui/v5emb"
)
// Chat is the HTTP handler and depends only on the application boundary.
type Chat struct {
attachments *attachment.Service
instanceID string
draining atomic.Bool
useCase UseCase
cursor cursorCodec
}
func NewChat(useCase UseCase, cursorKey [32]byte) *Chat {
instanceID := os.Getenv("INSTANCE_ID")
if instanceID == "" {
instanceID = uuid.NewString()
}
return &Chat{useCase: useCase, cursor: cursorCodec{secret: cursorKey}, instanceID: instanceID}
}
func (h *Chat) Drain() { h.draining.Store(true) }
func (h *Chat) Router() *echo.Echo {
e := echo.New()
e.HideBanner = true
e.HidePort = true
e.HTTPErrorHandler = h.httpErrorHandler
e.Use(h.requestIDMiddleware)
e.Use(middleware.RequestLoggerWithConfig(middleware.RequestLoggerConfig{
HandleError: true,
LogLatency: true,
LogMethod: true,
LogRoutePath: true,
LogURIPath: true,
LogRequestID: true,
LogStatus: true,
LogResponseSize: true,
LogValuesFunc: func(_ echo.Context, values middleware.RequestLoggerValues) error {
path := values.RoutePath
if path == "" {
path = values.URIPath
}
log.Printf(
"request_id=%s method=%s path=%s status=%d response_bytes=%d latency=%s",
values.RequestID, values.Method, path, values.Status, values.ResponseSize, values.Latency,
)
return nil
},
}))
e.Use(middleware.Recover())
e.GET("/health/live", h.liveness)
e.GET("/health/ready", h.readiness)
swaggerUI := echo.WrapHandler(v5emb.New(
"MTUSI Messenger",
"/swagger/openapi.json",
"/swagger/",
))
e.GET("/swagger", h.swagger)
e.GET("/swagger/", swaggerUI)
e.GET("/swagger/openapi.json", h.swaggerSpec)
e.GET("/swagger/*", swaggerUI)
e.POST("/api/v1/users", h.createUser)
e.POST("/api/v1/auth/sessions", h.createSession)
api := e.Group("/api/v1", h.authenticate)
api.GET("/users/me", h.currentUser)
api.DELETE("/auth/sessions/current", h.deleteSession)
api.POST("/chats", h.createChat)
api.GET("/chats", h.listChats)
api.GET("/chats/:chat_id", h.getChat)
api.POST("/chats/:chat_id/messages", h.createMessage)
api.GET("/chats/:chat_id/messages", h.listMessages)
if h.attachments != nil {
api.POST("/chats/:chat_id/attachments", h.uploadAttachment)
api.GET("/attachments/:attachment_id", h.getAttachment)
api.GET("/attachments/:attachment_id/content", h.attachmentContent)
}
return e
}
+353
View File
@@ -0,0 +1,353 @@
package chat_test
import (
"bytes"
"context"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"net/http"
"net/http/httptest"
"net/url"
"sync"
"testing"
"time"
"github.com/google/uuid"
chathandler "gitflic.ru/akselbant/mtusi2026lab1-fork/internal/app/chat"
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain"
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/repository"
chatusecase "gitflic.ru/akselbant/mtusi2026lab1-fork/internal/usecase/chat"
)
type testAPI struct {
server *httptest.Server
tokens sync.Map
}
type userResponse struct {
ID string `json:"id"`
}
type chatResponse struct {
ID string `json:"id"`
}
type messageResponse struct {
ID string `json:"id"`
Text string `json:"text"`
}
type messagePageResponse struct {
Items []messageResponse `json:"items"`
NextCursor *string `json:"next_cursor"`
}
type errorResponse struct {
Error struct {
Code string `json:"code"`
} `json:"error"`
}
func newTestAPI(t *testing.T) *testAPI {
t.Helper()
useCase := chatusecase.New(repository.NewMemory(), &testSessions{values: map[string]domain.Session{}}, time.Hour)
server := httptest.NewServer(chathandler.NewChat(useCase, [32]byte{1}).Router())
t.Cleanup(server.Close)
return &testAPI{server: server}
}
func (a *testAPI) request(t *testing.T, client *http.Client, method, path, actorID, body string, wantStatus int, target any) {
t.Helper()
request, err := http.NewRequest(method, a.server.URL+path, bytes.NewBufferString(body))
if err != nil {
t.Fatalf("create request: %v", err)
}
if body != "" {
request.Header.Set("Content-Type", "application/json")
request.Header.Set("Idempotency-Key", uuid.NewString())
}
if actorID != "" {
token, _ := a.tokens.Load(actorID)
request.Header.Set("Authorization", "Bearer "+token.(string))
}
response, err := client.Do(request)
if err != nil {
t.Fatalf("%s %s: %v", method, path, err)
}
defer response.Body.Close()
responseBody, err := io.ReadAll(response.Body)
if err != nil {
t.Fatalf("read response: %v", err)
}
if response.StatusCode != wantStatus {
t.Fatalf("%s %s: status=%d, want=%d, body=%s", method, path, response.StatusCode, wantStatus, responseBody)
}
if response.Header.Get("X-Request-Id") == "" {
t.Fatalf("%s %s: missing X-Request-Id", method, path)
}
if target != nil {
if err := json.Unmarshal(responseBody, target); err != nil {
t.Fatalf("decode response %q: %v", responseBody, err)
}
}
}
func (a *testAPI) createUser(t *testing.T, username string) userResponse {
t.Helper()
var user userResponse
a.request(t, http.DefaultClient, http.MethodPost, "/api/v1/users", "",
fmt.Sprintf(`{"username":%q,"display_name":%q,"password":"test-password-12345"}`, username, username), http.StatusCreated, &user)
req, err := http.NewRequest(http.MethodPost, a.server.URL+"/api/v1/auth/sessions", nil)
if err != nil {
t.Fatal(err)
}
req.Header.Set("Authorization", "Basic "+base64.StdEncoding.EncodeToString([]byte(username+":test-password-12345")))
response, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatal(err)
}
defer response.Body.Close()
var login struct {
Token string `json:"token"`
}
if response.StatusCode != http.StatusCreated {
t.Fatalf("login status: %d", response.StatusCode)
}
if err = json.NewDecoder(response.Body).Decode(&login); err != nil {
t.Fatal(err)
}
a.tokens.Store(user.ID, login.Token)
return user
}
func (a *testAPI) requestError(t *testing.T, method, path, actorID, body string, wantStatus int, wantCode string) {
t.Helper()
var response errorResponse
a.request(t, http.DefaultClient, method, path, actorID, body, wantStatus, &response)
if response.Error.Code != wantCode {
t.Fatalf("%s %s: error code=%q, want=%q", method, path, response.Error.Code, wantCode)
}
}
func (a *testAPI) createChat(t *testing.T, ownerID string, memberIDs []string) chatResponse {
t.Helper()
body, err := json.Marshal(map[string]any{"title": "test chat", "member_ids": memberIDs})
if err != nil {
t.Fatalf("encode chat: %v", err)
}
var chat chatResponse
a.request(t, http.DefaultClient, http.MethodPost, "/api/v1/chats", ownerID, string(body), http.StatusCreated, &chat)
return chat
}
func (a *testAPI) createMessage(t *testing.T, client *http.Client, actorID, chatID, text string) messageResponse {
t.Helper()
body, err := json.Marshal(map[string]string{"text": text})
if err != nil {
t.Fatalf("encode message: %v", err)
}
var message messageResponse
a.request(t, client, http.MethodPost, "/api/v1/chats/"+chatID+"/messages", actorID, string(body), http.StatusCreated, &message)
return message
}
func TestRejectsMalformedJSON(t *testing.T) {
api := newTestAPI(t)
api.requestError(t, http.MethodPost, "/api/v1/users", "",
`{"username":`, http.StatusBadRequest, "invalid_request")
}
func TestHidesForeignChat(t *testing.T) {
api := newTestAPI(t)
owner := api.createUser(t, "owner_user")
outsider := api.createUser(t, "outsider_user")
chat := api.createChat(t, owner.ID, []string{owner.ID})
api.requestError(t, http.MethodGet, "/api/v1/chats/"+chat.ID, outsider.ID,
"", http.StatusNotFound, "not_found")
}
func TestRejectsEmptyMessage(t *testing.T) {
api := newTestAPI(t)
user := api.createUser(t, "empty_message_user")
chat := api.createChat(t, user.ID, []string{user.ID})
api.requestError(t, http.MethodPost, "/api/v1/chats/"+chat.ID+"/messages", user.ID,
`{"text":" "}`, http.StatusBadRequest, "invalid_request")
}
func TestRejectsDuplicateUsername(t *testing.T) {
api := newTestAPI(t)
api.createUser(t, "duplicate_user")
api.requestError(t, http.MethodPost, "/api/v1/users", "",
`{"username":"duplicate_user","display_name":"Duplicate","password":"test-password-12345"}`, http.StatusConflict, "conflict")
}
func TestPaginatesMessagesAcrossMultiplePages(t *testing.T) {
api := newTestAPI(t)
user := api.createUser(t, "pagination_user")
chat := api.createChat(t, user.ID, []string{user.ID})
for index := 0; index < 7; index++ {
api.createMessage(t, http.DefaultClient, user.ID, chat.ID, fmt.Sprintf("message-%d", index))
}
seen := make(map[string]struct{})
cursor := ""
pageSizes := make([]int, 0, 4)
for {
path := "/api/v1/chats/" + chat.ID + "/messages?limit=2"
if cursor != "" {
path += "&cursor=" + url.QueryEscape(cursor)
}
var page messagePageResponse
api.request(t, http.DefaultClient, http.MethodGet, path, user.ID, "", http.StatusOK, &page)
pageSizes = append(pageSizes, len(page.Items))
for _, message := range page.Items {
if _, duplicate := seen[message.ID]; duplicate {
t.Fatalf("message %s appeared on multiple pages", message.ID)
}
seen[message.ID] = struct{}{}
}
if page.NextCursor == nil {
break
}
cursor = *page.NextCursor
}
if len(seen) != 7 {
t.Fatalf("received %d unique messages, want 7", len(seen))
}
wantPageSizes := []int{2, 2, 2, 1}
if fmt.Sprint(pageSizes) != fmt.Sprint(wantPageSizes) {
t.Fatalf("page sizes=%v, want=%v", pageSizes, wantPageSizes)
}
}
func TestConcurrentMessagesAreUnique(t *testing.T) {
api := newTestAPI(t)
users := make([]userResponse, 10)
memberIDs := make([]string, 10)
for index := range users {
users[index] = api.createUser(t, fmt.Sprintf("parallel_user_%02d", index))
memberIDs[index] = users[index].ID
}
chat := api.createChat(t, users[0].ID, memberIDs)
start := make(chan struct{})
errors := make(chan error, 10)
var waitGroup sync.WaitGroup
for clientIndex := 0; clientIndex < 10; clientIndex++ {
waitGroup.Add(1)
go func(clientIndex int) {
defer waitGroup.Done()
client := &http.Client{Transport: &http.Transport{}, Timeout: 5 * time.Second}
defer client.CloseIdleConnections()
<-start
for messageIndex := 0; messageIndex < 10; messageIndex++ {
body, err := json.Marshal(map[string]string{
"text": fmt.Sprintf("client-%02d-message-%02d", clientIndex, messageIndex),
})
if err != nil {
errors <- err
return
}
request, err := http.NewRequest(http.MethodPost,
api.server.URL+"/api/v1/chats/"+chat.ID+"/messages", bytes.NewReader(body))
if err != nil {
errors <- err
return
}
request.Header.Set("Content-Type", "application/json")
request.Header.Set("Idempotency-Key", uuid.NewString())
token, _ := api.tokens.Load(users[clientIndex].ID)
request.Header.Set("Authorization", "Bearer "+token.(string))
response, err := client.Do(request)
if err != nil {
errors <- err
return
}
_, readErr := io.Copy(io.Discard, response.Body)
closeErr := response.Body.Close()
if readErr != nil {
errors <- readErr
return
}
if closeErr != nil {
errors <- closeErr
return
}
if response.StatusCode != http.StatusCreated {
errors <- fmt.Errorf("client %d message %d: status=%d", clientIndex, messageIndex, response.StatusCode)
return
}
}
}(clientIndex)
}
close(start)
waitGroup.Wait()
close(errors)
for err := range errors {
if err != nil {
t.Fatal(err)
}
}
seenIDs := make(map[string]struct{}, 10*10)
seenTexts := make(map[string]struct{}, 10*10)
cursor := ""
for {
path := "/api/v1/chats/" + chat.ID + "/messages?limit=17"
if cursor != "" {
path += "&cursor=" + url.QueryEscape(cursor)
}
var page messagePageResponse
api.request(t, http.DefaultClient, http.MethodGet, path, users[0].ID, "", http.StatusOK, &page)
for _, message := range page.Items {
if _, duplicate := seenIDs[message.ID]; duplicate {
t.Fatalf("duplicate message ID %s", message.ID)
}
if _, duplicate := seenTexts[message.Text]; duplicate {
t.Fatalf("duplicate message text %q", message.Text)
}
seenIDs[message.ID] = struct{}{}
seenTexts[message.Text] = struct{}{}
}
if page.NextCursor == nil {
break
}
cursor = *page.NextCursor
}
if len(seenIDs) != 10*10 || len(seenTexts) != 10*10 {
t.Fatalf("received %d unique IDs and %d unique texts, want %d of each",
len(seenIDs), len(seenTexts), 10*10)
}
}
// Session fake is only used by HTTP unit tests; the server always uses Redis.
type testSessions struct {
mu sync.Mutex
values map[string]domain.Session
}
func (s *testSessions) Ready(context.Context) error { return nil }
func (s *testSessions) Put(_ context.Context, key string, value domain.Session) error {
s.mu.Lock()
defer s.mu.Unlock()
s.values[key] = value
return nil
}
func (s *testSessions) Get(_ context.Context, key string) (domain.Session, bool, error) {
s.mu.Lock()
defer s.mu.Unlock()
value, ok := s.values[key]
return value, ok, nil
}
func (s *testSessions) Delete(_ context.Context, key string) (bool, error) {
s.mu.Lock()
defer s.mu.Unlock()
_, ok := s.values[key]
delete(s.values, key)
return ok, nil
}
+45
View File
@@ -0,0 +1,45 @@
package chat
import (
"io"
"net/http"
"strings"
"github.com/labstack/echo/v4"
"gitflic.ru/akselbant/mtusi2026lab1-fork/dto"
)
func bearerToken(c echo.Context) string {
parts := strings.Fields(c.Request().Header.Get("Authorization"))
if len(parts) != 2 || !strings.EqualFold(parts[0], "Bearer") {
return ""
}
return parts[1]
}
func (h *Chat) createSession(c echo.Context) error {
username, password, ok := c.Request().BasicAuth()
if !ok {
c.Response().Header().Set("WWW-Authenticate", `Basic realm="messenger", charset="UTF-8"`)
return h.writeError(c, http.StatusUnauthorized, "unauthorized", "Неверные учётные данные")
}
body, err := io.ReadAll(io.LimitReader(c.Request().Body, 1))
if err != nil || len(body) != 0 {
return h.invalid(c, "Тело запроса входа должно быть пустым")
}
login, err := h.useCase.CreateSession(c.Request().Context(), username, password)
if err != nil {
return h.useCaseError(c, err)
}
return c.JSON(http.StatusCreated, dto.CreateSessionResponse{
Token: login.Token, TokenType: "Bearer", ExpiresAt: dto.Timestamp(login.ExpiresAt), User: createUserResponseFromDomain(login.User),
})
}
func (h *Chat) deleteSession(c echo.Context) error {
if err := h.useCase.DeleteSession(c.Request().Context(), bearerToken(c)); err != nil {
return h.useCaseError(c, err)
}
return c.NoContent(http.StatusNoContent)
}
+38
View File
@@ -0,0 +1,38 @@
package chat
import (
"encoding/json"
"net/http"
"github.com/labstack/echo/v4"
"gitflic.ru/akselbant/mtusi2026lab1-fork/contracts"
)
var swaggerOpenAPI = makeSwaggerOpenAPI()
func (h *Chat) swagger(c echo.Context) error {
return c.Redirect(http.StatusTemporaryRedirect, "/swagger/")
}
func (h *Chat) swaggerSpec(c echo.Context) error {
return c.Blob(http.StatusOK, echo.MIMEApplicationJSON, swaggerOpenAPI)
}
func makeSwaggerOpenAPI() []byte {
var document map[string]any
if err := json.Unmarshal(contracts.OpenAPI, &document); err != nil {
panic("cannot decode embedded OpenAPI contract: " + err.Error())
}
// A relative URL keeps Swagger requests on the same scheme, host and port
// as the UI. This also works behind a reverse proxy and on a custom PORT.
document["servers"] = []map[string]string{{
"url": "/",
"description": "Текущий адрес Swagger UI",
}}
encoded, err := json.Marshal(document)
if err != nil {
panic("cannot encode Swagger OpenAPI contract: " + err.Error())
}
return encoded
}
+21
View File
@@ -0,0 +1,21 @@
package chat
import (
"context"
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain"
)
// UseCase is the application boundary required by the HTTP handler.
type UseCase interface {
Ready(context.Context) error
CreateSession(context.Context, string, string) (domain.Login, error)
DeleteSession(context.Context, string) error
Authenticate(ctx context.Context, token string) (domain.User, error)
CreateUser(ctx context.Context, user domain.User, password string) (domain.User, error)
CreateChat(ctx context.Context, callerID string, chat domain.Chat) (domain.Chat, error)
GetChat(ctx context.Context, callerID string, chat domain.Chat) (domain.Chat, error)
ListChats(ctx context.Context, callerID string, pagination domain.Pagination) (domain.ChatPage, error)
CreateMessage(ctx context.Context, callerID string, message domain.Message) (domain.Message, error)
ListMessages(ctx context.Context, callerID string, chat domain.Chat, pagination domain.Pagination) (domain.MessagePage, error)
}
+128
View File
@@ -0,0 +1,128 @@
package attachment
import (
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"image"
_ "image/jpeg"
_ "image/png"
"io"
"mime"
"os"
"strings"
"unicode"
"unicode/utf8"
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain"
)
const MaxBytes int64 = 10 * 1024 * 1024
const MaxPixels int64 = 40_000_000
func appError(code domain.ErrorCode, message string) error {
return domain.NewApplicationError(code, message)
}
func unavailable() error {
return appError(domain.ErrorUnavailable, "Хранилище вложений недоступно")
}
func ValidateFilename(name string) error {
if !utf8.ValidString(name) || strings.TrimSpace(name) == "" || utf8.RuneCountInString(name) > 255 {
return appError(domain.ErrorInvalid, "Некорректный filename")
}
for _, r := range name {
if r == '/' || r == '\\' || unicode.IsControl(r) {
return appError(domain.ErrorInvalid, "Недопустимые символы filename")
}
}
return nil
}
type Original struct {
File *os.File
Size int64
SHA256, ContentType string
Width, Height int
}
func (o *Original) Close() { name := o.File.Name(); o.File.Close(); os.Remove(name) }
// Spool bounds compressed bytes on disk before any decode. DecodeConfig checks the
// pixel budget before a full decode verifies CRCs/truncated scan data.
func Spool(ctx context.Context, body io.Reader, declared string) (*Original, error) {
media, _, err := mime.ParseMediaType(declared)
if err != nil || (media != "image/png" && media != "image/jpeg") {
return nil, appError("unsupported_media_type", "Допустимы PNG и JPEG")
}
f, err := os.CreateTemp("", "messenger-upload-*")
if err != nil {
return nil, unavailable()
}
o := &Original{File: f}
good := false
defer func() {
if !good {
o.Close()
}
}()
hash := sha256.New()
n, err := io.Copy(io.MultiWriter(f, hash), io.LimitReader(&contextReader{ctx: ctx, r: body}, MaxBytes+1))
if n > MaxBytes {
return nil, appError("payload_too_large", "Файл превышает 10 MiB")
}
if err != nil {
return nil, appError(domain.ErrorInvalid, "Загрузка прервана")
}
o.Size = n
o.SHA256 = hex.EncodeToString(hash.Sum(nil))
if _, err = f.Seek(0, 0); err != nil {
return nil, unavailable()
}
cfg, format, err := image.DecodeConfig(f)
if err != nil {
return nil, appError("unsupported_media_type", "Повреждённое изображение")
}
actual := "image/" + format
if actual != media {
return nil, appError("unsupported_media_type", "MIME не соответствует содержимому")
}
if cfg.Width <= 0 || cfg.Height <= 0 || int64(cfg.Width) > MaxPixels/int64(cfg.Height) {
return nil, appError("payload_too_large", "Изображение превышает 40 миллионов пикселей")
}
if _, err = f.Seek(0, 0); err != nil {
return nil, unavailable()
}
decoded, format, err := image.Decode(f)
if err != nil || decoded == nil || "image/"+format != actual {
return nil, appError("unsupported_media_type", "Повреждённое изображение")
}
if decoded.Bounds().Dx() != cfg.Width || decoded.Bounds().Dy() != cfg.Height {
return nil, appError("unsupported_media_type", "Некорректные размеры изображения")
}
decoded = nil
if _, err = f.Seek(0, 0); err != nil {
return nil, unavailable()
}
o.ContentType = actual
o.Width = cfg.Width
o.Height = cfg.Height
good = true
return o, nil
}
type contextReader struct {
ctx context.Context
r io.Reader
}
func (r *contextReader) Read(p []byte) (int, error) {
if err := r.ctx.Err(); err != nil {
return 0, err
}
n, err := r.r.Read(p)
if errors.Is(err, context.Canceled) {
return n, err
}
return n, err
}
+139
View File
@@ -0,0 +1,139 @@
package attachment
import (
"bytes"
"context"
"encoding/binary"
"hash/crc32"
"image"
"image/color"
"image/jpeg"
"image/png"
"io"
"testing"
"time"
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain"
)
func pngFixture(t *testing.T) []byte {
t.Helper()
m := image.NewRGBA(image.Rect(0, 0, 10, 8))
m.Set(1, 1, color.RGBA{R: 255, A: 255})
var b bytes.Buffer
if err := png.Encode(&b, m); err != nil {
t.Fatal(err)
}
return b.Bytes()
}
func code(t *testing.T, err error, want domain.ErrorCode) {
t.Helper()
app, ok := domain.AsApplicationError(err)
if !ok || app.Code != want {
t.Fatalf("want %s, got %v", want, err)
}
}
func TestSpoolOriginalAndFullValidation(t *testing.T) {
original := pngFixture(t)
good, err := Spool(context.Background(), bytes.NewReader(original), "image/png")
if err != nil {
t.Fatal(err)
}
defer good.Close()
got, err := io.ReadAll(good.File)
if err != nil || !bytes.Equal(got, original) {
t.Fatal("original changed")
}
if good.Width != 10 || good.Height != 8 || good.Size != int64(len(original)) || len(good.SHA256) != 64 {
t.Fatalf("wrong metadata %+v", good)
}
_, err = Spool(context.Background(), bytes.NewReader(original), "image/jpeg")
code(t, err, "unsupported_media_type")
_, err = Spool(context.Background(), bytes.NewReader(original[:len(original)-12]), "image/png")
code(t, err, "unsupported_media_type")
corrupted := bytes.Clone(original)
corrupted[len(corrupted)-18] ^= 0x80
_, err = Spool(context.Background(), bytes.NewReader(corrupted), "image/png")
code(t, err, "unsupported_media_type")
var jpegBytes bytes.Buffer
if err = jpeg.Encode(&jpegBytes, image.NewRGBA(image.Rect(0, 0, 12, 9)), nil); err != nil {
t.Fatal(err)
}
jpegOriginal, err := Spool(context.Background(), bytes.NewReader(jpegBytes.Bytes()), "image/jpeg")
if err != nil {
t.Fatal(err)
}
jpegOriginal.Close()
_, err = Spool(context.Background(), bytes.NewReader(jpegBytes.Bytes()[:jpegBytes.Len()/2]), "image/jpeg")
code(t, err, "unsupported_media_type")
}
func TestSpoolLimitsBeforeDecode(t *testing.T) {
// Oversized compressed input is stopped after exactly MaxBytes+1 reads.
source := &countingReader{remaining: MaxBytes + 100_000}
_, err := Spool(context.Background(), source, "image/png")
code(t, err, "payload_too_large")
if source.read != MaxBytes+1 {
t.Fatalf("read %d bytes", source.read)
}
bomb := bytes.Clone(pngFixture(t))
binary.BigEndian.PutUint32(bomb[16:20], 40001)
binary.BigEndian.PutUint32(bomb[20:24], 1000)
binary.BigEndian.PutUint32(bomb[29:33], crc32.ChecksumIEEE(bomb[12:29]))
_, err = Spool(context.Background(), bytes.NewReader(bomb), "image/png")
code(t, err, "payload_too_large")
}
type countingReader struct{ remaining, read int64 }
func (c *countingReader) Read(p []byte) (int, error) {
if c.remaining == 0 {
return 0, io.EOF
}
n := min(int64(len(p)), c.remaining)
clear(p[:n])
c.remaining -= n
c.read += n
return int(n), nil
}
func TestFilenameAndCancelledUpload(t *testing.T) {
for _, name := range []string{"", "../x.png", "x\\photo.jpg", "a\x00b", "a\nb", "\t"} {
code(t, ValidateFilename(name), domain.ErrorInvalid)
}
for _, name := range []string{"фото.png", "image.jpg", ".."} {
if err := ValidateFilename(name); err != nil {
t.Fatal(err)
}
}
ctx, cancel := context.WithCancel(context.Background())
cancel()
_, err := Spool(ctx, bytes.NewReader(pngFixture(t)), "image/png")
code(t, err, domain.ErrorInvalid)
}
func TestReconcileRejectsUnsafeGrace(t *testing.T) {
s := &Service{}
if _, err := s.Reconcile(context.Background(), true, 89*time.Second); err == nil {
t.Fatal("unsafe grace accepted")
}
if MinimumGrace <= UploadTimeout {
t.Fatal("grace does not cover in-flight PUT")
}
}
func TestValid16BitWidePNG(t *testing.T) {
// Exercise the same RGBA64 + scanline allocation path as an extreme-aspect
// 40M image, at 1/1000 of that pixel count to keep the unit suite small.
img := image.NewNRGBA64(image.Rect(0, 0, 40000, 1))
img.SetNRGBA64(1, 0, color.NRGBA64{R: 65535, G: 12345, B: 4, A: 32000})
var encoded bytes.Buffer
if err := png.Encode(&encoded, img); err != nil {
t.Fatal(err)
}
original, err := Spool(context.Background(), bytes.NewReader(encoded.Bytes()), "image/png")
if err != nil {
t.Fatal(err)
}
defer original.Close()
if original.Width != 40000 || original.Height != 1 {
t.Fatal("wide PNG dimensions changed")
}
}
+18
View File
@@ -0,0 +1,18 @@
package attachment
import (
"encoding/json"
"gitflic.ru/akselbant/mtusi2026lab1-fork/dto"
)
// MarshalJSON uses the API's fixed microsecond precision instead of time.Time's
// variable fractional precision, which Python 3.9 clients cannot always parse.
func (a Attachment) MarshalJSON() ([]byte, error) {
type fields Attachment
return json.Marshal(struct {
fields
CreatedAt dto.Timestamp `json:"created_at"`
UpdatedAt dto.Timestamp `json:"updated_at"`
}{fields: fields(a), CreatedAt: dto.Timestamp(a.CreatedAt), UpdatedAt: dto.Timestamp(a.UpdatedAt)})
}
+37
View File
@@ -0,0 +1,37 @@
package attachment
import (
"encoding/json"
"testing"
"time"
)
func TestAttachmentTimestampsUseFixedMicroseconds(t *testing.T) {
value := Attachment{ID: "attachment-id", CreatedAt: time.Date(2026, 1, 2, 3, 4, 5, 123400000, time.UTC), UpdatedAt: time.Date(2026, 1, 2, 6, 4, 5, 0, time.FixedZone("MSK", 3*60*60)), Key: "original/private", Variants: []any{}}
encoded, err := json.Marshal(value)
if err != nil {
t.Fatal(err)
}
var fields map[string]any
if err = json.Unmarshal(encoded, &fields); err != nil {
t.Fatal(err)
}
if fields["created_at"] != "2026-01-02T03:04:05.123400Z" {
t.Fatalf("created_at=%v", fields["created_at"])
}
if fields["updated_at"] != "2026-01-02T03:04:05.000000Z" {
t.Fatalf("updated_at=%v", fields["updated_at"])
}
if fields["id"] != value.ID {
t.Fatal("serialization lost metadata")
}
if _, exposed := fields["Key"]; exposed {
t.Fatal("serialization exposed private object key")
}
if _, exposed := fields["key"]; exposed {
t.Fatal("serialization exposed private object key")
}
if fields["error_code"] != nil {
t.Fatal("ready error_code must be null")
}
}
+222
View File
@@ -0,0 +1,222 @@
package attachment
import (
"context"
"fmt"
"time"
"github.com/jackc/pgx/v5"
"github.com/minio/minio-go/v7"
)
type Summary struct {
Apply bool `json:"apply"`
GraceSeconds float64 `json:"grace_seconds"`
ObjectsScanned int `json:"objects_scanned"`
MetadataScanned int `json:"metadata_scanned"`
BytesScanned int64 `json:"bytes_scanned"`
ListRequestsEstimate int `json:"list_requests_estimate"`
StatRequests int `json:"stat_requests"`
DBQueries int `json:"db_queries"`
Orphans int `json:"orphans"`
Missing int `json:"missing"`
FreshSkipped int `json:"fresh_skipped"`
LockedSkipped int `json:"locked_skipped"`
ReferencedMissing int `json:"referenced_missing"`
Deleted int `json:"deleted"`
MarkedFailed int `json:"marked_failed"`
DurationMS int64 `json:"duration_ms"`
Actions []Action `json:"actions"`
}
type Action struct {
Kind string `json:"kind"`
Key string `json:"key"`
Applied bool `json:"applied"`
}
// Reconcile scans a fixed cutoff and rechecks each candidate while holding the
// same transaction-scoped advisory lock as upload. Metadata, including message
// references, is never deleted. Missing originals become failed tombstones.
func (s *Service) Reconcile(ctx context.Context, apply bool, grace time.Duration) (result Summary, err error) {
started := time.Now()
result = Summary{Apply: apply, GraceSeconds: grace.Seconds(), Actions: []Action{}}
defer func() { result.DurationMS = time.Since(started).Milliseconds() }()
if grace < MinimumGrace {
return result, fmt.Errorf("grace must be at least %s (upload timeout %s)", MinimumGrace, UploadTimeout)
}
cutoff := started.Add(-grace)
for obj := range s.Store.Client.ListObjects(ctx, s.Store.Bucket, minio.ListObjectsOptions{Prefix: "original/", Recursive: true, MaxKeys: 1000}) {
if obj.Err != nil {
return result, fmt.Errorf("S3 listing failed")
}
result.ObjectsScanned++
result.BytesScanned += obj.Size
if result.ObjectsScanned%1000 == 1 {
result.ListRequestsEstimate++
}
if !obj.LastModified.Before(cutoff) {
result.FreshSkipped++
continue
}
err = s.reconcileObject(ctx, obj.Key, cutoff, apply, &result)
if err != nil {
return result, err
}
}
// Bounded keyset pages avoid retaining the entire bucket or a DB cursor while
// making per-object transactions. A later run picks up concurrent new rows.
last := "00000000-0000-0000-0000-000000000000"
for {
result.DBQueries++
rows, e := s.Pool.Query(ctx, `SELECT id::text,object_key,created_at,status FROM attachments WHERE id>$1 ORDER BY id LIMIT 100`, last)
if e != nil {
return result, fmt.Errorf("metadata scan failed")
}
type metadata struct {
id, key, status string
created time.Time
}
page := []metadata{}
for rows.Next() {
var m metadata
if e = rows.Scan(&m.id, &m.key, &m.created, &m.status); e != nil {
rows.Close()
return result, e
}
page = append(page, m)
}
e = rows.Err()
rows.Close()
if e != nil {
return result, e
}
if len(page) == 0 {
break
}
for _, m := range page {
last = m.id
result.MetadataScanned++
if m.status != "ready" {
continue
}
if !m.created.Before(cutoff) {
result.FreshSkipped++
continue
}
if e = s.reconcileMetadata(ctx, m.id, m.key, cutoff, apply, &result); e != nil {
return result, e
}
}
}
if ctx.Err() != nil {
return result, ctx.Err()
}
return result, nil
}
func (s *Service) locked(ctx context.Context, key string, r *Summary) (pgx.Tx, bool, error) {
tx, err := s.Pool.Begin(ctx)
if err != nil {
return nil, false, fmt.Errorf("DB unavailable")
}
var locked bool
r.DBQueries++
if err = tx.QueryRow(ctx, `SELECT pg_try_advisory_xact_lock(hashtextextended($1,0))`, key).Scan(&locked); err != nil {
tx.Rollback(context.Background())
return nil, false, fmt.Errorf("lock failed")
}
if !locked {
r.LockedSkipped++
tx.Rollback(context.Background())
return nil, false, nil
}
return tx, true, nil
}
func (s *Service) reconcileObject(ctx context.Context, key string, cutoff time.Time, apply bool, r *Summary) error {
tx, ok, err := s.locked(ctx, key, r)
if err != nil || !ok {
return err
}
defer tx.Rollback(context.Background())
var exists bool
r.DBQueries++
if err = tx.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM attachments WHERE object_key=$1)`, key).Scan(&exists); err != nil {
return fmt.Errorf("metadata recheck failed")
}
if exists {
return nil
}
r.StatRequests++
obj, err := s.Store.Client.StatObject(ctx, s.Store.Bucket, key, minio.StatObjectOptions{})
if IsMissing(err) {
return nil
}
if err != nil {
return fmt.Errorf("object recheck failed")
}
if !obj.LastModified.Before(cutoff) {
r.FreshSkipped++
return nil
}
r.Orphans++
if apply {
if err = s.Store.Client.RemoveObject(ctx, s.Store.Bucket, key, minio.RemoveObjectOptions{}); err != nil {
return fmt.Errorf("orphan deletion failed")
}
r.Deleted++
}
if len(r.Actions) < 100 {
r.Actions = append(r.Actions, Action{Kind: "orphan", Key: key, Applied: apply})
}
return nil
}
func (s *Service) reconcileMetadata(ctx context.Context, id, key string, cutoff time.Time, apply bool, r *Summary) error {
tx, ok, err := s.locked(ctx, key, r)
if err != nil || !ok {
return err
}
defer tx.Rollback(context.Background())
var created time.Time
var status string
r.DBQueries++
err = tx.QueryRow(ctx, `SELECT created_at,status FROM attachments WHERE id=$1 FOR UPDATE`, id).Scan(&created, &status)
if err == pgx.ErrNoRows {
return nil
}
if err != nil {
return fmt.Errorf("metadata recheck failed")
}
if status != "ready" || !created.Before(cutoff) {
return nil
}
r.StatRequests++
_, err = s.Store.Client.StatObject(ctx, s.Store.Bucket, key, minio.StatObjectOptions{})
if err == nil {
return nil
}
if !IsMissing(err) {
return fmt.Errorf("object stat failed (no mutation)")
}
var referenced bool
r.DBQueries++
if err = tx.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM messages WHERE $1::uuid=ANY(attachment_ids))`, id).Scan(&referenced); err != nil {
return fmt.Errorf("reference check failed")
}
r.Missing++
if referenced {
r.ReferencedMissing++
}
if apply {
r.DBQueries++
if _, err = tx.Exec(ctx, `UPDATE attachments SET status='failed',error_code='original_missing' WHERE id=$1 AND status='ready'`, id); err != nil {
return fmt.Errorf("mark missing failed")
}
if err = tx.Commit(ctx); err != nil {
return fmt.Errorf("commit missing failed")
}
r.MarkedFailed++
}
if len(r.Actions) < 100 {
r.Actions = append(r.Actions, Action{Kind: "missing", Key: key, Applied: apply})
}
return nil
}
+44
View File
@@ -0,0 +1,44 @@
package attachment
import (
"context"
"crypto/tls"
"net"
"net/http"
"time"
"github.com/minio/minio-go/v7"
"github.com/minio/minio-go/v7/pkg/credentials"
)
type Store struct {
Client *minio.Client
Bucket string
}
func NewStore(endpoint, bucket, access, secret string, secure bool) (*Store, error) {
transport := &http.Transport{Proxy: http.ProxyFromEnvironment, DialContext: (&net.Dialer{Timeout: 3 * time.Second, KeepAlive: 30 * time.Second}).DialContext, MaxIdleConns: 16, MaxIdleConnsPerHost: 8, IdleConnTimeout: 30 * time.Second, ResponseHeaderTimeout: 5 * time.Second, TLSHandshakeTimeout: 5 * time.Second, TLSClientConfig: &tls.Config{MinVersion: tls.VersionTLS12}}
c, err := minio.New(endpoint, &minio.Options{Creds: credentials.NewStaticV4(access, secret, ""), Secure: secure, Region: "us-east-1", Transport: transport, MaxRetries: 1})
if err != nil {
return nil, err
}
return &Store{Client: c, Bucket: bucket}, nil
}
func (s *Store) Ready(ctx context.Context) error {
ctx, cancel := context.WithTimeout(ctx, 3*time.Second)
defer cancel()
for item := range s.Client.ListObjects(ctx, s.Bucket, minio.ListObjectsOptions{Prefix: "original/", MaxKeys: 1, Recursive: true}) {
if item.Err != nil {
return unavailable()
}
return nil
}
if ctx.Err() != nil {
return unavailable()
}
return nil
}
func IsMissing(err error) bool {
code := minio.ToErrorResponse(err).Code
return code == "NoSuchKey" || code == "NoSuchObject"
}
+132
View File
@@ -0,0 +1,132 @@
package attachment
import (
"context"
"errors"
"io"
"log"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/minio/minio-go/v7"
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain"
)
const UploadTimeout = 45 * time.Second
const MinimumGrace = 90 * time.Second
type Attachment struct {
ID string `json:"id"`
ChatID string `json:"chat_id"`
OwnerID string `json:"owner_id"`
Filename string `json:"filename"`
ContentType string `json:"content_type"`
Size int64 `json:"size_bytes"`
SHA256 string `json:"sha256"`
Status string `json:"status"`
Variants []any `json:"variants"`
ErrorCode *string `json:"error_code"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
Key string `json:"-"`
}
type Service struct {
Pool *pgxpool.Pool
Store *Store
slots chan struct{}
}
func New(pool *pgxpool.Pool, store *Store) *Service {
return &Service{Pool: pool, Store: store, slots: make(chan struct{}, 1)}
}
func (s *Service) Ready(ctx context.Context) error { return s.Store.Ready(ctx) }
func (s *Service) Upload(ctx context.Context, chatID, userID, name, contentType string, body io.Reader) (Attachment, error) {
if err := ValidateFilename(name); err != nil {
return Attachment{}, err
}
ctx, cancel := context.WithTimeout(ctx, UploadTimeout)
defer cancel()
select {
case s.slots <- struct{}{}:
defer func() { <-s.slots }()
case <-ctx.Done():
return Attachment{}, unavailable()
}
original, err := Spool(ctx, body, contentType)
if err != nil {
return Attachment{}, err
}
defer original.Close()
a := Attachment{ID: uuid.NewString(), ChatID: chatID, OwnerID: userID, Filename: name, ContentType: original.ContentType, Size: original.Size, SHA256: original.SHA256, Status: "ready", Variants: []any{}}
a.Key = "original/" + a.ID
tx, err := s.Pool.Begin(ctx)
if err != nil {
return Attachment{}, unavailable()
}
defer tx.Rollback(context.Background())
// Keep the object lock through PUT, metadata insert and COMMIT. A crash releases
// the lock; the grace protects a still-running client PUT at the S3 server.
if _, err = tx.Exec(ctx, `SELECT pg_advisory_xact_lock(hashtextextended($1,0))`, a.Key); err != nil {
return Attachment{}, unavailable()
}
_, err = s.Store.Client.PutObject(ctx, s.Store.Bucket, a.Key, original.File, a.Size, minio.PutObjectOptions{ContentType: a.ContentType, DisableMultipart: true, UserMetadata: map[string]string{"sha256": a.SHA256}})
if err != nil {
return Attachment{}, unavailable()
}
err = tx.QueryRow(ctx, `INSERT INTO attachments(id,chat_id,uploader_id,filename,object_key,content_type,size_bytes,sha256,width,height) VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10) RETURNING created_at`, a.ID, a.ChatID, a.OwnerID, a.Filename, a.Key, a.ContentType, a.Size, a.SHA256, original.Width, original.Height).Scan(&a.CreatedAt)
if err != nil {
log.Print("attachment metadata failed; orphan retained for grace-period reconciliation")
return Attachment{}, unavailable()
}
// Never DELETE on an ambiguous COMMIT failure: the DB may have committed. A
// later reconciler checks both stores under the same lock before any cleanup.
if err = tx.Commit(ctx); err != nil {
return Attachment{}, unavailable()
}
a.UpdatedAt = a.CreatedAt
return a, nil
}
func (s *Service) Get(ctx context.Context, id, userID string) (Attachment, error) {
parsed, err := uuid.Parse(id)
if err != nil {
return Attachment{}, appError(domain.ErrorInvalid, "Некорректный attachment_id")
}
ctx, cancel := context.WithTimeout(ctx, 3*time.Second)
defer cancel()
a := Attachment{Variants: []any{}}
err = s.Pool.QueryRow(ctx, `SELECT a.id::text,a.chat_id::text,a.uploader_id::text,a.filename,a.object_key,a.content_type,a.size_bytes,a.sha256,a.status,a.error_code,a.created_at FROM attachments a JOIN chat_members m ON m.chat_id=a.chat_id WHERE a.id=$1 AND m.user_id=$2`, parsed.String(), userID).Scan(&a.ID, &a.ChatID, &a.OwnerID, &a.Filename, &a.Key, &a.ContentType, &a.Size, &a.SHA256, &a.Status, &a.ErrorCode, &a.CreatedAt)
if errors.Is(err, pgx.ErrNoRows) {
return Attachment{}, appError(domain.ErrorNotFound, "Объект не найден")
}
if err != nil {
return Attachment{}, unavailable()
}
a.UpdatedAt = a.CreatedAt
// Keep the mandatory lab4 ready-only metadata schema. Failed originals are
// represented by 409; internal status remains inspectable in reconciliation.
if a.Status != "ready" {
return Attachment{}, appError(domain.ErrorConflict, "Оригинал вложения недоступен")
}
return a, nil
}
func (s *Service) Content(ctx context.Context, a Attachment) (*minio.Object, error) {
if a.Status != "ready" {
return nil, appError(domain.ErrorConflict, "Вложение не готово")
}
obj, err := s.Store.Client.GetObject(ctx, s.Store.Bucket, a.Key, minio.GetObjectOptions{})
if err != nil {
return nil, unavailable()
}
if _, err = obj.Stat(); err != nil {
obj.Close()
if IsMissing(err) {
return nil, appError(domain.ErrorConflict, "Оригинал вложения недоступен")
}
return nil, unavailable()
}
return obj, nil
}
+119
View File
@@ -0,0 +1,119 @@
package config
import (
"encoding/hex"
"fmt"
"os"
"strconv"
"strings"
"time"
)
type Config struct {
S3Endpoint string
S3Bucket string
S3AccessKey string
S3SecretKey string
S3UseSSL bool
Port string
PostgresHost string
PostgresPort uint16
PostgresUser string
PostgresDatabase string
PostgresPassword string
PostgresMaxConns int32
RedisAddr string
SessionTTL time.Duration
QueryTimeout time.Duration
CursorKey [32]byte
}
func value(name, fallback string) string {
if v := os.Getenv(name); v != "" {
return v
}
return fallback
}
func positive(name string, fallback, max int) (int, error) {
n, err := strconv.Atoi(value(name, strconv.Itoa(fallback)))
if err != nil || n < 1 || n > max {
return 0, fmt.Errorf("invalid %s", name)
}
return n, nil
}
func secret(name string) (string, error) {
if file := os.Getenv(name + "_FILE"); file != "" {
data, err := os.ReadFile(file)
if err != nil {
return "", fmt.Errorf("cannot read %s_FILE", name)
}
if s := strings.TrimSpace(string(data)); s != "" {
return s, nil
}
}
if s := os.Getenv(name); s != "" {
return s, nil
}
return "", fmt.Errorf("%s or %s_FILE is required", name, name)
}
func Load() (Config, error) {
var c Config
port, err := positive("PORT", 8080, 65535)
if err != nil {
return c, err
}
c.Port = strconv.Itoa(port)
pgPort, err := positive("POSTGRES_PORT", 5432, 65535)
if err != nil {
return c, err
}
c.PostgresPort = uint16(pgPort)
max, err := positive("POSTGRES_MAX_CONNS", 10, 100)
if err != nil {
return c, err
}
c.PostgresMaxConns = int32(max)
ttl, err := positive("SESSION_TTL_SECONDS", 3600, 86400*30)
if err != nil {
return c, err
}
c.SessionTTL = time.Duration(ttl) * time.Second
timeout, err := positive("QUERY_TIMEOUT_MS", 2000, 10000)
if err != nil {
return c, err
}
c.QueryTimeout = time.Duration(timeout) * time.Millisecond
c.PostgresHost = value("POSTGRES_HOST", "localhost")
c.PostgresUser = value("POSTGRES_USER", "messenger")
c.PostgresDatabase = value("POSTGRES_DB", "messenger")
c.RedisAddr = value("REDIS_ADDR", "localhost:6379")
c.PostgresPassword, err = secret("POSTGRES_PASSWORD")
if err != nil {
return c, err
}
key, err := secret("CURSOR_KEY")
if err != nil {
return c, err
}
decoded, err := hex.DecodeString(key)
if err != nil || len(decoded) != 32 {
return c, fmt.Errorf("CURSOR_KEY must be 32 random bytes encoded as hex")
}
copy(c.CursorKey[:], decoded)
c.S3Endpoint = value("S3_ENDPOINT", "minio:9000")
c.S3Bucket = value("S3_BUCKET", "attachments")
c.S3UseSSL, err = strconv.ParseBool(value("S3_USE_SSL", "false"))
if err != nil {
return c, fmt.Errorf("invalid S3_USE_SSL")
}
c.S3AccessKey, err = secret("S3_ACCESS_KEY")
if err != nil {
return c, err
}
c.S3SecretKey, err = secret("S3_SECRET_KEY")
if err != nil {
return c, err
}
return c, nil
}
+10
View File
@@ -0,0 +1,10 @@
package domain
import "time"
type Chat struct {
ID string
Title string
MemberIDs []string
CreatedAt time.Time
}
+32
View File
@@ -0,0 +1,32 @@
package domain
import "errors"
type ErrorCode string
const (
ErrorUnavailable ErrorCode = "unavailable"
ErrorInvalid ErrorCode = "invalid_request"
ErrorUnauthorized ErrorCode = "unauthorized"
ErrorNotFound ErrorCode = "not_found"
ErrorConflict ErrorCode = "conflict"
)
type ApplicationError struct {
Code ErrorCode
Message string
}
func (e *ApplicationError) Error() string {
return e.Message
}
func NewApplicationError(code ErrorCode, message string) error {
return &ApplicationError{Code: code, Message: message}
}
func AsApplicationError(err error) (*ApplicationError, bool) {
var applicationError *ApplicationError
ok := errors.As(err, &applicationError)
return applicationError, ok
}
+13
View File
@@ -0,0 +1,13 @@
package domain
import "time"
type Message struct {
IdempotencyKey string
ID string
ChatID string
SenderID string
AttachmentIDs []string
Text string
CreatedAt time.Time
}
+23
View File
@@ -0,0 +1,23 @@
package domain
import "time"
type Position struct {
CreatedAt time.Time
ID string
}
type Pagination struct {
After *Position
Limit int
}
type ChatPage struct {
Items []Chat
HasMore bool
}
type MessagePage struct {
Items []Message
HasMore bool
}
+14
View File
@@ -0,0 +1,14 @@
package domain
import "time"
type Session struct {
UserID string `json:"user_id"`
ExpiresAt time.Time `json:"expires_at"`
}
type Login struct {
Token string
ExpiresAt time.Time
User User
}
+10
View File
@@ -0,0 +1,10 @@
package domain
import "time"
type User struct {
ID string
Username string
DisplayName string
CreatedAt time.Time
}
+65
View File
@@ -0,0 +1,65 @@
package password
import (
"context"
"crypto/rand"
"crypto/subtle"
"encoding/base64"
"errors"
"strings"
"golang.org/x/crypto/argon2"
)
// Bound simultaneous KDF work to 4 * 19 MiB, including concurrent registrations.
var slots = make(chan struct{}, 4)
const prefix = "$argon2id$v=19$m=19456,t=2,p=1$"
func derive(ctx context.Context, password string, salt []byte) ([]byte, error) {
select {
case slots <- struct{}{}:
case <-ctx.Done():
return nil, ctx.Err()
}
defer func() { <-slots }()
if err := ctx.Err(); err != nil {
return nil, err
}
return argon2.IDKey([]byte(password), salt, 2, 19456, 1, 32), nil
}
func Hash(ctx context.Context, password string) (string, error) {
salt := make([]byte, 16)
if _, err := rand.Read(salt); err != nil {
return "", err
}
key, err := derive(ctx, password, salt)
if err != nil {
return "", err
}
return prefix + base64.RawStdEncoding.EncodeToString(salt) + "$" + base64.RawStdEncoding.EncodeToString(key), nil
}
func Verify(ctx context.Context, password, encoded string) (bool, error) {
if !strings.HasPrefix(encoded, prefix) {
return false, errors.New("unsupported password hash")
}
parts := strings.Split(strings.TrimPrefix(encoded, prefix), "$")
if len(parts) != 2 {
return false, errors.New("invalid password hash")
}
salt, err := base64.RawStdEncoding.DecodeString(parts[0])
if err != nil || len(salt) != 16 {
return false, errors.New("invalid salt")
}
expected, err := base64.RawStdEncoding.DecodeString(parts[1])
if err != nil || len(expected) != 32 {
return false, errors.New("invalid hash")
}
actual, err := derive(ctx, password, salt)
return subtle.ConstantTimeCompare(actual, expected) == 1, err
}
// A valid fixed encoding for equal-cost verification when username does not exist.
const DummyHash = prefix + "AAAAAAAAAAAAAAAAAAAAAA$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
+35
View File
@@ -0,0 +1,35 @@
package password_test
import (
"context"
"strings"
"testing"
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/password"
)
func TestUnicodeAndSalt(t *testing.T) {
ctx := context.Background()
secret := strings.Repeat("🔑", 128)
first, err := password.Hash(ctx, secret)
if err != nil {
t.Fatal(err)
}
second, err := password.Hash(ctx, secret)
if err != nil {
t.Fatal(err)
}
if first == second {
t.Fatal("password hashes reused salt")
}
for _, hash := range []string{first, second} {
ok, err := password.Verify(ctx, secret, hash)
if err != nil || !ok {
t.Fatal("128-code-point UTF-8 password rejected")
}
ok, err = password.Verify(ctx, strings.Repeat("🔑", 127)+"x", hash)
if err != nil || ok {
t.Fatal("password suffix was ignored")
}
}
}
+202
View File
@@ -0,0 +1,202 @@
package repository
import (
"context"
"sort"
"sync"
"time"
"github.com/google/uuid"
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain"
chatusecase "gitflic.ru/akselbant/mtusi2026lab1-fork/internal/usecase/chat"
)
// Memory is the lab1 in-memory Repository implementation.
type Memory struct {
mu sync.RWMutex
users map[string]domain.User
hashes map[string]string
userByUsername map[string]string
chats map[string]domain.Chat
messages map[string][]domain.Message
}
var _ chatusecase.Repository = (*Memory)(nil)
func NewMemory() *Memory {
return &Memory{
users: make(map[string]domain.User),
hashes: make(map[string]string),
userByUsername: make(map[string]string),
chats: make(map[string]domain.Chat),
messages: make(map[string][]domain.Message),
}
}
func (m *Memory) CreateUser(_ context.Context, username, displayName, hash string) (domain.User, error) {
m.mu.Lock()
defer m.mu.Unlock()
if _, exists := m.userByUsername[username]; exists {
return domain.User{}, chatusecase.ErrUsernameTaken
}
user := domain.User{
ID: uuid.NewString(),
Username: username,
DisplayName: displayName,
CreatedAt: now(),
}
m.users[user.ID] = user
m.hashes[user.ID] = hash
m.userByUsername[user.Username] = user.ID
return user, nil
}
func (m *Memory) User(_ context.Context, id string) (domain.User, bool, error) {
m.mu.RLock()
defer m.mu.RUnlock()
user, ok := m.users[id]
return user, ok, nil
}
func (m *Memory) CreateChat(_ context.Context, title string, memberIDs []string) (domain.Chat, error) {
m.mu.Lock()
defer m.mu.Unlock()
for _, memberID := range memberIDs {
if _, exists := m.users[memberID]; !exists {
return domain.Chat{}, chatusecase.ErrUserNotFound
}
}
chat := domain.Chat{
ID: uuid.NewString(),
Title: title,
MemberIDs: append([]string(nil), memberIDs...),
CreatedAt: now(),
}
m.chats[chat.ID] = chat
return cloneChat(chat), nil
}
func (m *Memory) ChatForUser(_ context.Context, chatID, userID string) (domain.Chat, error) {
m.mu.RLock()
defer m.mu.RUnlock()
chat, exists := m.chats[chatID]
if !exists {
return domain.Chat{}, chatusecase.ErrChatNotFound
}
if !contains(chat.MemberIDs, userID) {
return domain.Chat{}, chatusecase.ErrNotMember
}
return cloneChat(chat), nil
}
func (m *Memory) ListChats(_ context.Context, userID string, after *domain.Position, limit int) ([]domain.Chat, error) {
m.mu.RLock()
defer m.mu.RUnlock()
result := make([]domain.Chat, 0)
for _, chat := range m.chats {
if contains(chat.MemberIDs, userID) && isAfter(chat.CreatedAt, chat.ID, after) {
result = append(result, cloneChat(chat))
}
}
sort.Slice(result, func(i, j int) bool {
return less(result[i].CreatedAt, result[i].ID, result[j].CreatedAt, result[j].ID)
})
if len(result) > limit {
result = result[:limit]
}
return result, nil
}
func (m *Memory) CreateMessage(_ context.Context, chatID, senderID, text, key string) (domain.Message, error) {
m.mu.Lock()
defer m.mu.Unlock()
chat, exists := m.chats[chatID]
if !exists {
return domain.Message{}, chatusecase.ErrChatNotFound
}
if !contains(chat.MemberIDs, senderID) {
return domain.Message{}, chatusecase.ErrNotMember
}
if key != "" {
for _, previous := range m.messages[chatID] {
if previous.SenderID == senderID && previous.IdempotencyKey == key {
if previous.Text != text {
return domain.Message{}, domain.NewApplicationError(domain.ErrorConflict, "Idempotency-Key уже использован с другим телом")
}
return previous, nil
}
}
}
message := domain.Message{
IdempotencyKey: key,
ID: uuid.NewString(),
ChatID: chatID,
SenderID: senderID,
Text: text,
CreatedAt: now(),
}
m.messages[chatID] = append(m.messages[chatID], message)
return message, nil
}
func (m *Memory) ListMessages(_ context.Context, chatID string, after *domain.Position, limit int) ([]domain.Message, error) {
m.mu.RLock()
defer m.mu.RUnlock()
values := m.messages[chatID]
result := make([]domain.Message, 0, min(len(values), limit))
for _, message := range values {
if isAfter(message.CreatedAt, message.ID, after) {
result = append(result, message)
}
}
sort.Slice(result, func(i, j int) bool {
return less(result[i].CreatedAt, result[i].ID, result[j].CreatedAt, result[j].ID)
})
if len(result) > limit {
result = result[:limit]
}
return result, nil
}
func cloneChat(chat domain.Chat) domain.Chat {
chat.MemberIDs = append([]string(nil), chat.MemberIDs...)
return chat
}
func now() time.Time {
return time.Now().UTC().Truncate(time.Second)
}
func contains(values []string, target string) bool {
for _, value := range values {
if value == target {
return true
}
}
return false
}
func isAfter(createdAt time.Time, id string, after *domain.Position) bool {
return after == nil || createdAt.After(after.CreatedAt) || createdAt.Equal(after.CreatedAt) && id > after.ID
}
func less(leftTime time.Time, leftID string, rightTime time.Time, rightID string) bool {
if leftTime.Equal(rightTime) {
return leftID < rightID
}
return leftTime.Before(rightTime)
}
func (m *Memory) Ready(context.Context) error { return nil }
func (m *Memory) UserByUsername(_ context.Context, username string) (domain.User, string, bool, error) {
m.mu.RLock()
defer m.mu.RUnlock()
id, ok := m.userByUsername[username]
return m.users[id], m.hashes[id], ok, nil
}
+78
View File
@@ -0,0 +1,78 @@
package postgres
import (
"context"
"errors"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain"
chatusecase "gitflic.ru/akselbant/mtusi2026lab1-fork/internal/usecase/chat"
)
func (s *Storage) CreateChat(ctx context.Context, title string, members []string) (domain.Chat, error) {
ctx, cancel := context.WithTimeout(ctx, s.timeout)
defer cancel()
tx, err := s.pool.Begin(ctx)
if err != nil {
return domain.Chat{}, dbError(err)
}
defer tx.Rollback(context.WithoutCancel(ctx))
chat := domain.Chat{ID: uuid.NewString(), Title: title, MemberIDs: append([]string(nil), members...)}
err = tx.QueryRow(ctx, `INSERT INTO chats(id,title) VALUES($1,$2) RETURNING created_at`, chat.ID, title).Scan(&chat.CreatedAt)
if err != nil {
return domain.Chat{}, dbError(err)
}
for i, member := range members {
if _, err = tx.Exec(ctx, `INSERT INTO chat_members(chat_id,user_id,ordinal) VALUES($1,$2,$3)`, chat.ID, member, i); err != nil {
return domain.Chat{}, dbError(err)
}
}
if err = tx.Commit(ctx); err != nil {
return domain.Chat{}, dbError(err)
}
return chat, nil
}
const chatColumns = `c.id::text,c.title,c.created_at,ARRAY(SELECT m.user_id::text FROM chat_members m WHERE m.chat_id=c.id ORDER BY m.ordinal)`
func (s *Storage) ChatForUser(ctx context.Context, chatID, userID string) (domain.Chat, error) {
ctx, cancel := context.WithTimeout(ctx, s.timeout)
defer cancel()
var chat domain.Chat
err := s.pool.QueryRow(ctx, `SELECT `+chatColumns+` FROM chats c
WHERE c.id=$1 AND EXISTS(SELECT 1 FROM chat_members m WHERE m.chat_id=c.id AND m.user_id=$2)`, chatID, userID).
Scan(&chat.ID, &chat.Title, &chat.CreatedAt, &chat.MemberIDs)
if errors.Is(err, pgx.ErrNoRows) {
return chat, chatusecase.ErrChatNotFound
}
return chat, dbError(err)
}
func (s *Storage) ListChats(ctx context.Context, userID string, after *domain.Position, limit int) ([]domain.Chat, error) {
ctx, cancel := context.WithTimeout(ctx, s.timeout)
defer cancel()
query := `SELECT ` + chatColumns + ` FROM chats c JOIN chat_members member ON member.chat_id=c.id
WHERE member.user_id=$1`
args := []any{userID, limit}
if after != nil {
query += ` AND (c.created_at,c.id)>($3,$4)`
args = append(args, after.CreatedAt, after.ID)
}
query += ` ORDER BY c.created_at,c.id LIMIT $2`
rows, err := s.pool.Query(ctx, query, args...)
if err != nil {
return nil, dbError(err)
}
defer rows.Close()
chats := make([]domain.Chat, 0)
for rows.Next() {
var chat domain.Chat
if err = rows.Scan(&chat.ID, &chat.Title, &chat.CreatedAt, &chat.MemberIDs); err != nil {
return nil, dbError(err)
}
chats = append(chats, chat)
}
return chats, dbError(rows.Err())
}
@@ -0,0 +1,341 @@
package postgres_test
import (
"bufio"
"bytes"
"context"
"encoding/xml"
"fmt"
"image"
"image/png"
"io"
"net/http"
"net/http/httptest"
"strconv"
"strings"
"sync"
"testing"
"time"
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/attachment"
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain"
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/repository/postgres"
"github.com/google/uuid"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/minio/minio-go/v7"
"github.com/minio/minio-go/v7/pkg/credentials"
)
type fakeObject struct {
data []byte
modified time.Time
}
type fakeS3 struct {
mu sync.Mutex
objects map[string]fakeObject
failPUT bool
}
func (f *fakeS3) ServeHTTP(w http.ResponseWriter, r *http.Request) {
f.mu.Lock()
defer f.mu.Unlock()
key := strings.TrimPrefix(r.URL.Path, "/attachments/")
if r.Method == "GET" && r.URL.Path == "/attachments/" || r.Method == "GET" && r.URL.Path == "/attachments" {
type item struct {
Key string
LastModified string
ETag string
Size int
}
type listing struct {
XMLName xml.Name `xml:"ListBucketResult"`
Xmlns string `xml:"xmlns,attr"`
Name string
Prefix string
MaxKeys int
IsTruncated bool
Contents []item
}
l := listing{Xmlns: "http://s3.amazonaws.com/doc/2006-03-01/", Name: "attachments", Prefix: r.URL.Query().Get("prefix"), MaxKeys: 1000}
for k, v := range f.objects {
if strings.HasPrefix(k, l.Prefix) {
l.Contents = append(l.Contents, item{Key: k, LastModified: v.modified.UTC().Format("2006-01-02T15:04:05.000Z"), ETag: `"abc"`, Size: len(v.data)})
}
}
w.Header().Set("Content-Type", "application/xml")
xml.NewEncoder(w).Encode(l)
return
}
if r.Method == "PUT" {
if f.failPUT {
w.WriteHeader(503)
fmt.Fprint(w, `<Error><Code>ServiceUnavailable</Code></Error>`)
return
}
var data []byte
var err error
if strings.Contains(r.Header.Get("Content-Encoding"), "aws-chunked") || strings.HasPrefix(r.Header.Get("X-Amz-Content-Sha256"), "STREAMING-") {
reader := bufio.NewReader(r.Body)
for {
line, e := reader.ReadString('\n')
if e != nil {
err = e
break
}
size, e := strconv.ParseInt(strings.Split(strings.TrimSpace(line), ";")[0], 16, 64)
if e != nil {
err = e
break
}
if size == 0 {
break
}
chunk := make([]byte, size)
if _, e = io.ReadFull(reader, chunk); e != nil {
err = e
break
}
data = append(data, chunk...)
if _, e = reader.Discard(2); e != nil {
err = e
break
}
}
} else {
data, err = io.ReadAll(r.Body)
}
if err != nil {
w.WriteHeader(400)
return
}
f.objects[key] = fakeObject{data: data, modified: time.Now().UTC()}
w.Header().Set("ETag", `"900150983cd24fb0d6963f7d28e17f72"`)
w.WriteHeader(200)
return
}
obj, ok := f.objects[key]
if !ok {
w.WriteHeader(404)
if r.Method != "HEAD" {
fmt.Fprint(w, `<Error><Code>NoSuchKey</Code></Error>`)
}
return
}
if r.Method == "DELETE" {
delete(f.objects, key)
w.WriteHeader(204)
return
}
w.Header().Set("Last-Modified", obj.modified.UTC().Format(http.TimeFormat))
w.Header().Set("ETag", `"abc"`)
w.Header().Set("Content-Length", fmt.Sprint(len(obj.data)))
w.Header().Set("Content-Type", "image/png")
if r.Method == "GET" {
w.Write(obj.data)
}
}
func lab4Backend(t *testing.T, pool *pgxpool.Pool, repo *postgres.Storage, user domain.User, chat domain.Chat) {
ctx := context.Background()
fake := &fakeS3{objects: map[string]fakeObject{}}
server := httptest.NewServer(fake)
defer server.Close()
client, err := minio.New(strings.TrimPrefix(server.URL, "http://"), &minio.Options{Creds: credentials.NewStaticV4("test-key", "test-secret", ""), Region: "us-east-1", MaxRetries: 1})
if err != nil {
t.Fatal(err)
}
service := attachment.New(pool, &attachment.Store{Client: client, Bucket: "attachments"})
var imageBytes bytes.Buffer
if err = png.Encode(&imageBytes, image.NewRGBA(image.Rect(0, 0, 10, 8))); err != nil {
t.Fatal(err)
}
upload := func(name string) attachment.Attachment {
t.Helper()
a, e := service.Upload(ctx, chat.ID, user.ID, name, "image/png", bytes.NewReader(imageBytes.Bytes()))
if e != nil {
t.Fatal(e)
}
return a
}
first := upload("first.png")
second := upload("second.png")
requireCode := func(err error, want domain.ErrorCode) {
t.Helper()
e, ok := domain.AsApplicationError(err)
if !ok || e.Code != want {
t.Fatalf("expected %s, got %v", want, err)
}
}
outside, err := repo.CreateUser(ctx, "attachment_outsider", "Outside", "hash")
if err != nil {
t.Fatal(err)
}
_, err = service.Get(ctx, first.ID, outside.ID)
requireCode(err, domain.ErrorNotFound)
obj, err := service.Content(ctx, first)
if err != nil {
t.Fatal(err)
}
data, err := io.ReadAll(obj)
obj.Close()
if err != nil || !bytes.Equal(data, imageBytes.Bytes()) {
t.Fatalf("original mismatch: %v", err)
}
otherChat, err := repo.CreateChat(ctx, "Other", []string{user.ID})
if err != nil {
t.Fatal(err)
}
_, err = repo.CreateMessageWithAttachments(ctx, otherChat.ID, user.ID, "", "cross-chat", []string{first.ID})
requireCode(err, domain.ErrorNotFound)
_, err = repo.CreateMessageWithAttachments(ctx, chat.ID, user.ID, "", "unknown", []string{uuid.NewString()})
requireCode(err, domain.ErrorNotFound)
sent, err := repo.CreateMessageWithAttachments(ctx, chat.ID, user.ID, "", "ordered", []string{first.ID, second.ID})
if err != nil {
t.Fatal(err)
}
replay, err := repo.CreateMessageWithAttachments(ctx, chat.ID, user.ID, "", "ordered", []string{first.ID, second.ID})
if err != nil || sent.ID != replay.ID {
t.Fatalf("replay failed: %v", err)
}
_, err = repo.CreateMessageWithAttachments(ctx, chat.ID, user.ID, "", "ordered", []string{second.ID, first.ID})
requireCode(err, domain.ErrorConflict)
textOnly, err := repo.CreateMessageWithAttachments(ctx, chat.ID, user.ID, "text", "empty-equivalent", nil)
if err != nil {
t.Fatal(err)
}
replay, err = repo.CreateMessageWithAttachments(ctx, chat.ID, user.ID, "text", "empty-equivalent", []string{})
if err != nil || textOnly.ID != replay.ID {
t.Fatalf("absent/empty differs: %v", err)
}
const callers = 12
outcomes := make(chan domain.Message, callers)
failures := make(chan error, callers)
var concurrent sync.WaitGroup
start := make(chan struct{})
for i := 0; i < callers; i++ {
concurrent.Add(1)
go func() {
defer concurrent.Done()
<-start
m, e := repo.CreateMessageWithAttachments(ctx, chat.ID, user.ID, "", "concurrent-attachments", []string{first.ID, second.ID})
if e != nil {
failures <- e
} else {
outcomes <- m
}
}()
}
close(start)
concurrent.Wait()
close(outcomes)
close(failures)
for e := range failures {
t.Fatal(e)
}
identity := ""
for m := range outcomes {
if identity == "" {
identity = m.ID
}
if m.ID != identity {
t.Fatal("duplicate concurrent attachment message")
}
}
var effects int
if err = pool.QueryRow(ctx, `SELECT count(*) FROM messages WHERE chat_id=$1 AND idempotency_key='concurrent-attachments'`, chat.ID).Scan(&effects); err != nil || effects != 1 {
t.Fatalf("concurrent effects=%d %v", effects, err)
}
t.Log("ACL, original bytes, cross-chat attachment rejection, ordered/concurrent idempotency and absent=[] passed")
old := time.Now().Add(-3 * time.Minute)
orphan := "original/" + uuid.NewString()
fresh := "original/" + uuid.NewString()
locked := "original/" + uuid.NewString()
fake.mu.Lock()
delete(fake.objects, first.Key)
v := fake.objects[second.Key]
v.modified = old
fake.objects[second.Key] = v
fake.objects[orphan] = fakeObject{data: []byte("orphan"), modified: old}
fake.objects[fresh] = fakeObject{data: []byte("fresh"), modified: time.Now()}
fake.objects[locked] = fakeObject{data: []byte("locked"), modified: old}
fake.mu.Unlock()
if _, err = pool.Exec(ctx, `UPDATE attachments SET created_at=$1 WHERE id=ANY($2::uuid[])`, old, []string{first.ID, second.ID}); err != nil {
t.Fatal(err)
}
hold, err := pool.Begin(ctx)
if err != nil {
t.Fatal(err)
}
defer hold.Rollback(ctx)
if _, err = hold.Exec(ctx, `SELECT pg_advisory_xact_lock(hashtextextended($1,0))`, locked); err != nil {
t.Fatal(err)
}
dry, err := service.Reconcile(ctx, false, 90*time.Second)
if err != nil {
t.Fatal(err)
}
if dry.Orphans != 1 || dry.Missing != 1 || dry.ReferencedMissing != 1 || dry.LockedSkipped != 1 || dry.FreshSkipped < 1 || dry.Deleted != 0 || dry.MarkedFailed != 0 {
t.Fatalf("bad dry-run %+v", dry)
}
var status string
if err = pool.QueryRow(ctx, `SELECT status FROM attachments WHERE id=$1`, first.ID).Scan(&status); err != nil || status != "ready" {
t.Fatalf("dry-run mutated metadata %s %v", status, err)
}
applied, err := service.Reconcile(ctx, true, 90*time.Second)
if err != nil {
t.Fatal(err)
}
if applied.Deleted != 1 || applied.MarkedFailed != 1 {
t.Fatalf("bad apply %+v", applied)
}
fake.mu.Lock()
_, hasOrphan := fake.objects[orphan]
_, hasFresh := fake.objects[fresh]
_, hasLinked := fake.objects[second.Key]
_, hasLocked := fake.objects[locked]
fake.mu.Unlock()
if hasOrphan || !hasFresh || !hasLinked || !hasLocked {
t.Fatal("unsafe object cleanup")
}
_, err = service.Get(ctx, first.ID, user.ID)
requireCode(err, domain.ErrorConflict)
_, err = repo.CreateMessageWithAttachments(ctx, chat.ID, user.ID, "", "failed-attachment", []string{first.ID})
requireCode(err, domain.ErrorConflict)
replay, err = repo.CreateMessageWithAttachments(ctx, chat.ID, user.ID, "", "ordered", []string{first.ID, second.ID})
if err != nil || replay.ID != sent.ID {
t.Fatalf("historical replay changed after missing: %v", err)
}
repeated, err := service.Reconcile(ctx, true, 90*time.Second)
if err != nil {
t.Fatal(err)
}
if repeated.Deleted != 0 || repeated.MarkedFailed != 0 || repeated.Orphans != 0 || repeated.Missing != 0 {
t.Fatalf("not repeatable %+v", repeated)
}
t.Logf("dry-run=%+v apply=%+v repeat=%+v; fresh, locked and referenced objects retained", dry, applied, repeated)
}
func TestS3WireFixture(t *testing.T) {
fake := &fakeS3{objects: map[string]fakeObject{}}
server := httptest.NewServer(fake)
defer server.Close()
client, err := minio.New(strings.TrimPrefix(server.URL, "http://"), &minio.Options{Creds: credentials.NewStaticV4("test-key", "test-secret", ""), Region: "us-east-1", MaxRetries: 1})
if err != nil {
t.Fatal(err)
}
payload := []byte("exact object bytes")
_, err = client.PutObject(context.Background(), "attachments", "original/test", bytes.NewReader(payload), int64(len(payload)), minio.PutObjectOptions{ContentType: "image/png", DisableMultipart: true})
if err != nil {
t.Fatal(err)
}
obj, err := client.GetObject(context.Background(), "attachments", "original/test", minio.GetObjectOptions{})
if err != nil {
t.Fatal(err)
}
defer obj.Close()
got, err := io.ReadAll(obj)
if err != nil || !bytes.Equal(got, payload) {
t.Fatalf("wire fixture did not store original: %q %v", got, err)
}
}

Some files were not shown because too many files have changed in this diff Show More