ЛР 5: асинхронная обработка изображений, уровень 5

This commit is contained in:
Nurlygayanova Ekaterina
2026-11-12 20:32:55 +03:00
parent 276dbdad8a
commit 7b3eab5473
115 changed files with 8847 additions and 34 deletions
+209
View File
@@ -0,0 +1,209 @@
// messenger — сервер API мессенджера, один процесс одной реплики. Своего состояния у реплики нет:
// данные лежат в PostgreSQL, сессии в Valkey, поэтому реплик может быть несколько.
//
// Здесь только сборка: загрузка настроек, подключения, создание сервисов, запуск HTTP-сервера и
// штатное завершение по SIGTERM. Логика находится в internal.
package main
import (
"context"
"fmt"
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/pipeline"
"log/slog"
"os"
"os/signal"
"runtime"
"syscall"
"time"
httpapi "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/api/http"
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/cache"
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/config"
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/logging"
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/objectstore"
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/password"
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/service"
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/session"
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/store"
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/store/db"
)
// main запускает сервер и завершается после сигнала остановки. При ошибке запуска код выхода 1.
// os.Exit не выполняет defer, поэтому перед ним подключение к БД закрывается явно.
func main() {
// Настройки из окружения. Логгера ещё нет, поэтому ошибка идёт прямо в stderr.
cfg, err := config.Load()
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
logger, err := logging.New(cfg.Logger.Level, cfg.Env, cfg.Version)
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
slog.SetDefault(logger)
// Пул подключений к PostgreSQL. Без БД реплика работать не может и завершается: Docker её перезапустит.
pool, err := db.Connect(context.Background(), cfg.Database)
if err != nil {
logger.Error("database connect failed", slog.Any("err", err))
os.Exit(1)
}
// Хранилище с таймаутом запросов на все обращения к БД.
storage := db.New(pool, time.Duration(cfg.Database.QueryTimeoutMs)*time.Millisecond)
defer storage.Close()
// Общее хранилище сессий в Valkey: токен, выданный одной репликой, принимают все остальные.
sessClient, err := session.Connect(context.Background(), cfg.Cache)
if err != nil {
logger.Error("session store connect failed", slog.Any("err", err))
storage.Close()
os.Exit(1)
}
defer sessClient.Close()
sessions := session.NewValkey(sessClient)
// Хеширование паролей. Оно тяжёлое, поэтому одновременных вычислений не больше числа ядер и не больше 4.
hasher := password.NewHasher(password.Default, min(runtime.GOMAXPROCS(0), 4))
auth, err := service.NewAuth(storage, sessions, hasher, time.Duration(cfg.Session.TTLSeconds)*time.Second)
if err != nil {
logger.Error("auth init failed", slog.Any("err", err))
storage.Close()
os.Exit(1)
}
// История сообщений по умолчанию читается прямо из БД. Кэш подключается, только если он включён,
// и заменяет собой источник: остальной код разницы не видит.
var messages store.MessageStore = storage
if cfg.HistoryCache.Mode != cache.ModeOff {
hcClient, err := cache.Connect(cfg.HistoryCache)
if err != nil {
logger.Error("history cache config failed", slog.Any("err", err))
storage.Close()
os.Exit(1)
}
defer hcClient.Close()
hc := cache.New(storage.Messages, hcClient, cache.Options{
Mode: cfg.HistoryCache.Mode,
Outbox: storage.Messages,
PageTTL: time.Duration(cfg.HistoryCache.PageTTLSeconds) * time.Second,
FillDelay: time.Duration(cfg.HistoryCache.FillDelayMs) * time.Millisecond,
Logger: logger,
})
defer hc.Close()
messages = hc
}
logger.Info("history cache", slog.String("mode", cfg.HistoryCache.Mode))
// Клиент S3 не обращается к серверу при создании: bucket готовит сервис s3-init.
objects, err := objectstore.NewS3(cfg.S3)
if err != nil {
logger.Error("object store config failed", slog.Any("err", err))
storage.Close()
os.Exit(1)
}
// Сборка HTTP-сервера из готовых зависимостей.
srv := httpapi.NewServer(httpapi.Deps{
Config: cfg,
Logger: logger,
Store: storage,
Auth: auth,
Users: service.NewUsers(storage, hasher),
Chats: service.NewChats(storage),
Messages: service.NewMessages(messages),
Attachments: service.NewAttachments(storage, objects, service.AttachmentLimits{
MaxUploadBytes: cfg.Attachments.MaxUploadBytes,
MaxImagePixels: cfg.Attachments.MaxImagePixels,
MaxConcurrentUploads: cfg.Attachments.MaxConcurrentUploads,
}, logger),
// Readiness: реплика готова, только если доступны и БД, и Valkey. Иначе LB выведет её из
// работы. Схему БД эта проверка не проверяет. S3 сюда намеренно не входит: без него
// недоступны только вложения (503), а пользователи и текстовые сообщения продолжают работать.
// Если бы S3 входил в readiness, его отказ снял бы с балансировки все реплики сразу.
Ready: func(ctx context.Context) error {
if err := storage.Ping(ctx); err != nil {
return err
}
return sessions.Ping(ctx)
},
})
// ctx отменяется при SIGTERM (docker stop) или Ctrl+C: это начало штатного завершения.
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
go pipeline.Dispatch(ctx, pool)
// Фоновая очистка старых ключей идемпотентности. Останавливается вместе с ctx.
go purgeIdempotencyKeys(ctx, storage, time.Duration(cfg.Idempotency.TTLSeconds)*time.Second, logger)
// Сервер блокирует поток до остановки, поэтому запускается отдельно. Буфер 1 не даёт горутине
// зависнуть на отправке, если её уже никто не ждёт.
startErr := make(chan error, 1)
go func() {
startErr <- srv.Start()
}()
// Ждём первое из двух событий: сервер сам завершился или пришёл сигнал остановки.
select {
case err := <-startErr:
if err != nil {
logger.Error("server failed to start", slog.Any("err", err))
storage.Close()
os.Exit(1)
}
case <-ctx.Done():
logger.Info("shutdown signal received")
// Drain: readiness начинает отвечать 503, но запросы ещё обслуживаются. За это время LB
// выводит реплику, поэтому новые запросы перестают приходить до закрытия порта.
srv.Drain(time.Duration(cfg.HTTP.ShutdownDrainMs) * time.Millisecond)
}
// Предел на завершение открытых запросов. Он должен быть меньше stop_grace_period в compose.yaml,
// иначе Docker пришлёт SIGKILL раньше.
shutdownCtx, cancel := context.WithTimeout(
context.Background(),
time.Duration(cfg.HTTP.ShutdownTimeoutMs)*time.Millisecond,
)
defer cancel()
// Закрыть порт и дождаться открытых запросов. Если не успели за предел, это ошибка завершения.
if err := srv.Shutdown(shutdownCtx); err != nil {
logger.Error("shutdown failed", slog.Any("err", err))
storage.Close()
os.Exit(1)
}
// Эта строка в логе подтверждает штатное завершение: её ищет failure-detection.py.
logger.Info("server stopped cleanly")
}
// Как часто удалять устаревшие ключи идемпотентности.
const idempotencyPurgeInterval = time.Hour
// purgeIdempotencyKeys удаляет ключи старше ttl: сразу при запуске и затем по таймеру. Ошибка не
// опасна: очистка просто повторится позже. Удаление работает на каждой реплике, это безопасно,
// потому что удалять будет нечего после первой из них.
func purgeIdempotencyKeys(ctx context.Context, storage *db.DB, ttl time.Duration, logger *slog.Logger) {
t := time.NewTicker(idempotencyPurgeInterval)
defer t.Stop()
for {
if n, err := storage.PurgeIdempotencyKeys(ctx, ttl); err != nil {
// Ошибка из-за остановки сервера ожидаема: просто выходим.
if ctx.Err() != nil {
return
}
logger.Warn("idempotency keys purge failed", slog.Any("err", err))
} else if n > 0 {
logger.Info("idempotency keys purged", slog.Int64("count", n))
}
select {
case <-ctx.Done():
return
case <-t.C:
}
}
}
+55
View File
@@ -0,0 +1,55 @@
// s3init — одноразовая подготовка хранилища: дожидается S3, создаёт bucket, удаляет постороннюю
// политику и проверяет, что bucket приватный. Повторный запуск безопасен: объекты не затрагиваются. Запускается сервисом s3-init до старта API.
package main
import (
"context"
"fmt"
"os"
"time"
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/config"
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/objectstore"
)
const waitLimit = 90 * time.Second
func main() {
if err := run(); err != nil {
fmt.Fprintln(os.Stderr, "s3init:", err)
os.Exit(1)
}
fmt.Println("s3init: bucket is ready and private")
}
func run() error {
cfg, err := config.Load()
if err != nil {
return err
}
s3, err := objectstore.NewS3(cfg.S3)
if err != nil {
return err
}
ctx, cancel := context.WithTimeout(context.Background(), waitLimit)
defer cancel()
// Шлюз S3 может стать здоровым раньше, чем готово хранилище под ним: первые ошибки ожидаемы.
for {
err = s3.EnsureBucket(ctx)
if err == nil {
removed, err := s3.RemovePolicy(ctx)
if err != nil {
return err
}
if removed {
fmt.Println("s3init: foreign bucket policy removed")
}
return s3.CheckPrivate(ctx)
}
select {
case <-ctx.Done():
return err
case <-time.After(time.Second):
}
}
}
+375
View File
@@ -0,0 +1,375 @@
package main
import (
"bytes"
"context"
"encoding/json"
"fmt"
"image"
_ "image/jpeg"
_ "image/png"
"io"
"log"
"math/rand/v2"
"os"
"os/exec"
"os/signal"
"strconv"
"sync"
"syscall"
"time"
"errors"
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/config"
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain"
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/objectstore"
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/pipeline"
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/store/db"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/redis/go-redis/v9"
)
func main() {
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
cfg, err := config.Load()
if err != nil {
log.Fatal(err)
}
pool, err := db.Connect(ctx, cfg.Database)
if err != nil {
log.Fatal(err)
}
defer pool.Close()
objects, err := objectstore.NewS3(cfg.S3)
if err != nil {
log.Fatal(err)
}
if len(os.Args) == 4 && os.Args[1] == "render" {
conn, e := pool.Acquire(ctx)
if e != nil {
os.Exit(1)
}
defer conn.Release()
attempt, _ := strconv.Atoi(os.Args[3])
e = render(ctx, conn, objects, os.Args[2], attempt)
if e != nil {
var pe permanentError
if errors.As(e, &pe) {
os.Exit(42)
}
os.Exit(1)
}
return
}
if len(os.Args) == 3 && os.Args[1] == "replay" {
if err := replay(ctx, pool, objects, os.Args[2]); err != nil {
log.Fatal(err)
}
log.Print("replay queued")
return
}
if len(os.Args) == 2 && os.Args[1] == "failed" {
rows, e := pool.Query(ctx, `SELECT id::text,error_code,attempts FROM attachments WHERE status='failed' ORDER BY updated_at DESC LIMIT 100`)
if e != nil {
log.Fatal(e)
}
defer rows.Close()
for rows.Next() {
var id, code string
var n int
if e = rows.Scan(&id, &code, &n); e != nil {
log.Fatal(e)
}
fmt.Println(id, code, n)
}
if rows.Err() != nil {
log.Fatal(rows.Err())
}
return
}
go pipeline.Dispatch(ctx, pool)
c := pipeline.Client()
defer c.Close()
maxAttempts := 5
if s := os.Getenv("JOB_MAX_ATTEMPTS"); s != "" {
n, e := strconv.Atoi(s)
if e != nil || n < 1 {
log.Fatal("invalid JOB_MAX_ATTEMPTS")
}
maxAttempts = n
}
// Один worker держит сессионную блокировку PostgreSQL. После его смерти новый
// worker возвращает неподтверждённые сообщения в очередь.
lock, err := pool.Acquire(ctx)
if err != nil {
log.Fatal(err)
}
defer lock.Release()
if _, err = lock.Exec(ctx, "SELECT pg_advisory_lock(505001)"); err != nil {
log.Fatal(err)
}
for ctx.Err() == nil {
_, err = c.RPopLPush(ctx, pipeline.Active, pipeline.Pending).Result()
if errors.Is(err, redis.Nil) {
break
}
if err != nil {
log.Fatal("queue recovery failed")
}
}
concurrency := positiveEnv("WORKER_CONCURRENCY", 1, 8)
prefetch := positiveEnv("WORKER_PREFETCH", concurrency, 64)
if prefetch < concurrency {
log.Fatal("WORKER_PREFETCH must be >= WORKER_CONCURRENCY")
}
if int(cfg.Database.MaxConns) < concurrency+2 {
log.Fatal("DB_MAX_CONNS must be >= WORKER_CONCURRENCY+2")
}
slots := make(chan struct{}, prefetch)
jobs := make(chan string, prefetch)
var workers sync.WaitGroup
for i := 0; i < concurrency; i++ {
workers.Add(1)
go func() {
defer workers.Done()
for raw := range jobs {
func() {
defer func() { <-slots }()
conn, e := pool.Acquire(ctx)
if e != nil {
return
} // Active entry is recovered on restart; outbox also retries.
defer conn.Release()
var job pipeline.Job
if json.Unmarshal([]byte(raw), &job) != nil || !validJob(job) {
log.Print("invalid job")
if err := c.Eval(ctx, `redis.call("LPUSH", KEYS[2], ARGV[1]); return redis.call("LREM", KEYS[1], 1, ARGV[1])`, []string{pipeline.Active, "attachments:invalid"}, raw).Err(); err != nil {
return
}
return
}
for ctx.Err() == nil {
done, err := process(ctx, conn, objects, job.AttachmentID, maxAttempts)
if err != nil {
log.Printf("job %s: %v", job.JobID, err)
if conn.Conn().IsClosed() {
log.Fatal("worker database session lost; restart required")
}
}
if done {
if os.Getenv("FAULT_BEFORE_ACK") == "1" {
faultOnce("/tmp/fault-before-ack")
}
if err = c.LRem(ctx, pipeline.Active, 1, raw).Err(); err != nil {
log.Fatal("queue ack failed; restart required")
}
break
}
select {
case <-ctx.Done():
return
case <-time.After(time.Second):
}
}
}()
}
}()
}
defer func() { close(jobs); workers.Wait() }()
for ctx.Err() == nil {
// The owner session alone holds the advisory lock and performs maintenance.
rows, e := lock.Query(ctx, `SELECT o.attachment_id::text FROM attachment_outbox o JOIN attachments a ON a.id=o.attachment_id WHERE a.status='ready' LIMIT 16`)
if e != nil && lock.Conn().IsClosed() {
log.Fatal("worker database session lost; restart required")
}
if e == nil {
var ids []string
for rows.Next() {
var id string
if rows.Scan(&id) == nil {
ids = append(ids, id)
}
}
rows.Close()
for _, id := range ids {
_ = cleanup(ctx, lock, objects, id)
}
}
select {
case slots <- struct{}{}:
case <-ctx.Done():
return
case <-time.After(200 * time.Millisecond):
continue
}
raw, err := c.BRPopLPush(ctx, pipeline.Pending, pipeline.Active, time.Second).Result()
if err != nil {
<-slots
continue
}
select {
case jobs <- raw:
case <-ctx.Done():
<-slots
return
}
}
}
func positiveEnv(name string, fallback, maximum int) int {
value := os.Getenv(name)
if value == "" {
return fallback
}
n, err := strconv.Atoi(value)
if err != nil || n < 1 || n > maximum {
log.Fatalf("invalid %s (1..%d)", name, maximum)
}
return n
}
// One owner with bounded concurrent render processes. A killed render subprocess cannot outlive its deadline.
func process(ctx context.Context, p *pgxpool.Conn, s objectstore.Store, id string, max int) (bool, error) {
var attempt int
err := p.QueryRow(ctx, `UPDATE attachments SET status='processing',attempts=attempts+1,
lease_until=now()+interval '60 seconds',processing_started_at=COALESCE(processing_started_at,now()),updated_at=now()
WHERE id=$1 AND attempts<$2 AND ((status='queued' AND next_attempt_at<=now()) OR
(status='processing' AND lease_until<now())) RETURNING attempts`, id, max).Scan(&attempt)
if errors.Is(err, pgx.ErrNoRows) {
_, err = p.Exec(ctx, `UPDATE attachments SET status='failed',error_code='retry_exhausted',lease_until=NULL,updated_at=now()
WHERE id=$1 AND attempts >= $2 AND (status='queued' OR (status='processing' AND lease_until<now()))`, id, max)
return err == nil, err
}
if err != nil {
return false, err
}
deadline, cancel := context.WithTimeout(ctx, 45*time.Second)
defer cancel()
executable, err := os.Executable()
if err != nil {
return false, err
}
cmd := exec.CommandContext(deadline, executable, "render", id, strconv.Itoa(attempt))
cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true, Pdeathsig: syscall.SIGKILL}
cmd.Cancel = func() error { return syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL) }
cmd.WaitDelay = time.Second
err = cmd.Run()
if err == nil {
return true, nil
}
var ee *exec.ExitError
if errors.As(err, &ee) && ee.ExitCode() == 86 {
os.Exit(86)
}
code := "processing_error"
status := "queued"
if errors.As(err, &ee) && ee.ExitCode() == 42 {
code = "invalid_image"
status = "failed"
}
if attempt >= max {
code = "retry_exhausted"
status = "failed"
}
if deadline.Err() != nil {
code = "processing_timeout"
}
delay := retryDelay(attempt)
_, e := p.Exec(ctx, `UPDATE attachments SET status=$3,error_code=$4,lease_until=NULL,
next_attempt_at=now()+($5 * interval '1 millisecond'),updated_at=now()
WHERE id=$1 AND attempts=$2 AND status='processing'`, id, attempt, status, code, delay.Milliseconds())
// The outbox is still present. Ack only after durable retry/failed state.
return e == nil, e
}
func retryDelay(attempt int) time.Duration {
capMs := int64(1000) << min(max(attempt-1, 0), 6)
return time.Duration(capMs/2+rand.Int64N(capMs/2+1)) * time.Millisecond
}
type permanentError struct{ error }
func faultOnce(path string) {
f, err := os.OpenFile(path, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0600)
if err == nil {
f.Close()
os.Exit(86)
}
}
func render(ctx context.Context, p *pgxpool.Conn, s objectstore.Store, id string, attempt int) error {
var key, ct string
if err := p.QueryRow(ctx, `SELECT object_key,content_type FROM attachments WHERE id=$1 AND attempts=$2 AND status='processing'`, id, attempt).Scan(&key, &ct); err != nil {
return err
}
r, _, err := s.Get(ctx, key)
if err != nil {
return err
}
data, err := io.ReadAll(io.LimitReader(r, 10485761))
r.Close()
if err != nil {
return err
}
if len(data) > 10485760 {
return permanentError{fmt.Errorf("image too large")}
}
cfg, _, err := image.DecodeConfig(bytes.NewReader(data))
if err != nil {
return permanentError{err}
}
if cfg.Width <= 0 || cfg.Height <= 0 || int64(cfg.Width)*int64(cfg.Height) > 40000000 {
return permanentError{fmt.Errorf("invalid image dimensions")}
}
im, _, err := image.Decode(bytes.NewReader(data))
if err != nil {
return permanentError{err}
}
im = orient(im, data)
outputs, err := variants(ctx, im)
if err != nil {
return err
}
original := "originals/" + id
if err = s.Put(ctx, original, ct, bytes.NewReader(data), int64(len(data))); err != nil {
return err
}
var metadata []domain.Variant
for _, o := range outputs {
if err = s.Put(ctx, o.meta.Name+"s/"+id, o.meta.ContentType, bytes.NewReader(o.data), int64(len(o.data))); err != nil {
return err
}
metadata = append(metadata, o.meta)
}
if os.Getenv("FAULT_AFTER_OBJECTS") == "1" {
faultOnce("/tmp/fault-after-objects")
}
meta, _ := json.Marshal(metadata)
thumb, _ := json.Marshal(metadata[0])
result, err := p.Exec(ctx, `UPDATE attachments SET status='ready',object_key=$2,thumbnail=$3,variants=$4,
error_code=NULL,lease_until=NULL,updated_at=now() WHERE id=$1 AND attempts=$5 AND status='processing'`, id, original, thumb, meta, attempt)
if err != nil {
return err
}
if result.RowsAffected() != 1 {
return fmt.Errorf("lost lease")
}
// Terminal state first; cleanup is retried by the worker maintenance loop.
return cleanup(ctx, p, s, id)
}
func cleanup(ctx context.Context, p *pgxpool.Conn, s objectstore.Store, id string) error {
if err := s.Delete(ctx, "staging/"+id); err != nil {
return err
}
_, err := p.Exec(ctx, `DELETE FROM attachment_outbox WHERE attachment_id=$1 AND EXISTS(SELECT 1 FROM attachments WHERE id=$1 AND status='ready')`, id)
return err
}
func validJob(j pipeline.Job) bool {
_, e1 := uuid.Parse(j.JobID)
_, e2 := uuid.Parse(j.AttachmentID)
return e1 == nil && e2 == nil && j.SchemaVersion == 1 && j.PipelineVersion == 1 && j.Type == "attachment.process.v1" && j.Attempt >= 1 && !j.CreatedAt.IsZero()
}
+99
View File
@@ -0,0 +1,99 @@
package main
import (
"bytes"
"encoding/binary"
"image"
)
// EXIF IFD0 Orientation, включая отражения. Исходные байты не изменяются.
func orient(src image.Image, data []byte) image.Image {
orientation := 1
if len(data) > 2 && data[0] == 255 && data[1] == 216 {
for pos := 2; pos+4 <= len(data); {
if data[pos] != 255 {
break
}
marker := data[pos+1]
if marker == 0xda || marker == 0xd9 {
break
}
n := int(binary.BigEndian.Uint16(data[pos+2 : pos+4]))
if n < 2 || pos+2+n > len(data) {
break
}
segment := data[pos+4 : pos+2+n]
if marker == 0xe1 && bytes.HasPrefix(segment, []byte("Exif\x00\x00")) {
orientation = exifOrientation(segment[6:])
break
}
pos += 2 + n
}
}
if orientation < 2 || orientation > 8 {
return src
}
b := src.Bounds()
w, h := b.Dx(), b.Dy()
dw, dh := w, h
if orientation >= 5 {
dw, dh = h, w
}
dst := image.NewNRGBA(image.Rect(0, 0, dw, dh))
for y := 0; y < h; y++ {
for x := 0; x < w; x++ {
dx, dy := x, y
switch orientation {
case 2:
dx = w - 1 - x
case 3:
dx, dy = w-1-x, h-1-y
case 4:
dy = h - 1 - y
case 5:
dx, dy = y, x
case 6:
dx, dy = h-1-y, x
case 7:
dx, dy = h-1-y, w-1-x
case 8:
dx, dy = y, w-1-x
}
dst.Set(dx, dy, src.At(b.Min.X+x, b.Min.Y+y))
}
}
return dst
}
func exifOrientation(b []byte) int {
if len(b) < 8 {
return 1
}
var order binary.ByteOrder
switch string(b[:2]) {
case "II":
order = binary.LittleEndian
case "MM":
order = binary.BigEndian
default:
return 1
}
if order.Uint16(b[2:4]) != 42 {
return 1
}
offset := uint64(order.Uint32(b[4:8]))
if offset+2 > uint64(len(b)) {
return 1
}
count := int(order.Uint16(b[offset : offset+2]))
start := int(offset) + 2
for i := 0; i < count; i++ {
p := start + i*12
if p+12 > len(b) {
break
}
if order.Uint16(b[p:p+2]) == 0x112 && order.Uint16(b[p+2:p+4]) == 3 && order.Uint32(b[p+4:p+8]) == 1 {
return int(order.Uint16(b[p+8 : p+10]))
}
}
return 1
}
+42
View File
@@ -0,0 +1,42 @@
package main
import (
"context"
"fmt"
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/objectstore"
"github.com/google/uuid"
"github.com/jackc/pgx/v5/pgxpool"
)
func replay(ctx context.Context, p *pgxpool.Pool, s objectstore.Store, id string) error {
if _, err := uuid.Parse(id); err != nil {
return fmt.Errorf("invalid attachment id")
}
tx, err := p.Begin(ctx)
if err != nil {
return err
}
defer tx.Rollback(ctx)
var status, key string
if err = tx.QueryRow(ctx, `SELECT status,object_key FROM attachments WHERE id=$1 FOR UPDATE`, id).Scan(&status, &key); err != nil {
return err
}
if status != "failed" {
return fmt.Errorf("replay requires failed state; ready is never reset")
}
body, _, err := s.Get(ctx, key)
if err != nil {
return fmt.Errorf("staging unavailable")
}
body.Close()
if _, err = tx.Exec(ctx, `UPDATE attachments SET status='queued',attempts=0,processing_started_at=NULL,error_code=NULL,lease_until=NULL,next_attempt_at=now(),updated_at=now() WHERE id=$1`, id); err != nil {
return err
}
if _, err = tx.Exec(ctx, `INSERT INTO attachment_outbox(attachment_id) VALUES($1) ON CONFLICT(attachment_id) DO UPDATE SET next_publish_at=now()`, id); err != nil {
return err
}
if _, err = tx.Exec(ctx, `INSERT INTO attachment_replays(attachment_id) VALUES($1)`, id); err != nil {
return err
}
return tx.Commit(ctx)
}
+35
View File
@@ -0,0 +1,35 @@
package main
import (
"bytes"
"image"
"image/color"
"image/jpeg"
)
func thumbnail(im image.Image) ([]byte, int, int, error) {
b := im.Bounds()
w, h := b.Dx(), b.Dy()
nw, nh := w, h
if w > 256 || h > 256 {
if w >= h {
nw = 256
nh = max(1, h*256/w)
} else {
nh = 256
nw = max(1, w*256/h)
}
}
thumb := image.NewRGBA(image.Rect(0, 0, nw, nh))
for y := 0; y < nh; y++ {
for x := 0; x < nw; x++ {
rr, gg, bb, aa := im.At(b.Min.X+x*w/nw, b.Min.Y+y*h/nh).RGBA()
thumb.SetRGBA(x, y, color.RGBA{uint8((rr + 65535 - aa) >> 8), uint8((gg + 65535 - aa) >> 8), uint8((bb + 65535 - aa) >> 8), 255})
}
}
var out bytes.Buffer
if err := jpeg.Encode(&out, thumb, &jpeg.Options{Quality: 85}); err != nil {
return nil, 0, 0, err
}
return out.Bytes(), nw, nh, nil
}
+87
View File
@@ -0,0 +1,87 @@
package main
import (
"bytes"
"context"
"crypto/sha256"
"encoding/hex"
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain"
"image"
"image/color"
"image/jpeg"
"image/png"
"os"
"os/exec"
"syscall"
)
type output struct {
meta domain.Variant
data []byte
}
func newOutput(name, ct string, data []byte, w, h int) output {
sum := sha256.Sum256(data)
return output{domain.Variant{Name: name, ContentType: ct, SizeBytes: int64(len(data)), Width: w, Height: h, SHA256: hex.EncodeToString(sum[:])}, data}
}
// Decode/re-encode drops EXIF/ICC/XMP; orientation is applied before this function.
func variants(ctx context.Context, im image.Image) ([]output, error) {
thumb, w, h, err := thumbnail(im)
if err != nil {
return nil, err
}
out := []output{newOutput("thumbnail", "image/jpeg", thumb, w, h)}
b := im.Bounds()
side := min(b.Dx(), b.Dy())
x, y := b.Min.X+(b.Dx()-side)/2, b.Min.Y+(b.Dy()-side)/2
crop := resize(im, image.Rect(x, y, x+side, y+side), 128, 128)
var buf bytes.Buffer
if err = jpeg.Encode(&buf, crop, &jpeg.Options{Quality: 85}); err != nil {
return nil, err
}
out = append(out, newOutput("crop", "image/jpeg", bytes.Clone(buf.Bytes()), 128, 128))
w, h = b.Dx(), b.Dy()
if w > 1280 || h > 1280 {
if w >= h {
h = max(1, h*1280/w)
w = 1280
} else {
w = max(1, w*1280/h)
h = 1280
}
}
buf.Reset()
if err = png.Encode(&buf, resize(im, b, w, h)); err != nil {
return nil, err
}
f, err := os.CreateTemp("", "optimized-*.png")
if err != nil {
return nil, err
}
defer os.Remove(f.Name())
if _, err = f.Write(buf.Bytes()); err != nil {
f.Close()
return nil, err
}
if err = f.Close(); err != nil {
return nil, err
}
cmd := exec.CommandContext(ctx, "cwebp", "-quiet", "-q", "80", "-metadata", "none", "-o", "-", f.Name())
cmd.SysProcAttr = &syscall.SysProcAttr{Pdeathsig: syscall.SIGKILL}
data, err := cmd.Output()
if err != nil {
return nil, err
}
return append(out, newOutput("optimized", "image/webp", data, w, h)), nil
}
func resize(im image.Image, b image.Rectangle, w, h int) *image.RGBA {
dst := image.NewRGBA(image.Rect(0, 0, w, h))
for y := 0; y < h; y++ {
for x := 0; x < w; x++ {
r, g, bl, a := im.At(b.Min.X+x*b.Dx()/w, b.Min.Y+y*b.Dy()/h).RGBA()
dst.SetRGBA(x, y, color.RGBA{uint8((r + 65535 - a) >> 8), uint8((g + 65535 - a) >> 8), uint8((bl + 65535 - a) >> 8), 255})
}
}
return dst
}
+73
View File
@@ -0,0 +1,73 @@
package main
import (
"bytes"
"context"
"crypto/sha256"
"encoding/hex"
"image"
"image/color"
"image/jpeg"
"os/exec"
"testing"
"time"
)
func TestImageContract(t *testing.T) {
im := image.NewNRGBA(image.Rect(0, 0, 320, 200))
im.SetNRGBA(160, 100, color.NRGBA{R: 255, A: 128})
data, w, h, err := thumbnail(im)
if err != nil {
t.Fatal(err)
}
cfg, err := jpeg.DecodeConfig(bytes.NewReader(data))
if err != nil || w != 256 || h != 160 || cfg.Width != 256 || cfg.Height != 160 {
t.Fatal("thumbnail contract", cfg, err)
}
// Transparent input must become white, not black.
small := image.NewNRGBA(image.Rect(0, 0, 8, 4))
data, w, h, err = thumbnail(small)
decoded, err := jpeg.Decode(bytes.NewReader(data))
if err != nil || w != 8 || h != 4 {
t.Fatal("small image enlarged", err)
}
r, g, b, _ := decoded.At(0, 0).RGBA()
if r < 65000 || g < 65000 || b < 65000 {
t.Fatal("alpha not composited on white")
}
}
func TestRetryDelayBounds(t *testing.T) {
for attempt := 1; attempt <= 12; attempt++ {
ceiling := time.Second << min(attempt-1, 6)
for i := 0; i < 100; i++ {
delay := retryDelay(attempt)
if delay < ceiling/2 || delay > ceiling {
t.Fatalf("attempt %d delay %s outside [%s, %s]", attempt, delay, ceiling/2, ceiling)
}
}
}
}
func TestRealVariants(t *testing.T) {
if _, err := exec.LookPath("cwebp"); err != nil {
t.Skip("cwebp is installed in the worker image")
}
outputs, err := variants(context.Background(), image.NewRGBA(image.Rect(0, 0, 320, 200)))
if err != nil {
t.Fatal(err)
}
for _, output := range outputs {
sum := sha256.Sum256(output.data)
if hex.EncodeToString(sum[:]) != output.meta.SHA256 || int64(len(output.data)) != output.meta.SizeBytes {
t.Fatalf("%s bytes differ from metadata", output.meta.Name)
}
}
crop, err := jpeg.DecodeConfig(bytes.NewReader(outputs[1].data))
if err != nil || crop.Width != 128 || crop.Height != 128 {
t.Fatal("crop", err)
}
webp := outputs[2]
if webp.meta.Width != 320 || webp.meta.Height != 200 || !bytes.Equal(webp.data[:4], []byte("RIFF")) || !bytes.Equal(webp.data[8:12], []byte("WEBP")) {
t.Fatal("WebP contract")
}
}