forked from mtusi2026/mtusi2026lab6
ЛР 6 — БПИ2302 — Нурлыгаянова — на 3
This commit is contained in:
@@ -0,0 +1,117 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"go.opentelemetry.io/otel"
|
||||
"go.opentelemetry.io/otel/propagation"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
|
||||
"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()
|
||||
|
||||
ctx, span := otel.Tracer("messenger").Start(ctx, "attachment.enqueue", trace.WithSpanKind(trace.SpanKindProducer))
|
||||
defer span.End()
|
||||
carrier := propagation.MapCarrier{}
|
||||
otel.GetTextMapPropagator().Inject(ctx, carrier)
|
||||
tx, err := a.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return domain.Attachment{}, mapErr(err)
|
||||
}
|
||||
defer tx.Rollback(ctx)
|
||||
if _, err = tx.Exec(ctx, "SELECT set_config('messenger.traceparent',$1,true), set_config('messenger.tracestate',$2,true)", carrier.Get("traceparent"), carrier.Get("tracestate")); err != nil {
|
||||
return domain.Attachment{}, mapErr(err)
|
||||
}
|
||||
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.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
|
||||
var variants []byte
|
||||
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.variants, a.error_code
|
||||
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, &variants, &att.ErrorCode)
|
||||
if err != nil {
|
||||
return domain.Attachment{}, mapErr(err)
|
||||
}
|
||||
att.CreatedAt = att.CreatedAt.UTC()
|
||||
att.UpdatedAt = att.UpdatedAt.UTC()
|
||||
if err := json.Unmarshal(variants, &att.Variants); err != nil {
|
||||
return domain.Attachment{}, err
|
||||
}
|
||||
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