forked from mtusi2026/mtusi2026lab6
711 lines
20 KiB
Go
711 lines
20 KiB
Go
package main
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"crypto/sha256"
|
|
"encoding/hex"
|
|
"errors"
|
|
"fmt"
|
|
"image"
|
|
"image/color"
|
|
"image/draw"
|
|
"image/jpeg"
|
|
"io"
|
|
"log/slog"
|
|
"math/rand"
|
|
"os"
|
|
"os/signal"
|
|
"strconv"
|
|
"strings"
|
|
"sync"
|
|
"sync/atomic"
|
|
"syscall"
|
|
"time"
|
|
|
|
"mtusi2026lab6-fork/src/internal/model"
|
|
"mtusi2026lab6-fork/src/internal/storage"
|
|
"mtusi2026lab6-fork/src/internal/store"
|
|
"mtusi2026lab6-fork/src/internal/telemetry"
|
|
|
|
"github.com/HugoSmits86/nativewebp"
|
|
"github.com/disintegration/imaging"
|
|
"github.com/redis/go-redis/v9"
|
|
"go.opentelemetry.io/otel"
|
|
"go.opentelemetry.io/otel/attribute"
|
|
"go.opentelemetry.io/otel/metric"
|
|
"go.opentelemetry.io/otel/propagation"
|
|
"go.opentelemetry.io/otel/trace"
|
|
)
|
|
|
|
var instanceID = func() string {
|
|
if h, err := os.Hostname(); err == nil && h != "" {
|
|
return h
|
|
}
|
|
return "worker-unknown"
|
|
}()
|
|
|
|
type cfg struct {
|
|
stream, group, consumer, dlq string
|
|
concurrency int
|
|
lease, jobTimeout time.Duration
|
|
pollEvery, stagingRetention time.Duration
|
|
reclaimIdle time.Duration
|
|
maxBytes, maxPixels int64
|
|
}
|
|
|
|
func envInt(k string, d int) int {
|
|
if v := os.Getenv(k); v != "" {
|
|
if n, e := strconv.Atoi(v); e == nil && n > 0 {
|
|
return n
|
|
}
|
|
}
|
|
return d
|
|
}
|
|
|
|
func loadCfg() cfg {
|
|
return cfg{
|
|
stream: "attachment_jobs",
|
|
group: "worker_group",
|
|
consumer: instanceID,
|
|
dlq: "attachment_jobs_dlq",
|
|
concurrency: envInt("JOB_CONCURRENCY", 2),
|
|
lease: time.Duration(envInt("JOB_LEASE_SECONDS", 90)) * time.Second,
|
|
jobTimeout: time.Duration(envInt("JOB_TIMEOUT_SECONDS", 60)) * time.Second,
|
|
pollEvery: time.Duration(envInt("JOB_POLL_SECONDS", 5)) * time.Second,
|
|
stagingRetention: time.Duration(envInt("STAGING_RETENTION_SECONDS", 300)) * time.Second,
|
|
reclaimIdle: time.Duration(envInt("JOB_RECLAIM_IDLE_SECONDS", 15)) * time.Second,
|
|
maxBytes: int64(envInt("MAX_UPLOAD_BYTES", 10485760)),
|
|
maxPixels: int64(envInt("MAX_IMAGE_PIXELS", 40000000)),
|
|
}
|
|
}
|
|
|
|
type app struct {
|
|
pg store.Store
|
|
s3 *storage.Client
|
|
rdb *redis.Client
|
|
c cfg
|
|
|
|
tracer trace.Tracer
|
|
logger *slog.Logger
|
|
|
|
jobsProcessed metric.Int64Counter
|
|
jobDuration metric.Float64Histogram
|
|
|
|
depth atomic.Int64
|
|
oldestAge atomic.Int64
|
|
inFlight atomic.Int64
|
|
}
|
|
|
|
func faultMarker(name string) string { return "/tmp/.lab6_fault_" + name }
|
|
|
|
func faultExit(point string) {
|
|
if os.Getenv("FAULT_EXIT_AT") != point {
|
|
return
|
|
}
|
|
m := faultMarker("exit_" + point)
|
|
if _, err := os.Stat(m); err == nil {
|
|
return
|
|
}
|
|
_ = os.WriteFile(m, []byte(time.Now().Format(time.RFC3339Nano)), 0o600)
|
|
slog.Info("FAULT deliberate exit", "point", point, "instance", instanceID)
|
|
os.Exit(70)
|
|
}
|
|
|
|
func faultFailure() *procErr {
|
|
mode := os.Getenv("FAULT_FAIL_MODE")
|
|
if mode != "transient" && mode != "permanent" {
|
|
return nil
|
|
}
|
|
limit := envInt("FAULT_FAIL_TIMES", 1000000)
|
|
m := faultMarker("fail_" + mode)
|
|
n := 0
|
|
if b, err := os.ReadFile(m); err == nil {
|
|
n, _ = strconv.Atoi(strings.TrimSpace(string(b)))
|
|
}
|
|
if n >= limit {
|
|
return nil
|
|
}
|
|
_ = os.WriteFile(m, []byte(strconv.Itoa(n+1)), 0o600)
|
|
if mode == "permanent" {
|
|
return pe("invalid_image_format", fmt.Errorf("injected permanent failure #%d", n+1))
|
|
}
|
|
return te("s3_download_failed", fmt.Errorf("injected transient failure #%d", n+1))
|
|
}
|
|
|
|
func main() {
|
|
ctx := context.Background()
|
|
|
|
serviceName := os.Getenv("OTEL_SERVICE_NAME")
|
|
if serviceName == "" {
|
|
serviceName = "messenger-worker"
|
|
}
|
|
|
|
providers, err := telemetry.Init(ctx, serviceName)
|
|
if err != nil {
|
|
slog.Warn("telemetry init failed, running with fallback", "error", err)
|
|
}
|
|
|
|
logger := slog.New(telemetry.NewTraceContextHandler(providers.Logger.Handler()))
|
|
slog.SetDefault(logger)
|
|
|
|
logger.Info("worker starting", "instance", instanceID)
|
|
c := loadCfg()
|
|
|
|
dbURL := os.Getenv("DATABASE_URL")
|
|
if dbURL == "" {
|
|
dbURL = "postgres://lab4:lab4@postgres:5432/lab4?sslmode=disable&timezone=UTC"
|
|
}
|
|
pg, err := store.NewPostgres(dbURL)
|
|
if err != nil {
|
|
logger.Error("postgres connect failed", "error", err)
|
|
os.Exit(1)
|
|
}
|
|
defer pg.Close()
|
|
|
|
brokerURL := os.Getenv("REDIS_URL")
|
|
if brokerURL == "" {
|
|
brokerURL = "redis://broker:6379/1"
|
|
}
|
|
opt, err := redis.ParseURL(brokerURL)
|
|
if err != nil {
|
|
logger.Error("broker url parse failed", "error", err)
|
|
os.Exit(1)
|
|
}
|
|
rdb := redis.NewClient(opt)
|
|
defer rdb.Close()
|
|
|
|
s3c, err := storage.NewClient(storage.ConfigFromEnv())
|
|
if err != nil {
|
|
logger.Error("s3 connect failed", "error", err)
|
|
os.Exit(1)
|
|
}
|
|
|
|
a := &app{pg: pg, s3: s3c, rdb: rdb, c: c, tracer: providers.Tracer, logger: logger}
|
|
initMetrics(a, providers)
|
|
|
|
// нулевые серии с момента старта: дашборд показывает 0, а не No data
|
|
a.jobsProcessed.Add(context.Background(), 0,
|
|
metric.WithAttributes(attribute.String("status", "done")))
|
|
a.jobsProcessed.Add(context.Background(), 0,
|
|
metric.WithAttributes(attribute.String("status", "failed")))
|
|
|
|
if err := rdb.XGroupCreateMkStream(ctx, c.stream, c.group, "0").Err(); err != nil &&
|
|
!strings.Contains(err.Error(), "BUSYGROUP") {
|
|
logger.Error("create group failed", "error", err)
|
|
os.Exit(1)
|
|
}
|
|
|
|
runCtx, cancel := context.WithCancel(context.Background())
|
|
defer cancel()
|
|
go func() {
|
|
q := make(chan os.Signal, 1)
|
|
signal.Notify(q, syscall.SIGINT, syscall.SIGTERM)
|
|
<-q
|
|
logger.Info("shutting down", "instance", instanceID)
|
|
cancel()
|
|
}()
|
|
|
|
logger.Info("worker config",
|
|
"concurrency", c.concurrency, "lease", c.lease, "timeout", c.jobTimeout,
|
|
"reclaimIdle", c.reclaimIdle, "maxBytes", c.maxBytes, "maxPixels", c.maxPixels)
|
|
|
|
var wg sync.WaitGroup
|
|
wg.Add(4)
|
|
go func() { defer wg.Done(); a.consume(runCtx) }()
|
|
go func() { defer wg.Done(); a.recover(runCtx) }()
|
|
go func() { defer wg.Done(); a.janitor(runCtx) }()
|
|
go func() { defer wg.Done(); a.reclaim(runCtx) }()
|
|
|
|
<-runCtx.Done()
|
|
wg.Wait()
|
|
shCtx, shCancel := context.WithTimeout(context.Background(), 5*time.Second)
|
|
defer shCancel()
|
|
_ = providers.Shutdown(shCtx)
|
|
logger.Info("worker stopped gracefully", "instance", instanceID)
|
|
}
|
|
|
|
func initMetrics(a *app, p *telemetry.Providers) {
|
|
if p == nil || p.Meter == nil {
|
|
return
|
|
}
|
|
m := p.Meter
|
|
|
|
a.jobsProcessed, _ = m.Int64Counter("worker_jobs_processed_total",
|
|
metric.WithDescription("Jobs processed by terminal status"))
|
|
a.jobDuration, _ = m.Float64Histogram("worker_job_duration_seconds",
|
|
metric.WithUnit("s"), metric.WithDescription("End-to-end job processing duration"))
|
|
|
|
qd, _ := m.Int64ObservableGauge("attachment_jobs_queue_depth",
|
|
metric.WithDescription("pending+published+processing jobs"))
|
|
oa, _ := m.Int64ObservableGauge("attachment_jobs_oldest_age_seconds",
|
|
metric.WithUnit("s"), metric.WithDescription("Age of the oldest unfinished job (queue lag)"))
|
|
fl, _ := m.Int64ObservableGauge("worker_in_flight_jobs",
|
|
metric.WithDescription("Jobs currently being processed (saturation)"))
|
|
cap, _ := m.Int64ObservableGauge("worker_concurrency_limit",
|
|
metric.WithDescription("Configured max concurrent jobs"))
|
|
acq, _ := m.Int64ObservableGauge("db_pool_acquired_conns")
|
|
idle, _ := m.Int64ObservableGauge("db_pool_idle_conns")
|
|
mx, _ := m.Int64ObservableGauge("db_pool_max_conns")
|
|
|
|
_, _ = m.RegisterCallback(func(_ context.Context, o metric.Observer) error {
|
|
o.ObserveInt64(qd, a.depth.Load())
|
|
o.ObserveInt64(oa, a.oldestAge.Load())
|
|
o.ObserveInt64(fl, a.inFlight.Load())
|
|
o.ObserveInt64(cap, int64(a.c.concurrency))
|
|
st := a.pg.PoolStats()
|
|
o.ObserveInt64(acq, int64(st.AcquiredConns))
|
|
o.ObserveInt64(idle, int64(st.IdleConns))
|
|
o.ObserveInt64(mx, int64(st.MaxConns))
|
|
return nil
|
|
}, qd, oa, fl, cap, acq, idle, mx)
|
|
}
|
|
|
|
// extractParent восстанавливает W3C trace context из полей сообщения брокера.
|
|
func extractParent(values map[string]interface{}) context.Context {
|
|
carrier := propagation.MapCarrier{}
|
|
for k, v := range values {
|
|
if s, ok := v.(string); ok {
|
|
carrier[k] = s
|
|
}
|
|
}
|
|
return otel.GetTextMapPropagator().Extract(context.Background(), carrier)
|
|
}
|
|
|
|
func (a *app) consume(ctx context.Context) {
|
|
sem := make(chan struct{}, a.c.concurrency)
|
|
for {
|
|
if ctx.Err() != nil {
|
|
return
|
|
}
|
|
res, err := a.rdb.XReadGroup(ctx, &redis.XReadGroupArgs{
|
|
Group: a.c.group,
|
|
Consumer: a.c.consumer,
|
|
Streams: []string{a.c.stream, ">"},
|
|
Count: int64(a.c.concurrency),
|
|
Block: 3 * time.Second,
|
|
}).Result()
|
|
if err != nil && !errors.Is(err, redis.Nil) {
|
|
if ctx.Err() != nil {
|
|
return
|
|
}
|
|
a.logger.ErrorContext(ctx, "XReadGroup error", "error", err)
|
|
time.Sleep(time.Second)
|
|
continue
|
|
}
|
|
for _, st := range res {
|
|
for _, m := range st.Messages {
|
|
jobID, _ := m.Values["job_id"].(string)
|
|
if jobID == "" {
|
|
a.ack(ctx, m.ID)
|
|
continue
|
|
}
|
|
parent := extractParent(m.Values)
|
|
sem <- struct{}{}
|
|
go func(msgID, jid string, pctx context.Context) {
|
|
defer func() { <-sem }()
|
|
a.handle(pctx, msgID, jid)
|
|
}(m.ID, jobID, parent)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
func (a *app) recover(ctx context.Context) {
|
|
t := time.NewTicker(a.c.pollEvery)
|
|
defer t.Stop()
|
|
for {
|
|
select {
|
|
case <-ctx.Done():
|
|
return
|
|
case <-t.C:
|
|
if n, err := a.pg.RequeueExpiredLeases(ctx); err != nil {
|
|
a.logger.ErrorContext(ctx, "requeue leases", "error", err)
|
|
} else if n > 0 {
|
|
a.logger.WarnContext(ctx, "requeued expired-lease jobs", "count", n)
|
|
}
|
|
|
|
if n, err := a.pg.QueueDepth(ctx); err == nil {
|
|
a.depth.Store(n)
|
|
}
|
|
if age, err := a.pg.OldestJobAgeSeconds(ctx); err == nil {
|
|
a.oldestAge.Store(int64(age))
|
|
}
|
|
|
|
jobs, err := a.pg.GetPendingJobs(ctx, 20)
|
|
if err != nil {
|
|
a.logger.ErrorContext(ctx, "pending jobs", "error", err)
|
|
continue
|
|
}
|
|
for _, j := range jobs {
|
|
if err := a.publish(ctx, j.ID); err != nil {
|
|
a.logger.WarnContext(ctx, "republish failed", "job_id", j.ID, "error", err)
|
|
continue
|
|
}
|
|
_ = a.pg.UpdateJobStatus(ctx, j.ID, "published", j.Attempts, "")
|
|
a.logger.InfoContext(ctx, "republished job", "job_id", j.ID, "attempt", j.Attempts)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
func (a *app) reclaim(ctx context.Context) {
|
|
t := time.NewTicker(a.c.pollEvery)
|
|
defer t.Stop()
|
|
for {
|
|
select {
|
|
case <-ctx.Done():
|
|
return
|
|
case <-t.C:
|
|
pend, err := a.rdb.XPendingExt(ctx, &redis.XPendingExtArgs{
|
|
Stream: a.c.stream, Group: a.c.group,
|
|
Start: "-", End: "+", Count: 20, Idle: a.c.reclaimIdle,
|
|
}).Result()
|
|
if err != nil && !errors.Is(err, redis.Nil) {
|
|
a.logger.ErrorContext(ctx, "XPendingExt", "error", err)
|
|
continue
|
|
}
|
|
for _, p := range pend {
|
|
msgs, err := a.rdb.XClaim(ctx, &redis.XClaimArgs{
|
|
Stream: a.c.stream, Group: a.c.group, Consumer: a.c.consumer,
|
|
MinIdle: a.c.reclaimIdle, Messages: []string{p.ID},
|
|
}).Result()
|
|
if err != nil {
|
|
continue
|
|
}
|
|
for _, m := range msgs {
|
|
jobID, _ := m.Values["job_id"].(string)
|
|
if jobID == "" {
|
|
a.ack(ctx, m.ID)
|
|
continue
|
|
}
|
|
a.logger.InfoContext(ctx, "reclaimed message",
|
|
"msg_id", m.ID, "job_id", jobID, "idle", p.Idle)
|
|
a.handle(extractParent(m.Values), m.ID, jobID)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
func (a *app) janitor(ctx context.Context) {
|
|
t := time.NewTicker(60 * time.Second)
|
|
defer t.Stop()
|
|
for {
|
|
select {
|
|
case <-ctx.Done():
|
|
return
|
|
case <-t.C:
|
|
refs, err := a.pg.ListCompletedStaging(ctx, time.Now().Add(-a.c.stagingRetention))
|
|
if err != nil {
|
|
a.logger.ErrorContext(ctx, "list staging", "error", err)
|
|
continue
|
|
}
|
|
for _, r := range refs {
|
|
if err := a.s3.DeleteObject(ctx, r.StagingKey); err != nil {
|
|
continue
|
|
}
|
|
_ = a.pg.ClearStagingKey(ctx, r.ID)
|
|
a.logger.InfoContext(ctx, "janitor removed staging", "key", r.StagingKey)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
func (a *app) publish(ctx context.Context, jobID string) error {
|
|
values := map[string]interface{}{"job_id": jobID}
|
|
carrier := propagation.MapCarrier{}
|
|
otel.GetTextMapPropagator().Inject(ctx, carrier)
|
|
for k, v := range carrier {
|
|
values[k] = v
|
|
}
|
|
return a.rdb.XAdd(ctx, &redis.XAddArgs{Stream: a.c.stream, Values: values}).Err()
|
|
}
|
|
|
|
func (a *app) ack(ctx context.Context, msgID string) {
|
|
_ = a.rdb.XAck(ctx, a.c.stream, a.c.group, msgID).Err()
|
|
}
|
|
|
|
func (a *app) handle(parent context.Context, msgID, jobID string) {
|
|
ctx, span := a.tracer.Start(parent, "process_job",
|
|
trace.WithSpanKind(trace.SpanKindConsumer))
|
|
defer span.End()
|
|
span.SetAttributes(
|
|
attribute.String("messaging.system", "redis_streams"),
|
|
attribute.String("messaging.operation", "process"),
|
|
attribute.String("job.id", jobID),
|
|
)
|
|
|
|
a.inFlight.Add(1)
|
|
defer a.inFlight.Add(-1)
|
|
start := time.Now()
|
|
|
|
job, err := a.pg.ClaimJob(ctx, jobID, a.c.consumer, a.c.lease)
|
|
if err != nil {
|
|
if errors.Is(err, store.ErrConflict) {
|
|
if cur, e := a.pg.GetJobByID(ctx, jobID); e == nil {
|
|
a.logger.InfoContext(ctx, "job not claimable, ack", "job_id", jobID, "status", cur.Status)
|
|
}
|
|
a.ack(ctx, msgID)
|
|
return
|
|
}
|
|
a.logger.ErrorContext(ctx, "claim job", "job_id", jobID, "error", err)
|
|
return
|
|
}
|
|
span.SetAttributes(attribute.Int("job.attempt", job.Attempts))
|
|
|
|
faultExit("after_claim")
|
|
|
|
att, err := a.pg.GetAttachmentByID(ctx, job.AttachmentID)
|
|
if err != nil {
|
|
a.observe(ctx, start, "failed")
|
|
a.fail(ctx, msgID, job, job.AttachmentID, "attachment_not_found", err, false)
|
|
return
|
|
}
|
|
if att.Status == "ready" {
|
|
a.logger.InfoContext(ctx, "job already complete, no-op ack", "job_id", jobID)
|
|
_ = a.pg.CompleteAttachment(ctx, att.ID, jobID, att.ObjectKey, nil)
|
|
a.observe(ctx, start, "done")
|
|
a.ack(ctx, msgID)
|
|
return
|
|
}
|
|
if job.Attempts > job.MaxAttempts {
|
|
a.observe(ctx, start, "failed")
|
|
a.fail(ctx, msgID, job, att.ID, "retry_exhausted",
|
|
fmt.Errorf("attempts=%d max=%d", job.Attempts, job.MaxAttempts), false)
|
|
return
|
|
}
|
|
|
|
jctx, cancel := context.WithTimeout(ctx, a.c.jobTimeout)
|
|
defer cancel()
|
|
|
|
variants, finalKey, perr := a.build(jctx, att)
|
|
if perr != nil {
|
|
span.RecordError(perr.err)
|
|
a.observe(ctx, start, "failed")
|
|
a.fail(jctx, msgID, job, att.ID, perr.code, perr.err, !perr.permanent)
|
|
return
|
|
}
|
|
|
|
faultExit("after_s3_before_commit")
|
|
|
|
_, dbSpan := a.tracer.Start(jctx, "db.complete_attachment")
|
|
err = a.pg.CompleteAttachment(jctx, att.ID, jobID, finalKey, variants)
|
|
dbSpan.End()
|
|
if err != nil {
|
|
a.observe(ctx, start, "failed")
|
|
a.fail(ctx, msgID, job, att.ID, "db_commit_failed", err, true)
|
|
return
|
|
}
|
|
|
|
faultExit("after_commit_before_ack")
|
|
|
|
if att.ObjectKey != finalKey {
|
|
if err := a.s3.DeleteObject(ctx, att.ObjectKey); err == nil {
|
|
_ = a.pg.ClearStagingKey(ctx, att.ID)
|
|
}
|
|
}
|
|
a.observe(ctx, start, "done")
|
|
a.ack(ctx, msgID)
|
|
a.logger.InfoContext(ctx, "job done",
|
|
"job_id", jobID, "attempt", job.Attempts, "variants", len(variants),
|
|
"duration_ms", time.Since(start).Milliseconds())
|
|
}
|
|
|
|
func (a *app) observe(ctx context.Context, start time.Time, status string) {
|
|
if a.jobsProcessed == nil {
|
|
return
|
|
}
|
|
attrs := metric.WithAttributes(attribute.String("status", status))
|
|
a.jobsProcessed.Add(ctx, 1, attrs)
|
|
a.jobDuration.Record(ctx, time.Since(start).Seconds(), attrs)
|
|
}
|
|
|
|
type procErr struct {
|
|
code string
|
|
err error
|
|
permanent bool
|
|
}
|
|
|
|
func pe(code string, err error) *procErr { return &procErr{code, err, true} }
|
|
func te(code string, err error) *procErr { return &procErr{code, err, false} }
|
|
|
|
func (a *app) build(ctx context.Context, att *model.Attachment) ([]model.Variant, string, *procErr) {
|
|
if fe := faultFailure(); fe != nil {
|
|
return nil, "", fe
|
|
}
|
|
|
|
_, s3Span := a.tracer.Start(ctx, "s3.get_staging")
|
|
obj, err := a.s3.GetObject(ctx, att.ObjectKey)
|
|
s3Span.End()
|
|
if err != nil {
|
|
return nil, "", te("s3_download_failed", err)
|
|
}
|
|
raw, err := io.ReadAll(io.LimitReader(obj.Body, a.c.maxBytes+1))
|
|
obj.Body.Close()
|
|
if err != nil {
|
|
return nil, "", te("s3_read_failed", err)
|
|
}
|
|
if int64(len(raw)) > a.c.maxBytes {
|
|
return nil, "", pe("image_too_large", fmt.Errorf("bytes=%d", len(raw)))
|
|
}
|
|
|
|
_, decSpan := a.tracer.Start(ctx, "image.decode")
|
|
dcfg, _, err := image.DecodeConfig(bytes.NewReader(raw))
|
|
if err != nil {
|
|
decSpan.End()
|
|
return nil, "", pe("invalid_image_format", err)
|
|
}
|
|
if int64(dcfg.Width)*int64(dcfg.Height) > a.c.maxPixels {
|
|
decSpan.End()
|
|
return nil, "", pe("image_too_many_pixels", fmt.Errorf("%dx%d", dcfg.Width, dcfg.Height))
|
|
}
|
|
img, err := imaging.Decode(bytes.NewReader(raw), imaging.AutoOrientation(true))
|
|
decSpan.End()
|
|
if err != nil {
|
|
return nil, "", pe("invalid_image_format", err)
|
|
}
|
|
|
|
ext := ".png"
|
|
if att.ContentType == "image/jpeg" {
|
|
ext = ".jpg"
|
|
}
|
|
finalKey := "original/" + att.ID + ext
|
|
thumbKey := "variants/" + att.ID + "/thumbnail.jpg"
|
|
cropKey := "variants/" + att.ID + "/crop.jpg"
|
|
optKey := "variants/" + att.ID + "/optimized.webp"
|
|
|
|
if err := a.s3.PutObject(ctx, finalKey, raw, att.ContentType); err != nil {
|
|
return nil, "", te("s3_upload_original_failed", err)
|
|
}
|
|
|
|
_, encSpan := a.tracer.Start(ctx, "image.encode_variants")
|
|
thumb := imaging.Fit(img, 256, 256, imaging.Lanczos)
|
|
tb, err := encodeJPEG(thumb, 85)
|
|
if err != nil {
|
|
encSpan.End()
|
|
return nil, "", pe("jpeg_encode_failed", err)
|
|
}
|
|
crop := imaging.Fill(img, 128, 128, imaging.Center, imaging.Lanczos)
|
|
cb, err := encodeJPEG(crop, 90)
|
|
if err != nil {
|
|
encSpan.End()
|
|
return nil, "", pe("jpeg_encode_failed", err)
|
|
}
|
|
src := img
|
|
if img.Bounds().Dx() > 1280 || img.Bounds().Dy() > 1280 {
|
|
src = imaging.Fit(img, 1280, 1280, imaging.Lanczos)
|
|
}
|
|
ob, err := encodeWebP(src)
|
|
encSpan.End()
|
|
if err != nil {
|
|
return nil, "", pe("webp_encode_failed", err)
|
|
}
|
|
|
|
_, putSpan := a.tracer.Start(ctx, "s3.put_variants")
|
|
for _, o := range []struct {
|
|
key, ct string
|
|
data []byte
|
|
}{
|
|
{thumbKey, "image/jpeg", tb},
|
|
{cropKey, "image/jpeg", cb},
|
|
{optKey, "image/webp", ob},
|
|
} {
|
|
if err := a.s3.PutObject(ctx, o.key, o.data, o.ct); err != nil {
|
|
putSpan.End()
|
|
return nil, "", te("s3_upload_variant_failed", err)
|
|
}
|
|
}
|
|
putSpan.End()
|
|
|
|
mk := func(name, key, ct string, b []byte, im image.Image) model.Variant {
|
|
return model.Variant{
|
|
Name: name, ObjectKey: key, ContentType: ct,
|
|
SizeBytes: int64(len(b)), Width: im.Bounds().Dx(), Height: im.Bounds().Dy(),
|
|
SHA256: sha256Hex(b),
|
|
}
|
|
}
|
|
return []model.Variant{
|
|
mk("thumbnail", thumbKey, "image/jpeg", tb, thumb),
|
|
mk("crop", cropKey, "image/jpeg", cb, crop),
|
|
mk("optimized", optKey, "image/webp", ob, src),
|
|
}, finalKey, nil
|
|
}
|
|
|
|
func flatten(src image.Image) *image.RGBA {
|
|
b := src.Bounds()
|
|
dst := image.NewRGBA(image.Rect(0, 0, b.Dx(), b.Dy()))
|
|
draw.Draw(dst, dst.Bounds(), image.NewUniform(color.RGBA{255, 255, 255, 255}), image.Point{}, draw.Src)
|
|
draw.Draw(dst, dst.Bounds(), src, b.Min, draw.Over)
|
|
return dst
|
|
}
|
|
|
|
func encodeJPEG(src image.Image, q int) ([]byte, error) {
|
|
var buf bytes.Buffer
|
|
if err := jpeg.Encode(&buf, flatten(src), &jpeg.Options{Quality: q}); err != nil {
|
|
return nil, err
|
|
}
|
|
return buf.Bytes(), nil
|
|
}
|
|
|
|
func encodeWebP(src image.Image) ([]byte, error) {
|
|
var buf bytes.Buffer
|
|
if err := nativewebp.Encode(&buf, src, nil); err != nil {
|
|
return nil, err
|
|
}
|
|
return buf.Bytes(), nil
|
|
}
|
|
|
|
func (a *app) fail(ctx context.Context, msgID string, job *model.Job, attID, code string, cause error, transient bool) {
|
|
a.logger.ErrorContext(ctx, "job failed",
|
|
"job_id", job.ID, "code", code, "error", cause,
|
|
"attempt", job.Attempts, "max", job.MaxAttempts)
|
|
|
|
if transient && job.Attempts < job.MaxAttempts {
|
|
delay := backoff(job.Attempts)
|
|
if err := a.pg.RetryJob(ctx, job.ID, attID, code, cause.Error(), delay); err != nil {
|
|
a.logger.ErrorContext(ctx, "retry job", "error", err)
|
|
return
|
|
}
|
|
a.logger.WarnContext(ctx, "job retry scheduled", "job_id", job.ID, "delay", delay)
|
|
a.ack(ctx, msgID)
|
|
return
|
|
}
|
|
|
|
if err := a.pg.FailJob(ctx, job.ID, attID, code, cause.Error()); err != nil {
|
|
a.logger.ErrorContext(ctx, "fail job", "error", err)
|
|
return
|
|
}
|
|
_ = a.rdb.XAdd(ctx, &redis.XAddArgs{
|
|
Stream: a.c.dlq,
|
|
Values: map[string]interface{}{
|
|
"job_id": job.ID, "attachment_id": attID,
|
|
"error_code": code, "attempts": job.Attempts,
|
|
},
|
|
}).Err()
|
|
a.ack(ctx, msgID)
|
|
}
|
|
|
|
func backoff(attempt int) time.Duration {
|
|
if attempt < 1 {
|
|
attempt = 1
|
|
}
|
|
d := float64(5*time.Second) * float64(int(1)<<min(attempt-1, 4))
|
|
if d > float64(60*time.Second) {
|
|
d = float64(60 * time.Second)
|
|
}
|
|
return time.Duration(d * (0.75 + rand.Float64()*0.5))
|
|
}
|
|
|
|
func min(a, b int) int {
|
|
if a < b {
|
|
return a
|
|
}
|
|
return b
|
|
}
|
|
|
|
func sha256Hex(b []byte) string {
|
|
s := sha256.Sum256(b)
|
|
return hex.EncodeToString(s[:])
|
|
}
|