ЛР7: перенести приложение и инфраструктуру ЛР6 в skeleton ЛР7

This commit is contained in:
Ivan Melnikov
2026-12-06 16:55:45 +03:00
parent 20afc2c790
commit 7d5fd459d6
2032 changed files with 745747 additions and 0 deletions
+237
View File
@@ -0,0 +1,237 @@
// Command jobctl is the explicit operator surface for the lab6 pipeline. It is
// not part of the public HTTP API and is never used by ordinary requests.
//
// It supports: inspecting a durable job, replaying a failed job, creating a
// newer pipeline version for the stale-result scenario, duplicating one broker
// delivery for fault injection, listing the failed registry and showing outbox
// and stream counters. It prints identifiers only, never bytes or credentials.
package main
import (
"context"
"encoding/json"
"flag"
"fmt"
"os"
"time"
"mtusi.ru/messenger-lab7/internal/broker"
"mtusi.ru/messenger-lab7/internal/config"
"mtusi.ru/messenger-lab7/internal/job"
"mtusi.ru/messenger-lab7/internal/store"
"mtusi.ru/messenger-lab7/internal/uuid"
)
func main() {
op := flag.String("op", "status", "status, replay, upgrade, duplicate, withdraw, failed, outbox or stream")
attachmentID := flag.String("attachment", "", "attachment UUID")
jobID := flag.String("job", "", "job UUID for -op duplicate")
version := flag.Int("version", 2, "target pipeline version for -op upgrade")
limit := flag.Int("limit", 20, "row limit for -op failed")
attemptOverride := flag.Int("attempt", 0, "override delivered attempt for -op duplicate (0 = current)")
streamID := flag.String("stream-id", "", "stream entry for -op withdraw")
actor := flag.String("actor", "operator", "audit actor for replay/upgrade")
flag.Parse()
cfg, err := config.LoadJobctl()
if err != nil {
fail("configuration error: " + err.Error())
}
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
repository, err := store.Open(ctx, cfg.DatabaseURL, store.Options{
MaxConns: 2, MinConns: 0,
ConnectTimeout: cfg.DBConnectTimeout,
StatementTimeout: cfg.DBStatementTimeout,
QueryTimeout: cfg.QueryTimeout,
})
if err != nil {
fail("database configuration failed: " + err.Error())
}
defer repository.Close()
switch *op {
case "status":
requireAttachment(*attachmentID)
id, ok := uuid.Normalize(*attachmentID)
if !ok {
fail("attachment is not a UUID")
}
attachment, err := repository.AttachmentForOperator(ctx, id)
if err != nil {
fail("attachment lookup failed: " + err.Error())
}
jobs, err := repository.JobDetails(ctx, id)
if err != nil {
fail("job lookup failed: " + err.Error())
}
printJSON(map[string]any{"attachment": attachment, "jobs": jobs})
case "failed":
if *limit < 1 || *limit > 100 {
fail("limit must be between 1 and 100")
}
jobs, err := repository.FailedJobs(ctx, *limit)
if err != nil {
fail("failed registry lookup failed: " + err.Error())
}
printJSON(map[string]any{"failed_jobs": jobs})
case "outbox":
pending, published, cancelled, err := repository.OutboxStats(ctx)
if err != nil {
fail("outbox stats failed: " + err.Error())
}
printJSON(map[string]any{"pending": pending, "published": published, "cancelled": cancelled})
case "replay":
requireAttachment(*attachmentID)
id, ok := uuid.Normalize(*attachmentID)
if !ok {
fail("attachment is not a UUID")
}
replayID, err := repository.ReplayFailedJob(ctx, id, *actor, time.Now().UTC())
if err != nil {
fail("replay refused: " + err.Error())
}
printJSON(map[string]any{"replayed_job_id": replayID, "attachment_id": id, "actor": *actor})
case "upgrade":
requireAttachment(*attachmentID)
id, ok := uuid.Normalize(*attachmentID)
if !ok {
fail("attachment is not a UUID")
}
if *version < 1 || *version > 100 {
fail("version must be between 1 and 100")
}
newJobID, err := repository.EnqueuePipelineVersion(ctx, id, *version, 5, *actor, time.Now().UTC())
if err != nil {
fail("version upgrade refused: " + err.Error())
}
printJSON(map[string]any{"job_id": newJobID, "attachment_id": id, "pipeline_version": *version, "actor": *actor})
case "duplicate":
duplicate(ctx, cfg, repository, *attachmentID, *jobID, *attemptOverride)
case "withdraw":
if *streamID == "" {
fail("-stream-id is required for -op withdraw")
}
transport, err := broker.Open(ctx, broker.Config{URL: cfg.BrokerURL, Stream: cfg.BrokerStream, Group: cfg.BrokerGroup, Timeout: 3 * time.Second})
if err != nil {
fail("broker unavailable: " + err.Error())
}
defer func() { _ = transport.Close() }()
if err := transport.Delete(ctx, *streamID); err != nil {
fail("withdraw failed: " + err.Error())
}
printJSON(map[string]any{"withdrawn_stream_id": *streamID})
case "stream":
transport, err := broker.Open(ctx, broker.Config{URL: cfg.BrokerURL, Stream: cfg.BrokerStream, Group: cfg.BrokerGroup, Timeout: 3 * time.Second})
if err != nil {
fail("broker unavailable: " + err.Error())
}
defer func() { _ = transport.Close() }()
entries, err := transport.StreamLen(ctx)
if err != nil {
fail("stream length failed: " + err.Error())
}
pending, err := transport.Pending(ctx)
if err != nil {
fail("pending count failed: " + err.Error())
}
raw, err := transport.Entries(ctx, 20)
if err != nil {
fail("stream entries failed: " + err.Error())
}
recent := make([]map[string]any, 0, len(raw))
for _, entry := range raw {
item := map[string]any{"stream_id": entry.ID}
if parsed, parseErr := job.Parse([]byte(entry.Payload)); parseErr == nil {
item["job_id"] = parsed.JobID
item["attachment_id"] = parsed.AttachmentID
item["pipeline_version"] = parsed.PipelineVersion
item["attempt"] = parsed.Attempt
}
recent = append(recent, item)
}
printJSON(map[string]any{"stream": transport.Stream(), "group": transport.Group(), "entries": entries, "pending": pending, "recent": recent})
default:
fail("unknown -op; expected status, replay, upgrade, duplicate, withdraw, failed, outbox or stream")
}
}
func duplicate(ctx context.Context, cfg config.Config, repository *store.Store, attachmentID, jobID string, attemptOverride int) {
transport, err := broker.Open(ctx, broker.Config{URL: cfg.BrokerURL, Stream: cfg.BrokerStream, Group: cfg.BrokerGroup, Timeout: 3 * time.Second})
if err != nil {
fail("broker unavailable: " + err.Error())
}
defer func() { _ = transport.Close() }()
var assignment store.Assignment
if jobID != "" {
id, ok := uuid.Normalize(jobID)
if !ok {
fail("job is not a UUID")
}
assignment, err = repository.JobAssignment(ctx, id)
if err != nil {
fail("job lookup failed: " + err.Error())
}
} else {
requireAttachment(attachmentID)
id, ok := uuid.Normalize(attachmentID)
if !ok {
fail("attachment is not a UUID")
}
jobs, err := repository.JobDetails(ctx, id)
if err != nil || len(jobs) == 0 {
fail("attachment has no durable job")
}
assignment, err = repository.JobAssignment(ctx, jobs[len(jobs)-1].JobID)
if err != nil {
fail("job lookup failed: " + err.Error())
}
}
attempt := assignment.JobAttempts
if attempt < 1 {
attempt = 1
}
if attemptOverride > 0 {
attempt = attemptOverride
}
if attempt > assignment.MaxAttempts {
attempt = assignment.MaxAttempts
}
message := job.New(assignment.JobID, assignment.AttachmentID, assignment.PipelineVersion, attempt, assignment.JobCreatedAt)
payload, err := message.Marshal()
if err != nil {
fail("message encoding failed: " + err.Error())
}
streamID, err := transport.Publish(ctx, payload)
if err != nil {
fail("duplicate publish failed: " + err.Error())
}
printJSON(map[string]any{
"duplicated_job_id": assignment.JobID,
"attachment_id": assignment.AttachmentID,
"pipeline_version": assignment.PipelineVersion,
"attempt": attempt,
"stream_id": streamID,
})
}
func requireAttachment(value string) {
if value == "" {
fail("-attachment is required for this operation")
}
}
func printJSON(value any) {
encoded, err := json.MarshalIndent(value, "", " ")
if err != nil {
fail("JSON encoding failed: " + err.Error())
}
fmt.Println(string(encoded))
}
func fail(message string) {
fmt.Fprintln(os.Stderr, "jobctl:", message)
os.Exit(1)
}
+362
View File
@@ -0,0 +1,362 @@
// 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-lab7/internal/api"
"mtusi.ru/messenger-lab7/internal/broker"
"mtusi.ru/messenger-lab7/internal/config"
"mtusi.ru/messenger-lab7/internal/objectstore"
"mtusi.ru/messenger-lab7/internal/outbox"
"mtusi.ru/messenger-lab7/internal/session"
"mtusi.ru/messenger-lab7/internal/store"
"mtusi.ru/messenger-lab7/internal/telemetry"
"mtusi.ru/messenger-lab7/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))
}
ctx := context.Background()
instanceID := instanceIdentity()
telemetryProvider, err := telemetry.Setup(ctx, telemetry.Options{
ServiceName: "messenger-api",
ServiceVersion: version,
InstanceID: instanceID,
Environment: cfg.Env,
})
if err != nil {
fmt.Fprintln(os.Stderr, "telemetry configuration error:", err)
os.Exit(2)
}
logger := telemetryProvider.Logger()
shutdownTelemetry := func() {
shutdownCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := telemetryProvider.Shutdown(shutdownCtx); err != nil {
logger.Warn("telemetry shutdown failed", "error", err)
}
}
repository, err := store.Open(ctx, cfg.DatabaseURL, store.Options{
MaxConns: cfg.DBMaxConns,
MinConns: cfg.DBMinConns,
ConnectTimeout: cfg.DBConnectTimeout,
StatementTimeout: cfg.DBStatementTimeout,
QueryTimeout: cfg.QueryTimeout,
QueryTracer: telemetry.NewPgxTracer(telemetryProvider.Tracer("postgresql")),
})
if err != nil {
logger.Error("database configuration failed", "error", err)
os.Exit(2)
}
defer repository.Close()
if err := waitForDatabase(ctx, repository, cfg.StartupTimeout, logger); err != nil {
logger.Error("postgres did not become ready", "timeout_seconds", int(cfg.StartupTimeout.Seconds()), "error", err)
os.Exit(1)
}
sessions, err := session.Open(cfg.CacheURL, session.Options{
PoolSize: cfg.CachePoolSize,
DialTimeout: cfg.CacheTimeout,
IOTimeout: cfg.CacheTimeout,
TTL: cfg.SessionTTL,
})
if err != nil {
logger.Error("session store configuration failed", "error", err)
os.Exit(2)
}
defer func() { _ = sessions.Close() }()
objects, err := objectstore.Open(objectstore.Config{
Endpoint: cfg.S3Endpoint,
Region: cfg.S3Region,
Bucket: cfg.S3Bucket,
AccessKey: cfg.S3AccessKey,
SecretKey: cfg.S3SecretKey,
Timeout: cfg.S3Timeout,
})
if err != nil {
logger.Error("object store configuration failed", "error", err)
os.Exit(2)
}
transport, err := broker.Open(ctx, broker.Config{
URL: cfg.BrokerURL,
Stream: cfg.BrokerStream,
Group: cfg.BrokerGroup,
Timeout: 3 * time.Second,
})
if err != nil {
logger.Error("broker configuration failed", "error", err)
os.Exit(2)
}
defer func() { _ = transport.Close() }()
app, err := api.New(repository, sessions, objects, logger, instanceID, version, api.Options{
MaxUploadBytes: cfg.MaxUploadBytes,
MaxImagePixels: cfg.MaxImagePixels,
DecodeConcurrency: cfg.DecodeConcurrency,
PutConcurrency: cfg.PutConcurrency,
TempDir: cfg.TempDir,
PipelineVersion: cfg.PipelineVersion,
JobMaxAttempts: cfg.JobMaxAttempts,
Metrics: telemetryProvider.Instruments(),
Tracer: telemetryProvider.Tracer("messenger-api"),
})
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)
// The outbox publisher is the only broker writer on the API side. Uploads
// never wait for it: the transaction commits the intention and the 202 is
// returned, then this loop publishes with publisher-confirm semantics.
if err := telemetryProvider.Instruments().RegisterGauges(telemetry.Gauges{
Queue: func(checkCtx context.Context) (int64, time.Duration, bool) {
stats, statsErr := transport.QueueStats(checkCtx)
if statsErr != nil {
return 0, 0, false
}
return stats.Depth, stats.Oldest, true
},
Pool: func(_ context.Context) (int64, int64, int64, int64, float64, bool) {
stats := repository.PoolStats()
return int64(stats.AcquiredConns), int64(stats.IdleConns), int64(stats.MaxConns),
stats.EmptyAcquireCount, float64(stats.AcquireDurationMillis) / 1000.0, true
},
}); err != nil {
logger.Warn("metric gauge registration failed", "error", err)
}
publisher := outbox.New(repository, transport, logger, telemetryProvider.Tracer("outbox"), cfg.OutboxPoll, cfg.OutboxBatch)
go publisher.Run(pruneCtx)
logger.Info("server listening",
"address", listener.Addr().String(),
"env", cfg.Env,
"instance_id", instanceID,
"version", version,
"revision", revision,
"session_ttl_seconds", int(cfg.SessionTTL.Seconds()),
"s3_bucket", cfg.S3Bucket,
"max_upload_bytes", cfg.MaxUploadBytes,
"max_image_pixels", cfg.MaxImagePixels,
"decode_concurrency", cfg.DecodeConcurrency,
"s3_put_concurrency", cfg.PutConcurrency,
"pipeline_version", cfg.PipelineVersion,
"job_max_attempts", cfg.JobMaxAttempts,
"outbox_poll_ms", cfg.OutboxPoll.Milliseconds(),
"broker_stream", cfg.BrokerStream,
"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()
shutdownTelemetry()
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-lab7", "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-lab7/internal/config"
"mtusi.ru/messenger-lab7/internal/store"
)
var revision = "unknown"
func main() {
flag.Parse()
logger := slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{Level: slog.LevelInfo})).
With("service", "messenger-lab7-migrate", "revision", revision)
cfg, err := config.LoadMigrate()
if err != nil {
logger.Error("configuration error", "error", err)
os.Exit(2)
}
ctx, cancel := context.WithTimeout(context.Background(), 90*time.Second)
defer cancel()
repository, err := store.Open(ctx, cfg.DatabaseURL, store.Options{
MaxConns: cfg.DBMaxConns,
MinConns: 0,
ConnectTimeout: cfg.DBConnectTimeout,
StatementTimeout: cfg.DBStatementTimeout,
QueryTimeout: cfg.QueryTimeout,
})
if err != nil {
logger.Error("database configuration failed", "error", err)
os.Exit(2)
}
defer repository.Close()
for {
pingCtx, pingCancel := context.WithTimeout(ctx, 2*time.Second)
err = repository.Ping(pingCtx)
pingCancel()
if err == nil {
break
}
if ctx.Err() != nil {
logger.Error("postgres did not become ready", "error", err)
os.Exit(1)
}
logger.Info("waiting for postgres", "error", err)
time.Sleep(500 * time.Millisecond)
}
started := time.Now()
if err := repository.Migrate(ctx); err != nil {
logger.Error("migrations failed", "error", err)
os.Exit(1)
}
logger.Info("migrations complete", "elapsed_ms", float64(time.Since(started).Microseconds())/1000.0)
fmt.Println("migrations: up-to-date")
}
+71
View File
@@ -0,0 +1,71 @@
// Command s3bootstrap creates the private attachment bucket idempotently and
// proves that the configured administrative credentials can use it. It is a
// one-shot compose service, separate from the API: API replicas never receive
// the administrative credentials and cannot create buckets.
package main
import (
"context"
"encoding/json"
"fmt"
"os"
"strconv"
"strings"
"time"
"mtusi.ru/messenger-lab7/internal/objectstore"
)
func main() {
endpoint := strings.TrimSpace(os.Getenv("S3_ENDPOINT"))
bucket := strings.TrimSpace(os.Getenv("S3_BUCKET"))
region := strings.TrimSpace(os.Getenv("S3_REGION"))
if region == "" {
region = "us-east-1"
}
accessKey := strings.TrimSpace(os.Getenv("S3_ADMIN_ACCESS_KEY"))
secretKey := strings.TrimSpace(os.Getenv("S3_ADMIN_SECRET_KEY"))
if endpoint == "" || bucket == "" || accessKey == "" || secretKey == "" {
fmt.Fprintln(os.Stderr, "s3bootstrap: S3_ENDPOINT, S3_BUCKET, S3_ADMIN_ACCESS_KEY and S3_ADMIN_SECRET_KEY are required")
os.Exit(2)
}
timeout := 30 * time.Second
if raw := strings.TrimSpace(os.Getenv("S3_TIMEOUT_SECONDS")); raw != "" {
seconds, err := strconv.Atoi(raw)
if err != nil || seconds < 5 || seconds > 120 {
fmt.Fprintln(os.Stderr, "s3bootstrap: S3_TIMEOUT_SECONDS must be an integer between 5 and 120")
os.Exit(2)
}
timeout = time.Duration(seconds) * time.Second
}
store, err := objectstore.Open(objectstore.Config{
Endpoint: endpoint,
Region: region,
Bucket: bucket,
AccessKey: accessKey,
SecretKey: secretKey,
Timeout: timeout,
})
if err != nil {
fmt.Fprintln(os.Stderr, "s3bootstrap: configuration error:", err)
os.Exit(2)
}
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
defer cancel()
created, err := store.EnsureBucket(ctx)
if err != nil {
fmt.Fprintln(os.Stderr, "s3bootstrap: bucket creation failed:", err)
os.Exit(1)
}
if err := store.Probe(ctx); err != nil {
fmt.Fprintln(os.Stderr, "s3bootstrap: credential/bucket probe failed:", err)
os.Exit(1)
}
result := map[string]any{
"bucket": bucket,
"created": created,
"verified": true,
}
encoded, _ := json.Marshal(result)
fmt.Println(string(encoded))
}
+150
View File
@@ -0,0 +1,150 @@
// Command s3ctl is a small operator/test helper for the private bucket. It is
// not part of the HTTP API: it uses the same restricted API credentials as the
// application and is used only to seed failure scenarios for the reconciler
// and to prove that anonymous access and cross-bucket access are denied.
package main
import (
"bytes"
"context"
"encoding/json"
"flag"
"fmt"
"io"
"os"
"time"
"mtusi.ru/messenger-lab7/internal/config"
"mtusi.ru/messenger-lab7/internal/objectstore"
)
func main() {
op := flag.String("op", "", "put, get, stat, delete or list")
key := flag.String("key", "", "object key")
file := flag.String("file", "", "file to upload for -op put")
contentType := flag.String("content-type", "application/octet-stream", "content type for -op put")
prefix := flag.String("prefix", "", "prefix for -op list")
bucketOverride := flag.String("bucket", "", "override the configured bucket (permission test)")
flag.Parse()
cfg, err := config.LoadTool()
if err != nil {
fmt.Fprintln(os.Stderr, "s3ctl: configuration error:", err)
os.Exit(2)
}
bucket := cfg.S3Bucket
if *bucketOverride != "" {
bucket = *bucketOverride
}
store, err := objectstore.Open(objectstore.Config{
Endpoint: cfg.S3Endpoint,
Region: cfg.S3Region,
Bucket: bucket,
AccessKey: cfg.S3AccessKey,
SecretKey: cfg.S3SecretKey,
Timeout: cfg.S3Timeout,
})
if err != nil {
fmt.Fprintln(os.Stderr, "s3ctl: configuration error:", err)
os.Exit(2)
}
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
defer cancel()
switch *op {
case "put":
if *key == "" || *file == "" {
fail("-op put requires -key and -file")
}
if *file == "-" {
// Test/operator helper: read a bounded body from stdin. The API path
// never uses this command, so the 10 MiB contract limit is not
// re-implemented here; s3ctl is only used on isolated synthetic data.
payload, err := io.ReadAll(io.LimitReader(os.Stdin, 16<<20))
if err != nil {
fail("cannot read stdin: " + err.Error())
}
if err := store.Put(ctx, *key, bytes.NewReader(payload), int64(len(payload)), *contentType); err != nil {
fail("put failed: " + err.Error())
}
print(map[string]any{"operation": "put", "key": *key, "size_bytes": len(payload)})
return
}
handle, err := os.Open(*file)
if err != nil {
fail("cannot open -file: " + err.Error())
}
defer handle.Close()
info, err := handle.Stat()
if err != nil {
fail("cannot stat -file: " + err.Error())
}
if err := store.Put(ctx, *key, handle, info.Size(), *contentType); err != nil {
fail("put failed: " + err.Error())
}
print(map[string]any{"operation": "put", "key": *key, "size_bytes": info.Size()})
case "delete":
if *key == "" {
fail("-op delete requires -key")
}
if err := store.Remove(ctx, *key); err != nil {
fail("delete failed: " + err.Error())
}
print(map[string]any{"operation": "delete", "key": *key})
case "stat":
if *key == "" {
fail("-op stat requires -key")
}
info, err := store.Stat(ctx, *key)
if err != nil {
fail("stat failed: " + err.Error())
}
print(map[string]any{"operation": "stat", "key": info.Key, "size_bytes": info.Size, "content_type": info.ContentType, "last_modified": info.LastModified.UTC().Format(time.RFC3339Nano)})
case "list":
items, err := store.List(ctx, *prefix)
if err != nil {
fail("list failed: " + err.Error())
}
keys := make([]map[string]any, 0, len(items))
for _, item := range items {
keys = append(keys, map[string]any{"key": item.Key, "size_bytes": item.Size, "last_modified": item.LastModified.UTC().Format(time.RFC3339Nano)})
}
print(map[string]any{"operation": "list", "bucket": bucket, "prefix": *prefix, "objects": keys})
case "get":
if *key == "" {
fail("-op get requires -key")
}
body, info, err := store.Get(ctx, *key)
if err != nil {
fail("get failed: " + err.Error())
}
defer body.Close()
buffer := make([]byte, 32*1024)
written := int64(0)
for {
n, readErr := body.Read(buffer)
if n > 0 {
if _, err := os.Stdout.Write(buffer[:n]); err != nil {
fail("write stdout failed")
}
written += int64(n)
}
if readErr != nil {
break
}
}
fmt.Fprintf(os.Stderr, "s3ctl: read %d of %d bytes\n", written, info.Size)
default:
fail("-op must be one of put, get, stat, delete or list")
}
}
func print(value any) {
encoded, _ := json.Marshal(value)
fmt.Println(string(encoded))
}
func fail(message string) {
fmt.Fprintln(os.Stderr, "s3ctl:", message)
os.Exit(1)
}
+260
View File
@@ -0,0 +1,260 @@
// Command worker runs the lab6 attachment pipeline as a separate process from
// the HTTP API. It consumes the durable broker, owns all image transformations
// and publishes the final objects. It never serves HTTP.
package main
import (
"context"
"errors"
"flag"
"fmt"
"log/slog"
"os"
"os/signal"
"strings"
"syscall"
"time"
"mtusi.ru/messenger-lab7/internal/broker"
"mtusi.ru/messenger-lab7/internal/config"
"mtusi.ru/messenger-lab7/internal/objectstore"
"mtusi.ru/messenger-lab7/internal/store"
"mtusi.ru/messenger-lab7/internal/telemetry"
"mtusi.ru/messenger-lab7/internal/uuid"
"mtusi.ru/messenger-lab7/internal/worker"
)
var (
version = "dev"
revision = "unknown"
)
func main() {
healthcheck := flag.Bool("healthcheck", false, "probe PostgreSQL, S3 and the broker, then exit 0/1")
once := flag.Bool("once", false, "consume and handle exactly one delivery, then exit")
flag.Parse()
cfg, err := config.LoadWorker()
if err != nil {
fmt.Fprintln(os.Stderr, "configuration error:", err)
os.Exit(2)
}
if *healthcheck {
os.Exit(runHealthcheck(cfg))
}
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM, syscall.SIGINT)
defer stop()
instanceID := consumerIdentity()
telemetryProvider, err := telemetry.Setup(ctx, telemetry.Options{
ServiceName: "messenger-worker",
ServiceVersion: version,
InstanceID: instanceID,
Environment: cfg.Env,
})
if err != nil {
fmt.Fprintln(os.Stderr, "telemetry configuration error:", err)
os.Exit(2)
}
logger := telemetryProvider.Logger().With("revision", revision)
shutdownTelemetry := func() {
shutdownCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := telemetryProvider.Shutdown(shutdownCtx); err != nil {
logger.Warn("telemetry shutdown failed", "error", err)
}
}
repository, err := store.Open(ctx, cfg.DatabaseURL, store.Options{
MaxConns: cfg.DBMaxConns,
MinConns: cfg.DBMinConns,
ConnectTimeout: cfg.DBConnectTimeout,
StatementTimeout: cfg.DBStatementTimeout,
QueryTimeout: cfg.QueryTimeout,
QueryTracer: telemetry.NewPgxTracer(telemetryProvider.Tracer("postgresql")),
})
if err != nil {
logger.Error("database configuration failed", "error", err)
os.Exit(2)
}
defer repository.Close()
if err := waitFor(ctx, cfg.StartupTimeout, "postgres", func(checkCtx context.Context) error {
return repository.Ping(checkCtx)
}, logger); err != nil {
logger.Error("postgres did not become ready", "error", err)
os.Exit(1)
}
objects, err := objectstore.Open(objectstore.Config{
Endpoint: cfg.S3Endpoint,
Region: cfg.S3Region,
Bucket: cfg.S3Bucket,
AccessKey: cfg.S3AccessKey,
SecretKey: cfg.S3SecretKey,
Timeout: cfg.S3Timeout,
})
if err != nil {
logger.Error("object store configuration failed", "error", err)
os.Exit(2)
}
if err := waitFor(ctx, cfg.StartupTimeout, "s3", objects.Health, logger); err != nil {
logger.Error("s3 did not become ready", "error", err)
os.Exit(1)
}
var transport *broker.Broker
if err := waitFor(ctx, cfg.StartupTimeout, "broker", func(checkCtx context.Context) error {
opened, openErr := broker.Open(checkCtx, broker.Config{
URL: cfg.BrokerURL,
Stream: cfg.BrokerStream,
Group: cfg.BrokerGroup,
Timeout: 3 * time.Second,
})
if openErr != nil {
return openErr
}
transport = opened
return nil
}, logger); err != nil {
logger.Error("broker did not become ready", "error", err)
os.Exit(1)
}
defer func() { _ = transport.Close() }()
consumer := instanceID
runner := worker.New(repository, objects, transport, logger, consumer, worker.Options{
Env: cfg.Env,
Concurrency: cfg.WorkerConcurrency,
MaxAttempts: cfg.JobMaxAttempts,
JobTimeout: cfg.JobTimeout,
Lease: cfg.JobLease,
ClaimIdle: cfg.ClaimIdle,
BackoffBase: cfg.BackoffBase,
BackoffMax: cfg.BackoffMax,
StagingRetention: cfg.StagingRetention,
ClaimInterval: 5 * time.Second,
RecoveryInterval: 5 * time.Second,
JanitorInterval: 30 * time.Second,
FaultInject: cfg.FaultInject,
FaultTarget: cfg.FaultTargetAttachmentID,
MaxUploadBytes: cfg.MaxUploadBytes,
Metrics: telemetryProvider.Instruments(),
Tracer: telemetryProvider.Tracer("messenger-worker"),
})
if err := telemetryProvider.Instruments().RegisterGauges(telemetry.Gauges{
Pool: func(_ context.Context) (int64, int64, int64, int64, float64, bool) {
stats := repository.PoolStats()
return int64(stats.AcquiredConns), int64(stats.IdleConns), int64(stats.MaxConns),
stats.EmptyAcquireCount, float64(stats.AcquireDurationMillis) / 1000.0, true
},
Worker: func(_ context.Context) (int64, int64, bool) {
return runner.Busy(), runner.Capacity(), true
},
}); err != nil {
logger.Warn("metric gauge registration failed", "error", err)
}
logger.Info("worker starting",
"consumer", consumer,
"concurrency", cfg.WorkerConcurrency,
"job_timeout_seconds", int(cfg.JobTimeout.Seconds()),
"job_lease_seconds", int(cfg.JobLease.Seconds()),
"claim_idle_seconds", int(cfg.ClaimIdle.Seconds()),
"job_max_attempts", cfg.JobMaxAttempts,
"staging_retention_seconds", int(cfg.StagingRetention.Seconds()),
"stream", cfg.BrokerStream,
"group", cfg.BrokerGroup,
"fault_inject", cfg.FaultInject,
"version", version)
run := runner.Run
if *once {
run = runner.RunOnce
}
if err := run(ctx); err != nil && !errors.Is(err, context.Canceled) {
logger.Error("worker stopped with an error", "error", err)
shutdownTelemetry()
os.Exit(1)
}
shutdownTelemetry()
logger.Info("worker stopped cleanly; unacknowledged deliveries remain in the consumer group")
}
func waitFor(ctx context.Context, timeout time.Duration, dependency string, check func(context.Context) error, logger *slog.Logger) error {
deadline := time.Now().Add(timeout)
for {
checkCtx, cancel := context.WithTimeout(ctx, 3*time.Second)
err := check(checkCtx)
cancel()
if err == nil {
return nil
}
if ctx.Err() != nil {
return ctx.Err()
}
if time.Now().After(deadline) {
return err
}
logger.Info("waiting for dependency", "dependency", dependency, "error", err)
select {
case <-ctx.Done():
return ctx.Err()
case <-time.After(time.Second):
}
}
}
func consumerIdentity() string {
hostname, _ := os.Hostname()
hostname = strings.TrimSpace(hostname)
if hostname == "" {
hostname = "worker"
}
return "worker-" + hostname + "-" + uuid.NewRandom(3)
}
func runHealthcheck(cfg config.Config) int {
ctx, cancel := context.WithTimeout(context.Background(), 8*time.Second)
defer cancel()
failures := 0
report := func(name string, err error) {
if err != nil {
fmt.Fprintln(os.Stderr, "worker healthcheck:", name, "unavailable:", err)
failures++
}
}
repository, err := store.Open(ctx, cfg.DatabaseURL, store.Options{MaxConns: 1, MinConns: 0, ConnectTimeout: 2 * time.Second, StatementTimeout: 3 * time.Second, QueryTimeout: 2 * time.Second})
if err != nil {
report("postgres", err)
} else {
defer repository.Close()
report("postgres", repository.Ping(ctx))
}
objects, err := objectstore.Open(objectstore.Config{
Endpoint: cfg.S3Endpoint, Region: cfg.S3Region, Bucket: cfg.S3Bucket,
AccessKey: cfg.S3AccessKey, SecretKey: cfg.S3SecretKey, Timeout: 3 * time.Second,
})
if err != nil {
report("s3", err)
} else {
report("s3", objects.Health(ctx))
}
transport, err := broker.Open(ctx, broker.Config{
URL: cfg.BrokerURL, Stream: cfg.BrokerStream, Group: cfg.BrokerGroup, Timeout: 2 * time.Second,
})
if err != nil {
report("broker", err)
} else {
defer func() { _ = transport.Close() }()
report("broker", transport.Ping(ctx))
}
if failures > 0 {
return 1
}
return 0
}
+57
View File
@@ -0,0 +1,57 @@
module mtusi.ru/messenger-lab7
go 1.26.0
require (
github.com/jackc/pgx/v5 v5.7.2
github.com/jackc/puddle/v2 v2.2.2
github.com/minio/minio-go/v7 v7.0.82
github.com/redis/go-redis/v9 v9.7.0
go.opentelemetry.io/otel v1.48.0
go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp v0.24.0
go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp v1.48.0
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.48.0
go.opentelemetry.io/otel/log v1.48.0
go.opentelemetry.io/otel/metric v1.48.0
go.opentelemetry.io/otel/sdk v1.48.0
go.opentelemetry.io/otel/sdk/log v1.48.0
go.opentelemetry.io/otel/sdk/metric v1.48.0
go.opentelemetry.io/otel/trace v1.48.0
golang.org/x/crypto v0.59.0
)
require (
github.com/cenkalti/backoff/v7 v7.0.3 // indirect
github.com/go-logr/logr v1.4.4 // indirect
github.com/go-logr/stdr v1.2.2 // indirect
github.com/grpc-ecosystem/grpc-gateway/v2 v2.34.0 // indirect
go.opentelemetry.io/auto/sdk v1.2.2 // indirect
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.48.0 // indirect
go.opentelemetry.io/proto/otlp v1.11.0 // indirect
go.opentelemetry.io/proto/slim/otlp v1.11.1 // indirect
google.golang.org/genproto/googleapis/api v0.0.0-20261202194610-22e8acf14972 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20261202194610-22e8acf14972 // indirect
google.golang.org/grpc v1.85.0 // indirect
google.golang.org/protobuf v1.36.12 // indirect
)
require (
github.com/KarpelesLab/gowebp v0.1.1
github.com/cespare/xxhash/v2 v2.3.0 // indirect
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
github.com/dustin/go-humanize v1.0.1 // indirect
github.com/go-ini/ini v1.67.0 // indirect
github.com/goccy/go-json v0.10.3 // indirect
github.com/google/uuid v1.6.0 // indirect
github.com/jackc/pgpassfile v1.0.0 // indirect
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
github.com/klauspost/compress v1.17.11 // indirect
github.com/klauspost/cpuid/v2 v2.2.8 // indirect
github.com/minio/md5-simd v1.1.2 // indirect
github.com/rs/xid v1.6.0 // indirect
golang.org/x/image v0.24.0
golang.org/x/net v0.63.0 // indirect
golang.org/x/sync v0.25.0 // indirect
golang.org/x/sys v0.50.0 // indirect
golang.org/x/text v0.44.0 // indirect
)
+147
View File
@@ -0,0 +1,147 @@
cel.dev/expr v0.25.3/go.mod h1:hrXvqGP6G6gyx8UAHSHJ5RGk//1Oj5nXQ2NI02Nrsg4=
cloud.google.com/go/compute/metadata v0.9.0/go.mod h1:E0bWwX5wTnLPedCKqk3pJmVgCBSM6qQI1yTBdEb3C10=
github.com/BurntSushi/toml v1.4.1-0.20240526193622-a339e1f7089c/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho=
github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.35.0/go.mod h1:Yj5vHEz/aAepZGliRJsA6uvHAVAQyEwajq9ORCHPxzM=
github.com/KarpelesLab/gowebp v0.1.1 h1:W11ZrRVx+Zk4ypW5NBEU31FQzghICXIrAbAbO5yd4M0=
github.com/KarpelesLab/gowebp v0.1.1/go.mod h1:Js8OXPQ94yl94HqaO/9XuUqk0wOPod6uycryhzmTgsU=
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/cenkalti/backoff/v7 v7.0.3 h1:oJlXCmDgfNcGYViwioz1cZ1kHebejP4OLfJ/gqMQVWA=
github.com/cenkalti/backoff/v7 v7.0.3/go.mod h1:qcKBGwsu4hpxHtQ8tWYsQ+ifzx2+sS+Xx/3jfe30lI8=
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
github.com/cncf/xds/go v0.0.0-20260202195803-dba9d589def2/go.mod h1:qwXFYgsP6T7XnJtbKlf1HP8AjxZZyzxMmc+Lq5GjlU4=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78=
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc=
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
github.com/envoyproxy/go-control-plane v0.14.0/go.mod h1:NcS5X47pLl/hfqxU70yPwL9ZMkUlwlKxtAohpi2wBEU=
github.com/envoyproxy/go-control-plane/envoy v1.39.1-0.20260819172001-e6e3fd93e4be/go.mod h1:PYEOlng9XcrulfyWpm49jECTPV0LT4q8cO7fLW/xwgk=
github.com/envoyproxy/go-control-plane/ratelimit v0.1.0/go.mod h1:Wk+tMFAFbCXaJPzVVHnPgRKdUdwW/KdbRt94AzgRee4=
github.com/envoyproxy/protoc-gen-validate v1.3.3/go.mod h1:TsndJ/ngyIdQRhMcVVGDDHINPLWB7C82oDArY51KfB0=
github.com/go-ini/ini v1.67.0 h1:z6ZrTEZqSWOTyH2FlglNbNgARyHG8oLW9gMELqKr06A=
github.com/go-ini/ini v1.67.0/go.mod h1:ByCAeIL28uOIIG0E3PJtZPDL8WnHpFKFOtgjp+3Ies8=
github.com/go-jose/go-jose/v4 v4.1.4/go.mod h1:x4oUasVrzR7071A4TnHLGSPpNOm2a21K9Kf04k1rs08=
github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=
github.com/go-logr/logr v1.4.4 h1:tG4xh9yMsRCAiodLVTxyrkzSZ9+o0L1Kg/+cPVcbP/8=
github.com/go-logr/logr v1.4.4/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
github.com/goccy/go-json v0.10.3 h1:KZ5WoDbxAIgm2HNbYckL0se1fHD6rz5j4ywS6ebzDqA=
github.com/goccy/go-json v0.10.3/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M=
github.com/golang/glog v1.2.5/go.mod h1:6AhwSGph0fcJtXVM/PEHPqZlFeoLxhs7/t5UDAwmO+w=
github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=
github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/grpc-ecosystem/grpc-gateway/v2 v2.34.0 h1:vzlTzzi4tHLa/JQdIE5LeXw6SEX5EVVhq/VPqKHnKOk=
github.com/grpc-ecosystem/grpc-gateway/v2 v2.34.0/go.mod h1:FHXQZnW5pA0txiMr3jApv9uNJzZ+7mYZd+u+PPenCFU=
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
github.com/jackc/pgx/v5 v5.7.2 h1:mLoDLV6sonKlvjIEsV56SkWNCnuNv531l94GaIzO+XI=
github.com/jackc/pgx/v5 v5.7.2/go.mod h1:ncY89UGWxg82EykZUwSpUKEfccBGGYq1xjrOpsbsfGQ=
github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo=
github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
github.com/klauspost/compress v1.17.11 h1:In6xLpyWOi1+C7tXUUWv2ot1QvBjxevKAaI6IXrJmUc=
github.com/klauspost/compress v1.17.11/go.mod h1:pMDklpSncoRMuLFrf1W9Ss9KT+0rH90U12bZKk7uwG0=
github.com/klauspost/cpuid/v2 v2.0.1/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
github.com/klauspost/cpuid/v2 v2.2.8 h1:+StwCXwm9PdpiEkPyzBXIy+M9KUb4ODm0Zarf1kS5BM=
github.com/klauspost/cpuid/v2 v2.2.8/go.mod h1:Lcz8mBdAVJIBVzewtcLocK12l3Y+JytZYpaMropDUws=
github.com/kr/pretty v0.3.0/go.mod h1:640gp4NfQd8pI5XOwp5fnNeVWj67G7CFk/SaSQn7NBk=
github.com/minio/md5-simd v1.1.2 h1:Gdi1DZK69+ZVMoNHRXJyNcxrMA4dSxoYHZSQbirFg34=
github.com/minio/md5-simd v1.1.2/go.mod h1:MzdKDxYpY2BT9XQFocsiZf/NKVtR7nkE4RoEpN+20RM=
github.com/minio/minio-go/v7 v7.0.82 h1:tWfICLhmp2aFPXL8Tli0XDTHj2VB/fNf0PC1f/i1gRo=
github.com/minio/minio-go/v7 v7.0.82/go.mod h1:84gmIilaX4zcvAWWzJ5Z1WI5axN+hAbM5w25xf8xvC0=
github.com/planetscale/vtprotobuf v0.6.1-0.20240319094008-0393e58bdf10/go.mod h1:t/avpk3KcrXxUnYOhZhMXJlSEyie6gQbtLq5NM3loB8=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/redis/go-redis/v9 v9.7.0 h1:HhLSs+B6O021gwzl+locl0zEDnyNkxMtf/Z3NNBMa9E=
github.com/redis/go-redis/v9 v9.7.0/go.mod h1:f6zhXITC7JUJIlPEiBOTXxJgPLdZcA93GewI7inzyWw=
github.com/rs/xid v1.6.0 h1:fV591PaemRlL6JfRxGDEPl69wICngIQ3shQtzfy2gxU=
github.com/rs/xid v1.6.0/go.mod h1:7XoLgs4eV+QndskICGsho+ADou8ySMSjJKDIan90Nz0=
github.com/spiffe/go-spiffe/v2 v2.8.1/go.mod h1:47Q0Q9/AqGha8QLHp+kxpH4Wca7X7EnOtlIJy3mxZ3U=
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.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE=
github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg=
go.opentelemetry.io/auto/sdk v1.2.2 h1:ErNn7NW2t1F9CFBLb9iyPMyLRbcEd07l5m/StCe9AEE=
go.opentelemetry.io/auto/sdk v1.2.2/go.mod h1:Ca3X8ec6gdTYjAirla//dnp05ECtQPfN4Ut74OJLVsQ=
go.opentelemetry.io/contrib/detectors/gcp v1.45.0/go.mod h1:VSme3o2fvSg5bVg0dRzyHaj4Z5EVhG+g2Fde6LKzmQA=
go.opentelemetry.io/otel v1.48.0 h1:+B+p9J2Mt8jNFzbQddQzBt5dcwIzjYZVeRE1pPaTI6Y=
go.opentelemetry.io/otel v1.48.0/go.mod h1:eZOWPvdtyhR+5xJ4z53+JXD94Kb6ulSVbRYF5s3Ez9s=
go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp v0.24.0 h1:nU6KeHUhxNGvgMS51MRmfJRQibbE/BL60NG7TxKLeZU=
go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp v0.24.0/go.mod h1:z35lW3UxqaqpPkgc3ghOr4Ha2aminOj5bRs1xmzyapg=
go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp v1.48.0 h1:00w9xOQRiXJHmWbFf1Dzff0PrEln/xzKllXGQszKkkU=
go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp v1.48.0/go.mod h1:6cidiC3kozfzjGSrqmP5e3+E98gukxseRiMD4+IZUWU=
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.48.0 h1:CuXLX0J8TrokZ6C1XmBYlJgQzVl2GTtMcY5jE23t/hg=
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.48.0/go.mod h1:OyW2/YjD4TPITIypYuWhLzJ7ko8A9NBPWfxUp36FPr8=
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.48.0 h1:VU+LgQ5ZCS4JUr8xFjkSDRHVGgtbP8uKDG1XiQvwFFg=
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.48.0/go.mod h1:/XhwmD+kqbGuJZrNYKdkuP6ysLv9FBVfps7XEb4hPCc=
go.opentelemetry.io/otel/log v1.48.0 h1:End7kfHjTOT7m2aQxasIeXyk03VkGja8OLy/z11DzOw=
go.opentelemetry.io/otel/log v1.48.0/go.mod h1:J2AqJn5ckRJ/7/gAyI1tvhuy/kjMuKrbnDZ7mkkHPE8=
go.opentelemetry.io/otel/log/global v1.48.0/go.mod h1:CQNUyv/qTDHD9IW4vc4L5B+ZVFkuMEe3IzBPlhTd1FY=
go.opentelemetry.io/otel/metric v1.48.0 h1:cnE2xH39/AzZLwuCs5Z8f0y92kdskuAz25cSU+tCXiA=
go.opentelemetry.io/otel/metric v1.48.0/go.mod h1:sgzQ/mqhJzbrA2xUtO3Bh7bqoDwZxtuE1tXBJfS9Lhw=
go.opentelemetry.io/otel/metric/x v0.70.0 h1:Td11/3l9/LFa5NhIesdVZimVrDYYweXW0PmpLeZ7viI=
go.opentelemetry.io/otel/metric/x v0.70.0/go.mod h1:0brLEhgs4qAUdgmygdtyD8W7chH/V/JJvN8NP5ByUhE=
go.opentelemetry.io/otel/sdk v1.48.0 h1:qlsDCB0xHG2Fp0MRlPAIoK/I7aMKKJJJCbLfY7U7uQI=
go.opentelemetry.io/otel/sdk v1.48.0/go.mod h1:FrKDqW0po4chr9XJ48sR8borRbMZ/ym10xrMWQETzFM=
go.opentelemetry.io/otel/sdk/log v1.48.0 h1:sZtoUKejhc8aGvNw1xpxA81XP5OP7wCMHHKnbpo7Lo4=
go.opentelemetry.io/otel/sdk/log v1.48.0/go.mod h1:sK0GNDLXMhBcYaSVBJ4wxCMcBO+bvO4OyARi9zxLPSw=
go.opentelemetry.io/otel/sdk/log/logtest v0.24.0 h1:v37tXY6elm4eKT9i8PMGj3nV7lxVRTLcY5GJ5d7Rg8c=
go.opentelemetry.io/otel/sdk/log/logtest v0.24.0/go.mod h1:lBcbqvGIPOA/msghB4i012T0ofVqm7pMSkYWh9g+9Rc=
go.opentelemetry.io/otel/sdk/metric v1.48.0 h1:zu7cDV8E+M/ZMSHuG4xXp+mJerzJZ9Gvd9PVqzPPa4s=
go.opentelemetry.io/otel/sdk/metric v1.48.0/go.mod h1:QuH0bjjuGpdityXBrF3+JmVRvyvKRJeCk3NxBgiQzCo=
go.opentelemetry.io/otel/trace v1.48.0 h1:iHfNaHEbGEuR+KbEI9A53POz65oqZN4Et+QcRma2iGk=
go.opentelemetry.io/otel/trace v1.48.0/go.mod h1:bwi5DwkYvU0t4AhGnAkfZ4YJDQosiB0zKnba7+bxvTU=
go.opentelemetry.io/proto/otlp v1.11.0 h1:5rrYs0Ykyj50sdU/JU0x8etU+LubXWb+gED6TbEdMIk=
go.opentelemetry.io/proto/otlp v1.11.0/go.mod h1:SmVizdCOAm3XBtG1g1NnOdhW6jtddT72hLMhv8VwA8E=
go.opentelemetry.io/proto/slim/otlp v1.11.1 h1:qf2OA3kQcIDXh3q7b6kc0IzRe8BFXlVIlH5uaOACrVQ=
go.opentelemetry.io/proto/slim/otlp v1.11.1/go.mod h1:15pWfj6/rYjQzyrC3ZGQoZ0rNgLqI/Lk+jFgYgV4UIE=
go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
go.yaml.in/yaml/v3 v3.0.6 h1:zcDfvjXEqTQmpjniUBLc91xYJMB2c4QOFxEF/LCEckM=
go.yaml.in/yaml/v3 v3.0.6/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg=
go.yaml.in/yaml/v4 v4.0.0/go.mod h1:aZqd9kCMsGL7AuUv/m/PvWLdg5sjJsZ4oHDEnfPPfY0=
golang.org/x/crypto v0.59.0 h1:xS2jhqYbzNrpvkWP2YTDf4TJwBy3ykR03i8vFDxEc7c=
golang.org/x/crypto v0.59.0/go.mod h1:veDyUwATGs3c+vN3VfTbzViMGXeTBk3WyhBOkn+F/4U=
golang.org/x/exp v0.0.0-20261113113407-e3970619a1a4/go.mod h1:J3U+E8RzytcGvwz+uJuAP4zULJ2TkAQBnmPZMexpdXs=
golang.org/x/exp/typeparams v0.0.0-20231108232855-2478ac86f678/go.mod h1:AbB0pIl9nAr9wVwH+Z2ZpaocVmF5I4GyWCDIsVjR0bk=
golang.org/x/image v0.24.0 h1:AN7zRgVsbvmTfNyqIbbOraYL8mSwcKncEj8ofjgzcMQ=
golang.org/x/image v0.24.0/go.mod h1:4b/ITuLfqYq1hqZcjofwctIhi7sZh2WaCjvsBNjjya8=
golang.org/x/mod v0.42.0/go.mod h1:u5fzIrRInkL8MaO1cbRkUHT64v303YIT5KEqpNr7jRs=
golang.org/x/net v0.63.0 h1:HCoTmNh9EpD1PpK8gBNFY4gcTY4N+KQEO8ylfIKqFJ0=
golang.org/x/net v0.63.0/go.mod h1:15JLg3IX1bLjHK264EZQEbIpTiR/KVLuo9CTRWd0pig=
golang.org/x/oauth2 v0.36.0/go.mod h1:YDBUJMTkDnJS+A4BP4eZBjCqtokkg1hODuPjwiGPO7Q=
golang.org/x/sync v0.25.0 h1:dJnifr0nMV8/SBnBvdo4eSGGnrc3O4FFx6IqvtLcmRs=
golang.org/x/sync v0.25.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.50.0 h1:dkKZEFTEKaLr1sjhs0WiKqoi8Jj5nHbS3Njmx1UoMJs=
golang.org/x/sys v0.50.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
golang.org/x/term v0.48.0/go.mod h1:BRDLHCZr2SUjIeBHHpRyQeC9xzSAVbzY2rvKgafnHf4=
golang.org/x/text v0.44.0 h1:YItdp/mQNGnsmrgpcdA5yQ3bnRxCfo/Tj/iByGW9GGo=
golang.org/x/text v0.44.0/go.mod h1:S4FR1waQ9LbjQTls97SyRjDaUUVkaM+cXwwuG/G+MwY=
golang.org/x/tools v0.52.1-0.20261106145633-d407941a339a/go.mod h1:ItcP5UNaVGG+Yc4eIYmaFLNJ4soEopkx5Y2d4lcEurs=
gonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4=
gonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E=
google.golang.org/genproto/googleapis/api v0.0.0-20261202194610-22e8acf14972 h1:gCcQH4NWwNzKNSZECKA7HFLmPqPzLjpi1wdn/9jHybE=
google.golang.org/genproto/googleapis/api v0.0.0-20261202194610-22e8acf14972/go.mod h1:T2EZt+uhefg9Jhmovc6NLhtwf6cJnFAk1UDcWG5zS9k=
google.golang.org/genproto/googleapis/rpc v0.0.0-20261202194610-22e8acf14972 h1:+HvG6t+1Owr+0YLuHo6vnpgP1MvAqlpovMQ2QIMKNsg=
google.golang.org/genproto/googleapis/rpc v0.0.0-20261202194610-22e8acf14972/go.mod h1:OaIUM3+LpYcK2GXM4FTmhWoIq371Owdr+Cc7/BsYHHc=
google.golang.org/grpc v1.85.0 h1:BPBCfuVRQ1qvBhKDOq9uvQllMvO59rKsYhXpp7Dd8vw=
google.golang.org/grpc v1.85.0/go.mod h1:0rQrOD58yjal/0EaVbGBANindixsCZNQPDV3VKtaKuQ=
google.golang.org/protobuf v1.36.12 h1:pJOKDDOyeXErUroCihFAd5LQuwXBSpVnKGrj5o/fwxc=
google.golang.org/protobuf v1.36.12/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
honnef.co/go/tools v0.8.2/go.mod h1:xG1Q4n+mg3bKZrO6RWFA9jFlkqplflmDRHGeuexiLDs=
+7
View File
@@ -0,0 +1,7 @@
# Инфраструктура студента
Здесь разместите конфигурации выбранных сервисов; основную топологию — в корневом compose.yaml/stack.yaml. `compose.example.yaml` — только worksheet ролей и намеренно не запускается. `contracts/infrastructure.json` задаёт минимальные роли, не готовые образы/пароли.
В REPORT.md сопоставьте роль → service name → версия/digest → health/readiness → volume → сеть/порт → способ передачи credentials. Приведите bootstrap (schema, bucket, broker topology, а с lab6 provisioning) и безопасное повторение этих команд.
Приложение строится из исходников. Не используйте заранее существующий образ преподавательского сервера вместо своей реализации. Restart hook перезапускает все соответствующие stores с volumes; failover hook останавливает только заданную API-реплику.
@@ -0,0 +1,871 @@
{
"annotations": {
"list": []
},
"editable": false,
"fiscalYearStartMonth": 0,
"graphTooltip": 1,
"id": null,
"links": [],
"panels": [
{
"id": 1,
"type": "row",
"title": "API — SLI/SLO, traffic, errors, latency",
"gridPos": {
"h": 1,
"w": 24,
"x": 0,
"y": 0
},
"collapsed": false
},
{
"id": 2,
"title": "SLO: API availability, 1h window (target 99.5%)",
"type": "stat",
"gridPos": {
"h": 4,
"w": 6,
"x": 0,
"y": 1
},
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"editorMode": "code",
"expr": "1 - ((sum(rate(http_server_requests_total{service_name=\"messenger-api\",http_route!~\"/health.*\",status_class=\"5xx\"}[1h])) or vector(0)) / clamp_min(sum(rate(http_server_requests_total{service_name=\"messenger-api\",http_route!~\"/health.*\"}[1h])), 1e-9))",
"legendFormat": "availability",
"range": true,
"refId": "A",
"instant": false
}
],
"description": "SLI = 1 - 5xx/business requests over 1h. Health probes excluded from both numerator and denominator. Target 99.5% (error budget 0.5%).",
"fieldConfig": {
"defaults": {
"unit": "percentunit"
},
"overrides": []
},
"options": {
"reduceOptions": {
"calcs": [
"lastNotNull"
]
},
"thresholds": {
"mode": "absolute",
"steps": [
{
"color": "red",
"value": null
},
{
"color": "orange",
"value": 0.99
},
{
"color": "green",
"value": 0.995
}
]
}
}
},
{
"id": 3,
"title": "Business RPS by route template",
"type": "timeseries",
"gridPos": {
"h": 7,
"w": 9,
"x": 6,
"y": 1
},
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"editorMode": "code",
"expr": "sum by (http_route) (rate(http_server_requests_total{service_name=\"messenger-api\",http_route!~\"/health.*\"}[$__rate_interval]))",
"legendFormat": "{{route}}",
"range": true,
"refId": "A",
"instant": false
}
],
"description": "Counter http_server_requests_total, labels are method, route template and status_class. Health routes excluded.",
"fieldConfig": {
"defaults": {
"unit": "reqps"
},
"overrides": []
}
},
{
"id": 4,
"title": "5xx error ratio (2m)",
"type": "timeseries",
"gridPos": {
"h": 7,
"w": 9,
"x": 15,
"y": 1
},
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"editorMode": "code",
"expr": "(sum(rate(http_server_requests_total{service_name=\"messenger-api\",http_route!~\"/health.*\",status_class=\"5xx\"}[2m])) or vector(0)) / clamp_min(sum(rate(http_server_requests_total{service_name=\"messenger-api\",http_route!~\"/health.*\"}[2m])), 1e-9)",
"legendFormat": "5xx ratio",
"range": true,
"refId": "A",
"instant": false
}
],
"description": "Same numerator/denominator as the high-error-rate alert. Client 4xx and health probes are not service failures.",
"fieldConfig": {
"defaults": {
"unit": "percentunit"
},
"overrides": []
}
},
{
"id": 5,
"title": "HTTP latency p50 / p95 / p99 from histogram",
"type": "timeseries",
"gridPos": {
"h": 7,
"w": 24,
"x": 0,
"y": 8
},
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"editorMode": "code",
"expr": "histogram_quantile(0.50, sum by (le) (rate(http_server_duration_seconds_bucket{service_name=\"messenger-api\",http_route!~\"/health.*\"}[$__rate_interval])))",
"legendFormat": "p50",
"range": true,
"refId": "A",
"instant": false
},
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"editorMode": "code",
"expr": "histogram_quantile(0.95, sum by (le) (rate(http_server_duration_seconds_bucket{service_name=\"messenger-api\",http_route!~\"/health.*\"}[$__rate_interval])))",
"legendFormat": "p95",
"range": true,
"refId": "B",
"instant": false
},
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"editorMode": "code",
"expr": "histogram_quantile(0.99, sum by (le) (rate(http_server_duration_seconds_bucket{service_name=\"messenger-api\",http_route!~\"/health.*\"}[$__rate_interval])))",
"legendFormat": "p99",
"range": true,
"refId": "C",
"instant": false
}
],
"description": "Percentiles are computed from the SDK histogram buckets, aggregated across API replicas by le. Never averaged from per-replica p99.",
"fieldConfig": {
"defaults": {
"unit": "s"
},
"overrides": []
}
},
{
"id": 6,
"type": "row",
"title": "Worker — jobs, saturation, end-to-end readiness",
"gridPos": {
"h": 1,
"w": 24,
"x": 0,
"y": 15
},
"collapsed": false
},
{
"id": 7,
"title": "Jobs per second by outcome",
"type": "timeseries",
"gridPos": {
"h": 7,
"w": 8,
"x": 0,
"y": 16
},
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"editorMode": "code",
"expr": "sum by (outcome) (rate(jobs_processed_total{service_name=\"messenger-worker\"}[$__rate_interval]))",
"legendFormat": "{{outcome}}",
"range": true,
"refId": "A",
"instant": false
}
],
"description": "Terminal success/failed plus retry scheduling. Duplicate no-op deliveries are not counted as processed jobs.",
"fieldConfig": {
"defaults": {
"unit": "reqps"
},
"overrides": []
}
},
{
"id": 8,
"title": "Job processing duration p95 by outcome",
"type": "timeseries",
"gridPos": {
"h": 7,
"w": 8,
"x": 8,
"y": 16
},
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"editorMode": "code",
"expr": "histogram_quantile(0.95, sum by (le, outcome) (rate(jobs_duration_seconds_bucket{service_name=\"messenger-worker\"}[$__rate_interval])))",
"legendFormat": "{{outcome}}",
"range": true,
"refId": "A",
"instant": false
}
],
"description": "Histogram jobs_duration_seconds, measured per managed attempt.",
"fieldConfig": {
"defaults": {
"unit": "s"
},
"overrides": []
}
},
{
"id": 9,
"title": "End-to-end time to ready p50/p95",
"type": "timeseries",
"gridPos": {
"h": 7,
"w": 8,
"x": 16,
"y": 16
},
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"editorMode": "code",
"expr": "histogram_quantile(0.50, sum by (le) (rate(job_time_to_ready_seconds_bucket{service_name=\"messenger-worker\"}[$__rate_interval])))",
"legendFormat": "p50",
"range": true,
"refId": "A",
"instant": false
},
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"editorMode": "code",
"expr": "histogram_quantile(0.95, sum by (le) (rate(job_time_to_ready_seconds_bucket{service_name=\"messenger-worker\"}[$__rate_interval])))",
"legendFormat": "p95",
"range": true,
"refId": "B",
"instant": false
}
],
"description": "From durable acceptance (job created_at) to the ready COMMIT. Not queue processing latency.",
"fieldConfig": {
"defaults": {
"unit": "s"
},
"overrides": []
}
},
{
"id": 10,
"title": "Queue depth (lag + pending)",
"type": "timeseries",
"gridPos": {
"h": 6,
"w": 8,
"x": 0,
"y": 23
},
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"editorMode": "code",
"expr": "max(queue_depth{service_name=\"messenger-api\"})",
"legendFormat": "attachments",
"range": true,
"refId": "A",
"instant": false
}
],
"description": "Consumer-group lag plus pending entries. Both API replicas report the same global value; max removes duplicate series.",
"fieldConfig": {
"defaults": {
"unit": "short"
},
"overrides": []
}
},
{
"id": 11,
"title": "Oldest unacknowledged job age",
"type": "timeseries",
"gridPos": {
"h": 6,
"w": 8,
"x": 8,
"y": 23
},
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"editorMode": "code",
"expr": "max(queue_oldest_age_seconds{service_name=\"messenger-api\"})",
"legendFormat": "oldest age",
"range": true,
"refId": "A",
"instant": false
}
],
"description": "Derived from the Valkey stream ID millisecond timestamp of the oldest lag/pending entry. Alert threshold 20 s.",
"fieldConfig": {
"defaults": {
"unit": "s"
},
"overrides": []
}
},
{
"id": 12,
"title": "Worker saturation (busy / capacity)",
"type": "timeseries",
"gridPos": {
"h": 6,
"w": 8,
"x": 16,
"y": 23
},
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"editorMode": "code",
"expr": "max(worker_jobs_busy{service_name=\"messenger-worker\"}) / clamp_min(max(worker_jobs_capacity{service_name=\"messenger-worker\"}), 1)",
"legendFormat": "saturation",
"range": true,
"refId": "A",
"instant": false
}
],
"description": "Bounded worker concurrency; 1.0 means every slot is busy.",
"fieldConfig": {
"defaults": {
"unit": "percentunit"
},
"overrides": []
}
},
{
"id": 13,
"type": "row",
"title": "Dependencies — DB pool, CPU/RAM, collector health",
"gridPos": {
"h": 1,
"w": 24,
"x": 0,
"y": 29
},
"collapsed": false
},
{
"id": 14,
"title": "DB pool used / idle / max",
"type": "timeseries",
"gridPos": {
"h": 6,
"w": 8,
"x": 0,
"y": 30
},
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"editorMode": "code",
"expr": "sum by (service_name) (db_pool_used)",
"legendFormat": "used {{service_name}}",
"range": true,
"refId": "A",
"instant": false
},
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"editorMode": "code",
"expr": "sum by (service_name) (db_pool_idle)",
"legendFormat": "idle {{service_name}}",
"range": true,
"refId": "B",
"instant": false
},
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"editorMode": "code",
"expr": "sum by (service_name) (db_pool_max)",
"legendFormat": "max {{service_name}}",
"range": true,
"refId": "C",
"instant": false
}
],
"description": "pgxpool AcquiredConns/IdleConns/MaxConns. Used near max with wait events is pool saturation.",
"fieldConfig": {
"defaults": {
"unit": "short"
},
"overrides": []
}
},
{
"id": 15,
"title": "DB pool acquire waits",
"type": "timeseries",
"gridPos": {
"h": 6,
"w": 8,
"x": 8,
"y": 30
},
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"editorMode": "code",
"expr": "max(db_pool_waiting{service_name=~\"messenger-.*\"})",
"legendFormat": "blocked acquires per collection",
"range": true,
"refId": "A",
"instant": false
},
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"editorMode": "code",
"expr": "sum(rate(db_pool_wait_duration_seconds{service_name=~\"messenger-.*\"}[$__rate_interval]))",
"legendFormat": "seconds spent waiting/s",
"range": true,
"refId": "A",
"instant": false
}
],
"description": "pgxpool exposes cumulative EmptyAcquireCount and AcquireDuration, not an instantaneous waiter gauge. db_pool_waiting is the delta of blocked acquires since the previous 15 s collection.",
"fieldConfig": {
"defaults": {
"unit": "short"
},
"overrides": []
}
},
{
"id": 16,
"title": "Process CPU by service",
"type": "timeseries",
"gridPos": {
"h": 6,
"w": 8,
"x": 16,
"y": 30
},
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"editorMode": "code",
"expr": "sum by (service_name) (rate(process_cpu_time_seconds_total{service_name=~\"messenger-.*\"}[$__rate_interval]))",
"legendFormat": "{{service_name}}",
"range": true,
"refId": "A",
"instant": false
}
],
"description": "Cgroup v2 cpu.stat usage_usec converted to seconds; rate over the interval. Not host CPU.",
"fieldConfig": {
"defaults": {
"unit": "percentunit"
},
"overrides": []
}
},
{
"id": 17,
"title": "Container memory by service",
"type": "timeseries",
"gridPos": {
"h": 6,
"w": 8,
"x": 0,
"y": 36
},
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"editorMode": "code",
"expr": "max by (service_name) (process_memory_usage_bytes{service_name=~\"messenger-.*\"})",
"legendFormat": "{{service_name}}",
"range": true,
"refId": "A",
"instant": false
}
],
"description": "Cgroup v2 memory.current. Includes page cache; not identical to process RSS.",
"fieldConfig": {
"defaults": {
"unit": "bytes"
},
"overrides": []
}
},
{
"id": 18,
"title": "Collector spans accepted / sent / dropped",
"type": "timeseries",
"gridPos": {
"h": 6,
"w": 8,
"x": 8,
"y": 36
},
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"editorMode": "code",
"expr": "sum(rate(otelcol_receiver_accepted_spans_total[5m]))",
"legendFormat": "accepted",
"range": true,
"refId": "A",
"instant": false
},
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"editorMode": "code",
"expr": "sum(rate(otelcol_exporter_sent_spans_total[5m]))",
"legendFormat": "sent",
"range": true,
"refId": "A",
"instant": false
},
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"editorMode": "code",
"expr": "sum(rate(otelcol_exporter_send_failed_spans_total[5m]))",
"legendFormat": "enqueue failed",
"range": true,
"refId": "A",
"instant": false
},
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"editorMode": "code",
"expr": "sum(rate(otelcol_receiver_refused_spans_total[5m]))",
"legendFormat": "refused",
"range": true,
"refId": "A",
"instant": false
}
],
"description": "Collector self-telemetry. Dropped spans prove bounded queue behaviour during a backend outage.",
"fieldConfig": {
"defaults": {
"unit": "short"
},
"overrides": []
}
},
{
"id": 19,
"title": "Collector exporter queue",
"type": "timeseries",
"gridPos": {
"h": 6,
"w": 8,
"x": 16,
"y": 36
},
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"editorMode": "code",
"expr": "max(otelcol_exporter_queue_size)",
"legendFormat": "queue size",
"range": true,
"refId": "A",
"instant": false
},
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"editorMode": "code",
"expr": "max(otelcol_exporter_queue_capacity)",
"legendFormat": "capacity",
"range": true,
"refId": "A",
"instant": false
}
],
"description": "Bounded sending queue. When full the collector drops instead of blocking the application.",
"fieldConfig": {
"defaults": {
"unit": "short"
},
"overrides": []
}
},
{
"id": 20,
"type": "row",
"title": "Logs, traces and alert state",
"gridPos": {
"h": 1,
"w": 24,
"x": 0,
"y": 42
},
"collapsed": false
},
{
"id": 21,
"title": "Firing alerts",
"type": "table",
"gridPos": {
"h": 6,
"w": 6,
"x": 0,
"y": 43
},
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"editorMode": "code",
"expr": "ALERTS{alertstate=\"firing\"}",
"legendFormat": "{{alertname}} {{severity}}",
"range": true,
"refId": "A",
"instant": false
}
],
"description": "Prometheus evaluates the rules in infra/prometheus/rules/lab6.yml. No external delivery is configured."
},
{
"id": 22,
"title": "Structured logs with trace_id/span_id (Loki)",
"type": "logs",
"gridPos": {
"h": 8,
"w": 18,
"x": 6,
"y": 43
},
"datasource": {
"type": "loki",
"uid": "loki"
},
"targets": [
{
"datasource": {
"type": "loki",
"uid": "loki"
},
"editorMode": "code",
"expr": "{service_name=~\"messenger-.*\"} | json",
"queryType": "range",
"refId": "A"
}
],
"description": "Every line carries service.name, event, trace_id and span_id. Click a trace_id to open the Tempo trace (derived field)."
},
{
"id": 23,
"title": "Trace drilldown",
"type": "text",
"gridPos": {
"h": 6,
"w": 6,
"x": 0,
"y": 49
},
"options": {
"mode": "markdown",
"content": "Open **Explore → Tempo** and search by `service.name = messenger-api` or paste a `trace_id` from the log panel.\n\nUseful queries:\n- `{ service.name = \"messenger-worker\" }`\n- `{ name = \"attachment.process\" && job.outcome = \"success\" }`\n\nThe default trace view shows API server span → S3/DB child spans → producer publish → worker consumer → S3 puts and ready COMMIT."
}
}
],
"refresh": "10s",
"schemaVersion": 39,
"tags": [
"lab6",
"observability"
],
"templating": {
"list": []
},
"time": {
"from": "now-1h",
"to": "now"
},
"timezone": "browser",
"title": "Lab6 — Messenger observability",
"uid": "lab6-observability",
"version": 1,
"weekStart": ""
}
@@ -0,0 +1,14 @@
apiVersion: 1
providers:
- name: lab6
orgId: 1
folder: Lab6
folderUid: lab6
type: file
disableDeletion: false
updateIntervalSeconds: 10
allowUiUpdates: false
options:
path: /etc/grafana/dashboards
foldersFromFilesStructure: false
@@ -0,0 +1,47 @@
apiVersion: 1
datasources:
- name: Prometheus
uid: prometheus
type: prometheus
access: proxy
url: http://prometheus:9090
isDefault: true
editable: false
jsonData:
timeInterval: 15s
httpMethod: POST
- name: Loki
uid: loki
type: loki
access: proxy
url: http://loki:3100
editable: false
jsonData:
derivedFields:
- name: trace_id
matcherRegex: '"trace_id":"([a-f0-9]{32})"'
datasourceUid: tempo
url: '$${__value.raw}'
- name: Tempo
uid: tempo
type: tempo
access: proxy
url: http://tempo:3200
editable: false
jsonData:
tracesToLogsV2:
datasourceUid: loki
filterByTraceID: true
filterBySpanID: false
spanStartTimeShift: '-2m'
spanEndTimeShift: '2m'
tags: []
nodeGraph:
enabled: true
search:
hide: false
lokiSearch:
datasourceUid: loki
+64
View File
@@ -0,0 +1,64 @@
# Lab3 public entrypoint. HAProxy discovers API replicas through Docker's
# embedded DNS and actively probes /health/ready. There is no sticky session:
# every request is balanced independently, and a backend that fails two
# consecutive probes is removed within roughly two probe intervals.
#
# The stats endpoint is bound to loopback inside the container only. It is not
# published and is used by the experiment scripts through `docker exec`.
global
log stdout format raw local0
maxconn 8192
stats socket /tmp/haproxy.sock mode 600 level admin
defaults
mode http
log global
option httplog
option dontlognull
# Per-request access logging is intentionally disabled: at thousands of
# requests per second it moves the LB bottleneck into stdout and hides the
# component under study. Errors are still logged.
option dontlog-normal
option redispatch
retries 2
timeout connect 1s
timeout client 15s
timeout server 15s
timeout http-request 5s
timeout http-keep-alive 5s
default-server inter 1s fastinter 500ms downinter 1s fall 2 rise 1
frontend public
bind :8080
mode http
default_backend api
backend api
mode http
balance roundrobin
option httpchk GET /health/ready
http-check expect status 200
# One template slot per A record returned for the compose service name.
# Docker DNS adds/removes records on scale/stop; `hold valid 1s` keeps the
# backend list current instead of caching the first resolution.
server-template api 1-10 api:8080 check resolvers docker init-addr none
resolvers docker
nameserver dns 127.0.0.11:53
resolve_retries 3
timeout resolve 1s
timeout retry 1s
hold valid 1s
hold refused 1s
hold nx 1s
hold timeout 1s
hold obsolete 1s
frontend stats
bind 127.0.0.1:8404
mode http
stats enable
stats uri /stats
stats refresh 1s
stats show-legends
+57
View File
@@ -0,0 +1,57 @@
# Loki is the logs store. The collector ships OTLP log records to the native
# /otlp/v1/logs endpoint. Structured metadata keeps trace_id/span_id searchable
# without turning them into high-cardinality labels.
auth_enabled: false
server:
http_listen_port: 3100
grpc_listen_port: 9096
log_level: warn
grpc_server_max_recv_msg_size: 16777216
grpc_server_max_send_msg_size: 16777216
common:
instance_addr: 127.0.0.1
path_prefix: /loki
storage:
filesystem:
chunks_directory: /loki/chunks
rules_directory: /loki/rules
replication_factor: 1
ring:
kvstore:
store: inmemory
schema_config:
configs:
- from: 2024-01-01
store: tsdb
object_store: filesystem
schema: v13
index:
prefix: index_
period: 24h
limits_config:
retention_period: 168h
allow_structured_metadata: true
reject_old_samples: false
max_query_series: 5000
split_queries_by_interval: 30m
compactor:
working_directory: /loki/compactor
compaction_interval: 10m
retention_enabled: true
retention_delete_delay: 2h
retention_delete_worker_count: 50
delete_request_store: filesystem
ruler:
storage:
type: local
local:
directory: /loki/rules
analytics:
reporting_enabled: false
+7
View File
@@ -0,0 +1,7 @@
# Конфигурация наблюдаемости — реализовать
Добавьте `collector.yaml` с OTLP receivers, processors и exporters выбранной версии Collector. Укажите явные bind endpoints, внутренние сети, memory limits/batch и поведение при backpressure по уровню. Сопоставьте все три pipeline с реально развёрнутыми backend.
Добавьте конфигурации storage, Grafana provisioning/datasources, provisioning/dashboards и импортируемые dashboard JSON. На 4 — alert rules и runbooks. Пустой dashboard или debug exporter, который только печатает данные в stdout, не заменяют хранилища/доказательства из `contracts/observability.md`.
Не публикуйте OTLP/metrics/административные ports в общую сеть без необходимости. В lab7 реализуйте TLS/mTLS по trust matrix; экспорт Authorization и message bodies запрещён.
+120
View File
@@ -0,0 +1,120 @@
# OpenTelemetry Collector for the lab6 stand.
#
# The collector is the only OTLP receiver. It never stores telemetry itself:
# metrics go to Prometheus (scraped from the Prometheus exporter), logs go to
# Loki's native OTLP endpoint and traces go to Tempo over OTLP/gRPC.
#
# Failure posture: memory_limiter caps RAM, batch reduces RPCs, and every
# exporter has a bounded sending queue with retry/backoff. When a backend is
# down the collector drops after its queue is full and keeps serving business
# traffic; the API and worker never block on telemetry.
receivers:
otlp:
protocols:
grpc:
endpoint: 0.0.0.0:4317
http:
endpoint: 0.0.0.0:4318
processors:
memory_limiter:
check_interval: 1s
limit_mib: 160
spike_limit_mib: 32
# Balanced track-1 configuration: keep every erroring trace and every trace
# slower than 800 ms, and sample the remaining healthy/fast traces at 10%.
# Tail sampling must see all spans of a trace, so this stand runs one
# collector instance. decision_wait bounds the in-memory wait window.
tail_sampling:
decision_wait: 6s
num_traces: 10000
expected_new_traces_per_sec: 100
policies:
- name: errors
type: status_code
status_code:
status_codes: [ERROR]
- name: slow
type: latency
latency:
threshold_ms: 800
- name: baseline
type: probabilistic
probabilistic:
sampling_percentage: 10
batch:
timeout: 5s
send_batch_size: 1024
send_batch_max_size: 2048
# The SDK already sets the resource attributes; this processor is a safety
# net for data produced by a misconfigured client.
resource/lab:
attributes:
- key: deployment.environment.name
value: lab
action: upsert
extensions:
health_check:
endpoint: 0.0.0.0:13133
exporters:
# Prometheus scrapes this endpoint. resource_to_telemetry_conversion turns
# service.name/service.instance.id into labels, which the dashboard uses to
# split the API replicas and the worker.
prometheus:
endpoint: 0.0.0.0:9464
resource_to_telemetry_conversion:
enabled: true
otlp/tempo:
endpoint: tempo:4317
tls:
insecure: true
timeout: 5s
retry_on_failure:
enabled: true
initial_interval: 1s
max_interval: 30s
max_elapsed_time: 300s
sending_queue:
enabled: true
num_consumers: 4
queue_size: 2048
otlphttp/loki:
endpoint: http://loki:3100/otlp
timeout: 5s
retry_on_failure:
enabled: true
initial_interval: 1s
max_interval: 30s
max_elapsed_time: 300s
sending_queue:
enabled: true
num_consumers: 4
queue_size: 2048
service:
extensions: [health_check]
telemetry:
logs:
level: info
metrics:
readers:
- pull:
exporter:
prometheus:
host: 0.0.0.0
port: 8888
pipelines:
traces:
receivers: [otlp]
processors: [memory_limiter, resource/lab, tail_sampling, batch]
exporters: [otlp/tempo]
metrics:
receivers: [otlp]
processors: [memory_limiter, resource/lab, batch]
exporters: [prometheus]
logs:
receivers: [otlp]
processors: [memory_limiter, resource/lab, batch]
exporters: [otlphttp/loki]
+99
View File
@@ -0,0 +1,99 @@
# OpenTelemetry Collector for the lab6 stand.
#
# The collector is the only OTLP receiver. It never stores telemetry itself:
# metrics go to Prometheus (scraped from the Prometheus exporter), logs go to
# Loki's native OTLP endpoint and traces go to Tempo over OTLP/gRPC.
#
# Failure posture: memory_limiter caps RAM, batch reduces RPCs, and every
# exporter has a bounded sending queue with retry/backoff. When a backend is
# down the collector drops after its queue is full and keeps serving business
# traffic; the API and worker never block on telemetry.
receivers:
otlp:
protocols:
grpc:
endpoint: 0.0.0.0:4317
http:
endpoint: 0.0.0.0:4318
processors:
memory_limiter:
check_interval: 1s
limit_mib: 160
spike_limit_mib: 32
batch:
timeout: 5s
send_batch_size: 1024
send_batch_max_size: 2048
# The SDK already sets the resource attributes; this processor is a safety
# net for data produced by a misconfigured client.
resource/lab:
attributes:
- key: deployment.environment.name
value: lab
action: upsert
extensions:
health_check:
endpoint: 0.0.0.0:13133
exporters:
# Prometheus scrapes this endpoint. resource_to_telemetry_conversion turns
# service.name/service.instance.id into labels, which the dashboard uses to
# split the API replicas and the worker.
prometheus:
endpoint: 0.0.0.0:9464
resource_to_telemetry_conversion:
enabled: true
otlp/tempo:
endpoint: tempo:4317
tls:
insecure: true
timeout: 5s
retry_on_failure:
enabled: true
initial_interval: 1s
max_interval: 30s
max_elapsed_time: 300s
sending_queue:
enabled: true
num_consumers: 4
queue_size: 2048
otlphttp/loki:
endpoint: http://loki:3100/otlp
timeout: 5s
retry_on_failure:
enabled: true
initial_interval: 1s
max_interval: 30s
max_elapsed_time: 300s
sending_queue:
enabled: true
num_consumers: 4
queue_size: 2048
service:
extensions: [health_check]
telemetry:
logs:
level: info
metrics:
readers:
- pull:
exporter:
prometheus:
host: 0.0.0.0
port: 8888
pipelines:
traces:
receivers: [otlp]
processors: [memory_limiter, resource/lab, batch]
exporters: [otlp/tempo]
metrics:
receivers: [otlp]
processors: [memory_limiter, resource/lab, batch]
exporters: [prometheus]
logs:
receivers: [otlp]
processors: [memory_limiter, resource/lab, batch]
exporters: [otlphttp/loki]
+22
View File
@@ -0,0 +1,22 @@
# Prometheus is the metrics store. The only application metrics source is the
# collector's Prometheus exporter; Prometheus never scrapes the API or worker
# directly. Collector self-telemetry is scraped separately so queue drops and
# refused spans are visible when a backend is unhealthy.
global:
scrape_interval: 15s
scrape_timeout: 10s
evaluation_interval: 15s
rule_files:
- /etc/prometheus/rules/*.yml
scrape_configs:
- job_name: otel-collector-application
static_configs:
- targets: ["otel-collector:9464"]
- job_name: otel-collector-internal
static_configs:
- targets: ["otel-collector:8888"]
- job_name: prometheus
static_configs:
- targets: ["127.0.0.1:9090"]
+70
View File
@@ -0,0 +1,70 @@
# Lab6 alert rules. Prometheus evaluates them and exposes the local
# firing/pending state at /api/v1/alerts; Grafana renders that state on the
# dashboard. No external delivery (email, chat) is configured or permitted.
groups:
- name: lab6-api
interval: 15s
rules:
- alert: MessengerHighApiErrorRate
# SLI: 5xx / all business HTTP requests, excluding health probes.
# Both numerator and denominator come from the same counter and the
# same route filter, so a health-check change cannot move the ratio.
expr: |
(sum(rate(http_server_requests_total{service_name="messenger-api",http_route!~"/health.*",status_class="5xx"}[2m])) or vector(0))
/
clamp_min(sum(rate(http_server_requests_total{service_name="messenger-api",http_route!~"/health.*"}[2m])), 1e-9)
> 0.05
for: 45s
labels:
severity: warning
slo: api_error_ratio
annotations:
summary: "API 5xx ratio above 5% for 45 s"
description: "The 2-minute 5xx ratio over business routes is {{ $value | humanizePercentage }}. Check the DB dependency and the failing route in the API RPS/errors panels, then follow the runbook."
runbook: "infra/prometheus/runbooks.md#high-api-error-rate"
- name: lab6-queue
interval: 15s
rules:
- alert: MessengerQueueLagGrowing
# Queue depth is the consumer-group lag plus pending entries. Oldest age
# is derived from the oldest unacknowledged stream ID, not from HTTP
# latency. Both must be abnormal: a short burst that drains is not an
# incident.
expr: |
max(queue_oldest_age_seconds{service_name="messenger-api"}) > 20
and
max(queue_depth{service_name="messenger-api"}) > 0
for: 30s
labels:
severity: warning
slo: job_latency
annotations:
summary: "Oldest unacknowledged attachment job is older than 20 s"
description: "Queue depth is {{ $labels.queue_name }} and the oldest job age is above 20 s. If the worker is down or saturated the backlog grows; see the runbook for the queue/worker triage order."
runbook: "infra/prometheus/runbooks.md#queue-lag-growing"
- name: lab6-telemetry
interval: 15s
rules:
- alert: MessengerCollectorDroppingSpans
# A non-zero drop rate means the collector queue is full or the
# memory_limiter refused data. Business traffic is unaffected, but
# observations are missing, so this alert points at the telemetry
# backend instead of the application.
expr: |
sum(rate(otelcol_exporter_send_failed_spans_total[5m])) > 0
or
sum(rate(otelcol_receiver_refused_spans_total[5m])) > 0
for: 1m
labels:
severity: info
slo: telemetry_completeness
annotations:
summary: "Collector is dropping telemetry spans"
description: "The exporter queue or the memory limiter is refusing spans. Inspect collector queue size, backend health and the incident record; application availability is not necessarily affected."
runbook: "infra/prometheus/runbooks.md#telemetry-backend-outage"
# Alertmanager delivery is intentionally not configured. The evidence for lab6
# is Prometheus /api/v1/alerts state transitions (pending -> firing -> resolved)
# plus the same state shown in Grafana.
+102
View File
@@ -0,0 +1,102 @@
# Локальные runbook'и alert'ов lab6
Все команды выполняются из корня `highload/lab6` на учебном стенде. Alert'ы
оценивает Prometheus (`http://127.0.0.1:9096`), их состояние видно в
`/api/v1/alerts` и на панели `Firing alerts` в Grafana. Внешняя доставка не
настроена и не требуется: доказательство — переход `inactive → pending →
firing → inactive` в сохранённом ответе Prometheus.
Порядок общего триажа: сначала отличить отказ приложения от отказа
зависимости по RED-метрикам API и trace, затем проверить очередь/worker, и
только потом telemetry-плоскость. Telemetry-плоскость никогда не является
причиной недоступности бизнес-API: SDK и Collector не блокируют запросы.
## high-api-error-rate
**Условие.** `MessengerHighApiErrorRate`: 5xx / все бизнес-запросы (без
`/health*`) по `http_server_requests_total` за 2 минуты выше 5% в течение
45 секунд. SLI/SLO: доступность API 99.5% на окне 1 час (панель
`SLO: API availability`).
1. Посмотреть долю и маршруты:
```sh
curl -s --get http://127.0.0.1:9096/api/v1/query \
--data-urlencode 'query=sum by (http_route) (rate(http_server_requests_total{service_name="messenger-api",http_route!~"/health.*",status_class="5xx"}[2m]))'
```
2. Проверить `/health/ready` через LB: `curl -i http://127.0.0.1:8086/health/ready`.
503 с `"code":"unavailable"` означает недоступность PostgreSQL или Valkey;
ответ 5xx на бизнес-маршруте при готовом API указывает на конкретную
зависимость (например, S3 при загрузке вложения).
3. Взять `X-Request-Id`/`X-Trace-Id` из ответа и открыть trace в Grafana →
Tempo. Наличие медленного/ошибочного `postgresql ...` или `s3.put staging`
child span отличает медленный handler от отказа зависимости.
4. Логи: `{service_name="messenger-api"} | json | request_id="<id>"`.
Секреты и тела сообщений в логи не попадают.
5. Проверить контейнеры: `make ps`, затем `docker logs --tail=100 <api>`.
PostgreSQL/S3/Valkey: `./scripts/compose.sh --env-file .env ps`.
6. После устранения причины (например, `docker start` остановленного S3)
отправить несколько успешных запросов и дождаться, пока 2-минутное окно
опустит долю ниже 5%; alert перейдёт в `inactive`.
## queue-lag-growing
**Условие.** `MessengerQueueLagGrowing`: `queue_oldest_age_seconds > 20` и
`queue_depth > 0` в течение 30 секунд. Очередь — Valkey Streams consumer
group; depth/age считаются по потоку `lab6:attachments:jobs`, а не по
latency HTTP.
1. Проверить состояние worker: `make ps`, `docker logs --tail=100 <worker>`.
Если worker остановлен, API продолжает принимать вложения (202/queued).
2. Посмотреть глубину и возраст:
```sh
curl -s --get http://127.0.0.1:9096/api/v1/query \
--data-urlencode 'query=max(queue_depth{service_name="messenger-api"})'
curl -s --get http://127.0.0.1:9096/api/v1/query \
--data-urlencode 'query=max(queue_oldest_age_seconds{service_name="messenger-api"})'
```
3. Проверить stream/outbox через операторский CLI:
`make jobctl ARGS="-op stream"`, `make jobctl ARGS="-op outbox"`.
Outbox rows с `published_at IS NULL` означают, что API не может опубликовать
задание (broker), а не что worker медленный.
4. Если worker жив, но saturation=1: `make ps`, панель `Worker saturation`.
Один worker с `WORKER_CONCURRENCY=1` — намеренный предел учебного стенда;
backlog растёт при интенсивности загрузок выше его пропускной способности.
5. Восстановление: `docker start <worker-id>` (или
`./scripts/compose.sh --env-file .env up -d --no-deps worker`). После
разбора очереди depth→0, age<20, alert становится `inactive`.
## telemetry-backend-outage
**Условие.** `MessengerCollectorDroppingSpans`: рост
`otelcol_exporter_send_failed_spans_total` или
`otelcol_receiver_refused_spans_total` в течение минуты. Бизнес-API при этом
может быть полностью работоспособен — теряются только наблюдения.
1. Проверить готовность хранилищ: `curl -s http://127.0.0.1:9096/-/ready`,
`http://127.0.0.1:3106/ready`, `http://127.0.0.1:3206/ready`,
`http://127.0.0.1:3006/api/health`.
2. Посмотреть очередь и отказы Collector:
```sh
curl -s http://127.0.0.1:8886/metrics | grep -E 'otelcol_(exporter_queue|exporter_send_failed_spans|receiver_refused_spans|process_runtime_total_sys_memory_bytes)'
```
`queue_size → queue_capacity` означает переполнение ограниченной очереди;
лимит RAM задан `memory_limiter` и `COLLECTOR_MEM_LIMIT`.
3. Убедиться, что API не затронут: `curl -s http://127.0.0.1:8086/health/ready`
и несколько бизнес-запросов; в логах API нет блокировок на telemetry.
4. Диагностика причины: `docker logs --tail=100 <collector>` (ошибки exporter,
retry/backoff), `docker logs --tail=50 <tempo|loki>`. Остановленный backend
не роняет API, но необработанные batches Collector теряет после заполнения
очереди — это ограниченная потеря наблюдений, а не данных приложения.
5. Восстановление: поднять остановленный backend, дождаться `/ready`, проверить
`<backend>_send_failed` перестал расти, и что новые traces/логи появляются.
Старые данные в persistent volumes остаются доступными после restart.
6. Записать в evidence: интервал отказа, счётчики accepted/sent/failed/refused,
max queue size, max RSS Collector, число успешных бизнес-запросов за окно.
## Общие ограничения
- Один Docker host: PostgreSQL, S3, broker и LB — единые точки отказа.
- `memory_limiter` Collector и bounded sending queues ограничивают RAM, но при
длительном отказе backend часть telemetry теряется детерминированно.
- Alert'ы не отправляются наружу: разрешённая доставка — локальное состояние
Prometheus/Grafana.
+22
View File
@@ -0,0 +1,22 @@
{
"identities": [
{
"name": "lab6-admin-bootstrap",
"credentials": [
{"accessKey": "mL6CzXp0LWD2WNoVUhRNB6uKKb276Ug9", "secretKey": "e8WQnzjk8eCujM5v4Ej6sVhOMGNdmC4g"}
],
"actions": ["Admin"]
},
{
"name": "lab6-api-bucket-scoped",
"credentials": [
{"accessKey": "SV0177Zkp0AIsWWq5faJ453mr3PKp5V3", "secretKey": "2vcFWY8iVCgETNEKWU7RCjXWlyDieshM"}
],
"actions": [
"Read:messenger-attachments",
"Write:messenger-attachments",
"List:messenger-attachments"
]
}
]
}
+43
View File
@@ -0,0 +1,43 @@
# Tempo is the traces store. It receives OTLP/gRPC from the collector and keeps
# blocks on a local persistent volume. One Tempo process serves distributor,
# ingester, querier and compactor on this single-host teaching stand.
server:
http_listen_port: 3200
grpc_listen_port: 9095
log_level: warn
distributor:
receivers:
otlp:
protocols:
grpc:
endpoint: 0.0.0.0:4317
http:
endpoint: 0.0.0.0:4318
ingester:
max_block_duration: 5m
# Smaller blocks reduce the peak memory of the local querier/compactor on
# the 2 GiB teaching VM; trace history is short-lived and block count is low.
max_block_bytes: 52428800
compactor:
compaction:
block_retention: 24h
storage:
trace:
backend: local
local:
path: /var/tempo/traces
wal:
path: /var/tempo/wal
querier:
# Eight parallel trace lookups during the track-1 experiment once pushed the
# process over its 320 MiB cap. The limit is now 448 MiB with GOMEMLIMIT set
# and query concurrency bounded; the experiment also queries with 3 workers.
max_concurrent_queries: 4
usage_report:
reporting_enabled: false
+313
View File
@@ -0,0 +1,313 @@
package api
import (
"context"
"encoding/json"
"log/slog"
"net/http"
"strings"
"sync/atomic"
"time"
"go.opentelemetry.io/otel/trace"
"mtusi.ru/messenger-lab7/internal/auth"
"mtusi.ru/messenger-lab7/internal/model"
"mtusi.ru/messenger-lab7/internal/objectstore"
"mtusi.ru/messenger-lab7/internal/session"
"mtusi.ru/messenger-lab7/internal/store"
"mtusi.ru/messenger-lab7/internal/telemetry"
)
const maxBodyBytes = 1 << 20 // far above the 4000-character message limit
type healthResponse struct {
Status string `json:"status"`
}
// identity is the authenticated principal derived only from the Bearer
// session. X-User-Id is not consulted anywhere in this package.
type identity struct {
user model.User
token string
}
// App is the HTTP layer. PostgreSQL is the source of truth for users, chats
// and messages; Valkey is the source of truth for sessions. App adds request
// validation, authentication and contract mapping.
type App struct {
store *store.Store
sessions *session.Store
objects *objectstore.Store
log *slog.Logger
ready atomic.Bool
maxBody int64
instanceID string
version string
startedAt time.Time
dummyHash string
metrics *telemetry.Instruments
tracer trace.Tracer
maxUpload int64
maxPixels int64
tempDir string
decodeSem chan struct{}
putSem chan struct{}
pipelineVersion int
jobMaxAttempts int
createdMessages atomic.Uint64
replayedMessages atomic.Uint64
conflictMessages atomic.Uint64
}
// Options carries the upload limits and concurrency bound. Values are
// validated by config.Load before the application starts.
type Options struct {
MaxUploadBytes int64
MaxImagePixels int64
DecodeConcurrency int
PutConcurrency int
TempDir string
PipelineVersion int
JobMaxAttempts int
Metrics *telemetry.Instruments
Tracer trace.Tracer
}
// New creates the HTTP application. The dummy Argon2id hash is generated once
// so login can spend the same work for an unknown username as for a known one.
func New(repository *store.Store, sessions *session.Store, objects *objectstore.Store, logger *slog.Logger, instanceID, version string, options Options) (*App, error) {
dummy, err := auth.Hash("dummy-password-never-used-for-login")
if err != nil {
return nil, err
}
if options.MaxUploadBytes <= 0 {
options.MaxUploadBytes = 10 * 1024 * 1024
}
if options.MaxImagePixels <= 0 {
options.MaxImagePixels = 40_000_000
}
if options.DecodeConcurrency <= 0 {
options.DecodeConcurrency = 1
}
if options.PutConcurrency <= 0 {
options.PutConcurrency = 1
}
if options.PipelineVersion <= 0 {
options.PipelineVersion = 1
}
if options.JobMaxAttempts <= 0 {
options.JobMaxAttempts = 5
}
if options.Tracer == nil {
options.Tracer = trace.NewNoopTracerProvider().Tracer("messenger-api")
}
if options.Metrics == nil {
options.Metrics = telemetry.NewNoopInstruments()
}
app := &App{
store: repository,
sessions: sessions,
objects: objects,
log: logger,
maxBody: maxBodyBytes,
instanceID: instanceID,
version: version,
startedAt: time.Now(),
dummyHash: dummy,
maxUpload: options.MaxUploadBytes,
maxPixels: options.MaxImagePixels,
tempDir: options.TempDir,
decodeSem: make(chan struct{}, options.DecodeConcurrency),
putSem: make(chan struct{}, options.PutConcurrency),
pipelineVersion: options.PipelineVersion,
jobMaxAttempts: options.JobMaxAttempts,
metrics: options.Metrics,
tracer: options.Tracer,
}
app.ready.Store(true)
return app, nil
}
// SetReady flips readiness. The main process clears it as soon as SIGTERM is
// received and before http.Server.Shutdown stops accepting connections.
func (a *App) SetReady(ready bool) { a.ready.Store(ready) }
// Handler returns the fully instrumented handler.
func (a *App) Handler() http.Handler {
return a.withObservability(a)
}
// ServeHTTP routes the lab3 API. Method mismatches become 404 in the contract
// error shape because the public error enum has no method_not_allowed code.
func (a *App) ServeHTTP(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/health/live":
if r.Method != http.MethodGet {
a.notFound(w, r)
return
}
a.writeJSON(w, r, http.StatusOK, healthResponse{Status: "ok"})
case "/health/ready":
if r.Method != http.MethodGet {
a.notFound(w, r)
return
}
a.readiness(w, r)
case "/api/v1/users":
if r.Method != http.MethodPost {
a.notFound(w, r)
return
}
a.createUser(w, r)
case "/api/v1/auth/sessions":
if r.Method != http.MethodPost {
a.notFound(w, r)
return
}
a.createSession(w, r)
case "/api/v1/auth/sessions/current":
if r.Method != http.MethodDelete {
a.notFound(w, r)
return
}
a.withAuth(a.logout).ServeHTTP(w, r)
case "/api/v1/users/me":
if r.Method != http.MethodGet {
a.notFound(w, r)
return
}
a.withAuth(a.currentUser).ServeHTTP(w, r)
case "/api/v1/chats":
switch r.Method {
case http.MethodGet:
a.withAuth(a.listChats).ServeHTTP(w, r)
case http.MethodPost:
a.withAuth(a.createChat).ServeHTTP(w, r)
default:
a.notFound(w, r)
}
default:
if rest, ok := trimPathPrefix(r.URL.Path, "/api/v1/attachments/"); ok {
a.withAuth(func(w http.ResponseWriter, r *http.Request, actor identity) {
a.attachmentRoutes(w, r, rest, actor)
}).ServeHTTP(w, r)
return
}
if rest, ok := trimPathPrefix(r.URL.Path, "/api/v1/chats/"); ok {
// Authentication runs before resource resolution: an anonymous
// request must not learn whether a chat id exists.
a.withAuth(func(w http.ResponseWriter, r *http.Request, actor identity) {
a.chatRoutes(w, r, rest, actor)
}).ServeHTTP(w, r)
return
}
a.notFound(w, r)
}
}
func (a *App) chatRoutes(w http.ResponseWriter, r *http.Request, rest string, actor identity) {
parts := splitPath(rest)
if len(parts) == 1 {
if r.Method != http.MethodGet {
a.notFound(w, r)
return
}
a.getChat(w, r, parts[0], actor)
return
}
if len(parts) == 2 && parts[1] == "attachments" {
if r.Method != http.MethodPost {
a.notFound(w, r)
return
}
a.createAttachment(w, r, parts[0], actor)
return
}
if len(parts) == 2 && parts[1] == "messages" {
switch r.Method {
case http.MethodGet:
a.listMessages(w, r, parts[0], actor)
case http.MethodPost:
a.createMessage(w, r, parts[0], actor)
default:
a.notFound(w, r)
}
return
}
a.notFound(w, r)
}
// withAuth resolves the Bearer session before the wrapped handler runs.
func (a *App) withAuth(next func(http.ResponseWriter, *http.Request, identity)) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
actor, problem := a.authenticate(r)
if problem != nil {
a.writeError(w, r, problem)
return
}
next(w, r, actor)
}
}
// readiness reports whether the mandatory synchronous path can be served.
// Both PostgreSQL and Valkey are critical: without PostgreSQL the API cannot
// answer, and without Valkey it cannot authenticate a single protected call.
func (a *App) readiness(w http.ResponseWriter, r *http.Request) {
if !a.ready.Load() {
a.writeError(w, r, statusUnavailable)
return
}
dbCtx, dbCancel := context.WithTimeout(r.Context(), 900*time.Millisecond)
dbErr := a.store.Ping(dbCtx)
dbCancel()
if dbErr != nil {
a.log.Log(r.Context(), slog.LevelWarn, "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.Log(r.Context(), slog.LevelWarn, "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.Log(r.Context(), slog.LevelError, "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.Log(r.Context(), slog.LevelDebug, "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
}
+504
View File
@@ -0,0 +1,504 @@
package api
import (
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"image"
_ "image/jpeg" // register the JPEG decoder used by image.DecodeConfig/Decode
_ "image/png" // register the PNG decoder used by image.DecodeConfig/Decode
"io"
"log/slog"
"mime"
"net/http"
"net/url"
"os"
"strconv"
"strings"
"syscall"
"time"
"unicode"
"unicode/utf8"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/codes"
"go.opentelemetry.io/otel/trace"
"mtusi.ru/messenger-lab7/internal/model"
"mtusi.ru/messenger-lab7/internal/objectstore"
"mtusi.ru/messenger-lab7/internal/store"
"mtusi.ru/messenger-lab7/internal/telemetry"
"mtusi.ru/messenger-lab7/internal/uuid"
)
const (
stagingPrefix = "staging/"
finalPrefix = "attachments/"
decodeWaitTimeout = 30 * time.Second
putWaitTimeout = 10 * time.Second
maxFilenameCodePoints = 255
imagePNG = "image/png"
imageJPEG = "image/jpeg"
maxImageDimensionProduct = int64(40_000_000)
attachmentQueued = "queued"
attachmentProcessing = "processing"
attachmentReady = "ready"
attachmentFailed = "failed"
)
// attachmentRoutes handles /api/v1/attachments/{id} and .../content. The caller
// has already been authenticated by withAuth.
func (a *App) attachmentRoutes(w http.ResponseWriter, r *http.Request, rest string, actor identity) {
parts := splitPath(rest)
if len(parts) == 1 {
if r.Method != http.MethodGet {
a.notFound(w, r)
return
}
a.getAttachment(w, r, parts[0], actor)
return
}
if len(parts) == 2 && parts[1] == "content" {
if r.Method != http.MethodGet {
a.notFound(w, r)
return
}
a.downloadAttachment(w, r, parts[0], actor)
return
}
a.notFound(w, r)
}
// createAttachment accepts the complete original, validates it, writes it to
// the durable staging prefix and commits the attachment/job/outbox transaction
// before returning 202. It deliberately does no resize: the worker owns every
// derivative. A 202 therefore means: the exact bytes are durable and the
// intention to process them is committed, not that processing finished.
func (a *App) createAttachment(w http.ResponseWriter, r *http.Request, rawChatID string, actor identity) {
chatID, problem := normalizePathUUID(rawChatID, "chat_id")
if problem != nil {
a.writeError(w, r, problem)
return
}
filename, problem := uploadFilename(r)
if problem != nil {
a.writeError(w, r, problem)
return
}
declared, problem := uploadMediaType(r)
if problem != nil {
a.writeError(w, r, problem)
return
}
member, err := a.store.IsChatMember(r.Context(), chatID, actor.user.ID)
if err != nil {
a.log.Log(r.Context(), slog.LevelError, "attachment membership check failed", "request_id", requestIDFromContext(r.Context()), "error", err)
if errors.Is(err, store.ErrUnavailable) {
a.writeError(w, r, statusUnavailable)
return
}
a.writeError(w, r, statusInternal)
return
}
if !member {
a.writeError(w, r, statusNotFound)
return
}
if r.ContentLength > a.maxUpload {
a.writeError(w, r, statusPayloadTooLarge)
return
}
temp, err := os.CreateTemp(a.tempDir, "lab6-upload-*")
if err != nil {
a.log.Log(r.Context(), slog.LevelError, "could not create upload temp file", "request_id", requestIDFromContext(r.Context()), "error", err)
a.writeError(w, r, statusUnavailable)
return
}
tempName := temp.Name()
defer func() {
_ = temp.Close()
_ = os.Remove(tempName)
}()
hasher := sha256.New()
body := http.MaxBytesReader(w, r.Body, a.maxUpload)
written, err := io.Copy(io.MultiWriter(temp, hasher), body)
if err != nil {
var tooLarge *http.MaxBytesError
switch {
case errors.As(err, &tooLarge):
a.writeError(w, r, statusPayloadTooLarge)
case errors.Is(err, syscall.ENOSPC):
a.log.Log(r.Context(), slog.LevelError, "upload temp file is full", "request_id", requestIDFromContext(r.Context()))
a.writeError(w, r, statusUnavailable)
default:
a.writeError(w, r, invalidRequest("could not read the upload body"))
}
return
}
if written > a.maxUpload {
a.writeError(w, r, statusPayloadTooLarge)
return
}
if written == 0 {
a.writeError(w, r, unsupportedMediaType("the upload body is empty"))
return
}
detected, width, height, problem := a.validateImage(r.Context(), temp, declared)
if problem != nil {
a.writeError(w, r, problem)
return
}
sum := hex.EncodeToString(hasher.Sum(nil))
attachmentID := uuid.New()
jobID := uuid.New()
stagingKey := stagingPrefix + attachmentID
objectKey := finalPrefix + attachmentID + "/original"
createdAt := time.Now().UTC()
record := store.AttachmentRecord{
Attachment: model.Attachment{
ID: attachmentID,
ChatID: chatID,
OwnerID: actor.user.ID,
Filename: filename,
ContentType: detected,
SizeBytes: written,
SHA256: sum,
Status: attachmentQueued,
Variants: []model.Variant{},
ErrorCode: nil,
CreatedAt: model.Time{Time: createdAt},
UpdatedAt: model.Time{Time: createdAt},
},
ObjectKey: objectKey,
StagingKey: stagingKey,
PipelineVersion: a.pipelineVersion,
}
if _, err := temp.Seek(0, io.SeekStart); err != nil {
a.writeError(w, r, statusInternal)
return
}
// Bound simultaneous S3 writes per replica. The body is already streamed to
// a bounded temporary file, so waiting here does not accumulate RAM.
putCtx, putSpan := a.tracer.Start(r.Context(), "s3.put staging",
trace.WithSpanKind(trace.SpanKindClient),
trace.WithAttributes(
attribute.String("aws.s3.operation", "PutObject"),
attribute.String("aws.s3.bucket", a.objects.Bucket()),
attribute.String("aws.s3.object_role", "staging"),
attribute.Int64("aws.s3.object_size_bytes", written),
),
)
select {
case a.putSem <- struct{}{}:
err = a.objects.Put(putCtx, stagingKey, temp, written, detected)
<-a.putSem
case <-time.After(putWaitTimeout):
a.log.Log(r.Context(), slog.LevelWarn, "staging upload queue timed out", "request_id", requestIDFromContext(r.Context()),
"attachment_id", attachmentID)
a.writeError(w, r, statusUnavailable)
return
case <-r.Context().Done():
putSpan.End()
a.writeError(w, r, statusUnavailable)
return
}
if err != nil {
putSpan.RecordError(err)
putSpan.SetStatus(codes.Error, "staging upload failed")
}
putSpan.End()
if err != nil {
a.log.Log(r.Context(), slog.LevelError, "staging upload failed", "request_id", requestIDFromContext(r.Context()),
"attachment_id", attachmentID, "error", err)
if errors.Is(err, objectstore.ErrUnavailable) || errors.Is(err, objectstore.ErrNotFound) {
a.writeError(w, r, statusUnavailable)
return
}
a.writeError(w, r, statusInternal)
return
}
traceParent, traceState := telemetry.TraceContext(r.Context())
if err := a.store.CreateAttachmentWithJob(r.Context(), record, jobID, a.jobMaxAttempts, createdAt, traceParent, traceState); err != nil {
// The staging object is durable but no row owns it. Best-effort cleanup;
// the worker janitor removes an orphan after the retention grace period
// if this delete also fails.
cleanupCtx, cleanupCancel := context.WithTimeout(context.Background(), 3*time.Second)
_ = a.objects.Remove(cleanupCtx, stagingKey)
cleanupCancel()
a.log.Log(r.Context(), slog.LevelError, "could not record attachment intent", "request_id", requestIDFromContext(r.Context()),
"attachment_id", attachmentID, "job_id", jobID, "error", err)
if errors.Is(err, store.ErrUnavailable) {
a.writeError(w, r, statusUnavailable)
return
}
a.writeError(w, r, statusInternal)
return
}
a.log.Log(r.Context(), slog.LevelInfo, "attachment accepted",
"request_id", requestIDFromContext(r.Context()),
"attachment_id", attachmentID,
"job_id", jobID,
"chat_id", chatID,
"size_bytes", written,
"content_type", detected,
"image_width", width,
"image_height", height,
"pipeline_version", a.pipelineVersion,
"status", attachmentQueued,
)
a.writeJSON(w, r, http.StatusAccepted, record.Attachment)
}
// validateImage applies every content rule before staging or PostgreSQL is
// touched. The declared media type must match the bytes; the decoded pixel count
// is checked from the header before a potentially large full decode.
func (a *App) validateImage(ctx context.Context, temp *os.File, declared string) (detected string, width, height int, problem *apiError) {
if _, err := temp.Seek(0, io.SeekStart); err != nil {
return "", 0, 0, statusInternal
}
header := make([]byte, 512)
n, err := io.ReadFull(temp, header)
if err != nil && !errors.Is(err, io.ErrUnexpectedEOF) {
return "", 0, 0, unsupportedMediaType("the upload body is not a valid image")
}
detected = http.DetectContentType(header[:n])
if detected != imagePNG && detected != imageJPEG {
return "", 0, 0, unsupportedMediaType("only PNG and JPEG images are accepted")
}
if declared != detected {
return "", 0, 0, unsupportedMediaType("Content-Type does not match the image bytes")
}
if _, err := temp.Seek(0, io.SeekStart); err != nil {
return "", 0, 0, statusInternal
}
config, format, err := image.DecodeConfig(temp)
if err != nil || (format != "png" && format != "jpeg") {
return "", 0, 0, unsupportedMediaType("the image header is corrupt or unsupported")
}
if config.Width < 1 || config.Height < 1 {
return "", 0, 0, unsupportedMediaType("the image has invalid dimensions")
}
pixels := int64(config.Width) * int64(config.Height)
if pixels > a.maxPixels || pixels > maxImageDimensionProduct {
return "", 0, 0, statusPayloadTooLarge
}
select {
case a.decodeSem <- struct{}{}:
defer func() { <-a.decodeSem }()
case <-time.After(decodeWaitTimeout):
return "", 0, 0, statusUnavailable
case <-ctx.Done():
return "", 0, 0, statusUnavailable
}
if _, err := temp.Seek(0, io.SeekStart); err != nil {
return "", 0, 0, statusInternal
}
decoded, _, err := image.Decode(temp)
if err != nil {
return "", 0, 0, unsupportedMediaType("the image is corrupt or truncated")
}
bounds := decoded.Bounds()
if bounds.Dx() < 1 || bounds.Dy() < 1 {
return "", 0, 0, unsupportedMediaType("the image has invalid dimensions")
}
return detected, bounds.Dx(), bounds.Dy(), nil
}
// uploadMediaType parses the declared Content-Type strictly. Parameters are
// accepted; any other media type is rejected before the body is read.
func uploadMediaType(r *http.Request) (string, *apiError) {
raw := strings.TrimSpace(r.Header.Get("Content-Type"))
if raw == "" {
return "", unsupportedMediaType("Content-Type must be image/png or image/jpeg")
}
mediaType, _, err := mime.ParseMediaType(raw)
if err != nil || (mediaType != imagePNG && mediaType != imageJPEG) {
return "", unsupportedMediaType("Content-Type must be image/png or image/jpeg")
}
return mediaType, nil
}
// uploadFilename validates the display-only filename query parameter. The value
// is never used as a path, object key or S3 prefix.
func uploadFilename(r *http.Request) (string, *apiError) {
query, err := url.ParseQuery(r.URL.RawQuery)
if err != nil {
return "", invalidRequest("query string is not valid")
}
values, present := query["filename"]
if !present || len(values) != 1 || values[0] == "" {
return "", invalidRequest("filename query parameter is required exactly once")
}
name := values[0]
if !utf8.ValidString(name) {
return "", invalidRequest("filename must be valid UTF-8")
}
if count := utf8.RuneCountInString(name); count < 1 || count > maxFilenameCodePoints {
return "", invalidRequest("filename must contain 1 to 255 Unicode code points")
}
if name == "." || name == ".." {
return "", invalidRequest("filename must not be a path component")
}
for _, char := range name {
if char == '/' || char == '\\' || char == 0 || unicode.IsControl(char) {
return "", invalidRequest("filename must not contain path separators, NUL or control characters")
}
}
return name, nil
}
func (a *App) getAttachment(w http.ResponseWriter, r *http.Request, rawID string, actor identity) {
attachmentID, problem := normalizePathUUID(rawID, "attachment_id")
if problem != nil {
a.writeError(w, r, problem)
return
}
record, err := a.store.AttachmentForUser(r.Context(), attachmentID, actor.user.ID)
if err != nil {
switch {
case errors.Is(err, store.ErrNotFound):
a.writeError(w, r, statusNotFound)
case errors.Is(err, store.ErrUnavailable):
a.log.Log(r.Context(), slog.LevelError, "attachment metadata lookup failed", "request_id", requestIDFromContext(r.Context()), "error", err)
a.writeError(w, r, statusUnavailable)
default:
a.log.Log(r.Context(), slog.LevelError, "attachment metadata lookup failed", "request_id", requestIDFromContext(r.Context()), "error", err)
a.writeError(w, r, statusInternal)
}
return
}
// A ready row with missing bytes must not be presented as a finished
// result. Queued/processing rows intentionally have no final object yet.
if record.Status == attachmentReady {
if _, err := a.objects.Stat(r.Context(), record.ObjectKey); err != nil {
switch {
case errors.Is(err, objectstore.ErrNotFound):
a.writeError(w, r, statusNotFound)
case errors.Is(err, objectstore.ErrUnavailable):
a.log.Log(r.Context(), slog.LevelError, "attachment object stat failed", "request_id", requestIDFromContext(r.Context()), "error", err)
a.writeError(w, r, statusUnavailable)
default:
a.log.Log(r.Context(), slog.LevelError, "attachment object stat failed", "request_id", requestIDFromContext(r.Context()), "error", err)
a.writeError(w, r, statusInternal)
}
return
}
}
a.writeJSON(w, r, http.StatusOK, record.Attachment)
}
func (a *App) downloadAttachment(w http.ResponseWriter, r *http.Request, rawID string, actor identity) {
attachmentID, problem := normalizePathUUID(rawID, "attachment_id")
if problem != nil {
a.writeError(w, r, problem)
return
}
// ACL and state are resolved before the variant name is interpreted, so a
// foreign attachment is always 404 and an unfinished attachment is 409.
record, err := a.store.AttachmentForUser(r.Context(), attachmentID, actor.user.ID)
if err != nil {
switch {
case errors.Is(err, store.ErrNotFound):
a.writeError(w, r, statusNotFound)
case errors.Is(err, store.ErrUnavailable):
a.log.Log(r.Context(), slog.LevelError, "attachment download lookup failed", "request_id", requestIDFromContext(r.Context()), "error", err)
a.writeError(w, r, statusUnavailable)
default:
a.log.Log(r.Context(), slog.LevelError, "attachment download lookup failed", "request_id", requestIDFromContext(r.Context()), "error", err)
a.writeError(w, r, statusInternal)
}
return
}
variantName, problem := attachmentVariant(r)
if problem != nil {
a.writeError(w, r, problem)
return
}
if record.Status != attachmentReady {
a.writeError(w, r, conflict("attachment is not ready"))
return
}
objectKey := record.ObjectKey
contentType := record.ContentType
if variantName != "original" {
variant, err := a.store.VariantObject(r.Context(), record, variantName)
if err != nil {
switch {
case errors.Is(err, store.ErrNotFound):
a.writeError(w, r, statusNotFound)
case errors.Is(err, store.ErrAttachmentNotReady):
a.writeError(w, r, conflict("attachment is not ready"))
case errors.Is(err, store.ErrUnavailable):
a.log.Log(r.Context(), slog.LevelError, "attachment variant lookup failed", "request_id", requestIDFromContext(r.Context()), "error", err)
a.writeError(w, r, statusUnavailable)
default:
a.log.Log(r.Context(), slog.LevelError, "attachment variant lookup failed", "request_id", requestIDFromContext(r.Context()), "error", err)
a.writeError(w, r, statusInternal)
}
return
}
objectKey = variant.ObjectKey
contentType = variant.ContentType
}
body, info, err := a.objects.Get(r.Context(), objectKey)
if err != nil {
switch {
case errors.Is(err, objectstore.ErrNotFound):
a.writeError(w, r, statusNotFound)
case errors.Is(err, objectstore.ErrUnavailable):
a.log.Log(r.Context(), slog.LevelError, "attachment object read failed", "request_id", requestIDFromContext(r.Context()), "error", err)
a.writeError(w, r, statusUnavailable)
default:
a.log.Log(r.Context(), slog.LevelError, "attachment object read failed", "request_id", requestIDFromContext(r.Context()), "error", err)
a.writeError(w, r, statusInternal)
}
return
}
defer body.Close()
w.Header().Set("Content-Type", contentType)
w.Header().Set("Content-Length", strconv.FormatInt(info.Size, 10))
w.Header().Set("X-Content-Type-Options", "nosniff")
w.Header().Set("Cache-Control", "private, no-store")
w.WriteHeader(http.StatusOK)
if _, err := io.Copy(w, body); err != nil {
a.log.Log(r.Context(), slog.LevelWarn, "attachment stream interrupted", "request_id", requestIDFromContext(r.Context()),
"attachment_id", attachmentID, "variant", variantName, "error", err)
}
}
// attachmentVariant parses the optional variant query parameter. The default is
// original; an unknown name is a 404 after the caller has passed the ACL.
func attachmentVariant(r *http.Request) (string, *apiError) {
query, err := url.ParseQuery(r.URL.RawQuery)
if err != nil {
return "", invalidRequest("query string is not valid")
}
values, present := query["variant"]
if !present {
return "original", nil
}
if len(values) != 1 || values[0] == "" {
return "", invalidRequest("variant must be a non-empty string")
}
switch values[0] {
case "original", "thumbnail", "crop", "optimized":
return values[0], nil
default:
return "", statusNotFound
}
}
+138
View File
@@ -0,0 +1,138 @@
package api
import (
"errors"
"log/slog"
"net/http"
"mtusi.ru/messenger-lab7/internal/cursor"
"mtusi.ru/messenger-lab7/internal/store"
"mtusi.ru/messenger-lab7/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.Log(r.Context(), slog.LevelError, "create chat failed", "request_id", requestIDFromContext(r.Context()), "error", err)
a.writeError(w, r, statusUnavailable)
return
case err != nil:
a.log.Log(r.Context(), slog.LevelError, "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.Log(r.Context(), slog.LevelError, "list chats failed", "request_id", requestIDFromContext(r.Context()), "error", err)
a.writeError(w, r, statusUnavailable)
return
}
a.log.Log(r.Context(), slog.LevelError, "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.Log(r.Context(), slog.LevelError, "get chat failed", "request_id", requestIDFromContext(r.Context()), "error", err)
a.writeError(w, r, statusUnavailable)
return
case err != nil:
a.log.Log(r.Context(), slog.LevelError, "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
}
+258
View File
@@ -0,0 +1,258 @@
package api
import (
"context"
"fmt"
"log/slog"
"net/http"
"strings"
"sync/atomic"
"time"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/codes"
"go.opentelemetry.io/otel/propagation"
"go.opentelemetry.io/otel/trace"
"mtusi.ru/messenger-lab7/internal/uuid"
)
// apiError is a contract-shaped error: HTTP status, machine-readable code, a
// safe human-readable message and an optional authentication challenge. The
// request id is filled from the request context at write time.
type apiError struct {
status int
code string
message string
challenge string
}
func (e *apiError) Error() string { return e.code + ": " + e.message }
const (
basicChallenge = `Basic realm="messenger", charset="UTF-8"`
bearerChallenge = `Bearer realm="messenger"`
)
var (
statusInvalidRequest = &apiError{status: http.StatusBadRequest, code: "invalid_request", message: "request validation failed"}
statusNotFound = &apiError{status: http.StatusNotFound, code: "not_found", message: "object not found"}
statusConflict = &apiError{status: http.StatusConflict, code: "conflict", message: "object already exists"}
statusPayloadTooLarge = &apiError{status: http.StatusRequestEntityTooLarge, code: "payload_too_large", message: "request body is too large"}
statusUnsupportedMediaType = &apiError{status: http.StatusUnsupportedMediaType, code: "unsupported_media_type", message: "Content-Type must be application/json"}
statusUnavailable = &apiError{status: http.StatusServiceUnavailable, code: "unavailable", message: "a required dependency is unavailable"}
statusInternal = &apiError{status: http.StatusInternalServerError, code: "internal_error", message: "internal server error"}
)
func invalidRequest(message string) *apiError {
return &apiError{status: http.StatusBadRequest, code: "invalid_request", message: message}
}
func conflict(message string) *apiError {
return &apiError{status: http.StatusConflict, code: "conflict", message: message}
}
func unsupportedMediaType(message string) *apiError {
return &apiError{status: http.StatusUnsupportedMediaType, code: "unsupported_media_type", message: message}
}
func unauthorizedBasic() *apiError {
return &apiError{status: http.StatusUnauthorized, code: "unauthorized", message: "invalid username or password", challenge: basicChallenge}
}
func unauthorizedBearer() *apiError {
return &apiError{status: http.StatusUnauthorized, code: "unauthorized", message: "a valid bearer session is required", challenge: bearerChallenge}
}
type errorEnvelope struct {
Error errorBody `json:"error"`
}
type errorBody struct {
Code string `json:"code"`
Message string `json:"message"`
RequestID string `json:"request_id"`
}
// writeError writes a JSON error whose request_id matches X-Request-Id. The
// message never contains SQL, stack traces, credentials or object existence
// details for foreign resources.
func (a *App) writeError(w http.ResponseWriter, r *http.Request, problem *apiError) {
requestID := requestIDFromContext(r.Context())
if requestID == "" {
requestID = w.Header().Get("X-Request-Id")
}
if requestID == "" {
requestID = uuid.NewRandom(16)
w.Header().Set("X-Request-Id", requestID)
}
if problem.challenge != "" {
w.Header().Set("WWW-Authenticate", problem.challenge)
}
a.writeJSON(w, r, problem.status, errorEnvelope{Error: errorBody{
Code: problem.code,
Message: problem.message,
RequestID: requestID,
}})
}
func (a *App) notFound(w http.ResponseWriter, r *http.Request) {
a.writeError(w, r, statusNotFound)
}
type requestIDContextKey struct{}
func requestIDFromContext(ctx context.Context) string {
value, _ := ctx.Value(requestIDContextKey{}).(string)
return value
}
// statusWriter records the status code and byte count for logs and for the
// panic path, so a partially written response is not written twice.
type statusWriter struct {
http.ResponseWriter
status int
bytes int
wrote bool
}
func (w *statusWriter) WriteHeader(code int) {
if w.wrote {
return
}
w.wrote = true
w.status = code
w.ResponseWriter.WriteHeader(code)
}
func (w *statusWriter) Write(data []byte) (int, error) {
if !w.wrote {
w.WriteHeader(http.StatusOK)
}
written, err := w.ResponseWriter.Write(data)
w.bytes += written
return written, err
}
func (a *App) withObservability(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
requestID := uuid.NewRandom(16)
w.Header().Set("X-Request-Id", requestID)
// Stable for the life of the process and unique per container. lab3
// uses the container hostname: it is the actual process identity, so
// stop-one can map a response to exactly one container. lab7 will
// replace it with an opaque alias.
w.Header().Set("X-Instance-Id", a.instanceID)
// Extra, non-contract header used only to observe an image replacement
// during the rolling-update experiment. The mandatory contract does
// not define or require it.
w.Header().Set("X-App-Version", a.version)
// Continue an incoming W3C trace when a caller supplies one. The
// public black-box tests do not, so their uploads start a new trace.
ctx := otel.GetTextMapPropagator().Extract(r.Context(), propagation.HeaderCarrier(r.Header))
route := routeTemplate(r.URL.Path)
ctx, span := a.tracer.Start(ctx, route,
trace.WithSpanKind(trace.SpanKindServer),
trace.WithAttributes(
attribute.String("http.request.method", r.Method),
attribute.String("http.route", route),
attribute.String("network.protocol.version", r.Proto),
),
)
defer span.End()
if span.SpanContext().IsValid() {
// Non-contract debugging header. It is not used for authorization
// and contains no secret; it makes the trace of a request directly
// discoverable by a synthetic load generator.
w.Header().Set("X-Trace-Id", span.SpanContext().TraceID().String())
}
r = r.WithContext(context.WithValue(ctx, requestIDContextKey{}, requestID))
writer := &statusWriter{ResponseWriter: w, status: http.StatusOK}
defer func() {
if recovered := recover(); recovered != nil {
span.RecordError(fmt.Errorf("panic: %v", recovered))
span.SetStatus(codes.Error, "panic")
a.log.Log(r.Context(), slog.LevelError, "panic while handling request",
"request_id", requestID,
"instance_id", a.instanceID,
"method", r.Method,
"route", route,
"panic", recovered,
)
if !writer.wrote {
a.writeError(writer, r, statusInternal)
}
}
duration := time.Since(start)
span.SetAttributes(attribute.Int("http.response.status_code", writer.status))
if writer.status >= 500 {
span.SetStatus(codes.Error, "server error")
span.SetAttributes(attribute.String("error.type", "http_5xx"))
}
a.metrics.HTTPRequest(r.Context(), r.Method, route, writer.status, duration)
level := slog.LevelInfo
if route == "/health/live" || route == "/health/ready" {
level = slog.LevelDebug
}
a.log.Log(r.Context(), level, "http request",
"request_id", requestID,
"instance_id", a.instanceID,
"method", r.Method,
"route", route,
"status", writer.status,
"duration_s", duration.Seconds(),
"bytes", writer.bytes,
)
}()
next.ServeHTTP(writer, r)
})
}
// routeTemplate maps a request path to a bounded metric label. Real UUIDs,
// filenames and query strings never become label values.
func routeTemplate(path string) string {
switch path {
case "/health/live", "/health/ready",
"/api/v1/users", "/api/v1/users/me",
"/api/v1/auth/sessions", "/api/v1/auth/sessions/current",
"/api/v1/chats":
return path
}
if rest, ok := strings.CutPrefix(path, "/api/v1/attachments/"); ok {
parts := strings.Split(rest, "/")
if len(parts) == 2 && parts[1] == "content" && parts[0] != "" {
return "/api/v1/attachments/{attachment_id}/content"
}
if len(parts) == 1 && parts[0] != "" {
return "/api/v1/attachments/{attachment_id}"
}
return "unmatched"
}
if rest, ok := strings.CutPrefix(path, "/api/v1/chats/"); ok {
parts := strings.Split(rest, "/")
if len(parts) == 1 && parts[0] != "" {
return "/api/v1/chats/{chat_id}"
}
if len(parts) == 2 && parts[0] != "" {
switch parts[1] {
case "attachments":
return "/api/v1/chats/{chat_id}/attachments"
case "messages":
return "/api/v1/chats/{chat_id}/messages"
}
}
}
return "unmatched"
}
// 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() }
+214
View File
@@ -0,0 +1,214 @@
package api
import (
"bytes"
"crypto/sha256"
"encoding/json"
"errors"
"log/slog"
"net/http"
"unicode/utf8"
"mtusi.ru/messenger-lab7/internal/cursor"
"mtusi.ru/messenger-lab7/internal/store"
"mtusi.ru/messenger-lab7/internal/uuid"
)
const maxMessageAttachments = 10
type createMessageRequest struct {
Text *string `json:"text"`
AttachmentIDs json.RawMessage `json:"attachment_ids"`
}
// messageHash is the canonical semantic body used for idempotency. A missing
// attachment_ids is normalised to [], exactly as the contract requires, and
// JSON object key order never affects the hash. Array order is preserved: the
// response also preserves it.
type messageHashBody struct {
Text string `json:"text"`
AttachmentIDs []string `json:"attachment_ids"`
}
func (a *App) createMessage(w http.ResponseWriter, r *http.Request, rawChatID string, actor identity) {
chatID, problem := normalizePathUUID(rawChatID, "chat_id")
if problem != nil {
a.writeError(w, r, problem)
return
}
// The key is validated before the body, but after authentication and path
// validation: a malformed/missing key is always 400, while an outsider
// still cannot learn anything by replaying someone else's key.
idempotencyKey, problem := idempotencyKey(r)
if problem != nil {
a.writeError(w, r, problem)
return
}
// Resource access is checked before the body is decoded so a foreign chat
// always looks like a missing chat, independent of the submitted payload.
member, err := a.store.IsChatMember(r.Context(), chatID, actor.user.ID)
if err != nil {
if errors.Is(err, store.ErrUnavailable) {
a.log.Log(r.Context(), slog.LevelError, "membership check failed", "request_id", requestIDFromContext(r.Context()), "error", err)
a.writeError(w, r, statusUnavailable)
return
}
a.log.Log(r.Context(), slog.LevelError, "membership check failed", "request_id", requestIDFromContext(r.Context()), "error", err)
a.writeError(w, r, statusInternal)
return
}
if !member {
a.writeError(w, r, statusNotFound)
return
}
var request createMessageRequest
if problem := a.decodeJSON(r, &request, "text", "attachment_ids"); problem != nil {
a.writeError(w, r, problem)
return
}
if request.Text == nil {
a.writeError(w, r, invalidRequest("text is required"))
return
}
attachmentIDs, problem := parseAttachmentIDs(request.AttachmentIDs)
if problem != nil {
a.writeError(w, r, problem)
return
}
if utf8.RuneCountInString(*request.Text) > 4000 {
a.writeError(w, r, invalidRequest("text must contain at most 4000 Unicode code points"))
return
}
if isBlank(*request.Text) && len(attachmentIDs) == 0 {
a.writeError(w, r, invalidRequest("text must not be blank without attachments"))
return
}
canonical, err := json.Marshal(messageHashBody{Text: *request.Text, AttachmentIDs: attachmentIDs})
if err != nil {
a.writeError(w, r, statusInternal)
return
}
hash := sha256.Sum256(canonical)
message, replayed, err := a.store.CreateMessageIdempotent(
r.Context(), chatID, actor.user.ID, http.MethodPost, messagePath(chatID),
idempotencyKey, hash[:], *request.Text, attachmentIDs,
)
switch {
case errors.Is(err, store.ErrIdempotencyConflict):
a.conflictMessages.Add(1)
a.writeError(w, r, statusConflict)
return
case errors.Is(err, store.ErrAttachmentNotReady):
a.writeError(w, r, conflict("attachment is not ready"))
return
case errors.Is(err, store.ErrNotFound):
a.writeError(w, r, statusNotFound)
return
case errors.Is(err, store.ErrUnavailable):
a.log.Log(r.Context(), slog.LevelError, "create message failed", "request_id", requestIDFromContext(r.Context()), "error", err)
a.writeError(w, r, statusUnavailable)
return
case err != nil:
a.log.Log(r.Context(), slog.LevelError, "create message failed", "request_id", requestIDFromContext(r.Context()), "error", err)
a.writeError(w, r, statusInternal)
return
}
if replayed {
a.replayedMessages.Add(1)
} else {
a.createdMessages.Add(1)
}
a.writeJSON(w, r, http.StatusCreated, message)
}
// parseAttachmentIDs accepts an absent field as [], rejects null and every
// wrong JSON type, and enforces the UUID / uniqueness / count rules before any
// database access.
func parseAttachmentIDs(raw json.RawMessage) ([]string, *apiError) {
if len(bytes.TrimSpace(raw)) == 0 {
return []string{}, nil
}
if bytes.Equal(bytes.TrimSpace(raw), []byte("null")) {
return nil, invalidRequest("attachment_ids must be an array, not null")
}
var values []string
if err := json.Unmarshal(raw, &values); err != nil {
return nil, invalidRequest("attachment_ids must be an array of UUID strings")
}
if len(values) > maxMessageAttachments {
return nil, invalidRequest("attachment_ids must contain at most 10 items")
}
result := make([]string, 0, len(values))
seen := make(map[string]struct{}, len(values))
for _, value := range values {
id, ok := uuid.Normalize(value)
if !ok {
return nil, invalidRequest("every attachment_ids entry must be a UUID")
}
if _, duplicate := seen[id]; duplicate {
return nil, invalidRequest("attachment_ids must not contain duplicates")
}
seen[id] = struct{}{}
result = append(result, id)
}
return result, nil
}
func messagePath(chatID string) string {
return "/api/v1/chats/" + chatID + "/messages"
}
func (a *App) listMessages(w http.ResponseWriter, r *http.Request, rawChatID string, actor identity) {
chatID, problem := normalizePathUUID(rawChatID, "chat_id")
if problem != nil {
a.writeError(w, r, problem)
return
}
// A foreign/nonexistent chat is always 404, even if the query itself is
// malformed; this avoids making object existence observable.
member, err := a.store.IsChatMember(r.Context(), chatID, actor.user.ID)
if err != nil {
if errors.Is(err, store.ErrUnavailable) {
a.log.Log(r.Context(), slog.LevelError, "membership check failed", "request_id", requestIDFromContext(r.Context()), "error", err)
a.writeError(w, r, statusUnavailable)
return
}
a.log.Log(r.Context(), slog.LevelError, "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.Log(r.Context(), slog.LevelError, "list messages failed", "request_id", requestIDFromContext(r.Context()), "error", err)
a.writeError(w, r, statusUnavailable)
return
}
a.log.Log(r.Context(), slog.LevelError, "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)
}
+158
View File
@@ -0,0 +1,158 @@
package api
import (
"errors"
"log/slog"
"net/http"
"strings"
"unicode/utf8"
"mtusi.ru/messenger-lab7/internal/auth"
"mtusi.ru/messenger-lab7/internal/model"
"mtusi.ru/messenger-lab7/internal/session"
"mtusi.ru/messenger-lab7/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.Log(r.Context(), slog.LevelError, "login database unavailable", "request_id", requestIDFromContext(r.Context()), "error", err)
a.writeError(w, r, statusUnavailable)
return
case err != nil:
a.log.Log(r.Context(), slog.LevelError, "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.Log(r.Context(), slog.LevelError, "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.Log(r.Context(), slog.LevelError, "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.Log(r.Context(), slog.LevelError, "session lookup failed", "request_id", requestIDFromContext(r.Context()), "error", err)
return identity{}, statusUnavailable
case err != nil:
a.log.Log(r.Context(), slog.LevelError, "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.Log(r.Context(), slog.LevelError, "user lookup failed", "request_id", requestIDFromContext(r.Context()), "error", err)
return identity{}, statusUnavailable
case err != nil:
a.log.Log(r.Context(), slog.LevelError, "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.Log(r.Context(), slog.LevelError, "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
}
+75
View File
@@ -0,0 +1,75 @@
package api
import (
"errors"
"log/slog"
"net/http"
"mtusi.ru/messenger-lab7/internal/auth"
"mtusi.ru/messenger-lab7/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.Log(r.Context(), slog.LevelError, "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.Log(r.Context(), slog.LevelError, "create user failed", "request_id", requestIDFromContext(r.Context()), "error", err)
a.writeError(w, r, statusUnavailable)
return
case err != nil:
a.log.Log(r.Context(), slog.LevelError, "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
}
+296
View File
@@ -0,0 +1,296 @@
// Package broker is the durable job transport for lab6. It uses Valkey
// Streams with a consumer group: XADD is the publisher confirm (the stream id
// is returned only after the broker persisted the entry), XREADGROUP delivers
// at least once, XACK confirms processing and XAUTOCLAIM recovers entries whose
// consumer died before acknowledging them.
//
// The stream entry contains one field, "job", with the JSON document defined by
// contracts/jobs.schema.json. It never contains image bytes, object paths or
// credentials.
package broker
import (
"context"
"errors"
"fmt"
"strconv"
"strings"
"time"
"github.com/redis/go-redis/v9"
)
// ErrGroupExists is returned when the consumer group already exists.
var ErrGroupExists = errors.New("consumer group already exists")
// Config is the validated broker connection.
type Config struct {
URL string
Stream string
Group string
Timeout time.Duration
}
// Broker wraps the Streams commands used by the API publisher and the worker.
type Broker struct {
client *redis.Client
stream string
group string
}
// Open parses a redis:// URL and verifies connectivity. The URL may contain a
// password; it is never logged or included in returned errors.
func Open(ctx context.Context, cfg Config) (*Broker, error) {
if strings.TrimSpace(cfg.URL) == "" {
return nil, errors.New("BROKER_URL is required")
}
options, err := redis.ParseURL(cfg.URL)
if err != nil {
return nil, errors.New("BROKER_URL is not a valid redis:// URL")
}
if options.DB != 0 {
return nil, errors.New("BROKER_URL must use database 0")
}
if cfg.Timeout > 0 {
options.DialTimeout = cfg.Timeout
options.ReadTimeout = cfg.Timeout
options.WriteTimeout = cfg.Timeout
}
options.MaxRetries = 1
client := redis.NewClient(options)
pingCtx, cancel := context.WithTimeout(ctx, 3*time.Second)
defer cancel()
if err := client.Ping(pingCtx).Err(); err != nil {
_ = client.Close()
return nil, fmt.Errorf("broker is unavailable: %w", err)
}
return &Broker{client: client, stream: cfg.Stream, group: cfg.Group}, nil
}
// Close releases the connection pool.
func (b *Broker) Close() error { return b.client.Close() }
// Ping is used by the worker healthcheck and startup wait loop.
func (b *Broker) Ping(ctx context.Context) error { return b.client.Ping(ctx).Err() }
// EnsureGroup creates the stream and consumer group idempotently. A repeated
// call is safe and is what every worker start relies on.
func (b *Broker) EnsureGroup(ctx context.Context) error {
err := b.client.XGroupCreateMkStream(ctx, b.stream, b.group, "0").Err()
if err == nil {
return nil
}
if strings.Contains(err.Error(), "BUSYGROUP") {
return ErrGroupExists
}
return err
}
// Publish appends one job entry and returns its stream id. The id is the
// publisher-confirm boundary: when XADD returns, the configured broker
// durability (AOF every write) has persisted the entry.
func (b *Broker) Publish(ctx context.Context, payload []byte) (string, error) {
if len(payload) == 0 {
return "", errors.New("refusing to publish an empty job payload")
}
id, err := b.client.XAdd(ctx, &redis.XAddArgs{
Stream: b.stream,
Values: map[string]any{"job": string(payload)},
}).Result()
if err != nil {
return "", err
}
return id, nil
}
// Message is one delivered stream entry.
type Message struct {
ID string
Payload string
}
// Read blocks for up to block waiting for new entries for this consumer. It is
// called with Count=1 by every bounded worker slot, so prefetch never exceeds
// the configured concurrency.
func (b *Broker) Read(ctx context.Context, consumer string, block time.Duration, count int64) ([]Message, error) {
result, err := b.client.XReadGroup(ctx, &redis.XReadGroupArgs{
Group: b.group,
Consumer: consumer,
Streams: []string{b.stream, ">"},
Count: count,
Block: block,
}).Result()
if errors.Is(err, redis.Nil) {
return nil, nil
}
if err != nil {
return nil, err
}
return flatten(result), nil
}
// AutoClaim takes ownership of pending entries idle for at least minIdle. It is
// the redelivery path for a worker that crashed after delivery but before ack.
func (b *Broker) AutoClaim(ctx context.Context, consumer string, minIdle time.Duration, start string, count int64) ([]Message, string, error) {
messages, next, err := b.client.XAutoClaim(ctx, &redis.XAutoClaimArgs{
Stream: b.stream,
Group: b.group,
Consumer: consumer,
MinIdle: minIdle,
Start: start,
Count: count,
}).Result()
if errors.Is(err, redis.Nil) {
return nil, start, nil
}
if err != nil {
return nil, start, err
}
return flattenMessages(messages), next, nil
}
// Ack confirms a delivered entry. It is called only after the durable database
// effect (or a safe no-op decision) is committed.
func (b *Broker) Ack(ctx context.Context, id string) error {
_, err := b.client.XAck(ctx, b.stream, b.group, id).Result()
return err
}
// AckBatch confirms several entries in one command.
func (b *Broker) AckBatch(ctx context.Context, ids []string) error {
if len(ids) == 0 {
return nil
}
_, err := b.client.XAck(ctx, b.stream, b.group, ids...).Result()
return err
}
// Delete removes one stream entry. It is used only by the track-2 reorder
// fault: the entry is withheld from delivery and republished later, after a
// newer pipeline-version message. Normal operation never deletes accepted jobs.
func (b *Broker) Delete(ctx context.Context, id string) error {
_, err := b.client.XDel(ctx, b.stream, id).Result()
return err
}
// Pending reports the pending-entries count for the group. It is used by the
// student checks and the REPORT evidence; it is not on the API hot path.
func (b *Broker) Pending(ctx context.Context) (int64, error) {
result, err := b.client.XPending(ctx, b.stream, b.group).Result()
if err != nil {
return 0, err
}
return result.Count, nil
}
// StreamLen reports the number of entries retained in the stream.
func (b *Broker) StreamLen(ctx context.Context) (int64, error) {
return b.client.XLen(ctx, b.stream).Result()
}
// Entries returns up to count entries from the stream for inspection by the
// operator/test CLI. It does not consume or acknowledge anything.
func (b *Broker) Entries(ctx context.Context, count int64) ([]Message, error) {
// Newest first: the operator CLI shows recent deliveries, not the oldest
// entries retained since the stream was created.
items, err := b.client.XRevRangeN(ctx, b.stream, "+", "-", count).Result()
if err != nil {
return nil, err
}
return flattenMessages(items), nil
}
// QueueStats is the small, bounded snapshot the API exports as queue gauges.
// Depth counts entries the group has not acknowledged yet (undelivered lag plus
// the pending list). Oldest is the age of the oldest such entry, derived from
// the stream ID millisecond timestamp, not from processing timestamps.
type QueueStats struct {
Depth int64
Oldest time.Duration
}
// QueueStats reads the consumer group lag and the age of the oldest
// unacknowledged entry. It is called by the metric callback every collection
// interval, never on the request path.
func (b *Broker) QueueStats(ctx context.Context) (QueueStats, error) {
groups, err := b.client.XInfoGroups(ctx, b.stream).Result()
if err != nil {
return QueueStats{}, err
}
var lag, pending int64
var lastDelivered string
for _, group := range groups {
if group.Name == b.group {
lag = group.Lag
pending = group.Pending
lastDelivered = group.LastDeliveredID
break
}
}
stats := QueueStats{Depth: lag + pending}
if stats.Depth <= 0 {
return stats, nil
}
var oldestMillis int64
if pending > 0 {
summary, pendingErr := b.client.XPending(ctx, b.stream, b.group).Result()
if pendingErr == nil && summary.Count > 0 {
if millis, ok := streamIDMillis(summary.Lower); ok {
oldestMillis = millis
}
}
}
if lag > 0 {
start := "-"
if lastDelivered != "" && lastDelivered != "0-0" {
start = "(" + lastDelivered
}
items, rangeErr := b.client.XRangeN(ctx, b.stream, start, "+", 1).Result()
if rangeErr == nil && len(items) > 0 {
if millis, ok := streamIDMillis(items[0].ID); ok && (oldestMillis == 0 || millis < oldestMillis) {
oldestMillis = millis
}
}
}
if oldestMillis > 0 {
stats.Oldest = time.Since(time.UnixMilli(oldestMillis))
if stats.Oldest < 0 {
stats.Oldest = 0
}
}
return stats, nil
}
func streamIDMillis(id string) (int64, bool) {
index := strings.IndexByte(id, '-')
if index <= 0 {
return 0, false
}
millis, err := strconv.ParseInt(id[:index], 10, 64)
if err != nil {
return 0, false
}
return millis, true
}
// Stream and Group are safe identifiers for CLI output; they never include the
// broker URL or credentials.
func (b *Broker) Stream() string { return b.stream }
func (b *Broker) Group() string { return b.group }
func flatten(result []redis.XStream) []Message {
out := make([]Message, 0, 4)
for _, stream := range result {
out = append(out, flattenMessages(stream.Messages)...)
}
return out
}
func flattenMessages(messages []redis.XMessage) []Message {
out := make([]Message, 0, len(messages))
for _, message := range messages {
payload, _ := message.Values["job"].(string)
out = append(out, Message{ID: message.ID, Payload: payload})
}
return out
}
+503
View File
@@ -0,0 +1,503 @@
// Package config loads the explicit runtime configuration of the lab3
// messenger. The container image stays immutable: the same image is configured
// through environment variables (or files referenced by *_FILE variables for
// operators that do not want secrets in the environment).
package config
import (
"fmt"
"log/slog"
"os"
"strconv"
"strings"
"time"
)
const (
// DefaultSessionTTL is the contract default of contracts/README.md.
DefaultSessionTTL = time.Hour
// MaxShutdownTimeout leaves headroom below the 10 second termination
// window promised by the previous lab and expected by the container
// checks, even if an operator overrides the environment variable.
MaxShutdownTimeout = 9 * time.Second
// MaxStartupTimeout bounds the initial PostgreSQL connectivity wait.
MaxStartupTimeout = 120 * time.Second
)
// Config is validated at startup. The process refuses to start with an
// invalid value instead of silently falling back to a different security or
// durability posture.
type Config struct {
Host string
Port int
Env string
LogLevel slog.Level
ShutdownTimeout time.Duration
ShutdownDrain time.Duration
StartupTimeout time.Duration
MetricsAddr string
DatabaseURL string
CacheURL string
SessionTTL time.Duration
DBMaxConns int32
DBMinConns int32
DBConnectTimeout time.Duration
DBStatementTimeout time.Duration
QueryTimeout time.Duration
CachePoolSize int
CacheTimeout time.Duration
S3Endpoint string
S3Region string
S3Bucket string
S3AccessKey string
S3SecretKey string
S3Timeout time.Duration
MaxUploadBytes int64
MaxImagePixels int64
DecodeConcurrency int
PutConcurrency int
TempDir string
// Lab6 asynchronous pipeline.
BrokerURL string
BrokerStream string
BrokerGroup string
PipelineVersion int
JobMaxAttempts int
JobTimeout time.Duration
JobLease time.Duration
ClaimIdle time.Duration
BackoffBase time.Duration
BackoffMax time.Duration
StagingRetention time.Duration
OutboxPoll time.Duration
OutboxBatch int
WorkerConcurrency int
FaultInject string
FaultTargetAttachmentID string
}
// Load reads and validates the full API configuration. The API publishes the
// transactional outbox to the durable broker, so BROKER_URL is mandatory.
func Load() (Config, error) { return load(true, true, true) }
// LoadMigrate loads only what the one-shot migration command needs.
func LoadMigrate() (Config, error) { return load(false, false, false) }
// LoadTool loads the database and S3 configuration used by the bucket CLI.
func LoadTool() (Config, error) { return load(false, true, false) }
// LoadJobctl loads the database and broker configuration used by the job
// operator CLI. S3 and Valkey are not required.
func LoadJobctl() (Config, error) { return load(false, false, true) }
// LoadWorker loads the worker configuration: PostgreSQL, S3 and the broker.
// The session store is not used by the worker.
func LoadWorker() (Config, error) { return load(false, true, true) }
// load is the shared parser. requireCache, requireS3 and requireBroker select
// which dependency blocks are mandatory for the calling command.
func load(requireCache, requireS3, requireBroker bool) (Config, error) {
cfg := Config{
Host: envString("APP_HOST", "0.0.0.0"),
Env: envString("APP_ENV", "lab"),
ShutdownTimeout: 6 * time.Second,
ShutdownDrain: 3 * time.Second,
StartupTimeout: 30 * time.Second,
QueryTimeout: 3 * time.Second,
MetricsAddr: envString("METRICS_ADDR", "127.0.0.1:9090"),
}
port, err := envInt("APP_PORT", 8080)
if err != nil {
return Config{}, fmt.Errorf("APP_PORT: %w", err)
}
if port < 1 || port > 65535 {
return Config{}, fmt.Errorf("APP_PORT: must be between 1 and 65535")
}
cfg.Port = port
level, err := parseLogLevel(envString("LOG_LEVEL", "info"))
if err != nil {
return Config{}, fmt.Errorf("LOG_LEVEL: %w", err)
}
cfg.LogLevel = level
if strings.TrimSpace(cfg.Host) == "" {
return Config{}, fmt.Errorf("APP_HOST: must not be empty")
}
databaseURL, err := secret("DATABASE_URL")
if err != nil {
return Config{}, err
}
cfg.DatabaseURL = databaseURL
if requireCache {
cacheURL, err := secret("CACHE_URL")
if err != nil {
return Config{}, err
}
cfg.CacheURL = cacheURL
}
seconds, err := envInt("SESSION_TTL_SECONDS", int(DefaultSessionTTL/time.Second))
if err != nil {
return Config{}, fmt.Errorf("SESSION_TTL_SECONDS: %w", err)
}
if seconds < 1 || seconds > 30*24*60*60 {
return Config{}, fmt.Errorf("SESSION_TTL_SECONDS: must be between 1 and 2592000")
}
cfg.SessionTTL = time.Duration(seconds) * time.Second
maxConns, err := envInt("DB_MAX_CONNS", 8)
if err != nil {
return Config{}, fmt.Errorf("DB_MAX_CONNS: %w", err)
}
if maxConns < 1 || maxConns > 100 {
return Config{}, fmt.Errorf("DB_MAX_CONNS: must be between 1 and 100")
}
cfg.DBMaxConns = int32(maxConns)
minConns, err := envInt("DB_MIN_CONNS", 1)
if err != nil {
return Config{}, fmt.Errorf("DB_MIN_CONNS: %w", err)
}
if minConns < 0 || minConns > maxConns {
return Config{}, fmt.Errorf("DB_MIN_CONNS: must be between 0 and DB_MAX_CONNS")
}
cfg.DBMinConns = int32(minConns)
if cfg.DBConnectTimeout, err = envDurationSeconds("DB_CONNECT_TIMEOUT_SECONDS", 3, 1, 30); err != nil {
return Config{}, err
}
if cfg.DBStatementTimeout, err = envDurationSeconds("DB_STATEMENT_TIMEOUT_SECONDS", 3, 1, 60); err != nil {
return Config{}, err
}
if cfg.QueryTimeout, err = envDurationSeconds("DB_QUERY_TIMEOUT_SECONDS", 3, 1, 60); err != nil {
return Config{}, err
}
cachePool, err := envInt("CACHE_POOL_SIZE", 8)
if err != nil {
return Config{}, fmt.Errorf("CACHE_POOL_SIZE: %w", err)
}
if cachePool < 1 || cachePool > 100 {
return Config{}, fmt.Errorf("CACHE_POOL_SIZE: must be between 1 and 100")
}
cfg.CachePoolSize = cachePool
if cfg.CacheTimeout, err = envDurationSeconds("CACHE_TIMEOUT_SECONDS", 2, 1, 30); err != nil {
return Config{}, err
}
shutdown, err := envDurationSeconds("SHUTDOWN_TIMEOUT_SECONDS", 6, 1, 60)
if err != nil {
return Config{}, err
}
if shutdown > MaxShutdownTimeout {
shutdown = MaxShutdownTimeout
}
cfg.ShutdownTimeout = shutdown
drain, err := envDurationSeconds("SHUTDOWN_DRAIN_SECONDS", 3, 0, 8)
if err != nil {
return Config{}, err
}
// The drain must finish before the hard shutdown window; otherwise a
// SIGTERM could spend the whole grace period advertising readiness and
// never reach http.Server.Shutdown.
if drain >= shutdown {
return Config{}, fmt.Errorf("SHUTDOWN_DRAIN_SECONDS must be smaller than SHUTDOWN_TIMEOUT_SECONDS")
}
cfg.ShutdownDrain = drain
startup, err := envDurationSeconds("STARTUP_TIMEOUT_SECONDS", 30, 1, 120)
if err != nil {
return Config{}, err
}
cfg.StartupTimeout = startup
if requireS3 {
if err := loadS3(&cfg); err != nil {
return Config{}, err
}
}
if requireBroker {
brokerURL, err := secret("BROKER_URL")
if err != nil {
return Config{}, err
}
cfg.BrokerURL = brokerURL
cfg.BrokerStream = envString("BROKER_STREAM", "lab6:attachments:jobs")
cfg.BrokerGroup = envString("BROKER_GROUP", "attachment-workers")
}
if err := loadPipeline(&cfg); err != nil {
return Config{}, err
}
return cfg, nil
}
// loadPipeline parses the asynchronous-pipeline settings shared by the API,
// the worker and the operator CLI. Defaults are documented in REPORT.md and
// .env.example. The API only uses the outbox/version/attempt fields; the worker
// additionally uses the lease, timeout and concurrency bounds.
func loadPipeline(cfg *Config) error {
version, err := envInt("PIPELINE_VERSION", 1)
if err != nil {
return fmt.Errorf("PIPELINE_VERSION: %w", err)
}
if version < 1 || version > 2 {
return fmt.Errorf("PIPELINE_VERSION: must be 1 or 2 on this stand")
}
cfg.PipelineVersion = version
attempts, err := envInt("JOB_MAX_ATTEMPTS", 5)
if err != nil {
return fmt.Errorf("JOB_MAX_ATTEMPTS: %w", err)
}
if attempts < 1 || attempts > 10 {
return fmt.Errorf("JOB_MAX_ATTEMPTS: must be between 1 and 10")
}
cfg.JobMaxAttempts = attempts
if cfg.JobTimeout, err = envDurationSeconds("JOB_TIMEOUT_SECONDS", 60, 5, 300); err != nil {
return err
}
if cfg.JobLease, err = envDurationSeconds("JOB_LEASE_SECONDS", 90, 10, 600); err != nil {
return err
}
if cfg.JobLease < cfg.JobTimeout+5*time.Second {
return fmt.Errorf("JOB_LEASE_SECONDS must be at least JOB_TIMEOUT_SECONDS + 5")
}
if cfg.ClaimIdle, err = envDurationSeconds("WORKER_CLAIM_IDLE_SECONDS", int(cfg.JobLease/time.Second)+30, 10, 900); err != nil {
return err
}
if cfg.ClaimIdle < cfg.JobLease {
return fmt.Errorf("WORKER_CLAIM_IDLE_SECONDS must be at least JOB_LEASE_SECONDS")
}
if cfg.BackoffBase, err = envDurationSeconds("JOB_BACKOFF_BASE_SECONDS", 1, 1, 60); err != nil {
return err
}
if cfg.BackoffMax, err = envDurationSeconds("JOB_BACKOFF_MAX_SECONDS", 30, 2, 600); err != nil {
return err
}
if cfg.BackoffMax < cfg.BackoffBase {
return fmt.Errorf("JOB_BACKOFF_MAX_SECONDS must be at least JOB_BACKOFF_BASE_SECONDS")
}
if cfg.StagingRetention, err = envDurationSeconds("STAGING_RETENTION_SECONDS", 3600, 10, 86400); err != nil {
return err
}
pollMS, err := envInt("OUTBOX_POLL_MS", 200)
if err != nil {
return fmt.Errorf("OUTBOX_POLL_MS: %w", err)
}
if pollMS < 50 || pollMS > 5000 {
return fmt.Errorf("OUTBOX_POLL_MS: must be between 50 and 5000")
}
cfg.OutboxPoll = time.Duration(pollMS) * time.Millisecond
batch, err := envInt("OUTBOX_BATCH", 10)
if err != nil {
return fmt.Errorf("OUTBOX_BATCH: %w", err)
}
if batch < 1 || batch > 100 {
return fmt.Errorf("OUTBOX_BATCH: must be between 1 and 100")
}
cfg.OutboxBatch = batch
concurrency, err := envInt("WORKER_CONCURRENCY", 1)
if err != nil {
return fmt.Errorf("WORKER_CONCURRENCY: %w", err)
}
if concurrency < 1 || concurrency > 8 {
return fmt.Errorf("WORKER_CONCURRENCY: must be between 1 and 8")
}
cfg.WorkerConcurrency = concurrency
cfg.FaultInject = envString("FAULT_INJECT", "none")
switch cfg.FaultInject {
case "none", "crash_before_side_effect", "crash_after_side_effect",
"crash_after_commit_before_ack", "transient_once", "transient_always":
default:
return fmt.Errorf("FAULT_INJECT: unknown scenario %q", cfg.FaultInject)
}
cfg.FaultTargetAttachmentID = envString("FAULT_TARGET_ATTACHMENT_ID", "")
return nil
}
// loadS3 parses the private object store configuration and the image limits
// that must be enforced before any unbounded read or decode.
func loadS3(cfg *Config) error {
endpoint, err := secret("S3_ENDPOINT")
if err != nil {
return err
}
cfg.S3Endpoint = endpoint
cfg.S3Region = envString("S3_REGION", "us-east-1")
cfg.S3Bucket = envString("S3_BUCKET", "messenger-attachments")
if !validBucketName(cfg.S3Bucket) {
return fmt.Errorf("S3_BUCKET: must match [a-z0-9][a-z0-9.-]{1,61}[a-z0-9]")
}
accessKey, err := secret("S3_ACCESS_KEY")
if err != nil {
return err
}
secretKey, err := secret("S3_SECRET_KEY")
if err != nil {
return err
}
cfg.S3AccessKey = accessKey
cfg.S3SecretKey = secretKey
timeout, err := envDurationSeconds("S3_TIMEOUT_SECONDS", 10, 5, 120)
if err != nil {
return err
}
cfg.S3Timeout = timeout
maxUpload, err := envInt64("MAX_UPLOAD_BYTES", 10*1024*1024)
if err != nil {
return fmt.Errorf("MAX_UPLOAD_BYTES: %w", err)
}
if maxUpload < 1 || maxUpload > 10*1024*1024 {
return fmt.Errorf("MAX_UPLOAD_BYTES: must be between 1 and 10485760")
}
cfg.MaxUploadBytes = maxUpload
maxPixels, err := envInt64("MAX_IMAGE_PIXELS", 40_000_000)
if err != nil {
return fmt.Errorf("MAX_IMAGE_PIXELS: %w", err)
}
if maxPixels < 1 || maxPixels > 40_000_000 {
return fmt.Errorf("MAX_IMAGE_PIXELS: must be between 1 and 40000000")
}
cfg.MaxImagePixels = maxPixels
concurrency, err := envInt("UPLOAD_DECODE_CONCURRENCY", 1)
if err != nil {
return fmt.Errorf("UPLOAD_DECODE_CONCURRENCY: %w", err)
}
if concurrency < 1 || concurrency > 4 {
return fmt.Errorf("UPLOAD_DECODE_CONCURRENCY: must be between 1 and 4")
}
cfg.DecodeConcurrency = concurrency
// The single-node SeaweedFS stand was verified stable at one concurrent
// PUT per API replica; two concurrent multi-megabyte writes could restart
// it. Uploads queue after their body was already streamed to a bounded
// temporary file, so queuing does not add unbounded RAM.
putConcurrency, err := envInt("S3_PUT_CONCURRENCY", 1)
if err != nil {
return fmt.Errorf("S3_PUT_CONCURRENCY: %w", err)
}
if putConcurrency != 1 {
return fmt.Errorf("S3_PUT_CONCURRENCY: must be 1 on this single-node stand")
}
cfg.PutConcurrency = putConcurrency
cfg.TempDir = envString("UPLOAD_TEMP_DIR", "")
return nil
}
func validBucketName(value string) bool {
if len(value) < 3 || len(value) > 63 {
return false
}
for i := 0; i < len(value); i++ {
c := value[i]
if (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '.' || c == '-' {
continue
}
return false
}
return value[0] != '.' && value[0] != '-' && value[len(value)-1] != '.' && value[len(value)-1] != '-'
}
// secret resolves NAME or NAME_FILE. A file is preferred when both are set so
// compose-style file secrets win over inherited environment values. Values are
// never echoed in error messages.
func secret(name string) (string, error) {
if path := strings.TrimSpace(os.Getenv(name + "_FILE")); path != "" {
data, err := os.ReadFile(path)
if err != nil {
return "", fmt.Errorf("%s_FILE: cannot read referenced file", name)
}
value := strings.TrimSpace(string(data))
if value == "" {
return "", fmt.Errorf("%s_FILE: referenced file is empty", name)
}
return value, nil
}
if value := strings.TrimSpace(os.Getenv(name)); value != "" {
return value, nil
}
return "", fmt.Errorf("%s or %s_FILE is required", name, name)
}
func envString(key, fallback string) string {
// An environment variable set to an empty string is treated as unset; this
// keeps container defaults working when compose passes "" for an optional
// setting.
if value := strings.TrimSpace(os.Getenv(key)); value != "" {
return value
}
return fallback
}
func envInt(key string, fallback int) (int, error) {
raw, ok := os.LookupEnv(key)
if !ok || strings.TrimSpace(raw) == "" {
return fallback, nil
}
value, err := strconv.Atoi(strings.TrimSpace(raw))
if err != nil {
return 0, fmt.Errorf("expected an integer, got %q", raw)
}
return value, nil
}
func envInt64(key string, fallback int64) (int64, error) {
raw, ok := os.LookupEnv(key)
if !ok || strings.TrimSpace(raw) == "" {
return fallback, nil
}
value, err := strconv.ParseInt(strings.TrimSpace(raw), 10, 64)
if err != nil {
return 0, fmt.Errorf("expected an integer, got %q", raw)
}
return value, nil
}
func envDurationSeconds(key string, fallback, minimum, maximum int) (time.Duration, error) {
value, err := envInt(key, fallback)
if err != nil {
return 0, fmt.Errorf("%s: %w", key, err)
}
if value < minimum || value > maximum {
return 0, fmt.Errorf("%s: must be between %d and %d", key, minimum, maximum)
}
return time.Duration(value) * time.Second, nil
}
func parseLogLevel(raw string) (slog.Level, error) {
switch strings.ToLower(strings.TrimSpace(raw)) {
case "debug":
return slog.LevelDebug, nil
case "info":
return slog.LevelInfo, nil
case "warn", "warning":
return slog.LevelWarn, nil
case "error":
return slog.LevelError, nil
default:
return 0, fmt.Errorf("expected debug, info, warn or error, got %q", raw)
}
}
+218
View File
@@ -0,0 +1,218 @@
package config
import (
"os"
"path/filepath"
"testing"
"time"
)
var allKeys = []string{
"APP_HOST", "APP_PORT", "APP_ENV", "LOG_LEVEL", "SESSION_TTL_SECONDS",
"DB_MAX_CONNS", "DB_MIN_CONNS", "DB_CONNECT_TIMEOUT_SECONDS",
"DB_STATEMENT_TIMEOUT_SECONDS", "DB_QUERY_TIMEOUT_SECONDS",
"CACHE_POOL_SIZE", "CACHE_TIMEOUT_SECONDS", "SHUTDOWN_TIMEOUT_SECONDS",
"STARTUP_TIMEOUT_SECONDS", "DATABASE_URL", "DATABASE_URL_FILE",
"CACHE_URL", "CACHE_URL_FILE",
"S3_ENDPOINT", "S3_ENDPOINT_FILE", "S3_REGION", "S3_BUCKET",
"S3_ACCESS_KEY", "S3_ACCESS_KEY_FILE", "S3_SECRET_KEY", "S3_SECRET_KEY_FILE",
"S3_TIMEOUT_SECONDS", "MAX_UPLOAD_BYTES", "MAX_IMAGE_PIXELS",
"UPLOAD_DECODE_CONCURRENCY", "S3_PUT_CONCURRENCY", "UPLOAD_TEMP_DIR",
"BROKER_URL", "BROKER_URL_FILE", "BROKER_STREAM", "BROKER_GROUP",
"PIPELINE_VERSION", "JOB_MAX_ATTEMPTS", "JOB_TIMEOUT_SECONDS",
"JOB_LEASE_SECONDS", "WORKER_CLAIM_IDLE_SECONDS", "JOB_BACKOFF_BASE_SECONDS",
"JOB_BACKOFF_MAX_SECONDS", "STAGING_RETENTION_SECONDS", "OUTBOX_POLL_MS",
"OUTBOX_BATCH", "WORKER_CONCURRENCY", "FAULT_INJECT", "FAULT_TARGET_ATTACHMENT_ID",
}
func clearEnvironment(t *testing.T) {
t.Helper()
for _, key := range allKeys {
t.Setenv(key, "")
}
}
func baseEnvironment(t *testing.T) {
t.Helper()
clearEnvironment(t)
t.Setenv("DATABASE_URL", "postgres://user:pass@postgres:5432/db?sslmode=disable")
t.Setenv("CACHE_URL", "redis://:pass@valkey:6379/0")
t.Setenv("S3_ENDPOINT", "http://s3:8333")
t.Setenv("S3_BUCKET", "messenger-attachments")
t.Setenv("S3_ACCESS_KEY", "local-test-access")
t.Setenv("S3_SECRET_KEY", "local-test-secret")
t.Setenv("BROKER_URL", "redis://:pass@broker: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)
}
if cfg.MaxUploadBytes != 10*1024*1024 || cfg.MaxImagePixels != 40_000_000 || cfg.DecodeConcurrency != 1 {
t.Fatalf("unexpected upload defaults: %+v", cfg)
}
if cfg.S3Bucket != "messenger-attachments" || cfg.S3Region != "us-east-1" {
t.Fatalf("unexpected S3 defaults: %+v", cfg)
}
}
func TestLoadReadsSecretsFromFiles(t *testing.T) {
clearEnvironment(t)
directory := t.TempDir()
databaseFile := filepath.Join(directory, "database_url")
cacheFile := filepath.Join(directory, "cache_url")
if err := os.WriteFile(databaseFile, []byte("postgres://file:secret@postgres/db\n"), 0o600); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(cacheFile, []byte("redis://:file-secret@valkey:6379/0\n"), 0o600); err != nil {
t.Fatal(err)
}
t.Setenv("DATABASE_URL_FILE", databaseFile)
t.Setenv("CACHE_URL_FILE", cacheFile)
t.Setenv("S3_ENDPOINT", "http://s3:8333")
t.Setenv("S3_ACCESS_KEY", "file-test-access")
t.Setenv("S3_SECRET_KEY", "file-test-secret")
t.Setenv("BROKER_URL", "redis://:file-secret@broker:6379/0")
cfg, err := Load()
if err != nil {
t.Fatalf("Load: %v", err)
}
if cfg.DatabaseURL != "postgres://file:secret@postgres/db" {
t.Fatalf("database URL was not read from file: %q", cfg.DatabaseURL)
}
if cfg.CacheURL != "redis://:file-secret@valkey:6379/0" {
t.Fatalf("cache URL was not read from file: %q", cfg.CacheURL)
}
}
func TestLoadRejectsInvalidValues(t *testing.T) {
cases := []struct {
name string
key string
value string
}{
{"zero ttl", "SESSION_TTL_SECONDS", "0"},
{"huge ttl", "SESSION_TTL_SECONDS", "99999999"},
{"zero port", "APP_PORT", "0"},
{"bad log level", "LOG_LEVEL", "verbose"},
{"zero max conns", "DB_MAX_CONNS", "0"},
{"min above max", "DB_MIN_CONNS", "9"},
{"bad timeout", "DB_QUERY_TIMEOUT_SECONDS", "0"},
{"bad int", "APP_PORT", "eighty"},
{"upload above contract", "MAX_UPLOAD_BYTES", "10485761"},
{"pixels above contract", "MAX_IMAGE_PIXELS", "40000001"},
{"zero decode concurrency", "UPLOAD_DECODE_CONCURRENCY", "0"},
{"zero put concurrency", "S3_PUT_CONCURRENCY", "0"},
{"unsafe put concurrency", "S3_PUT_CONCURRENCY", "2"},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
baseEnvironment(t)
t.Setenv(tc.key, tc.value)
if _, err := Load(); err == nil {
t.Fatalf("Load accepted %s=%q", tc.key, tc.value)
}
})
}
}
func TestLoadRequiresDatabaseAndCacheURLs(t *testing.T) {
clearEnvironment(t)
if _, err := Load(); err == nil {
t.Fatal("Load accepted missing DATABASE_URL/CACHE_URL")
}
t.Setenv("DATABASE_URL", "postgres://user:pass@postgres/db")
if _, err := Load(); err == nil {
t.Fatal("Load accepted missing CACHE_URL")
}
}
func TestLoadRequiresS3Configuration(t *testing.T) {
baseEnvironment(t)
t.Setenv("S3_ACCESS_KEY", "")
if _, err := Load(); err == nil {
t.Fatal("Load accepted missing S3_ACCESS_KEY")
}
t.Setenv("S3_ACCESS_KEY", "local-test-access")
t.Setenv("S3_BUCKET", "Invalid_Bucket")
if _, err := Load(); err == nil {
t.Fatal("Load accepted an invalid S3 bucket name")
}
}
func TestLoadRequiresBrokerURL(t *testing.T) {
baseEnvironment(t)
t.Setenv("BROKER_URL", "")
if _, err := Load(); err == nil {
t.Fatal("Load accepted missing BROKER_URL")
}
}
func TestLoadRejectsInvalidPipelineSettings(t *testing.T) {
cases := []struct {
name string
key string
value string
}{
{"unsupported pipeline version", "PIPELINE_VERSION", "3"},
{"zero attempts", "JOB_MAX_ATTEMPTS", "0"},
{"lease below timeout", "JOB_LEASE_SECONDS", "20"},
{"claim idle below lease", "WORKER_CLAIM_IDLE_SECONDS", "1"},
{"unknown fault", "FAULT_INJECT", "crash_everything"},
{"bad outbox poll", "OUTBOX_POLL_MS", "1"},
{"bad concurrency", "WORKER_CONCURRENCY", "0"},
}
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 TestMigrateConfigurationDoesNotRequireCacheOrS3(t *testing.T) {
clearEnvironment(t)
t.Setenv("DATABASE_URL", "postgres://user:pass@postgres:5432/db?sslmode=disable")
cfg, err := LoadMigrate()
if err != nil {
t.Fatalf("LoadMigrate: %v", err)
}
if cfg.DatabaseURL == "" || cfg.CacheURL != "" || cfg.S3Endpoint != "" {
t.Fatalf("unexpected migrate configuration: %+v", cfg)
}
}
func TestShutdownTimeoutIsClamped(t *testing.T) {
baseEnvironment(t)
t.Setenv("SHUTDOWN_TIMEOUT_SECONDS", "60")
cfg, err := Load()
if err != nil {
t.Fatalf("Load: %v", err)
}
if cfg.ShutdownTimeout != MaxShutdownTimeout {
t.Fatalf("shutdown timeout = %v, want clamp to %v", cfg.ShutdownTimeout, MaxShutdownTimeout)
}
}
func TestSecretFileErrorsDoNotLeakThePath(t *testing.T) {
clearEnvironment(t)
t.Setenv("DATABASE_URL_FILE", "/nonexistent/path/database_url")
_, err := Load()
if err == nil {
t.Fatal("Load accepted a missing secret file")
}
if got := err.Error(); got != "DATABASE_URL_FILE: cannot read referenced file" {
t.Fatalf("error leaks path: %q", got)
}
}
+119
View File
@@ -0,0 +1,119 @@
// Package cursor implements the opaque keyset cursor of the contract. A cursor
// carries the last item already returned; the next page asks PostgreSQL for
// rows strictly after (created_at, id). Cursors are bound to the endpoint and,
// for message history, to the chat that issued them.
package cursor
import (
"bytes"
"encoding/base64"
"encoding/json"
"errors"
"io"
"time"
"mtusi.ru/messenger-lab7/internal/model"
"mtusi.ru/messenger-lab7/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-lab7/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)
}
}
}
+131
View File
@@ -0,0 +1,131 @@
// Package job defines the durable broker message described by
// contracts/jobs.schema.json. The payload is a pointer to PostgreSQL state: it
// carries identifiers and the managed attempt number only. It never carries
// image bytes, storage keys, signed URLs or credentials.
package job
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"time"
"mtusi.ru/messenger-lab7/internal/uuid"
)
const (
SchemaVersion = 1
Type = "attachment.process.v1"
MaxAttempts = 10
)
// Message is the exact JSON object of jobs.schema.json.
type Message struct {
SchemaVersion int `json:"schema_version"`
JobID string `json:"job_id"`
Type string `json:"type"`
AttachmentID string `json:"attachment_id"`
PipelineVersion int `json:"pipeline_version"`
Attempt int `json:"attempt"`
CreatedAt string `json:"created_at"`
// W3C trace context of the producer span. The schema makes both fields
// optional so a message produced by an older API remains valid.
TraceParent string `json:"traceparent,omitempty"`
TraceState string `json:"tracestate,omitempty"`
}
// New builds a validated message for an existing durable job.
func New(jobID, attachmentID string, pipelineVersion, attempt int, createdAt time.Time) Message {
return Message{
SchemaVersion: SchemaVersion,
JobID: jobID,
Type: Type,
AttachmentID: attachmentID,
PipelineVersion: pipelineVersion,
Attempt: attempt,
CreatedAt: createdAt.UTC().Format("2006-01-02T15:04:05.000000Z"),
}
}
// Marshal encodes the message without HTML escaping.
func (m Message) Marshal() ([]byte, error) {
return json.Marshal(m)
}
// Parse applies the contract schema strictly. Unknown fields are rejected, so
// a future producer cannot smuggle bytes or credentials through this carrier.
func Parse(payload []byte) (Message, error) {
decoder := json.NewDecoder(bytes.NewReader(payload))
decoder.DisallowUnknownFields()
var message Message
if err := decoder.Decode(&message); err != nil {
return Message{}, fmt.Errorf("job payload is not valid JSON: %w", err)
}
var trailing any
if err := decoder.Decode(&trailing); !errors.Is(err, io.EOF) {
return Message{}, errors.New("job payload has trailing JSON")
}
if err := message.Validate(); err != nil {
return Message{}, err
}
return message, nil
}
// Validate enforces every schema constraint that matters before the worker
// touches PostgreSQL or S3.
func (m Message) Validate() error {
if m.SchemaVersion != SchemaVersion {
return fmt.Errorf("unsupported schema_version %d", m.SchemaVersion)
}
if m.Type != Type {
return fmt.Errorf("unsupported job type %q", m.Type)
}
if _, ok := uuid.Normalize(m.JobID); !ok {
return errors.New("job_id is not a UUID")
}
if _, ok := uuid.Normalize(m.AttachmentID); !ok {
return errors.New("attachment_id is not a UUID")
}
if m.PipelineVersion < 1 || m.PipelineVersion > 100 {
return fmt.Errorf("pipeline_version %d is outside 1..100", m.PipelineVersion)
}
if m.Attempt < 1 || m.Attempt > MaxAttempts {
return fmt.Errorf("attempt %d is outside 1..%d", m.Attempt, MaxAttempts)
}
if _, err := time.Parse(time.RFC3339Nano, m.CreatedAt); err != nil {
return errors.New("created_at is not an RFC 3339 timestamp")
}
if m.TraceParent != "" && !validTraceParent(m.TraceParent) {
return errors.New("traceparent is not a W3C version-00 trace context")
}
if len(m.TraceState) > 512 {
return errors.New("tracestate is too long")
}
return nil
}
// WithTrace returns a copy carrying the W3C context of the span that produced
// the message. The job schema declares both fields; bytes and credentials are
// still impossible because the JSON decoder rejects unknown fields.
func (m Message) WithTrace(traceParent, traceState string) Message {
m.TraceParent = traceParent
m.TraceState = traceState
return m
}
func validTraceParent(value string) bool {
if len(value) != 55 || value[2] != '-' || value[35] != '-' || value[52] != '-' {
return false
}
for index, char := range value {
if index == 2 || index == 35 || index == 52 {
continue
}
if !((char >= '0' && char <= '9') || (char >= 'a' && char <= 'f')) {
return false
}
}
return value[:2] == "00"
}
+99
View File
@@ -0,0 +1,99 @@
// Package model holds the public JSON shapes of the lab3 contract. They are
// deliberately separate from the database scan helpers so an accidental new
// column cannot silently become an API field.
package model
import "time"
// Time marshals an RFC 3339 UTC timestamp with exactly six fractional digits.
// Go's default time.Time JSON encoder trims trailing zeros, which produces
// 3-5 digit fractions that some Python 3.9 datetime parsers (used by the
// public test client) reject. A fixed microsecond precision matches
// PostgreSQL timestamptz and stays valid RFC 3339.
type Time struct{ time.Time }
const timestampLayout = "2006-01-02T15:04:05.000000Z"
// MarshalJSON implements json.Marshaler.
func (t Time) MarshalJSON() ([]byte, error) {
return []byte(`"` + t.UTC().Format(timestampLayout) + `"`), nil
}
// User is the public user shape. It never contains a password hash or session
// data.
type User struct {
ID string `json:"id"`
Username string `json:"username"`
DisplayName string `json:"display_name"`
CreatedAt Time `json:"created_at"`
}
// Chat is the public chat shape. MemberIDs preserves the order supplied at
// creation; membership is immutable in the mandatory lab3 API.
type Chat struct {
ID string `json:"id"`
Title string `json:"title"`
MemberIDs []string `json:"member_ids"`
CreatedAt Time `json:"created_at"`
}
// Message is the public message shape. SenderID always comes from the server
// session, never from the request body. AttachmentIDs is always a JSON array,
// never null, and preserves the order supplied by the client.
type Message struct {
ID string `json:"id"`
ChatID string `json:"chat_id"`
SenderID string `json:"sender_id"`
Text string `json:"text"`
CreatedAt Time `json:"created_at"`
AttachmentIDs []string `json:"attachment_ids"`
}
// Variant is the public derivative shape. Lab4 never creates variants, so
// every Attachment carries an empty array; the schema is kept for lab6.
type Variant struct {
Name string `json:"name"`
ContentType string `json:"content_type"`
SizeBytes int64 `json:"size_bytes"`
Width int `json:"width"`
Height int `json:"height"`
SHA256 string `json:"sha256"`
}
// Attachment is the public metadata shape. Object keys, bucket names and
// storage credentials are deliberately absent: they are server-side details.
type Attachment struct {
ID string `json:"id"`
ChatID string `json:"chat_id"`
OwnerID string `json:"owner_id"`
Filename string `json:"filename"`
ContentType string `json:"content_type"`
SizeBytes int64 `json:"size_bytes"`
SHA256 string `json:"sha256"`
Status string `json:"status"`
Variants []Variant `json:"variants"`
ErrorCode *string `json:"error_code"`
CreatedAt Time `json:"created_at"`
UpdatedAt Time `json:"updated_at"`
}
// ChatPage is one keyset page of accessible chats.
type ChatPage struct {
Items []Chat `json:"items"`
NextCursor *string `json:"next_cursor"`
}
// MessagePage is one keyset page of a chat history.
type MessagePage struct {
Items []Message `json:"items"`
NextCursor *string `json:"next_cursor"`
}
// Session is the login response. Token is only ever written to the response
// body, never to logs or PostgreSQL.
type Session struct {
Token string `json:"token"`
TokenType string `json:"token_type"`
ExpiresAt Time `json:"expires_at"`
User User `json:"user"`
}
+50
View File
@@ -0,0 +1,50 @@
package model
import (
"encoding/json"
"strings"
"testing"
"time"
)
func TestTimeMarshalUsesFixedMicroseconds(t *testing.T) {
value := Time{Time: time.Date(2026, 11, 30, 12, 0, 0, 120000000, time.UTC)}
data, err := json.Marshal(value)
if err != nil {
t.Fatal(err)
}
got := string(data)
// .120000 would be trimmed to .12 by the default encoder; the public
// Python 3.9 client requires 3 or 6 fractional digits.
if got != `"2026-11-30T12:00:00.120000Z"` {
t.Fatalf("marshal = %s", got)
}
if !strings.HasSuffix(got, "Z\"") {
t.Fatal("timestamp does not end in Z")
}
}
func TestUserJSONHasOnlyPublicFields(t *testing.T) {
user := User{
ID: "11111111-2222-4333-8444-555555555555",
Username: "alice",
DisplayName: "Алиса",
CreatedAt: Time{Time: time.Date(2026, 9, 1, 12, 0, 0, 0, time.UTC)},
}
data, err := json.Marshal(user)
if err != nil {
t.Fatal(err)
}
var fields map[string]any
if err := json.Unmarshal(data, &fields); err != nil {
t.Fatal(err)
}
if len(fields) != 4 {
t.Fatalf("user JSON has unexpected fields: %v", fields)
}
for _, forbidden := range []string{"password", "password_hash", "token", "token_hash"} {
if _, present := fields[forbidden]; present {
t.Fatalf("user JSON leaks %q", forbidden)
}
}
}
+314
View File
@@ -0,0 +1,314 @@
// Package objectstore is the S3 adapter. PostgreSQL stores attachment
// metadata; this package stores and streams the original bytes. No handler
// talks to the S3 SDK directly, so error classification and timeouts are in one
// place.
package objectstore
import (
"context"
"errors"
"fmt"
"io"
"net"
"net/http"
"net/url"
"strings"
"time"
"github.com/minio/minio-go/v7"
"github.com/minio/minio-go/v7/pkg/credentials"
)
var (
// ErrNotFound means the object (or a prerequisite such as the bucket) does
// not exist. The HTTP layer maps it to 404 for an attachment read.
ErrNotFound = errors.New("object not found")
// ErrUnavailable means S3 could not answer. The HTTP layer maps it to 503
// and never to a fabricated success.
ErrUnavailable = errors.New("object store unavailable")
)
// Config is the validated S3 connection. Credentials are never logged.
type Config struct {
Endpoint string
Region string
Bucket string
AccessKey string
SecretKey string
Timeout time.Duration
}
// Store is a thin, timeout-aware wrapper around minio-go.
type Store struct {
client *minio.Client
bucket string
timeout time.Duration
}
// Open parses S3_ENDPOINT as a scheme://host:port URL and builds a client. The
// caller must have validated that every field is non-empty.
func Open(cfg Config) (*Store, error) {
parsed, err := url.Parse(strings.TrimSpace(cfg.Endpoint))
if err != nil || parsed.Host == "" {
return nil, errors.New("S3_ENDPOINT must be an http(s) URL with a host")
}
if parsed.Scheme != "http" && parsed.Scheme != "https" {
return nil, errors.New("S3_ENDPOINT scheme must be http or https")
}
if parsed.Path != "" && parsed.Path != "/" {
return nil, errors.New("S3_ENDPOINT must not contain a path")
}
if cfg.Timeout <= 0 {
cfg.Timeout = 30 * time.Second
}
transport := &http.Transport{
Proxy: nil,
DialContext: (&net.Dialer{Timeout: 3 * time.Second, KeepAlive: 30 * time.Second}).DialContext,
MaxIdleConns: 32,
MaxIdleConnsPerHost: 16,
IdleConnTimeout: 60 * time.Second,
TLSHandshakeTimeout: 5 * time.Second,
ResponseHeaderTimeout: 10 * time.Second,
ExpectContinueTimeout: time.Second,
}
client, err := minio.New(parsed.Host, &minio.Options{
Creds: credentials.NewStaticV4(cfg.AccessKey, cfg.SecretKey, ""),
Secure: parsed.Scheme == "https",
Region: cfg.Region,
BucketLookup: minio.BucketLookupPath,
Transport: transport,
// The HTTP request is synchronous user work. One bounded retry is
// enough; the default exponential retry series would hold an upload
// request open for many seconds when S3 is unreachable.
MaxRetries: 1,
})
if err != nil {
return nil, errors.New("could not create S3 client")
}
return &Store{client: client, bucket: cfg.Bucket, timeout: cfg.Timeout}, nil
}
// Bucket returns the configured bucket name, which is safe to export as a
// telemetry attribute (it is not a credential or object key).
func (s *Store) Bucket() string { return s.bucket }
func (s *Store) opCtx(ctx context.Context) (context.Context, context.CancelFunc) {
return context.WithTimeout(ctx, s.timeout)
}
// Put uploads exactly size bytes with the declared content type. The caller
// has already validated the image; this function does not buffer the body.
func (s *Store) Put(ctx context.Context, key string, body io.Reader, size int64, contentType string) error {
ctx, cancel := s.opCtx(ctx)
defer cancel()
_, err := s.client.PutObject(ctx, s.bucket, key, body, size, minio.PutObjectOptions{
ContentType: contentType,
PartSize: 16 << 20,
NumThreads: 1,
DisableMultipart: size <= 16<<20,
})
if err != nil {
return classify(err)
}
return nil
}
// Get opens the object stream. The caller closes it. A missing object is
// ErrNotFound; an unreachable store is ErrUnavailable.
//
// The operation context must stay alive while the body is read: cancelling it
// when Get returns would abort the HTTP response stream. Close releases both
// the SDK object and its timeout.
//
// Existence and size come from a separate StatObject. Calling Stat on the
// lazily opened Object would make minio-go attach an If-Match ETag to the
// subsequent GET; SeaweedFS 3.98 rejects that conditional read for large
// objects with 412 after the store has been restarted. A plain GET avoids the
// false precondition while the HEAD still lets the handler return 404 before
// it writes response headers.
func (s *Store) Get(ctx context.Context, key string) (io.ReadCloser, ObjectInfo, error) {
ctx, cancel := s.opCtx(ctx)
info, err := s.client.StatObject(ctx, s.bucket, key, minio.StatObjectOptions{})
if err != nil {
cancel()
return nil, ObjectInfo{}, classify(err)
}
object, err := s.client.GetObject(ctx, s.bucket, key, minio.GetObjectOptions{})
if err != nil {
cancel()
return nil, ObjectInfo{}, classify(err)
}
return &objectStream{ReadCloser: object, cancel: cancel}, ObjectInfo{
Key: key,
Size: info.Size,
ContentType: info.ContentType,
LastModified: info.LastModified,
}, nil
}
// objectStream ties the S3 read lifetime to Close. The standard S3 response
// is not reusable after Close, and the caller always defers Close.
type objectStream struct {
io.ReadCloser
cancel context.CancelFunc
}
func (s *objectStream) Close() error {
err := s.ReadCloser.Close()
s.cancel()
return err
}
// Health probes the configured bucket with a HEAD. A missing probe object is a
// successful answer: it proves connectivity and bucket-scoped credentials
// without leaving test data behind.
func (s *Store) Health(ctx context.Context) error {
ctx, cancel := s.opCtx(ctx)
defer cancel()
_, err := s.client.StatObject(ctx, s.bucket, "_health/probe", minio.StatObjectOptions{})
if err != nil {
if errors.Is(classify(err), ErrNotFound) {
return nil
}
return classify(err)
}
return nil
}
// Stat checks existence without downloading the bytes. It is used by the
// metadata endpoint so a missing object is not reported as a ready attachment.
func (s *Store) Stat(ctx context.Context, key string) (ObjectInfo, error) {
ctx, cancel := s.opCtx(ctx)
defer cancel()
info, err := s.client.StatObject(ctx, s.bucket, key, minio.StatObjectOptions{})
if err != nil {
return ObjectInfo{}, classify(err)
}
return ObjectInfo{
Key: key,
Size: info.Size,
ContentType: info.ContentType,
LastModified: info.LastModified,
}, nil
}
// Remove deletes one object. S3 delete is idempotent: a missing key is not an
// error, which makes a repeated reconciler run safe.
func (s *Store) Remove(ctx context.Context, key string) error {
ctx, cancel := s.opCtx(ctx)
defer cancel()
if err := s.client.RemoveObject(ctx, s.bucket, key, minio.RemoveObjectOptions{}); err != nil {
return classify(err)
}
return nil
}
// ObjectInfo is the subset of S3 metadata the reconciler needs.
type ObjectInfo struct {
Key string
Size int64
ContentType string
LastModified time.Time
}
// List returns every object under prefix. The reconciler uses it once per run;
// the HTTP path never lists the bucket.
func (s *Store) List(ctx context.Context, prefix string) ([]ObjectInfo, error) {
ctx, cancel := s.opCtx(ctx)
defer cancel()
result := make([]ObjectInfo, 0, 64)
for object := range s.client.ListObjects(ctx, s.bucket, minio.ListObjectsOptions{Prefix: prefix, Recursive: true}) {
if object.Err != nil {
return nil, classify(object.Err)
}
result = append(result, ObjectInfo{
Key: object.Key,
Size: object.Size,
ContentType: object.ContentType,
LastModified: object.LastModified,
})
}
return result, nil
}
// EnsureBucket creates the bucket if it is absent. It is safe to run
// concurrently and repeatedly: an already existing bucket is not an error.
// The caller uses administrative credentials; API credentials are not allowed
// to create buckets.
func (s *Store) EnsureBucket(ctx context.Context) (bool, error) {
ctx, cancel := s.opCtx(ctx)
defer cancel()
exists, err := s.client.BucketExists(ctx, s.bucket)
if err != nil {
return false, classify(err)
}
if exists {
return false, nil
}
if err := s.client.MakeBucket(ctx, s.bucket, minio.MakeBucketOptions{Region: s.region()}); err != nil {
response := minio.ToErrorResponse(err)
switch response.Code {
case "BucketAlreadyOwnedByYou", "BucketAlreadyExists":
return false, nil
}
return false, classify(err)
}
return true, nil
}
func (s *Store) region() string {
// minio-go keeps the region in an unexported field. Passing an empty
// region lets it discover us-east-1 for SeaweedFS; the explicit region is
// still set in the client options for signed requests.
return ""
}
// Probe writes, stats and removes a tiny object. It proves that the configured
// credentials can actually use the private bucket without leaving test data.
func (s *Store) Probe(ctx context.Context) error {
const key = "_bootstrap/probe"
ctx, cancel := s.opCtx(ctx)
defer cancel()
body := strings.NewReader("mtusi-lab6-bucket-probe")
if _, err := s.client.PutObject(ctx, s.bucket, key, body, int64(body.Len()), minio.PutObjectOptions{
ContentType: "text/plain",
PartSize: 5 << 20,
}); err != nil {
return classify(err)
}
if _, err := s.client.StatObject(ctx, s.bucket, key, minio.StatObjectOptions{}); err != nil {
return classify(err)
}
if err := s.client.RemoveObject(ctx, s.bucket, key, minio.RemoveObjectOptions{}); err != nil {
return classify(err)
}
return nil
}
// classify converts an S3/SDK error into the two dependency classes the HTTP
// layer understands. An access-denied or malformed-bucket error stays a plain
// error and becomes a generic 500: it is a server configuration defect, not a
// user error and not a transient outage.
func classify(err error) error {
if err == nil {
return nil
}
if errors.Is(err, context.DeadlineExceeded) || errors.Is(err, context.Canceled) {
return fmt.Errorf("%w: %w", ErrUnavailable, err)
}
var netErr net.Error
if errors.As(err, &netErr) {
return fmt.Errorf("%w: %w", ErrUnavailable, err)
}
response := minio.ToErrorResponse(err)
switch response.Code {
case "NoSuchKey", "NoSuchObject", "NotFound":
return ErrNotFound
case "NoSuchBucket", "SlowDown", "InternalError", "ServiceUnavailable", "XMinioServerNotInitialized":
return fmt.Errorf("%w: %s", ErrUnavailable, response.Code)
}
if response.StatusCode >= 500 {
return fmt.Errorf("%w: HTTP %d", ErrUnavailable, response.StatusCode)
}
return err
}
+145
View File
@@ -0,0 +1,145 @@
// Package outbox publishes committed job intentions to the durable broker.
//
// It is deliberately separate from the HTTP handler: the 202 response depends
// only on the staged original and the PostgreSQL COMMIT, not on broker
// availability. If the broker is down the outbox keeps the row pending and the
// publisher retries; a crash between COMMIT and XADD therefore loses nothing.
//
// Lab6: the stored W3C context resumes the upload trace in a producer span, and
// the producer's traceparent is injected into the job document consumed by the
// worker.
package outbox
import (
"context"
"errors"
"log/slog"
"sync/atomic"
"time"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/codes"
"go.opentelemetry.io/otel/trace"
"mtusi.ru/messenger-lab7/internal/broker"
"mtusi.ru/messenger-lab7/internal/job"
"mtusi.ru/messenger-lab7/internal/store"
"mtusi.ru/messenger-lab7/internal/telemetry"
)
// Publisher drains due outbox rows.
type Publisher struct {
store *store.Store
broker *broker.Broker
log *slog.Logger
tracer trace.Tracer
interval time.Duration
batch int
published atomic.Uint64
cancelled atomic.Uint64
failures atomic.Uint64
}
// New creates a publisher. interval and batch are bounded by config.Load.
func New(repository *store.Store, transport *broker.Broker, logger *slog.Logger, tracer trace.Tracer, interval time.Duration, batch int) *Publisher {
if interval <= 0 {
interval = 200 * time.Millisecond
}
if batch <= 0 {
batch = 10
}
return &Publisher{store: repository, broker: transport, log: logger, tracer: tracer, interval: interval, batch: batch}
}
// Run polls until the context is cancelled. A transient broker or database
// failure is logged and retried; it never crashes the API process.
func (p *Publisher) Run(ctx context.Context) {
timer := time.NewTimer(0)
defer timer.Stop()
for {
select {
case <-ctx.Done():
return
case <-timer.C:
}
published, cancelled, err := p.RunOnce(ctx)
if err != nil {
if ctx.Err() == nil {
p.failures.Add(1)
p.log.Log(ctx, slog.LevelWarn, "outbox publish attempt failed", "error", err)
}
}
if published > 0 || cancelled > 0 {
p.log.Log(ctx, slog.LevelInfo, "outbox batch published", "published", published, "cancelled", cancelled)
}
// When work was available, poll immediately for the next batch; this
// keeps burst latency low without busy-looping on an empty outbox.
delay := p.interval
if published > 0 || cancelled > 0 {
delay = 0
}
timer.Reset(delay)
}
}
// RunOnce publishes at most one batch. It is exported for tests and for the
// operator CLI, which can flush the outbox explicitly.
func (p *Publisher) RunOnce(ctx context.Context) (int, int, error) {
published, cancelled, err := p.store.PublishDueOutbox(ctx, p.batch, time.Now().UTC(), func(item store.OutboxItem) (string, error) {
// Resume the upload context stored in the outbox row. A missing context
// (operator replay, lease recovery) starts a new trace.
parent := telemetry.RemoteContext(ctx, item.TraceParent, item.TraceState)
spanCtx, span := p.tracer.Start(parent, "attachment.job publish",
trace.WithSpanKind(trace.SpanKindProducer),
trace.WithAttributes(
attribute.String("messaging.system", "valkey_streams"),
attribute.String("messaging.destination.name", p.broker.Stream()),
attribute.String("messaging.operation.name", "publish"),
attribute.String("job.type", job.Type),
attribute.Int("job.attempt", item.Attempt),
attribute.Int("job.pipeline_version", item.PipelineVersion),
),
)
defer span.End()
traceParent, traceState := telemetry.TraceContext(spanCtx)
message := job.New(item.JobID, item.AttachmentID, item.PipelineVersion, item.Attempt, item.JobCreatedAt).
WithTrace(traceParent, traceState)
payload, err := message.Marshal()
if err != nil {
span.RecordError(err)
span.SetStatus(codes.Error, "job message encoding failed")
return "", err
}
streamID, err := p.broker.Publish(spanCtx, payload)
if err != nil {
span.RecordError(err)
span.SetStatus(codes.Error, "broker publish failed")
return "", err
}
span.SetAttributes(attribute.String("messaging.message.id", streamID))
return streamID, nil
})
if err == nil {
if published > 0 {
p.published.Add(uint64(published))
}
if cancelled > 0 {
p.cancelled.Add(uint64(cancelled))
}
}
return published, cancelled, err
}
// Stats returns monotonic counters for the operator stats endpoint.
func (p *Publisher) Stats() map[string]uint64 {
return map[string]uint64{
"outbox_published_total": p.published.Load(),
"outbox_cancelled_total": p.cancelled.Load(),
"outbox_failures_total": p.failures.Load(),
}
}
// ErrNotConfigured is returned when the API was started without a broker.
var ErrNotConfigured = errors.New("outbox publisher is not configured")
+364
View File
@@ -0,0 +1,364 @@
// Package pipeline turns one accepted original image into the deterministic
// lab6 derivative set. It is deliberately independent of HTTP, PostgreSQL and
// S3: the worker can rerun it any number of times and receive byte-identical
// output for the same (input, pipeline_version).
package pipeline
import (
"bytes"
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"image"
"image/color"
"image/draw"
"image/jpeg"
_ "image/png"
xdraw "golang.org/x/image/draw"
_ "golang.org/x/image/webp"
"github.com/KarpelesLab/gowebp"
)
// Variant names are fixed by contracts/openapi.json. A new name would be an API
// change, so the worker never invents additional variants.
const (
NameThumbnail = "thumbnail"
NameCrop = "crop"
NameOptimized = "optimized"
ThumbnailSize = 256
CropSize = 128
OptimizedSize = 1280
// maxPixels mirrors the API boundary. The worker re-checks it because the
// database is not the only place where a corrupted row could originate.
maxPixels = 40_000_000
)
// Errors are classified by the worker: invalid images and unsupported versions
// are permanent, while a context timeout is transient.
var (
ErrInvalidImage = errors.New("invalid image")
ErrTooLarge = errors.New("image exceeds the pixel limit")
ErrUnsupportedVersion = errors.New("unsupported pipeline version")
)
// Variant is one encoded derivative. Bytes are the exact object contents the
// worker uploads; SHA256 is their lowercase hex digest.
type Variant struct {
Name string
ContentType string
Bytes []byte
Width int
Height int
SHA256 string
}
// Render applies EXIF orientation, flattens alpha onto white and encodes the
// three mandatory derivatives for the requested pipeline version.
//
// Version 1 and version 2 differ only in documented encoder parameters. Keeping
// versioned object keys in the worker means a late version-1 delivery cannot
// overwrite a version-2 result even though both are valid WebP/JPEG files.
func Render(ctx context.Context, src []byte, version int) ([]Variant, error) {
jpegQuality, webpQuality, webpMethod, err := parameters(version)
if err != nil {
return nil, err
}
config, format, err := image.DecodeConfig(bytes.NewReader(src))
if err != nil || (format != "png" && format != "jpeg") {
return nil, fmt.Errorf("%w: header is corrupt or unsupported", ErrInvalidImage)
}
if config.Width < 1 || config.Height < 1 {
return nil, fmt.Errorf("%w: non-positive dimensions", ErrInvalidImage)
}
if int64(config.Width)*int64(config.Height) > maxPixels {
return nil, ErrTooLarge
}
decoded, _, err := image.Decode(bytes.NewReader(src))
if err != nil {
return nil, fmt.Errorf("%w: decode failed", ErrInvalidImage)
}
orientation, _ := jpegEXIFOrientation(src)
oriented := &orientedImage{src: decoded, orientation: orientation}
bounds := oriented.Bounds()
width, height := bounds.Dx(), bounds.Dy()
if width < 1 || height < 1 {
return nil, fmt.Errorf("%w: empty image", ErrInvalidImage)
}
type spec struct {
name string
contentType string
width int
height int
source image.Rectangle
encode func(image.Image) ([]byte, error)
}
thumbW, thumbH := fitWithin(width, height, ThumbnailSize)
side := width
if height < side {
side = height
}
cx := (width - side) / 2
cy := (height - side) / 2
optimizedW, optimizedH := fitWithin(width, height, OptimizedSize)
variantSpecs := []spec{
{
name: NameThumbnail, contentType: "image/jpeg", width: thumbW, height: thumbH,
source: oriented.Bounds(),
encode: func(img image.Image) ([]byte, error) { return encodeJPEG(img, jpegQuality) },
},
{
name: NameCrop, contentType: "image/jpeg", width: CropSize, height: CropSize,
source: image.Rect(bounds.Min.X+cx, bounds.Min.Y+cy, bounds.Min.X+cx+side, bounds.Min.Y+cy+side),
encode: func(img image.Image) ([]byte, error) { return encodeJPEG(img, jpegQuality) },
},
{
name: NameOptimized, contentType: "image/webp", width: optimizedW, height: optimizedH,
source: oriented.Bounds(),
encode: func(img image.Image) ([]byte, error) { return encodeWebP(img, webpQuality, webpMethod) },
},
}
result := make([]Variant, 0, len(variantSpecs))
for _, spec := range variantSpecs {
if err := ctx.Err(); err != nil {
return nil, err
}
target := image.NewRGBA(image.Rect(0, 0, spec.width, spec.height))
// White background is part of the contract for alpha sources. Scaling
// with draw.Over onto a white canvas both resamples and composites, so
// the worker never allocates a full-size RGBA copy of a 40 MP image.
draw.Draw(target, target.Bounds(), image.NewUniform(color.White), image.Point{}, draw.Src)
xdraw.CatmullRom.Scale(target, target.Bounds(), oriented, spec.source, xdraw.Over, nil)
encoded, err := spec.encode(target)
if err != nil {
return nil, fmt.Errorf("%w: %s encoding failed: %v", ErrInvalidImage, spec.name, err)
}
if err := verifyEncoded(encoded, spec.width, spec.height); err != nil {
return nil, err
}
sum := sha256.Sum256(encoded)
result = append(result, Variant{
Name: spec.name,
ContentType: spec.contentType,
Bytes: encoded,
Width: spec.width,
Height: spec.height,
SHA256: hex.EncodeToString(sum[:]),
})
}
return result, nil
}
func parameters(version int) (jpegQuality, webpQuality, webpMethod int, err error) {
switch version {
case 1:
return 80, 72, 3, nil
case 2:
return 86, 82, 4, nil
default:
return 0, 0, 0, fmt.Errorf("%w: %d", ErrUnsupportedVersion, version)
}
}
// fitWithin returns the largest integer dimensions inside max×max with the
// source aspect ratio. It never upscales and rounds down with a 1 px floor,
// which is exactly the contract rule ("320×200 -> 256×160", "round down,
// minimum 1").
func fitWithin(width, height, max int) (int, int) {
if width <= max && height <= max {
return width, height
}
if width >= height {
scaled := int(int64(height) * int64(max) / int64(width))
if scaled < 1 {
scaled = 1
}
return max, scaled
}
scaled := int(int64(width) * int64(max) / int64(height))
if scaled < 1 {
scaled = 1
}
return scaled, max
}
func encodeJPEG(img image.Image, quality int) ([]byte, error) {
var buffer bytes.Buffer
if err := jpeg.Encode(&buffer, img, &jpeg.Options{Quality: quality}); err != nil {
return nil, err
}
return buffer.Bytes(), nil
}
func encodeWebP(img image.Image, quality, method int) ([]byte, error) {
var buffer bytes.Buffer
if err := gowebp.Encode(&buffer, img, &gowebp.Options{
Lossy: true,
Quality: float32(quality),
Method: method,
}); err != nil {
return nil, err
}
return buffer.Bytes(), nil
}
// verifyEncoded re-decodes the produced bytes and checks the exact dimensions.
// This is cheap for the small derivative targets and prevents a broken encoder
// or an accidental alpha-file from reaching S3.
func verifyEncoded(data []byte, wantWidth, wantHeight int) error {
config, format, err := image.DecodeConfig(bytes.NewReader(data))
if err != nil {
return fmt.Errorf("%w: encoded derivative is not decodable", ErrInvalidImage)
}
if format != "jpeg" && format != "webp" {
return fmt.Errorf("%w: encoded derivative has unexpected format %q", ErrInvalidImage, format)
}
if config.Width != wantWidth || config.Height != wantHeight {
return fmt.Errorf("%w: encoded derivative has %dx%d, want %dx%d", ErrInvalidImage, config.Width, config.Height, wantWidth, wantHeight)
}
return nil
}
// orientedImage applies the eight EXIF orientation mappings without copying the
// decoded source. Scaling reads through At, so only the small target buffers
// are allocated.
type orientedImage struct {
src image.Image
orientation int
}
func (o *orientedImage) ColorModel() color.Model { return o.src.ColorModel() }
func (o *orientedImage) Bounds() image.Rectangle {
b := o.src.Bounds()
w, h := b.Dx(), b.Dy()
if o.orientation >= 5 && o.orientation <= 8 {
return image.Rect(0, 0, h, w)
}
return image.Rect(0, 0, w, h)
}
func (o *orientedImage) At(x, y int) color.Color {
b := o.src.Bounds()
w, h := b.Dx(), b.Dy()
var sx, sy int
switch o.orientation {
case 2:
sx, sy = w-1-x, y
case 3:
sx, sy = w-1-x, h-1-y
case 4:
sx, sy = x, h-1-y
case 5:
sx, sy = y, x
case 6:
sx, sy = y, h-1-x
case 7:
sx, sy = w-1-y, h-1-x
case 8:
sx, sy = w-1-y, x
default:
sx, sy = x, y
}
return o.src.At(b.Min.X+sx, b.Min.Y+sy)
}
// jpegEXIFOrientation extracts tag 0x0112 from the first EXIF APP1 segment.
// Malformed EXIF is treated as orientation 1: it must never make an otherwise
// valid image unprocessable, and the raw bytes remain downloadable.
func jpegEXIFOrientation(data []byte) (int, bool) {
if len(data) < 4 || data[0] != 0xff || data[1] != 0xd8 {
return 1, false
}
offset := 2
for offset+4 <= len(data) {
if data[offset] != 0xff {
return 1, false
}
marker := data[offset+1]
offset += 2
if marker == 0xd9 || marker == 0xda {
return 1, false
}
if marker == 0x01 || (marker >= 0xd0 && marker <= 0xd7) {
continue
}
if offset+2 > len(data) {
return 1, false
}
length := int(data[offset])<<8 | int(data[offset+1])
if length < 2 || offset+length > len(data) {
return 1, false
}
segment := data[offset+2 : offset+length]
if marker == 0xe1 && len(segment) >= 6 && string(segment[:4]) == "Exif" && segment[4] == 0 && segment[5] == 0 {
if orientation, ok := tiffOrientation(segment[6:]); ok {
return orientation, true
}
return 1, false
}
offset += length
}
return 1, false
}
func tiffOrientation(tiff []byte) (int, bool) {
if len(tiff) < 8 {
return 1, false
}
little := false
switch {
case tiff[0] == 'I' && tiff[1] == 'I':
little = true
case tiff[0] == 'M' && tiff[1] == 'M':
default:
return 1, false
}
if tiffUint16(tiff[2:4], little) != 42 {
return 1, false
}
ifdOffset := int(tiffUint32(tiff[4:8], little))
if ifdOffset < 8 || ifdOffset+2 > len(tiff) {
return 1, false
}
count := int(tiffUint16(tiff[ifdOffset:ifdOffset+2], little))
entry := ifdOffset + 2
for i := 0; i < count; i++ {
if entry+12 > len(tiff) {
return 1, false
}
tag := tiffUint16(tiff[entry:entry+2], little)
if tag == 0x0112 {
value := int(tiffUint16(tiff[entry+8:entry+10], little))
if value >= 1 && value <= 8 {
return value, true
}
return 1, false
}
entry += 12
}
return 1, false
}
func tiffUint16(b []byte, little bool) uint16 {
if little {
return uint16(b[0]) | uint16(b[1])<<8
}
return uint16(b[1]) | uint16(b[0])<<8
}
func tiffUint32(b []byte, little bool) uint32 {
if little {
return uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24
}
return uint32(b[3]) | uint32(b[2])<<8 | uint32(b[1])<<16 | uint32(b[0])<<24
}
+194
View File
@@ -0,0 +1,194 @@
package pipeline
import (
"bytes"
"context"
"crypto/sha256"
"encoding/hex"
"image"
"image/color"
"image/jpeg"
"image/png"
"os"
"testing"
)
func samplePNG(t *testing.T) []byte {
t.Helper()
data, err := os.ReadFile("../../tests/fixtures/sample.png")
if err != nil {
t.Fatalf("read fixture: %v", err)
}
return data
}
func variantsByName(t *testing.T, src []byte, version int) map[string]Variant {
t.Helper()
result, err := Render(context.Background(), src, version)
if err != nil {
t.Fatalf("render version %d: %v", version, err)
}
if len(result) != 3 {
t.Fatalf("expected 3 variants, got %d", len(result))
}
byName := make(map[string]Variant, len(result))
for _, variant := range result {
byName[variant.Name] = variant
}
return byName
}
func TestRenderContractDimensions(t *testing.T) {
byName := variantsByName(t, samplePNG(t), 1)
thumbnail := byName[NameThumbnail]
if thumbnail.Width != 256 || thumbnail.Height != 160 {
t.Fatalf("thumbnail is %dx%d, want 256x160", thumbnail.Width, thumbnail.Height)
}
if thumbnail.ContentType != "image/jpeg" || len(thumbnail.Bytes) < 2 || thumbnail.Bytes[0] != 0xff || thumbnail.Bytes[1] != 0xd8 {
t.Fatalf("thumbnail is not JPEG")
}
crop := byName[NameCrop]
if crop.Width != 128 || crop.Height != 128 || crop.ContentType != "image/jpeg" {
t.Fatalf("crop = %dx%d %s", crop.Width, crop.Height, crop.ContentType)
}
optimized := byName[NameOptimized]
if optimized.Width != 320 || optimized.Height != 200 || optimized.ContentType != "image/webp" {
t.Fatalf("optimized = %dx%d %s", optimized.Width, optimized.Height, optimized.ContentType)
}
for name, variant := range byName {
sum := sha256.Sum256(variant.Bytes)
if variant.SHA256 != hex.EncodeToString(sum[:]) {
t.Fatalf("%s sha256 does not describe its bytes", name)
}
}
}
func TestRenderDeterministic(t *testing.T) {
src := samplePNG(t)
first, err := Render(context.Background(), src, 2)
if err != nil {
t.Fatal(err)
}
second, err := Render(context.Background(), src, 2)
if err != nil {
t.Fatal(err)
}
if len(first) != len(second) {
t.Fatal("variant count changed")
}
for i := range first {
if first[i].Name != second[i].Name || first[i].SHA256 != second[i].SHA256 {
t.Fatalf("%s is not deterministic: %s vs %s", first[i].Name, first[i].SHA256, second[i].SHA256)
}
}
}
func TestPipelineVersionsDiffer(t *testing.T) {
src := samplePNG(t)
v1 := variantsByName(t, src, 1)[NameOptimized]
v2 := variantsByName(t, src, 2)[NameOptimized]
if v1.SHA256 == v2.SHA256 {
t.Fatal("documented version 1 and 2 encoder settings produced identical WebP")
}
if _, err := Render(context.Background(), src, 3); err == nil {
t.Fatal("unsupported pipeline version was accepted")
}
}
func TestAlphaFlattenedOnWhite(t *testing.T) {
// Left half transparent, right half opaque red. The thumbnail must show
// white (not black or garbage) where the source is transparent.
src := image.NewRGBA(image.Rect(0, 0, 100, 80))
for y := 0; y < 80; y++ {
for x := 0; x < 100; x++ {
if x >= 50 {
src.Set(x, y, color.RGBA{R: 255, A: 255})
}
}
}
var encoded bytes.Buffer
if err := png.Encode(&encoded, src); err != nil {
t.Fatal(err)
}
byName := variantsByName(t, encoded.Bytes(), 1)
var decoded image.Image
var err error
decoded, err = jpeg.Decode(bytes.NewReader(byName[NameThumbnail].Bytes))
if err != nil {
t.Fatal(err)
}
if decoded.Bounds().Dx() != 100 || decoded.Bounds().Dy() != 80 {
t.Fatalf("small image was upscaled: %v", decoded.Bounds())
}
r, g, b, _ := decoded.At(5, 40).RGBA()
if r < 0xe000 || g < 0xe000 || b < 0xe000 {
t.Fatalf("transparent area is not white: %d %d %d", r>>8, g>>8, b>>8)
}
r, g, b, _ = decoded.At(90, 40).RGBA()
if r < 0xa000 || g > 0x4000 || b > 0x4000 {
t.Fatalf("opaque red area is wrong: %d %d %d", r>>8, g>>8, b>>8)
}
}
func TestSmallImageCropUpscalesCenteredSquare(t *testing.T) {
// 100x60: the centered 60x60 square is scaled up to 128x128.
src := image.NewRGBA(image.Rect(0, 0, 100, 60))
for y := 0; y < 60; y++ {
for x := 0; x < 100; x++ {
src.Set(x, y, color.RGBA{R: uint8(x * 2), G: 40, B: 200, A: 255})
}
}
var encoded bytes.Buffer
if err := png.Encode(&encoded, src); err != nil {
t.Fatal(err)
}
crop := variantsByName(t, encoded.Bytes(), 2)[NameCrop]
if crop.Width != 128 || crop.Height != 128 {
t.Fatalf("crop = %dx%d", crop.Width, crop.Height)
}
}
func TestEXIFOrientationApplied(t *testing.T) {
base := image.NewRGBA(image.Rect(0, 0, 320, 200))
for y := 0; y < 200; y++ {
for x := 0; x < 320; x++ {
base.Set(x, y, color.RGBA{R: uint8(x), G: uint8(y), B: 128, A: 255})
}
}
var encoded bytes.Buffer
if err := jpeg.Encode(&encoded, base, &jpeg.Options{Quality: 90}); err != nil {
t.Fatal(err)
}
oriented := injectOrientation(t, encoded.Bytes(), 6)
thumbnail := variantsByName(t, oriented, 1)[NameThumbnail]
// A 320x200 stored image tagged orientation 6 is displayed as 200x320, so
// the contract fit is 160x256, not 256x160.
if thumbnail.Width != 160 || thumbnail.Height != 256 {
t.Fatalf("oriented thumbnail is %dx%d, want 160x256", thumbnail.Width, thumbnail.Height)
}
}
func injectOrientation(t *testing.T, jpegBytes []byte, orientation int) []byte {
t.Helper()
if len(jpegBytes) < 2 || jpegBytes[0] != 0xff || jpegBytes[1] != 0xd8 {
t.Fatal("not a JPEG")
}
tiff := []byte{
'I', 'I', 0x2a, 0x00, 0x08, 0x00, 0x00, 0x00,
0x01, 0x00, // one IFD entry
0x12, 0x01, // tag 0x0112
0x03, 0x00, // SHORT
0x01, 0x00, 0x00, 0x00, // count 1
byte(orientation), 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, // next IFD
}
payload := append([]byte("Exif\x00\x00"), tiff...)
length := len(payload) + 2
app1 := []byte{0xff, 0xe1, byte(length >> 8), byte(length)}
app1 = append(app1, payload...)
result := make([]byte, 0, len(jpegBytes)+len(app1))
result = append(result, jpegBytes[:2]...)
result = append(result, app1...)
result = append(result, jpegBytes[2:]...)
return result
}
+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-lab7/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 }
File diff suppressed because it is too large Load Diff
+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
}
+77
View File
@@ -0,0 +1,77 @@
package store
import (
"strings"
"testing"
)
func TestLoadMigrations(t *testing.T) {
migrations, err := loadMigrations()
if err != nil {
t.Fatalf("loadMigrations: %v", err)
}
if len(migrations) != 7 {
t.Fatalf("loaded %d migrations, want 7", len(migrations))
}
for index, item := range migrations {
if item.version != index+1 {
t.Fatalf("migration order at %d = %d", index, item.version)
}
}
for _, item := range migrations {
if len(item.checksum) != 64 {
t.Fatalf("checksum for %d has length %d", item.version, len(item.checksum))
}
lower := strings.ToLower(item.sql)
if !strings.Contains(lower, "create ") && !strings.Contains(lower, "alter ") {
t.Fatalf("migration %d has no schema statements", item.version)
}
}
// The checksum must be stable across process runs: it is what detects an
// edited migration after it has been applied.
again, err := loadMigrations()
if err != nil {
t.Fatal(err)
}
for index := range migrations {
if migrations[index].checksum != again[index].checksum {
t.Fatal("migration checksums are not deterministic")
}
}
}
func TestMigrationsContainRequiredDomainObjects(t *testing.T) {
migrations, err := loadMigrations()
if err != nil {
t.Fatal(err)
}
all := ""
for _, item := range migrations {
all += item.sql
}
for _, required := range []string{
"CREATE TABLE users",
"CREATE TABLE chats",
"CREATE TABLE chat_members",
"CREATE TABLE messages",
"CREATE UNIQUE INDEX users_username_key",
"messages_sender_membership_fk",
"messages_chat_created_id_idx",
"CREATE TABLE message_idempotency",
"PRIMARY KEY (user_id, method, path, key)",
"CREATE TABLE attachments",
"CREATE TABLE message_attachments",
"attachments_object_key_unique",
"message_attachments_attachment_chat_fk",
"CREATE TABLE attachment_jobs",
"CREATE TABLE attachment_variants",
"CREATE TABLE outbox",
"CREATE TABLE job_audit",
"outbox_pending_job_attempt",
"attachment_jobs_attachment_version_unique",
} {
if !strings.Contains(all, required) {
t.Fatalf("migrations do not contain %q", required)
}
}
}
+54
View File
@@ -0,0 +1,54 @@
-- Lab2 schema. PostgreSQL is the source of truth for users, chats, chat
-- membership and messages. Sessions intentionally live in Valkey with a TTL.
CREATE TABLE users (
id uuid PRIMARY KEY,
username text NOT NULL,
display_name text NOT NULL,
password_hash text NOT NULL,
created_at timestamptz NOT NULL,
CONSTRAINT users_username_format
CHECK (username ~ '^[a-z0-9_]{3,32}$'),
CONSTRAINT users_display_name_length
CHECK (char_length(display_name) BETWEEN 1 AND 100),
CONSTRAINT users_password_hash_present
CHECK (length(password_hash) > 0)
);
-- Uniqueness is enforced by the database, not by a read-then-insert check, so
-- two concurrent registrations of the same username cannot both succeed.
CREATE UNIQUE INDEX users_username_key ON users (username);
CREATE TABLE chats (
id uuid PRIMARY KEY,
title text NOT NULL,
created_at timestamptz NOT NULL,
CONSTRAINT chats_title_length
CHECK (char_length(title) BETWEEN 1 AND 100)
);
CREATE TABLE chat_members (
chat_id uuid NOT NULL REFERENCES chats (id) ON DELETE CASCADE,
user_id uuid NOT NULL REFERENCES users (id),
position integer NOT NULL,
PRIMARY KEY (chat_id, user_id),
CONSTRAINT chat_members_position_nonnegative CHECK (position >= 0)
);
-- "Chats of the current user" walks chat_members by user_id.
CREATE INDEX chat_members_user_chat_idx ON chat_members (user_id, chat_id);
CREATE TABLE messages (
id uuid PRIMARY KEY,
chat_id uuid NOT NULL,
sender_id uuid NOT NULL,
text text NOT NULL,
created_at timestamptz NOT NULL,
CONSTRAINT messages_text_length
CHECK (char_length(text) BETWEEN 1 AND 4000),
CONSTRAINT messages_chat_fk
FOREIGN KEY (chat_id) REFERENCES chats (id) ON DELETE CASCADE,
-- The sender must be a member of the chat at the database level too, not
-- only in the HTTP handler.
CONSTRAINT messages_sender_membership_fk
FOREIGN KEY (chat_id, sender_id) REFERENCES chat_members (chat_id, user_id)
);
@@ -0,0 +1,15 @@
-- Indexes justified by the two keyset queries of the contract.
--
-- Message history:
-- WHERE chat_id = $1 AND (created_at, id) > ($2, $3)
-- ORDER BY created_at, id LIMIT $4
-- The three-column index lets PostgreSQL start at the cursor position inside
-- one chat instead of scanning the whole history for every page.
CREATE INDEX messages_chat_created_id_idx
ON messages (chat_id, created_at, id);
-- Chat list:
-- ORDER BY created_at, id LIMIT $1
-- after joining chat_members for the current user.
CREATE INDEX chats_created_id_idx
ON chats (created_at, id);
@@ -0,0 +1,28 @@
-- Lab3: shared idempotency records for POST /api/v1/chats/{chat_id}/messages.
--
-- The primary key is exactly the contract scope: acting user + HTTP method +
-- chat message path + Idempotency-Key. Different users or chats may reuse the
-- same key independently. request_hash lets a replay distinguish the same
-- semantic body (201 + original message) from a different body (409).
--
-- A row is written in the same transaction as the message it references, so a
-- committed row always has a committed message and an aborted request leaves
-- neither. created_at supports the 24-hour retention prune; contract requires
-- at least 24 h, this stand prunes only records older than that bound.
CREATE TABLE message_idempotency (
user_id uuid NOT NULL REFERENCES users (id) ON DELETE CASCADE,
method text NOT NULL,
path text NOT NULL,
key text NOT NULL,
request_hash bytea NOT NULL,
message_id uuid NOT NULL REFERENCES messages (id) ON DELETE CASCADE,
created_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (user_id, method, path, key),
CONSTRAINT message_idempotency_method_post CHECK (method = 'POST'),
CONSTRAINT message_idempotency_key_length CHECK (char_length(key) BETWEEN 1 AND 128),
CONSTRAINT message_idempotency_path_length CHECK (char_length(path) BETWEEN 1 AND 256)
);
-- Retention housekeeping walks old rows; new inserts stay cheap.
CREATE INDEX message_idempotency_created_at_idx
ON message_idempotency (created_at);
@@ -0,0 +1,75 @@
-- Lab4: attachment metadata lives in PostgreSQL; the original bytes live in
-- the private S3 bucket. The only public state in the mandatory lab4 contract
-- is ready. pending exists solely as an internal, server-side upload intent:
-- it is written before the S3 PUT and promoted in the same request after the
-- PUT. A crash or a database failure between the two steps therefore leaves an
-- accounted row, never an anonymous object. The reconciler removes stale
-- pending rows and their objects after a documented grace period.
CREATE TABLE attachments (
id uuid PRIMARY KEY,
chat_id uuid NOT NULL REFERENCES chats (id) ON DELETE CASCADE,
owner_id uuid NOT NULL REFERENCES users (id),
filename text NOT NULL,
content_type text NOT NULL,
size_bytes bigint NOT NULL,
sha256 text NOT NULL,
status text NOT NULL,
error_code text,
object_key text NOT NULL,
created_at timestamptz NOT NULL,
updated_at timestamptz NOT NULL,
CONSTRAINT attachments_filename_length
CHECK (char_length(filename) BETWEEN 1 AND 255),
CONSTRAINT attachments_content_type
CHECK (content_type IN ('image/png', 'image/jpeg')),
CONSTRAINT attachments_size
CHECK (size_bytes BETWEEN 1 AND 10485760),
CONSTRAINT attachments_sha256
CHECK (sha256 ~ '^[a-f0-9]{64}$'),
CONSTRAINT attachments_status
CHECK (status IN ('pending', 'ready')),
CONSTRAINT attachments_ready_error
CHECK ((status = 'ready' AND error_code IS NULL) OR status = 'pending'),
CONSTRAINT attachments_object_key
CHECK (object_key LIKE 'attachments/%'),
CONSTRAINT attachments_object_key_unique UNIQUE (object_key),
-- Referenced by the composite foreign key of message_attachments so the
-- database itself rejects a link to an attachment of another chat.
CONSTRAINT attachments_id_chat_unique UNIQUE (id, chat_id)
);
-- The only attachment query on the hot path is "attachment of this chat".
CREATE INDEX attachments_chat_created_idx
ON attachments (chat_id, created_at, id);
-- The reconciler scans all rows by state and age. It never runs on the HTTP
-- hot path.
CREATE INDEX attachments_status_updated_idx
ON attachments (status, updated_at);
-- messages.id is already the primary key; this unique constraint is the
-- target required by the composite foreign keys below, not a second identity.
-- It must exist before the foreign key that references (id, chat_id).
ALTER TABLE messages
ADD CONSTRAINT messages_id_chat_unique UNIQUE (id, chat_id);
-- A message and its attachment links share one transaction. The composite
-- foreign keys make "file of another chat" impossible at the database level
-- even if a future handler forgets the application check.
CREATE TABLE message_attachments (
message_id uuid NOT NULL,
attachment_id uuid NOT NULL,
chat_id uuid NOT NULL,
position integer NOT NULL,
PRIMARY KEY (message_id, attachment_id),
CONSTRAINT message_attachments_position_unique UNIQUE (message_id, position),
CONSTRAINT message_attachments_position_nonnegative CHECK (position >= 0),
CONSTRAINT message_attachments_message_chat_fk
FOREIGN KEY (message_id, chat_id) REFERENCES messages (id, chat_id) ON DELETE CASCADE,
CONSTRAINT message_attachments_attachment_chat_fk
FOREIGN KEY (attachment_id, chat_id) REFERENCES attachments (id, chat_id)
);
-- Reconciler lookup: "is this object key still referenced by any row?".
CREATE INDEX message_attachments_attachment_idx
ON message_attachments (attachment_id);
@@ -0,0 +1,10 @@
-- Lab4 contract: a message may carry text = "" when it references at least one
-- attachment of the chat (contracts/README.md, "Вложения"). The HTTP handler
-- still rejects empty or blank text without attachments; the database
-- constraint only widens to permit the documented attachment-only message.
ALTER TABLE messages
DROP CONSTRAINT messages_text_length;
ALTER TABLE messages
ADD CONSTRAINT messages_text_length
CHECK (char_length(text) BETWEEN 0 AND 4000);
@@ -0,0 +1,165 @@
-- Lab5: asynchronous attachment processing.
--
-- The attachment row becomes the durable intention: the original is already in
-- the private staging prefix, and one PostgreSQL transaction stores the public
-- metadata, the logical job and the outbox row that will publish it. A broker
-- message is a pointer to this job; image bytes and credentials never enter it.
--
-- The effect key is (attachment_id, pipeline_version, variant). Object keys also
-- include the version, so a late old-version delivery cannot overwrite a newer
-- result. attachments.ready_version is monotonic and selects the variant set the
-- public API exposes.
ALTER TABLE attachments
ADD COLUMN staging_key text,
ADD COLUMN pipeline_version integer NOT NULL DEFAULT 1,
ADD COLUMN ready_version integer;
UPDATE attachments
SET status = 'queued'
WHERE status = 'pending';
UPDATE attachments
SET staging_key = 'staging/' || id::text
WHERE staging_key IS NULL;
ALTER TABLE attachments
ALTER COLUMN staging_key SET NOT NULL;
ALTER TABLE attachments
DROP CONSTRAINT attachments_status,
DROP CONSTRAINT attachments_ready_error,
ADD CONSTRAINT attachments_status
CHECK (status IN ('queued', 'processing', 'ready', 'failed')),
ADD CONSTRAINT attachments_ready_error
CHECK (
(status = 'ready' AND error_code IS NULL AND ready_version IS NOT NULL)
OR (status = 'failed' AND error_code IS NOT NULL)
OR (status IN ('queued', 'processing') AND error_code IS NULL)
),
ADD CONSTRAINT attachments_pipeline_version
CHECK (pipeline_version BETWEEN 1 AND 100),
ADD CONSTRAINT attachments_ready_version
CHECK (ready_version IS NULL OR (ready_version BETWEEN 1 AND pipeline_version)),
ADD CONSTRAINT attachments_staging_key
CHECK (staging_key LIKE 'staging/%'),
ADD CONSTRAINT attachments_staging_key_unique UNIQUE (staging_key);
-- One logical job per attachment and pipeline version. job_id is stable across
-- broker redelivery; attempts counts managed worker attempts, not deliveries.
CREATE TABLE attachment_jobs (
id uuid PRIMARY KEY,
attachment_id uuid NOT NULL REFERENCES attachments (id) ON DELETE CASCADE,
type text NOT NULL,
pipeline_version integer NOT NULL,
status text NOT NULL,
attempts integer NOT NULL DEFAULT 0,
max_attempts integer NOT NULL,
available_at timestamptz NOT NULL,
lease_owner text,
lease_expires_at timestamptz,
error_code text,
replay_count integer NOT NULL DEFAULT 0,
created_at timestamptz NOT NULL,
updated_at timestamptz NOT NULL,
completed_at timestamptz,
CONSTRAINT attachment_jobs_type
CHECK (type = 'attachment.process.v1'),
CONSTRAINT attachment_jobs_version
CHECK (pipeline_version BETWEEN 1 AND 100),
CONSTRAINT attachment_jobs_status
CHECK (status IN ('queued', 'processing', 'ready', 'failed')),
CONSTRAINT attachment_jobs_attempts
CHECK (attempts BETWEEN 0 AND max_attempts AND max_attempts BETWEEN 1 AND 10),
CONSTRAINT attachment_jobs_error
CHECK (
(status = 'ready' AND error_code IS NULL AND completed_at IS NOT NULL)
OR (status = 'failed' AND error_code IS NOT NULL AND completed_at IS NOT NULL)
OR (status IN ('queued', 'processing') AND error_code IS NULL)
),
CONSTRAINT attachment_jobs_lease
CHECK (
(status = 'processing' AND lease_owner IS NOT NULL AND lease_expires_at IS NOT NULL)
OR status <> 'processing'
),
CONSTRAINT attachment_jobs_attachment_version_unique
UNIQUE (attachment_id, pipeline_version)
);
CREATE INDEX attachment_jobs_recovery_idx
ON attachment_jobs (status, available_at, id);
CREATE INDEX attachment_jobs_lease_idx
ON attachment_jobs (status, lease_expires_at)
WHERE status = 'processing';
-- Variants are effects keyed by (attachment, version, name). The primary key
-- makes a redelivered job update the same three rows instead of adding more.
CREATE TABLE attachment_variants (
attachment_id uuid NOT NULL,
pipeline_version integer NOT NULL,
name text NOT NULL,
content_type text NOT NULL,
size_bytes bigint NOT NULL,
width integer NOT NULL,
height integer NOT NULL,
sha256 text NOT NULL,
object_key text NOT NULL,
created_at timestamptz NOT NULL,
PRIMARY KEY (attachment_id, pipeline_version, name),
CONSTRAINT attachment_variants_job_fk
FOREIGN KEY (attachment_id, pipeline_version)
REFERENCES attachment_jobs (attachment_id, pipeline_version) ON DELETE CASCADE,
CONSTRAINT attachment_variants_name
CHECK (name IN ('thumbnail', 'crop', 'optimized')),
CONSTRAINT attachment_variants_content_type
CHECK (content_type IN ('image/jpeg', 'image/webp')),
CONSTRAINT attachment_variants_size CHECK (size_bytes > 0),
CONSTRAINT attachment_variants_dimensions CHECK (width > 0 AND height > 0),
CONSTRAINT attachment_variants_sha CHECK (sha256 ~ '^[a-f0-9]{64}$'),
CONSTRAINT attachment_variants_name_type
CHECK ((name IN ('thumbnail', 'crop') AND content_type = 'image/jpeg')
OR (name = 'optimized' AND content_type = 'image/webp')),
CONSTRAINT attachment_variants_object_key CHECK (object_key LIKE 'attachments/%'),
CONSTRAINT attachment_variants_object_key_unique UNIQUE (object_key)
);
-- Transactional outbox. The upload transaction and every retry transaction
-- insert a row here in the same COMMIT as the state change, so there is no
-- window in which a committed job exists but no durable publish intention does.
-- A publisher marks published_at only after XADD returned (publisher confirm).
CREATE TABLE outbox (
id bigserial PRIMARY KEY,
job_id uuid NOT NULL REFERENCES attachment_jobs (id) ON DELETE CASCADE,
attempt integer NOT NULL,
available_at timestamptz NOT NULL,
published_at timestamptz,
cancelled_at timestamptz,
stream_id text,
created_at timestamptz NOT NULL,
CONSTRAINT outbox_attempt CHECK (attempt BETWEEN 1 AND 10),
CONSTRAINT outbox_state CHECK (NOT (published_at IS NOT NULL AND cancelled_at IS NOT NULL))
);
-- At most one not-yet-published intention per job attempt. After a publish
-- confirmation (or cancellation) a later recovery may insert another row for
-- the same attempt; this is the intended at-least-once retry boundary.
CREATE UNIQUE INDEX outbox_pending_job_attempt
ON outbox (job_id, attempt)
WHERE published_at IS NULL AND cancelled_at IS NULL;
CREATE INDEX outbox_due_idx
ON outbox (available_at, id)
WHERE published_at IS NULL AND cancelled_at IS NULL;
-- Explicit operator actions are audited separately from the job state.
CREATE TABLE job_audit (
id bigserial PRIMARY KEY,
job_id uuid NOT NULL REFERENCES attachment_jobs (id) ON DELETE CASCADE,
event text NOT NULL,
actor text NOT NULL,
detail text,
created_at timestamptz NOT NULL
);
CREATE INDEX job_audit_job_idx ON job_audit (job_id, id);
@@ -0,0 +1,23 @@
-- Lab6: W3C trace context for the asynchronous job chain.
--
-- The outbox row is the durable carrier of the producer context between the
-- upload transaction and the outbox publisher. The publisher starts a producer
-- span as a child of this context and injects its own traceparent into the
-- broker job document (contracts/jobs.schema.json already declares the
-- optional traceparent/tracestate fields). The worker then starts its consumer
-- span as a child of the producer span.
--
-- A retry inserts a new outbox row with the context of the failing consumer
-- span, so the retry is linked to the attempt that scheduled it. Rows created
-- by operator replay or lease recovery have NULL and start a new trace; that is
-- honest because no request span exists for them.
ALTER TABLE outbox
ADD COLUMN traceparent text,
ADD COLUMN tracestate text;
ALTER TABLE outbox
ADD CONSTRAINT outbox_traceparent
CHECK (traceparent IS NULL OR traceparent ~ '^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$'),
ADD CONSTRAINT outbox_tracestate
CHECK (tracestate IS NULL OR length(tracestate) <= 512);
+712
View File
@@ -0,0 +1,712 @@
// 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-lab7/internal/cursor"
"mtusi.ru/messenger-lab7/internal/model"
"mtusi.ru/messenger-lab7/internal/uuid"
)
// Domain errors. The HTTP layer maps them to the contract's status codes.
var (
ErrNotFound = errors.New("object not found")
ErrUsernameTaken = errors.New("username already taken")
ErrUnknownMember = errors.New("unknown chat member")
ErrUnavailable = errors.New("database unavailable")
ErrIdempotencyConflict = errors.New("idempotency key reused with a different request body")
ErrAttachmentNotReady = errors.New("attachment is not ready")
)
// Options bounds the pool and every query. Zero values fall back to safe
// defaults so the store is still testable from small programs.
type Options struct {
MaxConns int32
MinConns int32
ConnectTimeout time.Duration
StatementTimeout time.Duration
QueryTimeout time.Duration
// QueryTracer creates client spans for SQL statements. It is nil in tools
// that do not need tracing.
QueryTracer pgx.QueryTracer
}
// 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-lab7"
// 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)
if options.QueryTracer != nil {
config.ConnConfig.Tracer = options.QueryTracer
}
pool, err := pgxpool.NewWithConfig(ctx, config)
if err != nil {
return nil, fmt.Errorf("create PostgreSQL pool: %w", err)
}
return &Store{pool: pool, queryTimeout: options.QueryTimeout}, nil
}
func applyDefaults(options *Options) {
if options.MaxConns <= 0 {
options.MaxConns = 8
}
if options.MinConns < 0 {
options.MinConns = 0
}
if options.MinConns > options.MaxConns {
options.MinConns = options.MaxConns
}
if options.ConnectTimeout <= 0 {
options.ConnectTimeout = 3 * time.Second
}
if options.StatementTimeout <= 0 {
options.StatementTimeout = 3 * time.Second
}
if options.QueryTimeout <= 0 {
options.QueryTimeout = 3 * time.Second
}
}
// Ping is used by /health/ready and by the startup readiness loop.
func (s *Store) Ping(ctx context.Context) error {
return s.pool.Ping(ctx)
}
// Close waits for in-flight queries and closes the pool.
func (s *Store) Close() { s.pool.Close() }
func (s *Store) opCtx(ctx context.Context) (context.Context, context.CancelFunc) {
if s.queryTimeout <= 0 {
return ctx, func() {}
}
return context.WithTimeout(ctx, s.queryTimeout)
}
// classify separates a dependency outage (contract 503 unavailable) from a
// genuine application bug (500 internal_error). Only the error class is mapped;
// the original error is logged server-side and never sent to a client.
func (s *Store) classify(err error) error {
if err == nil {
return nil
}
if errors.Is(err, pgx.ErrNoRows) {
return ErrNotFound
}
if errors.Is(err, context.DeadlineExceeded) || errors.Is(err, context.Canceled) {
return fmt.Errorf("%w: %w", ErrUnavailable, err)
}
var pgErr *pgconn.PgError
if errors.As(err, &pgErr) {
switch {
case strings.HasPrefix(pgErr.Code, "08"), // connection exception
pgErr.Code == "57P01", // admin shutdown
pgErr.Code == "57P02", // crash shutdown
pgErr.Code == "57P03", // cannot connect now
pgErr.Code == "57014", // query cancelled (statement_timeout)
strings.HasPrefix(pgErr.Code, "53"): // insufficient resources
return fmt.Errorf("%w: %w", ErrUnavailable, err)
}
return err
}
if errors.Is(err, puddle.ErrClosedPool) || errors.Is(err, io.EOF) || errors.Is(err, io.ErrUnexpectedEOF) {
return fmt.Errorf("%w: %w", ErrUnavailable, err)
}
var netErr net.Error
if errors.As(err, &netErr) {
return fmt.Errorf("%w: %w", ErrUnavailable, err)
}
return err
}
func isUniqueViolation(err error) bool {
var pgErr *pgconn.PgError
return errors.As(err, &pgErr) && pgErr.Code == "23505" && pgErr.ConstraintName == "users_username_key"
}
func isForeignKeyViolation(err error) bool {
var pgErr *pgconn.PgError
return errors.As(err, &pgErr) && pgErr.Code == "23503"
}
func isIdempotencyViolation(err error) bool {
var pgErr *pgconn.PgError
return errors.As(err, &pgErr) && pgErr.Code == "23505" &&
pgErr.ConstraintName == "message_idempotency_pkey"
}
// CreateUser inserts a user and relies on the unique index for both ordinary
// duplicates and concurrent registrations of the same username.
func (s *Store) CreateUser(ctx context.Context, username, displayName, passwordHash string) (model.User, error) {
ctx, cancel := s.opCtx(ctx)
defer cancel()
id := uuid.New()
createdAt := time.Now().UTC()
var stored time.Time
err := s.pool.QueryRow(ctx, `
INSERT INTO users (id, username, display_name, password_hash, created_at)
VALUES ($1::uuid, $2, $3, $4, $5)
RETURNING created_at`,
id, username, displayName, passwordHash, createdAt,
).Scan(&stored)
if err != nil {
if isUniqueViolation(err) {
return model.User{}, ErrUsernameTaken
}
return model.User{}, s.classify(err)
}
return model.User{
ID: id,
Username: username,
DisplayName: displayName,
CreatedAt: model.Time{Time: stored.UTC()},
}, nil
}
// UserByUsername returns the public user and the Argon2id hash. The hash is
// used only by the login handler and is never serialised.
func (s *Store) UserByUsername(ctx context.Context, username string) (model.User, string, error) {
ctx, cancel := s.opCtx(ctx)
defer cancel()
var user model.User
var passwordHash string
var createdAt time.Time
err := s.pool.QueryRow(ctx, `
SELECT id::text, username, display_name, password_hash, created_at
FROM users WHERE username = $1`, username,
).Scan(&user.ID, &user.Username, &user.DisplayName, &passwordHash, &createdAt)
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return model.User{}, "", ErrNotFound
}
return model.User{}, "", s.classify(err)
}
user.CreatedAt = model.Time{Time: createdAt.UTC()}
return user, passwordHash, nil
}
// UserByID resolves the identity stored in a server-side session.
func (s *Store) UserByID(ctx context.Context, id string) (model.User, error) {
ctx, cancel := s.opCtx(ctx)
defer cancel()
var user model.User
var createdAt time.Time
err := s.pool.QueryRow(ctx, `
SELECT id::text, username, display_name, created_at
FROM users WHERE id = $1::uuid`, id,
).Scan(&user.ID, &user.Username, &user.DisplayName, &createdAt)
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return model.User{}, ErrNotFound
}
return model.User{}, s.classify(err)
}
user.CreatedAt = model.Time{Time: createdAt.UTC()}
return user, nil
}
// CreateChat inserts the chat and its membership in one transaction. A caller
// cannot observe a chat without members: either both are committed or neither.
func (s *Store) CreateChat(ctx context.Context, title string, memberIDs []string, callerID string) (model.Chat, error) {
ctx, cancel := s.opCtx(ctx)
defer cancel()
tx, err := s.pool.Begin(ctx)
if err != nil {
return model.Chat{}, s.classify(err)
}
defer func() { _ = tx.Rollback(context.Background()) }()
var existing int
if err := tx.QueryRow(ctx, `
SELECT count(*) FROM users
WHERE id IN (SELECT value::uuid FROM unnest($1::text[]) AS value)`, memberIDs,
).Scan(&existing); err != nil {
return model.Chat{}, s.classify(err)
}
if existing != len(memberIDs) {
return model.Chat{}, ErrUnknownMember
}
id := uuid.New()
createdAt := time.Now().UTC()
var stored time.Time
if err := tx.QueryRow(ctx, `
INSERT INTO chats (id, title, created_at) VALUES ($1::uuid, $2, $3)
RETURNING created_at`, id, title, createdAt,
).Scan(&stored); err != nil {
return model.Chat{}, s.classify(err)
}
batch := &pgx.Batch{}
for position, memberID := range memberIDs {
batch.Queue(`INSERT INTO chat_members (chat_id, user_id, position) VALUES ($1::uuid, $2::uuid, $3)`,
id, memberID, position)
}
results := tx.SendBatch(ctx, batch)
for range memberIDs {
if _, err := results.Exec(); err != nil {
_ = results.Close()
if isForeignKeyViolation(err) {
return model.Chat{}, ErrUnknownMember
}
return model.Chat{}, s.classify(err)
}
}
if err := results.Close(); err != nil {
return model.Chat{}, s.classify(err)
}
if err := tx.Commit(ctx); err != nil {
return model.Chat{}, s.classify(err)
}
return model.Chat{
ID: id,
Title: title,
MemberIDs: append([]string(nil), memberIDs...),
CreatedAt: model.Time{Time: stored.UTC()},
}, nil
}
// IsChatMember is used before parsing query parameters so a foreign chat is
// always 404, independent of the submitted cursor or limit.
func (s *Store) IsChatMember(ctx context.Context, chatID, userID string) (bool, error) {
ctx, cancel := s.opCtx(ctx)
defer cancel()
var member bool
err := s.pool.QueryRow(ctx, `
SELECT EXISTS (
SELECT 1 FROM chat_members WHERE chat_id = $1::uuid AND user_id = $2::uuid
)`, chatID, userID).Scan(&member)
if err != nil {
return false, s.classify(err)
}
return member, nil
}
// ChatForUser returns a chat only when the user is a member. A missing chat and
// a foreign chat are indistinguishable to the caller.
func (s *Store) ChatForUser(ctx context.Context, chatID, userID string) (model.Chat, error) {
ctx, cancel := s.opCtx(ctx)
defer cancel()
var chat model.Chat
var createdAt time.Time
err := s.pool.QueryRow(ctx, `
SELECT c.id::text, c.title, c.created_at,
array_agg(cm.user_id::text ORDER BY cm.position)
FROM chats c
JOIN chat_members me ON me.chat_id = c.id AND me.user_id = $2::uuid
JOIN chat_members cm ON cm.chat_id = c.id
WHERE c.id = $1::uuid
GROUP BY c.id`, chatID, userID,
).Scan(&chat.ID, &chat.Title, &createdAt, &chat.MemberIDs)
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return model.Chat{}, ErrNotFound
}
return model.Chat{}, s.classify(err)
}
chat.CreatedAt = model.Time{Time: createdAt.UTC()}
return chat, nil
}
const chatsPageSelect = `
SELECT c.id::text, c.title, c.created_at,
array_agg(cm.user_id::text ORDER BY cm.position)
FROM chats c
JOIN chat_members me ON me.chat_id = c.id AND me.user_id = $1::uuid
JOIN chat_members cm ON cm.chat_id = c.id`
// Chats returns one keyset page of chats visible to the user.
func (s *Store) Chats(ctx context.Context, userID string, position *cursor.Cursor, limit int) (model.ChatPage, error) {
ctx, cancel := s.opCtx(ctx)
defer cancel()
query := chatsPageSelect + `
GROUP BY c.id
ORDER BY c.created_at, c.id
LIMIT $2`
args := []any{userID, limit + 1}
if position != nil {
query = chatsPageSelect + `
WHERE (c.created_at, c.id) > ($2::timestamptz, $3::uuid)
GROUP BY c.id
ORDER BY c.created_at, c.id
LIMIT $4`
args = []any{userID, position.At, position.ID, limit + 1}
}
rows, err := s.pool.Query(ctx, query, args...)
if err != nil {
return model.ChatPage{}, s.classify(err)
}
defer rows.Close()
items := make([]model.Chat, 0, limit)
for rows.Next() {
var chat model.Chat
var createdAt time.Time
if err := rows.Scan(&chat.ID, &chat.Title, &createdAt, &chat.MemberIDs); err != nil {
return model.ChatPage{}, s.classify(err)
}
chat.CreatedAt = model.Time{Time: createdAt.UTC()}
items = append(items, chat)
}
if err := rows.Err(); err != nil {
return model.ChatPage{}, s.classify(err)
}
page := model.ChatPage{Items: items}
if len(items) > limit {
page.Items = items[:limit]
next := cursor.ForChat(page.Items[len(page.Items)-1])
page.NextCursor = &next
}
return page, nil
}
// PoolStats is a point-in-time snapshot of the bounded pgx pool. It is used
// only by the operator-only metrics listener, never by the public API.
type PoolStats struct {
MaxConns int32 `json:"max_conns"`
TotalConns int32 `json:"total_conns"`
AcquiredConns int32 `json:"acquired_conns"`
IdleConns int32 `json:"idle_conns"`
EmptyAcquireCount int64 `json:"empty_acquire_count"`
CanceledAcquireCount int64 `json:"canceled_acquire_count"`
AcquireCount int64 `json:"acquire_count"`
AcquireDurationMillis int64 `json:"acquire_duration_ms_total"`
NewConnsCount int64 `json:"new_conns_count"`
MaxLifetimeDestroyCount int64 `json:"max_lifetime_destroy_count"`
MaxIdleDestroyCount int64 `json:"max_idle_destroy_count"`
}
// PoolStats reports saturation signals for the connection pool. EmptyAcquire
// Count is the number of calls that had to wait for a free connection; a fast
// rising value while the API CPU is below its limit points at the database or
// the pool size, not at the HTTP layer.
func (s *Store) PoolStats() PoolStats {
stat := s.pool.Stat()
return PoolStats{
MaxConns: stat.MaxConns(),
TotalConns: stat.TotalConns(),
AcquiredConns: stat.AcquiredConns(),
IdleConns: stat.IdleConns(),
EmptyAcquireCount: stat.EmptyAcquireCount(),
CanceledAcquireCount: stat.CanceledAcquireCount(),
AcquireCount: stat.AcquireCount(),
AcquireDurationMillis: stat.AcquireDuration().Milliseconds(),
NewConnsCount: stat.NewConnsCount(),
MaxLifetimeDestroyCount: stat.MaxLifetimeDestroyCount(),
MaxIdleDestroyCount: stat.MaxIdleDestroyCount(),
}
}
// CreateMessageIdempotent appends a message, its attachment links and the
// idempotency result in one PostgreSQL transaction. A committed transaction
// therefore always contains the message, every link and the key record; a
// failed one contains none of them. The idempotency unique index serialises
// concurrent replays: the loser blocks, then rolls back and reads the committed
// winner, so a concurrent repeat can never create a second message.
//
// Behavior derived from contracts/README.md:
// - a new (user, method, path, key) creates a message and its record, 201;
// - the same semantic body replays the stored message and links, 201;
// - a different body with the same key is a conflict, 409;
// - a transient failure touches neither table, so the client may safely
// retry the same key and never observe a duplicate side effect.
func (s *Store) CreateMessageIdempotent(ctx context.Context, chatID, senderID, method, path, key string, requestHash []byte, text string, attachmentIDs []string) (model.Message, bool, error) {
if attachmentIDs == nil {
attachmentIDs = []string{}
}
message := model.Message{
ID: uuid.New(),
ChatID: chatID,
SenderID: senderID,
Text: text,
// A non-nil empty slice is required: the public Message schema has
// attachment_ids: [] as an array, never null.
AttachmentIDs: append([]string{}, attachmentIDs...),
}
ctx, cancel := s.opCtx(ctx)
defer cancel()
tx, err := s.pool.Begin(ctx)
if err != nil {
return model.Message{}, false, s.classify(err)
}
defer func() { _ = tx.Rollback(context.Background()) }()
// Validate every attachment against the message chat before writing any
// row. The composite foreign key is the second line of defence; this query
// lets the handler distinguish "foreign/unknown" (404) from "not ready"
// (409) without leaking whether a foreign attachment id exists.
if len(attachmentIDs) > 0 {
rows, queryErr := tx.Query(ctx, `
SELECT id::text, status
FROM attachments
WHERE chat_id = $1::uuid
AND id IN (SELECT value::uuid FROM unnest($2::text[]) AS value)`,
chatID, attachmentIDs)
if queryErr != nil {
return model.Message{}, false, s.classify(queryErr)
}
statuses := make(map[string]string, len(attachmentIDs))
for rows.Next() {
var id, status string
if scanErr := rows.Scan(&id, &status); scanErr != nil {
rows.Close()
return model.Message{}, false, s.classify(scanErr)
}
statuses[id] = status
}
if rows.Err() != nil {
rows.Close()
return model.Message{}, false, s.classify(rows.Err())
}
rows.Close()
if len(statuses) != len(attachmentIDs) {
return model.Message{}, false, ErrNotFound
}
// Lab6 allows linking queued/processing attachments: the message is a
// durable reference and becomes fully usable when the worker finishes.
// A failed attachment can never be attached (409), and a ready one keeps
// the inherited ready behaviour.
for _, status := range statuses {
if status == "failed" {
return model.Message{}, false, ErrAttachmentNotReady
}
}
}
created := time.Now().UTC()
var stored time.Time
err = tx.QueryRow(ctx, `
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
VALUES ($1::uuid, $2::uuid, $3::uuid, $4, $5)
RETURNING created_at`,
message.ID, chatID, senderID, text, created,
).Scan(&stored)
if err != nil {
if isForeignKeyViolation(err) {
return model.Message{}, false, ErrNotFound
}
return model.Message{}, false, s.classify(err)
}
if len(attachmentIDs) > 0 {
batch := &pgx.Batch{}
for position, attachmentID := range attachmentIDs {
batch.Queue(`
INSERT INTO message_attachments (message_id, attachment_id, chat_id, position)
VALUES ($1::uuid, $2::uuid, $3::uuid, $4)`,
message.ID, attachmentID, chatID, position)
}
results := tx.SendBatch(ctx, batch)
for range attachmentIDs {
if _, execErr := results.Exec(); execErr != nil {
_ = results.Close()
if isForeignKeyViolation(execErr) {
return model.Message{}, false, ErrNotFound
}
return model.Message{}, false, s.classify(execErr)
}
}
if closeErr := results.Close(); closeErr != nil {
if isForeignKeyViolation(closeErr) {
return model.Message{}, false, ErrNotFound
}
return model.Message{}, false, s.classify(closeErr)
}
}
_, err = tx.Exec(ctx, `
INSERT INTO message_idempotency
(user_id, method, path, key, request_hash, message_id, created_at)
VALUES ($1::uuid, $2, $3, $4, $5, $6::uuid, $7)`,
senderID, method, path, key, requestHash, message.ID, created)
if err != nil {
if isIdempotencyViolation(err) {
// This transaction never committed. Roll it back explicitly before
// reading the winner; PostgreSQL has already released the row lock
// when it reported the unique violation.
_ = tx.Rollback(ctx)
storedHash, storedMessage, found, replayErr := s.replayIdempotent(ctx, senderID, method, path, key)
if replayErr != nil {
return model.Message{}, false, replayErr
}
if !found {
return model.Message{}, false, fmt.Errorf("%w: idempotency record vanished", ErrUnavailable)
}
if !bytes.Equal(storedHash, requestHash) {
return model.Message{}, false, ErrIdempotencyConflict
}
return storedMessage, true, nil
}
return model.Message{}, false, s.classify(err)
}
if err := tx.Commit(ctx); err != nil {
return model.Message{}, false, s.classify(err)
}
message.CreatedAt = model.Time{Time: stored.UTC()}
return message, false, nil
}
func (s *Store) replayIdempotent(ctx context.Context, userID, method, path, key string) ([]byte, model.Message, bool, error) {
var storedHash []byte
var message model.Message
var createdAt time.Time
err := s.pool.QueryRow(ctx, `
SELECT i.request_hash,
m.id::text, m.chat_id::text, m.sender_id::text, m.text, m.created_at,
COALESCE((
SELECT array_agg(ma.attachment_id::text ORDER BY ma.position)
FROM message_attachments ma
WHERE ma.message_id = m.id
), '{}')
FROM message_idempotency i
JOIN messages m ON m.id = i.message_id
WHERE i.user_id = $1::uuid AND i.method = $2 AND i.path = $3 AND i.key = $4`,
userID, method, path, key,
).Scan(&storedHash, &message.ID, &message.ChatID, &message.SenderID, &message.Text, &createdAt, &message.AttachmentIDs)
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return nil, model.Message{}, false, nil
}
return nil, model.Message{}, false, s.classify(err)
}
if message.AttachmentIDs == nil {
message.AttachmentIDs = []string{}
}
message.CreatedAt = model.Time{Time: createdAt.UTC()}
return storedHash, message, true, nil
}
// PruneIdempotency removes records older than the contract's minimum
// retention. It runs opportunistically from every replica; the statement is
// safe to execute concurrently and is bounded to keep one delete short.
func (s *Store) PruneIdempotency(ctx context.Context, olderThan time.Duration) (int64, error) {
ctx, cancel := s.opCtx(ctx)
defer cancel()
tag, err := s.pool.Exec(ctx, `
DELETE FROM message_idempotency
WHERE ctid IN (
SELECT ctid FROM message_idempotency
WHERE created_at < now() - $1::interval
LIMIT 500
)`, fmt.Sprintf("%d seconds", int(olderThan.Seconds())))
if err != nil {
return 0, s.classify(err)
}
return tag.RowsAffected(), nil
}
const messagesPageSelect = `
SELECT m.id::text, m.chat_id::text, m.sender_id::text, m.text, m.created_at,
COALESCE((
SELECT array_agg(ma.attachment_id::text ORDER BY ma.position)
FROM message_attachments ma
WHERE ma.message_id = m.id
), '{}')
FROM (`
// Messages returns one keyset page of a chat history. The caller has already
// verified membership; the query itself never loads the whole history.
func (s *Store) Messages(ctx context.Context, chatID string, position *cursor.Cursor, limit int) (model.MessagePage, error) {
ctx, cancel := s.opCtx(ctx)
defer cancel()
where := `WHERE chat_id = $1::uuid`
args := []any{chatID, limit + 1}
order := `ORDER BY created_at, id
LIMIT $2`
if position != nil {
where = `WHERE chat_id = $1::uuid
AND (created_at, id) > ($2::timestamptz, $3::uuid)`
args = []any{chatID, position.At, position.ID, limit + 1}
order = `ORDER BY created_at, id
LIMIT $4`
}
query := messagesPageSelect + `
SELECT id, chat_id, sender_id, text, created_at
FROM messages
` + where + `
` + order + `
) m
LEFT JOIN message_attachments ma ON ma.message_id = m.id
GROUP BY m.id, m.chat_id, m.sender_id, m.text, m.created_at
ORDER BY m.created_at, m.id`
rows, err := s.pool.Query(ctx, query, args...)
if err != nil {
return model.MessagePage{}, s.classify(err)
}
defer rows.Close()
items := make([]model.Message, 0, limit)
for rows.Next() {
var message model.Message
var createdAt time.Time
if err := rows.Scan(&message.ID, &message.ChatID, &message.SenderID, &message.Text, &createdAt, &message.AttachmentIDs); err != nil {
return model.MessagePage{}, s.classify(err)
}
if message.AttachmentIDs == nil {
message.AttachmentIDs = []string{}
}
message.CreatedAt = model.Time{Time: createdAt.UTC()}
items = append(items, message)
}
if err := rows.Err(); err != nil {
return model.MessagePage{}, s.classify(err)
}
page := model.MessagePage{Items: items}
if len(items) > limit {
page.Items = items[:limit]
next := cursor.ForMessage(page.Items[len(page.Items)-1])
page.NextCursor = &next
}
return page, nil
}
+150
View File
@@ -0,0 +1,150 @@
package telemetry
import (
"context"
"fmt"
"io"
"log/slog"
"strings"
"time"
"go.opentelemetry.io/otel/attribute"
otellog "go.opentelemetry.io/otel/log"
"go.opentelemetry.io/otel/trace"
)
// newJSONHandler is the stdout sink. Docker logs stay useful even when the
// telemetry backend is down, and the same fields are exported over OTLP.
func newJSONHandler(w io.Writer, level slog.Leveler) slog.Handler {
return slog.NewJSONHandler(w, &slog.HandlerOptions{Level: level})
}
// handler writes one structured JSON line to stdout and emits the same record
// to the OTel log SDK. Trace and span identifiers come from the context, so a
// log written inside a server or consumer span is correlated without the caller
// passing IDs explicitly.
type handler struct {
json slog.Handler
logger otellog.Logger
service string
instance string
emitToOTL bool
attrs []slog.Attr
groups []string
}
func (h *handler) Enabled(ctx context.Context, level slog.Level) bool {
return h.json.Enabled(ctx, level)
}
func (h *handler) WithAttrs(attrs []slog.Attr) slog.Handler {
if len(attrs) == 0 {
return h
}
clone := *h
clone.attrs = append(append([]slog.Attr{}, h.attrs...), attrs...)
return &clone
}
func (h *handler) WithGroup(name string) slog.Handler {
if name == "" {
return h
}
clone := *h
clone.groups = append(append([]string{}, h.groups...), name)
return &clone
}
func (h *handler) Handle(ctx context.Context, record slog.Record) error {
spanContext := trace.SpanContextFromContext(ctx)
stdout := record.Clone()
stdout.AddAttrs(h.attrs...)
stdout.AddAttrs(slog.String("event", record.Message))
if spanContext.IsValid() {
stdout.AddAttrs(
slog.String("trace_id", spanContext.TraceID().String()),
slog.String("span_id", spanContext.SpanID().String()),
)
}
stdoutErr := h.json.Handle(ctx, stdout)
if !h.emitToOTL {
return stdoutErr
}
rec := otellog.Record{}
rec.SetTimestamp(record.Time)
rec.SetObservedTimestamp(time.Now())
rec.SetSeverity(severity(record.Level))
rec.SetSeverityText(record.Level.String())
rec.SetEventName(record.Message)
rec.SetBody(attribute.StringValue(record.Message))
attrs := make([]attribute.KeyValue, 0, len(h.attrs)+record.NumAttrs()+5)
attrs = append(attrs,
attribute.String("event", record.Message),
attribute.String("service.name", h.service),
attribute.String("service.instance.id", h.instance),
)
for _, item := range h.attrs {
attrs = append(attrs, slogAttrs(h.groups, item)...)
}
record.Attrs(func(item slog.Attr) bool {
attrs = append(attrs, slogAttrs(h.groups, item)...)
return true
})
if spanContext.IsValid() {
attrs = append(attrs,
attribute.String("trace_id", spanContext.TraceID().String()),
attribute.String("span_id", spanContext.SpanID().String()),
)
}
rec.AddAttributes(attrs...)
h.logger.Emit(ctx, rec)
return stdoutErr
}
func severity(level slog.Level) otellog.Severity {
switch {
case level >= slog.LevelError:
return otellog.SeverityError
case level >= slog.LevelWarn:
return otellog.SeverityWarn
case level >= slog.LevelInfo:
return otellog.SeverityInfo
default:
return otellog.SeverityDebug
}
}
func slogAttrs(groups []string, item slog.Attr) []attribute.KeyValue {
item.Value = item.Value.Resolve()
key := item.Key
if len(groups) > 0 {
key = strings.Join(append(append([]string{}, groups...), key), ".")
}
switch item.Value.Kind() {
case slog.KindGroup:
result := make([]attribute.KeyValue, 0, len(item.Value.Group()))
next := append(append([]string{}, groups...), item.Key)
for _, nested := range item.Value.Group() {
result = append(result, slogAttrs(next, nested)...)
}
return result
case slog.KindString:
return []attribute.KeyValue{attribute.String(key, item.Value.String())}
case slog.KindInt64:
return []attribute.KeyValue{attribute.Int64(key, item.Value.Int64())}
case slog.KindUint64:
return []attribute.KeyValue{attribute.Int64(key, int64(item.Value.Uint64()))}
case slog.KindFloat64:
return []attribute.KeyValue{attribute.Float64(key, item.Value.Float64())}
case slog.KindBool:
return []attribute.KeyValue{attribute.Bool(key, item.Value.Bool())}
case slog.KindDuration:
return []attribute.KeyValue{attribute.Float64(key, item.Value.Duration().Seconds())}
case slog.KindTime:
return []attribute.KeyValue{attribute.String(key, item.Value.Time().UTC().Format(time.RFC3339Nano))}
default:
return []attribute.KeyValue{attribute.String(key, fmt.Sprint(item.Value.Any()))}
}
}
+377
View File
@@ -0,0 +1,377 @@
package telemetry
import (
"context"
"fmt"
"os"
"strconv"
"strings"
"sync"
"time"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/metric"
)
// Instruments is the single place where metric names and units are defined.
// The names are translated by the collector's Prometheus exporter; REPORT.md
// maps each logical signal to the final Prometheus series.
type Instruments struct {
httpRequests metric.Int64Counter
httpDuration metric.Float64Histogram
jobsProcessed metric.Int64Counter
jobsDuration metric.Float64Histogram
timeToReady metric.Float64Histogram
meter metric.Meter
mu sync.Mutex
lastEmpty int64
lastAcquire float64
}
// NewInstruments creates the metric instruments and registers the process
// cgroup gauges (container CPU and memory).
func NewInstruments(provider metric.MeterProvider) (*Instruments, error) {
if provider == nil {
return newNoopInstruments(), nil
}
meter := provider.Meter("messenger-lab7")
httpRequests, err := meter.Int64Counter(MetricHTTPRequests,
metric.WithUnit("{request}"),
metric.WithDescription("HTTP server requests by method, route template and status class"),
)
if err != nil {
return nil, fmt.Errorf("create %s: %w", MetricHTTPRequests, err)
}
httpDuration, err := meter.Float64Histogram(MetricHTTPDuration,
metric.WithUnit("s"),
metric.WithDescription("HTTP server request duration in seconds"),
)
if err != nil {
return nil, fmt.Errorf("create %s: %w", MetricHTTPDuration, err)
}
jobsProcessed, err := meter.Int64Counter(MetricJobsProcessed,
metric.WithUnit("{job}"),
metric.WithDescription("Attachment jobs by outcome"),
)
if err != nil {
return nil, fmt.Errorf("create %s: %w", MetricJobsProcessed, err)
}
jobsDuration, err := meter.Float64Histogram(MetricJobsDuration,
metric.WithUnit("s"),
metric.WithDescription("Attachment job processing duration in seconds"),
)
if err != nil {
return nil, fmt.Errorf("create %s: %w", MetricJobsDuration, err)
}
timeToReady, err := meter.Float64Histogram(MetricTimeToReady,
metric.WithUnit("s"),
metric.WithDescription("End-to-end time from durable acceptance to published ready"),
)
if err != nil {
return nil, fmt.Errorf("create %s: %w", MetricTimeToReady, err)
}
instruments := &Instruments{
httpRequests: httpRequests,
httpDuration: httpDuration,
jobsProcessed: jobsProcessed,
jobsDuration: jobsDuration,
timeToReady: timeToReady,
meter: meter,
}
if err := instruments.registerContainerMetrics(meter); err != nil {
return nil, err
}
return instruments, nil
}
func newNoopInstruments() *Instruments { return &Instruments{} }
// NewNoopInstruments is used by tests and by worker construction without a
// configured meter provider.
func NewNoopInstruments() *Instruments { return newNoopInstruments() }
// HTTPRequest records one completed server request. status is the real HTTP
// status; status_class is what the SLO alert uses.
func (i *Instruments) HTTPRequest(ctx context.Context, method, route string, status int, duration time.Duration) {
if i == nil || i.httpRequests == nil {
return
}
class := statusClass(status)
attrs := metric.WithAttributes(
attribute.String("http.request.method", method),
attribute.String("http.route", route),
attribute.String("status_class", class),
attribute.Int("http.response.status_code", status),
)
i.httpRequests.Add(ctx, 1, attrs)
i.httpDuration.Record(ctx, duration.Seconds(), attrs)
}
// JobProcessed records a terminal or retry outcome for one managed attempt.
func (i *Instruments) JobProcessed(ctx context.Context, jobType, outcome string, duration time.Duration) {
if i == nil || i.jobsProcessed == nil {
return
}
attrs := metric.WithAttributes(
attribute.String("job.type", jobType),
attribute.String("outcome", outcome),
)
i.jobsProcessed.Add(ctx, 1, attrs)
i.jobsDuration.Record(ctx, duration.Seconds(), attrs)
}
// JobReady records the end-to-end acceptance-to-ready time.
func (i *Instruments) JobReady(ctx context.Context, jobType string, duration time.Duration) {
if i == nil || i.timeToReady == nil {
return
}
i.timeToReady.Record(ctx, duration.Seconds(), metric.WithAttributes(
attribute.String("job.type", jobType),
attribute.String("outcome", "success"),
))
}
// Gauges are callbacks into application state; they are evaluated by the SDK
// reader, never on the request hot path.
type Gauges struct {
// Queue returns the number of jobs not yet acknowledged and the age of the
// oldest such entry.
Queue func(ctx context.Context) (depth int64, oldest time.Duration, ok bool)
// Pool returns pgxpool counters. emptyAcquires is cumulative; the exporter
// turns its delta into db.pool.waiting.
Pool func(ctx context.Context) (used, idle, max, emptyAcquires int64, acquireSeconds float64, ok bool)
// Worker returns current active jobs and configured capacity.
Worker func(ctx context.Context) (busy, capacity int64, ok bool)
}
// RegisterGauges installs observable metrics for queue, database pool and
// worker saturation. Missing callbacks are skipped so the API and worker can
// register only the state they own.
func (i *Instruments) RegisterGauges(gauges Gauges) error {
if i == nil || i.meter == nil {
return nil
}
meter := i.meter
if gauges.Queue != nil {
_, err := meter.Int64ObservableGauge(MetricQueueDepth,
metric.WithUnit("{job}"),
metric.WithDescription("Broker entries not yet acknowledged"),
metric.WithInt64Callback(func(ctx context.Context, observer metric.Int64Observer) error {
depth, _, ok := gauges.Queue(ctx)
if ok {
observer.Observe(depth, metric.WithAttributes(attribute.String("queue.name", "attachments")))
}
return nil
}),
)
if err != nil {
return fmt.Errorf("create %s: %w", MetricQueueDepth, err)
}
_, err = meter.Float64ObservableGauge(MetricQueueOldest,
metric.WithUnit("s"),
metric.WithDescription("Age in seconds of the oldest unacknowledged broker entry"),
metric.WithFloat64Callback(func(ctx context.Context, observer metric.Float64Observer) error {
_, oldest, ok := gauges.Queue(ctx)
if ok {
observer.Observe(oldest.Seconds(), metric.WithAttributes(attribute.String("queue.name", "attachments")))
}
return nil
}),
)
if err != nil {
return fmt.Errorf("create %s: %w", MetricQueueOldest, err)
}
}
if gauges.Pool != nil {
if _, err := meter.Int64ObservableGauge(MetricDBPoolUsed,
metric.WithUnit("{connection}"),
metric.WithDescription("Acquired pgx pool connections"),
metric.WithInt64Callback(func(ctx context.Context, observer metric.Int64Observer) error {
used, _, _, _, _, ok := gauges.Pool(ctx)
if ok {
observer.Observe(used)
}
return nil
}),
); err != nil {
return fmt.Errorf("create %s: %w", MetricDBPoolUsed, err)
}
if _, err := meter.Int64ObservableGauge(MetricDBPoolIdle,
metric.WithUnit("{connection}"),
metric.WithDescription("Idle pgx pool connections"),
metric.WithInt64Callback(func(ctx context.Context, observer metric.Int64Observer) error {
_, idle, _, _, _, ok := gauges.Pool(ctx)
if ok {
observer.Observe(idle)
}
return nil
}),
); err != nil {
return fmt.Errorf("create %s: %w", MetricDBPoolIdle, err)
}
if _, err := meter.Int64ObservableGauge(MetricDBPoolMax,
metric.WithUnit("{connection}"),
metric.WithDescription("Configured maximum pgx pool connections"),
metric.WithInt64Callback(func(ctx context.Context, observer metric.Int64Observer) error {
_, _, max, _, _, ok := gauges.Pool(ctx)
if ok {
observer.Observe(max)
}
return nil
}),
); err != nil {
return fmt.Errorf("create %s: %w", MetricDBPoolMax, err)
}
// pgxpool does not expose an instantaneous waiter counter. The exported
// gauge is the number of acquires that had to wait since the previous
// collection; the cumulative counter is kept for rate queries.
if _, err := meter.Int64ObservableGauge(MetricDBPoolWaiting,
metric.WithUnit("{acquire}"),
metric.WithDescription("Acquires that blocked since the previous metric collection"),
metric.WithInt64Callback(func(ctx context.Context, observer metric.Int64Observer) error {
used, idle, max, empty, acquireSeconds, ok := gauges.Pool(ctx)
if !ok {
return nil
}
i.mu.Lock()
delta := empty - i.lastEmpty
if delta < 0 {
delta = empty
}
i.lastEmpty = empty
waited := acquireSeconds - i.lastAcquire
if waited < 0 {
waited = acquireSeconds
}
i.lastAcquire = acquireSeconds
i.mu.Unlock()
_ = used
_ = idle
_ = max
observer.Observe(delta)
return nil
}),
); err != nil {
return fmt.Errorf("create %s: %w", MetricDBPoolWaiting, err)
}
if _, err := meter.Float64ObservableGauge(MetricDBPoolWaitSec,
metric.WithUnit("s"),
metric.WithDescription("Cumulative seconds spent waiting for a pool connection"),
metric.WithFloat64Callback(func(ctx context.Context, observer metric.Float64Observer) error {
_, _, _, _, acquireSeconds, ok := gauges.Pool(ctx)
if ok {
observer.Observe(acquireSeconds)
}
return nil
}),
); err != nil {
return fmt.Errorf("create %s: %w", MetricDBPoolWaitSec, err)
}
}
if gauges.Worker != nil {
if _, err := meter.Int64ObservableGauge(MetricWorkerBusy,
metric.WithUnit("{job}"),
metric.WithDescription("Attachment jobs currently processed by this worker"),
metric.WithInt64Callback(func(ctx context.Context, observer metric.Int64Observer) error {
busy, _, ok := gauges.Worker(ctx)
if ok {
observer.Observe(busy)
}
return nil
}),
); err != nil {
return fmt.Errorf("create %s: %w", MetricWorkerBusy, err)
}
if _, err := meter.Int64ObservableGauge(MetricWorkerCap,
metric.WithUnit("{job}"),
metric.WithDescription("Configured worker concurrency"),
metric.WithInt64Callback(func(ctx context.Context, observer metric.Int64Observer) error {
_, capacity, ok := gauges.Worker(ctx)
if ok {
observer.Observe(capacity)
}
return nil
}),
); err != nil {
return fmt.Errorf("create %s: %w", MetricWorkerCap, err)
}
}
return nil
}
func statusClass(status int) string {
switch {
case status >= 100 && status < 200:
return "1xx"
case status >= 200 && status < 300:
return "2xx"
case status >= 300 && status < 400:
return "3xx"
case status >= 400 && status < 500:
return "4xx"
default:
return "5xx"
}
}
func (i *Instruments) registerContainerMetrics(meter metric.Meter) error {
if _, err := meter.Int64ObservableGauge(MetricMemUsage,
metric.WithUnit("By"),
metric.WithDescription("Container cgroup memory.current in bytes"),
metric.WithInt64Callback(func(_ context.Context, observer metric.Int64Observer) error {
if value, ok := cgroupMemoryBytes(); ok {
observer.Observe(value)
}
return nil
}),
); err != nil {
return fmt.Errorf("create %s: %w", MetricMemUsage, err)
}
if _, err := meter.Float64ObservableCounter(MetricCPUTime,
metric.WithUnit("s"),
metric.WithDescription("Cumulative container CPU time in seconds from cgroup cpu.stat"),
metric.WithFloat64Callback(func(_ context.Context, observer metric.Float64Observer) error {
if value, ok := cgroupCPUSeconds(); ok {
observer.Observe(value)
}
return nil
}),
); err != nil {
return fmt.Errorf("create %s: %w", MetricCPUTime, err)
}
return nil
}
func cgroupMemoryBytes() (int64, bool) {
for _, path := range []string{"/sys/fs/cgroup/memory.current", "/sys/fs/cgroup/memory/memory.usage_in_bytes"} {
data, err := os.ReadFile(path)
if err != nil {
continue
}
value, err := strconv.ParseInt(strings.TrimSpace(string(data)), 10, 64)
if err == nil {
return value, true
}
}
return 0, false
}
func cgroupCPUSeconds() (float64, bool) {
if data, err := os.ReadFile("/sys/fs/cgroup/cpu.stat"); err == nil {
for _, line := range strings.Split(string(data), "\n") {
fields := strings.Fields(line)
if len(fields) == 2 && fields[0] == "usage_usec" {
if value, err := strconv.ParseInt(fields[1], 10, 64); err == nil {
return float64(value) / 1e6, true
}
}
}
}
if data, err := os.ReadFile("/sys/fs/cgroup/cpuacct/cpuacct.usage"); err == nil {
if value, err := strconv.ParseInt(strings.TrimSpace(string(data)), 10, 64); err == nil {
return float64(value) / 1e9, true
}
}
return 0, false
}
+77
View File
@@ -0,0 +1,77 @@
package telemetry
import (
"context"
"strings"
"github.com/jackc/pgx/v5"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/codes"
"go.opentelemetry.io/otel/trace"
)
type pgxSpanKey struct{}
// PgxTracer turns every Query/QueryRow/Exec into a client span. It records the
// operation class and duration only: SQL text and arguments are intentionally
// not exported because they can contain user data or credentials.
type PgxTracer struct {
tracer trace.Tracer
}
// NewPgxTracer returns a tracer suitable for pgxpool.Config.ConnConfig.Tracer.
func NewPgxTracer(tracer trace.Tracer) *PgxTracer { return &PgxTracer{tracer: tracer} }
func (t *PgxTracer) TraceQueryStart(ctx context.Context, _ *pgx.Conn, data pgx.TraceQueryStartData) context.Context {
// Only instrument queries that are already inside a request or job span.
// Background outbox polling and recovery loops have no active span; creating
// root database traces for them would inflate the trace count without
// explaining a user-visible operation.
if !trace.SpanContextFromContext(ctx).IsValid() {
return ctx
}
operation := sqlOperation(data.SQL)
ctx, span := t.tracer.Start(ctx, "postgresql "+operation,
trace.WithSpanKind(trace.SpanKindClient),
trace.WithAttributes(
attribute.String("db.system.name", "postgresql"),
attribute.String("db.operation.name", operation),
),
)
return context.WithValue(ctx, pgxSpanKey{}, span)
}
func (t *PgxTracer) TraceQueryEnd(ctx context.Context, _ *pgx.Conn, data pgx.TraceQueryEndData) {
span, _ := ctx.Value(pgxSpanKey{}).(trace.Span)
if span == nil {
return
}
if data.Err != nil {
span.SetStatus(codes.Error, "database operation failed")
span.SetAttributes(attribute.String("error.type", "database_error"))
}
span.End()
}
func sqlOperation(sql string) string {
value := strings.TrimSpace(sql)
for strings.HasPrefix(value, "--") {
if index := strings.IndexByte(value, '\n'); index >= 0 {
value = strings.TrimSpace(value[index+1:])
} else {
return "unknown"
}
}
if value == "" {
return "unknown"
}
fields := strings.Fields(value)
if len(fields) == 0 {
return "unknown"
}
operation := strings.ToUpper(strings.TrimRight(fields[0], ";"))
if len(operation) > 24 {
operation = operation[:24]
}
return operation
}
+402
View File
@@ -0,0 +1,402 @@
// Package telemetry wires the OpenTelemetry SDK into the API and the worker.
//
// The application sends all three signals to a dedicated OTel Collector over
// OTLP/HTTP. Nothing is written directly to Prometheus, Loki or Tempo: the
// collector owns retries, batching and bounded queues, so a telemetry backend
// outage cannot block a business request.
package telemetry
import (
"context"
"errors"
"fmt"
"log/slog"
"net/url"
"os"
"strconv"
"strings"
"time"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/attribute"
otellog "go.opentelemetry.io/otel/log"
"go.opentelemetry.io/otel/propagation"
sdklog "go.opentelemetry.io/otel/sdk/log"
sdkmetric "go.opentelemetry.io/otel/sdk/metric"
"go.opentelemetry.io/otel/sdk/resource"
sdktrace "go.opentelemetry.io/otel/sdk/trace"
"go.opentelemetry.io/otel/trace"
"go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp"
"go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp"
"go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp"
)
const (
// DefaultEndpoint is the collector's OTLP/HTTP listener inside the compose
// network. It is never the address of a storage backend.
DefaultEndpoint = "http://otel-collector:4318"
// These bounds make the SDK side of the telemetry pipeline finite. When a
// queue is full the SDK drops telemetry; it never blocks the caller.
traceQueueSize = 2048
traceBatchSize = 512
logQueueSize = 2048
logBatchSize = 512
metricExportPeriod = 15 * time.Second
)
// Options describes one process' telemetry identity.
type Options struct {
ServiceName string
ServiceVersion string
InstanceID string
Environment string
}
// Provider owns the SDK providers and the context-aware structured logger.
type Provider struct {
tracerProvider *sdktrace.TracerProvider
meterProvider *sdkmetric.MeterProvider
loggerProvider *sdklog.LoggerProvider
instruments *Instruments
logger *slog.Logger
enabled bool
}
// Enabled reports whether OTLP export is active.
func (p *Provider) Enabled() bool { return p != nil && p.enabled }
// Instruments exposes the metric instruments shared by the API and worker.
func (p *Provider) Instruments() *Instruments { return p.instruments }
// Logger returns the JSON+OTLP structured logger.
func (p *Provider) Logger() *slog.Logger { return p.logger }
// Tracer returns a named tracer from the configured provider.
func (p *Provider) Tracer(name string) trace.Tracer {
// When OTEL_SDK_DISABLED=true the provider is non-nil but owns no tracer
// provider. Returning a no-op tracer keeps the instrumentation call sites
// identical in both modes and must not panic on startup.
if p == nil || p.tracerProvider == nil {
return trace.NewNoopTracerProvider().Tracer(name)
}
return p.tracerProvider.Tracer(name)
}
// Setup builds the providers according to the standard OTEL_* environment
// variables. OTEL_SDK_DISABLED=true turns every signal off while keeping the
// same structured JSON logging on stdout.
func Setup(ctx context.Context, opts Options) (*Provider, error) {
if opts.ServiceName == "" {
return nil, errors.New("telemetry service name is required")
}
if opts.Environment == "" {
opts.Environment = "lab"
}
disabled := strings.EqualFold(strings.TrimSpace(os.Getenv("OTEL_SDK_DISABLED")), "true")
endpoint := strings.TrimSpace(os.Getenv("OTEL_EXPORTER_OTLP_ENDPOINT"))
if endpoint == "" {
endpoint = DefaultEndpoint
}
serviceName := opts.ServiceName
logger := slog.New(newJSONHandler(os.Stdout, logLevel())).With(
slog.String("service.name", serviceName),
slog.String("service.instance.id", opts.InstanceID),
slog.String("deployment.environment.name", opts.Environment),
)
provider := &Provider{enabled: !disabled}
if disabled {
// Keep the global providers at their no-op defaults. Instrumentation
// calls remain in the code path, which is what the "telemetry off"
// experiment measures.
provider.instruments = newNoopInstruments()
provider.logger = logger
return provider, nil
}
host, insecure, err := parseEndpoint(endpoint)
if err != nil {
return nil, err
}
res, err := resource.New(ctx,
resource.WithAttributes(
attribute.String("service.name", serviceName),
attribute.String("service.version", opts.ServiceVersion),
attribute.String("service.instance.id", opts.InstanceID),
attribute.String("deployment.environment.name", opts.Environment),
attribute.Int("process.pid", os.Getpid()),
),
resource.WithFromEnv(),
resource.WithTelemetrySDK(),
)
if err != nil {
return nil, fmt.Errorf("build telemetry resource: %w", err)
}
traceOpts := []otlptracehttp.Option{
otlptracehttp.WithEndpoint(host),
otlptracehttp.WithURLPath("/v1/traces"),
otlptracehttp.WithTimeout(5 * time.Second),
otlptracehttp.WithCompression(otlptracehttp.GzipCompression),
}
if insecure {
traceOpts = append(traceOpts, otlptracehttp.WithInsecure())
}
traceExporter, err := otlptracehttp.New(ctx, traceOpts...)
if err != nil {
return nil, fmt.Errorf("create OTLP trace exporter: %w", err)
}
// ParentBased(TraceIDRatioBased) is the standard head sampler. The
// collector configuration can additionally apply tail sampling.
sampler, samplerName, err := samplerFromEnv()
if err != nil {
return nil, err
}
traceProvider := sdktrace.NewTracerProvider(
sdktrace.WithResource(res),
sdktrace.WithSampler(sampler),
sdktrace.WithBatcher(traceExporter,
sdktrace.WithMaxQueueSize(traceQueueSize),
sdktrace.WithMaxExportBatchSize(traceBatchSize),
sdktrace.WithBatchTimeout(5*time.Second),
sdktrace.WithExportTimeout(5*time.Second),
),
)
metricOpts := []otlpmetrichttp.Option{
otlpmetrichttp.WithEndpoint(host),
otlpmetrichttp.WithURLPath("/v1/metrics"),
otlpmetrichttp.WithTimeout(10 * time.Second),
otlpmetrichttp.WithCompression(otlpmetrichttp.GzipCompression),
}
if insecure {
metricOpts = append(metricOpts, otlpmetrichttp.WithInsecure())
}
metricExporter, err := otlpmetrichttp.New(ctx, metricOpts...)
if err != nil {
return nil, fmt.Errorf("create OTLP metric exporter: %w", err)
}
meterProvider := sdkmetric.NewMeterProvider(
sdkmetric.WithResource(res),
sdkmetric.WithReader(sdkmetric.NewPeriodicReader(metricExporter,
sdkmetric.WithInterval(metricExportPeriod),
sdkmetric.WithTimeout(10*time.Second),
)),
histogramViews(),
)
logOpts := []otlploghttp.Option{
otlploghttp.WithEndpoint(host),
otlploghttp.WithURLPath("/v1/logs"),
otlploghttp.WithTimeout(5 * time.Second),
otlploghttp.WithCompression(otlploghttp.GzipCompression),
}
if insecure {
logOpts = append(logOpts, otlploghttp.WithInsecure())
}
logExporter, err := otlploghttp.New(ctx, logOpts...)
if err != nil {
return nil, fmt.Errorf("create OTLP log exporter: %w", err)
}
loggerProvider := sdklog.NewLoggerProvider(
sdklog.WithResource(res),
sdklog.WithProcessor(sdklog.NewBatchProcessor(logExporter,
sdklog.WithMaxQueueSize(logQueueSize),
sdklog.WithExportMaxBatchSize(logBatchSize),
sdklog.WithExportInterval(5*time.Second),
sdklog.WithExportTimeout(5*time.Second),
)),
)
otel.SetTracerProvider(traceProvider)
otel.SetMeterProvider(meterProvider)
otel.SetLoggerProvider(loggerProvider)
otel.SetTextMapPropagator(propagation.NewCompositeTextMapPropagator(
propagation.TraceContext{},
propagation.Baggage{},
))
instruments, err := NewInstruments(meterProvider)
if err != nil {
return nil, err
}
provider.tracerProvider = traceProvider
provider.meterProvider = meterProvider
provider.loggerProvider = loggerProvider
provider.instruments = instruments
otlpLogger := loggerProvider.Logger("messenger-lab7/structured")
handler := &handler{
json: newJSONHandler(os.Stdout, logLevel()),
logger: otlpLogger,
service: serviceName,
instance: opts.InstanceID,
emitToOTL: true,
}
provider.logger = slog.New(handler).With(
slog.String("service.name", serviceName),
slog.String("service.instance.id", opts.InstanceID),
slog.String("deployment.environment.name", opts.Environment),
)
provider.logger.Info("telemetry initialized",
"otel_endpoint", endpoint,
"trace_sampler", samplerName,
"trace_queue_size", traceQueueSize,
"trace_batch_size", traceBatchSize,
"log_queue_size", logQueueSize,
"metric_export_interval_seconds", metricExportPeriod.Seconds(),
)
return provider, nil
}
// Shutdown flushes and closes all providers. It is bounded so process
// termination keeps the container grace period.
func (p *Provider) Shutdown(ctx context.Context) error {
if p == nil || !p.enabled {
return nil
}
var errs []error
if p.loggerProvider != nil {
errs = append(errs, p.loggerProvider.Shutdown(ctx))
}
if p.meterProvider != nil {
errs = append(errs, p.meterProvider.Shutdown(ctx))
}
if p.tracerProvider != nil {
errs = append(errs, p.tracerProvider.Shutdown(ctx))
}
return errors.Join(errs...)
}
func parseEndpoint(raw string) (host string, insecure bool, err error) {
parsed, err := url.Parse(raw)
if err != nil || parsed.Host == "" {
return "", false, fmt.Errorf("OTEL_EXPORTER_OTLP_ENDPOINT must be an absolute http(s) URL")
}
switch parsed.Scheme {
case "http":
insecure = true
case "https":
insecure = false
default:
return "", false, fmt.Errorf("OTEL_EXPORTER_OTLP_ENDPOINT must use http or https")
}
return parsed.Host, insecure, nil
}
func samplerFromEnv() (sdktrace.Sampler, string, error) {
name := strings.ToLower(strings.TrimSpace(os.Getenv("OTEL_TRACES_SAMPLER")))
if name == "" {
name = "parentbased_always_on"
}
ratio := 1.0
if raw := strings.TrimSpace(os.Getenv("OTEL_TRACES_SAMPLER_ARG")); raw != "" {
value, err := strconv.ParseFloat(raw, 64)
if err != nil || value < 0 || value > 1 {
return nil, "", errors.New("OTEL_TRACES_SAMPLER_ARG must be a number between 0 and 1")
}
ratio = value
}
switch name {
case "always_on":
return sdktrace.AlwaysSample(), name, nil
case "always_off":
return sdktrace.NeverSample(), name, nil
case "traceidratio":
return sdktrace.TraceIDRatioBased(ratio), fmt.Sprintf("%s(%.3f)", name, ratio), nil
case "parentbased_always_on":
return sdktrace.ParentBased(sdktrace.AlwaysSample()), name, nil
case "parentbased_always_off":
return sdktrace.ParentBased(sdktrace.NeverSample()), name, nil
case "parentbased_traceidratio":
return sdktrace.ParentBased(sdktrace.TraceIDRatioBased(ratio)), fmt.Sprintf("%s(%.3f)", name, ratio), nil
default:
return nil, "", fmt.Errorf("unsupported OTEL_TRACES_SAMPLER %q", name)
}
}
// TraceContext returns the W3C traceparent/tracestate pair for ctx. It returns
// empty strings when ctx has no valid span context.
func TraceContext(ctx context.Context) (traceParent, traceState string) {
carrier := propagation.MapCarrier{}
otel.GetTextMapPropagator().Inject(ctx, carrier)
return carrier["traceparent"], carrier["tracestate"]
}
// RemoteContext extracts W3C trace context from a broker message. A missing or
// malformed value simply starts a new trace; it never fails the job.
func RemoteContext(ctx context.Context, traceParent, traceState string) context.Context {
carrier := propagation.MapCarrier{}
if traceParent != "" {
carrier["traceparent"] = traceParent
}
if traceState != "" {
carrier["tracestate"] = traceState
}
return otel.GetTextMapPropagator().Extract(ctx, carrier)
}
// logLevel reads LOG_LEVEL without importing the config package (avoids a
// cycle: config validates telemetry settings numerically, telemetry only logs).
func logLevel() slog.Level {
switch strings.ToLower(strings.TrimSpace(os.Getenv("LOG_LEVEL"))) {
case "debug":
return slog.LevelDebug
case "warn", "warning":
return slog.LevelWarn
case "error":
return slog.LevelError
default:
return slog.LevelInfo
}
}
// Metric instrument names are intentionally stable and documented in REPORT.md.
const (
MetricHTTPRequests = "http.server.requests"
MetricHTTPDuration = "http.server.duration"
MetricJobsProcessed = "jobs.processed"
MetricJobsDuration = "jobs.duration"
MetricTimeToReady = "job.time_to_ready"
MetricQueueDepth = "queue.depth"
MetricQueueOldest = "queue.oldest.age"
MetricDBPoolUsed = "db.pool.used"
MetricDBPoolIdle = "db.pool.idle"
MetricDBPoolMax = "db.pool.max"
MetricDBPoolWaiting = "db.pool.waiting"
MetricDBPoolWaitSec = "db.pool.wait.duration"
MetricWorkerBusy = "worker.jobs.busy"
MetricWorkerCap = "worker.jobs.capacity"
MetricMemUsage = "process.memory.usage"
MetricCPUTime = "process.cpu.time"
)
func histogramViews() sdkmetric.Option {
httpBuckets := []float64{0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10}
jobBuckets := []float64{0.01, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10, 30, 60}
readyBuckets := []float64{0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10, 30, 60, 120}
return sdkmetric.WithView(
sdkmetric.NewView(
sdkmetric.Instrument{Name: MetricHTTPDuration},
sdkmetric.Stream{Aggregation: sdkmetric.AggregationExplicitBucketHistogram{Boundaries: httpBuckets}},
),
sdkmetric.NewView(
sdkmetric.Instrument{Name: MetricJobsDuration},
sdkmetric.Stream{Aggregation: sdkmetric.AggregationExplicitBucketHistogram{Boundaries: jobBuckets}},
),
sdkmetric.NewView(
sdkmetric.Instrument{Name: MetricTimeToReady},
sdkmetric.Stream{Aggregation: sdkmetric.AggregationExplicitBucketHistogram{Boundaries: readyBuckets}},
),
)
}
// Ensure the log package aliases are used even when the OTLP handler path is
// compiled with a no-op provider.
var _ otellog.Logger = sdklog.NewLoggerProvider().Logger("compile-time-check")
+46
View File
@@ -0,0 +1,46 @@
package telemetry
import (
"context"
"testing"
"go.opentelemetry.io/otel/trace"
)
// TestSetupDisabledKeepsInstrumentationUsable guards the telemetry-off
// configuration used by the track-1 cost experiment. The SDK is disabled, but
// every instrumented call site (Tracer, Instruments, Logger) must still work
// and stay a no-op; a nil tracer provider must not panic during process start.
func TestSetupDisabledKeepsInstrumentationUsable(t *testing.T) {
t.Setenv("OTEL_SDK_DISABLED", "true")
provider, err := Setup(context.Background(), Options{
ServiceName: "messenger-api",
ServiceVersion: "test",
InstanceID: "test-instance",
Environment: "lab",
})
if err != nil {
t.Fatalf("Setup with telemetry disabled: %v", err)
}
if provider.Enabled() {
t.Fatal("provider reports enabled while OTEL_SDK_DISABLED=true")
}
ctx, span := provider.Tracer("test").Start(context.Background(), "disabled-span")
if trace.SpanContextFromContext(ctx).IsValid() {
t.Fatal("disabled telemetry produced a valid span context")
}
span.End()
if provider.Instruments() == nil {
t.Fatal("disabled telemetry returned nil instruments")
}
provider.Instruments().HTTPRequest(context.Background(), "GET", "/health/live", 200, 0)
if err := provider.Instruments().RegisterGauges(Gauges{}); err != nil {
t.Fatalf("disabled telemetry gauge registration: %v", err)
}
if provider.Logger() == nil {
t.Fatal("disabled telemetry returned a nil logger")
}
if err := provider.Shutdown(context.Background()); err != nil {
t.Fatalf("disabled telemetry shutdown: %v", err)
}
}
+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)
}
}
}
+942
View File
@@ -0,0 +1,942 @@
// Package worker runs the durable attachment pipeline. It consumes the broker
// at least once, claims a PostgreSQL lease, writes the final original and the
// three versioned derivatives to S3, commits the result atomically, removes the
// staging object and only then acknowledges the broker entry.
//
// Every effect is keyed by (attachment_id, pipeline_version, variant), and the
// database makes ready_version monotonic. A duplicate, reordered or stale
// delivery therefore either completes the same bytes or is a safe no-op.
package worker
import (
"bytes"
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"io"
"log/slog"
"math/rand"
"os"
"strings"
"sync"
"sync/atomic"
"time"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/codes"
"go.opentelemetry.io/otel/trace"
"mtusi.ru/messenger-lab7/internal/broker"
"mtusi.ru/messenger-lab7/internal/job"
"mtusi.ru/messenger-lab7/internal/objectstore"
"mtusi.ru/messenger-lab7/internal/pipeline"
"mtusi.ru/messenger-lab7/internal/store"
"mtusi.ru/messenger-lab7/internal/telemetry"
"mtusi.ru/messenger-lab7/internal/uuid"
)
// Options bounds every worker resource. They come from validated configuration.
type Options struct {
Env string
Concurrency int
MaxAttempts int
JobTimeout time.Duration
Lease time.Duration
ClaimIdle time.Duration
BackoffBase time.Duration
BackoffMax time.Duration
StagingRetention time.Duration
ClaimInterval time.Duration
RecoveryInterval time.Duration
JanitorInterval time.Duration
FaultInject string
FaultTarget string
MaxUploadBytes int64
Metrics *telemetry.Instruments
Tracer trace.Tracer
}
// Worker is the long-running consumer process.
type Worker struct {
store *store.Store
objects *objectstore.Store
broker *broker.Broker
log *slog.Logger
opts Options
consumer string
metrics *telemetry.Instruments
tracer trace.Tracer
busy atomic.Int64
}
var errStagingCorrupt = errors.New("staged original does not match its recorded checksum")
// New creates a worker. consumer is stable for this process lifetime; pending
// entries from a previous process are recovered with XAUTOCLAIM.
func New(repository *store.Store, objects *objectstore.Store, transport *broker.Broker, logger *slog.Logger, consumer string, opts Options) *Worker {
if opts.Concurrency <= 0 {
opts.Concurrency = 1
}
if opts.MaxAttempts <= 0 {
opts.MaxAttempts = 5
}
if opts.ClaimInterval <= 0 {
opts.ClaimInterval = 5 * time.Second
}
if opts.RecoveryInterval <= 0 {
opts.RecoveryInterval = 5 * time.Second
}
if opts.JanitorInterval <= 0 {
opts.JanitorInterval = 30 * time.Second
}
if opts.Tracer == nil {
opts.Tracer = trace.NewNoopTracerProvider().Tracer("messenger-worker")
}
if opts.Metrics == nil {
opts.Metrics = telemetry.NewNoopInstruments()
}
return &Worker{
store: repository, objects: objects, broker: transport, log: logger,
opts: opts, consumer: consumer, metrics: opts.Metrics, tracer: opts.Tracer,
}
}
// Run starts bounded consumers and the recovery loops, then blocks until the
// context is cancelled. Unacknowledged entries stay in the consumer-group PEL
// and are redelivered after ClaimIdle by the next process.
// RunOnce consumes and handles one broker delivery, then returns. It is used by
// the bounded-retry fault tests, where each worker invocation represents one
// managed attempt. Recovery loops and consumer slots are not started.
func (w *Worker) RunOnce(ctx context.Context) error {
for {
err := w.broker.EnsureGroup(ctx)
if err == nil || errors.Is(err, broker.ErrGroupExists) {
break
}
if ctx.Err() != nil {
return ctx.Err()
}
w.log.Log(ctx, slog.LevelWarn, "waiting for broker consumer group", "error", err)
select {
case <-ctx.Done():
return ctx.Err()
case <-time.After(2 * time.Second):
}
}
consumer := w.consumer + ":once"
for ctx.Err() == nil {
messages, err := w.broker.Read(ctx, consumer, 2*time.Second, 1)
if err != nil {
if ctx.Err() != nil {
return ctx.Err()
}
w.log.Log(ctx, slog.LevelWarn, "broker read failed", "error", err)
time.Sleep(time.Second)
continue
}
for _, message := range messages {
w.handle(ctx, message)
return nil
}
}
return ctx.Err()
}
func (w *Worker) Run(ctx context.Context) error {
for {
err := w.broker.EnsureGroup(ctx)
if err == nil || errors.Is(err, broker.ErrGroupExists) {
break
}
if ctx.Err() != nil {
return ctx.Err()
}
w.log.Log(ctx, slog.LevelWarn, "waiting for broker consumer group", "error", err)
select {
case <-ctx.Done():
return ctx.Err()
case <-time.After(2 * time.Second):
}
}
var wait sync.WaitGroup
for slot := 0; slot < w.opts.Concurrency; slot++ {
wait.Add(1)
go func(slot int) {
defer wait.Done()
w.consume(ctx, fmt.Sprintf("%s:%d", w.consumer, slot))
}(slot)
}
wait.Add(1)
go func() {
defer wait.Done()
w.autoclaimLoop(ctx)
}()
wait.Add(1)
go func() {
defer wait.Done()
w.recoveryLoop(ctx)
}()
wait.Add(1)
go func() {
defer wait.Done()
w.janitorLoop(ctx)
}()
<-ctx.Done()
wait.Wait()
return nil
}
func (w *Worker) consume(ctx context.Context, consumer string) {
for ctx.Err() == nil {
messages, err := w.broker.Read(ctx, consumer, 2*time.Second, 1)
if err != nil {
if ctx.Err() != nil {
return
}
w.log.Log(ctx, slog.LevelWarn, "broker read failed", "error", err)
select {
case <-ctx.Done():
return
case <-time.After(time.Second):
}
continue
}
for _, message := range messages {
w.handle(ctx, message)
}
}
}
func (w *Worker) handle(ctx context.Context, delivery broker.Message) {
message, err := job.Parse([]byte(delivery.Payload))
if err != nil {
// A malformed entry cannot be tied to a durable job. Log without the
// payload (it could contain anything) and acknowledge so one poison
// entry cannot block the stream forever.
w.log.Log(ctx, slog.LevelError, "invalid broker job payload; acknowledging poison entry",
"stream_id", delivery.ID, "error", err)
w.ack(ctx, delivery.ID)
return
}
parent := telemetry.RemoteContext(ctx, message.TraceParent, message.TraceState)
ctx, span := w.tracer.Start(parent, "attachment.process",
trace.WithSpanKind(trace.SpanKindConsumer),
trace.WithAttributes(
attribute.String("messaging.system", "valkey_streams"),
attribute.String("messaging.destination.name", w.broker.Stream()),
attribute.String("messaging.operation.name", "process"),
attribute.String("messaging.message.id", delivery.ID),
attribute.String("job.type", message.Type),
attribute.Int("job.attempt", message.Attempt),
attribute.Int("job.pipeline_version", message.PipelineVersion),
attribute.String("job.id", message.JobID),
attribute.String("attachment.id", message.AttachmentID),
),
)
defer span.End()
assignment, err := w.store.JobAssignment(ctx, message.JobID)
if err != nil {
if errors.Is(err, store.ErrNotFound) {
w.log.Log(ctx, slog.LevelWarn, "job from broker does not exist; acknowledging orphan",
"job_id", message.JobID, "stream_id", delivery.ID)
w.ack(ctx, delivery.ID)
return
}
w.log.Log(ctx, slog.LevelWarn, "could not read job assignment; leaving delivery pending",
"job_id", message.JobID, "error", err)
return
}
if assignment.AttachmentID != message.AttachmentID ||
assignment.PipelineVersion != message.PipelineVersion {
w.log.Log(ctx, slog.LevelError, "broker job disagrees with durable job; acknowledging poison entry",
"job_id", message.JobID, "stream_id", delivery.ID)
w.ack(ctx, delivery.ID)
return
}
now := time.Now().UTC()
switch assignment.JobStatus {
case "ready":
w.verifyAndAck(ctx, delivery.ID, assignment)
return
case "failed":
w.log.Log(ctx, slog.LevelInfo, "duplicate delivery of failed job; acknowledging",
"job_id", assignment.JobID, "attempt", message.Attempt)
w.ack(ctx, delivery.ID)
return
}
if assignment.JobAttempts > message.Attempt {
w.log.Log(ctx, slog.LevelInfo, "stale attempt delivery; acknowledging without effect",
"job_id", assignment.JobID, "delivered_attempt", message.Attempt,
"current_attempt", assignment.JobAttempts)
w.ack(ctx, delivery.ID)
return
}
if assignment.JobStatus == "queued" && assignment.AvailableAt.After(now) {
// The retry outbox row will publish the next attempt when it is due.
w.ack(ctx, delivery.ID)
return
}
if assignment.JobStatus == "processing" && assignment.LeaseExpiresAt != nil && assignment.LeaseExpiresAt.After(now) {
w.log.Log(ctx, slog.LevelInfo, "duplicate delivery while another lease is live; acknowledging",
"job_id", assignment.JobID, "attempt", message.Attempt,
"lease_owner", safeOwner(assignment.LeaseOwner))
w.ack(ctx, delivery.ID)
return
}
claim, claimed, err := w.store.TryClaimJob(ctx, message.JobID, message.Attempt, w.consumer, w.opts.Lease, now)
if err != nil {
w.log.Log(ctx, slog.LevelWarn, "job claim failed; leaving delivery pending", "job_id", message.JobID, "error", err)
return
}
if !claimed {
w.log.Log(ctx, slog.LevelInfo, "job claim lost the race; acknowledging duplicate",
"job_id", message.JobID, "attempt", message.Attempt)
w.ack(ctx, delivery.ID)
return
}
w.process(ctx, delivery, assignment, claim)
}
// Busy and Capacity feed the worker saturation gauge.
func (w *Worker) Busy() int64 { return w.busy.Load() }
// Capacity is the configured number of consumer slots.
func (w *Worker) Capacity() int64 { return int64(w.opts.Concurrency) }
func safeOwner(owner *string) string {
if owner == nil {
return ""
}
return *owner
}
func (w *Worker) process(ctx context.Context, delivery broker.Message, assignment store.Assignment, claim store.Claim) {
started := time.Now()
w.busy.Add(1)
defer w.busy.Add(-1)
workCtx, cancelWork := context.WithTimeout(ctx, w.opts.JobTimeout)
defer cancelWork()
var leaseLost atomic.Bool
heartbeatDone := make(chan struct{})
go func() {
defer close(heartbeatDone)
ticker := time.NewTicker(w.opts.Lease / 3)
defer ticker.Stop()
for {
select {
case <-workCtx.Done():
return
case <-ticker.C:
ok, err := w.store.HeartbeatLease(workCtx, claim.JobID, w.consumer, w.opts.Lease, time.Now().UTC())
if err != nil {
w.log.Log(ctx, slog.LevelWarn, "lease heartbeat failed", "job_id", claim.JobID, "error", err)
continue
}
if !ok {
leaseLost.Store(true)
cancelWork()
return
}
}
}
}()
defer func() {
cancelWork()
<-heartbeatDone
}()
if err := w.injectTransient(ctx, claim); err != nil {
w.finishWithError(ctx, delivery, claim, started, err, leaseLost.Load())
return
}
downloadCtx, downloadSpan := w.tracer.Start(workCtx, "s3.get staging",
trace.WithSpanKind(trace.SpanKindClient),
trace.WithAttributes(
attribute.String("aws.s3.operation", "GetObject"),
attribute.String("aws.s3.bucket", w.objects.Bucket()),
attribute.String("job.id", claim.JobID),
))
src, err := w.download(downloadCtx, assignment)
if err != nil {
downloadSpan.RecordError(err)
downloadSpan.SetStatus(codes.Error, "staging download failed")
}
downloadSpan.End()
if err != nil {
w.finishWithError(ctx, delivery, claim, started, err, leaseLost.Load())
return
}
renderCtx, renderSpan := w.tracer.Start(workCtx, "image.render",
trace.WithAttributes(
attribute.Int("job.pipeline_version", claim.PipelineVersion),
attribute.Int64("image.bytes", int64(len(src))),
))
variants, err := pipeline.Render(renderCtx, src, claim.PipelineVersion)
if err != nil {
renderSpan.RecordError(err)
renderSpan.SetStatus(codes.Error, "image render failed")
}
renderSpan.End()
if err != nil {
w.finishWithError(ctx, delivery, claim, started, err, leaseLost.Load())
return
}
w.injectFault(ctx, "crash_before_side_effect", assignment.AttachmentID)
records, err := w.uploadEffects(workCtx, assignment, src, variants)
if err != nil {
w.finishWithError(ctx, delivery, claim, started, err, leaseLost.Load())
return
}
w.injectFault(ctx, "crash_after_side_effect", assignment.AttachmentID)
commitCtx, commitSpan := w.tracer.Start(workCtx, "job.complete",
trace.WithSpanKind(trace.SpanKindClient),
trace.WithAttributes(
attribute.Int("job.pipeline_version", claim.PipelineVersion),
attribute.Int("job.attempt", claim.Attempts),
))
result, err := w.store.CompleteJobReady(commitCtx, store.ReadyCompletion{
JobID: claim.JobID,
AttachmentID: claim.AttachmentID,
PipelineVersion: claim.PipelineVersion,
Owner: w.consumer,
Variants: records,
Now: time.Now().UTC(),
})
if err != nil {
commitSpan.RecordError(err)
commitSpan.SetStatus(codes.Error, "ready commit failed")
}
commitSpan.End()
if err != nil {
if errors.Is(err, store.ErrLeaseLost) || errors.Is(err, store.ErrJobTerminal) {
w.log.Log(ctx, slog.LevelInfo, "job completion skipped after lease/terminal race; acknowledging",
"job_id", claim.JobID, "error", err)
w.ack(ctx, delivery.ID)
return
}
// The effects are already in S3 and are deterministic, so a later
// redelivery repeats the same objects. The entry stays unacknowledged.
w.log.Log(ctx, slog.LevelError, "could not commit ready job; leaving delivery pending",
"job_id", claim.JobID, "error", err)
return
}
w.cleanupStagingIfSafe(ctx, claim.AttachmentID)
w.injectFault(ctx, "crash_after_commit_before_ack", assignment.AttachmentID)
if err := w.ack(ctx, delivery.ID); err != nil {
w.log.Log(ctx, slog.LevelWarn, "ack failed after committed result; redelivery will be a no-op",
"job_id", claim.JobID, "stream_id", delivery.ID, "error", err)
return
}
w.metrics.JobProcessed(ctx, job.Type, "success", time.Since(started))
w.metrics.JobReady(ctx, job.Type, time.Since(assignment.JobCreatedAt))
span := trace.SpanFromContext(ctx)
span.SetAttributes(
attribute.String("job.outcome", "success"),
attribute.Int("job.variants", len(records)),
attribute.Bool("job.stale_result", result.Stale),
attribute.Int("job.ready_version", result.ReadyVersion),
)
w.log.Log(ctx, slog.LevelInfo, "attachment processed",
"job_id", claim.JobID, "attachment_id", claim.AttachmentID,
"pipeline_version", claim.PipelineVersion, "attempt", claim.Attempts,
"variants", len(records), "stale_result", result.Stale,
"ready_version", result.ReadyVersion)
}
// verifyAndAck implements the contract rule for a repeated delivery of an
// already ready job: verify the complete effect and acknowledge without doing
// work. It never creates a second variant or changes the ready version.
func (w *Worker) verifyAndAck(ctx context.Context, deliveryID string, assignment store.Assignment) {
if assignment.AttachmentStatus != "ready" {
w.log.Log(ctx, slog.LevelWarn, "ready job without a ready attachment; acknowledging for operator review",
"job_id", assignment.JobID)
w.ack(ctx, deliveryID)
return
}
records, err := w.store.VariantRecords(ctx, assignment.AttachmentID, assignment.PipelineVersion)
if err != nil {
w.log.Log(ctx, slog.LevelWarn, "could not verify ready effects; leaving delivery pending",
"job_id", assignment.JobID, "error", err)
return
}
ok := len(records) == 3
if ok {
if _, statErr := w.objects.Stat(ctx, assignment.ObjectKey); statErr != nil {
ok = false
}
for _, record := range records {
if !ok {
break
}
info, statErr := w.objects.Stat(ctx, record.ObjectKey)
if statErr != nil || info.Size != record.SizeBytes {
ok = false
}
}
}
if !ok {
// Do not loop forever on a data-loss anomaly. The job stays ready in
// PostgreSQL and the API refuses to serve a missing object, so the
// incident is visible and operator-owned rather than hidden by a
// silently acked fake success.
w.log.Log(ctx, slog.LevelError, "ready job effect is incomplete; acknowledging for operator review",
"job_id", assignment.JobID, "attachment_id", assignment.AttachmentID,
"variants", len(records))
w.ack(ctx, deliveryID)
return
}
w.log.Log(ctx, slog.LevelInfo, "duplicate delivery of ready job verified as no-op",
"job_id", assignment.JobID, "attachment_id", assignment.AttachmentID,
"variants", len(records))
w.ack(ctx, deliveryID)
}
func (w *Worker) finishWithError(ctx context.Context, delivery broker.Message, claim store.Claim, started time.Time, err error, leaseLost bool) {
if leaseLost || errors.Is(err, store.ErrLeaseLost) {
w.log.Log(ctx, slog.LevelInfo, "processing stopped after lease loss; acknowledging stale delivery",
"job_id", claim.JobID, "error", err)
w.ack(ctx, delivery.ID)
return
}
if ctx.Err() != nil {
// Worker shutdown: leave the entry pending so the next process resumes.
w.log.Log(ctx, slog.LevelInfo, "processing interrupted by shutdown; leaving delivery pending",
"job_id", claim.JobID, "error", err)
return
}
code, permanent := classify(err)
now := time.Now().UTC()
if permanent || claim.Attempts >= claim.MaxAttempts {
finalCode := code
event := "failed_" + code
if !permanent {
finalCode = "retry_exhausted"
event = "retry_exhausted"
}
completeErr := w.store.CompleteJobFailed(ctx, store.FailureCompletion{
JobID: claim.JobID,
AttachmentID: claim.AttachmentID,
PipelineVersion: claim.PipelineVersion,
Owner: w.consumer,
ErrorCode: finalCode,
Event: event,
Now: now,
})
if completeErr != nil {
if errors.Is(completeErr, store.ErrLeaseLost) || errors.Is(completeErr, store.ErrJobTerminal) {
w.ack(ctx, delivery.ID)
return
}
w.log.Log(ctx, slog.LevelError, "could not store permanent failure; leaving delivery pending",
"job_id", claim.JobID, "error", completeErr)
return
}
w.metrics.JobProcessed(ctx, job.Type, "failed", time.Since(started))
span := trace.SpanFromContext(ctx)
span.RecordError(err)
span.SetStatus(codes.Error, finalCode)
span.SetAttributes(attribute.String("job.outcome", "failed"), attribute.String("job.error_code", finalCode))
w.log.Log(ctx, slog.LevelError, "attachment processing failed permanently",
"job_id", claim.JobID, "attachment_id", claim.AttachmentID,
"error_code", finalCode, "permanent", permanent, "attempt", claim.Attempts)
w.ack(ctx, delivery.ID)
return
}
delay := w.retryDelay(claim.Attempts)
nextAttempt := claim.Attempts + 1
traceParent, traceState := telemetry.TraceContext(ctx)
retryErr := w.store.RetryJob(ctx, store.RetryRequest{
JobID: claim.JobID,
AttachmentID: claim.AttachmentID,
PipelineVersion: claim.PipelineVersion,
Owner: w.consumer,
DeliveredAttempt: claim.Attempts,
NextAttempt: nextAttempt,
AvailableAt: now.Add(delay),
ErrorCode: code,
Now: now,
TraceParent: traceParent,
TraceState: traceState,
})
if retryErr != nil {
if errors.Is(retryErr, store.ErrLeaseLost) {
w.ack(ctx, delivery.ID)
return
}
w.log.Log(ctx, slog.LevelError, "could not schedule retry; leaving delivery pending",
"job_id", claim.JobID, "error", retryErr)
return
}
w.metrics.JobProcessed(ctx, job.Type, "retry", time.Since(started))
span := trace.SpanFromContext(ctx)
span.SetAttributes(attribute.String("job.outcome", "retry"), attribute.String("job.error_code", code),
attribute.Int("job.next_attempt", nextAttempt), attribute.Int64("job.retry_delay_ms", delay.Milliseconds()))
w.log.Log(ctx, slog.LevelWarn, "transient processing error scheduled for retry",
"job_id", claim.JobID, "error_code", code, "attempt", claim.Attempts,
"next_attempt", nextAttempt, "delay_ms", delay.Milliseconds())
if err := w.ack(ctx, delivery.ID); err != nil {
w.log.Log(ctx, slog.LevelWarn, "ack failed after retry was durably scheduled; redelivery will be a no-op",
"job_id", claim.JobID, "error", err)
}
}
func classify(err error) (string, bool) {
switch {
case errors.Is(err, pipeline.ErrInvalidImage):
return "invalid_image", true
case errors.Is(err, pipeline.ErrTooLarge):
return "image_too_large", true
case errors.Is(err, pipeline.ErrUnsupportedVersion):
return "unsupported_pipeline_version", true
case errors.Is(err, errStagingCorrupt):
return "staging_corrupt", true
case errors.Is(err, objectstore.ErrNotFound):
// Staging was written before the 202 and is never deleted before a
// successful publication, so a missing staging object is data loss,
// not a transient condition.
return "staging_missing", true
case errors.Is(err, objectstore.ErrUnavailable):
return "storage_unavailable", false
case errors.Is(err, context.DeadlineExceeded):
return "timeout", false
case errors.Is(err, context.Canceled):
return "canceled", false
default:
return "processing_error", false
}
}
func (w *Worker) download(ctx context.Context, assignment store.Assignment) ([]byte, error) {
body, info, err := w.objects.Get(ctx, assignment.StagingKey)
if err != nil {
return nil, err
}
defer body.Close()
limit := assignment.SizeBytes + 1
if limit < 1 {
limit = w.opts.MaxUploadBytes + 1
}
if limit < 1 {
limit = 10*1024*1024 + 1
}
data, err := io.ReadAll(io.LimitReader(body, limit))
if err != nil {
return nil, err
}
if int64(len(data)) != assignment.SizeBytes || (info.Size > 0 && info.Size != assignment.SizeBytes) {
return nil, fmt.Errorf("%w: size mismatch", errStagingCorrupt)
}
sum := sha256.Sum256(data)
if hex.EncodeToString(sum[:]) != assignment.SHA256 {
return nil, fmt.Errorf("%w: sha256 mismatch", errStagingCorrupt)
}
return data, nil
}
func (w *Worker) uploadEffects(ctx context.Context, assignment store.Assignment, original []byte, variants []pipeline.Variant) ([]store.VariantRecord, error) {
if err := w.putObject(ctx, assignment.ObjectKey, bytes.NewReader(original), int64(len(original)), assignment.ContentType, "original"); err != nil {
return nil, err
}
records := make([]store.VariantRecord, 0, len(variants))
for _, variant := range variants {
objectKey := fmt.Sprintf("attachments/%s/v%d/%s", assignment.AttachmentID, assignment.PipelineVersion, variant.Name)
if err := w.putObject(ctx, objectKey, bytes.NewReader(variant.Bytes), int64(len(variant.Bytes)), variant.ContentType, variant.Name); err != nil {
return nil, err
}
records = append(records, store.VariantRecord{
Name: variant.Name,
ContentType: variant.ContentType,
SizeBytes: int64(len(variant.Bytes)),
Width: variant.Width,
Height: variant.Height,
SHA256: variant.SHA256,
ObjectKey: objectKey,
PipelineVersion: assignment.PipelineVersion,
})
}
return records, nil
}
// putObject creates one client span per S3 write. The object key is not
// exported: only its role (original/thumbnail/crop/optimized) and the bucket.
func (w *Worker) putObject(ctx context.Context, key string, body io.Reader, size int64, contentType, role string) error {
putCtx, span := w.tracer.Start(ctx, "s3.put "+role,
trace.WithSpanKind(trace.SpanKindClient),
trace.WithAttributes(
attribute.String("aws.s3.operation", "PutObject"),
attribute.String("aws.s3.bucket", w.objects.Bucket()),
attribute.String("aws.s3.object_role", role),
attribute.Int64("aws.s3.object_size_bytes", size),
))
defer span.End()
if err := w.objects.Put(putCtx, key, body, size, contentType); err != nil {
span.RecordError(err)
span.SetStatus(codes.Error, "S3 put failed")
return err
}
return nil
}
func (w *Worker) retryDelay(attempt int) time.Duration {
if attempt < 1 {
attempt = 1
}
ceiling := w.opts.BackoffBase
for i := 1; i < attempt && ceiling < w.opts.BackoffMax; i++ {
ceiling *= 2
}
if ceiling > w.opts.BackoffMax {
ceiling = w.opts.BackoffMax
}
// Uniform jitter in [50%, 100%] of the exponential ceiling. It de-synchronises
// retries from several workers without collapsing to a tight fixed interval.
factor := 0.5 + rand.Float64()*0.5
delay := time.Duration(float64(ceiling) * factor)
if delay < 250*time.Millisecond {
delay = 250 * time.Millisecond
}
return delay
}
func (w *Worker) ack(ctx context.Context, streamID string) error {
ackCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 3*time.Second)
defer cancel()
if err := w.broker.Ack(ackCtx, streamID); err != nil {
w.log.Log(ctx, slog.LevelWarn, "broker ack failed", "stream_id", streamID, "error", err)
return err
}
return nil
}
// cleanupStagingIfSafe removes the shared staged original only when no job for
// this attachment can still need it. A newer pipeline version completing must
// not delete the bytes of a still-queued older version or of a replayable
// failed job; the janitor applies the documented retention to those cases.
func (w *Worker) cleanupStagingIfSafe(ctx context.Context, attachmentID string) {
checkCtx, cancel := context.WithTimeout(ctx, 3*time.Second)
active, failed, err := w.store.JobCounts(checkCtx, attachmentID)
cancel()
if err != nil {
w.log.Log(ctx, slog.LevelWarn, "could not check staging safety; keeping object", "attachment_id", attachmentID, "error", err)
return
}
if active > 0 || failed > 0 {
w.log.Log(ctx, slog.LevelInfo, "staging retained for a non-ready job", "attachment_id", attachmentID,
"active_jobs", active, "failed_jobs", failed)
return
}
cleanupCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
key := "staging/" + attachmentID
if err := w.objects.Remove(cleanupCtx, key); err != nil {
w.log.Log(ctx, slog.LevelWarn, "staging cleanup failed; janitor will retry", "attachment_id", attachmentID, "error", err)
}
}
func (w *Worker) autoclaimLoop(ctx context.Context) {
w.autoclaim(ctx)
ticker := time.NewTicker(w.opts.ClaimInterval)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
w.autoclaim(ctx)
}
}
}
func (w *Worker) autoclaim(ctx context.Context) {
start := "0-0"
for {
messages, next, err := w.broker.AutoClaim(ctx, w.consumer+":claim", w.opts.ClaimIdle, start, 10)
if err != nil {
if ctx.Err() == nil {
w.log.Log(ctx, slog.LevelWarn, "autoclaim failed", "error", err)
}
return
}
for _, message := range messages {
w.handle(ctx, message)
}
if next == "0-0" || next == start || len(messages) == 0 {
return
}
start = next
}
}
func (w *Worker) recoveryLoop(ctx context.Context) {
w.recover(ctx)
ticker := time.NewTicker(w.opts.RecoveryInterval)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
w.recover(ctx)
}
}
}
func (w *Worker) recover(ctx context.Context) {
count, err := w.store.RecoverExpiredJobs(ctx, 20, time.Now().UTC())
if err != nil {
if ctx.Err() == nil {
w.log.Log(ctx, slog.LevelWarn, "expired-lease recovery failed", "error", err)
}
return
}
if count > 0 {
w.log.Log(ctx, slog.LevelInfo, "recovered expired processing leases", "jobs", count)
}
}
func (w *Worker) janitorLoop(ctx context.Context) {
select {
case <-ctx.Done():
return
case <-time.After(10 * time.Second):
}
w.janitor(ctx)
ticker := time.NewTicker(w.opts.JanitorInterval)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
w.janitor(ctx)
}
}
}
// janitor removes staging objects only when the database says the original was
// safely published (ready/failed) or when no row references it and the object
// is older than the retention grace period. queued/processing rows are never
// cleaned: their bytes are still required input.
func (w *Worker) janitor(ctx context.Context) {
objects, err := w.objects.List(ctx, "staging/")
if err != nil {
if ctx.Err() == nil {
w.log.Log(ctx, slog.LevelWarn, "staging janitor list failed", "error", err)
}
return
}
now := time.Now().UTC()
deleted := 0
for _, object := range objects {
id := strings.TrimPrefix(object.Key, "staging/")
if _, ok := uuid.Normalize(id); !ok {
continue
}
status, exists, err := w.store.StagingDisposition(ctx, id)
if err != nil {
if ctx.Err() == nil {
w.log.Log(ctx, slog.LevelWarn, "staging janitor database check failed", "attachment_id", id, "error", err)
}
continue
}
active, failed := 0, 0
if exists {
active, failed, err = w.store.JobCounts(ctx, id)
if err != nil {
if ctx.Err() == nil {
w.log.Log(ctx, slog.LevelWarn, "staging janitor job check failed", "attachment_id", id, "error", err)
}
continue
}
}
// Policy:
// active job -> keep, bytes are still input;
// failed job -> keep for the replay retention window;
// all jobs ready -> published result is safe, remove now;
// no attachment row -> orphan, remove after the orphan grace;
// attachment failed with no job -> remove after retention.
allReady := exists && active == 0 && failed == 0 && status == "ready"
orphanExpired := !exists && now.Sub(object.LastModified) >= w.opts.StagingRetention
failedExpired := exists && active == 0 && (failed > 0 || status == "failed") &&
now.Sub(object.LastModified) >= w.opts.StagingRetention
safe := allReady
if !safe && !orphanExpired && !failedExpired {
continue
}
removeCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
err = w.objects.Remove(removeCtx, object.Key)
cancel()
if err != nil {
w.log.Log(ctx, slog.LevelWarn, "staging janitor delete failed", "key", object.Key, "error", err)
continue
}
deleted++
reason := "retention_expired"
switch {
case allReady:
reason = "publication_complete"
case orphanExpired:
reason = "orphan_after_retention"
case failedExpired:
reason = "failed_retention_expired"
}
w.log.Log(ctx, slog.LevelInfo, "staging object removed", "attachment_id", id, "reason", reason)
}
if deleted > 0 {
w.log.Log(ctx, slog.LevelInfo, "staging janitor pass complete", "deleted", deleted, "scanned", len(objects))
}
}
// injectTransient implements the bounded-retry fault. transient_once fails only
// the first managed attempt; transient_always fails every attempt so the test
// can prove that the configured attempt budget terminates in failed rather than
// retrying forever.
func (w *Worker) injectTransient(ctx context.Context, claim store.Claim) error {
switch w.opts.FaultInject {
case "transient_once", "transient_always":
default:
return nil
}
if w.opts.FaultTarget != "" && !strings.EqualFold(w.opts.FaultTarget, claim.AttachmentID) {
return nil
}
if w.opts.FaultInject == "transient_once" && claim.Attempts != 1 {
return nil
}
if w.opts.Env != "lab" {
w.log.Log(ctx, slog.LevelError, "refusing transient fault injection outside APP_ENV=lab")
return nil
}
w.log.Log(ctx, slog.LevelWarn, "FAULT INJECTION: synthetic transient storage error",
"stage", w.opts.FaultInject, "attachment_id", claim.AttachmentID, "attempt", claim.Attempts)
return fmt.Errorf("%w: injected transient fault", objectstore.ErrUnavailable)
}
// injectFault implements the track-2 crash injection. It is disabled in any
// environment other than APP_ENV=lab and only triggers for the configured
// scenario and optional attachment id. The abrupt exit is the point: no
// deferred cleanup, no ack, exactly like SIGKILL.
func (w *Worker) injectFault(ctx context.Context, stage, attachmentID string) {
if w.opts.FaultInject != stage {
return
}
if w.opts.FaultTarget != "" && !strings.EqualFold(w.opts.FaultTarget, attachmentID) {
return
}
if w.opts.Env != "lab" {
w.log.Log(ctx, slog.LevelError, "refusing fault injection outside APP_ENV=lab", "stage", stage)
return
}
w.log.Log(ctx, slog.LevelError, "FAULT INJECTION: killing worker process abruptly",
"stage", stage, "attachment_id", attachmentID)
os.Exit(75)
}
+432
View File
@@ -0,0 +1,432 @@
#!/usr/bin/env python3
"""Lab6 attachment contract checks: async accept, limits, MIME, names, ACL,
variants, staging cleanup and dependency faults.
Expectations are derived from contracts/README.md, attachment-states.md and
openapi.json, not from the current implementation:
* POST returns 202 with status=queued only after durable staging + job COMMIT;
* original download is byte-identical, thumbnail/crop/optimized follow the
documented dimensions and content types;
* 10 MiB body limit and 40 MP pixel limit are checked before unbounded work;
* Content-Type is validated against the bytes; corrupt/foreign formats are 415;
* filename is display-only, 1..255 code points, no '/', '\\\\', NUL or controls;
* foreign/unknown metadata and bytes are 404; queued content is 409;
* an unavailable S3 is 503 on upload/download/metadata, while invalid input is
still rejected as a user error (415/400), never masked as 500;
* an interrupted upload leaves neither a metadata row nor a staging object.
Python 3.9+, standard library only. Requires the running stand and Docker.
"""
import hashlib
import os
import socket
import sys
import time
import urllib.parse
import uuid
ROOT = __import__('pathlib').Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tests'))
sys.path.insert(0, str(ROOT / 'scripts'))
from client import Client, Failure, arguments, check # noqa: E402
import lab6_metrics as M # noqa: E402
from image_probe import jpeg_size # noqa: E402
CHECKS = 0
def ok(condition, message):
global CHECKS
CHECKS += 1
check(condition, message)
def upload(c, actor, chat_id, data, filename='test.png', content_type='image/png', status=202):
path = '/api/v1/chats/' + chat_id + '/attachments?filename=' + urllib.parse.quote(filename, safe='')
headers = {'Content-Type': content_type} if content_type else {}
return c.call('POST', path, status, actor=actor, raw=data, headers=headers,
schema='Attachment' if status < 300 else None)
def error_code(response):
return response['json']['error']['code']
def wait_attachment(c, actor, att, wanted='ready', timeout=60):
deadline = time.monotonic() + timeout
current = att
while time.monotonic() < deadline:
current = c.call('GET', '/api/v1/attachments/' + att['id'], actor=actor, schema='Attachment')['json']
check(current['status'] != 'failed',
'attachment failed unexpectedly: %s' % current.get('error_code'))
if current['status'] == wanted:
return current
time.sleep(0.2)
raise Failure('attachment did not reach %s within %s s' % (wanted, timeout))
def webp_size(data):
"""Read WebP canvas dimensions from VP8X / VP8 / VP8L headers."""
check(data[:4] == b'RIFF' and data[8:12] == b'WEBP', 'optimized variant is not RIFF/WEBP')
chunk = data[12:16]
if chunk == b'VP8X':
width = int.from_bytes(data[24:27], 'little') + 1
height = int.from_bytes(data[27:30], 'little') + 1
return width, height
if chunk == b'VP8 ':
start = data.find(b'\x9d\x01\x2a', 20)
check(start >= 0 and start + 7 <= len(data), 'invalid VP8 frame header')
width = int.from_bytes(data[start + 3:start + 5], 'little') & 0x3fff
height = int.from_bytes(data[start + 5:start + 7], 'little') & 0x3fff
return width, height
if chunk == b'VP8L':
check(data[20] == 0x2f, 'invalid VP8L signature')
bits = int.from_bytes(data[21:25], 'little')
width = (bits & 0x3fff) + 1
height = ((bits >> 14) & 0x3fff) + 1
return width, height
raise Failure('unknown WebP chunk %r' % chunk)
def test_async_accept_and_variants(c, alice, bob, chat):
content = M.fixture_bytes('sample.png')
response = upload(c, alice, chat['id'], content, 'sample.png')
att = response['json']
ok(response['status'] == 202, 'lab6 upload must return 202')
ok(att['status'] == 'queued', 'upload snapshot must be queued')
ok(att['variants'] == [] and att['error_code'] is None, 'queued snapshot must have no variants/error')
ok(att['sha256'] == hashlib.sha256(content).hexdigest() and att['size_bytes'] == len(content),
'original checksum/size mismatch in the 202 response')
ready = wait_attachment(c, bob, att, 'ready', 60)
ok(ready['error_code'] is None, 'ready attachment has an error_code')
names = sorted(item['name'] for item in ready['variants'])
ok(names == ['crop', 'optimized', 'thumbnail'], 'ready variants are not exactly the three contract names')
by_name = {item['name']: item for item in ready['variants']}
thumbnail = by_name['thumbnail']
ok((thumbnail['width'], thumbnail['height']) == (256, 160),
'thumbnail metadata is %dx%d, want 256x160' % (thumbnail['width'], thumbnail['height']))
thumb = c.call('GET', '/api/v1/attachments/' + att['id'] + '/content?variant=thumbnail', actor=bob)
ok(thumb['headers'].get_content_type() == 'image/jpeg', 'thumbnail content type is not JPEG')
ok(len(thumb['bytes']) == thumbnail['size_bytes'] and
hashlib.sha256(thumb['bytes']).hexdigest() == thumbnail['sha256'],
'thumbnail bytes do not match metadata')
ok(jpeg_size(thumb['bytes']) == (256, 160), 'actual thumbnail JPEG is not 256x160')
crop = by_name['crop']
ok((crop['width'], crop['height']) == (128, 128), 'crop metadata is not 128x128')
crop_bytes = c.call('GET', '/api/v1/attachments/' + att['id'] + '/content?variant=crop', actor=bob)
ok(crop_bytes['headers'].get_content_type() == 'image/jpeg', 'crop content type is not JPEG')
ok(jpeg_size(crop_bytes['bytes']) == (128, 128), 'actual crop JPEG is not 128x128')
optimized = by_name['optimized']
ok(optimized['content_type'] == 'image/webp', 'optimized content type is not WebP')
webp = c.call('GET', '/api/v1/attachments/' + att['id'] + '/content?variant=optimized', actor=bob)
ok(webp['headers'].get_content_type() == 'image/webp', 'optimized download content type mismatch')
ok(len(webp['bytes']) == optimized['size_bytes'] and
hashlib.sha256(webp['bytes']).hexdigest() == optimized['sha256'],
'optimized bytes do not match metadata')
ok(webp_size(webp['bytes']) == (320, 200), 'optimized WebP is not fitted without upscaling')
original = c.call('GET', '/api/v1/attachments/' + att['id'] + '/content', actor=bob)
ok(original['bytes'] == content and original['headers'].get_content_type() == 'image/png',
'original download differs from the uploaded bytes')
# The staging object is removed after the ready COMMIT. The janitor also
# covers a failed immediate delete; give it a short moment here.
time.sleep(0.5)
staging = [item for item in M.s3_list('staging/') if att['id'] in item.get('key', '')]
ok(staging == [], 'staging object survived a successful publication')
# A message may be attachment-only even while the attachment is only queued,
# because linking a durable reference is legal from lab6.
second = upload(c, alice, chat['id'], content, 'second.png')['json']
message = c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 201, actor=alice,
body={'text': '', 'attachment_ids': [second['id'], att['id']]},
headers={'Idempotency-Key': uuid.uuid4().hex}, schema='Message')['json']
ok(message['text'] == '' and message['attachment_ids'] == [second['id'], att['id']],
'attachment-only message lost text or order')
ok(any(item == message for item in all_messages(c, bob, chat)),
'member cannot read a message with attachments')
print('PASS async accept, ready variants and staging cleanup')
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
check(page['next_cursor'] not in seen, 'message cursor cycle')
seen.add(page['next_cursor'])
path = ('/api/v1/chats/' + chat['id'] + '/messages?limit=' + str(limit) +
'&cursor=' + urllib.parse.quote(page['next_cursor'], safe=''))
raise Failure('message pagination exceeded safety bound')
def test_size_limits(c, alice, chat):
# 10 MiB + 1 byte: the declared Content-Length is enough for the handler to
# return 413 before it accepts or decodes the content.
oversized = os.urandom(10485761)
response = upload(c, alice, chat['id'], oversized, 'too-big.png', status=413)
ok(error_code(response) == 'payload_too_large', 'declared body over 10 MiB is not 413')
# A real, valid PNG just under the 10 MiB boundary is accepted and stored
# byte-for-byte.
boundary = M.png_random(1600, 2167)
ok(10485760 - len(boundary) < 100000, 'boundary fixture is not near 10 MiB: %d' % len(boundary))
att = upload(c, alice, chat['id'], boundary, 'boundary.png')['json']
ok(att['size_bytes'] == len(boundary), 'near-limit size changed')
ok(att['sha256'] == hashlib.sha256(boundary).hexdigest(), 'near-limit checksum changed')
ready = wait_attachment(c, alice, att, 'ready', 60)
ok(any(item['name'] == 'thumbnail' for item in ready['variants']), 'boundary attachment has no thumbnail')
download = c.call('GET', '/api/v1/attachments/' + att['id'] + '/content', actor=alice)
ok(download['bytes'] == boundary, 'near-limit download differs')
empty = c.call('POST', '/api/v1/chats/' + chat['id'] + '/attachments?filename=empty.png', 415,
actor=alice, raw=b'', headers={'Content-Type': 'image/png'})
ok(error_code(empty) == 'unsupported_media_type', 'empty body is not 415')
# More than 40 million decoded pixels, but a small compressed file: the
# limit must come from the decoded header, not from the byte size.
huge_pixels = M.png_solid(8000, 5001)
ok(len(huge_pixels) < 10485760, 'pixel-limit fixture unexpectedly large')
response = upload(c, alice, chat['id'], huge_pixels, 'pixels.png', status=413)
ok(error_code(response) == 'payload_too_large', '>40 MP is not 413')
before = len(M.s3_list('attachments/'))
time.sleep(0.5)
ok(len(M.s3_list('attachments/')) == before, '>40 MP upload left a final object in S3')
print('PASS size and pixel limits')
def test_mime_and_damage(c, alice, chat):
png = M.fixture_bytes('sample.png')
jpeg = (ROOT / 'student-tests/fixtures/sample.jpg').read_bytes()
response = upload(c, alice, chat['id'], png, 'wrong.jpg', 'image/jpeg', status=415)
ok(error_code(response) == 'unsupported_media_type', 'PNG declared as JPEG is not 415')
response = upload(c, alice, chat['id'], jpeg, 'wrong.png', 'image/png', status=415)
ok(error_code(response) == 'unsupported_media_type', 'JPEG declared as PNG is not 415')
response = upload(c, alice, chat['id'], b'not an image at all\n' * 20, 'text.png', 'image/png', status=415)
ok(error_code(response) == 'unsupported_media_type', 'non-image bytes are not 415')
response = upload(c, alice, chat['id'], png[:200], 'truncated.png', 'image/png', status=415)
ok(error_code(response) == 'unsupported_media_type', 'truncated PNG is not 415')
response = upload(c, alice, chat['id'], M.png_corrupt(), 'corrupt.png', 'image/png', status=415)
ok(error_code(response) == 'unsupported_media_type', 'corrupt PNG is not 415')
response = upload(c, alice, chat['id'], png, 'none.png', '', status=415)
ok(error_code(response) == 'unsupported_media_type', 'missing Content-Type is not 415')
response = upload(c, alice, chat['id'], png, 'plain.png', 'text/plain', status=415)
ok(error_code(response) == 'unsupported_media_type', 'text/plain is not 415')
response = upload(c, alice, chat['id'], png, 'multi.png', 'multipart/form-data; boundary=x', status=415)
ok(error_code(response) == 'unsupported_media_type', 'multipart is not 415')
att = upload(c, alice, chat['id'], jpeg, 'real.jpg', 'image/jpeg')['json']
ok(att['content_type'] == 'image/jpeg' and att['sha256'] == hashlib.sha256(jpeg).hexdigest(),
'JPEG upload metadata mismatch')
wait_attachment(c, alice, att, 'ready', 60)
download = c.call('GET', '/api/v1/attachments/' + att['id'] + '/content', actor=alice)
ok(download['bytes'] == jpeg and download['headers'].get_content_type() == 'image/jpeg',
'JPEG download mismatch')
# The display name is returned verbatim but never used as a key/path, and
# the public JSON never exposes storage internals.
unicode_name = 'фото 🚀.png'
named = upload(c, alice, chat['id'], png, unicode_name)['json']
ok(named['filename'] == unicode_name, 'Unicode filename changed')
ok('object_key' not in named and 'bucket' not in named, 'attachment JSON leaks storage internals')
print('PASS MIME, damage and filename display')
def test_filenames(c, alice, chat):
png = M.fixture_bytes('sample.png')
base = '/api/v1/chats/' + chat['id'] + '/attachments'
def expect(query, status):
c.call('POST', base + query, status, actor=alice, raw=png,
headers={'Content-Type': 'image/png'})
expect('', 400) # required parameter
expect('?filename=', 400) # empty
expect('?filename=a.png&filename=b.png', 400) # exactly once
expect('?filename=' + urllib.parse.quote('../evil.png', safe=''), 400)
expect('?filename=' + urllib.parse.quote('..\\evil.png', safe=''), 400)
expect('?filename=' + urllib.parse.quote('bad\x00name.png', safe=''), 400)
expect('?filename=' + urllib.parse.quote('bad\x01name.png', safe=''), 400)
expect('?filename=' + 'a' * 256, 400)
expect('?filename=' + urllib.parse.quote('a' * 255, safe=''), 202)
expect('?filename=' + urllib.parse.quote('./x.png', safe=''), 400)
print('PASS filename validation')
def test_acl(c, alice, bob, eve, chat):
att, content = c.attachment(alice, chat)
wait_attachment(c, alice, att, 'ready', 60)
for suffix in ('', '/content'):
c.call('GET', '/api/v1/attachments/' + att['id'] + suffix, 404, actor=eve)
c.call('GET', '/api/v1/attachments/' + att['id'], 200, actor=bob)
c.call('GET', '/api/v1/attachments/' + att['id'] + '/content', 200, actor=bob)
png = M.fixture_bytes('sample.png')
response = upload(c, eve, chat['id'], png, 'outsider.png', status=404)
ok(error_code(response) == 'not_found', 'outsider upload is not hidden as 404')
c.call('POST', '/api/v1/chats/not-a-uuid/attachments?filename=x.png', 400, actor=alice,
raw=png, headers={'Content-Type': 'image/png'})
c.call('POST', '/api/v1/chats/' + str(uuid.uuid4()) + '/attachments?filename=x.png', 404,
actor=alice, raw=png, headers={'Content-Type': 'image/png'})
eve_chat = c.call('POST', '/api/v1/chats', 201, actor=eve,
body={'title': 'Чужой чат', 'member_ids': [eve['id']]}, schema='Chat')['json']
foreign, _ = c.attachment(eve, eve_chat)
response = c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 404, actor=alice,
body={'text': 'чужое', 'attachment_ids': [foreign['id']]},
headers={'Idempotency-Key': uuid.uuid4().hex})
ok(error_code(response) == 'not_found', 'foreign attachment link is not 404')
c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 404, actor=alice,
body={'text': 'нет', 'attachment_ids': [str(uuid.uuid4())]},
headers={'Idempotency-Key': uuid.uuid4().hex})
print('PASS attachment ACL')
def test_interrupted_upload(c, alice, chat):
before_rows = int(M.psql("SELECT count(*) FROM attachments"))
before_objects = len(M.s3_list('attachments/')) + len(M.s3_list('staging/'))
head = (
'POST /api/v1/chats/' + chat['id'] + '/attachments?filename=aborted.png HTTP/1.1\r\n'
'Host: 127.0.0.1\r\n'
'Authorization: Bearer ' + alice['token'] + '\r\n'
'Content-Type: image/png\r\n'
'Content-Length: 4194304\r\n'
'Connection: close\r\n\r\n'
).encode('ascii')
# Send only a prefix of the declared body and close: the server must abort
# the upload before staging or metadata is created.
parsed = urllib.parse.urlsplit(c.base)
connection = socket.create_connection((parsed.hostname, parsed.port or 80), timeout=5)
try:
connection.sendall(head)
connection.sendall(M.fixture_bytes()[:100000])
finally:
connection.close()
time.sleep(1.0)
after_rows = int(M.psql("SELECT count(*) FROM attachments"))
after_objects = len(M.s3_list('attachments/')) + len(M.s3_list('staging/'))
ok(after_rows == before_rows, 'interrupted upload left an attachment row')
ok(after_objects == before_objects, 'interrupted upload left an S3 object')
print('PASS interrupted upload leaves no row/object')
def test_s3_unavailable(c, alice, bob, chat):
att, content = c.attachment(alice, chat)
wait_attachment(c, alice, att, 'ready', 60)
try:
M.compose('stop', 's3')
time.sleep(1.0)
png = M.fixture_bytes('sample.png')
response = upload(c, alice, chat['id'], png, 'outage.png', status=503)
ok(error_code(response) == 'unavailable', 'S3 outage upload is not the contract 503')
response = c.call('GET', '/api/v1/attachments/' + att['id'], 503, actor=bob)
ok(error_code(response) == 'unavailable', 'S3 outage metadata is not 503')
response = c.call('GET', '/api/v1/attachments/' + att['id'] + '/content', 503, actor=bob)
ok(error_code(response) == 'unavailable', 'S3 outage download is not 503')
# Invalid input is still a user error, not a fake 500/503: validation
# runs before any S3 access.
response = upload(c, alice, chat['id'], b'broken image', 'broken.png', status=415)
ok(error_code(response) == 'unsupported_media_type', 'bad image masked as dependency error')
# The message path does not depend on S3 and must keep working.
c.message(alice, chat, 'сообщение при недоступном S3')
finally:
M.compose('start', 's3')
M.wait_healthy('s3', 60)
deadline = time.monotonic() + 30
while True:
try:
recovered = upload(c, alice, chat['id'], M.fixture_bytes('sample.png'), 'recovered.png')['json']
wait_attachment(c, alice, recovered, 'ready', 60)
break
except Failure:
if time.monotonic() >= deadline:
raise
time.sleep(0.5)
ok(c.call('GET', '/api/v1/attachments/' + att['id'] + '/content', actor=bob)['bytes'] == content,
'existing attachment changed after S3 restart')
print('PASS unavailable S3 is 503, not 500, and recovers')
def test_database_unavailable(c, alice, chat):
try:
M.compose('stop', 'postgres')
deadline = time.monotonic() + 30
while time.monotonic() < deadline:
try:
c.call('GET', '/health/ready', 503)
break
except Failure:
time.sleep(0.5)
else:
raise Failure('readiness did not become 503 while PostgreSQL was stopped')
live = c.call('GET', '/health/live', schema='Health')
ok(live['status'] == 200, 'liveness failed while PostgreSQL was down')
response = c.call('GET', '/api/v1/users/me', 503, actor=alice)
ok(error_code(response) == 'unavailable', 'DB outage /users/me is not 503')
response = c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 503, actor=alice,
body={'text': 'пока БД лежит'}, headers={'Idempotency-Key': uuid.uuid4().hex})
ok(error_code(response) == 'unavailable', 'DB outage message is not 503')
# Authentication shape is checked before the database: a malformed
# bearer header is still a user-level 401, not a masked 500/503.
c.call('GET', '/api/v1/users/me', 401, headers={'Authorization': 'Bearer short'})
finally:
M.compose('start', 'postgres')
M.wait_ready(120)
c.message(alice, chat, 'после восстановления БД')
print('PASS unavailable PostgreSQL is 503, liveness stays up, data recovers')
def test_log_privacy(c, alice, chat):
sentinel = 'SENTINEL-' + uuid.uuid4().hex
c.message(alice, chat, sentinel)
password = alice['registration']['password']
token = alice['token']
api = M.compose_ids('api')
ok(len(api) >= 2, 'need at least two API containers to inspect both logs')
secret = M.env_value(api[0], 'S3_SECRET_KEY')
admin = M.env_value(api[0], 'S3_ADMIN_SECRET_KEY')
logs = M.compose('logs', '--no-color', 'api').stdout
ok(token not in logs, 'session token leaked into API logs')
ok(password not in logs, 'password leaked into API logs')
ok(sentinel not in logs, 'message text leaked into API logs')
ok(secret and secret not in logs, 'S3 API secret leaked into API logs')
ok(not admin, 'administrative S3 secret is present in the API container')
worker_logs = M.compose('logs', '--no-color', 'worker').stdout
ok(token not in worker_logs and sentinel not in worker_logs,
'session token or message text leaked into worker logs')
worker_admin = M.env_value(M.compose_ids('worker')[0], 'S3_ADMIN_SECRET_KEY')
ok(not worker_admin, 'administrative S3 secret is present in the worker container')
print('PASS no token/password/message/S3 secret in API or worker logs')
def main():
args = arguments('Lab6 attachment async/limits/ACL/variants checks; creates synthetic data')
c = Client(args.base_url, args.ca_file)
alice, bob, eve, chat = c.bootstrap()
test_async_accept_and_variants(c, alice, bob, chat)
test_size_limits(c, alice, chat)
test_mime_and_damage(c, alice, chat)
test_filenames(c, alice, chat)
test_acl(c, alice, bob, eve, chat)
test_interrupted_upload(c, alice, chat)
test_s3_unavailable(c, alice, bob, chat)
test_database_unavailable(c, alice, chat)
test_log_privacy(c, alice, chat)
print('PASS: lab6 attachment checks, %d assertions' % CHECKS)
if __name__ == '__main__':
try:
main()
except (Failure, ValueError, OSError) as exc:
print('FAIL:', str(exc))
raise SystemExit(1)
+656
View File
@@ -0,0 +1,656 @@
#!/usr/bin/env python3
"""Own black-box tests for lab6. They complement, and never weaken, tests/smoke.py.
The suite assumes a running stack (make up) and creates only synthetic data.
It keeps the lab3 regression surface — exact JSON keys, strict input
validation, Bearer-only business API, membership hiding as 404, keyset
pagination, concurrent registration/messages/idempotency — and adds the lab6
attachment regression: message attachment_ids, attachment-only messages and
idempotency over the attachment payload. Deep upload limits and ACL negatives
live in student-tests/attachment-checks.py.
Python 3.9+, standard library only.
"""
import base64
import concurrent.futures
import datetime as dt
import json
import sys
import threading
import uuid
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tests'))
from client import Client, arguments, check, timestamp # noqa: E402
CHECKS = 0
def ok(condition, message):
global CHECKS
CHECKS += 1
check(condition, message)
def expect_keys(payload, expected, where):
ok(set(payload) == set(expected), where + ': JSON keys differ: ' + repr(sorted(payload)))
def basic(username, password):
return 'Basic ' + base64.b64encode((username + ':' + password).encode('utf-8')).decode('ascii')
def register(c, username=None, display_name=None, password=None):
username = username or 'bb_' + uuid.uuid4().hex[:12]
password = password or 'B3st-' + uuid.uuid4().hex
display_name = display_name or 'Тестовый пользователь'
body = {'username': username, 'display_name': display_name, 'password': password}
user = c.call('POST', '/api/v1/users', 201, body=body, schema='User')['json']
expect_keys(user, {'id', 'username', 'display_name', 'created_at'}, 'User')
return {'id': user['id'], 'user': user, 'registration': body, 'password': password}
def login(c, actor):
response = c.call('POST', '/api/v1/auth/sessions', 201,
headers={'Authorization': basic(actor['registration']['username'], actor['password'])},
schema='Session')['json']
expect_keys(response, {'token', 'token_type', 'expires_at', 'user'}, 'Session')
actor['token'] = response['token']
actor['session'] = response
return actor
def new_chat(c, actor, title, member_ids):
return c.call('POST', '/api/v1/chats', 201, actor=actor,
body={'title': title, 'member_ids': member_ids}, schema='Chat')['json']
def key():
return uuid.uuid4().hex
def send_with_key(c, actor, chat, text, idem, headers=None):
merged = {'Idempotency-Key': idem}
merged.update(headers or {})
return c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 201, actor=actor,
body={'text': text}, headers=merged, schema='Message')['json']
def send(c, actor, chat, text, headers=None):
return send_with_key(c, actor, chat, text, key(), headers)
def all_messages(c, actor, chat, limit=100):
path = '/api/v1/chats/' + chat['id'] + '/messages?limit=' + str(limit)
items, seen = [], set()
for _ in range(1000):
page = c.call('GET', path, actor=actor, schema='MessagePage')['json']
items.extend(page['items'])
if page['next_cursor'] is None:
return items
ok(page['next_cursor'] not in seen, 'message cursor cycle')
seen.add(page['next_cursor'])
from urllib.parse import quote
path = ('/api/v1/chats/' + chat['id'] + '/messages?limit=' + str(limit) +
'&cursor=' + quote(page['next_cursor'], safe=''))
raise AssertionError('message pagination exceeded safety bound')
def sorted_messages(items):
return sorted(items, key=lambda x: (timestamp(x['created_at']), uuid.UUID(x['id']).int))
def test_health(c):
live = c.call('GET', '/health/live', schema='Health')
ok(live['json'] == {'status': 'ok'}, 'liveness body')
ok(bool(live['headers'].get('X-Request-Id')), 'liveness X-Request-Id')
ok(bool(live['headers'].get('X-Instance-Id')), 'liveness X-Instance-Id')
ready = c.call('GET', '/health/ready', schema='Health')
ok(ready['json'] == {'status': 'ok'}, 'readiness body')
print('PASS health')
def test_registration_and_login(c):
alice = register(c)
bob = register(c)
login(c, alice)
login(c, bob)
ok(len(alice['session']['token']) >= 32, 'session token shorter than contract minimum')
ok(alice['session']['token_type'] == 'Bearer', 'token_type')
ok(timestamp(alice['session']['expires_at']) > dt.datetime.now(dt.timezone.utc), 'expiry in the past')
ok(alice['session']['user'] == alice['user'], 'session user differs from created user')
# Duplicate username, including a different display name/password.
c.call('POST', '/api/v1/users', 409, body={
'username': alice['registration']['username'],
'display_name': 'Другой',
'password': 'Another-password-123',
})
# Wrong / unknown / malformed credentials all give the same Basic 401.
c.call('POST', '/api/v1/auth/sessions', 401, headers={'Authorization': basic(alice['registration']['username'], 'wrong-password-123')})
c.call('POST', '/api/v1/auth/sessions', 401, headers={'Authorization': basic('definitely_unknown', 'wrong-password-123')})
c.call('POST', '/api/v1/auth/sessions', 401, headers={'Authorization': 'Basic !!!!'})
c.call('POST', '/api/v1/auth/sessions', 401, headers={'Authorization': 'Basic ' + base64.b64encode(b'no-colon').decode()})
c.call('POST', '/api/v1/auth/sessions', 401, headers={'Authorization': 'Bearer abcdefghijklmnopqrstuvwxyz'})
# Basic is not accepted on business endpoints; X-User-Id grants nothing.
c.call('GET', '/api/v1/users/me', 401, headers={'Authorization': basic(alice['registration']['username'], alice['password'])})
c.call('GET', '/api/v1/users/me', 401, headers={'X-User-Id': alice['id']})
c.call('GET', '/api/v1/users/me', 401, headers={'Authorization': 'Bearer ' + 'a' * 43})
c.call('GET', '/api/v1/users/me', 401, headers={'Authorization': 'X-User-Id ' + alice['id']})
me = c.call('GET', '/api/v1/users/me', actor=alice, headers={'X-User-Id': bob['id']}, schema='User')['json']
ok(me['id'] == alice['id'], 'X-User-Id overrode the bearer identity')
# A UTF-8 password containing colons is valid and is not truncated at the
# first colon by Basic parsing.
unicode_password = 'pässwörd:with:12'
unicode_user = register(c, password=unicode_password)
login(c, unicode_user)
ok(unicode_user['session']['user']['username'] == unicode_user['registration']['username'], 'unicode password login')
# Session JSON must never contain the password or its hash.
serialized = json.dumps(alice['session'], ensure_ascii=False)
for forbidden in ('password', 'argon2', 'salt'):
ok(forbidden not in serialized, 'session leaks ' + forbidden)
print('PASS registration/auth')
def test_registration_validation(c):
username = 'bb_' + uuid.uuid4().hex[:10]
password = 'B3st-' + uuid.uuid4().hex
valid = {'username': username, 'display_name': 'Имя', 'password': password}
def bad(body, status=400, raw=None, headers=None):
c.call('POST', '/api/v1/users', status, body=body if raw is None else None, raw=raw,
headers=headers)
bad({'username': username, 'display_name': 'Имя'})
bad({'username': username, 'display_name': 'Имя', 'password': 'short'})
bad({'username': username, 'display_name': 'Имя', 'password': 'p' * 129})
bad({'username': username, 'display_name': 'Имя', 'password': ' ' * 12})
bad({'username': 'ab', 'display_name': 'Имя', 'password': password})
bad({'username': 'a' * 33, 'display_name': 'Имя', 'password': password})
bad({'username': 'UPPER', 'display_name': 'Имя', 'password': password})
bad({'username': 'bad-name', 'display_name': 'Имя', 'password': password})
bad({'username': 'бвт', 'display_name': 'Имя', 'password': password})
bad({'username': username, 'display_name': '', 'password': password})
bad({'username': username, 'display_name': ' ', 'password': password})
bad({'username': username, 'display_name': 'Имя', 'password': password, 'extra': 1})
bad({'username': username, 'display_name': 'Имя', 'password': password, 'Password': 'x'})
bad({'Username': username, 'display_name': 'Имя', 'password': password})
bad({'username': username, 'display_name': 'Имя', 'password': 123456789012})
bad({'username': None, 'display_name': 'Имя', 'password': password})
bad({}, raw=b'{', headers={'Content-Type': 'application/json'})
bad({}, raw=b'[]', headers={'Content-Type': 'application/json'})
bad({}, status=415, raw=json.dumps(valid).encode(), headers={'Content-Type': 'text/plain'})
bad({}, raw=(json.dumps(valid)[:-1] + ', "username": "x"}').encode(), headers={'Content-Type': 'application/json'})
# Exact code-point boundaries.
long_name = register(c, display_name='😀' * 100)
ok(long_name['user']['display_name'] == '😀' * 100, '100 code points display_name changed')
c.call('POST', '/api/v1/users', 400, body={
'username': 'bb_' + uuid.uuid4().hex[:10],
'display_name': '😀' * 101,
'password': password,
})
c.call('POST', '/api/v1/users', 400, body={
'username': 'a' * 32 + 'b',
'display_name': 'Имя', 'password': password,
})
register(c, username='a' * 24 + uuid.uuid4().hex[:8])
print('PASS registration validation')
def test_chats(c, alice, bob, eve):
chat = new_chat(c, alice, 'Комната с Unicode 🚀', [alice['id'], bob['id']])
ok(set(chat['member_ids']) == {alice['id'], bob['id']}, 'chat member set')
expect_keys(chat, {'id', 'title', 'member_ids', 'created_at'}, 'Chat')
def bad(body, status=400):
c.call('POST', '/api/v1/chats', status, actor=alice, body=body)
bad({'title': 'Без автора', 'member_ids': [bob['id']]})
bad({'title': 'Дубликат', 'member_ids': [alice['id'], alice['id']]})
bad({'title': 'Неизвестный', 'member_ids': [alice['id'], str(uuid.uuid4())]})
bad({'title': 'Не UUID', 'member_ids': [alice['id'], 'not-a-uuid']})
bad({'title': 'Слишком много', 'member_ids': [alice['id']] + [str(uuid.uuid4()) for _ in range(100)]})
bad({'title': '', 'member_ids': [alice['id']]})
bad({'title': ' ', 'member_ids': [alice['id']]})
bad({'title': 'я' * 101, 'member_ids': [alice['id']]})
bad({'title': 'Лишнее', 'member_ids': [alice['id']], 'extra': True})
bad({'title': 'Нет списка'})
own = c.call('GET', '/api/v1/chats/' + chat['id'], actor=bob, schema='Chat')['json']
ok(own['id'] == chat['id'], 'member cannot read chat')
c.call('GET', '/api/v1/chats/' + chat['id'], 404, actor=eve)
c.call('GET', '/api/v1/chats/' + str(uuid.uuid4()), 404, actor=alice)
c.call('GET', '/api/v1/chats/not-a-uuid', 400, actor=alice)
c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 404, actor=eve,
body={'text': 'чужое'}, headers={'Idempotency-Key': key()})
hidden = c.call('GET', '/api/v1/chats?limit=100', actor=eve, schema='ChatPage')['json']
ok(all(item['id'] != chat['id'] for item in hidden['items']), 'foreign chat leaked into list')
listed = c.call('GET', '/api/v1/chats?limit=100', actor=bob, schema='ChatPage')['json']
ok(any(item['id'] == chat['id'] for item in listed['items']), 'member chat missing from list')
print('PASS chats/membership')
def test_messages(c, alice, bob, eve, chat):
text = 'Привет 👋 e\u0301 中文'
message = send(c, alice, chat, text)
expect_keys(message, {'id', 'chat_id', 'sender_id', 'text', 'created_at', 'attachment_ids'}, 'Message')
ok(message['attachment_ids'] == [], 'attachment_ids must default to an empty array')
ok(message['text'] == text, 'message text changed')
ok(message['sender_id'] == alice['id'] and message['chat_id'] == chat['id'], 'message identity')
# X-User-Id cannot substitute for the Bearer owner.
spoofed = send(c, alice, chat, 'не от Боба', headers={'X-User-Id': bob['id']})
ok(spoofed['sender_id'] == alice['id'], 'X-User-Id changed the message sender')
def bad(actor, body, status=400, raw=None, headers=None):
merged = {'Idempotency-Key': key()}
merged.update(headers or {})
c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', status, actor=actor,
body=body, raw=raw, headers=merged)
bad(alice, {'text': ''})
bad(alice, {'text': ' '})
bad(alice, {'text': None})
bad(alice, {})
bad(alice, {'text': 'x' * 4001})
bad(alice, {'text': 'ok', 'sender_id': alice['id']})
bad(alice, {'text': 'ok', 'attachment_ids': None})
bad(alice, {'text': 'ok', 'attachment_ids': 'not-an-array'})
bad(alice, {'text': 'ok', 'attachment_ids': ['not-a-uuid']})
bad(alice, {'text': 'ok', 'attachment_ids': [str(uuid.uuid4()), str(uuid.uuid4())] * 6})
bad(alice, {'Text': 'ok'})
c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 400, actor=alice,
raw=b'{', headers={'Content-Type': 'application/json', 'Idempotency-Key': key()})
# Resource access is checked before body parsing: a foreign chat with a
# malformed body still looks like a missing chat.
c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 404, actor=eve,
raw=b'{', headers={'Content-Type': 'application/json', 'Idempotency-Key': key()})
boundary = send(c, alice, chat, 'я' * 4000)
ok(len(boundary['text']) == 4000, '4000 code point message changed')
history = all_messages(c, bob, chat)
ok(any(item == boundary for item in history), 'member cannot read message history')
print('PASS messages')
def test_pagination(c, alice, bob):
chat = new_chat(c, alice, 'Пагинация', [alice['id'], bob['id']])
for index in range(23):
send(c, alice if index % 2 == 0 else bob, chat, 'строка %02d' % index)
expected = sorted_messages(all_messages(c, alice, chat, limit=100))
collected = []
cursor = None
limits = [7, 5, 100, 1, 3, 9]
step = 0
while True:
path = '/api/v1/chats/' + chat['id'] + '/messages?limit=' + str(limits[step % len(limits)])
if cursor:
from urllib.parse import quote
path += '&cursor=' + quote(cursor, safe='')
page = c.call('GET', path, actor=bob, schema='MessagePage')['json']
collected.extend(page['items'])
step += 1
if page['next_cursor'] is None:
break
cursor = page['next_cursor']
ok(step < 100, 'pagination did not finish')
ok(collected == expected, 'pagination lost, duplicated or reordered messages')
ids = [item['id'] for item in collected]
ok(len(ids) == len(set(ids)), 'pagination repeated an id')
first = c.call('GET', '/api/v1/chats/' + chat['id'] + '/messages?limit=3', actor=alice, schema='MessagePage')['json']
ok(first['next_cursor'] is not None, 'first page cursor missing')
other = new_chat(c, alice, 'Другой чат', [alice['id']])
c.call('GET', '/api/v1/chats/' + other['id'] + '/messages?cursor=' + first['next_cursor'], 400, actor=alice)
c.call('GET', '/api/v1/chats/' + chat['id'] + '/messages?cursor=not-base64!!', 400, actor=alice)
c.call('GET', '/api/v1/chats/' + chat['id'] + '/messages?limit=0', 400, actor=alice)
c.call('GET', '/api/v1/chats/' + chat['id'] + '/messages?limit=101', 400, actor=alice)
c.call('GET', '/api/v1/chats/' + chat['id'] + '/messages?limit=abc', 400, actor=alice)
c.call('GET', '/api/v1/chats/' + chat['id'] + '/messages?limit=1&limit=2', 400, actor=alice)
c.call('GET', '/api/v1/chats/' + chat['id'] + '/messages?cursor=', 400, actor=alice)
# A message cursor is scoped to a chat and cannot continue the chat list.
c.call('GET', '/api/v1/chats?cursor=' + first['next_cursor'], 400, actor=alice)
listed = c.call('GET', '/api/v1/chats?limit=100', actor=alice, schema='ChatPage')['json']
ok(any(item['id'] == chat['id'] for item in listed['items']), 'paginated chat missing from list')
ok(any(item['id'] == other['id'] for item in listed['items']), 'other chat missing from list')
print('PASS pagination')
def test_concurrent_registration(c):
username = 'race_' + uuid.uuid4().hex[:10]
body = {'username': username, 'display_name': 'Гонка', 'password': 'Race-password-123'}
def attempt(_):
local = Client(c.base)
try:
return local.call('POST', '/api/v1/users', (201, 409), body=body)['status']
except Exception as exc: # failures are assertions for this test
return 'error:' + type(exc).__name__
barrier = threading.Barrier(8)
def synchronized_attempt(index):
barrier.wait()
return attempt(index)
with concurrent.futures.ThreadPoolExecutor(max_workers=8) as pool:
statuses = list(pool.map(synchronized_attempt, range(8)))
ok(statuses.count(201) == 1, 'concurrent registration: expected exactly one 201, got ' + repr(statuses))
ok(statuses.count(409) == 7, 'concurrent registration: expected seven 409, got ' + repr(statuses))
c.call('POST', '/api/v1/auth/sessions', 201, headers={'Authorization': basic(username, 'Race-password-123')}, schema='Session')
print('PASS concurrent registration')
def test_concurrent_messages(c, alice, bob):
chat = new_chat(c, alice, 'Конкурентная запись', [alice['id'], bob['id']])
def worker(index):
local = Client(c.base)
actor = alice if index % 2 == 0 else bob
return local.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 201, actor=actor,
body={'text': 'concurrent %02d' % index},
headers={'Idempotency-Key': key()}, schema='Message')['json']
with concurrent.futures.ThreadPoolExecutor(max_workers=12) as pool:
messages = list(pool.map(worker, range(24)))
ids = [message['id'] for message in messages]
ok(len(ids) == 24 and len(set(ids)) == 24, 'concurrent messages produced duplicate ids')
for index, message in enumerate(messages):
ok(message['sender_id'] == (alice['id'] if index % 2 == 0 else bob['id']), 'concurrent sender mismatch')
history = all_messages(c, alice, chat)
ok(len(history) == 24, 'concurrent history has %d rows, want 24' % len(history))
ok(sorted_messages(history) == history, 'concurrent history is not ordered by (created_at, id)')
ok([item['text'] for item in history].count('concurrent 00') == 1, 'concurrent duplicate text')
print('PASS concurrent messages')
def test_logout(c, alice):
second = login(c, {'id': alice['id'], 'user': alice['user'],
'registration': alice['registration'], 'password': alice['password']})
first_token = alice['token']
c.call('DELETE', '/api/v1/auth/sessions/current', 204, actor=alice)
c.call('GET', '/api/v1/users/me', 401, actor={'token': first_token})
c.call('DELETE', '/api/v1/auth/sessions/current', 401, actor={'token': first_token})
me = c.call('GET', '/api/v1/users/me', actor=second, schema='User')['json']
ok(me['id'] == alice['id'], 'logout revoked another session of the same user')
alice['token'] = second['token']
print('PASS logout')
def test_instances(c, alice):
"""One session served by at least two real processes through the LB."""
seen = set()
for _ in range(40):
response = c.call('GET', '/api/v1/users/me', actor=alice, schema='User')
instance = response['headers']['X-Instance-Id']
seen.add(instance)
ok(not response['headers'].get('Set-Cookie'), 'LB introduced a sticky cookie')
ok(len(seen) >= 2, 'only one X-Instance-Id observed; run the default >=2 replicas')
ok(all(instance for instance in seen), 'empty X-Instance-Id')
# The same token keeps working while the LB moves it between processes.
ready = c.call('GET', '/health/ready', schema='Health')
ok(ready['headers']['X-Instance-Id'] in seen, 'health and business endpoints disagree on replicas')
missing = c.call('GET', '/api/v1/chats/' + str(uuid.uuid4()), 404, actor=alice)
ok(bool(missing['headers']['X-Instance-Id']), 'error response missing X-Instance-Id')
ok(missing['json']['error']['request_id'] == missing['headers']['X-Request-Id'],
'error request_id differs from X-Request-Id')
print('PASS instances (%d observed) ' % len(seen))
def test_idempotency(c, alice, bob, eve, chat):
text = 'Идемпотентность ✅ e\u0301'
idem = key()
first = send_with_key(c, alice, chat, text, idem)
expect_keys(first, {'id', 'chat_id', 'sender_id', 'text', 'created_at', 'attachment_ids'}, 'Message')
replay = send_with_key(c, alice, chat, text, idem)
ok(replay == first, 'sequential replay returned a different Message')
# JSON whitespace and escapes are not part of the semantic body.
raw = json.dumps({'text': text}, ensure_ascii=True, indent=2).encode('utf-8')
escaped = c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 201,
actor=alice, raw=raw,
headers={'Content-Type': 'application/json', 'Idempotency-Key': idem},
schema='Message')['json']
ok(escaped == first, 'semantically equal JSON did not replay the message')
# A different body with the same key is a conflict and must not append.
c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 409, actor=alice,
body={'text': 'другой body'}, headers={'Idempotency-Key': idem})
# The original body is still the recorded result after a conflict.
ok(send_with_key(c, alice, chat, text, idem) == first, 'conflict replaced the stored result')
# Scope includes the user and the chat path, so the same key is independent.
other = new_chat(c, alice, 'Другой чат идемпотентности', [alice['id'], bob['id']])
other_message = send_with_key(c, alice, other, text, idem)
ok(other_message['id'] != first['id'] and other_message['chat_id'] == other['id'],
'same key leaked across chats')
bob_message = send_with_key(c, bob, chat, text, idem)
ok(bob_message['id'] != first['id'] and bob_message['sender_id'] == bob['id'],
'same key leaked across users')
# The outsider cannot replay or inspect alice's record: scope + access = 404.
c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 404, actor=eve,
body={'text': text}, headers={'Idempotency-Key': idem})
# Header validation is exact ASCII [A-Za-z0-9._:-]{1,128}.
def bad_key(value, status=400):
headers = {} if value is None else {'Idempotency-Key': value}
c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', status, actor=alice,
body={'text': 'ключ'}, headers=headers)
bad_key(None)
bad_key('')
bad_key('bad key')
bad_key('ключ'.encode('utf-8').decode('latin-1')) # raw non-ASCII header bytes
bad_key('a' * 129)
accepted = 'A.-_:z9' + 'x' * 121
ok(len(accepted) == 128, 'test key length')
boundary = send_with_key(c, alice, chat, 'максимальный ключ', accepted)
ok(boundary['text'] == 'максимальный ключ', '128-character key rejected')
# Revoked/unknown session is checked before the idempotency record.
temp = login(c, register(c))
temp_chat = new_chat(c, temp, 'Сессия и ключ', [temp['id'], alice['id']])
temp_key = key()
keep = send_with_key(c, temp, temp_chat, 'до logout', temp_key)
c.call('DELETE', '/api/v1/auth/sessions/current', 204, actor=temp)
c.call('POST', '/api/v1/chats/' + temp_chat['id'] + '/messages', 401,
actor={'token': temp['token']}, body={'text': 'до logout'},
headers={'Idempotency-Key': temp_key})
# A different user's valid session cannot inherit the record.
c.call('POST', '/api/v1/chats/' + temp_chat['id'] + '/messages', 404, actor=bob,
body={'text': 'до logout'}, headers={'Idempotency-Key': temp_key})
ok(keep['sender_id'] == temp['id'], 'temporary message identity')
print('PASS idempotency replay/conflict/scope/validation')
def test_idempotency_concurrency(c, alice, bob, chat):
"""Concurrent same-key POSTs through several replicas must be exactly-once."""
text = 'конкурентная идемпотентность ' + uuid.uuid4().hex
idem = key()
barrier = threading.Barrier(16)
def worker(index):
local = Client(c.base)
barrier.wait()
response = local.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 201,
actor=alice, body={'text': text},
headers={'Idempotency-Key': idem}, schema='Message')
return response['json'], response['headers']['X-Instance-Id']
with concurrent.futures.ThreadPoolExecutor(max_workers=16) as pool:
results = list(pool.map(worker, range(16)))
ids = {item['id'] for item, _ in results}
instances = {instance for _, instance in results}
ok(len(ids) == 1, 'concurrent replay returned %d distinct messages' % len(ids))
ok(len(instances) >= 2, 'concurrent replay did not cross replicas: ' + repr(instances))
history = [m for m in all_messages(c, bob, chat) if m['text'] == text]
ok(len(history) == 1, 'concurrent replay appended %d rows' % len(history))
# Different bodies racing for one key: one winner, one row, the rest 409.
mixed_key = key()
barrier = threading.Barrier(12)
def mixed(index):
local = Client(c.base)
payload = 'вариант A' if index % 2 == 0 else 'вариант B'
barrier.wait()
try:
response = local.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', (201, 409),
actor=bob, body={'text': payload},
headers={'Idempotency-Key': mixed_key}, schema='Message')
return response['status'], response['json']
except Exception as exc: # noqa: BLE001 - a status other than 201/409 is a failure below
return 'error:' + type(exc).__name__, None
with concurrent.futures.ThreadPoolExecutor(max_workers=12) as pool:
outcomes = list(pool.map(mixed, range(12)))
statuses = [status for status, _ in outcomes]
ok(set(statuses) <= {201, 409}, 'mixed race produced unexpected results: ' + repr(statuses))
winners = [payload for status, payload in outcomes if status == 201]
ok(len({item['id'] for item in winners}) == 1, 'mixed race produced more than one message')
ok(any(status == 409 for status in statuses), 'mixed race did not produce a conflict')
stored = [m for m in all_messages(c, alice, chat)
if m['text'] in ('вариант A', 'вариант B') and m['id'] == winners[0]['id']]
ok(len(stored) == 1, 'mixed race stored a different or duplicate message')
print('PASS concurrent idempotency across %d replicas' % len(instances))
def upload(c, actor, chat, raw=None, filename='sample.png', content_type='image/png', status=202):
if raw is None:
raw = (ROOT / 'tests/fixtures/sample.png').read_bytes()
return c.call('POST', '/api/v1/chats/' + chat['id'] + '/attachments?filename=' + filename,
status, actor=actor, raw=raw, headers={'Content-Type': content_type},
schema='Attachment' if status < 300 else None)
def test_attachments(c, alice, bob, eve, chat):
att, content = c.attachment(alice, chat)
expect_keys(att, {'id', 'chat_id', 'owner_id', 'filename', 'content_type', 'size_bytes',
'sha256', 'status', 'variants', 'error_code', 'created_at', 'updated_at'}, 'Attachment')
ok(att['status'] == 'queued' and att['variants'] == [] and att['error_code'] is None,
'lab6 upload must return a queued snapshot with no variants and no error')
# A message may be attachment-only and may link a queued attachment: the
# link is durable and the content becomes downloadable when ready.
second, _ = c.attachment(alice, chat)
message = c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 201, actor=alice,
body={'text': '', 'attachment_ids': [second['id'], att['id']]},
headers={'Idempotency-Key': key()}, schema='Message')['json']
ok(message['text'] == '' and message['attachment_ids'] == [second['id'], att['id']],
'attachment-only message lost text or order')
history = all_messages(c, bob, chat)
ok(any(item == message for item in history), 'member cannot read a message with attachments')
# Both endpoints enforce chat membership; a foreign id is indistinguishable
# from an absent one.
for suffix in ('', '/content'):
c.call('GET', '/api/v1/attachments/' + att['id'] + suffix, 404, actor=eve)
c.call('GET', '/api/v1/attachments/' + str(uuid.uuid4()) + suffix, 404, actor=alice)
ready = c.wait_ready(bob, att)
ok(ready['status'] == 'ready' and ready['error_code'] is None, 'attachment did not become ready')
ok(sorted(v['name'] for v in ready['variants']) == ['crop', 'optimized', 'thumbnail'],
'ready attachment must expose exactly the three contract variants')
c.call('GET', '/api/v1/attachments/' + att['id'] + '/content', 200, actor=bob)
c.call('GET', '/api/v1/attachments/' + att['id'] + '/content?variant=original', 200, actor=bob)
thumb = c.call('GET', '/api/v1/attachments/' + att['id'] + '/content?variant=thumbnail', 200, actor=bob)
ok(thumb['headers'].get_content_type() == 'image/jpeg', 'thumbnail content type mismatch')
c.call('GET', '/api/v1/attachments/' + att['id'] + '/content?variant=unknown', 404, actor=bob)
# An attachment from another chat cannot be linked, even by its owner.
eve_chat = new_chat(c, eve, 'Чужой чат', [eve['id']])
foreign, _ = c.attachment(eve, eve_chat)
c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 404, actor=alice,
body={'text': 'чужая картинка', 'attachment_ids': [foreign['id']]},
headers={'Idempotency-Key': key()})
c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 404, actor=alice,
body={'text': 'нет такой', 'attachment_ids': [str(uuid.uuid4())]},
headers={'Idempotency-Key': key()})
# The owner of the foreign attachment still cannot link it here.
c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 404, actor=eve,
body={'text': 'чужое', 'attachment_ids': [foreign['id']]},
headers={'Idempotency-Key': key()})
# And the same attachment works in its own chat.
own = c.call('POST', '/api/v1/chats/' + eve_chat['id'] + '/messages', 201, actor=eve,
body={'text': '', 'attachment_ids': [foreign['id']]},
headers={'Idempotency-Key': key()}, schema='Message')['json']
ok(own['attachment_ids'] == [foreign['id']], 'attachment cannot be used in its own chat')
# Attachment ids are unique, limited to ten and syntactically valid UUIDs.
for ids in ([att['id']] * 2,
[str(uuid.uuid4()) for _ in range(11)],
['not-a-uuid']):
c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 400, actor=alice,
body={'text': 'x', 'attachment_ids': ids},
headers={'Idempotency-Key': key()})
# Idempotency covers the attachment payload: [] is the same as an absent
# field, while a different set of ids with the same key is a conflict.
plain_key = key()
plain = c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 201, actor=alice,
body={'text': 'без вложений'}, headers={'Idempotency-Key': plain_key},
schema='Message')['json']
explicit = c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 201, actor=alice,
body={'text': 'без вложений', 'attachment_ids': []},
headers={'Idempotency-Key': plain_key}, schema='Message')['json']
ok(explicit == plain, 'absent attachment_ids and [] are not semantically equal')
c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 409, actor=alice,
body={'text': 'без вложений', 'attachment_ids': [att['id']]},
headers={'Idempotency-Key': plain_key})
with_key = key()
first = c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 201, actor=alice,
body={'text': '', 'attachment_ids': [att['id']]},
headers={'Idempotency-Key': with_key}, schema='Message')['json']
replay = c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 201, actor=alice,
body={'text': '', 'attachment_ids': [att['id']]},
headers={'Idempotency-Key': with_key}, schema='Message')['json']
ok(replay == first, 'attachment message replay differs')
c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 409, actor=alice,
body={'text': '', 'attachment_ids': [second['id']]},
headers={'Idempotency-Key': with_key})
print('PASS attachments and message links')
def main():
args = arguments('Lab6 own black-box suite; creates synthetic data')
c = Client(args.base_url, args.ca_file)
test_health(c)
alice = register(c)
bob = register(c)
eve = register(c)
login(c, alice)
login(c, bob)
login(c, eve)
test_registration_and_login(c)
test_registration_validation(c)
test_chats(c, alice, bob, eve)
chat = new_chat(c, alice, 'Основной чат blackbox', [alice['id'], bob['id']])
test_messages(c, alice, bob, eve, chat)
test_attachments(c, alice, bob, eve, chat)
test_instances(c, alice)
test_idempotency(c, alice, bob, eve, chat)
test_idempotency_concurrency(c, alice, bob, chat)
test_pagination(c, alice, bob)
test_concurrent_registration(c)
test_concurrent_messages(c, alice, bob)
test_logout(c, alice)
print('PASS: lab6 student black-box suite, %d checks' % CHECKS)
if __name__ == '__main__':
try:
main()
except AssertionError as exc:
print('FAIL:', exc)
raise SystemExit(1)
Binary file not shown.

After

Width:  |  Height:  |  Size: 8.6 KiB

+676
View File
@@ -0,0 +1,676 @@
#!/usr/bin/env python3
"""Controlled lab6 incidents with saved observations and recovery evidence.
Scenarios (each bounded, each restores the stand):
1. worker — stop the worker, upload images, watch queue depth/oldest age,
the growing-queue alert fires, restart, drain, alert resolves.
2. db — pause PostgreSQL under load: readiness fails, in-flight requests
show a slow/erroring DB child span inside the HTTP trace, then
recovery is measured after unpause.
3. s3 — stop the private S3 store, keep sending attachment uploads:
HTTP 503s produce a high error-rate alert that later resolves.
4. telemetry — stop Prometheus/Loki/Tempo while the API serves traffic:
business success stays intact, the collector queue/drop counters
and bounded memory are recorded, telemetry resumes afterwards.
Python 3.9+, standard library only. Writes evidence/incidents/*.json.
"""
import argparse
import datetime as dt
import json
import os
import sys
import threading
import time
import urllib.error
import urllib.parse
import urllib.request
import uuid
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'scripts'))
import lab6_metrics as M # noqa: E402
sys.path.insert(0, str(ROOT / 'tests'))
from client import Client # noqa: E402
OUT = ROOT / 'evidence' / 'incidents'
SUMMARY = OUT / 'summary.json'
STATE = {}
def iso(ts=None):
return (dt.datetime.fromtimestamp(ts, dt.timezone.utc) if ts else dt.datetime.now(dt.timezone.utc)).isoformat()
def http_json(url, timeout=15):
with urllib.request.urlopen(url, timeout=timeout) as response:
return json.loads(response.read().decode('utf-8'))
def prom(prometheus, expression):
try:
result = http_json(prometheus + '/api/v1/query?' + urllib.parse.urlencode({'query': expression}))
data = result.get('data', {}).get('result', [])
if not data:
return None
return float(data[0]['value'][1])
except (urllib.error.URLError, urllib.error.HTTPError, KeyError, ValueError, TimeoutError):
return None
def collector_metrics(url):
result = {}
try:
with urllib.request.urlopen(url + '/metrics', timeout=10) as response:
for line in response.read().decode('utf-8', 'replace').splitlines():
if line.startswith('#') or ' ' not in line:
continue
key, value = line.rsplit(' ', 1)
try:
result[key] = float(value)
except ValueError:
continue
except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError):
return {}
return result
def collector_sum(metrics, prefix):
total = 0.0
for key, value in metrics.items():
if key.startswith(prefix):
total += value
return total
def docker(*args, check=True):
return M.run(['docker'] + list(args), check=check)
def alerts(prometheus):
try:
payload = http_json(prometheus + '/api/v1/alerts')
return [item for item in payload.get('data', {}).get('alerts', [])]
except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError):
return None
def alert_state(prometheus, name):
items = alerts(prometheus)
if items is None:
return 'unknown'
for item in items:
if item.get('labels', {}).get('alertname') == name:
return item.get('state', 'pending')
return 'inactive'
def wait_alert(prometheus, name, wanted, timeout):
started = time.time()
snapshots = []
while time.time() - started < timeout:
state = alert_state(prometheus, name)
snapshots.append({'at': iso(), 'state': state})
if state == wanted:
return True, time.time() - started, snapshots
time.sleep(3)
return False, time.time() - started, snapshots
def wait_for(condition, timeout, interval=2):
started = time.time()
while time.time() - started < timeout:
if condition():
return True, time.time() - started
time.sleep(interval)
return False, time.time() - started
def stack_status():
names = {}
for service in ('api', 'worker', 'postgres', 'broker', 's3', 'otel-collector', 'prometheus', 'loki', 'tempo'):
ids = M.compose_ids(service)
states = []
for container in ids:
data = M.inspect(container)
states.append((data.get('State') or {}).get('Status'))
names[service] = states
return names
def wait_service(service, wanted, timeout):
def check():
ids = M.compose_ids(service)
if not ids:
return False
for container in ids:
data = M.inspect(container)
state = data.get('State') or {}
health = (state.get('Health') or {}).get('Status')
if state.get('Status') != 'running':
return False
if health == 'starting':
return False
if wanted == 'healthy' and health != 'healthy':
return False
return True
return wait_for(check, timeout)
def register_actor(client, label):
return client.user(label)
def upload_raw(client, actor, chat):
content = (ROOT / 'tests/fixtures/sample.png').read_bytes()
return client.call('POST', '/api/v1/chats/' + chat['id'] + '/attachments?filename=incident.png', 202,
actor=actor, raw=content, headers={'Content-Type': 'image/png'}, schema='Attachment')
def scenario_worker(prometheus):
record = {'name': 'worker_stopped', 'started_at': iso(), 'steps': []}
worker_id = M.compose_ids('worker')[0]
client = Client(M.BASE_URL)
actor = register_actor(client, 'incidentworker')
other = register_actor(client, 'incidentworker2')
chat = client.call('POST', '/api/v1/chats', 201, actor=actor,
body={'title': 'Worker incident', 'member_ids': [actor['id'], other['id']]},
schema='Chat')['json']
docker('stop', worker_id)
record['steps'].append({'at': iso(), 'event': 'worker stopped', 'container': worker_id[-12:]})
attachments = [upload_raw(client, actor, chat)['json'] for _ in range(4)]
record['attachments'] = [item['id'] for item in attachments]
record['steps'].append({'at': iso(), 'event': 'four uploads accepted with worker stopped',
'statuses': ['queued'] * len(attachments)})
depth = 0
oldest = 0.0
deadline = time.time() + 90
while time.time() < deadline:
depth = prom(prometheus, 'max(queue_depth{service_name="messenger-api"})') or 0
oldest = prom(prometheus, 'max(queue_oldest_age_seconds{service_name="messenger-api"})') or 0
if depth >= len(attachments) and oldest > 25:
break
time.sleep(3)
record['observed_before_alert'] = {'queue_depth': depth, 'oldest_age_seconds': oldest, 'at': iso()}
fired, fire_seconds, firing_snapshots = wait_alert(prometheus, 'MessengerQueueLagGrowing', 'firing', 150)
record['alert_firing'] = {'fired': fired, 'seconds': fire_seconds, 'snapshots': firing_snapshots[-3:]}
record['steps'].append({'at': iso(), 'event': 'queue lag alert state observed', 'firing': fired,
'queue_depth': depth, 'oldest_age_seconds': oldest})
docker('start', worker_id)
ok, started_seconds = wait_service('worker', 'healthy', 90)
record['worker_restart'] = {'healthy': ok, 'seconds': started_seconds}
ready_started = time.time()
for item in attachments:
client.wait_ready(actor, item, wait_seconds=120)
record['all_ready_seconds'] = time.time() - ready_started
record['steps'].append({'at': iso(), 'event': 'all queued attachments ready after worker restart'})
drained, drained_seconds = wait_for(
lambda: (prom(prometheus, 'max(queue_oldest_age_seconds{service_name="messenger-api"})') or 999) < 20,
150, 3)
record['queue_drained'] = {'drained': drained, 'seconds': drained_seconds,
'depth': prom(prometheus, 'max(queue_depth{service_name="messenger-api"})')}
resolved, resolve_seconds, resolve_snapshots = wait_alert(prometheus, 'MessengerQueueLagGrowing', 'inactive', 180)
record['alert_resolved'] = {'resolved': resolved, 'seconds': resolve_seconds,
'snapshots': resolve_snapshots[-3:]}
record['steps'].append({'at': iso(), 'event': 'queue drained and alert resolved', 'resolved': resolved})
record['finished_at'] = iso()
record['result'] = 'PASS' if fired and resolved and ok else 'FAIL'
return record
def post_message_raw(client, actor, chat, key):
"""POST a message without raising on 4xx/5xx, so the trace header of a
failed request is still available for diagnosis."""
url = client.base + '/api/v1/chats/' + chat['id'] + '/messages'
request = urllib.request.Request(
url, data=json.dumps({'text': 'incident-' + key[:8]}).encode('utf-8'), method='POST',
headers={'Authorization': 'Bearer ' + actor['token'], 'Content-Type': 'application/json',
'Idempotency-Key': key, 'Accept': 'application/json'})
started = time.monotonic()
try:
with urllib.request.urlopen(request, timeout=client.timeout) as response:
response.read()
status = response.status
headers = response.headers
except urllib.error.HTTPError as error:
error.read()
status = error.code
headers = error.headers
except (urllib.error.URLError, TimeoutError, OSError):
status = 0
headers = {}
return {'status': status, 'elapsed': time.monotonic() - started, 'route': '/messages',
'trace_id': headers.get('X-Trace-Id', '') if headers else ''}
def load_messages(client, actor, chat, seconds, rate, stop_event, results):
"""Bounded load generator. The deadline is absolute: `next_at` advances, so
comparing it with `time.time()` would loop until stop_event is set and leak
a non-daemon thread when a scenario fails before setting the event."""
interval = 1.0 / max(rate, 0.1)
deadline = time.time() + seconds
next_at = time.time()
while time.time() < deadline and not stop_event.is_set():
scheduled = next_at
next_at += interval
delay = scheduled - time.time()
if delay > 0:
time.sleep(delay)
key = uuid.uuid4().hex
results.append(post_message_raw(client, actor, chat, key))
return
def fetch_trace(tempo, trace_id, attempts=15):
for _ in range(attempts):
try:
return http_json(tempo + '/api/traces/' + trace_id)
except (urllib.error.HTTPError, urllib.error.URLError, TimeoutError):
time.sleep(1)
return None
def trace_spans(trace):
spans = []
for batch in (trace or {}).get('batches', []):
resource = {item['key']: list(item['value'].values())[0]
for item in batch.get('resource', {}).get('attributes', [])}
for scope in batch.get('scopeSpans', []):
for span in scope.get('spans', []):
attrs = {item['key']: list(item['value'].values())[0]
for item in span.get('attributes', [])}
spans.append({'service': resource.get('service.name'), 'name': span.get('name'),
'start': int(span.get('startTimeUnixNano', 0)),
'end': int(span.get('endTimeUnixNano', 0)),
'attrs': attrs, 'parent': span.get('parentSpanId', '')})
return spans
def scenario_db(prometheus, tempo):
record = {'name': 'postgres_paused', 'started_at': iso(), 'steps': []}
postgres_id = M.compose_ids('postgres')[0]
client = Client(M.BASE_URL, timeout=10)
actor = register_actor(client, 'incidentdb')
other = register_actor(client, 'incidentdb2')
chat = client.call('POST', '/api/v1/chats', 201, actor=actor,
body={'title': 'DB incident', 'member_ids': [actor['id'], other['id']]},
schema='Chat')['json']
results = []
stop_event = threading.Event()
worker = threading.Thread(target=load_messages, args=(client, actor, chat, 20, 5, stop_event, results), daemon=True)
worker.start()
time.sleep(3)
docker('pause', postgres_id)
paused_at = time.time()
record['steps'].append({'at': iso(), 'event': 'postgres paused (SIGSTOP)'})
# Observe that readiness fails and the API still answers 503 rather than crashing.
readiness = []
while time.time() - paused_at < 10:
try:
with urllib.request.urlopen(M.BASE_URL + '/health/ready', timeout=3) as response:
readiness.append({'at': iso(), 'status': response.status})
except urllib.error.HTTPError as exc:
readiness.append({'at': iso(), 'status': exc.code})
except (urllib.error.URLError, TimeoutError):
readiness.append({'at': iso(), 'status': 0})
time.sleep(2)
record['readiness_during_pause'] = readiness
docker('unpause', postgres_id)
unpaused_at = time.time()
record['steps'].append({'at': iso(), 'event': 'postgres unpaused'})
stop_event.set()
worker.join(timeout=30)
recovered, recovery_seconds = wait_for(
lambda: _get_status(M.BASE_URL + '/health/ready', timeout=3) == 200, 90, 2)
record['recovery'] = {'ready': recovered, 'seconds': time.time() - unpaused_at}
record['requests'] = {
'total': len(results),
'errors': sum(1 for item in results if item['status'] >= 500),
'success': sum(1 for item in results if item['status'] == 201),
'error_ratio': (sum(1 for item in results if item['status'] >= 500) / len(results)) if results else 0,
}
record['steps'].append({'at': iso(), 'event': 'database recovered', 'ready': recovered})
# Find a trace of an in-flight request whose DB child is slow/erroring. The
# X-Trace-Id header is only present when the API answered; requests removed
# by the LB have none. Retry with a request sent just before a second short
# pause to guarantee an application-level span.
trace_id = record.get('trace_id', '')
if not trace_id:
actor2 = register_actor(client, 'incidentdb3')
stop_event2 = threading.Event()
results2 = []
worker2 = threading.Thread(target=load_messages, args=(client, actor2, chat, 8, 2, stop_event2, results2), daemon=True)
worker2.start()
time.sleep(2)
docker('pause', postgres_id)
time.sleep(4)
docker('unpause', postgres_id)
stop_event2.set()
worker2.join(timeout=30)
for item in list(results) + list(results2):
if item.get('trace_id') and (item.get('status', 0) >= 500 or item.get('elapsed', 0) > 1):
trace_id = item['trace_id']
break
record['trace_id'] = trace_id
if trace_id:
for _ in range(30):
try:
trace = http_json(tempo + '/api/traces/' + trace_id)
break
except (urllib.error.HTTPError, urllib.error.URLError, TimeoutError):
time.sleep(1)
else:
trace = None
spans = []
if trace:
for batch in trace.get('batches', []):
resource = {item['key']: list(item['value'].values())[0]
for item in batch.get('resource', {}).get('attributes', [])}
for scope in batch.get('scopeSpans', []):
for span in scope.get('spans', []):
attrs = {item['key']: list(item['value'].values())[0]
for item in span.get('attributes', [])}
spans.append({'service': resource.get('service.name'), 'name': span.get('name'),
'attrs': attrs, 'parent': span.get('parentSpanId', '')})
record['trace_spans'] = [{k: v for k, v in span.items() if k in ('service', 'name')} for span in spans]
record['db_spans'] = [span for span in spans if 'db.operation.name' in span['attrs']]
record['trace_diagnosis'] = {
'has_server_span': any(span['name'].startswith('/api/') for span in spans),
'has_db_child': any(span['attrs'].get('db.operation.name') for span in spans),
'db_operations': sorted({span['attrs'].get('db.operation.name') for span in spans
if span['attrs'].get('db.operation.name')}),
}
# Deterministic slow-DB probe: a temporary trigger sleeps 1.2 s inside the
# INSERT. The trace then contains a `postgresql INSERT` client span of about
# 1.2 s inside the HTTP server span, which distinguishes a slow dependency
# from a slow handler. The trigger is always dropped in `finally`.
slow_probe = {'trigger_sleep_ms': 1200, 'requested': 0, 'db_child_traces': []}
if recovered:
actor3 = actor # must already be a chat member; a fresh user would get 404
M.psql('DROP TRIGGER IF EXISTS lab6_slow_insert ON messages')
M.psql('CREATE OR REPLACE FUNCTION lab6_slow_insert() RETURNS trigger LANGUAGE plpgsql '
'AS $fn$ BEGIN PERFORM pg_sleep(1.2); RETURN NEW; END $fn$')
M.psql('CREATE TRIGGER lab6_slow_insert BEFORE INSERT ON messages '
'FOR EACH ROW EXECUTE FUNCTION lab6_slow_insert()')
try:
results3 = []
for _ in range(5):
results3.append(post_message_raw(client, actor3, chat, uuid.uuid4().hex))
finally:
M.psql('DROP TRIGGER IF EXISTS lab6_slow_insert ON messages')
M.psql('DROP FUNCTION IF EXISTS lab6_slow_insert()')
slow_probe['requested'] = len(results3)
slow_probe['statuses'] = [item.get('status') for item in results3]
slow_probe['elapsed_s'] = [round(item['elapsed'], 3) for item in results3]
for item in results3:
trace_id_candidate = item.get('trace_id')
if not trace_id_candidate:
continue
spans_candidate = trace_spans(fetch_trace(tempo, trace_id_candidate, attempts=8))
db_spans = [span for span in spans_candidate if span['attrs'].get('db.operation.name')]
if not db_spans:
continue
slow_span = max(db_spans, key=lambda span: span['end'] - span['start'])
slow_duration = (slow_span['end'] - slow_span['start']) / 1e9
if slow_duration < 0.8:
continue
server_spans = [span for span in spans_candidate if span['name'].startswith('/api/')]
server_duration = 0.0
if server_spans:
server_duration = (max(span['end'] for span in server_spans)
- min(span['start'] for span in server_spans)) / 1e9
slow_probe['db_child_traces'].append({
'trace_id': trace_id_candidate,
'server_duration_s': server_duration,
'db_spans': [{
'operation': span['attrs'].get('db.operation.name'),
'duration_s': (span['end'] - span['start']) / 1e9,
'status': span['attrs'].get('error.type', 'ok'),
} for span in db_spans],
})
if len(slow_probe['db_child_traces']) >= 3:
break
slow_probe['slow_db_trace_found'] = bool(slow_probe['db_child_traces'])
record['slow_db_probe'] = slow_probe
record['steps'].append({'at': iso(), 'event': 'temporary trigger produced trace-level DB latency evidence',
'db_child_traces': len(slow_probe['db_child_traces'])})
record['finished_at'] = iso()
record['result'] = 'PASS' if recovered and slow_probe['db_child_traces'] else 'FAIL'
return record
def _get_status(url, timeout=5):
try:
with urllib.request.urlopen(url, timeout=timeout) as response:
return response.status
except urllib.error.HTTPError as exc:
return exc.code
except (urllib.error.URLError, TimeoutError):
return 0
def scenario_s3(prometheus):
record = {'name': 's3_unavailable', 'started_at': iso(), 'steps': []}
s3_id = M.compose_ids('s3')[0]
client = Client(M.BASE_URL, timeout=20)
actor = register_actor(client, 'incidents3')
other = register_actor(client, 'incidents32')
chat = client.call('POST', '/api/v1/chats', 201, actor=actor,
body={'title': 'S3 incident', 'member_ids': [actor['id'], other['id']]},
schema='Chat')['json']
docker('stop', s3_id)
record['steps'].append({'at': iso(), 'event': 'S3 stopped, sending attachment uploads'})
results = []
# Sustained failures for 75 s, not a one-second burst: the alert needs the
# 2-minute ratio above 5% for 45 s, and a short burst can be hidden by the
# denominator of a previous test. Four uploads per second also produce a
# clear 5xx rate on the attachments route.
outage_seconds = 75
deadline = time.time() + outage_seconds
while time.time() < deadline:
for _ in range(2):
try:
response = upload_raw(client, actor, chat)
results.append({'status': response['status']})
except AssertionError:
results.append({'status': 503})
time.sleep(0.5)
record['uploads'] = {'total': len(results),
'errors': sum(1 for item in results if item['status'] >= 500),
'duration_s': outage_seconds}
record['steps'].append({'at': iso(), 'event': 'uploads observed during S3 outage',
'errors': record['uploads']['errors']})
# Keep a small healthy denominator so the 2m ratio can decay after recovery.
fired, fire_seconds, firing_snapshots = wait_alert(prometheus, 'MessengerHighApiErrorRate', 'firing', 150)
record['alert_firing'] = {'fired': fired, 'seconds': fire_seconds, 'snapshots': firing_snapshots[-3:]}
docker('start', s3_id)
ok, _ = wait_service('s3', 'healthy', 120)
record['s3_restarted'] = ok
record['steps'].append({'at': iso(), 'event': 'S3 restarted and healthy'})
# A successful upload proves the dependency recovered; the alert needs the
# 2-minute error ratio to fall.
recovered_upload = upload_raw(client, actor, chat)
record['recovery_upload'] = {'status': recovered_upload['status'], 'attachment': recovered_upload['json']['id']}
resolved, resolve_seconds, resolve_snapshots = wait_alert(prometheus, 'MessengerHighApiErrorRate', 'inactive', 240)
record['alert_resolved'] = {'resolved': resolved, 'seconds': resolve_seconds,
'snapshots': resolve_snapshots[-3:]}
record['finished_at'] = iso()
record['result'] = 'PASS' if fired and resolved and ok else 'FAIL'
return record
def scenario_telemetry(prometheus, collector_url):
record = {'name': 'telemetry_backend_outage', 'started_at': iso(), 'steps': []}
client = Client(M.BASE_URL, timeout=10)
actor = register_actor(client, 'incidenttelemetry')
other = register_actor(client, 'incidtlm2')
chat = client.call('POST', '/api/v1/chats', 201, actor=actor,
body={'title': 'Telemetry incident', 'member_ids': [actor['id'], other['id']]},
schema='Chat')['json']
before = collector_metrics(collector_url)
record['collector_before'] = {
'accepted_spans': collector_sum(before, 'otelcol_receiver_accepted_spans_total'),
'sent_spans': collector_sum(before, 'otelcol_exporter_sent_spans_total'),
'send_failed_spans': collector_sum(before, 'otelcol_exporter_send_failed_spans_total'),
'queue_size': max([value for key, value in before.items()
if key.startswith('otelcol_exporter_queue_size')] or [0]),
}
# Stop the three storage backends, not the collector and not the app.
# Container IDs are resolved before the stop: `compose ps -q` lists only
# running containers, so after `docker stop` the IDs would be gone.
backend_ids = {service: M.compose_ids(service) for service in ('prometheus', 'loki', 'tempo')}
for service in ('prometheus', 'loki', 'tempo'):
if not backend_ids[service]:
raise RuntimeError('no running container for ' + service)
docker('stop', *backend_ids[service])
stopped_at = time.time()
record['steps'].append({'at': iso(), 'event': 'Prometheus, Loki and Tempo stopped'})
results = []
stop_event = threading.Event()
worker = threading.Thread(target=load_messages, args=(client, actor, chat, 45, 8, stop_event, results), daemon=True)
uploads = []
def uploads_during():
while time.time() - stopped_at < 40:
try:
response = upload_raw(client, actor, chat)
uploads.append({'status': response['status']})
except AssertionError:
uploads.append({'status': 503})
time.sleep(2)
up = threading.Thread(target=uploads_during, daemon=True)
worker.start()
up.start()
memory = []
while time.time() - stopped_at < 40:
try:
stats = M.run(['docker', 'stats', '--no-stream', '--format', '{{.Name}} {{.MemUsage}}',
M.compose_ids('otel-collector')[0]]).stdout.strip()
memory.append({'at': iso(), 'sample': stats})
except Exception: # noqa: BLE001 - sampling must not fail the incident
pass
time.sleep(5)
worker.join(timeout=60)
up.join(timeout=60)
record['requests_during_outage'] = {
'total': len(results),
'success': sum(1 for item in results if item['status'] == 201),
'errors': sum(1 for item in results if item['status'] >= 500),
'uploads': {'total': len(uploads), 'success': sum(1 for item in uploads if item['status'] == 202)},
}
during = collector_metrics(collector_url)
record['collector_send_failed_delta'] = (
collector_sum(during, 'otelcol_exporter_send_failed_spans_total')
- record['collector_before']['send_failed_spans'])
record['collector_during'] = {
'accepted_spans': collector_sum(during, 'otelcol_receiver_accepted_spans_total'),
'send_failed_spans': collector_sum(during, 'otelcol_exporter_send_failed_spans_total'),
'refused_spans': collector_sum(during, 'otelcol_receiver_refused_spans_total'),
'queue_size_max': max([value for key, value in during.items()
if key.startswith('otelcol_exporter_queue_size')] or [0]),
'memory_samples': memory[-3:],
}
for service in ('prometheus', 'loki', 'tempo'):
docker('start', *backend_ids[service])
started = time.time()
record['backends_restarted'] = {}
for service in ('prometheus', 'loki', 'tempo'):
ok, seconds = wait_service(service, 'running', 120)
record['backends_restarted'][service] = {'running': ok, 'seconds': seconds}
# A fresh upload after recovery must produce a trace again.
recovery_upload = upload_raw(client, actor, chat)
trace_id = recovery_upload['headers'].get('X-Trace-Id', '')
record['recovery_upload'] = {'status': recovery_upload['status'], 'trace_id': trace_id}
record['steps'].append({'at': iso(), 'event': 'backends restarted; recovery upload accepted'})
record['finished_at'] = iso()
success_ratio = (record['requests_during_outage']['success'] /
max(record['requests_during_outage']['total'], 1))
record['business_available'] = success_ratio >= 0.99
# Parse the docker-stats samples (for example "45.2MiB / 224MiB") and assert
# the collector stayed bounded; the limit is 224 MiB and the memory limiter
# is configured at 160 MiB.
memories = []
for sample in memory:
text = sample.get('sample', '')
try:
value = text.split()[1]
if value.endswith('MiB'):
memories.append(float(value[:-3]))
elif value.endswith('GiB'):
memories.append(float(value[:-3]) * 1024)
except (IndexError, ValueError):
continue
record['collector_memory_mib_max'] = max(memories) if memories else None
record['memory_bounded'] = bool(memories) and max(memories) < 220
record['result'] = 'PASS' if (record['business_available'] and trace_id
and record['memory_bounded']
and record['collector_send_failed_delta'] >= 0) else 'FAIL'
return record
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--base-url', default=os.environ.get('BASE_URL', 'http://127.0.0.1:8086'))
parser.add_argument('--prometheus-url', default=os.environ.get('PROMETHEUS_URL', 'http://127.0.0.1:9096'))
parser.add_argument('--collector-url', default=os.environ.get('COLLECTOR_METRICS_URL', 'http://127.0.0.1:8886'))
parser.add_argument('--tempo-url', default=os.environ.get('TEMPO_URL', 'http://127.0.0.1:3206'))
parser.add_argument('--grafana-url', default=os.environ.get('GRAFANA_URL', 'http://127.0.0.1:3006'))
parser.add_argument('--scenario', choices=['all', 'worker', 'db', 's3', 'telemetry'], default='all')
args = parser.parse_args()
M.BASE_URL = args.base_url.rstrip('/')
prometheus = args.prometheus_url.rstrip('/')
collector_url = args.collector_url.rstrip('/')
tempo = args.tempo_url.rstrip('/')
summary = {'started_at': iso(), 'base_url': M.BASE_URL, 'scenarios': [], 'stack_before': stack_status()}
scenarios = []
if args.scenario in ('all', 'worker'):
scenarios.append(('worker', lambda: scenario_worker(prometheus)))
if args.scenario in ('all', 'db'):
scenarios.append(('db', lambda: scenario_db(prometheus, tempo)))
if args.scenario in ('all', 's3'):
scenarios.append(('s3', lambda: scenario_s3(prometheus)))
if args.scenario in ('all', 'telemetry'):
scenarios.append(('telemetry', lambda: scenario_telemetry(prometheus, collector_url)))
OUT.mkdir(parents=True, exist_ok=True)
for name, func in scenarios:
print('incident:', name, flush=True)
try:
summary['scenarios'].append(func())
except Exception as exc: # noqa: BLE001 - keep earlier scenario evidence
summary['scenarios'].append({'name': name, 'result': 'FAIL', 'error': type(exc).__name__ + ': ' + str(exc)})
# Persist after every scenario so a later failure cannot discard earlier observations.
summary['results'] = {item['name']: item.get('result', 'FAIL') for item in summary['scenarios']}
SUMMARY.write_text(json.dumps(summary, indent=2, ensure_ascii=False) + '\n')
for item in summary['scenarios']:
(OUT / (item['name'] + '.json')).write_text(json.dumps(item, indent=2, ensure_ascii=False) + '\n')
summary['stack_after'] = stack_status()
summary['finished_at'] = iso()
summary['results'] = {item['name']: item['result'] for item in summary['scenarios']}
summary['result'] = 'PASS' if all(item['result'] == 'PASS' for item in summary['scenarios']) else 'FAIL'
OUT.mkdir(parents=True, exist_ok=True)
SUMMARY.write_text(json.dumps(summary, indent=2, ensure_ascii=False) + '\n')
for item in summary['scenarios']:
(OUT / (item['name'] + '.json')).write_text(json.dumps(item, indent=2, ensure_ascii=False) + '\n')
print(json.dumps(summary['results'], indent=2))
if summary['result'] != 'PASS':
raise SystemExit(1)
print('PASS: lab6 incident evidence;', SUMMARY.relative_to(ROOT))
if __name__ == '__main__':
try:
main()
except (AssertionError, RuntimeError, ValueError, OSError) as exc:
print('FAIL:', str(exc))
raise SystemExit(1)
+405
View File
@@ -0,0 +1,405 @@
#!/usr/bin/env python3
"""Required lab6 failure demonstrations and evidence collection.
Scenarios, all on the running local stand:
1. worker stopped -> upload 202 -> message with attachment -> API restart ->
worker up -> ready + downloadable thumbnail;
2. broker restart with its AOF volume does not lose an accepted job;
3. crash between the attachment/job COMMIT and outbox publish (brokers down,
APIs killed) -> API restart republishes and the same job completes;
4. worker killed after the final S3 side effect but before ack (and after the
ready COMMIT before ack) -> redelivery completes the same result;
5. explicit replay of a ready attachment is refused.
Python 3.9+, standard library only. Writes a compact JSON evidence file without
tokens, passwords or object bytes.
"""
import datetime as dt
import json
import subprocess
import sys
import time
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tests'))
sys.path.insert(0, str(ROOT / 'scripts'))
from client import Client, Failure, arguments, check # noqa: E402
import lab6_metrics as M # noqa: E402
from image_probe import jpeg_size # noqa: E402
CHECKS = 0
EVIDENCE = ROOT / 'evidence/lifecycle/summary.json'
def ok(condition, message):
global CHECKS
CHECKS += 1
check(condition, message)
def now():
return dt.datetime.now(dt.timezone.utc).isoformat().replace('+00:00', 'Z')
def upload_sample(c, actor, chat, filename='lifecycle.png'):
att, content = c.attachment(actor, chat)
ok(att['status'] == 'queued', 'upload response is not queued')
return att, content
def wait_attachment(c, actor, attachment_id, statuses, timeout=90):
deadline = time.monotonic() + timeout
current = None
while time.monotonic() < deadline:
current = c.call('GET', '/api/v1/attachments/' + attachment_id, actor=actor, schema='Attachment')['json']
if current['status'] == 'failed':
raise Failure('attachment failed: %s' % current.get('error_code'))
if current['status'] in statuses:
return current
time.sleep(0.25)
raise Failure('attachment did not reach %s within %d s' % (statuses, timeout))
def wait_ready(c, actor, attachment_id, timeout=90):
return wait_attachment(c, actor, attachment_id, ('ready',), timeout)
def wait_outbox_pending(predicate, timeout=60):
deadline = time.monotonic() + timeout
stats = None
while time.monotonic() < deadline:
stats = M.jobctl('-op', 'outbox')
if predicate(stats):
return stats
time.sleep(0.5)
raise Failure('outbox condition not reached: %r' % (stats,))
def job_status(attachment_id):
return M.jobctl('-op', 'status', '-attachment', attachment_id)
def wait_job(attachment_id, predicate, timeout=90):
deadline = time.monotonic() + timeout
state = None
while time.monotonic() < deadline:
state = job_status(attachment_id)
if predicate(state):
return state
time.sleep(0.5)
raise Failure('job condition not reached: %r' % (state,))
def stream_has_job(job_id):
stream = M.jobctl('-op', 'stream')
return any(item.get('job_id') == job_id for item in stream.get('recent', [])), stream
def container_state(service):
ids = M.compose_ids(service)
if not ids:
return []
result = []
for container_id in ids:
data = M.inspect(container_id)
result.append({
'container_id': data['Id'],
'started_at': (data.get('State') or {}).get('StartedAt'),
'status': (data.get('State') or {}).get('Status'),
'health': ((data.get('State') or {}).get('Health') or {}).get('Status'),
'mounts': [
{'type': mount.get('Type'), 'name': mount.get('Name'), 'destination': mount.get('Destination')}
for mount in data.get('Mounts', [])
],
})
return result
def stop_service(service):
M.compose('stop', service)
def start_service(service):
M.compose('start', service)
def wait_running(service, timeout=60):
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
states = container_state(service)
if states and all(item['status'] == 'running' for item in states):
return states
time.sleep(0.5)
raise Failure('service did not start: ' + service)
def run_fault(scenario, attachment_id):
process = M.run(
[str(ROOT / 'scripts/worker-fault.sh'), scenario, attachment_id],
check=False, timeout=180,
)
return process.returncode
def variant_signature(ready):
return sorted((item['name'], item['sha256'], item['size_bytes']) for item in ready['variants'])
def scenario_worker_stop_api_restart(c, alice, bob, chat, evidence):
stop_service('worker')
att, content = upload_sample(c, alice, chat, 'worker-stopped.png')
message = c.message(alice, chat, '', attachments=[att['id']])['json']
ok(message['attachment_ids'] == [att['id']], 'message lost the queued attachment')
current = wait_attachment(c, bob, att['id'], ('queued', 'processing'))
ok(current['status'] in ('queued', 'processing'), 'worker stopped but attachment is ready')
conflict = c.call('GET', '/api/v1/attachments/' + att['id'] + '/content', 409, actor=bob)
ok(conflict['json']['error']['code'] == 'conflict', 'queued content is not 409')
job = wait_job(att['id'], lambda state: state['jobs'] and state['jobs'][0]['status'] in ('queued', 'processing'))
job_id = job['jobs'][0]['job_id']
wait_outbox_pending(lambda stats: stats['pending'] == 0, 60)
present, stream_before = stream_has_job(job_id)
ok(present, 'accepted job is not present in the broker stream')
ok(len(M.s3_list('staging/')) >= 1, 'accepted original is not in staging')
api_before = container_state('api')
M.compose('restart', 'api')
M.wait_ready(120)
api_after = container_state('api')
ok(all(a['container_id'] == b['container_id'] for a, b in zip(api_before, api_after)),
'API restart replaced containers instead of restarting them')
ok(any(a['started_at'] != b['started_at'] for a, b in zip(api_before, api_after)),
'API StartedAt did not change; the API was not actually restarted')
still = c.call('GET', '/api/v1/attachments/' + att['id'], actor=bob, schema='Attachment')['json']
ok(still['status'] in ('queued', 'processing'), 'API restart changed the queued state')
start_service('worker')
wait_running('worker', 60)
M.wait_healthy('worker', 60)
ready = wait_ready(c, bob, att['id'], 90)
thumb = c.call('GET', '/api/v1/attachments/' + att['id'] + '/content?variant=thumbnail', actor=bob)
ok(thumb['headers'].get_content_type() == 'image/jpeg' and jpeg_size(thumb['bytes']) == (256, 160),
'thumbnail is not a 256x160 JPEG after recovery')
ok(c.call('GET', '/api/v1/attachments/' + att['id'] + '/content', actor=bob)['bytes'] == content,
'original changed after API/worker restart')
evidence['worker_stop_api_restart'] = {
'when': now(),
'attachment_id': att['id'],
'job_id': job_id,
'message_id': message['id'],
'status_before_worker': 'queued',
'status_after_restart': ready['status'],
'thumbnail': {'content_type': 'image/jpeg', 'width': 256, 'height': 160},
'stream_entries': stream_before.get('entries'),
'api_before': api_before,
'api_after': api_after,
}
print('PASS worker stopped -> 202 -> API restart -> worker up -> ready')
def scenario_broker_restart(c, alice, bob, chat, evidence):
stop_service('worker')
att, content = upload_sample(c, alice, chat, 'broker-restart.png')
job = wait_job(att['id'], lambda state: bool(state['jobs']))
job_id = job['jobs'][0]['job_id']
wait_outbox_pending(lambda stats: stats['pending'] == 0, 60)
present, stream_before = stream_has_job(job_id)
ok(present, 'job is missing before broker restart')
broker_before = container_state('broker')
volume_before = [mount for mount in broker_before[0]['mounts'] if mount['destination'] == '/data']
ok(volume_before and volume_before[0]['name'], 'broker has no persistent /data volume')
M.compose('restart', 'broker')
M.wait_healthy('broker', 60)
broker_after = container_state('broker')
ok(broker_before[0]['container_id'] == broker_after[0]['container_id'],
'broker restart replaced the container')
ok(broker_before[0]['started_at'] != broker_after[0]['started_at'],
'broker StartedAt did not change')
present, stream_after = stream_has_job(job_id)
ok(present, 'accepted job disappeared from the broker after restart with volume')
still = c.call('GET', '/api/v1/attachments/' + att['id'], actor=alice, schema='Attachment')['json']
ok(still['status'] in ('queued', 'processing'), 'attachment changed while worker was stopped')
start_service('worker')
wait_running('worker', 60)
M.wait_healthy('worker', 60)
ready = wait_ready(c, bob, att['id'], 90)
ok(c.call('GET', '/api/v1/attachments/' + att['id'] + '/content', actor=bob)['bytes'] == content,
'original changed after broker restart')
evidence['broker_restart'] = {
'when': now(),
'attachment_id': att['id'],
'job_id': job_id,
'status_after_restart': ready['status'],
'stream_before': {'entries': stream_before.get('entries'), 'pending': stream_before.get('pending')},
'stream_after': {'entries': stream_after.get('entries'), 'pending': stream_after.get('pending')},
'broker_before': broker_before,
'broker_after': broker_after,
'volume': volume_before[0],
}
print('PASS broker restart with volume preserves the accepted job')
def scenario_outbox_gap(c, alice, bob, chat, evidence):
stop_service('worker')
stop_service('broker')
att, content = upload_sample(c, alice, chat, 'outbox-gap.png')
stats_before = M.jobctl('-op', 'outbox')
ok(stats_before['pending'] >= 1, 'outbox did not retain the committed intention while broker was down')
staging = [item for item in M.s3_list('staging/') if att['id'] in item['key']]
ok(staging, 'staging object is missing while publish is pending')
job = wait_job(att['id'], lambda state: bool(state['jobs']))
job_id = job['jobs'][0]['job_id']
api_before = container_state('api')
M.compose('kill', 'api')
time.sleep(1.0)
killed = container_state('api')
ok(all(item['status'] != 'running' for item in killed), 'API replicas are still running after kill')
stats_after_kill = M.jobctl('-op', 'outbox')
ok(stats_after_kill['pending'] >= 1, 'outbox intention was lost when the API process died')
M.compose('start', 'broker')
M.wait_healthy('broker', 60)
M.compose('start', 'api')
M.wait_ready(120)
stats_after_publish = wait_outbox_pending(lambda stats: stats['pending'] == 0, 60)
present, stream = stream_has_job(job_id)
ok(present, 'committed job was not published after API recovery')
start_service('worker')
wait_running('worker', 60)
M.wait_healthy('worker', 60)
ready = wait_ready(c, bob, att['id'], 90)
ok(c.call('GET', '/api/v1/attachments/' + att['id'] + '/content', actor=bob)['bytes'] == content,
'original changed after outbox recovery')
evidence['outbox_gap'] = {
'when': now(),
'attachment_id': att['id'],
'job_id': job_id,
'outbox_before': stats_before,
'outbox_after_api_kill': stats_after_kill,
'outbox_after_recovery': stats_after_publish,
'status_after_recovery': ready['status'],
'api_killed': api_before,
'stream': {'entries': stream.get('entries'), 'pending': stream.get('pending')},
}
print('PASS COMMIT -> publish crash window recovered automatically')
def scenario_crash_points(c, alice, bob, chat, evidence):
# Control: the same original and pipeline version processed normally. Its
# deterministic variant hashes are the expected result for crash retries.
control, content = upload_sample(c, alice, chat, 'control.png')
control_ready = wait_ready(c, bob, control['id'], 60)
control_signature = variant_signature(control_ready)
ok(len(control_signature) == 3, 'control does not expose three variants')
evidence['crash_points'] = {'when': now(), 'control_attachment_id': control['id'],
'control_variants': control_signature}
crash_results = {}
for scenario in ('crash_before_side_effect', 'crash_after_side_effect', 'crash_after_commit_before_ack'):
stop_service('worker')
att, payload = upload_sample(c, alice, chat, scenario + '.png')
job = wait_job(att['id'], lambda state: bool(state['jobs']))
job_id = job['jobs'][0]['job_id']
wait_outbox_pending(lambda stats: stats['pending'] == 0, 60)
before_objects = M.s3_list('attachments/' + att['id'] + '/')
exit_code = run_fault(scenario, att['id'])
ok(exit_code != 0, scenario + ': fault worker did not exit abruptly')
after_job = job_status(att['id'])
job_row = after_job['jobs'][0]
after_objects = M.s3_list('attachments/' + att['id'] + '/')
if scenario == 'crash_before_side_effect':
ok(after_objects == [], 'crash before side effect wrote final S3 objects')
ok(job_row['status'] == 'processing', 'job did not retain the processing lease')
elif scenario == 'crash_after_side_effect':
ok(len(after_objects) == 4, 'crash after side effect did not leave four final objects')
ok(job_row['status'] == 'processing', 'job committed the result before the injected crash')
else:
ok(job_row['status'] == 'ready', 'job was not ready after the after-COMMIT crash')
ok(len(after_objects) == 4, 'ready job is missing final objects')
start_service('worker')
wait_running('worker', 60)
M.wait_healthy('worker', 60)
ready = wait_ready(c, bob, att['id'], 120)
ok(variant_signature(ready) == control_signature,
scenario + ': redelivery produced a different result set')
ok(c.call('GET', '/api/v1/attachments/' + att['id'] + '/content', actor=bob)['bytes'] == payload,
scenario + ': original differs after redelivery')
# The worker is up again for the next scenario; stop it explicitly at
# the top of the loop.
crash_results[scenario] = {
'attachment_id': att['id'],
'job_id': job_id,
'fault_exit_code': exit_code,
'job_before_recovery': job_row['status'],
'objects_before_recovery': len(after_objects),
'objects_before': len(before_objects),
'status_after_recovery': ready['status'],
'variants_after': variant_signature(ready),
}
print('PASS %s -> redelivery completed the same result' % scenario)
evidence['crash_points']['scenarios'] = crash_results
def scenario_replay_refused(c, alice, chat, evidence):
att, _ = upload_sample(c, alice, chat, 'ready-replay.png')
wait_ready(c, alice, att['id'], 60)
process = M.run([str(ROOT / 'scripts/jobctl.sh'), '-op', 'replay',
'-attachment', att['id'], '-actor', 'lifecycle-test'],
check=False, timeout=60)
ok(process.returncode != 0, 'replay of a ready job was accepted')
ok('already ready' in (process.stderr or ''), 'replay refusal does not mention the ready state')
evidence['replay_ready_refused'] = {
'when': now(), 'attachment_id': att['id'], 'exit_code': process.returncode,
'refusal': (process.stderr or '').strip().splitlines()[-1] if process.stderr else '',
}
print('PASS replay of a ready job is refused')
def main():
def configure(parser):
parser.add_argument('--output', default=str(EVIDENCE))
args = arguments('Lab6 required worker/broker/API failure demonstrations', configure)
M.BASE_URL = args.base_url or M.BASE_URL
c = Client(args.base_url, args.ca_file, timeout=5)
alice, bob, eve, chat = c.bootstrap()
evidence = {
'lab': 5,
'when': now(),
'base_url': args.base_url,
'checks': 0,
}
try:
scenario_worker_stop_api_restart(c, alice, bob, chat, evidence)
scenario_broker_restart(c, alice, bob, chat, evidence)
scenario_outbox_gap(c, alice, bob, chat, evidence)
scenario_crash_points(c, alice, bob, chat, evidence)
scenario_replay_refused(c, alice, chat, evidence)
finally:
# Always leave the normal worker running for subsequent checks.
try:
start_service('worker')
wait_running('worker', 30)
except Exception:
pass
evidence['checks'] = CHECKS
evidence['completed_at'] = now()
output = Path(args.output)
output.parent.mkdir(parents=True, exist_ok=True)
output.write_text(json.dumps(evidence, indent=2, ensure_ascii=False) + '\n', encoding='utf-8')
print('evidence:', output)
print('PASS: lab6 lifecycle demonstrations, %d assertions' % CHECKS)
if __name__ == '__main__':
try:
main()
except (Failure, ValueError, OSError, subprocess.TimeoutExpired) as exc:
print('FAIL:', str(exc))
raise SystemExit(1)
+414
View File
@@ -0,0 +1,414 @@
#!/usr/bin/env python3
"""Lab6 observability acceptance checks.
Proves, from the running stand and the real backends, that:
* Grafana loaded the Git-provisioned Prometheus/Loki/Tempo datasources,
the dashboard and the Prometheus alert rules;
* all mandatory low-cardinality metric families exist with the expected
labels, and forbidden IDs never become metric labels;
* one real upload produces one W3C trace shared by the API server span, the
outbox producer span, the worker consumer span and its S3/DB children;
* Loki contains the same trace_id in structured API and worker logs;
* synthetic message text, passwords and session tokens are absent from
metrics, logs and traces;
* telemetry data survives a restart of Prometheus, Loki and Tempo
(--restart-backends).
Python 3.9+, standard library only. Writes evidence/observability/summary.json.
"""
import argparse
import base64
import datetime as dt
import json
import os
import re
import sys
import time
import urllib.error
import urllib.parse
import urllib.request
import uuid
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tests'))
from client import Client, check # noqa: E402
CHECKS = 0
EVIDENCE = ROOT / 'evidence' / 'observability'
SUMMARY = EVIDENCE / 'summary.json'
FORBIDDEN_METRIC_LABELS = {'user_id', 'chat_id', 'message_id', 'attachment_id', 'request_id', 'session_token',
'raw_url', 'filename', 'message_text'}
UUID_RE = re.compile(r'[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}')
def ok(condition, message):
global CHECKS
CHECKS += 1
check(bool(condition), message)
def now_iso():
return dt.datetime.now(dt.timezone.utc).isoformat()
def http_json(url, timeout=15, headers=None):
request = urllib.request.Request(url, headers=headers or {})
with urllib.request.urlopen(request, timeout=timeout) as response:
return response.status, json.loads(response.read().decode('utf-8'))
def http_text(url, timeout=15):
with urllib.request.urlopen(url, timeout=timeout) as response:
return response.status, response.read().decode('utf-8', 'replace')
def grafana_auth():
password = os.environ.get('GRAFANA_ADMIN_PASSWORD')
if not password:
env_file = ROOT / '.env'
if env_file.is_file():
for line in env_file.read_text().splitlines():
if line.startswith('GRAFANA_ADMIN_PASSWORD='):
password = line.split('=', 1)[1].strip()
if not password:
return {}
token = base64.b64encode(('admin:' + password).encode('utf-8')).decode('ascii')
return {'Authorization': 'Basic ' + token}
def prom_query(prometheus, expression):
url = prometheus + '/api/v1/query?' + urllib.parse.urlencode({'query': expression})
status, payload = http_json(url)
ok(status == 200 and payload.get('status') == 'success', 'Prometheus query failed: ' + expression)
return payload['data']['result']
def prom_series(prometheus, selector):
end = time.time()
start = end - 2 * 3600
query = urllib.parse.urlencode({'match[]': selector, 'start': str(start), 'end': str(end)})
status, payload = http_json(prometheus + '/api/v1/series?' + query)
ok(status == 200 and payload.get('status') == 'success', 'Prometheus series query failed: ' + selector)
return payload['data']
def loki_range(loki, query, start_ns, end_ns, limit=200):
params = urllib.parse.urlencode({'query': query, 'start': str(start_ns), 'end': str(end_ns),
'limit': str(limit), 'direction': 'forward'})
status, payload = http_json(loki + '/loki/api/v1/query_range?' + params)
ok(status == 200 and payload.get('status') == 'success', 'Loki query failed: ' + query)
return payload['data'].get('result', [])
def tempo_trace(tempo, trace_id, attempts=30):
for _ in range(attempts):
try:
status, payload = http_json(tempo + '/api/traces/' + trace_id)
if status == 200 and payload.get('batches'):
return payload
except urllib.error.HTTPError:
pass
except (urllib.error.URLError, TimeoutError):
pass
time.sleep(1)
return None
def normalize_trace_id(value):
"""Tempo JSON returns trace IDs as base64; the API header and logs use hex."""
value = value or ''
if len(value) == 24:
try:
return base64.b64decode(value).hex()
except (ValueError, TypeError):
return value
return value
def flatten_spans(payload):
spans = []
for batch in payload.get('batches', []):
resource = {item['key']: list(item['value'].values())[0] for item in batch.get('resource', {}).get('attributes', [])}
for scope in batch.get('scopeSpans', []):
for span in scope.get('spans', []):
attrs = {item['key']: list(item['value'].values())[0] for item in span.get('attributes', [])}
spans.append({
'service': resource.get('service.name'),
'name': span.get('name'),
'trace_id': normalize_trace_id(span.get('traceId')),
'span_id': span.get('spanId'),
'parent_id': span.get('parentSpanId', ''),
'kind': span.get('kind'),
'attrs': attrs,
'raw': span,
})
return spans
def metric_labels(series):
labels = set()
for item in series:
labels.update((item.get('metric') or item).keys())
return labels
def assert_metric(prometheus, name, expected_labels=()):
result = prom_query(prometheus, 'count(' + name + ')')
ok(result and float(result[0]['value'][1]) > 0, 'metric is missing or empty: ' + name)
series = prom_series(prometheus, name)
labels = metric_labels(series)
for label in expected_labels:
ok(label in labels, name + ' has no label ' + label)
forbidden = labels & FORBIDDEN_METRIC_LABELS
ok(not forbidden, name + ' uses forbidden labels: ' + repr(sorted(forbidden)))
return series
def wait_ready(url, attempts=90):
for _ in range(attempts):
try:
status, _ = http_text(url)
if status == 200:
return
except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError):
pass
time.sleep(1)
raise RuntimeError('backend did not become ready: ' + url)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--base-url', default=os.environ.get('BASE_URL', 'http://127.0.0.1:8086'))
parser.add_argument('--prometheus-url', default=os.environ.get('PROMETHEUS_URL', 'http://127.0.0.1:9096'))
parser.add_argument('--loki-url', default=os.environ.get('LOKI_URL', 'http://127.0.0.1:3106'))
parser.add_argument('--tempo-url', default=os.environ.get('TEMPO_URL', 'http://127.0.0.1:3206'))
parser.add_argument('--grafana-url', default=os.environ.get('GRAFANA_URL', 'http://127.0.0.1:3006'))
parser.add_argument('--restart-backends', action='store_true',
help='restart Prometheus/Loki/Tempo with volumes kept and re-check old data')
args = parser.parse_args()
prometheus = args.prometheus_url.rstrip('/')
loki = args.loki_url.rstrip('/')
tempo = args.tempo_url.rstrip('/')
grafana = args.grafana_url.rstrip('/')
summary = {
'started_at': now_iso(),
'base_url': args.base_url,
'backends': {'prometheus': prometheus, 'loki': loki, 'tempo': tempo, 'grafana': grafana},
'checks': [],
}
# ---- health of the three stores and Grafana ---------------------------
for name, url in (('prometheus', prometheus + '/-/ready'), ('loki', loki + '/ready'),
('tempo', tempo + '/ready'), ('grafana', grafana + '/api/health')):
status, _ = http_text(url)
ok(status == 200, name + ' is not ready')
summary['checks'].append({'check': name + '_ready', 'result': 'PASS'})
# ---- Git-provisioned datasources, dashboard and alert rules ----------
auth = grafana_auth()
status, datasources = http_json(grafana + '/api/datasources', headers=auth)
ok(status == 200, 'Grafana datasource API failed')
by_uid = {item['uid']: item for item in datasources}
for uid, kind in (('prometheus', 'prometheus'), ('loki', 'loki'), ('tempo', 'tempo')):
ok(uid in by_uid and by_uid[uid]['type'] == kind, 'missing Grafana datasource ' + uid)
status, dashboard = http_json(grafana + '/api/dashboards/uid/lab6-observability', headers=auth)
ok(status == 200, 'provisioned dashboard lab6-observability is missing')
panels = dashboard.get('dashboard', {}).get('panels', [])
ok(len(panels) >= 20, 'dashboard has too few panels: %d' % len(panels))
titles = ' '.join(panel.get('title', '') for panel in panels).lower()
for needle in ('p50', 'p95', 'p99', 'queue depth', 'oldest', 'pool', 'saturation', 'error'):
ok(needle in titles, 'dashboard does not cover ' + needle)
status, rules_payload = http_json(prometheus + '/api/v1/rules')
ok(status == 200, 'Prometheus rules API failed')
rules = [rule for group in rules_payload['data']['groups'] for rule in group['rules']]
names = {rule['name'] for rule in rules}
ok('MessengerHighApiErrorRate' in names, 'high error rate alert is missing')
ok('MessengerQueueLagGrowing' in names, 'queue lag alert is missing')
ok(all(rule.get('health') == 'ok' for rule in rules), 'an alert rule is not healthy')
summary['checks'].append({'check': 'provisioning', 'datasources': sorted(by_uid), 'panels': len(panels),
'alerts': sorted(names), 'result': 'PASS'})
# Create one warm-up upload so the job histograms/counters exist before the
# metric presence checks. Metrics are exported every 15 s by the SDK.
warm = Client(args.base_url)
warm_user = warm.user('warmup')
warm_other = warm.user('warmup2')
warm_chat = warm.call('POST', '/api/v1/chats', 201, actor=warm_user,
body={'title': 'Warm-up', 'member_ids': [warm_user['id'], warm_other['id']]},
schema='Chat')['json']
warm.call('POST', '/api/v1/chats/' + warm_chat['id'] + '/messages', 201, actor=warm_user,
body={'text': 'warm-up'}, headers={'Idempotency-Key': uuid.uuid4().hex}, schema='Message')
warm_attachment, _ = warm.attachment(warm_user, warm_chat)
warm.wait_ready(warm_user, warm_attachment, wait_seconds=60)
time.sleep(16)
# ---- mandatory metric families and labels ----------------------------
metric_specs = [
('http_server_requests_total', ('http_request_method', 'http_route', 'status_class', 'service_name')),
('http_server_duration_seconds_bucket', ('le', 'http_route', 'service_name')),
('jobs_processed_total', ('job_type', 'outcome', 'service_name')),
('jobs_duration_seconds_bucket', ('job_type', 'outcome', 'service_name')),
('queue_depth', ('queue_name', 'service_name')),
('queue_oldest_age_seconds', ('queue_name', 'service_name')),
('db_pool_used', ('service_name',)),
('db_pool_waiting', ('service_name',)),
('worker_jobs_busy', ('service_name',)),
('worker_jobs_capacity', ('service_name',)),
('process_cpu_time_seconds_total', ('service_name',)),
('process_memory_usage_bytes', ('service_name',)),
('job_time_to_ready_seconds_bucket', ('le', 'service_name')),
]
for name, labels in metric_specs:
assert_metric(prometheus, name, labels)
# Route labels must be templates, never concrete UUIDs or raw URLs.
routes = set()
for item in prom_series(prometheus, 'http_server_requests_total'):
route = (item.get('metric') or item).get('http_route', '')
routes.add(route)
ok(not UUID_RE.search(route), 'raw UUID in http_route label: ' + route)
ok('?' not in route, 'query string in http_route label: ' + route)
ok('/api/v1/chats/{chat_id}/messages' in routes, 'message route template is not observed')
ok('/api/v1/chats/{chat_id}/attachments' in routes, 'attachment route template is not observed')
summary['checks'].append({'check': 'metrics', 'families': [item[0] for item in metric_specs],
'routes': sorted(routes), 'result': 'PASS'})
# ---- one real upload: trace and logs --------------------------------
client = Client(args.base_url)
marker = 'observability-marker-' + uuid.uuid4().hex
password = 'Obs-' + uuid.uuid4().hex
username = 'obs_' + uuid.uuid4().hex[:12]
user = client.call('POST', '/api/v1/users', 201,
body={'username': username, 'display_name': 'Obs Test', 'password': password},
schema='User')['json']
credential = base64.b64encode((username + ':' + password).encode('utf-8')).decode('ascii')
session = client.call('POST', '/api/v1/auth/sessions', 201,
headers={'Authorization': 'Basic ' + credential}, schema='Session')['json']
token = session['token']
actor = {'id': user['id'], 'user': user, 'token': token}
other = client.user('obsother')
chat = client.call('POST', '/api/v1/chats', 201, actor=actor,
body={'title': 'Observability ' + marker[:8], 'member_ids': [actor['id'], other['id']]},
schema='Chat')['json']
client.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 201, actor=actor,
body={'text': marker}, headers={'Idempotency-Key': uuid.uuid4().hex}, schema='Message')
content = (ROOT / 'tests/fixtures/sample.png').read_bytes()
upload = client.call('POST', '/api/v1/chats/' + chat['id'] + '/attachments?filename=obs.png', 202,
actor=actor, raw=content, headers={'Content-Type': 'image/png'}, schema='Attachment')
trace_id = upload['headers'].get('X-Trace-Id', '')
ok(len(trace_id) == 32, 'upload response has no X-Trace-Id; telemetry is disabled or the span is invalid')
ready = client.wait_ready(actor, upload['json'], wait_seconds=60)
trace = None
spans = []
deadline = time.time() + 45
while time.time() < deadline:
trace = tempo_trace(tempo, trace_id, attempts=1)
if trace is not None:
spans = flatten_spans(trace)
if {span['service'] for span in spans} >= {'messenger-api', 'messenger-worker'} \
and any(span['name'] == 'attachment.process' for span in spans):
break
time.sleep(1)
ok(trace is not None, 'trace was not stored in Tempo within 45 s: ' + trace_id)
ok({span['service'] for span in spans} >= {'messenger-api', 'messenger-worker'},
'trace does not contain both API and worker services')
by_id = {span['span_id']: span for span in spans}
server = next((span for span in spans if span['service'] == 'messenger-api'
and span['name'] == '/api/v1/chats/{chat_id}/attachments'), None)
producer = next((span for span in spans if span['name'] == 'attachment.job publish'), None)
consumer = next((span for span in spans if span['name'] == 'attachment.process'), None)
ok(server is not None, 'API server span is missing from the upload trace')
ok(producer is not None, 'outbox producer span is missing from the upload trace')
ok(consumer is not None, 'worker consumer span is missing from the upload trace')
ok(producer['parent_id'] == server['span_id'], 'producer span is not a child of the upload server span')
ok(consumer['parent_id'] == producer['span_id'], 'consumer span is not a child of the producer span')
ok(consumer['kind'] == 'SPAN_KIND_CONSUMER', 'worker consumer span has the wrong kind')
ok(consumer['attrs'].get('messaging.system') == 'valkey_streams', 'consumer span lacks messaging.system')
ok(consumer['attrs'].get('job.outcome') == 'success', 'consumer span does not record the terminal outcome')
ok(any(span['attrs'].get('aws.s3.operation') for span in spans), 'no S3 span in the upload trace')
ok(any(span['attrs'].get('db.operation.name') for span in spans), 'no DB span in the upload trace')
ok(all(span['trace_id'] == trace_id for span in spans), 'spans of the upload trace have different trace IDs')
apply_span = next((span for span in spans if span['name'] == 'attachment.process'), None)
ok(apply_span is not None, 'missing worker apply span')
trace_text = json.dumps(trace)
for forbidden in (marker, password, token, 'Authorization', 'Bearer '):
ok(forbidden not in trace_text, 'forbidden value leaked into the trace: ' + forbidden[:20])
forbidden_attrs = {'message.text', 'image.data', 'http.request.header.authorization', 'password', 'token'}
ok(not forbidden_attrs & {key.lower() for span in spans for key in span['attrs']},
'trace attributes contain a forbidden key')
start_ns = int((time.time() - 900) * 1e9)
end_ns = int((time.time() + 60) * 1e9)
streams = loki_range(loki, '{service_name=~"messenger-.*"} | json | trace_id="' + trace_id + '"',
start_ns, end_ns)
services = {item['stream'].get('service_name') for item in streams}
ok('messenger-api' in services and 'messenger-worker' in services,
'Loki does not contain correlated API and worker logs for the trace')
lines = 0
for item in streams:
for value in item['values']:
lines += 1
ok(len(item['stream'].get('trace_id', '')) == 32, 'Loki stream lost trace_id')
ok(len(item['stream'].get('span_id', '')) == 16, 'Loki stream lost span_id')
ok(lines >= 3, 'too few correlated log lines: %d' % lines)
marker_logs = loki_range(loki, '{service_name=~"messenger-.*"} |= "' + marker + '"', start_ns, end_ns)
ok(not marker_logs, 'message body leaked into Loki logs')
password_logs = loki_range(loki, '{service_name=~"messenger-.*"} |= "' + password + '"', start_ns, end_ns)
ok(not password_logs, 'password leaked into Loki logs')
summary['checks'].append({
'check': 'trace_and_logs', 'trace_id': trace_id, 'attachment_id': ready['id'],
'spans': len(spans), 'span_names': sorted({span['name'] for span in spans}),
'log_lines': lines, 'result': 'PASS',
})
# ---- collector pipeline is configured with bounded resources --------
collector = (ROOT / 'infra/otel/collector.yaml').read_text()
for needle in ('memory_limiter', 'batch:', 'sending_queue:', 'queue_size:', 'retry_on_failure:',
'max_elapsed_time:', 'prometheus:', 'otlp/tempo:', 'otlphttp/loki:'):
ok(needle in collector, 'collector config lacks ' + needle)
ok('debug' not in collector.split('exporters:')[1].split('service:')[0],
'collector uses the debug exporter instead of a real store')
summary['checks'].append({'check': 'collector_bounded', 'result': 'PASS'})
# ---- optional restart persistence -----------------------------------
if args.restart_backends:
old_trace = trace_id
old_marker = marker
compose = [str(ROOT / 'scripts/compose.sh'), '--env-file', '.env']
import subprocess
subprocess.run(compose + ['restart', 'prometheus', 'loki', 'tempo'], cwd=str(ROOT), check=True,
stdout=subprocess.DEVNULL)
wait_ready(prometheus + '/-/ready')
wait_ready(loki + '/ready')
wait_ready(tempo + '/ready')
trace_after = tempo_trace(tempo, old_trace, attempts=60)
ok(trace_after is not None, 'trace disappeared after a telemetry store restart')
streams_after = loki_range(loki, '{service_name=~"messenger-.*"} | json | trace_id="' + old_trace + '"',
start_ns, end_ns)
ok(streams_after, 'logs disappeared after a telemetry store restart')
metric_after = prom_query(prometheus, 'count(http_server_requests_total)')
ok(metric_after and float(metric_after[0]['value'][1]) > 0,
'metrics disappeared after a Prometheus restart')
summary['checks'].append({'check': 'restart_persistence', 'trace_id': old_trace,
'log_streams': len(streams_after), 'result': 'PASS'})
del old_marker
summary['checks'].append({'check': 'secret_absence', 'result': 'PASS'})
summary['finished_at'] = now_iso()
summary['assertions'] = CHECKS
summary['result'] = 'PASS'
EVIDENCE.mkdir(parents=True, exist_ok=True)
SUMMARY.write_text(json.dumps(summary, indent=2, ensure_ascii=False) + '\n')
print('PASS: lab6 observability checks (%d assertions); evidence %s' % (CHECKS, SUMMARY.relative_to(ROOT)))
if __name__ == '__main__':
try:
main()
except (AssertionError, RuntimeError, ValueError, OSError) as exc:
print('FAIL:', str(exc))
raise SystemExit(1)
+319
View File
@@ -0,0 +1,319 @@
#!/usr/bin/env python3
"""Bounded-retry, backoff and explicit-replay scenario.
Verifies from contracts/attachment-states.md and README level 4:
* a transient error returns the job to queued, schedules a later attempt and
carries no raw error text into the API;
* the attempt counter is bounded by JOB_MAX_ATTEMPTS and the final state is
failed with the safe error_code retry_exhausted;
* the failed registry exposes the job, and an explicit replay after the fault
is removed succeeds and preserves the same deterministic variants;
* a successful job is never replayed (checked by the lifecycle suite).
Python 3.9+, standard library only. Writes evidence/retry/summary.json.
"""
import datetime as dt
import json
import os
import sys
import time
import urllib.error
import urllib.request
import uuid
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tests'))
sys.path.insert(0, str(ROOT / 'scripts'))
from client import Client, Failure, arguments, check # noqa: E402
import lab6_metrics as M # noqa: E402
CHECKS = 0
EVIDENCE = ROOT / 'evidence/retry/summary.json'
def ok(condition, message):
global CHECKS
CHECKS += 1
check(condition, message)
def now():
return dt.datetime.now(dt.timezone.utc).isoformat().replace('+00:00', 'Z')
def upload(c, actor, chat, filename):
content = (ROOT / 'tests/fixtures/sample.png').read_bytes()
response = c.call('POST', '/api/v1/chats/' + chat['id'] + '/attachments?filename=' + filename, 202,
actor=actor, raw=content, headers={'Content-Type': 'image/png'}, schema='Attachment')
att = response['json']
ok(att['status'] == 'queued', filename + ': upload is not queued')
return att, content, response['headers'].get('X-Trace-Id', '')
def tempo_trace(tempo, trace_id, attempts=40):
for _ in range(attempts):
try:
with urllib.request.urlopen(tempo + '/api/traces/' + trace_id, timeout=10) as response:
return json.loads(response.read().decode('utf-8'))
except urllib.error.HTTPError:
pass
except (urllib.error.URLError, TimeoutError, OSError, ValueError):
pass
time.sleep(1)
return None
def flatten_trace(payload):
spans = []
for batch in (payload or {}).get('batches', []):
resource = {item['key']: list(item['value'].values())[0]
for item in batch.get('resource', {}).get('attributes', [])}
for scope in batch.get('scopeSpans', []):
for span in scope.get('spans', []):
attrs = {item['key']: list(item['value'].values())[0]
for item in span.get('attributes', [])}
spans.append({'service': resource.get('service.name'), 'name': span.get('name'),
'span_id': span.get('spanId', ''), 'parent': span.get('parentSpanId', ''),
'attrs': attrs})
return spans
def verify_retry_trace(tempo, trace_id):
"""Prove the retry continues the upload trace through broker producer/consumer spans."""
ok(bool(trace_id), 'upload response has no X-Trace-Id; cannot verify retry trace context')
payload = None
deadline = time.time() + 45
while time.time() < deadline:
payload = tempo_trace(tempo, trace_id, attempts=1)
if payload:
if sum(1 for span in flatten_trace(payload) if span['name'] == 'attachment.process') >= 2:
break
time.sleep(2)
ok(payload is not None, 'retry trace %s was not found in Tempo' % trace_id)
spans = flatten_trace(payload)
by_id = {span['span_id']: span for span in spans}
servers = [span for span in spans if span['name'] == '/api/v1/chats/{chat_id}/attachments']
producers = [span for span in spans if span['name'] == 'attachment.job publish']
consumers = [span for span in spans if span['name'] == 'attachment.process']
ok(bool(servers), 'retry trace has no API upload server span')
ok(len(producers) >= 2, 'retry trace has fewer than two producer spans: %d' % len(producers))
ok(len(consumers) >= 2, 'retry trace has fewer than two consumer spans: %d' % len(consumers))
attempts = sorted({int(span['attrs'].get('job.attempt', 0)) for span in consumers})
ok(1 in attempts and 2 in attempts, 'retry trace consumer attempts are %r' % (attempts,))
first = next(span for span in consumers if int(span['attrs'].get('job.attempt', 0)) == 1)
second = next(span for span in consumers if int(span['attrs'].get('job.attempt', 0)) == 2)
ok(first['attrs'].get('job.outcome') == 'retry', 'first attempt outcome is not retry')
ok(second['attrs'].get('job.outcome') == 'success', 'second attempt outcome is not success')
ok(first['parent'] in {span['span_id'] for span in producers},
'first consumer is not a child of a producer span')
ok(second['parent'] in {span['span_id'] for span in producers},
'second consumer is not a child of a producer span')
# Parent chain from the successful attempt back to the upload server span:
# consumer2 -> producer2 -> consumer1 -> producer1 -> server span.
chain = []
current = second
for _ in range(12):
parent = by_id.get(current['parent'])
if parent is None:
break
chain.append(parent)
current = parent
chain_ids = [span['span_id'] for span in chain]
ok(first['span_id'] in chain_ids,
'second attempt is not linked to the failed first attempt consumer span')
ok(any(span['span_id'] in chain_ids for span in servers),
'retry trace chain does not reach the API upload server span')
return {'trace_id': trace_id, 'spans': len(spans),
'producers': len(producers), 'consumers': len(consumers),
'attempts': attempts, 'parent_chain': [span['name'] for span in chain]}
def wait_attachment(c, actor, attachment_id, predicate, timeout=120):
deadline = time.monotonic() + timeout
current = None
while time.monotonic() < deadline:
current = c.call('GET', '/api/v1/attachments/' + attachment_id, actor=actor, schema='Attachment')['json']
if predicate(current):
return current
if current['status'] == 'failed' and not predicate(current):
return current
time.sleep(0.25)
raise Failure('attachment condition not reached: %r' % (current,))
def wait_ready(c, actor, attachment_id, timeout=120):
return wait_attachment(c, actor, attachment_id, lambda value: value['status'] == 'ready', timeout)
def wait_job(attachment_id, predicate, timeout=120):
deadline = time.monotonic() + timeout
state = None
while time.monotonic() < deadline:
state = M.jobctl('-op', 'status', '-attachment', attachment_id)
if predicate(state):
return state
time.sleep(0.4)
raise Failure('job condition not reached: %r' % (state,))
def wait_outbox_zero(timeout=90):
deadline = time.monotonic() + timeout
stats = None
while time.monotonic() < deadline:
stats = M.jobctl('-op', 'outbox')
if stats['pending'] == 0:
return stats
time.sleep(0.4)
raise Failure('outbox did not drain: %r' % (stats,))
def stop_worker():
M.compose('stop', 'worker')
time.sleep(0.5)
def start_worker_healthy():
M.compose('start', 'worker')
deadline = time.monotonic() + 60
while time.monotonic() < deadline:
ids = M.compose_ids('worker')
if ids and M.inspect(ids[0]).get('State', {}).get('Status') == 'running':
break
time.sleep(0.3)
M.wait_healthy('worker', 60)
def run_fault(scenario, attachment_id):
process = M.run(
[str(ROOT / 'scripts/worker-fault.sh'), scenario, attachment_id],
check=False, timeout=180,
)
return process.returncode
def signature(ready):
return sorted((item['name'], item['sha256'], item['size_bytes']) for item in ready['variants'])
def main():
def configure(parser):
parser.add_argument('--output', default=str(EVIDENCE))
parser.add_argument('--tempo-url', default=os.environ.get('TEMPO_URL', 'http://127.0.0.1:3206'))
args = arguments('Lab6 retry/backoff/exhaustion/replay and W3C retry trace scenario', configure)
M.BASE_URL = args.base_url or M.BASE_URL
c = Client(args.base_url, args.ca_file, timeout=5)
alice, bob, eve, chat = c.bootstrap()
evidence = {'when': now(), 'checks': 0}
try:
start_worker_healthy()
control, _, _ = upload(c, alice, chat, 'retry-control.png')
control_ready = wait_ready(c, bob, control['id'], 120)
control_signature = signature(control_ready)
# Transient once: attempt 1 fails, attempt 2 succeeds.
stop_worker()
transient, _, transient_trace = upload(c, alice, chat, 'transient-once.png')
job = M.jobctl('-op', 'status', '-attachment', transient['id'])
transient_job = job['jobs'][0]['job_id']
wait_outbox_zero()
exit_code = run_fault('transient_once', transient['id'])
ok(exit_code == 0, 'transient-once worker exited abnormally')
state = wait_job(
transient['id'],
lambda value: value['jobs'][0]['status'] == 'queued' and value['jobs'][0]['attempts'] == 1,
)
ok(state['jobs'][0]['error_code'] is None, 'queued retry leaks an error_code')
retry_entry = wait_outbox_zero(90)
stream = M.jobctl('-op', 'stream')
attempts = [item.get('attempt') for item in stream.get('recent', [])
if item.get('job_id') == transient_job]
ok(2 in attempts, 'retry attempt 2 was not published after backoff')
metadata = c.call('GET', '/api/v1/attachments/' + transient['id'], actor=bob, schema='Attachment')['json']
ok(metadata['status'] in ('queued', 'processing'), 'attachment is not queued during retry')
start_worker_healthy()
ready = wait_ready(c, bob, transient['id'], 120)
ok(signature(ready) == control_signature, 'retry produced different variants')
state = M.jobctl('-op', 'status', '-attachment', transient['id'])
ok(state['jobs'][0]['attempts'] == 2, 'successful retry did not record attempt 2')
ok(state['jobs'][0]['status'] == 'ready', 'retried job is not ready')
retry_trace = verify_retry_trace(args.tempo_url, transient_trace)
evidence['transient_once'] = {
'attachment_id': transient['id'], 'job_id': transient_job,
'attempts': state['jobs'][0]['attempts'], 'outbox': retry_entry,
'variants': signature(ready), 'retry_trace': retry_trace,
}
print('PASS transient retry reaches ready on attempt 2 and keeps one W3C trace')
print('retry trace:', json.dumps(retry_trace))
# Exhaustion: every attempt fails transiently; the bounded budget must
# end in failed/retry_exhausted, not an endless retry loop.
stop_worker()
exhausted, _, _ = upload(c, alice, chat, 'retry-exhausted.png')
exhausted_job = M.jobctl('-op', 'status', '-attachment', exhausted['id'])['jobs'][0]['job_id']
wait_outbox_zero()
attempts_seen = []
for attempt in range(1, 6):
exit_code = run_fault('transient_always', exhausted['id'])
ok(exit_code == 0, 'exhaustion worker exited abnormally on attempt %d' % attempt)
state = wait_job(
exhausted['id'],
lambda value, attempt=attempt: value['jobs'][0]['attempts'] >= attempt,
)
attempts_seen.append(state['jobs'][0]['attempts'])
if attempt < 5:
wait_outbox_zero(120)
final = wait_attachment(c, bob, exhausted['id'],
lambda value: value['status'] == 'failed', 30)
ok(final['error_code'] == 'retry_exhausted', 'exhaustion error_code is %r' % final['error_code'])
state = M.jobctl('-op', 'status', '-attachment', exhausted['id'])
ok(state['jobs'][0]['status'] == 'failed', 'exhausted job is not failed')
ok(state['jobs'][0]['attempts'] == 5, 'exhausted job attempts = %d, want 5' % state['jobs'][0]['attempts'])
registry = M.jobctl('-op', 'failed', '-limit', '100')
ok(any(item['job_id'] == exhausted_job for item in registry['failed_jobs']),
'failed registry does not contain the exhausted job')
conflict = c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 409, actor=alice,
body={'text': 'failed attachment', 'attachment_ids': [exhausted['id']]},
headers={'Idempotency-Key': uuid.uuid4().hex})
ok(conflict['json']['error']['code'] == 'conflict', 'failed attachment is linkable')
# Explicit operator replay after removing the fault succeeds and keeps
# the deterministic result.
replay = M.jobctl('-op', 'replay', '-attachment', exhausted['id'], '-actor', 'retry-test')
ok(replay['replayed_job_id'] == exhausted_job, 'replay selected another job')
start_worker_healthy()
replayed = wait_ready(c, bob, exhausted['id'], 120)
ok(signature(replayed) == control_signature, 'replay produced different variants')
state = M.jobctl('-op', 'status', '-attachment', exhausted['id'])
ok(state['jobs'][0]['replay_count'] == 1, 'replay_count was not recorded')
ok(state['attachment']['error_code'] is None, 'replayed attachment still has an error_code')
evidence['exhaustion_replay'] = {
'attachment_id': exhausted['id'], 'job_id': exhausted_job,
'attempts_seen': attempts_seen, 'failure': final['error_code'],
'replay_count': state['jobs'][0]['replay_count'], 'variants': signature(replayed),
}
print('PASS exhausted retries end failed and explicit replay recovers')
evidence['hypothesis'] = ('Bounded exponential backoff with jitter converts transient storage errors '
'into a later attempt, while the configured attempt ceiling terminates in a '
'safe failed state; an explicit replay starts a fresh bounded cycle.')
finally:
try:
start_worker_healthy()
except Exception:
pass
evidence['checks'] = CHECKS
evidence['completed_at'] = now()
output = Path(args.output)
output.parent.mkdir(parents=True, exist_ok=True)
output.write_text(json.dumps(evidence, indent=2, ensure_ascii=False) + '\n', encoding='utf-8')
print('evidence:', output)
print('PASS: lab6 retry/replay checks, %d assertions' % CHECKS)
if __name__ == '__main__':
try:
main()
except (Failure, ValueError, OSError) as exc:
print('FAIL:', str(exc))
raise SystemExit(1)
File diff suppressed because it is too large Load Diff
+363
View File
@@ -0,0 +1,363 @@
#!/usr/bin/env python3
"""Track 2: proven idempotency of the versioned attachment pipeline.
Hypothesis
----------
At-least-once delivery plus deterministic, version-keyed effects and a monotonic
ready_version is enough to make duplicate, reordered, crashed and stale
deliveries safe: every job reaches exactly one durable result set, an older
pipeline version cannot overwrite a newer one, and redelivery never creates extra
variants.
Injected faults (all automatic and repeatable):
* duplicate delivery before and after the job is ready;
* reorder: an older attempt is published after the retry attempt, then both are
consumed in that order;
* crash before the final S3 side effect, after the S3 side effect but before
the database COMMIT, and after the ready COMMIT but before the broker ack;
* a stale version-1 job that failed and is replayed after version 2 is ready.
Python 3.9+, standard library only. Writes evidence/track2/summary.json.
"""
import datetime as dt
import json
import subprocess
import sys
import time
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tests'))
sys.path.insert(0, str(ROOT / 'scripts'))
from client import Client, Failure, arguments, check # noqa: E402
import lab6_metrics as M # noqa: E402
CHECKS = 0
EVIDENCE = ROOT / 'evidence/track2/summary.json'
def ok(condition, message):
global CHECKS
CHECKS += 1
check(condition, message)
def now():
return dt.datetime.now(dt.timezone.utc).isoformat().replace('+00:00', 'Z')
def wait_attachment(c, actor, attachment_id, statuses, timeout=120):
deadline = time.monotonic() + timeout
current = None
while time.monotonic() < deadline:
current = c.call('GET', '/api/v1/attachments/' + attachment_id, actor=actor, schema='Attachment')['json']
if current['status'] == 'failed':
raise Failure('attachment failed: %s' % current.get('error_code'))
if current['status'] in statuses:
return current
time.sleep(0.25)
raise Failure('attachment did not reach %s: %r' % (statuses, current))
def wait_ready(c, actor, attachment_id, timeout=120):
return wait_attachment(c, actor, attachment_id, ('ready',), timeout)
def wait_failed(c, actor, attachment_id, timeout=120):
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
current = c.call('GET', '/api/v1/attachments/' + attachment_id, actor=actor, schema='Attachment')['json']
if current['status'] == 'failed':
return current
time.sleep(0.25)
raise Failure('attachment did not fail within the deadline')
def wait_job(attachment_id, predicate, timeout=120):
deadline = time.monotonic() + timeout
state = None
while time.monotonic() < deadline:
state = M.jobctl('-op', 'status', '-attachment', attachment_id)
if predicate(state):
return state
time.sleep(0.5)
raise Failure('job condition not reached: %r' % (state,))
def wait_outbox_zero(timeout=90):
deadline = time.monotonic() + timeout
stats = None
while time.monotonic() < deadline:
stats = M.jobctl('-op', 'outbox')
if stats['pending'] == 0:
return stats
time.sleep(0.5)
raise Failure('outbox did not drain: %r' % (stats,))
def wait_stream_pending_zero(timeout=120):
deadline = time.monotonic() + timeout
stream = None
while time.monotonic() < deadline:
stream = M.jobctl('-op', 'stream')
if stream.get('pending') == 0:
return stream
time.sleep(0.5)
raise Failure('stream pending entries did not drain: %r' % (stream,))
def upload(c, actor, chat, filename):
att, content = c.attachment(actor, chat)
ok(att['status'] == 'queued', filename + ': upload is not queued')
return att, content
def signature(ready):
return sorted((item['name'], item['sha256'], item['size_bytes']) for item in ready['variants'])
def start_worker():
M.compose('start', 'worker')
deadline = time.monotonic() + 60
while time.monotonic() < deadline:
ids = M.compose_ids('worker')
if ids and M.inspect(ids[0]).get('State', {}).get('Status') == 'running':
return
time.sleep(0.3)
raise Failure('worker did not start')
def stop_worker():
M.compose('stop', 'worker')
time.sleep(0.5)
def start_worker_healthy():
start_worker()
M.wait_healthy('worker', 60)
def scenario_duplicate(c, alice, bob, chat, control_signature, evidence):
stop_worker()
att, content = upload(c, alice, chat, 'duplicate.png')
job = wait_job(att['id'], lambda state: bool(state['jobs']))
job_id = job['jobs'][0]['job_id']
wait_outbox_zero()
duplicate_one = M.jobctl('-op', 'duplicate', '-job', job_id)
duplicate_two = M.jobctl('-op', 'duplicate', '-job', job_id)
ok(duplicate_one['stream_id'] != duplicate_two['stream_id'], 'duplicates reused one stream id')
start_worker_healthy()
ready = wait_ready(c, bob, att['id'], 120)
ok(signature(ready) == control_signature, 'duplicate-before-ready changed the deterministic result')
updated_before = ready['updated_at']
time.sleep(0.5)
after = M.jobctl('-op', 'duplicate', '-job', job_id)
wait_stream_pending_zero(60)
time.sleep(0.5)
final = c.call('GET', '/api/v1/attachments/' + att['id'], actor=bob, schema='Attachment')['json']
ok(signature(final) == control_signature, 'duplicate-after-ready changed the result set')
ok(len(final['variants']) == 3, 'duplicate-after-ready created extra variants')
ok(final['updated_at'] == updated_before, 'duplicate-after-ready rewrote the ready row')
evidence['duplicate'] = {
'attachment_id': att['id'],
'job_id': job_id,
'injected_before_ready': [duplicate_one, duplicate_two],
'injected_after_ready': after,
'variants': signature(final),
'updated_at': final['updated_at'],
}
print('PASS duplicate delivery before and after ready is a no-op')
def scenario_reorder(c, alice, bob, chat, control_signature, evidence):
"""Withhold the v1 delivery, let v2 complete, then deliver v1 afterwards.
This is the delivery-order fault in its clearest form: an older logical job
is consumed after a newer one. It must complete without changing the public
v2 result set or creating a second variant set.
"""
stop_worker()
att, content = upload(c, alice, chat, 'reorder.png')
job = wait_job(att['id'], lambda state: bool(state['jobs']))
v1_job = job['jobs'][0]['job_id']
wait_outbox_zero()
stream = M.jobctl('-op', 'stream')
v1_entry = [item for item in stream.get('recent', []) if item.get('job_id') == v1_job]
ok(len(v1_entry) == 1, 'expected exactly one stream entry for the v1 job')
v1_stream_id = v1_entry[0]['stream_id']
withdrawn = M.jobctl('-op', 'withdraw', '-stream-id', v1_stream_id)
ok(withdrawn['withdrawn_stream_id'] == v1_stream_id, 'withdraw returned another stream id')
upgrade = M.jobctl('-op', 'upgrade', '-attachment', att['id'], '-version', '2')
v2_job = upgrade['job_id']
wait_outbox_zero()
v2_entries = [item for item in M.jobctl('-op', 'stream').get('recent', [])
if item.get('job_id') == v2_job and item.get('attempt') == 1]
ok(len(v2_entries) == 1, 'v2 job was not published after the upgrade')
start_worker_healthy()
v2_ready = wait_ready(c, bob, att['id'], 120)
v2_signature = signature(v2_ready)
ok(v2_signature != control_signature, 'v2 produced the same optimized WebP as v1')
ok(len(v2_signature) == 3, 'v2 result does not expose three variants')
# Old v1 delivery arrives only now, after v2 is public.
old = M.jobctl('-op', 'duplicate', '-job', v1_job, '-attempt', '1')
state = wait_job(
att['id'],
lambda value: {job_item['job_id']: job_item['status'] for job_item in value['jobs']}[v1_job] == 'ready',
120,
)
final = c.call('GET', '/api/v1/attachments/' + att['id'], actor=bob, schema='Attachment')['json']
ok(signature(final) == v2_signature, 'stale v1 delivery overwrote the v2 result set')
ok(len(final['variants']) == 3, 'stale v1 delivery created extra variants')
ok(state['attachment']['ready_version'] == 2, 'stale v1 delivery lowered ready_version')
audit = int(M.psql(
"SELECT count(*) FROM job_audit WHERE job_id = '%s' AND event = 'completed_stale_version'" % v1_job))
ok(audit == 1, 'stale v1 completion is not audited exactly once')
evidence['reorder'] = {
'attachment_id': att['id'],
'v1_job_id': v1_job,
'v1_withdrawn_stream_id': v1_stream_id,
'v2_job_id': v2_job,
'v2_stream_entry': v2_entries[0],
'old_v1_injected': old,
'v2_variants': v2_signature,
'final_variants': signature(final),
'ready_version': state['attachment']['ready_version'],
'stale_audit_events': audit,
}
print('PASS reordered v1 delivery after v2 is a no-op')
def scenario_stale_version(c, alice, bob, chat, control_signature, evidence):
stop_worker()
att, content = upload(c, alice, chat, 'stale-version.png')
job = wait_job(att['id'], lambda state: bool(state['jobs']))
v1_job = job['jobs'][0]['job_id']
wait_outbox_zero()
# Permanent failure of v1: corrupt the staging object, then let the worker
# classify it. The original DB metadata (size/sha) is untouched.
staging_key = 'staging/' + att['id']
M.s3_put_bytes(staging_key, b'corrupted staging bytes', 'image/png')
start_worker_healthy()
failed = wait_failed(c, bob, att['id'], 120)
ok(failed['error_code'] == 'staging_corrupt', 'unexpected failure code: %r' % failed['error_code'])
stop_worker()
registry = M.jobctl('-op', 'failed', '-limit', '100')
entries = [item for item in registry['failed_jobs'] if item['job_id'] == v1_job]
ok(entries and entries[0]['error_code'] == 'staging_corrupt', 'failed registry does not expose the job')
# Restore the exact original and add a version-2 job. Version 2 completes
# first and becomes the public ready_version.
M.s3_put_bytes(staging_key, content, 'image/png')
upgrade = M.jobctl('-op', 'upgrade', '-attachment', att['id'], '-version', '2')
v2_job = upgrade['job_id']
start_worker_healthy()
v2_ready = wait_ready(c, bob, att['id'], 120)
v2_signature = signature(v2_ready)
ok(v2_signature != control_signature, 'pipeline version 2 produced the same WebP as version 1')
state = M.jobctl('-op', 'status', '-attachment', att['id'])
ok(state['attachment']['ready_version'] == 2, 'ready_version is not 2 after v2')
ok({job['job_id']: job['status'] for job in state['jobs']}[v2_job] == 'ready', 'v2 job is not ready')
# Replay the failed v1 AFTER v2 is public. It processes successfully but is
# stale: ready_version stays 2 and the public variant hashes do not change.
replay = M.jobctl('-op', 'replay', '-attachment', att['id'], '-actor', 'track2-stale-test')
ok(replay['replayed_job_id'] == v1_job, 'replay selected a different job')
state = wait_job(
att['id'],
lambda value: {job['job_id']: job['status'] for job in value['jobs']}[v1_job] == 'ready',
120,
)
final = c.call('GET', '/api/v1/attachments/' + att['id'], actor=bob, schema='Attachment')['json']
ok(final['status'] == 'ready', 'attachment left ready after stale replay')
ok(final['variants'] and signature(final) == v2_signature, 'stale v1 overwrote the v2 result set')
ok(len(final['variants']) == 3, 'stale replay created extra variants')
ok(state['attachment']['ready_version'] == 2, 'stale replay lowered ready_version')
ok({job['job_id']: job['replay_count'] for job in state['jobs']}[v1_job] == 1,
'replay audit counter was not incremented')
stale_audit = int(M.psql(
"SELECT count(*) FROM job_audit WHERE job_id = '%s' AND event = 'completed_stale_version'" % v1_job))
ok(stale_audit == 1, 'stale completion is not audited exactly once')
evidence['stale_version'] = {
'attachment_id': att['id'],
'v1_job_id': v1_job,
'v2_job_id': v2_job,
'v1_failure': failed['error_code'],
'failed_registry_entry': entries[0],
'v2_variants': v2_signature,
'final_variants': signature(final),
'ready_version': state['attachment']['ready_version'],
'v1_replay_count': {job['job_id']: job['replay_count'] for job in state['jobs']}[v1_job],
'stale_audit_events': stale_audit,
}
print('PASS stale v1 replay cannot overwrite the v2 result')
def main():
def configure(parser):
parser.add_argument('--output', default=str(EVIDENCE))
args = arguments('Lab6 track 2 idempotency fault injection', configure)
M.BASE_URL = args.base_url or M.BASE_URL
c = Client(args.base_url, args.ca_file, timeout=5)
alice, bob, eve, chat = c.bootstrap()
evidence = {
'track': 2,
'title': 'proven idempotency of the versioned pipeline',
'when': now(),
'hypothesis': ('At-least-once delivery + deterministic version-keyed effects + '
'monotonic ready_version make duplicate, reordered, crashed and stale '
'deliveries safe without extra variants or lost confirmed jobs.'),
'protocol': ('Stop the worker or selected dependency, inject duplicate/old/retry '
'messages through cmd/jobctl, kill the worker at documented hooks, restart '
'the normal worker, and compare exact variant hashes against a control.'),
'checks': 0,
}
try:
start_worker_healthy()
control, _ = upload(c, alice, chat, 'control-v1.png')
control_ready = wait_ready(c, bob, control['id'], 120)
control_signature = signature(control_ready)
ok(len(control_signature) == 3, 'control does not expose three variants')
evidence['control'] = {'attachment_id': control['id'], 'variants': control_signature}
scenario_duplicate(c, alice, bob, chat, control_signature, evidence)
scenario_reorder(c, alice, bob, chat, control_signature, evidence)
scenario_stale_version(c, alice, bob, chat, control_signature, evidence)
evidence['invariants'] = {
'confirmed_jobs_not_lost': True,
'old_result_did_not_overwrite_new': True,
'no_extra_variants': True,
'delivery_semantics': 'at-least-once; effects are idempotent per (attachment_id, pipeline_version, variant)',
}
evidence['limitations'] = [
'Single Docker host; broker, PostgreSQL and S3 are single points of failure outside the tested restarts.',
'Fault injection is compiled into the worker but refuses to run outside APP_ENV=lab.',
'The experiment proves effect-level idempotency, not exactly-once delivery; duplicate messages are expected and acknowledged as no-ops.',
'Variant determinism is verified for the bundled synthetic fixtures and the two documented pipeline versions, not for every possible decoder input.',
]
finally:
try:
start_worker_healthy()
except Exception:
pass
evidence['checks'] = CHECKS
evidence['completed_at'] = now()
output = Path(args.output)
output.parent.mkdir(parents=True, exist_ok=True)
output.write_text(json.dumps(evidence, indent=2, ensure_ascii=False) + '\n', encoding='utf-8')
print('evidence:', output)
print('PASS: lab6 track 2 fault injection, %d assertions' % CHECKS)
if __name__ == '__main__':
try:
main()
except (Failure, ValueError, OSError, subprocess.TimeoutExpired) as exc:
print('FAIL:', str(exc))
raise SystemExit(1)
+2
View File
@@ -0,0 +1,2 @@
testdata/*.png
testdata/*.webp
+22
View File
@@ -0,0 +1,22 @@
MIT License
Copyright (c) 2024 Hugo Smits
Copyright (c) 2026 Karpeles Lab Inc
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.
+209
View File
@@ -0,0 +1,209 @@
[![Tests](https://github.com/KarpelesLab/gowebp/actions/workflows/test.yml/badge.svg)](https://github.com/KarpelesLab/gowebp/actions/workflows/test.yml)
[![Coverage Status](https://coveralls.io/repos/github/KarpelesLab/gowebp/badge.svg?branch=main)](https://coveralls.io/github/KarpelesLab/gowebp?branch=main)
[![Go Reference](https://pkg.go.dev/badge/github.com/KarpelesLab/gowebp.svg)](https://pkg.go.dev/github.com/KarpelesLab/gowebp)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
# gowebp
A pure-Go WebP codec. No `libwebp`, no `cgo`, no runtime dependencies
beyond `golang.org/x/image` (which is used for decoding only).
Encodes to either WebP format:
- **VP8L (lossless)** — default. Every pixel preserved exactly.
- **VP8 (lossy)** — opt-in via `Options.Lossy`. Full intra-only VP8
keyframe encoder with I16 + B_PRED + UV8 intra prediction, DCT +
Walsh-Hadamard transforms, boolean arithmetic coding, loop filter,
and reconstruction-based RD mode selection.
Also encodes WebP **animations** (ANIM/ANMF) with either codec, and
preserves **alpha channels** via ALPH chunks (raw or VP8L-compressed,
static or in-animation).
## Installation
```bash
go get github.com/KarpelesLab/gowebp
```
## Usage
### Lossless
```go
import "github.com/KarpelesLab/gowebp"
f, _ := os.Create(name)
defer f.Close()
if err := gowebp.Encode(f, img, nil); err != nil {
log.Fatal(err)
}
```
### Lossy
```go
err := gowebp.Encode(f, img, &gowebp.Options{
Lossy: true,
Quality: 75, // 0 (smallest) to 100 (best), default 75
Method: 4, // 0 (fastest) to 6 (highest quality), default 0
})
```
### Animation
```go
ani := gowebp.Animation{
Images: []image.Image{frame1, frame2, frame3},
Durations: []uint{100, 100, 100}, // ms per frame
Disposals: []uint{0, 0, 0}, // 0=keep, 1=clear
LoopCount: 0, // 0 = infinite
BackgroundColor: 0xffffffff, // BGRA
}
// Pass Options{Lossy: true} for VP8 frames; nil for VP8L.
gowebp.EncodeAll(f, &ani, nil)
```
### Decoding
```go
img, err := gowebp.Decode(r)
```
Wraps `golang.org/x/image/webp`. Also provides `DecodeIgnoreAlphaFlag`
for VP8X files where a misset alpha flag trips up the standard
decoder.
## Lossy method tiers
The `Method` field picks between different speed/quality/size
tradeoffs. Higher values spend more CPU per macroblock to produce
smaller or higher-quality output.
| Method | Strategy | Notes |
|---|---|---|
| 0 | I16 with DC_PRED only | fastest baseline |
| 1 | I16 with 4-mode SSE search | +1–3 dB over M0 |
| 2 | B_PRED with 10 I4 modes per sub-block | best on textured content |
| 3 | Per-MB I16/B_PRED arbitration (prediction SSE) | fast, good default |
| 4 | Per-MB arbitration with reconstruction-aware RDO | **recommended** |
| 5 | Dual-path (measure both I16 and B_PRED) | principled reference |
| 6 | Adds trailing-coefficient trellis trim | helps on high-freq content |
Encoding is goroutine-safe: each `Encode`/`EncodeAll` call is
self-contained and has no shared mutable state.
## Benchmarks
Measured on Intel i9-14900K (Linux, Go 1.25) against the 5 natural
photos linked from [Google's WebP Gallery](https://developers.google.com/speed/webp/gallery2).
Baseline is Go's `image/png` with `png.BestCompression`.
Reproduce:
```bash
NATIVEWEBP_FETCH=1 go test -run TestGalleryPSNR -v # populate testdata/
go test -bench=. -benchtime=5x
```
### File sizes (bytes per frame)
| Image | PNG | Lossless | Lossy Q=50 M=4 | Lossy Q=75 M=3 | Lossy Q=75 M=4 | Lossy Q=90 M=4 |
|---|---:|---:|---:|---:|---:|---:|
| [`1.png`](https://www.gstatic.com/webp/gallery3/1.png) (400×301) | 120 188 | **97 720** | 16 766 | 17 648 | 24 906 | 43 518 |
| [`2.png`](https://www.gstatic.com/webp/gallery3/2.png) (386×395) | 45 659 | **37 018** | 15 050 | 13 808 | 21 888 | 33 632 |
| [`3.png`](https://www.gstatic.com/webp/gallery3/3.png) (800×600) | 236 018 | **194 714** | 80 992 | 80 552 | 95 330 | 130 828 |
| [`4.png`](https://www.gstatic.com/webp/gallery3/4.png) (421×163) | 52 681 | **41 554** | 27 304 | 24 838 | 35 736 | 47 510 |
| [`5.png`](https://www.gstatic.com/webp/gallery3/5.png) (300×300) | 138 919 | **123 932** | 74 202 | 78 300 | 97 588 | 133 548 |
- **Lossless (VP8L)** averages 13–23 % smaller than PNG's best compression.
- **Lossy Q=75 M=3** is 1.8×–3.3× smaller than lossless on the same images.
- **Lossy Q=50 M=4** can reach 7× smaller than PNG while still
producing visually acceptable output on photos.
### Encode time (ns/op)
| Image | PNG | Lossless | Lossy Q=75 M=3 | Lossy Q=75 M=4 |
|---|---:|---:|---:|---:|
| `1.png` (400×301) | 38 034 | **25 745** | 30 476 | 30 629 |
| `2.png` (386×395) | 82 888 | **29 999** | 34 298 | 49 051 |
| `3.png` (800×600) | 152 804 | **100 415** | 110 645 | 117 259 |
| `4.png` (421×163) | 23 707 | **24 294** | 17 631 | 19 426 |
| `5.png` (300×300) | 54 435 | **20 294** | 27 094 | 27 931 |
All timings in microseconds for brevity: lossless WebP is **≈ 1.5–2.8×
faster than PNG** across the gallery, while producing smaller files.
Lossy encoding is typically within a small constant factor of
lossless speed.
### Quality (spec-correct Y-PSNR, lossy Q=75 M=3)
Y-PSNR measured against VP8 limited-range BT.601 (what a real decoder
shows). Higher is better; >40 dB is visually lossless on photographic
content.
| Image | Y-PSNR |
|---|---:|
| `1.png` | 39.2 dB |
| `2.png` | 42.2 dB |
| `3.png` | 43.5 dB |
| `4.png` | 38.7 dB |
| `5.png` | 36.7 dB |
Threshold floors on these numbers are asserted by `TestGalleryPSNR`
so future encoder changes can't quietly regress quality.
## BT.601 color handling
VP8 stores pixels in limited-range BT.601 YCbCr (luma 16–235, chroma
16–240) per RFC 6386. Go's stdlib `image/color.YCbCrToRGB` uses the
JFIF full-range inverse, which shifts the resulting RGB by 2–5 units
per channel when applied to VP8 samples.
`Decode` handles this automatically: for VP8 sources the returned
image is a `*gowebp.BT601YCbCr` (or `*gowebp.BT601NYCbCrA` when the
source has an ALPH chunk) whose `At()` method uses the spec-correct
limited-range BT.601 inverse. Calling `img.At(x, y).RGBA()` gives the
same RGB values a libwebp or browser decoder would produce.
Users who want the raw `*image.YCbCr` for zero-copy plane access
can type-assert to `*gowebp.BT601YCbCr` and read the embedded field:
```go
img, _ := gowebp.Decode(r)
if y, ok := img.(*gowebp.BT601YCbCr); ok {
rawYCbCr := y.YCbCr // *image.YCbCr with limited-range samples
_ = rawYCbCr
}
```
VP8L (lossless) sources decode to `*image.NRGBA` with exact pixel
fidelity and don't go through YCbCr, so no wrapping is applied.
## Implementation notes
The lossy VP8 encoder lives in `internal/vp8enc/` and is a pure-Go
implementation of **RFC 6386** (*The VP8 Data Format and Decoding
Guide*). The following open-source implementations were consulted as
references for bit-exact compatibility; no code was copied, but table
values (which are specification constants) were transcribed:
- [`golang.org/x/image/vp8`](https://pkg.go.dev/golang.org/x/image/vp8)
— pure-Go VP8 decoder, used as the round-trip test oracle (BSD-3-Clause).
- [`libwebp`](https://chromium.googlesource.com/webm/libwebp) — the
reference C encoder/decoder from Google (BSD-3-Clause).
- [`libvpx`](https://chromium.googlesource.com/webm/libvpx) — VP8/VP9
reference codec (BSD-3-Clause).
Every file in `internal/vp8enc/` references the relevant RFC 6386
section and the matching path in the x/image/vp8 decoder, which is
the oracle used by the test suite's round-trip integration tests.
Remaining work (tracked in the source, not here): full rate-distortion
optimization with calibrated λ; proper Viterbi trellis quantization
with context-aware token-tree rate estimation.
## License
MIT, same as the upstream project this was forked from
(`HugoSmits86/nativewebp`).
+62
View File
@@ -0,0 +1,62 @@
package gowebp
import (
//------------------------------
//general
//------------------------------
"bytes"
)
type bitWriter struct {
Buffer *bytes.Buffer
BitBuffer uint64
BitBufferSize int
}
func (w *bitWriter) writeBits(value uint64, n int) {
if n < 0 || n > 64 {
panic("Invalid bit count: must be between 1 and 64")
}
if value >= (1 << n) {
panic("too many bits for the given value")
}
w.BitBuffer |= (value << w.BitBufferSize)
w.BitBufferSize += n
w.writeThrough()
}
func (w *bitWriter) writeBytes(values []byte) {
for _, v := range values {
w.writeBits(uint64(v), 8)
}
}
func (w *bitWriter) writeCode(code huffmanCode) {
if code.Depth <= 0 {
return
}
value := uint64(code.Bits)
reversed := uint64(0)
for i := 0; i < code.Depth; i++ {
reversed = (reversed << 1) | (value & 1)
value >>= 1
}
w.writeBits(reversed, code.Depth)
}
func (w *bitWriter) alignByte() {
w.BitBufferSize = (w.BitBufferSize + 7) &^ 7
w.writeThrough()
}
func (w *bitWriter) writeThrough() {
for w.BitBufferSize >= 8 {
w.Buffer.WriteByte(byte(w.BitBuffer & 0xFF))
w.BitBuffer >>= 8
w.BitBufferSize -= 8
}
}
+173
View File
@@ -0,0 +1,173 @@
package gowebp
import (
"image"
"image/color"
)
// BT601YCbCrColor is a single pixel in VP8 limited-range BT.601 color
// space (luma 16–235, chroma 16–240), the color space WebP files
// actually store per RFC 6386.
//
// It exists because Go's stdlib `image/color.YCbCrToRGB` applies the
// JFIF (full-range) inverse even to values that were produced under
// limited-range encoding, which shifts the resulting RGB by 2–5 units
// per channel. BT601YCbCrColor.RGBA() uses the spec-correct inverse:
//
// R = clip((298·(Y-16) + 409·(Cr-128) + 128) >> 8)
// G = clip((298·(Y-16) - 100·(Cb-128) - 208·(Cr-128) + 128) >> 8)
// B = clip((298·(Y-16) + 516·(Cb-128) + 128) >> 8)
//
// Decode returns images whose pixels are BT601YCbCrColor (wrapped in
// BT601YCbCr or BT601NYCbCrA) for VP8 sources, so calling
// img.At(x, y).RGBA() produces the colors a real VP8 decoder (libwebp,
// browsers) would show.
type BT601YCbCrColor struct {
Y, Cb, Cr uint8
}
// RGBA implements color.Color using the VP8 spec's limited-range
// BT.601 inverse. Returns premultiplied 16-bit components (α is always
// 0xffff for this type).
func (c BT601YCbCrColor) RGBA() (r, g, b, a uint32) {
Y := int32(c.Y) - 16
Cb := int32(c.Cb) - 128
Cr := int32(c.Cr) - 128
R := (298*Y + 409*Cr + 128) >> 8
G := (298*Y - 100*Cb - 208*Cr + 128) >> 8
B := (298*Y + 516*Cb + 128) >> 8
if R < 0 {
R = 0
} else if R > 255 {
R = 255
}
if G < 0 {
G = 0
} else if G > 255 {
G = 255
}
if B < 0 {
B = 0
} else if B > 255 {
B = 255
}
// color.Color expects 16-bit values; 0x101 == 257 scales 0..255
// to 0..65535 the same way as stdlib's color types.
return uint32(R) * 0x101, uint32(G) * 0x101, uint32(B) * 0x101, 0xffff
}
// BT601NYCbCrAColor is BT601YCbCrColor with a non-premultiplied alpha
// channel. Used by the WebP decoder output when the source has an
// ALPH chunk.
type BT601NYCbCrAColor struct {
BT601YCbCrColor
A uint8
}
// RGBA returns premultiplied 16-bit components.
func (c BT601NYCbCrAColor) RGBA() (r, g, b, a uint32) {
r, g, b, _ = c.BT601YCbCrColor.RGBA()
a = uint32(c.A) * 0x101
// Premultiply.
r = r * a / 0xffff
g = g * a / 0xffff
b = b * a / 0xffff
return
}
// BT601YCbCrColorModel and BT601NYCbCrAColorModel convert an arbitrary
// color into the limited-range BT.601 representation.
var (
BT601YCbCrColorModel = color.ModelFunc(bt601YCbCrModel)
BT601NYCbCrAColorModel = color.ModelFunc(bt601NYCbCrAModel)
)
func bt601YCbCrModel(c color.Color) color.Color {
if _, ok := c.(BT601YCbCrColor); ok {
return c
}
r, g, b, _ := c.RGBA()
R := int32(r >> 8)
G := int32(g >> 8)
B := int32(b >> 8)
Y := (66*R + 129*G + 25*B + 128) >> 8 + 16
Cb := (-38*R - 74*G + 112*B + 128) >> 8 + 128
Cr := (112*R - 94*G - 18*B + 128) >> 8 + 128
return BT601YCbCrColor{
Y: clamp0255(Y),
Cb: clamp0255(Cb),
Cr: clamp0255(Cr),
}
}
func bt601NYCbCrAModel(c color.Color) color.Color {
if _, ok := c.(BT601NYCbCrAColor); ok {
return c
}
_, _, _, a := c.RGBA()
yc := bt601YCbCrModel(c).(BT601YCbCrColor)
return BT601NYCbCrAColor{BT601YCbCrColor: yc, A: uint8(a >> 8)}
}
func clamp0255(v int32) uint8 {
if v < 0 {
return 0
}
if v > 255 {
return 255
}
return uint8(v)
}
// BT601YCbCr wraps an *image.YCbCr whose samples are in VP8's
// limited-range BT.601. It forwards everything to the embedded image
// except At(), which returns BT601YCbCrColor for spec-correct RGB
// conversion.
//
// Callers who specifically want the raw stdlib YCbCr (e.g. for fast
// plane-level access) can dereference the embedded *image.YCbCr
// field directly.
type BT601YCbCr struct {
*image.YCbCr
}
func (b *BT601YCbCr) At(x, y int) color.Color {
return b.BT601YCbCrAt(x, y)
}
// BT601YCbCrAt is a typed helper that avoids the color.Color interface
// allocation when callers know they want BT601YCbCrColor.
func (b *BT601YCbCr) BT601YCbCrAt(x, y int) BT601YCbCrColor {
if !(image.Point{X: x, Y: y}.In(b.Rect)) {
return BT601YCbCrColor{}
}
yi := b.YOffset(x, y)
ci := b.COffset(x, y)
return BT601YCbCrColor{Y: b.Y[yi], Cb: b.Cb[ci], Cr: b.Cr[ci]}
}
func (b *BT601YCbCr) ColorModel() color.Model { return BT601YCbCrColorModel }
// BT601NYCbCrA wraps an *image.NYCbCrA for sources with an ALPH chunk.
type BT601NYCbCrA struct {
*image.NYCbCrA
}
func (b *BT601NYCbCrA) At(x, y int) color.Color {
return b.BT601NYCbCrAAt(x, y)
}
func (b *BT601NYCbCrA) BT601NYCbCrAAt(x, y int) BT601NYCbCrAColor {
if !(image.Point{X: x, Y: y}.In(b.Rect)) {
return BT601NYCbCrAColor{}
}
yi := b.YOffset(x, y)
ci := b.COffset(x, y)
ai := b.AOffset(x, y)
return BT601NYCbCrAColor{
BT601YCbCrColor: BT601YCbCrColor{Y: b.Y[yi], Cb: b.Cb[ci], Cr: b.Cr[ci]},
A: b.A[ai],
}
}
func (b *BT601NYCbCrA) ColorModel() color.Model { return BT601NYCbCrAColorModel }
+213
View File
@@ -0,0 +1,213 @@
package gowebp
import (
//------------------------------
//general
//------------------------------
"container/heap"
"sort"
)
type huffmanCode struct {
Symbol int
Bits int
Depth int
}
type node struct {
IsBranch bool
Weight int
Symbol int
BranchLeft *node
BranchRight *node
}
type nodeHeap []*node
func (h nodeHeap) Len() int { return len(h) }
func (h nodeHeap) Less(i, j int) bool { return h[i].Weight < h[j].Weight }
func (h nodeHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
func (h *nodeHeap) Push(x interface{}) { *h = append(*h, x.(*node)) }
func (h *nodeHeap) Pop() interface{} {
old := *h
n := len(old)
x := old[n-1]
*h = old[0 : n-1]
return x
}
func buildHuffmanTree(histo []int, maxDepth int) *node {
sum := 0
for _, x := range histo {
sum += x
}
minWeight := sum >> (maxDepth - 2)
nHeap := &nodeHeap{}
heap.Init(nHeap)
for s, w := range histo {
if w > 0 {
if w < minWeight {
w = minWeight
}
heap.Push(nHeap, &node{
Weight: w,
Symbol: s,
})
}
}
for nHeap.Len() < 1 {
heap.Push(nHeap, &node{
Weight: minWeight,
Symbol: 0,
})
}
for nHeap.Len() > 1 {
n1 := heap.Pop(nHeap).(*node)
n2 := heap.Pop(nHeap).(*node)
heap.Push(nHeap, &node{
IsBranch: true,
Weight: n1.Weight + n2.Weight,
BranchLeft: n1,
BranchRight: n2,
})
}
return heap.Pop(nHeap).(*node)
}
func buildhuffmanCodes(histo []int, maxDepth int) []huffmanCode {
codes := make([]huffmanCode, len(histo))
tree := buildHuffmanTree(histo, maxDepth)
if !tree.IsBranch {
codes[tree.Symbol] = huffmanCode{tree.Symbol, 0, -1}
return codes
}
var symbols []huffmanCode
setBitDepths(tree, &symbols, 0)
sort.Slice(symbols, func(i, j int) bool {
if symbols[i].Depth == symbols[j].Depth {
return symbols[i].Symbol < symbols[j].Symbol
}
return symbols[i].Depth < symbols[j].Depth
})
bits := 0
prevDepth := 0
for _, sym := range symbols {
bits <<= (sym.Depth - prevDepth)
codes[sym.Symbol].Symbol = sym.Symbol
codes[sym.Symbol].Bits = bits
codes[sym.Symbol].Depth = sym.Depth
bits++
prevDepth = sym.Depth
}
return codes
}
func setBitDepths(node *node, codes *[]huffmanCode, level int) {
if node == nil {
return
}
if !node.IsBranch {
*codes = append(*codes, huffmanCode{
Symbol: node.Symbol,
Depth: level,
})
return
}
setBitDepths(node.BranchLeft, codes, level + 1)
setBitDepths(node.BranchRight, codes, level + 1)
}
func writehuffmanCodes(w *bitWriter, codes []huffmanCode) {
var symbols [2]int
cnt := 0
for _, code := range codes {
if code.Depth != 0 {
if cnt < 2 {
symbols[cnt] = code.Symbol
}
cnt++
}
if cnt > 2 {
break
}
}
if cnt == 0 {
w.writeBits(1, 1)
w.writeBits(0, 3)
} else if cnt <= 2 && symbols[0] < 1 << 8 && symbols[1] < 1 << 8 {
w.writeBits(1, 1)
w.writeBits(uint64(cnt - 1), 1)
if symbols[0] <= 1 {
w.writeBits(0, 1)
w.writeBits(uint64(symbols[0]), 1)
} else {
w.writeBits(1, 1)
w.writeBits(uint64(symbols[0]), 8)
}
if cnt > 1 {
w.writeBits(uint64(symbols[1]), 8)
}
} else {
writeFullhuffmanCode(w, codes)
}
}
func writeFullhuffmanCode(w *bitWriter, codes []huffmanCode) {
histo := make([]int, 19)
for _, c := range codes {
histo[c.Depth]++
}
// lengthCodeOrder comes directly from the WebP specs!
var lengthCodeOrder = []int{
17, 18, 0, 1, 2, 3, 4, 5, 16, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
}
cnt := 0
for i, c := range lengthCodeOrder {
if histo[c] > 0 {
cnt = max(i + 1, 4)
}
}
w.writeBits(0, 1)
w.writeBits(uint64(cnt - 4), 4)
lengths := buildhuffmanCodes(histo, 7)
for i := 0; i < cnt; i++ {
l := lengths[lengthCodeOrder[i]].Depth
if l < 0 {
w.writeBits(uint64(1), 3)
continue
}
w.writeBits(uint64(l), 3)
}
w.writeBits(0, 1)
for _, c := range codes {
w.writeCode(lengths[c.Depth])
}
}
+155
View File
@@ -0,0 +1,155 @@
package vp8enc
// BoolEncoder is the VP8 boolean arithmetic coder in write (encode) mode.
//
// The algorithm is specified in RFC 6386 section 7 and follows the libvpx
// reference implementation. The output byte sequence is designed to be
// decoded by the matching decoder described in section 7.3; we verify this
// with a round-trip test against a mirror decoder that is bit-compatible
// with golang.org/x/image/vp8's `partition` type.
//
// Invariants held between calls to WriteBit:
// - rng (range) is in [128, 255]
// - low holds up to 24 bits of "pending" output
// - count tracks bits committed into low but not yet emitted;
// initial value -24 means we need 24 shift-ins before the first emit.
//
// Carry propagation: when an emitted byte would overflow due to a late
// addition in low, we propagate a +1 back through any preceding 0xff bytes,
// turning them into 0x00 and incrementing the first non-0xff byte before
// the run.
type BoolEncoder struct {
buf []byte
low uint32
rng uint32
count int32
}
// NewBoolEncoder returns a freshly initialized encoder writing to an
// internal buffer. Retrieve the output via Bytes after calling Finish.
func NewBoolEncoder() *BoolEncoder {
return &BoolEncoder{
rng: 255,
count: -24,
}
}
// Reset re-initializes the encoder to a fresh state, reusing the backing
// byte slice's capacity.
func (e *BoolEncoder) Reset() {
e.buf = e.buf[:0]
e.low = 0
e.rng = 255
e.count = -24
}
// WriteBit encodes a single bit against the given probability.
//
// prob is an 8-bit probability in [0, 255] where higher values bias toward
// the "0" branch being taken. 128 is the 50/50 (uniform) probability.
func (e *BoolEncoder) WriteBit(bit int, prob int) {
split := uint32(1) + (((e.rng - 1) * uint32(prob)) >> 8)
if bit != 0 {
e.low += split
e.rng -= split
} else {
e.rng = split
}
shift := int32(VP8Norm[e.rng])
e.rng <<= shift
e.count += shift
if e.count >= 0 {
offset := shift - e.count
if offset >= 1 && (e.low<<uint32(offset-1))&0x80000000 != 0 {
// Carry: propagate +1 back through the buffer, flipping 0xff
// bytes to 0x00 and incrementing the first byte before them.
x := len(e.buf) - 1
for x >= 0 && e.buf[x] == 0xff {
e.buf[x] = 0
x--
}
if x >= 0 {
e.buf[x]++
}
// If x < 0 we would propagate past the start of the buffer.
// This cannot happen in a well-formed encoder because the
// initial low is 0 and the first emitted byte is always < 0x80.
}
e.buf = append(e.buf, byte(e.low>>(24-uint32(offset))))
e.low = (e.low << uint32(offset)) & 0xffffff
shift = e.count
e.count -= 8
}
e.low <<= uint32(shift)
}
// WriteUint encodes n bits of value v high-bit first, each against prob.
func (e *BoolEncoder) WriteUint(v uint32, n int, prob int) {
for n > 0 {
n--
bit := int((v >> uint(n)) & 1)
e.WriteBit(bit, prob)
}
}
// WriteFlag encodes a 1-bit flag against uniform probability (128).
func (e *BoolEncoder) WriteFlag(v bool) {
bit := 0
if v {
bit = 1
}
e.WriteBit(bit, UniformProb)
}
// WriteInt encodes a signed value as magnitude + sign.
// Signed values are stored as |v| in n bits followed by a sign bit.
// Each bit is coded against prob (typically UniformProb).
func (e *BoolEncoder) WriteInt(v int32, n int, prob int) {
u := v
sign := 0
if v < 0 {
u = -v
sign = 1
}
e.WriteUint(uint32(u), n, prob)
e.WriteBit(sign, prob)
}
// WriteOptionalInt encodes a possibly-zero signed value. When v == 0 a
// single "not present" bit is emitted; otherwise a "present" bit followed
// by the magnitude+sign encoding.
func (e *BoolEncoder) WriteOptionalInt(v int32, n int, prob int) {
if v == 0 {
e.WriteBit(0, prob)
return
}
e.WriteBit(1, prob)
e.WriteInt(v, n, prob)
}
// Finish flushes any pending bits and returns the encoded byte stream.
// It emits enough trailing zero bits at prob 128 to drain the internal
// state, so every previously written bit is recoverable by the decoder.
//
// The returned slice is the encoder's internal buffer; callers that want
// to retain it across subsequent encodes must copy it.
func (e *BoolEncoder) Finish() []byte {
// Push out any committed bits still in `low` by writing 32 dummy 0
// bits at uniform probability. This is the approach used by libvpx's
// vp8_stop_encode.
for i := 0; i < 32; i++ {
e.WriteBit(0, UniformProb)
}
return e.buf
}
// Bytes returns the currently encoded bytes without flushing.
// Only meaningful for diagnostics; call Finish for a decodable stream.
func (e *BoolEncoder) Bytes() []byte {
return e.buf
}
// Len returns the number of bytes emitted so far.
func (e *BoolEncoder) Len() int {
return len(e.buf)
}
+381
View File
@@ -0,0 +1,381 @@
package vp8enc
// This file implements the forward and inverse transforms used by VP8:
// - 4x4 integer DCT on 4x4 spatial blocks of residuals
// - 4x4 Walsh-Hadamard (WHT) on the 16 Y DC coefficients of an I16 MB
//
// Both transforms are bit-exact to the libvpx reference (RFC 6386 sections
// 14.3 and 14.4). Output coefficients are stored in row-major 4x4 order
// (index 0 = top-left DC, index 1 = top-right, etc.).
// FDCT constants: approximations of 2*cos(pi/8)*sqrt(2) and related terms
// as rational multipliers, chosen so all intermediate products fit in
// int32 and the inverse matches.
const (
fdctC1 = 2217
fdctC2 = 5352
)
// FDCT4x4 performs a forward 4x4 DCT on 16 residual values in src and
// writes 16 coefficients to dst. Both slices are row-major 4x4 blocks.
//
// This is the libvpx vp8_short_fdct4x4_c form, which pairs exactly with the
// libvpx IDCT implemented below (and with the decoder at
// golang.org/x/image/vp8/idct.go).
//
// Known property: because the pass-1 rounding biases (14500, 7500) exceed
// their >>12 divisor, an all-zero residual produces tiny non-zero outputs
// in some odd-harmonic positions. These values are smaller than any
// realistic quantizer and quantize to 0 in practice; encoders rely on the
// "skip" flag to avoid emitting empty blocks.
//
// Input residual range is [-510, 510] (signed 10-bit). Output fits in int16.
func FDCT4x4(src []int16, dst []int16) {
_ = src[15]
_ = dst[15]
var tmp [16]int32
// Pass 1: rows.
for i := 0; i < 4; i++ {
r := i * 4
d0 := int32(src[r+0])
d1 := int32(src[r+1])
d2 := int32(src[r+2])
d3 := int32(src[r+3])
a1 := (d0 + d3) << 3
b1 := (d1 + d2) << 3
c1 := (d1 - d2) << 3
d1d := (d0 - d3) << 3
tmp[r+0] = a1 + b1
tmp[r+2] = a1 - b1
tmp[r+1] = (c1*fdctC1 + d1d*fdctC2 + 14500) >> 12
tmp[r+3] = (d1d*fdctC1 - c1*fdctC2 + 7500) >> 12
}
// Pass 2: columns.
for i := 0; i < 4; i++ {
a1 := tmp[i+0] + tmp[i+12]
b1 := tmp[i+4] + tmp[i+8]
c1 := tmp[i+4] - tmp[i+8]
d1 := tmp[i+0] - tmp[i+12]
dst[i+0] = int16((a1 + b1 + 7) >> 4)
dst[i+8] = int16((a1 - b1 + 7) >> 4)
col1 := (c1*fdctC1 + d1*fdctC2 + 12000) >> 16
if d1 != 0 {
col1++
}
dst[i+4] = int16(col1)
dst[i+12] = int16((d1*fdctC1 - c1*fdctC2 + 51000) >> 16)
}
}
// iDCT constants.
const (
sinpi8sqrt2 = 35468
cospi8sqrt2minus1 = 20091
)
// IDCT4x4 performs the inverse 4x4 DCT on 16 coefficients in src, writing
// 16 reconstructed residuals to dst. Output residuals may overshoot the
// input range by small amounts and must be clipped to [0, 255] after
// adding prediction.
func IDCT4x4(src []int16, dst []int16) {
_ = src[15]
_ = dst[15]
var tmp [16]int32
// Pass 1: rows.
for i := 0; i < 4; i++ {
r := i * 4
i0 := int32(src[r+0])
i1 := int32(src[r+1])
i2 := int32(src[r+2])
i3 := int32(src[r+3])
a := i0 + i2
b := i0 - i2
c := (i1 * sinpi8sqrt2) >> 16
c -= i3 + ((i3 * cospi8sqrt2minus1) >> 16)
d := i1 + ((i1 * cospi8sqrt2minus1) >> 16)
d += (i3 * sinpi8sqrt2) >> 16
tmp[r+0] = a + d
tmp[r+3] = a - d
tmp[r+1] = b + c
tmp[r+2] = b - c
}
// Pass 2: columns.
for i := 0; i < 4; i++ {
i0 := tmp[i+0]
i1 := tmp[i+4]
i2 := tmp[i+8]
i3 := tmp[i+12]
a := i0 + i2
b := i0 - i2
c := (i1 * sinpi8sqrt2) >> 16
c -= i3 + ((i3 * cospi8sqrt2minus1) >> 16)
d := i1 + ((i1 * cospi8sqrt2minus1) >> 16)
d += (i3 * sinpi8sqrt2) >> 16
dst[i+0] = int16((a + d + 4) >> 3)
dst[i+12] = int16((a - d + 4) >> 3)
dst[i+4] = int16((b + c + 4) >> 3)
dst[i+8] = int16((b - c + 4) >> 3)
}
}
// FWHT4x4 performs the forward Walsh-Hadamard transform on the 16 DC
// coefficients of an I16 macroblock's Y plane. Input is the 16 DC values
// (one per 4x4 Y sub-block, in raster order); output is the Y2 block.
func FWHT4x4(src []int16, dst []int16) {
_ = src[15]
_ = dst[15]
var tmp [16]int32
// Pass 1: rows.
for i := 0; i < 4; i++ {
r := i * 4
d0 := int32(src[r+0])
d1 := int32(src[r+1])
d2 := int32(src[r+2])
d3 := int32(src[r+3])
a1 := (d0 + d2) << 2
d1d := (d1 + d3) << 2
c1 := (d1 - d3) << 2
b1 := (d0 - d2) << 2
op0 := a1 + d1d
if a1 != 0 {
op0++
}
tmp[r+0] = op0
tmp[r+1] = b1 + c1
tmp[r+2] = b1 - c1
tmp[r+3] = a1 - d1d
}
// Pass 2: columns.
for i := 0; i < 4; i++ {
a1 := tmp[i+0] + tmp[i+8]
d1 := tmp[i+4] + tmp[i+12]
c1 := tmp[i+4] - tmp[i+12]
b1 := tmp[i+0] - tmp[i+8]
a2 := a1 + d1
b2 := b1 + c1
c2 := b1 - c1
d2 := a1 - d1
if a2 < 0 {
a2++
}
if b2 < 0 {
b2++
}
if c2 < 0 {
c2++
}
if d2 < 0 {
d2++
}
dst[i+0] = int16((a2 + 3) >> 3)
dst[i+4] = int16((b2 + 3) >> 3)
dst[i+8] = int16((c2 + 3) >> 3)
dst[i+12] = int16((d2 + 3) >> 3)
}
}
// IWHT4x4 performs the inverse WHT on the 16 Y2 coefficients, producing
// 16 reconstructed Y-DC values in dst.
func IWHT4x4(src []int16, dst []int16) {
_ = src[15]
_ = dst[15]
var tmp [16]int32
// Pass 1: rows.
for i := 0; i < 4; i++ {
r := i * 4
d0 := int32(src[r+0])
d1 := int32(src[r+1])
d2 := int32(src[r+2])
d3 := int32(src[r+3])
a := d0 + d3
b := d1 + d2
c := d1 - d2
d := d0 - d3
tmp[r+0] = a + b
tmp[r+1] = d + c
tmp[r+2] = a - b
tmp[r+3] = d - c
}
// Pass 2: columns.
for i := 0; i < 4; i++ {
a := tmp[i+0] + tmp[i+12]
b := tmp[i+4] + tmp[i+8]
c := tmp[i+4] - tmp[i+8]
d := tmp[i+0] - tmp[i+12]
dst[i+0] = int16((a + b + 3) >> 3)
dst[i+4] = int16((d + c + 3) >> 3)
dst[i+8] = int16((a - b + 3) >> 3)
dst[i+12] = int16((d - c + 3) >> 3)
}
}
// Quantizer bundles the six VP8 dequant factors needed to (de)quantize
// Y, Y2, and UV blocks. Indices: [0] = DC factor, [1] = AC factor.
type Quantizer struct {
Y1 [2]uint16 // Y AC blocks
Y2 [2]uint16 // Y DC (Walsh) block
UV [2]uint16 // Chroma AC blocks
}
// NewQuantizer derives dequant factors from a base quantizer index in
// [0, 127] using the exact lookup + adjustments specified in RFC 6386
// section 9.6 (mirrored from x/image/vp8 quant.go).
func NewQuantizer(qi int) Quantizer {
qi = clampInt(qi, 0, 127)
q := Quantizer{}
q.Y1[0] = DequantTableDC[qi]
q.Y1[1] = DequantTableAC[qi]
q.Y2[0] = DequantTableDC[qi] * 2
q.Y2[1] = DequantTableAC[qi] * 155 / 100
if q.Y2[1] < 8 {
q.Y2[1] = 8
}
// UV DC is clipped to dequantTableDC[117] = 132 by the spec's
// reference decoder.
uvDCIdx := qi
if uvDCIdx > 117 {
uvDCIdx = 117
}
q.UV[0] = DequantTableDC[uvDCIdx]
q.UV[1] = DequantTableAC[qi]
return q
}
// QuantizeBlock performs deadzone quantization of 16 coefficients given
// (dcFactor, acFactor) dequant values and a uniform deadzone bias. It
// writes the quantized integer coefficients to qOut and the
// reconstructed (dequantized) coefficients to dqOut. Returns the
// end-of-block index (1 + position of last non-zero coefficient in
// zigzag order) or 0 for an all-zero block.
//
// For per-position deadzone tuning (smaller bias on DC, larger on AC),
// use QuantizeBlockSplit instead.
func QuantizeBlock(
coef []int16, qOut []int16, dqOut []int16,
dcFactor, acFactor uint16, deadzone int32,
) int {
return QuantizeBlockSplit(coef, qOut, dqOut, dcFactor, acFactor, deadzone, deadzone)
}
// QuantizeBlockSplit performs deadzone quantization with separate
// deadzones for DC (zigzag position 0) and AC (all other positions).
// Typical use: dcDeadzone=0 (preserve DC accuracy, critical for
// perceived color and brightness) and acDeadzone=acFactor/4 (zero
// out small AC noise, saves entropy bits at little perceptual cost).
func QuantizeBlockSplit(
coef []int16, qOut []int16, dqOut []int16,
dcFactor, acFactor uint16, dcDeadzone, acDeadzone int32,
) int {
_ = coef[15]
_ = qOut[15]
_ = dqOut[15]
eob := 0
for i := 0; i < 16; i++ {
rc := Zigzag4x4[i]
f := int32(acFactor)
deadzone := acDeadzone
if rc == 0 {
f = int32(dcFactor)
deadzone = dcDeadzone
}
c := int32(coef[rc])
sign := int32(1)
abs := c
if c < 0 {
sign = -1
abs = -c
}
abs -= deadzone
if abs < 0 {
qOut[rc] = 0
dqOut[rc] = 0
continue
}
q := (abs + f/2) / f
if q == 0 {
qOut[rc] = 0
dqOut[rc] = 0
continue
}
qs := int16(sign * q)
qOut[rc] = qs
dqOut[rc] = int16(int32(qs) * f)
eob = i + 1
}
return eob
}
// TrellisTrim performs a simple trailing-noise trellis pass on a
// quantized 4x4 block: examines non-zero coefficients at mid-to-high
// zigzag positions with magnitude 1 and zeroes them in place. Moving
// the EOB earlier saves ~3-5 arithmetic-coded bits per coefficient at
// the cost of a small reconstruction error.
//
// This isn't the full Viterbi trellis (which would track token-context
// transitions across all 16 positions simultaneously), but captures
// the common pathology where the last few non-zero coefficients are
// ±1s that barely survived rounding.
//
// Returns the new EOB (count of coefficients up to and including the
// last non-zero in zigzag order).
func TrellisTrim(q *[16]int16, dq *[16]int16, acFactor uint16) int {
eob := 16
for eob > 0 && q[Zigzag4x4[eob-1]] == 0 {
eob--
}
// Walk backward from the last non-zero position. Zero out any
// ±1 coefficients at zigzag position >= 5 (past the low-frequency
// plateau where DC dominance ends). Lower positions represent the
// perceptually visible primary AC terms and are kept.
for eob >= 6 {
rc := Zigzag4x4[eob-1]
if q[rc] != 1 && q[rc] != -1 {
break
}
q[rc] = 0
dq[rc] = 0
eob--
}
return eob
}
// DequantizeBlock reconstructs coefficients from a quantized block in the
// zigzag-ordered input `q`. Writes to `coef` in raster 4x4 order.
// (This is the operation the decoder performs implicitly via the coefficient
// stream; exposed here for encoder-side reconstruction / RDO.)
func DequantizeBlock(q []int16, coef []int16, dcFactor, acFactor uint16) {
_ = q[15]
_ = coef[15]
for i := 0; i < 16; i++ {
rc := Zigzag4x4[i]
f := int32(acFactor)
if rc == 0 {
f = int32(dcFactor)
}
coef[rc] = int16(int32(q[rc]) * f)
}
}
File diff suppressed because it is too large Load Diff
+263
View File
@@ -0,0 +1,263 @@
package vp8enc
// Partition 0 header emission (RFC 6386 sections 9.2–9.7, 13.4–13.5).
//
// All bits here are encoded via the boolean arithmetic coder against
// UniformProb unless otherwise noted. Ordering is strict — the decoder at
// golang.org/x/image/vp8 parses in this exact sequence, and any drift
// makes every subsequent field misalign.
// WriteHeaderInit writes the keyframe-only fields at the top of partition 0:
// - color_space (1 bit, must be 0)
// - clamp_type (1 bit, typically 0 meaning "bicubic clamping")
func WriteHeaderInit(e *BoolEncoder) {
e.WriteBit(0, UniformProb) // color_space
e.WriteBit(0, UniformProb) // clamp_type
}
// WriteSegmentHeaderOff emits a "no segmentation" segment header: a single
// zero bit indicating use_segment is false.
func WriteSegmentHeaderOff(e *BoolEncoder) {
e.WriteBit(0, UniformProb)
}
// WriteFilterHeader emits the loop-filter header:
// simple (1 bit) | level (6 bits) | sharpness (3 bits) | useLFDelta (1 bit)
//
// level=0 disables the filter entirely (RFC 6386 section 15). Otherwise
// the decoder applies the normal filter (simple=false) or simple filter
// (simple=true) to the reconstructed frame as a post-processing pass
// that smooths block boundaries.
func WriteFilterHeader(e *BoolEncoder, simple bool, level, sharpness int) {
if level < 0 {
level = 0
}
if level > 63 {
level = 63
}
if sharpness < 0 {
sharpness = 0
}
if sharpness > 7 {
sharpness = 7
}
b := 0
if simple {
b = 1
}
e.WriteBit(b, UniformProb)
e.WriteUint(uint32(level), 6, UniformProb)
e.WriteUint(uint32(sharpness), 3, UniformProb)
e.WriteBit(0, UniformProb) // useLFDelta
}
// WriteFilterHeaderOff is a backward-compatible shortcut for
// WriteFilterHeader(e, false, 0, 0).
func WriteFilterHeaderOff(e *BoolEncoder) {
WriteFilterHeader(e, false, 0, 0)
}
// WriteLog2NumParts writes the log2 of the number of coefficient partitions
// (0..3 → 1, 2, 4, 8 partitions).
func WriteLog2NumParts(e *BoolEncoder, log2 int) {
e.WriteUint(uint32(log2), 2, UniformProb)
}
// WriteQuantHeader emits the quantizer indexer: base Y AC index in 7 bits
// followed by five optional deltas (Y1 DC, Y2 DC, Y2 AC, UV DC, UV AC).
// Set all deltas to 0 for simple mode.
func WriteQuantHeader(e *BoolEncoder, baseQ int) {
e.WriteUint(uint32(baseQ&0x7f), 7, UniformProb)
e.WriteOptionalInt(0, 4, UniformProb) // y1dc_delta_q
e.WriteOptionalInt(0, 4, UniformProb) // y2dc_delta_q
e.WriteOptionalInt(0, 4, UniformProb) // y2ac_delta_q
e.WriteOptionalInt(0, 4, UniformProb) // uvdc_delta_q
e.WriteOptionalInt(0, 4, UniformProb) // uvac_delta_q
}
// WriteRefreshEntropyProbs emits the single "refresh entropy probs" flag.
// Keyframe-only. 0 means the next frame does not inherit updated probs
// (we're still a static image encoder so this is always 0).
func WriteRefreshEntropyProbs(e *BoolEncoder) {
e.WriteBit(0, UniformProb)
}
// WriteTokenProbUpdates emits the 4×8×3×11 = 1056 "should we update this
// prob?" bits, each coded against TokenProbUpdateProb. We never update, so
// every emitted bit is 0. The decoder MUST consume exactly this many bits
// in this exact order.
func WriteTokenProbUpdates(e *BoolEncoder) {
for i := 0; i < NumPlanes; i++ {
for j := 0; j < NumBands; j++ {
for k := 0; k < NumContexts; k++ {
for l := 0; l < NumProbs; l++ {
e.WriteBit(0, int(TokenProbUpdateProb[i][j][k][l]))
}
}
}
}
}
// WriteSkipProb emits mb_no_skip_coeff plus, if true, an 8-bit skip
// probability. If skipProbOn is true, per-MB skip bits follow; if false,
// every MB carries full residuals.
func WriteSkipProb(e *BoolEncoder, skipProbOn bool, prob uint8) {
if !skipProbOn {
e.WriteBit(0, UniformProb)
return
}
e.WriteBit(1, UniformProb)
e.WriteUint(uint32(prob), 8, UniformProb)
}
// Y16 mode enum used by WriteMBModes. The decoder tree is:
//
// readBit(156) -> if 0: readBit(163) -> 0:DC, 1:VE
// -> if 1: readBit(128) -> 0:HE, 1:TM
const (
ModeDC = 0
ModeVE = 1
ModeHE = 2
ModeTM = 3
)
// WriteMBModes writes the per-macroblock mode fields for an I16 MB:
//
// usePredY16 (1 bit at prob 145), predY16, predC8.
// Must be called once per MB, after any skip bit, in MB raster order.
func WriteMBModes(e *BoolEncoder, predY16, predC8 int) {
e.WriteBit(1, 145) // usePredY16 = true (I16 mode)
// I16 Y mode tree.
switch predY16 {
case ModeDC:
e.WriteBit(0, 156)
e.WriteBit(0, 163)
case ModeVE:
e.WriteBit(0, 156)
e.WriteBit(1, 163)
case ModeHE:
e.WriteBit(1, 156)
e.WriteBit(0, 128)
case ModeTM:
e.WriteBit(1, 156)
e.WriteBit(1, 128)
}
writeUVMode(e, predC8)
}
// WriteMBModesBPred writes the per-macroblock mode fields for a B_PRED
// MB: usePredY16=0, 16 I4 modes (tree-coded against PredProb[above][left]),
// then the UV mode.
//
// modes[j][i] is the I4 mode for sub-block at (i, j) in the MB.
// aboveModes[i] is the mode of the sub-block above sub-block column i
// (bottom-row modes of the MB above, or ModeI4DC if on the frame edge).
// leftModes is updated in place: on entry, leftModes[j] is the mode of
// the sub-block to the left of sub-block row j; on return, leftModes[j]
// holds the mode of this MB's rightmost sub-block in row j (i.e. the
// input context for the NEXT MB to the right).
// aboveModes is also updated in place to reflect the bottom-row modes
// of this MB.
func WriteMBModesBPred(e *BoolEncoder, modes *[4][4]int, aboveModes *[4]int, leftModes *[4]int, predC8 int) {
e.WriteBit(0, 145) // usePredY16 = false (B_PRED)
for j := 0; j < 4; j++ {
l := leftModes[j]
for i := 0; i < 4; i++ {
mode := modes[j][i]
writeI4Mode(e, mode, aboveModes[i], l)
l = mode
aboveModes[i] = mode
}
leftModes[j] = l
}
writeUVMode(e, predC8)
}
// writeI4Mode emits the tree-coded I4 mode given the modes of the
// sub-blocks above and to the left. Tree structure from RFC 6386 section
// 11.5, mirroring parsePredModeY4 in x/image/vp8/pred.go.
func writeI4Mode(e *BoolEncoder, mode, above, left int) {
prob := &PredProb[above][left]
switch mode {
case ModeI4DC:
e.WriteBit(0, int(prob[0]))
case ModeI4TM:
e.WriteBit(1, int(prob[0]))
e.WriteBit(0, int(prob[1]))
case ModeI4VE:
e.WriteBit(1, int(prob[0]))
e.WriteBit(1, int(prob[1]))
e.WriteBit(0, int(prob[2]))
case ModeI4HE:
e.WriteBit(1, int(prob[0]))
e.WriteBit(1, int(prob[1]))
e.WriteBit(1, int(prob[2]))
e.WriteBit(0, int(prob[3]))
e.WriteBit(0, int(prob[4]))
case ModeI4RD:
e.WriteBit(1, int(prob[0]))
e.WriteBit(1, int(prob[1]))
e.WriteBit(1, int(prob[2]))
e.WriteBit(0, int(prob[3]))
e.WriteBit(1, int(prob[4]))
e.WriteBit(0, int(prob[5]))
case ModeI4VR:
e.WriteBit(1, int(prob[0]))
e.WriteBit(1, int(prob[1]))
e.WriteBit(1, int(prob[2]))
e.WriteBit(0, int(prob[3]))
e.WriteBit(1, int(prob[4]))
e.WriteBit(1, int(prob[5]))
case ModeI4LD:
e.WriteBit(1, int(prob[0]))
e.WriteBit(1, int(prob[1]))
e.WriteBit(1, int(prob[2]))
e.WriteBit(1, int(prob[3]))
e.WriteBit(0, int(prob[6]))
case ModeI4VL:
e.WriteBit(1, int(prob[0]))
e.WriteBit(1, int(prob[1]))
e.WriteBit(1, int(prob[2]))
e.WriteBit(1, int(prob[3]))
e.WriteBit(1, int(prob[6]))
e.WriteBit(0, int(prob[7]))
case ModeI4HD:
e.WriteBit(1, int(prob[0]))
e.WriteBit(1, int(prob[1]))
e.WriteBit(1, int(prob[2]))
e.WriteBit(1, int(prob[3]))
e.WriteBit(1, int(prob[6]))
e.WriteBit(1, int(prob[7]))
e.WriteBit(0, int(prob[8]))
case ModeI4HU:
e.WriteBit(1, int(prob[0]))
e.WriteBit(1, int(prob[1]))
e.WriteBit(1, int(prob[2]))
e.WriteBit(1, int(prob[3]))
e.WriteBit(1, int(prob[6]))
e.WriteBit(1, int(prob[7]))
e.WriteBit(1, int(prob[8]))
}
}
func writeUVMode(e *BoolEncoder, predC8 int) {
switch predC8 {
case ModeDC:
e.WriteBit(0, 142)
case ModeVE:
e.WriteBit(1, 142)
e.WriteBit(0, 114)
case ModeHE:
e.WriteBit(1, 142)
e.WriteBit(1, 114)
e.WriteBit(0, 183)
case ModeTM:
e.WriteBit(1, 142)
e.WriteBit(1, 114)
e.WriteBit(1, 183)
}
}
+318
View File
@@ -0,0 +1,318 @@
package vp8enc
// Forward intra prediction for VP8 encoding.
//
// Predictors are pure functions: given an input block's neighbors (top row,
// left column, top-left corner) they produce the predicted pixel values
// which the encoder subtracts from the source to get residuals. The
// neighbors come from already-reconstructed (i.e. lossy) MB data, matching
// exactly what the decoder will see.
//
// This file implements I16 (16×16 luma block) and UV8 (8×8 chroma block)
// modes: DC, VE (vertical), HE (horizontal), TM (true-motion/Paeth-ish).
// The four I4 modes and six diagonal I4 modes land in a later phase.
//
// Reference: RFC 6386 chapter 12; cross-checked against x/image/vp8/predfunc.go.
// PredictI16 fills dst[0..16][0..16] (row-major, stride 16) with the
// predicted pixels of a 16x16 block, given the reconstructed neighbors:
// - topLeft: single pixel at (x-1, y-1)
// - topRow: 16 pixels along the top edge at (x..x+15, y-1)
// - leftCol: 16 pixels along the left edge at (x-1, y..y+15)
// - hasTop, hasLeft indicate whether those neighbors are valid MBs
// (i.e. mby > 0 for top, mbx > 0 for left). When false, the
// corresponding side uses the default filler (0x7f for top, 0x81 for
// left) and DC mode switches to the appropriate variant.
func PredictI16(dst *[256]byte, mode int, topRow, leftCol *[16]byte, topLeft byte, hasTop, hasLeft bool) {
switch mode {
case ModeDC:
var sum uint32
cnt := uint32(0)
if hasTop {
for i := 0; i < 16; i++ {
sum += uint32(topRow[i])
}
cnt += 16
}
if hasLeft {
for j := 0; j < 16; j++ {
sum += uint32(leftCol[j])
}
cnt += 16
}
var avg byte
switch {
case cnt == 32:
avg = byte((sum + 16) >> 5)
case cnt == 16:
avg = byte((sum + 8) >> 4)
default:
avg = 0x80
}
for j := 0; j < 16; j++ {
for i := 0; i < 16; i++ {
dst[j*16+i] = avg
}
}
case ModeVE:
// Copy top row to every row.
for j := 0; j < 16; j++ {
for i := 0; i < 16; i++ {
dst[j*16+i] = topRow[i]
}
}
case ModeHE:
for j := 0; j < 16; j++ {
v := leftCol[j]
for i := 0; i < 16; i++ {
dst[j*16+i] = v
}
}
case ModeTM:
tl := int32(topLeft)
for j := 0; j < 16; j++ {
l := int32(leftCol[j])
for i := 0; i < 16; i++ {
t := int32(topRow[i])
dst[j*16+i] = byte(clampInt32(t+l-tl, 0, 255))
}
}
}
}
// PredictUV8 fills an 8x8 block with predicted chroma values. Semantics
// match PredictI16 but sized to 8.
func PredictUV8(dst *[64]byte, mode int, topRow, leftCol *[8]byte, topLeft byte, hasTop, hasLeft bool) {
switch mode {
case ModeDC:
var sum uint32
cnt := uint32(0)
if hasTop {
for i := 0; i < 8; i++ {
sum += uint32(topRow[i])
}
cnt += 8
}
if hasLeft {
for j := 0; j < 8; j++ {
sum += uint32(leftCol[j])
}
cnt += 8
}
var avg byte
switch {
case cnt == 16:
avg = byte((sum + 8) >> 4)
case cnt == 8:
avg = byte((sum + 4) >> 3)
default:
avg = 0x80
}
for j := 0; j < 8; j++ {
for i := 0; i < 8; i++ {
dst[j*8+i] = avg
}
}
case ModeVE:
for j := 0; j < 8; j++ {
for i := 0; i < 8; i++ {
dst[j*8+i] = topRow[i]
}
}
case ModeHE:
for j := 0; j < 8; j++ {
v := leftCol[j]
for i := 0; i < 8; i++ {
dst[j*8+i] = v
}
}
case ModeTM:
tl := int32(topLeft)
for j := 0; j < 8; j++ {
l := int32(leftCol[j])
for i := 0; i < 8; i++ {
t := int32(topRow[i])
dst[j*8+i] = byte(clampInt32(t+l-tl, 0, 255))
}
}
}
}
// SumSquaredError returns the sum of squared differences between two
// equal-length byte slices, reinterpreted as pixel values. Used for mode
// selection (min-SSE search).
func SumSquaredError(a, b []byte) int64 {
n := len(a)
if len(b) < n {
n = len(b)
}
var sum int64
for i := 0; i < n; i++ {
d := int64(a[i]) - int64(b[i])
sum += d * d
}
return sum
}
// PredictI4 fills dst with the 16 predicted pixels of one 4x4 sub-block
// for the given mode. Neighbors:
// - tl: top-left corner pixel (at y-1, x-1)
// - top[0..3]: 4 pixels directly above (at y-1, x..x+3)
// - top[4..7]: 4 pixels to the top-right (at y-1, x+4..x+7);
// for right-column sub-blocks these are the MB-level overhang values
// (RFC 6386 section 12.2 / x/image/vp8 prepareYBR's column-24..27 fill)
// - left[0..3]: 4 pixels along the left column (at y..y+3, x-1)
func PredictI4(dst *[16]byte, mode int, tl byte, top *[8]byte, left *[4]byte) {
a := int32(tl)
b := int32(top[0])
c := int32(top[1])
d := int32(top[2])
e := int32(top[3])
f := int32(top[4])
g := int32(top[5])
h := int32(top[6])
h2 := int32(top[7]) // eighth column pixel; used by LD for g+2h+h averaging
_ = h2 // (h_extra not all modes need it; keep for parity)
p := int32(left[0])
q := int32(left[1])
r := int32(left[2])
s := int32(left[3])
setRow := func(row int, v0, v1, v2, v3 byte) {
dst[row*4+0] = v0
dst[row*4+1] = v1
dst[row*4+2] = v2
dst[row*4+3] = v3
}
switch mode {
case ModeI4DC:
avg := byte((b + c + d + e + p + q + r + s + 4) >> 3)
for i := 0; i < 16; i++ {
dst[i] = avg
}
case ModeI4TM:
for j := 0; j < 4; j++ {
lj := int32(left[j])
for i := 0; i < 4; i++ {
ti := int32(top[i])
dst[j*4+i] = byte(clampInt32(ti+lj-a, 0, 255))
}
}
case ModeI4VE:
abc := byte((a + 2*b + c + 2) >> 2)
bcd := byte((b + 2*c + d + 2) >> 2)
cde := byte((c + 2*d + e + 2) >> 2)
def := byte((d + 2*e + f + 2) >> 2)
for j := 0; j < 4; j++ {
setRow(j, abc, bcd, cde, def)
}
case ModeI4HE:
apq := byte((a + 2*p + q + 2) >> 2)
pqr := byte((p + 2*q + r + 2) >> 2)
qrs := byte((q + 2*r + s + 2) >> 2)
rss := byte((r + 2*s + s + 2) >> 2)
for i := 0; i < 4; i++ {
dst[0*4+i] = apq
dst[1*4+i] = pqr
dst[2*4+i] = qrs
dst[3*4+i] = rss
}
case ModeI4RD:
srq := byte((s + 2*r + q + 2) >> 2)
rqp := byte((r + 2*q + p + 2) >> 2)
qpa := byte((q + 2*p + a + 2) >> 2)
pab := byte((p + 2*a + b + 2) >> 2)
abc := byte((a + 2*b + c + 2) >> 2)
bcd := byte((b + 2*c + d + 2) >> 2)
cde := byte((c + 2*d + e + 2) >> 2)
setRow(0, pab, abc, bcd, cde)
setRow(1, qpa, pab, abc, bcd)
setRow(2, rqp, qpa, pab, abc)
setRow(3, srq, rqp, qpa, pab)
case ModeI4VR:
ab := byte((a + b + 1) >> 1)
bc := byte((b + c + 1) >> 1)
cd := byte((c + d + 1) >> 1)
de := byte((d + e + 1) >> 1)
rqp := byte((r + 2*q + p + 2) >> 2)
qpa := byte((q + 2*p + a + 2) >> 2)
pab := byte((p + 2*a + b + 2) >> 2)
abc := byte((a + 2*b + c + 2) >> 2)
bcd := byte((b + 2*c + d + 2) >> 2)
cde := byte((c + 2*d + e + 2) >> 2)
setRow(0, ab, bc, cd, de)
setRow(1, pab, abc, bcd, cde)
setRow(2, qpa, ab, bc, cd)
setRow(3, rqp, pab, abc, bcd)
case ModeI4LD:
abc := byte((b + 2*c + d + 2) >> 2)
bcd := byte((c + 2*d + e + 2) >> 2)
cde := byte((d + 2*e + f + 2) >> 2)
def := byte((e + 2*f + g + 2) >> 2)
efg := byte((f + 2*g + h + 2) >> 2)
fgh := byte((g + 2*h + h2 + 2) >> 2)
ghh := byte((h + 2*h2 + h2 + 2) >> 2)
setRow(0, abc, bcd, cde, def)
setRow(1, bcd, cde, def, efg)
setRow(2, cde, def, efg, fgh)
setRow(3, def, efg, fgh, ghh)
case ModeI4VL:
ab := byte((b + c + 1) >> 1)
bc := byte((c + d + 1) >> 1)
cd := byte((d + e + 1) >> 1)
de := byte((e + f + 1) >> 1)
abc := byte((b + 2*c + d + 2) >> 2)
bcd := byte((c + 2*d + e + 2) >> 2)
cde := byte((d + 2*e + f + 2) >> 2)
def := byte((e + 2*f + g + 2) >> 2)
efg := byte((f + 2*g + h + 2) >> 2)
fgh := byte((g + 2*h + h2 + 2) >> 2)
setRow(0, ab, bc, cd, de)
setRow(1, abc, bcd, cde, def)
setRow(2, bc, cd, de, efg)
setRow(3, bcd, cde, def, fgh)
case ModeI4HD:
sr := byte((s + r + 1) >> 1)
rq := byte((r + q + 1) >> 1)
qp := byte((q + p + 1) >> 1)
pa := byte((p + a + 1) >> 1)
srq := byte((s + 2*r + q + 2) >> 2)
rqp := byte((r + 2*q + p + 2) >> 2)
qpa := byte((q + 2*p + a + 2) >> 2)
pab := byte((p + 2*a + b + 2) >> 2)
abc := byte((a + 2*b + c + 2) >> 2)
bcd := byte((b + 2*c + d + 2) >> 2)
setRow(0, pa, pab, abc, bcd)
setRow(1, qp, qpa, pa, pab)
setRow(2, rq, rqp, qp, qpa)
setRow(3, sr, srq, rq, rqp)
case ModeI4HU:
pq := byte((p + q + 1) >> 1)
qr := byte((q + r + 1) >> 1)
rs := byte((r + s + 1) >> 1)
pqr := byte((p + 2*q + r + 2) >> 2)
qrs := byte((q + 2*r + s + 2) >> 2)
rss := byte((r + 2*s + s + 2) >> 2)
sss := byte(s)
setRow(0, pq, pqr, qr, qrs)
setRow(1, qr, qrs, rs, rss)
setRow(2, rs, rss, sss, sss)
setRow(3, sss, sss, sss, sss)
}
}
+673
View File
@@ -0,0 +1,673 @@
// Package vp8enc implements a VP8 (lossy) keyframe encoder for WebP.
//
// All constants in this file are taken directly from RFC 6386
// (The VP8 Data Format and Decoding Guide). They are facts about the codec,
// not original authorship, and are used here as specification constants.
//
// Cross-referenced against the pure-Go decoder at golang.org/x/image/vp8
// (BSD-3-Clause) to guarantee bit-exact roundtrip compatibility.
package vp8enc
// Plane indices (RFC 6386 section 13.3).
const (
PlaneY1WithY2 = 0 // Y AC coefficients when MB has a Y2 block
PlaneY2 = 1 // Y2 DC-plane (16 DC coefficients combined via WHT)
PlaneUV = 2 // Chroma
PlaneY1SansY2 = 3 // Y coefficients when MB has no Y2 (B_PRED mode)
NumPlanes = 4
)
const (
NumBands = 8
NumContexts = 3
NumProbs = 11
)
// UniformProb is the canonical 50/50 probability used for uncoded bits
// carried through the boolean coder (RFC 6386 section 7).
const UniformProb = 128
// Zigzag4x4 maps DCT zigzag order to raster 4x4 indices (RFC 6386 section 13).
// IMPORTANT: this is NOT the JPEG zigzag.
var Zigzag4x4 = [16]int{0, 1, 4, 8, 5, 2, 3, 6, 9, 12, 13, 10, 7, 11, 14, 15}
// CoefBands maps a coefficient's zigzag position to one of 8 coding bands
// (RFC 6386 section 13.3). Used as an index into the token probability table.
var CoefBands = [16]int{0, 1, 2, 3, 6, 4, 5, 6, 6, 6, 6, 6, 6, 6, 6, 7}
// Token values (RFC 6386 section 13.2).
const (
DctEOB = 0 // End of block
DctZero = 1
DctVal1 = 2
DctVal2 = 3
DctVal3 = 4
DctVal4 = 5
DctCat1 = 6 // [5..6]
DctCat2 = 7 // [7..10]
DctCat3 = 8 // [11..18]
DctCat4 = 9 // [19..34]
DctCat5 = 10 // [35..66]
DctCat6 = 11 // [67..2048]
NumTokens = 12
)
// Category extra-bits specifications (RFC 6386 section 13.2).
type CategoryInfo struct {
Base int // base value for this category
Bits []int // probabilities for each extra bit (high bit first)
}
// DctCategories is indexed by (token-DctCat1). Each entry gives the base
// value of the category and the fixed probability table used to code the
// magnitude extra bits.
var DctCategories = [6]CategoryInfo{
{Base: 5, Bits: []int{159}},
{Base: 7, Bits: []int{165, 145}},
{Base: 11, Bits: []int{173, 148, 140}},
{Base: 19, Bits: []int{176, 155, 140, 135}},
{Base: 35, Bits: []int{180, 157, 141, 134, 130}},
{Base: 67, Bits: []int{254, 254, 243, 230, 196, 177, 153, 140, 133, 130, 129}},
}
// Token tree structure (RFC 6386 section 13.2 figure). Each internal node
// has a probability (from the context tables) and two children. Traversing
// left on a "0" bit, right on a "1" bit. The encoder walks the tree from
// the token value back to the root to produce the bit sequence.
//
// Tree layout (-token means leaf with that token value):
//
// root
// / \
// EOB node1
// / \
// Zero node2
// / \
// Val1 node3
// / \
// node4 node5
// / \ / \
// Val2 Val3 Cat1 node6 ...
var CoefTree = [22]int8{
-DctEOB, 2,
-DctZero, 4,
-DctVal1, 6,
8, 12,
-DctVal2, 10,
-DctVal3, -DctVal4,
14, 16,
-DctCat1, -DctCat2,
18, 20,
-DctCat3, -DctCat4,
-DctCat5, -DctCat6,
}
// Block scan order: for coding coefficients, we walk position 0..15 in
// zigzag order. When a block has a Y2 (DC predicted separately), the Y1
// plane starts at zigzag index 1 (i.e. skips DC).
//
// CoefFirst[plane] = starting zigzag index.
var CoefFirst = [NumPlanes]int{
PlaneY1WithY2: 1, // skip DC
PlaneY2: 0,
PlaneUV: 0,
PlaneY1SansY2: 0,
}
// VP8Norm[i] returns the number of left-shifts needed to bring value i into
// the range [128, 255]. Used during boolean-coder range renormalization.
// Indexed 0..255; VP8Norm[0] is unused (range can never be zero).
var VP8Norm = [256]uint8{
0, 7, 6, 6, 5, 5, 5, 5, 4, 4, 4, 4, 4, 4, 4, 4,
3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
}
// DequantTableDC and DequantTableAC are the quantizer lookup tables
// (RFC 6386 section 14.1). Index is the "quantizer index" in [0, 127].
var DequantTableDC = [128]uint16{
4, 5, 6, 7, 8, 9, 10, 10,
11, 12, 13, 14, 15, 16, 17, 17,
18, 19, 20, 20, 21, 21, 22, 22,
23, 23, 24, 25, 25, 26, 27, 28,
29, 30, 31, 32, 33, 34, 35, 36,
37, 37, 38, 39, 40, 41, 42, 43,
44, 45, 46, 46, 47, 48, 49, 50,
51, 52, 53, 54, 55, 56, 57, 58,
59, 60, 61, 62, 63, 64, 65, 66,
67, 68, 69, 70, 71, 72, 73, 74,
75, 76, 76, 77, 78, 79, 80, 81,
82, 83, 84, 85, 86, 87, 88, 89,
91, 93, 95, 96, 98, 100, 101, 102,
104, 106, 108, 110, 112, 114, 116, 118,
122, 124, 126, 128, 130, 132, 134, 136,
138, 140, 143, 145, 148, 151, 154, 157,
}
var DequantTableAC = [128]uint16{
4, 5, 6, 7, 8, 9, 10, 11,
12, 13, 14, 15, 16, 17, 18, 19,
20, 21, 22, 23, 24, 25, 26, 27,
28, 29, 30, 31, 32, 33, 34, 35,
36, 37, 38, 39, 40, 41, 42, 43,
44, 45, 46, 47, 48, 49, 50, 51,
52, 53, 54, 55, 56, 57, 58, 60,
62, 64, 66, 68, 70, 72, 74, 76,
78, 80, 82, 84, 86, 88, 90, 92,
94, 96, 98, 100, 102, 104, 106, 108,
110, 112, 114, 116, 119, 122, 125, 128,
131, 134, 137, 140, 143, 146, 149, 152,
155, 158, 161, 164, 167, 170, 173, 177,
181, 185, 189, 193, 197, 201, 205, 209,
213, 217, 221, 225, 229, 234, 239, 245,
249, 254, 259, 264, 269, 274, 279, 284,
}
// DefaultTokenProb is the default probability table used to arithmetic-code
// DCT/WHT coefficients (RFC 6386 section 13.5). Indexed by
// [plane][band][context][prob].
var DefaultTokenProb = [NumPlanes][NumBands][NumContexts][NumProbs]uint8{
{
{
{128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128},
{128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128},
{128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128},
},
{
{253, 136, 254, 255, 228, 219, 128, 128, 128, 128, 128},
{189, 129, 242, 255, 227, 213, 255, 219, 128, 128, 128},
{106, 126, 227, 252, 214, 209, 255, 255, 128, 128, 128},
},
{
{1, 98, 248, 255, 236, 226, 255, 255, 128, 128, 128},
{181, 133, 238, 254, 221, 234, 255, 154, 128, 128, 128},
{78, 134, 202, 247, 198, 180, 255, 219, 128, 128, 128},
},
{
{1, 185, 249, 255, 243, 255, 128, 128, 128, 128, 128},
{184, 150, 247, 255, 236, 224, 128, 128, 128, 128, 128},
{77, 110, 216, 255, 236, 230, 128, 128, 128, 128, 128},
},
{
{1, 101, 251, 255, 241, 255, 128, 128, 128, 128, 128},
{170, 139, 241, 252, 236, 209, 255, 255, 128, 128, 128},
{37, 116, 196, 243, 228, 255, 255, 255, 128, 128, 128},
},
{
{1, 204, 254, 255, 245, 255, 128, 128, 128, 128, 128},
{207, 160, 250, 255, 238, 128, 128, 128, 128, 128, 128},
{102, 103, 231, 255, 211, 171, 128, 128, 128, 128, 128},
},
{
{1, 152, 252, 255, 240, 255, 128, 128, 128, 128, 128},
{177, 135, 243, 255, 234, 225, 128, 128, 128, 128, 128},
{80, 129, 211, 255, 194, 224, 128, 128, 128, 128, 128},
},
{
{1, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128},
{246, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128},
{255, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128},
},
},
{
{
{198, 35, 237, 223, 193, 187, 162, 160, 145, 155, 62},
{131, 45, 198, 221, 172, 176, 220, 157, 252, 221, 1},
{68, 47, 146, 208, 149, 167, 221, 162, 255, 223, 128},
},
{
{1, 149, 241, 255, 221, 224, 255, 255, 128, 128, 128},
{184, 141, 234, 253, 222, 220, 255, 199, 128, 128, 128},
{81, 99, 181, 242, 176, 190, 249, 202, 255, 255, 128},
},
{
{1, 129, 232, 253, 214, 197, 242, 196, 255, 255, 128},
{99, 121, 210, 250, 201, 198, 255, 202, 128, 128, 128},
{23, 91, 163, 242, 170, 187, 247, 210, 255, 255, 128},
},
{
{1, 200, 246, 255, 234, 255, 128, 128, 128, 128, 128},
{109, 178, 241, 255, 231, 245, 255, 255, 128, 128, 128},
{44, 130, 201, 253, 205, 192, 255, 255, 128, 128, 128},
},
{
{1, 132, 239, 251, 219, 209, 255, 165, 128, 128, 128},
{94, 136, 225, 251, 218, 190, 255, 255, 128, 128, 128},
{22, 100, 174, 245, 186, 161, 255, 199, 128, 128, 128},
},
{
{1, 182, 249, 255, 232, 235, 128, 128, 128, 128, 128},
{124, 143, 241, 255, 227, 234, 128, 128, 128, 128, 128},
{35, 77, 181, 251, 193, 211, 255, 205, 128, 128, 128},
},
{
{1, 157, 247, 255, 236, 231, 255, 255, 128, 128, 128},
{121, 141, 235, 255, 225, 227, 255, 255, 128, 128, 128},
{45, 99, 188, 251, 195, 217, 255, 224, 128, 128, 128},
},
{
{1, 1, 251, 255, 213, 255, 128, 128, 128, 128, 128},
{203, 1, 248, 255, 255, 128, 128, 128, 128, 128, 128},
{137, 1, 177, 255, 224, 255, 128, 128, 128, 128, 128},
},
},
{
{
{253, 9, 248, 251, 207, 208, 255, 192, 128, 128, 128},
{175, 13, 224, 243, 193, 185, 249, 198, 255, 255, 128},
{73, 17, 171, 221, 161, 179, 236, 167, 255, 234, 128},
},
{
{1, 95, 247, 253, 212, 183, 255, 255, 128, 128, 128},
{239, 90, 244, 250, 211, 209, 255, 255, 128, 128, 128},
{155, 77, 195, 248, 188, 195, 255, 255, 128, 128, 128},
},
{
{1, 24, 239, 251, 218, 219, 255, 205, 128, 128, 128},
{201, 51, 219, 255, 196, 186, 128, 128, 128, 128, 128},
{69, 46, 190, 239, 201, 218, 255, 228, 128, 128, 128},
},
{
{1, 191, 251, 255, 255, 128, 128, 128, 128, 128, 128},
{223, 165, 249, 255, 213, 255, 128, 128, 128, 128, 128},
{141, 124, 248, 255, 255, 128, 128, 128, 128, 128, 128},
},
{
{1, 16, 248, 255, 255, 128, 128, 128, 128, 128, 128},
{190, 36, 230, 255, 236, 255, 128, 128, 128, 128, 128},
{149, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128},
},
{
{1, 226, 255, 128, 128, 128, 128, 128, 128, 128, 128},
{247, 192, 255, 128, 128, 128, 128, 128, 128, 128, 128},
{240, 128, 255, 128, 128, 128, 128, 128, 128, 128, 128},
},
{
{1, 134, 252, 255, 255, 128, 128, 128, 128, 128, 128},
{213, 62, 250, 255, 255, 128, 128, 128, 128, 128, 128},
{55, 93, 255, 128, 128, 128, 128, 128, 128, 128, 128},
},
{
{128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128},
{128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128},
{128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128},
},
},
{
{
{202, 24, 213, 235, 186, 191, 220, 160, 240, 175, 255},
{126, 38, 182, 232, 169, 184, 228, 174, 255, 187, 128},
{61, 46, 138, 219, 151, 178, 240, 170, 255, 216, 128},
},
{
{1, 112, 230, 250, 199, 191, 247, 159, 255, 255, 128},
{166, 109, 228, 252, 211, 215, 255, 174, 128, 128, 128},
{39, 77, 162, 232, 172, 180, 245, 178, 255, 255, 128},
},
{
{1, 52, 220, 246, 198, 199, 249, 220, 255, 255, 128},
{124, 74, 191, 243, 183, 193, 250, 221, 255, 255, 128},
{24, 71, 130, 219, 154, 170, 243, 182, 255, 255, 128},
},
{
{1, 182, 225, 249, 219, 240, 255, 224, 128, 128, 128},
{149, 150, 226, 252, 216, 205, 255, 171, 128, 128, 128},
{28, 108, 170, 242, 183, 194, 254, 223, 255, 255, 128},
},
{
{1, 81, 230, 252, 204, 203, 255, 192, 128, 128, 128},
{123, 102, 209, 247, 188, 196, 255, 233, 128, 128, 128},
{20, 95, 153, 243, 164, 173, 255, 203, 128, 128, 128},
},
{
{1, 222, 248, 255, 216, 213, 128, 128, 128, 128, 128},
{168, 175, 246, 252, 235, 205, 255, 255, 128, 128, 128},
{47, 116, 215, 255, 211, 212, 255, 255, 128, 128, 128},
},
{
{1, 121, 236, 253, 212, 214, 255, 255, 128, 128, 128},
{141, 84, 213, 252, 201, 202, 255, 219, 128, 128, 128},
{42, 80, 160, 240, 162, 185, 255, 205, 128, 128, 128},
},
{
{1, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128},
{244, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128},
{238, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128},
},
},
}
// NumPredModes is the number of I4 prediction modes.
const NumPredModes = 10
// I4 mode enum (extends the I16/UV8 Mode* constants). These match the
// decoder's predDC..predHU values so we can use them as array indices into
// PredProb.
const (
ModeI4DC = 0
ModeI4TM = 1
ModeI4VE = 2
ModeI4HE = 3
ModeI4RD = 4
ModeI4VR = 5
ModeI4LD = 6
ModeI4VL = 7
ModeI4HD = 8
ModeI4HU = 9
)
// PredProb is the probability table used to tree-code I4 sub-block modes
// given the modes of the sub-blocks above and to the left (RFC 6386
// section 11.5). Indexed [above][left][prob-index 0..8].
var PredProb = [NumPredModes][NumPredModes][9]uint8{
{
{231, 120, 48, 89, 115, 113, 120, 152, 112},
{152, 179, 64, 126, 170, 118, 46, 70, 95},
{175, 69, 143, 80, 85, 82, 72, 155, 103},
{56, 58, 10, 171, 218, 189, 17, 13, 152},
{114, 26, 17, 163, 44, 195, 21, 10, 173},
{121, 24, 80, 195, 26, 62, 44, 64, 85},
{144, 71, 10, 38, 171, 213, 144, 34, 26},
{170, 46, 55, 19, 136, 160, 33, 206, 71},
{63, 20, 8, 114, 114, 208, 12, 9, 226},
{81, 40, 11, 96, 182, 84, 29, 16, 36},
},
{
{134, 183, 89, 137, 98, 101, 106, 165, 148},
{72, 187, 100, 130, 157, 111, 32, 75, 80},
{66, 102, 167, 99, 74, 62, 40, 234, 128},
{41, 53, 9, 178, 241, 141, 26, 8, 107},
{74, 43, 26, 146, 73, 166, 49, 23, 157},
{65, 38, 105, 160, 51, 52, 31, 115, 128},
{104, 79, 12, 27, 217, 255, 87, 17, 7},
{87, 68, 71, 44, 114, 51, 15, 186, 23},
{47, 41, 14, 110, 182, 183, 21, 17, 194},
{66, 45, 25, 102, 197, 189, 23, 18, 22},
},
{
{88, 88, 147, 150, 42, 46, 45, 196, 205},
{43, 97, 183, 117, 85, 38, 35, 179, 61},
{39, 53, 200, 87, 26, 21, 43, 232, 171},
{56, 34, 51, 104, 114, 102, 29, 93, 77},
{39, 28, 85, 171, 58, 165, 90, 98, 64},
{34, 22, 116, 206, 23, 34, 43, 166, 73},
{107, 54, 32, 26, 51, 1, 81, 43, 31},
{68, 25, 106, 22, 64, 171, 36, 225, 114},
{34, 19, 21, 102, 132, 188, 16, 76, 124},
{62, 18, 78, 95, 85, 57, 50, 48, 51},
},
{
{193, 101, 35, 159, 215, 111, 89, 46, 111},
{60, 148, 31, 172, 219, 228, 21, 18, 111},
{112, 113, 77, 85, 179, 255, 38, 120, 114},
{40, 42, 1, 196, 245, 209, 10, 25, 109},
{88, 43, 29, 140, 166, 213, 37, 43, 154},
{61, 63, 30, 155, 67, 45, 68, 1, 209},
{100, 80, 8, 43, 154, 1, 51, 26, 71},
{142, 78, 78, 16, 255, 128, 34, 197, 171},
{41, 40, 5, 102, 211, 183, 4, 1, 221},
{51, 50, 17, 168, 209, 192, 23, 25, 82},
},
{
{138, 31, 36, 171, 27, 166, 38, 44, 229},
{67, 87, 58, 169, 82, 115, 26, 59, 179},
{63, 59, 90, 180, 59, 166, 93, 73, 154},
{40, 40, 21, 116, 143, 209, 34, 39, 175},
{47, 15, 16, 183, 34, 223, 49, 45, 183},
{46, 17, 33, 183, 6, 98, 15, 32, 183},
{57, 46, 22, 24, 128, 1, 54, 17, 37},
{65, 32, 73, 115, 28, 128, 23, 128, 205},
{40, 3, 9, 115, 51, 192, 18, 6, 223},
{87, 37, 9, 115, 59, 77, 64, 21, 47},
},
{
{104, 55, 44, 218, 9, 54, 53, 130, 226},
{64, 90, 70, 205, 40, 41, 23, 26, 57},
{54, 57, 112, 184, 5, 41, 38, 166, 213},
{30, 34, 26, 133, 152, 116, 10, 32, 134},
{39, 19, 53, 221, 26, 114, 32, 73, 255},
{31, 9, 65, 234, 2, 15, 1, 118, 73},
{75, 32, 12, 51, 192, 255, 160, 43, 51},
{88, 31, 35, 67, 102, 85, 55, 186, 85},
{56, 21, 23, 111, 59, 205, 45, 37, 192},
{55, 38, 70, 124, 73, 102, 1, 34, 98},
},
{
{125, 98, 42, 88, 104, 85, 117, 175, 82},
{95, 84, 53, 89, 128, 100, 113, 101, 45},
{75, 79, 123, 47, 51, 128, 81, 171, 1},
{57, 17, 5, 71, 102, 57, 53, 41, 49},
{38, 33, 13, 121, 57, 73, 26, 1, 85},
{41, 10, 67, 138, 77, 110, 90, 47, 114},
{115, 21, 2, 10, 102, 255, 166, 23, 6},
{101, 29, 16, 10, 85, 128, 101, 196, 26},
{57, 18, 10, 102, 102, 213, 34, 20, 43},
{117, 20, 15, 36, 163, 128, 68, 1, 26},
},
{
{102, 61, 71, 37, 34, 53, 31, 243, 192},
{69, 60, 71, 38, 73, 119, 28, 222, 37},
{68, 45, 128, 34, 1, 47, 11, 245, 171},
{62, 17, 19, 70, 146, 85, 55, 62, 70},
{37, 43, 37, 154, 100, 163, 85, 160, 1},
{63, 9, 92, 136, 28, 64, 32, 201, 85},
{75, 15, 9, 9, 64, 255, 184, 119, 16},
{86, 6, 28, 5, 64, 255, 25, 248, 1},
{56, 8, 17, 132, 137, 255, 55, 116, 128},
{58, 15, 20, 82, 135, 57, 26, 121, 40},
},
{
{164, 50, 31, 137, 154, 133, 25, 35, 218},
{51, 103, 44, 131, 131, 123, 31, 6, 158},
{86, 40, 64, 135, 148, 224, 45, 183, 128},
{22, 26, 17, 131, 240, 154, 14, 1, 209},
{45, 16, 21, 91, 64, 222, 7, 1, 197},
{56, 21, 39, 155, 60, 138, 23, 102, 213},
{83, 12, 13, 54, 192, 255, 68, 47, 28},
{85, 26, 85, 85, 128, 128, 32, 146, 171},
{18, 11, 7, 63, 144, 171, 4, 4, 246},
{35, 27, 10, 146, 174, 171, 12, 26, 128},
},
{
{190, 80, 35, 99, 180, 80, 126, 54, 45},
{85, 126, 47, 87, 176, 51, 41, 20, 32},
{101, 75, 128, 139, 118, 146, 116, 128, 85},
{56, 41, 15, 176, 236, 85, 37, 9, 62},
{71, 30, 17, 119, 118, 255, 17, 18, 138},
{101, 38, 60, 138, 55, 70, 43, 26, 142},
{146, 36, 19, 30, 171, 255, 97, 27, 20},
{138, 45, 61, 62, 219, 1, 81, 188, 64},
{32, 41, 20, 117, 151, 142, 20, 21, 163},
{112, 19, 12, 61, 195, 128, 48, 4, 24},
},
}
// TokenProbUpdateProb is the probability of a token-probability update bit
// (RFC 6386 section 13.4). The encoder emits 4*8*3*11=1056 arithmetic-coded
// bits against this table, each indicating whether the corresponding
// DefaultTokenProb entry is overridden. We currently never override, so
// every emitted bit is 0; but they must still be emitted or the decoder
// misaligns.
var TokenProbUpdateProb = [NumPlanes][NumBands][NumContexts][NumProbs]uint8{
{
{
{255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255},
{255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255},
{255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255},
},
{
{176, 246, 255, 255, 255, 255, 255, 255, 255, 255, 255},
{223, 241, 252, 255, 255, 255, 255, 255, 255, 255, 255},
{249, 253, 253, 255, 255, 255, 255, 255, 255, 255, 255},
},
{
{255, 244, 252, 255, 255, 255, 255, 255, 255, 255, 255},
{234, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255},
{253, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255},
},
{
{255, 246, 254, 255, 255, 255, 255, 255, 255, 255, 255},
{239, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255},
{254, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255},
},
{
{255, 248, 254, 255, 255, 255, 255, 255, 255, 255, 255},
{251, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255},
{255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255},
},
{
{255, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255},
{251, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255},
{254, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255},
},
{
{255, 254, 253, 255, 254, 255, 255, 255, 255, 255, 255},
{250, 255, 254, 255, 254, 255, 255, 255, 255, 255, 255},
{254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255},
},
{
{255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255},
{255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255},
{255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255},
},
},
{
{
{217, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255},
{225, 252, 241, 253, 255, 255, 254, 255, 255, 255, 255},
{234, 250, 241, 250, 253, 255, 253, 254, 255, 255, 255},
},
{
{255, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255},
{223, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255},
{238, 253, 254, 254, 255, 255, 255, 255, 255, 255, 255},
},
{
{255, 248, 254, 255, 255, 255, 255, 255, 255, 255, 255},
{249, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255},
{255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255},
},
{
{255, 253, 255, 255, 255, 255, 255, 255, 255, 255, 255},
{247, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255},
{255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255},
},
{
{255, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255},
{252, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255},
{255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255},
},
{
{255, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255},
{253, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255},
{255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255},
},
{
{255, 254, 253, 255, 255, 255, 255, 255, 255, 255, 255},
{250, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255},
{254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255},
},
{
{255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255},
{255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255},
{255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255},
},
},
{
{
{186, 251, 250, 255, 255, 255, 255, 255, 255, 255, 255},
{234, 251, 244, 254, 255, 255, 255, 255, 255, 255, 255},
{251, 251, 243, 253, 254, 255, 254, 255, 255, 255, 255},
},
{
{255, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255},
{236, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255},
{251, 253, 253, 254, 254, 255, 255, 255, 255, 255, 255},
},
{
{255, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255},
{254, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255},
{255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255},
},
{
{255, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255},
{254, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255},
{254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255},
},
{
{255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255},
{254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255},
{255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255},
},
{
{255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255},
{255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255},
{255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255},
},
{
{255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255},
{255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255},
{255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255},
},
{
{255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255},
{255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255},
{255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255},
},
},
{
{
{248, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255},
{250, 254, 252, 254, 255, 255, 255, 255, 255, 255, 255},
{248, 254, 249, 253, 255, 255, 255, 255, 255, 255, 255},
},
{
{255, 253, 253, 255, 255, 255, 255, 255, 255, 255, 255},
{246, 253, 253, 255, 255, 255, 255, 255, 255, 255, 255},
{252, 254, 251, 254, 254, 255, 255, 255, 255, 255, 255},
},
{
{255, 254, 252, 255, 255, 255, 255, 255, 255, 255, 255},
{248, 254, 253, 255, 255, 255, 255, 255, 255, 255, 255},
{253, 255, 254, 254, 255, 255, 255, 255, 255, 255, 255},
},
{
{255, 251, 254, 255, 255, 255, 255, 255, 255, 255, 255},
{245, 251, 254, 255, 255, 255, 255, 255, 255, 255, 255},
{253, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255},
},
{
{255, 251, 253, 255, 255, 255, 255, 255, 255, 255, 255},
{252, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255},
{255, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255},
},
{
{255, 252, 255, 255, 255, 255, 255, 255, 255, 255, 255},
{249, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255},
{255, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255},
},
{
{255, 255, 253, 255, 255, 255, 255, 255, 255, 255, 255},
{250, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255},
{255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255},
},
{
{255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255},
{254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255},
{255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255},
},
},
}
+198
View File
@@ -0,0 +1,198 @@
package vp8enc
// DCT/WHT coefficient token encoding (RFC 6386 chapter 13).
//
// Coefficients are emitted in VP8 zigzag order through the boolean coder
// against a context-adaptive probability model indexed by (plane, band,
// previous-coef-category). The model is the token-tree defined in section
// 13.2. This encoder is the exact inverse of parseResiduals4 in
// golang.org/x/image/vp8/reconstruct.go — if the encoder and decoder walk
// the same tree in the same order against the same probability row, the
// bitstream roundtrips.
//
// The bands table has 17 entries to handle n=16 during EOB tail-matching
// after position 15. The extra entry is unused for probability lookup in
// the inner loop but the decoder reads bands[16]=0 for the trailing check
// that our encoder mirrors.
var bandsExt = [17]uint8{0, 1, 2, 3, 6, 4, 5, 6, 6, 6, 6, 6, 6, 6, 6, 7, 0}
// Category-3/4/5/6 extra-bit probability tables (RFC 6386 section 13.2,
// cross-checked against x/image/vp8/reconstruct.go's cat3456).
var cat3Bits = [3]uint8{173, 148, 140}
var cat4Bits = [4]uint8{176, 155, 140, 135}
var cat5Bits = [5]uint8{180, 157, 141, 134, 130}
var cat6Bits = [11]uint8{254, 254, 243, 230, 196, 177, 153, 140, 133, 130, 129}
// WriteCoefBlock encodes 16 quantized coefficients (raster order) for one
// 4x4 block. Returns 1 if the block had any non-zero coefficient, 0
// otherwise — matches the decoder's return value, which the caller
// propagates as the "non-zero" context for subsequent blocks.
//
// coefs is indexed by raster (0..15); the zigzag mapping is applied
// internally. plane selects the probability plane; context is 0/1/2 from
// neighbor non-zero counts; tokenProb is the current probability table
// (we always use DefaultTokenProb, but passed in for future prob-update
// support). skipFirstCoeff == true for I16 Y1 blocks (DC is in the Y2
// block, not this one), starting from zigzag position 1.
func WriteCoefBlock(
enc *BoolEncoder,
coefs *[16]int16,
plane, context int,
tokenProb *[NumPlanes][NumBands][NumContexts][NumProbs]uint8,
skipFirstCoeff bool,
) int {
start := 0
if skipFirstCoeff {
start = 1
}
// Find the index (in zigzag order) of the last non-zero coefficient.
lastNZ := -1
for i := start; i < 16; i++ {
z := Zigzag4x4[i]
if coefs[z] != 0 {
lastNZ = i
}
}
p := &tokenProb[plane][bandsExt[start]][context]
// Leading EOB check at the block's first zigzag position.
if lastNZ < 0 {
enc.WriteBit(0, int((*p)[0]))
return 0
}
enc.WriteBit(1, int((*p)[0]))
n := start
for n < 16 {
z := Zigzag4x4[n]
v := int32(coefs[z])
absV := v
if absV < 0 {
absV = -absV
}
if absV == 0 {
enc.WriteBit(0, int((*p)[1]))
p = &tokenProb[plane][bandsExt[n+1]][0]
n++
continue
}
// Non-zero.
enc.WriteBit(1, int((*p)[1]))
var nextCtx int
if absV == 1 {
enc.WriteBit(0, int((*p)[2]))
nextCtx = 1
} else {
enc.WriteBit(1, int((*p)[2]))
writeValueGE2(enc, int(absV), p)
nextCtx = 2
}
// Sign bit.
signBit := 0
if v < 0 {
signBit = 1
}
enc.WriteBit(signBit, UniformProb)
// EOB marker after this coefficient, unless we're at the very end.
if n == lastNZ {
if n+1 < 16 {
// Encode EOB against the NEXT position's prob row.
pEOB := &tokenProb[plane][bandsExt[n+1]][nextCtx]
enc.WriteBit(0, int((*pEOB)[0]))
}
return 1
}
// Not the last non-zero — emit "continue" bit and advance.
pNext := &tokenProb[plane][bandsExt[n+1]][nextCtx]
enc.WriteBit(1, int((*pNext)[0]))
p = pNext
n++
}
return 1
}
// writeValueGE2 emits the magnitude of a quantized coefficient with
// absolute value >= 2. It mirrors the decoder's value-tree traversal:
//
// 2 : 0 0
// 3, 4 : 0 1 X (cat 0a/0b via p[5])
// 5, 6 : 1 0 0 X (cat 1 via fixed 159)
// 7..10 : 1 0 1 X X (cat 2 via 165, 145)
// 11..2114 : 1 1 <cat> <bits> (cat 3..6)
//
// p is the current position's probability row.
func writeValueGE2(enc *BoolEncoder, v int, p *[NumProbs]uint8) {
switch {
case v == 2:
enc.WriteBit(0, int(p[3]))
enc.WriteBit(0, int(p[4]))
case v == 3:
enc.WriteBit(0, int(p[3]))
enc.WriteBit(1, int(p[4]))
enc.WriteBit(0, int(p[5]))
case v == 4:
enc.WriteBit(0, int(p[3]))
enc.WriteBit(1, int(p[4]))
enc.WriteBit(1, int(p[5]))
case v == 5 || v == 6:
enc.WriteBit(1, int(p[3]))
enc.WriteBit(0, int(p[6]))
enc.WriteBit(0, int(p[7]))
enc.WriteBit(v-5, 159)
case v >= 7 && v <= 10:
enc.WriteBit(1, int(p[3]))
enc.WriteBit(0, int(p[6]))
enc.WriteBit(1, int(p[7]))
r := v - 7
enc.WriteBit((r>>1)&1, 165)
enc.WriteBit(r&1, 145)
case v >= 11 && v <= 18:
writeCategoryHeader(enc, p, 0)
writeExtraBits(enc, v-11, cat3Bits[:])
case v >= 19 && v <= 34:
writeCategoryHeader(enc, p, 1)
writeExtraBits(enc, v-19, cat4Bits[:])
case v >= 35 && v <= 66:
writeCategoryHeader(enc, p, 2)
writeExtraBits(enc, v-35, cat5Bits[:])
case v >= 67:
// Cat 6 nominally caps at 2048 per RFC; clamp for safety.
if v > 2048 {
v = 2048
}
writeCategoryHeader(enc, p, 3)
writeExtraBits(enc, v-67, cat6Bits[:])
}
}
// writeCategoryHeader emits the 4 tree-selector bits that identify
// categories 3..6. cat ∈ {0,1,2,3} corresponds to RFC categories 3..6.
func writeCategoryHeader(enc *BoolEncoder, p *[NumProbs]uint8, cat int) {
enc.WriteBit(1, int(p[3]))
enc.WriteBit(1, int(p[6]))
b1 := (cat >> 1) & 1
b0 := cat & 1
enc.WriteBit(b1, int(p[8]))
enc.WriteBit(b0, int(p[9+b1]))
}
// writeExtraBits emits the magnitude bits of a category (3..6) in
// MSB-first order against the per-category fixed probabilities.
func writeExtraBits(enc *BoolEncoder, remainder int, probs []uint8) {
n := len(probs)
for i := 0; i < n; i++ {
bit := (remainder >> (n - 1 - i)) & 1
enc.WriteBit(bit, int(probs[i]))
}
}
+168
View File
@@ -0,0 +1,168 @@
package vp8enc
import (
"image"
"image/draw"
)
// Frame is a macroblock-aligned YCbCr 4:2:0 image in planar layout.
//
// The display size is (Width, Height) in pixels. The allocated planes are
// padded up to the next multiple of 16 (luma) or 8 (chroma) so macroblock
// loops can read uniformly. Edge rows/columns are filled by replicating
// the last valid pixel, matching libwebp's padding policy.
type Frame struct {
Width, Height int
MBWidth int // ceil(Width/16)
MBHeight int // ceil(Height/16)
Y []byte // YStride * MBHeight*16
Cb []byte // UVStride * MBHeight*8
Cr []byte // UVStride * MBHeight*8
YStride int // == MBWidth*16
UVStride int // == MBWidth*8
}
// NewFrame allocates a Frame with zeroed planes sized for (w, h) display
// dimensions. The planes are MB-aligned.
func NewFrame(w, h int) *Frame {
mbW := (w + 15) >> 4
mbH := (h + 15) >> 4
f := &Frame{
Width: w,
Height: h,
MBWidth: mbW,
MBHeight: mbH,
YStride: mbW * 16,
UVStride: mbW * 8,
}
f.Y = make([]byte, f.YStride*mbH*16)
f.Cb = make([]byte, f.UVStride*mbH*8)
f.Cr = make([]byte, f.UVStride*mbH*8)
return f
}
// RGBAToFrame converts an image.Image to a macroblock-aligned 4:2:0 YCbCr
// Frame using BT.601 fixed-point coefficients (matching RFC 6386 and
// libwebp's picture_csp_enc.c). Padding pixels beyond (Width, Height)
// replicate the nearest edge pixel.
//
// Alpha is ignored here; ALPH chunk handling is the caller's responsibility.
func RGBAToFrame(img image.Image) *Frame {
b := img.Bounds()
w, h := b.Dx(), b.Dy()
frame := NewFrame(w, h)
// Materialize to NRGBA so we read RGB in a predictable layout.
nrgba, ok := img.(*image.NRGBA)
if !ok || !nrgba.Rect.Eq(b) {
nrgba = image.NewNRGBA(image.Rect(0, 0, w, h))
draw.Draw(nrgba, nrgba.Bounds(), img, b.Min, draw.Src)
b = nrgba.Bounds()
}
srcMinX := b.Min.X
srcMinY := b.Min.Y
// Luma: every pixel.
for y := 0; y < frame.MBHeight*16; y++ {
sy := clampInt(y, 0, h-1)
srcRow := srcMinY + sy
rowOff := y * frame.YStride
base := nrgba.PixOffset(srcMinX, srcRow)
pix := nrgba.Pix
for x := 0; x < frame.MBWidth*16; x++ {
sx := clampInt(x, 0, w-1)
p := base + sx*4
r := int32(pix[p])
g := int32(pix[p+1])
bl := int32(pix[p+2])
// Y = (66R + 129G + 25B + 128) >> 8 + 16
Y := (66*r+129*g+25*bl+128)>>8 + 16
frame.Y[rowOff+x] = byte(clampInt32(Y, 0, 255))
}
}
// Chroma: 2x2 averaged.
for cy := 0; cy < frame.MBHeight*8; cy++ {
y0 := cy * 2
rowOff := cy * frame.UVStride
for cx := 0; cx < frame.MBWidth*8; cx++ {
x0 := cx * 2
var sumR, sumG, sumB int32
for dy := 0; dy < 2; dy++ {
sy := clampInt(y0+dy, 0, h-1)
srcRow := srcMinY + sy
base := nrgba.PixOffset(srcMinX, srcRow)
for dx := 0; dx < 2; dx++ {
sx := clampInt(x0+dx, 0, w-1)
p := base + sx*4
sumR += int32(nrgba.Pix[p])
sumG += int32(nrgba.Pix[p+1])
sumB += int32(nrgba.Pix[p+2])
}
}
r := (sumR + 2) >> 2
g := (sumG + 2) >> 2
bl := (sumB + 2) >> 2
// Cb = (-38R - 74G + 112B + 128) >> 8 + 128
// Cr = (112R - 94G - 18B + 128) >> 8 + 128
Cb := (-38*r-74*g+112*bl+128)>>8 + 128
Cr := (112*r-94*g-18*bl+128)>>8 + 128
frame.Cb[rowOff+cx] = byte(clampInt32(Cb, 0, 255))
frame.Cr[rowOff+cx] = byte(clampInt32(Cr, 0, 255))
}
}
return frame
}
// ExtractAlpha returns the 8-bit alpha plane for img, sized exactly (w, h)
// — no MB padding. Returns nil if the image has no alpha channel or is
// fully opaque. Used by the ALPH chunk encoder.
func ExtractAlpha(img image.Image) []byte {
b := img.Bounds()
w, h := b.Dx(), b.Dy()
nrgba, ok := img.(*image.NRGBA)
if !ok || !nrgba.Rect.Eq(b) {
nrgba = image.NewNRGBA(image.Rect(0, 0, w, h))
draw.Draw(nrgba, nrgba.Bounds(), img, b.Min, draw.Src)
b = nrgba.Bounds()
}
out := make([]byte, w*h)
fullyOpaque := true
for y := 0; y < h; y++ {
base := nrgba.PixOffset(b.Min.X, b.Min.Y+y)
for x := 0; x < w; x++ {
a := nrgba.Pix[base+x*4+3]
if a != 0xff {
fullyOpaque = false
}
out[y*w+x] = a
}
}
if fullyOpaque {
return nil
}
return out
}
func clampInt(v, lo, hi int) int {
if v < lo {
return lo
}
if v > hi {
return hi
}
return v
}
func clampInt32(v, lo, hi int32) int32 {
if v < lo {
return lo
}
if v > hi {
return hi
}
return v
}
+113
View File
@@ -0,0 +1,113 @@
package gowebp
import (
//------------------------------
//general
//------------------------------
"io"
"bytes"
"encoding/binary"
//------------------------------
//imaging
//------------------------------
"image"
//------------------------------
//errors
//------------------------------
decoderWebP "golang.org/x/image/webp"
)
// registers the webp decoder so image.Decode can detect and use it.
func init() {
image.RegisterFormat("webp", "RIFF", Decode, DecodeConfig)
}
// Decode reads a WebP image from the provided io.Reader and returns it as an image.Image.
//
// For VP8L (lossless) sources the returned image is an *image.NRGBA (or
// compatible) from the underlying x/image/webp decoder. For VP8 (lossy)
// sources it is wrapped as a *BT601YCbCr (or *BT601NYCbCrA when the
// source has an ALPH chunk) so that img.At(x, y).RGBA() produces the
// colors a spec-compliant VP8 decoder would show; Go's stdlib
// color.YCbCrToRGB uses JFIF full-range math which shifts VP8 pixels
// by several units per channel.
//
// Callers that specifically need the raw *image.YCbCr / *image.NYCbCrA
// (e.g. for zero-copy plane access) can type-assert to *BT601YCbCr
// or *BT601NYCbCrA and read the embedded field.
func Decode(r io.Reader) (image.Image, error) {
img, err := decoderWebP.Decode(r)
if err != nil {
return nil, err
}
return wrapBT601(img), nil
}
// wrapBT601 wraps *image.YCbCr / *image.NYCbCrA results in BT.601-
// limited-range types. Other image types (notably the NRGBA that
// VP8L decoding produces) pass through unchanged.
func wrapBT601(img image.Image) image.Image {
switch m := img.(type) {
case *image.YCbCr:
return &BT601YCbCr{YCbCr: m}
case *image.NYCbCrA:
return &BT601NYCbCrA{NYCbCrA: m}
}
return img
}
// DecodeConfig reads the image configuration from the provided io.Reader without fully decoding the image.
//
// This function is a wrapper around the underlying WebP decode package (golang.org/x/image/webp) and
// provides access to the image's metadata, such as its dimensions and color model.
// It is useful for obtaining image information before performing a full decode.
//
// Parameters:
// r - The source io.Reader containing the WebP encoded image.
//
// Returns:
// An image.Config containing the image's dimensions and color model, or an error if the configuration cannot be retrieved
func DecodeConfig(r io.Reader) (image.Config, error) {
return decoderWebP.DecodeConfig(r)
}
// DecodeIgnoreAlphaFlag reads a WebP image from the provided io.Reader and returns it as an image.Image.
//
// This function fixes x/image/webp rejecting VP8L images with the VP8X alpha flag, expecting an ALPHA chunk.
// VP8L handles transparency internally, and the WebP spec requires the flag for transparency.
//
// This function is a wrapper around the underlying WebP decode package (golang.org/x/image/webp).
// It supports both lossy and lossless WebP formats, decoding the image accordingly.
//
// Parameters:
// r - The source io.Reader containing the WebP encoded image.
//
// Returns:
// The decoded image as image.Image or an error if the decoding fails.
func DecodeIgnoreAlphaFlag(r io.Reader) (image.Image, error) {
data, err := io.ReadAll(r)
if err != nil {
return nil, err
}
if len(data) >= 30 && string(data[8:16]) == "WEBPVP8X" {
for i := 30; i + 8 < len(data); {
// Detect VP8L chunk, which handles transparency internally.
// The x/image/webp package misinterprets this, so we clear the alpha flag.
if string(data[i: i + 4]) == "VP8L" {
flags := binary.LittleEndian.Uint32(data[20:24])
flags &^= 0x00000010
binary.LittleEndian.PutUint32(data[20:24], flags)
break
}
i += 8 + int(binary.LittleEndian.Uint32(data[i + 4: i + 8]))
}
}
img, err := decoderWebP.Decode(bytes.NewReader(data))
if err != nil {
return nil, err
}
return wrapBT601(img), nil
}
+325
View File
@@ -0,0 +1,325 @@
package gowebp
import (
//------------------------------
//general
//------------------------------
"math"
"slices"
//------------------------------
//imaging
//------------------------------
"image/color"
//------------------------------
//errors
//------------------------------
//"log"
"errors"
)
type transform int
const (
transformPredict = transform(0)
transformColor = transform(1)
transformSubGreen = transform(2)
transformColorIndexing = transform(3)
)
func applyPredictTransform(pixels []color.NRGBA, width, height int) (int, int, int, []color.NRGBA) {
tileBits := 4
tileSize := 1 << tileBits
bw := (width + tileSize - 1) / tileSize
bh := (height + tileSize - 1) / tileSize
blocks := make([]color.NRGBA, bw * bh)
deltas := make([]color.NRGBA, width * height)
accum := [][]int{
make([]int, 256),
make([]int, 256),
make([]int, 256),
make([]int, 256),
make([]int, 40),
}
histos := make([][]int, len(accum))
for i := range accum {
histos[i] = make([]int, len(accum[i]))
}
for y := 0; y < bh; y++ {
for x := 0; x < bw; x++ {
mx := min((x + 1) << tileBits, width)
my := min((y + 1) << tileBits, height)
var best int
var bestEntropy float64
for i := 0; i < 14; i++ {
for j := range accum {
copy(histos[j], accum[j])
}
for tx := x << tileBits; tx < mx; tx++ {
for ty := y << tileBits; ty < my; ty++ {
d := applyFilter(pixels, width, tx, ty, i)
off := ty * width + tx
histos[0][int(uint8(pixels[off].R - d.R))]++
histos[1][int(uint8(pixels[off].G - d.G))]++
histos[2][int(uint8(pixels[off].B - d.B))]++
histos[3][int(uint8(pixels[off].A - d.A))]++
}
}
var total float64
for _, histo := range histos {
sum := 0
sumSquares := 0
for _, count := range histo {
sum += count
sumSquares += count * count
}
if sum == 0 {
continue
}
total += 1.0 - float64(sumSquares) / (float64(sum) * float64(sum))
}
if i == 0 || total < bestEntropy {
bestEntropy = total
best = i
}
}
for tx := x << tileBits; tx < mx; tx++ {
for ty := y << tileBits; ty < my; ty++ {
d := applyFilter(pixels, width, tx, ty, best)
off := ty * width + tx
deltas[off] = color.NRGBA{
R: uint8(pixels[off].R - d.R),
G: uint8(pixels[off].G - d.G),
B: uint8(pixels[off].B - d.B),
A: uint8(pixels[off].A - d.A),
}
accum[0][int(uint8(pixels[off].R - d.R))]++
accum[1][int(uint8(pixels[off].G - d.G))]++
accum[2][int(uint8(pixels[off].B - d.B))]++
accum[3][int(uint8(pixels[off].A - d.A))]++
}
}
blocks[y * bw + x] = color.NRGBA{0, byte(best), 0, 255}
}
}
copy(pixels, deltas)
return tileBits, bw, bh, blocks
}
func applyFilter(pixels []color.NRGBA, width, x, y, prediction int) color.NRGBA {
if x == 0 && y == 0 {
return color.NRGBA{0, 0, 0, 255}
} else if x == 0 {
return pixels[(y - 1) * width + x]
} else if y == 0 {
return pixels[y * width + (x - 1)]
}
t := pixels[(y - 1) * width + x]
l := pixels[y * width + (x - 1)]
tl := pixels[(y - 1) * width + (x - 1)]
tr := pixels[(y - 1) * width + (x + 1)]
avarage2 := func(a, b color.NRGBA) color.NRGBA {
return color.NRGBA {
uint8((int(a.R) + int(b.R)) / 2),
uint8((int(a.G) + int(b.G)) / 2),
uint8((int(a.B) + int(b.B)) / 2),
uint8((int(a.A) + int(b.A)) / 2),
}
}
filters := []func(t, l, tl, tr color.NRGBA) color.NRGBA {
func(t, l, tl, tr color.NRGBA) color.NRGBA { return color.NRGBA{0, 0, 0, 255} },
func(t, l, tl, tr color.NRGBA) color.NRGBA { return l },
func(t, l, tl, tr color.NRGBA) color.NRGBA { return t },
func(t, l, tl, tr color.NRGBA) color.NRGBA { return tr },
func(t, l, tl, tr color.NRGBA) color.NRGBA { return tl },
func(t, l, tl, tr color.NRGBA) color.NRGBA {
return avarage2(avarage2(l, tr), t)
},
func(t, l, tl, tr color.NRGBA) color.NRGBA {
return avarage2(l, tl)
},
func(t, l, tl, tr color.NRGBA) color.NRGBA {
return avarage2(l, t)
},
func(t, l, tl, tr color.NRGBA) color.NRGBA {
return avarage2(tl, t)
},
func(t, l, tl, tr color.NRGBA) color.NRGBA {
return avarage2(t, tr)
},
func(t, l, tl, tr color.NRGBA) color.NRGBA {
return avarage2(avarage2(l, tl), avarage2(t, tr))
},
func(t, l, tl, tr color.NRGBA) color.NRGBA {
pr := float64(l.R) + float64(t.R) - float64(tl.R)
pg := float64(l.G) + float64(t.G) - float64(tl.G)
pb := float64(l.B) + float64(t.B) - float64(tl.B)
pa := float64(l.A) + float64(t.A) - float64(tl.A)
// Manhattan distances to estimates for left and top pixels.
pl := math.Abs(pa - float64(l.A)) + math.Abs(pr - float64(l.R)) +
math.Abs(pg - float64(l.G)) + math.Abs(pb - float64(l.B))
pt := math.Abs(pa - float64(t.A)) + math.Abs(pr - float64(t.R)) +
math.Abs(pg - float64(t.G)) + math.Abs(pb - float64(t.B))
if pl < pt {
return l
}
return t
},
func(t, l, tl, tr color.NRGBA) color.NRGBA {
return color.NRGBA{
uint8(max(min(int(l.R) + int(t.R) - int(tl.R), 255), 0)),
uint8(max(min(int(l.G) + int(t.G) - int(tl.G), 255), 0)),
uint8(max(min(int(l.B) + int(t.B) - int(tl.B), 255), 0)),
uint8(max(min(int(l.A) + int(t.A) - int(tl.A), 255), 0)),
}
},
func(t, l, tl, tr color.NRGBA) color.NRGBA {
a := avarage2(l, t)
return color.NRGBA{
uint8(max(min(int(a.R) + (int(a.R) - int(tl.R)) / 2, 255), 0)),
uint8(max(min(int(a.G) + (int(a.G) - int(tl.G)) / 2, 255), 0)),
uint8(max(min(int(a.B) + (int(a.B) - int(tl.B)) / 2, 255), 0)),
uint8(max(min(int(a.A) + (int(a.A) - int(tl.A)) / 2, 255), 0)),
}
},
}
return filters[prediction](t, l, tl, tr)
}
func applyColorTransform(pixels []color.NRGBA, width, height int) (int, int, int, []color.NRGBA) {
tileBits := 4
tileSize := 1 << tileBits
bw := (width + tileSize - 1) / tileSize
bh := (height + tileSize - 1) / tileSize
blocks := make([]color.NRGBA, bw * bh)
deltas := make([]color.NRGBA, width * height)
//TODO: analyze block and pick best Color transform Element (CTE)
cte := color.NRGBA {
R: 1, //red to blue
G: 2, //green to blue
B: 3, //green to red
A: 255,
}
for y := 0; y < bh; y++ {
for x := 0; x < bw; x++ {
mx := min((x + 1) << tileBits, width)
my := min((y + 1) << tileBits, height)
for tx := x << tileBits; tx < mx; tx++ {
for ty := y << tileBits; ty < my; ty++ {
off := ty * width + tx
r := int(int8(pixels[off].R))
g := int(int8(pixels[off].G))
b := int(int8(pixels[off].B))
b -= int(int8((int16(int8(cte.G)) * int16(g)) >> 5))
b -= int(int8((int16(int8(cte.R)) * int16(r)) >> 5))
r -= int(int8((int16(int8(cte.B)) * int16(g)) >> 5))
pixels[off].R = uint8(r & 0xff)
pixels[off].B = uint8(b & 0xff)
deltas[off] = pixels[off]
}
}
blocks[y * bw + x] = cte
}
}
copy(pixels, deltas)
return tileBits, bw, bh, blocks
}
func applySubtractGreenTransform(pixels []color.NRGBA) {
for i := range pixels {
pixels[i].R = pixels[i].R - pixels[i].G
pixels[i].B = pixels[i].B - pixels[i].G
}
}
func applyPaletteTransform(pixels *[]color.NRGBA, width, height int) ([]color.NRGBA, int, error) {
var pal []color.NRGBA
for _, p := range (*pixels) {
if !slices.Contains(pal, p) {
pal = append(pal, p)
}
if len(pal) > 256 {
return nil, 0, errors.New("palette exceeds 256 colors")
}
}
size := 1
if len(pal) <= 2 {
size = 8
} else if len(pal) <= 4 {
size = 4
} else if len(pal) <= 16 {
size = 2
}
pw := (width + size - 1) / size
packed := make([]color.NRGBA, pw * height)
for y := 0; y < height; y++ {
for x := 0; x < pw; x++ {
pack := 0
for i := 0; i < size; i++ {
px := x * size + i
if px >= width {
break
}
idx := slices.Index(pal, (*pixels)[y * width + px])
pack |= int(idx) << (i * (8 / size))
}
packed[y * pw + x] = color.NRGBA{G: uint8(pack), A: 255}
}
}
*pixels = packed
for i := len(pal) - 1; i > 0; i-- {
pal[i] = color.NRGBA{
R: pal[i].R - pal[i - 1].R,
G: pal[i].G - pal[i - 1].G,
B: pal[i].B - pal[i - 1].B,
A: pal[i].A - pal[i - 1].A,
}
}
return pal, pw, nil
}
+752
View File
@@ -0,0 +1,752 @@
package gowebp
import (
//------------------------------
//general
//------------------------------
"io"
"bytes"
"encoding/binary"
//------------------------------
//imaging
//------------------------------
"image"
"image/draw"
"image/color"
//------------------------------
//errors
//------------------------------
"errors"
//------------------------------
//vp8 (lossy)
//------------------------------
"github.com/KarpelesLab/gowebp/internal/vp8enc"
)
// Options holds configuration settings for WebP encoding.
//
// Fields:
// - UseExtendedFormat: If true, wraps the VP8L frame inside a VP8X container
// to enable metadata support. This does not affect image compression or
// encoding itself, as VP8L remains the encoding format.
// - Lossy: If true, encode as VP8 (lossy). Otherwise (default) encode as
// VP8L (lossless), preserving existing behavior byte-for-byte.
// - Quality: Lossy quality in [0, 100]. Higher values preserve more
// detail. Default (when zero) is 75. Ignored when Lossy is false.
// - Method: Lossy speed/quality tradeoff in [0, 6]. Higher values spend
// more time searching for better compression. Default 4. Ignored when
// Lossy is false.
type Options struct {
UseExtendedFormat bool
Lossy bool
Quality float32
Method int
}
// Animation holds configuration settings for WebP animations.
//
// It allows encoding a sequence of frames with individual timing and disposal options,
// supporting features like looping and background color settings.
//
// Fields:
// - Images: A list of frames to be displayed in sequence.
// - Durations: Timing for each frame in milliseconds, matching the Images slice.
// - Disposals: Disposal methods for frames after display; 0 = keep, 1 = clear to background.
// - LoopCount: Number of times the animation should repeat; 0 means infinite looping.
// - BackgroundColor: Canvas background color in BGRA order, used for clear operations.
type Animation struct {
Images []image.Image
Durations []uint
Disposals []uint
LoopCount uint16
BackgroundColor uint32
}
// Encode writes the provided image.Image to the specified io.Writer in WebP format.
//
// This function always encodes the image using VP8L (lossless WebP). If `UseExtendedFormat`
// is enabled, it wraps the VP8L frame inside a VP8X container, allowing the use of metadata
// such as EXIF, ICC color profiles, or XMP metadata.
//
// Note: VP8L already supports transparency, so VP8X is **not required** for alpha support.
//
// Parameters:
// w - The destination writer where the encoded WebP image will be written.
// img - The input image to be encoded.
// o - Pointer to Options containing encoding settings:
// - UseExtendedFormat: If true, wraps the image in a VP8X container to enable
// extended WebP features like metadata.
//
// Returns:
// An error if encoding fails or writing to the io.Writer encounters an issue.
func Encode(w io.Writer, img image.Image, o *Options) error {
if o != nil && o.Lossy {
return encodeLossy(w, img, o)
}
stream, hasAlpha, err := writeBitStream(img)
if err != nil {
return err
}
buf := &bytes.Buffer{}
if o != nil && o.UseExtendedFormat {
writeChunkVP8X(buf, img.Bounds(), hasAlpha, false)
}
buf.Write([]byte("VP8L"))
binary.Write(buf, binary.LittleEndian, uint32(stream.Len()))
buf.Write(stream.Bytes())
w.Write([]byte("RIFF"))
binary.Write(w, binary.LittleEndian, uint32(4 + buf.Len()))
w.Write([]byte("WEBP"))
w.Write(buf.Bytes())
return nil
}
// encodeLossy produces a VP8-coded .webp file. When the source image has
// alpha, the VP8 (opaque color) chunk is paired with an ALPH chunk
// carrying the alpha plane inside a VP8X container (spec section 2 /
// WebP container spec "Alpha").
func encodeLossy(w io.Writer, img image.Image, o *Options) error {
if o.Quality < 0 || o.Quality > 100 {
return errors.New("Options.Quality must be in [0, 100]")
}
if o.Method < 0 || o.Method > 6 {
return errors.New("Options.Method must be in [0, 6]")
}
q := o.Quality
if q == 0 {
q = 75
}
alpha := vp8enc.ExtractAlpha(img)
if alpha == nil {
// Fully opaque (or no alpha channel): simple VP8 container.
return vp8enc.EncodeWebP(w, img, vp8enc.EncodeOptions{
Quality: q,
Method: o.Method,
})
}
// Mixed-alpha path: VP8X + VP8 + ALPH.
var vp8buf bytes.Buffer
if err := vp8enc.EncodeFrame(&vp8buf, img, vp8enc.EncodeOptions{
Quality: q,
Method: o.Method,
}); err != nil {
return err
}
inner := &bytes.Buffer{}
writeChunkVP8X(inner, img.Bounds(), true, false)
writeChunkALPH(inner, img.Bounds(), alpha)
writeChunkVP8(inner, vp8buf.Bytes())
w.Write([]byte("RIFF"))
binary.Write(w, binary.LittleEndian, uint32(4+inner.Len()))
w.Write([]byte("WEBP"))
w.Write(inner.Bytes())
return nil
}
// writeChunkVP8 emits a VP8 sub-chunk with even-length padding.
func writeChunkVP8(buf *bytes.Buffer, payload []byte) {
buf.Write([]byte("VP8 "))
binary.Write(buf, binary.LittleEndian, uint32(len(payload)))
buf.Write(payload)
if len(payload)&1 == 1 {
buf.WriteByte(0)
}
}
// writeChunkALPH emits an ALPH sub-chunk. When VP8L-compressed alpha is
// smaller than raw, we use method=1 (VP8L with alpha stored in the
// green channel); otherwise method=0 (raw alpha plane). Filter and
// preprocessing are always 0 in the current implementation.
//
// Header byte layout is RRMMFFCC where CC is compression method, FF is
// filter, MM is preprocessing, RR is reserved (must be 0).
func writeChunkALPH(buf *bytes.Buffer, bounds image.Rectangle, alpha []byte) {
body, method := encodeAlphaPayload(alpha, bounds.Dx(), bounds.Dy())
payloadLen := 1 + len(body)
buf.Write([]byte("ALPH"))
binary.Write(buf, binary.LittleEndian, uint32(payloadLen))
buf.WriteByte(byte(method))
buf.Write(body)
if payloadLen&1 == 1 {
buf.WriteByte(0)
}
}
// encodeAlphaPayload returns the alpha-plane bytes to embed in an ALPH
// chunk along with the compression-method value (0 or 1) to put in the
// header byte. Tries VP8L first; falls back to raw if it's not smaller.
func encodeAlphaPayload(alpha []byte, w, h int) ([]byte, int) {
compressed, err := encodeAlphaVP8L(alpha, w, h)
if err == nil && len(compressed) < len(alpha) {
return compressed, 1
}
return alpha, 0
}
// encodeAlphaVP8L produces a VP8L-compressed alpha plane suitable for
// embedding in an ALPH chunk with compression method 1. The plane is
// encoded as a synthetic NRGBA image whose green channel carries the
// alpha values; the decoder reads only the green channel out of the
// VP8L sub-image.
//
// The 5-byte VP8L header (magic + dimensions + alpha flag + version) is
// stripped from the output because the ALPH decoder synthesizes that
// header from the VP8X-level dimensions.
func encodeAlphaVP8L(alpha []byte, w, h int) ([]byte, error) {
img := image.NewNRGBA(image.Rect(0, 0, w, h))
for y := 0; y < h; y++ {
for x := 0; x < w; x++ {
img.Pix[(y*w+x)*4+1] = alpha[y*w+x] // green = alpha
img.Pix[(y*w+x)*4+3] = 0xff // fully opaque
}
}
stream, _, err := writeBitStream(img)
if err != nil {
return nil, err
}
b := stream.Bytes()
if len(b) < 5 {
return nil, errors.New("VP8L stream too short for alpha payload")
}
// Strip the 5-byte VP8L header; the decoder re-synthesizes it from
// VP8X dimensions when parsing the ALPH chunk.
return b[5:], nil
}
// EncodeAll writes the provided animation sequence to the specified io.Writer in WebP format.
//
// This function encodes a list of frames as a WebP animation using the VP8X container, which
// supports features like looping, frame timing, disposal methods, and background color settings.
// Each frame is individually compressed using the VP8L (lossless) format.
//
// Note: Even if `UseExtendedFormat` is not explicitly set, animations always use the VP8X container
// because it is required for WebP animation support.
//
// Parameters:
// w - The destination writer where the encoded WebP animation will be written.
// ani - Pointer to Animation containing the frames and animation settings:
// - Images: List of frames to encode.
// - Durations: Display times for each frame in milliseconds.
// - Disposals: Disposal methods after frame display (keep or clear).
// - LoopCount: Number of times the animation should loop (0 = infinite).
// - BackgroundColor: Background color for the canvas, used when clearing.
// o - Pointer to Options containing additional encoding settings:
// - UseExtendedFormat: Currently unused for animations, but accepted for consistency.
//
// Returns:
// An error if encoding fails or writing to the io.Writer encounters an issue.
func EncodeAll(w io.Writer, ani *Animation, o *Options) error {
frames, alpha, err := writeFrames(ani, o)
if err != nil {
return err
}
var bounds image.Rectangle
for _, img := range ani.Images {
bounds.Max.X = max(img.Bounds().Max.X, bounds.Max.X)
bounds.Max.Y = max(img.Bounds().Max.Y, bounds.Max.Y)
}
buf := &bytes.Buffer{}
writeChunkVP8X(buf, bounds, alpha, true)
buf.Write([]byte("ANIM"))
binary.Write(buf, binary.LittleEndian, uint32(6))
binary.Write(buf, binary.LittleEndian, uint32(ani.BackgroundColor))
binary.Write(buf, binary.LittleEndian, uint16(ani.LoopCount))
buf.Write(frames.Bytes())
w.Write([]byte("RIFF"))
binary.Write(w, binary.LittleEndian, uint32(4 + buf.Len()))
w.Write([]byte("WEBP"))
w.Write(buf.Bytes())
return nil
}
func writeChunkVP8X(buf *bytes.Buffer, bounds image.Rectangle, flagAlpha, flagAni bool) {
buf.Write([]byte("VP8X"))
binary.Write(buf, binary.LittleEndian, uint32(10))
var flags byte
if flagAni {
flags |= 1 << 1
}
if flagAlpha {
flags |= 1 << 4
}
binary.Write(buf, binary.LittleEndian, flags)
buf.Write([]byte{0x00, 0x00, 0x00})
dx := bounds.Dx() - 1
dy := bounds.Dy() - 1
buf.Write([]byte{byte(dx), byte(dx >> 8), byte(dx >> 16)})
buf.Write([]byte{byte(dy), byte(dy >> 8), byte(dy >> 16)})
}
func writeFrames(ani *Animation, o *Options) (*bytes.Buffer, bool, error) {
if len(ani.Images) == 0 {
return nil, false, errors.New("must provide at least one image")
}
if len(ani.Images) != len(ani.Durations) {
return nil, false, errors.New("mismatched image and durations lengths")
}
if len(ani.Images) != len(ani.Disposals) {
return nil, false, errors.New("mismatched image and disposals lengths")
}
for i := 0; i < len(ani.Images); i++ {
ani.Durations[i] = min(ani.Durations[i], 1 << 24 - 1)
ani.Disposals[i] = min(ani.Disposals[i], 1)
}
lossy := o != nil && o.Lossy
quality := float32(75)
method := 0
if o != nil && o.Quality != 0 {
quality = o.Quality
}
if o != nil {
method = o.Method
}
buf := &bytes.Buffer{}
var hasAlpha bool
for i, img := range ani.Images {
var framePayload bytes.Buffer
var alpha bool
if lossy {
// Lossy animation frame: optional ALPH (if image has alpha)
// followed by a VP8 color chunk, both wrapped in the ANMF.
alphaPlane := vp8enc.ExtractAlpha(img)
if alphaPlane != nil {
writeChunkALPH(&framePayload, img.Bounds(), alphaPlane)
alpha = true
}
var vp8 bytes.Buffer
if err := vp8enc.EncodeFrame(&vp8, img, vp8enc.EncodeOptions{
Quality: quality,
Method: method,
}); err != nil {
return nil, false, err
}
writeChunkVP8(&framePayload, vp8.Bytes())
} else {
stream, a, err := writeBitStream(img)
if err != nil {
return nil, false, err
}
// VP8L sub-chunk inside ANMF. Use the same fourcc/size/pad
// pattern as writeChunkVP8 for consistency.
framePayload.Write([]byte("VP8L"))
binary.Write(&framePayload, binary.LittleEndian, uint32(stream.Len()))
framePayload.Write(stream.Bytes())
if stream.Len()&1 == 1 {
framePayload.WriteByte(0)
}
alpha = a
}
hasAlpha = hasAlpha || alpha
w := &bitWriter{Buffer: buf}
w.writeBytes([]byte("ANMF"))
// ANMF payload = 16-byte frame header + framePayload (which
// already contains its own sub-chunk headers + padding).
w.writeBits(uint64(16+framePayload.Len()), 32)
// WebP specs requires frame offsets to be divided by 2
w.writeBits(uint64(img.Bounds().Min.X/2), 24)
w.writeBits(uint64(img.Bounds().Min.Y/2), 24)
w.writeBits(uint64(img.Bounds().Dx()-1), 24)
w.writeBits(uint64(img.Bounds().Dy()-1), 24)
w.writeBits(uint64(ani.Durations[i]), 24)
w.writeBits(uint64(ani.Disposals[i]), 1)
w.writeBits(uint64(0), 1)
w.writeBits(uint64(0), 6)
w.Buffer.Write(framePayload.Bytes())
}
return buf, hasAlpha, nil
}
func writeBitStream(img image.Image) (*bytes.Buffer, bool, error) {
if img == nil {
return nil, false, errors.New("image is nil")
}
if img.Bounds().Dx() < 1 || img.Bounds().Dy() < 1 {
return nil, false, errors.New("invalid image size")
}
if img.Bounds().Dx() > 1 << 14 || img.Bounds().Dy() > 1 << 14 {
return nil, false, errors.New("invalid image size")
}
_, isIndexed := img.(*image.Paletted)
rgba := image.NewNRGBA(image.Rect(0, 0, img.Bounds().Dx(), img.Bounds().Dy()))
draw.Draw(rgba, rgba.Bounds(), img, img.Bounds().Min, draw.Src)
b := &bytes.Buffer{}
s := &bitWriter{Buffer: b}
writeBitStreamHeader(s, rgba.Bounds(), !rgba.Opaque())
var transforms [4]bool
transforms[transformPredict] = !isIndexed
transforms[transformColor] = false
transforms[transformSubGreen] = !isIndexed
transforms[transformColorIndexing] = isIndexed
err := writeBitStreamData(s, rgba, 4, transforms)
if err != nil {
return nil, false, err
}
s.alignByte()
if b.Len() % 2 != 0 {
b.Write([]byte{0x00})
}
return b, !rgba.Opaque(), nil
}
func writeBitStreamHeader(w *bitWriter, bounds image.Rectangle, hasAlpha bool) {
w.writeBits(0x2f, 8)
w.writeBits(uint64(bounds.Dx() - 1), 14)
w.writeBits(uint64(bounds.Dy() - 1), 14)
if hasAlpha {
w.writeBits(1, 1)
} else {
w.writeBits(0, 1)
}
w.writeBits(0, 3)
}
func writeBitStreamData(w *bitWriter, img image.Image, colorCacheBits int, transforms [4]bool) error {
pixels, err := flatten(img)
if err != nil {
return err
}
width := img.Bounds().Dx()
height := img.Bounds().Dy()
if transforms[transformColorIndexing] {
w.writeBits(1, 1)
w.writeBits(3, 2)
pal, pw, err := applyPaletteTransform(&pixels, width, height)
if err != nil {
return err
}
width = pw
w.writeBits(uint64(len(pal) - 1), 8);
writeImageData(w, pal, len(pal), 1, false, colorCacheBits);
}
if transforms[transformSubGreen] {
w.writeBits(1, 1)
w.writeBits(2, 2)
applySubtractGreenTransform(pixels)
}
if transforms[transformColor] {
w.writeBits(1, 1)
w.writeBits(1, 2)
bits, bw, bh, blocks := applyColorTransform(pixels, width, height)
w.writeBits(uint64(bits - 2), 3);
writeImageData(w, blocks, bw, bh, false, colorCacheBits)
}
if transforms[transformPredict] {
w.writeBits(1, 1)
w.writeBits(0, 2)
bits, bw, bh, blocks := applyPredictTransform(pixels, width, height)
w.writeBits(uint64(bits - 2), 3);
writeImageData(w, blocks, bw, bh, false, colorCacheBits)
}
w.writeBits(0, 1) // end of transform
writeImageData(w, pixels, width, height, true, colorCacheBits)
return nil
}
func writeImageData(w *bitWriter, pixels []color.NRGBA, width, height int, isRecursive bool, colorCacheBits int) {
if colorCacheBits > 0 {
w.writeBits(1, 1)
w.writeBits(uint64(colorCacheBits), 4)
} else {
w.writeBits(0, 1)
}
if isRecursive {
w.writeBits(0, 1)
}
encoded := encodeImageData(pixels, width, height, colorCacheBits)
histos := computeHistograms(encoded, colorCacheBits)
var codes [][]huffmanCode
for i := 0; i < 5; i++ {
// WebP specs requires Huffman codes with maximum depth of 15
c := buildhuffmanCodes(histos[i], 15)
codes = append(codes, c)
writehuffmanCodes(w, c)
}
for i := 0; i < len(encoded); i ++ {
w.writeCode(codes[0][encoded[i + 0]])
if encoded[i + 0] < 256 {
w.writeCode(codes[1][encoded[i + 1]])
w.writeCode(codes[2][encoded[i + 2]])
w.writeCode(codes[3][encoded[i + 3]])
i += 3
} else if encoded[i + 0] < 256 + 24 {
cnt := prefixEncodeBits(int(encoded[i + 0]) - 256)
w.writeBits(uint64(encoded[i + 1]), cnt);
w.writeCode(codes[4][encoded[i + 2]])
cnt = prefixEncodeBits(int(encoded[i + 2]))
w.writeBits(uint64(encoded[i + 3]), cnt);
i += 3
}
}
}
func encodeImageData(pixels []color.NRGBA, width, height, colorCacheBits int) []int {
head := make([]int, 1 << 14)
prev := make([]int, len(pixels))
cache := make([]color.NRGBA, 1 << colorCacheBits)
encoded := make([]int, len(pixels) * 4)
cnt := 0
var distances = []int {
96, 73, 55, 39, 23, 13, 5, 1, 255, 255, 255, 255, 255, 255, 255, 255,
101, 78, 58, 42, 26, 16, 8, 2, 0, 3, 9, 17, 27, 43, 59, 79,
102, 86, 62, 46, 32, 20, 10, 6, 4, 7, 11, 21, 33, 47, 63, 87,
105, 90, 70, 52, 37, 28, 18, 14, 12, 15, 19, 29, 38, 53, 71, 91,
110, 99, 82, 66, 48, 35, 30, 24, 22, 25, 31, 36, 49, 67, 83, 100,
115, 108, 94, 76, 64, 50, 44, 40, 34, 41, 45, 51, 65, 77, 95, 109,
118, 113, 103, 92, 80, 68, 60, 56, 54, 57, 61, 69, 81, 93, 104, 114,
119, 116, 111, 106, 97, 88, 84, 74, 72, 75, 85, 89, 98, 107, 112, 117,
}
for i := 0; i < len(pixels); i++ {
if i + 2 < len(pixels) {
h := hash(pixels[i + 0], 14)
h ^= hash(pixels[i + 1], 14) * 0x9e3779b9
h ^= hash(pixels[i + 2], 14) * 0x85ebca6b
h = h % (1 << 14)
cur := head[h] - 1
prev[i] = head[h]
head[h] = i + 1
dis := 0
streak := 0
for j := 0; j < 8; j++ {
// 1 << 20: sliding window size is 2^20 (1,048,576) per WebP specs.
// 120: reserved margin for offset adjustments.
if cur == -1 || i - cur >= 1 << 20 - 120 {
break
}
l := 0
// Limit the maximum match length to 4096 pixels per WebP specs.
for i + l < len(pixels) && l < 4096 {
if pixels[i + l] != pixels[cur + l] {
break
}
l++
}
if l > streak {
streak = l
dis = i - cur
}
cur = prev[cur] - 1
}
// Only use the match if it is at least 3 pixels long per WebP specs.
if streak >= 3 {
for j := 0; j < streak; j++ {
h := hash(pixels[i + j], colorCacheBits)
cache[h] = pixels[i + j]
}
y := dis / width
x := dis - y * width
code := dis + 120
if x <= 8 && y < 8 {
code = distances[y * 16 + 8 - x] + 1
} else if x > width - 8 && y < 7 {
code = distances[(y + 1) * 16 + 8 + (width - x)] + 1
}
s, l := prefixEncodeCode(streak)
encoded[cnt + 0] = int(s + 256)
encoded[cnt + 1] = int(l)
s, l = prefixEncodeCode(code)
encoded[cnt + 2] = int(s)
encoded[cnt + 3] = int(l)
cnt += 4
i += streak - 1
continue
}
}
p := pixels[i]
if colorCacheBits > 0 {
hash := hash(p, colorCacheBits)
if i > 0 && cache[hash] == p {
encoded[cnt] = int(hash + 256 + 24)
cnt++
continue
}
cache[hash] = p
}
encoded[cnt+0] = int(p.G)
encoded[cnt+1] = int(p.R)
encoded[cnt+2] = int(p.B)
encoded[cnt+3] = int(p.A)
cnt += 4
}
return encoded[:cnt]
}
func prefixEncodeCode(n int) (int, int) {
if n <= 5 {
return max(0, n - 1), 0
}
shift := 0
rem := n - 1
for rem > 3 {
rem >>= 1
shift += 1
}
if rem == 2 {
return 2 + 2 * shift, n - (2 << shift) - 1
}
return 3 + 2 * shift, n - (3 << shift) - 1
}
func prefixEncodeBits(prefix int) int {
if prefix < 4 {
return 0
}
return (prefix - 2) >> 1
}
func hash(c color.NRGBA, shifts int) uint32 {
//hash formula including magic number 0x1e35a7bd comes directly from WebP specs!
x := uint32(c.A) << 24 | uint32(c.R) << 16 | uint32(c.G) << 8 | uint32(c.B)
return (x * 0x1e35a7bd) >> (32 - min(shifts, 32))
}
func computeHistograms(pixels []int, colorCacheBits int) [][]int {
c := 0
if colorCacheBits > 0 {
c = 1 << colorCacheBits
}
histos := [][]int{
make([]int, 256 + 24 + c),
make([]int, 256),
make([]int, 256),
make([]int, 256),
make([]int, 40),
}
for i := 0; i < len(pixels); i++ {
histos[0][pixels[i]]++
if(pixels[i] < 256) {
histos[1][pixels[i + 1]]++
histos[2][pixels[i + 2]]++
histos[3][pixels[i + 3]]++
i += 3
} else if pixels[i] < 256 + 24 {
histos[4][pixels[i + 2]]++
i += 3
}
}
return histos
}
func flatten(img image.Image) ([]color.NRGBA, error) {
w := img.Bounds().Dx()
h := img.Bounds().Dy()
rgba, ok := img.(*image.NRGBA)
if !ok {
return nil, errors.New("unsupported image format")
}
pixels := make([]color.NRGBA, w * h)
for y := 0; y < h; y++ {
for x := 0; x < w; x++ {
i := rgba.PixOffset(x, y)
s := rgba.Pix[i : i + 4 : i + 4]
pixels[y * w + x].R = uint8(s[0])
pixels[y * w + x].G = uint8(s[1])
pixels[y * w + x].B = uint8(s[2])
pixels[y * w + x].A = uint8(s[3])
}
}
return pixels, nil
}
+25
View File
@@ -0,0 +1,25 @@
# 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
# IDEs
.idea/
+80
View File
@@ -0,0 +1,80 @@
# Changelog
All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [7.0.3] - 2026-11-01
### Fixed
- `Ticker` no longer delivers a tick to a receive started after `Stop` returns. `Stop` now waits for the ticker to shut down, so `C` is closed when it returns; it must not be called from the `BackOff`'s methods. ([#198](https://github.com/cenkalti/backoff/issues/198))
- `Ticker` stops its pending timer when it shuts down instead of leaving it to expire. ([#197](https://github.com/cenkalti/backoff/pull/197))
## [7.0.2] - 2026-10-19
### Fixed
- Recheck context cancellation after `WithNotify` runs and after timer expiration, preventing subsequent attempts if the context is cancelled. ([#194](https://github.com/cenkalti/backoff/issues/194))
## [7.0.1] - 2026-09-30
### Fixed
- `WithMaxElapsedTime` no longer lets a delay near the maximum `time.Duration` overflow past the limit, and a negative `RetryAfter` delay is treated as zero instead of extending it. ([#191](https://github.com/cenkalti/backoff/pull/191))
- `ExponentialBackOff` no longer returns a negative delay when a randomized interval exceeds the maximum `time.Duration`.
- `Retry` no longer panics when the operation returns a typed-nil `*RetryAfterError`. It is retried like any other error.
- The `RetryAfterError` docs now state that the backoff policy's `Stop` takes precedence over the requested delay. ([#192](https://github.com/cenkalti/backoff/issues/192))
- The `WithMaxElapsedTime` docs now state that the limit includes the runtime of the attempts, so an operation that fails after running past it is not retried. ([#188](https://github.com/cenkalti/backoff/issues/188))
## [7.0.0] - 2026-06-30
### Changed
- `RetryAfter` now takes a `time.Duration` and a required cause error: `RetryAfter(d time.Duration, cause error)`. The cause is preserved as `RetryError.LastErr` when retrying stops. ([#184](https://github.com/cenkalti/backoff/issues/184))
### Added
- `RetryAfterError` carries the cause passed to `RetryAfter`, exposed via `Unwrap`.
## [6.0.0] - 2026-06-16
### Added
- `RetryError`, returned by `Retry` on every failure, exposing the last operation error (`LastErr`) and the reason it stopped (`Cause`). ([#181](https://github.com/cenkalti/backoff/issues/181))
- `ErrPermanent`, `ErrExhausted`, and `ErrMaxElapsedTime` cause sentinels, plus `AsRetryError` to extract a `*RetryError` from an error chain.
### Changed
- `Retry` now returns a `*RetryError` on any failure instead of the bare context or operation error. Inspect it with `errors.Is`/`errors.As`; the last operation error is always preserved.
- `WithMaxElapsedTime` now reports `ErrMaxElapsedTime` instead of `context.DeadlineExceeded`.
### Removed
- The `PermanentError` type. Use `Permanent(err)` (unchanged) and detect it with `errors.Is(err, ErrPermanent)`.
See [`ExampleRetry_outcomes`](example_test.go) for how to inspect error outcomes.
## [5.0.0] - 2024-12-19
### Added
- RetryAfterError can be returned from an operation to indicate how long to wait before the next retry.
### Changed
- Retry function now accepts additional options for specifying max number of tries and max elapsed time.
- Retry function now accepts a context.Context.
- Operation function signature changed to return result (any type) and error.
### Removed
- RetryNotify* and RetryWithData functions. Only single Retry function remains.
- Optional arguments from ExponentialBackoff constructor.
- Clock and Timer interfaces.
### Fixed
- The original error is returned from Retry if there's a PermanentError. ([#144](https://github.com/cenkalti/backoff/issues/144))
- The Retry function respects the wrapped PermanentError. ([#140](https://github.com/cenkalti/backoff/issues/140))
+20
View File
@@ -0,0 +1,20 @@
The MIT License (MIT)
Copyright (c) 2014 Cenk Altı
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.
+96
View File
@@ -0,0 +1,96 @@
# Exponential Backoff [![GoDoc][godoc image]][godoc]
This is a Go port of the exponential backoff algorithm from [Google's HTTP Client Library for Java][google-http-java-client].
[Exponential backoff][exponential backoff wiki]
is an algorithm that uses feedback to multiplicatively decrease the rate of some process,
in order to gradually find an acceptable rate.
The retries exponentially increase and stop increasing when a certain threshold is met.
## Install
```
go get github.com/cenkalti/backoff/v7
```
Note the `/v7` at the end of the import path.
## Usage
For most cases, wrap the operation you want to retry in `Retry`:
```go
result, err := backoff.Retry(ctx, func() (string, error) {
resp, err := http.Get("https://www.example.com")
if err != nil {
return "", err // transient: Retry will try again
}
defer resp.Body.Close()
switch {
case resp.StatusCode >= 500:
return "", fmt.Errorf("server error: %s", resp.Status) // retried
case resp.StatusCode >= 400:
// client errors won't fix themselves, so stop retrying.
return "", backoff.Permanent(fmt.Errorf("client error: %s", resp.Status))
}
return "ok", nil
}, backoff.WithMaxTries(5))
```
`Retry` runs the operation at least once and keeps retrying with exponential
backoff until it succeeds, returns a `Permanent` error, or a limit is reached.
See [example_test.go][example] for a fuller example, and the [package docs][godoc]
for the available options (`WithBackOff`, `WithMaxTries`, `WithMaxElapsedTime`,
`WithNotify`).
If `Retry` does not fit your needs, copy it from [retry.go][retry-src] and adapt it.
### Handling errors
On failure, `Retry` always returns a `*RetryError`. It carries the last operation error (`LastErr`) and the reason retrying stopped (`Cause`). Inspect it with `errors.Is`, or reach the struct with `AsRetryError`:
```go
result, err := backoff.Retry(ctx, operation)
switch {
case errors.Is(err, backoff.ErrPermanent):
// the operation returned a Permanent error
case errors.Is(err, context.Canceled), errors.Is(err, context.DeadlineExceeded):
// the caller's context was cancelled or its deadline expired
case errors.Is(err, backoff.ErrMaxElapsedTime):
// the WithMaxElapsedTime budget was exhausted
case errors.Is(err, backoff.ErrExhausted):
// WithMaxTries was reached or the backoff policy returned Stop
}
// The last operation error is always available, whatever the cause:
if re := backoff.AsRetryError(err); re != nil {
log.Printf("gave up after last error: %v", re.LastErr)
}
```
Mark an error non-retriable with `backoff.Permanent(err)`; `Retry` stops immediately and returns a `*RetryError` whose `Cause` is `ErrPermanent` and whose `LastErr` is `err`.
### Bounding total time
Two independent limits cap how long `Retry` runs, and they behave differently:
- A **context deadline** (`context.WithTimeout`) is reactive: it interrupts the wait between attempts and — if your operation observes the context — can abort an in-flight attempt. `Retry` reports it as `context.DeadlineExceeded`.
- **`WithMaxElapsedTime`** bounds only retry scheduling: it is checked between attempts, never interrupts a running operation, and is reported as `ErrMaxElapsedTime`. It counts from when `Retry` is called and includes the attempts' own runtime, so an operation that fails only after running past the limit is not retried.
`WithMaxElapsedTime` defaults to 15 minutes, so **both limits are active unless you override it** — pass `backoff.WithMaxElapsedTime(0)` to rely solely on the context.
## Contributing
* I would like to keep this library as small as possible.
* Please don't send a PR without opening an issue and discussing it first.
* If proposed change is not a common use case, I will probably not accept it.
[godoc]: https://pkg.go.dev/github.com/cenkalti/backoff/v7
[godoc image]: https://pkg.go.dev/badge/github.com/cenkalti/backoff/v7.svg
[google-http-java-client]: https://github.com/google/google-http-java-client/blob/da1aa993e90285ec18579f1553339b00e19b3ab5/google-http-client/src/main/java/com/google/api/client/util/ExponentialBackOff.java
[exponential backoff wiki]: http://en.wikipedia.org/wiki/Exponential_backoff
[retry-src]: https://github.com/cenkalti/backoff/blob/v7/retry.go
[example]: https://github.com/cenkalti/backoff/blob/v7/example_test.go
+70
View File
@@ -0,0 +1,70 @@
// Package backoff implements backoff algorithms for retrying operations.
//
// Use Retry function for retrying operations that may fail.
// If Retry does not meet your needs,
// copy/paste the function into your project and modify as you wish.
//
// On failure Retry returns a *RetryError reporting the last operation error
// and why it stopped; see RetryError, AsRetryError, and the ErrPermanent,
// ErrExhausted, and ErrMaxElapsedTime causes.
//
// There is also Ticker type similar to time.Ticker.
// You can use it if you need to work with channels.
//
// See Examples section below for usage examples.
package backoff
import "time"
// BackOff is a backoff policy for retrying an operation.
type BackOff interface {
// NextBackOff returns the duration to wait before retrying the operation,
// backoff.Stop to indicate that no more retries should be made.
//
// Example usage:
//
// duration := backoff.NextBackOff()
// if duration == backoff.Stop {
// // Do not retry operation.
// } else {
// // Sleep for duration and retry operation.
// }
//
NextBackOff() time.Duration
// Reset to initial state.
Reset()
}
// Stop indicates that no more retries should be made for use in NextBackOff().
const Stop time.Duration = -1
// ZeroBackOff is a fixed backoff policy whose backoff time is always zero,
// meaning that the operation is retried immediately without waiting, indefinitely.
type ZeroBackOff struct{}
func (b *ZeroBackOff) Reset() {}
func (b *ZeroBackOff) NextBackOff() time.Duration { return 0 }
// StopBackOff is a fixed backoff policy that always returns backoff.Stop for
// NextBackOff(), meaning that the operation should never be retried.
type StopBackOff struct{}
func (b *StopBackOff) Reset() {}
func (b *StopBackOff) NextBackOff() time.Duration { return Stop }
// ConstantBackOff is a backoff policy that always returns the same backoff delay.
// This is in contrast to an exponential backoff policy,
// which returns a delay that grows longer as you call NextBackOff() over and over again.
type ConstantBackOff struct {
Interval time.Duration
}
func (b *ConstantBackOff) Reset() {}
func (b *ConstantBackOff) NextBackOff() time.Duration { return b.Interval }
func NewConstantBackOff(d time.Duration) *ConstantBackOff {
return &ConstantBackOff{Interval: d}
}
+146
View File
@@ -0,0 +1,146 @@
package backoff
import (
"errors"
"fmt"
"time"
)
// Cause values reported by RetryError.Cause. Match them with errors.Is.
var (
// ErrPermanent is the cause when the operation returned a Permanent error.
ErrPermanent = errors.New("backoff: permanent error")
// ErrExhausted is the cause when retrying stops because WithMaxTries was
// reached or the backoff policy returned Stop.
ErrExhausted = errors.New("backoff: retries exhausted")
// ErrMaxElapsedTime is the cause when retrying stops because
// WithMaxElapsedTime was reached.
ErrMaxElapsedTime = errors.New("backoff: maximum elapsed time exceeded")
)
// RetryError is the error returned by Retry for every failure. It records the
// last error returned by the operation (LastErr) together with the reason
// retrying stopped (Cause), so callers never lose either piece of information.
//
// Inspect it with errors.Is, errors.As, or AsRetryError:
//
// result, err := backoff.Retry(ctx, op)
// switch {
// case errors.Is(err, backoff.ErrPermanent):
// // operation returned a Permanent error
// case errors.Is(err, context.Canceled):
// // caller cancelled ctx
// case errors.Is(err, backoff.ErrMaxElapsedTime):
// // ran out of the WithMaxElapsedTime budget
// case errors.Is(err, backoff.ErrExhausted):
// // hit WithMaxTries or the backoff policy stopped
// }
//
// if re := backoff.AsRetryError(err); re != nil {
// log.Printf("gave up after last error: %v", re.LastErr)
// }
//
// Because RetryError implements Unwrap() []error, errors.Unwrap (the single
// error form) returns nil for it; use errors.Is, errors.As, or AsRetryError.
type RetryError struct {
// LastErr is the error returned by the final operation attempt. For a
// permanent failure it is the error passed to Permanent.
LastErr error
// Cause reports why retrying stopped: ErrPermanent, ErrExhausted,
// ErrMaxElapsedTime, or a context cancellation cause (see context.Cause).
Cause error
}
// Error returns a single-line representation of the cause and last error.
func (e *RetryError) Error() string {
return fmt.Sprintf("%s (last error: %s)", e.Cause, e.LastErr)
}
// Unwrap returns the cause and the last operation error so both can be
// matched with errors.Is and errors.As.
func (e *RetryError) Unwrap() []error {
return []error{e.Cause, e.LastErr}
}
// AsRetryError returns the *RetryError in err's chain, or nil if there is none
// (including when err is nil). It is a convenience wrapper around errors.As.
func AsRetryError(err error) *RetryError {
var re *RetryError
errors.As(err, &re)
return re
}
// permanent marks an operation error as non-retriable. It is an internal
// transport produced by Permanent and consumed by Retry, which converts it
// into a RetryError with Cause ErrPermanent. It is never returned to callers.
type permanent struct {
err error
}
// Permanent wraps err to signal that Retry should stop immediately instead of
// retrying. Retry then returns a *RetryError with Cause ErrPermanent and
// LastErr set to err. Permanent(nil) returns nil.
func Permanent(err error) error {
if err == nil {
return nil
}
return &permanent{err: err}
}
// Error returns the wrapped error's message.
func (e *permanent) Error() string { return e.err.Error() }
// Unwrap returns the wrapped error.
func (e *permanent) Unwrap() error { return e.err }
// Is reports a match against ErrPermanent so a Permanent error can be detected
// with errors.Is even before Retry converts it into a RetryError.
func (e *permanent) Is(target error) bool { return target == ErrPermanent }
// RetryAfterError signals that the operation should be retried after the given
// duration. When an operation returns one (directly or wrapped), Retry waits
// that duration before the next attempt and resets the backoff policy, so the
// backoff sequence restarts afterward.
//
// The backoff policy still decides whether to retry at all.
// If its NextBackOff returns Stop, Retry stops with ErrExhausted and the requested delay is ignored.
// Limits set with WithMaxTries and WithMaxElapsedTime apply as usual.
//
// The error that triggered the wait (passed to RetryAfter) is available via
// Unwrap, so errors.Is and errors.As see through the RetryAfterError. If
// retrying later stops because a limit is reached or the context ends, Retry
// reports that error as RetryError.LastErr instead of the RetryAfterError
// itself, so the underlying cause is not lost.
type RetryAfterError struct {
Duration time.Duration
err error
}
// RetryAfter returns a RetryAfterError that tells Retry to wait the given
// duration before the next attempt. cause is the error that triggered the
// wait; it is preserved as RetryError.LastErr if retrying stops. Pass a non-nil
// cause so the failure reason is not lost; nil is allowed but discouraged.
func RetryAfter(d time.Duration, cause error) error {
return &RetryAfterError{
Duration: d,
err: cause,
}
}
// Error returns a string representation of the RetryAfter error.
func (e *RetryAfterError) Error() string {
if e.err != nil {
return fmt.Sprintf("%s (retry after %s)", e.err, e.Duration)
}
return fmt.Sprintf("retry after %s", e.Duration)
}
// Unwrap returns the error that triggered the retry, if one was provided.
func (e *RetryAfterError) Unwrap() error {
if e == nil {
return nil
}
return e.err
}
+124
View File
@@ -0,0 +1,124 @@
package backoff
import (
"math"
"math/rand/v2"
"time"
)
/*
ExponentialBackOff is a backoff implementation that increases the backoff
period for each retry attempt using a randomization function that grows exponentially.
NextBackOff() is calculated using the following formula:
randomized interval =
RetryInterval * (random value in range [1 - RandomizationFactor, 1 + RandomizationFactor])
In other words NextBackOff() will range between the randomization factor
percentage below and above the retry interval.
For example, given the following parameters:
RetryInterval = 2
RandomizationFactor = 0.5
Multiplier = 2
the actual backoff period used in the next retry attempt will range between 1 and 3 seconds,
multiplied by the exponential, that is, between 2 and 6 seconds.
Note: MaxInterval caps the RetryInterval and not the randomized interval.
Example: Given the following default arguments, for 9 tries the sequence will be:
Request # RetryInterval (seconds) Randomized Interval (seconds)
1 0.5 [0.25, 0.75]
2 0.75 [0.375, 1.125]
3 1.125 [0.562, 1.687]
4 1.687 [0.8435, 2.53]
5 2.53 [1.265, 3.795]
6 3.795 [1.897, 5.692]
7 5.692 [2.846, 8.538]
8 8.538 [4.269, 12.807]
9 12.807 [6.403, 19.210]
Note: Implementation is not thread-safe.
*/
type ExponentialBackOff struct {
InitialInterval time.Duration
RandomizationFactor float64
Multiplier float64
MaxInterval time.Duration
currentInterval time.Duration
}
// Default values for ExponentialBackOff.
const (
DefaultInitialInterval = 500 * time.Millisecond
DefaultRandomizationFactor = 0.5
DefaultMultiplier = 1.5
DefaultMaxInterval = 60 * time.Second
)
// NewExponentialBackOff creates an instance of ExponentialBackOff using default values.
func NewExponentialBackOff() *ExponentialBackOff {
return &ExponentialBackOff{
InitialInterval: DefaultInitialInterval,
RandomizationFactor: DefaultRandomizationFactor,
Multiplier: DefaultMultiplier,
MaxInterval: DefaultMaxInterval,
}
}
// Reset the interval back to the initial retry interval and restarts the timer.
// Reset must be called before using b.
func (b *ExponentialBackOff) Reset() {
b.currentInterval = b.InitialInterval
}
// NextBackOff calculates the next backoff interval using the formula:
//
// Randomized interval = RetryInterval * (1 ± RandomizationFactor)
func (b *ExponentialBackOff) NextBackOff() time.Duration {
if b.currentInterval == 0 {
b.currentInterval = b.InitialInterval
}
next := getRandomValueFromInterval(b.RandomizationFactor, rand.Float64(), b.currentInterval)
b.incrementCurrentInterval()
return next
}
// Increments the current interval by multiplying it with the multiplier.
func (b *ExponentialBackOff) incrementCurrentInterval() {
// Check for overflow, if overflow is detected set the current interval to the max interval.
if float64(b.currentInterval) >= float64(b.MaxInterval)/b.Multiplier {
b.currentInterval = b.MaxInterval
} else {
b.currentInterval = time.Duration(float64(b.currentInterval) * b.Multiplier)
}
}
// Returns a random value from the following interval:
//
// [currentInterval - randomizationFactor * currentInterval, currentInterval + randomizationFactor * currentInterval].
func getRandomValueFromInterval(randomizationFactor, random float64, currentInterval time.Duration) time.Duration {
if randomizationFactor == 0 {
return currentInterval // make sure no randomness is used when randomizationFactor is 0.
}
var delta = randomizationFactor * float64(currentInterval)
var minInterval = float64(currentInterval) - delta
var maxInterval = float64(currentInterval) + delta
// Get a random value from the range [minInterval, maxInterval].
// The formula used below has a +1 because if the minInterval is 1 and the maxInterval is 3 then
// we want a 33% chance for selecting either 1, 2 or 3.
value := minInterval + (random * (maxInterval - minInterval + 1))
// float64(math.MaxInt64) rounds up to 2^63, which does not fit in a Duration.
if value >= float64(math.MaxInt64) {
return math.MaxInt64
}
return time.Duration(value)
}

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