ЛР4: S3-вложения, приватный bucket и согласованность хранилищ (трек 2)

This commit is contained in:
IvanMeln1k
2026-12-04 14:19:19 +03:00
parent ec540a1a72
commit f1fae32722
1134 changed files with 557640 additions and 21 deletions
+1
View File
@@ -18,3 +18,4 @@ __pycache__
node_modules node_modules
evidence evidence
.DS_Store .DS_Store
infra/seaweedfs-s3.json
+61 -16
View File
@@ -1,20 +1,65 @@
# Copy to .env for your LOCAL synthetic test environment; never commit .env. # Copy to .env for your LOCAL synthetic teaching stand: `make env` generates
# These are logical interface suggestions; map actual framework names in REPORT.md. # random local credentials, writes this ignored file and the ignored
APP_HOST=0.0.0.0 # infra/seaweedfs-s3.json, and never prints secret values.
APP_PORT=8080
APP_ENV=lab APP_ENV=lab
SESSION_TTL_SECONDS=3600 LOG_LEVEL=info
# Choose credentials locally. File paths contain no secret values. APP_VERSION=1.0.0
DATABASE_URL_FILE=/run/secrets/database_url COMPOSE_PROJECT_NAME=mtusi-lab4-melnikov
# Optional on 3, required use on 4 in lab2; Redis OR Valkey:
SESSION_STORE=postgres # Local credentials. Never commit real values.
CACHE_URL_FILE=/run/secrets/cache_url POSTGRES_USER=messenger
API_REPLICAS=2 POSTGRES_DB=messenger
IDEMPOTENCY_TTL_SECONDS=86400 POSTGRES_PASSWORD=
S3_ENDPOINT=http://s3:9000 VALKEY_PASSWORD=
S3_REGION=us-east-1
# Private S3 store. The API identity is bucket-scoped; the administrative
# identity is used only by the one-shot s3-init container.
S3_BUCKET=messenger-attachments S3_BUCKET=messenger-attachments
S3_ACCESS_KEY_ID_FILE=/run/secrets/s3_access_key_id S3_REGION=us-east-1
S3_SECRET_ACCESS_KEY_FILE=/run/secrets/s3_secret_access_key S3_ADMIN_ACCESS_KEY=
S3_ADMIN_SECRET_KEY=
S3_API_ACCESS_KEY=
S3_API_SECRET_KEY=
S3_TIMEOUT_SECONDS=10
# Public entrypoint: HAProxy on loopback only. API and S3 have no host port.
LB_PORT=8084
# Replica count and per-replica limits. The whole stand must fit the local
# Colima VM: 2 vCPU / 2 GiB (verified actual capacity in REPORT.md).
API_REPLICAS=2
API_CPU_LIMIT=0.5
API_MEM_LIMIT=384M
GOMEMLIMIT=300MiB
POSTGRES_CPU_LIMIT=0.5
POSTGRES_MEM_LIMIT=384M
VALKEY_CPU_LIMIT=0.1
VALKEY_MEM_LIMIT=96M
S3_CPU_LIMIT=0.4
S3_MEM_LIMIT=384M
LB_CPU_LIMIT=0.2
LB_MEM_LIMIT=64M
SESSION_TTL_SECONDS=3600
DB_MAX_CONNS=8
DB_MIN_CONNS=1
DB_CONNECT_TIMEOUT_SECONDS=3
DB_STATEMENT_TIMEOUT_SECONDS=3
DB_QUERY_TIMEOUT_SECONDS=3
CACHE_POOL_SIZE=8
CACHE_TIMEOUT_SECONDS=2
SHUTDOWN_TIMEOUT_SECONDS=6
SHUTDOWN_DRAIN_SECONDS=3
STARTUP_TIMEOUT_SECONDS=30
# Contract limits. The API refuses startup with larger values.
MAX_UPLOAD_BYTES=10485760 MAX_UPLOAD_BYTES=10485760
MAX_IMAGE_PIXELS=40000000 MAX_IMAGE_PIXELS=40000000
UPLOAD_DECODE_CONCURRENCY=1
# Single-node SeaweedFS was verified stable at one concurrent PUT per API
# replica; the API queues further uploads after their bounded temp file is
# complete. The API refuses to start with any other value.
S3_PUT_CONCURRENCY=1
# Build metadata, filled by make if not supplied.
GIT_REVISION=unknown
+3
View File
@@ -30,3 +30,6 @@ coverage/
.vscode/ .vscode/
# Keep small, sanitized evidence summaries in evidence/ under version control. # Keep small, sanitized evidence summaries in evidence/ under version control.
# Inspect git diff --cached: ignore rules are not a secret scanner. # Inspect git diff --cached: ignore rules are not a secret scanner.
# Local SeaweedFS identities generated from .env by make env.
infra/seaweedfs-s3.json
+81
View File
@@ -0,0 +1,81 @@
# syntax=docker/dockerfile:1
# Compile stage. Dependencies are vendored, so the build needs no module proxy
# and the same source tree produces the same binaries from a clean clone.
FROM golang:1.25.1-alpine3.22@sha256:b6ed3fd0452c0e9bcdef5597f29cc1418f61672e9d3a2f55bf02e7222c014abd AS build
WORKDIR /src
ENV CGO_ENABLED=0 \
GOTOOLCHAIN=local \
GOFLAGS=-mod=vendor
COPY go.mod go.sum ./
COPY vendor ./vendor
COPY cmd ./cmd
COPY internal ./internal
ARG VERSION=1.0.0
ARG REVISION=unknown
RUN go build \
-trimpath \
-buildvcs=false \
-ldflags="-s -w -buildid= -X main.version=${VERSION} -X main.revision=${REVISION}" \
-o /out/messenger \
./cmd/messenger \
&& go build \
-trimpath \
-buildvcs=false \
-ldflags="-s -w -buildid= -X main.revision=${REVISION}" \
-o /out/migrate \
./cmd/migrate \
&& go build \
-trimpath \
-buildvcs=false \
-ldflags="-s -w -buildid= -X main.revision=${REVISION}" \
-o /out/s3bootstrap \
./cmd/s3bootstrap \
&& go build \
-trimpath \
-buildvcs=false \
-ldflags="-s -w -buildid= -X main.revision=${REVISION}" \
-o /out/s3ctl \
./cmd/s3ctl \
&& go build \
-trimpath \
-buildvcs=false \
-ldflags="-s -w -buildid= -X main.revision=${REVISION}" \
-o /out/reconciler \
./cmd/reconciler
# Runtime stage: minimal Alpine pinned by digest, no shell tooling and no
# package manager calls. The process runs as the unprivileged uid 10001.
FROM alpine:3.22.1@sha256:4bcff63911fcb4448bd4fdacec207030997caf25e9bea4045fa6c8c44de311d1 AS runtime
LABEL org.opencontainers.image.title="mtusi-messenger-lab4" \
org.opencontainers.image.description="MTUSI highload lab 4: HAProxy, replicated API, PostgreSQL, Valkey and a private S3 store" \
org.opencontainers.image.version="1.0.0"
WORKDIR /app
COPY --from=build --chown=10001:10001 /out/messenger /app/messenger
COPY --from=build --chown=10001:10001 /out/migrate /app/migrate
COPY --from=build --chown=10001:10001 /out/s3bootstrap /app/s3bootstrap
COPY --from=build --chown=10001:10001 /out/s3ctl /app/s3ctl
COPY --from=build --chown=10001:10001 /out/reconciler /app/reconciler
USER 10001:10001
EXPOSE 8080
ENV APP_HOST=0.0.0.0 \
APP_PORT=8080 \
APP_ENV=lab \
LOG_LEVEL=info \
SESSION_TTL_SECONDS=3600 \
SHUTDOWN_TIMEOUT_SECONDS=6 \
SHUTDOWN_DRAIN_SECONDS=3
# The same binary implements -healthcheck, so the image needs no curl/wget and
# the probe runs as the unprivileged user.
HEALTHCHECK --interval=3s --timeout=2s --start-period=10s --retries=3 \
CMD ["/app/messenger", "-healthcheck"]
ENTRYPOINT ["/app/messenger"]
+85 -5
View File
@@ -1,13 +1,31 @@
PYTHON ?= python3 PYTHON ?= python3
BASE_URL ?= http://localhost:8080 GO ?= go
BASE_URL ?= http://127.0.0.1:8084
CA_FILE ?= CA_FILE ?=
ACTION_SCRIPT ?= ACTION_SCRIPT ?=
TLS_ARGS = $(if $(CA_FILE),--ca-file "$(CA_FILE)",) TLS_ARGS = $(if $(CA_FILE),--ca-file "$(CA_FILE)",)
COMPOSE ?= ./scripts/compose.sh
COMPOSE_ARGS = --env-file .env
IMAGE ?= mtusi-messenger-lab4-melnikov:local
GIT_REVISION ?= $(shell git rev-parse HEAD 2>/dev/null || echo unknown)
export GIT_REVISION
export API_IMAGE ?= $(IMAGE)
.PHONY: help check validate test load test-persistence test-failover .PHONY: help check validate env up wait build-image docker-config stop down purge logs ps \
test load test-persistence test-failover test-student test-student-race \
test-attachment test-container test-consistency experiment clean-clone py39 collect-evidence
help: help:
@echo "check: offline structure; validate: full OpenAPI (requirements-dev.txt); test: running API; load: synthetic writes" @echo "check: offline structure; validate: full OpenAPI (requirements-dev.txt); test: running API"
@echo "env: create ignored .env and infra/seaweedfs-s3.json; up: build+start stack; wait: wait for /health/ready"
@echo "stop: stop containers (data kept); down: remove containers (volumes kept); purge: DELETE volumes and data"
@echo "test-student: Go tests + black-box lab4 suite; test-student-race: Go race detector"
@echo "test-persistence: ACTION_SCRIPT=scripts/restart.sh; test-failover: ACTION_SCRIPT=scripts/stop-one.sh"
@echo "test-attachment: upload limits/ACL/consistency negatives; test-container: infra/S3 privacy checks"
@echo "test-consistency: reconciler dry-run/apply/grace scenario (track 2)"
@echo "experiment: >=10 concurrent uploads with API RSS sampling"
@echo "clean-clone: build and smoke a fresh clone with empty volumes; py39: run suites on Python 3.9"
@echo "collect-evidence: rerun all mandatory/own checks and keep raw stdout in evidence/commands"
check: check:
$(PYTHON) scripts/check_contract.py $(PYTHON) scripts/check_contract.py
@@ -21,10 +39,72 @@ test:
load: load:
$(PYTHON) tests/load.py --base-url "$(BASE_URL)" $(TLS_ARGS) $(PYTHON) tests/load.py --base-url "$(BASE_URL)" $(TLS_ARGS)
env:
./scripts/init-env.sh
up:
@test -f .env || (echo "Run make env first" >&2; exit 2)
GIT_REVISION="$(GIT_REVISION)" API_IMAGE="$(IMAGE)" $(COMPOSE) $(COMPOSE_ARGS) up -d --build
./scripts/wait-ready.sh
wait:
./scripts/wait-ready.sh
build-image:
@test -f .env || (echo "Run make env first" >&2; exit 2)
GIT_REVISION="$(GIT_REVISION)" API_IMAGE="$(IMAGE)" $(COMPOSE) $(COMPOSE_ARGS) build api
docker-config:
GIT_REVISION="$(GIT_REVISION)" API_IMAGE="$(IMAGE)" $(COMPOSE) $(COMPOSE_ARGS) config --quiet
stop:
$(COMPOSE) $(COMPOSE_ARGS) stop
down:
$(COMPOSE) $(COMPOSE_ARGS) down
purge:
@echo "PURGE removes containers AND named volumes mtusi-lab4-melnikov-*: all synthetic data is lost."
$(COMPOSE) $(COMPOSE_ARGS) down -v
logs:
$(COMPOSE) $(COMPOSE_ARGS) logs --tail=100 api
ps:
$(COMPOSE) $(COMPOSE_ARGS) ps
test-persistence: test-persistence:
@test -n "$(ACTION_SCRIPT)" || (echo "Set ACTION_SCRIPT to your implemented executable restart hook"; exit 2) @test -n "$(ACTION_SCRIPT)" || (echo "Set ACTION_SCRIPT to your implemented executable restart hook" >&2; exit 2)
$(PYTHON) tests/resilience.py --mode persistence --action-script "$(ACTION_SCRIPT)" --base-url "$(BASE_URL)" $(TLS_ARGS) $(PYTHON) tests/resilience.py --mode persistence --action-script "$(ACTION_SCRIPT)" --base-url "$(BASE_URL)" $(TLS_ARGS)
test-failover: test-failover:
@test -n "$(ACTION_SCRIPT)" || (echo "Set ACTION_SCRIPT to your implemented executable stop-one hook"; exit 2) @test -n "$(ACTION_SCRIPT)" || (echo "Set ACTION_SCRIPT to your implemented executable stop-one hook" >&2; 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 "$(ACTION_SCRIPT)" --base-url "$(BASE_URL)" $(TLS_ARGS)
test-student:
$(GO) test -count=1 ./...
$(PYTHON) student-tests/blackbox.py --base-url "$(BASE_URL)" $(TLS_ARGS)
test-student-race:
$(GO) test -race -count=1 ./...
test-attachment:
$(PYTHON) student-tests/attachment-checks.py --base-url "$(BASE_URL)" $(TLS_ARGS)
test-container:
$(PYTHON) scripts/container-checks.py --base-url "$(BASE_URL)" $(TLS_ARGS)
test-consistency:
$(PYTHON) scripts/track2.py --base-url "$(BASE_URL)" $(TLS_ARGS)
experiment:
$(PYTHON) scripts/upload-experiment.py --base-url "$(BASE_URL)" $(TLS_ARGS)
clean-clone:
./scripts/clean-clone-check.sh
py39:
./scripts/py39-tests.sh
collect-evidence:
./scripts/collect-evidence.sh
+700
View File
@@ -0,0 +1,700 @@
// Command loadgen is a synthetic HTTP load generator for the lab3 experiment.
// It is not part of the public API contract. It creates its own synthetic user
// and chat through the load balancer, then measures message POST throughput
// (or a mixed read/write profile) with per-second buckets and X-Instance-Id
// attribution.
//
// The default profile is closed-loop: `-concurrency` workers each send the
// next request as soon as the previous one finishes. `-rate` switches to an
// open-loop target rate. Both are reported honestly as HTTP acknowledgement
// throughput, not as a count of PostgreSQL commits.
package main
import (
"bytes"
"context"
"crypto/rand"
"encoding/hex"
"encoding/json"
"flag"
"fmt"
"io"
"math"
"net/http"
"os"
"os/exec"
"sort"
"sync"
"sync/atomic"
"time"
)
var version = "dev"
type config struct {
baseURL string
duration time.Duration
warmup time.Duration
concurrency int
rate float64
readRatio float64
timeout time.Duration
output string
retryUncertain bool
note string
stopInstance string
stopScript string
stopAfter time.Duration
}
type seriesBucket struct {
Second int64 `json:"second"`
Success int64 `json:"success"`
Errors int64 `json:"errors"`
P50 float64 `json:"p50_ms"`
P95 float64 `json:"p95_ms"`
P99 float64 `json:"p99_ms"`
latency []float64
}
type summary struct {
Tool string `json:"tool"`
Version string `json:"version"`
StartedAt string `json:"started_at"`
FinishedAt string `json:"finished_at"`
MeasuredSeconds float64 `json:"measured_seconds"`
WarmupSeconds float64 `json:"warmup_seconds"`
Concurrency int `json:"concurrency"`
RateLimit float64 `json:"rate_limit_per_second"`
ReadRatio float64 `json:"read_ratio"`
RetryUncertain bool `json:"retry_uncertain"`
Profile string `json:"profile"`
Successful int64 `json:"successful_requests"`
Failed int64 `json:"failed_requests"`
ErrorRatio float64 `json:"error_ratio"`
SuccessfulRPS float64 `json:"successful_rps"`
OfferedRPS float64 `json:"offered_rps"`
LatencyMS latencySummary `json:"successful_latency_ms"`
StatusCounts map[string]int64 `json:"status_counts"`
Instances map[string]int64 `json:"instances"`
AppVersions map[string]int64 `json:"app_versions"`
Kinds map[string]int64 `json:"kinds"`
Series []seriesBucket `json:"series"`
Retries int64 `json:"uncertain_retries"`
Violations []string `json:"idempotency_violations,omitempty"`
Note string `json:"note"`
Failover *failoverSummary `json:"failover,omitempty"`
}
type failoverSummary struct {
TargetInstance string `json:"target_instance"`
StopStartedAt string `json:"stop_started_at"`
StopFinishedAt string `json:"stop_finished_at"`
StopScriptExit int `json:"stop_script_exit"`
StopDurationSeconds float64 `json:"stop_duration_seconds"`
FirstSuccessAfterStopSec float64 `json:"first_success_after_stop_seconds"`
FirstWriteAfterStopSec float64 `json:"first_write_after_stop_seconds"`
FirstOtherSuccessSec float64 `json:"first_success_on_other_replica_seconds"`
SuccessesAfterStop int64 `json:"successes_after_stop"`
OtherSuccessesAfterStop int64 `json:"successes_on_other_replica_after_stop"`
ErrorsAfterStop int64 `json:"errors_after_stop"`
TargetResponsesAfterStop int64 `json:"target_responses_after_stop"`
TargetLastResponseAt string `json:"target_last_response_at"`
}
type latencySummary struct {
P50 float64 `json:"p50"`
P95 float64 `json:"p95"`
P99 float64 `json:"p99"`
Max float64 `json:"max"`
Mean float64 `json:"mean"`
}
func main() {
cfg := config{}
flag.StringVar(&cfg.baseURL, "base-url", "http://127.0.0.1:8083", "LB base URL")
flag.DurationVar(&cfg.duration, "duration", 20*time.Second, "measured duration")
flag.DurationVar(&cfg.warmup, "warmup", 5*time.Second, "warmup before measurement")
flag.IntVar(&cfg.concurrency, "concurrency", 32, "workers (closed loop) or max in-flight (rate mode)")
flag.Float64Var(&cfg.rate, "rate", 0, "open-loop target requests/second; 0 = closed loop")
flag.Float64Var(&cfg.readRatio, "read-ratio", 0, "fraction of GET /users/me requests (failover probe)")
flag.DurationVar(&cfg.timeout, "timeout", 5*time.Second, "per-request timeout")
flag.StringVar(&cfg.output, "output", "", "write JSON summary to this path")
flag.BoolVar(&cfg.retryUncertain, "retry-uncertain", false, "retry failed POSTs with the same Idempotency-Key (failover probe)")
flag.StringVar(&cfg.note, "note", "", "free-form note stored in the summary")
flag.StringVar(&cfg.stopInstance, "stop-instance", "", "failover probe: stop this X-Instance-Id during the run")
flag.StringVar(&cfg.stopScript, "stop-script", "", "failover probe: executable that stops TARGET_INSTANCE_ID")
flag.DurationVar(&cfg.stopAfter, "stop-after", 0, "failover probe: stop after this much measured time")
flag.StringVar(&version, "version", "dev", "generator revision label")
flag.Parse()
if cfg.duration <= 0 || cfg.concurrency < 1 || cfg.readRatio < 0 || cfg.readRatio > 1 || cfg.rate < 0 {
fmt.Fprintln(os.Stderr, "invalid load parameters")
os.Exit(2)
}
client := &http.Client{
Timeout: cfg.timeout,
Transport: &http.Transport{
MaxIdleConns: cfg.concurrency*2 + 8,
MaxIdleConnsPerHost: cfg.concurrency*2 + 8,
IdleConnTimeout: 30 * time.Second,
DisableCompression: true,
},
}
actor, chat := bootstrap(client, cfg.baseURL)
runID := randomHex(8)
measureStart := time.Now().Add(cfg.warmup)
deadline := measureStart.Add(cfg.duration)
var failover *failoverState
if cfg.stopScript != "" {
target := cfg.stopInstance
if target == "" {
target = observeAnyInstance(client, cfg.baseURL, actor)
}
if target == "" {
fail("no X-Instance-Id observed for failover target")
}
failover = &failoverState{target: target, script: cfg.stopScript}
go failover.run(measureStart.Add(cfg.stopAfter))
}
var (
mu sync.Mutex
samples []result
series = map[int64]*seriesBucket{}
retries int64
)
worker := func(id int) {
seq := 0
for {
now := time.Now()
if !now.Before(deadline) {
return
}
// Warmup traffic is sent but excluded from every summary number.
measured := !now.Before(measureStart)
kind := "write"
if cfg.readRatio > 0 && float64((id+seq)%1000)/1000.0 < cfg.readRatio {
kind = "read"
}
start := time.Now()
result := oneRequest(client, cfg.baseURL, actor, chat, kind, fmt.Sprintf("%s-%d-%d", runID, id, seq), cfg.retryUncertain)
elapsed := time.Since(start)
seq++
if !measured {
continue
}
result.at = start
result.done = time.Now()
result.latency = elapsed
mu.Lock()
samples = append(samples, result)
if result.err != "" && result.ok {
retries++
}
bucket := series[start.Unix()]
if bucket == nil {
bucket = &seriesBucket{Second: start.Unix()}
series[start.Unix()] = bucket
}
if result.ok {
bucket.Success++
bucket.latency = append(bucket.latency, float64(result.latency.Microseconds())/1000.0)
} else {
bucket.Errors++
}
mu.Unlock()
if cfg.rate > 0 {
// Spread a fixed offered rate across workers. This is a
// best-effort pacing, not a hard scheduler; lateness is
// visible in the latency distribution.
interval := time.Duration(float64(time.Second) * float64(cfg.concurrency) / cfg.rate)
if sleep := interval - time.Since(start); sleep > 0 {
time.Sleep(sleep)
}
}
}
}
var wg sync.WaitGroup
for i := 0; i < cfg.concurrency; i++ {
wg.Add(1)
go func(id int) {
defer wg.Done()
worker(id)
}(i)
}
wg.Wait()
finished := time.Now()
measuredSeconds := finished.Sub(measureStart).Seconds()
var failoverSnapshot *failoverState
if failover != nil {
failoverSnapshot = failover
}
sum := summarize(cfg, runID, measureStart, finished, measuredSeconds, samples, series, atomic.LoadInt64(&retries), failoverSnapshot)
if cfg.output != "" {
data, _ := json.MarshalIndent(sum, "", " ")
if err := os.WriteFile(cfg.output, append(data, '\n'), 0o644); err != nil {
fmt.Fprintln(os.Stderr, "cannot write output:", err)
os.Exit(1)
}
}
encoded, _ := json.MarshalIndent(sum, "", " ")
fmt.Println(string(encoded))
if sum.Successful == 0 {
os.Exit(1)
}
}
type credentials struct {
token string
user string
}
type chatInfo struct {
id string
}
type result struct {
at time.Time
done time.Time
latency time.Duration
ok bool
status int
instance string
appVer string
kind string
key string
message string
err string
}
func oneRequest(client *http.Client, base string, actor credentials, chat chatInfo, kind, key string, retry bool) result {
deadline := time.Now().Add(10 * time.Second)
for {
res := requestOnce(client, base, actor, chat, kind, key)
if res.ok || !retry || kind != "write" || time.Now().After(deadline) {
return res
}
// A timeout or LB 502/503 after SIGTERM is an uncertain result. The
// same key is safe to retry only because the server's idempotency
// record and message are committed atomically.
res.err = "retry:" + res.err
time.Sleep(30 * time.Millisecond)
}
}
func requestOnce(client *http.Client, base string, actor credentials, chat chatInfo, kind, key string) result {
method, path := http.MethodPost, "/api/v1/chats/"+chat.id+"/messages"
var body io.Reader
if kind == "read" {
method, path = http.MethodGet, "/api/v1/users/me"
} else {
payload, _ := json.Marshal(map[string]string{"text": "load " + key})
body = bytes.NewReader(payload)
}
req, err := http.NewRequestWithContext(context.Background(), method, base+path, body)
if err != nil {
return result{status: 0, err: "build_request"}
}
req.Header.Set("Authorization", "Bearer "+actor.token)
if kind == "write" {
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Idempotency-Key", key)
}
response, err := client.Do(req)
if err != nil {
return result{status: 0, err: "transport"}
}
defer response.Body.Close()
data, readErr := io.ReadAll(io.LimitReader(response.Body, 1<<20))
res := result{
status: response.StatusCode,
instance: response.Header.Get("X-Instance-Id"),
appVer: response.Header.Get("X-App-Version"),
kind: kind,
key: key,
}
if readErr != nil {
res.err = "read_body"
return res
}
if response.StatusCode == http.StatusCreated || response.StatusCode == http.StatusOK {
res.ok = true
if kind == "write" {
var message struct {
ID string `json:"id"`
}
if err := json.Unmarshal(data, &message); err != nil || message.ID == "" {
res.ok = false
res.err = "bad_json"
} else {
res.message = message.ID
}
}
return res
}
res.err = "status"
return res
}
func bootstrap(client *http.Client, base string) (credentials, chatInfo) {
// /health/ready is retried until the stack is up.
waitReady(client, base)
username := "lg_" + randomHex(10)
password := "Loadgen-" + randomHex(12)
registered := struct {
ID string `json:"id"`
}{}
postJSON(client, base+"/api/v1/users", "", map[string]string{
"username": username, "display_name": "Load generator", "password": password,
}, &registered)
basic := basicAuth(username, password)
session := struct {
Token string `json:"token"`
}{}
postJSON(client, base+"/api/v1/auth/sessions", "Basic "+basic, nil, &session)
if session.Token == "" || registered.ID == "" {
fail("bootstrap failed")
}
chat := struct {
ID string `json:"id"`
}{}
postJSON(client, base+"/api/v1/chats", "Bearer "+session.Token, map[string]interface{}{
"title": "loadgen " + randomHex(6), "member_ids": []string{registered.ID},
}, &chat)
if chat.ID == "" {
fail("chat bootstrap failed")
}
return credentials{token: session.Token, user: registered.ID}, chatInfo{id: chat.ID}
}
func waitReady(client *http.Client, base string) {
deadline := time.Now().Add(90 * time.Second)
for time.Now().Before(deadline) {
response, err := client.Get(base + "/health/ready")
if err == nil {
io.Copy(io.Discard, response.Body)
response.Body.Close()
if response.StatusCode == http.StatusOK {
return
}
}
time.Sleep(250 * time.Millisecond)
}
fail("stack did not become ready")
}
func postJSON(client *http.Client, url, authorization string, body interface{}, out interface{}) {
var reader io.Reader
if body != nil {
data, _ := json.Marshal(body)
reader = bytes.NewReader(data)
}
req, err := http.NewRequest(http.MethodPost, url, reader)
if err != nil {
fail("build bootstrap request")
}
if body != nil {
req.Header.Set("Content-Type", "application/json")
}
if authorization != "" {
req.Header.Set("Authorization", authorization)
}
response, err := client.Do(req)
if err != nil {
fail("bootstrap transport failure")
}
defer response.Body.Close()
data, _ := io.ReadAll(io.LimitReader(response.Body, 1<<20))
if response.StatusCode != http.StatusCreated {
fail(fmt.Sprintf("bootstrap status %d", response.StatusCode))
}
if out != nil {
if err := json.Unmarshal(data, out); err != nil {
fail("bootstrap JSON")
}
}
}
func basicAuth(username, password string) string {
const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
raw := []byte(username + ":" + password)
var encoded []byte
for i := 0; i < len(raw); i += 3 {
var chunk [3]byte
n := copy(chunk[:], raw[i:])
value := uint(chunk[0])<<16 | uint(chunk[1])<<8 | uint(chunk[2])
encoded = append(encoded, alphabet[value>>18&63], alphabet[value>>12&63])
if n > 1 {
encoded = append(encoded, alphabet[value>>6&63])
} else {
encoded = append(encoded, '=')
}
if n > 2 {
encoded = append(encoded, alphabet[value&63])
} else {
encoded = append(encoded, '=')
}
}
return string(encoded)
}
func summarize(cfg config, runID string, start, finished time.Time, seconds float64, samples []result, series map[int64]*seriesBucket, retries int64, failover *failoverState) summary {
sum := summary{
Tool: "mtusi-lab3-loadgen",
Version: version,
StartedAt: start.UTC().Format(time.RFC3339Nano),
FinishedAt: finished.UTC().Format(time.RFC3339Nano),
MeasuredSeconds: round(seconds, 3),
WarmupSeconds: cfg.warmup.Seconds(),
Concurrency: cfg.concurrency,
RateLimit: cfg.rate,
ReadRatio: cfg.readRatio,
RetryUncertain: cfg.retryUncertain,
Profile: "closed-loop",
StatusCounts: map[string]int64{},
Instances: map[string]int64{},
AppVersions: map[string]int64{},
Kinds: map[string]int64{},
Retries: retries,
Note: cfg.note,
}
if cfg.rate > 0 {
sum.Profile = fmt.Sprintf("open-loop target %.1f req/s (best effort)", cfg.rate)
}
sum.Note = cfg.note + "; synthetic messages created by loadgen, no retries unless -retry-uncertain"
var latencies []float64
idByKey := map[string]string{}
summaryFailover := buildFailoverSummary(failover, samples)
for _, item := range samples {
sum.Kinds[item.kind]++
statusKey := fmt.Sprintf("%d", item.status)
if item.status == 0 {
statusKey = "error:" + item.err
}
sum.StatusCounts[statusKey]++
if item.ok {
sum.Successful++
latencies = append(latencies, float64(item.latency.Microseconds())/1000.0)
if item.instance == "" {
item.instance = "(missing)"
}
sum.Instances[item.instance]++
ver := item.appVer
if ver == "" {
ver = "(missing)"
}
sum.AppVersions[ver]++
if item.kind == "write" && item.message != "" {
if previous, seen := idByKey[item.key]; seen && previous != item.message {
sum.Violations = append(sum.Violations, "same key returned different message ids")
}
idByKey[item.key] = item.message
}
} else {
sum.Failed++
}
}
sum.OfferedRPS = round(float64(sum.Successful+sum.Failed)/seconds, 3)
sum.SuccessfulRPS = round(float64(sum.Successful)/seconds, 3)
if total := sum.Successful + sum.Failed; total > 0 {
sum.ErrorRatio = round(float64(sum.Failed)/float64(total), 6)
}
sort.Float64s(latencies)
sum.LatencyMS = latencyPercentiles(latencies)
sum.Failover = summaryFailover
keys := make([]int64, 0, len(series))
for second := range series {
keys = append(keys, second)
}
sort.Slice(keys, func(i, j int) bool { return keys[i] < keys[j] })
for _, second := range keys {
bucket := series[second]
sort.Float64s(bucket.latency)
bucket.P50 = percentile(bucket.latency, 0.50)
bucket.P95 = percentile(bucket.latency, 0.95)
bucket.P99 = percentile(bucket.latency, 0.99)
sum.Series = append(sum.Series, *bucket)
}
return sum
}
func percentile(sorted []float64, p float64) float64 {
if len(sorted) == 0 {
return 0
}
index := int(math.Ceil(p*float64(len(sorted)))) - 1
if index < 0 {
index = 0
}
if index >= len(sorted) {
index = len(sorted) - 1
}
return round(sorted[index], 3)
}
func latencyPercentiles(sorted []float64) latencySummary {
if len(sorted) == 0 {
return latencySummary{}
}
pick := func(p float64) float64 { return percentile(sorted, p) }
var total float64
for _, value := range sorted {
total += value
}
return latencySummary{
P50: pick(0.50), P95: pick(0.95), P99: pick(0.99),
Max: round(sorted[len(sorted)-1], 3), Mean: round(total/float64(len(sorted)), 3),
}
}
func round(value float64, digits int) float64 {
scale := math.Pow(10, float64(digits))
return math.Round(value*scale) / scale
}
func randomHex(n int) string {
buf := make([]byte, n)
if _, err := rand.Read(buf); err != nil {
fail("random")
}
return hex.EncodeToString(buf)
}
func fail(message string) {
fmt.Fprintln(os.Stderr, "loadgen:", message)
os.Exit(2)
}
type failoverState struct {
target string
script string
mu sync.Mutex
started time.Time
finished time.Time
exitCode int
err string
}
func (f *failoverState) run(at time.Time) {
if delay := time.Until(at); delay > 0 {
time.Sleep(delay)
}
f.mu.Lock()
f.started = time.Now()
f.mu.Unlock()
command := exec.Command(f.script)
command.Env = append(os.Environ(), "TARGET_INSTANCE_ID="+f.target)
command.Stdout = io.Discard
command.Stderr = io.Discard
err := command.Run()
f.mu.Lock()
defer f.mu.Unlock()
f.finished = time.Now()
if err == nil {
f.exitCode = 0
return
}
if exitError, ok := err.(*exec.ExitError); ok {
f.exitCode = exitError.ExitCode()
} else {
f.exitCode = -1
f.err = err.Error()
}
}
func (f *failoverState) snapshot() failoverState {
f.mu.Lock()
defer f.mu.Unlock()
return failoverState{
target: f.target,
started: f.started,
finished: f.finished,
exitCode: f.exitCode,
err: f.err,
}
}
func observeAnyInstance(client *http.Client, base string, actor credentials) string {
deadline := time.Now().Add(30 * time.Second)
for time.Now().Before(deadline) {
req, _ := http.NewRequest(http.MethodGet, base+"/api/v1/users/me", nil)
req.Header.Set("Authorization", "Bearer "+actor.token)
response, err := client.Do(req)
if err == nil {
io.Copy(io.Discard, response.Body)
response.Body.Close()
if instance := response.Header.Get("X-Instance-Id"); instance != "" {
return instance
}
}
time.Sleep(100 * time.Millisecond)
}
return ""
}
func buildFailoverSummary(failover *failoverState, samples []result) *failoverSummary {
if failover == nil {
return nil
}
state := failover.snapshot()
if state.started.IsZero() {
return nil
}
summary := &failoverSummary{
TargetInstance: state.target,
StopStartedAt: state.started.UTC().Format(time.RFC3339Nano),
StopFinishedAt: state.finished.UTC().Format(time.RFC3339Nano),
StopScriptExit: state.exitCode,
StopDurationSeconds: round(state.finished.Sub(state.started).Seconds(), 3),
FirstSuccessAfterStopSec: -1,
FirstWriteAfterStopSec: -1,
FirstOtherSuccessSec: -1,
}
var firstSuccess, firstWrite, firstOther time.Time
var lastTarget time.Time
for _, item := range samples {
if item.instance == state.target && item.done.After(lastTarget) {
lastTarget = item.done
}
if !item.at.After(state.started) {
continue
}
if item.ok {
summary.SuccessesAfterStop++
if firstSuccess.IsZero() || item.done.Before(firstSuccess) {
firstSuccess = item.done
}
if item.kind == "write" && (firstWrite.IsZero() || item.done.Before(firstWrite)) {
firstWrite = item.done
}
if item.instance != state.target {
summary.OtherSuccessesAfterStop++
if firstOther.IsZero() || item.done.Before(firstOther) {
firstOther = item.done
}
}
} else {
summary.ErrorsAfterStop++
}
if item.at.After(state.finished.Add(500*time.Millisecond)) && item.instance == state.target {
summary.TargetResponsesAfterStop++
}
}
if !firstSuccess.IsZero() {
summary.FirstSuccessAfterStopSec = round(firstSuccess.Sub(state.started).Seconds(), 3)
}
if !firstWrite.IsZero() {
summary.FirstWriteAfterStopSec = round(firstWrite.Sub(state.started).Seconds(), 3)
}
if !firstOther.IsZero() {
summary.FirstOtherSuccessSec = round(firstOther.Sub(state.started).Seconds(), 3)
}
if !lastTarget.IsZero() {
summary.TargetLastResponseAt = lastTarget.UTC().Format(time.RFC3339Nano)
}
return summary
}
+298
View File
@@ -0,0 +1,298 @@
// Command messenger runs the lab3 HTTP API and the container healthcheck
// helper. PostgreSQL holds users, chats, membership, messages and idempotency
// records; Valkey holds server-side sessions shared by every API replica.
package main
import (
"context"
"errors"
"flag"
"fmt"
"io"
"log/slog"
"net"
"net/http"
"os"
"os/signal"
"strconv"
"strings"
"syscall"
"time"
"mtusi.ru/messenger-lab4/internal/api"
"mtusi.ru/messenger-lab4/internal/config"
"mtusi.ru/messenger-lab4/internal/objectstore"
"mtusi.ru/messenger-lab4/internal/session"
"mtusi.ru/messenger-lab4/internal/store"
"mtusi.ru/messenger-lab4/internal/uuid"
)
// Overridden at build time with -X main.version=... and -X main.revision=...
var (
version = "dev"
revision = "unknown"
)
const idempotencyRetention = 24 * time.Hour
func main() {
healthcheck := flag.Bool("healthcheck", false, "probe the local liveness endpoint and exit 0/1")
flag.Parse()
cfg, err := config.Load()
if err != nil {
fmt.Fprintln(os.Stderr, "configuration error:", err)
os.Exit(2)
}
if *healthcheck {
os.Exit(runHealthcheck(cfg))
}
logger := newLogger(cfg)
ctx := context.Background()
instanceID := instanceIdentity()
repository, err := store.Open(ctx, cfg.DatabaseURL, store.Options{
MaxConns: cfg.DBMaxConns,
MinConns: cfg.DBMinConns,
ConnectTimeout: cfg.DBConnectTimeout,
StatementTimeout: cfg.DBStatementTimeout,
QueryTimeout: cfg.QueryTimeout,
})
if err != nil {
logger.Error("database configuration failed", "error", err)
os.Exit(2)
}
defer repository.Close()
if err := waitForDatabase(ctx, repository, cfg.StartupTimeout, logger); err != nil {
logger.Error("postgres did not become ready", "timeout_seconds", int(cfg.StartupTimeout.Seconds()), "error", err)
os.Exit(1)
}
sessions, err := session.Open(cfg.CacheURL, session.Options{
PoolSize: cfg.CachePoolSize,
DialTimeout: cfg.CacheTimeout,
IOTimeout: cfg.CacheTimeout,
TTL: cfg.SessionTTL,
})
if err != nil {
logger.Error("session store configuration failed", "error", err)
os.Exit(2)
}
defer func() { _ = sessions.Close() }()
objects, err := objectstore.Open(objectstore.Config{
Endpoint: cfg.S3Endpoint,
Region: cfg.S3Region,
Bucket: cfg.S3Bucket,
AccessKey: cfg.S3AccessKey,
SecretKey: cfg.S3SecretKey,
Timeout: cfg.S3Timeout,
})
if err != nil {
logger.Error("object store configuration failed", "error", err)
os.Exit(2)
}
app, err := api.New(repository, sessions, objects, logger, instanceID, version, api.Options{
MaxUploadBytes: cfg.MaxUploadBytes,
MaxImagePixels: cfg.MaxImagePixels,
DecodeConcurrency: cfg.DecodeConcurrency,
PutConcurrency: cfg.PutConcurrency,
TempDir: cfg.TempDir,
})
if err != nil {
logger.Error("application initialization failed", "error", err)
os.Exit(1)
}
server := &http.Server{
Handler: app.Handler(),
ReadHeaderTimeout: 5 * time.Second,
ReadTimeout: 15 * time.Second,
WriteTimeout: 20 * time.Second,
IdleTimeout: 60 * time.Second,
MaxHeaderBytes: 1 << 20,
}
address := net.JoinHostPort(cfg.Host, strconv.Itoa(cfg.Port))
listener, err := net.Listen("tcp", address)
if err != nil {
logger.Error("listen failed", "address", address, "error", err)
os.Exit(1)
}
// Operator-only stats listener. It is bound to container loopback by
// default and is not published by compose, so it cannot bypass the LB.
var metricsServer *http.Server
if cfg.MetricsAddr != "off" {
metricsMux := http.NewServeMux()
metricsMux.HandleFunc("/internal/stats", app.InternalStatsHandler)
metricsServer = &http.Server{
Handler: metricsMux,
ReadHeaderTimeout: 2 * time.Second,
ReadTimeout: 5 * time.Second,
WriteTimeout: 5 * time.Second,
}
metricsListener, listenErr := net.Listen("tcp", cfg.MetricsAddr)
if listenErr != nil {
logger.Error("metrics listen failed", "address", cfg.MetricsAddr, "error", listenErr)
os.Exit(1)
}
go func() {
if serveErr := metricsServer.Serve(metricsListener); serveErr != nil && !errors.Is(serveErr, http.ErrServerClosed) {
logger.Error("metrics server stopped unexpectedly", "error", serveErr)
}
}()
}
pruneCtx, pruneCancel := context.WithCancel(ctx)
defer pruneCancel()
go pruneIdempotency(pruneCtx, repository, logger)
logger.Info("server listening",
"address", listener.Addr().String(),
"env", cfg.Env,
"instance_id", instanceID,
"version", version,
"revision", revision,
"session_ttl_seconds", int(cfg.SessionTTL.Seconds()),
"s3_bucket", cfg.S3Bucket,
"max_upload_bytes", cfg.MaxUploadBytes,
"max_image_pixels", cfg.MaxImagePixels,
"decode_concurrency", cfg.DecodeConcurrency,
"s3_put_concurrency", cfg.PutConcurrency,
"shutdown_timeout_seconds", int(cfg.ShutdownTimeout.Seconds()),
"shutdown_drain_seconds", int(cfg.ShutdownDrain.Seconds()),
"db_max_conns", cfg.DBMaxConns,
)
serveErrors := make(chan error, 1)
go func() {
serveErrors <- server.Serve(listener)
}()
signals := make(chan os.Signal, 1)
signal.Notify(signals, syscall.SIGTERM, syscall.SIGINT)
select {
case received := <-signals:
logger.Info("shutdown initiated", "signal", received.String(), "instance_id", instanceID)
// Stop advertising readiness first. The load balancer removes this
// backend during the drain window while the process still accepts
// requests, so in-flight work is not cut off by the health transition.
app.SetReady(false)
if cfg.ShutdownDrain > 0 {
logger.Info("draining", "seconds", int(cfg.ShutdownDrain.Seconds()))
time.Sleep(cfg.ShutdownDrain)
}
started := time.Now()
shutdownCtx, cancel := context.WithTimeout(context.Background(), cfg.ShutdownTimeout)
defer cancel()
if err := server.Shutdown(shutdownCtx); err != nil {
logger.Error("graceful shutdown failed", "error", err)
_ = server.Close()
os.Exit(1)
}
if metricsServer != nil {
_ = metricsServer.Close()
}
pruneCancel()
logger.Info("shutdown complete",
"instance_id", instanceID,
"elapsed_ms", float64(time.Since(started).Microseconds())/1000.0,
)
os.Exit(0)
case err := <-serveErrors:
if err != nil && !errors.Is(err, http.ErrServerClosed) {
logger.Error("server stopped unexpectedly", "error", err)
os.Exit(1)
}
}
}
// instanceIdentity is stable for the lifetime of this process and unique per
// container. INSTANCE_ID overrides it; otherwise the container hostname is the
// actual process identity, which lets scripts/stop-one.sh map an X-Instance-Id
// response to exactly one Docker container. lab7 replaces this with an opaque
// alias that does not reveal a hostname.
func instanceIdentity() string {
if value := strings.TrimSpace(os.Getenv("INSTANCE_ID")); value != "" {
return value
}
if hostname, err := os.Hostname(); err == nil && strings.TrimSpace(hostname) != "" {
return hostname
}
return uuid.NewRandom(8)
}
func newLogger(cfg config.Config) *slog.Logger {
handler := slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{Level: cfg.LogLevel})
return slog.New(handler).With("service", "messenger-lab4", "app_env", cfg.Env)
}
func waitForDatabase(ctx context.Context, repository *store.Store, timeout time.Duration, logger *slog.Logger) error {
deadline := time.Now().Add(timeout)
attempt := 0
for {
attempt++
pingCtx, cancel := context.WithTimeout(ctx, 2*time.Second)
err := repository.Ping(pingCtx)
cancel()
if err == nil {
return nil
}
if time.Now().After(deadline) {
return err
}
logger.Debug("waiting for postgres", "attempt", attempt, "error", err)
time.Sleep(500 * time.Millisecond)
}
}
func pruneIdempotency(ctx context.Context, repository *store.Store, logger *slog.Logger) {
run := func() {
pruneCtx, cancel := context.WithTimeout(ctx, 15*time.Second)
deleted, err := repository.PruneIdempotency(pruneCtx, idempotencyRetention)
cancel()
if err != nil && ctx.Err() == nil {
logger.Warn("idempotency prune failed", "error", err)
return
}
if deleted > 0 {
logger.Info("pruned expired idempotency records", "rows", deleted, "retention_hours", 24)
}
}
run()
ticker := time.NewTicker(time.Hour)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
run()
}
}
}
// runHealthcheck is compiled into the same binary as the server, so the
// runtime image needs no curl, wget or shell. It always talks to loopback
// inside the container, independently of APP_HOST.
func runHealthcheck(cfg config.Config) int {
client := &http.Client{Timeout: 2 * time.Second}
url := "http://127.0.0.1:" + strconv.Itoa(cfg.Port) + "/health/live"
response, err := client.Get(url) //nolint:gosec // fixed loopback URL built from a validated port
if err != nil {
fmt.Fprintln(os.Stderr, "healthcheck request failed:", err)
return 1
}
defer response.Body.Close()
_, _ = io.Copy(io.Discard, response.Body)
if response.StatusCode != http.StatusOK {
fmt.Fprintln(os.Stderr, "healthcheck status:", response.StatusCode)
return 1
}
return 0
}
+69
View File
@@ -0,0 +1,69 @@
// Command migrate applies the embedded, checksummed PostgreSQL migrations and
// exits. It is a separate one-shot compose service: API replicas never race to
// migrate the shared schema. The advisory lock inside store.Migrate serialises
// concurrent invocations of this command as well.
package main
import (
"context"
"flag"
"fmt"
"log/slog"
"os"
"time"
"mtusi.ru/messenger-lab4/internal/config"
"mtusi.ru/messenger-lab4/internal/store"
)
var revision = "unknown"
func main() {
flag.Parse()
logger := slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{Level: slog.LevelInfo})).
With("service", "messenger-lab4-migrate", "revision", revision)
cfg, err := config.LoadMigrate()
if err != nil {
logger.Error("configuration error", "error", err)
os.Exit(2)
}
ctx, cancel := context.WithTimeout(context.Background(), 90*time.Second)
defer cancel()
repository, err := store.Open(ctx, cfg.DatabaseURL, store.Options{
MaxConns: cfg.DBMaxConns,
MinConns: 0,
ConnectTimeout: cfg.DBConnectTimeout,
StatementTimeout: cfg.DBStatementTimeout,
QueryTimeout: cfg.QueryTimeout,
})
if err != nil {
logger.Error("database configuration failed", "error", err)
os.Exit(2)
}
defer repository.Close()
for {
pingCtx, pingCancel := context.WithTimeout(ctx, 2*time.Second)
err = repository.Ping(pingCtx)
pingCancel()
if err == nil {
break
}
if ctx.Err() != nil {
logger.Error("postgres did not become ready", "error", err)
os.Exit(1)
}
logger.Info("waiting for postgres", "error", err)
time.Sleep(500 * time.Millisecond)
}
started := time.Now()
if err := repository.Migrate(ctx); err != nil {
logger.Error("migrations failed", "error", err)
os.Exit(1)
}
logger.Info("migrations complete", "elapsed_ms", float64(time.Since(started).Microseconds())/1000.0)
fmt.Println("migrations: up-to-date")
}
+357
View File
@@ -0,0 +1,357 @@
// Command reconciler is the track-2 consistency tool for the two stores.
//
// It compares PostgreSQL attachment rows with the objects under the private
// bucket prefix and reports:
// - ready row + object -> ok
// - ready row without object -> missing_object (report only: bytes
// cannot be invented or safely replaced; the operator must restore them)
// - pending row + object -> stale upload intent after the grace
// period; the object and the row are both removed
// - pending row without object -> stale upload intent; the row is removed
// - object without a row -> orphan object; removed only after grace
//
// Fresh objects and rows are never touched: the grace period protects an
// upload that is between its S3 PUT and its PostgreSQL COMMIT, and the
// reconciler re-checks the database immediately before every delete.
package main
import (
"context"
"encoding/json"
"errors"
"flag"
"fmt"
"os"
"sort"
"strconv"
"time"
"mtusi.ru/messenger-lab4/internal/config"
"mtusi.ru/messenger-lab4/internal/objectstore"
"mtusi.ru/messenger-lab4/internal/store"
)
type item struct {
ID string `json:"id,omitempty"`
ObjectKey string `json:"object_key"`
Status string `json:"status,omitempty"`
AgeSeconds int64 `json:"age_seconds"`
ObjectPresent bool `json:"object_present,omitempty"`
}
type report struct {
GeneratedAt string `json:"generated_at"`
Mode string `json:"mode"`
Bucket string `json:"bucket"`
Prefix string `json:"prefix"`
GraceSeconds int64 `json:"grace_seconds"`
Database dbCounts `json:"database"`
ObjectStore s3Counts `json:"object_store"`
Findings findings `json:"findings"`
Actions actions `json:"actions"`
Timing timing `json:"timing"`
}
type dbCounts struct {
Rows int `json:"rows"`
Ready int `json:"ready"`
Pending int `json:"pending"`
}
type s3Counts struct {
Objects int `json:"objects"`
}
type findings struct {
OK int `json:"ok"`
OrphanObjects []item `json:"orphan_objects"`
ProtectedObjects []item `json:"protected_recent_objects"`
MissingObjects []item `json:"missing_objects"`
StalePending []item `json:"stale_pending"`
ProtectedPending []item `json:"protected_pending"`
}
type actions struct {
PlannedDeletes []string `json:"planned_deletes,omitempty"`
DeletedObjects []string `json:"deleted_objects"`
DeletedPendingRows []string `json:"deleted_pending_rows"`
Skipped []string `json:"skipped"`
UnresolvedMissing []string `json:"unresolved_missing"`
Errors []string `json:"errors"`
}
type timing struct {
DBScanMS int64 `json:"db_scan_ms"`
S3ListMS int64 `json:"s3_list_ms"`
TotalMS int64 `json:"total_ms"`
DBRows int `json:"db_rows"`
S3Objects int `json:"s3_objects"`
}
func main() {
apply := flag.Bool("apply", false, "perform safe deletions; without it the run is a read-only dry run")
prefix := flag.String("prefix", "attachments/", "bucket prefix owned by the application")
output := flag.String("output", "", "optional path for the JSON report")
defaultGrace := time.Hour
if raw := os.Getenv("RECONCILE_GRACE_SECONDS"); raw != "" {
seconds, err := strconv.Atoi(raw)
if err != nil || seconds < 1 {
fmt.Fprintln(os.Stderr, "reconciler: RECONCILE_GRACE_SECONDS must be a positive integer")
os.Exit(2)
}
defaultGrace = time.Duration(seconds) * time.Second
}
grace := flag.Duration("grace", defaultGrace, "minimum age before an orphan object or pending upload intent may be removed")
flag.Parse()
if *grace < time.Second {
fmt.Fprintln(os.Stderr, "reconciler: -grace must be at least 1s")
os.Exit(2)
}
if *prefix == "" || *prefix == "/" {
fmt.Fprintln(os.Stderr, "reconciler: -prefix must be a non-empty application prefix")
os.Exit(2)
}
cfg, err := config.LoadTool()
if err != nil {
fmt.Fprintln(os.Stderr, "reconciler: configuration error:", err)
os.Exit(2)
}
repository, err := store.Open(context.Background(), cfg.DatabaseURL, store.Options{
MaxConns: 4,
MinConns: 0,
ConnectTimeout: cfg.DBConnectTimeout,
StatementTimeout: cfg.DBStatementTimeout,
QueryTimeout: cfg.QueryTimeout,
})
if err != nil {
fmt.Fprintln(os.Stderr, "reconciler: database configuration error:", err)
os.Exit(2)
}
defer repository.Close()
objects, err := objectstore.Open(objectstore.Config{
Endpoint: cfg.S3Endpoint,
Region: cfg.S3Region,
Bucket: cfg.S3Bucket,
AccessKey: cfg.S3AccessKey,
SecretKey: cfg.S3SecretKey,
Timeout: cfg.S3Timeout,
})
if err != nil {
fmt.Fprintln(os.Stderr, "reconciler: object store configuration error:", err)
os.Exit(2)
}
started := time.Now().UTC()
result := report{
GeneratedAt: started.Format(time.RFC3339Nano),
Mode: "dry-run",
Bucket: cfg.S3Bucket,
Prefix: *prefix,
GraceSeconds: int64(grace.Seconds()),
}
if *apply {
result.Mode = "apply"
}
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
defer cancel()
dbStarted := time.Now()
rows, err := repository.ListAttachmentsForReconcile(ctx)
if err != nil {
fmt.Fprintln(os.Stderr, "reconciler: database scan failed:", err)
os.Exit(1)
}
result.Timing.DBScanMS = time.Since(dbStarted).Milliseconds()
result.Timing.DBRows = len(rows)
result.Database.Rows = len(rows)
s3Started := time.Now()
stored, err := objects.List(ctx, *prefix)
if err != nil {
fmt.Fprintln(os.Stderr, "reconciler: object store scan failed:", err)
os.Exit(1)
}
result.Timing.S3ListMS = time.Since(s3Started).Milliseconds()
result.Timing.S3Objects = len(stored)
result.ObjectStore.Objects = len(stored)
now := time.Now().UTC()
dbByKey := make(map[string]store.ReconcileAttachment, len(rows))
for _, row := range rows {
dbByKey[row.ObjectKey] = row
switch row.Status {
case "ready":
result.Database.Ready++
case "pending":
result.Database.Pending++
}
}
objectByKey := make(map[string]objectstore.ObjectInfo, len(stored))
for _, object := range stored {
objectByKey[object.Key] = object
}
// Objects with no metadata row: candidate orphans, unless still fresh.
for _, object := range stored {
if _, known := dbByKey[object.Key]; known {
continue
}
age := ageSeconds(now, object.LastModified)
if object.LastModified.IsZero() || age < int64(grace.Seconds()) {
result.Findings.ProtectedObjects = append(result.Findings.ProtectedObjects, item{
ObjectKey: object.Key, AgeSeconds: age,
})
continue
}
result.Findings.OrphanObjects = append(result.Findings.OrphanObjects, item{
ObjectKey: object.Key, AgeSeconds: age,
})
}
// Metadata rows: ready rows must have an object; pending rows are internal
// upload intents and are cleaned only after the grace period.
for _, row := range rows {
_, exists := objectByKey[row.ObjectKey]
age := ageSeconds(now, row.UpdatedAt)
switch row.Status {
case "ready":
if exists {
result.Findings.OK++
} else {
result.Findings.MissingObjects = append(result.Findings.MissingObjects, item{
ID: row.ID, ObjectKey: row.ObjectKey, Status: row.Status, AgeSeconds: age,
})
}
case "pending":
if age >= int64(grace.Seconds()) {
result.Findings.StalePending = append(result.Findings.StalePending, item{
ID: row.ID, ObjectKey: row.ObjectKey, Status: row.Status,
AgeSeconds: age, ObjectPresent: exists,
})
} else {
result.Findings.ProtectedPending = append(result.Findings.ProtectedPending, item{
ID: row.ID, ObjectKey: row.ObjectKey, Status: row.Status,
AgeSeconds: age, ObjectPresent: exists,
})
}
}
}
sortFindings(&result.Findings)
if *apply {
applyActions(ctx, repository, objects, result.Findings.OrphanObjects, result.Findings.StalePending, *grace, &result.Actions)
} else {
for _, orphan := range result.Findings.OrphanObjects {
result.Actions.PlannedDeletes = append(result.Actions.PlannedDeletes, orphan.ObjectKey)
}
for _, pending := range result.Findings.StalePending {
result.Actions.PlannedDeletes = append(result.Actions.PlannedDeletes, pending.ObjectKey)
}
}
for _, missing := range result.Findings.MissingObjects {
result.Actions.UnresolvedMissing = append(result.Actions.UnresolvedMissing, missing.ID)
}
result.Timing.TotalMS = time.Since(started).Milliseconds()
encoded, err := json.MarshalIndent(result, "", " ")
if err != nil {
fmt.Fprintln(os.Stderr, "reconciler: encode report failed:", err)
os.Exit(1)
}
fmt.Println(string(encoded))
if *output != "" {
if err := os.WriteFile(*output, append(encoded, '\n'), 0o644); err != nil {
fmt.Fprintln(os.Stderr, "reconciler: write report failed:", err)
os.Exit(1)
}
}
if len(result.Actions.Errors) > 0 {
os.Exit(1)
}
}
// applyActions performs the two safe mutations. Broken ready metadata is never
// deleted: automatic deletion would destroy the only record of a user's file
// and could hide data loss. Each mutation re-reads the database first.
func applyActions(ctx context.Context, repository *store.Store, objects *objectstore.Store, orphans, stale []item, grace time.Duration, result *actions) {
for _, orphan := range orphans {
stillReferenced, err := repository.AttachmentByObjectKey(ctx, orphan.ObjectKey)
if err != nil {
result.Errors = append(result.Errors, "recheck "+orphan.ObjectKey+": "+err.Error())
continue
}
if stillReferenced {
result.Skipped = append(result.Skipped, orphan.ObjectKey)
continue
}
if err := objects.Remove(ctx, orphan.ObjectKey); err != nil {
result.Errors = append(result.Errors, "delete "+orphan.ObjectKey+": "+err.Error())
continue
}
result.DeletedObjects = append(result.DeletedObjects, orphan.ObjectKey)
}
for _, pending := range stale {
status, key, updatedAt, err := repository.AttachmentState(ctx, pending.ID)
if err != nil {
if errors.Is(err, store.ErrNotFound) {
result.Skipped = append(result.Skipped, pending.ObjectKey)
continue
}
result.Errors = append(result.Errors, "recheck "+pending.ID+": "+err.Error())
continue
}
if status != "pending" {
result.Skipped = append(result.Skipped, pending.ObjectKey)
continue
}
if time.Since(updatedAt) < grace {
// Defensive: the snapshot said stale, but the row is fresh now
// (a retried upload may have updated it). Never delete it.
result.Skipped = append(result.Skipped, pending.ObjectKey)
continue
}
// Delete the intent row first, then the object. The reverse order has
// a race: a concurrent MarkAttachmentReady could promote the row
// between Remove and DELETE, leaving a ready row whose bytes are gone.
// With this order a crash after the row delete leaves an orphan object
// that the next run removes after the grace period.
deleted, err := repository.DeleteAttachmentIfPending(ctx, pending.ID)
if err != nil {
result.Errors = append(result.Errors, "delete row "+pending.ID+": "+err.Error())
continue
}
if !deleted {
result.Skipped = append(result.Skipped, pending.ObjectKey)
continue
}
result.DeletedPendingRows = append(result.DeletedPendingRows, pending.ID)
if !pending.ObjectPresent {
continue
}
if err := objects.Remove(ctx, key); err != nil {
result.Errors = append(result.Errors, "delete orphaned object after row "+key+": "+err.Error())
continue
}
result.DeletedObjects = append(result.DeletedObjects, key)
}
}
func ageSeconds(now, then time.Time) int64 {
if then.IsZero() {
return -1
}
age := now.Sub(then)
if age < 0 {
return 0
}
return int64(age.Seconds())
}
func sortFindings(value *findings) {
sort.Slice(value.OrphanObjects, func(i, j int) bool { return value.OrphanObjects[i].ObjectKey < value.OrphanObjects[j].ObjectKey })
sort.Slice(value.ProtectedObjects, func(i, j int) bool { return value.ProtectedObjects[i].ObjectKey < value.ProtectedObjects[j].ObjectKey })
sort.Slice(value.MissingObjects, func(i, j int) bool { return value.MissingObjects[i].ObjectKey < value.MissingObjects[j].ObjectKey })
sort.Slice(value.StalePending, func(i, j int) bool { return value.StalePending[i].ObjectKey < value.StalePending[j].ObjectKey })
sort.Slice(value.ProtectedPending, func(i, j int) bool { return value.ProtectedPending[i].ObjectKey < value.ProtectedPending[j].ObjectKey })
}
+71
View File
@@ -0,0 +1,71 @@
// Command s3bootstrap creates the private attachment bucket idempotently and
// proves that the configured administrative credentials can use it. It is a
// one-shot compose service, separate from the API: API replicas never receive
// the administrative credentials and cannot create buckets.
package main
import (
"context"
"encoding/json"
"fmt"
"os"
"strconv"
"strings"
"time"
"mtusi.ru/messenger-lab4/internal/objectstore"
)
func main() {
endpoint := strings.TrimSpace(os.Getenv("S3_ENDPOINT"))
bucket := strings.TrimSpace(os.Getenv("S3_BUCKET"))
region := strings.TrimSpace(os.Getenv("S3_REGION"))
if region == "" {
region = "us-east-1"
}
accessKey := strings.TrimSpace(os.Getenv("S3_ADMIN_ACCESS_KEY"))
secretKey := strings.TrimSpace(os.Getenv("S3_ADMIN_SECRET_KEY"))
if endpoint == "" || bucket == "" || accessKey == "" || secretKey == "" {
fmt.Fprintln(os.Stderr, "s3bootstrap: S3_ENDPOINT, S3_BUCKET, S3_ADMIN_ACCESS_KEY and S3_ADMIN_SECRET_KEY are required")
os.Exit(2)
}
timeout := 30 * time.Second
if raw := strings.TrimSpace(os.Getenv("S3_TIMEOUT_SECONDS")); raw != "" {
seconds, err := strconv.Atoi(raw)
if err != nil || seconds < 5 || seconds > 120 {
fmt.Fprintln(os.Stderr, "s3bootstrap: S3_TIMEOUT_SECONDS must be an integer between 5 and 120")
os.Exit(2)
}
timeout = time.Duration(seconds) * time.Second
}
store, err := objectstore.Open(objectstore.Config{
Endpoint: endpoint,
Region: region,
Bucket: bucket,
AccessKey: accessKey,
SecretKey: secretKey,
Timeout: timeout,
})
if err != nil {
fmt.Fprintln(os.Stderr, "s3bootstrap: configuration error:", err)
os.Exit(2)
}
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
defer cancel()
created, err := store.EnsureBucket(ctx)
if err != nil {
fmt.Fprintln(os.Stderr, "s3bootstrap: bucket creation failed:", err)
os.Exit(1)
}
if err := store.Probe(ctx); err != nil {
fmt.Fprintln(os.Stderr, "s3bootstrap: credential/bucket probe failed:", err)
os.Exit(1)
}
result := map[string]any{
"bucket": bucket,
"created": created,
"verified": true,
}
encoded, _ := json.Marshal(result)
fmt.Println(string(encoded))
}
+134
View File
@@ -0,0 +1,134 @@
// Command s3ctl is a small operator/test helper for the private bucket. It is
// not part of the HTTP API: it uses the same restricted API credentials as the
// application and is used only to seed failure scenarios for the reconciler
// and to prove that anonymous access and cross-bucket access are denied.
package main
import (
"context"
"encoding/json"
"flag"
"fmt"
"os"
"time"
"mtusi.ru/messenger-lab4/internal/config"
"mtusi.ru/messenger-lab4/internal/objectstore"
)
func main() {
op := flag.String("op", "", "put, get, stat, delete or list")
key := flag.String("key", "", "object key")
file := flag.String("file", "", "file to upload for -op put")
contentType := flag.String("content-type", "application/octet-stream", "content type for -op put")
prefix := flag.String("prefix", "", "prefix for -op list")
bucketOverride := flag.String("bucket", "", "override the configured bucket (permission test)")
flag.Parse()
cfg, err := config.LoadTool()
if err != nil {
fmt.Fprintln(os.Stderr, "s3ctl: configuration error:", err)
os.Exit(2)
}
bucket := cfg.S3Bucket
if *bucketOverride != "" {
bucket = *bucketOverride
}
store, err := objectstore.Open(objectstore.Config{
Endpoint: cfg.S3Endpoint,
Region: cfg.S3Region,
Bucket: bucket,
AccessKey: cfg.S3AccessKey,
SecretKey: cfg.S3SecretKey,
Timeout: cfg.S3Timeout,
})
if err != nil {
fmt.Fprintln(os.Stderr, "s3ctl: configuration error:", err)
os.Exit(2)
}
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
defer cancel()
switch *op {
case "put":
if *key == "" || *file == "" {
fail("-op put requires -key and -file")
}
handle, err := os.Open(*file)
if err != nil {
fail("cannot open -file: " + err.Error())
}
defer handle.Close()
info, err := handle.Stat()
if err != nil {
fail("cannot stat -file: " + err.Error())
}
if err := store.Put(ctx, *key, handle, info.Size(), *contentType); err != nil {
fail("put failed: " + err.Error())
}
print(map[string]any{"operation": "put", "key": *key, "size_bytes": info.Size()})
case "delete":
if *key == "" {
fail("-op delete requires -key")
}
if err := store.Remove(ctx, *key); err != nil {
fail("delete failed: " + err.Error())
}
print(map[string]any{"operation": "delete", "key": *key})
case "stat":
if *key == "" {
fail("-op stat requires -key")
}
info, err := store.Stat(ctx, *key)
if err != nil {
fail("stat failed: " + err.Error())
}
print(map[string]any{"operation": "stat", "key": info.Key, "size_bytes": info.Size, "content_type": info.ContentType, "last_modified": info.LastModified.UTC().Format(time.RFC3339Nano)})
case "list":
items, err := store.List(ctx, *prefix)
if err != nil {
fail("list failed: " + err.Error())
}
keys := make([]map[string]any, 0, len(items))
for _, item := range items {
keys = append(keys, map[string]any{"key": item.Key, "size_bytes": item.Size, "last_modified": item.LastModified.UTC().Format(time.RFC3339Nano)})
}
print(map[string]any{"operation": "list", "bucket": bucket, "prefix": *prefix, "objects": keys})
case "get":
if *key == "" {
fail("-op get requires -key")
}
body, info, err := store.Get(ctx, *key)
if err != nil {
fail("get failed: " + err.Error())
}
defer body.Close()
buffer := make([]byte, 32*1024)
written := int64(0)
for {
n, readErr := body.Read(buffer)
if n > 0 {
if _, err := os.Stdout.Write(buffer[:n]); err != nil {
fail("write stdout failed")
}
written += int64(n)
}
if readErr != nil {
break
}
}
fmt.Fprintf(os.Stderr, "s3ctl: read %d of %d bytes\n", written, info.Size)
default:
fail("-op must be one of put, get, stat, delete or list")
}
}
func print(value any) {
encoded, _ := json.Marshal(value)
fmt.Println(string(encoded))
}
func fail(message string) {
fmt.Fprintln(os.Stderr, "s3ctl:", message)
os.Exit(1)
}
+320
View File
@@ -0,0 +1,320 @@
# Lab4 local teaching stand: client -> HAProxy -> 2+ interchangeable API
# processes -> shared PostgreSQL and Valkey, plus a private SeaweedFS S3 store.
#
# There is intentionally no container_name: a Compose service with fixed
# container names cannot be scaled. Every replica gets its own container ID,
# hostname and X-Instance-Id. Only HAProxy on 127.0.0.1:8084 is published;
# API, S3, SeaweedFS master/filer/volume and the admin surfaces stay on the
# internal backend network.
#
# Start: make env && make up
# Stop: make stop (processes stopped, named volumes and data preserved)
# Remove: make down (containers removed, volumes preserved)
# Purge: make purge (containers AND named volumes removed; explicit data loss)
name: ${COMPOSE_PROJECT_NAME:-mtusi-lab4-melnikov}
x-api-build: &api-build
context: .
args:
VERSION: ${APP_VERSION:-1.0.0}
REVISION: ${GIT_REVISION:-unknown}
x-s3-common: &s3-common
S3_ENDPOINT: http://s3:8333
S3_REGION: ${S3_REGION:-us-east-1}
S3_BUCKET: ${S3_BUCKET:-messenger-attachments}
S3_TIMEOUT_SECONDS: ${S3_TIMEOUT_SECONDS:-10}
services:
postgres:
image: postgres:16.4-alpine3.20@sha256:5660c2cbfea50c7a9127d17dc4e48543eedd3d7a41a595a2dfa572471e37e64c
environment:
POSTGRES_USER: ${POSTGRES_USER:-messenger}
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?set POSTGRES_PASSWORD in .env via make env}
POSTGRES_DB: ${POSTGRES_DB:-messenger}
PGDATA: /var/lib/postgresql/data/pgdata
command:
- postgres
- -c
- max_connections=100
- -c
- shared_buffers=128MB
- -c
- effective_cache_size=256MB
- -c
- work_mem=4MB
- -c
- maintenance_work_mem=64MB
- -c
- max_wal_size=4GB
- -c
- checkpoint_timeout=30min
- -c
- checkpoint_completion_target=0.9
volumes:
- pgdata:/var/lib/postgresql/data
networks:
- backend
healthcheck:
test: ["CMD-SHELL", "pg_isready -U $${POSTGRES_USER} -d $${POSTGRES_DB}"]
interval: 3s
timeout: 3s
retries: 20
start_period: 5s
restart: unless-stopped
security_opt:
- no-new-privileges:true
stop_grace_period: 20s
deploy:
resources:
limits:
cpus: "${POSTGRES_CPU_LIMIT:-0.5}"
memory: ${POSTGRES_MEM_LIMIT:-384M}
valkey:
image: valkey/valkey:8.0.2-alpine@sha256:752ba000a58bc8925d11ee863a39b5225617cd2cb3dbc9ec8ac65268b65ebb6d
environment:
VALKEY_PASSWORD: ${VALKEY_PASSWORD:?set VALKEY_PASSWORD in .env via make env}
# Shared session store. AOF everysec is the durability boundary: graceful
# restart keeps acknowledged sessions; a hard crash can lose up to one
# second of session writes. TTLs are absolute deadlines, so replaying the
# AOF neither revives nor extends a session.
command:
- valkey-server
- --appendonly
- "yes"
- --appendfsync
- everysec
- --requirepass
- ${VALKEY_PASSWORD:?set VALKEY_PASSWORD in .env via make env}
- --protected-mode
- "no"
volumes:
- valkeydata:/data
networks:
- backend
healthcheck:
test: ["CMD-SHELL", "valkey-cli --no-auth-warning -a \"$$VALKEY_PASSWORD\" ping | grep -q PONG"]
interval: 3s
timeout: 3s
retries: 20
start_period: 5s
restart: unless-stopped
security_opt:
- no-new-privileges:true
stop_grace_period: 20s
deploy:
resources:
limits:
cpus: "${VALKEY_CPU_LIMIT:-0.1}"
memory: ${VALKEY_MEM_LIMIT:-96M}
# One S3-compatible server (SeaweedFS) owns the original bytes. The image is
# pinned by tag and digest. The master/filer/volume/S3 ports stay unpublished;
# only the API reaches the private bucket over the backend network.
s3:
image: chrislusf/seaweedfs:3.98@sha256:2f7de737bd35c5e2cf93944e8aa66de802a135f068ea285d8d290d0206347d22
command:
- server
- -dir=/data
- -s3
- -s3.port=8333
- -s3.config=/etc/seaweedfs/s3.json
volumes:
- s3data:/data
# Generated locally by make env from .env; contains local synthetic
# credentials only and is ignored by Git.
- ./infra/seaweedfs-s3.json:/etc/seaweedfs/s3.json:ro
networks:
- backend
healthcheck:
# The master answers on 9333 before the S3 gateway on 8333 is ready.
# Probe the actual S3 port: any HTTP response (normally 403 for an
# anonymous root request) proves the gateway is listening.
test: ["CMD-SHELL", "wget -S -O /dev/null http://127.0.0.1:8333/ 2>&1 | grep -qE 'HTTP/[0-9.]+ (200|400|403)'"]
interval: 3s
timeout: 3s
retries: 30
start_period: 20s
restart: unless-stopped
security_opt:
- no-new-privileges:true
stop_grace_period: 20s
deploy:
resources:
limits:
cpus: "${S3_CPU_LIMIT:-0.4}"
memory: ${S3_MEM_LIMIT:-384M}
# One-shot, idempotent bucket bootstrap with the administrative SeaweedFS
# identity. The API never receives these credentials.
s3-init:
image: ${API_IMAGE:-mtusi-messenger-lab4-melnikov:local}
build: *api-build
entrypoint: ["/app/s3bootstrap"]
environment:
<<: *s3-common
S3_ADMIN_ACCESS_KEY: ${S3_ADMIN_ACCESS_KEY:?set S3_ADMIN_ACCESS_KEY in .env via make env}
S3_ADMIN_SECRET_KEY: ${S3_ADMIN_SECRET_KEY:?set S3_ADMIN_SECRET_KEY in .env via make env}
depends_on:
s3:
condition: service_healthy
networks:
- backend
# A stopped service alias must fail closed. Without an explicit search
# domain, the host's public search suffixes could turn the single-label
# name "s3" into a public host when the container is temporarily absent.
# "invalid" is reserved by RFC 2606 and always NXDOMAIN.
dns_search:
- invalid
restart: "no"
read_only: true
tmpfs:
- /tmp
security_opt:
- no-new-privileges:true
deploy:
resources:
limits:
cpus: "0.2"
memory: 64M
# One-shot migration runner. API replicas depend on this service completing,
# so the schema is never migrated by a race between replicas. The advisory
# lock and checksums make a repeated invocation safe.
migrate:
image: ${API_IMAGE:-mtusi-messenger-lab4-melnikov:local}
build: *api-build
entrypoint: ["/app/migrate"]
environment:
APP_ENV: ${APP_ENV:-lab}
LOG_LEVEL: ${LOG_LEVEL:-info}
DATABASE_URL: postgres://${POSTGRES_USER:-messenger}:${POSTGRES_PASSWORD:?set POSTGRES_PASSWORD in .env via make env}@postgres:5432/${POSTGRES_DB:-messenger}?sslmode=disable
DB_MAX_CONNS: "2"
DB_CONNECT_TIMEOUT_SECONDS: "3"
DB_STATEMENT_TIMEOUT_SECONDS: "10"
DB_QUERY_TIMEOUT_SECONDS: "10"
depends_on:
postgres:
condition: service_healthy
networks:
- backend
restart: "no"
read_only: true
security_opt:
- no-new-privileges:true
deploy:
resources:
limits:
cpus: "0.25"
memory: 128M
api:
image: ${API_IMAGE:-mtusi-messenger-lab4-melnikov:local}
build: *api-build
environment:
APP_HOST: 0.0.0.0
APP_PORT: "8080"
APP_ENV: ${APP_ENV:-lab}
LOG_LEVEL: ${LOG_LEVEL:-info}
DATABASE_URL: postgres://${POSTGRES_USER:-messenger}:${POSTGRES_PASSWORD:?set POSTGRES_PASSWORD in .env via make env}@postgres:5432/${POSTGRES_DB:-messenger}?sslmode=disable
CACHE_URL: redis://:${VALKEY_PASSWORD:?set VALKEY_PASSWORD in .env via make env}@valkey:6379/0
SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600}
DB_MAX_CONNS: ${DB_MAX_CONNS:-8}
DB_MIN_CONNS: ${DB_MIN_CONNS:-1}
DB_CONNECT_TIMEOUT_SECONDS: ${DB_CONNECT_TIMEOUT_SECONDS:-3}
DB_STATEMENT_TIMEOUT_SECONDS: ${DB_STATEMENT_TIMEOUT_SECONDS:-3}
DB_QUERY_TIMEOUT_SECONDS: ${DB_QUERY_TIMEOUT_SECONDS:-3}
CACHE_POOL_SIZE: ${CACHE_POOL_SIZE:-8}
CACHE_TIMEOUT_SECONDS: ${CACHE_TIMEOUT_SECONDS:-2}
SHUTDOWN_TIMEOUT_SECONDS: ${SHUTDOWN_TIMEOUT_SECONDS:-6}
SHUTDOWN_DRAIN_SECONDS: ${SHUTDOWN_DRAIN_SECONDS:-3}
STARTUP_TIMEOUT_SECONDS: ${STARTUP_TIMEOUT_SECONDS:-30}
METRICS_ADDR: 127.0.0.1:9090
GOMEMLIMIT: ${GOMEMLIMIT:-300MiB}
<<: *s3-common
S3_ACCESS_KEY: ${S3_API_ACCESS_KEY:?set S3_API_ACCESS_KEY in .env via make env}
S3_SECRET_KEY: ${S3_API_SECRET_KEY:?set S3_API_SECRET_KEY in .env via make env}
MAX_UPLOAD_BYTES: ${MAX_UPLOAD_BYTES:-10485760}
MAX_IMAGE_PIXELS: ${MAX_IMAGE_PIXELS:-40000000}
UPLOAD_DECODE_CONCURRENCY: ${UPLOAD_DECODE_CONCURRENCY:-1}
S3_PUT_CONCURRENCY: ${S3_PUT_CONCURRENCY:-1}
depends_on:
postgres:
condition: service_healthy
valkey:
condition: service_healthy
migrate:
condition: service_completed_successfully
s3-init:
condition: service_completed_successfully
networks:
- backend
# Same fail-closed DNS rule as s3-init: while S3 is stopped, "s3" must not
# fall through to a public search-domain host.
dns_search:
- invalid
healthcheck:
test: ["CMD", "/app/messenger", "-healthcheck"]
interval: 3s
timeout: 2s
retries: 12
start_period: 10s
restart: unless-stopped
read_only: true
tmpfs:
# Bounded scratch space for one upload in flight. It is an ephemeral
# staging area, never the source of truth for a ready attachment.
- /tmp:size=256m,mode=1777
security_opt:
- no-new-privileges:true
cap_drop:
- ALL
stop_grace_period: 15s
deploy:
replicas: ${API_REPLICAS:-2}
resources:
limits:
cpus: "${API_CPU_LIMIT:-0.5}"
memory: ${API_MEM_LIMIT:-384M}
lb:
image: haproxy:3.0-alpine@sha256:457d1c0dcbf2dfc0e0358723c07df4410d30e7de42bec036b383cfede4a5dbe3
volumes:
- ./infra/haproxy.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro
ports:
- "127.0.0.1:${LB_PORT:-8084}:8080"
networks:
- backend
healthcheck:
test: ["CMD-SHELL", "wget -q -O /dev/null http://127.0.0.1:8404/stats || exit 1"]
interval: 3s
timeout: 2s
retries: 10
start_period: 5s
restart: unless-stopped
read_only: true
tmpfs:
- /tmp
security_opt:
- no-new-privileges:true
cap_drop:
- ALL
stop_grace_period: 10s
deploy:
resources:
limits:
cpus: "${LB_CPU_LIMIT:-0.2}"
memory: ${LB_MEM_LIMIT:-64M}
volumes:
pgdata:
name: ${COMPOSE_PROJECT_NAME:-mtusi-lab4-melnikov}-pgdata
valkeydata:
name: ${COMPOSE_PROJECT_NAME:-mtusi-lab4-melnikov}-valkeydata
s3data:
name: ${COMPOSE_PROJECT_NAME:-mtusi-lab4-melnikov}-s3data
networks:
backend:
name: ${COMPOSE_PROJECT_NAME:-mtusi-lab4-melnikov}-net
+30
View File
@@ -0,0 +1,30 @@
module mtusi.ru/messenger-lab4
go 1.25.1
require (
github.com/jackc/pgx/v5 v5.7.2
github.com/jackc/puddle/v2 v2.2.2
github.com/minio/minio-go/v7 v7.0.82
github.com/redis/go-redis/v9 v9.7.0
golang.org/x/crypto v0.31.0
)
require (
github.com/cespare/xxhash/v2 v2.2.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.3 // indirect
github.com/google/uuid v1.6.0 // indirect
github.com/jackc/pgpassfile v1.0.0 // indirect
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
github.com/klauspost/compress v1.17.11 // indirect
github.com/klauspost/cpuid/v2 v2.2.8 // indirect
github.com/minio/md5-simd v1.1.2 // indirect
github.com/rs/xid v1.6.0 // indirect
golang.org/x/net v0.30.0 // indirect
golang.org/x/sync v0.10.0 // indirect
golang.org/x/sys v0.28.0 // indirect
golang.org/x/text v0.21.0 // indirect
)
+62
View File
@@ -0,0 +1,62 @@
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.2.0 h1:DC2CZ1Ep5Y4k3ZQ899DldepgrayRUGE6BBZ/cd9Cj44=
github.com/cespare/xxhash/v2 v2.2.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.3 h1:KZ5WoDbxAIgm2HNbYckL0se1fHD6rz5j4ywS6ebzDqA=
github.com/goccy/go-json v0.10.3/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.2 h1:mLoDLV6sonKlvjIEsV56SkWNCnuNv531l94GaIzO+XI=
github.com/jackc/pgx/v5 v5.7.2/go.mod h1:ncY89UGWxg82EykZUwSpUKEfccBGGYq1xjrOpsbsfGQ=
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.17.11 h1:In6xLpyWOi1+C7tXUUWv2ot1QvBjxevKAaI6IXrJmUc=
github.com/klauspost/compress v1.17.11/go.mod h1:pMDklpSncoRMuLFrf1W9Ss9KT+0rH90U12bZKk7uwG0=
github.com/klauspost/cpuid/v2 v2.0.1/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
github.com/klauspost/cpuid/v2 v2.2.8 h1:+StwCXwm9PdpiEkPyzBXIy+M9KUb4ODm0Zarf1kS5BM=
github.com/klauspost/cpuid/v2 v2.2.8/go.mod h1:Lcz8mBdAVJIBVzewtcLocK12l3Y+JytZYpaMropDUws=
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.82 h1:tWfICLhmp2aFPXL8Tli0XDTHj2VB/fNf0PC1f/i1gRo=
github.com/minio/minio-go/v7 v7.0.82/go.mod h1:84gmIilaX4zcvAWWzJ5Z1WI5axN+hAbM5w25xf8xvC0=
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.7.0 h1:HhLSs+B6O021gwzl+locl0zEDnyNkxMtf/Z3NNBMa9E=
github.com/redis/go-redis/v9 v9.7.0/go.mod h1:f6zhXITC7JUJIlPEiBOTXxJgPLdZcA93GewI7inzyWw=
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.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
golang.org/x/crypto v0.31.0 h1:ihbySMvVjLAeSH1IbfcRTkD/iNscyz8rGzjF/E5hV6U=
golang.org/x/crypto v0.31.0/go.mod h1:kDsLvtWBEx7MV9tJOj9bnXsPbxwJQ6csT/x4KIN4Ssk=
golang.org/x/net v0.30.0 h1:AcW1SDZMkb8IpzCdQUaIq2sP4sZ4zw+55h6ynffypl4=
golang.org/x/net v0.30.0/go.mod h1:2wGyMJ5iFasEhkwi13ChkO/t1ECNC4X4eBKkVFyYFlU=
golang.org/x/sync v0.10.0 h1:3NQrjDixjgGwUOCaF8w2+VYHv0Ve/vGYSbdkTa98gmQ=
golang.org/x/sync v0.10.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.28.0 h1:Fksou7UEQUWlKvIdsqzJmUmCX3cZuD2+P3XyyzwMhlA=
golang.org/x/sys v0.28.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/text v0.21.0 h1:zyQAAkrwaneQ066sspRyJaG9VNi/YJ1NfzcGB3hZ/qo=
golang.org/x/text v0.21.0/go.mod h1:4IBbMaMmOPCJ8SecivzSH54+73PCFmPWxNTLm+vZkEQ=
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=
+64
View File
@@ -0,0 +1,64 @@
# Lab3 public entrypoint. HAProxy discovers API replicas through Docker's
# embedded DNS and actively probes /health/ready. There is no sticky session:
# every request is balanced independently, and a backend that fails two
# consecutive probes is removed within roughly two probe intervals.
#
# The stats endpoint is bound to loopback inside the container only. It is not
# published and is used by the experiment scripts through `docker exec`.
global
log stdout format raw local0
maxconn 8192
stats socket /tmp/haproxy.sock mode 600 level admin
defaults
mode http
log global
option httplog
option dontlognull
# Per-request access logging is intentionally disabled: at thousands of
# requests per second it moves the LB bottleneck into stdout and hides the
# component under study. Errors are still logged.
option dontlog-normal
option redispatch
retries 2
timeout connect 1s
timeout client 15s
timeout server 15s
timeout http-request 5s
timeout http-keep-alive 5s
default-server inter 1s fastinter 500ms downinter 1s fall 2 rise 1
frontend public
bind :8080
mode http
default_backend api
backend api
mode http
balance roundrobin
option httpchk GET /health/ready
http-check expect status 200
# One template slot per A record returned for the compose service name.
# Docker DNS adds/removes records on scale/stop; `hold valid 1s` keeps the
# backend list current instead of caching the first resolution.
server-template api 1-10 api:8080 check resolvers docker init-addr none
resolvers docker
nameserver dns 127.0.0.11:53
resolve_retries 3
timeout resolve 1s
timeout retry 1s
hold valid 1s
hold refused 1s
hold nx 1s
hold timeout 1s
hold obsolete 1s
frontend stats
bind 127.0.0.1:8404
mode http
stats enable
stats uri /stats
stats refresh 1s
stats show-legends
+286
View File
@@ -0,0 +1,286 @@
package api
import (
"context"
"encoding/json"
"log/slog"
"net/http"
"strings"
"sync/atomic"
"time"
"mtusi.ru/messenger-lab4/internal/auth"
"mtusi.ru/messenger-lab4/internal/model"
"mtusi.ru/messenger-lab4/internal/objectstore"
"mtusi.ru/messenger-lab4/internal/session"
"mtusi.ru/messenger-lab4/internal/store"
)
const maxBodyBytes = 1 << 20 // far above the 4000-character message limit
type healthResponse struct {
Status string `json:"status"`
}
// identity is the authenticated principal derived only from the Bearer
// session. X-User-Id is not consulted anywhere in this package.
type identity struct {
user model.User
token string
}
// App is the HTTP layer. PostgreSQL is the source of truth for users, chats
// and messages; Valkey is the source of truth for sessions. App adds request
// validation, authentication and contract mapping.
type App struct {
store *store.Store
sessions *session.Store
objects *objectstore.Store
log *slog.Logger
ready atomic.Bool
maxBody int64
instanceID string
version string
startedAt time.Time
dummyHash string
maxUpload int64
maxPixels int64
tempDir string
decodeSem chan struct{}
putSem chan struct{}
createdMessages atomic.Uint64
replayedMessages atomic.Uint64
conflictMessages atomic.Uint64
}
// Options carries the upload limits and concurrency bound. Values are
// validated by config.Load before the application starts.
type Options struct {
MaxUploadBytes int64
MaxImagePixels int64
DecodeConcurrency int
PutConcurrency int
TempDir string
}
// New creates the HTTP application. The dummy Argon2id hash is generated once
// so login can spend the same work for an unknown username as for a known one.
func New(repository *store.Store, sessions *session.Store, objects *objectstore.Store, logger *slog.Logger, instanceID, version string, options Options) (*App, error) {
dummy, err := auth.Hash("dummy-password-never-used-for-login")
if err != nil {
return nil, err
}
if options.MaxUploadBytes <= 0 {
options.MaxUploadBytes = 10 * 1024 * 1024
}
if options.MaxImagePixels <= 0 {
options.MaxImagePixels = 40_000_000
}
if options.DecodeConcurrency <= 0 {
options.DecodeConcurrency = 1
}
if options.PutConcurrency <= 0 {
options.PutConcurrency = 1
}
app := &App{
store: repository,
sessions: sessions,
objects: objects,
log: logger,
maxBody: maxBodyBytes,
instanceID: instanceID,
version: version,
startedAt: time.Now(),
dummyHash: dummy,
maxUpload: options.MaxUploadBytes,
maxPixels: options.MaxImagePixels,
tempDir: options.TempDir,
decodeSem: make(chan struct{}, options.DecodeConcurrency),
putSem: make(chan struct{}, options.PutConcurrency),
}
app.ready.Store(true)
return app, nil
}
// SetReady flips readiness. The main process clears it as soon as SIGTERM is
// received and before http.Server.Shutdown stops accepting connections.
func (a *App) SetReady(ready bool) { a.ready.Store(ready) }
// Handler returns the fully instrumented handler.
func (a *App) Handler() http.Handler {
return a.withObservability(a)
}
// ServeHTTP routes the lab3 API. Method mismatches become 404 in the contract
// error shape because the public error enum has no method_not_allowed code.
func (a *App) ServeHTTP(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/health/live":
if r.Method != http.MethodGet {
a.notFound(w, r)
return
}
a.writeJSON(w, r, http.StatusOK, healthResponse{Status: "ok"})
case "/health/ready":
if r.Method != http.MethodGet {
a.notFound(w, r)
return
}
a.readiness(w, r)
case "/api/v1/users":
if r.Method != http.MethodPost {
a.notFound(w, r)
return
}
a.createUser(w, r)
case "/api/v1/auth/sessions":
if r.Method != http.MethodPost {
a.notFound(w, r)
return
}
a.createSession(w, r)
case "/api/v1/auth/sessions/current":
if r.Method != http.MethodDelete {
a.notFound(w, r)
return
}
a.withAuth(a.logout).ServeHTTP(w, r)
case "/api/v1/users/me":
if r.Method != http.MethodGet {
a.notFound(w, r)
return
}
a.withAuth(a.currentUser).ServeHTTP(w, r)
case "/api/v1/chats":
switch r.Method {
case http.MethodGet:
a.withAuth(a.listChats).ServeHTTP(w, r)
case http.MethodPost:
a.withAuth(a.createChat).ServeHTTP(w, r)
default:
a.notFound(w, r)
}
default:
if rest, ok := trimPathPrefix(r.URL.Path, "/api/v1/attachments/"); ok {
a.withAuth(func(w http.ResponseWriter, r *http.Request, actor identity) {
a.attachmentRoutes(w, r, rest, actor)
}).ServeHTTP(w, r)
return
}
if rest, ok := trimPathPrefix(r.URL.Path, "/api/v1/chats/"); ok {
// Authentication runs before resource resolution: an anonymous
// request must not learn whether a chat id exists.
a.withAuth(func(w http.ResponseWriter, r *http.Request, actor identity) {
a.chatRoutes(w, r, rest, actor)
}).ServeHTTP(w, r)
return
}
a.notFound(w, r)
}
}
func (a *App) chatRoutes(w http.ResponseWriter, r *http.Request, rest string, actor identity) {
parts := splitPath(rest)
if len(parts) == 1 {
if r.Method != http.MethodGet {
a.notFound(w, r)
return
}
a.getChat(w, r, parts[0], actor)
return
}
if len(parts) == 2 && parts[1] == "attachments" {
if r.Method != http.MethodPost {
a.notFound(w, r)
return
}
a.createAttachment(w, r, parts[0], actor)
return
}
if len(parts) == 2 && parts[1] == "messages" {
switch r.Method {
case http.MethodGet:
a.listMessages(w, r, parts[0], actor)
case http.MethodPost:
a.createMessage(w, r, parts[0], actor)
default:
a.notFound(w, r)
}
return
}
a.notFound(w, r)
}
// withAuth resolves the Bearer session before the wrapped handler runs.
func (a *App) withAuth(next func(http.ResponseWriter, *http.Request, identity)) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
actor, problem := a.authenticate(r)
if problem != nil {
a.writeError(w, r, problem)
return
}
next(w, r, actor)
}
}
// readiness reports whether the mandatory synchronous path can be served.
// Both PostgreSQL and Valkey are critical: without PostgreSQL the API cannot
// answer, and without Valkey it cannot authenticate a single protected call.
func (a *App) readiness(w http.ResponseWriter, r *http.Request) {
if !a.ready.Load() {
a.writeError(w, r, statusUnavailable)
return
}
dbCtx, dbCancel := context.WithTimeout(r.Context(), 900*time.Millisecond)
dbErr := a.store.Ping(dbCtx)
dbCancel()
if dbErr != nil {
a.log.Warn("readiness probe failed", "request_id", requestIDFromContext(r.Context()), "dependency", "postgres", "error", dbErr)
a.writeError(w, r, statusUnavailable)
return
}
cacheCtx, cacheCancel := context.WithTimeout(r.Context(), 900*time.Millisecond)
cacheErr := a.sessions.Ping(cacheCtx)
cacheCancel()
if cacheErr != nil {
a.log.Warn("readiness probe failed", "request_id", requestIDFromContext(r.Context()), "dependency", "valkey", "error", cacheErr)
a.writeError(w, r, statusUnavailable)
return
}
a.writeJSON(w, r, http.StatusOK, healthResponse{Status: "ok"})
}
// writeJSON encodes a success response. X-Request-Id is set by middleware
// before the handler runs, so even a marshal-time 500 keeps the header.
func (a *App) writeJSON(w http.ResponseWriter, r *http.Request, status int, value any) {
data, err := json.Marshal(value)
if err != nil {
a.log.Error("response encoding failed", "request_id", requestIDFromContext(r.Context()), "error", err)
a.writeError(w, r, statusInternal)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
if _, err := w.Write(data); err != nil {
a.log.Debug("response write failed", "request_id", requestIDFromContext(r.Context()), "error", err)
}
}
func trimPathPrefix(value, prefix string) (string, bool) {
if !strings.HasPrefix(value, prefix) || len(value) == len(prefix) {
return "", false
}
return value[len(prefix):], true
}
func splitPath(value string) []string {
parts := strings.Split(value, "/")
for _, part := range parts {
if part == "" {
return nil
}
}
return parts
}
+458
View File
@@ -0,0 +1,458 @@
package api
import (
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"image"
_ "image/jpeg" // register the JPEG decoder used by image.DecodeConfig/Decode
_ "image/png" // register the PNG decoder used by image.DecodeConfig/Decode
"io"
"mime"
"net/http"
"net/url"
"os"
"strconv"
"strings"
"syscall"
"time"
"unicode"
"unicode/utf8"
"mtusi.ru/messenger-lab4/internal/model"
"mtusi.ru/messenger-lab4/internal/objectstore"
"mtusi.ru/messenger-lab4/internal/store"
"mtusi.ru/messenger-lab4/internal/uuid"
)
const (
objectPrefix = "attachments/"
decodeWaitTimeout = 30 * time.Second
putWaitTimeout = 10 * time.Second
maxFilenameCodePoints = 255
imagePNG = "image/png"
imageJPEG = "image/jpeg"
attachmentStateReady = "ready"
attachmentStatePending = "pending"
maxImageDimensionProduct = int64(40_000_000)
)
// attachmentRoutes handles /api/v1/attachments/{id} and .../content. The
// caller has already been authenticated by withAuth.
func (a *App) attachmentRoutes(w http.ResponseWriter, r *http.Request, rest string, actor identity) {
parts := splitPath(rest)
if len(parts) == 1 {
if r.Method != http.MethodGet {
a.notFound(w, r)
return
}
a.getAttachment(w, r, parts[0], actor)
return
}
if len(parts) == 2 && parts[1] == "content" {
if r.Method != http.MethodGet {
a.notFound(w, r)
return
}
a.downloadAttachment(w, r, parts[0], actor)
return
}
a.notFound(w, r)
}
// createAttachment performs a synchronous binary upload. The body is streamed
// to a bounded temporary file while its SHA-256 is computed; the image is
// validated before any S3 or database write. Only a validated image can create
// a pending row, so an invalid request never leaves an accounted object behind.
func (a *App) createAttachment(w http.ResponseWriter, r *http.Request, rawChatID string, actor identity) {
chatID, problem := normalizePathUUID(rawChatID, "chat_id")
if problem != nil {
a.writeError(w, r, problem)
return
}
filename, problem := uploadFilename(r)
if problem != nil {
a.writeError(w, r, problem)
return
}
declared, problem := uploadMediaType(r)
if problem != nil {
a.writeError(w, r, problem)
return
}
member, err := a.store.IsChatMember(r.Context(), chatID, actor.user.ID)
if err != nil {
a.log.Error("attachment membership check failed", "request_id", requestIDFromContext(r.Context()), "error", err)
if errors.Is(err, store.ErrUnavailable) {
a.writeError(w, r, statusUnavailable)
return
}
a.writeError(w, r, statusInternal)
return
}
if !member {
a.writeError(w, r, statusNotFound)
return
}
if r.ContentLength > a.maxUpload {
a.writeError(w, r, statusPayloadTooLarge)
return
}
temp, err := os.CreateTemp(a.tempDir, "lab4-upload-*")
if err != nil {
a.log.Error("could not create upload temp file", "request_id", requestIDFromContext(r.Context()), "error", err)
a.writeError(w, r, statusUnavailable)
return
}
tempName := temp.Name()
defer func() {
_ = temp.Close()
_ = os.Remove(tempName)
}()
hasher := sha256.New()
body := http.MaxBytesReader(w, r.Body, a.maxUpload)
written, err := io.Copy(io.MultiWriter(temp, hasher), body)
if err != nil {
var tooLarge *http.MaxBytesError
switch {
case errors.As(err, &tooLarge):
a.writeError(w, r, statusPayloadTooLarge)
case errors.Is(err, syscall.ENOSPC):
a.log.Error("upload temp file is full", "request_id", requestIDFromContext(r.Context()))
a.writeError(w, r, statusUnavailable)
default:
a.writeError(w, r, invalidRequest("could not read the upload body"))
}
return
}
if written > a.maxUpload {
a.writeError(w, r, statusPayloadTooLarge)
return
}
if written == 0 {
a.writeError(w, r, unsupportedMediaType("the upload body is empty"))
return
}
detected, width, height, problem := a.validateImage(r.Context(), temp, declared)
if problem != nil {
a.writeError(w, r, problem)
return
}
sum := hex.EncodeToString(hasher.Sum(nil))
attachmentID := uuid.New()
objectKey := objectPrefix + attachmentID
createdAt := time.Now().UTC()
record := store.AttachmentRecord{
Attachment: model.Attachment{
ID: attachmentID,
ChatID: chatID,
OwnerID: actor.user.ID,
Filename: filename,
ContentType: detected,
SizeBytes: written,
SHA256: sum,
Status: attachmentStatePending,
Variants: []model.Variant{},
ErrorCode: nil,
CreatedAt: model.Time{Time: createdAt},
UpdatedAt: model.Time{Time: createdAt},
},
ObjectKey: objectKey,
}
if err := a.store.CreatePendingAttachment(r.Context(), record, createdAt); err != nil {
a.log.Error("could not record attachment intent", "request_id", requestIDFromContext(r.Context()), "error", err)
if errors.Is(err, store.ErrUnavailable) {
a.writeError(w, r, statusUnavailable)
return
}
a.writeError(w, r, statusInternal)
return
}
if _, err := temp.Seek(0, io.SeekStart); err != nil {
_ = a.store.DeleteAttachmentRow(context.Background(), attachmentID)
a.writeError(w, r, statusInternal)
return
}
// Bound the number of simultaneous object writes per API replica. A queued
// upload has already been streamed to a bounded temporary file and is not
// holding a decoded image, so waiting here does not add unbounded RAM.
select {
case a.putSem <- struct{}{}:
err = a.objects.Put(r.Context(), objectKey, temp, written, detected)
<-a.putSem
case <-time.After(putWaitTimeout):
a.compensatePending(attachmentID)
a.log.Warn("S3 upload queue timed out", "request_id", requestIDFromContext(r.Context()),
"attachment_id", attachmentID)
a.writeError(w, r, statusUnavailable)
return
case <-r.Context().Done():
a.compensatePending(attachmentID)
a.writeError(w, r, statusUnavailable)
return
}
if err != nil {
// Compensation for a failed PUT: the pending row is removed. If this
// best-effort delete also fails, the reconciler removes the stale row
// and any object after the grace period.
a.compensatePending(attachmentID)
a.log.Error("S3 upload failed", "request_id", requestIDFromContext(r.Context()), "attachment_id", attachmentID, "error", err)
if errors.Is(err, objectstore.ErrUnavailable) || errors.Is(err, objectstore.ErrNotFound) {
a.writeError(w, r, statusUnavailable)
return
}
a.writeError(w, r, statusInternal)
return
}
updatedAt, err := a.store.MarkAttachmentReady(r.Context(), attachmentID, time.Now().UTC())
if err != nil {
// The object and the pending row are both durable. Never delete the
// object here: an ambiguous COMMIT could have promoted the row already,
// and deleting a ready original is worse than a reconciler pass.
a.log.Error("could not promote attachment after S3 upload", "request_id", requestIDFromContext(r.Context()), "attachment_id", attachmentID, "error", err)
if errors.Is(err, store.ErrUnavailable) {
a.writeError(w, r, statusUnavailable)
return
}
a.writeError(w, r, statusInternal)
return
}
record.Status = attachmentStateReady
record.UpdatedAt = model.Time{Time: updatedAt}
a.log.Info("attachment ready",
"request_id", requestIDFromContext(r.Context()),
"attachment_id", attachmentID,
"chat_id", chatID,
"size_bytes", written,
"content_type", detected,
"image_width", width,
"image_height", height,
)
a.writeJSON(w, r, http.StatusCreated, record.Attachment)
}
// compensatePending removes the upload intent after a failed or abandoned S3
// write. A failed best-effort delete is intentionally left to the reconciler:
// deleting a possibly committed row here would be worse than a stale pending row.
func (a *App) compensatePending(attachmentID string) {
cleanupCtx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
_ = a.store.DeleteAttachmentRow(cleanupCtx, attachmentID)
cancel()
}
// validateImage applies every content rule before S3 or PostgreSQL is touched.
// The declared media type must match the bytes; the decoded pixel count is
// checked from the header before a potentially large full decode.
func (a *App) validateImage(ctx context.Context, temp *os.File, declared string) (detected string, width, height int, problem *apiError) {
if _, err := temp.Seek(0, io.SeekStart); err != nil {
return "", 0, 0, statusInternal
}
header := make([]byte, 512)
n, err := io.ReadFull(temp, header)
if err != nil && !errors.Is(err, io.ErrUnexpectedEOF) {
return "", 0, 0, unsupportedMediaType("the upload body is not a valid image")
}
detected = http.DetectContentType(header[:n])
if detected != imagePNG && detected != imageJPEG {
return "", 0, 0, unsupportedMediaType("only PNG and JPEG images are accepted")
}
if declared != detected {
return "", 0, 0, unsupportedMediaType("Content-Type does not match the image bytes")
}
if _, err := temp.Seek(0, io.SeekStart); err != nil {
return "", 0, 0, statusInternal
}
config, format, err := image.DecodeConfig(temp)
if err != nil || (format != "png" && format != "jpeg") {
return "", 0, 0, unsupportedMediaType("the image header is corrupt or unsupported")
}
if config.Width < 1 || config.Height < 1 {
return "", 0, 0, unsupportedMediaType("the image has invalid dimensions")
}
pixels := int64(config.Width) * int64(config.Height)
if pixels > a.maxPixels || pixels > maxImageDimensionProduct {
return "", 0, 0, statusPayloadTooLarge
}
select {
case a.decodeSem <- struct{}{}:
defer func() { <-a.decodeSem }()
case <-time.After(decodeWaitTimeout):
return "", 0, 0, statusUnavailable
case <-ctx.Done():
return "", 0, 0, statusUnavailable
}
if _, err := temp.Seek(0, io.SeekStart); err != nil {
return "", 0, 0, statusInternal
}
decoded, _, err := image.Decode(temp)
if err != nil {
return "", 0, 0, unsupportedMediaType("the image is corrupt or truncated")
}
bounds := decoded.Bounds()
if bounds.Dx() < 1 || bounds.Dy() < 1 {
return "", 0, 0, unsupportedMediaType("the image has invalid dimensions")
}
return detected, bounds.Dx(), bounds.Dy(), nil
}
// uploadMediaType parses the declared Content-Type strictly. Parameters are
// accepted; any other media type is rejected before the body is read.
func uploadMediaType(r *http.Request) (string, *apiError) {
raw := strings.TrimSpace(r.Header.Get("Content-Type"))
if raw == "" {
return "", unsupportedMediaType("Content-Type must be image/png or image/jpeg")
}
mediaType, _, err := mime.ParseMediaType(raw)
if err != nil || (mediaType != imagePNG && mediaType != imageJPEG) {
return "", unsupportedMediaType("Content-Type must be image/png or image/jpeg")
}
return mediaType, nil
}
// uploadFilename validates the display-only filename query parameter. The
// value is never used as a path or an object key.
func uploadFilename(r *http.Request) (string, *apiError) {
query, err := url.ParseQuery(r.URL.RawQuery)
if err != nil {
return "", invalidRequest("query string is not valid")
}
values, present := query["filename"]
if !present || len(values) != 1 || values[0] == "" {
return "", invalidRequest("filename query parameter is required exactly once")
}
name := values[0]
if !utf8.ValidString(name) {
return "", invalidRequest("filename must be valid UTF-8")
}
if count := utf8.RuneCountInString(name); count < 1 || count > maxFilenameCodePoints {
return "", invalidRequest("filename must contain 1 to 255 Unicode code points")
}
if name == "." || name == ".." {
return "", invalidRequest("filename must not be a path component")
}
for _, char := range name {
if char == '/' || char == '\\' || char == 0 || unicode.IsControl(char) {
return "", invalidRequest("filename must not contain path separators, NUL or control characters")
}
}
return name, nil
}
func (a *App) getAttachment(w http.ResponseWriter, r *http.Request, rawID string, actor identity) {
attachmentID, problem := normalizePathUUID(rawID, "attachment_id")
if problem != nil {
a.writeError(w, r, problem)
return
}
record, err := a.store.ReadyAttachmentForUser(r.Context(), attachmentID, actor.user.ID)
if err != nil {
switch {
case errors.Is(err, store.ErrNotFound):
a.writeError(w, r, statusNotFound)
case errors.Is(err, store.ErrUnavailable):
a.log.Error("attachment metadata lookup failed", "request_id", requestIDFromContext(r.Context()), "error", err)
a.writeError(w, r, statusUnavailable)
default:
a.log.Error("attachment metadata lookup failed", "request_id", requestIDFromContext(r.Context()), "error", err)
a.writeError(w, r, statusInternal)
}
return
}
// The object is the source of truth for existence. A row whose bytes are
// gone must not be presented as a ready attachment.
if _, err := a.objects.Stat(r.Context(), record.ObjectKey); err != nil {
switch {
case errors.Is(err, objectstore.ErrNotFound):
a.writeError(w, r, statusNotFound)
case errors.Is(err, objectstore.ErrUnavailable):
a.log.Error("attachment object stat failed", "request_id", requestIDFromContext(r.Context()), "error", err)
a.writeError(w, r, statusUnavailable)
default:
a.log.Error("attachment object stat failed", "request_id", requestIDFromContext(r.Context()), "error", err)
a.writeError(w, r, statusInternal)
}
return
}
a.writeJSON(w, r, http.StatusOK, record.Attachment)
}
func (a *App) downloadAttachment(w http.ResponseWriter, r *http.Request, rawID string, actor identity) {
attachmentID, problem := normalizePathUUID(rawID, "attachment_id")
if problem != nil {
a.writeError(w, r, problem)
return
}
if problem := requireOriginalVariant(r); problem != nil {
a.writeError(w, r, problem)
return
}
record, err := a.store.ReadyAttachmentForUser(r.Context(), attachmentID, actor.user.ID)
if err != nil {
switch {
case errors.Is(err, store.ErrNotFound):
a.writeError(w, r, statusNotFound)
case errors.Is(err, store.ErrUnavailable):
a.log.Error("attachment download lookup failed", "request_id", requestIDFromContext(r.Context()), "error", err)
a.writeError(w, r, statusUnavailable)
default:
a.log.Error("attachment download lookup failed", "request_id", requestIDFromContext(r.Context()), "error", err)
a.writeError(w, r, statusInternal)
}
return
}
body, info, err := a.objects.Get(r.Context(), record.ObjectKey)
if err != nil {
switch {
case errors.Is(err, objectstore.ErrNotFound):
a.writeError(w, r, statusNotFound)
case errors.Is(err, objectstore.ErrUnavailable):
a.log.Error("attachment object read failed", "request_id", requestIDFromContext(r.Context()), "error", err)
a.writeError(w, r, statusUnavailable)
default:
a.log.Error("attachment object read failed", "request_id", requestIDFromContext(r.Context()), "error", err)
a.writeError(w, r, statusInternal)
}
return
}
defer body.Close()
w.Header().Set("Content-Type", record.ContentType)
w.Header().Set("Content-Length", strconv.FormatInt(info.Size, 10))
w.Header().Set("X-Content-Type-Options", "nosniff")
w.Header().Set("Cache-Control", "private, no-store")
w.WriteHeader(http.StatusOK)
if _, err := io.Copy(w, body); err != nil {
a.log.Warn("attachment stream interrupted", "request_id", requestIDFromContext(r.Context()), "attachment_id", attachmentID, "error", err)
}
}
// requireOriginalVariant accepts the optional variant parameter but lab4 has
// only the original. An unknown variant of a ready object is 404.
func requireOriginalVariant(r *http.Request) *apiError {
query, err := url.ParseQuery(r.URL.RawQuery)
if err != nil {
return invalidRequest("query string is not valid")
}
values, present := query["variant"]
if !present {
return nil
}
if len(values) != 1 || values[0] == "" {
return invalidRequest("variant must be a non-empty string")
}
if values[0] == "original" {
return nil
}
return statusNotFound
}
+137
View File
@@ -0,0 +1,137 @@
package api
import (
"errors"
"net/http"
"mtusi.ru/messenger-lab4/internal/cursor"
"mtusi.ru/messenger-lab4/internal/store"
"mtusi.ru/messenger-lab4/internal/uuid"
)
type createChatRequest struct {
Title *string `json:"title"`
MemberIDs []string `json:"member_ids"`
}
func (a *App) createChat(w http.ResponseWriter, r *http.Request, actor identity) {
var request createChatRequest
if problem := a.decodeJSON(r, &request, "title", "member_ids"); problem != nil {
a.writeError(w, r, problem)
return
}
if request.Title == nil {
a.writeError(w, r, invalidRequest("title is required"))
return
}
if problem := validateTitle(*request.Title); problem != nil {
a.writeError(w, r, problem)
return
}
if len(request.MemberIDs) < 1 || len(request.MemberIDs) > 100 {
a.writeError(w, r, invalidRequest("member_ids must contain 1 to 100 members"))
return
}
members := make([]string, 0, len(request.MemberIDs))
seen := make(map[string]struct{}, len(request.MemberIDs))
callerIncluded := false
for _, rawID := range request.MemberIDs {
id, ok := uuid.Normalize(rawID)
if !ok {
a.writeError(w, r, invalidRequest("every member_ids entry must be a UUID"))
return
}
if _, duplicate := seen[id]; duplicate {
a.writeError(w, r, invalidRequest("member_ids must not contain duplicates"))
return
}
seen[id] = struct{}{}
members = append(members, id)
if id == actor.user.ID {
callerIncluded = true
}
}
if !callerIncluded {
a.writeError(w, r, invalidRequest("caller must be present in member_ids"))
return
}
chat, err := a.store.CreateChat(r.Context(), *request.Title, members, actor.user.ID)
switch {
case errors.Is(err, store.ErrUnknownMember):
a.writeError(w, r, invalidRequest("every member_ids entry must reference an existing user"))
return
case errors.Is(err, store.ErrUnavailable):
a.log.Error("create chat failed", "request_id", requestIDFromContext(r.Context()), "error", err)
a.writeError(w, r, statusUnavailable)
return
case err != nil:
a.log.Error("create chat failed", "request_id", requestIDFromContext(r.Context()), "error", err)
a.writeError(w, r, statusInternal)
return
}
a.writeJSON(w, r, http.StatusCreated, chat)
}
func (a *App) listChats(w http.ResponseWriter, r *http.Request, actor identity) {
limit, rawCursor, problem := a.pageParams(r)
if problem != nil {
a.writeError(w, r, problem)
return
}
var position *cursor.Cursor
if rawCursor != "" {
decoded, err := cursor.Decode(rawCursor, cursor.ScopeChats, "")
if err != nil {
a.writeError(w, r, invalidRequest("cursor is invalid for this request"))
return
}
position = &decoded
}
page, err := a.store.Chats(r.Context(), actor.user.ID, position, limit)
if err != nil {
if errors.Is(err, store.ErrUnavailable) {
a.log.Error("list chats failed", "request_id", requestIDFromContext(r.Context()), "error", err)
a.writeError(w, r, statusUnavailable)
return
}
a.log.Error("list chats failed", "request_id", requestIDFromContext(r.Context()), "error", err)
a.writeError(w, r, statusInternal)
return
}
a.writeJSON(w, r, http.StatusOK, page)
}
func (a *App) getChat(w http.ResponseWriter, r *http.Request, rawChatID string, actor identity) {
chatID, problem := normalizePathUUID(rawChatID, "chat_id")
if problem != nil {
a.writeError(w, r, problem)
return
}
chat, err := a.store.ChatForUser(r.Context(), chatID, actor.user.ID)
switch {
case errors.Is(err, store.ErrNotFound):
a.writeError(w, r, statusNotFound)
return
case errors.Is(err, store.ErrUnavailable):
a.log.Error("get chat failed", "request_id", requestIDFromContext(r.Context()), "error", err)
a.writeError(w, r, statusUnavailable)
return
case err != nil:
a.log.Error("get chat failed", "request_id", requestIDFromContext(r.Context()), "error", err)
a.writeError(w, r, statusInternal)
return
}
a.writeJSON(w, r, http.StatusOK, chat)
}
// normalizePathUUID validates a path identifier before any database access.
func normalizePathUUID(raw, field string) (string, *apiError) {
id, ok := uuid.Normalize(raw)
if !ok {
return "", invalidRequest(field + " must be a UUID")
}
return id, nil
}
+184
View File
@@ -0,0 +1,184 @@
package api
import (
"context"
"log/slog"
"net/http"
"sync/atomic"
"time"
"mtusi.ru/messenger-lab4/internal/uuid"
)
// apiError is a contract-shaped error: HTTP status, machine-readable code, a
// safe human-readable message and an optional authentication challenge. The
// request id is filled from the request context at write time.
type apiError struct {
status int
code string
message string
challenge string
}
func (e *apiError) Error() string { return e.code + ": " + e.message }
const (
basicChallenge = `Basic realm="messenger", charset="UTF-8"`
bearerChallenge = `Bearer realm="messenger"`
)
var (
statusInvalidRequest = &apiError{status: http.StatusBadRequest, code: "invalid_request", message: "request validation failed"}
statusNotFound = &apiError{status: http.StatusNotFound, code: "not_found", message: "object not found"}
statusConflict = &apiError{status: http.StatusConflict, code: "conflict", message: "object already exists"}
statusPayloadTooLarge = &apiError{status: http.StatusRequestEntityTooLarge, code: "payload_too_large", message: "request body is too large"}
statusUnsupportedMediaType = &apiError{status: http.StatusUnsupportedMediaType, code: "unsupported_media_type", message: "Content-Type must be application/json"}
statusUnavailable = &apiError{status: http.StatusServiceUnavailable, code: "unavailable", message: "a required dependency is unavailable"}
statusInternal = &apiError{status: http.StatusInternalServerError, code: "internal_error", message: "internal server error"}
)
func invalidRequest(message string) *apiError {
return &apiError{status: http.StatusBadRequest, code: "invalid_request", message: message}
}
func conflict(message string) *apiError {
return &apiError{status: http.StatusConflict, code: "conflict", message: message}
}
func unsupportedMediaType(message string) *apiError {
return &apiError{status: http.StatusUnsupportedMediaType, code: "unsupported_media_type", message: message}
}
func unauthorizedBasic() *apiError {
return &apiError{status: http.StatusUnauthorized, code: "unauthorized", message: "invalid username or password", challenge: basicChallenge}
}
func unauthorizedBearer() *apiError {
return &apiError{status: http.StatusUnauthorized, code: "unauthorized", message: "a valid bearer session is required", challenge: bearerChallenge}
}
type errorEnvelope struct {
Error errorBody `json:"error"`
}
type errorBody struct {
Code string `json:"code"`
Message string `json:"message"`
RequestID string `json:"request_id"`
}
// writeError writes a JSON error whose request_id matches X-Request-Id. The
// message never contains SQL, stack traces, credentials or object existence
// details for foreign resources.
func (a *App) writeError(w http.ResponseWriter, r *http.Request, problem *apiError) {
requestID := requestIDFromContext(r.Context())
if requestID == "" {
requestID = w.Header().Get("X-Request-Id")
}
if requestID == "" {
requestID = uuid.NewRandom(16)
w.Header().Set("X-Request-Id", requestID)
}
if problem.challenge != "" {
w.Header().Set("WWW-Authenticate", problem.challenge)
}
a.writeJSON(w, r, problem.status, errorEnvelope{Error: errorBody{
Code: problem.code,
Message: problem.message,
RequestID: requestID,
}})
}
func (a *App) notFound(w http.ResponseWriter, r *http.Request) {
a.writeError(w, r, statusNotFound)
}
type requestIDContextKey struct{}
func requestIDFromContext(ctx context.Context) string {
value, _ := ctx.Value(requestIDContextKey{}).(string)
return value
}
// statusWriter records the status code and byte count for logs and for the
// panic path, so a partially written response is not written twice.
type statusWriter struct {
http.ResponseWriter
status int
bytes int
wrote bool
}
func (w *statusWriter) WriteHeader(code int) {
if w.wrote {
return
}
w.wrote = true
w.status = code
w.ResponseWriter.WriteHeader(code)
}
func (w *statusWriter) Write(data []byte) (int, error) {
if !w.wrote {
w.WriteHeader(http.StatusOK)
}
written, err := w.ResponseWriter.Write(data)
w.bytes += written
return written, err
}
func (a *App) withObservability(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
requestID := uuid.NewRandom(16)
w.Header().Set("X-Request-Id", requestID)
// Stable for the life of the process and unique per container. lab3
// uses the container hostname: it is the actual process identity, so
// stop-one can map a response to exactly one container. lab7 will
// replace it with an opaque alias.
w.Header().Set("X-Instance-Id", a.instanceID)
// Extra, non-contract header used only to observe an image replacement
// during the rolling-update experiment. The mandatory contract does
// not define or require it.
w.Header().Set("X-App-Version", a.version)
r = r.WithContext(context.WithValue(r.Context(), requestIDContextKey{}, requestID))
writer := &statusWriter{ResponseWriter: w, status: http.StatusOK}
defer func() {
if recovered := recover(); recovered != nil {
a.log.Error("panic while handling request",
"request_id", requestID,
"instance_id", a.instanceID,
"method", r.Method,
"path", r.URL.Path,
"panic", recovered,
)
if !writer.wrote {
a.writeError(writer, r, statusInternal)
}
}
level := slog.LevelInfo
if r.URL.Path == "/health/live" || r.URL.Path == "/health/ready" {
level = slog.LevelDebug
}
a.log.Log(r.Context(), level, "http request",
"request_id", requestID,
"instance_id", a.instanceID,
"method", r.Method,
"path", r.URL.Path,
"status", writer.status,
"duration_ms", float64(time.Since(start).Microseconds())/1000.0,
"bytes", writer.bytes,
)
}()
next.ServeHTTP(writer, r)
})
}
// atomicBool keeps the readiness flag readable from the signal goroutine
// without importing sync/atomic into every handler file.
type atomicBool struct{ value atomic.Bool }
func (b *atomicBool) Store(value bool) { b.value.Store(value) }
func (b *atomicBool) Load() bool { return b.value.Load() }
+213
View File
@@ -0,0 +1,213 @@
package api
import (
"bytes"
"crypto/sha256"
"encoding/json"
"errors"
"net/http"
"unicode/utf8"
"mtusi.ru/messenger-lab4/internal/cursor"
"mtusi.ru/messenger-lab4/internal/store"
"mtusi.ru/messenger-lab4/internal/uuid"
)
const maxMessageAttachments = 10
type createMessageRequest struct {
Text *string `json:"text"`
AttachmentIDs json.RawMessage `json:"attachment_ids"`
}
// messageHash is the canonical semantic body used for idempotency. A missing
// attachment_ids is normalised to [], exactly as the contract requires, and
// JSON object key order never affects the hash. Array order is preserved: the
// response also preserves it.
type messageHashBody struct {
Text string `json:"text"`
AttachmentIDs []string `json:"attachment_ids"`
}
func (a *App) createMessage(w http.ResponseWriter, r *http.Request, rawChatID string, actor identity) {
chatID, problem := normalizePathUUID(rawChatID, "chat_id")
if problem != nil {
a.writeError(w, r, problem)
return
}
// The key is validated before the body, but after authentication and path
// validation: a malformed/missing key is always 400, while an outsider
// still cannot learn anything by replaying someone else's key.
idempotencyKey, problem := idempotencyKey(r)
if problem != nil {
a.writeError(w, r, problem)
return
}
// Resource access is checked before the body is decoded so a foreign chat
// always looks like a missing chat, independent of the submitted payload.
member, err := a.store.IsChatMember(r.Context(), chatID, actor.user.ID)
if err != nil {
if errors.Is(err, store.ErrUnavailable) {
a.log.Error("membership check failed", "request_id", requestIDFromContext(r.Context()), "error", err)
a.writeError(w, r, statusUnavailable)
return
}
a.log.Error("membership check failed", "request_id", requestIDFromContext(r.Context()), "error", err)
a.writeError(w, r, statusInternal)
return
}
if !member {
a.writeError(w, r, statusNotFound)
return
}
var request createMessageRequest
if problem := a.decodeJSON(r, &request, "text", "attachment_ids"); problem != nil {
a.writeError(w, r, problem)
return
}
if request.Text == nil {
a.writeError(w, r, invalidRequest("text is required"))
return
}
attachmentIDs, problem := parseAttachmentIDs(request.AttachmentIDs)
if problem != nil {
a.writeError(w, r, problem)
return
}
if utf8.RuneCountInString(*request.Text) > 4000 {
a.writeError(w, r, invalidRequest("text must contain at most 4000 Unicode code points"))
return
}
if isBlank(*request.Text) && len(attachmentIDs) == 0 {
a.writeError(w, r, invalidRequest("text must not be blank without attachments"))
return
}
canonical, err := json.Marshal(messageHashBody{Text: *request.Text, AttachmentIDs: attachmentIDs})
if err != nil {
a.writeError(w, r, statusInternal)
return
}
hash := sha256.Sum256(canonical)
message, replayed, err := a.store.CreateMessageIdempotent(
r.Context(), chatID, actor.user.ID, http.MethodPost, messagePath(chatID),
idempotencyKey, hash[:], *request.Text, attachmentIDs,
)
switch {
case errors.Is(err, store.ErrIdempotencyConflict):
a.conflictMessages.Add(1)
a.writeError(w, r, statusConflict)
return
case errors.Is(err, store.ErrAttachmentNotReady):
a.writeError(w, r, conflict("attachment is not ready"))
return
case errors.Is(err, store.ErrNotFound):
a.writeError(w, r, statusNotFound)
return
case errors.Is(err, store.ErrUnavailable):
a.log.Error("create message failed", "request_id", requestIDFromContext(r.Context()), "error", err)
a.writeError(w, r, statusUnavailable)
return
case err != nil:
a.log.Error("create message failed", "request_id", requestIDFromContext(r.Context()), "error", err)
a.writeError(w, r, statusInternal)
return
}
if replayed {
a.replayedMessages.Add(1)
} else {
a.createdMessages.Add(1)
}
a.writeJSON(w, r, http.StatusCreated, message)
}
// parseAttachmentIDs accepts an absent field as [], rejects null and every
// wrong JSON type, and enforces the UUID / uniqueness / count rules before any
// database access.
func parseAttachmentIDs(raw json.RawMessage) ([]string, *apiError) {
if len(bytes.TrimSpace(raw)) == 0 {
return []string{}, nil
}
if bytes.Equal(bytes.TrimSpace(raw), []byte("null")) {
return nil, invalidRequest("attachment_ids must be an array, not null")
}
var values []string
if err := json.Unmarshal(raw, &values); err != nil {
return nil, invalidRequest("attachment_ids must be an array of UUID strings")
}
if len(values) > maxMessageAttachments {
return nil, invalidRequest("attachment_ids must contain at most 10 items")
}
result := make([]string, 0, len(values))
seen := make(map[string]struct{}, len(values))
for _, value := range values {
id, ok := uuid.Normalize(value)
if !ok {
return nil, invalidRequest("every attachment_ids entry must be a UUID")
}
if _, duplicate := seen[id]; duplicate {
return nil, invalidRequest("attachment_ids must not contain duplicates")
}
seen[id] = struct{}{}
result = append(result, id)
}
return result, nil
}
func messagePath(chatID string) string {
return "/api/v1/chats/" + chatID + "/messages"
}
func (a *App) listMessages(w http.ResponseWriter, r *http.Request, rawChatID string, actor identity) {
chatID, problem := normalizePathUUID(rawChatID, "chat_id")
if problem != nil {
a.writeError(w, r, problem)
return
}
// A foreign/nonexistent chat is always 404, even if the query itself is
// malformed; this avoids making object existence observable.
member, err := a.store.IsChatMember(r.Context(), chatID, actor.user.ID)
if err != nil {
if errors.Is(err, store.ErrUnavailable) {
a.log.Error("membership check failed", "request_id", requestIDFromContext(r.Context()), "error", err)
a.writeError(w, r, statusUnavailable)
return
}
a.log.Error("membership check failed", "request_id", requestIDFromContext(r.Context()), "error", err)
a.writeError(w, r, statusInternal)
return
}
if !member {
a.writeError(w, r, statusNotFound)
return
}
limit, rawCursor, problem := a.pageParams(r)
if problem != nil {
a.writeError(w, r, problem)
return
}
var position *cursor.Cursor
if rawCursor != "" {
decoded, err := cursor.Decode(rawCursor, cursor.ScopeMessages, chatID)
if err != nil {
a.writeError(w, r, invalidRequest("cursor is invalid for this chat"))
return
}
position = &decoded
}
page, err := a.store.Messages(r.Context(), chatID, position, limit)
if err != nil {
if errors.Is(err, store.ErrUnavailable) {
a.log.Error("list messages failed", "request_id", requestIDFromContext(r.Context()), "error", err)
a.writeError(w, r, statusUnavailable)
return
}
a.log.Error("list messages failed", "request_id", requestIDFromContext(r.Context()), "error", err)
a.writeError(w, r, statusInternal)
return
}
a.writeJSON(w, r, http.StatusOK, page)
}
+91
View File
@@ -0,0 +1,91 @@
package api
import (
"encoding/json"
"net/http"
"runtime"
"time"
)
// InternalStats is the operator-only JSON document served on the loopback
// metrics listener inside each API container. It is deliberately not part of
// the public contract and is never routed through the load balancer; the
// experiment scripts read it with `docker exec` to attribute saturation to
// the connection pool versus PostgreSQL/CPU.
type InternalStats struct {
InstanceID string `json:"instance_id"`
Version string `json:"version"`
UptimeSeconds float64 `json:"uptime_seconds"`
Pool poolStats `json:"pool"`
Messages messageCounters `json:"messages"`
Runtime runtimeStats `json:"runtime"`
CollectedAt string `json:"collected_at"`
}
type poolStats struct {
MaxConns int32 `json:"max_conns"`
TotalConns int32 `json:"total_conns"`
AcquiredConns int32 `json:"acquired_conns"`
IdleConns int32 `json:"idle_conns"`
EmptyAcquireCount int64 `json:"empty_acquire_count"`
CanceledAcquireCount int64 `json:"canceled_acquire_count"`
AcquireCount int64 `json:"acquire_count"`
AcquireDurationMillis int64 `json:"acquire_duration_ms_total"`
NewConnsCount int64 `json:"new_conns_count"`
MaxLifetimeDestroyCount int64 `json:"max_lifetime_destroy_count"`
MaxIdleDestroyCount int64 `json:"max_idle_destroy_count"`
}
type messageCounters struct {
Created uint64 `json:"created"`
Replayed uint64 `json:"replayed"`
Conflicts uint64 `json:"conflicts"`
}
type runtimeStats struct {
Goroutines int `json:"goroutines"`
HeapAlloc uint64 `json:"heap_alloc_bytes"`
HeapSys uint64 `json:"heap_sys_bytes"`
TotalAlloc uint64 `json:"total_alloc_bytes"`
}
// InternalStatsHandler serves one snapshot. It is mounted only on the
// 127.0.0.1 listener started by cmd/messenger.
func (a *App) InternalStatsHandler(w http.ResponseWriter, _ *http.Request) {
pool := a.store.PoolStats()
var memory runtime.MemStats
runtime.ReadMemStats(&memory)
stats := InternalStats{
InstanceID: a.instanceID,
Version: a.version,
UptimeSeconds: time.Since(a.startedAt).Seconds(),
Pool: poolStats{
MaxConns: pool.MaxConns,
TotalConns: pool.TotalConns,
AcquiredConns: pool.AcquiredConns,
IdleConns: pool.IdleConns,
EmptyAcquireCount: pool.EmptyAcquireCount,
CanceledAcquireCount: pool.CanceledAcquireCount,
AcquireCount: pool.AcquireCount,
AcquireDurationMillis: pool.AcquireDurationMillis,
NewConnsCount: pool.NewConnsCount,
MaxLifetimeDestroyCount: pool.MaxLifetimeDestroyCount,
MaxIdleDestroyCount: pool.MaxIdleDestroyCount,
},
Messages: messageCounters{
Created: a.createdMessages.Load(),
Replayed: a.replayedMessages.Load(),
Conflicts: a.conflictMessages.Load(),
},
Runtime: runtimeStats{
Goroutines: runtime.NumGoroutine(),
HeapAlloc: memory.HeapAlloc,
HeapSys: memory.HeapSys,
TotalAlloc: memory.TotalAlloc,
},
CollectedAt: time.Now().UTC().Format(time.RFC3339Nano),
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
_ = json.NewEncoder(w).Encode(stats)
}
+157
View File
@@ -0,0 +1,157 @@
package api
import (
"errors"
"net/http"
"strings"
"unicode/utf8"
"mtusi.ru/messenger-lab4/internal/auth"
"mtusi.ru/messenger-lab4/internal/model"
"mtusi.ru/messenger-lab4/internal/session"
"mtusi.ru/messenger-lab4/internal/store"
)
// createSession is the only endpoint that accepts Basic credentials. It never
// accepts a JSON body and never reveals whether the username exists.
func (a *App) createSession(w http.ResponseWriter, r *http.Request) {
username, password, err := auth.ParseBasic(r.Header.Get("Authorization"))
if err != nil {
a.writeError(w, r, unauthorizedBasic())
return
}
// Reject values that could never have been registered before touching the
// database (invalid UTF-8 would otherwise become a 500 from PostgreSQL).
if !usernameAllowed(username) || !validLoginPassword(password) {
_, _ = auth.Verify(password, a.dummyHash)
a.writeError(w, r, unauthorizedBasic())
return
}
user, passwordHash, err := a.store.UserByUsername(r.Context(), username)
switch {
case errors.Is(err, store.ErrNotFound):
// Spend the same KDF work for an unknown username so response timing
// does not disclose account existence.
_, _ = auth.Verify(password, a.dummyHash)
a.writeError(w, r, unauthorizedBasic())
return
case errors.Is(err, store.ErrUnavailable):
a.log.Error("login database unavailable", "request_id", requestIDFromContext(r.Context()), "error", err)
a.writeError(w, r, statusUnavailable)
return
case err != nil:
a.log.Error("login lookup failed", "request_id", requestIDFromContext(r.Context()), "error", err)
a.writeError(w, r, statusInternal)
return
}
match, err := auth.Verify(password, passwordHash)
if err != nil {
// A corrupt stored hash is an internal data problem, not a wrong
// password; do not silently lock the account out with a 401 log line.
a.log.Error("stored password hash is invalid", "request_id", requestIDFromContext(r.Context()), "error", err)
a.writeError(w, r, statusInternal)
return
}
if !match {
a.writeError(w, r, unauthorizedBasic())
return
}
token, expiresAt, err := a.sessions.Create(r.Context(), user.ID)
if err != nil {
a.log.Error("session creation failed", "request_id", requestIDFromContext(r.Context()), "error", err)
if errors.Is(err, session.ErrUnavailable) {
a.writeError(w, r, statusUnavailable)
return
}
a.writeError(w, r, statusInternal)
return
}
a.writeJSON(w, r, http.StatusCreated, model.Session{
Token: token,
TokenType: "Bearer",
ExpiresAt: model.Time{Time: expiresAt},
User: user,
})
}
// authenticate accepts only "Authorization: Bearer <opaque token>". A Basic
// header on a business endpoint, a missing header and an X-User-Id header all
// produce the same 401 challenge.
func (a *App) authenticate(r *http.Request) (identity, *apiError) {
token, ok := bearerToken(r.Header.Get("Authorization"))
if !ok || !auth.ValidTokenShape(token) {
return identity{}, unauthorizedBearer()
}
userID, err := a.sessions.Get(r.Context(), token)
switch {
case errors.Is(err, session.ErrInvalid):
return identity{}, unauthorizedBearer()
case errors.Is(err, session.ErrUnavailable):
a.log.Error("session lookup failed", "request_id", requestIDFromContext(r.Context()), "error", err)
return identity{}, statusUnavailable
case err != nil:
a.log.Error("session lookup failed", "request_id", requestIDFromContext(r.Context()), "error", err)
return identity{}, statusInternal
}
user, err := a.store.UserByID(r.Context(), userID)
switch {
case errors.Is(err, store.ErrNotFound):
// A session pointing at a missing user is not usable. Deleting it is
// best effort; the response is the normal 401 either way.
_ = a.sessions.Delete(r.Context(), token)
return identity{}, unauthorizedBearer()
case errors.Is(err, store.ErrUnavailable):
a.log.Error("user lookup failed", "request_id", requestIDFromContext(r.Context()), "error", err)
return identity{}, statusUnavailable
case err != nil:
a.log.Error("user lookup failed", "request_id", requestIDFromContext(r.Context()), "error", err)
return identity{}, statusInternal
}
return identity{user: user, token: token}, nil
}
// logout revokes the current server-side session. The response has no body.
func (a *App) logout(w http.ResponseWriter, r *http.Request, actor identity) {
if err := a.sessions.Delete(r.Context(), actor.token); err != nil {
a.log.Error("logout failed", "request_id", requestIDFromContext(r.Context()), "error", err)
if errors.Is(err, session.ErrUnavailable) {
a.writeError(w, r, statusUnavailable)
return
}
a.writeError(w, r, statusInternal)
return
}
w.WriteHeader(http.StatusNoContent)
}
func bearerToken(header string) (string, bool) {
trimmed := strings.TrimSpace(header)
space := strings.IndexByte(trimmed, ' ')
if space <= 0 {
return "", false
}
if !strings.EqualFold(trimmed[:space], "Bearer") {
return "", false
}
token := trimmed[space+1:]
if token == "" || strings.ContainsAny(token, " \t") {
return "", false
}
return token, true
}
// validLoginPassword mirrors the registration policy. A login with an
// out-of-range password cannot match any stored hash and must still look like
// an ordinary 401.
func validLoginPassword(password string) bool {
if !utf8.ValidString(password) || isBlank(password) {
return false
}
count := utf8.RuneCountInString(password)
return count >= 12 && count <= 128
}
+74
View File
@@ -0,0 +1,74 @@
package api
import (
"errors"
"net/http"
"mtusi.ru/messenger-lab4/internal/auth"
"mtusi.ru/messenger-lab4/internal/store"
)
type createUserRequest struct {
Username *string `json:"username"`
DisplayName *string `json:"display_name"`
Password *string `json:"password"`
}
func (a *App) createUser(w http.ResponseWriter, r *http.Request) {
var request createUserRequest
if problem := a.decodeJSON(r, &request, "username", "display_name", "password"); problem != nil {
a.writeError(w, r, problem)
return
}
if request.Username == nil {
a.writeError(w, r, invalidRequest("username is required"))
return
}
if request.DisplayName == nil {
a.writeError(w, r, invalidRequest("display_name is required"))
return
}
if request.Password == nil {
a.writeError(w, r, invalidRequest("password is required"))
return
}
if problem := validateUsername(*request.Username); problem != nil {
a.writeError(w, r, problem)
return
}
if problem := validateDisplayName(*request.DisplayName); problem != nil {
a.writeError(w, r, problem)
return
}
if problem := validatePassword(*request.Password); problem != nil {
a.writeError(w, r, problem)
return
}
passwordHash, err := auth.Hash(*request.Password)
if err != nil {
a.log.Error("password hashing failed", "request_id", requestIDFromContext(r.Context()), "error", err)
a.writeError(w, r, statusInternal)
return
}
user, err := a.store.CreateUser(r.Context(), *request.Username, *request.DisplayName, passwordHash)
switch {
case errors.Is(err, store.ErrUsernameTaken):
a.writeError(w, r, statusConflict)
return
case errors.Is(err, store.ErrUnavailable):
a.log.Error("create user failed", "request_id", requestIDFromContext(r.Context()), "error", err)
a.writeError(w, r, statusUnavailable)
return
case err != nil:
a.log.Error("create user failed", "request_id", requestIDFromContext(r.Context()), "error", err)
a.writeError(w, r, statusInternal)
return
}
a.writeJSON(w, r, http.StatusCreated, user)
}
func (a *App) currentUser(w http.ResponseWriter, r *http.Request, actor identity) {
a.writeJSON(w, r, http.StatusOK, actor.user)
}
+236
View File
@@ -0,0 +1,236 @@
package api
import (
"bytes"
"encoding/json"
"errors"
"io"
"mime"
"net/http"
"net/url"
"strconv"
"strings"
"unicode/utf8"
)
// decodeJSON enforces the contract's JSON rules: application/json, strict
// UTF-8, exactly one object with exactly the documented top-level keys, no
// unknown/duplicate fields and a bounded body size.
//
// encoding/json matches struct fields case-insensitively even with
// DisallowUnknownFields, so the exact key set is checked separately on the
// token stream. That also rejects Unicode case-folding aliases and duplicates.
func (a *App) decodeJSON(r *http.Request, destination any, allowedKeys ...string) *apiError {
if raw := r.Header.Get("Content-Type"); raw != "" {
mediaType, _, err := mime.ParseMediaType(raw)
if err != nil || mediaType != "application/json" {
return statusUnsupportedMediaType
}
}
body, err := io.ReadAll(io.LimitReader(r.Body, a.maxBody+1))
if err != nil {
return invalidRequest("could not read request body")
}
if int64(len(body)) > a.maxBody {
return statusPayloadTooLarge
}
if len(bytes.TrimSpace(body)) == 0 {
return invalidRequest("request body must not be empty")
}
if !utf8.Valid(body) {
return invalidRequest("request body must be valid UTF-8")
}
if problem := validateTopLevelKeys(body, allowedKeys); problem != nil {
return problem
}
decoder := json.NewDecoder(bytes.NewReader(body))
decoder.DisallowUnknownFields()
if err := decoder.Decode(destination); err != nil {
return invalidRequest("request body does not match the documented schema")
}
var extra any
if err := decoder.Decode(&extra); !errors.Is(err, io.EOF) {
return invalidRequest("request body must contain exactly one JSON value")
}
return nil
}
func validateTopLevelKeys(body []byte, allowedKeys []string) *apiError {
allowed := make(map[string]struct{}, len(allowedKeys))
for _, key := range allowedKeys {
allowed[key] = struct{}{}
}
decoder := json.NewDecoder(bytes.NewReader(body))
token, err := decoder.Token()
if err != nil {
return invalidRequest("request body must be valid JSON")
}
opening, ok := token.(json.Delim)
if !ok || opening != '{' {
return invalidRequest("request body must be a JSON object")
}
seen := make(map[string]struct{}, len(allowedKeys))
for decoder.More() {
token, err := decoder.Token()
if err != nil {
return invalidRequest("request body must be valid JSON")
}
key, ok := token.(string)
if !ok {
return invalidRequest("request body must contain string field names")
}
if _, duplicate := seen[key]; duplicate {
return invalidRequest("request body must not contain duplicate fields")
}
seen[key] = struct{}{}
if _, ok := allowed[key]; !ok {
return invalidRequest("request body contains an unknown field")
}
var value json.RawMessage
if err := decoder.Decode(&value); err != nil {
return invalidRequest("request body must be valid JSON")
}
}
if _, err := decoder.Token(); err != nil {
return invalidRequest("request body must be valid JSON")
}
var extra any
if err := decoder.Decode(&extra); !errors.Is(err, io.EOF) {
return invalidRequest("request body must contain exactly one JSON value")
}
return nil
}
// pageParams parses limit/cursor. Cursor decoding happens after membership is
// verified so a foreign chat cannot be probed with a malformed cursor.
func (a *App) pageParams(r *http.Request) (int, string, *apiError) {
query, err := url.ParseQuery(r.URL.RawQuery)
if err != nil {
return 0, "", invalidRequest("query string is not valid")
}
limit := 50
if values, present := query["limit"]; present {
if len(values) != 1 {
return 0, "", invalidRequest("limit must be specified once")
}
parsed, err := strconv.Atoi(values[0])
if err != nil || parsed < 1 || parsed > 100 {
return 0, "", invalidRequest("limit must be an integer between 1 and 100")
}
limit = parsed
}
cursor := ""
if values, present := query["cursor"]; present {
if len(values) != 1 || values[0] == "" {
return 0, "", invalidRequest("cursor must be a non-empty string")
}
cursor = values[0]
}
return limit, cursor, nil
}
func validateUsername(value string) *apiError {
if !usernameAllowed(value) {
return invalidRequest("username must match [a-z0-9_]{3,32}")
}
return nil
}
func validateDisplayName(value string) *apiError {
if isBlank(value) {
return invalidRequest("display_name must not be blank")
}
if count := utf8.RuneCountInString(value); count < 1 || count > 100 {
return invalidRequest("display_name must contain 1 to 100 Unicode code points")
}
return nil
}
func validateTitle(value string) *apiError {
if isBlank(value) {
return invalidRequest("title must not be blank")
}
if count := utf8.RuneCountInString(value); count < 1 || count > 100 {
return invalidRequest("title must contain 1 to 100 Unicode code points")
}
return nil
}
func validateMessageText(value string) *apiError {
if isBlank(value) {
return invalidRequest("text must not be blank")
}
if count := utf8.RuneCountInString(value); count < 1 || count > 4000 {
return invalidRequest("text must contain 1 to 4000 Unicode code points")
}
return nil
}
// validatePassword implements the registration rule: 12 to 128 Unicode code
// points, not only whitespace. The exact bytes are handed to Argon2id, so
// Unicode passwords are neither truncated nor normalized by the server.
func validatePassword(value string) *apiError {
if !utf8.ValidString(value) {
return invalidRequest("password must be valid UTF-8")
}
if isBlank(value) {
return invalidRequest("password must not be blank")
}
if count := utf8.RuneCountInString(value); count < 12 || count > 128 {
return invalidRequest("password must contain 12 to 128 Unicode code points")
}
return nil
}
func isBlank(value string) bool {
return strings.TrimSpace(value) == ""
}
// usernameAllowed is a byte-wise equivalent of the contract pattern
// ^[a-z0-9_]{3,32}$; non-ASCII bytes can never match.
func usernameAllowed(value string) bool {
if len(value) < 3 || len(value) > 32 {
return false
}
for i := 0; i < len(value); i++ {
c := value[i]
if (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '_' {
continue
}
return false
}
return true
}
// idempotencyKey enforces the contract's header rule exactly:
// ASCII [A-Za-z0-9._:-]{1,128}, present exactly once. No trimming: whitespace
// is outside the permitted alphabet, so a value with surrounding spaces is
// rejected rather than silently normalised into a different scope.
func idempotencyKey(r *http.Request) (string, *apiError) {
values := r.Header.Values("Idempotency-Key")
if len(values) != 1 {
return "", invalidRequest("Idempotency-Key header is required exactly once")
}
key := values[0]
if len(key) < 1 || len(key) > 128 {
return "", invalidRequest("Idempotency-Key must contain 1 to 128 ASCII characters")
}
for i := 0; i < len(key); i++ {
c := key[i]
switch {
case c >= 'A' && c <= 'Z':
case c >= 'a' && c <= 'z':
case c >= '0' && c <= '9':
case c == '.' || c == '_' || c == ':' || c == '-':
default:
return "", invalidRequest("Idempotency-Key may contain only A-Z a-z 0-9 . _ : -")
}
}
return key, nil
}
+203
View File
@@ -0,0 +1,203 @@
package api
import (
"bytes"
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
)
type sampleRequest struct {
Username *string `json:"username"`
DisplayName *string `json:"display_name"`
Password *string `json:"password"`
}
func decodeTestApp() *App { return &App{maxBody: maxBodyBytes} }
func TestDecodeJSONAcceptsDocumentedObject(t *testing.T) {
app := decodeTestApp()
body := `{"username":"alice","display_name":"Алиса","password":"long-enough-secret"}`
request := httptest.NewRequest(http.MethodPost, "/api/v1/users", strings.NewReader(body))
request.Header.Set("Content-Type", "application/json; charset=utf-8")
var destination sampleRequest
if problem := app.decodeJSON(request, &destination, "username", "display_name", "password"); problem != nil {
t.Fatalf("decodeJSON rejected a valid body: %v", problem)
}
if destination.Username == nil || *destination.Username != "alice" {
t.Fatalf("decoded value = %+v", destination)
}
}
func TestDecodeJSONRejectsContractViolations(t *testing.T) {
app := decodeTestApp()
cases := []struct {
name string
body string
contentType string
status int
}{
{"empty", "", "application/json", http.StatusBadRequest},
{"whitespace only", " \n", "application/json", http.StatusBadRequest},
{"malformed", `{"username":`, "application/json", http.StatusBadRequest},
{"array instead of object", `[]`, "application/json", http.StatusBadRequest},
{"string instead of object", `"x"`, "application/json", http.StatusBadRequest},
{"unknown field", `{"username":"a","display_name":"b","password":"c","extra":1}`, "application/json", http.StatusBadRequest},
{"duplicate field", `{"username":"a","username":"b","display_name":"c","password":"d"}`, "application/json", http.StatusBadRequest},
{"uppercase alias", `{"Username":"a","display_name":"b","password":"c"}`, "application/json", http.StatusBadRequest},
{"alias beside correct key", `{"username":"a","Username":"b","display_name":"c","password":"d"}`, "application/json", http.StatusBadRequest},
{"wrong type", `{"username":1,"display_name":"b","password":"c"}`, "application/json", http.StatusBadRequest},
{"two values", `{"username":"a","display_name":"b","password":"c"}{}`, "application/json", http.StatusBadRequest},
{"wrong content type", `{"username":"a","display_name":"b","password":"c"}`, "text/plain", http.StatusUnsupportedMediaType},
{"malformed content type", `{"username":"a","display_name":"b","password":"c"}`, "application/json; charset", http.StatusUnsupportedMediaType},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
request := httptest.NewRequest(http.MethodPost, "/api/v1/users", strings.NewReader(tc.body))
request.Header.Set("Content-Type", tc.contentType)
var destination sampleRequest
problem := app.decodeJSON(request, &destination, "username", "display_name", "password")
if problem == nil {
t.Fatal("decodeJSON accepted an invalid body")
}
if problem.status != tc.status {
t.Fatalf("status = %d, want %d", problem.status, tc.status)
}
})
}
}
func TestDecodeJSONRejectsInvalidUTF8(t *testing.T) {
app := decodeTestApp()
body := append([]byte(`{"username":"`), 0xff, 0xfe)
body = append(body, []byte(`","display_name":"b","password":"c"}`)...)
request := httptest.NewRequest(http.MethodPost, "/api/v1/users", bytes.NewReader(body))
request.Header.Set("Content-Type", "application/json")
var destination sampleRequest
if problem := app.decodeJSON(request, &destination, "username", "display_name", "password"); problem == nil || problem.status != http.StatusBadRequest {
t.Fatalf("invalid UTF-8 was not rejected with 400: %v", problem)
}
}
func TestDecodeJSONRejectsOversizedBody(t *testing.T) {
app := decodeTestApp()
app.maxBody = 16
request := httptest.NewRequest(http.MethodPost, "/api/v1/users", strings.NewReader(`{"username":"`+strings.Repeat("x", 64)+`"}`))
request.Header.Set("Content-Type", "application/json")
var destination sampleRequest
if problem := app.decodeJSON(request, &destination, "username"); problem == nil || problem.status != http.StatusRequestEntityTooLarge {
t.Fatalf("oversized body = %v, want 413", problem)
}
}
func TestUsernameValidation(t *testing.T) {
valid := []string{"abc", "a_b9", strings.Repeat("a", 32)}
for _, value := range valid {
if problem := validateUsername(value); problem != nil {
t.Fatalf("validateUsername(%q) = %v", value, problem)
}
}
invalid := []string{"", "ab", strings.Repeat("a", 33), "Alice", "a-b", "a b", "aбв", "abc\n"}
for _, value := range invalid {
if problem := validateUsername(value); problem == nil {
t.Fatalf("validateUsername accepted %q", value)
}
}
}
func TestLengthValidationCountsCodePoints(t *testing.T) {
if problem := validateDisplayName(strings.Repeat("😀", 100)); problem != nil {
t.Fatalf("100 code points rejected: %v", problem)
}
if problem := validateDisplayName(strings.Repeat("😀", 101)); problem == nil {
t.Fatal("101 code points accepted")
}
if problem := validateDisplayName(" "); problem == nil {
t.Fatal("blank display_name accepted")
}
if problem := validateMessageText(strings.Repeat("я", 4000)); problem != nil {
t.Fatalf("4000 code points rejected: %v", problem)
}
if problem := validateMessageText(strings.Repeat("я", 4001)); problem == nil {
t.Fatal("4001 code points accepted")
}
if problem := validateMessageText(" \t\n"); problem == nil {
t.Fatal("blank message accepted")
}
if problem := validatePassword(strings.Repeat("p", 12)); problem != nil {
t.Fatalf("12-character password rejected: %v", problem)
}
if problem := validatePassword(strings.Repeat("p", 11)); problem == nil {
t.Fatal("11-character password accepted")
}
if problem := validatePassword(strings.Repeat("p", 128)); problem != nil {
t.Fatalf("128-character password rejected: %v", problem)
}
if problem := validatePassword(strings.Repeat("p", 129)); problem == nil {
t.Fatal("129-character password accepted")
}
if problem := validatePassword(strings.Repeat(" ", 12)); problem == nil {
t.Fatal("whitespace password accepted")
}
}
func TestPageParams(t *testing.T) {
valid := map[string][2]any{
"": {50, ""},
"?limit=1": {1, ""},
"?limit=100": {100, ""},
"?limit=7&cursor=x": {7, "x"},
}
for query, want := range valid {
request := httptest.NewRequest(http.MethodGet, "/api/v1/chats"+query, nil)
limit, cursor, problem := decodeTestApp().pageParams(request)
if problem != nil {
t.Fatalf("pageParams(%q) = %v", query, problem)
}
if limit != want[0].(int) || cursor != want[1].(string) {
t.Fatalf("pageParams(%q) = %d,%q", query, limit, cursor)
}
}
invalid := []string{"?limit=0", "?limit=101", "?limit=abc", "?limit=", "?limit=1&limit=2", "?cursor=", "?cursor=a&cursor=b", "?limit=1;cursor=x"}
for _, query := range invalid {
request := httptest.NewRequest(http.MethodGet, "/api/v1/chats"+query, nil)
if _, _, problem := decodeTestApp().pageParams(request); problem == nil {
t.Fatalf("pageParams accepted %q", query)
}
}
}
func TestBearerTokenParsing(t *testing.T) {
token := strings.Repeat("a", 43)
cases := map[string]string{
"Bearer " + token: token,
"bearer " + token: token,
"BEARER " + token: token,
}
for header, want := range cases {
got, ok := bearerToken(header)
if !ok || got != want {
t.Fatalf("bearerToken(%q) = %q,%v", header, got, ok)
}
}
for _, header := range []string{"", "Bearer", "Bearer ", "Basic abc", "Bearer a b", "Token " + token} {
if _, ok := bearerToken(header); ok {
t.Fatalf("bearerToken accepted %q", header)
}
}
}
func TestErrorEnvelopeShape(t *testing.T) {
envelope := errorEnvelope{Error: errorBody{Code: "invalid_request", Message: "x", RequestID: "id"}}
data, err := json.Marshal(envelope)
if err != nil {
t.Fatal(err)
}
if string(data) != `{"error":{"code":"invalid_request","message":"x","request_id":"id"}}` {
t.Fatalf("unexpected error JSON: %s", data)
}
}
+156
View File
@@ -0,0 +1,156 @@
package auth
import (
"encoding/base64"
"strings"
"testing"
)
func TestHashAndVerify(t *testing.T) {
password := "correct horse battery staple"
encoded, err := Hash(password)
if err != nil {
t.Fatalf("Hash: %v", err)
}
if !strings.HasPrefix(encoded, "$argon2id$v=19$m=19456,t=2,p=1$") {
t.Fatalf("unexpected PHC prefix: %q", encoded)
}
match, err := Verify(password, encoded)
if err != nil || !match {
t.Fatalf("Verify(correct) = %v, %v", match, err)
}
match, err = Verify(password+"x", encoded)
if err != nil || match {
t.Fatalf("Verify(wrong) = %v, %v", match, err)
}
}
func TestHashUnicodeAndMaximumLength(t *testing.T) {
for _, password := range []string{
"pässwörd:12✓",
strings.Repeat("界", 128),
" leading and trailing spaces ",
} {
encoded, err := Hash(password)
if err != nil {
t.Fatalf("Hash(%q): %v", password, err)
}
if match, err := Verify(password, encoded); err != nil || !match {
t.Fatalf("Verify(%q) = %v, %v", password, match, err)
}
}
}
func TestHashUsesRandomSalt(t *testing.T) {
first, err := Hash("same-password-twice")
if err != nil {
t.Fatal(err)
}
second, err := Hash("same-password-twice")
if err != nil {
t.Fatal(err)
}
if first == second {
t.Fatal("two hashes of the same password are identical")
}
}
func TestVerifyRejectsMalformedHashes(t *testing.T) {
for _, encoded := range []string{
"",
"plaintext",
"$2a$10$abcdefghijklmnopqrstuv",
"$argon2id$v=19$m=19456,t=2,p=1$not-base64$hash",
"$argon2id$v=19$m=1,t=3,p=2$c2FsdHNhbHQ$aGFzaGhhc2hoYXNoaGFzaA",
"$argon2id$v=19$m=19456,t=2,p=1$c2FsdA$aGFzaA",
} {
if _, err := Verify("password", encoded); err == nil {
t.Fatalf("Verify accepted malformed hash %q", encoded)
}
}
}
func TestParseBasic(t *testing.T) {
cases := []struct {
name string
raw string
username string
password string
ok bool
}{
{
name: "ordinary",
raw: "Basic " + base64.StdEncoding.EncodeToString([]byte("alice:secret")),
username: "alice",
password: "secret",
ok: true,
},
{
name: "password contains colon and UTF-8",
raw: "bAsIc " + base64.StdEncoding.EncodeToString([]byte("alice:pässwörd:with:colons")),
username: "alice",
password: "pässwörd:with:colons",
ok: true,
},
{
name: "unpadded base64",
raw: "Basic " + base64.RawStdEncoding.EncodeToString([]byte("alice:secret")),
username: "alice",
password: "secret",
ok: true,
},
{name: "no scheme", raw: "alice:secret"},
{name: "wrong scheme", raw: "Bearer abc"},
{name: "no space", raw: "Basic" + base64.StdEncoding.EncodeToString([]byte("alice:secret"))},
{name: "bad base64", raw: "Basic !!!"},
{name: "no separator", raw: "Basic " + base64.StdEncoding.EncodeToString([]byte("alice"))},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
username, password, err := ParseBasic(tc.raw)
if !tc.ok {
if err == nil {
t.Fatalf("ParseBasic accepted %q", tc.raw)
}
return
}
if err != nil {
t.Fatalf("ParseBasic: %v", err)
}
if username != tc.username || password != tc.password {
t.Fatalf("got %q/%q, want %q/%q", username, password, tc.username, tc.password)
}
})
}
}
func TestTokenProperties(t *testing.T) {
first, err := NewToken()
if err != nil {
t.Fatal(err)
}
second, err := NewToken()
if err != nil {
t.Fatal(err)
}
if first == second {
t.Fatal("tokens are not unique")
}
if len(first) != 43 {
t.Fatalf("token length = %d, want 43 (256 bits)", len(first))
}
if !ValidTokenShape(first) {
t.Fatal("issued token fails its own shape check")
}
if TokenHash(first) == TokenHash(second) {
t.Fatal("token hashes collide")
}
if len(TokenHash(first)) != 64 {
t.Fatalf("token hash length = %d", len(TokenHash(first)))
}
for _, bad := range []string{"", "short", "has space in it", strings.Repeat("a", 129), "abc+/="} {
if ValidTokenShape(bad) {
t.Fatalf("ValidTokenShape accepted %q", bad)
}
}
}
+90
View File
@@ -0,0 +1,90 @@
// Package auth implements the lab3 credential primitives: a library password
// KDF (Argon2id), opaque session tokens and RFC 7617 Basic parsing. None of
// these helpers log or serialise the secret material they receive.
package auth
import (
"crypto/rand"
"crypto/subtle"
"encoding/base64"
"errors"
"fmt"
"strings"
"golang.org/x/crypto/argon2"
)
// Argon2id parameters. 19 MiB / 2 passes / 1 lane is the OWASP password
// storage minimum for Argon2id, chosen so eight concurrent registrations fit
// inside the 256 MiB API container limit. The parameters are stored in every
// PHC string, so a future change remains backward compatible.
const (
argonMemory uint32 = 19 * 1024 // KiB
argonIterations uint32 = 2
argonParallelism uint8 = 1
argonSaltLength = 16
argonKeyLength uint32 = 32
)
// ErrInvalidHash means a stored PHC string is malformed or uses unsupported
// parameters. It is an internal error, never shown to a client.
var ErrInvalidHash = errors.New("invalid password hash")
// Hash derives an Argon2id PHC string for password. Callers must validate the
// password policy before calling; the KDF itself accepts arbitrary UTF-8.
func Hash(password string) (string, error) {
salt := make([]byte, argonSaltLength)
if _, err := rand.Read(salt); err != nil {
return "", fmt.Errorf("generate password salt: %w", err)
}
key := argon2.IDKey([]byte(password), salt, argonIterations, argonMemory, argonParallelism, argonKeyLength)
return fmt.Sprintf("$argon2id$v=%d$m=%d,t=%d,p=%d$%s$%s",
argon2.Version, argonMemory, argonIterations, argonParallelism,
base64.RawStdEncoding.EncodeToString(salt),
base64.RawStdEncoding.EncodeToString(key),
), nil
}
// Verify checks password against a PHC string in constant time and reports
// whether the encoded hash was structurally valid. A malformed hash is not a
// password mismatch and should be treated as an internal error by the caller.
func Verify(password, encoded string) (match bool, err error) {
params, salt, key, err := parse(encoded)
if err != nil {
return false, err
}
candidate := argon2.IDKey([]byte(password), salt, params.iterations, params.memory, params.parallelism, uint32(len(key)))
return subtle.ConstantTimeCompare(candidate, key) == 1, nil
}
type params struct {
memory uint32
iterations uint32
parallelism uint8
}
func parse(encoded string) (params, []byte, []byte, error) {
parts := strings.Split(encoded, "$")
if len(parts) != 6 || parts[0] != "" || parts[1] != "argon2id" {
return params{}, nil, nil, ErrInvalidHash
}
if parts[2] != fmt.Sprintf("v=%d", argon2.Version) {
return params{}, nil, nil, ErrInvalidHash
}
var p params
if _, err := fmt.Sscanf(parts[3], "m=%d,t=%d,p=%d", &p.memory, &p.iterations, &p.parallelism); err != nil {
return params{}, nil, nil, ErrInvalidHash
}
if p.memory < 8*1024 || p.memory > 256*1024 || p.iterations < 1 || p.iterations > 10 || p.parallelism < 1 || p.parallelism > 16 {
return params{}, nil, nil, ErrInvalidHash
}
salt, err := base64.RawStdEncoding.DecodeString(parts[4])
if err != nil || len(salt) < 8 || len(salt) > 64 {
return params{}, nil, nil, ErrInvalidHash
}
key, err := base64.RawStdEncoding.DecodeString(parts[5])
if err != nil || len(key) < 16 || len(key) > 64 {
return params{}, nil, nil, ErrInvalidHash
}
return p, salt, key, nil
}
+102
View File
@@ -0,0 +1,102 @@
package auth
import (
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"errors"
)
// tokenBytes gives 256 bits of entropy, the contract minimum. The token is an
// opaque value: it is not a username, a UUID or a JWT.
const tokenBytes = 32
// NewToken returns a URL-safe opaque session token.
func NewToken() (string, error) {
raw := make([]byte, tokenBytes)
if _, err := rand.Read(raw); err != nil {
return "", err
}
return base64.RawURLEncoding.EncodeToString(raw), nil
}
// TokenHash is the only representation of a token that is persisted. A cache
// dump therefore does not contain bearer credentials usable against the API.
func TokenHash(token string) string {
sum := sha256.Sum256([]byte(token))
return hex.EncodeToString(sum[:])
}
// ValidTokenShape rejects absurd header values before hashing. The check is a
// superset of the 43-character tokens this server issues, so token rotation
// remains possible without rejecting old values early.
func ValidTokenShape(token string) bool {
if len(token) < 16 || len(token) > 128 {
return false
}
for i := 0; i < len(token); i++ {
c := token[i]
if (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '-' || c == '_' {
continue
}
return false
}
return true
}
// ErrMalformedBasic is returned for anything that is not a well-formed
// RFC 7617 Basic credential. Callers must answer with the same 401 as a
// wrong password.
var ErrMalformedBasic = errors.New("malformed basic credentials")
// ParseBasic decodes an Authorization header of the form "Basic base64(user:pass)".
// The password may contain colons and arbitrary UTF-8; only the first colon
// separates the username.
func ParseBasic(header string) (username, password string, err error) {
const scheme = "basic"
trimmed := header
if len(trimmed) < len(scheme)+1 || !equalFoldASCII(trimmed[:len(scheme)], scheme) || trimmed[len(scheme)] != ' ' {
return "", "", ErrMalformedBasic
}
encoded := trimmed[len(scheme)+1:]
if encoded == "" || len(encoded) > 1024 {
return "", "", ErrMalformedBasic
}
decoded, err := base64.StdEncoding.DecodeString(encoded)
if err != nil {
// Some clients omit the RFC 4648 padding. Accept the unpadded form as
// well, but never fall back to a different alphabet.
decoded, err = base64.RawStdEncoding.DecodeString(encoded)
if err != nil {
return "", "", ErrMalformedBasic
}
}
separator := -1
for i := 0; i < len(decoded); i++ {
if decoded[i] == ':' {
separator = i
break
}
}
if separator < 0 {
return "", "", ErrMalformedBasic
}
return string(decoded[:separator]), string(decoded[separator+1:]), nil
}
func equalFoldASCII(value, lower string) bool {
if len(value) != len(lower) {
return false
}
for i := 0; i < len(value); i++ {
c := value[i]
if c >= 'A' && c <= 'Z' {
c += 'a' - 'A'
}
if c != lower[i] {
return false
}
}
return true
}
+375
View File
@@ -0,0 +1,375 @@
// Package config loads the explicit runtime configuration of the lab3
// messenger. The container image stays immutable: the same image is configured
// through environment variables (or files referenced by *_FILE variables for
// operators that do not want secrets in the environment).
package config
import (
"fmt"
"log/slog"
"os"
"strconv"
"strings"
"time"
)
const (
// DefaultSessionTTL is the contract default of contracts/README.md.
DefaultSessionTTL = time.Hour
// MaxShutdownTimeout leaves headroom below the 10 second termination
// window promised by the previous lab and expected by the container
// checks, even if an operator overrides the environment variable.
MaxShutdownTimeout = 9 * time.Second
// MaxStartupTimeout bounds the initial PostgreSQL connectivity wait.
MaxStartupTimeout = 120 * time.Second
)
// Config is validated at startup. The process refuses to start with an
// invalid value instead of silently falling back to a different security or
// durability posture.
type Config struct {
Host string
Port int
Env string
LogLevel slog.Level
ShutdownTimeout time.Duration
ShutdownDrain time.Duration
StartupTimeout time.Duration
MetricsAddr string
DatabaseURL string
CacheURL string
SessionTTL time.Duration
DBMaxConns int32
DBMinConns int32
DBConnectTimeout time.Duration
DBStatementTimeout time.Duration
QueryTimeout time.Duration
CachePoolSize int
CacheTimeout time.Duration
S3Endpoint string
S3Region string
S3Bucket string
S3AccessKey string
S3SecretKey string
S3Timeout time.Duration
MaxUploadBytes int64
MaxImagePixels int64
DecodeConcurrency int
PutConcurrency int
TempDir string
}
// Load reads and validates the full API configuration.
func Load() (Config, error) { return load(true, true) }
// LoadMigrate loads only what the one-shot migration command needs.
func LoadMigrate() (Config, error) { return load(false, false) }
// LoadTool loads the database and S3 configuration used by the offline
// reconciler and the bucket/test tools; Valkey is not required.
func LoadTool() (Config, error) { return load(false, true) }
// load is the shared parser. requireCache and requireS3 select which optional
// dependency blocks are mandatory for the calling command.
func load(requireCache, requireS3 bool) (Config, error) {
cfg := Config{
Host: envString("APP_HOST", "0.0.0.0"),
Env: envString("APP_ENV", "lab"),
ShutdownTimeout: 6 * time.Second,
ShutdownDrain: 3 * time.Second,
StartupTimeout: 30 * time.Second,
QueryTimeout: 3 * time.Second,
MetricsAddr: envString("METRICS_ADDR", "127.0.0.1:9090"),
}
port, err := envInt("APP_PORT", 8080)
if err != nil {
return Config{}, fmt.Errorf("APP_PORT: %w", err)
}
if port < 1 || port > 65535 {
return Config{}, fmt.Errorf("APP_PORT: must be between 1 and 65535")
}
cfg.Port = port
level, err := parseLogLevel(envString("LOG_LEVEL", "info"))
if err != nil {
return Config{}, fmt.Errorf("LOG_LEVEL: %w", err)
}
cfg.LogLevel = level
if strings.TrimSpace(cfg.Host) == "" {
return Config{}, fmt.Errorf("APP_HOST: must not be empty")
}
databaseURL, err := secret("DATABASE_URL")
if err != nil {
return Config{}, err
}
cfg.DatabaseURL = databaseURL
if requireCache {
cacheURL, err := secret("CACHE_URL")
if err != nil {
return Config{}, err
}
cfg.CacheURL = cacheURL
}
seconds, err := envInt("SESSION_TTL_SECONDS", int(DefaultSessionTTL/time.Second))
if err != nil {
return Config{}, fmt.Errorf("SESSION_TTL_SECONDS: %w", err)
}
if seconds < 1 || seconds > 30*24*60*60 {
return Config{}, fmt.Errorf("SESSION_TTL_SECONDS: must be between 1 and 2592000")
}
cfg.SessionTTL = time.Duration(seconds) * time.Second
maxConns, err := envInt("DB_MAX_CONNS", 8)
if err != nil {
return Config{}, fmt.Errorf("DB_MAX_CONNS: %w", err)
}
if maxConns < 1 || maxConns > 100 {
return Config{}, fmt.Errorf("DB_MAX_CONNS: must be between 1 and 100")
}
cfg.DBMaxConns = int32(maxConns)
minConns, err := envInt("DB_MIN_CONNS", 1)
if err != nil {
return Config{}, fmt.Errorf("DB_MIN_CONNS: %w", err)
}
if minConns < 0 || minConns > maxConns {
return Config{}, fmt.Errorf("DB_MIN_CONNS: must be between 0 and DB_MAX_CONNS")
}
cfg.DBMinConns = int32(minConns)
if cfg.DBConnectTimeout, err = envDurationSeconds("DB_CONNECT_TIMEOUT_SECONDS", 3, 1, 30); err != nil {
return Config{}, err
}
if cfg.DBStatementTimeout, err = envDurationSeconds("DB_STATEMENT_TIMEOUT_SECONDS", 3, 1, 60); err != nil {
return Config{}, err
}
if cfg.QueryTimeout, err = envDurationSeconds("DB_QUERY_TIMEOUT_SECONDS", 3, 1, 60); err != nil {
return Config{}, err
}
cachePool, err := envInt("CACHE_POOL_SIZE", 8)
if err != nil {
return Config{}, fmt.Errorf("CACHE_POOL_SIZE: %w", err)
}
if cachePool < 1 || cachePool > 100 {
return Config{}, fmt.Errorf("CACHE_POOL_SIZE: must be between 1 and 100")
}
cfg.CachePoolSize = cachePool
if cfg.CacheTimeout, err = envDurationSeconds("CACHE_TIMEOUT_SECONDS", 2, 1, 30); err != nil {
return Config{}, err
}
shutdown, err := envDurationSeconds("SHUTDOWN_TIMEOUT_SECONDS", 6, 1, 60)
if err != nil {
return Config{}, err
}
if shutdown > MaxShutdownTimeout {
shutdown = MaxShutdownTimeout
}
cfg.ShutdownTimeout = shutdown
drain, err := envDurationSeconds("SHUTDOWN_DRAIN_SECONDS", 3, 0, 8)
if err != nil {
return Config{}, err
}
// The drain must finish before the hard shutdown window; otherwise a
// SIGTERM could spend the whole grace period advertising readiness and
// never reach http.Server.Shutdown.
if drain >= shutdown {
return Config{}, fmt.Errorf("SHUTDOWN_DRAIN_SECONDS must be smaller than SHUTDOWN_TIMEOUT_SECONDS")
}
cfg.ShutdownDrain = drain
startup, err := envDurationSeconds("STARTUP_TIMEOUT_SECONDS", 30, 1, 120)
if err != nil {
return Config{}, err
}
cfg.StartupTimeout = startup
if requireS3 {
if err := loadS3(&cfg); err != nil {
return Config{}, err
}
}
return cfg, nil
}
// loadS3 parses the private object store configuration and the image limits
// that must be enforced before any unbounded read or decode.
func loadS3(cfg *Config) error {
endpoint, err := secret("S3_ENDPOINT")
if err != nil {
return err
}
cfg.S3Endpoint = endpoint
cfg.S3Region = envString("S3_REGION", "us-east-1")
cfg.S3Bucket = envString("S3_BUCKET", "messenger-attachments")
if !validBucketName(cfg.S3Bucket) {
return fmt.Errorf("S3_BUCKET: must match [a-z0-9][a-z0-9.-]{1,61}[a-z0-9]")
}
accessKey, err := secret("S3_ACCESS_KEY")
if err != nil {
return err
}
secretKey, err := secret("S3_SECRET_KEY")
if err != nil {
return err
}
cfg.S3AccessKey = accessKey
cfg.S3SecretKey = secretKey
timeout, err := envDurationSeconds("S3_TIMEOUT_SECONDS", 10, 5, 120)
if err != nil {
return err
}
cfg.S3Timeout = timeout
maxUpload, err := envInt64("MAX_UPLOAD_BYTES", 10*1024*1024)
if err != nil {
return fmt.Errorf("MAX_UPLOAD_BYTES: %w", err)
}
if maxUpload < 1 || maxUpload > 10*1024*1024 {
return fmt.Errorf("MAX_UPLOAD_BYTES: must be between 1 and 10485760")
}
cfg.MaxUploadBytes = maxUpload
maxPixels, err := envInt64("MAX_IMAGE_PIXELS", 40_000_000)
if err != nil {
return fmt.Errorf("MAX_IMAGE_PIXELS: %w", err)
}
if maxPixels < 1 || maxPixels > 40_000_000 {
return fmt.Errorf("MAX_IMAGE_PIXELS: must be between 1 and 40000000")
}
cfg.MaxImagePixels = maxPixels
concurrency, err := envInt("UPLOAD_DECODE_CONCURRENCY", 1)
if err != nil {
return fmt.Errorf("UPLOAD_DECODE_CONCURRENCY: %w", err)
}
if concurrency < 1 || concurrency > 4 {
return fmt.Errorf("UPLOAD_DECODE_CONCURRENCY: must be between 1 and 4")
}
cfg.DecodeConcurrency = concurrency
// The single-node SeaweedFS stand was verified stable at one concurrent
// PUT per API replica; two concurrent multi-megabyte writes could restart
// it. Uploads queue after their body was already streamed to a bounded
// temporary file, so queuing does not add unbounded RAM.
putConcurrency, err := envInt("S3_PUT_CONCURRENCY", 1)
if err != nil {
return fmt.Errorf("S3_PUT_CONCURRENCY: %w", err)
}
if putConcurrency != 1 {
return fmt.Errorf("S3_PUT_CONCURRENCY: must be 1 on this single-node stand")
}
cfg.PutConcurrency = putConcurrency
cfg.TempDir = envString("UPLOAD_TEMP_DIR", "")
return nil
}
func validBucketName(value string) bool {
if len(value) < 3 || len(value) > 63 {
return false
}
for i := 0; i < len(value); i++ {
c := value[i]
if (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '.' || c == '-' {
continue
}
return false
}
return value[0] != '.' && value[0] != '-' && value[len(value)-1] != '.' && value[len(value)-1] != '-'
}
// secret resolves NAME or NAME_FILE. A file is preferred when both are set so
// compose-style file secrets win over inherited environment values. Values are
// never echoed in error messages.
func secret(name string) (string, error) {
if path := strings.TrimSpace(os.Getenv(name + "_FILE")); path != "" {
data, err := os.ReadFile(path)
if err != nil {
return "", fmt.Errorf("%s_FILE: cannot read referenced file", name)
}
value := strings.TrimSpace(string(data))
if value == "" {
return "", fmt.Errorf("%s_FILE: referenced file is empty", name)
}
return value, nil
}
if value := strings.TrimSpace(os.Getenv(name)); value != "" {
return value, nil
}
return "", fmt.Errorf("%s or %s_FILE is required", name, name)
}
func envString(key, fallback string) string {
// An environment variable set to an empty string is treated as unset; this
// keeps container defaults working when compose passes "" for an optional
// setting.
if value := strings.TrimSpace(os.Getenv(key)); value != "" {
return value
}
return fallback
}
func envInt(key string, fallback int) (int, error) {
raw, ok := os.LookupEnv(key)
if !ok || strings.TrimSpace(raw) == "" {
return fallback, nil
}
value, err := strconv.Atoi(strings.TrimSpace(raw))
if err != nil {
return 0, fmt.Errorf("expected an integer, got %q", raw)
}
return value, nil
}
func envInt64(key string, fallback int64) (int64, error) {
raw, ok := os.LookupEnv(key)
if !ok || strings.TrimSpace(raw) == "" {
return fallback, nil
}
value, err := strconv.ParseInt(strings.TrimSpace(raw), 10, 64)
if err != nil {
return 0, fmt.Errorf("expected an integer, got %q", raw)
}
return value, nil
}
func envDurationSeconds(key string, fallback, minimum, maximum int) (time.Duration, error) {
value, err := envInt(key, fallback)
if err != nil {
return 0, fmt.Errorf("%s: %w", key, err)
}
if value < minimum || value > maximum {
return 0, fmt.Errorf("%s: must be between %d and %d", key, minimum, maximum)
}
return time.Duration(value) * time.Second, nil
}
func parseLogLevel(raw string) (slog.Level, error) {
switch strings.ToLower(strings.TrimSpace(raw)) {
case "debug":
return slog.LevelDebug, nil
case "info":
return slog.LevelInfo, nil
case "warn", "warning":
return slog.LevelWarn, nil
case "error":
return slog.LevelError, nil
default:
return 0, fmt.Errorf("expected debug, info, warn or error, got %q", raw)
}
}
+178
View File
@@ -0,0 +1,178 @@
package config
import (
"os"
"path/filepath"
"testing"
"time"
)
var allKeys = []string{
"APP_HOST", "APP_PORT", "APP_ENV", "LOG_LEVEL", "SESSION_TTL_SECONDS",
"DB_MAX_CONNS", "DB_MIN_CONNS", "DB_CONNECT_TIMEOUT_SECONDS",
"DB_STATEMENT_TIMEOUT_SECONDS", "DB_QUERY_TIMEOUT_SECONDS",
"CACHE_POOL_SIZE", "CACHE_TIMEOUT_SECONDS", "SHUTDOWN_TIMEOUT_SECONDS",
"STARTUP_TIMEOUT_SECONDS", "DATABASE_URL", "DATABASE_URL_FILE",
"CACHE_URL", "CACHE_URL_FILE",
"S3_ENDPOINT", "S3_ENDPOINT_FILE", "S3_REGION", "S3_BUCKET",
"S3_ACCESS_KEY", "S3_ACCESS_KEY_FILE", "S3_SECRET_KEY", "S3_SECRET_KEY_FILE",
"S3_TIMEOUT_SECONDS", "MAX_UPLOAD_BYTES", "MAX_IMAGE_PIXELS",
"UPLOAD_DECODE_CONCURRENCY", "S3_PUT_CONCURRENCY", "UPLOAD_TEMP_DIR",
}
func clearEnvironment(t *testing.T) {
t.Helper()
for _, key := range allKeys {
t.Setenv(key, "")
}
}
func baseEnvironment(t *testing.T) {
t.Helper()
clearEnvironment(t)
t.Setenv("DATABASE_URL", "postgres://user:pass@postgres:5432/db?sslmode=disable")
t.Setenv("CACHE_URL", "redis://:pass@valkey:6379/0")
t.Setenv("S3_ENDPOINT", "http://s3:8333")
t.Setenv("S3_BUCKET", "messenger-attachments")
t.Setenv("S3_ACCESS_KEY", "local-test-access")
t.Setenv("S3_SECRET_KEY", "local-test-secret")
}
func TestLoadDefaults(t *testing.T) {
baseEnvironment(t)
cfg, err := Load()
if err != nil {
t.Fatalf("Load: %v", err)
}
if cfg.Port != 8080 || cfg.SessionTTL != time.Hour {
t.Fatalf("unexpected defaults: %+v", cfg)
}
if cfg.DBMaxConns != 8 || cfg.DBMinConns != 1 || cfg.QueryTimeout != 3*time.Second {
t.Fatalf("unexpected pool defaults: %+v", cfg)
}
if cfg.MaxUploadBytes != 10*1024*1024 || cfg.MaxImagePixels != 40_000_000 || cfg.DecodeConcurrency != 1 {
t.Fatalf("unexpected upload defaults: %+v", cfg)
}
if cfg.S3Bucket != "messenger-attachments" || cfg.S3Region != "us-east-1" {
t.Fatalf("unexpected S3 defaults: %+v", cfg)
}
}
func TestLoadReadsSecretsFromFiles(t *testing.T) {
clearEnvironment(t)
directory := t.TempDir()
databaseFile := filepath.Join(directory, "database_url")
cacheFile := filepath.Join(directory, "cache_url")
if err := os.WriteFile(databaseFile, []byte("postgres://file:secret@postgres/db\n"), 0o600); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(cacheFile, []byte("redis://:file-secret@valkey:6379/0\n"), 0o600); err != nil {
t.Fatal(err)
}
t.Setenv("DATABASE_URL_FILE", databaseFile)
t.Setenv("CACHE_URL_FILE", cacheFile)
t.Setenv("S3_ENDPOINT", "http://s3:8333")
t.Setenv("S3_ACCESS_KEY", "file-test-access")
t.Setenv("S3_SECRET_KEY", "file-test-secret")
cfg, err := Load()
if err != nil {
t.Fatalf("Load: %v", err)
}
if cfg.DatabaseURL != "postgres://file:secret@postgres/db" {
t.Fatalf("database URL was not read from file: %q", cfg.DatabaseURL)
}
if cfg.CacheURL != "redis://:file-secret@valkey:6379/0" {
t.Fatalf("cache URL was not read from file: %q", cfg.CacheURL)
}
}
func TestLoadRejectsInvalidValues(t *testing.T) {
cases := []struct {
name string
key string
value string
}{
{"zero ttl", "SESSION_TTL_SECONDS", "0"},
{"huge ttl", "SESSION_TTL_SECONDS", "99999999"},
{"zero port", "APP_PORT", "0"},
{"bad log level", "LOG_LEVEL", "verbose"},
{"zero max conns", "DB_MAX_CONNS", "0"},
{"min above max", "DB_MIN_CONNS", "9"},
{"bad timeout", "DB_QUERY_TIMEOUT_SECONDS", "0"},
{"bad int", "APP_PORT", "eighty"},
{"upload above contract", "MAX_UPLOAD_BYTES", "10485761"},
{"pixels above contract", "MAX_IMAGE_PIXELS", "40000001"},
{"zero decode concurrency", "UPLOAD_DECODE_CONCURRENCY", "0"},
{"zero put concurrency", "S3_PUT_CONCURRENCY", "0"},
{"unsafe put concurrency", "S3_PUT_CONCURRENCY", "2"},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
baseEnvironment(t)
t.Setenv(tc.key, tc.value)
if _, err := Load(); err == nil {
t.Fatalf("Load accepted %s=%q", tc.key, tc.value)
}
})
}
}
func TestLoadRequiresDatabaseAndCacheURLs(t *testing.T) {
clearEnvironment(t)
if _, err := Load(); err == nil {
t.Fatal("Load accepted missing DATABASE_URL/CACHE_URL")
}
t.Setenv("DATABASE_URL", "postgres://user:pass@postgres/db")
if _, err := Load(); err == nil {
t.Fatal("Load accepted missing CACHE_URL")
}
}
func TestLoadRequiresS3Configuration(t *testing.T) {
baseEnvironment(t)
t.Setenv("S3_ACCESS_KEY", "")
if _, err := Load(); err == nil {
t.Fatal("Load accepted missing S3_ACCESS_KEY")
}
t.Setenv("S3_ACCESS_KEY", "local-test-access")
t.Setenv("S3_BUCKET", "Invalid_Bucket")
if _, err := Load(); err == nil {
t.Fatal("Load accepted an invalid S3 bucket name")
}
}
func TestMigrateConfigurationDoesNotRequireCacheOrS3(t *testing.T) {
clearEnvironment(t)
t.Setenv("DATABASE_URL", "postgres://user:pass@postgres:5432/db?sslmode=disable")
cfg, err := LoadMigrate()
if err != nil {
t.Fatalf("LoadMigrate: %v", err)
}
if cfg.DatabaseURL == "" || cfg.CacheURL != "" || cfg.S3Endpoint != "" {
t.Fatalf("unexpected migrate configuration: %+v", cfg)
}
}
func TestShutdownTimeoutIsClamped(t *testing.T) {
baseEnvironment(t)
t.Setenv("SHUTDOWN_TIMEOUT_SECONDS", "60")
cfg, err := Load()
if err != nil {
t.Fatalf("Load: %v", err)
}
if cfg.ShutdownTimeout != MaxShutdownTimeout {
t.Fatalf("shutdown timeout = %v, want clamp to %v", cfg.ShutdownTimeout, MaxShutdownTimeout)
}
}
func TestSecretFileErrorsDoNotLeakThePath(t *testing.T) {
clearEnvironment(t)
t.Setenv("DATABASE_URL_FILE", "/nonexistent/path/database_url")
_, err := Load()
if err == nil {
t.Fatal("Load accepted a missing secret file")
}
if got := err.Error(); got != "DATABASE_URL_FILE: cannot read referenced file" {
t.Fatalf("error leaks path: %q", got)
}
}
+119
View File
@@ -0,0 +1,119 @@
// Package cursor implements the opaque keyset cursor of the contract. A cursor
// carries the last item already returned; the next page asks PostgreSQL for
// rows strictly after (created_at, id). Cursors are bound to the endpoint and,
// for message history, to the chat that issued them.
package cursor
import (
"bytes"
"encoding/base64"
"encoding/json"
"errors"
"io"
"time"
"mtusi.ru/messenger-lab4/internal/model"
"mtusi.ru/messenger-lab4/internal/uuid"
)
const (
ScopeChats = "chats"
ScopeMessages = "messages"
version = 1
maxCursorSize = 512
)
// ErrInvalid is returned for malformed, tampered or out-of-scope cursors. The
// HTTP layer maps it to 400 invalid_request.
var ErrInvalid = errors.New("invalid cursor")
// Cursor is the decoded keyset position.
type Cursor struct {
At time.Time
ID string
ChatID string
}
// Encoding of the wire form. Time is an RFC 3339 timestamp with UTC Z and
// microsecond precision, matching PostgreSQL timestamptz. It is never used as
// an identifier on its own.
type wire struct {
Version int `json:"v"`
Scope string `json:"s"`
ChatID string `json:"c,omitempty"`
Time string `json:"t"`
ID string `json:"i"`
}
// ForChat encodes the position of the last returned chat.
func ForChat(chat model.Chat) string {
return encode(wire{Scope: ScopeChats, Time: chat.CreatedAt.UTC().Format(time.RFC3339Nano), ID: chat.ID})
}
// ForMessage encodes the position of the last returned message.
func ForMessage(message model.Message) string {
return encode(wire{
Scope: ScopeMessages,
ChatID: message.ChatID,
Time: message.CreatedAt.UTC().Format(time.RFC3339Nano),
ID: message.ID,
})
}
// Decode validates a cursor for the expected scope. chatID is required for the
// messages scope and must be empty for the chats scope.
func Decode(raw, scope, chatID string) (Cursor, error) {
if raw == "" || len(raw) > maxCursorSize {
return Cursor{}, ErrInvalid
}
data, err := base64.RawURLEncoding.DecodeString(raw)
if err != nil {
return Cursor{}, ErrInvalid
}
var value wire
decoder := json.NewDecoder(bytes.NewReader(data))
decoder.DisallowUnknownFields()
if err := decoder.Decode(&value); err != nil {
return Cursor{}, ErrInvalid
}
var extra any
if err := decoder.Decode(&extra); !errors.Is(err, io.EOF) {
return Cursor{}, ErrInvalid
}
if value.Version != version || value.Scope != scope {
return Cursor{}, ErrInvalid
}
at, err := time.Parse(time.RFC3339Nano, value.Time)
if err != nil || at.IsZero() || at.Location() != time.UTC {
return Cursor{}, ErrInvalid
}
normalizedID, ok := uuid.Normalize(value.ID)
if !ok || normalizedID != value.ID {
return Cursor{}, ErrInvalid
}
switch scope {
case ScopeChats:
if value.ChatID != "" {
return Cursor{}, ErrInvalid
}
return Cursor{At: at, ID: normalizedID}, nil
case ScopeMessages:
normalizedChat, ok := uuid.Normalize(value.ChatID)
if !ok || normalizedChat != value.ChatID || normalizedChat != chatID {
return Cursor{}, ErrInvalid
}
return Cursor{At: at, ID: normalizedID, ChatID: normalizedChat}, nil
default:
return Cursor{}, ErrInvalid
}
}
func encode(value wire) string {
value.Version = version
data, err := json.Marshal(value)
if err != nil {
panic("encode cursor: " + err.Error())
}
return base64.RawURLEncoding.EncodeToString(data)
}
+97
View File
@@ -0,0 +1,97 @@
package cursor
import (
"encoding/base64"
"encoding/json"
"strings"
"testing"
"time"
"mtusi.ru/messenger-lab4/internal/model"
)
func TestChatCursorRoundTrip(t *testing.T) {
at := time.Date(2026, 11, 30, 12, 34, 56, 123456000, time.UTC)
chat := model.Chat{
ID: "11111111-2222-4333-8444-555555555555",
Title: "chat",
MemberIDs: []string{"11111111-2222-4333-8444-555555555555"},
CreatedAt: model.Time{Time: at},
}
raw := ForChat(chat)
decoded, err := Decode(raw, ScopeChats, "")
if err != nil {
t.Fatalf("Decode: %v", err)
}
if !decoded.At.Equal(at) || decoded.ID != chat.ID || decoded.ChatID != "" {
t.Fatalf("decoded = %+v", decoded)
}
}
func TestMessageCursorIsBoundToChat(t *testing.T) {
at := time.Now().UTC().Truncate(time.Microsecond)
chatID := "11111111-2222-4333-8444-555555555555"
message := model.Message{
ID: "99999999-2222-4333-8444-555555555555",
ChatID: chatID,
SenderID: "11111111-2222-4333-8444-555555555555",
Text: "hello",
CreatedAt: model.Time{Time: at},
}
raw := ForMessage(message)
if _, err := Decode(raw, ScopeMessages, chatID); err != nil {
t.Fatalf("Decode(same chat): %v", err)
}
if _, err := Decode(raw, ScopeMessages, "22222222-2222-4333-8444-555555555555"); err == nil {
t.Fatal("cursor was accepted for another chat")
}
if _, err := Decode(raw, ScopeChats, ""); err == nil {
t.Fatal("message cursor was accepted by the chats scope")
}
}
func TestDecodeRejectsTamperedCursors(t *testing.T) {
at := time.Now().UTC().Truncate(time.Microsecond)
valid := wire{
Version: version,
Scope: ScopeMessages,
ChatID: "11111111-2222-4333-8444-555555555555",
Time: at.Format(time.RFC3339Nano),
ID: "99999999-2222-4333-8444-555555555555",
}
tampered := []wire{
{Version: 2, Scope: valid.Scope, ChatID: valid.ChatID, Time: valid.Time, ID: valid.ID},
{Version: version, Scope: ScopeChats, ChatID: valid.ChatID, Time: valid.Time, ID: valid.ID},
{Version: version, Scope: valid.Scope, ChatID: "", Time: valid.Time, ID: valid.ID},
{Version: version, Scope: valid.Scope, ChatID: "not-a-uuid", Time: valid.Time, ID: valid.ID},
{Version: version, Scope: valid.Scope, ChatID: valid.ChatID, Time: "2026-11-30T12:00:00+03:00", ID: valid.ID},
{Version: version, Scope: valid.Scope, ChatID: valid.ChatID, Time: "yesterday", ID: valid.ID},
{Version: version, Scope: valid.Scope, ChatID: valid.ChatID, Time: valid.Time, ID: "not-a-uuid"},
}
for i, value := range tampered {
data, err := json.Marshal(value)
if err != nil {
t.Fatal(err)
}
raw := base64.RawURLEncoding.EncodeToString(data)
if _, err := Decode(raw, ScopeMessages, valid.ChatID); err == nil {
t.Fatalf("tampered cursor %d was accepted", i)
}
}
withExtra, _ := json.Marshal(map[string]any{
"v": version, "s": ScopeMessages, "c": valid.ChatID,
"t": valid.Time, "i": valid.ID, "x": 1,
})
if _, err := Decode(base64.RawURLEncoding.EncodeToString(withExtra), ScopeMessages, valid.ChatID); err == nil {
t.Fatal("cursor with an unknown field was accepted")
}
}
func TestDecodeRejectsGarbage(t *testing.T) {
for _, raw := range []string{"", "!!!", base64.RawURLEncoding.EncodeToString([]byte("not json")), strings.Repeat("a", 600)} {
if _, err := Decode(raw, ScopeChats, ""); err == nil {
t.Fatalf("Decode accepted %q", raw)
}
}
}
+99
View File
@@ -0,0 +1,99 @@
// Package model holds the public JSON shapes of the lab3 contract. They are
// deliberately separate from the database scan helpers so an accidental new
// column cannot silently become an API field.
package model
import "time"
// Time marshals an RFC 3339 UTC timestamp with exactly six fractional digits.
// Go's default time.Time JSON encoder trims trailing zeros, which produces
// 3-5 digit fractions that some Python 3.9 datetime parsers (used by the
// public test client) reject. A fixed microsecond precision matches
// PostgreSQL timestamptz and stays valid RFC 3339.
type Time struct{ time.Time }
const timestampLayout = "2006-01-02T15:04:05.000000Z"
// MarshalJSON implements json.Marshaler.
func (t Time) MarshalJSON() ([]byte, error) {
return []byte(`"` + t.UTC().Format(timestampLayout) + `"`), nil
}
// User is the public user shape. It never contains a password hash or session
// data.
type User struct {
ID string `json:"id"`
Username string `json:"username"`
DisplayName string `json:"display_name"`
CreatedAt Time `json:"created_at"`
}
// Chat is the public chat shape. MemberIDs preserves the order supplied at
// creation; membership is immutable in the mandatory lab3 API.
type Chat struct {
ID string `json:"id"`
Title string `json:"title"`
MemberIDs []string `json:"member_ids"`
CreatedAt Time `json:"created_at"`
}
// Message is the public message shape. SenderID always comes from the server
// session, never from the request body. AttachmentIDs is always a JSON array,
// never null, and preserves the order supplied by the client.
type Message struct {
ID string `json:"id"`
ChatID string `json:"chat_id"`
SenderID string `json:"sender_id"`
Text string `json:"text"`
CreatedAt Time `json:"created_at"`
AttachmentIDs []string `json:"attachment_ids"`
}
// Variant is the public derivative shape. Lab4 never creates variants, so
// every Attachment carries an empty array; the schema is kept for lab5.
type Variant struct {
Name string `json:"name"`
ContentType string `json:"content_type"`
SizeBytes int64 `json:"size_bytes"`
Width int `json:"width"`
Height int `json:"height"`
SHA256 string `json:"sha256"`
}
// Attachment is the public metadata shape. Object keys, bucket names and
// storage credentials are deliberately absent: they are server-side details.
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"`
SizeBytes int64 `json:"size_bytes"`
SHA256 string `json:"sha256"`
Status string `json:"status"`
Variants []Variant `json:"variants"`
ErrorCode *string `json:"error_code"`
CreatedAt Time `json:"created_at"`
UpdatedAt Time `json:"updated_at"`
}
// ChatPage is one keyset page of accessible chats.
type ChatPage struct {
Items []Chat `json:"items"`
NextCursor *string `json:"next_cursor"`
}
// MessagePage is one keyset page of a chat history.
type MessagePage struct {
Items []Message `json:"items"`
NextCursor *string `json:"next_cursor"`
}
// Session is the login response. Token is only ever written to the response
// body, never to logs or PostgreSQL.
type Session struct {
Token string `json:"token"`
TokenType string `json:"token_type"`
ExpiresAt Time `json:"expires_at"`
User User `json:"user"`
}
+50
View File
@@ -0,0 +1,50 @@
package model
import (
"encoding/json"
"strings"
"testing"
"time"
)
func TestTimeMarshalUsesFixedMicroseconds(t *testing.T) {
value := Time{Time: time.Date(2026, 11, 30, 12, 0, 0, 120000000, time.UTC)}
data, err := json.Marshal(value)
if err != nil {
t.Fatal(err)
}
got := string(data)
// .120000 would be trimmed to .12 by the default encoder; the public
// Python 3.9 client requires 3 or 6 fractional digits.
if got != `"2026-11-30T12:00:00.120000Z"` {
t.Fatalf("marshal = %s", got)
}
if !strings.HasSuffix(got, "Z\"") {
t.Fatal("timestamp does not end in Z")
}
}
func TestUserJSONHasOnlyPublicFields(t *testing.T) {
user := User{
ID: "11111111-2222-4333-8444-555555555555",
Username: "alice",
DisplayName: "Алиса",
CreatedAt: Time{Time: time.Date(2026, 9, 1, 12, 0, 0, 0, time.UTC)},
}
data, err := json.Marshal(user)
if err != nil {
t.Fatal(err)
}
var fields map[string]any
if err := json.Unmarshal(data, &fields); err != nil {
t.Fatal(err)
}
if len(fields) != 4 {
t.Fatalf("user JSON has unexpected fields: %v", fields)
}
for _, forbidden := range []string{"password", "password_hash", "token", "token_hash"} {
if _, present := fields[forbidden]; present {
t.Fatalf("user JSON leaks %q", forbidden)
}
}
}
+294
View File
@@ -0,0 +1,294 @@
// Package objectstore is the S3 adapter. PostgreSQL stores attachment
// metadata; this package stores and streams the original bytes. No handler
// talks to the S3 SDK directly, so error classification and timeouts are in one
// place.
package objectstore
import (
"context"
"errors"
"fmt"
"io"
"net"
"net/http"
"net/url"
"strings"
"time"
"github.com/minio/minio-go/v7"
"github.com/minio/minio-go/v7/pkg/credentials"
)
var (
// ErrNotFound means the object (or a prerequisite such as the bucket) does
// not exist. The HTTP layer maps it to 404 for an attachment read.
ErrNotFound = errors.New("object not found")
// ErrUnavailable means S3 could not answer. The HTTP layer maps it to 503
// and never to a fabricated success.
ErrUnavailable = errors.New("object store unavailable")
)
// Config is the validated S3 connection. Credentials are never logged.
type Config struct {
Endpoint string
Region string
Bucket string
AccessKey string
SecretKey string
Timeout time.Duration
}
// Store is a thin, timeout-aware wrapper around minio-go.
type Store struct {
client *minio.Client
bucket string
timeout time.Duration
}
// Open parses S3_ENDPOINT as a scheme://host:port URL and builds a client. The
// caller must have validated that every field is non-empty.
func Open(cfg Config) (*Store, error) {
parsed, err := url.Parse(strings.TrimSpace(cfg.Endpoint))
if err != nil || parsed.Host == "" {
return nil, errors.New("S3_ENDPOINT must be an http(s) URL with a host")
}
if parsed.Scheme != "http" && parsed.Scheme != "https" {
return nil, errors.New("S3_ENDPOINT scheme must be http or https")
}
if parsed.Path != "" && parsed.Path != "/" {
return nil, errors.New("S3_ENDPOINT must not contain a path")
}
if cfg.Timeout <= 0 {
cfg.Timeout = 30 * time.Second
}
transport := &http.Transport{
Proxy: nil,
DialContext: (&net.Dialer{Timeout: 3 * time.Second, KeepAlive: 30 * time.Second}).DialContext,
MaxIdleConns: 32,
MaxIdleConnsPerHost: 16,
IdleConnTimeout: 60 * time.Second,
TLSHandshakeTimeout: 5 * time.Second,
ResponseHeaderTimeout: 10 * time.Second,
ExpectContinueTimeout: time.Second,
}
client, err := minio.New(parsed.Host, &minio.Options{
Creds: credentials.NewStaticV4(cfg.AccessKey, cfg.SecretKey, ""),
Secure: parsed.Scheme == "https",
Region: cfg.Region,
BucketLookup: minio.BucketLookupPath,
Transport: transport,
// The HTTP request is synchronous user work. One bounded retry is
// enough; the default exponential retry series would hold an upload
// request open for many seconds when S3 is unreachable.
MaxRetries: 1,
})
if err != nil {
return nil, errors.New("could not create S3 client")
}
return &Store{client: client, bucket: cfg.Bucket, timeout: cfg.Timeout}, nil
}
func (s *Store) opCtx(ctx context.Context) (context.Context, context.CancelFunc) {
return context.WithTimeout(ctx, s.timeout)
}
// Put uploads exactly size bytes with the declared content type. The caller
// has already validated the image; this function does not buffer the body.
func (s *Store) Put(ctx context.Context, key string, body io.Reader, size int64, contentType string) error {
ctx, cancel := s.opCtx(ctx)
defer cancel()
_, err := s.client.PutObject(ctx, s.bucket, key, body, size, minio.PutObjectOptions{
ContentType: contentType,
PartSize: 16 << 20,
NumThreads: 1,
DisableMultipart: size <= 16<<20,
})
if err != nil {
return classify(err)
}
return nil
}
// Get opens the object stream. The caller closes it. A missing object is
// ErrNotFound; an unreachable store is ErrUnavailable.
//
// The operation context must stay alive while the body is read: cancelling it
// when Get returns would abort the HTTP response stream. Close releases both
// the SDK object and its timeout.
//
// Existence and size come from a separate StatObject. Calling Stat on the
// lazily opened Object would make minio-go attach an If-Match ETag to the
// subsequent GET; SeaweedFS 3.98 rejects that conditional read for large
// objects with 412 after the store has been restarted. A plain GET avoids the
// false precondition while the HEAD still lets the handler return 404 before
// it writes response headers.
func (s *Store) Get(ctx context.Context, key string) (io.ReadCloser, ObjectInfo, error) {
ctx, cancel := s.opCtx(ctx)
info, err := s.client.StatObject(ctx, s.bucket, key, minio.StatObjectOptions{})
if err != nil {
cancel()
return nil, ObjectInfo{}, classify(err)
}
object, err := s.client.GetObject(ctx, s.bucket, key, minio.GetObjectOptions{})
if err != nil {
cancel()
return nil, ObjectInfo{}, classify(err)
}
return &objectStream{ReadCloser: object, cancel: cancel}, ObjectInfo{
Key: key,
Size: info.Size,
ContentType: info.ContentType,
LastModified: info.LastModified,
}, nil
}
// objectStream ties the S3 read lifetime to Close. The standard S3 response
// is not reusable after Close, and the caller always defers Close.
type objectStream struct {
io.ReadCloser
cancel context.CancelFunc
}
func (s *objectStream) Close() error {
err := s.ReadCloser.Close()
s.cancel()
return err
}
// Stat checks existence without downloading the bytes. It is used by the
// metadata endpoint so a missing object is not reported as a ready attachment.
func (s *Store) Stat(ctx context.Context, key string) (ObjectInfo, error) {
ctx, cancel := s.opCtx(ctx)
defer cancel()
info, err := s.client.StatObject(ctx, s.bucket, key, minio.StatObjectOptions{})
if err != nil {
return ObjectInfo{}, classify(err)
}
return ObjectInfo{
Key: key,
Size: info.Size,
ContentType: info.ContentType,
LastModified: info.LastModified,
}, nil
}
// Remove deletes one object. S3 delete is idempotent: a missing key is not an
// error, which makes a repeated reconciler run safe.
func (s *Store) Remove(ctx context.Context, key string) error {
ctx, cancel := s.opCtx(ctx)
defer cancel()
if err := s.client.RemoveObject(ctx, s.bucket, key, minio.RemoveObjectOptions{}); err != nil {
return classify(err)
}
return nil
}
// ObjectInfo is the subset of S3 metadata the reconciler needs.
type ObjectInfo struct {
Key string
Size int64
ContentType string
LastModified time.Time
}
// List returns every object under prefix. The reconciler uses it once per run;
// the HTTP path never lists the bucket.
func (s *Store) List(ctx context.Context, prefix string) ([]ObjectInfo, error) {
ctx, cancel := s.opCtx(ctx)
defer cancel()
result := make([]ObjectInfo, 0, 64)
for object := range s.client.ListObjects(ctx, s.bucket, minio.ListObjectsOptions{Prefix: prefix, Recursive: true}) {
if object.Err != nil {
return nil, classify(object.Err)
}
result = append(result, ObjectInfo{
Key: object.Key,
Size: object.Size,
ContentType: object.ContentType,
LastModified: object.LastModified,
})
}
return result, nil
}
// EnsureBucket creates the bucket if it is absent. It is safe to run
// concurrently and repeatedly: an already existing bucket is not an error.
// The caller uses administrative credentials; API credentials are not allowed
// to create buckets.
func (s *Store) EnsureBucket(ctx context.Context) (bool, error) {
ctx, cancel := s.opCtx(ctx)
defer cancel()
exists, err := s.client.BucketExists(ctx, s.bucket)
if err != nil {
return false, classify(err)
}
if exists {
return false, nil
}
if err := s.client.MakeBucket(ctx, s.bucket, minio.MakeBucketOptions{Region: s.region()}); err != nil {
response := minio.ToErrorResponse(err)
switch response.Code {
case "BucketAlreadyOwnedByYou", "BucketAlreadyExists":
return false, nil
}
return false, classify(err)
}
return true, nil
}
func (s *Store) region() string {
// minio-go keeps the region in an unexported field. Passing an empty
// region lets it discover us-east-1 for SeaweedFS; the explicit region is
// still set in the client options for signed requests.
return ""
}
// Probe writes, stats and removes a tiny object. It proves that the configured
// credentials can actually use the private bucket without leaving test data.
func (s *Store) Probe(ctx context.Context) error {
const key = "_bootstrap/probe"
ctx, cancel := s.opCtx(ctx)
defer cancel()
body := strings.NewReader("mtusi-lab4-bucket-probe")
if _, err := s.client.PutObject(ctx, s.bucket, key, body, int64(body.Len()), minio.PutObjectOptions{
ContentType: "text/plain",
PartSize: 5 << 20,
}); err != nil {
return classify(err)
}
if _, err := s.client.StatObject(ctx, s.bucket, key, minio.StatObjectOptions{}); err != nil {
return classify(err)
}
if err := s.client.RemoveObject(ctx, s.bucket, key, minio.RemoveObjectOptions{}); err != nil {
return classify(err)
}
return nil
}
// classify converts an S3/SDK error into the two dependency classes the HTTP
// layer understands. An access-denied or malformed-bucket error stays a plain
// error and becomes a generic 500: it is a server configuration defect, not a
// user error and not a transient outage.
func classify(err error) error {
if err == nil {
return nil
}
if errors.Is(err, context.DeadlineExceeded) || errors.Is(err, context.Canceled) {
return fmt.Errorf("%w: %w", ErrUnavailable, err)
}
var netErr net.Error
if errors.As(err, &netErr) {
return fmt.Errorf("%w: %w", ErrUnavailable, err)
}
response := minio.ToErrorResponse(err)
switch response.Code {
case "NoSuchKey", "NoSuchObject", "NotFound":
return ErrNotFound
case "NoSuchBucket", "SlowDown", "InternalError", "ServiceUnavailable", "XMinioServerNotInitialized":
return fmt.Errorf("%w: %s", ErrUnavailable, response.Code)
}
if response.StatusCode >= 500 {
return fmt.Errorf("%w: HTTP %d", ErrUnavailable, response.StatusCode)
}
return err
}
+151
View File
@@ -0,0 +1,151 @@
// Package session stores opaque server-side sessions in Valkey. The token is
// never persisted: only its SHA-256 hash is used as the cache key, so a cache
// dump does not contain credentials that can be replayed against the API.
//
// Valkey is the source of truth for sessions. It is configured with AOF
// persistence and a named volume, so valid sessions survive both the API
// process and the Valkey process restarting with volumes kept.
package session
import (
"context"
"encoding/json"
"errors"
"fmt"
"time"
"github.com/redis/go-redis/v9"
"mtusi.ru/messenger-lab4/internal/auth"
)
const keyPrefix = "mtusi:lab3:session:"
var (
// ErrInvalid means the token is unknown, expired or malformed.
ErrInvalid = errors.New("invalid session")
// ErrUnavailable means Valkey is not answering; the API must return a
// bounded 503 instead of trusting the bearer token.
ErrUnavailable = errors.New("session store unavailable")
)
type record struct {
UserID string `json:"user_id"`
ExpiresAt time.Time `json:"expires_at"`
}
// Options bound every network operation and the connection pool.
type Options struct {
PoolSize int
DialTimeout time.Duration
IOTimeout time.Duration
TTL time.Duration
}
// Store is a thin, timeout-aware wrapper around go-redis.
type Store struct {
client *redis.Client
ttl time.Duration
}
// Open parses CACHE_URL (redis:// or rediss://) without echoing it in errors.
// It does not require Valkey to be reachable at startup: /health/ready and
// login report the outage as 503.
func Open(rawURL string, options Options) (*Store, error) {
parsed, err := redis.ParseURL(rawURL)
if err != nil {
return nil, errors.New("CACHE_URL is not a valid Redis/Valkey URL")
}
if options.PoolSize <= 0 {
options.PoolSize = 8
}
if options.DialTimeout <= 0 {
options.DialTimeout = 2 * time.Second
}
if options.IOTimeout <= 0 {
options.IOTimeout = 2 * time.Second
}
if options.TTL <= 0 {
options.TTL = time.Hour
}
parsed.PoolSize = options.PoolSize
parsed.DialTimeout = options.DialTimeout
parsed.ReadTimeout = options.IOTimeout
parsed.WriteTimeout = options.IOTimeout
// One retry keeps a transient blip invisible while bounding the worst-case
// time a handler spends waiting for the cache.
parsed.MaxRetries = 1
parsed.MinRetryBackoff = 20 * time.Millisecond
parsed.MaxRetryBackoff = 100 * time.Millisecond
return &Store{client: redis.NewClient(parsed), ttl: options.TTL}, nil
}
// TTL exposes the configured session lifetime (used by tests and startup logs).
func (s *Store) TTL() time.Duration { return s.ttl }
// Create issues a new opaque token and stores the session with a TTL. The
// returned expiry is the absolute instant the client must treat as the end of
// the session; restarting a process does not extend it.
func (s *Store) Create(ctx context.Context, userID string) (token string, expiresAt time.Time, err error) {
token, err = auth.NewToken()
if err != nil {
return "", time.Time{}, fmt.Errorf("generate session token: %w", err)
}
// A whole number of microseconds keeps the value parseable by the
// Python 3.9 public client (its fromisoformat accepts 3 or 6 fractional
// digits, not Go's trimmed nanosecond form) while staying RFC 3339.
expiresAt = time.Now().UTC().Add(s.ttl).Truncate(time.Microsecond)
payload, err := json.Marshal(record{UserID: userID, ExpiresAt: expiresAt})
if err != nil {
return "", time.Time{}, fmt.Errorf("encode session: %w", err)
}
if err := s.client.Set(ctx, key(auth.TokenHash(token)), payload, s.ttl).Err(); err != nil {
return "", time.Time{}, fmt.Errorf("%w: %w", ErrUnavailable, err)
}
return token, expiresAt, nil
}
// Get resolves a token to a user id. Unknown, expired and corrupt records are
// all ErrInvalid; a transport failure is ErrUnavailable.
func (s *Store) Get(ctx context.Context, token string) (string, error) {
raw, err := s.client.Get(ctx, key(auth.TokenHash(token))).Bytes()
if errors.Is(err, redis.Nil) {
return "", ErrInvalid
}
if err != nil {
return "", fmt.Errorf("%w: %w", ErrUnavailable, err)
}
var value record
if err := json.Unmarshal(raw, &value); err != nil || value.UserID == "" {
return "", ErrInvalid
}
if !value.ExpiresAt.After(time.Now()) {
// TTL should already have removed the key; this also covers a clock
// adjustment or an externally imported record.
_ = s.client.Del(ctx, key(auth.TokenHash(token))).Err()
return "", ErrInvalid
}
return value.UserID, nil
}
// Delete revokes the session. Missing keys are not an error here: the caller
// has already authenticated the token, and a concurrent logout is harmless.
func (s *Store) Delete(ctx context.Context, token string) error {
if err := s.client.Del(ctx, key(auth.TokenHash(token))).Err(); err != nil {
return fmt.Errorf("%w: %w", ErrUnavailable, err)
}
return nil
}
// Ping is used by /health/ready and the startup log.
func (s *Store) Ping(ctx context.Context) error {
if err := s.client.Ping(ctx).Err(); err != nil {
return fmt.Errorf("%w: %w", ErrUnavailable, err)
}
return nil
}
// Close releases the connection pool.
func (s *Store) Close() error { return s.client.Close() }
func key(tokenHash string) string { return keyPrefix + tokenHash }
+184
View File
@@ -0,0 +1,184 @@
package store
import (
"context"
"errors"
"time"
"github.com/jackc/pgx/v5"
"mtusi.ru/messenger-lab4/internal/model"
)
// AttachmentRecord is the database view of an attachment. ObjectKey is an
// internal server detail and is never serialised into the public API.
type AttachmentRecord struct {
model.Attachment
ObjectKey string
}
// ReconcileAttachment is the minimal row the offline reconciler needs. It is
// intentionally not an API shape.
type ReconcileAttachment struct {
ID string
ObjectKey string
Status string
CreatedAt time.Time
UpdatedAt time.Time
}
// CreatePendingAttachment records the upload intent before the S3 PUT. If the
// process dies after this insert, the row is still accounted for and the
// reconciler can remove it after the grace period; it is never returned by the
// public API because only ready rows are visible.
func (s *Store) CreatePendingAttachment(ctx context.Context, record AttachmentRecord, createdAt time.Time) error {
ctx, cancel := s.opCtx(ctx)
defer cancel()
_, err := s.pool.Exec(ctx, `
INSERT INTO attachments
(id, chat_id, owner_id, filename, content_type, size_bytes, sha256,
status, error_code, object_key, created_at, updated_at)
VALUES ($1::uuid, $2::uuid, $3::uuid, $4, $5, $6, $7,
'pending', NULL, $8, $9, $9)`,
record.ID, record.ChatID, record.OwnerID, record.Filename,
record.ContentType, record.SizeBytes, record.SHA256, record.ObjectKey, createdAt,
)
return s.classify(err)
}
// MarkAttachmentReady promotes the pending row after the original bytes are in
// S3. If the update fails, the row stays pending and the object remains
// accounted; the reconciler owns the cleanup. Nothing is deleted here because
// an ambiguous commit must never destroy a successfully stored original.
func (s *Store) MarkAttachmentReady(ctx context.Context, id string, updatedAt time.Time) (time.Time, error) {
ctx, cancel := s.opCtx(ctx)
defer cancel()
var stored time.Time
err := s.pool.QueryRow(ctx, `
UPDATE attachments
SET status = 'ready', updated_at = $2
WHERE id = $1::uuid AND status = 'pending'
RETURNING updated_at`, id, updatedAt).Scan(&stored)
if errors.Is(err, pgx.ErrNoRows) {
return time.Time{}, ErrNotFound
}
if err != nil {
return time.Time{}, s.classify(err)
}
return stored.UTC(), nil
}
// ReadyAttachmentForUser applies the ACL in SQL: the row is returned only when
// the caller is a member of the attachment's chat and the attachment is ready.
// A foreign and a nonexistent attachment are indistinguishable.
func (s *Store) ReadyAttachmentForUser(ctx context.Context, attachmentID, userID string) (AttachmentRecord, error) {
ctx, cancel := s.opCtx(ctx)
defer cancel()
var record AttachmentRecord
var createdAt, updatedAt time.Time
err := s.pool.QueryRow(ctx, `
SELECT a.id::text, a.chat_id::text, a.owner_id::text, a.filename,
a.content_type, a.size_bytes, a.sha256, a.status, a.error_code,
a.object_key, a.created_at, a.updated_at
FROM attachments a
JOIN chat_members cm ON cm.chat_id = a.chat_id AND cm.user_id = $2::uuid
WHERE a.id = $1::uuid AND a.status = 'ready'`,
attachmentID, userID,
).Scan(&record.ID, &record.ChatID, &record.OwnerID, &record.Filename,
&record.ContentType, &record.SizeBytes, &record.SHA256, &record.Status, &record.ErrorCode,
&record.ObjectKey, &createdAt, &updatedAt)
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return AttachmentRecord{}, ErrNotFound
}
return AttachmentRecord{}, s.classify(err)
}
record.CreatedAt = model.Time{Time: createdAt.UTC()}
record.UpdatedAt = model.Time{Time: updatedAt.UTC()}
record.Variants = []model.Variant{}
return record, nil
}
// DeleteAttachmentRow removes a pending upload intent. It is used only after a
// failed S3 PUT or by the reconciler; ready rows are never deleted here.
func (s *Store) DeleteAttachmentRow(ctx context.Context, id string) error {
ctx, cancel := s.opCtx(ctx)
defer cancel()
_, err := s.pool.Exec(ctx, `DELETE FROM attachments WHERE id = $1::uuid`, id)
return s.classify(err)
}
// ListAttachmentsForReconcile returns every row, including internal pending
// upload intents. Only the offline reconciler calls it.
func (s *Store) ListAttachmentsForReconcile(ctx context.Context) ([]ReconcileAttachment, error) {
ctx, cancel := s.opCtx(ctx)
defer cancel()
rows, err := s.pool.Query(ctx, `
SELECT id::text, object_key, status, created_at, updated_at
FROM attachments
ORDER BY created_at, id`)
if err != nil {
return nil, s.classify(err)
}
defer rows.Close()
result := make([]ReconcileAttachment, 0, 128)
for rows.Next() {
var item ReconcileAttachment
if err := rows.Scan(&item.ID, &item.ObjectKey, &item.Status, &item.CreatedAt, &item.UpdatedAt); err != nil {
return nil, s.classify(err)
}
result = append(result, item)
}
if err := rows.Err(); err != nil {
return nil, s.classify(err)
}
return result, nil
}
// AttachmentByObjectKey reports whether a row still references the key. The
// reconciler re-checks this immediately before deleting an object, so a
// concurrent upload that committed between the snapshot and the delete is not
// destroyed.
func (s *Store) AttachmentByObjectKey(ctx context.Context, key string) (bool, error) {
ctx, cancel := s.opCtx(ctx)
defer cancel()
var exists bool
if err := s.pool.QueryRow(ctx,
`SELECT EXISTS (SELECT 1 FROM attachments WHERE object_key = $1)`, key).Scan(&exists); err != nil {
return false, s.classify(err)
}
return exists, nil
}
// AttachmentState re-reads the status and key before a mutation. A pending row
// that became ready while the reconciler was scanning must not be deleted.
func (s *Store) AttachmentState(ctx context.Context, id string) (string, string, time.Time, error) {
ctx, cancel := s.opCtx(ctx)
defer cancel()
var status, objectKey string
var updatedAt time.Time
err := s.pool.QueryRow(ctx,
`SELECT status, object_key, updated_at FROM attachments WHERE id = $1::uuid`, id,
).Scan(&status, &objectKey, &updatedAt)
if errors.Is(err, pgx.ErrNoRows) {
return "", "", time.Time{}, ErrNotFound
}
if err != nil {
return "", "", time.Time{}, s.classify(err)
}
return status, objectKey, updatedAt.UTC(), nil
}
// DeleteAttachmentIfPending deletes the row only while it is still pending.
// The status predicate is the last line of defence against deleting a row that
// a concurrent request has already promoted to ready.
func (s *Store) DeleteAttachmentIfPending(ctx context.Context, id string) (bool, error) {
ctx, cancel := s.opCtx(ctx)
defer cancel()
tag, err := s.pool.Exec(ctx,
`DELETE FROM attachments WHERE id = $1::uuid AND status = 'pending'`, id)
if err != nil {
return false, s.classify(err)
}
return tag.RowsAffected() == 1, nil
}
+139
View File
@@ -0,0 +1,139 @@
package store
import (
"context"
"crypto/sha256"
"embed"
"encoding/hex"
"errors"
"fmt"
"io/fs"
"sort"
"strconv"
"strings"
"github.com/jackc/pgx/v5"
)
//go:embed migrations/*.sql
var migrationFiles embed.FS
// advisoryLockKey is a fixed application-wide key. pg_advisory_lock serialises
// concurrent API replicas that start at the same time; it is released when the
// dedicated connection is returned or the session ends.
const advisoryLockKey int64 = 0x6d74756c616233 // "mtulab3"
type migration struct {
version int
name string
checksum string
sql string
}
// Migrate applies every embedded migration exactly once and records its
// checksum. Re-running it is a no-op, which is what the restart hook relies on.
// A changed migration file is a startup error rather than a silent divergence.
func (s *Store) Migrate(ctx context.Context) error {
conn, err := s.pool.Acquire(ctx)
if err != nil {
return s.classify(err)
}
defer conn.Release()
if _, err := conn.Exec(ctx, `SELECT pg_advisory_lock($1)`, advisoryLockKey); err != nil {
return s.classify(err)
}
defer func() {
// Use a background context: the request context may already be
// cancelled when a startup timeout fires, but the lock still has to be
// released explicitly before the connection is returned to the pool.
_, _ = conn.Exec(context.Background(), `SELECT pg_advisory_unlock($1)`, advisoryLockKey)
}()
if _, err := conn.Exec(ctx, `
CREATE TABLE IF NOT EXISTS schema_migrations (
version integer PRIMARY KEY,
name text NOT NULL,
checksum text NOT NULL,
applied_at timestamptz NOT NULL DEFAULT now()
)`); err != nil {
return s.classify(err)
}
migrations, err := loadMigrations()
if err != nil {
return err
}
for _, item := range migrations {
var existing string
err := conn.QueryRow(ctx, `SELECT checksum FROM schema_migrations WHERE version = $1`, item.version).Scan(&existing)
switch {
case err == nil:
if existing != item.checksum {
return fmt.Errorf("migration %04d_%s was modified after it was applied", item.version, item.name)
}
continue
case !errors.Is(err, pgx.ErrNoRows):
return s.classify(err)
}
tx, err := conn.Begin(ctx)
if err != nil {
return s.classify(err)
}
if _, err := tx.Exec(ctx, item.sql); err != nil {
_ = tx.Rollback(context.Background())
return fmt.Errorf("apply migration %04d_%s: %w", item.version, item.name, err)
}
if _, err := tx.Exec(ctx,
`INSERT INTO schema_migrations (version, name, checksum) VALUES ($1, $2, $3)`,
item.version, item.name, item.checksum,
); err != nil {
_ = tx.Rollback(context.Background())
return s.classify(err)
}
if err := tx.Commit(ctx); err != nil {
return s.classify(err)
}
}
return nil
}
func loadMigrations() ([]migration, error) {
entries, err := fs.ReadDir(migrationFiles, "migrations")
if err != nil {
return nil, err
}
items := make([]migration, 0, len(entries))
for _, entry := range entries {
if entry.IsDir() || !strings.HasSuffix(entry.Name(), ".sql") {
continue
}
name := entry.Name()
if len(name) < 9 {
return nil, fmt.Errorf("migration %q has no NNNN_ prefix", name)
}
version, err := strconv.Atoi(name[:4])
if err != nil {
return nil, fmt.Errorf("migration %q has no numeric prefix", name)
}
data, err := migrationFiles.ReadFile("migrations/" + name)
if err != nil {
return nil, err
}
sum := sha256.Sum256(data)
items = append(items, migration{
version: version,
name: strings.TrimSuffix(name[5:], ".sql"),
checksum: hex.EncodeToString(sum[:]),
sql: string(data),
})
}
sort.Slice(items, func(i, j int) bool { return items[i].version < items[j].version })
for i := 1; i < len(items); i++ {
if items[i].version == items[i-1].version {
return nil, fmt.Errorf("duplicate migration version %d", items[i].version)
}
}
return items, nil
}
+71
View File
@@ -0,0 +1,71 @@
package store
import (
"strings"
"testing"
)
func TestLoadMigrations(t *testing.T) {
migrations, err := loadMigrations()
if err != nil {
t.Fatalf("loadMigrations: %v", err)
}
if len(migrations) != 5 {
t.Fatalf("loaded %d migrations, want 5", len(migrations))
}
for index, item := range migrations {
if item.version != index+1 {
t.Fatalf("migration order at %d = %d", index, item.version)
}
}
for _, item := range migrations {
if len(item.checksum) != 64 {
t.Fatalf("checksum for %d has length %d", item.version, len(item.checksum))
}
lower := strings.ToLower(item.sql)
if !strings.Contains(lower, "create ") && !strings.Contains(lower, "alter ") {
t.Fatalf("migration %d has no schema statements", item.version)
}
}
// The checksum must be stable across process runs: it is what detects an
// edited migration after it has been applied.
again, err := loadMigrations()
if err != nil {
t.Fatal(err)
}
for index := range migrations {
if migrations[index].checksum != again[index].checksum {
t.Fatal("migration checksums are not deterministic")
}
}
}
func TestMigrationsContainRequiredDomainObjects(t *testing.T) {
migrations, err := loadMigrations()
if err != nil {
t.Fatal(err)
}
all := ""
for _, item := range migrations {
all += item.sql
}
for _, required := range []string{
"CREATE TABLE users",
"CREATE TABLE chats",
"CREATE TABLE chat_members",
"CREATE TABLE messages",
"CREATE UNIQUE INDEX users_username_key",
"messages_sender_membership_fk",
"messages_chat_created_id_idx",
"CREATE TABLE message_idempotency",
"PRIMARY KEY (user_id, method, path, key)",
"CREATE TABLE attachments",
"CREATE TABLE message_attachments",
"attachments_object_key_unique",
"message_attachments_attachment_chat_fk",
} {
if !strings.Contains(all, required) {
t.Fatalf("migrations do not contain %q", required)
}
}
}
+54
View File
@@ -0,0 +1,54 @@
-- Lab2 schema. PostgreSQL is the source of truth for users, chats, chat
-- membership and messages. Sessions intentionally live in Valkey with a TTL.
CREATE TABLE users (
id uuid PRIMARY KEY,
username text NOT NULL,
display_name text NOT NULL,
password_hash text NOT NULL,
created_at timestamptz NOT NULL,
CONSTRAINT users_username_format
CHECK (username ~ '^[a-z0-9_]{3,32}$'),
CONSTRAINT users_display_name_length
CHECK (char_length(display_name) BETWEEN 1 AND 100),
CONSTRAINT users_password_hash_present
CHECK (length(password_hash) > 0)
);
-- Uniqueness is enforced by the database, not by a read-then-insert check, so
-- two concurrent registrations of the same username cannot both succeed.
CREATE UNIQUE INDEX users_username_key ON users (username);
CREATE TABLE chats (
id uuid PRIMARY KEY,
title text NOT NULL,
created_at timestamptz NOT NULL,
CONSTRAINT chats_title_length
CHECK (char_length(title) BETWEEN 1 AND 100)
);
CREATE TABLE chat_members (
chat_id uuid NOT NULL REFERENCES chats (id) ON DELETE CASCADE,
user_id uuid NOT NULL REFERENCES users (id),
position integer NOT NULL,
PRIMARY KEY (chat_id, user_id),
CONSTRAINT chat_members_position_nonnegative CHECK (position >= 0)
);
-- "Chats of the current user" walks chat_members by user_id.
CREATE INDEX chat_members_user_chat_idx ON chat_members (user_id, chat_id);
CREATE TABLE messages (
id uuid PRIMARY KEY,
chat_id uuid NOT NULL,
sender_id uuid NOT NULL,
text text NOT NULL,
created_at timestamptz NOT NULL,
CONSTRAINT messages_text_length
CHECK (char_length(text) BETWEEN 1 AND 4000),
CONSTRAINT messages_chat_fk
FOREIGN KEY (chat_id) REFERENCES chats (id) ON DELETE CASCADE,
-- The sender must be a member of the chat at the database level too, not
-- only in the HTTP handler.
CONSTRAINT messages_sender_membership_fk
FOREIGN KEY (chat_id, sender_id) REFERENCES chat_members (chat_id, user_id)
);
@@ -0,0 +1,15 @@
-- Indexes justified by the two keyset queries of the contract.
--
-- Message history:
-- WHERE chat_id = $1 AND (created_at, id) > ($2, $3)
-- ORDER BY created_at, id LIMIT $4
-- The three-column index lets PostgreSQL start at the cursor position inside
-- one chat instead of scanning the whole history for every page.
CREATE INDEX messages_chat_created_id_idx
ON messages (chat_id, created_at, id);
-- Chat list:
-- ORDER BY created_at, id LIMIT $1
-- after joining chat_members for the current user.
CREATE INDEX chats_created_id_idx
ON chats (created_at, id);
@@ -0,0 +1,28 @@
-- Lab3: shared idempotency records for POST /api/v1/chats/{chat_id}/messages.
--
-- The primary key is exactly the contract scope: acting user + HTTP method +
-- chat message path + Idempotency-Key. Different users or chats may reuse the
-- same key independently. request_hash lets a replay distinguish the same
-- semantic body (201 + original message) from a different body (409).
--
-- A row is written in the same transaction as the message it references, so a
-- committed row always has a committed message and an aborted request leaves
-- neither. created_at supports the 24-hour retention prune; contract requires
-- at least 24 h, this stand prunes only records older than that bound.
CREATE TABLE message_idempotency (
user_id uuid NOT NULL REFERENCES users (id) ON DELETE CASCADE,
method text NOT NULL,
path text NOT NULL,
key text NOT NULL,
request_hash bytea NOT NULL,
message_id uuid NOT NULL REFERENCES messages (id) ON DELETE CASCADE,
created_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (user_id, method, path, key),
CONSTRAINT message_idempotency_method_post CHECK (method = 'POST'),
CONSTRAINT message_idempotency_key_length CHECK (char_length(key) BETWEEN 1 AND 128),
CONSTRAINT message_idempotency_path_length CHECK (char_length(path) BETWEEN 1 AND 256)
);
-- Retention housekeeping walks old rows; new inserts stay cheap.
CREATE INDEX message_idempotency_created_at_idx
ON message_idempotency (created_at);
@@ -0,0 +1,75 @@
-- Lab4: attachment metadata lives in PostgreSQL; the original bytes live in
-- the private S3 bucket. The only public state in the mandatory lab4 contract
-- is ready. pending exists solely as an internal, server-side upload intent:
-- it is written before the S3 PUT and promoted in the same request after the
-- PUT. A crash or a database failure between the two steps therefore leaves an
-- accounted row, never an anonymous object. The reconciler removes stale
-- pending rows and their objects after a documented grace period.
CREATE TABLE attachments (
id uuid PRIMARY KEY,
chat_id uuid NOT NULL REFERENCES chats (id) ON DELETE CASCADE,
owner_id uuid NOT NULL REFERENCES users (id),
filename text NOT NULL,
content_type text NOT NULL,
size_bytes bigint NOT NULL,
sha256 text NOT NULL,
status text NOT NULL,
error_code text,
object_key text NOT NULL,
created_at timestamptz NOT NULL,
updated_at timestamptz NOT NULL,
CONSTRAINT attachments_filename_length
CHECK (char_length(filename) BETWEEN 1 AND 255),
CONSTRAINT attachments_content_type
CHECK (content_type IN ('image/png', 'image/jpeg')),
CONSTRAINT attachments_size
CHECK (size_bytes BETWEEN 1 AND 10485760),
CONSTRAINT attachments_sha256
CHECK (sha256 ~ '^[a-f0-9]{64}$'),
CONSTRAINT attachments_status
CHECK (status IN ('pending', 'ready')),
CONSTRAINT attachments_ready_error
CHECK ((status = 'ready' AND error_code IS NULL) OR status = 'pending'),
CONSTRAINT attachments_object_key
CHECK (object_key LIKE 'attachments/%'),
CONSTRAINT attachments_object_key_unique UNIQUE (object_key),
-- Referenced by the composite foreign key of message_attachments so the
-- database itself rejects a link to an attachment of another chat.
CONSTRAINT attachments_id_chat_unique UNIQUE (id, chat_id)
);
-- The only attachment query on the hot path is "attachment of this chat".
CREATE INDEX attachments_chat_created_idx
ON attachments (chat_id, created_at, id);
-- The reconciler scans all rows by state and age. It never runs on the HTTP
-- hot path.
CREATE INDEX attachments_status_updated_idx
ON attachments (status, updated_at);
-- messages.id is already the primary key; this unique constraint is the
-- target required by the composite foreign keys below, not a second identity.
-- It must exist before the foreign key that references (id, chat_id).
ALTER TABLE messages
ADD CONSTRAINT messages_id_chat_unique UNIQUE (id, chat_id);
-- A message and its attachment links share one transaction. The composite
-- foreign keys make "file of another chat" impossible at the database level
-- even if a future handler forgets the application check.
CREATE TABLE message_attachments (
message_id uuid NOT NULL,
attachment_id uuid NOT NULL,
chat_id uuid NOT NULL,
position integer NOT NULL,
PRIMARY KEY (message_id, attachment_id),
CONSTRAINT message_attachments_position_unique UNIQUE (message_id, position),
CONSTRAINT message_attachments_position_nonnegative CHECK (position >= 0),
CONSTRAINT message_attachments_message_chat_fk
FOREIGN KEY (message_id, chat_id) REFERENCES messages (id, chat_id) ON DELETE CASCADE,
CONSTRAINT message_attachments_attachment_chat_fk
FOREIGN KEY (attachment_id, chat_id) REFERENCES attachments (id, chat_id)
);
-- Reconciler lookup: "is this object key still referenced by any row?".
CREATE INDEX message_attachments_attachment_idx
ON message_attachments (attachment_id);
@@ -0,0 +1,10 @@
-- Lab4 contract: a message may carry text = "" when it references at least one
-- attachment of the chat (contracts/README.md, "Вложения"). The HTTP handler
-- still rejects empty or blank text without attachments; the database
-- constraint only widens to permit the documented attachment-only message.
ALTER TABLE messages
DROP CONSTRAINT messages_text_length;
ALTER TABLE messages
ADD CONSTRAINT messages_text_length
CHECK (char_length(text) BETWEEN 0 AND 4000);
+702
View File
@@ -0,0 +1,702 @@
// Package store is the PostgreSQL repository. Every statement uses positional
// parameters; identifiers are never interpolated into SQL. The pool is
// bounded and every operation carries a context timeout.
package store
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"net"
"strconv"
"strings"
"time"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/jackc/puddle/v2"
"mtusi.ru/messenger-lab4/internal/cursor"
"mtusi.ru/messenger-lab4/internal/model"
"mtusi.ru/messenger-lab4/internal/uuid"
)
// Domain errors. The HTTP layer maps them to the contract's status codes.
var (
ErrNotFound = errors.New("object not found")
ErrUsernameTaken = errors.New("username already taken")
ErrUnknownMember = errors.New("unknown chat member")
ErrUnavailable = errors.New("database unavailable")
ErrIdempotencyConflict = errors.New("idempotency key reused with a different request body")
ErrAttachmentNotReady = errors.New("attachment is not ready")
)
// Options bounds the pool and every query. Zero values fall back to safe
// defaults so the store is still testable from small programs.
type Options struct {
MaxConns int32
MinConns int32
ConnectTimeout time.Duration
StatementTimeout time.Duration
QueryTimeout time.Duration
}
// Store owns a bounded pgx pool.
type Store struct {
pool *pgxpool.Pool
queryTimeout time.Duration
}
// Open parses the DSN and creates the pool. Parse errors deliberately do not
// echo the DSN: it contains the database password.
func Open(ctx context.Context, dsn string, options Options) (*Store, error) {
config, err := pgxpool.ParseConfig(dsn)
if err != nil {
return nil, errors.New("DATABASE_URL is not a valid PostgreSQL URL")
}
applyDefaults(&options)
config.MaxConns = options.MaxConns
config.MinConns = options.MinConns
config.MaxConnLifetime = 30 * time.Minute
config.MaxConnIdleTime = 5 * time.Minute
config.HealthCheckPeriod = 30 * time.Second
config.ConnConfig.ConnectTimeout = options.ConnectTimeout
config.ConnConfig.RuntimeParams["application_name"] = "messenger-lab4"
// A statement timeout in the server session is the last line of defence
// against a runaway query; the caller's context is the first.
config.ConnConfig.RuntimeParams["statement_timeout"] = strconv.FormatInt(options.StatementTimeout.Milliseconds(), 10)
pool, err := pgxpool.NewWithConfig(ctx, config)
if err != nil {
return nil, fmt.Errorf("create PostgreSQL pool: %w", err)
}
return &Store{pool: pool, queryTimeout: options.QueryTimeout}, nil
}
func applyDefaults(options *Options) {
if options.MaxConns <= 0 {
options.MaxConns = 8
}
if options.MinConns < 0 {
options.MinConns = 0
}
if options.MinConns > options.MaxConns {
options.MinConns = options.MaxConns
}
if options.ConnectTimeout <= 0 {
options.ConnectTimeout = 3 * time.Second
}
if options.StatementTimeout <= 0 {
options.StatementTimeout = 3 * time.Second
}
if options.QueryTimeout <= 0 {
options.QueryTimeout = 3 * time.Second
}
}
// Ping is used by /health/ready and by the startup readiness loop.
func (s *Store) Ping(ctx context.Context) error {
return s.pool.Ping(ctx)
}
// Close waits for in-flight queries and closes the pool.
func (s *Store) Close() { s.pool.Close() }
func (s *Store) opCtx(ctx context.Context) (context.Context, context.CancelFunc) {
if s.queryTimeout <= 0 {
return ctx, func() {}
}
return context.WithTimeout(ctx, s.queryTimeout)
}
// classify separates a dependency outage (contract 503 unavailable) from a
// genuine application bug (500 internal_error). Only the error class is mapped;
// the original error is logged server-side and never sent to a client.
func (s *Store) classify(err error) error {
if err == nil {
return nil
}
if errors.Is(err, pgx.ErrNoRows) {
return ErrNotFound
}
if errors.Is(err, context.DeadlineExceeded) || errors.Is(err, context.Canceled) {
return fmt.Errorf("%w: %w", ErrUnavailable, err)
}
var pgErr *pgconn.PgError
if errors.As(err, &pgErr) {
switch {
case strings.HasPrefix(pgErr.Code, "08"), // connection exception
pgErr.Code == "57P01", // admin shutdown
pgErr.Code == "57P02", // crash shutdown
pgErr.Code == "57P03", // cannot connect now
pgErr.Code == "57014", // query cancelled (statement_timeout)
strings.HasPrefix(pgErr.Code, "53"): // insufficient resources
return fmt.Errorf("%w: %w", ErrUnavailable, err)
}
return err
}
if errors.Is(err, puddle.ErrClosedPool) || errors.Is(err, io.EOF) || errors.Is(err, io.ErrUnexpectedEOF) {
return fmt.Errorf("%w: %w", ErrUnavailable, err)
}
var netErr net.Error
if errors.As(err, &netErr) {
return fmt.Errorf("%w: %w", ErrUnavailable, err)
}
return err
}
func isUniqueViolation(err error) bool {
var pgErr *pgconn.PgError
return errors.As(err, &pgErr) && pgErr.Code == "23505" && pgErr.ConstraintName == "users_username_key"
}
func isForeignKeyViolation(err error) bool {
var pgErr *pgconn.PgError
return errors.As(err, &pgErr) && pgErr.Code == "23503"
}
func isIdempotencyViolation(err error) bool {
var pgErr *pgconn.PgError
return errors.As(err, &pgErr) && pgErr.Code == "23505" &&
pgErr.ConstraintName == "message_idempotency_pkey"
}
// CreateUser inserts a user and relies on the unique index for both ordinary
// duplicates and concurrent registrations of the same username.
func (s *Store) CreateUser(ctx context.Context, username, displayName, passwordHash string) (model.User, error) {
ctx, cancel := s.opCtx(ctx)
defer cancel()
id := uuid.New()
createdAt := time.Now().UTC()
var stored time.Time
err := s.pool.QueryRow(ctx, `
INSERT INTO users (id, username, display_name, password_hash, created_at)
VALUES ($1::uuid, $2, $3, $4, $5)
RETURNING created_at`,
id, username, displayName, passwordHash, createdAt,
).Scan(&stored)
if err != nil {
if isUniqueViolation(err) {
return model.User{}, ErrUsernameTaken
}
return model.User{}, s.classify(err)
}
return model.User{
ID: id,
Username: username,
DisplayName: displayName,
CreatedAt: model.Time{Time: stored.UTC()},
}, nil
}
// UserByUsername returns the public user and the Argon2id hash. The hash is
// used only by the login handler and is never serialised.
func (s *Store) UserByUsername(ctx context.Context, username string) (model.User, string, error) {
ctx, cancel := s.opCtx(ctx)
defer cancel()
var user model.User
var passwordHash string
var createdAt time.Time
err := s.pool.QueryRow(ctx, `
SELECT id::text, username, display_name, password_hash, created_at
FROM users WHERE username = $1`, username,
).Scan(&user.ID, &user.Username, &user.DisplayName, &passwordHash, &createdAt)
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return model.User{}, "", ErrNotFound
}
return model.User{}, "", s.classify(err)
}
user.CreatedAt = model.Time{Time: createdAt.UTC()}
return user, passwordHash, nil
}
// UserByID resolves the identity stored in a server-side session.
func (s *Store) UserByID(ctx context.Context, id string) (model.User, error) {
ctx, cancel := s.opCtx(ctx)
defer cancel()
var user model.User
var createdAt time.Time
err := s.pool.QueryRow(ctx, `
SELECT id::text, username, display_name, created_at
FROM users WHERE id = $1::uuid`, id,
).Scan(&user.ID, &user.Username, &user.DisplayName, &createdAt)
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return model.User{}, ErrNotFound
}
return model.User{}, s.classify(err)
}
user.CreatedAt = model.Time{Time: createdAt.UTC()}
return user, nil
}
// CreateChat inserts the chat and its membership in one transaction. A caller
// cannot observe a chat without members: either both are committed or neither.
func (s *Store) CreateChat(ctx context.Context, title string, memberIDs []string, callerID string) (model.Chat, error) {
ctx, cancel := s.opCtx(ctx)
defer cancel()
tx, err := s.pool.Begin(ctx)
if err != nil {
return model.Chat{}, s.classify(err)
}
defer func() { _ = tx.Rollback(context.Background()) }()
var existing int
if err := tx.QueryRow(ctx, `
SELECT count(*) FROM users
WHERE id IN (SELECT value::uuid FROM unnest($1::text[]) AS value)`, memberIDs,
).Scan(&existing); err != nil {
return model.Chat{}, s.classify(err)
}
if existing != len(memberIDs) {
return model.Chat{}, ErrUnknownMember
}
id := uuid.New()
createdAt := time.Now().UTC()
var stored time.Time
if err := tx.QueryRow(ctx, `
INSERT INTO chats (id, title, created_at) VALUES ($1::uuid, $2, $3)
RETURNING created_at`, id, title, createdAt,
).Scan(&stored); err != nil {
return model.Chat{}, s.classify(err)
}
batch := &pgx.Batch{}
for position, memberID := range memberIDs {
batch.Queue(`INSERT INTO chat_members (chat_id, user_id, position) VALUES ($1::uuid, $2::uuid, $3)`,
id, memberID, position)
}
results := tx.SendBatch(ctx, batch)
for range memberIDs {
if _, err := results.Exec(); err != nil {
_ = results.Close()
if isForeignKeyViolation(err) {
return model.Chat{}, ErrUnknownMember
}
return model.Chat{}, s.classify(err)
}
}
if err := results.Close(); err != nil {
return model.Chat{}, s.classify(err)
}
if err := tx.Commit(ctx); err != nil {
return model.Chat{}, s.classify(err)
}
return model.Chat{
ID: id,
Title: title,
MemberIDs: append([]string(nil), memberIDs...),
CreatedAt: model.Time{Time: stored.UTC()},
}, nil
}
// IsChatMember is used before parsing query parameters so a foreign chat is
// always 404, independent of the submitted cursor or limit.
func (s *Store) IsChatMember(ctx context.Context, chatID, userID string) (bool, error) {
ctx, cancel := s.opCtx(ctx)
defer cancel()
var member bool
err := s.pool.QueryRow(ctx, `
SELECT EXISTS (
SELECT 1 FROM chat_members WHERE chat_id = $1::uuid AND user_id = $2::uuid
)`, chatID, userID).Scan(&member)
if err != nil {
return false, s.classify(err)
}
return member, nil
}
// ChatForUser returns a chat only when the user is a member. A missing chat and
// a foreign chat are indistinguishable to the caller.
func (s *Store) ChatForUser(ctx context.Context, chatID, userID string) (model.Chat, error) {
ctx, cancel := s.opCtx(ctx)
defer cancel()
var chat model.Chat
var createdAt time.Time
err := s.pool.QueryRow(ctx, `
SELECT c.id::text, c.title, c.created_at,
array_agg(cm.user_id::text ORDER BY cm.position)
FROM chats c
JOIN chat_members me ON me.chat_id = c.id AND me.user_id = $2::uuid
JOIN chat_members cm ON cm.chat_id = c.id
WHERE c.id = $1::uuid
GROUP BY c.id`, chatID, userID,
).Scan(&chat.ID, &chat.Title, &createdAt, &chat.MemberIDs)
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return model.Chat{}, ErrNotFound
}
return model.Chat{}, s.classify(err)
}
chat.CreatedAt = model.Time{Time: createdAt.UTC()}
return chat, nil
}
const chatsPageSelect = `
SELECT c.id::text, c.title, c.created_at,
array_agg(cm.user_id::text ORDER BY cm.position)
FROM chats c
JOIN chat_members me ON me.chat_id = c.id AND me.user_id = $1::uuid
JOIN chat_members cm ON cm.chat_id = c.id`
// Chats returns one keyset page of chats visible to the user.
func (s *Store) Chats(ctx context.Context, userID string, position *cursor.Cursor, limit int) (model.ChatPage, error) {
ctx, cancel := s.opCtx(ctx)
defer cancel()
query := chatsPageSelect + `
GROUP BY c.id
ORDER BY c.created_at, c.id
LIMIT $2`
args := []any{userID, limit + 1}
if position != nil {
query = chatsPageSelect + `
WHERE (c.created_at, c.id) > ($2::timestamptz, $3::uuid)
GROUP BY c.id
ORDER BY c.created_at, c.id
LIMIT $4`
args = []any{userID, position.At, position.ID, limit + 1}
}
rows, err := s.pool.Query(ctx, query, args...)
if err != nil {
return model.ChatPage{}, s.classify(err)
}
defer rows.Close()
items := make([]model.Chat, 0, limit)
for rows.Next() {
var chat model.Chat
var createdAt time.Time
if err := rows.Scan(&chat.ID, &chat.Title, &createdAt, &chat.MemberIDs); err != nil {
return model.ChatPage{}, s.classify(err)
}
chat.CreatedAt = model.Time{Time: createdAt.UTC()}
items = append(items, chat)
}
if err := rows.Err(); err != nil {
return model.ChatPage{}, s.classify(err)
}
page := model.ChatPage{Items: items}
if len(items) > limit {
page.Items = items[:limit]
next := cursor.ForChat(page.Items[len(page.Items)-1])
page.NextCursor = &next
}
return page, nil
}
// PoolStats is a point-in-time snapshot of the bounded pgx pool. It is used
// only by the operator-only metrics listener, never by the public API.
type PoolStats struct {
MaxConns int32 `json:"max_conns"`
TotalConns int32 `json:"total_conns"`
AcquiredConns int32 `json:"acquired_conns"`
IdleConns int32 `json:"idle_conns"`
EmptyAcquireCount int64 `json:"empty_acquire_count"`
CanceledAcquireCount int64 `json:"canceled_acquire_count"`
AcquireCount int64 `json:"acquire_count"`
AcquireDurationMillis int64 `json:"acquire_duration_ms_total"`
NewConnsCount int64 `json:"new_conns_count"`
MaxLifetimeDestroyCount int64 `json:"max_lifetime_destroy_count"`
MaxIdleDestroyCount int64 `json:"max_idle_destroy_count"`
}
// PoolStats reports saturation signals for the connection pool. EmptyAcquire
// Count is the number of calls that had to wait for a free connection; a fast
// rising value while the API CPU is below its limit points at the database or
// the pool size, not at the HTTP layer.
func (s *Store) PoolStats() PoolStats {
stat := s.pool.Stat()
return PoolStats{
MaxConns: stat.MaxConns(),
TotalConns: stat.TotalConns(),
AcquiredConns: stat.AcquiredConns(),
IdleConns: stat.IdleConns(),
EmptyAcquireCount: stat.EmptyAcquireCount(),
CanceledAcquireCount: stat.CanceledAcquireCount(),
AcquireCount: stat.AcquireCount(),
AcquireDurationMillis: stat.AcquireDuration().Milliseconds(),
NewConnsCount: stat.NewConnsCount(),
MaxLifetimeDestroyCount: stat.MaxLifetimeDestroyCount(),
MaxIdleDestroyCount: stat.MaxIdleDestroyCount(),
}
}
// CreateMessageIdempotent appends a message, its attachment links and the
// idempotency result in one PostgreSQL transaction. A committed transaction
// therefore always contains the message, every link and the key record; a
// failed one contains none of them. The idempotency unique index serialises
// concurrent replays: the loser blocks, then rolls back and reads the committed
// winner, so a concurrent repeat can never create a second message.
//
// Behavior derived from contracts/README.md:
// - a new (user, method, path, key) creates a message and its record, 201;
// - the same semantic body replays the stored message and links, 201;
// - a different body with the same key is a conflict, 409;
// - a transient failure touches neither table, so the client may safely
// retry the same key and never observe a duplicate side effect.
func (s *Store) CreateMessageIdempotent(ctx context.Context, chatID, senderID, method, path, key string, requestHash []byte, text string, attachmentIDs []string) (model.Message, bool, error) {
if attachmentIDs == nil {
attachmentIDs = []string{}
}
message := model.Message{
ID: uuid.New(),
ChatID: chatID,
SenderID: senderID,
Text: text,
// A non-nil empty slice is required: the public Message schema has
// attachment_ids: [] as an array, never null.
AttachmentIDs: append([]string{}, attachmentIDs...),
}
ctx, cancel := s.opCtx(ctx)
defer cancel()
tx, err := s.pool.Begin(ctx)
if err != nil {
return model.Message{}, false, s.classify(err)
}
defer func() { _ = tx.Rollback(context.Background()) }()
// Validate every attachment against the message chat before writing any
// row. The composite foreign key is the second line of defence; this query
// lets the handler distinguish "foreign/unknown" (404) from "not ready"
// (409) without leaking whether a foreign attachment id exists.
if len(attachmentIDs) > 0 {
rows, queryErr := tx.Query(ctx, `
SELECT id::text, status
FROM attachments
WHERE chat_id = $1::uuid
AND id IN (SELECT value::uuid FROM unnest($2::text[]) AS value)`,
chatID, attachmentIDs)
if queryErr != nil {
return model.Message{}, false, s.classify(queryErr)
}
statuses := make(map[string]string, len(attachmentIDs))
for rows.Next() {
var id, status string
if scanErr := rows.Scan(&id, &status); scanErr != nil {
rows.Close()
return model.Message{}, false, s.classify(scanErr)
}
statuses[id] = status
}
if rows.Err() != nil {
rows.Close()
return model.Message{}, false, s.classify(rows.Err())
}
rows.Close()
if len(statuses) != len(attachmentIDs) {
return model.Message{}, false, ErrNotFound
}
for _, status := range statuses {
if status != "ready" {
return model.Message{}, false, ErrAttachmentNotReady
}
}
}
created := time.Now().UTC()
var stored time.Time
err = tx.QueryRow(ctx, `
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
VALUES ($1::uuid, $2::uuid, $3::uuid, $4, $5)
RETURNING created_at`,
message.ID, chatID, senderID, text, created,
).Scan(&stored)
if err != nil {
if isForeignKeyViolation(err) {
return model.Message{}, false, ErrNotFound
}
return model.Message{}, false, s.classify(err)
}
if len(attachmentIDs) > 0 {
batch := &pgx.Batch{}
for position, attachmentID := range attachmentIDs {
batch.Queue(`
INSERT INTO message_attachments (message_id, attachment_id, chat_id, position)
VALUES ($1::uuid, $2::uuid, $3::uuid, $4)`,
message.ID, attachmentID, chatID, position)
}
results := tx.SendBatch(ctx, batch)
for range attachmentIDs {
if _, execErr := results.Exec(); execErr != nil {
_ = results.Close()
if isForeignKeyViolation(execErr) {
return model.Message{}, false, ErrNotFound
}
return model.Message{}, false, s.classify(execErr)
}
}
if closeErr := results.Close(); closeErr != nil {
if isForeignKeyViolation(closeErr) {
return model.Message{}, false, ErrNotFound
}
return model.Message{}, false, s.classify(closeErr)
}
}
_, err = tx.Exec(ctx, `
INSERT INTO message_idempotency
(user_id, method, path, key, request_hash, message_id, created_at)
VALUES ($1::uuid, $2, $3, $4, $5, $6::uuid, $7)`,
senderID, method, path, key, requestHash, message.ID, created)
if err != nil {
if isIdempotencyViolation(err) {
// This transaction never committed. Roll it back explicitly before
// reading the winner; PostgreSQL has already released the row lock
// when it reported the unique violation.
_ = tx.Rollback(ctx)
storedHash, storedMessage, found, replayErr := s.replayIdempotent(ctx, senderID, method, path, key)
if replayErr != nil {
return model.Message{}, false, replayErr
}
if !found {
return model.Message{}, false, fmt.Errorf("%w: idempotency record vanished", ErrUnavailable)
}
if !bytes.Equal(storedHash, requestHash) {
return model.Message{}, false, ErrIdempotencyConflict
}
return storedMessage, true, nil
}
return model.Message{}, false, s.classify(err)
}
if err := tx.Commit(ctx); err != nil {
return model.Message{}, false, s.classify(err)
}
message.CreatedAt = model.Time{Time: stored.UTC()}
return message, false, nil
}
func (s *Store) replayIdempotent(ctx context.Context, userID, method, path, key string) ([]byte, model.Message, bool, error) {
var storedHash []byte
var message model.Message
var createdAt time.Time
err := s.pool.QueryRow(ctx, `
SELECT i.request_hash,
m.id::text, m.chat_id::text, m.sender_id::text, m.text, m.created_at,
COALESCE((
SELECT array_agg(ma.attachment_id::text ORDER BY ma.position)
FROM message_attachments ma
WHERE ma.message_id = m.id
), '{}')
FROM message_idempotency i
JOIN messages m ON m.id = i.message_id
WHERE i.user_id = $1::uuid AND i.method = $2 AND i.path = $3 AND i.key = $4`,
userID, method, path, key,
).Scan(&storedHash, &message.ID, &message.ChatID, &message.SenderID, &message.Text, &createdAt, &message.AttachmentIDs)
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return nil, model.Message{}, false, nil
}
return nil, model.Message{}, false, s.classify(err)
}
if message.AttachmentIDs == nil {
message.AttachmentIDs = []string{}
}
message.CreatedAt = model.Time{Time: createdAt.UTC()}
return storedHash, message, true, nil
}
// PruneIdempotency removes records older than the contract's minimum
// retention. It runs opportunistically from every replica; the statement is
// safe to execute concurrently and is bounded to keep one delete short.
func (s *Store) PruneIdempotency(ctx context.Context, olderThan time.Duration) (int64, error) {
ctx, cancel := s.opCtx(ctx)
defer cancel()
tag, err := s.pool.Exec(ctx, `
DELETE FROM message_idempotency
WHERE ctid IN (
SELECT ctid FROM message_idempotency
WHERE created_at < now() - $1::interval
LIMIT 500
)`, fmt.Sprintf("%d seconds", int(olderThan.Seconds())))
if err != nil {
return 0, s.classify(err)
}
return tag.RowsAffected(), nil
}
const messagesPageSelect = `
SELECT m.id::text, m.chat_id::text, m.sender_id::text, m.text, m.created_at,
COALESCE((
SELECT array_agg(ma.attachment_id::text ORDER BY ma.position)
FROM message_attachments ma
WHERE ma.message_id = m.id
), '{}')
FROM (`
// Messages returns one keyset page of a chat history. The caller has already
// verified membership; the query itself never loads the whole history.
func (s *Store) Messages(ctx context.Context, chatID string, position *cursor.Cursor, limit int) (model.MessagePage, error) {
ctx, cancel := s.opCtx(ctx)
defer cancel()
where := `WHERE chat_id = $1::uuid`
args := []any{chatID, limit + 1}
order := `ORDER BY created_at, id
LIMIT $2`
if position != nil {
where = `WHERE chat_id = $1::uuid
AND (created_at, id) > ($2::timestamptz, $3::uuid)`
args = []any{chatID, position.At, position.ID, limit + 1}
order = `ORDER BY created_at, id
LIMIT $4`
}
query := messagesPageSelect + `
SELECT id, chat_id, sender_id, text, created_at
FROM messages
` + where + `
` + order + `
) m
LEFT JOIN message_attachments ma ON ma.message_id = m.id
GROUP BY m.id, m.chat_id, m.sender_id, m.text, m.created_at
ORDER BY m.created_at, m.id`
rows, err := s.pool.Query(ctx, query, args...)
if err != nil {
return model.MessagePage{}, s.classify(err)
}
defer rows.Close()
items := make([]model.Message, 0, limit)
for rows.Next() {
var message model.Message
var createdAt time.Time
if err := rows.Scan(&message.ID, &message.ChatID, &message.SenderID, &message.Text, &createdAt, &message.AttachmentIDs); err != nil {
return model.MessagePage{}, s.classify(err)
}
if message.AttachmentIDs == nil {
message.AttachmentIDs = []string{}
}
message.CreatedAt = model.Time{Time: createdAt.UTC()}
items = append(items, message)
}
if err := rows.Err(); err != nil {
return model.MessagePage{}, s.classify(err)
}
page := model.MessagePage{Items: items}
if len(items) > limit {
page.Items = items[:limit]
next := cursor.ForMessage(page.Items[len(page.Items)-1])
page.NextCursor = &next
}
return page, nil
}
+75
View File
@@ -0,0 +1,75 @@
// Package uuid generates and normalizes canonical lowercase UUIDs. The
// application, not PostgreSQL, assigns identifiers so every API replica and
// the database agree on the exact on-the-wire form.
package uuid
import (
"crypto/rand"
"encoding/hex"
"strings"
)
// New returns a canonical lowercase UUIDv4. A failure of crypto/rand means the
// process cannot safely create identifiers, so panicking is intentional; the
// HTTP layer turns it into a generic 500 response.
func New() string {
var b [16]byte
if _, err := rand.Read(b[:]); err != nil {
panic("crypto/rand failed: " + err.Error())
}
b[6] = (b[6] & 0x0f) | 0x40 // version 4
b[8] = (b[8] & 0x3f) | 0x80 // RFC 4122 variant
return format(b)
}
// NewRandom returns a lowercase hex string with n random bytes. It is used for
// request ids and stable per-process instance ids, not for resource ids.
func NewRandom(n int) string {
raw := make([]byte, n)
if _, err := rand.Read(raw); err != nil {
panic("crypto/rand failed: " + err.Error())
}
return hex.EncodeToString(raw)
}
func format(b [16]byte) string {
var out [36]byte
hex.Encode(out[0:8], b[0:4])
out[8] = '-'
hex.Encode(out[9:13], b[4:6])
out[13] = '-'
hex.Encode(out[14:18], b[6:8])
out[18] = '-'
hex.Encode(out[19:23], b[8:10])
out[23] = '-'
hex.Encode(out[24:36], b[10:16])
return string(out[:])
}
// Normalize accepts only the canonical 8-4-4-4-12 hyphenated form (ASCII hex,
// case-insensitive) and returns its lowercase representation. Braces, urn:
// prefixes, SQL uuid spellings and other aliases are rejected so resource
// identifiers have exactly one wire form.
func Normalize(value string) (string, bool) {
if len(value) != 36 {
return "", false
}
for i := 0; i < len(value); i++ {
c := value[i]
switch i {
case 8, 13, 18, 23:
if c != '-' {
return "", false
}
default:
if !isHex(c) {
return "", false
}
}
}
return strings.ToLower(value), true
}
func isHex(c byte) bool {
return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F')
}
+44
View File
@@ -0,0 +1,44 @@
package uuid
import "testing"
func TestNewIsCanonicalV4(t *testing.T) {
id := New()
normalized, ok := Normalize(id)
if !ok || normalized != id {
t.Fatalf("New() returned non-canonical UUID %q", id)
}
if id[14] != '4' {
t.Fatalf("version nibble = %c, want 4", id[14])
}
if id[19] != '8' && id[19] != '9' && id[19] != 'a' && id[19] != 'b' {
t.Fatalf("variant nibble = %c, want 8/9/a/b", id[19])
}
if New() == New() {
t.Fatal("two generated UUIDs are equal")
}
}
func TestNormalize(t *testing.T) {
valid := "11111111-2222-4333-8444-555555555555"
if got, ok := Normalize(valid); !ok || got != valid {
t.Fatalf("Normalize(%q) = %q, %v", valid, got, ok)
}
upper := "AAAAAAAA-BBBB-4CCC-8DDD-EEEEEEEEEEEE"
if got, ok := Normalize(upper); !ok || got != "aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee" {
t.Fatalf("uppercase normalization failed: %q, %v", got, ok)
}
for _, invalid := range []string{
"",
"{11111111-2222-4333-8444-555555555555}",
"urn:uuid:11111111-2222-4333-8444-555555555555",
"11111111222243338444555555555555",
"11111111-2222-4333-8444-55555555555z",
"11111111-2222-4333-8444-5555555555555",
" 1111111-2222-4333-8444-555555555555",
} {
if _, ok := Normalize(invalid); ok {
t.Fatalf("Normalize accepted %q", invalid)
}
}
}
Regular → Executable
View File
+108
View File
@@ -0,0 +1,108 @@
#!/bin/sh
# Build and test the committed revision from a separate clone with empty named
# volumes, then remove only that clone's containers, network, volumes and image.
#
# The main lab4 stand (if running) is stopped with data preserved for the
# duration so both stands fit the 2 vCPU / ~2 GiB Colima VM, and restarted at
# the end. The temporary clone lives under .local/highload-tasks/lab4-artifacts
# because Colima only shares the user's home into the VM.
set -eu
cd "$(dirname "$0")/.."
root=$(pwd)
revision=$(git rev-parse HEAD)
if [ -n "$(git status --porcelain)" ]; then
echo "clean-clone-check: working tree is dirty; commit first" >&2
exit 2
fi
artifact_root=${LAB4_ARTIFACTS:-$(cd "$root/../.." && pwd)/.local/highload-tasks/lab4-artifacts}
mkdir -p "$artifact_root"
tmp=$(mktemp -d "$artifact_root/clean-clone.XXXXXX")
project=mtusi-lab4-melnikov-clean
port=8085
image=$project:local
main_was_running=0
if docker ps --format '{{.Names}}' | grep -q '^mtusi-lab4-melnikov-'; then
main_was_running=1
fi
cleanup() {
status=$?
if [ -d "$tmp" ]; then
(cd "$tmp" && COMPOSE_PROJECT_NAME=$project LB_PORT=$port \
./scripts/compose.sh --env-file .env down -v --remove-orphans >/dev/null 2>&1 || true)
docker image rm -f "$image" >/dev/null 2>&1 || true
case "$tmp" in
"$artifact_root"/clean-clone.*) rm -rf "$tmp" ;;
*) echo "clean-clone-check: refusing to remove unexpected path $tmp" >&2 ;;
esac
fi
if [ "$main_was_running" = "1" ]; then
(cd "$root" && make up >/dev/null 2>&1 && ./scripts/wait-ready.sh >/dev/null 2>&1 || true)
fi
exit "$status"
}
trap cleanup EXIT INT TERM
echo "== clean clone =="
echo "source revision: $revision"
echo "clone: $tmp"
echo "project: $project; LB port: $port; image: $image"
if [ "$main_was_running" = "1" ]; then
echo "stopping the main lab4 stand with data preserved for the check"
(cd "$root" && make stop >/dev/null)
fi
git clone --quiet "$root" "$tmp"
cd "$tmp"
test "$(git rev-parse HEAD)" = "$revision"
echo "== local configuration with fresh synthetic credentials =="
./scripts/init-env.sh
python3 - "$tmp/.env" "$port" <<'PY'
import sys
path, port = sys.argv[1], sys.argv[2]
lines = []
for line in open(path):
if line.startswith('LB_PORT='):
line = 'LB_PORT=%s\n' % port
lines.append(line)
open(path, 'w').writelines(lines)
PY
export COMPOSE_PROJECT_NAME=$project
export LB_PORT=$port
export IMAGE=$image
export BASE_URL=http://127.0.0.1:$port
echo "== offline contract and syntax checks =="
make check
echo "== build, migrate and bootstrap the bucket from empty volumes =="
GIT_REVISION=$revision API_IMAGE=$image make up
postgres=$(./scripts/compose.sh --env-file .env ps -q postgres)
set -a
. ./.env
set +a
docker exec -i "$postgres" psql -X -A -t -U "$POSTGRES_USER" -d "$POSTGRES_DB" \
-c "SELECT 'users=' || count(*) FROM users;" \
-c "SELECT 'attachments=' || count(*) FROM attachments;" \
-c "SELECT 'migrations=' || string_agg(version::text, ',' ORDER BY version) FROM schema_migrations;"
./scripts/compose.sh --env-file .env logs s3-init 2>&1 | grep -E '"created":(true|false)' || true
./scripts/compose.sh --env-file .env ps --format 'table {{.Name}}\t{{.Status}}'
echo "== public and own API tests on the clean stand =="
make test
make test-student
make test-persistence ACTION_SCRIPT=scripts/restart.sh
echo "== intentional cleanup of this temporary clone's resources =="
make purge
docker image rm -f "$image" >/dev/null 2>&1 || true
if docker ps -aq --filter label=com.docker.compose.project=$project | grep -q .; then
echo "clean-clone-check: containers remain" >&2
exit 1
fi
if docker volume ls -q | grep -q "^${project}-"; then
echo "clean-clone-check: volumes remain" >&2
exit 1
fi
echo "PASS: clean clone built, migrated, bootstrapped and tested; temporary resources removed"
+93
View File
@@ -0,0 +1,93 @@
#!/bin/bash
# Reproduce the lab4 mandatory and own checks on the running stand and keep
# their real stdout under evidence/commands/. No secrets are printed by these
# commands; the context block contains versions and image ids only.
set -euo pipefail
cd "$(dirname "$0")/.."
export BASE_URL=${BASE_URL:-http://127.0.0.1:8084}
PY39=/usr/bin/python3
out=evidence/commands
mkdir -p "$out"
stamp=$(date -u +%Y-%m-%dT%H:%M:%SZ)
{
echo "started_at: $stamp"
echo "base_url: $BASE_URL"
echo "git_revision: $(git rev-parse HEAD)"
echo "git_status_lines: $(git status --porcelain | wc -l | tr -d ' ')"
echo "python3: $(python3 --version 2>&1)"
echo "python39: $($PY39 --version 2>&1)"
echo "go: $(go version)"
echo "docker_server: $(docker version --format '{{.Server.Version}}')"
echo "docker_cpus_mem: $(docker info --format 'CPUs={{.NCPU}} MemTotal={{.MemTotal}}')"
echo "api_images:"
for id in $(./scripts/compose.sh --env-file .env ps -q api); do
docker inspect -f ' {{.Name}} image={{.Image}} started={{.State.StartedAt}}' "$id"
done
echo "s3_image:"
for id in $(./scripts/compose.sh --env-file .env ps -q s3); do
docker inspect -f ' {{.Name}} image={{.Image}}' "$id"
done
} | tee "$out/context.txt"
run() {
name=$1
shift
{
echo
echo "### $name"
echo "### command: $*"
echo "### started_at: $(date -u +%Y-%m-%dT%H:%M:%SZ)"
} | tee "$out/$name.txt"
set +e
"$@" 2>&1 | tee -a "$out/$name.txt"
code=${PIPESTATUS[0]}
set -e
echo "### exit_code: $code" | tee -a "$out/$name.txt"
if [ "$code" -ne 0 ]; then
echo "evidence collection stopped: $name failed" >&2
exit "$code"
fi
}
restore_replicas() {
./scripts/compose.sh --env-file .env up -d --no-deps api >/dev/null
./scripts/wait-ready.sh
# The LB needs a moment to see the restarted backend. Do not continue until
# the public health endpoint reports two distinct X-Instance-Id values.
attempt=0
while [ "$attempt" -lt 60 ]; do
visible=$(for _ in $(seq 1 20); do
curl -fsS -D - -o /dev/null "$BASE_URL/health/ready" 2>/dev/null \
| tr -d '\r' | awk 'tolower($1)=="x-instance-id:"{print $2}'
done | sort -u | wc -l | tr -d ' ')
if [ "$visible" -ge 2 ]; then
return 0
fi
attempt=$((attempt + 1))
sleep 0.5
done
echo "restore_replicas: LB still sees fewer than two API instances" >&2
return 1
}
run make_check make PYTHON=$PY39 check
run make_validate make PYTHON=.venv/bin/python validate
run go_tests make PYTHON=$PY39 test-student
run go_race make PYTHON=$PY39 test-student-race
run smoke make PYTHON=$PY39 test
run smoke_python39 ./scripts/py39-tests.sh
run attachment_checks make PYTHON=$PY39 test-attachment
run container_checks make PYTHON=$PY39 test-container
run persistence_public make PYTHON=$PY39 test-persistence ACTION_SCRIPT=scripts/restart.sh
run persistence_evidence $PY39 scripts/persistence-evidence.py --base-url "$BASE_URL"
run failover_public make PYTHON=$PY39 test-failover ACTION_SCRIPT=scripts/stop-one.sh
restore_replicas
run failover_upload $PY39 scripts/failover-upload.py --base-url "$BASE_URL"
run track2 make PYTHON=$PY39 test-consistency
run experiment make PYTHON=$PY39 experiment
run smoke_after_experiment make PYTHON=$PY39 test
echo "finished_at: $(date -u +%Y-%m-%dT%H:%M:%SZ)" | tee "$out/summary.txt"
grep -h '^### exit_code:' "$out"/*.txt | sort | uniq -c | tee -a "$out/summary.txt"
echo "PASS: evidence collection finished; raw command logs are in $out"
+13
View File
@@ -0,0 +1,13 @@
#!/bin/sh
# Accept both the Compose v2 plugin ("docker compose") and the standalone
# binary ("docker-compose"), so the same Makefile works on machines where only
# one of them is installed. This wrapper does not change any global setting.
set -eu
if docker compose version >/dev/null 2>&1; then
exec docker compose "$@"
fi
if command -v docker-compose >/dev/null 2>&1; then
exec docker-compose "$@"
fi
echo "Docker Compose is required (docker compose or docker-compose)" >&2
exit 2
+232
View File
@@ -0,0 +1,232 @@
#!/usr/bin/env python3
"""Lab4 infrastructure evidence from actual Docker state, not compose.yaml.
Checks:
* at least two API processes with distinct container ids and hostnames;
* only HAProxy is published, on 127.0.0.1, and API/S3/admin ports are not;
* API is non-root, read-only, cap-drop ALL, no state volume; S3 has its data volume;
* every stand service has CPU and memory limits; named volumes use the lab prefix;
* the API S3 identity is bucket-scoped and differs from the admin identity,
and the admin identity is never present in an API container;
* the bucket bootstrap is idempotent (second run reports created=false);
* an anonymous S3 GET/list outside the API is denied;
* one session is served by both API replicas through the LB.
Python 3.9+, standard library only. Requires the running stand and Docker.
Writes evidence/container-checks.json and .txt.
"""
import json
import re
import subprocess
import sys
import time
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tests'))
sys.path.insert(0, str(ROOT / 'scripts'))
from client import Client, arguments, check # noqa: E402
import lab4_metrics as M # noqa: E402
def docker_exec(container, *args):
return subprocess.run(['docker', 'exec', container] + list(args),
stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
def wait_exited(container, timeout=60):
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
state = M.inspect(container).get('State', {})
if state.get('Status') == 'exited':
return state.get('ExitCode')
time.sleep(0.5)
raise RuntimeError('container did not exit: ' + container)
def main():
args = arguments('Lab4 container, S3 privacy and credential checks')
checks = {}
failures = []
compose_text = (ROOT / 'compose.yaml').read_text()
checks['no_container_name_in_compose'] = not re.search(r'^\s*container_name\s*:', compose_text, re.MULTILINE)
images = re.findall(r'^\s*image:\s*(\S+)', compose_text, re.MULTILINE)
third_party = [image for image in images if not image.startswith('${API_IMAGE')]
checks['third_party_images_pinned_by_digest'] = all('@sha256:' in image for image in third_party)
checks['third_party_images'] = third_party
api = M.containers('api')
lb = M.containers('lb')
postgres = M.containers('postgres')
valkey = M.containers('valkey')
s3 = M.containers('s3')
check(len(api) >= 2, 'expected at least two API containers')
check(len(lb) == 1 and len(postgres) == 1 and len(valkey) == 1 and len(s3) == 1,
'expected one LB, PostgreSQL, Valkey and S3 container')
checks['api_replica_count'] = len(api)
checks['api_container_ids_distinct'] = len({item['container_id'] for item in api}) == len(api)
checks['api_hostnames_distinct'] = len({item['hostname'] for item in api}) == len(api)
checks['api_image_ids'] = sorted({item['image_id'] for item in api})
checks['s3_image_id'] = s3[0]['image_id']
checks['git_revision'] = M.run(['git', 'rev-parse', 'HEAD']).stdout.strip()
api_ports = {item['name']: M.run(['docker', 'port', item['container_id']]).stdout.strip() for item in api}
s3_ports = M.run(['docker', 'port', s3[0]['container_id']]).stdout.strip()
lb_ports = M.run(['docker', 'port', lb[0]['container_id']]).stdout.strip()
checks['api_ports'] = api_ports
checks['s3_published_ports'] = s3_ports
checks['lb_ports'] = lb_ports
checks['api_has_no_published_ports'] = all(value == '' for value in api_ports.values())
checks['s3_has_no_published_ports'] = s3_ports == ''
checks['lb_published_loopback_only'] = ('127.0.0.1:' in lb_ports and '8080' in lb_ports)
limits = {}
for service, items in (('api', api), ('postgres', postgres), ('valkey', valkey), ('s3', s3), ('lb', lb)):
rows = []
for item in items:
data = M.inspect(item['container_id'])
host = data.get('HostConfig', {})
rows.append({
'name': item['name'],
'nano_cpus': host.get('NanoCpus'),
'memory_bytes': host.get('Memory'),
'readonly_rootfs': host.get('ReadonlyRootfs'),
'cap_drop': host.get('CapDrop'),
'security_opt': host.get('SecurityOpt'),
'user': data.get('Config', {}).get('User'),
'mounts': [mount.get('Name') or mount.get('Source') for mount in data.get('Mounts', [])],
'volume_mounts': [mount.get('Name') for mount in data.get('Mounts', [])
if mount.get('Type') == 'volume'],
})
limits[service] = rows
checks['limits'] = limits
checks['all_services_have_cpu_and_memory_limits'] = all(
row['nano_cpus'] and row['memory_bytes']
for rows in limits.values() for row in rows)
checks['api_non_root'] = all((row['user'] or '').startswith('10001') for row in limits['api'])
checks['api_read_only_rootfs'] = all(row['readonly_rootfs'] for row in limits['api'])
checks['api_cap_drop_all'] = all(row['cap_drop'] == ['ALL'] for row in limits['api'])
checks['api_no_new_privileges'] = all(
any('no-new-privileges' in value for value in (row['security_opt'] or []))
for row in limits['api'])
checks['api_has_no_state_volume'] = all(not row['mounts'] for row in limits['api'])
checks['s3_has_data_volume'] = any(
row['volume_mounts'] and all(name.startswith(M.PROJECT + '-') for name in row['volume_mounts'])
for row in limits['s3'])
volume_names = set()
for item in postgres + valkey + s3:
for mount in M.inspect(item['container_id']).get('Mounts', []):
if mount.get('Type') == 'volume':
volume_names.add(mount.get('Name'))
checks['named_volumes'] = sorted(volume_names)
checks['volumes_have_prefix'] = all(name.startswith(M.PROJECT + '-') for name in volume_names)
# S3 credentials: the API must not receive the administrative identity and
# must fail on a bucket outside its grant.
api_env = api[0]['env']
s3_init = M.compose('ps', '-a', '-q', 's3-init').stdout.strip()
check(s3_init != '', 's3-init container is missing')
init_env = M.inspect(s3_init).get('Config', {}).get('Env', [])
admin_access = ''
for item in init_env:
if item.startswith('S3_ADMIN_ACCESS_KEY='):
admin_access = item.split('=', 1)[1]
checks['api_s3_access_key_present'] = bool(api_env.get('S3_ACCESS_KEY'))
checks['api_s3_secret_present'] = bool(api_env.get('S3_SECRET_KEY'))
checks['api_credentials_differ_from_admin'] = (
bool(admin_access) and api_env.get('S3_ACCESS_KEY') != admin_access)
checks['api_has_no_admin_credentials'] = not any(
key.startswith('S3_ADMIN_') for key in api_env)
buckets = M.s3ctl('-op', 'list', '-prefix', '').stdout
checks['api_credentials_can_list_own_bucket'] = '"objects"' in buckets
other = M.s3ctl('-op', 'list', '-prefix', '', '-bucket', 'definitely-not-granted', check=False)
checks['api_credentials_denied_other_bucket'] = other.returncode != 0
# Bucket bootstrap is idempotent: run the same one-shot container again.
first = M.run(['docker', 'start', '-a', s3_init.strip()], check=False)
code = wait_exited(s3_init.strip())
logs = M.run(['docker', 'logs', '--tail', '5', s3_init.strip()]).stdout + M.run(
['docker', 'logs', '--tail', '5', s3_init.strip()]).stderr
checks['bucket_bootstrap_second_run_exit'] = code
checks['bucket_bootstrap_second_run_created_false'] = '"created":false' in logs
checks['bucket_bootstrap_second_run_verified'] = '"verified":true' in logs
# Anonymous access outside the API must not return an object or a listing.
alice, bob, eve, chat = Client(args.base_url, args.ca_file).bootstrap()
attachment, content = Client(args.base_url, args.ca_file).attachment(alice, chat)
object_key = M.psql(
"SELECT object_key FROM attachments WHERE id = '%s'" % attachment['id'])
bucket = api_env.get('S3_BUCKET', '')
check(bucket and object_key, 'cannot resolve bucket/object key for the privacy probe')
anonymous_object = docker_exec(api[0]['container_id'], 'wget', '-q', '-S', '-O', '/dev/null',
'http://s3:8333/' + bucket + '/' + object_key)
anonymous_list = docker_exec(api[0]['container_id'], 'wget', '-q', '-S', '-O', '/dev/null',
'http://s3:8333/' + bucket + '?list-type=2')
checks['anonymous_object_get_status'] = anonymous_object.stderr + anonymous_object.stdout
checks['anonymous_object_get_denied'] = (
anonymous_object.returncode != 0 and '403' in checks['anonymous_object_get_status'])
checks['anonymous_list_status'] = anonymous_list.stderr + anonymous_list.stdout
checks['anonymous_list_denied'] = (
anonymous_list.returncode != 0 and '403' in checks['anonymous_list_status'])
checks['attachment_download_still_authorized'] = (
Client(args.base_url, args.ca_file).call(
'GET', '/api/v1/attachments/' + attachment['id'] + '/content', actor=bob)['bytes'] == content)
# One session crosses the real replicas through the LB.
client = Client(args.base_url, args.ca_file)
observed = set()
for _ in range(40):
response = client.call('GET', '/api/v1/users/me', actor=alice, schema='User')
observed.add(response['headers']['X-Instance-Id'])
checks['observed_instances'] = sorted(observed)
checks['session_crosses_replicas'] = len(observed) >= 2
checks['session_instances_are_api_hostnames'] = observed.issubset({item['hostname'] for item in api})
checks['health_ready_via_lb'] = client.call('GET', '/health/ready', schema='Health')['status'] == 200
for key, value in checks.items():
if isinstance(value, bool) and not value:
failures.append(key)
checks['result'] = 'PASS' if not failures else 'FAIL'
checks['failed'] = failures
checks['checked_at'] = M.now_iso()
checks['base_url'] = args.base_url
output = ROOT / 'evidence' / 'container-checks.json'
output.parent.mkdir(parents=True, exist_ok=True)
M.write_json(output, checks)
lines = [
'lab4 container checks at ' + checks['checked_at'],
'result: ' + checks['result'],
'git revision: ' + checks['git_revision'],
'API replicas: %d (%s)' % (len(api), ', '.join(item['hostname'] for item in api)),
'API image ids: ' + ', '.join(checks['api_image_ids']),
'S3 image id: ' + checks['s3_image_id'],
'API ports published: %r' % api_ports,
'S3 ports published: %r' % s3_ports,
'LB ports: ' + lb_ports,
'volumes: ' + ', '.join(checks['named_volumes']),
'limits: ' + json.dumps(limits, separators=(',', ':')),
'observed session instances: ' + ', '.join(sorted(observed)),
'anonymous object GET denied: %r' % checks['anonymous_object_get_denied'],
'anonymous bucket list denied: %r' % checks['anonymous_list_denied'],
'bootstrap second run: exit=%r created_false=%r' % (
checks['bucket_bootstrap_second_run_exit'],
checks['bucket_bootstrap_second_run_created_false']),
]
(ROOT / 'evidence' / 'container-checks.txt').write_text('\n'.join(lines) + '\n', encoding='utf-8')
print('\n'.join(lines))
if failures:
raise SystemExit('FAILED checks: ' + ', '.join(failures))
print('PASS: container, S3 privacy and credential checks')
if __name__ == '__main__':
try:
main()
except Exception as exc: # noqa: BLE001
import traceback
traceback.print_exc()
print('FAIL:', exc)
raise SystemExit(1)
+155
View File
@@ -0,0 +1,155 @@
#!/usr/bin/env python3
"""Lab4 failover evidence: upload, stop the serving API replica, read elsewhere.
The public `make test-failover` checks writes and idempotency. This script adds
the lab4-specific proof: the attachment is uploaded by a known replica, that
replica is stopped with scripts/stop-one.sh, and the same original is
downloaded through a different replica with an identical SHA-256.
Python 3.9+, standard library only. Requires the running stand and Docker.
"""
import hashlib
import json
import os
import subprocess
import sys
import time
import uuid
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tests'))
sys.path.insert(0, str(ROOT / 'scripts'))
from client import Client, Failure, arguments, check # noqa: E402
import lab4_metrics as M # noqa: E402
EVIDENCE = ROOT / 'evidence' / 'resilience'
def upload_with_instance(c, actor, chat, data):
response = c.call('POST', '/api/v1/chats/' + chat['id'] + '/attachments?filename=failover.png',
201, actor=actor, raw=data, headers={'Content-Type': 'image/png'},
schema='Attachment')
return response['json'], response['headers']['X-Instance-Id']
def main():
args = arguments('Lab4 upload/failover evidence; stops one API replica and restores it')
EVIDENCE.mkdir(parents=True, exist_ok=True)
c = Client(args.base_url, args.ca_file, timeout=20)
alice, bob, eve, chat = c.bootstrap()
data = M.png_random(1400, 1000, seed=42)
attachment, uploader = upload_with_instance(c, alice, chat, data)
observed = set()
deadline = time.monotonic() + 30
while time.monotonic() < deadline:
observed.add(c.call('GET', '/api/v1/users/me', actor=alice,
schema='User')['headers']['X-Instance-Id'])
if len(observed) >= 2:
break
time.sleep(0.3)
check(len(observed) >= 2, 'expected at least two API replicas before failover')
check(uploader in observed, 'upload was served by an unknown instance: ' + uploader)
command = [str(ROOT / 'scripts/stop-one.sh')]
environment = dict(os.environ)
environment['TARGET_INSTANCE_ID'] = uploader
started = M.now_iso()
process = subprocess.run(command, cwd=str(ROOT), env=environment,
stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
stopped = M.now_iso()
check(process.returncode == 0, 'stop-one.sh failed: ' + process.stderr.strip()[-500:])
# The stopped replica must be the actual Docker container and stay stopped.
target_ids = []
for container in M.compose('ps', '-a', '-q', 'api').stdout.split():
hostname = M.run(['docker', 'inspect', '-f', '{{.Config.Hostname}}', container]).stdout.strip()
if hostname == uploader:
target_ids.append(container)
check(len(target_ids) == 1, 'could not map the upload instance to exactly one API container')
state = M.inspect(target_ids[0])['State']
check(state['Status'] == 'exited', 'target container is not stopped: ' + state['Status'])
M.wait_ready(60)
replica_set = set()
download = None
restored_at = None
restored_instances = set()
try:
deadline = time.monotonic() + 30
while time.monotonic() < deadline:
download = c.call('GET', '/api/v1/attachments/' + attachment['id'] + '/content', actor=bob)
replica_set.add(download['headers']['X-Instance-Id'])
if download['headers']['X-Instance-Id'] != uploader and download['bytes'] == data:
break
time.sleep(0.3)
check(download is not None and download['bytes'] == data,
'download after failover differs from the original')
check(download['headers']['X-Instance-Id'] != uploader,
'download was served by the stopped replica')
check(uploader not in replica_set, 'download hit the stopped replica')
metadata = c.call('GET', '/api/v1/attachments/' + attachment['id'], actor=bob,
schema='Attachment')['json']
check(metadata['sha256'] == hashlib.sha256(data).hexdigest(),
'metadata checksum changed after failover')
check(metadata['size_bytes'] == len(data), 'metadata size changed after failover')
finally:
# Restore the replica explicitly; the failover hook itself must leave it
# down, and this cleanup runs even when an assertion above fails.
M.compose('up', '-d', '--no-deps', 'api')
M.wait_ready(120)
restored_at = M.now_iso()
deadline = time.monotonic() + 30
while time.monotonic() < deadline:
restored_instances.add(
c.call('GET', '/api/v1/users/me', actor=alice, schema='User')['headers']['X-Instance-Id'])
if len(restored_instances) >= 2:
break
time.sleep(0.3)
check(len(restored_instances) >= 2, 'restored stand does not serve two API replicas')
result = {
'checked_at': M.now_iso(),
'base_url': args.base_url,
'git_revision': M.run(['git', 'rev-parse', 'HEAD']).stdout.strip(),
'attachment_id': attachment['id'],
'content_bytes': len(data),
'sha256': hashlib.sha256(data).hexdigest(),
'instances_before': sorted(observed),
'upload_instance': uploader,
'stopped_container_id': target_ids[0],
'stopped_container_state': state['Status'],
'stop_started_at': started,
'stop_finished_at': stopped,
'download_instance': download['headers']['X-Instance-Id'] if download else None,
'download_instances_seen': sorted(replica_set),
'download_sha256': hashlib.sha256(download['bytes']).hexdigest() if download else None,
'restored_at': restored_at,
'restored_instances': sorted(restored_instances),
'result': 'PASS',
'notes': [
'The upload response X-Instance-Id was mapped to the exact Docker hostname.',
'scripts/stop-one.sh left that container exited; the hook is not a restart helper.',
'The download was served by the remaining replica and matched the original bytes.',
'The stopped replica was restored explicitly with docker compose up -d api; Compose may recreate it with a new hostname.',
],
}
M.write_json(EVIDENCE / 'failover-upload.json', result)
print(json.dumps({
'upload_instance': uploader,
'download_instance': result['download_instance'],
'instances_seen': result['download_instances_seen'],
'sha256_matches': result['download_sha256'] == result['sha256'],
'stopped_container_state': result['stopped_container_state'],
'restored_at': result['restored_at'],
}, ensure_ascii=False))
print('PASS: upload survived replica stop and downloaded with the same SHA-256 via another replica')
if __name__ == '__main__':
try:
main()
except (Failure, ValueError, OSError) as exc:
print('FAIL:', str(exc))
raise SystemExit(1)
+93
View File
@@ -0,0 +1,93 @@
#!/bin/sh
# Create a local .env with fresh synthetic passwords and generate the ignored
# SeaweedFS S3 identity file from those values. Nothing is printed: the files
# are readable only by the current user. This stand never talks to a remote
# secret store.
set -eu
cd "$(dirname "$0")/.."
if [ ! -f .env ]; then
random_secret() {
LC_ALL=C tr -dc 'A-Za-z0-9' < /dev/urandom | head -c 32
}
postgres_password=$(random_secret)
valkey_password=$(random_secret)
s3_admin_access=$(random_secret)
s3_admin_secret=$(random_secret)
s3_api_access=$(random_secret)
s3_api_secret=$(random_secret)
for value in "$postgres_password" "$valkey_password" "$s3_admin_access" "$s3_admin_secret" "$s3_api_access" "$s3_api_secret"; do
if [ "${#value}" -ne 32 ]; then
echo "could not generate local secrets" >&2
exit 1
fi
done
revision=$(git rev-parse HEAD 2>/dev/null || echo unknown)
umask 077
sed \
-e "s|^POSTGRES_PASSWORD=.*|POSTGRES_PASSWORD=${postgres_password}|" \
-e "s|^VALKEY_PASSWORD=.*|VALKEY_PASSWORD=${valkey_password}|" \
-e "s|^S3_ADMIN_ACCESS_KEY=.*|S3_ADMIN_ACCESS_KEY=${s3_admin_access}|" \
-e "s|^S3_ADMIN_SECRET_KEY=.*|S3_ADMIN_SECRET_KEY=${s3_admin_secret}|" \
-e "s|^S3_API_ACCESS_KEY=.*|S3_API_ACCESS_KEY=${s3_api_access}|" \
-e "s|^S3_API_SECRET_KEY=.*|S3_API_SECRET_KEY=${s3_api_secret}|" \
-e "s|^GIT_REVISION=.*|GIT_REVISION=${revision}|" \
.env.example > .env
chmod 600 .env
echo "wrote .env with generated local synthetic credentials (mode 600); values not printed"
else
echo ".env already exists; keeping it"
fi
# Read the values back from the ignored file. The generated secrets use only
# [A-Za-z0-9], so a simple sed extraction is sufficient and never echoes them.
value() {
sed -n "s/^$1=//p" .env | head -n 1
}
postgres_password=$(value POSTGRES_PASSWORD)
valkey_password=$(value VALKEY_PASSWORD)
s3_admin_access=$(value S3_ADMIN_ACCESS_KEY)
s3_admin_secret=$(value S3_ADMIN_SECRET_KEY)
s3_api_access=$(value S3_API_ACCESS_KEY)
s3_api_secret=$(value S3_API_SECRET_KEY)
s3_bucket=$(value S3_BUCKET)
s3_bucket=${s3_bucket:-messenger-attachments}
for value_name in postgres_password valkey_password s3_admin_access s3_admin_secret s3_api_access s3_api_secret; do
eval "check=\${$value_name}"
if [ -z "$check" ]; then
echo "init-env: $value_name is empty in .env" >&2
exit 1
fi
done
umask 077
mkdir -p infra
cat > infra/seaweedfs-s3.json <<EOF
{
"identities": [
{
"name": "lab4-admin-bootstrap",
"credentials": [
{"accessKey": "${s3_admin_access}", "secretKey": "${s3_admin_secret}"}
],
"actions": ["Admin"]
},
{
"name": "lab4-api-bucket-scoped",
"credentials": [
{"accessKey": "${s3_api_access}", "secretKey": "${s3_api_secret}"}
],
"actions": [
"Read:${s3_bucket}",
"Write:${s3_bucket}",
"List:${s3_bucket}"
]
}
]
}
EOF
chmod 600 infra/seaweedfs-s3.json
echo "wrote infra/seaweedfs-s3.json (mode 600); values not printed"
+199
View File
@@ -0,0 +1,199 @@
#!/usr/bin/env python3
"""Shared operator helpers for the lab4 evidence scripts.
Python 3.9+, standard library only. The module wraps Docker/Compose and
PostgreSQL access used by student tests and experiments. It never prints
credentials: values are read from the running containers or the ignored .env
and are returned only to the caller.
"""
import datetime as dt
import json
import os
import random
import struct
import subprocess
import time
import zlib
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
BASE_URL = os.environ.get('BASE_URL', 'http://127.0.0.1:8084')
PROJECT = 'mtusi-lab4-melnikov'
def run(args, cwd=ROOT, check=True, input_bytes=None):
process = subprocess.run(
args, cwd=str(cwd), input=input_bytes, stdout=subprocess.PIPE,
stderr=subprocess.PIPE, text=input_bytes is None,
)
if check and process.returncode != 0:
stderr = process.stderr if isinstance(process.stderr, str) else process.stderr.decode('utf-8', 'replace')
raise RuntimeError('command failed: %s\n%s' % (' '.join(args), stderr.strip()[:2000]))
return process
def compose(*args):
return run([str(ROOT / 'scripts/compose.sh'), '--env-file', '.env'] + list(args))
def compose_ids(service):
output = compose('ps', '-q', service).stdout
return [line.strip() for line in output.splitlines() if line.strip()]
def inspect(container):
output = run(['docker', 'inspect', container]).stdout
return json.loads(output)[0]
def containers(service):
result = []
for container_id in compose_ids(service):
data = inspect(container_id)
result.append({
'container_id': data['Id'],
'name': (data.get('Name') or '').lstrip('/'),
'hostname': data.get('Config', {}).get('Hostname', ''),
'image_id': data.get('Image', ''),
'image_ref': (data.get('Config', {}).get('Image') or ''),
'status': (data.get('State') or {}).get('Status', ''),
'env': dict(item.split('=', 1) for item in (data.get('Config', {}).get('Env') or []) if '=' in item),
})
return result
def env_value(container, name):
for item in inspect(container).get('Config', {}).get('Env', []) or []:
if item.startswith(name + '='):
return item.split('=', 1)[1]
return ''
def postgres_identity():
postgres = compose_ids('postgres')
if not postgres:
raise RuntimeError('postgres container is not running')
user = env_value(postgres[0], 'POSTGRES_USER')
database = env_value(postgres[0], 'POSTGRES_DB')
return postgres[0], user, database
def psql(sql):
container, user, database = postgres_identity()
process = subprocess.run(
['docker', 'exec', '-i', container, 'psql', '-X', '-A', '-t', '-v', 'ON_ERROR_STOP=1',
'-U', user, '-d', database, '-c', sql],
stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True,
)
if process.returncode != 0:
raise RuntimeError('psql failed: ' + process.stderr.strip()[:2000])
return process.stdout.strip()
def s3ctl(*args, check=True):
api = compose_ids('api')
if not api:
raise RuntimeError('no API container is running')
return run(['docker', 'exec', api[0], '/app/s3ctl'] + list(args), check=check)
def s3_list(prefix='attachments/'):
output = s3ctl('-op', 'list', '-prefix', prefix).stdout
return json.loads(output)['objects']
def s3_count(prefix='attachments/'):
return len(s3_list(prefix))
def wait_ready(timeout=90, base_url=None):
import urllib.error
import urllib.request
url = (base_url or BASE_URL).rstrip('/') + '/health/ready'
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
try:
with urllib.request.urlopen(url, timeout=2) as response:
if response.status == 200:
return True
except (urllib.error.URLError, OSError):
pass
time.sleep(0.5)
raise RuntimeError('stack did not become ready: ' + url)
def wait_healthy(service, timeout=60):
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
ids = compose_ids(service)
if ids:
state = inspect(ids[0]).get('State', {})
health = state.get('Health', {}).get('Status')
if health in (None, 'healthy'):
return True
time.sleep(0.5)
raise RuntimeError('service did not become healthy: ' + service)
def now_iso():
return dt.datetime.now(dt.timezone.utc).isoformat().replace('+00:00', 'Z')
def monotonic_ms():
return int(time.monotonic() * 1000)
def png_chunk(kind, payload):
body = kind + payload
return struct.pack('>I', len(payload)) + body + struct.pack('>I', zlib.crc32(body) & 0xffffffff)
def _png_header(width, height, color_type=2, bit_depth=8):
return (b'\x89PNG\r\n\x1a\n'
+ png_chunk(b'IHDR', struct.pack('>IIBBBBB', width, height, bit_depth, color_type, 0, 0, 0)))
def png_solid(width, height, rgb=(90, 130, 200)):
"""Small, valid PNG that compresses extremely well (used for pixel limits)."""
row = b'\x00' + bytes(rgb) * width
compressor = zlib.compressobj(6)
payload = bytearray()
for _ in range(height):
payload += compressor.compress(row)
payload += compressor.flush()
return (_png_header(width, height)
+ png_chunk(b'IDAT', bytes(payload))
+ png_chunk(b'IEND', b''))
def png_random(width, height, seed=7):
"""Valid PNG with incompressible RGB rows for byte-size and load profiles."""
generator = random.Random(seed)
compressor = zlib.compressobj(1)
payload = bytearray()
row_size = width * 3 + 1
for _ in range(height):
payload += compressor.compress(b'\x00' + generator.randbytes(row_size - 1))
payload += compressor.flush()
return (_png_header(width, height)
+ png_chunk(b'IDAT', bytes(payload))
+ png_chunk(b'IEND', b''))
def png_corrupt(width=320, height=200):
data = bytearray(png_solid(width, height))
# Flip a byte inside IDAT; the signature and IHDR still look like PNG, so
# the failure must come from the real decoder, not from MIME sniffing.
data[len(data) // 2] ^= 0xff
return bytes(data)
def fixture_bytes(name='sample.png'):
return (ROOT / 'tests' / 'fixtures' / name).read_bytes()
def write_json(path, value):
target = Path(path)
target.parent.mkdir(parents=True, exist_ok=True)
target.write_text(json.dumps(value, indent=2, ensure_ascii=False) + '\n', encoding='utf-8')
return target
+127
View File
@@ -0,0 +1,127 @@
#!/usr/bin/env python3
"""Operator evidence for lab4 persistence: real containers restarted, volumes kept.
The public `make test-persistence` proves the contract result. This script adds
the missing infrastructure evidence: every API/PostgreSQL/Valkey/S3 container
has the same id but a new StartedAt, the named volumes are unchanged, and the
same token, message and original attachment still work afterwards.
Python 3.9+, standard library only. Requires the running stand and Docker.
"""
import json
import subprocess
import sys
import time
import uuid
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tests'))
sys.path.insert(0, str(ROOT / 'scripts'))
from client import Client, Failure, arguments, check # noqa: E402
import lab4_metrics as M # noqa: E402
EVIDENCE = ROOT / 'evidence' / 'resilience'
def snapshot():
state = {'services': {}, 'volumes': [], 'captured_at': M.now_iso()}
for service in ('api', 'postgres', 'valkey', 's3'):
state['services'][service] = []
for item in M.containers(service):
data = M.inspect(item['container_id'])
state['services'][service].append({
'container_id': item['container_id'],
'name': item['name'],
'started_at': data['State'].get('StartedAt'),
'restart_count': data['RestartCount'],
'image_id': item['image_id'],
'volumes': [mount.get('Name') for mount in data.get('Mounts', [])
if mount.get('Type') == 'volume'],
})
volumes = M.run(['docker', 'volume', 'ls', '--format', '{{.Name}}']).stdout.splitlines()
state['volumes'] = sorted(name for name in volumes if name.startswith(M.PROJECT + '-'))
return state
def main():
args = arguments('Lab4 persistence infrastructure evidence; restarts the stand')
EVIDENCE.mkdir(parents=True, exist_ok=True)
c = Client(args.base_url, args.ca_file)
alice, bob, chat = None, None, None
alice, bob, eve, chat = c.bootstrap()
message = c.message(alice, chat, 'persistence evidence ' + uuid.uuid4().hex)['json']
attachment, content = c.attachment(alice, chat)
before = snapshot()
check(len(before['services']['api']) >= 2, 'need at least two API replicas')
check(len(before['volumes']) >= 3, 'expected pgdata, valkeydata and s3data volumes')
started = M.now_iso()
print('running scripts/restart.sh (all API replicas and used stores, volumes kept)')
process = subprocess.run([str(ROOT / 'scripts/restart.sh')], cwd=str(ROOT),
stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
check(process.returncode == 0, 'restart.sh failed: ' + process.stderr.strip()[-500:])
finished = M.now_iso()
M.wait_ready(120)
after = snapshot()
checks = {}
checks['same_container_ids'] = all(
before['services'][service][index]['container_id'] == after['services'][service][index]['container_id']
for service in before['services'] for index in range(len(before['services'][service])))
checks['started_at_changed'] = all(
before['services'][service][index]['started_at'] != after['services'][service][index]['started_at']
for service in before['services'] for index in range(len(before['services'][service])))
checks['all_services_restarted'] = all(
len(before['services'][service]) == len(after['services'][service])
for service in before['services'])
checks['volumes_unchanged'] = before['volumes'] == after['volumes']
# Same token, no re-login. The session lives in the restarted Valkey with
# an absolute deadline; the original attachment lives in the restarted S3
# with its metadata in PostgreSQL.
me = c.call('GET', '/api/v1/users/me', actor=alice, schema='User')['json']
checks['same_token_still_valid'] = me['id'] == alice['id']
page = c.call('GET', '/api/v1/chats/' + chat['id'] + '/messages?limit=100',
actor=bob, schema='MessagePage')['json']
checks['message_survived'] = any(item == message for item in page['items'])
metadata = c.call('GET', '/api/v1/attachments/' + attachment['id'], actor=bob, schema='Attachment')['json']
checks['attachment_metadata_survived'] = metadata['sha256'] == attachment['sha256']
download = c.call('GET', '/api/v1/attachments/' + attachment['id'] + '/content', actor=bob)
checks['attachment_bytes_survived'] = download['bytes'] == content
failed = [key for key, value in checks.items() if not value]
result = {
'checked_at': M.now_iso(),
'base_url': args.base_url,
'git_revision': M.run(['git', 'rev-parse', 'HEAD']).stdout.strip(),
'restart_started_at': started,
'restart_finished_at': finished,
'hook_exit_code': process.returncode,
'hook_stdout': process.stdout,
'hook_stderr': process.stderr,
'before': before,
'after': after,
'checks': checks,
'result': 'PASS' if not failed else 'FAIL',
'failed': failed,
'notes': [
'Container ids are unchanged: compose restarted real containers, it did not recreate them.',
'StartedAt changed for every API/PostgreSQL/Valkey/S3 container.',
'Named volumes were preserved; no volume was removed or re-created.',
'The public make test-persistence additionally checks the contract with the old token.',
],
}
M.write_json(EVIDENCE / 'persistence.json', result)
print(json.dumps({'result': result['result'], 'checks': checks}, ensure_ascii=False))
if failed:
raise SystemExit('FAILED checks: ' + ', '.join(failed))
print('PASS: real containers restarted, volumes and data preserved')
if __name__ == '__main__':
try:
main()
except (Failure, ValueError, OSError) as exc:
print('FAIL:', str(exc))
raise SystemExit(1)
+13
View File
@@ -0,0 +1,13 @@
#!/bin/sh
# Run the public and own black-box suites with the oldest promised Python
# (system Python 3.9 on this machine) against the running stand.
set -eu
cd "$(dirname "$0")/.."
base_url=${BASE_URL:-http://127.0.0.1:8084}
/usr/bin/python3 --version
/usr/bin/python3 -m py_compile scripts/*.py student-tests/*.py tests/*.py
/usr/bin/python3 scripts/check_contract.py
/usr/bin/python3 tests/smoke.py --base-url "$base_url"
/usr/bin/python3 student-tests/blackbox.py --base-url "$base_url"
echo "PASS: Python 3.9 compilation, public smoke and student black-box suite"
+56
View File
@@ -0,0 +1,56 @@
#!/bin/sh
# Restart the API and every state store this lab uses, keeping the named
# volumes and all data. This is the hook for:
# make test-persistence ACTION_SCRIPT=scripts/restart.sh
#
# It never removes volumes, never re-seeds and never prints credentials.
set -eu
cd "$(dirname "$0")/.."
if [ ! -f .env ]; then
echo "restart.sh: .env is missing; run make env first" >&2
exit 2
fi
compose="./scripts/compose.sh --env-file .env"
wait_healthy() {
container=$1
attempts=0
while [ "$attempts" -lt 60 ]; do
status=$(docker inspect -f '{{if .State.Health}}{{.State.Health.Status}}{{else}}{{.State.Status}}{{end}}' "$container" 2>/dev/null || echo missing)
if [ "$status" = "healthy" ] || [ "$status" = "running" ]; then
return 0
fi
attempts=$((attempts + 1))
sleep 1
done
echo "restart.sh: $container did not become healthy" >&2
return 1
}
echo "restart.sh: restarting shared postgres, valkey and the private S3 store (volumes kept)"
postgres=$($compose ps -q postgres)
valkey=$($compose ps -q valkey)
s3=$($compose ps -q s3)
$compose restart postgres valkey s3
wait_healthy "$postgres"
wait_healthy "$valkey"
wait_healthy "$s3"
echo "restart.sh: restarting every api replica"
$compose restart api
for container in $($compose ps -q api); do
wait_healthy "$container"
done
attempts=0
while [ "$attempts" -lt 90 ]; do
if curl -fsS -o /dev/null "http://127.0.0.1:${LB_PORT:-8084}/health/ready" 2>/dev/null; then
echo "restart.sh: all lab4 services restarted; volumes preserved"
exit 0
fi
attempts=$((attempts + 1))
sleep 1
done
echo "restart.sh: LB readiness did not recover" >&2
exit 1
+42
View File
@@ -0,0 +1,42 @@
#!/bin/sh
# Stop exactly the API replica that served TARGET_INSTANCE_ID and leave it
# stopped. This is the hook for:
# make test-failover ACTION_SCRIPT=scripts/stop-one.sh
#
# X-Instance-Id is the container hostname in lab4, so the mapping is an exact
# identity match, not a guess from a header prefix. The script touches only
# that one API container: no DB, no sessions, no volumes, no LB.
set -eu
cd "$(dirname "$0")/.."
: "${TARGET_INSTANCE_ID:?test provides target API instance alias}"
if [ ! -f .env ]; then
echo "stop-one.sh: .env is missing; run make env first" >&2
exit 2
fi
target=""
for container in $(./scripts/compose.sh --env-file .env ps -q api); do
hostname=$(docker inspect -f '{{.Config.Hostname}}' "$container" 2>/dev/null || true)
if [ "$hostname" = "$TARGET_INSTANCE_ID" ]; then
target=$container
break
fi
done
if [ -z "$target" ]; then
echo "stop-one.sh: no running API container has hostname $TARGET_INSTANCE_ID" >&2
exit 1
fi
echo "stop-one.sh: stopping API container $target (instance $TARGET_INSTANCE_ID)"
# SIGTERM starts the drain window; compose stop_grace_period is 15 s and the
# application's hard shutdown budget is 6 s, so this returns well within the
# test's 10 s hook budget. The container stays stopped afterwards.
docker stop --time 15 "$target" >/dev/null
state=$(docker inspect -f '{{.State.Status}}' "$target")
if [ "$state" != "exited" ] && [ "$state" != "dead" ]; then
echo "stop-one.sh: container state is $state, expected exited" >&2
exit 1
fi
echo "stop-one.sh: container $target is $state; other replicas keep serving"
+448
View File
@@ -0,0 +1,448 @@
#!/usr/bin/env python3
"""Track 2: repeatable reconciler experiment for the two lab4 stores.
Hypothesis: a single-pass reconciler that compares PostgreSQL attachment rows
with the private bucket, protects everything younger than a configurable grace
period, and re-reads each row immediately before a mutation can remove only
provably unreferenced stale objects and stale upload intents. It must never
delete a ready attachment that a message uses, a fresh upload in flight, or a
file whose metadata and bytes still agree, and it must not invent missing
bytes or report a missing object as ready.
Protocol:
1. create a reproducible base set of attachments (half linked to messages);
2. measure clean dry-run scans (cost of the traversal);
3. inject real faults on both sides:
- stale orphan object (S3 has no metadata row),
- stale pending intent with object (crash between PUT and COMMIT),
- stale pending intent without object,
- ready metadata whose object is gone (missing, used and unused),
- fresh orphan object and fresh pending intent (must be protected);
4. dry-run (no mutations), verify findings and unchanged counts;
5. apply, verify only the provable stale items changed;
6. rerun apply immediately (no new deletions while fresh items are young);
7. wait past the grace period and apply again: the fresh orphan is then old
enough to remove, while a completed real attachment stays intact;
8. verify the API still serves used attachments and new uploads.
Python 3.9+, standard library only. Requires the running stand and Docker.
Raw reports and a compact summary are written under evidence/track2/.
"""
import concurrent.futures
import hashlib
import json
import statistics
import subprocess
import sys
import time
import uuid
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tests'))
sys.path.insert(0, str(ROOT / 'scripts'))
from client import Client, Failure, arguments, check # noqa: E402
import lab4_metrics as M # noqa: E402
EVIDENCE = ROOT / 'evidence' / 'track2'
BASE_SIZE = 300
USED_SIZE = 150
GRACE = 20
RESULTS = []
def ok(condition, message):
RESULTS.append({'check': message, 'passed': bool(condition)})
check(condition, message)
def reconcile(apply, grace, output_path):
command = [
str(ROOT / 'scripts/compose.sh'), '--env-file', '.env', 'run', '--rm', '--no-deps', '-T',
'--entrypoint', '/app/reconciler', 'api', '-prefix', 'attachments/', '-grace', '%ds' % grace,
]
if apply:
command.append('-apply')
started = M.now_iso()
process = M.run(command)
finished = M.now_iso()
report = json.loads(process.stdout.strip())
report['_invocation'] = {'command': ' '.join(command), 'started_at': started, 'finished_at': finished}
M.write_json(output_path, report)
return report
def object_keys(report, section):
return {item['object_key'] for item in (report['findings'].get(section) or [])}
def item_ids(report, section):
return {item['id'] for item in (report['findings'].get(section) or []) if item.get('id')}
def attachment_count(status=None):
where = '' if status is None else " WHERE status = '%s'" % status
return int(M.psql('SELECT count(*) FROM attachments' + where))
def link_count():
return int(M.psql('SELECT count(*) FROM message_attachments'))
def object_exists(key):
return M.s3ctl('-op', 'stat', '-key', key, check=False).returncode == 0
def put_object(key, data, container=None):
container = container or M.compose_ids('api')[0]
name = '/tmp/lab4-track2-object.bin'
process = subprocess.run(
['docker', 'exec', '-i', container, 'sh', '-c', 'cat > ' + name],
input=data, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
)
if process.returncode != 0:
raise RuntimeError('could not stage object in API container')
M.s3ctl('-op', 'put', '-key', key, '-file', name, '-content-type', 'image/png')
M.run(['docker', 'exec', container, 'rm', '-f', name])
def delete_object(key):
M.s3ctl('-op', 'delete', '-key', key)
def insert_pending(attachment_id, chat_id, owner_id, object_key, data, age_seconds):
M.psql(
"INSERT INTO attachments "
"(id, chat_id, owner_id, filename, content_type, size_bytes, sha256, status, error_code, "
" object_key, created_at, updated_at) VALUES "
"('%s'::uuid, '%s'::uuid, '%s'::uuid, 'crash.png', 'image/png', %d, '%s', 'pending', NULL, "
" '%s', now() - interval '%d seconds', now() - interval '%d seconds')" % (
attachment_id, chat_id, owner_id, len(data), hashlib.sha256(data).hexdigest(),
object_key, age_seconds, age_seconds))
def promote_ready(attachment_id):
M.psql("UPDATE attachments SET status = 'ready', updated_at = now() "
"WHERE id = '%s'::uuid AND status = 'pending'" % attachment_id)
def all_messages(c, actor, chat):
from urllib.parse import quote
path = '/api/v1/chats/' + chat['id'] + '/messages?limit=100'
items, seen = [], set()
for _ in range(1000):
page = c.call('GET', path, actor=actor, schema='MessagePage')['json']
items.extend(page['items'])
cursor = page['next_cursor']
if cursor is None:
return items
if cursor in seen:
raise Failure('message cursor cycle')
seen.add(cursor)
path = '/api/v1/chats/' + chat['id'] + '/messages?limit=100&cursor=' + quote(cursor, safe='')
raise Failure('message history exceeded safety bound')
def sleep_until_age(started_monotonic, grace, margin=1.5):
while time.monotonic() - started_monotonic < grace + margin:
time.sleep(0.25)
def main():
args = arguments('Track 2 reconciler experiment; injects faults into SQL and S3')
EVIDENCE.mkdir(parents=True, exist_ok=True)
c = Client(args.base_url, args.ca_file)
alice, bob, eve, chat = c.bootstrap()
sample = M.fixture_bytes('sample.png')
sha = hashlib.sha256(sample).hexdigest()
revision = M.run(['git', 'rev-parse', 'HEAD']).stdout.strip()
api_image = M.containers('api')[0]['image_id']
print('== reproducible base set ==')
rows_pre = attachment_count()
objects_pre = M.s3_count()
attachments = []
for index in range(BASE_SIZE):
response = c.call('POST', '/api/v1/chats/' + chat['id'] + '/attachments?filename=track2-%03d.png' % index,
201, actor=alice, raw=sample, headers={'Content-Type': 'image/png'},
schema='Attachment')
attachments.append({'id': response['json']['id'], 'used': False,
'size_bytes': response['json']['size_bytes']})
used_messages = []
for index in range(USED_SIZE // 10):
chosen = attachments[index * 10:(index + 1) * 10]
message = c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 201, actor=alice,
body={'text': 'track2 link %02d' % index,
'attachment_ids': [item['id'] for item in chosen]},
headers={'Idempotency-Key': uuid.uuid4().hex}, schema='Message')['json']
used_messages.append(message)
for item in chosen:
item['used'] = True
used = [item for item in attachments if item['used']]
unused = [item for item in attachments if not item['used']]
ok(len(attachments) == BASE_SIZE and len(used) == USED_SIZE and len(unused) == BASE_SIZE - USED_SIZE,
'base attachment set is incomplete')
ok(all(message['attachment_ids'] == [item['id'] for item in attachments[index * 10:(index + 1) * 10]]
for index, message in enumerate(used_messages)), 'message attachments were reordered')
baseline_rows = attachment_count() - rows_pre
baseline_objects = M.s3_count() - objects_pre
baseline_links = link_count()
ok(baseline_rows == BASE_SIZE and baseline_objects == BASE_SIZE,
'base rows/objects were not exactly the %d uploads' % BASE_SIZE)
# A previous interrupted run may have left stale pending rows/orphans.
# One preliminary apply makes the cost baseline honest on a reused stand;
# on a clean stand it deletes nothing.
cleanup = reconcile(True, GRACE, EVIDENCE / 'raw-cleanup.json')
cleanup_deleted = list(cleanup['actions'].get('deleted_objects') or []) + list(
cleanup['actions'].get('deleted_pending_rows') or [])
if cleanup_deleted:
print('pre-run cleanup removed %d leftovers from an earlier interrupted run' % len(cleanup_deleted))
print('== cost of a clean traversal ==')
cost_runs = []
for index in range(3):
report = reconcile(False, 3600, EVIDENCE / ('raw-cost-%d.json' % index))
cost_runs.append({
'run': index + 1,
'generated_at': report['generated_at'],
'db_scan_ms': report['timing']['db_scan_ms'],
's3_list_ms': report['timing']['s3_list_ms'],
'total_ms': report['timing']['total_ms'],
'db_rows': report['timing']['db_rows'],
's3_objects': report['timing']['s3_objects'],
})
ok(all(run['db_rows'] >= BASE_SIZE and run['s3_objects'] >= BASE_SIZE for run in cost_runs),
'cost run did not scan the full base set')
print('== inject faults on both sides ==')
stale_started = time.monotonic()
stale_orphan = 'attachments/orphan-stale-' + uuid.uuid4().hex
put_object(stale_orphan, sample)
crash_one = str(uuid.uuid4())
crash_one_key = 'attachments/' + crash_one
insert_pending(crash_one, chat['id'], alice['id'], crash_one_key, sample, 60)
put_object(crash_one_key, sample)
crash_two = str(uuid.uuid4())
crash_two_key = 'attachments/' + crash_two
insert_pending(crash_two, chat['id'], alice['id'], crash_two_key, sample, 60)
missing_used = used[0]
missing_unused = unused[0]
missing_used_key = M.psql("SELECT object_key FROM attachments WHERE id = '%s'::uuid" % missing_used['id'])
missing_unused_key = M.psql("SELECT object_key FROM attachments WHERE id = '%s'::uuid" % missing_unused['id'])
delete_object(missing_used_key)
delete_object(missing_unused_key)
ok(not object_exists(missing_used_key) and not object_exists(missing_unused_key),
'missing objects were not removed from S3')
# The stale orphan must be older than the grace period. The injected rows
# are already older by construction; the S3 object uses its real mtime.
sleep_until_age(stale_started, GRACE)
active_id = str(uuid.uuid4())
active_key = 'attachments/' + active_id
insert_pending(active_id, chat['id'], alice['id'], active_key, sample, 0)
put_object(active_key, sample)
fresh_orphan = 'attachments/orphan-fresh-' + uuid.uuid4().hex
put_object(fresh_orphan, sample)
fresh_started = time.monotonic()
rows_before = attachment_count()
objects_before = M.s3_count()
links_before = link_count()
print('== dry run: detection without mutation ==')
dry = reconcile(False, GRACE, EVIDENCE / 'raw-dry-run.json')
ok(stale_orphan in object_keys(dry, 'orphan_objects'), 'stale orphan object not detected')
ok(fresh_orphan in object_keys(dry, 'protected_recent_objects'), 'fresh orphan object not protected')
ok({crash_one, crash_two} <= item_ids(dry, 'stale_pending'), 'stale upload intents not detected')
ok(active_id in item_ids(dry, 'protected_pending'), 'fresh upload intent not protected')
ok({missing_used['id'], missing_unused['id']} <= item_ids(dry, 'missing_objects'),
'missing objects not detected')
ok(not (dry['actions'].get('deleted_objects') or []), 'dry run deleted objects')
ok(not (dry['actions'].get('deleted_pending_rows') or []), 'dry run deleted rows')
ok(attachment_count() == rows_before and M.s3_count() == objects_before and link_count() == links_before,
'dry run mutated either store')
ok(object_exists(stale_orphan) and object_exists(fresh_orphan), 'dry run removed an object')
ok(object_exists(active_key), 'dry run removed an active upload object')
print('== apply: only provable stale items ==')
def upload_worker(index):
local = Client(c.base)
response = local.call(
'POST', '/api/v1/chats/' + chat['id'] + '/attachments?filename=concurrent-%d.png' % index,
201, actor=alice, raw=sample, headers={'Content-Type': 'image/png'}, schema='Attachment')
return response['json']
upload_pool = concurrent.futures.ThreadPoolExecutor(max_workers=6)
upload_futures = [upload_pool.submit(upload_worker, index) for index in range(6)]
# Run the reconciler while those uploads are in flight. Their rows/objects
# are younger than the grace period and must not be touched.
apply = reconcile(True, GRACE, EVIDENCE / 'raw-apply.json')
uploaded_concurrently = [future.result() for future in upload_futures]
upload_pool.shutdown()
ok(all(item['status'] == 'ready' for item in uploaded_concurrently),
'concurrent upload during reconcile did not finish ready')
deleted_objects = set(apply['actions'].get('deleted_objects') or [])
deleted_rows = set(apply['actions'].get('deleted_pending_rows') or [])
ok(stale_orphan in deleted_objects, 'stale orphan object was not removed')
ok(crash_one in deleted_rows and crash_two in deleted_rows, 'stale pending rows were not removed')
ok(crash_one_key in deleted_objects, 'stale pending object was not removed')
ok(not object_exists(stale_orphan) and not object_exists(crash_one_key) and not object_exists(crash_two_key),
'stale S3 objects survived apply')
ok(M.psql("SELECT count(*) FROM attachments WHERE id IN ('%s'::uuid, '%s'::uuid)" % (crash_one, crash_two)).strip() == '0',
'stale pending rows survived apply')
ok(object_exists(fresh_orphan), 'fresh orphan object was deleted inside grace')
rows_after_apply = rows_before + len(uploaded_concurrently) - 2
ok(object_exists(active_key) and attachment_count() == rows_after_apply,
'active upload, concurrent upload or active row was deleted')
ok({missing_used['id'], missing_unused['id']} <= set(apply['actions'].get('unresolved_missing') or []),
'missing objects were not left for manual recovery')
ok(link_count() == links_before, 'apply changed message attachment links')
ok(M.psql("SELECT status FROM attachments WHERE id = '%s'::uuid" % active_id).strip() == 'pending',
'active upload intent changed state unexpectedly')
# The simulated in-flight upload completes: the same row is promoted ready
# and becomes usable, proving the reconciler protected a real file.
promote_ready(active_id)
active_message = c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 201, actor=alice,
body={'text': '', 'attachment_ids': [active_id]},
headers={'Idempotency-Key': uuid.uuid4().hex}, schema='Message')['json']
ok(active_message['attachment_ids'] == [active_id], 'protected upload cannot be attached after completion')
active_download = c.call('GET', '/api/v1/attachments/' + active_id + '/content', actor=bob)
ok(active_download['bytes'] == sample, 'protected upload bytes changed')
print('== rerun before grace expiry: no new deletions ==')
rerun = reconcile(True, GRACE, EVIDENCE / 'raw-rerun.json')
ok(not (rerun['actions'].get('deleted_objects') or []), 'rerun deleted objects')
ok(not (rerun['actions'].get('deleted_pending_rows') or []), 'rerun deleted rows')
ok(fresh_orphan in object_keys(rerun, 'protected_recent_objects'), 'fresh orphan lost protection on rerun')
ok(object_exists(fresh_orphan), 'fresh orphan removed on rerun')
print('== grace expiry: the fresh orphan is now old enough ==')
sleep_until_age(fresh_started, GRACE)
expired = reconcile(True, GRACE, EVIDENCE / 'raw-after-grace.json')
ok(fresh_orphan in set(expired['actions'].get('deleted_objects') or []),
'aged orphan was not removed after grace')
ok(not object_exists(fresh_orphan), 'aged orphan object still exists')
ok(attachment_count() == rows_after_apply, 'grace expiry deleted a metadata row')
ok(c.call('GET', '/api/v1/attachments/' + active_id + '/content', actor=bob)['bytes'] == sample,
'completed protected attachment lost after grace expiry')
print('== API and used attachments after reconciliation ==')
history = all_messages(c, bob, chat)
indexed = {item['id']: item for item in history}
for message in used_messages:
ok(message['id'] in indexed, 'used message disappeared from history')
ok(indexed[message['id']]['attachment_ids'] == message['attachment_ids'],
'used message lost or reordered its attachment links')
sample_used = used[10]
download = c.call('GET', '/api/v1/attachments/' + sample_used['id'] + '/content', actor=bob)
ok(download['bytes'] == sample, 'used attachment bytes changed or disappeared')
c.call('GET', '/api/v1/attachments/' + sample_used['id'], 404, actor=eve)
c.call('GET', '/api/v1/attachments/' + missing_used['id'], 404, actor=bob)
c.call('GET', '/api/v1/attachments/' + missing_unused['id'] + '/content', 404, actor=bob)
new_attachment = c.call('POST', '/api/v1/chats/' + chat['id'] + '/attachments?filename=after.png', 201,
actor=alice, raw=sample, headers={'Content-Type': 'image/png'},
schema='Attachment')['json']
ok(new_attachment['sha256'] == sha, 'new upload after reconciliation failed')
failures = [item for item in RESULTS if not item['passed']]
summary = {
'track': 'Track 2: consistency of two stores',
'hypothesis': ('A grace-protected, re-checked reconciler removes only stale orphan objects and '
'stale upload intents, and never deletes ready/used/fresh attachments or invents '
'missing bytes.'),
'generated_at': M.now_iso(),
'git_revision': revision,
'api_image_id': api_image,
'database_rows_base': baseline_rows,
'object_store_objects_base': baseline_objects,
'message_attachment_links_base': baseline_links,
'base_profile': {
'attachments': BASE_SIZE,
'linked_attachments': USED_SIZE,
'unlinked_ready_attachments': BASE_SIZE - USED_SIZE,
'bytes_per_attachment': len(sample),
'total_attachment_bytes': BASE_SIZE * len(sample),
'image_profile': 'tests/fixtures/sample.png 320x200, identical synthetic bytes',
},
'grace_seconds': GRACE,
'cost_runs': cost_runs,
'cost_summary': {
'runs': len(cost_runs),
'db_scan_ms_median': statistics.median(run['db_scan_ms'] for run in cost_runs),
's3_list_ms_median': statistics.median(run['s3_list_ms'] for run in cost_runs),
'total_ms_median': statistics.median(run['total_ms'] for run in cost_runs),
'note': 'traversal cost is O(rows + objects); timings are wall-clock milliseconds '
'reported by the reconciler process on this local stand',
},
'injected': {
'stale_orphan_object': stale_orphan,
'stale_pending_with_object': {'id': crash_one, 'object_key': crash_one_key},
'stale_pending_without_object': {'id': crash_two, 'object_key': crash_two_key},
'missing_used_attachment': {'id': missing_used['id'], 'object_key': missing_used_key},
'missing_unused_attachment': {'id': missing_unused['id'], 'object_key': missing_unused_key},
'fresh_orphan_object': fresh_orphan,
'active_upload_intent': {'id': active_id, 'object_key': active_key},
},
'dry_run': {
'orphan_objects': sorted(object_keys(dry, 'orphan_objects')),
'protected_recent_objects': sorted(object_keys(dry, 'protected_recent_objects')),
'stale_pending': sorted(item_ids(dry, 'stale_pending')),
'protected_pending': sorted(item_ids(dry, 'protected_pending')),
'missing_objects': sorted(item_ids(dry, 'missing_objects')),
'deleted_objects': dry['actions'].get('deleted_objects') or [],
'deleted_pending_rows': dry['actions'].get('deleted_pending_rows') or [],
},
'apply': {
'deleted_objects': sorted(deleted_objects),
'deleted_pending_rows': sorted(deleted_rows),
'unresolved_missing': apply['actions'].get('unresolved_missing') or [],
},
'rerun': {
'deleted_objects': rerun['actions'].get('deleted_objects') or [],
'deleted_pending_rows': rerun['actions'].get('deleted_pending_rows') or [],
},
'after_grace': {
'deleted_objects': expired['actions'].get('deleted_objects') or [],
'deleted_pending_rows': expired['actions'].get('deleted_pending_rows') or [],
},
'assertions': RESULTS,
'assertions_failed': len(failures),
'result': 'PASS' if not failures else 'FAIL',
'limitations': [
'The reconciler never deletes or fabricates a missing original: bytes cannot be restored '
'automatically, so those rows are reported as unresolved for operator recovery.',
'A simulated in-flight upload row is used as the deterministic active state; real concurrent '
'uploads are additionally exercised and must finish ready.',
'Cost is measured on this 2 vCPU / ~2 GiB Colima stand and does not extrapolate to production.',
'The S3 ListObjects scan is not a snapshot: concurrent uploads are protected by the grace '
'period and by the immediate database re-check before each delete.',
],
}
M.write_json(EVIDENCE / 'dataset.json', {
'generated_at': summary['generated_at'],
'base_profile': summary['base_profile'],
'attachments': attachments,
'used_messages': [{'id': item['id'], 'attachment_ids': item['attachment_ids']} for item in used_messages],
'concurrent_uploads': [item['id'] for item in uploaded_concurrently],
})
M.write_json(EVIDENCE / 'summary.json', summary)
print(json.dumps({'result': summary['result'], 'assertions': len(RESULTS),
'failed': len(failures), 'cost_ms_median': summary['cost_summary']['total_ms_median']},
ensure_ascii=False))
if failures:
raise SystemExit('FAILED checks: ' + ', '.join(item['check'] for item in failures))
print('PASS: track 2 reconciler experiment')
if __name__ == '__main__':
try:
main()
except (Failure, ValueError, OSError) as exc:
print('FAIL:', str(exc))
raise SystemExit(1)
+335
View File
@@ -0,0 +1,335 @@
#!/usr/bin/env python3
"""Mandatory lab4 upload experiment: >=10 simultaneous uploads + API memory.
Metrics and units (do not confuse them):
* process RSS: VmRSS from /proc/1/status inside each API container, bytes.
This is the resident set of the API process (PID 1), sampled by `docker exec`.
* process peak RSS (HWM): VmHWM from the same file, bytes. The kernel high-water
mark since that process started; the API is restarted before the run so the
baseline is fresh.
* cgroup memory.current / memory.peak: the whole container cgroup, bytes,
including page cache and any other process. It is reported separately and
is NOT presented as process RSS.
The run uploads a reproducible profile of generated PNGs (no giant fixtures in
Git), records real UTC timestamps, per-upload intervals, observed concurrency,
HTTP results and the Sampled RSS of both API replicas. Raw samples and the
compact summary are stored under evidence/experiment/.
Python 3.9+, standard library only. Requires the running stand and Docker.
"""
import concurrent.futures
import datetime as dt
import hashlib
import json
import sys
import threading
import time
import uuid
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tests'))
sys.path.insert(0, str(ROOT / 'scripts'))
from client import Client, Failure, arguments, check # noqa: E402
import lab4_metrics as M # noqa: E402
EVIDENCE = ROOT / 'evidence' / 'experiment'
CONCURRENCY = 12
SAMPLE_INTERVAL_SECONDS = 0.2
def iso_now():
return dt.datetime.now(dt.timezone.utc).isoformat().replace('+00:00', 'Z')
def process_memory(container):
process = M.run(['docker', 'exec', container, 'cat', '/proc/1/status'], check=False)
if process.returncode != 0:
return None
values = {}
for line in process.stdout.splitlines():
if line.startswith('VmRSS:'):
values['rss_bytes'] = int(line.split()[1]) * 1024
elif line.startswith('VmHWM:'):
values['hwm_bytes'] = int(line.split()[1]) * 1024
return values
def cgroup_memory(container):
result = {}
current = M.run(['docker', 'exec', container, 'cat', '/sys/fs/cgroup/memory.current'], check=False)
peak = M.run(['docker', 'exec', container, 'cat', '/sys/fs/cgroup/memory.peak'], check=False)
if current.returncode == 0:
result['current_bytes'] = int(current.stdout.strip())
if peak.returncode == 0:
result['peak_bytes'] = int(peak.stdout.strip())
return result or None
class Sampler(threading.Thread):
def __init__(self, containers):
super().__init__(daemon=True)
self.containers = containers
self.samples = []
self.error = None
self._stop_event = threading.Event() # never name this Thread._stop
def run(self):
try:
while not self._stop_event.is_set():
started = iso_now()
monotonic = time.monotonic()
row = {'sampled_at': started, 'monotonic_seconds': round(monotonic, 6), 'api': {}}
for container in self.containers:
row['api'][container['hostname']] = {
'process': process_memory(container['container_id']),
'cgroup': cgroup_memory(container['container_id']),
}
self.samples.append(row)
self._stop_event.wait(SAMPLE_INTERVAL_SECONDS)
except Exception as exc: # noqa: BLE001 - reported in the summary
self.error = type(exc).__name__ + ': ' + str(exc)
def stop(self):
self._stop_event.set()
def main():
args = arguments('Lab4 >=10 concurrent uploads with API process RSS sampling')
EVIDENCE.mkdir(parents=True, exist_ok=True)
api = M.containers('api')
check(len(api) >= 2, 'the experiment needs at least two API replicas')
api_limit = M.inspect(api[0]['container_id'])['HostConfig'].get('Memory')
gomemlimit = api[0]['env'].get('GOMEMLIMIT', '')
decode_concurrency = api[0]['env'].get('UPLOAD_DECODE_CONCURRENCY', '')
put_concurrency = api[0]['env'].get('S3_PUT_CONCURRENCY', '')
max_upload = api[0]['env'].get('MAX_UPLOAD_BYTES', '')
max_pixels = api[0]['env'].get('MAX_IMAGE_PIXELS', '')
revision = M.run(['git', 'rev-parse', 'HEAD']).stdout.strip()
image_id = api[0]['image_id']
print('== restart API replicas to reset the process high-water mark ==')
M.compose('restart', 'api')
M.wait_ready(120)
api = M.containers('api')
check(len(api) >= 2, 'API replicas did not come back')
restarts_before = {item['hostname']: M.inspect(item['container_id'])['RestartCount'] for item in api}
baseline = {}
for item in api:
baseline[item['hostname']] = {
'process': process_memory(item['container_id']),
'cgroup': cgroup_memory(item['container_id']),
}
print('== generate the reproducible upload profile ==')
profiles = []
for index in range(CONCURRENCY):
if index < 6:
width, height = 1000, 700
profile = 'small'
elif index < 10:
width, height = 1500, 1100
profile = 'medium'
else:
width, height = 1600, 2167
profile = 'near-max-bytes'
data = M.png_random(width, height, seed=1000 + index)
profiles.append({
'index': index,
'profile': profile,
'filename': 'load-%02d.png' % index,
'width': width,
'height': height,
'pixels': width * height,
'bytes': len(data),
'sha256': hashlib.sha256(data).hexdigest(),
'content': data,
})
check(all(item['pixels'] <= 40_000_000 and item['bytes'] <= 10 * 1024 * 1024 for item in profiles),
'generated profile violates contract limits')
check(max(item['bytes'] for item in profiles) > 10 * 1024 * 1024 - 100000,
'profile does not include a near-limit file')
client = Client(args.base_url, args.ca_file, timeout=60)
alice, bob, eve, chat = client.bootstrap()
barrier = threading.Barrier(CONCURRENCY)
def upload(item):
local = Client(args.base_url, args.ca_file, timeout=60)
barrier.wait()
started_monotonic = time.monotonic()
started_utc = iso_now()
response = local.call(
'POST', '/api/v1/chats/' + chat['id'] + '/attachments?filename=' + item['filename'],
201, actor=alice, raw=item['content'],
headers={'Content-Type': 'image/png'}, schema='Attachment')
finished_monotonic = time.monotonic()
return {
'index': item['index'],
'profile': item['profile'],
'filename': item['filename'],
'width': item['width'],
'height': item['height'],
'pixels': item['pixels'],
'bytes': item['bytes'],
'sha256': item['sha256'],
'started_at': started_utc,
'finished_at': iso_now(),
'started_monotonic': started_monotonic,
'finished_monotonic': finished_monotonic,
'duration_ms': round((finished_monotonic - started_monotonic) * 1000, 3),
'status': response['status'],
'instance_id': response['headers'].get('X-Instance-Id', ''),
'attachment_id': response['json']['id'],
'server_sha256': response['json']['sha256'],
'server_size_bytes': response['json']['size_bytes'],
'server_status': response['json']['status'],
}
sampler = Sampler(api)
sampler.start()
started_utc = iso_now()
started_monotonic = time.monotonic()
with concurrent.futures.ThreadPoolExecutor(max_workers=CONCURRENCY) as pool:
results = list(pool.map(upload, profiles))
finished_monotonic = time.monotonic()
finished_utc = iso_now()
time.sleep(0.5)
sampler.stop()
sampler.join(timeout=5)
check(sampler.error is None, 'memory sampler failed: ' + str(sampler.error))
# Observed concurrency from the real client intervals.
events = []
for item in results:
events.append((item['started_monotonic'], 1))
events.append((item['finished_monotonic'], -1))
active = peak = 0
for _, delta in sorted(events, key=lambda pair: (pair[0], -pair[1])):
active += delta
peak = max(peak, active)
per_instance = {}
for item in results:
bucket = per_instance.setdefault(item['instance_id'], {'uploads': 0, 'bytes': 0})
bucket['uploads'] += 1
bucket['bytes'] += item['bytes']
memory = {}
for hostname in baseline:
rss = [row['api'][hostname]['process']['rss_bytes']
for row in sampler.samples
if row['api'].get(hostname) and row['api'][hostname]['process']]
hwm = [row['api'][hostname]['process']['hwm_bytes']
for row in sampler.samples
if row['api'].get(hostname) and row['api'][hostname]['process']]
cgroup = [row['api'][hostname]['cgroup']['current_bytes']
for row in sampler.samples
if row['api'].get(hostname) and row['api'][hostname]['cgroup']]
cgroup_peak = [row['api'][hostname]['cgroup']['peak_bytes']
for row in sampler.samples
if row['api'].get(hostname) and row['api'][hostname]['cgroup']]
memory[hostname] = {
'samples': len(rss),
'baseline_rss_bytes': baseline[hostname]['process']['rss_bytes'] if baseline[hostname]['process'] else None,
'baseline_hwm_bytes': baseline[hostname]['process']['hwm_bytes'] if baseline[hostname]['process'] else None,
'peak_sampled_rss_bytes': max(rss) if rss else None,
'peak_sampled_rss_delta_bytes': (max(rss) - baseline[hostname]['process']['rss_bytes'])
if rss and baseline[hostname]['process'] else None,
'final_hwm_bytes': hwm[-1] if hwm else None,
'peak_cgroup_current_bytes': max(cgroup) if cgroup else None,
'peak_cgroup_memory_peak_bytes': max(cgroup_peak) if cgroup_peak else None,
'api_memory_limit_bytes': api_limit,
}
successes = [item for item in results if item['status'] == 201 and item['server_status'] == 'ready'
and item['server_sha256'] == item['sha256'] and item['server_size_bytes'] == item['bytes']]
failures = [item for item in results if item not in successes]
restarts_after = {item['hostname']: M.inspect(item['container_id'])['RestartCount'] for item in api}
check(len(results) == CONCURRENCY, 'not all uploads returned')
check(len(successes) == CONCURRENCY, 'some uploads failed')
check(peak >= 10, 'observed concurrency below 10: %d' % peak)
check(not failures, 'failed uploads: %r' % [(item['index'], item['status']) for item in failures])
check(restarts_after == restarts_before, 'an API container restarted during the experiment')
for hostname, item in memory.items():
check(item['peak_sampled_rss_bytes'] and item['peak_sampled_rss_bytes'] < api_limit,
'process RSS exceeded the container limit on ' + hostname)
summary = {
'experiment': 'lab4 concurrent upload: peak API process RSS',
'generated_at': iso_now(),
'git_revision': revision,
'api_image_id': image_id,
'base_url': args.base_url,
'started_at': started_utc,
'finished_at': finished_utc,
'wall_seconds': round(finished_monotonic - started_monotonic, 3),
'configured_concurrency': CONCURRENCY,
'observed_peak_concurrency': peak,
'successful_uploads': len(successes),
'failed_uploads': len(failures),
'api_instances': sorted(per_instance),
'uploads_per_instance': per_instance,
'profile': {
'files': len(profiles),
'total_bytes': sum(item['bytes'] for item in profiles),
'min_bytes': min(item['bytes'] for item in profiles),
'max_bytes': max(item['bytes'] for item in profiles),
'max_pixels': max(item['pixels'] for item in profiles),
'small': {'count': 6, 'width': 1000, 'height': 700},
'medium': {'count': 4, 'width': 1500, 'height': 1100},
'near_max_bytes': {'count': 2, 'width': 1600, 'height': 2167},
},
'limits': {
'api_memory_limit_bytes': api_limit,
'GOMEMLIMIT': gomemlimit,
'UPLOAD_DECODE_CONCURRENCY': decode_concurrency,
'S3_PUT_CONCURRENCY': put_concurrency,
'MAX_UPLOAD_BYTES': max_upload,
'MAX_IMAGE_PIXELS': max_pixels,
},
'memory_metrics': {
'process_rss_source': '/proc/1/status VmRSS inside each API container, sampled by docker exec',
'process_hwm_source': '/proc/1/status VmHWM inside each API container',
'cgroup_source': '/sys/fs/cgroup/memory.current and memory.peak (whole container cgroup)',
'sample_interval_seconds': SAMPLE_INTERVAL_SECONDS,
'samples_taken': len(sampler.samples),
'first_sample_at': sampler.samples[0]['sampled_at'] if sampler.samples else None,
'last_sample_at': sampler.samples[-1]['sampled_at'] if sampler.samples else None,
'max_sample_gap_seconds': round(max(
sampler.samples[index]['monotonic_seconds'] - sampler.samples[index - 1]['monotonic_seconds']
for index in range(1, len(sampler.samples))), 3) if len(sampler.samples) > 1 else None,
'per_instance': memory,
},
'uploads': [{key: value for key, value in item.items() if key != 'content'} for item in results],
'result': 'PASS',
'limitations': [
'One local stand: RSS includes Go runtime and handler state, not a production profile.',
'The sampler uses docker exec every 200 ms; a shorter allocation spike between samples is '
'bounded by VmHWM, which is also reported.',
'cgroup memory.current includes page cache and is not process RSS.',
],
}
M.write_json(EVIDENCE / 'uploads.json', summary['uploads'])
M.write_json(EVIDENCE / 'rss-samples.json', {'samples': sampler.samples, 'baseline': baseline})
M.write_json(EVIDENCE / 'summary.json', summary)
print(json.dumps({
'result': 'PASS',
'observed_peak_concurrency': peak,
'successful_uploads': len(successes),
'wall_seconds': summary['wall_seconds'],
'process_peak_sampled_rss_bytes': {key: value['peak_sampled_rss_bytes'] for key, value in memory.items()},
'process_final_hwm_bytes': {key: value['final_hwm_bytes'] for key, value in memory.items()},
'api_memory_limit_bytes': api_limit,
}, ensure_ascii=False))
print('PASS: >=10 concurrent uploads with bounded API process RSS')
if __name__ == '__main__':
try:
main()
except (Failure, ValueError, OSError) as exc:
print('FAIL:', str(exc))
raise SystemExit(1)
Regular → Executable
View File
+16
View File
@@ -0,0 +1,16 @@
#!/bin/sh
# Wait until /health/ready answers 200 through the load balancer.
# Usage: scripts/wait-ready.sh [url]
set -eu
url=${1:-http://127.0.0.1:${LB_PORT:-8084}/health/ready}
attempts=0
while [ "$attempts" -lt 120 ]; do
if curl -fsS -o /dev/null "$url" 2>/dev/null; then
echo "ready: $url"
exit 0
fi
attempts=$((attempts + 1))
sleep 1
done
echo "not ready after 120 seconds: $url" >&2
exit 1
+302
View File
@@ -0,0 +1,302 @@
#!/usr/bin/env python3
"""Lab4 attachment contract checks: limits, MIME, names, ACL, dependency faults.
Expectations in this file are derived from contracts/README.md, not from the
current implementation:
* 10 MiB body limit and 40 MP pixel limit, checked before unbounded read/decode;
* Content-Type is validated against the bytes; corrupt/foreign formats are 415;
* filename is display-only, 1..255 code points, no '/', '\\\\', NUL or controls;
* foreign/unknown metadata and bytes are 404;
* files of another chat cannot be linked to a message (404);
* an unavailable S3 is 503 on upload/download/metadata, while invalid input is
still rejected as a user error (415), never masked as 500;
* an interrupted upload leaves neither an attachment row nor an object.
Python 3.9+, standard library only. Requires the running stand and Docker.
"""
import hashlib
import os
import socket
import sys
import time
import urllib.parse
import uuid
ROOT = __import__('pathlib').Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tests'))
sys.path.insert(0, str(ROOT / 'scripts'))
from client import Client, Failure, arguments, check # noqa: E402
import lab4_metrics as M # noqa: E402
CHECKS = 0
def ok(condition, message):
global CHECKS
CHECKS += 1
check(condition, message)
def upload(c, actor, chat_id, data, filename='test.png', content_type='image/png', status=201):
path = '/api/v1/chats/' + chat_id + '/attachments?filename=' + urllib.parse.quote(filename, safe='')
headers = {'Content-Type': content_type} if content_type else {}
return c.call('POST', path, status, actor=actor, raw=data, headers=headers,
schema='Attachment' if status == 201 else None)
def error_code(response):
return response['json']['error']['code']
def test_size_limits(c, alice, chat):
# 10 MiB + 1 byte: the declared Content-Length is enough for the handler to
# return 413 before it accepts or decodes the content.
oversized = os.urandom(10485761)
response = upload(c, alice, chat['id'], oversized, 'too-big.png', status=413)
ok(error_code(response) == 'payload_too_large', 'declared body over 10 MiB is not 413')
# A real, valid PNG just under the 10 MiB boundary is accepted and stored
# byte-for-byte.
boundary = M.png_random(1600, 2167)
ok(10485760 - len(boundary) < 100000, 'boundary fixture is not near 10 MiB: %d' % len(boundary))
att = upload(c, alice, chat['id'], boundary, 'boundary.png', status=201)['json']
ok(att['size_bytes'] == len(boundary), 'near-limit size changed')
ok(att['sha256'] == hashlib.sha256(boundary).hexdigest(), 'near-limit checksum changed')
download = c.call('GET', '/api/v1/attachments/' + att['id'] + '/content', actor=alice)
ok(download['bytes'] == boundary, 'near-limit download differs')
empty = c.call('POST', '/api/v1/chats/' + chat['id'] + '/attachments?filename=empty.png', 415,
actor=alice, raw=b'', headers={'Content-Type': 'image/png'})
ok(error_code(empty) == 'unsupported_media_type', 'empty body is not 415')
# More than 40 million decoded pixels, but a small compressed file: the
# limit must come from the decoded header, not from the byte size.
huge_pixels = M.png_solid(8000, 5001)
ok(len(huge_pixels) < 10485760, 'pixel-limit fixture unexpectedly large')
response = upload(c, alice, chat['id'], huge_pixels, 'pixels.png', status=413)
ok(error_code(response) == 'payload_too_large', '>40 MP is not 413')
ok(not any(item['size_bytes'] == len(huge_pixels) for item in M.s3_list()),
'>40 MP upload left an object in S3')
print('PASS size and pixel limits')
def test_mime_and_damage(c, alice, chat):
png = M.fixture_bytes('sample.png')
jpeg = (ROOT / 'student-tests/fixtures/sample.jpg').read_bytes()
response = upload(c, alice, chat['id'], png, 'wrong.jpg', 'image/jpeg', status=415)
ok(error_code(response) == 'unsupported_media_type', 'PNG declared as JPEG is not 415')
response = upload(c, alice, chat['id'], jpeg, 'wrong.png', 'image/png', status=415)
ok(error_code(response) == 'unsupported_media_type', 'JPEG declared as PNG is not 415')
response = upload(c, alice, chat['id'], b'not an image at all\n' * 20, 'text.png', 'image/png', status=415)
ok(error_code(response) == 'unsupported_media_type', 'non-image bytes are not 415')
response = upload(c, alice, chat['id'], png[:200], 'truncated.png', 'image/png', status=415)
ok(error_code(response) == 'unsupported_media_type', 'truncated PNG is not 415')
response = upload(c, alice, chat['id'], M.png_corrupt(), 'corrupt.png', 'image/png', status=415)
ok(error_code(response) == 'unsupported_media_type', 'corrupt PNG is not 415')
response = upload(c, alice, chat['id'], png, 'none.png', '', status=415)
ok(error_code(response) == 'unsupported_media_type', 'missing Content-Type is not 415')
response = upload(c, alice, chat['id'], png, 'plain.png', 'text/plain', status=415)
ok(error_code(response) == 'unsupported_media_type', 'text/plain is not 415')
response = upload(c, alice, chat['id'], png, 'multi.png', 'multipart/form-data; boundary=x', status=415)
ok(error_code(response) == 'unsupported_media_type', 'multipart is not 415')
att = upload(c, alice, chat['id'], jpeg, 'real.jpg', 'image/jpeg', status=201)['json']
ok(att['content_type'] == 'image/jpeg' and att['sha256'] == hashlib.sha256(jpeg).hexdigest(),
'JPEG upload metadata mismatch')
download = c.call('GET', '/api/v1/attachments/' + att['id'] + '/content', actor=alice)
ok(download['bytes'] == jpeg and download['headers'].get_content_type() == 'image/jpeg',
'JPEG download mismatch')
# The display name is returned verbatim but never used as a key/path, and
# the public JSON never exposes storage internals.
unicode_name = 'фото 🚀.png'
named = upload(c, alice, chat['id'], png, unicode_name, status=201)['json']
ok(named['filename'] == unicode_name, 'Unicode filename changed')
ok('object_key' not in named and 'bucket' not in named, 'attachment JSON leaks storage internals')
print('PASS MIME, damage and filename display')
def test_filenames(c, alice, chat):
png = M.fixture_bytes('sample.png')
base = '/api/v1/chats/' + chat['id'] + '/attachments'
def expect(query, status):
c.call('POST', base + query, status, actor=alice, raw=png,
headers={'Content-Type': 'image/png'})
expect('', 400) # required parameter
expect('?filename=', 400) # empty
expect('?filename=a.png&filename=b.png', 400) # exactly once
expect('?filename=' + urllib.parse.quote('../evil.png', safe=''), 400)
expect('?filename=' + urllib.parse.quote('..\\evil.png', safe=''), 400)
expect('?filename=' + urllib.parse.quote('bad\x00name.png', safe=''), 400)
expect('?filename=' + urllib.parse.quote('bad\x01name.png', safe=''), 400)
expect('?filename=' + 'a' * 256, 400)
expect('?filename=' + urllib.parse.quote('a' * 255, safe=''), 201)
expect('?filename=' + urllib.parse.quote('./x.png', safe=''), 400)
print('PASS filename validation')
def test_acl(c, alice, bob, eve, chat):
att, content = c.attachment(alice, chat)
for suffix in ('', '/content'):
c.call('GET', '/api/v1/attachments/' + att['id'] + suffix, 404, actor=eve)
c.call('GET', '/api/v1/attachments/' + att['id'], 200, actor=bob)
c.call('GET', '/api/v1/attachments/' + att['id'] + '/content', 200, actor=bob)
png = M.fixture_bytes('sample.png')
response = upload(c, eve, chat['id'], png, 'outsider.png', status=404)
ok(error_code(response) == 'not_found', 'outsider upload is not hidden as 404')
c.call('POST', '/api/v1/chats/not-a-uuid/attachments?filename=x.png', 400, actor=alice,
raw=png, headers={'Content-Type': 'image/png'})
c.call('POST', '/api/v1/chats/' + str(uuid.uuid4()) + '/attachments?filename=x.png', 404,
actor=alice, raw=png, headers={'Content-Type': 'image/png'})
eve_chat = c.call('POST', '/api/v1/chats', 201, actor=eve,
body={'title': 'Чужой чат', 'member_ids': [eve['id']]}, schema='Chat')['json']
foreign, _ = c.attachment(eve, eve_chat)
response = c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 404, actor=alice,
body={'text': 'чужое', 'attachment_ids': [foreign['id']]},
headers={'Idempotency-Key': uuid.uuid4().hex})
ok(error_code(response) == 'not_found', 'foreign attachment link is not 404')
c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 404, actor=alice,
body={'text': 'нет', 'attachment_ids': [str(uuid.uuid4())]},
headers={'Idempotency-Key': uuid.uuid4().hex})
print('PASS attachment ACL')
def test_interrupted_upload(c, alice, chat):
before_rows = int(M.psql("SELECT count(*) FROM attachments"))
before_objects = M.s3_count()
head = (
'POST /api/v1/chats/' + chat['id'] + '/attachments?filename=aborted.png HTTP/1.1\r\n'
'Host: 127.0.0.1\r\n'
'Authorization: Bearer ' + alice['token'] + '\r\n'
'Content-Type: image/png\r\n'
'Content-Length: 4194304\r\n'
'Connection: close\r\n\r\n'
).encode('ascii')
# Send only a prefix of the declared body and close: the server must abort
# the upload without creating metadata or an object.
parsed = urllib.parse.urlsplit(c.base)
connection = socket.create_connection((parsed.hostname, parsed.port or 80), timeout=5)
try:
connection.sendall(head)
connection.sendall(M.fixture_bytes()[:100000])
finally:
connection.close()
time.sleep(1.0)
after_rows = int(M.psql("SELECT count(*) FROM attachments"))
after_objects = M.s3_count()
ok(after_rows == before_rows, 'interrupted upload left an attachment row')
ok(after_objects == before_objects, 'interrupted upload left an S3 object')
print('PASS interrupted upload leaves no row/object')
def test_s3_unavailable(c, alice, bob, chat):
att, content = c.attachment(alice, chat)
try:
M.compose('stop', 's3')
time.sleep(1.0)
png = M.fixture_bytes('sample.png')
response = upload(c, alice, chat['id'], png, 'outage.png', status=503)
ok(error_code(response) == 'unavailable', 'S3 outage upload is not the contract 503')
response = c.call('GET', '/api/v1/attachments/' + att['id'], 503, actor=bob)
ok(error_code(response) == 'unavailable', 'S3 outage metadata is not 503')
response = c.call('GET', '/api/v1/attachments/' + att['id'] + '/content', 503, actor=bob)
ok(error_code(response) == 'unavailable', 'S3 outage download is not 503')
# Invalid input is still a user error, not a fake 500/503: validation
# runs before any S3 access.
response = upload(c, alice, chat['id'], b'broken image', 'broken.png', status=415)
ok(error_code(response) == 'unsupported_media_type', 'bad image masked as dependency error')
# The message path does not depend on S3 and must keep working.
c.message(alice, chat, 'сообщение при недоступном S3')
finally:
M.compose('start', 's3')
M.wait_healthy('s3', 60)
# Docker's embedded DNS needs a moment to publish the restarted alias
# again; retry the first upload instead of asserting instantaneous recovery.
deadline = time.monotonic() + 30
while True:
try:
upload(c, alice, chat['id'], M.fixture_bytes('sample.png'), 'recovered.png', status=201)
break
except Failure:
if time.monotonic() >= deadline:
raise
time.sleep(0.5)
ok(c.call('GET', '/api/v1/attachments/' + att['id'] + '/content', actor=bob)['bytes'] == content,
'existing attachment changed after S3 restart')
print('PASS unavailable S3 is 503, not 500, and recovers')
def test_database_unavailable(c, alice, chat):
try:
M.compose('stop', 'postgres')
deadline = time.monotonic() + 30
while time.monotonic() < deadline:
try:
c.call('GET', '/health/ready', 503)
break
except Failure:
time.sleep(0.5)
else:
raise Failure('readiness did not become 503 while PostgreSQL was stopped')
live = c.call('GET', '/health/live', schema='Health')
ok(live['status'] == 200, 'liveness failed while PostgreSQL was down')
response = c.call('GET', '/api/v1/users/me', 503, actor=alice)
ok(error_code(response) == 'unavailable', 'DB outage /users/me is not 503')
response = c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 503, actor=alice,
body={'text': 'пока БД лежит'}, headers={'Idempotency-Key': uuid.uuid4().hex})
ok(error_code(response) == 'unavailable', 'DB outage message is not 503')
# Authentication shape is checked before the database: a malformed
# bearer header is still a user-level 401, not a masked 500/503.
c.call('GET', '/api/v1/users/me', 401, headers={'Authorization': 'Bearer short'})
finally:
M.compose('start', 'postgres')
M.wait_ready(120)
c.message(alice, chat, 'после восстановления БД')
print('PASS unavailable PostgreSQL is 503, liveness stays up, data recovers')
def test_log_privacy(c, alice, chat):
sentinel = 'SENTINEL-' + uuid.uuid4().hex
c.message(alice, chat, sentinel)
password = alice['registration']['password']
token = alice['token']
api = M.compose_ids('api')
ok(len(api) >= 2, 'need at least two API containers to inspect both logs')
secret = M.env_value(api[0], 'S3_SECRET_KEY')
admin = M.env_value(api[0], 'S3_ADMIN_SECRET_KEY')
logs = M.compose('logs', '--no-color', 'api').stdout
ok(token not in logs, 'session token leaked into API logs')
ok(password not in logs, 'password leaked into API logs')
ok(sentinel not in logs, 'message text leaked into API logs')
ok(secret and secret not in logs, 'S3 API secret leaked into API logs')
ok(not admin, 'administrative S3 secret is present in the API container')
print('PASS no token/password/message/S3 secret in API logs')
def main():
args = arguments('Lab4 attachment limits, ACL and dependency faults; creates synthetic data')
c = Client(args.base_url, args.ca_file)
alice, bob, eve, chat = c.bootstrap()
test_size_limits(c, alice, chat)
test_mime_and_damage(c, alice, chat)
test_filenames(c, alice, chat)
test_acl(c, alice, bob, eve, chat)
test_interrupted_upload(c, alice, chat)
test_s3_unavailable(c, alice, bob, chat)
test_database_unavailable(c, alice, chat)
test_log_privacy(c, alice, chat)
print('PASS: lab4 attachment checks, %d assertions' % CHECKS)
if __name__ == '__main__':
try:
main()
except (Failure, ValueError, OSError) as exc:
print('FAIL:', str(exc))
raise SystemExit(1)
+650
View File
@@ -0,0 +1,650 @@
#!/usr/bin/env python3
"""Own black-box tests for lab4. They complement, and never weaken, tests/smoke.py.
The suite assumes a running stack (make up) and creates only synthetic data.
It keeps the lab3 regression surface — exact JSON keys, strict input
validation, Bearer-only business API, membership hiding as 404, keyset
pagination, concurrent registration/messages/idempotency — and adds the lab4
attachment regression: message attachment_ids, attachment-only messages and
idempotency over the attachment payload. Deep upload limits and ACL negatives
live in student-tests/attachment-checks.py.
Python 3.9+, standard library only.
"""
import base64
import concurrent.futures
import datetime as dt
import json
import sys
import threading
import uuid
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tests'))
from client import Client, arguments, check, timestamp # noqa: E402
CHECKS = 0
def ok(condition, message):
global CHECKS
CHECKS += 1
check(condition, message)
def expect_keys(payload, expected, where):
ok(set(payload) == set(expected), where + ': JSON keys differ: ' + repr(sorted(payload)))
def basic(username, password):
return 'Basic ' + base64.b64encode((username + ':' + password).encode('utf-8')).decode('ascii')
def register(c, username=None, display_name=None, password=None):
username = username or 'bb_' + uuid.uuid4().hex[:12]
password = password or 'B3st-' + uuid.uuid4().hex
display_name = display_name or 'Тестовый пользователь'
body = {'username': username, 'display_name': display_name, 'password': password}
user = c.call('POST', '/api/v1/users', 201, body=body, schema='User')['json']
expect_keys(user, {'id', 'username', 'display_name', 'created_at'}, 'User')
return {'id': user['id'], 'user': user, 'registration': body, 'password': password}
def login(c, actor):
response = c.call('POST', '/api/v1/auth/sessions', 201,
headers={'Authorization': basic(actor['registration']['username'], actor['password'])},
schema='Session')['json']
expect_keys(response, {'token', 'token_type', 'expires_at', 'user'}, 'Session')
actor['token'] = response['token']
actor['session'] = response
return actor
def new_chat(c, actor, title, member_ids):
return c.call('POST', '/api/v1/chats', 201, actor=actor,
body={'title': title, 'member_ids': member_ids}, schema='Chat')['json']
def key():
return uuid.uuid4().hex
def send_with_key(c, actor, chat, text, idem, headers=None):
merged = {'Idempotency-Key': idem}
merged.update(headers or {})
return c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 201, actor=actor,
body={'text': text}, headers=merged, schema='Message')['json']
def send(c, actor, chat, text, headers=None):
return send_with_key(c, actor, chat, text, key(), headers)
def all_messages(c, actor, chat, limit=100):
path = '/api/v1/chats/' + chat['id'] + '/messages?limit=' + str(limit)
items, seen = [], set()
for _ in range(1000):
page = c.call('GET', path, actor=actor, schema='MessagePage')['json']
items.extend(page['items'])
if page['next_cursor'] is None:
return items
ok(page['next_cursor'] not in seen, 'message cursor cycle')
seen.add(page['next_cursor'])
from urllib.parse import quote
path = ('/api/v1/chats/' + chat['id'] + '/messages?limit=' + str(limit) +
'&cursor=' + quote(page['next_cursor'], safe=''))
raise AssertionError('message pagination exceeded safety bound')
def sorted_messages(items):
return sorted(items, key=lambda x: (timestamp(x['created_at']), uuid.UUID(x['id']).int))
def test_health(c):
live = c.call('GET', '/health/live', schema='Health')
ok(live['json'] == {'status': 'ok'}, 'liveness body')
ok(bool(live['headers'].get('X-Request-Id')), 'liveness X-Request-Id')
ok(bool(live['headers'].get('X-Instance-Id')), 'liveness X-Instance-Id')
ready = c.call('GET', '/health/ready', schema='Health')
ok(ready['json'] == {'status': 'ok'}, 'readiness body')
print('PASS health')
def test_registration_and_login(c):
alice = register(c)
bob = register(c)
login(c, alice)
login(c, bob)
ok(len(alice['session']['token']) >= 32, 'session token shorter than contract minimum')
ok(alice['session']['token_type'] == 'Bearer', 'token_type')
ok(timestamp(alice['session']['expires_at']) > dt.datetime.now(dt.timezone.utc), 'expiry in the past')
ok(alice['session']['user'] == alice['user'], 'session user differs from created user')
# Duplicate username, including a different display name/password.
c.call('POST', '/api/v1/users', 409, body={
'username': alice['registration']['username'],
'display_name': 'Другой',
'password': 'Another-password-123',
})
# Wrong / unknown / malformed credentials all give the same Basic 401.
c.call('POST', '/api/v1/auth/sessions', 401, headers={'Authorization': basic(alice['registration']['username'], 'wrong-password-123')})
c.call('POST', '/api/v1/auth/sessions', 401, headers={'Authorization': basic('definitely_unknown', 'wrong-password-123')})
c.call('POST', '/api/v1/auth/sessions', 401, headers={'Authorization': 'Basic !!!!'})
c.call('POST', '/api/v1/auth/sessions', 401, headers={'Authorization': 'Basic ' + base64.b64encode(b'no-colon').decode()})
c.call('POST', '/api/v1/auth/sessions', 401, headers={'Authorization': 'Bearer abcdefghijklmnopqrstuvwxyz'})
# Basic is not accepted on business endpoints; X-User-Id grants nothing.
c.call('GET', '/api/v1/users/me', 401, headers={'Authorization': basic(alice['registration']['username'], alice['password'])})
c.call('GET', '/api/v1/users/me', 401, headers={'X-User-Id': alice['id']})
c.call('GET', '/api/v1/users/me', 401, headers={'Authorization': 'Bearer ' + 'a' * 43})
c.call('GET', '/api/v1/users/me', 401, headers={'Authorization': 'X-User-Id ' + alice['id']})
me = c.call('GET', '/api/v1/users/me', actor=alice, headers={'X-User-Id': bob['id']}, schema='User')['json']
ok(me['id'] == alice['id'], 'X-User-Id overrode the bearer identity')
# A UTF-8 password containing colons is valid and is not truncated at the
# first colon by Basic parsing.
unicode_password = 'pässwörd:with:12'
unicode_user = register(c, password=unicode_password)
login(c, unicode_user)
ok(unicode_user['session']['user']['username'] == unicode_user['registration']['username'], 'unicode password login')
# Session JSON must never contain the password or its hash.
serialized = json.dumps(alice['session'], ensure_ascii=False)
for forbidden in ('password', 'argon2', 'salt'):
ok(forbidden not in serialized, 'session leaks ' + forbidden)
print('PASS registration/auth')
def test_registration_validation(c):
username = 'bb_' + uuid.uuid4().hex[:10]
password = 'B3st-' + uuid.uuid4().hex
valid = {'username': username, 'display_name': 'Имя', 'password': password}
def bad(body, status=400, raw=None, headers=None):
c.call('POST', '/api/v1/users', status, body=body if raw is None else None, raw=raw,
headers=headers)
bad({'username': username, 'display_name': 'Имя'})
bad({'username': username, 'display_name': 'Имя', 'password': 'short'})
bad({'username': username, 'display_name': 'Имя', 'password': 'p' * 129})
bad({'username': username, 'display_name': 'Имя', 'password': ' ' * 12})
bad({'username': 'ab', 'display_name': 'Имя', 'password': password})
bad({'username': 'a' * 33, 'display_name': 'Имя', 'password': password})
bad({'username': 'UPPER', 'display_name': 'Имя', 'password': password})
bad({'username': 'bad-name', 'display_name': 'Имя', 'password': password})
bad({'username': 'бвт', 'display_name': 'Имя', 'password': password})
bad({'username': username, 'display_name': '', 'password': password})
bad({'username': username, 'display_name': ' ', 'password': password})
bad({'username': username, 'display_name': 'Имя', 'password': password, 'extra': 1})
bad({'username': username, 'display_name': 'Имя', 'password': password, 'Password': 'x'})
bad({'Username': username, 'display_name': 'Имя', 'password': password})
bad({'username': username, 'display_name': 'Имя', 'password': 123456789012})
bad({'username': None, 'display_name': 'Имя', 'password': password})
bad({}, raw=b'{', headers={'Content-Type': 'application/json'})
bad({}, raw=b'[]', headers={'Content-Type': 'application/json'})
bad({}, status=415, raw=json.dumps(valid).encode(), headers={'Content-Type': 'text/plain'})
bad({}, raw=(json.dumps(valid)[:-1] + ', "username": "x"}').encode(), headers={'Content-Type': 'application/json'})
# Exact code-point boundaries.
long_name = register(c, display_name='😀' * 100)
ok(long_name['user']['display_name'] == '😀' * 100, '100 code points display_name changed')
c.call('POST', '/api/v1/users', 400, body={
'username': 'bb_' + uuid.uuid4().hex[:10],
'display_name': '😀' * 101,
'password': password,
})
c.call('POST', '/api/v1/users', 400, body={
'username': 'a' * 32 + 'b',
'display_name': 'Имя', 'password': password,
})
register(c, username='a' * 24 + uuid.uuid4().hex[:8])
print('PASS registration validation')
def test_chats(c, alice, bob, eve):
chat = new_chat(c, alice, 'Комната с Unicode 🚀', [alice['id'], bob['id']])
ok(set(chat['member_ids']) == {alice['id'], bob['id']}, 'chat member set')
expect_keys(chat, {'id', 'title', 'member_ids', 'created_at'}, 'Chat')
def bad(body, status=400):
c.call('POST', '/api/v1/chats', status, actor=alice, body=body)
bad({'title': 'Без автора', 'member_ids': [bob['id']]})
bad({'title': 'Дубликат', 'member_ids': [alice['id'], alice['id']]})
bad({'title': 'Неизвестный', 'member_ids': [alice['id'], str(uuid.uuid4())]})
bad({'title': 'Не UUID', 'member_ids': [alice['id'], 'not-a-uuid']})
bad({'title': 'Слишком много', 'member_ids': [alice['id']] + [str(uuid.uuid4()) for _ in range(100)]})
bad({'title': '', 'member_ids': [alice['id']]})
bad({'title': ' ', 'member_ids': [alice['id']]})
bad({'title': 'я' * 101, 'member_ids': [alice['id']]})
bad({'title': 'Лишнее', 'member_ids': [alice['id']], 'extra': True})
bad({'title': 'Нет списка'})
own = c.call('GET', '/api/v1/chats/' + chat['id'], actor=bob, schema='Chat')['json']
ok(own['id'] == chat['id'], 'member cannot read chat')
c.call('GET', '/api/v1/chats/' + chat['id'], 404, actor=eve)
c.call('GET', '/api/v1/chats/' + str(uuid.uuid4()), 404, actor=alice)
c.call('GET', '/api/v1/chats/not-a-uuid', 400, actor=alice)
c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 404, actor=eve,
body={'text': 'чужое'}, headers={'Idempotency-Key': key()})
hidden = c.call('GET', '/api/v1/chats?limit=100', actor=eve, schema='ChatPage')['json']
ok(all(item['id'] != chat['id'] for item in hidden['items']), 'foreign chat leaked into list')
listed = c.call('GET', '/api/v1/chats?limit=100', actor=bob, schema='ChatPage')['json']
ok(any(item['id'] == chat['id'] for item in listed['items']), 'member chat missing from list')
print('PASS chats/membership')
def test_messages(c, alice, bob, eve, chat):
text = 'Привет 👋 e\u0301 中文'
message = send(c, alice, chat, text)
expect_keys(message, {'id', 'chat_id', 'sender_id', 'text', 'created_at', 'attachment_ids'}, 'Message')
ok(message['attachment_ids'] == [], 'attachment_ids must default to an empty array')
ok(message['text'] == text, 'message text changed')
ok(message['sender_id'] == alice['id'] and message['chat_id'] == chat['id'], 'message identity')
# X-User-Id cannot substitute for the Bearer owner.
spoofed = send(c, alice, chat, 'не от Боба', headers={'X-User-Id': bob['id']})
ok(spoofed['sender_id'] == alice['id'], 'X-User-Id changed the message sender')
def bad(actor, body, status=400, raw=None, headers=None):
merged = {'Idempotency-Key': key()}
merged.update(headers or {})
c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', status, actor=actor,
body=body, raw=raw, headers=merged)
bad(alice, {'text': ''})
bad(alice, {'text': ' '})
bad(alice, {'text': None})
bad(alice, {})
bad(alice, {'text': 'x' * 4001})
bad(alice, {'text': 'ok', 'sender_id': alice['id']})
bad(alice, {'text': 'ok', 'attachment_ids': None})
bad(alice, {'text': 'ok', 'attachment_ids': 'not-an-array'})
bad(alice, {'text': 'ok', 'attachment_ids': ['not-a-uuid']})
bad(alice, {'text': 'ok', 'attachment_ids': [str(uuid.uuid4()), str(uuid.uuid4())] * 6})
bad(alice, {'Text': 'ok'})
c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 400, actor=alice,
raw=b'{', headers={'Content-Type': 'application/json', 'Idempotency-Key': key()})
# Resource access is checked before body parsing: a foreign chat with a
# malformed body still looks like a missing chat.
c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 404, actor=eve,
raw=b'{', headers={'Content-Type': 'application/json', 'Idempotency-Key': key()})
boundary = send(c, alice, chat, 'я' * 4000)
ok(len(boundary['text']) == 4000, '4000 code point message changed')
history = all_messages(c, bob, chat)
ok(any(item == boundary for item in history), 'member cannot read message history')
print('PASS messages')
def test_pagination(c, alice, bob):
chat = new_chat(c, alice, 'Пагинация', [alice['id'], bob['id']])
for index in range(23):
send(c, alice if index % 2 == 0 else bob, chat, 'строка %02d' % index)
expected = sorted_messages(all_messages(c, alice, chat, limit=100))
collected = []
cursor = None
limits = [7, 5, 100, 1, 3, 9]
step = 0
while True:
path = '/api/v1/chats/' + chat['id'] + '/messages?limit=' + str(limits[step % len(limits)])
if cursor:
from urllib.parse import quote
path += '&cursor=' + quote(cursor, safe='')
page = c.call('GET', path, actor=bob, schema='MessagePage')['json']
collected.extend(page['items'])
step += 1
if page['next_cursor'] is None:
break
cursor = page['next_cursor']
ok(step < 100, 'pagination did not finish')
ok(collected == expected, 'pagination lost, duplicated or reordered messages')
ids = [item['id'] for item in collected]
ok(len(ids) == len(set(ids)), 'pagination repeated an id')
first = c.call('GET', '/api/v1/chats/' + chat['id'] + '/messages?limit=3', actor=alice, schema='MessagePage')['json']
ok(first['next_cursor'] is not None, 'first page cursor missing')
other = new_chat(c, alice, 'Другой чат', [alice['id']])
c.call('GET', '/api/v1/chats/' + other['id'] + '/messages?cursor=' + first['next_cursor'], 400, actor=alice)
c.call('GET', '/api/v1/chats/' + chat['id'] + '/messages?cursor=not-base64!!', 400, actor=alice)
c.call('GET', '/api/v1/chats/' + chat['id'] + '/messages?limit=0', 400, actor=alice)
c.call('GET', '/api/v1/chats/' + chat['id'] + '/messages?limit=101', 400, actor=alice)
c.call('GET', '/api/v1/chats/' + chat['id'] + '/messages?limit=abc', 400, actor=alice)
c.call('GET', '/api/v1/chats/' + chat['id'] + '/messages?limit=1&limit=2', 400, actor=alice)
c.call('GET', '/api/v1/chats/' + chat['id'] + '/messages?cursor=', 400, actor=alice)
# A message cursor is scoped to a chat and cannot continue the chat list.
c.call('GET', '/api/v1/chats?cursor=' + first['next_cursor'], 400, actor=alice)
listed = c.call('GET', '/api/v1/chats?limit=100', actor=alice, schema='ChatPage')['json']
ok(any(item['id'] == chat['id'] for item in listed['items']), 'paginated chat missing from list')
ok(any(item['id'] == other['id'] for item in listed['items']), 'other chat missing from list')
print('PASS pagination')
def test_concurrent_registration(c):
username = 'race_' + uuid.uuid4().hex[:10]
body = {'username': username, 'display_name': 'Гонка', 'password': 'Race-password-123'}
def attempt(_):
local = Client(c.base)
try:
return local.call('POST', '/api/v1/users', (201, 409), body=body)['status']
except Exception as exc: # failures are assertions for this test
return 'error:' + type(exc).__name__
barrier = threading.Barrier(8)
def synchronized_attempt(index):
barrier.wait()
return attempt(index)
with concurrent.futures.ThreadPoolExecutor(max_workers=8) as pool:
statuses = list(pool.map(synchronized_attempt, range(8)))
ok(statuses.count(201) == 1, 'concurrent registration: expected exactly one 201, got ' + repr(statuses))
ok(statuses.count(409) == 7, 'concurrent registration: expected seven 409, got ' + repr(statuses))
c.call('POST', '/api/v1/auth/sessions', 201, headers={'Authorization': basic(username, 'Race-password-123')}, schema='Session')
print('PASS concurrent registration')
def test_concurrent_messages(c, alice, bob):
chat = new_chat(c, alice, 'Конкурентная запись', [alice['id'], bob['id']])
def worker(index):
local = Client(c.base)
actor = alice if index % 2 == 0 else bob
return local.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 201, actor=actor,
body={'text': 'concurrent %02d' % index},
headers={'Idempotency-Key': key()}, schema='Message')['json']
with concurrent.futures.ThreadPoolExecutor(max_workers=12) as pool:
messages = list(pool.map(worker, range(24)))
ids = [message['id'] for message in messages]
ok(len(ids) == 24 and len(set(ids)) == 24, 'concurrent messages produced duplicate ids')
for index, message in enumerate(messages):
ok(message['sender_id'] == (alice['id'] if index % 2 == 0 else bob['id']), 'concurrent sender mismatch')
history = all_messages(c, alice, chat)
ok(len(history) == 24, 'concurrent history has %d rows, want 24' % len(history))
ok(sorted_messages(history) == history, 'concurrent history is not ordered by (created_at, id)')
ok([item['text'] for item in history].count('concurrent 00') == 1, 'concurrent duplicate text')
print('PASS concurrent messages')
def test_logout(c, alice):
second = login(c, {'id': alice['id'], 'user': alice['user'],
'registration': alice['registration'], 'password': alice['password']})
first_token = alice['token']
c.call('DELETE', '/api/v1/auth/sessions/current', 204, actor=alice)
c.call('GET', '/api/v1/users/me', 401, actor={'token': first_token})
c.call('DELETE', '/api/v1/auth/sessions/current', 401, actor={'token': first_token})
me = c.call('GET', '/api/v1/users/me', actor=second, schema='User')['json']
ok(me['id'] == alice['id'], 'logout revoked another session of the same user')
alice['token'] = second['token']
print('PASS logout')
def test_instances(c, alice):
"""One session served by at least two real processes through the LB."""
seen = set()
for _ in range(40):
response = c.call('GET', '/api/v1/users/me', actor=alice, schema='User')
instance = response['headers']['X-Instance-Id']
seen.add(instance)
ok(not response['headers'].get('Set-Cookie'), 'LB introduced a sticky cookie')
ok(len(seen) >= 2, 'only one X-Instance-Id observed; run the default >=2 replicas')
ok(all(instance for instance in seen), 'empty X-Instance-Id')
# The same token keeps working while the LB moves it between processes.
ready = c.call('GET', '/health/ready', schema='Health')
ok(ready['headers']['X-Instance-Id'] in seen, 'health and business endpoints disagree on replicas')
missing = c.call('GET', '/api/v1/chats/' + str(uuid.uuid4()), 404, actor=alice)
ok(bool(missing['headers']['X-Instance-Id']), 'error response missing X-Instance-Id')
ok(missing['json']['error']['request_id'] == missing['headers']['X-Request-Id'],
'error request_id differs from X-Request-Id')
print('PASS instances (%d observed) ' % len(seen))
def test_idempotency(c, alice, bob, eve, chat):
text = 'Идемпотентность ✅ e\u0301'
idem = key()
first = send_with_key(c, alice, chat, text, idem)
expect_keys(first, {'id', 'chat_id', 'sender_id', 'text', 'created_at', 'attachment_ids'}, 'Message')
replay = send_with_key(c, alice, chat, text, idem)
ok(replay == first, 'sequential replay returned a different Message')
# JSON whitespace and escapes are not part of the semantic body.
raw = json.dumps({'text': text}, ensure_ascii=True, indent=2).encode('utf-8')
escaped = c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 201,
actor=alice, raw=raw,
headers={'Content-Type': 'application/json', 'Idempotency-Key': idem},
schema='Message')['json']
ok(escaped == first, 'semantically equal JSON did not replay the message')
# A different body with the same key is a conflict and must not append.
c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 409, actor=alice,
body={'text': 'другой body'}, headers={'Idempotency-Key': idem})
# The original body is still the recorded result after a conflict.
ok(send_with_key(c, alice, chat, text, idem) == first, 'conflict replaced the stored result')
# Scope includes the user and the chat path, so the same key is independent.
other = new_chat(c, alice, 'Другой чат идемпотентности', [alice['id'], bob['id']])
other_message = send_with_key(c, alice, other, text, idem)
ok(other_message['id'] != first['id'] and other_message['chat_id'] == other['id'],
'same key leaked across chats')
bob_message = send_with_key(c, bob, chat, text, idem)
ok(bob_message['id'] != first['id'] and bob_message['sender_id'] == bob['id'],
'same key leaked across users')
# The outsider cannot replay or inspect alice's record: scope + access = 404.
c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 404, actor=eve,
body={'text': text}, headers={'Idempotency-Key': idem})
# Header validation is exact ASCII [A-Za-z0-9._:-]{1,128}.
def bad_key(value, status=400):
headers = {} if value is None else {'Idempotency-Key': value}
c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', status, actor=alice,
body={'text': 'ключ'}, headers=headers)
bad_key(None)
bad_key('')
bad_key('bad key')
bad_key('ключ'.encode('utf-8').decode('latin-1')) # raw non-ASCII header bytes
bad_key('a' * 129)
accepted = 'A.-_:z9' + 'x' * 121
ok(len(accepted) == 128, 'test key length')
boundary = send_with_key(c, alice, chat, 'максимальный ключ', accepted)
ok(boundary['text'] == 'максимальный ключ', '128-character key rejected')
# Revoked/unknown session is checked before the idempotency record.
temp = login(c, register(c))
temp_chat = new_chat(c, temp, 'Сессия и ключ', [temp['id'], alice['id']])
temp_key = key()
keep = send_with_key(c, temp, temp_chat, 'до logout', temp_key)
c.call('DELETE', '/api/v1/auth/sessions/current', 204, actor=temp)
c.call('POST', '/api/v1/chats/' + temp_chat['id'] + '/messages', 401,
actor={'token': temp['token']}, body={'text': 'до logout'},
headers={'Idempotency-Key': temp_key})
# A different user's valid session cannot inherit the record.
c.call('POST', '/api/v1/chats/' + temp_chat['id'] + '/messages', 404, actor=bob,
body={'text': 'до logout'}, headers={'Idempotency-Key': temp_key})
ok(keep['sender_id'] == temp['id'], 'temporary message identity')
print('PASS idempotency replay/conflict/scope/validation')
def test_idempotency_concurrency(c, alice, bob, chat):
"""Concurrent same-key POSTs through several replicas must be exactly-once."""
text = 'конкурентная идемпотентность ' + uuid.uuid4().hex
idem = key()
barrier = threading.Barrier(16)
def worker(index):
local = Client(c.base)
barrier.wait()
response = local.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 201,
actor=alice, body={'text': text},
headers={'Idempotency-Key': idem}, schema='Message')
return response['json'], response['headers']['X-Instance-Id']
with concurrent.futures.ThreadPoolExecutor(max_workers=16) as pool:
results = list(pool.map(worker, range(16)))
ids = {item['id'] for item, _ in results}
instances = {instance for _, instance in results}
ok(len(ids) == 1, 'concurrent replay returned %d distinct messages' % len(ids))
ok(len(instances) >= 2, 'concurrent replay did not cross replicas: ' + repr(instances))
history = [m for m in all_messages(c, bob, chat) if m['text'] == text]
ok(len(history) == 1, 'concurrent replay appended %d rows' % len(history))
# Different bodies racing for one key: one winner, one row, the rest 409.
mixed_key = key()
barrier = threading.Barrier(12)
def mixed(index):
local = Client(c.base)
payload = 'вариант A' if index % 2 == 0 else 'вариант B'
barrier.wait()
try:
response = local.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', (201, 409),
actor=bob, body={'text': payload},
headers={'Idempotency-Key': mixed_key}, schema='Message')
return response['status'], response['json']
except Exception as exc: # noqa: BLE001 - a status other than 201/409 is a failure below
return 'error:' + type(exc).__name__, None
with concurrent.futures.ThreadPoolExecutor(max_workers=12) as pool:
outcomes = list(pool.map(mixed, range(12)))
statuses = [status for status, _ in outcomes]
ok(set(statuses) <= {201, 409}, 'mixed race produced unexpected results: ' + repr(statuses))
winners = [payload for status, payload in outcomes if status == 201]
ok(len({item['id'] for item in winners}) == 1, 'mixed race produced more than one message')
ok(any(status == 409 for status in statuses), 'mixed race did not produce a conflict')
stored = [m for m in all_messages(c, alice, chat)
if m['text'] in ('вариант A', 'вариант B') and m['id'] == winners[0]['id']]
ok(len(stored) == 1, 'mixed race stored a different or duplicate message')
print('PASS concurrent idempotency across %d replicas' % len(instances))
def upload(c, actor, chat, raw=None, filename='sample.png', content_type='image/png', status=201):
if raw is None:
raw = (ROOT / 'tests/fixtures/sample.png').read_bytes()
return c.call('POST', '/api/v1/chats/' + chat['id'] + '/attachments?filename=' + filename,
status, actor=actor, raw=raw, headers={'Content-Type': content_type},
schema='Attachment' if status == 201 else None)
def test_attachments(c, alice, bob, eve, chat):
att, content = c.attachment(alice, chat)
expect_keys(att, {'id', 'chat_id', 'owner_id', 'filename', 'content_type', 'size_bytes',
'sha256', 'status', 'variants', 'error_code', 'created_at', 'updated_at'}, 'Attachment')
ok(att['status'] == 'ready' and att['variants'] == [] and att['error_code'] is None,
'lab4 upload must return ready with no variants and no error')
# A message may be attachment-only: text="" is legal with at least one
# attachment of this chat, and the order of ids is preserved.
second, _ = c.attachment(alice, chat)
message = c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 201, actor=alice,
body={'text': '', 'attachment_ids': [second['id'], att['id']]},
headers={'Idempotency-Key': key()}, schema='Message')['json']
ok(message['text'] == '' and message['attachment_ids'] == [second['id'], att['id']],
'attachment-only message lost text or order')
history = all_messages(c, bob, chat)
ok(any(item == message for item in history), 'member cannot read a message with attachments')
# Both endpoints enforce chat membership; a foreign id is indistinguishable
# from an absent one.
for suffix in ('', '/content'):
c.call('GET', '/api/v1/attachments/' + att['id'] + suffix, 404, actor=eve)
c.call('GET', '/api/v1/attachments/' + str(uuid.uuid4()) + suffix, 404, actor=alice)
c.call('GET', '/api/v1/attachments/' + att['id'] + '/content', 200, actor=bob)
c.call('GET', '/api/v1/attachments/' + att['id'] + '/content?variant=original', 200, actor=bob)
c.call('GET', '/api/v1/attachments/' + att['id'] + '/content?variant=thumbnail', 404, actor=bob)
# An attachment from another chat cannot be linked, even by its owner.
eve_chat = new_chat(c, eve, 'Чужой чат', [eve['id']])
foreign, _ = c.attachment(eve, eve_chat)
c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 404, actor=alice,
body={'text': 'чужая картинка', 'attachment_ids': [foreign['id']]},
headers={'Idempotency-Key': key()})
c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 404, actor=alice,
body={'text': 'нет такой', 'attachment_ids': [str(uuid.uuid4())]},
headers={'Idempotency-Key': key()})
# The owner of the foreign attachment still cannot link it here.
c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 404, actor=eve,
body={'text': 'чужое', 'attachment_ids': [foreign['id']]},
headers={'Idempotency-Key': key()})
# And the same attachment works in its own chat.
own = c.call('POST', '/api/v1/chats/' + eve_chat['id'] + '/messages', 201, actor=eve,
body={'text': '', 'attachment_ids': [foreign['id']]},
headers={'Idempotency-Key': key()}, schema='Message')['json']
ok(own['attachment_ids'] == [foreign['id']], 'attachment cannot be used in its own chat')
# Attachment ids are unique, limited to ten and syntactically valid UUIDs.
for ids in ([att['id']] * 2,
[str(uuid.uuid4()) for _ in range(11)],
['not-a-uuid']):
c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 400, actor=alice,
body={'text': 'x', 'attachment_ids': ids},
headers={'Idempotency-Key': key()})
# Idempotency covers the attachment payload: [] is the same as an absent
# field, while a different set of ids with the same key is a conflict.
plain_key = key()
plain = c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 201, actor=alice,
body={'text': 'без вложений'}, headers={'Idempotency-Key': plain_key},
schema='Message')['json']
explicit = c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 201, actor=alice,
body={'text': 'без вложений', 'attachment_ids': []},
headers={'Idempotency-Key': plain_key}, schema='Message')['json']
ok(explicit == plain, 'absent attachment_ids and [] are not semantically equal')
c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 409, actor=alice,
body={'text': 'без вложений', 'attachment_ids': [att['id']]},
headers={'Idempotency-Key': plain_key})
with_key = key()
first = c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 201, actor=alice,
body={'text': '', 'attachment_ids': [att['id']]},
headers={'Idempotency-Key': with_key}, schema='Message')['json']
replay = c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 201, actor=alice,
body={'text': '', 'attachment_ids': [att['id']]},
headers={'Idempotency-Key': with_key}, schema='Message')['json']
ok(replay == first, 'attachment message replay differs')
c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 409, actor=alice,
body={'text': '', 'attachment_ids': [second['id']]},
headers={'Idempotency-Key': with_key})
print('PASS attachments and message links')
def main():
args = arguments('Lab4 own black-box suite; creates synthetic data')
c = Client(args.base_url, args.ca_file)
test_health(c)
alice = register(c)
bob = register(c)
eve = register(c)
login(c, alice)
login(c, bob)
login(c, eve)
test_registration_and_login(c)
test_registration_validation(c)
test_chats(c, alice, bob, eve)
chat = new_chat(c, alice, 'Основной чат blackbox', [alice['id'], bob['id']])
test_messages(c, alice, bob, eve, chat)
test_attachments(c, alice, bob, eve, chat)
test_instances(c, alice)
test_idempotency(c, alice, bob, eve, chat)
test_idempotency_concurrency(c, alice, bob, chat)
test_pagination(c, alice, bob)
test_concurrent_registration(c)
test_concurrent_messages(c, alice, bob)
test_logout(c, alice)
print('PASS: lab4 student black-box suite, %d checks' % CHECKS)
if __name__ == '__main__':
try:
main()
except AssertionError as exc:
print('FAIL:', exc)
raise SystemExit(1)
Binary file not shown.

After

Width:  |  Height:  |  Size: 8.6 KiB

+22
View File
@@ -0,0 +1,22 @@
Copyright (c) 2016 Caleb Spare
MIT License
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+72
View File
@@ -0,0 +1,72 @@
# xxhash
[![Go Reference](https://pkg.go.dev/badge/github.com/cespare/xxhash/v2.svg)](https://pkg.go.dev/github.com/cespare/xxhash/v2)
[![Test](https://github.com/cespare/xxhash/actions/workflows/test.yml/badge.svg)](https://github.com/cespare/xxhash/actions/workflows/test.yml)
xxhash is a Go implementation of the 64-bit [xxHash] algorithm, XXH64. This is a
high-quality hashing algorithm that is much faster than anything in the Go
standard library.
This package provides a straightforward API:
```
func Sum64(b []byte) uint64
func Sum64String(s string) uint64
type Digest struct{ ... }
func New() *Digest
```
The `Digest` type implements hash.Hash64. Its key methods are:
```
func (*Digest) Write([]byte) (int, error)
func (*Digest) WriteString(string) (int, error)
func (*Digest) Sum64() uint64
```
The package is written with optimized pure Go and also contains even faster
assembly implementations for amd64 and arm64. If desired, the `purego` build tag
opts into using the Go code even on those architectures.
[xxHash]: http://cyan4973.github.io/xxHash/
## Compatibility
This package is in a module and the latest code is in version 2 of the module.
You need a version of Go with at least "minimal module compatibility" to use
github.com/cespare/xxhash/v2:
* 1.9.7+ for Go 1.9
* 1.10.3+ for Go 1.10
* Go 1.11 or later
I recommend using the latest release of Go.
## Benchmarks
Here are some quick benchmarks comparing the pure-Go and assembly
implementations of Sum64.
| input size | purego | asm |
| ---------- | --------- | --------- |
| 4 B | 1.3 GB/s | 1.2 GB/s |
| 16 B | 2.9 GB/s | 3.5 GB/s |
| 100 B | 6.9 GB/s | 8.1 GB/s |
| 4 KB | 11.7 GB/s | 16.7 GB/s |
| 10 MB | 12.0 GB/s | 17.3 GB/s |
These numbers were generated on Ubuntu 20.04 with an Intel Xeon Platinum 8252C
CPU using the following commands under Go 1.19.2:
```
benchstat <(go test -tags purego -benchtime 500ms -count 15 -bench 'Sum64$')
benchstat <(go test -benchtime 500ms -count 15 -bench 'Sum64$')
```
## Projects using this package
- [InfluxDB](https://github.com/influxdata/influxdb)
- [Prometheus](https://github.com/prometheus/prometheus)
- [VictoriaMetrics](https://github.com/VictoriaMetrics/VictoriaMetrics)
- [FreeCache](https://github.com/coocood/freecache)
- [FastCache](https://github.com/VictoriaMetrics/fastcache)
+10
View File
@@ -0,0 +1,10 @@
#!/bin/bash
set -eu -o pipefail
# Small convenience script for running the tests with various combinations of
# arch/tags. This assumes we're running on amd64 and have qemu available.
go test ./...
go test -tags purego ./...
GOARCH=arm64 go test
GOARCH=arm64 go test -tags purego
+228
View File
@@ -0,0 +1,228 @@
// Package xxhash implements the 64-bit variant of xxHash (XXH64) as described
// at http://cyan4973.github.io/xxHash/.
package xxhash
import (
"encoding/binary"
"errors"
"math/bits"
)
const (
prime1 uint64 = 11400714785074694791
prime2 uint64 = 14029467366897019727
prime3 uint64 = 1609587929392839161
prime4 uint64 = 9650029242287828579
prime5 uint64 = 2870177450012600261
)
// Store the primes in an array as well.
//
// The consts are used when possible in Go code to avoid MOVs but we need a
// contiguous array of the assembly code.
var primes = [...]uint64{prime1, prime2, prime3, prime4, prime5}
// Digest implements hash.Hash64.
type Digest struct {
v1 uint64
v2 uint64
v3 uint64
v4 uint64
total uint64
mem [32]byte
n int // how much of mem is used
}
// New creates a new Digest that computes the 64-bit xxHash algorithm.
func New() *Digest {
var d Digest
d.Reset()
return &d
}
// Reset clears the Digest's state so that it can be reused.
func (d *Digest) Reset() {
d.v1 = primes[0] + prime2
d.v2 = prime2
d.v3 = 0
d.v4 = -primes[0]
d.total = 0
d.n = 0
}
// Size always returns 8 bytes.
func (d *Digest) Size() int { return 8 }
// BlockSize always returns 32 bytes.
func (d *Digest) BlockSize() int { return 32 }
// Write adds more data to d. It always returns len(b), nil.
func (d *Digest) Write(b []byte) (n int, err error) {
n = len(b)
d.total += uint64(n)
memleft := d.mem[d.n&(len(d.mem)-1):]
if d.n+n < 32 {
// This new data doesn't even fill the current block.
copy(memleft, b)
d.n += n
return
}
if d.n > 0 {
// Finish off the partial block.
c := copy(memleft, b)
d.v1 = round(d.v1, u64(d.mem[0:8]))
d.v2 = round(d.v2, u64(d.mem[8:16]))
d.v3 = round(d.v3, u64(d.mem[16:24]))
d.v4 = round(d.v4, u64(d.mem[24:32]))
b = b[c:]
d.n = 0
}
if len(b) >= 32 {
// One or more full blocks left.
nw := writeBlocks(d, b)
b = b[nw:]
}
// Store any remaining partial block.
copy(d.mem[:], b)
d.n = len(b)
return
}
// Sum appends the current hash to b and returns the resulting slice.
func (d *Digest) Sum(b []byte) []byte {
s := d.Sum64()
return append(
b,
byte(s>>56),
byte(s>>48),
byte(s>>40),
byte(s>>32),
byte(s>>24),
byte(s>>16),
byte(s>>8),
byte(s),
)
}
// Sum64 returns the current hash.
func (d *Digest) Sum64() uint64 {
var h uint64
if d.total >= 32 {
v1, v2, v3, v4 := d.v1, d.v2, d.v3, d.v4
h = rol1(v1) + rol7(v2) + rol12(v3) + rol18(v4)
h = mergeRound(h, v1)
h = mergeRound(h, v2)
h = mergeRound(h, v3)
h = mergeRound(h, v4)
} else {
h = d.v3 + prime5
}
h += d.total
b := d.mem[:d.n&(len(d.mem)-1)]
for ; len(b) >= 8; b = b[8:] {
k1 := round(0, u64(b[:8]))
h ^= k1
h = rol27(h)*prime1 + prime4
}
if len(b) >= 4 {
h ^= uint64(u32(b[:4])) * prime1
h = rol23(h)*prime2 + prime3
b = b[4:]
}
for ; len(b) > 0; b = b[1:] {
h ^= uint64(b[0]) * prime5
h = rol11(h) * prime1
}
h ^= h >> 33
h *= prime2
h ^= h >> 29
h *= prime3
h ^= h >> 32
return h
}
const (
magic = "xxh\x06"
marshaledSize = len(magic) + 8*5 + 32
)
// MarshalBinary implements the encoding.BinaryMarshaler interface.
func (d *Digest) MarshalBinary() ([]byte, error) {
b := make([]byte, 0, marshaledSize)
b = append(b, magic...)
b = appendUint64(b, d.v1)
b = appendUint64(b, d.v2)
b = appendUint64(b, d.v3)
b = appendUint64(b, d.v4)
b = appendUint64(b, d.total)
b = append(b, d.mem[:d.n]...)
b = b[:len(b)+len(d.mem)-d.n]
return b, nil
}
// UnmarshalBinary implements the encoding.BinaryUnmarshaler interface.
func (d *Digest) UnmarshalBinary(b []byte) error {
if len(b) < len(magic) || string(b[:len(magic)]) != magic {
return errors.New("xxhash: invalid hash state identifier")
}
if len(b) != marshaledSize {
return errors.New("xxhash: invalid hash state size")
}
b = b[len(magic):]
b, d.v1 = consumeUint64(b)
b, d.v2 = consumeUint64(b)
b, d.v3 = consumeUint64(b)
b, d.v4 = consumeUint64(b)
b, d.total = consumeUint64(b)
copy(d.mem[:], b)
d.n = int(d.total % uint64(len(d.mem)))
return nil
}
func appendUint64(b []byte, x uint64) []byte {
var a [8]byte
binary.LittleEndian.PutUint64(a[:], x)
return append(b, a[:]...)
}
func consumeUint64(b []byte) ([]byte, uint64) {
x := u64(b)
return b[8:], x
}
func u64(b []byte) uint64 { return binary.LittleEndian.Uint64(b) }
func u32(b []byte) uint32 { return binary.LittleEndian.Uint32(b) }
func round(acc, input uint64) uint64 {
acc += input * prime2
acc = rol31(acc)
acc *= prime1
return acc
}
func mergeRound(acc, val uint64) uint64 {
val = round(0, val)
acc ^= val
acc = acc*prime1 + prime4
return acc
}
func rol1(x uint64) uint64 { return bits.RotateLeft64(x, 1) }
func rol7(x uint64) uint64 { return bits.RotateLeft64(x, 7) }
func rol11(x uint64) uint64 { return bits.RotateLeft64(x, 11) }
func rol12(x uint64) uint64 { return bits.RotateLeft64(x, 12) }
func rol18(x uint64) uint64 { return bits.RotateLeft64(x, 18) }
func rol23(x uint64) uint64 { return bits.RotateLeft64(x, 23) }
func rol27(x uint64) uint64 { return bits.RotateLeft64(x, 27) }
func rol31(x uint64) uint64 { return bits.RotateLeft64(x, 31) }
+209
View File
@@ -0,0 +1,209 @@
//go:build !appengine && gc && !purego
// +build !appengine
// +build gc
// +build !purego
#include "textflag.h"
// Registers:
#define h AX
#define d AX
#define p SI // pointer to advance through b
#define n DX
#define end BX // loop end
#define v1 R8
#define v2 R9
#define v3 R10
#define v4 R11
#define x R12
#define prime1 R13
#define prime2 R14
#define prime4 DI
#define round(acc, x) \
IMULQ prime2, x \
ADDQ x, acc \
ROLQ $31, acc \
IMULQ prime1, acc
// round0 performs the operation x = round(0, x).
#define round0(x) \
IMULQ prime2, x \
ROLQ $31, x \
IMULQ prime1, x
// mergeRound applies a merge round on the two registers acc and x.
// It assumes that prime1, prime2, and prime4 have been loaded.
#define mergeRound(acc, x) \
round0(x) \
XORQ x, acc \
IMULQ prime1, acc \
ADDQ prime4, acc
// blockLoop processes as many 32-byte blocks as possible,
// updating v1, v2, v3, and v4. It assumes that there is at least one block
// to process.
#define blockLoop() \
loop: \
MOVQ +0(p), x \
round(v1, x) \
MOVQ +8(p), x \
round(v2, x) \
MOVQ +16(p), x \
round(v3, x) \
MOVQ +24(p), x \
round(v4, x) \
ADDQ $32, p \
CMPQ p, end \
JLE loop
// func Sum64(b []byte) uint64
TEXT ·Sum64(SB), NOSPLIT|NOFRAME, $0-32
// Load fixed primes.
MOVQ ·primes+0(SB), prime1
MOVQ ·primes+8(SB), prime2
MOVQ ·primes+24(SB), prime4
// Load slice.
MOVQ b_base+0(FP), p
MOVQ b_len+8(FP), n
LEAQ (p)(n*1), end
// The first loop limit will be len(b)-32.
SUBQ $32, end
// Check whether we have at least one block.
CMPQ n, $32
JLT noBlocks
// Set up initial state (v1, v2, v3, v4).
MOVQ prime1, v1
ADDQ prime2, v1
MOVQ prime2, v2
XORQ v3, v3
XORQ v4, v4
SUBQ prime1, v4
blockLoop()
MOVQ v1, h
ROLQ $1, h
MOVQ v2, x
ROLQ $7, x
ADDQ x, h
MOVQ v3, x
ROLQ $12, x
ADDQ x, h
MOVQ v4, x
ROLQ $18, x
ADDQ x, h
mergeRound(h, v1)
mergeRound(h, v2)
mergeRound(h, v3)
mergeRound(h, v4)
JMP afterBlocks
noBlocks:
MOVQ ·primes+32(SB), h
afterBlocks:
ADDQ n, h
ADDQ $24, end
CMPQ p, end
JG try4
loop8:
MOVQ (p), x
ADDQ $8, p
round0(x)
XORQ x, h
ROLQ $27, h
IMULQ prime1, h
ADDQ prime4, h
CMPQ p, end
JLE loop8
try4:
ADDQ $4, end
CMPQ p, end
JG try1
MOVL (p), x
ADDQ $4, p
IMULQ prime1, x
XORQ x, h
ROLQ $23, h
IMULQ prime2, h
ADDQ ·primes+16(SB), h
try1:
ADDQ $4, end
CMPQ p, end
JGE finalize
loop1:
MOVBQZX (p), x
ADDQ $1, p
IMULQ ·primes+32(SB), x
XORQ x, h
ROLQ $11, h
IMULQ prime1, h
CMPQ p, end
JL loop1
finalize:
MOVQ h, x
SHRQ $33, x
XORQ x, h
IMULQ prime2, h
MOVQ h, x
SHRQ $29, x
XORQ x, h
IMULQ ·primes+16(SB), h
MOVQ h, x
SHRQ $32, x
XORQ x, h
MOVQ h, ret+24(FP)
RET
// func writeBlocks(d *Digest, b []byte) int
TEXT ·writeBlocks(SB), NOSPLIT|NOFRAME, $0-40
// Load fixed primes needed for round.
MOVQ ·primes+0(SB), prime1
MOVQ ·primes+8(SB), prime2
// Load slice.
MOVQ b_base+8(FP), p
MOVQ b_len+16(FP), n
LEAQ (p)(n*1), end
SUBQ $32, end
// Load vN from d.
MOVQ s+0(FP), d
MOVQ 0(d), v1
MOVQ 8(d), v2
MOVQ 16(d), v3
MOVQ 24(d), v4
// We don't need to check the loop condition here; this function is
// always called with at least one block of data to process.
blockLoop()
// Copy vN back to d.
MOVQ v1, 0(d)
MOVQ v2, 8(d)
MOVQ v3, 16(d)
MOVQ v4, 24(d)
// The number of bytes written is p minus the old base pointer.
SUBQ b_base+8(FP), p
MOVQ p, ret+32(FP)
RET
+183
View File
@@ -0,0 +1,183 @@
//go:build !appengine && gc && !purego
// +build !appengine
// +build gc
// +build !purego
#include "textflag.h"
// Registers:
#define digest R1
#define h R2 // return value
#define p R3 // input pointer
#define n R4 // input length
#define nblocks R5 // n / 32
#define prime1 R7
#define prime2 R8
#define prime3 R9
#define prime4 R10
#define prime5 R11
#define v1 R12
#define v2 R13
#define v3 R14
#define v4 R15
#define x1 R20
#define x2 R21
#define x3 R22
#define x4 R23
#define round(acc, x) \
MADD prime2, acc, x, acc \
ROR $64-31, acc \
MUL prime1, acc
// round0 performs the operation x = round(0, x).
#define round0(x) \
MUL prime2, x \
ROR $64-31, x \
MUL prime1, x
#define mergeRound(acc, x) \
round0(x) \
EOR x, acc \
MADD acc, prime4, prime1, acc
// blockLoop processes as many 32-byte blocks as possible,
// updating v1, v2, v3, and v4. It assumes that n >= 32.
#define blockLoop() \
LSR $5, n, nblocks \
PCALIGN $16 \
loop: \
LDP.P 16(p), (x1, x2) \
LDP.P 16(p), (x3, x4) \
round(v1, x1) \
round(v2, x2) \
round(v3, x3) \
round(v4, x4) \
SUB $1, nblocks \
CBNZ nblocks, loop
// func Sum64(b []byte) uint64
TEXT ·Sum64(SB), NOSPLIT|NOFRAME, $0-32
LDP b_base+0(FP), (p, n)
LDP ·primes+0(SB), (prime1, prime2)
LDP ·primes+16(SB), (prime3, prime4)
MOVD ·primes+32(SB), prime5
CMP $32, n
CSEL LT, prime5, ZR, h // if n < 32 { h = prime5 } else { h = 0 }
BLT afterLoop
ADD prime1, prime2, v1
MOVD prime2, v2
MOVD $0, v3
NEG prime1, v4
blockLoop()
ROR $64-1, v1, x1
ROR $64-7, v2, x2
ADD x1, x2
ROR $64-12, v3, x3
ROR $64-18, v4, x4
ADD x3, x4
ADD x2, x4, h
mergeRound(h, v1)
mergeRound(h, v2)
mergeRound(h, v3)
mergeRound(h, v4)
afterLoop:
ADD n, h
TBZ $4, n, try8
LDP.P 16(p), (x1, x2)
round0(x1)
// NOTE: here and below, sequencing the EOR after the ROR (using a
// rotated register) is worth a small but measurable speedup for small
// inputs.
ROR $64-27, h
EOR x1 @> 64-27, h, h
MADD h, prime4, prime1, h
round0(x2)
ROR $64-27, h
EOR x2 @> 64-27, h, h
MADD h, prime4, prime1, h
try8:
TBZ $3, n, try4
MOVD.P 8(p), x1
round0(x1)
ROR $64-27, h
EOR x1 @> 64-27, h, h
MADD h, prime4, prime1, h
try4:
TBZ $2, n, try2
MOVWU.P 4(p), x2
MUL prime1, x2
ROR $64-23, h
EOR x2 @> 64-23, h, h
MADD h, prime3, prime2, h
try2:
TBZ $1, n, try1
MOVHU.P 2(p), x3
AND $255, x3, x1
LSR $8, x3, x2
MUL prime5, x1
ROR $64-11, h
EOR x1 @> 64-11, h, h
MUL prime1, h
MUL prime5, x2
ROR $64-11, h
EOR x2 @> 64-11, h, h
MUL prime1, h
try1:
TBZ $0, n, finalize
MOVBU (p), x4
MUL prime5, x4
ROR $64-11, h
EOR x4 @> 64-11, h, h
MUL prime1, h
finalize:
EOR h >> 33, h
MUL prime2, h
EOR h >> 29, h
MUL prime3, h
EOR h >> 32, h
MOVD h, ret+24(FP)
RET
// func writeBlocks(d *Digest, b []byte) int
TEXT ·writeBlocks(SB), NOSPLIT|NOFRAME, $0-40
LDP ·primes+0(SB), (prime1, prime2)
// Load state. Assume v[1-4] are stored contiguously.
MOVD d+0(FP), digest
LDP 0(digest), (v1, v2)
LDP 16(digest), (v3, v4)
LDP b_base+8(FP), (p, n)
blockLoop()
// Store updated state.
STP (v1, v2), 0(digest)
STP (v3, v4), 16(digest)
BIC $31, n
MOVD n, ret+32(FP)
RET
+15
View File
@@ -0,0 +1,15 @@
//go:build (amd64 || arm64) && !appengine && gc && !purego
// +build amd64 arm64
// +build !appengine
// +build gc
// +build !purego
package xxhash
// Sum64 computes the 64-bit xxHash digest of b.
//
//go:noescape
func Sum64(b []byte) uint64
//go:noescape
func writeBlocks(d *Digest, b []byte) int
+76
View File
@@ -0,0 +1,76 @@
//go:build (!amd64 && !arm64) || appengine || !gc || purego
// +build !amd64,!arm64 appengine !gc purego
package xxhash
// Sum64 computes the 64-bit xxHash digest of b.
func Sum64(b []byte) uint64 {
// A simpler version would be
// d := New()
// d.Write(b)
// return d.Sum64()
// but this is faster, particularly for small inputs.
n := len(b)
var h uint64
if n >= 32 {
v1 := primes[0] + prime2
v2 := prime2
v3 := uint64(0)
v4 := -primes[0]
for len(b) >= 32 {
v1 = round(v1, u64(b[0:8:len(b)]))
v2 = round(v2, u64(b[8:16:len(b)]))
v3 = round(v3, u64(b[16:24:len(b)]))
v4 = round(v4, u64(b[24:32:len(b)]))
b = b[32:len(b):len(b)]
}
h = rol1(v1) + rol7(v2) + rol12(v3) + rol18(v4)
h = mergeRound(h, v1)
h = mergeRound(h, v2)
h = mergeRound(h, v3)
h = mergeRound(h, v4)
} else {
h = prime5
}
h += uint64(n)
for ; len(b) >= 8; b = b[8:] {
k1 := round(0, u64(b[:8]))
h ^= k1
h = rol27(h)*prime1 + prime4
}
if len(b) >= 4 {
h ^= uint64(u32(b[:4])) * prime1
h = rol23(h)*prime2 + prime3
b = b[4:]
}
for ; len(b) > 0; b = b[1:] {
h ^= uint64(b[0]) * prime5
h = rol11(h) * prime1
}
h ^= h >> 33
h *= prime2
h ^= h >> 29
h *= prime3
h ^= h >> 32
return h
}
func writeBlocks(d *Digest, b []byte) int {
v1, v2, v3, v4 := d.v1, d.v2, d.v3, d.v4
n := len(b)
for len(b) >= 32 {
v1 = round(v1, u64(b[0:8:len(b)]))
v2 = round(v2, u64(b[8:16:len(b)]))
v3 = round(v3, u64(b[16:24:len(b)]))
v4 = round(v4, u64(b[24:32:len(b)]))
b = b[32:len(b):len(b)]
}
d.v1, d.v2, d.v3, d.v4 = v1, v2, v3, v4
return n - len(b)
}
+16
View File
@@ -0,0 +1,16 @@
//go:build appengine
// +build appengine
// This file contains the safe implementations of otherwise unsafe-using code.
package xxhash
// Sum64String computes the 64-bit xxHash digest of s.
func Sum64String(s string) uint64 {
return Sum64([]byte(s))
}
// WriteString adds more data to d. It always returns len(s), nil.
func (d *Digest) WriteString(s string) (n int, err error) {
return d.Write([]byte(s))
}
+58
View File
@@ -0,0 +1,58 @@
//go:build !appengine
// +build !appengine
// This file encapsulates usage of unsafe.
// xxhash_safe.go contains the safe implementations.
package xxhash
import (
"unsafe"
)
// In the future it's possible that compiler optimizations will make these
// XxxString functions unnecessary by realizing that calls such as
// Sum64([]byte(s)) don't need to copy s. See https://go.dev/issue/2205.
// If that happens, even if we keep these functions they can be replaced with
// the trivial safe code.
// NOTE: The usual way of doing an unsafe string-to-[]byte conversion is:
//
// var b []byte
// bh := (*reflect.SliceHeader)(unsafe.Pointer(&b))
// bh.Data = (*reflect.StringHeader)(unsafe.Pointer(&s)).Data
// bh.Len = len(s)
// bh.Cap = len(s)
//
// Unfortunately, as of Go 1.15.3 the inliner's cost model assigns a high enough
// weight to this sequence of expressions that any function that uses it will
// not be inlined. Instead, the functions below use a different unsafe
// conversion designed to minimize the inliner weight and allow both to be
// inlined. There is also a test (TestInlining) which verifies that these are
// inlined.
//
// See https://github.com/golang/go/issues/42739 for discussion.
// Sum64String computes the 64-bit xxHash digest of s.
// It may be faster than Sum64([]byte(s)) by avoiding a copy.
func Sum64String(s string) uint64 {
b := *(*[]byte)(unsafe.Pointer(&sliceHeader{s, len(s)}))
return Sum64(b)
}
// WriteString adds more data to d. It always returns len(s), nil.
// It may be faster than Write([]byte(s)) by avoiding a copy.
func (d *Digest) WriteString(s string) (n int, err error) {
d.Write(*(*[]byte)(unsafe.Pointer(&sliceHeader{s, len(s)})))
// d.Write always returns len(s), nil.
// Ignoring the return output and returning these fixed values buys a
// savings of 6 in the inliner's cost model.
return len(s), nil
}
// sliceHeader is similar to reflect.SliceHeader, but it assumes that the layout
// of the first two words is the same as the layout of a string.
type sliceHeader struct {
s string
cap int
}
+21
View File
@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2017-2020 Damian Gryski <damian@gryski.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
+79
View File
@@ -0,0 +1,79 @@
package rendezvous
type Rendezvous struct {
nodes map[string]int
nstr []string
nhash []uint64
hash Hasher
}
type Hasher func(s string) uint64
func New(nodes []string, hash Hasher) *Rendezvous {
r := &Rendezvous{
nodes: make(map[string]int, len(nodes)),
nstr: make([]string, len(nodes)),
nhash: make([]uint64, len(nodes)),
hash: hash,
}
for i, n := range nodes {
r.nodes[n] = i
r.nstr[i] = n
r.nhash[i] = hash(n)
}
return r
}
func (r *Rendezvous) Lookup(k string) string {
// short-circuit if we're empty
if len(r.nodes) == 0 {
return ""
}
khash := r.hash(k)
var midx int
var mhash = xorshiftMult64(khash ^ r.nhash[0])
for i, nhash := range r.nhash[1:] {
if h := xorshiftMult64(khash ^ nhash); h > mhash {
midx = i + 1
mhash = h
}
}
return r.nstr[midx]
}
func (r *Rendezvous) Add(node string) {
r.nodes[node] = len(r.nstr)
r.nstr = append(r.nstr, node)
r.nhash = append(r.nhash, r.hash(node))
}
func (r *Rendezvous) Remove(node string) {
// find index of node to remove
nidx := r.nodes[node]
// remove from the slices
l := len(r.nstr)
r.nstr[nidx] = r.nstr[l]
r.nstr = r.nstr[:l]
r.nhash[nidx] = r.nhash[l]
r.nhash = r.nhash[:l]
// update the map
delete(r.nodes, node)
moved := r.nstr[nidx]
r.nodes[moved] = nidx
}
func xorshiftMult64(x uint64) uint64 {
x ^= x >> 12 // a
x ^= x << 25 // b
x ^= x >> 27 // c
return x * 2685821657736338717
}
+21
View File
@@ -0,0 +1,21 @@
sudo: false
language: go
go_import_path: github.com/dustin/go-humanize
go:
- 1.13.x
- 1.14.x
- 1.15.x
- 1.16.x
- stable
- master
matrix:
allow_failures:
- go: master
fast_finish: true
install:
- # Do nothing. This is needed to prevent default install action "go get -t -v ./..." from happening here (we want it to happen inside script step).
script:
- diff -u <(echo -n) <(gofmt -d -s .)
- go vet .
- go install -v -race ./...
- go test -v -race ./...
+21
View File
@@ -0,0 +1,21 @@
Copyright (c) 2005-2008 Dustin Sallings <dustin@spy.net>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
<http://www.opensource.org/licenses/mit-license.php>
+124
View File
@@ -0,0 +1,124 @@
# Humane Units [![Build Status](https://travis-ci.org/dustin/go-humanize.svg?branch=master)](https://travis-ci.org/dustin/go-humanize) [![GoDoc](https://godoc.org/github.com/dustin/go-humanize?status.svg)](https://godoc.org/github.com/dustin/go-humanize)
Just a few functions for helping humanize times and sizes.
`go get` it as `github.com/dustin/go-humanize`, import it as
`"github.com/dustin/go-humanize"`, use it as `humanize`.
See [godoc](https://pkg.go.dev/github.com/dustin/go-humanize) for
complete documentation.
## Sizes
This lets you take numbers like `82854982` and convert them to useful
strings like, `83 MB` or `79 MiB` (whichever you prefer).
Example:
```go
fmt.Printf("That file is %s.", humanize.Bytes(82854982)) // That file is 83 MB.
```
## Times
This lets you take a `time.Time` and spit it out in relative terms.
For example, `12 seconds ago` or `3 days from now`.
Example:
```go
fmt.Printf("This was touched %s.", humanize.Time(someTimeInstance)) // This was touched 7 hours ago.
```
Thanks to Kyle Lemons for the time implementation from an IRC
conversation one day. It's pretty neat.
## Ordinals
From a [mailing list discussion][odisc] where a user wanted to be able
to label ordinals.
0 -> 0th
1 -> 1st
2 -> 2nd
3 -> 3rd
4 -> 4th
[...]
Example:
```go
fmt.Printf("You're my %s best friend.", humanize.Ordinal(193)) // You are my 193rd best friend.
```
## Commas
Want to shove commas into numbers? Be my guest.
0 -> 0
100 -> 100
1000 -> 1,000
1000000000 -> 1,000,000,000
-100000 -> -100,000
Example:
```go
fmt.Printf("You owe $%s.\n", humanize.Comma(6582491)) // You owe $6,582,491.
```
## Ftoa
Nicer float64 formatter that removes trailing zeros.
```go
fmt.Printf("%f", 2.24) // 2.240000
fmt.Printf("%s", humanize.Ftoa(2.24)) // 2.24
fmt.Printf("%f", 2.0) // 2.000000
fmt.Printf("%s", humanize.Ftoa(2.0)) // 2
```
## SI notation
Format numbers with [SI notation][sinotation].
Example:
```go
humanize.SI(0.00000000223, "M") // 2.23 nM
```
## English-specific functions
The following functions are in the `humanize/english` subpackage.
### Plurals
Simple English pluralization
```go
english.PluralWord(1, "object", "") // object
english.PluralWord(42, "object", "") // objects
english.PluralWord(2, "bus", "") // buses
english.PluralWord(99, "locus", "loci") // loci
english.Plural(1, "object", "") // 1 object
english.Plural(42, "object", "") // 42 objects
english.Plural(2, "bus", "") // 2 buses
english.Plural(99, "locus", "loci") // 99 loci
```
### Word series
Format comma-separated words lists with conjuctions:
```go
english.WordSeries([]string{"foo"}, "and") // foo
english.WordSeries([]string{"foo", "bar"}, "and") // foo and bar
english.WordSeries([]string{"foo", "bar", "baz"}, "and") // foo, bar and baz
english.OxfordWordSeries([]string{"foo", "bar", "baz"}, "and") // foo, bar, and baz
```
[odisc]: https://groups.google.com/d/topic/golang-nuts/l8NhI74jl-4/discussion
[sinotation]: http://en.wikipedia.org/wiki/Metric_prefix
+31
View File
@@ -0,0 +1,31 @@
package humanize
import (
"math/big"
)
// order of magnitude (to a max order)
func oomm(n, b *big.Int, maxmag int) (float64, int) {
mag := 0
m := &big.Int{}
for n.Cmp(b) >= 0 {
n.DivMod(n, b, m)
mag++
if mag == maxmag && maxmag >= 0 {
break
}
}
return float64(n.Int64()) + (float64(m.Int64()) / float64(b.Int64())), mag
}
// total order of magnitude
// (same as above, but with no upper limit)
func oom(n, b *big.Int) (float64, int) {
mag := 0
m := &big.Int{}
for n.Cmp(b) >= 0 {
n.DivMod(n, b, m)
mag++
}
return float64(n.Int64()) + (float64(m.Int64()) / float64(b.Int64())), mag
}
+189
View File
@@ -0,0 +1,189 @@
package humanize
import (
"fmt"
"math/big"
"strings"
"unicode"
)
var (
bigIECExp = big.NewInt(1024)
// BigByte is one byte in bit.Ints
BigByte = big.NewInt(1)
// BigKiByte is 1,024 bytes in bit.Ints
BigKiByte = (&big.Int{}).Mul(BigByte, bigIECExp)
// BigMiByte is 1,024 k bytes in bit.Ints
BigMiByte = (&big.Int{}).Mul(BigKiByte, bigIECExp)
// BigGiByte is 1,024 m bytes in bit.Ints
BigGiByte = (&big.Int{}).Mul(BigMiByte, bigIECExp)
// BigTiByte is 1,024 g bytes in bit.Ints
BigTiByte = (&big.Int{}).Mul(BigGiByte, bigIECExp)
// BigPiByte is 1,024 t bytes in bit.Ints
BigPiByte = (&big.Int{}).Mul(BigTiByte, bigIECExp)
// BigEiByte is 1,024 p bytes in bit.Ints
BigEiByte = (&big.Int{}).Mul(BigPiByte, bigIECExp)
// BigZiByte is 1,024 e bytes in bit.Ints
BigZiByte = (&big.Int{}).Mul(BigEiByte, bigIECExp)
// BigYiByte is 1,024 z bytes in bit.Ints
BigYiByte = (&big.Int{}).Mul(BigZiByte, bigIECExp)
// BigRiByte is 1,024 y bytes in bit.Ints
BigRiByte = (&big.Int{}).Mul(BigYiByte, bigIECExp)
// BigQiByte is 1,024 r bytes in bit.Ints
BigQiByte = (&big.Int{}).Mul(BigRiByte, bigIECExp)
)
var (
bigSIExp = big.NewInt(1000)
// BigSIByte is one SI byte in big.Ints
BigSIByte = big.NewInt(1)
// BigKByte is 1,000 SI bytes in big.Ints
BigKByte = (&big.Int{}).Mul(BigSIByte, bigSIExp)
// BigMByte is 1,000 SI k bytes in big.Ints
BigMByte = (&big.Int{}).Mul(BigKByte, bigSIExp)
// BigGByte is 1,000 SI m bytes in big.Ints
BigGByte = (&big.Int{}).Mul(BigMByte, bigSIExp)
// BigTByte is 1,000 SI g bytes in big.Ints
BigTByte = (&big.Int{}).Mul(BigGByte, bigSIExp)
// BigPByte is 1,000 SI t bytes in big.Ints
BigPByte = (&big.Int{}).Mul(BigTByte, bigSIExp)
// BigEByte is 1,000 SI p bytes in big.Ints
BigEByte = (&big.Int{}).Mul(BigPByte, bigSIExp)
// BigZByte is 1,000 SI e bytes in big.Ints
BigZByte = (&big.Int{}).Mul(BigEByte, bigSIExp)
// BigYByte is 1,000 SI z bytes in big.Ints
BigYByte = (&big.Int{}).Mul(BigZByte, bigSIExp)
// BigRByte is 1,000 SI y bytes in big.Ints
BigRByte = (&big.Int{}).Mul(BigYByte, bigSIExp)
// BigQByte is 1,000 SI r bytes in big.Ints
BigQByte = (&big.Int{}).Mul(BigRByte, bigSIExp)
)
var bigBytesSizeTable = map[string]*big.Int{
"b": BigByte,
"kib": BigKiByte,
"kb": BigKByte,
"mib": BigMiByte,
"mb": BigMByte,
"gib": BigGiByte,
"gb": BigGByte,
"tib": BigTiByte,
"tb": BigTByte,
"pib": BigPiByte,
"pb": BigPByte,
"eib": BigEiByte,
"eb": BigEByte,
"zib": BigZiByte,
"zb": BigZByte,
"yib": BigYiByte,
"yb": BigYByte,
"rib": BigRiByte,
"rb": BigRByte,
"qib": BigQiByte,
"qb": BigQByte,
// Without suffix
"": BigByte,
"ki": BigKiByte,
"k": BigKByte,
"mi": BigMiByte,
"m": BigMByte,
"gi": BigGiByte,
"g": BigGByte,
"ti": BigTiByte,
"t": BigTByte,
"pi": BigPiByte,
"p": BigPByte,
"ei": BigEiByte,
"e": BigEByte,
"z": BigZByte,
"zi": BigZiByte,
"y": BigYByte,
"yi": BigYiByte,
"r": BigRByte,
"ri": BigRiByte,
"q": BigQByte,
"qi": BigQiByte,
}
var ten = big.NewInt(10)
func humanateBigBytes(s, base *big.Int, sizes []string) string {
if s.Cmp(ten) < 0 {
return fmt.Sprintf("%d B", s)
}
c := (&big.Int{}).Set(s)
val, mag := oomm(c, base, len(sizes)-1)
suffix := sizes[mag]
f := "%.0f %s"
if val < 10 {
f = "%.1f %s"
}
return fmt.Sprintf(f, val, suffix)
}
// BigBytes produces a human readable representation of an SI size.
//
// See also: ParseBigBytes.
//
// BigBytes(82854982) -> 83 MB
func BigBytes(s *big.Int) string {
sizes := []string{"B", "kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB", "RB", "QB"}
return humanateBigBytes(s, bigSIExp, sizes)
}
// BigIBytes produces a human readable representation of an IEC size.
//
// See also: ParseBigBytes.
//
// BigIBytes(82854982) -> 79 MiB
func BigIBytes(s *big.Int) string {
sizes := []string{"B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB", "RiB", "QiB"}
return humanateBigBytes(s, bigIECExp, sizes)
}
// ParseBigBytes parses a string representation of bytes into the number
// of bytes it represents.
//
// See also: BigBytes, BigIBytes.
//
// ParseBigBytes("42 MB") -> 42000000, nil
// ParseBigBytes("42 mib") -> 44040192, nil
func ParseBigBytes(s string) (*big.Int, error) {
lastDigit := 0
hasComma := false
for _, r := range s {
if !(unicode.IsDigit(r) || r == '.' || r == ',') {
break
}
if r == ',' {
hasComma = true
}
lastDigit++
}
num := s[:lastDigit]
if hasComma {
num = strings.Replace(num, ",", "", -1)
}
val := &big.Rat{}
_, err := fmt.Sscanf(num, "%f", val)
if err != nil {
return nil, err
}
extra := strings.ToLower(strings.TrimSpace(s[lastDigit:]))
if m, ok := bigBytesSizeTable[extra]; ok {
mv := (&big.Rat{}).SetInt(m)
val.Mul(val, mv)
rv := &big.Int{}
rv.Div(val.Num(), val.Denom())
return rv, nil
}
return nil, fmt.Errorf("unhandled size name: %v", extra)
}
+143
View File
@@ -0,0 +1,143 @@
package humanize
import (
"fmt"
"math"
"strconv"
"strings"
"unicode"
)
// IEC Sizes.
// kibis of bits
const (
Byte = 1 << (iota * 10)
KiByte
MiByte
GiByte
TiByte
PiByte
EiByte
)
// SI Sizes.
const (
IByte = 1
KByte = IByte * 1000
MByte = KByte * 1000
GByte = MByte * 1000
TByte = GByte * 1000
PByte = TByte * 1000
EByte = PByte * 1000
)
var bytesSizeTable = map[string]uint64{
"b": Byte,
"kib": KiByte,
"kb": KByte,
"mib": MiByte,
"mb": MByte,
"gib": GiByte,
"gb": GByte,
"tib": TiByte,
"tb": TByte,
"pib": PiByte,
"pb": PByte,
"eib": EiByte,
"eb": EByte,
// Without suffix
"": Byte,
"ki": KiByte,
"k": KByte,
"mi": MiByte,
"m": MByte,
"gi": GiByte,
"g": GByte,
"ti": TiByte,
"t": TByte,
"pi": PiByte,
"p": PByte,
"ei": EiByte,
"e": EByte,
}
func logn(n, b float64) float64 {
return math.Log(n) / math.Log(b)
}
func humanateBytes(s uint64, base float64, sizes []string) string {
if s < 10 {
return fmt.Sprintf("%d B", s)
}
e := math.Floor(logn(float64(s), base))
suffix := sizes[int(e)]
val := math.Floor(float64(s)/math.Pow(base, e)*10+0.5) / 10
f := "%.0f %s"
if val < 10 {
f = "%.1f %s"
}
return fmt.Sprintf(f, val, suffix)
}
// Bytes produces a human readable representation of an SI size.
//
// See also: ParseBytes.
//
// Bytes(82854982) -> 83 MB
func Bytes(s uint64) string {
sizes := []string{"B", "kB", "MB", "GB", "TB", "PB", "EB"}
return humanateBytes(s, 1000, sizes)
}
// IBytes produces a human readable representation of an IEC size.
//
// See also: ParseBytes.
//
// IBytes(82854982) -> 79 MiB
func IBytes(s uint64) string {
sizes := []string{"B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB"}
return humanateBytes(s, 1024, sizes)
}
// ParseBytes parses a string representation of bytes into the number
// of bytes it represents.
//
// See Also: Bytes, IBytes.
//
// ParseBytes("42 MB") -> 42000000, nil
// ParseBytes("42 mib") -> 44040192, nil
func ParseBytes(s string) (uint64, error) {
lastDigit := 0
hasComma := false
for _, r := range s {
if !(unicode.IsDigit(r) || r == '.' || r == ',') {
break
}
if r == ',' {
hasComma = true
}
lastDigit++
}
num := s[:lastDigit]
if hasComma {
num = strings.Replace(num, ",", "", -1)
}
f, err := strconv.ParseFloat(num, 64)
if err != nil {
return 0, err
}
extra := strings.ToLower(strings.TrimSpace(s[lastDigit:]))
if m, ok := bytesSizeTable[extra]; ok {
f *= float64(m)
if f >= math.MaxUint64 {
return 0, fmt.Errorf("too large: %v", s)
}
return uint64(f), nil
}
return 0, fmt.Errorf("unhandled size name: %v", extra)
}
+116
View File
@@ -0,0 +1,116 @@
package humanize
import (
"bytes"
"math"
"math/big"
"strconv"
"strings"
)
// Comma produces a string form of the given number in base 10 with
// commas after every three orders of magnitude.
//
// e.g. Comma(834142) -> 834,142
func Comma(v int64) string {
sign := ""
// Min int64 can't be negated to a usable value, so it has to be special cased.
if v == math.MinInt64 {
return "-9,223,372,036,854,775,808"
}
if v < 0 {
sign = "-"
v = 0 - v
}
parts := []string{"", "", "", "", "", "", ""}
j := len(parts) - 1
for v > 999 {
parts[j] = strconv.FormatInt(v%1000, 10)
switch len(parts[j]) {
case 2:
parts[j] = "0" + parts[j]
case 1:
parts[j] = "00" + parts[j]
}
v = v / 1000
j--
}
parts[j] = strconv.Itoa(int(v))
return sign + strings.Join(parts[j:], ",")
}
// Commaf produces a string form of the given number in base 10 with
// commas after every three orders of magnitude.
//
// e.g. Commaf(834142.32) -> 834,142.32
func Commaf(v float64) string {
buf := &bytes.Buffer{}
if v < 0 {
buf.Write([]byte{'-'})
v = 0 - v
}
comma := []byte{','}
parts := strings.Split(strconv.FormatFloat(v, 'f', -1, 64), ".")
pos := 0
if len(parts[0])%3 != 0 {
pos += len(parts[0]) % 3
buf.WriteString(parts[0][:pos])
buf.Write(comma)
}
for ; pos < len(parts[0]); pos += 3 {
buf.WriteString(parts[0][pos : pos+3])
buf.Write(comma)
}
buf.Truncate(buf.Len() - 1)
if len(parts) > 1 {
buf.Write([]byte{'.'})
buf.WriteString(parts[1])
}
return buf.String()
}
// CommafWithDigits works like the Commaf but limits the resulting
// string to the given number of decimal places.
//
// e.g. CommafWithDigits(834142.32, 1) -> 834,142.3
func CommafWithDigits(f float64, decimals int) string {
return stripTrailingDigits(Commaf(f), decimals)
}
// BigComma produces a string form of the given big.Int in base 10
// with commas after every three orders of magnitude.
func BigComma(b *big.Int) string {
sign := ""
if b.Sign() < 0 {
sign = "-"
b.Abs(b)
}
athousand := big.NewInt(1000)
c := (&big.Int{}).Set(b)
_, m := oom(c, athousand)
parts := make([]string, m+1)
j := len(parts) - 1
mod := &big.Int{}
for b.Cmp(athousand) >= 0 {
b.DivMod(b, athousand, mod)
parts[j] = strconv.FormatInt(mod.Int64(), 10)
switch len(parts[j]) {
case 2:
parts[j] = "0" + parts[j]
case 1:
parts[j] = "00" + parts[j]
}
j--
}
parts[j] = strconv.Itoa(int(b.Int64()))
return sign + strings.Join(parts[j:], ",")
}
+41
View File
@@ -0,0 +1,41 @@
//go:build go1.6
// +build go1.6
package humanize
import (
"bytes"
"math/big"
"strings"
)
// BigCommaf produces a string form of the given big.Float in base 10
// with commas after every three orders of magnitude.
func BigCommaf(v *big.Float) string {
buf := &bytes.Buffer{}
if v.Sign() < 0 {
buf.Write([]byte{'-'})
v.Abs(v)
}
comma := []byte{','}
parts := strings.Split(v.Text('f', -1), ".")
pos := 0
if len(parts[0])%3 != 0 {
pos += len(parts[0]) % 3
buf.WriteString(parts[0][:pos])
buf.Write(comma)
}
for ; pos < len(parts[0]); pos += 3 {
buf.WriteString(parts[0][pos : pos+3])
buf.Write(comma)
}
buf.Truncate(buf.Len() - 1)
if len(parts) > 1 {
buf.Write([]byte{'.'})
buf.WriteString(parts[1])
}
return buf.String()
}
+49
View File
@@ -0,0 +1,49 @@
package humanize
import (
"strconv"
"strings"
)
func stripTrailingZeros(s string) string {
if !strings.ContainsRune(s, '.') {
return s
}
offset := len(s) - 1
for offset > 0 {
if s[offset] == '.' {
offset--
break
}
if s[offset] != '0' {
break
}
offset--
}
return s[:offset+1]
}
func stripTrailingDigits(s string, digits int) string {
if i := strings.Index(s, "."); i >= 0 {
if digits <= 0 {
return s[:i]
}
i++
if i+digits >= len(s) {
return s
}
return s[:i+digits]
}
return s
}
// Ftoa converts a float to a string with no trailing zeros.
func Ftoa(num float64) string {
return stripTrailingZeros(strconv.FormatFloat(num, 'f', 6, 64))
}
// FtoaWithDigits converts a float to a string but limits the resulting string
// to the given number of decimal places, and no trailing zeros.
func FtoaWithDigits(num float64, digits int) string {
return stripTrailingZeros(stripTrailingDigits(strconv.FormatFloat(num, 'f', 6, 64), digits))
}
+8
View File
@@ -0,0 +1,8 @@
/*
Package humanize converts boring ugly numbers to human-friendly strings and back.
Durations can be turned into strings such as "3 days ago", numbers
representing sizes like 82854982 into useful strings like, "83 MB" or
"79 MiB" (whichever you prefer).
*/
package humanize
+192
View File
@@ -0,0 +1,192 @@
package humanize
/*
Slightly adapted from the source to fit go-humanize.
Author: https://github.com/gorhill
Source: https://gist.github.com/gorhill/5285193
*/
import (
"math"
"strconv"
)
var (
renderFloatPrecisionMultipliers = [...]float64{
1,
10,
100,
1000,
10000,
100000,
1000000,
10000000,
100000000,
1000000000,
}
renderFloatPrecisionRounders = [...]float64{
0.5,
0.05,
0.005,
0.0005,
0.00005,
0.000005,
0.0000005,
0.00000005,
0.000000005,
0.0000000005,
}
)
// FormatFloat produces a formatted number as string based on the following user-specified criteria:
// * thousands separator
// * decimal separator
// * decimal precision
//
// Usage: s := RenderFloat(format, n)
// The format parameter tells how to render the number n.
//
// See examples: http://play.golang.org/p/LXc1Ddm1lJ
//
// Examples of format strings, given n = 12345.6789:
// "#,###.##" => "12,345.67"
// "#,###." => "12,345"
// "#,###" => "12345,678"
// "#\u202F###,##" => "12 345,68"
// "#.###,###### => 12.345,678900
// "" (aka default format) => 12,345.67
//
// The highest precision allowed is 9 digits after the decimal symbol.
// There is also a version for integer number, FormatInteger(),
// which is convenient for calls within template.
func FormatFloat(format string, n float64) string {
// Special cases:
// NaN = "NaN"
// +Inf = "+Infinity"
// -Inf = "-Infinity"
if math.IsNaN(n) {
return "NaN"
}
if n > math.MaxFloat64 {
return "Infinity"
}
if n < (0.0 - math.MaxFloat64) {
return "-Infinity"
}
// default format
precision := 2
decimalStr := "."
thousandStr := ","
positiveStr := ""
negativeStr := "-"
if len(format) > 0 {
format := []rune(format)
// If there is an explicit format directive,
// then default values are these:
precision = 9
thousandStr = ""
// collect indices of meaningful formatting directives
formatIndx := []int{}
for i, char := range format {
if char != '#' && char != '0' {
formatIndx = append(formatIndx, i)
}
}
if len(formatIndx) > 0 {
// Directive at index 0:
// Must be a '+'
// Raise an error if not the case
// index: 0123456789
// +0.000,000
// +000,000.0
// +0000.00
// +0000
if formatIndx[0] == 0 {
if format[formatIndx[0]] != '+' {
panic("RenderFloat(): invalid positive sign directive")
}
positiveStr = "+"
formatIndx = formatIndx[1:]
}
// Two directives:
// First is thousands separator
// Raise an error if not followed by 3-digit
// 0123456789
// 0.000,000
// 000,000.00
if len(formatIndx) == 2 {
if (formatIndx[1] - formatIndx[0]) != 4 {
panic("RenderFloat(): thousands separator directive must be followed by 3 digit-specifiers")
}
thousandStr = string(format[formatIndx[0]])
formatIndx = formatIndx[1:]
}
// One directive:
// Directive is decimal separator
// The number of digit-specifier following the separator indicates wanted precision
// 0123456789
// 0.00
// 000,0000
if len(formatIndx) == 1 {
decimalStr = string(format[formatIndx[0]])
precision = len(format) - formatIndx[0] - 1
}
}
}
// generate sign part
var signStr string
if n >= 0.000000001 {
signStr = positiveStr
} else if n <= -0.000000001 {
signStr = negativeStr
n = -n
} else {
signStr = ""
n = 0.0
}
// split number into integer and fractional parts
intf, fracf := math.Modf(n + renderFloatPrecisionRounders[precision])
// generate integer part string
intStr := strconv.FormatInt(int64(intf), 10)
// add thousand separator if required
if len(thousandStr) > 0 {
for i := len(intStr); i > 3; {
i -= 3
intStr = intStr[:i] + thousandStr + intStr[i:]
}
}
// no fractional part, we can leave now
if precision == 0 {
return signStr + intStr
}
// generate fractional part
fracStr := strconv.Itoa(int(fracf * renderFloatPrecisionMultipliers[precision]))
// may need padding
if len(fracStr) < precision {
fracStr = "000000000000000"[:precision-len(fracStr)] + fracStr
}
return signStr + intStr + decimalStr + fracStr
}
// FormatInteger produces a formatted number as string.
// See FormatFloat.
func FormatInteger(format string, n int) string {
return FormatFloat(format, float64(n))
}
+25
View File
@@ -0,0 +1,25 @@
package humanize
import "strconv"
// Ordinal gives you the input number in a rank/ordinal format.
//
// Ordinal(3) -> 3rd
func Ordinal(x int) string {
suffix := "th"
switch x % 10 {
case 1:
if x%100 != 11 {
suffix = "st"
}
case 2:
if x%100 != 12 {
suffix = "nd"
}
case 3:
if x%100 != 13 {
suffix = "rd"
}
}
return strconv.Itoa(x) + suffix
}
+127
View File
@@ -0,0 +1,127 @@
package humanize
import (
"errors"
"math"
"regexp"
"strconv"
)
var siPrefixTable = map[float64]string{
-30: "q", // quecto
-27: "r", // ronto
-24: "y", // yocto
-21: "z", // zepto
-18: "a", // atto
-15: "f", // femto
-12: "p", // pico
-9: "n", // nano
-6: "µ", // micro
-3: "m", // milli
0: "",
3: "k", // kilo
6: "M", // mega
9: "G", // giga
12: "T", // tera
15: "P", // peta
18: "E", // exa
21: "Z", // zetta
24: "Y", // yotta
27: "R", // ronna
30: "Q", // quetta
}
var revSIPrefixTable = revfmap(siPrefixTable)
// revfmap reverses the map and precomputes the power multiplier
func revfmap(in map[float64]string) map[string]float64 {
rv := map[string]float64{}
for k, v := range in {
rv[v] = math.Pow(10, k)
}
return rv
}
var riParseRegex *regexp.Regexp
func init() {
ri := `^([\-0-9.]+)\s?([`
for _, v := range siPrefixTable {
ri += v
}
ri += `]?)(.*)`
riParseRegex = regexp.MustCompile(ri)
}
// ComputeSI finds the most appropriate SI prefix for the given number
// and returns the prefix along with the value adjusted to be within
// that prefix.
//
// See also: SI, ParseSI.
//
// e.g. ComputeSI(2.2345e-12) -> (2.2345, "p")
func ComputeSI(input float64) (float64, string) {
if input == 0 {
return 0, ""
}
mag := math.Abs(input)
exponent := math.Floor(logn(mag, 10))
exponent = math.Floor(exponent/3) * 3
value := mag / math.Pow(10, exponent)
// Handle special case where value is exactly 1000.0
// Should return 1 M instead of 1000 k
if value == 1000.0 {
exponent += 3
value = mag / math.Pow(10, exponent)
}
value = math.Copysign(value, input)
prefix := siPrefixTable[exponent]
return value, prefix
}
// SI returns a string with default formatting.
//
// SI uses Ftoa to format float value, removing trailing zeros.
//
// See also: ComputeSI, ParseSI.
//
// e.g. SI(1000000, "B") -> 1 MB
// e.g. SI(2.2345e-12, "F") -> 2.2345 pF
func SI(input float64, unit string) string {
value, prefix := ComputeSI(input)
return Ftoa(value) + " " + prefix + unit
}
// SIWithDigits works like SI but limits the resulting string to the
// given number of decimal places.
//
// e.g. SIWithDigits(1000000, 0, "B") -> 1 MB
// e.g. SIWithDigits(2.2345e-12, 2, "F") -> 2.23 pF
func SIWithDigits(input float64, decimals int, unit string) string {
value, prefix := ComputeSI(input)
return FtoaWithDigits(value, decimals) + " " + prefix + unit
}
var errInvalid = errors.New("invalid input")
// ParseSI parses an SI string back into the number and unit.
//
// See also: SI, ComputeSI.
//
// e.g. ParseSI("2.2345 pF") -> (2.2345e-12, "F", nil)
func ParseSI(input string) (float64, string, error) {
found := riParseRegex.FindStringSubmatch(input)
if len(found) != 4 {
return 0, "", errInvalid
}
mag := revSIPrefixTable[found[2]]
unit := found[3]
base, err := strconv.ParseFloat(found[1], 64)
return base * mag, unit, err
}
+117
View File
@@ -0,0 +1,117 @@
package humanize
import (
"fmt"
"math"
"sort"
"time"
)
// Seconds-based time units
const (
Day = 24 * time.Hour
Week = 7 * Day
Month = 30 * Day
Year = 12 * Month
LongTime = 37 * Year
)
// Time formats a time into a relative string.
//
// Time(someT) -> "3 weeks ago"
func Time(then time.Time) string {
return RelTime(then, time.Now(), "ago", "from now")
}
// A RelTimeMagnitude struct contains a relative time point at which
// the relative format of time will switch to a new format string. A
// slice of these in ascending order by their "D" field is passed to
// CustomRelTime to format durations.
//
// The Format field is a string that may contain a "%s" which will be
// replaced with the appropriate signed label (e.g. "ago" or "from
// now") and a "%d" that will be replaced by the quantity.
//
// The DivBy field is the amount of time the time difference must be
// divided by in order to display correctly.
//
// e.g. if D is 2*time.Minute and you want to display "%d minutes %s"
// DivBy should be time.Minute so whatever the duration is will be
// expressed in minutes.
type RelTimeMagnitude struct {
D time.Duration
Format string
DivBy time.Duration
}
var defaultMagnitudes = []RelTimeMagnitude{
{time.Second, "now", time.Second},
{2 * time.Second, "1 second %s", 1},
{time.Minute, "%d seconds %s", time.Second},
{2 * time.Minute, "1 minute %s", 1},
{time.Hour, "%d minutes %s", time.Minute},
{2 * time.Hour, "1 hour %s", 1},
{Day, "%d hours %s", time.Hour},
{2 * Day, "1 day %s", 1},
{Week, "%d days %s", Day},
{2 * Week, "1 week %s", 1},
{Month, "%d weeks %s", Week},
{2 * Month, "1 month %s", 1},
{Year, "%d months %s", Month},
{18 * Month, "1 year %s", 1},
{2 * Year, "2 years %s", 1},
{LongTime, "%d years %s", Year},
{math.MaxInt64, "a long while %s", 1},
}
// RelTime formats a time into a relative string.
//
// It takes two times and two labels. In addition to the generic time
// delta string (e.g. 5 minutes), the labels are used applied so that
// the label corresponding to the smaller time is applied.
//
// RelTime(timeInPast, timeInFuture, "earlier", "later") -> "3 weeks earlier"
func RelTime(a, b time.Time, albl, blbl string) string {
return CustomRelTime(a, b, albl, blbl, defaultMagnitudes)
}
// CustomRelTime formats a time into a relative string.
//
// It takes two times two labels and a table of relative time formats.
// In addition to the generic time delta string (e.g. 5 minutes), the
// labels are used applied so that the label corresponding to the
// smaller time is applied.
func CustomRelTime(a, b time.Time, albl, blbl string, magnitudes []RelTimeMagnitude) string {
lbl := albl
diff := b.Sub(a)
if a.After(b) {
lbl = blbl
diff = a.Sub(b)
}
n := sort.Search(len(magnitudes), func(i int) bool {
return magnitudes[i].D > diff
})
if n >= len(magnitudes) {
n = len(magnitudes) - 1
}
mag := magnitudes[n]
args := []interface{}{}
escaped := false
for _, ch := range mag.Format {
if escaped {
switch ch {
case 's':
args = append(args, lbl)
case 'd':
args = append(args, diff/mag.DivBy)
}
escaped = false
} else {
escaped = ch == '%'
}
}
return fmt.Sprintf(mag.Format, args...)
}
+12
View File
@@ -0,0 +1,12 @@
# http://editorconfig.org
root = true
[*]
charset = utf-8
end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true
[*_test.go]
trim_trailing_whitespace = false
+7
View File
@@ -0,0 +1,7 @@
testdata/conf_out.ini
ini.sublime-project
ini.sublime-workspace
testdata/conf_reflect.ini
.idea
/.vscode
.DS_Store
+27
View File
@@ -0,0 +1,27 @@
linters-settings:
staticcheck:
checks: [
"all",
"-SA1019" # There are valid use cases of strings.Title
]
nakedret:
max-func-lines: 0 # Disallow any unnamed return statement
linters:
enable:
- deadcode
- errcheck
- gosimple
- govet
- ineffassign
- staticcheck
- structcheck
- typecheck
- unused
- varcheck
- nakedret
- gofmt
- rowserrcheck
- unconvert
- goimports
- unparam
+191
View File
@@ -0,0 +1,191 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction, and
distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by the copyright
owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all other entities
that control, are controlled by, or are under common control with that entity.
For the purposes of this definition, "control" means (i) the power, direct or
indirect, to cause the direction or management of such entity, whether by
contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity exercising
permissions granted by this License.
"Source" form shall mean the preferred form for making modifications, including
but not limited to software source code, documentation source, and configuration
files.
"Object" form shall mean any form resulting from mechanical transformation or
translation of a Source form, including but not limited to compiled object code,
generated documentation, and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or Object form, made
available under the License, as indicated by a copyright notice that is included
in or attached to the work (an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object form, that
is based on (or derived from) the Work and for which the editorial revisions,
annotations, elaborations, or other modifications represent, as a whole, an
original work of authorship. For the purposes of this License, Derivative Works
shall not include works that remain separable from, or merely link (or bind by
name) to the interfaces of, the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including the original version
of the Work and any modifications or additions to that Work or Derivative Works
thereof, that is intentionally submitted to Licensor for inclusion in the Work
by the copyright owner or by an individual or Legal Entity authorized to submit
on behalf of the copyright owner. For the purposes of this definition,
"submitted" means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems, and
issue tracking systems that are managed by, or on behalf of, the Licensor for
the purpose of discussing and improving the Work, but excluding communication
that is conspicuously marked or otherwise designated in writing by the copyright
owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf
of whom a Contribution has been received by Licensor and subsequently
incorporated within the Work.
2. Grant of Copyright License.
Subject to the terms and conditions of this License, each Contributor hereby
grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free,
irrevocable copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the Work and such
Derivative Works in Source or Object form.
3. Grant of Patent License.
Subject to the terms and conditions of this License, each Contributor hereby
grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free,
irrevocable (except as stated in this section) patent license to make, have
made, use, offer to sell, sell, import, and otherwise transfer the Work, where
such license applies only to those patent claims licensable by such Contributor
that are necessarily infringed by their Contribution(s) alone or by combination
of their Contribution(s) with the Work to which such Contribution(s) was
submitted. If You institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work or a
Contribution incorporated within the Work constitutes direct or contributory
patent infringement, then any patent licenses granted to You under this License
for that Work shall terminate as of the date such litigation is filed.
4. Redistribution.
You may reproduce and distribute copies of the Work or Derivative Works thereof
in any medium, with or without modifications, and in Source or Object form,
provided that You meet the following conditions:
You must give any other recipients of the Work or Derivative Works a copy of
this License; and
You must cause any modified files to carry prominent notices stating that You
changed the files; and
You must retain, in the Source form of any Derivative Works that You distribute,
all copyright, patent, trademark, and attribution notices from the Source form
of the Work, excluding those notices that do not pertain to any part of the
Derivative Works; and
If the Work includes a "NOTICE" text file as part of its distribution, then any
Derivative Works that You distribute must include a readable copy of the
attribution notices contained within such NOTICE file, excluding those notices
that do not pertain to any part of the Derivative Works, in at least one of the
following places: within a NOTICE text file distributed as part of the
Derivative Works; within the Source form or documentation, if provided along
with the Derivative Works; or, within a display generated by the Derivative
Works, if and wherever such third-party notices normally appear. The contents of
the NOTICE file are for informational purposes only and do not modify the
License. You may add Your own attribution notices within Derivative Works that
You distribute, alongside or as an addendum to the NOTICE text from the Work,
provided that such additional attribution notices cannot be construed as
modifying the License.
You may add Your own copyright statement to Your modifications and may provide
additional or different license terms and conditions for use, reproduction, or
distribution of Your modifications, or for any such Derivative Works as a whole,
provided Your use, reproduction, and distribution of the Work otherwise complies
with the conditions stated in this License.
5. Submission of Contributions.
Unless You explicitly state otherwise, any Contribution intentionally submitted
for inclusion in the Work by You to the Licensor shall be under the terms and
conditions of this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify the terms of
any separate license agreement you may have executed with Licensor regarding
such Contributions.
6. Trademarks.
This License does not grant permission to use the trade names, trademarks,
service marks, or product names of the Licensor, except as required for
reasonable and customary use in describing the origin of the Work and
reproducing the content of the NOTICE file.
7. Disclaimer of Warranty.
Unless required by applicable law or agreed to in writing, Licensor provides the
Work (and each Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied,
including, without limitation, any warranties or conditions of TITLE,
NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are
solely responsible for determining the appropriateness of using or
redistributing the Work and assume any risks associated with Your exercise of
permissions under this License.
8. Limitation of Liability.
In no event and under no legal theory, whether in tort (including negligence),
contract, or otherwise, unless required by applicable law (such as deliberate
and grossly negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special, incidental,
or consequential damages of any character arising as a result of this License or
out of the use or inability to use the Work (including but not limited to
damages for loss of goodwill, work stoppage, computer failure or malfunction, or
any and all other commercial damages or losses), even if such Contributor has
been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability.
While redistributing the Work or Derivative Works thereof, You may choose to
offer, and charge a fee for, acceptance of support, warranty, indemnity, or
other liability obligations and/or rights consistent with this License. However,
in accepting such obligations, You may act only on Your own behalf and on Your
sole responsibility, not on behalf of any other Contributor, and only if You
agree to indemnify, defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason of your
accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work
To apply the Apache License to your work, attach the following boilerplate
notice, with the fields enclosed by brackets "[]" replaced with your own
identifying information. (Don't include the brackets!) The text should be
enclosed in the appropriate comment syntax for the file format. We also
recommend that a file or class name and description of purpose be included on
the same "printed page" as the copyright notice for easier identification within
third-party archives.
Copyright 2014 Unknwon
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
+15
View File
@@ -0,0 +1,15 @@
.PHONY: build test bench vet coverage
build: vet bench
test:
go test -v -cover -race
bench:
go test -v -cover -test.bench=. -test.benchmem
vet:
go vet
coverage:
go test -coverprofile=c.out && go tool cover -html=c.out && rm c.out
+43
View File
@@ -0,0 +1,43 @@
# INI
[![GitHub Workflow Status](https://img.shields.io/github/checks-status/go-ini/ini/main?logo=github&style=for-the-badge)](https://github.com/go-ini/ini/actions?query=branch%3Amain)
[![codecov](https://img.shields.io/codecov/c/github/go-ini/ini/master?logo=codecov&style=for-the-badge)](https://codecov.io/gh/go-ini/ini)
[![GoDoc](https://img.shields.io/badge/GoDoc-Reference-blue?style=for-the-badge&logo=go)](https://pkg.go.dev/github.com/go-ini/ini?tab=doc)
[![Sourcegraph](https://img.shields.io/badge/view%20on-Sourcegraph-brightgreen.svg?style=for-the-badge&logo=sourcegraph)](https://sourcegraph.com/github.com/go-ini/ini)
![](https://avatars0.githubusercontent.com/u/10216035?v=3&s=200)
Package ini provides INI file read and write functionality in Go.
## Features
- Load from multiple data sources(file, `[]byte`, `io.Reader` and `io.ReadCloser`) with overwrites.
- Read with recursion values.
- Read with parent-child sections.
- Read with auto-increment key names.
- Read with multiple-line values.
- Read with tons of helper methods.
- Read and convert values to Go types.
- Read and **WRITE** comments of sections and keys.
- Manipulate sections, keys and comments with ease.
- Keep sections and keys in order as you parse and save.
## Installation
The minimum requirement of Go is **1.13**.
```sh
$ go get gopkg.in/ini.v1
```
Please add `-u` flag to update in the future.
## Getting Help
- [Getting Started](https://ini.unknwon.io/docs/intro/getting_started)
- [API Documentation](https://gowalker.org/gopkg.in/ini.v1)
- 中国大陆镜像:https://ini.unknwon.cn
## License
This project is under Apache v2 License. See the [LICENSE](LICENSE) file for the full license text.
+16
View File
@@ -0,0 +1,16 @@
coverage:
range: "60...95"
status:
project:
default:
threshold: 1%
informational: true
patch:
defualt:
only_pulls: true
informational: true
comment:
layout: 'diff'
github_checks: false
+76
View File
@@ -0,0 +1,76 @@
// Copyright 2019 Unknwon
//
// Licensed under the Apache License, Version 2.0 (the "License"): you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations
// under the License.
package ini
import (
"bytes"
"fmt"
"io"
"io/ioutil"
"os"
)
var (
_ dataSource = (*sourceFile)(nil)
_ dataSource = (*sourceData)(nil)
_ dataSource = (*sourceReadCloser)(nil)
)
// dataSource is an interface that returns object which can be read and closed.
type dataSource interface {
ReadCloser() (io.ReadCloser, error)
}
// sourceFile represents an object that contains content on the local file system.
type sourceFile struct {
name string
}
func (s sourceFile) ReadCloser() (_ io.ReadCloser, err error) {
return os.Open(s.name)
}
// sourceData represents an object that contains content in memory.
type sourceData struct {
data []byte
}
func (s *sourceData) ReadCloser() (io.ReadCloser, error) {
return ioutil.NopCloser(bytes.NewReader(s.data)), nil
}
// sourceReadCloser represents an input stream with Close method.
type sourceReadCloser struct {
reader io.ReadCloser
}
func (s *sourceReadCloser) ReadCloser() (io.ReadCloser, error) {
return s.reader, nil
}
func parseDataSource(source interface{}) (dataSource, error) {
switch s := source.(type) {
case string:
return sourceFile{s}, nil
case []byte:
return &sourceData{s}, nil
case io.ReadCloser:
return &sourceReadCloser{s}, nil
case io.Reader:
return &sourceReadCloser{ioutil.NopCloser(s)}, nil
default:
return nil, fmt.Errorf("error parsing data source: unknown type %q", s)
}
}

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