Lab3 baseline: HAProxy, replicated stateless API, shared PostgreSQL/Valkey, idempotent messages

This commit is contained in:
Ivan Melnikov
2026-12-02 18:22:57 +03:00
parent 0ab3a341aa
commit e9bf138053
474 changed files with 206416 additions and 16 deletions
+41 -11
View File
@@ -1,13 +1,43 @@
# Copy to .env for your LOCAL synthetic test environment; never commit .env.
# These are logical interface suggestions; map actual framework names in REPORT.md.
APP_HOST=0.0.0.0
APP_PORT=8080
# Copy to .env for this LOCAL synthetic teaching stand: `make env` generates
# random local credentials and never prints them. .env is ignored by Git.
# These are logical settings; compose.yaml maps them to the application.
APP_ENV=lab
SESSION_TTL_SECONDS=3600
# Choose credentials locally. File paths contain no secret values.
DATABASE_URL_FILE=/run/secrets/database_url
# Optional on 3, required use on 4 in lab2; Redis OR Valkey:
SESSION_STORE=postgres
CACHE_URL_FILE=/run/secrets/cache_url
LOG_LEVEL=info
APP_VERSION=1.0.0
# Local credentials. Never commit real values.
POSTGRES_USER=messenger
POSTGRES_DB=messenger
POSTGRES_PASSWORD=
VALKEY_PASSWORD=
# Public entrypoint: HAProxy on loopback only. API replicas have no host port.
LB_PORT=8083
# Replica count and per-replica limits. For track-1 runs the experiment script
# keeps the total constant: 1x0.8, 2x0.4, 4x0.2 CPU and 1x512M, 2x256M, 4x128M.
API_REPLICAS=2
IDEMPOTENCY_TTL_SECONDS=86400
API_CPU_LIMIT=0.4
API_MEM_LIMIT=256M
GOMEMLIMIT=220MiB
POSTGRES_CPU_LIMIT=0.6
POSTGRES_MEM_LIMIT=512M
VALKEY_CPU_LIMIT=0.15
VALKEY_MEM_LIMIT=128M
LB_CPU_LIMIT=0.1
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
# Build metadata, filled by make if not supplied.
GIT_REVISION=unknown
+60
View File
@@ -0,0 +1,60 @@
# syntax=docker/dockerfile:1
# Compile stage. Dependencies are vendored, so the build needs no module proxy
# and the same source tree produces the same binary 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
# 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-lab3" \
org.opencontainers.image.description="MTUSI highload lab 3: HAProxy, replicated API, shared PostgreSQL and Valkey" \
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
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"]
+80 -5
View File
@@ -1,13 +1,29 @@
PYTHON ?= python3
BASE_URL ?= http://localhost:8080
GO ?= go
BASE_URL ?= http://127.0.0.1:8083
CA_FILE ?=
ACTION_SCRIPT ?=
TLS_ARGS = $(if $(CA_FILE),--ca-file "$(CA_FILE)",)
COMPOSE ?= ./scripts/compose.sh
COMPOSE_ARGS = --env-file .env
IMAGE ?= mtusi-messenger-lab3-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-expiry test-failure test-container test-db track1 failover-each rolling
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 with random local credentials; 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 unit tests + black-box suite; test-student-race: Go race detector"
@echo "test-persistence: ACTION_SCRIPT=scripts/restart.sh; test-failover: ACTION_SCRIPT=scripts/stop-one.sh"
@echo "failover-each: stop every real API replica in turn and measure RPS/errors/recovery"
@echo "track1: level-5 track 1 (scaling price, saturation, one improvement)"
@echo "rolling: rolling replacement of API containers under load"
check:
$(PYTHON) scripts/check_contract.py
@@ -21,10 +37,69 @@ test:
load:
$(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-lab3-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 -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)
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)
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 ./...
failover-each:
$(PYTHON) scripts/failover-matrix.py --base-url "$(BASE_URL)" $(TLS_ARGS)
rolling:
./scripts/rolling-update.sh
test-failure:
$(PYTHON) scripts/failure-checks.py --base-url "$(BASE_URL)" $(TLS_ARGS)
test-container:
$(PYTHON) scripts/container-checks.py --base-url "$(BASE_URL)" $(TLS_ARGS) --image "$(IMAGE)"
test-db:
$(PYTHON) scripts/db-checks.py
track1:
$(PYTHON) scripts/track1.py --base-url "$(BASE_URL)" $(TLS_ARGS)
+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
}
+273
View File
@@ -0,0 +1,273 @@
// 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-lab3/internal/api"
"mtusi.ru/messenger-lab3/internal/config"
"mtusi.ru/messenger-lab3/internal/session"
"mtusi.ru/messenger-lab3/internal/store"
"mtusi.ru/messenger-lab3/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() }()
app, err := api.New(repository, sessions, logger, instanceID, version)
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()),
"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-lab3", "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-lab3/internal/config"
"mtusi.ru/messenger-lab3/internal/store"
)
var revision = "unknown"
func main() {
flag.Parse()
logger := slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{Level: slog.LevelInfo})).
With("service", "messenger-lab3-migrate", "revision", revision)
cfg, err := config.Load()
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")
}
+224
View File
@@ -0,0 +1,224 @@
# Lab3 local teaching stand: client -> HAProxy -> 2+ interchangeable API
# processes -> shared PostgreSQL and shared Valkey.
#
# 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. API ports are not published; the only public
# route is the load balancer on 127.0.0.1:8083.
#
# 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: mtusi-lab3-melnikov
x-api-build: &api-build
context: .
args:
VERSION: ${APP_VERSION:-1.0.0}
REVISION: ${GIT_REVISION:-unknown}
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=1GB
- -c
- checkpoint_timeout=15min
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.6}"
memory: ${POSTGRES_MEM_LIMIT:-512M}
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.15}"
memory: ${VALKEY_MEM_LIMIT:-128M}
# 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-lab3-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
CACHE_URL: redis://:${VALKEY_PASSWORD:?set VALKEY_PASSWORD in .env via make env}@valkey:6379/0
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"
security_opt:
- no-new-privileges:true
deploy:
resources:
limits:
cpus: "0.25"
memory: 128M
api:
image: ${API_IMAGE:-mtusi-messenger-lab3-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:-220MiB}
depends_on:
postgres:
condition: service_healthy
valkey:
condition: service_healthy
migrate:
condition: service_completed_successfully
networks:
- backend
healthcheck:
test: ["CMD", "/app/messenger", "-healthcheck"]
interval: 3s
timeout: 2s
retries: 12
start_period: 10s
restart: unless-stopped
read_only: true
tmpfs:
- /tmp
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.4}"
memory: ${API_MEM_LIMIT:-256M}
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:-8083}: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.1}"
memory: ${LB_MEM_LIMIT:-64M}
volumes:
pgdata:
name: mtusi-lab3-melnikov-pgdata
valkeydata:
name: mtusi-lab3-melnikov-valkeydata
networks:
backend:
name: mtusi-lab3-melnikov-net
@@ -0,0 +1,193 @@
{
"tool": "mtusi-lab3-loadgen",
"version": "dev",
"started_at": "2026-12-02T15:20:50.488268Z",
"finished_at": "2026-12-02T15:21:06.489711Z",
"measured_seconds": 16.002,
"warmup_seconds": 2,
"concurrency": 8,
"rate_limit_per_second": 0,
"read_ratio": 0.5,
"retry_uncertain": true,
"profile": "closed-loop",
"successful_requests": 40360,
"failed_requests": 0,
"error_ratio": 0,
"successful_rps": 2522.234,
"offered_rps": 2522.234,
"successful_latency_ms": {
"p50": 1.897,
"p95": 5.411,
"p99": 51.351,
"max": 87.701,
"mean": 3.169
},
"status_counts": {
"200": 20000,
"201": 20360
},
"instances": {
"1b3b710ee8b7": 34486,
"286d4623fa19": 5874
},
"app_versions": {
"1.0.0": 40360
},
"kinds": {
"read": 20000,
"write": 20360
},
"series": [
{
"second": 1796224850,
"success": 1167,
"errors": 0,
"p50_ms": 2.905,
"p95_ms": 5.862,
"p99_ms": 20.031
},
{
"second": 1796224851,
"success": 2717,
"errors": 0,
"p50_ms": 2.25,
"p95_ms": 4.53,
"p99_ms": 23.012
},
{
"second": 1796224852,
"success": 2847,
"errors": 0,
"p50_ms": 1.234,
"p95_ms": 2.082,
"p99_ms": 57.141
},
{
"second": 1796224853,
"success": 2148,
"errors": 0,
"p50_ms": 3.042,
"p95_ms": 7.324,
"p99_ms": 20.46
},
{
"second": 1796224854,
"success": 2440,
"errors": 0,
"p50_ms": 2.739,
"p95_ms": 5.608,
"p99_ms": 21.487
},
{
"second": 1796224855,
"success": 2770,
"errors": 0,
"p50_ms": 1.183,
"p95_ms": 2.281,
"p99_ms": 60.519
},
{
"second": 1796224856,
"success": 2620,
"errors": 0,
"p50_ms": 2.354,
"p95_ms": 4.623,
"p99_ms": 25.295
},
{
"second": 1796224857,
"success": 2529,
"errors": 0,
"p50_ms": 2.463,
"p95_ms": 4.315,
"p99_ms": 27.288
},
{
"second": 1796224858,
"success": 2422,
"errors": 0,
"p50_ms": 1.162,
"p95_ms": 2.529,
"p99_ms": 67.87
},
{
"second": 1796224859,
"success": 2284,
"errors": 0,
"p50_ms": 1.783,
"p95_ms": 9.091,
"p99_ms": 51.09
},
{
"second": 1796224860,
"success": 2267,
"errors": 0,
"p50_ms": 2.893,
"p95_ms": 5.58,
"p99_ms": 19.855
},
{
"second": 1796224861,
"success": 3075,
"errors": 0,
"p50_ms": 1.182,
"p95_ms": 3.787,
"p99_ms": 57.88
},
{
"second": 1796224862,
"success": 2663,
"errors": 0,
"p50_ms": 1.373,
"p95_ms": 3.77,
"p99_ms": 55.762
},
{
"second": 1796224863,
"success": 1780,
"errors": 0,
"p50_ms": 3.17,
"p95_ms": 11.969,
"p99_ms": 25.463
},
{
"second": 1796224864,
"success": 2574,
"errors": 0,
"p50_ms": 1.596,
"p95_ms": 6.574,
"p99_ms": 39.102
},
{
"second": 1796224865,
"success": 2877,
"errors": 0,
"p50_ms": 1.13,
"p95_ms": 3.197,
"p99_ms": 59.883
},
{
"second": 1796224866,
"success": 1180,
"errors": 0,
"p50_ms": 2.631,
"p95_ms": 4.819,
"p99_ms": 22.043
}
],
"uncertain_retries": 0,
"note": "level-4 failover matrix, target 286d4623fa19; synthetic messages created by loadgen, no retries unless -retry-uncertain",
"failover": {
"target_instance": "286d4623fa19",
"stop_started_at": "2026-12-02T15:20:53.488355Z",
"stop_finished_at": "2026-12-02T15:20:56.775656Z",
"stop_script_exit": 0,
"stop_duration_seconds": 3.287,
"first_success_after_stop_seconds": 0.005,
"first_write_after_stop_seconds": 0.005,
"successes_after_stop": 32440,
"errors_after_stop": 0,
"target_responses_after_stop": 0,
"target_last_response_at": "2026-12-02T15:20:55.126081Z"
}
}
@@ -0,0 +1,193 @@
{
"tool": "mtusi-lab3-loadgen",
"version": "dev",
"started_at": "2026-12-02T15:21:09.519285Z",
"finished_at": "2026-12-02T15:21:25.524239Z",
"measured_seconds": 16.005,
"warmup_seconds": 2,
"concurrency": 8,
"rate_limit_per_second": 0,
"read_ratio": 0.5,
"retry_uncertain": true,
"profile": "closed-loop",
"successful_requests": 40771,
"failed_requests": 0,
"error_ratio": 0,
"successful_rps": 2547.359,
"offered_rps": 2547.359,
"successful_latency_ms": {
"p50": 1.923,
"p95": 4.865,
"p99": 47.339,
"max": 88.058,
"mean": 3.137
},
"status_counts": {
"200": 20000,
"201": 20771
},
"instances": {
"1b3b710ee8b7": 4524,
"286d4623fa19": 36247
},
"app_versions": {
"1.0.0": 40771
},
"kinds": {
"read": 20000,
"write": 20771
},
"series": [
{
"second": 1796224869,
"success": 1144,
"errors": 0,
"p50_ms": 2.856,
"p95_ms": 4.969,
"p99_ms": 18.281
},
{
"second": 1796224870,
"success": 1869,
"errors": 0,
"p50_ms": 3.441,
"p95_ms": 13.169,
"p99_ms": 21.36
},
{
"second": 1796224871,
"success": 2844,
"errors": 0,
"p50_ms": 1.249,
"p95_ms": 2.215,
"p99_ms": 55.604
},
{
"second": 1796224872,
"success": 2511,
"errors": 0,
"p50_ms": 2.392,
"p95_ms": 5.072,
"p99_ms": 28.992
},
{
"second": 1796224873,
"success": 2044,
"errors": 0,
"p50_ms": 2.836,
"p95_ms": 11.984,
"p99_ms": 26.677
},
{
"second": 1796224874,
"success": 2928,
"errors": 0,
"p50_ms": 1.178,
"p95_ms": 2.993,
"p99_ms": 58.086
},
{
"second": 1796224875,
"success": 2589,
"errors": 0,
"p50_ms": 1.824,
"p95_ms": 4.502,
"p99_ms": 48.765
},
{
"second": 1796224876,
"success": 2275,
"errors": 0,
"p50_ms": 2.69,
"p95_ms": 4.965,
"p99_ms": 27.491
},
{
"second": 1796224877,
"success": 2570,
"errors": 0,
"p50_ms": 1.25,
"p95_ms": 3.48,
"p99_ms": 60.57
},
{
"second": 1796224878,
"success": 2821,
"errors": 0,
"p50_ms": 1.352,
"p95_ms": 3.465,
"p99_ms": 45.405
},
{
"second": 1796224879,
"success": 2310,
"errors": 0,
"p50_ms": 2.661,
"p95_ms": 5.478,
"p99_ms": 26.679
},
{
"second": 1796224880,
"success": 2757,
"errors": 0,
"p50_ms": 1.313,
"p95_ms": 3.807,
"p99_ms": 55.155
},
{
"second": 1796224881,
"success": 3015,
"errors": 0,
"p50_ms": 1.297,
"p95_ms": 3.332,
"p99_ms": 56.109
},
{
"second": 1796224882,
"success": 2368,
"errors": 0,
"p50_ms": 2.605,
"p95_ms": 4.63,
"p99_ms": 23.228
},
{
"second": 1796224883,
"success": 2651,
"errors": 0,
"p50_ms": 1.298,
"p95_ms": 4.5,
"p99_ms": 58.57
},
{
"second": 1796224884,
"success": 2959,
"errors": 0,
"p50_ms": 1.264,
"p95_ms": 3.888,
"p99_ms": 56.6
},
{
"second": 1796224885,
"success": 1116,
"errors": 0,
"p50_ms": 2.687,
"p95_ms": 4.913,
"p99_ms": 27.491
}
],
"uncertain_retries": 0,
"note": "level-4 failover matrix, target 1b3b710ee8b7; synthetic messages created by loadgen, no retries unless -retry-uncertain",
"failover": {
"target_instance": "1b3b710ee8b7",
"stop_started_at": "2026-12-02T15:21:12.521297Z",
"stop_finished_at": "2026-12-02T15:21:15.837741Z",
"stop_script_exit": 0,
"stop_duration_seconds": 3.316,
"first_success_after_stop_seconds": 0.004,
"first_write_after_stop_seconds": 0.004,
"successes_after_stop": 33494,
"errors_after_stop": 0,
"target_responses_after_stop": 0,
"target_last_response_at": "2026-12-02T15:21:13.345522Z"
}
}
+510
View File
@@ -0,0 +1,510 @@
{
"started_at": "2026-12-02T15:20:47.632397Z",
"base_url": "http://127.0.0.1:8083",
"image": "mtusi-messenger-lab3-melnikov:local",
"profile": {
"api_replicas": 2,
"api_cpu_limit": "0.4",
"api_mem_limit": "256M"
},
"containers_before": [
{
"container_id": "286d4623fa1976ac75919bae70692ff23a995b73c91e1f2e9c1e29c8e9c28d14",
"name": "mtusi-lab3-melnikov-api-1",
"hostname": "286d4623fa19",
"image": "mtusi-messenger-lab3-melnikov:local",
"state": "running",
"started_at": "2026-12-02T15:20:47.115851522Z",
"finished_at": "0001-01-01T00:00:00Z",
"exit_code": 0
},
{
"container_id": "1b3b710ee8b716806b7e304d83406d544ba186810d8e407fbe90cc1916695c8b",
"name": "mtusi-lab3-melnikov-api-2",
"hostname": "1b3b710ee8b7",
"image": "mtusi-messenger-lab3-melnikov:local",
"state": "running",
"started_at": "2026-12-02T15:20:47.198184541Z",
"finished_at": "0001-01-01T00:00:00Z",
"exit_code": 0
}
],
"results": [
{
"target_instance": "286d4623fa19",
"target_container": {
"container_id": "286d4623fa1976ac75919bae70692ff23a995b73c91e1f2e9c1e29c8e9c28d14",
"name": "mtusi-lab3-melnikov-api-1",
"image": "mtusi-messenger-lab3-melnikov:local",
"started_at_before": "2026-12-02T15:20:47.115851522Z",
"finished_at_after_stop": "2026-12-02T15:20:56.984367056Z",
"exit_code_after_stop": 0
},
"probe_elapsed_seconds": 18.877,
"loadgen": {
"tool": "mtusi-lab3-loadgen",
"version": "dev",
"started_at": "2026-12-02T15:20:50.488268Z",
"finished_at": "2026-12-02T15:21:06.489711Z",
"measured_seconds": 16.002,
"warmup_seconds": 2,
"concurrency": 8,
"rate_limit_per_second": 0,
"read_ratio": 0.5,
"retry_uncertain": true,
"profile": "closed-loop",
"successful_requests": 40360,
"failed_requests": 0,
"error_ratio": 0,
"successful_rps": 2522.234,
"offered_rps": 2522.234,
"successful_latency_ms": {
"p50": 1.897,
"p95": 5.411,
"p99": 51.351,
"max": 87.701,
"mean": 3.169
},
"status_counts": {
"200": 20000,
"201": 20360
},
"instances": {
"1b3b710ee8b7": 34486,
"286d4623fa19": 5874
},
"app_versions": {
"1.0.0": 40360
},
"kinds": {
"read": 20000,
"write": 20360
},
"series": [
{
"second": 1796224850,
"success": 1167,
"errors": 0,
"p50_ms": 2.905,
"p95_ms": 5.862,
"p99_ms": 20.031
},
{
"second": 1796224851,
"success": 2717,
"errors": 0,
"p50_ms": 2.25,
"p95_ms": 4.53,
"p99_ms": 23.012
},
{
"second": 1796224852,
"success": 2847,
"errors": 0,
"p50_ms": 1.234,
"p95_ms": 2.082,
"p99_ms": 57.141
},
{
"second": 1796224853,
"success": 2148,
"errors": 0,
"p50_ms": 3.042,
"p95_ms": 7.324,
"p99_ms": 20.46
},
{
"second": 1796224854,
"success": 2440,
"errors": 0,
"p50_ms": 2.739,
"p95_ms": 5.608,
"p99_ms": 21.487
},
{
"second": 1796224855,
"success": 2770,
"errors": 0,
"p50_ms": 1.183,
"p95_ms": 2.281,
"p99_ms": 60.519
},
{
"second": 1796224856,
"success": 2620,
"errors": 0,
"p50_ms": 2.354,
"p95_ms": 4.623,
"p99_ms": 25.295
},
{
"second": 1796224857,
"success": 2529,
"errors": 0,
"p50_ms": 2.463,
"p95_ms": 4.315,
"p99_ms": 27.288
},
{
"second": 1796224858,
"success": 2422,
"errors": 0,
"p50_ms": 1.162,
"p95_ms": 2.529,
"p99_ms": 67.87
},
{
"second": 1796224859,
"success": 2284,
"errors": 0,
"p50_ms": 1.783,
"p95_ms": 9.091,
"p99_ms": 51.09
},
{
"second": 1796224860,
"success": 2267,
"errors": 0,
"p50_ms": 2.893,
"p95_ms": 5.58,
"p99_ms": 19.855
},
{
"second": 1796224861,
"success": 3075,
"errors": 0,
"p50_ms": 1.182,
"p95_ms": 3.787,
"p99_ms": 57.88
},
{
"second": 1796224862,
"success": 2663,
"errors": 0,
"p50_ms": 1.373,
"p95_ms": 3.77,
"p99_ms": 55.762
},
{
"second": 1796224863,
"success": 1780,
"errors": 0,
"p50_ms": 3.17,
"p95_ms": 11.969,
"p99_ms": 25.463
},
{
"second": 1796224864,
"success": 2574,
"errors": 0,
"p50_ms": 1.596,
"p95_ms": 6.574,
"p99_ms": 39.102
},
{
"second": 1796224865,
"success": 2877,
"errors": 0,
"p50_ms": 1.13,
"p95_ms": 3.197,
"p99_ms": 59.883
},
{
"second": 1796224866,
"success": 1180,
"errors": 0,
"p50_ms": 2.631,
"p95_ms": 4.819,
"p99_ms": 22.043
}
],
"uncertain_retries": 0,
"note": "level-4 failover matrix, target 286d4623fa19; synthetic messages created by loadgen, no retries unless -retry-uncertain",
"failover": {
"target_instance": "286d4623fa19",
"stop_started_at": "2026-12-02T15:20:53.488355Z",
"stop_finished_at": "2026-12-02T15:20:56.775656Z",
"stop_script_exit": 0,
"stop_duration_seconds": 3.287,
"first_success_after_stop_seconds": 0.005,
"first_write_after_stop_seconds": 0.005,
"successes_after_stop": 32440,
"errors_after_stop": 0,
"target_responses_after_stop": 0,
"target_last_response_at": "2026-12-02T15:20:55.126081Z"
}
},
"checks": {
"stop_script_exit_zero": true,
"target_container_exited": true,
"target_not_answering_after_stop": true,
"first_success_within_10s": true,
"first_write_within_10s": true,
"no_idempotency_violations": true,
"other_replica_still_running": true
},
"restore_seconds_until_lb_serves_target": 0.838,
"containers_after_stop": [
{
"container_id": "286d4623fa1976ac75919bae70692ff23a995b73c91e1f2e9c1e29c8e9c28d14",
"name": "mtusi-lab3-melnikov-api-1",
"hostname": "286d4623fa19",
"image": "mtusi-messenger-lab3-melnikov:local",
"state": "exited",
"started_at": "2026-12-02T15:20:47.115851522Z",
"finished_at": "2026-12-02T15:20:56.984367056Z",
"exit_code": 0
},
{
"container_id": "1b3b710ee8b716806b7e304d83406d544ba186810d8e407fbe90cc1916695c8b",
"name": "mtusi-lab3-melnikov-api-2",
"hostname": "1b3b710ee8b7",
"image": "mtusi-messenger-lab3-melnikov:local",
"state": "running",
"started_at": "2026-12-02T15:20:47.198184541Z",
"finished_at": "0001-01-01T00:00:00Z",
"exit_code": 0
}
]
},
{
"target_instance": "1b3b710ee8b7",
"target_container": {
"container_id": "1b3b710ee8b716806b7e304d83406d544ba186810d8e407fbe90cc1916695c8b",
"name": "mtusi-lab3-melnikov-api-2",
"image": "mtusi-messenger-lab3-melnikov:local",
"started_at_before": "2026-12-02T15:20:47.198184541Z",
"finished_at_after_stop": "2026-12-02T15:21:16.040602824Z",
"exit_code_after_stop": 0
},
"probe_elapsed_seconds": 18.157,
"loadgen": {
"tool": "mtusi-lab3-loadgen",
"version": "dev",
"started_at": "2026-12-02T15:21:09.519285Z",
"finished_at": "2026-12-02T15:21:25.524239Z",
"measured_seconds": 16.005,
"warmup_seconds": 2,
"concurrency": 8,
"rate_limit_per_second": 0,
"read_ratio": 0.5,
"retry_uncertain": true,
"profile": "closed-loop",
"successful_requests": 40771,
"failed_requests": 0,
"error_ratio": 0,
"successful_rps": 2547.359,
"offered_rps": 2547.359,
"successful_latency_ms": {
"p50": 1.923,
"p95": 4.865,
"p99": 47.339,
"max": 88.058,
"mean": 3.137
},
"status_counts": {
"200": 20000,
"201": 20771
},
"instances": {
"1b3b710ee8b7": 4524,
"286d4623fa19": 36247
},
"app_versions": {
"1.0.0": 40771
},
"kinds": {
"read": 20000,
"write": 20771
},
"series": [
{
"second": 1796224869,
"success": 1144,
"errors": 0,
"p50_ms": 2.856,
"p95_ms": 4.969,
"p99_ms": 18.281
},
{
"second": 1796224870,
"success": 1869,
"errors": 0,
"p50_ms": 3.441,
"p95_ms": 13.169,
"p99_ms": 21.36
},
{
"second": 1796224871,
"success": 2844,
"errors": 0,
"p50_ms": 1.249,
"p95_ms": 2.215,
"p99_ms": 55.604
},
{
"second": 1796224872,
"success": 2511,
"errors": 0,
"p50_ms": 2.392,
"p95_ms": 5.072,
"p99_ms": 28.992
},
{
"second": 1796224873,
"success": 2044,
"errors": 0,
"p50_ms": 2.836,
"p95_ms": 11.984,
"p99_ms": 26.677
},
{
"second": 1796224874,
"success": 2928,
"errors": 0,
"p50_ms": 1.178,
"p95_ms": 2.993,
"p99_ms": 58.086
},
{
"second": 1796224875,
"success": 2589,
"errors": 0,
"p50_ms": 1.824,
"p95_ms": 4.502,
"p99_ms": 48.765
},
{
"second": 1796224876,
"success": 2275,
"errors": 0,
"p50_ms": 2.69,
"p95_ms": 4.965,
"p99_ms": 27.491
},
{
"second": 1796224877,
"success": 2570,
"errors": 0,
"p50_ms": 1.25,
"p95_ms": 3.48,
"p99_ms": 60.57
},
{
"second": 1796224878,
"success": 2821,
"errors": 0,
"p50_ms": 1.352,
"p95_ms": 3.465,
"p99_ms": 45.405
},
{
"second": 1796224879,
"success": 2310,
"errors": 0,
"p50_ms": 2.661,
"p95_ms": 5.478,
"p99_ms": 26.679
},
{
"second": 1796224880,
"success": 2757,
"errors": 0,
"p50_ms": 1.313,
"p95_ms": 3.807,
"p99_ms": 55.155
},
{
"second": 1796224881,
"success": 3015,
"errors": 0,
"p50_ms": 1.297,
"p95_ms": 3.332,
"p99_ms": 56.109
},
{
"second": 1796224882,
"success": 2368,
"errors": 0,
"p50_ms": 2.605,
"p95_ms": 4.63,
"p99_ms": 23.228
},
{
"second": 1796224883,
"success": 2651,
"errors": 0,
"p50_ms": 1.298,
"p95_ms": 4.5,
"p99_ms": 58.57
},
{
"second": 1796224884,
"success": 2959,
"errors": 0,
"p50_ms": 1.264,
"p95_ms": 3.888,
"p99_ms": 56.6
},
{
"second": 1796224885,
"success": 1116,
"errors": 0,
"p50_ms": 2.687,
"p95_ms": 4.913,
"p99_ms": 27.491
}
],
"uncertain_retries": 0,
"note": "level-4 failover matrix, target 1b3b710ee8b7; synthetic messages created by loadgen, no retries unless -retry-uncertain",
"failover": {
"target_instance": "1b3b710ee8b7",
"stop_started_at": "2026-12-02T15:21:12.521297Z",
"stop_finished_at": "2026-12-02T15:21:15.837741Z",
"stop_script_exit": 0,
"stop_duration_seconds": 3.316,
"first_success_after_stop_seconds": 0.004,
"first_write_after_stop_seconds": 0.004,
"successes_after_stop": 33494,
"errors_after_stop": 0,
"target_responses_after_stop": 0,
"target_last_response_at": "2026-12-02T15:21:13.345522Z"
}
},
"checks": {
"stop_script_exit_zero": true,
"target_container_exited": true,
"target_not_answering_after_stop": true,
"first_success_within_10s": true,
"first_write_within_10s": true,
"no_idempotency_violations": true,
"other_replica_still_running": true
},
"restore_seconds_until_lb_serves_target": 0.608,
"containers_after_stop": [
{
"container_id": "286d4623fa1976ac75919bae70692ff23a995b73c91e1f2e9c1e29c8e9c28d14",
"name": "mtusi-lab3-melnikov-api-1",
"hostname": "286d4623fa19",
"image": "mtusi-messenger-lab3-melnikov:local",
"state": "running",
"started_at": "2026-12-02T15:21:06.876638057Z",
"finished_at": "2026-12-02T15:20:56.984367056Z",
"exit_code": 0
},
{
"container_id": "1b3b710ee8b716806b7e304d83406d544ba186810d8e407fbe90cc1916695c8b",
"name": "mtusi-lab3-melnikov-api-2",
"hostname": "1b3b710ee8b7",
"image": "mtusi-messenger-lab3-melnikov:local",
"state": "exited",
"started_at": "2026-12-02T15:20:47.198184541Z",
"finished_at": "2026-12-02T15:21:16.040602824Z",
"exit_code": 0
}
]
}
],
"finished_at": "2026-12-02T15:21:26.194211Z",
"all_checks_passed": true
}
+20
View File
@@ -0,0 +1,20 @@
module mtusi.ru/messenger-lab3
go 1.25.1
require (
github.com/jackc/pgx/v5 v5.7.2
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/jackc/pgpassfile v1.0.0 // indirect
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
github.com/jackc/puddle/v2 v2.2.2 // indirect
golang.org/x/sync v0.10.0 // indirect
golang.org/x/sys v0.28.0 // indirect
golang.org/x/text v0.21.0 // indirect
)
+40
View File
@@ -0,0 +1,40 @@
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/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/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/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.8.1 h1:w7B6lhMri9wdJUVmEZPGGhZzrYTPvgJArz7wNPgYKsk=
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
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/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.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=
+60
View File
@@ -0,0 +1,60 @@
# 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
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
+236
View File
@@ -0,0 +1,236 @@
package api
import (
"context"
"encoding/json"
"log/slog"
"net/http"
"strings"
"sync/atomic"
"time"
"mtusi.ru/messenger-lab3/internal/auth"
"mtusi.ru/messenger-lab3/internal/model"
"mtusi.ru/messenger-lab3/internal/session"
"mtusi.ru/messenger-lab3/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
log *slog.Logger
ready atomic.Bool
maxBody int64
instanceID string
version string
startedAt time.Time
dummyHash string
createdMessages atomic.Uint64
replayedMessages atomic.Uint64
conflictMessages atomic.Uint64
}
// 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, logger *slog.Logger, instanceID, version string) (*App, error) {
dummy, err := auth.Hash("dummy-password-never-used-for-login")
if err != nil {
return nil, err
}
app := &App{
store: repository,
sessions: sessions,
log: logger,
maxBody: maxBodyBytes,
instanceID: instanceID,
version: version,
startedAt: time.Now(),
dummyHash: dummy,
}
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/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] == "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
}
+137
View File
@@ -0,0 +1,137 @@
package api
import (
"errors"
"net/http"
"mtusi.ru/messenger-lab3/internal/cursor"
"mtusi.ru/messenger-lab3/internal/store"
"mtusi.ru/messenger-lab3/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
}
+176
View File
@@ -0,0 +1,176 @@
package api
import (
"context"
"log/slog"
"net/http"
"sync/atomic"
"time"
"mtusi.ru/messenger-lab3/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 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() }
+150
View File
@@ -0,0 +1,150 @@
package api
import (
"crypto/sha256"
"errors"
"net/http"
"mtusi.ru/messenger-lab3/internal/cursor"
"mtusi.ru/messenger-lab3/internal/store"
)
type createMessageRequest struct {
Text *string `json:"text"`
}
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"); problem != nil {
a.writeError(w, r, problem)
return
}
if request.Text == nil {
a.writeError(w, r, invalidRequest("text is required"))
return
}
if problem := validateMessageText(*request.Text); problem != nil {
a.writeError(w, r, problem)
return
}
// The canonical body for lab3 is {"text": ...}. Hash the decoded text, not
// the raw bytes: insignificant JSON whitespace or escapes must replay the
// same key, while any different text must conflict. attachment_ids is not
// part of the lab3 schema; lab4 will extend this canonical form.
hash := sha256.Sum256([]byte(*request.Text))
message, replayed, err := a.store.CreateMessageIdempotent(
r.Context(), chatID, actor.user.ID, http.MethodPost, messagePath(chatID), idempotencyKey, hash[:], *request.Text,
)
switch {
case errors.Is(err, store.ErrIdempotencyConflict):
a.conflictMessages.Add(1)
a.writeError(w, r, statusConflict)
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)
}
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-lab3/internal/auth"
"mtusi.ru/messenger-lab3/internal/model"
"mtusi.ru/messenger-lab3/internal/session"
"mtusi.ru/messenger-lab3/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-lab3/internal/auth"
"mtusi.ru/messenger-lab3/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
}
+245
View File
@@ -0,0 +1,245 @@
// 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
}
// Load reads and validates the runtime configuration.
func Load() (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
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
return cfg, nil
}
// 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 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)
}
}
+131
View File
@@ -0,0 +1,131 @@
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",
}
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")
}
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)
}
}
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)
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"},
}
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 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-lab3/internal/model"
"mtusi.ru/messenger-lab3/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-lab3/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)
}
}
}
+69
View File
@@ -0,0 +1,69 @@
// 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.
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"`
}
// 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)
}
}
}
+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-lab3/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 }
+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
}
+64
View File
@@ -0,0 +1,64 @@
package store
import (
"strings"
"testing"
)
func TestLoadMigrations(t *testing.T) {
migrations, err := loadMigrations()
if err != nil {
t.Fatalf("loadMigrations: %v", err)
}
if len(migrations) != 3 {
t.Fatalf("loaded %d migrations, want 3", len(migrations))
}
if migrations[0].version != 1 || migrations[1].version != 2 || migrations[2].version != 3 {
t.Fatalf("migration order = %d,%d,%d", migrations[0].version, migrations[1].version, migrations[2].version)
}
for _, item := range migrations {
if len(item.checksum) != 64 {
t.Fatalf("checksum for %d has length %d", item.version, len(item.checksum))
}
if !strings.Contains(strings.ToLower(item.sql), "create ") {
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)",
} {
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);
+631
View File
@@ -0,0 +1,631 @@
// 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-lab3/internal/cursor"
"mtusi.ru/messenger-lab3/internal/model"
"mtusi.ru/messenger-lab3/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")
)
// 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-lab3"
// 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"
}
// 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(),
}
}
// CreateMessage appends a message. The composite foreign key also guarantees
// that the sender belongs to the chat at the database level.
func (s *Store) CreateMessage(ctx context.Context, chatID, senderID, text string) (model.Message, error) {
ctx, cancel := s.opCtx(ctx)
defer cancel()
message := model.Message{
ID: uuid.New(),
ChatID: chatID,
SenderID: senderID,
Text: text,
}
var createdAt time.Time
err := s.pool.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, time.Now().UTC(),
).Scan(&createdAt)
if err != nil {
if isForeignKeyViolation(err) {
return model.Message{}, ErrNotFound
}
return model.Message{}, s.classify(err)
}
message.CreatedAt = model.Time{Time: createdAt.UTC()}
return message, nil
}
// CreateMessageIdempotent appends a message and records the idempotency
// result in one transaction. It is the lab3 replacement for CreateMessage on
// the public POST path.
//
// 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, 201, exactly once;
// - a different body with the same key is a conflict, 409;
// - a transient failure rolls both statements back, 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) (model.Message, bool, error) {
message := model.Message{
ID: uuid.New(),
ChatID: chatID,
SenderID: senderID,
Text: text,
}
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()) }()
var createdAt time.Time
if 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, time.Now().UTC(),
).Scan(&createdAt); err != nil {
if isForeignKeyViolation(err) {
return model.Message{}, false, ErrNotFound
}
return model.Message{}, false, s.classify(err)
}
tag, 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)
ON CONFLICT (user_id, method, path, key) DO NOTHING`,
senderID, method, path, key, requestHash, message.ID, time.Now().UTC(),
)
if err != nil {
return model.Message{}, false, s.classify(err)
}
if tag.RowsAffected() == 1 {
if err := tx.Commit(ctx); err != nil {
return model.Message{}, false, s.classify(err)
}
message.CreatedAt = model.Time{Time: createdAt.UTC()}
return message, false, nil
}
// Another transaction owns this key. Roll back this speculative message,
// then read the committed record. A concurrent insert waits on the unique
// index inside Exec above, so the conflicting row is already committed
// when RowsAffected reports zero.
_ = tx.Rollback(context.Background())
storedHash, storedMessage, found, err := s.replayIdempotent(ctx, senderID, method, path, key)
if err != nil {
return model.Message{}, false, err
}
if !found {
// The conflicting row disappeared between the conflict and this read
// (only a retention prune can do that). Report a bounded transient
// error; no message was committed and the same key is safe to retry.
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
}
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
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)
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return nil, model.Message{}, false, nil
}
return nil, model.Message{}, false, s.classify(err)
}
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 id::text, chat_id::text, sender_id::text, text, created_at
FROM messages
WHERE chat_id = $1::uuid`
// 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()
query := messagesPageSelect + `
ORDER BY created_at, messages.id
LIMIT $2`
args := []any{chatID, limit + 1}
if position != nil {
query = messagesPageSelect + `
AND (created_at, messages.id) > ($2::timestamptz, $3::uuid)
ORDER BY created_at, messages.id
LIMIT $4`
args = []any{chatID, position.At, position.ID, limit + 1}
}
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); err != nil {
return model.MessagePage{}, s.classify(err)
}
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)
}
}
}
+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
+239
View File
@@ -0,0 +1,239 @@
#!/usr/bin/env python3
"""Level-4 evidence: stop every real API replica in turn under load.
For each of the two default API containers this script:
* starts a mixed read/write probe through the LB;
* asks scripts/stop-one.sh to stop the process that actually served the
target X-Instance-Id (the script maps the hostname to one container);
* records per-second successes/errors, first success and first write after
the stop began, and whether the stopped instance answered after the stop;
* restarts exactly that container and waits until the LB routes to it again.
It never removes volumes and never stops PostgreSQL, Valkey or HAProxy.
Python 3.9+, standard library only.
"""
import argparse
import datetime as dt
import json
import os
import subprocess
import sys
import time
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
COMPOSE = str(ROOT / 'scripts/compose.sh')
PROJECT = 'mtusi-lab3-melnikov'
LOADGEN = Path('/tmp/mtusi-lab3-loadgen')
OUT = ROOT / 'evidence/failover'
BASE = 'http://127.0.0.1:8083'
def now():
return dt.datetime.now(dt.timezone.utc).isoformat().replace('+00:00', 'Z')
def run(command, env=None, cwd=ROOT, check=True):
return subprocess.run(command, cwd=str(cwd), env=env, text=True,
capture_output=True, check=check)
def compose(*args, env_extra=None, check=True):
env = os.environ.copy()
# The compose file interpolates these; keep the experiment deterministic.
env.update(env_extra or {})
return run([COMPOSE, '--env-file', '.env'] + list(args), env=env, check=check)
def api_containers():
result = run(['docker', 'ps', '-aq',
'--filter', 'label=com.docker.compose.service=api',
'--filter', 'label=com.docker.compose.project=' + PROJECT])
containers = []
for container in result.stdout.split():
info = run(['docker', 'inspect', container]).stdout
data = json.loads(info)[0]
containers.append({
'container_id': data['Id'],
'name': data['Name'].lstrip('/'),
'hostname': data['Config']['Hostname'],
'image': data['Config']['Image'],
'state': data['State']['Status'],
'started_at': data['State']['StartedAt'],
'finished_at': data['State'].get('FinishedAt', ''),
'exit_code': data['State'].get('ExitCode'),
})
return sorted(containers, key=lambda item: item['name'])
def wait_http_ready(timeout=60):
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
result = run(['curl', '-fsS', '-o', '/dev/null', BASE + '/health/ready'], check=False)
if result.returncode == 0:
return True
time.sleep(0.25)
return False
def wait_all_running(expected, timeout=60):
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
containers = api_containers()
if len(containers) == expected and all(c['state'] == 'running' for c in containers):
return containers
time.sleep(0.25)
raise RuntimeError('API replicas did not all reach running state')
def wait_target_serving(target, timeout=45):
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
result = run(['curl', '-fsS', '-D', '-', '-o', '/dev/null', BASE + '/health/live'], check=False)
if result.returncode == 0 and ('x-instance-id: ' + target) in result.stdout.lower():
return True
time.sleep(0.2)
return False
def build_loadgen():
run(['go', 'build', '-o', str(LOADGEN), './cmd/loadgen'])
def set_profile(replicas, cpu, memory, image):
env_extra = {
'API_REPLICAS': str(replicas),
'API_CPU_LIMIT': str(cpu),
'API_MEM_LIMIT': memory,
'GOMEMLIMIT': '200MiB',
'API_IMAGE': image,
'GIT_REVISION': run(['git', 'rev-parse', 'HEAD']).stdout.strip(),
}
compose('up', '-d', '--no-deps', '--force-recreate', 'api', env_extra=env_extra)
wait_all_running(replicas)
if not wait_http_ready(90):
raise RuntimeError('LB did not become ready after recreating API replicas')
def main():
global BASE, OUT
parser = argparse.ArgumentParser(description='Stop each real API replica under load')
parser.add_argument('--base-url', default=BASE)
parser.add_argument('--image', default='mtusi-messenger-lab3-melnikov:local')
parser.add_argument('--replicas', type=int, default=2)
parser.add_argument('--cpu', default='0.4')
parser.add_argument('--memory', default='256M')
parser.add_argument('--output-dir', default='evidence/failover')
args = parser.parse_args()
BASE = args.base_url.rstrip('/')
OUT = (ROOT / args.output_dir).resolve()
OUT.mkdir(parents=True, exist_ok=True)
build_loadgen()
set_profile(args.replicas, args.cpu, args.memory, args.image)
before = api_containers()
if len(before) != args.replicas:
raise RuntimeError('expected %d API containers, got %d' % (args.replicas, len(before)))
if len({item['container_id'] for item in before}) != args.replicas:
raise RuntimeError('API replicas are not distinct container IDs')
if len({item['hostname'] for item in before}) != args.replicas:
raise RuntimeError('API replicas are not distinct instance IDs')
matrix = {
'started_at': now(),
'base_url': BASE,
'image': args.image,
'profile': {'api_replicas': args.replicas, 'api_cpu_limit': args.cpu,
'api_mem_limit': args.memory},
'containers_before': before,
'results': [],
}
for index, item in enumerate(before):
target = item['hostname']
raw_path = OUT / ('%s-%s.json' % (dt.datetime.now(dt.timezone.utc).strftime('%Y%m%dT%H%M%SZ'), target))
command = [
str(LOADGEN), '-base-url', BASE,
'-duration', '16s', '-warmup', '2s', '-concurrency', '8',
'-read-ratio', '0.5', '-timeout', '2s', '-retry-uncertain',
'-stop-instance', target, '-stop-script', str(ROOT / 'scripts/stop-one.sh'),
'-stop-after', '3s', '-output', str(raw_path),
'-note', 'level-4 failover matrix, target ' + target,
]
started = time.time()
probe = run(command, check=False)
elapsed = time.time() - started
if not raw_path.exists():
raise RuntimeError('loadgen produced no output: ' + probe.stderr[-500:])
raw = json.loads(raw_path.read_text())
failover = raw.get('failover') or {}
after_stop = api_containers()
target_container = [c for c in after_stop if c['hostname'] == target]
if not target_container:
raise RuntimeError('target container disappeared')
target_container = target_container[0]
checks = {
'stop_script_exit_zero': failover.get('stop_script_exit') == 0,
'target_container_exited': target_container['state'] == 'exited',
'target_not_answering_after_stop': failover.get('target_responses_after_stop') == 0,
'first_success_within_10s': 0 <= failover.get('first_success_after_stop_seconds', -1) <= 10,
'first_write_within_10s': 0 <= failover.get('first_write_after_stop_seconds', -1) <= 10,
'first_success_on_other_replica_within_10s': 0 <= failover.get('first_success_on_other_replica_seconds', -1) <= 10,
'no_idempotency_violations': not raw.get('idempotency_violations'),
'other_replica_still_running': any(c['hostname'] != target and c['state'] == 'running' for c in after_stop),
}
if not all(checks.values()):
raise RuntimeError('failover checks failed for %s: %r' % (target, checks))
# Restart exactly the stopped container, then wait until the LB serves it.
restore_started = time.time()
run(['docker', 'start', target_container['container_id']])
restored = False
deadline = time.monotonic() + 45
while time.monotonic() < deadline:
current = [c for c in api_containers() if c['hostname'] == target]
if current and current[0]['state'] == 'running' and wait_target_serving(target, 1):
restored = True
break
time.sleep(0.25)
restore_seconds = round(time.time() - restore_started, 3)
if not restored:
raise RuntimeError('restored replica did not start serving again')
matrix['results'].append({
'target_instance': target,
'target_container': {
'container_id': target_container['container_id'],
'name': target_container['name'],
'image': target_container['image'],
'started_at_before': item['started_at'],
'finished_at_after_stop': target_container['finished_at'],
'exit_code_after_stop': target_container['exit_code'],
},
'probe_elapsed_seconds': round(elapsed, 3),
'loadgen': raw,
'checks': checks,
'restore_seconds_until_lb_serves_target': restore_seconds,
'containers_after_stop': after_stop,
})
print('PASS failover target %s: %sB %d success/%d errors, first success %.3fs, other replica %.3fs, first write %.3fs, restore %.3fs' % (
target,
raw.get('successful_rps'), raw.get('successful_requests'), raw.get('failed_requests'),
failover.get('first_success_after_stop_seconds'), failover.get('first_success_on_other_replica_seconds'),
failover.get('first_write_after_stop_seconds'), restore_seconds))
matrix['finished_at'] = now()
matrix['all_checks_passed'] = True
out_file = OUT / 'each-replica.json'
out_file.write_text(json.dumps(matrix, indent=2, ensure_ascii=False) + '\n')
print('wrote', out_file)
print('PASS: stopped and restored each of %d distinct API processes' % len(matrix['results']))
if __name__ == '__main__':
try:
main()
except Exception as exc: # noqa: BLE001 - CLI failure must be non-zero
print('FAIL:', exc)
raise SystemExit(1)
+31
View File
@@ -0,0 +1,31 @@
#!/bin/sh
# Create a local .env with fresh synthetic passwords. The file is ignored by
# Git, is readable only by the current user, and its values are never printed.
set -eu
cd "$(dirname "$0")/.."
if [ -f .env ]; then
echo ".env already exists; refusing to overwrite it" >&2
exit 0
fi
random_secret() {
LC_ALL=C tr -dc 'A-Za-z0-9' < /dev/urandom | head -c 32
}
postgres_password=$(random_secret)
valkey_password=$(random_secret)
if [ "${#postgres_password}" -ne 32 ] || [ "${#valkey_password}" -ne 32 ]; then
echo "could not generate local secrets" >&2
exit 1
fi
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|^GIT_REVISION=.*|GIT_REVISION=${revision}|" \
.env.example > .env
chmod 600 .env
echo "wrote .env with generated local synthetic credentials (mode 600); values not printed"
+465
View File
@@ -0,0 +1,465 @@
"""Shared measurement helpers for lab3 experiments (Python 3.9+).
Metric sources are explicit:
* loadgen JSON - HTTP acknowledgement throughput and latency;
* cgroup v2 files - CPU time and throttling of each container (not RSS);
* PostgreSQL views - commits, tuples, buffer hits, connections, waits;
* HAProxy CSV - request totals, queues, 5xx and connection errors;
* internal stats - pgx pool waits and message idempotency counters.
Nothing here reads tokens or message bodies. All data is synthetic.
"""
import csv
import datetime as dt
import io
import json
import os
import statistics
import subprocess
import time
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
COMPOSE = str(ROOT / 'scripts/compose.sh')
PROJECT = 'mtusi-lab3-melnikov'
BASE_URL = 'http://127.0.0.1:8083'
SERVICES = ('api', 'postgres', 'valkey', 'lb')
def utcnow():
return dt.datetime.now(dt.timezone.utc)
def iso(value=None):
return (value or utcnow()).isoformat().replace('+00:00', 'Z')
def read_env():
values = {}
for line in (ROOT / '.env').read_text().splitlines():
line = line.strip()
if not line or line.startswith('#') or '=' not in line:
continue
key, value = line.split('=', 1)
values[key.strip()] = value.strip()
return values
ENV = read_env()
def run(command, env=None, check=True, cwd=ROOT, timeout=None):
result = subprocess.run(command, cwd=str(cwd), env=env, text=True,
capture_output=True, check=False, timeout=timeout)
if check and result.returncode != 0:
raise RuntimeError('command failed (%d): %s\n%s' % (
result.returncode, ' '.join(command[:6]), (result.stderr or result.stdout)[-800:]))
return result
def compose(*args, env_extra=None, check=True):
env = os.environ.copy()
env.update(env_extra or {})
return run([COMPOSE, '--env-file', '.env'] + list(args), env=env, check=check)
def image_id(container):
return run(['docker', 'inspect', '-f', '{{.Image}}', container]).stdout.strip()
def containers(service, running_only=True):
result = run(['docker', 'ps', '-aq',
'--filter', 'label=com.docker.compose.service=' + service,
'--filter', 'label=com.docker.compose.project=' + PROJECT])
items = []
for container in result.stdout.split():
data = json.loads(run(['docker', 'inspect', container]).stdout)[0]
if running_only and data['State']['Status'] != 'running':
continue
items.append({
'container_id': data['Id'],
'name': data['Name'].lstrip('/'),
'hostname': data['Config']['Hostname'],
'image_ref': data['Config']['Image'],
'image_id': data['Image'],
'state': data['State']['Status'],
'started_at': data['State']['StartedAt'],
'cpu_limit_nano': data['HostConfig'].get('NanoCpus', 0),
'memory_limit_bytes': data['HostConfig'].get('Memory', 0),
'cpu_max': read_text(container, '/sys/fs/cgroup/cpu.max').strip(),
'memory_max': read_text(container, '/sys/fs/cgroup/memory.max').strip(),
})
return sorted(items, key=lambda item: item['name'])
def read_text(container, path):
return run(['docker', 'exec', container, 'cat', path], check=False).stdout
def cgroup(container):
raw = read_text(container, '/sys/fs/cgroup/cpu.stat')
values = {}
for line in raw.splitlines():
parts = line.split()
if len(parts) == 2:
try:
values[parts[0]] = int(parts[1])
except ValueError:
pass
memory = read_text(container, '/sys/fs/cgroup/memory.current').strip()
memory_max = read_text(container, '/sys/fs/cgroup/memory.max').strip()
return {
'usage_usec': values.get('usage_usec', 0),
'user_usec': values.get('user_usec', 0),
'system_usec': values.get('system_usec', 0),
'nr_periods': values.get('nr_periods', 0),
'nr_throttled': values.get('nr_throttled', 0),
'throttled_usec': values.get('throttled_usec', 0),
'memory_current_bytes': int(memory) if memory.isdigit() else None,
'memory_max': memory_max,
}
def cgroup_all():
result = {}
for service in SERVICES:
for item in containers(service):
result[item['container_id']] = {
'service': service,
'hostname': item['hostname'],
'cgroup': cgroup(item['container_id']),
}
return result
def psql_json(sql):
command = ['docker', 'exec', '-i', containers('postgres')[0]['container_id'],
'psql', '-X', '-A', '-t', '-v', 'ON_ERROR_STOP=1',
'-U', ENV['POSTGRES_USER'], '-d', ENV['POSTGRES_DB'], '-c', sql]
result = run(command)
text = result.stdout.strip()
if not text:
return None
return json.loads(text.splitlines()[-1])
def db_snapshot():
database = psql_json("""
SELECT json_build_object(
'xact_commit', xact_commit, 'xact_rollback', xact_rollback,
'blks_read', blks_read, 'blks_hit', blks_hit,
'tup_returned', tup_returned, 'tup_fetched', tup_fetched,
'tup_inserted', tup_inserted, 'tup_updated', tup_updated,
'tup_deleted', tup_deleted, 'deadlocks', deadlocks,
'temp_files', temp_files, 'temp_bytes', temp_bytes,
'stats_reset', stats_reset)
FROM pg_stat_database WHERE datname = current_database();""")
activity = psql_json("""
SELECT json_build_object(
'total', count(*),
'active', count(*) FILTER (WHERE state = 'active'),
'idle', count(*) FILTER (WHERE state = 'idle'),
'active_waiting', count(*) FILTER (WHERE state = 'active' AND wait_event_type IS NOT NULL),
'idle_in_transaction', count(*) FILTER (WHERE state = 'idle in transaction'))
FROM pg_stat_activity WHERE datname = current_database();""")
datasets = psql_json("""
SELECT json_build_object(
'messages', (SELECT count(*) FROM messages),
'idempotency', (SELECT count(*) FROM message_idempotency),
'users', (SELECT count(*) FROM users),
'chats', (SELECT count(*) FROM chats),
'db_bytes', pg_database_size(current_database()),
'locks', (SELECT count(*) FROM pg_locks));""")
settings = psql_json("""
SELECT json_build_object(
'max_connections', current_setting('max_connections')::int,
'shared_buffers', current_setting('shared_buffers'),
'synchronous_commit', current_setting('synchronous_commit'));""")
row = activity or {}
row['database'] = database or {}
row['datasets'] = datasets or {}
row['settings'] = settings or {}
return row
def haproxy_snapshot():
container = containers('lb')[0]['container_id']
result = run(['docker', 'exec', container, 'wget', '-qO-', 'http://127.0.0.1:8404/stats;csv'])
lines = [line for line in result.stdout.splitlines() if line.strip()]
if not lines:
return {}
header = lines[0].lstrip('# ').split(',')
rows = {}
for line in lines[1:]:
values = next(csv.reader(io.StringIO(line)))
item = dict(zip(header, values))
key = item.get('pxname', '') + '/' + item.get('svname', '')
rows[key] = item
return {
'public': rows.get('public/FRONTEND', {}),
'backend': rows.get('api/BACKEND', {}),
'servers': {key.split('/', 1)[1]: value for key, value in rows.items()
if key.startswith('api/') and key not in ('api/BACKEND', 'api/FRONTEND')},
'collected_at': iso(),
}
def api_stats():
result = {}
for item in containers('api'):
raw = run(['docker', 'exec', item['container_id'], 'wget', '-qO-',
'http://127.0.0.1:9090/internal/stats'], check=False).stdout
try:
result[item['hostname']] = json.loads(raw)
except ValueError:
result[item['hostname']] = {'error': 'stats unavailable'}
return result
def snapshot():
started = time.monotonic()
data = {
'collected_at': iso(),
'cgroups': cgroup_all(),
'db': db_snapshot(),
'haproxy': haproxy_snapshot(),
'api': api_stats(),
'containers': {service: containers(service) for service in SERVICES},
}
data['collection_seconds'] = round(time.monotonic() - started, 3)
return data
def wait_ready(timeout=90):
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
result = run(['curl', '-fsS', '-o', '/dev/null', BASE_URL + '/health/ready'], check=False)
if result.returncode == 0:
return True
time.sleep(0.25)
return False
def wait_api_running(expected, timeout=90):
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
items = containers('api')
if len(items) == expected and all(item['state'] == 'running' for item in items):
healthy = True
for item in items:
status = run(['docker', 'inspect', '-f', '{{if .State.Health}}{{.State.Health.Status}}{{end}}',
item['container_id']]).stdout.strip()
if status not in ('healthy',):
healthy = False
break
if healthy:
return items
time.sleep(0.25)
raise RuntimeError('API replicas did not become healthy')
def set_stack_profile(image, revision, replicas, api_cpu, api_mem, gomemlimit,
postgres_cpu='0.6', postgres_mem='512M', valkey_cpu='0.15',
valkey_mem='128M', lb_cpu='0.1', lb_mem='64M', recreate_state=False):
env_extra = {
'API_IMAGE': image,
'GIT_REVISION': revision,
'API_REPLICAS': str(replicas),
'API_CPU_LIMIT': str(api_cpu),
'API_MEM_LIMIT': api_mem,
'GOMEMLIMIT': gomemlimit,
'POSTGRES_CPU_LIMIT': postgres_cpu,
'POSTGRES_MEM_LIMIT': postgres_mem,
'VALKEY_CPU_LIMIT': valkey_cpu,
'VALKEY_MEM_LIMIT': valkey_mem,
'LB_CPU_LIMIT': lb_cpu,
'LB_MEM_LIMIT': lb_mem,
}
if recreate_state:
compose('up', '-d', '--no-deps', '--force-recreate', 'postgres', 'valkey', 'lb', env_extra=env_extra)
compose('up', '-d', '--no-deps', '--force-recreate', 'api', env_extra=env_extra)
wait_api_running(replicas)
if not wait_ready(120):
raise RuntimeError('LB did not become ready')
return env_extra
def delta(before, after):
"""Exact deltas for monotonic counters; elapsed is from snapshot times."""
def cg(snapshot_data):
return snapshot_data['cgroups']
result = {'api': {}, 'postgres': {}, 'valkey': {}, 'lb': {}}
for container_id, item in after['cgroups'].items():
previous = cg(before).get(container_id)
if not previous:
continue
current_values = item['cgroup']
old_values = previous['cgroup']
change = {}
for key in ('usage_usec', 'user_usec', 'system_usec', 'nr_periods', 'nr_throttled', 'throttled_usec'):
change[key] = current_values.get(key, 0) - old_values.get(key, 0)
change['memory_current_bytes_end'] = current_values.get('memory_current_bytes')
change['memory_max'] = current_values.get('memory_max')
result[item['service']][container_id] = change
db_before = before['db']; db_after = after['db']
result['db'] = {
'xact_commit': db_after['database']['xact_commit'] - db_before['database']['xact_commit'],
'xact_rollback': db_after['database']['xact_rollback'] - db_before['database']['xact_rollback'],
'blks_read': db_after['database']['blks_read'] - db_before['database']['blks_read'],
'blks_hit': db_after['database']['blks_hit'] - db_before['database']['blks_hit'],
'tup_inserted': db_after['database']['tup_inserted'] - db_before['database']['tup_inserted'],
'tup_returned': db_after['database']['tup_returned'] - db_before['database']['tup_returned'],
'temp_bytes': db_after['database']['temp_bytes'] - db_before['database']['temp_bytes'],
'deadlocks': db_after['database']['deadlocks'] - db_before['database']['deadlocks'],
'activity_after': db_after['total'],
'active_after': db_after['active'],
'active_waiting_after': db_after['active_waiting'],
'idle_in_transaction_after': db_after['idle_in_transaction'],
'settings': db_after['settings'],
'datasets_after': db_after['datasets'],
}
lb_before = before['haproxy']; lb_after = after['haproxy']
def number(row, key):
try:
return int(float(row.get(key) or 0))
except ValueError:
return 0
result['lb'] = {
'req_tot_delta': number(lb_after['public'], 'req_tot') - number(lb_before['public'], 'req_tot'),
'hrsp_5xx_delta': number(lb_after['public'], 'hrsp_5xx') - number(lb_before['public'], 'hrsp_5xx'),
'hrsp_4xx_delta': number(lb_after['public'], 'hrsp_4xx') - number(lb_before['public'], 'hrsp_4xx'),
'econ_delta': number(lb_after['backend'], 'econ') - number(lb_before['backend'], 'econ'),
'eresp_delta': number(lb_after['backend'], 'eresp') - number(lb_before['backend'], 'eresp'),
'qmax_after': number(lb_after['public'], 'qmax'),
'qcur_after': number(lb_after['public'], 'qcur'),
'rtime_ms_after': number(lb_after['backend'], 'rtime'),
'status_after': lb_after['backend'].get('status'),
}
result['api_pool'] = {}
for instance, current in after['api'].items():
previous = before['api'].get(instance, {})
pool_now = current.get('pool', {})
pool_before = previous.get('pool', {})
result['api_pool'][instance] = {
'max_conns': pool_now.get('max_conns'),
'empty_acquire_delta': pool_now.get('empty_acquire_count', 0) - pool_before.get('empty_acquire_count', 0),
'canceled_acquire_delta': pool_now.get('canceled_acquire_count', 0) - pool_before.get('canceled_acquire_count', 0),
'acquire_delta': pool_now.get('acquire_count', 0) - pool_before.get('acquire_count', 0),
'acquire_ms_delta': pool_now.get('acquire_duration_ms_total', 0) - pool_before.get('acquire_duration_ms_total', 0),
'total_conns_after': pool_now.get('total_conns'),
'acquired_conns_after': pool_now.get('acquired_conns'),
'messages_created_delta': (current.get('messages', {}).get('created', 0) -
previous.get('messages', {}).get('created', 0)),
'messages_replayed_delta': (current.get('messages', {}).get('replayed', 0) -
previous.get('messages', {}).get('replayed', 0)),
'messages_conflicts_delta': (current.get('messages', {}).get('conflicts', 0) -
previous.get('messages', {}).get('conflicts', 0)),
}
return result
def summarize_run(label, config, before, after, elapsed_seconds, load):
change = delta(before, after)
api_cpu = 0.0
api_throttled = 0.0
api_limit = 0.0
for item in after['containers']['api']:
values = change['api'].get(item['container_id'], {})
api_cpu += values.get('usage_usec', 0) / 1e6
api_throttled += values.get('throttled_usec', 0) / 1e6
api_limit += item['cpu_limit_nano'] / 1e9
postgres_values = next(iter(change['postgres'].values()), {})
valkey_values = next(iter(change['valkey'].values()), {})
lb_values = next(iter(change['lb'].values()), {})
postgres_limit = next((item['cpu_limit_nano'] / 1e9 for item in after['containers']['postgres']), 0)
lb_limit = next((item['cpu_limit_nano'] / 1e9 for item in after['containers']['lb']), 0)
valkey_limit = next((item['cpu_limit_nano'] / 1e9 for item in after['containers']['valkey']), 0)
total_api_cpu_used = api_cpu / elapsed_seconds
pool_waits = sum(value.get('empty_acquire_delta', 0) for value in change['api_pool'].values())
pool_acquires = sum(value.get('acquire_delta', 0) for value in change['api_pool'].values())
pool_acquire_ms = sum(value.get('acquire_ms_delta', 0) for value in change['api_pool'].values())
db = change['db']
lb = change['lb']
commits = db['xact_commit']
return {
'label': label,
'config': config,
'measured_seconds': round(elapsed_seconds, 3),
'loadgen': load,
'resource': {
'api_used_cores': round(total_api_cpu_used, 4),
'api_limit_cores': round(api_limit, 4),
'api_utilization': round(total_api_cpu_used / api_limit, 4) if api_limit else None,
'api_throttled_seconds': round(api_throttled, 4),
'db_used_cores': round(postgres_values.get('usage_usec', 0) / 1e6 / elapsed_seconds, 4),
'db_limit_cores': round(postgres_limit, 4),
'db_utilization': round(postgres_values.get('usage_usec', 0) / 1e6 / elapsed_seconds / postgres_limit, 4) if postgres_limit else None,
'db_throttled_seconds': round(postgres_values.get('throttled_usec', 0) / 1e6, 4),
'db_throttled_periods': postgres_values.get('nr_throttled', 0),
'valkey_used_cores': round(valkey_values.get('usage_usec', 0) / 1e6 / elapsed_seconds, 4),
'valkey_limit_cores': round(valkey_limit, 4),
'lb_used_cores': round(lb_values.get('usage_usec', 0) / 1e6 / elapsed_seconds, 4),
'lb_limit_cores': round(lb_limit, 4),
'api_cgroup_memory_end_bytes': [value.get('memory_current_bytes_end') for value in change['api'].values()],
'postgres_cgroup_memory_end_bytes': postgres_values.get('memory_current_bytes_end'),
'valkey_cgroup_memory_end_bytes': valkey_values.get('memory_current_bytes_end'),
'lb_cgroup_memory_end_bytes': lb_values.get('memory_current_bytes_end'),
},
'postgres': {
'commits_delta': commits,
'commits_per_second': round(commits / elapsed_seconds, 3),
'rollbacks_delta': db['xact_rollback'],
'buffer_hit_ratio': round(db['blks_hit'] / (db['blks_hit'] + db['blks_read']), 6) if (db['blks_hit'] + db['blks_read']) else None,
'tuples_inserted_delta': db['tup_inserted'],
'temp_bytes_delta': db['temp_bytes'],
'deadlocks_delta': db['deadlocks'],
'connections_after': db['activity_after'],
'active_after': db['active_after'],
'active_waiting_after': db['active_waiting_after'],
'idle_in_transaction_after': db['idle_in_transaction_after'],
'max_connections': db['settings'].get('max_connections'),
'datasets_after': db['datasets_after'],
'pool_waits_delta': pool_waits,
'pool_acquires_delta': pool_acquires,
'pool_acquire_ms_delta': pool_acquire_ms,
'pool_waits_per_acquire': round(pool_waits / pool_acquires, 6) if pool_acquires else 0,
},
'lb': lb,
'snapshot_before_at': before['collected_at'],
'snapshot_after_at': after['collected_at'],
}
def median(values):
values = [value for value in values if value is not None]
return round(statistics.median(values), 4) if values else None
def run_loadgen(binary, output, duration, warmup, concurrency, note, extra=None):
command = [str(binary), '-base-url', BASE_URL,
'-duration', '%ds' % duration, '-warmup', '%ds' % warmup,
'-concurrency', str(concurrency), '-output', str(output), '-note', note]
command.extend(extra or [])
result = run(command, check=False)
if not Path(output).exists():
raise RuntimeError('loadgen failed: ' + (result.stderr or result.stdout)[-800:])
return json.loads(Path(output).read_text())
def build_metadata(image):
docker_version = run(['docker', 'version', '--format', '{{.Server.Version}}']).stdout.strip()
info = run(['docker', 'info', '--format', '{{.NCPU}} {{.MemTotal}} {{.OperatingSystem}}']).stdout.strip()
uname = run(['uname', '-m']).stdout.strip()
revision = run(['git', 'rev-parse', 'HEAD']).stdout.strip()
status = run(['git', 'status', '--porcelain']).stdout.strip()
return {
'revision': revision,
'worktree_dirty': bool(status),
'image': image,
'docker_server_version': docker_version,
'docker_vm': info,
'arch': uname,
'collected_at': iso(),
'note': 'One Docker VM (Colima); all API replicas share one kernel, DB and LB. Not independent nodes.',
}
+54
View File
@@ -0,0 +1,54 @@
#!/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 and valkey (volumes kept)"
postgres=$($compose ps -q postgres)
valkey=$($compose ps -q valkey)
$compose restart postgres valkey
wait_healthy "$postgres"
wait_healthy "$valkey"
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:8083/health/ready 2>/dev/null; then
echo "restart.sh: all lab3 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 lab3, 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"
+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:8083/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
+554
View File
@@ -0,0 +1,554 @@
#!/usr/bin/env python3
"""Own black-box tests for lab3. They complement, and never weaken, tests/smoke.py.
The suite assumes a running stack (make up) and creates only synthetic data.
It checks the contract expectations derived from contracts/openapi.json and
contracts/README.md: exact JSON keys, strict input validation, Bearer-only
business API, membership hiding as 404, keyset pagination, concurrent username
registration and concurrent message writes.
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'}, 'Message')
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': []})
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'}, '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 main():
args = arguments('Lab2 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_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: lab3 student black-box suite, %d checks' % CHECKS)
if __name__ == '__main__':
try:
main()
except AssertionError as exc:
print('FAIL:', exc)
raise SystemExit(1)
+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
}
+9
View File
@@ -0,0 +1,9 @@
language: go
go:
- 1.x
- tip
matrix:
allow_failures:
- go: tip
+22
View File
@@ -0,0 +1,22 @@
Copyright (c) 2019 Jack Christensen
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.
+8
View File
@@ -0,0 +1,8 @@
[![](https://godoc.org/github.com/jackc/pgpassfile?status.svg)](https://godoc.org/github.com/jackc/pgpassfile)
[![Build Status](https://travis-ci.org/jackc/pgpassfile.svg)](https://travis-ci.org/jackc/pgpassfile)
# pgpassfile
Package pgpassfile is a parser PostgreSQL .pgpass files.
Extracted and rewritten from original implementation in https://github.com/jackc/pgx.
+110
View File
@@ -0,0 +1,110 @@
// Package pgpassfile is a parser PostgreSQL .pgpass files.
package pgpassfile
import (
"bufio"
"io"
"os"
"regexp"
"strings"
)
// Entry represents a line in a PG passfile.
type Entry struct {
Hostname string
Port string
Database string
Username string
Password string
}
// Passfile is the in memory data structure representing a PG passfile.
type Passfile struct {
Entries []*Entry
}
// ReadPassfile reads the file at path and parses it into a Passfile.
func ReadPassfile(path string) (*Passfile, error) {
f, err := os.Open(path)
if err != nil {
return nil, err
}
defer f.Close()
return ParsePassfile(f)
}
// ParsePassfile reads r and parses it into a Passfile.
func ParsePassfile(r io.Reader) (*Passfile, error) {
passfile := &Passfile{}
scanner := bufio.NewScanner(r)
for scanner.Scan() {
entry := parseLine(scanner.Text())
if entry != nil {
passfile.Entries = append(passfile.Entries, entry)
}
}
return passfile, scanner.Err()
}
// Match (not colons or escaped colon or escaped backslash)+. Essentially gives a split on unescaped
// colon.
var colonSplitterRegexp = regexp.MustCompile("(([^:]|(\\:)))+")
// var colonSplitterRegexp = regexp.MustCompile("((?:[^:]|(?:\\:)|(?:\\\\))+)")
// parseLine parses a line into an *Entry. It returns nil on comment lines or any other unparsable
// line.
func parseLine(line string) *Entry {
const (
tmpBackslash = "\r"
tmpColon = "\n"
)
line = strings.TrimSpace(line)
if strings.HasPrefix(line, "#") {
return nil
}
line = strings.Replace(line, `\\`, tmpBackslash, -1)
line = strings.Replace(line, `\:`, tmpColon, -1)
parts := strings.Split(line, ":")
if len(parts) != 5 {
return nil
}
// Unescape escaped colons and backslashes
for i := range parts {
parts[i] = strings.Replace(parts[i], tmpBackslash, `\`, -1)
parts[i] = strings.Replace(parts[i], tmpColon, `:`, -1)
}
return &Entry{
Hostname: parts[0],
Port: parts[1],
Database: parts[2],
Username: parts[3],
Password: parts[4],
}
}
// FindPassword finds the password for the provided hostname, port, database, and username. For a
// Unix domain socket hostname must be set to "localhost". An empty string will be returned if no
// match is found.
//
// See https://www.postgresql.org/docs/current/libpq-pgpass.html for more password file information.
func (pf *Passfile) FindPassword(hostname, port, database, username string) (password string) {
for _, e := range pf.Entries {
if (e.Hostname == "*" || e.Hostname == hostname) &&
(e.Port == "*" || e.Port == port) &&
(e.Database == "*" || e.Database == database) &&
(e.Username == "*" || e.Username == username) {
return e.Password
}
}
return ""
}
+22
View File
@@ -0,0 +1,22 @@
Copyright (c) 2020 Jack Christensen
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.
+7
View File
@@ -0,0 +1,7 @@
[![Go Reference](https://pkg.go.dev/badge/github.com/jackc/pgservicefile.svg)](https://pkg.go.dev/github.com/jackc/pgservicefile)
[![Build Status](https://github.com/jackc/pgservicefile/actions/workflows/ci.yml/badge.svg)](https://github.com/jackc/pgservicefile/actions/workflows/ci.yml)
# pgservicefile
Package pgservicefile is a parser for PostgreSQL service files (e.g. `.pg_service.conf`).
+81
View File
@@ -0,0 +1,81 @@
// Package pgservicefile is a parser for PostgreSQL service files (e.g. .pg_service.conf).
package pgservicefile
import (
"bufio"
"errors"
"fmt"
"io"
"os"
"strings"
)
type Service struct {
Name string
Settings map[string]string
}
type Servicefile struct {
Services []*Service
servicesByName map[string]*Service
}
// GetService returns the named service.
func (sf *Servicefile) GetService(name string) (*Service, error) {
service, present := sf.servicesByName[name]
if !present {
return nil, errors.New("not found")
}
return service, nil
}
// ReadServicefile reads the file at path and parses it into a Servicefile.
func ReadServicefile(path string) (*Servicefile, error) {
f, err := os.Open(path)
if err != nil {
return nil, err
}
defer f.Close()
return ParseServicefile(f)
}
// ParseServicefile reads r and parses it into a Servicefile.
func ParseServicefile(r io.Reader) (*Servicefile, error) {
servicefile := &Servicefile{}
var service *Service
scanner := bufio.NewScanner(r)
lineNum := 0
for scanner.Scan() {
lineNum += 1
line := scanner.Text()
line = strings.TrimSpace(line)
if line == "" || strings.HasPrefix(line, "#") {
// ignore comments and empty lines
} else if strings.HasPrefix(line, "[") && strings.HasSuffix(line, "]") {
service = &Service{Name: line[1 : len(line)-1], Settings: make(map[string]string)}
servicefile.Services = append(servicefile.Services, service)
} else if service != nil {
parts := strings.SplitN(line, "=", 2)
if len(parts) != 2 {
return nil, fmt.Errorf("unable to parse line %d", lineNum)
}
key := strings.TrimSpace(parts[0])
value := strings.TrimSpace(parts[1])
service.Settings[key] = value
} else {
return nil, fmt.Errorf("line %d is not in a section", lineNum)
}
}
servicefile.servicesByName = make(map[string]*Service, len(servicefile.Services))
for _, service := range servicefile.Services {
servicefile.servicesByName[service.Name] = service
}
return servicefile, scanner.Err()
}
+27
View File
@@ -0,0 +1,27 @@
# Compiled Object files, Static and Dynamic libs (Shared Objects)
*.o
*.a
*.so
# Folders
_obj
_test
# Architecture specific extensions/prefixes
*.[568vq]
[568vq].out
*.cgo1.go
*.cgo2.c
_cgo_defun.c
_cgo_gotypes.go
_cgo_export.*
_testmain.go
*.exe
.envrc
/.testdb
.DS_Store
+434
View File
@@ -0,0 +1,434 @@
# 5.7.2 (December 21, 2024)
* Fix prepared statement already exists on batch prepare failure
* Add commit query to tx options (Lucas Hild)
* Fix pgtype.Timestamp json unmarshal (Shean de Montigny-Desautels)
* Add message body size limits in frontend and backend (zene)
* Add xid8 type
* Ensure planning encodes and scans cannot infinitely recurse
* Implement pgtype.UUID.String() (Konstantin Grachev)
* Switch from ExecParams to Exec in ValidateConnectTargetSessionAttrs functions (Alexander Rumyantsev)
* Update golang.org/x/crypto
# 5.7.1 (September 10, 2024)
* Fix data race in tracelog.TraceLog
* Update puddle to v2.2.2. This removes the import of nanotime via linkname.
* Update golang.org/x/crypto and golang.org/x/text
# 5.7.0 (September 7, 2024)
* Add support for sslrootcert=system (Yann Soubeyrand)
* Add LoadTypes to load multiple types in a single SQL query (Nick Farrell)
* Add XMLCodec supports encoding + scanning XML column type like json (nickcruess-soda)
* Add MultiTrace (Stepan Rabotkin)
* Add TraceLogConfig with customizable TimeKey (stringintech)
* pgx.ErrNoRows wraps sql.ErrNoRows to aid in database/sql compatibility with native pgx functions (merlin)
* Support scanning binary formatted uint32 into string / TextScanner (jennifersp)
* Fix interval encoding to allow 0s and avoid extra spaces (Carlos Pérez-Aradros Herce)
* Update pgservicefile - fixes panic when parsing invalid file
* Better error message when reading past end of batch
* Don't print url when url.Parse returns an error (Kevin Biju)
* Fix snake case name normalization collision in RowToStructByName with db tag (nolandseigler)
* Fix: Scan and encode types with underlying types of arrays
# 5.6.0 (May 25, 2024)
* Add StrictNamedArgs (Tomas Zahradnicek)
* Add support for macaddr8 type (Carlos Pérez-Aradros Herce)
* Add SeverityUnlocalized field to PgError / Notice
* Performance optimization of RowToStructByPos/Name (Zach Olstein)
* Allow customizing context canceled behavior for pgconn
* Add ScanLocation to pgtype.Timestamp[tz]Codec
* Add custom data to pgconn.PgConn
* Fix ResultReader.Read() to handle nil values
* Do not encode interval microseconds when they are 0 (Carlos Pérez-Aradros Herce)
* pgconn.SafeToRetry checks for wrapped errors (tjasko)
* Failed connection attempts include all errors
* Optimize LargeObject.Read (Mitar)
* Add tracing for connection acquire and release from pool (ngavinsir)
* Fix encode driver.Valuer not called when nil
* Add support for custom JSON marshal and unmarshal (Mitar)
* Use Go default keepalive for TCP connections (Hans-Joachim Kliemeck)
# 5.5.5 (March 9, 2024)
Use spaces instead of parentheses for SQL sanitization.
This still solves the problem of negative numbers creating a line comment, but this avoids breaking edge cases such as
`set foo to $1` where the substitution is taking place in a location where an arbitrary expression is not allowed.
# 5.5.4 (March 4, 2024)
Fix CVE-2024-27304
SQL injection can occur if an attacker can cause a single query or bind message to exceed 4 GB in size. An integer
overflow in the calculated message size can cause the one large message to be sent as multiple messages under the
attacker's control.
Thanks to Paul Gerste for reporting this issue.
* Fix behavior of CollectRows to return empty slice if Rows are empty (Felix)
* Fix simple protocol encoding of json.RawMessage
* Fix *Pipeline.getResults should close pipeline on error
* Fix panic in TryFindUnderlyingTypeScanPlan (David Kurman)
* Fix deallocation of invalidated cached statements in a transaction
* Handle invalid sslkey file
* Fix scan float4 into sql.Scanner
* Fix pgtype.Bits not making copy of data from read buffer. This would cause the data to be corrupted by future reads.
# 5.5.3 (February 3, 2024)
* Fix: prepared statement already exists
* Improve CopyFrom auto-conversion of text-ish values
* Add ltree type support (Florent Viel)
* Make some properties of Batch and QueuedQuery public (Pavlo Golub)
* Add AppendRows function (Edoardo Spadolini)
* Optimize convert UUID [16]byte to string (Kirill Malikov)
* Fix: LargeObject Read and Write of more than ~1GB at a time (Mitar)
# 5.5.2 (January 13, 2024)
* Allow NamedArgs to start with underscore
* pgproto3: Maximum message body length support (jeremy.spriet)
* Upgrade golang.org/x/crypto to v0.17.0
* Add snake_case support to RowToStructByName (Tikhon Fedulov)
* Fix: update description cache after exec prepare (James Hartig)
* Fix: pipeline checks if it is closed (James Hartig and Ryan Fowler)
* Fix: normalize timeout / context errors during TLS startup (Samuel Stauffer)
* Add OnPgError for easier centralized error handling (James Hartig)
# 5.5.1 (December 9, 2023)
* Add CopyFromFunc helper function. (robford)
* Add PgConn.Deallocate method that uses PostgreSQL protocol Close message.
* pgx uses new PgConn.Deallocate method. This allows deallocating statements to work in a failed transaction. This fixes a case where the prepared statement map could become invalid.
* Fix: Prefer driver.Valuer over json.Marshaler for json fields. (Jacopo)
* Fix: simple protocol SQL sanitizer previously panicked if an invalid $0 placeholder was used. This now returns an error instead. (maksymnevajdev)
* Add pgtype.Numeric.ScanScientific (Eshton Robateau)
# 5.5.0 (November 4, 2023)
* Add CollectExactlyOneRow. (Julien GOTTELAND)
* Add OpenDBFromPool to create *database/sql.DB from *pgxpool.Pool. (Lev Zakharov)
* Prepare can automatically choose statement name based on sql. This makes it easier to explicitly manage prepared statements.
* Statement cache now uses deterministic, stable statement names.
* database/sql prepared statement names are deterministically generated.
* Fix: SendBatch wasn't respecting context cancellation.
* Fix: Timeout error from pipeline is now normalized.
* Fix: database/sql encoding json.RawMessage to []byte.
* CancelRequest: Wait for the cancel request to be acknowledged by the server. This should improve PgBouncer compatibility. (Anton Levakin)
* stdlib: Use Ping instead of CheckConn in ResetSession
* Add json.Marshaler and json.Unmarshaler for Float4, Float8 (Kirill Mironov)
# 5.4.3 (August 5, 2023)
* Fix: QCharArrayOID was defined with the wrong OID (Christoph Engelbert)
* Fix: connect_timeout for sslmode=allow|prefer (smaher-edb)
* Fix: pgxpool: background health check cannot overflow pool
* Fix: Check for nil in defer when sending batch (recover properly from panic)
* Fix: json scan of non-string pointer to pointer
* Fix: zeronull.Timestamptz should use pgtype.Timestamptz
* Fix: NewConnsCount was not correctly counting connections created by Acquire directly. (James Hartig)
* RowTo(AddrOf)StructByPos ignores fields with "-" db tag
* Optimization: improve text format numeric parsing (horpto)
# 5.4.2 (July 11, 2023)
* Fix: RowScanner errors are fatal to Rows
* Fix: Enable failover efforts when pg_hba.conf disallows non-ssl connections (Brandon Kauffman)
* Hstore text codec internal improvements (Evan Jones)
* Fix: Stop timers for background reader when not in use. Fixes memory leak when closing connections (Adrian-Stefan Mares)
* Fix: Stop background reader as soon as possible.
* Add PgConn.SyncConn(). This combined with the above fix makes it safe to directly use the underlying net.Conn.
# 5.4.1 (June 18, 2023)
* Fix: concurrency bug with pgtypeDefaultMap and simple protocol (Lev Zakharov)
* Add TxOptions.BeginQuery to allow overriding the default BEGIN query
# 5.4.0 (June 14, 2023)
* Replace platform specific syscalls for non-blocking IO with more traditional goroutines and deadlines. This returns to the v4 approach with some additional improvements and fixes. This restores the ability to use a pgx.Conn over an ssh.Conn as well as other non-TCP or Unix socket connections. In addition, it is a significantly simpler implementation that is less likely to have cross platform issues.
* Optimization: The default type registrations are now shared among all connections. This saves about 100KB of memory per connection. `pgtype.Type` and `pgtype.Codec` values are now required to be immutable after registration. This was already necessary in most cases but wasn't documented until now. (Lev Zakharov)
* Fix: Ensure pgxpool.Pool.QueryRow.Scan releases connection on panic
* CancelRequest: don't try to read the reply (Nicola Murino)
* Fix: correctly handle bool type aliases (Wichert Akkerman)
* Fix: pgconn.CancelRequest: Fix unix sockets: don't use RemoteAddr()
* Fix: pgx.Conn memory leak with prepared statement caching (Evan Jones)
* Add BeforeClose to pgxpool.Pool (Evan Cordell)
* Fix: various hstore fixes and optimizations (Evan Jones)
* Fix: RowToStructByPos with embedded unexported struct
* Support different bool string representations (Lev Zakharov)
* Fix: error when using BatchResults.Exec on a select that returns an error after some rows.
* Fix: pipelineBatchResults.Exec() not returning error from ResultReader
* Fix: pipeline batch results not closing pipeline when error occurs while reading directly from results instead of using
a callback.
* Fix: scanning a table type into a struct
* Fix: scan array of record to pointer to slice of struct
* Fix: handle null for json (Cemre Mengu)
* Batch Query callback is called even when there is an error
* Add RowTo(AddrOf)StructByNameLax (Audi P. Risa P)
# 5.3.1 (February 27, 2023)
* Fix: Support v4 and v5 stdlib in same program (Tomáš Procházka)
* Fix: sql.Scanner not being used in certain cases
* Add text format jsonpath support
* Fix: fake non-blocking read adaptive wait time
# 5.3.0 (February 11, 2023)
* Fix: json values work with sql.Scanner
* Fixed / improved error messages (Mark Chambers and Yevgeny Pats)
* Fix: support scan into single dimensional arrays
* Fix: MaxConnLifetimeJitter setting actually jitter (Ben Weintraub)
* Fix: driver.Value representation of bytea should be []byte not string
* Fix: better handling of unregistered OIDs
* CopyFrom can use query cache to avoid extra round trip to get OIDs (Alejandro Do Nascimento Mora)
* Fix: encode to json ignoring driver.Valuer
* Support sql.Scanner on renamed base type
* Fix: pgtype.Numeric text encoding of negative numbers (Mark Chambers)
* Fix: connect with multiple hostnames when one can't be resolved
* Upgrade puddle to remove dependency on uber/atomic and fix alignment issue on 32-bit platform
* Fix: scanning json column into **string
* Multiple reductions in memory allocations
* Fake non-blocking read adapts its max wait time
* Improve CopyFrom performance and reduce memory usage
* Fix: encode []any to array
* Fix: LoadType for composite with dropped attributes (Felix Röhrich)
* Support v4 and v5 stdlib in same program
* Fix: text format array decoding with string of "NULL"
* Prefer binary format for arrays
# 5.2.0 (December 5, 2022)
* `tracelog.TraceLog` implements the pgx.PrepareTracer interface. (Vitalii Solodilov)
* Optimize creating begin transaction SQL string (Petr Evdokimov and ksco)
* `Conn.LoadType` supports range and multirange types (Vitalii Solodilov)
* Fix scan `uint` and `uint64` `ScanNumeric`. This resolves a PostgreSQL `numeric` being incorrectly scanned into `uint` and `uint64`.
# 5.1.1 (November 17, 2022)
* Fix simple query sanitizer where query text contains a Unicode replacement character.
* Remove erroneous `name` argument from `DeallocateAll()`. Technically, this is a breaking change, but given that method was only added 5 days ago this change was accepted. (Bodo Kaiser)
# 5.1.0 (November 12, 2022)
* Update puddle to v2.1.2. This resolves a race condition and a deadlock in pgxpool.
* `QueryRewriter.RewriteQuery` now returns an error. Technically, this is a breaking change for any external implementers, but given the minimal likelihood that there are actually any external implementers this change was accepted.
* Expose `GetSSLPassword` support to pgx.
* Fix encode `ErrorResponse` unknown field handling. This would only affect pgproto3 being used directly as a proxy with a non-PostgreSQL server that included additional error fields.
* Fix date text format encoding with 5 digit years.
* Fix date values passed to a `sql.Scanner` as `string` instead of `time.Time`.
* DateCodec.DecodeValue can return `pgtype.InfinityModifier` instead of `string` for infinite values. This now matches the behavior of the timestamp types.
* Add domain type support to `Conn.LoadType()`.
* Add `RowToStructByName` and `RowToAddrOfStructByName`. (Pavlo Golub)
* Add `Conn.DeallocateAll()` to clear all prepared statements including the statement cache. (Bodo Kaiser)
# 5.0.4 (October 24, 2022)
* Fix: CollectOneRow prefers PostgreSQL error over pgx.ErrorNoRows
* Fix: some reflect Kind checks to first check for nil
* Bump golang.org/x/text dependency to placate snyk
* Fix: RowToStructByPos on structs with multiple anonymous sub-structs (Baptiste Fontaine)
* Fix: Exec checks if tx is closed
# 5.0.3 (October 14, 2022)
* Fix `driver.Valuer` handling edge cases that could cause infinite loop or crash
# v5.0.2 (October 8, 2022)
* Fix date encoding in text format to always use 2 digits for month and day
* Prefer driver.Valuer over wrap plans when encoding
* Fix scan to pointer to pointer to renamed type
* Allow scanning NULL even if PG and Go types are incompatible
# v5.0.1 (September 24, 2022)
* Fix 32-bit atomic usage
* Add MarshalJSON for Float8 (yogipristiawan)
* Add `[` and `]` to text encoding of `Lseg`
* Fix sqlScannerWrapper NULL handling
# v5.0.0 (September 17, 2022)
## Merged Packages
`github.com/jackc/pgtype`, `github.com/jackc/pgconn`, and `github.com/jackc/pgproto3` are now included in the main
`github.com/jackc/pgx` repository. Previously there was confusion as to where issues should be reported, additional
release work due to releasing multiple packages, and less clear changelogs.
## pgconn
`CommandTag` is now an opaque type instead of directly exposing an underlying `[]byte`.
The return value `ResultReader.Values()` is no longer safe to retain a reference to after a subsequent call to `NextRow()` or `Close()`.
`Trace()` method adds low level message tracing similar to the `PQtrace` function in `libpq`.
pgconn now uses non-blocking IO. This is a significant internal restructuring, but it should not cause any visible changes on its own. However, it is important in implementing other new features.
`CheckConn()` checks a connection's liveness by doing a non-blocking read. This can be used to detect database restarts or network interruptions without executing a query or a ping.
pgconn now supports pipeline mode.
`*PgConn.ReceiveResults` removed. Use pipeline mode instead.
`Timeout()` no longer considers `context.Canceled` as a timeout error. `context.DeadlineExceeded` still is considered a timeout error.
## pgxpool
`Connect` and `ConnectConfig` have been renamed to `New` and `NewWithConfig` respectively. The `LazyConnect` option has been removed. Pools always lazily connect.
## pgtype
The `pgtype` package has been significantly changed.
### NULL Representation
Previously, types had a `Status` field that could be `Undefined`, `Null`, or `Present`. This has been changed to a
`Valid` `bool` field to harmonize with how `database/sql` represents `NULL` and to make the zero value useable.
Previously, a type that implemented `driver.Valuer` would have the `Value` method called even on a nil pointer. All nils
whether typed or untyped now represent `NULL`.
### Codec and Value Split
Previously, the type system combined decoding and encoding values with the value types. e.g. Type `Int8` both handled
encoding and decoding the PostgreSQL representation and acted as a value object. This caused some difficulties when
there was not an exact 1 to 1 relationship between the Go types and the PostgreSQL types For example, scanning a
PostgreSQL binary `numeric` into a Go `float64` was awkward (see https://github.com/jackc/pgtype/issues/147). This
concepts have been separated. A `Codec` only has responsibility for encoding and decoding values. Value types are
generally defined by implementing an interface that a particular `Codec` understands (e.g. `PointScanner` and
`PointValuer` for the PostgreSQL `point` type).
### Array Types
All array types are now handled by `ArrayCodec` instead of using code generation for each new array type. This also
means that less common array types such as `point[]` are now supported. `Array[T]` supports PostgreSQL multi-dimensional
arrays.
### Composite Types
Composite types must be registered before use. `CompositeFields` may still be used to construct and destruct composite
values, but any type may now implement `CompositeIndexGetter` and `CompositeIndexScanner` to be used as a composite.
### Range Types
Range types are now handled with types `RangeCodec` and `Range[T]`. This allows additional user defined range types to
easily be handled. Multirange types are handled similarly with `MultirangeCodec` and `Multirange[T]`.
### pgxtype
`LoadDataType` moved to `*Conn` as `LoadType`.
### Bytea
The `Bytea` and `GenericBinary` types have been replaced. Use the following instead:
* `[]byte` - For normal usage directly use `[]byte`.
* `DriverBytes` - Uses driver memory only available until next database method call. Avoids a copy and an allocation.
* `PreallocBytes` - Uses preallocated byte slice to avoid an allocation.
* `UndecodedBytes` - Avoids any decoding. Allows working with raw bytes.
### Dropped lib/pq Support
`pgtype` previously supported and was tested against [lib/pq](https://github.com/lib/pq). While it will continue to work
in most cases this is no longer supported.
### database/sql Scan
Previously, most `Scan` implementations would convert `[]byte` to `string` automatically to decode a text value. Now
only `string` is handled. This is to allow the possibility of future binary support in `database/sql` mode by
considering `[]byte` to be binary format and `string` text format. This change should have no effect for any use with
`pgx`. The previous behavior was only necessary for `lib/pq` compatibility.
Added `*Map.SQLScanner` to create a `sql.Scanner` for types such as `[]int32` and `Range[T]` that do not implement
`sql.Scanner` directly.
### Number Type Fields Include Bit size
`Int2`, `Int4`, `Int8`, `Float4`, `Float8`, and `Uint32` fields now include bit size. e.g. `Int` is renamed to `Int64`.
This matches the convention set by `database/sql`. In addition, for comparable types like `pgtype.Int8` and
`sql.NullInt64` the structures are identical. This means they can be directly converted one to another.
### 3rd Party Type Integrations
* Extracted integrations with https://github.com/shopspring/decimal and https://github.com/gofrs/uuid to
https://github.com/jackc/pgx-shopspring-decimal and https://github.com/jackc/pgx-gofrs-uuid respectively. This trims
the pgx dependency tree.
### Other Changes
* `Bit` and `Varbit` are both replaced by the `Bits` type.
* `CID`, `OID`, `OIDValue`, and `XID` are replaced by the `Uint32` type.
* `Hstore` is now defined as `map[string]*string`.
* `JSON` and `JSONB` types removed. Use `[]byte` or `string` directly.
* `QChar` type removed. Use `rune` or `byte` directly.
* `Inet` and `Cidr` types removed. Use `netip.Addr` and `netip.Prefix` directly. These types are more memory efficient than the previous `net.IPNet`.
* `Macaddr` type removed. Use `net.HardwareAddr` directly.
* Renamed `pgtype.ConnInfo` to `pgtype.Map`.
* Renamed `pgtype.DataType` to `pgtype.Type`.
* Renamed `pgtype.None` to `pgtype.Finite`.
* `RegisterType` now accepts a `*Type` instead of `Type`.
* Assorted array helper methods and types made private.
## stdlib
* Removed `AcquireConn` and `ReleaseConn` as that functionality has been built in since Go 1.13.
## Reduced Memory Usage by Reusing Read Buffers
Previously, the connection read buffer would allocate large chunks of memory and never reuse them. This allowed
transferring ownership to anything such as scanned values without incurring an additional allocation and memory copy.
However, this came at the cost of overall increased memory allocation size. But worse it was also possible to pin large
chunks of memory by retaining a reference to a small value that originally came directly from the read buffer. Now
ownership remains with the read buffer and anything needing to retain a value must make a copy.
## Query Execution Modes
Control over automatic prepared statement caching and simple protocol use are now combined into query execution mode.
See documentation for `QueryExecMode`.
## QueryRewriter Interface and NamedArgs
pgx now supports named arguments with the `NamedArgs` type. This is implemented via the new `QueryRewriter` interface which
allows arbitrary rewriting of query SQL and arguments.
## RowScanner Interface
The `RowScanner` interface allows a single argument to Rows.Scan to scan the entire row.
## Rows Result Helpers
* `CollectRows` and `RowTo*` functions simplify collecting results into a slice.
* `CollectOneRow` collects one row using `RowTo*` functions.
* `ForEachRow` simplifies scanning each row and executing code using the scanned values. `ForEachRow` replaces `QueryFunc`.
## Tx Helpers
Rather than every type that implemented `Begin` or `BeginTx` methods also needing to implement `BeginFunc` and
`BeginTxFunc` these methods have been converted to functions that take a db that implements `Begin` or `BeginTx`.
## Improved Batch Query Ergonomics
Previously, the code for building a batch went in one place before the call to `SendBatch`, and the code for reading the
results went in one place after the call to `SendBatch`. This could make it difficult to match up the query and the code
to handle the results. Now `Queue` returns a `QueuedQuery` which has methods `Query`, `QueryRow`, and `Exec` which can
be used to register a callback function that will handle the result. Callback functions are called automatically when
`BatchResults.Close` is called.
## SendBatch Uses Pipeline Mode When Appropriate
Previously, a batch with 10 unique parameterized statements executed 100 times would entail 11 network round trips. 1
for each prepare / describe and 1 for executing them all. Now pipeline mode is used to prepare / describe all statements
in a single network round trip. So it would only take 2 round trips.
## Tracing and Logging
Internal logging support has been replaced with tracing hooks. This allows custom tracing integration with tools like OpenTelemetry. Package tracelog provides an adapter for pgx v4 loggers to act as a tracer.
All integrations with 3rd party loggers have been extracted to separate repositories. This trims the pgx dependency
tree.
+121
View File
@@ -0,0 +1,121 @@
# Contributing
## Discuss Significant Changes
Before you invest a significant amount of time on a change, please create a discussion or issue describing your
proposal. This will help to ensure your proposed change has a reasonable chance of being merged.
## Avoid Dependencies
Adding a dependency is a big deal. While on occasion a new dependency may be accepted, the default answer to any change
that adds a dependency is no.
## Development Environment Setup
pgx tests naturally require a PostgreSQL database. It will connect to the database specified in the `PGX_TEST_DATABASE`
environment variable. The `PGX_TEST_DATABASE` environment variable can either be a URL or key-value pairs. In addition,
the standard `PG*` environment variables will be respected. Consider using [direnv](https://github.com/direnv/direnv) to
simplify environment variable handling.
### Using an Existing PostgreSQL Cluster
If you already have a PostgreSQL development server this is the quickest way to start and run the majority of the pgx
test suite. Some tests will be skipped that require server configuration changes (e.g. those testing different
authentication methods).
Create and setup a test database:
```
export PGDATABASE=pgx_test
createdb
psql -c 'create extension hstore;'
psql -c 'create extension ltree;'
psql -c 'create domain uint64 as numeric(20,0);'
```
Ensure a `postgres` user exists. This happens by default in normal PostgreSQL installs, but some installation methods
such as Homebrew do not.
```
createuser -s postgres
```
Ensure your `PGX_TEST_DATABASE` environment variable points to the database you just created and run the tests.
```
export PGX_TEST_DATABASE="host=/private/tmp database=pgx_test"
go test ./...
```
This will run the vast majority of the tests, but some tests will be skipped (e.g. those testing different connection methods).
### Creating a New PostgreSQL Cluster Exclusively for Testing
The following environment variables need to be set both for initial setup and whenever the tests are run. (direnv is
highly recommended). Depending on your platform, you may need to change the host for `PGX_TEST_UNIX_SOCKET_CONN_STRING`.
```
export PGPORT=5015
export PGUSER=postgres
export PGDATABASE=pgx_test
export POSTGRESQL_DATA_DIR=postgresql
export PGX_TEST_DATABASE="host=127.0.0.1 database=pgx_test user=pgx_md5 password=secret"
export PGX_TEST_UNIX_SOCKET_CONN_STRING="host=/private/tmp database=pgx_test"
export PGX_TEST_TCP_CONN_STRING="host=127.0.0.1 database=pgx_test user=pgx_md5 password=secret"
export PGX_TEST_SCRAM_PASSWORD_CONN_STRING="host=127.0.0.1 user=pgx_scram password=secret database=pgx_test"
export PGX_TEST_MD5_PASSWORD_CONN_STRING="host=127.0.0.1 database=pgx_test user=pgx_md5 password=secret"
export PGX_TEST_PLAIN_PASSWORD_CONN_STRING="host=127.0.0.1 user=pgx_pw password=secret"
export PGX_TEST_TLS_CONN_STRING="host=localhost user=pgx_ssl password=secret sslmode=verify-full sslrootcert=`pwd`/.testdb/ca.pem"
export PGX_SSL_PASSWORD=certpw
export PGX_TEST_TLS_CLIENT_CONN_STRING="host=localhost user=pgx_sslcert sslmode=verify-full sslrootcert=`pwd`/.testdb/ca.pem database=pgx_test sslcert=`pwd`/.testdb/pgx_sslcert.crt sslkey=`pwd`/.testdb/pgx_sslcert.key"
```
Create a new database cluster.
```
initdb --locale=en_US -E UTF-8 --username=postgres .testdb/$POSTGRESQL_DATA_DIR
echo "listen_addresses = '127.0.0.1'" >> .testdb/$POSTGRESQL_DATA_DIR/postgresql.conf
echo "port = $PGPORT" >> .testdb/$POSTGRESQL_DATA_DIR/postgresql.conf
cat testsetup/postgresql_ssl.conf >> .testdb/$POSTGRESQL_DATA_DIR/postgresql.conf
cp testsetup/pg_hba.conf .testdb/$POSTGRESQL_DATA_DIR/pg_hba.conf
cd .testdb
# Generate CA, server, and encrypted client certificates.
go run ../testsetup/generate_certs.go
# Copy certificates to server directory and set permissions.
cp ca.pem $POSTGRESQL_DATA_DIR/root.crt
cp localhost.key $POSTGRESQL_DATA_DIR/server.key
chmod 600 $POSTGRESQL_DATA_DIR/server.key
cp localhost.crt $POSTGRESQL_DATA_DIR/server.crt
cd ..
```
Start the new cluster. This will be necessary whenever you are running pgx tests.
```
postgres -D .testdb/$POSTGRESQL_DATA_DIR
```
Setup the test database in the new cluster.
```
createdb
psql --no-psqlrc -f testsetup/postgresql_setup.sql
```
### PgBouncer
There are tests specific for PgBouncer that will be executed if `PGX_TEST_PGBOUNCER_CONN_STRING` is set.
### Optional Tests
pgx supports multiple connection types and means of authentication. These tests are optional. They will only run if the
appropriate environment variables are set. In addition, there may be tests specific to particular PostgreSQL versions,
non-PostgreSQL servers (e.g. CockroachDB), or connection poolers (e.g. PgBouncer). `go test ./... -v | grep SKIP` to see
if any tests are being skipped.
+22
View File
@@ -0,0 +1,22 @@
Copyright (c) 2013-2021 Jack Christensen
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.
+174
View File
@@ -0,0 +1,174 @@
[![Go Reference](https://pkg.go.dev/badge/github.com/jackc/pgx/v5.svg)](https://pkg.go.dev/github.com/jackc/pgx/v5)
[![Build Status](https://github.com/jackc/pgx/actions/workflows/ci.yml/badge.svg)](https://github.com/jackc/pgx/actions/workflows/ci.yml)
# pgx - PostgreSQL Driver and Toolkit
pgx is a pure Go driver and toolkit for PostgreSQL.
The pgx driver is a low-level, high performance interface that exposes PostgreSQL-specific features such as `LISTEN` /
`NOTIFY` and `COPY`. It also includes an adapter for the standard `database/sql` interface.
The toolkit component is a related set of packages that implement PostgreSQL functionality such as parsing the wire protocol
and type mapping between PostgreSQL and Go. These underlying packages can be used to implement alternative drivers,
proxies, load balancers, logical replication clients, etc.
## Example Usage
```go
package main
import (
"context"
"fmt"
"os"
"github.com/jackc/pgx/v5"
)
func main() {
// urlExample := "postgres://username:password@localhost:5432/database_name"
conn, err := pgx.Connect(context.Background(), os.Getenv("DATABASE_URL"))
if err != nil {
fmt.Fprintf(os.Stderr, "Unable to connect to database: %v\n", err)
os.Exit(1)
}
defer conn.Close(context.Background())
var name string
var weight int64
err = conn.QueryRow(context.Background(), "select name, weight from widgets where id=$1", 42).Scan(&name, &weight)
if err != nil {
fmt.Fprintf(os.Stderr, "QueryRow failed: %v\n", err)
os.Exit(1)
}
fmt.Println(name, weight)
}
```
See the [getting started guide](https://github.com/jackc/pgx/wiki/Getting-started-with-pgx) for more information.
## Features
* Support for approximately 70 different PostgreSQL types
* Automatic statement preparation and caching
* Batch queries
* Single-round trip query mode
* Full TLS connection control
* Binary format support for custom types (allows for much quicker encoding/decoding)
* `COPY` protocol support for faster bulk data loads
* Tracing and logging support
* Connection pool with after-connect hook for arbitrary connection setup
* `LISTEN` / `NOTIFY`
* Conversion of PostgreSQL arrays to Go slice mappings for integers, floats, and strings
* `hstore` support
* `json` and `jsonb` support
* Maps `inet` and `cidr` PostgreSQL types to `netip.Addr` and `netip.Prefix`
* Large object support
* NULL mapping to pointer to pointer
* Supports `database/sql.Scanner` and `database/sql/driver.Valuer` interfaces for custom types
* Notice response handling
* Simulated nested transactions with savepoints
## Choosing Between the pgx and database/sql Interfaces
The pgx interface is faster. Many PostgreSQL specific features such as `LISTEN` / `NOTIFY` and `COPY` are not available
through the `database/sql` interface.
The pgx interface is recommended when:
1. The application only targets PostgreSQL.
2. No other libraries that require `database/sql` are in use.
It is also possible to use the `database/sql` interface and convert a connection to the lower-level pgx interface as needed.
## Testing
See [CONTRIBUTING.md](./CONTRIBUTING.md) for setup instructions.
## Architecture
See the presentation at Golang Estonia, [PGX Top to Bottom](https://www.youtube.com/watch?v=sXMSWhcHCf8) for a description of pgx architecture.
## Supported Go and PostgreSQL Versions
pgx supports the same versions of Go and PostgreSQL that are supported by their respective teams. For [Go](https://golang.org/doc/devel/release.html#policy) that is the two most recent major releases and for [PostgreSQL](https://www.postgresql.org/support/versioning/) the major releases in the last 5 years. This means pgx supports Go 1.21 and higher and PostgreSQL 12 and higher. pgx also is tested against the latest version of [CockroachDB](https://www.cockroachlabs.com/product/).
## Version Policy
pgx follows semantic versioning for the documented public API on stable releases. `v5` is the latest stable major version.
## PGX Family Libraries
### [github.com/jackc/pglogrepl](https://github.com/jackc/pglogrepl)
pglogrepl provides functionality to act as a client for PostgreSQL logical replication.
### [github.com/jackc/pgmock](https://github.com/jackc/pgmock)
pgmock offers the ability to create a server that mocks the PostgreSQL wire protocol. This is used internally to test pgx by purposely inducing unusual errors. pgproto3 and pgmock together provide most of the foundational tooling required to implement a PostgreSQL proxy or MitM (such as for a custom connection pooler).
### [github.com/jackc/tern](https://github.com/jackc/tern)
tern is a stand-alone SQL migration system.
### [github.com/jackc/pgerrcode](https://github.com/jackc/pgerrcode)
pgerrcode contains constants for the PostgreSQL error codes.
## Adapters for 3rd Party Types
* [github.com/jackc/pgx-gofrs-uuid](https://github.com/jackc/pgx-gofrs-uuid)
* [github.com/jackc/pgx-shopspring-decimal](https://github.com/jackc/pgx-shopspring-decimal)
* [github.com/twpayne/pgx-geos](https://github.com/twpayne/pgx-geos) ([PostGIS](https://postgis.net/) and [GEOS](https://libgeos.org/) via [go-geos](https://github.com/twpayne/go-geos))
* [github.com/vgarvardt/pgx-google-uuid](https://github.com/vgarvardt/pgx-google-uuid)
## Adapters for 3rd Party Tracers
* [github.com/jackhopner/pgx-xray-tracer](https://github.com/jackhopner/pgx-xray-tracer)
## Adapters for 3rd Party Loggers
These adapters can be used with the tracelog package.
* [github.com/jackc/pgx-go-kit-log](https://github.com/jackc/pgx-go-kit-log)
* [github.com/jackc/pgx-log15](https://github.com/jackc/pgx-log15)
* [github.com/jackc/pgx-logrus](https://github.com/jackc/pgx-logrus)
* [github.com/jackc/pgx-zap](https://github.com/jackc/pgx-zap)
* [github.com/jackc/pgx-zerolog](https://github.com/jackc/pgx-zerolog)
* [github.com/mcosta74/pgx-slog](https://github.com/mcosta74/pgx-slog)
* [github.com/kataras/pgx-golog](https://github.com/kataras/pgx-golog)
## 3rd Party Libraries with PGX Support
### [github.com/pashagolub/pgxmock](https://github.com/pashagolub/pgxmock)
pgxmock is a mock library implementing pgx interfaces.
pgxmock has one and only purpose - to simulate pgx behavior in tests, without needing a real database connection.
### [github.com/georgysavva/scany](https://github.com/georgysavva/scany)
Library for scanning data from a database into Go structs and more.
### [github.com/vingarcia/ksql](https://github.com/vingarcia/ksql)
A carefully designed SQL client for making using SQL easier,
more productive, and less error-prone on Golang.
### [github.com/otan/gopgkrb5](https://github.com/otan/gopgkrb5)
Adds GSSAPI / Kerberos authentication support.
### [github.com/wcamarao/pmx](https://github.com/wcamarao/pmx)
Explicit data mapping and scanning library for Go structs and slices.
### [github.com/stephenafamo/scan](https://github.com/stephenafamo/scan)
Type safe and flexible package for scanning database data into Go types.
Supports, structs, maps, slices and custom mapping functions.
### [github.com/z0ne-dev/mgx](https://github.com/z0ne-dev/mgx)
Code first migration library for native pgx (no database/sql abstraction).
+18
View File
@@ -0,0 +1,18 @@
require "erb"
rule '.go' => '.go.erb' do |task|
erb = ERB.new(File.read(task.source))
File.write(task.name, "// Do not edit. Generated from #{task.source}\n" + erb.result(binding))
sh "goimports", "-w", task.name
end
generated_code_files = [
"pgtype/int.go",
"pgtype/int_test.go",
"pgtype/integration_benchmark_test.go",
"pgtype/zeronull/int.go",
"pgtype/zeronull/int_test.go"
]
desc "Generate code"
task generate: generated_code_files
+443
View File
@@ -0,0 +1,443 @@
package pgx
import (
"context"
"errors"
"fmt"
"github.com/jackc/pgx/v5/pgconn"
)
// QueuedQuery is a query that has been queued for execution via a Batch.
type QueuedQuery struct {
SQL string
Arguments []any
Fn batchItemFunc
sd *pgconn.StatementDescription
}
type batchItemFunc func(br BatchResults) error
// Query sets fn to be called when the response to qq is received.
func (qq *QueuedQuery) Query(fn func(rows Rows) error) {
qq.Fn = func(br BatchResults) error {
rows, _ := br.Query()
defer rows.Close()
err := fn(rows)
if err != nil {
return err
}
rows.Close()
return rows.Err()
}
}
// Query sets fn to be called when the response to qq is received.
func (qq *QueuedQuery) QueryRow(fn func(row Row) error) {
qq.Fn = func(br BatchResults) error {
row := br.QueryRow()
return fn(row)
}
}
// Exec sets fn to be called when the response to qq is received.
func (qq *QueuedQuery) Exec(fn func(ct pgconn.CommandTag) error) {
qq.Fn = func(br BatchResults) error {
ct, err := br.Exec()
if err != nil {
return err
}
return fn(ct)
}
}
// Batch queries are a way of bundling multiple queries together to avoid
// unnecessary network round trips. A Batch must only be sent once.
type Batch struct {
QueuedQueries []*QueuedQuery
}
// Queue queues a query to batch b. query can be an SQL query or the name of a prepared statement. The only pgx option
// argument that is supported is QueryRewriter. Queries are executed using the connection's DefaultQueryExecMode.
//
// While query can contain multiple statements if the connection's DefaultQueryExecMode is QueryModeSimple, this should
// be avoided. QueuedQuery.Fn must not be set as it will only be called for the first query. That is, QueuedQuery.Query,
// QueuedQuery.QueryRow, and QueuedQuery.Exec must not be called. In addition, any error messages or tracing that
// include the current query may reference the wrong query.
func (b *Batch) Queue(query string, arguments ...any) *QueuedQuery {
qq := &QueuedQuery{
SQL: query,
Arguments: arguments,
}
b.QueuedQueries = append(b.QueuedQueries, qq)
return qq
}
// Len returns number of queries that have been queued so far.
func (b *Batch) Len() int {
return len(b.QueuedQueries)
}
type BatchResults interface {
// Exec reads the results from the next query in the batch as if the query has been sent with Conn.Exec. Prefer
// calling Exec on the QueuedQuery.
Exec() (pgconn.CommandTag, error)
// Query reads the results from the next query in the batch as if the query has been sent with Conn.Query. Prefer
// calling Query on the QueuedQuery.
Query() (Rows, error)
// QueryRow reads the results from the next query in the batch as if the query has been sent with Conn.QueryRow.
// Prefer calling QueryRow on the QueuedQuery.
QueryRow() Row
// Close closes the batch operation. All unread results are read and any callback functions registered with
// QueuedQuery.Query, QueuedQuery.QueryRow, or QueuedQuery.Exec will be called. If a callback function returns an
// error or the batch encounters an error subsequent callback functions will not be called.
//
// Close must be called before the underlying connection can be used again. Any error that occurred during a batch
// operation may have made it impossible to resyncronize the connection with the server. In this case the underlying
// connection will have been closed.
//
// Close is safe to call multiple times. If it returns an error subsequent calls will return the same error. Callback
// functions will not be rerun.
Close() error
}
type batchResults struct {
ctx context.Context
conn *Conn
mrr *pgconn.MultiResultReader
err error
b *Batch
qqIdx int
closed bool
endTraced bool
}
// Exec reads the results from the next query in the batch as if the query has been sent with Exec.
func (br *batchResults) Exec() (pgconn.CommandTag, error) {
if br.err != nil {
return pgconn.CommandTag{}, br.err
}
if br.closed {
return pgconn.CommandTag{}, fmt.Errorf("batch already closed")
}
query, arguments, _ := br.nextQueryAndArgs()
if !br.mrr.NextResult() {
err := br.mrr.Close()
if err == nil {
err = errors.New("no more results in batch")
}
if br.conn.batchTracer != nil {
br.conn.batchTracer.TraceBatchQuery(br.ctx, br.conn, TraceBatchQueryData{
SQL: query,
Args: arguments,
Err: err,
})
}
return pgconn.CommandTag{}, err
}
commandTag, err := br.mrr.ResultReader().Close()
if err != nil {
br.err = err
br.mrr.Close()
}
if br.conn.batchTracer != nil {
br.conn.batchTracer.TraceBatchQuery(br.ctx, br.conn, TraceBatchQueryData{
SQL: query,
Args: arguments,
CommandTag: commandTag,
Err: br.err,
})
}
return commandTag, br.err
}
// Query reads the results from the next query in the batch as if the query has been sent with Query.
func (br *batchResults) Query() (Rows, error) {
query, arguments, ok := br.nextQueryAndArgs()
if !ok {
query = "batch query"
}
if br.err != nil {
return &baseRows{err: br.err, closed: true}, br.err
}
if br.closed {
alreadyClosedErr := fmt.Errorf("batch already closed")
return &baseRows{err: alreadyClosedErr, closed: true}, alreadyClosedErr
}
rows := br.conn.getRows(br.ctx, query, arguments)
rows.batchTracer = br.conn.batchTracer
if !br.mrr.NextResult() {
rows.err = br.mrr.Close()
if rows.err == nil {
rows.err = errors.New("no more results in batch")
}
rows.closed = true
if br.conn.batchTracer != nil {
br.conn.batchTracer.TraceBatchQuery(br.ctx, br.conn, TraceBatchQueryData{
SQL: query,
Args: arguments,
Err: rows.err,
})
}
return rows, rows.err
}
rows.resultReader = br.mrr.ResultReader()
return rows, nil
}
// QueryRow reads the results from the next query in the batch as if the query has been sent with QueryRow.
func (br *batchResults) QueryRow() Row {
rows, _ := br.Query()
return (*connRow)(rows.(*baseRows))
}
// Close closes the batch operation. Any error that occurred during a batch operation may have made it impossible to
// resyncronize the connection with the server. In this case the underlying connection will have been closed.
func (br *batchResults) Close() error {
defer func() {
if !br.endTraced {
if br.conn != nil && br.conn.batchTracer != nil {
br.conn.batchTracer.TraceBatchEnd(br.ctx, br.conn, TraceBatchEndData{Err: br.err})
}
br.endTraced = true
}
}()
if br.err != nil {
return br.err
}
if br.closed {
return nil
}
// Read and run fn for all remaining items
for br.err == nil && !br.closed && br.b != nil && br.qqIdx < len(br.b.QueuedQueries) {
if br.b.QueuedQueries[br.qqIdx].Fn != nil {
err := br.b.QueuedQueries[br.qqIdx].Fn(br)
if err != nil {
br.err = err
}
} else {
br.Exec()
}
}
br.closed = true
err := br.mrr.Close()
if br.err == nil {
br.err = err
}
return br.err
}
func (br *batchResults) earlyError() error {
return br.err
}
func (br *batchResults) nextQueryAndArgs() (query string, args []any, ok bool) {
if br.b != nil && br.qqIdx < len(br.b.QueuedQueries) {
bi := br.b.QueuedQueries[br.qqIdx]
query = bi.SQL
args = bi.Arguments
ok = true
br.qqIdx++
}
return
}
type pipelineBatchResults struct {
ctx context.Context
conn *Conn
pipeline *pgconn.Pipeline
lastRows *baseRows
err error
b *Batch
qqIdx int
closed bool
endTraced bool
}
// Exec reads the results from the next query in the batch as if the query has been sent with Exec.
func (br *pipelineBatchResults) Exec() (pgconn.CommandTag, error) {
if br.err != nil {
return pgconn.CommandTag{}, br.err
}
if br.closed {
return pgconn.CommandTag{}, fmt.Errorf("batch already closed")
}
if br.lastRows != nil && br.lastRows.err != nil {
return pgconn.CommandTag{}, br.err
}
query, arguments, err := br.nextQueryAndArgs()
if err != nil {
return pgconn.CommandTag{}, err
}
results, err := br.pipeline.GetResults()
if err != nil {
br.err = err
return pgconn.CommandTag{}, br.err
}
var commandTag pgconn.CommandTag
switch results := results.(type) {
case *pgconn.ResultReader:
commandTag, br.err = results.Close()
default:
return pgconn.CommandTag{}, fmt.Errorf("unexpected pipeline result: %T", results)
}
if br.conn.batchTracer != nil {
br.conn.batchTracer.TraceBatchQuery(br.ctx, br.conn, TraceBatchQueryData{
SQL: query,
Args: arguments,
CommandTag: commandTag,
Err: br.err,
})
}
return commandTag, br.err
}
// Query reads the results from the next query in the batch as if the query has been sent with Query.
func (br *pipelineBatchResults) Query() (Rows, error) {
if br.err != nil {
return &baseRows{err: br.err, closed: true}, br.err
}
if br.closed {
alreadyClosedErr := fmt.Errorf("batch already closed")
return &baseRows{err: alreadyClosedErr, closed: true}, alreadyClosedErr
}
if br.lastRows != nil && br.lastRows.err != nil {
br.err = br.lastRows.err
return &baseRows{err: br.err, closed: true}, br.err
}
query, arguments, err := br.nextQueryAndArgs()
if err != nil {
return &baseRows{err: err, closed: true}, err
}
rows := br.conn.getRows(br.ctx, query, arguments)
rows.batchTracer = br.conn.batchTracer
br.lastRows = rows
results, err := br.pipeline.GetResults()
if err != nil {
br.err = err
rows.err = err
rows.closed = true
if br.conn.batchTracer != nil {
br.conn.batchTracer.TraceBatchQuery(br.ctx, br.conn, TraceBatchQueryData{
SQL: query,
Args: arguments,
Err: err,
})
}
} else {
switch results := results.(type) {
case *pgconn.ResultReader:
rows.resultReader = results
default:
err = fmt.Errorf("unexpected pipeline result: %T", results)
br.err = err
rows.err = err
rows.closed = true
}
}
return rows, rows.err
}
// QueryRow reads the results from the next query in the batch as if the query has been sent with QueryRow.
func (br *pipelineBatchResults) QueryRow() Row {
rows, _ := br.Query()
return (*connRow)(rows.(*baseRows))
}
// Close closes the batch operation. Any error that occurred during a batch operation may have made it impossible to
// resyncronize the connection with the server. In this case the underlying connection will have been closed.
func (br *pipelineBatchResults) Close() error {
defer func() {
if !br.endTraced {
if br.conn.batchTracer != nil {
br.conn.batchTracer.TraceBatchEnd(br.ctx, br.conn, TraceBatchEndData{Err: br.err})
}
br.endTraced = true
}
}()
if br.err == nil && br.lastRows != nil && br.lastRows.err != nil {
br.err = br.lastRows.err
return br.err
}
if br.closed {
return br.err
}
// Read and run fn for all remaining items
for br.err == nil && !br.closed && br.b != nil && br.qqIdx < len(br.b.QueuedQueries) {
if br.b.QueuedQueries[br.qqIdx].Fn != nil {
err := br.b.QueuedQueries[br.qqIdx].Fn(br)
if err != nil {
br.err = err
}
} else {
br.Exec()
}
}
br.closed = true
err := br.pipeline.Close()
if br.err == nil {
br.err = err
}
return br.err
}
func (br *pipelineBatchResults) earlyError() error {
return br.err
}
func (br *pipelineBatchResults) nextQueryAndArgs() (query string, args []any, err error) {
if br.b == nil {
return "", nil, errors.New("no reference to batch")
}
if br.qqIdx >= len(br.b.QueuedQueries) {
return "", nil, errors.New("no more results in batch")
}
bi := br.b.QueuedQueries[br.qqIdx]
br.qqIdx++
return bi.SQL, bi.Arguments, nil
}
+1444
View File
File diff suppressed because it is too large Load Diff
+276
View File
@@ -0,0 +1,276 @@
package pgx
import (
"bytes"
"context"
"fmt"
"io"
"github.com/jackc/pgx/v5/internal/pgio"
"github.com/jackc/pgx/v5/pgconn"
)
// CopyFromRows returns a CopyFromSource interface over the provided rows slice
// making it usable by *Conn.CopyFrom.
func CopyFromRows(rows [][]any) CopyFromSource {
return &copyFromRows{rows: rows, idx: -1}
}
type copyFromRows struct {
rows [][]any
idx int
}
func (ctr *copyFromRows) Next() bool {
ctr.idx++
return ctr.idx < len(ctr.rows)
}
func (ctr *copyFromRows) Values() ([]any, error) {
return ctr.rows[ctr.idx], nil
}
func (ctr *copyFromRows) Err() error {
return nil
}
// CopyFromSlice returns a CopyFromSource interface over a dynamic func
// making it usable by *Conn.CopyFrom.
func CopyFromSlice(length int, next func(int) ([]any, error)) CopyFromSource {
return &copyFromSlice{next: next, idx: -1, len: length}
}
type copyFromSlice struct {
next func(int) ([]any, error)
idx int
len int
err error
}
func (cts *copyFromSlice) Next() bool {
cts.idx++
return cts.idx < cts.len
}
func (cts *copyFromSlice) Values() ([]any, error) {
values, err := cts.next(cts.idx)
if err != nil {
cts.err = err
}
return values, err
}
func (cts *copyFromSlice) Err() error {
return cts.err
}
// CopyFromFunc returns a CopyFromSource interface that relies on nxtf for values.
// nxtf returns rows until it either signals an 'end of data' by returning row=nil and err=nil,
// or it returns an error. If nxtf returns an error, the copy is aborted.
func CopyFromFunc(nxtf func() (row []any, err error)) CopyFromSource {
return &copyFromFunc{next: nxtf}
}
type copyFromFunc struct {
next func() ([]any, error)
valueRow []any
err error
}
func (g *copyFromFunc) Next() bool {
g.valueRow, g.err = g.next()
// only return true if valueRow exists and no error
return g.valueRow != nil && g.err == nil
}
func (g *copyFromFunc) Values() ([]any, error) {
return g.valueRow, g.err
}
func (g *copyFromFunc) Err() error {
return g.err
}
// CopyFromSource is the interface used by *Conn.CopyFrom as the source for copy data.
type CopyFromSource interface {
// Next returns true if there is another row and makes the next row data
// available to Values(). When there are no more rows available or an error
// has occurred it returns false.
Next() bool
// Values returns the values for the current row.
Values() ([]any, error)
// Err returns any error that has been encountered by the CopyFromSource. If
// this is not nil *Conn.CopyFrom will abort the copy.
Err() error
}
type copyFrom struct {
conn *Conn
tableName Identifier
columnNames []string
rowSrc CopyFromSource
readerErrChan chan error
mode QueryExecMode
}
func (ct *copyFrom) run(ctx context.Context) (int64, error) {
if ct.conn.copyFromTracer != nil {
ctx = ct.conn.copyFromTracer.TraceCopyFromStart(ctx, ct.conn, TraceCopyFromStartData{
TableName: ct.tableName,
ColumnNames: ct.columnNames,
})
}
quotedTableName := ct.tableName.Sanitize()
cbuf := &bytes.Buffer{}
for i, cn := range ct.columnNames {
if i != 0 {
cbuf.WriteString(", ")
}
cbuf.WriteString(quoteIdentifier(cn))
}
quotedColumnNames := cbuf.String()
var sd *pgconn.StatementDescription
switch ct.mode {
case QueryExecModeExec, QueryExecModeSimpleProtocol:
// These modes don't support the binary format. Before the inclusion of the
// QueryExecModes, Conn.Prepare was called on every COPY operation to get
// the OIDs. These prepared statements were not cached.
//
// Since that's the same behavior provided by QueryExecModeDescribeExec,
// we'll default to that mode.
ct.mode = QueryExecModeDescribeExec
fallthrough
case QueryExecModeCacheStatement, QueryExecModeCacheDescribe, QueryExecModeDescribeExec:
var err error
sd, err = ct.conn.getStatementDescription(
ctx,
ct.mode,
fmt.Sprintf("select %s from %s", quotedColumnNames, quotedTableName),
)
if err != nil {
return 0, fmt.Errorf("statement description failed: %w", err)
}
default:
return 0, fmt.Errorf("unknown QueryExecMode: %v", ct.mode)
}
r, w := io.Pipe()
doneChan := make(chan struct{})
go func() {
defer close(doneChan)
// Purposely NOT using defer w.Close(). See https://github.com/golang/go/issues/24283.
buf := ct.conn.wbuf
buf = append(buf, "PGCOPY\n\377\r\n\000"...)
buf = pgio.AppendInt32(buf, 0)
buf = pgio.AppendInt32(buf, 0)
moreRows := true
for moreRows {
var err error
moreRows, buf, err = ct.buildCopyBuf(buf, sd)
if err != nil {
w.CloseWithError(err)
return
}
if ct.rowSrc.Err() != nil {
w.CloseWithError(ct.rowSrc.Err())
return
}
if len(buf) > 0 {
_, err = w.Write(buf)
if err != nil {
w.Close()
return
}
}
buf = buf[:0]
}
w.Close()
}()
commandTag, err := ct.conn.pgConn.CopyFrom(ctx, r, fmt.Sprintf("copy %s ( %s ) from stdin binary;", quotedTableName, quotedColumnNames))
r.Close()
<-doneChan
if ct.conn.copyFromTracer != nil {
ct.conn.copyFromTracer.TraceCopyFromEnd(ctx, ct.conn, TraceCopyFromEndData{
CommandTag: commandTag,
Err: err,
})
}
return commandTag.RowsAffected(), err
}
func (ct *copyFrom) buildCopyBuf(buf []byte, sd *pgconn.StatementDescription) (bool, []byte, error) {
const sendBufSize = 65536 - 5 // The packet has a 5-byte header
lastBufLen := 0
largestRowLen := 0
for ct.rowSrc.Next() {
lastBufLen = len(buf)
values, err := ct.rowSrc.Values()
if err != nil {
return false, nil, err
}
if len(values) != len(ct.columnNames) {
return false, nil, fmt.Errorf("expected %d values, got %d values", len(ct.columnNames), len(values))
}
buf = pgio.AppendInt16(buf, int16(len(ct.columnNames)))
for i, val := range values {
buf, err = encodeCopyValue(ct.conn.typeMap, buf, sd.Fields[i].DataTypeOID, val)
if err != nil {
return false, nil, err
}
}
rowLen := len(buf) - lastBufLen
if rowLen > largestRowLen {
largestRowLen = rowLen
}
// Try not to overflow size of the buffer PgConn.CopyFrom will be reading into. If that happens then the nature of
// io.Pipe means that the next Read will be short. This can lead to pathological send sizes such as 65531, 13, 65531
// 13, 65531, 13, 65531, 13.
if len(buf) > sendBufSize-largestRowLen {
return true, buf, nil
}
}
return false, buf, nil
}
// CopyFrom uses the PostgreSQL copy protocol to perform bulk data insertion. It returns the number of rows copied and
// an error.
//
// CopyFrom requires all values use the binary format. A pgtype.Type that supports the binary format must be registered
// for the type of each column. Almost all types implemented by pgx support the binary format.
//
// Even though enum types appear to be strings they still must be registered to use with CopyFrom. This can be done with
// Conn.LoadType and pgtype.Map.RegisterType.
func (c *Conn) CopyFrom(ctx context.Context, tableName Identifier, columnNames []string, rowSrc CopyFromSource) (int64, error) {
ct := &copyFrom{
conn: c,
tableName: tableName,
columnNames: columnNames,
rowSrc: rowSrc,
readerErrChan: make(chan error),
mode: c.config.DefaultQueryExecMode,
}
return ct.run(ctx)
}
+262
View File
@@ -0,0 +1,262 @@
package pgx
import (
"context"
"fmt"
"regexp"
"strconv"
"strings"
"github.com/jackc/pgx/v5/pgtype"
)
/*
buildLoadDerivedTypesSQL generates the correct query for retrieving type information.
pgVersion: the major version of the PostgreSQL server
typeNames: the names of the types to load. If nil, load all types.
*/
func buildLoadDerivedTypesSQL(pgVersion int64, typeNames []string) string {
supportsMultirange := (pgVersion >= 14)
var typeNamesClause string
if typeNames == nil {
// This should not occur; this will not return any types
typeNamesClause = "= ''"
} else {
typeNamesClause = "= ANY($1)"
}
parts := make([]string, 0, 10)
// Each of the type names provided might be found in pg_class or pg_type.
// Additionally, it may or may not include a schema portion.
parts = append(parts, `
WITH RECURSIVE
-- find the OIDs in pg_class which match one of the provided type names
selected_classes(oid,reltype) AS (
-- this query uses the namespace search path, so will match type names without a schema prefix
SELECT pg_class.oid, pg_class.reltype
FROM pg_catalog.pg_class
LEFT JOIN pg_catalog.pg_namespace n ON n.oid = pg_class.relnamespace
WHERE pg_catalog.pg_table_is_visible(pg_class.oid)
AND relname `, typeNamesClause, `
UNION ALL
-- this query will only match type names which include the schema prefix
SELECT pg_class.oid, pg_class.reltype
FROM pg_class
INNER JOIN pg_namespace ON (pg_class.relnamespace = pg_namespace.oid)
WHERE nspname || '.' || relname `, typeNamesClause, `
),
selected_types(oid) AS (
-- collect the OIDs from pg_types which correspond to the selected classes
SELECT reltype AS oid
FROM selected_classes
UNION ALL
-- as well as any other type names which match our criteria
SELECT pg_type.oid
FROM pg_type
LEFT OUTER JOIN pg_namespace ON (pg_type.typnamespace = pg_namespace.oid)
WHERE typname `, typeNamesClause, `
OR nspname || '.' || typname `, typeNamesClause, `
),
-- this builds a parent/child mapping of objects, allowing us to know
-- all the child (ie: dependent) types that a parent (type) requires
-- As can be seen, there are 3 ways this can occur (the last of which
-- is due to being a composite class, where the composite fields are children)
pc(parent, child) AS (
SELECT parent.oid, parent.typelem
FROM pg_type parent
WHERE parent.typtype = 'b' AND parent.typelem != 0
UNION ALL
SELECT parent.oid, parent.typbasetype
FROM pg_type parent
WHERE parent.typtypmod = -1 AND parent.typbasetype != 0
UNION ALL
SELECT pg_type.oid, atttypid
FROM pg_attribute
INNER JOIN pg_class ON (pg_class.oid = pg_attribute.attrelid)
INNER JOIN pg_type ON (pg_type.oid = pg_class.reltype)
WHERE NOT attisdropped
AND attnum > 0
),
-- Now construct a recursive query which includes a 'depth' element.
-- This is used to ensure that the "youngest" children are registered before
-- their parents.
relationships(parent, child, depth) AS (
SELECT DISTINCT 0::OID, selected_types.oid, 0
FROM selected_types
UNION ALL
SELECT pg_type.oid AS parent, pg_attribute.atttypid AS child, 1
FROM selected_classes c
inner join pg_type ON (c.reltype = pg_type.oid)
inner join pg_attribute on (c.oid = pg_attribute.attrelid)
UNION ALL
SELECT pc.parent, pc.child, relationships.depth + 1
FROM pc
INNER JOIN relationships ON (pc.parent = relationships.child)
),
-- composite fields need to be encapsulated as a couple of arrays to provide the required information for registration
composite AS (
SELECT pg_type.oid, ARRAY_AGG(attname ORDER BY attnum) AS attnames, ARRAY_AGG(atttypid ORDER BY ATTNUM) AS atttypids
FROM pg_attribute
INNER JOIN pg_class ON (pg_class.oid = pg_attribute.attrelid)
INNER JOIN pg_type ON (pg_type.oid = pg_class.reltype)
WHERE NOT attisdropped
AND attnum > 0
GROUP BY pg_type.oid
)
-- Bring together this information, showing all the information which might possibly be required
-- to complete the registration, applying filters to only show the items which relate to the selected
-- types/classes.
SELECT typname,
pg_namespace.nspname,
typtype,
typbasetype,
typelem,
pg_type.oid,`)
if supportsMultirange {
parts = append(parts, `
COALESCE(multirange.rngtypid, 0) AS rngtypid,`)
} else {
parts = append(parts, `
0 AS rngtypid,`)
}
parts = append(parts, `
COALESCE(pg_range.rngsubtype, 0) AS rngsubtype,
attnames, atttypids
FROM relationships
INNER JOIN pg_type ON (pg_type.oid = relationships.child)
LEFT OUTER JOIN pg_range ON (pg_type.oid = pg_range.rngtypid)`)
if supportsMultirange {
parts = append(parts, `
LEFT OUTER JOIN pg_range multirange ON (pg_type.oid = multirange.rngmultitypid)`)
}
parts = append(parts, `
LEFT OUTER JOIN composite USING (oid)
LEFT OUTER JOIN pg_namespace ON (pg_type.typnamespace = pg_namespace.oid)
WHERE NOT (typtype = 'b' AND typelem = 0)`)
parts = append(parts, `
GROUP BY typname, pg_namespace.nspname, typtype, typbasetype, typelem, pg_type.oid, pg_range.rngsubtype,`)
if supportsMultirange {
parts = append(parts, `
multirange.rngtypid,`)
}
parts = append(parts, `
attnames, atttypids
ORDER BY MAX(depth) desc, typname;`)
return strings.Join(parts, "")
}
type derivedTypeInfo struct {
Oid, Typbasetype, Typelem, Rngsubtype, Rngtypid uint32
TypeName, Typtype, NspName string
Attnames []string
Atttypids []uint32
}
// LoadTypes performs a single (complex) query, returning all the required
// information to register the named types, as well as any other types directly
// or indirectly required to complete the registration.
// The result of this call can be passed into RegisterTypes to complete the process.
func (c *Conn) LoadTypes(ctx context.Context, typeNames []string) ([]*pgtype.Type, error) {
m := c.TypeMap()
if typeNames == nil || len(typeNames) == 0 {
return nil, fmt.Errorf("No type names were supplied.")
}
// Disregard server version errors. This will result in
// the SQL not support recent structures such as multirange
serverVersion, _ := serverVersion(c)
sql := buildLoadDerivedTypesSQL(serverVersion, typeNames)
var rows Rows
var err error
if typeNames == nil {
rows, err = c.Query(ctx, sql, QueryExecModeSimpleProtocol)
} else {
rows, err = c.Query(ctx, sql, QueryExecModeSimpleProtocol, typeNames)
}
if err != nil {
return nil, fmt.Errorf("While generating load types query: %w", err)
}
defer rows.Close()
result := make([]*pgtype.Type, 0, 100)
for rows.Next() {
ti := derivedTypeInfo{}
err = rows.Scan(&ti.TypeName, &ti.NspName, &ti.Typtype, &ti.Typbasetype, &ti.Typelem, &ti.Oid, &ti.Rngtypid, &ti.Rngsubtype, &ti.Attnames, &ti.Atttypids)
if err != nil {
return nil, fmt.Errorf("While scanning type information: %w", err)
}
var type_ *pgtype.Type
switch ti.Typtype {
case "b": // array
dt, ok := m.TypeForOID(ti.Typelem)
if !ok {
return nil, fmt.Errorf("Array element OID %v not registered while loading pgtype %q", ti.Typelem, ti.TypeName)
}
type_ = &pgtype.Type{Name: ti.TypeName, OID: ti.Oid, Codec: &pgtype.ArrayCodec{ElementType: dt}}
case "c": // composite
var fields []pgtype.CompositeCodecField
for i, fieldName := range ti.Attnames {
dt, ok := m.TypeForOID(ti.Atttypids[i])
if !ok {
return nil, fmt.Errorf("Unknown field for composite type %q: field %q (OID %v) is not already registered.", ti.TypeName, fieldName, ti.Atttypids[i])
}
fields = append(fields, pgtype.CompositeCodecField{Name: fieldName, Type: dt})
}
type_ = &pgtype.Type{Name: ti.TypeName, OID: ti.Oid, Codec: &pgtype.CompositeCodec{Fields: fields}}
case "d": // domain
dt, ok := m.TypeForOID(ti.Typbasetype)
if !ok {
return nil, fmt.Errorf("Domain base type OID %v was not already registered, needed for %q", ti.Typbasetype, ti.TypeName)
}
type_ = &pgtype.Type{Name: ti.TypeName, OID: ti.Oid, Codec: dt.Codec}
case "e": // enum
type_ = &pgtype.Type{Name: ti.TypeName, OID: ti.Oid, Codec: &pgtype.EnumCodec{}}
case "r": // range
dt, ok := m.TypeForOID(ti.Rngsubtype)
if !ok {
return nil, fmt.Errorf("Range element OID %v was not already registered, needed for %q", ti.Rngsubtype, ti.TypeName)
}
type_ = &pgtype.Type{Name: ti.TypeName, OID: ti.Oid, Codec: &pgtype.RangeCodec{ElementType: dt}}
case "m": // multirange
dt, ok := m.TypeForOID(ti.Rngtypid)
if !ok {
return nil, fmt.Errorf("Multirange element OID %v was not already registered, needed for %q", ti.Rngtypid, ti.TypeName)
}
type_ = &pgtype.Type{Name: ti.TypeName, OID: ti.Oid, Codec: &pgtype.MultirangeCodec{ElementType: dt}}
default:
return nil, fmt.Errorf("Unknown typtype %q was found while registering %q", ti.Typtype, ti.TypeName)
}
if type_ != nil {
m.RegisterType(type_)
if ti.NspName != "" {
nspType := &pgtype.Type{Name: ti.NspName + "." + type_.Name, OID: type_.OID, Codec: type_.Codec}
m.RegisterType(nspType)
result = append(result, nspType)
}
result = append(result, type_)
}
}
return result, nil
}
// serverVersion returns the postgresql server version.
func serverVersion(c *Conn) (int64, error) {
serverVersionStr := c.PgConn().ParameterStatus("server_version")
serverVersionStr = regexp.MustCompile(`^[0-9]+`).FindString(serverVersionStr)
// if not PostgreSQL do nothing
if serverVersionStr == "" {
return 0, fmt.Errorf("Cannot identify server version in %q", serverVersionStr)
}
version, err := strconv.ParseInt(serverVersionStr, 10, 64)
if err != nil {
return 0, fmt.Errorf("postgres version parsing failed: %w", err)
}
return version, nil
}
+194
View File
@@ -0,0 +1,194 @@
// Package pgx is a PostgreSQL database driver.
/*
pgx provides a native PostgreSQL driver and can act as a database/sql driver. The native PostgreSQL interface is similar
to the database/sql interface while providing better speed and access to PostgreSQL specific features. Use
github.com/jackc/pgx/v5/stdlib to use pgx as a database/sql compatible driver. See that package's documentation for
details.
Establishing a Connection
The primary way of establishing a connection is with [pgx.Connect]:
conn, err := pgx.Connect(context.Background(), os.Getenv("DATABASE_URL"))
The database connection string can be in URL or key/value format. Both PostgreSQL settings and pgx settings can be
specified here. In addition, a config struct can be created by [ParseConfig] and modified before establishing the
connection with [ConnectConfig] to configure settings such as tracing that cannot be configured with a connection
string.
Connection Pool
[*pgx.Conn] represents a single connection to the database and is not concurrency safe. Use package
github.com/jackc/pgx/v5/pgxpool for a concurrency safe connection pool.
Query Interface
pgx implements Query in the familiar database/sql style. However, pgx provides generic functions such as CollectRows and
ForEachRow that are a simpler and safer way of processing rows than manually calling defer rows.Close(), rows.Next(),
rows.Scan, and rows.Err().
CollectRows can be used collect all returned rows into a slice.
rows, _ := conn.Query(context.Background(), "select generate_series(1,$1)", 5)
numbers, err := pgx.CollectRows(rows, pgx.RowTo[int32])
if err != nil {
return err
}
// numbers => [1 2 3 4 5]
ForEachRow can be used to execute a callback function for every row. This is often easier than iterating over rows
directly.
var sum, n int32
rows, _ := conn.Query(context.Background(), "select generate_series(1,$1)", 10)
_, err := pgx.ForEachRow(rows, []any{&n}, func() error {
sum += n
return nil
})
if err != nil {
return err
}
pgx also implements QueryRow in the same style as database/sql.
var name string
var weight int64
err := conn.QueryRow(context.Background(), "select name, weight from widgets where id=$1", 42).Scan(&name, &weight)
if err != nil {
return err
}
Use Exec to execute a query that does not return a result set.
commandTag, err := conn.Exec(context.Background(), "delete from widgets where id=$1", 42)
if err != nil {
return err
}
if commandTag.RowsAffected() != 1 {
return errors.New("No row found to delete")
}
PostgreSQL Data Types
pgx uses the pgtype package to converting Go values to and from PostgreSQL values. It supports many PostgreSQL types
directly and is customizable and extendable. User defined data types such as enums, domains, and composite types may
require type registration. See that package's documentation for details.
Transactions
Transactions are started by calling Begin.
tx, err := conn.Begin(context.Background())
if err != nil {
return err
}
// Rollback is safe to call even if the tx is already closed, so if
// the tx commits successfully, this is a no-op
defer tx.Rollback(context.Background())
_, err = tx.Exec(context.Background(), "insert into foo(id) values (1)")
if err != nil {
return err
}
err = tx.Commit(context.Background())
if err != nil {
return err
}
The Tx returned from Begin also implements the Begin method. This can be used to implement pseudo nested transactions.
These are internally implemented with savepoints.
Use BeginTx to control the transaction mode. BeginTx also can be used to ensure a new transaction is created instead of
a pseudo nested transaction.
BeginFunc and BeginTxFunc are functions that begin a transaction, execute a function, and commit or rollback the
transaction depending on the return value of the function. These can be simpler and less error prone to use.
err = pgx.BeginFunc(context.Background(), conn, func(tx pgx.Tx) error {
_, err := tx.Exec(context.Background(), "insert into foo(id) values (1)")
return err
})
if err != nil {
return err
}
Prepared Statements
Prepared statements can be manually created with the Prepare method. However, this is rarely necessary because pgx
includes an automatic statement cache by default. Queries run through the normal Query, QueryRow, and Exec functions are
automatically prepared on first execution and the prepared statement is reused on subsequent executions. See ParseConfig
for information on how to customize or disable the statement cache.
Copy Protocol
Use CopyFrom to efficiently insert multiple rows at a time using the PostgreSQL copy protocol. CopyFrom accepts a
CopyFromSource interface. If the data is already in a [][]any use CopyFromRows to wrap it in a CopyFromSource interface.
Or implement CopyFromSource to avoid buffering the entire data set in memory.
rows := [][]any{
{"John", "Smith", int32(36)},
{"Jane", "Doe", int32(29)},
}
copyCount, err := conn.CopyFrom(
context.Background(),
pgx.Identifier{"people"},
[]string{"first_name", "last_name", "age"},
pgx.CopyFromRows(rows),
)
When you already have a typed array using CopyFromSlice can be more convenient.
rows := []User{
{"John", "Smith", 36},
{"Jane", "Doe", 29},
}
copyCount, err := conn.CopyFrom(
context.Background(),
pgx.Identifier{"people"},
[]string{"first_name", "last_name", "age"},
pgx.CopyFromSlice(len(rows), func(i int) ([]any, error) {
return []any{rows[i].FirstName, rows[i].LastName, rows[i].Age}, nil
}),
)
CopyFrom can be faster than an insert with as few as 5 rows.
Listen and Notify
pgx can listen to the PostgreSQL notification system with the `Conn.WaitForNotification` method. It blocks until a
notification is received or the context is canceled.
_, err := conn.Exec(context.Background(), "listen channelname")
if err != nil {
return err
}
notification, err := conn.WaitForNotification(context.Background())
if err != nil {
return err
}
// do something with notification
Tracing and Logging
pgx supports tracing by setting ConnConfig.Tracer. To combine several tracers you can use the multitracer.Tracer.
In addition, the tracelog package provides the TraceLog type which lets a traditional logger act as a Tracer.
For debug tracing of the actual PostgreSQL wire protocol messages see github.com/jackc/pgx/v5/pgproto3.
Lower Level PostgreSQL Functionality
github.com/jackc/pgx/v5/pgconn contains a lower level PostgreSQL driver roughly at the level of libpq. pgx.Conn in
implemented on top of pgconn. The Conn.PgConn() method can be used to access this lower layer.
PgBouncer
By default pgx automatically uses prepared statements. Prepared statements are incompatible with PgBouncer. This can be
disabled by setting a different QueryExecMode in ConnConfig.DefaultQueryExecMode.
*/
package pgx
+146
View File
@@ -0,0 +1,146 @@
package pgx
import (
"fmt"
"github.com/jackc/pgx/v5/pgconn"
"github.com/jackc/pgx/v5/pgtype"
)
// ExtendedQueryBuilder is used to choose the parameter formats, to format the parameters and to choose the result
// formats for an extended query.
type ExtendedQueryBuilder struct {
ParamValues [][]byte
paramValueBytes []byte
ParamFormats []int16
ResultFormats []int16
}
// Build sets ParamValues, ParamFormats, and ResultFormats for use with *PgConn.ExecParams or *PgConn.ExecPrepared. If
// sd is nil then QueryExecModeExec behavior will be used.
func (eqb *ExtendedQueryBuilder) Build(m *pgtype.Map, sd *pgconn.StatementDescription, args []any) error {
eqb.reset()
if sd == nil {
for i := range args {
err := eqb.appendParam(m, 0, pgtype.TextFormatCode, args[i])
if err != nil {
err = fmt.Errorf("failed to encode args[%d]: %w", i, err)
return err
}
}
return nil
}
if len(sd.ParamOIDs) != len(args) {
return fmt.Errorf("mismatched param and argument count")
}
for i := range args {
err := eqb.appendParam(m, sd.ParamOIDs[i], -1, args[i])
if err != nil {
err = fmt.Errorf("failed to encode args[%d]: %w", i, err)
return err
}
}
for i := range sd.Fields {
eqb.appendResultFormat(m.FormatCodeForOID(sd.Fields[i].DataTypeOID))
}
return nil
}
// appendParam appends a parameter to the query. format may be -1 to automatically choose the format. If arg is nil it
// must be an untyped nil.
func (eqb *ExtendedQueryBuilder) appendParam(m *pgtype.Map, oid uint32, format int16, arg any) error {
if format == -1 {
preferredFormat := eqb.chooseParameterFormatCode(m, oid, arg)
preferredErr := eqb.appendParam(m, oid, preferredFormat, arg)
if preferredErr == nil {
return nil
}
var otherFormat int16
if preferredFormat == TextFormatCode {
otherFormat = BinaryFormatCode
} else {
otherFormat = TextFormatCode
}
otherErr := eqb.appendParam(m, oid, otherFormat, arg)
if otherErr == nil {
return nil
}
return preferredErr // return the error from the preferred format
}
v, err := eqb.encodeExtendedParamValue(m, oid, format, arg)
if err != nil {
return err
}
eqb.ParamFormats = append(eqb.ParamFormats, format)
eqb.ParamValues = append(eqb.ParamValues, v)
return nil
}
// appendResultFormat appends a result format to the query.
func (eqb *ExtendedQueryBuilder) appendResultFormat(format int16) {
eqb.ResultFormats = append(eqb.ResultFormats, format)
}
// reset readies eqb to build another query.
func (eqb *ExtendedQueryBuilder) reset() {
eqb.ParamValues = eqb.ParamValues[0:0]
eqb.paramValueBytes = eqb.paramValueBytes[0:0]
eqb.ParamFormats = eqb.ParamFormats[0:0]
eqb.ResultFormats = eqb.ResultFormats[0:0]
if cap(eqb.ParamValues) > 64 {
eqb.ParamValues = make([][]byte, 0, 64)
}
if cap(eqb.paramValueBytes) > 256 {
eqb.paramValueBytes = make([]byte, 0, 256)
}
if cap(eqb.ParamFormats) > 64 {
eqb.ParamFormats = make([]int16, 0, 64)
}
if cap(eqb.ResultFormats) > 64 {
eqb.ResultFormats = make([]int16, 0, 64)
}
}
func (eqb *ExtendedQueryBuilder) encodeExtendedParamValue(m *pgtype.Map, oid uint32, formatCode int16, arg any) ([]byte, error) {
if eqb.paramValueBytes == nil {
eqb.paramValueBytes = make([]byte, 0, 128)
}
pos := len(eqb.paramValueBytes)
buf, err := m.Encode(oid, formatCode, arg, eqb.paramValueBytes)
if err != nil {
return nil, err
}
if buf == nil {
return nil, nil
}
eqb.paramValueBytes = buf
return eqb.paramValueBytes[pos:], nil
}
// chooseParameterFormatCode determines the correct format code for an
// argument to a prepared statement. It defaults to TextFormatCode if no
// determination can be made.
func (eqb *ExtendedQueryBuilder) chooseParameterFormatCode(m *pgtype.Map, oid uint32, arg any) int16 {
switch arg.(type) {
case string, *string:
return TextFormatCode
}
return m.FormatCodeForOID(oid)
}
+70
View File
@@ -0,0 +1,70 @@
// Package iobufpool implements a global segregated-fit pool of buffers for IO.
//
// It uses *[]byte instead of []byte to avoid the sync.Pool allocation with Put. Unfortunately, using a pointer to avoid
// an allocation is purposely not documented. https://github.com/golang/go/issues/16323
package iobufpool
import "sync"
const minPoolExpOf2 = 8
var pools [18]*sync.Pool
func init() {
for i := range pools {
bufLen := 1 << (minPoolExpOf2 + i)
pools[i] = &sync.Pool{
New: func() any {
buf := make([]byte, bufLen)
return &buf
},
}
}
}
// Get gets a []byte of len size with cap <= size*2.
func Get(size int) *[]byte {
i := getPoolIdx(size)
if i >= len(pools) {
buf := make([]byte, size)
return &buf
}
ptrBuf := (pools[i].Get().(*[]byte))
*ptrBuf = (*ptrBuf)[:size]
return ptrBuf
}
func getPoolIdx(size int) int {
size--
size >>= minPoolExpOf2
i := 0
for size > 0 {
size >>= 1
i++
}
return i
}
// Put returns buf to the pool.
func Put(buf *[]byte) {
i := putPoolIdx(cap(*buf))
if i < 0 {
return
}
pools[i].Put(buf)
}
func putPoolIdx(size int) int {
minPoolSize := 1 << minPoolExpOf2
for i := range pools {
if size == minPoolSize<<i {
return i
}
}
return -1
}
+6
View File
@@ -0,0 +1,6 @@
# pgio
Package pgio is a low-level toolkit building messages in the PostgreSQL wire protocol.
pgio provides functions for appending integers to a []byte while doing byte
order conversion.
+6
View File
@@ -0,0 +1,6 @@
// Package pgio is a low-level toolkit building messages in the PostgreSQL wire protocol.
/*
pgio provides functions for appending integers to a []byte while doing byte
order conversion.
*/
package pgio
+40
View File
@@ -0,0 +1,40 @@
package pgio
import "encoding/binary"
func AppendUint16(buf []byte, n uint16) []byte {
wp := len(buf)
buf = append(buf, 0, 0)
binary.BigEndian.PutUint16(buf[wp:], n)
return buf
}
func AppendUint32(buf []byte, n uint32) []byte {
wp := len(buf)
buf = append(buf, 0, 0, 0, 0)
binary.BigEndian.PutUint32(buf[wp:], n)
return buf
}
func AppendUint64(buf []byte, n uint64) []byte {
wp := len(buf)
buf = append(buf, 0, 0, 0, 0, 0, 0, 0, 0)
binary.BigEndian.PutUint64(buf[wp:], n)
return buf
}
func AppendInt16(buf []byte, n int16) []byte {
return AppendUint16(buf, uint16(n))
}
func AppendInt32(buf []byte, n int32) []byte {
return AppendUint32(buf, uint32(n))
}
func AppendInt64(buf []byte, n int64) []byte {
return AppendUint64(buf, uint64(n))
}
func SetInt32(buf []byte, n int32) {
binary.BigEndian.PutUint32(buf, uint32(n))
}
+331
View File
@@ -0,0 +1,331 @@
package sanitize
import (
"bytes"
"encoding/hex"
"fmt"
"strconv"
"strings"
"time"
"unicode/utf8"
)
// Part is either a string or an int. A string is raw SQL. An int is a
// argument placeholder.
type Part any
type Query struct {
Parts []Part
}
// utf.DecodeRune returns the utf8.RuneError for errors. But that is actually rune U+FFFD -- the unicode replacement
// character. utf8.RuneError is not an error if it is also width 3.
//
// https://github.com/jackc/pgx/issues/1380
const replacementcharacterwidth = 3
func (q *Query) Sanitize(args ...any) (string, error) {
argUse := make([]bool, len(args))
buf := &bytes.Buffer{}
for _, part := range q.Parts {
var str string
switch part := part.(type) {
case string:
str = part
case int:
argIdx := part - 1
if argIdx < 0 {
return "", fmt.Errorf("first sql argument must be > 0")
}
if argIdx >= len(args) {
return "", fmt.Errorf("insufficient arguments")
}
arg := args[argIdx]
switch arg := arg.(type) {
case nil:
str = "null"
case int64:
str = strconv.FormatInt(arg, 10)
case float64:
str = strconv.FormatFloat(arg, 'f', -1, 64)
case bool:
str = strconv.FormatBool(arg)
case []byte:
str = QuoteBytes(arg)
case string:
str = QuoteString(arg)
case time.Time:
str = arg.Truncate(time.Microsecond).Format("'2006-01-02 15:04:05.999999999Z07:00:00'")
default:
return "", fmt.Errorf("invalid arg type: %T", arg)
}
argUse[argIdx] = true
// Prevent SQL injection via Line Comment Creation
// https://github.com/jackc/pgx/security/advisories/GHSA-m7wr-2xf7-cm9p
str = " " + str + " "
default:
return "", fmt.Errorf("invalid Part type: %T", part)
}
buf.WriteString(str)
}
for i, used := range argUse {
if !used {
return "", fmt.Errorf("unused argument: %d", i)
}
}
return buf.String(), nil
}
func NewQuery(sql string) (*Query, error) {
l := &sqlLexer{
src: sql,
stateFn: rawState,
}
for l.stateFn != nil {
l.stateFn = l.stateFn(l)
}
query := &Query{Parts: l.parts}
return query, nil
}
func QuoteString(str string) string {
return "'" + strings.ReplaceAll(str, "'", "''") + "'"
}
func QuoteBytes(buf []byte) string {
return `'\x` + hex.EncodeToString(buf) + "'"
}
type sqlLexer struct {
src string
start int
pos int
nested int // multiline comment nesting level.
stateFn stateFn
parts []Part
}
type stateFn func(*sqlLexer) stateFn
func rawState(l *sqlLexer) stateFn {
for {
r, width := utf8.DecodeRuneInString(l.src[l.pos:])
l.pos += width
switch r {
case 'e', 'E':
nextRune, width := utf8.DecodeRuneInString(l.src[l.pos:])
if nextRune == '\'' {
l.pos += width
return escapeStringState
}
case '\'':
return singleQuoteState
case '"':
return doubleQuoteState
case '$':
nextRune, _ := utf8.DecodeRuneInString(l.src[l.pos:])
if '0' <= nextRune && nextRune <= '9' {
if l.pos-l.start > 0 {
l.parts = append(l.parts, l.src[l.start:l.pos-width])
}
l.start = l.pos
return placeholderState
}
case '-':
nextRune, width := utf8.DecodeRuneInString(l.src[l.pos:])
if nextRune == '-' {
l.pos += width
return oneLineCommentState
}
case '/':
nextRune, width := utf8.DecodeRuneInString(l.src[l.pos:])
if nextRune == '*' {
l.pos += width
return multilineCommentState
}
case utf8.RuneError:
if width != replacementcharacterwidth {
if l.pos-l.start > 0 {
l.parts = append(l.parts, l.src[l.start:l.pos])
l.start = l.pos
}
return nil
}
}
}
}
func singleQuoteState(l *sqlLexer) stateFn {
for {
r, width := utf8.DecodeRuneInString(l.src[l.pos:])
l.pos += width
switch r {
case '\'':
nextRune, width := utf8.DecodeRuneInString(l.src[l.pos:])
if nextRune != '\'' {
return rawState
}
l.pos += width
case utf8.RuneError:
if width != replacementcharacterwidth {
if l.pos-l.start > 0 {
l.parts = append(l.parts, l.src[l.start:l.pos])
l.start = l.pos
}
return nil
}
}
}
}
func doubleQuoteState(l *sqlLexer) stateFn {
for {
r, width := utf8.DecodeRuneInString(l.src[l.pos:])
l.pos += width
switch r {
case '"':
nextRune, width := utf8.DecodeRuneInString(l.src[l.pos:])
if nextRune != '"' {
return rawState
}
l.pos += width
case utf8.RuneError:
if width != replacementcharacterwidth {
if l.pos-l.start > 0 {
l.parts = append(l.parts, l.src[l.start:l.pos])
l.start = l.pos
}
return nil
}
}
}
}
// placeholderState consumes a placeholder value. The $ must have already has
// already been consumed. The first rune must be a digit.
func placeholderState(l *sqlLexer) stateFn {
num := 0
for {
r, width := utf8.DecodeRuneInString(l.src[l.pos:])
l.pos += width
if '0' <= r && r <= '9' {
num *= 10
num += int(r - '0')
} else {
l.parts = append(l.parts, num)
l.pos -= width
l.start = l.pos
return rawState
}
}
}
func escapeStringState(l *sqlLexer) stateFn {
for {
r, width := utf8.DecodeRuneInString(l.src[l.pos:])
l.pos += width
switch r {
case '\\':
_, width = utf8.DecodeRuneInString(l.src[l.pos:])
l.pos += width
case '\'':
nextRune, width := utf8.DecodeRuneInString(l.src[l.pos:])
if nextRune != '\'' {
return rawState
}
l.pos += width
case utf8.RuneError:
if width != replacementcharacterwidth {
if l.pos-l.start > 0 {
l.parts = append(l.parts, l.src[l.start:l.pos])
l.start = l.pos
}
return nil
}
}
}
}
func oneLineCommentState(l *sqlLexer) stateFn {
for {
r, width := utf8.DecodeRuneInString(l.src[l.pos:])
l.pos += width
switch r {
case '\\':
_, width = utf8.DecodeRuneInString(l.src[l.pos:])
l.pos += width
case '\n', '\r':
return rawState
case utf8.RuneError:
if width != replacementcharacterwidth {
if l.pos-l.start > 0 {
l.parts = append(l.parts, l.src[l.start:l.pos])
l.start = l.pos
}
return nil
}
}
}
}
func multilineCommentState(l *sqlLexer) stateFn {
for {
r, width := utf8.DecodeRuneInString(l.src[l.pos:])
l.pos += width
switch r {
case '/':
nextRune, width := utf8.DecodeRuneInString(l.src[l.pos:])
if nextRune == '*' {
l.pos += width
l.nested++
}
case '*':
nextRune, width := utf8.DecodeRuneInString(l.src[l.pos:])
if nextRune != '/' {
continue
}
l.pos += width
if l.nested == 0 {
return rawState
}
l.nested--
case utf8.RuneError:
if width != replacementcharacterwidth {
if l.pos-l.start > 0 {
l.parts = append(l.parts, l.src[l.start:l.pos])
l.start = l.pos
}
return nil
}
}
}
}
// SanitizeSQL replaces placeholder values with args. It quotes and escapes args
// as necessary. This function is only safe when standard_conforming_strings is
// on.
func SanitizeSQL(sql string, args ...any) (string, error) {
query, err := NewQuery(sql)
if err != nil {
return "", err
}
return query.Sanitize(args...)
}
+112
View File
@@ -0,0 +1,112 @@
package stmtcache
import (
"container/list"
"github.com/jackc/pgx/v5/pgconn"
)
// LRUCache implements Cache with a Least Recently Used (LRU) cache.
type LRUCache struct {
cap int
m map[string]*list.Element
l *list.List
invalidStmts []*pgconn.StatementDescription
}
// NewLRUCache creates a new LRUCache. cap is the maximum size of the cache.
func NewLRUCache(cap int) *LRUCache {
return &LRUCache{
cap: cap,
m: make(map[string]*list.Element),
l: list.New(),
}
}
// Get returns the statement description for sql. Returns nil if not found.
func (c *LRUCache) Get(key string) *pgconn.StatementDescription {
if el, ok := c.m[key]; ok {
c.l.MoveToFront(el)
return el.Value.(*pgconn.StatementDescription)
}
return nil
}
// Put stores sd in the cache. Put panics if sd.SQL is "". Put does nothing if sd.SQL already exists in the cache or
// sd.SQL has been invalidated and HandleInvalidated has not been called yet.
func (c *LRUCache) Put(sd *pgconn.StatementDescription) {
if sd.SQL == "" {
panic("cannot store statement description with empty SQL")
}
if _, present := c.m[sd.SQL]; present {
return
}
// The statement may have been invalidated but not yet handled. Do not readd it to the cache.
for _, invalidSD := range c.invalidStmts {
if invalidSD.SQL == sd.SQL {
return
}
}
if c.l.Len() == c.cap {
c.invalidateOldest()
}
el := c.l.PushFront(sd)
c.m[sd.SQL] = el
}
// Invalidate invalidates statement description identified by sql. Does nothing if not found.
func (c *LRUCache) Invalidate(sql string) {
if el, ok := c.m[sql]; ok {
delete(c.m, sql)
c.invalidStmts = append(c.invalidStmts, el.Value.(*pgconn.StatementDescription))
c.l.Remove(el)
}
}
// InvalidateAll invalidates all statement descriptions.
func (c *LRUCache) InvalidateAll() {
el := c.l.Front()
for el != nil {
c.invalidStmts = append(c.invalidStmts, el.Value.(*pgconn.StatementDescription))
el = el.Next()
}
c.m = make(map[string]*list.Element)
c.l = list.New()
}
// GetInvalidated returns a slice of all statement descriptions invalidated since the last call to RemoveInvalidated.
func (c *LRUCache) GetInvalidated() []*pgconn.StatementDescription {
return c.invalidStmts
}
// RemoveInvalidated removes all invalidated statement descriptions. No other calls to Cache must be made between a
// call to GetInvalidated and RemoveInvalidated or RemoveInvalidated may remove statement descriptions that were
// never seen by the call to GetInvalidated.
func (c *LRUCache) RemoveInvalidated() {
c.invalidStmts = nil
}
// Len returns the number of cached prepared statement descriptions.
func (c *LRUCache) Len() int {
return c.l.Len()
}
// Cap returns the maximum number of cached prepared statement descriptions.
func (c *LRUCache) Cap() int {
return c.cap
}
func (c *LRUCache) invalidateOldest() {
oldest := c.l.Back()
sd := oldest.Value.(*pgconn.StatementDescription)
c.invalidStmts = append(c.invalidStmts, sd)
delete(c.m, sd.SQL)
c.l.Remove(oldest)
}
+45
View File
@@ -0,0 +1,45 @@
// Package stmtcache is a cache for statement descriptions.
package stmtcache
import (
"crypto/sha256"
"encoding/hex"
"github.com/jackc/pgx/v5/pgconn"
)
// StatementName returns a statement name that will be stable for sql across multiple connections and program
// executions.
func StatementName(sql string) string {
digest := sha256.Sum256([]byte(sql))
return "stmtcache_" + hex.EncodeToString(digest[0:24])
}
// Cache caches statement descriptions.
type Cache interface {
// Get returns the statement description for sql. Returns nil if not found.
Get(sql string) *pgconn.StatementDescription
// Put stores sd in the cache. Put panics if sd.SQL is "". Put does nothing if sd.SQL already exists in the cache.
Put(sd *pgconn.StatementDescription)
// Invalidate invalidates statement description identified by sql. Does nothing if not found.
Invalidate(sql string)
// InvalidateAll invalidates all statement descriptions.
InvalidateAll()
// GetInvalidated returns a slice of all statement descriptions invalidated since the last call to RemoveInvalidated.
GetInvalidated() []*pgconn.StatementDescription
// RemoveInvalidated removes all invalidated statement descriptions. No other calls to Cache must be made between a
// call to GetInvalidated and RemoveInvalidated or RemoveInvalidated may remove statement descriptions that were
// never seen by the call to GetInvalidated.
RemoveInvalidated()
// Len returns the number of cached prepared statement descriptions.
Len() int
// Cap returns the maximum number of cached prepared statement descriptions.
Cap() int
}
+77
View File
@@ -0,0 +1,77 @@
package stmtcache
import (
"math"
"github.com/jackc/pgx/v5/pgconn"
)
// UnlimitedCache implements Cache with no capacity limit.
type UnlimitedCache struct {
m map[string]*pgconn.StatementDescription
invalidStmts []*pgconn.StatementDescription
}
// NewUnlimitedCache creates a new UnlimitedCache.
func NewUnlimitedCache() *UnlimitedCache {
return &UnlimitedCache{
m: make(map[string]*pgconn.StatementDescription),
}
}
// Get returns the statement description for sql. Returns nil if not found.
func (c *UnlimitedCache) Get(sql string) *pgconn.StatementDescription {
return c.m[sql]
}
// Put stores sd in the cache. Put panics if sd.SQL is "". Put does nothing if sd.SQL already exists in the cache.
func (c *UnlimitedCache) Put(sd *pgconn.StatementDescription) {
if sd.SQL == "" {
panic("cannot store statement description with empty SQL")
}
if _, present := c.m[sd.SQL]; present {
return
}
c.m[sd.SQL] = sd
}
// Invalidate invalidates statement description identified by sql. Does nothing if not found.
func (c *UnlimitedCache) Invalidate(sql string) {
if sd, ok := c.m[sql]; ok {
delete(c.m, sql)
c.invalidStmts = append(c.invalidStmts, sd)
}
}
// InvalidateAll invalidates all statement descriptions.
func (c *UnlimitedCache) InvalidateAll() {
for _, sd := range c.m {
c.invalidStmts = append(c.invalidStmts, sd)
}
c.m = make(map[string]*pgconn.StatementDescription)
}
// GetInvalidated returns a slice of all statement descriptions invalidated since the last call to RemoveInvalidated.
func (c *UnlimitedCache) GetInvalidated() []*pgconn.StatementDescription {
return c.invalidStmts
}
// RemoveInvalidated removes all invalidated statement descriptions. No other calls to Cache must be made between a
// call to GetInvalidated and RemoveInvalidated or RemoveInvalidated may remove statement descriptions that were
// never seen by the call to GetInvalidated.
func (c *UnlimitedCache) RemoveInvalidated() {
c.invalidStmts = nil
}
// Len returns the number of cached prepared statement descriptions.
func (c *UnlimitedCache) Len() int {
return len(c.m)
}
// Cap returns the maximum number of cached prepared statement descriptions.
func (c *UnlimitedCache) Cap() int {
return math.MaxInt
}
+161
View File
@@ -0,0 +1,161 @@
package pgx
import (
"context"
"errors"
"io"
"github.com/jackc/pgx/v5/pgtype"
)
// The PostgreSQL wire protocol has a limit of 1 GB - 1 per message. See definition of
// PQ_LARGE_MESSAGE_LIMIT in the PostgreSQL source code. To allow for the other data
// in the message,maxLargeObjectMessageLength should be no larger than 1 GB - 1 KB.
var maxLargeObjectMessageLength = 1024*1024*1024 - 1024
// LargeObjects is a structure used to access the large objects API. It is only valid within the transaction where it
// was created.
//
// For more details see: http://www.postgresql.org/docs/current/static/largeobjects.html
type LargeObjects struct {
tx Tx
}
type LargeObjectMode int32
const (
LargeObjectModeWrite LargeObjectMode = 0x20000
LargeObjectModeRead LargeObjectMode = 0x40000
)
// Create creates a new large object. If oid is zero, the server assigns an unused OID.
func (o *LargeObjects) Create(ctx context.Context, oid uint32) (uint32, error) {
err := o.tx.QueryRow(ctx, "select lo_create($1)", oid).Scan(&oid)
return oid, err
}
// Open opens an existing large object with the given mode. ctx will also be used for all operations on the opened large
// object.
func (o *LargeObjects) Open(ctx context.Context, oid uint32, mode LargeObjectMode) (*LargeObject, error) {
var fd int32
err := o.tx.QueryRow(ctx, "select lo_open($1, $2)", oid, mode).Scan(&fd)
if err != nil {
return nil, err
}
return &LargeObject{fd: fd, tx: o.tx, ctx: ctx}, nil
}
// Unlink removes a large object from the database.
func (o *LargeObjects) Unlink(ctx context.Context, oid uint32) error {
var result int32
err := o.tx.QueryRow(ctx, "select lo_unlink($1)", oid).Scan(&result)
if err != nil {
return err
}
if result != 1 {
return errors.New("failed to remove large object")
}
return nil
}
// A LargeObject is a large object stored on the server. It is only valid within the transaction that it was initialized
// in. It uses the context it was initialized with for all operations. It implements these interfaces:
//
// io.Writer
// io.Reader
// io.Seeker
// io.Closer
type LargeObject struct {
ctx context.Context
tx Tx
fd int32
}
// Write writes p to the large object and returns the number of bytes written and an error if not all of p was written.
func (o *LargeObject) Write(p []byte) (int, error) {
nTotal := 0
for {
expected := len(p) - nTotal
if expected == 0 {
break
} else if expected > maxLargeObjectMessageLength {
expected = maxLargeObjectMessageLength
}
var n int
err := o.tx.QueryRow(o.ctx, "select lowrite($1, $2)", o.fd, p[nTotal:nTotal+expected]).Scan(&n)
if err != nil {
return nTotal, err
}
if n < 0 {
return nTotal, errors.New("failed to write to large object")
}
nTotal += n
if n < expected {
return nTotal, errors.New("short write to large object")
} else if n > expected {
return nTotal, errors.New("invalid write to large object")
}
}
return nTotal, nil
}
// Read reads up to len(p) bytes into p returning the number of bytes read.
func (o *LargeObject) Read(p []byte) (int, error) {
nTotal := 0
for {
expected := len(p) - nTotal
if expected == 0 {
break
} else if expected > maxLargeObjectMessageLength {
expected = maxLargeObjectMessageLength
}
res := pgtype.PreallocBytes(p[nTotal:])
err := o.tx.QueryRow(o.ctx, "select loread($1, $2)", o.fd, expected).Scan(&res)
// We compute expected so that it always fits into p, so it should never happen
// that PreallocBytes's ScanBytes had to allocate a new slice.
nTotal += len(res)
if err != nil {
return nTotal, err
}
if len(res) < expected {
return nTotal, io.EOF
} else if len(res) > expected {
return nTotal, errors.New("invalid read of large object")
}
}
return nTotal, nil
}
// Seek moves the current location pointer to the new location specified by offset.
func (o *LargeObject) Seek(offset int64, whence int) (n int64, err error) {
err = o.tx.QueryRow(o.ctx, "select lo_lseek64($1, $2, $3)", o.fd, offset, whence).Scan(&n)
return n, err
}
// Tell returns the current read or write location of the large object descriptor.
func (o *LargeObject) Tell() (n int64, err error) {
err = o.tx.QueryRow(o.ctx, "select lo_tell64($1)", o.fd).Scan(&n)
return n, err
}
// Truncate the large object to size.
func (o *LargeObject) Truncate(size int64) (err error) {
_, err = o.tx.Exec(o.ctx, "select lo_truncate64($1, $2)", o.fd, size)
return err
}
// Close the large object descriptor.
func (o *LargeObject) Close() error {
_, err := o.tx.Exec(o.ctx, "select lo_close($1)", o.fd)
return err
}
+295
View File
@@ -0,0 +1,295 @@
package pgx
import (
"context"
"fmt"
"strconv"
"strings"
"unicode/utf8"
)
// NamedArgs can be used as the first argument to a query method. It will replace every '@' named placeholder with a '$'
// ordinal placeholder and construct the appropriate arguments.
//
// For example, the following two queries are equivalent:
//
// conn.Query(ctx, "select * from widgets where foo = @foo and bar = @bar", pgx.NamedArgs{"foo": 1, "bar": 2})
// conn.Query(ctx, "select * from widgets where foo = $1 and bar = $2", 1, 2)
//
// Named placeholders are case sensitive and must start with a letter or underscore. Subsequent characters can be
// letters, numbers, or underscores.
type NamedArgs map[string]any
// RewriteQuery implements the QueryRewriter interface.
func (na NamedArgs) RewriteQuery(ctx context.Context, conn *Conn, sql string, args []any) (newSQL string, newArgs []any, err error) {
return rewriteQuery(na, sql, false)
}
// StrictNamedArgs can be used in the same way as NamedArgs, but provided arguments are also checked to include all
// named arguments that the sql query uses, and no extra arguments.
type StrictNamedArgs map[string]any
// RewriteQuery implements the QueryRewriter interface.
func (sna StrictNamedArgs) RewriteQuery(ctx context.Context, conn *Conn, sql string, args []any) (newSQL string, newArgs []any, err error) {
return rewriteQuery(sna, sql, true)
}
type namedArg string
type sqlLexer struct {
src string
start int
pos int
nested int // multiline comment nesting level.
stateFn stateFn
parts []any
nameToOrdinal map[namedArg]int
}
type stateFn func(*sqlLexer) stateFn
func rewriteQuery(na map[string]any, sql string, isStrict bool) (newSQL string, newArgs []any, err error) {
l := &sqlLexer{
src: sql,
stateFn: rawState,
nameToOrdinal: make(map[namedArg]int, len(na)),
}
for l.stateFn != nil {
l.stateFn = l.stateFn(l)
}
sb := strings.Builder{}
for _, p := range l.parts {
switch p := p.(type) {
case string:
sb.WriteString(p)
case namedArg:
sb.WriteRune('$')
sb.WriteString(strconv.Itoa(l.nameToOrdinal[p]))
}
}
newArgs = make([]any, len(l.nameToOrdinal))
for name, ordinal := range l.nameToOrdinal {
var found bool
newArgs[ordinal-1], found = na[string(name)]
if isStrict && !found {
return "", nil, fmt.Errorf("argument %s found in sql query but not present in StrictNamedArgs", name)
}
}
if isStrict {
for name := range na {
if _, found := l.nameToOrdinal[namedArg(name)]; !found {
return "", nil, fmt.Errorf("argument %s of StrictNamedArgs not found in sql query", name)
}
}
}
return sb.String(), newArgs, nil
}
func rawState(l *sqlLexer) stateFn {
for {
r, width := utf8.DecodeRuneInString(l.src[l.pos:])
l.pos += width
switch r {
case 'e', 'E':
nextRune, width := utf8.DecodeRuneInString(l.src[l.pos:])
if nextRune == '\'' {
l.pos += width
return escapeStringState
}
case '\'':
return singleQuoteState
case '"':
return doubleQuoteState
case '@':
nextRune, _ := utf8.DecodeRuneInString(l.src[l.pos:])
if isLetter(nextRune) || nextRune == '_' {
if l.pos-l.start > 0 {
l.parts = append(l.parts, l.src[l.start:l.pos-width])
}
l.start = l.pos
return namedArgState
}
case '-':
nextRune, width := utf8.DecodeRuneInString(l.src[l.pos:])
if nextRune == '-' {
l.pos += width
return oneLineCommentState
}
case '/':
nextRune, width := utf8.DecodeRuneInString(l.src[l.pos:])
if nextRune == '*' {
l.pos += width
return multilineCommentState
}
case utf8.RuneError:
if l.pos-l.start > 0 {
l.parts = append(l.parts, l.src[l.start:l.pos])
l.start = l.pos
}
return nil
}
}
}
func isLetter(r rune) bool {
return (r >= 'a' && r <= 'z') || (r >= 'A' && r <= 'Z')
}
func namedArgState(l *sqlLexer) stateFn {
for {
r, width := utf8.DecodeRuneInString(l.src[l.pos:])
l.pos += width
if r == utf8.RuneError {
if l.pos-l.start > 0 {
na := namedArg(l.src[l.start:l.pos])
if _, found := l.nameToOrdinal[na]; !found {
l.nameToOrdinal[na] = len(l.nameToOrdinal) + 1
}
l.parts = append(l.parts, na)
l.start = l.pos
}
return nil
} else if !(isLetter(r) || (r >= '0' && r <= '9') || r == '_') {
l.pos -= width
na := namedArg(l.src[l.start:l.pos])
if _, found := l.nameToOrdinal[na]; !found {
l.nameToOrdinal[na] = len(l.nameToOrdinal) + 1
}
l.parts = append(l.parts, namedArg(na))
l.start = l.pos
return rawState
}
}
}
func singleQuoteState(l *sqlLexer) stateFn {
for {
r, width := utf8.DecodeRuneInString(l.src[l.pos:])
l.pos += width
switch r {
case '\'':
nextRune, width := utf8.DecodeRuneInString(l.src[l.pos:])
if nextRune != '\'' {
return rawState
}
l.pos += width
case utf8.RuneError:
if l.pos-l.start > 0 {
l.parts = append(l.parts, l.src[l.start:l.pos])
l.start = l.pos
}
return nil
}
}
}
func doubleQuoteState(l *sqlLexer) stateFn {
for {
r, width := utf8.DecodeRuneInString(l.src[l.pos:])
l.pos += width
switch r {
case '"':
nextRune, width := utf8.DecodeRuneInString(l.src[l.pos:])
if nextRune != '"' {
return rawState
}
l.pos += width
case utf8.RuneError:
if l.pos-l.start > 0 {
l.parts = append(l.parts, l.src[l.start:l.pos])
l.start = l.pos
}
return nil
}
}
}
func escapeStringState(l *sqlLexer) stateFn {
for {
r, width := utf8.DecodeRuneInString(l.src[l.pos:])
l.pos += width
switch r {
case '\\':
_, width = utf8.DecodeRuneInString(l.src[l.pos:])
l.pos += width
case '\'':
nextRune, width := utf8.DecodeRuneInString(l.src[l.pos:])
if nextRune != '\'' {
return rawState
}
l.pos += width
case utf8.RuneError:
if l.pos-l.start > 0 {
l.parts = append(l.parts, l.src[l.start:l.pos])
l.start = l.pos
}
return nil
}
}
}
func oneLineCommentState(l *sqlLexer) stateFn {
for {
r, width := utf8.DecodeRuneInString(l.src[l.pos:])
l.pos += width
switch r {
case '\\':
_, width = utf8.DecodeRuneInString(l.src[l.pos:])
l.pos += width
case '\n', '\r':
return rawState
case utf8.RuneError:
if l.pos-l.start > 0 {
l.parts = append(l.parts, l.src[l.start:l.pos])
l.start = l.pos
}
return nil
}
}
}
func multilineCommentState(l *sqlLexer) stateFn {
for {
r, width := utf8.DecodeRuneInString(l.src[l.pos:])
l.pos += width
switch r {
case '/':
nextRune, width := utf8.DecodeRuneInString(l.src[l.pos:])
if nextRune == '*' {
l.pos += width
l.nested++
}
case '*':
nextRune, width := utf8.DecodeRuneInString(l.src[l.pos:])
if nextRune != '/' {
continue
}
l.pos += width
if l.nested == 0 {
return rawState
}
l.nested--
case utf8.RuneError:
if l.pos-l.start > 0 {
l.parts = append(l.parts, l.src[l.start:l.pos])
l.start = l.pos
}
return nil
}
}
}
+29
View File
@@ -0,0 +1,29 @@
# pgconn
Package pgconn is a low-level PostgreSQL database driver. It operates at nearly the same level as the C library libpq.
It is primarily intended to serve as the foundation for higher level libraries such as https://github.com/jackc/pgx.
Applications should handle normal queries with a higher level library and only use pgconn directly when required for
low-level access to PostgreSQL functionality.
## Example Usage
```go
pgConn, err := pgconn.Connect(context.Background(), os.Getenv("DATABASE_URL"))
if err != nil {
log.Fatalln("pgconn failed to connect:", err)
}
defer pgConn.Close(context.Background())
result := pgConn.ExecParams(context.Background(), "SELECT email FROM users WHERE id=$1", [][]byte{[]byte("123")}, nil, nil, nil)
for result.NextRow() {
fmt.Println("User 123 has email:", string(result.Values()[0]))
}
_, err = result.Close()
if err != nil {
log.Fatalln("failed reading result:", err)
}
```
## Testing
See CONTRIBUTING.md for setup instructions.
+272
View File
@@ -0,0 +1,272 @@
// SCRAM-SHA-256 authentication
//
// Resources:
// https://tools.ietf.org/html/rfc5802
// https://tools.ietf.org/html/rfc8265
// https://www.postgresql.org/docs/current/sasl-authentication.html
//
// Inspiration drawn from other implementations:
// https://github.com/lib/pq/pull/608
// https://github.com/lib/pq/pull/788
// https://github.com/lib/pq/pull/833
package pgconn
import (
"bytes"
"crypto/hmac"
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"errors"
"fmt"
"strconv"
"github.com/jackc/pgx/v5/pgproto3"
"golang.org/x/crypto/pbkdf2"
"golang.org/x/text/secure/precis"
)
const clientNonceLen = 18
// Perform SCRAM authentication.
func (c *PgConn) scramAuth(serverAuthMechanisms []string) error {
sc, err := newScramClient(serverAuthMechanisms, c.config.Password)
if err != nil {
return err
}
// Send client-first-message in a SASLInitialResponse
saslInitialResponse := &pgproto3.SASLInitialResponse{
AuthMechanism: "SCRAM-SHA-256",
Data: sc.clientFirstMessage(),
}
c.frontend.Send(saslInitialResponse)
err = c.flushWithPotentialWriteReadDeadlock()
if err != nil {
return err
}
// Receive server-first-message payload in an AuthenticationSASLContinue.
saslContinue, err := c.rxSASLContinue()
if err != nil {
return err
}
err = sc.recvServerFirstMessage(saslContinue.Data)
if err != nil {
return err
}
// Send client-final-message in a SASLResponse
saslResponse := &pgproto3.SASLResponse{
Data: []byte(sc.clientFinalMessage()),
}
c.frontend.Send(saslResponse)
err = c.flushWithPotentialWriteReadDeadlock()
if err != nil {
return err
}
// Receive server-final-message payload in an AuthenticationSASLFinal.
saslFinal, err := c.rxSASLFinal()
if err != nil {
return err
}
return sc.recvServerFinalMessage(saslFinal.Data)
}
func (c *PgConn) rxSASLContinue() (*pgproto3.AuthenticationSASLContinue, error) {
msg, err := c.receiveMessage()
if err != nil {
return nil, err
}
switch m := msg.(type) {
case *pgproto3.AuthenticationSASLContinue:
return m, nil
case *pgproto3.ErrorResponse:
return nil, ErrorResponseToPgError(m)
}
return nil, fmt.Errorf("expected AuthenticationSASLContinue message but received unexpected message %T", msg)
}
func (c *PgConn) rxSASLFinal() (*pgproto3.AuthenticationSASLFinal, error) {
msg, err := c.receiveMessage()
if err != nil {
return nil, err
}
switch m := msg.(type) {
case *pgproto3.AuthenticationSASLFinal:
return m, nil
case *pgproto3.ErrorResponse:
return nil, ErrorResponseToPgError(m)
}
return nil, fmt.Errorf("expected AuthenticationSASLFinal message but received unexpected message %T", msg)
}
type scramClient struct {
serverAuthMechanisms []string
password []byte
clientNonce []byte
clientFirstMessageBare []byte
serverFirstMessage []byte
clientAndServerNonce []byte
salt []byte
iterations int
saltedPassword []byte
authMessage []byte
}
func newScramClient(serverAuthMechanisms []string, password string) (*scramClient, error) {
sc := &scramClient{
serverAuthMechanisms: serverAuthMechanisms,
}
// Ensure server supports SCRAM-SHA-256
hasScramSHA256 := false
for _, mech := range sc.serverAuthMechanisms {
if mech == "SCRAM-SHA-256" {
hasScramSHA256 = true
break
}
}
if !hasScramSHA256 {
return nil, errors.New("server does not support SCRAM-SHA-256")
}
// precis.OpaqueString is equivalent to SASLprep for password.
var err error
sc.password, err = precis.OpaqueString.Bytes([]byte(password))
if err != nil {
// PostgreSQL allows passwords invalid according to SCRAM / SASLprep.
sc.password = []byte(password)
}
buf := make([]byte, clientNonceLen)
_, err = rand.Read(buf)
if err != nil {
return nil, err
}
sc.clientNonce = make([]byte, base64.RawStdEncoding.EncodedLen(len(buf)))
base64.RawStdEncoding.Encode(sc.clientNonce, buf)
return sc, nil
}
func (sc *scramClient) clientFirstMessage() []byte {
sc.clientFirstMessageBare = []byte(fmt.Sprintf("n=,r=%s", sc.clientNonce))
return []byte(fmt.Sprintf("n,,%s", sc.clientFirstMessageBare))
}
func (sc *scramClient) recvServerFirstMessage(serverFirstMessage []byte) error {
sc.serverFirstMessage = serverFirstMessage
buf := serverFirstMessage
if !bytes.HasPrefix(buf, []byte("r=")) {
return errors.New("invalid SCRAM server-first-message received from server: did not include r=")
}
buf = buf[2:]
idx := bytes.IndexByte(buf, ',')
if idx == -1 {
return errors.New("invalid SCRAM server-first-message received from server: did not include s=")
}
sc.clientAndServerNonce = buf[:idx]
buf = buf[idx+1:]
if !bytes.HasPrefix(buf, []byte("s=")) {
return errors.New("invalid SCRAM server-first-message received from server: did not include s=")
}
buf = buf[2:]
idx = bytes.IndexByte(buf, ',')
if idx == -1 {
return errors.New("invalid SCRAM server-first-message received from server: did not include i=")
}
saltStr := buf[:idx]
buf = buf[idx+1:]
if !bytes.HasPrefix(buf, []byte("i=")) {
return errors.New("invalid SCRAM server-first-message received from server: did not include i=")
}
buf = buf[2:]
iterationsStr := buf
var err error
sc.salt, err = base64.StdEncoding.DecodeString(string(saltStr))
if err != nil {
return fmt.Errorf("invalid SCRAM salt received from server: %w", err)
}
sc.iterations, err = strconv.Atoi(string(iterationsStr))
if err != nil || sc.iterations <= 0 {
return fmt.Errorf("invalid SCRAM iteration count received from server: %w", err)
}
if !bytes.HasPrefix(sc.clientAndServerNonce, sc.clientNonce) {
return errors.New("invalid SCRAM nonce: did not start with client nonce")
}
if len(sc.clientAndServerNonce) <= len(sc.clientNonce) {
return errors.New("invalid SCRAM nonce: did not include server nonce")
}
return nil
}
func (sc *scramClient) clientFinalMessage() string {
clientFinalMessageWithoutProof := []byte(fmt.Sprintf("c=biws,r=%s", sc.clientAndServerNonce))
sc.saltedPassword = pbkdf2.Key([]byte(sc.password), sc.salt, sc.iterations, 32, sha256.New)
sc.authMessage = bytes.Join([][]byte{sc.clientFirstMessageBare, sc.serverFirstMessage, clientFinalMessageWithoutProof}, []byte(","))
clientProof := computeClientProof(sc.saltedPassword, sc.authMessage)
return fmt.Sprintf("%s,p=%s", clientFinalMessageWithoutProof, clientProof)
}
func (sc *scramClient) recvServerFinalMessage(serverFinalMessage []byte) error {
if !bytes.HasPrefix(serverFinalMessage, []byte("v=")) {
return errors.New("invalid SCRAM server-final-message received from server")
}
serverSignature := serverFinalMessage[2:]
if !hmac.Equal(serverSignature, computeServerSignature(sc.saltedPassword, sc.authMessage)) {
return errors.New("invalid SCRAM ServerSignature received from server")
}
return nil
}
func computeHMAC(key, msg []byte) []byte {
mac := hmac.New(sha256.New, key)
mac.Write(msg)
return mac.Sum(nil)
}
func computeClientProof(saltedPassword, authMessage []byte) []byte {
clientKey := computeHMAC(saltedPassword, []byte("Client Key"))
storedKey := sha256.Sum256(clientKey)
clientSignature := computeHMAC(storedKey[:], authMessage)
clientProof := make([]byte, len(clientSignature))
for i := 0; i < len(clientSignature); i++ {
clientProof[i] = clientKey[i] ^ clientSignature[i]
}
buf := make([]byte, base64.StdEncoding.EncodedLen(len(clientProof)))
base64.StdEncoding.Encode(buf, clientProof)
return buf
}
func computeServerSignature(saltedPassword []byte, authMessage []byte) []byte {
serverKey := computeHMAC(saltedPassword, []byte("Server Key"))
serverSignature := computeHMAC(serverKey, authMessage)
buf := make([]byte, base64.StdEncoding.EncodedLen(len(serverSignature)))
base64.StdEncoding.Encode(buf, serverSignature)
return buf
}
+934
View File
@@ -0,0 +1,934 @@
package pgconn
import (
"context"
"crypto/tls"
"crypto/x509"
"encoding/pem"
"errors"
"fmt"
"io"
"math"
"net"
"net/url"
"os"
"path/filepath"
"strconv"
"strings"
"time"
"github.com/jackc/pgpassfile"
"github.com/jackc/pgservicefile"
"github.com/jackc/pgx/v5/pgconn/ctxwatch"
"github.com/jackc/pgx/v5/pgproto3"
)
type AfterConnectFunc func(ctx context.Context, pgconn *PgConn) error
type ValidateConnectFunc func(ctx context.Context, pgconn *PgConn) error
type GetSSLPasswordFunc func(ctx context.Context) string
// Config is the settings used to establish a connection to a PostgreSQL server. It must be created by [ParseConfig]. A
// manually initialized Config will cause ConnectConfig to panic.
type Config struct {
Host string // host (e.g. localhost) or absolute path to unix domain socket directory (e.g. /private/tmp)
Port uint16
Database string
User string
Password string
TLSConfig *tls.Config // nil disables TLS
ConnectTimeout time.Duration
DialFunc DialFunc // e.g. net.Dialer.DialContext
LookupFunc LookupFunc // e.g. net.Resolver.LookupHost
BuildFrontend BuildFrontendFunc
// BuildContextWatcherHandler is called to create a ContextWatcherHandler for a connection. The handler is called
// when a context passed to a PgConn method is canceled.
BuildContextWatcherHandler func(*PgConn) ctxwatch.Handler
RuntimeParams map[string]string // Run-time parameters to set on connection as session default values (e.g. search_path or application_name)
KerberosSrvName string
KerberosSpn string
Fallbacks []*FallbackConfig
// ValidateConnect is called during a connection attempt after a successful authentication with the PostgreSQL server.
// It can be used to validate that the server is acceptable. If this returns an error the connection is closed and the next
// fallback config is tried. This allows implementing high availability behavior such as libpq does with target_session_attrs.
ValidateConnect ValidateConnectFunc
// AfterConnect is called after ValidateConnect. It can be used to set up the connection (e.g. Set session variables
// or prepare statements). If this returns an error the connection attempt fails.
AfterConnect AfterConnectFunc
// OnNotice is a callback function called when a notice response is received.
OnNotice NoticeHandler
// OnNotification is a callback function called when a notification from the LISTEN/NOTIFY system is received.
OnNotification NotificationHandler
// OnPgError is a callback function called when a Postgres error is received by the server. The default handler will close
// the connection on any FATAL errors. If you override this handler you should call the previously set handler or ensure
// that you close on FATAL errors by returning false.
OnPgError PgErrorHandler
createdByParseConfig bool // Used to enforce created by ParseConfig rule.
}
// ParseConfigOptions contains options that control how a config is built such as GetSSLPassword.
type ParseConfigOptions struct {
// GetSSLPassword gets the password to decrypt a SSL client certificate. This is analogous to the libpq function
// PQsetSSLKeyPassHook_OpenSSL.
GetSSLPassword GetSSLPasswordFunc
}
// Copy returns a deep copy of the config that is safe to use and modify.
// The only exception is the TLSConfig field:
// according to the tls.Config docs it must not be modified after creation.
func (c *Config) Copy() *Config {
newConf := new(Config)
*newConf = *c
if newConf.TLSConfig != nil {
newConf.TLSConfig = c.TLSConfig.Clone()
}
if newConf.RuntimeParams != nil {
newConf.RuntimeParams = make(map[string]string, len(c.RuntimeParams))
for k, v := range c.RuntimeParams {
newConf.RuntimeParams[k] = v
}
}
if newConf.Fallbacks != nil {
newConf.Fallbacks = make([]*FallbackConfig, len(c.Fallbacks))
for i, fallback := range c.Fallbacks {
newFallback := new(FallbackConfig)
*newFallback = *fallback
if newFallback.TLSConfig != nil {
newFallback.TLSConfig = fallback.TLSConfig.Clone()
}
newConf.Fallbacks[i] = newFallback
}
}
return newConf
}
// FallbackConfig is additional settings to attempt a connection with when the primary Config fails to establish a
// network connection. It is used for TLS fallback such as sslmode=prefer and high availability (HA) connections.
type FallbackConfig struct {
Host string // host (e.g. localhost) or path to unix domain socket directory (e.g. /private/tmp)
Port uint16
TLSConfig *tls.Config // nil disables TLS
}
// connectOneConfig is the configuration for a single attempt to connect to a single host.
type connectOneConfig struct {
network string
address string
originalHostname string // original hostname before resolving
tlsConfig *tls.Config // nil disables TLS
}
// isAbsolutePath checks if the provided value is an absolute path either
// beginning with a forward slash (as on Linux-based systems) or with a capital
// letter A-Z followed by a colon and a backslash, e.g., "C:\", (as on Windows).
func isAbsolutePath(path string) bool {
isWindowsPath := func(p string) bool {
if len(p) < 3 {
return false
}
drive := p[0]
colon := p[1]
backslash := p[2]
if drive >= 'A' && drive <= 'Z' && colon == ':' && backslash == '\\' {
return true
}
return false
}
return strings.HasPrefix(path, "/") || isWindowsPath(path)
}
// NetworkAddress converts a PostgreSQL host and port into network and address suitable for use with
// net.Dial.
func NetworkAddress(host string, port uint16) (network, address string) {
if isAbsolutePath(host) {
network = "unix"
address = filepath.Join(host, ".s.PGSQL.") + strconv.FormatInt(int64(port), 10)
} else {
network = "tcp"
address = net.JoinHostPort(host, strconv.Itoa(int(port)))
}
return network, address
}
// ParseConfig builds a *Config from connString with similar behavior to the PostgreSQL standard C library libpq. It
// uses the same defaults as libpq (e.g. port=5432) and understands most PG* environment variables. ParseConfig closely
// matches the parsing behavior of libpq. connString may either be in URL format or keyword = value format. See
// https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-CONNSTRING for details. connString also may be empty
// to only read from the environment. If a password is not supplied it will attempt to read the .pgpass file.
//
// # Example Keyword/Value
// user=jack password=secret host=pg.example.com port=5432 dbname=mydb sslmode=verify-ca
//
// # Example URL
// postgres://jack:secret@pg.example.com:5432/mydb?sslmode=verify-ca
//
// The returned *Config may be modified. However, it is strongly recommended that any configuration that can be done
// through the connection string be done there. In particular the fields Host, Port, TLSConfig, and Fallbacks can be
// interdependent (e.g. TLSConfig needs knowledge of the host to validate the server certificate). These fields should
// not be modified individually. They should all be modified or all left unchanged.
//
// ParseConfig supports specifying multiple hosts in similar manner to libpq. Host and port may include comma separated
// values that will be tried in order. This can be used as part of a high availability system. See
// https://www.postgresql.org/docs/11/libpq-connect.html#LIBPQ-MULTIPLE-HOSTS for more information.
//
// # Example URL
// postgres://jack:secret@foo.example.com:5432,bar.example.com:5432/mydb
//
// ParseConfig currently recognizes the following environment variable and their parameter key word equivalents passed
// via database URL or keyword/value:
//
// PGHOST
// PGPORT
// PGDATABASE
// PGUSER
// PGPASSWORD
// PGPASSFILE
// PGSERVICE
// PGSERVICEFILE
// PGSSLMODE
// PGSSLCERT
// PGSSLKEY
// PGSSLROOTCERT
// PGSSLPASSWORD
// PGAPPNAME
// PGCONNECT_TIMEOUT
// PGTARGETSESSIONATTRS
//
// See http://www.postgresql.org/docs/11/static/libpq-envars.html for details on the meaning of environment variables.
//
// See https://www.postgresql.org/docs/11/libpq-connect.html#LIBPQ-PARAMKEYWORDS for parameter key word names. They are
// usually but not always the environment variable name downcased and without the "PG" prefix.
//
// Important Security Notes:
//
// ParseConfig tries to match libpq behavior with regard to PGSSLMODE. This includes defaulting to "prefer" behavior if
// not set.
//
// See http://www.postgresql.org/docs/11/static/libpq-ssl.html#LIBPQ-SSL-PROTECTION for details on what level of
// security each sslmode provides.
//
// The sslmode "prefer" (the default), sslmode "allow", and multiple hosts are implemented via the Fallbacks field of
// the Config struct. If TLSConfig is manually changed it will not affect the fallbacks. For example, in the case of
// sslmode "prefer" this means it will first try the main Config settings which use TLS, then it will try the fallback
// which does not use TLS. This can lead to an unexpected unencrypted connection if the main TLS config is manually
// changed later but the unencrypted fallback is present. Ensure there are no stale fallbacks when manually setting
// TLSConfig.
//
// Other known differences with libpq:
//
// When multiple hosts are specified, libpq allows them to have different passwords set via the .pgpass file. pgconn
// does not.
//
// In addition, ParseConfig accepts the following options:
//
// - servicefile.
// libpq only reads servicefile from the PGSERVICEFILE environment variable. ParseConfig accepts servicefile as a
// part of the connection string.
func ParseConfig(connString string) (*Config, error) {
var parseConfigOptions ParseConfigOptions
return ParseConfigWithOptions(connString, parseConfigOptions)
}
// ParseConfigWithOptions builds a *Config from connString and options with similar behavior to the PostgreSQL standard
// C library libpq. options contains settings that cannot be specified in a connString such as providing a function to
// get the SSL password.
func ParseConfigWithOptions(connString string, options ParseConfigOptions) (*Config, error) {
defaultSettings := defaultSettings()
envSettings := parseEnvSettings()
connStringSettings := make(map[string]string)
if connString != "" {
var err error
// connString may be a database URL or in PostgreSQL keyword/value format
if strings.HasPrefix(connString, "postgres://") || strings.HasPrefix(connString, "postgresql://") {
connStringSettings, err = parseURLSettings(connString)
if err != nil {
return nil, &ParseConfigError{ConnString: connString, msg: "failed to parse as URL", err: err}
}
} else {
connStringSettings, err = parseKeywordValueSettings(connString)
if err != nil {
return nil, &ParseConfigError{ConnString: connString, msg: "failed to parse as keyword/value", err: err}
}
}
}
settings := mergeSettings(defaultSettings, envSettings, connStringSettings)
if service, present := settings["service"]; present {
serviceSettings, err := parseServiceSettings(settings["servicefile"], service)
if err != nil {
return nil, &ParseConfigError{ConnString: connString, msg: "failed to read service", err: err}
}
settings = mergeSettings(defaultSettings, envSettings, serviceSettings, connStringSettings)
}
config := &Config{
createdByParseConfig: true,
Database: settings["database"],
User: settings["user"],
Password: settings["password"],
RuntimeParams: make(map[string]string),
BuildFrontend: func(r io.Reader, w io.Writer) *pgproto3.Frontend {
return pgproto3.NewFrontend(r, w)
},
BuildContextWatcherHandler: func(pgConn *PgConn) ctxwatch.Handler {
return &DeadlineContextWatcherHandler{Conn: pgConn.conn}
},
OnPgError: func(_ *PgConn, pgErr *PgError) bool {
// we want to automatically close any fatal errors
if strings.EqualFold(pgErr.Severity, "FATAL") {
return false
}
return true
},
}
if connectTimeoutSetting, present := settings["connect_timeout"]; present {
connectTimeout, err := parseConnectTimeoutSetting(connectTimeoutSetting)
if err != nil {
return nil, &ParseConfigError{ConnString: connString, msg: "invalid connect_timeout", err: err}
}
config.ConnectTimeout = connectTimeout
config.DialFunc = makeConnectTimeoutDialFunc(connectTimeout)
} else {
defaultDialer := makeDefaultDialer()
config.DialFunc = defaultDialer.DialContext
}
config.LookupFunc = makeDefaultResolver().LookupHost
notRuntimeParams := map[string]struct{}{
"host": {},
"port": {},
"database": {},
"user": {},
"password": {},
"passfile": {},
"connect_timeout": {},
"sslmode": {},
"sslkey": {},
"sslcert": {},
"sslrootcert": {},
"sslpassword": {},
"sslsni": {},
"krbspn": {},
"krbsrvname": {},
"target_session_attrs": {},
"service": {},
"servicefile": {},
}
// Adding kerberos configuration
if _, present := settings["krbsrvname"]; present {
config.KerberosSrvName = settings["krbsrvname"]
}
if _, present := settings["krbspn"]; present {
config.KerberosSpn = settings["krbspn"]
}
for k, v := range settings {
if _, present := notRuntimeParams[k]; present {
continue
}
config.RuntimeParams[k] = v
}
fallbacks := []*FallbackConfig{}
hosts := strings.Split(settings["host"], ",")
ports := strings.Split(settings["port"], ",")
for i, host := range hosts {
var portStr string
if i < len(ports) {
portStr = ports[i]
} else {
portStr = ports[0]
}
port, err := parsePort(portStr)
if err != nil {
return nil, &ParseConfigError{ConnString: connString, msg: "invalid port", err: err}
}
var tlsConfigs []*tls.Config
// Ignore TLS settings if Unix domain socket like libpq
if network, _ := NetworkAddress(host, port); network == "unix" {
tlsConfigs = append(tlsConfigs, nil)
} else {
var err error
tlsConfigs, err = configTLS(settings, host, options)
if err != nil {
return nil, &ParseConfigError{ConnString: connString, msg: "failed to configure TLS", err: err}
}
}
for _, tlsConfig := range tlsConfigs {
fallbacks = append(fallbacks, &FallbackConfig{
Host: host,
Port: port,
TLSConfig: tlsConfig,
})
}
}
config.Host = fallbacks[0].Host
config.Port = fallbacks[0].Port
config.TLSConfig = fallbacks[0].TLSConfig
config.Fallbacks = fallbacks[1:]
passfile, err := pgpassfile.ReadPassfile(settings["passfile"])
if err == nil {
if config.Password == "" {
host := config.Host
if network, _ := NetworkAddress(config.Host, config.Port); network == "unix" {
host = "localhost"
}
config.Password = passfile.FindPassword(host, strconv.Itoa(int(config.Port)), config.Database, config.User)
}
}
switch tsa := settings["target_session_attrs"]; tsa {
case "read-write":
config.ValidateConnect = ValidateConnectTargetSessionAttrsReadWrite
case "read-only":
config.ValidateConnect = ValidateConnectTargetSessionAttrsReadOnly
case "primary":
config.ValidateConnect = ValidateConnectTargetSessionAttrsPrimary
case "standby":
config.ValidateConnect = ValidateConnectTargetSessionAttrsStandby
case "prefer-standby":
config.ValidateConnect = ValidateConnectTargetSessionAttrsPreferStandby
case "any":
// do nothing
default:
return nil, &ParseConfigError{ConnString: connString, msg: fmt.Sprintf("unknown target_session_attrs value: %v", tsa)}
}
return config, nil
}
func mergeSettings(settingSets ...map[string]string) map[string]string {
settings := make(map[string]string)
for _, s2 := range settingSets {
for k, v := range s2 {
settings[k] = v
}
}
return settings
}
func parseEnvSettings() map[string]string {
settings := make(map[string]string)
nameMap := map[string]string{
"PGHOST": "host",
"PGPORT": "port",
"PGDATABASE": "database",
"PGUSER": "user",
"PGPASSWORD": "password",
"PGPASSFILE": "passfile",
"PGAPPNAME": "application_name",
"PGCONNECT_TIMEOUT": "connect_timeout",
"PGSSLMODE": "sslmode",
"PGSSLKEY": "sslkey",
"PGSSLCERT": "sslcert",
"PGSSLSNI": "sslsni",
"PGSSLROOTCERT": "sslrootcert",
"PGSSLPASSWORD": "sslpassword",
"PGTARGETSESSIONATTRS": "target_session_attrs",
"PGSERVICE": "service",
"PGSERVICEFILE": "servicefile",
}
for envname, realname := range nameMap {
value := os.Getenv(envname)
if value != "" {
settings[realname] = value
}
}
return settings
}
func parseURLSettings(connString string) (map[string]string, error) {
settings := make(map[string]string)
parsedURL, err := url.Parse(connString)
if err != nil {
if urlErr := new(url.Error); errors.As(err, &urlErr) {
return nil, urlErr.Err
}
return nil, err
}
if parsedURL.User != nil {
settings["user"] = parsedURL.User.Username()
if password, present := parsedURL.User.Password(); present {
settings["password"] = password
}
}
// Handle multiple host:port's in url.Host by splitting them into host,host,host and port,port,port.
var hosts []string
var ports []string
for _, host := range strings.Split(parsedURL.Host, ",") {
if host == "" {
continue
}
if isIPOnly(host) {
hosts = append(hosts, strings.Trim(host, "[]"))
continue
}
h, p, err := net.SplitHostPort(host)
if err != nil {
return nil, fmt.Errorf("failed to split host:port in '%s', err: %w", host, err)
}
if h != "" {
hosts = append(hosts, h)
}
if p != "" {
ports = append(ports, p)
}
}
if len(hosts) > 0 {
settings["host"] = strings.Join(hosts, ",")
}
if len(ports) > 0 {
settings["port"] = strings.Join(ports, ",")
}
database := strings.TrimLeft(parsedURL.Path, "/")
if database != "" {
settings["database"] = database
}
nameMap := map[string]string{
"dbname": "database",
}
for k, v := range parsedURL.Query() {
if k2, present := nameMap[k]; present {
k = k2
}
settings[k] = v[0]
}
return settings, nil
}
func isIPOnly(host string) bool {
return net.ParseIP(strings.Trim(host, "[]")) != nil || !strings.Contains(host, ":")
}
var asciiSpace = [256]uint8{'\t': 1, '\n': 1, '\v': 1, '\f': 1, '\r': 1, ' ': 1}
func parseKeywordValueSettings(s string) (map[string]string, error) {
settings := make(map[string]string)
nameMap := map[string]string{
"dbname": "database",
}
for len(s) > 0 {
var key, val string
eqIdx := strings.IndexRune(s, '=')
if eqIdx < 0 {
return nil, errors.New("invalid keyword/value")
}
key = strings.Trim(s[:eqIdx], " \t\n\r\v\f")
s = strings.TrimLeft(s[eqIdx+1:], " \t\n\r\v\f")
if len(s) == 0 {
} else if s[0] != '\'' {
end := 0
for ; end < len(s); end++ {
if asciiSpace[s[end]] == 1 {
break
}
if s[end] == '\\' {
end++
if end == len(s) {
return nil, errors.New("invalid backslash")
}
}
}
val = strings.Replace(strings.Replace(s[:end], "\\\\", "\\", -1), "\\'", "'", -1)
if end == len(s) {
s = ""
} else {
s = s[end+1:]
}
} else { // quoted string
s = s[1:]
end := 0
for ; end < len(s); end++ {
if s[end] == '\'' {
break
}
if s[end] == '\\' {
end++
}
}
if end == len(s) {
return nil, errors.New("unterminated quoted string in connection info string")
}
val = strings.Replace(strings.Replace(s[:end], "\\\\", "\\", -1), "\\'", "'", -1)
if end == len(s) {
s = ""
} else {
s = s[end+1:]
}
}
if k, ok := nameMap[key]; ok {
key = k
}
if key == "" {
return nil, errors.New("invalid keyword/value")
}
settings[key] = val
}
return settings, nil
}
func parseServiceSettings(servicefilePath, serviceName string) (map[string]string, error) {
servicefile, err := pgservicefile.ReadServicefile(servicefilePath)
if err != nil {
return nil, fmt.Errorf("failed to read service file: %v", servicefilePath)
}
service, err := servicefile.GetService(serviceName)
if err != nil {
return nil, fmt.Errorf("unable to find service: %v", serviceName)
}
nameMap := map[string]string{
"dbname": "database",
}
settings := make(map[string]string, len(service.Settings))
for k, v := range service.Settings {
if k2, present := nameMap[k]; present {
k = k2
}
settings[k] = v
}
return settings, nil
}
// configTLS uses libpq's TLS parameters to construct []*tls.Config. It is
// necessary to allow returning multiple TLS configs as sslmode "allow" and
// "prefer" allow fallback.
func configTLS(settings map[string]string, thisHost string, parseConfigOptions ParseConfigOptions) ([]*tls.Config, error) {
host := thisHost
sslmode := settings["sslmode"]
sslrootcert := settings["sslrootcert"]
sslcert := settings["sslcert"]
sslkey := settings["sslkey"]
sslpassword := settings["sslpassword"]
sslsni := settings["sslsni"]
// Match libpq default behavior
if sslmode == "" {
sslmode = "prefer"
}
if sslsni == "" {
sslsni = "1"
}
tlsConfig := &tls.Config{}
if sslrootcert != "" {
var caCertPool *x509.CertPool
if sslrootcert == "system" {
var err error
caCertPool, err = x509.SystemCertPool()
if err != nil {
return nil, fmt.Errorf("unable to load system certificate pool: %w", err)
}
sslmode = "verify-full"
} else {
caCertPool = x509.NewCertPool()
caPath := sslrootcert
caCert, err := os.ReadFile(caPath)
if err != nil {
return nil, fmt.Errorf("unable to read CA file: %w", err)
}
if !caCertPool.AppendCertsFromPEM(caCert) {
return nil, errors.New("unable to add CA to cert pool")
}
}
tlsConfig.RootCAs = caCertPool
tlsConfig.ClientCAs = caCertPool
}
switch sslmode {
case "disable":
return []*tls.Config{nil}, nil
case "allow", "prefer":
tlsConfig.InsecureSkipVerify = true
case "require":
// According to PostgreSQL documentation, if a root CA file exists,
// the behavior of sslmode=require should be the same as that of verify-ca
//
// See https://www.postgresql.org/docs/12/libpq-ssl.html
if sslrootcert != "" {
goto nextCase
}
tlsConfig.InsecureSkipVerify = true
break
nextCase:
fallthrough
case "verify-ca":
// Don't perform the default certificate verification because it
// will verify the hostname. Instead, verify the server's
// certificate chain ourselves in VerifyPeerCertificate and
// ignore the server name. This emulates libpq's verify-ca
// behavior.
//
// See https://github.com/golang/go/issues/21971#issuecomment-332693931
// and https://pkg.go.dev/crypto/tls?tab=doc#example-Config-VerifyPeerCertificate
// for more info.
tlsConfig.InsecureSkipVerify = true
tlsConfig.VerifyPeerCertificate = func(certificates [][]byte, _ [][]*x509.Certificate) error {
certs := make([]*x509.Certificate, len(certificates))
for i, asn1Data := range certificates {
cert, err := x509.ParseCertificate(asn1Data)
if err != nil {
return errors.New("failed to parse certificate from server: " + err.Error())
}
certs[i] = cert
}
// Leave DNSName empty to skip hostname verification.
opts := x509.VerifyOptions{
Roots: tlsConfig.RootCAs,
Intermediates: x509.NewCertPool(),
}
// Skip the first cert because it's the leaf. All others
// are intermediates.
for _, cert := range certs[1:] {
opts.Intermediates.AddCert(cert)
}
_, err := certs[0].Verify(opts)
return err
}
case "verify-full":
tlsConfig.ServerName = host
default:
return nil, errors.New("sslmode is invalid")
}
if (sslcert != "" && sslkey == "") || (sslcert == "" && sslkey != "") {
return nil, errors.New(`both "sslcert" and "sslkey" are required`)
}
if sslcert != "" && sslkey != "" {
buf, err := os.ReadFile(sslkey)
if err != nil {
return nil, fmt.Errorf("unable to read sslkey: %w", err)
}
block, _ := pem.Decode(buf)
if block == nil {
return nil, errors.New("failed to decode sslkey")
}
var pemKey []byte
var decryptedKey []byte
var decryptedError error
// If PEM is encrypted, attempt to decrypt using pass phrase
if x509.IsEncryptedPEMBlock(block) {
// Attempt decryption with pass phrase
// NOTE: only supports RSA (PKCS#1)
if sslpassword != "" {
decryptedKey, decryptedError = x509.DecryptPEMBlock(block, []byte(sslpassword))
}
//if sslpassword not provided or has decryption error when use it
//try to find sslpassword with callback function
if sslpassword == "" || decryptedError != nil {
if parseConfigOptions.GetSSLPassword != nil {
sslpassword = parseConfigOptions.GetSSLPassword(context.Background())
}
if sslpassword == "" {
return nil, fmt.Errorf("unable to find sslpassword")
}
}
decryptedKey, decryptedError = x509.DecryptPEMBlock(block, []byte(sslpassword))
// Should we also provide warning for PKCS#1 needed?
if decryptedError != nil {
return nil, fmt.Errorf("unable to decrypt key: %w", err)
}
pemBytes := pem.Block{
Type: "RSA PRIVATE KEY",
Bytes: decryptedKey,
}
pemKey = pem.EncodeToMemory(&pemBytes)
} else {
pemKey = pem.EncodeToMemory(block)
}
certfile, err := os.ReadFile(sslcert)
if err != nil {
return nil, fmt.Errorf("unable to read cert: %w", err)
}
cert, err := tls.X509KeyPair(certfile, pemKey)
if err != nil {
return nil, fmt.Errorf("unable to load cert: %w", err)
}
tlsConfig.Certificates = []tls.Certificate{cert}
}
// Set Server Name Indication (SNI), if enabled by connection parameters.
// Per RFC 6066, do not set it if the host is a literal IP address (IPv4
// or IPv6).
if sslsni == "1" && net.ParseIP(host) == nil {
tlsConfig.ServerName = host
}
switch sslmode {
case "allow":
return []*tls.Config{nil, tlsConfig}, nil
case "prefer":
return []*tls.Config{tlsConfig, nil}, nil
case "require", "verify-ca", "verify-full":
return []*tls.Config{tlsConfig}, nil
default:
panic("BUG: bad sslmode should already have been caught")
}
}
func parsePort(s string) (uint16, error) {
port, err := strconv.ParseUint(s, 10, 16)
if err != nil {
return 0, err
}
if port < 1 || port > math.MaxUint16 {
return 0, errors.New("outside range")
}
return uint16(port), nil
}
func makeDefaultDialer() *net.Dialer {
// rely on GOLANG KeepAlive settings
return &net.Dialer{}
}
func makeDefaultResolver() *net.Resolver {
return net.DefaultResolver
}
func parseConnectTimeoutSetting(s string) (time.Duration, error) {
timeout, err := strconv.ParseInt(s, 10, 64)
if err != nil {
return 0, err
}
if timeout < 0 {
return 0, errors.New("negative timeout")
}
return time.Duration(timeout) * time.Second, nil
}
func makeConnectTimeoutDialFunc(timeout time.Duration) DialFunc {
d := makeDefaultDialer()
d.Timeout = timeout
return d.DialContext
}
// ValidateConnectTargetSessionAttrsReadWrite is a ValidateConnectFunc that implements libpq compatible
// target_session_attrs=read-write.
func ValidateConnectTargetSessionAttrsReadWrite(ctx context.Context, pgConn *PgConn) error {
result, err := pgConn.Exec(ctx, "show transaction_read_only").ReadAll()
if err != nil {
return err
}
if string(result[0].Rows[0][0]) == "on" {
return errors.New("read only connection")
}
return nil
}
// ValidateConnectTargetSessionAttrsReadOnly is a ValidateConnectFunc that implements libpq compatible
// target_session_attrs=read-only.
func ValidateConnectTargetSessionAttrsReadOnly(ctx context.Context, pgConn *PgConn) error {
result, err := pgConn.Exec(ctx, "show transaction_read_only").ReadAll()
if err != nil {
return err
}
if string(result[0].Rows[0][0]) != "on" {
return errors.New("connection is not read only")
}
return nil
}
// ValidateConnectTargetSessionAttrsStandby is a ValidateConnectFunc that implements libpq compatible
// target_session_attrs=standby.
func ValidateConnectTargetSessionAttrsStandby(ctx context.Context, pgConn *PgConn) error {
result, err := pgConn.Exec(ctx, "select pg_is_in_recovery()").ReadAll()
if err != nil {
return err
}
if string(result[0].Rows[0][0]) != "t" {
return errors.New("server is not in hot standby mode")
}
return nil
}
// ValidateConnectTargetSessionAttrsPrimary is a ValidateConnectFunc that implements libpq compatible
// target_session_attrs=primary.
func ValidateConnectTargetSessionAttrsPrimary(ctx context.Context, pgConn *PgConn) error {
result, err := pgConn.Exec(ctx, "select pg_is_in_recovery()").ReadAll()
if err != nil {
return err
}
if string(result[0].Rows[0][0]) == "t" {
return errors.New("server is in standby mode")
}
return nil
}
// ValidateConnectTargetSessionAttrsPreferStandby is a ValidateConnectFunc that implements libpq compatible
// target_session_attrs=prefer-standby.
func ValidateConnectTargetSessionAttrsPreferStandby(ctx context.Context, pgConn *PgConn) error {
result, err := pgConn.Exec(ctx, "select pg_is_in_recovery()").ReadAll()
if err != nil {
return err
}
if string(result[0].Rows[0][0]) != "t" {
return &NotPreferredError{err: errors.New("server is not in hot standby mode")}
}
return nil
}
+80
View File
@@ -0,0 +1,80 @@
package ctxwatch
import (
"context"
"sync"
)
// ContextWatcher watches a context and performs an action when the context is canceled. It can watch one context at a
// time.
type ContextWatcher struct {
handler Handler
unwatchChan chan struct{}
lock sync.Mutex
watchInProgress bool
onCancelWasCalled bool
}
// NewContextWatcher returns a ContextWatcher. onCancel will be called when a watched context is canceled.
// OnUnwatchAfterCancel will be called when Unwatch is called and the watched context had already been canceled and
// onCancel called.
func NewContextWatcher(handler Handler) *ContextWatcher {
cw := &ContextWatcher{
handler: handler,
unwatchChan: make(chan struct{}),
}
return cw
}
// Watch starts watching ctx. If ctx is canceled then the onCancel function passed to NewContextWatcher will be called.
func (cw *ContextWatcher) Watch(ctx context.Context) {
cw.lock.Lock()
defer cw.lock.Unlock()
if cw.watchInProgress {
panic("Watch already in progress")
}
cw.onCancelWasCalled = false
if ctx.Done() != nil {
cw.watchInProgress = true
go func() {
select {
case <-ctx.Done():
cw.handler.HandleCancel(ctx)
cw.onCancelWasCalled = true
<-cw.unwatchChan
case <-cw.unwatchChan:
}
}()
} else {
cw.watchInProgress = false
}
}
// Unwatch stops watching the previously watched context. If the onCancel function passed to NewContextWatcher was
// called then onUnwatchAfterCancel will also be called.
func (cw *ContextWatcher) Unwatch() {
cw.lock.Lock()
defer cw.lock.Unlock()
if cw.watchInProgress {
cw.unwatchChan <- struct{}{}
if cw.onCancelWasCalled {
cw.handler.HandleUnwatchAfterCancel()
}
cw.watchInProgress = false
}
}
type Handler interface {
// HandleCancel is called when the context that a ContextWatcher is currently watching is canceled. canceledCtx is the
// context that was canceled.
HandleCancel(canceledCtx context.Context)
// HandleUnwatchAfterCancel is called when a ContextWatcher that called HandleCancel on this Handler is unwatched.
HandleUnwatchAfterCancel()
}
+63
View File
@@ -0,0 +1,63 @@
//go:build !windows
// +build !windows
package pgconn
import (
"os"
"os/user"
"path/filepath"
)
func defaultSettings() map[string]string {
settings := make(map[string]string)
settings["host"] = defaultHost()
settings["port"] = "5432"
// Default to the OS user name. Purposely ignoring err getting user name from
// OS. The client application will simply have to specify the user in that
// case (which they typically will be doing anyway).
user, err := user.Current()
if err == nil {
settings["user"] = user.Username
settings["passfile"] = filepath.Join(user.HomeDir, ".pgpass")
settings["servicefile"] = filepath.Join(user.HomeDir, ".pg_service.conf")
sslcert := filepath.Join(user.HomeDir, ".postgresql", "postgresql.crt")
sslkey := filepath.Join(user.HomeDir, ".postgresql", "postgresql.key")
if _, err := os.Stat(sslcert); err == nil {
if _, err := os.Stat(sslkey); err == nil {
// Both the cert and key must be present to use them, or do not use either
settings["sslcert"] = sslcert
settings["sslkey"] = sslkey
}
}
sslrootcert := filepath.Join(user.HomeDir, ".postgresql", "root.crt")
if _, err := os.Stat(sslrootcert); err == nil {
settings["sslrootcert"] = sslrootcert
}
}
settings["target_session_attrs"] = "any"
return settings
}
// defaultHost attempts to mimic libpq's default host. libpq uses the default unix socket location on *nix and localhost
// on Windows. The default socket location is compiled into libpq. Since pgx does not have access to that default it
// checks the existence of common locations.
func defaultHost() string {
candidatePaths := []string{
"/var/run/postgresql", // Debian
"/private/tmp", // OSX - homebrew
"/tmp", // standard PostgreSQL
}
for _, path := range candidatePaths {
if _, err := os.Stat(path); err == nil {
return path
}
}
return "localhost"
}
+57
View File
@@ -0,0 +1,57 @@
package pgconn
import (
"os"
"os/user"
"path/filepath"
"strings"
)
func defaultSettings() map[string]string {
settings := make(map[string]string)
settings["host"] = defaultHost()
settings["port"] = "5432"
// Default to the OS user name. Purposely ignoring err getting user name from
// OS. The client application will simply have to specify the user in that
// case (which they typically will be doing anyway).
user, err := user.Current()
appData := os.Getenv("APPDATA")
if err == nil {
// Windows gives us the username here as `DOMAIN\user` or `LOCALPCNAME\user`,
// but the libpq default is just the `user` portion, so we strip off the first part.
username := user.Username
if strings.Contains(username, "\\") {
username = username[strings.LastIndex(username, "\\")+1:]
}
settings["user"] = username
settings["passfile"] = filepath.Join(appData, "postgresql", "pgpass.conf")
settings["servicefile"] = filepath.Join(user.HomeDir, ".pg_service.conf")
sslcert := filepath.Join(appData, "postgresql", "postgresql.crt")
sslkey := filepath.Join(appData, "postgresql", "postgresql.key")
if _, err := os.Stat(sslcert); err == nil {
if _, err := os.Stat(sslkey); err == nil {
// Both the cert and key must be present to use them, or do not use either
settings["sslcert"] = sslcert
settings["sslkey"] = sslkey
}
}
sslrootcert := filepath.Join(appData, "postgresql", "root.crt")
if _, err := os.Stat(sslrootcert); err == nil {
settings["sslrootcert"] = sslrootcert
}
}
settings["target_session_attrs"] = "any"
return settings
}
// defaultHost attempts to mimic libpq's default host. libpq uses the default unix socket location on *nix and localhost
// on Windows. The default socket location is compiled into libpq. Since pgx does not have access to that default it
// checks the existence of common locations.
func defaultHost() string {
return "localhost"
}
+38
View File
@@ -0,0 +1,38 @@
// Package pgconn is a low-level PostgreSQL database driver.
/*
pgconn provides lower level access to a PostgreSQL connection than a database/sql or pgx connection. It operates at
nearly the same level is the C library libpq.
Establishing a Connection
Use Connect to establish a connection. It accepts a connection string in URL or keyword/value format and will read the
environment for libpq style environment variables.
Executing a Query
ExecParams and ExecPrepared execute a single query. They return readers that iterate over each row. The Read method
reads all rows into memory.
Executing Multiple Queries in a Single Round Trip
Exec and ExecBatch can execute multiple queries in a single round trip. They return readers that iterate over each query
result. The ReadAll method reads all query results into memory.
Pipeline Mode
Pipeline mode allows sending queries without having read the results of previously sent queries. It allows control of
exactly how many and when network round trips occur.
Context Support
All potentially blocking operations take a context.Context. The default behavior when a context is canceled is for the
method to immediately return. In most circumstances, this will also close the underlying connection. This behavior can
be customized by using BuildContextWatcherHandler on the Config to create a ctxwatch.Handler with different behavior.
This can be especially useful when queries that are frequently canceled and the overhead of creating new connections is
a problem. DeadlineContextWatcherHandler and CancelRequestContextWatcherHandler can be used to introduce a delay before
interrupting the query in such a way as to close the connection.
The CancelRequest method may be used to request the PostgreSQL server cancel an in-progress query without forcing the
client to abort.
*/
package pgconn
+248
View File
@@ -0,0 +1,248 @@
package pgconn
import (
"context"
"errors"
"fmt"
"net"
"net/url"
"regexp"
"strings"
)
// SafeToRetry checks if the err is guaranteed to have occurred before sending any data to the server.
func SafeToRetry(err error) bool {
var retryableErr interface{ SafeToRetry() bool }
if errors.As(err, &retryableErr) {
return retryableErr.SafeToRetry()
}
return false
}
// Timeout checks if err was caused by a timeout. To be specific, it is true if err was caused within pgconn by a
// context.DeadlineExceeded or an implementer of net.Error where Timeout() is true.
func Timeout(err error) bool {
var timeoutErr *errTimeout
return errors.As(err, &timeoutErr)
}
// PgError represents an error reported by the PostgreSQL server. See
// http://www.postgresql.org/docs/11/static/protocol-error-fields.html for
// detailed field description.
type PgError struct {
Severity string
SeverityUnlocalized string
Code string
Message string
Detail string
Hint string
Position int32
InternalPosition int32
InternalQuery string
Where string
SchemaName string
TableName string
ColumnName string
DataTypeName string
ConstraintName string
File string
Line int32
Routine string
}
func (pe *PgError) Error() string {
return pe.Severity + ": " + pe.Message + " (SQLSTATE " + pe.Code + ")"
}
// SQLState returns the SQLState of the error.
func (pe *PgError) SQLState() string {
return pe.Code
}
// ConnectError is the error returned when a connection attempt fails.
type ConnectError struct {
Config *Config // The configuration that was used in the connection attempt.
err error
}
func (e *ConnectError) Error() string {
prefix := fmt.Sprintf("failed to connect to `user=%s database=%s`:", e.Config.User, e.Config.Database)
details := e.err.Error()
if strings.Contains(details, "\n") {
return prefix + "\n\t" + strings.ReplaceAll(details, "\n", "\n\t")
} else {
return prefix + " " + details
}
}
func (e *ConnectError) Unwrap() error {
return e.err
}
type perDialConnectError struct {
address string
originalHostname string
err error
}
func (e *perDialConnectError) Error() string {
return fmt.Sprintf("%s (%s): %s", e.address, e.originalHostname, e.err.Error())
}
func (e *perDialConnectError) Unwrap() error {
return e.err
}
type connLockError struct {
status string
}
func (e *connLockError) SafeToRetry() bool {
return true // a lock failure by definition happens before the connection is used.
}
func (e *connLockError) Error() string {
return e.status
}
// ParseConfigError is the error returned when a connection string cannot be parsed.
type ParseConfigError struct {
ConnString string // The connection string that could not be parsed.
msg string
err error
}
func (e *ParseConfigError) Error() string {
// Now that ParseConfigError is public and ConnString is available to the developer, perhaps it would be better only
// return a static string. That would ensure that the error message cannot leak a password. The ConnString field would
// allow access to the original string if desired and Unwrap would allow access to the underlying error.
connString := redactPW(e.ConnString)
if e.err == nil {
return fmt.Sprintf("cannot parse `%s`: %s", connString, e.msg)
}
return fmt.Sprintf("cannot parse `%s`: %s (%s)", connString, e.msg, e.err.Error())
}
func (e *ParseConfigError) Unwrap() error {
return e.err
}
func normalizeTimeoutError(ctx context.Context, err error) error {
var netErr net.Error
if errors.As(err, &netErr) && netErr.Timeout() {
if ctx.Err() == context.Canceled {
// Since the timeout was caused by a context cancellation, the actual error is context.Canceled not the timeout error.
return context.Canceled
} else if ctx.Err() == context.DeadlineExceeded {
return &errTimeout{err: ctx.Err()}
} else {
return &errTimeout{err: netErr}
}
}
return err
}
type pgconnError struct {
msg string
err error
safeToRetry bool
}
func (e *pgconnError) Error() string {
if e.msg == "" {
return e.err.Error()
}
if e.err == nil {
return e.msg
}
return fmt.Sprintf("%s: %s", e.msg, e.err.Error())
}
func (e *pgconnError) SafeToRetry() bool {
return e.safeToRetry
}
func (e *pgconnError) Unwrap() error {
return e.err
}
// errTimeout occurs when an error was caused by a timeout. Specifically, it wraps an error which is
// context.Canceled, context.DeadlineExceeded, or an implementer of net.Error where Timeout() is true.
type errTimeout struct {
err error
}
func (e *errTimeout) Error() string {
return fmt.Sprintf("timeout: %s", e.err.Error())
}
func (e *errTimeout) SafeToRetry() bool {
return SafeToRetry(e.err)
}
func (e *errTimeout) Unwrap() error {
return e.err
}
type contextAlreadyDoneError struct {
err error
}
func (e *contextAlreadyDoneError) Error() string {
return fmt.Sprintf("context already done: %s", e.err.Error())
}
func (e *contextAlreadyDoneError) SafeToRetry() bool {
return true
}
func (e *contextAlreadyDoneError) Unwrap() error {
return e.err
}
// newContextAlreadyDoneError double-wraps a context error in `contextAlreadyDoneError` and `errTimeout`.
func newContextAlreadyDoneError(ctx context.Context) (err error) {
return &errTimeout{&contextAlreadyDoneError{err: ctx.Err()}}
}
func redactPW(connString string) string {
if strings.HasPrefix(connString, "postgres://") || strings.HasPrefix(connString, "postgresql://") {
if u, err := url.Parse(connString); err == nil {
return redactURL(u)
}
}
quotedKV := regexp.MustCompile(`password='[^']*'`)
connString = quotedKV.ReplaceAllLiteralString(connString, "password=xxxxx")
plainKV := regexp.MustCompile(`password=[^ ]*`)
connString = plainKV.ReplaceAllLiteralString(connString, "password=xxxxx")
brokenURL := regexp.MustCompile(`:[^:@]+?@`)
connString = brokenURL.ReplaceAllLiteralString(connString, ":xxxxxx@")
return connString
}
func redactURL(u *url.URL) string {
if u == nil {
return ""
}
if _, pwSet := u.User.Password(); pwSet {
u.User = url.UserPassword(u.User.Username(), "xxxxx")
}
return u.String()
}
type NotPreferredError struct {
err error
safeToRetry bool
}
func (e *NotPreferredError) Error() string {
return fmt.Sprintf("standby server not found: %s", e.err.Error())
}
func (e *NotPreferredError) SafeToRetry() bool {
return e.safeToRetry
}
func (e *NotPreferredError) Unwrap() error {
return e.err
}
+139
View File
@@ -0,0 +1,139 @@
// Package bgreader provides a io.Reader that can optionally buffer reads in the background.
package bgreader
import (
"io"
"sync"
"github.com/jackc/pgx/v5/internal/iobufpool"
)
const (
StatusStopped = iota
StatusRunning
StatusStopping
)
// BGReader is an io.Reader that can optionally buffer reads in the background. It is safe for concurrent use.
type BGReader struct {
r io.Reader
cond *sync.Cond
status int32
readResults []readResult
}
type readResult struct {
buf *[]byte
err error
}
// Start starts the backgrounder reader. If the background reader is already running this is a no-op. The background
// reader will stop automatically when the underlying reader returns an error.
func (r *BGReader) Start() {
r.cond.L.Lock()
defer r.cond.L.Unlock()
switch r.status {
case StatusStopped:
r.status = StatusRunning
go r.bgRead()
case StatusRunning:
// no-op
case StatusStopping:
r.status = StatusRunning
}
}
// Stop tells the background reader to stop after the in progress Read returns. It is safe to call Stop when the
// background reader is not running.
func (r *BGReader) Stop() {
r.cond.L.Lock()
defer r.cond.L.Unlock()
switch r.status {
case StatusStopped:
// no-op
case StatusRunning:
r.status = StatusStopping
case StatusStopping:
// no-op
}
}
// Status returns the current status of the background reader.
func (r *BGReader) Status() int32 {
r.cond.L.Lock()
defer r.cond.L.Unlock()
return r.status
}
func (r *BGReader) bgRead() {
keepReading := true
for keepReading {
buf := iobufpool.Get(8192)
n, err := r.r.Read(*buf)
*buf = (*buf)[:n]
r.cond.L.Lock()
r.readResults = append(r.readResults, readResult{buf: buf, err: err})
if r.status == StatusStopping || err != nil {
r.status = StatusStopped
keepReading = false
}
r.cond.L.Unlock()
r.cond.Broadcast()
}
}
// Read implements the io.Reader interface.
func (r *BGReader) Read(p []byte) (int, error) {
r.cond.L.Lock()
defer r.cond.L.Unlock()
if len(r.readResults) > 0 {
return r.readFromReadResults(p)
}
// There are no unread background read results and the background reader is stopped.
if r.status == StatusStopped {
return r.r.Read(p)
}
// Wait for results from the background reader
for len(r.readResults) == 0 {
r.cond.Wait()
}
return r.readFromReadResults(p)
}
// readBackgroundResults reads a result previously read by the background reader. r.cond.L must be held.
func (r *BGReader) readFromReadResults(p []byte) (int, error) {
buf := r.readResults[0].buf
var err error
n := copy(p, *buf)
if n == len(*buf) {
err = r.readResults[0].err
iobufpool.Put(buf)
if len(r.readResults) == 1 {
r.readResults = nil
} else {
r.readResults = r.readResults[1:]
}
} else {
*buf = (*buf)[n:]
r.readResults[0].buf = buf
}
return n, err
}
func New(r io.Reader) *BGReader {
return &BGReader{
r: r,
cond: &sync.Cond{
L: &sync.Mutex{},
},
}
}
+100
View File
@@ -0,0 +1,100 @@
package pgconn
import (
"errors"
"fmt"
"github.com/jackc/pgx/v5/pgproto3"
)
// NewGSSFunc creates a GSS authentication provider, for use with
// RegisterGSSProvider.
type NewGSSFunc func() (GSS, error)
var newGSS NewGSSFunc
// RegisterGSSProvider registers a GSS authentication provider. For example, if
// you need to use Kerberos to authenticate with your server, add this to your
// main package:
//
// import "github.com/otan/gopgkrb5"
//
// func init() {
// pgconn.RegisterGSSProvider(func() (pgconn.GSS, error) { return gopgkrb5.NewGSS() })
// }
func RegisterGSSProvider(newGSSArg NewGSSFunc) {
newGSS = newGSSArg
}
// GSS provides GSSAPI authentication (e.g., Kerberos).
type GSS interface {
GetInitToken(host string, service string) ([]byte, error)
GetInitTokenFromSPN(spn string) ([]byte, error)
Continue(inToken []byte) (done bool, outToken []byte, err error)
}
func (c *PgConn) gssAuth() error {
if newGSS == nil {
return errors.New("kerberos error: no GSSAPI provider registered, see https://github.com/otan/gopgkrb5")
}
cli, err := newGSS()
if err != nil {
return err
}
var nextData []byte
if c.config.KerberosSpn != "" {
// Use the supplied SPN if provided.
nextData, err = cli.GetInitTokenFromSPN(c.config.KerberosSpn)
} else {
// Allow the kerberos service name to be overridden
service := "postgres"
if c.config.KerberosSrvName != "" {
service = c.config.KerberosSrvName
}
nextData, err = cli.GetInitToken(c.config.Host, service)
}
if err != nil {
return err
}
for {
gssResponse := &pgproto3.GSSResponse{
Data: nextData,
}
c.frontend.Send(gssResponse)
err = c.flushWithPotentialWriteReadDeadlock()
if err != nil {
return err
}
resp, err := c.rxGSSContinue()
if err != nil {
return err
}
var done bool
done, nextData, err = cli.Continue(resp.Data)
if err != nil {
return err
}
if done {
break
}
}
return nil
}
func (c *PgConn) rxGSSContinue() (*pgproto3.AuthenticationGSSContinue, error) {
msg, err := c.receiveMessage()
if err != nil {
return nil, err
}
switch m := msg.(type) {
case *pgproto3.AuthenticationGSSContinue:
return m, nil
case *pgproto3.ErrorResponse:
return nil, ErrorResponseToPgError(m)
}
return nil, fmt.Errorf("expected AuthenticationGSSContinue message but received unexpected message %T", msg)
}
+2346
View File
File diff suppressed because it is too large Load Diff

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