forked from mtusi2026/mtusi2026lab5
lab5 na4
This commit is contained in:
@@ -0,0 +1,51 @@
|
||||
package store
|
||||
|
||||
import "sync/atomic"
|
||||
|
||||
type Limiter struct {
|
||||
maxMessages int64
|
||||
messageCount int64
|
||||
maxConcurrent int
|
||||
inFlight chan struct{}
|
||||
}
|
||||
|
||||
func NewLimiter(maxMessages int64, maxConcurrent int) *Limiter {
|
||||
return &Limiter{
|
||||
maxMessages: maxMessages,
|
||||
maxConcurrent: maxConcurrent,
|
||||
inFlight: make(chan struct{}, maxConcurrent),
|
||||
}
|
||||
}
|
||||
|
||||
func (l *Limiter) TryReserveMessage() bool {
|
||||
for {
|
||||
cur := atomic.LoadInt64(&l.messageCount)
|
||||
if cur >= l.maxMessages {
|
||||
return false
|
||||
}
|
||||
if atomic.CompareAndSwapInt64(&l.messageCount, cur, cur+1) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (l *Limiter) ReleaseMessage() {
|
||||
atomic.AddInt64(&l.messageCount, -1)
|
||||
}
|
||||
|
||||
func (l *Limiter) CurrentMessageCount() int64 {
|
||||
return atomic.LoadInt64(&l.messageCount)
|
||||
}
|
||||
|
||||
func (l *Limiter) TryAcquire() bool {
|
||||
select {
|
||||
case l.inFlight <- struct{}{}:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func (l *Limiter) Release() {
|
||||
<-l.inFlight
|
||||
}
|
||||
@@ -0,0 +1,612 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"sync/atomic"
|
||||
"unicode"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"mtusi2026/internal/cursor"
|
||||
"mtusi2026/internal/idgen"
|
||||
"mtusi2026/internal/jobs"
|
||||
"mtusi2026/internal/model"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrUsernameTaken = errors.New("username taken")
|
||||
ErrChatNotFound = errors.New("chat not found or not accessible")
|
||||
ErrValidation = errors.New("validation failed")
|
||||
ErrCapacityExceeded = errors.New("message capacity exceeded")
|
||||
ErrAttachmentNotFound = errors.New("attachment not found or not accessible")
|
||||
ErrAttachmentFailed = errors.New("attachment processing failed")
|
||||
ErrUsernameNotFound = errors.New("username not found")
|
||||
ErrSessionNotFound = errors.New("session not found or expired")
|
||||
)
|
||||
|
||||
type Store struct {
|
||||
pool *pgxpool.Pool
|
||||
Limiter *Limiter
|
||||
chatSQLQueries atomic.Int64
|
||||
}
|
||||
|
||||
func (s *Store) ResetChatSQLQueries() {
|
||||
s.chatSQLQueries.Store(0)
|
||||
}
|
||||
|
||||
func (s *Store) ChatSQLQueries() int64 {
|
||||
return s.chatSQLQueries.Load()
|
||||
}
|
||||
|
||||
func (s *Store) IsChatMember(ctx context.Context, chatID, userID string) (bool, error) {
|
||||
var ok bool
|
||||
err := s.pool.QueryRow(ctx,
|
||||
`SELECT EXISTS(SELECT 1 FROM chat_members WHERE chat_id = $1 AND user_id = $2)`,
|
||||
chatID, userID).Scan(&ok)
|
||||
return ok, err
|
||||
}
|
||||
|
||||
func (s *Store) CreateAttachment(ctx context.Context, a model.Attachment) (model.Attachment, error) {
|
||||
tx, err := s.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return a, err
|
||||
}
|
||||
defer tx.Rollback(ctx)
|
||||
err = tx.QueryRow(ctx,
|
||||
`INSERT INTO attachments (id, chat_id, owner_id, filename, content_type, size_bytes, sha256, object_key, staging_key, status)
|
||||
VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,'queued')
|
||||
RETURNING status, created_at, updated_at`,
|
||||
a.ID, a.ChatID, a.OwnerID, a.Filename, a.ContentType, a.SizeBytes, a.SHA256, a.ObjectKey, a.StagingKey,
|
||||
).Scan(&a.Status, &a.CreatedAt, &a.UpdatedAt)
|
||||
if err != nil {
|
||||
return a, err
|
||||
}
|
||||
if err = jobs.Enqueue(ctx, tx, a.ID); err != nil {
|
||||
return a, err
|
||||
}
|
||||
err = tx.Commit(ctx)
|
||||
a.Variants = []model.Variant{}
|
||||
return a, err
|
||||
}
|
||||
func (s *Store) GetAttachmentForUser(ctx context.Context, id, userID string) (model.Attachment, error) {
|
||||
var a model.Attachment
|
||||
var variants []byte
|
||||
err := s.pool.QueryRow(ctx,
|
||||
`SELECT a.id, a.chat_id, a.owner_id, 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`, id, userID,
|
||||
).Scan(&a.ID, &a.ChatID, &a.OwnerID, &a.Filename, &a.ContentType, &a.SizeBytes, &a.SHA256,
|
||||
&a.ObjectKey, &a.Status, &a.CreatedAt, &a.UpdatedAt, &variants, &a.ErrorCode)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return model.Attachment{}, ErrAttachmentNotFound
|
||||
}
|
||||
a.Variants = []model.Variant{}
|
||||
if err == nil {
|
||||
err = json.Unmarshal(variants, &a.Variants)
|
||||
}
|
||||
return a, err
|
||||
}
|
||||
|
||||
func (s *Store) loadAttachmentIDs(ctx context.Context, msgs []model.Message) error {
|
||||
if len(msgs) == 0 {
|
||||
return nil
|
||||
}
|
||||
ids := make([]string, len(msgs))
|
||||
pos := make(map[string]int, len(msgs))
|
||||
for i := range msgs {
|
||||
ids[i] = msgs[i].ID
|
||||
pos[msgs[i].ID] = i
|
||||
msgs[i].AttachmentIDs = []string{}
|
||||
}
|
||||
rows, err := s.pool.Query(ctx,
|
||||
`SELECT message_id, attachment_id FROM message_attachments
|
||||
WHERE message_id IN (SELECT unnest($1::text[])::uuid)
|
||||
ORDER BY message_id, position`, ids)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer rows.Close()
|
||||
for rows.Next() {
|
||||
var mid, aid string
|
||||
if err := rows.Scan(&mid, &aid); err != nil {
|
||||
return err
|
||||
}
|
||||
if i, ok := pos[mid]; ok {
|
||||
msgs[i].AttachmentIDs = append(msgs[i].AttachmentIDs, aid)
|
||||
}
|
||||
}
|
||||
return rows.Err()
|
||||
}
|
||||
|
||||
func New(pool *pgxpool.Pool, limiter *Limiter) *Store {
|
||||
return &Store{pool: pool, Limiter: limiter}
|
||||
}
|
||||
|
||||
func txAttachmentIDs(ctx context.Context, tx pgx.Tx, messageID string) ([]string, error) {
|
||||
rows, err := tx.Query(ctx,
|
||||
`SELECT attachment_id FROM message_attachments WHERE message_id = $1 ORDER BY position`, messageID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
ids := []string{}
|
||||
for rows.Next() {
|
||||
var id string
|
||||
if err := rows.Scan(&id); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ids = append(ids, id)
|
||||
}
|
||||
return ids, rows.Err()
|
||||
}
|
||||
|
||||
func (s *Store) CreateUser(ctx context.Context, username, displayName, passwordHash string) (model.User, error) {
|
||||
var u model.User
|
||||
err := s.pool.QueryRow(ctx,
|
||||
`INSERT INTO users (username, display_name, password_hash)
|
||||
VALUES ($1, $2, $3)
|
||||
RETURNING id, username, display_name, created_at`,
|
||||
username, displayName, passwordHash,
|
||||
).Scan(&u.ID, &u.Username, &u.DisplayName, &u.CreatedAt)
|
||||
|
||||
if err != nil {
|
||||
if isUniqueViolation(err) {
|
||||
return model.User{}, ErrUsernameTaken
|
||||
}
|
||||
return model.User{}, err
|
||||
}
|
||||
return u, nil
|
||||
}
|
||||
|
||||
func (s *Store) GetUserByID(ctx context.Context, id string) (model.User, bool, error) {
|
||||
var u model.User
|
||||
err := s.pool.QueryRow(ctx,
|
||||
`SELECT id, username, display_name, created_at FROM users WHERE id = $1`,
|
||||
id,
|
||||
).Scan(&u.ID, &u.Username, &u.DisplayName, &u.CreatedAt)
|
||||
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return model.User{}, false, nil
|
||||
}
|
||||
if err != nil {
|
||||
return model.User{}, false, err
|
||||
}
|
||||
|
||||
return u, true, nil
|
||||
}
|
||||
|
||||
func (s *Store) CreateChat(ctx context.Context, callerID, title string, memberIDs []string) (model.Chat, error) {
|
||||
if len(memberIDs) == 0 || len(memberIDs) > 100 {
|
||||
return model.Chat{}, ErrValidation
|
||||
}
|
||||
|
||||
seen := make(map[string]bool, len(memberIDs))
|
||||
callerIncluded := false
|
||||
for _, id := range memberIDs {
|
||||
if seen[id] {
|
||||
return model.Chat{}, ErrValidation
|
||||
}
|
||||
seen[id] = true
|
||||
if id == callerID {
|
||||
callerIncluded = true
|
||||
}
|
||||
}
|
||||
if !callerIncluded {
|
||||
return model.Chat{}, ErrValidation
|
||||
}
|
||||
|
||||
tx, err := s.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return model.Chat{}, err
|
||||
}
|
||||
defer tx.Rollback(ctx)
|
||||
|
||||
var c model.Chat
|
||||
err = tx.QueryRow(ctx,
|
||||
`INSERT INTO chats (title) VALUES ($1) RETURNING id, title, created_at`,
|
||||
title,
|
||||
).Scan(&c.ID, &c.Title, &c.CreatedAt)
|
||||
if err != nil {
|
||||
return model.Chat{}, err
|
||||
}
|
||||
|
||||
for _, memberID := range memberIDs {
|
||||
_, err = tx.Exec(ctx,
|
||||
`INSERT INTO chat_members (chat_id, user_id) VALUES ($1, $2)`,
|
||||
c.ID, memberID,
|
||||
)
|
||||
if err != nil {
|
||||
if isForeignKeyViolation(err) {
|
||||
return model.Chat{}, ErrValidation
|
||||
}
|
||||
return model.Chat{}, err
|
||||
}
|
||||
}
|
||||
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return model.Chat{}, err
|
||||
}
|
||||
|
||||
c.MemberIDs = append([]string{}, memberIDs...)
|
||||
return c, nil
|
||||
}
|
||||
|
||||
func (s *Store) GetChat(ctx context.Context, chatID, userID string) (model.Chat, error) {
|
||||
var c model.Chat
|
||||
s.chatSQLQueries.Add(1)
|
||||
|
||||
err := s.pool.QueryRow(ctx,
|
||||
`SELECT c.id, c.title, c.created_at
|
||||
FROM chats c
|
||||
JOIN chat_members cm ON cm.chat_id = c.id AND cm.user_id = $2
|
||||
WHERE c.id = $1`,
|
||||
chatID, userID,
|
||||
).Scan(&c.ID, &c.Title, &c.CreatedAt)
|
||||
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return model.Chat{}, ErrChatNotFound
|
||||
}
|
||||
return model.Chat{}, fmt.Errorf("get chat: %w", err)
|
||||
}
|
||||
|
||||
memberIDs, err := s.listChatMemberIDs(ctx, c.ID)
|
||||
if err != nil {
|
||||
return model.Chat{}, err
|
||||
}
|
||||
c.MemberIDs = memberIDs
|
||||
return c, nil
|
||||
}
|
||||
|
||||
func (s *Store) listChatMemberIDs(ctx context.Context, chatID string) ([]string, error) {
|
||||
s.chatSQLQueries.Add(1)
|
||||
|
||||
rows, err := s.pool.Query(ctx, `SELECT user_id FROM chat_members WHERE chat_id = $1`, chatID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var ids []string
|
||||
for rows.Next() {
|
||||
var id string
|
||||
if err := rows.Scan(&id); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ids = append(ids, id)
|
||||
}
|
||||
return ids, rows.Err()
|
||||
}
|
||||
|
||||
func (s *Store) ListChatsForUser(ctx context.Context, userID, cursorStr string, limit int) ([]model.Chat, *string, error) {
|
||||
var after *cursor.Cursor
|
||||
if cursorStr != "" {
|
||||
c, err := cursor.Decode(cursorStr)
|
||||
if err != nil || c.Scope != "chats:"+userID {
|
||||
return nil, nil, ErrValidation
|
||||
}
|
||||
after = &c
|
||||
}
|
||||
|
||||
query := `
|
||||
SELECT c.id, c.title, c.created_at
|
||||
FROM chats c
|
||||
JOIN chat_members cm ON cm.chat_id = c.id
|
||||
WHERE cm.user_id = $1`
|
||||
args := []any{userID}
|
||||
|
||||
if after != nil {
|
||||
query += ` AND (c.created_at, c.id) > ($2, $3)`
|
||||
args = append(args, after.CreatedAt, after.ID)
|
||||
}
|
||||
query += ` ORDER BY c.created_at ASC, c.id ASC LIMIT $` + strconv.Itoa(len(args)+1)
|
||||
args = append(args, limit+1)
|
||||
|
||||
rows, err := s.pool.Query(ctx, query, args...)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var page []model.Chat
|
||||
for rows.Next() {
|
||||
var c model.Chat
|
||||
if err := rows.Scan(&c.ID, &c.Title, &c.CreatedAt); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
page = append(page, c)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
var next *string
|
||||
if len(page) > limit {
|
||||
last := page[limit-1]
|
||||
nc := cursor.Encode(cursor.Cursor{Scope: "chats:" + userID, CreatedAt: last.CreatedAt, ID: last.ID})
|
||||
next = &nc
|
||||
page = page[:limit]
|
||||
}
|
||||
|
||||
for i := range page {
|
||||
memberIDs, err := s.listChatMemberIDs(ctx, page[i].ID)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
page[i].MemberIDs = memberIDs
|
||||
}
|
||||
|
||||
return page, next, nil
|
||||
}
|
||||
|
||||
var ErrIdempotencyConflict = errors.New("idempotency key reused with different body")
|
||||
|
||||
func (s *Store) CreateMessage(ctx context.Context, chatID, senderID, idemKey, text string, attIDs []string) (model.Message, error) {
|
||||
if attIDs == nil {
|
||||
attIDs = []string{}
|
||||
}
|
||||
if !ValidMessageBody(text, len(attIDs) > 0) {
|
||||
return model.Message{}, ErrValidation
|
||||
}
|
||||
hash := requestHash(text, attIDs)
|
||||
|
||||
tx, err := s.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return model.Message{}, err
|
||||
}
|
||||
defer tx.Rollback(ctx)
|
||||
|
||||
var isMember bool
|
||||
if err := tx.QueryRow(ctx,
|
||||
`SELECT EXISTS(SELECT 1 FROM chat_members WHERE chat_id=$1 AND user_id=$2)`,
|
||||
chatID, senderID).Scan(&isMember); err != nil {
|
||||
return model.Message{}, err
|
||||
}
|
||||
if !isMember {
|
||||
return model.Message{}, ErrChatNotFound
|
||||
}
|
||||
|
||||
if len(attIDs) > 0 {
|
||||
var n int
|
||||
if err := tx.QueryRow(ctx,
|
||||
`SELECT count(*) FROM attachments
|
||||
WHERE chat_id = $1 AND id IN (SELECT unnest($2::text[])::uuid)`,
|
||||
chatID, attIDs).Scan(&n); err != nil {
|
||||
return model.Message{}, err
|
||||
}
|
||||
if n != len(attIDs) {
|
||||
return model.Message{}, ErrAttachmentNotFound
|
||||
}
|
||||
}
|
||||
|
||||
msgID := idgen.GenerateUUIDv4()
|
||||
tag, err := tx.Exec(ctx,
|
||||
`INSERT INTO idempotency_keys (user_id, chat_id, key, request_hash, message_id)
|
||||
VALUES ($1,$2,$3,$4,$5)
|
||||
ON CONFLICT (user_id, chat_id, key) DO NOTHING`,
|
||||
senderID, chatID, idemKey, hash, msgID)
|
||||
if err != nil {
|
||||
return model.Message{}, err
|
||||
}
|
||||
|
||||
if tag.RowsAffected() == 0 {
|
||||
var storedHash string
|
||||
var m model.Message
|
||||
var textBytes []byte
|
||||
|
||||
if err := tx.QueryRow(ctx, `
|
||||
SELECT k.request_hash, m.id, m.chat_id, m.sender_id, m.text, m.created_at
|
||||
FROM idempotency_keys k
|
||||
JOIN messages m ON m.id = k.message_id
|
||||
WHERE k.user_id=$1 AND k.chat_id=$2 AND k.key=$3
|
||||
`, senderID, chatID, idemKey).Scan(
|
||||
&storedHash, &m.ID, &m.ChatID, &m.SenderID, &textBytes, &m.CreatedAt,
|
||||
); err != nil {
|
||||
return model.Message{}, err
|
||||
}
|
||||
|
||||
m.Text = string(textBytes)
|
||||
if storedHash != hash {
|
||||
return model.Message{}, ErrIdempotencyConflict
|
||||
}
|
||||
if m.AttachmentIDs, err = txAttachmentIDs(ctx, tx, m.ID); err != nil {
|
||||
return model.Message{}, err
|
||||
}
|
||||
return m, nil
|
||||
}
|
||||
|
||||
if len(attIDs) > 0 {
|
||||
rows, err := tx.Query(ctx, `SELECT status FROM attachments WHERE id IN
|
||||
(SELECT unnest($1::text[])::uuid) ORDER BY id FOR SHARE`, attIDs)
|
||||
if err != nil {
|
||||
return model.Message{}, err
|
||||
}
|
||||
failed := false
|
||||
for rows.Next() {
|
||||
var state string
|
||||
if err := rows.Scan(&state); err != nil {
|
||||
rows.Close()
|
||||
return model.Message{}, err
|
||||
}
|
||||
failed = failed || state == "failed"
|
||||
}
|
||||
rows.Close()
|
||||
if err := rows.Err(); err != nil {
|
||||
return model.Message{}, err
|
||||
}
|
||||
if failed {
|
||||
return model.Message{}, ErrAttachmentFailed
|
||||
}
|
||||
}
|
||||
|
||||
var m model.Message
|
||||
var textBytes []byte
|
||||
|
||||
err = tx.QueryRow(ctx, `
|
||||
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
|
||||
VALUES ($1,$2,$3,$4, clock_timestamp())
|
||||
RETURNING id, chat_id, sender_id, text, created_at
|
||||
`, msgID, chatID, senderID, []byte(text)).Scan(
|
||||
&m.ID, &m.ChatID, &m.SenderID, &textBytes, &m.CreatedAt,
|
||||
)
|
||||
if err != nil {
|
||||
if isCheckViolation(err) {
|
||||
return model.Message{}, ErrValidation
|
||||
}
|
||||
return model.Message{}, err
|
||||
}
|
||||
m.Text = string(textBytes)
|
||||
for i, id := range attIDs {
|
||||
if _, err := tx.Exec(ctx,
|
||||
`INSERT INTO message_attachments (message_id, attachment_id, position) VALUES ($1,$2,$3)`,
|
||||
m.ID, id, i); err != nil {
|
||||
return model.Message{}, err
|
||||
}
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return model.Message{}, err
|
||||
}
|
||||
m.AttachmentIDs = attIDs
|
||||
return m, nil
|
||||
}
|
||||
|
||||
func (s *Store) ListMessages(ctx context.Context, chatID, userID, cursorStr string, limit int) ([]model.Message, *string, error) {
|
||||
var isMember bool
|
||||
err := s.pool.QueryRow(ctx,
|
||||
`SELECT EXISTS(SELECT 1 FROM chat_members WHERE chat_id = $1 AND user_id = $2)`,
|
||||
chatID, userID,
|
||||
).Scan(&isMember)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
if !isMember {
|
||||
return nil, nil, ErrChatNotFound
|
||||
}
|
||||
|
||||
var after *cursor.Cursor
|
||||
if cursorStr != "" {
|
||||
dc, err := cursor.Decode(cursorStr)
|
||||
if err != nil || dc.Scope != "messages:"+chatID {
|
||||
return nil, nil, ErrValidation
|
||||
}
|
||||
after = &dc
|
||||
}
|
||||
|
||||
query := `
|
||||
SELECT id, chat_id, sender_id, text, created_at
|
||||
FROM messages
|
||||
WHERE chat_id = $1`
|
||||
args := []any{chatID}
|
||||
|
||||
if after != nil {
|
||||
query += ` AND (created_at, id) > ($2, $3)`
|
||||
args = append(args, after.CreatedAt, after.ID)
|
||||
}
|
||||
query += ` ORDER BY created_at ASC, id ASC LIMIT $` + strconv.Itoa(len(args)+1)
|
||||
args = append(args, limit+1)
|
||||
|
||||
rows, err := s.pool.Query(ctx, query, args...)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var page []model.Message
|
||||
for rows.Next() {
|
||||
var m model.Message
|
||||
var textBytes []byte
|
||||
|
||||
if err := rows.Scan(
|
||||
&m.ID, &m.ChatID, &m.SenderID, &textBytes, &m.CreatedAt,
|
||||
); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
m.Text = string(textBytes)
|
||||
page = append(page, m)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
var next *string
|
||||
if len(page) > limit {
|
||||
last := page[limit-1]
|
||||
nc := cursor.Encode(cursor.Cursor{Scope: "messages:" + chatID, CreatedAt: last.CreatedAt, ID: last.ID})
|
||||
next = &nc
|
||||
page = page[:limit]
|
||||
}
|
||||
if err := s.loadAttachmentIDs(ctx, page); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
return page, next, nil
|
||||
}
|
||||
|
||||
func isUniqueViolation(err error) bool {
|
||||
var pgErr *pgconn.PgError
|
||||
return errors.As(err, &pgErr) && pgErr.Code == "23505"
|
||||
}
|
||||
|
||||
func isForeignKeyViolation(err error) bool {
|
||||
var pgErr *pgconn.PgError
|
||||
return errors.As(err, &pgErr) && pgErr.Code == "23503"
|
||||
}
|
||||
|
||||
func isCheckViolation(err error) bool {
|
||||
var pgErr *pgconn.PgError
|
||||
return errors.As(err, &pgErr) && pgErr.Code == "23514"
|
||||
}
|
||||
|
||||
func ValidMessageBody(s string, hasAttachments bool) bool {
|
||||
if !utf8.ValidString(s) || utf8.RuneCountInString(s) > 4000 {
|
||||
return false
|
||||
}
|
||||
|
||||
hasContent := false
|
||||
for _, r := range s {
|
||||
if !unicode.IsSpace(r) {
|
||||
hasContent = true
|
||||
}
|
||||
}
|
||||
return hasAttachments || hasContent
|
||||
}
|
||||
|
||||
func requestHash(text string, ids []string) string {
|
||||
b, _ := json.Marshal(struct {
|
||||
Text string `json:"text"`
|
||||
AttachmentIDs []string `json:"attachment_ids"`
|
||||
}{text, ids})
|
||||
sum := sha256.Sum256(b)
|
||||
return hex.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
func (s *Store) GetUserByUsername(ctx context.Context, username string) (model.User, string, error) {
|
||||
var u model.User
|
||||
var passwordHash string
|
||||
|
||||
err := s.pool.QueryRow(ctx,
|
||||
`SELECT id, username, display_name, created_at, password_hash
|
||||
FROM users WHERE username = $1`,
|
||||
username,
|
||||
).Scan(&u.ID, &u.Username, &u.DisplayName, &u.CreatedAt, &passwordHash)
|
||||
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return model.User{}, "", ErrUsernameNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return model.User{}, "", err
|
||||
}
|
||||
|
||||
return u, passwordHash, nil
|
||||
}
|
||||
Reference in New Issue
Block a user