lab6: OpenTelemetry (traces, metrics, logs), Collector, Prometheus, Loki, Tempo, Grafana; перенос trace context через outbox и AMQP

This commit is contained in:
2026-11-12 12:10:30 +03:00
parent 470d9d6f1e
commit 010739d9fa
118 changed files with 15009 additions and 3 deletions
+291
View File
@@ -0,0 +1,291 @@
// Package imaging строит варианты вложения по контракту lab5.
//
// thumbnail JPEG, вписан в 256×256 с сохранением пропорций, без увеличения,
// EXIF orientation применён, alpha компонуется на белый,
// размеры округляются вниз, минимум 1 px (320×200 → 256×160)
// crop JPEG, центрированный квадрат 128×128 (маленькие увеличиваются)
// optimized WebP, вписан в 1280×1280 без увеличения; lossy, качество WEBP_QUALITY,
// метаданные удалены (cwebp -metadata none; пиксели и так
// перекодированы из декодированного изображения, EXIF не переносится)
//
// Все кодировщики детерминированы: одинаковый вход даёт одинаковые байты, поэтому
// повтор job перезаписывает объект тем же содержимым.
package imaging
import (
"bytes"
"context"
"crypto/sha256"
"encoding/binary"
"encoding/hex"
"errors"
"fmt"
"image"
"image/color"
"image/draw"
"image/jpeg"
"image/png"
"os"
"os/exec"
"path/filepath"
xdraw "golang.org/x/image/draw"
)
// ErrDecode — изображение не декодируется: постоянная ошибка (повтор не поможет).
var ErrDecode = errors.New("cannot decode image")
// Params — параметры версии pipeline. Новая версия может менять их, не трогая
// уже опубликованные результаты старой (ключ эффекта включает версию).
type Params struct {
ThumbQuality int
CropQuality int
WebPQuality int
}
// ParamsFor — параметры по номеру версии pipeline.
func ParamsFor(version, webpQuality int) Params {
p := Params{ThumbQuality: 85, CropQuality: 85, WebPQuality: webpQuality}
if version >= 2 {
// v2 (трек 5): чуть выше качество превью — другой, но детерминированный результат.
p.ThumbQuality, p.CropQuality = 92, 92
}
return p
}
// Output — закодированный вариант.
type Output struct {
Name string
ContentType string
Data []byte
Width int
Height int
SHA256 string
}
func newOutput(name, ctype string, data []byte, w, h int) Output {
sum := sha256.Sum256(data)
return Output{Name: name, ContentType: ctype, Data: data, Width: w, Height: h, SHA256: hex.EncodeToString(sum[:])}
}
// Decode декодирует оригинал, применяет EXIF orientation (JPEG) и компонует
// прозрачность на белый фон.
func Decode(data []byte) (*image.RGBA, error) {
src, _, err := image.Decode(bytes.NewReader(data))
if err != nil {
return nil, fmt.Errorf("%w: %v", ErrDecode, err)
}
b := src.Bounds()
// Непрозрачный RGBA (типичный PNG RGB) уже готов: вторая полноразмерная копия
// (4 байта × пиксель) не нужна — для 36 Мпикс это 137 MiB памяти worker.
if rgba, ok := src.(*image.RGBA); ok && b.Min == (image.Point{}) && rgba.Opaque() {
return Orient(rgba, ExifOrientation(data)), nil
}
out := image.NewRGBA(image.Rect(0, 0, b.Dx(), b.Dy()))
draw.Draw(out, out.Bounds(), image.NewUniform(color.White), image.Point{}, draw.Src)
draw.Draw(out, out.Bounds(), src, b.Min, draw.Over) // alpha → на белый
return Orient(out, ExifOrientation(data)), nil
}
// FitSize — вписать w×h в box×box с сохранением пропорций; без увеличения,
// если allowUpscale=false; округление вниз, минимум 1.
func FitSize(w, h, box int, allowUpscale bool) (int, int) {
if !allowUpscale && w <= box && h <= box {
return w, h
}
if w >= h {
nh := h * box / w
return box, max(1, nh)
}
nw := w * box / h
return max(1, nw), box
}
func resize(src image.Image, w, h int) *image.RGBA {
dst := image.NewRGBA(image.Rect(0, 0, w, h))
xdraw.CatmullRom.Scale(dst, dst.Bounds(), src, src.Bounds(), xdraw.Src, nil)
return dst
}
func encodeJPEG(img image.Image, quality int) ([]byte, error) {
var b bytes.Buffer
if err := jpeg.Encode(&b, img, &jpeg.Options{Quality: quality}); err != nil {
return nil, err
}
return b.Bytes(), nil
}
// Thumbnail — JPEG, вписан в 256×256 без увеличения.
func Thumbnail(img *image.RGBA, p Params) (Output, error) {
w, h := FitSize(img.Bounds().Dx(), img.Bounds().Dy(), 256, false)
var src image.Image = img
if w != img.Bounds().Dx() || h != img.Bounds().Dy() {
src = resize(img, w, h)
}
data, err := encodeJPEG(src, p.ThumbQuality)
if err != nil {
return Output{}, err
}
return newOutput("thumbnail", "image/jpeg", data, w, h), nil
}
// Crop — JPEG, центрированный квадрат 128×128 (маленькие исходники увеличиваются).
func Crop(img *image.RGBA, p Params) (Output, error) {
b := img.Bounds()
side := min(b.Dx(), b.Dy())
x0 := b.Min.X + (b.Dx()-side)/2
y0 := b.Min.Y + (b.Dy()-side)/2
sq := img.SubImage(image.Rect(x0, y0, x0+side, y0+side))
data, err := encodeJPEG(resize(sq, 128, 128), p.CropQuality)
if err != nil {
return Output{}, err
}
return newOutput("crop", "image/jpeg", data, 128, 128), nil
}
// WebPEncoder кодирует RGBA в WebP.
type WebPEncoder func(ctx context.Context, img image.Image, quality int) ([]byte, error)
// CWebP — кодировщик через cwebp (libwebp-tools): lossy, -metadata none.
// Вход — PNG во временном каталоге процесса (эфемерный, удаляется сразу).
func CWebP(ctx context.Context, img image.Image, quality int) ([]byte, error) {
dir, err := os.MkdirTemp("", "webp-")
if err != nil {
return nil, err
}
defer os.RemoveAll(dir)
in, out := filepath.Join(dir, "in.png"), filepath.Join(dir, "out.webp")
f, err := os.Create(in)
if err != nil {
return nil, err
}
enc := png.Encoder{CompressionLevel: png.BestSpeed}
if err := enc.Encode(f, img); err != nil {
f.Close()
return nil, err
}
f.Close()
cmd := exec.CommandContext(ctx, "cwebp", "-quiet", "-q", fmt.Sprint(quality), "-m", "4", "-metadata", "none", in, "-o", out)
if msg, err := cmd.CombinedOutput(); err != nil {
return nil, fmt.Errorf("cwebp: %v: %s", err, bytes.TrimSpace(msg))
}
return os.ReadFile(out)
}
// Optimized — WebP, вписан в 1280×1280 без увеличения.
func Optimized(ctx context.Context, img *image.RGBA, p Params, enc WebPEncoder) (Output, error) {
w, h := FitSize(img.Bounds().Dx(), img.Bounds().Dy(), 1280, false)
var src image.Image = img
if w != img.Bounds().Dx() || h != img.Bounds().Dy() {
src = resize(img, w, h)
}
data, err := enc(ctx, src, p.WebPQuality)
if err != nil {
return Output{}, err
}
if len(data) < 12 || string(data[0:4]) != "RIFF" || string(data[8:12]) != "WEBP" {
return Output{}, errors.New("encoder produced non-WebP data")
}
return newOutput("optimized", "image/webp", data, w, h), nil
}
// --- EXIF orientation ---
// ExifOrientation возвращает тег 0x0112 из APP1 Exif JPEG (1 — нет поворота).
func ExifOrientation(data []byte) int {
if len(data) < 4 || data[0] != 0xFF || data[1] != 0xD8 {
return 1
}
i := 2
for i+4 <= len(data) && data[i] == 0xFF {
marker := data[i+1]
if marker == 0xDA || marker == 0xD9 {
break
}
segLen := int(binary.BigEndian.Uint16(data[i+2 : i+4]))
if segLen < 2 || i+2+segLen > len(data) {
break
}
seg := data[i+4 : i+2+segLen]
if marker == 0xE1 && len(seg) > 14 && string(seg[:6]) == "Exif\x00\x00" {
if o := tiffOrientation(seg[6:]); o >= 1 && o <= 8 {
return o
}
}
i += 2 + segLen
}
return 1
}
func tiffOrientation(t []byte) int {
if len(t) < 8 {
return 1
}
var bo binary.ByteOrder
switch string(t[:2]) {
case "II":
bo = binary.LittleEndian
case "MM":
bo = binary.BigEndian
default:
return 1
}
off := int(bo.Uint32(t[4:8]))
if off+2 > len(t) {
return 1
}
n := int(bo.Uint16(t[off : off+2]))
for k := 0; k < n; k++ {
e := off + 2 + 12*k
if e+12 > len(t) {
return 1
}
if bo.Uint16(t[e:e+2]) == 0x0112 {
return int(bo.Uint16(t[e+8 : e+10]))
}
}
return 1
}
// Orient применяет EXIF orientation 1..8 (поворот/отражение).
func Orient(src *image.RGBA, o int) *image.RGBA {
if o <= 1 || o > 8 {
return src
}
b := src.Bounds()
w, h := b.Dx(), b.Dy()
dw, dh := w, h
if o >= 5 {
dw, dh = h, w
}
dst := image.NewRGBA(image.Rect(0, 0, dw, dh))
for y := 0; y < h; y++ {
for x := 0; x < w; x++ {
var dx, dy int
switch o {
case 2:
dx, dy = w-1-x, y
case 3:
dx, dy = w-1-x, h-1-y
case 4:
dx, dy = x, 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.SetRGBA(dx, dy, src.RGBAAt(b.Min.X+x, b.Min.Y+y))
}
}
return dst
}
// SHA256Hex — lowercase hex SHA-256.
func SHA256Hex(data []byte) string {
sum := sha256.Sum256(data)
return hex.EncodeToString(sum[:])
}
+208
View File
@@ -0,0 +1,208 @@
package imaging
import (
"bytes"
"context"
"encoding/binary"
"image"
"image/color"
"image/jpeg"
"image/png"
"os"
"os/exec"
"testing"
)
func solid(w, h int, c color.Color) *image.NRGBA {
m := image.NewNRGBA(image.Rect(0, 0, w, h))
for y := 0; y < h; y++ {
for x := 0; x < w; x++ {
m.Set(x, y, c)
}
}
return m
}
func encPNG(t *testing.T, img image.Image) []byte {
var b bytes.Buffer
if err := png.Encode(&b, img); err != nil {
t.Fatal(err)
}
return b.Bytes()
}
func TestFitSize(t *testing.T) {
cases := []struct {
w, h, box int
up bool
ww, wh int
}{
{320, 200, 256, false, 256, 160}, // fixture курса
{200, 320, 256, false, 160, 256},
{100, 50, 256, false, 100, 50}, // без увеличения
{5000, 1, 256, false, 256, 1}, // минимум 1 px
{1, 5000, 256, false, 1, 256},
{257, 255, 256, false, 256, 254}, // округление вниз
{40, 30, 128, true, 128, 96},
{3000, 2000, 1280, false, 1280, 853},
}
for _, c := range cases {
if w, h := FitSize(c.w, c.h, c.box, c.up); w != c.ww || h != c.wh {
t.Errorf("FitSize(%d,%d,%d,%v)=%d×%d want %d×%d", c.w, c.h, c.box, c.up, w, h, c.ww, c.wh)
}
}
}
func jpegSize(t *testing.T, data []byte) (int, int) {
cfg, err := jpeg.DecodeConfig(bytes.NewReader(data))
if err != nil {
t.Fatal(err)
}
return cfg.Width, cfg.Height
}
func TestCourseFixtureThumbnail(t *testing.T) {
data, err := os.ReadFile("../../tests/fixtures/sample.png")
if err != nil {
t.Skip("fixture not found")
}
img, err := Decode(data)
if err != nil {
t.Fatal(err)
}
th, err := Thumbnail(img, ParamsFor(1, 80))
if err != nil {
t.Fatal(err)
}
if w, h := jpegSize(t, th.Data); w != 256 || h != 160 || th.Width != 256 || th.Height != 160 {
t.Fatalf("thumbnail %d×%d (meta %d×%d), want 256×160", w, h, th.Width, th.Height)
}
again, _ := Thumbnail(img, ParamsFor(1, 80))
if !bytes.Equal(th.Data, again.Data) {
t.Error("thumbnail encoding is not deterministic")
}
cr, err := Crop(img, ParamsFor(1, 80))
if err != nil {
t.Fatal(err)
}
if w, h := jpegSize(t, cr.Data); w != 128 || h != 128 {
t.Fatalf("crop %d×%d", w, h)
}
v2, _ := Thumbnail(img, ParamsFor(2, 80))
if bytes.Equal(v2.Data, th.Data) {
t.Error("pipeline v2 must produce a different thumbnail")
}
}
func TestSmallImageNotUpscaledButCropIs(t *testing.T) {
img, err := Decode(encPNG(t, solid(40, 30, color.RGBA{10, 20, 30, 255})))
if err != nil {
t.Fatal(err)
}
th, _ := Thumbnail(img, ParamsFor(1, 80))
if th.Width != 40 || th.Height != 30 {
t.Errorf("small thumbnail upscaled to %d×%d", th.Width, th.Height)
}
cr, _ := Crop(img, ParamsFor(1, 80))
if w, h := jpegSize(t, cr.Data); w != 128 || h != 128 {
t.Errorf("crop of small image %d×%d", w, h)
}
}
func TestAlphaOnWhite(t *testing.T) {
img, err := Decode(encPNG(t, solid(10, 10, color.NRGBA{0, 0, 0, 0})))
if err != nil {
t.Fatal(err)
}
if c := img.RGBAAt(5, 5); c.R != 255 || c.G != 255 || c.B != 255 {
t.Errorf("transparent pixel composited to %v, want white", c)
}
half, _ := Decode(encPNG(t, solid(4, 4, color.NRGBA{0, 0, 0, 128})))
if c := half.RGBAAt(1, 1); c.R < 120 || c.R > 135 {
t.Errorf("50%% black over white = %v, want ~127", c)
}
}
// withExif вставляет APP1 Exif с orientation сразу после SOI.
func withExif(jpg []byte, orientation uint16) []byte {
var tiff bytes.Buffer
tiff.WriteString("MM\x00\x2a")
binary.Write(&tiff, binary.BigEndian, uint32(8))
binary.Write(&tiff, binary.BigEndian, uint16(1))
binary.Write(&tiff, binary.BigEndian, uint16(0x0112))
binary.Write(&tiff, binary.BigEndian, uint16(3))
binary.Write(&tiff, binary.BigEndian, uint32(1))
binary.Write(&tiff, binary.BigEndian, orientation)
tiff.Write([]byte{0, 0})
binary.Write(&tiff, binary.BigEndian, uint32(0))
seg := append([]byte("Exif\x00\x00"), tiff.Bytes()...)
var out bytes.Buffer
out.Write(jpg[:2])
out.Write([]byte{0xFF, 0xE1})
binary.Write(&out, binary.BigEndian, uint16(len(seg)+2))
out.Write(seg)
out.Write(jpg[2:])
return out.Bytes()
}
func TestExifOrientation(t *testing.T) {
// 300×100: слева красный, справа синий.
src := image.NewRGBA(image.Rect(0, 0, 300, 100))
for y := 0; y < 100; y++ {
for x := 0; x < 300; x++ {
c := color.RGBA{255, 0, 0, 255}
if x >= 150 {
c = color.RGBA{0, 0, 255, 255}
}
src.Set(x, y, c)
}
}
var b bytes.Buffer
jpeg.Encode(&b, src, &jpeg.Options{Quality: 95})
data := withExif(b.Bytes(), 6) // 90° по часовой
if o := ExifOrientation(data); o != 6 {
t.Fatalf("orientation %d, want 6", o)
}
img, err := Decode(data)
if err != nil {
t.Fatal(err)
}
if img.Bounds().Dx() != 100 || img.Bounds().Dy() != 300 {
t.Fatalf("rotated size %v, want 100×300", img.Bounds())
}
// После поворота на 90° по часовой левая (красная) половина оказывается сверху.
if c := img.RGBAAt(50, 20); c.R < 200 || c.B > 60 {
t.Errorf("top after rotation = %v, want red", c)
}
th, _ := Thumbnail(img, ParamsFor(1, 80))
if th.Width != 85 || th.Height != 256 {
t.Errorf("thumbnail of rotated %d×%d, want 85×256", th.Width, th.Height)
}
if ExifOrientation(b.Bytes()) != 1 {
t.Error("no exif must mean orientation 1")
}
}
func TestDecodeGarbage(t *testing.T) {
if _, err := Decode([]byte("not an image")); err == nil {
t.Fatal("garbage decoded")
}
}
func TestOptimizedWebP(t *testing.T) {
if _, err := exec.LookPath("cwebp"); err != nil {
t.Skip("cwebp not installed (worker image has libwebp-tools)")
}
img, _ := Decode(encPNG(t, solid(2000, 1000, color.RGBA{200, 100, 50, 255})))
out, err := Optimized(context.Background(), img, ParamsFor(1, 80), CWebP)
if err != nil {
t.Fatal(err)
}
if out.Width != 1280 || out.Height != 640 || out.ContentType != "image/webp" {
t.Fatalf("optimized %+v", out)
}
again, _ := Optimized(context.Background(), img, ParamsFor(1, 80), CWebP)
if !bytes.Equal(out.Data, again.Data) {
t.Error("cwebp output not deterministic")
}
}