lab4 - fixed

This commit is contained in:
Rakshasa2
2026-11-05 13:37:38 +03:00
parent 8c7375a6ea
commit bf8da2b7d9
4 changed files with 197 additions and 26 deletions
+126 -3
View File
@@ -54,6 +54,10 @@ type Store interface {
GetAttachmentForUser(ctx context.Context, attachmentID, userID string) (*model.Attachment, error)
ClaimStaleUploading(ctx context.Context, olderThan time.Time) ([]model.Attachment, error)
DeleteFailedStaleAttachment(ctx context.Context, id string) error
GetReadyAttachmentBySHA256(ctx context.Context, sha256Hex string) (*model.Attachment, error)
GetAttachmentBySHA256InChat(ctx context.Context, chatID, sha256Hex string) (*model.Attachment, error)
CreateAttachmentReady(ctx context.Context, chatID, ownerID, filename, objectKey, contentType string, sizeBytes int64, sha256Hex string) (*model.Attachment, error)
}
type PostgresStore struct {
@@ -500,7 +504,6 @@ func (s *PostgresStore) GetMessages(ctx context.Context, chatID, userID, cursor
query = `SELECT id, chat_id, sender_id, text, created_at FROM messages WHERE chat_id = $1 ORDER BY created_at, id LIMIT $2`
args = []interface{}{chatID, fetchLimit}
} else {
// Используем подзапрос, чтобы избежать потери точности времени при передаче через Go
query = `
SELECT id, chat_id, sender_id, text, created_at
FROM messages
@@ -623,6 +626,32 @@ func (s *PostgresStore) CreateAttachmentUploading(ctx context.Context, chatID, o
return &a, nil
}
// GetAttachmentByID возвращает метаданные вложения по его ID.
// Используется воркером для получения object_key перед скачиванием из S3.
func (s *PostgresStore) GetAttachmentByID(ctx context.Context, id string) (*model.Attachment, error) {
var a model.Attachment
err := s.pool.QueryRow(ctx, `
SELECT id::text, chat_id::text, owner_id::text, filename, object_key,
content_type, size_bytes, sha256, status, error_code, created_at, updated_at
FROM attachments
WHERE id = $1
`, id).Scan(
&a.ID, &a.ChatID, &a.OwnerID, &a.Filename, &a.ObjectKey,
&a.ContentType, &a.SizeBytes, &a.SHA256, &a.Status,
&a.ErrorCode, &a.CreatedAt, &a.UpdatedAt,
)
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrNotFound
}
return nil, fmt.Errorf("get attachment by id: %w", err)
}
a.CreatedAt = a.CreatedAt.UTC()
a.UpdatedAt = a.UpdatedAt.UTC()
a.Variants = []any{}
return &a, nil
}
func (s *PostgresStore) MarkAttachmentReady(ctx context.Context, id string) (*model.Attachment, error) {
var a model.Attachment
err := s.pool.QueryRow(ctx, `UPDATE attachments SET status = 'ready', error_code = NULL, updated_at = NOW() WHERE id = $1 AND status = 'uploading' RETURNING id::text, chat_id::text, owner_id::text, filename, object_key, content_type, size_bytes, sha256, status, error_code, created_at, updated_at`, id).
@@ -667,11 +696,17 @@ func (s *PostgresStore) GetAttachmentForUser(ctx context.Context, attachmentID,
}
func (s *PostgresStore) ClaimStaleUploading(ctx context.Context, olderThan time.Time) ([]model.Attachment, error) {
rows, err := s.pool.Query(ctx, `UPDATE attachments SET status = 'failed', error_code = 'stale_upload', updated_at = NOW() WHERE status = 'uploading' AND created_at < $1 RETURNING id::text, object_key`, olderThan)
rows, err := s.pool.Query(ctx, `
UPDATE attachments
SET status = 'deleting', error_code = 'stale_cleanup', updated_at = NOW()
WHERE status = 'uploading' AND created_at < $1
RETURNING id::text, object_key
`, olderThan)
if err != nil {
return nil, fmt.Errorf("claim stale uploading: %w", err)
}
defer rows.Close()
var out []model.Attachment
for rows.Next() {
var a model.Attachment
@@ -684,13 +719,101 @@ func (s *PostgresStore) ClaimStaleUploading(ctx context.Context, olderThan time.
}
func (s *PostgresStore) DeleteFailedStaleAttachment(ctx context.Context, id string) error {
_, err := s.pool.Exec(ctx, `DELETE FROM attachments WHERE id = $1 AND status = 'failed' AND error_code = 'stale_upload'`, id)
_, err := s.pool.Exec(ctx, `
DELETE FROM attachments
WHERE id = $1 AND status = 'deleting'
`, id)
if err != nil {
return fmt.Errorf("delete failed stale attachment: %w", err)
}
return nil
}
func (s *PostgresStore) GetReadyAttachmentBySHA256(ctx context.Context, sha256Hex string) (*model.Attachment, error) {
var a model.Attachment
err := s.pool.QueryRow(ctx, `
SELECT id::text, chat_id::text, owner_id::text, filename, object_key,
content_type, size_bytes, sha256, status, error_code,
created_at, updated_at
FROM attachments
WHERE sha256 = $1 AND status = 'ready'
ORDER BY created_at
LIMIT 1
`, sha256Hex).Scan(
&a.ID, &a.ChatID, &a.OwnerID, &a.Filename, &a.ObjectKey,
&a.ContentType, &a.SizeBytes, &a.SHA256, &a.Status,
&a.ErrorCode, &a.CreatedAt, &a.UpdatedAt,
)
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrNotFound
}
return nil, fmt.Errorf("get ready attachment by sha256: %w", err)
}
a.CreatedAt = a.CreatedAt.UTC()
a.UpdatedAt = a.UpdatedAt.UTC()
a.Variants = []any{}
return &a, nil
}
func (s *PostgresStore) GetAttachmentBySHA256InChat(ctx context.Context, chatID, sha256Hex string) (*model.Attachment, error) {
var a model.Attachment
err := s.pool.QueryRow(ctx, `
SELECT id::text, chat_id::text, owner_id::text, filename, object_key,
content_type, size_bytes, sha256, status, error_code,
created_at, updated_at
FROM attachments
WHERE chat_id = $1 AND sha256 = $2 AND status = 'ready'
ORDER BY created_at
LIMIT 1
`, chatID, sha256Hex).Scan(
&a.ID, &a.ChatID, &a.OwnerID, &a.Filename, &a.ObjectKey,
&a.ContentType, &a.SizeBytes, &a.SHA256, &a.Status,
&a.ErrorCode, &a.CreatedAt, &a.UpdatedAt,
)
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrNotFound
}
return nil, fmt.Errorf("get attachment by sha256 in chat: %w", err)
}
a.CreatedAt = a.CreatedAt.UTC()
a.UpdatedAt = a.UpdatedAt.UTC()
a.Variants = []any{}
return &a, nil
}
func (s *PostgresStore) CreateAttachmentReady(ctx context.Context, chatID, ownerID, filename, objectKey, contentType string, sizeBytes int64, sha256Hex string) (*model.Attachment, error) {
var a model.Attachment
err := s.pool.QueryRow(ctx, `
INSERT INTO attachments (
chat_id, owner_id, filename, object_key,
content_type, size_bytes, sha256, status
)
VALUES ($1, $2, $3, $4, $5, $6, $7, 'ready')
RETURNING id::text, chat_id::text, owner_id::text, filename,
object_key, content_type, size_bytes, sha256,
status, error_code, created_at, updated_at
`, chatID, ownerID, filename, objectKey, contentType, sizeBytes, sha256Hex).Scan(
&a.ID, &a.ChatID, &a.OwnerID, &a.Filename, &a.ObjectKey,
&a.ContentType, &a.SizeBytes, &a.SHA256, &a.Status,
&a.ErrorCode, &a.CreatedAt, &a.UpdatedAt,
)
if err != nil {
if isUniqueViolation(err) {
return nil, ErrConflict
}
if isForeignKeyViolation(err) {
return nil, ErrNotFound
}
return nil, fmt.Errorf("insert attachment ready: %w", err)
}
a.CreatedAt = a.CreatedAt.UTC()
a.UpdatedAt = a.UpdatedAt.UTC()
a.Variants = []any{}
return &a, nil
}
func hashScope(s string) int64 {
h := sha256.Sum256([]byte(s))
return int64(binary.BigEndian.Uint64(h[:8]))