forked from mtusi2026/mtusi2026lab5
ЛР 5: асинхронная обработка изображений, уровень 5
This commit is contained in:
@@ -0,0 +1,127 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"strconv"
|
||||
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain"
|
||||
)
|
||||
|
||||
type Attachments struct {
|
||||
conn
|
||||
}
|
||||
|
||||
// CreateAttachment сохраняет метаданные. FK на chat_members не даёт записать вложение постороннего.
|
||||
func (a *Attachments) CreateAttachment(ctx context.Context, att domain.Attachment) (domain.Attachment, error) {
|
||||
ctx, cancel := a.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
tx, err := a.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return domain.Attachment{}, mapErr(err)
|
||||
}
|
||||
defer tx.Rollback(ctx)
|
||||
// Serialize admission across API replicas. Only unfinished jobs consume capacity.
|
||||
limit := 64
|
||||
if value := os.Getenv("JOB_MAX_INFLIGHT"); value != "" {
|
||||
n, e := strconv.Atoi(value)
|
||||
if e != nil || n < 1 {
|
||||
return domain.Attachment{}, fmt.Errorf("invalid JOB_MAX_INFLIGHT")
|
||||
}
|
||||
limit = n
|
||||
}
|
||||
if _, err = tx.Exec(ctx, `SELECT pg_advisory_xact_lock(505002)`); err != nil {
|
||||
return domain.Attachment{}, mapErr(err)
|
||||
}
|
||||
var outstanding int
|
||||
if err = tx.QueryRow(ctx, `SELECT count(*) FROM attachments WHERE status IN ('queued','processing')`).Scan(&outstanding); err != nil {
|
||||
return domain.Attachment{}, mapErr(err)
|
||||
}
|
||||
if outstanding >= limit {
|
||||
return domain.Attachment{}, domain.ErrRateLimited
|
||||
}
|
||||
err = tx.QueryRow(ctx, `
|
||||
INSERT INTO attachments (id, chat_id, owner_id, filename, content_type, size_bytes, sha256, object_key, status)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)
|
||||
RETURNING created_at, updated_at`,
|
||||
att.ID, att.ChatID, att.OwnerID, att.Filename, att.ContentType, att.SizeBytes, att.SHA256, att.ObjectKey, att.Status,
|
||||
).Scan(&att.CreatedAt, &att.UpdatedAt)
|
||||
if isFKViolation(err) {
|
||||
return domain.Attachment{}, domain.ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return domain.Attachment{}, mapErr(err)
|
||||
}
|
||||
if _, err = tx.Exec(ctx, `INSERT INTO attachment_outbox(attachment_id) VALUES ($1)`, att.ID); err != nil {
|
||||
return domain.Attachment{}, mapErr(err)
|
||||
}
|
||||
if err = tx.Commit(ctx); err != nil {
|
||||
return domain.Attachment{}, mapErr(err)
|
||||
}
|
||||
att.CreatedAt = att.CreatedAt.UTC()
|
||||
att.UpdatedAt = att.UpdatedAt.UTC()
|
||||
return att, nil
|
||||
}
|
||||
|
||||
// AttachmentForMember возвращает вложение, только если вызывающий состоит в его чате: для
|
||||
// постороннего результат неотличим от отсутствующего объекта.
|
||||
func (a *Attachments) AttachmentForMember(ctx context.Context, callerID, attachmentID string) (domain.Attachment, error) {
|
||||
ctx, cancel := a.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
var att domain.Attachment
|
||||
err := a.pool.QueryRow(ctx, `
|
||||
SELECT a.id::text, a.chat_id::text, a.owner_id::text, a.filename, a.content_type, a.size_bytes,
|
||||
a.sha256, a.object_key, a.status, a.created_at, a.updated_at, a.thumbnail, a.error_code, a.variants
|
||||
FROM attachments a
|
||||
JOIN chat_members cm ON cm.chat_id = a.chat_id AND cm.user_id = $2
|
||||
WHERE a.id = $1`,
|
||||
attachmentID, callerID,
|
||||
).Scan(&att.ID, &att.ChatID, &att.OwnerID, &att.Filename, &att.ContentType, &att.SizeBytes,
|
||||
&att.SHA256, &att.ObjectKey, &att.Status, &att.CreatedAt, &att.UpdatedAt, &att.Thumbnail, &att.ErrorCode, &att.Variants)
|
||||
if err != nil {
|
||||
return domain.Attachment{}, mapErr(err)
|
||||
}
|
||||
att.CreatedAt = att.CreatedAt.UTC()
|
||||
att.UpdatedAt = att.UpdatedAt.UTC()
|
||||
return att, nil
|
||||
}
|
||||
|
||||
// AttachmentExists отвечает без учёта доступа: вызывается только сервером при компенсации.
|
||||
func (a *Attachments) AttachmentExists(ctx context.Context, attachmentID string) (bool, error) {
|
||||
ctx, cancel := a.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
var exists bool
|
||||
err := a.pool.QueryRow(ctx, `SELECT EXISTS (SELECT 1 FROM attachments WHERE id = $1)`, attachmentID).Scan(&exists)
|
||||
if err != nil {
|
||||
return false, mapErr(err)
|
||||
}
|
||||
return exists, nil
|
||||
}
|
||||
|
||||
// ExistingObjectKeys возвращает те ключи из списка, на которые есть строка. Нужен очистителю.
|
||||
func (a *Attachments) ExistingObjectKeys(ctx context.Context, keys []string) (map[string]struct{}, error) {
|
||||
ctx, cancel := a.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
rows, err := a.pool.Query(ctx, `SELECT object_key FROM attachments WHERE object_key = ANY($1)`, keys)
|
||||
if err != nil {
|
||||
return nil, mapErr(err)
|
||||
}
|
||||
defer rows.Close()
|
||||
existing := make(map[string]struct{}, len(keys))
|
||||
for rows.Next() {
|
||||
var key string
|
||||
if err := rows.Scan(&key); err != nil {
|
||||
return nil, mapErr(err)
|
||||
}
|
||||
existing[key] = struct{}{}
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, mapErr(err)
|
||||
}
|
||||
return existing, nil
|
||||
}
|
||||
Reference in New Issue
Block a user