Реализовать уровень 3: очередь RabbitMQ и обработку изображений
Добавить устойчивый приём с ответом 202, durable jobs, dispatcher с publisher confirms и отдельный worker с ручным ACK. Формировать thumbnail, ограничить retry и защитить результат от повторной доставки. Добавить проверки очереди и адаптировать клиент к асинхронным состояниям.
This commit is contained in:
@@ -0,0 +1 @@
|
||||
*.sh text eol=lf
|
||||
+67
-2
@@ -107,10 +107,13 @@ services:
|
||||
deploy:
|
||||
replicas: ${API_REPLICAS:-2}
|
||||
stop_grace_period: 15s
|
||||
environment:
|
||||
environment: &api-environment
|
||||
<<: *s3-environment
|
||||
S3_ROOT_ACCESS_KEY_ID_FILE: ""
|
||||
S3_ROOT_SECRET_ACCESS_KEY_FILE: ""
|
||||
BROKER_URL_FILE: /run/secrets/broker_url
|
||||
JOB_MAX_ATTEMPTS: ${JOB_MAX_ATTEMPTS:-5}
|
||||
JOB_TIMEOUT_SECONDS: ${JOB_TIMEOUT_SECONDS:-60}
|
||||
UPLOAD_TMP_DIR: /tmp/uploads
|
||||
UPLOAD_CLEANUP_GRACE_SECONDS: ${UPLOAD_CLEANUP_GRACE_SECONDS:-600}
|
||||
# Go 1.22 sees host CPUs; keep parallelism suitable for this 0.5 CPU limit.
|
||||
@@ -127,9 +130,10 @@ services:
|
||||
DATABASE_URL: postgres://${POSTGRES_USER}:${POSTGRES_PASSWORD}@db:5432/${POSTGRES_DB}?sslmode=disable
|
||||
tmpfs:
|
||||
- /tmp/uploads:rw,noexec,nosuid,size=16m,mode=1777
|
||||
volumes:
|
||||
volumes: &api-volumes
|
||||
- ./secrets/s3_api_access_key_id:${S3_ACCESS_KEY_ID_FILE:-/run/secrets/s3_access_key_id}:ro
|
||||
- ./secrets/s3_api_secret_access_key:${S3_SECRET_ACCESS_KEY_FILE:-/run/secrets/s3_secret_access_key}:ro
|
||||
- ./secrets/broker_url:/run/secrets/broker_url:ro
|
||||
- ./secrets/database_url:${DATABASE_URL_FILE:-/run/secrets/database_url}:ro
|
||||
- ./secrets/cache_url:${CACHE_URL_FILE:-/run/secrets/cache_url}:ro
|
||||
depends_on:
|
||||
@@ -146,6 +150,66 @@ services:
|
||||
interval: 5s
|
||||
timeout: 3s
|
||||
retries: 20
|
||||
broker:
|
||||
image: rabbitmq:4.2.0-management
|
||||
hostname: broker
|
||||
environment:
|
||||
RABBITMQ_SERVER_ADDITIONAL_ERL_ARGS: "+S 2:2"
|
||||
RABBITMQ_CTL_ERL_ARGS: "+S 1:1"
|
||||
cpus: 0.5
|
||||
mem_limit: 512m
|
||||
networks: [data]
|
||||
command:
|
||||
- sh
|
||||
- -ec
|
||||
- |
|
||||
export RABBITMQ_DEFAULT_USER="$$(cat /run/secrets/broker_user)"
|
||||
export RABBITMQ_DEFAULT_PASS="$$(cat /run/secrets/broker_password)"
|
||||
exec docker-entrypoint.sh rabbitmq-server
|
||||
volumes:
|
||||
- rabbitmq_data:/var/lib/rabbitmq
|
||||
- ./secrets/broker_user:/run/secrets/broker_user:ro
|
||||
- ./secrets/broker_password:/run/secrets/broker_password:ro
|
||||
healthcheck:
|
||||
test: ["CMD", "rabbitmq-diagnostics", "-q", "ping"]
|
||||
interval: 5s
|
||||
timeout: 5s
|
||||
start_period: 20s
|
||||
retries: 30
|
||||
worker:
|
||||
build: ./src
|
||||
restart: unless-stopped
|
||||
cpus: 1.0
|
||||
mem_limit: 512m
|
||||
networks: [data]
|
||||
environment: *api-environment
|
||||
volumes: *api-volumes
|
||||
command: ["./messenger", "worker"]
|
||||
healthcheck:
|
||||
disable: true
|
||||
depends_on:
|
||||
migrate:
|
||||
condition: service_completed_successfully
|
||||
s3-bootstrap:
|
||||
condition: service_completed_successfully
|
||||
broker:
|
||||
condition: service_healthy
|
||||
dispatcher:
|
||||
build: ./src
|
||||
restart: unless-stopped
|
||||
cpus: 0.25
|
||||
mem_limit: 128m
|
||||
networks: [data]
|
||||
environment: *api-environment
|
||||
volumes: *api-volumes
|
||||
command: ["./messenger", "dispatcher"]
|
||||
healthcheck:
|
||||
disable: true
|
||||
depends_on:
|
||||
migrate:
|
||||
condition: service_completed_successfully
|
||||
broker:
|
||||
condition: service_healthy
|
||||
upload-cleanup:
|
||||
restart: unless-stopped
|
||||
cpus: 0.25
|
||||
@@ -253,6 +317,7 @@ services:
|
||||
retries: 20
|
||||
|
||||
volumes:
|
||||
rabbitmq_data:
|
||||
postgres_data:
|
||||
redis_data:
|
||||
s3_data:
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Synthetic lab5 recovery checks; restarts only this Compose project."""
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / 'tests'))
|
||||
from client import Client, check, Failure
|
||||
|
||||
def compose(*args):
|
||||
return subprocess.check_output(['docker', 'compose', '--project-name', 'highload-lab5', *args], cwd=ROOT, text=True, stderr=subprocess.DEVNULL).strip()
|
||||
|
||||
def sql(query):
|
||||
return compose('exec', '-T', 'db', 'sh', '-c', 'exec psql -U "$POSTGRES_USER" -d "$POSTGRES_DB" -Atc "$1"', 'sh', query)
|
||||
|
||||
def until(fn, seconds=60):
|
||||
deadline = time.monotonic() + seconds
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
value = fn()
|
||||
if value:
|
||||
return value
|
||||
except (OSError, Failure, subprocess.CalledProcessError):
|
||||
pass
|
||||
time.sleep(.5)
|
||||
raise AssertionError('condition timed out')
|
||||
|
||||
def queue_depth():
|
||||
rows=json.loads(compose('exec','-T','broker','rabbitmqctl','-q','list_queues','name','messages_ready','messages_unacknowledged','--formatter','json'))
|
||||
return sum(row['messages_ready']+row['messages_unacknowledged'] for row in rows if row['name']=='attachments.v1')
|
||||
|
||||
|
||||
def main():
|
||||
c = Client(sys.argv[1] if len(sys.argv)>1 else 'http://localhost:8085')
|
||||
alice, bob, _, chat = c.bootstrap()
|
||||
evidence = {}
|
||||
compose('stop', 'worker')
|
||||
try:
|
||||
att, original = c.attachment(alice, chat)
|
||||
c.message(alice, chat, '', attachments=[att['id']])
|
||||
c.call('GET', '/api/v1/attachments/'+att['id']+'/content', 409, actor=bob)
|
||||
until(lambda: queue_depth() > 0)
|
||||
before = queue_depth()
|
||||
compose('stop','dispatcher')
|
||||
compose('restart', 'api', 'broker')
|
||||
until(lambda: c.call('GET','/health/ready')['status']==200)
|
||||
until(lambda: queue_depth() >= int(before))
|
||||
check(queue_depth() == before, 'broker lost queued entries')
|
||||
queued = c.call('GET','/api/v1/attachments/'+att['id'],actor=alice,schema='Attachment')['json']
|
||||
check(queued['status']=='queued','API processed work without worker')
|
||||
compose('start','dispatcher')
|
||||
compose('start','worker')
|
||||
ready = c.wait_ready(bob, att)
|
||||
check(c.call('GET','/api/v1/attachments/'+att['id']+'/content',actor=bob)['bytes']==original,'original lost')
|
||||
evidence['restart_recovery'] = {'attachment_id':att['id'], 'status':ready['status'], 'rabbitmq_messages_before_and_after':int(before)}
|
||||
job = json.loads(sql("SELECT json_build_object('schema_version',1,'job_id',id,'type','attachment.process.v1','attachment_id',attachment_id,'pipeline_version',1,'attempt',1,'created_at',to_char(created_at AT TIME ZONE 'UTC','YYYY-MM-DD\"T\"HH24:MI:SS.US\"Z\"')) FROM attachment_jobs WHERE attachment_id='"+att['id']+"'"))
|
||||
attempts = sql("SELECT attempts FROM attachment_jobs WHERE attachment_id='"+att['id']+"'")
|
||||
for _ in range(3):
|
||||
compose('exec','-T','dispatcher','./messenger','broker-publish',json.dumps(job))
|
||||
until(lambda: queue_depth()==0)
|
||||
check(sql("SELECT attempts FROM attachment_jobs WHERE attachment_id='"+att['id']+"'")==attempts,'terminal duplicate reprocessed')
|
||||
check(c.call('GET','/api/v1/attachments/'+att['id'],actor=bob,schema='Attachment')['json']==ready,'duplicate changed ready metadata')
|
||||
evidence['duplicate_delivery']={'duplicates':3,'unchanged':True}
|
||||
compose('stop','worker')
|
||||
broken,_=c.attachment(alice,chat)
|
||||
# Only this newly created synthetic job is changed to inject S3 failure.
|
||||
sql("UPDATE attachment_jobs SET staging_key='staging/jobs/missing-test-object' WHERE attachment_id='"+broken['id']+"'")
|
||||
compose('start','worker')
|
||||
def failed():
|
||||
value=c.call('GET','/api/v1/attachments/'+broken['id'],actor=alice,schema='Attachment')['json']
|
||||
return value if value['status']=='failed' else None
|
||||
result=until(failed,90)
|
||||
count=int(sql("SELECT attempts FROM attachment_jobs WHERE attachment_id='"+broken['id']+"'"))
|
||||
check(count==5 and result['error_code']=='retry_exhausted','retry not bounded to configured five attempts')
|
||||
c.call('GET','/api/v1/attachments/'+broken['id']+'/content',409,actor=bob)
|
||||
c.call('POST','/api/v1/chats/'+chat['id']+'/messages',409,actor=alice,body={'text':'','attachment_ids':[broken['id']]},headers={'Idempotency-Key':'failed-link-'+broken['id']})
|
||||
evidence['retry_exhaustion']={'attachment_id':broken['id'],'attempts':count,'error_code':result['error_code']}
|
||||
target=ROOT/'.memory/grade3-results.json'
|
||||
target.parent.mkdir(exist_ok=True)
|
||||
target.write_text(json.dumps(evidence,ensure_ascii=False,indent=2)+'\n')
|
||||
print('PASS: worker-off upload, broker/API restart, ready recovery, three duplicates, bounded retry.')
|
||||
finally:
|
||||
compose('start','dispatcher','worker')
|
||||
|
||||
if __name__=='__main__':
|
||||
main()
|
||||
@@ -67,9 +67,22 @@ def main():
|
||||
quote(values["POSTGRES_PASSWORD"], safe=""),
|
||||
quote(values["POSTGRES_DB"], safe=""),
|
||||
)
|
||||
for filename,content in (("broker_user","messenger"),("broker_password",secrets.token_hex(32))):
|
||||
target=secret_dir/filename
|
||||
if not target.exists():
|
||||
target.write_text(content+"\n",encoding="utf-8")
|
||||
os.chmod(target,0o644)
|
||||
broker_url="amqp://{}:{}@broker:5672/%2F".format(
|
||||
quote((secret_dir/"broker_user").read_text().strip(),safe=""),
|
||||
quote((secret_dir/"broker_password").read_text().strip(),safe=""))
|
||||
# Migrate only the generated legacy Redis URL; preserve custom AMQP settings.
|
||||
broker_file=secret_dir/"broker_url"
|
||||
if broker_file.exists() and broker_file.read_text().strip()=="redis://broker:6379/0":
|
||||
broker_file.write_text(broker_url+"\n",encoding="utf-8")
|
||||
for name, content in (
|
||||
("DATABASE_URL_FILE", database_url),
|
||||
("CACHE_URL_FILE", "redis://redis:6379/0"),
|
||||
("BROKER_URL_FILE", broker_url),
|
||||
("S3_ACCESS_KEY_ID_FILE", secrets.token_hex(12)),
|
||||
("S3_SECRET_ACCESS_KEY_FILE", secrets.token_hex(32)),
|
||||
):
|
||||
@@ -81,6 +94,7 @@ def main():
|
||||
/ {
|
||||
"DATABASE_URL_FILE": "database_url",
|
||||
"CACHE_URL_FILE": "cache_url",
|
||||
"BROKER_URL_FILE": "broker_url",
|
||||
"S3_ACCESS_KEY_ID_FILE": "s3_access_key_id",
|
||||
"S3_SECRET_ACCESS_KEY_FILE": "s3_secret_access_key",
|
||||
}[name]
|
||||
|
||||
+3
-3
@@ -1,7 +1,7 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
docker compose --project-name highload-lab5 --env-file .env -f compose.yml restart db redis s3 >/dev/null
|
||||
docker compose --project-name highload-lab5 --env-file .env -f compose.yml up -d --wait db redis s3 >/dev/null
|
||||
docker compose --project-name highload-lab5 --env-file .env -f compose.yml restart api upload-cleanup >/dev/null
|
||||
docker compose --project-name highload-lab5 --env-file .env -f compose.yml restart db redis s3 broker >/dev/null
|
||||
docker compose --project-name highload-lab5 --env-file .env -f compose.yml up -d --wait db redis s3 broker >/dev/null
|
||||
docker compose --project-name highload-lab5 --env-file .env -f compose.yml restart api upload-cleanup worker dispatcher >/dev/null
|
||||
docker compose --project-name highload-lab5 --env-file .env -f compose.yml up -d --wait >/dev/null
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net"
|
||||
"time"
|
||||
|
||||
amqp "github.com/rabbitmq/amqp091-go"
|
||||
)
|
||||
|
||||
const jobQueue = "attachments.v1"
|
||||
|
||||
type jobBroker struct {
|
||||
connection *amqp.Connection
|
||||
channel *amqp.Channel
|
||||
returned chan amqp.Return
|
||||
}
|
||||
|
||||
func openJobBroker(ctx context.Context, address string) (*jobBroker, error) {
|
||||
connection, err := amqp.DialConfig(address, amqp.Config{
|
||||
Heartbeat: 10 * time.Second,
|
||||
Dial: func(network, address string) (net.Conn, error) {
|
||||
return (&net.Dialer{Timeout: 5 * time.Second}).DialContext(ctx, network, address)
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
return nil, errors.New("RabbitMQ connection unavailable")
|
||||
}
|
||||
channel, err := connection.Channel()
|
||||
if err != nil {
|
||||
connection.Close()
|
||||
return nil, errors.New("RabbitMQ channel unavailable")
|
||||
}
|
||||
b := &jobBroker{connection: connection, channel: channel, returned: make(chan amqp.Return, 1)}
|
||||
// Queue metadata and message bodies both survive a broker restart.
|
||||
_, err = channel.QueueDeclare(jobQueue, true, false, false, false, nil)
|
||||
if err == nil {
|
||||
err = channel.Confirm(false)
|
||||
}
|
||||
if err == nil {
|
||||
err = channel.Qos(1, 0, false)
|
||||
}
|
||||
if err != nil {
|
||||
b.Close()
|
||||
return nil, errors.New("RabbitMQ queue initialization failed")
|
||||
}
|
||||
channel.NotifyReturn(b.returned)
|
||||
return b, nil
|
||||
}
|
||||
|
||||
func (b *jobBroker) Close() { b.channel.Close(); b.connection.Close() }
|
||||
|
||||
func (b *jobBroker) Publish(ctx context.Context, body []byte) error {
|
||||
// mandatory catches an unroutable message; confirms alone do not prove routing.
|
||||
confirmation, err := b.channel.PublishWithDeferredConfirmWithContext(ctx, "", jobQueue, true, false, amqp.Publishing{
|
||||
DeliveryMode: amqp.Persistent, ContentType: "application/json", Body: body,
|
||||
})
|
||||
if err != nil {
|
||||
return errors.New("RabbitMQ publication failed")
|
||||
}
|
||||
confirmed, err := confirmation.WaitContext(ctx)
|
||||
if err != nil || !confirmed {
|
||||
return errors.New("RabbitMQ publication not confirmed")
|
||||
}
|
||||
// basic.return precedes basic.ack on the channel; NotifyReturn is buffered.
|
||||
select {
|
||||
case <-b.returned:
|
||||
return errors.New("RabbitMQ message was not routed")
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
@@ -66,7 +66,7 @@ func uploadAttachmentHandler(chats *services.ChatService, attachments *services.
|
||||
writeServiceError(w, err, requestID)
|
||||
return
|
||||
}
|
||||
writeJSON(w, 201, attachment)
|
||||
writeJSON(w, 202, attachment)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -107,12 +107,31 @@ func attachmentHandler(attachments *services.AttachmentService) http.HandlerFunc
|
||||
writeServiceError(w, err, requestID)
|
||||
return
|
||||
}
|
||||
if a.Status != "ready" {
|
||||
writeServiceError(w, services.ErrConflict, requestID)
|
||||
return
|
||||
}
|
||||
if variants, exists := query["variant"]; exists {
|
||||
if len(variants) != 1 {
|
||||
writeError(w, 400, "invalid_request", "invalid variant", requestID)
|
||||
return
|
||||
}
|
||||
if variants[0] != "original" {
|
||||
if variants[0] == "thumbnail" {
|
||||
found := false
|
||||
for _, raw := range a.Variants {
|
||||
if v, ok := raw.(map[string]any); ok && v["name"] == "thumbnail" {
|
||||
a.ObjectKey = "variants/" + a.ID + "/v1/thumbnail.jpg"
|
||||
a.ContentType = "image/jpeg"
|
||||
a.SizeBytes = int64(v["size_bytes"].(float64))
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
writeServiceError(w, services.ErrAttachmentNotFound, requestID)
|
||||
return
|
||||
}
|
||||
} else if variants[0] != "original" {
|
||||
writeServiceError(w, services.ErrAttachmentNotFound, requestID)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -53,7 +53,7 @@ func directUploadHandler(chats *services.ChatService, attachments *services.Atta
|
||||
writeServiceError(w, err, requestID)
|
||||
return
|
||||
}
|
||||
writeJSON(w, 201, a)
|
||||
writeJSON(w, 202, a)
|
||||
return
|
||||
}
|
||||
r.Body = http.MaxBytesReader(w, r.Body, 4096)
|
||||
|
||||
@@ -32,6 +32,12 @@ func serverAddress() string {
|
||||
}
|
||||
|
||||
func main() {
|
||||
if len(os.Args) >= 2 && (os.Args[1] == "worker" || os.Args[1] == "dispatcher" || os.Args[1] == "broker-publish") {
|
||||
if err := runPipeline(os.Args[1]); err != nil {
|
||||
log.Fatal("pipeline initialization failed: ", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
if environment := os.Getenv("APP_ENV"); environment != "" {
|
||||
log.SetPrefix("[" + environment + "] ")
|
||||
}
|
||||
|
||||
@@ -0,0 +1,238 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"github.com/disintegration/imaging"
|
||||
|
||||
"image"
|
||||
"image/color"
|
||||
"image/draw"
|
||||
"image/jpeg"
|
||||
"io"
|
||||
"log"
|
||||
"messenger/src/backend/repositories"
|
||||
"messenger/src/backend/services"
|
||||
"os"
|
||||
"os/signal"
|
||||
"strconv"
|
||||
"strings"
|
||||
"syscall"
|
||||
"time"
|
||||
)
|
||||
|
||||
func positiveEnv(name string, fallback int) (int, error) {
|
||||
s := os.Getenv(name)
|
||||
if s == "" {
|
||||
return fallback, nil
|
||||
}
|
||||
n, e := strconv.Atoi(s)
|
||||
if e != nil || n < 1 || n > 3600 {
|
||||
return 0, errors.New("invalid " + name)
|
||||
}
|
||||
return n, nil
|
||||
}
|
||||
func runPipeline(mode string) error {
|
||||
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
||||
defer stop()
|
||||
db, err := repositories.OpenDatabase(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer db.Close()
|
||||
store := repositories.NewAttachmentStore(db)
|
||||
data, err := os.ReadFile(os.Getenv("BROKER_URL_FILE"))
|
||||
if err != nil {
|
||||
return errors.New("cannot read broker URL")
|
||||
}
|
||||
|
||||
address := strings.TrimSpace(string(data))
|
||||
if mode == "broker-publish" {
|
||||
var job repositories.Job
|
||||
if len(os.Args) != 3 || json.Unmarshal([]byte(os.Args[2]), &job) != nil || job.SchemaVersion != 1 || job.Type != "attachment.process.v1" {
|
||||
return errors.New("valid internal job JSON required")
|
||||
}
|
||||
broker, e := openJobBroker(ctx, address)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
defer broker.Close()
|
||||
publishCtx, cancel := context.WithTimeout(ctx, 10*time.Second)
|
||||
defer cancel()
|
||||
return broker.Publish(publishCtx, []byte(os.Args[2]))
|
||||
}
|
||||
maxAttempts, err := positiveEnv("JOB_MAX_ATTEMPTS", 5)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
seconds, err := positiveEnv("JOB_TIMEOUT_SECONDS", 60)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
timeout := time.Duration(seconds) * time.Second
|
||||
objects, err := repositories.NewObjectStoreFromEnvironment()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for ctx.Err() == nil {
|
||||
broker, e := openJobBroker(ctx, address)
|
||||
if e == nil {
|
||||
if mode == "dispatcher" {
|
||||
e = dispatchJobs(ctx, store, broker)
|
||||
} else {
|
||||
e = consumeJobs(ctx, store, objects, broker, maxAttempts, timeout)
|
||||
}
|
||||
broker.Close()
|
||||
}
|
||||
if e != nil && ctx.Err() == nil {
|
||||
log.Print("pipeline: broker session interrupted; reconnecting")
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
case <-time.After(time.Second):
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func dispatchJobs(ctx context.Context, store *repositories.AttachmentStore, broker *jobBroker) error {
|
||||
for ctx.Err() == nil {
|
||||
jobs, err := store.QueuedJobs(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, job := range jobs {
|
||||
payload, err := json.Marshal(job)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
publishCtx, cancel := context.WithTimeout(ctx, 10*time.Second)
|
||||
err = broker.Publish(publishCtx, payload)
|
||||
cancel()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// Only confirmed publications are marked. Uncertainty causes safe duplicates.
|
||||
if err = store.MarkPublished(ctx, job.ID); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
case <-time.After(time.Second):
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func consumeJobs(ctx context.Context, store *repositories.AttachmentStore, objects services.AttachmentObjects, broker *jobBroker, maxAttempts int, timeout time.Duration) error {
|
||||
deliveries, err := broker.channel.Consume(jobQueue, "", false, false, false, false, nil)
|
||||
if err != nil {
|
||||
return errors.New("RabbitMQ consumer unavailable")
|
||||
}
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return nil
|
||||
case message, ok := <-deliveries:
|
||||
if !ok {
|
||||
return errors.New("RabbitMQ consumer disconnected")
|
||||
}
|
||||
var job repositories.Job
|
||||
if json.Unmarshal(message.Body, &job) != nil || job.SchemaVersion != 1 || job.Type != "attachment.process.v1" {
|
||||
log.Print("worker: invalid internal job rejected")
|
||||
if err = message.Reject(false); err != nil {
|
||||
return err
|
||||
}
|
||||
continue
|
||||
}
|
||||
task, cancel := context.WithTimeout(ctx, timeout)
|
||||
claimed, workErr := store.StartAttempt(task, job, timeout)
|
||||
if workErr == nil && claimed {
|
||||
workErr = store.ProcessJob(task, job, maxAttempts, func(a repositories.Attachment, staging string) ([]repositories.Variant, string, error) {
|
||||
return processImage(task, objects, a, staging)
|
||||
})
|
||||
}
|
||||
cancel()
|
||||
completed := claimed && workErr == nil
|
||||
if workErr == nil && !claimed {
|
||||
completed, workErr = store.JobTerminal(ctx, job.ID)
|
||||
}
|
||||
// Ack after COMMIT of ready/failed or durable retry intent, or terminal no-op.
|
||||
// A closed connection automatically returns unacked deliveries to RabbitMQ.
|
||||
if completed {
|
||||
if err = message.Ack(false); err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
if err = message.Nack(false, true); err != nil {
|
||||
return err
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
case <-time.After(time.Second):
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func processImage(ctx context.Context, objects services.AttachmentObjects, a repositories.Attachment, staging string) ([]repositories.Variant, string, error) {
|
||||
reader, err := objects.Get(ctx, staging)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
data, err := io.ReadAll(io.LimitReader(reader, services.MaxUploadBytes+1))
|
||||
reader.Close()
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
sum := sha256.Sum256(data)
|
||||
if int64(len(data)) != a.SizeBytes || hex.EncodeToString(sum[:]) != a.SHA256 {
|
||||
return nil, "invalid_image", errors.New("staging checksum mismatch")
|
||||
}
|
||||
config, _, err := image.DecodeConfig(bytes.NewReader(data))
|
||||
if err != nil || config.Width < 1 || config.Height < 1 || int64(config.Width) > services.MaxImagePixels/int64(config.Height) {
|
||||
return nil, "invalid_image", errors.New("invalid image dimensions")
|
||||
}
|
||||
source, err := imaging.Decode(bytes.NewReader(data), imaging.AutoOrientation(true))
|
||||
if err != nil {
|
||||
return nil, "invalid_image", err
|
||||
}
|
||||
w, h := source.Bounds().Dx(), source.Bounds().Dy()
|
||||
if w > 256 || h > 256 {
|
||||
if w >= h {
|
||||
h = max(1, h*256/w)
|
||||
w = 256
|
||||
} else {
|
||||
w = max(1, w*256/h)
|
||||
h = 256
|
||||
}
|
||||
}
|
||||
small := imaging.Resize(source, w, h, imaging.Lanczos)
|
||||
white := image.NewRGBA(image.Rect(0, 0, w, h))
|
||||
draw.Draw(white, white.Bounds(), &image.Uniform{C: color.White}, image.Point{}, draw.Src)
|
||||
draw.Draw(white, white.Bounds(), small, image.Point{}, draw.Over)
|
||||
var thumbnail bytes.Buffer
|
||||
if err = jpeg.Encode(&thumbnail, white, &jpeg.Options{Quality: 85}); err != nil {
|
||||
return nil, "processing_failed", err
|
||||
}
|
||||
if err = ctx.Err(); err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
// Deterministic keys make redelivery repeat the same effects.
|
||||
if err = objects.Put(ctx, a.ObjectKey, bytes.NewReader(data), a.SizeBytes, a.ContentType); err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
thumb := thumbnail.Bytes()
|
||||
key := "variants/" + a.ID + "/v1/thumbnail.jpg"
|
||||
if err = objects.Put(ctx, key, bytes.NewReader(thumb), int64(len(thumb)), "image/jpeg"); err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
digest := sha256.Sum256(thumb)
|
||||
return []repositories.Variant{{Name: "thumbnail", ContentType: "image/jpeg", SizeBytes: int64(len(thumb)), Width: w, Height: h, SHA256: hex.EncodeToString(digest[:])}}, "", nil
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"image"
|
||||
"image/color"
|
||||
"image/jpeg"
|
||||
"image/png"
|
||||
"io"
|
||||
"messenger/src/backend/repositories"
|
||||
"testing"
|
||||
)
|
||||
|
||||
type imageObjects map[string][]byte
|
||||
|
||||
func (o imageObjects) Get(_ context.Context, key string) (io.ReadCloser, error) {
|
||||
return io.NopCloser(bytes.NewReader(o[key])), nil
|
||||
}
|
||||
func (o imageObjects) Put(_ context.Context, key string, r io.Reader, _ int64, _ string) error {
|
||||
b, e := io.ReadAll(r)
|
||||
o[key] = b
|
||||
return e
|
||||
}
|
||||
func TestThumbnailContract(t *testing.T) {
|
||||
for _, size := range [][4]int{{320, 200, 256, 160}, {200, 320, 160, 256}, {17, 9, 17, 9}, {1000, 1, 256, 1}} {
|
||||
t.Run(fmt.Sprintf("%dx%d", size[0], size[1]), func(t *testing.T) {
|
||||
var source bytes.Buffer
|
||||
if err := png.Encode(&source, image.NewNRGBA(image.Rect(0, 0, size[0], size[1]))); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
digest := sha256.Sum256(source.Bytes())
|
||||
o := imageObjects{"staging": source.Bytes()}
|
||||
a := repositories.Attachment{ID: "sample", ObjectKey: "originals/sample", SizeBytes: int64(source.Len()), SHA256: hex.EncodeToString(digest[:]), ContentType: "image/png"}
|
||||
variants, code, err := processImage(context.Background(), o, a, "staging")
|
||||
if err != nil {
|
||||
t.Fatalf("%s: %v", code, err)
|
||||
}
|
||||
thumb, err := jpeg.Decode(bytes.NewReader(o["variants/sample/v1/thumbnail.jpg"]))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
wantW, wantH := size[2], size[3]
|
||||
if thumb.Bounds().Dx() != wantW || thumb.Bounds().Dy() != wantH || variants[0].Width != wantW || variants[0].Height != wantH {
|
||||
t.Fatalf("wrong dimensions: %v", thumb.Bounds())
|
||||
}
|
||||
pixel := color.RGBAModel.Convert(thumb.At(0, 0)).(color.RGBA)
|
||||
if pixel.R < 250 || pixel.G < 250 || pixel.B < 250 {
|
||||
t.Fatal("alpha not composited on white")
|
||||
}
|
||||
if !bytes.Equal(o[a.ObjectKey], source.Bytes()) {
|
||||
t.Fatal("original changed")
|
||||
}
|
||||
first := append([]byte{}, o["variants/sample/v1/thumbnail.jpg"]...)
|
||||
if _, _, err = processImage(context.Background(), o, a, "staging"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(o) != 3 || !bytes.Equal(first, o["variants/sample/v1/thumbnail.jpg"]) {
|
||||
t.Fatal("redelivery changed or multiplied effects")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestThumbnailAppliesEXIFOrientation(t *testing.T) {
|
||||
var source bytes.Buffer
|
||||
if err := jpeg.Encode(&source, image.NewRGBA(image.Rect(0, 0, 320, 200)), nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// APP1 Exif, little-endian TIFF, one SHORT Orientation entry with value 6.
|
||||
exif := []byte{'E', 'x', 'i', 'f', 0, 0, 'I', 'I', 42, 0, 8, 0, 0, 0, 1, 0, 0x12, 1, 3, 0, 1, 0, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0}
|
||||
data := append([]byte{}, source.Bytes()[:2]...)
|
||||
data = append(data, 0xff, 0xe1, 0, byte(len(exif)+2))
|
||||
data = append(data, exif...)
|
||||
data = append(data, source.Bytes()[2:]...)
|
||||
digest := sha256.Sum256(data)
|
||||
o := imageObjects{"staging": data}
|
||||
a := repositories.Attachment{ID: "rotated", ObjectKey: "originals/rotated", SizeBytes: int64(len(data)), SHA256: hex.EncodeToString(digest[:]), ContentType: "image/jpeg"}
|
||||
variants, _, err := processImage(context.Background(), o, a, "staging")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if variants[0].Width != 160 || variants[0].Height != 256 {
|
||||
t.Fatalf("orientation ignored: %+v", variants[0])
|
||||
}
|
||||
if !bytes.Equal(o[a.ObjectKey], data) {
|
||||
t.Fatal("original EXIF modified")
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@ package repositories
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"time"
|
||||
)
|
||||
@@ -34,8 +35,12 @@ func (s *AttachmentStore) Create(ctx context.Context, a Attachment) error {
|
||||
func (s *AttachmentStore) GetForMember(ctx context.Context, id, userID string) (Attachment, error) {
|
||||
ctx, cancel := boundedQuery(ctx)
|
||||
defer cancel()
|
||||
a := Attachment{Status: "ready", Variants: []any{}}
|
||||
err := s.db.QueryRow(ctx, `SELECT a.id,a.chat_id,a.owner_id,a.filename,a.object_key,a.content_type,a.size_bytes,a.sha256,a.created_at,a.updated_at FROM attachments a JOIN chat_members cm ON cm.chat_id=a.chat_id WHERE a.id=$1 AND cm.user_id=$2`, id, userID).Scan(&a.ID, &a.ChatID, &a.OwnerID, &a.Filename, &a.ObjectKey, &a.ContentType, &a.SizeBytes, &a.SHA256, &a.CreatedAt, &a.UpdatedAt)
|
||||
a := Attachment{Variants: []any{}}
|
||||
var variants []byte
|
||||
err := s.db.QueryRow(ctx, `SELECT a.id,a.chat_id,a.owner_id,a.filename,a.object_key,a.content_type,a.size_bytes,a.sha256,a.created_at,a.updated_at,a.status,a.variants,a.error_code FROM attachments a JOIN chat_members cm ON cm.chat_id=a.chat_id WHERE a.id=$1 AND cm.user_id=$2`, id, userID).Scan(&a.ID, &a.ChatID, &a.OwnerID, &a.Filename, &a.ObjectKey, &a.ContentType, &a.SizeBytes, &a.SHA256, &a.CreatedAt, &a.UpdatedAt, &a.Status, &variants, &a.ErrorCode)
|
||||
if err == nil {
|
||||
err = json.Unmarshal(variants, &a.Variants)
|
||||
}
|
||||
a.CreatedAt = a.CreatedAt.UTC()
|
||||
a.UpdatedAt = a.UpdatedAt.UTC()
|
||||
return a, err
|
||||
|
||||
@@ -129,11 +129,14 @@ func (s *AttachmentStore) CompleteDirect(ctx context.Context, id, chat, user str
|
||||
return a, err
|
||||
}
|
||||
now := time.Now().UTC().Truncate(time.Microsecond)
|
||||
a = Attachment{ID: u.AttachmentID, ChatID: u.ChatID, OwnerID: u.OwnerID, Filename: u.Filename, ContentType: u.ContentType, SizeBytes: u.SizeBytes, SHA256: u.SHA256, ObjectKey: u.FinalKey, Status: "ready", Variants: []any{}, CreatedAt: now, UpdatedAt: now}
|
||||
a = Attachment{ID: u.AttachmentID, ChatID: u.ChatID, OwnerID: u.OwnerID, Filename: u.Filename, ContentType: u.ContentType, SizeBytes: u.SizeBytes, SHA256: u.SHA256, ObjectKey: u.FinalKey, Status: "queued", Variants: []any{}, CreatedAt: now, UpdatedAt: now}
|
||||
_, err = tx.Exec(ctx, `INSERT INTO attachments(id,chat_id,owner_id,filename,object_key,content_type,size_bytes,sha256,created_at,updated_at) VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10)`, a.ID, a.ChatID, a.OwnerID, a.Filename, a.ObjectKey, a.ContentType, a.SizeBytes, a.SHA256, a.CreatedAt, a.UpdatedAt)
|
||||
if err != nil {
|
||||
return Attachment{}, err
|
||||
}
|
||||
if err = enqueueJob(ctx, tx, a, a.ObjectKey); err != nil {
|
||||
return Attachment{}, err
|
||||
}
|
||||
if _, err = tx.Exec(ctx, `UPDATE direct_uploads SET state='ready',cleanup_after=clock_timestamp(),purge_after=clock_timestamp()+interval '24 hours' WHERE id=$1`, id); err != nil {
|
||||
return Attachment{}, err
|
||||
}
|
||||
|
||||
@@ -11,6 +11,7 @@ import (
|
||||
)
|
||||
|
||||
var ErrAttachmentNotFound = errors.New("attachment not found")
|
||||
var ErrAttachmentFailed = errors.New("attachment failed")
|
||||
|
||||
var ErrIdempotencyConflict = errors.New("idempotency key belongs to a different message")
|
||||
|
||||
@@ -34,16 +35,20 @@ func (s *MessageStore) CreateIdempotent(ctx context.Context, chatID, senderID, t
|
||||
if _, err = tx.Exec(ctx, "SELECT pg_advisory_xact_lock(hashtextextended($1, 0))", scope); err != nil {
|
||||
return Message{}, err
|
||||
}
|
||||
// Validate attachments in this same transaction, including replay.
|
||||
// A shared row lock prevents failure publication racing with a new link.
|
||||
hasFailed := false
|
||||
for _, id := range ids {
|
||||
var exists bool
|
||||
if err = tx.QueryRow(ctx, "SELECT EXISTS(SELECT 1 FROM attachments WHERE id=$1 AND chat_id=$2)", id, chatID).Scan(&exists); err != nil {
|
||||
return Message{}, err
|
||||
}
|
||||
if !exists {
|
||||
var status string
|
||||
err = tx.QueryRow(ctx, "SELECT status FROM attachments WHERE id=$1 AND chat_id=$2 FOR SHARE", id, chatID).Scan(&status)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return Message{}, ErrAttachmentNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return Message{}, err
|
||||
}
|
||||
hasFailed = hasFailed || status == "failed"
|
||||
}
|
||||
|
||||
var message Message
|
||||
err = tx.QueryRow(ctx, `
|
||||
SELECT m.id, m.chat_id, m.sender_id, m.text, m.created_at, ARRAY(SELECT attachment_id::text FROM message_attachments ma WHERE ma.message_id=m.id ORDER BY position)
|
||||
@@ -62,6 +67,10 @@ func (s *MessageStore) CreateIdempotent(ctx context.Context, chatID, senderID, t
|
||||
return Message{}, err
|
||||
}
|
||||
|
||||
if hasFailed {
|
||||
return Message{}, ErrAttachmentFailed
|
||||
}
|
||||
|
||||
// Expiry permits key reuse; it never deletes the original message.
|
||||
if _, err = tx.Exec(ctx, "DELETE FROM message_idempotency WHERE sender_id=$1 AND chat_id=$2 AND key=$3", senderID, chatID, key); err != nil {
|
||||
return Message{}, err
|
||||
|
||||
@@ -0,0 +1,147 @@
|
||||
package repositories
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"time"
|
||||
)
|
||||
|
||||
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"`
|
||||
}
|
||||
type Job struct {
|
||||
SchemaVersion int `json:"schema_version"`
|
||||
ID string `json:"job_id"`
|
||||
Type string `json:"type"`
|
||||
AttachmentID string `json:"attachment_id"`
|
||||
PipelineVersion int `json:"pipeline_version"`
|
||||
Attempt int `json:"attempt"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
// QueuedJobs is also the recovery source when publish/confirm is uncertain.
|
||||
// Re-publication is intentional: a durable intent is never removed by publish.
|
||||
func (s *AttachmentStore) QueuedJobs(ctx context.Context) ([]Job, error) {
|
||||
rows, err := s.db.Query(ctx, `SELECT j.id,j.attachment_id,j.pipeline_version,j.attempts+1,j.created_at FROM attachment_jobs j JOIN attachments a ON a.id=j.attachment_id WHERE a.status IN ('queued','processing') AND j.next_attempt_at<=now() AND (j.lease_until IS NULL OR j.lease_until<now()) AND (j.published_at IS NULL OR j.published_at<now()-interval '30 seconds') ORDER BY j.created_at LIMIT 100`)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
jobs := []Job{}
|
||||
for rows.Next() {
|
||||
j := Job{SchemaVersion: 1, Type: "attachment.process.v1"}
|
||||
if err = rows.Scan(&j.ID, &j.AttachmentID, &j.PipelineVersion, &j.Attempt, &j.CreatedAt); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
j.CreatedAt = j.CreatedAt.UTC()
|
||||
jobs = append(jobs, j)
|
||||
}
|
||||
return jobs, rows.Err()
|
||||
}
|
||||
func (s *AttachmentStore) MarkPublished(ctx context.Context, id string) error {
|
||||
_, err := s.db.Exec(ctx, `UPDATE attachment_jobs SET published_at=now() WHERE id=$1`, id)
|
||||
return err
|
||||
}
|
||||
|
||||
// Claim holds a PostgreSQL row lock across object effects. Concurrent deliveries
|
||||
// skip the lock. A process crash releases it; the persisted lease bounds recovery.
|
||||
func (s *AttachmentStore) ProcessJob(ctx context.Context, j Job, maxAttempts int, process func(Attachment, string) ([]Variant, string, error)) error {
|
||||
tx, err := s.db.Begin(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback(context.Background())
|
||||
var staging string
|
||||
var attempts, version int
|
||||
var a Attachment
|
||||
err = tx.QueryRow(ctx, `SELECT a.id,a.object_key,a.content_type,a.size_bytes,a.sha256,a.status,j.staging_key,j.attempts,j.pipeline_version FROM attachment_jobs j JOIN attachments a ON a.id=j.attachment_id WHERE j.id=$1 AND j.attachment_id=$2 FOR UPDATE OF j,a SKIP LOCKED`, j.ID, j.AttachmentID).Scan(&a.ID, &a.ObjectKey, &a.ContentType, &a.SizeBytes, &a.SHA256, &a.Status, &staging, &attempts, &version)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if a.Status == "ready" || a.Status == "failed" || version != j.PipelineVersion {
|
||||
return nil
|
||||
}
|
||||
var due bool
|
||||
if err = tx.QueryRow(ctx, `SELECT next_attempt_at<=now() FROM attachment_jobs WHERE id=$1`, j.ID).Scan(&due); err != nil {
|
||||
return err
|
||||
}
|
||||
if !due {
|
||||
return nil
|
||||
}
|
||||
// Attempts include interrupted executions: StartAttempt commits the counter.
|
||||
if attempts > maxAttempts {
|
||||
_, err = tx.Exec(ctx, `UPDATE attachments SET status='failed',error_code='retry_exhausted',updated_at=now() WHERE id=$1`, a.ID)
|
||||
} else {
|
||||
variants, code, workErr := process(a, staging)
|
||||
if workErr == nil {
|
||||
data, e := json.Marshal(variants)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
_, err = tx.Exec(ctx, `UPDATE attachments SET status='ready',variants=$2,error_code=NULL,updated_at=now() WHERE id=$1`, a.ID, data)
|
||||
} else if code != "" || attempts >= maxAttempts {
|
||||
if code == "" {
|
||||
code = "retry_exhausted"
|
||||
}
|
||||
_, err = tx.Exec(ctx, `UPDATE attachments SET status='failed',error_code=$2,updated_at=now() WHERE id=$1`, a.ID, code)
|
||||
} else {
|
||||
_, err = tx.Exec(ctx, `UPDATE attachments SET status='queued',error_code=NULL,updated_at=now() WHERE id=$1`, a.ID)
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = tx.Exec(ctx, `UPDATE attachment_jobs SET lease_until=NULL,published_at=NULL,next_attempt_at=now()+interval '2 seconds' WHERE id=$1`, j.ID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Commit(ctx)
|
||||
}
|
||||
|
||||
// StartAttempt publishes processing before the long transaction starts; expired
|
||||
// leases are recoverable from PostgreSQL even if the broker delivery is pending.
|
||||
func (s *AttachmentStore) StartAttempt(ctx context.Context, j Job, timeout time.Duration) (bool, error) {
|
||||
tx, err := s.db.Begin(ctx)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
defer tx.Rollback(context.Background())
|
||||
var id string
|
||||
err = tx.QueryRow(ctx, `UPDATE attachment_jobs j SET attempts=attempts+1,lease_until=now()+$2*interval '1 second' FROM attachments a WHERE j.id=$1 AND a.id=j.attachment_id AND a.status IN ('queued','processing') AND (j.lease_until IS NULL OR j.lease_until<now()) AND j.next_attempt_at<=now() RETURNING j.attachment_id`, j.ID, timeout.Seconds()+10).Scan(&id)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return false, nil
|
||||
}
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
if _, err = tx.Exec(ctx, `UPDATE attachments SET status='processing',updated_at=now() WHERE id=$1`, id); err != nil {
|
||||
return false, err
|
||||
}
|
||||
return true, tx.Commit(ctx)
|
||||
}
|
||||
|
||||
func enqueueJob(ctx context.Context, tx pgx.Tx, a Attachment, staging string) error {
|
||||
_, err := tx.Exec(ctx, `UPDATE attachments SET status='queued' WHERE id=$1`, a.ID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = tx.Exec(ctx, `INSERT INTO attachment_jobs(id,attachment_id,staging_key) VALUES($1,$2,$3)`, uuid.NewString(), a.ID, staging)
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *AttachmentStore) JobTerminal(ctx context.Context, id string) (bool, error) {
|
||||
var done bool
|
||||
err := s.db.QueryRow(ctx, `SELECT a.status IN ('ready','failed') FROM attachment_jobs j JOIN attachments a ON a.id=j.attachment_id WHERE j.id=$1`, id).Scan(&done)
|
||||
return done, err
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
DROP TABLE attachment_jobs;
|
||||
ALTER TABLE attachments DROP COLUMN status, DROP COLUMN variants, DROP COLUMN error_code;
|
||||
@@ -0,0 +1,10 @@
|
||||
ALTER TABLE attachments ADD COLUMN status text NOT NULL DEFAULT 'ready' CHECK(status IN ('queued','processing','ready','failed'));
|
||||
ALTER TABLE attachments ADD COLUMN variants jsonb NOT NULL DEFAULT '[]';
|
||||
ALTER TABLE attachments ADD COLUMN error_code text;
|
||||
CREATE TABLE attachment_jobs (
|
||||
id uuid PRIMARY KEY, attachment_id uuid NOT NULL UNIQUE REFERENCES attachments(id),
|
||||
staging_key text NOT NULL, pipeline_version integer NOT NULL DEFAULT 1,
|
||||
attempts integer NOT NULL DEFAULT 0, next_attempt_at timestamptz NOT NULL DEFAULT now(),
|
||||
lease_until timestamptz, published_at timestamptz,
|
||||
created_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
@@ -68,7 +68,7 @@ func BootstrapS3(ctx context.Context) error {
|
||||
}
|
||||
policy := map[string]any{"Version": "2012-10-17", "Statement": []any{
|
||||
map[string]any{"Effect": "Allow", "Action": []string{"s3:GetBucketLocation", "s3:ListBucket"}, "Resource": []string{"arn:aws:s3:::" + store.bucket}},
|
||||
map[string]any{"Effect": "Allow", "Action": []string{"s3:GetObject", "s3:PutObject", "s3:DeleteObject"}, "Resource": []string{"arn:aws:s3:::" + store.bucket + "/originals/*", "arn:aws:s3:::" + store.bucket + "/staging/direct/*"}},
|
||||
map[string]any{"Effect": "Allow", "Action": []string{"s3:GetObject", "s3:PutObject", "s3:DeleteObject"}, "Resource": []string{"arn:aws:s3:::" + store.bucket + "/originals/*", "arn:aws:s3:::" + store.bucket + "/staging/direct/*", "arn:aws:s3:::" + store.bucket + "/staging/jobs/*", "arn:aws:s3:::" + store.bucket + "/variants/*"}},
|
||||
}}
|
||||
data, err := json.Marshal(policy)
|
||||
if err != nil {
|
||||
|
||||
@@ -37,10 +37,13 @@ func (s *AttachmentStore) PublishUpload(ctx context.Context, a Attachment, put f
|
||||
if err = put(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = tx.Exec(ctx, `INSERT INTO attachments(id,chat_id,owner_id,filename,object_key,content_type,size_bytes,sha256,created_at,updated_at) VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10)`, a.ID, a.ChatID, a.OwnerID, a.Filename, a.ObjectKey, a.ContentType, a.SizeBytes, a.SHA256, a.CreatedAt, a.UpdatedAt)
|
||||
_, err = tx.Exec(ctx, `INSERT INTO attachments(id,chat_id,owner_id,filename,object_key,content_type,size_bytes,sha256,created_at,updated_at) VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10)`, a.ID, a.ChatID, a.OwnerID, a.Filename, "originals/"+a.ID, a.ContentType, a.SizeBytes, a.SHA256, a.CreatedAt, a.UpdatedAt)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err = enqueueJob(ctx, tx, a, a.ObjectKey); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err = tx.Exec(ctx, "DELETE FROM upload_attempts WHERE id=$1", a.ID); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -120,11 +123,11 @@ func (s *AttachmentStore) cleanupUpload(ctx context.Context, id string, dryRun b
|
||||
}
|
||||
// Restrict destructive actions to server-generated keys even if a journal row is malformed.
|
||||
parsed, err := uuid.Parse(id)
|
||||
if err != nil || key != "originals/"+parsed.String() {
|
||||
if err != nil || (key != "originals/"+parsed.String() && key != "staging/jobs/"+parsed.String()) {
|
||||
return "", errors.New("invalid upload journal key")
|
||||
}
|
||||
var ready bool
|
||||
if err = tx.QueryRow(ctx, "SELECT EXISTS(SELECT 1 FROM attachments WHERE object_key=$1)", key).Scan(&ready); err != nil {
|
||||
if err = tx.QueryRow(ctx, "SELECT EXISTS(SELECT 1 FROM attachments WHERE object_key=$1 UNION ALL SELECT 1 FROM attachment_jobs WHERE staging_key=$1)", key).Scan(&ready); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if dryRun {
|
||||
|
||||
@@ -131,8 +131,8 @@ func (s *AttachmentService) Upload(ctx context.Context, userID, chatID, filename
|
||||
return repositories.Attachment{}, err
|
||||
}
|
||||
now := time.Now().UTC().Truncate(time.Microsecond)
|
||||
a := repositories.Attachment{ID: uuid.NewString(), ChatID: chatID, OwnerID: userID, Filename: filename, ContentType: actual, SizeBytes: size, SHA256: hex.EncodeToString(hash.Sum(nil)), Status: "ready", Variants: []any{}, CreatedAt: now, UpdatedAt: now}
|
||||
a.ObjectKey = "originals/" + a.ID
|
||||
a := repositories.Attachment{ID: uuid.NewString(), ChatID: chatID, OwnerID: userID, Filename: filename, ContentType: actual, SizeBytes: size, SHA256: hex.EncodeToString(hash.Sum(nil)), Status: "queued", Variants: []any{}, CreatedAt: now, UpdatedAt: now}
|
||||
a.ObjectKey = "staging/jobs/" + a.ID
|
||||
if err = s.metadata.ReserveUpload(ctx, a, grace); err != nil {
|
||||
return repositories.Attachment{}, err
|
||||
}
|
||||
|
||||
@@ -34,7 +34,7 @@ func (s *MessageService) CreateIdempotent(ctx context.Context, userID string, ch
|
||||
if errors.Is(err, repositories.ErrAttachmentNotFound) {
|
||||
return repositories.Message{}, ErrAttachmentNotFound
|
||||
}
|
||||
if errors.Is(err, repositories.ErrIdempotencyConflict) {
|
||||
if errors.Is(err, repositories.ErrIdempotencyConflict) || errors.Is(err, repositories.ErrAttachmentFailed) {
|
||||
return repositories.Message{}, ErrConflict
|
||||
}
|
||||
return message, err
|
||||
|
||||
@@ -129,9 +129,13 @@ func TestDirectUploadFlow(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
router := attachmentRouter(f, objects)
|
||||
content := attachmentCall(t, f, router, "GET", "/api/v1/attachments/"+a.ID+"/content", user, "", nil, 200)
|
||||
if !bytes.Equal(content.Body.Bytes(), sample.data) {
|
||||
t.Fatal("original bytes changed")
|
||||
attachmentCall(t, f, router, "GET", "/api/v1/attachments/"+a.ID+"/content", user, "", nil, 409)
|
||||
if a.Status != "queued" {
|
||||
t.Fatal("direct complete must queue processing")
|
||||
}
|
||||
var jobs int
|
||||
if err = f.db.QueryRow(context.Background(), "SELECT count(*) FROM attachment_jobs WHERE attachment_id=$1", a.ID).Scan(&jobs); err != nil || jobs != 1 {
|
||||
t.Fatal("durable job missing", err)
|
||||
}
|
||||
message := []byte(`{"text":"","attachment_ids":["` + a.ID + `"]}`)
|
||||
attachmentCall(t, f, router, "POST", "/api/v1/chats/"+chat+"/messages", user, "application/json", message, 201)
|
||||
@@ -198,7 +202,7 @@ func TestDirectUploadValidationHTTP(t *testing.T) {
|
||||
if status := postDirect(t, result.Upload, uploadPNG(t), nil); status != 204 {
|
||||
t.Fatal("HTTP-created form failed")
|
||||
}
|
||||
attachmentCall(t, f, router, "POST", path+"/"+result.ID+"/complete", user, "", nil, 201)
|
||||
attachmentCall(t, f, router, "POST", path+"/"+result.ID+"/complete", user, "", nil, 202)
|
||||
}
|
||||
|
||||
func TestDirectUploadValidationContents(t *testing.T) {
|
||||
|
||||
@@ -107,6 +107,13 @@ func newTestFixture(t *testing.T) *testFixture {
|
||||
if _, err = db.Exec(ctx, string(ddl)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ddl, err = os.ReadFile("../repositories/migrations/000007_jobs.up.sql")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = db.Exec(ctx, string(ddl)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = redisClient.Close() })
|
||||
if err := redisClient.Ping(ctx).Err(); err != nil {
|
||||
t.Fatal(err)
|
||||
|
||||
@@ -14,7 +14,13 @@ export default function AttachmentImage({ id, token, onError }: {
|
||||
setSource(""); setFailed(false);
|
||||
async function load() {
|
||||
try {
|
||||
const attachment = await api.attachment(token, id, controller.signal);
|
||||
let attachment = await api.attachment(token, id, controller.signal);
|
||||
while (attachment.status === "queued" || attachment.status === "processing") {
|
||||
await new Promise(resolve => setTimeout(resolve, 1000));
|
||||
if (controller.signal.aborted) return;
|
||||
attachment = await api.attachment(token,id,controller.signal);
|
||||
}
|
||||
if (attachment.status === "failed") throw new Error("Обработка изображения завершилась ошибкой");
|
||||
const content = await api.attachmentContent(token, id, controller.signal);
|
||||
if (controller.signal.aborted) return;
|
||||
objectURL = URL.createObjectURL(content);
|
||||
|
||||
@@ -15,7 +15,7 @@ export interface Chat {
|
||||
export interface Attachment {
|
||||
id: string; chat_id: string; owner_id: string; filename: string;
|
||||
content_type: "image/png" | "image/jpeg"; size_bytes: number; sha256: string;
|
||||
status: "ready"; variants: unknown[]; error_code: null; created_at: string; updated_at: string;
|
||||
status: "queued" | "processing" | "ready" | "failed"; variants: unknown[]; error_code: string | null; created_at: string; updated_at: string;
|
||||
}
|
||||
|
||||
export interface DirectUpload {
|
||||
|
||||
@@ -3,11 +3,13 @@ module messenger/src
|
||||
go 1.22.2
|
||||
|
||||
require (
|
||||
github.com/disintegration/imaging v1.6.2
|
||||
github.com/golang-migrate/migrate/v4 v4.17.1
|
||||
github.com/google/uuid v1.6.0
|
||||
github.com/jackc/pgx/v5 v5.5.5
|
||||
github.com/minio/madmin-go/v3 v3.0.70
|
||||
github.com/minio/minio-go/v7 v7.0.76
|
||||
github.com/rabbitmq/amqp091-go v1.10.0
|
||||
github.com/redis/go-redis/v9 v9.17.3
|
||||
golang.org/x/crypto v0.27.0
|
||||
)
|
||||
@@ -50,6 +52,7 @@ require (
|
||||
github.com/tklauser/numcpus v0.8.0 // indirect
|
||||
github.com/yusufpapurcu/wmi v1.2.4 // indirect
|
||||
go.uber.org/atomic v1.11.0 // indirect
|
||||
golang.org/x/image v0.0.0-20191009234506-e7c1f5e7dbb8 // indirect
|
||||
golang.org/x/net v0.29.0 // indirect
|
||||
golang.org/x/sync v0.8.0 // indirect
|
||||
golang.org/x/sys v0.25.0 // indirect
|
||||
|
||||
@@ -15,6 +15,8 @@ github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/r
|
||||
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc=
|
||||
github.com/dhui/dktest v0.4.1 h1:/w+IWuDXVymg3IrRJCHHOkMK10m9aNVMOyD0X12YVTg=
|
||||
github.com/dhui/dktest v0.4.1/go.mod h1:DdOqcUpL7vgyP4GlF3X3w7HbSlz8cEQzwewPveYEQbA=
|
||||
github.com/disintegration/imaging v1.6.2 h1:w1LecBlG2Lnp8B3jk5zSuNqd7b4DXhcjwek1ei82L+c=
|
||||
github.com/disintegration/imaging v1.6.2/go.mod h1:44/5580QXChDfwIclfc/PCwrr44amcmDAg8hxG0Ewe4=
|
||||
github.com/distribution/reference v0.5.0 h1:/FUIFXtfc/x2gpa5/VGfiGLuOIdYa1t65IKK2OFGvA0=
|
||||
github.com/distribution/reference v0.5.0/go.mod h1:BbU0aIcezP1/5jX/8MP0YiH4SdvB5Y4f/wlDRiLyi3E=
|
||||
github.com/docker/docker v27.0.3+incompatible h1:aBGI9TeQ4MPlhquTQKq9XbK79rKFVwXNUAYz9aXyEBE=
|
||||
@@ -114,6 +116,8 @@ github.com/prometheus/prom2json v1.4.0 h1:2AEOsd1ebqql/p9u0IWgCpUAteAAf9Lnf/SVyi
|
||||
github.com/prometheus/prom2json v1.4.0/go.mod h1:DmcIMPspQD/fMyFCYti5qJJbuEnqDh3DGoooO0sgr4w=
|
||||
github.com/prometheus/prometheus v0.54.1 h1:vKuwQNjnYN2/mDoWfHXDhAsz/68q/dQDb+YbcEqU7MQ=
|
||||
github.com/prometheus/prometheus v0.54.1/go.mod h1:xlLByHhk2g3ycakQGrMaU8K7OySZx98BzeCR99991NY=
|
||||
github.com/rabbitmq/amqp091-go v1.10.0 h1:STpn5XsHlHGcecLmMFCtg7mqq0RnD+zFr4uzukfVhBw=
|
||||
github.com/rabbitmq/amqp091-go v1.10.0/go.mod h1:Hy4jKW5kQART1u+JkDTF9YYOQUHXqMuhrgxOEeS7G4o=
|
||||
github.com/redis/go-redis/v9 v9.17.3 h1:fN29NdNrE17KttK5Ndf20buqfDZwGNgoUr9qjl1DQx4=
|
||||
github.com/redis/go-redis/v9 v9.17.3/go.mod h1:u410H11HMLoB+TP67dz8rL9s6QW2j76l0//kSOd3370=
|
||||
github.com/rs/xid v1.6.0 h1:fV591PaemRlL6JfRxGDEPl69wICngIQ3shQtzfy2gxU=
|
||||
@@ -151,10 +155,14 @@ go.opentelemetry.io/otel/trace v1.28.0 h1:GhQ9cUuQGmNDd5BTCP2dAvv75RdMxEfTmYejp+
|
||||
go.opentelemetry.io/otel/trace v1.28.0/go.mod h1:jPyXzNPg6da9+38HEwElrQiHlVMTnVfM3/yv2OlIHaI=
|
||||
go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE=
|
||||
go.uber.org/atomic v1.11.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0=
|
||||
go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
|
||||
go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
|
||||
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||
golang.org/x/crypto v0.0.0-20200302210943-78000ba7a073/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
|
||||
golang.org/x/crypto v0.27.0 h1:GXm2NjJrPaiv/h1tb2UH8QfgC/hOf/+z0p6PT8o1w7A=
|
||||
golang.org/x/crypto v0.27.0/go.mod h1:1Xngt8kV6Dvbssa53Ziq6Eqn0HqbZi5Z6R0ZpwQzt70=
|
||||
golang.org/x/image v0.0.0-20191009234506-e7c1f5e7dbb8 h1:hVwzHzIUGRjiF7EcUjqNxk3NCfkPxbDKRdnNE1Rpg0U=
|
||||
golang.org/x/image v0.0.0-20191009234506-e7c1f5e7dbb8/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0=
|
||||
golang.org/x/mod v0.19.0 h1:fEdghXQSo20giMthA7cd28ZC+jts4amQ3YMXiP5oMQ8=
|
||||
golang.org/x/mod v0.19.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
|
||||
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
|
||||
|
||||
Reference in New Issue
Block a user