lab2 fix
This commit is contained in:
@@ -51,6 +51,10 @@ func TestCacheLatencyExperiment(t *testing.T) {
|
||||
var loads atomic.Int32
|
||||
|
||||
source := mocks.NewMockChatSource(t)
|
||||
source.EXPECT().ListVersion(mock.Anything, mock.Anything).RunAndReturn(
|
||||
func(ctx context.Context, userID uuid.UUID) (int64, error) {
|
||||
return realChats.ListVersion(ctx, userID)
|
||||
}).Maybe()
|
||||
source.EXPECT().ListVisible(mock.Anything, mock.Anything, mock.Anything, mock.Anything).
|
||||
RunAndReturn(func(ctx context.Context, callerID uuid.UUID, after *domain.Cursor, limit int) (domain.Page[domain.Chat], error) {
|
||||
loads.Add(1)
|
||||
|
||||
@@ -67,6 +67,10 @@ func TestCachePerformanceExperiment(t *testing.T) {
|
||||
var loads atomic.Int32
|
||||
|
||||
source := mocks.NewMockChatSource(t)
|
||||
source.EXPECT().ListVersion(mock.Anything, mock.Anything).RunAndReturn(
|
||||
func(ctx context.Context, userID uuid.UUID) (int64, error) {
|
||||
return realChats.ListVersion(ctx, userID)
|
||||
}).Maybe()
|
||||
source.EXPECT().ListVisible(mock.Anything, mock.Anything, mock.Anything, mock.Anything).
|
||||
RunAndReturn(func(ctx context.Context, callerID uuid.UUID, after *domain.Cursor, limit int) (domain.Page[domain.Chat], error) {
|
||||
loads.Add(1)
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"slices"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
@@ -44,6 +46,10 @@ func (r *ChatRepository) Create(ctx context.Context, draft domain.ChatDraft) (do
|
||||
return fmt.Errorf("add chat members: %w", mapError(err))
|
||||
}
|
||||
|
||||
if err := queries.BumpChatListVersions(ctx, sortedUnique(draft.MemberIDs)); err != nil {
|
||||
return fmt.Errorf("bump chat list versions: %w", mapError(err))
|
||||
}
|
||||
|
||||
created = mapChat(row.ID, row.Title, row.CreatedAt, draft.MemberIDs)
|
||||
|
||||
return nil
|
||||
@@ -54,6 +60,27 @@ func (r *ChatRepository) Create(ctx context.Context, draft domain.ChatDraft) (do
|
||||
return created, nil
|
||||
}
|
||||
|
||||
func (r *ChatRepository) ListVersion(ctx context.Context, userID uuid.UUID) (int64, error) {
|
||||
ctx, cancel := r.store.timeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
version, err := r.store.queries.GetChatListVersion(ctx, userID)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("get chat list version: %w", mapError(err))
|
||||
}
|
||||
|
||||
return version, nil
|
||||
}
|
||||
|
||||
func sortedUnique(ids []uuid.UUID) []uuid.UUID {
|
||||
sorted := slices.Clone(ids)
|
||||
slices.SortFunc(sorted, func(a, b uuid.UUID) int {
|
||||
return bytes.Compare(a[:], b[:])
|
||||
})
|
||||
|
||||
return slices.Compact(sorted)
|
||||
}
|
||||
|
||||
func (r *ChatRepository) GetVisible(ctx context.Context, chatID, callerID uuid.UUID) (domain.Chat, error) {
|
||||
ctx, cancel := r.store.timeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
@@ -3,6 +3,9 @@
|
||||
package postgres_test
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"slices"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/google/uuid"
|
||||
@@ -49,6 +52,85 @@ func (s *ChatRepositorySuite) TestCreateRejectsDuplicateMembers() {
|
||||
s.Require().ErrorIs(err, domain.ErrConflict)
|
||||
}
|
||||
|
||||
func (s *ChatRepositorySuite) TestCreateBumpsMemberListVersions() {
|
||||
ctx := s.T().Context()
|
||||
alice := s.createUser("alice")
|
||||
bob := s.createUser("bob")
|
||||
carol := s.createUser("carol")
|
||||
|
||||
s.createChat(alice, bob)
|
||||
|
||||
aliceVersion, err := s.store.Chats().ListVersion(ctx, alice.ID)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(int64(1), aliceVersion, "creator version must be bumped")
|
||||
|
||||
bobVersion, err := s.store.Chats().ListVersion(ctx, bob.ID)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(int64(1), bobVersion, "member version must be bumped")
|
||||
|
||||
carolVersion, err := s.store.Chats().ListVersion(ctx, carol.ID)
|
||||
s.Require().NoError(err)
|
||||
s.Zero(carolVersion, "non-member version must stay unchanged")
|
||||
|
||||
s.createChat(alice, carol)
|
||||
|
||||
aliceVersion, err = s.store.Chats().ListVersion(ctx, alice.ID)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(int64(2), aliceVersion, "version must grow monotonically")
|
||||
|
||||
carolVersion, err = s.store.Chats().ListVersion(ctx, carol.ID)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(int64(1), carolVersion)
|
||||
}
|
||||
|
||||
func (s *ChatRepositorySuite) TestConcurrentCreateNoDeadlock() {
|
||||
ctx := s.T().Context()
|
||||
|
||||
users := make([]domain.User, 0, 8)
|
||||
for i := range 8 {
|
||||
users = append(users, s.createUser(fmt.Sprintf("member%d", i)))
|
||||
}
|
||||
|
||||
const workers = 16
|
||||
|
||||
var wg sync.WaitGroup
|
||||
|
||||
errs := make(chan error, workers)
|
||||
|
||||
wg.Add(workers)
|
||||
|
||||
for w := range workers {
|
||||
go func(w int) {
|
||||
defer wg.Done()
|
||||
|
||||
ids := []uuid.UUID{
|
||||
users[w%len(users)].ID,
|
||||
users[(w+1)%len(users)].ID,
|
||||
users[(w+2)%len(users)].ID,
|
||||
}
|
||||
if w%2 == 1 {
|
||||
slices.Reverse(ids)
|
||||
}
|
||||
|
||||
_, err := s.store.Chats().Create(ctx, domain.ChatDraft{
|
||||
Title: fmt.Sprintf("chat-%d", w),
|
||||
MemberIDs: ids,
|
||||
CallerID: ids[0],
|
||||
})
|
||||
if err != nil {
|
||||
errs <- err
|
||||
}
|
||||
}(w)
|
||||
}
|
||||
|
||||
wg.Wait()
|
||||
close(errs)
|
||||
|
||||
for err := range errs {
|
||||
s.Require().NoError(err)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *ChatRepositorySuite) TestCreateStoresAllMembers() {
|
||||
alice := s.createUser("alice")
|
||||
bob := s.createUser("bob")
|
||||
|
||||
@@ -28,6 +28,19 @@ func (q *Queries) AddChatMembers(ctx context.Context, arg AddChatMembersParams)
|
||||
return err
|
||||
}
|
||||
|
||||
const bumpChatListVersions = `-- name: BumpChatListVersions :exec
|
||||
INSERT INTO user_chat_versions (user_id, version)
|
||||
SELECT DISTINCT m, 1
|
||||
FROM unnest($1::uuid[]) AS m
|
||||
ORDER BY m
|
||||
ON CONFLICT (user_id) DO UPDATE SET version = user_chat_versions.version + 1
|
||||
`
|
||||
|
||||
func (q *Queries) BumpChatListVersions(ctx context.Context, userIds []uuid.UUID) error {
|
||||
_, err := q.db.Exec(ctx, bumpChatListVersions, userIds)
|
||||
return err
|
||||
}
|
||||
|
||||
const createChat = `-- name: CreateChat :one
|
||||
INSERT INTO chats (title)
|
||||
VALUES ($1)
|
||||
@@ -81,6 +94,19 @@ func (q *Queries) GetChatForMember(ctx context.Context, arg GetChatForMemberPara
|
||||
return i, err
|
||||
}
|
||||
|
||||
const getChatListVersion = `-- name: GetChatListVersion :one
|
||||
SELECT COALESCE(MAX(version), 0)::bigint AS version
|
||||
FROM user_chat_versions
|
||||
WHERE user_id = $1
|
||||
`
|
||||
|
||||
func (q *Queries) GetChatListVersion(ctx context.Context, userID uuid.UUID) (int64, error) {
|
||||
row := q.db.QueryRow(ctx, getChatListVersion, userID)
|
||||
var version int64
|
||||
err := row.Scan(&version)
|
||||
return version, err
|
||||
}
|
||||
|
||||
const listChatsForMember = `-- name: ListChatsForMember :many
|
||||
SELECT
|
||||
c.id,
|
||||
|
||||
@@ -44,3 +44,8 @@ type User struct {
|
||||
DisplayName string
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
type UserChatVersion struct {
|
||||
UserID uuid.UUID
|
||||
Version int64
|
||||
}
|
||||
|
||||
@@ -54,7 +54,7 @@ func (q *Queries) DeleteSession(ctx context.Context, arg DeleteSessionParams) er
|
||||
}
|
||||
|
||||
const getSessionUser = `-- name: GetSessionUser :one
|
||||
SELECT u.id, u.username, u.display_name, u.created_at, u.password_hash, s.expires_at
|
||||
SELECT u.id, u.username, u.display_name, u.created_at, s.expires_at
|
||||
FROM sessions s
|
||||
JOIN users u ON u.id = s.user_id
|
||||
WHERE s.token_hash = $1
|
||||
@@ -62,12 +62,11 @@ WHERE s.token_hash = $1
|
||||
`
|
||||
|
||||
type GetSessionUserRow struct {
|
||||
ID uuid.UUID
|
||||
Username string
|
||||
DisplayName string
|
||||
CreatedAt time.Time
|
||||
PasswordHash string
|
||||
ExpiresAt time.Time
|
||||
ID uuid.UUID
|
||||
Username string
|
||||
DisplayName string
|
||||
CreatedAt time.Time
|
||||
ExpiresAt time.Time
|
||||
}
|
||||
|
||||
func (q *Queries) GetSessionUser(ctx context.Context, tokenHash []byte) (GetSessionUserRow, error) {
|
||||
@@ -78,7 +77,6 @@ func (q *Queries) GetSessionUser(ctx context.Context, tokenHash []byte) (GetSess
|
||||
&i.Username,
|
||||
&i.DisplayName,
|
||||
&i.CreatedAt,
|
||||
&i.PasswordHash,
|
||||
&i.ExpiresAt,
|
||||
)
|
||||
return i, err
|
||||
|
||||
@@ -44,6 +44,10 @@ CREATE TABLE sessions (
|
||||
created_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE TABLE user_chat_versions (
|
||||
user_id uuid PRIMARY KEY REFERENCES users (id) ON DELETE CASCADE,
|
||||
version bigint NOT NULL DEFAULT 0
|
||||
);
|
||||
|
||||
CREATE INDEX messages_chat_id_created_at_id_idx
|
||||
ON messages (chat_id, created_at, id);
|
||||
@@ -54,6 +58,9 @@ CREATE INDEX chat_members_user_id_chat_id_idx
|
||||
CREATE INDEX chats_created_at_id_idx
|
||||
ON chats (created_at, id);
|
||||
|
||||
CREATE INDEX sessions_user_id_idx
|
||||
ON sessions (user_id);
|
||||
|
||||
-- +goose Down
|
||||
|
||||
DROP TABLE sessions;
|
||||
@@ -61,3 +68,4 @@ DROP TABLE messages;
|
||||
DROP TABLE chat_members;
|
||||
DROP TABLE chats;
|
||||
DROP TABLE users;
|
||||
DROP TABLE user_chat_versions;
|
||||
|
||||
@@ -14,6 +14,18 @@ FROM unnest(sqlc.arg(user_ids)::uuid[]) AS input(id)
|
||||
LEFT JOIN users u ON u.id = input.id
|
||||
WHERE u.id IS NULL;
|
||||
|
||||
-- name: BumpChatListVersions :exec
|
||||
INSERT INTO user_chat_versions (user_id, version)
|
||||
SELECT DISTINCT m, 1
|
||||
FROM unnest(sqlc.arg(user_ids)::uuid[]) AS m
|
||||
ORDER BY m
|
||||
ON CONFLICT (user_id) DO UPDATE SET version = user_chat_versions.version + 1;
|
||||
|
||||
-- name: GetChatListVersion :one
|
||||
SELECT COALESCE(MAX(version), 0)::bigint AS version
|
||||
FROM user_chat_versions
|
||||
WHERE user_id = sqlc.arg(user_id);
|
||||
|
||||
-- name: GetChatForMember :one
|
||||
SELECT
|
||||
c.id,
|
||||
|
||||
@@ -4,7 +4,7 @@ VALUES (sqlc.arg(token_hash), sqlc.arg(user_id), sqlc.arg(expires_at))
|
||||
RETURNING token_hash, user_id, expires_at;
|
||||
|
||||
-- name: GetSessionUser :one
|
||||
SELECT u.id, u.username, u.display_name, u.created_at, u.password_hash, s.expires_at
|
||||
SELECT u.id, u.username, u.display_name, u.created_at, s.expires_at
|
||||
FROM sessions s
|
||||
JOIN users u ON u.id = s.user_id
|
||||
WHERE s.token_hash = sqlc.arg(token_hash)
|
||||
|
||||
@@ -80,14 +80,13 @@ func (r *SessionRepository) Resolve(ctx context.Context, tokenHash []byte) (doma
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Revoke is intentionally idempotent: deleting an already absent session is a no-op.
|
||||
// The HTTP contract for DELETE /auth/sessions/current defines only 204/401, so a
|
||||
// missing session must not surface as an error.
|
||||
func (r *SessionRepository) Revoke(ctx context.Context, userID uuid.UUID, tokenHash []byte) error {
|
||||
ctx, cancel := r.store.timeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
if err := r.store.queries.DeleteSession(ctx, sqlcgen.DeleteSessionParams{TokenHash: tokenHash, UserID: userID}); err != nil {
|
||||
if err := r.store.queries.DeleteSession(
|
||||
ctx, sqlcgen.DeleteSessionParams{TokenHash: tokenHash, UserID: userID},
|
||||
); err != nil {
|
||||
return fmt.Errorf("revoke session: %w", mapError(err))
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user