forked from mtusi2026/mtusi2026lab6
chore: add lab5 files and merge env.example.
This commit is contained in:
@@ -0,0 +1,47 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"high-loud-apps-labs/internal/domain"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
type AttachmentVariantRepo struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewAttachmentVariantRepo(pool *pgxpool.Pool) *AttachmentVariantRepo {
|
||||
return &AttachmentVariantRepo{pool: pool}
|
||||
}
|
||||
|
||||
func (r *AttachmentVariantRepo) Upsert(ctx context.Context, tx domain.Tx, v *domain.AttachmentVariant) error {
|
||||
const q = `
|
||||
INSERT INTO attachment_variants
|
||||
(attachment_id, name, object_key, content_type, size_bytes, width, height, sha256, created_at)
|
||||
VALUES ($1::uuid, $2, $3, $4, $5, $6, $7, $8, $9)
|
||||
ON CONFLICT (attachment_id, name) DO NOTHING
|
||||
`
|
||||
return tx.Exec(ctx, q, v.AttachmentID, v.Name, v.ObjectKey, v.ContentType, v.SizeBytes, v.Width, v.Height, v.SHA256, v.CreatedAt)
|
||||
}
|
||||
|
||||
func (r *AttachmentVariantRepo) ListByAttachment(ctx context.Context, id string) ([]domain.AttachmentVariant, error) {
|
||||
const q = `SELECT attachment_id, name, object_key, content_type, size_bytes, width, height, sha256, created_at FROM attachment_variants WHERE attachment_id = $1::uuid`
|
||||
rows, err := r.pool.Query(ctx, q, id)
|
||||
if err != nil {
|
||||
return nil, mapError(err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var out []domain.AttachmentVariant
|
||||
for rows.Next() {
|
||||
var v domain.AttachmentVariant
|
||||
if err := rows.Scan(&v.AttachmentID, &v.Name, &v.ObjectKey, &v.ContentType, &v.SizeBytes, &v.Width, &v.Height, &v.SHA256, &v.CreatedAt); err != nil {
|
||||
return nil, mapError(err)
|
||||
}
|
||||
out = append(out, v)
|
||||
}
|
||||
return out, mapError(rows.Err())
|
||||
}
|
||||
|
||||
var _ domain.AttachmentVariantRepository = (*AttachmentVariantRepo)(nil)
|
||||
@@ -0,0 +1,352 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"high-loud-apps-labs/internal/domain"
|
||||
)
|
||||
|
||||
type AttachmentRepo struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewAttachmentRepo(pool *pgxpool.Pool) *AttachmentRepo {
|
||||
return &AttachmentRepo{pool: pool}
|
||||
}
|
||||
|
||||
func (r *AttachmentRepo) Create(ctx context.Context, a *domain.Attachment) error {
|
||||
const q = `
|
||||
INSERT INTO attachments
|
||||
(id, chat_id, owner_id, filename, content_type, size_bytes, sha256,
|
||||
object_key, status, error_code, created_at, updated_at)
|
||||
VALUES ($1::uuid, $2::uuid, $3::uuid, $4, $5, $6, $7, $8, $9, NULL, $10, $10)`
|
||||
_, err := r.pool.Exec(ctx, q,
|
||||
a.ID, a.ChatID, a.OwnerID, a.Filename, a.ContentType, a.SizeBytes,
|
||||
a.SHA256, a.ObjectKey, string(a.Status), a.CreatedAt,
|
||||
)
|
||||
if err != nil {
|
||||
if uniqueViolation(err) {
|
||||
return &domain.AlreadyExistsError{
|
||||
Entity: "attachment",
|
||||
Field: "object_key",
|
||||
Value: a.ObjectKey,
|
||||
}
|
||||
}
|
||||
if foreignKeyViolation(err) {
|
||||
return &domain.NotFoundError{Entity: "chat", ID: a.ChatID}
|
||||
}
|
||||
if checkViolation(err) {
|
||||
return &domain.ValidationError{
|
||||
Field: "attachment",
|
||||
Message: "нарушено ограничение целостности",
|
||||
}
|
||||
}
|
||||
return mapError(err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *AttachmentRepo) CreateInTx(ctx context.Context, tx domain.Tx, a *domain.Attachment) error {
|
||||
const q = `
|
||||
INSERT INTO attachments
|
||||
(id, chat_id, owner_id, filename, content_type, size_bytes, sha256,
|
||||
object_key, status, error_code,
|
||||
attempts, pipeline_version, staging_key,
|
||||
created_at, updated_at)
|
||||
VALUES ($1::uuid, $2::uuid, $3::uuid, $4, $5, $6, $7, $8, $9, NULL,
|
||||
0, $10, $11, $12, $12)
|
||||
`
|
||||
return tx.Exec(ctx, q,
|
||||
a.ID, a.ChatID, a.OwnerID, a.Filename, a.ContentType, a.SizeBytes,
|
||||
a.SHA256, a.ObjectKey, string(a.Status),
|
||||
a.PipelineVersion, a.StagingKey, a.CreatedAt,
|
||||
)
|
||||
}
|
||||
|
||||
func (r *AttachmentRepo) GetByID(ctx context.Context, id string) (*domain.Attachment, error) {
|
||||
const q = `
|
||||
SELECT id, chat_id, owner_id, filename, content_type, size_bytes, sha256,
|
||||
object_key, status, error_code, created_at, updated_at,
|
||||
attempts, next_attempt_at, locked_until, pipeline_version, staging_key
|
||||
FROM attachments
|
||||
WHERE id = $1::uuid
|
||||
`
|
||||
a := &domain.Attachment{}
|
||||
var status string
|
||||
err := r.pool.QueryRow(ctx, q, id).
|
||||
Scan(&a.ID, &a.ChatID, &a.OwnerID, &a.Filename, &a.ContentType,
|
||||
&a.SizeBytes, &a.SHA256, &a.ObjectKey, &status, &a.ErrorCode,
|
||||
&a.CreatedAt, &a.UpdatedAt,
|
||||
&a.Attempts, &a.NextAttemptAt, &a.LockedUntil, &a.PipelineVersion, &a.StagingKey)
|
||||
if err != nil {
|
||||
return nil, notFound(err, "attachment", id)
|
||||
}
|
||||
a.Status = domain.AttachmentStatus(status)
|
||||
|
||||
rows, err := r.pool.Query(ctx, `
|
||||
SELECT name, object_key, content_type, size_bytes, width, height, sha256, created_at
|
||||
FROM attachment_variants
|
||||
WHERE attachment_id = $1::uuid
|
||||
ORDER BY name
|
||||
`, id)
|
||||
if err != nil {
|
||||
log.Printf("GetByID: ошибка запроса variants: %v", err)
|
||||
} else {
|
||||
defer rows.Close()
|
||||
for rows.Next() {
|
||||
var v domain.AttachmentVariant
|
||||
v.AttachmentID = id
|
||||
if err := rows.Scan(&v.Name, &v.ObjectKey, &v.ContentType, &v.SizeBytes, &v.Width, &v.Height, &v.SHA256, &v.CreatedAt); err != nil {
|
||||
log.Printf("GetByID: ошибка Scan variant: %v", err)
|
||||
} else {
|
||||
a.Variants = append(a.Variants, v)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return a, nil
|
||||
}
|
||||
|
||||
func (r *AttachmentRepo) MarkReady(ctx context.Context, id string) error {
|
||||
const q = `
|
||||
UPDATE attachments
|
||||
SET status = 'ready', updated_at = now()
|
||||
WHERE id = $1::uuid AND status = 'pending'
|
||||
`
|
||||
tag, err := r.pool.Exec(ctx, q, id)
|
||||
if err != nil {
|
||||
return mapError(err)
|
||||
}
|
||||
if tag.RowsAffected() > 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
var status string
|
||||
err = r.pool.QueryRow(ctx, `SELECT status FROM attachments WHERE id = $1::uuid`, id).
|
||||
Scan(&status)
|
||||
if err != nil {
|
||||
return notFound(err, "attachment", id)
|
||||
}
|
||||
switch domain.AttachmentStatus(status) {
|
||||
case domain.AttachmentStatusReady:
|
||||
return nil
|
||||
case domain.AttachmentStatusFailed:
|
||||
return &domain.ConflictError{Reason: "нельзя перевести failed-вложение в ready"}
|
||||
default:
|
||||
return &domain.ConflictError{Reason: "некорректное состояние вложения"}
|
||||
}
|
||||
}
|
||||
|
||||
func (r *AttachmentRepo) MarkFailed(ctx context.Context, id, errorCode string) error {
|
||||
if errorCode == "" {
|
||||
return &domain.ValidationError{Field: "error_code", Message: "не может быть пустым"}
|
||||
}
|
||||
const q = `
|
||||
UPDATE attachments
|
||||
SET status = 'failed', error_code = $2, updated_at = now()
|
||||
WHERE id = $1::uuid AND status = 'pending'
|
||||
`
|
||||
tag, err := r.pool.Exec(ctx, q, id, errorCode)
|
||||
if err != nil {
|
||||
return mapError(err)
|
||||
}
|
||||
if tag.RowsAffected() > 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
var status string
|
||||
err = r.pool.QueryRow(ctx, `SELECT status FROM attachments WHERE id = $1::uuid`, id).
|
||||
Scan(&status)
|
||||
if err != nil {
|
||||
return notFound(err, "attachment", id)
|
||||
}
|
||||
switch domain.AttachmentStatus(status) {
|
||||
case domain.AttachmentStatusFailed, domain.AttachmentStatusReady:
|
||||
return nil
|
||||
default:
|
||||
return &domain.ConflictError{Reason: "некорректное состояние вложения"}
|
||||
}
|
||||
}
|
||||
|
||||
func (r *AttachmentRepo) ExistingKeys(ctx context.Context, keys []string) ([]string, error) {
|
||||
if len(keys) == 0 {
|
||||
return []string{}, nil
|
||||
}
|
||||
const q = `SELECT object_key FROM attachments WHERE object_key = ANY($1::text[])`
|
||||
rows, err := r.pool.Query(ctx, q, keys)
|
||||
if err != nil {
|
||||
return nil, mapError(err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
out := make([]string, 0, len(keys))
|
||||
for rows.Next() {
|
||||
var k string
|
||||
if err := rows.Scan(&k); err != nil {
|
||||
return nil, mapError(err)
|
||||
}
|
||||
out = append(out, k)
|
||||
}
|
||||
return out, mapError(rows.Err())
|
||||
}
|
||||
|
||||
func (r *AttachmentRepo) ClaimForProcessing(ctx context.Context, id string, version int, lease time.Duration) (*domain.Attachment, error) {
|
||||
const q = `
|
||||
UPDATE attachments
|
||||
SET status = 'processing', locked_until = now() + $2, updated_at = now(), attempts = attempts + 1
|
||||
WHERE id = $1::uuid AND status = 'queued' AND pipeline_version = $3
|
||||
RETURNING id, chat_id, staging_key, pipeline_version, object_key, content_type, attempts
|
||||
`
|
||||
var a domain.Attachment
|
||||
err := r.pool.QueryRow(ctx, q, id, lease, version).Scan(&a.ID, &a.ChatID, &a.StagingKey, &a.PipelineVersion, &a.ObjectKey, &a.ContentType, &a.Attempts)
|
||||
if err != nil {
|
||||
if err == pgx.ErrNoRows {
|
||||
return nil, nil
|
||||
}
|
||||
return nil, mapError(err)
|
||||
}
|
||||
return &a, nil
|
||||
}
|
||||
|
||||
func (r *AttachmentRepo) CompleteJob(ctx context.Context, id string, pipelineVersion int, variants []domain.AttachmentVariant) (bool, error) {
|
||||
tx, err := r.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return false, mapError(err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback(ctx) }()
|
||||
|
||||
const q = `
|
||||
UPDATE attachments
|
||||
SET status = 'ready', locked_until = NULL, updated_at = now()
|
||||
WHERE id = $1::uuid AND pipeline_version = $2 AND status = 'processing'
|
||||
`
|
||||
tag, err := tx.Exec(ctx, q, id, pipelineVersion)
|
||||
if err != nil {
|
||||
return false, mapError(err)
|
||||
}
|
||||
if tag.RowsAffected() == 0 {
|
||||
return false, nil
|
||||
}
|
||||
|
||||
variantRepo := NewAttachmentVariantRepo(r.pool)
|
||||
for _, v := range variants {
|
||||
if err := variantRepo.Upsert(ctx, &pgxTx{tx: tx}, &v); err != nil {
|
||||
log.Printf("CompleteJob: ошибка Upsert %s: %v", v.Name, err)
|
||||
return false, err
|
||||
} else {
|
||||
log.Printf("CompleteJob: успешно добавлен вариант %s", v.Name)
|
||||
}
|
||||
}
|
||||
|
||||
return true, mapError(tx.Commit(ctx))
|
||||
}
|
||||
|
||||
func (r *AttachmentRepo) FailJob(ctx context.Context, id string, errorCode string) error {
|
||||
const q = `
|
||||
UPDATE attachments
|
||||
SET status = 'failed', error_code = $2, locked_until = NULL, updated_at = now()
|
||||
WHERE id = $1::uuid AND status = 'processing'
|
||||
`
|
||||
_, err := r.pool.Exec(ctx, q, id, errorCode)
|
||||
return mapError(err)
|
||||
}
|
||||
|
||||
func (r *AttachmentRepo) ScheduleRetry(ctx context.Context, id string, nextAttemptAt time.Time, errorCode string) error {
|
||||
const q = `
|
||||
UPDATE attachments
|
||||
SET status = 'queued', error_code = NULL, next_attempt_at = $2, locked_until = NULL, updated_at = now()
|
||||
WHERE id = $1::uuid AND status = 'processing'
|
||||
`
|
||||
_, err := r.pool.Exec(ctx, q, id, nextAttemptAt)
|
||||
return mapError(err)
|
||||
}
|
||||
|
||||
func (r *AttachmentRepo) ResetForReplay(ctx context.Context, tx domain.Tx, id string) error {
|
||||
const q = `
|
||||
UPDATE attachments
|
||||
SET status = 'queued', attempts = 0, error_code = NULL, locked_until = NULL, next_attempt_at = NULL, updated_at = now()
|
||||
WHERE id = $1::uuid AND status = 'failed'
|
||||
`
|
||||
return tx.Exec(ctx, q, id)
|
||||
}
|
||||
|
||||
// для сверщика.
|
||||
func (r *AttachmentRepo) ListExpiredLeases(ctx context.Context, limit int) ([]domain.Attachment, error) {
|
||||
const q = `
|
||||
SELECT id, chat_id, owner_id, filename, content_type, size_bytes, sha256,
|
||||
object_key, status, error_code, created_at, updated_at,
|
||||
attempts, next_attempt_at, locked_until, pipeline_version, staging_key
|
||||
FROM attachments
|
||||
WHERE status = 'processing' AND locked_until < now()
|
||||
ORDER BY locked_until
|
||||
LIMIT $1
|
||||
`
|
||||
rows, err := r.pool.Query(ctx, q, limit)
|
||||
if err != nil {
|
||||
return nil, mapError(err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var out []domain.Attachment
|
||||
for rows.Next() {
|
||||
var a domain.Attachment
|
||||
var status string
|
||||
err := rows.Scan(&a.ID, &a.ChatID, &a.OwnerID, &a.Filename, &a.ContentType,
|
||||
&a.SizeBytes, &a.SHA256, &a.ObjectKey, &status, &a.ErrorCode,
|
||||
&a.CreatedAt, &a.UpdatedAt, &a.Attempts, &a.NextAttemptAt, &a.LockedUntil,
|
||||
&a.PipelineVersion, &a.StagingKey)
|
||||
if err != nil {
|
||||
return nil, mapError(err)
|
||||
}
|
||||
a.Status = domain.AttachmentStatus(status)
|
||||
out = append(out, a)
|
||||
}
|
||||
return out, mapError(rows.Err())
|
||||
}
|
||||
|
||||
func (r *AttachmentRepo) ResetLease(ctx context.Context, id string) error {
|
||||
const q = `
|
||||
UPDATE attachments
|
||||
SET status = 'queued', locked_until = NULL, updated_at = now()
|
||||
WHERE id = $1::uuid AND status = 'processing' AND locked_until < now()
|
||||
`
|
||||
_, err := r.pool.Exec(ctx, q, id)
|
||||
return mapError(err)
|
||||
}
|
||||
|
||||
func (r *AttachmentRepo) ListStagingToCleanup(ctx context.Context, limit int) ([]domain.Attachment, error) {
|
||||
const q = `
|
||||
SELECT id, staging_key
|
||||
FROM attachments
|
||||
WHERE status = 'ready' AND staging_key IS NOT NULL
|
||||
LIMIT $1
|
||||
`
|
||||
rows, err := r.pool.Query(ctx, q, limit)
|
||||
if err != nil {
|
||||
return nil, mapError(err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var out []domain.Attachment
|
||||
for rows.Next() {
|
||||
var a domain.Attachment
|
||||
if err := rows.Scan(&a.ID, &a.StagingKey); err != nil {
|
||||
return nil, mapError(err)
|
||||
}
|
||||
out = append(out, a)
|
||||
}
|
||||
return out, mapError(rows.Err())
|
||||
}
|
||||
|
||||
func (r *AttachmentRepo) ClearStagingKey(ctx context.Context, id string) error {
|
||||
const q = `UPDATE attachments SET staging_key = NULL WHERE id = $1::uuid`
|
||||
_, err := r.pool.Exec(ctx, q, id)
|
||||
return mapError(err)
|
||||
}
|
||||
|
||||
var _ domain.AttachmentRepository = (*AttachmentRepo)(nil)
|
||||
@@ -0,0 +1,195 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"high-loud-apps-labs/internal/domain"
|
||||
)
|
||||
|
||||
type ChatRepo struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewChatRepo(pool *pgxpool.Pool) *ChatRepo {
|
||||
return &ChatRepo{pool: pool}
|
||||
}
|
||||
|
||||
// Create атомарно создаёт чат и его участников.
|
||||
func (r *ChatRepo) Create(ctx context.Context, chat *domain.Chat) error {
|
||||
tx, err := r.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return mapError(err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback(ctx) }()
|
||||
|
||||
const qChat = `INSERT INTO chats (id, title, created_at) VALUES ($1::uuid, $2, $3)`
|
||||
if _, err := tx.Exec(ctx, qChat, chat.ID, chat.Title, chat.CreatedAt); err != nil {
|
||||
if checkViolation(err) {
|
||||
return &domain.ValidationError{Field: "chat", Message: "нарушено ограничение целостности"}
|
||||
}
|
||||
return mapError(err)
|
||||
}
|
||||
|
||||
const qMember = `INSERT INTO chat_members (chat_id, user_id) VALUES ($1::uuid, $2::uuid)`
|
||||
for _, uid := range chat.MemberIDs {
|
||||
if _, err := tx.Exec(ctx, qMember, chat.ID, uid); err != nil {
|
||||
if foreignKeyViolation(err) {
|
||||
return &domain.ValidationError{
|
||||
Field: "member_ids",
|
||||
Message: "неизвестный участник " + uid,
|
||||
}
|
||||
}
|
||||
if uniqueViolation(err) {
|
||||
return &domain.ValidationError{
|
||||
Field: "member_ids",
|
||||
Message: "дубликаты запрещены",
|
||||
}
|
||||
}
|
||||
return mapError(err)
|
||||
}
|
||||
}
|
||||
|
||||
return mapError(tx.Commit(ctx))
|
||||
}
|
||||
|
||||
func (r *ChatRepo) GetByID(ctx context.Context, id string) (*domain.Chat, error) {
|
||||
const q = `SELECT id, title, created_at FROM chats WHERE id = $1::uuid`
|
||||
c := &domain.Chat{}
|
||||
err := r.pool.QueryRow(ctx, q, id).Scan(&c.ID, &c.Title, &c.CreatedAt)
|
||||
if err != nil {
|
||||
return nil, notFound(err, "chat", id)
|
||||
}
|
||||
members, err := r.loadMembers(ctx, []string{c.ID})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
c.MemberIDs = members[c.ID]
|
||||
if c.MemberIDs == nil {
|
||||
c.MemberIDs = []string{}
|
||||
}
|
||||
return c, nil
|
||||
}
|
||||
|
||||
func (r *ChatRepo) ListByMember(ctx context.Context, userID string, limit int, cursor *string) ([]domain.Chat, *string, error) {
|
||||
scope := "chats:" + userID
|
||||
|
||||
var (
|
||||
afterTime time.Time
|
||||
afterID string
|
||||
hasCursor bool
|
||||
)
|
||||
if cursor != nil {
|
||||
t, id, err := decodeCursor(*cursor, scope)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
afterTime = t
|
||||
afterID = id
|
||||
hasCursor = true
|
||||
}
|
||||
|
||||
var (
|
||||
rows pgx.Rows
|
||||
err error
|
||||
)
|
||||
if hasCursor {
|
||||
const q = `
|
||||
SELECT c.id, c.title, c.created_at
|
||||
FROM chats c
|
||||
JOIN chat_members m ON m.chat_id = c.id
|
||||
WHERE m.user_id = $1::uuid
|
||||
AND (c.created_at, c.id) > ($2, $3::uuid)
|
||||
ORDER BY c.created_at, c.id
|
||||
LIMIT $4
|
||||
`
|
||||
rows, err = r.pool.Query(ctx, q, userID, afterTime, afterID, limit+1)
|
||||
} else {
|
||||
const q = `
|
||||
SELECT c.id, c.title, c.created_at
|
||||
FROM chats c
|
||||
JOIN chat_members m ON m.chat_id = c.id
|
||||
WHERE m.user_id = $1::uuid
|
||||
ORDER BY c.created_at, c.id
|
||||
LIMIT $2
|
||||
`
|
||||
rows, err = r.pool.Query(ctx, q, userID, limit+1)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, nil, mapError(err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
page := make([]domain.Chat, 0, limit)
|
||||
for rows.Next() {
|
||||
var c domain.Chat
|
||||
if err := rows.Scan(&c.ID, &c.Title, &c.CreatedAt); err != nil {
|
||||
return nil, nil, mapError(err)
|
||||
}
|
||||
page = append(page, c)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, nil, mapError(err)
|
||||
}
|
||||
|
||||
var next *string
|
||||
if len(page) > limit {
|
||||
page = page[:limit]
|
||||
last := page[len(page)-1]
|
||||
c := encodeCursor(scope, last.CreatedAt, last.ID)
|
||||
next = &c
|
||||
}
|
||||
|
||||
if len(page) > 0 {
|
||||
ids := make([]string, len(page))
|
||||
for i := range page {
|
||||
ids[i] = page[i].ID
|
||||
}
|
||||
members, err := r.loadMembers(ctx, ids)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
for i := range page {
|
||||
if m, ok := members[page[i].ID]; ok {
|
||||
page[i].MemberIDs = m
|
||||
} else {
|
||||
page[i].MemberIDs = []string{}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return page, next, nil
|
||||
}
|
||||
|
||||
// loadMembers одним запросом собирает участников для указанных чатов.
|
||||
func (r *ChatRepo) loadMembers(ctx context.Context, chatIDs []string) (map[string][]string, error) {
|
||||
if len(chatIDs) == 0 {
|
||||
return map[string][]string{}, nil
|
||||
}
|
||||
const q = `
|
||||
SELECT chat_id, user_id
|
||||
FROM chat_members
|
||||
WHERE chat_id = ANY($1::uuid[])
|
||||
ORDER BY chat_id, user_id
|
||||
`
|
||||
rows, err := r.pool.Query(ctx, q, chatIDs)
|
||||
if err != nil {
|
||||
return nil, mapError(err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
result := make(map[string][]string, len(chatIDs))
|
||||
for rows.Next() {
|
||||
var chatID, userID string
|
||||
if err := rows.Scan(&chatID, &userID); err != nil {
|
||||
return nil, mapError(err)
|
||||
}
|
||||
result[chatID] = append(result[chatID], userID)
|
||||
}
|
||||
return result, mapError(rows.Err())
|
||||
}
|
||||
|
||||
var _ domain.ChatRepository = (*ChatRepo)(nil)
|
||||
@@ -0,0 +1,46 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"high-loud-apps-labs/internal/domain"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// Взял за основу что в inmemery делал
|
||||
func encodeCursor(scope string, createdAt time.Time, id string) string {
|
||||
raw := scope + "|" + createdAt.UTC().Format(time.RFC3339Nano) + "|" + id
|
||||
return base64.RawURLEncoding.EncodeToString([]byte(raw))
|
||||
}
|
||||
|
||||
func decodeCursor(cursor, expectedScope string) (time.Time, string, error) {
|
||||
data, err := base64.RawURLEncoding.DecodeString(cursor)
|
||||
if err != nil {
|
||||
return time.Time{}, "", badCursor()
|
||||
}
|
||||
parts := strings.SplitN(string(data), "|", 3)
|
||||
if len(parts) != 3 {
|
||||
return time.Time{}, "", badCursor()
|
||||
}
|
||||
if parts[0] != expectedScope {
|
||||
return time.Time{}, "", badCursor()
|
||||
}
|
||||
t, err := time.Parse(time.RFC3339Nano, parts[1])
|
||||
if err != nil {
|
||||
return time.Time{}, "", badCursor()
|
||||
}
|
||||
if _, err := uuid.Parse(parts[2]); err != nil {
|
||||
return time.Time{}, "", badCursor()
|
||||
}
|
||||
return t, parts[2], nil
|
||||
}
|
||||
|
||||
func badCursor() error {
|
||||
return &domain.ValidationError{
|
||||
Field: "cursor",
|
||||
Message: "некорректный формат",
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"github.com/jackc/pgx/v5/stdlib"
|
||||
"github.com/pressly/goose/v3"
|
||||
|
||||
"high-loud-apps-labs/migrations"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
URL string
|
||||
MaxConns int32
|
||||
MinConns int32
|
||||
MaxConnLifetime time.Duration
|
||||
MaxConnIdleTime time.Duration
|
||||
ConnectTimeout time.Duration
|
||||
}
|
||||
|
||||
func Connect(ctx context.Context, cfg Config) (*pgxpool.Pool, error) {
|
||||
if cfg.URL == "" {
|
||||
return nil, fmt.Errorf("DATABASE_URL пустой")
|
||||
}
|
||||
|
||||
poolCfg, err := pgxpool.ParseConfig(cfg.URL)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("разбор DATABASE_URL: %w", err)
|
||||
}
|
||||
if cfg.MaxConns > 0 {
|
||||
poolCfg.MaxConns = cfg.MaxConns
|
||||
}
|
||||
if cfg.MinConns > 0 {
|
||||
poolCfg.MinConns = cfg.MinConns
|
||||
}
|
||||
if cfg.MaxConnLifetime > 0 {
|
||||
poolCfg.MaxConnLifetime = cfg.MaxConnLifetime
|
||||
}
|
||||
if cfg.MaxConnIdleTime > 0 {
|
||||
poolCfg.MaxConnIdleTime = cfg.MaxConnIdleTime
|
||||
}
|
||||
if cfg.ConnectTimeout > 0 {
|
||||
poolCfg.ConnConfig.ConnectTimeout = cfg.ConnectTimeout
|
||||
}
|
||||
poolCfg.HealthCheckPeriod = 10 * time.Second
|
||||
|
||||
pool, err := pgxpool.NewWithConfig(ctx, poolCfg)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("создание пула: %w", err)
|
||||
}
|
||||
|
||||
pingCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
|
||||
defer cancel()
|
||||
if err := pool.Ping(pingCtx); err != nil {
|
||||
pool.Close()
|
||||
return nil, fmt.Errorf("ping БД: %w", err)
|
||||
}
|
||||
return pool, nil
|
||||
}
|
||||
|
||||
func RunMigrations(ctx context.Context, pool *pgxpool.Pool) error {
|
||||
db := stdlib.OpenDBFromPool(pool)
|
||||
|
||||
goose.SetBaseFS(migrations.FS)
|
||||
if err := goose.SetDialect("postgres"); err != nil {
|
||||
return fmt.Errorf("goose dialect: %w", err)
|
||||
}
|
||||
if err := goose.UpContext(ctx, db, "."); err != nil {
|
||||
return fmt.Errorf("применение миграций: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"github.com/jackc/pgerrcode"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
|
||||
"high-loud-apps-labs/internal/domain"
|
||||
)
|
||||
|
||||
type coded interface {
|
||||
Code() domain.ErrorCode
|
||||
}
|
||||
|
||||
// mapError переводит ошибки драйвера в доменные.
|
||||
func mapError(err error) error {
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
var c coded
|
||||
if errors.As(err, &c) {
|
||||
return err
|
||||
}
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return err
|
||||
}
|
||||
if errors.Is(err, context.DeadlineExceeded) {
|
||||
return &domain.UnavailableError{Reason: "превышено время ожидания БД"}
|
||||
}
|
||||
if errors.Is(err, context.Canceled) {
|
||||
return &domain.UnavailableError{Reason: "запрос отменён"}
|
||||
}
|
||||
return &domain.UnavailableError{Reason: err.Error()}
|
||||
}
|
||||
|
||||
func notFound(err error, entity, id string) error {
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return &domain.NotFoundError{Entity: entity, ID: id}
|
||||
}
|
||||
return mapError(err)
|
||||
}
|
||||
|
||||
func uniqueViolation(err error) bool {
|
||||
var pgErr *pgconn.PgError
|
||||
if errors.As(err, &pgErr) {
|
||||
return pgErr.Code == pgerrcode.UniqueViolation
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func foreignKeyViolation(err error) bool {
|
||||
var pgErr *pgconn.PgError
|
||||
if errors.As(err, &pgErr) {
|
||||
return pgErr.Code == pgerrcode.ForeignKeyViolation
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func checkViolation(err error) bool {
|
||||
var pgErr *pgconn.PgError
|
||||
if errors.As(err, &pgErr) {
|
||||
return pgErr.Code == pgerrcode.CheckViolation
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"high-loud-apps-labs/internal/domain"
|
||||
)
|
||||
|
||||
type FailedJobRepo struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewFailedJobRepo(pool *pgxpool.Pool) *FailedJobRepo {
|
||||
return &FailedJobRepo{pool: pool}
|
||||
}
|
||||
|
||||
func (r *FailedJobRepo) Record(ctx context.Context, f *domain.FailedJob) error {
|
||||
if f.ID == "" {
|
||||
f.ID = uuid.NewString()
|
||||
}
|
||||
if f.LastErrorAt.IsZero() {
|
||||
f.LastErrorAt = time.Now().UTC()
|
||||
}
|
||||
const q = `
|
||||
INSERT INTO failed_jobs (id, attachment_id, reason_code, attempts, last_error_at, created_at)
|
||||
VALUES ($1::uuid, $2::uuid, $3, $4, $5, $5)
|
||||
`
|
||||
_, err := r.pool.Exec(ctx, q, f.ID, f.AttachmentID, f.ReasonCode, f.Attempts, f.LastErrorAt)
|
||||
return mapError(err)
|
||||
}
|
||||
|
||||
func (r *FailedJobRepo) Resolve(ctx context.Context, attachmentID string, resolution string) error {
|
||||
const q = `UPDATE failed_jobs SET resolved_at = now(), resolution = $2 WHERE attachment_id = $1::uuid AND resolved_at IS NULL`
|
||||
_, err := r.pool.Exec(ctx, q, attachmentID, resolution)
|
||||
return mapError(err)
|
||||
}
|
||||
|
||||
func (r *FailedJobRepo) ResolveInTx(ctx context.Context, tx domain.Tx, id string) error {
|
||||
const q = `
|
||||
UPDATE failed_jobs
|
||||
SET resolved_at = now(), resolution = 'manual_replay'
|
||||
WHERE attachment_id = $1::uuid AND resolved_at IS NULL
|
||||
`
|
||||
return tx.Exec(ctx, q, id)
|
||||
}
|
||||
|
||||
var _ domain.FailedJobRepository = (*FailedJobRepo)(nil)
|
||||
@@ -0,0 +1,321 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"high-loud-apps-labs/internal/domain"
|
||||
)
|
||||
|
||||
type MessageRepo struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewMessageRepo(pool *pgxpool.Pool) *MessageRepo {
|
||||
return &MessageRepo{pool: pool}
|
||||
}
|
||||
|
||||
func (r *MessageRepo) Create(ctx context.Context, m *domain.Message) error {
|
||||
const q = `
|
||||
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
|
||||
VALUES ($1::uuid, $2::uuid, $3::uuid, $4, $5)
|
||||
`
|
||||
_, err := r.pool.Exec(ctx, q, m.ID, m.ChatID, m.SenderID, m.Text, m.CreatedAt)
|
||||
if err != nil {
|
||||
if foreignKeyViolation(err) {
|
||||
return &domain.NotFoundError{Entity: "chat", ID: m.ChatID}
|
||||
}
|
||||
if checkViolation(err) {
|
||||
return &domain.ValidationError{Field: "text", Message: "нарушено ограничение"}
|
||||
}
|
||||
return mapError(err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *MessageRepo) CreateIdempotent(
|
||||
ctx context.Context,
|
||||
scope domain.IdempotencyScope,
|
||||
requestHash []byte,
|
||||
fresh *domain.Message,
|
||||
freshResponse []byte,
|
||||
ttl time.Duration,
|
||||
) (*domain.CreateIdempotentResult, error) {
|
||||
tx, err := r.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return nil, mapError(err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback(ctx) }()
|
||||
|
||||
// 1) Убираем просроченную запись, чтобы ON CONFLICT сработал
|
||||
// только на живой, а не на истёкшей строке.
|
||||
if _, err := tx.Exec(ctx, `
|
||||
DELETE FROM idempotency_keys
|
||||
WHERE user_id = $1::uuid AND method = $2 AND path = $3 AND key = $4
|
||||
AND expires_at <= now()
|
||||
`, scope.UserID, scope.Method, scope.Path, scope.Key); err != nil {
|
||||
return nil, mapError(err)
|
||||
}
|
||||
|
||||
// 2) Резервируем слот. Если параллельная реплика уже вставила —
|
||||
// Postgres заблокирует конфликтный INSERT и мы увидим RowsAffected=0
|
||||
// только после того, как конкурент закоммитит или откатится.
|
||||
expiresAt := time.Now().UTC().Add(ttl)
|
||||
tag, err := tx.Exec(ctx, `
|
||||
INSERT INTO idempotency_keys
|
||||
(user_id, method, path, key, request_hash, response_status, response_body, expires_at)
|
||||
VALUES ($1::uuid, $2, $3, $4, $5, $6, $7, $8)
|
||||
ON CONFLICT (user_id, method, path, key) DO NOTHING
|
||||
`, scope.UserID, scope.Method, scope.Path, scope.Key,
|
||||
requestHash, http.StatusCreated, freshResponse, expiresAt)
|
||||
if err != nil {
|
||||
return nil, mapError(err)
|
||||
}
|
||||
|
||||
// 3) Слот занят — читаем сохранённый ответ в этой же транзакции.
|
||||
if tag.RowsAffected() == 0 {
|
||||
var (
|
||||
storedHash []byte
|
||||
storedStatus int
|
||||
storedBody []byte
|
||||
)
|
||||
err := tx.QueryRow(ctx, `
|
||||
SELECT request_hash, response_status, response_body
|
||||
FROM idempotency_keys
|
||||
WHERE user_id = $1::uuid AND method = $2 AND path = $3 AND key = $4
|
||||
`, scope.UserID, scope.Method, scope.Path, scope.Key).
|
||||
Scan(&storedHash, &storedStatus, &storedBody)
|
||||
if err != nil {
|
||||
return nil, mapError(err)
|
||||
}
|
||||
|
||||
if !bytes.Equal(storedHash, requestHash) {
|
||||
return nil, &domain.IdempotencyConflictError{Key: scope.Key}
|
||||
}
|
||||
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return nil, mapError(err)
|
||||
}
|
||||
return &domain.CreateIdempotentResult{
|
||||
Status: storedStatus,
|
||||
Body: storedBody,
|
||||
Replayed: true,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// 4) Слот наш — валидируем вложения, вставляем сообщение, линкуем
|
||||
// вложения. Всё в одной транзакции: при ошибке на любом шаге
|
||||
// откатывается и idempotency-ключ, и сообщение, и связи.
|
||||
if err := r.validateAttachments(ctx, tx, fresh.ChatID, fresh.AttachmentIDs); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if _, err := tx.Exec(ctx, `
|
||||
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
|
||||
VALUES ($1::uuid, $2::uuid, $3::uuid, $4, $5)
|
||||
`, fresh.ID, fresh.ChatID, fresh.SenderID, fresh.Text, fresh.CreatedAt); err != nil {
|
||||
if foreignKeyViolation(err) {
|
||||
return nil, &domain.NotFoundError{Entity: "chat", ID: fresh.ChatID}
|
||||
}
|
||||
if checkViolation(err) {
|
||||
return nil, &domain.ValidationError{Field: "text", Message: "нарушено ограничение"}
|
||||
}
|
||||
return nil, mapError(err)
|
||||
}
|
||||
|
||||
if err := r.linkAttachments(ctx, tx, fresh.ID, fresh.AttachmentIDs); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return nil, mapError(err)
|
||||
}
|
||||
return &domain.CreateIdempotentResult{
|
||||
Status: http.StatusCreated,
|
||||
Body: freshResponse,
|
||||
Replayed: false,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (r *MessageRepo) ListByChat(ctx context.Context, chatID string, limit int, cursor *string) ([]domain.Message, *string, error) {
|
||||
scope := "messages:" + chatID
|
||||
|
||||
var (
|
||||
afterTime time.Time
|
||||
afterID string
|
||||
hasCursor bool
|
||||
)
|
||||
if cursor != nil {
|
||||
t, id, err := decodeCursor(*cursor, scope)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
afterTime = t
|
||||
afterID = id
|
||||
hasCursor = true
|
||||
}
|
||||
|
||||
var (
|
||||
rows pgx.Rows
|
||||
err error
|
||||
)
|
||||
if hasCursor {
|
||||
const q = `
|
||||
SELECT id, chat_id, sender_id, text, created_at
|
||||
FROM messages
|
||||
WHERE chat_id = $1::uuid
|
||||
AND (created_at, id) > ($2, $3::uuid)
|
||||
ORDER BY created_at, id
|
||||
LIMIT $4
|
||||
`
|
||||
rows, err = r.pool.Query(ctx, q, chatID, afterTime, afterID, limit+1)
|
||||
} else {
|
||||
const q = `
|
||||
SELECT id, chat_id, sender_id, text, created_at
|
||||
FROM messages
|
||||
WHERE chat_id = $1::uuid
|
||||
ORDER BY created_at, id
|
||||
LIMIT $2
|
||||
`
|
||||
rows, err = r.pool.Query(ctx, q, chatID, limit+1)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
page := make([]domain.Message, 0, limit)
|
||||
for rows.Next() {
|
||||
var m domain.Message
|
||||
if err := rows.Scan(&m.ID, &m.ChatID, &m.SenderID, &m.Text, &m.CreatedAt); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
page = append(page, m)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
var next *string
|
||||
if len(page) > limit {
|
||||
page = page[:limit]
|
||||
last := page[len(page)-1]
|
||||
c := encodeCursor(scope, last.CreatedAt, last.ID)
|
||||
next = &c
|
||||
}
|
||||
|
||||
if len(page) > 0 {
|
||||
msgIDs := make([]string, len(page))
|
||||
for i := range page {
|
||||
msgIDs[i] = page[i].ID
|
||||
}
|
||||
links, err := r.loadAttachmentIDs(ctx, msgIDs)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
for i := range page {
|
||||
if ids, ok := links[page[i].ID]; ok {
|
||||
page[i].AttachmentIDs = ids
|
||||
} else {
|
||||
page[i].AttachmentIDs = []string{}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return page, next, nil
|
||||
}
|
||||
|
||||
func (r *MessageRepo) validateAttachments(ctx context.Context, tx pgx.Tx, chatID string, ids []string) error {
|
||||
if len(ids) == 0 {
|
||||
return nil
|
||||
}
|
||||
const q = `SELECT id, chat_id, status FROM attachments WHERE id = ANY($1::uuid[])`
|
||||
rows, err := tx.Query(ctx, q, ids)
|
||||
if err != nil {
|
||||
return mapError(err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
type info struct {
|
||||
chatID string
|
||||
status domain.AttachmentStatus
|
||||
}
|
||||
found := make(map[string]info, len(ids))
|
||||
for rows.Next() {
|
||||
var id, chID, st string
|
||||
if err := rows.Scan(&id, &chID, &st); err != nil {
|
||||
return mapError(err)
|
||||
}
|
||||
found[id] = info{chatID: chID, status: domain.AttachmentStatus(st)}
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return mapError(err)
|
||||
}
|
||||
|
||||
for _, id := range ids {
|
||||
a, ok := found[id]
|
||||
if !ok || a.chatID != chatID {
|
||||
return &domain.NotFoundError{Entity: "attachment", ID: id}
|
||||
}
|
||||
if a.status == domain.AttachmentStatusFailed {
|
||||
return &domain.ConflictError{Reason: "вложение " + id + " в состоянии failed"}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *MessageRepo) linkAttachments(ctx context.Context, tx pgx.Tx, messageID string, ids []string) error {
|
||||
if len(ids) == 0 {
|
||||
return nil
|
||||
}
|
||||
const q = `INSERT INTO message_attachments (message_id, attachment_id, position) VALUES ($1::uuid, $2::uuid, $3)`
|
||||
for i, id := range ids {
|
||||
if _, err := tx.Exec(ctx, q, messageID, id, int16(i)); err != nil {
|
||||
if foreignKeyViolation(err) {
|
||||
return &domain.NotFoundError{Entity: "attachment", ID: id}
|
||||
}
|
||||
if uniqueViolation(err) {
|
||||
return &domain.ValidationError{Field: "attachment_ids", Message: "дубликаты запрещены"}
|
||||
}
|
||||
if checkViolation(err) {
|
||||
return &domain.ValidationError{Field: "attachment_ids", Message: "нарушено ограничение"}
|
||||
}
|
||||
return mapError(err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *MessageRepo) loadAttachmentIDs(ctx context.Context, messageIDs []string) (map[string][]string, error) {
|
||||
if len(messageIDs) == 0 {
|
||||
return map[string][]string{}, nil
|
||||
}
|
||||
const q = `
|
||||
SELECT message_id, attachment_id
|
||||
FROM message_attachments
|
||||
WHERE message_id = ANY($1::uuid[])
|
||||
ORDER BY message_id, position
|
||||
`
|
||||
rows, err := r.pool.Query(ctx, q, messageIDs)
|
||||
if err != nil {
|
||||
return nil, mapError(err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
result := make(map[string][]string, len(messageIDs))
|
||||
for rows.Next() {
|
||||
var msgID, attID string
|
||||
if err := rows.Scan(&msgID, &attID); err != nil {
|
||||
return nil, mapError(err)
|
||||
}
|
||||
result[msgID] = append(result[msgID], attID)
|
||||
}
|
||||
return result, mapError(rows.Err())
|
||||
}
|
||||
|
||||
var _ domain.MessageRepository = (*MessageRepo)(nil)
|
||||
@@ -0,0 +1,116 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"high-loud-apps-labs/internal/domain"
|
||||
)
|
||||
|
||||
type OutboxRepo struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewOutboxRepo(pool *pgxpool.Pool) *OutboxRepo {
|
||||
return &OutboxRepo{pool: pool}
|
||||
}
|
||||
|
||||
func (r *OutboxRepo) Enqueue(ctx context.Context, tx domain.Tx, e *domain.OutboxEntry) error {
|
||||
if e.AggregateType == "" || e.AggregateID == "" || e.EventType == "" {
|
||||
return &domain.ValidationError{
|
||||
Field: "outbox",
|
||||
Message: "aggregate_type, aggregate_id и event_type обязательны",
|
||||
}
|
||||
}
|
||||
if len(e.Payload) == 0 {
|
||||
return &domain.ValidationError{
|
||||
Field: "outbox.payload",
|
||||
Message: "не может быть пустым",
|
||||
}
|
||||
}
|
||||
|
||||
if e.ID == "" {
|
||||
e.ID = uuid.NewString()
|
||||
}
|
||||
if e.CreatedAt.IsZero() {
|
||||
e.CreatedAt = time.Now().UTC()
|
||||
}
|
||||
|
||||
const q = `
|
||||
INSERT INTO outbox
|
||||
(id, aggregate_type, aggregate_id, event_type, payload, attempts, created_at, published_at)
|
||||
VALUES ($1::uuid, $2, $3::uuid, $4, $5::jsonb, $6, $7, $8)
|
||||
`
|
||||
if err := tx.Exec(ctx, q,
|
||||
e.ID, e.AggregateType, e.AggregateID, e.EventType,
|
||||
string(e.Payload), e.Attempts, e.CreatedAt, e.PublishedAt,
|
||||
); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *OutboxRepo) ClaimBatch(ctx context.Context, limit int) ([]domain.OutboxEntry, error) {
|
||||
const q = `
|
||||
WITH claimed AS (
|
||||
SELECT id FROM outbox
|
||||
WHERE published_at IS NULL AND created_at <= now()
|
||||
ORDER BY created_at
|
||||
LIMIT $1
|
||||
FOR UPDATE SKIP LOCKED
|
||||
)
|
||||
UPDATE outbox o
|
||||
SET attempts = attempts + 1
|
||||
FROM claimed c
|
||||
WHERE o.id = c.id
|
||||
RETURNING o.id, o.aggregate_type, o.aggregate_id, o.event_type, o.payload, o.attempts, o.created_at, o.published_at
|
||||
`
|
||||
rows, err := r.pool.Query(ctx, q, limit)
|
||||
if err != nil {
|
||||
return nil, mapError(err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var entries []domain.OutboxEntry
|
||||
for rows.Next() {
|
||||
var e domain.OutboxEntry
|
||||
if err := rows.Scan(
|
||||
&e.ID, &e.AggregateType, &e.AggregateID, &e.EventType,
|
||||
&e.Payload, &e.Attempts, &e.CreatedAt, &e.PublishedAt,
|
||||
); err != nil {
|
||||
return nil, mapError(err)
|
||||
}
|
||||
entries = append(entries, e)
|
||||
}
|
||||
return entries, mapError(rows.Err())
|
||||
}
|
||||
|
||||
func (r *OutboxRepo) EnqueueDirect(ctx context.Context, e *domain.OutboxEntry) error {
|
||||
if e.ID == "" {
|
||||
e.ID = uuid.NewString()
|
||||
}
|
||||
const q = `
|
||||
INSERT INTO outbox
|
||||
(id, aggregate_type, aggregate_id, event_type, payload, attempts, created_at, published_at)
|
||||
VALUES ($1::uuid, $2, $3::uuid, $4, $5::jsonb, $6, $7, $8)
|
||||
`
|
||||
_, err := r.pool.Exec(ctx, q,
|
||||
e.ID, e.AggregateType, e.AggregateID, e.EventType,
|
||||
string(e.Payload), e.Attempts, e.CreatedAt, e.PublishedAt,
|
||||
)
|
||||
return mapError(err)
|
||||
}
|
||||
|
||||
func (r *OutboxRepo) MarkPublished(ctx context.Context, ids []string) error {
|
||||
if len(ids) == 0 {
|
||||
return nil
|
||||
}
|
||||
const q = `UPDATE outbox SET published_at = now() WHERE id = ANY($1::uuid[])`
|
||||
_, err := r.pool.Exec(ctx, q, ids)
|
||||
return mapError(err)
|
||||
}
|
||||
|
||||
var _ domain.OutboxRepository = (*OutboxRepo)(nil)
|
||||
@@ -0,0 +1,59 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"high-loud-apps-labs/internal/domain"
|
||||
)
|
||||
|
||||
type SessionRepo struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewSessionRepo(pool *pgxpool.Pool) *SessionRepo {
|
||||
return &SessionRepo{pool: pool}
|
||||
}
|
||||
|
||||
func (r *SessionRepo) Create(ctx context.Context, s *domain.Session) error {
|
||||
const q = `
|
||||
INSERT INTO sessions (token_hash, user_id, expires_at, created_at)
|
||||
VALUES ($1, $2::uuid, $3, $4)
|
||||
`
|
||||
_, err := r.pool.Exec(ctx, q, s.TokenHash, s.UserID, s.ExpiresAt, s.CreatedAt)
|
||||
if err != nil {
|
||||
if uniqueViolation(err) {
|
||||
return &domain.AlreadyExistsError{
|
||||
Entity: "session",
|
||||
Field: "token_hash",
|
||||
Value: "",
|
||||
}
|
||||
}
|
||||
return mapError(err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *SessionRepo) GetByTokenHash(ctx context.Context, tokenHash []byte) (*domain.Session, error) {
|
||||
const q = `
|
||||
SELECT token_hash, user_id, expires_at, created_at
|
||||
FROM sessions
|
||||
WHERE token_hash = $1
|
||||
`
|
||||
s := &domain.Session{}
|
||||
err := r.pool.QueryRow(ctx, q, tokenHash).
|
||||
Scan(&s.TokenHash, &s.UserID, &s.ExpiresAt, &s.CreatedAt)
|
||||
if err != nil {
|
||||
return nil, notFound(err, "session", "")
|
||||
}
|
||||
return s, nil
|
||||
}
|
||||
|
||||
func (r *SessionRepo) DeleteByTokenHash(ctx context.Context, tokenHash []byte) error {
|
||||
const q = `DELETE FROM sessions WHERE token_hash = $1`
|
||||
_, err := r.pool.Exec(ctx, q, tokenHash)
|
||||
return mapError(err)
|
||||
}
|
||||
|
||||
var _ domain.SessionRepository = (*SessionRepo)(nil)
|
||||
@@ -0,0 +1,22 @@
|
||||
package postgres
|
||||
|
||||
import "github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
type Storage struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func New(pool *pgxpool.Pool) *Storage {
|
||||
return &Storage{pool: pool}
|
||||
}
|
||||
|
||||
func (s *Storage) Pool() *pgxpool.Pool { return s.pool }
|
||||
|
||||
func (s *Storage) Users() *UserRepo { return &UserRepo{pool: s.pool} }
|
||||
func (s *Storage) Chats() *ChatRepo { return &ChatRepo{pool: s.pool} }
|
||||
func (s *Storage) Messages() *MessageRepo { return &MessageRepo{pool: s.pool} }
|
||||
func (s *Storage) Sessions() *SessionRepo { return &SessionRepo{pool: s.pool} }
|
||||
func (s *Storage) Attachments() *AttachmentRepo { return &AttachmentRepo{pool: s.pool} }
|
||||
func (s *Storage) Outbox() *OutboxRepo { return &OutboxRepo{pool: s.pool} }
|
||||
func (s *Storage) Variants() *AttachmentVariantRepo { return &AttachmentVariantRepo{pool: s.pool} }
|
||||
func (s *Storage) FailedJobs() *FailedJobRepo { return &FailedJobRepo{pool: s.pool} }
|
||||
@@ -0,0 +1,35 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
"high-loud-apps-labs/internal/domain"
|
||||
)
|
||||
|
||||
type pgxTx struct {
|
||||
tx pgx.Tx
|
||||
}
|
||||
|
||||
func (t *pgxTx) Exec(ctx context.Context, sql string, args ...any) error {
|
||||
_, err := t.tx.Exec(ctx, sql, args...)
|
||||
return mapError(err)
|
||||
}
|
||||
|
||||
// WithTx выполняет fn в одной транзакции:
|
||||
// - commit, если fn вернул nil;
|
||||
// - rollback, если fn вернул ошибку.
|
||||
|
||||
func (s *Storage) WithTx(ctx context.Context, fn func(tx domain.Tx) error) error {
|
||||
tx, err := s.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return mapError(err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback(ctx) }()
|
||||
|
||||
if err := fn(&pgxTx{tx: tx}); err != nil {
|
||||
return err
|
||||
}
|
||||
return mapError(tx.Commit(ctx))
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"high-loud-apps-labs/internal/domain"
|
||||
)
|
||||
|
||||
type UserRepo struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewUserRepo(pool *pgxpool.Pool) *UserRepo {
|
||||
return &UserRepo{pool: pool}
|
||||
}
|
||||
|
||||
func (r *UserRepo) Create(ctx context.Context, user *domain.User) error {
|
||||
const q = `
|
||||
INSERT INTO users (id, username, display_name, password_hash, created_at)
|
||||
VALUES ($1::uuid, $2, $3, $4, $5)
|
||||
`
|
||||
_, err := r.pool.Exec(ctx, q,
|
||||
user.ID, user.Username, user.DisplayName, user.PasswordHash, user.CreatedAt,
|
||||
)
|
||||
if err != nil {
|
||||
if uniqueViolation(err) {
|
||||
return &domain.AlreadyExistsError{
|
||||
Entity: "user",
|
||||
Field: "username",
|
||||
Value: user.Username,
|
||||
}
|
||||
}
|
||||
if checkViolation(err) {
|
||||
return &domain.ValidationError{
|
||||
Field: "user",
|
||||
Message: "нарушено ограничение целостности",
|
||||
}
|
||||
}
|
||||
return mapError(err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *UserRepo) GetByID(ctx context.Context, id string) (*domain.User, error) {
|
||||
const q = `
|
||||
SELECT id, username, display_name, password_hash, created_at
|
||||
FROM users
|
||||
WHERE id = $1::uuid
|
||||
`
|
||||
u := &domain.User{}
|
||||
err := r.pool.QueryRow(ctx, q, id).
|
||||
Scan(&u.ID, &u.Username, &u.DisplayName, &u.PasswordHash, &u.CreatedAt)
|
||||
if err != nil {
|
||||
return nil, notFound(err, "user", id)
|
||||
}
|
||||
return u, nil
|
||||
}
|
||||
|
||||
func (r *UserRepo) GetByUsername(ctx context.Context, username string) (*domain.User, error) {
|
||||
const q = `
|
||||
SELECT id, username, display_name, password_hash, created_at
|
||||
FROM users
|
||||
WHERE username = $1
|
||||
`
|
||||
u := &domain.User{}
|
||||
err := r.pool.QueryRow(ctx, q, username).
|
||||
Scan(&u.ID, &u.Username, &u.DisplayName, &u.PasswordHash, &u.CreatedAt)
|
||||
if err != nil {
|
||||
return nil, notFound(err, "user", username)
|
||||
}
|
||||
return u, nil
|
||||
}
|
||||
|
||||
var _ domain.UserRepository = (*UserRepo)(nil)
|
||||
Reference in New Issue
Block a user