forked from mtusi2026/mtusi2026lab2
ЛР 2 — БВТ2303 — Брезгунова — на 5
This commit is contained in:
+180
@@ -0,0 +1,180 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"database/sql"
|
||||
"embed"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/lib/pq"
|
||||
"github.com/redis/go-redis/v9"
|
||||
"mtusi2026lab2/models"
|
||||
)
|
||||
|
||||
//go:embed migrations/*.sql
|
||||
var migrations embed.FS
|
||||
|
||||
type store struct {
|
||||
db *sql.DB
|
||||
cache *redis.Client
|
||||
metrics *cacheMetrics
|
||||
}
|
||||
|
||||
// A transaction-scoped advisory lock serializes migrations across starting API processes.
|
||||
func migrate(ctx context.Context, db *sql.DB) error {
|
||||
tx, err := db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
if _, err = tx.ExecContext(ctx, `SELECT pg_advisory_xact_lock(202602)`); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err = tx.ExecContext(ctx, `CREATE TABLE IF NOT EXISTS schema_migrations (name text PRIMARY KEY, checksum text NOT NULL, applied_at timestamptz NOT NULL DEFAULT clock_timestamp())`); err != nil {
|
||||
return err
|
||||
}
|
||||
entries, err := migrations.ReadDir("migrations")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, entry := range entries {
|
||||
data, err := migrations.ReadFile("migrations/" + entry.Name())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
sum := sha256.Sum256(data)
|
||||
checksum := hex.EncodeToString(sum[:])
|
||||
var previous string
|
||||
err = tx.QueryRowContext(ctx, `SELECT checksum FROM schema_migrations WHERE name=$1`, entry.Name()).Scan(&previous)
|
||||
if err == nil {
|
||||
if previous != checksum {
|
||||
return fmt.Errorf("changed migration %s", entry.Name())
|
||||
}
|
||||
continue
|
||||
}
|
||||
if !errors.Is(err, sql.ErrNoRows) {
|
||||
return err
|
||||
}
|
||||
if _, err = tx.ExecContext(ctx, string(data)); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err = tx.ExecContext(ctx, `INSERT INTO schema_migrations(name,checksum) VALUES($1,$2)`, entry.Name(), checksum); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return tx.Commit()
|
||||
}
|
||||
|
||||
func scanUser(row interface{ Scan(...any) error }) (models.User, error) {
|
||||
var u models.User
|
||||
err := row.Scan(&u.ID, &u.Username, &u.DisplayName, &u.CreatedAt)
|
||||
u.CreatedAt = u.CreatedAt.UTC()
|
||||
return u, err
|
||||
}
|
||||
|
||||
func (s *store) user(ctx context.Context, id models.UUID) (models.User, error) {
|
||||
key := "profile:v1:" + string(id)
|
||||
if s.cache != nil {
|
||||
cacheCtx, cancel := context.WithTimeout(ctx, 150*time.Millisecond)
|
||||
data, err := s.cache.Get(cacheCtx, key).Bytes()
|
||||
cancel()
|
||||
var u models.User
|
||||
if err == nil && json.Unmarshal(data, &u) == nil && u.ID == id {
|
||||
s.metrics.hits.Add(1)
|
||||
return u, nil
|
||||
}
|
||||
s.metrics.misses.Add(1)
|
||||
if err != nil && !errors.Is(err, redis.Nil) {
|
||||
s.metrics.failures.Add(1)
|
||||
}
|
||||
}
|
||||
u, err := scanUser(s.db.QueryRowContext(ctx, `SELECT id,username,display_name,created_at FROM users WHERE id=$1`, id))
|
||||
if err == nil && s.cache != nil {
|
||||
data, _ := json.Marshal(u)
|
||||
cacheCtx, cancel := context.WithTimeout(ctx, 150*time.Millisecond)
|
||||
if s.cache.Set(cacheCtx, key, data, 5*time.Minute).Err() != nil {
|
||||
s.metrics.failures.Add(1)
|
||||
}
|
||||
cancel()
|
||||
}
|
||||
return u, err
|
||||
}
|
||||
|
||||
func (s *store) createChat(ctx context.Context, title string, members []models.UUID) (models.Chat, error) {
|
||||
tx, err := s.db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return models.Chat{}, err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
chat := models.Chat{ID: models.UUID(newID()), Title: title, MemberIDs: members}
|
||||
err = tx.QueryRowContext(ctx, `INSERT INTO chats(id,title) VALUES($1,$2) RETURNING created_at`, chat.ID, title).Scan(&chat.CreatedAt)
|
||||
if err != nil {
|
||||
return chat, err
|
||||
}
|
||||
for i, id := range members {
|
||||
if _, err = tx.ExecContext(ctx, `INSERT INTO chat_members(chat_id,user_id,position) VALUES($1,$2,$3)`, chat.ID, id, i); err != nil {
|
||||
return chat, err
|
||||
}
|
||||
}
|
||||
err = tx.Commit()
|
||||
chat.CreatedAt = chat.CreatedAt.UTC()
|
||||
return chat, err
|
||||
}
|
||||
|
||||
func scanChat(row interface{ Scan(...any) error }) (models.Chat, error) {
|
||||
var c models.Chat
|
||||
var members pq.StringArray
|
||||
err := row.Scan(&c.ID, &c.Title, &c.CreatedAt, &members)
|
||||
c.CreatedAt = c.CreatedAt.UTC()
|
||||
c.MemberIDs = make([]models.UUID, len(members))
|
||||
for i, m := range members {
|
||||
c.MemberIDs[i] = models.UUID(m)
|
||||
}
|
||||
return c, err
|
||||
}
|
||||
|
||||
const chatColumns = `c.id,c.title,c.created_at,ARRAY(SELECT user_id::text FROM chat_members WHERE chat_id=c.id ORDER BY position)`
|
||||
|
||||
func (s *store) chat(ctx context.Context, id, user models.UUID) (models.Chat, error) {
|
||||
return scanChat(s.db.QueryRowContext(ctx, `SELECT `+chatColumns+` FROM chats c WHERE c.id=$1 AND EXISTS(SELECT 1 FROM chat_members WHERE chat_id=c.id AND user_id=$2)`, id, user))
|
||||
}
|
||||
|
||||
func (s *store) chats(ctx context.Context, user models.UUID, p cursor, limit int) ([]models.Chat, error) {
|
||||
rows, err := s.db.QueryContext(ctx, `SELECT `+chatColumns+` FROM chats c WHERE EXISTS(SELECT 1 FROM chat_members WHERE chat_id=c.id AND user_id=$1) AND (c.created_at,c.id)>($2,$3::uuid) ORDER BY c.created_at,c.id LIMIT $4`, user, p.CreatedAt, p.ID, limit+1)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
items := []models.Chat{}
|
||||
for rows.Next() {
|
||||
c, err := scanChat(rows)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, c)
|
||||
}
|
||||
return items, rows.Err()
|
||||
}
|
||||
|
||||
func (s *store) messages(ctx context.Context, chat models.UUID, p cursor, limit int) ([]models.Message, error) {
|
||||
rows, err := s.db.QueryContext(ctx, `SELECT id,chat_id,sender_id,text,created_at FROM messages WHERE chat_id=$1 AND (created_at,id)>($2,$3::uuid) ORDER BY created_at,id LIMIT $4`, chat, p.CreatedAt, p.ID, limit+1)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
items := []models.Message{}
|
||||
for rows.Next() {
|
||||
var m models.Message
|
||||
if err = rows.Scan(&m.ID, &m.ChatID, &m.SenderID, &m.Text, &m.CreatedAt); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
m.CreatedAt = m.CreatedAt.UTC()
|
||||
items = append(items, m)
|
||||
}
|
||||
return items, rows.Err()
|
||||
}
|
||||
Reference in New Issue
Block a user